@simplr-ai/node 1.1.0 → 1.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.
package/dist/index.d.ts CHANGED
@@ -1,9 +1,33 @@
1
+ type NetworkSource = "frontend" | "backend";
2
+ interface NetworkLogEntry {
3
+ id: string;
4
+ source: NetworkSource;
5
+ timestamp: string;
6
+ sdk?: string;
7
+ applicationId?: string;
8
+ environment?: string;
9
+ method: string;
10
+ url: string;
11
+ requestHeaders?: Record<string, string>;
12
+ requestBody?: unknown;
13
+ status?: number;
14
+ statusText?: string;
15
+ responseHeaders?: Record<string, string>;
16
+ responseBody?: unknown;
17
+ durationMs?: number;
18
+ ok?: boolean;
19
+ error?: string;
20
+ }
21
+ type NetworkLogger = (entry: NetworkLogEntry) => void;
22
+
1
23
  interface HttpConfig {
2
- /** Auth headers to send (e.g. { "X-API-Key": "sk_…" } or { Authorization: "Bearer …" }). */
3
24
  authHeaders: Record<string, string>;
4
25
  baseUrl: string;
5
26
  timeoutMs: number;
6
27
  fetchImpl: typeof fetch;
28
+ onNetworkLog?: NetworkLogger;
29
+ logBodies?: boolean;
30
+ redactFields?: string[];
7
31
  }
8
32
 
9
33
  type RiskLevel = "low" | "medium" | "high" | "critical";
@@ -12,12 +36,24 @@ interface SimplrOptions {
12
36
  apiKey: string;
13
37
  /** Public key (pk_…) — enables `simplr.flags` for server-side feature-flag evaluation. */
14
38
  publicKey?: string;
39
+ /**
40
+ * Which environment's flags `simplr.flags` should load. Accepts a named
41
+ * environment slug (e.g. "dev", "uat", "prod") as well as the legacy
42
+ * "live"/"test" key modes. When unset, the API falls back to the public
43
+ * key's own live/test mode.
44
+ */
45
+ environment?: string;
15
46
  /** API base URL. Defaults to https://api.simplr.sh. */
16
47
  baseUrl?: string;
17
48
  /** Per-request timeout in ms (default 15000). */
18
49
  timeoutMs?: number;
19
50
  /** Override the fetch implementation (defaults to global fetch). */
20
51
  fetch?: typeof fetch;
52
+ onNetworkLog?: NetworkLogger;
53
+ logBodies?: boolean;
54
+ redactFields?: string[];
55
+ shipNetworkLogs?: boolean;
56
+ applicationId?: string;
21
57
  }
22
58
  interface CheckInput {
23
59
  email?: string;
@@ -74,6 +110,133 @@ interface EdgeLogEntry {
74
110
  message: string;
75
111
  [key: string]: unknown;
76
112
  }
113
+ interface IdentifyOptions {
114
+ /** Profile type. */
115
+ profileType?: "customer" | "cashier" | "employee";
116
+ /** Device fingerprint hash to link to this profile. */
117
+ fingerprintHash?: string;
118
+ /** Extra fields merged into the request body. */
119
+ [key: string]: unknown;
120
+ }
121
+ interface ProfileResult {
122
+ profile: {
123
+ id: string;
124
+ external_id: string;
125
+ profile_type: string;
126
+ status: string;
127
+ risk_score: number;
128
+ risk_level: string;
129
+ device_count: number;
130
+ total_orders: number;
131
+ first_seen_at: string;
132
+ last_seen_at: string;
133
+ };
134
+ is_new: boolean;
135
+ device_linked: boolean;
136
+ device_anomaly?: string;
137
+ [key: string]: unknown;
138
+ }
139
+ interface ProfileRiskResult {
140
+ profile: {
141
+ id: string;
142
+ external_id: string;
143
+ profile_type: string;
144
+ status: string;
145
+ risk_score: number;
146
+ risk_level: string;
147
+ signals: Record<string, number>;
148
+ device_count: number;
149
+ total_orders: number;
150
+ flagged_orders: number;
151
+ fraud_reports: number;
152
+ legitimate_reports: number;
153
+ first_seen_at: string;
154
+ last_seen_at: string;
155
+ };
156
+ [key: string]: unknown;
157
+ }
158
+ type RUMEventType = "session_start" | "session_end" | "view" | "action" | "error" | "log";
159
+ type RUMLogLevel = "debug" | "info" | "warn" | "error";
160
+ interface RUMEvent {
161
+ type: RUMEventType;
162
+ timestamp: number;
163
+ sessionId: string;
164
+ viewId?: string;
165
+ userId?: string;
166
+ applicationId: string;
167
+ applicationVersion?: string;
168
+ environment?: string;
169
+ view?: {
170
+ id: string;
171
+ name: string;
172
+ };
173
+ action?: {
174
+ name: string;
175
+ type: string;
176
+ };
177
+ error?: {
178
+ message: string;
179
+ stack?: string;
180
+ type?: string;
181
+ };
182
+ log?: {
183
+ level: RUMLogLevel;
184
+ message: string;
185
+ };
186
+ attributes?: Record<string, unknown>;
187
+ userAttributes?: Record<string, unknown>;
188
+ globalAttributes?: Record<string, unknown>;
189
+ }
190
+ interface RUMEventBatch {
191
+ events: RUMEvent[];
192
+ sentAt: number;
193
+ }
194
+ type BindingMode = "verified_device" | "any_location";
195
+ interface CreateDelegationOptions {
196
+ userId: string;
197
+ email?: string;
198
+ binding?: BindingMode;
199
+ expiresInDays?: number;
200
+ sessionId?: string;
201
+ fingerprintHash?: string;
202
+ }
203
+ interface DelegationResult {
204
+ token: string;
205
+ delegationId: string;
206
+ expiresAt: string;
207
+ bindingMode: BindingMode;
208
+ }
209
+ interface DelegationInfo {
210
+ delegationId: string;
211
+ endUserId: string;
212
+ bindingMode: BindingMode;
213
+ status: "active" | "revoked" | "expired";
214
+ expiresAt: string;
215
+ useCount: number;
216
+ lastUsedAt?: string;
217
+ createdAt: string;
218
+ }
219
+ interface ValidationResult {
220
+ valid: boolean;
221
+ sessionType?: "ai";
222
+ endUserId?: string;
223
+ delegation?: {
224
+ delegationId: string;
225
+ bindingMode: BindingMode;
226
+ expiresAt: string;
227
+ useCount: number;
228
+ };
229
+ error?: string;
230
+ }
231
+ interface DelegationStats {
232
+ totalDelegations: number;
233
+ activeDelegations: number;
234
+ totalUses: number;
235
+ delegationsByBinding: {
236
+ verifiedDevice: number;
237
+ anyLocation: number;
238
+ };
239
+ }
77
240
 
78
241
  /** Order fraud scoring. */
79
242
  declare class OrdersResource {
@@ -129,12 +292,20 @@ interface FlagsOptions {
129
292
  publicKey: string;
130
293
  /** API base URL. Defaults to https://api.simplr.sh. */
131
294
  baseUrl?: string;
132
- /** Which environment's flags to load. Defaults to the key's own environment. */
133
- environment?: "live" | "test";
295
+ /**
296
+ * Which environment's flags to load. Defaults to the key's own environment
297
+ * (the API falls back to the key's live/test mode when unset). Accepts a
298
+ * named environment slug (e.g. "dev", "uat", "prod") as well as the legacy
299
+ * "live"/"test" key modes. Sent to the API as `?environment=<value>`.
300
+ */
301
+ environment?: string;
134
302
  /** Auto-refresh interval in ms (default 60000; 0 disables). */
135
303
  refreshIntervalMs?: number;
136
304
  timeoutMs?: number;
137
305
  fetch?: typeof fetch;
306
+ onNetworkLog?: NetworkLogger;
307
+ logBodies?: boolean;
308
+ redactFields?: string[];
138
309
  }
139
310
  interface EvalContext {
140
311
  userId?: string;
@@ -172,6 +343,123 @@ declare class SimplrFlags {
172
343
  dispose(): void;
173
344
  }
174
345
 
346
+ /**
347
+ * Anonymous user profile management and order fraud monitoring.
348
+ *
349
+ * Works with the configured key (secret for server-side use). Mirrors the
350
+ * browser SimplrProfiles surface but reuses the Node http helper (which unwraps
351
+ * the `{ success, message, content }` envelope).
352
+ */
353
+ declare class SimplrProfiles {
354
+ private readonly cfg;
355
+ constructor(cfg: HttpConfig);
356
+ /**
357
+ * Identify a user — creates or updates an anonymous profile and (optionally)
358
+ * links a device fingerprint. POST /v1/profiles.
359
+ */
360
+ identify(externalId: string, options?: IdentifyOptions): Promise<ProfileResult>;
361
+ /** Submit an order for real-time fraud scoring. POST /v1/orders. */
362
+ submitOrder(order: OrderInput): Promise<OrderResult>;
363
+ /** Get the risk profile for a user. GET /v1/profiles/{externalId}. */
364
+ getProfileRisk(externalId: string): Promise<ProfileRiskResult>;
365
+ /** Report a profile as fraud or legitimate. POST /v1/profiles/{externalId}/outcome. */
366
+ reportOutcome(externalId: string, outcome: "fraud" | "legitimate"): Promise<void>;
367
+ }
368
+
369
+ interface SimplrRUMConfig {
370
+ /** Application identifier (required). */
371
+ applicationId: string;
372
+ /** Optional version/environment tags applied to every event. */
373
+ applicationVersion?: string;
374
+ environment?: string;
375
+ /** Flush when this many events are queued (default 30). */
376
+ batchSize?: number;
377
+ /** Background flush interval in ms (default 10000; 0 disables the timer). */
378
+ flushInterval?: number;
379
+ /** Override the events endpoint path (default /v1/rum/events). */
380
+ endpoint?: string;
381
+ }
382
+ /**
383
+ * Server-side Real User Monitoring. Batches events and flushes them to
384
+ * POST /v1/rum/events using the configured key. Unlike the browser SDK there is
385
+ * no DOM auto-capture — views/actions/errors/logs are reported via the public
386
+ * API. A timer-based flush is installed with `unref()` so it never keeps the
387
+ * Node process alive.
388
+ */
389
+ declare class SimplrRUM {
390
+ private readonly cfg;
391
+ private config;
392
+ private initialized;
393
+ private queue;
394
+ private timer;
395
+ private flushing;
396
+ private sessionId;
397
+ private currentViewId;
398
+ private userId?;
399
+ private userAttributes?;
400
+ private globalAttributes;
401
+ private batchSize;
402
+ private endpoint;
403
+ constructor(cfg: HttpConfig);
404
+ /** Initialize the SDK, start a session, and begin the flush timer. */
405
+ initialize(config: SimplrRUMConfig): void;
406
+ isInitialized(): boolean;
407
+ /** Associate subsequent events with a user. */
408
+ setUser(userId: string, attributes?: Record<string, unknown>): void;
409
+ clearUser(): void;
410
+ addAttribute(key: string, value: unknown): void;
411
+ removeAttribute(key: string): void;
412
+ /** Track a screen/page view. */
413
+ trackView(name: string, attributes?: Record<string, unknown>): void;
414
+ /** Track a user action. */
415
+ trackAction(name: string, attributes?: Record<string, unknown>): void;
416
+ /** Track an error. */
417
+ trackError(error: Error | {
418
+ message: string;
419
+ stack?: string;
420
+ type?: string;
421
+ }, attributes?: Record<string, unknown>): void;
422
+ /** Emit a log line. */
423
+ log(level: RUMLogLevel, message: string, attributes?: Record<string, unknown>): void;
424
+ private trackEvent;
425
+ /** Flush queued events to POST /v1/rum/events. */
426
+ flush(): Promise<void>;
427
+ /** End the session, flush remaining events, and stop the timer. */
428
+ stopSession(): Promise<void>;
429
+ getSessionId(): string | null;
430
+ getViewId(): string | null;
431
+ }
432
+
433
+ /**
434
+ * AI delegation — OAuth-like AI authentication. Lets you mint, validate and
435
+ * revoke delegation tokens that an end user shares with their AI agent.
436
+ *
437
+ * Reuses the Node http helper, which unwraps the `{ success, message, content }`
438
+ * envelope — so `apiRequest` returns the inner `content` object directly.
439
+ */
440
+ declare class SimplrAI {
441
+ private readonly cfg;
442
+ constructor(cfg: HttpConfig);
443
+ /** Create a new AI delegation token for a user. POST /v1/ai/delegations. */
444
+ createDelegation(options: CreateDelegationOptions): Promise<DelegationResult>;
445
+ /** Validate (introspect) an AI delegation token. POST /v1/ai/validate. */
446
+ validate(token: string, options?: {
447
+ fingerprintHash?: string;
448
+ aiProvider?: string;
449
+ action?: string;
450
+ }): Promise<ValidationResult>;
451
+ /** Revoke a delegation. POST /v1/ai/delegations/{id}/revoke. */
452
+ revoke(delegationId: string, reason?: string): Promise<void>;
453
+ /** List delegations, optionally filtered by user. GET /v1/ai/delegations. */
454
+ list(userId?: string): Promise<DelegationInfo[]>;
455
+ /** Get a single delegation. GET /v1/ai/delegations/{id}. */
456
+ get(delegationId: string): Promise<DelegationInfo>;
457
+ /** Get delegation statistics. GET /v1/ai/stats. */
458
+ stats(): Promise<DelegationStats>;
459
+ /** Revoke all delegations for a user (e.g. on logout). POST /v1/ai/revoke-all. */
460
+ revokeAllForUser(userId: string, reason?: string): Promise<number>;
461
+ }
462
+
175
463
  interface VerifyOptions {
176
464
  /** Reject signatures whose timestamp is older than this many seconds (default 300). 0 disables. */
177
465
  toleranceSec?: number;
@@ -217,6 +505,27 @@ declare class WebhookVerificationError extends Error {
217
505
  constructor(message: string);
218
506
  }
219
507
 
508
+ interface ShipperConfig {
509
+ baseUrl: string;
510
+ apiKey: string;
511
+ fetchImpl: typeof fetch;
512
+ sdk: string;
513
+ applicationId?: string;
514
+ environment?: string;
515
+ batchSize?: number;
516
+ flushIntervalMs?: number;
517
+ }
518
+ declare class NetworkLogShipper {
519
+ private readonly cfg;
520
+ private queue;
521
+ private timer;
522
+ constructor(cfg: ShipperConfig);
523
+ start(): void;
524
+ add(entry: NetworkLogEntry): void;
525
+ flush(): Promise<void>;
526
+ stop(): void;
527
+ }
528
+
220
529
  interface SimplrAdminOptions {
221
530
  /** Portal token (JWT) for dashboard/admin operations. */
222
531
  token: string;
@@ -299,9 +608,16 @@ declare class Simplr {
299
608
  readonly orders: OrdersResource;
300
609
  readonly phone: PhoneResource;
301
610
  readonly edge: EdgeResource;
611
+ /** Anonymous user profiles + order fraud monitoring. */
612
+ readonly profiles: SimplrProfiles;
613
+ /** Real User Monitoring — batched events to /v1/rum/events. */
614
+ readonly rum: SimplrRUM;
615
+ /** AI delegation — OAuth-like AI authentication. */
616
+ readonly ai: SimplrAI;
302
617
  /** Webhook signature helpers (no network). */
303
618
  readonly webhooks: typeof webhooks$1;
304
619
  private readonly _flags?;
620
+ private readonly shipper?;
305
621
  constructor(options: SimplrOptions);
306
622
  /**
307
623
  * Server-side feature flags. Requires a `publicKey` in the constructor options
@@ -312,6 +628,8 @@ declare class Simplr {
312
628
  check(input: CheckInput): Promise<CheckResult>;
313
629
  /** Run up to 100 checks at once. */
314
630
  checkBulk(items: CheckInput[]): Promise<BulkResult<CheckResult>>;
631
+ flushNetworkLogs(): Promise<void>;
632
+ close(): void;
315
633
  }
316
634
 
317
- export { type BulkResult, type CheckInput, type CheckResult, type EdgeLogEntry, type EvalContext, type FlagDefinition, type FlagRule, type FlagsOptions, type OrderInput, type OrderResult, type PhoneOutcome, type PhoneReportInput, type RiskLevel, Simplr, SimplrAdmin, type SimplrAdminOptions, SimplrError, SimplrFlags, type SimplrOptions, WebhookVerificationError, constructEvent as constructWebhookEvent, Simplr as default, verify as verifyWebhook };
635
+ export { type BindingMode, type BulkResult, type CheckInput, type CheckResult, type CreateDelegationOptions, type DelegationInfo, type DelegationResult, type DelegationStats, type EdgeLogEntry, type EvalContext, type FlagDefinition, type FlagRule, type FlagsOptions, type IdentifyOptions, type NetworkLogEntry, NetworkLogShipper, type NetworkLogger, type NetworkSource, type OrderInput, type OrderResult, type PhoneOutcome, type PhoneReportInput, type ProfileResult, type ProfileRiskResult, type RUMEvent, type RUMEventBatch, type RUMEventType, type RUMLogLevel, type RiskLevel, type ShipperConfig, Simplr, SimplrAI, SimplrAdmin, type SimplrAdminOptions, SimplrError, SimplrFlags, type SimplrOptions, SimplrProfiles, SimplrRUM, type SimplrRUMConfig, type ValidationResult, WebhookVerificationError, constructEvent as constructWebhookEvent, Simplr as default, verify as verifyWebhook };