gemi 0.141.0 → 0.143.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/App.d.ts +4 -3
- package/dist/app/App.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/config.d.ts +24 -5
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/bin/gemi.js +2 -2
- package/dist/bin/gemi.js.map +3 -3
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-s58hbczk.js → chunk-0839f72f.js} +2 -2
- package/dist/{chunk-s58hbczk.js.map → chunk-0839f72f.js.map} +1 -1
- package/dist/{chunk-0c553zfq.js → chunk-0t2ym9ap.js} +3 -3
- package/dist/{chunk-0c553zfq.js.map → chunk-0t2ym9ap.js.map} +1 -1
- package/dist/{chunk-1axhttzr.js → chunk-159c392q.js} +2 -2
- package/dist/{chunk-1axhttzr.js.map → chunk-159c392q.js.map} +1 -1
- package/dist/{chunk-r6thf4ge.js → chunk-1cn7ets3.js} +3 -3
- package/dist/{chunk-r6thf4ge.js.map → chunk-1cn7ets3.js.map} +1 -1
- package/dist/{chunk-kddgfct7.js → chunk-1ed75a7b.js} +3 -3
- package/dist/{chunk-kddgfct7.js.map → chunk-1ed75a7b.js.map} +1 -1
- package/dist/chunk-1rvnk7g8.js +24 -0
- package/dist/{chunk-03qkwjvy.js.map → chunk-1rvnk7g8.js.map} +5 -6
- package/dist/{chunk-98dxtkbt.js → chunk-1skdsmjx.js} +2 -2
- package/dist/{chunk-98dxtkbt.js.map → chunk-1skdsmjx.js.map} +1 -1
- package/dist/{chunk-x4g0r9d3.js → chunk-1w5dnkd1.js} +2 -2
- package/dist/{chunk-x4g0r9d3.js.map → chunk-1w5dnkd1.js.map} +1 -1
- package/dist/{chunk-3wpxqcw7.js → chunk-1x9ghjpt.js} +1 -1
- package/dist/{chunk-vtqvq9ca.js → chunk-20d0n391.js} +2 -2
- package/dist/{chunk-tbhtx2t0.js.map → chunk-20d0n391.js.map} +1 -1
- package/dist/{chunk-y7v30zd8.js → chunk-236be97q.js} +1 -1
- package/dist/{chunk-tghh8r2q.js → chunk-2ra5skyk.js} +2 -2
- package/dist/{chunk-tghh8r2q.js.map → chunk-2ra5skyk.js.map} +1 -1
- package/dist/{chunk-kc2z9z3m.js → chunk-3q7sc68p.js} +2 -2
- package/dist/{chunk-kc2z9z3m.js.map → chunk-3q7sc68p.js.map} +1 -1
- package/dist/{chunk-t7qp951h.js → chunk-5g7m7g4a.js} +3 -3
- package/dist/{chunk-t7qp951h.js.map → chunk-5g7m7g4a.js.map} +1 -1
- package/dist/{chunk-5013raxj.js → chunk-5qfzvnyp.js} +3 -3
- package/dist/{chunk-5013raxj.js.map → chunk-5qfzvnyp.js.map} +1 -1
- package/dist/{chunk-eydahc2f.js → chunk-5xfpqda5.js} +1 -1
- package/dist/{chunk-p131vmpy.js → chunk-63q7ycwt.js} +2 -2
- package/dist/{chunk-p131vmpy.js.map → chunk-63q7ycwt.js.map} +1 -1
- package/dist/{chunk-gy307m19.js → chunk-68f0jpje.js} +2 -2
- package/dist/{chunk-gy307m19.js.map → chunk-68f0jpje.js.map} +1 -1
- package/dist/{chunk-b9d021hx.js → chunk-78bfmwp0.js} +2 -2
- package/dist/{chunk-b9d021hx.js.map → chunk-78bfmwp0.js.map} +1 -1
- package/dist/{chunk-j9hf1jyd.js → chunk-83cvkhzn.js} +2 -2
- package/dist/{chunk-j9hf1jyd.js.map → chunk-83cvkhzn.js.map} +1 -1
- package/dist/{chunk-9yfg4nqq.js → chunk-8ex0y47w.js} +2 -2
- package/dist/{chunk-9yfg4nqq.js.map → chunk-8ex0y47w.js.map} +1 -1
- package/dist/{chunk-me6mmvbq.js → chunk-8ky8cmde.js} +2 -2
- package/dist/{chunk-me6mmvbq.js.map → chunk-8ky8cmde.js.map} +1 -1
- package/dist/{chunk-gp4s95kn.js → chunk-9dkpv8ev.js} +2 -2
- package/dist/{chunk-gp4s95kn.js.map → chunk-9dkpv8ev.js.map} +1 -1
- package/dist/{chunk-v2cv3wcw.js → chunk-9k46m1vf.js} +2 -2
- package/dist/{chunk-v2cv3wcw.js.map → chunk-9k46m1vf.js.map} +1 -1
- package/dist/chunk-9qfd02h8.js +10 -0
- package/dist/{chunk-0540ptgm.js.map → chunk-9qfd02h8.js.map} +4 -4
- package/dist/{chunk-e9eh5k8a.js → chunk-9tgcmx4h.js} +2 -2
- package/dist/{chunk-e9eh5k8a.js.map → chunk-9tgcmx4h.js.map} +1 -1
- package/dist/{chunk-23mcs80p.js → chunk-9xzg05xg.js} +3 -3
- package/dist/{chunk-23mcs80p.js.map → chunk-9xzg05xg.js.map} +1 -1
- package/dist/{chunk-e9xbdgb2.js → chunk-a37shxb1.js} +2 -2
- package/dist/{chunk-e9xbdgb2.js.map → chunk-a37shxb1.js.map} +1 -1
- package/dist/chunk-aw8gj99f.js +4 -0
- package/dist/chunk-aw8gj99f.js.map +10 -0
- package/dist/{chunk-k732d7x5.js → chunk-azd6da5h.js} +2 -2
- package/dist/{chunk-k732d7x5.js.map → chunk-azd6da5h.js.map} +1 -1
- package/dist/{chunk-1fe07ge4.js → chunk-b4jx4fzq.js} +1 -1
- package/dist/chunk-b6mgrrk6.js +5 -0
- package/dist/{chunk-5gkzbhts.js.map → chunk-b6mgrrk6.js.map} +1 -1
- package/dist/{chunk-6zz3kez5.js → chunk-ce9wm3r9.js} +2 -2
- package/dist/{chunk-6zz3kez5.js.map → chunk-ce9wm3r9.js.map} +1 -1
- package/dist/{chunk-t6n490ha.js → chunk-ceb4jcrm.js} +2 -2
- package/dist/{chunk-t6n490ha.js.map → chunk-ceb4jcrm.js.map} +1 -1
- package/dist/{chunk-9b4ypfcw.js → chunk-ej4kf7m5.js} +3 -3
- package/dist/{chunk-9b4ypfcw.js.map → chunk-ej4kf7m5.js.map} +1 -1
- package/dist/{chunk-b3tmkge9.js → chunk-f2e7n064.js} +2 -2
- package/dist/{chunk-b3tmkge9.js.map → chunk-f2e7n064.js.map} +1 -1
- package/dist/{chunk-6qydm38w.js → chunk-f5qdyw45.js} +2 -2
- package/dist/{chunk-6qydm38w.js.map → chunk-f5qdyw45.js.map} +1 -1
- package/dist/{chunk-r1x5ms0y.js → chunk-fpz9e3xx.js} +2 -2
- package/dist/{chunk-r1x5ms0y.js.map → chunk-fpz9e3xx.js.map} +1 -1
- package/dist/{chunk-mj55jdwp.js → chunk-fsem81ec.js} +1 -1
- package/dist/{chunk-b97tpvet.js → chunk-hnsrwr0p.js} +2 -2
- package/dist/{chunk-b97tpvet.js.map → chunk-hnsrwr0p.js.map} +1 -1
- package/dist/{chunk-dptp6ceg.js → chunk-hyhbk12v.js} +2 -2
- package/dist/{chunk-dptp6ceg.js.map → chunk-hyhbk12v.js.map} +1 -1
- package/dist/{chunk-eve0hewa.js → chunk-j2k408xc.js} +3 -3
- package/dist/{chunk-eve0hewa.js.map → chunk-j2k408xc.js.map} +1 -1
- package/dist/{chunk-ct3sgfpj.js → chunk-jmhrpfqn.js} +2 -2
- package/dist/{chunk-ct3sgfpj.js.map → chunk-jmhrpfqn.js.map} +1 -1
- package/dist/{chunk-qdz4dqbf.js → chunk-kaphqnpp.js} +3 -3
- package/dist/{chunk-qdz4dqbf.js.map → chunk-kaphqnpp.js.map} +1 -1
- package/dist/chunk-kkqw8bqg.js +117 -0
- package/dist/{chunk-akahs8fn.js.map → chunk-kkqw8bqg.js.map} +10 -8
- package/dist/{chunk-dzvp8ynr.js → chunk-ktrm6y5j.js} +3 -3
- package/dist/{chunk-dzvp8ynr.js.map → chunk-ktrm6y5j.js.map} +1 -1
- package/dist/{chunk-vp4x2c0k.js → chunk-kzc6bn8n.js} +2 -2
- package/dist/{chunk-vp4x2c0k.js.map → chunk-kzc6bn8n.js.map} +1 -1
- package/dist/{chunk-5aj27bgc.js → chunk-m6t5a0me.js} +2 -2
- package/dist/{chunk-5aj27bgc.js.map → chunk-m6t5a0me.js.map} +1 -1
- package/dist/{chunk-yxhg3wjf.js → chunk-m70hn4eg.js} +2 -2
- package/dist/{chunk-yxhg3wjf.js.map → chunk-m70hn4eg.js.map} +1 -1
- package/dist/{chunk-rw4z3n9b.js → chunk-m8yd59gg.js} +2 -2
- package/dist/{chunk-rw4z3n9b.js.map → chunk-m8yd59gg.js.map} +1 -1
- package/dist/{chunk-b4qh3ywd.js → chunk-maqkrbsb.js} +2 -2
- package/dist/{chunk-b4qh3ywd.js.map → chunk-maqkrbsb.js.map} +1 -1
- package/dist/{chunk-7dwgex81.js → chunk-mfn94b95.js} +2 -2
- package/dist/{chunk-7dwgex81.js.map → chunk-mfn94b95.js.map} +1 -1
- package/dist/{chunk-jrvg80jw.js → chunk-mkw35cz7.js} +2 -2
- package/dist/{chunk-jrvg80jw.js.map → chunk-mkw35cz7.js.map} +1 -1
- package/dist/{chunk-7hdfbp2x.js → chunk-mnmr27wd.js} +2 -2
- package/dist/{chunk-7hdfbp2x.js.map → chunk-mnmr27wd.js.map} +1 -1
- package/dist/{chunk-1cdz01em.js → chunk-n9zycjm1.js} +3 -3
- package/dist/{chunk-1cdz01em.js.map → chunk-n9zycjm1.js.map} +1 -1
- package/dist/{chunk-d0kw04ym.js → chunk-ncb1qtae.js} +2 -2
- package/dist/{chunk-d0kw04ym.js.map → chunk-ncb1qtae.js.map} +1 -1
- package/dist/{chunk-c7ecv545.js → chunk-p57nt0pm.js} +2 -2
- package/dist/{chunk-c7ecv545.js.map → chunk-p57nt0pm.js.map} +1 -1
- package/dist/{chunk-yxjfghq3.js → chunk-p81qeav5.js} +3 -3
- package/dist/{chunk-yxjfghq3.js.map → chunk-p81qeav5.js.map} +1 -1
- package/dist/{chunk-rwrcsfzv.js → chunk-qt6x2r6a.js} +2 -2
- package/dist/{chunk-rwrcsfzv.js.map → chunk-qt6x2r6a.js.map} +1 -1
- package/dist/{chunk-qvtmn7mn.js → chunk-r0z27j6t.js} +2 -2
- package/dist/{chunk-qvtmn7mn.js.map → chunk-r0z27j6t.js.map} +1 -1
- package/dist/{chunk-6d9f4vw0.js → chunk-r567t83k.js} +4 -4
- package/dist/{chunk-6d9f4vw0.js.map → chunk-r567t83k.js.map} +1 -1
- package/dist/{chunk-pfgbkhmm.js → chunk-rezmtdyt.js} +2 -2
- package/dist/{chunk-pfgbkhmm.js.map → chunk-rezmtdyt.js.map} +1 -1
- package/dist/{chunk-apfk702c.js → chunk-rvm5mkwm.js} +2 -2
- package/dist/{chunk-apfk702c.js.map → chunk-rvm5mkwm.js.map} +1 -1
- package/dist/{chunk-eyqsvzej.js → chunk-s29tgy4y.js} +2 -2
- package/dist/{chunk-eyqsvzej.js.map → chunk-s29tgy4y.js.map} +1 -1
- package/dist/{chunk-dje31gme.js → chunk-sa6a0wy1.js} +2 -2
- package/dist/{chunk-dje31gme.js.map → chunk-sa6a0wy1.js.map} +1 -1
- package/dist/{chunk-d1whcvyn.js → chunk-sgwgj2q0.js} +1 -1
- package/dist/{chunk-8r9kna46.js → chunk-t03nda3s.js} +2 -2
- package/dist/{chunk-8r9kna46.js.map → chunk-t03nda3s.js.map} +1 -1
- package/dist/{chunk-tbhtx2t0.js → chunk-t2nsn0r2.js} +2 -2
- package/dist/{chunk-vtqvq9ca.js.map → chunk-t2nsn0r2.js.map} +1 -1
- package/dist/{chunk-7p64zc6a.js → chunk-tkvamktq.js} +2 -2
- package/dist/{chunk-7p64zc6a.js.map → chunk-tkvamktq.js.map} +1 -1
- package/dist/{chunk-8gfgsmxk.js → chunk-v57ndv0h.js} +2 -2
- package/dist/{chunk-8gfgsmxk.js.map → chunk-v57ndv0h.js.map} +1 -1
- package/dist/{chunk-e3y72vzw.js → chunk-wffc5k3m.js} +2 -2
- package/dist/{chunk-e3y72vzw.js.map → chunk-wffc5k3m.js.map} +1 -1
- package/dist/{chunk-pxavt1j3.js → chunk-x0t3t7g3.js} +2 -2
- package/dist/{chunk-pxavt1j3.js.map → chunk-x0t3t7g3.js.map} +1 -1
- package/dist/{chunk-dvwdehnp.js → chunk-y5yac6n1.js} +2 -2
- package/dist/{chunk-dvwdehnp.js.map → chunk-y5yac6n1.js.map} +1 -1
- package/dist/{chunk-ks7msv3e.js → chunk-yjszzjyj.js} +2 -2
- package/dist/{chunk-ks7msv3e.js.map → chunk-yjszzjyj.js.map} +1 -1
- package/dist/{chunk-18y8n1r3.js → chunk-z80v4z8y.js} +2 -2
- package/dist/{chunk-18y8n1r3.js.map → chunk-z80v4z8y.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
- package/dist/http/clientAddress.d.ts +8 -0
- package/dist/http/clientAddress.d.ts.map +1 -0
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/forwardedFor.d.ts +28 -20
- package/dist/server/forwardedFor.d.ts.map +1 -1
- package/dist/server/httpProd.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/broadcast/SocketHub.d.ts.map +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/DomainResolver.d.ts +2 -1
- package/dist/services/router/DomainResolver.d.ts.map +1 -1
- package/dist/services/router/DomainRouter.d.ts +17 -0
- package/dist/services/router/DomainRouter.d.ts.map +1 -1
- package/dist/services/router/RouteServiceProvider.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-03qkwjvy.js +0 -24
- package/dist/chunk-0540ptgm.js +0 -10
- package/dist/chunk-3v4esxbd.js +0 -4
- package/dist/chunk-3v4esxbd.js.map +0 -10
- package/dist/chunk-5gkzbhts.js +0 -5
- package/dist/chunk-akahs8fn.js +0 -117
- /package/dist/{chunk-3wpxqcw7.js.map → chunk-1x9ghjpt.js.map} +0 -0
- /package/dist/{chunk-y7v30zd8.js.map → chunk-236be97q.js.map} +0 -0
- /package/dist/{chunk-eydahc2f.js.map → chunk-5xfpqda5.js.map} +0 -0
- /package/dist/{chunk-1fe07ge4.js.map → chunk-b4jx4fzq.js.map} +0 -0
- /package/dist/{chunk-mj55jdwp.js.map → chunk-fsem81ec.js.map} +0 -0
- /package/dist/{chunk-d1whcvyn.js.map → chunk-sgwgj2q0.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{P as ue}from"./chunk-x4g0r9d3.js";import{Q as w}from"./chunk-yxhg3wjf.js";import{_}from"./chunk-gp4s95kn.js";import"./chunk-me6mmvbq.js";import{aa as l}from"./chunk-jrvg80jw.js";import{nl as o,rl as d}from"./chunk-tbhtx2t0.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-dje31gme.js"),{fromContainerMetadata:c}=await import("./chunk-tghh8r2q.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-tghh8r2q.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-3wpxqcw7.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-j9hf1jyd.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-b9d021hx.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-6qydm38w.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-p131vmpy.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-pfgbkhmm.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
|
|
2
|
+
import{P as ue}from"./chunk-1w5dnkd1.js";import{Q as w}from"./chunk-m70hn4eg.js";import{_}from"./chunk-9dkpv8ev.js";import"./chunk-8ky8cmde.js";import{aa as l}from"./chunk-mkw35cz7.js";import{rl as o,vl as d}from"./chunk-t2nsn0r2.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-sa6a0wy1.js"),{fromContainerMetadata:c}=await import("./chunk-2ra5skyk.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-2ra5skyk.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-1x9ghjpt.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-83cvkhzn.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-78bfmwp0.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-f5qdyw45.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-63q7ycwt.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-rezmtdyt.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=A0B6993784687DCC64756E2164756E21
|
|
@@ -15,6 +15,6 @@
|
|
|
15
15
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => import(\"@aws-sdk/credential-provider-web-identity\").then(({ fromTokenFile }) => fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n})({\n callerClientConfig,\n}).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_STS_WEB_ID_TO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j as g,rj as m}from"./chunk-a37shxb1.js";import{Xk as p}from"./chunk-1ed75a7b.js";import{tl as n}from"./chunk-t2nsn0r2.js";var b={};n(b,{registeredNames:()=>x,register:()=>i,has:()=>S,get:()=>_,clearRegistry:()=>a});var M=new Map;function i(q,z){M.set(q,z)}function S(q){return M.has(q)}function _(q){let z=M.get(q);if(z===void 0)throw new k(q,[...M.keys()]);return z}function x(){return[...M.keys()]}function a(){M.clear()}import{createCipheriv as r,createDecipheriv as e,randomBytes as qq}from"crypto";class Y{static token="encrypter";keys=new Map;currentId;constructor(q={}){for(let[z,J]of Object.entries(q.keys??{})){if(!u.test(z))throw new U(`Encryption key id "${z}" is not valid. Use 1-32 letters, digits, "_" or "-": the id is written into every encrypted value.`);this.keys.set(z,zq(z,J))}if(q.current!==void 0){if(!this.keys.has(q.current))throw new U(`encryption.current is "${q.current}", but encryption.keys has no key by that id (${I(this.keys)}).`);this.currentId=q.current}else if(this.keys.size===1)this.currentId=[...this.keys.keys()][0];else if(this.keys.size>1)throw new U(`encryption.keys has ${this.keys.size} keys (${I(this.keys)}) and no encryption.current to say which one encrypts new values.`)}get configured(){return this.currentId!==void 0}get currentKeyId(){return this.requireCurrent()}encrypt(q){if(typeof q!=="string")throw TypeError(`Encrypter.encrypt takes a string, got ${Jq(q)}. Serialise other values first (JSON.stringify).`);let z=this.requireCurrent(),J=this.keys.get(z),Q=`${j}:${z}`,Z=qq(y),$=r(E,J,Z);$.setAAD(Buffer.from(Q));let X=Buffer.concat([$.update(q,"utf8"),$.final(),$.getAuthTag()]);return`${Q}:${Z.toString("base64url")}:${X.toString("base64url")}`}decrypt(q){let z=D(q);if(!z)throw new N("malformed","The value is not an encrypted envelope.");if(!this.configured)this.requireCurrent();let J=this.keys.get(z.keyId);if(!J)throw new N("unknown_key",`The value was encrypted with key "${z.keyId}", which is not in encryption.keys (${I(this.keys)}). Keep a key configured until encryption:rotate has re-encrypted the values written with it.`);try{let Q=e(E,J,z.iv);return Q.setAAD(Buffer.from(`${j}:${z.keyId}`)),Q.setAuthTag(z.tag),Buffer.concat([Q.update(z.ciphertext),Q.final()]).toString("utf8")}catch{throw new N("invalid",`The value did not authenticate under key "${z.keyId}": it was altered, or encrypted with a different key under the same id.`)}}isEncrypted(q){return D(q)!==null}keyIdOf(q){return D(q)?.keyId??null}needsReencryption(q){return this.keyIdOf(q)!==this.requireCurrent()}requireCurrent(){if(this.currentId===void 0)throw new U("No encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as `encryption` in your Kernel's config. Generate a key with `openssl rand -base64 32`.");return this.currentId}}class U extends Error{constructor(q){super(q);this.name="EncryptionKeyError"}}class N extends Error{reason;column;constructor(q,z){super(z);this.reason=q;this.name="DecryptionError"}}var j="v1",E="aes-256-gcm",f=32,y=12,A=16,u=/^[A-Za-z0-9_-]{1,32}$/,v=/^[A-Za-z0-9_-]+$/;function zq(q,z){if(typeof z!=="string"||z.trim()==="")throw new U(`Encryption key "${q}" is empty. Is the environment variable it reads set?`);let J=z.trim().replace(/^base64:/,""),Q=/^[A-Za-z0-9+/=_-]+$/.test(J)?Buffer.from(J,"base64"):Buffer.alloc(0);if(Q.length!==f)throw new U(`Encryption key "${q}" is not ${f} bytes of base64 (it decodes to ${Q.length}). Generate one with \`openssl rand -base64 32\`.`);return Q}function D(q){if(typeof q!=="string")return null;let z=q.split(":");if(z.length!==4||z[0]!==j)return null;let[,J,Q,Z]=z;if(!u.test(J)||!v.test(Q)||!v.test(Z))return null;let $=Buffer.from(Q,"base64url"),X=Buffer.from(Z,"base64url");if($.length!==y||X.length<A)return null;return{keyId:J,iv:$,ciphertext:X.subarray(0,X.length-A),tag:X.subarray(X.length-A)}}function I(q){return q.size===0?"none configured":[...q.keys()].map((z)=>`"${z}"`).join(", ")}function Jq(q){return q===null?"null":Array.isArray(q)?"an array":`a ${typeof q}`}var h=new WeakMap;function T(q){let z=h.get(q);if(z===void 0)z=Object.values(q.fields).filter((J)=>J.encrypted===!0).map((J)=>J.name),h.set(q,z);return z}function Mq(){let q=new Set,z=[];for(let J of x()){let Q=O(J);if(!Q||q.has(Q.name))continue;q.add(Q.name);for(let Z of T(Q))z.push(`${Q.name}.${Z}`)}return z}function c(){let q=p();if(!q.bound(Y))throw new U("Encrypted columns need an Encrypter, and none is bound in this application. A booted Kernel binds one from the `encryption` config slice; a hand-built Application can bind its own: `application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.");return q.make(Y)}var l=Symbol("gemi.orm.encryptedColumnsRaw");function Nq(q){return{...q,[l]:!0}}function Vq(q){return typeof q==="object"&&q!==null&&q[l]===!0}function Lq(q,z,J){if(!P(J))return;let Q={model:q.name,operation:z};d(q,J,Q,0);for(let Z of["by","_min","_max","_avg","_sum"])if(J[Z]!==void 0)o(q,J[Z],Z,Q);if(J.having!==void 0)B(q,J.having,Q)}var w=64;function d(q,z,J,Q){if(Q>w)return;if(z.where!==void 0)W(q,z.where,"where",J,Q);if(z.cursor!==void 0)W(q,z.cursor,"cursor",J,Q);if(z.orderBy!==void 0)K(q,z.orderBy,J,Q);if(z.distinct!==void 0)o(q,z.distinct,"distinct",J);for(let Z of[z.include,z.select]){if(!P(Z))continue;for(let[$,X]of Object.entries(Z)){if(!P(X))continue;if($==="_count"){if(!P(X.select))continue;for(let[G,F]of Object.entries(X.select)){let H=R(q,G);if(H&&P(F)&&F.where!==void 0)W(H,F.where,"where",J,Q+1)}continue}let C=R(q,$);if(C)d(C,X,J,Q+1)}}}var Qq=["some","every","none","is","isNot"];function W(q,z,J,Q,Z){if(Z>w)return;if(Array.isArray(z)){for(let $ of z)W(q,$,J,Q,Z);return}if(!P(z))return;for(let[$,X]of Object.entries(z)){if(X===void 0)continue;if($==="AND"||$==="OR"||$==="NOT"){W(q,X,J,Q,Z);continue}let C=q.fields[$];if(C){if(C.encrypted===!0&&!t(X))L(q,$,J,Q);continue}let G=R(q,$);if(G){if(!P(X))continue;let F=Object.keys(X).filter((H)=>Qq.includes(H));if(F.length>0)for(let H of F)W(G,X[H],J,Q,Z+1);else W(G,X,J,Q,Z+1);continue}if(P(X)){for(let F of Object.keys(X))if(q.fields[F]?.encrypted===!0)L(q,F,J,Q)}}}function K(q,z,J,Q){if(Q>w)return;if(Array.isArray(z)){for(let Z of z)K(q,Z,J,Q);return}if(!P(z))return;for(let[Z,$]of Object.entries(z)){if(q.fields[Z]?.encrypted===!0)L(q,Z,"orderBy",J);let X=R(q,Z);if(X&&P($)&&!("_count"in $))K(X,$,J,Q+1)}}function o(q,z,J,Q){let Z=typeof z==="string"?[z]:Array.isArray(z)?z.filter(($)=>typeof $==="string"):P(z)?Object.keys(z).filter(($)=>z[$]):[];for(let $ of Z)if(q.fields[$]?.encrypted===!0)L(q,$,J,Q)}function B(q,z,J){if(Array.isArray(z)){for(let Q of z)B(q,Q,J);return}if(!P(z))return;for(let[Q,Z]of Object.entries(z)){if(Q==="AND"||Q==="OR"||Q==="NOT"){B(q,Z,J);continue}if(q.fields[Q]?.encrypted===!0&&!t(Z))L(q,Q,"having",J)}}function t(q){if(q===null)return!0;if(!P(q))return!1;let z=Object.entries(q).filter(([,J])=>J!==void 0);return z.length>0&&z.every(([J,Q])=>(J==="equals"||J==="not")&&Q===null)}function L(q,z,J,Q){throw new m(J,Q.model,Q.operation,`${q.name}.${z} is an encrypted column: each write stores a different random ciphertext, so the database cannot compare, sort or group by it. Only null checks work on it ({ ${z}: null } or { ${z}: { not: null } }). To look a row up by a secret, store a keyed hash of it in a separate column and filter on that.`)}function Yq(q,z,J){let Q=T(q);if(Q.length===0||!P(J))return J;let Z={model:q.name,operation:z},$,X=(F)=>($??=c()).encrypt(F),C=J,G=(F,H)=>{if(H===C[F])return;if(C===J)C={...J};C[F]=H};switch(z){case"create":case"update":case"updateMany":G("data",V(Q,J.data,X,Z));break;case"createMany":G("data",Array.isArray(J.data)?Zq(J.data,(F)=>V(Q,F,X,Z)):V(Q,J.data,X,Z));break;case"upsert":G("create",V(Q,J.create,X,Z)),G("update",V(Q,J.update,X,Z));break}return C}function V(q,z,J,Q){if(!P(z))return z;let Z;for(let $ of q){if(!($ in z))continue;let X=z[$],C=s($,X,J,Q);if(C!==X)(Z??={...z})[$]=C}return Z??z}function s(q,z,J,Q){if(z===void 0||z===null)return z;if(typeof z==="string")return J(z);if(P(z)&&Object.keys(z).length===1&&"set"in z){let Z=z.set;return Z===null||Z===void 0?z:{set:s(q,Z,J,Q)}}throw new g("data",Q.model,Q.operation,`${Q.model}.${q} is an encrypted column and takes a string or null (or { set: string | null }); got ${Cq(z)}.`)}function Zq(q,z){let J;return q.forEach((Q,Z)=>{let $=z(Q);if($!==Q)(J??=[...q])[Z]=$}),J??q}function $q(q,z){let J=T(q);if(J.length===0||z.length===0)return;let Q;for(let Z of z){if(!P(Z))continue;for(let $ of J){let X=Z[$];if(typeof X!=="string")continue;Q??=c();try{Z[$]=Q.decrypt(X)}catch(C){if(C instanceof N)C.column={model:q.name,field:$},C.message=`Could not decrypt ${q.name}.${$}: ${C.message}`;throw C}}}}function Xq(q,z){let J=O(q.model),Q=[];for(let Z of z){if(!P(Z))continue;let $=Z[q.as];if(Array.isArray($))Q.push(...$);else if(P($))Q.push($)}if(Q.length===0)return;if(J)$q(J,Q);for(let Z of q.folded??[])Xq(Z,Q)}function O(q){if(!S(q))return;return _(q).$schema}function R(q,z){let J=q.relations[z];return J?O(J.model):void 0}function P(q){return typeof q==="object"&&q!==null&&!Array.isArray(q)&&!(q instanceof Date)}function Cq(q){if(Array.isArray(q))return"an array";if(q instanceof Date)return"a Date";return`a ${typeof q}`}
|
|
3
|
+
export{i as _i,S as $i,_ as aj,x as bj,b as cj,Y as dj,U as ej,N as fj,T as gj,Mq as hj,c as ij,Nq as jj,Vq as kj,Lq as lj,Yq as mj,$q as nj,Xq as oj};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=3788A0337833F48964756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import { app } from \"../foundation/app\";\nimport {\n DecryptionError,\n Encrypter,\n EncryptionKeyError,\n} from \"../services/encryption/Encrypter\";\nimport { InvalidArgumentError, UnsupportedByDesignError } from \"./errors\";\nimport * as registry from \"./registry\";\nimport type { ModelSchema } from \"./schema\";\n\n/**\n * Encrypted columns: a `String` field marked `/// @gemi.encrypted` in the\n * Prisma schema is stored as an `Encrypter` envelope and read back as the\n * plaintext.\n *\n * Applied in `Model.$exec`, per model, at the two places a value crosses the\n * boundary:\n *\n * - **Writes** encrypt the model's *own* columns in `data` (and an upsert's\n * `create` / `update`). A nested write into a related model is not touched\n * here: every nested write runs through the related model's own `$exec`,\n * which encrypts its own columns, so encrypting it here as well would\n * encrypt it twice.\n * - **Reads** decrypt the model's own rows after shaping. A batched `include`\n * comes back through the child's `$exec` and is already decrypted; a folded\n * (lateral) one never enters it, so the parent decrypts those rows on the\n * child's behalf (`decryptFolded`) — the same split `redactFolded` handles\n * for policies.\n *\n * The schema, not the model class, says which columns are encrypted. That is\n * deliberate: a column that is encrypted when written through `FigmaConnection`\n * and plaintext when written through `FigmaConnectionModel` is not encrypted\n * at rest. The generated base, the subclass and every `Model.on(...)` variant\n * share one `$schema`, so none of them can write the column in the clear.\n *\n * A filter, sort or grouping on an encrypted column is refused: every write\n * stores a different random ciphertext, so the database cannot compare it to\n * anything. A null check is the exception, because a NULL column is stored as\n * NULL.\n */\n\nconst fieldsBySchema = new WeakMap<ModelSchema, readonly string[]>();\n\n/** The schema's encrypted fields, in declaration order. Empty for most models. */\nexport function encryptedFields(schema: ModelSchema): readonly string[] {\n let fields = fieldsBySchema.get(schema);\n if (fields === undefined) {\n fields = Object.values(schema.fields)\n .filter((field) => field.encrypted === true)\n .map((field) => field.name);\n fieldsBySchema.set(schema, fields);\n }\n return fields;\n}\n\n/** `Model.field` for every encrypted column of every registered model. */\nexport function encryptedColumnsInRegistry(): string[] {\n const seen = new Set<string>();\n const columns: string[] = [];\n for (const name of registry.registeredNames()) {\n const schema = schemaOf(name);\n if (!schema || seen.has(schema.name)) continue;\n seen.add(schema.name);\n for (const field of encryptedFields(schema)) columns.push(`${schema.name}.${field}`);\n }\n return columns;\n}\n\n/**\n * The application's `Encrypter`. An application booted without the\n * framework's providers (a test harness that binds only the database) gets a\n * typed error naming the fix rather than a container error.\n */\nexport function currentEncrypter(): Encrypter {\n const application = app();\n if (!application.bound(Encrypter)) {\n throw new EncryptionKeyError(\n \"Encrypted columns need an Encrypter, and none is bound in this \" +\n \"application. A booted Kernel binds one from the `encryption` config \" +\n \"slice; a hand-built Application can bind its own: \" +\n \"`application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.\",\n );\n }\n return application.make(Encrypter);\n}\n\n// --- the internal raw mode ---------------------------------------------------\n\n/**\n * Marks an `$exec` call as reading and writing encrypted columns *as stored*:\n * no decryption of results, no encryption of `data`, and filters on encrypted\n * columns allowed (compared against the envelope). Used by `encryption:rotate`\n * to compare-and-swap one envelope for another. A module-private symbol, like\n * the other `$exec` markers, so an application cannot set it.\n */\nconst RAW = Symbol(\"gemi.orm.encryptedColumnsRaw\");\n\nexport function markEncryptionRaw<T extends object>(options: T): T {\n return { ...options, [RAW]: true };\n}\n\nexport function isEncryptionRaw(options: unknown): boolean {\n return (\n typeof options === \"object\" &&\n options !== null &&\n (options as Record<symbol, unknown>)[RAW] === true\n );\n}\n\n// --- refusing filters --------------------------------------------------------\n\ninterface Origin {\n model: string;\n operation: string;\n}\n\n/**\n * Refuses any argument that would make the database compare, sort or group an\n * encrypted column: `where` (including relation filters into other models),\n * `orderBy`, `distinct`, `cursor`, `groupBy`'s `by` and `having`, the\n * `_min` / `_max` aggregates, and the same arguments nested inside an\n * `include` or `select`.\n *\n * Walked whether or not this model has encrypted columns, because a relation\n * filter or an include reaches other models'.\n */\nexport function assertNoEncryptedFilters(schema: ModelSchema, op: string, args: unknown): void {\n if (!isObject(args)) return;\n const origin: Origin = { model: schema.name, operation: op };\n readArgs(schema, args, origin, 0);\n for (const key of [\"by\", \"_min\", \"_max\", \"_avg\", \"_sum\"]) {\n if (args[key] !== undefined) fieldList(schema, args[key], key, origin);\n }\n if (args.having !== undefined) having(schema, args.having, origin);\n}\n\n/** Generous: relation depth is bounded by `MAX_RELATION_DEPTH` long before this. */\nconst MAX_WALK_DEPTH = 64;\n\nfunction readArgs(schema: ModelSchema, args: Record<string, any>, origin: Origin, depth: number) {\n if (depth > MAX_WALK_DEPTH) return;\n if (args.where !== undefined) where(schema, args.where, \"where\", origin, depth);\n if (args.cursor !== undefined) where(schema, args.cursor, \"cursor\", origin, depth);\n if (args.orderBy !== undefined) orderBy(schema, args.orderBy, origin, depth);\n if (args.distinct !== undefined) fieldList(schema, args.distinct, \"distinct\", origin);\n\n for (const projection of [args.include, args.select]) {\n if (!isObject(projection)) continue;\n for (const [key, value] of Object.entries(projection)) {\n if (!isObject(value)) continue;\n if (key === \"_count\") {\n if (!isObject(value.select)) continue;\n for (const [name, count] of Object.entries(value.select)) {\n const target = relationTarget(schema, name);\n if (target && isObject(count) && count.where !== undefined) {\n where(target, count.where, \"where\", origin, depth + 1);\n }\n }\n continue;\n }\n const target = relationTarget(schema, key);\n if (target) readArgs(target, value, origin, depth + 1);\n }\n }\n}\n\nconst RELATION_FILTERS = [\"some\", \"every\", \"none\", \"is\", \"isNot\"];\n\nfunction where(\n schema: ModelSchema,\n node: unknown,\n argument: string,\n origin: Origin,\n depth: number,\n): void {\n if (depth > MAX_WALK_DEPTH) return;\n if (Array.isArray(node)) {\n for (const item of node) where(schema, item, argument, origin, depth);\n return;\n }\n if (!isObject(node)) return;\n\n for (const [key, value] of Object.entries(node)) {\n if (value === undefined) continue;\n\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n where(schema, value, argument, origin, depth);\n continue;\n }\n\n const field = schema.fields[key];\n if (field) {\n if (field.encrypted === true && !isNullCheck(value)) {\n refuse(schema, key, argument, origin);\n }\n continue;\n }\n\n const target = relationTarget(schema, key);\n if (target) {\n if (!isObject(value)) continue;\n const filters = Object.keys(value).filter((name) => RELATION_FILTERS.includes(name));\n if (filters.length > 0) {\n for (const name of filters) where(target, value[name], argument, origin, depth + 1);\n } else {\n where(target, value, argument, origin, depth + 1);\n }\n continue;\n }\n\n // A compound unique key — `provider_providerId: { provider, providerId }`.\n if (isObject(value)) {\n for (const name of Object.keys(value)) {\n if (schema.fields[name]?.encrypted === true) refuse(schema, name, argument, origin);\n }\n }\n }\n}\n\nfunction orderBy(schema: ModelSchema, node: unknown, origin: Origin, depth: number): void {\n if (depth > MAX_WALK_DEPTH) return;\n if (Array.isArray(node)) {\n for (const item of node) orderBy(schema, item, origin, depth);\n return;\n }\n if (!isObject(node)) return;\n for (const [key, value] of Object.entries(node)) {\n if (schema.fields[key]?.encrypted === true) refuse(schema, key, \"orderBy\", origin);\n const target = relationTarget(schema, key);\n if (target && isObject(value) && !(\"_count\" in value)) {\n orderBy(target, value, origin, depth + 1);\n }\n }\n}\n\n/** `distinct`, `by`, and the `_min` / `_max` / `_avg` / `_sum` selections. */\nfunction fieldList(schema: ModelSchema, node: unknown, argument: string, origin: Origin): void {\n const names =\n typeof node === \"string\"\n ? [node]\n : Array.isArray(node)\n ? node.filter((name): name is string => typeof name === \"string\")\n : isObject(node)\n ? Object.keys(node).filter((name) => node[name])\n : [];\n for (const name of names) {\n if (schema.fields[name]?.encrypted === true) refuse(schema, name, argument, origin);\n }\n}\n\nfunction having(schema: ModelSchema, node: unknown, origin: Origin): void {\n if (Array.isArray(node)) {\n for (const item of node) having(schema, item, origin);\n return;\n }\n if (!isObject(node)) return;\n for (const [key, value] of Object.entries(node)) {\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n having(schema, value, origin);\n continue;\n }\n if (schema.fields[key]?.encrypted === true && !isNullCheck(value)) {\n refuse(schema, key, \"having\", origin);\n }\n }\n}\n\n/** `null`, `{ equals: null }`, `{ not: null }` — the only comparisons a ciphertext supports. */\nfunction isNullCheck(value: unknown): boolean {\n if (value === null) return true;\n if (!isObject(value)) return false;\n const entries = Object.entries(value).filter(([, operand]) => operand !== undefined);\n return (\n entries.length > 0 &&\n entries.every(([operator, operand]) => (operator === \"equals\" || operator === \"not\") && operand === null)\n );\n}\n\nfunction refuse(schema: ModelSchema, field: string, argument: string, origin: Origin): never {\n throw new UnsupportedByDesignError(\n argument,\n origin.model,\n origin.operation,\n `${schema.name}.${field} is an encrypted column: each write stores a ` +\n `different random ciphertext, so the database cannot compare, sort or ` +\n `group by it. Only null checks work on it ({ ${field}: null } or ` +\n `{ ${field}: { not: null } }). To look a row up by a secret, store a ` +\n `keyed hash of it in a separate column and filter on that.`,\n );\n}\n\n// --- writes ------------------------------------------------------------------\n\n/**\n * `args` with this model's encrypted columns encrypted, or `args` itself when\n * there is nothing to encrypt. Never mutates the caller's objects: the same\n * `data` may be reused for a second call.\n *\n * Only `data` (and an upsert's `create` / `update`) at this level. Nested\n * relation writes are left as they are; see the note at the top of the file.\n */\nexport function encryptWriteArgs(schema: ModelSchema, op: string, args: any): any {\n const fields = encryptedFields(schema);\n if (fields.length === 0 || !isObject(args)) return args;\n\n const origin: Origin = { model: schema.name, operation: op };\n let encrypter: Encrypter | undefined;\n const encrypt = (value: string) => (encrypter ??= currentEncrypter()).encrypt(value);\n\n let next = args;\n const replace = (key: string, value: unknown) => {\n if (value === next[key]) return;\n if (next === args) next = { ...args };\n next[key] = value;\n };\n\n switch (op) {\n case \"create\":\n case \"update\":\n case \"updateMany\":\n replace(\"data\", encryptData(fields, args.data, encrypt, origin));\n break;\n case \"createMany\":\n replace(\n \"data\",\n Array.isArray(args.data)\n ? mapIfChanged(args.data, (row) => encryptData(fields, row, encrypt, origin))\n : encryptData(fields, args.data, encrypt, origin),\n );\n break;\n case \"upsert\":\n replace(\"create\", encryptData(fields, args.create, encrypt, origin));\n replace(\"update\", encryptData(fields, args.update, encrypt, origin));\n break;\n }\n return next;\n}\n\nfunction encryptData(\n fields: readonly string[],\n data: unknown,\n encrypt: (value: string) => string,\n origin: Origin,\n): unknown {\n if (!isObject(data)) return data;\n let copy: Record<string, unknown> | undefined;\n for (const name of fields) {\n if (!(name in data)) continue;\n const value = data[name];\n const next = encryptValue(name, value, encrypt, origin);\n if (next !== value) (copy ??= { ...data })[name] = next;\n }\n return copy ?? data;\n}\n\nfunction encryptValue(\n field: string,\n value: unknown,\n encrypt: (value: string) => string,\n origin: Origin,\n): unknown {\n if (value === undefined || value === null) return value;\n if (typeof value === \"string\") return encrypt(value);\n // Prisma's `{ set: value }` spelling of a scalar update.\n if (isObject(value) && Object.keys(value).length === 1 && \"set\" in value) {\n const set = value.set;\n return set === null || set === undefined ? value : { set: encryptValue(field, set, encrypt, origin) };\n }\n throw new InvalidArgumentError(\n \"data\",\n origin.model,\n origin.operation,\n `${origin.model}.${field} is an encrypted column and takes a string or ` +\n `null (or { set: string | null }); got ${describe(value)}.`,\n );\n}\n\nfunction mapIfChanged<T>(items: T[], fn: (item: T) => T): T[] {\n let copy: T[] | undefined;\n items.forEach((item, index) => {\n const next = fn(item);\n if (next !== item) (copy ??= [...items])[index] = next;\n });\n return copy ?? items;\n}\n\n// --- reads -------------------------------------------------------------------\n\n/**\n * Decrypts this model's encrypted columns on `rows`, in place. A value that\n * does not decrypt raises `DecryptionError` naming the column — a ciphertext\n * is never handed back as if it were the value.\n */\nexport function decryptRows(schema: ModelSchema, rows: readonly unknown[]): void {\n const fields = encryptedFields(schema);\n if (fields.length === 0 || rows.length === 0) return;\n\n let encrypter: Encrypter | undefined;\n for (const row of rows) {\n if (!isObject(row)) continue;\n for (const field of fields) {\n const value = row[field];\n if (typeof value !== \"string\") continue;\n encrypter ??= currentEncrypter();\n try {\n row[field] = encrypter.decrypt(value);\n } catch (error) {\n if (error instanceof DecryptionError) {\n error.column = { model: schema.name, field };\n error.message = `Could not decrypt ${schema.name}.${field}: ${error.message}`;\n }\n throw error;\n }\n }\n }\n}\n\n/**\n * Decrypts the rows a strategy folded into the parent's statement, which never\n * passed through their own model's `$exec`. Recursive, because the fold is.\n */\nexport function decryptFolded(\n relation: { as: string; model: string; folded?: readonly { as: string; model: string; folded?: readonly unknown[] }[] },\n parents: readonly unknown[],\n): void {\n const schema = schemaOf(relation.model);\n const rows: unknown[] = [];\n for (const parent of parents) {\n if (!isObject(parent)) continue;\n const value = parent[relation.as];\n if (Array.isArray(value)) rows.push(...value);\n else if (isObject(value)) rows.push(value);\n }\n if (rows.length === 0) return;\n if (schema) decryptRows(schema, rows);\n for (const child of relation.folded ?? []) {\n decryptFolded(child as Parameters<typeof decryptFolded>[0], rows);\n }\n}\n\n// --- helpers -----------------------------------------------------------------\n\nfunction schemaOf(model: string): ModelSchema | undefined {\n if (!registry.has(model)) return undefined;\n return registry.get<{ $schema?: ModelSchema }>(model).$schema;\n}\n\nfunction relationTarget(schema: ModelSchema, name: string): ModelSchema | undefined {\n const relation = schema.relations[name];\n return relation ? schemaOf(relation.model) : undefined;\n}\n\nfunction isObject(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof Date);\n}\n\nfunction describe(value: unknown): string {\n if (Array.isArray(value)) return \"an array\";\n if (value instanceof Date) return \"a Date\";\n return `a ${typeof value}`;\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";oPAeA,FAAM,JAAS,IAAI,IAEZ,SAAS,CAAQ,CAAC,EAAc,EAAsB,CAC3D,EAAO,IAAI,EAAM,CAAK,EAGjB,SAAS,CAAG,CAAC,EAAuB,CACzC,OAAO,EAAO,IAAI,CAAI,EAGjB,SAAS,CAAgB,CAAC,EAAiB,CAChD,IAAM,EAAQ,EAAO,IAAI,CAAI,EAC7B,GAAI,IAAU,OACZ,MAAM,IAAI,EAAwB,EAAM,CAAC,GAAG,EAAO,KAAK,CAAC,CAAC,EAE5D,OAAO,EAGF,SAAS,CAAe,EAAa,CAC1C,MAAO,CAAC,GAAG,EAAO,KAAK,CAAC,EAGnB,SAAS,CAAa,EAAS,CACpC,EAAO,MAAM,ECtCf,yBAAS,sBAAgB,iBAAkB,gBA2BpC,MAAM,C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AG,EAAK,KAAK,CAAK,EAE3C,GAAI,EAAK,SAAW,EAAG,OACvB,GAAI,EAAQ,GAAY,EAAQ,CAAI,EACpC,QAAW,KAAS,EAAS,QAAU,CAAC,EACtC,GAAc,EAA8C,CAAI,EAMpE,SAAS,CAAQ,CAAC,EAAwC,CACxD,GAAI,CAAU,EAAI,CAAK,EAAG,OAC1B,OAAgB,EAA+B,CAAK,EAAE,QAGxD,SAAS,CAAc,CAAC,EAAqB,EAAuC,CAClF,IAAM,EAAW,EAAO,UAAU,GAClC,OAAO,EAAW,EAAS,EAAS,KAAK,EAAI,OAG/C,SAAS,CAAQ,CAAC,EAA8C,CAC9D,OAAO,OAAO,IAAU,UAAY,IAAU,MAAQ,CAAC,MAAM,QAAQ,CAAK,GAAK,EAAE,aAAiB,MAGpG,SAAS,EAAQ,CAAC,EAAwB,CACxC,GAAI,MAAM,QAAQ,CAAK,EAAG,MAAO,WACjC,GAAI,aAAiB,KAAM,MAAO,SAClC,MAAO,KAAK,OAAO",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "3788A0337833F48964756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -45,6 +45,6 @@ Say which, and registerModels will leave it alone:
|
|
|
45
45
|
register("${j}", ${z[0]})
|
|
46
46
|
|
|
47
47
|
A class that is only a typed view over the same rows belongs in a module you do not hand to registerModels.`);this.model=j;this.candidates=z;this.name="AmbiguousModelRegistrationError"}}class C extends Error{model;operation;required;limit;dialect;constructor(j,z,B,G,H,I){super(`${j}.${z} would bind ${B} parameters, and the '${H}' driver accepts at most ${G} in one statement. ${I}`+(z==="createMany"?" A createMany over the ceiling is normally split across statements inside one transaction, so reaching this means splitting cannot help: a single row binds more than the driver accepts.":" Splitting is not something this operation can do for you \u2014 one "+"statement has to carry one answer. Narrow the query."));this.model=j;this.operation=z;this.required=B;this.limit=G;this.dialect=H;this.name="ParameterLimitError"}}class D extends Error{model;operation;field;constructor(j,z,B){super(`${j}.${z} is missing a value for '${B}', which is required and has no default.`);this.model=j;this.operation=z;this.field=B;this.name="MissingRequiredValueError"}}class F extends Error{relation;model;constructor(j,z,B){super(`'${j}' is not a relation on model ${z}. `+(B.length>0?`Known relations: ${B.join(", ")}.`:`${z} declares no relations.`));this.relation=j;this.model=z;this.name="UnknownRelationError"}}class b extends Error{model;limit;constructor(j,z){super(`The include tree nests more than ${z} relations deep (at model ${j}). Deeply nested includes are legal, so this is a guard against a generated or malformed argument tree rather than a limit on `+"modelling \u2014 every level costs at least one query.");this.model=j;this.limit=z;this.name="RelationDepthExceededError"}}class P extends Error{model;relation;target;constructor(j,z,B,G){super(`${j}.${z} points at model '${B}', which nothing has registered. The generated artifact and the registry disagree: re-run \`prisma generate\`, and check that app/models/generated/index.ts is imported. `+(G.length>0?`Registered models: ${G.join(", ")}.`:"Nothing is registered at all."));this.model=j;this.relation=z;this.target=B;this.name="UnregisteredRelationTargetError"}}class R extends Error{model;relation;constructor(j,z,B){super(`Cannot resolve how ${j}.${z} joins: ${B} This means `+"app/models/generated is stale or hand-edited \u2014 re-run "+"`prisma generate`.");this.model=j;this.relation=z;this.name="MalformedRelationError"}}class v extends Error{constructor(j,z){super(`No model is registered under the name '${j}'. `+(z.length>0?`Registered models: ${z.join(", ")}.`:"Nothing is registered \u2014 is app/models/generated/index.ts imported?"));this.name="ModelNotRegisteredError"}}class N extends Error{constructor(j){super(`${j} has no $schema. Model subclasses must extend a generated base class from app/models/generated/models.ts.`);this.name="MissingModelSchemaError"}}class Q extends Error{model;operation;constructor(j,z){super(`${j}.${z} was given 'lock' outside a transaction. A row lock lasts until the transaction that took it ends, so outside one it is released as soon as the row is read and protects nothing. Run the read and the writes it guards inside Model.transaction(async () => { ... }).`);this.model=j;this.operation=z;this.name="LockOutsideTransactionError"}}
|
|
48
|
-
export{K as
|
|
48
|
+
export{K as pj,Z as qj,_ as rj,$ as sj,L as tj,M as uj,U as vj,V as wj,y as xj,O as yj,W as zj,E as Aj,S as Bj,T as Cj,x as Dj,A as Ej,C as Fj,D as Gj,F as Hj,b as Ij,P as Jj,R as Kj,v as Lj,N as Mj,Q as Nj};
|
|
49
49
|
|
|
50
|
-
//# debugId=
|
|
50
|
+
//# debugId=07129A59B2555A6264756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Thrown when the compiler is handed an argument it does not implement yet.\n *\n * Every public operation accepts the full Prisma argument type from iteration 1\n * — signatures are final, capability grows underneath them. The price of that is\n * that anything unimplemented has to fail loudly: silently dropping a `take: 10`\n * and returning the whole table is the worst failure mode this ORM has.\n */\nexport class UnsupportedQueryError extends Error {\n constructor(\n public readonly argument: string,\n public readonly model: string,\n public readonly operation: string,\n /**\n * What cannot work, and what to do instead.\n *\n * **Required**, which is the second half of #61 — the first being the\n * `UnsupportedByDesignError` split beside this. It was optional, and the\n * refusals that omitted it were the highest-traffic ones: an argument the\n * operation does not accept, on the path a typo takes. Those said only\n * *that* something was refused, to the reader least likely to know why.\n *\n * Required rather than conventionally-supplied for the reason five other\n * parameters here are — `render`'s `origin`, `changedFields`' `schema`,\n * `RelationExecutor.exec`'s `preScoped`, `resolveLink`'s `operation`,\n * `assertPageArgument`'s reported name: where omitting an argument produces\n * a *worse* result rather than an error, `tsc` is the only thing that keeps\n * a convention. Ninety-five of a hundred call sites already passed one; the\n * five that did not are exactly the ones nobody revisited.\n *\n * `UnknownFieldError` and `UnknownRelationError` set the standard this\n * meets: both enumerate the valid names rather than only rejecting the\n * invalid one.\n */\n detail: string,\n ) {\n super(\n `gemi ORM does not support '${argument}' yet (${model}.${operation}). ` +\n detail,\n );\n this.name = \"UnsupportedQueryError\";\n }\n}\n\n/**\n * An argument the ORM has **decided not to implement**, as opposed to one it has\n * not implemented yet.\n *\n * The distinction is the whole point, and it is a distinction a caller can act\n * on: \"yet\" means wait for a release, \"will not\" means change the code. Sharing\n * one error for both meant `docs/orm.md` could list `omit` under *Not in scope*\n * while the runtime said \"yet\" — a contradiction a reader has no way to\n * resolve, and the one #68 exists to end.\n *\n * A subclass rather than a sibling, so `catch (e) { if (e instanceof\n * UnsupportedQueryError) … }` keeps working for callers that do not care which\n * kind it is.\n */\n/**\n * An argument the ORM **does** implement, given a value it cannot mean.\n *\n * The third category, and the one that made \"yet\" wrong four separate times —\n * #82, #88, #100 and #101 each corrected it at their own call site before #61\n * was found to own the problem. The taxonomy the three classes now draw:\n *\n * not implemented yet UnsupportedQueryError wait for a release\n * decided against UnsupportedByDesignError change the call (#78)\n * implemented, bad value InvalidArgumentError fix the value\n *\n * `take: \"-2\"` is the clearest case. `take` is implemented; `\"-2\"` is not a\n * take. Telling that caller the ORM \"does not support 'take' yet\" is wrong on\n * both halves — it does, and there is nothing to wait for — and it sends them\n * to a changelog when the fix is one character in their own code.\n *\n * **Extends `UnsupportedQueryError`**, so every existing `catch` and every test\n * asserting the base class keeps working. That is the same choice\n * `UnsupportedByDesignError` made, and it is what lets a taxonomy be added to a\n * shipped ORM without a breaking change: the specific classes are for the\n * reader, the base class is for the handler.\n *\n * **Where the taxonomy stops, and why it stops there.** An argument that is not\n * in the grammar at all keeps the base class and its \"yet\" — `{ nope: 1 }`\n * reports \"does not support 'nope' yet\". That is right for half of what reaches\n * that path and wrong for the other half: the same check refuses a typo and a\n * real Prisma argument this ORM has genuinely not implemented, and nothing at\n * that point can tell them apart. Splitting it would mean carrying Prisma's\n * full argument grammar per operation, which is a large amount of duplicated\n * schema for a small gain.\n *\n * What makes it tolerable is the sentence after it. Since #61's other half made\n * `detail` mandatory, that refusal always continues *\"findMany takes include,\n * omit, orderBy, select, skip, take, where\"* — so a caller who typed `nope`\n * learns it is not coming from the very next clause, without the class having\n * to know. Recorded here rather than left to be re-derived, because \"the third\n * class did not cover this one\" is the obvious first reading and it is not the\n * interesting part.\n */\nexport class InvalidArgumentError extends UnsupportedQueryError {\n constructor(\n argument: string,\n model: string,\n operation: string,\n /** What is wrong with the value, and what a good one looks like. */\n reason: string,\n ) {\n super(argument, model, operation, reason);\n this.name = \"InvalidArgumentError\";\n this.message = `Invalid '${argument}' (${model}.${operation}). ${reason}`;\n }\n}\n\nexport class UnsupportedByDesignError extends UnsupportedQueryError {\n constructor(\n argument: string,\n model: string,\n operation: string,\n /** What to use instead. Required — see #61: a refusal owes the caller a next step. */\n reason: string,\n ) {\n super(argument, model, operation, reason);\n this.name = \"UnsupportedByDesignError\";\n this.message =\n `gemi ORM does not implement '${argument}' (${model}.${operation}), ` +\n `and this is a decision rather than a gap. ${reason}`;\n }\n}\n\n/**\n * Thrown when an argument names something that is not a field on the model. A\n * `where` key with no matching field is an error, never a passthrough — that is\n * the rule that keeps user input out of the identifier positions in the SQL.\n */\nexport class UnknownFieldError extends Error {\n constructor(\n public readonly field: string,\n public readonly model: string,\n known: string[],\n ) {\n super(\n `'${field}' is not a field on model ${model}. ` +\n `Known fields: ${known.join(\", \")}.`,\n );\n this.name = \"UnknownFieldError\";\n }\n}\n\n/**\n * Thrown when a column holds something the generated schema says it cannot —\n * an unparseable timestamp, a fractional value in a `BigInt` column, malformed\n * JSON. Every dialect needs it, which is why it lives here rather than beside\n * one of them.\n *\n * It exists so those cases fail rather than decode into a plausible wrong\n * value: `new Date(\"nonsense\")` is an `Invalid Date`, not an error, and it\n * would travel a long way before anyone noticed.\n */\nexport class DecodeError extends Error {\n constructor(\n public readonly field: { column: string; type: string },\n public readonly value: unknown,\n ) {\n super(\n `Could not decode the value ${JSON.stringify(String(value))} from column ` +\n `'${field.column}' as ${field.type}. The column's contents do not match ` +\n `the Prisma schema — was it written by something other than Prisma or ` +\n `the gemi ORM?`,\n );\n this.name = \"DecodeError\";\n }\n}\n\n/**\n * Thrown by the `*OrThrow` operations when the query matched nothing. Prisma\n * raises `NotFoundError` / `P2025` for the same case; the differential harness\n * compares the fact of throwing, not the error type.\n */\nexport class RecordNotFoundError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n ) {\n super(`No ${model} found (${model}.${operation}).`);\n this.name = \"RecordNotFoundError\";\n }\n}\n\n/**\n * The dispatchers' test for a lookup that matched nothing and should be\n * answered with a 404.\n *\n * Matches the name as well as the class for the reason `isPolicyDeniedError`\n * and `isUniqueConstraintError` do: `instanceof` compares against *this*\n * module instance's class object, so a second copy of `gemi/orm` — two\n * versions in one dependency tree, a linked package beside a bundled one —\n * throws an error this would not recognise, and the request would go back to\n * being a 500 carrying the model's name in its body.\n *\n * The name is the identity here, so an application error that calls itself\n * `RecordNotFoundError` is deliberately matched too. That is the same bargain\n * the other two predicates make, and the failure it trades against — a 500\n * where a 404 was meant — is the worse one.\n */\nexport function isRecordNotFoundError(error: unknown): error is RecordNotFoundError {\n if (error instanceof RecordNotFoundError) return true;\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"RecordNotFoundError\"\n );\n}\n\n/**\n * Thrown when a write violates a unique constraint.\n *\n * DECISION — gemi defines its own error rather than mirroring Prisma's codes.\n *\n * Prisma raises `PrismaClientKnownRequestError` with code `P2002` and\n * `meta.target` holding the field names. Mirroring that would ease a migration\n * for code already branching on `P2002`.\n *\n * **The premise this note used to rest on was wrong, and the conclusion is\n * unchanged.** It said \"nothing in this repository does (checked)\", which was\n * true of *this* repository and was never the question — the code that branches\n * on `P2002` lives in the applications the ORM is for. The first real port\n * measured four such guards, every one of them in concurrency-recovery code\n * (catch the collision, re-read, retry), and every one of them silently dead the\n * moment the write moved onto gemi: the `catch` still ran, the condition was\n * false, the recovery did not happen. Nor was the repository itself clean —\n * `templates/saas-starter/app/models/differential.ts:621` branches on `P2002`\n * today, and did when this was written.\n *\n * What the premise was doing was answering \"would anyone notice?\", and the\n * answer is that four people noticed at once. The decision never depended on it.\n * Carrying a `P` code implies the rest of the taxonomy is implemented too:\n * `P2003`, `P2025`, and the fifty others an application might reasonably then\n * expect to catch. Claiming a compatibility surface we have not built is worse\n * than asking the call sites that need it to catch a gemi error instead —\n * *especially* when the code in question is a retry loop, because a\n * compatibility surface that covers `P2002` and not `P2034` fails in exactly\n * the same silent way, one layer further in.\n *\n * A porter reaches for `isUniqueConstraintError` below. `UPGRADE.md` carries\n * the temporary `|| error.code === \"P2002\"` bridge, for a codebase halfway\n * through the move, with the marker that says when to delete it; it is\n * deliberately not exported, because a Prisma code in gemi's permanent surface\n * is the thing this note declined.\n *\n * What the contract does promise is the part that matters: the error is typed,\n * catchable, and names the fields — as *field* names, the way Prisma's\n * `meta.target` does, not as the database columns the driver reported.\n */\nexport class UniqueConstraintError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n /** Field names, mapped back through the schema from the driver's columns. */\n public readonly fields: string[],\n /** The constraint's own name, when the dialect reports one. */\n public readonly constraint?: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Unique constraint violated on ${model}.${operation}` +\n (fields.length > 0 ? ` for ${fields.join(\", \")}` : \"\") +\n (constraint ? ` (constraint '${constraint}')` : \"\") +\n `. A ${model} with those values already exists.`,\n options,\n );\n this.name = \"UniqueConstraintError\";\n }\n}\n\n/**\n * The guard to write in a retry-on-collision `catch`, which is where a\n * `code === \"P2002\"` test almost always was:\n *\n * try {\n * return await Invite.create({ data: { token } })\n * } catch (error) {\n * if (!isUniqueConstraintError(error)) throw error\n * return await Invite.findUniqueOrThrow({ where: { token } })\n * }\n *\n * **Why this is worth shipping rather than telling people to write\n * `instanceof`**, which is the obvious objection and the reason it nearly was\n * not shipped. The second half of the test is the whole of it:\n *\n * error instanceof UniqueConstraintError || error.name === \"UniqueConstraintError\"\n *\n * `instanceof` compares against *this module instance's* class object, so it is\n * false across a duplicate copy of `gemi/orm` — two versions in one dependency\n * tree, a bundled build alongside a linked one, a monorepo package resolving\n * its own. The error is the right error, thrown by the right code, and the\n * guard silently does not fire. That is not a hypothetical: duck-typing rather\n * than importing the class is precisely what the ported application had already\n * done for Prisma's error, for precisely this reason, and shipping a predicate\n * that only does `instanceof` would hand it back the same trap under a new\n * name.\n *\n * So the name is load-bearing rather than a convenience: it is the identity\n * that survives module duplication, which is why every error in this file sets\n * `this.name` explicitly instead of relying on the class name surviving\n * minification.\n *\n * **The narrowing is a claim, and this is what it rests on.** The name branch\n * asserts `UniqueConstraintError` on the strength of a string — a second copy\n * of this module really does carry `model`, `operation` and `fields`, so the\n * claim holds for the case it exists for. An unrelated object named\n * `\"UniqueConstraintError\"` would defeat it, and that is not something that\n * happens by accident.\n *\n * **It deliberately does not match `code === \"P2002\"`.** See the DECISION\n * above: the temporary bridge for a half-ported codebase is in `UPGRADE.md`,\n * where it can carry a delete-me marker, rather than in gemi's permanent\n * surface, where it would have neither.\n */\nexport function isUniqueConstraintError(\n error: unknown,\n): error is UniqueConstraintError {\n if (error instanceof UniqueConstraintError) return true;\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"UniqueConstraintError\"\n );\n}\n\n/**\n * Thrown when a write needs `RETURNING` and the dialect has none.\n *\n * Unreachable on SQLite and Postgres, which both support it. It exists so that\n * the MySQL / MariaDB path is a named gap rather than a wrong answer: the\n * fallback there is `lastInsertRowid` plus a re-select, which is a different\n * statement shape and is not implemented.\n */\nexport class ReturningUnsupportedError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly dialect: string,\n ) {\n super(\n `${model}.${operation} needs RETURNING to report its result, and the ` +\n `'${dialect}' dialect does not support it. The fallback — ` +\n `lastInsertRowid plus a re-select — is not implemented.`,\n );\n this.name = \"ReturningUnsupportedError\";\n }\n}\n\n/**\n * Thrown when a policy denies an operation.\n *\n * Two ways to get here, and the message distinguishes them because the fixes\n * are different: a policy's `before` returned false, or the model is policied\n * and there is no user in scope at all.\n *\n * The second is the deny-by-default rule, and it is the reason this error is\n * loud. A cron tick or a queue worker reading a policied model has no user, and\n * the alternative — treating \"no user\" as \"no policy\" — means the dangerous\n * case is the silent one: a request whose auth middleware was misconfigured\n * would read every tenant's rows rather than failing. So unscoped access is\n * always a decision written at the call site, through `Model.asSystem`.\n */\nexport class PolicyDeniedError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly reason: \"denied\" | \"no-user\" = \"denied\",\n ) {\n super(\n reason === \"no-user\"\n ? `${model}.${operation} is governed by a policy and there is no user ` +\n `in scope. If this is a cron tick, a queue worker or a script, say ` +\n `so at the call site: Model.asSystem(() => ...). Policies are ` +\n `never skipped just because a user failed to turn up.`\n : `${model}.${operation} was denied by ${model}'s policy.`,\n );\n this.name = \"PolicyDeniedError\";\n }\n}\n\n/**\n * The api dispatcher's test for a denial it should answer with a 403. It\n * matches the name as well as the class for the reason\n * `isUniqueConstraintError` does: a second copy of `gemi/orm` throws an error\n * that is not `instanceof` this class, and a denial that failed the test would\n * go back to being a 500 that carries the policy's message.\n */\nexport function isPolicyDeniedError(error: unknown): error is PolicyDeniedError {\n if (error instanceof PolicyDeniedError) return true;\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"PolicyDeniedError\"\n );\n}\n\n/**\n * Thrown when an `update` writes to a column its own policy's `scope` selects on,\n * and the policy has no `onUpdate` saying what that should mean.\n *\n * The shape it catches:\n *\n * scope: (ctx) => ({ organizationId: ctx.user.organizationId })\n * // ...and then\n * User.update({ where: { id }, data: { organizationId: 999 } })\n *\n * The scope did its job — only rows in the caller's own tenant could be selected\n * — and the statement still hands one of them to another tenant. Afterwards the\n * row is outside the scope, so it cannot be read back and cannot be put right by\n * the same caller: a one-way door rather than a visible failure. The usual way in\n * is not malice but mass assignment, a handler forwarding request fields into\n * `data`.\n *\n * This is `assertCreateCovered`'s question asked of the other write. There it is\n * \"you scoped reads but never said what an insert means\"; here it is \"you scoped\n * reads but never said whether an update may move a row out\". Both are answered\n * by writing the hook, including when the answer is \"allow it\" —\n * `onUpdate: (_ctx, data) => data` is a complete and legitimate answer, and\n * saying it out loud is the point.\n *\n * **What it cannot see.** The scope-owned columns are read off the top level of\n * the fragment the policy returned, so `{ organizationId: 7 }` is understood and\n * `{ OR: [...] }` is not — a scope built from combinators is not attributed to\n * any column and an update through it is not checked. Narrowing that would mean\n * either interpreting arbitrary `where` grammar or refusing every update on such\n * a model, and neither is worth it: the guard is a rail on the common shape, not\n * a proof.\n */\nexport class ScopeEscapeError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly fields: readonly string[],\n ) {\n const named = fields.map((field) => `'${field}'`).join(\", \");\n super(\n `${model}.${operation} writes ${named}, which ${model}'s policy also ` +\n `scopes on — so this update can move a row outside the scope that ` +\n `selected it, where the caller can no longer read or repair it.\\n\\n` +\n `Add an onUpdate to that policy. It may reassert the column ` +\n `(data => ({ ...data, ${fields[0]}: ctx.user.${fields[0]} })), reject ` +\n `the write, or allow it explicitly with (_ctx, data) => data — all ` +\n `three are fine, and the point is that the policy says which.`,\n );\n this.name = \"ScopeEscapeError\";\n }\n}\n\n/**\n * Thrown when a model class carries policies but is not the class the registry\n * resolves its name to.\n *\n * This exists because of a cross-tenant leak that shipped past review. The\n * generated `index.ts` registers the *generated* base — `register(\"Account\",\n * AccountModel)` — while an application authors its policy on a subclass:\n *\n * export class Account extends AccountModel {\n * static $policies = [{ scope: (ctx) => ({ organizationId: … }) }]\n * }\n *\n * A root query goes through `Account`, so `policiesFor(this)` finds the policy\n * and the scope applies. A **nested** relation read resolves through the\n * registry, gets `AccountModel`, and walks a prototype chain the policy is not\n * on — so `User.findMany({ include: { accounts: true } })` returned every\n * tenant's accounts. Root queries scoped, nested reads unscoped: exactly the\n * Prisma behaviour policies exist to fix, and silent.\n *\n * Raised at the first query through the unregistered class, naming the one-line\n * fix, because the alternative is data crossing a tenant boundary with nothing\n * to notice it.\n *\n * It fires on a divergence in the resolved policy *chain*, not merely on the two\n * classes differing. A plain subclass that adds no policy of its own inherits\n * the same policy objects in the same order, so a nested read resolving to its\n * parent applies exactly what the root query applied — no divergence, nothing\n * to refuse. An earlier version compared class identity and rejected\n * `class AdminUser extends User {}` for policies it had not written.\n */\nexport class UnregisteredPolicyClassError extends Error {\n constructor(\n public readonly model: string,\n /**\n * Under `carries: \"narrowing\"` this is the *ancestor* — the class the model\n * belongs to — rather than whatever the registry currently holds. The two\n * classes are on one prototype chain there, and which of them is registered\n * is the thing in question, so naming them by their relationship is what\n * makes the message readable.\n */\n public readonly registered: string,\n /** Under `carries: \"narrowing\"`, the descendant: the view that narrows. */\n public readonly queried: string,\n /**\n * Which side carries the policies that would be skipped, and therefore what\n * the author should do about it. Three, because they need three different\n * answers: a missing registration, a query through the wrong class, and a\n * view that should not be competing for the name at all.\n */\n public readonly carries: \"queried\" | \"registered\" | \"narrowing\" = \"queried\",\n ) {\n super(\n carries === \"narrowing\"\n ? `${queried} extends ${registered}, which owns the model '${model}', ` +\n `and carries policies of its own on top of it. A class that ` +\n `narrows an existing model is a view, and the registry holds one ` +\n `class per name — so registering ${queried} would apply its ` +\n `narrowing to every nested read of ${model}, and leaving ` +\n `${registered} registered would skip ${queried}'s policies ` +\n `entirely. Neither is a thing to choose for you.\\n\\n` +\n `Keep the view out of the modules you hand to Kernel.models, and ` +\n `query it directly where you want it:\\n\\n` +\n ` ${queried}.findMany(…) // narrowed, at the call site\\n\\n` +\n `If it is not a view but the model itself, move the policies onto ` +\n `${registered} — the class the model's name resolves to — and ` +\n `${queried} inherits them everywhere.\\n`\n : carries === \"queried\"\n ? `${queried} carries policies but the registry resolves '${model}' to ` +\n `${registered}. Nested relation reads go through the registry, so ` +\n `they would run on ${registered} and skip every policy on ` +\n `${queried} — scoped at the root, unscoped inside an include. ` +\n `Register the class that carries the policy:\\n\\n` +\n ` import { register } from \"gemi/orm\"\\n` +\n ` export class ${queried} extends ${registered} { … }\\n` +\n ` register(\"${model}\", ${queried})\\n`\n : `This query goes through ${queried}, but the registry resolves ` +\n `'${model}' to ${registered}, which carries policies ${queried} ` +\n `does not. Nested relation reads would be scoped and this query is ` +\n `not — the same policy applying to some queries and not others. ` +\n `Query ${registered} instead:\\n\\n` +\n ` ${registered}.findMany(…)\\n\\n` +\n `If skipping policies is intended, say so at the call site — that ` +\n `is what Model.asSystem() is for, and it is the only way to do it ` +\n `that a reader can see.\\n`,\n );\n this.name = \"UnregisteredPolicyClassError\";\n }\n}\n\n/**\n * Thrown when a `$policies` array holds something that is not a usable policy.\n *\n * Every case it covers is refused today — by `tsc`, at the class declaration,\n * with `TS2417`, because `Model` declares `static $policies?: readonly\n * PolicyEntry[]` and `ModelPolicy`'s members are all optional, so a typo'd key\n * trips weak-type detection. This is therefore a guard on the paths that import\n * user code *without* having type-checked it: `registerModels` at boot, and\n * `gemi check models`, whose whole job is to find mistakes in a file somebody is\n * still writing.\n *\n * Two failures, and the second is the one that matters.\n *\n * **A function the ORM cannot get a policy out of.** `resolveEntry` instantiates\n * every function entry with no arguments, and there are two ways that goes\n * wrong. A factory nobody called — `softDeletes` rather than\n * `softDeletes({ field })` — is not constructable at all and reached `new entry`\n * to produce `TypeError: function is not a constructor`. A class that *is*\n * constructable and whose constructor wants an argument gets through that check\n * and dies inside its own body instead, with\n * `TypeError: undefined is not an object (evaluating 'opts.field')`. Both are\n * loud and neither named the model, the index or the file, which on a 79-model\n * app leaves the first question unanswered; the second is the case that survived\n * a first pass at this error, because \"constructable\" is a fact about\n * `[[Construct]]` and says nothing about what the constructor then does.\n *\n * **An entry with no recognised hook.** `{ scopes: … }` and\n * `{ default: { scope: … } }` were accepted in silence: `applyPolicies`\n * dispatches on `before` / `scope` / `onCreate` / `onUpdate` and\n * `applyRedaction` on `redact`, so an entry spelling none of them contributes\n * nothing. The model then carries a visible `$policies` array, passes\n * `gemi check models` as correctly registered, and **reads unscoped** — the same\n * written-believed-not-in-effect shape `UnregisteredPolicyClassError` exists\n * for, arriving through a typo instead of through the registry.\n *\n * The line between *empty but valid* and *malformed* is drawn at \"would this\n * ever run\": an entry with at least one recognised hook that is callable is\n * accepted whatever else it carries, because a factory's return value and a\n * policy class routinely hold configuration and helpers beside the hooks, and\n * refusing unknown *extra* keys would reject code that works. An entry with no\n * callable hook at all is refused, `{}` included — it is indistinguishable from\n * a policy that was meant to do something, and a conditional policy belongs in\n * the array rather than in the entry.\n */\nexport class InvalidPolicyEntryError extends Error {\n constructor(\n /**\n * The class whose **own** `$policies` array holds the entry — the class the\n * author wrote the array on, which is not necessarily the model being\n * queried when the array is on a base.\n */\n public readonly model: string,\n /** The entry's index in that array. */\n public readonly index: number,\n public readonly reason:\n | \"not-a-policy\"\n | \"not-constructable\"\n | \"constructor-threw\"\n | \"no-hooks\"\n | \"hook-not-callable\",\n /** What was found in the entry's place, rendered for a human. */\n public readonly found: string,\n /**\n * The hook names the runtime dispatches on, supplied by `policy.ts` so the\n * list lives beside the code that reads it rather than being restated here.\n */\n hooks: readonly string[],\n /**\n * A key the entry actually spells and the hook it is within one edit of.\n *\n * **The pair, not the hook alone.** An unattributed \"Did you mean `scope`?\"\n * after a list of five keys does not say which of them was read as a\n * misspelling, so a reader who can see that none of them are has no way to\n * dismiss it — and this error is about an authorization rule that is not in\n * effect, where a suggestion followed wrongly costs a rename of something\n * that was never the problem.\n */\n public readonly suggestion?: { key: string; hook: string },\n options?: { cause?: unknown },\n ) {\n const where = `${model}.$policies[${index}]`;\n const named =\n hooks.length > 1\n ? `${hooks.slice(0, -1).join(\", \")} or ${hooks[hooks.length - 1]}`\n : (hooks[0] ?? \"\");\n\n super(\n reason === \"not-a-policy\"\n ? `${where} is ${found}, which is not a policy. An entry is either a ` +\n `policy object — { scope, onCreate, … } — or a class the ORM ` +\n `constructs with no arguments.\\n\\n` +\n `A policy that only sometimes applies belongs in the array rather ` +\n `than in the entry:\\n\\n` +\n ` static $policies = [...(multiTenant ? [tenantScope] : [])]\\n`\n : reason === \"not-constructable\"\n ? `${where} is ${found}, and a function entry is instantiated with ` +\n `no arguments — so an arrow function, a plain function, or a ` +\n `factory that was never called cannot be one.\\n\\n` +\n `If it is a factory, call it:\\n\\n` +\n ` static $policies = [softDeletes({ field: \"deletedAt\" })]\\n`\n : reason === \"constructor-threw\"\n ? `${where} is ${found}\\n\\n` +\n `A class entry is constructed with no arguments. If this one ` +\n `needs some, construct it yourself and put the instance in the ` +\n `array:\\n\\n` +\n ` static $policies = [new TenantPolicy({ field: \"orgId\" })]\\n\\n` +\n `If the constructor reaches for something that is not ready yet, ` +\n `note that it runs on the first query through this model, not at ` +\n `boot.\\n`\n : reason === \"hook-not-callable\"\n ? `${where} has a ${found}, and every hook is called — so this ` +\n `would throw on the first query that reached it rather than ` +\n `doing whatever it was meant to do. Give it a function, or ` +\n `leave the key out.\\n`\n : `${where} has none of ${named}, so it would never run. The ` +\n `model carries a visible $policies array and nothing in it ` +\n `applies to any query — which for a scope means the model ` +\n `reads unscoped. ${found}` +\n (suggestion\n ? ` Is '${suggestion.key}' meant to be \\`${suggestion.hook}\\`?`\n : \"\") +\n `\\n`,\n options,\n );\n this.name = \"InvalidPolicyEntryError\";\n }\n}\n\n/**\n * Thrown when `registerModels` finds two unrelated classes in one module both\n * claiming the same model name.\n *\n * Deriving registration from a module namespace works because the candidates\n * are normally a chain — a generated base, the application's subclass, perhaps\n * a typed view over it — and a chain has a least element to elect. Two classes\n * that extend the same base without extending each other do not: both were\n * written for this model, and only the author knows which one nested reads\n * should run.\n *\n * Refused rather than guessed at, because both guesses are silent. Picking\n * either would scope every `include` of the model by one class's policies while\n * the other's code keeps reading as though its own applied.\n *\n * **\"In one module\" is the exact scope, and the asymmetry is deliberate.**\n * Election happens per module, so two unrelated claims split across *different*\n * modules never meet inside one — the later import simply wins. What catches\n * that is the audit at the end of `registerModels` rather than this error, and\n * only when the two diverge in policies. Two unrelated *unpolicied* claims on\n * one name resolve by import order and nothing reports it, which is tolerable\n * for the same reason it is invisible: with no policies on either, the choice\n * changes no query's scope.\n */\nexport class AmbiguousModelRegistrationError extends Error {\n constructor(\n public readonly model: string,\n public readonly candidates: readonly string[],\n ) {\n const named = candidates.map((candidate) => `'${candidate}'`).join(\", \");\n super(\n `Two classes in one module claim the model '${model}' — ${named} — and ` +\n `neither extends the other, so there is no way to tell which one ` +\n `nested relation reads should run.\\n\\n` +\n `Say which, and registerModels will leave it alone:\\n\\n` +\n ` import { register } from \"gemi/orm\"\\n` +\n ` register(\"${model}\", ${candidates[0]})\\n\\n` +\n `A class that is only a typed view over the same rows belongs in a ` +\n `module you do not hand to registerModels.`,\n );\n this.name = \"AmbiguousModelRegistrationError\";\n }\n}\n\n/**\n * Thrown when a statement would bind more parameters than the driver's wire\n * protocol can carry.\n *\n * Three shapes reach it, all of them scaling with the caller's *data* rather\n * than with the query's shape: `createMany` at `rows × columns`, an `in` list on\n * SQLite (one placeholder per element, and such a list is routinely\n * request-derived), and a to-many `include` on SQLite, which batches an `in`\n * over the parent keys. Both limits are hard and low enough to hit with an\n * ordinary import — Postgres counts parameters in an int16 (65535), SQLite\n * defaults `SQLITE_MAX_VARIABLE_NUMBER` to 32766. Postgres escapes the last two\n * either way: `= any($1)` is one parameter however long the array.\n *\n * Prisma chunks the insert automatically. Doing that here means several\n * statements, which without a transaction is a partially-applied `createMany`\n * on failure — so it waits for iteration 5, and until then this is a named gap\n * rather than a driver error naming neither the model nor the cause. Same\n * treatment as `ReturningUnsupportedError`, for the same reason.\n */\nexport class ParameterLimitError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly required: number,\n public readonly limit: number,\n public readonly dialect: string,\n detail: string,\n ) {\n super(\n `${model}.${operation} would bind ${required} parameters, and the ` +\n `'${dialect}' driver accepts at most ${limit} in one statement. ` +\n `${detail}` +\n (operation === \"createMany\"\n ? ` A createMany over the ceiling is normally split across statements ` +\n `inside one transaction, so reaching this means splitting cannot ` +\n `help: a single row binds more than the driver accepts.`\n : ` Splitting is not something this operation can do for you — one ` +\n `statement has to carry one answer. Narrow the query.`),\n );\n this.name = \"ParameterLimitError\";\n }\n}\n\n/**\n * Thrown when a write omits a column that has no value to fall back on: not\n * supplied, no client-side default, no database default, and not nullable.\n *\n * Raised in the compiler rather than left to the database so the message names\n * the field and the model, instead of surfacing as `NOT NULL constraint failed`\n * with a column name and no context.\n */\nexport class MissingRequiredValueError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n public readonly field: string,\n ) {\n super(\n `${model}.${operation} is missing a value for '${field}', which is ` +\n `required and has no default.`,\n );\n this.name = \"MissingRequiredValueError\";\n }\n}\n\n/**\n * Thrown when an `include` — or a relation-shaped key inside a `select` — names\n * something the model does not declare as a relation.\n */\nexport class UnknownRelationError extends Error {\n constructor(\n public readonly relation: string,\n public readonly model: string,\n known: string[],\n ) {\n super(\n `'${relation}' is not a relation on model ${model}. ` +\n (known.length > 0\n ? `Known relations: ${known.join(\", \")}.`\n : `${model} declares no relations.`),\n );\n this.name = \"UnknownRelationError\";\n }\n}\n\n/**\n * Thrown when an include tree nests deeper than the guard allows.\n *\n * A cyclic include is legal and finite — `user -> accounts -> user` terminates\n * because the caller wrote a finite tree. What this catches is an *unbounded*\n * one: an argument tree built by a loop, or forwarded from a request body, that\n * describes a thousand levels. Under the batched planner every level is at least\n * one query, so the guard is what stops a malformed argument from becoming a\n * self-inflicted denial of service.\n */\nexport class RelationDepthExceededError extends Error {\n constructor(\n public readonly model: string,\n public readonly limit: number,\n ) {\n super(\n `The include tree nests more than ${limit} relations deep (at model ` +\n `${model}). Deeply nested includes are legal, so this is a guard ` +\n `against a generated or malformed argument tree rather than a limit on ` +\n `modelling — every level costs at least one query.`,\n );\n this.name = \"RelationDepthExceededError\";\n }\n}\n\n/**\n * Thrown when a relation names a model the registry does not hold. Every\n * relation in a generated artifact was emitted from a model in the same\n * `schema.prisma`, so this can only mean the artifact and the registry disagree.\n */\nexport class UnregisteredRelationTargetError extends Error {\n constructor(\n public readonly model: string,\n public readonly relation: string,\n public readonly target: string,\n known: string[],\n ) {\n super(\n `${model}.${relation} points at model '${target}', which nothing has ` +\n `registered. The generated artifact and the registry disagree: re-run ` +\n `\\`prisma generate\\`, and check that app/models/generated/index.ts is ` +\n `imported. ` +\n (known.length > 0\n ? `Registered models: ${known.join(\", \")}.`\n : `Nothing is registered at all.`),\n );\n this.name = \"UnregisteredRelationTargetError\";\n }\n}\n\n/**\n * Thrown when a relation is registered on both sides but the two sides do not\n * describe a link the planner can follow: no matching `relationName` on the\n * other model, or a `from` / `to` naming a field that is not there. Like\n * `UnregisteredRelationTargetError`, it means a stale generated artifact — a\n * consistent one cannot produce it.\n */\nexport class MalformedRelationError extends Error {\n constructor(\n public readonly model: string,\n public readonly relation: string,\n detail: string,\n ) {\n super(\n `Cannot resolve how ${model}.${relation} joins: ${detail} This means ` +\n `app/models/generated is stale or hand-edited — re-run ` +\n `\\`prisma generate\\`.`,\n );\n this.name = \"MalformedRelationError\";\n }\n}\n\n/** Thrown when a relation resolves to a model name nothing registered. */\nexport class ModelNotRegisteredError extends Error {\n constructor(name: string, known: string[]) {\n super(\n `No model is registered under the name '${name}'. ` +\n (known.length > 0\n ? `Registered models: ${known.join(\", \")}.`\n : `Nothing is registered — is app/models/generated/index.ts imported?`),\n );\n this.name = \"ModelNotRegisteredError\";\n }\n}\n\n/** Thrown when a model class is used before the generator has given it a schema. */\nexport class MissingModelSchemaError extends Error {\n constructor(className: string) {\n super(\n `${className} has no $schema. Model subclasses must extend a generated ` +\n `base class from app/models/generated/models.ts.`,\n );\n this.name = \"MissingModelSchemaError\";\n }\n}\n\n/**\n * A `lock` asked for outside a transaction.\n *\n * A row lock is held until the transaction that took it ends. Outside one, the\n * statement is its own transaction, so the lock is released the moment the row\n * comes back — before the write it was meant to guard has even been issued. The\n * read would succeed and protect nothing, which is the failure this refuses: the\n * race the lock was written to close stays open, silently.\n *\n * Raised on SQLite too, where the lock itself compiles to nothing, so code that\n * forgot its transaction fails in development rather than first on Postgres.\n */\nexport class LockOutsideTransactionError extends Error {\n constructor(\n public readonly model: string,\n public readonly operation: string,\n ) {\n super(\n `${model}.${operation} was given 'lock' outside a transaction. A row ` +\n `lock lasts until the transaction that took it ends, so outside one it ` +\n `is released as soon as the row is read and protects nothing. Run the ` +\n `read and the writes it guards inside Model.transaction(async () => { ` +\n `... }).`,\n );\n this.name = \"LockOutsideTransactionError\";\n }\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAQO,MAAM,UAA8B,KAAM,CAE7B,SACA,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,aACA,gBAQhB,KAAK,KAAO,yBAEhB,CAGO,MAAM,UAAgC,KAAM,CACjD,WAAW,CAAC,EAAc,EAAiB,CACzC,MACE,0CAA0C,QACvC,EAAM,OAAS,EACZ,sBAAsB,EAAM,KAAK,IAAI,KACrC,0EACR,EACA,KAAK,KAAO,0BAEhB,CAGO,MAAM,UAAgC,KAAM,CACjD,WAAW,CAAC,EAAmB,CAC7B,MACE,GAAG,4GAEL,EACA,KAAK,KAAO,0BAEhB,CAcO,MAAM,UAAoC,KAAM,CAEnC,MACA,UAFlB,WAAW,CACO,EACA,EAChB,CACA,MACE,GAAG,KAAS,yQAKd,EATgB,aACA,iBAShB,KAAK,KAAO,8BAEhB",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "07129A59B2555A6264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{pl as J}from"./chunk-m6t5a0me.js";class L{kernel;onException;constructor(f){this.kernel=new f.kernel,this.kernel.boot.call(this.kernel),this.onException=f.onException??((A)=>{console.error("Unhandled exception in App:",A)})}async waitForBoot(){await this.kernel.waitForBoot()}getComponentTree(){return this.kernel.viewRoutes().componentTree}getFlatComponentTree(){let f=new Set;for(let A of this.kernel.domains().viewDispatchers())for(let C of A.flatComponentTree)f.add(C);return Array.from(f)}devAllowedHosts(){let f=this.kernel.domains();if(!f.resolver)return[];return f.acceptsCustomDomains?!0:[`.${f.resolver.root}`]}sockets(){return this.kernel.sockets.call(this.kernel)}applyTrustedClientIp(f){this.kernel.domains().applyClientIp(f)}getRouteManifest(){return this.kernel.viewRoutes().routeManifest}globallyGated=new WeakMap;async withGlobalMiddleware(f,A,C){let z;try{z=await this.kernel.run.call(this.kernel,()=>this.kernel.globalMiddleware(f))}catch(F){return await C(F)}if(z.refusal)return z.refusal;return this.globallyGated.set(f,z.carried),z.apply(await A(f))}async fetch(f){let A=new URL(f.url);return this.kernel.run.call(this.kernel,async()=>{this.applyTrustedClientIp(f);let C=this.globallyGated.has(f),z=C?null:await this.kernel.globalMiddleware(f),F=C?this.globallyGated.get(f):z.carried;if(z?.refusal)return z.refusal;let H=this.kernel.mcpHttp();if(H){let B=await H.handle(f);if(B)return z?z.apply(B):B}let I=this.kernel.domains(),D=await I.ask(f)??await I.route(f);if(D instanceof Response)return z?z.apply(D):D;if(!D){let B=new Response("Unknown host",{status:404});return z?z.apply(B):B}let G=J(A.pathname)?await D.api.handleApiRequest(f,F):await D.view.handleViewRequest(f,F);if(!z)return G;if(typeof G==="function"){let B=G;return async(...M)=>z.apply(await B(...M))}return z.apply(G)})}dispatchJob(f,A){return this.kernel.run.bind(this.kernel)(()=>{return this.kernel.queue().dispatchJob(f,A)})}shutdown(f){return this.kernel.shutdown(f)}destroy(){this.kernel.destroy()}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}}export{L as Da};
|
|
3
|
+
|
|
4
|
+
//# debugId=846A6586247DF07864756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../app/App.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { Kernel } from \"../kernel\";\nimport type { CarriedContext } from \"../http/requestContext\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport type { SocketHub } from \"../services/broadcast/SocketHub\";\n\n/** What the servers use of the broadcast `SocketHub`. */\nexport type SocketTransport = Pick<\n SocketHub,\n \"matches\" | \"upgrade\" | \"websocket\" | \"socketOptions\" | \"start\" | \"shutdown\"\n>;\n\ninterface AppParams {\n kernel: new () => Kernel;\n onException?: (error: Error) => void;\n}\n\nexport class App {\n private kernel: Kernel;\n public onException?: (error: Error) => void;\n\n constructor(params: AppParams) {\n this.kernel = new params.kernel();\n this.kernel.boot.call(this.kernel);\n this.onException =\n params.onException ??\n ((error: Error) => {\n console.error(\"Unhandled exception in App:\", error);\n });\n }\n\n // Every service this class touches is resolved through a `this.kernel.*`\n // accessor rather than by importing the service class and calling `app()`\n // here. That is deliberate: the built bin (`dist/bin/gemi.js`) bundles its own\n // copy of gemi, while the app's Kernel is loaded from source and resolves\n // `gemi/*` to the source modules — so the two copies have *different*\n // `kernelContext` AsyncLocalStorage instances and different `Application`\n // class objects. A method call on the Kernel executes in the app's copy and\n // reads the app's container; a resolution attempted here would not. Service\n // *tokens* still cross the boundary safely (they are plain strings), which is\n // why `kernel.resolve()` works from either side.\n public async waitForBoot() {\n await this.kernel.waitForBoot();\n }\n\n public getComponentTree() {\n return this.kernel.viewRoutes().componentTree;\n }\n\n // Every host group's views, not just the root's: the servers load these\n // modules up front, and a view only an `admin.` group routes to still has\n // to be among them.\n public getFlatComponentTree() {\n const views = new Set<string>();\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n for (const view of dispatcher.flatComponentTree) {\n views.add(view);\n }\n }\n return Array.from(views);\n }\n\n /**\n * The hosts the dev server's Vite may answer: the `route.domains` root and\n * its subdomains, or any host when custom domains are on, since those are\n * only known to the app's resolver.\n */\n public devAllowedHosts(): true | string[] {\n const domains = this.kernel.domains();\n if (!domains.resolver) {\n return [];\n }\n return domains.acceptsCustomDomains ? true : [`.${domains.resolver.root}`];\n }\n\n /**\n * The broadcast WebSocket endpoint the servers wire into `Bun.serve`, or\n * `null` when the app has no `route.channels`. Typed structurally: the hub\n * belongs to the app's copy of gemi (see the note above).\n */\n public sockets(): SocketTransport | null {\n return this.kernel.sockets.call(this.kernel);\n }\n\n /**\n * Applies `route.domains.trustProxy.clientIpHeader`, or\n * `GEMI_CLIENT_IP_HEADER` for an app without `route.domains`: on a request\n * that carries the proxy's secret, the address that header names becomes\n * the one in `X-Forwarded-For`. The servers call it right after settling\n * `X-Forwarded-For` (`GEMI_TRUST_PROXY`) and before anything reads it —\n * the socket upgrade and the global middleware included. `fetch` calls it\n * too, for a caller that is not one of the servers. Idempotent.\n */\n public applyTrustedClientIp(req: Request) {\n this.kernel.domains().applyClientIp(req);\n }\n\n public getRouteManifest() {\n return this.kernel.viewRoutes().routeManifest;\n }\n\n // Requests `withGlobalMiddleware` already ran the global middleware for, so\n // `fetch` inside it does not run the list a second time, and can still hand\n // the route what the list carried. Keyed by the Request object: the servers\n // hand `fetch` the same one they gated.\n private globallyGated = new WeakMap<Request, CarriedContext | null>();\n\n /**\n * Runs the `global` middleware list, then `next` — what the servers put in\n * front of everything they serve, so the list covers static files, which\n * never reach `fetch`, as well as routes. A refusal is answered without\n * calling `next`. A global middleware that throws something other than a\n * break is answered by `onError` rather than by `next`, since a gate that\n * failed must not let a static file through.\n */\n public async withGlobalMiddleware(\n req: Request,\n next: (req: Request) => Promise<Response>,\n onError: (err: unknown) => Response | Promise<Response>,\n ): Promise<Response> {\n let outcome: Awaited<ReturnType<Kernel[\"globalMiddleware\"]>>;\n try {\n outcome = await this.kernel.run.call(this.kernel, () => this.kernel.globalMiddleware(req));\n } catch (err) {\n return await onError(err);\n }\n if (outcome.refusal) {\n return outcome.refusal;\n }\n this.globallyGated.set(req, outcome.carried);\n return outcome.apply(await next(req));\n }\n\n public async fetch(req: Request): Promise<Response> {\n const url = new URL(req.url);\n return this.kernel.run.call(this.kernel, async () => {\n // Repeated from the servers, for a caller that is not one of them.\n this.applyTrustedClientIp(req);\n // Run here too for a caller that is not one of the servers, a test or an\n // app's own `Bun.serve`, so the list is not skipped by calling `fetch`.\n const gated = this.globallyGated.has(req);\n const outcome = gated ? null : await this.kernel.globalMiddleware(req);\n const carried = gated ? this.globallyGated.get(req) : outcome.carried;\n if (outcome?.refusal) {\n return outcome.refusal;\n }\n // The MCP endpoint, and its OAuth endpoints, on the host it is\n // configured for. Ahead of routing, so no route can shadow it, and after\n // the global middleware, which covers it as it covers everything.\n const mcp = this.kernel.mcpHttp();\n if (mcp) {\n const answered = await mcp.handle(req);\n if (answered) {\n return outcome ? outcome.apply(answered) : answered;\n }\n }\n const domains = this.kernel.domains();\n const dispatchers = (await domains.ask(req)) ?? (await domains.route(req));\n if (dispatchers instanceof Response) {\n return outcome ? outcome.apply(dispatchers) : dispatchers;\n }\n if (!dispatchers) {\n const unknown = new Response(\"Unknown host\", { status: 404 });\n return outcome ? outcome.apply(unknown) : unknown;\n }\n const result = isApiPath(url.pathname)\n ? await dispatchers.api.handleApiRequest(req, carried)\n : await dispatchers.view.handleViewRequest(req, carried);\n if (!outcome) {\n return result;\n }\n // A document comes back as a render function the server calls with its\n // manifests, and the Response only exists once it has.\n if (typeof result === \"function\") {\n const render = result as (...args: any[]) => Promise<Response>;\n return (async (...args: any[]) => outcome.apply(await render(...args))) as any;\n }\n return outcome.apply(result);\n });\n }\n\n public dispatchJob(jobName: string, args: string) {\n const kernelRun = this.kernel.run.bind(this.kernel);\n return kernelRun(() => {\n return this.kernel.queue().dispatchJob(jobName, args);\n });\n }\n\n /** Every provider's `shutdown()`; see `Kernel.shutdown`. */\n public shutdown(options?: { timeoutMs?: number }) {\n return this.kernel.shutdown(options);\n }\n\n public destroy() {\n this.kernel.destroy();\n }\n\n public clone() {\n return Object.assign(Object.create(Object.getPrototypeOf(this)), this);\n }\n}\n\nexport type FetchHandler = InstanceType<typeof App>[\"fetch\"];\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";yCAgBO,MAAM,CAAI,CACP,OACD,YAEP,WAAW,CAAC,EAAmB,CAC7B,KAAK,OAAS,IAAI,EAAO,OACzB,KAAK,OAAO,KAAK,KAAK,KAAK,MAAM,EACjC,KAAK,YACH,EAAO,cACN,CAAC,IAAiB,CACjB,QAAQ,MAAM,8BAA+B,CAAK,SAc3C,YAAW,EAAG,CACzB,MAAM,KAAK,OAAO,YAAY,EAGzB,gBAAgB,EAAG,CACxB,OAAO,KAAK,OAAO,WAAW,EAAE,cAM3B,oBAAoB,EAAG,CAC5B,IAAM,EAAQ,IAAI,IAClB,QAAW,KAAc,KAAK,OAAO,QAAQ,EAAE,gBAAgB,EAC7D,QAAW,KAAQ,EAAW,kBAC5B,EAAM,IAAI,CAAI,EAGlB,OA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