@standards/client 1.0.0-alpha.419 → 1.0.0-alpha.425

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.
@@ -0,0 +1,292 @@
1
+
2
+ import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange } from "@standards/schema";
3
+ import { Operation, OperationCaller, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
4
+ /**
5
+ * Any non-2xx answer from a Standards API. `code` is the server's `SchemaErrorCode` when it sent
6
+ * one; `details` is the body's `details` field, kept as the server sent it.
7
+ */
8
+ declare class StandardsRequestError extends Error {
9
+ readonly status: number;
10
+ readonly code?: string;
11
+ readonly details?: unknown;
12
+ constructor(status: number, message: string, code?: string, details?: unknown);
13
+ }
14
+ /** 401 or 403: the key is missing, invalid, or lacks the permission the route requires. */
15
+ declare class StandardsAuthError extends StandardsRequestError {
16
+ constructor(status: number, message: string, code?: string, details?: unknown);
17
+ }
18
+ /**
19
+ * 409 from `PUT /bundles/:name`: a name this bundle declares is owned by core or another bundle.
20
+ * A declared view that clashes with the workspace's views (a second default for the same object
21
+ * and context, or a name held by a system view) is a 409 too; its message names no owner, so
22
+ * `objectName` and `owner` are empty.
23
+ */
24
+ declare class BundleConflictError extends StandardsRequestError {
25
+ /** The object or `object:view` name that clashed. */
26
+ readonly objectName: string;
27
+ /** `core` or `bundle:<name>`. */
28
+ readonly owner: string;
29
+ constructor(status: number, message: string, code: string | undefined);
30
+ }
31
+ /** 400 from `PUT /bundles/:name`: bad name, oversize payload, hash mismatch, invalid definition, or an unresolved migration. */
32
+ declare class BundleValidationError extends StandardsRequestError {
33
+ constructor(status: number, message: string, code: string | undefined);
34
+ }
35
+ /** The client was constructed in a way it refuses to run (e.g. an API key in a browser). */
36
+ declare class StandardsConfigurationError extends Error {
37
+ constructor(message: string);
38
+ }
39
+ /** Per-request overrides a multipart upload may carry. */
40
+ interface MultipartRequestOptions {
41
+ /** This request's timeout in ms, instead of the client's `timeoutMs`. */
42
+ timeoutMs?: number;
43
+ }
44
+ interface HttpTransportConfig {
45
+ baseUrl: string;
46
+ /** A path joined between `baseUrl` and every request path. */
47
+ apiPrefix?: string;
48
+ fetch?: typeof fetch;
49
+ /** Read before every attempt, so a refreshed token reaches the retry. */
50
+ headers?: () => HeadersInit | Promise<HeadersInit>;
51
+ /** Asked on a 401; `true` means the credentials were refreshed and the request is sent once more. */
52
+ onUnauthorized?: () => Promise<boolean>;
53
+ /** Sees every response — success, refusal, and the retry after a refresh. Read-only: the body belongs to the request. */
54
+ onResponse?: (response: Response) => void;
55
+ /** Per attempt, in ms. Defaults to 30 000. */
56
+ timeoutMs?: number;
57
+ /** Extra attempts after the first for a GET (5xx and network failures). Defaults to 0. */
58
+ getRetries?: number;
59
+ /**
60
+ * The bearer an upload sent over XMLHttpRequest carries (to report its
61
+ * progress): XHR cannot run an injected `fetch`, where an app's auth lives,
62
+ * so with an injected `fetch` and no `uploadAuthorization` an upload goes
63
+ * through `fetch` and reports no progress.
64
+ */
65
+ uploadAuthorization?: () => Promise<string | null>;
66
+ }
67
+ /** Bytes of a multipart body sent so far, out of its total. */
68
+ interface UploadProgress {
69
+ loaded: number;
70
+ total: number;
71
+ }
72
+ /** Per-call options of one operation. */
73
+ interface OperationCallOptions {
74
+ /** Aborts the call: it rejects with the signal's reason (an `AbortError` by default). */
75
+ signal?: AbortSignal;
76
+ /** Extra attempts after the first; defaults to `getRetries` for a GET and 0 otherwise. */
77
+ maxRetries?: number;
78
+ /**
79
+ * This call's wait for the response headers, in ms, instead of the client's
80
+ * `timeoutMs`; `null` waits as long as it takes (an upload's body is sent
81
+ * before the headers come back, so a large one outlives any fixed deadline).
82
+ */
83
+ timeoutMs?: number | null;
84
+ /**
85
+ * Lets the request outlive the page that sent it (`fetch`'s `keepalive`),
86
+ * on every attempt: for a write taken right before a navigation, which the
87
+ * browser would otherwise cancel in flight.
88
+ */
89
+ keepalive?: boolean;
90
+ /**
91
+ * The bytes of an `upload` operation's body sent so far. `fetch` cannot
92
+ * report them, so the upload goes over XMLHttpRequest — one attempt, no
93
+ * deadline, no refresh on a 401 — when the transport can authenticate it
94
+ * there (see `uploadAuthorization`); otherwise it goes through `fetch` and
95
+ * reports nothing.
96
+ */
97
+ onUploadProgress?: (progress: UploadProgress) => void;
98
+ }
99
+ /**
100
+ * Per-call options of an `"events"` operation. No deadline and no retry: a
101
+ * stream outlives any request timeout, so its signal is the only abort.
102
+ */
103
+ interface OperationStreamOptions {
104
+ signal?: AbortSignal;
105
+ /** Merged over the configured headers (`Accept: text/event-stream`). */
106
+ headers?: Record<string, string>;
107
+ /**
108
+ * Observes each HTTP attempt, the one after a 401 refresh included, so a
109
+ * reader can tell which credential a refusal answered.
110
+ */
111
+ onRequest?: () => void;
112
+ }
113
+ interface HttpTransport {
114
+ /**
115
+ * Sends one operation: path parameters fill the path; the rest is the query
116
+ * for a GET, otherwise the body, except the keys the operation lists in `query`.
117
+ * An `upload` operation sends its body as multipart, its files under the
118
+ * operation's field; a `response: "bytes"` one resolves to a `DownloadedFile`.
119
+ */
120
+ call<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationCallOptions): Promise<OperationResult<O>>;
121
+ /**
122
+ * Opens an `"events"` operation and resolves to its `Response` once the
123
+ * headers are in, for the caller to read: no deadline, no retry, one
124
+ * refresh on a 401 (never on `MFA_REQUIRED`, which a token cannot satisfy).
125
+ * Any refusal is read and thrown as the typed error before a byte streams.
126
+ */
127
+ stream<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationStreamOptions): Promise<Response>;
128
+ get<T = unknown>(path: string, params?: Record<string, unknown>): Promise<T>;
129
+ post<T = unknown>(path: string, body?: unknown): Promise<T>;
130
+ patch<T = unknown>(path: string, body?: unknown): Promise<T>;
131
+ put<T = unknown>(path: string, body?: unknown): Promise<T>;
132
+ delete<T = unknown>(path: string): Promise<T>;
133
+ getText(path: string, params?: Record<string, unknown>): Promise<string>;
134
+ /**
135
+ * POST that hands back the unread `Response` so a caller can stream a large
136
+ * body (the CSV export). A refusal is read here and thrown as the typed error.
137
+ */
138
+ postRaw(path: string, body: unknown): Promise<Response>;
139
+ postMultipart<T>(path: string, form: FormData, options?: MultipartRequestOptions): Promise<T>;
140
+ }
141
+ /** The verbs the records, files and schema layers use; `createTransport` returns their superset. */
142
+ /** What `createAppClient` calls: every operation, and a stream for an `"events"` one. */
143
+ type OperationTransport = Pick<HttpTransport, "call" | "stream">;
144
+ type Transport = Pick<HttpTransport, "call" | "get" | "post" | "patch" | "put" | "delete" | "getText" | "postRaw" | "postMultipart">;
145
+ interface TransportConfig {
146
+ baseUrl: string;
147
+ apiKey: string;
148
+ tenantId?: string;
149
+ timeoutMs?: number;
150
+ }
151
+ /**
152
+ * A refusal read from its status and body text, for a response that is not a
153
+ * `Response` (an XMLHttpRequest upload): the same error the transport throws.
154
+ */
155
+ declare function refusalOf(status: number, text: string): StandardsRequestError;
156
+ /** Reads a refused `Response` into the error the transport itself throws. */
157
+ declare function readRefusal(response: Response): Promise<StandardsRequestError>;
158
+ declare function createHttpTransport(config: HttpTransportConfig): HttpTransport;
159
+ /**
160
+ * The API-key transport the public SDK documents: `createHttpTransport` with
161
+ * the bearer key and tenant header, one attempt, no refresh.
162
+ */
163
+ declare function createTransport(config: TransportConfig): HttpTransport;
164
+ /** The server's `SchemaErrorCode` on a failed call, when it sent one. */
165
+ declare function schemaApiErrorCode(error: unknown): string | undefined;
166
+ /** Whether a failure is an answer, and so must not be asked again. */
167
+ declare function isPermanentRefusal(error: unknown): boolean;
168
+ /**
169
+ * Whether a failure says the object does not exist, rather than that the read
170
+ * failed (#3290): with a definition seeded from the cached catalogue, a 500 and
171
+ * a 404 are opposite answers — a transient failure may be ridden out, an
172
+ * authoritative not-found may not.
173
+ *
174
+ * Either signal is enough, deliberately: reading only the code would tolerate a
175
+ * deleted object behind a plainer not-found, reading only the status would miss
176
+ * a coded refusal carrying no status.
177
+ */
178
+ declare function isObjectNotFound(error: unknown): boolean;
179
+ /**
180
+ * Whether a write was refused because the draft moved since it was read
181
+ * (`DRAFT_REVISION_CONFLICT`, a 409): only a fresh read of the draft makes the
182
+ * next attempt mean something (#4899).
183
+ */
184
+ declare function isDraftRevisionConflict(error: unknown): boolean;
185
+ /**
186
+ * What a publish refused for a conflict found published on its targets since
187
+ * the draft captured them (#5936). Empty for any other refusal, a conflict on
188
+ * the draft's own revision included: that one is answered by reading it again.
189
+ */
190
+ declare function draftConflictChanges(error: unknown): DraftConflictChange[];
191
+ /**
192
+ * Whether a view read failed because the object simply has no view for that
193
+ * context (#2659) — a working object not laid out yet, not a failure.
194
+ *
195
+ * Status-only: the view routes' not-found carries the generic
196
+ * `SCHEMA_RECORD_NOT_FOUND` code, which says nothing view-specific. Call it
197
+ * ONLY on a view query's error — on any other query a 404 means something
198
+ * else entirely.
199
+ */
200
+ declare function isViewNotFound(error: unknown): boolean;
201
+ type AgentStreamStatus = "connecting" | "connected" | "reconnecting" | "error" | "auth-blocked";
202
+ type AgentStreamHandle = {
203
+ close(): void;
204
+ /** Ends a pending reconnect delay now (the tab came back, the network returned). */
205
+ wake(): void;
206
+ };
207
+ type AgentStreamControl = AgentStreamControlFrame["control"];
208
+ type OpenAgentStreamOptions = {
209
+ /**
210
+ * Opens the HTTP stream after `cursor` — the client method from agent-api.
211
+ * The transport (auth headers, 401 refresh) lives here; this loop owns only
212
+ * the parser and the reconnect policy.
213
+ */
214
+ open(sessionId: string, cursor: number, signal: AbortSignal, onRequest?: () => void): Promise<Response>;
215
+ sessionId: string;
216
+ /** The cursor every (re)connection opens after: the last seq the caller holds. */
217
+ cursor(): number;
218
+ /** One event, in seq order; the caller advances its cursor before returning. */
219
+ onEvent(event: AgentSessionEvent): void;
220
+ onControl(control: AgentStreamControl): void;
221
+ onStatus(status: AgentStreamStatus, error?: StandardsRequestError): void;
222
+ /**
223
+ * The server no longer holds the events after the cursor (410
224
+ * `AGENT_SESSION_STREAM_CURSOR_EXPIRED`): rehydrate, which moves the cursor
225
+ * to the history's `committedSeq`, then the loop reopens there.
226
+ */
227
+ onExpired(): Promise<void>;
228
+ /** Changed credentials only; independent of Presence authorization. */
229
+ subscribeAuthChanges?(listener: () => void): () => void;
230
+ };
231
+ /** The event types that end a turn. */
232
+ declare const TURN_END_TYPES: ReadonlySet<AgentSessionEvent["type"]>;
233
+ /**
234
+ * Read the session's durable event stream (spec §9.4) and keep it open.
235
+ *
236
+ * Fetch-based on purpose: `EventSource` cannot see the 410's code. Every
237
+ * connection opens after `cursor()`, so a reconnect — a 60 s lease ending, a
238
+ * network error — resumes exactly where the caller is, and an event at or
239
+ * below the cursor is never delivered twice. A 410 rehydrates once
240
+ * (`onExpired`), then reopens at the new cursor; 400/403/404 and an
241
+ * unresolvable actor are terminal; a 401 waits for a credential change.
242
+ */
243
+ declare function openAgentStream(options: OpenAgentStreamOptions): AgentStreamHandle;
244
+ /**
245
+ * Parse the download filename out of a `Content-Disposition` response header.
246
+ *
247
+ * The server is the single naming source (see `contentDispositionFilename` in
248
+ * adapter-nestjs): it emits both the RFC 5987 `filename*=UTF-8''...` form
249
+ * (accent-safe, percent-encoded) and a sanitized ASCII `filename="..."`
250
+ * fallback. We prefer the extended form and percent-decode it so accented,
251
+ * title-based names ("Pièce d'identité – 2.jpg") survive the round trip.
252
+ *
253
+ * Returns `undefined` when the header is absent or carries no filename, letting
254
+ * callers fall back to a client-side name.
255
+ */
256
+ declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
257
+ /**
258
+ * The in-process transport: an {@link OperationTransport} that can also be
259
+ * bound to who acts, which a transport over HTTP cannot (its identity is the
260
+ * API key's).
261
+ */
262
+ interface InProcessTransport extends OperationTransport {
263
+ /** The same transport, every call acting as `caller`. */
264
+ withCaller(caller: OperationCaller): InProcessTransport;
265
+ }
266
+ /**
267
+ * A transport over operations run in this process (the runtime's
268
+ * `createOperationHost`), for a server that embeds Standards: the same
269
+ * `createAppClient` API, inputs, answers and errors as over HTTP, without a
270
+ * socket. Each call acts as the actor the ambient context implies (the
271
+ * request's, the job's, the system where none runs), or as the one
272
+ * `withCaller` names, and each operation's permissions are checked as the
273
+ * HTTP API checks them. A refusal rejects with the `StandardsRequestError`
274
+ * (`StandardsAuthError` for 401/403) the HTTP transport would throw.
275
+ *
276
+ * Streams (`"events"` operations) are served over HTTP only.
277
+ */
278
+ declare function createInProcessTransport(host: OperationHost): InProcessTransport;
279
+ type AppOperationGroups = typeof appOperationGroups;
280
+ type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
281
+ type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
282
+ type VerbOf<N> = N extends `${string}.${infer V}` ? V : never;
283
+ /** An `"events"` operation opens a stream (`transport.stream`); any other is one call. */
284
+ type OptionsOf<O extends Operation> = O extends {
285
+ readonly response: "events";
286
+ } ? OperationStreamOptions : OperationCallOptions;
287
+ /** An input the schema defaults (`.default({})`) may be left out; `options` carries the call's signal. */
288
+ type OperationCall<O extends Operation> = (...args: undefined extends OperationInput<O> ? [input?: OperationInput<O>, options?: OptionsOf<O>] : [input: OperationInput<O>, options?: OptionsOf<O>]) => Promise<OperationResult<O>>;
289
+ type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
290
+ /** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
291
+ declare function createAppClient(transport: OperationTransport): AppClient;
292
+ export { refusalOf as A, OperationTransport as C, createHttpTransport as D, UploadProgress as E, StandardsRequestError as F, BundleValidationError as M, StandardsAuthError as N, createTransport as O, StandardsConfigurationError as P, OperationStreamOptions as S, TransportConfig as T, schemaApiErrorCode as _, parseContentDispositionFilename as a, MultipartRequestOptions as b, AgentStreamStatus as c, openAgentStream as d, draftConflictChanges as f, isViewNotFound as g, isPermanentRefusal as h, createInProcessTransport as i, BundleConflictError as j, readRefusal as k, OpenAgentStreamOptions as l, isObjectNotFound as m, createAppClient as n, AgentStreamControl as o, isDraftRevisionConflict as p, InProcessTransport as r, AgentStreamHandle as s, AppClient as t, TURN_END_TYPES as u, HttpTransport as v, Transport as w, OperationCallOptions as x, HttpTransportConfig as y };
package/dist/app.d.mts CHANGED
@@ -1,68 +1,3 @@
1
1
 
2
- import { _ as StandardsRequestError, a as OperationStreamOptions, c as UploadProgress, d as readRefusal, f as refusalOf, h as StandardsAuthError, i as OperationCallOptions, l as createHttpTransport, n as HttpTransportConfig, t as HttpTransport } from "./http-transport-BxJhcXjy.mjs";
3
- import { DraftConflictChange } from "@standards/schema";
4
- import { Operation, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
5
- /** The server's `SchemaErrorCode` on a failed call, when it sent one. */
6
- export declare function schemaApiErrorCode(error: unknown): string | undefined;
7
- /** Whether a failure is an answer, and so must not be asked again. */
8
- export declare function isPermanentRefusal(error: unknown): boolean;
9
- /**
10
- * Whether a failure says the object does not exist, rather than that the read
11
- * failed (#3290): with a definition seeded from the cached catalogue, a 500 and
12
- * a 404 are opposite answers — a transient failure may be ridden out, an
13
- * authoritative not-found may not.
14
- *
15
- * Either signal is enough, deliberately: reading only the code would tolerate a
16
- * deleted object behind a plainer not-found, reading only the status would miss
17
- * a coded refusal carrying no status.
18
- */
19
- export declare function isObjectNotFound(error: unknown): boolean;
20
- /**
21
- * Whether a write was refused because the draft moved since it was read
22
- * (`DRAFT_REVISION_CONFLICT`, a 409): only a fresh read of the draft makes the
23
- * next attempt mean something (#4899).
24
- */
25
- export declare function isDraftRevisionConflict(error: unknown): boolean;
26
- /**
27
- * What a publish refused for a conflict found published on its targets since
28
- * the draft captured them (#5936). Empty for any other refusal, a conflict on
29
- * the draft's own revision included: that one is answered by reading it again.
30
- */
31
- export declare function draftConflictChanges(error: unknown): DraftConflictChange[];
32
- /**
33
- * Whether a view read failed because the object simply has no view for that
34
- * context (#2659) — a working object not laid out yet, not a failure.
35
- *
36
- * Status-only: the view routes' not-found carries the generic
37
- * `SCHEMA_RECORD_NOT_FOUND` code, which says nothing view-specific. Call it
38
- * ONLY on a view query's error — on any other query a 404 means something
39
- * else entirely.
40
- */
41
- export declare function isViewNotFound(error: unknown): boolean;
42
- /**
43
- * Parse the download filename out of a `Content-Disposition` response header.
44
- *
45
- * The server is the single naming source (see `contentDispositionFilename` in
46
- * adapter-nestjs): it emits both the RFC 5987 `filename*=UTF-8''...` form
47
- * (accent-safe, percent-encoded) and a sanitized ASCII `filename="..."`
48
- * fallback. We prefer the extended form and percent-decode it so accented,
49
- * title-based names ("Pièce d'identité – 2.jpg") survive the round trip.
50
- *
51
- * Returns `undefined` when the header is absent or carries no filename, letting
52
- * callers fall back to a client-side name.
53
- */
54
- export declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
55
- type AppOperationGroups = typeof appOperationGroups;
56
- type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
57
- type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
58
- type VerbOf<N> = N extends `${string}.${infer V}` ? V : never;
59
- /** An `"events"` operation opens a stream (`transport.stream`); any other is one call. */
60
- type OptionsOf<O extends Operation> = O extends {
61
- readonly response: "events";
62
- } ? OperationStreamOptions : OperationCallOptions;
63
- /** An input the schema defaults (`.default({})`) may be left out; `options` carries the call's signal. */
64
- type OperationCall<O extends Operation> = (...args: undefined extends OperationInput<O> ? [input?: OperationInput<O>, options?: OptionsOf<O>] : [input: OperationInput<O>, options?: OptionsOf<O>]) => Promise<OperationResult<O>>;
65
- export type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
66
- /** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
67
- export declare function createAppClient(transport: HttpTransport): AppClient;
68
- export { type HttpTransport, type HttpTransportConfig, type OperationCallOptions, type OperationStreamOptions, StandardsAuthError, StandardsRequestError, type UploadProgress, createHttpTransport, readRefusal, refusalOf };
2
+ import { A as refusalOf, C as OperationTransport, D as createHttpTransport, E as UploadProgress, F as StandardsRequestError, N as StandardsAuthError, S as OperationStreamOptions, _ as schemaApiErrorCode, a as parseContentDispositionFilename, c as AgentStreamStatus, d as openAgentStream, f as draftConflictChanges, g as isViewNotFound, h as isPermanentRefusal, i as createInProcessTransport, k as readRefusal, l as OpenAgentStreamOptions, m as isObjectNotFound, n as createAppClient, o as AgentStreamControl, p as isDraftRevisionConflict, r as InProcessTransport, s as AgentStreamHandle, t as AppClient, u as TURN_END_TYPES, v as HttpTransport, x as OperationCallOptions, y as HttpTransportConfig } from "./app-_CiXRLoD.mjs";
3
+ export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type InProcessTransport, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
package/dist/app.d.ts CHANGED
@@ -1,68 +1,3 @@
1
1
 
2
- import { _ as StandardsRequestError, a as OperationStreamOptions, c as UploadProgress, d as readRefusal, f as refusalOf, h as StandardsAuthError, i as OperationCallOptions, l as createHttpTransport, n as HttpTransportConfig, t as HttpTransport } from "./http-transport-BxJhcXjy.js";
3
- import { DraftConflictChange } from "@standards/schema";
4
- import { Operation, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
5
- /** The server's `SchemaErrorCode` on a failed call, when it sent one. */
6
- export declare function schemaApiErrorCode(error: unknown): string | undefined;
7
- /** Whether a failure is an answer, and so must not be asked again. */
8
- export declare function isPermanentRefusal(error: unknown): boolean;
9
- /**
10
- * Whether a failure says the object does not exist, rather than that the read
11
- * failed (#3290): with a definition seeded from the cached catalogue, a 500 and
12
- * a 404 are opposite answers — a transient failure may be ridden out, an
13
- * authoritative not-found may not.
14
- *
15
- * Either signal is enough, deliberately: reading only the code would tolerate a
16
- * deleted object behind a plainer not-found, reading only the status would miss
17
- * a coded refusal carrying no status.
18
- */
19
- export declare function isObjectNotFound(error: unknown): boolean;
20
- /**
21
- * Whether a write was refused because the draft moved since it was read
22
- * (`DRAFT_REVISION_CONFLICT`, a 409): only a fresh read of the draft makes the
23
- * next attempt mean something (#4899).
24
- */
25
- export declare function isDraftRevisionConflict(error: unknown): boolean;
26
- /**
27
- * What a publish refused for a conflict found published on its targets since
28
- * the draft captured them (#5936). Empty for any other refusal, a conflict on
29
- * the draft's own revision included: that one is answered by reading it again.
30
- */
31
- export declare function draftConflictChanges(error: unknown): DraftConflictChange[];
32
- /**
33
- * Whether a view read failed because the object simply has no view for that
34
- * context (#2659) — a working object not laid out yet, not a failure.
35
- *
36
- * Status-only: the view routes' not-found carries the generic
37
- * `SCHEMA_RECORD_NOT_FOUND` code, which says nothing view-specific. Call it
38
- * ONLY on a view query's error — on any other query a 404 means something
39
- * else entirely.
40
- */
41
- export declare function isViewNotFound(error: unknown): boolean;
42
- /**
43
- * Parse the download filename out of a `Content-Disposition` response header.
44
- *
45
- * The server is the single naming source (see `contentDispositionFilename` in
46
- * adapter-nestjs): it emits both the RFC 5987 `filename*=UTF-8''...` form
47
- * (accent-safe, percent-encoded) and a sanitized ASCII `filename="..."`
48
- * fallback. We prefer the extended form and percent-decode it so accented,
49
- * title-based names ("Pièce d'identité – 2.jpg") survive the round trip.
50
- *
51
- * Returns `undefined` when the header is absent or carries no filename, letting
52
- * callers fall back to a client-side name.
53
- */
54
- export declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
55
- type AppOperationGroups = typeof appOperationGroups;
56
- type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
57
- type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
58
- type VerbOf<N> = N extends `${string}.${infer V}` ? V : never;
59
- /** An `"events"` operation opens a stream (`transport.stream`); any other is one call. */
60
- type OptionsOf<O extends Operation> = O extends {
61
- readonly response: "events";
62
- } ? OperationStreamOptions : OperationCallOptions;
63
- /** An input the schema defaults (`.default({})`) may be left out; `options` carries the call's signal. */
64
- type OperationCall<O extends Operation> = (...args: undefined extends OperationInput<O> ? [input?: OperationInput<O>, options?: OptionsOf<O>] : [input: OperationInput<O>, options?: OptionsOf<O>]) => Promise<OperationResult<O>>;
65
- export type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
66
- /** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
67
- export declare function createAppClient(transport: HttpTransport): AppClient;
68
- export { type HttpTransport, type HttpTransportConfig, type OperationCallOptions, type OperationStreamOptions, StandardsAuthError, StandardsRequestError, type UploadProgress, createHttpTransport, readRefusal, refusalOf };
2
+ import { A as refusalOf, C as OperationTransport, D as createHttpTransport, E as UploadProgress, F as StandardsRequestError, N as StandardsAuthError, S as OperationStreamOptions, _ as schemaApiErrorCode, a as parseContentDispositionFilename, c as AgentStreamStatus, d as openAgentStream, f as draftConflictChanges, g as isViewNotFound, h as isPermanentRefusal, i as createInProcessTransport, k as readRefusal, l as OpenAgentStreamOptions, m as isObjectNotFound, n as createAppClient, o as AgentStreamControl, p as isDraftRevisionConflict, r as InProcessTransport, s as AgentStreamHandle, t as AppClient, u as TURN_END_TYPES, v as HttpTransport, x as OperationCallOptions, y as HttpTransportConfig } from "./app-_CiXRLoD.js";
3
+ export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type InProcessTransport, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
package/dist/app.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./http-transport-Dr0ZiTG1.js");let t=require("@standards/schema/api");function createAppClient(e){let n={},r=Object.values(t.appOperationGroups);for(let i of r.flatMap(e=>Object.values(e))){let r=(0,t.operationGroup)(i),a=i.name.slice(r.length+1);n[r]??={},n[r][a]=(t,n)=>i.response===`events`?e.stream(i,t,n):e.call(i,t,n)}return n}exports.StandardsAuthError=e.h,exports.StandardsRequestError=e._,exports.createAppClient=createAppClient,exports.createHttpTransport=e.t,exports.draftConflictChanges=e.s,exports.isDraftRevisionConflict=e.c,exports.isObjectNotFound=e.l,exports.isPermanentRefusal=e.u,exports.isViewNotFound=e.d,exports.parseContentDispositionFilename=e.o,exports.readRefusal=e.r,exports.refusalOf=e.i,exports.schemaApiErrorCode=e.f;
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./app-BgWz3r5k.js");exports.StandardsAuthError=e.p,exports.StandardsRequestError=e.h,exports.TURN_END_TYPES=e.l,exports.createAppClient=e.t,exports.createHttpTransport=e.r,exports.createInProcessTransport=e.n,exports.draftConflictChanges=e.g,exports.isDraftRevisionConflict=e._,exports.isObjectNotFound=e.v,exports.isPermanentRefusal=e.y,exports.isViewNotFound=e.b,exports.openAgentStream=e.u,exports.parseContentDispositionFilename=e.c,exports.readRefusal=e.a,exports.refusalOf=e.o,exports.schemaApiErrorCode=e.x;
package/dist/app.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- import{_ as e,c as t,d as n,f as r,h as i,i as a,l as o,o as s,r as c,s as l,t as u,u as d}from"./http-transport-GAQftrWY.mjs";import{appOperationGroups as f,operationGroup as p}from"@standards/schema/api";function createAppClient(e){let t={},n=Object.values(f);for(let r of n.flatMap(e=>Object.values(e))){let n=p(r),i=r.name.slice(n.length+1);t[n]??={},t[n][i]=(t,n)=>r.response===`events`?e.stream(r,t,n):e.call(r,t,n)}return t}export{i as StandardsAuthError,e as StandardsRequestError,createAppClient,u as createHttpTransport,l as draftConflictChanges,t as isDraftRevisionConflict,o as isObjectNotFound,d as isPermanentRefusal,n as isViewNotFound,s as parseContentDispositionFilename,c as readRefusal,a as refusalOf,r as schemaApiErrorCode};
2
+ export{p as StandardsAuthError,h as StandardsRequestError,l as TURN_END_TYPES,t as createAppClient,r as createHttpTransport,n as createInProcessTransport,g as draftConflictChanges,_ as isDraftRevisionConflict,v as isObjectNotFound,y as isPermanentRefusal,b as isViewNotFound,u as openAgentStream,c as parseContentDispositionFilename,a as readRefusal,o as refusalOf,x as schemaApiErrorCode}from"./app-TJt8rk9y.mjs";
@@ -0,0 +1,4 @@
1
+ /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
+ const e=require("./app-BgWz3r5k.js");let t=require("@standards/schema"),n=require("@standards/schema/api");async function readInstalled(t,r){try{return await t.call(n.bundlesOperations.get,{name:r})}catch(t){if(t instanceof e.h&&t.status===404)return null;throw t}}async function syncBundle(t,r,i={}){let a=await r.build(),o=await readInstalled(t,a.name);if(o?.hash===a.hash&&o.label===a.label&&o.description===a.description&&o.uses.join(`
3
+ `)===a.uses.join(`
4
+ `))return{applied:!1,hash:a.hash};let s=i.resolutions&&i.resolutions.length>0?{...a,resolutions:i.resolutions}:a;try{return await t.call(n.bundlesOperations.sync,{name:a.name,bundle:s})}catch(t){throw t instanceof e.h&&t.status===409?new e.d(t.status,t.message,t.code):t instanceof e.h&&t.status===400?new e.f(t.status,t.message,t.code):t}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`,`as`]);function assertObjectKeys(t){let n=/* @__PURE__ */ new Map;for(let i of t){if(i.includes(`--`)||i.endsWith(`-`))throw new e.m(`Object "${i}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let t=objectKeyOf(i);if(r.has(t))throw new e.m(`Object "${i}" maps to the client key "${t}", which is reserved. Rename the object.`);let a=n.get(t);if(a!==void 0&&a!==i)throw new e.m(`Objects "${a}" and "${i}" both map to the client key "${t}". Rename one of them.`);n.set(t,i)}}function assertObjectNames(e){let n=/* @__PURE__ */ new Set;for(let r of e){if(n.has(r))throw new t.DuplicateError(`object`,r);n.add(r)}assertObjectKeys(e)}function readRecord(e,n){let{values:r,...i}=n;return(0,t.isPlainRecord)(r)?{...i,...(0,t.decodeRecordValues)(e,r)}:n}var i=class RecordsQueryImpl extends t.RecordQuery{constructor(e,t,n,r={object:t,combinator:`and`,rules:[],sorts:[]}){super(r),this.transport=e,this.objectName=t,this.definition=n}with(e){return new RecordsQueryImpl(this.transport,this.objectName,this.definition,{...this.state,...e})}body(){let e={};return this.state.search!==void 0&&(e.q=this.state.search),this.state.rules.length>0&&(e.filters={combinator:this.state.combinator,rules:this.state.rules}),this.state.sorts.length>0&&(e.sorts=this.state.sorts),this.state.limit!==void 0&&(e.limit=this.state.limit),this.state.offset!==void 0&&(e.offset=this.state.offset),e}revive(e){return readRecord(this.definition,e)}async export(t,r={}){if(!this.transport.postRaw)throw new e.m(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:i,sorts:a}=this.body(),{ids:o,locale:s,filename:c}=r;return await this.transport.postRaw((0,n.buildOperationPath)(n.recordsOperations.export,{objectName:this.objectName}),{q:this.state.search??``,...i?{filters:i}:{},...a?{sorts:a}:{},columns:t,...o?{ids:o}:{},...s?{locale:s}:{},timezone:r.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...c?{filename:c}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new t.AggregateValidationError(t.SchemaErrorCode.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let r={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.call(n.recordsOperations.aggregate,{objectName:this.objectName,...r})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(n.recordsOperations.list,e):await this.transport.call(n.recordsOperations.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(n.recordsOperations.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:r,metadata:i}={}){let a={...r!==void 0&&{allowDraft:r},...i!==void 0&&{metadata:i}},o=await this.transport.call(n.recordsOperations.create,{objectName:this.objectName,data:(0,t.encodeRecordValues)(this.definition,e),...Object.keys(a).length>0&&{options:a}});return this.revive(o)}async update(r,i,{metadata:a}={}){let o=(0,t.encodeRecordValues)(this.definition,i);if(a===void 0){let e=await this.transport.call(n.recordsOperations.update,{objectName:this.objectName,id:r,values:o});return this.revive(e)}let{objectId:s}=await this.transport.call(n.recordsOperations.get,{objectName:this.objectName,id:r}),{steps:c}=await this.transport.call(n.recordOperationsOperations.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:s,recordId:r,values:o,metadata:a}]}),[l]=c;if(l===void 0||l.status===`error`){let n=l?.code,r=n===void 0?500:t.SCHEMA_ERROR_HTTP_STATUS[n];throw e.o(r,JSON.stringify({message:l?.message,code:n}))}let u=(0,n.decodeOperationOutput)(n.recordsOperations.get,l.record);return this.revive(u)}async delete(e){await this.transport.call(n.recordsOperations.delete,{objectName:this.objectName,id:e})}async inChunks(e,t){for(let n=0;n<e.length;n+=100)await t(e.slice(n,n+100),n)}async createMany(e){let r={created:[],errors:[]};return await this.inChunks(e,async(e,i)=>{let a=await this.transport.call(n.recordsOperations.bulkCreate,{objectName:this.objectName,records:e.map(e=>(0,t.encodeRecordValues)(this.definition,e))});r.created.push(...a.created.map(e=>this.revive(e))),r.errors.push(...a.errors.map(e=>({...e,index:e.index+i})))}),r}async updateMany(e){let r={updated:[],errors:[]};return await this.inChunks(e,async e=>{let i=await this.transport.call(n.recordsOperations.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:n})=>({id:e,data:(0,t.encodeRecordValues)(this.definition,n)}))});r.updated.push(...i.updated.map(e=>this.revive(e))),r.errors.push(...i.errors)}),r}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.call(n.recordsOperations.bulkDelete,{objectName:this.objectName,ids:e});t.deleted.push(...r.deleted),t.errors.push(...r.errors)}),t}async listAccess(e){return await this.transport.call(n.recordAccessOperations.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,r){return await this.transport.call(n.recordAccessOperations.grant,{objectName:this.objectName,recordId:e,actorId:t,role:r})}async revokeAccess(e,t){return await this.transport.call(n.recordAccessOperations.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(n.recordAccessOperations.clear,{objectName:this.objectName,recordId:e})}};const a=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=a.get(e);if(t)return t;let n=e.build();return a.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new i(e,t,null);let n=definitionOf(t);return new i(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(t){if(globalThis.window!==void 0){if(t.apiKey)throw new e.m(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(t.baseUrl===void 0)throw new e.m(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...t,baseUrl:t.baseUrl,apiKey:``}}let n=readEnvironment(),r=t.baseUrl??n.baseUrl;if(r===void 0)throw new e.m(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=t.apiKey??n.apiKey;if(i===void 0)throw new e.m(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...t,baseUrl:r,apiKey:i}}function createStandards(t={}){let{bundles:n=[],transport:r,...i}=t;if(r!==void 0&&Object.values(i).some(e=>e!==void 0))throw new e.m(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(r??e.i(resolveConfig(i)),n.flatMap(e=>e.objectBuilders))}function buildStandards(t,r){let i=e.t(t),sync=((e,n)=>isBundleBuilder(e)?syncBundle(t,e,n):i.bundles.sync(e,n)),a={...i,bundles:{...i.bundles,sync},from:e=>createRecordsQuery(t,e),contract:i},o=r.map(e=>definitionOf(e).name);assertObjectNames(o),r.forEach((e,n)=>{a[objectKeyOf(o[n])]=createRecordsQuery(t,e)});let s=t.withCaller?.bind(t);return s!==void 0&&(a.as=e=>buildStandards(s((0,n.callerOf)(e)),r)),a}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return createRecordsQuery}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createStandards}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return readRecord}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return resolveConfig}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return syncBundle}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});
@@ -0,0 +1,4 @@
1
+ /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
+ import{d as e,f as t,h as n,i as r,m as i,o as a,t as o}from"./app-TJt8rk9y.mjs";import{AggregateValidationError as s,DuplicateError as c,RecordQuery as l,SCHEMA_ERROR_HTTP_STATUS as u,SchemaErrorCode as d,decodeRecordValues as f,encodeRecordValues as p,isPlainRecord as m}from"@standards/schema";import{buildOperationPath as h,bundlesOperations as g,callerOf as _,decodeOperationOutput as v,recordAccessOperations as y,recordOperationsOperations as b,recordsOperations as x}from"@standards/schema/api";async function readInstalled(e,t){try{return await e.call(g.get,{name:t})}catch(e){if(e instanceof n&&e.status===404)return null;throw e}}async function syncBundle(r,i,a={}){let o=await i.build(),s=await readInstalled(r,o.name);if(s?.hash===o.hash&&s.label===o.label&&s.description===o.description&&s.uses.join(`
3
+ `)===o.uses.join(`
4
+ `))return{applied:!1,hash:o.hash};let c=a.resolutions&&a.resolutions.length>0?{...o,resolutions:a.resolutions}:o;try{return await r.call(g.sync,{name:o.name,bundle:c})}catch(r){throw r instanceof n&&r.status===409?new e(r.status,r.message,r.code):r instanceof n&&r.status===400?new t(r.status,r.message,r.code):r}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const S=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`,`as`]);function assertObjectKeys(e){let t=/* @__PURE__ */ new Map;for(let n of e){if(n.includes(`--`)||n.endsWith(`-`))throw new i(`Object "${n}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(n);if(S.has(e))throw new i(`Object "${n}" maps to the client key "${e}", which is reserved. Rename the object.`);let r=t.get(e);if(r!==void 0&&r!==n)throw new i(`Objects "${r}" and "${n}" both map to the client key "${e}". Rename one of them.`);t.set(e,n)}}function assertObjectNames(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(t.has(n))throw new c(`object`,n);t.add(n)}assertObjectKeys(e)}function readRecord(e,t){let{values:n,...r}=t;return m(n)?{...r,...f(e,n)}:t}var C=class RecordsQueryImpl extends l{constructor(e,t,n,r={object:t,combinator:`and`,rules:[],sorts:[]}){super(r),this.transport=e,this.objectName=t,this.definition=n}with(e){return new RecordsQueryImpl(this.transport,this.objectName,this.definition,{...this.state,...e})}body(){let e={};return this.state.search!==void 0&&(e.q=this.state.search),this.state.rules.length>0&&(e.filters={combinator:this.state.combinator,rules:this.state.rules}),this.state.sorts.length>0&&(e.sorts=this.state.sorts),this.state.limit!==void 0&&(e.limit=this.state.limit),this.state.offset!==void 0&&(e.offset=this.state.offset),e}revive(e){return readRecord(this.definition,e)}async export(e,t={}){if(!this.transport.postRaw)throw new i(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:n,sorts:r}=this.body(),{ids:a,locale:o,filename:s}=t;return await this.transport.postRaw(h(x.export,{objectName:this.objectName}),{q:this.state.search??``,...n?{filters:n}:{},...r?{sorts:r}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:t.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new s(d.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let t={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.call(x.aggregate,{objectName:this.objectName,...t})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(x.list,e):await this.transport.call(x.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(x.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:t,metadata:n}={}){let r={...t!==void 0&&{allowDraft:t},...n!==void 0&&{metadata:n}},i=await this.transport.call(x.create,{objectName:this.objectName,data:p(this.definition,e),...Object.keys(r).length>0&&{options:r}});return this.revive(i)}async update(e,t,{metadata:n}={}){let r=p(this.definition,t);if(n===void 0){let t=await this.transport.call(x.update,{objectName:this.objectName,id:e,values:r});return this.revive(t)}let{objectId:i}=await this.transport.call(x.get,{objectName:this.objectName,id:e}),{steps:o}=await this.transport.call(b.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:i,recordId:e,values:r,metadata:n}]}),[s]=o;if(s===void 0||s.status===`error`){let e=s?.code,t=e===void 0?500:u[e];throw a(t,JSON.stringify({message:s?.message,code:e}))}let c=v(x.get,s.record);return this.revive(c)}async delete(e){await this.transport.call(x.delete,{objectName:this.objectName,id:e})}async inChunks(e,t){for(let n=0;n<e.length;n+=100)await t(e.slice(n,n+100),n)}async createMany(e){let t={created:[],errors:[]};return await this.inChunks(e,async(e,n)=>{let r=await this.transport.call(x.bulkCreate,{objectName:this.objectName,records:e.map(e=>p(this.definition,e))});t.created.push(...r.created.map(e=>this.revive(e))),t.errors.push(...r.errors.map(e=>({...e,index:e.index+n})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(x.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:t})=>({id:e,data:p(this.definition,t)}))});t.updated.push(...n.updated.map(e=>this.revive(e))),t.errors.push(...n.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(x.bulkDelete,{objectName:this.objectName,ids:e});t.deleted.push(...n.deleted),t.errors.push(...n.errors)}),t}async listAccess(e){return await this.transport.call(y.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,n){return await this.transport.call(y.grant,{objectName:this.objectName,recordId:e,actorId:t,role:n})}async revokeAccess(e,t){return await this.transport.call(y.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(y.clear,{objectName:this.objectName,recordId:e})}};const w=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=w.get(e);if(t)return t;let n=e.build();return w.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new C(e,t,null);let n=definitionOf(t);return new C(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(e){if(globalThis.window!==void 0){if(e.apiKey)throw new i(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(e.baseUrl===void 0)throw new i(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...e,baseUrl:e.baseUrl,apiKey:``}}let t=readEnvironment(),n=e.baseUrl??t.baseUrl;if(n===void 0)throw new i(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let r=e.apiKey??t.apiKey;if(r===void 0)throw new i(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:n,apiKey:r}}function createStandards(e={}){let{bundles:t=[],transport:n,...a}=e;if(n!==void 0&&Object.values(a).some(e=>e!==void 0))throw new i(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(n??r(resolveConfig(a)),t.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n=o(e),sync=((t,r)=>isBundleBuilder(t)?syncBundle(e,t,r):n.bundles.sync(t,r)),r={...n,bundles:{...n.bundles,sync},from:t=>createRecordsQuery(e,t),contract:n},i=t.map(e=>definitionOf(e).name);assertObjectNames(i),t.forEach((t,n)=>{r[objectKeyOf(i[n])]=createRecordsQuery(e,t)});let a=e.withCaller?.bind(e);return a!==void 0&&(r.as=e=>buildStandards(a(_(e)),t)),r}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}export{definitionOf as a,createRecordsQuery as i,createStandards as n,readRecord as o,resolveConfig as r,syncBundle as s,buildStandards as t};