@farthershore/client 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/README.md +252 -2
  3. package/dist/index.js +7009 -0
  4. package/dist/types/api.generated.d.ts +1362 -0
  5. package/dist/types/credentials.d.ts +78 -0
  6. package/dist/types/envelope.d.ts +48 -0
  7. package/dist/types/errors.d.ts +86 -0
  8. package/dist/types/generated/schemas.d.ts +3670 -0
  9. package/dist/types/helpers/abort.d.ts +7 -0
  10. package/dist/types/helpers/paginate.d.ts +32 -0
  11. package/dist/types/helpers/poll.d.ts +26 -0
  12. package/dist/types/helpers/refs.d.ts +84 -0
  13. package/dist/types/helpers/wait-for-frontend-build.d.ts +51 -0
  14. package/dist/types/index.d.ts +24 -0
  15. package/dist/types/operations/agents.d.ts +240 -0
  16. package/dist/types/operations/agreements.d.ts +174 -0
  17. package/dist/types/operations/analytics.d.ts +47 -0
  18. package/dist/types/operations/audit-notifications.d.ts +90 -0
  19. package/dist/types/operations/auth.d.ts +24 -0
  20. package/dist/types/operations/backends.d.ts +255 -0
  21. package/dist/types/operations/billing.d.ts +71 -0
  22. package/dist/types/operations/businesses.d.ts +795 -0
  23. package/dist/types/operations/change-sets.d.ts +462 -0
  24. package/dist/types/operations/consumers.d.ts +168 -0
  25. package/dist/types/operations/define.d.ts +102 -0
  26. package/dist/types/operations/environments.d.ts +55 -0
  27. package/dist/types/operations/frontend.d.ts +31 -0
  28. package/dist/types/operations/index.d.ts +4773 -0
  29. package/dist/types/operations/maker-tokens.d.ts +194 -0
  30. package/dist/types/operations/organizations.d.ts +373 -0
  31. package/dist/types/operations/personas.d.ts +136 -0
  32. package/dist/types/operations/plans-usage.d.ts +84 -0
  33. package/dist/types/operations/platform.d.ts +455 -0
  34. package/dist/types/operations/portal.d.ts +442 -0
  35. package/dist/types/operations/promo-codes.d.ts +139 -0
  36. package/dist/types/operations/variables.d.ts +188 -0
  37. package/dist/types/operations/webhooks.d.ts +130 -0
  38. package/dist/types/surface-types.d.ts +76 -0
  39. package/dist/types/surface.d.ts +35 -0
  40. package/dist/types/transport.d.ts +114 -0
  41. package/dist/types/types.d.ts +440 -0
  42. package/dist/types/version.d.ts +8 -0
  43. package/package.json +53 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,196 @@
1
+ # Changelog — @farthershore/client
2
+
3
+ All notable changes to the API client are documented here. This package
4
+ versions independently from the CLI and the other SDKs. Pre-1.0: minor versions
5
+ may include breaking changes.
6
+
7
+ ## [0.2.0] - 2026-10-14
8
+
9
+ ### Changed
10
+
11
+ - **Breaking:** the last untyped `businesses.*` methods are typed from the zod
12
+ schemas in `@farthershore/contracts/business-contract-response`; no method
13
+ output is `unknown`, a loose record or an index signature any more.
14
+ `routes.read` → `BusinessRouteList` (one row per route, no compiled row
15
+ `id`), `contract.read` → `BusinessContract` (limits and meters typed),
16
+ `config.read` → `BusinessConfig` (`state: accepted | none | unreadable`,
17
+ the contract as `AcceptedBusinessContract` without an upstream credential's
18
+ token; no `ok`, contract hash or raw sync error; `githubSha` → `commitSha`,
19
+ `githubSyncStatus` → `repositorySyncStatus`), `configAttempts.read` →
20
+ `BusinessConfigAttemptList` (no raw proposal or payload), `status` →
21
+ `BusinessStatusResult` (runs report `publishStatus` / `billingStatus`;
22
+ applies' phases are `publish` / `billing`; `edgeCoherence` is replaced by
23
+ `serving: { status, coherent, message }`), `compile` →
24
+ `BusinessValidateResult` (was `ManifestCompileResult`; no record id, IR or
25
+ spec hash), `rbac.subjects.read` → `CustomPermissionSubjectList`,
26
+ `rbac.enable`/`disable` → `BusinessRbacUpdateResult`, `brand.uploadAsset` →
27
+ `BrandAssetUploadResult`, `subdomainAvailability.read` →
28
+ `ManagedSubdomainAvailability`. `PaginatedResult` and
29
+ `ManifestCompileDiagnostic` are removed (`BusinessDiagnostic`).
30
+ - **Breaking:** portal service-account / usage-limit and caller-identity
31
+ responses are typed from the zod schemas in
32
+ `@farthershore/contracts/{portal,auth}-response`. Every `portal.*` method
33
+ returns a real type instead of `unknown` (`PortalServiceAccountList`,
34
+ `PortalServiceAccountCreateResult`, …, `PortalUsageLimit(List)`,
35
+ `PortalUsageLimitDeleteResult`); `auth.context.issue` returns
36
+ `ContextTokenIssuance`. `MakerTokenContext` no longer carries `authVersion`;
37
+ `BuilderBootstrapContext` is the closed bootstrap (no `user.clerkUserId`,
38
+ organizations named by `{ id, type, name, slug }`).
39
+ - **Breaking:** operating-agent, bulletin, automation-rule, Knowledge Registry
40
+ and platform-operation responses are typed from the zod schemas in
41
+ `@farthershore/contracts/{agent,automation-rule,knowledge,platform-ops}-response`.
42
+ `AgentSummary`, `AgentStatus`, `AgentRunSummary` and `BulletinPost` are
43
+ closed (agent `config` is the closed `AgentConfig`); `agents.runs.show`
44
+ returns `AgentRunDetail` (was `Record<string, unknown>`); `automationRules.*`,
45
+ `knowledge.*.read`, `platform.resourceCounts.report`, `platform.denials.read`,
46
+ `platform.dependents.read` and `platform.workflowControl.{replay,rollback}`
47
+ return `AutomationRule(List)`, `KnowledgeIndex`, `ResourceCountReport`,
48
+ `DenialExplanation`, `BusinessDependents`, `ReplayResult` and
49
+ `ConfigRollbackPreview` instead of `unknown`. A run's `errorMessage` is a
50
+ fixed description of its `errorCode`; a run detail drops `traceRef` and
51
+ renames `resultJson` / `traceJson` to `result` / `trace`; an action receipt
52
+ carries `summary` / `reason` instead of its stored result. A config rollback
53
+ preview reports `currentCommitSha` (was `currentGithubSha`).
54
+ - **Breaking:** analytics, usage, plan-list and billing-connection responses
55
+ are typed from `@farthershore/contracts/{analytics,usage,billing}-response`.
56
+ `analytics.timeseries` / `latency` / `top` / `log` return their verb's
57
+ `{ result }` (`AnalyticsTimeseriesResult`, `AnalyticsPercentilesResult`,
58
+ `AnalyticsTopKResult`, `AnalyticsEventFeedResult`; `analytics.query` returns
59
+ `AnalyticsQueryResult`); `plans.read` returns `PlanList`, `usage.read`
60
+ `UsageSummary`, `usage.limits` `ManagementUsageLimitList`,
61
+ `billing.stripe.read` `StripeConnectionStatus`, `billing.stripe.delete`
62
+ `StripeDisconnectResult`, and `billing.taxSettings.read` / `update`
63
+ `TaxSettings` (all were `unknown`). Event-feed rows carry `request` instead
64
+ of the archived `payload`; the usage summary's `activeRuntimeKeys` is
65
+ `activeApiKeys`; usage limits name `plan: { key, version }` instead of
66
+ subscription and plan-version ids; the Stripe status has no account id.
67
+ - **Breaking:** variables, frontend, audit-log and notification-preference
68
+ responses are typed from the zod schemas in
69
+ `@farthershore/contracts/variable-response`, `frontend-response`,
70
+ `audit-log-response` and `communication`. `frontend.status` returns
71
+ `FrontendStatusResult`, `frontend.rollback` `FrontendRollbackResult` (a
72
+ preview `FrontendRollbackPreview`), `auditLogs.read` /
73
+ `auditLogs.business.read` `AuditLogPage`, and
74
+ `notifications.preferences.*` `NotificationPreferences`, instead of
75
+ `unknown`. `BusinessVariableRow` and `SecretMutationOperation` are generated
76
+ and closed: an operation drops `mutationId`, `state` and `result`, and its
77
+ `impact` is `{ integrations, subscriberCount }`; `generation` is `version`
78
+ on both. Frontend status renames
79
+ `activeReleaseHash` to `activeReleaseId` and a build's `manifestHash` to
80
+ `releaseId`.
81
+ - **Breaking:** `waitForFrontendBuild` reads the typed status (no `data`
82
+ envelope fallback); `BuildWaitResult.status` is the build status union (or
83
+ `UNKNOWN`). `readBuildDiagnostics` is removed: a build's `diagnostics` are
84
+ already typed.
85
+
86
+ - **Breaking:** agreement, promo-code and test-persona responses are typed from
87
+ the zod schemas in `@farthershore/contracts/{agreement,promo-code,persona}-response`.
88
+ `EconomicAgreement`, `SubjectPins` and `PromoCode` are closed; `AgreementPreview`
89
+ splits into `AgreementCreatePreview` / `AgreementAmendPreview` (typed effects);
90
+ `agreements.read` returns `EconomicAgreementList`; `personas.bootstrap`,
91
+ `personas.read`, `personas.rotate` and `personas.delete` return
92
+ `TestPersonaBootstrapResult`, `TestPersonaList`, `TestPersonaRotateResult` and
93
+ `TestPersonaDeleteResult` instead of `unknown`. `personas.bootstrap` no longer
94
+ takes `compiledPlanId` (pass `planKey`).
95
+ - **Breaking:** change set and Apply Timeline responses are typed from the zod
96
+ schemas in `@farthershore/contracts/change-set-response`.
97
+ `changeSets.propose` / `preview` / `proposalRead` return `ChangeSet`,
98
+ `proposalList` returns `ChangeSetList` (all were `unknown`), and a
99
+ `propose(…, { dryRun: true })` preview is typed `ChangeSetProposePreview`.
100
+ `ApplyTimelineEntry` / `ApplyTimelineEntryList` are closed and generated (the
101
+ list carries `environmentId`; apply phases are `publish` and `billing`).
102
+ - **Breaking:** organization and maker-token responses are typed from the zod
103
+ schemas in `@farthershore/contracts/organization-response` and
104
+ `maker-token-response`. Every `organizations.*` and `makerTokens.*` method
105
+ returns a real type instead of `unknown` (`OrganizationList`,
106
+ `OrganizationMembers`, `OrganizationRoleList`, `OrganizationOverview`,
107
+ `OrganizationBulletin`, `MakerTokenList`, `OrgMakerTokenCreateResult`,
108
+ `MakerTokenRotation`, …). `organizations.invitation.create` no longer
109
+ returns the accept token (it goes to the invitee by email only), so its
110
+ `meta.oneTimeSecret` is now `false` (code mode no longer gates or redacts it);
111
+ `makerTokens.create` takes a typed `businessScope`.
112
+ - **Breaking:** environment responses are typed from the zod schemas in
113
+ `@farthershore/contracts/environment-response`. `EnvironmentSummary` and
114
+ `EnvironmentListResult` are closed (no index signature; `branch` is always a
115
+ string), and `environments.create` returns the new `EnvironmentCreateResult`
116
+ (the environment plus `created` and `branchCreated`) instead of `unknown`.
117
+ - **Breaking:** business responses are typed from the zod schema in
118
+ `@farthershore/contracts` (generated into `src/generated/schemas.ts`).
119
+ `BusinessSummary` is closed (no index signature) and lists exactly what the
120
+ server sends; `businesses.read` / `businesses.rbac.read` return the new
121
+ `BusinessDetail` (with `environments`), `businesses.create` returns
122
+ `BusinessCreateResult` instead of `unknown`, and `businesses.publish` returns
123
+ `PublishBusinessResult` (a `{ dryRun: true }` call resolves to
124
+ `DryRunPreview<PublishBusinessResult>`, also exported as
125
+ `PublishBusinessPreview`). `PublishRelease` is derived from the same schema.
126
+ Each business plan carries `featured`.
127
+ - **Breaking:** backend and runtime-token responses are typed from the zod
128
+ schemas in `@farthershore/contracts/backend-response`. `backends.read` returns
129
+ `BackendList`, `backends.create` returns `BackendCreateResult` (a preview
130
+ resolves to `DryRunPreview<BackendCreatePreview>`), `backends.bind` returns
131
+ `BackendSummary`, `backends.delete` returns
132
+ `BackendDeleteResult`, `runtimeTokens.read` returns `RuntimeTokenList`, and
133
+ `runtimeTokens.mint` / `runtimeTokens.rotate` return `RuntimeTokenIssuance`
134
+ (the one-time plaintext `token`). `RuntimeTokenSummary` is generated from the
135
+ same schema. A backend's lifecycle is one `status` field; `agentStatus`,
136
+ `provisionStatus`, `readinessState` and `originHostname` are gone.
137
+ - **Breaking:** webhook responses are typed from the zod schemas in
138
+ `@farthershore/contracts/webhook-response`. `webhooks.read` returns
139
+ `WebhookEndpointList`, `webhooks.create` returns
140
+ `WebhookEndpointCreateResult` (the one-time signing `secret`),
141
+ `webhooks.update` returns `WebhookEndpointUpdateResult`,
142
+ `webhooks.rotateSecret` returns `WebhookEndpointRotateSecretResult` (the new
143
+ one-time `secret` plus `previousSecretExpiresAt`), `webhooks.delete` returns
144
+ `WebhookEndpointDeleteResult`, `webhooks.delivery.read` returns
145
+ `WebhookDeliveryList`, and `webhooks.eventType.read` returns
146
+ `WebhookEventTypeList`. `WebhookEndpoint`, `WebhookDelivery` and
147
+ `WebhookTestResult` are closed and generated from the same schemas; a
148
+ listed or updated endpoint has no `secret` field. A delivery's `status` is
149
+ `pending`, `success`, `failed` or `dead`; a test result always carries
150
+ `status`, `deliveryId`, `responseBody` and `error` (null when absent).
151
+ - New `webhooks.delivery.get({ businessId, webhookId, deliveryId })` returns
152
+ `WebhookDeliveryResult`: one delivery's metadata, the same fields as the
153
+ list. Neither the event payload nor the endpoint's response body is
154
+ returned (both can carry subscriber PII; no permission gates them yet).
155
+ - **Breaking:** consumer responses are typed from the zod schemas in
156
+ `@farthershore/contracts/consumer-response`. `consumers.read` returns
157
+ `BusinessConsumerList`, `consumers.migrateLatest` returns
158
+ `ConsumerMigrateLatestResult` (was `unknown`), `consumers.role.list` returns
159
+ `ConsumerRbacRoleList` and `consumers.apiKeys.list` returns
160
+ `ConsumerApiKeyList`; the other consumer types are generated from the same
161
+ schemas and closed. A member carries `accountRole` only (the stored `role`
162
+ enum is gone, also from `consumers.roles.assign`, which drops the membership
163
+ `id`). Migrate-latest answers `{ migrated, subscriberId, reason? }` with no
164
+ plan-version or subscription ids. `ConsumerRbacSettingsResult.defaultRoleKey`
165
+ is always present (null when unset).
166
+ - `operation<I, O, W>` takes an optional third type, the preview's `wouldHave`
167
+ when it differs from the output; `DryRunPreview<W>` uses it.
168
+
169
+ ## [0.1.0] - 2026-10-12
170
+
171
+ ### Added
172
+
173
+ - `createFartherShore({ transport })`: the namespaced operation surface
174
+ (`fs.<namespace>.<method>(input, { signal, dryRun, retry })`), one method
175
+ per operation key at its derived namespace path, each with static `meta`
176
+ (summary, description, side effect, destructive, one-time secret, preview,
177
+ reconcile read, pagination, permission). `fs.call(opKey, …)` and
178
+ `listOperations()` for discovery. `dryRun` is refused locally on operations
179
+ without a preview; an `OUTCOME_UNKNOWN` error carries
180
+ `details.reconcile = { op }`.
181
+ - Helpers: `paginate` / `collect` (offset and cursor), `createRefs` (business
182
+ and environment references), `poll`, `waitForFrontendBuild`.
183
+ - `createTransport`: the authenticated transport extracted from the
184
+ `farthershore` CLI, with its retry rules (reads retry on transient failures;
185
+ writes only on a server-proven refusal), `OUTCOME_UNKNOWN` reporting,
186
+ per-attempt deadlines that cover the body read, single-flight token exchange,
187
+ one re-exchange after a 401, `dryRun`, and an `AbortSignal` on every request.
188
+ - `x-fs-client: @farthershore/client/<version>` on every request, followed by
189
+ the caller's `clientInfo`.
190
+ - Credential sources: `cliExchangeCredentials`, `bearerCredentials`,
191
+ `consumerCredentials`.
192
+ - `FartherShoreError` / `FartherShoreTransportError` with `toJSON()`, and a
193
+ single error-envelope reader (`errorEnvelopeOf`, `diagnosticsOf`).
194
+ - `transport.raw()` for untyped requests to any path. It never follows a
195
+ redirect: any 3xx is `REDIRECT_NOT_FOLLOWED` with `details.location`,
196
+ never retried, and reported as an unknown outcome for a write.
package/README.md CHANGED
@@ -1,3 +1,253 @@
1
- # Temporary Holding Version
1
+ # @farthershore/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Farther Shore API client that the `farthershore` CLI runs on: a
4
+ namespaced, typed operation surface (`fs.runtimeTokens.revoke(…)`) over an
5
+ authenticated `fetch` transport with exact retry and outcome semantics,
6
+ pluggable credential sources, and typed errors.
7
+
8
+ > **Status: `0.2.0`.** Pre-1.0: minor releases may include breaking changes.
9
+ > Every response is typed. All but the publish-rollback receipt are generated
10
+ > from the platform's zod schemas (through the API's OpenAPI components), so a
11
+ > field exists in a type exactly when the server sends it.
12
+
13
+ ```sh
14
+ npm install @farthershore/client
15
+ ```
16
+
17
+ Works anywhere with a standard `fetch` (Node 22+, browsers, workers): the
18
+ package uses Web APIs only.
19
+
20
+ > Writing an agent or script against the client? See [`AGENTS.md`](./AGENTS.md)
21
+ > for the working summary: setup, metadata checks, retry rules, and code mode.
22
+
23
+ ## Quick start
24
+
25
+ ```ts
26
+ import {
27
+ createFartherShore,
28
+ createTransport,
29
+ cliExchangeCredentials,
30
+ } from "@farthershore/client";
31
+
32
+ const fs = createFartherShore({
33
+ transport: createTransport({
34
+ baseUrl: "https://api.example.com",
35
+ credentials: cliExchangeCredentials(process.env.FARTHERSHORE_TOKEN!),
36
+ surface: "my-tool",
37
+ }),
38
+ });
39
+
40
+ const businesses = await fs.businesses.list();
41
+ const revoked = await fs.runtimeTokens.revoke({ businessId, tokenId });
42
+ ```
43
+
44
+ ## The namespaced API
45
+
46
+ Every operation is a method `fs.<namespace>.<method>(input, options?)`:
47
+
48
+ - **input** is one object. Path parameters are named fields
49
+ (`{ businessId, tokenId }`); typed body fields sit next to them; endpoints
50
+ whose body is an open record take it as `body`.
51
+ - **options** are `{ signal?, dryRun?, retry? }`. `signal` cancels the request
52
+ and any retry wait. `dryRun: true` asks for a preview and is accepted only
53
+ where `method.meta.preview` is true; anywhere else the method throws
54
+ `DRY_RUN_NOT_SUPPORTED` before sending anything. `retry: "none"` makes a
55
+ single attempt.
56
+
57
+ The namespace path comes from the operation key (`runtime_token.revoke` →
58
+ `fs.runtimeTokens.revoke`). The namespaces:
59
+
60
+ | Namespace | Covers |
61
+ | -------------------- | --------------------------------------------------------------------------------------- |
62
+ | `fs.agents` | Operating agents: list, status, runs, enable, disable |
63
+ | `fs.agreements` | Economic agreements: read, preview, create, amend, subject pins |
64
+ | `fs.analytics` | Event analytics: `timeseries`, `latency`, `top`, `log`, `query` |
65
+ | `fs.auditLogs` | Organization and business audit logs, CSV export |
66
+ | `fs.auth` | `context.read` (who am I), `context.issue`, `listOrganizations`, `selectedOrganization` |
67
+ | `fs.automationRules` | Automation rules |
68
+ | `fs.backends` | Backends: read, create, bind, delete |
69
+ | `fs.billing` | `stripe` (status, disconnect) and `taxSettings` |
70
+ | `fs.bulletin` | Business bulletin: list, read, ack, resolve |
71
+ | `fs.businesses` | Businesses, publish/rollback/status, `brand`, `docs`, `previewEnv`, `cors`, `rbac`, … |
72
+ | `fs.changeSets` | Governed ChangeSet proposals and the apply `timeline` |
73
+ | `fs.consumers` | Subscribers: read, block, remove, migrate, roles, RBAC, API keys |
74
+ | `fs.environments` | Preview environments: read, create, delete |
75
+ | `fs.frontend` | Hosted frontend: status, rollback |
76
+ | `fs.knowledge` | Knowledge index (guide, business) |
77
+ | `fs.makerTokens` | Organization maker tokens and their approvals |
78
+ | `fs.notifications` | Notification preferences |
79
+ | `fs.organizations` | Organizations, roles, members, invitations, ownership, overview |
80
+ | `fs.personas` | Test personas and local-preview sign-in |
81
+ | `fs.plans` | Compiled plans (read) |
82
+ | `fs.platform` | Denial explanations, dependents, resource counts, workflow replay/rollback previews |
83
+ | `fs.portal` | Subscriber plane (consumer credentials): service accounts, usage limits |
84
+ | `fs.promoCodes` | Promo codes |
85
+ | `fs.runtimeTokens` | Runtime tokens: read, mint, rotate, revoke |
86
+ | `fs.usage` | Usage |
87
+ | `fs.variables` | Write-only business variables and their asynchronous operations |
88
+ | `fs.webhooks` | Webhook endpoints, test/trigger, secret rotation, event types, deliveries |
89
+
90
+ Each method carries static metadata as `method.meta`:
91
+
92
+ ```ts
93
+ fs.runtimeTokens.revoke.meta;
94
+ // { path: "runtimeTokens.revoke", op: "runtime_token.revoke",
95
+ // summary, description, sideEffect: "write", destructive: true,
96
+ // oneTimeSecret: false, preview: false,
97
+ // reconcile: { op: "runtime_token.read" }, pagination: null,
98
+ // maxPageSize: null, permission: "runtime_token:revoke" }
99
+ ```
100
+
101
+ Portal-plane methods have no opKey; they declare the same safety and paging
102
+ flags themselves (`fs.portal.serviceAccounts.rotate.meta.oneTimeSecret` is
103
+ `true`). `paginate` clamps a requested `limit` to `meta.maxPageSize`, so a
104
+ server-capped page is never mistaken for the last one.
105
+
106
+ `fs.listOperations()` (also exported as `listOperations()`) returns that
107
+ metadata for every method, for discovery. `fs.call(opKey, input, options)`
108
+ runs an operation by its key.
109
+
110
+ A write that may have run without an answer proving it (`OUTCOME_UNKNOWN`)
111
+ carries the read that reconciles it: `error.details.reconcile = { op }`
112
+ (merged into the server's object `details`; a non-object `details` is left
113
+ as the server sent it). Run
114
+ that read before deciding whether to send the write again.
115
+
116
+ The surface never exposes the transport, the credential source, or a token.
117
+
118
+ ## Helpers
119
+
120
+ ```ts
121
+ import {
122
+ createRefs,
123
+ paginate,
124
+ poll,
125
+ waitForFrontendBuild,
126
+ } from "@farthershore/client";
127
+
128
+ // Every item of a paginated method (offset or cursor, from `meta.pagination`).
129
+ for await (const env of paginate(
130
+ fs.environments.read,
131
+ { businessId },
132
+ {
133
+ maxItems: 500,
134
+ signal,
135
+ },
136
+ )) {
137
+ console.log(env.name);
138
+ }
139
+
140
+ // Resolve references (pure lookups; no working directory or env vars).
141
+ const refs = createRefs(fs);
142
+ const businessId = await refs.business("acme");
143
+ const preview = await refs.environment(businessId, "preview");
144
+
145
+ // Wait for a condition.
146
+ const { value, timedOut } = await poll({
147
+ check: (signal) => fs.businesses.status({ businessId }, { signal }),
148
+ until: (status) => status.live,
149
+ intervalMs: 2_000,
150
+ deadlineMs: 120_000,
151
+ });
152
+
153
+ // Wait for a git-triggered frontend build to be built and served.
154
+ const build = await waitForFrontendBuild(fs, {
155
+ businessId,
156
+ ref: commitSha,
157
+ timeoutMs: 600_000,
158
+ });
159
+ ```
160
+
161
+ `paginate` fails with `PAGINATION_NOT_ADVANCING` rather than looping when a
162
+ page does not advance. A starting `offset` or `limit` may be a number or a
163
+ numeric string (`"50"`); anything else fails with `INVALID_PAGE_PARAMETER`
164
+ before a page is fetched. `collect(method, input, options)` gathers the items
165
+ into an array.
166
+
167
+ ## `createTransport`
168
+
169
+ ```ts
170
+ import { createTransport, cliExchangeCredentials } from "@farthershore/client";
171
+
172
+ const transport = createTransport({
173
+ baseUrl: "https://api.example.com",
174
+ credentials: cliExchangeCredentials(process.env.FARTHERSHORE_TOKEN!),
175
+ surface: "my-tool",
176
+ clientInfo: "my-tool/1.0.0",
177
+ });
178
+
179
+ const businesses = await transport.request("GET", "/businesses");
180
+ ```
181
+
182
+ Options: `baseUrl`, `credentials`, `surface` (sent as `x-fs-surface`), and
183
+ optionally `fetch` (defaults to `globalThis.fetch`), `organizationId` (id or
184
+ slug), `requiredOrganizationId` (refuses a credential acting in any other
185
+ organization), `clientInfo` (appended to the `x-fs-client`
186
+ header after `@farthershore/client/<version>`), and `retry`
187
+ (`{ attempts, sleep }`; `attempts` must be a whole number).
188
+
189
+ | Method | What it does |
190
+ | -------------------------------------------------------- | ------------------------------------------------------------- |
191
+ | `request(method, path, body?, options?)` | JSON request; resolves the parsed body (`undefined` for 204). |
192
+ | `requestRaw(method, path, bytes, contentType, options?)` | Binary body, JSON answer. |
193
+ | `requestText(method, path, options?)` | Text answer (CSV exports). |
194
+ | `raw(method, path, { query, body, headers, ... })` | Any path; resolves `{ status, headers, data }`. |
195
+ | `selectedOrganizationId()` | The organization the credential acts in. |
196
+ | `listOrganizations()` | Organizations a user login can act in. |
197
+
198
+ `raw` never follows a redirect, so caller headers never reach another
199
+ location: a 3xx answer fails with `REDIRECT_NOT_FOLLOWED` (the 3xx `status`,
200
+ `details.location`; `outcomeUnknown: true` for a write, which may have run).
201
+
202
+ Per-request `options`: `signal` (an `AbortSignal`), `headers`, `dryRun`
203
+ (appends `dry_run=true`), and `retry`:
204
+
205
+ - omitted: `GET`/`HEAD` are reads, everything else is a write;
206
+ - `"read"`: a read-only `POST` (queries, previews);
207
+ - `"write"`: force write handling;
208
+ - `"none"`: one attempt, same classification.
209
+
210
+ One exception applies to every mode: a refreshable credential
211
+ (`cliExchangeCredentials`) that the server rejects with 401 is re-minted and the
212
+ request is resent once, even with `"none"` or `attempts: 1`. A 401 means the
213
+ request did not run, so that resend cannot apply a write twice.
214
+
215
+ Reads are retried on network errors, timeouts, 429 and 5xx. Writes are retried
216
+ only when the server proves nothing ran (429, or an error marked `retryable`
217
+ with `retryDisposition: "safe_to_repeat"`). A write that may have run fails with
218
+ `outcomeUnknown: true`: read current state before sending it again. Key on
219
+ `outcomeUnknown`, not on `code`: when the server answered with an error
220
+ envelope the error keeps the server's own `code` (a 5xx write can be
221
+ `TEARDOWN_FAILED` with `outcomeUnknown: true`); `code: "OUTCOME_UNKNOWN"` is
222
+ used only when no server code arrived. Each attempt has a 30-second deadline that also covers
223
+ reading the response body.
224
+
225
+ ## Credential sources
226
+
227
+ | Source | Use |
228
+ | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
229
+ | `cliExchangeCredentials(token)` | A CLI login or maker token, exchanged for a short-lived access token and refreshed as needed. |
230
+ | `bearerCredentials(token)` | A static bearer token, sent as is. |
231
+ | `consumerCredentials({ token, environmentId, organizationId })` | A subscriber session acting in one environment and subscribing organization. |
232
+
233
+ A `CredentialSource` is `{ kind, getAccessToken({ signal, forceRefresh }) }`.
234
+ The transport keeps the source private: no transport method returns a token.
235
+ Give each transport its own source.
236
+
237
+ ## Errors
238
+
239
+ Request failures are `FartherShoreError`s with `status` (0 when no HTTP answer
240
+ arrived), `code`, `message`, `details`, `param`, `retryable`,
241
+ `retryDisposition`, `outcomeUnknown` and `cause`; an error from an HTTP answer
242
+ also carries that answer's `headers` (`Retry-After`, request ids). `toJSON()`
243
+ returns the plain data, without `headers`. Requests that got no answer throw `FartherShoreTransportError`
244
+ (`NETWORK_ERROR`, `TIMEOUT`, `REQUEST_ABORTED` or `OUTCOME_UNKNOWN`). A
245
+ custom `fetch` that resolves to something other than a response fails with
246
+ `INVALID_RESPONSE` (status 0; counted against the attempt limit for a read,
247
+ `outcomeUnknown: true` for a write). No outcome retries past `retry.attempts`.
248
+
249
+ Two deterministic failures stay native, because repeating them cannot help:
250
+ a successful read whose JSON body is malformed rejects with the parser's
251
+ `SyntaxError` (it is not retried), and a request `body` that `JSON.stringify`
252
+ cannot serialize (a `BigInt`, a cycle) throws its `TypeError` before anything
253
+ is sent.