@prisma/extension-optimize 1.1.3 → 1.1.4

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.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ht=Object.create;var z=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var Tt=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})},Se=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yt(t))!bt.call(e,s)&&s!==n&&z(e,s,{get:()=>t[s],enumerable:!(r=St(t,s))||r.enumerable});return e};var wt=(e,t,n)=>(n=e!=null?ht(xt(e)):{},Se(t||!e||!e.__esModule?z(n,"default",{value:e,enumerable:!0}):n,e)),It=e=>Se(z({},"__esModule",{value:!0}),e);var en={};Tt(en,{PROD_DASHBOARD_URL:()=>dt,PROD_INGESTION_URL:()=>mt,withOptimize:()=>Jt});module.exports=It(en);var lt=require("@opentelemetry/api"),ft=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 N=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 Rt(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 ye(e,t){let n=Rt(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 I(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function O(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 _=class{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return ye(this.transfomers,n=>n.isApplicable(t))}findByName(t){return this.transfomers[t]}};var vt=e=>Object.prototype.toString.call(e).slice(8,-1),J=e=>typeof e>"u",Et=e=>e===null,R=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,V=e=>R(e)&&Object.keys(e).length===0,d=e=>Array.isArray(e),Ot=e=>typeof e=="string",Pt=e=>typeof e=="number"&&!isNaN(e),At=e=>typeof e=="boolean",xe=e=>e instanceof RegExp,y=e=>e instanceof Map,x=e=>e instanceof Set,ee=e=>vt(e)==="Symbol",be=e=>e instanceof Date&&!isNaN(e.valueOf()),Te=e=>e instanceof Error,te=e=>typeof e=="number"&&isNaN(e),we=e=>At(e)||Et(e)||J(e)||Pt(e)||Ot(e)||ee(e),Ie=e=>typeof e=="bigint",Re=e=>e===1/0||e===-1/0,ve=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ee=e=>e instanceof URL;var ne=e=>e.replace(/\./g,"\\."),M=e=>e.map(String).map(ne).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 Oe=[h(J,"undefined",()=>null,()=>{}),h(Ie,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),h(be,"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(xe,"regexp",e=>""+e,e=>{let t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),h(x,"set",e=>[...e.values()],e=>new Set(e)),h(y,"map",e=>[...e.entries()],e=>new Map(e)),h(e=>te(e)||Re(e),"number",e=>te(e)?"NaN":e>0?"Infinity":"-Infinity",Number),h(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),h(Ee,"URL",e=>e.toString(),e=>new URL(e))];function F(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Pe=F((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}),qt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),Ae=F(ve,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{let n=qt[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 qe=F(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)}),Ce=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)}),Ct=[qe,Pe,Ce,Ae],se=(e,t)=>{let n=Y(Ct,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=Y(Oe,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},ke={};Oe.forEach(e=>{ke[e.annotation]=e});var je=(e,t,n)=>{if(d(t))switch(t[0]){case"symbol":return Pe.untransform(e,t,n);case"class":return qe.untransform(e,t,n);case"custom":return Ce.untransform(e,t,n);case"typed-array":return Ae.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{let r=ke[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 ze(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 Be=(e,t)=>{ze(t);for(let n=0;n<t.length;n++){let r=t[n];if(x(e))e=A(e,+r);else if(y(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(ze(t),t.length===0)return n(e);let r=e;for(let i=0;i<t.length-1;i++){let a=t[i];if(d(r)){let p=+a;r=r[p]}else if(R(r))r=r[a];else if(x(r)){let p=+a;r=A(r,p)}else if(y(r)){if(i===t.length-2)break;let u=+a,S=+t[++i]==0?"key":"value",m=A(r,u);switch(S){case"key":r=m;break;case"value":r=r.get(m);break}}}let s=t[t.length-1];if(d(r)?r[+s]=n(r[+s]):R(r)&&(r[s]=n(r[s])),x(r)){let i=A(r,+s),a=n(i);i!==a&&(r.delete(i),r.add(a))}if(y(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 ie(e,t,n=[]){if(!e)return;if(!d(e)){I(e,(i,a)=>ie(i,t,[...n,...P(a)]));return}let[r,s]=e;s&&I(s,(i,a)=>{ie(i,t,[...n,...P(a)])}),t(r,n)}function Ne(e,t,n){return ie(t,(r,s)=>{e=U(e,s,i=>je(i,r,n))}),e}function _e(e,t){function n(r,s){let i=Be(e,P(s));r.map(P).forEach(a=>{e=U(e,a,()=>i)})}if(d(t)){let[r,s]=t;r.forEach(i=>{e=U(e,P(i),()=>e)}),s&&I(s,n)}else I(t,n);return e}var kt=(e,t)=>R(e)||d(e)||y(e)||x(e)||re(e,t);function jt(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function Ve(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 oe=(e,t,n,r,s=[],i=[],a=new Map)=>{let p=we(e);if(!p){jt(e,s,t);let g=a.get(e);if(g)return r?{transformedValue:null}:g}if(!kt(e,n)){let g=se(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=se(e,n),S=u?.value??e,m=d(S)?[]:{},T={};I(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 w=oe(g,t,n,r,[...s,l],[...i,e],a);m[l]=w.transformedValue,d(w.annotations)?T[l]=w.annotations:R(w.annotations)&&I(w.annotations,(G,Z)=>{T[ne(l)+"."+Z]=G})});let j=V(T)?{transformedValue:m,annotations:u?[u.type]:void 0}:{transformedValue:m,annotations:u?[u.type,T]:T};return p||a.set(e,j),j};function D(e){return Object.prototype.toString.call(e).slice(8,-1)}function ae(e){return D(e)==="Array"}function Me(e){if(D(e)!=="Object")return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function zt(e){return D(e)==="Null"}function Bt(e,t,n,r,s){return i=>e(i)||t(i)||!!n&&n(i)||!!r&&r(i)||!!s&&s(i)}function Nt(e){return D(e)==="Undefined"}var En=Bt(zt,Nt);function _t(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(ae(e))return e.map(s=>L(s,t));if(!Me(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=L(a,t);return _t(s,i,p,e,t.nonenumerable),s},{})}var c=class{constructor({dedupe:t=!1}={}){this.classRegistry=new N,this.symbolRegistry=new E(n=>n.description??""),this.customTransformerRegistry=new _,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=Ve(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=_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 Bn=c.serialize,Vt=c.deserialize,Fe=c.stringify,Nn=c.parse,_n=c.registerClass,Ue=c.registerCustom,Vn=c.registerSymbol,Mn=c.allowErrorProps;var Le=!1;function Mt(e){Ue({isApplicable:t=>(e?.isBuffer?.(t)??(typeof Buffer<"u"&&Buffer.isBuffer(t)))||De(t),serialize:t=>De(t)?t.data:[...t],deserialize:t=>e?.from?.(t)??(typeof Buffer<"u"?Buffer.from(t):{type:"Buffer",data:t})},"buffer"),Le=!0}function De(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"type")==="Buffer"&&Array.isArray(Reflect.get(e,"data"))}var $e=e=>typeof e=="string"?e:(Le||Mt(),Fe(e));function Ft(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:$e(i)});if(!u.ok){let m=await u.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${u.status} ${u.statusText}: ${m}`)}let S=u.headers.get("prisma-optimize-jwt");return S&&(n=S),u}}function He(e,t){let n=Ft(e,t);return{request:n,post:(r,s)=>n(r,"POST",s)}}var Ke=wt(require("kleur"));var{bold:Ut,underline:Dt}=Ke.default;function Qe(e){let t="See your Optimize dashboard at:",n=t.length,r=`${Dt(Ut(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 Je=require("@opentelemetry/api"),et=require("@opentelemetry/context-async-hooks"),tt=require("@opentelemetry/instrumentation"),nt=require("@opentelemetry/resources"),rt=require("@opentelemetry/sdk-trace-base"),W=require("@opentelemetry/semantic-conventions"),st=require("@prisma/instrumentation");async function We(e,t){t.length>0&&await e.post("/ingest",t)}async function Ge(e,t){return await(await e.post("/schema",t)).text()}function b(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=Lt(()=>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]);this.spans[s]&&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)&&(this.rootSpans[s]={...this.spans[s],done:!1},this.waitSpans[s]=this.spans[s]),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[];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 Lt(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 Ze=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:db_query"),...f})}),$t=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:itx_execute_single"),...f}),children:q([Ze])}),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([Ze])}),Ht=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([$t])}),K=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:connect"),...f})}),ce=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([K,H]),o.z.tuple([H,K])])}),pe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:q([Ht])}),Kt=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine:start_transaction"),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(K)}),le=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([Kt,pe,K])}),fe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([ue,H])}),Xe=o.z.union([ce,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 Q=class extends ${requests={};errors={};schemaHash;resolvedSchemaHash;apiClient;schemaRequest;constructor(t){super({treeShape:Xe,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??=Ge(this.apiClient,this.schemaRequest),this.resolvedSchemaHash??=await this.schemaHash;let n=t.flatMap(({pruned:r})=>Qt(r,this));await We(this.apiClient,n)}};function Qt(e,t){return le.safeParse(e).success?Wt(e,t):fe.safeParse(e).success?Gt(e,t):ce.safeParse(e).success?Zt(e,t):[]}function Wt(e,t){let n=[],r=e.children.filter(s=>pe.safeParse(s).success);for(let s of r){if(de({span:s,ip:t})===!1)continue;let i=Yt(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 Gt(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 Zt(e,t){let n=me(e),r=Xt(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:b(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:b(a.endTime)-b(a.startTime)}}function Ye(e){return e.sort((n,r)=>b(n.value.startTime)-b(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 Xt(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 Ye(n)}function Yt(e){let{children:t}=e.children.find(({value:s})=>s.name==="prisma:engine"||s.name==="prisma:engine:query"),r=t.filter(({value:s})=>s.name==="prisma:engine:itx_execute_single").flatMap(({children:s})=>s.filter(({value:i})=>i.name==="prisma:engine:db_query"));return Ye(r)}function me(e){let{value:t}=e.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return t?b(t.endTime)-b(t.startTime):!1}function de(e){let{span:t,ip:n}=e;return!!n.requests[t.value.spanContext().spanId]}var k;function it(e){if(k)return k;let t=new et.AsyncHooksContextManager().enable();Je.context.setGlobalContextManager(t);let n=new rt.BasicTracerProvider({resource:new nt.Resource({[W.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[W.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});return k=new Q(e),n.addSpanProcessor(k),(0,tt.registerInstrumentations)({tracerProvider:n,instrumentations:[new st.PrismaInstrumentation]}),n.register(),k}function ot(e){return e._previewFeatures?.includes("tracing")}function at(e){return e._engineConfig.inlineSchema}function ct(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 pt=require("@prisma/client/extension"),ut=pt.Prisma.defineExtension(e=>e.$extends({}));var mt="https://optimize-ingestion.datacdn.workers.dev/",dt="https://optimize.prisma.io";function Jt({enable:e=!0,ingestionUrl:t=mt,dashboardUrl:n=dt,sendInterval:r=500,sendTimeout:s=1e4,showNotification:i=!0,apiKey:a}){return e?(i&&Qe(n),ft.Prisma.defineExtension(p=>{let u=at(p),S=Reflect.get(p,"_activeProvider"),m=Reflect.get(p,"_accelerateEngineConfig"),{protocol:T}=new URL(m.accelerateUtils.resolveDatasourceUrl(m)),j={schema:u,provider:S,protocol:T},g=He(t,a),l=it({schemaRequest:j,apiClient:g,sendInterval:r,sendTimeout:s});if(!ot(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:Z,args:ge}){let X=lt.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");l.setRequest({spanId:X,model:G,operation:Z,args:ge});try{return await w(ge)}catch(he){let gt=ct(he);throw l.setError({spanId:X,error:gt}),he}}}})})):ut}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
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 rn={};Rt(rn,{PROD_DASHBOARD_URL:()=>gt,PROD_INGESTION_URL:()=>dt,withOptimize:()=>nn});module.exports=vt(rn);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 N=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 Y(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var _=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),J=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,ee=e=>Ot(e)==="Symbol",Ie=e=>e instanceof Date&&!isNaN(e.valueOf()),Te=e=>e instanceof Error,te=e=>typeof e=="number"&&isNaN(e),Re=e=>Ct(e)||Pt(e)||J(e)||qt(e)||At(e)||ee(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 ne=e=>e.replace(/\./g,"\\."),M=e=>e.map(String).map(ne).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(J,"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=>te(e)||ve(e),"number",e=>te(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)=>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}),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 re(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var Ce=F(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)}),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],se=(e,t)=>{let n=Y(jt,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=Y(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 Ne=(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 u=+a;r=r[u]}else if(w(r))r=r[a];else if(I(r)){let u=+a;r=A(r,u)}else if(b(r)){if(i===t.length-2)break;let p=+a,S=+t[++i]==0?"key":"value",d=A(r,p);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 p=n(a);r.set(p,r.get(a)),p!==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(!m(e)){R(e,(i,a)=>ie(i,t,[...n,...P(a)]));return}let[r,s]=e;s&&R(s,(i,a)=>{ie(i,t,[...n,...P(a)])}),t(r,n)}function _e(e,t,n){return ie(t,(r,s)=>{e=U(e,s,i=>ze(i,r,n))}),e}function Ve(e,t){function n(r,s){let i=Ne(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)||re(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(u=>u.map(String)).sort((u,p)=>u.length-p.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 oe=(e,t,n,r,s=[],i=[],a=new Map)=>{let u=Re(e);if(!u){Bt(e,s,t);let g=a.get(e);if(g)return r?{transformedValue:null}:g}if(!zt(e,n)){let g=se(e,n),l=g?{transformedValue:g.value,annotations:[g.type]}:{transformedValue:e};return u||a.set(e,l),l}if(O(i,e))return{transformedValue:null};let p=se(e,n),S=p?.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=oe(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,(G,Z)=>{y[ne(l)+"."+Z]=G})});let j=V(y)?{transformedValue:d,annotations:p?[p.type]:void 0}:{transformedValue:d,annotations:p?[p.type,y]:y};return u||a.set(e,j),j};function D(e){return Object.prototype.toString.call(e).slice(8,-1)}function ae(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 Nt(e){return D(e)==="Null"}function _t(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 An=_t(Nt,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(ae(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(ae(t.props)&&!t.props.includes(i))return s;let a=e[i],u=L(a,t);return Mt(s,i,u,e,t.nonenumerable),s},{})}var c=class{constructor({dedupe:t=!1}={}){this.classRegistry=new N,this.symbolRegistry=new E(n=>n.description??""),this.customTransformerRegistry=new _,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=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=_e(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 Vn=c.serialize,Ft=c.deserialize,Ue=c.stringify,Mn=c.parse,Fn=c.registerClass,De=c.registerCustom,Un=c.registerSymbol,Dn=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),u=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${t}`});n&&u.set("prisma-optimize-jwt",n);let p=await fetch(a,{method:s,headers:u,body:He(i)});if(!p.ok){let d=await p.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${p.status} ${p.statusText}: ${d}`)}let S=p.headers.get("prisma-optimize-jwt");return S&&(n=S),p}}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"),W=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]);this.spans[s]&&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)&&(this.rootSpans[s]={...this.spans[s],done:!1},this.waitSpans[s]=this.spans[s]),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[];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 Xe=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([Xe])}),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([Xe])}),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([Kt])}),K=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:connect"),...f})}),ce=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([K,H]),o.z.tuple([H,K])])}),ue=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.union([o.z.literal("prisma:engine:start_transaction"),o.z.literal("prisma:engine:commit_transaction")]),...f})}),pe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:o.z.array(K)}),le=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([Wt,ue,K])}),fe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([pe,H])}),Ye=o.z.union([ce,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 Q=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})=>Gt(r,this));await Ge(this.apiClient,n)}};function Gt(e,t){return le.safeParse(e).success?Zt(e,t):fe.safeParse(e).success?Xt(e,t):ce.safeParse(e).success?Yt(e,t):[]}function Zt(e,t){let n=[],r=e.children.filter(s=>ue.safeParse(s).success);for(let s of r){if(de({span:s,ip:t})===!1)continue;let i=en(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 Xt(e,t){let n=[],r=e.children.filter(i=>pe.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 Yt(e,t){let n=me(e),r=Jt(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 Jt(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 en(e){let{children:t}=e.children.find(({value:s})=>s.name==="prisma:engine"||s.name==="prisma:engine:query"),r=t.filter(({value:s})=>s.name==="prisma:engine:itx_execute_single").flatMap(({children:s})=>s.filter(({value:i})=>i.name==="prisma:engine:db_query"));return Je(r)}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,tn={"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({[W.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[W.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});k=new Q(e),n.addSpanProcessor(k);let[r="5",s="0"]=e.clientVersion.split("."),i=tn[`${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 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 pt=require("@prisma/client/extension"),lt=pt.Prisma.defineExtension(e=>e.$extends({}));var dt="https://optimize-ingestion.datacdn.workers.dev/",gt="https://optimize.prisma.io";function nn({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(u=>{let p=ct(u),S=Reflect.get(u,"_clientVersion"),d=Reflect.get(u,"_activeProvider"),y=Reflect.get(u,"_accelerateEngineConfig"),{protocol:j}=new URL(y.accelerateUtils.resolveDatasourceUrl(y)),g={schema:p,provider:d,protocol:j},l=Ke(t,a),x=ot({schemaRequest:g,apiClient:l,sendInterval:r,sendTimeout:s,clientVersion:S});if(!at(u))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return u.$extends({query:{async $allOperations({query:G,model:Z,operation:ht,args:he}){let X=ft.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:ht,args:he});try{return await G(he)}catch(Se){let St=ut(Se);throw x.setError({spanId:X,error:St}),Se}}}})})):lt}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/extension-optimize",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "sideEffects": false,
5
5
  "description": "",
6
6
  "main": "./dist/index.js",
@@ -14,7 +14,8 @@
14
14
  "@opentelemetry/sdk-trace-base": "^1.22",
15
15
  "@opentelemetry/semantic-conventions": "1.22.0",
16
16
  "@prisma/debug": "5.19.1",
17
- "@prisma/instrumentation": "5.19.1",
17
+ "prisma-instrumentation-5-x": "npm:@prisma/instrumentation@5.19.1",
18
+ "prisma-instrumentation-6-x": "npm:@prisma/instrumentation@6.1.0",
18
19
  "kleur": "4.1.5",
19
20
  "zod": "3.23.8"
20
21
  },