@simplr-ai/node 1.0.0 → 1.1.1

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,5 +1,6 @@
1
1
  interface HttpConfig {
2
- apiKey: string;
2
+ /** Auth headers to send (e.g. { "X-API-Key": "sk_…" } or { Authorization: "Bearer …" }). */
3
+ authHeaders: Record<string, string>;
3
4
  baseUrl: string;
4
5
  timeoutMs: number;
5
6
  fetchImpl: typeof fetch;
@@ -9,6 +10,15 @@ type RiskLevel = "low" | "medium" | "high" | "critical";
9
10
  interface SimplrOptions {
10
11
  /** Secret API key (sk_live_… / sk_test_…). Keep this server-side only. */
11
12
  apiKey: string;
13
+ /** Public key (pk_…) — enables `simplr.flags` for server-side feature-flag evaluation. */
14
+ publicKey?: string;
15
+ /**
16
+ * Which environment's flags `simplr.flags` should load. Accepts a named
17
+ * environment slug (e.g. "dev", "uat", "prod") as well as the legacy
18
+ * "live"/"test" key modes. When unset, the API falls back to the public
19
+ * key's own live/test mode.
20
+ */
21
+ environment?: string;
12
22
  /** API base URL. Defaults to https://api.simplr.sh. */
13
23
  baseUrl?: string;
14
24
  /** Per-request timeout in ms (default 15000). */
@@ -71,6 +81,133 @@ interface EdgeLogEntry {
71
81
  message: string;
72
82
  [key: string]: unknown;
73
83
  }
84
+ interface IdentifyOptions {
85
+ /** Profile type. */
86
+ profileType?: "customer" | "cashier" | "employee";
87
+ /** Device fingerprint hash to link to this profile. */
88
+ fingerprintHash?: string;
89
+ /** Extra fields merged into the request body. */
90
+ [key: string]: unknown;
91
+ }
92
+ interface ProfileResult {
93
+ profile: {
94
+ id: string;
95
+ external_id: string;
96
+ profile_type: string;
97
+ status: string;
98
+ risk_score: number;
99
+ risk_level: string;
100
+ device_count: number;
101
+ total_orders: number;
102
+ first_seen_at: string;
103
+ last_seen_at: string;
104
+ };
105
+ is_new: boolean;
106
+ device_linked: boolean;
107
+ device_anomaly?: string;
108
+ [key: string]: unknown;
109
+ }
110
+ interface ProfileRiskResult {
111
+ profile: {
112
+ id: string;
113
+ external_id: string;
114
+ profile_type: string;
115
+ status: string;
116
+ risk_score: number;
117
+ risk_level: string;
118
+ signals: Record<string, number>;
119
+ device_count: number;
120
+ total_orders: number;
121
+ flagged_orders: number;
122
+ fraud_reports: number;
123
+ legitimate_reports: number;
124
+ first_seen_at: string;
125
+ last_seen_at: string;
126
+ };
127
+ [key: string]: unknown;
128
+ }
129
+ type RUMEventType = "session_start" | "session_end" | "view" | "action" | "error" | "log";
130
+ type RUMLogLevel = "debug" | "info" | "warn" | "error";
131
+ interface RUMEvent {
132
+ type: RUMEventType;
133
+ timestamp: number;
134
+ sessionId: string;
135
+ viewId?: string;
136
+ userId?: string;
137
+ applicationId: string;
138
+ applicationVersion?: string;
139
+ environment?: string;
140
+ view?: {
141
+ id: string;
142
+ name: string;
143
+ };
144
+ action?: {
145
+ name: string;
146
+ type: string;
147
+ };
148
+ error?: {
149
+ message: string;
150
+ stack?: string;
151
+ type?: string;
152
+ };
153
+ log?: {
154
+ level: RUMLogLevel;
155
+ message: string;
156
+ };
157
+ attributes?: Record<string, unknown>;
158
+ userAttributes?: Record<string, unknown>;
159
+ globalAttributes?: Record<string, unknown>;
160
+ }
161
+ interface RUMEventBatch {
162
+ events: RUMEvent[];
163
+ sentAt: number;
164
+ }
165
+ type BindingMode = "verified_device" | "any_location";
166
+ interface CreateDelegationOptions {
167
+ userId: string;
168
+ email?: string;
169
+ binding?: BindingMode;
170
+ expiresInDays?: number;
171
+ sessionId?: string;
172
+ fingerprintHash?: string;
173
+ }
174
+ interface DelegationResult {
175
+ token: string;
176
+ delegationId: string;
177
+ expiresAt: string;
178
+ bindingMode: BindingMode;
179
+ }
180
+ interface DelegationInfo {
181
+ delegationId: string;
182
+ endUserId: string;
183
+ bindingMode: BindingMode;
184
+ status: "active" | "revoked" | "expired";
185
+ expiresAt: string;
186
+ useCount: number;
187
+ lastUsedAt?: string;
188
+ createdAt: string;
189
+ }
190
+ interface ValidationResult {
191
+ valid: boolean;
192
+ sessionType?: "ai";
193
+ endUserId?: string;
194
+ delegation?: {
195
+ delegationId: string;
196
+ bindingMode: BindingMode;
197
+ expiresAt: string;
198
+ useCount: number;
199
+ };
200
+ error?: string;
201
+ }
202
+ interface DelegationStats {
203
+ totalDelegations: number;
204
+ activeDelegations: number;
205
+ totalUses: number;
206
+ delegationsByBinding: {
207
+ verifiedDevice: number;
208
+ anyLocation: number;
209
+ };
210
+ }
74
211
 
75
212
  /** Order fraud scoring. */
76
213
  declare class OrdersResource {
@@ -109,6 +246,188 @@ declare class EdgeResource {
109
246
  ingestLogs(deviceId: string, logs: EdgeLogEntry[]): Promise<unknown>;
110
247
  }
111
248
 
249
+ interface FlagRule {
250
+ attribute: string;
251
+ op: "eq" | "neq" | "contains";
252
+ value: string;
253
+ }
254
+ interface FlagDefinition {
255
+ key: string;
256
+ enabled: boolean;
257
+ rollout_percentage: number;
258
+ target_user_ids: string[];
259
+ rules: FlagRule[];
260
+ }
261
+ interface FlagsOptions {
262
+ /** Public API key (pk_live_… / pk_test_…). Required — flags read uses the public key. */
263
+ publicKey: string;
264
+ /** API base URL. Defaults to https://api.simplr.sh. */
265
+ baseUrl?: string;
266
+ /**
267
+ * Which environment's flags to load. Defaults to the key's own environment
268
+ * (the API falls back to the key's live/test mode when unset). Accepts a
269
+ * named environment slug (e.g. "dev", "uat", "prod") as well as the legacy
270
+ * "live"/"test" key modes. Sent to the API as `?environment=<value>`.
271
+ */
272
+ environment?: string;
273
+ /** Auto-refresh interval in ms (default 60000; 0 disables). */
274
+ refreshIntervalMs?: number;
275
+ timeoutMs?: number;
276
+ fetch?: typeof fetch;
277
+ }
278
+ interface EvalContext {
279
+ userId?: string;
280
+ attributes?: Record<string, unknown>;
281
+ }
282
+ /**
283
+ * Server-side feature flags with local, deterministic evaluation.
284
+ *
285
+ * ```ts
286
+ * const flags = new SimplrFlags({ publicKey: process.env.SIMPLR_PUBLIC_KEY! });
287
+ * await flags.initialize();
288
+ * if (flags.isEnabled("new-checkout", { userId: "user_123" })) { ... }
289
+ * ```
290
+ */
291
+ declare class SimplrFlags {
292
+ private readonly cfg;
293
+ private readonly environment?;
294
+ private readonly refreshIntervalMs;
295
+ private flags;
296
+ private defaultUserId?;
297
+ private timer;
298
+ private ready;
299
+ constructor(options: FlagsOptions);
300
+ /** Fetch the flag config once and start the background refresh. */
301
+ initialize(): Promise<void>;
302
+ /** Set the default identifier used for bucketing when none is passed to isEnabled. */
303
+ setUser(userId: string): void;
304
+ /** Re-fetch the flag config (counts as one billable request). */
305
+ refresh(): Promise<void>;
306
+ /** Evaluate a flag locally. Deterministic per user; no network call. */
307
+ isEnabled(key: string, ctx?: EvalContext): boolean;
308
+ getAll(): Record<string, FlagDefinition>;
309
+ isReady(): boolean;
310
+ /** Stop the background refresh timer. */
311
+ dispose(): void;
312
+ }
313
+
314
+ /**
315
+ * Anonymous user profile management and order fraud monitoring.
316
+ *
317
+ * Works with the configured key (secret for server-side use). Mirrors the
318
+ * browser SimplrProfiles surface but reuses the Node http helper (which unwraps
319
+ * the `{ success, message, content }` envelope).
320
+ */
321
+ declare class SimplrProfiles {
322
+ private readonly cfg;
323
+ constructor(cfg: HttpConfig);
324
+ /**
325
+ * Identify a user — creates or updates an anonymous profile and (optionally)
326
+ * links a device fingerprint. POST /v1/profiles.
327
+ */
328
+ identify(externalId: string, options?: IdentifyOptions): Promise<ProfileResult>;
329
+ /** Submit an order for real-time fraud scoring. POST /v1/orders. */
330
+ submitOrder(order: OrderInput): Promise<OrderResult>;
331
+ /** Get the risk profile for a user. GET /v1/profiles/{externalId}. */
332
+ getProfileRisk(externalId: string): Promise<ProfileRiskResult>;
333
+ /** Report a profile as fraud or legitimate. POST /v1/profiles/{externalId}/outcome. */
334
+ reportOutcome(externalId: string, outcome: "fraud" | "legitimate"): Promise<void>;
335
+ }
336
+
337
+ interface SimplrRUMConfig {
338
+ /** Application identifier (required). */
339
+ applicationId: string;
340
+ /** Optional version/environment tags applied to every event. */
341
+ applicationVersion?: string;
342
+ environment?: string;
343
+ /** Flush when this many events are queued (default 30). */
344
+ batchSize?: number;
345
+ /** Background flush interval in ms (default 10000; 0 disables the timer). */
346
+ flushInterval?: number;
347
+ /** Override the events endpoint path (default /v1/rum/events). */
348
+ endpoint?: string;
349
+ }
350
+ /**
351
+ * Server-side Real User Monitoring. Batches events and flushes them to
352
+ * POST /v1/rum/events using the configured key. Unlike the browser SDK there is
353
+ * no DOM auto-capture — views/actions/errors/logs are reported via the public
354
+ * API. A timer-based flush is installed with `unref()` so it never keeps the
355
+ * Node process alive.
356
+ */
357
+ declare class SimplrRUM {
358
+ private readonly cfg;
359
+ private config;
360
+ private initialized;
361
+ private queue;
362
+ private timer;
363
+ private flushing;
364
+ private sessionId;
365
+ private currentViewId;
366
+ private userId?;
367
+ private userAttributes?;
368
+ private globalAttributes;
369
+ private batchSize;
370
+ private endpoint;
371
+ constructor(cfg: HttpConfig);
372
+ /** Initialize the SDK, start a session, and begin the flush timer. */
373
+ initialize(config: SimplrRUMConfig): void;
374
+ isInitialized(): boolean;
375
+ /** Associate subsequent events with a user. */
376
+ setUser(userId: string, attributes?: Record<string, unknown>): void;
377
+ clearUser(): void;
378
+ addAttribute(key: string, value: unknown): void;
379
+ removeAttribute(key: string): void;
380
+ /** Track a screen/page view. */
381
+ trackView(name: string, attributes?: Record<string, unknown>): void;
382
+ /** Track a user action. */
383
+ trackAction(name: string, attributes?: Record<string, unknown>): void;
384
+ /** Track an error. */
385
+ trackError(error: Error | {
386
+ message: string;
387
+ stack?: string;
388
+ type?: string;
389
+ }, attributes?: Record<string, unknown>): void;
390
+ /** Emit a log line. */
391
+ log(level: RUMLogLevel, message: string, attributes?: Record<string, unknown>): void;
392
+ private trackEvent;
393
+ /** Flush queued events to POST /v1/rum/events. */
394
+ flush(): Promise<void>;
395
+ /** End the session, flush remaining events, and stop the timer. */
396
+ stopSession(): Promise<void>;
397
+ getSessionId(): string | null;
398
+ getViewId(): string | null;
399
+ }
400
+
401
+ /**
402
+ * AI delegation — OAuth-like AI authentication. Lets you mint, validate and
403
+ * revoke delegation tokens that an end user shares with their AI agent.
404
+ *
405
+ * Reuses the Node http helper, which unwraps the `{ success, message, content }`
406
+ * envelope — so `apiRequest` returns the inner `content` object directly.
407
+ */
408
+ declare class SimplrAI {
409
+ private readonly cfg;
410
+ constructor(cfg: HttpConfig);
411
+ /** Create a new AI delegation token for a user. POST /v1/ai/delegations. */
412
+ createDelegation(options: CreateDelegationOptions): Promise<DelegationResult>;
413
+ /** Validate (introspect) an AI delegation token. POST /v1/ai/validate. */
414
+ validate(token: string, options?: {
415
+ fingerprintHash?: string;
416
+ aiProvider?: string;
417
+ action?: string;
418
+ }): Promise<ValidationResult>;
419
+ /** Revoke a delegation. POST /v1/ai/delegations/{id}/revoke. */
420
+ revoke(delegationId: string, reason?: string): Promise<void>;
421
+ /** List delegations, optionally filtered by user. GET /v1/ai/delegations. */
422
+ list(userId?: string): Promise<DelegationInfo[]>;
423
+ /** Get a single delegation. GET /v1/ai/delegations/{id}. */
424
+ get(delegationId: string): Promise<DelegationInfo>;
425
+ /** Get delegation statistics. GET /v1/ai/stats. */
426
+ stats(): Promise<DelegationStats>;
427
+ /** Revoke all delegations for a user (e.g. on logout). POST /v1/ai/revoke-all. */
428
+ revokeAllForUser(userId: string, reason?: string): Promise<number>;
429
+ }
430
+
112
431
  interface VerifyOptions {
113
432
  /** Reject signatures whose timestamp is older than this many seconds (default 300). 0 disables. */
114
433
  toleranceSec?: number;
@@ -154,6 +473,74 @@ declare class WebhookVerificationError extends Error {
154
473
  constructor(message: string);
155
474
  }
156
475
 
476
+ interface SimplrAdminOptions {
477
+ /** Portal token (JWT) for dashboard/admin operations. */
478
+ token: string;
479
+ /** API base URL. Defaults to https://api.simplr.sh. */
480
+ baseUrl?: string;
481
+ timeoutMs?: number;
482
+ fetch?: typeof fetch;
483
+ }
484
+ /** Usage / measurement reads. */
485
+ declare class UsageApi {
486
+ private readonly cfg;
487
+ constructor(cfg: HttpConfig);
488
+ /** Aggregate usage stats for an org. */
489
+ stats(orgId: string): Promise<unknown>;
490
+ /** Raw usage logs for an org. */
491
+ logs(orgId: string, params?: {
492
+ page?: number;
493
+ limit?: number;
494
+ }): Promise<unknown>;
495
+ /** Billing usage breakdown (per-service totals + estimated cost). */
496
+ billing(orgId: string): Promise<unknown>;
497
+ }
498
+ /** Feature-flag administration (create/update/delete/history). */
499
+ declare class FlagsAdminApi {
500
+ private readonly cfg;
501
+ constructor(cfg: HttpConfig);
502
+ list(orgId: string, environment?: "live" | "test"): Promise<unknown>;
503
+ get(orgId: string, id: string): Promise<unknown>;
504
+ create(orgId: string, data: Record<string, unknown>): Promise<unknown>;
505
+ update(orgId: string, id: string, data: Record<string, unknown>): Promise<unknown>;
506
+ remove(orgId: string, id: string): Promise<unknown>;
507
+ history(orgId: string, id: string, params?: {
508
+ limit?: number;
509
+ offset?: number;
510
+ }): Promise<unknown>;
511
+ }
512
+ /** RUM analytics reads. */
513
+ declare class RumApi {
514
+ private readonly cfg;
515
+ constructor(cfg: HttpConfig);
516
+ overview(orgId: string, params?: {
517
+ application_id?: string;
518
+ start_date?: string;
519
+ end_date?: string;
520
+ }): Promise<unknown>;
521
+ sessions(orgId: string, params?: {
522
+ page?: number;
523
+ limit?: number;
524
+ user_id?: string;
525
+ }): Promise<unknown>;
526
+ }
527
+ /**
528
+ * Management client for dashboard/admin operations that require a portal token
529
+ * (usage/measurement, feature-flag CRUD, RUM analytics).
530
+ *
531
+ * ```ts
532
+ * const admin = new SimplrAdmin({ token: process.env.SIMPLR_PORTAL_TOKEN! });
533
+ * const usage = await admin.usage.billing(orgId);
534
+ * await admin.flags.create(orgId, { key: "new-checkout", environment: "test", rollout_percentage: 10 });
535
+ * ```
536
+ */
537
+ declare class SimplrAdmin {
538
+ readonly usage: UsageApi;
539
+ readonly flags: FlagsAdminApi;
540
+ readonly rum: RumApi;
541
+ constructor(options: SimplrAdminOptions);
542
+ }
543
+
157
544
  /**
158
545
  * Simplr server-side client.
159
546
  *
@@ -168,13 +555,25 @@ declare class Simplr {
168
555
  readonly orders: OrdersResource;
169
556
  readonly phone: PhoneResource;
170
557
  readonly edge: EdgeResource;
558
+ /** Anonymous user profiles + order fraud monitoring. */
559
+ readonly profiles: SimplrProfiles;
560
+ /** Real User Monitoring — batched events to /v1/rum/events. */
561
+ readonly rum: SimplrRUM;
562
+ /** AI delegation — OAuth-like AI authentication. */
563
+ readonly ai: SimplrAI;
171
564
  /** Webhook signature helpers (no network). */
172
565
  readonly webhooks: typeof webhooks$1;
566
+ private readonly _flags?;
173
567
  constructor(options: SimplrOptions);
568
+ /**
569
+ * Server-side feature flags. Requires a `publicKey` in the constructor options
570
+ * (flag config is read with the public key). Call `simplr.flags.initialize()` once.
571
+ */
572
+ get flags(): SimplrFlags;
174
573
  /** Run an identity/fraud check. Provide any of email, phone, device, behavior. */
175
574
  check(input: CheckInput): Promise<CheckResult>;
176
575
  /** Run up to 100 checks at once. */
177
576
  checkBulk(items: CheckInput[]): Promise<BulkResult<CheckResult>>;
178
577
  }
179
578
 
180
- export { type BulkResult, type CheckInput, type CheckResult, type EdgeLogEntry, type OrderInput, type OrderResult, type PhoneOutcome, type PhoneReportInput, type RiskLevel, Simplr, SimplrError, type SimplrOptions, WebhookVerificationError, constructEvent as constructWebhookEvent, Simplr as default, verify as verifyWebhook };
579
+ 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 OrderInput, type OrderResult, type PhoneOutcome, type PhoneReportInput, type ProfileResult, type ProfileRiskResult, type RUMEvent, type RUMEventBatch, type RUMEventType, type RUMLogLevel, type RiskLevel, 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 };