@vxil/sdk 0.31.0 → 0.34.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 +169 -27
- package/dist/index.js +145 -17
- 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;
|
|
@@ -1213,7 +1280,7 @@ export interface PublishedFile {
|
|
|
1213
1280
|
* `oauth_provider_unreachable` (502). */
|
|
1214
1281
|
export type OAuthSignInErrorCode = 'oauth_token_invalid' | 'oidc_domain_not_allowed' | 'oidc_link_only' | 'signup_not_allowed' | 'auth_method_disabled' | 'oauth_email_conflict' | 'oauth_provider_unconfigured' | 'oauth_provider_unreachable';
|
|
1215
1282
|
/** Why one id of a bulk publish was not published. */
|
|
1216
|
-
export type PublishErrorCode = 'not_found' | 'upload_incomplete' | 'content_type_not_publishable' | 'object_too_large' | 'quota_exceeded' | 'batch_budget_exceeded' | 'asset_taken_down' | 'publish_failed';
|
|
1283
|
+
export type PublishErrorCode = 'not_found' | 'upload_incomplete' | 'content_type_not_publishable' | 'object_too_large' | 'quota_exceeded' | 'batch_budget_exceeded' | 'asset_taken_down' | 'publish_failed' | 'object_rewritten';
|
|
1217
1284
|
/** A live shared link as listed by GET /v1/files/{id}/shared-links (guide ch. 6,
|
|
1218
1285
|
* files). `downloads` is the burn-on-read counter; `max_downloads` null =
|
|
1219
1286
|
* unlimited (1 = a one-time link). A link that hit its cap, expired, or was
|
|
@@ -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
|
}
|
|
@@ -2991,9 +3070,10 @@ export type EnabledVxil<S extends VxilSchemaShape> = Omit<Vxil<S>, DisabledFeatu
|
|
|
2991
3070
|
};
|
|
2992
3071
|
/** A cms collection's END-USER ACCESS mode (guide ch. 9): what a verified end
|
|
2993
3072
|
* user (thin-client key + session) may do on it — `'readwrite'` (default),
|
|
2994
|
-
* `'read'` (writes are `403 server_only`)
|
|
2995
|
-
* `403 server_only`)
|
|
2996
|
-
|
|
3073
|
+
* `'read'` (writes are `403 server_only`), `'none'` (reads and writes are
|
|
3074
|
+
* `403 server_only`) or `'read_all'` (every row is readable past the owner
|
|
3075
|
+
* field; writes stay owner-scoped). Server keys are never affected. */
|
|
3076
|
+
export type CmsEndUserAccess = 'readwrite' | 'read' | 'none' | 'read_all';
|
|
2997
3077
|
/** One config-declared per-record ACTION (guide ch. 4): a button on a record row
|
|
2998
3078
|
* that invokes the deployed tenant function `fn` ONCE with `{ collection,
|
|
2999
3079
|
* item_id, action, actor, item }`. Exactly one human-initiated step — no
|
|
@@ -5101,6 +5181,13 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5101
5181
|
* are never affected. Omitted/`[]` = ungated. ≤16 entries, each
|
|
5102
5182
|
* `^[a-z0-9][a-z0-9_-]{0,31}$` (the `orgs` role alphabet). */
|
|
5103
5183
|
write_roles?: string[];
|
|
5184
|
+
/** W39-3: role slugs whose VERIFIED holders MANAGE this owned collection
|
|
5185
|
+
* — get / list / count read every row, and the single-item update may
|
|
5186
|
+
* change another member's row (the owner field never moves; the
|
|
5187
|
+
* collection's hooks still decide the fields). Every other end-user
|
|
5188
|
+
* door stays owner-scoped. Needs `owner_field` and an end-user-writable
|
|
5189
|
+
* `end_user_access`. Omitted/`[]` = none. ≤16 entries. */
|
|
5190
|
+
manager_roles?: string[];
|
|
5104
5191
|
/** Retention (guide ch. 4): live items created more than this many days
|
|
5105
5192
|
* ago (1..3650) are soft-deleted by the nightly platform sweep — like a
|
|
5106
5193
|
* normal delete (no restore; purged at least 30 days later, unique values freed), with ONE
|
|
@@ -5174,6 +5261,8 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5174
5261
|
end_user_access?: CmsEndUserAccess;
|
|
5175
5262
|
/** present when the collection is role-gated for end-user writes */
|
|
5176
5263
|
write_roles?: string[];
|
|
5264
|
+
/** present when the collection names manager roles */
|
|
5265
|
+
manager_roles?: string[];
|
|
5177
5266
|
/** present when retention is set */
|
|
5178
5267
|
retain_days?: number;
|
|
5179
5268
|
/** present when a shorter deleted-item window is set */
|
|
@@ -5193,6 +5282,8 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5193
5282
|
end_user_access?: CmsEndUserAccess;
|
|
5194
5283
|
/** the roles an end user needs to write it (null / absent = ungated) */
|
|
5195
5284
|
write_roles?: string[] | null;
|
|
5285
|
+
/** W39-3: the roles that manage this owned collection (null / absent = none) */
|
|
5286
|
+
manager_roles?: string[] | null;
|
|
5196
5287
|
/** retention in days (null = keep until deleted; absent from an older server) */
|
|
5197
5288
|
retain_days?: number | null;
|
|
5198
5289
|
/** deleted-item recovery window in days (null = the default 30) */
|
|
@@ -5258,6 +5349,16 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5258
5349
|
collection: string;
|
|
5259
5350
|
write_roles: string[];
|
|
5260
5351
|
}>;
|
|
5352
|
+
/** W39-3: set (or clear, with `[]` / `null`) the collection's MANAGER
|
|
5353
|
+
* ROLES: a verified end user holding one reads every row of this owned
|
|
5354
|
+
* collection (get / list / count) and may update another member's row
|
|
5355
|
+
* through the single-item update; the collection's hooks still decide
|
|
5356
|
+
* the fields. Every other end-user door stays owner-scoped; server keys
|
|
5357
|
+
* are never affected. Audited; takes effect on the next request. */
|
|
5358
|
+
setManagerRoles: (collection: string, roles: string[] | null) => Promise<{
|
|
5359
|
+
collection: string;
|
|
5360
|
+
manager_roles: string[];
|
|
5361
|
+
}>;
|
|
5261
5362
|
/** Set (or clear, with `null`) the collection's WORKSPACE field (guide
|
|
5262
5363
|
* ch. 4, "Workspace-scoped collections"): a `string` field on an index
|
|
5263
5364
|
* slot (s1–s4) holding the orgs org id. A verified end user then reads and
|
|
@@ -5343,7 +5444,9 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5343
5444
|
};
|
|
5344
5445
|
items: {
|
|
5345
5446
|
/** `lock` serializes same-key writers (a per-key lock); `guard`
|
|
5346
|
-
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
5447
|
+
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
5448
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
5449
|
+
* server rules dropped (an owner-only or rule-controlled field). */
|
|
5347
5450
|
create: (collection: string, input: {
|
|
5348
5451
|
data: Record<string, unknown>;
|
|
5349
5452
|
status?: "draft" | "published";
|
|
@@ -5355,6 +5458,7 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5355
5458
|
status: string;
|
|
5356
5459
|
version: number;
|
|
5357
5460
|
data: Record<string, unknown>;
|
|
5461
|
+
dropped_fields?: string[];
|
|
5358
5462
|
}>;
|
|
5359
5463
|
/** Upsert by a declared `unique` field (guide ch. 4): creates the item, or
|
|
5360
5464
|
* — when a live item already holds `data[field]` — merges `patch` into
|
|
@@ -5417,8 +5521,12 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
5417
5521
|
}>;
|
|
5418
5522
|
/** Merge-patch data keys; null clears a key. Concurrency opts (guide ch. 4):
|
|
5419
5523
|
* `ifVersion` → If-Match CAS; `if` → bounded field precondition against
|
|
5420
|
-
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
5421
|
-
|
|
5524
|
+
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
5525
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
5526
|
+
* server rules dropped, as on `create`. */
|
|
5527
|
+
patch: (collection: string, itemId: string, data: Record<string, unknown>, opts?: CmsWriteOpts) => Promise<Record<string, unknown> & {
|
|
5528
|
+
dropped_fields?: string[];
|
|
5529
|
+
}>;
|
|
5422
5530
|
/** Atomic in-database increment — PATCH `{ $inc: {field: delta} }`, ONE
|
|
5423
5531
|
* conditional UPDATE guarded by the field's validation min/max (the quota
|
|
5424
5532
|
* shape), the optional `if` precondition, and If-Match. 409
|
|
@@ -6062,6 +6170,36 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
6062
6170
|
/** Shared executor for the seen/read/archive notification-state endpoints. */
|
|
6063
6171
|
private feedsMark;
|
|
6064
6172
|
readonly webhooks: {
|
|
6173
|
+
/** The failure-alert digest (`webhooks.alerts`): owner e-mail, plus an
|
|
6174
|
+
* optional chat webhook. Thin over GET / PUT /v1/config/webhooks — the
|
|
6175
|
+
* write keeps every other webhooks setting and sends If-Match, so it
|
|
6176
|
+
* versions and rolls back like any config change. Needs features:read /
|
|
6177
|
+
* features:write. */
|
|
6178
|
+
alerts: {
|
|
6179
|
+
get: () => Promise<{
|
|
6180
|
+
version: number;
|
|
6181
|
+
alerts: WebhooksAlerts | null;
|
|
6182
|
+
}>;
|
|
6183
|
+
/** Merge `patch` into the current alerts settings and write. Pass
|
|
6184
|
+
* `chatWebhook: null` to remove the chat destination. That removes only
|
|
6185
|
+
* the config reference: the stored URL (a token-bearing credential)
|
|
6186
|
+
* stays in the secret store until you delete it —
|
|
6187
|
+
* `DELETE /v1/secrets/webhooks/<name>` (the dashboard's "Remove chat
|
|
6188
|
+
* webhook" does both). */
|
|
6189
|
+
set: (patch: Partial<Omit<WebhooksAlerts, "chatWebhook">> & {
|
|
6190
|
+
chatWebhook?: {
|
|
6191
|
+
secret: string;
|
|
6192
|
+
} | null;
|
|
6193
|
+
}) => Promise<FeatureConfig>;
|
|
6194
|
+
/** Store the chat webhook URL as an encrypted webhooks secret (write-only;
|
|
6195
|
+
* never readable back) and return the name to put in
|
|
6196
|
+
* `chatWebhook.secret`. Default name `alerts_chat`. Needs features:write. */
|
|
6197
|
+
storeChatWebhookUrl: (url: string, opts?: {
|
|
6198
|
+
secretName?: string;
|
|
6199
|
+
}) => Promise<{
|
|
6200
|
+
secret: string;
|
|
6201
|
+
}>;
|
|
6202
|
+
};
|
|
6065
6203
|
/**
|
|
6066
6204
|
* Subscribe an https endpoint to audit-stream events (optionally
|
|
6067
6205
|
* filtered by event-name prefixes like 'user.'). Deliveries are jobs
|
|
@@ -7622,7 +7760,9 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
7622
7760
|
* 404 charge_not_found; 422 charge_user_mismatch (another user's charge) /
|
|
7623
7761
|
* charge_refunded (the refund beat the grant — nothing to grant against).
|
|
7624
7762
|
* 422 reserved_idempotency_key when `idempotency_key` starts with
|
|
7625
|
-
* `purchase:` (the namespace of purchase passes).
|
|
7763
|
+
* `purchase:` (the namespace of purchase passes). Stacking: a grant whose
|
|
7764
|
+
* `until` reaches past a live same-tier manual row (a grant or a pass with
|
|
7765
|
+
* an end) starts where that row ends — `since` names that start. */
|
|
7626
7766
|
grantSubscription: (input: PaymentsSubjectBody & {
|
|
7627
7767
|
tier: string;
|
|
7628
7768
|
until?: string | null;
|
|
@@ -7634,8 +7774,10 @@ export declare class Vxil<S extends VxilSchemaShape = VxilSchemaShape> {
|
|
|
7634
7774
|
user_id: string;
|
|
7635
7775
|
tier: string;
|
|
7636
7776
|
status: string;
|
|
7637
|
-
/**
|
|
7638
|
-
*
|
|
7777
|
+
/** the grant row's start: the time it was written — or, when `until`
|
|
7778
|
+
* reaches past a live same-tier manual grant or pass, the end of that
|
|
7779
|
+
* window (the grant queues behind it like a purchase; `until` is yours,
|
|
7780
|
+
* never moved). A replay answers the first grant's. */
|
|
7639
7781
|
since?: string | null;
|
|
7640
7782
|
until: string | null;
|
|
7641
7783
|
charge_id: string | null;
|
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
|
|
@@ -1646,6 +1721,13 @@ export class Vxil {
|
|
|
1646
1721
|
* unaffected; server keys are never affected. Audited; takes effect on
|
|
1647
1722
|
* the next write. */
|
|
1648
1723
|
setWriteRoles: async (collection, roles) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { write_roles: roles ?? [] })).data,
|
|
1724
|
+
/** W39-3: set (or clear, with `[]` / `null`) the collection's MANAGER
|
|
1725
|
+
* ROLES: a verified end user holding one reads every row of this owned
|
|
1726
|
+
* collection (get / list / count) and may update another member's row
|
|
1727
|
+
* through the single-item update; the collection's hooks still decide
|
|
1728
|
+
* the fields. Every other end-user door stays owner-scoped; server keys
|
|
1729
|
+
* are never affected. Audited; takes effect on the next request. */
|
|
1730
|
+
setManagerRoles: async (collection, roles) => (await this.call('POST', `/v1/cms/collections/${encodeURIComponent(collection)}/fields`, { manager_roles: roles ?? [] })).data,
|
|
1649
1731
|
/** Set (or clear, with `null`) the collection's WORKSPACE field (guide
|
|
1650
1732
|
* ch. 4, "Workspace-scoped collections"): a `string` field on an index
|
|
1651
1733
|
* slot (s1–s4) holding the orgs org id. A verified end user then reads and
|
|
@@ -1740,7 +1822,9 @@ export class Vxil {
|
|
|
1740
1822
|
},
|
|
1741
1823
|
items: {
|
|
1742
1824
|
/** `lock` serializes same-key writers (a per-key lock); `guard`
|
|
1743
|
-
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
1825
|
+
* is the declarative capacity/overlap invariant (requires lock) — guide ch. 4.
|
|
1826
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
1827
|
+
* server rules dropped (an owner-only or rule-controlled field). */
|
|
1744
1828
|
create: async (collection, input) => (await this.call('POST', `/v1/cms/items/${encodeURIComponent(collection)}`, input)).data,
|
|
1745
1829
|
/** Upsert by a declared `unique` field (guide ch. 4): creates the item, or
|
|
1746
1830
|
* — when a live item already holds `data[field]` — merges `patch` into
|
|
@@ -1788,7 +1872,9 @@ export class Vxil {
|
|
|
1788
1872
|
},
|
|
1789
1873
|
/** Merge-patch data keys; null clears a key. Concurrency opts (guide ch. 4):
|
|
1790
1874
|
* `ifVersion` → If-Match CAS; `if` → bounded field precondition against
|
|
1791
|
-
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
1875
|
+
* the locked row; `lock`/`guard` → the write-serialization primitives (guide ch. 4).
|
|
1876
|
+
* `dropped_fields` (App builder app proxy only): the sent keys the app's
|
|
1877
|
+
* server rules dropped, as on `create`. */
|
|
1792
1878
|
patch: async (collection, itemId, data, opts) => (await this.call('PATCH', `/v1/cms/items/${encodeURIComponent(collection)}/${encodeURIComponent(itemId)}`, {
|
|
1793
1879
|
data,
|
|
1794
1880
|
...(opts?.if ? { if: opts.if } : {}),
|
|
@@ -2125,6 +2211,46 @@ export class Vxil {
|
|
|
2125
2211
|
return { unseen, unread, total };
|
|
2126
2212
|
}
|
|
2127
2213
|
webhooks = {
|
|
2214
|
+
/** The failure-alert digest (`webhooks.alerts`): owner e-mail, plus an
|
|
2215
|
+
* optional chat webhook. Thin over GET / PUT /v1/config/webhooks — the
|
|
2216
|
+
* write keeps every other webhooks setting and sends If-Match, so it
|
|
2217
|
+
* versions and rolls back like any config change. Needs features:read /
|
|
2218
|
+
* features:write. */
|
|
2219
|
+
alerts: {
|
|
2220
|
+
get: async () => {
|
|
2221
|
+
const cfg = (await this.call('GET', `/v1/config/${ALERTS_FEATURE}`)).data;
|
|
2222
|
+
const a = cfg.manifest?.alerts;
|
|
2223
|
+
return { version: cfg.version, alerts: a && typeof a === 'object' ? a : null };
|
|
2224
|
+
},
|
|
2225
|
+
/** Merge `patch` into the current alerts settings and write. Pass
|
|
2226
|
+
* `chatWebhook: null` to remove the chat destination. That removes only
|
|
2227
|
+
* the config reference: the stored URL (a token-bearing credential)
|
|
2228
|
+
* stays in the secret store until you delete it —
|
|
2229
|
+
* `DELETE /v1/secrets/webhooks/<name>` (the dashboard's "Remove chat
|
|
2230
|
+
* webhook" does both). */
|
|
2231
|
+
set: async (patch) => {
|
|
2232
|
+
const cur = (await this.call('GET', `/v1/config/${ALERTS_FEATURE}`)).data;
|
|
2233
|
+
const prev = (cur.manifest?.alerts && typeof cur.manifest.alerts === 'object'
|
|
2234
|
+
? cur.manifest.alerts : {});
|
|
2235
|
+
const { chatWebhook, ...rest } = patch;
|
|
2236
|
+
const next = { enabled: false, ...prev, ...rest };
|
|
2237
|
+
if (chatWebhook === null)
|
|
2238
|
+
delete next.chatWebhook;
|
|
2239
|
+
else if (chatWebhook !== undefined)
|
|
2240
|
+
next.chatWebhook = chatWebhook;
|
|
2241
|
+
return (await this.call('PUT', `/v1/config/${ALERTS_FEATURE}`, { ...cur.manifest, alerts: next }, {
|
|
2242
|
+
'if-match': String(cur.version),
|
|
2243
|
+
})).data;
|
|
2244
|
+
},
|
|
2245
|
+
/** Store the chat webhook URL as an encrypted webhooks secret (write-only;
|
|
2246
|
+
* never readable back) and return the name to put in
|
|
2247
|
+
* `chatWebhook.secret`. Default name `alerts_chat`. Needs features:write. */
|
|
2248
|
+
storeChatWebhookUrl: async (url, opts) => {
|
|
2249
|
+
const name = opts?.secretName ?? 'alerts_chat';
|
|
2250
|
+
await this.call('PUT', `/v1/secrets/${ALERTS_FEATURE}/${encodeURIComponent(name)}`, { value: url });
|
|
2251
|
+
return { secret: name };
|
|
2252
|
+
},
|
|
2253
|
+
},
|
|
2128
2254
|
/**
|
|
2129
2255
|
* Subscribe an https endpoint to audit-stream events (optionally
|
|
2130
2256
|
* filtered by event-name prefixes like 'user.'). Deliveries are jobs
|
|
@@ -2976,7 +3102,9 @@ export class Vxil {
|
|
|
2976
3102
|
* 404 charge_not_found; 422 charge_user_mismatch (another user's charge) /
|
|
2977
3103
|
* charge_refunded (the refund beat the grant — nothing to grant against).
|
|
2978
3104
|
* 422 reserved_idempotency_key when `idempotency_key` starts with
|
|
2979
|
-
* `purchase:` (the namespace of purchase passes).
|
|
3105
|
+
* `purchase:` (the namespace of purchase passes). Stacking: a grant whose
|
|
3106
|
+
* `until` reaches past a live same-tier manual row (a grant or a pass with
|
|
3107
|
+
* an end) starts where that row ends — `since` names that start. */
|
|
2980
3108
|
grantSubscription: async (input) => (await this.call('POST', '/v1/payments/subscriptions/grant', input)).data,
|
|
2981
3109
|
/** SERVER-ONLY. Revoke a MANUAL grant now (409 not_manual for a provider
|
|
2982
3110
|
* subscription — use `cancel`). Never touches a provider. */
|
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