@drip-sdk/node 1.0.10 → 1.1.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/README.md +154 -592
- package/dist/core.cjs +3 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.cts +762 -0
- package/dist/core.d.ts +760 -0
- package/dist/core.js +3 -0
- package/dist/core.js.map +1 -0
- package/dist/express.cjs +2 -2
- package/dist/express.cjs.map +1 -1
- package/dist/express.d.cts +3 -3
- package/dist/express.d.ts +3 -3
- package/dist/express.js +2 -2
- package/dist/express.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +746 -54
- package/dist/index.d.ts +746 -54
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/langchain.cjs +3 -0
- package/dist/langchain.cjs.map +1 -0
- package/dist/langchain.d.cts +290 -0
- package/dist/langchain.d.ts +290 -0
- package/dist/langchain.js +3 -0
- package/dist/langchain.js.map +1 -0
- package/dist/middleware.cjs +2 -2
- package/dist/middleware.cjs.map +1 -1
- package/dist/middleware.d.cts +3 -3
- package/dist/middleware.d.ts +3 -3
- package/dist/middleware.js +2 -2
- package/dist/middleware.js.map +1 -1
- package/dist/next.cjs +2 -2
- package/dist/next.cjs.map +1 -1
- package/dist/next.d.cts +3 -3
- package/dist/next.d.ts +3 -3
- package/dist/next.js +2 -2
- package/dist/next.js.map +1 -1
- package/dist/{types-D8mMON4v.d.ts → types-B2qwDadD.d.ts} +1 -1
- package/dist/{types-92iVqLtE.d.cts → types-Bo8SiUdl.d.cts} +1 -1
- package/package.json +23 -1
package/dist/express.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { b as X402PaymentProof, a as X402PaymentRequest } from './types-
|
|
3
|
-
export { ChargeParams, ChargeResult, ChargeStatus, Customer,
|
|
1
|
+
import { c as DripContext, W as WithDripConfig, D as DripMiddlewareError } from './types-Bo8SiUdl.cjs';
|
|
2
|
+
export { b as X402PaymentProof, a as X402PaymentRequest } from './types-Bo8SiUdl.cjs';
|
|
3
|
+
export { ChargeParams, ChargeResult, ChargeStatus, Customer, Drip, DripConfig, DripError } from './index.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Drip Express Adapter
|
package/dist/express.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { b as X402PaymentProof, a as X402PaymentRequest } from './types-
|
|
3
|
-
export { ChargeParams, ChargeResult, ChargeStatus, Customer,
|
|
1
|
+
import { c as DripContext, W as WithDripConfig, D as DripMiddlewareError } from './types-B2qwDadD.js';
|
|
2
|
+
export { b as X402PaymentProof, a as X402PaymentRequest } from './types-B2qwDadD.js';
|
|
3
|
+
export { ChargeParams, ChargeResult, ChargeStatus, Customer, Drip, DripConfig, DripError } from './index.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Drip Express Adapter
|
package/dist/express.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';var I=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var w=class{_total=0;_flushed=false;_flushCount=0;_chargeFn;_options;constructor(e,r){this._chargeFn=e,this._options=r;}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 r=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:r,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 D={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3};function N(t){return t instanceof Error&&(t.message.includes("fetch")||t.message.includes("network"))?true:t instanceof f?t.statusCode>=500||t.statusCode===408||t.statusCode===429:false}async function W(t,e={}){let r=e.maxAttempts??D.maxAttempts,s=e.baseDelayMs??D.baseDelayMs,i=e.maxDelayMs??D.maxDelayMs,n=e.isRetryable??N,o;for(let a=1;a<=r;a++)try{return await t()}catch(c){if(o=c,a===r||!n(c))throw c;let m=Math.min(s*Math.pow(2,a-1)+Math.random()*100,i);await new Promise(d=>setTimeout(d,m));}throw o}var f=class t extends Error{constructor(r,s,i){super(r);this.statusCode=s;this.code=i;this.name="DripError",Object.setPrototypeOf(this,t.prototype);}},E=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,r={}){let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeout);try{let n=await fetch(`${this.baseUrl}${e}`,{...r,signal:s.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...r.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,r=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,a="unknown",c=Date.now();try{let m=await n.json();typeof m.status=="string"&&(a=m.status),typeof m.timestamp=="number"&&(c=m.timestamp);}catch{a=n.ok?"healthy":`error:${n.status}`;}return !n.ok&&a==="unknown"&&(a=`error:${n.status}`),{ok:n.ok&&a==="healthy",status:a,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(r);}}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 r=new URLSearchParams;e?.limit&&r.set("limit",e.limit.toString()),e?.status&&r.set("status",e.status);let s=r.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 r=e.idempotencyKey??`wrap_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,s=await e.call(),i=e.extractUsage(s),n=await W(()=>this.charge({customerId:e.customerId,meter:e.meter,quantity:i,idempotencyKey:r,metadata:e.metadata}),e.retryOptions);return {result:s,charge:n,idempotencyKey:r}}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 r=new URLSearchParams;e?.customerId&&r.set("customerId",e.customerId),e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",e.limit.toString()),e?.offset&&r.set("offset",e.offset.toString());let s=r.toString(),i=s?`/charges?${s}`:"/charges";return this.request(i)}async getChargeStatus(e){return this.request(`/charges/${e}/status`)}async checkout(e){let r=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:r.id,url:r.url,expiresAt:r.expires_at,amountUsd:r.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,r){return this.request(`/runs/${e}`,{method:"PATCH",body:JSON.stringify(r)})}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(r=>({id:r.id,name:r.name,meter:r.unitType,unitPriceUsd:r.unitPriceUsd,isActive:r.isActive})),count:e.count}}async recordRun(e){let r=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,x=>x.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,a=0;if(e.events.length>0){let p=e.events.map((l,x)=>({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}:${x}`:void 0})),g=await this.emitEventsBatch(p);o=g.created,a=g.duplicates;}let c=await this.endRun(n.id,{status:e.status,errorMessage:e.errorMessage,errorCode:e.errorCode}),m=Date.now()-r,d=e.events.length>0?`${o} events recorded`:"no events",y=`${e.status==="COMPLETED"?"\u2713":e.status==="FAILED"?"\u2717":"\u25CB"} ${i}: ${d} (${c.durationMs??m}ms)`;return {run:{id:n.id,workflowId:s,workflowName:i,status:e.status,durationMs:c.durationMs},events:{created:o,duplicates:a},totalCostUnits:c.totalCostUnits,summary:y}}static generateIdempotencyKey(e){let r=[e.customerId,e.runId??"no_run",e.stepName,String(e.sequence??0)],s=0,i=r.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,r,s,i=300){if(!e||!r||!s)return false;try{let n=r.split(","),o=n.find(b=>b.startsWith("t=")),a=n.find(b=>b.startsWith("v1="));if(!o||!a)return !1;let c=parseInt(o.slice(2),10),m=a.slice(3);if(isNaN(c))return !1;let d=Math.floor(Date.now()/1e3);if(Math.abs(d-c)>i)return !1;let u=`${c}.${e}`,y=new TextEncoder,p=y.encode(s),g=y.encode(u),l=globalThis.crypto?.subtle??I("crypto").webcrypto.subtle,x=await l.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),U=await l.sign("HMAC",x,g),q=Array.from(new Uint8Array(U)).map(b=>b.toString(16).padStart(2,"0")).join("");if(m.length!==q.length)return !1;let T=0;for(let b=0;b<m.length;b++)T|=m.charCodeAt(b)^q.charCodeAt(b);return T===0}catch{return false}}static verifyWebhookSignatureSync(e,r,s,i=300){if(!e||!r||!s)return false;try{let n=r.split(","),o=n.find(x=>x.startsWith("t=")),a=n.find(x=>x.startsWith("v1="));if(!o||!a)return !1;let c=parseInt(o.slice(2),10),m=a.slice(3);if(isNaN(c))return !1;let d=Math.floor(Date.now()/1e3);if(Math.abs(d-c)>i)return !1;let u=I("crypto"),y=`${c}.${e}`,p=u.createHmac("sha256",s).update(y).digest("hex"),g=Buffer.from(m),l=Buffer.from(p);return g.length!==l.length?!1:u.timingSafeEqual(g,l)}catch{return false}}static generateWebhookSignature(e,r,s){let i=I("crypto"),n=s??Math.floor(Date.now()/1e3),o=`${n}.${e}`,a=i.createHmac("sha256",r).update(o).digest("hex");return `t=${n},v1=${a}`}createStreamMeter(e){return new w(this.charge.bind(this),e)}};var h=class t extends Error{constructor(r,s,i,n){super(r);this.code=s;this.statusCode=i;this.details=n;this.name="DripMiddlewareError",Object.setPrototypeOf(this,t.prototype);}};var K=300,$=300,F=["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 X(t){return t.toLowerCase()}function R(t,e){let r=X(e);if(t[r]!==void 0){let s=t[r];return Array.isArray(s)?s[0]:s}for(let[s,i]of Object.entries(t))if(s.toLowerCase()===r)return Array.isArray(i)?i[0]:i}function k(t){return F.every(e=>R(t,e)!==void 0)}function H(t){let e=R(t,"x-payment-signature"),r=R(t,"x-payment-session-key"),s=R(t,"x-payment-smart-account"),i=R(t,"x-payment-timestamp"),n=R(t,"x-payment-amount"),o=R(t,"x-payment-recipient"),a=R(t,"x-payment-usage-id"),c=R(t,"x-payment-nonce");if(!e||!r||!s||!i||!n||!o||!a||!c)return null;let m=parseInt(i,10);if(isNaN(m)||Math.floor(Date.now()/1e3)-m>$)return null;let u=(y,p)=>{if(!y.startsWith("0x"))return false;let g=y.slice(2);return g.length<p?false:/^[a-fA-F0-9]+$/.test(g)};return !u(e,130)||!u(r,64)||!u(s,40)?null:{signature:e,sessionKeyId:r,smartAccount:s,timestamp:m,amount:n,recipient:o,usageId:a,nonce:c}}function j(t){let e=Math.floor(Date.now()/1e3),r=e+(t.expiresInSec??K),s=`${e}-${randomBytes(16).toString("hex")}`,i=t.usageId;i.startsWith("0x")||(i=A(i));let n={"X-Payment-Required":"true","X-Payment-Amount":t.amount,"X-Payment-Recipient":t.recipient,"X-Payment-Usage-Id":i,"X-Payment-Description":t.description??"API usage charge","X-Payment-Expires":String(r),"X-Payment-Nonce":s,"X-Payment-Timestamp":String(e)},o={amount:t.amount,recipient:t.recipient,usageId:i,description:t.description??"API usage charge",expiresAt:r,nonce:s,timestamp:e};return {headers:n,paymentRequest:o}}function A(t){let e=5381,r=52711;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);e=(e<<5)+e^o,r=(r<<5)+r^o;}return `0x${Math.abs(e*31+r).toString(16).padStart(16,"0").slice(0,16).padEnd(64,"0")}`}async function B(t,e){let r=e.customerResolver??"header";if(typeof r=="function")return r(t);if(r==="header"){let s=R(t.headers,"x-drip-customer-id")??R(t.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(r==="query"){let s=t.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: ${r}`,"CONFIGURATION_ERROR",500)}async function G(t,e){return typeof e.quantity=="function"?e.quantity(t):e.quantity}async function J(t,e,r){if(r.idempotencyKey)return r.idempotencyKey(t);let s=Date.now(),i=[t.method,t.url,e,s];return `drip_${A(i.join("|")).slice(2,18)}`}function v(t){let e=t.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 E({apiKey:e,baseUrl:t.baseUrl??process.env.DRIP_API_URL})}async function S(t,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 r=v(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:r,isReplay:false}}try{let r=v(e),s=await B(t,e),i=await G(t,e),n=await J(t,s,e),o=k(t.headers),a=o?H(t.headers):void 0,c={customerId:s,quantity:i,idempotencyKey:n,hasPaymentProof:o,paymentProof:a??void 0},m=typeof e.metadata=="function"?e.metadata(t):e.metadata;try{let d=await r.charge({customerId:s,meter:e.meter,quantity:i,idempotencyKey:n,metadata:m});return e.onCharge&&await e.onCharge(d,t),{success:!0,state:c,charge:d,drip:r,isReplay:d.isReplay??!1}}catch(d){if(d instanceof f){if(d.statusCode===402){let u=process.env.DRIP_RECIPIENT_ADDRESS;if(!u)throw new h("DRIP_RECIPIENT_ADDRESS environment variable must be configured for x402 payment flow.","CONFIGURATION_ERROR",500);let y="0.01",p=d.message.match(/amount[:\s]+([0-9.]+)/i);p?y=p[1]:y=(i*1e-4).toFixed(6);let{headers:g,paymentRequest:l}=j({amount:y,recipient:u,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(d,t),new h(d.message,"CHARGE_FAILED",d.statusCode,{code:d.code})}throw d}}catch(r){if(r instanceof h)return {success:false,error:r};let s=r instanceof Error?r.message:"Unknown error";return {success:false,error:new h(s,"INTERNAL_ERROR",500)}}}function M(t){let e={};for(let[r,s]of Object.entries(t))e[r.toLowerCase()]=Array.isArray(s)?s[0]:s;return e}function Y(t,e,r){t.status(402).set(e).json({error:"Payment required",code:"PAYMENT_REQUIRED",paymentRequest:r,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"}});}function Q(t,e,r,s,i){t.status(s).json({error:e,code:r,...i&&{details:i}});}function _(t){let e=t.attachToRequest??true;return async(r,s,i)=>{let n={method:r.method,url:r.originalUrl||r.url,headers:M(r.headers),query:r.query},o=typeof t.quantity=="function"?await t.quantity(r):t.quantity,a;if(typeof t.customerResolver=="function"){let p=t.customerResolver;a=async()=>p(r);}else a=t.customerResolver;let c;if(typeof t.idempotencyKey=="function"){let p=t.idempotencyKey;c=async()=>p(r);}let m=typeof t.metadata=="function"?t.metadata(r):t.metadata,d={meter:t.meter,quantity:o,apiKey:t.apiKey,baseUrl:t.baseUrl,customerResolver:a,idempotencyKey:c,metadata:m,skipInDevelopment:t.skipInDevelopment,onCharge:void 0,onError:void 0},u=await S(n,d);if(!u.success){if(t.errorHandler&&await t.errorHandler(u.error,r,s))return;if(u.paymentRequired){Y(s,u.paymentRequired.headers,u.paymentRequired.paymentRequest);return}Q(s,u.error.message,u.error.code,u.error.statusCode,u.error.details);return}t.onCharge&&await t.onCharge(u.charge,r);let y={drip:u.drip,customerId:u.state.customerId,charge:u.charge,isReplay:u.isReplay};e&&(r.drip=y),i();}}function z(t){return e=>_({...t,...e})}function V(t){return k(M(t.headers))}function O(t){return "drip"in t&&typeof t.drip=="object"}function Z(t){if(!O(t))throw new Error("Drip context not found on request. Ensure dripMiddleware is applied before this route.");return t.drip}
|
|
2
|
-
export{
|
|
1
|
+
import {createHash,randomBytes}from'crypto';var T=(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 J=0;function E(r,...e){let t=++J,s=e.filter(i=>i!==void 0).map(String);s.push(String(t));let n=createHash("sha256").update(s.join("|")).digest("hex").slice(0,24);return `${r}_${n}`}var S=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}`:E("stream",this._options.customerId,this._options.meter,e,this._flushCount),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 n={success:s.success,quantity:e,charge:s.charge,isReplay:s.isReplay};return this._options.onFlush?.(n),n}reset(){this._total=0;}};var Q={requestsPerSecond:100,burstSize:200,enabled:true},D=class{config;tokens;lastRefill;constructor(e){this.config={...Q,...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 n=t-Date.now();if(n<=0)return false;await this.sleep(Math.min(s,n));}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 q=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 F(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 K(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 V={failureThreshold:5,successThreshold:2,timeoutMs:3e4,enabled:true},M=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);}},v=class{name;config;state="closed";failureCount=0;successCount=0;lastFailureTime=null;constructor(e,t){this.name=e,this.config={...V,...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;}},A=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,a)=>o-a),t=this.metrics.filter(o=>o.success).length,s={};for(let o of this.metrics)s[o.endpoint]=(s[o.endpoint]??0)+1;let n={};for(let o of this.metrics)o.error&&(n[o.error]=(n[o.error]??0)+1);let i=e.reduce((o,a)=>o+a,0);return {windowSize:this.metrics.length,totalRequests:this.totalRequests,totalSuccesses:this.totalSuccesses,totalFailures:this.totalFailures,successRate:t/this.metrics.length*100,avgLatencyMs:i/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:n}}reset(){this.metrics.length=0,this.totalRequests=0,this.totalSuccesses=0,this.totalFailures=0;}};function P(){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 _(){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 I=class{config;rateLimiter;circuitBreaker;metrics;constructor(e){this.config={...P(),...e,rateLimiter:{...P().rateLimiter,...e?.rateLimiter},retry:{...P().retry,...e?.retry},circuitBreaker:{...P().circuitBreaker,...e?.circuitBreaker}},this.rateLimiter=new D(this.config.rateLimiter),this.circuitBreaker=new v("drip_api",this.config.circuitBreaker),this.metrics=this.config.collectMetrics?new A:null;}async execute(e,t="UNKNOWN",s="unknown"){let n=performance.now(),i=0,o=null;if(!await this.rateLimiter.acquire(3e4))throw new Error("Rate limiter timeout");if(!this.circuitBreaker.allowRequest())throw new M(this.circuitBreaker.name,this.circuitBreaker.getTimeUntilRetry());for(let u=0;u<=this.config.retry.maxRetries;u++)try{let c=await e();if(this.circuitBreaker.recordSuccess(),this.metrics){let d=performance.now()-n;this.metrics.record({method:t,endpoint:s,statusCode:200,durationMs:d,success:!0,timestamp:Date.now(),retryCount:i});}return c}catch(c){if(o=c instanceof Error?c:new Error(String(c)),this.config.retry.enabled&&K(c,this.config.retry)&&u<this.config.retry.maxRetries){i+=1;let l=F(u,this.config.retry);await this.sleep(l);continue}if(this.circuitBreaker.recordFailure(),this.metrics){let l=performance.now()-n,g=c.statusCode??null;this.metrics.record({method:t,endpoint:s,statusCode:g,durationMs:l,success:false,timestamp:Date.now(),error:o.name,retryCount:i});}throw c}throw o?new q(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 U={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3};function Z(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 ee(r,e={}){let t=e.maxAttempts??U.maxAttempts,s=e.baseDelayMs??U.baseDelayMs,n=e.maxDelayMs??U.maxDelayMs,i=e.isRetryable??Z,o;for(let a=1;a<=t;a++)try{return await r()}catch(u){if(o=u,a===t||!i(u))throw u;let c=Math.min(s*Math.pow(2,a-1)+Math.random()*100,n);await new Promise(d=>setTimeout(d,c));}throw o}var y=class r extends Error{constructor(t,s,n){super(t);this.statusCode=s;this.code=n;this.name="DripError",Object.setPrototypeOf(this,r.prototype);}},k=class{apiKey;baseUrl;timeout;resilience;keyType;constructor(e={}){let t=e.apiKey??(typeof process<"u"?process.env.DRIP_API_KEY:void 0),s=e.baseUrl??(typeof process<"u"?process.env.DRIP_BASE_URL:void 0);if(!t)throw new Error("Drip API key is required. Either pass { apiKey } to constructor or set DRIP_API_KEY environment variable.");this.apiKey=t,this.baseUrl=s||"https://drip-app-hlunj.ondigitalocean.app/v1",this.timeout=e.timeout||3e4,t.startsWith("sk_")?this.keyType="secret":t.startsWith("pk_")?this.keyType="public":this.keyType="unknown",e.resilience===true?this.resilience=new I(P()):e.resilience==="high-throughput"?this.resilience=new I(_()):e.resilience&&typeof e.resilience=="object"?this.resilience=new I(e.resilience):this.resilience=null;}assertSecretKey(e){if(this.keyType==="public")throw new y(`${e} requires a secret key (sk_). You are using a public key (pk_), which cannot access this endpoint. Use a secret key for webhook, API key, and feature flag management.`,403,"PUBLIC_KEY_NOT_ALLOWED")}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,n=setTimeout(()=>s.abort(),this.timeout);try{let i=await fetch(`${this.baseUrl}${e}`,{...t,signal:s.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(i.status===204)return {success:!0};let o=await i.json();if(!i.ok)throw new y(o.message||o.error||"Request failed",i.status,o.code);return o}catch(i){throw i instanceof y?i:i instanceof Error&&i.name==="AbortError"?new y("Request timed out",408,"TIMEOUT"):new y(i instanceof Error?i.message:"Unknown error",0,"UNKNOWN")}finally{clearTimeout(n);}}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 n=Date.now();try{let i=await fetch(`${s}/health`,{signal:e.signal,headers:{Authorization:`Bearer ${this.apiKey}`}}),o=Date.now()-n,a="unknown",u=Date.now();try{let c=await i.json();typeof c.status=="string"&&(a=c.status),typeof c.timestamp=="number"&&(u=c.timestamp);}catch{a=i.ok?"healthy":`error:${i.status}`;}return !i.ok&&a==="unknown"&&(a=`error:${i.status}`),{ok:i.ok&&a==="healthy",status:a,latencyMs:o,timestamp:u}}catch(i){throw i instanceof Error&&i.name==="AbortError"?new y("Request timed out",408,"TIMEOUT"):new y(i instanceof Error?i.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(),n=s?`/customers?${s}`:"/customers";return this.request(n)}async getBalance(e){return this.request(`/customers/${e}/balance`)}async charge(e){let t=e.idempotencyKey??E("chg",e.customerId,e.meter,e.quantity);return this.request("/usage",{method:"POST",body:JSON.stringify({customerId:e.customerId,usageType:e.meter,quantity:e.quantity,idempotencyKey:t,metadata:e.metadata})})}async wrapApiCall(e){let t=e.idempotencyKey??`wrap_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,s=await e.call(),n=e.extractUsage(s),i=await ee(()=>this.charge({customerId:e.customerId,meter:e.meter,quantity:n,idempotencyKey:t,metadata:e.metadata}),e.retryOptions);return {result:s,charge:i,idempotencyKey:t}}async trackUsage(e){let t=e.idempotencyKey??E("track",e.customerId,e.meter,e.quantity);return this.request("/usage/internal",{method:"POST",body:JSON.stringify({customerId:e.customerId,usageType:e.meter,quantity:e.quantity,idempotencyKey:t,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(),n=s?`/charges?${s}`:"/charges";return this.request(n)}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.assertSecretKey("createWebhook()"),this.request("/webhooks",{method:"POST",body:JSON.stringify(e)})}async listWebhooks(){return this.assertSecretKey("listWebhooks()"),this.request("/webhooks")}async getWebhook(e){return this.assertSecretKey("getWebhook()"),this.request(`/webhooks/${e}`)}async deleteWebhook(e){return this.assertSecretKey("deleteWebhook()"),this.request(`/webhooks/${e}`,{method:"DELETE"})}async testWebhook(e){return this.assertSecretKey("testWebhook()"),this.request(`/webhooks/${e}/test`,{method:"POST"})}async rotateWebhookSecret(e){return this.assertSecretKey("rotateWebhookSecret()"),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 getRun(e){return this.request(`/runs/${e}`)}async getRunTimeline(e,t){let s=new URLSearchParams;t?.limit&&s.set("limit",t.limit.toString()),t?.cursor&&s.set("cursor",t.cursor),t?.includeAnomalies!==void 0&&s.set("includeAnomalies",String(t.includeAnomalies)),t?.collapseRetries!==void 0&&s.set("collapseRetries",String(t.collapseRetries));let n=s.toString(),i=n?`/runs/${e}/timeline?${n}`:`/runs/${e}/timeline`;return this.request(i)}async emitEvent(e){let t=e.idempotencyKey??E("evt",e.runId,e.eventType,e.quantity);return this.request("/run-events",{method:"POST",body:JSON.stringify({...e,idempotencyKey:t})})}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,n=e.workflow;if(!e.workflow.startsWith("wf_"))try{let h=(await this.listWorkflows()).data.find(m=>m.slug===e.workflow||m.id===e.workflow);if(h)s=h.id,n=h.name;else {let m=await this.createWorkflow({name:e.workflow.replace(/[_-]/g," ").replace(/\b\w/g,R=>R.toUpperCase()),slug:e.workflow,productSurface:"AGENT"});s=m.id,n=m.name;}}catch{s=e.workflow;}let i=await this.startRun({customerId:e.customerId,workflowId:s,externalRunId:e.externalRunId,correlationId:e.correlationId,metadata:e.metadata}),o=0,a=0;if(e.events.length>0){let p=e.events.map((m,R)=>({runId:i.id,eventType:m.eventType,quantity:m.quantity,units:m.units,description:m.description,costUnits:m.costUnits,metadata:m.metadata,idempotencyKey:e.externalRunId?`${e.externalRunId}:${m.eventType}:${R}`:E("run",i.id,m.eventType,R)})),h=await this.emitEventsBatch(p);o=h.created,a=h.duplicates;}let u=await this.endRun(i.id,{status:e.status,errorMessage:e.errorMessage,errorCode:e.errorCode}),c=Date.now()-t,d=e.events.length>0?`${o} events recorded`:"no events",g=`${e.status==="COMPLETED"?"\u2713":e.status==="FAILED"?"\u2717":"\u25CB"} ${n}: ${d} (${u.durationMs??c}ms)`;return {run:{id:i.id,workflowId:s,workflowName:n,status:e.status,durationMs:u.durationMs},events:{created:o,duplicates:a},totalCostUnits:u.totalCostUnits,summary:g}}static generateIdempotencyKey(e){let s=[e.customerId,e.runId??"no_run",e.stepName,String(e.sequence??0)].join("|");return `drip_${T("crypto").createHash("sha256").update(s).digest("hex").slice(0,32)}_${e.stepName.slice(0,16)}`}static async verifyWebhookSignature(e,t,s,n=300){if(!e||!t||!s)return false;try{let i=t.split(","),o=i.find(C=>C.startsWith("t=")),a=i.find(C=>C.startsWith("v1="));if(!o||!a)return !1;let u=parseInt(o.slice(2),10),c=a.slice(3);if(isNaN(u))return !1;let d=Math.floor(Date.now()/1e3);if(Math.abs(d-u)>n)return !1;let l=`${u}.${e}`,g=new TextEncoder,p=g.encode(s),h=g.encode(l),m=globalThis.crypto?.subtle??T("crypto").webcrypto.subtle,R=await m.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),z=await m.sign("HMAC",R,h),N=Array.from(new Uint8Array(z)).map(C=>C.toString(16).padStart(2,"0")).join("");if(c.length!==N.length)return !1;let W=0;for(let C=0;C<c.length;C++)W|=c.charCodeAt(C)^N.charCodeAt(C);return W===0}catch{return false}}static verifyWebhookSignatureSync(e,t,s,n=300){if(!e||!t||!s)return false;try{let i=t.split(","),o=i.find(R=>R.startsWith("t=")),a=i.find(R=>R.startsWith("v1="));if(!o||!a)return !1;let u=parseInt(o.slice(2),10),c=a.slice(3);if(isNaN(u))return !1;let d=Math.floor(Date.now()/1e3);if(Math.abs(d-u)>n)return !1;let l=T("crypto"),g=`${u}.${e}`,p=l.createHmac("sha256",s).update(g).digest("hex"),h=Buffer.from(c),m=Buffer.from(p);return h.length!==m.length?!1:l.timingSafeEqual(h,m)}catch{return false}}static generateWebhookSignature(e,t,s){let n=T("crypto"),i=s??Math.floor(Date.now()/1e3),o=`${i}.${e}`,a=n.createHmac("sha256",t).update(o).digest("hex");return `t=${i},v1=${a}`}createStreamMeter(e){return new S(this.charge.bind(this),e)}};var O=null;function te(){return O||(O=new k),O}new Proxy({},{get(r,e){let t=te(),s=t[e];return typeof s=="function"?s.bind(t):s}});var f=class r extends Error{constructor(t,s,n,i){super(t);this.code=s;this.statusCode=n;this.details=i;this.name="DripMiddlewareError",Object.setPrototypeOf(this,r.prototype);}};var se=300,ne=300,ie=["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 oe(r){return r.toLowerCase()}function b(r,e){let t=oe(e);if(r[t]!==void 0){let s=r[t];return Array.isArray(s)?s[0]:s}for(let[s,n]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(n)?n[0]:n}function L(r){return ie.every(e=>b(r,e)!==void 0)}function ae(r){let e=b(r,"x-payment-signature"),t=b(r,"x-payment-session-key"),s=b(r,"x-payment-smart-account"),n=b(r,"x-payment-timestamp"),i=b(r,"x-payment-amount"),o=b(r,"x-payment-recipient"),a=b(r,"x-payment-usage-id"),u=b(r,"x-payment-nonce");if(!e||!t||!s||!n||!i||!o||!a||!u)return null;let c=parseInt(n,10);if(isNaN(c)||Math.floor(Date.now()/1e3)-c>ne)return null;let l=(g,p)=>{if(!g.startsWith("0x"))return false;let h=g.slice(2);return h.length<p?false:/^[a-fA-F0-9]+$/.test(h)};return !l(e,130)||!l(t,64)||!l(s,40)?null:{signature:e,sessionKeyId:t,smartAccount:s,timestamp:c,amount:i,recipient:o,usageId:a,nonce:u}}function ue(r){let e=Math.floor(Date.now()/1e3),t=e+(r.expiresInSec??se),s=`${e}-${randomBytes(16).toString("hex")}`,n=r.usageId;n.startsWith("0x")||(n=$(n));let i={"X-Payment-Required":"true","X-Payment-Amount":r.amount,"X-Payment-Recipient":r.recipient,"X-Payment-Usage-Id":n,"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:n,description:r.description??"API usage charge",expiresAt:t,nonce:s,timestamp:e};return {headers:i,paymentRequest:o}}function $(r){let{createHash:e}=T("crypto");return `0x${e("sha256").update(r).digest("hex")}`}async function ce(r,e){let t=e.customerResolver??"header";if(typeof t=="function")return t(r);if(t==="header"){let s=b(r.headers,"x-drip-customer-id")??b(r.headers,"x-customer-id");if(!s)throw new f("Missing customer ID. Include X-Drip-Customer-Id header.","CUSTOMER_RESOLUTION_FAILED",400);return s}if(t==="query"){let s=r.query??{},n=s.drip_customer_id??s.customer_id,i=Array.isArray(n)?n[0]:n;if(!i)throw new f("Missing customer ID. Include drip_customer_id query parameter.","CUSTOMER_RESOLUTION_FAILED",400);return i}throw new f(`Invalid customer resolver: ${t}`,"CONFIGURATION_ERROR",500)}async function le(r,e){return typeof e.quantity=="function"?e.quantity(r):e.quantity}async function de(r,e,t){if(t.idempotencyKey)return t.idempotencyKey(r);let s=Date.now(),n=[r.method,r.url,e,s];return `drip_${$(n.join("|")).slice(2,18)}`}function B(r){let e=r.apiKey??process.env.DRIP_API_KEY;if(!e)throw new f("Missing Drip API key. Set DRIP_API_KEY environment variable or pass apiKey in config.","CONFIGURATION_ERROR",500);return new k({apiKey:e,baseUrl:r.baseUrl??process.env.DRIP_API_URL})}async function H(r,e){if(e.skipInDevelopment&&process.env.NODE_ENV==="development"){let t=B(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=B(e),s=await ce(r,e),n=await le(r,e),i=await de(r,s,e),o=L(r.headers),a=o?ae(r.headers):void 0,u={customerId:s,quantity:n,idempotencyKey:i,hasPaymentProof:o,paymentProof:a??void 0},c=typeof e.metadata=="function"?e.metadata(r):e.metadata;try{let d=await t.charge({customerId:s,meter:e.meter,quantity:n,idempotencyKey:i,metadata:c});return e.onCharge&&await e.onCharge(d,r),{success:!0,state:u,charge:d,drip:t,isReplay:d.isReplay??!1}}catch(d){if(d instanceof y){if(d.statusCode===402){let l=process.env.DRIP_RECIPIENT_ADDRESS;if(!l)throw new f("DRIP_RECIPIENT_ADDRESS environment variable must be configured for x402 payment flow.","CONFIGURATION_ERROR",500);let g="0.01",p=d.message.match(/amount[:\s]+([0-9.]+)/i);p?g=p[1]:g=(n*1e-4).toFixed(6);let{headers:h,paymentRequest:m}=ue({amount:g,recipient:l,usageId:i,description:`${e.meter} usage charge`});return {success:!1,error:new f("Insufficient balance. Payment required.","PAYMENT_REQUIRED",402),paymentRequired:{headers:h,paymentRequest:m}}}throw e.onError&&await e.onError(d,r),new f(d.message,"CHARGE_FAILED",d.statusCode,{code:d.code})}throw d}}catch(t){if(t instanceof f)return {success:false,error:t};let s=t instanceof Error?t.message:"Unknown error";return {success:false,error:new f(s,"INTERNAL_ERROR",500)}}}function X(r){let e={};for(let[t,s]of Object.entries(r))e[t.toLowerCase()]=Array.isArray(s)?s[0]:s;return e}function me(r,e,t){r.status(402).set(e).json({error:"Payment required",code:"PAYMENT_REQUIRED",paymentRequest:t,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"}});}function ge(r,e,t,s,n){r.status(s).json({error:e,code:t,...n&&{details:n}});}function j(r){let e=r.attachToRequest??true;return async(t,s,n)=>{let i={method:t.method,url:t.originalUrl||t.url,headers:X(t.headers),query:t.query},o=typeof r.quantity=="function"?await r.quantity(t):r.quantity,a;if(typeof r.customerResolver=="function"){let p=r.customerResolver;a=async()=>p(t);}else a=r.customerResolver;let u;if(typeof r.idempotencyKey=="function"){let p=r.idempotencyKey;u=async()=>p(t);}let c=typeof r.metadata=="function"?r.metadata(t):r.metadata,d={meter:r.meter,quantity:o,apiKey:r.apiKey,baseUrl:r.baseUrl,customerResolver:a,idempotencyKey:u,metadata:c,skipInDevelopment:r.skipInDevelopment,onCharge:void 0,onError:void 0},l=await H(i,d);if(!l.success){if(r.errorHandler&&await r.errorHandler(l.error,t,s))return;if(l.paymentRequired){me(s,l.paymentRequired.headers,l.paymentRequired.paymentRequest);return}ge(s,l.error.message,l.error.code,l.error.statusCode,l.error.details);return}r.onCharge&&await r.onCharge(l.charge,t);let g={drip:l.drip,customerId:l.state.customerId,charge:l.charge,isReplay:l.isReplay};e&&(t.drip=g),n();}}function pe(r){return e=>j({...r,...e})}function he(r){return L(X(r.headers))}function G(r){return "drip"in r&&typeof r.drip=="object"}function ye(r){if(!G(r))throw new Error("Drip context not found on request. Ensure dripMiddleware is applied before this route.");return r.drip}
|
|
2
|
+
export{k as Drip,y as DripError,f as DripMiddlewareError,pe as createDripMiddleware,j as dripMiddleware,ye as getDripContext,G as hasDripContext,he as hasPaymentProofHeaders};//# sourceMappingURL=express.js.map
|
|
3
3
|
//# sourceMappingURL=express.js.map
|