@sylphx/sdk 0.21.1 → 0.23.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.
@@ -1,4 +1,4 @@
1
- import { SdkBillingPlan, SdkBillingSubscription, SdkConsentType, UserConsent as UserConsent$1, ReferralRewardDefaults as ReferralRewardDefaults$1, WebhookDelivery as WebhookDelivery$2, OrgSdkRole, OrgInvitation, OrgMember, CreateOrgInput as CreateOrgInput$1, Organization, File as File$1, FileId } from '@sylphx/contract';
1
+ import { SdkBillingPlan, SdkBillingSubscription, SdkConsentType, UserConsent as UserConsent$1, ConsentHistoryResponse, GetStatsResponse, ReferralRewardDefaults as ReferralRewardDefaults$1, RedeemResponse, RuntimeWebhookDelivery, OrgSdkRole, OrgInvitation, OrgMember, CreateOrgInput as CreateOrgInput$1, Organization, File as File$1, FileId } from '@sylphx/contract';
2
2
  export { Organization, File as StorageFile, FileId as StorageFileId } from '@sylphx/contract';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
  import * as react from 'react';
@@ -1018,12 +1018,11 @@ type Subscription = SdkBillingSubscription;
1018
1018
  * - Platform auto-discovers/creates consent types when first referenced
1019
1019
  * - Console can override names, descriptions, requirements without deployment
1020
1020
  *
1021
- * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
1022
- * contract is the single source of truth for `GET /consent/types`,
1023
- * `GET /consent`, `POST /consent`, and friends. SDK-specific input types
1024
- * (history pagination, anonymous linking) remain local — they describe
1025
- * ergonomic helpers on top of the wire shapes rather than the wire
1026
- * shapes themselves.
1021
+ * Wire-shape types and endpoint paths are re-exported from
1022
+ * `@sylphx/contract` (ADR-084). The contract is the single source of truth
1023
+ * for `GET /consent/types`, `GET /consent`, `POST /consent`, and friends.
1024
+ * This module keeps ergonomic helper inputs only where the public SDK API
1025
+ * intentionally differs from the wire shape.
1027
1026
  *
1028
1027
  * @example
1029
1028
  * ```typescript
@@ -1067,36 +1066,7 @@ interface GetConsentHistoryInput {
1067
1066
  */
1068
1067
  cursor?: string;
1069
1068
  }
1070
- /** A single consent change history entry */
1071
- interface ConsentHistoryEntry {
1072
- /** Unique entry ID */
1073
- id: string;
1074
- /** Consent type slug (e.g., 'analytics') */
1075
- consentType: string;
1076
- /** Display name of the consent type */
1077
- consentTypeName: string;
1078
- /** Previous consent state (null = initial consent) */
1079
- previousGranted: boolean | null;
1080
- /** New consent state */
1081
- newGranted: boolean;
1082
- /** Source of the change (banner, settings, api) */
1083
- source: string;
1084
- /** Reason for change (user_action, policy_update, etc.) */
1085
- reason: string | null;
1086
- /** ISO timestamp when change occurred */
1087
- createdAt: string;
1088
- }
1089
- interface ConsentHistoryResult {
1090
- /** List of consent change entries */
1091
- entries: ConsentHistoryEntry[];
1092
- /**
1093
- * Opaque cursor for the next page. Pass as `cursor` to the next call.
1094
- * Null when this is the last page.
1095
- */
1096
- nextCursor: string | null;
1097
- /** Whether there are more entries */
1098
- hasMore: boolean;
1099
- }
1069
+ type ConsentHistoryResult = ConsentHistoryResponse;
1100
1070
  /**
1101
1071
  * Inline defaults for consent purpose auto-discovery
1102
1072
  *
@@ -1197,42 +1167,20 @@ interface ToolCall {
1197
1167
  */
1198
1168
 
1199
1169
  type ReferralRewardDefaults = ReferralRewardDefaults$1;
1200
- interface ReferralStats {
1201
- /** User's referral code */
1202
- code: string;
1203
- /** Total referrals made */
1204
- totalReferrals: number;
1205
- /** Successful (redeemed) referrals */
1206
- successfulReferrals: number;
1207
- /** Pending referrals */
1208
- pendingReferrals: number;
1209
- /** Total rewards earned */
1210
- totalRewards: number;
1211
- }
1212
- interface RedeemResult {
1213
- success: boolean;
1214
- /** Reward type - platform types or app-specific types */
1215
- rewardType: 'points' | 'premium_trial' | 'discount' | 'credit' | (string & {});
1216
- referredReward?: Record<string, unknown>;
1217
- referrerReward?: Record<string, unknown>;
1218
- }
1170
+ type ReferralStats = GetStatsResponse;
1171
+ type RedeemResult = RedeemResponse;
1219
1172
 
1220
1173
  /**
1221
1174
  * Webhooks Functions
1222
1175
  *
1223
1176
  * Pure functions for webhook configuration and delivery management.
1224
1177
  *
1225
- * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
1226
- * contract is the single source of truth for every `/webhooks/*` endpoint
1227
- * under the Console / Management plane. This module keeps a handful of
1228
- * SDK-specific ergonomic envelopes (`WebhookConfig`, `WebhookEnvironment`,
1229
- * `WebhookStats`, `WebhookConfigUpdate`, `ListDeliveriesOptions`,
1230
- * `WebhookDeliveriesResult`) that are looser or richer than the strict
1231
- * contract shapes — they predate the contract and stay put to avoid
1232
- * breaking downstream consumers (SDK tests, apps/web hooks layer).
1178
+ * Runtime endpoint paths and methods come from `webhooksRuntimeEndpoints`
1179
+ * (ADR-084). Management-plane webhook administration stays in
1180
+ * `webhooksEndpoints`; this module targets the BaaS runtime API mounted at
1181
+ * `/webhooks` for customer SDK calls.
1233
1182
  */
1234
1183
 
1235
- type WebhookDelivery$1 = WebhookDelivery$2;
1236
1184
  interface WebhookEnvironment {
1237
1185
  id: string;
1238
1186
  name: string;
@@ -1254,7 +1202,33 @@ interface WebhookConfig {
1254
1202
  interface WebhookDeliveriesResult {
1255
1203
  deliveries: WebhookDelivery$1[];
1256
1204
  total: number;
1257
- hasMore: boolean;
1205
+ hasMore?: boolean;
1206
+ limit?: number;
1207
+ offset?: number;
1208
+ }
1209
+ type WebhookDeliveryStatus$1 = RuntimeWebhookDelivery['status'] | 'success';
1210
+ interface WebhookDelivery$1 {
1211
+ id: string;
1212
+ event: string;
1213
+ eventType?: string;
1214
+ url: string;
1215
+ status: WebhookDeliveryStatus$1;
1216
+ retryCount: number;
1217
+ responseStatus?: number | null;
1218
+ statusCode?: number;
1219
+ error?: string | null;
1220
+ payload?: Record<string, unknown>;
1221
+ messageId?: string | null;
1222
+ attempts?: number;
1223
+ response?: string | null;
1224
+ createdAt: string;
1225
+ queuedAt?: string | null;
1226
+ deliveredAt?: string | null;
1227
+ failedAt?: string | null;
1228
+ lastAttemptAt?: string | null;
1229
+ timestamp?: string;
1230
+ webhookId?: string;
1231
+ duration?: number;
1258
1232
  }
1259
1233
  interface WebhookStats {
1260
1234
  total: number;
@@ -16,7 +16,7 @@ function detectSdkPlatform() {
16
16
  if (typeof runtimeGlobal.EdgeRuntime !== "undefined") return "edge";
17
17
  return "node";
18
18
  }
19
- var SDK_API_PATH, DEFAULT_SDK_API_HOST, SDK_VERSION, SDK_PLATFORM, DEFAULT_TIMEOUT_MS, TOKEN_EXPIRY_BUFFER_MS, SESSION_TOKEN_LIFETIME_SECONDS, SESSION_TOKEN_LIFETIME_MS, REFRESH_TOKEN_LIFETIME_SECONDS, FLAGS_CACHE_TTL_MS, FLAGS_STALE_WHILE_REVALIDATE_MS, MAX_RETRY_DELAY_MS, BASE_RETRY_DELAY_MS, MAX_RETRIES, ANALYTICS_SESSION_TIMEOUT_MS, WEBHOOK_MAX_AGE_MS, WEBHOOK_CLOCK_SKEW_MS, PKCE_CODE_TTL_MS, JOBS_DLQ_MAX_AGE_MS, SESSION_REPLAY_MAX_DURATION_MS, SESSION_REPLAY_UPLOAD_INTERVAL_MS, SESSION_REPLAY_RAGE_CLICK_WINDOW_MS, SESSION_REPLAY_DEAD_CLICK_TIMEOUT_MS, SESSION_REPLAY_SCROLL_HEAT_WINDOW_MS, SESSION_REPLAY_STATUS_CHECK_MS, ANALYTICS_FLUSH_INTERVAL_MS, ANALYTICS_FLUSH_TIMEOUT_MS, ANALYTICS_INTERVAL_CHECK_MS, ANALYTICS_RETRY_BASE_DELAY_MS, ANALYTICS_RETRY_MAX_DELAY_MS, ANALYTICS_RETRY_JITTER, ANALYTICS_MAX_RETRIES, FLAGS_EXPOSURE_DEDUPE_WINDOW_MS, FLAGS_STREAM_INITIAL_RECONNECT_MS, FLAGS_STREAM_MAX_RECONNECT_MS, FLAGS_STREAM_HEARTBEAT_TIMEOUT_MS, FLAGS_HTTP_POLLING_INTERVAL_MS, DEFAULT_RETRY_DELAYS_MS, JOB_DEFAULT_TIMEOUT_MS, STORAGE_KEY_PREFIX, FLAGS_CACHE_KEY, FLAGS_CACHE_TIMESTAMP_KEY, PKCE_STORAGE_PREFIX, STORAGE_TEST_KEY, ANALYTICS_SESSION_KEY, FLAGS_STORAGE_KEY, CLICK_ID_EXPIRY_MS, STALE_TIME_FREQUENT_MS, STALE_TIME_MODERATE_MS, STALE_TIME_STABLE_MS, STALE_TIME_STATS_MS, UI_COPY_FEEDBACK_MS, UI_FORM_SUCCESS_MS, UI_NOTIFICATION_MS, UI_PROMPT_DELAY_MS, UI_REDIRECT_DELAY_MS, EMAIL_RESEND_COOLDOWN_TICK_MS, NEW_USER_THRESHOLD_MS, WEB_VITALS_FCP_GOOD_MS, WEB_VITALS_FCP_POOR_MS, STORAGE_MULTIPART_THRESHOLD_BYTES, STORAGE_DEFAULT_MAX_SIZE_BYTES, STORAGE_AVATAR_MAX_SIZE_BYTES, STORAGE_LARGE_MAX_SIZE_BYTES, JWK_CACHE_TTL_MS, ANALYTICS_MAX_TRACKED_EVENT_IDS, ANALYTICS_TRACKED_IDS_KEEP, ANALYTICS_QUEUE_LIMIT, SESSION_REPLAY_CHECK_INTERVAL_MS, UI_SUCCESS_REDIRECT_MS, LOG_MESSAGE_MAX_LENGTH, DOM_SNAPSHOT_MAX_LENGTH, STACK_TRACE_MAX_LENGTH, CONSENT_WAIT_FOR_UPDATE_MS, MS_PER_MINUTE, MS_PER_HOUR, MS_PER_DAY, SECONDS_PER_MINUTE, SECONDS_PER_HOUR, Z_INDEX_OVERLAY, Z_INDEX_CRITICAL_OVERLAY, API_KEY_EXPIRY_1_DAY, API_KEY_EXPIRY_7_DAYS, API_KEY_EXPIRY_30_DAYS, API_KEY_EXPIRY_90_DAYS, API_KEY_EXPIRY_1_YEAR, WEB_VITALS_LCP_GOOD_MS, WEB_VITALS_LCP_POOR_MS, WEB_VITALS_INP_GOOD_MS, WEB_VITALS_INP_POOR_MS, WEB_VITALS_TTFB_GOOD_MS, WEB_VITALS_TTFB_POOR_MS, MIN_PASSWORD_LENGTH, DEFAULT_CONTEXT_WINDOW, ETAG_CACHE_TTL_MS;
19
+ var SDK_API_PATH, DEFAULT_SDK_API_HOST, SDK_VERSION, SDK_PLATFORM, DEFAULT_TIMEOUT_MS, SESSION_TOKEN_LIFETIME_SECONDS, SESSION_TOKEN_LIFETIME_MS, REFRESH_TOKEN_LIFETIME_SECONDS, FLAGS_CACHE_TTL_MS, FLAGS_STALE_WHILE_REVALIDATE_MS, MAX_RETRY_DELAY_MS, BASE_RETRY_DELAY_MS, MAX_RETRIES, ANALYTICS_SESSION_TIMEOUT_MS, WEBHOOK_MAX_AGE_MS, WEBHOOK_CLOCK_SKEW_MS, PKCE_CODE_TTL_MS, JOBS_DLQ_MAX_AGE_MS, SESSION_REPLAY_MAX_DURATION_MS, SESSION_REPLAY_UPLOAD_INTERVAL_MS, SESSION_REPLAY_RAGE_CLICK_WINDOW_MS, SESSION_REPLAY_DEAD_CLICK_TIMEOUT_MS, SESSION_REPLAY_SCROLL_HEAT_WINDOW_MS, SESSION_REPLAY_STATUS_CHECK_MS, ANALYTICS_FLUSH_INTERVAL_MS, ANALYTICS_FLUSH_TIMEOUT_MS, ANALYTICS_INTERVAL_CHECK_MS, ANALYTICS_RETRY_BASE_DELAY_MS, ANALYTICS_RETRY_MAX_DELAY_MS, ANALYTICS_RETRY_JITTER, ANALYTICS_MAX_RETRIES, FLAGS_EXPOSURE_DEDUPE_WINDOW_MS, FLAGS_STREAM_INITIAL_RECONNECT_MS, FLAGS_STREAM_MAX_RECONNECT_MS, FLAGS_STREAM_HEARTBEAT_TIMEOUT_MS, FLAGS_HTTP_POLLING_INTERVAL_MS, DEFAULT_RETRY_DELAYS_MS, JOB_DEFAULT_TIMEOUT_MS, STORAGE_KEY_PREFIX, FLAGS_CACHE_KEY, FLAGS_CACHE_TIMESTAMP_KEY, PKCE_STORAGE_PREFIX, STORAGE_TEST_KEY, ANALYTICS_SESSION_KEY, FLAGS_STORAGE_KEY, CLICK_ID_EXPIRY_MS, STALE_TIME_FREQUENT_MS, STALE_TIME_MODERATE_MS, STALE_TIME_STABLE_MS, STALE_TIME_STATS_MS, UI_COPY_FEEDBACK_MS, UI_FORM_SUCCESS_MS, UI_NOTIFICATION_MS, UI_PROMPT_DELAY_MS, UI_REDIRECT_DELAY_MS, EMAIL_RESEND_COOLDOWN_TICK_MS, NEW_USER_THRESHOLD_MS, WEB_VITALS_FCP_GOOD_MS, WEB_VITALS_FCP_POOR_MS, STORAGE_MULTIPART_THRESHOLD_BYTES, STORAGE_DEFAULT_MAX_SIZE_BYTES, STORAGE_AVATAR_MAX_SIZE_BYTES, STORAGE_LARGE_MAX_SIZE_BYTES, JWK_CACHE_TTL_MS, ANALYTICS_MAX_TRACKED_EVENT_IDS, ANALYTICS_TRACKED_IDS_KEEP, ANALYTICS_QUEUE_LIMIT, SESSION_REPLAY_CHECK_INTERVAL_MS, UI_SUCCESS_REDIRECT_MS, LOG_MESSAGE_MAX_LENGTH, DOM_SNAPSHOT_MAX_LENGTH, STACK_TRACE_MAX_LENGTH, CONSENT_WAIT_FOR_UPDATE_MS, MS_PER_MINUTE, MS_PER_HOUR, MS_PER_DAY, SECONDS_PER_MINUTE, SECONDS_PER_HOUR, Z_INDEX_OVERLAY, Z_INDEX_CRITICAL_OVERLAY, API_KEY_EXPIRY_1_DAY, API_KEY_EXPIRY_7_DAYS, API_KEY_EXPIRY_30_DAYS, API_KEY_EXPIRY_90_DAYS, API_KEY_EXPIRY_1_YEAR, WEB_VITALS_LCP_GOOD_MS, WEB_VITALS_LCP_POOR_MS, WEB_VITALS_INP_GOOD_MS, WEB_VITALS_INP_POOR_MS, WEB_VITALS_TTFB_GOOD_MS, WEB_VITALS_TTFB_POOR_MS, MIN_PASSWORD_LENGTH, DEFAULT_CONTEXT_WINDOW, ETAG_CACHE_TTL_MS;
20
20
  var init_constants = __esm({
21
21
  "src/constants.ts"() {
22
22
  "use strict";
@@ -25,7 +25,6 @@ var init_constants = __esm({
25
25
  SDK_VERSION = "0.5.0";
26
26
  SDK_PLATFORM = detectSdkPlatform();
27
27
  DEFAULT_TIMEOUT_MS = 3e4;
28
- TOKEN_EXPIRY_BUFFER_MS = 3e4;
29
28
  SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60;
30
29
  SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1e3;
31
30
  REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
@@ -2563,8 +2562,8 @@ function useUser() {
2563
2562
  const platform = useContext4(PlatformContext);
2564
2563
  const refresh = useCallback3(async () => {
2565
2564
  try {
2566
- const token = await getToken();
2567
- if (token && platform) {
2565
+ await getToken();
2566
+ if (platform) {
2568
2567
  window.dispatchEvent(
2569
2568
  new StorageEvent("storage", {
2570
2569
  key: `sylphx_${platform.appId}_user`
@@ -11540,9 +11539,11 @@ import { QueryClient, QueryClientProvider, useQuery as useQuery5 } from "@tansta
11540
11539
  import { useCallback as useCallback27, useEffect as useEffect23, useMemo as useMemo9, useRef as useRef10, useState as useState30 } from "react";
11541
11540
 
11542
11541
  // src/consent.ts
11542
+ import { consentEndpoints } from "@sylphx/contract";
11543
11543
  async function linkAnonymousConsents(config2, input) {
11544
- return callApi(config2, "/consent/link-anonymous", {
11545
- method: "POST",
11544
+ const endpoint = consentEndpoints.linkAnonymous;
11545
+ await callApi(config2, endpoint.path, {
11546
+ method: endpoint.method,
11546
11547
  body: input
11547
11548
  });
11548
11549
  }
@@ -12287,30 +12288,30 @@ function createWebhooksValue(config2) {
12287
12288
 
12288
12289
  // src/react/rest-client.ts
12289
12290
  init_constants();
12291
+ var DEFAULT_BAAS_PREFIX = "/sylphx";
12290
12292
  function createRestApi(config2) {
12291
- const baseUrl = `${config2.platformUrl}${SDK_API_PATH}`;
12292
- const buildHeaders2 = async () => {
12293
- const h2 = {
12294
- "Content-Type": "application/json",
12295
- // SDK identification headers for debugging and analytics
12296
- "X-SDK-Version": SDK_VERSION,
12297
- "X-SDK-Platform": SDK_PLATFORM
12298
- };
12299
- if (config2.appId) h2["x-app-secret"] = config2.appId;
12300
- const token = await config2.tokenManager.getToken();
12301
- if (token) h2.Authorization = `Bearer ${token}`;
12302
- return h2;
12303
- };
12293
+ const baasPrefix = (config2.baasPrefix ?? DEFAULT_BAAS_PREFIX).replace(/\/+$/u, "") || "/sylphx";
12294
+ const authPrefix = (config2.authPrefix ?? "/auth").replace(/\/+$/u, "") || "/auth";
12295
+ const buildHeaders2 = () => ({
12296
+ "Content-Type": "application/json",
12297
+ "X-SDK-Version": SDK_VERSION,
12298
+ "X-SDK-Platform": SDK_PLATFORM
12299
+ });
12304
12300
  const fetchWithAuth = async (url, method, body, retryOn401 = true) => {
12305
- const headers = await buildHeaders2();
12306
12301
  const options = {
12307
12302
  method,
12308
- headers,
12303
+ headers: buildHeaders2(),
12304
+ credentials: "include",
12305
+ cache: "no-store",
12309
12306
  ...body !== void 0 && { body: JSON.stringify(body) }
12310
12307
  };
12311
12308
  const res = await fetch(url, options);
12312
12309
  if (res.status === 401 && retryOn401) {
12313
12310
  config2.tokenManager.invalidate();
12311
+ const refreshed = await config2.tokenManager.ensureSession();
12312
+ if (!refreshed) {
12313
+ return res;
12314
+ }
12314
12315
  return fetchWithAuth(url, method, body, false);
12315
12316
  }
12316
12317
  return res;
@@ -12322,28 +12323,33 @@ function createRestApi(config2) {
12322
12323
  }
12323
12324
  return res.json();
12324
12325
  }
12325
- async function get(path, query) {
12326
- const url = new URL(`${baseUrl}${path}`);
12326
+ function resolveUrl(path, query) {
12327
+ const normalized = path.startsWith("/") ? path : `/${path}`;
12328
+ const url = new URL(`${baasPrefix}${normalized}`, "http://bff.local");
12327
12329
  if (query) {
12328
12330
  Object.entries(query).forEach(([k2, v2]) => {
12329
12331
  if (v2) url.searchParams.set(k2, v2);
12330
12332
  });
12331
12333
  }
12332
- const res = await fetchWithAuth(url.toString(), "GET");
12334
+ return `${url.pathname}${url.search}`;
12335
+ }
12336
+ async function get(path, query) {
12337
+ const res = await fetchWithAuth(resolveUrl(path, query), "GET");
12333
12338
  return handleResponse(res);
12334
12339
  }
12335
12340
  async function post(path, body) {
12336
- const res = await fetchWithAuth(`${baseUrl}${path}`, "POST", body);
12341
+ const res = await fetchWithAuth(resolveUrl(path), "POST", body);
12337
12342
  return handleResponse(res);
12338
12343
  }
12339
12344
  async function put(path, body) {
12340
- const res = await fetchWithAuth(`${baseUrl}${path}`, "PUT", body);
12345
+ const res = await fetchWithAuth(resolveUrl(path), "PUT", body);
12341
12346
  return handleResponse(res);
12342
12347
  }
12343
12348
  async function del(path) {
12344
- const res = await fetchWithAuth(`${baseUrl}${path}`, "DELETE");
12349
+ const res = await fetchWithAuth(resolveUrl(path), "DELETE");
12345
12350
  return handleResponse(res);
12346
12351
  }
12352
+ void authPrefix;
12347
12353
  return { get, post, put, del };
12348
12354
  }
12349
12355
 
@@ -12542,79 +12548,65 @@ function clearUserCookie(appId) {
12542
12548
  // src/react/token-manager.ts
12543
12549
  init_constants();
12544
12550
  var TokenManager = class {
12545
- token = null;
12546
- tokenExpiry = null;
12547
12551
  fetchPromise = null;
12548
- refreshTimer = null;
12549
12552
  config;
12550
12553
  constructor(config2) {
12551
12554
  this.config = config2;
12552
12555
  }
12553
12556
  /**
12554
- * Get a valid access token.
12555
- * - Returns cached token if valid
12556
- * - Fetches new token if expired or missing
12557
- * - Queues concurrent requests (only one fetch at a time)
12557
+ * @deprecated ADR-3457 — session bearers are never returned to browser JS.
12558
+ * Always returns `null`. Use same-origin BaaS proxy with cookies instead.
12558
12559
  */
12559
12560
  async getToken() {
12560
12561
  if (!this.config.isSignedIn()) {
12561
12562
  return null;
12562
12563
  }
12563
- if (this.token && this.tokenExpiry && Date.now() < this.tokenExpiry - TOKEN_EXPIRY_BUFFER_MS) {
12564
- return this.token;
12564
+ await this.ensureSession();
12565
+ return null;
12566
+ }
12567
+ /**
12568
+ * Ensure HttpOnly session cookies are still valid (refresh if needed).
12569
+ * Does not return or cache any bearer token.
12570
+ */
12571
+ async ensureSession() {
12572
+ if (!this.config.isSignedIn()) {
12573
+ return false;
12565
12574
  }
12566
12575
  if (this.fetchPromise) {
12567
12576
  return this.fetchPromise;
12568
12577
  }
12569
- this.fetchPromise = this.fetchTokenWithRetry();
12578
+ this.fetchPromise = this.refreshSessionCookiesWithRetry();
12570
12579
  try {
12571
- const token = await this.fetchPromise;
12572
- return token;
12580
+ return await this.fetchPromise;
12573
12581
  } finally {
12574
12582
  this.fetchPromise = null;
12575
12583
  }
12576
12584
  }
12577
12585
  /**
12578
- * Invalidate cached token (call on 401)
12586
+ * No-op: no in-memory bearer is cached after ADR-3457.
12579
12587
  */
12580
12588
  invalidate() {
12581
- this.token = null;
12582
- this.tokenExpiry = null;
12583
- if (this.refreshTimer) {
12584
- clearTimeout(this.refreshTimer);
12585
- this.refreshTimer = null;
12586
- }
12587
12589
  }
12588
12590
  /**
12589
- * Clear everything (call on sign out)
12591
+ * Clear in-flight keep-alive work (call on sign out).
12590
12592
  */
12591
12593
  clear() {
12592
- this.invalidate();
12593
12594
  this.fetchPromise = null;
12594
12595
  }
12595
- /**
12596
- * Fetch token with exponential backoff retry
12597
- */
12598
- async fetchTokenWithRetry() {
12596
+ async refreshSessionCookiesWithRetry() {
12599
12597
  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
12600
12598
  try {
12601
12599
  const response = await fetch(`${this.config.authPrefix}/token`, {
12602
12600
  method: "GET",
12603
- credentials: "include"
12601
+ credentials: "include",
12602
+ cache: "no-store"
12604
12603
  });
12605
12604
  if (response.ok) {
12606
- const data = await response.json();
12607
- const accessToken = data.accessToken;
12608
- if (accessToken) {
12609
- this.token = accessToken;
12610
- this.tokenExpiry = this.decodeTokenExpiry(accessToken);
12611
- this.scheduleRefresh();
12612
- return accessToken;
12613
- }
12605
+ return true;
12614
12606
  }
12615
12607
  if (response.status === 401) {
12616
12608
  this.config.onSessionExpired?.();
12617
- return null;
12609
+ return false;
12618
12610
  }
12619
12611
  } catch {
12620
12612
  }
@@ -12622,41 +12614,7 @@ var TokenManager = class {
12622
12614
  await new Promise((r2) => setTimeout(r2, BASE_RETRY_DELAY_MS * 2 ** attempt));
12623
12615
  }
12624
12616
  }
12625
- return null;
12626
- }
12627
- /**
12628
- * Decode JWT expiry without verification
12629
- * (Verification happens server-side)
12630
- */
12631
- decodeTokenExpiry(token) {
12632
- try {
12633
- const parts = token.split(".");
12634
- if (parts.length !== 3) return null;
12635
- const payload = parts[1];
12636
- const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
12637
- const jsonPayload = atob(base64);
12638
- const parsed = JSON.parse(jsonPayload);
12639
- return parsed.exp ? parsed.exp * 1e3 : null;
12640
- } catch {
12641
- return null;
12642
- }
12643
- }
12644
- /**
12645
- * Schedule token refresh before expiry
12646
- */
12647
- scheduleRefresh() {
12648
- if (this.refreshTimer) {
12649
- clearTimeout(this.refreshTimer);
12650
- }
12651
- if (!this.tokenExpiry) return;
12652
- const refreshIn = this.tokenExpiry - Date.now() - TOKEN_EXPIRY_BUFFER_MS;
12653
- if (refreshIn > 0) {
12654
- this.refreshTimer = setTimeout(() => {
12655
- if (this.config.isSignedIn()) {
12656
- this.fetchTokenWithRetry();
12657
- }
12658
- }, refreshIn);
12659
- }
12617
+ return false;
12660
12618
  }
12661
12619
  };
12662
12620
 
@@ -12818,11 +12776,11 @@ function SylphxProviderInner({
12818
12776
  ]);
12819
12777
  const api = useMemo9(
12820
12778
  () => createRestApi({
12821
- appId,
12822
- platformUrl,
12779
+ baasPrefix: "/sylphx",
12780
+ authPrefix,
12823
12781
  tokenManager
12824
12782
  }),
12825
- [appId, platformUrl, tokenManager]
12783
+ [authPrefix, tokenManager]
12826
12784
  );
12827
12785
  const plans = config2.plans;
12828
12786
  const plansLoading = false;
@@ -13162,21 +13120,9 @@ function SylphxProviderInner({
13162
13120
  if (!authState.isSignedIn) {
13163
13121
  return null;
13164
13122
  }
13165
- try {
13166
- const response = await fetch(`${authPrefix}/token`, {
13167
- method: "GET",
13168
- credentials: "include"
13169
- // Send cookies
13170
- });
13171
- if (!response.ok) {
13172
- return null;
13173
- }
13174
- const data = await response.json();
13175
- return data.accessToken ?? null;
13176
- } catch {
13177
- return null;
13178
- }
13179
- }, [authState.isSignedIn, authPrefix]);
13123
+ await tokenManager.ensureSession();
13124
+ return null;
13125
+ }, [authState.isSignedIn, tokenManager]);
13180
13126
  const switchOrganizationToken = useCallback27(
13181
13127
  async (orgId) => {
13182
13128
  if (!authState.isSignedIn) {
@@ -14715,6 +14661,18 @@ function useHasPermission(permissions, required) {
14715
14661
  import { useMutation as useMutation2, useQuery as useQuery7, useQueryClient as useQueryClient6 } from "@tanstack/react-query";
14716
14662
  import { useCallback as useCallback29, useContext as useContext17, useMemo as useMemo11, useState as useState31 } from "react";
14717
14663
 
14664
+ // src/storage.ts
14665
+ import { storageEndpoints } from "@sylphx/contract";
14666
+
14667
+ // src/contract-http.ts
14668
+ function interpolatePath(template, params) {
14669
+ let path = template;
14670
+ for (const [key, value] of Object.entries(params)) {
14671
+ path = path.replace(`:${key}`, encodeURIComponent(value));
14672
+ }
14673
+ return path;
14674
+ }
14675
+
14718
14676
  // src/lib/retry.ts
14719
14677
  init_constants();
14720
14678
  var DEFAULT_RETRY_CONFIG = {
@@ -14825,18 +14783,24 @@ function randomBytes(n2) {
14825
14783
 
14826
14784
  // src/storage.ts
14827
14785
  var PATHS = {
14828
- uploads: "/storage/uploads",
14829
- upload: (id) => `/storage/uploads/${encodeURIComponent(String(id))}`,
14830
- uploadComplete: (id) => `/storage/uploads/${encodeURIComponent(String(id))}:complete`,
14831
- uploadPart: (id, n2) => `/storage/uploads/${encodeURIComponent(String(id))}/parts/${n2}`,
14832
- files: "/storage/files",
14833
- file: (id) => `/storage/files/${encodeURIComponent(String(id))}`,
14834
- fileTakedown: (id) => `/storage/files/${encodeURIComponent(String(id))}:takedown`,
14835
- fileRestore: (id) => `/storage/files/${encodeURIComponent(String(id))}:restore`,
14836
- fileSignedUrl: (id) => `/storage/files/${encodeURIComponent(String(id))}:signedUrl`,
14837
- fileCopy: (id) => `/storage/files/${encodeURIComponent(String(id))}:copy`,
14838
- versions: (id) => `/storage/files/${encodeURIComponent(String(id))}/versions`,
14839
- versionRestore: (id, vid) => `/storage/files/${encodeURIComponent(String(id))}/versions/${encodeURIComponent(String(vid))}:restore`
14786
+ uploads: storageEndpoints.createUpload.path,
14787
+ upload: (id) => interpolatePath(storageEndpoints.abortUpload.path, { uploadId: String(id) }),
14788
+ uploadComplete: (id) => interpolatePath(storageEndpoints.completeUpload.path, { uploadId: String(id) }),
14789
+ uploadPart: (id, n2) => interpolatePath(storageEndpoints.presignUploadPart.path, {
14790
+ uploadId: String(id),
14791
+ partNumber: String(n2)
14792
+ }),
14793
+ files: storageEndpoints.listFiles.path,
14794
+ file: (id) => interpolatePath(storageEndpoints.getFile.path, { fileId: String(id) }),
14795
+ fileTakedown: (id) => interpolatePath(storageEndpoints.takedownFile.path, { fileId: String(id) }),
14796
+ fileRestore: (id) => interpolatePath(storageEndpoints.restoreFile.path, { fileId: String(id) }),
14797
+ fileSignedUrl: (id) => interpolatePath(storageEndpoints.signFileUrl.path, { fileId: String(id) }),
14798
+ fileCopy: (id) => interpolatePath(storageEndpoints.copyFile.path, { fileId: String(id) }),
14799
+ versions: (id) => interpolatePath(storageEndpoints.listFileVersions.path, { fileId: String(id) }),
14800
+ versionRestore: (id, vid) => interpolatePath(storageEndpoints.restoreFileVersion.path, {
14801
+ fileId: String(id),
14802
+ versionId: String(vid)
14803
+ })
14840
14804
  };
14841
14805
  var hasXhr = () => typeof globalThis.XMLHttpRequest !== "undefined";
14842
14806
  var hasLocalStorage = () => {
@@ -15034,7 +14998,7 @@ async function uploadsCreate(config2, blob, options) {
15034
14998
  ifNoneMatch: options.ifNoneMatch
15035
14999
  };
15036
15000
  const session = await callApi(config2, PATHS.uploads, {
15037
- method: "POST",
15001
+ method: storageEndpoints.createUpload.method,
15038
15002
  body: createBody,
15039
15003
  idempotencyKey,
15040
15004
  signal
@@ -15042,7 +15006,7 @@ async function uploadsCreate(config2, blob, options) {
15042
15006
  const uploadId = session.uploadId;
15043
15007
  const onAborted = async () => {
15044
15008
  try {
15045
- await callApi(config2, PATHS.upload(uploadId), { method: "DELETE" });
15009
+ await callApi(config2, PATHS.upload(uploadId), { method: storageEndpoints.abortUpload.method });
15046
15010
  } catch {
15047
15011
  }
15048
15012
  clearResume(String(uploadId));
@@ -15074,7 +15038,7 @@ async function runSinglePart(config2, blob, session, options, idempotencyKey) {
15074
15038
  config2,
15075
15039
  PATHS.uploadComplete(session.uploadId),
15076
15040
  {
15077
- method: "POST",
15041
+ method: storageEndpoints.completeUpload.method,
15078
15042
  body: { parts: [{ partNumber: 1, etag: put.etag }] },
15079
15043
  idempotencyKey: `${idempotencyKey}:complete`,
15080
15044
  signal
@@ -15119,7 +15083,7 @@ async function runMultipart(config2, blob, session, options, idempotencyKey) {
15119
15083
  config2,
15120
15084
  PATHS.uploadComplete(session.uploadId),
15121
15085
  {
15122
- method: "POST",
15086
+ method: storageEndpoints.completeUpload.method,
15123
15087
  body: { parts: completedParts },
15124
15088
  idempotencyKey: `${idempotencyKey}:complete`,
15125
15089
  signal
@@ -15129,9 +15093,12 @@ async function runMultipart(config2, blob, session, options, idempotencyKey) {
15129
15093
  return fileFromCompletion(completion, options, blob);
15130
15094
  }
15131
15095
  async function uploadsAbort(config2, uploadId) {
15132
- await withRetry(() => callApi(config2, PATHS.upload(uploadId), { method: "DELETE" }), {
15133
- maxRetries: 3
15134
- });
15096
+ await withRetry(
15097
+ () => callApi(config2, PATHS.upload(uploadId), { method: storageEndpoints.abortUpload.method }),
15098
+ {
15099
+ maxRetries: 3
15100
+ }
15101
+ );
15135
15102
  clearResume(String(uploadId));
15136
15103
  }
15137
15104
  function filesListPage(config2, options, cursor) {
@@ -15142,7 +15109,7 @@ function filesListPage(config2, options, cursor) {
15142
15109
  includeDeleted: options.includeDeleted
15143
15110
  };
15144
15111
  return callApi(config2, PATHS.files, {
15145
- method: "GET",
15112
+ method: storageEndpoints.listFiles.method,
15146
15113
  query: {
15147
15114
  folder: query.folder,
15148
15115
  cursor: query.cursor,
@@ -15166,19 +15133,23 @@ function filesList(config2, options = {}) {
15166
15133
  return Object.assign(iter, { fetchPage });
15167
15134
  }
15168
15135
  async function filesGet(config2, fileId) {
15169
- return callApi(config2, PATHS.file(fileId), { method: "GET" });
15136
+ return callApi(config2, PATHS.file(fileId), {
15137
+ method: storageEndpoints.getFile.method
15138
+ });
15170
15139
  }
15171
15140
  async function filesDelete(config2, fileId) {
15172
- return callApi(config2, PATHS.file(fileId), { method: "DELETE" });
15141
+ return callApi(config2, PATHS.file(fileId), { method: storageEndpoints.deleteFile.method });
15173
15142
  }
15174
15143
  async function filesTakedown(config2, fileId, options) {
15175
15144
  return callApi(config2, PATHS.fileTakedown(fileId), {
15176
- method: "POST",
15145
+ method: storageEndpoints.takedownFile.method,
15177
15146
  body: options
15178
15147
  });
15179
15148
  }
15180
15149
  async function filesRestore(config2, fileId) {
15181
- return callApi(config2, PATHS.fileRestore(fileId), { method: "POST" });
15150
+ return callApi(config2, PATHS.fileRestore(fileId), {
15151
+ method: storageEndpoints.restoreFile.method
15152
+ });
15182
15153
  }
15183
15154
  async function filesSignedUrl(config2, fileId, options = {}) {
15184
15155
  const body = {
@@ -15187,7 +15158,7 @@ async function filesSignedUrl(config2, fileId, options = {}) {
15187
15158
  userId: options.userId
15188
15159
  };
15189
15160
  return callApi(config2, PATHS.fileSignedUrl(fileId), {
15190
- method: "POST",
15161
+ method: storageEndpoints.signFileUrl.method,
15191
15162
  body
15192
15163
  });
15193
15164
  }
@@ -15199,18 +15170,20 @@ async function filesCopy(config2, fileId, options) {
15199
15170
  metadata: options.metadata
15200
15171
  };
15201
15172
  return callApi(config2, PATHS.fileCopy(fileId), {
15202
- method: "POST",
15173
+ method: storageEndpoints.copyFile.method,
15203
15174
  body
15204
15175
  });
15205
15176
  }
15206
15177
  async function filesVersionsList(config2, fileId) {
15207
15178
  const data = await callApi(config2, PATHS.versions(fileId), {
15208
- method: "GET"
15179
+ method: storageEndpoints.listFileVersions.method
15209
15180
  });
15210
15181
  return data.versions;
15211
15182
  }
15212
15183
  async function filesVersionsRestore(config2, fileId, versionId) {
15213
- return callApi(config2, PATHS.versionRestore(fileId, versionId), { method: "POST" });
15184
+ return callApi(config2, PATHS.versionRestore(fileId, versionId), {
15185
+ method: storageEndpoints.restoreFileVersion.method
15186
+ });
15214
15187
  }
15215
15188
  var storage = {
15216
15189
  uploads: {
@@ -25231,7 +25204,7 @@ function ReferralCardInner({
25231
25204
  fontWeight: 700,
25232
25205
  color: theme.colorSuccess
25233
25206
  },
25234
- children: stats.successfulReferrals || 0
25207
+ children: stats.completedReferrals || 0
25235
25208
  }
25236
25209
  ),
25237
25210
  /* @__PURE__ */ jsx42("div", { style: mergeStyles(styles2.textXs, styles2.textMuted), children: "Successful" })