gemi 0.237.1 → 0.237.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +1 -1
- package/dist/ai/usageMeter.d.ts +11 -7
- package/dist/ai/usageMeter.d.ts.map +1 -1
- package/dist/{chunk-txf4kfze.js → chunk-41bpne77.js} +17 -17
- package/dist/{chunk-txf4kfze.js.map → chunk-41bpne77.js.map} +4 -4
- package/dist/{chunk-mt68n713.js → chunk-5na9khtz.js} +1 -1
- package/dist/{chunk-mk8jwsm4.js → chunk-cvg01wc0.js} +1 -1
- package/dist/{chunk-sajfdtkt.js → chunk-dnqmvmnp.js} +1 -1
- package/dist/{chunk-wgpg670d.js → chunk-f0bz1q3t.js} +1 -1
- package/dist/{chunk-h0b4rjzn.js → chunk-fcbtgekt.js} +2 -2
- package/dist/{chunk-h0b4rjzn.js.map → chunk-fcbtgekt.js.map} +1 -1
- package/dist/{chunk-tfefp5jh.js → chunk-h1a4febx.js} +1 -1
- package/dist/chunk-mxqrmjha.js +13 -0
- package/dist/chunk-mxqrmjha.js.map +10 -0
- package/dist/{chunk-fhbre39m.js → chunk-psdcmh65.js} +1 -1
- package/dist/{chunk-j0bbh93g.js → chunk-szyr67g7.js} +1 -1
- package/dist/{chunk-8ccjtbm2.js → chunk-wt80ekv9.js} +1 -1
- package/dist/{chunk-g6re0kkk.js → chunk-y89vn9da.js} +1 -1
- package/dist/{chunk-2apm69wz.js → chunk-ycwv9n7m.js} +1 -1
- package/dist/console/run.js +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/queue/work.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-ab5xsxyx.js +0 -13
- package/dist/chunk-ab5xsxyx.js.map +0 -10
- /package/dist/{chunk-mt68n713.js.map → chunk-5na9khtz.js.map} +0 -0
- /package/dist/{chunk-mk8jwsm4.js.map → chunk-cvg01wc0.js.map} +0 -0
- /package/dist/{chunk-sajfdtkt.js.map → chunk-dnqmvmnp.js.map} +0 -0
- /package/dist/{chunk-wgpg670d.js.map → chunk-f0bz1q3t.js.map} +0 -0
- /package/dist/{chunk-tfefp5jh.js.map → chunk-h1a4febx.js.map} +0 -0
- /package/dist/{chunk-fhbre39m.js.map → chunk-psdcmh65.js.map} +0 -0
- /package/dist/{chunk-j0bbh93g.js.map → chunk-szyr67g7.js.map} +0 -0
- /package/dist/{chunk-8ccjtbm2.js.map → chunk-wt80ekv9.js.map} +0 -0
- /package/dist/{chunk-g6re0kkk.js.map → chunk-y89vn9da.js.map} +0 -0
- /package/dist/{chunk-2apm69wz.js.map → chunk-ycwv9n7m.js.map} +0 -0
package/dist/kernel/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ta as E}from"../chunk-4wdc4q33.js";import{ob as l}from"../chunk-
|
|
2
|
+
import{Ta as E}from"../chunk-4wdc4q33.js";import{ob as l}from"../chunk-ycwv9n7m.js";import{pb as H}from"../chunk-cwkf46bk.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,dc as b,gc as f,hc as k,ic as m}from"../chunk-dnqmvmnp.js";import"../chunk-41bpne77.js";import"../chunk-7ytazpjd.js";import"../chunk-5na9khtz.js";import"../chunk-w9v8bbp8.js";import{Qe as h}from"../chunk-wt80ekv9.js";import"../chunk-g7exgg3k.js";import"../chunk-bhycdjcv.js";import{Pf as n,Qf as v,oh as w,sh as A,tf as d,uf as s,wh as R}from"../chunk-y89vn9da.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import"../chunk-ca1qwsjj.js";import"../chunk-0xmk4jyj.js";import"../chunk-szyr67g7.js";import{hk as M}from"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-psdcmh65.js";import"../chunk-6wv3k8ap.js";import"../chunk-mxqrmjha.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import"../chunk-mykr2v6g.js";import"../chunk-kbz5s9wb.js";import{rm as O,tm as J}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import"../chunk-4rs6w1gp.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new J;boot(){if(this.models.length>0)l(...this.models);else a();this.app.config.merge(this.config),J.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let z of this.services){let G=typeof z==="function"?new z:z,x=G.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,G),this.serviceInstances.push(G),this.serviceTokens.add(x.token)}this.app.setShutdownHooks(this.serviceInstances.map((z)=>({name:`${z.constructor.name}.onShutdown`,shutdown:(G)=>z.onShutdown(G)})))}async waitForBoot(){await this.app.boot(),await this.bootServices(),p(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),J.getInstance()===this.app)J.setInstance(void 0);O.disable()}}function a(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
|
|
3
3
|
Nested relation reads resolve a model by name, so a policy on a subclass that does not own its
|
|
4
4
|
`+" name is skipped inside every include \u2014 scoped at the root, "+`unscoped in an include, with nothing
|
|
5
5
|
to notice it. Declaring the modules registers each class under its own name and audits the set:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../orm/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,MAAM,KAAK,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAOrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,QAAQ;IACvB;;;;;OAKG;IACH,EAAE,CAAC,EAAE,cAAc,CAAC;IACpB,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC;IACd;;;;;;;;;;;;;;;;OAgBG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,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Q,CAAC,OAAO,EAAE,MAAM;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM;gBAFb,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM;CAOzB;AAED,6EAA6E;AAC7E,wBAAgB,eAAe,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAG9E;AAuBD;;;GAGG;AACH,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,IAAI,CAAC,CAK9D;AAED;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CAAC,CAAC,EACrC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,EAC7C,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA2CZ"}
|
package/dist/orm/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qa as g6}from"../chunk-wgpg670d.js";import{$a as w0,Ua as J9,Va as Y9,Wa as l,Xa as b9,Ya as E3,Za as E6,_a as w6,ab as e5,bb as w3,cb as x6,db as X3,eb as I0,fb as Z7,gb as X7,hb as z7,ib as d5,jb as J7,kb as Y7,lb as H7,mb as v6,nb as k6,ob as f6}from"../chunk-2apm69wz.js";import{Wh as O6,Xh as A6,Yh as S6,Zh as b6,_h as q6}from"../chunk-vcmwp7pv.js";import{$h as A0,ai as o,bi as j,ci as n,fi as R,gi as x,hi as c,ii as C6,ji as T6,ki as Y5,li as R6,mi as p3,ni as k,oi as I6,pi as U6,qi as N6,ri as F6,si as a5}from"../chunk-c3c37k46.js";import"../chunk-0xmk4jyj.js";import{ek as G6,fk as a,gk as d,hk as P3,ik as u0,kk as _6,lk as L6,qk as t4,rk as r4,sk as a4,tk as e4,uk as $7}from"../chunk-8adbpxpm.js";import{Ak as $0,Bk as Z6,Ck as c5,Dk as X6,Ek as T5,Fk as z6,Hk as J6,Ik as s5,Jk as Y6,Kk as H6,Lk as i5,Mk as R3,Nk as y0,Ok as s3,Pk as i3,Qk as s,Rk as V6,Sk as h0,Tk as n5,vk as K,wk as T,xk as g0,yk as g,zk as $6}from"../chunk-768yza4f.js";import{Al as K6,Bl as t5,Cl as r5,El as Q6,Fl as o4,ll as B6,ml as E0,nl as T0,ol as Z3,rl as D6,sl as l4,ul as P6,vl as j6,wl as l5,xl as o5,yl as p5,zl as b3}from"../chunk-ab5xsxyx.js";import{Sl as W6,Ul as M6,Wl as S3}from"../chunk-2as2xfem.js";import{um as A3}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-4rs6w1gp.js";function N0($,Z,X,z,J,Y){let H=X0($,Z),G=B0($,H,Z,Y),V=X.quoteIdent(z),W=`${V}.`,M=G.parentFields.map((Q,L)=>{let F=`${W}${X.quoteIdent(z3(H,Z,G.childFields[L]))}`,N=`${J}${X.quoteIdent(z3($,Z,Q))}`;return`${F} = ${N}`}).join(" and ");if(!G.join)return{child:H,source:`${X.quoteIdent(H.table)} as ${V}`,correlation:M,qualifier:W};let B=`${W}${X.quoteIdent(z3(H,Z,G.childFields[0]))}`,D=`${J}${X.quoteIdent(z3($,Z,G.parentFields[0]))}`,P=X.quoteIdent(`${z}j`);return{child:H,source:`${X.quoteIdent(H.table)} as ${V} join ${X.quoteIdent(G.join.table)} as ${P} on ${P}.${X.quoteIdent(G.join.childColumn)} = ${B}`,correlation:`${P}.${X.quoteIdent(G.join.parentColumn)} = ${D}`,qualifier:W}}function z3($,Z,X){let z=$.fields[X];if(!z)throw new s($.name,Z.name,`it joins on '${X}', which is not a field on ${$.name}.`);return z.column}function u($,Z,X){let z=J3($);if(typeof Z!=="object"||Z===null||Array.isArray(Z))throw X9($,X,z);let J=Object.keys(Z).filter((H)=>Z[H]!==void 0),Y=Z;for(let H of z){if(H.length===1&&J.includes(H[0]))return Z9($,X,H[0],Y[H[0]]),H;let G=H.join("_");if(H.length>1&&J.includes(G)){let V=Y[G];if(V&&typeof V==="object"&&!Array.isArray(V))for(let W of H)Z9($,X,`${G}.${W}`,V[W]);return H}}throw X9($,X,z)}function f3($){if($===null||$===void 0)return!1;let Z=typeof $;if(Z!=="object")return Z!=="function"&&Z!=="symbol";if(Array.isArray($))return!1;if($ instanceof Date||ArrayBuffer.isView($))return!0;let X=Object.getPrototypeOf($);return X!==Object.prototype&&X!==null}function Z9($,Z,X,z){if(z===void 0||f3(z))return;throw new T(`${Z.argument}.${X}`,Z.model,Z.operation,`A unique key takes a plain value to match, not ${z===null?"null":Array.isArray(z)?"an array":"a filter object"}. Use findFirst/findMany (or updateMany/deleteMany) to filter on ${$.name}.${X.split(".").pop()}.`)}function g3($,Z,X){u($,Z,{model:$.name,operation:X,argument:"where"})}function J3($){let Z=[];if($.primaryKey.length>0)Z.push($.primaryKey);for(let X of $.uniques)Z.push(X);return Z}function X9($,Z,X){let z=X.map((H)=>H.length===1?H[0]:H.join("_")).join(", "),Y=Z.argument.startsWith("data.")?`Name it by one of those, or reach it through the ${$.name} model directly.`:`Use ${Z.operation==="delete"||Z.operation==="update"?`${Z.operation}Many`:"findFirst"} to query on anything else.`;return new K(Z.argument,Z.model,Z.operation,`${$.name} needs a unique field here. It declares: ${z}. ${Y}`)}function y($,Z,X){let z=Z.castParameter($);if(!z)return n(X);return n((J,Y)=>{let H=X(J,Y);if(H===null||H===void 0)return null;let G=k(H);if(G==="db")return null;if(G==="json")return"null";if(G==="any")throw Error("gemi ORM bug: Prisma.AnyNull reached the parameter binder. It is a filter operand only, and both the filter and write paths are supposed to have handled it before this point.");return JSON.stringify(H)},z)}function f($,Z,X,z){if(Z===void 0||Z===null)return null;if(typeof Z!=="object"||Array.isArray(Z))throw new T("where",$.name,X.operation,"Expected an object.");let J=[];for(let Y of Object.keys(Z).sort()){let H=Z[Y];if(H===void 0)continue;let G=(W)=>z(W)?.[Y];if(Y==="AND"||Y==="OR"){let W=z9($,H,X,G,Y);if(W)J.push(W);continue}if(Y===z0){J.push(_7($,H,X,G));continue}if(Y==="NOT"){let W=z9($,H,X,G,"AND");if(W)J.push(R(j("not "),v0(W)));continue}if(Y in $.relations){let W=j7($,$.relations[Y],H,X,G);if(W)J.push(W);continue}let V=$.fields[Y];if(!V){let W=Q7($,Y,H,X,G);if(W){J.push(W);continue}throw new g(Y,$.name,Object.keys($.fields))}J.push(d3($,V,H,X,G))}if(J.length===0)return null;if(J.length===1)return J[0];return t(J," and ")}function j7($,Z,X,z,J){let Y=J9(Z.kind),H=K7($,Z,X,Y,z),G=z.relationDepth??0,V=z.dialect,W=z.qualifier??`${V.quoteIdent($.table)}.`,M=N0($,Z,V,`_r${G}`,W,z.operation),B=M.child,D=j(M.correlation),P={...z,qualifier:M.qualifier,relationDepth:G+1},Q=[];for(let L of Y){if(!(L in H))continue;let F=H[L],N=(I)=>H.direct?J(I):J(I)?.[L];if(F===null){Q.push(y3(M,D,null,L==="is"));continue}let C=f(B,F,P,N);if(L==="every"){if(!C)continue;Q.push(y3(M,D,R(j("not "),v0(C)),!0));continue}let _=L==="none"||L==="isNot";Q.push(y3(M,D,C,_))}if(Q.length===0)return null;if(Q.length===1)return Q[0];return t(Q," and ")}function y3($,Z,X,z){let J=[j(`${z?"not ":""}exists (select 1 from ${$.source} where `),Z];if(X)J.push(j(" and "),X);return J.push(j(")")),R(...J)}function K7($,Z,X,z,J){let Y=`where.${Z.name}`,H=Z.kind==="many";if(X===null){if(H)throw new K(Y,$.name,J.operation,`${Z.name} is a to-many relation, so null is not a filter for it. Use { none: {} } for "has no related rows".`);return{is:null,direct:!0}}if(typeof X!=="object"||Array.isArray(X))throw new T(Y,$.name,J.operation,H?`Expected an object holding ${z.join(", ")}.`:"Expected an object, or null.");if(Y9(X,z))return X;if(H)throw new K(Y,$.name,J.operation,`Expected one of ${z.join(", ")}. A to-many relation has no `+"single reading of a bare filter \u2014 { some: \u2026 } and { every: \u2026 } mean "+"different things.");return{is:X,direct:!0}}function Q7($,Z,X,z,J){let Y=J3($).find((V)=>V.length>1&&V.join("_")===Z);if(!Y)return null;if(typeof X!=="object"||X===null||Array.isArray(X))throw new T(`where.${Z}`,$.name,z.operation,`Expected an object holding ${Y.join(" and ")}.`);let H=X,G=[];for(let V of Y){if(H[V]===void 0)throw new K(`where.${Z}`,$.name,z.operation,`Missing '${V}'. A composite key needs all of ${Y.join(", ")}.`);if(!f3(H[V]))throw new T(`where.${Z}.${V}`,$.name,z.operation,`A composite key takes a plain value for each of ${Y.join(", ")}, not a filter, an array or null.`);G.push(d3($,$.fields[V],H[V],z,(W)=>J(W)?.[V]))}return G.length===1?G[0]:t(G," and ")}function z9($,Z,X,z,J){let Y=[];if(Array.isArray(Z))for(let H=0;H<Z.length;H++){let G=f($,Z[H],X,(V)=>z(V)?.[H]);if(G)Y.push(G)}else{let H=f($,Z,X,z);if(H)Y.push(H)}if(Y.length===0)return J==="AND"?null:H9;if(Y.length===1)return Y[0];return t(Y,J==="AND"?" and ":" or ")}var H9=j("false");function t($,Z){return R(j("("),x($,Z),j(")"))}function v0($){return $.text.startsWith("(")?$:t([$],"")}var m3=new Set(["equals","not","in","notIn","lt","lte","gt","gte","contains","startsWith","endsWith","mode"]),V9={lt:"<",lte:"<=",gt:">",gte:">="},z0="$compositeIn",G9=Symbol("gemi.orm.compositeInFromPlanner");function W9($,Z){return{[G9]:!0,fields:$,values:Z}}function _7($,Z,X,z){let{dialect:J}=X,H=L7($,Z,X).map((V)=>{let W=$.fields[V];if(!W)throw new g(V,$.name,Object.keys($.fields));return W}),G=H.map((V)=>`${X.qualifier??""}${J.quoteIdent(V.column)}`);return J.compositeIn(G,H.map((V)=>V.type),(V)=>z(V).values)}function L7($,Z,X){let z=()=>{throw new g(z0,$.name,Object.keys($.fields))};if(typeof Z!=="object"||Z===null||Array.isArray(Z))return z();if(Z[G9]!==!0)return z();let J=(G)=>{throw new K(z0,$.name,X.operation,G)},{fields:Y,values:H}=Z;if(!Array.isArray(Y)||Y.length===0)return J(`the planner built a '${z0}' with no fields.`);if(!Y.every((G)=>typeof G==="string"))return J(`the planner built a '${z0}' with a non-string field.`);if(!Array.isArray(H))return J(`the planner built a '${z0}' with no values.`);if(!H.every((G)=>Array.isArray(G)&&G.length===Y.length))return J(`the planner built a '${z0}' whose tuples do not all have ${Y.length} value(s).`);return Y}var C7=["equals","has","hasEvery","hasSome","isEmpty"],h3=new Set(C7);function T7($,Z,X,z,J,Y){let{dialect:H}=J;if(O0($,Z,`where.${Z.name}`,J.operation,H),Array.isArray(z))throw new T(`where.${Z.name}`,$.name,J.operation,`'${Z.name}' is a scalar list, and a bare array is not a filter on `+"one \u2014 Prisma rejects it here too. Say which comparison you mean: "+`{ ${Z.name}: { equals: [...] } } for the whole list, or { ${Z.name}: { hasEvery: [...] } } for "contains all of these". A bare array *is* accepted as a value in \`data\`.`);if(!c3(z))throw new T(`where.${Z.name}`,$.name,J.operation,`'${Z.name}' is a scalar list. Expected an object holding ${[...h3].sort().join(", ")}; received ${z===null?"null":typeof z}.`);let G=z,V=[];for(let W of Object.keys(G).sort()){let M=G[W];if(M===void 0)continue;if(!h3.has(W))throw new T(`where.${Z.name}.${W}`,$.name,J.operation,`'${Z.name}' is a scalar list, and a list filter takes ${[...h3].sort().join(", ")}. The scalar operators \u2014 `+`${[...m3].sort().join(", ")} \u2014 apply to a single value and `+"Prisma does not offer them here.");let B=(D)=>Y(D)?.[W];V.push(R7($,Z,X,W,M,J,B))}if(V.length===0)return j("true");if(V.length===1)return V[0];return t(V," and ")}function R7($,Z,X,z,J,Y,H){let{dialect:G}=Y;if(z==="equals")return I7($,Z,X,J,Y,H);if(z==="isEmpty"){if(typeof J!=="boolean")throw new T(`where.${Z.name}.isEmpty`,$.name,Y.operation,`Expected true or false, received ${J===null?"null":typeof J}.`);return G.listIsEmpty(X,J)}if(z==="has"){let W=U7(Z);return G.listHas(X,y(W,G,F0(W,G,H)))}if(!Array.isArray(J))throw new T(`where.${Z.name}.${z}`,$.name,Y.operation,`Expected an array, received ${J===null?"null":typeof J}.`);let V=y(Z,G,F0(Z,G,H));return z==="hasEvery"?G.listHasEvery(X,V):G.listHasSome(X,V)}function I7($,Z,X,z,J,Y){let{dialect:H}=J;if(z===null)return j(`${X} is null`);if(!Array.isArray(z))throw new T(`where.${Z.name}.equals`,$.name,J.operation,`'${Z.name}' is a scalar list, so it compares against an array. Received ${typeof z}. For "is this element present", use { ${Z.name}: { has: \u2026 } }.`);return R(j(`${X} = `),y(Z,H,F0(Z,H,Y)))}function U7($){return{...$,isList:!1}}function O0($,Z,X,z,J){if(J.listFilters.size>0)return;throw new K(X,$.name,z,`'${Z.name}' is a scalar list, and ${J.name} has no array type to hold one. Prisma refuses the column itself on ${J.name} \u2014 `+'"the current connector does not support lists of primitive types" \u2014 so '+`this is a difference between the databases rather than a gap in the ORM. The generated artifact is dialect-agnostic, which is why this surfaces here rather than at \`prisma generate\`: the schema was generated against Postgres and DATABASE_URL names a ${J.name} database, which has no '${Z.column}' column either. It works on postgres.`)}var N7=["equals","not","string_contains","string_starts_with","string_ends_with","array_contains","lt","lte","gt","gte"],u3=new Set(N7),F7=["has_key","has_some_keys","has_every_key"],Y3=new Set(F7);function M9($,Z,X,z,J,Y,H,G){let V=z!=="has_key",W=`where.${Z.name}.${z}`,M=(D)=>{if(!(V?Array.isArray(D)&&D.every((Q)=>typeof Q==="string"):typeof D==="string"))throw new T(W,$.name,Y.operation,V?"Expected an array of key names, like ['a', 'b'].":"Expected a key name, like 'a'.");return D};M(J);let B=(D,P)=>M(G(D,P));return Y.dialect.jsonHasKeys(X,H,B,z==="has_key"?"one":z==="has_some_keys"?"some":"every",Array.isArray(J)?J.length:0)}function O7($,Z,X,z,J,Y){let{dialect:H}=J;if(Z.type!=="Json")throw new K(`${Z.name}.path`,$.name,J.operation,`A 'path' filter reads inside a JSON document, and '${Z.name}' is a ${Z.type} column.`);q7($,Z,z.path,J);let G=(M)=>Y(M)?.path,V=Object.keys(z).filter((M)=>M!=="path"&&z[M]!==void 0).sort();if(V.length===0)throw new K(`${Z.name}.path`,$.name,J.operation,`A 'path' needs a filter beside it \u2014 ${[...u3,...Y3].sort().join(", ")}. Prisma refuses a bare path too.`);let W=[];for(let M of V){if(Y3.has(M)){W.push(M9($,Z,X,M,z[M],J,G,(P)=>Y(P)?.[M]));continue}if(!u3.has(M))throw new K(`${Z.name}.${M}`,$.name,J.operation,`A JSON path filter takes ${[...u3,...Y3].sort().join(", ")}.`);if(!H.jsonFilters.has(M))throw new K(`${Z.name}.${M}`,$.name,J.operation,`'${M}' on a JSON path is not available on ${H.name}. Prisma refuses it here too, so this is a difference between the databases rather than a gap in the ORM. It works on postgres.`);let B=z[M],D=B===null?"json":k(B);if(D&&(M==="equals"||M==="not")){W.push(A7(D,X,G,Z,H,M==="not"));continue}if(D&&B!==null){let P=M==="array_contains"?"'array_contains' tests containment against a document, and a sentinel is not one":`'${M}' compares an extracted value against a scalar, and a sentinel is not one`;throw new T(`where.${Z.name}.${M}`,$.name,J.operation,`${k0(D)} asks which kind of null a value is, which `+`only 'equals' and 'not' can express \u2014 ${P}. Prisma refuses it under this operator too. Write { ${Z.name}: { path: [\u2026], equals: ${k0(D)} } }, `+"or filter the column itself \u2014 "+`{ ${Z.name}: { equals: ${k0(D)} } }.`)}if(B9(B))throw new T(`where.${Z.name}.${M}`,$.name,J.operation,"Prisma.AnyNull is a question rather than a value \u2014 'either kind of "+"null' \u2014 so it cannot appear inside a document. Ask it directly: "+`{ ${Z.name}: { path: [\u2026], equals: Prisma.AnyNull } }.`);S7(M,B,$,Z,J),W.push(b7(M,X,G,Z,H,(P)=>Y(P)?.[M]))}return W.length===1?W[0]:t(W," and ")}function A7($,Z,X,z,J,Y){let H=()=>R(J.jsonValueAt(Z,X),j(Y?" is not null":" is null")),G=()=>R(J.jsonValueAt(Z,X),j(Y?" <> ":" = "),y(z,J,()=>J.encode(p3,z)));if($==="db")return H();if($==="json")return G();return t([G(),H()],Y?" and ":" or ")}function S7($,Z,X,z,J){let Y=$==="string_contains"||$==="string_starts_with"||$==="string_ends_with";if(Y&&typeof Z!=="string")throw new T(`where.${z.name}.${$}`,X.name,J.operation,`Expected a string, received ${Z===null?"null":typeof Z}. Prisma raises here too \u2014 without this the pattern becomes `+`'%${String(Z)}%', which runs and returns the wrong rows.`);if(Z===null)throw new T(`where.${z.name}.${$}`,X.name,J.operation,$==="array_contains"?"null cannot be tested for containment through a JSON path: the operand binds as SQL NULL rather than as the JSON value, and "+"'x @> NULL' is NULL rather than true \u2014 the query would run and "+`match nothing. A null *inside* the document is an ordinary value and still compiles: { ${z.name}: { path: [\u2026], array_contains: [null] } }.`:`null cannot be compared through a JSON path with '${$}', which `+"compares the extracted value as a number \u2014 the comparison against "+`NULL is NULL rather than true, so the query would run and match nothing. Prisma refuses it here too. For "the value at this path is a JSON null", use equals or not: { ${z.name}: { path: [\u2026], equals: null } }.`);if($==="array_contains"||Y)return;if(typeof Z==="object")throw new K(`where.${z.name}.${$}`,X.name,J.operation,`'${$}' on a JSON path compares the extracted value as a scalar, so `+"an object or array operand cannot be expressed \u2014 it would bind as "+`'${String(Z)}' and match nothing. Prisma accepts one here; gemi does not yet. Use array_contains for containment, or narrow the path until it names a scalar.`)}function b7($,Z,X,z,J,Y){if($==="array_contains")return J.jsonArrayContains(Z,X,Y);let H=$==="string_contains"||$==="string_starts_with"||$==="string_ends_with",G=J.jsonExtract(Z,X,!0);if(H){let B=$==="string_contains"?(D)=>`%${D}%`:$==="string_starts_with"?(D)=>`${D}%`:(D)=>`%${D}`;return R(j("("),G,j(") like "),n((D,P)=>{let Q=Y(D,P);return Q===null||Q===void 0?null:B(String(Q))}))}let V=$==="equals"?"=":$==="not"?"<>":V9[$],W=$!=="equals"&&$!=="not",M=W?R(j("cast(("),G,j(") as real)")):R(j("("),G,j(")"));return R(M,j(` ${V} `),n((B,D)=>{let P=Y(B,D);if(P===null||P===void 0)return null;if(W)return Number(P);return J.jsonComparesAsText?String(P):P}))}function q7($,Z,X,z){let{dialect:J}=z,Y=J.jsonPathSyntax==="array"?"array":"jsonpath",H=Array.isArray(X)?"array":typeof X==="string"?"jsonpath":"other";if(Array.isArray(X)&&X.length===0||X==="")throw new K(`${Z.name}.path`,$.name,z.operation,`A JSON path cannot be empty. ${J.jsonPathSyntax==="array"?`On ${J.name} an empty array selects the whole document, `+"which is a filter on the column rather than on a path \u2014 write "+`{ ${Z.name}: { equals: \u2026 } } if that is what you meant.`:`On ${J.name} an empty string raises inside json_extract.`}`);if(H===Y){if(Y!=="array")return;let V=X.findIndex((B)=>typeof B!=="string");if(V===-1)return;let W=X[V],M=W===null?"null":W===void 0?"undefined":Array.isArray(W)?"an array":typeof W==="object"?"an object":`a ${typeof W}`;throw new K(`${Z.name}.path`,$.name,z.operation,`A JSON path is an array of strings, and path[${V}] is ${M}. `+(typeof W==="number"?'An array index is a key too \u2014 write ["items", "0"] rather than '+`["items", 0]; it reaches the same element, because ${J.name} takes the path as text. Prisma's path is string[] and its client refuses a number here too.`:"Prisma's path is string[] too."))}throw new K(`${Z.name}.path`,$.name,z.operation,J.jsonPathSyntax==="array"?`On ${J.name} a JSON path is an array of keys \u2014 ["a", "b"] \u2014 `+"not a JSONPath string. Prisma splits them the same way, and refuses the other form on each database.":`On ${J.name} a JSON path is a JSONPath string \u2014 "$.a.b" \u2014 not `+"an array of keys. Prisma splits them the same way, and refuses the other form on each database.")}function d3($,Z,X,z,J){let{dialect:Y}=z,H=`${z.qualifier??""}${Y.quoteIdent(Z.column)}`,G=k(X);if(G)throw new T(`where.${Z.name}`,$.name,z.operation,`${k0(G)} is not a filter on `+"its own \u2014 Prisma rejects it here too. Write it as an explicit "+`comparison: { ${Z.name}: { equals: ${k0(G)} } }.`);if(Z.isList)return T7($,Z,H,X,z,J);if(!c3(X))return H3(H,Z,X,Y,J);let V=X,W=Object.keys(V).sort();if(V.path!==void 0)return O7($,Z,H,V,z,J);let M=V.mode==="insensitive";if(V.mode!==void 0&&V.mode!=="default"){if(!M)throw new T(`mode: ${JSON.stringify(V.mode)}`,$.name,z.operation,"Prisma takes 'default' or 'insensitive'.");if(!Y.supportsInsensitiveMode)throw new K('mode: "insensitive"',$.name,z.operation,`The ${Y.name} dialect cannot express it \u2014 Prisma rejects it `+"here too. Note SQLite's LIKE is already case-insensitive for ASCII.")}let B=[];for(let D of W){let P=V[D];if(P===void 0||D==="mode")continue;if(Z.type==="Json"&&Y3.has(D)){B.push(M9($,Z,H,D,P,z,void 0,(L)=>J(L)?.[D]));continue}if(!m3.has(D))throw new T(`where.${Z.name}.${D}`,$.name,z.operation,`A scalar filter takes ${[...m3].sort().join(", ")}.`);if(D!=="equals"&&D!=="not"&&B9(P))throw new T(`where.${Z.name}.${D}`,$.name,z.operation,`Prisma.AnyNull means 'either kind of null', which only 'equals' and 'not' can express. Write { ${Z.name}: { equals: Prisma.AnyNull } }, or name the one you mean with Prisma.DbNull or Prisma.JsonNull.`);let Q=(L)=>J(L)?.[D];switch(D){case"equals":B.push(H3(H,Z,P,Y,Q));break;case"not":B.push(E7($,Z,P,z,Q,H));break;case"in":case"notIn":B.push(x7($,H,Z,P,z,Q,D==="notIn"));break;case"lt":case"lte":case"gt":case"gte":B.push(R(j(`${H} ${V9[D]} `),y(Z,Y,F0(Z,Y,Q))));break;case"contains":case"startsWith":case"endsWith":if(typeof P!=="string")throw new T(`where.${Z.name}.${D}`,$.name,z.operation,`Expected a string, received ${P===null?"null":typeof P}.`);if(Z.type!=="String")throw new K(`where.${Z.name}.${D}`,$.name,z.operation,`'${Z.name}' is a ${Z.type}, and ${D} only applies to strings.`);B.push(Y.like(H,M,v7(D,Q)));break}}if(B.length===0)return j("true");if(B.length===1)return B[0];return t(B," and ")}function k0($){return`Prisma.${$==="db"?"DbNull":$==="json"?"JsonNull":"AnyNull"}`}function B9($){if(k($)==="any")return!0;return Array.isArray($)&&$.some((Z)=>k(Z)==="any")}function E7($,Z,X,z,J,Y){if(X===null||k(X)==="db")return j(`${Y} is not null`);if(k(X)==="json")return R(j("not "),v0(H3(Y,Z,X,z.dialect,J)));if(k(X)==="any")return R(j("not "),v0(H3(Y,Z,X,z.dialect,J)));if(!c3(X))return R(j(`${Y} <> `),y(Z,z.dialect,F0(Z,z.dialect,J)));let H=d3($,Z,X,z,J);return R(j("not "),v0(H))}function H3($,Z,X,z,J){if(X===null||k(X)==="db")return j(`${$} is null`);if(k(X)==="any")return t([j(`${$} is null`),w7($,Z,z)]," or ");return R(j(`${$} = `),y(Z,z,F0(Z,z,J)))}function w7($,Z,X){return R(j(`${$} = `),y(Z,X,()=>X.encode(p3,Z)))}function x7($,Z,X,z,J,Y,H){let{dialect:G}=J;if(!Array.isArray(z))throw new T(`where.${X.name}.${H?"notIn":"in"}`,$.name,J.operation,"Expected an array.");if(z.length===0)return H?j("true"):H9;return G.inList(Z,H,z.length,(V)=>{return Y(V).map((M)=>G.encode(M,X))})}function v7($,Z){return(X)=>{let z=String(Z(X));if($==="contains")return`%${z}%`;if($==="startsWith")return`${z}%`;return`%${z}`}}function F0($,Z,X){return(z)=>Z.encode(X(z),$)}function c3($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&!($ instanceof Date)&&!ArrayBuffer.isView($)}function D9($,Z,X,z,J,Y,H){let G=`orderBy.${Z.name}`;if(typeof X!=="object"||X===null||Array.isArray(X))throw new T(G,$.name,z,Z.kind==="many"?'Expected { _count: "asc" | "desc" }.':`Expected an object naming one field of ${Z.model}.`);let V=X,W=Object.keys(V).filter((L)=>L!=="where");if(W.length!==1)throw new K(G,$.name,z,W.length===0?"Name the field to order by.":`Name exactly one field to order by; got ${W.join(", ")}. `+"Order by several with an array: [{ a: \u2026 }, { b: \u2026 }].");let[M]=W,B=N0($,Z,J,`_o${H}`,`${J.quoteIdent($.table)}.`,z),D=k7($,Z,B.child,M,V[M],z,B.qualifier,J),P=f(B.child,V.where,{dialect:J,operation:z,qualifier:B.qualifier},(L)=>Y(L)?.where),Q=[j(`(select ${D.expression} from ${B.source} where ${B.correlation}`)];if(P)Q.push(j(" and "),P);return Q.push(j(")")),{expression:R(...Q),direction:D.direction,nulls:D.nulls}}function k7($,Z,X,z,J,Y,H,G){let V=`orderBy.${Z.name}.${z}`,{direction:W,nulls:M}=f7($,V,J,Y);if(z===l){if(Z.kind!=="many")throw new K(V,$.name,Y,`${Z.name} is a to-one relation, so its count is 0 or 1. Order by one of ${X.name}'s fields instead.`);return{expression:"count(*)",direction:W,nulls:M}}if(Z.kind==="many")throw new K(V,$.name,Y,`${Z.name} is a to-many relation, so ordering by '${z}' has no single answer for a parent with several children. Only `+"{ _count: \u2026 } is supported.");let B=X.fields[z];if(!B)throw new K(V,$.name,Y,`'${z}' is not a field on ${X.name}. Known fields: ${Object.keys(X.fields).join(", ")}.`);return{expression:`${H}${G.quoteIdent(B.column)}`,direction:W,nulls:M}}function f7($,Z,X,z){if(X==="asc"||X==="desc")return{direction:X};if(typeof X==="object"&&X!==null){let{sort:J,nulls:Y}=X;if(J!=="asc"&&J!=="desc")throw new T(Z,$.name,z,'Expected "asc" or "desc".');if(Y===void 0)return{direction:J};if(Y!=="first"&&Y!=="last")throw new K(`${Z}.nulls`,$.name,z,'Expected "first" or "last".');return{direction:J,nulls:Y}}throw new K(Z,$.name,z,'Expected "asc", "desc", or { sort, nulls }.')}var g7=new Set(["asc","desc"]),y7=new Set(["first","last"]);function D0($,Z,X,z){if(Z===void 0||Z===null)return[];let J=Array.isArray(Z),Y=J?Z:[Z],H=[];for(let G=0;G<Y.length;G++){let V=Y[G],W=(M)=>{let B=z?.locate(M);return J?B?.[G]:B};if(typeof V!=="object"||V===null)throw new T("orderBy",$.name,X,"Expected an object or an array of objects.");for(let[M,B]of Object.entries(V)){if(B===void 0)continue;if(M in $.relations){if(!z)throw new K(`orderBy.${M}`,$.name,X,"Ordering by a relation is not implemented here.");let P=D9($,$.relations[M],B,X,z.dialect,(Q)=>W(Q)?.[M],H.length);H.push({column:M,direction:P.direction,...P.nulls?{nulls:P.nulls}:{},expression:P.expression});continue}let D=$.fields[M];if(!D)throw new g(M,$.name,Object.keys($.fields));H.push({column:D.column,...P9($,M,B,X)})}}return H}function P9($,Z,X,z){if(typeof X==="string"){if(!g7.has(X))throw new T(`orderBy.${Z}: ${JSON.stringify(X)}`,$.name,z,'Expected "asc" or "desc".');return{direction:X}}if(typeof X==="object"&&X!==null){let{sort:J,nulls:Y}=X,H=P9($,Z,J,z).direction;if(Y===void 0)return{direction:H};if(typeof Y!=="string"||!y7.has(Y))throw new K(`orderBy.${Z}.nulls: ${JSON.stringify(Y)}`,$.name,z,'Expected "first" or "last".');return{direction:H,nulls:Y}}throw new K(`orderBy.${Z}`,$.name,z,'Expected "asc", "desc", or { sort, nulls }.')}function V3($){return $.map((Z)=>({...Z,direction:Z.direction==="asc"?"desc":"asc",...Z.nulls?{nulls:Z.nulls==="first"?"last":"first"}:{}}))}function r($,Z,X){if($.length===0)return null;return x($.map((z)=>{let J=` ${z.direction}`+(z.nulls?` nulls ${z.nulls}`:"");if(z.expression)return x([z.expression,j(J)],"");return j(`${X??""}${Z.quoteIdent(z.column)}${J}`)}),", ")}function G3($,Z,X,z,J){if(typeof J!=="number"||!Number.isInteger(J))throw new T(X,$,Z,`Expected an integer, got ${JSON.stringify(J)}.`);if(z==="skip"&&J<0)throw new T(X,$,Z,"A 'skip' counts rows to pass over, so it cannot be negative. Prisma rejects one too.")}function Q0($,Z,X,z,J,Y=!1){if(X?.take!==void 0)G3($.name,Z,"take","take",X.take);if(X?.skip!==void 0)G3($.name,Z,"skip","skip",X.skip);let H=Y?1:X?.take,G=X?.skip,V=J;if((H!==void 0||G!==void 0)&&V.length===0&&!Y)V=$.primaryKey.map((P)=>({column:$.fields[P]?.column??P,direction:"asc"}));let M=typeof H==="number"&&H<0;if(M)V=V3(V);let B=H===void 0?null:Y?()=>1:(P)=>Math.abs(Number(P?.take)),D=G===void 0?null:(P)=>Number(P?.skip);return{clause:z.paginate(B,D),terms:V,reversed:M}}function J0($,Z,X){let z=Z?.select,J=Z?.omit;if(z!==void 0&&Z?.include!==void 0)throw new K("select + include",$.name,X,"Prisma allows only one of them on the same query.");if(z!==void 0&&J!==void 0)throw new K("select + omit",$.name,X,"'select' names what to keep and 'omit' what to drop, so the two describe different column lists. Prisma allows only one of them on "+"the same query. Drop the 'omit' \u2014 a 'select' already excludes "+"everything it does not name.");if(z===void 0||z===null)return h7($,J,X);if(typeof z!=="object"||Array.isArray(z))throw new T("select",$.name,X,"Expected an object.");let Y=[];for(let[G,V]of Object.entries($.fields))if(z[G]===!0)Y.push(V);let H=0;for(let G of Object.keys(z)){let V=z[G];if(V===void 0)continue;if(G in $.relations){if(V!==!1)H++;continue}if(G===l){if(V!==!1)H++;continue}if(!(G in $.fields))throw new g(G,$.name,Object.keys($.fields));if(typeof V!=="boolean")throw new T(`select.${G}`,$.name,X,"Expected true or false.")}if(Y.length===0&&H===0)throw new K("select",$.name,X,"At least one field must be selected.");return Y}function h7($,Z,X){if(Z===void 0||Z===null)return Object.values($.fields);if(typeof Z!=="object"||Array.isArray(Z))throw new T("omit",$.name,X,"Expected an object of fields.");let z=new Set;for(let Y of Object.keys(Z)){let H=Z[Y];if(H===void 0)continue;if(Y in $.relations)throw new K(`omit.${Y}`,$.name,X,`'${Y}' is a relation, not a column. A relation is already absent unless an 'include' asks for it.`);if(!(Y in $.fields))throw new g(Y,$.name,Object.keys($.fields));if(typeof H!=="boolean")throw new T(`omit.${Y}`,$.name,X,"Expected true or false.");if(H)z.add(Y)}let J=Object.values($.fields).filter((Y)=>!z.has(Y.name));if(J.length===0)throw new K("omit",$.name,X,`It omits every field on ${$.name}, which leaves no column to select. Prisma rejects that too.`);return J}function W3($,Z,X){if(X.length===0)return{fields:Z};let z=new Set(Z.map((H)=>H.name)),J=X.filter((H)=>!z.has(H));if(J.length===0)return{fields:Z};let Y=new Set([...z,...J]);return{fields:Object.values($.fields).filter((H)=>Y.has(H.name)),hidden:J}}var j9=new Set(["where","orderBy","select","omit","include","take","skip"]),K9=new Set(["where","select","omit","include"]),D3=10;function m0($){return[...new Set($.map((Z)=>Z.strategy))].sort()}function S0($,Z,X,z,J=P0){let Y=p0($,Z,z);if(Y.length===0)return{plans:[],keyFields:[]};let H=[],G=new Set;for(let V of Y){T9($,V,z);let W=U9($,V);R9(W,V.node,z,2);let M=J.plan({parent:$,child:W,relation:V.relation,as:V.as,node:V.node,locate:V.locate,dialect:X,operation:z});H.push(M);for(let B of M.parentFields)G.add(B)}return{plans:H,keyFields:[...G]}}async function j3($,Z,X,z,J){let Y=Array.isArray(X)?X:X===null||X===void 0?[]:[X];if(Y.length===0)return;for(let H of $){if(H.root)continue;await H.load(Y,z,J)}if(Z&&Z.length>0)for(let H of Y)for(let G of Z)delete H[G]}function p0($,Z,X){if(Z===void 0||Z===null)return[];let{include:z,select:J}=Z;C9($,z,J,X);let Y=[];if(z!==void 0&&z!==null){if(typeof z!=="object"||Array.isArray(z))throw new T("include",$.name,X,"Expected an object.");for(let H of Object.keys(z).sort()){let G=z[H];if(G===void 0||G===!1)continue;if(H===l)continue;let V=$.relations[H];if(!V)throw new y0(H,$.name,Object.keys($.relations));Y.push({as:H,relation:V,node:G,locate:(W)=>W?.include?.[H]})}return Y}if(J!==void 0&&J!==null&&typeof J==="object")for(let H of Object.keys(J).sort()){let G=J[H];if(G===void 0||G===!1)continue;let V=$.relations[H];if(!V)continue;Y.push({as:H,relation:V,node:G,locate:(W)=>W?.select?.[H]})}return Y}function C9($,Z,X,z,J){if(Z===void 0||X===void 0)return;throw new K(J?`${J}: select + include`:"select + include",$.name,z,"Prisma allows only one of them on the same query, at any level.")}function T9($,Z,X){let z=Z.node;if(z===!0)return;if(typeof z!=="object"||z===null||Array.isArray(z))throw new T(Z.as,$.name,X,"Expected true or an object of relation arguments.");let J=z;C9($,J.include,J.select,X,Z.as);let Y=Z.relation.kind==="many";for(let H of Object.keys(J).sort()){if(J[H]===void 0)continue;if(Y&&(H==="take"||H==="skip")){u7($,Z,X,H,J[H]);continue}if(Y?j9.has(H):K9.has(H))continue;if(H==="lock")throw new g0(`${Z.as}.lock`,$.name,X,"'lock' locks the rows of the model being queried, not an included relation's. Lock the related rows with their own locking read in the same transaction.");if(H==="orderBy"&&!Y)throw new K(`${Z.as}.orderBy`,$.name,X,"Prisma does not accept 'orderBy' on a to-one relation \u2014 there is at "+"most one row to order.");if(H==="take"||H==="skip")throw new K(`${Z.as}.${H}`,$.name,X,`Prisma does not accept '${H}' on a to-one relation.`);throw new K(`${Z.as}.${H}`,$.name,X,`A relation node takes ${[...Y?j9:K9].sort().join(", ")}.`)}}function u7($,Z,X,z,J){G3($.name,X,`${Z.as}.${z}`,z,J)}function n3($,Z){let X=$.node;if(typeof X!=="object"||X===null||Array.isArray(X))return;for(let z of["take","skip"]){if(X[z]===void 0)continue;throw new K(`${$.as}.${z}`,$.parent.name,$.operation,`A '${z}' inside a to-many relation is per parent, and the batched `+"relation planner serves every parent from one query \u2014 so the only "+`limit it could emit would page every parent's children as one set. Only the lateral join strategy can express it, by paginating inside a subquery that already runs once per parent row, and it needs Postgres: ${Z}. Load '${$.as}' as its own query, or narrow it with 'where'.`)}}function R9($,Z,X,z){if(typeof Z!=="object"||Z===null||Array.isArray(Z))return;if(Z.select!==void 0)J0($,Z,X);let J=p0($,Z,X);if(J.length===0)return;if(z>D3)throw new s3($.name,D3);for(let Y of J)T9($,Y,X),R9(U9($,Y),Y.node,X,z+1)}function I9($,Z,X,z){if($.parentFields.length!==1)throw new K(X.name,Z.name,z,`${X.name} joins on ${$.parentFields.length} fields (${$.parentFields.join(", ")}), and it is planned through a join table, which links two models by a single primary key each side. Prisma does not build an implicit many-to-many over a composite key.`);return{parentField:$.parentFields[0],childField:$.childFields[0],join:$.join}}function B0($,Z,X,z){if(X.joinTable)return p7($,Z,X);if(X.from.length>0)return Q9($,X,X.from,X.to,z);let J=m7($,Z,X);if(J.from.length===0)throw new s($.name,X.name,`neither ${$.name}.${X.name} nor ${Z.name}.${J.name} holds the foreign key.`);return Q9($,X,J.to,J.from,z)}function Q9($,Z,X,z,J){if(X.length===0)throw new K(Z.name,$.name,J,`${Z.name} names no join fields.`);if(X.length!==z.length)throw new s($.name,Z.name,`it joins ${X.length} field(s) to ${z.length}: ${X.join(", ")} against ${z.join(", ")}.`);return{parentFields:X,childFields:z}}function m7($,Z,X){let z=Object.values(Z.relations).filter((J)=>J.relationName===X.relationName&&!(Z.name===$.name&&J.name===X.name));if(z.length!==1)throw new s($.name,X.name,z.length===0?`${Z.name} declares no relation named '${X.relationName}'.`:`${Z.name} declares ${z.length} relations named '${X.relationName}'.`);return z[0]}function p7($,Z,X){let{table:z,a:J,b:Y}=X.joinTable;if(J===Y){let G=X.joinTable.ownerColumn;if(!G)throw new K(X.name,$.name,"include",`${X.name} is a self-referential implicit many-to-many, and the generated artifact predates support for one. Re-run \`prisma generate\`.`);return{parentFields:[M3($,X)],childFields:[M3(Z,X)],join:{table:z,parentColumn:G,childColumn:G==="A"?"B":"A"}}}if($.name!==J&&$.name!==Y)throw new s($.name,X.name,`the join table '${z}' connects ${J} and ${Y}, neither of which is ${$.name}.`);let H=$.name===J?"A":"B";return{parentFields:[M3($,X)],childFields:[M3(Z,X)],join:{table:z,parentColumn:H,childColumn:H==="A"?"B":"A"}}}function M3($,Z){if($.primaryKey.length!==1)throw new s($.name,Z.name,`an implicit many-to-many joins on ${$.name}'s primary key, which has ${$.primaryKey.length} fields.`);return $.primaryKey[0]}function B3($,Z,X){let z=$.fields[X];if(!z)throw new s($.name,Z.name,`it joins on '${X}', which is not a field on ${$.name}.`);return z}function U9($,Z){return X0($,Z.relation,Z.as)}function X0($,Z,X=Z.name){let z=Z.model;if(!a(z))throw new i3($.name,X,z,P3());let J=d(z)?.$schema;if(!J)throw new h0(z);return J}var _9="batched",P0={name:_9,plan($){n3($,"this query planned with the batched strategy");let Z=B0($.parent,$.child,$.relation,$.operation);for(let Y of Z.parentFields)L9($.parent,$.relation,B3($.parent,$.relation,Y));for(let Y of Z.childFields)L9($.child,$.relation,B3($.child,$.relation,Y));let X=B3($.parent,$.relation,Z.parentFields[0]),z=B3($.child,$.relation,Z.childFields[0]),J=$.relation.kind==="many";return{as:$.as,model:$.relation.model,kind:$.relation.kind,parentFields:Z.parentFields,strategy:_9,load(Y,H,G){let V={parentKeyField:X,childKeyField:z,many:J,parents:Y,args:H,executor:G};return Z.join?c7($,Z,V):d7($,Z,V)}}}};async function d7($,Z,X){let{keys:z,byKey:J}=O9(X.parents,Z.parentFields);if(z.length===0)return;let Y=$.locate(X.args),H=N9(Y,Z.childFields,z,$.child,$.dialect),G=await X.executor.exec($.relation.model,"findMany",H.args,!0);for(let V of G){let W=J.get(f0(Z.childFields.map((M)=>V[M])));if(!W)continue;for(let M of W)F9(M,$.as,V,X.many)}if(H.hidden)for(let V of G)for(let W of Z.childFields)delete V[W]}async function c7($,Z,X){let{keys:z,byKey:J}=O9(X.parents,Z.parentFields);if(z.length===0)return;let{dialect:Y}=$,H=Z.join,G=await s7(Y,H,z.map((P)=>Y.encode(P[0],X.parentKeyField)),X.executor),V=new Map,W=[];for(let P of G){let Q=f0([Y.decode(P[H.parentColumn],X.parentKeyField)]),L=J.get(Q);if(!L)continue;let F=Y.decode(P[H.childColumn],X.childKeyField),N=f0([F]),C=V.get(N);if(C===void 0)C=[],V.set(N,C),W.push([F]);for(let _ of L)C.push(_)}if(W.length===0)return;let M=$.locate(X.args),B=N9(M,Z.childFields,W,$.child,$.dialect),D=await X.executor.exec($.relation.model,"findMany",B.args,!0);for(let P of D){let Q=V.get(f0([P[Z.childFields[0]]]));if(!Q)continue;for(let L of Q)F9(L,$.as,P,X.many)}if(B.hidden)for(let P of D)delete P[Z.childFields[0]]}async function s7($,Z,X,z){let J=R(j(`select ${$.quoteIdent(Z.parentColumn)}, ${$.quoteIdent(Z.childColumn)} from ${$.quoteIdent(Z.table)} where `),$.inList($.quoteIdent(Z.parentColumn),!1,X.length,()=>X)),{text:Y,binders:H}=c(J,$,{model:Z.table,operation:"include"}),G=A0();return z.query(Y,H.map((V)=>V(void 0,G)))}function N9($,Z,X,z,J){let Y=$===!0||$===null||typeof $!=="object"?{}:$,H=Z.length===1?{[Z[0]]:{in:X.map((B)=>B[0])}}:i7(z,Z,X,J),G={where:Y.where===void 0?H:{AND:[Y.where,H]}};if(Y.orderBy!==void 0)G.orderBy=Y.orderBy;if(Y.include!==void 0)G.include=Y.include;let V=Y.omit;if(V!==void 0){let B=Z.filter((D)=>V[D]===!0);if(B.length===0)G.omit=V;else{let D={...V};for(let P of B)delete D[P];return G.omit=D,{args:G,hidden:!0}}}let W=Y.select;if(W===void 0)return{args:G,hidden:!1};let M=Z.filter((B)=>W[B]!==!0);if(M.length===0)return G.select=W,{args:G,hidden:!1};G.select={...W};for(let B of M)G.select[B]=!0;return{args:G,hidden:!0}}function i7($,Z,X,z){let J=Z.map((Y)=>$.fields[Y]?.type);if(J.every((Y)=>Y!==void 0)&&z.canBindCompositeIn(J))return{[z0]:W9(Z,X)};return{OR:X.map((Y)=>Object.fromEntries(Z.map((H,G)=>[H,Y[G]])))}}function f0($){return JSON.stringify($.map(n7))}function F9($,Z,X,z){if(z){$[Z].push(X);return}if($[Z]===null)$[Z]=X}function O9($,Z){let X=new Map,z=[];for(let J of $){let Y=Z.map((V)=>J[V]);if(Y.some((V)=>V===null||V===void 0))continue;let H=f0(Y),G=X.get(H);if(G===void 0)G=[],X.set(H,G),z.push(Y);G.push(J)}return{keys:z,byKey:X}}function n7($){if(typeof $!=="object"||$===null)return $;if($ instanceof Date)return $.getTime();if(ArrayBuffer.isView($)){let Z=new Uint8Array($.buffer,$.byteOffset,$.byteLength),X="";for(let z of Z)X+=z.toString(16).padStart(2,"0");return`bytes:${X}`}throw Error(`Cannot key a relation stitch on ${Object.prototype.toString.call($)}.`)}function L9($,Z,X){if(X.isList)throw new s($.name,Z.name,`it joins on '${X.name}', a ${X.type} list \u2014 which decodes to a new `+"array per row and so cannot be compared between the two sides.");if(X.type!=="Json")return;throw new s($.name,Z.name,`it joins on '${X.name}', a ${X.type} \u2014 which decodes to a new object `+"per row and so cannot be compared between the two sides.")}var A9=(()=>{try{return Function("return 1")()===1}catch{return!1}})(),S9=!0;function l7($){S9=$}function o7(){return A9}function d0($,Z,X=[]){if(A9&&S9)return t7($,Z,X);return l3($,Z,X)}function l3($,Z,X=[]){let z=$.map((G)=>({key:G.name,column:G.column,field:G,decode:Z.needsDecode(G)})),J=z.length,Y=X.map((G)=>({key:G.key,many:G.kind==="many"})),H=Y.length;return(G)=>{let V=[];for(let W=0;W<G.length;W++){let M=G[W],B={};for(let D=0;D<J;D++){let P=z[D],Q=M[P.column];B[P.key]=P.decode?Z.decode(Q,P.field):Q??null}for(let D=0;D<H;D++)B[Y[D].key]=Y[D].many?[]:null;V.push(B)}return V}}function t7($,Z,X){let z=[];for(let Y=0;Y<$.length;Y++){let H=$[Y],G=JSON.stringify(H.name),V=JSON.stringify(H.column);z.push(Z.needsDecode(H)?`${G}: d.decode(row[${V}], f[${Y}])`:`${G}: row[${V}] ?? null`)}for(let Y of X)z.push(`${JSON.stringify(Y.key)}: ${Y.kind==="many"?"[]":"null"}`);let J=`
|
|
2
|
+
import{qa as g6}from"../chunk-f0bz1q3t.js";import{$a as w0,Ua as J9,Va as Y9,Wa as l,Xa as b9,Ya as E3,Za as E6,_a as w6,ab as e5,bb as w3,cb as x6,db as X3,eb as I0,fb as Z7,gb as X7,hb as z7,ib as d5,jb as J7,kb as Y7,lb as H7,mb as v6,nb as k6,ob as f6}from"../chunk-ycwv9n7m.js";import{Wh as O6,Xh as A6,Yh as S6,Zh as b6,_h as q6}from"../chunk-vcmwp7pv.js";import{$h as A0,ai as o,bi as j,ci as n,fi as R,gi as x,hi as c,ii as C6,ji as T6,ki as Y5,li as R6,mi as p3,ni as k,oi as I6,pi as U6,qi as N6,ri as F6,si as a5}from"../chunk-c3c37k46.js";import"../chunk-0xmk4jyj.js";import{ek as G6,fk as a,gk as d,hk as P3,ik as u0,kk as _6,lk as L6,qk as t4,rk as r4,sk as a4,tk as e4,uk as $7}from"../chunk-8adbpxpm.js";import{Ak as $0,Bk as Z6,Ck as c5,Dk as X6,Ek as T5,Fk as z6,Hk as J6,Ik as s5,Jk as Y6,Kk as H6,Lk as i5,Mk as R3,Nk as y0,Ok as s3,Pk as i3,Qk as s,Rk as V6,Sk as h0,Tk as n5,vk as K,wk as T,xk as g0,yk as g,zk as $6}from"../chunk-768yza4f.js";import{Al as K6,Bl as t5,Cl as r5,El as Q6,Fl as o4,ll as B6,ml as E0,nl as T0,ol as Z3,rl as D6,sl as l4,ul as P6,vl as j6,wl as l5,xl as o5,yl as p5,zl as b3}from"../chunk-mxqrmjha.js";import{Sl as W6,Ul as M6,Wl as S3}from"../chunk-2as2xfem.js";import{um as A3}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-4rs6w1gp.js";function N0($,Z,X,z,J,Y){let H=X0($,Z),G=B0($,H,Z,Y),V=X.quoteIdent(z),W=`${V}.`,M=G.parentFields.map((Q,L)=>{let F=`${W}${X.quoteIdent(z3(H,Z,G.childFields[L]))}`,N=`${J}${X.quoteIdent(z3($,Z,Q))}`;return`${F} = ${N}`}).join(" and ");if(!G.join)return{child:H,source:`${X.quoteIdent(H.table)} as ${V}`,correlation:M,qualifier:W};let B=`${W}${X.quoteIdent(z3(H,Z,G.childFields[0]))}`,D=`${J}${X.quoteIdent(z3($,Z,G.parentFields[0]))}`,P=X.quoteIdent(`${z}j`);return{child:H,source:`${X.quoteIdent(H.table)} as ${V} join ${X.quoteIdent(G.join.table)} as ${P} on ${P}.${X.quoteIdent(G.join.childColumn)} = ${B}`,correlation:`${P}.${X.quoteIdent(G.join.parentColumn)} = ${D}`,qualifier:W}}function z3($,Z,X){let z=$.fields[X];if(!z)throw new s($.name,Z.name,`it joins on '${X}', which is not a field on ${$.name}.`);return z.column}function u($,Z,X){let z=J3($);if(typeof Z!=="object"||Z===null||Array.isArray(Z))throw X9($,X,z);let J=Object.keys(Z).filter((H)=>Z[H]!==void 0),Y=Z;for(let H of z){if(H.length===1&&J.includes(H[0]))return Z9($,X,H[0],Y[H[0]]),H;let G=H.join("_");if(H.length>1&&J.includes(G)){let V=Y[G];if(V&&typeof V==="object"&&!Array.isArray(V))for(let W of H)Z9($,X,`${G}.${W}`,V[W]);return H}}throw X9($,X,z)}function f3($){if($===null||$===void 0)return!1;let Z=typeof $;if(Z!=="object")return Z!=="function"&&Z!=="symbol";if(Array.isArray($))return!1;if($ instanceof Date||ArrayBuffer.isView($))return!0;let X=Object.getPrototypeOf($);return X!==Object.prototype&&X!==null}function Z9($,Z,X,z){if(z===void 0||f3(z))return;throw new T(`${Z.argument}.${X}`,Z.model,Z.operation,`A unique key takes a plain value to match, not ${z===null?"null":Array.isArray(z)?"an array":"a filter object"}. Use findFirst/findMany (or updateMany/deleteMany) to filter on ${$.name}.${X.split(".").pop()}.`)}function g3($,Z,X){u($,Z,{model:$.name,operation:X,argument:"where"})}function J3($){let Z=[];if($.primaryKey.length>0)Z.push($.primaryKey);for(let X of $.uniques)Z.push(X);return Z}function X9($,Z,X){let z=X.map((H)=>H.length===1?H[0]:H.join("_")).join(", "),Y=Z.argument.startsWith("data.")?`Name it by one of those, or reach it through the ${$.name} model directly.`:`Use ${Z.operation==="delete"||Z.operation==="update"?`${Z.operation}Many`:"findFirst"} to query on anything else.`;return new K(Z.argument,Z.model,Z.operation,`${$.name} needs a unique field here. It declares: ${z}. ${Y}`)}function y($,Z,X){let z=Z.castParameter($);if(!z)return n(X);return n((J,Y)=>{let H=X(J,Y);if(H===null||H===void 0)return null;let G=k(H);if(G==="db")return null;if(G==="json")return"null";if(G==="any")throw Error("gemi ORM bug: Prisma.AnyNull reached the parameter binder. It is a filter operand only, and both the filter and write paths are supposed to have handled it before this point.");return JSON.stringify(H)},z)}function f($,Z,X,z){if(Z===void 0||Z===null)return null;if(typeof Z!=="object"||Array.isArray(Z))throw new T("where",$.name,X.operation,"Expected an object.");let J=[];for(let Y of Object.keys(Z).sort()){let H=Z[Y];if(H===void 0)continue;let G=(W)=>z(W)?.[Y];if(Y==="AND"||Y==="OR"){let W=z9($,H,X,G,Y);if(W)J.push(W);continue}if(Y===z0){J.push(_7($,H,X,G));continue}if(Y==="NOT"){let W=z9($,H,X,G,"AND");if(W)J.push(R(j("not "),v0(W)));continue}if(Y in $.relations){let W=j7($,$.relations[Y],H,X,G);if(W)J.push(W);continue}let V=$.fields[Y];if(!V){let W=Q7($,Y,H,X,G);if(W){J.push(W);continue}throw new g(Y,$.name,Object.keys($.fields))}J.push(d3($,V,H,X,G))}if(J.length===0)return null;if(J.length===1)return J[0];return t(J," and ")}function j7($,Z,X,z,J){let Y=J9(Z.kind),H=K7($,Z,X,Y,z),G=z.relationDepth??0,V=z.dialect,W=z.qualifier??`${V.quoteIdent($.table)}.`,M=N0($,Z,V,`_r${G}`,W,z.operation),B=M.child,D=j(M.correlation),P={...z,qualifier:M.qualifier,relationDepth:G+1},Q=[];for(let L of Y){if(!(L in H))continue;let F=H[L],N=(I)=>H.direct?J(I):J(I)?.[L];if(F===null){Q.push(y3(M,D,null,L==="is"));continue}let C=f(B,F,P,N);if(L==="every"){if(!C)continue;Q.push(y3(M,D,R(j("not "),v0(C)),!0));continue}let _=L==="none"||L==="isNot";Q.push(y3(M,D,C,_))}if(Q.length===0)return null;if(Q.length===1)return Q[0];return t(Q," and ")}function y3($,Z,X,z){let J=[j(`${z?"not ":""}exists (select 1 from ${$.source} where `),Z];if(X)J.push(j(" and "),X);return J.push(j(")")),R(...J)}function K7($,Z,X,z,J){let Y=`where.${Z.name}`,H=Z.kind==="many";if(X===null){if(H)throw new K(Y,$.name,J.operation,`${Z.name} is a to-many relation, so null is not a filter for it. Use { none: {} } for "has no related rows".`);return{is:null,direct:!0}}if(typeof X!=="object"||Array.isArray(X))throw new T(Y,$.name,J.operation,H?`Expected an object holding ${z.join(", ")}.`:"Expected an object, or null.");if(Y9(X,z))return X;if(H)throw new K(Y,$.name,J.operation,`Expected one of ${z.join(", ")}. A to-many relation has no `+"single reading of a bare filter \u2014 { some: \u2026 } and { every: \u2026 } mean "+"different things.");return{is:X,direct:!0}}function Q7($,Z,X,z,J){let Y=J3($).find((V)=>V.length>1&&V.join("_")===Z);if(!Y)return null;if(typeof X!=="object"||X===null||Array.isArray(X))throw new T(`where.${Z}`,$.name,z.operation,`Expected an object holding ${Y.join(" and ")}.`);let H=X,G=[];for(let V of Y){if(H[V]===void 0)throw new K(`where.${Z}`,$.name,z.operation,`Missing '${V}'. A composite key needs all of ${Y.join(", ")}.`);if(!f3(H[V]))throw new T(`where.${Z}.${V}`,$.name,z.operation,`A composite key takes a plain value for each of ${Y.join(", ")}, not a filter, an array or null.`);G.push(d3($,$.fields[V],H[V],z,(W)=>J(W)?.[V]))}return G.length===1?G[0]:t(G," and ")}function z9($,Z,X,z,J){let Y=[];if(Array.isArray(Z))for(let H=0;H<Z.length;H++){let G=f($,Z[H],X,(V)=>z(V)?.[H]);if(G)Y.push(G)}else{let H=f($,Z,X,z);if(H)Y.push(H)}if(Y.length===0)return J==="AND"?null:H9;if(Y.length===1)return Y[0];return t(Y,J==="AND"?" and ":" or ")}var H9=j("false");function t($,Z){return R(j("("),x($,Z),j(")"))}function v0($){return $.text.startsWith("(")?$:t([$],"")}var m3=new Set(["equals","not","in","notIn","lt","lte","gt","gte","contains","startsWith","endsWith","mode"]),V9={lt:"<",lte:"<=",gt:">",gte:">="},z0="$compositeIn",G9=Symbol("gemi.orm.compositeInFromPlanner");function W9($,Z){return{[G9]:!0,fields:$,values:Z}}function _7($,Z,X,z){let{dialect:J}=X,H=L7($,Z,X).map((V)=>{let W=$.fields[V];if(!W)throw new g(V,$.name,Object.keys($.fields));return W}),G=H.map((V)=>`${X.qualifier??""}${J.quoteIdent(V.column)}`);return J.compositeIn(G,H.map((V)=>V.type),(V)=>z(V).values)}function L7($,Z,X){let z=()=>{throw new g(z0,$.name,Object.keys($.fields))};if(typeof Z!=="object"||Z===null||Array.isArray(Z))return z();if(Z[G9]!==!0)return z();let J=(G)=>{throw new K(z0,$.name,X.operation,G)},{fields:Y,values:H}=Z;if(!Array.isArray(Y)||Y.length===0)return J(`the planner built a '${z0}' with no fields.`);if(!Y.every((G)=>typeof G==="string"))return J(`the planner built a '${z0}' with a non-string field.`);if(!Array.isArray(H))return J(`the planner built a '${z0}' with no values.`);if(!H.every((G)=>Array.isArray(G)&&G.length===Y.length))return J(`the planner built a '${z0}' whose tuples do not all have ${Y.length} value(s).`);return Y}var C7=["equals","has","hasEvery","hasSome","isEmpty"],h3=new Set(C7);function T7($,Z,X,z,J,Y){let{dialect:H}=J;if(O0($,Z,`where.${Z.name}`,J.operation,H),Array.isArray(z))throw new T(`where.${Z.name}`,$.name,J.operation,`'${Z.name}' is a scalar list, and a bare array is not a filter on `+"one \u2014 Prisma rejects it here too. Say which comparison you mean: "+`{ ${Z.name}: { equals: [...] } } for the whole list, or { ${Z.name}: { hasEvery: [...] } } for "contains all of these". A bare array *is* accepted as a value in \`data\`.`);if(!c3(z))throw new T(`where.${Z.name}`,$.name,J.operation,`'${Z.name}' is a scalar list. Expected an object holding ${[...h3].sort().join(", ")}; received ${z===null?"null":typeof z}.`);let G=z,V=[];for(let W of Object.keys(G).sort()){let M=G[W];if(M===void 0)continue;if(!h3.has(W))throw new T(`where.${Z.name}.${W}`,$.name,J.operation,`'${Z.name}' is a scalar list, and a list filter takes ${[...h3].sort().join(", ")}. The scalar operators \u2014 `+`${[...m3].sort().join(", ")} \u2014 apply to a single value and `+"Prisma does not offer them here.");let B=(D)=>Y(D)?.[W];V.push(R7($,Z,X,W,M,J,B))}if(V.length===0)return j("true");if(V.length===1)return V[0];return t(V," and ")}function R7($,Z,X,z,J,Y,H){let{dialect:G}=Y;if(z==="equals")return I7($,Z,X,J,Y,H);if(z==="isEmpty"){if(typeof J!=="boolean")throw new T(`where.${Z.name}.isEmpty`,$.name,Y.operation,`Expected true or false, received ${J===null?"null":typeof J}.`);return G.listIsEmpty(X,J)}if(z==="has"){let W=U7(Z);return G.listHas(X,y(W,G,F0(W,G,H)))}if(!Array.isArray(J))throw new T(`where.${Z.name}.${z}`,$.name,Y.operation,`Expected an array, received ${J===null?"null":typeof J}.`);let V=y(Z,G,F0(Z,G,H));return z==="hasEvery"?G.listHasEvery(X,V):G.listHasSome(X,V)}function I7($,Z,X,z,J,Y){let{dialect:H}=J;if(z===null)return j(`${X} is null`);if(!Array.isArray(z))throw new T(`where.${Z.name}.equals`,$.name,J.operation,`'${Z.name}' is a scalar list, so it compares against an array. Received ${typeof z}. For "is this element present", use { ${Z.name}: { has: \u2026 } }.`);return R(j(`${X} = `),y(Z,H,F0(Z,H,Y)))}function U7($){return{...$,isList:!1}}function O0($,Z,X,z,J){if(J.listFilters.size>0)return;throw new K(X,$.name,z,`'${Z.name}' is a scalar list, and ${J.name} has no array type to hold one. Prisma refuses the column itself on ${J.name} \u2014 `+'"the current connector does not support lists of primitive types" \u2014 so '+`this is a difference between the databases rather than a gap in the ORM. The generated artifact is dialect-agnostic, which is why this surfaces here rather than at \`prisma generate\`: the schema was generated against Postgres and DATABASE_URL names a ${J.name} database, which has no '${Z.column}' column either. It works on postgres.`)}var N7=["equals","not","string_contains","string_starts_with","string_ends_with","array_contains","lt","lte","gt","gte"],u3=new Set(N7),F7=["has_key","has_some_keys","has_every_key"],Y3=new Set(F7);function M9($,Z,X,z,J,Y,H,G){let V=z!=="has_key",W=`where.${Z.name}.${z}`,M=(D)=>{if(!(V?Array.isArray(D)&&D.every((Q)=>typeof Q==="string"):typeof D==="string"))throw new T(W,$.name,Y.operation,V?"Expected an array of key names, like ['a', 'b'].":"Expected a key name, like 'a'.");return D};M(J);let B=(D,P)=>M(G(D,P));return Y.dialect.jsonHasKeys(X,H,B,z==="has_key"?"one":z==="has_some_keys"?"some":"every",Array.isArray(J)?J.length:0)}function O7($,Z,X,z,J,Y){let{dialect:H}=J;if(Z.type!=="Json")throw new K(`${Z.name}.path`,$.name,J.operation,`A 'path' filter reads inside a JSON document, and '${Z.name}' is a ${Z.type} column.`);q7($,Z,z.path,J);let G=(M)=>Y(M)?.path,V=Object.keys(z).filter((M)=>M!=="path"&&z[M]!==void 0).sort();if(V.length===0)throw new K(`${Z.name}.path`,$.name,J.operation,`A 'path' needs a filter beside it \u2014 ${[...u3,...Y3].sort().join(", ")}. Prisma refuses a bare path too.`);let W=[];for(let M of V){if(Y3.has(M)){W.push(M9($,Z,X,M,z[M],J,G,(P)=>Y(P)?.[M]));continue}if(!u3.has(M))throw new K(`${Z.name}.${M}`,$.name,J.operation,`A JSON path filter takes ${[...u3,...Y3].sort().join(", ")}.`);if(!H.jsonFilters.has(M))throw new K(`${Z.name}.${M}`,$.name,J.operation,`'${M}' on a JSON path is not available on ${H.name}. Prisma refuses it here too, so this is a difference between the databases rather than a gap in the ORM. It works on postgres.`);let B=z[M],D=B===null?"json":k(B);if(D&&(M==="equals"||M==="not")){W.push(A7(D,X,G,Z,H,M==="not"));continue}if(D&&B!==null){let P=M==="array_contains"?"'array_contains' tests containment against a document, and a sentinel is not one":`'${M}' compares an extracted value against a scalar, and a sentinel is not one`;throw new T(`where.${Z.name}.${M}`,$.name,J.operation,`${k0(D)} asks which kind of null a value is, which `+`only 'equals' and 'not' can express \u2014 ${P}. Prisma refuses it under this operator too. Write { ${Z.name}: { path: [\u2026], equals: ${k0(D)} } }, `+"or filter the column itself \u2014 "+`{ ${Z.name}: { equals: ${k0(D)} } }.`)}if(B9(B))throw new T(`where.${Z.name}.${M}`,$.name,J.operation,"Prisma.AnyNull is a question rather than a value \u2014 'either kind of "+"null' \u2014 so it cannot appear inside a document. Ask it directly: "+`{ ${Z.name}: { path: [\u2026], equals: Prisma.AnyNull } }.`);S7(M,B,$,Z,J),W.push(b7(M,X,G,Z,H,(P)=>Y(P)?.[M]))}return W.length===1?W[0]:t(W," and ")}function A7($,Z,X,z,J,Y){let H=()=>R(J.jsonValueAt(Z,X),j(Y?" is not null":" is null")),G=()=>R(J.jsonValueAt(Z,X),j(Y?" <> ":" = "),y(z,J,()=>J.encode(p3,z)));if($==="db")return H();if($==="json")return G();return t([G(),H()],Y?" and ":" or ")}function S7($,Z,X,z,J){let Y=$==="string_contains"||$==="string_starts_with"||$==="string_ends_with";if(Y&&typeof Z!=="string")throw new T(`where.${z.name}.${$}`,X.name,J.operation,`Expected a string, received ${Z===null?"null":typeof Z}. Prisma raises here too \u2014 without this the pattern becomes `+`'%${String(Z)}%', which runs and returns the wrong rows.`);if(Z===null)throw new T(`where.${z.name}.${$}`,X.name,J.operation,$==="array_contains"?"null cannot be tested for containment through a JSON path: the operand binds as SQL NULL rather than as the JSON value, and "+"'x @> NULL' is NULL rather than true \u2014 the query would run and "+`match nothing. A null *inside* the document is an ordinary value and still compiles: { ${z.name}: { path: [\u2026], array_contains: [null] } }.`:`null cannot be compared through a JSON path with '${$}', which `+"compares the extracted value as a number \u2014 the comparison against "+`NULL is NULL rather than true, so the query would run and match nothing. Prisma refuses it here too. For "the value at this path is a JSON null", use equals or not: { ${z.name}: { path: [\u2026], equals: null } }.`);if($==="array_contains"||Y)return;if(typeof Z==="object")throw new K(`where.${z.name}.${$}`,X.name,J.operation,`'${$}' on a JSON path compares the extracted value as a scalar, so `+"an object or array operand cannot be expressed \u2014 it would bind as "+`'${String(Z)}' and match nothing. Prisma accepts one here; gemi does not yet. Use array_contains for containment, or narrow the path until it names a scalar.`)}function b7($,Z,X,z,J,Y){if($==="array_contains")return J.jsonArrayContains(Z,X,Y);let H=$==="string_contains"||$==="string_starts_with"||$==="string_ends_with",G=J.jsonExtract(Z,X,!0);if(H){let B=$==="string_contains"?(D)=>`%${D}%`:$==="string_starts_with"?(D)=>`${D}%`:(D)=>`%${D}`;return R(j("("),G,j(") like "),n((D,P)=>{let Q=Y(D,P);return Q===null||Q===void 0?null:B(String(Q))}))}let V=$==="equals"?"=":$==="not"?"<>":V9[$],W=$!=="equals"&&$!=="not",M=W?R(j("cast(("),G,j(") as real)")):R(j("("),G,j(")"));return R(M,j(` ${V} `),n((B,D)=>{let P=Y(B,D);if(P===null||P===void 0)return null;if(W)return Number(P);return J.jsonComparesAsText?String(P):P}))}function q7($,Z,X,z){let{dialect:J}=z,Y=J.jsonPathSyntax==="array"?"array":"jsonpath",H=Array.isArray(X)?"array":typeof X==="string"?"jsonpath":"other";if(Array.isArray(X)&&X.length===0||X==="")throw new K(`${Z.name}.path`,$.name,z.operation,`A JSON path cannot be empty. ${J.jsonPathSyntax==="array"?`On ${J.name} an empty array selects the whole document, `+"which is a filter on the column rather than on a path \u2014 write "+`{ ${Z.name}: { equals: \u2026 } } if that is what you meant.`:`On ${J.name} an empty string raises inside json_extract.`}`);if(H===Y){if(Y!=="array")return;let V=X.findIndex((B)=>typeof B!=="string");if(V===-1)return;let W=X[V],M=W===null?"null":W===void 0?"undefined":Array.isArray(W)?"an array":typeof W==="object"?"an object":`a ${typeof W}`;throw new K(`${Z.name}.path`,$.name,z.operation,`A JSON path is an array of strings, and path[${V}] is ${M}. `+(typeof W==="number"?'An array index is a key too \u2014 write ["items", "0"] rather than '+`["items", 0]; it reaches the same element, because ${J.name} takes the path as text. Prisma's path is string[] and its client refuses a number here too.`:"Prisma's path is string[] too."))}throw new K(`${Z.name}.path`,$.name,z.operation,J.jsonPathSyntax==="array"?`On ${J.name} a JSON path is an array of keys \u2014 ["a", "b"] \u2014 `+"not a JSONPath string. Prisma splits them the same way, and refuses the other form on each database.":`On ${J.name} a JSON path is a JSONPath string \u2014 "$.a.b" \u2014 not `+"an array of keys. Prisma splits them the same way, and refuses the other form on each database.")}function d3($,Z,X,z,J){let{dialect:Y}=z,H=`${z.qualifier??""}${Y.quoteIdent(Z.column)}`,G=k(X);if(G)throw new T(`where.${Z.name}`,$.name,z.operation,`${k0(G)} is not a filter on `+"its own \u2014 Prisma rejects it here too. Write it as an explicit "+`comparison: { ${Z.name}: { equals: ${k0(G)} } }.`);if(Z.isList)return T7($,Z,H,X,z,J);if(!c3(X))return H3(H,Z,X,Y,J);let V=X,W=Object.keys(V).sort();if(V.path!==void 0)return O7($,Z,H,V,z,J);let M=V.mode==="insensitive";if(V.mode!==void 0&&V.mode!=="default"){if(!M)throw new T(`mode: ${JSON.stringify(V.mode)}`,$.name,z.operation,"Prisma takes 'default' or 'insensitive'.");if(!Y.supportsInsensitiveMode)throw new K('mode: "insensitive"',$.name,z.operation,`The ${Y.name} dialect cannot express it \u2014 Prisma rejects it `+"here too. Note SQLite's LIKE is already case-insensitive for ASCII.")}let B=[];for(let D of W){let P=V[D];if(P===void 0||D==="mode")continue;if(Z.type==="Json"&&Y3.has(D)){B.push(M9($,Z,H,D,P,z,void 0,(L)=>J(L)?.[D]));continue}if(!m3.has(D))throw new T(`where.${Z.name}.${D}`,$.name,z.operation,`A scalar filter takes ${[...m3].sort().join(", ")}.`);if(D!=="equals"&&D!=="not"&&B9(P))throw new T(`where.${Z.name}.${D}`,$.name,z.operation,`Prisma.AnyNull means 'either kind of null', which only 'equals' and 'not' can express. Write { ${Z.name}: { equals: Prisma.AnyNull } }, or name the one you mean with Prisma.DbNull or Prisma.JsonNull.`);let Q=(L)=>J(L)?.[D];switch(D){case"equals":B.push(H3(H,Z,P,Y,Q));break;case"not":B.push(E7($,Z,P,z,Q,H));break;case"in":case"notIn":B.push(x7($,H,Z,P,z,Q,D==="notIn"));break;case"lt":case"lte":case"gt":case"gte":B.push(R(j(`${H} ${V9[D]} `),y(Z,Y,F0(Z,Y,Q))));break;case"contains":case"startsWith":case"endsWith":if(typeof P!=="string")throw new T(`where.${Z.name}.${D}`,$.name,z.operation,`Expected a string, received ${P===null?"null":typeof P}.`);if(Z.type!=="String")throw new K(`where.${Z.name}.${D}`,$.name,z.operation,`'${Z.name}' is a ${Z.type}, and ${D} only applies to strings.`);B.push(Y.like(H,M,v7(D,Q)));break}}if(B.length===0)return j("true");if(B.length===1)return B[0];return t(B," and ")}function k0($){return`Prisma.${$==="db"?"DbNull":$==="json"?"JsonNull":"AnyNull"}`}function B9($){if(k($)==="any")return!0;return Array.isArray($)&&$.some((Z)=>k(Z)==="any")}function E7($,Z,X,z,J,Y){if(X===null||k(X)==="db")return j(`${Y} is not null`);if(k(X)==="json")return R(j("not "),v0(H3(Y,Z,X,z.dialect,J)));if(k(X)==="any")return R(j("not "),v0(H3(Y,Z,X,z.dialect,J)));if(!c3(X))return R(j(`${Y} <> `),y(Z,z.dialect,F0(Z,z.dialect,J)));let H=d3($,Z,X,z,J);return R(j("not "),v0(H))}function H3($,Z,X,z,J){if(X===null||k(X)==="db")return j(`${$} is null`);if(k(X)==="any")return t([j(`${$} is null`),w7($,Z,z)]," or ");return R(j(`${$} = `),y(Z,z,F0(Z,z,J)))}function w7($,Z,X){return R(j(`${$} = `),y(Z,X,()=>X.encode(p3,Z)))}function x7($,Z,X,z,J,Y,H){let{dialect:G}=J;if(!Array.isArray(z))throw new T(`where.${X.name}.${H?"notIn":"in"}`,$.name,J.operation,"Expected an array.");if(z.length===0)return H?j("true"):H9;return G.inList(Z,H,z.length,(V)=>{return Y(V).map((M)=>G.encode(M,X))})}function v7($,Z){return(X)=>{let z=String(Z(X));if($==="contains")return`%${z}%`;if($==="startsWith")return`${z}%`;return`%${z}`}}function F0($,Z,X){return(z)=>Z.encode(X(z),$)}function c3($){return typeof $==="object"&&$!==null&&!Array.isArray($)&&!($ instanceof Date)&&!ArrayBuffer.isView($)}function D9($,Z,X,z,J,Y,H){let G=`orderBy.${Z.name}`;if(typeof X!=="object"||X===null||Array.isArray(X))throw new T(G,$.name,z,Z.kind==="many"?'Expected { _count: "asc" | "desc" }.':`Expected an object naming one field of ${Z.model}.`);let V=X,W=Object.keys(V).filter((L)=>L!=="where");if(W.length!==1)throw new K(G,$.name,z,W.length===0?"Name the field to order by.":`Name exactly one field to order by; got ${W.join(", ")}. `+"Order by several with an array: [{ a: \u2026 }, { b: \u2026 }].");let[M]=W,B=N0($,Z,J,`_o${H}`,`${J.quoteIdent($.table)}.`,z),D=k7($,Z,B.child,M,V[M],z,B.qualifier,J),P=f(B.child,V.where,{dialect:J,operation:z,qualifier:B.qualifier},(L)=>Y(L)?.where),Q=[j(`(select ${D.expression} from ${B.source} where ${B.correlation}`)];if(P)Q.push(j(" and "),P);return Q.push(j(")")),{expression:R(...Q),direction:D.direction,nulls:D.nulls}}function k7($,Z,X,z,J,Y,H,G){let V=`orderBy.${Z.name}.${z}`,{direction:W,nulls:M}=f7($,V,J,Y);if(z===l){if(Z.kind!=="many")throw new K(V,$.name,Y,`${Z.name} is a to-one relation, so its count is 0 or 1. Order by one of ${X.name}'s fields instead.`);return{expression:"count(*)",direction:W,nulls:M}}if(Z.kind==="many")throw new K(V,$.name,Y,`${Z.name} is a to-many relation, so ordering by '${z}' has no single answer for a parent with several children. Only `+"{ _count: \u2026 } is supported.");let B=X.fields[z];if(!B)throw new K(V,$.name,Y,`'${z}' is not a field on ${X.name}. Known fields: ${Object.keys(X.fields).join(", ")}.`);return{expression:`${H}${G.quoteIdent(B.column)}`,direction:W,nulls:M}}function f7($,Z,X,z){if(X==="asc"||X==="desc")return{direction:X};if(typeof X==="object"&&X!==null){let{sort:J,nulls:Y}=X;if(J!=="asc"&&J!=="desc")throw new T(Z,$.name,z,'Expected "asc" or "desc".');if(Y===void 0)return{direction:J};if(Y!=="first"&&Y!=="last")throw new K(`${Z}.nulls`,$.name,z,'Expected "first" or "last".');return{direction:J,nulls:Y}}throw new K(Z,$.name,z,'Expected "asc", "desc", or { sort, nulls }.')}var g7=new Set(["asc","desc"]),y7=new Set(["first","last"]);function D0($,Z,X,z){if(Z===void 0||Z===null)return[];let J=Array.isArray(Z),Y=J?Z:[Z],H=[];for(let G=0;G<Y.length;G++){let V=Y[G],W=(M)=>{let B=z?.locate(M);return J?B?.[G]:B};if(typeof V!=="object"||V===null)throw new T("orderBy",$.name,X,"Expected an object or an array of objects.");for(let[M,B]of Object.entries(V)){if(B===void 0)continue;if(M in $.relations){if(!z)throw new K(`orderBy.${M}`,$.name,X,"Ordering by a relation is not implemented here.");let P=D9($,$.relations[M],B,X,z.dialect,(Q)=>W(Q)?.[M],H.length);H.push({column:M,direction:P.direction,...P.nulls?{nulls:P.nulls}:{},expression:P.expression});continue}let D=$.fields[M];if(!D)throw new g(M,$.name,Object.keys($.fields));H.push({column:D.column,...P9($,M,B,X)})}}return H}function P9($,Z,X,z){if(typeof X==="string"){if(!g7.has(X))throw new T(`orderBy.${Z}: ${JSON.stringify(X)}`,$.name,z,'Expected "asc" or "desc".');return{direction:X}}if(typeof X==="object"&&X!==null){let{sort:J,nulls:Y}=X,H=P9($,Z,J,z).direction;if(Y===void 0)return{direction:H};if(typeof Y!=="string"||!y7.has(Y))throw new K(`orderBy.${Z}.nulls: ${JSON.stringify(Y)}`,$.name,z,'Expected "first" or "last".');return{direction:H,nulls:Y}}throw new K(`orderBy.${Z}`,$.name,z,'Expected "asc", "desc", or { sort, nulls }.')}function V3($){return $.map((Z)=>({...Z,direction:Z.direction==="asc"?"desc":"asc",...Z.nulls?{nulls:Z.nulls==="first"?"last":"first"}:{}}))}function r($,Z,X){if($.length===0)return null;return x($.map((z)=>{let J=` ${z.direction}`+(z.nulls?` nulls ${z.nulls}`:"");if(z.expression)return x([z.expression,j(J)],"");return j(`${X??""}${Z.quoteIdent(z.column)}${J}`)}),", ")}function G3($,Z,X,z,J){if(typeof J!=="number"||!Number.isInteger(J))throw new T(X,$,Z,`Expected an integer, got ${JSON.stringify(J)}.`);if(z==="skip"&&J<0)throw new T(X,$,Z,"A 'skip' counts rows to pass over, so it cannot be negative. Prisma rejects one too.")}function Q0($,Z,X,z,J,Y=!1){if(X?.take!==void 0)G3($.name,Z,"take","take",X.take);if(X?.skip!==void 0)G3($.name,Z,"skip","skip",X.skip);let H=Y?1:X?.take,G=X?.skip,V=J;if((H!==void 0||G!==void 0)&&V.length===0&&!Y)V=$.primaryKey.map((P)=>({column:$.fields[P]?.column??P,direction:"asc"}));let M=typeof H==="number"&&H<0;if(M)V=V3(V);let B=H===void 0?null:Y?()=>1:(P)=>Math.abs(Number(P?.take)),D=G===void 0?null:(P)=>Number(P?.skip);return{clause:z.paginate(B,D),terms:V,reversed:M}}function J0($,Z,X){let z=Z?.select,J=Z?.omit;if(z!==void 0&&Z?.include!==void 0)throw new K("select + include",$.name,X,"Prisma allows only one of them on the same query.");if(z!==void 0&&J!==void 0)throw new K("select + omit",$.name,X,"'select' names what to keep and 'omit' what to drop, so the two describe different column lists. Prisma allows only one of them on "+"the same query. Drop the 'omit' \u2014 a 'select' already excludes "+"everything it does not name.");if(z===void 0||z===null)return h7($,J,X);if(typeof z!=="object"||Array.isArray(z))throw new T("select",$.name,X,"Expected an object.");let Y=[];for(let[G,V]of Object.entries($.fields))if(z[G]===!0)Y.push(V);let H=0;for(let G of Object.keys(z)){let V=z[G];if(V===void 0)continue;if(G in $.relations){if(V!==!1)H++;continue}if(G===l){if(V!==!1)H++;continue}if(!(G in $.fields))throw new g(G,$.name,Object.keys($.fields));if(typeof V!=="boolean")throw new T(`select.${G}`,$.name,X,"Expected true or false.")}if(Y.length===0&&H===0)throw new K("select",$.name,X,"At least one field must be selected.");return Y}function h7($,Z,X){if(Z===void 0||Z===null)return Object.values($.fields);if(typeof Z!=="object"||Array.isArray(Z))throw new T("omit",$.name,X,"Expected an object of fields.");let z=new Set;for(let Y of Object.keys(Z)){let H=Z[Y];if(H===void 0)continue;if(Y in $.relations)throw new K(`omit.${Y}`,$.name,X,`'${Y}' is a relation, not a column. A relation is already absent unless an 'include' asks for it.`);if(!(Y in $.fields))throw new g(Y,$.name,Object.keys($.fields));if(typeof H!=="boolean")throw new T(`omit.${Y}`,$.name,X,"Expected true or false.");if(H)z.add(Y)}let J=Object.values($.fields).filter((Y)=>!z.has(Y.name));if(J.length===0)throw new K("omit",$.name,X,`It omits every field on ${$.name}, which leaves no column to select. Prisma rejects that too.`);return J}function W3($,Z,X){if(X.length===0)return{fields:Z};let z=new Set(Z.map((H)=>H.name)),J=X.filter((H)=>!z.has(H));if(J.length===0)return{fields:Z};let Y=new Set([...z,...J]);return{fields:Object.values($.fields).filter((H)=>Y.has(H.name)),hidden:J}}var j9=new Set(["where","orderBy","select","omit","include","take","skip"]),K9=new Set(["where","select","omit","include"]),D3=10;function m0($){return[...new Set($.map((Z)=>Z.strategy))].sort()}function S0($,Z,X,z,J=P0){let Y=p0($,Z,z);if(Y.length===0)return{plans:[],keyFields:[]};let H=[],G=new Set;for(let V of Y){T9($,V,z);let W=U9($,V);R9(W,V.node,z,2);let M=J.plan({parent:$,child:W,relation:V.relation,as:V.as,node:V.node,locate:V.locate,dialect:X,operation:z});H.push(M);for(let B of M.parentFields)G.add(B)}return{plans:H,keyFields:[...G]}}async function j3($,Z,X,z,J){let Y=Array.isArray(X)?X:X===null||X===void 0?[]:[X];if(Y.length===0)return;for(let H of $){if(H.root)continue;await H.load(Y,z,J)}if(Z&&Z.length>0)for(let H of Y)for(let G of Z)delete H[G]}function p0($,Z,X){if(Z===void 0||Z===null)return[];let{include:z,select:J}=Z;C9($,z,J,X);let Y=[];if(z!==void 0&&z!==null){if(typeof z!=="object"||Array.isArray(z))throw new T("include",$.name,X,"Expected an object.");for(let H of Object.keys(z).sort()){let G=z[H];if(G===void 0||G===!1)continue;if(H===l)continue;let V=$.relations[H];if(!V)throw new y0(H,$.name,Object.keys($.relations));Y.push({as:H,relation:V,node:G,locate:(W)=>W?.include?.[H]})}return Y}if(J!==void 0&&J!==null&&typeof J==="object")for(let H of Object.keys(J).sort()){let G=J[H];if(G===void 0||G===!1)continue;let V=$.relations[H];if(!V)continue;Y.push({as:H,relation:V,node:G,locate:(W)=>W?.select?.[H]})}return Y}function C9($,Z,X,z,J){if(Z===void 0||X===void 0)return;throw new K(J?`${J}: select + include`:"select + include",$.name,z,"Prisma allows only one of them on the same query, at any level.")}function T9($,Z,X){let z=Z.node;if(z===!0)return;if(typeof z!=="object"||z===null||Array.isArray(z))throw new T(Z.as,$.name,X,"Expected true or an object of relation arguments.");let J=z;C9($,J.include,J.select,X,Z.as);let Y=Z.relation.kind==="many";for(let H of Object.keys(J).sort()){if(J[H]===void 0)continue;if(Y&&(H==="take"||H==="skip")){u7($,Z,X,H,J[H]);continue}if(Y?j9.has(H):K9.has(H))continue;if(H==="lock")throw new g0(`${Z.as}.lock`,$.name,X,"'lock' locks the rows of the model being queried, not an included relation's. Lock the related rows with their own locking read in the same transaction.");if(H==="orderBy"&&!Y)throw new K(`${Z.as}.orderBy`,$.name,X,"Prisma does not accept 'orderBy' on a to-one relation \u2014 there is at "+"most one row to order.");if(H==="take"||H==="skip")throw new K(`${Z.as}.${H}`,$.name,X,`Prisma does not accept '${H}' on a to-one relation.`);throw new K(`${Z.as}.${H}`,$.name,X,`A relation node takes ${[...Y?j9:K9].sort().join(", ")}.`)}}function u7($,Z,X,z,J){G3($.name,X,`${Z.as}.${z}`,z,J)}function n3($,Z){let X=$.node;if(typeof X!=="object"||X===null||Array.isArray(X))return;for(let z of["take","skip"]){if(X[z]===void 0)continue;throw new K(`${$.as}.${z}`,$.parent.name,$.operation,`A '${z}' inside a to-many relation is per parent, and the batched `+"relation planner serves every parent from one query \u2014 so the only "+`limit it could emit would page every parent's children as one set. Only the lateral join strategy can express it, by paginating inside a subquery that already runs once per parent row, and it needs Postgres: ${Z}. Load '${$.as}' as its own query, or narrow it with 'where'.`)}}function R9($,Z,X,z){if(typeof Z!=="object"||Z===null||Array.isArray(Z))return;if(Z.select!==void 0)J0($,Z,X);let J=p0($,Z,X);if(J.length===0)return;if(z>D3)throw new s3($.name,D3);for(let Y of J)T9($,Y,X),R9(U9($,Y),Y.node,X,z+1)}function I9($,Z,X,z){if($.parentFields.length!==1)throw new K(X.name,Z.name,z,`${X.name} joins on ${$.parentFields.length} fields (${$.parentFields.join(", ")}), and it is planned through a join table, which links two models by a single primary key each side. Prisma does not build an implicit many-to-many over a composite key.`);return{parentField:$.parentFields[0],childField:$.childFields[0],join:$.join}}function B0($,Z,X,z){if(X.joinTable)return p7($,Z,X);if(X.from.length>0)return Q9($,X,X.from,X.to,z);let J=m7($,Z,X);if(J.from.length===0)throw new s($.name,X.name,`neither ${$.name}.${X.name} nor ${Z.name}.${J.name} holds the foreign key.`);return Q9($,X,J.to,J.from,z)}function Q9($,Z,X,z,J){if(X.length===0)throw new K(Z.name,$.name,J,`${Z.name} names no join fields.`);if(X.length!==z.length)throw new s($.name,Z.name,`it joins ${X.length} field(s) to ${z.length}: ${X.join(", ")} against ${z.join(", ")}.`);return{parentFields:X,childFields:z}}function m7($,Z,X){let z=Object.values(Z.relations).filter((J)=>J.relationName===X.relationName&&!(Z.name===$.name&&J.name===X.name));if(z.length!==1)throw new s($.name,X.name,z.length===0?`${Z.name} declares no relation named '${X.relationName}'.`:`${Z.name} declares ${z.length} relations named '${X.relationName}'.`);return z[0]}function p7($,Z,X){let{table:z,a:J,b:Y}=X.joinTable;if(J===Y){let G=X.joinTable.ownerColumn;if(!G)throw new K(X.name,$.name,"include",`${X.name} is a self-referential implicit many-to-many, and the generated artifact predates support for one. Re-run \`prisma generate\`.`);return{parentFields:[M3($,X)],childFields:[M3(Z,X)],join:{table:z,parentColumn:G,childColumn:G==="A"?"B":"A"}}}if($.name!==J&&$.name!==Y)throw new s($.name,X.name,`the join table '${z}' connects ${J} and ${Y}, neither of which is ${$.name}.`);let H=$.name===J?"A":"B";return{parentFields:[M3($,X)],childFields:[M3(Z,X)],join:{table:z,parentColumn:H,childColumn:H==="A"?"B":"A"}}}function M3($,Z){if($.primaryKey.length!==1)throw new s($.name,Z.name,`an implicit many-to-many joins on ${$.name}'s primary key, which has ${$.primaryKey.length} fields.`);return $.primaryKey[0]}function B3($,Z,X){let z=$.fields[X];if(!z)throw new s($.name,Z.name,`it joins on '${X}', which is not a field on ${$.name}.`);return z}function U9($,Z){return X0($,Z.relation,Z.as)}function X0($,Z,X=Z.name){let z=Z.model;if(!a(z))throw new i3($.name,X,z,P3());let J=d(z)?.$schema;if(!J)throw new h0(z);return J}var _9="batched",P0={name:_9,plan($){n3($,"this query planned with the batched strategy");let Z=B0($.parent,$.child,$.relation,$.operation);for(let Y of Z.parentFields)L9($.parent,$.relation,B3($.parent,$.relation,Y));for(let Y of Z.childFields)L9($.child,$.relation,B3($.child,$.relation,Y));let X=B3($.parent,$.relation,Z.parentFields[0]),z=B3($.child,$.relation,Z.childFields[0]),J=$.relation.kind==="many";return{as:$.as,model:$.relation.model,kind:$.relation.kind,parentFields:Z.parentFields,strategy:_9,load(Y,H,G){let V={parentKeyField:X,childKeyField:z,many:J,parents:Y,args:H,executor:G};return Z.join?c7($,Z,V):d7($,Z,V)}}}};async function d7($,Z,X){let{keys:z,byKey:J}=O9(X.parents,Z.parentFields);if(z.length===0)return;let Y=$.locate(X.args),H=N9(Y,Z.childFields,z,$.child,$.dialect),G=await X.executor.exec($.relation.model,"findMany",H.args,!0);for(let V of G){let W=J.get(f0(Z.childFields.map((M)=>V[M])));if(!W)continue;for(let M of W)F9(M,$.as,V,X.many)}if(H.hidden)for(let V of G)for(let W of Z.childFields)delete V[W]}async function c7($,Z,X){let{keys:z,byKey:J}=O9(X.parents,Z.parentFields);if(z.length===0)return;let{dialect:Y}=$,H=Z.join,G=await s7(Y,H,z.map((P)=>Y.encode(P[0],X.parentKeyField)),X.executor),V=new Map,W=[];for(let P of G){let Q=f0([Y.decode(P[H.parentColumn],X.parentKeyField)]),L=J.get(Q);if(!L)continue;let F=Y.decode(P[H.childColumn],X.childKeyField),N=f0([F]),C=V.get(N);if(C===void 0)C=[],V.set(N,C),W.push([F]);for(let _ of L)C.push(_)}if(W.length===0)return;let M=$.locate(X.args),B=N9(M,Z.childFields,W,$.child,$.dialect),D=await X.executor.exec($.relation.model,"findMany",B.args,!0);for(let P of D){let Q=V.get(f0([P[Z.childFields[0]]]));if(!Q)continue;for(let L of Q)F9(L,$.as,P,X.many)}if(B.hidden)for(let P of D)delete P[Z.childFields[0]]}async function s7($,Z,X,z){let J=R(j(`select ${$.quoteIdent(Z.parentColumn)}, ${$.quoteIdent(Z.childColumn)} from ${$.quoteIdent(Z.table)} where `),$.inList($.quoteIdent(Z.parentColumn),!1,X.length,()=>X)),{text:Y,binders:H}=c(J,$,{model:Z.table,operation:"include"}),G=A0();return z.query(Y,H.map((V)=>V(void 0,G)))}function N9($,Z,X,z,J){let Y=$===!0||$===null||typeof $!=="object"?{}:$,H=Z.length===1?{[Z[0]]:{in:X.map((B)=>B[0])}}:i7(z,Z,X,J),G={where:Y.where===void 0?H:{AND:[Y.where,H]}};if(Y.orderBy!==void 0)G.orderBy=Y.orderBy;if(Y.include!==void 0)G.include=Y.include;let V=Y.omit;if(V!==void 0){let B=Z.filter((D)=>V[D]===!0);if(B.length===0)G.omit=V;else{let D={...V};for(let P of B)delete D[P];return G.omit=D,{args:G,hidden:!0}}}let W=Y.select;if(W===void 0)return{args:G,hidden:!1};let M=Z.filter((B)=>W[B]!==!0);if(M.length===0)return G.select=W,{args:G,hidden:!1};G.select={...W};for(let B of M)G.select[B]=!0;return{args:G,hidden:!0}}function i7($,Z,X,z){let J=Z.map((Y)=>$.fields[Y]?.type);if(J.every((Y)=>Y!==void 0)&&z.canBindCompositeIn(J))return{[z0]:W9(Z,X)};return{OR:X.map((Y)=>Object.fromEntries(Z.map((H,G)=>[H,Y[G]])))}}function f0($){return JSON.stringify($.map(n7))}function F9($,Z,X,z){if(z){$[Z].push(X);return}if($[Z]===null)$[Z]=X}function O9($,Z){let X=new Map,z=[];for(let J of $){let Y=Z.map((V)=>J[V]);if(Y.some((V)=>V===null||V===void 0))continue;let H=f0(Y),G=X.get(H);if(G===void 0)G=[],X.set(H,G),z.push(Y);G.push(J)}return{keys:z,byKey:X}}function n7($){if(typeof $!=="object"||$===null)return $;if($ instanceof Date)return $.getTime();if(ArrayBuffer.isView($)){let Z=new Uint8Array($.buffer,$.byteOffset,$.byteLength),X="";for(let z of Z)X+=z.toString(16).padStart(2,"0");return`bytes:${X}`}throw Error(`Cannot key a relation stitch on ${Object.prototype.toString.call($)}.`)}function L9($,Z,X){if(X.isList)throw new s($.name,Z.name,`it joins on '${X.name}', a ${X.type} list \u2014 which decodes to a new `+"array per row and so cannot be compared between the two sides.");if(X.type!=="Json")return;throw new s($.name,Z.name,`it joins on '${X.name}', a ${X.type} \u2014 which decodes to a new object `+"per row and so cannot be compared between the two sides.")}var A9=(()=>{try{return Function("return 1")()===1}catch{return!1}})(),S9=!0;function l7($){S9=$}function o7(){return A9}function d0($,Z,X=[]){if(A9&&S9)return t7($,Z,X);return l3($,Z,X)}function l3($,Z,X=[]){let z=$.map((G)=>({key:G.name,column:G.column,field:G,decode:Z.needsDecode(G)})),J=z.length,Y=X.map((G)=>({key:G.key,many:G.kind==="many"})),H=Y.length;return(G)=>{let V=[];for(let W=0;W<G.length;W++){let M=G[W],B={};for(let D=0;D<J;D++){let P=z[D],Q=M[P.column];B[P.key]=P.decode?Z.decode(Q,P.field):Q??null}for(let D=0;D<H;D++)B[Y[D].key]=Y[D].many?[]:null;V.push(B)}return V}}function t7($,Z,X){let z=[];for(let Y=0;Y<$.length;Y++){let H=$[Y],G=JSON.stringify(H.name),V=JSON.stringify(H.column);z.push(Z.needsDecode(H)?`${G}: d.decode(row[${V}], f[${Y}])`:`${G}: row[${V}] ?? null`)}for(let Y of X)z.push(`${JSON.stringify(Y.key)}: ${Y.kind==="many"?"[]":"null"}`);let J=`
|
|
3
3
|
return function shape(rows) {
|
|
4
4
|
const out = [];
|
|
5
5
|
for (let i = 0; i < rows.length; i++) {
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-wzng3k56.js";import{Dm as Q,Fm as q,Gm as w,Jm as Z,Km as P,Lm as y,Mm as S,Nm as U}from"../chunk-49kkapvr.js";import{Rm as H}from"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import{Zm as F}from"../chunk-4rs6w1gp.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-
|
|
2
|
+
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-wzng3k56.js";import{Dm as Q,Fm as q,Gm as w,Jm as Z,Km as P,Lm as y,Mm as S,Nm as U}from"../chunk-49kkapvr.js";import{Rm as H}from"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import{Zm as F}from"../chunk-4rs6w1gp.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-h1a4febx.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-cvg01wc0.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{q as shutdownSignal,W as liveness,Q as isShuttingDown,w as holdShutdown,k as Server};
|
|
3
3
|
|
|
4
4
|
//# debugId=EC8ABA7ED3EF474964756E2164756E21
|
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,ic as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-sajfdtkt.js";import{lc as d4}from"../chunk-txf4kfze.js";import"../chunk-7ytazpjd.js";import{he as D9,ie as H9,je as N9,ke as U9,le as x9,me as R9,ne as O9,oe as _9,pe as V9,qe as k9,re as C9,se as T9,te as P9,ue as b9,ve as w9,we as q9}from"../chunk-mt68n713.js";import{xe as S9}from"../chunk-w9v8bbp8.js";import{Ae as pZ,Be as dZ,Ce as lZ,De as nZ,Ee as iZ,Fe as sZ,Ge as oZ,He as aZ,Ie as tZ,Je as rZ,Ke as eZ,Le as W9,Me as Z9,Ne as $9,Oe as Q9,Pe as Y9,Qe as K9,Ve as J9,ye as cZ,ze as uZ}from"../chunk-8ccjtbm2.js";import{We as h9,Xe as E9}from"../chunk-g7exgg3k.js";import"../chunk-bhycdjcv.js";import{$g as TZ,Af as Y8,Ag as GZ,Bf as K8,Cf as J8,Cg as XZ,Df as z8,Dg as BZ,Ef as G8,Eg as jZ,Ff as X8,Fg as MZ,Gf as B8,Gg as FZ,Hf as j8,Hg as LZ,If as Y6,Ig as DZ,Ih as yZ,Jf as M8,Jg as HZ,Jh as AZ,Kf as F8,Kg as NZ,Lf as L8,Lg as UZ,Mf as D8,Nf as H8,Qg as R,Rg as i,Sg as xZ,Tg as SZ,Ug as RZ,Vg as OZ,Wg as _Z,Yg as VZ,Zg as kZ,_g as CZ,ag as T8,bg as P8,bh as PZ,cg as b8,df as V6,dg as w8,ef as e5,eg as q8,eh as bZ,ff as W8,fg as v8,fh as wZ,gf as Z8,gh as qZ,if as $8,jh as vZ,mg as e8,ng as q6,of as k6,og as WZ,oh as IZ,pf as C4,qf as B6,rf as T4,sf as P4,sg as ZZ,sh as fZ,tg as $Z,ug as YZ,wf as f6,wh as i4,xf as y6,xg as KZ,xh as z1,yg as JZ,zf as Q8,zg as zZ}from"../chunk-g6re0kkk.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{$i as Y1,Aj as _8,Bi as k4,Ci as O4,Cj as d1,Di as k1,Vi as h4,Zi as j1,cj as _4,dj as C1,ej as p1,fj as N8,gj as U8,hj as x8,ij as S8,jj as R8,vj as mW,wj as cW,zj as O8}from"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import{Nj as V8,Oj as k8,Pj as C8}from"../chunk-ca1qwsjj.js";import{Rj as q}from"../chunk-0xmk4jyj.js";import{$j as U,Zj as g8,_j as m8,ak as c8,bk as b,ck as u8,dk as p8}from"../chunk-j0bbh93g.js";import{jk as A8,kk as h8,lk as E8}from"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import{Uk as QZ}from"../chunk-9a3wbbr6.js";import{$k as n8,Wk as I8,Xk as f8,Yk as y8,Zk as d8,_k as l8,al as i8,bl as s8,cl as o8,hl as a8,il as t8,jl as r8}from"../chunk-fhbre39m.js";import"../chunk-6wv3k8ap.js";import"../chunk-ab5xsxyx.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import{fm as w4,gm as hZ,hm as EZ,im as gZ,km as mZ}from"../chunk-mykr2v6g.js";import"../chunk-kbz5s9wb.js";import{um as C}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import{Zm as u1}from"../chunk-4rs6w1gp.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-d2jafhaf.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
2
|
+
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,ic as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-dnqmvmnp.js";import{lc as d4}from"../chunk-41bpne77.js";import"../chunk-7ytazpjd.js";import{he as D9,ie as H9,je as N9,ke as U9,le as x9,me as R9,ne as O9,oe as _9,pe as V9,qe as k9,re as C9,se as T9,te as P9,ue as b9,ve as w9,we as q9}from"../chunk-5na9khtz.js";import{xe as S9}from"../chunk-w9v8bbp8.js";import{Ae as pZ,Be as dZ,Ce as lZ,De as nZ,Ee as iZ,Fe as sZ,Ge as oZ,He as aZ,Ie as tZ,Je as rZ,Ke as eZ,Le as W9,Me as Z9,Ne as $9,Oe as Q9,Pe as Y9,Qe as K9,Ve as J9,ye as cZ,ze as uZ}from"../chunk-wt80ekv9.js";import{We as h9,Xe as E9}from"../chunk-g7exgg3k.js";import"../chunk-bhycdjcv.js";import{$g as TZ,Af as Y8,Ag as GZ,Bf as K8,Cf as J8,Cg as XZ,Df as z8,Dg as BZ,Ef as G8,Eg as jZ,Ff as X8,Fg as MZ,Gf as B8,Gg as FZ,Hf as j8,Hg as LZ,If as Y6,Ig as DZ,Ih as yZ,Jf as M8,Jg as HZ,Jh as AZ,Kf as F8,Kg as NZ,Lf as L8,Lg as UZ,Mf as D8,Nf as H8,Qg as R,Rg as i,Sg as xZ,Tg as SZ,Ug as RZ,Vg as OZ,Wg as _Z,Yg as VZ,Zg as kZ,_g as CZ,ag as T8,bg as P8,bh as PZ,cg as b8,df as V6,dg as w8,ef as e5,eg as q8,eh as bZ,ff as W8,fg as v8,fh as wZ,gf as Z8,gh as qZ,if as $8,jh as vZ,mg as e8,ng as q6,of as k6,og as WZ,oh as IZ,pf as C4,qf as B6,rf as T4,sf as P4,sg as ZZ,sh as fZ,tg as $Z,ug as YZ,wf as f6,wh as i4,xf as y6,xg as KZ,xh as z1,yg as JZ,zf as Q8,zg as zZ}from"../chunk-y89vn9da.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{$i as Y1,Aj as _8,Bi as k4,Ci as O4,Cj as d1,Di as k1,Vi as h4,Zi as j1,cj as _4,dj as C1,ej as p1,fj as N8,gj as U8,hj as x8,ij as S8,jj as R8,vj as mW,wj as cW,zj as O8}from"../chunk-h2cvg5r5.js";import"../chunk-2g1h9ktj.js";import{Nj as V8,Oj as k8,Pj as C8}from"../chunk-ca1qwsjj.js";import{Rj as q}from"../chunk-0xmk4jyj.js";import{$j as U,Zj as g8,_j as m8,ak as c8,bk as b,ck as u8,dk as p8}from"../chunk-szyr67g7.js";import{jk as A8,kk as h8,lk as E8}from"../chunk-8adbpxpm.js";import"../chunk-768yza4f.js";import{Uk as QZ}from"../chunk-9a3wbbr6.js";import{$k as n8,Wk as I8,Xk as f8,Yk as y8,Zk as d8,_k as l8,al as i8,bl as s8,cl as o8,hl as a8,il as t8,jl as r8}from"../chunk-psdcmh65.js";import"../chunk-6wv3k8ap.js";import"../chunk-mxqrmjha.js";import"../chunk-2as2xfem.js";import"../chunk-mhvg8nnb.js";import{fm as w4,gm as hZ,hm as EZ,im as gZ,km as mZ}from"../chunk-mykr2v6g.js";import"../chunk-kbz5s9wb.js";import{um as C}from"../chunk-wj0q7tyn.js";import"../chunk-vtf7tkef.js";import"../chunk-dh1wbntq.js";import"../chunk-49kkapvr.js";import"../chunk-j5r7vm8a.js";import"../chunk-358krc4n.js";import{Zm as u1}from"../chunk-4rs6w1gp.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-d2jafhaf.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qe as J,Te as A}from"../../chunk-
|
|
2
|
+
import{Qe as J,Te as A}from"../../chunk-wt80ekv9.js";import{Uk as V}from"../../chunk-9a3wbbr6.js";import"../../chunk-psdcmh65.js";import"../../chunk-6wv3k8ap.js";import"../../chunk-mxqrmjha.js";import"../../chunk-2as2xfem.js";import"../../chunk-wj0q7tyn.js";import"../../chunk-vtf7tkef.js";import{Em as Y,Hm as N,Im as Z,Jm as _,Nm as I}from"../../chunk-49kkapvr.js";import{Rm as x}from"../../chunk-j5r7vm8a.js";import"../../chunk-4rs6w1gp.js";import $ from"path";function X(z){if(!z.config.get("route.channels"))return null;let C=z.config.get("broadcast",{}).driver;if(!(C===void 0||C==="memory"||C instanceof V))return null;return'[gemi] Broadcasts from this worker reach no one: the broadcast driver is "memory", which delivers to the sockets of the process that emits, and a worker has none. Set `driver: "redis"` in app/config/broadcast.ts.'}class L extends Error{name="QueueWorkerRefused"}class O{kernel;stopping;keepAlive;settings;constructor(z,C={}){this.kernel=z;this.settings={..._(),...C}}async start(){if(await this.kernel.waitForBoot(),this.stopping)return;let z=this.kernel.app;if(!z.bound(J))throw new L("[gemi] `gemi queue:work` has no queue to claim from: this application does not register QueueServiceProvider.");let C=z.make(J);if(!C.durable)throw new L('[gemi] `gemi queue:work` refuses to start: the queue uses the memory driver, which keeps each job in the process that dispatched it, so a worker never sees one. Set `driver: "database"` (or another driver every process can reach) in app/config/queue.ts, or run jobs in the server and drop the worker.');C.start(),this.keepAlive=setInterval(()=>{},1073741824),console.log(`[gemi] Queue worker started: claiming up to ${C.config.concurrency} job(s) at a time.`);let E=X(z);if(E)console.warn(E)}stop(z={}){return this.stopping??=this.drain({...this.settings,...z}),this.stopping}async drain(z){let C=Date.now()+z.timeoutMs;Y();let E=this.kernel.app,F=E.resolved(J)?E.make(J):void 0;if(F)console.log(`[gemi] Shutting down: waiting for ${F.running} running job(s) (up to ${z.timeoutMs/1000}s).`),await F.drain(z.timeoutMs);let G=N()===0;if(!G){let U=C-Date.now();if(G=U>0&&await Promise.race([Z().then(()=>!0),new Promise((K)=>setTimeout(()=>K(!1),U))]),!G)console.error(`[gemi] Shutdown grace period elapsed with ${N()} held background task(s) still running; abandoning them.`)}let H=await this.kernel.shutdown({timeoutMs:z.providerTimeoutMs});clearInterval(this.keepAlive);let T=G&&(F?.running??0)===0&&H.failed.length===0&&H.timedOut.length===0;return console.log(`[gemi] Shutdown ${T?"complete":"finished with errors"}.`),T?0:1}}async function j(){let z=x();process.env.ROOT_DIR=z,process.env.APP_DIR=$.join(z,"app"),A();let C=$.join(z,"app/kernel/Kernel.ts"),{default:E}=await import(C);if(typeof E!=="function")return console.error(`[gemi] ${C} has no default export to boot the worker from.`),1;let F=new E;F.boot();let G=new O(F);I(()=>G.stop());try{await G.start()}catch(H){if(!(H instanceof L))throw H;return console.error(H.message),1}return}j().then((z)=>{if(z!==void 0)process.exit(z)},(z)=>{console.error("[gemi] The queue worker failed to start:",z),process.exit(1)});
|
|
3
3
|
|
|
4
4
|
//# debugId=8DA4890EA058388D64756E2164756E21
|
package/package.json
CHANGED
package/dist/chunk-ab5xsxyx.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Kl as Q,Rl as F,Ul as D}from"./chunk-2as2xfem.js";import{AsyncLocalStorage as L}from"async_hooks";var P=new L;function u(){return P.getStore()?.tx}function E(){return P.getStore()?.connection??F}function c(z,B){let J=P.getStore();if(E()===z)return B();return w(z),P.run({...J,depth:J?.depth??0,connection:z===F?void 0:z},B)}function w(z){let B=P.getStore();if(B?.tx===void 0)return;let J=B.connection??F;if(J===z)return;throw new D(J,z)}function k(z){let B=P.getStore();if(B?.tx===void 0||B.afterCommit===void 0)return!1;let J=W.get(B.afterCommit);if(J==="committed")return!1;if(J==="rolled_back")return!0;return B.afterCommit.push(z),!0}var W=new WeakMap;function d(z){if(k(z))return Promise.resolve();let B=(J)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",J)};try{return Promise.resolve(z()).catch(B)}catch(J){return B(J),Promise.resolve()}}function l(z){let B=P.getStore();if(B?.tx!==void 0&&B.tx===z&&B.statementFailed)B.statementFailed.value=!0}function i(z){let B=P.getStore();if(B?.tx===void 0||B.commitDependsOn===void 0)return!1;return B.commitDependsOn.push(z),!0}class A extends Error{constructor(z){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${z instanceof Error?z.message:String(z)}`,{cause:z});this.name="TransactionDependencyError"}}async function O(z,B){if(z.length===B)return;let K=(await Promise.allSettled(z.slice(B))).find((X)=>X.status==="rejected");if(K)throw new A(K.reason)}function a(){let z=P.getStore();return z?.tx===void 0?null:z.depth}function s(){return P.getStore()?.system===!0}function o(z){let B=P.getStore();return P.run({...B,depth:B?.depth??0,system:!0},z)}function n(z){return P.getStore()?.trashed?.get(z)}function t(z,B,J){let K=P.getStore(),X=new Map(K?.trashed);return X.set(z,B),P.run({...K,depth:K?.depth??0,trashed:X},J)}function r(){return P.getStore()?.actor}function e(z,B){let J=P.getStore();return P.run({...J,depth:J?.depth??0,system:!1,actor:{user:z??null}},B)}function _(z){if(Bun.env.NODE_ENV!=="development")return null;if(z===!1)return null;if(z===void 0)return Q;if(!Number.isFinite(z)||z<=0)return Q;return z}function N(z){let B=_(z);if(B===null)return()=>{};let J=Error("transaction opened here"),K=setTimeout(()=>{let X=J.stack?.split(`
|
|
3
|
-
`).slice(1).join(`
|
|
4
|
-
`)??"";console.warn(`[gemi] A database transaction has not settled after ${B}ms. It `+"reserves a pooled connection until it does \u2014 check for network or "+`filesystem I/O inside the callback, and move it outside the transaction if you find any.
|
|
5
|
-
${X}
|
|
6
|
-
(development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},B);return K.unref?.(),()=>clearTimeout(K)}async function T(z,B){if(z.length===0)return;await P.run({...B,tx:void 0,afterCommit:void 0,commitDependsOn:void 0,depth:B?.depth??0},async()=>{for(let J of z)try{await J()}catch(K){console.error("An after-commit callback threw. The transaction it was waiting on had already committed and stays committed, and the callbacks after it still ran.",K)}})}function zz(z,B,J){let K=P.getStore(),X=J?.connection??F;if(w(X),K?.tx){let V=K.afterCommit,Z=V?.length??0,G=K.commitDependsOn,Y=G?.length??0;return K.tx.savepoint((j)=>{let M=j;return P.run({...K,tx:M,depth:K.depth+1},async()=>{let $=await B(M);if(G)await O(G,Y);return $})}).catch((j)=>{if(V)V.length=Z;if(G)G.length=Y;throw j})}if(J?.dialect==="sqlite")return x(z,(V)=>v(z,B,J,K,X,V),J);return v(z,B,J,K,X)}var I=new WeakMap;class b extends Error{constructor(){super("A SQLite transaction started from inside an open transaction on the same connection, outside its scope (a raw `begin`, or an in-process call that left the transaction's scope while the transaction waits on it). SQLite runs one transaction per connection, so it would wait for the transaction that waits on it. Run it after the commit (`afterCommit`), or inside the transaction.");this.name="TransactionQueueDeadlockError"}}var H=new WeakMap,U=new L,S=5000;function x(z,B,J={}){let K=U.getStore(),X={},V,Z=new Promise((Y)=>{V=()=>{if(H.get(z)===X)H.delete(z);Y()}}),G=I.get(z)??Promise.resolve();return I.set(z,Z),new Promise((Y,j)=>{let M=!1,$=_(J.slowTransactionThreshold)===null?void 0:Error("transaction queued here"),R=setTimeout(()=>{let q=H.get(z);if(q&&K?.has(q)){M=!0,j(new b);return}if($)g($)},S);R.unref?.(),G.then(()=>{if(clearTimeout(R),M){V();return}H.set(z,X);let q=U.run(new Set([...K??[],X]),()=>B(V));q.then(V,V),q.then(Y,j)})})}function g(z){let B=z.stack?.split(`
|
|
7
|
-
`).slice(1).join(`
|
|
8
|
-
`)??"";console.warn(`[gemi] A SQLite transaction has waited ${S}ms for the one open on its connection (SQLite runs one at a time per connection). Look for a long transaction, or one that waits on work started outside it.
|
|
9
|
-
${B}
|
|
10
|
-
(development only; database.slowTransactionThreshold: false switches it off)`)}function v(z,B,J,K,X,V){let Z=N(J?.slowTransactionThreshold),G=V?[V]:[],Y=[],j=new Map,M={value:!1};try{return z.begin(($)=>P.run({...K,tx:$,depth:0,connection:X===F?void 0:X,afterCommit:G,commitDependsOn:Y,appliedSettings:j,statementFailed:M},async()=>{if(!J?.deferSettings)await y($,K?.settings,j);let R=await B($);if(await O(Y,0),M.value)await $.unsafe("select 1");return R})).finally(Z).then(async($)=>{return W.set(G,"committed"),await T(G,K),$},($)=>{throw W.set(G,"rolled_back"),$})}catch($){throw Z(),$}}var f=/^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)+$/;class h extends Error{setting;outer;inner;constructor(z,B,J){super(`DB.withSettings: "${z}" is already "${B}" in an enclosing withSettings block, and a nested block can't change it to "${J}". Open a separate block outside the first one.`);this.setting=z;this.outer=B;this.inner=J;this.name="SessionSettingConflictError"}}function Bz(){let z=P.getStore()?.settings;return z&&Object.keys(z).length>0?z:void 0}async function y(z,B,J){if(!B)return[];let K=Object.entries(B).filter(([V,Z])=>J.get(V)!==Z);if(K.length===0)return[];let X=K.map((V,Z)=>`set_config($${Z*2+1}, $${Z*2+2}, true)`);await z.unsafe(`select ${X.join(", ")}`,K.flatMap(([V,Z])=>[V,Z]));for(let[V,Z]of K)J.set(V,Z);return K.map(([V])=>V)}async function Jz(){let z=P.getStore();if(z?.tx&&z.appliedSettings)await y(z.tx,z.settings,z.appliedSettings)}async function Kz(z,B){let J=P.getStore(),K=J?.settings??{},X={...K};for(let[Y,j]of Object.entries(z)){if(!f.test(Y))throw Error(`DB.withSettings: "${Y}" is not a custom setting name. Use a prefix and a dot, like "app.tenant_id".`);let M=j===null?"":String(j);if(Object.hasOwn(K,Y)&&K[Y]!==M)throw new h(Y,K[Y],M);X[Y]=M}let V={...J,depth:J?.depth??0,settings:X},Z=J?.tx,G=J?.appliedSettings;if(!Z||!G)return P.run(V,B);return P.run(V,async()=>{let Y=await y(Z,X,G),j=async()=>{if(Y.length===0)return;let $=Y.map((R,q)=>`set_config($${q+1}, '', true)`);await Z.unsafe(`select ${$.join(", ")}`,Y);for(let R of Y)G.delete(R)},M;try{M=await B()}catch($){throw await j().catch(()=>{}),$}return await j(),M})}
|
|
11
|
-
export{P as ll,u as ml,E as nl,c as ol,w as pl,k as ql,d as rl,l as sl,i as tl,A as ul,a as vl,s as wl,o as xl,n as yl,t as zl,r as Al,e as Bl,zz as Cl,x as Dl,h as El,Bz as Fl,Jz as Gl,Kz as Hl};
|
|
12
|
-
|
|
13
|
-
//# debugId=5AF602F2ECA2FC9964756E2164756E21
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../orm/context.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import type { SQL, TransactionSQL } from \"bun\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { SLOW_TRANSACTION_THRESHOLD } from \"../database/config\";\nimport {\n CrossConnectionTransactionError,\n DEFAULT_CONNECTION,\n} from \"../database/Connection\";\n\n/**\n * The ambient transaction: the ORM's own `AsyncLocalStorage`, holding nothing\n * but the open handle and how deep the nesting is.\n *\n * One store per scope with one owner, which is the pattern the framework\n * already follows — `kernel/context.ts` holds the Application,\n * `http/requestContext.ts` the request and its user. The reasoning for\n * not folding this into the kernel's is written up beside it, and the short\n * version is that a transaction scope has to *nest inside* an Application scope\n * without replacing it, and `foundation/app.ts` must keep reading exactly one\n * shape out of the kernel store or resolving a service becomes a transaction\n * concern.\n *\n * What makes an ALS the right home rather than a field somewhere: two concurrent\n * requests each in their own transaction must never see each other's handle.\n * Anything reachable from the Application — which is one object shared by every\n * in-flight request — fails that by construction, and fails it as silently\n * written data, not as an error. \"two concurrent transactions never see each\n * other's handle\" in `context.test.ts` is the test that would catch it.\n */\nexport interface OrmScope {\n /**\n * Bun's transaction handle. Every ORM statement in scope runs on it, which\n * means they all run on one reserved connection — so nothing here may issue\n * two statements concurrently. `Model.$exec` already runs its nested writes\n * and its relation reads sequentially, for exactly this reason.\n */\n tx?: TransactionSQL;\n /** 0 for the outermost transaction, 1+ for each savepoint inside it. */\n depth: number;\n /**\n * Which named connection this subtree's queries run on, and — when `tx` is\n * set — which connection the open transaction belongs to.\n *\n * Ambient rather than an argument threaded through `$exec`, for the same\n * reason the handle above is: a relation read resolves its target through the\n * registry and calls that class's `$exec`, so an argument would have to be\n * carried by every intermediate that has no interest in it, and the one that\n * forgot would silently read a nested `include` off the *other* pool. There\n * is no error that shape produces; there are just rows from the wrong place.\n *\n * `undefined` means the default connection. Kept as absent-rather-than-\n * `\"default\"` so that entering a scope on the default connection is\n * indistinguishable from not entering one, which is what makes the\n * cross-connection check below cost a comparison of two `undefined`s on every\n * application that never declares a second connection.\n */\n connection?: string;\n /**\n * Whether policies are suspended for this scope. Set only by\n * `Model.asSystem`, and never by anything ambient — the whole point is that\n * unscoped access is a decision visible at the call site, not the accidental\n * result of a missing user.\n */\n system?: boolean;\n /**\n * The user policies should scope to, when there is no request to read one\n * from. Set only by `Model.asUser`.\n *\n * A sentinel wrapper rather than the bare value, so that \"a scope was entered\n * with `null`\" stays distinguishable from \"no scope was entered\" — the two\n * mean different things under deny-by-default.\n */\n actor?: { user: unknown };\n /**\n * Work that must not happen unless this transaction commits — an event whose\n * `static afterCommit` is set, today, and nothing else.\n *\n * **Created by the outermost `withTransaction` and never by a savepoint.** A\n * savepoint's scope is a spread of its parent's (`{ ...current, tx: nested }`),\n * so the array arrives here already shared by reference with the transaction\n * that opened it — which is the behaviour wanted rather than a leak. A\n * dispatch made inside a savepoint that commits, in a transaction that then\n * rolls back, must not run: rolling back the outermost transaction discards\n * the list whole, savepoint entries included, because nothing ever drains it.\n *\n * The inverse — a savepoint that rolls back under a transaction that commits\n * — is the case sharing gets wrong on its own, and `withTransaction`'s\n * savepoint branch is where it is put right.\n *\n * Absent, rather than an empty array, on every scope that is not a\n * transaction: `runAsSystem`, `runAsUser` and `runOnConnection` spread\n * whatever they are given, so \"there is a list here\" and \"there is an open\n * transaction here\" have to stay the same question. `deferUntilCommit`\n * answers `false` when either half is missing and the caller runs the work\n * now, which is what keeps a hand-built scope carrying a `tx` — the shape\n * tests write — from swallowing a dispatch into a list nothing drains.\n */\n afterCommit?: AfterCommitCallback[];\n /**\n * Statements written on `tx` that the commit must wait for and must not\n * outlive — today, a job row the database queue driver wrote on the\n * transaction (#563), and nothing else. See `commitDependsOn`.\n *\n * Created and shared exactly as `afterCommit` is, and truncated with it\n * when a savepoint rolls back.\n */\n commitDependsOn?: Promise<unknown>[];\n /**\n * Set when a statement the ORM or `DB` ran on `tx` failed. Shared by the\n * outermost transaction and its savepoints, like `afterCommit`.\n *\n * On Postgres a failed statement aborts the transaction, and a caller that\n * catches the error and returns normally used to get a resolved\n * `Model.transaction` whose `COMMIT` had quietly been a rollback: nothing\n * written, and the after-commit work ran anyway. Bun 1.4.3 and later reject\n * that `COMMIT` with `ERR_POSTGRES_COMMIT_ROLLED_BACK`; earlier versions\n * resolve. So when this is set, `withTransaction` asks the transaction one\n * `select 1` before it commits, which fails on an aborted transaction on\n * every Bun version, and costs nothing on the path where nothing failed.\n */\n statementFailed?: { value: boolean };\n /**\n * Models whose soft-delete scope (`static $softDeletes`) is lifted or\n * inverted for this async subtree, by name — set only by\n * `Model.withTrashed(fn)` / `Model.onlyTrashed(fn)`.\n *\n * Keyed by model name rather than class because a nested relation read\n * resolves its target through the registry by name, and the block has to\n * reach those reads too. A fresh map per block, never mutated, so an inner\n * block cannot leak its entry back into the enclosing one.\n */\n trashed?: ReadonlyMap<string, TrashedMode>;\n /**\n * Postgres session settings for this subtree (#1158), set by\n * `DB.withSettings`: applied with `set_config(name, value, true)` at the\n * start of every transaction opened here, and of the implicit transaction a\n * single ORM call or `DB.query` gets when none is open. A fresh object per\n * scope, never mutated.\n */\n settings?: Readonly<Record<string, string>>;\n /**\n * What has been applied on `tx` so far, by name. Created by the outermost\n * `withTransaction` and shared by reference with its savepoints, so a\n * `withSettings` block entered inside the transaction applies only what is\n * new and resets it on the way out.\n */\n appliedSettings?: Map<string, string>;\n}\n\n/**\n * How a soft-deleted model's trashed rows are treated: `\"with\"` includes them,\n * `\"only\"` reads nothing else. Absent means the default — they are hidden.\n */\nexport type TrashedMode = \"with\" | \"only\";\n\n/**\n * Work deferred to a transaction's commit.\n *\n * Awaited when it is drained, and its rejection is caught there: a callback is\n * a side effect that the transaction is not waiting on and cannot be told\n * about, so the only thing left to do with a failure is report it.\n *\n * Not exported: a caller passes a lambda and never names this, and an export\n * nothing outside this file uses is what `orm/architecture.test.ts` is pointed\n * at. The declaration emit carries it along regardless, so `OrmScope` stays\n * readable from a `.d.ts`.\n */\ntype AfterCommitCallback = () => void | Promise<void>;\n\n/**\n * One ambient scope for the ORM, not one per feature.\n *\n * Transactions (iteration 5) and system access (iteration 6) are both\n * \"something is true for this async subtree and every query in it\", so they\n * share a store rather than minting a second `AsyncLocalStorage` each. The\n * inventory note in `kernel/context.ts` sets the bar for adding one; two\n * booleans-worth of ORM state does not clear it.\n */\nexport const ormContext = new AsyncLocalStorage<OrmScope>();\n\n/**\n * The open transaction, or `undefined` outside one. This is what `Model.$exec`\n * consults to decide which connection a statement runs on.\n *\n * Exported as the escape hatch for code that genuinely needs the handle — a raw\n * query that must join the surrounding transaction, say. **Do not store what it\n * returns.** Bun's handle stays callable after its `begin` resolves: queries on\n * it then run on the pooled connection, outside any transaction, and succeed.\n * Verified against both dialects, and it is the reason `Model.transaction`'s\n * callback takes no argument.\n */\nexport function currentTransaction(): TransactionSQL | undefined {\n return ormContext.getStore()?.tx;\n}\n\n/**\n * The connection every query in this scope runs on unless it names another.\n *\n * `\"default\"` outside any scope, so callers get a name rather than a\n * `string | undefined` to normalise themselves — the store keeps it absent,\n * which is not the same distinction and is nobody else's business.\n */\nexport function currentConnectionName(): string {\n return ormContext.getStore()?.connection ?? DEFAULT_CONNECTION;\n}\n\n/**\n * Run `fn` with `name` as the ambient connection.\n *\n * Merged into the current scope rather than replacing it, exactly as\n * `runAsSystem` and `runAsUser` are: naming a connection must not drop an open\n * transaction handle or re-enable policies underneath it.\n *\n * Deliberately absent from `orm/index.ts`, so it is not part of what an\n * application can reach — `Model.on(name)` and `DB.connection(name)` are the\n * two doors, and both funnel through here so that a nested relation read,\n * which resolves its own class out of the registry and calls its `$exec`,\n * inherits the connection without anything having to pass it along.\n */\nexport function runOnConnection<T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n if (currentConnectionName() === name) return fn();\n\n // ENTERING A CONNECTION IS WHERE THE CROSS-CONNECTION CHECK BELONGS, not at\n // each door — and it has to be *here*, before the scope is entered, because\n // entering it is what makes the check impossible afterwards.\n //\n // The scope carries `tx` and `connection` together, so overwriting the name\n // while an open handle stays in place produces a store that says \"a\n // transaction on analytics\" while holding the *default* connection's handle.\n // Every check downstream then agrees with itself and the statement runs on\n // the wrong connection's transaction. `Model.save` found this: it routes to\n // the row's own connection, so it is the one caller that switches connections\n // with a transaction already open.\n assertConnectionUsable(name);\n\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n },\n fn,\n );\n}\n\n/**\n * Refuse a statement that names one connection while a transaction is open on\n * another.\n *\n * The check `withTransaction`'s single-connection note asked for, and the\n * reasoning for refusing rather than routing is on\n * `CrossConnectionTransactionError`. Both doors call it — `Model.$exec` for\n * every model operation, `DB` for a raw fragment — because either one alone\n * leaves the other free to straddle the two connections, and a raw `DB.execute`\n * escaping a transaction is the more damaging of the two.\n *\n * Only ever fires on a query that *names* a connection: an unqualified one\n * resolves to the ambient name, which is the transaction's own.\n */\nexport function assertConnectionUsable(name: string): void {\n const store = ormContext.getStore();\n if (store?.tx === undefined) return;\n\n const open = store.connection ?? DEFAULT_CONNECTION;\n if (open === name) return;\n\n throw new CrossConnectionTransactionError(open, name);\n}\n\n/**\n * Hold `callback` until the open transaction commits, and say whether that\n * happened.\n *\n * `false` means there was nothing to wait for — no transaction is open, or the\n * scope was entered by hand rather than by `withTransaction` — and the caller\n * must run the work itself, now. That return value is the whole contract: a\n * caller that ignores it turns \"no transaction here\" into a side effect queued\n * on a list nothing will ever drain, which is a dispatch that silently never\n * happens.\n *\n * `true` means the callback is on the outermost scope's list and will run after\n * `begin` resolves, outside the transaction, whatever the caller does next. It\n * will not run at all if the transaction rolls back, or if a savepoint it was\n * registered inside rolls back — both of which are the point.\n *\n * Nothing here is ordered against anything but the other deferred callbacks:\n * they run in registration order, one at a time, after the commit round-trip.\n */\nexport function deferUntilCommit(callback: AfterCommitCallback): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return false;\n\n // Async work started inside a transaction and not awaited by it — a sync\n // listener still awaiting, an un-awaited emit — can reach here after the\n // transaction settled, through a scope that still carries its handle and its\n // list. Pushing then would queue onto a list already drained (or discarded),\n // and the work would silently never run. A committed list answers \"run it\n // now\"; a rolled-back one keeps the promise that nothing runs.\n const settled = settledLists.get(store.afterCommit);\n if (settled === \"committed\") return false;\n if (settled === \"rolled_back\") return true;\n\n store.afterCommit.push(callback);\n return true;\n}\n\n/**\n * How each outermost transaction's after-commit list ended, once it has. Keyed\n * by the list itself, which every savepoint and every lingering async scope of\n * that transaction shares by reference.\n */\nconst settledLists = new WeakMap<AfterCommitCallback[], \"committed\" | \"rolled_back\">();\n\n/**\n * Run `callback` once the open transaction commits, or now when none is open.\n * Never when the transaction rolls back, nor when a savepoint it was\n * registered inside rolls back.\n *\n * The application-facing form of `deferUntilCommit`, exported from `gemi/orm`\n * (#786). The difference is the `false` branch: `deferUntilCommit` hands the\n * \"no transaction\" case back to the caller, who must remember to run the work\n * itself, and this runs it. A caller that wants a side effect only once its\n * writes are durable — waking a long-poll, notifying another process — has\n * nothing left to get wrong.\n *\n * Inside a transaction the callback joins the same list `static afterCommit`\n * events use, so it is drained after `begin` resolves, outside the\n * transaction, in registration order with them.\n *\n * The returned promise resolves once the callback has run (no transaction) or\n * been queued (inside one). It never rejects: a callback that throws is\n * reported on stderr, as a deferred one is at the drain, so a caller that does\n * not await — the usual case — cannot leave an unhandled rejection behind, and\n * the two branches fail the same way. A sync callback outside a transaction\n * runs before this returns.\n */\nexport function afterCommit(\n callback: () => void | Promise<void>,\n): Promise<void> {\n if (deferUntilCommit(callback)) return Promise.resolve();\n\n const report = (error: unknown) => {\n console.error(\n `An after-commit callback threw. No transaction was open, so it ran ` +\n `immediately.`,\n error,\n );\n };\n try {\n return Promise.resolve(callback()).catch(report);\n } catch (error) {\n report(error);\n return Promise.resolve();\n }\n}\n\n/**\n * Record that a statement run on `handle` failed, when `handle` is the open\n * transaction's. See `OrmScope.statementFailed`. @internal\n */\nexport function noteFailedStatement(handle: unknown): void {\n const store = ormContext.getStore();\n if (store?.tx !== undefined && store.tx === handle && store.statementFailed) {\n store.statementFailed.value = true;\n }\n}\n\n/**\n * Make the open transaction's commit depend on `write`, a statement issued on\n * its handle: the transaction does not commit until `write` settles, and\n * rolls back — rejecting with `TransactionDependencyError` — if it rejected.\n *\n * For a write the caller may not await. A queued listener's dispatch never is\n * (`EventManager` pushes it and moves on), and on Postgres a statement that\n * fails aborts the whole transaction: every statement after it is refused and\n * Bun's `COMMIT` quietly becomes a rollback. Without this, the callback's\n * promise resolved, `begin` resolved, and the rows the caller wrote were gone\n * with nothing to say so. MySQL does not abort on a failed statement, and is\n * failed here anyway, so that a joined write means the same thing on both:\n * it commits with the transaction or the transaction does not commit.\n *\n * `false` when there is no transaction to depend on, as for\n * `deferUntilCommit`.\n */\nexport function commitDependsOn(write: Promise<unknown>): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.commitDependsOn === undefined) {\n return false;\n }\n store.commitDependsOn.push(write);\n return true;\n}\n\n/**\n * A write the transaction's commit depended on failed, so the transaction —\n * or the savepoint the write was made in — rolled back. `cause` is the write's\n * own error.\n */\nexport class TransactionDependencyError extends Error {\n constructor(cause: unknown) {\n super(\n `A statement this transaction depended on failed after being issued on ` +\n `it, so the transaction rolled back instead of committing: ` +\n `${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"TransactionDependencyError\";\n }\n}\n\n/**\n * Wait for the writes registered from `mark` on, and throw if one failed.\n *\n * Called at the end of a transaction's or savepoint's callback, *inside*\n * `begin`/`savepoint`, so a throw is what makes Bun roll back rather than\n * commit — after `begin` has resolved it is too late to do anything but\n * report. Every write is settled before throwing, so none is still running on\n * the handle when the rollback is issued.\n */\nasync function awaitDependencies(\n writes: Promise<unknown>[],\n mark: number,\n): Promise<void> {\n if (writes.length === mark) return;\n const settled = await Promise.allSettled(writes.slice(mark));\n const failed = settled.find(\n (outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\",\n );\n if (failed) throw new TransactionDependencyError(failed.reason);\n}\n\n/** How deeply nested the current transaction is; `null` outside one. */\nexport function transactionDepth(): number | null {\n const store = ormContext.getStore();\n return store?.tx === undefined ? null : store.depth;\n}\n\n/** Whether policies are suspended for the current async scope. */\nexport function isSystemScope(): boolean {\n return ormContext.getStore()?.system === true;\n}\n\n/**\n * Run `fn` with policies suspended.\n *\n * The escape hatch the deny-by-default rule needs to be usable: a cron tick, a\n * queue worker or a seed script has no user, and under deny-by-default every\n * policied model would refuse it. This makes that intent explicit *at the call\n * site*, which is the property that matters — unscoped access must never be\n * what happens when a user simply fails to turn up.\n *\n * It nests inside a transaction and a transaction nests inside it: the scope is\n * merged rather than replaced, so `asSystem` does not silently drop an open\n * handle.\n */\nexport function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run({ ...current, depth: current?.depth ?? 0, system: true }, fn);\n}\n\n/**\n * How `model`'s trashed rows are treated in this async scope, or `undefined`\n * for the default (hidden). See `OrmScope.trashed`.\n */\nexport function trashedMode(model: string): TrashedMode | undefined {\n return ormContext.getStore()?.trashed?.get(model);\n}\n\n/**\n * Run `fn` with `model`'s soft-delete scope lifted (`\"with\"`) or inverted\n * (`\"only\"`). Merged into the current scope like `runAsSystem`, so it keeps an\n * open transaction, the system flag and the actor — and every other policy.\n */\nexport function runWithTrashed<T>(\n model: string,\n mode: TrashedMode,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n const trashed = new Map(current?.trashed);\n trashed.set(model, mode);\n return ormContext.run(\n { ...current, depth: current?.depth ?? 0, trashed },\n fn,\n );\n}\n\n/** The explicitly-set actor, or `undefined` when none was. */\nexport function currentActor(): { user: unknown } | undefined {\n return ormContext.getStore()?.actor;\n}\n\n/**\n * Run `fn` with policies scoped to `user`, for code with no request to read one\n * from.\n *\n * The counterpart to `runAsSystem`, and the reason that one is not the only\n * escape hatch. A queue worker processing \"send the invoice for organisation 7\"\n * genuinely acts *as somebody*; giving it `asSystem` would suspend policies\n * entirely and leave it hand-scoping every query — which is precisely the\n * unscoped-by-accident failure the deny-by-default rule exists to prevent. The\n * narrow tool should be the easy one.\n *\n * It is also what makes policies testable without reaching into\n * `RequestContext`'s internals.\n *\n * Takes precedence over the request store, so a job that says who it is acting\n * as is not quietly overridden by an ambient request that happens to enclose it.\n *\n * It also **clears `system`**, which is the more surprising half. Acting as a\n * user is strictly narrower than acting as the system, so naming one inside an\n * `asSystem` block has to narrow back — and the spread would otherwise carry\n * `system: true` forward, leaving `$exec` to skip policies entirely while\n * `currentUser()` cheerfully returned the actor. Silently unscoped, from the\n * realistic shape: a worker enters `asSystem` to read its job queue, then\n * narrows to the job's owner for the work itself. The reverse nesting —\n * `asSystem` inside `asUser` — suspends policies, which is what it should do.\n */\nexport function runAsUser<T>(user: unknown, fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n system: false,\n actor: { user: user ?? null },\n },\n fn,\n );\n}\n\n/**\n * The warning threshold in milliseconds, or `null` when the warning is off.\n *\n * `configured` is `database.slowTransactionThreshold` — see `DatabaseConfig`.\n * It arrives as a value rather than being read from here so that this file\n * keeps knowing nothing about the container: `withTransaction` is reachable\n * with a bare pool, and its tests use one.\n *\n * Exported for its own tests. The behaviour worth pinning is the fallback —\n * that a malformed threshold lands on the default rather than disabling — and\n * that cannot be observed through `withTransaction`: \"no warning fired\" is what\n * a disabled warning looks like too, so a behavioural test of it passes just as\n * happily when the fallback is gone. Asserting the number directly is the only\n * form of that test that can fail.\n */\nexport function slowTransactionThreshold(\n configured?: number | false,\n): number | null {\n // Read per call, never cached at module scope. `scripts/build.ts` rewrites\n // `process.env.NODE_ENV` to `Bun.env.NODE_ENV` precisely so mode stays a\n // runtime question in the built framework; caching it here would undo that.\n if (process.env.NODE_ENV !== \"development\") return null;\n\n // The one way to switch it off, and it has to be spelled. Everything else\n // falls back, so the warning is never lost to a mistyped value — only to an\n // explicit `false`.\n if (configured === false) return null;\n\n if (configured === undefined) return SLOW_TRANSACTION_THRESHOLD;\n if (!Number.isFinite(configured) || configured <= 0) {\n return SLOW_TRANSACTION_THRESHOLD;\n }\n return configured;\n}\n\n/**\n * Warn, in development only, about a transaction that has been open too long.\n *\n * The risk is structural rather than occasional: an open transaction holds one\n * reserved connection for as long as its callback runs, and nothing about\n * `Model.transaction(async () => { ... })` stops that callback from awaiting a\n * `fetch`, an S3 upload or a slow queue push. Under concurrency that drains the\n * pool, and the symptom — every unrelated query in the process blocking on\n * connection acquisition — names neither the callback nor the I/O in it.\n *\n * A timer rather than measuring elapsed time on the way out, for one reason:\n * the worst case is the transaction that *never* settles (a hung request, a\n * lock wait, a deadlock). After-the-fact measurement is silent for exactly that\n * case; a timer fires while it is still open and still holding the connection.\n *\n * The `Error` is constructed up front and read only if the timer fires — V8\n * formats `.stack` lazily on first access, so an ordinary fast transaction pays\n * for an object allocation and nothing else.\n *\n * The clock starts at the `begin` call, not at the moment a connection is\n * acquired, and stops when `begin` settles rather than when the callback\n * returns — so it spans the pool wait and the commit round-trip as well as the\n * callback. That is deliberate: all three are time this transaction is in\n * flight, and a warning that only covered the callback would stay silent for a\n * transaction stuck waiting on an exhausted pool, which is the exact situation\n * a long transaction elsewhere creates. Hence \"not settled\" rather than \"open\n * for\" — the message must not claim a connection was held for the whole span.\n */\nfunction watchForSlowTransaction(configured?: number | false): () => void {\n const threshold = slowTransactionThreshold(configured);\n if (threshold === null) return () => {};\n\n const site = new Error(\"transaction opened here\");\n\n const timer = setTimeout(() => {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A database transaction has not settled after ${threshold}ms. It ` +\n `reserves a pooled connection until it does — check for network or ` +\n `filesystem I/O inside the callback, and move it outside the ` +\n `transaction if you find any.\\n${stack}\\n` +\n `(development only; set database.slowTransactionThreshold to change ` +\n `the threshold, or false to switch this off)`,\n );\n }, threshold);\n\n // Otherwise the warning timer is itself a reason the process stays alive,\n // which would turn a diagnostic into a hang in short-lived commands and\n // scripts.\n timer.unref?.();\n\n return () => clearTimeout(timer);\n}\n\n/**\n * Runs what a committed transaction deferred, outside the transaction it was\n * deferred by.\n *\n * `outside` is the scope that was ambient before `begin` — an `asSystem` block,\n * a named connection, or nothing at all — and re-entering it explicitly is the\n * guarantee rather than a tidy-up. The alternative is relying on where a `.then`\n * happens to have captured its context, and the failure that produces is the\n * one the whole feature is about: a listener that runs \"after commit\" while\n * still holding the closed transaction's handle joins nothing, because Bun's\n * handle stays callable and simply runs on the pool. So the scope is rebuilt\n * with `tx` and the drained list cleared, and a listener that opens its own\n * transaction gets a real one.\n *\n * Errors are caught per callback and the next one still runs, for the reason\n * the event subsystem catches per listener: these are independent side effects\n * whose order came from a filesystem walk. And the transaction is not failed by\n * one — it committed, the database kept the rows, and reporting a rejection to\n * the caller would have it roll back or retry work that is already durable.\n * stderr is all that is left, and it is enough: the caller has no decision to\n * make here.\n *\n * The transaction's own promise does not resolve until this has finished, which\n * is the one thing about `afterCommit` that a caller can feel. Deliberate: the\n * alternative is a floating promise whose rejection nobody sees and whose work\n * a short-lived process — a command, a seed — exits out from under.\n */\nasync function drainAfterCommit(\n callbacks: AfterCommitCallback[],\n outside: OrmScope | undefined,\n): Promise<void> {\n if (callbacks.length === 0) return;\n\n await ormContext.run(\n {\n ...outside,\n tx: undefined,\n afterCommit: undefined,\n commitDependsOn: undefined,\n depth: outside?.depth ?? 0,\n },\n async () => {\n for (const callback of callbacks) {\n try {\n await callback();\n } catch (error) {\n console.error(\n `An after-commit callback threw. The transaction it was waiting ` +\n `on had already committed and stays committed, and the ` +\n `callbacks after it still ran.`,\n error,\n );\n }\n }\n },\n );\n}\n\n/**\n * Run `fn` inside a transaction, entering the ambient scope for its whole async\n * subtree.\n *\n * The single implementation behind both `Model.transaction` and\n * `DB.transaction`, so the two cannot become transaction systems that ignore\n * each other: a `Model.create` inside a `DB.transaction` joins it, and a raw\n * `DB.sql` inside a `Model.transaction` can join it through\n * `currentTransaction()`.\n *\n * Nesting becomes a savepoint. Not a preference — Bun refuses the alternative\n * outright (`cannot call begin inside a transaction use savepoint() instead`),\n * and a savepoint is the semantics worth having anyway: an inner failure rolls\n * back to it and leaves the outer transaction usable, which a caller that\n * catches can rely on. Verified on SQLite and Postgres.\n *\n * Note Bun hands the savepoint callback the *same* handle object as the outer\n * transaction (`sp === tx`), so the depth counter is the only thing that\n * actually changes on the way in. The callback's argument is still what gets\n * stored, so this keeps working if that ever stops being true. The cast is\n * because Bun types a savepoint handle as plain `SQL` — without `savepoint` on\n * it — while the runtime object does carry the method, which is what makes\n * three levels of nesting work.\n *\n * Anything `deferUntilCommit` queued is drained once `begin` resolves, outside\n * the transaction and only on the outermost call — a savepoint has committed\n * nothing durable, so draining there would run work that a later rollback of\n * the enclosing transaction was meant to have prevented. See `drainAfterCommit`\n * for what that costs the caller.\n *\n * In development, an outermost transaction that stays open past\n * `options.slowTransactionThreshold` (2s by default, `false` to disable) warns\n * — see `watchForSlowTransaction`. Nothing here *prevents* a long transaction;\n * the warning exists because the cost of one is paid by unrelated queries\n * elsewhere in the process, which makes it hard to trace back.\n *\n * The threshold is passed in rather than read from `app(DatabaseManager)` here.\n * Every caller already holds the manager — it is where `pool` came from — and\n * taking it as an argument keeps this file free of the container, so a bare\n * `SQL` is still enough to call it. Its tests rely on that.\n *\n * `options.connection` is the name `pool` belongs to, and follows the same rule\n * for the same reason: the pool cannot be asked what it is called. Passing it\n * is what lets a nested `withTransaction` tell \"the same connection, so take a\n * savepoint\" from \"a different one, so refuse\" — omitting it means the default\n * connection, which is what a two-argument call always meant.\n *\n * The return type is asserted rather than inferred for one reason worth\n * knowing: Bun's `begin` unwraps a callback that resolves to an *array of\n * promises*, awaiting each. So `Model.transaction(async () => [a, b])` where\n * `a` and `b` are promises resolves to their values, not to the promises. That\n * is Bun's behaviour and is left alone; it is only surprising if unmentioned.\n */\nexport function withTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options?: {\n slowTransactionThreshold?: number | false;\n connection?: string;\n /**\n * Leave the scope's `settings` (#1158) to `fn`, which applies them with\n * `applyTransactionSettings()` after statements that have to come first\n * (`SET TRANSACTION READ ONLY`).\n */\n deferSettings?: boolean;\n /**\n * The connection's dialect. On `\"sqlite\"` an outermost transaction\n * queues behind the one already open on the same pool (#1362); see\n * `queuedOnSqlite`.\n */\n dialect?: string;\n },\n): Promise<T> {\n const current = ormContext.getStore();\n\n // THE SINGLE-CONNECTION ASSUMPTION, WHICH IS NOW CHECKED RATHER THAN PINNED.\n //\n // The savepoint branch below ignores `pool` entirely. That was correct while\n // there was one `DatabaseManager` and one `SQL` — the ambient handle and\n // whatever pool the caller passed were necessarily the same database — and\n // the note that stood here said what would happen when a second connection\n // became configurable (#327): a `DB.transaction` on B inside a\n // `Model.transaction` on A would savepoint on **A** and hand the callback A's\n // handle, so statements landed in the wrong database with no error at all.\n //\n // So the name is compared before the branch is taken, and a mismatch raises.\n // Refusing is the whole answer rather than half of one — there is no way to\n // make one transaction span two pools, and the alternatives are covered on\n // `CrossConnectionTransactionError`.\n //\n // A caller that passes no `connection` is treated as naming the default,\n // which is what `withTransaction(pool, fn)` meant before this argument\n // existed.\n const name = options?.connection ?? DEFAULT_CONNECTION;\n assertConnectionUsable(name);\n\n // `current?.tx` rather than `current`: since iteration 6 a scope can exist\n // with no open transaction — `Model.asSystem` enters one — and a savepoint\n // needs an actual handle, not merely a store.\n if (current?.tx) {\n // WHERE THE SHARED AFTER-COMMIT LIST IS PUT RIGHT.\n //\n // The savepoint's scope is a spread of this one, so it appends to the\n // transaction's list rather than to a list of its own — which is what makes\n // \"the outer transaction rolled back, so nothing runs\" free. The case that\n // is not free is this one: the savepoint rolls back and the transaction\n // goes on to commit. Its entries have to go, or a dispatch made inside a\n // block the database threw away runs anyway, which is the same wrong answer\n // as before with an extra step.\n //\n // A mark on the way in and a truncate on the way out, rather than tagging\n // each entry with its depth and dropping everything at or below the failing\n // one. Depth cannot tell two *siblings* apart: a savepoint that committed\n // and one that rolled back both left entries at the same depth, adjacent in\n // the list, and dropping by depth would discard the committed sibling's\n // work as well. The index is exact because the ORM issues one statement at\n // a time on a transaction handle — see `OrmScope.tx` — so nothing appends\n // between the mark and the failure but this savepoint's own subtree.\n const deferred = current.afterCommit;\n const mark = deferred?.length ?? 0;\n // The same mark for the writes the commit depends on. The savepoint waits\n // for its own before it releases, so one that failed rolls back only the\n // savepoint — which a caller that catches can survive, exactly as it\n // survives a statement that threw inside it — and is then forgotten\n // rather than failing the transaction a second time.\n const dependencies = current.commitDependsOn;\n const dependencyMark = dependencies?.length ?? 0;\n\n return current.tx\n .savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n async () => {\n const result = await fn(nested);\n if (dependencies) {\n await awaitDependencies(dependencies, dependencyMark);\n }\n return result;\n },\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\n if (dependencies) dependencies.length = dependencyMark;\n throw error;\n }) as Promise<T>;\n }\n\n if (options?.dialect === \"sqlite\") {\n return queuedOnSqlite(pool, (release) => openTransaction(pool, fn, options, current, name, release), options);\n }\n return openTransaction(pool, fn, options, current, name);\n}\n\n/**\n * The transactions waiting on each SQLite pool, as the promise the last one\n * queued settles (#1362). Bun's SQLite client runs every statement on one\n * connection, where a second `BEGIN` while a transaction is open fails with\n * \"cannot start a transaction within a transaction\". SQLite allows one writer\n * at a time anyway, so queueing changes the order, not the throughput.\n */\nconst sqliteQueues = new WeakMap<SQL, Promise<void>>();\n\n/**\n * A transaction on a SQLite pool waited, in the queue, for one it is itself\n * inside (#1362). It would wait forever: the open transaction can't commit\n * until this one, which it is waiting on, has run.\n *\n * Thrown, rather than hung, when a transaction that isn't nested through the\n * ORM's scope starts from inside an open one on the same connection, and is\n * still waiting on it 5 seconds later: a raw\n * `sql.begin` (a store's), or code that deliberately left the transaction's\n * ORM scope while still awaited by it (an in-process API call or channel\n * message, `ormContext.exit`). Run that work after the commit\n * (`afterCommit`), or inside the transaction, where it becomes a savepoint.\n */\nexport class TransactionQueueDeadlockError extends Error {\n constructor() {\n super(\n \"A SQLite transaction started from inside an open transaction on the same connection, \" +\n \"outside its scope (a raw `begin`, or an in-process call that left the transaction's scope \" +\n \"while the transaction waits on it). SQLite runs one transaction per connection, so it \" +\n \"would wait for the transaction that waits on it. Run it after the commit (`afterCommit`), \" +\n \"or inside the transaction.\",\n );\n this.name = \"TransactionQueueDeadlockError\";\n }\n}\n\n/** The transaction each SQLite pool's queue is running now: its token. */\nconst queueHolders = new WeakMap<SQL, object>();\n\n/**\n * The queued transactions the current async context is inside of. An ORM\n * scope exit (`ormContext.exit`) doesn't leave this one, which is the point:\n * code that left the ORM scope on purpose is still awaited by the\n * transaction around it.\n */\nconst insideQueued = new AsyncLocalStorage<ReadonlySet<object>>();\n\n/** How long a transaction waits in the queue before development warns. */\nconst QUEUE_WAIT_WARNING_MS = 5_000;\n\n/**\n * `begin` once the transactions queued on `pool` before it have let it go\n * (#1362). Exported for the stores that open their own transactions on an\n * app connection, so every transaction on the pool takes the same turns.\n *\n * `release` lets the next one go. The ORM calls it first thing after COMMIT,\n * before the after-commit callbacks: `begin` resolves only after those have\n * run, and one that opened a transaction would otherwise wait on the very\n * transaction that waits on it. Settling lets it go too, so a caller that\n * ignores `release` (a raw `sql.begin`, whose commit is its settle) holds the\n * queue until its promise settles, including any work it does after its own\n * commit. `begin` must not queue on the same pool again from inside (it\n * would wait for itself; see below).\n *\n * Savepoints never come here: they run inside the open transaction.\n *\n * A transaction queued from inside the one holding the pool (its async\n * context says so) is only a suspected deadlock: async context is inherited\n * by work the transaction never waits for too (a `setTimeout`, an un-awaited\n * call), which just waits its turn. So it queues like any other, and is\n * rejected with `TransactionQueueDeadlockError` only if, after 5 seconds, it\n * is still waiting on a transaction it is inside. In development any\n * transaction still waiting then warns (`slowTransactionThreshold: false`\n * turns the warning off).\n */\nexport function queuedOnSqlite<T>(\n pool: SQL,\n begin: (release: () => void) => Promise<T>,\n options: { slowTransactionThreshold?: number | false } = {},\n): Promise<T> {\n const inside = insideQueued.getStore();\n const token = {};\n let release!: () => void;\n const released = new Promise<void>((resolve) => {\n release = () => {\n if (queueHolders.get(pool) === token) queueHolders.delete(pool);\n resolve();\n };\n });\n const previous = sqliteQueues.get(pool) ?? Promise.resolve();\n sqliteQueues.set(pool, released);\n\n return new Promise<T>((resolve, reject) => {\n let abandoned = false;\n // Only where it can be shown: a stack per transaction is not free.\n const site =\n slowTransactionThreshold(options.slowTransactionThreshold) === null\n ? undefined\n : new Error(\"transaction queued here\");\n const timer = setTimeout(() => {\n // Still waiting. On a transaction it is inside: it can never get its\n // turn, so it fails, and lets the queue go when its turn would come.\n const holder = queueHolders.get(pool);\n if (holder && inside?.has(holder)) {\n abandoned = true;\n reject(new TransactionQueueDeadlockError());\n return;\n }\n if (site) warnQueueWait(site);\n }, QUEUE_WAIT_WARNING_MS);\n timer.unref?.();\n\n void previous.then(() => {\n clearTimeout(timer);\n if (abandoned) {\n release();\n return;\n }\n queueHolders.set(pool, token);\n const result = insideQueued.run(new Set([...(inside ?? []), token]), () => begin(release));\n result.then(release, release);\n result.then(resolve, reject);\n });\n });\n}\n\n/** Development's warning for a transaction still waiting in the queue. */\nfunction warnQueueWait(site: Error): void {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A SQLite transaction has waited ${QUEUE_WAIT_WARNING_MS}ms for the one open on its ` +\n `connection (SQLite runs one at a time per connection). Look for a long transaction, or ` +\n `one that waits on work started outside it.\\n${stack}\\n` +\n `(development only; database.slowTransactionThreshold: false switches it off)`,\n );\n}\n\n/** The outermost half of `withTransaction`: `BEGIN` on `pool`, `fn`, `COMMIT`, then the after-commit list. */\nfunction openTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options: { slowTransactionThreshold?: number | false; deferSettings?: boolean } | undefined,\n current: OrmScope | undefined,\n name: string,\n release?: () => void,\n): Promise<T> {\n // Only the outermost scope is watched. A savepoint reserves no connection of\n // its own — its lifetime is bounded by the transaction it sits in, which is\n // already being timed — so warning per depth would report one slow block as\n // several warnings and point at the innermost frame rather than the one\n // holding the connection.\n const stopWatching = watchForSlowTransaction(\n options?.slowTransactionThreshold,\n );\n\n // Built out here rather than inside the `begin` callback, because the drain\n // below needs it *after* that callback's scope is gone, and reading it off\n // the store then is exactly what is no longer possible.\n // A queued SQLite transaction lets the next one go first thing after its\n // commit, before the app's callbacks (`queuedOnSqlite`).\n const deferred: AfterCommitCallback[] = release ? [release] : [];\n const dependencies: Promise<unknown>[] = [];\n const applied = new Map<string, string>();\n const statementFailed = { value: false };\n\n // The `try` covers a *synchronous* throw from `begin` — a closed pool, say.\n // `.finally` alone would not: it is only attached once `begin` has returned a\n // promise, so a synchronous throw escapes with the timer still armed and\n // eventually warns about a transaction that never opened. `unref` keeps that\n // from holding the process, which makes it cosmetic rather than a leak, but\n // it is the same gap the `.finally` below exists to close.\n try {\n // Spread rather than replace: a `Model.transaction` inside a\n // `Model.asSystem` must not silently re-enable policies for its subtree.\n //\n // The connection goes into the scope alongside the handle, and the pair is\n // what makes the check at the top of this function possible: \"which\n // connection is this transaction on\" has to be answerable from the store,\n // because the handle itself does not say. It is also what makes an\n // unqualified query inside `DB.connection(\"analytics\").transaction(...)`\n // *join* the transaction instead of being refused by it — the query\n // inherits the name rather than defaulting to the hot path.\n return (\n pool\n .begin((tx) =>\n ormContext.run(\n {\n ...current,\n tx,\n depth: 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n // A fresh list per outermost transaction, assigned rather than\n // left to the spread. `current` holds no list today — the drain\n // clears the field before it runs anything — and assigning is\n // what keeps that from being load-bearing: a transaction opened\n // by a callback during a drain gets its own list either way,\n // rather than appending to the array it is being run out of.\n afterCommit: deferred,\n commitDependsOn: dependencies,\n appliedSettings: applied,\n statementFailed,\n },\n async () => {\n if (!options?.deferSettings) {\n await applySettings(tx, current?.settings, applied);\n }\n const result = await fn(tx);\n await awaitDependencies(dependencies, 0);\n // Throws \"current transaction is aborted\" when a failed statement\n // was swallowed on Postgres, so `begin` rolls back and rejects\n // instead of resolving over a `COMMIT` that rolled back.\n if (statementFailed.value) await tx.unsafe(\"select 1\");\n return result;\n },\n ),\n )\n // `finally` and not a `then`/`catch` pair: the connection is released on\n // rollback exactly as it is on commit, so a throwing callback must clear\n // the timer too or every failed transaction leaves a warning armed\n // against a connection that has already gone back to the pool.\n //\n // Before the drain, so that a slow after-commit listener is not\n // reported as a transaction that will not settle. The connection went\n // back to the pool at the commit; the warning is about holding it.\n .finally(stopWatching)\n // Only here, on the fulfilled path. A rejected `begin` rolled back, so\n // the scope and everything queued on it are discarded unread — which is\n // the whole of what `afterCommit` promises.\n .then(\n async (result) => {\n settledLists.set(deferred, \"committed\");\n await drainAfterCommit(deferred, current);\n return result;\n },\n (error: unknown) => {\n settledLists.set(deferred, \"rolled_back\");\n throw error;\n },\n ) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n\n// --- session settings (#1158) ---------------------------------------------\n\n/** A custom Postgres setting's name: at least two dot-separated parts. */\nconst SETTING_NAME = /^[A-Za-z_][A-Za-z0-9_$]*(\\.[A-Za-z_][A-Za-z0-9_$]*)+$/;\n\n/** The value a setting can be given. `null` sets it to the empty string. */\nexport type SessionSettingValue = string | number | boolean | bigint | null;\n\n/**\n * A `withSettings` block tried to give a setting another value than the\n * block around it gave it (#1158). Refused rather than applied, because a\n * nested change would outlive the inner block: `SET LOCAL` survives\n * `RELEASE SAVEPOINT`, so the rest of the outer block would run as the inner\n * tenant.\n */\nexport class SessionSettingConflictError extends Error {\n constructor(\n readonly setting: string,\n readonly outer: string,\n readonly inner: string,\n ) {\n super(\n `DB.withSettings: \"${setting}\" is already \"${outer}\" in an enclosing withSettings block, and a nested block can't change it to \"${inner}\". Open a separate block outside the first one.`,\n );\n this.name = \"SessionSettingConflictError\";\n }\n}\n\n/** The settings of the ambient scope, or `undefined` when there are none. */\nexport function currentSettings(): Readonly<Record<string, string>> | undefined {\n const settings = ormContext.getStore()?.settings;\n return settings && Object.keys(settings).length > 0 ? settings : undefined;\n}\n\n/**\n * `set_config(name, value, true)` on `tx` for every setting not applied yet,\n * in one statement.\n */\nasync function applySettings(\n tx: TransactionSQL,\n settings: Readonly<Record<string, string>> | undefined,\n applied: Map<string, string>,\n): Promise<string[]> {\n if (!settings) return [];\n const pending = Object.entries(settings).filter(([name, value]) => applied.get(name) !== value);\n if (pending.length === 0) return [];\n const calls = pending.map((_, at) => `set_config($${at * 2 + 1}, $${at * 2 + 2}, true)`);\n await tx.unsafe(\n `select ${calls.join(\", \")}`,\n pending.flatMap(([name, value]) => [name, value]),\n );\n for (const [name, value] of pending) applied.set(name, value);\n return pending.map(([name]) => name);\n}\n\n/**\n * Apply the ambient scope's settings on the open transaction, for a caller\n * that opened it with `deferSettings` (`DB.readOnly`). @internal\n */\nexport async function applyTransactionSettings(): Promise<void> {\n const store = ormContext.getStore();\n if (store?.tx && store.appliedSettings) {\n await applySettings(store.tx, store.settings, store.appliedSettings);\n }\n}\n\n/**\n * Runs `fn` with Postgres session settings (#1158): every transaction opened\n * inside starts with `set_config(name, value, true)` for each, and so does the\n * implicit transaction a single ORM call or `DB.query` outside a transaction\n * is given. Inside an open transaction they are applied at once, and the ones\n * this block added are reset to `''` when it returns.\n *\n * Blocks nest: an inner block adds settings, and giving one the outer block\n * set another value throws `SessionSettingConflictError`.\n */\nexport async function runWithSettings<T>(\n settings: Record<string, SessionSettingValue>,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n const outer = current?.settings ?? {};\n const merged: Record<string, string> = { ...outer };\n for (const [name, raw] of Object.entries(settings)) {\n if (!SETTING_NAME.test(name)) {\n throw new Error(\n `DB.withSettings: \"${name}\" is not a custom setting name. Use a prefix and a dot, like \"app.tenant_id\".`,\n );\n }\n const value = raw === null ? \"\" : String(raw);\n if (Object.hasOwn(outer, name) && outer[name] !== value) {\n throw new SessionSettingConflictError(name, outer[name]!, value);\n }\n merged[name] = value;\n }\n const scope: OrmScope = { ...current, depth: current?.depth ?? 0, settings: merged };\n\n const tx = current?.tx;\n const applied = current?.appliedSettings;\n if (!tx || !applied) return ormContext.run(scope, fn);\n\n return ormContext.run(scope, async () => {\n const added = await applySettings(tx, merged, applied);\n const reset = async () => {\n if (added.length === 0) return;\n const calls = added.map((_, at) => `set_config($${at + 1}, '', true)`);\n await tx.unsafe(`select ${calls.join(\", \")}`, added);\n for (const name of added) applied.delete(name);\n };\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n // The transaction may already be failing (an aborted transaction\n // refuses every statement): the rollback resets them anyway, and the\n // caller sees the original error.\n await reset().catch(() => {});\n throw error;\n }\n await reset();\n return result;\n });\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";yDACA,4BAAS,oBAgLF,IAAM,EAAa,IAAI,EAavB,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAW,SAAS,GAAG,GAUzB,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAW,SAAS,GAAG,YAAc,EAgBvC,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAW,SAAS,EACpC,GAAI,EAAsB,IAAM,EA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FACvB,EAEF,IAAM,EAAQ,IAAQ,KAAO,GAAK,OAAO,CAAG,EAC5C,GAAI,OAAO,OAAO,EAAO,CAAI,GAAK,EAAM,KAAU,EAChD,MAAM,IAAI,EAA4B,EAAM,EAAM,GAAQ,CAAK,EAEjE,EAAO,GAAQ,EAEjB,IAAM,EAAkB,IAAK,EAAS,MAAO,GAAS,OAAS,EAAG,SAAU,CAAO,EAE7E,EAAK,GAAS,GACd,EAAU,GAAS,gBACzB,GAAI,CAAC,GAAM,CAAC,EAAS,OAAO,EAAW,IAAI,EAAO,CAAE,EAEpD,OAAO,EAAW,IAAI,EAAO,SAAY,CACvC,IAAM,EAAQ,MAAM,EAAc,EAAI,EAAQ,CAAO,EAC/C,EAAQ,SAAY,CACxB,GAAI,EAAM,SAAW,EAAG,OACxB,IAAM,EAAQ,EAAM,IAAI,CAAC,EAAG,IAAO,eAAe,EAAK,cAAc,EACrE,MAAM,EAAG,OAAO,UAAU,EAAM,KAAK,IAAI,IAAK,CAAK,EACnD,QAAW,KAAQ,EAAO,EAAQ,OAAO,CAAI,GAE3C,EACJ,GAAI,CACF,EAAS,MAAM,EAAG,EAClB,MAAO,EAAO,CAKd,MADA,MAAM,EAAM,EAAE,MAAM,IAAM,EAAE,EACtB,EAGR,OADA,MAAM,EAAM,EACL,EACR",
|
|
8
|
-
"debugId": "5AF602F2ECA2FC9964756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|