@prisma/extension-optimize 1.1.8 → 2.0.1

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/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var xt=Object.create;var B=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty;var wt=(e,t)=>{for(var n in t)B(e,n,{get:t[n],enumerable:!0})},xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of It(t))!Rt.call(e,s)&&s!==n&&B(e,s,{get:()=>t[s],enumerable:!(r=bt(t,s))||r.enumerable});return e};var vt=(e,t,n)=>(n=e!=null?xt(Tt(e)):{},xe(t||!e||!e.__esModule?B(n,"default",{value:e,enumerable:!0}):n,e)),Et=e=>xe(B({},"__esModule",{value:!0}),e);var an={};wt(an,{PROD_DASHBOARD_URL:()=>ht,PROD_INGESTION_URL:()=>gt,withOptimize:()=>sn});module.exports=Et(an);var mt=require("@opentelemetry/api"),dt=require("@prisma/client/extension");var _=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,n){this.keyToValue.set(t,n),this.valueToKey.set(n,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}};var O=class{constructor(t){this.generateIdentifier=t,this.kv=new _}register(t,n){this.kv.getByValue(t)||(n||(n=this.generateIdentifier(t)),this.kv.set(n,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}};var N=class extends O{constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),super.register(t,n.identifier)):super.register(t,n)}getAllowedProps(t){return this.classToAllowedProps.get(t)}};function Ot(e){if("values"in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function be(e,t){let n=Ot(e);if("find"in n)return n.find(t);let r=n;for(let s=0;s<r.length;s++){let i=r[s];if(t(i))return i}}function w(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function P(e,t){return e.indexOf(t)!==-1}function Y(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var V=class{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return be(this.transfomers,n=>n.isApplicable(t))}findByName(t){return this.transfomers[t]}};var Pt=e=>Object.prototype.toString.call(e).slice(8,-1),J=e=>typeof e>"u",At=e=>e===null,v=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,M=e=>v(e)&&Object.keys(e).length===0,g=e=>Array.isArray(e),qt=e=>typeof e=="string",Ct=e=>typeof e=="number"&&!isNaN(e),kt=e=>typeof e=="boolean",Ie=e=>e instanceof RegExp,b=e=>e instanceof Map,I=e=>e instanceof Set,ee=e=>Pt(e)==="Symbol",Te=e=>e instanceof Date&&!isNaN(e.valueOf()),Re=e=>e instanceof Error,te=e=>typeof e=="number"&&isNaN(e),we=e=>kt(e)||At(e)||J(e)||Ct(e)||qt(e)||ee(e),ve=e=>typeof e=="bigint",Ee=e=>e===1/0||e===-1/0,Oe=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Pe=e=>e instanceof URL;var ne=e=>e.replace(/\./g,"\\."),F=e=>e.map(String).map(ne).join("."),A=e=>{let t=[],n="";for(let s=0;s<e.length;s++){let i=e.charAt(s);if(i==="\\"&&e.charAt(s+1)==="."){n+=".",s++;continue}if(i==="."){t.push(n),n="";continue}n+=i}let r=n;return t.push(r),t};function S(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Ae=[S(J,"undefined",()=>null,()=>{}),S(ve,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),S(Te,"Date",e=>e.toISOString(),e=>new Date(e)),S(Re,"Error",(e,t)=>{let n={name:e.name,message:e.message};return t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n},(e,t)=>{let n=new Error(e.message);return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n}),S(Ie,"regexp",e=>""+e,e=>{let t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),S(I,"set",e=>[...e.values()],e=>new Set(e)),S(b,"map",e=>[...e.entries()],e=>new Map(e)),S(e=>te(e)||Ee(e),"number",e=>te(e)?"NaN":e>0?"Infinity":"-Infinity",Number),S(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),S(Pe,"URL",e=>e.toString(),e=>new URL(e))];function U(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var qe=U((e,t)=>ee(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),jt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),Ce=U(Oe,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{let n=jt[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function re(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var ke=U(re,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(s=>{r[s]=e[s]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),je=U((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),zt=[ke,qe,je,Ce],se=(e,t)=>{let n=Y(zt,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=Y(Ae,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},ze={};Ae.forEach(e=>{ze[e.annotation]=e});var Be=(e,t,n)=>{if(g(t))switch(t[0]){case"symbol":return qe.untransform(e,t,n);case"class":return ke.untransform(e,t,n);case"custom":return je.untransform(e,t,n);case"typed-array":return Ce.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{let r=ze[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,n)}};var q=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function _e(e){if(P(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(P(e,"prototype"))throw new Error("prototype is not allowed as a property");if(P(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Ne=(e,t)=>{_e(t);for(let n=0;n<t.length;n++){let r=t[n];if(I(e))e=q(e,+r);else if(b(e)){let s=+r,i=+t[++n]==0?"key":"value",a=q(e,s);switch(i){case"key":e=a;break;case"value":e=e.get(a);break}}else e=e[r]}return e},D=(e,t,n)=>{if(_e(t),t.length===0)return n(e);let r=e;for(let i=0;i<t.length-1;i++){let a=t[i];if(g(r)){let p=+a;r=r[p]}else if(v(r))r=r[a];else if(I(r)){let p=+a;r=q(r,p)}else if(b(r)){if(i===t.length-2)break;let l=+a,y=+t[++i]==0?"key":"value",d=q(r,l);switch(y){case"key":r=d;break;case"value":r=r.get(d);break}}}let s=t[t.length-1];if(g(r)?r[+s]=n(r[+s]):v(r)&&(r[s]=n(r[s])),I(r)){let i=q(r,+s),a=n(i);i!==a&&(r.delete(i),r.add(a))}if(b(r)){let i=+t[t.length-2],a=q(r,i);switch(+s==0?"key":"value"){case"key":{let l=n(a);r.set(l,r.get(a)),l!==a&&r.delete(a);break}case"value":{r.set(a,n(r.get(a)));break}}}return e};function ie(e,t,n=[]){if(!e)return;if(!g(e)){w(e,(i,a)=>ie(i,t,[...n,...A(a)]));return}let[r,s]=e;s&&w(s,(i,a)=>{ie(i,t,[...n,...A(a)])}),t(r,n)}function Ve(e,t,n){return ie(t,(r,s)=>{e=D(e,s,i=>Be(i,r,n))}),e}function Me(e,t){function n(r,s){let i=Ne(e,A(s));r.map(A).forEach(a=>{e=D(e,a,()=>i)})}if(g(t)){let[r,s]=t;r.forEach(i=>{e=D(e,A(i),()=>e)}),s&&w(s,n)}else w(t,n);return e}var Bt=(e,t)=>v(e)||g(e)||b(e)||I(e)||re(e,t);function _t(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function Fe(e,t){let n={},r;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(p=>p.map(String)).sort((p,l)=>p.length-l.length));let[i,...a]=s;i.length===0?r=a.map(F):n[F(i)]=a.map(F)}),r?M(n)?[r]:[r,n]:M(n)?void 0:n}var oe=(e,t,n,r,s=[],i=[],a=new Map)=>{let p=we(e);if(!p){_t(e,s,t);let h=a.get(e);if(h)return r?{transformedValue:null}:h}if(!Bt(e,n)){let h=se(e,n),f=h?{transformedValue:h.value,annotations:[h.type]}:{transformedValue:e};return p||a.set(e,f),f}if(P(i,e))return{transformedValue:null};let l=se(e,n),y=l?.value??e,d=g(y)?[]:{},R={};w(y,(h,f)=>{if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error(`Detected property ${f}. This is a prototype pollution risk, please remove it from your object.`);let x=oe(h,t,n,r,[...s,f],[...i,e],a);d[f]=x.transformedValue,g(x.annotations)?R[f]=x.annotations:v(x.annotations)&&w(x.annotations,(G,Z)=>{R[ne(f)+"."+Z]=G})});let z=M(R)?{transformedValue:d,annotations:l?[l.type]:void 0}:{transformedValue:d,annotations:l?[l.type,R]:R};return p||a.set(e,z),z};function L(e){return Object.prototype.toString.call(e).slice(8,-1)}function ae(e){return L(e)==="Array"}function Ue(e){if(L(e)!=="Object")return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function Nt(e){return L(e)==="Null"}function Vt(e,t,n,r,s){return i=>e(i)||t(i)||!!n&&n(i)||!!r&&r(i)||!!s&&s(i)}function Mt(e){return L(e)==="Undefined"}var Dn=Vt(Nt,Mt);function Ft(e,t,n,r,s){let i={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=n),s&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function $(e,t={}){if(ae(e))return e.map(s=>$(s,t));if(!Ue(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((s,i)=>{if(ae(t.props)&&!t.props.includes(i))return s;let a=e[i],p=$(a,t);return Ft(s,i,p,e,t.nonenumerable),s},{})}var c=class{constructor({dedupe:t=!1}={}){this.classRegistry=new N,this.symbolRegistry=new O(n=>n.description??""),this.customTransformerRegistry=new V,this.allowedErrorProps=[],this.dedupe=t}serialize(t){let n=new Map,r=oe(t,n,this,this.dedupe),s={json:r.transformedValue};r.annotations&&(s.meta={...s.meta,values:r.annotations});let i=Fe(n,this.dedupe);return i&&(s.meta={...s.meta,referentialEqualities:i}),s}deserialize(t){let{json:n,meta:r}=t,s=$(n);return r?.values&&(s=Ve(s,r.values,this)),r?.referentialEqualities&&(s=Me(s,r.referentialEqualities)),s}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t))}registerClass(t,n){this.classRegistry.register(t,n)}registerSymbol(t,n){this.symbolRegistry.register(t,n)}registerCustom(t,n){this.customTransformerRegistry.register({name:n,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}};c.defaultInstance=new c;c.serialize=c.defaultInstance.serialize.bind(c.defaultInstance);c.deserialize=c.defaultInstance.deserialize.bind(c.defaultInstance);c.stringify=c.defaultInstance.stringify.bind(c.defaultInstance);c.parse=c.defaultInstance.parse.bind(c.defaultInstance);c.registerClass=c.defaultInstance.registerClass.bind(c.defaultInstance);c.registerSymbol=c.defaultInstance.registerSymbol.bind(c.defaultInstance);c.registerCustom=c.defaultInstance.registerCustom.bind(c.defaultInstance);c.allowErrorProps=c.defaultInstance.allowErrorProps.bind(c.defaultInstance);var Jn=c.serialize,Ut=c.deserialize,De=c.stringify,er=c.parse,tr=c.registerClass,Le=c.registerCustom,nr=c.registerSymbol,rr=c.allowErrorProps;var He=!1;function Dt(e){Le({isApplicable:t=>(e?.isBuffer?.(t)??(typeof Buffer<"u"&&Buffer.isBuffer(t)))||$e(t),serialize:t=>$e(t)?t.data:[...t],deserialize:t=>e?.from?.(t)??(typeof Buffer<"u"?Buffer.from(t):{type:"Buffer",data:t})},"buffer"),He=!0}function $e(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"type")==="Buffer"&&Array.isArray(Reflect.get(e,"data"))}var Ke=e=>typeof e=="string"?e:(He||Dt(),De(e));function Lt(e,t){let n;return async function(r,s,i){let a=new URL(r,e),p=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${t}`});n&&p.set("prisma-optimize-jwt",n);let l=await fetch(a,{method:s,headers:p,body:Ke(i)});if(!l.ok){let d=await l.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${l.status} ${l.statusText}: ${d}`)}let y=l.headers.get("prisma-optimize-jwt");return y&&(n=y),l}}function Qe(e,t){let n=Lt(e,t);return{request:n,post:(r,s)=>n(r,"POST",s)}}var We=vt(require("kleur"),1);var{bold:$t,underline:Ht}=We.default;function Ge(e){let t="See your Optimize dashboard at:",n=t.length,r=`${Ht($t(e))}`,s=e.length,i=Math.max(n,s)+2;console.log("\u250C"+"\u2500".repeat(i)+"\u2510"),console.log("\u2502 "+t+" ".repeat(i-n-2)+" \u2502"),console.log("\u2502 "+r+" ".repeat(i-s-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(i)+"\u2518")}var tt=require("@opentelemetry/api"),nt=require("@opentelemetry/context-async-hooks"),rt=require("@opentelemetry/instrumentation"),st=require("@opentelemetry/resources"),it=require("@opentelemetry/sdk-trace-base"),W=require("@opentelemetry/semantic-conventions"),he=require("prisma-instrumentation-5-x"),ot=require("prisma-instrumentation-6-x");async function Ze(e,t){t.length>0&&await e.post("/ingest",t)}async function Xe(e,t){return await(await e.post("/schema",t)).text()}function T(e){return e[0]*1e3+e[1]/1e6}var o=require("zod/v4");var E=require("zod/v4"),H=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(t){this.treeShape=t.treeShape,this.sendTimeout=t.sendTimeout,this.sendInterval=t.sendInterval,this.collectedSpans=t.collectedSpans,this.collectedRootSpans=t.collectedRootSpans,this.onEnd=Kt(()=>void this.forceFlush(),this.sendInterval)}onStart(t){let{parentSpanId:n,name:r}=t,{spanId:s}=t.spanContext();if(!this.collectedSpans.includes(r))return this.cleanSpan(this.spans[s]);if(this.spans[s]?.kind==="future"?Object.assign(this.spans[s],{kind:"present",value:t}):this.spans[s]={spanId:s,kind:"present",children:[],value:t,retries:0},this.collectedRootSpans.includes(r)){(n===void 0||this.rootSpans[n]===void 0)&&(this.rootSpans[s]={...this.spans[s],done:!1}),this.waitSpans[s]=this.spans[s];for(let{spanId:i}of this.spans[s].children)delete this.rootSpans[i]}n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[s]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[s]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(t){if(t===void 0)return;let n=t.spanId;for(let r of t.children)this.cleanSpan(r);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(t)}async forceFlush(){await this.pendingSend;let t=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];if(process?.env?.__DEBUG_OPTIMIZE__){let s=(i,a="")=>{console.log(a,i.value.name,i.value.ended,i.value.attributes,i.spanId),i.children.forEach(p=>s(p,a+" ->"))};s(n)}let r=this.treeShape.safeParse(n);return r.data?(n.done=!0,[{original:n,pruned:r.data}]):[]});t.length>0&&(this.pendingSend=this.onFlush(t).finally(()=>{t.forEach(({original:n})=>this.cleanSpan(n))}));for(let n of Object.values(this.waitSpans))++n.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(n)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function Kt(e,t){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||e(),t))}}var m={ended:E.z.literal(!0),_spanContext:E.z.custom(),spanContext:E.z.custom(),startTime:E.z.custom(),endTime:E.z.custom(),attributes:E.z.custom()};var pe=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:db_query"),...m})}),Qt=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:itx_execute_single"),...m}),children:C([pe])}),K=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine"),o.z.literal("prisma:engine:query")]),...m}),children:C([pe])}),Wt=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine"),o.z.literal("prisma:engine:query")]),...m}),children:C([o.z.union([Qt,pe])])}),ce=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:connect"),...m})}),ue=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...m}),children:o.z.union([o.z.tuple([K]),o.z.tuple([ce,K]),o.z.tuple([K,ce])])}),Ye=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...m}),children:C([Wt])}),Gt=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:start_transaction"),...m})}),Zt=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:commit_transaction"),...m})}),le=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...m}),children:o.z.array(ce)}),fe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...m}),children:C([Gt,Zt])}),me=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...m}),children:C([le,K])}),Je=o.z.union([ue,fe,me]);function C(e){return o.z.array(o.z.any()).nonempty().superRefine((t,n)=>{e.every(s=>t.some(i=>s.safeParse(i).success))||n.addIssue({code:"custom",message:"Array does not contain all the required items"})})}var Q=class extends H{requests={};errors={};schemaHash;resolvedSchemaHash;apiClient;schemaRequest;constructor(t){super({treeShape:Je,sendTimeout:t.sendTimeout,sendInterval:t.sendInterval,collectedSpans:["prisma:client:transaction","prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:query","prisma:engine:db_query","prisma:engine:itx_execute_single","prisma:engine:start_transaction","prisma:engine:commit_transaction"],collectedRootSpans:["prisma:client:operation","prisma:client:transaction"]}),this.apiClient=t.apiClient,this.schemaRequest=t.schemaRequest}setRequest(t){this.requests[t.spanId]=t}setError(t){this.errors[t.spanId]=t}onClean({spanId:t}){delete this.requests[t],delete this.errors[t]}async onFlush(t){this.schemaHash??=Xe(this.apiClient,this.schemaRequest),this.resolvedSchemaHash??=await this.schemaHash;let n=t.flatMap(({pruned:r})=>Xt(r,this));await Ze(this.apiClient,n)}};function Xt(e,t){return fe.safeParse(e).success?Yt(e,t):me.safeParse(e).success?Jt(e,t):ue.safeParse(e).success?en(e,t):[]}function Yt(e,t){let n=[],r=e.children.filter(s=>Ye.safeParse(s).success);for(let s of r){if(ge({span:s,ip:t})===!1)continue;let i=nn(s);n.push(k({ip:t,span:s,sql:i,connect:!1}))}if(n.length){let s=de(e);n.unshift(k({ip:t,span:e,sql:null,connect:s}))}return n}function Jt(e,t){let n=[],r=e.children.filter(i=>le.safeParse(i).success),s=!1;for(let i of r)ge({span:i,ip:t})!==!1&&(s||=de(i),n.push(k({ip:t,span:i,sql:null,connect:!1})));return n.length&&n.unshift(k({ip:t,span:e,sql:null,connect:s})),n}function en(e,t){let n=de(e),r=tn(e);return ge({span:e,ip:t})===!1?[]:[k({ip:t,span:e,sql:r,connect:n})]}function k(e){let{span:t,sql:n,connect:r,ip:s}=e,i=t.value.spanContext().spanId,{value:a}=t;return{hash:s.resolvedSchemaHash,sql:n??null,connect:r??!1,error:s.errors[i]?.error??null,ts:T(a.startTime),model:s.requests[i]?.model??a.attributes.model??null,operation:s.requests[i]?.operation??a.attributes.method,args:s.requests[i]?.args??{},latency:T(a.endTime)-T(a.startTime)}}function et(e){return e.sort((n,r)=>T(n.value.startTime)-T(r.value.startTime)).reduce((n,r)=>{let s=r.value.attributes["db.statement"];return s??=r.value.attributes["db.query.text"],typeof s=="string"?`${n}${s}
2
+ `:n},"")}function tn(e){let{children:t}=e.children.find(({value:r})=>r.name==="prisma:engine"||r.name==="prisma:engine:query"),n=t.filter(({value:r})=>r.name==="prisma:engine:db_query");return et(n)}function nn(e){let{children:t}=e.children.find(({value:i})=>i.name==="prisma:engine"||i.name==="prisma:engine:query"),n=t.filter(({value:i})=>i.name==="prisma:engine:itx_execute_single"),s=(n.length?n:[{children:t}]).flatMap(({children:i})=>i.filter(({value:a})=>a.name==="prisma:engine:db_query"));return et(s)}function de(e){let{value:t}=e.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return t?T(t.endTime)-T(t.startTime):!1}function ge(e){let{span:t,ip:n}=e;return!!n.requests[t.value.spanContext().spanId]}var j,rn={"5-x":he.PrismaInstrumentation,"6-x":ot.PrismaInstrumentation};function at(e){if(j)return j;let t=new nt.AsyncHooksContextManager().enable();tt.context.setGlobalContextManager(t);let n=new it.BasicTracerProvider({resource:new st.Resource({[W.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[W.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});j=new Q(e),n.addSpanProcessor(j);let[r="5",s="0"]=e.clientVersion.split("."),i=rn[`${r}-x`];return(r==="6"&&s==="0"||i===void 0)&&(i=he.PrismaInstrumentation),(0,rt.registerInstrumentations)({tracerProvider:n,instrumentations:[new i]}),n.register(),j}function ct(e){let t=Reflect.get(e,"_clientVersion");return Number(t.split(".")[0]??"5")<6?e._previewFeatures?.includes("tracing"):!0}function pt(e){return e._engineConfig.inlineSchema}function ut(e){if(e instanceof Error)return e.stack??e.message;switch(typeof e){case"undefined":return"undefined";case"object":{let t;return e!==null&&typeof e.toString=="function"&&(t=e.toString()),typeof t=="string"&&t!=="[object Object]"?t:JSON.stringify(e)}default:return String(e)}}var lt=require("@prisma/client/extension"),ft=lt.Prisma.defineExtension(e=>e.$extends({}));var gt="https://optimize-ingestion.datacdn.workers.dev/",ht="https://optimize.prisma.io";function sn({enable:e=!0,ingestionUrl:t=gt,dashboardUrl:n=ht,sendInterval:r=500,sendTimeout:s=1e4,showNotification:i=!0,apiKey:a}){return e?(i&&Ge(n),dt.Prisma.defineExtension(p=>{let l=pt(p),y=Reflect.get(p,"_clientVersion"),d=Reflect.get(p,"_activeProvider"),R=Reflect.get(p,"_accelerateEngineConfig"),z=on(R,d),h={schema:l,provider:d,protocol:z},f=Qe(t,a),x=at({schemaRequest:h,apiClient:f,sendInterval:r,sendTimeout:s,clientVersion:y});if(!ct(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:G,model:Z,operation:St,args:Se}){let X=mt.trace.getActiveSpan()?.spanContext().spanId;if(!X)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");x.setRequest({spanId:X,model:Z,operation:St,args:Se});try{return await G(Se)}catch(ye){let yt=ut(ye);throw x.setError({spanId:X,error:yt}),ye}}}})})):ft}function on(e,t){try{let{protocol:n}=new URL(e.accelerateUtils.resolveDatasourceUrl(e));return n}catch{switch(t){case"sqlite":return"file:";case"postgresql":case"cockroachdb":return"postgres:";default:return`${t}:`}}}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
@@ -0,0 +1,48 @@
1
+ import * as _prisma_client_extension from '@prisma/client/extension';
2
+ import * as _prisma_client_runtime_library from '@prisma/client/runtime/library';
3
+
4
+ declare const PROD_INGESTION_URL = "https://optimize-ingestion.datacdn.workers.dev/";
5
+ declare const PROD_DASHBOARD_URL = "https://optimize.prisma.io";
6
+ type OptimizeOptions = {
7
+ /**
8
+ * Whether to enable Prisma Optimize. Defaults to `true`.
9
+ */
10
+ enable?: boolean;
11
+ /**
12
+ * A Prisma Optimize API key. Head to the Prisma Optimize dashboard to
13
+ * create one.
14
+ */
15
+ apiKey: string;
16
+ /**
17
+ * The minimum interval (in milliseconds) for sending batched Prisma
18
+ * operations to the Prisma Optimize interface.
19
+ *
20
+ * @default 500
21
+ * @remarks setting this value too low may impact your app performance.
22
+ */
23
+ sendInterval?: number;
24
+ /**
25
+ * The maximum time a query can be waited for before being discarded. If a
26
+ * query takes too long to complete, it will be discarded. Increase this if
27
+ * you have very slow queries.
28
+ *
29
+ * @default 10000
30
+ * @remarks when below `minSendInterval`, it defaults to `minSendInterval`.
31
+ */
32
+ sendTimeout?: number;
33
+ /**
34
+ * The URL of the ingestion service of Prisma Optimize.
35
+ */
36
+ ingestionUrl?: string;
37
+ /**
38
+ * The URL of the dashboard of Prisma Optimize
39
+ */
40
+ dashboardUrl?: string;
41
+ /**
42
+ * Whether to show a toast notification when the dashboard is ready.
43
+ */
44
+ showNotification?: boolean;
45
+ };
46
+ declare function withOptimize({ enable, ingestionUrl, dashboardUrl, sendInterval, sendTimeout, showNotification, apiKey, }: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
47
+
48
+ export { type OptimizeOptions, PROD_DASHBOARD_URL, PROD_INGESTION_URL, withOptimize };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var yt=Object.create;var z=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var bt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var Rt=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})},ye=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of bt(t))!Tt.call(e,s)&&s!==n&&z(e,s,{get:()=>t[s],enumerable:!(r=xt(t,s))||r.enumerable});return e};var wt=(e,t,n)=>(n=e!=null?yt(It(e)):{},ye(t||!e||!e.__esModule?z(n,"default",{value:e,enumerable:!0}):n,e)),vt=e=>ye(z({},"__esModule",{value:!0}),e);var sn={};Rt(sn,{PROD_DASHBOARD_URL:()=>gt,PROD_INGESTION_URL:()=>dt,withOptimize:()=>rn});module.exports=vt(sn);var ft=require("@opentelemetry/api"),mt=require("@prisma/client/extension");var B=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,n){this.keyToValue.set(t,n),this.valueToKey.set(n,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}};var E=class{constructor(t){this.generateIdentifier=t,this.kv=new B}register(t,n){this.kv.getByValue(t)||(n||(n=this.generateIdentifier(t)),this.kv.set(n,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}};var _=class extends E{constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),super.register(t,n.identifier)):super.register(t,n)}getAllowedProps(t){return this.classToAllowedProps.get(t)}};function Et(e){if("values"in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function xe(e,t){let n=Et(e);if("find"in n)return n.find(t);let r=n;for(let s=0;s<r.length;s++){let i=r[s];if(t(i))return i}}function R(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function O(e,t){return e.indexOf(t)!==-1}function X(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var N=class{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return xe(this.transfomers,n=>n.isApplicable(t))}findByName(t){return this.transfomers[t]}};var Ot=e=>Object.prototype.toString.call(e).slice(8,-1),Y=e=>typeof e>"u",Pt=e=>e===null,w=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,V=e=>w(e)&&Object.keys(e).length===0,m=e=>Array.isArray(e),At=e=>typeof e=="string",qt=e=>typeof e=="number"&&!isNaN(e),Ct=e=>typeof e=="boolean",be=e=>e instanceof RegExp,b=e=>e instanceof Map,I=e=>e instanceof Set,J=e=>Ot(e)==="Symbol",Ie=e=>e instanceof Date&&!isNaN(e.valueOf()),Te=e=>e instanceof Error,ee=e=>typeof e=="number"&&isNaN(e),Re=e=>Ct(e)||Pt(e)||Y(e)||qt(e)||At(e)||J(e),we=e=>typeof e=="bigint",ve=e=>e===1/0||e===-1/0,Ee=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Oe=e=>e instanceof URL;var te=e=>e.replace(/\./g,"\\."),M=e=>e.map(String).map(te).join("."),P=e=>{let t=[],n="";for(let s=0;s<e.length;s++){let i=e.charAt(s);if(i==="\\"&&e.charAt(s+1)==="."){n+=".",s++;continue}if(i==="."){t.push(n),n="";continue}n+=i}let r=n;return t.push(r),t};function h(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Pe=[h(Y,"undefined",()=>null,()=>{}),h(we,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),h(Ie,"Date",e=>e.toISOString(),e=>new Date(e)),h(Te,"Error",(e,t)=>{let n={name:e.name,message:e.message};return t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n},(e,t)=>{let n=new Error(e.message);return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n}),h(be,"regexp",e=>""+e,e=>{let t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),h(I,"set",e=>[...e.values()],e=>new Set(e)),h(b,"map",e=>[...e.entries()],e=>new Map(e)),h(e=>ee(e)||ve(e),"number",e=>ee(e)?"NaN":e>0?"Infinity":"-Infinity",Number),h(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),h(Oe,"URL",e=>e.toString(),e=>new URL(e))];function F(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Ae=F((e,t)=>J(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),kt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),qe=F(Ee,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{let n=kt[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function ne(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var Ce=F(ne,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(s=>{r[s]=e[s]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),ke=F((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),jt=[Ce,Ae,ke,qe],re=(e,t)=>{let n=X(jt,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=X(Pe,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},je={};Pe.forEach(e=>{je[e.annotation]=e});var ze=(e,t,n)=>{if(m(t))switch(t[0]){case"symbol":return Ae.untransform(e,t,n);case"class":return Ce.untransform(e,t,n);case"custom":return ke.untransform(e,t,n);case"typed-array":return qe.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{let r=je[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,n)}};var A=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function Be(e){if(O(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(O(e,"prototype"))throw new Error("prototype is not allowed as a property");if(O(e,"constructor"))throw new Error("constructor is not allowed as a property")}var _e=(e,t)=>{Be(t);for(let n=0;n<t.length;n++){let r=t[n];if(I(e))e=A(e,+r);else if(b(e)){let s=+r,i=+t[++n]==0?"key":"value",a=A(e,s);switch(i){case"key":e=a;break;case"value":e=e.get(a);break}}else e=e[r]}return e},U=(e,t,n)=>{if(Be(t),t.length===0)return n(e);let r=e;for(let i=0;i<t.length-1;i++){let a=t[i];if(m(r)){let p=+a;r=r[p]}else if(w(r))r=r[a];else if(I(r)){let p=+a;r=A(r,p)}else if(b(r)){if(i===t.length-2)break;let u=+a,S=+t[++i]==0?"key":"value",d=A(r,u);switch(S){case"key":r=d;break;case"value":r=r.get(d);break}}}let s=t[t.length-1];if(m(r)?r[+s]=n(r[+s]):w(r)&&(r[s]=n(r[s])),I(r)){let i=A(r,+s),a=n(i);i!==a&&(r.delete(i),r.add(a))}if(b(r)){let i=+t[t.length-2],a=A(r,i);switch(+s==0?"key":"value"){case"key":{let u=n(a);r.set(u,r.get(a)),u!==a&&r.delete(a);break}case"value":{r.set(a,n(r.get(a)));break}}}return e};function se(e,t,n=[]){if(!e)return;if(!m(e)){R(e,(i,a)=>se(i,t,[...n,...P(a)]));return}let[r,s]=e;s&&R(s,(i,a)=>{se(i,t,[...n,...P(a)])}),t(r,n)}function Ne(e,t,n){return se(t,(r,s)=>{e=U(e,s,i=>ze(i,r,n))}),e}function Ve(e,t){function n(r,s){let i=_e(e,P(s));r.map(P).forEach(a=>{e=U(e,a,()=>i)})}if(m(t)){let[r,s]=t;r.forEach(i=>{e=U(e,P(i),()=>e)}),s&&R(s,n)}else R(t,n);return e}var zt=(e,t)=>w(e)||m(e)||b(e)||I(e)||ne(e,t);function Bt(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function Me(e,t){let n={},r;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(p=>p.map(String)).sort((p,u)=>p.length-u.length));let[i,...a]=s;i.length===0?r=a.map(M):n[M(i)]=a.map(M)}),r?V(n)?[r]:[r,n]:V(n)?void 0:n}var ie=(e,t,n,r,s=[],i=[],a=new Map)=>{let p=Re(e);if(!p){Bt(e,s,t);let g=a.get(e);if(g)return r?{transformedValue:null}:g}if(!zt(e,n)){let g=re(e,n),l=g?{transformedValue:g.value,annotations:[g.type]}:{transformedValue:e};return p||a.set(e,l),l}if(O(i,e))return{transformedValue:null};let u=re(e,n),S=u?.value??e,d=m(S)?[]:{},y={};R(S,(g,l)=>{if(l==="__proto__"||l==="constructor"||l==="prototype")throw new Error(`Detected property ${l}. This is a prototype pollution risk, please remove it from your object.`);let x=ie(g,t,n,r,[...s,l],[...i,e],a);d[l]=x.transformedValue,m(x.annotations)?y[l]=x.annotations:w(x.annotations)&&R(x.annotations,(W,G)=>{y[te(l)+"."+G]=W})});let j=V(y)?{transformedValue:d,annotations:u?[u.type]:void 0}:{transformedValue:d,annotations:u?[u.type,y]:y};return p||a.set(e,j),j};function D(e){return Object.prototype.toString.call(e).slice(8,-1)}function oe(e){return D(e)==="Array"}function Fe(e){if(D(e)!=="Object")return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function _t(e){return D(e)==="Null"}function Nt(e,t,n,r,s){return i=>e(i)||t(i)||!!n&&n(i)||!!r&&r(i)||!!s&&s(i)}function Vt(e){return D(e)==="Undefined"}var qn=Nt(_t,Vt);function Mt(e,t,n,r,s){let i={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=n),s&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function L(e,t={}){if(oe(e))return e.map(s=>L(s,t));if(!Fe(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((s,i)=>{if(oe(t.props)&&!t.props.includes(i))return s;let a=e[i],p=L(a,t);return Mt(s,i,p,e,t.nonenumerable),s},{})}var c=class{constructor({dedupe:t=!1}={}){this.classRegistry=new _,this.symbolRegistry=new E(n=>n.description??""),this.customTransformerRegistry=new N,this.allowedErrorProps=[],this.dedupe=t}serialize(t){let n=new Map,r=ie(t,n,this,this.dedupe),s={json:r.transformedValue};r.annotations&&(s.meta={...s.meta,values:r.annotations});let i=Me(n,this.dedupe);return i&&(s.meta={...s.meta,referentialEqualities:i}),s}deserialize(t){let{json:n,meta:r}=t,s=L(n);return r?.values&&(s=Ne(s,r.values,this)),r?.referentialEqualities&&(s=Ve(s,r.referentialEqualities)),s}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t))}registerClass(t,n){this.classRegistry.register(t,n)}registerSymbol(t,n){this.symbolRegistry.register(t,n)}registerCustom(t,n){this.customTransformerRegistry.register({name:n,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}};c.defaultInstance=new c;c.serialize=c.defaultInstance.serialize.bind(c.defaultInstance);c.deserialize=c.defaultInstance.deserialize.bind(c.defaultInstance);c.stringify=c.defaultInstance.stringify.bind(c.defaultInstance);c.parse=c.defaultInstance.parse.bind(c.defaultInstance);c.registerClass=c.defaultInstance.registerClass.bind(c.defaultInstance);c.registerSymbol=c.defaultInstance.registerSymbol.bind(c.defaultInstance);c.registerCustom=c.defaultInstance.registerCustom.bind(c.defaultInstance);c.allowErrorProps=c.defaultInstance.allowErrorProps.bind(c.defaultInstance);var Mn=c.serialize,Ft=c.deserialize,Ue=c.stringify,Fn=c.parse,Un=c.registerClass,De=c.registerCustom,Dn=c.registerSymbol,Ln=c.allowErrorProps;var $e=!1;function Ut(e){De({isApplicable:t=>(e?.isBuffer?.(t)??(typeof Buffer<"u"&&Buffer.isBuffer(t)))||Le(t),serialize:t=>Le(t)?t.data:[...t],deserialize:t=>e?.from?.(t)??(typeof Buffer<"u"?Buffer.from(t):{type:"Buffer",data:t})},"buffer"),$e=!0}function Le(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"type")==="Buffer"&&Array.isArray(Reflect.get(e,"data"))}var He=e=>typeof e=="string"?e:($e||Ut(),Ue(e));function Dt(e,t){let n;return async function(r,s,i){let a=new URL(r,e),p=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${t}`});n&&p.set("prisma-optimize-jwt",n);let u=await fetch(a,{method:s,headers:p,body:He(i)});if(!u.ok){let d=await u.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${u.status} ${u.statusText}: ${d}`)}let S=u.headers.get("prisma-optimize-jwt");return S&&(n=S),u}}function Ke(e,t){let n=Dt(e,t);return{request:n,post:(r,s)=>n(r,"POST",s)}}var Qe=wt(require("kleur"));var{bold:Lt,underline:$t}=Qe.default;function We(e){let t="See your Optimize dashboard at:",n=t.length,r=`${$t(Lt(e))}`,s=e.length,i=Math.max(n,s)+2;console.log("\u250C"+"\u2500".repeat(i)+"\u2510"),console.log("\u2502 "+t+" ".repeat(i-n-2)+" \u2502"),console.log("\u2502 "+r+" ".repeat(i-s-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(i)+"\u2518")}var et=require("@opentelemetry/api"),tt=require("@opentelemetry/context-async-hooks"),nt=require("@opentelemetry/instrumentation"),rt=require("@opentelemetry/resources"),st=require("@opentelemetry/sdk-trace-base"),Q=require("@opentelemetry/semantic-conventions"),ge=require("prisma-instrumentation-5-x"),it=require("prisma-instrumentation-6-x");async function Ge(e,t){t.length>0&&await e.post("/ingest",t)}async function Ze(e,t){return await(await e.post("/schema",t)).text()}function T(e){return e[0]*1e3+e[1]/1e6}var o=require("zod");var v=require("zod"),$=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(t){this.treeShape=t.treeShape,this.sendTimeout=t.sendTimeout,this.sendInterval=t.sendInterval,this.collectedSpans=t.collectedSpans,this.collectedRootSpans=t.collectedRootSpans,this.onEnd=Ht(()=>void this.forceFlush(),this.sendInterval)}onStart(t){let{parentSpanId:n,name:r}=t,{spanId:s}=t.spanContext();if(!this.collectedSpans.includes(r))return this.cleanSpan(this.spans[s]);if(this.spans[s]?.kind==="future"?Object.assign(this.spans[s],{kind:"present",value:t}):this.spans[s]={spanId:s,kind:"present",children:[],value:t,retries:0},this.collectedRootSpans.includes(r)){(n===void 0||this.rootSpans[n]===void 0)&&(this.rootSpans[s]={...this.spans[s],done:!1}),this.waitSpans[s]=this.spans[s];for(let{spanId:i}of this.spans[s].children)delete this.rootSpans[i]}n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[s]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[s]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(t){if(t===void 0)return;let n=t.spanId;for(let r of t.children)this.cleanSpan(r);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(t)}async forceFlush(){await this.pendingSend;let t=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];if(process?.env?.__DEBUG_OPTIMIZE__){let s=(i,a="")=>{console.log(a,i.value.name,i.value.ended,i.value.attributes,i.spanId),i.children.forEach(p=>s(p,a+" ->"))};s(n)}let r=this.treeShape.safeParse(n);return r.data?(n.done=!0,[{original:n,pruned:r.data}]):[]});t.length>0&&(this.pendingSend=this.onFlush(t).finally(()=>{t.forEach(({original:n})=>this.cleanSpan(n))}));for(let n of Object.values(this.waitSpans))++n.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(n)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function Ht(e,t){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||e(),t))}}var f={ended:v.z.literal(!0),_spanContext:v.z.custom(),spanContext:v.z.custom(),startTime:v.z.custom(),endTime:v.z.custom(),attributes:v.z.custom()};var ce=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:db_query"),...f})}),Kt=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:itx_execute_single"),...f}),children:q([ce])}),H=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine"),o.z.literal("prisma:engine:query")]),...f}),children:q([ce])}),Qt=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine"),o.z.literal("prisma:engine:query")]),...f}),children:q([o.z.union([Kt,ce])])}),ae=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:connect"),...f})}),pe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:o.z.union([o.z.tuple([H]),o.z.tuple([ae,H]),o.z.tuple([H,ae])])}),Xe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:q([Qt])}),Wt=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:start_transaction"),...f})}),Gt=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:commit_transaction"),...f})}),ue=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:o.z.array(ae)}),le=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([Wt,Gt])}),fe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([ue,H])}),Ye=o.z.union([pe,le,fe]);function q(e){return o.z.array(o.z.any()).nonempty().superRefine((t,n)=>{e.every(s=>t.some(i=>s.safeParse(i).success))||n.addIssue({code:"custom",message:"Array does not contain all the required items"})})}var K=class extends ${requests={};errors={};schemaHash;resolvedSchemaHash;apiClient;schemaRequest;constructor(t){super({treeShape:Ye,sendTimeout:t.sendTimeout,sendInterval:t.sendInterval,collectedSpans:["prisma:client:transaction","prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:query","prisma:engine:db_query","prisma:engine:itx_execute_single","prisma:engine:start_transaction","prisma:engine:commit_transaction"],collectedRootSpans:["prisma:client:operation","prisma:client:transaction"]}),this.apiClient=t.apiClient,this.schemaRequest=t.schemaRequest}setRequest(t){this.requests[t.spanId]=t}setError(t){this.errors[t.spanId]=t}onClean({spanId:t}){delete this.requests[t],delete this.errors[t]}async onFlush(t){this.schemaHash??=Ze(this.apiClient,this.schemaRequest),this.resolvedSchemaHash??=await this.schemaHash;let n=t.flatMap(({pruned:r})=>Zt(r,this));await Ge(this.apiClient,n)}};function Zt(e,t){return le.safeParse(e).success?Xt(e,t):fe.safeParse(e).success?Yt(e,t):pe.safeParse(e).success?Jt(e,t):[]}function Xt(e,t){let n=[],r=e.children.filter(s=>Xe.safeParse(s).success);for(let s of r){if(de({span:s,ip:t})===!1)continue;let i=tn(s);n.push(C({ip:t,span:s,sql:i,connect:!1}))}if(n.length){let s=me(e);n.unshift(C({ip:t,span:e,sql:null,connect:s}))}return n}function Yt(e,t){let n=[],r=e.children.filter(i=>ue.safeParse(i).success),s=!1;for(let i of r)de({span:i,ip:t})!==!1&&(s||=me(i),n.push(C({ip:t,span:i,sql:null,connect:!1})));return n.length&&n.unshift(C({ip:t,span:e,sql:null,connect:s})),n}function Jt(e,t){let n=me(e),r=en(e);return de({span:e,ip:t})===!1?[]:[C({ip:t,span:e,sql:r,connect:n})]}function C(e){let{span:t,sql:n,connect:r,ip:s}=e,i=t.value.spanContext().spanId,{value:a}=t;return{hash:s.resolvedSchemaHash,sql:n??null,connect:r??!1,error:s.errors[i]?.error??null,ts:T(a.startTime),model:s.requests[i]?.model??a.attributes.model??null,operation:s.requests[i]?.operation??a.attributes.method,args:s.requests[i]?.args??{},latency:T(a.endTime)-T(a.startTime)}}function Je(e){return e.sort((n,r)=>T(n.value.startTime)-T(r.value.startTime)).reduce((n,r)=>{let s=r.value.attributes["db.statement"];return s??=r.value.attributes["db.query.text"],typeof s=="string"?`${n}${s}
2
- `:n},"")}function en(e){let{children:t}=e.children.find(({value:r})=>r.name==="prisma:engine"||r.name==="prisma:engine:query"),n=t.filter(({value:r})=>r.name==="prisma:engine:db_query");return Je(n)}function tn(e){let{children:t}=e.children.find(({value:i})=>i.name==="prisma:engine"||i.name==="prisma:engine:query"),n=t.filter(({value:i})=>i.name==="prisma:engine:itx_execute_single"),s=(n.length?n:[{children:t}]).flatMap(({children:i})=>i.filter(({value:a})=>a.name==="prisma:engine:db_query"));return Je(s)}function me(e){let{value:t}=e.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return t?T(t.endTime)-T(t.startTime):!1}function de(e){let{span:t,ip:n}=e;return!!n.requests[t.value.spanContext().spanId]}var k,nn={"5-x":ge.PrismaInstrumentation,"6-x":it.PrismaInstrumentation};function ot(e){if(k)return k;let t=new tt.AsyncHooksContextManager().enable();et.context.setGlobalContextManager(t);let n=new st.BasicTracerProvider({resource:new rt.Resource({[Q.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[Q.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});k=new K(e),n.addSpanProcessor(k);let[r="5",s="0"]=e.clientVersion.split("."),i=nn[`${r}-x`];return(r==="6"&&s==="0"||i===void 0)&&(i=ge.PrismaInstrumentation),(0,nt.registerInstrumentations)({tracerProvider:n,instrumentations:[new i]}),n.register(),k}function at(e){let t=Reflect.get(e,"_clientVersion");return Number(t.split(".")[0]??"5")<6?e._previewFeatures?.includes("tracing"):!0}function ct(e){return e._engineConfig.inlineSchema}function pt(e){if(e instanceof Error)return e.stack??e.message;switch(typeof e){case"undefined":return"undefined";case"object":{let t;return e!==null&&typeof e.toString=="function"&&(t=e.toString()),typeof t=="string"&&t!=="[object Object]"?t:JSON.stringify(e)}default:return String(e)}}var ut=require("@prisma/client/extension"),lt=ut.Prisma.defineExtension(e=>e.$extends({}));var dt="https://optimize-ingestion.datacdn.workers.dev/",gt="https://optimize.prisma.io";function rn({enable:e=!0,ingestionUrl:t=dt,dashboardUrl:n=gt,sendInterval:r=500,sendTimeout:s=1e4,showNotification:i=!0,apiKey:a}){return e?(i&&We(n),mt.Prisma.defineExtension(p=>{let u=ct(p),S=Reflect.get(p,"_clientVersion"),d=Reflect.get(p,"_activeProvider"),y=Reflect.get(p,"_accelerateEngineConfig"),{protocol:j}=new URL(y.accelerateUtils.resolveDatasourceUrl(y)),g={schema:u,provider:d,protocol:j},l=Ke(t,a),x=ot({schemaRequest:g,apiClient:l,sendInterval:r,sendTimeout:s,clientVersion:S});if(!at(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:W,model:G,operation:ht,args:he}){let Z=ft.trace.getActiveSpan()?.spanContext().spanId;if(!Z)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");x.setRequest({spanId:Z,model:G,operation:ht,args:he});try{return await W(he)}catch(Se){let St=pt(Se);throw x.setError({spanId:Z,error:St}),Se}}}})})):lt}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
1
+ import{trace as Kt}from"@opentelemetry/api";import{Prisma as Qt}from"@prisma/client/extension";var _=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,n){this.keyToValue.set(t,n),this.valueToKey.set(n,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}};var O=class{constructor(t){this.generateIdentifier=t,this.kv=new _}register(t,n){this.kv.getByValue(t)||(n||(n=this.generateIdentifier(t)),this.kv.set(n,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}};var N=class extends O{constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),super.register(t,n.identifier)):super.register(t,n)}getAllowedProps(t){return this.classToAllowedProps.get(t)}};function it(e){if("values"in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function Se(e,t){let n=it(e);if("find"in n)return n.find(t);let r=n;for(let s=0;s<r.length;s++){let i=r[s];if(t(i))return i}}function v(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function P(e,t){return e.indexOf(t)!==-1}function X(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var V=class{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return Se(this.transfomers,n=>n.isApplicable(t))}findByName(t){return this.transfomers[t]}};var ot=e=>Object.prototype.toString.call(e).slice(8,-1),Y=e=>typeof e>"u",at=e=>e===null,E=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,M=e=>E(e)&&Object.keys(e).length===0,h=e=>Array.isArray(e),ct=e=>typeof e=="string",pt=e=>typeof e=="number"&&!isNaN(e),ut=e=>typeof e=="boolean",ye=e=>e instanceof RegExp,I=e=>e instanceof Map,T=e=>e instanceof Set,J=e=>ot(e)==="Symbol",xe=e=>e instanceof Date&&!isNaN(e.valueOf()),be=e=>e instanceof Error,ee=e=>typeof e=="number"&&isNaN(e),Ie=e=>ut(e)||at(e)||Y(e)||pt(e)||ct(e)||J(e),Te=e=>typeof e=="bigint",Re=e=>e===1/0||e===-1/0,we=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),ve=e=>e instanceof URL;var te=e=>e.replace(/\./g,"\\."),F=e=>e.map(String).map(te).join("."),A=e=>{let t=[],n="";for(let s=0;s<e.length;s++){let i=e.charAt(s);if(i==="\\"&&e.charAt(s+1)==="."){n+=".",s++;continue}if(i==="."){t.push(n),n="";continue}n+=i}let r=n;return t.push(r),t};function y(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Ee=[y(Y,"undefined",()=>null,()=>{}),y(Te,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),y(xe,"Date",e=>e.toISOString(),e=>new Date(e)),y(be,"Error",(e,t)=>{let n={name:e.name,message:e.message};return t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n},(e,t)=>{let n=new Error(e.message);return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n}),y(ye,"regexp",e=>""+e,e=>{let t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),y(T,"set",e=>[...e.values()],e=>new Set(e)),y(I,"map",e=>[...e.entries()],e=>new Map(e)),y(e=>ee(e)||Re(e),"number",e=>ee(e)?"NaN":e>0?"Infinity":"-Infinity",Number),y(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),y(ve,"URL",e=>e.toString(),e=>new URL(e))];function U(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Oe=U((e,t)=>J(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),lt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),Pe=U(we,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{let n=lt[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function ne(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var Ae=U(ne,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(s=>{r[s]=e[s]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),qe=U((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),ft=[Ae,Oe,qe,Pe],re=(e,t)=>{let n=X(ft,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=X(Ee,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},Ce={};Ee.forEach(e=>{Ce[e.annotation]=e});var ke=(e,t,n)=>{if(h(t))switch(t[0]){case"symbol":return Oe.untransform(e,t,n);case"class":return Ae.untransform(e,t,n);case"custom":return qe.untransform(e,t,n);case"typed-array":return Pe.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{let r=Ce[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,n)}};var q=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function je(e){if(P(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(P(e,"prototype"))throw new Error("prototype is not allowed as a property");if(P(e,"constructor"))throw new Error("constructor is not allowed as a property")}var ze=(e,t)=>{je(t);for(let n=0;n<t.length;n++){let r=t[n];if(T(e))e=q(e,+r);else if(I(e)){let s=+r,i=+t[++n]==0?"key":"value",o=q(e,s);switch(i){case"key":e=o;break;case"value":e=e.get(o);break}}else e=e[r]}return e},D=(e,t,n)=>{if(je(t),t.length===0)return n(e);let r=e;for(let i=0;i<t.length-1;i++){let o=t[i];if(h(r)){let p=+o;r=r[p]}else if(E(r))r=r[o];else if(T(r)){let p=+o;r=q(r,p)}else if(I(r)){if(i===t.length-2)break;let f=+o,x=+t[++i]==0?"key":"value",g=q(r,f);switch(x){case"key":r=g;break;case"value":r=r.get(g);break}}}let s=t[t.length-1];if(h(r)?r[+s]=n(r[+s]):E(r)&&(r[s]=n(r[s])),T(r)){let i=q(r,+s),o=n(i);i!==o&&(r.delete(i),r.add(o))}if(I(r)){let i=+t[t.length-2],o=q(r,i);switch(+s==0?"key":"value"){case"key":{let f=n(o);r.set(f,r.get(o)),f!==o&&r.delete(o);break}case"value":{r.set(o,n(r.get(o)));break}}}return e};function se(e,t,n=[]){if(!e)return;if(!h(e)){v(e,(i,o)=>se(i,t,[...n,...A(o)]));return}let[r,s]=e;s&&v(s,(i,o)=>{se(i,t,[...n,...A(o)])}),t(r,n)}function Be(e,t,n){return se(t,(r,s)=>{e=D(e,s,i=>ke(i,r,n))}),e}function _e(e,t){function n(r,s){let i=ze(e,A(s));r.map(A).forEach(o=>{e=D(e,o,()=>i)})}if(h(t)){let[r,s]=t;r.forEach(i=>{e=D(e,A(i),()=>e)}),s&&v(s,n)}else v(t,n);return e}var mt=(e,t)=>E(e)||h(e)||I(e)||T(e)||ne(e,t);function dt(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function Ne(e,t){let n={},r;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(p=>p.map(String)).sort((p,f)=>p.length-f.length));let[i,...o]=s;i.length===0?r=o.map(F):n[F(i)]=o.map(F)}),r?M(n)?[r]:[r,n]:M(n)?void 0:n}var ie=(e,t,n,r,s=[],i=[],o=new Map)=>{let p=Ie(e);if(!p){dt(e,s,t);let S=o.get(e);if(S)return r?{transformedValue:null}:S}if(!mt(e,n)){let S=re(e,n),m=S?{transformedValue:S.value,annotations:[S.type]}:{transformedValue:e};return p||o.set(e,m),m}if(P(i,e))return{transformedValue:null};let f=re(e,n),x=f?.value??e,g=h(x)?[]:{},w={};v(x,(S,m)=>{if(m==="__proto__"||m==="constructor"||m==="prototype")throw new Error(`Detected property ${m}. This is a prototype pollution risk, please remove it from your object.`);let b=ie(S,t,n,r,[...s,m],[...i,e],o);g[m]=b.transformedValue,h(b.annotations)?w[m]=b.annotations:E(b.annotations)&&v(b.annotations,(W,G)=>{w[te(m)+"."+G]=W})});let B=M(w)?{transformedValue:g,annotations:f?[f.type]:void 0}:{transformedValue:g,annotations:f?[f.type,w]:w};return p||o.set(e,B),B};function L(e){return Object.prototype.toString.call(e).slice(8,-1)}function oe(e){return L(e)==="Array"}function Ve(e){if(L(e)!=="Object")return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function gt(e){return L(e)==="Null"}function ht(e,t,n,r,s){return i=>e(i)||t(i)||!!n&&n(i)||!!r&&r(i)||!!s&&s(i)}function St(e){return L(e)==="Undefined"}var Cn=ht(gt,St);function yt(e,t,n,r,s){let i={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=n),s&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function $(e,t={}){if(oe(e))return e.map(s=>$(s,t));if(!Ve(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((s,i)=>{if(oe(t.props)&&!t.props.includes(i))return s;let o=e[i],p=$(o,t);return yt(s,i,p,e,t.nonenumerable),s},{})}var c=class{constructor({dedupe:t=!1}={}){this.classRegistry=new N,this.symbolRegistry=new O(n=>n.description??""),this.customTransformerRegistry=new V,this.allowedErrorProps=[],this.dedupe=t}serialize(t){let n=new Map,r=ie(t,n,this,this.dedupe),s={json:r.transformedValue};r.annotations&&(s.meta={...s.meta,values:r.annotations});let i=Ne(n,this.dedupe);return i&&(s.meta={...s.meta,referentialEqualities:i}),s}deserialize(t){let{json:n,meta:r}=t,s=$(n);return r?.values&&(s=Be(s,r.values,this)),r?.referentialEqualities&&(s=_e(s,r.referentialEqualities)),s}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t))}registerClass(t,n){this.classRegistry.register(t,n)}registerSymbol(t,n){this.symbolRegistry.register(t,n)}registerCustom(t,n){this.customTransformerRegistry.register({name:n,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}};c.defaultInstance=new c;c.serialize=c.defaultInstance.serialize.bind(c.defaultInstance);c.deserialize=c.defaultInstance.deserialize.bind(c.defaultInstance);c.stringify=c.defaultInstance.stringify.bind(c.defaultInstance);c.parse=c.defaultInstance.parse.bind(c.defaultInstance);c.registerClass=c.defaultInstance.registerClass.bind(c.defaultInstance);c.registerSymbol=c.defaultInstance.registerSymbol.bind(c.defaultInstance);c.registerCustom=c.defaultInstance.registerCustom.bind(c.defaultInstance);c.allowErrorProps=c.defaultInstance.allowErrorProps.bind(c.defaultInstance);var Dn=c.serialize,xt=c.deserialize,Me=c.stringify,Ln=c.parse,$n=c.registerClass,Fe=c.registerCustom,Hn=c.registerSymbol,Kn=c.allowErrorProps;var De=!1;function bt(e){Fe({isApplicable:t=>(e?.isBuffer?.(t)??(typeof Buffer<"u"&&Buffer.isBuffer(t)))||Ue(t),serialize:t=>Ue(t)?t.data:[...t],deserialize:t=>e?.from?.(t)??(typeof Buffer<"u"?Buffer.from(t):{type:"Buffer",data:t})},"buffer"),De=!0}function Ue(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"type")==="Buffer"&&Array.isArray(Reflect.get(e,"data"))}var Le=e=>typeof e=="string"?e:(De||bt(),Me(e));function It(e,t){let n;return async function(r,s,i){let o=new URL(r,e),p=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${t}`});n&&p.set("prisma-optimize-jwt",n);let f=await fetch(o,{method:s,headers:p,body:Le(i)});if(!f.ok){let g=await f.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${f.status} ${f.statusText}: ${g}`)}let x=f.headers.get("prisma-optimize-jwt");return x&&(n=x),f}}function $e(e,t){let n=It(e,t);return{request:n,post:(r,s)=>n(r,"POST",s)}}import Tt from"kleur";var{bold:Rt,underline:wt}=Tt;function He(e){let t="See your Optimize dashboard at:",n=t.length,r=`${wt(Rt(e))}`,s=e.length,i=Math.max(n,s)+2;console.log("\u250C"+"\u2500".repeat(i)+"\u2510"),console.log("\u2502 "+t+" ".repeat(i-n-2)+" \u2502"),console.log("\u2502 "+r+" ".repeat(i-s-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(i)+"\u2518")}import{context as _t}from"@opentelemetry/api";import{AsyncHooksContextManager as Nt}from"@opentelemetry/context-async-hooks";import{registerInstrumentations as Vt}from"@opentelemetry/instrumentation";import{Resource as Mt}from"@opentelemetry/resources";import{BasicTracerProvider as Ft}from"@opentelemetry/sdk-trace-base";import{SEMRESATTRS_SERVICE_NAME as Ut,SEMRESATTRS_SERVICE_VERSION as Dt}from"@opentelemetry/semantic-conventions";import{PrismaInstrumentation as Xe}from"prisma-instrumentation-5-x";import{PrismaInstrumentation as Lt}from"prisma-instrumentation-6-x";async function Ke(e,t){t.length>0&&await e.post("/ingest",t)}async function Qe(e,t){return await(await e.post("/schema",t)).text()}function R(e){return e[0]*1e3+e[1]/1e6}import{z as a}from"zod/v4";import{z as C}from"zod/v4";var H=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(t){this.treeShape=t.treeShape,this.sendTimeout=t.sendTimeout,this.sendInterval=t.sendInterval,this.collectedSpans=t.collectedSpans,this.collectedRootSpans=t.collectedRootSpans,this.onEnd=vt(()=>void this.forceFlush(),this.sendInterval)}onStart(t){let{parentSpanId:n,name:r}=t,{spanId:s}=t.spanContext();if(!this.collectedSpans.includes(r))return this.cleanSpan(this.spans[s]);if(this.spans[s]?.kind==="future"?Object.assign(this.spans[s],{kind:"present",value:t}):this.spans[s]={spanId:s,kind:"present",children:[],value:t,retries:0},this.collectedRootSpans.includes(r)){(n===void 0||this.rootSpans[n]===void 0)&&(this.rootSpans[s]={...this.spans[s],done:!1}),this.waitSpans[s]=this.spans[s];for(let{spanId:i}of this.spans[s].children)delete this.rootSpans[i]}n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[s]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[s]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(t){if(t===void 0)return;let n=t.spanId;for(let r of t.children)this.cleanSpan(r);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(t)}async forceFlush(){await this.pendingSend;let t=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];if(process?.env?.__DEBUG_OPTIMIZE__){let s=(i,o="")=>{console.log(o,i.value.name,i.value.ended,i.value.attributes,i.spanId),i.children.forEach(p=>s(p,o+" ->"))};s(n)}let r=this.treeShape.safeParse(n);return r.data?(n.done=!0,[{original:n,pruned:r.data}]):[]});t.length>0&&(this.pendingSend=this.onFlush(t).finally(()=>{t.forEach(({original:n})=>this.cleanSpan(n))}));for(let n of Object.values(this.waitSpans))++n.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(n)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function vt(e,t){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||e(),t))}}var d={ended:C.literal(!0),_spanContext:C.custom(),spanContext:C.custom(),startTime:C.custom(),endTime:C.custom(),attributes:C.custom()};var ce=a.object({value:a.object({name:a.literal("prisma:engine:db_query"),...d})}),Et=a.object({value:a.object({name:a.literal("prisma:engine:itx_execute_single"),...d}),children:k([ce])}),K=a.object({value:a.object({name:a.union([a.literal("prisma:engine"),a.literal("prisma:engine:query")]),...d}),children:k([ce])}),Ot=a.object({value:a.object({name:a.union([a.literal("prisma:engine"),a.literal("prisma:engine:query")]),...d}),children:k([a.union([Et,ce])])}),ae=a.object({value:a.object({name:a.literal("prisma:client:connect"),...d})}),pe=a.object({value:a.object({name:a.literal("prisma:client:operation"),...d}),children:a.union([a.tuple([K]),a.tuple([ae,K]),a.tuple([K,ae])])}),We=a.object({value:a.object({name:a.literal("prisma:client:operation"),...d}),children:k([Ot])}),Pt=a.object({value:a.object({name:a.literal("prisma:engine:start_transaction"),...d})}),At=a.object({value:a.object({name:a.literal("prisma:engine:commit_transaction"),...d})}),ue=a.object({value:a.object({name:a.literal("prisma:client:operation"),...d}),children:a.array(ae)}),le=a.object({value:a.object({name:a.literal("prisma:client:transaction"),...d}),children:k([Pt,At])}),fe=a.object({value:a.object({name:a.literal("prisma:client:transaction"),...d}),children:k([ue,K])}),Ge=a.union([pe,le,fe]);function k(e){return a.array(a.any()).nonempty().superRefine((t,n)=>{e.every(s=>t.some(i=>s.safeParse(i).success))||n.addIssue({code:"custom",message:"Array does not contain all the required items"})})}var Q=class extends H{requests={};errors={};schemaHash;resolvedSchemaHash;apiClient;schemaRequest;constructor(t){super({treeShape:Ge,sendTimeout:t.sendTimeout,sendInterval:t.sendInterval,collectedSpans:["prisma:client:transaction","prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:query","prisma:engine:db_query","prisma:engine:itx_execute_single","prisma:engine:start_transaction","prisma:engine:commit_transaction"],collectedRootSpans:["prisma:client:operation","prisma:client:transaction"]}),this.apiClient=t.apiClient,this.schemaRequest=t.schemaRequest}setRequest(t){this.requests[t.spanId]=t}setError(t){this.errors[t.spanId]=t}onClean({spanId:t}){delete this.requests[t],delete this.errors[t]}async onFlush(t){this.schemaHash??=Qe(this.apiClient,this.schemaRequest),this.resolvedSchemaHash??=await this.schemaHash;let n=t.flatMap(({pruned:r})=>qt(r,this));await Ke(this.apiClient,n)}};function qt(e,t){return le.safeParse(e).success?Ct(e,t):fe.safeParse(e).success?kt(e,t):pe.safeParse(e).success?jt(e,t):[]}function Ct(e,t){let n=[],r=e.children.filter(s=>We.safeParse(s).success);for(let s of r){if(de({span:s,ip:t})===!1)continue;let i=Bt(s);n.push(j({ip:t,span:s,sql:i,connect:!1}))}if(n.length){let s=me(e);n.unshift(j({ip:t,span:e,sql:null,connect:s}))}return n}function kt(e,t){let n=[],r=e.children.filter(i=>ue.safeParse(i).success),s=!1;for(let i of r)de({span:i,ip:t})!==!1&&(s||=me(i),n.push(j({ip:t,span:i,sql:null,connect:!1})));return n.length&&n.unshift(j({ip:t,span:e,sql:null,connect:s})),n}function jt(e,t){let n=me(e),r=zt(e);return de({span:e,ip:t})===!1?[]:[j({ip:t,span:e,sql:r,connect:n})]}function j(e){let{span:t,sql:n,connect:r,ip:s}=e,i=t.value.spanContext().spanId,{value:o}=t;return{hash:s.resolvedSchemaHash,sql:n??null,connect:r??!1,error:s.errors[i]?.error??null,ts:R(o.startTime),model:s.requests[i]?.model??o.attributes.model??null,operation:s.requests[i]?.operation??o.attributes.method,args:s.requests[i]?.args??{},latency:R(o.endTime)-R(o.startTime)}}function Ze(e){return e.sort((n,r)=>R(n.value.startTime)-R(r.value.startTime)).reduce((n,r)=>{let s=r.value.attributes["db.statement"];return s??=r.value.attributes["db.query.text"],typeof s=="string"?`${n}${s}
2
+ `:n},"")}function zt(e){let{children:t}=e.children.find(({value:r})=>r.name==="prisma:engine"||r.name==="prisma:engine:query"),n=t.filter(({value:r})=>r.name==="prisma:engine:db_query");return Ze(n)}function Bt(e){let{children:t}=e.children.find(({value:i})=>i.name==="prisma:engine"||i.name==="prisma:engine:query"),n=t.filter(({value:i})=>i.name==="prisma:engine:itx_execute_single"),s=(n.length?n:[{children:t}]).flatMap(({children:i})=>i.filter(({value:o})=>o.name==="prisma:engine:db_query"));return Ze(s)}function me(e){let{value:t}=e.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return t?R(t.endTime)-R(t.startTime):!1}function de(e){let{span:t,ip:n}=e;return!!n.requests[t.value.spanContext().spanId]}var z,$t={"5-x":Xe,"6-x":Lt};function Ye(e){if(z)return z;let t=new Nt().enable();_t.setGlobalContextManager(t);let n=new Ft({resource:new Mt({[Ut]:"extension-optimize",[Dt]:"0.0.0"})});z=new Q(e),n.addSpanProcessor(z);let[r="5",s="0"]=e.clientVersion.split("."),i=$t[`${r}-x`];return(r==="6"&&s==="0"||i===void 0)&&(i=Xe),Vt({tracerProvider:n,instrumentations:[new i]}),n.register(),z}function Je(e){let t=Reflect.get(e,"_clientVersion");return Number(t.split(".")[0]??"5")<6?e._previewFeatures?.includes("tracing"):!0}function et(e){return e._engineConfig.inlineSchema}function tt(e){if(e instanceof Error)return e.stack??e.message;switch(typeof e){case"undefined":return"undefined";case"object":{let t;return e!==null&&typeof e.toString=="function"&&(t=e.toString()),typeof t=="string"&&t!=="[object Object]"?t:JSON.stringify(e)}default:return String(e)}}import{Prisma as Ht}from"@prisma/client/extension";var nt=Ht.defineExtension(e=>e.$extends({}));var Wt="https://optimize-ingestion.datacdn.workers.dev/",Gt="https://optimize.prisma.io";function Xr({enable:e=!0,ingestionUrl:t=Wt,dashboardUrl:n=Gt,sendInterval:r=500,sendTimeout:s=1e4,showNotification:i=!0,apiKey:o}){return e?(i&&He(n),Qt.defineExtension(p=>{let f=et(p),x=Reflect.get(p,"_clientVersion"),g=Reflect.get(p,"_activeProvider"),w=Reflect.get(p,"_accelerateEngineConfig"),B=Zt(w,g),S={schema:f,provider:g,protocol:B},m=$e(t,o),b=Ye({schemaRequest:S,apiClient:m,sendInterval:r,sendTimeout:s,clientVersion:x});if(!Je(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:W,model:G,operation:rt,args:ge}){let Z=Kt.getActiveSpan()?.spanContext().spanId;if(!Z)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");b.setRequest({spanId:Z,model:G,operation:rt,args:ge});try{return await W(ge)}catch(he){let st=tt(he);throw b.setError({spanId:Z,error:st}),he}}}})})):nt}function Zt(e,t){try{let{protocol:n}=new URL(e.accelerateUtils.resolveDatasourceUrl(e));return n}catch{switch(t){case"sqlite":return"file:";case"postgresql":case"cockroachdb":return"postgres:";default:return`${t}:`}}}export{Gt as PROD_DASHBOARD_URL,Wt as PROD_INGESTION_URL,Xr as withOptimize};
package/package.json CHANGED
@@ -1,10 +1,27 @@
1
1
  {
2
2
  "name": "@prisma/extension-optimize",
3
- "version": "1.1.8",
3
+ "version": "2.0.1",
4
4
  "sideEffects": false,
5
- "description": "",
6
- "main": "./dist/index.js",
5
+ "description": "Prisma Optimize client extension for Prisma ORM",
6
+ "type": "module",
7
+ "module": "./dist/index.js",
8
+ "main": "./dist/index.cjs",
7
9
  "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
8
25
  "keywords": [],
9
26
  "dependencies": {
10
27
  "@opentelemetry/api": "^1.8",
@@ -13,35 +30,31 @@
13
30
  "@opentelemetry/resources": "^1.22.0",
14
31
  "@opentelemetry/sdk-trace-base": "^1.22",
15
32
  "@opentelemetry/semantic-conventions": "1.22.0",
16
- "@prisma/debug": "5.19.1",
33
+ "@prisma/debug": "6.9.0",
17
34
  "kleur": "4.1.5",
18
35
  "prisma-instrumentation-5-x": "npm:@prisma/instrumentation@5.19.1",
19
- "prisma-instrumentation-6-x": "npm:@prisma/instrumentation@6.1.0",
20
- "zod": "3.23.8"
36
+ "prisma-instrumentation-6-x": "npm:@prisma/instrumentation@6.9.0",
37
+ "zod": "3.25.56"
21
38
  },
22
39
  "devDependencies": {
23
- "@hono/node-server": "1.9.1",
40
+ "@arethetypeswrong/cli": "0.18.2",
41
+ "@hono/node-server": "1.14.4",
24
42
  "@types/node-notifier": "8.0.5",
25
43
  "@types/readline-sync": "1.4.8",
26
44
  "eslint": "8.57.0",
27
- "hono": "4.4.6",
28
- "npm-run-all": "4.1.5",
29
- "tsup": "8.0.2",
30
- "tsx": "4.17.0",
31
- "typescript": "5.5.4",
32
- "vitest": "1.5.3",
33
- "wrangler": "3.105.1",
45
+ "hono": "4.7.11",
46
+ "tsup": "8.5.0",
47
+ "typescript": "5.8.3",
48
+ "vitest": "3.2.3",
34
49
  "optimize-common": "0.0.0"
35
50
  },
36
51
  "peerDependencies": {
37
52
  "@prisma/client": "5.x || 6.x"
38
53
  },
39
- "files": [
40
- "dist"
41
- ],
42
54
  "scripts": {
43
55
  "typecheck": "tsc --noEmit",
44
56
  "build": "tsup",
57
+ "check:exports": "attw . --pack",
45
58
  "lint": "eslint --fix .",
46
59
  "test": "vitest --run",
47
60
  "watch": "tsup --watch"