@vxil/sdk 0.32.0 → 0.35.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.
- package/dist/index.d.ts +174 -24
- package/dist/index.js +154 -19
- package/dist/retry.d.ts +26 -3
- package/dist/retry.js +44 -7
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -9,9 +9,11 @@ export type ApiVersion = 'v1';
|
|
|
9
9
|
* onto their real namespaces (`vx.search` → `search`, `vx.feeds` → `feeds`). */
|
|
10
10
|
export type FeatureKey = 'users' | 'notifications' | 'config' | 'features' | 'audit' | 'usage' | 'jobs' | 'auth' | 'rate-limits' | 'files' | 'cms' | 'comments' | 'dm' | 'feeds' | 'realtime' | 'orgs' | 'webhooks' | 'search' | 'ai' | 'rag' | 'payments' | 'fn' | 'copilot';
|
|
11
11
|
/** Retry policy for the client (DEFAULT OFF: `attempts` is `0`). Only
|
|
12
|
-
* idempotent requests are ever retried — GET/HEAD/PUT/DELETE,
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* idempotent requests are ever retried — GET/HEAD/PUT/DELETE, a POST when the
|
|
13
|
+
* call carries an `Idempotency-Key` header (`{ idempotencyKey }` on the money
|
|
14
|
+
* routes), and the replay-safe files POSTs (`upload-url`, `complete`,
|
|
15
|
+
* `publish`, `publishMany` — retry.ts REPLAY_SAFE_POST_PATHS) — so a retry can
|
|
16
|
+
* never double-apply a write. cms item create is never retried. */
|
|
15
17
|
export interface VxilRetryOptions {
|
|
16
18
|
/** How many RETRIES to make after the first attempt (`2` ⇒ up to 3 requests).
|
|
17
19
|
* Default `0` = retries off. */
|
|
@@ -113,8 +115,10 @@ export interface VxilOptions {
|
|
|
113
115
|
* is `'v1'` for every feature. */
|
|
114
116
|
apiVersions?: Partial<Record<FeatureKey, ApiVersion>>;
|
|
115
117
|
/** Retry policy — DEFAULT OFF (`attempts: 0`). Only idempotent requests are
|
|
116
|
-
* ever retried (GET/HEAD/PUT/DELETE,
|
|
117
|
-
* `Idempotency-Key
|
|
118
|
+
* ever retried (GET/HEAD/PUT/DELETE, a POST that carries an
|
|
119
|
+
* `Idempotency-Key`, and the replay-safe files POSTs — `upload-url`,
|
|
120
|
+
* `complete`, `publish`, `publishMany`), so a retry can never double-apply a
|
|
121
|
+
* write. cms item create is never retried. See
|
|
118
122
|
* `VxilRetryOptions` for the schedule and `Retry-After` handling. */
|
|
119
123
|
retry?: VxilRetryOptions;
|
|
120
124
|
/** Per-attempt timeout in milliseconds (default: none). On expiry the
|
|
@@ -136,24 +140,68 @@ export interface Meta {
|
|
|
136
140
|
request_id: string;
|
|
137
141
|
tenant_id?: string;
|
|
138
142
|
}
|
|
143
|
+
/** The named form of `VxilError`'s optional fields: pass it as
|
|
144
|
+
* the 4th constructor argument instead of the positional list. */
|
|
145
|
+
export interface VxilErrorOptions {
|
|
146
|
+
hint?: string;
|
|
147
|
+
fixUrl?: string;
|
|
148
|
+
requestId?: string;
|
|
149
|
+
/** seconds, from `Retry-After` */
|
|
150
|
+
retryAfter?: number;
|
|
151
|
+
/** `error.reason` — a machine-readable refinement of `code` */
|
|
152
|
+
reason?: string;
|
|
153
|
+
/** `error.details` — structured, route-specific context */
|
|
154
|
+
details?: Record<string, unknown>;
|
|
155
|
+
/** the transport failure's original error (a `network_error`) */
|
|
156
|
+
cause?: unknown;
|
|
157
|
+
method?: string;
|
|
158
|
+
path?: string;
|
|
159
|
+
attempts?: number;
|
|
160
|
+
}
|
|
139
161
|
/** Every non-2xx answer is thrown as this class, carrying the structured error
|
|
140
|
-
* envelope. `status` is the HTTP status — or `0` when no response arrived
|
|
141
|
-
*
|
|
162
|
+
* envelope. `status` is the HTTP status — or `0` when no response arrived:
|
|
163
|
+
* a `timeoutMs` timeout (`code: 'request_timeout'`) or a transport failure
|
|
164
|
+
* (`code: 'network_error'` — DNS, a reset or `terminated` connection; the
|
|
165
|
+
* original error is `cause`, and `method` / `path` / `attempts` say which
|
|
166
|
+
* request failed after how many tries). A `network_error` on a write means
|
|
167
|
+
* the outcome is UNKNOWN: the server may have applied it.
|
|
168
|
+
*
|
|
169
|
+
* Construct it positionally (`status, code, message, hint, fixUrl, requestId,
|
|
170
|
+
* retryAfter, reason, transport`) or with an options object as the 4th
|
|
171
|
+
* argument (`new VxilError(422, 'validation_failed', 'm', { reason, details })`). */
|
|
142
172
|
export declare class VxilError extends Error {
|
|
143
173
|
readonly status: number;
|
|
144
174
|
readonly code: string;
|
|
145
|
-
readonly hint?: string
|
|
146
|
-
readonly fixUrl?: string
|
|
147
|
-
readonly requestId?: string
|
|
148
|
-
/** Seconds the server asked the caller to wait — parsed from `Retry-After`
|
|
149
|
-
* (delta-seconds or an HTTP-date) when the answer carried it (a rate
|
|
150
|
-
* limit, a busy upstream); otherwise undefined. */
|
|
151
|
-
readonly retryAfter?: number | undefined;
|
|
152
|
-
constructor(status: number, code: string, message: string, hint?: string | undefined, fixUrl?: string | undefined, requestId?: string | undefined,
|
|
175
|
+
readonly hint?: string;
|
|
176
|
+
readonly fixUrl?: string;
|
|
177
|
+
readonly requestId?: string;
|
|
153
178
|
/** Seconds the server asked the caller to wait — parsed from `Retry-After`
|
|
154
179
|
* (delta-seconds or an HTTP-date) when the answer carried it (a rate
|
|
155
180
|
* limit, a busy upstream); otherwise undefined. */
|
|
156
|
-
retryAfter?: number
|
|
181
|
+
readonly retryAfter?: number;
|
|
182
|
+
/** A machine-readable refinement of `code` when the API sends one
|
|
183
|
+
* (`error.reason`) — e.g. `'provider_auth'` on a payments 502
|
|
184
|
+
* `provider_error`: the provider refused the tenant's API key (rotate it;
|
|
185
|
+
* retrying fails the same way). Undefined when the answer carried none. */
|
|
186
|
+
readonly reason?: string;
|
|
187
|
+
/** Structured, route-specific context when the API sends it
|
|
188
|
+
* (`error.details`, e.g. cms `{ unique_fields }`); otherwise undefined. */
|
|
189
|
+
readonly details?: Record<string, unknown>;
|
|
190
|
+
/** The request that failed (set on `network_error`). */
|
|
191
|
+
readonly method?: string;
|
|
192
|
+
/** Its path, without host or query (set on `network_error`). */
|
|
193
|
+
readonly path?: string;
|
|
194
|
+
/** How many attempts were made, retries included (set on `network_error`). */
|
|
195
|
+
readonly attempts?: number;
|
|
196
|
+
constructor(status: number, code: string, message: string, options?: VxilErrorOptions);
|
|
197
|
+
constructor(status: number, code: string, message: string, hint?: string, fixUrl?: string, requestId?: string, retryAfter?: number, reason?: string,
|
|
198
|
+
/** the transport failure's details. */
|
|
199
|
+
transport?: {
|
|
200
|
+
cause?: unknown;
|
|
201
|
+
method?: string;
|
|
202
|
+
path?: string;
|
|
203
|
+
attempts?: number;
|
|
204
|
+
});
|
|
157
205
|
}
|
|
158
206
|
export interface VxilUser {
|
|
159
207
|
id: string;
|
|
@@ -274,6 +322,25 @@ export interface FeatureConfig {
|
|
|
274
322
|
version: number;
|
|
275
323
|
manifest: Record<string, unknown>;
|
|
276
324
|
}
|
|
325
|
+
/** The failure-alert digest settings (`webhooks.alerts`, guide ch. 12). The
|
|
326
|
+
* digest mails the project's owner accounts; `chatWebhook` (ALERT-CHAT-DEST)
|
|
327
|
+
* ALSO posts it as `{ text }` to a Google Chat / Slack / Teams Workflows
|
|
328
|
+
* webhook. `chatWebhook.secret` NAMES a secret stored under feature
|
|
329
|
+
* `webhooks` (the URL embeds the channel's token, so it is never a config
|
|
330
|
+
* value): store it first with `webhooks.alerts.storeChatWebhookUrl(url)` or
|
|
331
|
+
* `vxil secrets set webhooks/alerts_chat`. Allowed hosts: chat.googleapis.com,
|
|
332
|
+
* hooks.slack.com, *.webhook.office.com, *.logic.azure.com (https only; a
|
|
333
|
+
* redirect is never followed). */
|
|
334
|
+
export interface WebhooksAlerts {
|
|
335
|
+
enabled: boolean;
|
|
336
|
+
/** 'error' (default) or 'warn' (warn + error). */
|
|
337
|
+
minLevel?: 'warn' | 'error';
|
|
338
|
+
/** 5–1440 minutes (default 15), or 0 for immediate. */
|
|
339
|
+
digestMinutes?: number;
|
|
340
|
+
chatWebhook?: {
|
|
341
|
+
secret: string;
|
|
342
|
+
};
|
|
343
|
+
}
|
|
277
344
|
/** One rule in the advisory architecture brief. `title`, `fact`, `replaces` and
|
|
278
345
|
* `docs` are platform copy rendered by the server from a gate-checked rule
|
|
279
346
|
* catalog — they are never model prose. `why` explains why the rule applies to
|
|
@@ -412,7 +479,7 @@ export interface UsageCurrent {
|
|
|
412
479
|
limit_per_day: number;
|
|
413
480
|
/** CPU-ms charged to the daily budget today; null without a fresh snapshot */
|
|
414
481
|
cpu_ms_today: number | null;
|
|
415
|
-
/** the enforced daily CPU-ms budget (Free staging/development
|
|
482
|
+
/** the enforced daily CPU-ms budget on every plan (Free production 150,000, Free staging/development 500,000, paid: the plan row); null = none (Enterprise) */
|
|
416
483
|
cpu_ms_limit_per_day: number | null;
|
|
417
484
|
as_of: string | null;
|
|
418
485
|
} | null;
|
|
@@ -1796,6 +1863,11 @@ export interface PaymentsRefundFailedEventPayload {
|
|
|
1796
1863
|
reason: string | null;
|
|
1797
1864
|
source: 'api' | 'webhook';
|
|
1798
1865
|
environment: PaymentsEventEnvironment;
|
|
1866
|
+
/** (w40) why the provider call failed, when vxil knows: `'provider_auth'` =
|
|
1867
|
+
* the provider refused the project's API key (401/403 — expired, revoked or
|
|
1868
|
+
* missing a permission; rotate the key, a retry fails the same way); null
|
|
1869
|
+
* otherwise. `reason` stays the refund reason you passed. */
|
|
1870
|
+
failure_reason: 'provider_auth' | null;
|
|
1799
1871
|
level: 'warn';
|
|
1800
1872
|
state: 'broken';
|
|
1801
1873
|
}
|
|
@@ -1894,6 +1966,13 @@ export interface PaymentsSubscriptionRevokedEventPayload {
|
|
|
1894
1966
|
* row and a `/revoke` or `DELETE`; `null` for a store subscription
|
|
1895
1967
|
* (RevenueCat — the store, not vxil, controls renewal). */
|
|
1896
1968
|
provider_subscription_active: boolean | null;
|
|
1969
|
+
/** (w40) the ended row's environment — a provider row's own; for a manual
|
|
1970
|
+
* grant, the project's configured payments environment. Manual grants are
|
|
1971
|
+
* not uniform across events: their `payments.subscription.granted` carries
|
|
1972
|
+
* `environment: null`, and their `payments.subscription.lapsed` carries the
|
|
1973
|
+
* stored `'production'` placeholder — so filter a manual grant's lifecycle by
|
|
1974
|
+
* `subscription_id`, not by `environment`. */
|
|
1975
|
+
environment: PaymentsEventEnvironment;
|
|
1897
1976
|
level: 'info';
|
|
1898
1977
|
state: 'ok';
|
|
1899
1978
|
}
|
|
@@ -4488,13 +4567,16 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4488
4567
|
* the move continues in the background — wait for the
|
|
4489
4568
|
* `auth.user.rekeyed` event before reading owner-scoped rows as the
|
|
4490
4569
|
* merged user. The event is written when the pass finishes and is
|
|
4491
|
-
* best-effort past this response (see `anonymous.link.verify`).
|
|
4570
|
+
* best-effort past this response (see `anonymous.link.verify`).
|
|
4571
|
+
* A link returned to a test recipient answers `verified: false,
|
|
4572
|
+
* test_issued: true` (it signs in, but proves nothing about the mailbox). */
|
|
4492
4573
|
verify: (token: string, opts?: {
|
|
4493
4574
|
anonymous_token?: string;
|
|
4494
4575
|
}) => Promise<{
|
|
4495
4576
|
user_id: string;
|
|
4496
4577
|
session: AuthSession;
|
|
4497
4578
|
verified: boolean;
|
|
4579
|
+
test_issued?: true;
|
|
4498
4580
|
merged?: boolean;
|
|
4499
4581
|
rekeyed?: boolean;
|
|
4500
4582
|
}>;
|
|
@@ -4523,6 +4605,8 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4523
4605
|
test_code?: string;
|
|
4524
4606
|
test_link?: string;
|
|
4525
4607
|
}>;
|
|
4608
|
+
/** `verified: false, test_issued: true` for a code returned to a test
|
|
4609
|
+
* recipient (it signs in, but proves nothing about the mailbox). */
|
|
4526
4610
|
verify: (input: {
|
|
4527
4611
|
email: string;
|
|
4528
4612
|
code: string;
|
|
@@ -4530,6 +4614,7 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4530
4614
|
user_id: string;
|
|
4531
4615
|
session: AuthSession;
|
|
4532
4616
|
verified: boolean;
|
|
4617
|
+
test_issued?: true;
|
|
4533
4618
|
}>;
|
|
4534
4619
|
};
|
|
4535
4620
|
/** Anonymous (guest) sessions: instant end-user + session (JWT carries
|
|
@@ -4568,7 +4653,9 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4568
4653
|
* retried — treat `rekeyed: false` with no event within a minute or
|
|
4569
4654
|
* so as "poll your own rows", or re-run the idempotent
|
|
4570
4655
|
* `cms.items.reKey` / `files.reKey` / `payments.reKeySubscriptions`
|
|
4571
|
-
* routes from the `auth.user.merged` backstop.
|
|
4656
|
+
* routes from the `auth.user.merged` backstop. A `test_code` handed
|
|
4657
|
+
* back for an `otp.testRecipients` address proves no mailbox: the
|
|
4658
|
+
* claim goes through unverified, `verified: false, test_issued: true`. */
|
|
4572
4659
|
verify: (input: {
|
|
4573
4660
|
token: string;
|
|
4574
4661
|
email: string;
|
|
@@ -4577,6 +4664,7 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4577
4664
|
user_id: string;
|
|
4578
4665
|
email: string;
|
|
4579
4666
|
verified: boolean;
|
|
4667
|
+
test_issued?: true;
|
|
4580
4668
|
merged?: true;
|
|
4581
4669
|
rekeyed?: boolean;
|
|
4582
4670
|
session?: {
|
|
@@ -4601,7 +4689,10 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4601
4689
|
* else `verify`'s optional `locale`; no mute preference suppresses it). With
|
|
4602
4690
|
* the auth config's `security.emailChangeStepUp: true`, `request` answers
|
|
4603
4691
|
* 403 `step_up_required` unless this session passed `auth.stepUp` in the
|
|
4604
|
-
* last 300 s — retry with the rotated token.
|
|
4692
|
+
* last 300 s — retry with the rotated token. A `test_code` handed back
|
|
4693
|
+
* for an `otp.testRecipients` address proves no mailbox: its verify
|
|
4694
|
+
* changes the address unverified and answers `verified: false,
|
|
4695
|
+
* test_issued: true`. */
|
|
4605
4696
|
email: {
|
|
4606
4697
|
change: {
|
|
4607
4698
|
request: (input: {
|
|
@@ -4620,7 +4711,8 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
4620
4711
|
}) => Promise<{
|
|
4621
4712
|
user_id: string;
|
|
4622
4713
|
email: string;
|
|
4623
|
-
verified:
|
|
4714
|
+
verified: boolean;
|
|
4715
|
+
test_issued?: true;
|
|
4624
4716
|
}>;
|
|
4625
4717
|
};
|
|
4626
4718
|
};
|
|
@@ -5102,6 +5194,13 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5102
5194
|
* are never affected. Omitted/`[]` = ungated. ≤16 entries, each
|
|
5103
5195
|
* `^[a-z0-9][a-z0-9_-]{0,31}$` (the `orgs` role alphabet). */
|
|
5104
5196
|
write_roles?: string[];
|
|
5197
|
+
/** W39-3: role slugs whose VERIFIED holders MANAGE this owned collection
|
|
5198
|
+
* — get / list / count read every row, and the single-item update may
|
|
5199
|
+
* change another member's row (the owner field never moves; the
|
|
5200
|
+
* collection's hooks still decide the fields). Every other end-user
|
|
5201
|
+
* door stays owner-scoped. Needs `owner_field` and an end-user-writable
|
|
5202
|
+
* `end_user_access`. Omitted/`[]` = none. ≤16 entries. */
|
|
5203
|
+
manager_roles?: string[];
|
|
5105
5204
|
/** Retention (guide ch. 4): live items created more than this many days
|
|
5106
5205
|
* ago (1..3650) are soft-deleted by the nightly platform sweep — like a
|
|
5107
5206
|
* normal delete (no restore; purged at least 30 days later, unique values freed), with ONE
|
|
@@ -5175,6 +5274,8 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5175
5274
|
end_user_access?: CmsEndUserAccess;
|
|
5176
5275
|
/** present when the collection is role-gated for end-user writes */
|
|
5177
5276
|
write_roles?: string[];
|
|
5277
|
+
/** present when the collection names manager roles */
|
|
5278
|
+
manager_roles?: string[];
|
|
5178
5279
|
/** present when retention is set */
|
|
5179
5280
|
retain_days?: number;
|
|
5180
5281
|
/** present when a shorter deleted-item window is set */
|
|
@@ -5194,6 +5295,8 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5194
5295
|
end_user_access?: CmsEndUserAccess;
|
|
5195
5296
|
/** the roles an end user needs to write it (null / absent = ungated) */
|
|
5196
5297
|
write_roles?: string[] | null;
|
|
5298
|
+
/** W39-3: the roles that manage this owned collection (null / absent = none) */
|
|
5299
|
+
manager_roles?: string[] | null;
|
|
5197
5300
|
/** retention in days (null = keep until deleted; absent from an older server) */
|
|
5198
5301
|
retain_days?: number | null;
|
|
5199
5302
|
/** deleted-item recovery window in days (null = the default 30) */
|
|
@@ -5259,6 +5362,16 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5259
5362
|
collection: string;
|
|
5260
5363
|
write_roles: string[];
|
|
5261
5364
|
}>;
|
|
5365
|
+
/** W39-3: set (or clear, with `[]` / `null`) the collection's MANAGER
|
|
5366
|
+
* ROLES: a verified end user holding one reads every row of this owned
|
|
5367
|
+
* collection (get / list / count) and may update another member's row
|
|
5368
|
+
* through the single-item update; the collection's hooks still decide
|
|
5369
|
+
* the fields. Every other end-user door stays owner-scoped; server keys
|
|
5370
|
+
* are never affected. Audited; takes effect on the next request. */
|
|
5371
|
+
setManagerRoles: (collection: string, roles: string[] | null) => Promise<{
|
|
5372
|
+
collection: string;
|
|
5373
|
+
manager_roles: string[];
|
|
5374
|
+
}>;
|
|
5262
5375
|
/** Set (or clear, with `null`) the collection's WORKSPACE field (guide
|
|
5263
5376
|
* ch. 4, "Workspace-scoped collections"): a `string` field on an index
|
|
5264
5377
|
* slot (s1–s4) holding the orgs org id. A verified end user then reads and
|
|
@@ -5344,7 +5457,9 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5344
5457
|
};
|
|
5345
5458
|
items: {
|
|
5346
5459
|
/** `lock` serializes same-key writers (a per-key lock); `guard`
|
|
5347
|
-
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
5460
|
+
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
5461
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
5462
|
+
* server rules dropped (an owner-only or rule-controlled field). */
|
|
5348
5463
|
create: (collection: string, input: {
|
|
5349
5464
|
data: Record<string, unknown>;
|
|
5350
5465
|
status?: "draft" | "published";
|
|
@@ -5356,6 +5471,7 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5356
5471
|
status: string;
|
|
5357
5472
|
version: number;
|
|
5358
5473
|
data: Record<string, unknown>;
|
|
5474
|
+
dropped_fields?: string[];
|
|
5359
5475
|
}>;
|
|
5360
5476
|
/** Upsert by a declared `unique` field (guide ch. 4): creates the item, or
|
|
5361
5477
|
* — when a live item already holds `data[field]` — merges `patch` into
|
|
@@ -5418,8 +5534,12 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5418
5534
|
}>;
|
|
5419
5535
|
/** Merge-patch data keys; null clears a key. Concurrency opts (guide ch. 4):
|
|
5420
5536
|
* `ifVersion` → If-Match CAS; `if` → bounded field precondition against
|
|
5421
|
-
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
5422
|
-
|
|
5537
|
+
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
5538
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
5539
|
+
* server rules dropped, as on `create`. */
|
|
5540
|
+
patch: (collection: string, itemId: string, data: Record<string, unknown>, opts?: CmsWriteOpts) => Promise<Record<string, unknown> & {
|
|
5541
|
+
dropped_fields?: string[];
|
|
5542
|
+
}>;
|
|
5423
5543
|
/** Atomic in-database increment — PATCH `{ $inc: {field: delta} }`, ONE
|
|
5424
5544
|
* conditional UPDATE guarded by the field's validation min/max (the quota
|
|
5425
5545
|
* shape), the optional `if` precondition, and If-Match. 409
|
|
@@ -6063,6 +6183,36 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
6063
6183
|
/** Shared executor for the seen/read/archive notification-state endpoints. */
|
|
6064
6184
|
private feedsMark;
|
|
6065
6185
|
readonly webhooks: {
|
|
6186
|
+
/** The failure-alert digest (`webhooks.alerts`): owner e-mail, plus an
|
|
6187
|
+
* optional chat webhook. Thin over GET / PUT /v1/config/webhooks — the
|
|
6188
|
+
* write keeps every other webhooks setting and sends If-Match, so it
|
|
6189
|
+
* versions and rolls back like any config change. Needs features:read /
|
|
6190
|
+
* features:write. */
|
|
6191
|
+
alerts: {
|
|
6192
|
+
get: () => Promise<{
|
|
6193
|
+
version: number;
|
|
6194
|
+
alerts: WebhooksAlerts | null;
|
|
6195
|
+
}>;
|
|
6196
|
+
/** Merge `patch` into the current alerts settings and write. Pass
|
|
6197
|
+
* `chatWebhook: null` to remove the chat destination. That removes only
|
|
6198
|
+
* the config reference: the stored URL (a token-bearing credential)
|
|
6199
|
+
* stays in the secret store until you delete it —
|
|
6200
|
+
* `DELETE /v1/secrets/webhooks/<name>` (the dashboard's "Remove chat
|
|
6201
|
+
* webhook" does both). */
|
|
6202
|
+
set: (patch: Partial<Omit<WebhooksAlerts, "chatWebhook">> & {
|
|
6203
|
+
chatWebhook?: {
|
|
6204
|
+
secret: string;
|
|
6205
|
+
} | null;
|
|
6206
|
+
}) => Promise<FeatureConfig>;
|
|
6207
|
+
/** Store the chat webhook URL as an encrypted webhooks secret (write-only;
|
|
6208
|
+
* never readable back) and return the name to put in
|
|
6209
|
+
* `chatWebhook.secret`. Default name `alerts_chat`. Needs features:write. */
|
|
6210
|
+
storeChatWebhookUrl: (url: string, opts?: {
|
|
6211
|
+
secretName?: string;
|
|
6212
|
+
}) => Promise<{
|
|
6213
|
+
secret: string;
|
|
6214
|
+
}>;
|
|
6215
|
+
};
|
|
6066
6216
|
/**
|
|
6067
6217
|
* Subscribe an https endpoint to audit-stream events (optionally
|
|
6068
6218
|
* filtered by event-name prefixes like 'user.'). Deliveries are jobs
|
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* widens this union. Every path the SDK builds is major-versioned; the default
|
|
9
9
|
* is the compile-time constant `'v1'` (never a floating `latest` alias). */
|
|
10
10
|
import { qs } from './qs.js';
|
|
11
|
-
import { createTransport, parseRetryAfter, retryOnCapacity, CAPACITY_ERROR_CODES as CAPACITY_CODES } from './retry.js';
|
|
11
|
+
import { createTransport, parseRetryAfter, requestPath, retryOnCapacity, CAPACITY_ERROR_CODES as CAPACITY_CODES } from './retry.js';
|
|
12
12
|
/** The 429 error codes `retryOnCapacity` treats as "at a capacity cap — try the
|
|
13
13
|
* SAME request again shortly". Declared here with an explicit type (not a
|
|
14
14
|
* re-export) so the served single-file index.d.ts never imports ./retry. */
|
|
@@ -27,30 +27,98 @@ export function versionedPath(path, globalDefault, overrides) {
|
|
|
27
27
|
return `/${version}/${ns}${m[2]}`;
|
|
28
28
|
}
|
|
29
29
|
/** Every non-2xx answer is thrown as this class, carrying the structured error
|
|
30
|
-
* envelope. `status` is the HTTP status — or `0` when no response arrived
|
|
31
|
-
*
|
|
30
|
+
* envelope. `status` is the HTTP status — or `0` when no response arrived:
|
|
31
|
+
* a `timeoutMs` timeout (`code: 'request_timeout'`) or a transport failure
|
|
32
|
+
* (`code: 'network_error'` — DNS, a reset or `terminated` connection; the
|
|
33
|
+
* original error is `cause`, and `method` / `path` / `attempts` say which
|
|
34
|
+
* request failed after how many tries). A `network_error` on a write means
|
|
35
|
+
* the outcome is UNKNOWN: the server may have applied it.
|
|
36
|
+
*
|
|
37
|
+
* Construct it positionally (`status, code, message, hint, fixUrl, requestId,
|
|
38
|
+
* retryAfter, reason, transport`) or with an options object as the 4th
|
|
39
|
+
* argument (`new VxilError(422, 'validation_failed', 'm', { reason, details })`). */
|
|
32
40
|
export class VxilError extends Error {
|
|
33
41
|
status;
|
|
34
42
|
code;
|
|
35
43
|
hint;
|
|
36
44
|
fixUrl;
|
|
37
45
|
requestId;
|
|
38
|
-
retryAfter;
|
|
39
|
-
constructor(status, code, message, hint, fixUrl, requestId,
|
|
40
46
|
/** Seconds the server asked the caller to wait — parsed from `Retry-After`
|
|
41
47
|
* (delta-seconds or an HTTP-date) when the answer carried it (a rate
|
|
42
48
|
* limit, a busy upstream); otherwise undefined. */
|
|
43
|
-
retryAfter
|
|
49
|
+
retryAfter;
|
|
50
|
+
/** A machine-readable refinement of `code` when the API sends one
|
|
51
|
+
* (`error.reason`) — e.g. `'provider_auth'` on a payments 502
|
|
52
|
+
* `provider_error`: the provider refused the tenant's API key (rotate it;
|
|
53
|
+
* retrying fails the same way). Undefined when the answer carried none. */
|
|
54
|
+
reason;
|
|
55
|
+
/** Structured, route-specific context when the API sends it
|
|
56
|
+
* (`error.details`, e.g. cms `{ unique_fields }`); otherwise undefined. */
|
|
57
|
+
details;
|
|
58
|
+
/** The request that failed (set on `network_error`). */
|
|
59
|
+
method;
|
|
60
|
+
/** Its path, without host or query (set on `network_error`). */
|
|
61
|
+
path;
|
|
62
|
+
/** How many attempts were made, retries included (set on `network_error`). */
|
|
63
|
+
attempts;
|
|
64
|
+
constructor(status, code, message, hintOrOptions, fixUrl, requestId, retryAfter, reason, transport) {
|
|
44
65
|
super(message);
|
|
45
66
|
this.status = status;
|
|
46
67
|
this.code = code;
|
|
47
|
-
this.hint = hint;
|
|
48
|
-
this.fixUrl = fixUrl;
|
|
49
|
-
this.requestId = requestId;
|
|
50
|
-
this.retryAfter = retryAfter;
|
|
51
68
|
this.name = 'VxilError';
|
|
69
|
+
const o = typeof hintOrOptions === 'object' && hintOrOptions !== null
|
|
70
|
+
? hintOrOptions
|
|
71
|
+
: { hint: hintOrOptions, fixUrl, requestId, retryAfter, reason, ...transport };
|
|
72
|
+
if (o.hint !== undefined)
|
|
73
|
+
this.hint = o.hint;
|
|
74
|
+
if (o.fixUrl !== undefined)
|
|
75
|
+
this.fixUrl = o.fixUrl;
|
|
76
|
+
if (o.requestId !== undefined)
|
|
77
|
+
this.requestId = o.requestId;
|
|
78
|
+
if (o.retryAfter !== undefined)
|
|
79
|
+
this.retryAfter = o.retryAfter;
|
|
80
|
+
if (o.reason !== undefined)
|
|
81
|
+
this.reason = o.reason;
|
|
82
|
+
if (o.details !== undefined)
|
|
83
|
+
this.details = o.details;
|
|
84
|
+
if (o.cause !== undefined) {
|
|
85
|
+
Object.defineProperty(this, 'cause', { value: o.cause, enumerable: false, writable: true, configurable: true });
|
|
86
|
+
}
|
|
87
|
+
if (o.method !== undefined)
|
|
88
|
+
this.method = o.method;
|
|
89
|
+
if (o.path !== undefined)
|
|
90
|
+
this.path = o.path;
|
|
91
|
+
if (o.attempts !== undefined)
|
|
92
|
+
this.attempts = o.attempts;
|
|
52
93
|
}
|
|
53
94
|
}
|
|
95
|
+
/** `error.details` when the envelope carries an object one (else undefined). */
|
|
96
|
+
function detailsOf(e) {
|
|
97
|
+
return e.details !== null && typeof e.details === 'object' && !Array.isArray(e.details)
|
|
98
|
+
? e.details : undefined;
|
|
99
|
+
}
|
|
100
|
+
/** `error.reason` when the envelope carries a string one (else undefined). */
|
|
101
|
+
function reasonOf(e) {
|
|
102
|
+
return typeof e.reason === 'string' ? e.reason : undefined;
|
|
103
|
+
}
|
|
104
|
+
/** The thrown form of an `{ error }` envelope (every field the body carries). */
|
|
105
|
+
function envelopeError(res, e, requestId) {
|
|
106
|
+
const retryAfter = parseRetryAfter(res.headers.get('retry-after'));
|
|
107
|
+
const reason = reasonOf(e);
|
|
108
|
+
const details = detailsOf(e);
|
|
109
|
+
return new VxilError(res.status, e.code, e.message, {
|
|
110
|
+
...(e.hint !== undefined ? { hint: e.hint } : {}),
|
|
111
|
+
...(e.fixUrl !== undefined ? { fixUrl: e.fixUrl } : {}),
|
|
112
|
+
...(requestId !== undefined ? { requestId } : {}),
|
|
113
|
+
...(retryAfter !== undefined ? { retryAfter } : {}),
|
|
114
|
+
...(reason !== undefined ? { reason } : {}),
|
|
115
|
+
...(details !== undefined ? { details } : {}),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/** The feature that owns the alert digest config and its chat-webhook secret
|
|
119
|
+
* (called through the documented /v1/config/{feature} and
|
|
120
|
+
* /v1/secrets/{feature}/{name} routes). */
|
|
121
|
+
const ALERTS_FEATURE = 'webhooks';
|
|
54
122
|
/** The run states no later write can move — what `waitForRun` and an
|
|
55
123
|
* async+wait invoke resolve `done: true` on. */
|
|
56
124
|
export const JOB_TERMINAL_STATES = new Set(['succeeded', 'failed', 'dead', 'cancelled']);
|
|
@@ -218,7 +286,7 @@ export async function listCmsPublic(tenantId, collection, query, opts) {
|
|
|
218
286
|
}
|
|
219
287
|
if (!res.ok || parsed.error) {
|
|
220
288
|
const e = parsed.error ?? { code: `http_${res.status}`, message: text.slice(0, 200) };
|
|
221
|
-
throw
|
|
289
|
+
throw envelopeError(res, e, parsed.meta?.request_id);
|
|
222
290
|
}
|
|
223
291
|
return parsed.data ?? { items: [], next_cursor: null };
|
|
224
292
|
}
|
|
@@ -248,7 +316,7 @@ export async function postRunCallback(callbackUrl, body, opts) {
|
|
|
248
316
|
}
|
|
249
317
|
if (!res.ok || parsed.error || !parsed.data) {
|
|
250
318
|
const e = parsed.error ?? { code: `http_${res.status}`, message: text.slice(0, 200) };
|
|
251
|
-
throw
|
|
319
|
+
throw envelopeError(res, e, parsed.meta?.request_id);
|
|
252
320
|
}
|
|
253
321
|
return parsed.data;
|
|
254
322
|
}
|
|
@@ -289,6 +357,13 @@ export class Vxil {
|
|
|
289
357
|
...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),
|
|
290
358
|
...(opts.hooks ? { hooks: opts.hooks } : {}),
|
|
291
359
|
timeoutError: (ms) => new VxilError(0, 'request_timeout', `request timed out after ${ms}ms`),
|
|
360
|
+
// a transport failure is a VxilError too (one class
|
|
361
|
+
// to catch), with the original error as `cause`
|
|
362
|
+
networkError: (cause, info) => {
|
|
363
|
+
const path = requestPath(info.url);
|
|
364
|
+
const why = cause instanceof Error ? cause.message : String(cause);
|
|
365
|
+
return new VxilError(0, 'network_error', `network error: ${info.method} ${path} failed after ${info.attempts} attempt(s) — ${why}`, 'No response arrived. A read can be repeated; a write may already have been applied — check before repeating it (see the guide\'s replay-safe routes).', undefined, undefined, undefined, undefined, { cause, method: info.method, path, attempts: info.attempts });
|
|
366
|
+
},
|
|
292
367
|
});
|
|
293
368
|
}
|
|
294
369
|
/** The header bag every request layers on top of `authorization`: the
|
|
@@ -563,7 +638,7 @@ export class Vxil {
|
|
|
563
638
|
}
|
|
564
639
|
if (!res.ok || parsed.error) {
|
|
565
640
|
const e = parsed.error ?? { code: `http_${res.status}`, message: text.slice(0, 200) };
|
|
566
|
-
throw
|
|
641
|
+
throw envelopeError(res, e, parsed.meta?.request_id);
|
|
567
642
|
}
|
|
568
643
|
return { data: parsed.data, meta: parsed.meta ?? { request_id: '' }, response: res };
|
|
569
644
|
}
|
|
@@ -832,7 +907,7 @@ export class Vxil {
|
|
|
832
907
|
}
|
|
833
908
|
catch { /* non-JSON error body — fall through to the status default */ }
|
|
834
909
|
const e = env.error ?? { code: `http_${res.status}`, message: text.slice(0, 200) };
|
|
835
|
-
throw
|
|
910
|
+
throw envelopeError(res, e, env.meta?.request_id);
|
|
836
911
|
}
|
|
837
912
|
// Skip blank lines AND tolerate a single malformed NDJSON line rather
|
|
838
913
|
// than aborting the whole batch (e.g. a truncated final line on a large
|
|
@@ -1165,7 +1240,9 @@ export class Vxil {
|
|
|
1165
1240
|
* the move continues in the background — wait for the
|
|
1166
1241
|
* `auth.user.rekeyed` event before reading owner-scoped rows as the
|
|
1167
1242
|
* merged user. The event is written when the pass finishes and is
|
|
1168
|
-
* best-effort past this response (see `anonymous.link.verify`).
|
|
1243
|
+
* best-effort past this response (see `anonymous.link.verify`).
|
|
1244
|
+
* A link returned to a test recipient answers `verified: false,
|
|
1245
|
+
* test_issued: true` (it signs in, but proves nothing about the mailbox). */
|
|
1169
1246
|
verify: async (token, opts = {}) => (await this.call('POST', '/v1/auth/magic-link/verify', { token, ...(opts.anonymous_token !== undefined ? { anonymous_token: opts.anonymous_token } : {}) })).data,
|
|
1170
1247
|
},
|
|
1171
1248
|
/** Email OTP sign-in: a 6-digit single-use code (distinct from magic-link).
|
|
@@ -1183,6 +1260,8 @@ export class Vxil {
|
|
|
1183
1260
|
* budget. The link lands on your page with `?token=`, which you pass to
|
|
1184
1261
|
* `auth.magicLink.verify`. A test recipient gets `test_link` too. */
|
|
1185
1262
|
request: async (input) => (await this.call('POST', '/v1/auth/otp/request', input)).data,
|
|
1263
|
+
/** `verified: false, test_issued: true` for a code returned to a test
|
|
1264
|
+
* recipient (it signs in, but proves nothing about the mailbox). */
|
|
1186
1265
|
verify: async (input) => (await this.call('POST', '/v1/auth/otp/verify', input)).data,
|
|
1187
1266
|
},
|
|
1188
1267
|
/** Anonymous (guest) sessions: instant end-user + session (JWT carries
|
|
@@ -1210,7 +1289,9 @@ export class Vxil {
|
|
|
1210
1289
|
* retried — treat `rekeyed: false` with no event within a minute or
|
|
1211
1290
|
* so as "poll your own rows", or re-run the idempotent
|
|
1212
1291
|
* `cms.items.reKey` / `files.reKey` / `payments.reKeySubscriptions`
|
|
1213
|
-
* routes from the `auth.user.merged` backstop.
|
|
1292
|
+
* routes from the `auth.user.merged` backstop. A `test_code` handed
|
|
1293
|
+
* back for an `otp.testRecipients` address proves no mailbox: the
|
|
1294
|
+
* claim goes through unverified, `verified: false, test_issued: true`. */
|
|
1214
1295
|
verify: async (input) => (await this.call('POST', '/v1/auth/anonymous/link/verify', input)).data,
|
|
1215
1296
|
},
|
|
1216
1297
|
},
|
|
@@ -1229,7 +1310,10 @@ export class Vxil {
|
|
|
1229
1310
|
* else `verify`'s optional `locale`; no mute preference suppresses it). With
|
|
1230
1311
|
* the auth config's `security.emailChangeStepUp: true`, `request` answers
|
|
1231
1312
|
* 403 `step_up_required` unless this session passed `auth.stepUp` in the
|
|
1232
|
-
* last 300 s — retry with the rotated token.
|
|
1313
|
+
* last 300 s — retry with the rotated token. A `test_code` handed back
|
|
1314
|
+
* for an `otp.testRecipients` address proves no mailbox: its verify
|
|
1315
|
+
* changes the address unverified and answers `verified: false,
|
|
1316
|
+
* test_issued: true`. */
|
|
1233
1317
|
email: {
|
|
1234
1318
|
change: {
|
|
1235
1319
|
request: async (input) => (await this.call('POST', '/v1/auth/email/change/request', input)).data,
|
|
@@ -1646,6 +1730,13 @@ export class Vxil {
|
|
|
1646
1730
|
* unaffected; server keys are never affected. Audited; takes effect on
|
|
1647
1731
|
* the next write. */
|
|
1648
1732
|
setWriteRoles: async (collection, roles) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { write_roles: roles ?? [] })).data,
|
|
1733
|
+
/** W39-3: set (or clear, with `[]` / `null`) the collection's MANAGER
|
|
1734
|
+
* ROLES: a verified end user holding one reads every row of this owned
|
|
1735
|
+
* collection (get / list / count) and may update another member's row
|
|
1736
|
+
* through the single-item update; the collection's hooks still decide
|
|
1737
|
+
* the fields. Every other end-user door stays owner-scoped; server keys
|
|
1738
|
+
* are never affected. Audited; takes effect on the next request. */
|
|
1739
|
+
setManagerRoles: async (collection, roles) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { manager_roles: roles ?? [] })).data,
|
|
1649
1740
|
/** Set (or clear, with `null`) the collection's WORKSPACE field (guide
|
|
1650
1741
|
* ch. 4, "Workspace-scoped collections"): a `string` field on an index
|
|
1651
1742
|
* slot (s1–s4) holding the orgs org id. A verified end user then reads and
|
|
@@ -1740,7 +1831,9 @@ export class Vxil {
|
|
|
1740
1831
|
},
|
|
1741
1832
|
items: {
|
|
1742
1833
|
/** `lock` serializes same-key writers (a per-key lock); `guard`
|
|
1743
|
-
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
1834
|
+
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
1835
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
1836
|
+
* server rules dropped (an owner-only or rule-controlled field). */
|
|
1744
1837
|
create: async (collection, input) => (await this.call('POST', `/v1/cms/items/${encodeURIComponent(collection)}`, input)).data,
|
|
1745
1838
|
/** Upsert by a declared `unique` field (guide ch. 4): creates the item, or
|
|
1746
1839
|
* — when a live item already holds `data[field]` — merges `patch` into
|
|
@@ -1788,7 +1881,9 @@ export class Vxil {
|
|
|
1788
1881
|
},
|
|
1789
1882
|
/** Merge-patch data keys; null clears a key. Concurrency opts (guide ch. 4):
|
|
1790
1883
|
* `ifVersion` → If-Match CAS; `if` → bounded field precondition against
|
|
1791
|
-
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
1884
|
+
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
1885
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
1886
|
+
* server rules dropped, as on `create`. */
|
|
1792
1887
|
patch: async (collection, itemId, data, opts) => (await this.call('PATCH', `/v1/cms/items/${encodeURIComponent(collection)}/${encodeURIComponent(itemId)}`, {
|
|
1793
1888
|
data,
|
|
1794
1889
|
...(opts?.if ? { if: opts.if } : {}),
|
|
@@ -2125,6 +2220,46 @@ export class Vxil {
|
|
|
2125
2220
|
return { unseen, unread, total };
|
|
2126
2221
|
}
|
|
2127
2222
|
webhooks = {
|
|
2223
|
+
/** The failure-alert digest (`webhooks.alerts`): owner e-mail, plus an
|
|
2224
|
+
* optional chat webhook. Thin over GET / PUT /v1/config/webhooks — the
|
|
2225
|
+
* write keeps every other webhooks setting and sends If-Match, so it
|
|
2226
|
+
* versions and rolls back like any config change. Needs features:read /
|
|
2227
|
+
* features:write. */
|
|
2228
|
+
alerts: {
|
|
2229
|
+
get: async () => {
|
|
2230
|
+
const cfg = (await this.call('GET', `/v1/config/${ALERTS_FEATURE}`)).data;
|
|
2231
|
+
const a = cfg.manifest?.alerts;
|
|
2232
|
+
return { version: cfg.version, alerts: a && typeof a === 'object' ? a : null };
|
|
2233
|
+
},
|
|
2234
|
+
/** Merge `patch` into the current alerts settings and write. Pass
|
|
2235
|
+
* `chatWebhook: null` to remove the chat destination. That removes only
|
|
2236
|
+
* the config reference: the stored URL (a token-bearing credential)
|
|
2237
|
+
* stays in the secret store until you delete it —
|
|
2238
|
+
* `DELETE /v1/secrets/webhooks/<name>` (the dashboard's "Remove chat
|
|
2239
|
+
* webhook" does both). */
|
|
2240
|
+
set: async (patch) => {
|
|
2241
|
+
const cur = (await this.call('GET', `/v1/config/${ALERTS_FEATURE}`)).data;
|
|
2242
|
+
const prev = (cur.manifest?.alerts && typeof cur.manifest.alerts === 'object'
|
|
2243
|
+
? cur.manifest.alerts : {});
|
|
2244
|
+
const { chatWebhook, ...rest } = patch;
|
|
2245
|
+
const next = { enabled: false, ...prev, ...rest };
|
|
2246
|
+
if (chatWebhook === null)
|
|
2247
|
+
delete next.chatWebhook;
|
|
2248
|
+
else if (chatWebhook !== undefined)
|
|
2249
|
+
next.chatWebhook = chatWebhook;
|
|
2250
|
+
return (await this.call('PUT', `/v1/config/${ALERTS_FEATURE}`, { ...cur.manifest, alerts: next }, {
|
|
2251
|
+
'if-match': String(cur.version),
|
|
2252
|
+
})).data;
|
|
2253
|
+
},
|
|
2254
|
+
/** Store the chat webhook URL as an encrypted webhooks secret (write-only;
|
|
2255
|
+
* never readable back) and return the name to put in
|
|
2256
|
+
* `chatWebhook.secret`. Default name `alerts_chat`. Needs features:write. */
|
|
2257
|
+
storeChatWebhookUrl: async (url, opts) => {
|
|
2258
|
+
const name = opts?.secretName ?? 'alerts_chat';
|
|
2259
|
+
await this.call('PUT', `/v1/secrets/${ALERTS_FEATURE}/${encodeURIComponent(name)}`, { value: url });
|
|
2260
|
+
return { secret: name };
|
|
2261
|
+
},
|
|
2262
|
+
},
|
|
2128
2263
|
/**
|
|
2129
2264
|
* Subscribe an https endpoint to audit-stream events (optionally
|
|
2130
2265
|
* filtered by event-name prefixes like 'user.'). Deliveries are jobs
|
package/dist/retry.d.ts
CHANGED
|
@@ -7,10 +7,24 @@ export declare const DEFAULT_MAX_BACKOFF_MS = 10000;
|
|
|
7
7
|
* and an HTTP-date (`Wed, 21 Oct 2026 07:28:00 GMT`, measured from `nowMs`,
|
|
8
8
|
* floored at 0). */
|
|
9
9
|
export declare function parseRetryAfter(value: string | null | undefined, nowMs?: number): number | undefined;
|
|
10
|
+
/** the POST routes whose replay is safe WITHOUT an
|
|
11
|
+
* `Idempotency-Key` (matched on the URL path, any API major, query ignored):
|
|
12
|
+
* - files `upload-url` — a replay mints a second pending object, which the
|
|
13
|
+
* 24 h reaper removes (the caller uploads to the URL it got back);
|
|
14
|
+
* - files `complete`, `publish` (one object) and `publish` (many) — they set
|
|
15
|
+
* a state the object already has on a replay.
|
|
16
|
+
* cms item create is NOT here: a replay would create a second item. cms
|
|
17
|
+
* upsert (`onConflict`) is replay-safe only when `patch` is a subset of
|
|
18
|
+
* `data` — the caller opts in with its own `Idempotency-Key`. */
|
|
19
|
+
export declare const REPLAY_SAFE_POST_PATHS: ReadonlyArray<RegExp>;
|
|
20
|
+
/** The path of a request URL (no scheme/host, no query) — string-only, so it
|
|
21
|
+
* works where `URL` is partial (React Native). */
|
|
22
|
+
export declare function requestPath(url: string): string;
|
|
10
23
|
/** The retry gate: GET/HEAD/PUT/DELETE/OPTIONS are idempotent by definition; a
|
|
11
|
-
* POST
|
|
12
|
-
*
|
|
13
|
-
|
|
24
|
+
* POST when it carries a non-empty `Idempotency-Key` (any header case) or its
|
|
25
|
+
* path is on `REPLAY_SAFE_POST_PATHS` (when `url` is given); PATCH and any
|
|
26
|
+
* other bare POST never. */
|
|
27
|
+
export declare function isIdempotentRequest(method: string, headers: Record<string, string>, url?: string): boolean;
|
|
14
28
|
/** Exponential backoff with equal jitter: `min(max, base·2^(attempt−1))`
|
|
15
29
|
* scaled into `[½, 1]` by `random()` (inject `() => 1` for a deterministic
|
|
16
30
|
* schedule). `attempt` is the attempt that just failed (1-based). */
|
|
@@ -34,6 +48,15 @@ export interface TransportOptions {
|
|
|
34
48
|
/** Builds the error thrown when an attempt exceeds `timeoutMs` (index.ts
|
|
35
49
|
* supplies a `VxilError` so callers catch one error class). */
|
|
36
50
|
timeoutError: (timeoutMs: number) => Error;
|
|
51
|
+
/** builds the error thrown when `fetch` itself fails
|
|
52
|
+
* (DNS, reset, `terminated`) and no retry is left (index.ts supplies a
|
|
53
|
+
* `VxilError(0, 'network_error')` carrying the cause). Absent ⇒ the raw
|
|
54
|
+
* failure is rethrown. */
|
|
55
|
+
networkError?: (cause: unknown, info: {
|
|
56
|
+
method: string;
|
|
57
|
+
url: string;
|
|
58
|
+
attempts: number;
|
|
59
|
+
}) => Error;
|
|
37
60
|
sleep?: (ms: number) => Promise<void>;
|
|
38
61
|
random?: () => number;
|
|
39
62
|
now?: () => number;
|
package/dist/retry.js
CHANGED
|
@@ -27,16 +27,42 @@ export function parseRetryAfter(value, nowMs = Date.now()) {
|
|
|
27
27
|
return undefined;
|
|
28
28
|
return Math.max(0, (at - nowMs) / 1000);
|
|
29
29
|
}
|
|
30
|
+
/** the POST routes whose replay is safe WITHOUT an
|
|
31
|
+
* `Idempotency-Key` (matched on the URL path, any API major, query ignored):
|
|
32
|
+
* - files `upload-url` — a replay mints a second pending object, which the
|
|
33
|
+
* 24 h reaper removes (the caller uploads to the URL it got back);
|
|
34
|
+
* - files `complete`, `publish` (one object) and `publish` (many) — they set
|
|
35
|
+
* a state the object already has on a replay.
|
|
36
|
+
* cms item create is NOT here: a replay would create a second item. cms
|
|
37
|
+
* upsert (`onConflict`) is replay-safe only when `patch` is a subset of
|
|
38
|
+
* `data` — the caller opts in with its own `Idempotency-Key`. */
|
|
39
|
+
export const REPLAY_SAFE_POST_PATHS = [
|
|
40
|
+
/\/v\d+\/files\/upload-url$/,
|
|
41
|
+
/\/v\d+\/files\/[^/]+\/complete$/,
|
|
42
|
+
/\/v\d+\/files\/[^/]+\/publish$/,
|
|
43
|
+
/\/v\d+\/files\/publish$/,
|
|
44
|
+
];
|
|
45
|
+
/** The path of a request URL (no scheme/host, no query) — string-only, so it
|
|
46
|
+
* works where `URL` is partial (React Native). */
|
|
47
|
+
export function requestPath(url) {
|
|
48
|
+
return url.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, '').split(/[?#]/)[0] ?? '';
|
|
49
|
+
}
|
|
30
50
|
/** The retry gate: GET/HEAD/PUT/DELETE/OPTIONS are idempotent by definition; a
|
|
31
|
-
* POST
|
|
32
|
-
*
|
|
33
|
-
|
|
51
|
+
* POST when it carries a non-empty `Idempotency-Key` (any header case) or its
|
|
52
|
+
* path is on `REPLAY_SAFE_POST_PATHS` (when `url` is given); PATCH and any
|
|
53
|
+
* other bare POST never. */
|
|
54
|
+
export function isIdempotentRequest(method, headers, url) {
|
|
34
55
|
const m = method.toUpperCase();
|
|
35
56
|
if (m === 'GET' || m === 'HEAD' || m === 'PUT' || m === 'DELETE' || m === 'OPTIONS')
|
|
36
57
|
return true;
|
|
37
58
|
if (m !== 'POST')
|
|
38
59
|
return false;
|
|
39
|
-
|
|
60
|
+
if (Object.keys(headers).some((k) => k.toLowerCase() === 'idempotency-key' && headers[k] !== ''))
|
|
61
|
+
return true;
|
|
62
|
+
if (url === undefined)
|
|
63
|
+
return false;
|
|
64
|
+
const path = requestPath(url);
|
|
65
|
+
return REPLAY_SAFE_POST_PATHS.some((re) => re.test(path));
|
|
40
66
|
}
|
|
41
67
|
/** Exponential backoff with equal jitter: `min(max, base·2^(attempt−1))`
|
|
42
68
|
* scaled into `[½, 1]` by `random()` (inject `() => 1` for a deterministic
|
|
@@ -103,9 +129,20 @@ export function createTransport(opts) {
|
|
|
103
129
|
if (timeoutMs !== undefined && typeof AbortController !== 'function') {
|
|
104
130
|
throw new Error('@vxil/sdk: `timeoutMs` needs a runtime with AbortController');
|
|
105
131
|
}
|
|
132
|
+
// errors this transport built for a timeout — rethrown as is (they are
|
|
133
|
+
// already the client's own error class), never wrapped as network_error
|
|
134
|
+
const timeouts = new WeakSet();
|
|
135
|
+
const timeoutError = (ms) => {
|
|
136
|
+
const e = opts.timeoutError(ms);
|
|
137
|
+
timeouts.add(e);
|
|
138
|
+
return e;
|
|
139
|
+
};
|
|
140
|
+
const surface = (failure, method, url, attempts) => !opts.networkError || (typeof failure === 'object' && failure !== null && timeouts.has(failure))
|
|
141
|
+
? failure
|
|
142
|
+
: opts.networkError(failure, { method, url, attempts });
|
|
106
143
|
return {
|
|
107
144
|
async send(url, init) {
|
|
108
|
-
const idempotent = isIdempotentRequest(init.method, init.headers);
|
|
145
|
+
const idempotent = isIdempotentRequest(init.method, init.headers, url);
|
|
109
146
|
for (let attempt = 1;; attempt++) {
|
|
110
147
|
const headers = { ...init.headers };
|
|
111
148
|
const request = describeRequest(init.method, url, headers, attempt);
|
|
@@ -121,7 +158,7 @@ export function createTransport(opts) {
|
|
|
121
158
|
let result;
|
|
122
159
|
let failure;
|
|
123
160
|
try {
|
|
124
|
-
result = await attemptOnce(opts.fetch, url, { ...init, headers }, timeoutMs,
|
|
161
|
+
result = await attemptOnce(opts.fetch, url, { ...init, headers }, timeoutMs, timeoutError);
|
|
125
162
|
}
|
|
126
163
|
catch (e) {
|
|
127
164
|
failure = e;
|
|
@@ -146,7 +183,7 @@ export function createTransport(opts) {
|
|
|
146
183
|
continue;
|
|
147
184
|
}
|
|
148
185
|
if (!(canRetry && retryOnNetworkError))
|
|
149
|
-
throw failure;
|
|
186
|
+
throw surface(failure, init.method, url, attempt);
|
|
150
187
|
const delayMs = backoffDelayMs(attempt, backoffMs, maxBackoffMs, random);
|
|
151
188
|
await hooks.onRetry?.({ request, delayMs, error: failure });
|
|
152
189
|
await sleep(delayMs);
|
package/package.json
CHANGED