@sylphx/flow 0.2.12 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -0
- package/LOOP_MODE.md +446 -0
- package/package.json +44 -93
- package/README.md +0 -625
- package/assets/agents/coder.md +0 -32
- package/assets/agents/orchestrator.md +0 -36
- package/assets/agents/reviewer.md +0 -30
- package/assets/agents/writer.md +0 -30
- package/assets/knowledge/data/sql.md +0 -216
- package/assets/knowledge/guides/saas-template.md +0 -85
- package/assets/knowledge/guides/system-prompt.md +0 -344
- package/assets/knowledge/guides/tech-stack.md +0 -92
- package/assets/knowledge/guides/ui-ux.md +0 -44
- package/assets/knowledge/stacks/nextjs-app.md +0 -165
- package/assets/knowledge/stacks/node-api.md +0 -220
- package/assets/knowledge/stacks/react-app.md +0 -232
- package/assets/knowledge/universal/deployment.md +0 -109
- package/assets/knowledge/universal/performance.md +0 -121
- package/assets/knowledge/universal/security.md +0 -79
- package/assets/knowledge/universal/testing.md +0 -111
- package/assets/output-styles/silent.md +0 -23
- package/assets/rules/core.md +0 -144
- package/assets/slash-commands/commit.md +0 -23
- package/assets/slash-commands/context.md +0 -112
- package/assets/slash-commands/explain.md +0 -35
- package/assets/slash-commands/mep.md +0 -63
- package/assets/slash-commands/review.md +0 -39
- package/assets/slash-commands/test.md +0 -30
- package/dist/assets/agents/coder.md +0 -32
- package/dist/assets/agents/orchestrator.md +0 -36
- package/dist/assets/agents/reviewer.md +0 -30
- package/dist/assets/agents/writer.md +0 -30
- package/dist/assets/knowledge/data/sql.md +0 -216
- package/dist/assets/knowledge/guides/saas-template.md +0 -85
- package/dist/assets/knowledge/guides/system-prompt.md +0 -344
- package/dist/assets/knowledge/guides/tech-stack.md +0 -92
- package/dist/assets/knowledge/guides/ui-ux.md +0 -44
- package/dist/assets/knowledge/stacks/nextjs-app.md +0 -165
- package/dist/assets/knowledge/stacks/node-api.md +0 -220
- package/dist/assets/knowledge/stacks/react-app.md +0 -232
- package/dist/assets/knowledge/universal/deployment.md +0 -109
- package/dist/assets/knowledge/universal/performance.md +0 -121
- package/dist/assets/knowledge/universal/security.md +0 -79
- package/dist/assets/knowledge/universal/testing.md +0 -111
- package/dist/assets/output-styles/silent.md +0 -23
- package/dist/assets/rules/core.md +0 -144
- package/dist/assets/slash-commands/commit.md +0 -23
- package/dist/assets/slash-commands/context.md +0 -112
- package/dist/assets/slash-commands/explain.md +0 -35
- package/dist/assets/slash-commands/mep.md +0 -63
- package/dist/assets/slash-commands/review.md +0 -39
- package/dist/assets/slash-commands/test.md +0 -30
- package/dist/chunk-01gv4qey.js +0 -4
- package/dist/chunk-01gv4qey.js.map +0 -11
- package/dist/chunk-3m9whg4q.js +0 -4
- package/dist/chunk-3m9whg4q.js.map +0 -9
- package/dist/chunk-3w6pd43t.js +0 -25
- package/dist/chunk-3w6pd43t.js.map +0 -61
- package/dist/chunk-4nm4ere4.js +0 -4
- package/dist/chunk-4nm4ere4.js.map +0 -11
- package/dist/chunk-4vrj3f8r.js +0 -26
- package/dist/chunk-4vrj3f8r.js.map +0 -75
- package/dist/chunk-5njgv5k5.js +0 -161
- package/dist/chunk-5njgv5k5.js.map +0 -83
- package/dist/chunk-67n29s4q.js +0 -7
- package/dist/chunk-67n29s4q.js.map +0 -10
- package/dist/chunk-86ce45n6.js +0 -3
- package/dist/chunk-86ce45n6.js.map +0 -10
- package/dist/chunk-99pz5wm0.js +0 -75
- package/dist/chunk-99pz5wm0.js.map +0 -12
- package/dist/chunk-cv1nhr27.js +0 -2
- package/dist/chunk-cv1nhr27.js.map +0 -9
- package/dist/chunk-d409xn8f.js +0 -6
- package/dist/chunk-d409xn8f.js.map +0 -11
- package/dist/chunk-g0qpndpd.js +0 -23
- package/dist/chunk-g0qpndpd.js.map +0 -132
- package/dist/chunk-g4baca7p.js +0 -10
- package/dist/chunk-g4baca7p.js.map +0 -23
- package/dist/chunk-gc66xe7z.js +0 -4
- package/dist/chunk-gc66xe7z.js.map +0 -11
- package/dist/chunk-hj6qtsqp.js +0 -15
- package/dist/chunk-hj6qtsqp.js.map +0 -10
- package/dist/chunk-jbd95k1f.js +0 -14
- package/dist/chunk-jbd95k1f.js.map +0 -20
- package/dist/chunk-kn908zkk.js +0 -4
- package/dist/chunk-kn908zkk.js.map +0 -10
- package/dist/chunk-mw13a082.js +0 -4
- package/dist/chunk-mw13a082.js.map +0 -10
- package/dist/chunk-nke51f3c.js +0 -4
- package/dist/chunk-nke51f3c.js.map +0 -10
- package/dist/chunk-ns5atzyz.js +0 -3
- package/dist/chunk-ns5atzyz.js.map +0 -10
- package/dist/chunk-pp4r3hp4.js +0 -105
- package/dist/chunk-pp4r3hp4.js.map +0 -27
- package/dist/chunk-q4nh3vst.js +0 -54
- package/dist/chunk-q4nh3vst.js.map +0 -53
- package/dist/chunk-q5gqgs0p.js +0 -4
- package/dist/chunk-q5gqgs0p.js.map +0 -10
- package/dist/chunk-s9bsh0gp.js +0 -4
- package/dist/chunk-s9bsh0gp.js.map +0 -10
- package/dist/chunk-ss51dw5h.js +0 -27
- package/dist/chunk-ss51dw5h.js.map +0 -23
- package/dist/chunk-waemzsf4.js +0 -4
- package/dist/chunk-waemzsf4.js.map +0 -10
- package/dist/chunk-xs370t8p.js +0 -119
- package/dist/chunk-xs370t8p.js.map +0 -26
- package/dist/chunk-xtrn4wn0.js +0 -3
- package/dist/chunk-xtrn4wn0.js.map +0 -10
- package/dist/chunk-xvfz960r.js +0 -4
- package/dist/chunk-xvfz960r.js.map +0 -12
- package/dist/chunk-xytc0fks.js +0 -27
- package/dist/chunk-xytc0fks.js.map +0 -14
- package/dist/chunk-yxv7hqse.js +0 -23
- package/dist/chunk-yxv7hqse.js.map +0 -11
- package/dist/chunk-zv5y8yfq.js +0 -19
- package/dist/chunk-zv5y8yfq.js.map +0 -11
- package/dist/index.js +0 -854
- package/dist/index.js.map +0 -903
- package/drizzle/0000_wooden_lady_bullseye.sql +0 -52
- package/drizzle/0001_material_pyro.sql +0 -85
- package/drizzle/0002_lyrical_random.sql +0 -2
- package/drizzle/0003_romantic_lockjaw.sql +0 -4
- package/drizzle/0004_blushing_meteorite.sql +0 -6
- package/drizzle/meta/0000_snapshot.json +0 -310
- package/drizzle/meta/0001_snapshot.json +0 -906
- package/drizzle/meta/0002_snapshot.json +0 -920
- package/drizzle/meta/0003_snapshot.json +0 -920
- package/drizzle/meta/0004_snapshot.json +0 -921
- package/drizzle/meta/_journal.json +0 -41
package/dist/chunk-cv1nhr27.js
DELETED
package/dist/chunk-d409xn8f.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{Q as _}from"./chunk-q4nh3vst.js";import{Tb as Z}from"./chunk-3m9whg4q.js";var W=Z(_(),1);import{readFile as $,readdir as z,access as C}from"node:fs/promises";import{join as U,parse as G,relative as B}from"node:path";import{homedir as D}from"node:os";async function v(k,q=!1,x){try{let H=await $(k,"utf-8"),{data:N,content:K}=W.default(H);if(!N.name||typeof N.name!=="string")return console.error(`Rule file ${k} missing required 'name' field`),null;let O={name:N.name,description:N.description||"",enabled:N.enabled!==void 0?Boolean(N.enabled):!0};return{id:x||G(k).name,metadata:O,content:K.trim(),isBuiltin:q,filePath:k}}catch(H){return console.error(`Failed to load rule from ${k}:`,H),null}}async function V(k,q=!1){try{let H=(await z(k,{recursive:!0,withFileTypes:!0})).filter((K)=>K.isFile()&&K.name.endsWith(".md")).map((K)=>{let O=U(K.parentPath||K.path,K.name),T=B(k,O).replace(/\.md$/,"");return{fullPath:O,ruleId:T}});return(await Promise.all(H.map(({fullPath:K,ruleId:O})=>v(K,q,O)))).filter((K)=>K!==null)}catch(x){return[]}}async function F(){let k=new URL(".",import.meta.url).pathname,q=U(k,"..","assets","rules"),x=U(k,"..","..","assets","rules");try{return await C(q),q}catch{return x}}function M(k){let q=U(D(),".sylphx-flow","rules"),x=U(k,".sylphx-flow","rules");return[q,x]}async function X(k){let q=await F(),[x,H]=M(k),[N,K,O]=await Promise.all([V(q,!0),V(x,!1),V(H,!1)]),T=new Map;for(let Q of N)T.set(Q.id,Q);for(let Q of K)T.set(Q.id,Q);for(let Q of O)T.set(Q.id,Q);return Array.from(T.values())}var J=null,L=null;function b(k){L=k}async function y(k){let q=await X(k),x=new Map;for(let H of q)x.set(H.id,H);if(J={rules:x,cwd:k},L){let H=L();if(H.getState){if((H.getState().enabledRuleIds||[]).length===0){let K=q.filter((O)=>O.metadata.enabled!==!1).map((O)=>O.id);if(K.length>0)H.getState().setEnabledRuleIds(K)}}}}function R(){if(!J)return[];return Array.from(J.rules.values())}function I(k){if(!J)return null;return J.rules.get(k)||null}function Y(){if(L){let k=L();if(k.getState)return k.getState().enabledRuleIds||[]}return[]}function w(){if(!J)return[];return Y().map((q)=>J.rules.get(q)).filter((q)=>q!==null)}function g(k){if(!J||!J.rules.has(k))return!1;if(L){let q=L();if(q.getState){let x=q.getState().enabledRuleIds||[];if(x.includes(k))q.getState().setEnabledRuleIds(x.filter((H)=>H!==k));else q.getState().setEnabledRuleIds([...x,k]);return!0}}return!1}function f(k){if(!J||!J.rules.has(k))return!1;if(L){let q=L();if(q.getState){let x=q.getState().enabledRuleIds||[];if(!x.includes(k))q.getState().setEnabledRuleIds([...x,k]);return!0}}return!1}function P(k){if(!J||!J.rules.has(k))return!1;if(L){let q=L();if(q.getState){let x=q.getState().enabledRuleIds||[];return q.getState().setEnabledRuleIds(x.filter((H)=>H!==k)),!0}}return!1}async function c(){if(!J)return;let k=J.cwd,q=Y();if(await y(k),J&&L){let x=L();if(x.getState){let H=q.filter((N)=>J.rules.has(N));x.getState().setEnabledRuleIds(H)}}}function h(k){if(!J)return!1;let q=k.filter((x)=>J.rules.has(x));if(L){let x=L();if(x.getState)return x.getState().setEnabledRuleIds(q),!0}return!1}function p(){let k=w();if(k.length===0)return"";return k.map((q)=>q.content).join(`
|
|
2
|
-
|
|
3
|
-
`)}export{g as toggleRule,b as setRuleAppStoreGetter,h as setEnabledRules,c as reloadRules,y as initializeRuleManager,I as getRuleById,p as getEnabledRulesContent,w as getEnabledRules,Y as getEnabledRuleIds,R as getAllRules,f as enableRule,P as disableRule};
|
|
4
|
-
export{b as F,y as G,R as H,g as I,p as J};
|
|
5
|
-
|
|
6
|
-
//# debugId=CE00DC8B22216C6A64756E2164756E21
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/core/rule-loader.ts", "../src/core/rule-manager.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * Rule Loader\n * Loads rule definitions from markdown files with front matter\n */\n\nimport { readFile, readdir, access } from 'node:fs/promises';\nimport { join, parse, relative } from 'node:path';\nimport { homedir } from 'node:os';\nimport matter from 'gray-matter';\nimport type { Rule, RuleMetadata } from '../types/rule.types.js';\n\n/**\n * Load a single rule from a markdown file\n */\nexport async function loadRuleFromFile(\n filePath: string,\n isBuiltin: boolean = false,\n ruleId?: string\n): Promise<Rule | null> {\n try {\n const fileContent = await readFile(filePath, 'utf-8');\n const { data, content } = matter(fileContent);\n\n // Validate front matter\n if (!data.name || typeof data.name !== 'string') {\n console.error(`Rule file ${filePath} missing required 'name' field`);\n return null;\n }\n\n const metadata: RuleMetadata = {\n name: data.name,\n description: data.description || '',\n enabled: data.enabled !== undefined ? Boolean(data.enabled) : true,\n };\n\n // Get rule ID from parameter or filename\n const id = ruleId || parse(filePath).name;\n\n return {\n id,\n metadata,\n content: content.trim(),\n isBuiltin,\n filePath,\n };\n } catch (error) {\n console.error(`Failed to load rule from ${filePath}:`, error);\n return null;\n }\n}\n\n/**\n * Load all rules from a directory (recursively)\n */\nexport async function loadRulesFromDirectory(dirPath: string, isBuiltin: boolean = false): Promise<Rule[]> {\n try {\n // Read directory recursively to support subdirectories\n const files = await readdir(dirPath, { recursive: true, withFileTypes: true });\n\n // Filter for .md files and calculate rule IDs from relative paths\n const ruleFiles = files\n .filter((f) => f.isFile() && f.name.endsWith('.md'))\n .map((f) => {\n const fullPath = join(f.parentPath || f.path, f.name);\n // Calculate relative path from dirPath and remove .md extension\n const relativePath = relative(dirPath, fullPath).replace(/\\.md$/, '');\n return { fullPath, ruleId: relativePath };\n });\n\n const rules = await Promise.all(\n ruleFiles.map(({ fullPath, ruleId }) => loadRuleFromFile(fullPath, isBuiltin, ruleId))\n );\n\n return rules.filter((rule): rule is Rule => rule !== null);\n } catch (error) {\n // Directory doesn't exist or can't be read\n return [];\n }\n}\n\n/**\n * Get system rules path (bundled with the app)\n */\nexport async function getSystemRulesPath(): Promise<string> {\n // Get the directory of the current module\n const currentDir = new URL('.', import.meta.url).pathname;\n\n // In production (dist), assets are at dist/assets/rules\n // In development (src), go up to project root: src/core -> project root\n const distPath = join(currentDir, '..', 'assets', 'rules');\n const devPath = join(currentDir, '..', '..', 'assets', 'rules');\n\n // Check which one exists (try dist first, then dev)\n try {\n await access(distPath);\n return distPath;\n } catch {\n return devPath;\n }\n}\n\n/**\n * Get all rule search paths\n */\nexport function getRuleSearchPaths(cwd: string): string[] {\n const globalPath = join(homedir(), '.sylphx-flow', 'rules');\n const projectPath = join(cwd, '.sylphx-flow', 'rules');\n\n return [globalPath, projectPath];\n}\n\n/**\n * Load all available rules from all sources\n */\nexport async function loadAllRules(cwd: string): Promise<Rule[]> {\n const systemPath = await getSystemRulesPath();\n const [globalPath, projectPath] = getRuleSearchPaths(cwd);\n\n const [systemRules, globalRules, projectRules] = await Promise.all([\n loadRulesFromDirectory(systemPath, true), // System rules are marked as builtin\n loadRulesFromDirectory(globalPath, false),\n loadRulesFromDirectory(projectPath, false),\n ]);\n\n // Priority: system < global < project\n // Use Map to deduplicate by ID (later entries override earlier ones)\n const ruleMap = new Map<string, Rule>();\n\n // Add system rules first (lowest priority)\n for (const rule of systemRules) {\n ruleMap.set(rule.id, rule);\n }\n\n // Add global rules (override system)\n for (const rule of globalRules) {\n ruleMap.set(rule.id, rule);\n }\n\n // Add project rules (override globals and system)\n for (const rule of projectRules) {\n ruleMap.set(rule.id, rule);\n }\n\n return Array.from(ruleMap.values());\n}\n",
|
|
6
|
-
"/**\n * Rule Manager\n * Manages rule state and operations\n */\n\nimport type { Rule } from '../types/rule.types.js';\nimport { loadAllRules } from './rule-loader.js';\n\n/**\n * Rule manager state\n */\ninterface RuleManagerState {\n rules: Map<string, Rule>;\n cwd: string;\n}\n\nlet state: RuleManagerState | null = null;\n\n/**\n * Get the app store (lazy import to avoid circular dependencies)\n */\nlet getAppStore: (() => any) | null = null;\n\n/**\n * Set the app store getter (called during initialization)\n */\nexport function setRuleAppStoreGetter(getter: () => any): void {\n getAppStore = getter;\n}\n\n/**\n * Initialize rule manager\n */\nexport async function initializeRuleManager(cwd: string): Promise<void> {\n const allRules = await loadAllRules(cwd);\n\n const ruleMap = new Map<string, Rule>();\n for (const rule of allRules) {\n ruleMap.set(rule.id, rule);\n }\n\n state = {\n rules: ruleMap,\n cwd,\n };\n\n // Initialize store with default enabled rules\n if (getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n const currentEnabledRules = store.getState().enabledRuleIds || [];\n\n // If no rules are enabled yet, enable all rules that have enabled: true in metadata\n if (currentEnabledRules.length === 0) {\n const defaultEnabledRules = allRules\n .filter((rule) => rule.metadata.enabled !== false)\n .map((rule) => rule.id);\n\n if (defaultEnabledRules.length > 0) {\n store.getState().setEnabledRuleIds(defaultEnabledRules);\n }\n }\n }\n }\n}\n\n/**\n * Get all available rules\n */\nexport function getAllRules(): Rule[] {\n if (!state) {\n return [];\n }\n return Array.from(state.rules.values());\n}\n\n/**\n * Get rule by ID\n */\nexport function getRuleById(id: string): Rule | null {\n if (!state) {\n return null;\n }\n return state.rules.get(id) || null;\n}\n\n/**\n * Get enabled rule IDs from store\n */\nexport function getEnabledRuleIds(): string[] {\n if (getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n return store.getState().enabledRuleIds || [];\n }\n }\n return [];\n}\n\n/**\n * Get enabled rules\n */\nexport function getEnabledRules(): Rule[] {\n if (!state) {\n return [];\n }\n\n const enabledIds = getEnabledRuleIds();\n return enabledIds\n .map((id) => state!.rules.get(id))\n .filter((rule): rule is Rule => rule !== null);\n}\n\n/**\n * Toggle a rule on/off\n */\nexport function toggleRule(ruleId: string): boolean {\n if (!state || !state.rules.has(ruleId)) {\n return false;\n }\n\n if (getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n const currentEnabled = store.getState().enabledRuleIds || [];\n\n if (currentEnabled.includes(ruleId)) {\n // Disable: remove from list\n store.getState().setEnabledRuleIds(currentEnabled.filter((id) => id !== ruleId));\n } else {\n // Enable: add to list\n store.getState().setEnabledRuleIds([...currentEnabled, ruleId]);\n }\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Enable a rule\n */\nexport function enableRule(ruleId: string): boolean {\n if (!state || !state.rules.has(ruleId)) {\n return false;\n }\n\n if (getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n const currentEnabled = store.getState().enabledRuleIds || [];\n\n if (!currentEnabled.includes(ruleId)) {\n store.getState().setEnabledRuleIds([...currentEnabled, ruleId]);\n }\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Disable a rule\n */\nexport function disableRule(ruleId: string): boolean {\n if (!state || !state.rules.has(ruleId)) {\n return false;\n }\n\n if (getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n const currentEnabled = store.getState().enabledRuleIds || [];\n store.getState().setEnabledRuleIds(currentEnabled.filter((id) => id !== ruleId));\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Reload rules from disk\n */\nexport async function reloadRules(): Promise<void> {\n if (!state) {\n return;\n }\n\n const cwd = state.cwd;\n const currentEnabled = getEnabledRuleIds();\n\n await initializeRuleManager(cwd);\n\n // Keep only enabled rules that still exist\n if (state && getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n const validEnabled = currentEnabled.filter((id) => state!.rules.has(id));\n store.getState().setEnabledRuleIds(validEnabled);\n }\n }\n}\n\n/**\n * Set enabled rules (replaces current enabled rules)\n */\nexport function setEnabledRules(ruleIds: string[]): boolean {\n if (!state) {\n return false;\n }\n\n // Validate all rule IDs exist\n const validRuleIds = ruleIds.filter((id) => state!.rules.has(id));\n\n if (getAppStore) {\n const store = getAppStore();\n if (store.getState) {\n store.getState().setEnabledRuleIds(validRuleIds);\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Get combined content of all enabled rules\n */\nexport function getEnabledRulesContent(): string {\n const enabledRules = getEnabledRules();\n\n if (enabledRules.length === 0) {\n return '';\n }\n\n return enabledRules.map((rule) => rule.content).join('\\n\\n');\n}\n"
|
|
7
|
-
],
|
|
8
|
-
"mappings": "uFAQA,SAHA,mBAAS,aAAU,YAAS,yBAC5B,eAAS,WAAM,cAAO,kBACtB,kBAAS,gBAOT,eAAsB,CAAgB,CACpC,EACA,EAAqB,GACrB,EACsB,CACtB,GAAI,CACF,IAAM,EAAc,MAAM,EAAS,EAAU,OAAO,GAC5C,OAAM,WAAY,UAAO,CAAW,EAG5C,GAAI,CAAC,EAAK,MAAQ,OAAO,EAAK,OAAS,SAErC,OADA,QAAQ,MAAM,aAAa,iCAAwC,EAC5D,KAGT,IAAM,EAAyB,CAC7B,KAAM,EAAK,KACX,YAAa,EAAK,aAAe,GACjC,QAAS,EAAK,UAAY,OAAY,QAAQ,EAAK,OAAO,EAAI,EAChE,EAKA,MAAO,CACL,GAHS,GAAU,EAAM,CAAQ,EAAE,KAInC,WACA,QAAS,EAAQ,KAAK,EACtB,YACA,UACF,EACA,MAAO,EAAO,CAEd,OADA,QAAQ,MAAM,4BAA4B,KAAa,CAAK,EACrD,MAOX,eAAsB,CAAsB,CAAC,EAAiB,EAAqB,GAAwB,CACzG,GAAI,CAKF,IAAM,GAHQ,MAAM,EAAQ,EAAS,CAAE,UAAW,GAAM,cAAe,EAAK,CAAC,GAI1E,OAAO,CAAC,IAAM,EAAE,OAAO,GAAK,EAAE,KAAK,SAAS,KAAK,CAAC,EAClD,IAAI,CAAC,IAAM,CACV,IAAM,EAAW,EAAK,EAAE,YAAc,EAAE,KAAM,EAAE,IAAI,EAE9C,EAAe,EAAS,EAAS,CAAQ,EAAE,QAAQ,QAAS,EAAE,EACpE,MAAO,CAAE,WAAU,OAAQ,CAAa,EACzC,EAMH,OAJc,MAAM,QAAQ,IAC1B,EAAU,IAAI,EAAG,WAAU,YAAa,EAAiB,EAAU,EAAW,CAAM,CAAC,CACvF,GAEa,OAAO,CAAC,IAAuB,IAAS,IAAI,EACzD,MAAO,EAAO,CAEd,MAAO,CAAC,GAOZ,eAAsB,CAAkB,EAAoB,CAE1D,IAAM,EAAa,IAAI,IAAI,IAAK,YAAY,GAAG,EAAE,SAI3C,EAAW,EAAK,EAAY,KAAM,SAAU,OAAO,EACnD,EAAU,EAAK,EAAY,KAAM,KAAM,SAAU,OAAO,EAG9D,GAAI,CAEF,OADA,MAAM,EAAO,CAAQ,EACd,EACP,KAAM,CACN,OAAO,GAOJ,SAAS,CAAkB,CAAC,EAAuB,CACxD,IAAM,EAAa,EAAK,EAAQ,EAAG,eAAgB,OAAO,EACpD,EAAc,EAAK,EAAK,eAAgB,OAAO,EAErD,MAAO,CAAC,EAAY,CAAW,EAMjC,eAAsB,CAAY,CAAC,EAA8B,CAC/D,IAAM,EAAa,MAAM,EAAmB,GACrC,EAAY,GAAe,EAAmB,CAAG,GAEjD,EAAa,EAAa,GAAgB,MAAM,QAAQ,IAAI,CACjE,EAAuB,EAAY,EAAI,EACvC,EAAuB,EAAY,EAAK,EACxC,EAAuB,EAAa,EAAK,CAC3C,CAAC,EAIK,EAAU,IAAI,IAGpB,QAAW,KAAQ,EACjB,EAAQ,IAAI,EAAK,GAAI,CAAI,EAI3B,QAAW,KAAQ,EACjB,EAAQ,IAAI,EAAK,GAAI,CAAI,EAI3B,QAAW,KAAQ,EACjB,EAAQ,IAAI,EAAK,GAAI,CAAI,EAG3B,OAAO,MAAM,KAAK,EAAQ,OAAO,CAAC,EC/HpC,IAAI,EAAiC,KAKjC,EAAkC,KAK/B,SAAS,CAAqB,CAAC,EAAyB,CAC7D,EAAc,EAMhB,eAAsB,CAAqB,CAAC,EAA4B,CACtE,IAAM,EAAW,MAAM,EAAa,CAAG,EAEjC,EAAU,IAAI,IACpB,QAAW,KAAQ,EACjB,EAAQ,IAAI,EAAK,GAAI,CAAI,EAS3B,GANA,EAAQ,CACN,MAAO,EACP,KACF,EAGI,EAAa,CACf,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,UAIR,IAH4B,EAAM,SAAS,EAAE,gBAAkB,CAAC,GAGxC,SAAW,EAAG,CACpC,IAAM,EAAsB,EACzB,OAAO,CAAC,IAAS,EAAK,SAAS,UAAY,EAAK,EAChD,IAAI,CAAC,IAAS,EAAK,EAAE,EAExB,GAAI,EAAoB,OAAS,EAC/B,EAAM,SAAS,EAAE,kBAAkB,CAAmB,KAUzD,SAAS,CAAW,EAAW,CACpC,GAAI,CAAC,EACH,MAAO,CAAC,EAEV,OAAO,MAAM,KAAK,EAAM,MAAM,OAAO,CAAC,EAMjC,SAAS,CAAW,CAAC,EAAyB,CACnD,GAAI,CAAC,EACH,OAAO,KAET,OAAO,EAAM,MAAM,IAAI,CAAE,GAAK,KAMzB,SAAS,CAAiB,EAAa,CAC5C,GAAI,EAAa,CACf,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,SACR,OAAO,EAAM,SAAS,EAAE,gBAAkB,CAAC,EAG/C,MAAO,CAAC,EAMH,SAAS,CAAe,EAAW,CACxC,GAAI,CAAC,EACH,MAAO,CAAC,EAIV,OADmB,EAAkB,EAElC,IAAI,CAAC,IAAO,EAAO,MAAM,IAAI,CAAE,CAAC,EAChC,OAAO,CAAC,IAAuB,IAAS,IAAI,EAM1C,SAAS,CAAU,CAAC,EAAyB,CAClD,GAAI,CAAC,GAAS,CAAC,EAAM,MAAM,IAAI,CAAM,EACnC,MAAO,GAGT,GAAI,EAAa,CACf,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,SAAU,CAClB,IAAM,EAAiB,EAAM,SAAS,EAAE,gBAAkB,CAAC,EAE3D,GAAI,EAAe,SAAS,CAAM,EAEhC,EAAM,SAAS,EAAE,kBAAkB,EAAe,OAAO,CAAC,IAAO,IAAO,CAAM,CAAC,EAG/E,OAAM,SAAS,EAAE,kBAAkB,CAAC,GAAG,EAAgB,CAAM,CAAC,EAEhE,MAAO,IAIX,MAAO,GAMF,SAAS,CAAU,CAAC,EAAyB,CAClD,GAAI,CAAC,GAAS,CAAC,EAAM,MAAM,IAAI,CAAM,EACnC,MAAO,GAGT,GAAI,EAAa,CACf,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,SAAU,CAClB,IAAM,EAAiB,EAAM,SAAS,EAAE,gBAAkB,CAAC,EAE3D,GAAI,CAAC,EAAe,SAAS,CAAM,EACjC,EAAM,SAAS,EAAE,kBAAkB,CAAC,GAAG,EAAgB,CAAM,CAAC,EAEhE,MAAO,IAIX,MAAO,GAMF,SAAS,CAAW,CAAC,EAAyB,CACnD,GAAI,CAAC,GAAS,CAAC,EAAM,MAAM,IAAI,CAAM,EACnC,MAAO,GAGT,GAAI,EAAa,CACf,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,SAAU,CAClB,IAAM,EAAiB,EAAM,SAAS,EAAE,gBAAkB,CAAC,EAE3D,OADA,EAAM,SAAS,EAAE,kBAAkB,EAAe,OAAO,CAAC,IAAO,IAAO,CAAM,CAAC,EACxE,IAIX,MAAO,GAMT,eAAsB,CAAW,EAAkB,CACjD,GAAI,CAAC,EACH,OAGF,IAAM,EAAM,EAAM,IACZ,EAAiB,EAAkB,EAKzC,GAHA,MAAM,EAAsB,CAAG,EAG3B,GAAS,EAAa,CACxB,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,SAAU,CAClB,IAAM,EAAe,EAAe,OAAO,CAAC,IAAO,EAAO,MAAM,IAAI,CAAE,CAAC,EACvE,EAAM,SAAS,EAAE,kBAAkB,CAAY,IAQ9C,SAAS,CAAe,CAAC,EAA4B,CAC1D,GAAI,CAAC,EACH,MAAO,GAIT,IAAM,EAAe,EAAQ,OAAO,CAAC,IAAO,EAAO,MAAM,IAAI,CAAE,CAAC,EAEhE,GAAI,EAAa,CACf,IAAM,EAAQ,EAAY,EAC1B,GAAI,EAAM,SAER,OADA,EAAM,SAAS,EAAE,kBAAkB,CAAY,EACxC,GAIX,MAAO,GAMF,SAAS,CAAsB,EAAW,CAC/C,IAAM,EAAe,EAAgB,EAErC,GAAI,EAAa,SAAW,EAC1B,MAAO,GAGT,OAAO,EAAa,IAAI,CAAC,IAAS,EAAK,OAAO,EAAE,KAAK;AAAA;AAAA,CAAM",
|
|
9
|
-
"debugId": "CE00DC8B22216C6A64756E2164756E21",
|
|
10
|
-
"names": []
|
|
11
|
-
}
|
package/dist/chunk-g0qpndpd.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{ra as n$}from"./chunk-01gv4qey.js";import{ya as X0}from"./chunk-g4baca7p.js";import{Tb as m6,Ub as y2,Wb as T2}from"./chunk-3m9whg4q.js";var _X=y2((z2)=>{var hZ=z2&&z2.__createBinding||(Object.create?function(X,$,Z,Y){if(Y===void 0)Y=Z;var G=Object.getOwnPropertyDescriptor($,Z);if(!G||("get"in G?!$.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return $[Z]}};Object.defineProperty(X,Y,G)}:function(X,$,Z,Y){if(Y===void 0)Y=Z;X[Y]=$[Z]}),fZ=z2&&z2.__setModuleDefault||(Object.create?function(X,$){Object.defineProperty(X,"default",{enumerable:!0,value:$})}:function(X,$){X.default=$}),JX=z2&&z2.__importStar||function(X){if(X&&X.__esModule)return X;var $={};if(X!=null){for(var Z in X)if(Z!=="default"&&Object.prototype.hasOwnProperty.call(X,Z))hZ($,X,Z)}return fZ($,X),$};Object.defineProperty(z2,"__esModule",{value:!0});z2.load=z2.currentTarget=void 0;var qZ=JX(T2("path")),yZ=JX(T2("fs"));function SZ(){let X=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}X="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}X="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}X="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return pZ()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}X="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";X="FreeBSD";break}if(X)throw Error(`Neon: unsupported ${X} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}z2.currentTarget=SZ;function pZ(){let X=process.report?.getReport();if(typeof X!=="object"||!X||!("header"in X))return!1;let $=X.header;return typeof $==="object"&&!!$&&"glibcVersionRuntime"in $}function bZ(X){let $=qZ.join(X,"index.node");return yZ.existsSync($)?T2($):null}z2.load=bZ});var HX=y2((ZW,zX)=>{var WX=()=>process.platform==="linux",g6=null,gZ=()=>{if(!g6)g6=WX()&&process.report?process.report.getReport():{};return g6};zX.exports={isLinux:WX,getReport:gZ}});var AX=y2((YW,OX)=>{var DX=T2("fs"),dZ=(X)=>DX.readFileSync(X,"utf-8"),mZ=(X)=>new Promise(($,Z)=>{DX.readFile(X,"utf-8",(Y,G)=>{if(Y)Z(Y);else $(G)})});OX.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:dZ,readFile:mZ}});var BX=y2((GW,QX)=>{var VX=T2("child_process"),{isLinux:E1,getReport:FX}=HX(),{LDD_PATH:S0,readFile:KX,readFileSync:EX}=AX(),M2,N2,S2="",RX=()=>{if(!S2)return new Promise((X)=>{VX.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",($,Z)=>{S2=$?" ":Z,X(S2)})});return S2},MX=()=>{if(!S2)try{S2=VX.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(X){S2=" "}return S2},j2="glibc",NX=/GLIBC\s(\d+\.\d+)/,t2="musl",cZ=j2.toUpperCase(),uZ=t2.toLowerCase(),nZ=(X)=>X.includes("libc.musl-")||X.includes("ld-musl-"),IX=()=>{let X=FX();if(X.header&&X.header.glibcVersionRuntime)return j2;if(Array.isArray(X.sharedObjects)){if(X.sharedObjects.some(nZ))return t2}return null},xX=(X)=>{let[$,Z]=X.split(/[\r\n]+/);if($&&$.includes(j2))return j2;if(Z&&Z.includes(t2))return t2;return null},wX=(X)=>{if(X.includes(uZ))return t2;if(X.includes(cZ))return j2;return null},oZ=async()=>{if(M2!==void 0)return M2;M2=null;try{let X=await KX(S0);M2=wX(X)}catch(X){}return M2},iZ=()=>{if(M2!==void 0)return M2;M2=null;try{let X=EX(S0);M2=wX(X)}catch(X){}return M2},PX=async()=>{let X=null;if(E1()){if(X=await oZ(),!X)X=IX();if(!X){let $=await RX();X=xX($)}}return X},kX=()=>{let X=null;if(E1()){if(X=iZ(),!X)X=IX();if(!X){let $=MX();X=xX($)}}return X},rZ=async()=>E1()&&await PX()!==j2,tZ=()=>E1()&&kX()!==j2,lZ=async()=>{if(N2!==void 0)return N2;N2=null;try{let $=(await KX(S0)).match(NX);if($)N2=$[1]}catch(X){}return N2},sZ=()=>{if(N2!==void 0)return N2;N2=null;try{let $=EX(S0).match(NX);if($)N2=$[1]}catch(X){}return N2},TX=()=>{let X=FX();if(X.header&&X.header.glibcVersionRuntime)return X.header.glibcVersionRuntime;return null},UX=(X)=>X.trim().split(/\s+/)[1],jX=(X)=>{let[$,Z,Y]=X.split(/[\r\n]+/);if($&&$.includes(j2))return UX($);if(Z&&Y&&Z.includes(t2))return UX(Y);return null},aZ=async()=>{let X=null;if(E1()){if(X=await lZ(),!X)X=TX();if(!X){let $=await RX();X=jX($)}}return X},eZ=()=>{let X=null;if(E1()){if(X=sZ(),!X)X=TX();if(!X){let $=MX();X=jX($)}}return X};QX.exports={GLIBC:j2,MUSL:t2,family:PX,familySync:kX,isNonGlibcLinux:rZ,isNonGlibcLinuxSync:tZ,version:aZ,versionSync:eZ}});var vX=y2((JW,LX)=>{var XY={ALLOW:0,DENY:1};LX.exports=XY});var hX=y2((_W,CX)=>{var d6={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function l2(X,$,Z){if(new.target!==l2)return new l2(X,$);if(typeof $!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,X),d6.value=""+X,Object.defineProperty(this,"message",d6),Error.captureStackTrace(this,l2),this.code=$,this.rawCode=Z}Object.setPrototypeOf(l2,Error);Object.setPrototypeOf(l2.prototype,Error.prototype);Object.defineProperty(l2.prototype,"name",d6);CX.exports=l2});var dX=y2((WW,p0)=>{var __dirname="/Users/kyle/rules/node_modules/libsql",{load:$Y,currentTarget:ZY}=_X(),{familySync:fX,GLIBC:YY,MUSL:GY}=BX();function JY(){if(process.env.LIBSQL_JS_DEV)return $Y(__dirname);let X=ZY();if(fX()==YY)switch(X){case"linux-x64-musl":X="linux-x64-gnu";break;case"linux-arm64-musl":X="linux-arm64-gnu";break}if(X==="linux-arm-gnueabihf"&&fX()==GY)X="linux-arm-musleabihf";return T2(`@libsql/${X}`)}var{databaseOpen:_Y,databaseOpenWithSync:WY,databaseInTransaction:zY,databaseInterrupt:HY,databaseClose:DY,databaseSyncSync:OY,databaseSyncUntilSync:AY,databaseExecSync:UY,databasePrepareSync:VY,databaseDefaultSafeIntegers:FY,databaseAuthorizer:KY,databaseLoadExtension:EY,databaseMaxWriteReplicationIndex:RY,statementRaw:MY,statementIsReader:NY,statementGet:qX,statementRun:yX,statementInterrupt:IY,statementRowsSync:SX,statementColumns:xY,statementSafeIntegers:wY,rowsNext:PY}=JY(),kY=vX(),pX=hX();function R1(X){if(X.libsqlError)return new pX(X.message,X.code,X.rawCode);return X}class bX{constructor(X,$){let Z=$?.encryptionCipher??"aes256cbc";if($&&$.syncUrl){var Y="";if($.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),Y=$.syncAuth;else if($.authToken)Y=$.authToken;let J=$?.encryptionKey??"",_=$?.syncPeriod??0,W=$?.readYourWrites??!0,H=$?.offline??!1,D=$?.remoteEncryptionKey??"";this.db=WY(X,$.syncUrl,Y,Z,J,_,W,H,D)}else{let J=$?.authToken??"",_=$?.encryptionKey??"",W=$?.timeout??0,H=$?.remoteEncryptionKey??"";this.db=_Y(X,J,Z,_,W,H)}this.memory=X===":memory:",this.readonly=!1,this.name="",this.open=!0;let G=this.db;Object.defineProperties(this,{inTransaction:{get(){return zY(G)}}})}sync(){return OY.call(this.db)}syncUntil(X){return AY.call(this.db,X)}prepare(X){try{let $=VY.call(this.db,X);return new gX($)}catch($){throw R1($)}}transaction(X){if(typeof X!=="function")throw TypeError("Expected first argument to be a function");let $=this,Z=(G)=>{return(...J)=>{$.exec("BEGIN "+G);try{let _=X(...J);return $.exec("COMMIT"),_}catch(_){throw $.exec("ROLLBACK"),_}}},Y={default:{value:Z("")},deferred:{value:Z("DEFERRED")},immediate:{value:Z("IMMEDIATE")},exclusive:{value:Z("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(Y.default.value,Y),Object.defineProperties(Y.deferred.value,Y),Object.defineProperties(Y.immediate.value,Y),Object.defineProperties(Y.exclusive.value,Y),Y.default.value}pragma(X,$){if($==null)$={};if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(typeof $!=="object")throw TypeError("Expected second argument to be an options object");let Z=$.simple,Y=this.prepare(`PRAGMA ${X}`,this,!0);return Z?Y.pluck().get():Y.all()}backup(X,$){throw Error("not implemented")}serialize(X){throw Error("not implemented")}function(X,$,Z){if($==null)$={};if(typeof $==="function")Z=$,$={};if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(typeof Z!=="function")throw TypeError("Expected last argument to be a function");if(typeof $!=="object")throw TypeError("Expected second argument to be an options object");if(!X)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(X,$){if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(typeof $!=="object"||$===null)throw TypeError("Expected second argument to be an options object");if(!X)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(X,$){if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(!X)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(X){KY.call(this.db,X)}loadExtension(...X){EY.call(this.db,...X)}maxWriteReplicationIndex(){return RY.call(this.db)}exec(X){try{UY.call(this.db,X)}catch($){throw R1($)}}interrupt(){HY.call(this.db)}close(){DY.call(this.db),this.open=!1}defaultSafeIntegers(X){return FY.call(this.db,X??!0),this}unsafeMode(...X){throw Error("not implemented")}}class gX{constructor(X){this.stmt=X,this.pluckMode=!1}raw(X){return MY.call(this.stmt,X??!0),this}pluck(X){return this.pluckMode=X??!0,this}get reader(){return NY.call(this.stmt)}run(...X){try{if(X.length==1&&typeof X[0]==="object")return yX.call(this.stmt,X[0]);else return yX.call(this.stmt,X.flat())}catch($){throw R1($)}}get(...X){try{if(X.length==1&&typeof X[0]==="object")return qX.call(this.stmt,X[0]);else return qX.call(this.stmt,X.flat())}catch($){throw R1($)}}iterate(...X){var $=void 0;if(X.length==1&&typeof X[0]==="object")$=SX.call(this.stmt,X[0]);else $=SX.call(this.stmt,X.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)PY.call($,this.nextRows),this.nextRowIndex=0;let Y=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!Y)return{done:!0};return this.nextRowIndex++,{value:Y,done:!1}}catch(Y){throw R1(Y)}},[Symbol.iterator](){return this}}}all(...X){try{let $=[];for(let Z of this.iterate(...X))if(this.pluckMode)$.push(Z[Object.keys(Z)[0]]);else $.push(Z);return $}catch($){throw R1($)}}interrupt(){IY.call(this.stmt)}columns(){return xY.call(this.stmt)}safeIntegers(X){return wY.call(this.stmt,X??!0),this}}p0.exports=bX;p0.exports.Authorization=kY;p0.exports.SqliteError=pX});var G4=y2((AH,j$)=>{function o7(X){var $=0,Z=[];function Y(){if($--,$<X)G()}function G(){var H=Z.shift();if(W.queue=Z.length,H)_(H.fn).then(H.resolve).catch(H.reject)}function J(H){return new Promise(function(D,A){Z.push({fn:H,resolve:D,reject:A}),W.queue=Z.length})}function _(H){$++;try{return Promise.resolve(H()).then(function(D){return Y(),D},function(D){throw Y(),D})}catch(D){return Y(),Promise.reject(D)}}var W=function(H){if($>=X)return J(H);else return _(H)};return W}function i7(X,$){var Z=!1,Y=this;return Promise.all(X.map(function(){var G=arguments;return Y(function(){if(!Z)return $.apply(void 0,G).catch(function(J){throw Z=!0,J})})}))}function T$(X){return X.queue=0,X.map=i7,X}j$.exports=function(X){if(X)return T$(o7(X));else return T$(function($){return $()})}});import{join as zG}from"node:path";import{homedir as HG}from"node:os";var O=Symbol.for("drizzle:entityKind");function U(X,$){if(!X||typeof X!=="object")return!1;if(X instanceof $)return!0;if(!Object.prototype.hasOwnProperty.call($,O))throw Error(`Class "${$.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let Z=Object.getPrototypeOf(X).constructor;if(Z)while(Z){if(O in Z&&Z[O]===$[O])return!0;Z=Object.getPrototypeOf(Z)}return!1}class Q{constructor(X,$){this.table=X,this.config=$,this.name=$.name,this.keyAsName=$.keyAsName,this.notNull=$.notNull,this.default=$.default,this.defaultFn=$.defaultFn,this.onUpdateFn=$.onUpdateFn,this.hasDefault=$.hasDefault,this.primary=$.primaryKey,this.isUnique=$.isUnique,this.uniqueName=$.uniqueName,this.uniqueType=$.uniqueType,this.dataType=$.dataType,this.columnType=$.columnType,this.generated=$.generated,this.generatedIdentity=$.generatedIdentity}static[O]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(X){return X}mapToDriverValue(X){return X}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class J6{static[O]="ColumnBuilder";config;constructor(X,$,Z){this.config={name:X,keyAsName:X==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:$,columnType:Z,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(X){return this.config.default=X,this.config.hasDefault=!0,this}$defaultFn(X){return this.config.defaultFn=X,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(X){return this.config.onUpdateFn=X,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(X){if(this.config.name!=="")return;this.config.name=X}}var Z2=Symbol.for("drizzle:Name");function D4(X,...$){return X(...$)}function O4(X,$){return`${X[Z2]}_${$.join("_")}_unique`}class f1 extends Q{constructor(X,$){if(!$.uniqueName)$.uniqueName=O4(X,[$.name]);super(X,$);this.table=X}static[O]="PgColumn"}class e$ extends f1{static[O]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(X){return this.indexConfig.opClass=X,this}}class XZ extends f1{static[O]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(X,$){super(X,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var A4=Symbol.for("drizzle:isPgEnum");function U4(X){return!!X&&typeof X==="function"&&A4 in X&&X[A4]===!0}class $Z extends f1{static[O]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(X,$){super(X,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}class m{static[O]="Subquery";constructor(X,$,Z,Y=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:$,alias:Z,isWith:Y,usedTables:G}}}class q1 extends m{static[O]="WithSubquery"}var V4="0.44.7";var _6,W6,F4={startActiveSpan(X,$){if(!_6)return $();if(!W6)W6=_6.trace.getTracer("drizzle-orm",V4);return D4((Z,Y)=>Y.startActiveSpan(X,(G)=>{try{return $(G)}catch(J){throw G.setStatus({code:Z.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),_6,W6)}};var q=Symbol.for("drizzle:ViewBaseConfig");var N0=Symbol.for("drizzle:Schema"),I0=Symbol.for("drizzle:Columns"),K4=Symbol.for("drizzle:ExtraConfigColumns"),z6=Symbol.for("drizzle:OriginalName"),H6=Symbol.for("drizzle:BaseName"),y1=Symbol.for("drizzle:IsAlias"),E4=Symbol.for("drizzle:ExtraConfigBuilder"),ZZ=Symbol.for("drizzle:IsDrizzleTable");class V{static[O]="Table";static Symbol={Name:Z2,Schema:N0,OriginalName:z6,Columns:I0,ExtraConfigColumns:K4,BaseName:H6,IsAlias:y1,ExtraConfigBuilder:E4};[Z2];[z6];[N0];[I0];[K4];[H6];[y1]=!1;[ZZ]=!0;[E4]=void 0;constructor(X,$,Z){this[Z2]=this[z6]=X,this[N0]=$,this[H6]=Z}}function v2(X){return X[Z2]}function u2(X){return`${X[N0]??"public"}.${X[Z2]}`}function D6(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function YZ(X){let $={sql:"",params:[]};for(let Z of X)if($.sql+=Z.sql,$.params.push(...Z.params),Z.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...Z.typings)}return $}class o{static[O]="StringChunk";value;constructor(X){this.value=Array.isArray(X)?X:[X]}getSQL(){return new E([this])}}class E{constructor(X){this.queryChunks=X;for(let $ of X)if(U($,V)){let Z=$[V.Symbol.Schema];this.usedTables.push(Z===void 0?$[V.Symbol.Name]:Z+"."+$[V.Symbol.Name])}}static[O]="SQL";decoder=M4;shouldInlineParams=!1;usedTables=[];append(X){return this.queryChunks.push(...X.queryChunks),this}toQuery(X){return F4.startActiveSpan("drizzle.buildSQL",($)=>{let Z=this.buildQueryFromSourceParams(this.queryChunks,X);return $?.setAttributes({"drizzle.query.text":Z.sql,"drizzle.query.params":JSON.stringify(Z.params)}),Z})}buildQueryFromSourceParams(X,$){let Z=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:Y,escapeName:G,escapeParam:J,prepareTyping:_,inlineParams:W,paramStartIndex:H}=Z;return YZ(X.map((D)=>{if(U(D,o))return{sql:D.value.join(""),params:[]};if(U(D,x0))return{sql:G(D.value),params:[]};if(D===void 0)return{sql:"",params:[]};if(Array.isArray(D)){let A=[new o("(")];for(let[R,F]of D.entries())if(A.push(F),R<D.length-1)A.push(new o(", "));return A.push(new o(")")),this.buildQueryFromSourceParams(A,Z)}if(U(D,E))return this.buildQueryFromSourceParams(D.queryChunks,{...Z,inlineParams:W||D.shouldInlineParams});if(U(D,V)){let A=D[V.Symbol.Schema],R=D[V.Symbol.Name];return{sql:A===void 0||D[y1]?G(R):G(A)+"."+G(R),params:[]}}if(U(D,Q)){let A=Y.getColumnCasing(D);if($.invokeSource==="indexes")return{sql:G(A),params:[]};let R=D.table[V.Symbol.Schema];return{sql:D.table[y1]||R===void 0?G(D.table[V.Symbol.Name])+"."+G(A):G(R)+"."+G(D.table[V.Symbol.Name])+"."+G(A),params:[]}}if(U(D,_2)){let A=D[q].schema,R=D[q].name;return{sql:A===void 0||D[q].isAlias?G(R):G(A)+"."+G(R),params:[]}}if(U(D,Y2)){if(U(D.value,C2))return{sql:J(H.value++,D),params:[D],typings:["none"]};let A=D.value===null?null:D.encoder.mapToDriverValue(D.value);if(U(A,E))return this.buildQueryFromSourceParams([A],Z);if(W)return{sql:this.mapInlineParam(A,Z),params:[]};let R=["none"];if(_)R=[_(D.encoder)];return{sql:J(H.value++,A),params:[A],typings:R}}if(U(D,C2))return{sql:J(H.value++,D),params:[D],typings:["none"]};if(U(D,E.Aliased)&&D.fieldAlias!==void 0)return{sql:G(D.fieldAlias),params:[]};if(U(D,m)){if(D._.isWith)return{sql:G(D._.alias),params:[]};return this.buildQueryFromSourceParams([new o("("),D._.sql,new o(") "),new x0(D._.alias)],Z)}if(U4(D)){if(D.schema)return{sql:G(D.schema)+"."+G(D.enumName),params:[]};return{sql:G(D.enumName),params:[]}}if(D6(D)){if(D.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([D.getSQL()],Z);return this.buildQueryFromSourceParams([new o("("),D.getSQL(),new o(")")],Z)}if(W)return{sql:this.mapInlineParam(D,Z),params:[]};return{sql:J(H.value++,D),params:[D],typings:["none"]}}))}mapInlineParam(X,{escapeString:$}){if(X===null)return"null";if(typeof X==="number"||typeof X==="boolean")return X.toString();if(typeof X==="string")return $(X);if(typeof X==="object"){let Z=X.toString();if(Z==="[object Object]")return $(JSON.stringify(X));return $(Z)}throw Error("Unexpected param value: "+X)}getSQL(){return this}as(X){if(X===void 0)return this;return new E.Aliased(this,X)}mapWith(X){return this.decoder=typeof X==="function"?{mapFromDriverValue:X}:X,this}inlineParams(){return this.shouldInlineParams=!0,this}if(X){return X?this:void 0}}class x0{constructor(X){this.value=X}static[O]="Name";brand;getSQL(){return new E([this])}}function R4(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var M4={mapFromDriverValue:(X)=>X},N4={mapToDriverValue:(X)=>X},oG={...M4,...N4};class Y2{constructor(X,$=N4){this.value=X,this.encoder=$}static[O]="Param";brand;getSQL(){return new E([this])}}function z(X,...$){let Z=[];if($.length>0||X.length>0&&X[0]!=="")Z.push(new o(X[0]));for(let[Y,G]of $.entries())Z.push(G,new o(X[Y+1]));return new E(Z)}((X)=>{function $(){return new E([])}X.empty=$;function Z(H){return new E(H)}X.fromList=Z;function Y(H){return new E([new o(H)])}X.raw=Y;function G(H,D){let A=[];for(let[R,F]of H.entries()){if(R>0&&D!==void 0)A.push(D);A.push(F)}return new E(A)}X.join=G;function J(H){return new x0(H)}X.identifier=J;function _(H){return new C2(H)}X.placeholder=_;function W(H,D){return new Y2(H,D)}X.param=W})(z||(z={}));((X)=>{class ${constructor(Z,Y){this.sql=Z,this.fieldAlias=Y}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}X.Aliased=$})(E||(E={}));class C2{constructor(X){this.name=X}static[O]="Placeholder";getSQL(){return new E([this])}}function S1(X,$){return X.map((Z)=>{if(U(Z,C2)){if(!(Z.name in $))throw Error(`No value for placeholder "${Z.name}" was provided`);return $[Z.name]}if(U(Z,Y2)&&U(Z.value,C2)){if(!(Z.value.name in $))throw Error(`No value for placeholder "${Z.value.name}" was provided`);return Z.encoder.mapToDriverValue($[Z.value.name])}return Z})}var GZ=Symbol.for("drizzle:IsDrizzleView");class _2{static[O]="View";[q];[GZ]=!0;constructor({name:X,schema:$,selectedFields:Z,query:Y}){this[q]={name:X,originalName:X,schema:$,selectedFields:Z,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new E([this])}}Q.prototype.getSQL=function(){return new E([this])};V.prototype.getSQL=function(){return new E([this])};m.prototype.getSQL=function(){return new E([this])};class J1{constructor(X){this.table=X}static[O]="ColumnAliasProxyHandler";get(X,$){if($==="table")return this.table;return X[$]}}class p1{constructor(X,$){this.alias=X,this.replaceOriginalName=$}static[O]="TableAliasProxyHandler";get(X,$){if($===V.Symbol.IsAlias)return!0;if($===V.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===V.Symbol.OriginalName)return this.alias;if($===q)return{...X[q],name:this.alias,isAlias:!0};if($===V.Symbol.Columns){let Y=X[V.Symbol.Columns];if(!Y)return Y;let G={};return Object.keys(Y).map((J)=>{G[J]=new Proxy(Y[J],new J1(new Proxy(X,this)))}),G}let Z=X[$];if(U(Z,Q))return new Proxy(Z,new J1(new Proxy(X,this)));return Z}}function w0(X,$){return new Proxy(X,new p1($,!1))}function K2(X,$){return new Proxy(X,new J1(new Proxy(X.table,new p1($,!1))))}function O6(X,$){return new E.Aliased(b1(X.sql,$),X.fieldAlias)}function b1(X,$){return z.join(X.queryChunks.map((Z)=>{if(U(Z,Q))return K2(Z,$);if(U(Z,E))return b1(Z,$);if(U(Z,E.Aliased))return O6(Z,$);return Z}))}class _1 extends Error{static[O]="DrizzleError";constructor({message:X,cause:$}){super(X);this.name="DrizzleError",this.cause=$}}class P2 extends Error{constructor(X,$,Z){super(`Failed query: ${X}
|
|
2
|
-
params: ${$}`);if(this.query=X,this.params=$,this.cause=Z,Error.captureStackTrace(this,P2),Z)this.cause=Z}}class A6 extends _1{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class I4{static[O]="ConsoleLogWriter";write(X){console.log(X)}}class U6{static[O]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new I4}logQuery(X,$){let Z=$.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),Y=Z.length?` -- params: [${Z.join(", ")}]`:"";this.writer.write(`Query: ${X}${Y}`)}}class V6{static[O]="NoopLogger";logQuery(){}}class s{static[O]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(X){return this.then(void 0,X)}finally(X){return this.then(($)=>{return X?.(),$},($)=>{throw X?.(),$})}then(X,$){return this.execute().then(X,$)}}function F6(X,$,Z){let Y={},G=X.reduce((J,{path:_,field:W},H)=>{let D;if(U(W,Q))D=W;else if(U(W,E))D=W.decoder;else D=W.sql.decoder;let A=J;for(let[R,F]of _.entries())if(R<_.length-1){if(!(F in A))A[F]={};A=A[F]}else{let M=$[H],K=A[F]=M===null?null:D.mapFromDriverValue(M);if(Z&&U(W,Q)&&_.length===2){let x=_[0];if(!(x in Y))Y[x]=K===null?v2(W.table):!1;else if(typeof Y[x]==="string"&&Y[x]!==v2(W.table))Y[x]=!1}}return J},{});if(Z&&Object.keys(Y).length>0){for(let[J,_]of Object.entries(Y))if(typeof _==="string"&&!Z[_])G[J]=null}return G}function W2(X,$){return Object.entries(X).reduce((Z,[Y,G])=>{if(typeof Y!=="string")return Z;let J=$?[...$,Y]:[Y];if(U(G,Q)||U(G,E)||U(G,E.Aliased))Z.push({path:J,field:G});else if(U(G,V))Z.push(...W2(G[V.Symbol.Columns],J));else Z.push(...W2(G,J));return Z},[])}function g1(X,$){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let[G,J]of Z.entries())if(J!==Y[G])return!1;return!0}function P0(X,$){let Z=Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,G])=>{if(U(G,E)||U(G,Q))return[Y,G];else return[Y,new Y2(G,X[V.Symbol.Columns][Y])]});if(Z.length===0)throw Error("No values to set");return Object.fromEntries(Z)}function x4(X,$){for(let Z of $)for(let Y of Object.getOwnPropertyNames(Z.prototype)){if(Y==="constructor")continue;Object.defineProperty(X.prototype,Y,Object.getOwnPropertyDescriptor(Z.prototype,Y)||Object.create(null))}}function w4(X){return X[V.Symbol.Columns]}function d1(X){return U(X,m)?X._.alias:U(X,_2)?X[q].name:U(X,E)?void 0:X[V.Symbol.IsAlias]?X[V.Symbol.Name]:X[V.Symbol.BaseName]}function E2(X,$){return{name:typeof X==="string"&&X.length>0?X:"",config:typeof X==="object"?X:$}}function P4(X){if(typeof X!=="object"||X===null)return!1;if(X.constructor.name!=="Object")return!1;if("logger"in X){let $=typeof X.logger;if($!=="boolean"&&($!=="object"||typeof X.logger.logQuery!=="function")&&$!=="undefined")return!1;return!0}if("schema"in X){let $=typeof X.schema;if($!=="object"&&$!=="undefined")return!1;return!0}if("casing"in X){let $=typeof X.casing;if($!=="string"&&$!=="undefined")return!1;return!0}if("mode"in X){if(X.mode!=="default"||X.mode!=="planetscale"||X.mode!==void 0)return!1;return!0}if("connection"in X){let $=typeof X.connection;if($!=="string"&&$!=="object"&&$!=="undefined")return!1;return!0}if("client"in X){let $=typeof X.client;if($!=="object"&&$!=="function"&&$!=="undefined")return!1;return!0}if(Object.keys(X).length===0)return!0;return!1}var K6=typeof TextDecoder>"u"?null:new TextDecoder;var k4=Symbol.for("drizzle:PgInlineForeignKeys"),T4=Symbol.for("drizzle:EnableRLS");class E6 extends V{static[O]="PgTable";static Symbol=Object.assign({},V.Symbol,{InlineForeignKeys:k4,EnableRLS:T4});[k4]=[];[T4]=!1;[V.Symbol.ExtraConfigBuilder]=void 0;[V.Symbol.ExtraConfigColumns]={}}class R6{static[O]="PgPrimaryKeyBuilder";columns;name;constructor(X,$){this.columns=X,this.name=$}build(X){return new j4(X,this.columns,this.name)}}class j4{constructor(X,$,Z){this.table=X,this.columns=$,this.name=Z}static[O]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[E6.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function e(X,$){if(R4($)&&!D6(X)&&!U(X,Y2)&&!U(X,C2)&&!U(X,Q)&&!U(X,V)&&!U(X,_2))return new Y2(X,$);return X}var b=(X,$)=>{return z`${X} = ${e($,X)}`},Q4=(X,$)=>{return z`${X} <> ${e($,X)}`};function m1(...X){let $=X.filter((Z)=>Z!==void 0);if($.length===0)return;if($.length===1)return new E($);return new E([new o("("),z.join($,new o(" and ")),new o(")")])}function B4(...X){let $=X.filter((Z)=>Z!==void 0);if($.length===0)return;if($.length===1)return new E($);return new E([new o("("),z.join($,new o(" or ")),new o(")")])}function L4(X){return z`not ${X}`}var v4=(X,$)=>{return z`${X} > ${e($,X)}`},C4=(X,$)=>{return z`${X} >= ${e($,X)}`},h4=(X,$)=>{return z`${X} < ${e($,X)}`},f4=(X,$)=>{return z`${X} <= ${e($,X)}`};function n2(X,$){if(Array.isArray($)){if($.length===0)return z`false`;return z`${X} in ${$.map((Z)=>e(Z,X))}`}return z`${X} in ${e($,X)}`}function q4(X,$){if(Array.isArray($)){if($.length===0)return z`true`;return z`${X} not in ${$.map((Z)=>e(Z,X))}`}return z`${X} not in ${e($,X)}`}function y4(X){return z`${X} is null`}function S4(X){return z`${X} is not null`}function p4(X){return z`exists ${X}`}function b4(X){return z`not exists ${X}`}function g4(X,$,Z){return z`${X} between ${e($,X)} and ${e(Z,X)}`}function d4(X,$,Z){return z`${X} not between ${e($,X)} and ${e(Z,X)}`}function k0(X,$){return z`${X} like ${$}`}function m4(X,$){return z`${X} not like ${$}`}function c4(X,$){return z`${X} ilike ${$}`}function u4(X,$){return z`${X} not ilike ${$}`}function n4(X){return z`${X} asc`}function W1(X){return z`${X} desc`}class M6{constructor(X,$,Z){this.sourceTable=X,this.referencedTable=$,this.relationName=Z,this.referencedTableName=$[V.Symbol.Name]}static[O]="Relation";referencedTableName;fieldName}class o4{constructor(X,$){this.table=X,this.config=$}static[O]="Relations"}class h2 extends M6{constructor(X,$,Z,Y){super(X,$,Z?.relationName);this.config=Z,this.isNullable=Y}static[O]="One";withFieldName(X){let $=new h2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=X,$}}class c1 extends M6{constructor(X,$,Z){super(X,$,Z?.relationName);this.config=Z}static[O]="Many";withFieldName(X){let $=new c1(this.sourceTable,this.referencedTable,this.config);return $.fieldName=X,$}}function i4(){return{and:m1,between:g4,eq:b,exists:p4,gt:v4,gte:C4,ilike:c4,inArray:n2,isNull:y4,isNotNull:S4,like:k0,lt:h4,lte:f4,ne:Q4,not:L4,notBetween:d4,notExists:b4,notLike:m4,notIlike:u4,notInArray:q4,or:B4,sql:z}}function r4(){return{sql:z,asc:n4,desc:W1}}function t4(X,$){if(Object.keys(X).length===1&&"default"in X&&!U(X.default,V))X=X.default;let Z={},Y={},G={};for(let[J,_]of Object.entries(X))if(U(_,V)){let W=u2(_),H=Y[W];Z[W]=J,G[J]={tsName:J,dbName:_[V.Symbol.Name],schema:_[V.Symbol.Schema],columns:_[V.Symbol.Columns],relations:H?.relations??{},primaryKey:H?.primaryKey??[]};for(let A of Object.values(_[V.Symbol.Columns]))if(A.primary)G[J].primaryKey.push(A);let D=_[V.Symbol.ExtraConfigBuilder]?.(_[V.Symbol.ExtraConfigColumns]);if(D){for(let A of Object.values(D))if(U(A,R6))G[J].primaryKey.push(...A.columns)}}else if(U(_,o4)){let W=u2(_.table),H=Z[W],D=_.config($(_.table)),A;for(let[R,F]of Object.entries(D))if(H){let M=G[H];if(M.relations[R]=F,A)M.primaryKey.push(...A)}else{if(!(W in Y))Y[W]={relations:{},primaryKey:A};Y[W].relations[R]=F}}return{tables:G,tableNamesMap:Z}}function JZ(X){return function(Z,Y){return new h2(X,Z,Y,Y?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function _Z(X){return function(Z,Y){return new c1(X,Z,Y)}}function l4(X,$,Z){if(U(Z,h2)&&Z.config)return{fields:Z.config.fields,references:Z.config.references};let Y=$[u2(Z.referencedTable)];if(!Y)throw Error(`Table "${Z.referencedTable[V.Symbol.Name]}" not found in schema`);let G=X[Y];if(!G)throw Error(`Table "${Y}" not found in schema`);let J=Z.sourceTable,_=$[u2(J)];if(!_)throw Error(`Table "${J[V.Symbol.Name]}" not found in schema`);let W=[];for(let H of Object.values(G.relations))if(Z.relationName&&Z!==H&&H.relationName===Z.relationName||!Z.relationName&&H.referencedTable===Z.sourceTable)W.push(H);if(W.length>1)throw Z.relationName?Error(`There are multiple relations with name "${Z.relationName}" in table "${Y}"`):Error(`There are multiple relations between "${Y}" and "${Z.sourceTable[V.Symbol.Name]}". Please specify relation name`);if(W[0]&&U(W[0],h2)&&W[0].config)return{fields:W[0].config.references,references:W[0].config.fields};throw Error(`There is not enough information to infer relation "${_}.${Z.fieldName}"`)}function s4(X){return{one:JZ(X),many:_Z(X)}}function T0(X,$,Z,Y,G=(J)=>J){let J={};for(let[_,W]of Y.entries())if(W.isJson){let H=$.relations[W.tsKey],D=Z[_],A=typeof D==="string"?JSON.parse(D):D;J[W.tsKey]=U(H,h2)?A&&T0(X,X[W.relationTableTsKey],A,W.selection,G):A.map((R)=>T0(X,X[W.relationTableTsKey],R,W.selection,G))}else{let H=G(Z[_]),D=W.field,A;if(U(D,Q))A=D;else if(U(D,E))A=D.decoder;else A=D.sql.decoder;J[W.tsKey]=H===null?null:A.mapFromDriverValue(H)}return J}import{randomUUID as t1}from"node:crypto";class N6{static[O]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(X,$){if(this.reference=()=>{let{name:Z,columns:Y,foreignColumns:G}=X();return{name:Z,columns:Y,foreignTable:G[0].table,foreignColumns:G}},$)this._onUpdate=$.onUpdate,this._onDelete=$.onDelete}onUpdate(X){return this._onUpdate=X,this}onDelete(X){return this._onDelete=X,this}build(X){return new a4(X,this)}}class a4{constructor(X,$){this.table=X,this.reference=$.reference,this.onUpdate=$._onUpdate,this.onDelete=$._onDelete}static[O]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:X,columns:$,foreignColumns:Z}=this.reference(),Y=$.map((_)=>_.name),G=Z.map((_)=>_.name),J=[this.table[Z2],...Y,Z[0].table[Z2],...G];return X??`${J.join("_")}_fk`}}function e4(X,$){return`${X[Z2]}_${$.join("_")}_unique`}class r extends J6{static[O]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(X,$={}){return this.foreignKeyConfigs.push({ref:X,actions:$}),this}unique(X){return this.config.isUnique=!0,this.config.uniqueName=X,this}generatedAlwaysAs(X,$){return this.config.generated={as:X,type:"always",mode:$?.mode??"virtual"},this}buildForeignKeys(X,$){return this.foreignKeyConfigs.map(({ref:Z,actions:Y})=>{return((G,J)=>{let _=new N6(()=>{let W=G();return{columns:[X],foreignColumns:[W]}});if(J.onUpdate)_.onUpdate(J.onUpdate);if(J.onDelete)_.onDelete(J.onDelete);return _.build($)})(Z,Y)})}}class S extends Q{constructor(X,$){if(!$.uniqueName)$.uniqueName=e4(X,[$.name]);super(X,$);this.table=X}static[O]="SQLiteColumn"}class X8 extends r{static[O]="SQLiteBigIntBuilder";constructor(X){super(X,"bigint","SQLiteBigInt")}build(X){return new $8(X,this.config)}}class $8 extends S{static[O]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(X){if(typeof Buffer<"u"&&Buffer.from){let $=Buffer.isBuffer(X)?X:X instanceof ArrayBuffer?Buffer.from(X):X.buffer?Buffer.from(X.buffer,X.byteOffset,X.byteLength):Buffer.from(X);return BigInt($.toString("utf8"))}return BigInt(K6.decode(X))}mapToDriverValue(X){return Buffer.from(X.toString())}}class Z8 extends r{static[O]="SQLiteBlobJsonBuilder";constructor(X){super(X,"json","SQLiteBlobJson")}build(X){return new Y8(X,this.config)}}class Y8 extends S{static[O]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(X){if(typeof Buffer<"u"&&Buffer.from){let $=Buffer.isBuffer(X)?X:X instanceof ArrayBuffer?Buffer.from(X):X.buffer?Buffer.from(X.buffer,X.byteOffset,X.byteLength):Buffer.from(X);return JSON.parse($.toString("utf8"))}return JSON.parse(K6.decode(X))}mapToDriverValue(X){return Buffer.from(JSON.stringify(X))}}class G8 extends r{static[O]="SQLiteBlobBufferBuilder";constructor(X){super(X,"buffer","SQLiteBlobBuffer")}build(X){return new J8(X,this.config)}}class J8 extends S{static[O]="SQLiteBlobBuffer";mapFromDriverValue(X){if(Buffer.isBuffer(X))return X;return Buffer.from(X)}getSQLType(){return"blob"}}function _8(X,$){let{name:Z,config:Y}=E2(X,$);if(Y?.mode==="json")return new Z8(Z);if(Y?.mode==="bigint")return new X8(Z);return new G8(Z)}class W8 extends r{static[O]="SQLiteCustomColumnBuilder";constructor(X,$,Z){super(X,"custom","SQLiteCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=Z}build(X){return new z8(X,this.config)}}class z8 extends S{static[O]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(X,$){super(X,$);this.sqlName=$.customTypeParams.dataType($.fieldConfig),this.mapTo=$.customTypeParams.toDriver,this.mapFrom=$.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(X){return typeof this.mapFrom==="function"?this.mapFrom(X):X}mapToDriverValue(X){return typeof this.mapTo==="function"?this.mapTo(X):X}}function H8(X){return($,Z)=>{let{name:Y,config:G}=E2($,Z);return new W8(Y,G,X)}}class j0 extends r{static[O]="SQLiteBaseIntegerBuilder";constructor(X,$,Z){super(X,$,Z);this.config.autoIncrement=!1}primaryKey(X){if(X?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class Q0 extends S{static[O]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class D8 extends j0{static[O]="SQLiteIntegerBuilder";constructor(X){super(X,"number","SQLiteInteger")}build(X){return new O8(X,this.config)}}class O8 extends Q0{static[O]="SQLiteInteger"}class A8 extends j0{static[O]="SQLiteTimestampBuilder";constructor(X,$){super(X,"date","SQLiteTimestamp");this.config.mode=$}defaultNow(){return this.default(z`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(X){return new U8(X,this.config)}}class U8 extends Q0{static[O]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(X){if(this.config.mode==="timestamp")return new Date(X*1000);return new Date(X)}mapToDriverValue(X){let $=X.getTime();if(this.config.mode==="timestamp")return Math.floor($/1000);return $}}class V8 extends j0{static[O]="SQLiteBooleanBuilder";constructor(X,$){super(X,"boolean","SQLiteBoolean");this.config.mode=$}build(X){return new F8(X,this.config)}}class F8 extends Q0{static[O]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(X){return Number(X)===1}mapToDriverValue(X){return X?1:0}}function g(X,$){let{name:Z,config:Y}=E2(X,$);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new A8(Z,Y.mode);if(Y?.mode==="boolean")return new V8(Z,Y.mode);return new D8(Z)}class K8 extends r{static[O]="SQLiteNumericBuilder";constructor(X){super(X,"string","SQLiteNumeric")}build(X){return new E8(X,this.config)}}class E8 extends S{static[O]="SQLiteNumeric";mapFromDriverValue(X){if(typeof X==="string")return X;return String(X)}getSQLType(){return"numeric"}}class R8 extends r{static[O]="SQLiteNumericNumberBuilder";constructor(X){super(X,"number","SQLiteNumericNumber")}build(X){return new M8(X,this.config)}}class M8 extends S{static[O]="SQLiteNumericNumber";mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}mapToDriverValue=String;getSQLType(){return"numeric"}}class N8 extends r{static[O]="SQLiteNumericBigIntBuilder";constructor(X){super(X,"bigint","SQLiteNumericBigInt")}build(X){return new I8(X,this.config)}}class I8 extends S{static[O]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function x8(X,$){let{name:Z,config:Y}=E2(X,$),G=Y?.mode;return G==="number"?new R8(Z):G==="bigint"?new N8(Z):new K8(Z)}class w8 extends r{static[O]="SQLiteRealBuilder";constructor(X){super(X,"number","SQLiteReal")}build(X){return new P8(X,this.config)}}class P8 extends S{static[O]="SQLiteReal";getSQLType(){return"real"}}function z1(X){return new w8(X??"")}class k8 extends r{static[O]="SQLiteTextBuilder";constructor(X,$){super(X,"string","SQLiteText");this.config.enumValues=$.enum,this.config.length=$.length}build(X){return new T8(X,this.config)}}class T8 extends S{static[O]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(X,$){super(X,$)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class j8 extends r{static[O]="SQLiteTextJsonBuilder";constructor(X){super(X,"json","SQLiteTextJson")}build(X){return new Q8(X,this.config)}}class Q8 extends S{static[O]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(X){return JSON.parse(X)}mapToDriverValue(X){return JSON.stringify(X)}}function N(X,$={}){let{name:Z,config:Y}=E2(X,$);if(Y.mode==="json")return new j8(Z);return new k8(Z,Y)}class c{static[O]="SelectionProxyHandler";config;constructor(X){this.config={...X}}get(X,$){if($==="_")return{...X._,selectedFields:new Proxy(X._.selectedFields,this)};if($===q)return{...X[q],selectedFields:new Proxy(X[q].selectedFields,this)};if(typeof $==="symbol")return X[$];let Y=(U(X,m)?X._.selectedFields:U(X,_2)?X[q].selectedFields:X)[$];if(U(Y,E.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!Y.isSelectionField)return Y.sql;let G=Y.clone();return G.isSelectionField=!0,G}if(U(Y,E)){if(this.config.sqlBehavior==="sql")return Y;throw Error(`You tried to reference "${$}" 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.`)}if(U(Y,Q)){if(this.config.alias)return new Proxy(Y,new J1(new Proxy(Y.table,new p1(this.config.alias,this.config.replaceOriginalName??!1))));return Y}if(typeof Y!=="object"||Y===null)return Y;return new Proxy(Y,new c(this.config))}}function B8(){return{blob:_8,customType:H8,integer:g,numeric:x8,real:z1,text:N}}var I6=Symbol.for("drizzle:SQLiteInlineForeignKeys");class u extends V{static[O]="SQLiteTable";static Symbol=Object.assign({},V.Symbol,{InlineForeignKeys:I6});[V.Symbol.Columns];[I6]=[];[V.Symbol.ExtraConfigBuilder]=void 0}function WZ(X,$,Z,Y,G=X){let J=new u(X,Y,G),_=typeof $==="function"?$(B8()):$,W=Object.fromEntries(Object.entries(_).map(([D,A])=>{let R=A;R.setName(D);let F=R.build(J);return J[I6].push(...R.buildForeignKeys(F,J)),[D,F]})),H=Object.assign(J,W);if(H[V.Symbol.Columns]=W,H[V.Symbol.ExtraConfigColumns]=W,Z)H[u.Symbol.ExtraConfigBuilder]=Z;return H}var X2=(X,$,Z)=>{return WZ(X,$,Z)};class L8{constructor(X,$){this.name=X,this.unique=$}static[O]="SQLiteIndexBuilderOn";on(...X){return new v8(this.name,X,this.unique)}}class v8{static[O]="SQLiteIndexBuilder";config;constructor(X,$,Z){this.config={name:X,columns:$,unique:Z,where:void 0}}where(X){return this.config.where=X,this}build(X){return new C8(this.config,X)}}class C8{static[O]="SQLiteIndex";config;constructor(X,$){this.config={...X,table:$}}}function f(X){return new L8(X,!1)}function w6(...X){if(X[0].columns)return new x6(X[0].columns,X[0].name);return new x6(X)}class x6{static[O]="SQLitePrimaryKeyBuilder";columns;name;constructor(X,$){this.columns=X,this.name=$}build(X){return new h8(X,this.columns,this.name)}}class h8{constructor(X,$,Z){this.table=X,this.columns=$,this.name=Z}static[O]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[u.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function O2(X){if(U(X,u))return[`${X[V.Symbol.BaseName]}`];if(U(X,m))return X._.usedTables??[];if(U(X,E))return X.usedTables??[];return[]}class B0 extends s{constructor(X,$,Z,Y){super();this.table=X,this.session=$,this.dialect=Z,this.config={table:X,withList:Y}}static[O]="SQLiteDelete";config;where(X){return this.config.where=X,this}orderBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.table[V.Symbol.Columns],new c({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray($)?$:[$];this.config.orderBy=Z}else{let $=X;this.config.orderBy=$}return this}limit(X){return this.config.limit=X,this}returning(X=this.table[u.Symbol.Columns]){return this.config.returning=W2(X),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(X=!0){return this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:O2(this.config.table)})}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(X){return this._prepare().execute(X)}$dynamic(){return this}}function zZ(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function HZ(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((Z,Y,G)=>{let J=G===0?Y.toLowerCase():`${Y[0].toUpperCase()}${Y.slice(1)}`;return Z+J},"")}function DZ(X){return X}class P6{static[O]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?zZ:X==="camelCase"?HZ:DZ}getColumnCasing(X){if(!X.keyAsName)return X.name;let $=X.table[V.Symbol.Schema]??"public",Z=X.table[V.Symbol.OriginalName],Y=`${$}.${Z}.${X.name}`;if(!this.cache[Y])this.cacheTable(X.table);return this.cache[Y]}cacheTable(X){let $=X[V.Symbol.Schema]??"public",Z=X[V.Symbol.OriginalName],Y=`${$}.${Z}`;if(!this.cachedTables[Y]){for(let G of Object.values(X[V.Symbol.Columns])){let J=`${Y}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[Y]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class o2 extends _2{static[O]="SQLiteViewBase"}class H1{static[O]="SQLiteDialect";casing;constructor(X){this.casing=new P6(X?.casing)}escapeName(X){return`"${X}"`}escapeParam(X){return"?"}escapeString(X){return`'${X.replace(/'/g,"''")}'`}buildWithCTE(X){if(!X?.length)return;let $=[z`with `];for(let[Z,Y]of X.entries())if($.push(z`${z.identifier(Y._.alias)} as (${Y._.sql})`),Z<X.length-1)$.push(z`, `);return $.push(z` `),z.join($)}buildDeleteQuery({table:X,where:$,returning:Z,withList:Y,limit:G,orderBy:J}){let _=this.buildWithCTE(Y),W=Z?z` returning ${this.buildSelection(Z,{isSingleTable:!0})}`:void 0,H=$?z` where ${$}`:void 0,D=this.buildOrderBy(J),A=this.buildLimit(G);return z`${_}delete from ${X}${H}${W}${D}${A}`}buildUpdateSet(X,$){let Z=X[V.Symbol.Columns],Y=Object.keys(Z).filter((J)=>$[J]!==void 0||Z[J]?.onUpdateFn!==void 0),G=Y.length;return z.join(Y.flatMap((J,_)=>{let W=Z[J],H=$[J]??z.param(W.onUpdateFn(),W),D=z`${z.identifier(this.casing.getColumnCasing(W))} = ${H}`;if(_<G-1)return[D,z.raw(", ")];return[D]}))}buildUpdateQuery({table:X,set:$,where:Z,returning:Y,withList:G,joins:J,from:_,limit:W,orderBy:H}){let D=this.buildWithCTE(G),A=this.buildUpdateSet(X,$),R=_&&z.join([z.raw(" from "),this.buildFromTable(_)]),F=this.buildJoins(J),M=Y?z` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,K=Z?z` where ${Z}`:void 0,x=this.buildOrderBy(H),k=this.buildLimit(W);return z`${D}update ${X} set ${A}${R}${F}${K}${M}${x}${k}`}buildSelection(X,{isSingleTable:$=!1}={}){let Z=X.length,Y=X.flatMap(({field:G},J)=>{let _=[];if(U(G,E.Aliased)&&G.isSelectionField)_.push(z.identifier(G.fieldAlias));else if(U(G,E.Aliased)||U(G,E)){let W=U(G,E.Aliased)?G.sql:G;if($)_.push(new E(W.queryChunks.map((H)=>{if(U(H,Q))return z.identifier(this.casing.getColumnCasing(H));return H})));else _.push(W);if(U(G,E.Aliased))_.push(z` as ${z.identifier(G.fieldAlias)}`)}else if(U(G,Q)){let W=G.table[V.Symbol.Name];if(G.columnType==="SQLiteNumericBigInt")if($)_.push(z`cast(${z.identifier(this.casing.getColumnCasing(G))} as text)`);else _.push(z`cast(${z.identifier(W)}.${z.identifier(this.casing.getColumnCasing(G))} as text)`);else if($)_.push(z.identifier(this.casing.getColumnCasing(G)));else _.push(z`${z.identifier(W)}.${z.identifier(this.casing.getColumnCasing(G))}`)}if(J<Z-1)_.push(z`, `);return _});return z.join(Y)}buildJoins(X){if(!X||X.length===0)return;let $=[];if(X)for(let[Z,Y]of X.entries()){if(Z===0)$.push(z` `);let G=Y.table,J=Y.on?z` on ${Y.on}`:void 0;if(U(G,u)){let _=G[u.Symbol.Name],W=G[u.Symbol.Schema],H=G[u.Symbol.OriginalName],D=_===H?void 0:Y.alias;$.push(z`${z.raw(Y.joinType)} join ${W?z`${z.identifier(W)}.`:void 0}${z.identifier(H)}${D&&z` ${z.identifier(D)}`}${J}`)}else $.push(z`${z.raw(Y.joinType)} join ${G}${J}`);if(Z<X.length-1)$.push(z` `)}return z.join($)}buildLimit(X){return typeof X==="object"||typeof X==="number"&&X>=0?z` limit ${X}`:void 0}buildOrderBy(X){let $=[];if(X){for(let[Z,Y]of X.entries())if($.push(Y),Z<X.length-1)$.push(z`, `)}return $.length>0?z` order by ${z.join($)}`:void 0}buildFromTable(X){if(U(X,V)&&X[V.Symbol.IsAlias])return z`${z`${z.identifier(X[V.Symbol.Schema]??"")}.`.if(X[V.Symbol.Schema])}${z.identifier(X[V.Symbol.OriginalName])} ${z.identifier(X[V.Symbol.Name])}`;return X}buildSelectQuery({withList:X,fields:$,fieldsFlat:Z,where:Y,having:G,table:J,joins:_,orderBy:W,groupBy:H,limit:D,offset:A,distinct:R,setOperators:F}){let M=Z??W2($);for(let D2 of M)if(U(D2.field,Q)&&v2(D2.field.table)!==(U(J,m)?J._.alias:U(J,o2)?J[q].name:U(J,E)?void 0:v2(J))&&!((F2)=>_?.some(({alias:M0})=>M0===(F2[V.Symbol.IsAlias]?v2(F2):F2[V.Symbol.BaseName])))(D2.field.table)){let F2=v2(D2.field.table);throw Error(`Your "${D2.path.join("->")}" field references a column "${F2}"."${D2.field.name}", but the table "${F2}" is not part of the query! Did you forget to join it?`)}let K=!_||_.length===0,x=this.buildWithCTE(X),k=R?z` distinct`:void 0,C=this.buildSelection(M,{isSingleTable:K}),L=this.buildFromTable(J),T=this.buildJoins(_),x2=Y?z` where ${Y}`:void 0,J2=G?z` having ${G}`:void 0,P=[];if(H){for(let[D2,F2]of H.entries())if(P.push(F2),D2<H.length-1)P.push(z`, `)}let h=P.length>0?z` group by ${z.join(P)}`:void 0,w2=this.buildOrderBy(W),R0=this.buildLimit(D),G6=A?z` offset ${A}`:void 0,G1=z`${x}select${k} ${C} from ${L}${T}${x2}${h}${J2}${w2}${R0}${G6}`;if(F.length>0)return this.buildSetOperations(G1,F);return G1}buildSetOperations(X,$){let[Z,...Y]=$;if(!Z)throw Error("Cannot pass undefined values to any set operator");if(Y.length===0)return this.buildSetOperationQuery({leftSelect:X,setOperator:Z});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:X,setOperator:Z}),Y)}buildSetOperationQuery({leftSelect:X,setOperator:{type:$,isAll:Z,rightSelect:Y,limit:G,orderBy:J,offset:_}}){let W=z`${X.getSQL()} `,H=z`${Y.getSQL()}`,D;if(J&&J.length>0){let M=[];for(let K of J)if(U(K,S))M.push(z.identifier(K.name));else if(U(K,E)){for(let x=0;x<K.queryChunks.length;x++){let k=K.queryChunks[x];if(U(k,S))K.queryChunks[x]=z.identifier(this.casing.getColumnCasing(k))}M.push(z`${K}`)}else M.push(z`${K}`);D=z` order by ${z.join(M,z`, `)}`}let A=typeof G==="object"||typeof G==="number"&&G>=0?z` limit ${G}`:void 0,R=z.raw(`${$} ${Z?"all ":""}`),F=_?z` offset ${_}`:void 0;return z`${W}${R}${H}${D}${A}${F}`}buildInsertQuery({table:X,values:$,onConflict:Z,returning:Y,withList:G,select:J}){let _=[],W=X[V.Symbol.Columns],H=Object.entries(W).filter(([K,x])=>!x.shouldDisableInsert()),D=H.map(([,K])=>z.identifier(this.casing.getColumnCasing(K)));if(J){let K=$;if(U(K,E))_.push(K);else _.push(K.getSQL())}else{let K=$;_.push(z.raw("values "));for(let[x,k]of K.entries()){let C=[];for(let[L,T]of H){let x2=k[L];if(x2===void 0||U(x2,Y2)&&x2.value===void 0){let J2;if(T.default!==null&&T.default!==void 0)J2=U(T.default,E)?T.default:z.param(T.default,T);else if(T.defaultFn!==void 0){let P=T.defaultFn();J2=U(P,E)?P:z.param(P,T)}else if(!T.default&&T.onUpdateFn!==void 0){let P=T.onUpdateFn();J2=U(P,E)?P:z.param(P,T)}else J2=z`null`;C.push(J2)}else C.push(x2)}if(_.push(C),x<K.length-1)_.push(z`, `)}}let A=this.buildWithCTE(G),R=z.join(_),F=Y?z` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,M=Z?.length?z.join(Z):void 0;return z`${A}insert into ${X} ${D} ${R}${M}${F}`}sqlToQuery(X,$){return X.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:$})}buildRelationalQuery({fullSchema:X,schema:$,tableNamesMap:Z,table:Y,tableConfig:G,queryConfig:J,tableAlias:_,nestedQueryRelation:W,joinOn:H}){let D=[],A,R,F=[],M,K=[];if(J===!0)D=Object.entries(G.columns).map(([C,L])=>({dbKey:L.name,tsKey:C,field:K2(L,_),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let k=Object.fromEntries(Object.entries(G.columns).map(([P,h])=>[P,K2(h,_)]));if(J.where){let P=typeof J.where==="function"?J.where(k,i4()):J.where;M=P&&b1(P,_)}let C=[],L=[];if(J.columns){let P=!1;for(let[h,w2]of Object.entries(J.columns)){if(w2===void 0)continue;if(h in G.columns){if(!P&&w2===!0)P=!0;L.push(h)}}if(L.length>0)L=P?L.filter((h)=>J.columns?.[h]===!0):Object.keys(G.columns).filter((h)=>!L.includes(h))}else L=Object.keys(G.columns);for(let P of L){let h=G.columns[P];C.push({tsKey:P,value:h})}let T=[];if(J.with)T=Object.entries(J.with).filter((P)=>!!P[1]).map(([P,h])=>({tsKey:P,queryConfig:h,relation:G.relations[P]}));let x2;if(J.extras){x2=typeof J.extras==="function"?J.extras(k,{sql:z}):J.extras;for(let[P,h]of Object.entries(x2))C.push({tsKey:P,value:O6(h,_)})}for(let{tsKey:P,value:h}of C)D.push({dbKey:U(h,E.Aliased)?h.fieldAlias:G.columns[P].name,tsKey:P,field:U(h,Q)?K2(h,_):h,relationTableTsKey:void 0,isJson:!1,selection:[]});let J2=typeof J.orderBy==="function"?J.orderBy(k,r4()):J.orderBy??[];if(!Array.isArray(J2))J2=[J2];F=J2.map((P)=>{if(U(P,Q))return K2(P,_);return b1(P,_)}),A=J.limit,R=J.offset;for(let{tsKey:P,queryConfig:h,relation:w2}of T){let R0=l4($,Z,w2),G6=u2(w2.referencedTable),G1=Z[G6],D2=`${_}_${P}`,F2=m1(...R0.fields.map((s$,a$)=>b(K2(R0.references[a$],D2),K2(s$,_)))),M0=this.buildRelationalQuery({fullSchema:X,schema:$,tableNamesMap:Z,table:X[G1],tableConfig:$[G1],queryConfig:U(w2,h2)?h===!0?{limit:1}:{...h,limit:1}:h,tableAlias:D2,joinOn:F2,nestedQueryRelation:w2}),l$=z`(${M0.sql})`.as(P);D.push({dbKey:P,tsKey:P,field:l$,relationTableTsKey:G1,isJson:!0,selection:M0.selection})}}if(D.length===0)throw new _1({message:`No fields selected for table "${G.tsName}" ("${_}"). 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 x;if(M=m1(H,M),W){let k=z`json_array(${z.join(D.map(({field:T})=>U(T,S)?z.identifier(this.casing.getColumnCasing(T)):U(T,E.Aliased)?T.sql:T),z`, `)})`;if(U(W,c1))k=z`coalesce(json_group_array(${k}), json_array())`;let C=[{dbKey:"data",tsKey:"data",field:k.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:D}];if(A!==void 0||R!==void 0||F.length>0)x=this.buildSelectQuery({table:w0(Y,_),fields:{},fieldsFlat:[{path:[],field:z.raw("*")}],where:M,limit:A,offset:R,orderBy:F,setOperators:[]}),M=void 0,A=void 0,R=void 0,F=void 0;else x=w0(Y,_);x=this.buildSelectQuery({table:U(x,u)?x:new m(x,{},_),fields:{},fieldsFlat:C.map(({field:T})=>({path:[],field:U(T,Q)?K2(T,_):T})),joins:K,where:M,limit:A,offset:R,orderBy:F,setOperators:[]})}else x=this.buildSelectQuery({table:w0(Y,_),fields:{},fieldsFlat:D.map(({field:k})=>({path:[],field:U(k,Q)?K2(k,_):k})),joins:K,where:M,limit:A,offset:R,orderBy:F,setOperators:[]});return{tableTsKey:G.tsName,sql:x,selection:D}}}class k6 extends H1{static[O]="SQLiteSyncDialect";migrate(X,$,Z){let Y=Z===void 0?"__drizzle_migrations":typeof Z==="string"?"__drizzle_migrations":Z.migrationsTable??"__drizzle_migrations",G=z`
|
|
3
|
-
CREATE TABLE IF NOT EXISTS ${z.identifier(Y)} (
|
|
4
|
-
id SERIAL PRIMARY KEY,
|
|
5
|
-
hash text NOT NULL,
|
|
6
|
-
created_at numeric
|
|
7
|
-
)
|
|
8
|
-
`;$.run(G);let _=$.values(z`SELECT id, hash, created_at FROM ${z.identifier(Y)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;$.run(z`BEGIN`);try{for(let W of X)if(!_||Number(_[2])<W.folderMillis){for(let H of W.sql)$.run(z.raw(H));$.run(z`INSERT INTO ${z.identifier(Y)} ("hash", "created_at") VALUES(${W.hash}, ${W.folderMillis})`)}$.run(z`COMMIT`)}catch(W){throw $.run(z`ROLLBACK`),W}}}class T6 extends H1{static[O]="SQLiteAsyncDialect";async migrate(X,$,Z){let Y=Z===void 0?"__drizzle_migrations":typeof Z==="string"?"__drizzle_migrations":Z.migrationsTable??"__drizzle_migrations",G=z`
|
|
9
|
-
CREATE TABLE IF NOT EXISTS ${z.identifier(Y)} (
|
|
10
|
-
id SERIAL PRIMARY KEY,
|
|
11
|
-
hash text NOT NULL,
|
|
12
|
-
created_at numeric
|
|
13
|
-
)
|
|
14
|
-
`;await $.run(G);let _=(await $.values(z`SELECT id, hash, created_at FROM ${z.identifier(Y)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await $.transaction(async(W)=>{for(let H of X)if(!_||Number(_[2])<H.folderMillis){for(let D of H.sql)await W.run(z.raw(D));await W.run(z`INSERT INTO ${z.identifier(Y)} ("hash", "created_at") VALUES(${H.hash}, ${H.folderMillis})`)}})}}class j6{static[O]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class A2{static[O]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(X){this.fields=X.fields,this.session=X.session,this.dialect=X.dialect,this.withList=X.withList,this.distinct=X.distinct}from(X){let $=!!this.fields,Z;if(this.fields)Z=this.fields;else if(U(X,m))Z=Object.fromEntries(Object.keys(X._.selectedFields).map((Y)=>[Y,X[Y]]));else if(U(X,o2))Z=X[q].selectedFields;else if(U(X,E))Z={};else Z=w4(X);return new Q6({table:X,fields:Z,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class f8 extends j6{static[O]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:X,fields:$,isPartialSelect:Z,session:Y,dialect:G,withList:J,distinct:_}){super();this.config={withList:J,table:X,fields:{...$},distinct:_,setOperators:[]},this.isPartialSelect=Z,this.session=Y,this.dialect=G,this._={selectedFields:$,config:this.config},this.tableName=d1(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let W of O2(X))this.usedTables.add(W)}getUsedTables(){return[...this.usedTables]}createJoin(X){return($,Z)=>{let Y=this.tableName,G=d1($);for(let J of O2($))this.usedTables.add(J);if(typeof G==="string"&&this.config.joins?.some((J)=>J.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof Y==="string")this.config.fields={[Y]:this.config.fields};if(typeof G==="string"&&!U($,E)){let J=U($,m)?$._.selectedFields:U($,_2)?$[q].selectedFields:$[V.Symbol.Columns];this.config.fields[G]=J}}if(typeof Z==="function")Z=Z(new Proxy(this.config.fields,new c({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:Z,table:$,joinType:X,alias:G}),typeof G==="string")switch(X){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!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(X,$){return(Z)=>{let Y=typeof Z==="function"?Z(OZ()):Z;if(!g1(this.getSelectedFields(),Y.getSelectedFields()))throw 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:X,isAll:$,rightSelect:Y}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(X){return this.config.setOperators.push(...X),this}where(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new c({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=X,this}having(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new c({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=X,this}groupBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.fields,new c({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray($)?$:[$]}else this.config.groupBy=X;return this}orderBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.fields,new c({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}else{let $=X;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}return this}limit(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=X;else this.config.limit=X;return this}offset(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=X;else this.config.offset=X;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}as(X){let $=[];if($.push(...O2(this.config.table)),this.config.joins)for(let Z of this.config.joins)$.push(...O2(Z.table));return new Proxy(new m(this.getSQL(),this.config.fields,X,!1,[...new Set($)]),new c({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new c({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class Q6 extends f8{static[O]="SQLiteSelect";_prepare(X=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let $=W2(this.config.fields),Z=this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),$,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}$withCache(X){return this.cacheConfig=X===void 0?{config:{},enable:!0,autoInvalidate:!0}:X===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...X},this}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(){return this.all()}}x4(Q6,[s]);function L0(X,$){return(Z,Y,...G)=>{let J=[Y,...G].map((_)=>({type:X,isAll:$,rightSelect:_}));for(let _ of J)if(!g1(Z.getSelectedFields(),_.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return Z.addSetOperators(J)}}var OZ=()=>({union:AZ,unionAll:UZ,intersect:VZ,except:FZ}),AZ=L0("union",!1),UZ=L0("union",!0),VZ=L0("intersect",!1),FZ=L0("except",!1);class u1{static[O]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(X){this.dialect=U(X,H1)?X:void 0,this.dialectConfig=U(X,H1)?void 0:X}$with=(X,$)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(Z);return new Proxy(new q1(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new c({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...X){let $=this;function Z(G){return new A2({fields:G??void 0,session:void 0,dialect:$.getDialect(),withList:X})}function Y(G){return new A2({fields:G??void 0,session:void 0,dialect:$.getDialect(),withList:X,distinct:!0})}return{select:Z,selectDistinct:Y}}select(X){return new A2({fields:X??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(X){return new A2({fields:X??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new k6(this.dialectConfig);return this.dialect}}class v0{constructor(X,$,Z,Y){this.table=X,this.session=$,this.dialect=Z,this.withList=Y}static[O]="SQLiteInsertBuilder";values(X){if(X=Array.isArray(X)?X:[X],X.length===0)throw Error("values() must be called with at least one value");let $=X.map((Z)=>{let Y={},G=this.table[V.Symbol.Columns];for(let J of Object.keys(Z)){let _=Z[J];Y[J]=U(_,E)?_:new Y2(_,G[J])}return Y});return new B6(this.table,$,this.session,this.dialect,this.withList)}select(X){let $=typeof X==="function"?X(new u1):X;if(!U($,E)&&!g1(this.table[I0],$._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new B6(this.table,$,this.session,this.dialect,this.withList,!0)}}class B6 extends s{constructor(X,$,Z,Y,G,J){super();this.session=Z,this.dialect=Y,this.config={table:X,values:$,withList:G,select:J}}static[O]="SQLiteInsert";config;returning(X=this.config.table[u.Symbol.Columns]){return this.config.returning=W2(X),this}onConflictDoNothing(X={}){if(!this.config.onConflict)this.config.onConflict=[];if(X.target===void 0)this.config.onConflict.push(z` on conflict do nothing`);else{let $=Array.isArray(X.target)?z`${X.target}`:z`${[X.target]}`,Z=X.where?z` where ${X.where}`:z``;this.config.onConflict.push(z` on conflict ${$} do nothing${Z}`)}return this}onConflictDoUpdate(X){if(X.where&&(X.targetWhere||X.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let $=X.where?z` where ${X.where}`:void 0,Z=X.targetWhere?z` where ${X.targetWhere}`:void 0,Y=X.setWhere?z` where ${X.setWhere}`:void 0,G=Array.isArray(X.target)?z`${X.target}`:z`${[X.target]}`,J=this.dialect.buildUpdateSet(this.config.table,P0(this.config.table,X.set));return this.config.onConflict.push(z` on conflict ${G}${Z} do update set ${J}${$}${Y}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(X=!0){return this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:O2(this.config.table)})}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class C0{constructor(X,$,Z,Y){this.table=X,this.session=$,this.dialect=Z,this.withList=Y}static[O]="SQLiteUpdateBuilder";set(X){return new q8(this.table,P0(this.table,X),this.session,this.dialect,this.withList)}}class q8 extends s{constructor(X,$,Z,Y,G){super();this.session=Z,this.dialect=Y,this.config={set:$,table:X,withList:G,joins:[]}}static[O]="SQLiteUpdate";config;from(X){return this.config.from=X,this}createJoin(X){return($,Z)=>{let Y=d1($);if(typeof Y==="string"&&this.config.joins.some((G)=>G.alias===Y))throw Error(`Alias "${Y}" is already used in this query`);if(typeof Z==="function"){let G=this.config.from?U($,u)?$[V.Symbol.Columns]:U($,m)?$._.selectedFields:U($,o2)?$[q].selectedFields:void 0:void 0;Z=Z(new Proxy(this.config.table[V.Symbol.Columns],new c({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new c({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:Z,table:$,joinType:X,alias:Y}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(X){return this.config.where=X,this}orderBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.table[V.Symbol.Columns],new c({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray($)?$:[$];this.config.orderBy=Z}else{let $=X;this.config.orderBy=$}return this}limit(X){return this.config.limit=X,this}returning(X=this.config.table[u.Symbol.Columns]){return this.config.returning=W2(X),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(X=!0){return this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:O2(this.config.table)})}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class n1 extends E{constructor(X){super(n1.buildEmbeddedCount(X.source,X.filters).queryChunks);this.params=X,this.session=X.session,this.sql=n1.buildCount(X.source,X.filters)}sql;static[O]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(X,$){return z`(select count(*) from ${X}${z.raw(" where ").if($)}${$})`}static buildCount(X,$){return z`select count(*) from ${X}${z.raw(" where ").if($)}${$}`}then(X,$){return Promise.resolve(this.session.count(this.sql)).then(X,$)}catch(X){return this.then(void 0,X)}finally(X){return this.then(($)=>{return X?.(),$},($)=>{throw X?.(),$})}}class v6{constructor(X,$,Z,Y,G,J,_,W){this.mode=X,this.fullSchema=$,this.schema=Z,this.tableNamesMap=Y,this.table=G,this.tableConfig=J,this.dialect=_,this.session=W}static[O]="SQLiteAsyncRelationalQueryBuilder";findMany(X){return this.mode==="sync"?new L6(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many"):new h0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many")}findFirst(X){return this.mode==="sync"?new L6(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first"):new h0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first")}}class h0 extends s{constructor(X,$,Z,Y,G,J,_,W,H){super();this.fullSchema=X,this.schema=$,this.tableNamesMap=Z,this.table=Y,this.tableConfig=G,this.dialect=J,this.session=_,this.config=W,this.mode=H}static[O]="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(X=!1){let{query:$,builtQuery:Z}=this._toSQL();return this.session[X?"prepareOneTimeQuery":"prepareQuery"](Z,void 0,this.mode==="first"?"get":"all",!0,(Y,G)=>{let J=Y.map((_)=>T0(this.schema,this.tableConfig,_,$.selection,G));if(this.mode==="first")return J[0];return J})}prepare(){return this._prepare(!1)}_toSQL(){let X=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}),$=this.dialect.sqlToQuery(X.sql);return{query:X,builtQuery:$}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}}class L6 extends h0{static[O]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class D1 extends s{constructor(X,$,Z,Y,G){super();this.execute=X,this.getSQL=$,this.dialect=Y,this.mapBatchResult=G,this.config={action:Z}}static[O]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(X,$){return $?this.mapBatchResult(X):X}_prepare(){return this}isResponseInArrayMode(){return!1}}class o1{constructor(X,$,Z,Y){this.resultKind=X,this.dialect=$,this.session=Z,this._=Y?{schema:Y.schema,fullSchema:Y.fullSchema,tableNamesMap:Y.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let G=this.query;if(this._.schema)for(let[J,_]of Object.entries(this._.schema))G[J]=new v6(X,Y.fullSchema,this._.schema,this._.tableNamesMap,Y.fullSchema[J],_,$,Z);this.$cache={invalidate:async(J)=>{}}}static[O]="BaseSQLiteDatabase";query;$with=(X,$)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(new u1(Z.dialect));return new Proxy(new q1(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new c({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(X,$){return new n1({source:X,filters:$,session:this.session})}with(...X){let $=this;function Z(W){return new A2({fields:W??void 0,session:$.session,dialect:$.dialect,withList:X})}function Y(W){return new A2({fields:W??void 0,session:$.session,dialect:$.dialect,withList:X,distinct:!0})}function G(W){return new C0(W,$.session,$.dialect,X)}function J(W){return new v0(W,$.session,$.dialect,X)}function _(W){return new B0(W,$.session,$.dialect,X)}return{select:Z,selectDistinct:Y,update:G,insert:J,delete:_}}select(X){return new A2({fields:X??void 0,session:this.session,dialect:this.dialect})}selectDistinct(X){return new A2({fields:X??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(X){return new C0(X,this.session,this.dialect)}$cache;insert(X){return new v0(X,this.session,this.dialect)}delete(X){return new B0(X,this.session,this.dialect)}run(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new D1(async()=>this.session.run($),()=>$,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run($)}all(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new D1(async()=>this.session.all($),()=>$,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all($)}get(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new D1(async()=>this.session.get($),()=>$,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get($)}values(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new D1(async()=>this.session.values($),()=>$,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values($)}transaction(X,$){return this.session.transaction(X,$)}}class y8{static[O]="Cache"}class i1 extends y8{strategy(){return"all"}static[O]="NoopCache";async get(X){return}async put(X,$,Z,Y){}async onMutate(X){}}async function C6(X,$){let Z=`${X}-${JSON.stringify($)}`,G=new TextEncoder().encode(Z),J=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(J)].map((H)=>H.toString(16).padStart(2,"0")).join("")}class S8 extends s{constructor(X){super();this.resultCb=X}static[O]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class h6{constructor(X,$,Z,Y,G,J){if(this.mode=X,this.executeMethod=$,this.query=Z,this.cache=Y,this.queryMetadata=G,this.cacheConfig=J,Y&&Y.strategy()==="all"&&J===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[O]="PreparedQuery";joinsNotNullableMap;async queryWithCache(X,$,Z){if(this.cache===void 0||U(this.cache,i1)||this.queryMetadata===void 0)try{return await Z()}catch(Y){throw new P2(X,$,Y)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await Z()}catch(Y){throw new P2(X,$,Y)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[Y]=await Promise.all([Z(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return Y}catch(Y){throw new P2(X,$,Y)}if(!this.cacheConfig)try{return await Z()}catch(Y){throw new P2(X,$,Y)}if(this.queryMetadata.type==="select"){let Y=await this.cache.get(this.cacheConfig.tag??await C6(X,$),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(Y===void 0){let G;try{G=await Z()}catch(J){throw new P2(X,$,J)}return await this.cache.put(this.cacheConfig.tag??await C6(X,$),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return Y}try{return await Z()}catch(Y){throw new P2(X,$,Y)}}getQuery(){return this.query}mapRunResult(X,$){return X}mapAllResult(X,$){throw Error("Not implemented")}mapGetResult(X,$){throw Error("Not implemented")}execute(X){if(this.mode==="async")return this[this.executeMethod](X);return new S8(()=>this[this.executeMethod](X))}mapResult(X,$){switch(this.executeMethod){case"run":return this.mapRunResult(X,$);case"all":return this.mapAllResult(X,$);case"get":return this.mapGetResult(X,$)}}}class f6{constructor(X){this.dialect=X}static[O]="SQLiteSession";prepareOneTimeQuery(X,$,Z,Y,G,J,_){return this.prepareQuery(X,$,Z,Y,G,J,_)}run(X){let $=this.dialect.sqlToQuery(X);try{return this.prepareOneTimeQuery($,void 0,"run",!1).run()}catch(Z){throw new _1({cause:Z,message:`Failed to run the query '${$.sql}'`})}}extractRawRunValueFromBatchResult(X){return X}all(X){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(X),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(X){throw Error("Not implemented")}get(X){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(X),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(X){throw Error("Not implemented")}values(X){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(X),void 0,"run",!1).values()}async count(X){return(await this.values(X))[0][0]}extractRawValuesValueFromBatchResult(X){throw Error("Not implemented")}}class q6 extends o1{constructor(X,$,Z,Y,G=0){super(X,$,Z,Y);this.schema=Y,this.nestedIndex=G}static[O]="SQLiteTransaction";rollback(){throw new A6}}var h_=X2("memory",{key:N("key").notNull(),namespace:N("namespace").notNull().default("default"),value:N("value").notNull(),timestamp:g("timestamp").notNull(),created_at:N("created_at").notNull(),updated_at:N("updated_at").notNull()},(X)=>({pk:w6({columns:[X.key,X.namespace]}),namespaceIdx:f("idx_memory_namespace").on(X.namespace),timestampIdx:f("idx_memory_timestamp").on(X.timestamp),keyIdx:f("idx_memory_key").on(X.key)})),p8=X2("codebase_files",{path:N("path").primaryKey(),mtime:g("mtime").notNull(),hash:N("hash").notNull(),content:N("content"),language:N("language"),size:g("size"),indexedAt:N("indexed_at").notNull()},(X)=>({mtimeIdx:f("idx_codebase_files_mtime").on(X.mtime),hashIdx:f("idx_codebase_files_hash").on(X.hash)})),f_=X2("tfidf_terms",{filePath:N("file_path").notNull().references(()=>p8.path,{onDelete:"cascade"}),term:N("term").notNull(),frequency:z1("frequency").notNull()},(X)=>({termIdx:f("idx_tfidf_terms_term").on(X.term),fileIdx:f("idx_tfidf_terms_file").on(X.filePath)})),q_=X2("tfidf_documents",{filePath:N("file_path").primaryKey().references(()=>p8.path,{onDelete:"cascade"}),magnitude:z1("magnitude").notNull(),termCount:g("term_count").notNull(),rawTerms:N("raw_terms").notNull()}),y_=X2("tfidf_idf",{term:N("term").primaryKey(),idfValue:z1("idf_value").notNull()}),S_=X2("codebase_metadata",{key:N("key").primaryKey(),value:N("value").notNull()}),v=X2("sessions",{id:N("id").primaryKey(),title:N("title"),provider:N("provider").notNull(),model:N("model").notNull(),nextTodoId:g("next_todo_id").notNull().default(1),created:g("created").notNull(),updated:g("updated").notNull()},(X)=>({updatedIdx:f("idx_sessions_updated").on(X.updated),createdIdx:f("idx_sessions_created").on(X.created),providerIdx:f("idx_sessions_provider").on(X.provider),titleIdx:f("idx_sessions_title").on(X.title)})),a=X2("messages",{id:N("id").primaryKey(),sessionId:N("session_id").notNull().references(()=>v.id,{onDelete:"cascade"}),role:N("role").notNull(),timestamp:g("timestamp").notNull(),ordering:g("ordering").notNull(),finishReason:N("finish_reason"),status:N("status").notNull().default("completed"),metadata:N("metadata")},(X)=>({sessionIdx:f("idx_messages_session").on(X.sessionId),orderingIdx:f("idx_messages_ordering").on(X.sessionId,X.ordering),timestampIdx:f("idx_messages_timestamp").on(X.timestamp),statusIdx:f("idx_messages_status").on(X.status)})),f2=X2("message_parts",{id:N("id").primaryKey(),messageId:N("message_id").notNull().references(()=>a.id,{onDelete:"cascade"}),ordering:g("ordering").notNull(),type:N("type").notNull(),content:N("content").notNull()},(X)=>({messageIdx:f("idx_message_parts_message").on(X.messageId),orderingIdx:f("idx_message_parts_ordering").on(X.messageId,X.ordering),typeIdx:f("idx_message_parts_type").on(X.type)})),f0=X2("message_attachments",{id:N("id").primaryKey(),messageId:N("message_id").notNull().references(()=>a.id,{onDelete:"cascade"}),path:N("path").notNull(),relativePath:N("relative_path").notNull(),size:g("size")},(X)=>({messageIdx:f("idx_message_attachments_message").on(X.messageId),pathIdx:f("idx_message_attachments_path").on(X.path)})),k2=X2("message_usage",{messageId:N("message_id").primaryKey().references(()=>a.id,{onDelete:"cascade"}),promptTokens:g("prompt_tokens").notNull(),completionTokens:g("completion_tokens").notNull(),totalTokens:g("total_tokens").notNull()}),i2=X2("todos",{id:g("id").notNull(),sessionId:N("session_id").notNull().references(()=>v.id,{onDelete:"cascade"}),content:N("content").notNull(),activeForm:N("active_form").notNull(),status:N("status").notNull(),ordering:g("ordering").notNull()},(X)=>({pk:w6({columns:[X.sessionId,X.id]}),sessionIdx:f("idx_todos_session").on(X.sessionId),statusIdx:f("idx_todos_status").on(X.status),orderingIdx:f("idx_todos_ordering").on(X.sessionId,X.ordering)})),r1=X2("message_todo_snapshots",{id:N("id").primaryKey(),messageId:N("message_id").notNull().references(()=>a.id,{onDelete:"cascade"}),todoId:g("todo_id").notNull(),content:N("content").notNull(),activeForm:N("active_form").notNull(),status:N("status").notNull(),ordering:g("ordering").notNull()},(X)=>({messageIdx:f("idx_message_todo_snapshots_message").on(X.messageId)}));async function O1(X,$=5){let Z;for(let Y=0;Y<$;Y++)try{return await X()}catch(G){if(Z=G,G.message?.includes("SQLITE_BUSY")||G.code==="SQLITE_BUSY"){let J=50*Math.pow(2,Y);await new Promise((_)=>setTimeout(_,J));continue}throw G}throw Z}class A1{db;constructor(X){this.db=X}async createSession(X,$){let Z=Date.now(),Y=`session-${Z}`,G={id:Y,provider:X,model:$,nextTodoId:1,created:Z,updated:Z};return await this.db.insert(v).values(G),{id:Y,provider:X,model:$,messages:[],todos:[],nextTodoId:1,created:Z,updated:Z}}async createSessionFromData(X){await O1(async()=>{let $={id:X.id,title:X.title||null,provider:X.provider,model:X.model,nextTodoId:X.nextTodoId,created:X.created,updated:X.updated};await this.db.insert(v).values($)})}async getRecentSessions(X=20,$=0){let Z=await this.db.select().from(v).orderBy(W1(v.updated)).limit(X).offset($);return(await Promise.all(Z.map((G)=>this.getSessionById(G.id)))).filter((G)=>G!==null)}async getSessionById(X){let[$]=await this.db.select().from(v).where(b(v.id,X)).limit(1);if(!$)return null;let Z=await this.getSessionMessages(X),Y=await this.getSessionTodos(X);return{id:$.id,title:$.title||void 0,provider:$.provider,model:$.model,messages:Z,todos:Y,nextTodoId:$.nextTodoId,created:$.created,updated:$.updated}}async getSessionMessages(X){let $=await this.db.select().from(a).where(b(a.sessionId,X)).orderBy(a.ordering);if($.length===0)return[];let Z=$.map((F)=>F.id),[Y,G,J,_]=await Promise.all([this.db.select().from(f2).where(n2(f2.messageId,Z)).orderBy(f2.ordering),this.db.select().from(f0).where(n2(f0.messageId,Z)),this.db.select().from(k2).where(n2(k2.messageId,Z)),this.db.select().from(r1).where(n2(r1.messageId,Z)).orderBy(r1.ordering)]),W=new Map,H=new Map,D=new Map,A=new Map;for(let F of Y){if(!W.has(F.messageId))W.set(F.messageId,[]);W.get(F.messageId).push(F)}for(let F of G){if(!H.has(F.messageId))H.set(F.messageId,[]);H.get(F.messageId).push(F)}for(let F of J)D.set(F.messageId,F);for(let F of _){if(!A.has(F.messageId))A.set(F.messageId,[]);A.get(F.messageId).push(F)}return $.map((F)=>{let M=W.get(F.id)||[],K=H.get(F.id)||[],x=D.get(F.id),k=A.get(F.id)||[],C={role:F.role,content:M.map((L)=>JSON.parse(L.content)),timestamp:F.timestamp,status:F.status||"completed"};if(F.metadata)C.metadata=JSON.parse(F.metadata);if(K.length>0){let L=K.filter((T)=>T&&typeof T==="object"&&T.path&&T.relativePath);if(L.length>0)C.attachments=L.map((T)=>({path:T.path,relativePath:T.relativePath,size:T.size||void 0}))}if(x)C.usage={promptTokens:x.promptTokens,completionTokens:x.completionTokens,totalTokens:x.totalTokens};if(F.finishReason)C.finishReason=F.finishReason;if(k.length>0)C.todoSnapshot=k.map((L)=>({id:L.todoId,content:L.content,activeForm:L.activeForm,status:L.status,ordering:L.ordering}));return C})}async getSessionTodos(X){return(await this.db.select().from(i2).where(b(i2.sessionId,X)).orderBy(i2.ordering)).map((Z)=>({id:Z.id,content:Z.content,activeForm:Z.activeForm,status:Z.status,ordering:Z.ordering}))}async addMessage(X,$,Z,Y,G,J,_,W,H){return await O1(async()=>{let D=t1(),A=Date.now(),[{count:R}]=await this.db.select({count:z`count(*)`}).from(a).where(b(a.sessionId,X)),F=R;return await this.db.transaction(async(M)=>{await M.insert(a).values({id:D,sessionId:X,role:$,timestamp:A,ordering:F,finishReason:J||null,status:H||"completed",metadata:_?JSON.stringify(_):null});for(let K=0;K<Z.length;K++)await M.insert(f2).values({id:t1(),messageId:D,ordering:K,type:Z[K].type,content:JSON.stringify(Z[K])});if(Y&&Y.length>0)for(let K of Y)await M.insert(f0).values({id:t1(),messageId:D,path:K.path,relativePath:K.relativePath,size:K.size||null});if(G)await M.insert(k2).values({messageId:D,promptTokens:G.promptTokens,completionTokens:G.completionTokens,totalTokens:G.totalTokens});if(W&&W.length>0)for(let K of W)await M.insert(r1).values({id:t1(),messageId:D,todoId:K.id,content:K.content,activeForm:K.activeForm,status:K.status,ordering:K.ordering});await M.update(v).set({updated:A}).where(b(v.id,X))}),D})}async updateSessionTitle(X,$){await this.db.update(v).set({title:$,updated:Date.now()}).where(b(v.id,X))}async updateSessionModel(X,$){await this.db.update(v).set({model:$,updated:Date.now()}).where(b(v.id,X))}async updateSessionProvider(X,$,Z){await this.db.update(v).set({provider:$,model:Z,updated:Date.now()}).where(b(v.id,X))}async updateMessageParts(X,$){await O1(async()=>{await this.db.transaction(async(Z)=>{await Z.delete(f2).where(b(f2.messageId,X));for(let Y=0;Y<$.length;Y++)await Z.insert(f2).values({id:t1(),messageId:X,ordering:Y,type:$[Y].type,content:JSON.stringify($[Y])})})})}async updateMessageStatus(X,$,Z){await O1(async()=>{let Y={status:$};if(Z!==void 0)Y.finishReason=Z||null;await this.db.update(a).set(Y).where(b(a.id,X))})}async updateMessageUsage(X,$){await O1(async()=>{let[Z]=await this.db.select().from(k2).where(b(k2.messageId,X)).limit(1);if(Z)await this.db.update(k2).set({promptTokens:$.promptTokens,completionTokens:$.completionTokens,totalTokens:$.totalTokens}).where(b(k2.messageId,X));else await this.db.insert(k2).values({messageId:X,promptTokens:$.promptTokens,completionTokens:$.completionTokens,totalTokens:$.totalTokens})})}async deleteSession(X){await this.db.delete(v).where(b(v.id,X))}async searchSessionsByTitle(X,$=20){let Z=await this.db.select().from(v).where(k0(v.title,`%${X}%`)).orderBy(W1(v.updated)).limit($);return(await Promise.all(Z.map((G)=>this.getSessionById(G.id)))).filter((G)=>G!==null)}async getSessionCount(){let[{count:X}]=await this.db.select({count:z`count(*)`}).from(v);return X}async getMessageCount(X){let[{count:$}]=await this.db.select({count:z`count(*)`}).from(a).where(b(a.sessionId,X));return $}async getLastSession(){let[X]=await this.db.select().from(v).orderBy(W1(v.updated)).limit(1);if(!X)return null;return this.getSessionById(X.id)}async updateTodos(X,$,Z){await O1(async()=>{await this.db.transaction(async(Y)=>{await Y.delete(i2).where(b(i2.sessionId,X));for(let G of $)await Y.insert(i2).values({id:G.id,sessionId:X,content:G.content,activeForm:G.activeForm,status:G.status,ordering:G.ordering});await Y.update(v).set({nextTodoId:Z,updated:Date.now()}).where(b(v.id,X))})})}}import{join as Y1}from"node:path";import{homedir as o$}from"node:os";import{readdir as $6,mkdir as XG,readFile as $G,unlink as i$}from"node:fs/promises";import{existsSync as r$}from"node:fs";class w extends Error{code;rawCode;constructor(X,$,Z,Y){if($!==void 0)X=`${$}: ${X}`;super(X,{cause:Y});this.code=$,this.rawCode=Z,this.name="LibsqlError"}}function b8(X){let $=KZ.exec(X);if($===null)throw new w(`The URL '${X}' is not in a valid format`,"URL_INVALID");let Z=$.groups,Y=Z.scheme,G=Z.authority!==void 0?EZ(Z.authority):void 0,J=r2(Z.path),_=Z.query!==void 0?MZ(Z.query):void 0,W=Z.fragment!==void 0?r2(Z.fragment):void 0;return{scheme:Y,authority:G,path:J,query:_,fragment:W}}var KZ=(()=>{return new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su")})();function EZ(X){let $=RZ.exec(X);if($===null)throw new w("The authority part of the URL is not in a valid format","URL_INVALID");let Z=$.groups,Y=r2(Z.host_br??Z.host),G=Z.port?parseInt(Z.port,10):void 0,J=Z.username!==void 0?{username:r2(Z.username),password:Z.password!==void 0?r2(Z.password):void 0}:void 0;return{host:Y,port:G,userinfo:J}}var RZ=(()=>{return new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su")})();function MZ(X){let $=X.split("&"),Z=[];for(let Y of $){if(Y==="")continue;let G,J,_=Y.indexOf("=");if(_<0)G=Y,J="";else G=Y.substring(0,_),J=Y.substring(_+1);Z.push({key:r2(G.replaceAll("+"," ")),value:r2(J.replaceAll("+"," "))})}return{pairs:Z}}function r2(X){try{return decodeURIComponent(X)}catch($){if($ instanceof URIError)throw new w(`URL component has invalid percent encoding: ${$}`,"URL_INVALID",void 0,$);throw $}}function l1(X,$,Z){if($===void 0)throw new w(`URL with scheme ${JSON.stringify(X+":")} requires authority (the "//" part)`,"URL_INVALID");let Y=`${X}:`,G=NZ($.host),J=IZ($.port),W=`//${xZ($.userinfo)}${G}${J}`,H=Z.split("/").map(encodeURIComponent).join("/");if(H!==""&&!H.startsWith("/"))H="/"+H;return new URL(`${Y}${W}${H}`)}function NZ(X){return X.includes(":")?`[${encodeURI(X)}]`:encodeURI(X)}function IZ(X){return X!==void 0?`:${X}`:""}function xZ(X){if(X===void 0)return"";let $=encodeURIComponent(X.username),Z=X.password!==void 0?`:${encodeURIComponent(X.password)}`:"";return`${$}${Z}@`}var V1=typeof Buffer==="function",g8=typeof TextDecoder==="function"?new TextDecoder:void 0,d8=typeof TextEncoder==="function"?new TextEncoder:void 0;var s1=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),q0=((X)=>{let $={};return X.forEach((Z,Y)=>$[Z]=Y),$})(s1),wZ=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,t=String.fromCharCode.bind(String),m8=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(X)=>new Uint8Array(Array.prototype.slice.call(X,0)),n8=(X)=>X.replace(/=/g,"").replace(/[+\/]/g,($)=>$=="+"?"-":"_"),o8=(X)=>X.replace(/[^A-Za-z0-9\+\/]/g,""),i8=(X)=>{let $,Z,Y,G,J="",_=X.length%3;for(let W=0;W<X.length;){if((Z=X.charCodeAt(W++))>255||(Y=X.charCodeAt(W++))>255||(G=X.charCodeAt(W++))>255)throw TypeError("invalid character found");$=Z<<16|Y<<8|G,J+=s1[$>>18&63]+s1[$>>12&63]+s1[$>>6&63]+s1[$&63]}return _?J.slice(0,_-3)+"===".substring(_):J},p6=typeof btoa==="function"?(X)=>btoa(X):V1?(X)=>Buffer.from(X,"binary").toString("base64"):i8,y6=V1?(X)=>Buffer.from(X).toString("base64"):(X)=>{let Z=[];for(let Y=0,G=X.length;Y<G;Y+=4096)Z.push(t.apply(null,X.subarray(Y,Y+4096)));return p6(Z.join(""))},y0=(X,$=!1)=>$?n8(y6(X)):y6(X),PZ=(X)=>{if(X.length<2){var $=X.charCodeAt(0);return $<128?X:$<2048?t(192|$>>>6)+t(128|$&63):t(224|$>>>12&15)+t(128|$>>>6&63)+t(128|$&63)}else{var $=65536+(X.charCodeAt(0)-55296)*1024+(X.charCodeAt(1)-56320);return t(240|$>>>18&7)+t(128|$>>>12&63)+t(128|$>>>6&63)+t(128|$&63)}},kZ=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,r8=(X)=>X.replace(kZ,PZ),c8=V1?(X)=>Buffer.from(X,"utf8").toString("base64"):d8?(X)=>y6(d8.encode(X)):(X)=>p6(r8(X)),U1=(X,$=!1)=>$?n8(c8(X)):c8(X),u8=(X)=>U1(X,!0),TZ=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,jZ=(X)=>{switch(X.length){case 4:var $=(7&X.charCodeAt(0))<<18|(63&X.charCodeAt(1))<<12|(63&X.charCodeAt(2))<<6|63&X.charCodeAt(3),Z=$-65536;return t((Z>>>10)+55296)+t((Z&1023)+56320);case 3:return t((15&X.charCodeAt(0))<<12|(63&X.charCodeAt(1))<<6|63&X.charCodeAt(2));default:return t((31&X.charCodeAt(0))<<6|63&X.charCodeAt(1))}},t8=(X)=>X.replace(TZ,jZ),l8=(X)=>{if(X=X.replace(/\s+/g,""),!wZ.test(X))throw TypeError("malformed base64.");X+="==".slice(2-(X.length&3));let $,Z,Y,G=[];for(let J=0;J<X.length;)if($=q0[X.charAt(J++)]<<18|q0[X.charAt(J++)]<<12|(Z=q0[X.charAt(J++)])<<6|(Y=q0[X.charAt(J++)]),Z===64)G.push(t($>>16&255));else if(Y===64)G.push(t($>>16&255,$>>8&255));else G.push(t($>>16&255,$>>8&255,$&255));return G.join("")},b6=typeof atob==="function"?(X)=>atob(o8(X)):V1?(X)=>Buffer.from(X,"base64").toString("binary"):l8,s8=V1?(X)=>m8(Buffer.from(X,"base64")):(X)=>m8(b6(X).split("").map(($)=>$.charCodeAt(0))),a8=(X)=>s8(e8(X)),QZ=V1?(X)=>Buffer.from(X,"base64").toString("utf8"):g8?(X)=>g8.decode(s8(X)):(X)=>t8(b6(X)),e8=(X)=>o8(X.replace(/[-_]/g,($)=>$=="-"?"+":"/")),S6=(X)=>QZ(e8(X)),BZ=(X)=>{if(typeof X!=="string")return!1;let $=X.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test($)||!/[^\s0-9a-zA-Z\-_]/.test($)},XX=(X)=>{return{value:X,enumerable:!1,writable:!0,configurable:!0}},$X=function(){let X=($,Z)=>Object.defineProperty(String.prototype,$,XX(Z));X("fromBase64",function(){return S6(this)}),X("toBase64",function($){return U1(this,$)}),X("toBase64URI",function(){return U1(this,!0)}),X("toBase64URL",function(){return U1(this,!0)}),X("toUint8Array",function(){return a8(this)})},ZX=function(){let X=($,Z)=>Object.defineProperty(Uint8Array.prototype,$,XX(Z));X("toBase64",function($){return y0(this,$)}),X("toBase64URI",function(){return y0(this,!0)}),X("toBase64URL",function(){return y0(this,!0)})},LZ=()=>{$X(),ZX()},F1={version:"3.7.8",VERSION:"3.7.8",atob:b6,atobPolyfill:l8,btoa:p6,btoaPolyfill:i8,fromBase64:S6,toBase64:U1,encode:U1,encodeURI:u8,encodeURL:u8,utob:r8,btou:t8,decode:S6,isValid:BZ,fromUint8Array:y0,toUint8Array:a8,extendString:$X,extendUint8Array:ZX,extendBuiltins:LZ};var R2="https://github.com/libsql/libsql-client-ts#supported-urls";function q2(X){if(X==="write")return"BEGIN IMMEDIATE";else if(X==="read")return"BEGIN TRANSACTION READONLY";else if(X==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class K1{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(X,$,Z,Y,G){this.columns=X,this.columnTypes=$,this.rows=Z,this.rowsAffected=Y,this.lastInsertRowid=G}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(vZ),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function vZ(X){return Array.prototype.map.call(X,CZ)}function CZ(X){if(typeof X==="bigint")return""+X;else if(X instanceof ArrayBuffer)return F1.fromUint8Array(new Uint8Array(X));else return X}var YX=":memory:";function GX(X){return X.scheme==="file"&&(X.path===":memory:"||X.path.startsWith(":memory:?"))}function a1(X,$){if(typeof X!=="object")throw TypeError(`Expected client configuration as object, got ${typeof X}`);let{url:Z,authToken:Y,tls:G,intMode:J,concurrency:_}=X;_=Math.max(0,_||20),J??="number";let W=[];if(Z===YX)Z="file::memory:";let H=b8(Z),D=H.scheme.toLowerCase(),A=D==="file"&&H.path===YX&&H.authority===void 0,R;if(A)R={cache:{values:["shared","private"],update:(x,k)=>W.push(`${x}=${k}`)}};else R={tls:{values:["0","1"],update:(x,k)=>G=k==="1"},authToken:{update:(x,k)=>Y=k}};for(let{key:x,value:k}of H.query?.pairs??[]){if(!Object.hasOwn(R,x))throw new w(`Unsupported URL query parameter ${JSON.stringify(x)}`,"URL_PARAM_NOT_SUPPORTED");let C=R[x];if(C.values!==void 0&&!C.values.includes(k))throw new w(`Unknown value for the "${x}" query argument: ${JSON.stringify(k)}. Supported values are: [${C.values.map((L)=>'"'+L+'"').join(", ")}]`,"URL_INVALID");if(C.update!==void 0)C?.update(x,k)}let F=W.length===0?"":`?${W.join("&")}`,M=H.path+F,K;if(D==="libsql")if(G===!1){if(H.authority?.port===void 0)throw new w('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");K=$?"http":"ws"}else K=$?"https":"wss";else K=D;if(K==="http"||K==="ws")G??=!1;else G??=!0;if(K!=="http"&&K!=="ws"&&K!=="https"&&K!=="wss"&&K!=="file")throw new w(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(H.scheme+":")}. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");if(J!=="number"&&J!=="bigint"&&J!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(J)}`);if(H.fragment!==void 0)throw new w(`URL fragments are not supported: ${JSON.stringify("#"+H.fragment)}`,"URL_INVALID");if(A)return{scheme:"file",tls:!1,path:M,intMode:J,concurrency:_,syncUrl:X.syncUrl,syncInterval:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline,fetch:X.fetch,authToken:void 0,encryptionKey:void 0,authority:void 0};return{scheme:K,tls:G,authority:H.authority,path:M,authToken:Y,intMode:J,concurrency:_,encryptionKey:X.encryptionKey,syncUrl:X.syncUrl,syncInterval:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline,fetch:X.fetch}}var e1=m6(dX(),1);import{Buffer as cX}from"node:buffer";function uX(X){if(X.scheme!=="file")throw new w(`URL scheme ${JSON.stringify(X.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");let $=X.authority;if($!==void 0){let _=$.host.toLowerCase();if(_!==""&&_!=="localhost")throw new w(`Invalid host in file URL: ${JSON.stringify($.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${R2}`,"URL_INVALID");if($.port!==void 0)throw new w("File URL cannot have a port","URL_INVALID");if($.userinfo!==void 0)throw new w("File URL cannot have username and password","URL_INVALID")}let Z=GX(X);if(Z&&X.syncUrl)throw new w(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${X.path}`,"URL_INVALID");let Y=X.path;if(Z)Y=`${X.scheme}:${X.path}`;let G={authToken:X.authToken,encryptionKey:X.encryptionKey,syncUrl:X.syncUrl,syncPeriod:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline},J=new e1.default(Y,G);return i(J,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",X.intMode),new nX(Y,G,J,X.intMode)}class nX{#X;#$;#Z;#Y;closed;protocol;constructor(X,$,Z,Y){this.#X=X,this.#$=$,this.#Z=Z,this.#Y=Y,this.closed=!1,this.protocol="file"}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.#G(),i(this.#J(),Z,this.#Y)}async batch(X,$="deferred"){this.#G();let Z=this.#J();try{i(Z,q2($),this.#Y);let Y=X.map((G)=>{if(!Z.inTransaction)throw new w("The transaction has been rolled back","TRANSACTION_CLOSED");let J=Array.isArray(G)?{sql:G[0],args:G[1]||[]}:G;return i(Z,J,this.#Y)});return i(Z,"COMMIT",this.#Y),Y}finally{if(Z.inTransaction)i(Z,"ROLLBACK",this.#Y)}}async migrate(X){this.#G();let $=this.#J();try{i($,"PRAGMA foreign_keys=off",this.#Y),i($,q2("deferred"),this.#Y);let Z=X.map((Y)=>{if(!$.inTransaction)throw new w("The transaction has been rolled back","TRANSACTION_CLOSED");return i($,Y,this.#Y)});return i($,"COMMIT",this.#Y),Z}finally{if($.inTransaction)i($,"ROLLBACK",this.#Y);i($,"PRAGMA foreign_keys=on",this.#Y)}}async transaction(X="write"){let $=this.#J();return i($,q2(X),this.#Y),this.#Z=null,new oX($,this.#Y)}async executeMultiple(X){this.#G();let $=this.#J();try{return iX($,X)}finally{if($.inTransaction)i($,"ROLLBACK",this.#Y)}}async sync(){this.#G();let X=await this.#J().sync();return{frames_synced:X.frames_synced,frame_no:X.frame_no}}async reconnect(){try{if(!this.closed&&this.#Z!==null)this.#Z.close()}finally{this.#Z=new e1.default(this.#X,this.#$),this.closed=!1}}close(){if(this.closed=!0,this.#Z!==null)this.#Z.close(),this.#Z=null}#G(){if(this.closed)throw new w("The client is closed","CLIENT_CLOSED")}#J(){if(this.#Z===null)this.#Z=new e1.default(this.#X,this.#$);return this.#Z}}class oX{#X;#$;constructor(X,$){this.#X=X,this.#$=$}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.#Z(),i(this.#X,Z,this.#$)}async batch(X){return X.map(($)=>{this.#Z();let Z=Array.isArray($)?{sql:$[0],args:$[1]||[]}:$;return i(this.#X,Z,this.#$)})}async executeMultiple(X){return this.#Z(),iX(this.#X,X)}async rollback(){if(!this.#X.open)return;this.#Z(),i(this.#X,"ROLLBACK",this.#$)}async commit(){this.#Z(),i(this.#X,"COMMIT",this.#$)}close(){if(this.#X.inTransaction)i(this.#X,"ROLLBACK",this.#$)}get closed(){return!this.#X.inTransaction}#Z(){if(this.closed)throw new w("The transaction is closed","TRANSACTION_CLOSED")}}function i(X,$,Z){let Y,G;if(typeof $==="string")Y=$,G=[];else if(Y=$.sql,Array.isArray($.args))G=$.args.map((J)=>mX(J,Z));else{G={};for(let J in $.args){let _=J[0]==="@"||J[0]==="$"||J[0]===":"?J.substring(1):J;G[_]=mX($.args[J],Z)}}try{let J=X.prepare(Y);J.safeIntegers(!0);let _=!0;try{J.raw(!0)}catch{_=!1}if(_){let W=Array.from(J.columns().map((F)=>F.name)),H=Array.from(J.columns().map((F)=>F.type??"")),D=J.all(G).map((F)=>{return TY(F,W,Z)}),A=0,R=void 0;return new K1(W,H,D,0,void 0)}else{let W=J.run(G),H=W.changes,D=BigInt(W.lastInsertRowid);return new K1([],[],[],H,D)}}catch(J){throw rX(J)}}function TY(X,$,Z){let Y={};Object.defineProperty(Y,"length",{value:X.length});for(let G=0;G<X.length;++G){let J=jY(X[G],Z);Object.defineProperty(Y,G,{value:J});let _=$[G];if(!Object.hasOwn(Y,_))Object.defineProperty(Y,_,{value:J,enumerable:!0,configurable:!0,writable:!0})}return Y}function jY(X,$){if(typeof X==="bigint")if($==="number"){if(X<QY||X>BY)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(X)}else if($==="bigint")return X;else if($==="string")return""+X;else throw Error("Invalid value for IntMode");else if(X instanceof cX)return X.buffer;return X}var QY=-9007199254740991n,BY=9007199254740991n;function mX(X,$){if(typeof X==="number"){if(!Number.isFinite(X))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return X}else if(typeof X==="bigint"){if(X<LY||X>vY)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return X}else if(typeof X==="boolean")switch($){case"bigint":return X?1n:0n;case"string":return X?"1":"0";default:return X?1:0}else if(X instanceof ArrayBuffer)return cX.from(X);else if(X instanceof Date)return X.valueOf();else if(X===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return X}var LY=-9223372036854775808n,vY=9223372036854775807n;function iX(X,$){try{X.exec($)}catch(Z){throw rX(Z)}}function rX(X){if(X instanceof e1.default.SqliteError)return new w(X.message,X.code,X.rawCode,X);return X}class M1{constructor(){this.intMode="number"}intMode}class B extends Error{constructor(X){super(X);this.name="ClientError"}}class I extends B{constructor(X){super(X);this.name="ProtoError"}}class $0 extends B{code;proto;constructor(X,$){super(X);this.name="ResponseError",this.code=$.code,this.proto=$,this.stack=void 0}}class d extends B{constructor(X,$){if($!==void 0){super(`${X}: ${$}`);this.cause=$}else super(X);this.name="ClosedError"}}class Z0 extends B{constructor(X){super(X);this.name="WebSocketUnsupportedError"}}class N1 extends B{constructor(X){super(X);this.name="WebSocketError"}}class s2 extends B{status;constructor(X,$){super(X);this.status=$,this.name="HttpServerError"}}class U2 extends B{constructor(X){super(X);this.name="ProtocolVersionError"}}class l extends B{constructor(X){super(X);this.name="InternalError"}}class I2 extends B{constructor(X){super(X);this.name="MisuseError"}}function $2(X){if(typeof X==="string")return X;throw I1(X,"string")}function G2(X){if(X===null||X===void 0)return;else if(typeof X==="string")return X;throw I1(X,"string or null")}function Q2(X){if(typeof X==="number")return X;throw I1(X,"number")}function p2(X){if(typeof X==="boolean")return X;throw I1(X,"boolean")}function Y0(X){if(Array.isArray(X))return X;throw I1(X,"array")}function n(X){if(X!==null&&typeof X==="object"&&!Array.isArray(X))return X;throw I1(X,"object")}function V2(X,$){return Y0(X).map((Z)=>$(n(Z)))}function I1(X,$){if(X===void 0)return new I(`Expected ${$}, but the property was missing`);let Z=typeof X;if(X===null)Z="null";else if(Array.isArray(X))Z="array";return new I(`Expected ${$}, received ${Z}`)}function a2(X,$){return $(n(X))}class tX{#X;#$;constructor(X){this.#X=X,this.#$=!1}begin(){this.#X.push("{"),this.#$=!0}end(){this.#X.push("}"),this.#$=!1}#Z(X){if(this.#$)this.#X.push('"'),this.#$=!1;else this.#X.push(',"');this.#X.push(X),this.#X.push('":')}string(X,$){this.#Z(X),this.#X.push(JSON.stringify($))}stringRaw(X,$){this.#Z(X),this.#X.push('"'),this.#X.push($),this.#X.push('"')}number(X,$){this.#Z(X),this.#X.push(""+$)}boolean(X,$){this.#Z(X),this.#X.push($?"true":"false")}object(X,$,Z){this.#Z(X),this.begin(),Z(this,$),this.end()}arrayObjects(X,$,Z){this.#Z(X),this.#X.push("[");for(let Y=0;Y<$.length;++Y){if(Y!==0)this.#X.push(",");this.begin(),Z(this,$[Y]),this.end()}this.#X.push("]")}}function G0(X,$){let Z=[],Y=new tX(Z);return Y.begin(),$(Y,X),Y.end(),Z.join("")}var e2=0,J0=1,_0=2;var lX=5;class sX{#X;#$;#Z;constructor(X){this.#X=X,this.#$=new DataView(X.buffer,X.byteOffset,X.byteLength),this.#Z=0}varint(){let X=0;for(let $=0;;$+=7){let Z=this.#X[this.#Z++];if(X|=(Z&127)<<$,!(Z&128))break}return X}varintBig(){let X=0n;for(let $=0n;;$+=7n){let Z=this.#X[this.#Z++];if(X|=BigInt(Z&127)<<$,!(Z&128))break}return X}bytes(X){let $=new Uint8Array(this.#X.buffer,this.#X.byteOffset+this.#Z,X);return this.#Z+=X,$}double(){let X=this.#$.getFloat64(this.#Z,!0);return this.#Z+=8,X}skipVarint(){for(;;)if(!(this.#X[this.#Z++]&128))break}skip(X){this.#Z+=X}eof(){return this.#Z>=this.#X.byteLength}}class aX{#X;#$;constructor(X){this.#X=X,this.#$=-1}setup(X){this.#$=X}#Z(X){if(this.#$!==X)throw new I(`Expected wire type ${X}, got ${this.#$}`);this.#$=-1}bytes(){this.#Z(_0);let X=this.#X.varint();return this.#X.bytes(X)}string(){return new TextDecoder().decode(this.bytes())}message(X){return b2(this.bytes(),X)}int32(){return this.#Z(e2),this.#X.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#Z(e2),this.#X.varintBig()}sint64(){let X=this.uint64();return X>>1n^-(X&1n)}double(){return this.#Z(J0),this.#X.double()}maybeSkip(){if(this.#$<0)return;else if(this.#$===e2)this.#X.skipVarint();else if(this.#$===J0)this.#X.skip(8);else if(this.#$===_0){let X=this.#X.varint();this.#X.skip(X)}else if(this.#$===lX)this.#X.skip(4);else throw new I(`Unexpected wire type ${this.#$}`);this.#$=-1}}function b2(X,$){let Z=new sX(X),Y=new aX(Z),G=$.default();while(!Z.eof()){let J=Z.varint(),_=J>>3,W=J&7;Y.setup(W);let H=$[_];if(H!==void 0){let D=H(Y,G);if(D!==void 0)G=D}Y.maybeSkip()}return G}class c6{#X;#$;#Z;#Y;constructor(){this.#X=new ArrayBuffer(256),this.#$=new Uint8Array(this.#X),this.#Z=new DataView(this.#X),this.#Y=0}#G(X){if(this.#Y+X<=this.#X.byteLength)return;let $=this.#X.byteLength;while($<this.#Y+X)$*=2;let Z=new ArrayBuffer($),Y=new Uint8Array(Z),G=new DataView(Z);Y.set(new Uint8Array(this.#X,0,this.#Y)),this.#X=Z,this.#$=Y,this.#Z=G}#J(X){this.#G(5),X=0|X;do{let $=X&127;X>>>=7,$|=X?128:0,this.#$[this.#Y++]=$}while(X)}#W(X){this.#G(10),X=X&0xffffffffffffffffn;do{let $=Number(X&0x7fn);X>>=7n,$|=X?128:0,this.#$[this.#Y++]=$}while(X)}#_(X,$){this.#J(X<<3|$)}bytes(X,$){this.#_(X,_0),this.#J($.byteLength),this.#G($.byteLength),this.#$.set($,this.#Y),this.#Y+=$.byteLength}string(X,$){this.bytes(X,new TextEncoder().encode($))}message(X,$,Z){let Y=new c6;Z(Y,$),this.bytes(X,Y.data())}int32(X,$){this.#_(X,e2),this.#J($)}uint32(X,$){this.int32(X,$)}bool(X,$){this.int32(X,$?1:0)}sint64(X,$){this.#_(X,e2),this.#W($<<1n^$>>63n)}double(X,$){this.#_(X,J0),this.#G(8),this.#Z.setFloat64(this.#Y,$,!0),this.#Y+=8}data(){return new Uint8Array(this.#X,0,this.#Y)}}function W0(X,$){let Z=new c6;return $(Z,X),Z.data()}class g2{#X;#$;constructor(){this.#X=new Set,this.#$=new Set}alloc(){for(let $ of this.#$){if(this.#$.delete($),this.#X.add($),!this.#X.has(this.#X.size-1))this.#$.add(this.#X.size-1);return $}let X=this.#X.size;return this.#X.add(X),X}free(X){if(!this.#X.delete(X))throw new l("Freeing an id that is not allocated");if(this.#$.delete(this.#X.size),X<this.#X.size)this.#$.add(X)}}function j(X,$){throw new l($)}function x1(X){if(X===null)return null;else if(typeof X==="string")return X;else if(typeof X==="number"){if(!Number.isFinite(X))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return X}else if(typeof X==="bigint"){if(X<hY||X>fY)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return X}else if(typeof X==="boolean")return X?1n:0n;else if(X instanceof ArrayBuffer)return new Uint8Array(X);else if(X instanceof Uint8Array)return X;else if(X instanceof Date)return+X.valueOf();else if(typeof X==="object")return""+X.toString();else throw TypeError("Unsupported type of value")}var hY=-9223372036854775808n,fY=9223372036854775807n;function u6(X,$){if(X===null)return null;else if(typeof X==="number")return X;else if(typeof X==="string")return X;else if(typeof X==="bigint")if($==="number"){let Z=Number(X);if(!Number.isSafeInteger(Z))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return Z}else if($==="bigint")return X;else if($==="string")return""+X;else throw new I2("Invalid value for IntMode");else if(X instanceof Uint8Array)return X.slice().buffer;else if(X===void 0)throw new I("Received unrecognized type of Value");else throw j(X,"Impossible type of Value")}function X1(X){return{affectedRowCount:X.affectedRowCount,lastInsertRowid:X.lastInsertRowid,columnNames:X.cols.map(($)=>$.name),columnDecltypes:X.cols.map(($)=>$.decltype)}}function g0(X,$){let Z=X1(X),Y=X.rows.map((G)=>eX(Z.columnNames,G,$));return{...Z,rows:Y}}function d0(X,$){let Z=X1(X),Y;if(X.rows.length>0)Y=eX(Z.columnNames,X.rows[0],$);return{...Z,row:Y}}function m0(X,$){let Z=X1(X),Y;if(X.rows.length>0&&Z.columnNames.length>0)Y=u6(X.rows[0][0],$);return{...Z,value:Y}}function eX(X,$,Z){let Y={};Object.defineProperty(Y,"length",{value:$.length});for(let G=0;G<$.length;++G){let J=u6($[G],Z);Object.defineProperty(Y,G,{value:J});let _=X[G];if(_!==void 0&&!Object.hasOwn(Y,_))Object.defineProperty(Y,_,{value:J,enumerable:!0,configurable:!0,writable:!0})}return Y}function B2(X){return new $0(X.message,X)}class $1{#X;#$;#Z;constructor(X,$){this.#X=X,this.#$=$,this.#Z=void 0}_getSqlId(X){if(this.#X!==X)throw new I2("Attempted to use SQL text opened with other object");else if(this.#Z!==void 0)throw new d("SQL text is closed",this.#Z);return this.#$}close(){this._setClosed(new B("SQL text was manually closed"))}_setClosed(X){if(this.#Z===void 0)this.#Z=X,this.#X._closeSql(this.#$)}get closed(){return this.#Z!==void 0}}function z0(X,$){if($ instanceof $1)return{sqlId:$._getSqlId(X)};else return{sql:""+$}}class d2{#X;#$;constructor(){this.#X=[],this.#$=[]}get length(){return this.#X.length+this.#$.length}push(X){this.#X.push(X)}shift(){if(this.#$.length===0&&this.#X.length>0)this.#$=this.#X.reverse(),this.#X=[];return this.#$.pop()}first(){return this.#$.length!==0?this.#$[this.#$.length-1]:this.#X[0]}}class H0{sql;_args;_namedArgs;constructor(X){this.sql=X,this._args=[],this._namedArgs=new Map}bindIndexes(X){this._args.length=0;for(let $ of X)this._args.push(x1($));return this}bindIndex(X,$){if(X!==(X|0)||X<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<X)this._args.push(null);return this._args[X-1]=x1($),this}bindName(X,$){return this._namedArgs.set(X,x1($)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function c0(X,$,Z){let Y,G=[],J=[];if($ instanceof H0){Y=$.sql,G=$._args;for(let[H,D]of $._namedArgs.entries())J.push({name:H,value:D})}else if(Array.isArray($))if(Y=$[0],Array.isArray($[1]))G=$[1].map((H)=>x1(H));else J=Object.entries($[1]).map(([H,D])=>{return{name:H,value:x1(D)}});else Y=$;let{sql:_,sqlId:W}=z0(X,Y);return{sql:_,sqlId:W,args:G,namedArgs:J,wantRows:Z}}class u0{_stream;#X;_steps;#$;constructor(X,$){this._stream=X,this.#X=$,this._steps=[],this.#$=!1}step(){return new n6(this)}execute(){if(this.#$)throw new I2("This batch has already been executed");this.#$=!0;let X={steps:this._steps.map(($)=>$.proto)};if(this.#X)return yY(this._stream,this._steps,X);else return qY(this._stream,this._steps,X)}}function qY(X,$,Z){return X._batch(Z).then((Y)=>{for(let G=0;G<$.length;++G){let J=Y.stepResults.get(G),_=Y.stepErrors.get(G);$[G].callback(J,_)}})}async function yY(X,$,Z){let Y=await X._openCursor(Z);try{let G=0,J=void 0,_=[];for(;;){let W=await Y.next();if(W===void 0)break;if(W.type==="step_begin"){if(W.step<G||W.step>=$.length)throw new I("Server produced StepBeginEntry for unexpected step");else if(J!==void 0)throw new I("Server produced StepBeginEntry before terminating previous step");for(let H=G;H<W.step;++H)$[H].callback(void 0,void 0);G=W.step+1,J=W,_=[]}else if(W.type==="step_end"){if(J===void 0)throw new I("Server produced StepEndEntry but no step is active");let H={cols:J.cols,rows:_,affectedRowCount:W.affectedRowCount,lastInsertRowid:W.lastInsertRowid};$[J.step].callback(H,void 0),J=void 0,_=[]}else if(W.type==="step_error"){if(J===void 0){if(W.step>=$.length)throw new I("Server produced StepErrorEntry for unexpected step");for(let H=G;H<W.step;++H)$[H].callback(void 0,void 0)}else{if(W.step!==J.step)throw new I("Server produced StepErrorEntry for unexpected step");J=void 0,_=[]}$[W.step].callback(void 0,W.error),G=W.step+1}else if(W.type==="row"){if(J===void 0)throw new I("Server produced RowEntry but no step is active");_.push(W.row)}else if(W.type==="error")throw B2(W.error);else if(W.type==="none")throw new I("Server produced unrecognized CursorEntry");else throw j(W,"Impossible CursorEntry")}if(J!==void 0)throw new I("Server closed Cursor before terminating active step");for(let W=G;W<$.length;++W)$[W].callback(void 0,void 0)}finally{Y.close()}}class n6{_batch;#X;_index;constructor(X){this._batch=X,this.#X=[],this._index=void 0}condition(X){return this.#X.push(X._proto),this}query(X){return this.#$(X,!0,g0)}queryRow(X){return this.#$(X,!0,d0)}queryValue(X){return this.#$(X,!0,m0)}run(X){return this.#$(X,!1,X1)}#$(X,$,Z){if(this._index!==void 0)throw new I2("This BatchStep has already been added to the batch");let Y=c0(this._batch._stream._sqlOwner(),X,$),G;if(this.#X.length===0)G=void 0;else if(this.#X.length===1)G=this.#X[0];else G={type:"and",conds:this.#X.slice()};let J={stmt:Y,condition:G};return new Promise((_,W)=>{let H=(D,A)=>{if(D!==void 0&&A!==void 0)W(new I("Server returned both result and error"));else if(A!==void 0)W(B2(A));else if(D!==void 0)_(Z(D,this._batch._stream.intMode));else _(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:J,callback:H})})}}class y{_batch;_proto;constructor(X,$){this._batch=X,this._proto=$}static ok(X){return new y(X._batch,{type:"ok",step:X$(X)})}static error(X){return new y(X._batch,{type:"error",step:X$(X)})}static not(X){return new y(X._batch,{type:"not",cond:X._proto})}static and(X,$){for(let Z of $)$$(X,Z);return new y(X,{type:"and",conds:$.map((Z)=>Z._proto)})}static or(X,$){for(let Z of $)$$(X,Z);return new y(X,{type:"or",conds:$.map((Z)=>Z._proto)})}static isAutocommit(X){return X._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new y(X,{type:"is_autocommit"})}}function X$(X){if(X._index===void 0)throw new I2("Cannot add a condition referencing a step that has not been added to the batch");return X._index}function $$(X,$){if($._batch!==X)throw new I2("Cannot mix BatchCond objects for different Batch objects")}function Z$(X){return{paramNames:X.params.map(($)=>$.name),columns:X.cols,isExplain:X.isExplain,isReadonly:X.isReadonly}}class w1{constructor(X){this.intMode=X}query(X){return this.#X(X,!0,g0)}queryRow(X){return this.#X(X,!0,d0)}queryValue(X){return this.#X(X,!0,m0)}run(X){return this.#X(X,!1,X1)}#X(X,$,Z){let Y=c0(this._sqlOwner(),X,$);return this._execute(Y).then((G)=>Z(G,this.intMode))}batch(X=!1){return new u0(this,X)}describe(X){let $=z0(this._sqlOwner(),X);return this._describe($).then(Z$)}sequence(X){let $=z0(this._sqlOwner(),X);return this._sequence($)}intMode}class D0{}var SY=1000,pY=10;class o6 extends D0{#X;#$;#Z;#Y;#G;#J;#W;constructor(X,$,Z){super();this.#X=X,this.#$=$,this.#Z=Z,this.#Y=new d2,this.#G=new d2,this.#J=void 0,this.#W=!1}async next(){for(;;){if(this.#J!==void 0)throw new d("Cursor is closed",this.#J);while(!this.#W&&this.#G.length<pY)this.#G.push(this.#_());let X=this.#Y.shift();if(this.#W||X!==void 0)return X;await this.#G.shift().then(($)=>{if($===void 0)return;for(let Z of $.entries)this.#Y.push(Z);this.#W||=$.done})}}#_(){return this.#$._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#Z,maxCount:SY}).then((X)=>X,(X)=>{this._setClosed(X);return})}_setClosed(X){if(this.#J!==void 0)return;this.#J=X,this.#$._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#Z}).catch(()=>{return}),this.#$._cursorClosed(this)}close(){this._setClosed(new B("Cursor was manually closed"))}get closed(){return this.#J!==void 0}}class O0 extends w1{#X;#$;#Z;#Y;#G;#J;static open(X){let $=X._streamIdAlloc.alloc(),Z=new O0(X,$),Y=()=>{return},G=(_)=>Z.#H(_),J={type:"open_stream",streamId:$};return X._sendRequest(J,{responseCallback:Y,errorCallback:G}),Z}constructor(X,$){super(X.intMode);this.#X=X,this.#$=$,this.#Z=new d2,this.#Y=void 0,this.#G=!1,this.#J=void 0}client(){return this.#X}_sqlOwner(){return this.#X}_execute(X){return this.#W({type:"execute",streamId:this.#$,stmt:X}).then(($)=>{return $.result})}_batch(X){return this.#W({type:"batch",streamId:this.#$,batch:X}).then(($)=>{return $.result})}_describe(X){return this.#X._ensureVersion(2,"describe()"),this.#W({type:"describe",streamId:this.#$,sql:X.sql,sqlId:X.sqlId}).then(($)=>{return $.result})}_sequence(X){return this.#X._ensureVersion(2,"sequence()"),this.#W({type:"sequence",streamId:this.#$,sql:X.sql,sqlId:X.sqlId}).then(($)=>{return})}getAutocommit(){return this.#X._ensureVersion(3,"getAutocommit()"),this.#W({type:"get_autocommit",streamId:this.#$}).then((X)=>{return X.isAutocommit})}#W(X){return new Promise(($,Z)=>{this.#_({type:"request",request:X,responseCallback:$,errorCallback:Z})})}_openCursor(X){return this.#X._ensureVersion(3,"cursor"),new Promise(($,Z)=>{this.#_({type:"cursor",batch:X,cursorCallback:$,errorCallback:Z})})}_sendCursorRequest(X,$){if(X!==this.#Y)throw new l("Cursor not associated with the stream attempted to execute a request");return new Promise((Z,Y)=>{if(this.#J!==void 0)Y(new d("Stream is closed",this.#J));else this.#X._sendRequest($,{responseCallback:Z,errorCallback:Y})})}_cursorClosed(X){if(X!==this.#Y)throw new l("Cursor was closed, but it was not associated with the stream");this.#Y=void 0,this.#z()}#_(X){if(this.#J!==void 0)X.errorCallback(new d("Stream is closed",this.#J));else if(this.#G)X.errorCallback(new d("Stream is closing",void 0));else this.#Z.push(X),this.#z()}#z(){for(;;){let X=this.#Z.first();if(X===void 0&&this.#Y===void 0&&this.#G){this.#H(new B("Stream was gracefully closed"));break}else if(X?.type==="request"&&this.#Y===void 0){let{request:$,responseCallback:Z,errorCallback:Y}=X;this.#Z.shift(),this.#X._sendRequest($,{responseCallback:Z,errorCallback:Y})}else if(X?.type==="cursor"&&this.#Y===void 0){let{batch:$,cursorCallback:Z}=X;this.#Z.shift();let Y=this.#X._cursorIdAlloc.alloc(),G=new o6(this.#X,this,Y),J={type:"open_cursor",streamId:this.#$,cursorId:Y,batch:$},_=()=>{return},W=(H)=>G._setClosed(H);this.#X._sendRequest(J,{responseCallback:_,errorCallback:W}),this.#Y=G,Z(G)}else break}}#H(X){if(this.#J!==void 0)return;if(this.#J=X,this.#Y!==void 0)this.#Y._setClosed(X);for(;;){let G=this.#Z.shift();if(G!==void 0)G.errorCallback(X);else break}let $={type:"close_stream",streamId:this.#$},Z=()=>this.#X._streamIdAlloc.free(this.#$),Y=()=>{return};this.#X._sendRequest($,{responseCallback:Z,errorCallback:Y})}close(){this.#H(new B("Stream was manually closed"))}closeGracefully(){this.#G=!0,this.#z()}get closed(){return this.#J!==void 0||this.#G}}function A0(X,$){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId);X.arrayObjects("args",$.args,Y$),X.arrayObjects("named_args",$.namedArgs,bY),X.boolean("want_rows",$.wantRows)}function bY(X,$){X.string("name",$.name),X.object("value",$.value,Y$)}function P1(X,$){X.arrayObjects("steps",$.steps,gY)}function gY(X,$){if($.condition!==void 0)X.object("condition",$.condition,i6);X.object("stmt",$.stmt,A0)}function i6(X,$){if(X.stringRaw("type",$.type),$.type==="ok"||$.type==="error")X.number("step",$.step);else if($.type==="not")X.object("cond",$.cond,i6);else if($.type==="and"||$.type==="or")X.arrayObjects("conds",$.conds,i6);else if($.type==="is_autocommit");else throw j($,"Impossible type of BatchCond")}function Y$(X,$){if($===null)X.stringRaw("type","null");else if(typeof $==="bigint")X.stringRaw("type","integer"),X.stringRaw("value",""+$);else if(typeof $==="number")X.stringRaw("type","float"),X.number("value",$);else if(typeof $==="string")X.stringRaw("type","text"),X.string("value",$);else if($ instanceof Uint8Array)X.stringRaw("type","blob"),X.stringRaw("base64",F1.fromUint8Array($));else if($===void 0);else throw j($,"Impossible type of Value")}function G$(X,$){if(X.stringRaw("type",$.type),$.type==="hello"){if($.jwt!==void 0)X.string("jwt",$.jwt)}else if($.type==="request")X.number("request_id",$.requestId),X.object("request",$.request,dY);else throw j($,"Impossible type of ClientMsg")}function dY(X,$){if(X.stringRaw("type",$.type),$.type==="open_stream")X.number("stream_id",$.streamId);else if($.type==="close_stream")X.number("stream_id",$.streamId);else if($.type==="execute")X.number("stream_id",$.streamId),X.object("stmt",$.stmt,A0);else if($.type==="batch")X.number("stream_id",$.streamId),X.object("batch",$.batch,P1);else if($.type==="open_cursor")X.number("stream_id",$.streamId),X.number("cursor_id",$.cursorId),X.object("batch",$.batch,P1);else if($.type==="close_cursor")X.number("cursor_id",$.cursorId);else if($.type==="fetch_cursor")X.number("cursor_id",$.cursorId),X.number("max_count",$.maxCount);else if($.type==="sequence"){if(X.number("stream_id",$.streamId),$.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="describe"){if(X.number("stream_id",$.streamId),$.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="store_sql")X.number("sql_id",$.sqlId),X.string("sql",$.sql);else if($.type==="close_sql")X.number("sql_id",$.sqlId);else if($.type==="get_autocommit")X.number("stream_id",$.streamId);else throw j($,"Impossible type of Request")}function U0(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId);for(let Z of $.args)X.message(3,Z,_$);for(let Z of $.namedArgs)X.message(4,Z,mY);X.bool(5,$.wantRows)}function mY(X,$){X.string(1,$.name),X.message(2,$.value,_$)}function k1(X,$){for(let Z of $.steps)X.message(1,Z,cY)}function cY(X,$){if($.condition!==void 0)X.message(1,$.condition,r6);X.message(2,$.stmt,U0)}function r6(X,$){if($.type==="ok")X.uint32(1,$.step);else if($.type==="error")X.uint32(2,$.step);else if($.type==="not")X.message(3,$.cond,r6);else if($.type==="and")X.message(4,$.conds,J$);else if($.type==="or")X.message(5,$.conds,J$);else if($.type==="is_autocommit")X.message(6,void 0,W$);else throw j($,"Impossible type of BatchCond")}function J$(X,$){for(let Z of $)X.message(1,Z,r6)}function _$(X,$){if($===null)X.message(1,void 0,W$);else if(typeof $==="bigint")X.sint64(2,$);else if(typeof $==="number")X.double(3,$);else if(typeof $==="string")X.string(4,$);else if($ instanceof Uint8Array)X.bytes(5,$);else if($===void 0);else throw j($,"Impossible type of Value")}function W$(X,$){}function z$(X,$){if($.type==="hello")X.message(1,$,uY);else if($.type==="request")X.message(2,$,nY);else throw j($,"Impossible type of ClientMsg")}function uY(X,$){if($.jwt!==void 0)X.string(1,$.jwt)}function nY(X,$){X.int32(1,$.requestId);let Z=$.request;if(Z.type==="open_stream")X.message(2,Z,oY);else if(Z.type==="close_stream")X.message(3,Z,iY);else if(Z.type==="execute")X.message(4,Z,rY);else if(Z.type==="batch")X.message(5,Z,tY);else if(Z.type==="open_cursor")X.message(6,Z,lY);else if(Z.type==="close_cursor")X.message(7,Z,sY);else if(Z.type==="fetch_cursor")X.message(8,Z,aY);else if(Z.type==="sequence")X.message(9,Z,eY);else if(Z.type==="describe")X.message(10,Z,X7);else if(Z.type==="store_sql")X.message(11,Z,$7);else if(Z.type==="close_sql")X.message(12,Z,Z7);else if(Z.type==="get_autocommit")X.message(13,Z,Y7);else throw j(Z,"Impossible type of Request")}function oY(X,$){X.int32(1,$.streamId)}function iY(X,$){X.int32(1,$.streamId)}function rY(X,$){X.int32(1,$.streamId),X.message(2,$.stmt,U0)}function tY(X,$){X.int32(1,$.streamId),X.message(2,$.batch,k1)}function lY(X,$){X.int32(1,$.streamId),X.int32(2,$.cursorId),X.message(3,$.batch,k1)}function sY(X,$){X.int32(1,$.cursorId)}function aY(X,$){X.int32(1,$.cursorId),X.uint32(2,$.maxCount)}function eY(X,$){if(X.int32(1,$.streamId),$.sql!==void 0)X.string(2,$.sql);if($.sqlId!==void 0)X.int32(3,$.sqlId)}function X7(X,$){if(X.int32(1,$.streamId),$.sql!==void 0)X.string(2,$.sql);if($.sqlId!==void 0)X.int32(3,$.sqlId)}function $7(X,$){X.int32(1,$.sqlId),X.string(2,$.sql)}function Z7(X,$){X.int32(1,$.sqlId)}function Y7(X,$){X.int32(1,$.streamId)}function m2(X){let $=$2(X.message),Z=G2(X.code);return{message:$,code:Z}}function V0(X){let $=V2(X.cols,H$),Z=Y0(X.rows).map((_)=>V2(_,D$)),Y=Q2(X.affected_row_count),G=G2(X.last_insert_rowid),J=G!==void 0?BigInt(G):void 0;return{cols:$,rows:Z,affectedRowCount:Y,lastInsertRowid:J}}function H$(X){let $=G2(X.name),Z=G2(X.decltype);return{name:$,decltype:Z}}function n0(X){let $=new Map;Y0(X.step_results).forEach((Y,G)=>{if(Y!==null)$.set(G,V0(n(Y)))});let Z=new Map;return Y0(X.step_errors).forEach((Y,G)=>{if(Y!==null)Z.set(G,m2(n(Y)))}),{stepResults:$,stepErrors:Z}}function o0(X){let $=$2(X.type);if($==="step_begin"){let Z=Q2(X.step),Y=V2(X.cols,H$);return{type:"step_begin",step:Z,cols:Y}}else if($==="step_end"){let Z=Q2(X.affected_row_count),Y=G2(X.last_insert_rowid),G=Y!==void 0?BigInt(Y):void 0;return{type:"step_end",affectedRowCount:Z,lastInsertRowid:G}}else if($==="step_error"){let Z=Q2(X.step),Y=m2(n(X.error));return{type:"step_error",step:Z,error:Y}}else if($==="row")return{type:"row",row:V2(X.row,D$)};else if($==="error")return{type:"error",error:m2(n(X.error))};else throw new I("Unexpected type of CursorEntry")}function i0(X){let $=V2(X.params,G7),Z=V2(X.cols,J7),Y=p2(X.is_explain),G=p2(X.is_readonly);return{params:$,cols:Z,isExplain:Y,isReadonly:G}}function G7(X){return{name:G2(X.name)}}function J7(X){let $=$2(X.name),Z=G2(X.decltype);return{name:$,decltype:Z}}function D$(X){let $=$2(X.type);if($==="null")return null;else if($==="integer"){let Z=$2(X.value);return BigInt(Z)}else if($==="float")return Q2(X.value);else if($==="text")return $2(X.value);else if($==="blob")return F1.toUint8Array($2(X.base64));else throw new I("Unexpected type of Value")}function O$(X){let $=$2(X.type);if($==="hello_ok")return{type:"hello_ok"};else if($==="hello_error")return{type:"hello_error",error:m2(n(X.error))};else if($==="response_ok"){let Z=Q2(X.request_id),Y=_7(n(X.response));return{type:"response_ok",requestId:Z,response:Y}}else if($==="response_error"){let Z=Q2(X.request_id),Y=m2(n(X.error));return{type:"response_error",requestId:Z,error:Y}}else throw new I("Unexpected type of ServerMsg")}function _7(X){let $=$2(X.type);if($==="open_stream")return{type:"open_stream"};else if($==="close_stream")return{type:"close_stream"};else if($==="execute")return{type:"execute",result:V0(n(X.result))};else if($==="batch")return{type:"batch",result:n0(n(X.result))};else if($==="open_cursor")return{type:"open_cursor"};else if($==="close_cursor")return{type:"close_cursor"};else if($==="fetch_cursor"){let Z=V2(X.entries,o0),Y=p2(X.done);return{type:"fetch_cursor",entries:Z,done:Y}}else if($==="sequence")return{type:"sequence"};else if($==="describe")return{type:"describe",result:i0(n(X.result))};else if($==="store_sql")return{type:"store_sql"};else if($==="close_sql")return{type:"close_sql"};else if($==="get_autocommit")return{type:"get_autocommit",isAutocommit:p2(X.is_autocommit)};else throw new I("Unexpected type of Response")}var H2={default(){return{message:"",code:void 0}},1(X,$){$.message=X.string()},2(X,$){$.code=X.string()}},c2={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(X,$){$.cols.push(X.message(A$))},2(X,$){$.rows.push(X.message(U$))},3(X,$){$.affectedRowCount=Number(X.uint64())},4(X,$){$.lastInsertRowid=X.sint64()}},A$={default(){return{name:void 0,decltype:void 0}},1(X,$){$.name=X.string()},2(X,$){$.decltype=X.string()}},U$={default(){return[]},1(X,$){$.push(X.message(V7))}},T1={default(){return{stepResults:new Map,stepErrors:new Map}},1(X,$){let[Z,Y]=X.message(W7);$.stepResults.set(Z,Y)},2(X,$){let[Z,Y]=X.message(z7);$.stepErrors.set(Z,Y)}},W7={default(){return[0,c2.default()]},1(X,$){$[0]=X.uint32()},2(X,$){$[1]=X.message(c2)}},z7={default(){return[0,H2.default()]},1(X,$){$[0]=X.uint32()},2(X,$){$[1]=X.message(H2)}},r0={default(){return{type:"none"}},1(X){return X.message(H7)},2(X){return X.message(D7)},3(X){return X.message(O7)},4(X){return{type:"row",row:X.message(U$)}},5(X){return{type:"error",error:X.message(H2)}}},H7={default(){return{type:"step_begin",step:0,cols:[]}},1(X,$){$.step=X.uint32()},2(X,$){$.cols.push(X.message(A$))}},D7={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(X,$){$.affectedRowCount=X.uint32()},2(X,$){$.lastInsertRowid=X.uint64()}},O7={default(){return{type:"step_error",step:0,error:H2.default()}},1(X,$){$.step=X.uint32()},2(X,$){$.error=X.message(H2)}},j1={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(X,$){$.params.push(X.message(A7))},2(X,$){$.cols.push(X.message(U7))},3(X,$){$.isExplain=X.bool()},4(X,$){$.isReadonly=X.bool()}},A7={default(){return{name:void 0}},1(X,$){$.name=X.string()}},U7={default(){return{name:"",decltype:void 0}},1(X,$){$.name=X.string()},2(X,$){$.decltype=X.string()}},V7={default(){return},1(X){return null},2(X){return X.sint64()},3(X){return X.double()},4(X){return X.string()},5(X){return X.bytes()}};var V$={default(){return{type:"none"}},1(X){return{type:"hello_ok"}},2(X){return X.message(F7)},3(X){return X.message(E7)},4(X){return X.message(K7)}},F7={default(){return{type:"hello_error",error:H2.default()}},1(X,$){$.error=X.message(H2)}},K7={default(){return{type:"response_error",requestId:0,error:H2.default()}},1(X,$){$.requestId=X.int32()},2(X,$){$.error=X.message(H2)}},E7={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(X,$){$.requestId=X.int32()},2(X,$){$.response={type:"open_stream"}},3(X,$){$.response={type:"close_stream"}},4(X,$){$.response=X.message(R7)},5(X,$){$.response=X.message(M7)},6(X,$){$.response={type:"open_cursor"}},7(X,$){$.response={type:"close_cursor"}},8(X,$){$.response=X.message(N7)},9(X,$){$.response={type:"sequence"}},10(X,$){$.response=X.message(I7)},11(X,$){$.response={type:"store_sql"}},12(X,$){$.response={type:"close_sql"}},13(X,$){$.response=X.message(x7)}},R7={default(){return{type:"execute",result:c2.default()}},1(X,$){$.result=X.message(c2)}},M7={default(){return{type:"batch",result:T1.default()}},1(X,$){$.result=X.message(T1)}},N7={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(X,$){$.entries.push(X.message(r0))},2(X,$){$.done=X.bool()}},I7={default(){return{type:"describe",result:j1.default()}},1(X,$){$.result=X.message(j1)}},x7={default(){return{type:"get_autocommit",isAutocommit:!1}},1(X,$){$.isAutocommit=X.bool()}};var F$=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),t6=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);class t0 extends M1{#X;#$;#Z;#Y;#G;#J;#W;#_;#z;_streamIdAlloc;_cursorIdAlloc;#H;constructor(X,$){super();this.#X=X,this.#$=[],this.#Z=!1,this.#Y=void 0,this.#G=!1,this.#J=void 0,this.#W=!1,this.#_=new Map,this.#z=new g2,this._streamIdAlloc=new g2,this._cursorIdAlloc=new g2,this.#H=new g2,this.#X.binaryType="arraybuffer",this.#X.addEventListener("open",()=>this.#V()),this.#X.addEventListener("close",(Z)=>this.#U(Z)),this.#X.addEventListener("error",(Z)=>this.#F(Z)),this.#X.addEventListener("message",(Z)=>this.#E(Z)),this.#O({type:"hello",jwt:$})}#O(X){if(this.#Y!==void 0)throw new l("Trying to send a message on a closed client");if(this.#Z)this.#A(X);else{let $=()=>this.#A(X),Z=()=>{return};this.#$.push({openCallback:$,errorCallback:Z})}}#V(){let X=this.#X.protocol;if(X===void 0){this.#D(new B("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(X==="")this.#J={version:1,encoding:"json"};else if(this.#J=t6.get(X),this.#J===void 0){this.#D(new I(`Unrecognized WebSocket subprotocol: ${JSON.stringify(X)}`));return}for(let $ of this.#$)$.openCallback();this.#$.length=0,this.#Z=!0}#A(X){let $=this.#J.encoding;if($==="json"){let Z=G0(X,G$);this.#X.send(Z)}else if($==="protobuf"){let Z=W0(X,z$);this.#X.send(Z)}else throw j($,"Impossible encoding")}getVersion(){return new Promise((X,$)=>{if(this.#W=!0,this.#Y!==void 0)$(this.#Y);else if(!this.#Z){let Z=()=>X(this.#J.version);this.#$.push({openCallback:Z,errorCallback:$})}else X(this.#J.version)})}_ensureVersion(X,$){if(this.#J===void 0||!this.#W)throw new U2(`${$} is supported only on protocol version ${X} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#J.version<X)throw new U2(`${$} is supported on protocol version ${X} and higher, but the WebSocket server only supports version ${this.#J.version}`)}_sendRequest(X,$){if(this.#Y!==void 0){$.errorCallback(new d("Client is closed",this.#Y));return}let Z=this.#z.alloc();this.#_.set(Z,{...$,type:X.type}),this.#O({type:"request",requestId:Z,request:X})}#F(X){let Z=X.message??"WebSocket was closed due to an error";this.#D(new N1(Z))}#U(X){let $=`WebSocket was closed with code ${X.code}`;if(X.reason)$+=`: ${X.reason}`;this.#D(new N1($))}#D(X){if(this.#Y!==void 0)return;this.#Y=X;for(let $ of this.#$)$.errorCallback(X);this.#$.length=0;for(let[$,Z]of this.#_.entries())Z.errorCallback(X),this.#z.free($);this.#_.clear(),this.#X.close()}#E(X){if(this.#Y!==void 0)return;try{let $,Z=this.#J.encoding;if(Z==="json"){if(typeof X.data!=="string"){this.#X.close(3003,"Only text messages are accepted with JSON encoding"),this.#D(new I("Received non-text message from server with JSON encoding"));return}$=a2(JSON.parse(X.data),O$)}else if(Z==="protobuf"){if(!(X.data instanceof ArrayBuffer)){this.#X.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#D(new I("Received non-binary message from server with Protobuf encoding"));return}$=b2(new Uint8Array(X.data),V$)}else throw j(Z,"Impossible encoding");this.#K($)}catch($){this.#X.close(3007,"Could not handle message"),this.#D($)}}#K(X){if(X.type==="none")throw new I("Received an unrecognized ServerMsg");else if(X.type==="hello_ok"||X.type==="hello_error"){if(this.#G)throw new I("Received a duplicated hello response");if(this.#G=!0,X.type==="hello_error")throw B2(X.error);return}else if(!this.#G)throw new I("Received a non-hello message before a hello response");if(X.type==="response_ok"){let $=X.requestId,Z=this.#_.get($);if(this.#_.delete($),Z===void 0)throw new I("Received unexpected OK response");this.#z.free($);try{if(Z.type!==X.response.type)throw console.dir({responseState:Z,msg:X}),new I("Received unexpected type of response");Z.responseCallback(X.response)}catch(Y){throw Z.errorCallback(Y),Y}}else if(X.type==="response_error"){let $=X.requestId,Z=this.#_.get($);if(this.#_.delete($),Z===void 0)throw new I("Received unexpected error response");this.#z.free($),Z.errorCallback(B2(X.error))}else throw j(X,"Impossible ServerMsg type")}openStream(){return O0.open(this)}storeSql(X){this._ensureVersion(2,"storeSql()");let $=this.#H.alloc(),Z=new $1(this,$),Y=()=>{return},G=(_)=>Z._setClosed(_),J={type:"store_sql",sqlId:$,sql:X};return this._sendRequest(J,{responseCallback:Y,errorCallback:G}),Z}_closeSql(X){if(this.#Y!==void 0)return;let $=()=>this.#H.free(X),Z=(G)=>this.#D(G),Y={type:"close_sql",sqlId:X};this._sendRequest(Y,{responseCallback:$,errorCallback:Z})}close(){this.#D(new B("Client was manually closed"))}get closed(){return this.#Y!==void 0}}var F0=Request,l6=Headers,s6=fetch;var Z1;if(typeof queueMicrotask<"u")Z1=queueMicrotask;else{let X=Promise.resolve();Z1=($)=>{X.then($)}}class a6{#X;#$;#Z;constructor(X){this.#X=new Uint8Array(new ArrayBuffer(X)),this.#$=0,this.#Z=0}get length(){return this.#Z-this.#$}data(){return this.#X.slice(this.#$,this.#Z)}push(X){this.#Y(X.byteLength),this.#X.set(X,this.#Z),this.#Z+=X.byteLength}#Y(X){if(this.#Z+X<=this.#X.byteLength)return;let $=this.#Z-this.#$;if($+X<=this.#X.byteLength&&2*this.#Z>=this.#X.byteLength)this.#X.copyWithin(0,this.#$,this.#Z);else{let Z=this.#X.byteLength;do Z*=2;while($+X>Z);let Y=new Uint8Array(new ArrayBuffer(Z));Y.set(this.#X.slice(this.#$,this.#Z),0),this.#X=Y}this.#Z=$,this.#$=0}shift(X){this.#$+=X}}function K$(X){let $=G2(X.baton),Z=G2(X.base_url),Y=V2(X.results,w7);return{baton:$,baseUrl:Z,results:Y}}function w7(X){let $=$2(X.type);if($==="ok")return{type:"ok",response:P7(n(X.response))};else if($==="error")return{type:"error",error:m2(n(X.error))};else throw new I("Unexpected type of StreamResult")}function P7(X){let $=$2(X.type);if($==="close")return{type:"close"};else if($==="execute")return{type:"execute",result:V0(n(X.result))};else if($==="batch")return{type:"batch",result:n0(n(X.result))};else if($==="sequence")return{type:"sequence"};else if($==="describe")return{type:"describe",result:i0(n(X.result))};else if($==="store_sql")return{type:"store_sql"};else if($==="close_sql")return{type:"close_sql"};else if($==="get_autocommit")return{type:"get_autocommit",isAutocommit:p2(X.is_autocommit)};else throw new I("Unexpected type of StreamResponse")}function E$(X){let $=G2(X.baton),Z=G2(X.base_url);return{baton:$,baseUrl:Z}}var R$={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(X,$){$.baton=X.string()},2(X,$){$.baseUrl=X.string()},3(X,$){$.results.push(X.message(k7))}},k7={default(){return{type:"none"}},1(X){return{type:"ok",response:X.message(T7)}},2(X){return{type:"error",error:X.message(H2)}}},T7={default(){return{type:"none"}},1(X){return{type:"close"}},2(X){return X.message(j7)},3(X){return X.message(Q7)},4(X){return{type:"sequence"}},5(X){return X.message(B7)},6(X){return{type:"store_sql"}},7(X){return{type:"close_sql"}},8(X){return X.message(L7)}},j7={default(){return{type:"execute",result:c2.default()}},1(X,$){$.result=X.message(c2)}},Q7={default(){return{type:"batch",result:T1.default()}},1(X,$){$.result=X.message(T1)}},B7={default(){return{type:"describe",result:j1.default()}},1(X,$){$.result=X.message(j1)}},L7={default(){return{type:"get_autocommit",isAutocommit:!1}},1(X,$){$.isAutocommit=X.bool()}},M$={default(){return{baton:void 0,baseUrl:void 0}},1(X,$){$.baton=X.string()},2(X,$){$.baseUrl=X.string()}};class e6 extends D0{#X;#$;#Z;#Y;#G;#J;constructor(X,$){super();this.#X=X,this.#$=$,this.#Z=void 0,this.#Y=new a6(16384),this.#G=void 0,this.#J=!1}async open(X){if(X.body===null)throw new I("No response body for cursor request");this.#Z=X.body.getReader();let $=await this.#W(E$,M$);if($===void 0)throw new I("Empty response to cursor request");return $}next(){return this.#W(o0,r0)}close(){this._setClosed(new B("Cursor was manually closed"))}_setClosed(X){if(this.#G!==void 0)return;if(this.#G=X,this.#X._cursorClosed(this),this.#Z!==void 0)this.#Z.cancel()}get closed(){return this.#G!==void 0}async#W(X,$){for(;;){if(this.#J)return;else if(this.#G!==void 0)throw new d("Cursor is closed",this.#G);if(this.#$==="json"){let G=this.#_();if(G!==void 0){let J=new TextDecoder().decode(G),_=JSON.parse(J);return a2(_,X)}}else if(this.#$==="protobuf"){let G=this.#z();if(G!==void 0)return b2(G,$)}else throw j(this.#$,"Impossible encoding");if(this.#Z===void 0)throw new l("Attempted to read from HTTP cursor before it was opened");let{value:Z,done:Y}=await this.#Z.read();if(Y&&this.#Y.length===0)this.#J=!0;else if(Y)throw new I("Unexpected end of cursor stream");else this.#Y.push(Z)}}#_(){let X=this.#Y.data(),$=10,Z=X.indexOf(10);if(Z<0)return;let Y=X.slice(0,Z);return this.#Y.shift(Z+1),Y}#z(){let X=this.#Y.data(),$=0,Z=0;for(;;){if(Z>=X.byteLength)return;let G=X[Z];if($|=(G&127)<<7*Z,Z+=1,!(G&128))break}if(X.byteLength<Z+$)return;let Y=X.slice(Z,Z+$);return this.#Y.shift(Z+$),Y}}function N$(X,$){if($.baton!==void 0)X.string("baton",$.baton);X.arrayObjects("requests",$.requests,v7)}function v7(X,$){if(X.stringRaw("type",$.type),$.type==="close");else if($.type==="execute")X.object("stmt",$.stmt,A0);else if($.type==="batch")X.object("batch",$.batch,P1);else if($.type==="sequence"){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="describe"){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="store_sql")X.number("sql_id",$.sqlId),X.string("sql",$.sql);else if($.type==="close_sql")X.number("sql_id",$.sqlId);else if($.type==="get_autocommit");else throw j($,"Impossible type of StreamRequest")}function I$(X,$){if($.baton!==void 0)X.string("baton",$.baton);X.object("batch",$.batch,P1)}function x$(X,$){if($.baton!==void 0)X.string(1,$.baton);for(let Z of $.requests)X.message(2,Z,C7)}function C7(X,$){if($.type==="close")X.message(1,$,h7);else if($.type==="execute")X.message(2,$,f7);else if($.type==="batch")X.message(3,$,q7);else if($.type==="sequence")X.message(4,$,y7);else if($.type==="describe")X.message(5,$,S7);else if($.type==="store_sql")X.message(6,$,p7);else if($.type==="close_sql")X.message(7,$,b7);else if($.type==="get_autocommit")X.message(8,$,g7);else throw j($,"Impossible type of StreamRequest")}function h7(X,$){}function f7(X,$){X.message(1,$.stmt,U0)}function q7(X,$){X.message(1,$.batch,k1)}function y7(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId)}function S7(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId)}function p7(X,$){X.int32(1,$.sqlId),X.string(2,$.sql)}function b7(X,$){X.int32(1,$.sqlId)}function g7(X,$){}function w$(X,$){if($.baton!==void 0)X.string(1,$.baton);X.message(2,$.batch,k1)}class l0 extends w1{#X;#$;#Z;#Y;#G;#J;#W;#_;#z;#H;#O;#V;constructor(X,$,Z,Y){super(X.intMode);this.#X=X,this.#$=$.toString(),this.#Z=Z,this.#Y=Y,this.#G=void 0,this.#J=new d2,this.#W=!1,this.#z=!1,this.#H=!1,this.#O=void 0,this.#V=new g2}client(){return this.#X}_sqlOwner(){return this}storeSql(X){let $=this.#V.alloc();return this.#A({type:"store_sql",sqlId:$,sql:X}).then(()=>{return},(Z)=>this._setClosed(Z)),new $1(this,$)}_closeSql(X){if(this.#O!==void 0)return;this.#A({type:"close_sql",sqlId:X}).then(()=>this.#V.free(X),($)=>this._setClosed($))}_execute(X){return this.#A({type:"execute",stmt:X}).then(($)=>{return $.result})}_batch(X){return this.#A({type:"batch",batch:X}).then(($)=>{return $.result})}_describe(X){return this.#A({type:"describe",sql:X.sql,sqlId:X.sqlId}).then(($)=>{return $.result})}_sequence(X){return this.#A({type:"sequence",sql:X.sql,sqlId:X.sqlId}).then(($)=>{return})}getAutocommit(){return this.#X._ensureVersion(3,"getAutocommit()"),this.#A({type:"get_autocommit"}).then((X)=>{return X.isAutocommit})}#A(X){return new Promise(($,Z)=>{this.#F({type:"pipeline",request:X,responseCallback:$,errorCallback:Z})})}_openCursor(X){return new Promise(($,Z)=>{this.#F({type:"cursor",batch:X,cursorCallback:$,errorCallback:Z})})}_cursorClosed(X){if(X!==this.#_)throw new l("Cursor was closed, but it was not associated with the stream");this.#_=void 0,Z1(()=>this.#U())}close(){this._setClosed(new B("Stream was manually closed"))}closeGracefully(){this.#z=!0,Z1(()=>this.#U())}get closed(){return this.#O!==void 0||this.#z}_setClosed(X){if(this.#O!==void 0)return;if(this.#O=X,this.#_!==void 0)this.#_._setClosed(X);this.#X._streamClosed(this);for(;;){let $=this.#J.shift();if($!==void 0)$.errorCallback(X);else break}if((this.#G!==void 0||this.#W)&&!this.#H)this.#J.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#H=!0,Z1(()=>this.#U())}#F(X){if(this.#O!==void 0)throw new d("Stream is closed",this.#O);else if(this.#z)throw new d("Stream is closing",void 0);else this.#J.push(X),Z1(()=>this.#U())}#U(){if(this.#W||this.#_!==void 0)return;if(this.#z&&this.#J.length===0){this._setClosed(new B("Stream was gracefully closed"));return}let X=this.#X._endpoint;if(X===void 0){this.#X._endpointPromise.then(()=>this.#U(),(Z)=>this._setClosed(Z));return}let $=this.#J.shift();if($===void 0)return;else if($.type==="pipeline"){let Z=[$];for(;;){let Y=this.#J.first();if(Y!==void 0&&Y.type==="pipeline")Z.push(Y),this.#J.shift();else if(Y===void 0&&this.#z&&!this.#H){Z.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#H=!0;break}else break}this.#D(X,Z)}else if($.type==="cursor")this.#E(X,$);else throw j($,"Impossible type of QueueEntry")}#D(X,$){this.#K(()=>this.#M($,X),(Z)=>m7(Z,X.encoding),(Z)=>Z.baton,(Z)=>Z.baseUrl,(Z)=>d7($,Z),(Z)=>$.forEach((Y)=>Y.errorCallback(Z)))}#E(X,$){let Z=new e6(this,X.encoding);this.#_=Z,this.#K(()=>this.#N($,X),(Y)=>Z.open(Y),(Y)=>Y.baton,(Y)=>Y.baseUrl,(Y)=>$.cursorCallback(Z),(Y)=>$.errorCallback(Y))}#K(X,$,Z,Y,G,J){let _;try{let W=X(),H=this.#Y;_=H(W)}catch(W){_=Promise.reject(W)}this.#W=!0,_.then((W)=>{if(!W.ok)return c7(W).then((H)=>{throw H});return $(W)}).then((W)=>{this.#G=Z(W),this.#$=Y(W)??this.#$,G(W)}).catch((W)=>{this._setClosed(W),J(W)}).finally(()=>{this.#W=!1,this.#U()})}#M(X,$){return this.#R(new URL($.pipelinePath,this.#$),{baton:this.#G,requests:X.map((Z)=>Z.request)},$.encoding,N$,x$)}#N(X,$){if($.cursorPath===void 0)throw new U2(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${$.version}.`);return this.#R(new URL($.cursorPath,this.#$),{baton:this.#G,batch:X.batch},$.encoding,I$,w$)}#R(X,$,Z,Y,G){let J,_;if(Z==="json")J=G0($,Y),_="application/json";else if(Z==="protobuf")J=W0($,G),_="application/x-protobuf";else throw j(Z,"Impossible encoding");let W=new l6;if(W.set("content-type",_),this.#Z!==void 0)W.set("authorization",`Bearer ${this.#Z}`);return new F0(X.toString(),{method:"POST",headers:W,body:J})}}function d7(X,$){if($.results.length!==X.length)throw new I("Server returned unexpected number of pipeline results");for(let Z=0;Z<X.length;++Z){let Y=$.results[Z],G=X[Z];if(Y.type==="ok"){if(Y.response.type!==G.request.type)throw new I("Received unexpected type of response");G.responseCallback(Y.response)}else if(Y.type==="error")G.errorCallback(B2(Y.error));else if(Y.type==="none")throw new I("Received unrecognized type of StreamResult");else throw j(Y,"Received impossible type of StreamResult")}}async function m7(X,$){if($==="json"){let Z=await X.json();return a2(Z,K$)}if($==="protobuf"){let Z=await X.arrayBuffer();return b2(new Uint8Array(Z),R$)}throw await X.body?.cancel(),j($,"Impossible encoding")}async function c7(X){let $=X.headers.get("content-type")??"text/plain",Z=`Server returned HTTP status ${X.status}`;if($==="application/json"){let Y=await X.json();if("message"in Y)return B2(Y);return new s2(Z,X.status)}if($==="text/plain"){let Y=(await X.text()).trim();if(Y!=="")Z+=`: ${Y}`;return new s2(Z,X.status)}return await X.body?.cancel(),new s2(Z,X.status)}var u7=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],X4={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};class s0 extends M1{#X;#$;#Z;#Y;#G;_endpointPromise;_endpoint;constructor(X,$,Z,Y=2){super();if(this.#X=X,this.#$=$,this.#Z=Z??s6,this.#Y=void 0,this.#G=new Set,Y==3)this._endpointPromise=n7(this.#Z,this.#X),this._endpointPromise.then((G)=>this._endpoint=G,(G)=>this.#J(G));else this._endpointPromise=Promise.resolve(X4),this._endpointPromise.then((G)=>this._endpoint=G,(G)=>this.#J(G))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(X,$){if(X<=X4.version)return;else if(this._endpoint===void 0)throw new U2(`${$} is supported only on protocol version ${X} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<X)throw new U2(`${$} is supported only on protocol version ${X} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#Y!==void 0)throw new d("Client is closed",this.#Y);let X=new l0(this,this.#X,this.#$,this.#Z);return this.#G.add(X),X}_streamClosed(X){this.#G.delete(X)}close(){this.#J(new B("Client was manually closed"))}get closed(){return this.#Y!==void 0}#J(X){if(this.#Y!==void 0)return;this.#Y=X;for(let $ of Array.from(this.#G))$._setClosed(new d("Client was closed",X))}}async function n7(X,$){let Z=X;for(let Y of u7){let G=new URL(Y.versionPath,$),J=new F0(G.toString(),{method:"GET"}),_=await Z(J);if(await _.arrayBuffer(),_.ok)return Y}return X4}function $4(X,$,Z=2){if(typeof X0.default>"u")throw new Z0("WebSockets are not supported in this environment");var Y=void 0;if(Z==3)Y=Array.from(t6.keys());else Y=Array.from(F$.keys());let G=new X0.default(X,Y);return new t0(G,$)}function Z4(X,$,Z,Y=2){return new s0(X instanceof URL?X:new URL(X),$,Z,Y)}class K0{#X;#$;#Z;constructor(X,$){this.#X=X,this.#$=$,this.#Z=void 0}execute(X){return this.batch([X]).then(($)=>$[0])}async batch(X){let $=this._getStream();if($.closed)throw new w("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let Z=X.map(L2),Y;if(this.#Z===void 0){this._getSqlCache().apply(Z);let J=$.batch(this.#$>=3),_=J.step(),W=_.run(q2(this.#X)),H=_;Y=Z.map((D)=>{let A=J.step().condition(y.ok(H));if(this.#$>=3)A.condition(y.not(y.isAutocommit(J)));let R=A.query(D);return R.catch(()=>{return}),H=A,R}),this.#Z=J.execute().then(()=>W).then(()=>{return});try{await this.#Z}catch(D){throw this.close(),D}}else{if(this.#$<3)await this.#Z;this._getSqlCache().apply(Z);let J=$.batch(this.#$>=3),_=void 0;Y=Z.map((W)=>{let H=J.step();if(_!==void 0)H.condition(y.ok(_));if(this.#$>=3)H.condition(y.not(y.isAutocommit(J)));let D=H.query(W);return D.catch(()=>{return}),_=H,D}),await J.execute()}let G=[];for(let J of Y){let _=await J;if(_===void 0)throw new w("Statement in a transaction was not executed, probably because the transaction has been rolled back","TRANSACTION_CLOSED");G.push(B1(_))}return G}catch(Z){throw p(Z)}}async executeMultiple(X){let $=this._getStream();if($.closed)throw new w("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#Z===void 0){this.#Z=$.run(q2(this.#X)).then(()=>{return});try{await this.#Z}catch(Z){throw this.close(),Z}}else await this.#Z;await $.sequence(X)}catch(Z){throw p(Z)}}async rollback(){try{let X=this._getStream();if(X.closed)return;if(this.#Z!==void 0);else return;let $=X.run("ROLLBACK").catch((Z)=>{throw p(Z)});X.closeGracefully(),await $}catch(X){throw p(X)}finally{this.close()}}async commit(){try{let X=this._getStream();if(X.closed)throw new w("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#Z!==void 0)await this.#Z;else return;let $=X.run("COMMIT").catch((Z)=>{throw p(Z)});X.closeGracefully(),await $}catch(X){throw p(X)}finally{this.close()}}}async function Q1(X,$,Z,Y,G=!1){if(G)Z.step().run("PRAGMA foreign_keys=off");let J=Z.step(),_=J.run(q2(X)),W=J,H=Y.map((M)=>{let K=Z.step().condition(y.ok(W));if($>=3)K.condition(y.not(y.isAutocommit(Z)));let x=K.query(M);return W=K,x}),D=Z.step().condition(y.ok(W));if($>=3)D.condition(y.not(y.isAutocommit(Z)));let A=D.run("COMMIT");if(Z.step().condition(y.not(y.ok(D))).run("ROLLBACK").catch((M)=>{return}),G)Z.step().run("PRAGMA foreign_keys=on");await Z.execute();let F=[];await _;for(let M of H){let K=await M;if(K===void 0)throw new w("Statement in a batch was not executed, probably because the transaction has been rolled back","TRANSACTION_CLOSED");F.push(B1(K))}return await A,F}function L2(X){let $,Z;if(Array.isArray(X))[$,Z]=X;else if(typeof X==="string")$=X;else $=X.sql,Z=X.args;let Y=new H0($);if(Z)if(Array.isArray(Z))Y.bindIndexes(Z);else for(let[G,J]of Object.entries(Z))Y.bindName(G,J);return Y}function B1(X){let $=X.columnNames.map((_)=>_??""),Z=X.columnDecltypes.map((_)=>_??""),Y=X.rows,G=X.affectedRowCount,J=X.lastInsertRowid!==void 0?X.lastInsertRowid:void 0;return new K1($,Z,Y,G,J)}function p(X){if(X instanceof B){let $=P$(X);return new w(X.message,$,void 0,X)}return X}function P$(X){if(X instanceof $0&&X.code!==void 0)return X.code;else if(X instanceof I)return"HRANA_PROTO_ERROR";else if(X instanceof d)return X.cause instanceof B?P$(X.cause):"HRANA_CLOSED_ERROR";else if(X instanceof N1)return"HRANA_WEBSOCKET_ERROR";else if(X instanceof s2)return"SERVER_ERROR";else if(X instanceof U2)return"PROTOCOL_VERSION_ERROR";else if(X instanceof l)return"INTERNAL_ERROR";else return"UNKNOWN"}class L1{#X;#$;capacity;constructor(X,$){this.#X=X,this.#$=new k$,this.capacity=$}apply(X){if(this.capacity<=0)return;let $=new Set;for(let Z of X){if(typeof Z.sql!=="string")continue;let Y=Z.sql;if(Y.length>=5000)continue;let G=this.#$.get(Y);if(G===void 0){while(this.#$.size+1>this.capacity){let[J,_]=this.#$.peekLru();if($.has(_))break;_.close(),this.#$.delete(J)}if(this.#$.size+1<=this.capacity)G=this.#X.storeSql(Y),this.#$.set(Y,G)}if(G!==void 0)Z.sql=G,$.add(G)}}}class k${#X;constructor(){this.#X=new Map}get(X){let $=this.#X.get(X);if($!==void 0)this.#X.delete(X),this.#X.set(X,$);return $}set(X,$){this.#X.set(X,$)}peekLru(){for(let X of this.#X.entries())return X;return}delete(X){this.#X.delete(X)}get size(){return this.#X.size}}var B$=m6(G4(),1);function L$(X){if(X.scheme!=="wss"&&X.scheme!=="ws")throw new w(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(X.scheme+":")}. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");if(X.encryptionKey!==void 0)throw new w("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(X.scheme==="ws"&&X.tls)throw new w('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(X.scheme==="wss"&&!X.tls)throw new w('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let $=l1(X.scheme,X.authority,X.path),Z;try{Z=$4($,X.authToken)}catch(Y){if(Y instanceof Z0){let G=X.scheme==="wss"?"https":"http",J=l1(G,X.authority,X.path);throw new w(`This environment does not support WebSockets, please switch to the HTTP client by using a "${G}:" URL (${JSON.stringify(J)}). For more information, please read ${R2}`,"WEBSOCKETS_NOT_SUPPORTED")}throw p(Y)}return new v$(Z,$,X.authToken,X.intMode,X.concurrency)}var r7=60000,Q$=100;class v${#X;#$;#Z;#Y;#G;closed;protocol;#J;#W;constructor(X,$,Z,Y,G){this.#X=$,this.#$=Z,this.#Z=Y,this.#Y=this.#z(X),this.#G=void 0,this.closed=!1,this.protocol="ws",this.#W=B$.default(G)}async limit(X){return this.#W(X)}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.limit(async()=>{let Y=await this.#_();try{let G=L2(Z);Y.conn.sqlCache.apply([G]);let J=Y.stream.query(G);Y.stream.closeGracefully();let _=await J;return B1(_)}catch(G){throw p(G)}finally{this._closeStream(Y)}})}async batch(X,$="deferred"){return this.limit(async()=>{let Z=await this.#_();try{let G=X.map((D)=>{if(Array.isArray(D))return{sql:D[0],args:D[1]||[]};return D}).map(L2),J=await Z.conn.client.getVersion();Z.conn.sqlCache.apply(G);let _=Z.stream.batch(J>=3);return await Q1($,J,_,G)}catch(Y){throw p(Y)}finally{this._closeStream(Z)}})}async migrate(X){return this.limit(async()=>{let $=await this.#_();try{let Z=X.map(L2),Y=await $.conn.client.getVersion(),G=$.stream.batch(Y>=3);return await Q1("deferred",Y,G,Z,!0)}catch(Z){throw p(Z)}finally{this._closeStream($)}})}async transaction(X="write"){return this.limit(async()=>{let $=await this.#_();try{let Z=await $.conn.client.getVersion();return new C$(this,$,X,Z)}catch(Z){throw this._closeStream($),p(Z)}})}async executeMultiple(X){return this.limit(async()=>{let $=await this.#_();try{let Z=$.stream.sequence(X);$.stream.closeGracefully(),await Z}catch(Z){throw p(Z)}finally{this._closeStream($)}})}sync(){throw new w("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#_(){if(this.closed)throw new w("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#Y.openTime.valueOf()>r7&&this.#G===void 0){let Y=this.#z();this.#G=Y,Y.client.getVersion().then((G)=>{if(this.#Y!==Y){if(this.#Y.streamStates.size===0)this.#Y.client.close()}this.#Y=Y,this.#G=void 0},(G)=>{this.#G=void 0})}if(this.#Y.client.closed)try{if(this.#G!==void 0)this.#Y=this.#G;else this.#Y=this.#z()}catch(Y){throw p(Y)}let Z=this.#Y;try{if(Z.useSqlCache===void 0){if(Z.useSqlCache=await Z.client.getVersion()>=2,Z.useSqlCache)Z.sqlCache.capacity=Q$}let Y=Z.client.openStream();Y.intMode=this.#Z;let G={conn:Z,stream:Y};return Z.streamStates.add(G),G}catch(Y){throw p(Y)}}#z(X){try{return X??=$4(this.#X,this.#$),{client:X,useSqlCache:void 0,sqlCache:new L1(X,0),openTime:new Date,streamStates:new Set}}catch($){throw p($)}}async reconnect(){try{for(let Z of Array.from(this.#Y.streamStates))try{Z.stream.close()}catch{}this.#Y.client.close()}catch{}if(this.#G){try{this.#G.client.close()}catch{}this.#G=void 0}let X=this.#z(),$=await X.client.getVersion();if(X.useSqlCache=$>=2,X.useSqlCache)X.sqlCache.capacity=Q$;this.#Y=X,this.closed=!1}_closeStream(X){X.stream.close();let $=X.conn;if($.streamStates.delete(X),$.streamStates.size===0&&$!==this.#Y)$.client.close()}close(){if(this.#Y.client.close(),this.closed=!0,this.#G){try{this.#G.client.close()}catch{}this.#G=void 0}this.closed=!0}}class C$ extends K0{#X;#$;constructor(X,$,Z,Y){super(Z,Y);this.#X=X,this.#$=$}_getStream(){return this.#$.stream}_getSqlCache(){return this.#$.conn.sqlCache}close(){this.#X._closeStream(this.#$)}get closed(){return this.#$.stream.closed}}var h$=m6(G4(),1);function f$(X){if(X.scheme!=="https"&&X.scheme!=="http")throw new w(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(X.scheme+":")}. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");if(X.encryptionKey!==void 0)throw new w("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(X.scheme==="http"&&X.tls)throw new w('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(X.scheme==="https"&&!X.tls)throw new w('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let $=l1(X.scheme,X.authority,X.path);return new y$($,X.authToken,X.intMode,X.fetch,X.concurrency)}var q$=30;class y${#X;protocol;#$;#Z;#Y;#G;#J;#W;constructor(X,$,Z,Y,G){this.#$=X,this.#J=$,this.#Z=Z,this.#Y=Y,this.#G=G,this.#X=Z4(this.#$,this.#J,this.#Y),this.#X.intMode=this.#Z,this.protocol="http",this.#W=h$.default(this.#G)}async limit(X){return this.#W(X)}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.limit(async()=>{try{let Y=L2(Z),G,J=this.#X.openStream();try{G=J.query(Y)}finally{J.closeGracefully()}let _=await G;return B1(_)}catch(Y){throw p(Y)}})}async batch(X,$="deferred"){return this.limit(async()=>{try{let Y=X.map((H)=>{if(Array.isArray(H))return{sql:H[0],args:H[1]||[]};return H}).map(L2),G=await this.#X.getVersion(),J,_=this.#X.openStream();try{new L1(_,q$).apply(Y);let D=_.batch(!1);J=Q1($,G,D,Y)}finally{_.closeGracefully()}return await J}catch(Z){throw p(Z)}})}async migrate(X){return this.limit(async()=>{try{let $=X.map(L2),Z=await this.#X.getVersion(),Y,G=this.#X.openStream();try{let _=G.batch(!1);Y=Q1("deferred",Z,_,$,!0)}finally{G.closeGracefully()}return await Y}catch($){throw p($)}})}async transaction(X="write"){return this.limit(async()=>{try{let $=await this.#X.getVersion();return new S$(this.#X.openStream(),X,$)}catch($){throw p($)}})}async executeMultiple(X){return this.limit(async()=>{try{let $,Z=this.#X.openStream();try{$=Z.sequence(X)}finally{Z.closeGracefully()}await $}catch($){throw p($)}})}sync(){throw new w("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#X.close()}async reconnect(){try{if(!this.closed)this.#X.close()}finally{this.#X=Z4(this.#$,this.#J,this.#Y),this.#X.intMode=this.#Z}}get closed(){return this.#X.closed}}class S$ extends K0{#X;#$;constructor(X,$,Z){super($,Z);this.#X=X,this.#$=new L1(X,q$)}_getStream(){return this.#X}_getSqlCache(){return this.#$}close(){this.#X.close()}get closed(){return this.#X.closed}}function v1(X){return t7(a1(X,!0))}function t7(X){if(X.scheme==="wss"||X.scheme==="ws")return L$(X);else if(X.scheme==="https"||X.scheme==="http")return f$(X);else return uX(X)}class e0 extends f6{constructor(X,$,Z,Y,G){super($);this.client=X,this.schema=Z,this.options=Y,this.tx=G,this.logger=Y.logger??new V6,this.cache=Y.cache??new i1}static[O]="LibSQLSession";logger;cache;prepareQuery(X,$,Z,Y,G,J,_){return new b$(this.client,X,this.logger,this.cache,J,_,$,this.tx,Z,Y,G)}async batch(X){let $=[],Z=[];for(let G of X){let J=G._prepare(),_=J.getQuery();$.push(J),Z.push({sql:_.sql,args:_.params})}return(await this.client.batch(Z)).map((G,J)=>$[J].mapResult(G,!0))}async migrate(X){let $=[],Z=[];for(let G of X){let J=G._prepare(),_=J.getQuery();$.push(J),Z.push({sql:_.sql,args:_.params})}return(await this.client.migrate(Z)).map((G,J)=>$[J].mapResult(G,!0))}async transaction(X,$){let Z=await this.client.transaction(),Y=new e0(this.client,this.dialect,this.schema,this.options,Z),G=new J4("async",this.dialect,Y,this.schema);try{let J=await X(G);return await Z.commit(),J}catch(J){throw await Z.rollback(),J}}extractRawAllValueFromBatchResult(X){return X.rows}extractRawGetValueFromBatchResult(X){return X.rows[0]}extractRawValuesValueFromBatchResult(X){return X.rows}}class J4 extends q6{static[O]="LibSQLTransaction";async transaction(X){let $=`sp${this.nestedIndex}`,Z=new J4("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(z.raw(`savepoint ${$}`));try{let Y=await X(Z);return await this.session.run(z.raw(`release savepoint ${$}`)),Y}catch(Y){throw await this.session.run(z.raw(`rollback to savepoint ${$}`)),Y}}}class b$ extends h6{constructor(X,$,Z,Y,G,J,_,W,H,D,A){super("async",H,$,Y,G,J);this.client=X,this.logger=Z,this.fields=_,this.tx=W,this._isResponseInArrayMode=D,this.customResultMapper=A,this.customResultMapper=A,this.fields=_}static[O]="LibSQLPreparedQuery";async run(X){let $=S1(this.query.params,X??{});return this.logger.logQuery(this.query.sql,$),await this.queryWithCache(this.query.sql,$,async()=>{let Z={sql:this.query.sql,args:$};return this.tx?this.tx.execute(Z):this.client.execute(Z)})}async all(X){let{fields:$,logger:Z,query:Y,tx:G,client:J,customResultMapper:_}=this;if(!$&&!_){let H=S1(Y.params,X??{});return Z.logQuery(Y.sql,H),await this.queryWithCache(Y.sql,H,async()=>{let D={sql:Y.sql,args:H};return(G?G.execute(D):J.execute(D)).then(({rows:A})=>this.mapAllResult(A))})}let W=await this.values(X);return this.mapAllResult(W)}mapAllResult(X,$){if($)X=X.rows;if(!this.fields&&!this.customResultMapper)return X.map((Z)=>p$(Z));if(this.customResultMapper)return this.customResultMapper(X,a0);return X.map((Z)=>{return F6(this.fields,Array.prototype.slice.call(Z).map((Y)=>a0(Y)),this.joinsNotNullableMap)})}async get(X){let{fields:$,logger:Z,query:Y,tx:G,client:J,customResultMapper:_}=this;if(!$&&!_){let H=S1(Y.params,X??{});return Z.logQuery(Y.sql,H),await this.queryWithCache(Y.sql,H,async()=>{let D={sql:Y.sql,args:H};return(G?G.execute(D):J.execute(D)).then(({rows:A})=>this.mapGetResult(A))})}let W=await this.values(X);return this.mapGetResult(W)}mapGetResult(X,$){if($)X=X.rows;let Z=X[0];if(!this.fields&&!this.customResultMapper)return p$(Z);if(!Z)return;if(this.customResultMapper)return this.customResultMapper(X,a0);return F6(this.fields,Array.prototype.slice.call(Z).map((Y)=>a0(Y)),this.joinsNotNullableMap)}async values(X){let $=S1(this.query.params,X??{});return this.logger.logQuery(this.query.sql,$),await this.queryWithCache(this.query.sql,$,async()=>{let Z={sql:this.query.sql,args:$};return(this.tx?this.tx.execute(Z):this.client.execute(Z)).then(({rows:Y})=>Y)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}function p$(X){return Object.keys(X).reduce(($,Z)=>{if(Object.prototype.propertyIsEnumerable.call(X,Z))$[Z]=X[Z];return $},{})}function a0(X){if(typeof ArrayBuffer<"u"&&X instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(X instanceof Buffer))return Buffer.from(X);return X}if(typeof TextDecoder<"u")return new TextDecoder().decode(X);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return X}class g$ extends o1{static[O]="LibSQLDatabase";async batch(X){return this.session.batch(X)}}function C1(X,$={}){let Z=new T6({casing:$.casing}),Y;if($.logger===!0)Y=new U6;else if($.logger!==!1)Y=$.logger;let G;if($.schema){let W=t4($.schema,s4);G={fullSchema:$.schema,schema:W.tables,tableNamesMap:W.tableNamesMap}}let J=new e0(X,Z,G,{logger:Y,cache:$.cache},void 0),_=new g$("async",Z,J,G);if(_.$client=X,_.$cache=$.cache,_.$cache)_.$cache.invalidate=$.cache?.onMutate;return _}function X6(...X){if(typeof X[0]==="string"){let $=v1({url:X[0]});return C1($,X[1])}if(P4(X[0])){let{connection:$,client:Z,...Y}=X[0];if(Z)return C1(Z,Y);let G=typeof $==="string"?v1({url:$}):v1($);return C1(G,Y)}return C1(X[0],X[1])}((X)=>{function $(Z){return C1({},Z)}X.mock=$})(X6||(X6={}));import l7 from"node:crypto";import _4 from"node:fs";function d$(X){let $=X.migrationsFolder,Z=[],Y=`${$}/meta/_journal.json`;if(!_4.existsSync(Y))throw Error("Can't find meta/_journal.json file");let G=_4.readFileSync(`${$}/meta/_journal.json`).toString(),J=JSON.parse(G);for(let _ of J.entries){let W=`${$}/${_.tag}.sql`;try{let H=_4.readFileSync(`${$}/${_.tag}.sql`).toString(),D=H.split("--> statement-breakpoint").map((A)=>{return A});Z.push({sql:D,bps:_.breakpoints,folderMillis:_.when,hash:l7.createHash("sha256").update(H).digest("hex")})}catch{throw Error(`No file ${W} found in ${$} folder`)}}return Z}async function m$(X,$){let Z=d$($),Y=$.migrationsTable??"__drizzle_migrations",G=z`
|
|
15
|
-
CREATE TABLE IF NOT EXISTS ${z.identifier(Y)} (
|
|
16
|
-
id SERIAL PRIMARY KEY,
|
|
17
|
-
hash text NOT NULL,
|
|
18
|
-
created_at numeric
|
|
19
|
-
)
|
|
20
|
-
`;await X.session.run(G);let _=(await X.values(z`SELECT id, hash, created_at FROM ${z.identifier(Y)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,W=[];for(let H of Z)if(!_||Number(_[2])<H.folderMillis){for(let D of H.sql)W.push(X.run(z.raw(D)));W.push(X.run(z`INSERT INTO ${z.identifier(Y)} ("hash", "created_at") VALUES(${H.hash}, ${H.folderMillis})`))}await X.session.migrate(W)}import{readFile as s7,writeFile as WD,mkdir as zD}from"node:fs/promises";import{join as W4}from"node:path";import{homedir as a7}from"node:os";var c$=W4(a7(),".sylphx","sessions"),OD=W4(c$,".last-session");function e7(X){return W4(c$,`${X}.json`)}async function u$(X){try{let $=e7(X),Z=await s7($,"utf8"),Y=JSON.parse(Z);if(!Y.todos)Y.todos=[];if(typeof Y.nextTodoId!=="number")Y.nextTodoId=1;if(Array.isArray(Y.messages))Y.messages=Y.messages.map((G)=>{if(typeof G.content==="string")return{...G,content:[{type:"text",content:G.content}]};return G});return Y}catch{return null}}function AD(X,$,Z){return{...X,messages:[...X.messages,{role:$,content:[{type:"text",content:Z}],timestamp:Date.now()}]}}var h1=Y1(o$(),".sylphx","sessions"),H4=Y1(o$(),".sylphx-flow"),ZG=Y1(H4,"memory.db"),z4=Y1(H4,".session-migrated");async function YG(X){try{if(r$(z4))return await GG(),!1;try{let Z=(await $6(h1)).filter((J)=>J.endsWith(".json")&&!J.startsWith("."));if(Z.length===0)return!1;return await new A1(X).getSessionCount()===0&&Z.length>0}catch{return!1}}catch{return!1}}async function GG(){try{let $=(await $6(h1)).filter((Y)=>Y.endsWith(".json")&&!Y.startsWith("."));if($.length===0)return;console.log(`Cleaning up ${$.length} old JSON files...`);let Z=0;for(let Y of $)try{await i$(Y1(h1,Y)),Z++}catch(G){console.warn(`Failed to delete ${Y}:`,G)}console.log(`Cleanup complete: deleted ${Z}/${$.length} JSON files`)}catch{}}async function JG(X){await XG(H4,{recursive:!0});let $=n$("drizzle migrations"),Z=Y1($,"drizzle");if(!r$(Z))throw Error(`Drizzle migrations not found at ${Z}`);await m$(X,{migrationsFolder:Z})}async function _G(X,$){let Z=new A1(X),G=(await $6(h1)).filter((W)=>W.endsWith(".json")&&!W.startsWith(".")),J=0,_=0;$?.({total:G.length,current:0,status:`Found ${G.length} sessions to migrate`});for(let W=0;W<G.length;W++){let H=G[W],D=H.replace(".json","");try{$?.({total:G.length,current:W+1,status:`Migrating session ${W+1}/${G.length}`});let A=await u$(D);if(!A){_++;continue}if(await Z.getSessionById(A.id))continue;await Z.createSessionFromData({id:A.id,provider:A.provider,model:A.model,title:A.title,nextTodoId:A.nextTodoId||1,created:A.created,updated:A.updated});for(let M of A.messages){let K=void 0;if(M.attachments&&Array.isArray(M.attachments)&&M.attachments.length>0){let x=M.attachments.filter((k)=>k&&typeof k==="object"&&k.path&&k.relativePath);if(x.length>0)K=x}await Z.addMessage(A.id,M.role,M.content,K,M.usage,M.finishReason,M.metadata,M.todoSnapshot)}if(A.todos&&A.todos.length>0)await Z.updateTodos(A.id,A.todos,A.nextTodoId);let F=Y1(h1,H);try{await i$(F)}catch(M){console.warn(`Successfully migrated ${D} but failed to delete JSON file:`,M)}J++}catch(A){console.error(`Error migrating ${D}:`,A),_++}}return await $G(z4,"utf8").catch(()=>T2("fs").writeFileSync(z4,new Date().toISOString())),{success:J,errors:_}}async function WG(X){let $=process.env.DATABASE_URL||`file:${ZG}`,Z=v1({url:$}),Y=X6(Z);if(await Z.execute("PRAGMA journal_mode = WAL"),await Z.execute("PRAGMA busy_timeout = 5000"),await Z.execute("PRAGMA synchronous = NORMAL"),X?.({total:2,current:0,status:"Running database migrations..."}),await JG(Y),X?.({total:2,current:1,status:"Database schema up to date"}),await YG(Y))try{let _=(await $6(h1)).filter((W)=>W.endsWith(".json")&&!W.startsWith("."));if(_.length>0){X?.({total:2+_.length,current:1,status:`Migrating ${_.length} sessions from files...`});let W=await _G(Y,(H)=>{X?.({total:2+H.total,current:1+H.current,status:H.status})});X?.({total:2+_.length,current:2+_.length,status:`Migration complete! ${W.success} sessions migrated`})}}catch{}return Y}async function t$(X){return WG(X)}var DG=zG(HG(),".sylphx-flow","memory.db"),BD=process.env.DATABASE_URL||`file:${DG}`,Z6=null,Y6=null,E0=null;async function OG(){if(Z6)return Z6;if(E0)return E0;return E0=t$((X)=>{if(process.env.DEBUG)console.log(`[DB] ${X.current}/${X.total}: ${X.status}`)}),Z6=await E0,E0=null,Z6}async function LD(){if(Y6)return Y6;let X=await OG();return Y6=new A1(X),Y6}
|
|
21
|
-
export{z as Y,b as Z,m1 as _,B4 as $,k0 as aa,W1 as ba,g as ca,z1 as da,N as ea,X2 as fa,f as ga,w6 as ha,v1 as ia,X6 as ja,AD as ka,OG as la,LD as ma};
|
|
22
|
-
|
|
23
|
-
//# debugId=FF7D5F25812F12A764756E2164756E21
|