usebecky 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,218 @@
1
+ import type { HttpClient } from '../lib/http.ts';
2
+ import type { AccessInfo, Order, OrderStatus, Result, Subscription } from '../lib/types.ts';
3
+ /** What `updateOrder()` changes. */
4
+ export interface OrderUpdate {
5
+ /** `'shipped'`, `'delivered'`, or `'unfulfilled'` to undo a mistake (the buyer isn't emailed again). */
6
+ fulfillment?: 'shipped' | 'delivered' | 'unfulfilled';
7
+ carrier?: string | null;
8
+ trackingNumber?: string | null;
9
+ /** The carrier's tracking page (https://…). The shipped email's button opens it. */
10
+ trackingUrl?: string | null;
11
+ /** Your team's note (never shown to the buyer). `null` removes it. */
12
+ note?: string | null;
13
+ /** `false`: no shipped email this time (order.shipped still goes out). Default true. */
14
+ notify?: boolean;
15
+ }
16
+ /** Details of a gift (only you see the note). */
17
+ export interface GiftDetails {
18
+ /** Running right now (not ended, not past `ends_at`). */
19
+ active: boolean;
20
+ starts_at: string;
21
+ /** When it ends; `null` = no end date. */
22
+ ends_at: string | null;
23
+ note: string | null;
24
+ /** Who gave it: the dashboard user's email, or `'secret key'`. */
25
+ gifted_by: string | null;
26
+ ended_at: string | null;
27
+ /** Why it ended: it reached `ends_at`, you ended it, or the user started paying for the product. */
28
+ end_reason: 'expired' | 'revoked' | 'paid' | null;
29
+ }
30
+ /** A product you gave to a user for free. */
31
+ export interface Gift extends Omit<Subscription, 'gift' | 'source'> {
32
+ source: 'gift';
33
+ gift: GiftDetails;
34
+ /** Same as `gift.active`. */
35
+ active: boolean;
36
+ user_id: string | null;
37
+ email: string | null;
38
+ /** Always null for gifts (nothing was paid). */
39
+ stripe_subscription_id: null;
40
+ stripe_customer_id: null;
41
+ amount: null;
42
+ currency: null;
43
+ interval: null;
44
+ quantity: number;
45
+ updated_at: string;
46
+ }
47
+ /** A subscription as your server sees it: plus who has it and the Stripe ids. */
48
+ export interface ServerSubscription extends Omit<Subscription, 'gift'> {
49
+ user_id: string | null;
50
+ email: string | null;
51
+ /** Gifts: the gift's details (with your note). `null` for paid subscriptions. */
52
+ gift: GiftDetails | null;
53
+ /** `null` for gifts. */
54
+ stripe_subscription_id: string | null;
55
+ stripe_customer_id: string | null;
56
+ /** Price in the smallest currency unit (cents), `null` for gifts. */
57
+ amount: number | null;
58
+ currency: string | null;
59
+ interval: 'day' | 'week' | 'month' | 'year' | null;
60
+ quantity: number;
61
+ past_due_since: string | null;
62
+ /** When it was canceled (also when it still runs until the period end). */
63
+ canceled_at: string | null;
64
+ updated_at: string;
65
+ }
66
+ export interface GiftOptions {
67
+ /** When the gift ends (a Date or an ISO date like '2027-01-31'). Leave out for no end date. */
68
+ endsAt?: Date | string | null;
69
+ /** Why you gave it (only you see it), e.g. 'Beta tester'. Up to 500 characters. */
70
+ note?: string;
71
+ }
72
+ export interface ServerPayments {
73
+ /**
74
+ * Does this user (object or id) have the feature (paid, trial, purchase or gift)? `false` on any error. Never throws.
75
+ * Right for paywalls. To decide something about money (delete an account, downgrade, cut a quota) use
76
+ * `checkAccess()`: it tells a network error apart from "doesn't pay".
77
+ */
78
+ hasAccess(userOrId: {
79
+ id: string;
80
+ } | string | null | undefined, feature: string): Promise<boolean>;
81
+ /**
82
+ * Like `hasAccess`, but errors come back as `error` instead of `false`, and it says where the access comes from:
83
+ * `'subscription'` (paid or trial), `'purchase'`, `'gift'` or `null`. No user (`null`, e.g. signed out): no access.
84
+ *
85
+ * ```ts
86
+ * const { data, error } = await baas.payments.checkAccess(user, 'pro')
87
+ * if (error) return res.status(503).send('Try again in a moment') // unknown: don't treat as "not paying"
88
+ * if (data.access) ...
89
+ * ```
90
+ */
91
+ checkAccess(userOrId: {
92
+ id: string;
93
+ } | string | null | undefined, feature: string): Promise<Result<AccessInfo>>;
94
+ /**
95
+ * The user's subscriptions, newest first: running ones by default (anything not ended, also those that end at the
96
+ * period end), `status: 'ended'` or `'all'` for the others. Paid ones and gifts.
97
+ *
98
+ * ```ts
99
+ * const { data: subs } = await baas.payments.listSubscriptions(user)
100
+ * ```
101
+ */
102
+ listSubscriptions(userOrId: {
103
+ id: string;
104
+ } | string, options?: {
105
+ status?: 'active' | 'ended' | 'all';
106
+ }): Promise<Result<ServerSubscription[]>>;
107
+ /**
108
+ * Cancel a paid subscription (its usebecky `id` or Stripe id `sub_…`). By default at the end of the paid period:
109
+ * the user keeps access until then and is not charged again. `atPeriodEnd: false` ends it now (no refund) and the
110
+ * access with it, e.g. before deleting an account. Already canceled: returned unchanged. Gifts: `revokeGift()`.
111
+ *
112
+ * ```ts
113
+ * for (const s of (await baas.payments.listSubscriptions(user)).data ?? []) {
114
+ * if (s.source !== 'gift') await baas.payments.cancelSubscription(s.id, { atPeriodEnd: false })
115
+ * }
116
+ * ```
117
+ * Errors: `subscription_not_found`, `gift_subscription`, `stripe_not_configured`, Stripe's own.
118
+ */
119
+ cancelSubscription(id: string, options?: {
120
+ atPeriodEnd?: boolean;
121
+ }): Promise<Result<ServerSubscription>>;
122
+ /**
123
+ * Test mode only, for automated tests: buy a subscription for a user with one of Stripe's test cards, without a
124
+ * browser. It is a real Stripe test subscription (paid now, or its trial starts) and grants access at once.
125
+ *
126
+ * ```ts
127
+ * const { data: sub } = await baas.payments.test.subscribe(user, 'pro_monthly', { trial: false })
128
+ * await baas.payments.cancelSubscription(sub!.id, { atPeriodEnd: false })
129
+ * ```
130
+ * `card: 'declined'` makes the payment fail (error `card_declined`). Errors: `live_mode` (never in live mode),
131
+ * `already_subscribed`, `price_not_found`, `not_a_subscription`, `stripe_not_connected`.
132
+ */
133
+ readonly test: {
134
+ subscribe(userOrId: {
135
+ id: string;
136
+ } | string, price: string, options?: {
137
+ card?: 'visa' | 'declined';
138
+ trial?: boolean;
139
+ }): Promise<Result<ServerSubscription>>;
140
+ };
141
+ /** Take back any cancellation at the period end (also one set as a date in Stripe): the subscription renews again.
142
+ * Error `subscription_ended` once it ended. */
143
+ resumeSubscription(id: string): Promise<Result<ServerSubscription>>;
144
+ /**
145
+ * Give a user a product for free, optionally until a date. No payment, no Stripe; the user gets access
146
+ * right away (`hasAccess`, access rules, `payments.me()` with `source: 'gift'`).
147
+ *
148
+ * ```ts
149
+ * const { data, error } = await baas.payments.gift(req.user, 'pro', { endsAt: '2027-01-31', note: 'Beta tester' })
150
+ * ```
151
+ * `user`: a user object, a user id, or `{ email }`. `product`: the product key (or id).
152
+ * Errors: `already_subscribed` / `already_purchased` (they already pay), `gift_exists`, `user_not_found`, `product_not_found`.
153
+ */
154
+ gift(user: {
155
+ id: string;
156
+ } | {
157
+ email: string;
158
+ } | string, product: string, options?: GiftOptions): Promise<Result<Gift>>;
159
+ /** Change a running gift: another product, a new end date (`null` = no end date) or note. */
160
+ updateGift(id: string, changes: {
161
+ product?: string;
162
+ endsAt?: Date | string | null;
163
+ note?: string | null;
164
+ }): Promise<Result<Gift>>;
165
+ /** End a gift now (the user loses access). Ending an already ended gift returns it unchanged. */
166
+ revokeGift(id: string): Promise<Result<Gift>>;
167
+ /** Gifts, newest first: running ones by default (`status: 'ended'` or `'all'` for the others), optionally for one user. */
168
+ listGifts(options?: {
169
+ userId?: string;
170
+ status?: 'active' | 'ended' | 'all';
171
+ limit?: number;
172
+ }): Promise<Result<Gift[]>>;
173
+ /**
174
+ * Shop orders, newest first (completed checkouts only), of one mode: the project's by default. Pass `next_cursor`
175
+ * back as `cursor` for the next page.
176
+ *
177
+ * ```ts
178
+ * const { data } = await baas.payments.listOrders({ status: 'paid', limit: 50 })
179
+ * ```
180
+ */
181
+ listOrders(options?: {
182
+ userId?: string;
183
+ status?: OrderStatus | OrderStatus[];
184
+ mode?: 'test' | 'live';
185
+ limit?: number;
186
+ cursor?: string;
187
+ }): Promise<Result<{
188
+ orders: ServerOrder[];
189
+ next_cursor: string | null;
190
+ prev_cursor: string | null;
191
+ }>>;
192
+ /** One order with its lines, who bought it, the Stripe ids and links to its files. */
193
+ getOrder(id: string): Promise<Result<ServerOrder>>;
194
+ /**
195
+ * Change an order's shipping, tracking or note (PATCH /payments/v1/orders/:id). Marking it shipped sends
196
+ * `order.shipped` and the shipped email to the buyer once; delivered sends `order.delivered`.
197
+ *
198
+ * ```ts
199
+ * await baas.payments.updateOrder(order.id, { fulfillment: 'shipped', carrier: 'DHL', trackingNumber: '00340434161094042557' })
200
+ * ```
201
+ * Errors: `order_not_found`, `order_not_paid`, `nothing_to_ship` (digital products only), `invalid_order_update`.
202
+ */
203
+ updateOrder(id: string, changes: OrderUpdate): Promise<Result<ServerOrder>>;
204
+ /** `updateOrder(id, { fulfillment: 'shipped', ...tracking })`. */
205
+ markShipped(id: string, tracking?: Pick<OrderUpdate, 'carrier' | 'trackingNumber' | 'trackingUrl' | 'notify'>): Promise<Result<ServerOrder>>;
206
+ /** `updateOrder(id, { fulfillment: 'delivered' })`. */
207
+ markDelivered(id: string): Promise<Result<ServerOrder>>;
208
+ }
209
+ /** An order as your server sees it: plus the buyer's user id (null for guests) and the Stripe ids. */
210
+ export interface ServerOrder extends Order {
211
+ user_id: string | null;
212
+ promotion_code: string | null;
213
+ purchase_id: string | null;
214
+ stripe_checkout_session_id: string | null;
215
+ stripe_payment_intent_id: string | null;
216
+ stripe_customer_id: string | null;
217
+ }
218
+ export declare function createServerPayments(http: HttpClient): ServerPayments;
@@ -0,0 +1,150 @@
1
+ // Payments from your server (secret key): access checks, subscriptions, gifts and shop orders.
2
+ //
3
+ // await baas.payments.hasAccess(req.user, 'pro') // true / false, never throws
4
+ // await baas.payments.checkAccess(user, 'pro') // { data: { access, source }, error }
5
+ // await baas.payments.listSubscriptions(user) // the user's running subscriptions
6
+ // await baas.payments.cancelSubscription(sub.id) // at the period end (atPeriodEnd: false: now)
7
+ // await baas.payments.gift(user, 'pro', { endsAt: '2027-01-31', note: 'Beta tester' }) // give a product for free
8
+ // await baas.payments.revokeGift(giftId) // end it now
9
+ // await baas.payments.listOrders({ status: 'paid' }) // orders to fulfil
10
+ // await baas.payments.markShipped(order.id, { carrier: 'DHL', trackingNumber: '0034…' }) // shipped: event + email
11
+ //
12
+ // A gift is a subscription with `source: 'gift'`: every access check treats it like an active subscription
13
+ // until it ends. No Stripe payment, never counted as revenue. Endpoints: /payments/v1/access, /payments/v1/subscriptions,
14
+ // /payments/v1/gifts, /payments/v1/orders (docs/API.md).
15
+ import { UseBeckyError } from "../lib/errors.js";
16
+ function invalid(message, hint) {
17
+ return new UseBeckyError({ code: 'invalid_input', message, hint, status: 0 });
18
+ }
19
+ function dateOrNull(v) {
20
+ if (v === undefined)
21
+ return undefined;
22
+ if (v === null)
23
+ return null;
24
+ return v instanceof Date ? v.toISOString() : v;
25
+ }
26
+ export function createServerPayments(http) {
27
+ return {
28
+ async hasAccess(userOrId, feature) {
29
+ const id = typeof userOrId === 'string' ? userOrId : userOrId?.id;
30
+ if (!id)
31
+ return false;
32
+ try {
33
+ const res = await http.request(`/payments/v1/access/${encodeURIComponent(feature)}`, { query: { user_id: id } });
34
+ return !res.error && res.data?.access === true;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ },
40
+ async checkAccess(userOrId, feature) {
41
+ const id = typeof userOrId === 'string' ? userOrId : userOrId?.id;
42
+ if (userOrId === null || userOrId === undefined)
43
+ return { data: { access: false, source: null }, error: null }; // signed out
44
+ if (!id)
45
+ return { data: null, error: invalid('Say whose access to check: a user object or a user id.', "Example: baas.payments.checkAccess(req.user, 'pro')") };
46
+ if (!feature)
47
+ return { data: null, error: invalid('Say which feature to check, like "pro".') };
48
+ const res = await http.request(`/payments/v1/access/${encodeURIComponent(feature)}`, { token: null, query: { user_id: id } });
49
+ return res.error ? { data: null, error: res.error } : { data: { access: res.data?.access === true, source: res.data?.source ?? null }, error: null };
50
+ },
51
+ async listSubscriptions(userOrId, options = {}) {
52
+ const id = typeof userOrId === 'string' ? userOrId : userOrId?.id;
53
+ if (!id)
54
+ return { data: null, error: invalid('Say whose subscriptions to list: a user object or a user id.') };
55
+ const res = await http.request('/payments/v1/subscriptions', { token: null, query: { user_id: id, status: options.status } });
56
+ return res.error ? { data: null, error: res.error } : { data: res.data ?? [], error: null };
57
+ },
58
+ async cancelSubscription(id, options = {}) {
59
+ if (!id)
60
+ return { data: null, error: invalid('Pass the id of the subscription (from baas.payments.listSubscriptions()).') };
61
+ const res = await http.request(`/payments/v1/subscriptions/${encodeURIComponent(id)}/cancel`, {
62
+ method: 'POST',
63
+ token: null,
64
+ body: { at_period_end: options.atPeriodEnd ?? true },
65
+ });
66
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
67
+ },
68
+ async resumeSubscription(id) {
69
+ if (!id)
70
+ return { data: null, error: invalid('Pass the id of the subscription (from baas.payments.listSubscriptions()).') };
71
+ const res = await http.request(`/payments/v1/subscriptions/${encodeURIComponent(id)}/resume`, { method: 'POST', token: null, body: {} });
72
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
73
+ },
74
+ test: {
75
+ async subscribe(userOrId, price, options = {}) {
76
+ const id = typeof userOrId === 'string' ? userOrId : userOrId?.id;
77
+ if (!id)
78
+ return { data: null, error: invalid('Say who buys: a user object or a user id.') };
79
+ if (!price)
80
+ return { data: null, error: invalid('Say what they buy: a price key, like "pro_monthly".') };
81
+ const res = await http.request('/payments/v1/test/subscriptions', { method: 'POST', token: null, body: { user_id: id, price, card: options.card, trial: options.trial } });
82
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
83
+ },
84
+ },
85
+ async gift(user, product, options = {}) {
86
+ const who = typeof user === 'string' ? { user_id: user } : user && 'id' in user && user.id ? { user_id: user.id } : user && 'email' in user && user.email ? { email: user.email } : null;
87
+ if (!who)
88
+ return { data: null, error: invalid('Say who gets the gift: a user object, a user id, or { email }.', "Example: baas.payments.gift(req.user, 'pro')") };
89
+ if (!product)
90
+ return { data: null, error: invalid('Say what to give: the product key, like "pro".') };
91
+ const res = await http.request('/payments/v1/gifts', {
92
+ method: 'POST',
93
+ token: null,
94
+ body: { ...who, product, ends_at: dateOrNull(options.endsAt), note: options.note },
95
+ });
96
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
97
+ },
98
+ async updateGift(id, changes) {
99
+ if (!id)
100
+ return { data: null, error: invalid('Pass the id of the gift (returned by baas.payments.gift()).') };
101
+ const res = await http.request(`/payments/v1/gifts/${encodeURIComponent(id)}`, {
102
+ method: 'PATCH',
103
+ token: null,
104
+ body: { product: changes?.product, ends_at: dateOrNull(changes?.endsAt), note: changes?.note },
105
+ });
106
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
107
+ },
108
+ async revokeGift(id) {
109
+ if (!id)
110
+ return { data: null, error: invalid('Pass the id of the gift (returned by baas.payments.gift()).') };
111
+ const res = await http.request(`/payments/v1/gifts/${encodeURIComponent(id)}`, { method: 'DELETE', token: null });
112
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
113
+ },
114
+ async listGifts(options = {}) {
115
+ const res = await http.request('/payments/v1/gifts', { token: null, query: { user_id: options.userId, status: options.status, limit: options.limit } });
116
+ return res.error ? { data: null, error: res.error } : { data: res.data ?? [], error: null };
117
+ },
118
+ async listOrders(options = {}) {
119
+ const status = Array.isArray(options.status) ? options.status.join(',') : options.status;
120
+ const res = await http.request('/payments/v1/orders', {
121
+ token: null,
122
+ query: { user_id: options.userId, status, mode: options.mode, limit: options.limit, cursor: options.cursor },
123
+ });
124
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
125
+ },
126
+ async getOrder(id) {
127
+ if (!id)
128
+ return { data: null, error: invalid('Pass the id of the order.') };
129
+ const res = await http.request(`/payments/v1/orders/${encodeURIComponent(id)}`, { token: null });
130
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
131
+ },
132
+ async updateOrder(id, changes) {
133
+ if (!id)
134
+ return { data: null, error: invalid('Pass the id of the order.') };
135
+ const c = changes ?? {};
136
+ const res = await http.request(`/payments/v1/orders/${encodeURIComponent(id)}`, {
137
+ method: 'PATCH',
138
+ token: null,
139
+ body: { fulfillment: c.fulfillment, carrier: c.carrier, tracking_number: c.trackingNumber, tracking_url: c.trackingUrl, note: c.note, notify: c.notify },
140
+ });
141
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
142
+ },
143
+ markShipped(id, tracking = {}) {
144
+ return this.updateOrder(id, { fulfillment: 'shipped', ...tracking });
145
+ },
146
+ markDelivered(id) {
147
+ return this.updateOrder(id, { fulfillment: 'delivered' });
148
+ },
149
+ };
150
+ }
@@ -0,0 +1,85 @@
1
+ import type { HttpClient } from '../lib/http.ts';
2
+ import type { Result } from '../lib/types.ts';
3
+ import type { PushPlatform } from '../push/client.ts';
4
+ export interface PushSendOptions {
5
+ /** Send to these users' devices (user ids, up to 1000). Leave out (and `tag`) to send to every device. */
6
+ userIds?: string[];
7
+ /** Send to devices registered with this tag, e.g. 'news'. */
8
+ tag?: string;
9
+ /** Bold first line, up to 200 characters. */
10
+ title: string;
11
+ /** The text under the title, up to 2000 characters. */
12
+ body: string;
13
+ /** Opened when the notification is tapped: a web link or a deep link like 'myapp://orders/42'. */
14
+ url?: string;
15
+ /** Extra values your app receives with the notification (sent as text), up to 2 KB. */
16
+ data?: Record<string, string | number | boolean>;
17
+ }
18
+ export interface PushPlatformStats {
19
+ sent: number;
20
+ failed: number;
21
+ pending: number;
22
+ }
23
+ export interface PushMessage {
24
+ id: string;
25
+ title: string;
26
+ body: string;
27
+ url: string | null;
28
+ data: Record<string, string> | null;
29
+ audience: {
30
+ type: 'all';
31
+ } | {
32
+ type: 'users';
33
+ user_ids: string[];
34
+ } | {
35
+ type: 'tag';
36
+ tag: string;
37
+ } | {
38
+ type: 'devices';
39
+ device_ids: string[];
40
+ };
41
+ source: 'dashboard' | 'api' | 'test';
42
+ /** 'queued' → 'sending' → 'sent' (or 'failed' when nothing could be delivered). */
43
+ status: 'queued' | 'sending' | 'sent' | 'failed';
44
+ /** How many devices it was addressed to. */
45
+ devices: number;
46
+ sent: number;
47
+ failed: number;
48
+ stats: Record<PushPlatform, PushPlatformStats>;
49
+ error: string | null;
50
+ created_at: string;
51
+ started_at: string | null;
52
+ finished_at: string | null;
53
+ }
54
+ export interface ServerPush {
55
+ /**
56
+ * Send a push notification to your users' phones and browsers.
57
+ *
58
+ * ```ts
59
+ * const { data, error } = await baas.push.send({ userIds: [user.id], title: 'Your order shipped', body: 'It arrives Tuesday.', url: 'myapp://orders/42' })
60
+ * // data: { id: '…', status: 'queued', devices: 2, … }
61
+ * ```
62
+ */
63
+ send(options: PushSendOptions): Promise<Result<PushMessage>>;
64
+ /** How a notification went: status and per-platform counts. */
65
+ getMessage(id: string): Promise<Result<PushMessage>>;
66
+ /** Register a device token for a user from your server (apps usually call baas.push.register themselves). */
67
+ registerDevice(options: {
68
+ userId: string;
69
+ platform: PushPlatform;
70
+ token: string | {
71
+ endpoint: string;
72
+ keys: {
73
+ p256dh: string;
74
+ auth: string;
75
+ };
76
+ };
77
+ appId?: string;
78
+ locale?: string;
79
+ tags?: string[];
80
+ }): Promise<Result<{
81
+ id: string;
82
+ created: boolean;
83
+ }>>;
84
+ }
85
+ export declare function createPush(http: HttpClient): ServerPush;
@@ -0,0 +1,37 @@
1
+ // Push notifications from your server: `baas.push.send({...})` → POST /push/v1/send (secret key only).
2
+ // Delivery happens in the background (Apple, Google and the browsers' push services); the answer
3
+ // says how many devices it was addressed to, and `getMessage(id)` tells how it went.
4
+ import { UseBeckyError } from "../lib/errors.js";
5
+ function invalid(message) {
6
+ return new UseBeckyError({ code: 'invalid_input', message, status: 0 });
7
+ }
8
+ export function createPush(http) {
9
+ return {
10
+ async send(o) {
11
+ if (!o || typeof o !== 'object')
12
+ return { data: null, error: invalid('Pass the notification as an object, like { userIds, title, body }.') };
13
+ const res = await http.request('/push/v1/send', {
14
+ method: 'POST',
15
+ token: null,
16
+ body: { user_ids: o.userIds, tag: o.tag, title: o.title, body: o.body, url: o.url, data: o.data },
17
+ });
18
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
19
+ },
20
+ async getMessage(id) {
21
+ if (!id)
22
+ return { data: null, error: invalid('Pass the id returned by baas.push.send().') };
23
+ const res = await http.request(`/push/v1/messages/${encodeURIComponent(id)}`, { token: null });
24
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
25
+ },
26
+ async registerDevice(o) {
27
+ if (!o?.userId)
28
+ return { data: null, error: invalid('Pass the user id, like { userId, platform, token }.') };
29
+ const res = await http.request('/push/v1/devices', {
30
+ method: 'POST',
31
+ token: null,
32
+ body: { user_id: o.userId, platform: o.platform, token: o.token, app_id: o.appId, locale: o.locale, tags: o.tags },
33
+ });
34
+ return res.error ? { data: null, error: res.error } : { data: { id: res.data?.id ?? '', created: !!res.data?.created }, error: null };
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,43 @@
1
+ import type { HttpClient } from '../lib/http.ts';
2
+ import type { Result } from '../lib/types.ts';
3
+ /** One limit of the plan. */
4
+ export interface UsageQuota {
5
+ /** e.g. 'emails_per_month', 'storage_bytes', 'monthly_active_users', 'api_requests_per_month'. */
6
+ key: string;
7
+ label: string;
8
+ /** 'bytes', 'count', … */
9
+ unit: string;
10
+ /** 'month' for monthly limits. */
11
+ period?: string;
12
+ /** 'team': the limit counts every project of the team (`used` is the team's total, `project_used` this project's). */
13
+ scope: 'project' | 'team' | 'account';
14
+ /** 'cap': a size limit (largest file, …), not something used up. */
15
+ kind: 'usage' | 'cap';
16
+ used: number | null;
17
+ /** null: no limit. */
18
+ limit: number | null;
19
+ project_used?: number | null;
20
+ percent: number;
21
+ /** 'warning' from 80%, 'exceeded' at 100%. */
22
+ status: 'ok' | 'warning' | 'exceeded';
23
+ /** The cheapest plan with room for more, or null. */
24
+ upgrade_plan: string | null;
25
+ }
26
+ export interface ProjectUsage {
27
+ plan: string;
28
+ plan_name: string;
29
+ /** The billing month the monthly limits count in. */
30
+ period: {
31
+ start: string;
32
+ end: string;
33
+ };
34
+ measured_at: string | null;
35
+ quotas: UsageQuota[];
36
+ /** Where an owner upgrades the plan. */
37
+ upgrade_url: string;
38
+ }
39
+ export interface ServerUsage {
40
+ /** The project's usage against its plan: every limit with used, limit, percent and status. */
41
+ get(): Promise<Result<ProjectUsage>>;
42
+ }
43
+ export declare function createServerUsage(http: HttpClient): ServerUsage;
@@ -0,0 +1,8 @@
1
+ export function createServerUsage(http) {
2
+ return {
3
+ async get() {
4
+ const res = await http.request('/usage/v1', { token: null });
5
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
6
+ },
7
+ };
8
+ }