@standards/client 0.0.0-stage → 1.0.0-alpha.382

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,165 @@
1
+
2
+ import { Operation, OperationInput, OperationResult } from "@standards/schema/api";
3
+ //#region src/errors.d.ts
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 /schema/sources/:id`: a name this source declares is owned by core, a bundle, or
20
+ * another source. A declared view that clashes with the workspace's views (a second default for
21
+ * the same object and context, or a name held by a system view) is a 409 too; its message names
22
+ * no owner, so `objectName` and `owner` are empty.
23
+ */
24
+ declare class SchemaSourceConflictError extends StandardsRequestError {
25
+ /** The object or `object:view` name that clashed. */
26
+ readonly objectName: string;
27
+ /** `core`, `bundle:<id>` or `source:<id>`. */
28
+ readonly owner: string;
29
+ constructor(status: number, message: string, code: string | undefined);
30
+ }
31
+ /** 400 from `PUT /schema/sources/:id`: bad id, oversize payload, hash mismatch, invalid definition, or an unresolved migration. */
32
+ declare class SchemaSourceValidationError 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
+ //#endregion
40
+ //#region src/transport/http-transport.d.ts
41
+ /** Per-request overrides a multipart upload may carry. */
42
+ interface MultipartRequestOptions {
43
+ /** This request's timeout in ms, instead of the client's `timeoutMs`. */
44
+ timeoutMs?: number;
45
+ }
46
+ interface HttpTransportConfig {
47
+ baseUrl: string;
48
+ /** A path joined between `baseUrl` and every request path. */
49
+ apiPrefix?: string;
50
+ fetch?: typeof fetch;
51
+ /** Read before every attempt, so a refreshed token reaches the retry. */
52
+ headers?: () => HeadersInit | Promise<HeadersInit>;
53
+ /** Asked on a 401; `true` means the credentials were refreshed and the request is sent once more. */
54
+ onUnauthorized?: () => Promise<boolean>;
55
+ /** Sees every response — success, refusal, and the retry after a refresh. Read-only: the body belongs to the request. */
56
+ onResponse?: (response: Response) => void;
57
+ /** Per attempt, in ms. Defaults to 30 000. */
58
+ timeoutMs?: number;
59
+ /** Extra attempts after the first for a GET (5xx and network failures). Defaults to 0. */
60
+ getRetries?: number;
61
+ /**
62
+ * The bearer an upload sent over XMLHttpRequest carries (to report its
63
+ * progress): XHR cannot run an injected `fetch`, where an app's auth lives,
64
+ * so with an injected `fetch` and no `uploadAuthorization` an upload goes
65
+ * through `fetch` and reports no progress.
66
+ */
67
+ uploadAuthorization?: () => Promise<string | null>;
68
+ }
69
+ /** Bytes of a multipart body sent so far, out of its total. */
70
+ interface UploadProgress {
71
+ loaded: number;
72
+ total: number;
73
+ }
74
+ /** Per-call options of one operation. */
75
+ interface OperationCallOptions {
76
+ /** Aborts the call: it rejects with the signal's reason (an `AbortError` by default). */
77
+ signal?: AbortSignal;
78
+ /** Extra attempts after the first; defaults to `getRetries` for a GET and 0 otherwise. */
79
+ maxRetries?: number;
80
+ /**
81
+ * This call's wait for the response headers, in ms, instead of the client's
82
+ * `timeoutMs`; `null` waits as long as it takes (an upload's body is sent
83
+ * before the headers come back, so a large one outlives any fixed deadline).
84
+ */
85
+ timeoutMs?: number | null;
86
+ /**
87
+ * Lets the request outlive the page that sent it (`fetch`'s `keepalive`),
88
+ * on every attempt: for a write taken right before a navigation, which the
89
+ * browser would otherwise cancel in flight.
90
+ */
91
+ keepalive?: boolean;
92
+ /**
93
+ * The bytes of an `upload` operation's body sent so far. `fetch` cannot
94
+ * report them, so the upload goes over XMLHttpRequest — one attempt, no
95
+ * deadline, no refresh on a 401 — when the transport can authenticate it
96
+ * there (see `uploadAuthorization`); otherwise it goes through `fetch` and
97
+ * reports nothing.
98
+ */
99
+ onUploadProgress?: (progress: UploadProgress) => void;
100
+ }
101
+ /**
102
+ * Per-call options of an `"events"` operation. No deadline and no retry: a
103
+ * stream outlives any request timeout, so its signal is the only abort.
104
+ */
105
+ interface OperationStreamOptions {
106
+ signal?: AbortSignal;
107
+ /** Merged over the configured headers (`Accept: text/event-stream`). */
108
+ headers?: Record<string, string>;
109
+ /**
110
+ * Observes each HTTP attempt, the one after a 401 refresh included, so a
111
+ * reader can tell which credential a refusal answered.
112
+ */
113
+ onRequest?: () => void;
114
+ }
115
+ interface HttpTransport {
116
+ /**
117
+ * Sends one operation: path parameters fill the path; the rest is the query
118
+ * for a GET, otherwise the body, except the keys the operation lists in `query`.
119
+ * An `upload` operation sends its body as multipart, its files under the
120
+ * operation's field; a `response: "bytes"` one resolves to a `DownloadedFile`.
121
+ */
122
+ call<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationCallOptions): Promise<OperationResult<O>>;
123
+ /**
124
+ * Opens an `"events"` operation and resolves to its `Response` once the
125
+ * headers are in, for the caller to read: no deadline, no retry, one
126
+ * refresh on a 401 (never on `MFA_REQUIRED`, which a token cannot satisfy).
127
+ * Any refusal is read and thrown as the typed error before a byte streams.
128
+ */
129
+ stream<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationStreamOptions): Promise<Response>;
130
+ get<T = unknown>(path: string, params?: Record<string, unknown>): Promise<T>;
131
+ post<T = unknown>(path: string, body?: unknown): Promise<T>;
132
+ patch<T = unknown>(path: string, body?: unknown): Promise<T>;
133
+ put<T = unknown>(path: string, body?: unknown): Promise<T>;
134
+ delete<T = unknown>(path: string): Promise<T>;
135
+ getText(path: string, params?: Record<string, unknown>): Promise<string>;
136
+ /**
137
+ * POST that hands back the unread `Response` so a caller can stream a large
138
+ * body (the CSV export). A refusal is read here and thrown as the typed error.
139
+ */
140
+ postRaw(path: string, body: unknown): Promise<Response>;
141
+ postMultipart<T>(path: string, form: FormData, options?: MultipartRequestOptions): Promise<T>;
142
+ }
143
+ /** The verbs the records, files and schema layers use; `createTransport` returns their superset. */
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
+ //#endregion
165
+ export { StandardsRequestError as _, OperationStreamOptions as a, UploadProgress as c, readRefusal as d, refusalOf as f, StandardsConfigurationError as g, StandardsAuthError as h, OperationCallOptions as i, createHttpTransport as l, SchemaSourceValidationError as m, HttpTransportConfig as n, Transport as o, SchemaSourceConflictError as p, MultipartRequestOptions as r, TransportConfig as s, HttpTransport as t, createTransport as u };
@@ -0,0 +1,165 @@
1
+
2
+ import { Operation, OperationInput, OperationResult } from "@standards/schema/api";
3
+ //#region src/errors.d.ts
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 /schema/sources/:id`: a name this source declares is owned by core, a bundle, or
20
+ * another source. A declared view that clashes with the workspace's views (a second default for
21
+ * the same object and context, or a name held by a system view) is a 409 too; its message names
22
+ * no owner, so `objectName` and `owner` are empty.
23
+ */
24
+ declare class SchemaSourceConflictError extends StandardsRequestError {
25
+ /** The object or `object:view` name that clashed. */
26
+ readonly objectName: string;
27
+ /** `core`, `bundle:<id>` or `source:<id>`. */
28
+ readonly owner: string;
29
+ constructor(status: number, message: string, code: string | undefined);
30
+ }
31
+ /** 400 from `PUT /schema/sources/:id`: bad id, oversize payload, hash mismatch, invalid definition, or an unresolved migration. */
32
+ declare class SchemaSourceValidationError 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
+ //#endregion
40
+ //#region src/transport/http-transport.d.ts
41
+ /** Per-request overrides a multipart upload may carry. */
42
+ interface MultipartRequestOptions {
43
+ /** This request's timeout in ms, instead of the client's `timeoutMs`. */
44
+ timeoutMs?: number;
45
+ }
46
+ interface HttpTransportConfig {
47
+ baseUrl: string;
48
+ /** A path joined between `baseUrl` and every request path. */
49
+ apiPrefix?: string;
50
+ fetch?: typeof fetch;
51
+ /** Read before every attempt, so a refreshed token reaches the retry. */
52
+ headers?: () => HeadersInit | Promise<HeadersInit>;
53
+ /** Asked on a 401; `true` means the credentials were refreshed and the request is sent once more. */
54
+ onUnauthorized?: () => Promise<boolean>;
55
+ /** Sees every response — success, refusal, and the retry after a refresh. Read-only: the body belongs to the request. */
56
+ onResponse?: (response: Response) => void;
57
+ /** Per attempt, in ms. Defaults to 30 000. */
58
+ timeoutMs?: number;
59
+ /** Extra attempts after the first for a GET (5xx and network failures). Defaults to 0. */
60
+ getRetries?: number;
61
+ /**
62
+ * The bearer an upload sent over XMLHttpRequest carries (to report its
63
+ * progress): XHR cannot run an injected `fetch`, where an app's auth lives,
64
+ * so with an injected `fetch` and no `uploadAuthorization` an upload goes
65
+ * through `fetch` and reports no progress.
66
+ */
67
+ uploadAuthorization?: () => Promise<string | null>;
68
+ }
69
+ /** Bytes of a multipart body sent so far, out of its total. */
70
+ interface UploadProgress {
71
+ loaded: number;
72
+ total: number;
73
+ }
74
+ /** Per-call options of one operation. */
75
+ interface OperationCallOptions {
76
+ /** Aborts the call: it rejects with the signal's reason (an `AbortError` by default). */
77
+ signal?: AbortSignal;
78
+ /** Extra attempts after the first; defaults to `getRetries` for a GET and 0 otherwise. */
79
+ maxRetries?: number;
80
+ /**
81
+ * This call's wait for the response headers, in ms, instead of the client's
82
+ * `timeoutMs`; `null` waits as long as it takes (an upload's body is sent
83
+ * before the headers come back, so a large one outlives any fixed deadline).
84
+ */
85
+ timeoutMs?: number | null;
86
+ /**
87
+ * Lets the request outlive the page that sent it (`fetch`'s `keepalive`),
88
+ * on every attempt: for a write taken right before a navigation, which the
89
+ * browser would otherwise cancel in flight.
90
+ */
91
+ keepalive?: boolean;
92
+ /**
93
+ * The bytes of an `upload` operation's body sent so far. `fetch` cannot
94
+ * report them, so the upload goes over XMLHttpRequest — one attempt, no
95
+ * deadline, no refresh on a 401 — when the transport can authenticate it
96
+ * there (see `uploadAuthorization`); otherwise it goes through `fetch` and
97
+ * reports nothing.
98
+ */
99
+ onUploadProgress?: (progress: UploadProgress) => void;
100
+ }
101
+ /**
102
+ * Per-call options of an `"events"` operation. No deadline and no retry: a
103
+ * stream outlives any request timeout, so its signal is the only abort.
104
+ */
105
+ interface OperationStreamOptions {
106
+ signal?: AbortSignal;
107
+ /** Merged over the configured headers (`Accept: text/event-stream`). */
108
+ headers?: Record<string, string>;
109
+ /**
110
+ * Observes each HTTP attempt, the one after a 401 refresh included, so a
111
+ * reader can tell which credential a refusal answered.
112
+ */
113
+ onRequest?: () => void;
114
+ }
115
+ interface HttpTransport {
116
+ /**
117
+ * Sends one operation: path parameters fill the path; the rest is the query
118
+ * for a GET, otherwise the body, except the keys the operation lists in `query`.
119
+ * An `upload` operation sends its body as multipart, its files under the
120
+ * operation's field; a `response: "bytes"` one resolves to a `DownloadedFile`.
121
+ */
122
+ call<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationCallOptions): Promise<OperationResult<O>>;
123
+ /**
124
+ * Opens an `"events"` operation and resolves to its `Response` once the
125
+ * headers are in, for the caller to read: no deadline, no retry, one
126
+ * refresh on a 401 (never on `MFA_REQUIRED`, which a token cannot satisfy).
127
+ * Any refusal is read and thrown as the typed error before a byte streams.
128
+ */
129
+ stream<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationStreamOptions): Promise<Response>;
130
+ get<T = unknown>(path: string, params?: Record<string, unknown>): Promise<T>;
131
+ post<T = unknown>(path: string, body?: unknown): Promise<T>;
132
+ patch<T = unknown>(path: string, body?: unknown): Promise<T>;
133
+ put<T = unknown>(path: string, body?: unknown): Promise<T>;
134
+ delete<T = unknown>(path: string): Promise<T>;
135
+ getText(path: string, params?: Record<string, unknown>): Promise<string>;
136
+ /**
137
+ * POST that hands back the unread `Response` so a caller can stream a large
138
+ * body (the CSV export). A refusal is read here and thrown as the typed error.
139
+ */
140
+ postRaw(path: string, body: unknown): Promise<Response>;
141
+ postMultipart<T>(path: string, form: FormData, options?: MultipartRequestOptions): Promise<T>;
142
+ }
143
+ /** The verbs the records, files and schema layers use; `createTransport` returns their superset. */
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
+ //#endregion
165
+ export { StandardsRequestError as _, OperationStreamOptions as a, UploadProgress as c, readRefusal as d, refusalOf as f, StandardsConfigurationError as g, StandardsAuthError as h, OperationCallOptions as i, createHttpTransport as l, SchemaSourceValidationError as m, HttpTransportConfig as n, Transport as o, SchemaSourceConflictError as p, MultipartRequestOptions as r, TransportConfig as s, HttpTransport as t, createTransport as u };
@@ -0,0 +1,2 @@
1
+ /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
+ let e=require("@standards/schema"),t=require("@standards/schema/api");var StandardsRequestError=class extends Error{constructor(e,t,n,r){super(t),this.name=`StandardsRequestError`,this.status=e,this.code=n,this.details=r}},StandardsAuthError=class extends StandardsRequestError{constructor(e,t,n,r){super(e,t,n,r),this.name=`StandardsAuthError`}},SchemaSourceConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`SchemaSourceConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},SchemaSourceValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`SchemaSourceValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}const n=new Set([e.SchemaErrorCode.CONFIGURATION_REQUIRED]);function isPermanentRefusal(e){let t=schemaApiErrorCode(e);return t!==void 0&&n.has(t)}function isObjectNotFound(t){if(typeof t!=`object`||!t)return!1;let{code:n,status:r}=t;return n===e.SchemaErrorCode.OBJECT_NOT_FOUND||r===404}function isDraftRevisionConflict(t){return schemaApiErrorCode(t)===e.SchemaErrorCode.DRAFT_REVISION_CONFLICT}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}function parseContentDispositionFilename(e){if(!e)return;let t=e.match(/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/i);if(t?.[1])try{return decodeURIComponent(t[1].trim())}catch{}let n=e.match(/filename\s*=\s*"([^"]*)"|filename\s*=\s*([^;]+)/i);return(n?.[1]??n?.[2])?.trim()||void 0}function recordsPath(e,...n){return[`/records`,...[e,...n].map(t.encodePathSegment)].join(`/`)}function resolveWithinBase(t,n){let r=t.endsWith(`/`)?t:`${t}/`,i=new URL(r),a=n.replace(/^\/+/,``),[o]=a.split(/[?#]/);if((o??``).split(`/`).some(e=>e===`..`||e===`.`))throw new e.ValidationError(`Request path "${n}" walks outside its own collection`,[]);let s=new URL(a,i);if(s.origin!==i.origin||!s.pathname.startsWith(i.pathname))throw new e.ValidationError(`Request path "${n}" resolves outside the API base "${i.pathname}"`,[]);return s}function readJson(e){return e.status===204||e.headers.get(`content-length`)===`0`?null:e.json()}async function readDownload(e){let t=await e.blob();return{blob:t,filename:parseContentDispositionFilename(e.headers.get(`Content-Disposition`)),mimeType:e.headers.get(`Content-Type`)??t.type}}function multipartBody(e,t){let n=new FormData;for(let[r,i]of Object.entries(t??{}))if(i!=null){if(r===e)for(let t of Array.isArray(i)?i:[i]){let r=t.name;typeof r==`string`?n.append(e,t,r):n.append(e,t)}else n.append(r,String(i))}return n}function headerRecord(e){return e===void 0?{}:e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}}function withoutContentType(e){return Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`content-type`))}function parseJsonObject(e){try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return}}function refusalFrom(e,t,n){let r=parseJsonObject(t),i=r?.message??r?.error??r?.detail,a=i==null?n&&r===void 0&&t?t:`Request failed with status ${e}`:String(i),o=typeof r?.code==`string`?r.code:void 0;return new(e===401||e===403?StandardsAuthError:StandardsRequestError)(e,a,o,r?.details)}function refusalOf(e,t){return refusalFrom(e,t,!1)}async function readRefusal(e){return refusalOf(e.status,await e.text().catch(()=>``))}function isTimeout(e){return e instanceof DOMException&&e.name===`TimeoutError`}function trimSlashes(e,t){let n=0,r=e.length;for(;t&&n<r&&e[n]===`/`;)n+=1;for(;r>n&&e[r-1]===`/`;)--r;return e.slice(n,r)}function backoff(e){return new Promise(t=>setTimeout(t,1e3*2**e))}function abortReason(e){return e?.aborted?e.reason:new DOMException(`The operation was aborted.`,`AbortError`)}function canReportUploadProgress(e){return typeof XMLHttpRequest>`u`?!1:e.fetch===void 0||e.uploadAuthorization!==void 0}function sendWithProgress(e,t){let{signal:n}=e;return n?.aborted?Promise.reject(abortReason(n)):new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(e.method,e.url);for(let[t,n]of Object.entries(e.headers))a.setRequestHeader(t,n);let o=Object.keys(e.headers).some(e=>e.toLowerCase()===`authorization`);e.token&&!o&&a.setRequestHeader(`Authorization`,`Bearer ${e.token}`),a.upload.addEventListener(`progress`,t=>{t.lengthComputable&&e.onUploadProgress({loaded:t.loaded,total:t.total})});let onAbort=()=>a.abort();n?.addEventListener(`abort`,onAbort,{once:!0});let settle=()=>n?.removeEventListener(`abort`,onAbort);a.addEventListener(`load`,()=>{if(settle(),a.status<200||a.status>=300){i(refusalOf(a.status,a.responseText));return}try{r(t(a.responseText))}catch(e){i(e)}}),a.addEventListener(`error`,()=>{settle(),i(new StandardsRequestError(0,`Network request failed`))}),a.addEventListener(`abort`,()=>{settle(),i(abortReason(n))}),a.send(e.form)})}function createHttpTransport(e){let{baseUrl:n,onUnauthorized:r,getRetries:i=0}=e,a=e.timeoutMs??3e4,o=e.apiPrefix===void 0?void 0:trimSlashes(e.apiPrefix,!0),s=o?`${trimSlashes(n,!1)}/${o}`:n;function buildUrl(e,t){let n=resolveWithinBase(s,e);for(let[e,r]of Object.entries(t??{}))r!=null&&n.searchParams.set(e,String(r));return n.toString()}async function headersFor(t){let n={"Content-Type":`application/json`,...headerRecord(await e.headers?.()),...headerRecord(t.headers)};return t.body instanceof FormData?withoutContentType(n):n}function observe(t){try{e.onResponse?.(t)}catch{}}async function fetchOnce(t,n,r){let i=n.signal??void 0;i?.throwIfAborted();let a=r===null?void 0:AbortSignal.timeout(r),o=new AbortController,expire=()=>o.abort(a?.reason);a?.addEventListener(`abort`,expire,{once:!0});let s=i?AbortSignal.any([i,o.signal]):o.signal,c=new Promise((e,t)=>{s.addEventListener(`abort`,()=>t(s.reason),{once:!0})});try{let r=e.fetch??fetch,i=await headersFor(n);return await Promise.race([r(t,{...n,headers:i,signal:s}),c])}catch(e){throw i?.aborted?i.reason:e}finally{a?.removeEventListener(`abort`,expire)}}function connectionFailure(e){return e instanceof TypeError||isTimeout(e)?new StandardsRequestError(0,`Could not connect to ${n}`):e}async function refreshAndRetry(e,t,n){try{if(!await r?.())return;let i=await fetchOnce(e,t,n);return observe(i),i}catch{if(t.signal?.aborted)throw t.signal.reason;return}}async function readRefusalWithin(e){let t,n=new Promise(n=>{t=setTimeout(()=>n(refusalFrom(e.status,``,!1)),1500)});try{let t=e.text().catch(()=>``).then(t=>refusalFrom(e.status,t,!1));return await Promise.race([t,n])}finally{clearTimeout(t)}}async function send(e,t,n,o){let s=buildUrl(e,n.params),c=(t.method??`GET`).toUpperCase(),l=n.maxRetries??(c===`GET`?i:0),u=n.timeoutMs===void 0?a:n.timeoutMs;for(let e=0;;e++){let i=e<l,a;try{a=await fetchOnce(s,t,u)}catch(n){if(i&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(a),a.status>=500&&i){let t=await readRefusalWithin(a);if(isPermanentRefusal(t))throw t;await backoff(e);continue}if(a.status===401&&r&&(a=await refreshAndRetry(s,t,u)??a),!a.ok){let e=await a.text().catch(()=>``);throw refusalFrom(a.status,e,n.plainTextRefusal??!1)}return await o(a)}}async function stream(n,i,a={}){let{path:o,query:s,body:c,headers:l}=(0,t.splitOperationInput)(n,i??{}),u=buildUrl(o,s),{signal:d,onRequest:f}=a,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(u,{method:n.method,body:c===void 0?void 0:JSON.stringify(c),signal:d,headers:await headersFor({headers:{...l,...a.headers}})})),m=await attempt();if(m.status===401){let e=await readRefusal(m);if(e.code===`MFA_REQUIRED`||!r||!await r().catch(()=>!1))throw e;d?.throwIfAborted(),m=await attempt()}if(!m.ok)throw await readRefusal(m);return m}async function json(e,t,n){return await send(t,{method:e,body:n?JSON.stringify(n):void 0},{},readJson)}return{async call(n,r,i={}){if(n.response===`events`)return await stream(n,r,{signal:i.signal});let{path:a,query:o,body:s,headers:c}=(0,t.splitOperationInput)(n,r??{});if(n.upload!==void 0&&i.onUploadProgress&&canReportUploadProgress(e)){i.signal?.throwIfAborted();let t=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(a,o),method:n.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:t,form:multipartBody(n.upload.field,s),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>e?JSON.parse(e):null)}let l=n.upload===void 0?s===void 0?void 0:JSON.stringify(s):multipartBody(n.upload.field,s),u=n.response===`bytes`?readDownload:readJson;return await send(a,{method:n.method,body:l,signal:i.signal,...c?{headers:c}:{},...i.keepalive?{keepalive:!0}:{}},{params:o,maxRetries:i.maxRetries,timeoutMs:i.timeoutMs},u)},stream,async get(e,t){return await send(e,{method:`GET`},{params:t},readJson)},post:(e,t)=>json(`POST`,e,t),patch:(e,t)=>json(`PATCH`,e,t),put:(e,t)=>json(`PUT`,e,t),delete:e=>json(`DELETE`,e),async getText(e,t){return await send(e,{method:`GET`},{params:t,plainTextRefusal:!0},e=>e.text())},async postRaw(e,t){return await send(e,{method:`POST`,body:JSON.stringify(t)},{plainTextRefusal:!0},e=>e)},async postMultipart(e,t,n={}){return await send(e,{method:`POST`,body:t},{timeoutMs:n.timeoutMs},readJson)}}}function createTransport(e){let{baseUrl:t,apiKey:n,tenantId:r,timeoutMs:i}=e,a={Authorization:`Bearer ${n}`,...r?{"X-Tenant-ID":r}:{}};return createHttpTransport({baseUrl:t,timeoutMs:i,headers:()=>a})}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return recordsPath}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return isObjectNotFound}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return schemaApiErrorCode}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return SchemaSourceConflictError}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return StandardsRequestError}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return StandardsConfigurationError}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return refusalOf}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return isPermanentRefusal}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return StandardsAuthError}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createTransport}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return parseContentDispositionFilename}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return SchemaSourceValidationError}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return readRefusal}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return isDraftRevisionConflict}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createHttpTransport}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return isViewNotFound}});
@@ -0,0 +1,22 @@
1
+
2
+ import { _ as StandardsRequestError, g as StandardsConfigurationError, h as StandardsAuthError, m as SchemaSourceValidationError, o as Transport, p as SchemaSourceConflictError, r as MultipartRequestOptions, s as TransportConfig, u as createTransport } from "./http-transport-DBgedLFQ.mjs";
3
+ import { A as UploadFileInput, B as FileInput, C as UpdateManyResult, D as FilesTransport, E as FilesApi, F as AttachToRecordInput, G as SchemaSource, H as IconName, I as AttachToRecordResult, J as defineSchemaSource, K as SchemaSourceConfig, L as DocumentsApi, M as UploadPublicFileInput, N as UploadedFile, O as PrivateUploadedFile, P as createFilesApi, R as DocumentsTransport, S as UpdateManyError, T as CamelCase, U as ObjectBuilderLike, V as UploadTimeoutOption, W as ResolvedSchemaSource, X as resolveSchemaSource, Y as hashSchemaSource, Z as sourceIdFromPackageName, _ as RecordsExportOptions, a as SchemaSourceSummary, b as UntypedRecordsQuery, c as syncSchemaSource, d as DeleteManyError, f as DeleteManyResult, g as RecordsAggregateOptions, h as RecordUpdate, i as createStandards, j as UploadPrivateFileInput, k as PublicUploadedFile, l as CreateManyError, m as RecordInput, n as Standards, o as SyncOptions, p as FetchResult, q as ViewInput, r as StandardsConfig, s as SyncResult, t as ObjectsOf, u as CreateManyResult, v as RecordsQuery, w as createRecordsQuery, x as UpdateManyEntry, y as UntypedBuilder, z as createDocumentsApi } from "./create-standards-Cl_Lxvy3.mjs";
4
+ import { Attribute, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, NotFoundError, ObjectDefinition, ObjectDefinition as ObjectDefinition$1, RecordAccessRole, RecordAudience, RecordMetadata, SCHEMA_SOURCE_ID_PATTERN, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, assertSchemaSourceId, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
5
+ import { encodePathSegment } from "@standards/schema/api";
6
+ //#region src/records/revive.d.ts
7
+ /**
8
+ * JSON delivers dates as ISO strings; the client knows the definition, so it
9
+ * revives system timestamps and every `date` attribute so `ExtractRecord` tells
10
+ * the truth on the wire. Nothing else is transformed.
11
+ */
12
+ export declare function reviveRecord<T extends Record<string, unknown>>(definition: ObjectDefinition$1 | null, raw: T): T;
13
+ //#endregion
14
+ //#region src/path.d.ts
15
+ /**
16
+ * Every caller-supplied path segment is percent-encoded: `objectName` and `id`
17
+ * come from the application, and an id such as `../../schema/sources/x` must
18
+ * never leave `/records/<object>/`.
19
+ */
20
+ export declare function recordsPath(objectName: string, ...segments: string[]): string;
21
+ //#endregion
22
+ export { type AttachToRecordInput, type AttachToRecordResult, type Attribute, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, type DocumentsApi, type DocumentsTransport, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FileInput, type FilesApi, type FilesTransport, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type IconName, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type PrivateUploadedFile, type PublicUploadedFile, type RecordAccessRole, type RecordAudience, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type ResolvedSchemaSource, SCHEMA_SOURCE_ID_PATTERN, SchemaError, SchemaErrorCode, type SchemaSource, type SchemaSourceConfig, SchemaSourceConflictError, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SchemaSourceSummary, SchemaSourceValidationError, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, StandardsRequestError, type SyncOptions, type SyncResult, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UploadFileInput, type UploadPrivateFileInput, type UploadPublicFileInput, type UploadTimeoutOption, type UploadedFile, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewInput, type ViewerAccess, assertSchemaSourceId, canonicalStringify, checkbox, content, createDocumentsApi, createFilesApi, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, defineSchemaSource, detailView, document, encodePathSegment, formula, group, hashSchemaSource, listView, location, multiselect, now, number, object, phone, query, relation, resolveSchemaSource, richtext, rollup, select, sourceIdFromPackageName, status, syncSchemaSource, text, today, user };
@@ -0,0 +1,22 @@
1
+
2
+ import { _ as StandardsRequestError, g as StandardsConfigurationError, h as StandardsAuthError, m as SchemaSourceValidationError, o as Transport, p as SchemaSourceConflictError, r as MultipartRequestOptions, s as TransportConfig, u as createTransport } from "./http-transport-DBgedLFQ.js";
3
+ import { A as UploadFileInput, B as FileInput, C as UpdateManyResult, D as FilesTransport, E as FilesApi, F as AttachToRecordInput, G as SchemaSource, H as IconName, I as AttachToRecordResult, J as defineSchemaSource, K as SchemaSourceConfig, L as DocumentsApi, M as UploadPublicFileInput, N as UploadedFile, O as PrivateUploadedFile, P as createFilesApi, R as DocumentsTransport, S as UpdateManyError, T as CamelCase, U as ObjectBuilderLike, V as UploadTimeoutOption, W as ResolvedSchemaSource, X as resolveSchemaSource, Y as hashSchemaSource, Z as sourceIdFromPackageName, _ as RecordsExportOptions, a as SchemaSourceSummary, b as UntypedRecordsQuery, c as syncSchemaSource, d as DeleteManyError, f as DeleteManyResult, g as RecordsAggregateOptions, h as RecordUpdate, i as createStandards, j as UploadPrivateFileInput, k as PublicUploadedFile, l as CreateManyError, m as RecordInput, n as Standards, o as SyncOptions, p as FetchResult, q as ViewInput, r as StandardsConfig, s as SyncResult, t as ObjectsOf, u as CreateManyResult, v as RecordsQuery, w as createRecordsQuery, x as UpdateManyEntry, y as UntypedBuilder, z as createDocumentsApi } from "./create-standards-3ODOXxRV.js";
4
+ import { encodePathSegment } from "@standards/schema/api";
5
+ import { Attribute, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, NotFoundError, ObjectDefinition, ObjectDefinition as ObjectDefinition$1, RecordAccessRole, RecordAudience, RecordMetadata, SCHEMA_SOURCE_ID_PATTERN, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, assertSchemaSourceId, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
6
+ //#region src/records/revive.d.ts
7
+ /**
8
+ * JSON delivers dates as ISO strings; the client knows the definition, so it
9
+ * revives system timestamps and every `date` attribute so `ExtractRecord` tells
10
+ * the truth on the wire. Nothing else is transformed.
11
+ */
12
+ export declare function reviveRecord<T extends Record<string, unknown>>(definition: ObjectDefinition$1 | null, raw: T): T;
13
+ //#endregion
14
+ //#region src/path.d.ts
15
+ /**
16
+ * Every caller-supplied path segment is percent-encoded: `objectName` and `id`
17
+ * come from the application, and an id such as `../../schema/sources/x` must
18
+ * never leave `/records/<object>/`.
19
+ */
20
+ export declare function recordsPath(objectName: string, ...segments: string[]): string;
21
+ //#endregion
22
+ export { type AttachToRecordInput, type AttachToRecordResult, type Attribute, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, type DocumentsApi, type DocumentsTransport, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FileInput, type FilesApi, type FilesTransport, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type IconName, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type PrivateUploadedFile, type PublicUploadedFile, type RecordAccessRole, type RecordAudience, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type ResolvedSchemaSource, SCHEMA_SOURCE_ID_PATTERN, SchemaError, SchemaErrorCode, type SchemaSource, type SchemaSourceConfig, SchemaSourceConflictError, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SchemaSourceSummary, SchemaSourceValidationError, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, StandardsRequestError, type SyncOptions, type SyncResult, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UploadFileInput, type UploadPrivateFileInput, type UploadPublicFileInput, type UploadTimeoutOption, type UploadedFile, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewInput, type ViewerAccess, assertSchemaSourceId, canonicalStringify, checkbox, content, createDocumentsApi, createFilesApi, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, defineSchemaSource, detailView, document, encodePathSegment, formula, group, hashSchemaSource, listView, location, multiselect, now, number, object, phone, query, relation, resolveSchemaSource, richtext, rollup, select, sourceIdFromPackageName, status, syncSchemaSource, text, today, user };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
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-DHbErYa4.js"),t=require("./create-standards-DVK0prD0.js");let n=require("@standards/schema/api"),r=require("@standards/schema");Object.defineProperty(exports,"DuplicateError",{enumerable:!0,get:function(){return r.DuplicateError}}),Object.defineProperty(exports,"ForbiddenError",{enumerable:!0,get:function(){return r.ForbiddenError}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get:function(){return r.NotFoundError}}),Object.defineProperty(exports,"SCHEMA_SOURCE_ID_PATTERN",{enumerable:!0,get:function(){return r.SCHEMA_SOURCE_ID_PATTERN}}),Object.defineProperty(exports,"SchemaError",{enumerable:!0,get:function(){return r.SchemaError}}),Object.defineProperty(exports,"SchemaErrorCode",{enumerable:!0,get:function(){return r.SchemaErrorCode}}),exports.SchemaSourceConflictError=e.f,exports.SchemaSourceValidationError=e.p,exports.StandardsAuthError=e.m,exports.StandardsConfigurationError=e.h,exports.StandardsRequestError=e.g,Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return r.ValidationError}}),Object.defineProperty(exports,"assertSchemaSourceId",{enumerable:!0,get:function(){return r.assertSchemaSourceId}}),Object.defineProperty(exports,"canonicalStringify",{enumerable:!0,get:function(){return r.canonicalStringify}}),Object.defineProperty(exports,"checkbox",{enumerable:!0,get:function(){return r.checkbox}}),Object.defineProperty(exports,"content",{enumerable:!0,get:function(){return r.content}}),exports.createDocumentsApi=t.l,exports.createFilesApi=t.c,exports.createRecordsQuery=t.i,exports.createStandards=t.n,exports.createTransport=e.n,Object.defineProperty(exports,"currency",{enumerable:!0,get:function(){return r.currency}}),Object.defineProperty(exports,"currentActor",{enumerable:!0,get:function(){return r.currentActor}}),Object.defineProperty(exports,"date",{enumerable:!0,get:function(){return r.date}}),exports.defineSchemaSource=t.u,Object.defineProperty(exports,"detailView",{enumerable:!0,get:function(){return r.detailView}}),Object.defineProperty(exports,"document",{enumerable:!0,get:function(){return r.document}}),Object.defineProperty(exports,"encodePathSegment",{enumerable:!0,get:function(){return n.encodePathSegment}}),Object.defineProperty(exports,"formula",{enumerable:!0,get:function(){return r.formula}}),Object.defineProperty(exports,"group",{enumerable:!0,get:function(){return r.group}}),exports.hashSchemaSource=t.d,Object.defineProperty(exports,"listView",{enumerable:!0,get:function(){return r.listView}}),Object.defineProperty(exports,"location",{enumerable:!0,get:function(){return r.location}}),Object.defineProperty(exports,"multiselect",{enumerable:!0,get:function(){return r.multiselect}}),Object.defineProperty(exports,"now",{enumerable:!0,get:function(){return r.now}}),Object.defineProperty(exports,"number",{enumerable:!0,get:function(){return r.number}}),Object.defineProperty(exports,"object",{enumerable:!0,get:function(){return r.object}}),Object.defineProperty(exports,"phone",{enumerable:!0,get:function(){return r.phone}}),Object.defineProperty(exports,"query",{enumerable:!0,get:function(){return r.query}}),exports.recordsPath=e.a,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return r.relation}}),exports.resolveSchemaSource=t.f,exports.reviveRecord=t.o,Object.defineProperty(exports,"richtext",{enumerable:!0,get:function(){return r.richtext}}),Object.defineProperty(exports,"rollup",{enumerable:!0,get:function(){return r.rollup}}),Object.defineProperty(exports,"select",{enumerable:!0,get:function(){return r.select}}),exports.sourceIdFromPackageName=t.p,Object.defineProperty(exports,"status",{enumerable:!0,get:function(){return r.status}}),exports.syncSchemaSource=t.r,Object.defineProperty(exports,"text",{enumerable:!0,get:function(){return r.text}}),Object.defineProperty(exports,"today",{enumerable:!0,get:function(){return r.today}}),Object.defineProperty(exports,"user",{enumerable:!0,get:function(){return r.user}});
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
+ import{a as e,f as t,g as n,h as r,m as i,n as a,p as o}from"./http-transport-17TmxnFl.mjs";import{c as s,d as c,f as l,i as u,l as d,n as f,o as p,p as m,r as h,u as g}from"./create-standards-p0dGJXSu.mjs";import{DuplicateError as _,ForbiddenError as v,NotFoundError as y,SCHEMA_SOURCE_ID_PATTERN as b,SchemaError as x,SchemaErrorCode as S,ValidationError as C,assertSchemaSourceId as w,canonicalStringify as T,checkbox as E,content as D,currency as O,currentActor as k,date as A,detailView as j,document as M,formula as N,group as P,listView as F,location as I,multiselect as L,now as R,number as z,object as B,phone as V,query as H,relation as U,richtext as W,rollup as G,select as K,status as q,text as J,today as Y,user as X}from"@standards/schema";import{encodePathSegment as Z}from"@standards/schema/api";export{_ as DuplicateError,v as ForbiddenError,y as NotFoundError,b as SCHEMA_SOURCE_ID_PATTERN,x as SchemaError,S as SchemaErrorCode,t as SchemaSourceConflictError,o as SchemaSourceValidationError,i as StandardsAuthError,r as StandardsConfigurationError,n as StandardsRequestError,C as ValidationError,w as assertSchemaSourceId,T as canonicalStringify,E as checkbox,D as content,d as createDocumentsApi,s as createFilesApi,u as createRecordsQuery,f as createStandards,a as createTransport,O as currency,k as currentActor,A as date,g as defineSchemaSource,j as detailView,M as document,Z as encodePathSegment,N as formula,P as group,c as hashSchemaSource,F as listView,I as location,L as multiselect,R as now,z as number,B as object,V as phone,H as query,e as recordsPath,U as relation,l as resolveSchemaSource,p as reviveRecord,W as richtext,G as rollup,K as select,m as sourceIdFromPackageName,q as status,h as syncSchemaSource,J as text,Y as today,X as user};
@@ -0,0 +1,79 @@
1
+
2
+ import "./http-transport-DBgedLFQ.mjs";
3
+ import { G as SchemaSource, U as ObjectBuilderLike$1, n as Standards, t as ObjectsOf } from "./create-standards-Cl_Lxvy3.mjs";
4
+ import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectDefinition } from "@standards/schema";
5
+ //#region src/testing/record-filters.d.ts
6
+ /**
7
+ * A filter rule the in-memory workspace does not serve. The server answers
8
+ * every operator it knows; a test double that matched an unknown one as
9
+ * "nothing" or "everything" would turn a missing feature into a passing test.
10
+ */
11
+ export declare class UnsupportedFilterOperatorError extends Error {
12
+ readonly operator: string;
13
+ constructor(operator: string, attribute: string);
14
+ }
15
+ //#endregion
16
+ //#region src/testing/in-memory-api.d.ts
17
+ /** What the next request fails with (`failNextRequestWith`). */
18
+ interface InjectedFailure {
19
+ message?: string;
20
+ code?: string;
21
+ }
22
+ //#endregion
23
+ //#region src/testing/index.d.ts
24
+ type NameOf<B> = B extends {
25
+ _types: {
26
+ name: infer N extends string;
27
+ };
28
+ } ? N : never;
29
+ /** The object names a schema declares — what `seed` and `records` take. */
30
+ export type ObjectNameOf<TObjects extends readonly ObjectBuilderLike$1[]> = NameOf<TObjects[number]>;
31
+ type BuilderNamed<TObjects extends readonly ObjectBuilderLike$1[], TName> = Extract<TObjects[number], {
32
+ _types: {
33
+ name: TName;
34
+ };
35
+ }>;
36
+ type PinnedKeys = "id" | "createdAt" | "updatedAt";
37
+ /**
38
+ * A record as a test seeds it: what `create` takes, plus the id and
39
+ * timestamps a test may pin — which `create` itself never accepts.
40
+ */
41
+ export type TestSeed<TBuilder> = Omit<ExtractRecordInputStrict<TBuilder>, PinnedKeys> & {
42
+ [key: string]: unknown;
43
+ } & {
44
+ id?: string;
45
+ createdAt?: Date | string;
46
+ updatedAt?: Date | string;
47
+ };
48
+ export interface TestStandards<TObjects extends readonly ObjectBuilderLike$1[]> {
49
+ /** The real client over the in-memory workspace: pass it wherever the app takes `createStandards`'s. */
50
+ db: Standards & ObjectsOf<TObjects>;
51
+ /**
52
+ * Store records directly, without a request; ids and timestamps are filled
53
+ * in unless given. Keyed by the object's name, as `from()` is.
54
+ */
55
+ seed<TName extends ObjectNameOf<TObjects>>(objectName: TName, records: readonly TestSeed<BuilderNamed<TObjects, TName>>[]): ExtractRecord<BuilderNamed<TObjects, TName>>[];
56
+ /** What the workspace holds for an object, in creation order, as `get` would answer it. */
57
+ records<TName extends ObjectNameOf<TObjects>>(objectName: TName): ExtractRecord<BuilderNamed<TObjects, TName>>[];
58
+ /** Fail the next request — any route — with this status; `401`/`403` raise `StandardsAuthError`. */
59
+ failNextRequestWith(status: number, failure?: InjectedFailure): void;
60
+ }
61
+ /**
62
+ * An in-memory Standards workspace for tests, typed by the app's schema.
63
+ *
64
+ * `db` is the real client — the same query layer, revival and bulk chunking an
65
+ * app ships — over a transport that answers like the records API: pages of 20
66
+ * by default and 1000 at most, newest first, the server's filter operators and
67
+ * sort order. An operator it does not serve throws
68
+ * `UnsupportedFilterOperatorError`; any other route answers `501`.
69
+ *
70
+ * @example
71
+ * const { db, seed } = createTestStandards({ schema });
72
+ * seed("tickets", [{ title: "Login fails" }]);
73
+ * await db.tickets.contains("title", "login").fetch();
74
+ */
75
+ export declare function createTestStandards<const TObjects extends readonly ObjectBuilderLike$1[]>(config: {
76
+ schema: SchemaSource<TObjects>;
77
+ }): TestStandards<TObjects>;
78
+ //#endregion
79
+ export type { InjectedFailure };
@@ -0,0 +1,79 @@
1
+
2
+ import "./http-transport-DBgedLFQ.js";
3
+ import { G as SchemaSource, U as ObjectBuilderLike$1, n as Standards, t as ObjectsOf } from "./create-standards-3ODOXxRV.js";
4
+ import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectDefinition } from "@standards/schema";
5
+ //#region src/testing/record-filters.d.ts
6
+ /**
7
+ * A filter rule the in-memory workspace does not serve. The server answers
8
+ * every operator it knows; a test double that matched an unknown one as
9
+ * "nothing" or "everything" would turn a missing feature into a passing test.
10
+ */
11
+ export declare class UnsupportedFilterOperatorError extends Error {
12
+ readonly operator: string;
13
+ constructor(operator: string, attribute: string);
14
+ }
15
+ //#endregion
16
+ //#region src/testing/in-memory-api.d.ts
17
+ /** What the next request fails with (`failNextRequestWith`). */
18
+ interface InjectedFailure {
19
+ message?: string;
20
+ code?: string;
21
+ }
22
+ //#endregion
23
+ //#region src/testing/index.d.ts
24
+ type NameOf<B> = B extends {
25
+ _types: {
26
+ name: infer N extends string;
27
+ };
28
+ } ? N : never;
29
+ /** The object names a schema declares — what `seed` and `records` take. */
30
+ export type ObjectNameOf<TObjects extends readonly ObjectBuilderLike$1[]> = NameOf<TObjects[number]>;
31
+ type BuilderNamed<TObjects extends readonly ObjectBuilderLike$1[], TName> = Extract<TObjects[number], {
32
+ _types: {
33
+ name: TName;
34
+ };
35
+ }>;
36
+ type PinnedKeys = "id" | "createdAt" | "updatedAt";
37
+ /**
38
+ * A record as a test seeds it: what `create` takes, plus the id and
39
+ * timestamps a test may pin — which `create` itself never accepts.
40
+ */
41
+ export type TestSeed<TBuilder> = Omit<ExtractRecordInputStrict<TBuilder>, PinnedKeys> & {
42
+ [key: string]: unknown;
43
+ } & {
44
+ id?: string;
45
+ createdAt?: Date | string;
46
+ updatedAt?: Date | string;
47
+ };
48
+ export interface TestStandards<TObjects extends readonly ObjectBuilderLike$1[]> {
49
+ /** The real client over the in-memory workspace: pass it wherever the app takes `createStandards`'s. */
50
+ db: Standards & ObjectsOf<TObjects>;
51
+ /**
52
+ * Store records directly, without a request; ids and timestamps are filled
53
+ * in unless given. Keyed by the object's name, as `from()` is.
54
+ */
55
+ seed<TName extends ObjectNameOf<TObjects>>(objectName: TName, records: readonly TestSeed<BuilderNamed<TObjects, TName>>[]): ExtractRecord<BuilderNamed<TObjects, TName>>[];
56
+ /** What the workspace holds for an object, in creation order, as `get` would answer it. */
57
+ records<TName extends ObjectNameOf<TObjects>>(objectName: TName): ExtractRecord<BuilderNamed<TObjects, TName>>[];
58
+ /** Fail the next request — any route — with this status; `401`/`403` raise `StandardsAuthError`. */
59
+ failNextRequestWith(status: number, failure?: InjectedFailure): void;
60
+ }
61
+ /**
62
+ * An in-memory Standards workspace for tests, typed by the app's schema.
63
+ *
64
+ * `db` is the real client — the same query layer, revival and bulk chunking an
65
+ * app ships — over a transport that answers like the records API: pages of 20
66
+ * by default and 1000 at most, newest first, the server's filter operators and
67
+ * sort order. An operator it does not serve throws
68
+ * `UnsupportedFilterOperatorError`; any other route answers `501`.
69
+ *
70
+ * @example
71
+ * const { db, seed } = createTestStandards({ schema });
72
+ * seed("tickets", [{ title: "Login fails" }]);
73
+ * await db.tickets.contains("title", "login").fetch();
74
+ */
75
+ export declare function createTestStandards<const TObjects extends readonly ObjectBuilderLike$1[]>(config: {
76
+ schema: SchemaSource<TObjects>;
77
+ }): TestStandards<TObjects>;
78
+ //#endregion
79
+ export type { InjectedFailure };
@@ -0,0 +1,2 @@
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-DHbErYa4.js"),t=require("./create-standards-DVK0prD0.js");let n=require("@standards/schema"),r=require("@standards/schema/api");var UnsupportedFilterOperatorError=class extends Error{constructor(e,t){super(`The in-memory test workspace does not serve the "${e}" operator (on "${t}"). Test it against a real workspace.`),this.name=`UnsupportedFilterOperatorError`,this.operator=e}};const i=new Set([`id`,`createdAt`,`updatedAt`]),a=new Set([`createdAt`,`updatedAt`]),o=new Set([`number`,`currency`]),s=new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/;function attributeValue(e,t){if(i.has(t))return e[t];let n=e.values[t];return typeof n==`object`&&n&&`value`in n&&!Array.isArray(n)?n.value:n}function isEmptyValue(e){return e==null||e===``||Array.isArray(e)&&e.length===0}function textOf(e){return e==null?null:e instanceof Date?e.toISOString():typeof e==`string`?e:JSON.stringify(e)}function members(e){return Array.isArray(e)?e.map(String):null}function dayOf(e){let t=textOf(e);if(t===null||!c.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}function nextDay(e){let t=new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),s=r!==void 0&&o.has(r),c=textOf(t.value)?.toLowerCase(),l=textOf(i)?.toLowerCase()??null;if((r===`date`||a.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,i,t.value,a.has(t.attribute));switch(t.operator){case`is`:return r===`checkbox`||r===void 0&&typeof t.value==`boolean`?t.value===!0?i===!0:i!==!0:textOf(i)!==null&&textOf(i)===textOf(t.value);case`is_not`:return textOf(i)===null||textOf(i)!==textOf(t.value);case`contains`:return Array.isArray(i)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>i.map(String).includes(e)):l!==null&&c!==void 0&&l.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return l!==null&&c!==void 0&&l.startsWith(c);case`ends_with`:return l!==null&&c!==void 0&&l.endsWith(c);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,s);return e===null?!1:t.operator===`greater_than`?e>0:t.operator===`greater_or_equal`?e>=0:t.operator===`less_than`?e<0:e<=0}case`is_empty`:return isEmptyValue(i);case`is_not_empty`:return!isEmptyValue(i);case`any_of`:{let e=members(t.value);return e===null||e.length===0||i==null?!1:Array.isArray(i)?i.some(t=>e.includes(String(t))):e.includes(textOf(i)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||i==null?!0:Array.isArray(i)?!i.some(t=>e.includes(String(t))):!e.includes(textOf(i)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const l=new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!l.has(n.operator)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);return i&&s.has(i.type)?(i.options??[]).find(e=>e.value===r)?.label??r:r}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute)?.type,a=sortKey(e,i.attribute,t),s=sortKey(r,i.attribute,t),c=textOf(a)===null,l=textOf(s)===null;if(c||l){if(c&&l)continue;return c?1:-1}let u=compare(a,s,n!==void 0&&o.has(n))??0;if(u!==0)return i.direction===`desc`?-u:u}return 0}}const u=`SCHEMA_RECORD_NOT_FOUND`,d=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,f=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getSystemAttributeList)()]}}function withoutSystemKeys(e){let t={...e};for(let e of f)delete t[e];return t}function boundOf(t,n,r){if(t==null)return r;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new e.g(400,`${n} must be a non-negative integer`);return t}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function errorFor(t,n,r){return t===401||t===403?new e.m(t,n,r):new e.g(t,n,r)}function asTheServerValidates(t){try{t()}catch(t){throw t instanceof n.ValidationError?new e.g(400,t.message,t.code):t}}function notServed(t,n){return new e.g(501,`The in-memory test workspace does not serve ${t} ${n}: only the records API is in memory.`)}function isoOf(e,t){return e===void 0?t:e instanceof Date?e.toISOString():new Date(e).toISOString()}function wire(e){return JSON.parse(JSON.stringify(e))}function createInMemoryApi(i){let a=new Map;for(let e of i.schema.builders){let n=t.a(e);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=new Set,c=null,l=0,f=1;function now(){return l=Math.max(Date.now(),l+1),new Date(l).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(t){let n=a.get(t),r=o.get(t);if(!(n&&r))throw new e.g(404,`Object "${t}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,n){let{records:r}=objectOf(e),{id:i,createdAt:a,updatedAt:o,...c}=n,l=now(),u={id:i??newId(),values:wire(t.s(c)),createdAt:isoOf(a,l),updatedAt:isoOf(o,isoOf(a,l)),visibility:`workspace`,ownedBy:null,metadata:{}};return r.push(u),s.add(u.id),u}function find(t,n){let r=objectOf(t).records.find(e=>e.id===n);if(!r)throw new e.g(404,readNotFound(n),u);return r}function requireWritable(t,n){if(!objectOf(t).records.some(e=>e.id===n))throw new e.g(404,writeNotFound(n),u)}function update(t,n,r){let i=objectOf(t).records.find(e=>e.id===n);if(!i)throw new e.g(404,writeNotFound(n),u);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(t,n){let{records:r}=objectOf(t),i=r.findIndex(e=>e.id===n);if(i===-1)throw new e.g(404,writeNotFound(n),u);r.splice(i,1)}function list(e,t,r){let{definition:i,records:a}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>(0,n.validateQualifiedRule)(structuredClone(e),{attributes:i.attributes}));assertServedOperators(t.filters,i);let o=Math.min(boundOf(t.limit,`limit`,20),1e3),s=boundOf(t.offset,`offset`,0);if(o===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let c=r?t.q:void 0,l=a.filter(e=>matchesFilters(e,t.filters,i)).filter(e=>c===void 0||matchesSearch(e,c)).sort(compareRecords(t.sorts,i)),u=l.slice(s,s+o);return{data:u,page:{hasMore:s+u.length<l.length,total:null,countMode:`none`}}}function bulk(t,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new e.g(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(t).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries()){if(!isObject(c)){i.push({index:s,error:`Record data must be an object`});continue}try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(t,withoutSystemKeys(c)))}catch(t){if(!(t instanceof e.g))throw t;i.push({index:s,error:t.message})}}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!isObject(c))throw new e.g(400,`Update data must be an object`,d);requireWritable(t,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(t,s,c))}catch(t){if(!(t instanceof e.g))throw t;i.push({id:s,error:t.message,code:t.code??d})}return{updated:r,errors:i}}let s=[],c=[];for(let e of a)try{remove(t,e),s.push(e)}catch{c.push({id:e,error:writeNotFound(e),code:u})}return{deleted:s,errors:c}}function route(t,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(a!==`records`||o===void 0||c.length>0)throw notServed(t,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=isObject(i)?i:{};if(t===`POST`&&u===void 0){let e=isObject(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(t===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(t===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(t,r);if(t===`GET`)return find(l,u);if(t===`PUT`||t===`PATCH`){if(Object.keys(d).length===0)throw new e.g(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(t===`DELETE`)return remove(l,u),null;throw notServed(t,r)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(c){let{status:e,failure:t}=c;throw c=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let p={call:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=(0,r.splitOperationInput)(e,t??{});throw notServed(e.method,n)}),get:e=>request(`GET`,e),post:(e,t)=>request(`POST`,e,t),patch:(e,t)=>request(`PATCH`,e,t),put:(e,t)=>request(`PUT`,e,t),delete:e=>request(`DELETE`,e),getText:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`GET`,e)}),postRaw:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)}),postMultipart:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)})};return{transport:p,get:p.get,post:p.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){c={status:e,failure:t}}}}function createTestStandards(e){let n=createInMemoryApi({schema:e.schema}),flatten=(e,r)=>t.o(n.definitionOf(e),JSON.parse(JSON.stringify(r)));return{db:t.t(n.transport,e.schema),seed:(e,t)=>n.seed(e,t).map(t=>flatten(e,t)),records:e=>n.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>n.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;