@drip-sdk/node 1.0.8 → 1.0.10

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/express.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var crypto$1=require('crypto');var k=(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 b=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 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);}},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,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 m=await n.json();typeof m.status=="string"&&(u=m.status),typeof m.timestamp=="number"&&(c=m.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 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 p=(await this.listWorkflows()).data.find(l=>l.slug===e.workflow||l.id===e.workflow);if(p)s=p.id,i=p.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,u=0;if(e.events.length>0){let g=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})),p=await this.emitEventsBatch(g);o=p.created,u=p.duplicates;}let c=await this.endRun(n.id,{status:e.status,errorMessage:e.errorMessage,errorCode:e.errorCode}),m=Date.now()-t,d=e.events.length>0?`${o} events recorded`:"no events",h=`${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:u},totalCostUnits:c.totalCostUnits,summary:h}}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),m=u.slice(3);if(isNaN(c))return !1;let d=Math.floor(Date.now()/1e3);if(Math.abs(d-c)>i)return !1;let a=`${c}.${e}`,h=new TextEncoder,g=h.encode(s),p=h.encode(a),l=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),x=await crypto.subtle.sign("HMAC",l,p),I=Array.from(new Uint8Array(x)).map(w=>w.toString(16).padStart(2,"0")).join("");if(m.length!==I.length)return !1;let q=0;for(let w=0;w<m.length;w++)q|=m.charCodeAt(w)^I.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(x=>x.startsWith("t=")),u=n.find(x=>x.startsWith("v1="));if(!o||!u)return !1;let c=parseInt(o.slice(2),10),m=u.slice(3);if(isNaN(c))return !1;let d=Math.floor(Date.now()/1e3);if(Math.abs(d-c)>i)return !1;let a=k("crypto"),h=`${c}.${e}`,g=a.createHmac("sha256",s).update(h).digest("hex"),p=Buffer.from(m),l=Buffer.from(g);return p.length!==l.length?!1:a.timingSafeEqual(p,l)}catch{return false}}static generateWebhookSignature(e,t,s){let i=k("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 b(this.charge.bind(this),e)}};var y=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 U=300,O=300,N=["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 W(r){return r.toLowerCase()}function R(r,e){let t=W(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 C(r){return N.every(e=>R(r,e)!==void 0)}function L(r){let e=R(r,"x-payment-signature"),t=R(r,"x-payment-session-key"),s=R(r,"x-payment-smart-account"),i=R(r,"x-payment-timestamp"),n=R(r,"x-payment-amount"),o=R(r,"x-payment-recipient"),u=R(r,"x-payment-usage-id"),c=R(r,"x-payment-nonce");if(!e||!t||!s||!i||!n||!o||!u||!c)return null;let m=parseInt(i,10);if(isNaN(m)||Math.floor(Date.now()/1e3)-m>O)return null;let a=(h,g)=>{if(!h.startsWith("0x"))return false;let p=h.slice(2);return p.length<g?false:/^[a-fA-F0-9]+$/.test(p)};return !a(e,130)||!a(t,64)||!a(s,40)?null:{signature:e,sessionKeyId:t,smartAccount:s,timestamp:m,amount:n,recipient:o,usageId:u,nonce:c}}function K(r){let e=Math.floor(Date.now()/1e3),t=e+(r.expiresInSec??U),s=`${e}-${crypto$1.randomBytes(16).toString("hex")}`,i=r.usageId;i.startsWith("0x")||(i=v(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 v(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 $(r,e){let t=e.customerResolver??"header";if(typeof t=="function")return t(r);if(t==="header"){let s=R(r.headers,"x-drip-customer-id")??R(r.headers,"x-customer-id");if(!s)throw new y("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 y("Missing customer ID. Include drip_customer_id query parameter.","CUSTOMER_RESOLUTION_FAILED",400);return n}throw new y(`Invalid customer resolver: ${t}`,"CONFIGURATION_ERROR",500)}async function F(r,e){return typeof e.quantity=="function"?e.quantity(r):e.quantity}async function X(r,e,t){if(t.idempotencyKey)return t.idempotencyKey(r);let s=Date.now(),i=[r.method,r.url,e,s];return `drip_${v(i.join("|")).slice(2,18)}`}function D(r){let e=r.apiKey??process.env.DRIP_API_KEY;if(!e)throw new y("Missing Drip API key. Set DRIP_API_KEY environment variable or pass apiKey in config.","CONFIGURATION_ERROR",500);return new E({apiKey:e,baseUrl:r.baseUrl??process.env.DRIP_API_URL})}async function T(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=D(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=D(e),s=await $(r,e),i=await F(r,e),n=await X(r,s,e),o=C(r.headers),u=o?L(r.headers):void 0,c={customerId:s,quantity:i,idempotencyKey:n,hasPaymentProof:o,paymentProof:u??void 0},m=typeof e.metadata=="function"?e.metadata(r):e.metadata;try{let d=await t.charge({customerId:s,meter:e.meter,quantity:i,idempotencyKey:n,metadata:m});return e.onCharge&&await e.onCharge(d,r),{success:!0,state:c,charge:d,drip:t,isReplay:d.isReplay??!1}}catch(d){if(d instanceof f){if(d.statusCode===402){let a=process.env.DRIP_RECIPIENT_ADDRESS;if(!a)throw new y("DRIP_RECIPIENT_ADDRESS environment variable must be configured for x402 payment flow.","CONFIGURATION_ERROR",500);let h="0.01",g=d.message.match(/amount[:\s]+([0-9.]+)/i);g?h=g[1]:h=(i*1e-4).toFixed(6);let{headers:p,paymentRequest:l}=K({amount:h,recipient:a,usageId:n,description:`${e.meter} usage charge`});return {success:!1,error:new y("Insufficient balance. Payment required.","PAYMENT_REQUIRED",402),paymentRequired:{headers:p,paymentRequest:l}}}throw e.onError&&await e.onError(d,r),new y(d.message,"CHARGE_FAILED",d.statusCode,{code:d.code})}throw d}}catch(t){if(t instanceof y)return {success:false,error:t};let s=t instanceof Error?t.message:"Unknown error";return {success:false,error:new y(s,"INTERNAL_ERROR",500)}}}function S(r){let e={};for(let[t,s]of Object.entries(r))e[t.toLowerCase()]=Array.isArray(s)?s[0]:s;return e}function H(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 j(r,e,t,s,i){r.status(s).json({error:e,code:t,...i&&{details:i}});}function A(r){let e=r.attachToRequest??true;return async(t,s,i)=>{let n={method:t.method,url:t.originalUrl||t.url,headers:S(t.headers),query:t.query},o=typeof r.quantity=="function"?await r.quantity(t):r.quantity,u;if(typeof r.customerResolver=="function"){let g=r.customerResolver;u=async()=>g(t);}else u=r.customerResolver;let c;if(typeof r.idempotencyKey=="function"){let g=r.idempotencyKey;c=async()=>g(t);}let m=typeof r.metadata=="function"?r.metadata(t):r.metadata,d={meter:r.meter,quantity:o,apiKey:r.apiKey,baseUrl:r.baseUrl,customerResolver:u,idempotencyKey:c,metadata:m,skipInDevelopment:r.skipInDevelopment,onCharge:void 0,onError:void 0},a=await T(n,d);if(!a.success){if(r.errorHandler&&await r.errorHandler(a.error,t,s))return;if(a.paymentRequired){H(s,a.paymentRequired.headers,a.paymentRequired.paymentRequest);return}j(s,a.error.message,a.error.code,a.error.statusCode,a.error.details);return}r.onCharge&&await r.onCharge(a.charge,t);let h={drip:a.drip,customerId:a.state.customerId,charge:a.charge,isReplay:a.isReplay};e&&(t.drip=h),i();}}function B(r){return e=>A({...r,...e})}function G(r){return C(S(r.headers))}function _(r){return "drip"in r&&typeof r.drip=="object"}function J(r){if(!_(r))throw new Error("Drip context not found on request. Ensure dripMiddleware is applied before this route.");return r.drip}
2
- exports.Drip=E;exports.DripError=f;exports.DripMiddlewareError=y;exports.createDripMiddleware=B;exports.dripMiddleware=A;exports.getDripContext=J;exports.hasDripContext=_;exports.hasPaymentProofHeaders=G;//# sourceMappingURL=express.cjs.map
1
+ 'use strict';var crypto=require('crypto');var E=(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 I={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3};function U(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 N(t,e={}){let r=e.maxAttempts??I.maxAttempts,s=e.baseDelayMs??I.baseDelayMs,i=e.maxDelayMs??I.maxDelayMs,n=e.isRetryable??U,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);}},P=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 N(()=>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??E("crypto").webcrypto.subtle,x=await l.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),O=await l.sign("HMAC",x,g),k=Array.from(new Uint8Array(O)).map(b=>b.toString(16).padStart(2,"0")).join("");if(m.length!==k.length)return !1;let q=0;for(let b=0;b<m.length;b++)q|=m.charCodeAt(b)^k.charCodeAt(b);return q===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=E("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=E("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 L=300,K=300,$=["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 F(t){return t.toLowerCase()}function R(t,e){let r=F(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 D(t){return $.every(e=>R(t,e)!==void 0)}function X(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>K)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 H(t){let e=Math.floor(Date.now()/1e3),r=e+(t.expiresInSec??L),s=`${e}-${crypto.randomBytes(16).toString("hex")}`,i=t.usageId;i.startsWith("0x")||(i=v(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 v(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 j(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 B(t,e){return typeof e.quantity=="function"?e.quantity(t):e.quantity}async function G(t,e,r){if(r.idempotencyKey)return r.idempotencyKey(t);let s=Date.now(),i=[t.method,t.url,e,s];return `drip_${v(i.join("|")).slice(2,18)}`}function T(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 P({apiKey:e,baseUrl:t.baseUrl??process.env.DRIP_API_URL})}async function A(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=T(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=T(e),s=await j(t,e),i=await B(t,e),n=await G(t,s,e),o=D(t.headers),a=o?X(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}=H({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 S(t){let e={};for(let[r,s]of Object.entries(t))e[r.toLowerCase()]=Array.isArray(s)?s[0]:s;return e}function J(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 Y(t,e,r,s,i){t.status(s).json({error:e,code:r,...i&&{details:i}});}function M(t){let e=t.attachToRequest??true;return async(r,s,i)=>{let n={method:r.method,url:r.originalUrl||r.url,headers:S(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 A(n,d);if(!u.success){if(t.errorHandler&&await t.errorHandler(u.error,r,s))return;if(u.paymentRequired){J(s,u.paymentRequired.headers,u.paymentRequired.paymentRequest);return}Y(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 Q(t){return e=>M({...t,...e})}function z(t){return D(S(t.headers))}function _(t){return "drip"in t&&typeof t.drip=="object"}function V(t){if(!_(t))throw new Error("Drip context not found on request. Ensure dripMiddleware is applied before this route.");return t.drip}
2
+ exports.Drip=P;exports.DripError=f;exports.DripMiddlewareError=h;exports.createDripMiddleware=Q;exports.dripMiddleware=M;exports.getDripContext=V;exports.hasDripContext=_;exports.hasPaymentProofHeaders=z;//# sourceMappingURL=express.cjs.map
3
3
  //# sourceMappingURL=express.cjs.map