@drawbridge/drawbridge-utils 0.0.103 → 0.0.105

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.
@@ -0,0 +1,820 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all2) => {
8
+ for (var name in all2)
9
+ __defProp(target, name, { get: all2[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // lib/pricing.js
30
+ var pricing_exports = {};
31
+ __export(pricing_exports, {
32
+ LOCAL_FLAT_CENTS: () => LOCAL_FLAT_CENTS,
33
+ MARKUP: () => MARKUP,
34
+ PREMIUM_CPM_CENTS: () => PREMIUM_CPM_CENTS,
35
+ PREMIUM_RATE_PER_GB: () => PREMIUM_RATE_PER_GB,
36
+ REUSE_FLAT_CENTS: () => REUSE_FLAT_CENTS,
37
+ STANDARD_CPM_CENTS: () => STANDARD_CPM_CENTS,
38
+ STANDARD_RATE_PER_GB: () => STANDARD_RATE_PER_GB,
39
+ ai: () => ai,
40
+ channels: () => channels,
41
+ conversionRate: () => conversionRate,
42
+ free: () => free,
43
+ plans: () => plans,
44
+ resolvePlan: () => resolvePlan,
45
+ scrape: () => scrape,
46
+ sending: () => sending,
47
+ unitAmountDecimal: () => unitAmountDecimal
48
+ });
49
+ module.exports = __toCommonJS(pricing_exports);
50
+
51
+ // lib/features.js
52
+ var page = {
53
+ qrcode: {
54
+ key: "page:qrcode",
55
+ error: "Plan does not include qrcodes",
56
+ feature: "Page qrcode management"
57
+ },
58
+ shortcode: {
59
+ key: "page:shortcode",
60
+ error: "Plan does not include shortcodes",
61
+ feature: "Page shortcode management"
62
+ },
63
+ slug: {
64
+ key: "page:slug",
65
+ error: "Plan does not include url customization",
66
+ feature: "Page slug customization"
67
+ }
68
+ };
69
+ var fields = {
70
+ additional: {
71
+ key: "campaign:fields:additional",
72
+ error: "Plan does not include additional fields",
73
+ feature: "Campaign additional fields"
74
+ },
75
+ lead: {
76
+ key: "campaign:fields:lead",
77
+ error: "Plan does not include lead fields",
78
+ feature: "Campaign lead fields"
79
+ }
80
+ };
81
+ var field = {
82
+ email: {
83
+ key: "campaign:field:email",
84
+ error: "Plan does not include email field",
85
+ feature: "Campaign email field"
86
+ },
87
+ name: {
88
+ key: "campaign:field:name",
89
+ error: "Plan does not include name field",
90
+ feature: "Campaign name field"
91
+ },
92
+ number: {
93
+ key: "campaign:field:number",
94
+ error: "Plan does not include number field",
95
+ feature: "Campaign number field"
96
+ },
97
+ phone: {
98
+ key: "campaign:field:phone",
99
+ error: "Plan does not include phone field",
100
+ feature: "Campaign phone field"
101
+ },
102
+ select: {
103
+ key: "campaign:field:select",
104
+ error: "Plan does not include dropdown field",
105
+ feature: "Campaign dropdown field"
106
+ },
107
+ text: {
108
+ key: "campaign:field:text",
109
+ error: "Plan does not include short text field",
110
+ feature: "Campaign short text field"
111
+ },
112
+ textarea: {
113
+ key: "campaign:field:textarea",
114
+ error: "Plan does not include long text field",
115
+ feature: "Campaign long text field"
116
+ }
117
+ };
118
+ var connection = {
119
+ mailchimp: {
120
+ key: "organization:connection:mailchimp",
121
+ error: "Plan does not include Mailchimp connection",
122
+ feature: "Mailchimp connection"
123
+ },
124
+ sender: {
125
+ key: "organization:connection:sender",
126
+ error: "Plan does not include a verified sending domain",
127
+ feature: "Sending domain connection"
128
+ },
129
+ sendgrid: {
130
+ key: "organization:connection:sendgrid",
131
+ error: "Plan does not include SendGrid connection",
132
+ feature: "SendGrid connection"
133
+ },
134
+ shopify: {
135
+ key: "organization:connection:shopify",
136
+ error: "Plan does not include Shopify connection",
137
+ feature: "Shopify connection"
138
+ },
139
+ twilio: {
140
+ key: "organization:connection:twilio",
141
+ error: "Plan does not include Twilio connection",
142
+ feature: "Twilio connection"
143
+ },
144
+ webhook: {
145
+ key: "organization:connection:webhook",
146
+ error: "Plan does not include Webhook connection",
147
+ feature: "Webhook connection"
148
+ }
149
+ };
150
+ var organization = {
151
+ advertisements: {
152
+ key: "organization:advertisements",
153
+ error: "Your plan does not include advertisements",
154
+ feature: "Organization advertisement management"
155
+ },
156
+ affiliates: {
157
+ key: "organization:affiliates",
158
+ error: "Your plan does not include affiliates",
159
+ feature: "Organization affiliates management"
160
+ },
161
+ analytics: {
162
+ key: "organization:analytics",
163
+ error: "Your plan does not include analytics",
164
+ feature: "Organization analytics management"
165
+ },
166
+ brands: {
167
+ key: "organization:brands",
168
+ error: "Your plan does not include brands",
169
+ feature: "Organization brands management"
170
+ },
171
+ members: {
172
+ key: "organization:members",
173
+ error: "Your plan does not include team members",
174
+ feature: "Organization members management"
175
+ },
176
+ reports: {
177
+ key: "organization:report",
178
+ error: "Plan does not include report generation",
179
+ feature: "Organization report generation"
180
+ },
181
+ subdomain: {
182
+ key: "organization:subdomain",
183
+ error: "Plan does not include subdomain customization",
184
+ feature: "Organization subdomain customization"
185
+ }
186
+ };
187
+
188
+ // index.js
189
+ var import_currency_codes = require("currency-codes");
190
+ var import_nanoid = require("nanoid");
191
+
192
+ // lib/color.js
193
+ var import_tinycolor2 = __toESM(require("tinycolor2"), 1);
194
+ var colorFormatted = (value) => {
195
+ const color = (0, import_tinycolor2.default)(value);
196
+ const attributes = {
197
+ brightness: color.getBrightness(),
198
+ dark: color.isDark(),
199
+ light: color.isLight(),
200
+ luminance: color.getLuminance()
201
+ };
202
+ return {
203
+ attributes,
204
+ hex: color.toHexString(),
205
+ hsl: color.toHsl(),
206
+ hsv: color.toHsv(),
207
+ rgb: color.toRgbString()
208
+ };
209
+ };
210
+ var colorAccessible = (background2) => {
211
+ const white = "#ffffff";
212
+ const black = "#000000";
213
+ return import_tinycolor2.default.isReadable(
214
+ background2,
215
+ white,
216
+ {
217
+ level: "AA",
218
+ size: "normal"
219
+ }
220
+ ) ? white : black;
221
+ };
222
+
223
+ // lib/constants.js
224
+ var font = {
225
+ family: "Roboto Flex",
226
+ transform: "none",
227
+ weight: "regular"
228
+ };
229
+ var background = "#ffffff";
230
+ var style = {
231
+ background: {
232
+ color: colorFormatted(background)
233
+ },
234
+ body: font,
235
+ button: {
236
+ background: {
237
+ color: colorFormatted(background)
238
+ },
239
+ radius: 0,
240
+ text: {
241
+ color: colorFormatted(colorAccessible(background))
242
+ }
243
+ },
244
+ heading: font,
245
+ input: {
246
+ radius: 0
247
+ },
248
+ text: {
249
+ color: colorFormatted(colorAccessible(background))
250
+ }
251
+ };
252
+
253
+ // index.js
254
+ var nanoid = (0, import_nanoid.customAlphabet)("0123456789abcdefghijklmnopqrstuvwxyz", 8);
255
+ var infinite = 1e300;
256
+ var megabyte = 1024 * 1024;
257
+ var gigabyte = megabyte * 1024;
258
+ var currencies = import_currency_codes.data.map((item) => ({
259
+ ...item,
260
+ key: item.currency,
261
+ value: item.code
262
+ }));
263
+
264
+ // lib/plans.js
265
+ var featuresFor = (array = []) => Object.values({
266
+ ...connection,
267
+ ...organization,
268
+ ...fields,
269
+ ...field,
270
+ ...page
271
+ }).reduce(
272
+ (accumulator, { key, error, feature }) => {
273
+ if (array.includes(key)) {
274
+ accumulator.granted[key] = feature;
275
+ } else {
276
+ accumulator.denied[key] = error;
277
+ }
278
+ return accumulator;
279
+ },
280
+ { denied: {}, granted: {} }
281
+ );
282
+ var overage = (actionCents) => ({
283
+ actionCents,
284
+ overages: { actions: String(actionCents) }
285
+ });
286
+ var unitAmountDecimal = (cents) => {
287
+ const value = Number(cents);
288
+ if (cents == null || !Number.isFinite(value)) throw new Error(`Invalid overage rate: ${cents}`);
289
+ return String(value);
290
+ };
291
+ var all = {
292
+ features: (array = []) => featuresFor([
293
+ connection.mailchimp.key,
294
+ connection.sendgrid.key,
295
+ connection.shopify.key,
296
+ connection.twilio.key,
297
+ connection.webhook.key,
298
+ organization.affiliates.key,
299
+ organization.brands.key,
300
+ fields.additional.key,
301
+ fields.lead.key,
302
+ field.email.key,
303
+ field.name.key,
304
+ field.number.key,
305
+ field.phone.key,
306
+ field.select.key,
307
+ field.text.key,
308
+ field.textarea.key,
309
+ page.qrcode.key,
310
+ page.shortcode.key,
311
+ ...array
312
+ ]),
313
+ // `members` and `storage` default to infinite so an unnamed term on a custom
314
+ // plan reads as UNLIMITED rather than absent. Storage used to have no
315
+ // default, so a deal that did not name it resolved to undefined and the
316
+ // organization's usage card simply omitted the row — the same blank field
317
+ // that showed "Unlimited" for members showed nothing at all for storage.
318
+ // Every catalog plan names both, so the defaults only ever apply to a
319
+ // custom plan. `actions` has no default on purpose: an unnamed allowance
320
+ // bills nothing, which is why the availability switch refuses to flip
321
+ // without one.
322
+ limits: ({ actions, members = infinite, storage = infinite }) => ({
323
+ campaign: {
324
+ advertisements: infinite,
325
+ links: infinite,
326
+ fields: infinite,
327
+ pages: infinite
328
+ },
329
+ organization: {
330
+ actions,
331
+ affiliates: infinite,
332
+ brands: infinite,
333
+ campaigns: infinite,
334
+ members,
335
+ storage
336
+ }
337
+ })
338
+ };
339
+ var free = {
340
+ conversion: 3,
341
+ features: all.features(),
342
+ limits: all.limits({
343
+ actions: 200,
344
+ members: 0,
345
+ storage: gigabyte * 5
346
+ }),
347
+ title: "Free"
348
+ };
349
+ var plans = {
350
+ DB00002: {
351
+ // A verified sending domain is a PAID capability: free plans cannot send
352
+ // lead-facing email at all (the send path gates on an active
353
+ // subscription), so granting it there would offer a domain that can
354
+ // never send from.
355
+ features: all.features([connection.sender.key, organization.members.key]),
356
+ limits: all.limits({ actions: 5e3, members: 3, storage: gigabyte * 10 }),
357
+ marketing: {
358
+ description: "Tools to fine-tune campaigns and improve lead quality.",
359
+ features: [],
360
+ limits: [
361
+ ["Actions per month", "5,000"],
362
+ ["Affiliates", "Unlimited"],
363
+ ["Brands", "Unlimited"],
364
+ ["Campaigns", "Unlimited"],
365
+ ["Pages", "Unlimited"],
366
+ ["Members", "3"],
367
+ ["Storage", "10GB"]
368
+ ]
369
+ },
370
+ ...overage(2.5),
371
+ title: "Starter",
372
+ conversion: 2
373
+ },
374
+ DB00003: {
375
+ features: all.features([
376
+ connection.sender.key,
377
+ organization.advertisements.key,
378
+ organization.analytics.key,
379
+ organization.members.key,
380
+ organization.subdomain.key,
381
+ page.slug.key
382
+ ]),
383
+ limits: all.limits({ actions: 15e3, members: 5, storage: gigabyte * 20 }),
384
+ marketing: {
385
+ description: "Expand your reach and grow your lead pipeline.",
386
+ features: [
387
+ "Analytics",
388
+ "Custom subdomain / URLs",
389
+ "Confirmation page ads"
390
+ ],
391
+ limits: [
392
+ ["Actions per month", "15,000"],
393
+ ["Affiliates", "Unlimited"],
394
+ ["Brands", "Unlimited"],
395
+ ["Campaigns", "Unlimited"],
396
+ ["Pages", "Unlimited"],
397
+ ["Members", "5"],
398
+ ["Storage", "20GB"]
399
+ ]
400
+ },
401
+ ...overage(2),
402
+ title: "Pro",
403
+ conversion: 1.5
404
+ },
405
+ DB00004: {
406
+ features: all.features([
407
+ connection.sender.key,
408
+ organization.advertisements.key,
409
+ organization.analytics.key,
410
+ organization.members.key,
411
+ organization.subdomain.key,
412
+ page.slug.key
413
+ ]),
414
+ limits: all.limits({ actions: 4e4, members: 10, storage: gigabyte * 50 }),
415
+ marketing: {
416
+ description: "Accelerate acquisition with more power and flexibility.",
417
+ features: [
418
+ "Analytics",
419
+ "Custom subdomain / URLs",
420
+ "Confirmation page ads"
421
+ ],
422
+ limits: [
423
+ ["Actions per month", "40,000"],
424
+ ["Affiliates", "Unlimited"],
425
+ ["Brands", "Unlimited"],
426
+ ["Campaigns", "Unlimited"],
427
+ ["Pages", "Unlimited"],
428
+ ["Members", "10"],
429
+ ["Storage", "50GB"]
430
+ ]
431
+ },
432
+ ...overage(1.85),
433
+ title: "Premium",
434
+ conversion: 1
435
+ },
436
+ DB00005: {
437
+ features: all.features([
438
+ connection.sender.key,
439
+ organization.advertisements.key,
440
+ organization.analytics.key,
441
+ organization.members.key,
442
+ organization.subdomain.key,
443
+ page.slug.key
444
+ ]),
445
+ limits: all.limits({ actions: 1e5, members: infinite, storage: gigabyte * 100 }),
446
+ marketing: {
447
+ description: "Built for brands focused on results.",
448
+ features: [
449
+ "Analytics",
450
+ "Custom subdomain / URLs",
451
+ "Confirmation page ads"
452
+ ],
453
+ limits: [
454
+ ["Actions per month", "100,000"],
455
+ ["Affiliates", "Unlimited"],
456
+ ["Brands", "Unlimited"],
457
+ ["Campaigns", "Unlimited"],
458
+ ["Pages", "Unlimited"],
459
+ ["Members", "Unlimited"],
460
+ ["Storage", "100GB"]
461
+ ]
462
+ },
463
+ ...overage(1.5),
464
+ title: "Elite",
465
+ conversion: 0.5
466
+ }
467
+ };
468
+ var resolvePlan = (subscription) => {
469
+ var _a, _b;
470
+ const custom = subscription == null ? void 0 : subscription.custom;
471
+ if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
472
+ return {
473
+ // Reusing all.features / all.limits is what keeps a custom plan the same
474
+ // SHAPE as a catalog one: the base feature grants every plan carries, the
475
+ // campaign limits that are always infinite, and members defaulting to
476
+ // infinite when a deal does not name it.
477
+ conversion: custom.conversion ?? free.conversion,
478
+ custom: true,
479
+ // A custom plan is a negotiated PAID deal, so it carries the paid-tier
480
+ // baseline whether or not the deal thought to name it. Today that is the
481
+ // sending domain: every catalog paid tier grants it, and a custom plan
482
+ // silently lacking it would be a support ticket, not a pricing decision.
483
+ features: all.features([connection.sender.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
484
+ limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
485
+ // A custom plan stores its overage BARE on `custom.overages` — a different
486
+ // shape from the catalog's nested one. Number() so a deal stored as a string
487
+ // still resolves to cents-per-action; an unnamed overage stays undefined
488
+ // (it bills nothing) rather than becoming NaN.
489
+ actionCents: custom.overages == null ? void 0 : Number(custom.overages),
490
+ overages: { actions: custom.overages },
491
+ title: custom.title || "Custom"
492
+ };
493
+ };
494
+ var conversionRate = (subscription) => {
495
+ var _a;
496
+ return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
497
+ };
498
+
499
+ // lib/transactions.js
500
+ var import_drawbridge_telemetry = require("@drawbridge/drawbridge-telemetry");
501
+ var insertTransaction = async ({
502
+ db,
503
+ user,
504
+ type,
505
+ category,
506
+ source,
507
+ amount,
508
+ _id,
509
+ stripeInvoiceId,
510
+ stripeEventId,
511
+ session,
512
+ ...rest
513
+ }) => {
514
+ const trace = (0, import_drawbridge_telemetry.currentTraceId)();
515
+ await db.create({
516
+ authenticated: user,
517
+ collection: "transaction",
518
+ data: {
519
+ ..._id && { _id },
520
+ user: user == null ? void 0 : user.id,
521
+ type,
522
+ category,
523
+ source,
524
+ amount,
525
+ ...trace && { trace },
526
+ ...rest,
527
+ ...stripeInvoiceId && { stripeInvoiceId },
528
+ ...stripeEventId && { stripeEventId }
529
+ },
530
+ ...session && { options: { session } }
531
+ });
532
+ };
533
+ var debit = async ({
534
+ db,
535
+ user,
536
+ amount,
537
+ type,
538
+ category,
539
+ source,
540
+ stripeInvoiceId,
541
+ stripeEventId,
542
+ session,
543
+ ...rest
544
+ }) => {
545
+ if (!Number.isInteger(amount) || amount <= 0) {
546
+ throw new Error(`debit() requires a positive integer amount, got ${amount}`);
547
+ }
548
+ if (!type) {
549
+ throw new Error('debit() requires a type (e.g., "ai")');
550
+ }
551
+ if (!source) {
552
+ throw new Error('debit() requires a source ("system" | "admin" | "user")');
553
+ }
554
+ await insertTransaction({
555
+ db,
556
+ user,
557
+ type,
558
+ category,
559
+ source,
560
+ amount: -amount,
561
+ stripeInvoiceId,
562
+ stripeEventId,
563
+ session,
564
+ ...rest
565
+ });
566
+ };
567
+
568
+ // lib/billing.js
569
+ var import_drawbridge_telemetry2 = require("@drawbridge/drawbridge-telemetry");
570
+ var logger = (0, import_drawbridge_telemetry2.createLogger)();
571
+ var MARKUP = 1.3;
572
+ var cost = {
573
+ // gemini-3.5-flash — verified against Google's pricing page 2026-07-09:
574
+ // $0.15 cached / $1.50 input / $9.00 output per 1M tokens (thinking billed at
575
+ // output). ~3.6x the retired 2.5-flash output rate.
576
+ "gemini-3.5-flash": {
577
+ cached: 15,
578
+ input: 150,
579
+ output: 900
580
+ },
581
+ // gemini-3.5-flash-lite — verified against Google's pricing page 2026-08-20:
582
+ // $0.03 cached / $0.30 input / $2.50 output per 1M tokens (thinking billed at
583
+ // output). A fifth of flash on input, ~a quarter on output. Growth's assistant
584
+ // ranks the feed on this tier — one call per page — so its rows were the
585
+ // unpriced ones until now.
586
+ "gemini-3.5-flash-lite": {
587
+ cached: 3,
588
+ input: 30,
589
+ output: 250
590
+ },
591
+ "gemini-2.5-flash": {
592
+ cached: 3,
593
+ input: 30,
594
+ output: 250
595
+ },
596
+ "gemini-2.5-flash-image": {
597
+ cached: 3,
598
+ input: 30,
599
+ output: 3e3
600
+ },
601
+ // gemini-3-pro-image-preview — verified against Google's pricing page
602
+ // 2026-08-12: $2.00 input / $12.00 text output per 1M, and image output
603
+ // tokens at ~$120/1M (a 1K-2K image is 1120 tokens = $0.134, a 4K image
604
+ // 2000 tokens = $0.24). Encoded the flash-image way: one flat output rate
605
+ // that reproduces the per-image price from the tokens usageMetadata
606
+ // reports. Growth's hero generation runs this model today.
607
+ "gemini-3-pro-image-preview": {
608
+ cached: 20,
609
+ input: 200,
610
+ output: 12e3
611
+ }
612
+ };
613
+ var toolCost = {
614
+ search: 3.5
615
+ };
616
+ var toolPricing = Object.fromEntries(
617
+ Object.entries(toolCost).map(([tool, value]) => [
618
+ tool,
619
+ Math.ceil(value * MARKUP)
620
+ ])
621
+ );
622
+ var pricing = Object.fromEntries(
623
+ Object.entries(cost).map(([model, rates]) => [
624
+ model,
625
+ {
626
+ cached: Math.round(rates.cached * MARKUP),
627
+ input: Math.round(rates.input * MARKUP),
628
+ output: Math.round(rates.output * MARKUP)
629
+ }
630
+ ])
631
+ );
632
+ var sumCents = (rates, tokens) => Math.ceil(
633
+ (Number((tokens == null ? void 0 : tokens.cached) || 0) * rates.cached + Number((tokens == null ? void 0 : tokens.input) || 0) * rates.input + (Number((tokens == null ? void 0 : tokens.output) || 0) + Number((tokens == null ? void 0 : tokens.thinking) || 0)) * rates.output) / 1e6
634
+ );
635
+ var sumToolCents = (table, tools) => Object.entries(tools || {}).reduce(
636
+ (total, [name, used]) => total + (used && table[name] ? table[name] : 0),
637
+ 0
638
+ );
639
+ var priceForRequest = (model, usage, tools) => {
640
+ const rates = pricing[model];
641
+ if (!rates) {
642
+ throw new Error(`Unknown model for pricing: ${model}`);
643
+ }
644
+ return sumCents(rates, usage) + Math.ceil(sumToolCents(toolPricing, tools));
645
+ };
646
+ var costForRequest = (model, usage, tools) => {
647
+ const rates = cost[model];
648
+ if (!rates) {
649
+ throw new Error(`Unknown model for cost: ${model}`);
650
+ }
651
+ return sumCents(rates, usage) + Math.ceil(sumToolCents(toolCost, tools));
652
+ };
653
+ var billRequest = async ({ db, user, model, usage, tools }) => {
654
+ const gross = priceForRequest(model, usage, tools);
655
+ const cogs = costForRequest(model, usage, tools);
656
+ await debit({
657
+ db,
658
+ user,
659
+ amount: gross,
660
+ type: "ai",
661
+ category: "usage",
662
+ source: "user",
663
+ ai: {
664
+ name: "google",
665
+ model,
666
+ tokens: usage,
667
+ tools,
668
+ rates: {
669
+ wholesale: cost[model],
670
+ retail: pricing[model]
671
+ },
672
+ totals: {
673
+ cost: cogs,
674
+ net: gross - cogs,
675
+ gross
676
+ }
677
+ }
678
+ });
679
+ };
680
+ var ai = {
681
+ // The rate tables themselves, in cents per 1,000,000 tokens (`tools` in cents
682
+ // per request). Read-only surface for lib/pricing.js — the fee math above is
683
+ // still the only thing that should compute from them.
684
+ rates: { wholesale: cost, retail: pricing, tools: { wholesale: toolCost, retail: toolPricing } },
685
+ // Retail cents for a request (what the user pays).
686
+ price: priceForRequest,
687
+ // Wholesale cents for a request (what we pay the provider).
688
+ cost: costForRequest,
689
+ // Deferred bill() the caller fires on success, so the debit lands only when
690
+ // the request succeeds and bundles into that request's Sentry trace. No user
691
+ // → a no-op.
692
+ bill: ({ db, user, model, usage, tools }) => (user == null ? void 0 : user.id) ? () => billRequest({ db, user, model, usage, tools }) : () => Promise.resolve()
693
+ };
694
+ var STANDARD_RATE_PER_GB = 8;
695
+ var PREMIUM_RATE_PER_GB = 11;
696
+ var STANDARD_CPM_CENTS = 0.15;
697
+ var PREMIUM_CPM_CENTS = 0.25;
698
+ var PREMIUM_HOSTS = /* @__PURE__ */ new Set();
699
+ var LOCAL_FLAT_CENTS = 1;
700
+ var REUSE_FLAT_CENTS = 1;
701
+ var isPremium = (url) => {
702
+ try {
703
+ return PREMIUM_HOSTS.has(new URL(url).hostname);
704
+ } catch {
705
+ return false;
706
+ }
707
+ };
708
+ var ratePerGB = (url) => isPremium(url) ? PREMIUM_RATE_PER_GB : STANDARD_RATE_PER_GB;
709
+ var cpmCents = (url) => isPremium(url) ? PREMIUM_CPM_CENTS : STANDARD_CPM_CENTS;
710
+ var scrapeFee = ({ provider, bytes, requests, url, cold }) => {
711
+ if (!cold) return REUSE_FLAT_CENTS;
712
+ if (provider === "brightdata") {
713
+ return Math.ceil((bytes || 0) / 1e9 * ratePerGB(url) * 100 * MARKUP);
714
+ }
715
+ if (provider === "brightdata-unlocker") {
716
+ return Math.ceil((requests || 0) * cpmCents(url) * MARKUP);
717
+ }
718
+ return LOCAL_FLAT_CENTS;
719
+ };
720
+ var scrapeBreakdown = ({ provider, bytes, requests, url }) => {
721
+ if (provider === "brightdata") {
722
+ return {
723
+ provider,
724
+ basis: "bytes",
725
+ units: bytes || 0,
726
+ rate: ratePerGB(url),
727
+ rateUnit: "GB",
728
+ cents: scrapeFee({ provider, bytes, url, cold: true })
729
+ };
730
+ }
731
+ if (provider === "brightdata-unlocker") {
732
+ return {
733
+ provider,
734
+ basis: "requests",
735
+ units: requests || 0,
736
+ // cpmCents is cents-per-request; ×10 expresses it as dollars per 1,000.
737
+ rate: cpmCents(url) * 10,
738
+ rateUnit: "1K requests",
739
+ cents: scrapeFee({ provider, requests, url, cold: true })
740
+ };
741
+ }
742
+ return { provider: provider || "local", basis: "local", units: null, rate: null, rateUnit: null, cents: LOCAL_FLAT_CENTS };
743
+ };
744
+ var scrape = {
745
+ // Cents for a scrape given its provider/bytes/cold basis.
746
+ fee: scrapeFee,
747
+ // Itemized cold-fee breakdown (basis/units/rate/cents) for display + the scrape doc.
748
+ breakdown: scrapeBreakdown,
749
+ // Deferred bill(scrapeId) the scrape store's resolve() hands the generation
750
+ // flow. Atomically claims the cold (first-time) fee via the `charged` flag so
751
+ // a BrightData scrape's metered cost is recovered ONCE; later reuses pay the
752
+ // flat rate. Best-effort — a billing hiccup never fails generation.
753
+ bill: ({ controller, user, page: page2, url }) => async (scrapeId) => {
754
+ var _a;
755
+ if (!(user == null ? void 0 : user.id) || !scrapeId) return;
756
+ try {
757
+ const claim = await controller.update({
758
+ collection: "scrape",
759
+ data: { $set: { charged: true } },
760
+ options: { bypassDocumentValidation: true },
761
+ query: { id: scrapeId, charged: { $ne: true } }
762
+ });
763
+ const cents = scrapeFee({
764
+ provider: (_a = page2 == null ? void 0 : page2.provider) == null ? void 0 : _a.name,
765
+ bytes: page2 == null ? void 0 : page2.bytes,
766
+ requests: page2 == null ? void 0 : page2.requests,
767
+ url: (page2 == null ? void 0 : page2.url) || url,
768
+ cold: Boolean(claim == null ? void 0 : claim.value)
769
+ });
770
+ if (cents > 0) await debit({ db: controller, user, amount: cents, type: "ai", category: "usage", source: "user" });
771
+ } catch (error) {
772
+ logger.error(error, { extra: { action: "generation.scrape.bill", scrapeId } });
773
+ }
774
+ }
775
+ };
776
+
777
+ // lib/pricing.js
778
+ var sending = {
779
+ email: {
780
+ // Fraction of monthlyCeiling that raises the alarm. Far enough ahead of
781
+ // the wall to act on, high enough not to fire on ordinary growth.
782
+ alertThreshold: 0.8,
783
+ // SendGrid Essentials 50K — emails per calendar month, PLATFORM-WIDE and
784
+ // across every send path: lead-facing mail, workflow steps, and the sign-in
785
+ // codes and account mail that no plan allowance meters.
786
+ monthlyCeiling: 5e4
787
+ }
788
+ };
789
+ var channels = {
790
+ email: {
791
+ actionsPerSend: 1,
792
+ includedInAllowance: true
793
+ },
794
+ sms: {
795
+ // Two actions PER SEGMENT (a long message is several segments), billed from
796
+ // the FIRST segment and never drawn from the plan's included allowance —
797
+ // carrier cost is real from message one, so there is no free tier of it.
798
+ actionsPerSegment: 2,
799
+ includedInAllowance: false
800
+ }
801
+ };
802
+ // Annotate the CommonJS export names for ESM import in node:
803
+ 0 && (module.exports = {
804
+ LOCAL_FLAT_CENTS,
805
+ MARKUP,
806
+ PREMIUM_CPM_CENTS,
807
+ PREMIUM_RATE_PER_GB,
808
+ REUSE_FLAT_CENTS,
809
+ STANDARD_CPM_CENTS,
810
+ STANDARD_RATE_PER_GB,
811
+ ai,
812
+ channels,
813
+ conversionRate,
814
+ free,
815
+ plans,
816
+ resolvePlan,
817
+ scrape,
818
+ sending,
819
+ unitAmountDecimal
820
+ });