@sylphx/sdk 0.28.0 → 0.30.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -118
  3. package/dist/access.d.ts +659 -0
  4. package/dist/access.js +638 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/ai.d.ts +176 -0
  7. package/dist/ai.js +112 -0
  8. package/dist/ai.js.map +1 -0
  9. package/dist/artifacts.d.ts +165 -0
  10. package/dist/artifacts.js +129 -0
  11. package/dist/artifacts.js.map +1 -0
  12. package/dist/auth.d.ts +896 -0
  13. package/dist/auth.js +828 -0
  14. package/dist/auth.js.map +1 -0
  15. package/dist/billing.d.ts +758 -0
  16. package/dist/billing.js +553 -0
  17. package/dist/billing.js.map +1 -0
  18. package/dist/broker.d.ts +226 -0
  19. package/dist/broker.js +187 -0
  20. package/dist/broker.js.map +1 -0
  21. package/dist/build.d.ts +313 -0
  22. package/dist/build.js +271 -0
  23. package/dist/build.js.map +1 -0
  24. package/dist/common.d.ts +162 -0
  25. package/dist/common.js +41 -0
  26. package/dist/common.js.map +1 -0
  27. package/dist/config.d.ts +198 -0
  28. package/dist/config.js +168 -0
  29. package/dist/config.js.map +1 -0
  30. package/dist/connections.d.ts +354 -0
  31. package/dist/connections.js +313 -0
  32. package/dist/connections.js.map +1 -0
  33. package/dist/data.d.ts +858 -0
  34. package/dist/data.js +814 -0
  35. package/dist/data.js.map +1 -0
  36. package/dist/entitlement.d.ts +172 -0
  37. package/dist/entitlement.js +116 -0
  38. package/dist/entitlement.js.map +1 -0
  39. package/dist/events.d.ts +1324 -0
  40. package/dist/events.js +1227 -0
  41. package/dist/events.js.map +1 -0
  42. package/dist/hosting.d.ts +709 -0
  43. package/dist/hosting.js +611 -0
  44. package/dist/hosting.js.map +1 -0
  45. package/dist/index.d.ts +79 -33656
  46. package/dist/index.js +113 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/keys.d.ts +438 -0
  49. package/dist/keys.js +406 -0
  50. package/dist/keys.js.map +1 -0
  51. package/dist/methods.d.ts +2 -0
  52. package/dist/methods.js +3995 -0
  53. package/dist/methods.js.map +1 -0
  54. package/dist/network.d.ts +733 -0
  55. package/dist/network.js +711 -0
  56. package/dist/network.js.map +1 -0
  57. package/dist/notify.d.ts +1359 -0
  58. package/dist/notify.js +1282 -0
  59. package/dist/notify.js.map +1 -0
  60. package/dist/observability.d.ts +509 -0
  61. package/dist/observability.js +437 -0
  62. package/dist/observability.js.map +1 -0
  63. package/dist/release.d.ts +303 -0
  64. package/dist/release.js +214 -0
  65. package/dist/release.js.map +1 -0
  66. package/dist/runners.d.ts +262 -0
  67. package/dist/runners.js +238 -0
  68. package/dist/runners.js.map +1 -0
  69. package/dist/runtime.d.ts +88 -0
  70. package/dist/runtime.js +226 -0
  71. package/dist/runtime.js.map +1 -0
  72. package/dist/sandboxes.d.ts +1705 -0
  73. package/dist/sandboxes.js +1226 -0
  74. package/dist/sandboxes.js.map +1 -0
  75. package/dist/secrets.d.ts +508 -0
  76. package/dist/secrets.js +474 -0
  77. package/dist/secrets.js.map +1 -0
  78. package/dist/workflows.d.ts +678 -0
  79. package/dist/workflows.js +595 -0
  80. package/dist/workflows.js.map +1 -0
  81. package/package.json +33 -112
  82. package/dist/connect.d.ts +0 -2838
  83. package/dist/connect.mjs +0 -220
  84. package/dist/connect.mjs.map +0 -1
  85. package/dist/health/index.d.ts +0 -1394
  86. package/dist/health/index.mjs +0 -1394
  87. package/dist/health/index.mjs.map +0 -1
  88. package/dist/index.mjs +0 -38429
  89. package/dist/index.mjs.map +0 -1
  90. package/dist/nextjs/index.d.ts +0 -724
  91. package/dist/nextjs/index.mjs +0 -3332
  92. package/dist/nextjs/index.mjs.map +0 -1
  93. package/dist/react/index.d.ts +0 -13066
  94. package/dist/react/index.mjs +0 -35329
  95. package/dist/react/index.mjs.map +0 -1
  96. package/dist/server/index.d.ts +0 -2000
  97. package/dist/server/index.mjs +0 -3446
  98. package/dist/server/index.mjs.map +0 -1
  99. package/dist/web-analytics.d.ts +0 -90
  100. package/dist/web-analytics.mjs +0 -225
  101. package/dist/web-analytics.mjs.map +0 -1
@@ -1,2000 +0,0 @@
1
- import { SdkBillingPlan, SdkConsentType } from '@sylphx/contract';
2
- export { LEGACY_PLATFORM_PROJECT_ID, PLATFORM_CONSOLE_SLUG, isPlatformProjectIdentity } from '@sylphx/contract';
3
-
4
- /**
5
- * REST Client for Sylphx Platform
6
- *
7
- * Type-safe REST API client built on plain `fetch` (no runtime `openapi-fetch`
8
- * dependency — ADR-084 routes types through `@sylphx/contract` so the codegen
9
- * layer no longer needs a transport library of its own). Public surface is
10
- * preserved: consumers still call `client.GET('/path')`, `client.POST(...)`,
11
- * etc. The middleware chain (deduplication → circuit breaker → ETag →
12
- * retry) runs in the same order as the previous implementation.
13
- *
14
- * @example
15
- * ```typescript
16
- * import { createRestClient } from '@sylphx/sdk'
17
- *
18
- * const client = createRestClient({
19
- * secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
20
- * })
21
- *
22
- * const { data: user, error } = await client.GET('/auth/me')
23
- * const { data: result } = await client.POST('/auth/login', {
24
- * body: { email, password },
25
- * })
26
- * ```
27
- */
28
- /**
29
- * Retry configuration for automatic request retries
30
- */
31
- interface RetryConfig {
32
- /** Maximum number of retries (default: 3) */
33
- maxRetries?: number;
34
- /** Base delay in milliseconds (default: 1000) */
35
- baseDelay?: number;
36
- /** Maximum delay in milliseconds (default: 30000) */
37
- maxDelay?: number;
38
- /** Custom function to determine if error is retryable */
39
- shouldRetry?: (status: number, attempt: number) => boolean;
40
- /** Request timeout in milliseconds (default: 30000) */
41
- timeout?: number;
42
- }
43
- /**
44
- * Request deduplication configuration
45
- */
46
- interface DeduplicationConfig {
47
- /** Enable request deduplication (default: true) */
48
- enabled?: boolean;
49
- /** HTTP methods to deduplicate (default: ['GET']) */
50
- methods?: ('GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH')[];
51
- }
52
- /**
53
- * Circuit breaker configuration (AWS/Resilience4j pattern)
54
- *
55
- * Prevents cascade failures by fast-failing when service is unhealthy.
56
- * States: CLOSED (normal) → OPEN (failing) → HALF_OPEN (testing)
57
- */
58
- interface CircuitBreakerConfig {
59
- /** Enable circuit breaker (default: true) */
60
- enabled?: boolean;
61
- /** Number of failures before opening circuit (default: 5) */
62
- failureThreshold?: number;
63
- /** Time window for counting failures in ms (default: 10000) */
64
- windowMs?: number;
65
- /** How long circuit stays open in ms (default: 30000) */
66
- openDurationMs?: number;
67
- /** Custom function to determine if response is a failure */
68
- isFailure?: (status: number) => boolean;
69
- }
70
- /**
71
- * ETag/Conditional request configuration (HTTP caching pattern)
72
- *
73
- * Enables HTTP conditional requests with If-None-Match header
74
- * to avoid re-downloading unchanged data (saves bandwidth).
75
- */
76
- interface ETagConfig {
77
- /** Enable ETag caching (default: true for GET requests) */
78
- enabled?: boolean;
79
- /** Maximum cache entries (default: 100) */
80
- maxEntries?: number;
81
- /** Cache TTL in milliseconds (default: 5 minutes) */
82
- ttlMs?: number;
83
- }
84
- /**
85
- * Configuration for the REST client
86
- *
87
- * The app key identifies the app — no separate app ID needed.
88
- */
89
- interface RestClientConfig {
90
- /**
91
- * Your app key — identifies the app and environment.
92
- *
93
- * Accepts either:
94
- * - Secret key (sk_dev_, sk_stg_, sk_prod_) — full access, server-side only
95
- * - Publishable key (app_dev_, app_stg_, app_prod_) — limited access, safe for client
96
- */
97
- secretKey: string;
98
- /** Platform URL (default: https://sylphx.com) */
99
- platformUrl?: string;
100
- /** Retry configuration (default: 3 retries with exponential backoff) */
101
- retry?: RetryConfig | false;
102
- /**
103
- * Request deduplication configuration (default: enabled for GET)
104
- *
105
- * Prevents duplicate concurrent requests for the same resource.
106
- * When multiple components request the same data simultaneously,
107
- * only one API call is made and the result is shared.
108
- */
109
- deduplication?: DeduplicationConfig | false;
110
- /**
111
- * Circuit breaker configuration (default: enabled)
112
- *
113
- * Prevents cascade failures by fast-failing when service is unhealthy.
114
- * Opens after 5 failures in 10s, stays open for 30s, then allows test request.
115
- */
116
- circuitBreaker?: CircuitBreakerConfig | false;
117
- /**
118
- * ETag caching configuration (default: enabled for GET)
119
- *
120
- * Uses HTTP conditional requests to avoid re-downloading unchanged data.
121
- * Saves bandwidth by returning 304 Not Modified when content hasn't changed.
122
- */
123
- etag?: ETagConfig | false;
124
- }
125
- /**
126
- * Middleware contract — kept structurally identical to the previous
127
- * `openapi-fetch` shape so existing implementations (dedup / circuit breaker
128
- * / ETag / retry) compose without change.
129
- */
130
- interface Middleware {
131
- onRequest?: (ctx: {
132
- request: Request;
133
- }) => Promise<Request | undefined> | Request | undefined;
134
- onFetch?: (ctx: {
135
- request: Request;
136
- next: (request: Request) => Promise<Response>;
137
- }) => Promise<Response | undefined> | Response | undefined;
138
- onResponse?: (ctx: {
139
- request: Request;
140
- response: Response;
141
- }) => Promise<Response | undefined> | Response | undefined;
142
- }
143
- /**
144
- * Options for an HTTP request — structural subset of `openapi-fetch`'s
145
- * `FetchOptions` so existing callsites (`client.GET('/path', { params: {...} })`)
146
- * continue to compile.
147
- */
148
- interface RequestOptions {
149
- body?: unknown;
150
- params?: {
151
- path?: Record<string, string>;
152
- query?: Record<string, unknown>;
153
- };
154
- headers?: Record<string, string>;
155
- }
156
- /**
157
- * Response envelope — `{ data, error, response }` mirroring `openapi-fetch`.
158
- * `data` is present on 2xx, `error` on non-2xx; both carry the parsed JSON
159
- * body when the server returns one. `response` is always the raw `Response`
160
- * so consumers can read headers (Content-Type, Retry-After, etc.).
161
- */
162
- interface FetchResponse<TOk, TError> {
163
- data?: TOk;
164
- error?: TError;
165
- response: Response;
166
- }
167
- /**
168
- * The typed method surface. Callers pass a path + options; return envelope
169
- * follows openapi-fetch's shape so migration is drop-in for the small number
170
- * of internal callers that relied on `.GET` / `.POST` etc.
171
- */
172
- interface RestClient {
173
- GET<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
174
- POST<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
175
- PUT<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
176
- PATCH<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
177
- DELETE<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
178
- HEAD<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
179
- OPTIONS<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
180
- use(...middleware: readonly Middleware[]): void;
181
- }
182
-
183
- declare class InvalidConnectionUrlError extends Error {
184
- readonly code: "INVALID_CONNECTION_URL";
185
- constructor(message: string);
186
- }
187
-
188
- /**
189
- * SDK Configuration — ADR-055 Connection URL API
190
- *
191
- * v0.5.0: The primary entry point is `createClient(url)` which accepts
192
- * a `sylphx://` connection URL. The old `createConfig({ ref, publicKey })`
193
- * API is removed.
194
- *
195
- * @example
196
- * ```typescript
197
- * import { createClient } from '@sylphx/sdk'
198
- *
199
- * const sylphx = createClient(process.env.SYLPHX_URL!)
200
- * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
201
- * ```
202
- */
203
-
204
- /**
205
- * SDK Configuration object — immutable, frozen.
206
- *
207
- * Created by `createClient()` or `createServerClient()`.
208
- * Passed to all pure SDK functions (`track()`, `signIn()`, etc.).
209
- */
210
- interface SylphxConfig {
211
- /** The credential string (pk_* or sk_*) */
212
- readonly credential: string;
213
- /** Credential type: 'pk' (publishable) or 'sk' (secret) */
214
- readonly credentialType: 'pk' | 'sk';
215
- /** Target environment: dev, stg, prod, or prev */
216
- readonly env: 'dev' | 'stg' | 'prod' | 'prev';
217
- /** Resource slug (first DNS label), e.g. 'bold-river-a1b2c3' */
218
- readonly slug: string;
219
- /** Pre-computed API base URL, e.g. 'https://bold-river-a1b2c3.api.sylphx.com/v1' */
220
- readonly baseUrl: string;
221
- /** Optional access token for authenticated requests */
222
- readonly accessToken?: string;
223
- /**
224
- * Secret key — populated when credentialType is 'sk'.
225
- * Backward-compatible alias for `credential` when credential is sk_*.
226
- */
227
- readonly secretKey?: string;
228
- /**
229
- * Publishable key — populated when credentialType is 'pk'.
230
- * Backward-compatible alias for `credential` when credential is pk_*.
231
- */
232
- readonly publicKey?: string;
233
- /**
234
- * @deprecated Use `slug`. Backward-compatible alias.
235
- */
236
- readonly ref: string;
237
- }
238
- /**
239
- * Explicit components input — alternative to connection URL string.
240
- *
241
- * For multi-tenant apps or cases where components are stored separately.
242
- */
243
- interface SylphxClientInput {
244
- /** Resource slug, e.g. 'bold-river-a1b2c3' */
245
- slug?: string;
246
- /** Publishable key (pk_*) — client-safe */
247
- publicKey?: string;
248
- /** Secret key (sk_*) — server-side only */
249
- secretKey?: string;
250
- /** Optional access token */
251
- accessToken?: string;
252
- /** API domain override (default: api.sylphx.com) */
253
- domain?: string;
254
- /**
255
- * @deprecated Use `slug`. Accepted for backward compatibility during migration.
256
- */
257
- ref?: string;
258
- /**
259
- * @deprecated Use `domain`. Accepted for backward compatibility during migration.
260
- */
261
- platformUrl?: string;
262
- }
263
- /**
264
- * Create a Sylphx client from a connection URL or explicit components.
265
- *
266
- * This is the primary SDK entry point for client-side (browser) usage.
267
- * Accepts a `sylphx://` connection URL or an explicit components object.
268
- *
269
- * @example Connection URL (recommended)
270
- * ```typescript
271
- * const sylphx = createClient(process.env.NEXT_PUBLIC_SYLPHX_URL!)
272
- * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
273
- * ```
274
- *
275
- * @example Explicit components
276
- * ```typescript
277
- * const sylphx = createClient({
278
- * slug: 'bold-river-a1b2c3',
279
- * publicKey: 'pk_prod_f19e...',
280
- * })
281
- * ```
282
- */
283
- declare function createClient(input: string | SylphxClientInput): SylphxConfig;
284
- /**
285
- * Create a Sylphx server client from a connection URL or explicit components.
286
- *
287
- * Equivalent to `createClient()` but validates that a secret key (sk_*) is provided.
288
- * Use this for server-side operations that require elevated permissions.
289
- *
290
- * @example Connection URL (recommended)
291
- * ```typescript
292
- * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
293
- * // Parses: sylphx://sk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
294
- * ```
295
- *
296
- * @example Explicit components
297
- * ```typescript
298
- * const sylphx = createServerClient({
299
- * slug: 'bold-river-a1b2c3',
300
- * secretKey: 'sk_prod_5120...',
301
- * })
302
- * ```
303
- */
304
- declare function createServerClient(input: string | SylphxClientInput): SylphxConfig;
305
-
306
- /**
307
- * Billing Functions
308
- *
309
- * Pure functions for billing and subscriptions.
310
- * Uses REST API at /api/sdk/billing/* for all operations.
311
- *
312
- * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
313
- * contract is the single source of truth for `GET /billing/plans`,
314
- * `/billing/subscription`, `POST /billing/checkout`, `/billing/portal`,
315
- * `GET /billing/balance`, `/billing/usage`.
316
- */
317
-
318
- type Plan = SdkBillingPlan;
319
-
320
- /**
321
- * Consent Functions
322
- *
323
- * Pure functions for GDPR/CCPA consent management.
324
- *
325
- * ## Architecture (ADR-004)
326
- *
327
- * Consent uses **Inline Defaults + Auto-Discovery + Console Override**:
328
- * - Code provides optional inline defaults when checking consent
329
- * - Platform auto-discovers/creates consent types when first referenced
330
- * - Console can override names, descriptions, requirements without deployment
331
- *
332
- * Wire-shape types and endpoint paths are re-exported from
333
- * `@sylphx/contract` (ADR-084). The contract is the single source of truth
334
- * for `GET /consent/types`, `GET /consent`, `POST /consent`, and friends.
335
- * This module keeps ergonomic helper inputs only where the public SDK API
336
- * intentionally differs from the wire shape.
337
- *
338
- * @example
339
- * ```typescript
340
- * import { hasConsent, getUserConsents, setConsents } from '@sylphx/sdk'
341
- *
342
- * // Check consent with inline defaults (auto-discovered if doesn't exist)
343
- * if (await hasConsent(config, 'analytics', { userId: 'user-123' }, {
344
- * name: 'Analytics Cookies',
345
- * description: 'Help us understand how visitors use our site',
346
- * category: 'analytics',
347
- * required: false,
348
- * })) {
349
- * track('pageview')
350
- * }
351
- *
352
- * // Get user's current consents
353
- * const consents = await getUserConsents(config, { userId: 'user-123' })
354
- *
355
- * // Set specific consents
356
- * await setConsents(config, {
357
- * userId: 'user-123',
358
- * consents: { analytics: true, marketing: false }
359
- * })
360
- * ```
361
- */
362
-
363
- type ConsentType = SdkConsentType;
364
-
365
- /**
366
- * AI Functions
367
- *
368
- * Pure functions for AI completions - Vercel AI SDK style.
369
- * Direct API calls with natural tree-shaking.
370
- *
371
- * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
372
- * contract is the single source of truth for `GET /ai/models`,
373
- * `/ai/usage`, `/ai/rate-limit`. Chat-completion / embedding envelopes
374
- * remain local to this module — they pass through the Vercel AI SDK
375
- * bridge and evolve independently of the platform contract.
376
- */
377
-
378
- interface ChatMessage {
379
- role: 'system' | 'user' | 'assistant' | 'tool';
380
- content: string | ContentPart[];
381
- name?: string;
382
- tool_call_id?: string;
383
- tool_calls?: ToolCall[];
384
- /** Timestamp for UI display */
385
- timestamp?: Date;
386
- }
387
- interface ContentPart {
388
- type: 'text' | 'image_url';
389
- text?: string;
390
- image_url?: {
391
- url: string;
392
- detail?: 'auto' | 'low' | 'high';
393
- };
394
- }
395
- interface ToolCall {
396
- id: string;
397
- type: 'function';
398
- function: {
399
- name: string;
400
- arguments: string;
401
- };
402
- }
403
-
404
- /**
405
- * SDK-specific types — cross-layer helpers and server-first configuration.
406
- *
407
- * Wire-shape types (API request/response envelopes) live in
408
- * `@sylphx/contract` and are re-exported per namespace from their SDK
409
- * module (e.g. `Plan` / `Subscription` from `./billing`, `ConsentType`
410
- * from `./consent`, `TokenResponse` from `./auth`). React-hook wrapper
411
- * shapes live in `./react/types` (tRPC-like convenience shapes that
412
- * are not part of the platform wire).
413
- *
414
- * History: pre-ADR-084 this file mirrored every wire shape the SDK
415
- * exposed; those aliases now come directly from `@sylphx/contract`.
416
- */
417
-
418
- declare const OAUTH_PROVIDERS: readonly ["google", "github", "apple", "microsoft", "facebook", "twitter", "discord", "linkedin", "slack", "gitlab", "bitbucket", "twitch", "spotify"];
419
- type OAuthProviderId = (typeof OAUTH_PROVIDERS)[number];
420
- interface OAuthProviderInfo$1 {
421
- id: OAuthProviderId;
422
- name: string;
423
- }
424
- interface FeatureFlagDefinition$1 {
425
- key: string;
426
- name: string;
427
- description: string | null;
428
- enabled: boolean;
429
- rolloutPercentage: number;
430
- targetPremiumOnly: boolean;
431
- targetAdminOnly: boolean;
432
- }
433
- interface AppMetadata$1 {
434
- id: string;
435
- name: string;
436
- slug: string;
437
- captcha?: {
438
- enabled: true;
439
- provider: 'turnstile' | 'hcaptcha';
440
- siteKey: string;
441
- action: 'register';
442
- };
443
- }
444
- /** Fetched server-side via `getAppConfig()`, passed to `SylphxProvider`. */
445
- interface AppConfig {
446
- plans: Plan[];
447
- consentTypes: ConsentType[];
448
- oauthProviders: OAuthProviderInfo$1[];
449
- featureFlags: FeatureFlagDefinition$1[];
450
- app: AppMetadata$1;
451
- fetchedAt: string;
452
- }
453
- interface AccessTokenPayload {
454
- /** Raw UUID (OAuth/OIDC spec). */
455
- sub: string;
456
- /** Prefixed platform ID (e.g. `user_xxx`). */
457
- pid?: string;
458
- email: string;
459
- name?: string;
460
- picture?: string;
461
- email_verified: boolean;
462
- app_id: string;
463
- role?: string;
464
- /** Project session id when the token was minted from a BaaS auth session. */
465
- sid?: string;
466
- /**
467
- * Org context claims — present on org-scoped tokens (switch-org exchanges
468
- * and service-account client-credentials grants; ADR-2062). Resource
469
- * servers MUST compare `org_id` against the addressed resource's org and
470
- * assert `org_role` against their allowlist before granting org-scoped
471
- * access. Absent on plain user tokens.
472
- *
473
- * `org_role` is one of `super_admin, admin, billing, analytics, developer,
474
- * viewer` (or a project-defined custom RBAC key). Service accounts emit
475
- * only their configured binding role ∈ `{admin, developer, viewer}`.
476
- * `owner` does not exist and is never emitted.
477
- */
478
- org_id?: string;
479
- org_slug?: string;
480
- org_role?: string;
481
- /**
482
- * RFC 7800 confirmation claim — present when the token is sender-
483
- * constrained (DPoP-bound, RFC 9449). `cnf.jkt` is the SHA-256 thumbprint
484
- * of the client's DPoP public key. Resource servers enforcing DPoP MUST
485
- * validate the inbound `DPoP` proof against this thumbprint. Narrowed to
486
- * `{ jkt? }` — never trust an unparsed claim shape.
487
- */
488
- cnf?: {
489
- jkt?: string;
490
- };
491
- iat: number;
492
- exp: number;
493
- }
494
-
495
- /**
496
- * API Key Validation — Single Source of Truth
497
- *
498
- * OAuth 2.0 standard key validation for Sylphx Platform.
499
- * ALL key validation, sanitization, and environment detection logic lives here.
500
- *
501
- * Principles:
502
- * 1. Fail fast - Invalid input rejected immediately with clear errors
503
- * 2. Helpful errors - Tell users exactly what's wrong and how to fix it
504
- * 3. Development warnings - Warn about issues that would fail in production
505
- * 4. No silent fixes - Transparency over convenience (but warn + continue)
506
- * 5. Single Source of Truth - All key logic in one place
507
- *
508
- * Key Formats (ADR-055):
509
- * - Publishable key: pk_(dev|stg|prod|prev)_{32hex} — client-safe
510
- * - Secret Key: sk_(dev|stg|prod|prev)_{64hex} — server-side only
511
- * - Legacy compatibility accepts embedded-ref keys from the superseded ADR-021 path.
512
- *
513
- * Legacy Key Formats (backward-compat):
514
- * - App ID (old): app_(dev|stg|prod|prev)_[identifier] — Public identifier
515
- *
516
- * Special Internal Formats (NOT rotated):
517
- * - Console bootstrap: app_prod_platform_{slug} / sk_prod_platform_{slug}
518
- */
519
- /** Environment type derived from key prefix */
520
- type EnvironmentType = 'development' | 'staging' | 'production' | 'preview';
521
- /** Key type - publicKey (pk_*), appId (legacy app_*), or secret (sk_*) */
522
- type KeyType = 'publicKey' | 'appId' | 'secret';
523
- /** Validation result with clear error information */
524
- interface KeyValidationResult {
525
- /** Whether the key is valid (possibly after sanitization) */
526
- valid: boolean;
527
- /** The sanitized key to use (only if valid) */
528
- sanitizedKey: string;
529
- /** Detected key type */
530
- keyType?: KeyType;
531
- /** Detected environment */
532
- environment?: EnvironmentType;
533
- /** Error message if invalid */
534
- error?: string;
535
- /** Warning message if key was auto-fixed */
536
- warning?: string;
537
- /** Detected issues for debugging */
538
- issues?: string[];
539
- }
540
- /**
541
- * Validate a legacy App ID (app_*) and return detailed results.
542
- *
543
- * @deprecated Use validatePublicKey() for ADR-055 pk_* keys.
544
- *
545
- * @example
546
- * ```typescript
547
- * const result = validateAppId(process.env.NEXT_PUBLIC_SYLPHX_APP_ID)
548
- * if (!result.valid) {
549
- * throw new Error(result.error)
550
- * }
551
- * if (result.warning) {
552
- * console.warn(result.warning)
553
- * }
554
- * ```
555
- */
556
- declare function validateAppId(key: string | undefined | null): KeyValidationResult;
557
- /**
558
- * Validate and sanitize App ID, logging warnings.
559
- *
560
- * @deprecated Use validateAndSanitizePublicKey() for ADR-055 pk_* keys.
561
- * @throws Error if the key is invalid and cannot be sanitized
562
- * @returns The sanitized App ID
563
- */
564
- declare function validateAndSanitizeAppId(key: string | undefined | null): string;
565
- /**
566
- * Validate a secret key and return detailed results
567
- *
568
- * @example
569
- * ```typescript
570
- * const result = validateSecretKey('sk_prod_...')
571
- * if (!result.valid) {
572
- * throw new Error(result.error)
573
- * }
574
- * ```
575
- */
576
- declare function validateSecretKey(key: string | undefined | null): KeyValidationResult;
577
- /**
578
- * Validate and sanitize secret key, logging warnings
579
- *
580
- * @throws Error if the key is invalid and cannot be sanitized
581
- * @returns The sanitized secret key
582
- */
583
- declare function validateAndSanitizeSecretKey(key: string | undefined | null): string;
584
- /**
585
- * Detect environment type from any key (App ID or Secret Key)
586
- *
587
- * @example
588
- * ```typescript
589
- * detectEnvironment('sk_dev_abc123') // 'development'
590
- * detectEnvironment('app_prod_xyz789') // 'production'
591
- * detectEnvironment('sk_stg_qwe456') // 'staging'
592
- * ```
593
- *
594
- * @throws Error if key format is invalid
595
- */
596
- declare function detectEnvironment(key: string): EnvironmentType;
597
- /**
598
- * Check if running in development environment based on key
599
- */
600
- declare function isDevelopmentKey(key: string): boolean;
601
- /**
602
- * Check if running in production environment based on key
603
- */
604
- declare function isProductionKey(key: string): boolean;
605
- /**
606
- * Get the cookie namespace for a given secret key
607
- *
608
- * Used by auth middleware to namespace cookies per environment.
609
- * This prevents dev/staging/prod cookies from conflicting.
610
- *
611
- * @example
612
- * ```typescript
613
- * getCookieNamespace('sk_dev_abc123') // 'sylphx_dev'
614
- * getCookieNamespace('sk_prod_xyz789') // 'sylphx_prod'
615
- * ```
616
- */
617
- declare function getCookieNamespace(secretKey: string): string;
618
- /**
619
- * Detect the type of key.
620
- *
621
- * @returns 'publicKey' (pk_*), 'appId' (legacy app_*), 'secret' (sk_*), or null if unknown
622
- */
623
- declare function detectKeyType(key: string): KeyType | null;
624
- /**
625
- * Check if a key is an App ID (legacy app_* format)
626
- *
627
- * @deprecated Use isPublishableKey() to also accept new pk_* keys
628
- */
629
- declare function isAppId(key: string): boolean;
630
- /**
631
- * Check if a key is a secret key (sk_*)
632
- */
633
- declare function isSecretKey(key: string): boolean;
634
- /**
635
- * Validate any key (auto-detects type)
636
- *
637
- * Use this when you accept either App ID or Secret Key.
638
- * The function auto-detects the key type and validates accordingly.
639
- *
640
- * @example
641
- * ```typescript
642
- * const result = validateKey('sk_prod_...')
643
- * if (!result.valid) {
644
- * throw new Error(result.error)
645
- * }
646
- * const sanitizedKey = result.sanitizedKey
647
- * ```
648
- */
649
- declare function validateKey(key: string | undefined | null): KeyValidationResult;
650
- /**
651
- * Validate any key and return sanitized version (throws on error)
652
- *
653
- * Use this when you need the key value and want to throw on invalid input.
654
- */
655
- declare function validateAndSanitizeKey(key: string | undefined | null): string;
656
- /**
657
- * Check if we're in development mode (based on NODE_ENV or hostname)
658
- */
659
- declare function isDevelopmentRuntime(): boolean;
660
-
661
- /**
662
- * OAuth SDK — customer-app-facing social login (ADR-089 Phase 4a)
663
- *
664
- * Backed by `apps/runtime/src/server/runtime/routes/oauth.ts`:
665
- *
666
- * POST /oauth/authorize — initiate OAuth flow, returns provider URL
667
- *
668
- * The per-provider callback handler is a browser-side redirect endpoint
669
- * on the runtime (`GET /oauth/callback/{provider}`); SDK consumers
670
- * redirect the user to `authorizationUrl`, then receive a `code` on
671
- * their own `redirect_uri` which they exchange via `signIn()` or
672
- * `auth/login` with grant_type=authorization_code.
673
- *
674
- * PKCE is required per OAuth 2.1. Callers MUST generate `code_verifier`
675
- * + `code_challenge` and persist the verifier in session / cookie for
676
- * the subsequent token exchange — this SDK does not retain state.
677
- *
678
- * ## Distinction from `auth.oauth`
679
- *
680
- * `auth.oauth.*` (from `./auth`) targets platform-plane admin mint
681
- * (`/auth/platform-jwt/mint`) used by Console / CLI. The functions
682
- * here target the customer-app social-login flow.
683
- */
684
-
685
- type OAuthProvider = OAuthProviderId | (string & {});
686
-
687
- /**
688
- * Functions Client — suite door client (honesty-first)
689
- *
690
- * **Market pack:** first-class forever (never delete). Suite doors are product-native
691
- * (postgres catalog + edge invoke) under hard cutover.
692
- * **Commercial OCI GA grade:** still `commercial_ga=false` until plane A dens-live.
693
- * Do not market plane A commercial GA as shipped; do not treat dens-dark as success.
694
- *
695
- * Planes (do not conflate) — see
696
- * `docs/migration/FUNCTIONS-OCI-COMMERCIAL-SSOT.md` and
697
- * `docs/catalog/baas/functions.md`:
698
- * - **A (commercial residual):** customer OCI image → project-isolated Knative Serving
699
- * - **B:** product web Knative scaleToZero (not Functions BaaS)
700
- * - **C:** historical monorepo dens hard-cut dark (retired as product terminal)
701
- * - **D:** Edge Runtime invoke implementation (product path; not commercial OCI GA)
702
- * - **E:** product-native postgres catalog + edge invoke (current suite doors)
703
- *
704
- * ## Product API (hard cutover ON)
705
- *
706
- * Deploy/list/get/delete/logs/invoke are product doors. Commercial OCI GA remains
707
- * residual grade only — not permission to delete the pack.
708
- *
709
- * ```typescript
710
- * // Deploy programmatically from trusted server-side tooling (dev residual)
711
- * import { createConfig, FunctionsClient } from '@sylphx/sdk'
712
- *
713
- * const config = createConfig({ secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey! })
714
- *
715
- * await FunctionsClient.deploy(config, {
716
- * name: 'hello-world',
717
- * code: `export default async (req) => Response.json({ ok: true })`,
718
- * })
719
- * ```
720
- *
721
- * ## Constraints (preview residual when enabled)
722
- *
723
- * - Memory: 150 MB default (max 512 MB)
724
- * - Timeout: 30s default (max 120s)
725
- * - Source-body deploy residual is not customer OCI commercial admission
726
- */
727
-
728
- type FunctionStatus = 'active' | 'deploying' | 'failed' | 'disabled';
729
- type FunctionRuntime = 'deno';
730
- interface FunctionDeployOptions {
731
- /**
732
- * Function slug — URL-safe name (lowercase kebab-case).
733
- * Used in the invocation URL: /functions/{name}
734
- */
735
- name: string;
736
- /**
737
- * TypeScript/JavaScript source code.
738
- * Must export a default handler function:
739
- * export default async function(req: Request): Promise<Response> { ... }
740
- *
741
- * For larger bundles, use a production-backed deployment workflow that
742
- * uploads source as an artifact instead of embedding it in JSON.
743
- */
744
- code: string;
745
- /** Human-readable display name */
746
- displayName?: string;
747
- /** Short description shown in console */
748
- description?: string;
749
- /** Memory limit in MB (default: 150, max: 512) */
750
- memoryMb?: number;
751
- /** Execution timeout in seconds (default: 30, max: 120) */
752
- timeoutSeconds?: number;
753
- /** Per-function env var overrides (merged with project env vars) */
754
- envVars?: Record<string, string>;
755
- /** Whether invocations require Sylphx platform auth (default: false) */
756
- requireAuth?: boolean;
757
- /** Target environment slug (default: 'production') */
758
- environment?: string;
759
- }
760
- interface FunctionRecord {
761
- id: string;
762
- name: string;
763
- displayName: string | null;
764
- description: string | null;
765
- status: FunctionStatus;
766
- version: number;
767
- runtime: FunctionRuntime;
768
- memoryMb: number;
769
- timeoutSeconds: number;
770
- requireAuth: boolean;
771
- invocationCount: number;
772
- errorCount: number;
773
- lastInvokedAt: string | null;
774
- /** Invocation URL */
775
- url: string;
776
- createdAt: string;
777
- updatedAt: string;
778
- }
779
- interface FunctionDeployResult {
780
- id: string;
781
- name: string;
782
- version: number;
783
- status: FunctionStatus;
784
- /** The live invocation URL */
785
- url: string;
786
- }
787
- interface FunctionInvokeOptions {
788
- /** HTTP method (default: POST) */
789
- method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
790
- /** Request headers */
791
- headers?: Record<string, string>;
792
- /** Request body (JSON-serialized automatically) */
793
- body?: unknown;
794
- /** Query parameters appended to the URL */
795
- query?: Record<string, string>;
796
- }
797
- interface FunctionListOptions {
798
- /** Filter by status */
799
- status?: FunctionStatus;
800
- /** Environment slug (default: 'production') */
801
- environment?: string;
802
- /** Max results (default: 50) */
803
- limit?: number;
804
- }
805
- interface FunctionLogsOptions {
806
- /** Maximum log entries to return (default: 100) */
807
- limit?: number;
808
- /** Only return errors */
809
- errorsOnly?: boolean;
810
- /** ISO timestamp — only logs after this time */
811
- since?: string;
812
- }
813
- interface FunctionLogEntry {
814
- id: string;
815
- status: 'success' | 'error' | 'timeout';
816
- statusCode: number | null;
817
- durationMs: number | null;
818
- method: string;
819
- path: string | null;
820
- errorMessage: string | null;
821
- createdAt: string;
822
- }
823
- declare const FunctionsClient: {
824
- /**
825
- * Deploy (create or update) a function.
826
- *
827
- * If a function with the same name already exists, it is updated
828
- * (version number incremented, code replaced atomically).
829
- *
830
- * @example
831
- * ```typescript
832
- * const fn = await FunctionsClient.deploy(config, {
833
- * name: 'send-webhook',
834
- * code: `
835
- * export default async (req: Request) => {
836
- * const body = await req.json()
837
- * await fetch(body.url, { method: 'POST', body: JSON.stringify(body.payload) })
838
- * return Response.json({ ok: true })
839
- * }
840
- * `,
841
- * timeoutSeconds: 10,
842
- * })
843
- * console.log('Deployed:', fn.url)
844
- * ```
845
- */
846
- readonly deploy: (config: SylphxConfig, options: FunctionDeployOptions) => Promise<FunctionDeployResult>;
847
- /**
848
- * Get a function by name.
849
- */
850
- readonly get: (config: SylphxConfig, name: string) => Promise<FunctionRecord>;
851
- /**
852
- * List all functions for this project.
853
- */
854
- readonly list: (config: SylphxConfig, options?: FunctionListOptions) => Promise<FunctionRecord[]>;
855
- /**
856
- * Delete a function permanently.
857
- */
858
- readonly delete: (config: SylphxConfig, name: string) => Promise<void>;
859
- /**
860
- * Invoke a function from server-side code.
861
- *
862
- * For client-side invocations, call the function URL directly via fetch().
863
- *
864
- * @example
865
- * ```typescript
866
- * const result = await FunctionsClient.invoke(config, 'process-order', {
867
- * body: { orderId: '123', userId: 'user_abc' },
868
- * })
869
- * ```
870
- */
871
- readonly invoke: <T = unknown>(config: SylphxConfig, name: string, body?: unknown, options?: FunctionInvokeOptions) => Promise<T>;
872
- /**
873
- * Retrieve recent invocation logs for a function.
874
- *
875
- * @example
876
- * ```typescript
877
- * const logs = await FunctionsClient.logs(config, 'send-webhook', { errorsOnly: true })
878
- * for (const entry of logs) {
879
- * console.log(`${entry.status} ${entry.durationMs}ms`, entry.errorMessage)
880
- * }
881
- * ```
882
- */
883
- readonly logs: (config: SylphxConfig, name: string, options?: FunctionLogsOptions) => Promise<FunctionLogEntry[]>;
884
- };
885
-
886
- /**
887
- * Platform ID utilities for the Sylphx SDK
888
- *
889
- * Converts between raw UUIDs (used internally / in JWT sub claims) and
890
- * prefixed TypeID strings (used in all API responses and JWT pid claims).
891
- *
892
- * Uses TypeID spec v0.3.0 (Crockford base32, case-insensitive).
893
- * Also accepts legacy base58 format for backward compatibility.
894
- *
895
- * No external dependencies — pure TypeScript implementation of Crockford base32.
896
- *
897
- * @example
898
- * ```ts
899
- * import { encodeUserId, decodeUserId } from '@sylphx/sdk/nextjs'
900
- *
901
- * const prefixed = encodeUserId('018f4a3b-1c2d-7000-9abc-def012345678')
902
- * // => 'user_01h2xcejqtf2nbrexx3vqjhp41'
903
- *
904
- * const uuid = decodeUserId('user_01h2xcejqtf2nbrexx3vqjhp41')
905
- * // => '018f4a3b-1c2d-7000-9abc-def012345678'
906
- * ```
907
- */
908
- /**
909
- * Encode a raw UUID as a prefixed TypeID user ID.
910
- *
911
- * @param uuid - Raw UUID string (with or without dashes)
912
- * @returns Prefixed TypeID: `user_<crockford_base32>`
913
- */
914
- declare function encodeUserId(uuid: string): string;
915
- /**
916
- * Decode a prefixed user ID back to a raw UUID.
917
- * Accepts both TypeID (current) and base58 (legacy) formats.
918
- *
919
- * @param prefixedId - Prefixed user ID: `user_<encoded>`
920
- * @returns Raw UUID string, or null if invalid
921
- */
922
- declare function decodeUserId(prefixedId: string): string | null;
923
-
924
- /**
925
- * Server-side AI Client
926
- *
927
- * Creates an OpenAI-compatible client configured for Sylphx Platform.
928
- * Use this in Server Components, API routes, and server actions.
929
- *
930
- * @example
931
- * ```ts
932
- * import { createAI } from '@sylphx/platform-sdk/server'
933
- *
934
- * const ai = createAI()
935
- *
936
- * // Chat completion
937
- * const response = await ai.chat({
938
- * model: 'anthropic/claude-3.5-sonnet',
939
- * messages: [{ role: 'user', content: 'Hello!' }],
940
- * })
941
- *
942
- * // Embeddings
943
- * const embeddings = await ai.embed({
944
- * model: 'openai/text-embedding-3-small',
945
- * input: 'Hello world',
946
- * })
947
- *
948
- * // Streaming
949
- * const stream = await ai.chat({
950
- * model: 'anthropic/claude-3.5-sonnet',
951
- * messages: [{ role: 'user', content: 'Tell me a story' }],
952
- * stream: true,
953
- * })
954
- *
955
- * for await (const chunk of stream) {
956
- * process.stdout.write(chunk.choices[0]?.delta?.content || '')
957
- * }
958
- * ```
959
- */
960
- interface AIClientOptions {
961
- /** Server connection URL. Defaults to SYLPHX_SECRET_URL. */
962
- secretUrl?: string;
963
- /** @deprecated Use secretUrl. */
964
- secretKey?: string;
965
- /** Platform URL (default: https://api.sylphx.com) */
966
- platformUrl?: string;
967
- }
968
-
969
- interface ChatCompletionTool {
970
- type?: 'function';
971
- function: {
972
- name: string;
973
- description?: string;
974
- parameters?: Record<string, unknown>;
975
- };
976
- }
977
- type ChatCompletionToolChoice = 'auto' | 'none' | 'required' | {
978
- type: 'function';
979
- function: {
980
- name: string;
981
- };
982
- };
983
- interface ChatCompletionToolCall {
984
- id: string;
985
- type?: 'function';
986
- function: {
987
- name: string;
988
- arguments: string;
989
- };
990
- }
991
- interface ChatCompletionOptions {
992
- model: string;
993
- messages: ChatMessage[];
994
- temperature?: number;
995
- max_tokens?: number;
996
- top_p?: number;
997
- frequency_penalty?: number;
998
- presence_penalty?: number;
999
- stop?: string | string[];
1000
- stream?: false;
1001
- tools?: ChatCompletionTool[];
1002
- tool_choice?: ChatCompletionToolChoice;
1003
- user?: string;
1004
- }
1005
- interface ChatCompletionStreamOptions extends Omit<ChatCompletionOptions, 'stream'> {
1006
- stream: true;
1007
- }
1008
- interface ChatCompletionResponse {
1009
- id: string;
1010
- object: 'chat.completion';
1011
- created: number;
1012
- model: string;
1013
- choices: Array<{
1014
- index: number;
1015
- message: {
1016
- role: 'assistant';
1017
- content: string;
1018
- tool_calls?: ChatCompletionToolCall[];
1019
- };
1020
- finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
1021
- }>;
1022
- usage: {
1023
- prompt_tokens: number;
1024
- completion_tokens: number;
1025
- total_tokens: number;
1026
- };
1027
- }
1028
- interface ChatCompletionChunk {
1029
- id: string;
1030
- object: 'chat.completion.chunk';
1031
- created: number;
1032
- model: string;
1033
- choices: Array<{
1034
- index: number;
1035
- delta: {
1036
- role?: 'assistant';
1037
- content?: string;
1038
- tool_calls?: Array<{
1039
- index: number;
1040
- id?: string;
1041
- type?: 'function';
1042
- function?: {
1043
- name?: string;
1044
- arguments?: string;
1045
- };
1046
- }>;
1047
- };
1048
- finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
1049
- }>;
1050
- }
1051
- interface EmbeddingOptions {
1052
- model: string;
1053
- input: string | string[];
1054
- dimensions?: number;
1055
- user?: string;
1056
- }
1057
- interface EmbeddingResponse {
1058
- object: 'list';
1059
- data: Array<{
1060
- object: 'embedding';
1061
- index: number;
1062
- embedding: number[];
1063
- }>;
1064
- model: string;
1065
- usage: {
1066
- prompt_tokens: number;
1067
- total_tokens: number;
1068
- };
1069
- }
1070
- interface ModelInfo {
1071
- id: string;
1072
- name: string;
1073
- context_length: number;
1074
- pricing: {
1075
- prompt: string;
1076
- completion: string;
1077
- };
1078
- capabilities: string[];
1079
- }
1080
- interface ModelsResponse {
1081
- object: 'list';
1082
- data: ModelInfo[];
1083
- }
1084
- interface AIClient {
1085
- /** Create a chat completion */
1086
- chat(options: ChatCompletionOptions): Promise<ChatCompletionResponse>;
1087
- /** Create a streaming chat completion */
1088
- chat(options: ChatCompletionStreamOptions): Promise<AsyncIterable<ChatCompletionChunk>>;
1089
- /** Create embeddings */
1090
- embed(options: EmbeddingOptions): Promise<EmbeddingResponse>;
1091
- /** List available models */
1092
- listModels(options?: {
1093
- capability?: string;
1094
- search?: string;
1095
- }): Promise<ModelsResponse>;
1096
- }
1097
- /**
1098
- * Create a server-side AI client
1099
- *
1100
- * Uses environment variables by default:
1101
- *
1102
- * - SYLPHX_SECRET_URL: Your app's server connection URL
1103
- */
1104
- declare function createAI(options?: AIClientOptions): AIClient;
1105
- /**
1106
- * Get the default AI client (singleton)
1107
- * Creates one using environment variables on first call
1108
- */
1109
- declare function getAI(): AIClient;
1110
-
1111
- /**
1112
- * KV (Key-Value Store) Types
1113
- *
1114
- * Shared type definitions for KV operations.
1115
- * Used by both server-side client (server/kv.ts) and React hooks (react/hooks/use-kv.ts).
1116
- *
1117
- * Single Source of Truth — never duplicate these types.
1118
- */
1119
- /** TTL options for SET operations */
1120
- interface KvSetOptions {
1121
- /** Expire time in seconds */
1122
- ex?: number;
1123
- /** Expire time in milliseconds */
1124
- px?: number;
1125
- /** Unix timestamp (seconds) at which the key will expire */
1126
- exat?: number;
1127
- /** Unix timestamp (milliseconds) at which the key will expire */
1128
- pxat?: number;
1129
- /** Only set the key if it does not already exist */
1130
- nx?: boolean;
1131
- /** Only set the key if it already exists */
1132
- xx?: boolean;
1133
- }
1134
- /** Rate limit result */
1135
- interface KvRateLimitResult {
1136
- /** Whether the request is allowed (under rate limit) */
1137
- success: boolean;
1138
- /** The rate limit maximum */
1139
- limit: number;
1140
- /** Remaining requests in current window */
1141
- remaining: number;
1142
- /** Unix timestamp (ms) when the rate limit resets */
1143
- reset: number;
1144
- }
1145
- /** Sorted set member */
1146
- interface KvZMember {
1147
- /** Member identifier */
1148
- member: string;
1149
- /** Score for ranking */
1150
- score?: number;
1151
- }
1152
-
1153
- /**
1154
- * Server-side KV (Key-Value Store) Client
1155
- *
1156
- * Creates a client for managed key-value operations.
1157
- * Use this in Server Components, API routes, and server actions.
1158
- *
1159
- * @example
1160
- * ```ts
1161
- * import { createKv } from '@sylphx/sdk/server'
1162
- *
1163
- * const kv = createKv()
1164
- *
1165
- * // Basic operations
1166
- * await kv.set('user:123:profile', { name: 'John' }, { ex: 3600 })
1167
- * const profile = await kv.get('user:123:profile')
1168
- *
1169
- * // Atomic counter
1170
- * const views = await kv.incr('page:home:views')
1171
- *
1172
- * // Rate limiting
1173
- * const { success, remaining } = await kv.ratelimit('api:user123', {
1174
- * limit: 100,
1175
- * window: '1h',
1176
- * })
1177
- * ```
1178
- */
1179
-
1180
- interface KvClientOptions {
1181
- /** Server connection URL. Defaults to SYLPHX_SECRET_URL. */
1182
- secretUrl?: string;
1183
- /** @deprecated Use secretUrl. */
1184
- secretKey?: string;
1185
- /** Platform URL (default: https://api.sylphx.com) */
1186
- platformUrl?: string;
1187
- }
1188
- interface KvClient {
1189
- /**
1190
- * Get a value by key
1191
- *
1192
- * @param key - Key name
1193
- * @returns The value, or null if not found
1194
- */
1195
- get<T = unknown>(key: string): Promise<{
1196
- value: T | null;
1197
- ttl: number | null;
1198
- }>;
1199
- /**
1200
- * Set a value
1201
- *
1202
- * @param key - Key name
1203
- * @param value - Any JSON-serializable value
1204
- * @param options - TTL and conditional options (ex, px, nx, xx)
1205
- * @returns Whether the SET was successful
1206
- */
1207
- set<T = unknown>(key: string, value: T, options?: KvSetOptions): Promise<boolean>;
1208
- /**
1209
- * Delete a key
1210
- *
1211
- * @param key - Key name
1212
- * @returns Number of keys deleted (0 or 1)
1213
- */
1214
- del(key: string): Promise<number>;
1215
- /**
1216
- * Check if a key exists
1217
- *
1218
- * @param key - Key name
1219
- * @returns Whether the key exists
1220
- */
1221
- exists(key: string): Promise<boolean>;
1222
- /**
1223
- * Get multiple values
1224
- *
1225
- * @param keys - Array of keys to get (max 100)
1226
- * @returns Map of key -> value (null if not found)
1227
- */
1228
- mget<T = unknown>(keys: string[]): Promise<Record<string, T | null>>;
1229
- /**
1230
- * Set multiple values
1231
- *
1232
- * @param entries - Array of { key, value } pairs (max 100)
1233
- * @param options - TTL options (ex or px only)
1234
- */
1235
- mset<T = unknown>(entries: Array<{
1236
- key: string;
1237
- value: T;
1238
- }>, options?: Pick<KvSetOptions, 'ex' | 'px'>): Promise<void>;
1239
- /**
1240
- * Increment a numeric value atomically
1241
- *
1242
- * Creates key with value 0 if it does not exist.
1243
- *
1244
- * @param key - Key name
1245
- * @param by - Amount to increment by (default: 1, use negative for decrement)
1246
- * @returns The value after increment
1247
- */
1248
- incr(key: string, by?: number): Promise<number>;
1249
- /**
1250
- * Set key expiration
1251
- *
1252
- * @param key - Key name
1253
- * @param ex - TTL in seconds
1254
- * @returns Whether the TTL was set (false if key does not exist)
1255
- */
1256
- expire(key: string, ex: number): Promise<boolean>;
1257
- /**
1258
- * Check rate limit using sliding window algorithm
1259
- *
1260
- * @param key - Rate limit identifier (e.g., "api:user123")
1261
- * @param options - Limit and window configuration
1262
- * @returns Rate limit status
1263
- *
1264
- * @example
1265
- * ```ts
1266
- * const { success, remaining, reset } = await kv.ratelimit('api:user123', {
1267
- * limit: 100,
1268
- * window: '1h',
1269
- * })
1270
- *
1271
- * if (!success) {
1272
- * throw new Error('Rate limit exceeded')
1273
- * }
1274
- * ```
1275
- */
1276
- ratelimit(key: string, options: {
1277
- limit: number;
1278
- window: string;
1279
- }): Promise<KvRateLimitResult>;
1280
- /**
1281
- * Set hash fields
1282
- *
1283
- * @param key - Hash key
1284
- * @param fields - Field-value pairs to set
1285
- * @returns Number of fields that were created (not updated)
1286
- */
1287
- hset<T = unknown>(key: string, fields: Record<string, T>): Promise<number>;
1288
- /**
1289
- * Get a hash field
1290
- *
1291
- * @param key - Hash key
1292
- * @param field - Field name
1293
- * @returns Field value, or null if not found
1294
- */
1295
- hget<T = unknown>(key: string, field: string): Promise<T | null>;
1296
- /**
1297
- * Get all hash fields
1298
- *
1299
- * @param key - Hash key
1300
- * @returns All field-value pairs, or null if key does not exist
1301
- */
1302
- hgetall<T = unknown>(key: string): Promise<Record<string, T> | null>;
1303
- /**
1304
- * Push values to the left of a list
1305
- *
1306
- * @param key - List key
1307
- * @param values - Values to push
1308
- * @returns Length of the list after push
1309
- */
1310
- lpush<T = unknown>(key: string, ...values: T[]): Promise<number>;
1311
- /**
1312
- * Get a range of elements from a list
1313
- *
1314
- * @param key - List key
1315
- * @param start - Start index (0-based, negative for from end)
1316
- * @param stop - Stop index (inclusive, -1 for end)
1317
- * @returns Values in the specified range
1318
- */
1319
- lrange<T = unknown>(key: string, start?: number, stop?: number): Promise<T[]>;
1320
- /**
1321
- * Add members with scores to a sorted set
1322
- *
1323
- * @param key - Sorted set key
1324
- * @param members - Score-member pairs
1325
- * @returns Number of members added (not updated)
1326
- */
1327
- zadd(key: string, ...members: Array<{
1328
- score: number;
1329
- member: string;
1330
- }>): Promise<number>;
1331
- /**
1332
- * Get members from a sorted set by rank range
1333
- *
1334
- * @param key - Sorted set key
1335
- * @param start - Start rank (0-based)
1336
- * @param stop - Stop rank (inclusive)
1337
- * @param options - Include scores and/or reverse order
1338
- * @returns Members in the specified range
1339
- */
1340
- zrange(key: string, start?: number, stop?: number, options?: {
1341
- withScores?: boolean;
1342
- rev?: boolean;
1343
- }): Promise<KvZMember[]>;
1344
- }
1345
- /**
1346
- * Create a server-side KV client
1347
- *
1348
- * Uses environment variables by default:
1349
- * - SYLPHX_SECRET_URL: Your app's server connection URL
1350
- */
1351
- declare function createKv(options?: KvClientOptions): KvClient;
1352
- /**
1353
- * Get the default KV client (singleton)
1354
- * Creates one using environment variables on first call
1355
- */
1356
- declare function getKv(): KvClient;
1357
-
1358
- /**
1359
- * Shared Realtime Types
1360
- *
1361
- * Single source of truth for types used by both:
1362
- * - Server: streams.ts (createStreams)
1363
- * - React: use-realtime.ts (useRealtime hook)
1364
- */
1365
- /** A message from a stream */
1366
- interface StreamMessage<T = unknown> {
1367
- /** Stream entry ID (e.g., "1234567890-0") */
1368
- id: string;
1369
- /** Event type */
1370
- event: string;
1371
- /** Channel the message was sent to */
1372
- channel: string;
1373
- /** Event data */
1374
- data: T;
1375
- /** Unix timestamp in milliseconds */
1376
- timestamp?: number;
1377
- }
1378
-
1379
- /**
1380
- * Server-side Streams Client
1381
- *
1382
- * Creates a client for managed real-time pub/sub.
1383
- * Use this in Server Components, API routes, and server actions.
1384
- *
1385
- * @example
1386
- * ```ts
1387
- * import { createStreams } from '@sylphx/sdk/server'
1388
- *
1389
- * const streams = createStreams()
1390
- *
1391
- * // Emit an event
1392
- * const id = await streams.emit('chat:room-1', 'message', {
1393
- * text: 'Hello!',
1394
- * userId: '123',
1395
- * })
1396
- *
1397
- * // Get message history
1398
- * const messages = await streams.history('chat:room-1', { limit: 50 })
1399
- *
1400
- * // Using channel helper
1401
- * const room = streams.channel('chat:room-1')
1402
- * await room.emit('message', { text: 'Hello!' })
1403
- * const history = await room.history({ limit: 50 })
1404
- * ```
1405
- */
1406
-
1407
- interface StreamsClientOptions {
1408
- /** Server connection URL. Defaults to SYLPHX_SECRET_URL. */
1409
- secretUrl?: string;
1410
- /** @deprecated Use secretUrl. */
1411
- secretKey?: string;
1412
- /** Platform URL (default: https://api.sylphx.com) */
1413
- platformUrl?: string;
1414
- }
1415
- /** Options for fetching stream history */
1416
- interface StreamHistoryOptions {
1417
- /** Start ID ("-" for oldest) */
1418
- start?: string;
1419
- /** End ID ("+" for newest) */
1420
- end?: string;
1421
- /** Maximum number of messages (max 1000) */
1422
- limit?: number;
1423
- }
1424
- /** Helper for a specific channel */
1425
- interface ChannelHelper {
1426
- /** Emit an event to this channel */
1427
- emit<T>(event: string, data: T): Promise<string>;
1428
- /** Get message history for this channel */
1429
- history<T>(options?: StreamHistoryOptions): Promise<StreamMessage<T>[]>;
1430
- }
1431
- interface StreamsClient {
1432
- /**
1433
- * Emit an event to a channel
1434
- *
1435
- * @param channel - Channel name (e.g., "chat:room-1")
1436
- * @param event - Event type (e.g., "message")
1437
- * @param data - Event data (any JSON-serializable value)
1438
- * @returns Stream entry ID
1439
- */
1440
- emit<T>(channel: string, event: string, data: T): Promise<string>;
1441
- /**
1442
- * Get message history for a channel
1443
- *
1444
- * @param channel - Channel name
1445
- * @param options - History options (start, end, limit)
1446
- * @returns Array of messages in chronological order
1447
- */
1448
- history<T>(channel: string, options?: StreamHistoryOptions): Promise<StreamMessage<T>[]>;
1449
- /**
1450
- * Get a channel helper for convenient operations
1451
- *
1452
- * @param channel - Channel name
1453
- * @returns Channel helper with emit() and history()
1454
- */
1455
- channel(name: string): ChannelHelper;
1456
- }
1457
- /**
1458
- * Create a server-side Streams client
1459
- *
1460
- * Uses environment variables by default:
1461
- *
1462
- * - SYLPHX_SECRET_URL: Your app's server connection URL
1463
- */
1464
- declare function createStreams(options?: StreamsClientOptions): StreamsClient;
1465
- /**
1466
- * Get the default Streams client (singleton)
1467
- * Creates one using environment variables on first call
1468
- */
1469
- declare function getStreams(): StreamsClient;
1470
-
1471
- /**
1472
- * Sylphx Server SDK
1473
- *
1474
- * @privilege-asymmetry:O-5 — re-exports Customer Zero identity predicate;
1475
- * see docs/catalog/subsystems/privilege-asymmetry.md §3.2.
1476
- *
1477
- * Server-side operations using REST API for type safety.
1478
- * Uses connection URL (sylphx://sk_*@tenant-slug.api.sylphx.com) for authentication.
1479
- *
1480
- * @example
1481
- * ```typescript
1482
- * import { createServerClient, verifyWebhook } from '@sylphx/sdk/server'
1483
- *
1484
- * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
1485
- * const client = createServerRestClient({
1486
- * secretKey: sylphx.secretKey!,
1487
- * platformUrl: sylphx.baseUrl.replace(/\/v1$/, ''),
1488
- * })
1489
- *
1490
- * // REST API calls
1491
- * const { data: plans } = await client.GET('/billing/plans')
1492
- * const { data: user } = await client.GET('/user/profile')
1493
- * ```
1494
- */
1495
-
1496
- declare const PLATFORM_TENANT_BAAS_URL = "https://keen-wave-x3m9p2.api.sylphx.com/v1";
1497
- interface PlatformBaasUrlEnv {
1498
- readonly [key: string]: string | undefined;
1499
- readonly SYLPHX_BAAS_URL?: string;
1500
- readonly SYLPHX_URL?: string;
1501
- readonly SYLPHX_RUNTIME_URL?: string;
1502
- }
1503
- declare function resolvePlatformBaasUrl(env?: PlatformBaasUrlEnv): string;
1504
- interface ServerConfig {
1505
- /**
1506
- * Your Secret Key (keep secure, server-only)
1507
- *
1508
- * The secret key IS the app identity — no separate app ID needed.
1509
- * Use environment-specific keys for proper isolation:
1510
- * - Development: sk_dev_xxx (relaxed rate limits, test mode)
1511
- * - Staging: sk_stg_xxx (test mode, production-like settings)
1512
- * - Production: sk_prod_xxx (strict settings, live data)
1513
- */
1514
- secretKey: string;
1515
- /** Platform URL (defaults to https://sylphx.com) */
1516
- platformUrl?: string;
1517
- /** Optional cache TTL in seconds. Default: 60 */
1518
- revalidate?: number;
1519
- }
1520
- /**
1521
- * Create a Server REST Client for type-safe API calls.
1522
- *
1523
- * For the new connection URL API, use `createServerClient()` from '@sylphx/sdk'.
1524
- * This function creates an openapi-fetch REST client from a raw secret key.
1525
- *
1526
- * @example
1527
- * ```typescript
1528
- * const client = createServerRestClient({
1529
- * secretKey: 'sk_prod_...',
1530
- * })
1531
- *
1532
- * const { data: plans } = await client.GET('/billing/plans')
1533
- * ```
1534
- */
1535
- declare function createServerRestClient(config: ServerConfig): RestClient;
1536
- /**
1537
- * Create a Server REST Client with user context (access token)
1538
- */
1539
- declare function createAuthenticatedServerClient(config: ServerConfig, accessToken: string): RestClient;
1540
- /**
1541
- * Canonical JWT `iss` for Platform-minted access tokens.
1542
- * Matches `packages/core` `JWT_ISSUER` production fallback (`https://sylphx.com`).
1543
- * Not the tenant BaaS routing host (`{slug}.api.sylphx.com`).
1544
- */
1545
- declare const DEFAULT_JWT_ISSUER = "https://sylphx.com";
1546
- /** Public JWKS path on the issuer origin (not tenant BaaS; tenant JWKS requires app secret). */
1547
- declare const JWT_JWKS_PATH = "/api/v1/auth/.well-known/jwks.json";
1548
- /**
1549
- * Reset the JWKS cache.
1550
- *
1551
- * Use in tests to prevent state bleed between test cases.
1552
- * In production, the cache auto-expires after JWK_CACHE_TTL_MS (1 hour).
1553
- *
1554
- * @example
1555
- * ```typescript
1556
- * afterEach(() => resetJwksCache())
1557
- * ```
1558
- */
1559
- declare function resetJwksCache(): void;
1560
- /**
1561
- * Resolve the JWT issuer origin used for `iss` pin + JWKS fetch.
1562
- * `SYLPHX_JWT_ISSUER` overrides for non-prod / dedicated issuer hosts.
1563
- */
1564
- declare function resolveJwtIssuer(explicit?: string): string;
1565
- /**
1566
- * Fetch JWKS from the **issuer** origin (canonical Platform JWT contract).
1567
- *
1568
- * Do not pass a tenant BaaS routing URL (`{slug}.api.sylphx.com`): that host
1569
- * requires `x-app-secret` on JWKS and is not the JWT issuer.
1570
- *
1571
- * @param issuer - JWT issuer origin (default {@link DEFAULT_JWT_ISSUER})
1572
- */
1573
- declare function getJwks(issuer?: string): Promise<JsonWebKey[]>;
1574
- /**
1575
- * Verify an access token from the platform.
1576
- *
1577
- * Verifies RS256 signature against issuer JWKS, pins `iss` to the canonical
1578
- * JWT issuer (not the tenant BaaS host), and **requires** `audience`.
1579
- *
1580
- * ## Issuer vs routing URL
1581
- *
1582
- * Tokens are minted with `iss = JWT_ISSUER` (`https://sylphx.com` in prod).
1583
- * `platformUrl` is the BaaS routing target only; it must never be used as
1584
- * `iss` or as the JWKS origin (tenant hosts return 401 on public JWKS).
1585
- *
1586
- * ## Audience
1587
- *
1588
- * Platform-issued project tokens carry `aud === app.slug` (and Platform-app
1589
- * tokens use `aud === 'platform'` — ADR-2062). Audience is mandatory:
1590
- * omitting it is a fail-open trap and is rejected.
1591
- *
1592
- * @example
1593
- * ```typescript
1594
- * import { verifyAccessToken } from '@sylphx/sdk/server'
1595
- *
1596
- * const claims = await verifyAccessToken(bearer, {
1597
- * audience: 'your-app-slug',
1598
- * // optional: issuer defaults to https://sylphx.com
1599
- * })
1600
- * if (claims.org_id !== resource.orgId) throw new Error('cross-org access')
1601
- * ```
1602
- */
1603
- declare function verifyAccessToken(token: string, options: {
1604
- secretKey?: string;
1605
- /**
1606
- * @deprecated Not used for issuer or JWKS. Kept for call-site
1607
- * compatibility; pass {@link issuer} / {@link audience} instead.
1608
- */
1609
- platformUrl?: string;
1610
- /** JWT issuer origin. Defaults to {@link DEFAULT_JWT_ISSUER}. */
1611
- issuer?: string;
1612
- /**
1613
- * Expected `aud` claim (project slug or `'platform'`). Required —
1614
- * tokens for other audiences are rejected even when signature is valid.
1615
- */
1616
- audience: string | string[];
1617
- }): Promise<AccessTokenPayload>;
1618
- interface WebhookPayload {
1619
- event: string;
1620
- data: unknown;
1621
- timestamp: number;
1622
- id: string;
1623
- }
1624
- interface WebhookVerifyResult {
1625
- valid: boolean;
1626
- payload?: WebhookPayload;
1627
- error?: string;
1628
- }
1629
- interface WebhookVerifyOptions {
1630
- /** Maximum age of webhook in milliseconds (default: 5 minutes) */
1631
- maxAge?: number;
1632
- /** Allow clock skew in milliseconds (default: 30 seconds) */
1633
- clockSkew?: number;
1634
- }
1635
- /**
1636
- * Verify webhook signature from Sylphx Platform
1637
- *
1638
- * The platform sends `X-Webhook-Signature` in `t={unix_seconds},v1={hmac_hex}`
1639
- * format. This function accepts either:
1640
- * - The raw header value (auto-parsed)
1641
- * - Pre-extracted `signature` + `timestamp` strings
1642
- *
1643
- * @example
1644
- * ```typescript
1645
- * import { verifyWebhook } from '@sylphx/sdk/server'
1646
- *
1647
- * export async function POST(request: Request) {
1648
- * const body = await request.text()
1649
- * const result = await verifyWebhook({
1650
- * payload: body,
1651
- * signatureHeader: request.headers.get('x-webhook-signature'),
1652
- * secret: process.env.SYLPHX_WEBHOOK_SECRET!,
1653
- * })
1654
- *
1655
- * if (!result.valid) {
1656
- * return new Response('Invalid signature', { status: 401 })
1657
- * }
1658
- *
1659
- * console.log('Received webhook:', result.payload)
1660
- * }
1661
- * ```
1662
- */
1663
- declare function verifyWebhook(options: {
1664
- payload: string;
1665
- /** Raw X-Webhook-Signature header value: "t={seconds},v1={hex}" */
1666
- signatureHeader?: string | null;
1667
- /** Pre-extracted HMAC hex (if parsing header yourself) */
1668
- signature?: string | null;
1669
- /** Pre-extracted timestamp in unix seconds (if parsing header yourself) */
1670
- timestamp?: string | null;
1671
- secret: string;
1672
- verifyOptions?: WebhookVerifyOptions;
1673
- }): Promise<WebhookVerifyResult>;
1674
- /**
1675
- * Create a webhook handler with automatic verification
1676
- *
1677
- * @example
1678
- * ```typescript
1679
- * import { createWebhookHandler } from '@sylphx/sdk/server'
1680
- *
1681
- * const handler = createWebhookHandler({
1682
- * secret: process.env.SYLPHX_WEBHOOK_SECRET!,
1683
- * handlers: {
1684
- * 'user.created': async (data) => {
1685
- * console.log('New user:', data)
1686
- * },
1687
- * 'subscription.updated': async (data) => {
1688
- * console.log('Subscription changed:', data)
1689
- * },
1690
- * },
1691
- * })
1692
- *
1693
- * export { handler as POST }
1694
- * ```
1695
- */
1696
- declare function createWebhookHandler(config: {
1697
- secret: string;
1698
- handlers: Record<string, (data: unknown) => Promise<void> | void>;
1699
- verifyOptions?: WebhookVerifyOptions;
1700
- }): (request: Request) => Promise<Response>;
1701
-
1702
- /** Common options for authenticated SDK fetch — secret key identifies the app */
1703
- interface AuthenticatedFetchOptions {
1704
- /** Secret key for authentication (sk_dev_xxx, sk_stg_xxx, sk_prod_xxx) */
1705
- secretKey: string;
1706
- /** Platform URL (defaults to https://sylphx.com) */
1707
- platformUrl?: string;
1708
- /** Optional cache TTL in seconds. Default: 60 */
1709
- revalidate?: number;
1710
- }
1711
- /**
1712
- * Options for public endpoints that only need an App ID (public key).
1713
- * The App ID IS the app identity — no separate key needed.
1714
- */
1715
- interface PublicFetchOptions {
1716
- /** App ID (app_dev_xxx, app_stg_xxx, app_prod_xxx) — identifies the app */
1717
- appId: string;
1718
- /** Platform URL (defaults to https://sylphx.com) */
1719
- platformUrl?: string;
1720
- /** Optional cache TTL in seconds. Default: 60 */
1721
- revalidate?: number;
1722
- }
1723
-
1724
- /** OAuth provider with display name */
1725
- interface OAuthProviderInfo {
1726
- id: OAuthProvider;
1727
- name: string;
1728
- }
1729
- /**
1730
- * Get enabled OAuth providers for an app (server-side)
1731
- *
1732
- * The App ID identifies the app via `X-App-Id` header.
1733
- *
1734
- * @example
1735
- * ```tsx
1736
- * const providers = await getOAuthProviders({
1737
- * appId: process.env.NEXT_PUBLIC_SYLPHX_APP_ID!,
1738
- * })
1739
- * ```
1740
- */
1741
- declare function getOAuthProviders(options: PublicFetchOptions): Promise<OAuthProvider[]>;
1742
- /**
1743
- * Get enabled OAuth providers with full info (server-side)
1744
- */
1745
- declare function getOAuthProvidersWithInfo(options: PublicFetchOptions): Promise<OAuthProviderInfo[]>;
1746
-
1747
- /**
1748
- * Get subscription plans for an app (server-side)
1749
- *
1750
- * Note: Prefer using `getAppConfig()` which fetches all config in parallel.
1751
- * This function is used internally by `getAppConfig()`.
1752
- */
1753
- declare function getPlans(options: AuthenticatedFetchOptions): Promise<Plan[]>;
1754
-
1755
- /**
1756
- * Get consent types for an app (server-side)
1757
- *
1758
- * Note: Prefer using `getAppConfig()` which fetches all config in parallel.
1759
- * This function is used internally by `getAppConfig()`.
1760
- */
1761
- declare function getConsentTypes(options: AuthenticatedFetchOptions): Promise<ConsentType[]>;
1762
- /** Feature flag definition for SSR */
1763
- interface FeatureFlagDefinition {
1764
- key: string;
1765
- name: string;
1766
- description: string | null;
1767
- enabled: boolean;
1768
- rolloutPercentage: number;
1769
- targetPremiumOnly: boolean;
1770
- targetAdminOnly: boolean;
1771
- }
1772
- /**
1773
- * Get feature flag definitions for an app (server-side)
1774
- *
1775
- * Returns flag definitions. Evaluation (rollout, targeting) happens
1776
- * client-side using the LocalEvaluator with user context.
1777
- *
1778
- * @example
1779
- * ```tsx
1780
- * import { getFeatureFlags } from '@sylphx/sdk/server'
1781
- *
1782
- * export default async function RootLayout({ children }) {
1783
- * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
1784
- * const flags = await getFeatureFlags({
1785
- * secretKey: sylphx.secretKey!,
1786
- * platformUrl: sylphx.baseUrl.replace(/\/v[0-9]+$/, ''),
1787
- * })
1788
- * return <FeatureFlagsProvider initialFlags={flags}>{children}</FeatureFlagsProvider>
1789
- * }
1790
- * ```
1791
- */
1792
- declare function getFeatureFlags(options: AuthenticatedFetchOptions): Promise<FeatureFlagDefinition[]>;
1793
- /** App metadata returned by /api/sdk/app */
1794
- interface AppMetadata {
1795
- id: string;
1796
- name: string;
1797
- slug: string;
1798
- captcha?: {
1799
- enabled: true;
1800
- provider: 'turnstile' | 'hcaptcha';
1801
- siteKey: string;
1802
- action: 'register';
1803
- };
1804
- }
1805
- /**
1806
- * Get app metadata (server-side)
1807
- *
1808
- * @internal Used by getAppConfig() - rarely called directly
1809
- */
1810
- declare function getAppMetadata(options: AuthenticatedFetchOptions): Promise<AppMetadata>;
1811
-
1812
- /**
1813
- * Options for getAppConfig()
1814
- */
1815
- interface GetAppConfigOptions {
1816
- /** Secret key for authenticated endpoints (plans, flags, consent types) */
1817
- secretKey: string;
1818
- /** App ID for public endpoints (OAuth providers) - identifies your app */
1819
- appId: string;
1820
- /** Platform URL (defaults to https://sylphx.com) */
1821
- platformUrl?: string;
1822
- /** Optional cache TTL in seconds. Default: 60 */
1823
- revalidate?: number;
1824
- }
1825
- /**
1826
- * Get complete app configuration for the SDK (server-side)
1827
- *
1828
- * This is the **recommended** way to initialize the Sylphx SDK. It fetches all
1829
- * configuration data in a single call from a Server Component, eliminating the
1830
- * need for client-side config fetching and the associated loading states.
1831
- *
1832
- * Returns:
1833
- * - plans: Subscription plans for billing
1834
- * - consentTypes: GDPR/CCPA consent configuration
1835
- * - oauthProviders: Enabled OAuth providers for auth
1836
- * - featureFlags: Feature flag definitions for client-side evaluation
1837
- * - app: App metadata (id, name, slug)
1838
- * - fetchedAt: ISO timestamp for cache debugging
1839
- *
1840
- * @example
1841
- * ```tsx
1842
- * // app/layout.tsx (Server Component)
1843
- * import { getAppConfig } from '@sylphx/sdk/server'
1844
- *
1845
- * export default async function RootLayout({ children }) {
1846
- * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
1847
- * const config = await getAppConfig({
1848
- * secretKey: sylphx.secretKey!,
1849
- * appId: process.env.NEXT_PUBLIC_SYLPHX_APP_ID!,
1850
- * platformUrl: sylphx.baseUrl.replace(/\/v[0-9]+$/, ''),
1851
- * })
1852
- *
1853
- * return (
1854
- * <html>
1855
- * <body>
1856
- * <SylphxProvider
1857
- * config={config}
1858
- * appId={process.env.NEXT_PUBLIC_SYLPHX_APP_ID!}
1859
- * >
1860
- * {children}
1861
- * </SylphxProvider>
1862
- * </body>
1863
- * </html>
1864
- * )
1865
- * }
1866
- * ```
1867
- */
1868
- declare function getAppConfig(options: GetAppConfigOptions): Promise<AppConfig>;
1869
- /** Referral leaderboard entry */
1870
- interface ReferralLeaderboardEntry {
1871
- rank: number;
1872
- userId: string;
1873
- /** Masked username for privacy */
1874
- name: string;
1875
- /** Number of successful referrals */
1876
- referrals: number;
1877
- isCurrentUser: boolean;
1878
- }
1879
- /** Referral leaderboard result */
1880
- interface ReferralLeaderboardResult {
1881
- entries: ReferralLeaderboardEntry[];
1882
- total: number;
1883
- period: 'all' | 'month' | 'week';
1884
- }
1885
- /**
1886
- * Get referral leaderboard for an app (server-side)
1887
- *
1888
- * @example
1889
- * ```tsx
1890
- * import { getReferralLeaderboard } from '@sylphx/sdk/server'
1891
- *
1892
- * export default async function ReferralsPage() {
1893
- * const leaderboard = await getReferralLeaderboard({
1894
- * secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
1895
- * limit: 10,
1896
- * period: 'month',
1897
- * })
1898
- * return <ReferralLeaderboard initialData={leaderboard} />
1899
- * }
1900
- * ```
1901
- */
1902
- declare function getReferralLeaderboard(options: AuthenticatedFetchOptions & {
1903
- limit?: number;
1904
- period?: 'all' | 'month' | 'week';
1905
- }): Promise<ReferralLeaderboardResult>;
1906
- /** Engagement leaderboard entry */
1907
- interface EngagementLeaderboardEntry {
1908
- rank: number;
1909
- userId: string;
1910
- name: string;
1911
- score: number;
1912
- isCurrentUser: boolean;
1913
- }
1914
- /** Engagement leaderboard result */
1915
- interface EngagementLeaderboardResult {
1916
- leaderboardId: string;
1917
- entries: EngagementLeaderboardEntry[];
1918
- period: string;
1919
- resetTime: string | null;
1920
- userEntry: EngagementLeaderboardEntry | null;
1921
- }
1922
- /**
1923
- * Get engagement leaderboard for an app (server-side)
1924
- *
1925
- * @example
1926
- * ```tsx
1927
- * import { getEngagementLeaderboard } from '@sylphx/sdk/server'
1928
- *
1929
- * export default async function LeaderboardPage() {
1930
- * const leaderboard = await getEngagementLeaderboard({
1931
- * secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
1932
- * leaderboardId: 'high-scores',
1933
- * })
1934
- * return <Leaderboard initialData={leaderboard} />
1935
- * }
1936
- * ```
1937
- */
1938
- declare function getEngagementLeaderboard(options: AuthenticatedFetchOptions & {
1939
- leaderboardId: string;
1940
- limit?: number;
1941
- }): Promise<EngagementLeaderboardResult>;
1942
- /** Database connection info returned by Platform */
1943
- interface DatabaseConnectionInfo {
1944
- connectionString: string;
1945
- databaseName: string;
1946
- roleName: string;
1947
- status: 'provisioning' | 'ready' | 'suspended' | 'failed' | 'deleted';
1948
- }
1949
- /** Database status info */
1950
- interface DatabaseStatusInfo {
1951
- status: 'provisioning' | 'ready' | 'suspended' | 'failed' | 'deleted' | 'not_provisioned';
1952
- region: string | null;
1953
- pgVersion: number | null;
1954
- databaseName: string | null;
1955
- }
1956
- /**
1957
- * Get database connection string from Platform (server-side)
1958
- *
1959
- * Use this when your app's database is provisioned by the Sylphx Platform.
1960
- * The connection string is securely stored on Platform and retrieved at startup.
1961
- *
1962
- * **Note:** This requires NEON_API_KEY and PLATFORM_ENCRYPTION_KEY to be
1963
- * configured on the Platform, and your app's database to be provisioned.
1964
- *
1965
- * @example
1966
- * ```typescript
1967
- * import { getDatabaseConnection } from '@sylphx/sdk/server'
1968
- *
1969
- * // In your database initialization
1970
- * const dbInfo = await getDatabaseConnection({
1971
- * secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
1972
- * })
1973
- *
1974
- * if (dbInfo) {
1975
- * const pool = new Pool({ connectionString: dbInfo.connectionString })
1976
- * }
1977
- * ```
1978
- */
1979
- declare function getDatabaseConnection(options: AuthenticatedFetchOptions): Promise<DatabaseConnectionInfo | null>;
1980
- /**
1981
- * Get database status from Platform (server-side)
1982
- *
1983
- * Use this to check if your app's database is provisioned and ready.
1984
- *
1985
- * @example
1986
- * ```typescript
1987
- * import { getDatabaseStatus } from '@sylphx/sdk/server'
1988
- *
1989
- * const status = await getDatabaseStatus({
1990
- * secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
1991
- * })
1992
- *
1993
- * if (status?.status === 'ready') {
1994
- * // Database is ready to use
1995
- * }
1996
- * ```
1997
- */
1998
- declare function getDatabaseStatus(options: AuthenticatedFetchOptions): Promise<DatabaseStatusInfo>;
1999
-
2000
- export { type AIClient, type AIClientOptions, type AppConfig, type AppMetadata, type ChannelHelper, type ChatCompletionChunk, type ChatCompletionOptions, type ChatCompletionResponse, type ChatCompletionStreamOptions, type ChatMessage, type ConsentType, DEFAULT_JWT_ISSUER, type DatabaseConnectionInfo, type DatabaseStatusInfo, type EmbeddingOptions, type EmbeddingResponse, type EngagementLeaderboardEntry, type EngagementLeaderboardResult, type EnvironmentType, type FeatureFlagDefinition, type FunctionDeployOptions, type FunctionDeployResult, type FunctionInvokeOptions, type FunctionListOptions, type FunctionLogEntry, type FunctionLogsOptions, type FunctionRecord, type FunctionRuntime, type FunctionStatus, FunctionsClient, type GetAppConfigOptions, InvalidConnectionUrlError, JWT_JWKS_PATH, type KeyType, type KeyValidationResult, type KvClient, type KvClientOptions, type KvRateLimitResult, type KvSetOptions, type KvZMember, type ModelInfo, type ModelsResponse, type OAuthProvider, type OAuthProviderInfo, PLATFORM_TENANT_BAAS_URL, type Plan, type PlatformBaasUrlEnv, type ReferralLeaderboardEntry, type ReferralLeaderboardResult, type RestClient, type RestClientConfig as ServerClientConfig, type ServerConfig, type StreamHistoryOptions, type StreamMessage, type StreamsClient, type StreamsClientOptions, type SylphxClientInput, type SylphxConfig, type WebhookPayload, type WebhookVerifyOptions, type WebhookVerifyResult, createAI, createAuthenticatedServerClient, createClient, createKv, createServerClient, createServerRestClient, createStreams, createWebhookHandler, decodeUserId, detectEnvironment, detectKeyType, encodeUserId, getAI, getAppConfig, getAppMetadata, getConsentTypes, getCookieNamespace, getDatabaseConnection, getDatabaseStatus, getEngagementLeaderboard, getFeatureFlags, getJwks, getKv, getOAuthProviders, getOAuthProvidersWithInfo, getPlans, getReferralLeaderboard, getStreams, isAppId, isDevelopmentKey, isDevelopmentRuntime, isProductionKey, isSecretKey, resetJwksCache, resolveJwtIssuer, resolvePlatformBaasUrl, validateAndSanitizeAppId, validateAndSanitizeKey, validateAndSanitizeSecretKey, validateAppId, validateKey, validateSecretKey, verifyAccessToken, verifyWebhook };