@sylphx/sdk 0.3.4 → 0.3.5
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.cts +71 -26
- package/dist/index.d.ts +71 -26
- package/dist/index.js +103 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +102 -13
- package/dist/index.mjs.map +1 -1
- package/dist/nextjs/index.js +12 -7
- package/dist/nextjs/index.js.map +1 -1
- package/dist/nextjs/index.mjs +12 -7
- package/dist/nextjs/index.mjs.map +1 -1
- package/dist/react/index.d.cts +33 -35
- package/dist/react/index.d.ts +33 -35
- package/dist/react/index.js +109 -20
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +109 -20
- package/dist/react/index.mjs.map +1 -1
- package/dist/server/index.d.cts +21 -14
- package/dist/server/index.d.ts +21 -14
- package/dist/server/index.js +17 -8
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +17 -8
- package/dist/server/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -8,6 +8,33 @@ import * as openapi_fetch from 'openapi-fetch';
|
|
|
8
8
|
*
|
|
9
9
|
* Uses appId or secretKey for authentication via x-app-secret header.
|
|
10
10
|
*/
|
|
11
|
+
/**
|
|
12
|
+
* Parsed representation of a Sylphx API key (ADR-021 format).
|
|
13
|
+
*/
|
|
14
|
+
interface ParsedKey {
|
|
15
|
+
/** Key type: 'pk' (publishable) or 'sk' (secret) */
|
|
16
|
+
type: 'pk' | 'sk';
|
|
17
|
+
/** Environment short code: 'prod', 'dev', or 'stg' */
|
|
18
|
+
env: 'prod' | 'dev' | 'stg';
|
|
19
|
+
/** 12-char project ref (base36) */
|
|
20
|
+
ref: string;
|
|
21
|
+
/** Random secret portion of the key */
|
|
22
|
+
token: string;
|
|
23
|
+
/** Whether this is a client-safe publishable key */
|
|
24
|
+
isPublic: boolean;
|
|
25
|
+
/** Pre-computed base URL for this project */
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Parse an ADR-021 API key into its component parts.
|
|
30
|
+
*
|
|
31
|
+
* Supports:
|
|
32
|
+
* pk_{env}_{ref}_{32hex} — publishable key (ADR-021)
|
|
33
|
+
* sk_{env}_{ref}_{64hex} — secret key (ADR-021)
|
|
34
|
+
*
|
|
35
|
+
* @throws SylphxError if key format is invalid or uses old app_* format
|
|
36
|
+
*/
|
|
37
|
+
declare function parseKey(key: string): ParsedKey;
|
|
11
38
|
/**
|
|
12
39
|
* SDK Configuration for Pure Functions
|
|
13
40
|
*
|
|
@@ -31,61 +58,79 @@ import * as openapi_fetch from 'openapi-fetch';
|
|
|
31
58
|
*/
|
|
32
59
|
interface SylphxConfig {
|
|
33
60
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* - Secret key (sk_dev_, sk_stg_, sk_prod_) — full access, server-side only
|
|
38
|
-
* - Publishable key (app_dev_, app_stg_, app_prod_) — limited access, safe for client
|
|
39
|
-
*
|
|
40
|
-
* Get this from Platform Console → Apps → Your App → Environments
|
|
61
|
+
* Secret key (sk_*) — full access, server-side only.
|
|
62
|
+
* Embed project ref, env, and routing info (ADR-021).
|
|
63
|
+
* Get from Platform Console → Apps → Your App → Environments.
|
|
41
64
|
*/
|
|
42
65
|
readonly secretKey?: string;
|
|
43
66
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
67
|
+
* Publishable key (pk_*) — client-safe, read-only access.
|
|
68
|
+
* Embeds project ref, env, and routing info (ADR-021).
|
|
69
|
+
* Get from Platform Console → Apps → Your App → Environments.
|
|
70
|
+
*/
|
|
71
|
+
readonly publicKey?: string;
|
|
72
|
+
/**
|
|
73
|
+
* Project ref — 12-char lowercase alphanumeric string.
|
|
74
|
+
* Extracted from the key automatically (ADR-021).
|
|
46
75
|
* The SDK targets: https://{ref}.api.sylphx.com/v1
|
|
47
|
-
*
|
|
48
|
-
* Get this from Platform Console → Projects → Your Project → Overview.
|
|
49
76
|
*/
|
|
50
77
|
readonly ref: string;
|
|
51
78
|
/**
|
|
52
79
|
* Pre-computed base URL: https://{ref}.api.sylphx.com/v1
|
|
53
|
-
*
|
|
54
|
-
* Used by buildApiUrl and callApi internally.
|
|
80
|
+
* Derived from the embedded ref in the key.
|
|
55
81
|
*/
|
|
56
82
|
readonly baseUrl: string;
|
|
57
83
|
/** Optional: Current access token for authenticated requests */
|
|
58
84
|
readonly accessToken?: string;
|
|
59
85
|
}
|
|
60
86
|
/**
|
|
61
|
-
* Configuration input
|
|
87
|
+
* Configuration input — ADR-021 key-first API.
|
|
88
|
+
*
|
|
89
|
+
* Provide either publicKey or secretKey (or both).
|
|
90
|
+
* The project ref is extracted automatically from the key.
|
|
62
91
|
*/
|
|
63
92
|
interface SylphxConfigInput {
|
|
93
|
+
/**
|
|
94
|
+
* Publishable key (pk_*) — client-safe.
|
|
95
|
+
* Format: pk_{env}_{ref}_{32hex}
|
|
96
|
+
* env var: NEXT_PUBLIC_SYLPHX_KEY
|
|
97
|
+
*/
|
|
98
|
+
publicKey?: string;
|
|
99
|
+
/**
|
|
100
|
+
* Secret key (sk_*) — server-side only.
|
|
101
|
+
* Format: sk_{env}_{ref}_{64hex}
|
|
102
|
+
* env var: SYLPHX_SECRET_KEY
|
|
103
|
+
*/
|
|
64
104
|
secretKey?: string;
|
|
65
105
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* The SDK automatically targets: https://{ref}.api.sylphx.com/v1
|
|
69
|
-
*
|
|
70
|
-
* Get this from Platform Console → Projects → Your Project → Overview.
|
|
106
|
+
* @deprecated Use publicKey or secretKey — ref is now embedded in keys (ADR-021).
|
|
107
|
+
* Still accepted for backward compatibility; overridden by key-embedded ref.
|
|
71
108
|
*/
|
|
72
|
-
ref
|
|
109
|
+
ref?: string;
|
|
73
110
|
accessToken?: string;
|
|
74
111
|
}
|
|
75
112
|
/**
|
|
76
|
-
* Create a Sylphx configuration object
|
|
113
|
+
* Create a Sylphx configuration object (ADR-021 key-first API).
|
|
114
|
+
*
|
|
115
|
+
* The project ref is extracted from the key automatically — no need to configure
|
|
116
|
+
* NEXT_PUBLIC_SYLPHX_APP_ID separately.
|
|
77
117
|
*
|
|
78
|
-
* Validates
|
|
79
|
-
* Validates the ref format (if provided) — must be a 12-char lowercase alphanumeric string.
|
|
80
|
-
* Sanitizes keys with common issues (whitespace, newlines) and logs warnings.
|
|
118
|
+
* Validates key format, extracts ref, builds base URL.
|
|
81
119
|
* Throws if key format is invalid.
|
|
82
120
|
*
|
|
83
|
-
* @example
|
|
121
|
+
* @example Server-side (secret key)
|
|
84
122
|
* ```typescript
|
|
85
123
|
* const config = createConfig({
|
|
86
124
|
* secretKey: process.env.SYLPHX_SECRET_KEY!,
|
|
87
125
|
* })
|
|
88
126
|
* ```
|
|
127
|
+
*
|
|
128
|
+
* @example Client-side (publishable key)
|
|
129
|
+
* ```typescript
|
|
130
|
+
* const config = createConfig({
|
|
131
|
+
* publicKey: process.env.NEXT_PUBLIC_SYLPHX_KEY!,
|
|
132
|
+
* })
|
|
133
|
+
* ```
|
|
89
134
|
*/
|
|
90
135
|
declare function createConfig(input: SylphxConfigInput): SylphxConfig;
|
|
91
136
|
/**
|
|
@@ -25725,4 +25770,4 @@ declare const WorkersClient: {
|
|
|
25725
25770
|
}): Promise<WorkerResult>;
|
|
25726
25771
|
};
|
|
25727
25772
|
|
|
25728
|
-
export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, AuthenticationError, AuthorizationError, type BalanceResponse, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type Breadcrumb, type BuildLog, type BuildLogHistoryResponse, type CaptureExceptionRequest, type CaptureMessageRequest, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CheckoutRequest, type CheckoutResponse, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CreateOrgInput, type CriteriaOperator, type CronInput, type CronSchedule, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DynamicRestClient, ERROR_CODE_STATUS, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type ExceptionFrame, type ExceptionValue, type ExecOptions, type FacetsResponse, type FileInfo, type FileUploadOptions, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, type IdentifyInput, type IndexDocumentInput, type IndexDocumentResult, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListUsersOptions, type ListUsersResult, type ListWorkersOptions, type ListWorkersResult, type LoginHistoryEntry, type LoginRequest, type LoginResponse, type MeResponse, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OrgRole, type Organization, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type PageInput, type PaginatedResponse, type PaginationInput, type Plan, type PortalRequest, type PortalResponse, type PushNotification, type PushNotificationPayload, type PushServiceWorkerConfig, type PushSubscription, RETRYABLE_CODES, RateLimitError, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RecordActivityInput, type RecordActivityResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type paths as RestPaths, type RetryConfig, type RevokeTokenOptions, type RollbackDeployRequest, type RunWorkerOptions, SandboxClient, type SandboxFile, type SandboxOptions, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, type SignedUrlResult, StepCompleteSignal, StepSleepSignal, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, type TaskInput, type TaskResult, type TaskStatus, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type TriggerDeployRequest, type TwoFactorVerifyRequest, type UpdateOrgInput, type UploadProgressEvent, type UploadResult, type UpsertDocumentInput, type UpsertDocumentResult, type UsageResponse, type User, type UserAchievement, type UserConsent, type UserProfile, ValidationError, type VisionInput, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, WorkerHandle, type WorkerLogsResult, type WorkerResourceSpec, type WorkerResult, type WorkerRun, type WorkerStatus, type WorkerVolumeMount, WorkersClient, acceptAllConsents, acceptOrganizationInvitation, batchIndex, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, chat, chatStream, checkFlag, complete, createCheckout, createConfig, createCron, createDynamicRestClient, createOrganization, createPortalSession, createRestClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteFile, deleteOrganization, deleteUser, disableDebug, embed, enableDebug, exponentialBackoff, extendedSignUp, forgotPassword, generateAnonymousId, getAchievement, getAchievementPoints, getAchievements, getAllFlags, getAllSecrets, getAllStreaks, getBillingBalance, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDeployHistory, getDeployStatus, getErrorCode, getErrorMessage, getFacets, getFileInfo, getFileUrl, getFlagPayload, getFlags, getLeaderboard, getMyReferralCode, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlans, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSession, getSignedUrl, getStreak, getSubscription, getTask, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, hasConsent, hasError, hasRole, hasSecret, identify, incrementAchievementProgress, indexDocument, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isEmailConfigured, isEnabled, isRetryableError, isSylphxError, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listScheduledEmails, listSecretKeys, listTasks, listUsers, page, pauseCron, realtimeEmit, recordStreakActivity, recoverStreak, redeemReferralCode, refreshToken, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, replayWebhookDelivery, rescheduleEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, rollbackDeploy, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, setConsents, setEnvVar, signIn, signOut, signUp, streamToString, submitScore, suspendUser, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePushPreferences, updateUser, updateUserMetadata, updateWebhookConfig, uploadAvatar, uploadFile, upsertDocument, verifyEmail, verifySignature as verifyTaskSignature, verifyTwoFactor, withToken };
|
|
25773
|
+
export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, AuthenticationError, AuthorizationError, type BalanceResponse, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type Breadcrumb, type BuildLog, type BuildLogHistoryResponse, type CaptureExceptionRequest, type CaptureMessageRequest, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CheckoutRequest, type CheckoutResponse, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CreateOrgInput, type CriteriaOperator, type CronInput, type CronSchedule, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DynamicRestClient, ERROR_CODE_STATUS, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type ExceptionFrame, type ExceptionValue, type ExecOptions, type FacetsResponse, type FileInfo, type FileUploadOptions, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, type IdentifyInput, type IndexDocumentInput, type IndexDocumentResult, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListUsersOptions, type ListUsersResult, type ListWorkersOptions, type ListWorkersResult, type LoginHistoryEntry, type LoginRequest, type LoginResponse, type MeResponse, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OrgRole, type Organization, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type PageInput, type PaginatedResponse, type PaginationInput, type ParsedKey, type Plan, type PortalRequest, type PortalResponse, type PushNotification, type PushNotificationPayload, type PushServiceWorkerConfig, type PushSubscription, RETRYABLE_CODES, RateLimitError, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RecordActivityInput, type RecordActivityResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type paths as RestPaths, type RetryConfig, type RevokeTokenOptions, type RollbackDeployRequest, type RunWorkerOptions, SandboxClient, type SandboxFile, type SandboxOptions, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, type SignedUrlResult, StepCompleteSignal, StepSleepSignal, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, type TaskInput, type TaskResult, type TaskStatus, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type TriggerDeployRequest, type TwoFactorVerifyRequest, type UpdateOrgInput, type UploadProgressEvent, type UploadResult, type UpsertDocumentInput, type UpsertDocumentResult, type UsageResponse, type User, type UserAchievement, type UserConsent, type UserProfile, ValidationError, type VisionInput, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, WorkerHandle, type WorkerLogsResult, type WorkerResourceSpec, type WorkerResult, type WorkerRun, type WorkerStatus, type WorkerVolumeMount, WorkersClient, acceptAllConsents, acceptOrganizationInvitation, batchIndex, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, chat, chatStream, checkFlag, complete, createCheckout, createConfig, createCron, createDynamicRestClient, createOrganization, createPortalSession, createRestClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteFile, deleteOrganization, deleteUser, disableDebug, embed, enableDebug, exponentialBackoff, extendedSignUp, forgotPassword, generateAnonymousId, getAchievement, getAchievementPoints, getAchievements, getAllFlags, getAllSecrets, getAllStreaks, getBillingBalance, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDeployHistory, getDeployStatus, getErrorCode, getErrorMessage, getFacets, getFileInfo, getFileUrl, getFlagPayload, getFlags, getLeaderboard, getMyReferralCode, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlans, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSession, getSignedUrl, getStreak, getSubscription, getTask, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, hasConsent, hasError, hasRole, hasSecret, identify, incrementAchievementProgress, indexDocument, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isEmailConfigured, isEnabled, isRetryableError, isSylphxError, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listScheduledEmails, listSecretKeys, listTasks, listUsers, page, parseKey, pauseCron, realtimeEmit, recordStreakActivity, recoverStreak, redeemReferralCode, refreshToken, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, replayWebhookDelivery, rescheduleEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, rollbackDeploy, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, setConsents, setEnvVar, signIn, signOut, signUp, streamToString, submitScore, suspendUser, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePushPreferences, updateUser, updateUserMetadata, updateWebhookConfig, uploadAvatar, uploadFile, upsertDocument, verifyEmail, verifySignature as verifyTaskSignature, verifyTwoFactor, withToken };
|
package/dist/index.d.ts
CHANGED
|
@@ -8,6 +8,33 @@ import * as openapi_fetch from 'openapi-fetch';
|
|
|
8
8
|
*
|
|
9
9
|
* Uses appId or secretKey for authentication via x-app-secret header.
|
|
10
10
|
*/
|
|
11
|
+
/**
|
|
12
|
+
* Parsed representation of a Sylphx API key (ADR-021 format).
|
|
13
|
+
*/
|
|
14
|
+
interface ParsedKey {
|
|
15
|
+
/** Key type: 'pk' (publishable) or 'sk' (secret) */
|
|
16
|
+
type: 'pk' | 'sk';
|
|
17
|
+
/** Environment short code: 'prod', 'dev', or 'stg' */
|
|
18
|
+
env: 'prod' | 'dev' | 'stg';
|
|
19
|
+
/** 12-char project ref (base36) */
|
|
20
|
+
ref: string;
|
|
21
|
+
/** Random secret portion of the key */
|
|
22
|
+
token: string;
|
|
23
|
+
/** Whether this is a client-safe publishable key */
|
|
24
|
+
isPublic: boolean;
|
|
25
|
+
/** Pre-computed base URL for this project */
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Parse an ADR-021 API key into its component parts.
|
|
30
|
+
*
|
|
31
|
+
* Supports:
|
|
32
|
+
* pk_{env}_{ref}_{32hex} — publishable key (ADR-021)
|
|
33
|
+
* sk_{env}_{ref}_{64hex} — secret key (ADR-021)
|
|
34
|
+
*
|
|
35
|
+
* @throws SylphxError if key format is invalid or uses old app_* format
|
|
36
|
+
*/
|
|
37
|
+
declare function parseKey(key: string): ParsedKey;
|
|
11
38
|
/**
|
|
12
39
|
* SDK Configuration for Pure Functions
|
|
13
40
|
*
|
|
@@ -31,61 +58,79 @@ import * as openapi_fetch from 'openapi-fetch';
|
|
|
31
58
|
*/
|
|
32
59
|
interface SylphxConfig {
|
|
33
60
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* - Secret key (sk_dev_, sk_stg_, sk_prod_) — full access, server-side only
|
|
38
|
-
* - Publishable key (app_dev_, app_stg_, app_prod_) — limited access, safe for client
|
|
39
|
-
*
|
|
40
|
-
* Get this from Platform Console → Apps → Your App → Environments
|
|
61
|
+
* Secret key (sk_*) — full access, server-side only.
|
|
62
|
+
* Embed project ref, env, and routing info (ADR-021).
|
|
63
|
+
* Get from Platform Console → Apps → Your App → Environments.
|
|
41
64
|
*/
|
|
42
65
|
readonly secretKey?: string;
|
|
43
66
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
67
|
+
* Publishable key (pk_*) — client-safe, read-only access.
|
|
68
|
+
* Embeds project ref, env, and routing info (ADR-021).
|
|
69
|
+
* Get from Platform Console → Apps → Your App → Environments.
|
|
70
|
+
*/
|
|
71
|
+
readonly publicKey?: string;
|
|
72
|
+
/**
|
|
73
|
+
* Project ref — 12-char lowercase alphanumeric string.
|
|
74
|
+
* Extracted from the key automatically (ADR-021).
|
|
46
75
|
* The SDK targets: https://{ref}.api.sylphx.com/v1
|
|
47
|
-
*
|
|
48
|
-
* Get this from Platform Console → Projects → Your Project → Overview.
|
|
49
76
|
*/
|
|
50
77
|
readonly ref: string;
|
|
51
78
|
/**
|
|
52
79
|
* Pre-computed base URL: https://{ref}.api.sylphx.com/v1
|
|
53
|
-
*
|
|
54
|
-
* Used by buildApiUrl and callApi internally.
|
|
80
|
+
* Derived from the embedded ref in the key.
|
|
55
81
|
*/
|
|
56
82
|
readonly baseUrl: string;
|
|
57
83
|
/** Optional: Current access token for authenticated requests */
|
|
58
84
|
readonly accessToken?: string;
|
|
59
85
|
}
|
|
60
86
|
/**
|
|
61
|
-
* Configuration input
|
|
87
|
+
* Configuration input — ADR-021 key-first API.
|
|
88
|
+
*
|
|
89
|
+
* Provide either publicKey or secretKey (or both).
|
|
90
|
+
* The project ref is extracted automatically from the key.
|
|
62
91
|
*/
|
|
63
92
|
interface SylphxConfigInput {
|
|
93
|
+
/**
|
|
94
|
+
* Publishable key (pk_*) — client-safe.
|
|
95
|
+
* Format: pk_{env}_{ref}_{32hex}
|
|
96
|
+
* env var: NEXT_PUBLIC_SYLPHX_KEY
|
|
97
|
+
*/
|
|
98
|
+
publicKey?: string;
|
|
99
|
+
/**
|
|
100
|
+
* Secret key (sk_*) — server-side only.
|
|
101
|
+
* Format: sk_{env}_{ref}_{64hex}
|
|
102
|
+
* env var: SYLPHX_SECRET_KEY
|
|
103
|
+
*/
|
|
64
104
|
secretKey?: string;
|
|
65
105
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* The SDK automatically targets: https://{ref}.api.sylphx.com/v1
|
|
69
|
-
*
|
|
70
|
-
* Get this from Platform Console → Projects → Your Project → Overview.
|
|
106
|
+
* @deprecated Use publicKey or secretKey — ref is now embedded in keys (ADR-021).
|
|
107
|
+
* Still accepted for backward compatibility; overridden by key-embedded ref.
|
|
71
108
|
*/
|
|
72
|
-
ref
|
|
109
|
+
ref?: string;
|
|
73
110
|
accessToken?: string;
|
|
74
111
|
}
|
|
75
112
|
/**
|
|
76
|
-
* Create a Sylphx configuration object
|
|
113
|
+
* Create a Sylphx configuration object (ADR-021 key-first API).
|
|
114
|
+
*
|
|
115
|
+
* The project ref is extracted from the key automatically — no need to configure
|
|
116
|
+
* NEXT_PUBLIC_SYLPHX_APP_ID separately.
|
|
77
117
|
*
|
|
78
|
-
* Validates
|
|
79
|
-
* Validates the ref format (if provided) — must be a 12-char lowercase alphanumeric string.
|
|
80
|
-
* Sanitizes keys with common issues (whitespace, newlines) and logs warnings.
|
|
118
|
+
* Validates key format, extracts ref, builds base URL.
|
|
81
119
|
* Throws if key format is invalid.
|
|
82
120
|
*
|
|
83
|
-
* @example
|
|
121
|
+
* @example Server-side (secret key)
|
|
84
122
|
* ```typescript
|
|
85
123
|
* const config = createConfig({
|
|
86
124
|
* secretKey: process.env.SYLPHX_SECRET_KEY!,
|
|
87
125
|
* })
|
|
88
126
|
* ```
|
|
127
|
+
*
|
|
128
|
+
* @example Client-side (publishable key)
|
|
129
|
+
* ```typescript
|
|
130
|
+
* const config = createConfig({
|
|
131
|
+
* publicKey: process.env.NEXT_PUBLIC_SYLPHX_KEY!,
|
|
132
|
+
* })
|
|
133
|
+
* ```
|
|
89
134
|
*/
|
|
90
135
|
declare function createConfig(input: SylphxConfigInput): SylphxConfig;
|
|
91
136
|
/**
|
|
@@ -25725,4 +25770,4 @@ declare const WorkersClient: {
|
|
|
25725
25770
|
}): Promise<WorkerResult>;
|
|
25726
25771
|
};
|
|
25727
25772
|
|
|
25728
|
-
export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, AuthenticationError, AuthorizationError, type BalanceResponse, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type Breadcrumb, type BuildLog, type BuildLogHistoryResponse, type CaptureExceptionRequest, type CaptureMessageRequest, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CheckoutRequest, type CheckoutResponse, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CreateOrgInput, type CriteriaOperator, type CronInput, type CronSchedule, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DynamicRestClient, ERROR_CODE_STATUS, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type ExceptionFrame, type ExceptionValue, type ExecOptions, type FacetsResponse, type FileInfo, type FileUploadOptions, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, type IdentifyInput, type IndexDocumentInput, type IndexDocumentResult, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListUsersOptions, type ListUsersResult, type ListWorkersOptions, type ListWorkersResult, type LoginHistoryEntry, type LoginRequest, type LoginResponse, type MeResponse, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OrgRole, type Organization, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type PageInput, type PaginatedResponse, type PaginationInput, type Plan, type PortalRequest, type PortalResponse, type PushNotification, type PushNotificationPayload, type PushServiceWorkerConfig, type PushSubscription, RETRYABLE_CODES, RateLimitError, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RecordActivityInput, type RecordActivityResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type paths as RestPaths, type RetryConfig, type RevokeTokenOptions, type RollbackDeployRequest, type RunWorkerOptions, SandboxClient, type SandboxFile, type SandboxOptions, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, type SignedUrlResult, StepCompleteSignal, StepSleepSignal, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, type TaskInput, type TaskResult, type TaskStatus, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type TriggerDeployRequest, type TwoFactorVerifyRequest, type UpdateOrgInput, type UploadProgressEvent, type UploadResult, type UpsertDocumentInput, type UpsertDocumentResult, type UsageResponse, type User, type UserAchievement, type UserConsent, type UserProfile, ValidationError, type VisionInput, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, WorkerHandle, type WorkerLogsResult, type WorkerResourceSpec, type WorkerResult, type WorkerRun, type WorkerStatus, type WorkerVolumeMount, WorkersClient, acceptAllConsents, acceptOrganizationInvitation, batchIndex, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, chat, chatStream, checkFlag, complete, createCheckout, createConfig, createCron, createDynamicRestClient, createOrganization, createPortalSession, createRestClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteFile, deleteOrganization, deleteUser, disableDebug, embed, enableDebug, exponentialBackoff, extendedSignUp, forgotPassword, generateAnonymousId, getAchievement, getAchievementPoints, getAchievements, getAllFlags, getAllSecrets, getAllStreaks, getBillingBalance, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDeployHistory, getDeployStatus, getErrorCode, getErrorMessage, getFacets, getFileInfo, getFileUrl, getFlagPayload, getFlags, getLeaderboard, getMyReferralCode, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlans, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSession, getSignedUrl, getStreak, getSubscription, getTask, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, hasConsent, hasError, hasRole, hasSecret, identify, incrementAchievementProgress, indexDocument, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isEmailConfigured, isEnabled, isRetryableError, isSylphxError, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listScheduledEmails, listSecretKeys, listTasks, listUsers, page, pauseCron, realtimeEmit, recordStreakActivity, recoverStreak, redeemReferralCode, refreshToken, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, replayWebhookDelivery, rescheduleEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, rollbackDeploy, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, setConsents, setEnvVar, signIn, signOut, signUp, streamToString, submitScore, suspendUser, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePushPreferences, updateUser, updateUserMetadata, updateWebhookConfig, uploadAvatar, uploadFile, upsertDocument, verifyEmail, verifySignature as verifyTaskSignature, verifyTwoFactor, withToken };
|
|
25773
|
+
export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, AuthenticationError, AuthorizationError, type BalanceResponse, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type Breadcrumb, type BuildLog, type BuildLogHistoryResponse, type CaptureExceptionRequest, type CaptureMessageRequest, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CheckoutRequest, type CheckoutResponse, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CreateOrgInput, type CriteriaOperator, type CronInput, type CronSchedule, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DynamicRestClient, ERROR_CODE_STATUS, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type ExceptionFrame, type ExceptionValue, type ExecOptions, type FacetsResponse, type FileInfo, type FileUploadOptions, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, type IdentifyInput, type IndexDocumentInput, type IndexDocumentResult, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListUsersOptions, type ListUsersResult, type ListWorkersOptions, type ListWorkersResult, type LoginHistoryEntry, type LoginRequest, type LoginResponse, type MeResponse, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OrgRole, type Organization, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type PageInput, type PaginatedResponse, type PaginationInput, type ParsedKey, type Plan, type PortalRequest, type PortalResponse, type PushNotification, type PushNotificationPayload, type PushServiceWorkerConfig, type PushSubscription, RETRYABLE_CODES, RateLimitError, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RecordActivityInput, type RecordActivityResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type paths as RestPaths, type RetryConfig, type RevokeTokenOptions, type RollbackDeployRequest, type RunWorkerOptions, SandboxClient, type SandboxFile, type SandboxOptions, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, type SignedUrlResult, StepCompleteSignal, StepSleepSignal, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, type TaskInput, type TaskResult, type TaskStatus, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type TriggerDeployRequest, type TwoFactorVerifyRequest, type UpdateOrgInput, type UploadProgressEvent, type UploadResult, type UpsertDocumentInput, type UpsertDocumentResult, type UsageResponse, type User, type UserAchievement, type UserConsent, type UserProfile, ValidationError, type VisionInput, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, WorkerHandle, type WorkerLogsResult, type WorkerResourceSpec, type WorkerResult, type WorkerRun, type WorkerStatus, type WorkerVolumeMount, WorkersClient, acceptAllConsents, acceptOrganizationInvitation, batchIndex, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, chat, chatStream, checkFlag, complete, createCheckout, createConfig, createCron, createDynamicRestClient, createOrganization, createPortalSession, createRestClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteFile, deleteOrganization, deleteUser, disableDebug, embed, enableDebug, exponentialBackoff, extendedSignUp, forgotPassword, generateAnonymousId, getAchievement, getAchievementPoints, getAchievements, getAllFlags, getAllSecrets, getAllStreaks, getBillingBalance, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDeployHistory, getDeployStatus, getErrorCode, getErrorMessage, getFacets, getFileInfo, getFileUrl, getFlagPayload, getFlags, getLeaderboard, getMyReferralCode, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlans, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSession, getSignedUrl, getStreak, getSubscription, getTask, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, hasConsent, hasError, hasRole, hasSecret, identify, incrementAchievementProgress, indexDocument, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isEmailConfigured, isEnabled, isRetryableError, isSylphxError, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listScheduledEmails, listSecretKeys, listTasks, listUsers, page, parseKey, pauseCron, realtimeEmit, recordStreakActivity, recoverStreak, redeemReferralCode, refreshToken, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, replayWebhookDelivery, rescheduleEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, rollbackDeploy, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, setConsents, setEnvVar, signIn, signOut, signUp, streamToString, submitScore, suspendUser, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePushPreferences, updateUser, updateUserMetadata, updateWebhookConfig, uploadAvatar, uploadFile, upsertDocument, verifyEmail, verifySignature as verifyTaskSignature, verifyTwoFactor, withToken };
|
package/dist/index.js
CHANGED
|
@@ -189,6 +189,7 @@ __export(index_exports, {
|
|
|
189
189
|
listTasks: () => listTasks,
|
|
190
190
|
listUsers: () => listUsers,
|
|
191
191
|
page: () => page,
|
|
192
|
+
parseKey: () => parseKey,
|
|
192
193
|
pauseCron: () => pauseCron,
|
|
193
194
|
realtimeEmit: () => realtimeEmit,
|
|
194
195
|
recordStreakActivity: () => recordStreakActivity,
|
|
@@ -579,6 +580,7 @@ function exponentialBackoff(attempt, baseDelay = BASE_RETRY_DELAY_MS, maxDelay =
|
|
|
579
580
|
}
|
|
580
581
|
|
|
581
582
|
// src/key-validation.ts
|
|
583
|
+
var PUBLIC_KEY_PATTERN = /^pk_(dev|stg|prod)_[a-z0-9]{12}_[a-f0-9]{32}$/;
|
|
582
584
|
var APP_ID_PATTERN = /^app_(dev|stg|prod)_[a-z0-9_-]+$/;
|
|
583
585
|
var SECRET_KEY_PATTERN = /^sk_(dev|stg|prod)_[a-z0-9_-]+$/;
|
|
584
586
|
var ENV_PREFIX_MAP = {
|
|
@@ -669,6 +671,9 @@ function validateKeyForType(key, keyType, pattern, envVarName) {
|
|
|
669
671
|
issues: [...issues, "invalid-format"]
|
|
670
672
|
};
|
|
671
673
|
}
|
|
674
|
+
function validatePublicKey(key) {
|
|
675
|
+
return validateKeyForType(key, "publicKey", PUBLIC_KEY_PATTERN, "NEXT_PUBLIC_SYLPHX_KEY");
|
|
676
|
+
}
|
|
672
677
|
function validateAppId(key) {
|
|
673
678
|
return validateKeyForType(key, "appId", APP_ID_PATTERN, "NEXT_PUBLIC_SYLPHX_APP_ID");
|
|
674
679
|
}
|
|
@@ -687,12 +692,16 @@ function validateAndSanitizeSecretKey(key) {
|
|
|
687
692
|
}
|
|
688
693
|
function detectKeyType(key) {
|
|
689
694
|
const sanitized = key.trim().toLowerCase();
|
|
695
|
+
if (sanitized.startsWith("pk_")) return "publicKey";
|
|
690
696
|
if (sanitized.startsWith("app_")) return "appId";
|
|
691
697
|
if (sanitized.startsWith("sk_")) return "secret";
|
|
692
698
|
return null;
|
|
693
699
|
}
|
|
694
700
|
function validateKey(key) {
|
|
695
701
|
const keyType = key ? detectKeyType(key) : null;
|
|
702
|
+
if (keyType === "publicKey") {
|
|
703
|
+
return validatePublicKey(key);
|
|
704
|
+
}
|
|
696
705
|
if (keyType === "appId") {
|
|
697
706
|
return validateAppId(key);
|
|
698
707
|
}
|
|
@@ -702,12 +711,63 @@ function validateKey(key) {
|
|
|
702
711
|
return {
|
|
703
712
|
valid: false,
|
|
704
713
|
sanitizedKey: "",
|
|
705
|
-
error: key ? `Invalid key format. Keys must start with 'app_' (
|
|
714
|
+
error: key ? `Invalid key format. Keys must start with 'pk_' (publishable), 'app_' (legacy), or 'sk_' (secret), followed by environment (dev/stg/prod). Got: ${key.slice(0, 20)}...` : "API key is required but was not provided.",
|
|
706
715
|
issues: key ? ["invalid_format"] : ["missing"]
|
|
707
716
|
};
|
|
708
717
|
}
|
|
709
718
|
|
|
710
719
|
// src/config.ts
|
|
720
|
+
function parseKey(key) {
|
|
721
|
+
const sanitized = key.trim().toLowerCase();
|
|
722
|
+
if (sanitized.startsWith("app_")) {
|
|
723
|
+
throw new SylphxError(
|
|
724
|
+
"[Sylphx] API key format has changed (ADR-021). Keys now embed the project ref.\n\nOld format: app_prod_xxx\nNew format: pk_prod_{ref}_xxx\n\nPlease regenerate your API keys from the Sylphx Console \u2192 Your App \u2192 Environments.\nOr contact support@sylphx.com for assistance.",
|
|
725
|
+
{ code: "BAD_REQUEST" }
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
const prefix = sanitized.startsWith("pk_") ? "pk" : sanitized.startsWith("sk_") ? "sk" : null;
|
|
729
|
+
if (!prefix) {
|
|
730
|
+
throw new SylphxError(
|
|
731
|
+
`[Sylphx] Invalid key format. Keys must start with 'pk_' (publishable) or 'sk_' (secret). Got: "${sanitized.slice(0, 15)}..."`,
|
|
732
|
+
{ code: "BAD_REQUEST" }
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
const parts = sanitized.split("_");
|
|
736
|
+
if (parts.length !== 4) {
|
|
737
|
+
throw new SylphxError(
|
|
738
|
+
`[Sylphx] Invalid key structure. Expected format: ${prefix}_{env}_{ref}_{token} (4 segments separated by '_'). Got ${parts.length} segment(s).`,
|
|
739
|
+
{ code: "BAD_REQUEST" }
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
const [, env, ref, token] = parts;
|
|
743
|
+
if (env !== "prod" && env !== "dev" && env !== "stg") {
|
|
744
|
+
throw new SylphxError(
|
|
745
|
+
`[Sylphx] Invalid key environment "${env}". Must be 'prod', 'dev', or 'stg'.`,
|
|
746
|
+
{ code: "BAD_REQUEST" }
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
if (!/^[a-z0-9]{12}$/.test(ref)) {
|
|
750
|
+
throw new SylphxError(
|
|
751
|
+
`[Sylphx] Invalid project ref in key: "${ref}". Must be a 12-character lowercase alphanumeric string.`,
|
|
752
|
+
{ code: "BAD_REQUEST" }
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
const expectedTokenLen = prefix === "pk" ? 32 : 64;
|
|
756
|
+
if (token.length !== expectedTokenLen || !/^[a-f0-9]+$/.test(token)) {
|
|
757
|
+
throw new SylphxError(
|
|
758
|
+
`[Sylphx] Invalid key token. ${prefix === "pk" ? "Publishable" : "Secret"} keys must have a ${expectedTokenLen}-char hex token.`,
|
|
759
|
+
{ code: "BAD_REQUEST" }
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
return {
|
|
763
|
+
type: prefix,
|
|
764
|
+
env,
|
|
765
|
+
ref,
|
|
766
|
+
token,
|
|
767
|
+
isPublic: prefix === "pk",
|
|
768
|
+
baseUrl: `https://${ref}.${DEFAULT_SDK_API_HOST}${SDK_API_PATH}`
|
|
769
|
+
};
|
|
770
|
+
}
|
|
711
771
|
function httpStatusToErrorCode(status) {
|
|
712
772
|
switch (status) {
|
|
713
773
|
case 400:
|
|
@@ -742,31 +802,58 @@ function httpStatusToErrorCode(status) {
|
|
|
742
802
|
}
|
|
743
803
|
var REF_PATTERN = /^[a-z0-9]{12}$/;
|
|
744
804
|
function createConfig(input) {
|
|
805
|
+
const keyForParsing = input.secretKey || input.publicKey;
|
|
806
|
+
if (!keyForParsing) {
|
|
807
|
+
if (input.ref) {
|
|
808
|
+
const trimmedRef = input.ref.trim();
|
|
809
|
+
if (!REF_PATTERN.test(trimmedRef)) {
|
|
810
|
+
throw new SylphxError(
|
|
811
|
+
`[Sylphx] Invalid project ref format: "${input.ref}". Expected a 12-character lowercase alphanumeric string (e.g. "abc123def456"). Get your ref from Platform Console \u2192 Projects \u2192 Your Project \u2192 Overview.`,
|
|
812
|
+
{ code: "BAD_REQUEST" }
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
const baseUrl2 = `https://${trimmedRef}.${DEFAULT_SDK_API_HOST}${SDK_API_PATH}`;
|
|
816
|
+
console.warn(
|
|
817
|
+
"[Sylphx] Providing only ref without a key is deprecated. Provide secretKey or publicKey \u2014 the ref is now embedded in keys (ADR-021)."
|
|
818
|
+
);
|
|
819
|
+
return Object.freeze({ ref: trimmedRef, baseUrl: baseUrl2, accessToken: input.accessToken });
|
|
820
|
+
}
|
|
821
|
+
throw new SylphxError(
|
|
822
|
+
"[Sylphx] Either publicKey or secretKey must be provided to createConfig().",
|
|
823
|
+
{ code: "BAD_REQUEST" }
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
const parsed = parseKey(keyForParsing);
|
|
827
|
+
const ref = parsed.ref;
|
|
828
|
+
const baseUrl = parsed.baseUrl;
|
|
745
829
|
let secretKey;
|
|
746
830
|
if (input.secretKey) {
|
|
747
831
|
const result = validateKey(input.secretKey);
|
|
748
832
|
if (!result.valid) {
|
|
749
|
-
throw new SylphxError(result.error || "Invalid
|
|
833
|
+
throw new SylphxError(result.error || "Invalid secret key", {
|
|
750
834
|
code: "BAD_REQUEST",
|
|
751
835
|
data: { issues: result.issues }
|
|
752
836
|
});
|
|
753
837
|
}
|
|
754
|
-
if (result.warning) {
|
|
755
|
-
console.warn(`[Sylphx] ${result.warning}`);
|
|
756
|
-
}
|
|
838
|
+
if (result.warning) console.warn(`[Sylphx] ${result.warning}`);
|
|
757
839
|
secretKey = result.sanitizedKey;
|
|
758
840
|
}
|
|
759
|
-
|
|
760
|
-
if (
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
841
|
+
let publicKey;
|
|
842
|
+
if (input.publicKey) {
|
|
843
|
+
const result = validateKey(input.publicKey);
|
|
844
|
+
if (!result.valid) {
|
|
845
|
+
throw new SylphxError(result.error || "Invalid public key", {
|
|
846
|
+
code: "BAD_REQUEST",
|
|
847
|
+
data: { issues: result.issues }
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
if (result.warning) console.warn(`[Sylphx] ${result.warning}`);
|
|
851
|
+
publicKey = result.sanitizedKey;
|
|
765
852
|
}
|
|
766
|
-
const baseUrl = `https://${trimmedRef}.${DEFAULT_SDK_API_HOST}${SDK_API_PATH}`;
|
|
767
853
|
return Object.freeze({
|
|
768
854
|
secretKey,
|
|
769
|
-
|
|
855
|
+
publicKey,
|
|
856
|
+
ref,
|
|
770
857
|
baseUrl,
|
|
771
858
|
accessToken: input.accessToken
|
|
772
859
|
});
|
|
@@ -784,6 +871,8 @@ function buildHeaders(config) {
|
|
|
784
871
|
};
|
|
785
872
|
if (config.secretKey) {
|
|
786
873
|
headers["x-app-secret"] = config.secretKey;
|
|
874
|
+
} else if (config.publicKey) {
|
|
875
|
+
headers["x-app-secret"] = config.publicKey;
|
|
787
876
|
}
|
|
788
877
|
if (config.accessToken) {
|
|
789
878
|
headers.Authorization = `Bearer ${config.accessToken}`;
|
|
@@ -3825,6 +3914,7 @@ function sleep2(ms) {
|
|
|
3825
3914
|
listTasks,
|
|
3826
3915
|
listUsers,
|
|
3827
3916
|
page,
|
|
3917
|
+
parseKey,
|
|
3828
3918
|
pauseCron,
|
|
3829
3919
|
realtimeEmit,
|
|
3830
3920
|
recordStreakActivity,
|