UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

24 lines • 113 kB
import{N as e,t}from"./git-operation.worker-subsystem-DibpW_lB.mjs";import{r as n}from"./git-operation.worker-record-coerce-B9rMjEA7.mjs";import{a as r,s as i}from"./git-operation.worker-sqlite-database-admission-DU53nRqT.mjs";import"./git-operation.worker.js";import{i as a}from"./git-operation.worker-git-C2q2uQ5t.mjs";import"./git-operation.worker-git-path-inventory-CqLBVwed.mjs";import{m as o}from"./git-operation.worker-schemas-OtWwONNf.mjs";import{o as s}from"./git-operation.worker-workspace-hash-memo-B4uJ3zCg.mjs";import{a as c,d as l,o as u,p as d,s as f}from"./git-operation.worker-workspace-manifest-Zk1wvpHZ.mjs";import{r as p}from"./git-operation.worker-workspace-actual-manifest-CCtoh4gL.mjs";import{a as m}from"./git-operation.worker-workspace-manifest-comparison-B0otBJpG.mjs";import"node:util";import{createHash as h}from"node:crypto";import"node:worker_threads";import{serialize as g}from"node:v8";import"node:timers/promises";import{isUtf8 as _}from"node:buffer";import v,{deflateRawSync as y}from"node:zlib";function isUndefined(e){return e===void 0||e===void 0}function isString(e){return typeof e==`string`}function isNumber(e){return typeof e==`number`}function isBoolean(e){return typeof e==`boolean`}function isNull(e){return e===null}function isDate(e){return e instanceof Date}function isBigInt(e){return typeof e==`bigint`}function isFunction(e){return typeof e==`function`}function isObject(e){return typeof e==`object`&&!!e}function freeze(e){return Object.freeze(e)}function asArray(e){return isReadonlyArray(e)?e:[e]}function isReadonlyArray(e){return Array.isArray(e)}function getMessage(e){return e instanceof Error?e.message:String(e)}const b=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),x=freeze({is(e){return e.kind===`CreateTableNode`},create(e){return freeze({kind:`CreateTableNode`,table:e,columns:freeze([])})},cloneWithColumn(e,t){return freeze({...e,columns:freeze([...e.columns,t])})},cloneWithConstraint(e,t){return freeze({...e,constraints:e.constraints?freeze([...e.constraints,t]):freeze([t])})},cloneWithIndex(e,t){return freeze({...e,indexes:e.indexes?freeze([...e.indexes,t]):freeze([t])})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWith(e,t){return freeze({...e,...t})}}),S=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:b.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:b.create(e),identifier:b.create(t)})}}),C=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),w=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:S.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:S.createWithSchema(e,t)})}});function isOperationNodeSource(e){return isObject(e)&&isFunction(e.toOperationNode)}function isExpression(e){return isObject(e)&&`expressionType`in e&&isOperationNodeSource(e)}function isAliasedExpression(e){return isObject(e)&&`expression`in e&&isString(e.alias)&&isOperationNodeSource(e)}const T=freeze({is(e){return e.kind===`SelectModifierNode`},create(e,t){return freeze({kind:`SelectModifierNode`,modifier:e,of:t})},createWithExpression(e){return freeze({kind:`SelectModifierNode`,rawModifier:e})}}),E=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),D=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),O=freeze({is(e){return e.kind===`OnNode`},create(e){return freeze({kind:`OnNode`,on:e})},cloneWithOperation(e,t,n){return freeze({...e,on:t===`And`?E.create(e.on,n):D.create(e.on,n)})}}),k=freeze({is(e){return e.kind===`JoinNode`},create(e,t){return freeze({kind:`JoinNode`,joinType:e,table:t,on:void 0})},createWithOn(e,t,n){return freeze({kind:`JoinNode`,joinType:e,table:t,on:O.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?O.cloneWithOperation(e.on,`And`,t):O.create(t)})}}),A=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),j=freeze({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0});Object.keys(j);const ee=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(ee);const M=freeze({"->":!0,"->>":!0}),te=Object.keys(M),N=freeze({...j,...ee,"||":!0}),ne=Object.keys(N),re=freeze({exists:!0,"not exists":!0});Object.keys(re);const ie=freeze({...re,"-":!0,not:!0}),ae=Object.keys(ie);[...ne,...te,...ae];const P=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&N[e]}function isJSONOperator(e){return isString(e)&&M[e]}function isUnaryOperator(e){return isString(e)&&ie[e]}const oe=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:b.create(e)})}}),se=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),ce=freeze({is(e){return e.kind===`ReferenceNode`},create(e,t){return freeze({kind:`ReferenceNode`,table:t,column:e})},createSelectAll(e){return freeze({kind:`ReferenceNode`,table:e,column:se.create()})}});function isDynamicReferenceBuilder(e){return isObject(e)&&isOperationNodeSource(e)&&isString(e.dynamicReference)}const F=freeze({is(e){return e.kind===`OrderByItemNode`},create(e,t){return freeze({kind:`OrderByItemNode`,orderBy:e,direction:t})},cloneWith(e,t){return freeze({...e,...t})}}),I=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return I.create([e],[])},createWithChild(e){return I.create([``,``],[e])},createWithChildren(e){return I.create(Array(e.length+1).fill(``),e)}}),le=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:b.create(e)})}});var ue=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:F.cloneWith(this.#e.node,{direction:I.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:F.cloneWith(this.#e.node,{direction:I.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:F.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:F.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:F.cloneWith(this.#e.node,{collation:le.create(e)})})}toOperationNode(){return this.#e.node}};const de=/* @__PURE__ */ new Set;function logOnce(e){de.has(e)||(de.add(e),console.log(e))}function isOrderByDirection(e){return e===`asc`||e===`desc`}function parseOrderBy(e){if(e.length===2)return[parseOrderByItem(e[0],e[1])];if(e.length===1){let[t]=e;return Array.isArray(t)?(logOnce(`orderBy(array) is deprecated, use multiple orderBy calls instead.`),t.map(e=>parseOrderByItem(e))):[parseOrderByItem(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function parseOrderByItem(e,t){let n=parseOrderByExpression(e);if(F.is(n)){if(t)throw Error(`Cannot specify direction twice!`);return n}return parseOrderByWithModifiers(n,t)}function parseOrderByExpression(e){if(isExpressionOrFactory(e))return parseExpression(e);if(isDynamicReferenceBuilder(e))return e.toOperationNode();let[t,n]=e.split(` `);return n?(logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),parseOrderByWithModifiers(parseStringReference(t),n)):parseStringReference(e)}function parseOrderByWithModifiers(e,t){if(typeof t==`string`){if(!isOrderByDirection(t))throw Error(`Invalid order by direction: ${t}`);return F.create(e,I.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),F.create(e,t.toOperationNode());let n=F.create(e);return t?t(new ue({node:n})).toOperationNode():n}const fe=freeze({is(e){return e.kind===`JSONReferenceNode`},create(e,t){return freeze({kind:`JSONReferenceNode`,reference:e,traversal:t})},cloneWithTraversal(e,t){return freeze({...e,traversal:t})}}),pe=freeze({is(e){return e.kind===`JSONOperatorChainNode`},create(e){return freeze({kind:`JSONOperatorChainNode`,operator:e,values:freeze([])})},cloneWithValue(e,t){return freeze({...e,values:freeze([...e.values,t])})}}),L=freeze({is(e){return e.kind===`JSONPathNode`},create(e){return freeze({kind:`JSONPathNode`,inOperator:e,pathLegs:freeze([])})},cloneWithLeg(e,t){return freeze({...e,pathLegs:freeze([...e.pathLegs,t])})}});function parseSimpleReferenceExpression(e){return isString(e)?parseStringReference(e):e.toOperationNode()}function parseReferenceExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseReferenceExpression(e)):[parseReferenceExpression(e)]}function parseReferenceExpression(e){return isExpressionOrFactory(e)?parseExpression(e):parseSimpleReferenceExpression(e)}function parseJSONReference(e,t){if(isJSONOperator(t))return fe.create(parseStringReference(e),pe.create(P.create(t)));if(t===`->$`||t===`->>$`)return fe.create(parseStringReference(e),L.create(P.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return ce.create(oe.create(e));let t=e.split(`.`).map(trim$1);if(t.length===3)return parseStringReferenceWithTableAndSchema(t);if(t.length===2)return parseStringReferenceWithTable(t);throw Error(`invalid column reference ${e}`)}function parseAliasedStringReference(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$1);return C.create(parseStringReference(n),b.create(r))}return parseStringReference(e)}function parseStringReferenceWithTableAndSchema(e){let[t,n,r]=e;return ce.create(oe.create(r),w.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return ce.create(oe.create(n),w.create(t))}function trim$1(e){return e.trim()}const me=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),he=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),R=freeze({is(e){return e.kind===`ValueNode`},create(e){return freeze({kind:`ValueNode`,value:e})},createImmediate(e){return freeze({kind:`ValueNode`,value:e,immediate:!0})}});function parseValueExpressionOrList(e){return isReadonlyArray(e)?parseValueExpressionList(e):parseValueExpression(e)}function parseValueExpression(e){return isExpressionOrFactory(e)?parseExpression(e):R.create(e)}function isSafeImmediateValue(e){return isNumber(e)||isBoolean(e)||isNull(e)}function parseSafeImmediateValue(e){if(!isSafeImmediateValue(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return R.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?he.create(e.map(e=>parseValueExpression(e))):me.create(e)}const z=freeze({is(e){return e.kind===`ParensNode`},create(e){return freeze({kind:`ParensNode`,node:e})}});function parseValueBinaryOperationOrExpression(e){if(e.length===3)return parseValueBinaryOperation(e[0],e[1],e[2]);if(e.length===1)return parseValueExpression(e[0]);throw Error(`invalid arguments: ${JSON.stringify(e)}`)}function parseValueBinaryOperation(e,t,n){return isIsOperator(t)&&needsIsOperator(n)?A.create(parseReferenceExpression(e),parseBinaryOperator(t),R.createImmediate(n)):A.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return A.create(parseReferenceExpression(e),parseBinaryOperator(t),parseReferenceExpression(n))}function parseFilterObject(e,t){return parseFilterList(Object.entries(e).filter(([,e])=>!isUndefined(e)).map(([e,t])=>parseValueBinaryOperation(e,needsIsOperator(t)?`is`:`=`,t)),t)}function parseFilterList(e,t,n=!0){let r=t===`and`?E.create:D.create;if(e.length===0)return A.create(R.createImmediate(1),P.create(`=`),R.createImmediate(+(t===`and`)));let i=toOperationNode(e[0]);for(let t=1;t<e.length;++t)i=r(i,toOperationNode(e[t]));return e.length>1&&n?z.create(i):i}function isIsOperator(e){return e===`is`||e===`is not`}function needsIsOperator(e){return isNull(e)||isBoolean(e)}function parseBinaryOperator(e){if(isBinaryOperator(e))return P.create(e);if(isOperationNodeSource(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function toOperationNode(e){return isOperationNodeSource(e)?e.toOperationNode():e}const B=freeze({is(e){return e.kind===`OrderByNode`},create(e){return freeze({kind:`OrderByNode`,items:freeze([...e])})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),ge=freeze({is(e){return e.kind===`PartitionByNode`},create(e){return freeze({kind:`PartitionByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),_e=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?B.cloneWithItems(e.orderBy,t):B.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?ge.cloneWithItems(e.partitionBy,t):ge.create(t)})}}),ve=freeze({is(e){return e.kind===`FromNode`},create(e){return freeze({kind:`FromNode`,froms:freeze(e)})},cloneWithFroms(e,t){return freeze({...e,froms:freeze([...e.froms,...t])})}}),ye=freeze({is(e){return e.kind===`GroupByNode`},create(e){return freeze({kind:`GroupByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),be=freeze({is(e){return e.kind===`HavingNode`},create(e){return freeze({kind:`HavingNode`,having:e})},cloneWithOperation(e,t,n){return freeze({...e,having:t===`And`?E.create(e.having,n):D.create(e.having,n)})}}),xe=freeze({is(e){return e.kind===`InsertQueryNode`},create(e,t,n){return freeze({kind:`InsertQueryNode`,into:e,...t&&{with:t},replace:n})},createWithoutInto(){return freeze({kind:`InsertQueryNode`})},cloneWith(e,t){return freeze({...e,...t})}}),Se=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Ce=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Se.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?ve.cloneWithFroms(e.from,t):ve.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),we=freeze({is(e){return e.kind===`UsingNode`},create(e){return freeze({kind:`UsingNode`,tables:freeze(e)})},cloneWithTables(e,t){return freeze({...e,tables:freeze([...e.tables,...t])})}}),Te=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:ve.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>U.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>U.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithUsing(e,t){return freeze({...e,using:e.using===void 0?we.create(t):we.cloneWithTables(e.using,t)})}}),V=freeze({is(e){return e.kind===`WhereNode`},create(e){return freeze({kind:`WhereNode`,where:e})},cloneWithOperation(e,t,n){return freeze({...e,where:t===`And`?E.create(e.where,n):D.create(e.where,n)})}}),Ee=freeze({is(e){return e.kind===`ReturningNode`},create(e){return freeze({kind:`ReturningNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),De=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),H=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),Oe=freeze({is(e){return e.kind===`MergeQueryNode`},create(e,t){return freeze({kind:`MergeQueryNode`,into:e,...t&&{with:t}})},cloneWithUsing(e,t){return freeze({...e,using:t})},cloneWithWhen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens,t]):freeze([t])})},cloneWithThen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens.slice(0,-1),H.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),ke=freeze({is(e){return e.kind===`OutputNode`},create(e){return freeze({kind:`OutputNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),U=freeze({is(e){return W.is(e)||xe.is(e)||Ce.is(e)||Te.is(e)||Oe.is(e)},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWithWhere(e,t){return freeze({...e,where:e.where?V.cloneWithOperation(e.where,`And`,t):V.create(t)})},cloneWithJoin(e,t){return freeze({...e,joins:e.joins?freeze([...e.joins,t]):freeze([t])})},cloneWithReturning(e,t){return freeze({...e,returning:e.returning?Ee.cloneWithSelections(e.returning,t):Ee.create(t)})},cloneWithoutReturning(e){return freeze({...e,returning:void 0})},cloneWithoutWhere(e){return freeze({...e,where:void 0})},cloneWithExplain(e,t,n){return freeze({...e,explain:De.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?ke.cloneWithSelections(e.output,t):ke.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?B.cloneWithItems(e.orderBy,t):B.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),W=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:ve.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})},cloneWithDistinctOn(e,t){return freeze({...e,distinctOn:e.distinctOn?freeze([...e.distinctOn,...t]):freeze(t)})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithOrderByItems:(e,t)=>U.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?ye.cloneWithItems(e.groupBy,t):ye.create(t)})},cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithOffset(e,t){return freeze({...e,offset:t})},cloneWithFetch(e,t){return freeze({...e,fetch:t})},cloneWithHaving(e,t){return freeze({...e,having:e.having?be.cloneWithOperation(e.having,`And`,t):be.create(t)})},cloneWithSetOperations(e,t){return freeze({...e,setOperations:e.setOperations?freeze([...e.setOperations,...t]):freeze([...t])})},cloneWithoutSelections(e){return freeze({...e,selections:[]})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithoutOffset(e){return freeze({...e,offset:void 0})},cloneWithoutOrderBy:e=>U.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var Ae=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:k.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:k.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:k.cloneWithOn(this.#e.joinNode,I.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const je=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(je.create)}var Me=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:_e.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:U.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:_e.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const G=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:se.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:ce.createSelectAll(e)})}});function parseSelectArg(e){return isFunction(e)?parseSelectArg(e(expressionBuilder())):isReadonlyArray(e)?e.map(e=>parseSelectExpression(e)):[parseSelectExpression(e)]}function parseSelectExpression(e){return isString(e)?G.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?G.create(e.toOperationNode()):G.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[G.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return G.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}const Ne=freeze({is(e){return e.kind===`TopNode`},create(e,t){return freeze({kind:`TopNode`,expression:e,modifiers:t})}});function parseTop(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid top expression: ${e}`);if(!isUndefined(t)&&!isTopModifiers(t))throw Error(`Invalid top modifiers: ${t}`);return Ne.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const Pe=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}}),Fe=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return Fe[~~(Math.random()*Fe.length)]}function createQueryId(){return new LazyQueryId}var LazyQueryId=class{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}},Deferred=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function provideControlledConnection(e,t){let n=new Deferred,r=new Deferred;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),freeze({connection:await n.promise,release:r.resolve})}function getInflightQueryAbortHandler(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function throwUnsupportedInflightQueryAbortStrategyError(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function assertNotAborted(e,t,n){e?.aborted&&(n?.(),throwReasonWithTiming(e.reason,t))}function throwReasonWithTiming(e,t){throw decorateWithTiming(e,t),e}const K={};function printBackgroundFail(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${getMessage(t)}`)}function decorateWithTiming(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}const Ie=freeze([]);var QueryExecutorBase=class{#e;constructor(e=Ie){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let n of this.#e){let r=n.transformQuery({node:e,queryId:t});if(r.kind===e.kind)e=r;else throw Error([`KyselyPlugin.transformQuery must return a node`,`of the same kind that was given to it.`,`The plugin was given a ${e.kind}`,`but it returned a ${r.kind}`].join(` `))}return e}async executeQuery(e,t){let{inflightQueryAbortStrategy:n=`ignore query`,signal:r}=t||{};if(!r){let n=await this.provideConnection(async t=>await t.executeQuery(e),t);return await this.#t(n,e.queryId)}assertNotAborted(r,`before query execution`),t=freeze({signal:r});let{connection:i,release:a}=await provideControlledConnection(this,t),o=this.provideConnection.bind(this),{promise:s,resolve:c}=new Deferred,abortListener=()=>c(K);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let c=getInflightQueryAbortHandler(n,i,a);if(c&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([s,e]).catch(e=>{throw a(),e})===K&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let l=i.executeQuery(e,t),u=await Promise.race([s,l]).catch(e=>{throw a(),e});u===K?(Promise.allSettled([l.catch(printBackgroundFail(`query`)),c?.(o).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let d=this.#t(u,e.queryId,t),f=await Promise.race([s,d]);return f===K&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(K),r.removeEventListener(`abort`,abortListener)}}async*stream(e,t,n){let{signal:r}=n||{};if(!r){let{connection:r,release:i}=await provideControlledConnection(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId,n)}finally{i()}return}n=freeze({signal:r}),assertNotAborted(r,`before connection acquisition`);let{connection:i,release:a}=await provideControlledConnection(this,n),{promise:o,resolve:s}=new Deferred,abortListener=()=>s(K);r.addEventListener(`abort`,abortListener,{once:!0});let c,l;assertNotAborted(r,`before query streaming`,a);let{queryId:u}=e;try{for(c=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=c.next(),t=await Promise.race([o,e]);if(t===K&&(l=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,u,n),a=await Promise.race([o,i]);a===K&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(K),r.removeEventListener(`abort`,abortListener);let e=(c?.return?.()||Promise.resolve()).finally(()=>l).finally(a);l||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(freeze({queryId:t,result:e,signal:r}));return e}};const Le=new class NoopQueryExecutor extends QueryExecutorBase{get adapter(){throw Error(`this query cannot be compiled to SQL`)}compileQuery(){throw Error(`this query cannot be compiled to SQL`)}provideConnection(){throw Error(`this query cannot be executed`)}withConnectionProvider(){throw Error(`this query cannot have a connection provider`)}withPlugin(e){return new NoopQueryExecutor([...this.plugins,e])}withPlugins(e){return new NoopQueryExecutor([...this.plugins,...e])}withPluginAtFront(e){return new NoopQueryExecutor([e,...this.plugins])}withoutPlugins(){return new NoopQueryExecutor([])}};function createJoinBuilder(e,t){return new Ae({joinNode:k.create(e,parseTableExpression(t))})}function createOverBuilder(){return new Me({overNode:_e.create()})}function parseJoin(e,t){if(t.length===3)return parseSingleOnJoin(e,t[0],t[1],t[2]);if(t.length===2)return parseCallbackJoin(e,t[0],t[1]);if(t.length===1)return parseOnlessJoin(e,t[0]);throw Error(`not implemented`)}function parseCallbackJoin(e,t,n){return n(createJoinBuilder(e,t)).toOperationNode()}function parseSingleOnJoin(e,t,n,r){return k.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return k.create(e,parseTableExpression(t))}const Re=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),ze=freeze({is(e){return e.kind===`GroupByItemNode`},create(e){return freeze({kind:`GroupByItemNode`,groupBy:e})}});function parseGroupBy(e){return e=isFunction(e)?e(expressionBuilder()):e,parseReferenceExpressionOrList(e).map(ze.create)}const Be=freeze({is(e){return e.kind===`SetOperationNode`},create(e,t,n){return freeze({kind:`SetOperationNode`,operator:e,expression:t,all:n})}});function parseSetOperations(e,t,n){return isFunction(t)&&(t=t(createExpressionBuilder())),isReadonlyArray(t)||(t=[t]),t.map(t=>Be.create(e,parseExpression(t),n))}var q=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Ve(D.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new He(E.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new ExpressionWrapper(this.#e)}$notNull(){return new ExpressionWrapper(this.#e)}toOperationNode(){return this.#e}},AliasedExpressionWrapper=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return C.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():b.create(this.#t))}},Ve=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(D.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return z.create(this.#e)}},He=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(E.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return z.create(this.#e)}};const Ue=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:R.create(e),modifier:t}}});function parseFetch(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid fetch row count: ${e}`);if(!isFetchModifier(t))throw Error(`Invalid fetch modifier: ${t}`);return Ue.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var J,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new J({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new J({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new J({...this.#e,queryNode:W.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new J({...this.#e,queryNode:W.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new J({...this.#e,queryNode:W.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new J({...this.#e,queryNode:W.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new J({...this.#e,queryNode:W.cloneWithFrontModifier(this.#e.queryNode,T.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.createWithExpression(e.toOperationNode()))})}distinct(){return new J({...this.#e,queryNode:W.cloneWithFrontModifier(this.#e.queryNode,T.create(`Distinct`))})}forUpdate(e){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.create(`SkipLocked`))})}noWait(){return new J({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,T.create(`NoWait`))})}selectAll(e){return new J({...this.#e,queryNode:W.cloneWithSelections(this.#e.queryNode,parseSelectAll(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}crossJoin(...e){return this.#t(`CrossJoin`,e)}innerJoinLateral(...e){return this.#t(`LateralInnerJoin`,e)}leftJoinLateral(...e){return this.#t(`LateralLeftJoin`,e)}crossJoinLateral(...e){return this.#t(`LateralCrossJoin`,e)}crossApply(...e){return this.#t(`CrossApply`,e)}outerApply(...e){return this.#t(`OuterApply`,e)}#t(e,t){return new J({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new J({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new J({...this.#e,queryNode:W.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new J({...this.#e,queryNode:W.cloneWithLimit(this.#e.queryNode,Pe.create(parseValueExpression(e)))})}offset(e){return new J({...this.#e,queryNode:W.cloneWithOffset(this.#e.queryNode,Re.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new J({...this.#e,queryNode:W.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new J({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new J({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new J({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new J({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new J({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new J({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new J({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new J({...this.#e,queryNode:W.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new J({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new J({...this.#e,queryNode:W.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new J({...this.#e,queryNode:W.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new J({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new J({...this.#e,queryNode:W.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new J({...this.#e})}$castTo(){return new J(this.#e)}$narrowType(){return new J(this.#e)}$assertType(){return new J(this.#e)}$asTuple(){return new q(this.toOperationNode())}$asScalar(){return new q(this.toOperationNode())}withPlugin(e){return new J({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();return(await this.#e.executor.executeQuery(t,e)).rows}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new J({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};J=SelectQueryBuilderImpl;function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var AliasedSelectQueryBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return C.create(this.#e.toOperationNode(),b.create(this.#t))}};const Y=freeze({is(e){return e.kind===`AggregateFunctionNode`},create(e,t=[]){return freeze({kind:`AggregateFunctionNode`,func:e,aggregated:t})},cloneWithDistinct(e){return freeze({...e,distinct:!0})},cloneWithOrderBy(e,t,n=!1){let r=n?`withinGroup`:`orderBy`;return freeze({...e,[r]:e[r]?B.cloneWithItems(e[r],t):B.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`And`,t):V.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`Or`,t):V.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),We=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var Ge=class AggregateFunctionBuilder{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}as(e){return new AliasedAggregateFunctionBuilder(this,e)}distinct(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Y.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:U.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:U.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Y.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Y.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Y.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Y.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(t):t).toOperationNode())})}$call(e){return e(this)}$castTo(){return new AggregateFunctionBuilder(this.#e)}$notNull(){return new AggregateFunctionBuilder(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},AliasedAggregateFunctionBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return C.create(this.#e.toOperationNode(),b.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new q(We.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new Ge({aggregateFunctionNode:Y.create(e,t?parseReferenceExpressionOrList(t):void 0)});return Object.assign(fn,{agg,avg(e){return agg(`avg`,[e])},coalesce(...e){return fn(`coalesce`,e)},count(e){return agg(`count`,[e])},countAll(e){return new Ge({aggregateFunctionNode:Y.create(`count`,parseSelectAll(e))})},max(e){return agg(`max`,[e])},min(e){return agg(`min`,[e])},sum(e){return agg(`sum`,[e])},any(e){return fn(`any`,[e])},jsonAgg(e){return new Ge({aggregateFunctionNode:Y.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new q(We.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Ke=freeze({is(e){return e.kind===`UnaryOperationNode`},create(e,t){return freeze({kind:`UnaryOperationNode`,operator:e,operand:t})}});function parseUnaryOperation(e,t){if(isUnaryOperator(e))return Ke.create(P.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const X=freeze({is(e){return e.kind===`CaseNode`},create(e){return freeze({kind:`CaseNode`,value:e})},cloneWithWhen(e,t){return freeze({...e,when:freeze(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return freeze({...e,when:e.when?freeze([...e.when.slice(0,-1),H.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,H.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,H.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:X.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:X.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,H.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,H.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:X.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:X.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new q(X.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new q(X.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new q(X.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new q(X.cloneWith(this.#e.node,{isStatement:!0}))}};const qe=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Je=/^#-\d+$/;var JSONPathBuilder=class{#e;constructor(e){this.#e=e}at(e){if(typeof e!=`number`&&typeof e!=`string`||typeof e==`number`&&!Number.isInteger(e)||typeof e==`string`&&e!==`last`&&!Je.test(e))throw Error(`Unexpected index value in .at(...): ${e}`);return this.#t(`ArrayLocation`,e)}key(e){return this.#t(`Member`,e)}#t(e,t){return fe.is(this.#e)?new Ye(fe.cloneWithTraversal(this.#e,L.is(this.#e.traversal)?L.cloneWithLeg(this.#e.traversal,qe.create(e,t)):pe.cloneWithValue(this.#e.traversal,R.createImmediate(t)))):new Ye(L.cloneWithLeg(this.#e,qe.create(e,t)))}},Ye=class TraversedJSONPathBuilder extends JSONPathBuilder{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new AliasedJSONPathBuilder(this,e)}$castTo(){return new TraversedJSONPathBuilder(this.#e)}$notNull(){return new TraversedJSONPathBuilder(this.#e)}toOperationNode(){return this.#e}},AliasedJSONPathBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return C.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():b.create(this.#t))}};const Xe=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Ze=freeze({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),Qe=freeze([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),$e=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Ze[e]||Qe.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return $e.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const et=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=Le){function binary(e,t,n){return new q(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new q(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:W.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:X.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new q(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(L.create())},table(e){return new q(parseTable(e))},val(e){return new q(parseValueExpression(e))},refTuple(...e){return new q(Xe.create(e.map(parseReferenceExpression)))},tuple(...e){return new q(Xe.create(e.map(parseValueExpression)))},lit(e){return new q(parseSafeImmediateValue(e))},unary,not(e){return unary(`not`,e)},exists(e){return unary(`exists`,e)},neg(e){return unary(`-`,e)},between(e,t,n){return new q(A.create(parseReferenceExpression(e),P.create(`between`),E.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new q(A.create(parseReferenceExpression(e),P.create(`between symmetric`),E.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new q(parseFilterList(e,`and`)):new q(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new q(parseFilterList(e,`or`)):new q(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return z.is(t)?new q(t):new q(z.create(t))},cast(e,t){return new q(et.create(parseReferenceExpression(e),parseDataTypeExpression(t)))}});return t.fn=createFunctionModule(),t.eb=t,t}function expressionBuilder(e){return createExpressionBuilder()}function parseExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function parseAliasedExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function isExpressionOrFactory(e){return isExpression(e)||isAliasedExpression(e)||isFunction(e)}function isAliasedDynamicTableBuilder(e){return isObject(e)&&isOperationNodeSource(e)&&isString(e.table)&&isString(e.alias)}function parseTableExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseTableExpression(e)):[parseTableExpression(e)]}function parseTableExpression(e){return isString(e)?parseAliasedTable(e):isAliasedDynamicTableBuilder(e)?e.toOperationNode():parseAliasedExpression(e)}function parseAliasedTable(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim);return C.create(parseTable(n),b.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim);return w.createWithSchema(t,n)}return w.create(e)}function trim(e){return e.trim()}const tt=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:S.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var nt=class RawBuilderImpl{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new AliasedRawBuilderImpl(this,e)}$castTo(){return new RawBuilderImpl({...this.#e})}$notNull(){return new RawBuilderImpl(this.#e)}withPlugin(e){return new RawBuilderImpl({...this.#e,plugins:this.#e.plugins===void 0?freeze([e]):freeze([...this.#e.plugins,e])})}toOperationNode(){return this.#n(this.#t())}compile(e){return this.#r(this.#t(e))}async execute(e,t){let n=this.#t(e);return n.executeQuery(this.#r(n),t)}#t(e){let t=e===void 0?Le:e.getExecutor();return this.#e.plugins===void 0?t:t.withPlugins(this.#e.plugins)}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}};function createRawBuilder(e){return new nt(e)}var AliasedRawBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return C.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():b.create(this.#t))}};const Z=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:I.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:I.create(t,e.map(b.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(R.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithSql(e)})},join(e,t=Z`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=parseParameter(e[t]),t!==e.length-1&&(n[2*t+1]=r);return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChildren(n)})}});function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var OperationNodeVisitor=class{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=freeze({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}};const rt=/'/g,it=/['"]/g;var DefaultQueryCompiler=class extends OperationNodeVisitor{#e=``;#t=[];get numParameters(){return this.#t.length}compileQuery(e,t){return this.#e=``,this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),freeze({query:e,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){let t=this.parentNode!==void 0&&!z.is(this.parentNode)&&!xe.is(this.parentNode)&&!x.is(this.parentNode)&&!tt.is(this.parentNode)&&!Be.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`select`),e.distinctOn&&(this.append(` `),this.compileDistinctOn(e.distinctOn)),e.frontModifiers?.length&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.top&&(this.append(` `),this.visitNode(e.top)),e.selections&&(this.append(` `),this.compileList(e.selections)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.groupBy&&(this.append(` `),this.visitNode(e.groupBy)),e.having&&(this.append(` `),this.visitNode(e.having)),e.setOperations&&(this.append(` `),this.compileList(e.setOperations,` `)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),e.offset&&(this.append(` `),this.visitNode(e.offset)),e.fetch&&(this.append(` `),this.visitNode(e.fetch)),e.endModifiers?.length&&(this.append(` `),this.compileList(this.sortSelectModifiers(e.endModifiers),` `)),t&&this.append(`)`)}visitFrom(e){this.append(`from `),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append(`distinct on (`),this.compileList(e),this.append(`)`)}compileList(e,t=`, `){let n=e.length-1;for(let r=0;r<=n;r++)this.visitNode(e[r]),r<n&&this.append(t)}visitWhere(e){this.append(`where `),this.visitNode(e.where)}visitHaving(e){this.append(`having `),this.visitNode(e.having)}visitInsertQuery(e){let t=this.parentNode!==void 0&&!z.is(this.parentNode)&&!I.is(this.parentNode)&&!H.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(e.replace?`replace`:`insert`),e.orAction&&(this.append(` `),this.visitNode(e.orAction)),e.top&&(this.append(` `),this.visitNode(e.top)),e.into&&(this.append(` into `),this.visitNode(e.into)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.output&&(this.append(` `),this.visitNode(e.output)),e.values&&(this.append(` `),this.visitNode(e.values)),e.defaultValues&&(this.append(` `),this.append(`default values`)),e.onConflict&&(this.append(` `),this.visitNode(e.onConflict)),e.onDuplicateKey&&(this.append(` `),this.visitNode(e.onDuplicateKey)),e.returning&&(this.append(` `),this.visitNode(e.returning)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitValues(e){this.append(`values `),this.compileList(e.values)}visitDeleteQuery(e){let t=this.parentNode!==void 0&&!z.is(this.parentNode)&&!I.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`delete `),e.top&&(this.visitNode(e.top),this.append(` `)),this.visitNode(e.from),e.output&&(this.append(` `),this.visitNode(e.output)),e.using&&(this.append(` `),this.visitNode(e.using)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitReturning(e){this.append(`returning `),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(` as `),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(`.`)),this.visitNode(e.column)}visitSelectAll(e){this.append(`*`)}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!isString(e.name))throw Error(`a non-string identifier was passed to compileUnwrappedIdentifier.`);this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(` and `),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(` or `),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitTuple(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitPrimitiveValueList(e){this.append(`(`);let{values:t}=e;for(let e=0;e<t.length;++e)this.appendValue(t[e]),e!==t.length-1&&this.append(`, `);this.append(`)`)}visitParens(e){this.append(`(`),this.visitNode(e.node),this.append(`)`)}visitJoin(e){this.append(st[e.joinType]),this.append(` `),this.visitNode(e.table),e.on&&(this.append(` `),this.visitNode(e.on))}visitOn(e){this.append(`on `),this.visitNode(e.on)}visitRaw(e){let{sqlFragments:t,parameters:n}=e;for(let e=0;e<t.length;++e)this.append(t[e]),n.length>e&&this.visitNode(n[e])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){e.schema&&(this.visitNode(e.schema),this.append(`.`)),this.visitNode(e.identifier)}visitCreateTable(e){this.append(`create `),e.frontModifiers?.length&&(this.compileList(e.frontModifiers,` `),this.append(` `)),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.table),e.selectQuery||(this.append(` (`),this.compileList([...e.columns,...e.constraints??[],...e.indexes??[]]),this.append(`)`)),e.onCommit&&(this.append(` on commit `),this.append(e.onCommit)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `)),e.selectQuery&&(this.append(` as `),this.visitNode(e.selectQuery))}visitColumnDefinition(e){e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.column),this.append(` `),this.visitNode(e.dataType),e.unsigned&&this.append(` unsigned`),e.frontModifiers&&e.frontModifiers.length>0&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.generated&&(this.append(` `),this.visitNode(e.generated)),e.identity&&this.append(` identity`),e.defaultTo&&(this.append(` `),this.visitNode(e.defaultTo)),e.notNull&&this.append(` not null`),e.unique&&this.append(` unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.primaryKey&&this.append(` primary key`),e.autoIncrement&&(this.append(` `),this.append(this.getAutoIncrement())),e.references&&(this.append(` `),this.visitNode(e.references)),e.check&&(this.append(` `),this.visitNode(e.check)),e.endModifiers&&e.endModifiers.length>0&&(this.append(` `),this.compileList(e.endModifiers,` `))}getAutoIncrement(){return`auto_increment`}visitReferences(e){this.append(`references `),this.visitNode(e.table),this.append(` (`),this.compileList(e.columns),this.append(`)`),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate))}visitDropTable(e){this.append(`drop `),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifExists&&this.append(`if exists `),this.visitNode(e.table),e.cascade&&this.append(` cascade`)}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append(`order by `),this.compileList(e.items)}visitOrderByItem(e){this.visitNode(e.orderBy),e.collation&&(this.append(` `),this.visitNode(e.collation)),e.direction&&(this.append(` `),this.visitNode(e.direction)),e.nulls&&(this.append(` nulls `),this.append(e.nulls))}visitGroupBy(e){this.append(`group by `),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){let t=this.parentNode!==void 0&&!z.is(this.parentNode)&&!I.is(this.parentNode)&&!H.is(this.parentNode);if(this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`update `),e.top&&(this.visitNode(e.top),this.append(` `)),e.table&&(this.visitNode(e.table),this.append(` `)),this.append(`set `),e.updates&&this.compileList(e.updates),e.output&&(this.append(` `),this.visitNode(e.output)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins){if(!e.from)throw Error(`Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins`);this.append(` `),this.compileList(e.joins,` `)}e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitColumnUpdate(e){this.visitNode(e.column),this.append(` = `),this.visitNode(e.value)}visitLimit(e){this.append(`limit `),this.visitNode(e.limit)}visitOffset(e){this.append(`offset `),this.visitNode(e.offset)}visitOnConflict(e){this.append(`on conflict`),e.columns?(this.append(` (`),this.compileList(e.columns),this.append(`)`)):e.constraint?(this.append(` on constraint `),this.visitNode(e.constraint)):e.indexExpression&&(this.append(` (`),this.visitNode(e.indexExpression),this.append(`)`)),e.indexWhere&&(this.append(` `),this.visitNode(e.indexWhere)),e.doNothing===!0?this.append(` do nothing`):e.updates&&(this.append(` do update set `),this.compileList(e.updates),e.updateWhere&&(this.append(` `),this.visitNode(e.updateWhere)))}visitOnDuplicateKey(e){this.append(`on duplicate key update `),this.compileList(e.updates)}visitCreateIndex(e){this.append(`create `),e.unique&&this.append(`unique `),this.append(`index `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.using&&(this.append(` using `),this.visitNode(e.using)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.where&&(this.append(` `),this.visitNode(e.where))}visitDropIndex(e){this.append(`drop index `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.cascade&&this.append(` cascade`)}visitCreateSchema(e){this.append(`create schema `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.schema)}visitDropSchema(e){this.append(`drop schema `),e.ifExists&&this.append(`if exists `),this.visitNode(e.schema),e.cascade&&this.append(` cascade`)}visitPrimaryKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`primary key (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}buildDeferrable(e){e.deferrable!==void 0&&(e.deferrable?this.append(` deferrable`):this.append(` not deferrable`)),e.initiallyDeferred!==void 0&&(e.initiallyDeferred?this.append(` initially deferred`):this.append(` initially immediate`))}visitUniqueConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),this.append(` (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}visitCheckConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`check (`),this.visitNode(e.expression),this.append(`)`)}visitForeignKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`foreign key (`),this.compileList(e.columns),this.append(`) `),this.visitNode(e.references),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate)),this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){this.append(`with `),e.recursive&&this.append(`recursive `),this.compileList(e.expressions)}visitCommonTableExpression(e){this.visitNode(e.name),this.append(` as `),isBoolean(e.materialized)&&(e.materialized||this.append(`not `),this.append(`materialized `)),this.visitNode(e.expression)}visitCommonTableExpressionName(e){this.visitNode(e.table),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`)`))}visitAlterTable(e){this.append(`alter table `),this.visitNode(e.table),this.append(` `),e.renameTo&&(this.append(`rename to `),this.visitNode(e.renameTo)),e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema)),e.addConstraint&&this.visitNode(e.addConstraint),e.dropConstraint&&this.visitNode(e.dropConstraint),e.renameConstraint&&this.visitNode(e.renameConstraint),e.columnAlterations&&this.compileColumnAlterations(e.columnAlterations),e.addIndex&&this.visitNode(e.addIndex),e.dropIndex&&this.visitNode(e.dropIndex)}visitAddColumn(e){this.append(`add column `),this.visitNode(e.column)}visitRenameColumn(e){this.append(`rename column `),this.visitNode(e.column),this.append(` to `),this.visitNode(e.renameTo)}visitDropColumn(e){this.append(`drop column `),e.ifExists&&this.append(`if exists `),this.visitNode(e.column)}visitAlterColumn(e){this.append(`alter column `),this.visitNode(e.column),this.append(` `),e.dataType&&(this.announcesNewColumnDataType()&&this.append(`type `),this.visitNode(e.dataType),e.dataTypeExpression&&(this.append(`using `),this.visitNode(e.dataTypeExpression))),e.setDefault&&(this.append(`set default `),this.visitNode(e.setDefault)),e.dropDefault&&this.append(`drop default`),e.setNotNull&&this.append(`set not null`),e.dropNotNull&&this.append(`drop not null`)}visitModifyColumn(e){this.append(`modify column `),this.visitNode(e.column)}visitAddConstraint(e){this.append(`add `),this.visitNode(e.constraint)}visitDropConstraint(e){this.append(`drop constraint `),e.ifExists&&this.append(`if exists `),this.visitNode(e.constraintName),e.modifier===`cascade`?this.append(` cascade`):e.modifier===`restrict`&&this.append(` restrict`)}visitRenameConstraint(e){this.append(`rename constraint `),this.visitNode(e.oldName),this.append(` to `),this.visitNode(e.newName)}visitSetOperation(e){this.append(e.operator),this.append(` `),e.all&&this.append(`all `),this.visitNode(e.expression)}visitCreateView(e){this.append(`create `),e.orReplace&&this.append(`or replace `),e.materialized&&this.append(`materialized `),e.temporary&&this.append(`temporary `),this.append(`view `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),this.append(` `),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`) `)),e.as&&(this.append(`as `),this.visitNode(e.as))}visitRefreshMaterializedView(e){this.append(`refresh materialized view `),e.concurrently&&this.append(`concurrently `),this.visitNode(e.name),e.withNoData?this.append(` with no data`):this.append(` with data`)}visitDropView(e){this.append(`drop `),e.materialized&&this.append(`materialized `),this.append(`view `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.cascade&&this.append(` cascade`)}visitGenerated(e){this.append(`generated `),e.always&&this.append(`always `),e.byDefault&&this.append(`by default `),this.append(`as `),e.identity&&this.append(`identity`),e.expression&&(this.append(`(`),this.visitNode(e.expression),this.append(`)`)),e.stored&&this.append(` stored`)}visitDefaultValue(e){this.append(`default `),this.visitNode(e.defaultValue)}visitSelectModifier(e){e.rawModifier?this.visitNode(e.rawModifier):this.append(at[e.modifier]),e.of&&(this.append(` of `),this.compileList(e.of,`, `))}visitCreateType(e){this.append(`create type `),this.visitNode(e.name),e.enum&&(this.append(` as enum `),this.visitNode(e.enum))}visitDropType(e){this.append(`drop type `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.additionalNames?.length&&(this.append(`, `),this.compileList(e.additionalNames)),e.cascade&&this.append(` cascade`)}visitAlterType(e){this.append(`alter type `),this.visitNode(e.name),this.append(` `),e.addValue?this.visitNode(e.addValue):e.renameTo?(this.append(`rename to `),this.visitNode(e.renameTo)):e.renameValue?this.visitNode(e.renameValue):e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema))}visitAddValue(e){this.append(`add value `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.value),e.neighborValue&&(this.append(e.isBefore?` before `:` after `),this.visitNode(e.neighborValue))}visitRenameValue(e){this.append(`rename value `),this.visitNode(e.oldValue),this.append(` to `),this.visitNode(e.newValue)}visitExplain(e){this.append(`explain`),(e.options||e.format)&&(this.append(` `),this.append(this.getLeftExplainOptionsWrapper()),e.options&&(this.visitNode(e.options),e.format&&this.append(this.getExplainOptionsDelimiter())),e.format&&(this.append(`format`),this.append(this.getExplainOptionAssignment()),this.append(e.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(e){this.append(`default`)}visitAggregateFunction(e){this.append(e.func),this.append(`(`),e.distinct&&this.append(`distinct `),this.compileList(e.aggregated),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),this.append(`)`),e.withinGroup&&(this.append(` within group (`),this.visitNode(e.withinGroup),this.append(`)`)),e.filter&&(this.append(` filter(`),this.visitNode(e.filter),this.append(`)`)),e.over&&(this.append(` `),this.visitNode(e.over))}visitOver(e){this.append(`over(`),e.partitionBy&&(this.visitNode(e.partitionBy),e.orderBy&&this.append(` `)),e.orderBy&&this.visitNode(e.orderBy),this.append(`)`)}visitPartitionBy(e){this.append(`partition by `),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(` `),this.visitNode(e.operator),this.append(` `),this.visitNode(e.rightOperand)}visitUnaryOperation(e){this.visitNode(e.operator),this.isMinusOperator(e.operator)||this.append(` `),this.visitNode(e.operand)}isMinusOperator(e){return P.is(e)&&e.operator===`-`}visitUsing(e){this.append(`using `),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append(`(`),this.compileList(e.arguments),this.append(`)`)}visitCase(e){this.append(`case`),e.value&&(this.append(` `),this.visitNode(e.value)),e.when&&(this.append(` `),this.compileList(e.when,` `)),e.else&&(this.append(` else `),this.visitNode(e.else)),this.append(` end`),e.isStatement&&this.append(` case`)}visitWhen(e){this.append(`when `),this.visitNode(e.condition),e.result&&(this.append(` then `),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append(`'$`);for(let t of e.pathLegs)this.visitNode(t);this.append(`'`)}visitJSONPathLeg(e){let t=e.type===`ArrayLocation`,n=String(e.value);t?(this.append(`[`),this.append(this.sanitizeStringLiteral(n)),this.append(`]`)):(this.append(`."`),this.append(this.sanitizeJSONPathMemberValue(n)),this.append(`"`))}visitJSONOperatorChain(e){for(let t=0,n=e.values.length;t<n;t++)t===n-1?this.visitNode(e.operator):this.append(`->`),this.visitNode(e.values[t])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`merge `),e.top&&(this.visitNode(e.top),this.append(` `)),this.append(`into `),this.visitNode(e.into),e.using&&(this.append(` `),this.visitNode(e.using)),e.whens&&(this.append(` `),this.compileList(e.whens,` `)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.output&&(this.append(` `),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitMatched(e){e.not&&this.append(`not `),this.append(`matched`),e.bySource&&this.append(` by source`)}visitAddIndex(e){(!this.parentNode||!x.is(this.parentNode))&&this.append(`add `),e.unique&&this.append(`unique `),this.append(`index `),this.visitNode(e.name),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.using&&(this.append(` using `),this.visitNode(e.using))}visitCast(e){this.append(`cast(`),this.visitNode(e.expression),this.append(` as `),this.visitNode(e.dataType),this.append(`)`)}visitFetch(e){this.append(`fetch next `),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append(`output `),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append(`collate `),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getCurrentParameterPlaceholder(){return`$`+this.numParameters}getLeftExplainOptionsWrapper(){return`(`}getExplainOptionAssignment(){return` `}getExplainOptionsDelimiter(){return`, `}getRightExplainOptionsWrapper(){return`)`}sanitizeIdentifier(e){let t=this.getLeftIdentifierWrapper(),n=this.getRightIdentifierWrapper(),r=``;for(let i of e)r+=i,i===t?r+=t:i===n&&(r+=n);return r}sanitizeStringLiteral(e){return e.replace(rt,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(it,e=>e===`'`?`''`:`\\"`)}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(isString(e))this.appendStringLiteral(e);else if(isNumber(e)||isBoolean(e)||isBigInt(e))this.append(e.toString());else if(isNull(e))this.append(`null`);else if(isDate(e))this.appendImmediateValue(e.toISOString());else throw Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append(`'`),this.append(this.sanitizeStringLiteral(e)),this.append(`'`)}sortSelectModifiers(e){return freeze(e.toSorted((e,t)=>e.modifier&&t.modifier?ot[e.modifier]-ot[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const at=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),ot=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),st=freeze({InnerJoin:`inner join`,LeftJoin:`left join`,RightJoin:`right join`,FullJoin:`full join`,CrossJoin:`cross join`,LateralInnerJoin:`inner join lateral`,LateralLeftJoin:`left join lateral`,LateralCrossJoin:`cross join lateral`,OuterApply:`outer apply`,CrossApply:`cross apply`,Using:`using`}),Q=freeze({raw(e,t=[]){return freeze({sql:e,query:I.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}});var DialectAdapterBase=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function parseSavepointCommand(e,t){return I.createWithChildren([I.createWithSql(`${e} `),b.create(t)])}var SqliteDriver=class{#e;#t;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#t=isFunction(this.#e.database)?await this.#e.database(e):this.#e.database,this.#n=new SqliteConnection(this.#t),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#n,e)}async acquireConnection(){return this.#n}async beginTransaction(e){await e.executeQuery(Q.raw(`begin`))}async commitTransaction(e){await e.executeQuery(Q.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Q.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(){}async destroy(){this.#t?.close()}},SqliteConnection=class{#e;constructor(e){this.#e=e}async executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t);if(r.reader)return{rows:r.all(n)};let{changes:i,lastInsertRowid:a}=r.run(n);return{insertId:a==null?void 0:BigInt(a),numAffectedRows:i==null?void 0:BigInt(i),rows:[]}}async*streamQuery(e,t){let{sql:n,parameters:r,query:i}=e,a=this.#e.prepare(n);if(!W.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let o=a.iterate(r);for(let e of o)yield{rows:[e]}}};const ct=/"/g,lt=/[\\'"]/g;var SqliteQueryCompiler=class extends DefaultQueryCompiler{visitOrAction(e){this.append(`or `),this.append(e.action)}getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}sanitizeIdentifier(e){return e.replace(ct,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(lt,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const ut=`kysely_migration`,dt=`kysely_migration_lock`;freeze({__noMigrations__:!0});var SqliteIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#n(e)}#t(e,t){let n=e.selectFrom(`sqlite_master`).where(`type`,`in`,[`table`,`view`]).where(`name`,`not like`,`sqlite_%`).select([`name`,`sql`,`type`]).orderBy(`name`);return t.withInternalKyselyTables||(n=n.where(`name`,`!=`,ut).where(`name`,`!=`,dt)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,Z`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject(e)&&isString(e.stack)}const ft=Symbol();var PostgresDriver=class{#e;#t=/* @__PURE__ */ new WeakMap;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#n=isFunction(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#n.connect();if(!this.#n)throw t.release(),Error(`driver has already been destroyed`);let n=this.#t.get(t);return n||(n=new PostgresConnection(t,{controlClient:this.#e.controlClient||this.#n.Client,cursor:this.#e.cursor??null,poolOptions:this.#n.options}),this.#t.set(t,n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){let n=`begin`;(t.isolationLevel||t.accessMode)&&(n=`start transaction`,t.isolationLevel&&(n+=` isolation level ${t.isolationLevel}`),t.accessMode&&(n+=` ${t.accessMode}`)),await e.executeQuery(Q.raw(n))}async commitTransaction(e){await e.executeQuery(Q.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Q.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(e){e[ft]()}async destroy(){if(this.#n){let e=this.#n;this.#n=void 0,await e.end()}}},PostgresConnection=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=t}async cancelQuery(e){return await this.#i(`select pg_cancel_backend(${this.#r})`,e)}async collectSessionInfo(){if(this.#r)return;let{processID:e}=this.#e;if(e)this.#r=e;else{let{rows:[{pid:e}]}=await this.#e.query(`select pg_backend_pid() as pid`,[]);this.#r=Number(e)}}async executeQuery(e){try{this.#n=e.queryId;let{command:t,rowCount:n,rows:r}=await this.#e.query(e.sql,e.parameters);return{numAffectedRows:t===`INSERT`||t===`UPDATE`||t===`DELETE`||t===`MERGE`?BigInt(n):void 0,rows:r??[]}}catch(e){throw extendStackTrace(e,/* @__PURE__ */ Error())}finally{this.#n=void 0}}async killSession(e){return await this.#i(`select pg_terminate_backend(${this.#r})`,e)}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#n=e.queryId;let n=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{for(;;){let e=await n.read(t);if(e.length===0)break;yield{rows:e}}}finally{await n.close(),this.#n=void 0}}[ft](){this.#e.release()}async#i(e,t){if(!this.#n)return;let{controlClient:n,poolOptions:r}=this.#t,i=this.#n;if(!n)return await t(async t=>{i.queryId===this.#n?.queryId&&await t.executeQuery(Q.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,Z`col_description(a.attrelid, a.attnum)`.as(`column_description`),Z`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where(Z`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,ut).where(`c.relname`,`!=`,dt));let n=await t.execute();return this.#t(n)}#t(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=n.get(r.schema);e||(e=/* @__PURE__ */ new Map,n.set(r.schema,e));let i=e.get(r.table);i||(i=freeze({columns:[],isForeign:r.table_type===`f`,isView:r.table_type===`v`,name:r.table,schema:r.schema}),e.set(r.table,i),t.push(i)),i.columns.push(freeze({comment:r.column_description??void 0,dataType:r.type,dataTypeSchema:r.type_schema,hasDefaultValue:r.has_default,isAutoIncrementing:r.auto_incrementing!==null,isNullable:!r.not_null,name:r.column}))}return t}};const pt=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(pt,`""`)}};const mt=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await Z`
    with set_timeout as (
      select set_config('lock_timeout', '${Z.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${Z.lit(mt)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await Z`select pg_advisory_unlock(${Z.lit(mt)})`.execute(e)}},PostgresDialect=class{#e;constructor(e){this.#e=e}createDriver(){return new PostgresDriver(this.#e)}createQueryCompiler(){return new PostgresQueryCompiler}createAdapter(){return new PostgresAdapter}createIntrospector(e){return new PostgresIntrospector(e)}};const ht=/^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,$=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],gt=$[$.length-1];`${$.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<$.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=ht.exec(e.trim());if(!t)return null;let n={major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])};return Object.values(n).every(Number.isSafeInteger)&&(!t[4]||n.major>gt.major)?n:null}function isNodeVersionAtLeast(e,t){return e?e.major===t.major?e.minor===t.minor?e.patch>=t.patch:e.minor>t.minor:e.major>t.major:!1}function renderProcessNodeVersionCheck(){return`((value) => {
  if (typeof value !== "string") return false;
  const match = new RegExp(${JSON.stringify(ht.source)}, "u").exec(value.trim());
  if (!match) return false;
  const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
  if (!Object.values(version).every(Number.isSafeInteger)) return false;
  const floors = ${JSON.stringify($)};
  if (match[4] && version.major <= floors[floors.length - 1].major) return false;
  const minimum = floors.find((floor) => floor.major === version.major);
  const atLeast = (floor) =>
    version.major > floor.major ||
    (version.major === floor.major &&
      (version.minor > floor.minor ||
        (version.minor === floor.minor && version.patch >= floor.patch)));
  return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major;
})(process.versions.node)`}renderProcessNodeVersionCheck();const{kyselyByDatabase:_t,queryErrorHandlerByDatabase:vt}=e(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap})),templateFragments=(e,t)=>e,yt=templateFragments`(SELECT value FROM json_each(${0}))`,bt=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!I.is(e)||e.sqlFragments!==yt||e.parameters.length!==1)return;let t=e.parameters[0];for(;I.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!R.is(t)||t.immediate||typeof t.value!=`string`)return;let n;try{n=JSON.parse(t.value)}catch{return}if(Array.isArray(n)&&n.every(e=>typeof e==`string`))return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(P.is(e.operator)&&e.operator.operator===`in`){let t=postgresStringArray(e.rightOperand);if(t!==void 0){this.visitNode(e.leftOperand),this.append(` = ANY(`),this.appendValue(t),this.append(`::text[])`);return}}super.visitBinaryOperation(e)}visitRaw(e){let t=e.sqlFragments===yt;!t&&e.sqlFragments!==bt?super.visitRaw(e):(this.append(t?`(SELECT value FROM json_array_elements_text(`:`(SELECT ordinality - 1 AS key, value FROM json_array_elements_text(`),this.compileList(e.parameters),this.append(t?`::json) AS value)`:`::json) WITH ORDINALITY AS entries(value, ordinality))`))}},OpenClawPostgresDialect=class extends PostgresDialect{createQueryCompiler(){return new OpenClawPostgresQueryCompiler}};const xt=parseNodeReleaseVersion(process.versions.node);!process.versions.bun&&(xt?.major===24&&isNodeVersionAtLeast(xt,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(xt,{major:26,minor:6,patch:0})),new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});const{busyTimeoutByDatabase:St,trackedDatabases:Ct}=e(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}));e(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap),e(Symbol.for(`openclaw.postgresReadSnapshots`),()=>/* @__PURE__ */ new WeakMap),t(`sqlite/transaction`),e(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map);function shellEscape(e){return`'${e.replaceAll(`'`,`'"'"'`)}'`}function localWorkspaceDigestBytes(e){if(!/^sha256:[a-f0-9]{64}$/u.test(e))throw Error(`Invalid local workspace tree digest`);return Uint8Array.from(Buffer.from(e.slice(7),`hex`))}function localWorkspaceDigestReference(e){return`sha256:${Buffer.from(e).toString(`hex`)}`}function encodeLocalWorkspaceTreePacks(e,t){let n=/* @__PURE__ */ new Set([``]);if(t===void 0)for(let t of e.values())t.children!==null&&n.add(t.children);else for(let r of t){if(r===``)continue;let t=r.slice(0,Math.max(0,r.lastIndexOf(`/`))),i=e.get(t)?.children;i!=null&&n.add(i)}return[...n].map(t=>{let n=e.get(t),r=[],i=[],a=[n];for(;a.length;){let t=a.pop();r.push(t),t.children!==null&&i.push(e.get(t.children).treeRef);for(let n of[t.left,t.right])n!==null&&a.push(e.get(n))}return{treeRef:n.treeRef,records:r,children:i}})}function prepareLocalWorkspaceTreePacks(e,t){let n=encodeLocalWorkspaceTreePacks(e,t),r=[];for(let e=0;e<n.length;e+=256)r.push(y(g({packs:n.slice(e,e+256)})));return r}const wt=/* @__PURE__ */ `sandbox_persistent_execs.user_profile_identities.user_background_images.local_workspace_projections.local_workspace_manifest_nodes.local_workspace_tree_packs.local_workspace_source_path_sets.update_runs.session_repository_workspaces.github_repository_publication_requests.github_publication_session_lifecycles.skill_library_entries.skill_library_revisions.skill_library_events.skill_library_uploads.github_personal_publication_requests.cron_job_runtime_authorities.cron_run_trigger_state_retirements.execution_identity_contexts.mcp_oauth_pending_authorizations.node_worker_launch_containers.node_worker_launch_boots.node_worker_launch_cleanup.node_worker_launch_process_scopes.node_worker_launches.node_worker_prepared_workspaces.node_worker_turns.operator_approval_execution_identities.operator_approval_standing_grants.operator_approval_standing_grant_generations.web_push_approval_deliveries.execution_decision_facts.execution_owner_lifecycle_bindings.outbound_message_execution_bindings.outbound_message_progress`.split(`.`),Tt=[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`,`idx_user_profile_identities_profile_id`,`idx_user_profile_identities_authorization`,`idx_update_runs_created`,`idx_update_runs_active`,`idx_github_repository_publication_shared_request`,`idx_github_repository_publication_personal_request`,`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`,`idx_node_worker_launches_terminal_completed`,`idx_node_worker_turns_terminal_completed`,`idx_node_worker_turns_active_owner`,`idx_operator_approval_standing_grants_binding`,`idx_web_push_approval_deliveries_subscription`,`execution_identity_contexts_run_created_idx`,`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_run_occurred_idx`,`outbound_message_execution_bindings_execution_event_idx`,`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`];[...wt],[...Tt],[i(r,`local_workspace_projections`),i(r,`local_workspace_manifest_nodes`),i(r,`local_workspace_tree_packs`),i(r,`local_workspace_source_path_sets`)].join(`
`),`${i(r,`user_profile_identities`)}`;let Et;function resolveZstdCodec(){return Et??={compress:(e,t,n)=>t===void 0&&n===void 0?v.zstdCompressSync(e):v.zstdCompressSync(e,{params:{...t===void 0?{}:{[v.constants.ZSTD_c_compressionLevel]:t},...n===void 0?{}:{[v.constants.ZSTD_c_checksumFlag]:n}}}),decompress:(e,t)=>v.zstdDecompressSync(e,t===void 0?void 0:{maxOutputLength:t,chunkSize:Math.max(v.constants.Z_MIN_CHUNK,Math.min(v.constants.Z_DEFAULT_CHUNK,t+1))})}}function filePaths(e){let t=[];for(let{node:n}of e.values())n.type===`file`&&t.push(n.path);return t.sort(),t}function prepareLocalWorkspaceFingerprints(e,t,n,r){let i=n===null||Buffer.isBuffer(n)?n:Buffer.from(n.buffer,n.byteOffset,n.byteLength),a=filePaths(e),o;if(n)try{let e=resolveZstdCodec().decompress(n,45+d*16);e.length===45+a.length*16&&e.readUInt8(0)===1&&e.subarray(9,41).equals(Buffer.from(t.slice(7),`hex`))&&e.readUInt32LE(41)===a.length&&(o=e)}catch{}let c=/* @__PURE__ */ new Map;for(let e=0;e<a.length;e++)c.set(a[e],45+e*16);let l=o?.readBigUInt64LE(1),u=/* @__PURE__ */ new Map,f=/* @__PURE__ */ new Map,p=o!==void 0,m=0;return{reuseFile(t,n,i){let a=c.get(t),d=e.get(t)?.node;if(!o||a===void 0||d?.type!==`file`)p=!1;else{if(i.dev===l&&i.ino===o.readBigUInt64LE(a)&&i.ctimeNs===o.readBigInt64LE(a+8)&&d.size===Number(i.size)&&s(i.ctimeNs,r))return u.set(t,n),d;p=!1}},observe(e,t){u.get(e)===t?m++:(p=!1,u.delete(e),f.set(e,t))},encode(e,n){if(n===t&&p&&m===a.length)return i;let d=a;if(n!==t){let t=a.filter(t=>e.get(t)?.node.type===`file`),n=[];for(let{node:t}of e.values())t.type===`file`&&!c.has(t.path)&&n.push(t.path);n.sort(),d=[];let r=0;for(let e of t){for(;r<n.length&&n[r]<e;)d.push(n[r++]);d.push(e)}for(;r<n.length;)d.push(n[r++])}let h=Buffer.alloc(45+d.length*16);h.writeUInt8(1,0),Buffer.from(n.slice(7),`hex`).copy(h,9),h.writeUInt32LE(d.length,41);let g;for(let e=0;e<d.length;e++){let t=d[e],n=45+e*16;if(u.has(t)){let e=c.get(t);if(g??=l,g!==l)return null;o.copy(h,n,e,e+16);continue}let i=f.get(t);if(!i)return null;let a=i.split(`:`),p=BigInt(a[1]);if(g??=p,p!==g)return null;let m=BigInt(a[5]);h.writeBigUInt64LE(BigInt(a[2]),n),h.writeBigInt64LE(s(m,r)?m:-1n,n+8)}return h.writeBigUInt64LE(g??0n,1),resolveZstdCodec().compress(h)}}}function decodeLocalWorkspaceGitPaths(e){if(!_(e))throw Error(`Local sandbox source paths must be UTF-8; rename the invalid Git path before retrying`);return e.toString(`utf8`).split(`\0`).filter(Boolean)}function parseLocalWorkspaceSourcePaths(e){let t=JSON.parse(e);if(!n(t))throw Error(`Invalid local workspace source admission`);return t}async function readLocalWorkspaceGitExclusions(e,t,n){let r=await a(e,[`--work-tree=${t}`,`ls-files`,`--full-name`,`--others`,`--ignored`,`--exclude-standard`,`--directory`,`-z`]);return{paths:new Set(decodeLocalWorkspaceGitPaths(r)),retainedPaths:n}}async function selectLocalWorkspaceCanonicalPaths(e){e.signal?.throwIfAborted(),e.assertCurrent();let t;if(e.preparedPaths)t=new Set(e.preparedPaths);else{let n=await a(e.root,[`ls-files`,`--cached`,`-z`],{signal:e.signal,beforeRun:e.assertCurrent});e.assertCurrent();let r=parseLocalWorkspaceSourcePaths(e.admittedPaths);t=/* @__PURE__ */ new Set([...r,...decodeLocalWorkspaceGitPaths(n)])}if(e.baselinePaths)for(let n of e.baselinePaths)t.add(n);for(let e of t){let n=e.lastIndexOf(`/`);n!==-1&&t.add(e.slice(0,n))}return t}function digest(e,...t){return`sha256:${h(`sha256`).update(JSON.stringify([`openclaw.local-workspace.${e}.v1`,...t])).digest(`hex`)}`}const Dt=digest(`empty`);function parentPath(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function localWorkspaceManifestRootReference(e,t){return digest(`root`,t,e.get(``).treeRef)}function createLocalWorkspaceManifestTree(e){let t={node:{path:``,type:`directory`},priority:``},n=/* @__PURE__ */ new Map([[``,t]]),r=/* @__PURE__ */ new Map;for(let t of e.toSorted((e,t)=>e.path<t.path?-1:+(e.path>t.path))){if(t.path===``)throw Error(`The workspace manifest root cannot be changed`);let e=parentPath(t.path),i=n.get(e);if(i?.node.type!==`directory`)throw Error(`Missing workspace manifest directory: ${e}`);let a={node:t,priority:digest(`priority`,t.path)},o=r.get(e)??[];for(;o.length&&o.at(-1).priority>a.priority;)a.left=o.pop();let s=o.at(-1);s?s.right=a:i.children=a,o.push(a),r.set(e,o),n.set(t.path,a)}let i=/* @__PURE__ */ new Map,finish=e=>{if(!e)return;let t=manifestRecord(e.node,finish(e.left),finish(e.right),finish(e.children));return i.set(e.node.path,t),t};return finish(t),i}function manifestRecord(e,t,n,r,i){let a=e.type===`directory`?digest(`directory`,e.path,r?.treeRef??Dt):i?.node===e?i.contentRef:e.type===`file`?digest(`file`,e.path,e.mode,e.size,e.sha256):digest(`symlink`,e.path,e.mode,e.target);return{node:e,left:t?.node.path??null,right:n?.node.path??null,children:r?.node.path??null,contentRef:a,treeRef:digest(`siblings`,t?.treeRef??Dt,a,n?.treeRef??Dt)}}function updateLocalWorkspaceManifestTree(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,recordAt=t=>t===null?void 0:e.get(t);function write(t,i,a,o){let s=manifestRecord(t,recordAt(i),recordAt(a),recordAt(o),e.get(t.path));e.set(t.path,s),n.set(t.path,s),r.delete(t.path)}function priority(e){let t=i.get(e);return t===void 0&&(t=digest(`priority`,e),i.set(e,t)),t}function precedes(e,t){let n=priority(e),r=priority(t);return n<r||n===r&&e<t}function insert(t,n){if(t===null)return write(n,null,null,null),n.path;let r=e.get(t);if(n.path===t){if(n.type!==`directory`&&r.children!==null)throw Error(`Cannot replace nonempty workspace directory: ${t}`);return write(n,r.left,r.right,r.children),t}if(n.path<t){let i=insert(r.left,n);if(precedes(i,t)){let n=e.get(i);return write(r.node,n.right,r.right,r.children),write(n.node,n.left,t,n.children),i}write(r.node,i,r.right,r.children)}else{let i=insert(r.right,n);if(precedes(i,t)){let n=e.get(i);return write(r.node,r.left,n.left,r.children),write(n.node,t,n.right,n.children),i}write(r.node,r.left,i,r.children)}return t}function merge(t,n){if(t===null||n===null)return t??n;if(precedes(t,n)){let r=e.get(t);return write(r.node,r.left,merge(r.right,n),r.children),t}let r=e.get(n);return write(r.node,merge(t,r.left),r.right,r.children),n}function remove(t,i){if(t===null)return null;let a=e.get(t);if(i===t){if(a.children!==null)throw Error(`Cannot remove nonempty workspace directory: ${t}`);let i=merge(a.left,a.right);return e.delete(t),n.delete(t),r.add(t),i}return i<t?write(a.node,remove(a.left,i),a.right,a.children):write(a.node,a.left,remove(a.right,i),a.children),t}function refresh(t,n){let r=e.get(t);return write(r.node,n<t?refresh(r.left,n):r.left,n>t?refresh(r.right,n):r.right,r.children),t}e.has(``)||write({path:``,type:`directory`},null,null,null);let a=t.toSorted((e,t)=>{if(!!e.node!=!!t.node)return e.node?1:-1;let n=e.path<t.path?-1:+(e.path>t.path);return e.node?n:-n});for(let t of a){if(t.path===``)throw Error(`The workspace manifest root cannot be changed`);if(!t.node&&!e.has(t.path))continue;let n=parentPath(t.path),r=e.get(n);if(r?.node.type!==`directory`)throw Error(`Missing workspace manifest directory: ${n}`);let i=t.node?insert(r.children,t.node):remove(r.children,t.path);for(;;){let t=e.get(n);if(write(t.node,t.left,t.right,i),n===``)break;let r=parentPath(n);i=refresh(e.get(r).children,n),n=r}}return{records:[...n.values()],removed:[...r]}}function manifestDocument(e,t,n,r=`current`){let i={version:1,baseCommit:t,entries:[],directories:[],...n?{buildCacheInputs:n}:{}};for(let t of e)t.type===`directory`?i.directories.push(t.path):i.entries.push(t);let a=u(i,r);return{rawManifest:a,manifestRef:`sha256:${h(`sha256`).update(a).digest(`hex`)}`}}function prepareUpdate(e,t=[]){let n=e.manifest,r={...e.patch,...n?{baseline_ref:n.resultingRoot,baseline_json:null}:{},...n?.treeRoot?{tree_root_digest:localWorkspaceDigestBytes(n.treeRoot)}:{},...n?.fingerprints?{[n.fingerprints.target===`canonical`?`canonical_fingerprints`:`projection_fingerprints`]:Buffer.from(n.fingerprints.blob,`base64`)}:{}};return{revision:e.revision,patch:r,mutation:y(g({...e,patch:r})),preparations:t}}async function executeLocalWorkspaceManifestRead(e,t){let{row:n}=e;if(t.kind===`repair`){if(!n.baseline_ref)throw Error(`Local workspace repair requires its saved baseline reference`);let r=n.tree_root_digest?localWorkspaceDigestReference(n.tree_root_digest):n.baseline_ref,i=f(parseLocalWorkspaceSourcePaths(n.source_paths_json)),a=n.checkpoint_json?JSON.parse(n.checkpoint_json):void 0,o=a?[c(a.baseManifestRaw,a.baseManifestRef,[...i],`stored`),c(a.currentManifestRaw,a.currentManifestRef,[...i],`stored`)].map(e=>new Map([...e.entries.map(e=>[e.path,e]),...(e.directories??[]).map(e=>[e,{path:e,type:`directory`}])])):[],s=new Set(e.records.keys());s.delete(``);let l=new Set([...e.records.values()].filter(({node:e})=>e.type===`directory`&&e.path!==``).map(({node:e})=>e.path));for(let e of o[1]?.values()??[])e.type===`directory`&&l.add(e.path);let u,d;for(let e of[!1,!0]){let c,f;for(let m of[`projection`,`canonical`,`canonicalWithProjectionPaths`]){let h=m===`canonicalWithProjectionPaths`;if(h&&!c)continue;let g=m===`projection`?n.projection_path:t.canonicalRoot,_=[];try{let t,r=new Set(l);if(m!==`projection`){if(u??=await selectLocalWorkspaceCanonicalPaths({root:g,admittedPaths:n.source_paths_json,baselinePaths:s,assertCurrent:()=>void 0}),t=new Set(u),h){for(let e of c)t.add(e);for(let e of f)r.add(e)}for(let e of o)for(let n of e.keys())t.add(n)}await p({root:g,baseCommit:n.base_commit,includePaths:t,preserveDirectories:r,buildCacheInputs:i,includeLegacyPnpmStore:e,onEntry:e=>_.push(e)})}catch(e){d=e;continue}m===`projection`&&(c=new Set(_.map(e=>e.path)),f=new Set(_.filter(e=>e.type===`directory`).map(e=>e.path)));let v=createLocalWorkspaceManifestTree(_);if(a&&v.get(``).treeRef===a.treeRoot&&r===a.previousTreeRoot){let[e,t]=o;updateLocalWorkspaceManifestTree(v,[.../* @__PURE__ */ new Set([...e.keys(),...t.keys()])].map(t=>({path:t,node:e.get(t)})))}let y=v.get(``).treeRef,b=[...v.values()].map(({node:e})=>e).filter(e=>e.path!==``);if((n.tree_root_digest?y:n.baseline_json?manifestDocument(b,n.base_commit,void 0,`stored`).manifestRef:localWorkspaceManifestRootReference(v,n.base_commit))===r)return{kind:`replace`,update:prepareUpdate({kind:`update`,revision:n.revision,patch:{tree_root_digest:localWorkspaceDigestBytes(y),...!n.tree_root_digest&&!n.pending_ref?{baseline_json:null}:{},canonical_fingerprints:null,projection_fingerprints:null}},prepareLocalWorkspaceTreePacks(v))}}}throw Error(`Local workspace baseline nodes are missing and neither workspace matches the saved baseline or a verified checkpoint. Both workspaces were preserved: canonical ${t.canonicalRoot}; sandbox ${n.projection_path}. A Gateway administrator must recover the saved baseline inventory before retrying the session. Inspect the preserved changes with: diff -ru -- ${shellEscape(t.canonicalRoot)} ${shellEscape(n.projection_path)}. Do not recreate or delete either workspace; retrying cannot safely choose between divergent edits.`,{cause:d})}if(t.kind===`replace`){let e=c(t.rawManifest,t.manifestRef,t.buildCacheInputs),r=createLocalWorkspaceManifestTree([...e.entries,...(e.directories??[]).map(e=>({path:e,type:`directory`}))]),i=localWorkspaceManifestRootReference(r,e.baseCommit);return{kind:`replace`,update:prepareUpdate({kind:`update`,revision:n.revision,patch:t.patch,manifest:{previousRoot:n.baseline_ref,resultingRoot:i,records:[],removed:[],treeRoot:r.get(``).treeRef,previousTreeRoot:n.tree_root_digest?localWorkspaceDigestReference(n.tree_root_digest):null,replace:!0}},prepareLocalWorkspaceTreePacks(r))}}if(t.kind===`materialize`&&n.baseline_json&&n.baseline_ref)return{kind:`materialize`,rawManifest:n.baseline_json,manifestRef:n.baseline_ref};let{records:r}=e,i=t.kind===`prepare`&&t.manifest.replace;if(i&&(r=new Map(t.manifest.records.map(e=>[e.node.path,e]))),!i&&!n.tree_root_digest&&n.baseline_json&&n.baseline_ref){let e=c(n.baseline_json,n.baseline_ref,void 0,`stored`);r=createLocalWorkspaceManifestTree([...e.entries,...(e.directories??[]).map(e=>({path:e,type:`directory`}))])}else if(r.size===0){if(n.baseline_ref)throw Error(`Local workspace baseline nodes are missing`);r=createLocalWorkspaceManifestTree([])}if(t.kind===`convert`){let e=Array.from(r.values(),({node:e})=>e).filter(e=>e.path!==``);return n.baseline_json||(r=createLocalWorkspaceManifestTree(e)),(n.baseline_json?manifestDocument(e,n.base_commit,void 0,`stored`).manifestRef:localWorkspaceManifestRootReference(r,n.base_commit))===n.baseline_ref?{kind:`replace`,update:prepareUpdate({kind:`update`,revision:n.revision,patch:{tree_root_digest:localWorkspaceDigestBytes(r.get(``).treeRef),baseline_json:n.pending_ref?n.baseline_json:null,baseline_ref:n.baseline_ref,source_paths_json:n.source_paths_json}},prepareLocalWorkspaceTreePacks(r))}:{kind:`rescan`}}if(t.kind===`prepare`){let e=t.manifest;if(!e.replace){for(let t of e.removed)r.delete(t);for(let t of e.records)r.set(t.node.path,t)}return{kind:`replace`,update:prepareUpdate({kind:`update`,revision:n.revision,patch:t.patch,manifest:{...e,records:[],removed:[],treeRoot:r.get(``).treeRef,previousTreeRoot:n.tree_root_digest?localWorkspaceDigestReference(n.tree_root_digest):null}},prepareLocalWorkspaceTreePacks(r))}}if(t.kind===`materialize`)return{kind:`materialize`,...manifestDocument(Array.from(r.values(),({node:e})=>e).filter(e=>e.path!==``),n.base_commit,void 0,`stored`)};let a=await selectLocalWorkspaceCanonicalPaths({root:t.canonicalRoot,admittedPaths:n.source_paths_json,assertCurrent:()=>void 0}),s=[...f(a)],u=/* @__PURE__ */ new Set;for(let[e,{node:t}]of r)e!==``&&(t.type===`directory`&&u.add(e),a.add(e));let d=t.target===`canonical`?`projection`:`canonical`,h=d===`canonical`?n.canonical_fingerprints:n.projection_fingerprints,g=/* @__PURE__ */ new Set,_=[],v=n.tree_root_digest?localWorkspaceDigestReference(n.tree_root_digest):null,y=Date.now(),b=prepareLocalWorkspaceFingerprints(r,v??r.get(``).treeRef,v?h:null,y);await p({root:t.target===`canonical`?n.projection_path:t.canonicalRoot,baseCommit:n.base_commit,includePaths:t.target===`projection`?a:void 0,gitIgnore:t.target===`canonical`?await readLocalWorkspaceGitExclusions(t.canonicalRoot,n.projection_path,a):void 0,preserveDirectories:u,buildCacheInputs:new Set(s),reuseFile:b.reuseFile,onEntry(e,t){g.add(e.path);let n=r.get(e.path);m(n?.node,e)||_.push({path:e.path,node:e}),t!==void 0&&b.observe(e.path,t)}});for(let e of r.keys())e!==``&&!g.has(e)&&_.push({path:e});let x=/* @__PURE__ */ new Set;for(let e of _){x.add(e.path);for(let t of l(e.path))x.add(t);let t=o(e.path);if(t){x.add(`${t}/.gitignore`);for(let e of l(`${t}/.gitignore`))x.add(e)}}let S=[];for(let e of x){let t=r.get(e);t&&S.push(t.node)}let C=updateLocalWorkspaceManifestTree(r,_),w=[];for(let e of x){let t=r.get(e);t&&w.push(t.node)}let T=manifestDocument(S,n.base_commit,s,`stored`),E=manifestDocument(w,n.base_commit,s),D=n.tree_root_digest===null,O=r.get(``).treeRef,k=localWorkspaceManifestRootReference(r,n.base_commit),A=b.encode(r,O),j=A!==null&&A!==h&&(!h||!A.equals(h)),ee=A&&j?{target:d,blob:A.toString(`base64`)}:void 0,M=s.length?parseLocalWorkspaceSourcePaths(n.source_paths_json):[],te=new Set(M),N=s.filter(e=>!te.has(e)),ne=k===n.baseline_ref,re=N.length||ne&&j?prepareUpdate({kind:`update`,revision:n.revision,patch:{...N.length?{source_paths_json:JSON.stringify([...M,...N])}:{},...ne&&j?{[d===`canonical`?`canonical_fingerprints`:`projection_fingerprints`]:A}:{}}}):void 0;return{version:1,kind:`scan`,previousRoot:n.baseline_ref,resultingRoot:k,treeRoot:O,previousTreeRoot:v,...ee?{fingerprints:ee}:{},preparations:O===v?[]:prepareLocalWorkspaceTreePacks(r,D?void 0:[...C.records.map(({node:e})=>e.path),...C.removed]),records:[],observation:re,removed:[],...D?{replace:!0}:{},baseManifestRaw:T.rawManifest,baseManifestRef:T.manifestRef,currentManifestRaw:E.rawManifest,currentManifestRef:E.manifestRef,buildCacheInputs:s}}export{executeLocalWorkspaceManifestRead};