@scrawn/core 0.0.3 → 0.0.7
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/config.d.ts +41 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +32 -0
- package/dist/config.js.map +1 -0
- package/dist/core/auth/apiKeyAuth.d.ts +58 -0
- package/dist/core/auth/apiKeyAuth.d.ts.map +1 -0
- package/dist/core/auth/apiKeyAuth.js +66 -0
- package/dist/core/auth/apiKeyAuth.js.map +1 -0
- package/dist/core/auth/baseAuth.d.ts +70 -0
- package/dist/core/auth/baseAuth.d.ts.map +1 -0
- package/dist/core/auth/baseAuth.js +22 -0
- package/dist/core/auth/baseAuth.js.map +1 -0
- package/dist/core/errors/index.d.ts +192 -0
- package/dist/core/errors/index.d.ts.map +1 -0
- package/dist/core/errors/index.js +280 -0
- package/dist/core/errors/index.js.map +1 -0
- package/dist/core/grpc/callContext.d.ts +18 -0
- package/dist/core/grpc/callContext.d.ts.map +1 -0
- package/dist/core/grpc/callContext.js +35 -0
- package/dist/core/grpc/callContext.js.map +1 -0
- package/dist/core/grpc/client.d.ts +16 -0
- package/dist/core/grpc/client.d.ts.map +1 -0
- package/dist/core/grpc/client.js +30 -0
- package/dist/core/grpc/client.js.map +1 -0
- package/dist/core/grpc/index.d.ts +14 -0
- package/dist/core/grpc/index.d.ts.map +1 -0
- package/dist/core/grpc/index.js +13 -0
- package/dist/core/grpc/index.js.map +1 -0
- package/dist/core/grpc/requestBuilder.d.ts +15 -0
- package/dist/core/grpc/requestBuilder.d.ts.map +1 -0
- package/dist/core/grpc/requestBuilder.js +56 -0
- package/dist/core/grpc/requestBuilder.js.map +1 -0
- package/dist/core/grpc/streamRequestBuilder.d.ts +13 -0
- package/dist/core/grpc/streamRequestBuilder.d.ts.map +1 -0
- package/dist/core/grpc/streamRequestBuilder.js +60 -0
- package/dist/core/grpc/streamRequestBuilder.js.map +1 -0
- package/dist/core/grpc/types.d.ts +7 -0
- package/dist/core/grpc/types.d.ts.map +1 -0
- package/dist/core/grpc/types.js +2 -0
- package/dist/core/grpc/types.js.map +1 -0
- package/dist/core/pricing/builders.d.ts +157 -0
- package/dist/core/pricing/builders.d.ts.map +1 -0
- package/dist/core/pricing/builders.js +218 -0
- package/dist/core/pricing/builders.js.map +1 -0
- package/dist/core/pricing/index.d.ts +30 -0
- package/dist/core/pricing/index.d.ts.map +1 -0
- package/dist/core/pricing/index.js +32 -0
- package/dist/core/pricing/index.js.map +1 -0
- package/dist/core/pricing/resolve.d.ts +39 -0
- package/dist/core/pricing/resolve.d.ts.map +1 -0
- package/dist/core/pricing/resolve.js +50 -0
- package/dist/core/pricing/resolve.js.map +1 -0
- package/dist/core/pricing/serialize.d.ts +55 -0
- package/dist/core/pricing/serialize.d.ts.map +1 -0
- package/dist/core/pricing/serialize.js +127 -0
- package/dist/core/pricing/serialize.js.map +1 -0
- package/dist/core/pricing/types.d.ts +122 -0
- package/dist/core/pricing/types.d.ts.map +1 -0
- package/dist/core/pricing/types.js +17 -0
- package/dist/core/pricing/types.js.map +1 -0
- package/dist/core/pricing/validate.d.ts +56 -0
- package/dist/core/pricing/validate.d.ts.map +1 -0
- package/dist/core/pricing/validate.js +162 -0
- package/dist/core/pricing/validate.js.map +1 -0
- package/dist/core/scrawn.d.ts +414 -0
- package/dist/core/scrawn.d.ts.map +1 -0
- package/dist/core/scrawn.js +822 -0
- package/dist/core/scrawn.js.map +1 -0
- package/dist/core/types/auth.d.ts +31 -0
- package/dist/core/types/auth.d.ts.map +1 -0
- package/dist/core/types/auth.js +2 -0
- package/dist/core/types/auth.js.map +1 -0
- package/dist/core/types/event.d.ts +320 -0
- package/dist/core/types/event.d.ts.map +1 -0
- package/dist/core/types/event.js +155 -0
- package/dist/core/types/event.js.map +1 -0
- package/dist/gen/auth/v1/auth_grpc_pb.d.ts +3 -0
- package/dist/gen/auth/v1/auth_pb.d.ts +65 -0
- package/dist/gen/data/v1/data_grpc_pb.d.ts +5 -0
- package/dist/gen/data/v1/data_pb.d.ts +254 -0
- package/dist/gen/event/v1/event_grpc_pb.d.ts +3 -0
- package/dist/gen/event/v1/event_pb.d.ts +342 -0
- package/dist/gen/event/v1/event_pb.js +573 -117
- package/dist/gen/payment/v1/payment_grpc_pb.d.ts +3 -0
- package/dist/gen/payment/v1/payment_pb.d.ts +45 -0
- package/dist/gen/query/v1/query_grpc_pb.d.ts +5 -0
- package/dist/gen/query/v1/query_pb.d.ts +381 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/utils/forkAsyncIterable.d.ts +13 -0
- package/dist/utils/forkAsyncIterable.d.ts.map +1 -0
- package/dist/utils/forkAsyncIterable.js +78 -0
- package/dist/utils/forkAsyncIterable.js.map +1 -0
- package/dist/utils/logger.d.ts +10 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +62 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/pathMatcher.d.ts +25 -0
- package/dist/utils/pathMatcher.d.ts.map +1 -0
- package/dist/utils/pathMatcher.js +46 -0
- package/dist/utils/pathMatcher.js.map +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import type { EventPayload, MiddlewareRequest, MiddlewareResponse, MiddlewareNext, MiddlewareEventConfig, AITokenUsagePayload, EventConsumerErrorCallback } from "./types/event.js";
|
|
2
|
+
import type { AllCredentials } from "./types/auth.js";
|
|
3
|
+
import type { TagExpr, PriceExpr, ScrawnExpr } from "./pricing/types.js";
|
|
4
|
+
import { GrpcClient } from "./grpc/index.js";
|
|
5
|
+
import type { StreamEventResponse } from "../gen/event/v1/event_pb.js";
|
|
6
|
+
/**
|
|
7
|
+
* Main SDK class for Scrawn billing infrastructure.
|
|
8
|
+
*
|
|
9
|
+
* Manages authentication, event tracking, and credential caching.
|
|
10
|
+
* All event consumption methods are available directly on the SDK instance.
|
|
11
|
+
*
|
|
12
|
+
* @typeParam TTags - Union of valid tag names for compile-time type checking
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* import { createScrawn } from '@scrawn/core';
|
|
17
|
+
*
|
|
18
|
+
* const biller = createScrawn({
|
|
19
|
+
* apiKey: process.env.SCRAWN_KEY,
|
|
20
|
+
* baseURL: 'http://localhost:8069',
|
|
21
|
+
* tags: ["PREMIUM_CALL", "EXTRA_FEE"] as const,
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Tags are compile-time checked
|
|
25
|
+
* biller.basicUsageEventConsumer({ userId: 'u123', debitTag: 'PREMIUM_FEATURE' });
|
|
26
|
+
* // biller.basicUsageEventConsumer({ userId: 'u123', debitTag: 'UNKNOWN' }); // Type error!
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare class Scrawn<TTags extends string = string, TExprs extends string = string> {
|
|
30
|
+
/** Map of authentication method names to their implementations */
|
|
31
|
+
private authMethods;
|
|
32
|
+
/**
|
|
33
|
+
* Cache of credentials keyed by auth method name for performance.
|
|
34
|
+
* Keys are restricted to registered auth method names only.
|
|
35
|
+
*/
|
|
36
|
+
private credCache;
|
|
37
|
+
/** API key used for default authentication */
|
|
38
|
+
private apiKey;
|
|
39
|
+
/** gRPC client for making type-safe API calls */
|
|
40
|
+
private grpcClient;
|
|
41
|
+
/** Number of auto-retry attempts on retryable errors before falling back to onError */
|
|
42
|
+
private retryCount;
|
|
43
|
+
/** Public access to the gRPC client for use by other packages (e.g. @scrawn/analytics) */
|
|
44
|
+
get grpc(): GrpcClient;
|
|
45
|
+
/** API key used for authorizing gRPC calls */
|
|
46
|
+
get apikey(): string;
|
|
47
|
+
private sleep;
|
|
48
|
+
private backoffMs;
|
|
49
|
+
private notifyEventConsumerError;
|
|
50
|
+
private notifyValidationError;
|
|
51
|
+
/**
|
|
52
|
+
* Creates a new Scrawn SDK instance.
|
|
53
|
+
*
|
|
54
|
+
* @param config - Configuration object
|
|
55
|
+
* @param config.apiKey - Your Scrawn API key for authentication
|
|
56
|
+
* @param config.baseURL - Base URL for the Scrawn API (e.g., 'https://api.scrawn.dev')
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* const scrawn = new Scrawn({
|
|
61
|
+
* apiKey: 'sk_test_...',
|
|
62
|
+
* baseURL: 'https://api.scrawn.dev'
|
|
63
|
+
* });
|
|
64
|
+
* await scrawn.init();
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
constructor(config: {
|
|
68
|
+
apiKey: AllCredentials["apiKey"];
|
|
69
|
+
baseURL: string;
|
|
70
|
+
secure?: boolean;
|
|
71
|
+
credentials?: import("@grpc/grpc-js").ChannelCredentials;
|
|
72
|
+
retryCount?: number;
|
|
73
|
+
});
|
|
74
|
+
private parseURLToTarget;
|
|
75
|
+
/**
|
|
76
|
+
* Create a type-safe tag reference.
|
|
77
|
+
*
|
|
78
|
+
* Only tag names known to this biller instance are accepted at compile time.
|
|
79
|
+
* Tag values are resolved to cent amounts by the backend at runtime.
|
|
80
|
+
*
|
|
81
|
+
* @param name - The tag name (must be one of the known tags for this instance)
|
|
82
|
+
* @returns A TagExpr referencing the named tag
|
|
83
|
+
* @throws PricingExpressionError at runtime if name format is invalid
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* const expr = mul(biller.tag("PREMIUM_CALL"), 3);
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
tag<T extends TTags>(name: T): TagExpr<T>;
|
|
91
|
+
/**
|
|
92
|
+
* Create a type-safe reference to a persisted expression.
|
|
93
|
+
*
|
|
94
|
+
* Expression names are compile-time checked against known expressions
|
|
95
|
+
* synced from the Scrawn server. The backend resolves the stored
|
|
96
|
+
* expression string and evaluates it at runtime.
|
|
97
|
+
*
|
|
98
|
+
* Also accepts inline PriceExpr as a passthrough for a consistent
|
|
99
|
+
* `biller.expr()` entry point for all expressions.
|
|
100
|
+
*
|
|
101
|
+
* @param nameOrExpr - The persisted expression name or an inline PriceExpr
|
|
102
|
+
* @returns An ExprRef (if name) or the original PriceExpr (passthrough)
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```typescript
|
|
106
|
+
* // Reference a persisted expression
|
|
107
|
+
* biller.basicUsageEventConsumer({
|
|
108
|
+
* userId: 'u123',
|
|
109
|
+
* debitExpr: biller.expr("MY_EXPR"),
|
|
110
|
+
* });
|
|
111
|
+
*
|
|
112
|
+
* // Inline expression passthrough
|
|
113
|
+
* biller.basicUsageEventConsumer({
|
|
114
|
+
* userId: 'u123',
|
|
115
|
+
* debitExpr: biller.expr(mul(biller.tag("PREMIUM_CALL"), 3)),
|
|
116
|
+
* });
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
expr<T extends TExprs>(name: T): ScrawnExpr<TTags>;
|
|
120
|
+
expr(expr: PriceExpr<TTags>): ScrawnExpr<TTags>;
|
|
121
|
+
/**
|
|
122
|
+
* Register an authentication method with the SDK.
|
|
123
|
+
*
|
|
124
|
+
* Auth methods handle credential management and can be shared across multiple event types.
|
|
125
|
+
* Only auth method names defined in AuthRegistry are allowed.
|
|
126
|
+
*
|
|
127
|
+
* @param name - Unique identifier for this auth method (must be in AuthRegistry)
|
|
128
|
+
* @param auth - Instance of an AuthBase implementation
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```typescript
|
|
132
|
+
* scrawn.registerAuthMethod('api', new ApiKeyAuth('sk_test_...'));
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
private registerAuthMethod;
|
|
136
|
+
/**
|
|
137
|
+
* Get credentials for a specific authentication method.
|
|
138
|
+
*
|
|
139
|
+
* Credentials are cached after the first fetch for performance.
|
|
140
|
+
* Subsequent calls return the cached value without re-fetching.
|
|
141
|
+
* Only auth method names defined in AuthRegistry are allowed.
|
|
142
|
+
*
|
|
143
|
+
* @param authMethodName - Name of the auth method to get credentials for (must be in AuthRegistry)
|
|
144
|
+
* @returns A promise that resolves to the credentials object
|
|
145
|
+
* @throws Error if the auth method is not registered
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```typescript
|
|
149
|
+
* const creds = await scrawn.getCredsFor('api');
|
|
150
|
+
* // { apiKey: 'sk_test_...' }
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
private getCredsFor;
|
|
154
|
+
/**
|
|
155
|
+
* Track a basic usage event.
|
|
156
|
+
*
|
|
157
|
+
* Records basic usage to the Scrawn backend for billing tracking.
|
|
158
|
+
* The event is authenticated using the API key provided during SDK initialization.
|
|
159
|
+
*
|
|
160
|
+
* @param payload - The usage data to track
|
|
161
|
+
* @param payload.userId - Unique identifier of the user making the call
|
|
162
|
+
* @param payload.debitAmount - (Optional) Direct amount in cents to debit from the user's account
|
|
163
|
+
* @param payload.debitTag - (Optional) Named price tag for backend-managed pricing
|
|
164
|
+
* @param payload.debitExpr - (Optional) Pricing expression for complex calculations
|
|
165
|
+
* @param payload.metadata - (Optional) Arbitrary metadata to associate with the event
|
|
166
|
+
* @param options - Optional configuration
|
|
167
|
+
* @param options.eventId - (Optional) Override the auto-generated event ID
|
|
168
|
+
* @param options.onError - Optional callback for handling validation or gRPC errors
|
|
169
|
+
* @returns A promise that resolves when the event is tracked or returns early on error
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```typescript
|
|
173
|
+
* import { add, mul, tag } from '@scrawn/core';
|
|
174
|
+
*
|
|
175
|
+
* // Using direct amount (500 cents = $5.00)
|
|
176
|
+
* await scrawn.basicUsageEventConsumer({
|
|
177
|
+
* userId: 'user_abc123',
|
|
178
|
+
* debitAmount: 500
|
|
179
|
+
* });
|
|
180
|
+
*
|
|
181
|
+
* // Using price tag
|
|
182
|
+
* await scrawn.basicUsageEventConsumer({
|
|
183
|
+
* userId: 'user_abc123',
|
|
184
|
+
* debitTag: 'PREMIUM_FEATURE'
|
|
185
|
+
* });
|
|
186
|
+
*
|
|
187
|
+
* // Using pricing expression: (PREMIUM_CALL * 3) + EXTRA_FEE + 250 cents
|
|
188
|
+
* await scrawn.basicUsageEventConsumer({
|
|
189
|
+
* userId: 'user_abc123',
|
|
190
|
+
* debitExpr: add(mul(tag('PREMIUM_CALL'), 3), tag('EXTRA_FEE'), 250)
|
|
191
|
+
* });
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
basicUsageEventConsumer(payload: EventPayload<TTags>, options?: {
|
|
195
|
+
eventId?: string;
|
|
196
|
+
onError?: EventConsumerErrorCallback;
|
|
197
|
+
}): Promise<void>;
|
|
198
|
+
/**
|
|
199
|
+
* Create an Express-compatible middleware for tracking API endpoint usage.
|
|
200
|
+
*
|
|
201
|
+
* This middleware automatically tracks requests to your API endpoints for billing purposes.
|
|
202
|
+
* You provide an extractor function that determines the userId and debit info (amount or tag) from each request.
|
|
203
|
+
* Optionally, you can provide a whitelist array to only track specific endpoints,
|
|
204
|
+
* or a blacklist array to exclude specific endpoints from tracking.
|
|
205
|
+
*
|
|
206
|
+
* The middleware is framework-agnostic and works with Express, Fastify, and similar frameworks.
|
|
207
|
+
*
|
|
208
|
+
* @param config - Configuration object for the middleware
|
|
209
|
+
* @param config.extractor - Function that extracts userId and debitAmount from the request. Return null to skip tracking.
|
|
210
|
+
* @param config.whitelist - Optional array of endpoint patterns to track. Supports wildcards:
|
|
211
|
+
* - Exact match: /api/users
|
|
212
|
+
* - Single segment (*): /api/* matches /api/users but not /api/users/123
|
|
213
|
+
* - Multi-segment (**): /api/** matches any path starting with /api/
|
|
214
|
+
* - Mixed: /api/star/profile, **.php
|
|
215
|
+
* Takes precedence over blacklist. If omitted, all requests will be tracked.
|
|
216
|
+
* @param config.blacklist - Optional array of endpoint patterns to exclude. Same wildcard support as whitelist.
|
|
217
|
+
* Only applies to endpoints not in the whitelist.
|
|
218
|
+
* @param config.onError - Optional callback for handling validation or gRPC errors
|
|
219
|
+
*
|
|
220
|
+
* @returns Express-compatible middleware function
|
|
221
|
+
*
|
|
222
|
+
* @example
|
|
223
|
+
* ```typescript
|
|
224
|
+
* // Track all endpoints
|
|
225
|
+
* app.use(scrawn.middlewareEventConsumer({
|
|
226
|
+
* extractor: (req) => ({
|
|
227
|
+
* userId: req.user.id,
|
|
228
|
+
* debitAmount: 1
|
|
229
|
+
* })
|
|
230
|
+
* }));
|
|
231
|
+
*
|
|
232
|
+
* // Track only specific endpoints with wildcards
|
|
233
|
+
* app.use(scrawn.middlewareEventConsumer({
|
|
234
|
+
* extractor: (req) => ({
|
|
235
|
+
* userId: req.headers['x-user-id'] as string,
|
|
236
|
+
* debitAmount: req.body.tokens || 1
|
|
237
|
+
* }),
|
|
238
|
+
* whitelist: ['/api/generate', '/api/analyze', '/api/v1/*']
|
|
239
|
+
* }));
|
|
240
|
+
*
|
|
241
|
+
* // Exclude specific endpoints from tracking
|
|
242
|
+
* app.use(scrawn.middlewareEventConsumer({
|
|
243
|
+
* extractor: (req) => ({
|
|
244
|
+
* userId: req.user.id,
|
|
245
|
+
* debitAmount: 1
|
|
246
|
+
* }),
|
|
247
|
+
* blacklist: ['/health', '/api/collect-payment', '/internal/**', '**.tmp']
|
|
248
|
+
* }));
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
middlewareEventConsumer(config: MiddlewareEventConfig<TTags>): (req: MiddlewareRequest, res: MiddlewareResponse, next: MiddlewareNext) => Promise<void>;
|
|
252
|
+
/**
|
|
253
|
+
* Collect payment by creating a checkout link for a user.
|
|
254
|
+
*
|
|
255
|
+
* Generates a payment checkout link for the specified user via the Scrawn payment service.
|
|
256
|
+
* The checkout link can be used to direct users to complete their payment.
|
|
257
|
+
*
|
|
258
|
+
* @param userId - Unique identifier of the user to collect payment from
|
|
259
|
+
* @returns A promise that resolves to the checkout link URL
|
|
260
|
+
* @throws Error if the gRPC call fails or if authentication is invalid
|
|
261
|
+
*
|
|
262
|
+
* @example
|
|
263
|
+
* ```typescript
|
|
264
|
+
* const checkoutLink = await scrawn.collectPayment('user_abc123');
|
|
265
|
+
* // Returns: 'https://checkout.scrawn.dev/...'
|
|
266
|
+
* // Redirect user to this URL to complete payment
|
|
267
|
+
* ```
|
|
268
|
+
*/
|
|
269
|
+
collectPayment(userId: string): Promise<string>;
|
|
270
|
+
/**
|
|
271
|
+
* Internal method to consume and process an event.
|
|
272
|
+
*
|
|
273
|
+
* This method:
|
|
274
|
+
* 1. Validates authentication
|
|
275
|
+
* 2. Fetches/caches credentials
|
|
276
|
+
* 3. Executes any pre-run hooks
|
|
277
|
+
* 4. Processes the event via gRPC call to RegisterEvent
|
|
278
|
+
*
|
|
279
|
+
* @param payload - Event payload data
|
|
280
|
+
* @param authMethodName - Name of the auth method to use (must be in AuthRegistry)
|
|
281
|
+
* @param eventType - Type of event for categorization (RAW or MIDDLEWARE_CALL)
|
|
282
|
+
* @param eventId - Stable event ID (generated by caller, reused across retries)
|
|
283
|
+
* @param idempotencyKey - Stable idempotency key (generated by caller, reused across retries)
|
|
284
|
+
* @returns A promise that resolves when the event is processed
|
|
285
|
+
* @throws Error if auth method is not registered or gRPC call fails
|
|
286
|
+
*
|
|
287
|
+
* @internal
|
|
288
|
+
*/
|
|
289
|
+
private consumeEvent;
|
|
290
|
+
/**
|
|
291
|
+
* Configuration options for aiTokenStreamConsumer.
|
|
292
|
+
*/
|
|
293
|
+
/**
|
|
294
|
+
* Stream AI token usage events to the Scrawn backend (fire-and-forget mode).
|
|
295
|
+
*
|
|
296
|
+
* Consumes an async iterable of AI token usage payloads and streams them
|
|
297
|
+
* to the backend for billing tracking. This is designed for real-time
|
|
298
|
+
* AI token tracking where usage is reported as tokens are consumed.
|
|
299
|
+
*
|
|
300
|
+
* @param stream - An async iterable of AI token usage payloads
|
|
301
|
+
* @returns A promise that resolves to the stream response or undefined on error
|
|
302
|
+
*/
|
|
303
|
+
aiTokenStreamConsumer(stream: AsyncIterable<AITokenUsagePayload<TTags>>): Promise<StreamEventResponse | undefined>;
|
|
304
|
+
/**
|
|
305
|
+
* Stream AI token usage events to the Scrawn backend (fire-and-forget mode).
|
|
306
|
+
*
|
|
307
|
+
* @param stream - An async iterable of AI token usage payloads
|
|
308
|
+
* @param config - Configuration with return: false (or omitted)
|
|
309
|
+
* @returns A promise that resolves to the stream response or undefined on error
|
|
310
|
+
*/
|
|
311
|
+
aiTokenStreamConsumer(stream: AsyncIterable<AITokenUsagePayload<TTags>>, config: {
|
|
312
|
+
return?: false;
|
|
313
|
+
onError?: EventConsumerErrorCallback;
|
|
314
|
+
}): Promise<StreamEventResponse | undefined>;
|
|
315
|
+
/**
|
|
316
|
+
* Stream AI token usage events to the Scrawn backend while returning a forked stream.
|
|
317
|
+
*
|
|
318
|
+
* When `return: true`, the input stream is forked: one fork is sent to the billing
|
|
319
|
+
* backend (non-blocking), and the other fork is returned to the caller for streaming
|
|
320
|
+
* to the user. This enables simultaneous billing and user-facing token streaming.
|
|
321
|
+
*
|
|
322
|
+
* @param stream - An async iterable of AI token usage payloads
|
|
323
|
+
* @param config - Configuration with return: true
|
|
324
|
+
* @returns Object containing the response promise (or undefined on error) and a forked stream for user consumption
|
|
325
|
+
*
|
|
326
|
+
* @example
|
|
327
|
+
* ```typescript
|
|
328
|
+
* const { response, stream: userStream } = await scrawn.aiTokenStreamConsumer(
|
|
329
|
+
* tokenGenerator(),
|
|
330
|
+
* { return: true }
|
|
331
|
+
* );
|
|
332
|
+
*
|
|
333
|
+
* // Stream tokens to user while billing happens in background
|
|
334
|
+
* for await (const token of userStream) {
|
|
335
|
+
* process.stdout.write(token.outputTokens.toString());
|
|
336
|
+
* }
|
|
337
|
+
*
|
|
338
|
+
* // Billing completes after stream is consumed
|
|
339
|
+
* const result = await response;
|
|
340
|
+
* if (result) {
|
|
341
|
+
* console.log(`Billed ${result.getEventsprocessed()} events`);
|
|
342
|
+
* }
|
|
343
|
+
* ```
|
|
344
|
+
*/
|
|
345
|
+
aiTokenStreamConsumer(stream: AsyncIterable<AITokenUsagePayload<TTags>>, config: {
|
|
346
|
+
return: true;
|
|
347
|
+
onError?: EventConsumerErrorCallback;
|
|
348
|
+
}): Promise<{
|
|
349
|
+
response: Promise<StreamEventResponse | undefined>;
|
|
350
|
+
stream: AsyncIterable<AITokenUsagePayload<TTags>>;
|
|
351
|
+
}>;
|
|
352
|
+
/**
|
|
353
|
+
* Transform user-provided AI token usage payloads into StreamEventRequest format.
|
|
354
|
+
*
|
|
355
|
+
* Validates each payload and maps it to the gRPC request format.
|
|
356
|
+
* Invalid payloads are logged and skipped.
|
|
357
|
+
*
|
|
358
|
+
* @param stream - The user's async iterable of AITokenUsagePayload
|
|
359
|
+
* @returns An async iterable of StreamEventRequest payloads
|
|
360
|
+
* @internal
|
|
361
|
+
*/
|
|
362
|
+
private transformAITokenStream;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Configuration for creating a Scrawn instance via {@link createScrawn}.
|
|
366
|
+
*/
|
|
367
|
+
export interface ScrawnInitConfig {
|
|
368
|
+
apiKey: string;
|
|
369
|
+
baseURL: string;
|
|
370
|
+
secure?: boolean;
|
|
371
|
+
credentials?: import("@grpc/grpc-js").ChannelCredentials;
|
|
372
|
+
tags?: readonly string[];
|
|
373
|
+
expressions?: readonly string[];
|
|
374
|
+
/**
|
|
375
|
+
* Number of automatic retry attempts on transient network errors
|
|
376
|
+
* (UNAVAILABLE, DEADLINE_EXCEEDED). Defaults to 2. Set to 0 to disable.
|
|
377
|
+
* Each event also gets a manual `.retry()` context in the onError callback.
|
|
378
|
+
*/
|
|
379
|
+
retryCount?: number;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Create a type-safe Scrawn billing instance.
|
|
383
|
+
*
|
|
384
|
+
* When `tags` or `expressions` are provided as const arrays, the returned
|
|
385
|
+
* instance is parameterized with the union of those names. All pricing
|
|
386
|
+
* methods will be compile-time checked against the known set.
|
|
387
|
+
*
|
|
388
|
+
* @example
|
|
389
|
+
* ```typescript
|
|
390
|
+
* import { createScrawn, mul, inputTokens } from '@scrawn/core';
|
|
391
|
+
*
|
|
392
|
+
* const biller = createScrawn({
|
|
393
|
+
* apiKey: process.env.SCRAWN_KEY,
|
|
394
|
+
* baseURL: process.env.SCRAWN_BASE_URL,
|
|
395
|
+
* tags: ["PREMIUM_CALL", "EXTRA_FEE"] as const,
|
|
396
|
+
* expressions: ["MY_EXPR"] as const,
|
|
397
|
+
* });
|
|
398
|
+
*
|
|
399
|
+
* biller.basicUsageEventConsumer({
|
|
400
|
+
* userId: 'u123',
|
|
401
|
+
* debitExpr: biller.expr("MY_EXPR"), // persisted expression
|
|
402
|
+
* });
|
|
403
|
+
* biller.basicUsageEventConsumer({
|
|
404
|
+
* userId: 'u123',
|
|
405
|
+
* debitExpr: mul(biller.tag("PREMIUM_CALL"), 3), // inline
|
|
406
|
+
* });
|
|
407
|
+
* ```
|
|
408
|
+
*/
|
|
409
|
+
export declare function createScrawn<const TTags extends readonly string[], const TExprs extends readonly string[]>(config: ScrawnInitConfig & {
|
|
410
|
+
tags: TTags;
|
|
411
|
+
expressions: TExprs;
|
|
412
|
+
}): Scrawn<TTags[number], TExprs[number]>;
|
|
413
|
+
export declare function createScrawn(config: ScrawnInitConfig): Scrawn;
|
|
414
|
+
//# sourceMappingURL=scrawn.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scrawn.d.ts","sourceRoot":"","sources":["../../src/core/scrawn.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,qBAAqB,EACrB,mBAAmB,EACnB,0BAA0B,EAE3B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAGV,cAAc,EACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EACV,OAAO,EACP,SAAS,EAET,UAAU,EACX,MAAM,oBAAoB,CAAC;AAS5B,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;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