@drip-sdk/node 1.0.10 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/next.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var crypto=require('crypto');var I=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var P=class{_total=0;_flushed=false;_flushCount=0;_chargeFn;_options;constructor(e,t){this._chargeFn=e,this._options=t;}get total(){return this._total}get isFlushed(){return this._flushed}get flushCount(){return this._flushCount}async add(e){return e<=0?null:(this._total+=e,this._options.onAdd?.(e,this._total),this._options.flushThreshold!==void 0&&this._total>=this._options.flushThreshold?this.flush():null)}addSync(e){e<=0||(this._total+=e,this._options.onAdd?.(e,this._total));}async flush(){let e=this._total;if(this._total=0,e===0)return {success:true,quantity:0,charge:null,isReplay:false};let t=this._options.idempotencyKey?`${this._options.idempotencyKey}_flush_${this._flushCount}`:void 0,s=await this._chargeFn({customerId:this._options.customerId,meter:this._options.meter,quantity:e,idempotencyKey:t,metadata:this._options.metadata});this._flushed=true,this._flushCount++;let i={success:s.success,quantity:e,charge:s.charge,isReplay:s.isReplay};return this._options.onFlush?.(i),i}reset(){this._total=0;}};var E={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3};function M(r){return r instanceof Error&&(r.message.includes("fetch")||r.message.includes("network"))?true:r instanceof f?r.statusCode>=500||r.statusCode===408||r.statusCode===429:false}async function O(r,e={}){let t=e.maxAttempts??E.maxAttempts,s=e.baseDelayMs??E.baseDelayMs,i=e.maxDelayMs??E.maxDelayMs,n=e.isRetryable??M,o;for(let u=1;u<=t;u++)try{return await r()}catch(c){if(o=c,u===t||!n(c))throw c;let d=Math.min(s*Math.pow(2,u-1)+Math.random()*100,i);await new Promise(a=>setTimeout(a,d));}throw o}var f=class r extends Error{constructor(t,s,i){super(t);this.statusCode=s;this.code=i;this.name="DripError",Object.setPrototypeOf(this,r.prototype);}},C=class{apiKey;baseUrl;timeout;constructor(e){if(!e.apiKey)throw new Error("Drip API key is required");this.apiKey=e.apiKey,this.baseUrl=e.baseUrl||"https://api.drip.dev/v1",this.timeout=e.timeout||3e4;}async request(e,t={}){let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeout);try{let n=await fetch(`${this.baseUrl}${e}`,{...t,signal:s.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(n.status===204)return {success:!0};let o=await n.json();if(!n.ok)throw new f(o.message||o.error||"Request failed",n.status,o.code);return o}catch(n){throw n instanceof f?n:n instanceof Error&&n.name==="AbortError"?new f("Request timed out",408,"TIMEOUT"):new f(n instanceof Error?n.message:"Unknown error",0,"UNKNOWN")}finally{clearTimeout(i);}}async ping(){let e=new AbortController,t=setTimeout(()=>e.abort(),this.timeout),s=this.baseUrl;s.endsWith("/v1/")?s=s.slice(0,-4):s.endsWith("/v1")&&(s=s.slice(0,-3)),s=s.replace(/\/+$/,"");let i=Date.now();try{let n=await fetch(`${s}/health`,{signal:e.signal,headers:{Authorization:`Bearer ${this.apiKey}`}}),o=Date.now()-i,u="unknown",c=Date.now();try{let d=await n.json();typeof d.status=="string"&&(u=d.status),typeof d.timestamp=="number"&&(c=d.timestamp);}catch{u=n.ok?"healthy":`error:${n.status}`;}return !n.ok&&u==="unknown"&&(u=`error:${n.status}`),{ok:n.ok&&u==="healthy",status:u,latencyMs:o,timestamp:c}}catch(n){throw n instanceof Error&&n.name==="AbortError"?new f("Request timed out",408,"TIMEOUT"):new f(n instanceof Error?n.message:"Unknown error",0,"UNKNOWN")}finally{clearTimeout(t);}}async createCustomer(e){return this.request("/customers",{method:"POST",body:JSON.stringify(e)})}async getCustomer(e){return this.request(`/customers/${e}`)}async listCustomers(e){let t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.status&&t.set("status",e.status);let s=t.toString(),i=s?`/customers?${s}`:"/customers";return this.request(i)}async getBalance(e){return this.request(`/customers/${e}/balance`)}async charge(e){return this.request("/usage",{method:"POST",body:JSON.stringify({customerId:e.customerId,usageType:e.meter,quantity:e.quantity,idempotencyKey:e.idempotencyKey,metadata:e.metadata})})}async wrapApiCall(e){let t=e.idempotencyKey??`wrap_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,s=await e.call(),i=e.extractUsage(s),n=await O(()=>this.charge({customerId:e.customerId,meter:e.meter,quantity:i,idempotencyKey:t,metadata:e.metadata}),e.retryOptions);return {result:s,charge:n,idempotencyKey:t}}async trackUsage(e){return this.request("/usage/internal",{method:"POST",body:JSON.stringify({customerId:e.customerId,usageType:e.meter,quantity:e.quantity,idempotencyKey:e.idempotencyKey,units:e.units,description:e.description,metadata:e.metadata})})}async getCharge(e){return this.request(`/charges/${e}`)}async listCharges(e){let t=new URLSearchParams;e?.customerId&&t.set("customerId",e.customerId),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",e.limit.toString()),e?.offset&&t.set("offset",e.offset.toString());let s=t.toString(),i=s?`/charges?${s}`:"/charges";return this.request(i)}async getChargeStatus(e){return this.request(`/charges/${e}/status`)}async checkout(e){let t=await this.request("/checkout",{method:"POST",body:JSON.stringify({customer_id:e.customerId,external_customer_id:e.externalCustomerId,amount:e.amount,return_url:e.returnUrl,cancel_url:e.cancelUrl,metadata:e.metadata})});return {id:t.id,url:t.url,expiresAt:t.expires_at,amountUsd:t.amount_usd}}async createWebhook(e){return this.request("/webhooks",{method:"POST",body:JSON.stringify(e)})}async listWebhooks(){return this.request("/webhooks")}async getWebhook(e){return this.request(`/webhooks/${e}`)}async deleteWebhook(e){return this.request(`/webhooks/${e}`,{method:"DELETE"})}async testWebhook(e){return this.request(`/webhooks/${e}/test`,{method:"POST"})}async rotateWebhookSecret(e){return this.request(`/webhooks/${e}/rotate-secret`,{method:"POST"})}async createWorkflow(e){return this.request("/workflows",{method:"POST",body:JSON.stringify(e)})}async listWorkflows(){return this.request("/workflows")}async startRun(e){return this.request("/runs",{method:"POST",body:JSON.stringify(e)})}async endRun(e,t){return this.request(`/runs/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async getRunTimeline(e){return this.request(`/runs/${e}`)}async emitEvent(e){return this.request("/events",{method:"POST",body:JSON.stringify(e)})}async emitEventsBatch(e){return this.request("/run-events/batch",{method:"POST",body:JSON.stringify({events:e})})}async listMeters(){let e=await this.request("/pricing-plans");return {data:e.data.map(t=>({id:t.id,name:t.name,meter:t.unitType,unitPriceUsd:t.unitPriceUsd,isActive:t.isActive})),count:e.count}}async recordRun(e){let t=Date.now(),s=e.workflow,i=e.workflow;if(!e.workflow.startsWith("wf_"))try{let g=(await this.listWorkflows()).data.find(l=>l.slug===e.workflow||l.id===e.workflow);if(g)s=g.id,i=g.name;else {let l=await this.createWorkflow({name:e.workflow.replace(/[_-]/g," ").replace(/\b\w/g,b=>b.toUpperCase()),slug:e.workflow,productSurface:"AGENT"});s=l.id,i=l.name;}}catch{s=e.workflow;}let n=await this.startRun({customerId:e.customerId,workflowId:s,externalRunId:e.externalRunId,correlationId:e.correlationId,metadata:e.metadata}),o=0,u=0;if(e.events.length>0){let R=e.events.map((l,b)=>({runId:n.id,eventType:l.eventType,quantity:l.quantity,units:l.units,description:l.description,costUnits:l.costUnits,metadata:l.metadata,idempotencyKey:e.externalRunId?`${e.externalRunId}:${l.eventType}:${b}`:void 0})),g=await this.emitEventsBatch(R);o=g.created,u=g.duplicates;}let c=await this.endRun(n.id,{status:e.status,errorMessage:e.errorMessage,errorCode:e.errorCode}),d=Date.now()-t,a=e.events.length>0?`${o} events recorded`:"no events",m=`${e.status==="COMPLETED"?"\u2713":e.status==="FAILED"?"\u2717":"\u25CB"} ${i}: ${a} (${c.durationMs??d}ms)`;return {run:{id:n.id,workflowId:s,workflowName:i,status:e.status,durationMs:c.durationMs},events:{created:o,duplicates:u},totalCostUnits:c.totalCostUnits,summary:m}}static generateIdempotencyKey(e){let t=[e.customerId,e.runId??"no_run",e.stepName,String(e.sequence??0)],s=0,i=t.join("|");for(let n=0;n<i.length;n++){let o=i.charCodeAt(n);s=(s<<5)-s+o,s=s&s;}return `drip_${Math.abs(s).toString(36)}_${e.stepName.slice(0,16)}`}static async verifyWebhookSignature(e,t,s,i=300){if(!e||!t||!s)return false;try{let n=t.split(","),o=n.find(w=>w.startsWith("t=")),u=n.find(w=>w.startsWith("v1="));if(!o||!u)return !1;let c=parseInt(o.slice(2),10),d=u.slice(3);if(isNaN(c))return !1;let a=Math.floor(Date.now()/1e3);if(Math.abs(a-c)>i)return !1;let p=`${c}.${e}`,m=new TextEncoder,R=m.encode(s),g=m.encode(p),l=globalThis.crypto?.subtle??I("crypto").webcrypto.subtle,b=await l.importKey("raw",R,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),N=await l.sign("HMAC",b,g),T=Array.from(new Uint8Array(N)).map(w=>w.toString(16).padStart(2,"0")).join("");if(d.length!==T.length)return !1;let q=0;for(let w=0;w<d.length;w++)q|=d.charCodeAt(w)^T.charCodeAt(w);return q===0}catch{return false}}static verifyWebhookSignatureSync(e,t,s,i=300){if(!e||!t||!s)return false;try{let n=t.split(","),o=n.find(b=>b.startsWith("t=")),u=n.find(b=>b.startsWith("v1="));if(!o||!u)return !1;let c=parseInt(o.slice(2),10),d=u.slice(3);if(isNaN(c))return !1;let a=Math.floor(Date.now()/1e3);if(Math.abs(a-c)>i)return !1;let p=I("crypto"),m=`${c}.${e}`,R=p.createHmac("sha256",s).update(m).digest("hex"),g=Buffer.from(d),l=Buffer.from(R);return g.length!==l.length?!1:p.timingSafeEqual(g,l)}catch{return false}}static generateWebhookSignature(e,t,s){let i=I("crypto"),n=s??Math.floor(Date.now()/1e3),o=`${n}.${e}`,u=i.createHmac("sha256",t).update(o).digest("hex");return `t=${n},v1=${u}`}createStreamMeter(e){return new P(this.charge.bind(this),e)}};var h=class r extends Error{constructor(t,s,i,n){super(t);this.code=s;this.statusCode=i;this.details=n;this.name="DripMiddlewareError",Object.setPrototypeOf(this,r.prototype);}};var W=300,L=300,K=["x-payment-signature","x-payment-session-key","x-payment-smart-account","x-payment-timestamp","x-payment-amount","x-payment-recipient","x-payment-usage-id","x-payment-nonce"];function $(r){return r.toLowerCase()}function y(r,e){let t=$(e);if(r[t]!==void 0){let s=r[t];return Array.isArray(s)?s[0]:s}for(let[s,i]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(i)?i[0]:i}function D(r){return K.every(e=>y(r,e)!==void 0)}function H(r){let e=y(r,"x-payment-signature"),t=y(r,"x-payment-session-key"),s=y(r,"x-payment-smart-account"),i=y(r,"x-payment-timestamp"),n=y(r,"x-payment-amount"),o=y(r,"x-payment-recipient"),u=y(r,"x-payment-usage-id"),c=y(r,"x-payment-nonce");if(!e||!t||!s||!i||!n||!o||!u||!c)return null;let d=parseInt(i,10);if(isNaN(d)||Math.floor(Date.now()/1e3)-d>L)return null;let p=(m,R)=>{if(!m.startsWith("0x"))return false;let g=m.slice(2);return g.length<R?false:/^[a-fA-F0-9]+$/.test(g)};return !p(e,130)||!p(t,64)||!p(s,40)?null:{signature:e,sessionKeyId:t,smartAccount:s,timestamp:d,amount:n,recipient:o,usageId:u,nonce:c}}function F(r){let e=Math.floor(Date.now()/1e3),t=e+(r.expiresInSec??W),s=`${e}-${crypto.randomBytes(16).toString("hex")}`,i=r.usageId;i.startsWith("0x")||(i=S(i));let n={"X-Payment-Required":"true","X-Payment-Amount":r.amount,"X-Payment-Recipient":r.recipient,"X-Payment-Usage-Id":i,"X-Payment-Description":r.description??"API usage charge","X-Payment-Expires":String(t),"X-Payment-Nonce":s,"X-Payment-Timestamp":String(e)},o={amount:r.amount,recipient:r.recipient,usageId:i,description:r.description??"API usage charge",expiresAt:t,nonce:s,timestamp:e};return {headers:n,paymentRequest:o}}function S(r){let e=5381,t=52711;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);e=(e<<5)+e^o,t=(t<<5)+t^o;}return `0x${Math.abs(e*31+t).toString(16).padStart(16,"0").slice(0,16).padEnd(64,"0")}`}async function X(r,e){let t=e.customerResolver??"header";if(typeof t=="function")return t(r);if(t==="header"){let s=y(r.headers,"x-drip-customer-id")??y(r.headers,"x-customer-id");if(!s)throw new h("Missing customer ID. Include X-Drip-Customer-Id header.","CUSTOMER_RESOLUTION_FAILED",400);return s}if(t==="query"){let s=r.query??{},i=s.drip_customer_id??s.customer_id,n=Array.isArray(i)?i[0]:i;if(!n)throw new h("Missing customer ID. Include drip_customer_id query parameter.","CUSTOMER_RESOLUTION_FAILED",400);return n}throw new h(`Invalid customer resolver: ${t}`,"CONFIGURATION_ERROR",500)}async function j(r,e){return typeof e.quantity=="function"?e.quantity(r):e.quantity}async function B(r,e,t){if(t.idempotencyKey)return t.idempotencyKey(r);let s=Date.now(),i=[r.method,r.url,e,s];return `drip_${S(i.join("|")).slice(2,18)}`}function A(r){let e=r.apiKey??process.env.DRIP_API_KEY;if(!e)throw new h("Missing Drip API key. Set DRIP_API_KEY environment variable or pass apiKey in config.","CONFIGURATION_ERROR",500);return new C({apiKey:e,baseUrl:r.baseUrl??process.env.DRIP_API_URL})}async function v(r,e){if(e.skipInDevelopment&&process.env.NODE_ENV==="development"){console.warn("[Drip] Skipping billing in development mode. Set skipInDevelopment: false or NODE_ENV to production to enable billing.");let t=A(e),s={success:true,usageEventId:"dev_usage_event",isReplay:false,charge:{id:"dev_charge",amountUsdc:"0.00",amountToken:"0",txHash:"0x0",status:"CONFIRMED"}};return {success:true,state:{customerId:"dev_customer",quantity:typeof e.quantity=="number"?e.quantity:1,idempotencyKey:"dev_idempotency",hasPaymentProof:false},charge:s,drip:t,isReplay:false}}try{let t=A(e),s=await X(r,e),i=await j(r,e),n=await B(r,s,e),o=D(r.headers),u=o?H(r.headers):void 0,c={customerId:s,quantity:i,idempotencyKey:n,hasPaymentProof:o,paymentProof:u??void 0},d=typeof e.metadata=="function"?e.metadata(r):e.metadata;try{let a=await t.charge({customerId:s,meter:e.meter,quantity:i,idempotencyKey:n,metadata:d});return e.onCharge&&await e.onCharge(a,r),{success:!0,state:c,charge:a,drip:t,isReplay:a.isReplay??!1}}catch(a){if(a instanceof f){if(a.statusCode===402){let p=process.env.DRIP_RECIPIENT_ADDRESS;if(!p)throw new h("DRIP_RECIPIENT_ADDRESS environment variable must be configured for x402 payment flow.","CONFIGURATION_ERROR",500);let m="0.01",R=a.message.match(/amount[:\s]+([0-9.]+)/i);R?m=R[1]:m=(i*1e-4).toFixed(6);let{headers:g,paymentRequest:l}=F({amount:m,recipient:p,usageId:n,description:`${e.meter} usage charge`});return {success:!1,error:new h("Insufficient balance. Payment required.","PAYMENT_REQUIRED",402),paymentRequired:{headers:g,paymentRequest:l}}}throw e.onError&&await e.onError(a,r),new h(a.message,"CHARGE_FAILED",a.statusCode,{code:a.code})}throw a}}catch(t){if(t instanceof h)return {success:false,error:t};let s=t instanceof Error?t.message:"Unknown error";return {success:false,error:new h(s,"INTERNAL_ERROR",500)}}}function k(r){let e={};return r.forEach((t,s)=>{e[s.toLowerCase()]=t;}),e}function G(r){let e={};return r.forEach((t,s)=>{e[s]=t;}),e}function J(r,e,t,s){return Response.json({error:r,code:e,...s&&{details:s}},{status:t})}function Y(r,e){let t=new Headers;return Object.entries(r).forEach(([s,i])=>{t.set(s,i);}),t.set("Content-Type","application/json"),new Response(JSON.stringify({error:"Payment required",code:"PAYMENT_REQUIRED",paymentRequest:e,instructions:{step1:"Sign the payment request with your session key using EIP-712",step2:"Retry the request with X-Payment-* headers",documentation:"https://docs.drip.dev/x402"}}),{status:402,headers:t})}function _(r,e){return async(t,s)=>{let i={method:t.method,url:t.url,headers:k(t.headers),query:t.nextUrl?G(t.nextUrl.searchParams):{}},n=typeof r.quantity=="function"?await r.quantity(t):r.quantity,o;if(typeof r.customerResolver=="function"){let m=r.customerResolver;o=async()=>m(t);}else o=r.customerResolver;let u;if(typeof r.idempotencyKey=="function"){let m=r.idempotencyKey;u=async()=>m(t);}let c=typeof r.metadata=="function"?r.metadata(t):r.metadata,d={meter:r.meter,quantity:n,apiKey:r.apiKey,baseUrl:r.baseUrl,customerResolver:o,idempotencyKey:u,metadata:c,skipInDevelopment:r.skipInDevelopment,onCharge:void 0,onError:void 0},a=await v(i,d);if(!a.success){if(r.errorResponse){let m=await r.errorResponse(a.error,t);if(m)return m}return a.paymentRequired?Y(a.paymentRequired.headers,a.paymentRequired.paymentRequest):J(a.error.message,a.error.code,a.error.statusCode,a.error.details)}r.onCharge&&await r.onCharge(a.charge,t);let p={drip:a.drip,customerId:a.state.customerId,charge:a.charge,isReplay:a.isReplay,params:s?.params};try{return await e(t,p)}catch(m){throw m}}}function Q(r){return (e,t)=>_({...r,...e},t)}function V(r){return D(k(r.headers))}function z(r,e){return y(k(r.headers),e)}
2
- exports.Drip=C;exports.DripError=f;exports.DripMiddlewareError=h;exports.createWithDrip=Q;exports.getDripHeader=z;exports.hasPaymentProofHeaders=V;exports.withDrip=_;//# sourceMappingURL=next.cjs.map
1
+ 'use strict';var crypto=require('crypto');var q=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var E=class{_total=0;_flushed=false;_flushCount=0;_chargeFn;_options;constructor(e,t){this._chargeFn=e,this._options=t;}get total(){return this._total}get isFlushed(){return this._flushed}get flushCount(){return this._flushCount}async add(e){return e<=0?null:(this._total+=e,this._options.onAdd?.(e,this._total),this._options.flushThreshold!==void 0&&this._total>=this._options.flushThreshold?this.flush():null)}addSync(e){e<=0||(this._total+=e,this._options.onAdd?.(e,this._total));}async flush(){let e=this._total;if(this._total=0,e===0)return {success:true,quantity:0,charge:null,isReplay:false};let t=this._options.idempotencyKey?`${this._options.idempotencyKey}_flush_${this._flushCount}`:void 0,s=await this._chargeFn({customerId:this._options.customerId,meter:this._options.meter,quantity:e,idempotencyKey:t,metadata:this._options.metadata});this._flushed=true,this._flushCount++;let i={success:s.success,quantity:e,charge:s.charge,isReplay:s.isReplay};return this._options.onFlush?.(i),i}reset(){this._total=0;}};var X={requestsPerSecond:100,burstSize:200,enabled:true},T=class{config;tokens;lastRefill;constructor(e){this.config={...X,...e},this.tokens=this.config.burstSize,this.lastRefill=Date.now();}refill(){let e=Date.now(),t=(e-this.lastRefill)/1e3;this.tokens=Math.min(this.config.burstSize,this.tokens+t*this.config.requestsPerSecond),this.lastRefill=e;}async acquire(e){if(!this.config.enabled)return true;let t=e!==void 0?Date.now()+e:void 0;for(;;){if(this.refill(),this.tokens>=1)return this.tokens-=1,true;let s=(1-this.tokens)/this.config.requestsPerSecond*1e3;if(t!==void 0){let i=t-Date.now();if(i<=0)return false;await this.sleep(Math.min(s,i));}else await this.sleep(s);}}tryAcquire(){return this.config.enabled?(this.refill(),this.tokens>=1?(this.tokens-=1,true):false):true}get availableTokens(){return this.refill(),this.tokens}sleep(e){return new Promise(t=>setTimeout(t,e))}};var S=class r extends Error{attempts;lastError;constructor(e,t){super(`Retry exhausted after ${e} attempts: ${t.message}`),this.name="RetryExhaustedError",this.attempts=e,this.lastError=t,Object.setPrototypeOf(this,r.prototype);}};function L(r,e){let t=e.baseDelayMs*Math.pow(e.exponentialBase,r);if(t=Math.min(t,e.maxDelayMs),e.jitter>0){let s=t*e.jitter;t+=Math.random()*2*s-s;}return Math.max(0,t)}function F(r,e){if(r instanceof Error){if(r.message.includes("fetch")||r.message.includes("network")||r.message.includes("ECONNREFUSED")||r.message.includes("ETIMEDOUT"))return true;let t=r.statusCode;if(t!==void 0)return e.retryableStatusCodes.includes(t)}return false}var j={failureThreshold:5,successThreshold:2,timeoutMs:3e4,enabled:true},k=class r extends Error{circuitName;timeUntilRetryMs;constructor(e,t){super(`Circuit '${e}' is open. Retry in ${Math.round(t)}ms`),this.name="CircuitBreakerOpenError",this.circuitName=e,this.timeUntilRetryMs=t,Object.setPrototypeOf(this,r.prototype);}},D=class{name;config;state="closed";failureCount=0;successCount=0;lastFailureTime=null;constructor(e,t){this.name=e,this.config={...j,...t};}getState(){return this.checkStateTransition(),this.state}checkStateTransition(){this.state==="open"&&this.lastFailureTime!==null&&Date.now()-this.lastFailureTime>=this.config.timeoutMs&&(this.state="half_open",this.successCount=0);}recordSuccess(){this.config.enabled&&(this.state==="half_open"?(this.successCount+=1,this.successCount>=this.config.successThreshold&&(this.state="closed",this.failureCount=0)):this.state==="closed"&&(this.failureCount=0));}recordFailure(){this.config.enabled&&(this.failureCount+=1,this.lastFailureTime=Date.now(),this.state==="half_open"?this.state="open":this.state==="closed"&&this.failureCount>=this.config.failureThreshold&&(this.state="open"));}allowRequest(){return !this.config.enabled||(this.checkStateTransition(),this.state==="closed")?true:this.state==="half_open"}getTimeUntilRetry(){if(this.state!=="open"||this.lastFailureTime===null)return 0;let e=Date.now()-this.lastFailureTime;return Math.max(0,this.config.timeoutMs-e)}reset(){this.state="closed",this.failureCount=0,this.successCount=0,this.lastFailureTime=null;}},M=class{windowSize;metrics=[];totalRequests=0;totalSuccesses=0;totalFailures=0;constructor(e=1e3){this.windowSize=e;}record(e){for(this.metrics.push(e),this.totalRequests+=1,e.success?this.totalSuccesses+=1:this.totalFailures+=1;this.metrics.length>this.windowSize;)this.metrics.shift();}getSummary(){if(this.metrics.length===0)return {windowSize:0,totalRequests:0,totalSuccesses:0,totalFailures:0,successRate:0,avgLatencyMs:0,minLatencyMs:0,maxLatencyMs:0,p50LatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,requestsByEndpoint:{},errorsByType:{}};let e=this.metrics.map(o=>o.durationMs).sort((o,u)=>o-u),t=this.metrics.filter(o=>o.success).length,s={};for(let o of this.metrics)s[o.endpoint]=(s[o.endpoint]??0)+1;let i={};for(let o of this.metrics)o.error&&(i[o.error]=(i[o.error]??0)+1);let n=e.reduce((o,u)=>o+u,0);return {windowSize:this.metrics.length,totalRequests:this.totalRequests,totalSuccesses:this.totalSuccesses,totalFailures:this.totalFailures,successRate:t/this.metrics.length*100,avgLatencyMs:n/e.length,minLatencyMs:e[0],maxLatencyMs:e[e.length-1],p50LatencyMs:e[Math.floor(e.length*.5)],p95LatencyMs:e[Math.floor(e.length*.95)],p99LatencyMs:e[Math.floor(e.length*.99)],requestsByEndpoint:s,errorsByType:i}}reset(){this.metrics.length=0,this.totalRequests=0,this.totalSuccesses=0,this.totalFailures=0;}};function w(){return {rateLimiter:{requestsPerSecond:100,burstSize:200,enabled:true},retry:{maxRetries:3,baseDelayMs:100,maxDelayMs:1e4,exponentialBase:2,jitter:.1,retryableStatusCodes:[429,500,502,503,504],enabled:true},circuitBreaker:{failureThreshold:5,successThreshold:2,timeoutMs:3e4,enabled:true},collectMetrics:true}}function v(){return {rateLimiter:{requestsPerSecond:1e3,burstSize:2e3,enabled:true},retry:{maxRetries:2,baseDelayMs:50,maxDelayMs:5e3,exponentialBase:2,jitter:.1,retryableStatusCodes:[429,500,502,503,504],enabled:true},circuitBreaker:{failureThreshold:10,successThreshold:3,timeoutMs:15e3,enabled:true},collectMetrics:true}}var x=class{config;rateLimiter;circuitBreaker;metrics;constructor(e){this.config={...w(),...e,rateLimiter:{...w().rateLimiter,...e?.rateLimiter},retry:{...w().retry,...e?.retry},circuitBreaker:{...w().circuitBreaker,...e?.circuitBreaker}},this.rateLimiter=new T(this.config.rateLimiter),this.circuitBreaker=new D("drip_api",this.config.circuitBreaker),this.metrics=this.config.collectMetrics?new M:null;}async execute(e,t="UNKNOWN",s="unknown"){let i=performance.now(),n=0,o=null;if(!await this.rateLimiter.acquire(3e4))throw new Error("Rate limiter timeout");if(!this.circuitBreaker.allowRequest())throw new k(this.circuitBreaker.name,this.circuitBreaker.getTimeUntilRetry());for(let l=0;l<=this.config.retry.maxRetries;l++)try{let c=await e();if(this.circuitBreaker.recordSuccess(),this.metrics){let a=performance.now()-i;this.metrics.record({method:t,endpoint:s,statusCode:200,durationMs:a,success:!0,timestamp:Date.now(),retryCount:n});}return c}catch(c){if(o=c instanceof Error?c:new Error(String(c)),this.config.retry.enabled&&F(c,this.config.retry)&&l<this.config.retry.maxRetries){n+=1;let g=L(l,this.config.retry);await this.sleep(g);continue}if(this.circuitBreaker.recordFailure(),this.metrics){let g=performance.now()-i,m=c.statusCode??null;this.metrics.record({method:t,endpoint:s,statusCode:m,durationMs:g,success:false,timestamp:Date.now(),error:o.name,retryCount:n});}throw c}throw o?new S(this.config.retry.maxRetries+1,o):new Error("Unexpected execution path")}getMetrics(){return this.metrics?.getSummary()??null}getHealth(){return {circuitBreaker:{state:this.circuitBreaker.getState(),timeUntilRetryMs:this.circuitBreaker.getTimeUntilRetry()},rateLimiter:{availableTokens:this.rateLimiter.availableTokens,requestsPerSecond:this.config.rateLimiter.requestsPerSecond},metrics:this.getMetrics()}}sleep(e){return new Promise(t=>setTimeout(t,e))}};var A={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3};function G(r){return r instanceof Error&&(r.message.includes("fetch")||r.message.includes("network"))?true:r instanceof y?r.statusCode>=500||r.statusCode===408||r.statusCode===429:false}async function z(r,e={}){let t=e.maxAttempts??A.maxAttempts,s=e.baseDelayMs??A.baseDelayMs,i=e.maxDelayMs??A.maxDelayMs,n=e.isRetryable??G,o;for(let u=1;u<=t;u++)try{return await r()}catch(l){if(o=l,u===t||!n(l))throw l;let c=Math.min(s*Math.pow(2,u-1)+Math.random()*100,i);await new Promise(a=>setTimeout(a,c));}throw o}var y=class r extends Error{constructor(t,s,i){super(t);this.statusCode=s;this.code=i;this.name="DripError",Object.setPrototypeOf(this,r.prototype);}},I=class{apiKey;baseUrl;timeout;resilience;constructor(e){if(!e.apiKey)throw new Error("Drip API key is required");this.apiKey=e.apiKey,this.baseUrl=e.baseUrl||"https://api.drip.dev/v1",this.timeout=e.timeout||3e4,e.resilience===true?this.resilience=new x(w()):e.resilience==="high-throughput"?this.resilience=new x(v()):e.resilience&&typeof e.resilience=="object"?this.resilience=new x(e.resilience):this.resilience=null;}async request(e,t={}){let s=(t.method??"GET").toUpperCase();return this.resilience?this.resilience.execute(()=>this.rawRequest(e,t),s,e):this.rawRequest(e,t)}async rawRequest(e,t={}){let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeout);try{let n=await fetch(`${this.baseUrl}${e}`,{...t,signal:s.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(n.status===204)return {success:!0};let o=await n.json();if(!n.ok)throw new y(o.message||o.error||"Request failed",n.status,o.code);return o}catch(n){throw n instanceof y?n:n instanceof Error&&n.name==="AbortError"?new y("Request timed out",408,"TIMEOUT"):new y(n instanceof Error?n.message:"Unknown error",0,"UNKNOWN")}finally{clearTimeout(i);}}async ping(){let e=new AbortController,t=setTimeout(()=>e.abort(),this.timeout),s=this.baseUrl;s.endsWith("/v1/")?s=s.slice(0,-4):s.endsWith("/v1")&&(s=s.slice(0,-3)),s=s.replace(/\/+$/,"");let i=Date.now();try{let n=await fetch(`${s}/health`,{signal:e.signal,headers:{Authorization:`Bearer ${this.apiKey}`}}),o=Date.now()-i,u="unknown",l=Date.now();try{let c=await n.json();typeof c.status=="string"&&(u=c.status),typeof c.timestamp=="number"&&(l=c.timestamp);}catch{u=n.ok?"healthy":`error:${n.status}`;}return !n.ok&&u==="unknown"&&(u=`error:${n.status}`),{ok:n.ok&&u==="healthy",status:u,latencyMs:o,timestamp:l}}catch(n){throw n instanceof Error&&n.name==="AbortError"?new y("Request timed out",408,"TIMEOUT"):new y(n instanceof Error?n.message:"Unknown error",0,"UNKNOWN")}finally{clearTimeout(t);}}getMetrics(){return this.resilience?.getMetrics()??null}getHealth(){return this.resilience?.getHealth()??null}async createCustomer(e){return this.request("/customers",{method:"POST",body:JSON.stringify(e)})}async getCustomer(e){return this.request(`/customers/${e}`)}async listCustomers(e){let t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.status&&t.set("status",e.status);let s=t.toString(),i=s?`/customers?${s}`:"/customers";return this.request(i)}async getBalance(e){return this.request(`/customers/${e}/balance`)}async charge(e){return this.request("/usage",{method:"POST",body:JSON.stringify({customerId:e.customerId,usageType:e.meter,quantity:e.quantity,idempotencyKey:e.idempotencyKey,metadata:e.metadata})})}async wrapApiCall(e){let t=e.idempotencyKey??`wrap_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,s=await e.call(),i=e.extractUsage(s),n=await z(()=>this.charge({customerId:e.customerId,meter:e.meter,quantity:i,idempotencyKey:t,metadata:e.metadata}),e.retryOptions);return {result:s,charge:n,idempotencyKey:t}}async trackUsage(e){return this.request("/usage/internal",{method:"POST",body:JSON.stringify({customerId:e.customerId,usageType:e.meter,quantity:e.quantity,idempotencyKey:e.idempotencyKey,units:e.units,description:e.description,metadata:e.metadata})})}async getCharge(e){return this.request(`/charges/${e}`)}async listCharges(e){let t=new URLSearchParams;e?.customerId&&t.set("customerId",e.customerId),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",e.limit.toString()),e?.offset&&t.set("offset",e.offset.toString());let s=t.toString(),i=s?`/charges?${s}`:"/charges";return this.request(i)}async getChargeStatus(e){return this.request(`/charges/${e}/status`)}async checkout(e){let t=await this.request("/checkout",{method:"POST",body:JSON.stringify({customer_id:e.customerId,external_customer_id:e.externalCustomerId,amount:e.amount,return_url:e.returnUrl,cancel_url:e.cancelUrl,metadata:e.metadata})});return {id:t.id,url:t.url,expiresAt:t.expires_at,amountUsd:t.amount_usd}}async createWebhook(e){return this.request("/webhooks",{method:"POST",body:JSON.stringify(e)})}async listWebhooks(){return this.request("/webhooks")}async getWebhook(e){return this.request(`/webhooks/${e}`)}async deleteWebhook(e){return this.request(`/webhooks/${e}`,{method:"DELETE"})}async testWebhook(e){return this.request(`/webhooks/${e}/test`,{method:"POST"})}async rotateWebhookSecret(e){return this.request(`/webhooks/${e}/rotate-secret`,{method:"POST"})}async createWorkflow(e){return this.request("/workflows",{method:"POST",body:JSON.stringify(e)})}async listWorkflows(){return this.request("/workflows")}async startRun(e){return this.request("/runs",{method:"POST",body:JSON.stringify(e)})}async endRun(e,t){return this.request(`/runs/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async getRunTimeline(e){return this.request(`/runs/${e}`)}async emitEvent(e){return this.request("/events",{method:"POST",body:JSON.stringify(e)})}async emitEventsBatch(e){return this.request("/run-events/batch",{method:"POST",body:JSON.stringify({events:e})})}async listMeters(){let e=await this.request("/pricing-plans");return {data:e.data.map(t=>({id:t.id,name:t.name,meter:t.unitType,unitPriceUsd:t.unitPriceUsd,isActive:t.isActive})),count:e.count}}async estimateFromUsage(e){let t=e.periodStart instanceof Date?e.periodStart.toISOString():e.periodStart,s=e.periodEnd instanceof Date?e.periodEnd.toISOString():e.periodEnd;return this.request("/dashboard/cost-estimate/from-usage",{method:"POST",body:JSON.stringify({customerId:e.customerId,periodStart:t,periodEnd:s,defaultUnitPrice:e.defaultUnitPrice,includeChargedEvents:e.includeChargedEvents,usageTypes:e.usageTypes,customPricing:e.customPricing})})}async estimateFromHypothetical(e){return this.request("/dashboard/cost-estimate/hypothetical",{method:"POST",body:JSON.stringify({items:e.items,defaultUnitPrice:e.defaultUnitPrice,customPricing:e.customPricing})})}async recordRun(e){let t=Date.now(),s=e.workflow,i=e.workflow;if(!e.workflow.startsWith("wf_"))try{let p=(await this.listWorkflows()).data.find(d=>d.slug===e.workflow||d.id===e.workflow);if(p)s=p.id,i=p.name;else {let d=await this.createWorkflow({name:e.workflow.replace(/[_-]/g," ").replace(/\b\w/g,b=>b.toUpperCase()),slug:e.workflow,productSurface:"AGENT"});s=d.id,i=d.name;}}catch{s=e.workflow;}let n=await this.startRun({customerId:e.customerId,workflowId:s,externalRunId:e.externalRunId,correlationId:e.correlationId,metadata:e.metadata}),o=0,u=0;if(e.events.length>0){let R=e.events.map((d,b)=>({runId:n.id,eventType:d.eventType,quantity:d.quantity,units:d.units,description:d.description,costUnits:d.costUnits,metadata:d.metadata,idempotencyKey:e.externalRunId?`${e.externalRunId}:${d.eventType}:${b}`:void 0})),p=await this.emitEventsBatch(R);o=p.created,u=p.duplicates;}let l=await this.endRun(n.id,{status:e.status,errorMessage:e.errorMessage,errorCode:e.errorCode}),c=Date.now()-t,a=e.events.length>0?`${o} events recorded`:"no events",m=`${e.status==="COMPLETED"?"\u2713":e.status==="FAILED"?"\u2717":"\u25CB"} ${i}: ${a} (${l.durationMs??c}ms)`;return {run:{id:n.id,workflowId:s,workflowName:i,status:e.status,durationMs:l.durationMs},events:{created:o,duplicates:u},totalCostUnits:l.totalCostUnits,summary:m}}static generateIdempotencyKey(e){let t=[e.customerId,e.runId??"no_run",e.stepName,String(e.sequence??0)],s=0,i=t.join("|");for(let n=0;n<i.length;n++){let o=i.charCodeAt(n);s=(s<<5)-s+o,s=s&s;}return `drip_${Math.abs(s).toString(36)}_${e.stepName.slice(0,16)}`}static async verifyWebhookSignature(e,t,s,i=300){if(!e||!t||!s)return false;try{let n=t.split(","),o=n.find(C=>C.startsWith("t=")),u=n.find(C=>C.startsWith("v1="));if(!o||!u)return !1;let l=parseInt(o.slice(2),10),c=u.slice(3);if(isNaN(l))return !1;let a=Math.floor(Date.now()/1e3);if(Math.abs(a-l)>i)return !1;let g=`${l}.${e}`,m=new TextEncoder,R=m.encode(s),p=m.encode(g),d=globalThis.crypto?.subtle??q("crypto").webcrypto.subtle,b=await d.importKey("raw",R,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),$=await d.sign("HMAC",b,p),N=Array.from(new Uint8Array($)).map(C=>C.toString(16).padStart(2,"0")).join("");if(c.length!==N.length)return !1;let O=0;for(let C=0;C<c.length;C++)O|=c.charCodeAt(C)^N.charCodeAt(C);return O===0}catch{return false}}static verifyWebhookSignatureSync(e,t,s,i=300){if(!e||!t||!s)return false;try{let n=t.split(","),o=n.find(b=>b.startsWith("t=")),u=n.find(b=>b.startsWith("v1="));if(!o||!u)return !1;let l=parseInt(o.slice(2),10),c=u.slice(3);if(isNaN(l))return !1;let a=Math.floor(Date.now()/1e3);if(Math.abs(a-l)>i)return !1;let g=q("crypto"),m=`${l}.${e}`,R=g.createHmac("sha256",s).update(m).digest("hex"),p=Buffer.from(c),d=Buffer.from(R);return p.length!==d.length?!1:g.timingSafeEqual(p,d)}catch{return false}}static generateWebhookSignature(e,t,s){let i=q("crypto"),n=s??Math.floor(Date.now()/1e3),o=`${n}.${e}`,u=i.createHmac("sha256",t).update(o).digest("hex");return `t=${n},v1=${u}`}createStreamMeter(e){return new E(this.charge.bind(this),e)}};var h=class r extends Error{constructor(t,s,i,n){super(t);this.code=s;this.statusCode=i;this.details=n;this.name="DripMiddlewareError",Object.setPrototypeOf(this,r.prototype);}};var Y=300,Q=300,V=["x-payment-signature","x-payment-session-key","x-payment-smart-account","x-payment-timestamp","x-payment-amount","x-payment-recipient","x-payment-usage-id","x-payment-nonce"];function Z(r){return r.toLowerCase()}function f(r,e){let t=Z(e);if(r[t]!==void 0){let s=r[t];return Array.isArray(s)?s[0]:s}for(let[s,i]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(i)?i[0]:i}function U(r){return V.every(e=>f(r,e)!==void 0)}function ee(r){let e=f(r,"x-payment-signature"),t=f(r,"x-payment-session-key"),s=f(r,"x-payment-smart-account"),i=f(r,"x-payment-timestamp"),n=f(r,"x-payment-amount"),o=f(r,"x-payment-recipient"),u=f(r,"x-payment-usage-id"),l=f(r,"x-payment-nonce");if(!e||!t||!s||!i||!n||!o||!u||!l)return null;let c=parseInt(i,10);if(isNaN(c)||Math.floor(Date.now()/1e3)-c>Q)return null;let g=(m,R)=>{if(!m.startsWith("0x"))return false;let p=m.slice(2);return p.length<R?false:/^[a-fA-F0-9]+$/.test(p)};return !g(e,130)||!g(t,64)||!g(s,40)?null:{signature:e,sessionKeyId:t,smartAccount:s,timestamp:c,amount:n,recipient:o,usageId:u,nonce:l}}function te(r){let e=Math.floor(Date.now()/1e3),t=e+(r.expiresInSec??Y),s=`${e}-${crypto.randomBytes(16).toString("hex")}`,i=r.usageId;i.startsWith("0x")||(i=B(i));let n={"X-Payment-Required":"true","X-Payment-Amount":r.amount,"X-Payment-Recipient":r.recipient,"X-Payment-Usage-Id":i,"X-Payment-Description":r.description??"API usage charge","X-Payment-Expires":String(t),"X-Payment-Nonce":s,"X-Payment-Timestamp":String(e)},o={amount:r.amount,recipient:r.recipient,usageId:i,description:r.description??"API usage charge",expiresAt:t,nonce:s,timestamp:e};return {headers:n,paymentRequest:o}}function B(r){let e=5381,t=52711;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);e=(e<<5)+e^o,t=(t<<5)+t^o;}return `0x${Math.abs(e*31+t).toString(16).padStart(16,"0").slice(0,16).padEnd(64,"0")}`}async function re(r,e){let t=e.customerResolver??"header";if(typeof t=="function")return t(r);if(t==="header"){let s=f(r.headers,"x-drip-customer-id")??f(r.headers,"x-customer-id");if(!s)throw new h("Missing customer ID. Include X-Drip-Customer-Id header.","CUSTOMER_RESOLUTION_FAILED",400);return s}if(t==="query"){let s=r.query??{},i=s.drip_customer_id??s.customer_id,n=Array.isArray(i)?i[0]:i;if(!n)throw new h("Missing customer ID. Include drip_customer_id query parameter.","CUSTOMER_RESOLUTION_FAILED",400);return n}throw new h(`Invalid customer resolver: ${t}`,"CONFIGURATION_ERROR",500)}async function se(r,e){return typeof e.quantity=="function"?e.quantity(r):e.quantity}async function ne(r,e,t){if(t.idempotencyKey)return t.idempotencyKey(r);let s=Date.now(),i=[r.method,r.url,e,s];return `drip_${B(i.join("|")).slice(2,18)}`}function W(r){let e=r.apiKey??process.env.DRIP_API_KEY;if(!e)throw new h("Missing Drip API key. Set DRIP_API_KEY environment variable or pass apiKey in config.","CONFIGURATION_ERROR",500);return new I({apiKey:e,baseUrl:r.baseUrl??process.env.DRIP_API_URL})}async function H(r,e){if(e.skipInDevelopment&&process.env.NODE_ENV==="development"){console.warn("[Drip] Skipping billing in development mode. Set skipInDevelopment: false or NODE_ENV to production to enable billing.");let t=W(e),s={success:true,usageEventId:"dev_usage_event",isReplay:false,charge:{id:"dev_charge",amountUsdc:"0.00",amountToken:"0",txHash:"0x0",status:"CONFIRMED"}};return {success:true,state:{customerId:"dev_customer",quantity:typeof e.quantity=="number"?e.quantity:1,idempotencyKey:"dev_idempotency",hasPaymentProof:false},charge:s,drip:t,isReplay:false}}try{let t=W(e),s=await re(r,e),i=await se(r,e),n=await ne(r,s,e),o=U(r.headers),u=o?ee(r.headers):void 0,l={customerId:s,quantity:i,idempotencyKey:n,hasPaymentProof:o,paymentProof:u??void 0},c=typeof e.metadata=="function"?e.metadata(r):e.metadata;try{let a=await t.charge({customerId:s,meter:e.meter,quantity:i,idempotencyKey:n,metadata:c});return e.onCharge&&await e.onCharge(a,r),{success:!0,state:l,charge:a,drip:t,isReplay:a.isReplay??!1}}catch(a){if(a instanceof y){if(a.statusCode===402){let g=process.env.DRIP_RECIPIENT_ADDRESS;if(!g)throw new h("DRIP_RECIPIENT_ADDRESS environment variable must be configured for x402 payment flow.","CONFIGURATION_ERROR",500);let m="0.01",R=a.message.match(/amount[:\s]+([0-9.]+)/i);R?m=R[1]:m=(i*1e-4).toFixed(6);let{headers:p,paymentRequest:d}=te({amount:m,recipient:g,usageId:n,description:`${e.meter} usage charge`});return {success:!1,error:new h("Insufficient balance. Payment required.","PAYMENT_REQUIRED",402),paymentRequired:{headers:p,paymentRequest:d}}}throw e.onError&&await e.onError(a,r),new h(a.message,"CHARGE_FAILED",a.statusCode,{code:a.code})}throw a}}catch(t){if(t instanceof h)return {success:false,error:t};let s=t instanceof Error?t.message:"Unknown error";return {success:false,error:new h(s,"INTERNAL_ERROR",500)}}}function _(r){let e={};return r.forEach((t,s)=>{e[s.toLowerCase()]=t;}),e}function ie(r){let e={};return r.forEach((t,s)=>{e[s]=t;}),e}function oe(r,e,t,s){return Response.json({error:r,code:e,...s&&{details:s}},{status:t})}function ae(r,e){let t=new Headers;return Object.entries(r).forEach(([s,i])=>{t.set(s,i);}),t.set("Content-Type","application/json"),new Response(JSON.stringify({error:"Payment required",code:"PAYMENT_REQUIRED",paymentRequest:e,instructions:{step1:"Sign the payment request with your session key using EIP-712",step2:"Retry the request with X-Payment-* headers",documentation:"https://docs.drip.dev/x402"}}),{status:402,headers:t})}function K(r,e){return async(t,s)=>{let i={method:t.method,url:t.url,headers:_(t.headers),query:t.nextUrl?ie(t.nextUrl.searchParams):{}},n=typeof r.quantity=="function"?await r.quantity(t):r.quantity,o;if(typeof r.customerResolver=="function"){let m=r.customerResolver;o=async()=>m(t);}else o=r.customerResolver;let u;if(typeof r.idempotencyKey=="function"){let m=r.idempotencyKey;u=async()=>m(t);}let l=typeof r.metadata=="function"?r.metadata(t):r.metadata,c={meter:r.meter,quantity:n,apiKey:r.apiKey,baseUrl:r.baseUrl,customerResolver:o,idempotencyKey:u,metadata:l,skipInDevelopment:r.skipInDevelopment,onCharge:void 0,onError:void 0},a=await H(i,c);if(!a.success){if(r.errorResponse){let m=await r.errorResponse(a.error,t);if(m)return m}return a.paymentRequired?ae(a.paymentRequired.headers,a.paymentRequired.paymentRequest):oe(a.error.message,a.error.code,a.error.statusCode,a.error.details)}r.onCharge&&await r.onCharge(a.charge,t);let g={drip:a.drip,customerId:a.state.customerId,charge:a.charge,isReplay:a.isReplay,params:s?.params};try{return await e(t,g)}catch(m){throw m}}}function ue(r){return (e,t)=>K({...r,...e},t)}function ce(r){return U(_(r.headers))}function le(r,e){return f(_(r.headers),e)}
2
+ exports.Drip=I;exports.DripError=y;exports.DripMiddlewareError=h;exports.createWithDrip=ue;exports.getDripHeader=le;exports.hasPaymentProofHeaders=ce;exports.withDrip=K;//# sourceMappingURL=next.cjs.map
3
3
  //# sourceMappingURL=next.cjs.map