@farthershore/farthershore-js/react exports
Every public export and declaration from @farthershore/farthershore-js/react.
Every public export and declaration from @farthershore/farthershore-js/react.
Import from @farthershore/farthershore-js/react. This reference is extracted from the published declaration surface for version 0.32.0. Read the collection's guides for workflows, prerequisites and failure handling.
A Notion-minimal access request (`/me/access-requests`). Track T3 —
approval AUTO-GRANTS the permission onto the requester's direct grants.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1061.
export interface AccessRequest {
id: string;
/** External identity id of the requesting member. */
requestedBy: string;
/** The requested permission (unified `<subject>:<verb>` grammar). */
permission: string;
note?: string | null;
/** PENDING | APPROVED | DENIED. */
status: string;
resolvedBy?: string | null;
resolvedAt?: string | null;
createdAt: string;
}
Public export ActiveServiceAccountCreateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L465.
export interface ActiveServiceAccountCreateResponse {
status: "ACTIVE";
serviceAccountId: string;
apiKeyId: string;
keyPrefix: string;
/** One-time plaintext secret. */
plaintext: string;
requestedPermissions: string[];
grantedPermissions: string[];
}
Public export ActiveServiceAccountUpdateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L486.
export interface ActiveServiceAccountUpdateResponse {
status: "ACTIVE";
serviceAccountId: string;
requestedPermissions: string[];
grantedPermissions: string[];
}
Public export ApiKey.
Declaration source: packages/farthershore-js/dist/types.d.ts#L347.
export interface ApiKey {
id: string;
keyPrefix: string;
label: string | null;
/** Normalized lowercase, e.g. "active" | "revoked". */
status: string;
createdAt: string;
lastUsedAt: string | null;
revokedAt: string | null;
/** Consumer-principal (D2): the key's subject kind — a PERSONAL key mints a
* member subject, a SERVICE key an org-owned service account. Always present
* (Core's `ApiKey.kind` is a NOT NULL column). */
kind: ApiKeyKind;
/** PERSONAL — the bound member's stable `Membership.id` (identity + permission
* source). Null for service keys / when the API omits it. */
memberId: string | null;
/** SERVICE — the org-owned `ServiceAccount.id` the key attaches to. Null for
* personal keys / when the API omits it. */
serviceAccountId: string | null;
/** SERVICE — the bound service account's display name, when the API returns
* it (the list groups service keys by account under this label). */
serviceAccountName: string | null;
/** Provenance: which member MINTED the key (audit only; may differ from the
* bound member when an admin mints a personal key for someone — D2a). Null
* for pre-attribution keys. */
createdBy: string | null;
}
Consumer-principal (D2): which stable identity an API key credentials.
`PERSONAL` binds to a member (perms = the member's live roles ∩ the key's
restrictions; auto-revoked when the member leaves). `SERVICE` attaches to a
named org-owned service account (admin-gated; survives offboarding).
Declaration source: packages/farthershore-js/dist/types.d.ts#L346.
export type ApiKeyKind = "PERSONAL" | "SERVICE";
Public export ApiKeysResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L15.
export interface ApiKeysResult extends AsyncResult<ApiKey[]> {
create(input?: {
label?: string;
scopes?: string[];
roleKeys?: string[];
restrictedPermissions?: string[];
/** Generic API-key creation is member-owned. */
kind?: "PERSONAL";
/** PERSONAL — mint FOR this member (`Membership.id`); admin-gated (D2a). */
memberId?: string;
}): Promise<CreatedApiKey>;
revoke(keyId: string): Promise<void>;
rotate(keyId: string): Promise<CreatedApiKey>;
}
Public export ApprovedServiceAccountCreateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L493.
export interface ApprovedServiceAccountCreateResponse {
status: "ACTIVE";
operation: "CREATE";
serviceAccountId: string;
apiKeyId: string;
/** One-time plaintext secret. */
plaintext: string;
grantedPermissions: string[];
}
Public export ApprovedServiceAccountUpdateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L502.
export interface ApprovedServiceAccountUpdateResponse {
status: "ACTIVE";
operation: "UPDATE";
serviceAccountId: string;
grantedPermissions: string[];
}
Public export ApproveServiceAccountInput.
Declaration source: packages/farthershore-js/dist/types.d.ts#L451.
export interface ApproveServiceAccountInput {
/** Omit to approve the complete original request. */
grantedPermissions?: string[];
}
The React-ecosystem-familiar result shape every data hook returns (the
same vocabulary TanStack Query / SWR consumers already know). `isError`/
`isSuccess` are DERIVED, never independently settable:
- `isError` = `error != null`
- `isSuccess` = `!isLoading && error == null && data != null`
`queryKey` is a stable per-hook identity array (resource name + the
meaningful scope/args) — not consumed internally today, but a caller-facing
handle for external cache/devtools integration.
Declaration source: packages/farthershore-js/dist/react/use-async.d.ts#L14.
export interface AsyncResult<T> {
data: T | null;
error: Error | null;
/** True while the read is in flight (initial load or a refetch). */
isLoading: boolean;
/** `error != null`. */
isError: boolean;
/** `!isLoading && error == null && data != null`. */
isSuccess: boolean;
/** Re-run the async function. AWAITABLE (W4): the returned promise resolves
* when a run STARTED AFTER this call has COMMITTED its result (fresh data
* or error visible on `.data`/`.error`) — the primitive mutation helpers
* use to hold "reconciling" state until the authoritative refetch lands.
* Generation-bound: a superseded/stale run's settlement can never release
* it; only the commit of a newer run does (settled from a commit-phase
* effect, so the awaited continuation always observes the new snapshot).
* It never rejects (a failed read surfaces on `.error`, not the waiter).
* Called after unmount it resolves immediately (documented no-op — there
* is no read to wait for). Fire-and-forget callers can ignore it. */
refetch: () => Promise<void>;
/** Stable identity for this read: `[resource, ...scope/args]`. */
queryKey: readonly unknown[];
}
Public export AsyncState.
Declaration source: packages/farthershore-js/dist/react/use-async.d.ts#L1.
export interface AsyncState<T> {
data: T | null;
loading: boolean;
error: Error | null;
}
Public export AuditLogEntry.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1074.
export interface AuditLogEntry {
id: string;
createdAt: string;
action: string;
decision?: "ALLOW" | "DENY" | null;
actorType?: string | null;
actorUserId?: string | null;
/** Friendly display name for a user actor (subscriber / builder / maker),
* resolved server-side from the actor's Clerk user id. Null for non-user
* actors (gateway / admin_service) or unknown ids — render `actorUserId`
* as the fallback. */
actorName?: string | null;
payloadJson?: Record<string, unknown> | null;
[k: string]: unknown;
}
The filters {@link useAuditLogs} / {@link usePaginatedAuditLogs} accept.
Mirrors {@link AuditLogsResource.list } (the resource already forwards every
field) so changing any one refetches.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L232.
export interface AuditLogFilters {
action?: string;
actorUserId?: string;
decision?: "ALLOW" | "DENY";
from?: string;
to?: string;
cursor?: string;
limit?: number;
/**
* Request-local workspace override. `null` omits the organization header and
* therefore reads the user's default subscription; it never mutates the
* provider's selected workspace.
*/
organizationId?: string | null;
}
Public export AuditLogPage.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1089.
export interface AuditLogPage {
items: AuditLogEntry[];
nextCursor: string | null;
}
Managed auth state, published by `<FsAuthProvider>`.
Declaration source: packages/farthershore-js/dist/react/mounted-context.d.ts#L6.
declare const AuthCtx: import("react").Context<FsAuth | null>;
Public export AuthStrategy.
Declaration source: packages/farthershore-js/dist/types.d.ts#L59.
export type AuthStrategy = "clerk" | "test-personas";
A partial-success auto-key failure: the subscriber activated but Core could
not mint the first API key. Mirrors core's `autoApiKeyError` ({@code
checkout.ts}). The caller should prompt the user to create a key manually
rather than silently dropping the signal.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1097.
export interface AutoApiKeyError {
code: string;
message: string;
}
Public export BillingResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L108.
export interface BillingResult extends AsyncResult<Subscription | null> {
openBillingPortal(input?: {
returnUrl?: string;
}): Promise<{
url: string;
}>;
/** Cancel the subscription — free ends immediately, paid is scheduled on
* the provider for the period boundary (`cancelsAt`). Optional `reason`
* (churn analytics) threads to Core. Always refreshes the local
* subscription read: the cancel HAPPENED either way. */
cancel(input?: {
reason?: string;
}): Promise<CancelSubscriptionResult>;
/** Buy more prepaid balance — returns the provider checkout URL to send the
* subscriber to. Nothing is funded until they complete it, so this does NOT
* refresh the local read. */
addFunds(input: {
amountCents: number;
requestId?: string;
successUrl?: string;
cancelUrl?: string;
}): Promise<{
checkoutUrl: string;
}>;
/** Reverse a scheduled cancel — the platform lifts `cancel_at_period_end`
* (paid) or flips a CANCELLED free sub back to ACTIVE. Always refreshes the
* local subscription read: the restore HAPPENED either way. */
restore(): Promise<RestoreSubscriptionResult>;
/** Change plan inline or schedule it according to product policy. */
changePlan(input: {
compiledPlanId: string;
}): Promise<ChangePlanResult>;
/** Set/clear the subscriber's monthly spend cap (cents; null clears). Refreshes
* the local subscription read. STORED-not-ENFORCED — see {@link useSpendCap}. */
setSpendCap(input: {
maxMonthlySpendCents: number | null;
}): Promise<SpendCapResult__395300e78371>;
}
Public export BillPreview.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1284.
export type BillPreview = TransparentBillPreview | OpaqueBillPreview;
A funding allowance (balance bucket) with nanodollar balances —
transparent disclosure only.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1198.
export interface BillPreviewAllowance {
/** Bucket source kind (e.g. `included`, `prepaid`, `promo`). */
kind: string;
/** Bucket lifecycle state — Core's `BucketState`, verbatim. */
state: BucketState;
/** Nanodollars, decimal strings (null = unavailable). */
remainingNanos: NanosAmount;
heldNanos: NanosAmount;
consumedNanos: NanosAmount;
/** ISO timestamp, or null when the allowance does not expire. */
expiresAt: string | null;
}
Served usage this cycle that `totals` does NOT account for.
`totals.ratedNanos` sums POSTED charges only, so usage that is metered but
not yet priced — or that can no longer be priced at all — contributes
nothing to it. Rendering that as `$0` asserts "you owe nothing" when the
truthful statement is "we have not priced this yet". Render this instead of
letting a confident zero stand.
`pendingEventCount` drains on its own; `unratableEventCount` will not without
operator action.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1251.
export interface BillPreviewUsageRating {
pendingEventCount: number;
unratableEventCount: number;
/** ISO instant of the oldest unaccounted event, or null when there is none. */
oldestUnratedServedAt: string | null;
}
One rating window's engine-exact recognized total.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1186.
export interface BillPreviewWindow {
windowId: string;
/** ISO timestamps. */
windowStart: string;
windowEnd: string;
/** Rated charges the engine recognized in this window. */
chargeCount: number;
/** Nanodollars, decimal string (null = unavailable). */
ratedNanos: NanosAmount;
}
Resolved bootstrap, published by `<FartherShoreRoot>`.
Declaration source: packages/farthershore-js/dist/react/mounted-context.d.ts#L4.
declare const BootCtx: import("react").Context<Bootstrap | null>;
What `fs.bootstrap()` returns — everything a generated/managed frontend needs
to discover the business it's running for AND render its catalog: the full
plan list (pricing model and included quotas), business meters, docs /
legal origins, and the featured-plan pointer.
Declaration source: packages/farthershore-js/dist/types.d.ts#L294.
export interface Bootstrap {
/** Wire schema version of the resolve DTO this bootstrap was decoded from
* (CC5). Additive negotiation hook; legacy payloads (no version) decode as
* `1`. Informational today — the SDK reads every shape tolerantly. */
schemaVersion: number;
business: Business;
environment: EnvironmentInfo | null;
branding: Branding;
/** The business's available/purchasable plans (empty when none are
* published). The single source the plans/pricing UI renders from. */
plans: Plan[];
/** The business's active custom-frontend release hash, or null. Informational
* (diagnostics) — V0 serving is host-keyed at the edge. */
frontendReleaseHash: string | null;
/** Available module keys derived from the plan set (non-empty once plans exist):
* e.g. "billing", "usage-quota", "docs", "legal". */
availableModules: string[];
/** The business's declared counted-resource catalog (W5.1). Empty when the
* business declares none. */
declaredResources: DeclaredResource[];
}
Public export Branding.
Declaration source: packages/farthershore-js/dist/types.d.ts#L2.
export interface Branding {
displayName: string;
/** Square brand mark (favicon / nav mark). */
iconUrl: string | null;
/** Horizontal text logo (wordmark) — rendered in place of the displayName
* text when set. Most products only have an icon. */
logoUrl: string | null;
/** Marketing/header description for the business, when set. */
description: string | null;
}
Lifecycle state of a funding allowance (balance bucket) — mirrors Core's
`BucketState` (Prisma) verbatim. `AVAILABLE` is the live, spendable
state; `EXPIRY_PENDING` is still spendable but about to expire; `PENDING`
is not yet spendable; `FROZEN` / `EXPIRED` / `CANCELLED` are not spendable.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1184.
export type BucketState = "PENDING" | "AVAILABLE" | "EXPIRY_PENDING" | "FROZEN" | "EXPIRED" | "CANCELLED";
Public export Business.
Declaration source: packages/farthershore-js/dist/types.d.ts#L23.
export interface Business {
id: string;
/** Subdomain slug (the first label of the gateway/portal host). */
slug: string;
name: string;
description: string | null;
branding: Branding;
/** Gateway origin host for builder-feature calls (the business `runtimeHostname`). */
gatewayHost: string;
/** Public portal host. */
portalHost: string;
/** R2 public origin + business prefix where MDX docs live, or null when the
* platform has no docs origin configured (local dev). The `/docs` view
* concatenates the doc filename onto this. */
docsBaseUrl: string | null;
/** R2 public origin + business prefix for per-business legal MDX
* (terms / privacy), or null. The legal view falls back to the platform
* terms notice when null. */
legalBaseUrl: string | null;
/** Versioned legal documents declared by the business, keyed by extensible
* kind (`terms`, `privacy`, custom kinds). URLs are public CDN MDX objects. */
legal?: {
documents: Record<string, LegalDocumentReference>;
};
/** Platform-owned docs visibility flag. When `false` the portal /docs
* surface is suppressed (nav item hidden, route 404s) regardless of
* whether `docsBaseUrl` is set. Absent on older Core payloads — the SDK
* defaults this to `true` (backward-compatible). */
docsEnabled: boolean;
/** Immutable `CompiledPlan.id` of the featured plan, or null. Used to render
* the "Most Popular" treatment in the plans UI. */
featuredCompiledPlanId: string | null;
/** Business-level meter definitions — the dimension catalog used to label
* usage rows. Empty when the business declares no meters. */
meters: Meter[];
}
`POST /me/cancel` — the platform performs the cancel: free subs end
immediately, paid subs are scheduled on the provider for the end of the
current billing period. There is no hosted-page hand-off: the caller gets
a typed result back, and `cancelsAt` is the boundary the provider
answered with (null when it reported none, or for an immediate free
cancel). NEVER invented client-side.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1122.
export interface CancelSubscriptionResult {
subscription?: unknown;
/** ISO instant the subscription ends, or null. */
cancelsAt: string | null;
raw: unknown;
}
`POST /me/change-plan` — Core decides inline-apply vs checkout vs portal
redirect; all three surfaces normalized onto one shape.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1144.
export interface ChangePlanResult {
subscription?: unknown;
checkoutUrl?: string | null;
portalRedirect?: {
url: string;
} | null;
raw: unknown;
}
One per-subscriber component-gate override row (`GET /me`
`componentAccessPolicies`) — shape-matches the contracts
`ComponentAccessPolicyDto`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L945.
export interface ComponentAccessPolicyRow {
/** A managed component id or a `custom:<slug>` key. */
componentKey: string;
/** Override render-gate permission, or null → component default. */
requiredPermission: string | null;
/** Override deny render (`hide|disable|readOnly|denied`), or null →
* component default. */
gateMode: string | null;
}
Public export CooldownResult.
Declaration source: packages/farthershore-js/dist/react/use-limits.d.ts#L9.
export interface CooldownResult {
/** Whole seconds left until the cooldown elapses; 0 once it has. */
secondsRemaining: number;
/** True while `secondsRemaining > 0`. */
active: boolean;
}
Returned ONLY by create/rotate — carries the full secret, shown once.
Declaration source: packages/farthershore-js/dist/types.d.ts#L375.
export interface CreatedApiKey extends ApiKey {
/** The full key. The platform never returns it again — store it now. */
secret: string;
}
An SWR-compatible fetcher bound to a client:
`(integrationId, path, opts?) => Promise<Response>`. Delegates to
`fs.integration(id).fetch`, so the named integration contract is available
as a plain fetcher function:
const fetcher = createFsFetcher(fs);
useSWR(["stripe-charges", "/v1/charges"], ([id, path]) => fetcher(id, path));
Declaration source: packages/farthershore-js/dist/react/query-adapter.d.ts#L21.
export declare function createFsFetcher(client: FartherShoreClient__e4fe174a542f): (integrationId: string, path: string, opts?: FsFetchOptions__62afbd421e0f) => Promise<Response>;
Public export CreateServiceAccountInput.
Declaration source: packages/farthershore-js/dist/types.d.ts#L441.
export interface CreateServiceAccountInput {
name: string;
requestedPermissions: NonEmptyPermissionList;
scopes?: string[];
usageLimit?: ServiceAccountUsageLimitRequest;
}
Strict POST body: immutable subject + quantity, one value lane, and a
coherent BLOCK/NOTIFY threshold.
Declaration source: packages/farthershore-js/dist/types.d.ts#L604.
export type CreateUsageLimitInput = UsageLimitSubject & UsageLimitValue & UsageLimitCreateMode__f16ef2d50497 & {
quantity: string;
};
A product-declared counted resource (W5.1 / P-RESCATALOG). The product's
catalog of `product.resource(...)` declarations, surfaced so a generated /
managed frontend can discover what resources exist and render their usage
WITHOUT a per-plan lookup.
- `scope: 'subscription'` — counted once per subscription (the common case).
- `scope: 'subject'` — counted per subject (e.g. per `project`), with
`subjectType` naming the subject; pass `{ subjectId }` to the resource
verbs so the count keys on that subject.
`cap` is the per-plan ceiling read from the active plan's
`resourceLimits[name]` (the bare resource name — NOT prefixed). It's
`number` (a numeric cap), `true` is treated as unlimited (left undefined),
and `null`/absent means uncapped/unknown.
Declaration source: packages/farthershore-js/dist/types.d.ts#L282.
export interface DeclaredResource {
name: string;
display?: string;
scope: "subscription" | "subject";
subjectType?: string;
/** Per-plan cap for this resource, when a plan declares one (numeric only). */
cap?: number | null;
}
Public export EnvironmentInfo.
Declaration source: packages/farthershore-js/dist/types.d.ts#L85.
export interface EnvironmentInfo {
id: string;
name: string;
slug: string;
/** Which sign-in flow the portal should drive: Clerk (production) or a
* platform-owned persona browser session (preview/test envs). */
authStrategy: AuthStrategy;
/** Env branch name (preview/test envs), or null for production scope. */
branch: string | null;
/** Billing provider mode for the env: "test" (no real money) or "live".
* Null when the resolve was production-scoped (no env block). The plans UI
* surfaces a "Test mode" badge when this is "test". */
stripeMode: string | null;
}
Thrown when a request was aborted (e.g. a React hook unmounted or its deps
changed before the request resolved). Callers/hooks should ignore it.
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L713.
export declare class FartherShoreAbortError extends FartherShoreError__8dbed6dcc500 {
constructor(message?: string);
}
Provides one Farther Shore client to the tree. Mount once at the app root.
Declaration source: packages/farthershore-js/dist/react/provider.d.ts#L13.
export declare function FartherShoreProvider({ client, config, children, }: FartherShoreProviderProps): import("react").JSX.Element;
Public export FartherShoreProviderProps.
Declaration source: packages/farthershore-js/dist/react/provider.d.ts#L4.
export interface FartherShoreProviderProps {
/** A pre-built client (preferred — you own its config + lifetime). */
client?: FartherShoreClient__e4fe174a542f;
/** Or a config to build one internally. Pass a STABLE object (module-level /
* memoized) so the client isn't recreated every render. */
config?: FartherShoreConfig__a72de6f5938f;
children: ReactNode;
}
Public export FsAuth.
Declaration source: packages/farthershore-js/dist/react/mounted-types.d.ts#L2.
export interface FsAuth {
strategy: AuthStrategy;
/** False while auth is initializing (Clerk JS loading / first session read). */
loaded: boolean;
/** True while the page is navigating to the primary domain for the silent
* SSO handshake (an `#fs-sso`-hinted load) — hosts keep their splash up. */
pendingSsoRedirect: boolean;
signedIn: boolean;
/** Clerk → redirect to the primary hosted sign-in (returning here);
* persona → scroll to CLI login guidance. */
signIn(): void;
/** Clerk → redirect to the primary hosted sign-UP (returning here). Use this
* for "Get started"/"Sign up" CTAs; `signIn()` is for "Log in". Strategies
* with no separate registration flow (persona, mock) alias it to signIn. */
signUp(): void;
signOut(): Promise<void>;
/** The signed-in user, normalized to {@link FsAuthUser} (Clerk OR persona),
* or null when signed out. */
user: FsAuthUser | null;
/** Re-read the session (persona only; Clerk pushes its own state). */
refresh(): void;
/** Managed-RBAC product-role keys assigned to the signed-in user
* (FAR-700), server-resolved from `GET /me` — the SDK never decodes
* tokens client-side. `[]` while auth/permissions load and when signed
* out. */
roles: string[];
/** The user's resolved permission strings (`<route-id>:read|write`
* grammar). Personal orgs / RBAC-off products resolve to `["*"]` (full
* access). `[]` while loading / signed out. */
permissions: string[];
/**
* Whether the signed-in user's permissions grant `key` under the unified
* grammar (`*` / `<subject>:*` / exact — no verb-class widening). Returns
* `false` while permissions load and when signed out.
*
* ⚠️ UX ONLY — hide affordances with it, but the gateway's `permission`
* constraint is the security boundary: a request the user isn't permitted
* to make is denied at the edge regardless of what the client renders.
*/
hasPermission(key: string): boolean;
/** Per-subscriber ComponentAccessPolicy override rows from `GET /me`
* (Wave 5) — consumed by the component-policy resolver so `<PermissionGate
* component=…>` and self-gated SDK components apply the subscriber's
* governed overrides. `[]` while loading / signed out / no overrides. */
componentPolicies: ComponentAccessPolicyRow[];
/**
* True once the Managed-RBAC claim has settled: the `/me` read answered
* (or failed → deny-defaults locked in), or the viewer is signed out /
* auth finished loading without a session. While false, permission-gated
* UI should render a pending placeholder instead of flashing a deny —
* `usePermissionGate` consumes this so `<PermissionGate>` never flickers.
*/
authzLoaded: boolean;
}
A normalized identity for the signed-in user — the same shape whether it
comes from Clerk or Core's safe test-persona session view. The persona
credential remains in an HttpOnly cookie and is never present in `raw`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L789.
export interface FsAuthUser {
/** Stable user/subscription id, or null when unknown. */
id: string | null;
firstName: string | null;
lastName: string | null;
/** Display name — Clerk's `fullName`, else `first last`, else null. */
fullName: string | null;
/** Primary email — Clerk's `primaryEmailAddress.emailAddress` (nested) or a
* flat `email`, else null. */
email: string | null;
imageUrl: string | null;
/** The original Clerk user or safe persona identity view, untouched. */
raw: unknown;
}
Builders returning TanStack-Query-compatible `{ queryKey, queryFn }` plain
objects for the SDK's main resource reads (keys, usage, billing, plans,
`me`, business). `queryKey` mirrors the Task-4 hook shape: `[resource,
businessId, organizationId, ...args]` (module-level reads that don't vary
by org — `plans`, `business` — omit the trailing `null` organizationId
segment, matching their hook counterparts `usePlans`/`useBusiness`).
Not every resource is covered here — this targets the reads apps most
commonly wire into an external cache. For anything else, build the same
shape inline:
{ queryKey: ["myThing", fs.context.businessId, id], queryFn: () => fs.resources("things").get(id) }
or reach for {@link FartherShoreClient.resources} directly via
`fsQueryOptions(fs).resource(name)` / `.resourceItem(name, id)` below.
Declaration source: packages/farthershore-js/dist/react/query-adapter.d.ts#L39.
export declare function fsQueryOptions(client: FartherShoreClient__e4fe174a542f): {
keys: {
list: () => FsQueryOptions<Awaited<ReturnType<typeof client.keys.list>>>;
};
usage: {
snapshot: (range?: UsageRange__216cd12bcfd1) => FsQueryOptions<Awaited<ReturnType<typeof client.usage.snapshot>>>;
};
billing: {
subscription: () => FsQueryOptions<Awaited<ReturnType<typeof client.billing.subscription>>>;
};
plans: {
list: () => FsQueryOptions<Awaited<ReturnType<typeof client.plans.list>>>;
};
me: () => FsQueryOptions<Awaited<ReturnType<typeof client.me>>>;
business: {
get: () => FsQueryOptions<Awaited<ReturnType<typeof client.business.get>>>;
};
/** A product-declared, quota-counted resource's list (rides the gateway).
* Generic escape hatch for resources beyond the named builders above. */
resource: <T = unknown>(name: string) => FsQueryOptions<ResourceRecord__87f0c814eb51<T>[]>;
/** A single record of a product-declared resource by id. */
resourceItem: <T = unknown>(name: string, id: string) => FsQueryOptions<ResourceRecord__87f0c814eb51<T>>;
};
A TanStack-Query-compatible plain object: `{ queryKey, queryFn }`. Every
builder below returns this shape structurally — it is never imported from
`@tanstack/react-query`, so no runtime dependency is created.
Declaration source: packages/farthershore-js/dist/react/query-adapter.d.ts#L8.
export interface FsQueryOptions<T> {
queryKey: readonly unknown[];
queryFn: () => Promise<T>;
}
Public export GatewayContextToken.
Declaration source: packages/farthershore-js/dist/types.d.ts#L803.
export interface GatewayContextToken {
/** Short-lived `fsc_` bearer accepted by the Gateway for this subscriber. */
token: string;
/** ISO timestamp when the token expires. */
expiresAt: string;
}
Public export LegalAcceptance.
Declaration source: packages/farthershore-js/dist/types.d.ts#L80.
export interface LegalAcceptance {
kind: string;
version: string;
contentHash: string;
}
Public export LegalConsentStatus.
Declaration source: packages/farthershore-js/dist/types.d.ts#L76.
export interface LegalConsentStatus {
required: boolean;
documents: LegalDocumentStatus[];
}
Public export LegalDocumentAcceptanceMode.
Declaration source: packages/farthershore-js/dist/types.d.ts#L60.
export type LegalDocumentAcceptanceMode = "agree" | "acknowledge" | "none";
Public export LegalDocumentReference.
Declaration source: packages/farthershore-js/dist/types.d.ts#L61.
export interface LegalDocumentReference {
title: string;
url: string;
acceptanceMode: LegalDocumentAcceptanceMode;
effectiveDate?: string;
}
Public export LegalDocumentStatus.
Declaration source: packages/farthershore-js/dist/types.d.ts#L67.
export interface LegalDocumentStatus extends LegalDocumentReference {
kind: string;
version: string;
contentHash: string;
consentLabel?: string;
changeNote?: string;
accepted: boolean;
acceptedAt?: string;
}
The proactive, advisory limit-state snapshot. Provider-neutral; stale-prone.
Every field is best-effort from what the SDK has already observed.
Declaration source: packages/farthershore-js/dist/react/use-limit-status.d.ts#L44.
export interface LimitStatus {
/** Always true — this surface is ADVISORY; the gateway stays authoritative.
* A UI must not use it as a hard gate, only a hint. */
advisory: true;
/** How current the picture is:
* - `fresh` — a live rate budget and/or a RECENT deny is informing it;
* - `stale` — only an OLD deny is known (older than `staleAfterMs`);
* - `unknown` — nothing observed yet. */
freshness: "fresh" | "stale" | "unknown";
/** The live rate budget (the freshest signal). */
rate: LimitStatusRate;
/** The most-recent observed limit/throttle deny, or null when none seen. */
lastDeny: LimitStatusLastDeny | null;
/** True when the most-recent deny is a CONCURRENCY saturation ("wait for a
* slot") that hasn't aged out — a hint to throttle outbound concurrency. */
concurrencySaturated: boolean;
/** True when the most-recent deny is an upstream PROVIDER throttle (adaptive /
* provider-origin) that hasn't aged out — a hint to back off / fall back. */
providerThrottled: boolean;
/** When the current advisory cooldown ends (the soonest of the rate-budget
* reset and the last deny's reset), or null when none is known. */
cooldownUntil: Date | null;
}
The last-observed deny facet (recent, advisory).
Declaration source: packages/farthershore-js/dist/react/use-limit-status.d.ts#L14.
export interface LimitStatusLastDeny {
/** The semantic class, or null for an UNKNOWN/future class (T13). */
limitClass: FsLimitClass__2d5726601b87 | null;
/** The raw class string when outside the closed mirror (T13). */
unknownLimitClass?: string;
/** The recommended client reaction. */
reaction: FsLimitReaction__06a9e09be641;
/** Platform vs provider origin. */
limitOrigin: FsLimitOrigin__1d4de1805fa7;
/** The provider-supplied reason verbatim, when relayed (adaptive deny). */
providerReason: string | null;
/** When the limit window resets, when known. */
reset: Date | null;
/** Units remaining at decision time, when known. */
remaining: number | null;
/** The cap hit, when known. */
limit: number | null;
/** The deny's HTTP status. */
status: number;
/** The deny's wire code. */
code: string;
/** The gateway decision id, when known. */
decisionId: string | null;
/** Wall-clock instant (epoch ms) the deny was observed. */
observedAt: number;
}
The live rate-budget facet of the limit picture (from `X-RateLimit-*`).
Declaration source: packages/farthershore-js/dist/react/use-limit-status.d.ts#L4.
export interface LimitStatusRate {
/** Requests left in the current window, or null when unknown. */
remaining: number | null;
/** When the window resets, or null when unknown. */
resetAt: Date | null;
/** True when the budget is KNOWN to be exhausted (`remaining <= 0`) — the next
* call would 429. Conservative: an unknown budget never saturates. */
saturated: boolean;
}
A business-level meter definition (the dimension catalog used to label/format
usage). Mirrors the wire `MeterDefinition`; only the display-relevant fields
are surfaced.
Declaration source: packages/farthershore-js/dist/types.d.ts#L15.
export interface Meter {
/** Stable dimension key (e.g. "requests", "tokens"). */
key: string;
/** Human-friendly label for the dimension. */
display: string;
/** Optional unit suffix (e.g. "ms", "tokens"). */
unit?: string;
}
A nanodollar amount off the wire: Core's decimal-integer STRING, or `null`
when the wire value was malformed (non-integer, non-string, missing). The
reader never coerces a malformed amount to `"0"` — a `null` renders as
"unavailable", never as `$0`. Format non-null values with
`format.formatNanos` (bigint) — never `Number()`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1179.
export type NanosAmount = string | null;
A service-account authority request must contain at least one permission.
Declaration source: packages/farthershore-js/dist/types.d.ts#L440.
export type NonEmptyPermissionList = [string, ...string[]];
The subscriber's full notification-preference state
(`GET /portal/businesses/:id/me/notification-preferences`). Email is the only
notifiable channel, so a preference is a single email OPT-OUT:
- `master === true` suppresses EVERY category's email;
- `categories[category] === true` additionally mutes a single category.
Email is suppressed for an event iff the master opts out OR the event's
category opts out. Category keys are the contracts notification categories
(`billing`, `usage`, …) — kept as a plain string map so the SDK stays
contracts-free; the UI joins them to `NOTIFICATION_CATEGORY_META`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1164.
export interface NotificationPreferences {
master: boolean;
categories: Record<string, boolean>;
}
The PATCH body — a PARTIAL patch of the master and/or any categories. Only
the master/categories present change; omit the rest. Send only the delta.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1170.
export interface NotificationPreferencesPatch {
master?: boolean;
categories?: Record<string, boolean>;
}
Public export NotificationPreferencesResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L221.
export interface NotificationPreferencesResult extends AsyncResult<NotificationPreferences> {
/** Apply a PARTIAL patch (send only what changed) and refetch on success. */
update(patch: NotificationPreferencesPatch): Promise<NotificationPreferences>;
}
Public export OffsetPage.
Declaration source: packages/farthershore-js/dist/types.d.ts#L535.
export interface OffsetPage<T> {
data: T[];
pagination: {
limit: number;
offset: number;
hasMore: boolean;
};
}
`POST /onboarding` result: paid plans hand back `checkoutUrl` (note: NOT
`url` like checkout-session); free plans activate inline and may include a
one-time auto-created API key (drives the auto-key banner).
Declaration source: packages/farthershore-js/dist/types.d.ts#L1104.
export interface OnboardingResult {
checkoutUrl?: string | null;
subscriber?: unknown;
/** One-time full key secret when Core auto-creates the first key. */
autoApiKey?: string | {
secret?: string;
} | null;
/** Set when the first-key mint failed AFTER the subscriber became active —
* surfaced (not swallowed) so the client can tell the user. */
autoApiKeyError?: AutoApiKeyError | null;
raw: unknown;
}
Opaque allowance display — NEVER carries a nanodollar amount. Either the
plan-authored display units (`multiplier`: the allowance is
`allowanceUnits` units, remaining/consumed are fractional units of it) or,
when the plan authored no display, the consumption fraction in basis
points.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1215.
export type OpaqueAllowanceDisplay = {
kind: "multiplier";
/** Authored allowance in display units (e.g. 5 for a "5x" plan). */
allowanceUnits: number;
/** Remaining allowance in display units, 2 decimals, as a string. */
remainingUnits: string;
/** Consumed allowance in display units, 2 decimals, as a string. */
consumedUnits: string;
} | {
kind: "fraction";
/** Consumed share of the allowance in basis points (0..10000). */
consumedBasisPoints: number;
/** Remaining share of the allowance in basis points (0..10000). */
remainingBasisPoints: number;
};
Opaque plans return allowance shape ONLY — nothing a subscriber could
divide by a known request count to recover the per-unit rate. Amounts owed
surface through the invoice, not the preview.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1277.
export interface OpaqueBillPreview {
currency: string;
disclosure: "opaque";
/** The plan's recurring fee, in cents. */
recurringFeeCents: number;
allowances: OpaqueBillPreviewAllowance[];
}
A funding allowance under opaque disclosure — kind / state / expiry plus
the authored display; no amounts.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1232.
export interface OpaqueBillPreviewAllowance {
kind: string;
/** Bucket lifecycle state — Core's `BucketState`, verbatim. */
state: BucketState;
expiresAt: string | null;
display: OpaqueAllowanceDisplay;
}
Public export OrganizationContextValue.
Declaration source: packages/farthershore-js/dist/react/organization-context.d.ts#L3.
export interface OrganizationContextValue {
/** The active org id (null = the user's default subscription / signed out). */
organizationId: string | null;
/** The requested scope: undefined auto-selects a workspace, null is the
* explicit default subscription, and a string names one workspace. */
organizationSelection: string | null | undefined;
/** The orgs through which the user holds a subscription to this product. */
organizations: SubscriptionContext[];
/** Switch the active org. Writes through to the client (token + read-cache
* bust via setOrganizationId), the persisted store, AND this context — so
* every hook depending on the reactive id refetches under the new scope. */
setOrganization(organizationId: string | null): void;
/** True while the org list is still loading. */
loading: boolean;
/** Last workspace-list error, distinct from a legitimate empty list. */
error: Error | null;
/** Re-read workspace membership after authentication changes. Awaitable so
* readiness gates never expose onboarding from a pre-auth empty snapshot. */
refetchOrganizations(): Promise<void>;
}
Holds the reactive active-org id for the tree. Seeds from the client's
current scope (which the client restored from the persisted store at boot),
then reconciles against the real subscription contexts once they load via the
single {@link resolveSelectedOrganizationId } path — so a stale persisted id
that no longer names a held subscription falls back to the server default.
Mounted by <FartherShoreProvider>; you normally never render this directly.
Declaration source: packages/farthershore-js/dist/react/organization-context.d.ts#L35.
export declare function OrganizationProvider({ children }: OrganizationProviderProps): import("react").JSX.Element;
Public export OrganizationProviderProps.
Declaration source: packages/farthershore-js/dist/react/organization-context.d.ts#L23.
export interface OrganizationProviderProps {
children: ReactNode;
}
Public export PaginatedAuditLogsResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L251.
export interface PaginatedAuditLogsResult {
/** All items accumulated across the pages loaded so far (deduped by id). */
items: AuditLogEntry[];
loading: boolean;
error: Error | null;
/** True while a `loadMore()` page is in flight (distinct from the initial
* `loading`). */
loadingMore: boolean;
/** True when the server reported another cursor — i.e. `loadMore()` will
* fetch more. */
hasMore: boolean;
/** Append the next page (the "Load older" UX). No-op while a fetch is in
* flight or when there is no next cursor. */
loadMore(): void;
/** Discard accumulated pages and re-fetch from the first page. */
reset(): void;
}
Public export PendingServiceAccountApproval.
Declaration source: packages/farthershore-js/dist/types.d.ts#L521.
export interface PendingServiceAccountApproval {
id: string;
operation: ServiceAccountApprovalOperation;
serviceAccountId: string;
requestedBy: string;
requestedPermissions: string[];
excessPermissions: string[];
createdAt: string;
serviceAccount: {
name: string;
/** Frozen grants that stay active for a pending UPDATE. */
grantedPermissions: string[];
};
}
Public export PendingServiceAccountCreateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L455.
export interface PendingServiceAccountCreateResponse {
status: "PENDING";
serviceAccountId: string;
approvalId: string;
requestedPermissions: string[];
/** A pending create has no live credential or frozen authority. */
grantedPermissions: [];
excessPermissions: string[];
eligibleApproverIds: string[];
}
Public export PendingServiceAccountUpdateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L476.
export interface PendingServiceAccountUpdateResponse {
status: "PENDING";
serviceAccountId: string;
approvalId: string;
/** Frozen grants that remain active while approval is pending. */
activePermissions: string[];
requestedPermissions: string[];
excessPermissions: string[];
eligibleApproverIds: string[];
}
Persist the active-org selection. Passing null deliberately persists the
user's default subscription rather than clearing the selection; this keeps
`setOrganizationId(null)` durable across reloads. Best-effort: a storage
failure (SSR / quota / privacy mode) is swallowed.
Declaration source: packages/farthershore-js/dist/organization.d.ts#L47.
export declare function persistOrganizationId(organizationId: string | null): void;
Safe, non-secret view of a server-owned test-persona browser session.
Declaration source: packages/farthershore-js/dist/types.d.ts#L334.
export interface PersonaAuthSession {
kind: "test-persona";
personaId: string;
userId: string;
organizationId: string | null;
displayName: string | null;
expiresAt: string;
}
Public export PinnedUsageRowsResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L189.
export interface PinnedUsageRowsResult {
/** Usage rows built from the subscriber's PINNED plan display surface. */
rows: MeterUsageRow__65f0c2813d76[];
loading: boolean;
error: Error | null;
}
A purchasable/available plan in the product catalog. Mirrors core's
`PortalPlan` (declared kind + recurring billing shape) so the template can
render the plan card, included quotas, and a subscribe button. Money for
usage lives ONLY in the bill preview ({@link BillPreview}).
Declaration source: packages/farthershore-js/dist/types.d.ts#L127.
export interface Plan {
/** Immutable `CompiledPlan.id` — the pointer passed to `subscribe()`. */
id: string;
key: string;
name: string;
description: string | null;
/**
* The builder's DECLARED plan kind. `"free"` is the free tier — a FLOOR,
* not an option: subscribers are auto-enrolled on it at sign-up and fall
* back to it when a paid plan is cancelled, so `<PlansTable>` and every
* other plan-card surface hides it rather than offering it as a choice.
* Read this field — do NOT infer it from a zero recurring fee, which is
* also true of `usage` plans that bill usage.
*/
kind: PlanKind;
/** Recurring fee, in cents (0 for free / usage plans). */
recurringFeeCents: number;
/** Billing cadence for the recurring fee + metered usage — `"month"`
* (default) or `"year"` (annual). Lets a pricing card render "$X/yr" vs
* "$X/mo" and badge annual tiers. Defaults to `"month"` when the wire DTO
* omits it (the platform omits the key for monthly plans). */
billingInterval: "month" | "year";
/** ISO 4217 currency of every money field on the plan. REQUIRED in the
* normalized model — defaults to `"USD"` when the wire DTO omits it (the
* USD-only platform omits the key today). */
currency: string;
/** Free-trial length in days (0 = no trial). */
trialDays: number;
/** Optional monthly spend cap, in cents. */
maxMonthlySpendCents: number | null;
/** Optional minimum monthly spend floor, in cents. */
minMonthlySpendCents: number | null;
/** Structural metered dimensions (no money). Empty for non-metered plans. */
meters: PlanMeter[];
/** Quota + rate-limit rules. Month-window rules are the included allowances. */
limits: PlanLimit[];
/** Optional builder-authored feature bullets shown on the plan card. */
planDetails: string[];
/** Control-plane resource limits — `key → maxCount` caps (webhooks: 5)
* such as api_keys or webhooks. Empty when the
* plan declares none. */
resourceLimits: Record<string, number>;
/**
* The plan's PUBLIC catalog terms for metered usage — the price list a buyer
* needs to compare plans, projected by Core from the served commercial
* release. `null` when the plan binds no catalog, when the served release
* carries no matching pricing policy, or when the builder declared
* `fs.disclosure.opaque`; card surfaces fall back to "priced per the
* catalog" and a docs pointer in that case.
*
* This is the only place on the SDK's plan model where per-unit money lives,
* and it is NOT an exception to the rule the rest of this module states: a
* pricing catalog is a PUBLISHED commerce term the builder authored for
* everyone, whereas a subscriber's rated usage, funding draw-down and
* projected bill remain exclusive to Core's bill preview. The SDK still
* derives NO money: it renders these rates, it never multiplies them by a
* usage count.
*/
pricingDisplay: PlanPricingDisplay | null;
}
Funding that pays for rated usage before anything is owed.
Declaration source: packages/farthershore-js/dist/types.d.ts#L232.
export interface PlanFunding {
kind: "included" | "promo" | "referral" | "prepaid";
/** Face value in minor units of {@link PlanPricingDisplay.currency}. */
amountMinor: number;
/** Whether the bucket refreshes each billing period. */
recurs: boolean;
/** The builder's authored marketing framing: the bucket is `factor`x of a
* `baseMinor` base. The base is `amountMinor / factor` by construction, so
* the label cannot misstate the allowance. */
display: {
kind: "multiplier";
factor: number;
baseMinor: number;
} | null;
}
The builder's DECLARED plan kind (`plan.kind.*` in the Business SDK):
`free` | `flat` | `usage` | `prepaid` | `hybrid` | `trial` | `custom`.
Every card decision (badge, picker, hiding the free floor) reads it —
nothing is inferred from shape.
Declaration source: packages/farthershore-js/dist/types.d.ts#L108.
export type PlanKind = PlanKindWire__a95f9171680c;
A named rate-limit / quota rule on a plan. `window.name === "month"` rules
are the included-quota allowances the usage card renders against.
Declaration source: packages/farthershore-js/dist/types.d.ts#L111.
export interface PlanLimit {
dimension: string;
window: {
type: "named";
name: string;
} | {
type: "custom";
seconds: number;
};
capacity: number;
enforcement?: "enforce" | "track";
}
A structural metered dimension on a plan — `{ dimension, kind? }`, NO
money. Rates, allowances, and the projected bill come from the bill-preview
API ({@link BillPreview}), never from the plan. Wire-faithful — the public
`PlanMeter` name re-exports the codegenned `PlanMeterWire`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L103.
export type PlanMeter = PlanMeterWire__47c3d2492e8a;
PUBLIC commerce terms for a plan's metered usage.
Declaration source: packages/farthershore-js/dist/types.d.ts#L248.
export interface PlanPricingDisplay {
/** The pricing policy key the plan's `usagePricing` binds. */
pricingPolicyKey: string;
/** Meter the policy rates. */
meterKey: string;
/** ISO 4217 currency of every amount below. */
currency: string;
/** How the plan binds the catalog. `fixed_version` plans pin `version`. */
binding: {
kind: "current" | "current_with_contract_terms" | "fixed_version";
version: number | null;
};
/** Rates in deterministic precedence order, most specific first. */
rules: PricingRule[];
/** Funding buckets declared on the plan, in authored order. */
funding: PlanFunding[];
/** What happens when funding runs out: `block` stops requests, `overage`
* keeps serving at the catalog, `prepaid` is the wallet shape. */
exhaustion: "block" | "overage" | "prepaid" | null;
}
The product's plan catalog + the subscribe/checkout mutation. The data is
the same plan list `bootstrap()` resolves; `subscribe()` starts checkout.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L172.
export interface PlansResult extends AsyncResult<Plan[]> {
subscribe(input: SubscribeInput__62c7cb21d77a): Promise<SubscribeResult__4b2d9557cede>;
/** The onboarding-view purchase path (`POST /onboarding`) — paid → checkoutUrl,
* free → inline activation (possibly with a one-time autoApiKey). */
startOnboarding(input?: StartOnboardingInput__af7cf0dea526): Promise<OnboardingResult>;
}
A catalog rate in currency-per-unit. Carries the EXACT reduced rational
alongside its decimal projection because rates like 1/3 have no finite
decimal form — render `decimal`, compare `num`/`den`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L190.
export interface PricingAmount {
num: string;
den: string;
/** `num / den` long-divided; exact where the expansion terminates. */
decimal: string;
/** True when `decimal` was truncated because the rational does not terminate. */
rounded: boolean;
}
One PUBLIC catalog rule, projected for display. `backendQuoted` rules are
never projected — a bound the backend quotes against is not a price.
Declaration source: packages/farthershore-js/dist/types.d.ts#L206.
export type PricingRule = {
/** Stable catalog-entry key — the builder's semantic rule id. */
key: string;
/** Measure this rule prices (`pages`, `tokens`). There is no per-measure
* display name anywhere in the commerce manifest, so the unit label a card
* shows is derived from this key. */
measurementKey: string;
/** Catalog-item namespace, when the rule is provider/model scoped. */
item: {
provider: string;
model: string;
modality?: string;
} | null;
/** Dimension conditions that select this rule (`mode = ocr`). */
where: Array<{
dimensionKey: string;
value: string;
}>;
} & ({
kind: "perUnit";
amount: PricingAmount;
} | {
kind: "graduated" | "volume";
tiers: PricingTier[];
});
One bracket of a tiered catalog rule. `upTo` is the inclusive cumulative
upper bound as a decimal string, `null` on the open-ended final tier.
Declaration source: packages/farthershore-js/dist/types.d.ts#L200.
export interface PricingTier {
upTo: string | null;
amount: PricingAmount;
}
Promo-code flavour on an applied subscriber promo. Mirrors the wire
`PromoCodeKind` (`percent_off` | `amount_off` | `free_months`); kept as an
open union so a producer-side addition doesn't break the typed read.
Declaration source: packages/farthershore-js/dist/types.d.ts#L812.
export type PromoCodeKind = "percent_off" | "amount_off" | "free_months" | (string & {});
One derived-catalog entry (`GET /me/rbac/catalog`): the permissions a
product's routes make grantable, grouped by route subject. Never authored —
derived from the product's accepted spec.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1053.
export interface RbacCatalogEntry {
subject: string;
/** Optional display title for the subject. */
title?: string;
permissions: string[];
}
One configurable role (`/me/rbac/roles`), template-seeded or custom.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1035.
export interface RbacRole {
roleKey: string;
name: string;
/** Permission strings in the `<subject>:read|write` grammar, or `"*"`. */
permissions: string[];
/** "ACCOUNT" rows are the membership-tier enforcement source: their
* permissions are editable but their identity is fixed — no rename,
* delete, default assignment, or credential binding. Absent ⇒ "CUSTOM". */
kind?: "CUSTOM" | "ACCOUNT";
/** ACCOUNT rows only: the full subscriber vocabulary — the editable
* option set (restoring a removed verb needs the catalog, not just the
* row's current grants). */
vocabulary?: string[];
createdAt?: string;
}
One assignable role, as listed on `GET /me/team` (`availableRoles`).
Declaration source: packages/farthershore-js/dist/types.d.ts#L1023.
export interface RbacRoleSummary {
roleKey: string;
name: string;
}
Org-level Managed-RBAC settings (`GET|PUT /me/rbac/settings`).
Declaration source: packages/farthershore-js/dist/types.d.ts#L1028.
export interface RbacSettings {
/** Whether role permissions are enforced for this org's user tokens. */
enabled: boolean;
/** Role auto-assigned to members with no explicit assignment. */
defaultRoleKey?: string;
}
The persisted active-org id, or null when the user chose the default
subscription, no selection is stored, or storage is unavailable (SSR).
Declaration source: packages/farthershore-js/dist/organization.d.ts#L40.
export declare function readPersistedOrganizationId(): string | null;
The composed read scope: the client, its resolved businessId, and the
reactive active-org id.
Declaration source: packages/farthershore-js/dist/react/scope.d.ts#L4.
export interface ReadScope {
/** The client from context (see {@link useFartherShore}). */
fs: FartherShoreClient__e4fe174a542f;
/** The client's resolved business id (`fs.context.businessId`), or null
* before `bootstrap()`/`resolve()` has discovered it. */
businessId: string | null;
/** The reactive active-org id (see {@link useReactiveOrganizationId}). Null
* outside an `<OrganizationProvider>` or when no org is selected. */
organizationId: string | null;
}
Public export RequestPrecheck.
Declaration source: packages/farthershore-js/dist/react/use-limits.d.ts#L33.
export interface RequestPrecheck {
/** True when the live rate-limit budget says the next gateway call would be
* throttled (remaining is known and 0) — disable the action / queue it. */
blocked: boolean;
/** Requests left in the current window, or null when unknown. */
remaining: number | null;
/** When the window resets, or null when unknown. */
resetAt: Date | null;
}
Resolve the active organization id from the available subscription contexts,
with a documented precedence (W9.1c). This is the SINGLE resolution path —
used at client boot AND by `<OrgSwitcher>` — so "which org am I in?" has one
answer everywhere.
Precedence (first match wins):
1. `requested` — an explicit caller/persisted choice. `null` means
the user's default subscription (no organization
header) and is preserved as such. A string wins
only if it still names a real context; a stale
persisted id falls through to the defaults.
2. entitled context — prefer active compiled customer access. If the server's
selection is entitled it wins; otherwise use the
first entitled workspace. This prevents a signed-
in customer from landing in an empty personal org
while their entitled team workspace is available.
3. server-default — `selectedOrganizationId` then `defaultOrganizationId`
reported on the contexts payload, IF it names a
real context.
4. `isDefault` flag — the first context flagged `isDefault`.
5. first — the first context in the list.
Returns `null` when there are no contexts at all (signed out / no
subscriptions), or when the caller explicitly requests the user's default
subscription (no `x-fs-organization-id` header).
Declaration source: packages/farthershore-js/dist/organization.d.ts#L29.
export declare function resolveSelectedOrganizationId(contexts: SubscriptionContextsResult | null | undefined, requested?: string | null): string | null;
Pick the cheapest upgrade for a plan-limit block ({@link LimitExceededError}).
For a LIMIT, with a known dimension, the cheapest more-expensive plan that
ACTUALLY RAISES that dimension's cap — never a plan whose cap equals or
undercuts the current one (that would be a false "raise to N" promise).
Returns null when no costlier plan raises the dimension, so the UI can render
a neutral "contact support" message instead. The next-tier fallback (with
raisesTo:null) is reserved for the compiled-ordinal case where the dimension
can't be named.
The invariant holds: only ever recommend a HIGHER plan — never a
same-price/cheaper sibling.
Declaration source: packages/farthershore-js/dist/react/use-upgrade.d.ts#L27.
export declare function resolveUpgrade(error: UpgradeResolvable, currentPlan: Plan | null, plans: Plan[]): UpgradeTarget | null;
Public export ResourcesListResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L301.
export interface ResourcesListResult<T = unknown> extends AsyncResult<ResourceRecord__87f0c814eb51<T>[]> {
/** Create a record — throws `LimitExceededError` at the plan cap. */
create(payload: T): Promise<ResourceRecord__87f0c814eb51<T>>;
/** Replace a record's payload. */
update(id: string, payload: T): Promise<ResourceRecord__87f0c814eb51<T>>;
/** Delete a record (frees one unit of the quota). */
remove(id: string): Promise<void>;
}
`POST /me/restore` — the platform performs the un-cancel: a paid sub's
scheduled `cancel_at_period_end` is lifted on the provider, a free
CANCELLED sub is flipped back to ACTIVE inline. Like cancel, there is no
hosted-page hand-off — the caller gets the subscription back, and
`cancelAtPeriodEnd` on it is what the platform read AFTER the un-cancel.
A `false` here is the proof the notice should be gone.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1134.
export interface RestoreSubscriptionResult {
subscription?: unknown;
/** The platform's post-restore reading. `false` is the success signal; the
* field is `null` only when Core's response carried no subscription state
* to read it from — never guessed. */
cancelAtPeriodEnd: boolean | null;
raw: unknown;
}
Repeatable metadata for a managed, organization-owned service account.
Declaration source: packages/farthershore-js/dist/types.d.ts#L425.
export interface ServiceAccount {
id: string;
name: string;
state: ServiceAccountProvisioningState;
requestedPermissions: string[];
grantedPermissions: string[];
createdBy: string | null;
approvedBy: string | null;
createdAt: string;
activatedAt: string | null;
revokedAt: string | null;
usageLimits?: ServiceAccountUsageLimitRequest[];
credentialApprovals: ServiceAccountApprovalSummary[];
}
Whether an approval creates a new account or replaces an active grant snapshot.
Declaration source: packages/farthershore-js/dist/types.d.ts#L382.
export type ServiceAccountApprovalOperation = "CREATE" | "UPDATE";
Public export ServiceAccountApprovalResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L508.
export type ServiceAccountApprovalResponse = ApprovedServiceAccountCreateResponse | ApprovedServiceAccountUpdateResponse;
Public export ServiceAccountApprovalSummary.
Declaration source: packages/farthershore-js/dist/types.d.ts#L383.
export interface ServiceAccountApprovalSummary {
id: string;
operation: ServiceAccountApprovalOperation;
requestedBy: string;
requestedPermissions: string[];
excessPermissions: string[];
createdAt: string;
}
Public export ServiceAccountCreateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L475.
export type ServiceAccountCreateResponse = ActiveServiceAccountCreateResponse | PendingServiceAccountCreateResponse;
Public export ServiceAccountDenyResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L518.
export interface ServiceAccountDenyResponse {
status: "DENIED";
}
Public export ServiceAccountProvisioningData.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L30.
export interface ServiceAccountProvisioningData {
accounts: ServiceAccount[];
approvals: PendingServiceAccountApproval[];
}
Durable provisioning state for an organization-owned service account.
Declaration source: packages/farthershore-js/dist/types.d.ts#L380.
export type ServiceAccountProvisioningState = "PENDING" | "ACTIVE";
Public export ServiceAccountRotationResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L509.
export interface ServiceAccountRotationResponse {
status: "ACTIVE";
serviceAccountId: string;
revokedKeyId: string;
apiKeyId: string;
/** One-time replacement secret. */
plaintext: string;
grantedPermissions: string[];
}
Managed service-account lifecycle. Reads accounts and the caller's eligible
approvals together so every mutation can refresh both views atomically from
the component's perspective.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L39.
export interface ServiceAccountsResult extends AsyncResult<ServiceAccountProvisioningData> {
create(input: CreateServiceAccountInput): Promise<ServiceAccountCreateResponse>;
update(serviceAccountId: string, input: UpdateServiceAccountInput): Promise<ServiceAccountUpdateResponse>;
rotate(serviceAccountId: string): Promise<ServiceAccountRotationResponse>;
revoke(serviceAccountId: string): Promise<void>;
approve(approvalId: string, input?: ApproveServiceAccountInput): Promise<ServiceAccountApprovalResponse>;
deny(approvalId: string): Promise<ServiceAccountDenyResponse>;
}
Public export ServiceAccountUpdateResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L492.
export type ServiceAccountUpdateResponse = ActiveServiceAccountUpdateResponse | PendingServiceAccountUpdateResponse;
Public export ServiceAccountUsageLimitMode.
Declaration source: packages/farthershore-js/dist/types.d.ts#L391.
export type ServiceAccountUsageLimitMode = "BLOCK" | "NOTIFY";
Discriminated to mirror `portalServiceAccountUsageLimitRequestSchema` exactly
(contracts): a NOTIFY limit REQUIRES `notifyAtPct`; a BLOCK limit forbids it;
exactly one of `limitUnits`/`limitCents` is set. This keeps the public type as
strict as its Zod validator — invalid mode/threshold combos are compile errors,
not just runtime 400s. Parity is pinned by `service-account-contract-drift.test.ts`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L399.
export type ServiceAccountUsageLimitRequest = {
quantity: string;
limitUnits: number;
limitCents?: never;
mode: "BLOCK";
notifyAtPct?: never;
} | {
quantity: string;
limitUnits: number;
limitCents?: never;
mode: "NOTIFY";
notifyAtPct: number;
} | {
quantity: string;
limitUnits?: never;
limitCents: number;
mode: "BLOCK";
notifyAtPct?: never;
} | {
quantity: string;
limitUnits?: never;
limitCents: number;
mode: "NOTIFY";
notifyAtPct: number;
};
Public export Session.
Declaration source: packages/farthershore-js/dist/types.d.ts#L326.
export interface Session {
authenticated: boolean;
subscriber: Subscriber | null;
/** Verified browser-session identity. Present only for a server-owned test
* persona cookie; Clerk sessions expose their user through the Clerk bridge. */
authSession: PersonaAuthSession | null;
}
Public export SessionResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L11.
export interface SessionResult extends AsyncResult<Session> {
signOut(): Promise<void>;
}
The subscriber's current monthly spend cap (cents), or null when none is set
/ signed out (P-SPENDCAP-READ). Reads the cap surfaced on the `/me` context.
`setSpendCap` writes it and the cap re-reads. CAVEAT: STORED-not-ENFORCED
today — UI copy must not promise hard spend enforcement.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L151.
export interface SpendCapResultHook extends AsyncResult<number | null> {
setSpendCap(input: {
maxMonthlySpendCents: number | null;
}): Promise<SpendCapResult__395300e78371>;
}
Public export Subscriber.
Declaration source: packages/farthershore-js/dist/types.d.ts#L315.
export interface Subscriber {
/** Lifecycle status (e.g. ONBOARDING | ACTIVE | SUSPENDED). */
status: string | null;
/** Denormalized plan key for display. */
planKey: string | null;
/** Immutable CompiledPlan id currently active for this subscriber. */
compiledPlanId: string | null;
/** True only after the selected environment's gateway has the exact active
* subscription projection. */
gatewayReady?: boolean;
}
An active promotional code applied to a subscriber. Mirrors core's
`PortalSubscriberContext.subscriber.activePromo`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L815.
export interface SubscriberActivePromo {
id: string;
code: string;
kind: PromoCodeKind;
/** Discount magnitude (percent or cents, per `kind`), or null/absent. */
amount?: number | null;
/** How many billing periods the promo applies for. */
durationMonths: number;
/** ISO timestamp the promo stops applying, or null. */
activeUntil?: string | null;
/** ISO timestamp the promo was applied, or null. */
appliedAt?: string | null;
}
Full `GET /me` context: the subscriber (null = signed-in user has no
subscriber record for the selected org → onboarding) plus the
eligibility-scoped plan list (NOT identical to the public catalog).
Declaration source: packages/farthershore-js/dist/types.d.ts#L897.
export interface SubscriberContext {
subscriber: SubscriberDetail | null;
availablePlans: Plan[];
/**
* E1 — the subscriber's PINNED plan, resolved server-side from the
* subscription's pinned CompiledPlan version (NOT the catalog head — a
* pinned older version may not appear in `availablePlans` at all).
*
* Tri-state for old-Core back-compat:
* - `Plan` — resolved pinned plan.
* - `null` — Core resolved it: there IS no pinned plan (no
* subscription). Do NOT fall back to guessing.
* - `undefined` — the wire field was ABSENT (pre-E1 Core). Only here may
* a consumer fall back to matching `availablePlans` by
* `subscriber.compiledPlanId` (deprecated path).
*/
currentPlan?: Plan | null;
/** Managed-RBAC product-role keys assigned to the CALLER within the org
* (FAR-698/FAR-700). Server-resolved on `GET /me` — the same row-backed
* source the gateway-token mint uses; the SDK never decodes tokens.
* Empty for pre-RBAC responses. */
roles: string[];
/** The caller's resolved permission strings (`<subject>:read|write`
* grammar). `["*"]` means Managed RBAC is off or the caller is an OWNER;
* personal-org members receive the same resolved permission sets as team-org
* members. Client-side gating over these is UX ONLY — the gateway's
* `permission` constraint is the security boundary. */
permissions: string[];
/** Reviewed product permissions explicitly denied by the subscriber's
* effective roles. Present on current Core responses. */
deniedPermissions?: string[];
/** Current product permissions that were not reviewed by the effective
* roles and therefore inherit the safe product-evolution default of allow.
* Platform/account permissions are never included. */
unassignedProductPermissions?: string[];
/** Per-subscriber ComponentAccessPolicy override rows (Permissions Kernel,
* Wave 5) — `{componentKey, requiredPermission, gateMode}` as core emits
* them. Consumed by the SDK's component-policy resolver; `[]` when the
* subscriber has no overrides (or on older responses). */
componentAccessPolicies: ComponentAccessPolicyRow[];
/** Current legal acceptance state for this subscriber/org, when served by
* Core. Absent on older responses. */
legalConsent?: LegalConsentStatus;
raw: unknown;
}
Rich subscriber detail from `GET /me` — superset of {@link Subscriber} with
the lifecycle/billing fields the account pages render. Extra Core fields ride
along untyped.
Declaration source: packages/farthershore-js/dist/types.d.ts#L859.
export interface SubscriberDetail {
id?: string;
status: string | null;
planKey: string | null;
compiledPlanId: string | null;
/** True only after the selected environment's gateway has the exact active
* subscription projection. */
gatewayReady?: boolean;
/** Resource limits on the subscriber's pinned plan, not the latest catalog. */
resourceLimits?: Record<string, number>;
/** Per-dimension meter map (`dimension → unit`) on the subscriber's PINNED
* compiled plan — the billing shape the subscriber is actually on. */
dimensions?: Record<string, number>;
/** The ordered list of meter dimensions the usage tab should display,
* authored by the pinned plan. `rules[].d` indexes into this array. */
displayDims?: string[];
/** Pinned-plan rate-limit / quota allowances (the source of truth for
* included quotas — see {@link SubscriberPinnedRule}). */
rules?: SubscriberPinnedRule[];
/** Stripe-driven lifecycle (e.g. ACTIVE | TRIALING | PAST_DUE | CANCELLED). */
subscriptionLifecycle?: string | null;
/** Stripe-synced trial end (ISO) — drives the trial banner countdown. */
trialEndsAt?: string | null;
/** True when a paid cancel is scheduled for period end ("Renew" un-schedules). */
cancelAtPeriodEnd?: boolean | null;
/** A scheduled plan transition (downgrades apply at period end). */
scheduledTransition?: SubscriberScheduledTransition | null;
/** An active promotional code applied to the subscription, when present. */
activePromo?: SubscriberActivePromo | null;
/** P-SPENDCAP-READ (W6.4) — the subscriber-set monthly spend cap, in cents,
* or null when none is set. STORED-not-ENFORCED today (held in
* `Subscription.customMetadata`, pending the rate-limit migration). */
maxMonthlySpendCents?: number | null;
[k: string]: unknown;
}
One pinned-plan display rule from `GET /me` (`subscriber.rules`). A
rate-limit / quota allowance in the compiled-entitlement compact form:
`d` = dimension index, `w` = window seconds, `c` = capacity. The usage card
reads the `month`-window (`w === 2592000`) rules as the included quotas the
subscriber is ACTUALLY billed under — not the latest catalog meter list,
which may have drifted from the subscriber's pinned plan.
Declaration source: packages/farthershore-js/dist/types.d.ts#L848.
export interface SubscriberPinnedRule {
/** Dimension index into `displayDims`. */
d: number;
/** Window length in seconds (a 30-day month is 2592000). */
w: number;
/** Capacity (the included allowance for the window). */
c: number;
}
A scheduled plan transition on a subscriber. Mirrors core's
`PortalSubscriberContext.subscriber.scheduledTransition` — richer than
{@link SubscriptionScheduledTransition} (carries the resolved plan name +
type).
Declaration source: packages/farthershore-js/dist/types.d.ts#L832.
export interface SubscriberScheduledTransition {
compiledPlanId: string | null;
planName: string | null;
planType: string | null;
/** ISO timestamp the transition takes effect. */
effectiveAt: string;
/** Movement direction (`CANCEL` | `UPGRADE` | `DOWNGRADE` | `SIDEGRADE`),
* open to producer-side additions. */
kind: string;
}
The consumer's current subscription for this product. Mirrors core's
`PortalSubscriptionDto` (lifecycle + billing state + scheduled transition)
mapped to the SDK's camelCase domain convention. The widened fields degrade
to safe defaults when the wire DTO is lean (`null` / `false`).
Declaration source: packages/farthershore-js/dist/types.d.ts#L739.
export interface Subscription {
id: string;
/** Display lifecycle status (e.g. ACTIVE | TRIALING | PAST_DUE). Falls back
* across `status` / `lifecycle` on the wire. */
status: string;
planKey: string | null;
planName: string | null;
/** Owning product id, or null when absent on a lean DTO. */
businessId: string | null;
/** Immutable `CompiledPlan.id` currently active, or null. */
compiledPlanId: string | null;
/** Richer lifecycle string straight off the row (may equal `status`). */
lifecycle: string | null;
/** Payment health (`ok` | `past_due` | `incomplete` | …), or null when the
* DTO doesn't carry it (free subs). */
paymentHealth: string | null;
/** ISO start of the current billing period, or null. */
currentPeriodStart: string | null;
/** ISO end of the current billing period, or null. */
currentPeriodEnd: string | null;
/** True when a paid cancel is scheduled for period end. */
cancelAtPeriodEnd: boolean;
/** ISO trial end — drives the trial countdown. */
trialEndsAt: string | null;
/** ISO timestamp the subscription was canceled, or null. */
canceledAt: string | null;
/** A scheduled plan transition, or null when none is pending. */
scheduledTransition: SubscriptionScheduledTransition | null;
/** Whether the subscriber has a Stripe customer (can open the billing
* portal). Free subs that never touched Stripe are `false`. */
canManageInStripe: boolean;
/**
* Whether there is actually something here to cancel — SERVER-DECIDED.
*
* A subscription on a `free`-kind plan has no paid, Stripe-managed
* subscription behind it, so "cancel" has no meaning. The client cannot work
* this out on its own (the portal DTO always carries a real subscription id,
* so "nothing to cancel" looks identical to a lean wire body), which is why
* core answers it.
*
* `null` means the server did not say — treated as CANCELLABLE so an older
* core never strands a paying subscriber with no way to cancel.
*/
cancellable: boolean | null;
/** The full platform subscription DTO (large + evolving) for advanced reads. */
raw: unknown;
}
One org through which the user holds a subscription to this product.
Declaration source: packages/farthershore-js/dist/types.d.ts#L955.
export interface SubscriptionContext {
organizationId: string;
/** Org display name — matches core's wire field (`name`, NOT
* `organizationName`; see apps/core/src/routes/portal-customer/shared.ts). */
name?: string | null;
isDefault?: boolean;
/** Existing subscriber row for this business/org pair. A non-null value
* means this workspace already owns customer state for the product. */
subscriberId?: string | null;
/** Authoritative active-plan entitlement for the selected environment. */
hasEntitlement?: boolean;
[k: string]: unknown;
}
Public export SubscriptionContextsResult.
Declaration source: packages/farthershore-js/dist/types.d.ts#L968.
export interface SubscriptionContextsResult {
contexts: SubscriptionContext[];
defaultOrganizationId: string;
selectedOrganizationId: string | null;
}
A scheduled plan transition on a subscription (downgrades apply at period
end). Mirrors core's `PortalSubscriptionDto.scheduledTransition`.
Declaration source: packages/farthershore-js/dist/types.d.ts#L726.
export interface SubscriptionScheduledTransition {
/** Immutable `CompiledPlan.id` the subscription moves to, or null. */
compiledPlanId: string | null;
/** ISO timestamp the transition takes effect, or null. */
effectiveAt: string | null;
/** Movement direction (`CANCEL` | `UPGRADE` | `DOWNGRADE` | `SIDEGRADE`),
* open to producer-side additions. */
kind: string | null;
}
A pending subscriber-team invitation (`GET|POST /me/team/invites`).
Declaration source: packages/farthershore-js/dist/types.d.ts#L999.
export interface TeamInvitation {
id: string;
email: string;
role: TeamRole;
/** Managed-RBAC product roles granted on accept. */
businessRoleKeys: string[];
status: string;
invitedByExternalId?: string | null;
expiresAt: string;
createdAt: string;
}
Result of accepting an invitation.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1017.
export interface TeamInvitationAccepted {
membershipId: string;
role: TeamRole;
businessRoleKeys: string[];
}
The one-time create response: the invitation plus the raw token (delivered
by email; surfaced here once for the off-app / no-provider path).
Declaration source: packages/farthershore-js/dist/types.d.ts#L1012.
export interface TeamInvitationCreated extends TeamInvitation {
token: string;
emailSent: boolean;
}
Team read result — `ok:false` (with `error`) drives the read-only banner.
Declaration source: packages/farthershore-js/dist/types.d.ts#L990.
export interface TeamListResult {
ok: boolean;
members: TeamMember[];
/** The org's assignable Managed-RBAC role list (FAR-698) — what the
* per-member role multi-select offers. Empty when RBAC is unused. */
availableRoles?: RbacRoleSummary[];
error?: string;
}
Public export TeamMember.
Declaration source: packages/farthershore-js/dist/types.d.ts#L974.
export interface TeamMember {
id: string;
userExternalId: string;
role: TeamRole;
/** Managed-RBAC product-role keys assigned to this member (FAR-698).
* Absent on pre-RBAC responses. */
businessRoleKeys?: string[];
/** Assigned keys whose role row no longer exists (deleted roles leave
* assignments in place — resolution ignores them). Drives the portal's
* stale-role warning. */
staleRoleKeys?: string[];
createdAt?: string;
updatedAt?: string;
[k: string]: unknown;
}
Public export TeamResult.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L212.
export interface TeamResult extends AsyncResult<TeamListResult> {
updateRole(membershipId: string, role: TeamRole): Promise<TeamMember>;
remove(membershipId: string): Promise<void>;
/** Set-replace a member's Managed-RBAC product-role assignment (FAR-700);
* `[]` clears it. Refetches the list on success. UX only — the edge
* `permission` constraint is the security boundary. */
assignRoles(membershipId: string, roles: string[]): Promise<TeamMember>;
}
Public export TeamRole.
Declaration source: packages/farthershore-js/dist/types.d.ts#L973.
export type TeamRole = "OWNER" | "ADMIN" | "VIEWER";
Public export TransparentBillPreview.
Declaration source: packages/farthershore-js/dist/types.d.ts#L1257.
export interface TransparentBillPreview {
currency: string;
disclosure: "transparent";
/** The plan's recurring fee, in cents. */
recurringFeeCents: number;
/** Per-rating-window engine totals. */
windows: BillPreviewWindow[];
totals: {
/** Nanodollars, decimal strings (null = unavailable). */
ratedNanos: NanosAmount;
fundedNanos: NanosAmount;
receivableNanos: NanosAmount;
};
allowances: BillPreviewAllowance[];
/** All-zero counts mean `totals` IS the whole bill. */
usageRating: BillPreviewUsageRating;
}
Public export UpdateServiceAccountInput.
Declaration source: packages/farthershore-js/dist/types.d.ts#L447.
export interface UpdateServiceAccountInput {
requestedPermissions?: NonEmptyPermissionList;
usageLimit?: ServiceAccountUsageLimitRequest | null;
}
Strict PUT body. Scope, subject, and quantity are immutable; at least one
value or mode/threshold field is required.
Declaration source: packages/farthershore-js/dist/types.d.ts#L637.
export type UpdateUsageLimitInput = (UsageLimitUpdateValue__e8f19d3e563b & UsageLimitUpdateMode__0a6925ca669e) | (UsageLimitNoUpdateValue__cd3ce2b61e4f & UsageLimitExplicitUpdateMode__577df72501b7) | (UsageLimitNoUpdateValue__cd3ce2b61e4f & {
mode?: never;
notifyAtPct: number | null;
});
What `resolveUpgrade` accepts — a plan-limit block (`dimension` +
`currentCapacity`, optionally its `limitClass`).
Declaration source: packages/farthershore-js/dist/react/use-upgrade.d.ts#L12.
export type UpgradeResolvable = Pick<LimitExceededError__7844c601e6fd, "dimension" | "currentCapacity" | "limitClass"> | Pick<LimitExceededError__7844c601e6fd, "dimension" | "currentCapacity">;
Public export UpgradeTarget.
Declaration source: packages/farthershore-js/dist/react/use-upgrade.d.ts#L3.
export interface UpgradeTarget {
/** The plan to upgrade to (pass `plan.id` to `billing.changePlan`). */
plan: Plan;
/** The new cap for the offending dimension, or null when unlimited/unknown.
*/
raisesTo: number | null;
}
Public, contracts-free projection of the Stage 1 portal usage-limit DTOs.
Exact parity is pinned in `test/usage-limits.test.ts`; the private contracts
workspace package must never leak into this published SDK's declarations.
Declaration source: packages/farthershore-js/dist/types.d.ts#L546.
declare const USAGE_LIMIT_SCOPES: readonly ["ORG", "MEMBER", "SERVICE_ACCOUNT"];
Public export USAGE_LIMIT_STRATEGIES.
Declaration source: packages/farthershore-js/dist/types.d.ts#L553.
declare const USAGE_LIMIT_STRATEGIES: readonly ["fixed_window", "sliding_window"];
Public export USAGE_TRAFFIC_CLASSES.
Declaration source: packages/farthershore-js/dist/types.d.ts#L650.
declare const USAGE_TRAFFIC_CLASSES: readonly ["customer_operation", "control_plane", "admin_internal", "background_job", "webhook", "healthcheck", "unclassified"];
Whether usage is billed as a pure request COUNT or weighted USAGE. Drives the
meter label ("Requests" vs "Usage"); computed server-side.
Declaration source: packages/farthershore-js/dist/types.d.ts#L649.
export type UsageBillingBasis = "requests" | "usage";
Public export UsageChargeableOutcomes.
Declaration source: packages/farthershore-js/dist/types.d.ts#L654.
export type UsageChargeableOutcomes = "success_only" | "success_and_partial" | "attempted" | "trusted_actual_usage_only";
Public export UsageData.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L59.
export interface UsageData {
summary: UsageSummary;
events: UsageEvent[];
/** Whether the `requests` total reads as an event COUNT ("requests") or a
* weighted unit SUM ("usage") — drives the Requests-vs-Usage display so a
* per-call meter doesn't mislabel a summed total as a request count. */
billingBasis: UsageBillingBasis;
/** True when `summary` is an EXACT period total; false when it's a bounded
* sample (the UI flags "approximate"). */
exact: boolean;
/** Event count behind the `summary` total over the period. */
sampledEvents: number;
/** ISO bounds of the period the `summary` covers, or null. */
periodStart: string | null;
periodEnd: string | null;
/** Aggregated advisory UsagePolicy from the freshest event, or null. */
usagePolicy: UsagePolicyAdvisory | null;
}
Public export UsageEvent.
Declaration source: packages/farthershore-js/dist/types.d.ts#L679.
export interface UsageEvent {
id: string;
timestamp: string;
operation: string;
apiKeyPrefix: string | null;
statusCode: number | null;
status: "success" | "error";
/** Event kind (e.g. "api"); shown as the row Type. */
type: string | null;
latencyMs: number | null;
/** Canonical per-event meter values, keyed by product-declared meter. */
dimensions: UsageEventDimensions;
/** Compatibility aliases for common legacy portal displays. */
requests: number | null;
tokens: number | null;
/** Advisory UsagePolicy state confirmed or relayed by the gateway/core. The
* frontend decides nothing from this; it is only for rendering stale-tolerant
* labels, cooldowns, and prompts. */
usagePolicy?: UsagePolicyAdvisory;
}
Public export UsageEventDimensions.
Declaration source: packages/farthershore-js/dist/types.d.ts#L646.
export type UsageEventDimensions = Record<string, number | null>;
Public export UsageLimit.
Declaration source: packages/farthershore-js/dist/types.d.ts#L580.
export type UsageLimit = UsageLimitSubject & UsageLimitValue & {
id: string;
quantity: string;
mode: UsageLimitMode;
period: "BILLING_PERIOD";
/** Present only for NOTIFY rows. */
notifyAtPct?: number;
ceiling: UsageLimitCeiling;
/** Present when the edge accounts this limit on a non-default window. */
effectiveWindow?: UsageLimitEffectiveWindow;
createdBy: string | null;
createdAt: string;
updatedAt: string;
};
Public export UsageLimitCeiling.
Declaration source: packages/farthershore-js/dist/types.d.ts#L549.
export interface UsageLimitCeiling {
limitUnits?: number;
limitCents?: number;
}
Public export UsageLimitDeleteResult.
Declaration source: packages/farthershore-js/dist/types.d.ts#L641.
export interface UsageLimitDeleteResult {
id: string;
deleted: true;
}
READ-ONLY: how the limit is actually accounted at the edge. Builder-owned
(inherited from the plan's own rule for the dimension); a `sliding_window`
makes the ceiling a rolling horizon of the period's length instead of one
that resets at the period boundary. Never writable by the subscriber.
Declaration source: packages/farthershore-js/dist/types.d.ts#L559.
export interface UsageLimitEffectiveWindow {
strategy: UsageLimitStrategy;
periodSeconds: number;
}
Public export UsageLimitListResponse.
Declaration source: packages/farthershore-js/dist/types.d.ts#L594.
export type UsageLimitListResponse = OffsetPage<UsageLimit>;
Public export UsageLimitMode.
Declaration source: packages/farthershore-js/dist/types.d.ts#L548.
export type UsageLimitMode = "BLOCK" | "NOTIFY";
Public export UsageLimitProfile.
Declaration source: packages/farthershore-js/dist/types.d.ts#L653.
export type UsageLimitProfile = "customer_usage" | "business_capacity" | "control_plane" | "admin_internal" | "platform_abuse_only" | "healthcheck" | "none";
Public export UsageLimitScope.
Declaration source: packages/farthershore-js/dist/types.d.ts#L547.
export type UsageLimitScope = (typeof USAGE_LIMIT_SCOPES)[number];
Subscriber-managed per-actor usage limits. Every successful mutation waits
for its authoritative list refetch to commit before its promise resolves.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L53.
export interface UsageLimitsResult extends AsyncResult<UsageLimit[]> {
create(input: CreateUsageLimitInput): Promise<UsageLimit>;
update(limitId: string, input: UpdateUsageLimitInput): Promise<UsageLimit>;
remove(limitId: string): Promise<void>;
}
Public export UsageLimitStrategy.
Declaration source: packages/farthershore-js/dist/types.d.ts#L554.
export type UsageLimitStrategy = (typeof USAGE_LIMIT_STRATEGIES)[number];
Public export UsageLimitSubject.
Declaration source: packages/farthershore-js/dist/types.d.ts#L570.
export type UsageLimitSubject = {
scope: "ORG";
subjectId?: never;
} | {
scope: "MEMBER";
subjectId: string;
} | {
scope: "SERVICE_ACCOUNT";
subjectId: string;
};
Public export UsageLimitValue.
Declaration source: packages/farthershore-js/dist/types.d.ts#L563.
export type UsageLimitValue = {
limitUnits: number;
limitCents?: never;
} | {
limitCents: number;
limitUnits?: never;
};
Public export UsagePolicyAdvisory.
Declaration source: packages/farthershore-js/dist/types.d.ts#L655.
export interface UsagePolicyAdvisory {
/** Gateway-resolved policy id, when the usage payload includes one. */
usagePolicyId: string | null;
/** Known traffic class; null when a newer gateway sends a class this SDK
* does not know yet. See `unknownTrafficClass` for the preserved raw value. */
trafficClass: UsageTrafficClass | null;
unknownTrafficClass?: string;
policySource: UsagePolicySource | null;
limitProfile: UsageLimitProfile | null;
customerBillable: boolean | null;
providerCostTracked: boolean | null;
chargeableOutcomes: UsageChargeableOutcomes | null;
meterKey: string | null;
cooldownResetAt: number | null;
retryAfterSeconds: number | null;
freeButLimited: boolean;
providerCost: boolean;
upgradePrompt: boolean;
creditPrompt: boolean;
genericMessage: string;
/** Raw gateway/core policy fields. Preserved for forward-compatible UIs and
* debugging; advisory only and never an enforcement input. */
raw: Record<string, unknown>;
}
Public export UsagePolicyData.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L94.
export type UsagePolicyData = UsageData;
Public export UsagePolicySource.
Declaration source: packages/farthershore-js/dist/types.d.ts#L652.
export type UsagePolicySource = "declared" | "inherited" | "defaulted" | "inferred";
A single round-trip's worth of usage: per-dimension totals, the recent
events, and the billing basis.
Declaration source: packages/farthershore-js/dist/types.d.ts#L701.
export interface UsageSnapshot {
summary: UsageSummary;
events: UsageEvent[];
billingBasis: UsageBillingBasis;
/** Whether `summary` is an EXACT total over the whole period (`true`, the
* DB-side aggregate) or an approximation from a bounded event sample
* (`false`). A `false` here means the UI should flag the figure as
* approximate. Defaults to `true` (additive — older Cores omit it). */
exact: boolean;
/** Number of usage events the `summary` total was computed from over the
* period. With `exact: true` this is the true event count; with
* `exact: false` it's the sampled (capped) count. */
sampledEvents: number;
/** ISO start of the period the `summary` covers (the resolved `from`), or
* null when the Core doesn't report it. */
periodStart: string | null;
/** ISO end of the period the `summary` covers (the resolved `to`), or null
* when the Core doesn't report it. */
periodEnd: string | null;
/** Aggregated advisory policy state from the freshest event in this snapshot.
* Null when no event carries policy metadata. */
usagePolicy: UsagePolicyAdvisory | null;
}
Public export UsageSummary.
Declaration source: packages/farthershore-js/dist/types.d.ts#L645.
export type UsageSummary = Record<string, number>;
Public export UsageTrafficClass.
Declaration source: packages/farthershore-js/dist/types.d.ts#L651.
export type UsageTrafficClass = (typeof USAGE_TRAFFIC_CLASSES)[number];
Public export useApiKeys.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L29.
export declare function useApiKeys(): ApiKeysResult;
A small data-fetching primitive the hooks share: tracks {data, isLoading,
error}, re-runs when `deps` change or `refetch()` is called, and ignores a
resolution after unmount/dep-change (no setState-after-unmount). The `fn`
receives an {@link AbortSignal} that fires on unmount/dep-change/refetch, so
the stale in-flight read is cancelled rather than left to resolve.
`queryKey` is the stable per-hook identity array a caller passes through to
the returned result (e.g. `["apiKeys", businessId, orgId]`) — `useAsync`
does not derive it from `deps` (deps often carry non-serializable values
like the client instance), so each hook builds its own.
Declaration source: packages/farthershore-js/dist/react/use-async.d.ts#L51.
export declare function useAsync<T>(fn: (signal: AbortSignal) => Promise<T>, deps: readonly unknown[], queryKey: readonly unknown[]): AsyncResult<T>;
Subscriber audit log, refetched when the (serialized) filters change — now
including `from`/`to`/`actorUserId` (W9.1d), which the resource already
forwards. Also re-runs on an org switch (reactive scope).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L250.
export declare function useAuditLogs(filters?: AuditLogFilters): AsyncResult<AuditLogPage>;
Public export useBilling.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L146.
export declare function useBilling(): BillingResult;
The subscriber's current-window bill preview (`GET /me/bill-preview`) —
Core-computed through the same rating engine + ledger state as invoicing.
Honors `disclosure`: `transparent` carries windows / totals / nanodollar
allowance balances; `opaque` carries allowance shape only. Nanodollar fields
are decimal STRINGS — render with `format.formatNanos`, never `Number()`.
Query key `["billPreview", businessId, organizationId]`. Re-reads whenever
an entitlement mutation busts the read cache (subscribe / change plan /
cancel / restore / migrate — the same wake `useBilling` / `useMe` get), and
on org switch.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L169.
export declare function useBillPreview(): AsyncResult<BillPreview>;
The resolved Bootstrap. Children of `<FartherShoreRoot>` render only after
resolve succeeds, so this never suspends or returns null.
Declaration source: packages/farthershore-js/dist/react/mounted-context.d.ts#L9.
export declare function useBoot(): Bootstrap;
Public export useBootstrap.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L5.
export declare function useBootstrap(): AsyncResult<Bootstrap>;
Public export useBusiness.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L6.
export declare function useBusiness(): AsyncResult<Business>;
A live cooldown countdown. Given a `Retry-After` (relative seconds) and/or a
`resetAt` (absolute instant), returns the whole seconds remaining, ticking
down each second until it reaches 0. SSR-safe: the first render computes a
static snapshot and the interval only starts after mount. The target is
recomputed when the inputs change, so feeding it a fresh caught error resets
the countdown.
Declaration source: packages/farthershore-js/dist/react/use-limits.d.ts#L32.
export declare function useCooldown(options?: UseCooldownOptions): CooldownResult;
Public export UseCooldownOptions.
Declaration source: packages/farthershore-js/dist/react/use-limits.d.ts#L15.
export interface UseCooldownOptions {
/** A `Retry-After` value — seconds (number) or the raw header string. Wins
* over `resetAt` when both are present. */
retryAfterSeconds?: number | string | null;
/** An absolute reset instant — a Date or unix-epoch ms. */
resetAt?: Date | number | null;
/** Injectable clock for tests (defaults to Date.now). */
now?: () => number;
}
The product's declared counted-resource catalog (W5.1) — name + label +
scope + per-plan cap. Resolved from `bootstrap()`, so it joins the memoized
resolve round-trip (no extra fetch).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L10.
export declare function useDeclaredResources(): AsyncResult<DeclaredResource[]>;
The current subscriber's enforced limit map from the pinned plan version.
Reads the same cached `/me` snapshot
`useMe()` does — signed-out callers resolve to empty maps (so gate UI can
render disabled/upsell without a separate auth guard).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L285.
export declare function useEntitlements(): AsyncResult<EntitlementSnapshot__78b1daa335cc>;
The client from context. Throws if used outside a provider.
Declaration source: packages/farthershore-js/dist/react/provider.d.ts#L15.
export declare function useFartherShore(): FartherShoreClient__e4fe174a542f;
Fetch through a named integration, reactively. Re-runs when the
integration id, path, or meaningful options change. The common case is one
line:
const { data, isLoading } = useFetch("weather", "/v1/forecast", {});
`select` maps the raw `Response` to `T` (default: `res.json()`). Pass a custom
`select` for non-JSON upstreams (`(res) => res.text()`).
Declaration source: packages/farthershore-js/dist/use-fetch.d.ts#L15.
export declare function useFetch<T = unknown>(integrationId: string, path: string, opts: Omit<FsFetchOptions__62afbd421e0f, "signal">, select?: (res: Response) => Promise<T>): UseFetchResult<T>;
The resolved secure-fetch hook state — the ecosystem resource-hook shape.
Declaration source: packages/farthershore-js/dist/use-fetch.d.ts#L4.
export type UseFetchResult<T> = AsyncResult<T>;
Public export useFsAuth.
Declaration source: packages/farthershore-js/dist/react/mounted-context.d.ts#L10.
export declare function useFsAuth(): FsAuth;
Resolve the {@link LimitFacet} for a caught limit error — the single object a
UI branches on (class, reaction, retry-safe, must-modify, can-upgrade,
headroom). Returns null when `err` is not a usage-limit deny. Memoized on the
error identity, so it's stable across renders for the same caught value.
Declaration source: packages/farthershore-js/dist/react/use-limits.d.ts#L8.
export declare function useLimitState(err: unknown): LimitFacet__c540ead8fd1d | null;
Read the proactive, ADVISORY limit-state snapshot (T11). Subscribes to the
client's live rate-budget store AND the last-deny store (both via
`useSyncExternalStore`), so any `fs.route` call — a successful one that carries
`X-RateLimit-*`, or a deny — updates every `useLimitStatus()` in the tree.
SSR-safe (the server snapshot is the empty/unknown state).
Advisory by construction: the gateway remains authoritative for the actual
decision. Use it to PRE-WARN a UI (a "you're near your limit" banner, a
disabled submit while saturated), never as a hard gate.
Declaration source: packages/farthershore-js/dist/react/use-limit-status.d.ts#L85.
export declare function useLimitStatus(options?: UseLimitStatusOptions): LimitStatus;
Public export UseLimitStatusOptions.
Declaration source: packages/farthershore-js/dist/react/use-limit-status.d.ts#L67.
export interface UseLimitStatusOptions {
/** A deny older than this (ms) reads as `stale` and stops driving the
* saturation/throttle flags. Default 60000 (1 min). */
staleAfterMs?: number;
/** Injectable clock (tests). Defaults to Date.now. */
now?: () => number;
}
Full subscriber context (`GET /me`) — lifecycle, trial, scheduled
transition, eligibility-scoped plans. Null = onboarding.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L181.
export declare function useMe(options?: {
/** Request-local scope. `null` omits the organization header without
* changing the provider's selected workspace. */
organizationId?: string | null;
}): AsyncResult<SubscriberContext | null>;
The subscriber's per-category notification preferences (opt-out model).
Reads on mount + org switch; `update()` patches and refetches. Non-degrading:
a read failure surfaces on `.error` (drives the page's error state).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L228.
export declare function useNotificationPreferences(): NotificationPreferencesResult;
Like {@link useFsAuth} but null outside the managed auth layer — lets
components degrade instead of throwing when mounted without a Root.
Declaration source: packages/farthershore-js/dist/react/mounted-context.d.ts#L13.
export declare function useOptionalFsAuth(): FsAuth | null;
The active org, the org list, and the switcher (W9.1a). Reactive: switching
via `setOrganization` re-runs every data hook (they depend on the reactive
org id) under the new scope, and persists across reloads.
Returns a stable shape even outside an <OrganizationProvider> (i.e. when only
a bare <FartherShoreProvider> hasn't mounted the org layer) so callers don't
need a guard — `organizationId` is null and `setOrganization` is a no-op.
Declaration source: packages/farthershore-js/dist/react/organization-context.d.ts#L45.
export declare function useOrganization(): OrganizationContextValue;
Audit log with ACCUMULATING cursor pagination (W9.1d) — the "Load older" UX.
Unlike {@link useAuditLogs} (which REPLACES the page when the cursor changes),
`loadMore()` APPENDS the next page to `items`, deduping by entry id (so a row
that straddles a page boundary isn't shown twice). The first page (and a full
reset) re-runs whenever the non-cursor filters — or the active org — change.
`filters.cursor` is ignored here: pagination is owned internally (the first
page starts uncursored; `loadMore` advances from the server's `nextCursor`).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L278.
export declare function usePaginatedAuditLogs(filters?: Omit<AuditLogFilters, "cursor">): PaginatedAuditLogsResult;
Public export usePinnedPlan.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L186.
export declare function usePinnedPlan(): {
plan: Plan | null | undefined;
};
Usage rows derived from the subscriber's PINNED plan (`GET /me`'s
`displayDims` + `rules`) rather than the latest catalog meter list — so the
"used / N included" figures match the entitlement the subscriber is actually
billed under, even after the product's catalog drifts.
Combines {@link useUsage} (the exact period summary + basis) with
{@link useMe} (the pinned display surface) and {@link useBusiness} (meter
labels/units). A drop-in alternative to the catalog-derived rows
{@link UsageCard } builds by default; optional, no new required dev step.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L206.
export declare function usePinnedUsageRows(range?: {
from?: string;
to?: string;
}): PinnedUsageRowsResult;
Public export usePlans.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L178.
export declare function usePlans(): PlansResult;
The reactive read scope shared by every org-scoped data hook: the client,
its businessId, and the active org id from the org context (W9.1a).
**Custom hooks that read org-scoped data must use this** instead of calling
`useFartherShore()` directly — folding `organizationId` (and `businessId`)
into a hook's dep array / queryKey is what makes an org switch auto-refetch
(the client reference itself is stable, so `[fs]` alone never reacts, and a
queryKey built without `businessId`/`organizationId` can collide across
scopes). Example:
```ts
function useMyResource() {
const { fs, businessId, organizationId } = useReadScope();
return useAsync(
(signal) => fs.resources("widgets").list({ signal }),
[fs, businessId, organizationId],
["widgets", businessId, organizationId],
);
}
```
`organizationId` is null outside an `<OrganizationProvider>` (a bare
provider tree behaves exactly as before — it just never reacts to a
switch).
Declaration source: packages/farthershore-js/dist/react/scope.d.ts#L40.
export declare function useReadScope(): ReadScope;
Reconcile the subscriber lifecycle after returning from a Stripe Checkout.
Polls `me()` (cache-busted, backed off) until ACTIVE/TRIALING or a timeout.
`enabled` (default true) lets a page mount the hook unconditionally but only
start the loop when it knows it just returned from checkout (e.g. a
`?checkout=success` query flag).
Declaration source: packages/farthershore-js/dist/react/use-reconcile.d.ts#L27.
export declare function useReconcileAfterCheckout(options?: ReconcileOptions__bcd46321c900 & {
enabled?: boolean;
}): UseReconcileAfterCheckoutResult;
Public export UseReconcileAfterCheckoutResult.
Declaration source: packages/farthershore-js/dist/react/use-reconcile.d.ts#L3.
export interface UseReconcileAfterCheckoutResult {
/** True while the poll loop is running. */
reconciling: boolean;
/** True once the lifecycle settled; false until then (and if it timed out). */
settled: boolean;
/** True once the current reconciliation attempt has finished, whether it
* settled, timed out, or failed. False before its effect starts and while it
* is running. */
finished: boolean;
/** The freshest subscriber detail read, or null. */
subscriber: SubscriberDetail | null;
/** A `me()` throw during the loop, or null. */
error: Error | null;
/** Re-run the reconciliation (e.g. a manual "still pending? retry" button). */
retry: () => void;
}
A cheap, reactive precheck over the live `X-RateLimit-*` budget (the most
recent gateway response). Lets a UI disable a submit / show a cooldown BEFORE
spending a round trip that would just 429. Conservative: `blocked` is only
true when the remaining count is KNOWN to be 0 — an unknown budget never
blocks (the request proceeds and the response carries the real verdict).
Declaration source: packages/farthershore-js/dist/react/use-limits.d.ts#L49.
export declare function useRequestPrecheck(): RequestPrecheck;
A single record of a product-declared resource (W5.3): wraps
`fs.resources(name).get(id)`. A 404 resolves to `null` (the record doesn't
exist) rather than an error, so callers branch on `data === null`. Re-runs
when `name`/`id` change.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L329.
export declare function useResource<T = unknown>(name: string, id: string): AsyncResult<ResourceRecord__87f0c814eb51<T> | null>;
The current plan's cap for a dimension (resource limit or quota), or null
when unknown / unlimited. Drives the `n / max` display in `<ResourcesPanel>`.
Declaration source: packages/farthershore-js/dist/react/use-upgrade.d.ts#L36.
export declare function useResourceCap(dimension: string): number | null;
Per-resource `{ limit, current }` for the pinned plan — the "N of M"
surface (e.g. api_keys: 3 of 5). The LIMIT side lives in the `/me`
snapshot, but `current` is a live count, so this reads the dedicated
`/me/resource-limit-usage` route. Signed-out / no subscription → an empty map.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L292.
export declare function useResourceLimitUsage(): AsyncResult<ResourceLimitUsageMap__cc534f1c9f18>;
List + mutate a product-declared, quota-counted resource (rides the gateway,
which diverts to core). `create` surfaces `LimitExceededError` at the cap —
pair with `<UpgradePrompt>`.
W5.3 — mutations are OPTIMISTIC: create/update return the authoritative record
from core, so the local list reconciles immediately (insert / patch / drop)
WITHOUT a full refetch, then the next dep-change/refresh reconciles against
the server. A mutation that throws (e.g. a cap deny) never touches the list.
The overlay resets on a scope change (org/resource) and prunes entries the
refetched server list already reflects, so it can never leak across scopes or
permanently mask a server change (B3).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L322.
export declare function useResourcesList<T = unknown>(name: string): ResourcesListResult<T>;
Authoritative `{ count, cap }` usage for a product-declared resource (W5.2) —
reads core (the system of record), so it works for backend-managed resources
the SDK can't `list()`. Signed-out / no subscription → `{ count: 0, cap: null }`.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L335.
export declare function useResourceUsage(name: string): AsyncResult<ResourceUsage__40697d865d06>;
The live `X-RateLimit-*` budget observed on the most recent `fs.route` gateway
call (W8.5) — `{ remaining, resetAt }`, or null until the first gateway
response carried the headers. Subscribes to the client's rate-limit store
(via `useSyncExternalStore`), so any `fs.route.get/getWithMeta` updates every
`<RateLimitDisplay>` in the tree. SSR-safe (the server snapshot is null).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L300.
export declare function useRouteRateLimit(): RateLimitSnapshot__934527ed940b | null;
Public export useServiceAccounts.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L47.
export declare function useServiceAccounts(options?: {
/** Skip protected reads until the caller's service-account RBAC claim settles. */
enabled?: boolean;
}): ServiceAccountsResult;
Public export useSession.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L14.
export declare function useSession(): SessionResult;
Public export useSpendCap.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L156.
export declare function useSpendCap(): SpendCapResultHook;
Multi-org subscription contexts (the org switcher's data).
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L211.
export declare function useSubscriptionContexts(strict?: boolean): AsyncResult<SubscriptionContextsResult>;
Public export useTeam.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L220.
export declare function useTeam(): TeamResult;
Catalog-aware upgrade resolver. `resolve(error)` is stable once loaded.
Declaration source: packages/farthershore-js/dist/react/use-upgrade.d.ts#L38.
export declare function useUpgrade(): UseUpgradeResult;
Public export UseUpgradeResult.
Declaration source: packages/farthershore-js/dist/react/use-upgrade.d.ts#L28.
export interface UseUpgradeResult {
loading: boolean;
resolve(error: UpgradeResolvable): UpgradeTarget | null;
}
Public export useUsage.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L77.
export declare function useUsage(range?: {
from?: string;
to?: string;
}): AsyncResult<UsageData>;
Public export useUsageLimits.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L58.
export declare function useUsageLimits(): UsageLimitsResult;
Advisory UsagePolicy state for rendering billable/free/limited/provider-cost
labels and cooldown prompts. It is an alias over the usage snapshot so older
Cores simply produce `usagePolicy: null`.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L98.
export declare function useUsagePolicy(range?: {
from?: string;
to?: string;
}): AsyncResult<UsagePolicyData>;
Back-compat ergonomic name for UI code that thinks in terms of current usage
state rather than the policy object. Advisory; decides nothing.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L104.
export declare function useUsageState(range?: {
from?: string;
to?: string;
}): AsyncResult<UsagePolicyData>;
The usage SUMMARY only — the quota counter — without the recent-activity
feed.
`useUsage()` returns both in one request, which means the Postgres-backed
counter waits on an R2 SQL scan of the event archive. A surface that renders
only the counter should use this hook and let the feed load beside it, so the
number never has to flash a placeholder zero first.
Declaration source: packages/farthershore-js/dist/react/hooks.d.ts#L90.
export declare function useUsageSummary(range?: {
from?: string;
to?: string;
}): AsyncResult<UsageData>;
These declarations explain types reachable from the public exports above. They are source evidence, not supported package imports. Suffixed names are documentation identifiers that preserve distinct lexical bindings. Standard-library and third-party types (for example Promise, React and Zod) remain external boundaries; their implementation declarations are not expanded here.
Declaration source: packages/farthershore-js/dist/resources/account.d.ts#L142.
export interface AuditLogsResource__99efa1e02380 {
/** Cursor-paged subscriber audit log (decision ALLOW|DENY, limit ≤ 200).
* Degrades to an empty page on error, like the SSR page. */
list(filters?: {
action?: string;
actorUserId?: string;
decision?: "ALLOW" | "DENY";
from?: string;
to?: string;
cursor?: string;
limit?: number;
signal?: AbortSignal;
/**
* `null` intentionally reads the user's default subscription without an
* organization header. `undefined` preserves the selected workspace.
*/
organizationId?: string | null;
}): Promise<AuditLogPage>;
}
Declaration source: packages/farthershore-js/dist/resources/auth.d.ts#L3.
export interface AuthResource__beeda8a7af1a {
/** The current session (authenticated identity + a light subscriber slice).
* Resolves to `{ authenticated: false }` on 401/403 rather than throwing.
* Test-persona identity comes from Core's verified HttpOnly cookie; no
* persona bearer is exposed to browser JavaScript. */
getSession(opts?: {
signal?: AbortSignal;
}): Promise<Session>;
/** Revoke the server-owned persona browser session and clear local auth
* caches. Clerk-strategy environments continue to sign out via Clerk. */
signOut(): Promise<void>;
/** Set a session bearer directly (for example, Clerk's session token). */
setToken(token: string | null): void;
/** Mint a short-lived Gateway bearer from the current authenticated browser
* session. In persona environments Core authenticates this with the
* same-origin HttpOnly cookie. */
gatewayContextToken(opts?: {
signal?: AbortSignal;
refresh?: boolean;
}): Promise<GatewayContextToken>;
}
Declaration source: packages/farthershore-js/dist/resources/billing.d.ts#L13.
export interface BillingResource__c8dbd9d25fa3 {
/** The consumer's current subscription for this product, or null.
*
* `opts.signal` is accepted for source-compat but does NOT cancel the shared
* cached fetch (the cache owns the fetch lifecycle); the read is unmount-safe
* via the hook's active-flag and bounded by the cache TTL. */
subscription(opts?: {
signal?: AbortSignal;
}): Promise<Subscription | null>;
/** Open the Stripe-hosted billing portal (payment method + invoices). Returns
* the URL to navigate to. This is also how invoices are viewed in V0. */
openBillingPortal(input?: {
returnUrl?: string;
}): Promise<{
url: string;
}>;
/** Cancel the current subscription. Free subs cancel inline; paid subs are
* scheduled on the provider for the end of the current billing period and
* the result carries the `cancelsAt` boundary. `reason` is recorded for
* churn analytics. */
cancelSubscription(input?: {
reason?: string;
}): Promise<CancelSubscriptionResult>;
/** Buy more prepaid balance. Starts a provider checkout for `amountCents`
* and returns the URL to send the subscriber to. Core gates this on
* `invoice:pay` and refuses (`INVALID_STATE`) for a plan that declares no
* prepaid funding. `requestId` is the idempotency handle — pass the SAME
* uuid to retry one intent; omit it and the SDK mints one per call. */
addFunds(input: {
amountCents: number;
requestId?: string;
successUrl?: string;
cancelUrl?: string;
}): Promise<{
checkoutUrl: string;
}>;
/** Reverse a scheduled cancel — the platform lifts `cancel_at_period_end`
* on the provider (paid) or flips a CANCELLED free sub back to ACTIVE. The
* result carries the platform's POST-restore `cancelAtPeriodEnd` so a
* caller can render the outcome instead of assuming it. */
restoreSubscription(): Promise<RestoreSubscriptionResult>;
/** Change an existing subscription to another plan. Core applies or
* schedules the transition according to the product's policy. */
changePlan(input: {
compiledPlanId: string;
}): Promise<ChangePlanResult>;
/** Set (or clear, with `null`) the subscriber's monthly spend cap (in cents).
* PATCHes `/me/spend-cap`. CAVEAT: the cap is currently STORED-not-ENFORCED
* (held in subscription metadata pending the rate-limit migration) — do NOT
* present this as a hard spend limit in UI copy. */
setSpendCap(input: {
maxMonthlySpendCents: number | null;
}): Promise<SpendCapResult__395300e78371>;
/** Read the subscriber's current monthly spend cap (in cents), or null when
* none is set / signed out. P-SPENDCAP-READ — reads the additive
* `subscriber.maxMonthlySpendCents` surfaced on the `/me` context (no new
* route). Joins the memoized `/me` read.
*
* `opts.signal` is accepted for source-compat but does NOT cancel the shared
* cached `/me` fetch (the cache owns the fetch lifecycle); the read is
* unmount-safe via the hook's active-flag and bounded by the cache TTL. */
getSpendCap(opts?: {
signal?: AbortSignal;
}): Promise<number | null>;
/** The subscriber's current-window bill preview (`GET /me/bill-preview`) —
* computed by Core through the SAME rating engine + ledger state as
* invoicing, so preview === invoice by construction. Honors the plan's
* `spendPolicy.disclosure`: `transparent` carries windows / totals /
* nanodollar allowance balances; `opaque` carries allowance shape only (no
* amounts). Nanodollar fields are decimal STRINGS — format them with
* `format.formatNanos`, never `Number()`. Read-through cached; every
* entitlement mutation (subscribe / change plan / cancel / restore /
* migrate) busts it. Signed-out / no subscription → Core serves an empty
* transparent preview.
*
* `opts.signal` is accepted for source-compat but does NOT cancel the shared
* cached fetch (the cache owns the fetch lifecycle). */
getBillPreview(opts?: {
signal?: AbortSignal;
}): Promise<BillPreview>;
}
Declaration source: packages/farthershore-js/dist/resources/business.d.ts#L2.
export interface BusinessResource__933d34c2f16a {
/** The business this frontend is running for (resolved via bootstrap). */
get(): Promise<Business>;
/** The business's declared counted-resource catalog (W5.1) — name + label +
* scope + per-plan cap. The same list `bootstrap()` resolves. */
resources(): Promise<DeclaredResource[]>;
}
Declaration source: packages/farthershore-js/dist/config.d.ts#L183.
export interface ClientContext__d9dbf3313290 {
/** Platform Core base URL. LAZY: resolved on read as explicit config >
* injected `window.__FS_CONFIG__` > the production platform default —
* never throws. Reading this property is what performs the lazy window
* read; never read it at module scope or client-construction time. */
readonly coreUrl: string;
/** Portal host identifying the product/env to Core. LAZY — see {@link
* coreUrl}; defaults to `location.host` in the browser, read on access. */
readonly portalHost: string | null;
businessId: string | null;
environmentId: string | null;
organizationId: string | null;
/**
* The organization selection before it is reconciled against subscription
* contexts. Unlike `organizationId`, undefined means no explicit selection;
* null is a durable request for the user's default subscription. Internal
* runtime state used by the React organization provider.
*/
organizationSelection?: string | null;
/** Subscribers notified when the imperative organization scope changes. */
organizationListeners: Set<() => void>;
/** Read-through cache backing `fs.prefetch.*` (see cache.ts). */
readCache: Map<string, ReadCacheEntry__ee67854da2b9>;
gatewayUrl: string | null;
apiKey: string | null;
/** Cached short-lived gateway context token for browser-session feature
* calls. Cleared whenever session/org scope changes. */
gatewayContextToken: {
token: string;
expiresAt: string;
cacheKey: string;
} | null;
/** In-flight context-token mint, keyed by cacheKey — SINGLE-FLIGHT coalescing
* so concurrent feature calls share ONE mint instead of stampeding Core
* (W6.3). Cleared as soon as the mint settles. Internal. */
gatewayContextTokenInflight: {
cacheKey: string;
promise: Promise<GatewayContextToken>;
} | null;
/** Explicit session bearer (for Clerk/advanced integrations), falling back
* to the configured `getToken` provider. Persona sessions are HttpOnly
* cookies and never enter JavaScript. */
sessionToken: string | null;
/** True after a cookie-authenticated Core request succeeds. This lets a
* later 401 trigger managed recovery without treating an anonymous first
* `/me` read as a lapsed session. Contains no credential. */
browserSessionAuthenticated: boolean;
getToken?: TokenProvider__40095f0da8e4;
/** Runtime-installed token provider (e.g. the managed Clerk bridge inside
* `<FartherShoreRoot>`). Wins over `config.getToken`; an explicitly set
* `sessionToken` still wins over both. */
tokenProvider: TokenProvider__40095f0da8e4 | null;
fetch: FetchLike__7d89beec4c77;
/** Resolved automatic-retry policy (defaults applied). */
retry: ResolvedRetryConfig__fe2336bea142;
/** Resolved global interceptors (all optional; default no-ops elsewhere). */
onError?: (err: unknown) => void;
onLimitExceeded?: (err: LimitExceededError__7844c601e6fd) => void;
onUnauthorized?: (err: FartherShoreApiError__ae8b4410fda4) => void;
/** Runtime-installed 401 reaction (the managed auth layer's mid-session
* recovery), wired by `<FsAuthProvider>` via `setOnUnauthorized`. Fires AFTER
* the config-level `onUnauthorized`. Internal. */
onUnauthorizedManaged?: (err: FartherShoreApiError__ae8b4410fda4) => void;
/**
* LATCH: managed auth recovery has already fired for the CURRENT credential.
*
* The interceptor de-dupe is per-ERROR-OBJECT, which only collapses one
* logical failure surfacing through nested transports. A dashboard runs many
* independent reads concurrently, so a single lapsed session produces MANY
* distinct 401 errors — each firing its own recovery, each remounting the
* surface, each triggering a fresh round of reads. That feedback loop was
* measured at ~274 requests in 25s from ONE dashboard (~650/min against
* core's 100/min portal limit): the portal rate-limited itself.
*
* Recovery is a per-SESSION event, not a per-request one. Cleared whenever a
* new credential is installed, so a genuinely re-authed session can recover
* again.
*/
managedRecoveryLatched?: boolean;
/** Last `X-RateLimit-*` snapshot observed on a gateway response (W8.5) — fed
* by `fs.route.getWithMeta`, read by `useRouteRateLimit()`. Null until the first
* gateway call that carried the headers. Internal. */
lastRateLimit: RateLimitSnapshot__934527ed940b | null;
/** Subscribers notified when `lastRateLimit` changes (the `useRouteRateLimit`
* external store). Internal. */
rateLimitListeners: Set<() => void>;
/** A5-amend (T11) — the last LIMIT/throttle deny observed leaving the
* transport, recorded by `fireInterceptors`. ADVISORY: the freshest known
* RECENT deny, not a live poll (the gateway stays authoritative). Read by
* `useLimitStatus()`. Null until the first limit deny is observed. Internal. */
lastLimitDeny: ObservedLimitDeny__ff379deca309 | null;
/** Subscribers notified when `lastLimitDeny` changes (the `useLimitStatus`
* external store). Internal. */
limitDenyListeners: Set<() => void>;
/** Subscribers notified when the read cache is BUSTED (auth change, org
* switch, entitlement mutation) — every mounted `useAsync` refetches.
*
* Clearing the cache alone only stops the NEXT read from being served stale;
* it does not re-run the reads already on screen. Without this notification a
* `setSessionToken` after a 401 leaves every mounted surface showing the
* signed-out result until something happens to remount it. Internal. */
readCacheListeners: Set<() => void>;
/** True when all SDK-owned network/auth paths are served by the local mock
* transport. Internal, read by the managed auth layer. */
mockMode: boolean;
}
Declaration source: packages/farthershore-js/dist/http.d.ts#L3.
export interface CoreRequest__88dbed0693a0 {
method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
path: string;
query?: Record<string, string | number | undefined | null>;
body?: unknown;
/** Caller-stable retry identity for durable mutation replay. */
idempotencyKey?: string;
/** "session" attaches the consumer session bearer; "none" is for public
* endpoints (resolve/discover). Defaults to "session". */
auth?: "session" | "none";
/** When `false`, a tolerated `401` on this (authed) read does NOT trigger the
* managed auth-layer recovery (`onUnauthorizedManaged` — the hosted-sign-in
* redirect / persona sign-out). Use for best-effort `/me` reads that already
* swallow a 401 and render a signed-out/unsubscribed surface: re-authing an
* already signed-in user can't clear an authorization 401, so the redirect is
* futile and loops. `onUnauthorized` (config hook) + `onError` still fire.
* Defaults to `true` (a lapsed authed session still bounces to recovery). */
recoverAuth?: boolean;
/** Abort signal — when it fires (e.g. a React hook unmounts or its deps
* change), the in-flight read rejects with {@link FartherShoreAbortError}. */
signal?: AbortSignal;
/**
* Per-request organization scope. `undefined` inherits the client selection;
* `null` deliberately omits the organization header without changing that
* shared selection. Use this for APIs whose documented default-subscription
* read is intentionally independent of the workspace currently shown in the
* rest of the portal.
*/
organizationId?: string | null;
}
Declaration source: packages/farthershore-js/dist/resources/entitlements.d.ts#L3.
export interface EntitlementSnapshot__78b1daa335cc {
/** True when an ACTIVE subscriber context backed this snapshot. */
hasSubscriber: boolean;
/** Resource limits on the current subscriber's pinned plan. */
resourceLimits: Record<string, number>;
}
Declaration source: packages/farthershore-js/dist/resources/entitlements.d.ts#L16.
export interface EntitlementsResource__eae052f23903 {
/** Read the current subscriber's entitlement maps. Signed-out users get
* empty maps so app code can render disabled/upsell states without a
* separate auth guard. */
snapshot(): Promise<EntitlementSnapshot__78b1daa335cc>;
/** Numeric resource limit, or null when absent. */
resourceLimit(key: string): Promise<number | null>;
/** Per-resource `{ limit, current }` for the pinned plan (`N of M`). The
* LIMIT side lives in the `/me` snapshot, but `current` is a live count, so
* this reads the dedicated `/me/resource-limit-usage` route. Read-through cached
* (the cache owns the fetch lifecycle, like the other `/me` reads — no
* per-caller signal). Signed-out / no subscription → an empty map. */
resourceLimitUsage(): Promise<ResourceLimitUsageMap__cc534f1c9f18>;
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L49.
export declare class FartherShoreApiError__ae8b4410fda4 extends FartherShoreError__8dbed6dcc500 {
readonly status: number;
readonly code: string;
readonly body: unknown;
/** Seconds to wait before retrying, parsed from `Retry-After`; null when the
* response carried no `Retry-After`. */
readonly retryAfterSeconds: number | null;
/** The `X-RateLimit-Remaining` / `-Reset` snapshot, or null when absent. */
readonly rateLimit: RateLimitSnapshot__934527ed940b | null;
/**
* Whether the request that produced this error actually carried an auth
* credential (a bearer was attached). Set by the transport AFTER the error is
* minted. A `401` with `authed === false` is a NEVER-authenticated visitor (a
* signed-out `/me` read sent no bearer) — the managed auth layer must treat it
* as a no-op, NOT a lapsed-session redirect. Defaults to `true` so any caller
* that doesn't thread the flag keeps the prior (always-fire) behaviour.
*/
authed: boolean;
/**
* Whether a `401` on this request should trigger the MANAGED auth-layer
* recovery (the hosted-sign-in redirect / persona sign-out). Best-effort `/me`
* reads that already swallow a 401 (and render a signed-out/unsubscribed
* surface) set this `false`: re-authenticating an already signed-in user can
* never clear an authorization 401, so the redirect is futile and loops. Set
* by the transport from `CoreRequest.recoverAuth`. The config-level
* `onUnauthorized` + `onError` hooks STILL fire (observability is unaffected);
* only the managed reaction is gated. Defaults to `true` (always recover).
*/
recoverAuth: boolean;
constructor(status: number, code: string, message: string, body: unknown, retryAfterSeconds?: number | null, rateLimit?: RateLimitSnapshot__934527ed940b | null);
}
Declaration source: packages/farthershore-js/dist/client.d.ts#L36.
export interface FartherShoreClient__e4fe174a542f {
/** The client's resolved runtime context (coreUrl, portalHost, businessId,
* auth/scoping state, …). `coreUrl`/`portalHost` are LAZY getters — reading
* them performs the `window.__FS_CONFIG__`/`location.host` resolution
* (`coreUrl` falls back to the production platform); everything else is a
* live snapshot of the client's current state. Mainly for
* introspection/tests — prefer the typed resources for actual calls. */
readonly context: ClientContext__d9dbf3313290;
/** Resolve + cache the business/env/gateway for the current portal host. Safe
* to call repeatedly (memoized). */
bootstrap(): Promise<Bootstrap>;
/** Set the consumer API key used for Gateway feature calls. */
setApiKey(key: string | null): void;
/** Set the Core session bearer directly (e.g. from the Clerk browser SDK). */
setSessionToken(token: string | null): void;
/** Install/replace a live token source resolved per request (short-lived
* Clerk JWTs). `<FartherShoreRoot>` wires this automatically in Clerk
* environments; pass null to uninstall. */
setTokenProvider(provider: (() => string | null | Promise<string | null>) | null): void;
/** Rescope subsequent Core calls to an owning org (the multi-org
* subscription-context switcher) — sets the `x-fs-organization-id` header.
* Pass null to return to the user's default subscription. Self-persists the
* choice (restored at the next client creation). */
setOrganizationId(organizationId: string | null): void;
/** The active org id scoping Core calls, or null (the user's default
* subscription). At boot this reflects the persisted choice restored from
* storage; the React org provider seeds its reactive state from it. */
getOrganizationId(): string | null;
/** Imperative organization scope as an external store. This keeps a mounted
* React provider in sync when an application calls `setOrganizationId()`
* directly rather than using the managed org switcher. */
readonly organizationScope?: {
subscribe(listener: () => void): () => void;
};
/** Install/replace the global 401 reaction (fired by the transport on a 401
* for an authed call). `<FartherShoreRoot>` / `<FsAuthProvider>` wire this
* automatically for managed mid-session recovery (persona sign-out / Clerk
* refresh); pass null to uninstall. A config-level `onUnauthorized` still
* fires first. */
setOnUnauthorized(handler: ((err: FartherShoreApiError__ae8b4410fda4) => void) | null): void;
/** Drop every cached Core read (and the short-lived gateway context token), so
* the next `me()` / list call goes to the network. Use after an out-of-band
* state change the SDK can't observe — e.g. polling `me()` for webhook lag to
* settle after returning from a Stripe Checkout (see `reconcileAfterCheckout`). */
invalidate(): void;
/** The last `X-RateLimit-*` snapshot observed on any `fs.route` gateway call,
* with a subscribe primitive — the external store behind `useRouteRateLimit()`
* (W8.5). `get()` is null until the first gateway response carried the
* headers; `subscribe` notifies on every change. */
readonly rateLimit: {
get(): RateLimitSnapshot__934527ed940b | null;
subscribe(listener: () => void): () => void;
};
/** A5-amend (T11) — the last LIMIT/throttle deny observed leaving the
* transport, with a subscribe primitive — the external store behind
* `useLimitStatus()`. ADVISORY (the freshest known RECENT deny, not a live
* poll — the gateway stays authoritative). `get()` is null until the first
* limit deny is observed; `subscribe` notifies on every change. */
readonly limitState: {
get(): ObservedLimitDeny__ff379deca309 | null;
subscribe(listener: () => void): () => void;
};
/** Read-cache invalidation as an external store. `subscribe` fires when a
* change invalidates what is ALREADY on screen: a new session/identity
* (`setSessionToken`, sign-in/sign-out) or a moved entitlement (any billing
* or plan action, and `invalidate()`).
*
* It deliberately does NOT fire on an org switch (org-scoped hooks refetch
* from their own deps) or on an ordinary resource mutation (the hook that
* performed it refetches itself).
*
* Every `useAsync`-backed hook subscribes automatically, so built-in hooks
* and custom ones written against `useAsync` already refetch. Use this
* directly only for state held OUTSIDE a hook (a store, an imperative cache
* of your own) that must be invalidated in step with ours. */
readonly readCache: {
subscribe(listener: () => void): () => void;
};
/** The business this frontend runs for (resolved via bootstrap). */
readonly business: BusinessResource__933d34c2f16a;
/** Consumer session: current identity, server-owned persona logout, and
* short-lived Gateway context-token minting. */
readonly auth: AuthResource__beeda8a7af1a;
/** The consumer's API keys (list / create / revoke / rotate). */
readonly keys: KeysResource__2bf8d8c5e820;
/** Per-dimension usage totals + recent events for this business. */
readonly usage: UsageResource__a3469cda0e70;
/** Subscriber-managed per-actor usage limits. */
readonly usageLimits: UsageLimitsResource__2b1e05e6bcda;
/** The consumer's subscription and Stripe billing portal. */
readonly billing: BillingResource__c8dbd9d25fa3;
/** The business's plan catalog + the subscribe/checkout flow. */
readonly plans: PlansResource__05a484289922;
/** Full subscriber context (`GET /me`): lifecycle, trial, scheduled
* transition, eligibility-scoped plans. Null when signed out / no
* subscriber. */
me(opts?: {
signal?: AbortSignal;
/** `null` omits the organization header without changing the shared
* client selection; `undefined` uses that selection. */
organizationId?: string | null;
}): Promise<SubscriberContext | null>;
/** Record legal-document acceptances for the current subscriber/org. */
acceptLegal(acceptances: LegalAcceptance[]): Promise<void>;
/** Multi-org subscription contexts (the org switcher's data). */
readonly organizations: OrganizationsResource__18d4024e64ce;
/** Team management on the current subscription. */
readonly team: TeamResource__b9e413854377;
/** Managed-RBAC management on the current subscription (settings, the
* derived permission catalog, role CRUD) — team-org OWNER/ADMIN only.
* Configures UX + minted-token claims; the EDGE `permission` constraint
* is the security boundary. */
readonly rbac: RbacResource__b63486266173;
/** The subscriber's per-category notification preferences (opt-out model):
* `get` the current state, `update` a partial patch. */
readonly notifications: NotificationsResource__dc7aa1b64a0f;
/** The subscriber-side audit log (cursor-paged). */
readonly auditLogs: AuditLogsResource__99efa1e02380;
/** Current subscriber entitlement maps from the pinned plan version. */
readonly entitlements: EntitlementsResource__eae052f23903;
/** Navigation-intent data warmers — see {@link PrefetchSurface}. */
readonly prefetch: PrefetchSurface__2b22bd2b6c45;
/**
* One-line, zero-config calls to your business's enforced gateway — host,
* auth, surface, and businessId all auto-resolved from the hosted context.
* `fs.route.post("/forecast", { city })`. Limit responses surface as
* `LimitExceededError` so the upgrade prompt works on any call.
*/
readonly route: RouteResource__52eafab15328;
/**
* Typed CRUD over a product-declared, quota-counted resource. Rides the
* gateway (which diverts to core, the system of record); `create` throws
* `LimitExceededError` at the plan cap. `fs.resources("widgets").list()`.
*/
resources<T = unknown>(name: string): ResourcesResource__ef6d17bbf151<T>;
/** Bound named-integration helper: `fs.integration("clerk-admin").fetch(...)`. */
integration(id: string): ManagedIntegration__68b11f8f586e;
/**
* Generic authenticated Core call — the escape hatch for platform endpoints
* the typed resources don't model yet (e.g. a product's `/me/team`,
* `/me/audit-logs`). The Core counterpart to {@link invoke}:
* it attaches the session bearer + the host/env/org scoping headers and maps
* non-2xx to {@link FartherShoreApiError}, exactly like the typed resources —
* the caller only supplies the path and the response type. Prefer a typed
* resource (`fs.usage`, `fs.keys`, …) when one exists.
*/
core<T>(req: CoreRequest__88dbed0693a0): Promise<T>;
}
Declaration source: packages/farthershore-js/dist/config.d.ts#L95.
export interface FartherShoreConfig__a72de6f5938f {
/** Owning org id for org-owned subscriptions (the `x-fs-organization-id`
* header / `organizationId` query). Usually set at runtime via
* `fs.setOrganizationId()` / the managed org switcher rather than here. */
organizationId?: string | null;
/** The consumer API key (`fsk_…`) used to authenticate Gateway feature calls.
* Settable later via `fs.setApiKey()`. */
apiKey?: string;
/** Session token provider for Core calls. Clerk browser sessions use this;
* test personas use the platform's same-origin HttpOnly cookie instead. */
getToken?: TokenProvider__40095f0da8e4;
/** Injectable fetch (tests / non-browser runtimes). Defaults to global fetch. */
fetch?: FetchLike__7d89beec4c77;
/** Automatic-retry policy for transient failures (429 + transient 502/503/504
* + network faults). Retry is ON by default; this only tunes/opts out. See
* {@link RetryConfig}. */
retry?: RetryConfig__bec25563219c;
/** Optional global hook fired (before the error is thrown) on EVERY non-2xx /
* network failure that leaves the transport. Observability only — it does not
* swallow the error. Default behaviour is unchanged when unset. */
onError?: (err: FartherShoreApiError__ae8b4410fda4 | unknown) => void;
/** Optional global hook fired (before throw) when the error is a
* {@link LimitExceededError} — a single place to surface an upgrade prompt. */
onLimitExceeded?: (err: LimitExceededError__7844c601e6fd) => void;
/** Optional global hook fired (before throw) on a `401` — a single place to
* trigger re-auth. */
onUnauthorized?: (err: FartherShoreApiError__ae8b4410fda4) => void;
/** Render a local portal with deterministic placeholder data and no live
* backend/auth. Also enabled by `window.__FS_CONFIG__.mock === true`. */
mock?: boolean;
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L2.
export declare class FartherShoreError__8dbed6dcc500 extends Error {
constructor(message: string);
}
Declaration source: packages/farthershore-js/dist/config.d.ts#L2.
export type FetchLike__7d89beec4c77 = typeof fetch;
Declaration source: packages/farthershore-js/dist/deny-codes.d.ts#L63.
declare const FS_LIMIT_CLASSES__cf69b28be276: readonly ["quota", "rate", "concurrency", "capacity", "spend", "adaptive"];
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L109.
export interface FsDenyEnvelope__adf7ef9f2448 {
/**
* The semantic class of limit hit — the primary axis clients branch on.
* `null` ONLY when the wire carried a `limitClass` string the SDK's closed
* mirror does NOT know (a FUTURE class added to contracts but not yet shipped
* in this bundle, T13). In that case the raw value is preserved on
* {@link unknownLimitClass} and the whole `_fs` block on {@link raw} so a
* client can still render + introspect the deny, while the SDK refuses to
* invent a known-class facet for it. A KNOWN class is always non-null.
*/
limitClass: FsLimitClass__2d5726601b87 | null;
/**
* T13 — the raw `limitClass` string when it is NOT a member of the closed
* {@link FsLimitClass} mirror (a future/unknown class). Undefined for every
* known class. Lets a forward-compat client surface "a `<unknownLimitClass>`
* limit was hit" + a debug breadcrumb without the SDK guessing semantics.
*/
unknownLimitClass?: string;
/**
* T13 — the raw `_fs` block exactly as it arrived on the wire, preserved for
* debugging/forwarding. Always present (even for a known class) so a developer
* can inspect fields this bundle's typed projection doesn't model yet.
*/
raw?: Record<string, unknown>;
/** The limit's scope when known (e.g. `subscription`, `org`, `route`). */
scope?: string;
/** Actor facet for actor-scoped subscriber limits. Carries kind only; raw
* actor ids must never be present in deny envelopes. */
actorScope?: "member" | "service_account";
/** The metered/resource dimension when known (e.g. `tokens`, `requests`). */
metric?: string;
/** Unix epoch ms when the limit window resets, when known. */
reset?: number;
/** Units remaining in the window at decision time, when known. */
remaining?: number;
/** Units already consumed in the window at decision time, when known. */
used?: number;
/** The cap value (the ceiling that was hit), when known. */
limit?: number;
/** True when retrying the SAME request can succeed (velocity/transient cap). */
retrySafe: boolean;
/** True when the caller must MODIFY the request (reduce size / change plan)
* before it can succeed — the `capacity`/`spend` affordances. */
mustModify: boolean;
/** Provider-supplied reason verbatim, when relayed upstream (an `adaptive`
* throttle). */
providerReason?: string;
/** Whether the platform or an upstream provider decided the limit. */
limitOrigin: FsLimitOrigin__1d4de1805fa7;
/** Human-facing next step for the END USER, when one applies. */
userAction?: string;
/** Human-facing next step for the DEVELOPER/operator, when one applies. */
devAction?: string;
/** The per-attempt request id (correlates with logs/traces). */
requestId?: string;
/** The gateway decision id (correlates with the usage event / audit). */
decisionId?: string;
/** Which exact constraint denied (projects from
* `LimitDecision.blockingConstraintId`); present on a limit deny when known. */
blockingConstraintId?: string;
/** The recommended client reaction. */
reaction: FsLimitReaction__06a9e09be641;
/** Envelope schema version. Bumped on a NON-additive envelope change. */
envelopeVersion?: number;
}
Declaration source: packages/farthershore-js/dist/fetch.d.ts#L3.
export interface FsFetchOptions__62afbd421e0f {
/** HTTP method for the upstream call. Defaults to `GET`. */
method?: string;
/** Browser-controlled headers. The named integration allowlists them. */
headers?: Record<string, string>;
/** Browser-controlled query parameters. The named integration allowlists
* each name; secret injection parameters remain server-owned. */
query?: Record<string, string>;
/** Optional, explicitly typed request body. The named integration's bounded
* body declaration is enforced by the gateway. */
body?: {
kind: "json";
value: unknown;
} | {
kind: "text";
value: string;
};
/** Abort signal — cancels the in-flight secure fetch (and the token mint). */
signal?: AbortSignal;
}
Declaration source: packages/farthershore-js/dist/deny-codes.d.ts#L65.
export type FsLimitClass__2d5726601b87 = (typeof FS_LIMIT_CLASSES__cf69b28be276)[number];
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L96.
export type FsLimitOrigin__1d4de1805fa7 = "platform" | "provider" | "subscriber";
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L99.
export type FsLimitReaction__06a9e09be641 = "none" | "backoff_retry" | "wait_then_retry" | "queue" | "reduce_then_retry" | "fallback" | "upgrade";
Declaration source: packages/farthershore-js/dist/resources/keys.d.ts#L3.
export interface KeysResource__2bf8d8c5e820 {
/** The consumer's API keys for this product (secrets are never returned). */
list(opts?: {
signal?: AbortSignal;
}): Promise<ApiKey[]>;
/**
* Create a key. The returned `secret` is shown ONCE.
*
* Consumer-principal (D2): this generic route creates PERSONAL member keys.
* Managed service credentials use the canonical `serviceAccounts` lifecycle,
* which can return PENDING without creating a secret.
*
* `roleKeys` binds the key to org RBAC roles (live-bound: a role edit reaches
* the key without reprovisioning); `restrictedPermissions` optionally narrows
* the bound roles to a Stripe-style subset. Both are grantable only within
* the creator's own permissions — the backend 403s an over-reaching binding.
* (PERSONAL keys ignore `roleKeys` — their perms track the bound member.)
*/
create(input?: {
label?: string;
scopes?: string[];
roleKeys?: string[];
restrictedPermissions?: string[];
kind?: "PERSONAL";
/** PERSONAL — mint FOR this member (their `Membership.id`); admin-gated. */
memberId?: string;
}): Promise<CreatedApiKey>;
/** Permanently revoke a key by id. */
revoke(keyId: string): Promise<void>;
/** Rotate a key — revokes the old and returns a new `secret` (shown once). */
rotate(keyId: string): Promise<CreatedApiKey>;
/** Canonical managed service-account provisioning and approval lifecycle. */
readonly serviceAccounts: ServiceAccountsResource__abd2dd8a7d4f;
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L85.
export interface LimitDescriptor__01693492a147 {
/** Stable identifier for the limit that was hit, e.g. `resource:widgets`. */
limitCode: string;
/** The metered/resource dimension, when known (e.g. `widgets`, `requests`). */
dimension: string | null;
/** The cap the subscriber is at, when known. */
currentCapacity: number | null;
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L206.
export declare class LimitExceededError__7844c601e6fd extends FartherShoreApiError__ae8b4410fda4 {
readonly limitCode: string;
readonly dimension: string | null;
readonly currentCapacity: number | null;
/** The semantic {@link FsLimitClass} of this limit — derived from the `_fs`
* envelope when present, else from the wire code + limitCode + status
* ({@link classifyFsLimit}). null only when nothing classifies it. */
readonly limitClass: FsLimitClass__2d5726601b87 | null;
/** The parsed `_fs` deny envelope, when the body carried one. The richer
* source for the reaction/headroom fields below. */
readonly envelope: FsDenyEnvelope__adf7ef9f2448 | null;
/** True when retrying the SAME request can succeed (a velocity/transient cap);
* false when it never will (a spend cap / oversized request). */
readonly retrySafe: boolean;
/** True when the caller must MODIFY the request before it can succeed (a
* `capacity` ceiling or `spend` cap). */
readonly mustModify: boolean;
/** The recommended client reaction. */
readonly reaction: FsLimitReaction__06a9e09be641;
/** Whether the platform or an upstream provider decided the limit. */
readonly limitOrigin: FsLimitOrigin__1d4de1805fa7;
/** The gateway decision id (correlates with the usage event / audit), when
* the `_fs` envelope carried one. */
readonly decisionId: string | null;
/** When the limit window resets, when known (from the `_fs` envelope `reset`,
* unix-epoch ms, else the `X-RateLimit-Reset` snapshot). */
readonly reset: Date | null;
/** Units remaining in the window at decision time, when known. */
readonly remaining: number | null;
/** Units already consumed in the window at decision time, when known. */
readonly used: number | null;
/** The cap value hit, when known. */
readonly limit: number | null;
constructor(status: number, code: string, message: string, body: unknown, descriptor: LimitDescriptor__01693492a147, retryAfterSeconds?: number | null, rateLimit?: RateLimitSnapshot__934527ed940b | null);
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L531.
export interface LimitFacet__c540ead8fd1d {
/** The semantic class — the primary axis a UI branches on. */
limitClass: FsLimitClass__2d5726601b87;
/** The recommended client reaction (from the `_fs` envelope, else a
* per-class default). */
reaction: FsLimitReaction__06a9e09be641;
/** Whether the platform or an upstream provider decided the limit. */
limitOrigin: FsLimitOrigin__1d4de1805fa7;
/** True when retrying the SAME request can succeed (rate/concurrency/adaptive
* are retry-safe; quota/spend/capacity are not). */
retrySafe: boolean;
/** True when the caller must MODIFY the request (capacity) or change the plan
* (spend) before it can succeed. */
mustModify: boolean;
/** True ONLY for the upgrade-affording classes (`quota` / `spend`). Drives
* whether a UI mounts the upgrade prompt — capacity's "bigger model"
* is a SEPARATE affordance, NOT an upgrade. */
canUpgrade: boolean;
/** When the limit window resets, when known. */
reset: Date | null;
/** Units remaining in the window at decision time, when known. */
remaining: number | null;
/** Units already consumed, when known. */
used: number | null;
/** The cap value hit, when known. */
limit: number | null;
/** The gateway decision id, when known. */
decisionId: string | null;
}
Declaration source: packages/farthershore-js/dist/integrations.d.ts#L6.
export type ManagedIntegration__68b11f8f586e = {
fetch(path: string, init?: ManagedIntegrationRequestInit__57e8453840f3): Promise<Response>;
/**
* Fetch-compatible adapter for native SDKs that accept a custom transport.
* Pair it with {@link url}; it converts the SDK's ordinary Request into the
* bounded named-integration envelope without exposing the injected secret.
*/
transport(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
/** Same-origin reserved base URL for native SDKs. It must be paired with this
* handle's `transport`; a raw browser fetch to the URL is not authorized. */
url(path?: string): string;
};
Declaration source: packages/farthershore-js/dist/integrations.d.ts#L3.
export type ManagedIntegrationRequestInit__57e8453840f3 = FsFetchOptions__62afbd421e0f;
Declaration source: packages/farthershore-js/dist/format/catalog-display.d.ts#L226.
export type MeterUsageRow__65f0c2813d76 = {
key: string;
label: string;
used: number;
quota: number | null;
unit?: string;
/** True when the row is a MEASURE the product meters but does NOT publish in
* its served meter catalog (`ocr_pages`, `pages`) rather than a first-class
* meter. Such a row is a breakdown of the metered total, not a peer of it —
* the usage surfaces render it as a secondary line under the meter rows
* instead of as another top-level row. */
secondary?: boolean;
};
Declaration source: packages/farthershore-js/dist/resources/account.d.ts#L169.
export interface NotificationsResource__dc7aa1b64a0f {
/** The current preference state. Missing `master`/`categories` in a partial
* wire response are normalized to the opted-in defaults. */
preferences(opts?: {
signal?: AbortSignal;
}): Promise<NotificationPreferences>;
/** Partial patch — send ONLY the changed channels/categories. Returns the
* full, normalized updated state. */
updatePreferences(patch: NotificationPreferencesPatch): Promise<NotificationPreferences>;
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L580.
export interface ObservedLimitDeny__ff379deca309 {
/** The semantic class, or null for an UNKNOWN/future class (T13). */
limitClass: FsLimitClass__2d5726601b87 | null;
/** The raw `limitClass` string when it is outside the closed mirror (T13). */
unknownLimitClass?: string;
/** The recommended client reaction. */
reaction: FsLimitReaction__06a9e09be641;
/** Whether the platform or an upstream provider decided the deny. */
limitOrigin: FsLimitOrigin__1d4de1805fa7;
/** The provider-supplied reason verbatim, when this relayed an upstream
* throttle (an adaptive deny). */
providerReason: string | null;
/** When the limit window resets, when known. */
reset: Date | null;
/** Units remaining in the window at decision time, when known. */
remaining: number | null;
/** The cap value hit, when known. */
limit: number | null;
/** The HTTP status of the deny. */
status: number;
/** The wire `code` of the deny. */
code: string;
/** The gateway decision id, when known. */
decisionId: string | null;
/** Wall-clock instant (epoch ms) the deny was observed — drives staleness. */
observedAt: number;
}
Declaration source: packages/farthershore-js/dist/resources/account.d.ts#L3.
export interface OrganizationsResource__18d4024e64ce {
/** The orgs through which the current user holds subscriptions to this
* product (B2B multi-org). Degrades to the empty shape on any error —
* exactly how the SSR portal treated it. Set `strict` only when a caller
* needs to render the read failure distinctly from a valid empty result. */
contexts(opts?: {
signal?: AbortSignal;
strict?: boolean;
}): Promise<SubscriptionContextsResult>;
}
Declaration source: packages/farthershore-js/dist/generated/catalog-types.d.ts#L25.
export type PlanKindWire__a95f9171680c = "free" | "flat" | "usage" | "prepaid" | "hybrid" | "trial" | "custom";
Declaration source: packages/farthershore-js/dist/generated/catalog-types.d.ts#L17.
export interface PlanMeterWire__47c3d2492e8a {
dimension: string;
/** Aggregation formula (`linear` sum | `active_count` gauge |
* `event_count` per-event). OPTIONAL — absent means `linear`. */
kind?: "linear" | "active_count" | "event_count";
}
Declaration source: packages/farthershore-js/dist/resources/plans.d.ts#L31.
export interface PlanOffer__5ab47cb32b7d {
/** The immutable CompiledPlan version id (equals `plan.id`). */
compiledPlanId: string;
/** The plan, in the same wire shape as `list()` / the portal catalog. */
plan: Plan;
/** The billing fingerprint of THIS plan version's economic content. Pass it
* to `subscribe()` / `startOnboarding()` as `offerFingerprint` to get a
* 409 PLAN_OFFER_CHANGED instead of a silent price change. */
offerFingerprint: string;
}
Declaration source: packages/farthershore-js/dist/resources/plans.d.ts#L61.
export interface PlansResource__05a484289922 {
/** The product's available plans (resolved via bootstrap). Empty when the
* product has no published, self-serve plans. */
list(): Promise<Plan[]>;
/** The currently-purchasable plan versions for the signed-in subscriber
* (including their pinned plan version), each with the `offerFingerprint`
* to echo back at `subscribe()` for price-change consent. Unlike `list()`,
* this is a live core read (not bootstrap-cached). */
getPlanOffers(): Promise<PlanOffer__5ab47cb32b7d[]>;
/** Start checkout for a plan. Paid → `{ url }` (navigate to Stripe). Free →
* `{ subscriber }` (activated directly). Pass `offerFingerprint` (from
* `getPlanOffers()`) to fail 409 PLAN_OFFER_CHANGED on a stale price. */
subscribe(input: SubscribeInput__62c7cb21d77a): Promise<SubscribeResult__4b2d9557cede>;
/** The dashboard onboarding path (`POST /onboarding`) the SSR portal's
* onboarding view uses. Differs from `subscribe()`: paid plans return
* `checkoutUrl` (not `url`), and free activations may include a one-time
* `autoApiKey` (drives the auto-created-key banner). */
startOnboarding(input?: StartOnboardingInput__af7cf0dea526): Promise<OnboardingResult>;
}
Declaration source: packages/farthershore-js/dist/client.d.ts#L24.
export interface PrefetchSurface__2b22bd2b6c45 {
/** Warm the host→business resolve (joins the memoized bootstrap). */
boot(): void;
/** Warm `GET /me` (subscriber context) for dashboard/account surfaces. */
me(): void;
/** Warm the default usage snapshot (what `<UsageCard>`/the usage page read). */
usage(): void;
/** Warm the API-key list. */
apiKeys(): void;
/** Warm the subscription read (billing surfaces). */
subscription(): void;
}
Declaration source: packages/farthershore-js/dist/errors/index.d.ts#L8.
export interface RateLimitSnapshot__934527ed940b {
/** Requests left in the current window, or null when the header is absent. */
remaining: number | null;
/** When the window resets, or null when the header is absent. The
* `X-RateLimit-Reset` value is unix-epoch SECONDS. */
resetAt: Date | null;
}
Declaration source: packages/farthershore-js/dist/resources/account.d.ts#L65.
export interface RbacResource__b63486266173 {
settings: {
/** Current org settings: `{ enabled, defaultRoleKey? }`. */
get(opts?: {
signal?: AbortSignal;
}): Promise<RbacSettings>;
/** Full-document replace. `enabled: true` seeds the editable
* Admin/Editor/Viewer templates (idempotent); omitted/null
* `defaultRoleKey` clears the default. */
update(input: {
enabled: boolean;
defaultRoleKey?: string | null;
}): Promise<RbacSettings>;
};
/** The DERIVED grantable-permission catalog (never authored) — grouped by
* route operation, in the `<route-id>:read|write` grammar. */
catalog(opts?: {
signal?: AbortSignal;
}): Promise<RbacCatalogEntry[]>;
roles: {
/** The org's role list (seeded templates + custom), sorted by key. */
list(opts?: {
signal?: AbortSignal;
}): Promise<RbacRole[]>;
/** Create a custom role. Permissions are validated against the catalog
* (400 `UNKNOWN_PERMISSION` naming offenders; `"*"` always grantable). */
create(input: {
roleKey: string;
name: string;
permissions: string[];
}): Promise<RbacRole>;
/** Rename and/or re-permission a role. */
update(roleKey: string, input: {
name?: string;
permissions?: string[];
}): Promise<RbacRole>;
/** Delete a role. Member assignments referencing it are left in place
* (resolution ignores stale keys); a matching `defaultRoleKey` is
* cleared server-side. */
remove(roleKey: string): Promise<void>;
};
/**
* Permissions Kernel Wave 6 — per-subscriber component gate policies. An
* org admin (team:manage_rbac) upserts one override row per component key;
* `requiredPermission: null` clears the permission override back to the
* component's default. Throws the typed `FartherShoreApiError` — a 409
* `GOVERNED_BY_CHANGE_SET` means change control governs these rows.
*/
componentPolicies: {
/** Upsert the override row for one component key
* (PUT /me/component-policies). */
update(input: {
componentKey: string;
requiredPermission: string | null;
gateMode: string;
}): Promise<ComponentAccessPolicyRow>;
};
/**
* Track T3 — Notion-minimal access requests. Any member files a request for a
* permission; owners/admins review the queue and approve (AUTO-GRANTS the
* permission onto the requester's direct grants) or deny.
*/
accessRequests: {
/** File a request for a permission. Idempotent on an open PENDING row for
* the same (requester, permission). Any authenticated member. */
create(input: {
permission: string;
note?: string;
}): Promise<AccessRequest>;
/** The request queue (OWNER/ADMIN): pending first, then resolved. */
list(opts?: {
signal?: AbortSignal;
}): Promise<AccessRequest[]>;
/** Approve (grants the permission) or deny a pending request. */
resolve(requestId: string, action: "approve" | "deny"): Promise<AccessRequest>;
};
}
Declaration source: packages/farthershore-js/dist/cache.d.ts#L2.
export interface ReadCacheEntry__ee67854da2b9 {
at: number;
promise: Promise<unknown>;
}
Declaration source: packages/farthershore-js/dist/reconcile.d.ts#L3.
export interface ReconcileOptions__bcd46321c900 {
/** Max number of `me()` reads before giving up. Default 6. */
maxAttempts?: number;
/** Base backoff delay in ms (doubles each attempt, capped at `maxDelayMs`).
* Default 600. */
baseDelayMs?: number;
/** Backoff ceiling in ms. Default 5000. */
maxDelayMs?: number;
/** Predicate deciding whether the lifecycle has settled. Default: ACTIVE or
* TRIALING. */
isSettled?: (subscriber: SubscriberDetail | null) => boolean;
/** Abort the poll loop early (e.g. component unmount). */
signal?: AbortSignal;
}
Declaration source: packages/farthershore-js/dist/config.d.ts#L29.
export interface ResolvedRetryConfig__fe2336bea142 {
maxAttempts: number;
retryOn: (err: unknown) => boolean;
respectRetryAfter: boolean;
sleep: (ms: number) => Promise<void>;
}
Declaration source: packages/farthershore-js/dist/resources/entitlements.d.ts#L10.
export interface ResourceLimitUsage__a2c3c3e2955a {
limit: number;
current: number;
}
Declaration source: packages/farthershore-js/dist/resources/entitlements.d.ts#L15.
export type ResourceLimitUsageMap__cc534f1c9f18 = Record<string, ResourceLimitUsage__a2c3c3e2955a>;
Declaration source: packages/farthershore-js/dist/resources/resources.d.ts#L10.
export interface ResourceRecord__87f0c814eb51<TPayload = unknown> {
id: string;
resource: string;
payload: TPayload;
createdAt: string;
updatedAt: string;
}
Declaration source: packages/farthershore-js/dist/resources/resources.d.ts#L6.
export type ResourceRequestInit__06eb38c7f26b = RouteRequestInit__7377dee5c3ef & {
subjectId?: string;
};
Declaration source: packages/farthershore-js/dist/resources/resources.d.ts#L25.
export interface ResourcesResource__ef6d17bbf151<TPayload = unknown> {
/** List this subscriber's records of the resource. */
list(init?: ResourceRequestInit__06eb38c7f26b): Promise<ResourceRecord__87f0c814eb51<TPayload>[]>;
/** Fetch one record by id. */
get(id: string, init?: ResourceRequestInit__06eb38c7f26b): Promise<ResourceRecord__87f0c814eb51<TPayload>>;
/** Create a record. Throws `LimitExceededError` (402) at the plan cap. */
create(payload: TPayload, init?: ResourceRequestInit__06eb38c7f26b): Promise<ResourceRecord__87f0c814eb51<TPayload>>;
/** Replace a record's payload. */
update(id: string, payload: TPayload, init?: ResourceRequestInit__06eb38c7f26b): Promise<ResourceRecord__87f0c814eb51<TPayload>>;
/** Delete a record (frees one unit of the quota). */
delete(id: string, init?: ResourceRequestInit__06eb38c7f26b): Promise<void>;
/** Authoritative `{ count, cap }` for this resource on the caller's
* subscription (W5.2). Reads core (the system of record), so it works for
* backend-managed resources the SDK can't `list()`. Signed-out / no
* subscription → `{ count: 0, cap: null }`. */
count(init?: {
signal?: AbortSignal;
subjectId?: string;
}): Promise<ResourceUsage__40697d865d06>;
}
Declaration source: packages/farthershore-js/dist/resources/resources.d.ts#L21.
export interface ResourceUsage__40697d865d06 {
count: number;
cap: number | null;
}
Declaration source: packages/farthershore-js/dist/config.d.ts#L13.
export interface RetryConfig__bec25563219c {
/** Total attempts including the first (so `2` = one retry). Default 3.
* Set to `1` to disable retry. */
maxAttempts?: number;
/** Predicate deciding whether a thrown error is retryable. Defaults to the
* canonical {@link isRetryable} (429 + transient 502/503/504 + network faults
* + the named retryable deny codes). */
retryOn?: (err: unknown) => boolean;
/** Honor a `Retry-After` header for the backoff delay when present. Default
* true. */
respectRetryAfter?: boolean;
/** Override the delay primitive (tests inject a no-op; default is a
* timer-based sleep). Not part of the public surface — internal/testing. */
sleep?: (ms: number) => Promise<void>;
}
Declaration source: packages/farthershore-js/dist/resources/route.d.ts#L2.
export type RouteRequestInit__7377dee5c3ef = RequestInit & {
apiKey?: string;
};
Declaration source: packages/farthershore-js/dist/resources/route.d.ts#L15.
export interface RouteResource__52eafab15328 {
/** Raw gateway call — returns the `Response` for any content type. */
fetch(path: string, init?: RouteRequestInit__7377dee5c3ef): Promise<Response>;
/** `GET path` → parsed JSON. */
get<T = unknown>(path: string, init?: RouteRequestInit__7377dee5c3ef): Promise<T>;
/** `GET path` → parsed JSON PLUS the `X-RateLimit-*` snapshot read off the
* live response before it's discarded (W8.5). Also publishes the snapshot to
* `useRouteRateLimit()`. */
getWithMeta<T = unknown>(path: string, init?: RouteRequestInit__7377dee5c3ef): Promise<RouteResponseMeta__0abf9098561d<T>>;
/** `POST path` with a JSON body → parsed JSON. */
post<T = unknown>(path: string, body?: unknown, init?: RouteRequestInit__7377dee5c3ef): Promise<T>;
/** `PUT path` with a JSON body → parsed JSON. */
put<T = unknown>(path: string, body?: unknown, init?: RouteRequestInit__7377dee5c3ef): Promise<T>;
/** `PATCH path` with a JSON body → parsed JSON. */
patch<T = unknown>(path: string, body?: unknown, init?: RouteRequestInit__7377dee5c3ef): Promise<T>;
/** `DELETE path` → parsed JSON (or undefined on 204). */
delete<T = void>(path: string, init?: RouteRequestInit__7377dee5c3ef): Promise<T>;
}
Declaration source: packages/farthershore-js/dist/resources/route.d.ts#L8.
export interface RouteResponseMeta__0abf9098561d<T> {
data: T;
rateLimit: {
remaining: number | null;
resetAt: Date | null;
};
}
Declaration source: packages/farthershore-js/dist/resources/keys.d.ts#L37.
export interface ServiceAccountApprovalsResource__52f0cefb9602 {
/** Approval requests this signed-in member is currently eligible to decide. */
list(opts?: {
signal?: AbortSignal;
limit?: number;
offset?: number;
}): Promise<OffsetPage<PendingServiceAccountApproval>>;
/** Approve the complete request or an explicitly trimmed subset. */
approve(approvalId: string, input?: ApproveServiceAccountInput): Promise<ServiceAccountApprovalResponse>;
/** Deny a pending request without minting or widening any credential. */
deny(approvalId: string): Promise<ServiceAccountDenyResponse>;
}
Declaration source: packages/farthershore-js/dist/resources/keys.d.ts#L49.
export interface ServiceAccountMutationOptions__2dee3eb4c17c {
/** Reuse this value to replay the same pending create/update request safely. */
idempotencyKey?: string;
}
Declaration source: packages/farthershore-js/dist/resources/keys.d.ts#L53.
export interface ServiceAccountsResource__abd2dd8a7d4f {
/** List managed accounts, including PENDING rows with no credential material. */
list(opts?: {
signal?: AbortSignal;
limit?: number;
offset?: number;
}): Promise<OffsetPage<ServiceAccount>>;
/** Create immediately when covered, otherwise return a strict PENDING response. */
create(input: CreateServiceAccountInput, options?: ServiceAccountMutationOptions__2dee3eb4c17c): Promise<ServiceAccountCreateResponse>;
/** Replace the frozen grant snapshot or create a pending UPDATE request. */
update(serviceAccountId: string, input: UpdateServiceAccountInput, options?: ServiceAccountMutationOptions__2dee3eb4c17c): Promise<ServiceAccountUpdateResponse>;
/** Rotate the account credential and return the replacement secret once. */
rotate(serviceAccountId: string): Promise<ServiceAccountRotationResponse>;
/** Revoke the account and every active credential attached to it. */
revoke(serviceAccountId: string): Promise<void>;
readonly approvals: ServiceAccountApprovalsResource__52f0cefb9602;
}
Declaration source: packages/farthershore-js/dist/resources/billing.d.ts#L5.
export interface SpendCapResult__395300e78371 {
/** The stored monthly spend cap in cents (null when cleared). */
maxMonthlySpendCents: number | null;
/** The subscription's entitlement version after the write, when returned. */
entitlementVersion?: number;
}
Declaration source: packages/farthershore-js/dist/resources/plans.d.ts#L27.
export interface StartOnboardingInput__af7cf0dea526 extends Omit<SubscribeInput__62c7cb21d77a, "compiledPlanId"> {
compiledPlanId?: string;
}
Declaration source: packages/farthershore-js/dist/resources/plans.d.ts#L5.
export interface SubscribeInput__62c7cb21d77a {
/** The plan to subscribe to — pass `plan.id`. */
compiledPlanId: string;
/** Owning org for org-owned subscriptions (forwarded as the
* `organizationId` query + header). */
organizationId?: string | null;
/** Where Stripe redirects after a successful paid checkout. */
successUrl?: string;
/** Where Stripe redirects if the subscriber abandons checkout. */
cancelUrl?: string;
/** OPTIONAL price-consent echo (E2 — Managed Stripe Price Integrity): the
* `offerFingerprint` from `getPlanOffers()`. When provided and the plan's
* economics changed since the offer was rendered, core rejects with
* 409 PLAN_OFFER_CHANGED (typed as `FartherShorePlanOfferChangedError`) and
* creates NO session — catch it, refetch offers, and re-present the price.
* Omit for today's unguarded behavior. */
offerFingerprint?: string;
}
Declaration source: packages/farthershore-js/dist/resources/plans.d.ts#L44.
export interface SubscribeResult__4b2d9557cede {
/** Stripe Checkout URL (paid plans only). Undefined for free activations. */
url?: string;
/** The activated subscriber (free plans only). Undefined for paid checkout. */
subscriber?: {
id: string;
businessId?: string | null;
status: string;
};
/** Server-side checkout-attempt id, when returned. */
checkoutAttemptId?: string;
/** Best-effort initial API key minted on free-plan activation, when present. */
autoApiKey?: string;
/** Set when the subscriber activated but the first-key mint FAILED — surfaced
* (not swallowed) so the caller can prompt a manual key creation. */
autoApiKeyError?: AutoApiKeyError;
}
Declaration source: packages/farthershore-js/dist/resources/account.d.ts#L13.
export interface TeamResource__b9e413854377 {
/** Team members on the current subscription. A failed read surfaces
* `{ ok:false, error }` (drives the SSR portal's read-only banner) — NOT a
* silent empty list. */
list(opts?: {
signal?: AbortSignal;
}): Promise<TeamListResult>;
/**
* Track T2 — subscriber-team invitations. Managers (OWNER/ADMIN) invite by
* email; the invitee accepts with the emailed token. Each method THROWS the
* typed `FartherShoreApiError` on validation/authz failure.
*/
invites: {
/** Pending invitations (OWNER/ADMIN). */
list(opts?: {
signal?: AbortSignal;
}): Promise<TeamInvitation[]>;
/** Create an invitation. `role` defaults to VIEWER; `businessRoleKeys` must
* be a subset of the caller's own permissions (403 otherwise). Returns the
* invitation plus the one-time raw token. */
create(input: {
email: string;
role?: TeamRole;
businessRoleKeys?: string[];
}): Promise<TeamInvitationCreated>;
/** Revoke a pending invitation. */
revoke(invitationId: string): Promise<void>;
/** Accept an invitation with its token. The signed-in user's email must
* match the invite (403 mismatch; 409 expired/already-used). */
accept(token: string): Promise<TeamInvitationAccepted>;
};
updateRole(membershipId: string, role: TeamRole): Promise<TeamMember>;
remove(membershipId: string): Promise<void>;
/**
* Set-replace a member's Managed-RBAC product-role assignment (FAR-698):
* the given list becomes the member's full assignment; `[]` clears it.
* Every key must reference an existing role. Throws the typed
* `FartherShoreApiError` on validation/authz failures.
* Client-side role gating is UX only; the gateway's `permission`
* constraint is the security boundary.
*/
assignRoles(membershipId: string, roles: string[]): Promise<TeamMember>;
}
Declaration source: packages/farthershore-js/dist/config.d.ts#L80.
export type TokenProvider__40095f0da8e4 = () => string | null | undefined | Promise<string | null | undefined>;
Declaration source: packages/farthershore-js/dist/types.d.ts#L595.
type UsageLimitCreateMode__f16ef2d50497 = {
mode: "BLOCK";
notifyAtPct?: never;
} | {
mode: "NOTIFY";
notifyAtPct: number;
};
Declaration source: packages/farthershore-js/dist/types.d.ts#L628.
type UsageLimitExplicitUpdateMode__577df72501b7 = {
mode: "BLOCK";
notifyAtPct?: null;
} | {
mode: "NOTIFY";
notifyAtPct: number;
};
Declaration source: packages/farthershore-js/dist/types.d.ts#L614.
type UsageLimitNoUpdateValue__cd3ce2b61e4f = {
limitUnits?: never;
limitCents?: never;
};
Declaration source: packages/farthershore-js/dist/resources/usage-limits.d.ts#L3.
export interface UsageLimitsResource__2b1e05e6bcda {
/** List the current subscriber organization's visible per-actor limits.
* `options.signal` is accepted for source compatibility but does not cancel
* the shared cached fetch; the cache owns the request lifecycle. */
list(options?: {
signal?: AbortSignal;
limit?: number;
offset?: number;
}): Promise<UsageLimitListResponse>;
/** Create a subscriber-authored usage limit. */
create(input: CreateUsageLimitInput): Promise<UsageLimit>;
/** Update mutable value, mode, or threshold fields. */
update(limitId: string, input: UpdateUsageLimitInput): Promise<UsageLimit>;
/** Permanently remove a subscriber-authored usage limit. */
delete(limitId: string): Promise<UsageLimitDeleteResult>;
}
Declaration source: packages/farthershore-js/dist/types.d.ts#L618.
type UsageLimitUpdateMode__0a6925ca669e = {
mode?: never;
notifyAtPct?: number | null;
} | {
mode: "BLOCK";
notifyAtPct?: null;
} | {
mode: "NOTIFY";
notifyAtPct: number;
};
Declaration source: packages/farthershore-js/dist/types.d.ts#L607.
type UsageLimitUpdateValue__e8f19d3e563b = {
limitUnits: number;
limitCents?: never;
} | {
limitCents: number;
limitUnits?: never;
};
Declaration source: packages/farthershore-js/dist/resources/usage.d.ts#L3.
export interface UsageRange__216cd12bcfd1 {
from?: string;
to?: string;
}
Declaration source: packages/farthershore-js/dist/resources/usage.d.ts#L7.
export interface UsageResource__a3469cda0e70 {
/** Dimension → total for the period (requests/tokens/computeMs/dollars…).
*
* `opts.signal` is accepted for source-compat but does NOT cancel the shared
* cached fetch (the cache owns the fetch lifecycle); the read is unmount-safe
* via the hook's active-flag and bounded by the cache TTL. */
summary(range?: UsageRange__216cd12bcfd1, opts?: {
signal?: AbortSignal;
}): Promise<UsageSummary>;
/** The most-recent usage events (platform caps this list).
*
* `opts.signal` is accepted for source-compat but does NOT cancel the shared
* cached fetch (the cache owns the fetch lifecycle); the read is unmount-safe
* via the hook's active-flag and bounded by the cache TTL. */
events(range?: UsageRange__216cd12bcfd1, opts?: {
signal?: AbortSignal;
}): Promise<UsageEvent[]>;
/** Everything in one round-trip: per-dimension totals + recent events + the
* billing basis (the "Requests" vs "Usage" meter-label hint).
*
* `opts.signal` is accepted for source-compat but does NOT cancel the shared
* cached fetch (the cache owns the fetch lifecycle); the read is unmount-safe
* via the hook's active-flag and bounded by the cache TTL. */
snapshot(range?: UsageRange__216cd12bcfd1, opts?: {
signal?: AbortSignal;
includeEvents?: boolean;
}): Promise<UsageSnapshot>;
}