@standards/client 1.0.0-alpha.445 → 1.0.0-alpha.447
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-DQ0e_dZD.mjs +9 -0
- package/dist/{app-t-7y8Oio.d.mts → app-KQAbWX9h.d.mts} +57 -6
- package/dist/{app-t-7y8Oio.d.ts → app-KQAbWX9h.d.ts} +57 -6
- package/dist/app-oCr8yvTF.js +9 -0
- package/dist/app.d.mts +2 -2
- package/dist/app.d.ts +2 -2
- package/dist/app.js +1 -1
- package/dist/app.mjs +1 -1
- package/dist/{create-standards-DZ6stJDK.d.ts → create-standards-2cgqcAYC.d.ts} +6 -3
- package/dist/create-standards-CJY4Dt0X.js +4 -0
- package/dist/{create-standards-DPw1bxv6.d.mts → create-standards-DQ9jRm9v.d.mts} +6 -3
- package/dist/{create-standards-Dq4tC8T6.mjs → create-standards-Gw85x9Mb.mjs} +2 -2
- package/dist/http-transport-CijwtqPm.mjs +2 -0
- package/dist/http-transport-CkB0bQlR.js +2 -0
- package/dist/http.d.mts +5 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +2 -0
- package/dist/http.mjs +2 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/testing.d.mts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +13 -2
- package/dist/app-BUHCJ8SR.js +0 -9
- package/dist/app-Cer-0oL4.mjs +0 -9
- package/dist/create-standards-Drs4y84m.js +0 -4
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
import{_ as e,d as t,i as n}from"./http-transport-CijwtqPm.mjs";import{isPlainRecord as r}from"@standards/schema";import{appOperationGroups as i,decodeOperationOutput as a,isOperationRefused as o,operationGroup as s,pathParamNames as c,splitOperationInput as l}from"@standards/schema/api";const u=[1e3,2e3,5e3],d=/* @__PURE__ */ new Set([`turn.completed`,`turn.failed`,`turn.cancelled`]);function parseSseFrame(e){let t,n=`message`,r,i=[];for(let a of e.split(`
|
|
3
|
+
`)){let e=a.endsWith(`\r`)?a.slice(0,-1):a;if(e===``||e.startsWith(`:`))continue;let o=e.indexOf(`:`),s=o===-1?e:e.slice(0,o),c=o===-1?``:e.slice(o+1);c.startsWith(` `)&&(c=c.slice(1)),s===`id`?t=c:s===`event`?n=c:s===`data`?i.push(c):s===`retry`&&/^\d+$/.test(c)&&(r=Number(c))}return{id:t,event:n,data:i.join(`
|
|
4
|
+
`),retry:r}}function parseEvent(e){let t;try{t=JSON.parse(e.data)}catch{return}if(r(t)&&typeof t.type==`string`&&typeof t.seq==`number`&&Number.isSafeInteger(t.seq)&&t.seq>0&&(e.id===void 0||e.id===String(t.seq)))return t}function parseControl(e){let t;try{t=JSON.parse(e.data)}catch{return}if(!r(t))return;let n=t.control;return n===`up-to-date`||n===`lease-ended`||n===`inbox`?n:void 0}function isUnresolvableActor(e){return e.status===401&&e.code===`ACTOR_RESOLUTION_FAILED`}function isTerminalRefusal(e){return e.status===400||e.status===403||e.status===404||isUnresolvableActor(e)}function isCursorExpired(e){return e instanceof t&&e.status===410&&e.code===`AGENT_SESSION_STREAM_CURSOR_EXPIRED`}function openAgentStream(e){let n=!1,r,i,a,o=1e3,s=0,c,l=e.subscribeAuthChanges?.(()=>{n||(s+=1,c?.(),c=void 0)});function endWait(){i!==void 0&&clearTimeout(i),i=void 0,a?.(),a=void 0}function close(){n||(n=!0,r?.abort(),endWait(),c?.(),c=void 0,l?.())}function waitForAuthChange(e){return n||s!==e?Promise.resolve():new Promise(e=>{c=e})}function sleep(e){return new Promise(t=>{a=t,i=setTimeout(endWait,e)})}function handleFrame(t){let n=parseSseFrame(t);if(n.retry!==void 0&&(o=n.retry),n.data===``)return`skipped`;if(n.event===`control`){let t=parseControl(n);return t&&e.onControl(t),t===`lease-ended`?`lease-ended`:`skipped`}if(n.event!==`event`)return`skipped`;let r=parseEvent(n);return r?r.seq<=e.cursor()?`skipped`:(e.onEvent(r),`delivered`):`malformed`}async function consume(e,t){let r=e.body;if(r===null)return{delivered:!1,end:`failed`};let i=r.getReader(),a=new TextDecoder,o=``,s=!1;try{for(;;){let{done:e,value:r}=await i.read();if(n||e)return{delivered:s,end:`clean`};o+=a.decode(r,{stream:!0}).replace(/\r\n/g,`
|
|
5
|
+
`);let c=o.indexOf(`
|
|
6
|
+
|
|
7
|
+
`);for(;c!==-1;){let e=o.slice(0,c);o=o.slice(c+2);let r=handleFrame(e);if(r===`delivered`&&(s=!0),n)return{delivered:s,end:`clean`};if(r===`malformed`)return t.abort(),{delivered:s,end:`malformed`};if(r===`lease-ended`)return{delivered:s,end:`lease-ended`};c=o.indexOf(`
|
|
8
|
+
|
|
9
|
+
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(n,r,i){if(isCursorExpired(n))try{return await e.onExpired(),i?`back-off`:`reopen`}catch{return`back-off`}return n instanceof t?isTerminalRefusal(n)?(close(),e.onStatus(`error`,n),`stop`):n.status===401?(e.onStatus(`auth-blocked`,n),await waitForAuthChange(r),`reopen`):`back-off`:`back-off`}let d,f=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(f=d===t?f+1:1,d=t,f<3))return!1;d=void 0,f=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?o:u[Math.min(t,u.length-1)]??5e3}async function run(){let t=!0,i=0,a=!1;for(;!n;){e.onStatus(t?`connecting`:`reconnecting`),t=!1;let o=new AbortController;r=o;let c=s,l=`failed`;try{let t=await e.open(e.sessionId,e.cursor(),o.signal,()=>{c=s});if(n)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(t,o);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(n)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(n)return;let t=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=t,r===`stop`||n)return;if(r===`reopen`)continue}if(n)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}const f=[1e3,2e3,4e3],p=[0,1e3,3e3,5e3,1e4,2e4];async function upload(e,t){let n=[];for(let[r,i]of t.files.entries())n.push(await uploadOne(e,t,i,r));return n}async function uploadAll(e,t){let n=await upload(e,t),r=n.find(e=>!e.ok);if(r===void 0||r.ok)return n.flatMap(e=>e.ok?[e.attached===void 0?{file:e.file}:{file:e.file,attached:e.attached}]:[]);for(let t of n)if(t.ok)try{await e.files.delete({id:t.file.id})}catch{}throw r.error}async function uploadOne(e,t,n,r){let{signal:i}=t;if(i?.aborted)return{ok:!1,error:i.reason};let a;try{a=await prepare(e,t,n)}catch(e){return{ok:!1,error:e}}try{t.onStatus?.(r,`sending`),await send(a.target,n,{signal:i,onProgress:e=>t.onProgress?.(r,e),onStatus:e=>t.onStatus?.(r,e)})}catch(t){return await abandon(e,a.uploadId),{ok:!1,error:i?.aborted?i.reason:t}}t.onStatus?.(r,`finalizing`);try{let{file:t,attached:n}=await complete(e,a.uploadId,i);return n===void 0?{ok:!0,file:t}:{ok:!0,file:t,attached:n}}catch(t){return i?.aborted?(await abandon(e,a.uploadId),{ok:!1,error:i.reason}):{ok:!1,error:t}}}async function prepare(e,t,n){let r={idempotencyKey:crypto.randomUUID(),fileName:n.name,mimeType:n.type||`application/octet-stream`,size:n.size,...t.folderPath===void 0?{}:{folderPath:t.folderPath},...t.public===void 0?{}:{public:t.public},protocol:t.protocol??`tus`,...t.attachTo===void 0?{}:{attachTo:t.attachTo}};return await e.files.prepareUpload(r,{signal:t.signal,maxRetries:2})}async function complete(t,n,r){let i=0;for(let a=0;;a+=1)try{return await t.files.completeUpload({uploadId:n},{signal:r})}catch(t){let n=e(t)===`UPLOAD_IN_PROGRESS`||unreached(t),o=f[a]??5e3;if(!n||r?.aborted||i+o>36e4)throw t;await sleep(o,r),i+=o}}async function abandon(e,t){try{await e.files.abortUpload({uploadId:t})}catch{}}function send(e,t,n){return e.protocol===`tus`?sendTus(e,t,n):sendPut(e,t,n)}async function sendPut(e,n,r){let i=await fetch(e.url,{method:`PUT`,headers:e.headers,body:n,...r.signal===void 0?{}:{signal:r.signal}});if(!i.ok)throw new t(i.status,`Storage refused the upload (HTTP ${i.status})`);r.onProgress({loaded:n.size,total:n.size})}async function sendTus(e,t,n){let{signal:r}=n;r?.throwIfAborted();let i=await import(`tus-js-client`),a=i.defaultOptions.onShouldRetry;return new Promise((o,s)=>{let c=!1,l=new i.Upload(t,{endpoint:e.url,headers:e.headers,metadata:e.metadata??{},...e.chunkSize===void 0?{}:{chunkSize:e.chunkSize},retryDelays:p,storeFingerprintForResuming:!1,fileReader:m,httpStack:onOrigin(new i.DefaultHttpStack({}),e.url),onProgress:(e,t)=>{c&&(c=!1,n.onStatus(`sending`)),n.onProgress({loaded:e,total:t})},onShouldRetry:(e,t,r)=>{let i=a?.(e,t,r)??!1;return i&&!c&&(c=!0,n.onStatus(`interrupted`)),i},onSuccess:()=>{r?.removeEventListener(`abort`,stop),o()},onError:e=>{r?.removeEventListener(`abort`,stop),s(e)}});function stop(){l.abort(!1).catch(()=>{}),s(r?.reason)}r?.addEventListener(`abort`,stop,{once:!0}),l.start()})}function onOrigin(e,t){let{origin:n}=new URL(t);return{createRequest(r,i){let{pathname:a,search:o}=new URL(i,t);return e.createRequest(r,`${n}${a}${o}`)},getName:()=>e.getName()}}const m={openFile:e=>Promise.resolve({size:e.size,slice:async(t,n)=>{let r=new Uint8Array(await e.slice(t,n).arrayBuffer());return{value:Object.assign(r,{size:r.length}),done:n>=e.size}},close:()=>{}})};function unreached(e){return e instanceof t&&e.status===0}function sleep(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,cancel),n()},e);function cancel(){clearTimeout(i),r(t?.reason)}t?.addEventListener(`abort`,cancel,{once:!0})})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,t){let{query:n,body:r,headers:i}=l(e,t),a=Object.fromEntries(c(e.path).map(e=>[e,String(t[e])])),o=Object.fromEntries(Object.entries(i??{}).map(([e,t])=>[e.toLowerCase(),t])),s={params:a,query:asStrings(n),headers:o};if(e.upload===void 0)return{...s,body:r===void 0?void 0:JSON.parse(JSON.stringify(r))};let{[e.upload.field]:u,...d}=r??{},f=u==null?[]:Array.isArray(u)?u:[u];return{...s,body:asStrings(d),uploads:await Promise.all(f.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){return transportActingAs(e,void 0)}function transportActingAs(e,t){async function call(r,i,s={}){if(s.signal?.throwIfAborted(),r.response===`events`)throw Error(`Operation ${r.name} streams over HTTP only`);let c=await wireRequest(r,i??{}),l;try{l=await e.execute(r,c,t)}catch(e){throw o(e)?n(e.status,JSON.stringify(e.body)):e}if(r.response===`bytes`)return downloaded(l);let u=l===void 0?null:JSON.parse(JSON.stringify(l));return a(r,u)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`)),withCaller:t=>transportActingAs(e,t)}}function createAppClient(e){let t={},n=Object.values(i);for(let r of n.flatMap(e=>Object.values(e))){let n=s(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{d as a,uploadAll as i,createInProcessTransport as n,openAgentStream as o,upload as r,createAppClient as t};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange } from "@standards/schema";
|
|
3
|
-
import { Operation, OperationCaller, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
2
|
+
import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange, File } from "@standards/schema";
|
|
3
|
+
import { AttachedRecordDocument, Operation, OperationCaller, OperationHost, OperationInput, OperationResult, UploadAttachTo, appOperationGroups } from "@standards/schema/api";
|
|
4
|
+
import { DeferredOperation, Operation as Operation$1, OperationInput as OperationInput$1, OperationResult as OperationResult$1 } from "@standards/schema/api/http";
|
|
4
5
|
/**
|
|
5
6
|
* Any non-2xx answer from a Standards API. `code` is the server's `SchemaErrorCode` when it sent
|
|
6
7
|
* one; `details` is the body's `details` field, kept as the server sent it.
|
|
@@ -117,14 +118,14 @@ interface HttpTransport {
|
|
|
117
118
|
* An `upload` operation sends its body as multipart, its files under the
|
|
118
119
|
* operation's field; a `response: "bytes"` one resolves to a `DownloadedFile`.
|
|
119
120
|
*/
|
|
120
|
-
call<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationCallOptions): Promise<OperationResult<O>>;
|
|
121
|
+
call<O extends Operation$1>(op: O, input: OperationInput$1<O>, options?: OperationCallOptions): Promise<OperationResult$1<O>>;
|
|
121
122
|
/**
|
|
122
123
|
* Opens an `"events"` operation and resolves to its `Response` once the
|
|
123
124
|
* headers are in, for the caller to read: no deadline, no retry, one
|
|
124
125
|
* refresh on a 401 (never on `MFA_REQUIRED`, which a token cannot satisfy).
|
|
125
126
|
* Any refusal is read and thrown as the typed error before a byte streams.
|
|
126
127
|
*/
|
|
127
|
-
stream<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationStreamOptions): Promise<Response>;
|
|
128
|
+
stream<O extends Operation$1>(op: O, input: OperationInput$1<O>, options?: OperationStreamOptions): Promise<Response>;
|
|
128
129
|
get<T = unknown>(path: string, params?: Record<string, unknown>): Promise<T>;
|
|
129
130
|
post<T = unknown>(path: string, body?: unknown): Promise<T>;
|
|
130
131
|
patch<T = unknown>(path: string, body?: unknown): Promise<T>;
|
|
@@ -140,6 +141,10 @@ interface HttpTransport {
|
|
|
140
141
|
}
|
|
141
142
|
/** The verbs the records, files and schema layers use; `createTransport` returns their superset. */
|
|
142
143
|
/** What `createAppClient` calls: every operation, and a stream for an `"events"` one. */
|
|
144
|
+
/** HTTP dispatch over projected wire fields, with canonical decoding after success. */
|
|
145
|
+
interface DeferredHttpTransport extends HttpTransport {
|
|
146
|
+
callDeferred<O extends Operation$1>(operation: DeferredOperation<O>, input: OperationInput$1<O>, options?: OperationCallOptions & OperationStreamOptions): Promise<OperationResult$1<O>>;
|
|
147
|
+
}
|
|
143
148
|
type OperationTransport = Pick<HttpTransport, "call" | "stream">;
|
|
144
149
|
type Transport = Pick<HttpTransport, "call" | "get" | "post" | "patch" | "put" | "delete" | "getText" | "postRaw" | "postMultipart">;
|
|
145
150
|
interface TransportConfig {
|
|
@@ -155,7 +160,7 @@ interface TransportConfig {
|
|
|
155
160
|
declare function refusalOf(status: number, text: string): StandardsRequestError;
|
|
156
161
|
/** Reads a refused `Response` into the error the transport itself throws. */
|
|
157
162
|
declare function readRefusal(response: Response): Promise<StandardsRequestError>;
|
|
158
|
-
declare function createHttpTransport(config: HttpTransportConfig):
|
|
163
|
+
declare function createHttpTransport(config: HttpTransportConfig): DeferredHttpTransport;
|
|
159
164
|
/**
|
|
160
165
|
* The API-key transport the public SDK documents: `createHttpTransport` with
|
|
161
166
|
* the bearer key and tenant header, one attempt, no refresh.
|
|
@@ -256,6 +261,52 @@ declare function openAgentStream(options: OpenAgentStreamOptions): AgentStreamHa
|
|
|
256
261
|
* callers fall back to a client-side name.
|
|
257
262
|
*/
|
|
258
263
|
declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
|
|
264
|
+
/** The record an uploaded file joins once stored, and how. */
|
|
265
|
+
type AttachTarget = UploadAttachTo;
|
|
266
|
+
interface UploadInput {
|
|
267
|
+
/** Each is sent as it is: a browser `File`, or a Node `Blob` with a name (`fs.openAsBlob`). */
|
|
268
|
+
files: readonly (Blob & {
|
|
269
|
+
readonly name: string;
|
|
270
|
+
})[];
|
|
271
|
+
folderPath?: string;
|
|
272
|
+
public?: boolean;
|
|
273
|
+
attachTo?: AttachTarget;
|
|
274
|
+
/** `tus` (default) resumes after a lost connection; `put` sends each file in one request. */
|
|
275
|
+
protocol?: "tus" | "put";
|
|
276
|
+
onProgress?: (fileIndex: number, progress: UploadProgress) => void;
|
|
277
|
+
/** `interrupted`: the connection dropped and the transfer is retrying; `finalizing`: bytes sent, the API is checking them. */
|
|
278
|
+
onStatus?: (fileIndex: number, status: "sending" | "interrupted" | "finalizing") => void;
|
|
279
|
+
/** Stops the transfer under way and every file not started; each prepared, uncompleted upload is aborted. */
|
|
280
|
+
signal?: AbortSignal;
|
|
281
|
+
}
|
|
282
|
+
type UploadResult = {
|
|
283
|
+
ok: true;
|
|
284
|
+
file: File;
|
|
285
|
+
attached?: AttachedRecordDocument;
|
|
286
|
+
} | {
|
|
287
|
+
ok: false;
|
|
288
|
+
error: unknown;
|
|
289
|
+
};
|
|
290
|
+
/** A file `uploadAll` stored, and the document it joined when the upload named `attachTo`. */
|
|
291
|
+
interface UploadedFile {
|
|
292
|
+
file: File;
|
|
293
|
+
attached?: AttachedRecordDocument;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Upload files straight to storage: for each, in sequence, prepare (the API
|
|
297
|
+
* judges it and signs a target), send the bytes to the target, then complete
|
|
298
|
+
* (the API checks and records them). The one implementation behind every
|
|
299
|
+
* uploader. Answers one result per file, in input order; a refusal is that
|
|
300
|
+
* file's result and the next file still goes.
|
|
301
|
+
*/
|
|
302
|
+
declare function upload(client: AppClient, input: UploadInput): Promise<UploadResult[]>;
|
|
303
|
+
/**
|
|
304
|
+
* `upload` for a batch the caller presents as one action: every file is
|
|
305
|
+
* stored, or none stays. When one is refused, the files of the batch already
|
|
306
|
+
* stored are deleted (best effort: one attached to a record stays in its
|
|
307
|
+
* pack) and the first refusal is thrown.
|
|
308
|
+
*/
|
|
309
|
+
declare function uploadAll(client: AppClient, input: UploadInput): Promise<UploadedFile[]>;
|
|
259
310
|
/**
|
|
260
311
|
* The in-process transport: an {@link OperationTransport} that can also be
|
|
261
312
|
* bound to who acts, which a transport over HTTP cannot (its identity is the
|
|
@@ -291,4 +342,4 @@ type OperationCall<O extends Operation> = (...args: undefined extends OperationI
|
|
|
291
342
|
type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
|
|
292
343
|
/** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
|
|
293
344
|
declare function createAppClient(transport: OperationTransport): AppClient;
|
|
294
|
-
export {
|
|
345
|
+
export { OperationStreamOptions as A, BundleValidationError as B, schemaApiErrorCode as C, HttpTransportConfig as D, HttpTransport as E, createHttpTransport as F, StandardsConfigurationError as H, createTransport as I, readRefusal as L, Transport as M, TransportConfig as N, MultipartRequestOptions as O, UploadProgress as P, refusalOf as R, isViewNotFound as S, DeferredHttpTransport as T, StandardsRequestError as U, StandardsAuthError as V, openAgentStream as _, AttachTarget as a, isObjectNotFound as b, UploadedFile as c, parseContentDispositionFilename as d, AgentStreamControl as f, TURN_END_TYPES as g, OpenAgentStreamOptions as h, createInProcessTransport as i, OperationTransport as j, OperationCallOptions as k, upload as l, AgentStreamStatus as m, createAppClient as n, UploadInput as o, AgentStreamHandle as p, InProcessTransport as r, UploadResult as s, AppClient as t, uploadAll as u, draftConflictChanges as v, schemaApiErrorDetails as w, isPermanentRefusal as x, isDraftRevisionConflict as y, BundleConflictError as z };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange } from "@standards/schema";
|
|
3
|
-
import { Operation, OperationCaller, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
2
|
+
import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange, File } from "@standards/schema";
|
|
3
|
+
import { AttachedRecordDocument, Operation, OperationCaller, OperationHost, OperationInput, OperationResult, UploadAttachTo, appOperationGroups } from "@standards/schema/api";
|
|
4
|
+
import { DeferredOperation, Operation as Operation$1, OperationInput as OperationInput$1, OperationResult as OperationResult$1 } from "@standards/schema/api/http";
|
|
4
5
|
/**
|
|
5
6
|
* Any non-2xx answer from a Standards API. `code` is the server's `SchemaErrorCode` when it sent
|
|
6
7
|
* one; `details` is the body's `details` field, kept as the server sent it.
|
|
@@ -117,14 +118,14 @@ interface HttpTransport {
|
|
|
117
118
|
* An `upload` operation sends its body as multipart, its files under the
|
|
118
119
|
* operation's field; a `response: "bytes"` one resolves to a `DownloadedFile`.
|
|
119
120
|
*/
|
|
120
|
-
call<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationCallOptions): Promise<OperationResult<O>>;
|
|
121
|
+
call<O extends Operation$1>(op: O, input: OperationInput$1<O>, options?: OperationCallOptions): Promise<OperationResult$1<O>>;
|
|
121
122
|
/**
|
|
122
123
|
* Opens an `"events"` operation and resolves to its `Response` once the
|
|
123
124
|
* headers are in, for the caller to read: no deadline, no retry, one
|
|
124
125
|
* refresh on a 401 (never on `MFA_REQUIRED`, which a token cannot satisfy).
|
|
125
126
|
* Any refusal is read and thrown as the typed error before a byte streams.
|
|
126
127
|
*/
|
|
127
|
-
stream<O extends Operation>(op: O, input: OperationInput<O>, options?: OperationStreamOptions): Promise<Response>;
|
|
128
|
+
stream<O extends Operation$1>(op: O, input: OperationInput$1<O>, options?: OperationStreamOptions): Promise<Response>;
|
|
128
129
|
get<T = unknown>(path: string, params?: Record<string, unknown>): Promise<T>;
|
|
129
130
|
post<T = unknown>(path: string, body?: unknown): Promise<T>;
|
|
130
131
|
patch<T = unknown>(path: string, body?: unknown): Promise<T>;
|
|
@@ -140,6 +141,10 @@ interface HttpTransport {
|
|
|
140
141
|
}
|
|
141
142
|
/** The verbs the records, files and schema layers use; `createTransport` returns their superset. */
|
|
142
143
|
/** What `createAppClient` calls: every operation, and a stream for an `"events"` one. */
|
|
144
|
+
/** HTTP dispatch over projected wire fields, with canonical decoding after success. */
|
|
145
|
+
interface DeferredHttpTransport extends HttpTransport {
|
|
146
|
+
callDeferred<O extends Operation$1>(operation: DeferredOperation<O>, input: OperationInput$1<O>, options?: OperationCallOptions & OperationStreamOptions): Promise<OperationResult$1<O>>;
|
|
147
|
+
}
|
|
143
148
|
type OperationTransport = Pick<HttpTransport, "call" | "stream">;
|
|
144
149
|
type Transport = Pick<HttpTransport, "call" | "get" | "post" | "patch" | "put" | "delete" | "getText" | "postRaw" | "postMultipart">;
|
|
145
150
|
interface TransportConfig {
|
|
@@ -155,7 +160,7 @@ interface TransportConfig {
|
|
|
155
160
|
declare function refusalOf(status: number, text: string): StandardsRequestError;
|
|
156
161
|
/** Reads a refused `Response` into the error the transport itself throws. */
|
|
157
162
|
declare function readRefusal(response: Response): Promise<StandardsRequestError>;
|
|
158
|
-
declare function createHttpTransport(config: HttpTransportConfig):
|
|
163
|
+
declare function createHttpTransport(config: HttpTransportConfig): DeferredHttpTransport;
|
|
159
164
|
/**
|
|
160
165
|
* The API-key transport the public SDK documents: `createHttpTransport` with
|
|
161
166
|
* the bearer key and tenant header, one attempt, no refresh.
|
|
@@ -256,6 +261,52 @@ declare function openAgentStream(options: OpenAgentStreamOptions): AgentStreamHa
|
|
|
256
261
|
* callers fall back to a client-side name.
|
|
257
262
|
*/
|
|
258
263
|
declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
|
|
264
|
+
/** The record an uploaded file joins once stored, and how. */
|
|
265
|
+
type AttachTarget = UploadAttachTo;
|
|
266
|
+
interface UploadInput {
|
|
267
|
+
/** Each is sent as it is: a browser `File`, or a Node `Blob` with a name (`fs.openAsBlob`). */
|
|
268
|
+
files: readonly (Blob & {
|
|
269
|
+
readonly name: string;
|
|
270
|
+
})[];
|
|
271
|
+
folderPath?: string;
|
|
272
|
+
public?: boolean;
|
|
273
|
+
attachTo?: AttachTarget;
|
|
274
|
+
/** `tus` (default) resumes after a lost connection; `put` sends each file in one request. */
|
|
275
|
+
protocol?: "tus" | "put";
|
|
276
|
+
onProgress?: (fileIndex: number, progress: UploadProgress) => void;
|
|
277
|
+
/** `interrupted`: the connection dropped and the transfer is retrying; `finalizing`: bytes sent, the API is checking them. */
|
|
278
|
+
onStatus?: (fileIndex: number, status: "sending" | "interrupted" | "finalizing") => void;
|
|
279
|
+
/** Stops the transfer under way and every file not started; each prepared, uncompleted upload is aborted. */
|
|
280
|
+
signal?: AbortSignal;
|
|
281
|
+
}
|
|
282
|
+
type UploadResult = {
|
|
283
|
+
ok: true;
|
|
284
|
+
file: File;
|
|
285
|
+
attached?: AttachedRecordDocument;
|
|
286
|
+
} | {
|
|
287
|
+
ok: false;
|
|
288
|
+
error: unknown;
|
|
289
|
+
};
|
|
290
|
+
/** A file `uploadAll` stored, and the document it joined when the upload named `attachTo`. */
|
|
291
|
+
interface UploadedFile {
|
|
292
|
+
file: File;
|
|
293
|
+
attached?: AttachedRecordDocument;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Upload files straight to storage: for each, in sequence, prepare (the API
|
|
297
|
+
* judges it and signs a target), send the bytes to the target, then complete
|
|
298
|
+
* (the API checks and records them). The one implementation behind every
|
|
299
|
+
* uploader. Answers one result per file, in input order; a refusal is that
|
|
300
|
+
* file's result and the next file still goes.
|
|
301
|
+
*/
|
|
302
|
+
declare function upload(client: AppClient, input: UploadInput): Promise<UploadResult[]>;
|
|
303
|
+
/**
|
|
304
|
+
* `upload` for a batch the caller presents as one action: every file is
|
|
305
|
+
* stored, or none stays. When one is refused, the files of the batch already
|
|
306
|
+
* stored are deleted (best effort: one attached to a record stays in its
|
|
307
|
+
* pack) and the first refusal is thrown.
|
|
308
|
+
*/
|
|
309
|
+
declare function uploadAll(client: AppClient, input: UploadInput): Promise<UploadedFile[]>;
|
|
259
310
|
/**
|
|
260
311
|
* The in-process transport: an {@link OperationTransport} that can also be
|
|
261
312
|
* bound to who acts, which a transport over HTTP cannot (its identity is the
|
|
@@ -291,4 +342,4 @@ type OperationCall<O extends Operation> = (...args: undefined extends OperationI
|
|
|
291
342
|
type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
|
|
292
343
|
/** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
|
|
293
344
|
declare function createAppClient(transport: OperationTransport): AppClient;
|
|
294
|
-
export {
|
|
345
|
+
export { OperationStreamOptions as A, BundleValidationError as B, schemaApiErrorCode as C, HttpTransportConfig as D, HttpTransport as E, createHttpTransport as F, StandardsConfigurationError as H, createTransport as I, readRefusal as L, Transport as M, TransportConfig as N, MultipartRequestOptions as O, UploadProgress as P, refusalOf as R, isViewNotFound as S, DeferredHttpTransport as T, StandardsRequestError as U, StandardsAuthError as V, openAgentStream as _, AttachTarget as a, isObjectNotFound as b, UploadedFile as c, parseContentDispositionFilename as d, AgentStreamControl as f, TURN_END_TYPES as g, OpenAgentStreamOptions as h, createInProcessTransport as i, OperationTransport as j, OperationCallOptions as k, upload as l, AgentStreamStatus as m, createAppClient as n, UploadInput as o, AgentStreamHandle as p, InProcessTransport as r, UploadResult as s, AppClient as t, uploadAll as u, draftConflictChanges as v, schemaApiErrorDetails as w, isPermanentRefusal as x, isDraftRevisionConflict as y, BundleConflictError as z };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
const e=require("./http-transport-CkB0bQlR.js");let t=require("@standards/schema"),n=require("@standards/schema/api");const r=[1e3,2e3,5e3],i=/* @__PURE__ */ new Set([`turn.completed`,`turn.failed`,`turn.cancelled`]);function parseSseFrame(e){let t,n=`message`,r,i=[];for(let a of e.split(`
|
|
3
|
+
`)){let e=a.endsWith(`\r`)?a.slice(0,-1):a;if(e===``||e.startsWith(`:`))continue;let o=e.indexOf(`:`),s=o===-1?e:e.slice(0,o),c=o===-1?``:e.slice(o+1);c.startsWith(` `)&&(c=c.slice(1)),s===`id`?t=c:s===`event`?n=c:s===`data`?i.push(c):s===`retry`&&/^\d+$/.test(c)&&(r=Number(c))}return{id:t,event:n,data:i.join(`
|
|
4
|
+
`),retry:r}}function parseEvent(e){let n;try{n=JSON.parse(e.data)}catch{return}if((0,t.isPlainRecord)(n)&&typeof n.type==`string`&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>0&&(e.id===void 0||e.id===String(n.seq)))return n}function parseControl(e){let n;try{n=JSON.parse(e.data)}catch{return}if(!(0,t.isPlainRecord)(n))return;let r=n.control;return r===`up-to-date`||r===`lease-ended`||r===`inbox`?r:void 0}function isUnresolvableActor(e){return e.status===401&&e.code===`ACTOR_RESOLUTION_FAILED`}function isTerminalRefusal(e){return e.status===400||e.status===403||e.status===404||isUnresolvableActor(e)}function isCursorExpired(t){return t instanceof e.d&&t.status===410&&t.code===`AGENT_SESSION_STREAM_CURSOR_EXPIRED`}function openAgentStream(t){let n=!1,i,a,o,s=1e3,c=0,l,u=t.subscribeAuthChanges?.(()=>{n||(c+=1,l?.(),l=void 0)});function endWait(){a!==void 0&&clearTimeout(a),a=void 0,o?.(),o=void 0}function close(){n||(n=!0,i?.abort(),endWait(),l?.(),l=void 0,u?.())}function waitForAuthChange(e){return n||c!==e?Promise.resolve():new Promise(e=>{l=e})}function sleep(e){return new Promise(t=>{o=t,a=setTimeout(endWait,e)})}function handleFrame(e){let n=parseSseFrame(e);if(n.retry!==void 0&&(s=n.retry),n.data===``)return`skipped`;if(n.event===`control`){let e=parseControl(n);return e&&t.onControl(e),e===`lease-ended`?`lease-ended`:`skipped`}if(n.event!==`event`)return`skipped`;let r=parseEvent(n);return r?r.seq<=t.cursor()?`skipped`:(t.onEvent(r),`delivered`):`malformed`}async function consume(e,t){let r=e.body;if(r===null)return{delivered:!1,end:`failed`};let i=r.getReader(),a=new TextDecoder,o=``,s=!1;try{for(;;){let{done:e,value:r}=await i.read();if(n||e)return{delivered:s,end:`clean`};o+=a.decode(r,{stream:!0}).replace(/\r\n/g,`
|
|
5
|
+
`);let c=o.indexOf(`
|
|
6
|
+
|
|
7
|
+
`);for(;c!==-1;){let e=o.slice(0,c);o=o.slice(c+2);let r=handleFrame(e);if(r===`delivered`&&(s=!0),n)return{delivered:s,end:`clean`};if(r===`malformed`)return t.abort(),{delivered:s,end:`malformed`};if(r===`lease-ended`)return{delivered:s,end:`lease-ended`};c=o.indexOf(`
|
|
8
|
+
|
|
9
|
+
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(n,r,i){if(isCursorExpired(n))try{return await t.onExpired(),i?`back-off`:`reopen`}catch{return`back-off`}return n instanceof e.d?isTerminalRefusal(n)?(close(),t.onStatus(`error`,n),`stop`):n.status===401?(t.onStatus(`auth-blocked`,n),await waitForAuthChange(r),`reopen`):`back-off`:`back-off`}let d,f=0;async function rehydratedPastStall(e){if(t.cursor()!==e||(f=d===e?f+1:1,d=e,f<3))return!1;d=void 0,f=0;try{return await t.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?s:r[Math.min(t,r.length-1)]??5e3}async function run(){let e=!0,r=0,a=!1;for(;!n;){t.onStatus(e?`connecting`:`reconnecting`),e=!1;let o=new AbortController;i=o;let s=c,l=`failed`;try{let e=await t.open(t.sessionId,t.cursor(),o.signal,()=>{s=c});if(n)return;t.onStatus(`connected`);let i=t.cursor(),u=await consume(e,o);if(l=u.end,l===`malformed`&&await rehydratedPastStall(i)){if(n)return;continue}u.delivered&&(r=0,a=!1)}catch(e){if(n)return;let t=isCursorExpired(e),r=await afterFailedOpen(e,s,a);if(a=t,r===`stop`||n)return;if(r===`reopen`)continue}if(n)return;t.onStatus(`reconnecting`);let u=delayAfter(l,r);l===`failed`&&(r+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}const a=[1e3,2e3,4e3],o=[0,1e3,3e3,5e3,1e4,2e4];async function upload(e,t){let n=[];for(let[r,i]of t.files.entries())n.push(await uploadOne(e,t,i,r));return n}async function uploadAll(e,t){let n=await upload(e,t),r=n.find(e=>!e.ok);if(r===void 0||r.ok)return n.flatMap(e=>e.ok?[e.attached===void 0?{file:e.file}:{file:e.file,attached:e.attached}]:[]);for(let t of n)if(t.ok)try{await e.files.delete({id:t.file.id})}catch{}throw r.error}async function uploadOne(e,t,n,r){let{signal:i}=t;if(i?.aborted)return{ok:!1,error:i.reason};let a;try{a=await prepare(e,t,n)}catch(e){return{ok:!1,error:e}}try{t.onStatus?.(r,`sending`),await send(a.target,n,{signal:i,onProgress:e=>t.onProgress?.(r,e),onStatus:e=>t.onStatus?.(r,e)})}catch(t){return await abandon(e,a.uploadId),{ok:!1,error:i?.aborted?i.reason:t}}t.onStatus?.(r,`finalizing`);try{let{file:t,attached:n}=await complete(e,a.uploadId,i);return n===void 0?{ok:!0,file:t}:{ok:!0,file:t,attached:n}}catch(t){return i?.aborted?(await abandon(e,a.uploadId),{ok:!1,error:i.reason}):{ok:!1,error:t}}}async function prepare(e,t,n){let r={idempotencyKey:crypto.randomUUID(),fileName:n.name,mimeType:n.type||`application/octet-stream`,size:n.size,...t.folderPath===void 0?{}:{folderPath:t.folderPath},...t.public===void 0?{}:{public:t.public},protocol:t.protocol??`tus`,...t.attachTo===void 0?{}:{attachTo:t.attachTo}};return await e.files.prepareUpload(r,{signal:t.signal,maxRetries:2})}async function complete(t,n,r){let i=0;for(let o=0;;o+=1)try{return await t.files.completeUpload({uploadId:n},{signal:r})}catch(t){let n=e._(t)===`UPLOAD_IN_PROGRESS`||unreached(t),s=a[o]??5e3;if(!n||r?.aborted||i+s>36e4)throw t;await sleep(s,r),i+=s}}async function abandon(e,t){try{await e.files.abortUpload({uploadId:t})}catch{}}function send(e,t,n){return e.protocol===`tus`?sendTus(e,t,n):sendPut(e,t,n)}async function sendPut(t,n,r){let i=await fetch(t.url,{method:`PUT`,headers:t.headers,body:n,...r.signal===void 0?{}:{signal:r.signal}});if(!i.ok)throw new e.d(i.status,`Storage refused the upload (HTTP ${i.status})`);r.onProgress({loaded:n.size,total:n.size})}async function sendTus(e,t,n){let{signal:r}=n;r?.throwIfAborted();let i=await import(`tus-js-client`),a=i.defaultOptions.onShouldRetry;return new Promise((c,l)=>{let u=!1,d=new i.Upload(t,{endpoint:e.url,headers:e.headers,metadata:e.metadata??{},...e.chunkSize===void 0?{}:{chunkSize:e.chunkSize},retryDelays:o,storeFingerprintForResuming:!1,fileReader:s,httpStack:onOrigin(new i.DefaultHttpStack({}),e.url),onProgress:(e,t)=>{u&&(u=!1,n.onStatus(`sending`)),n.onProgress({loaded:e,total:t})},onShouldRetry:(e,t,r)=>{let i=a?.(e,t,r)??!1;return i&&!u&&(u=!0,n.onStatus(`interrupted`)),i},onSuccess:()=>{r?.removeEventListener(`abort`,stop),c()},onError:e=>{r?.removeEventListener(`abort`,stop),l(e)}});function stop(){d.abort(!1).catch(()=>{}),l(r?.reason)}r?.addEventListener(`abort`,stop,{once:!0}),d.start()})}function onOrigin(e,t){let{origin:n}=new URL(t);return{createRequest(r,i){let{pathname:a,search:o}=new URL(i,t);return e.createRequest(r,`${n}${a}${o}`)},getName:()=>e.getName()}}const s={openFile:e=>Promise.resolve({size:e.size,slice:async(t,n)=>{let r=new Uint8Array(await e.slice(t,n).arrayBuffer());return{value:Object.assign(r,{size:r.length}),done:n>=e.size}},close:()=>{}})};function unreached(t){return t instanceof e.d&&t.status===0}function sleep(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,cancel),n()},e);function cancel(){clearTimeout(i),r(t?.reason)}t?.addEventListener(`abort`,cancel,{once:!0})})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,t){let{query:r,body:i,headers:a}=(0,n.splitOperationInput)(e,t),o=Object.fromEntries((0,n.pathParamNames)(e.path).map(e=>[e,String(t[e])])),s=Object.fromEntries(Object.entries(a??{}).map(([e,t])=>[e.toLowerCase(),t])),c={params:o,query:asStrings(r),headers:s};if(e.upload===void 0)return{...c,body:i===void 0?void 0:JSON.parse(JSON.stringify(i))};let{[e.upload.field]:l,...u}=i??{},d=l==null?[]:Array.isArray(l)?l:[l];return{...c,body:asStrings(u),uploads:await Promise.all(d.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){return transportActingAs(e,void 0)}function transportActingAs(t,r){async function call(i,a,o={}){if(o.signal?.throwIfAborted(),i.response===`events`)throw Error(`Operation ${i.name} streams over HTTP only`);let s=await wireRequest(i,a??{}),c;try{c=await t.execute(i,s,r)}catch(t){throw(0,n.isOperationRefused)(t)?e.i(t.status,JSON.stringify(t.body)):t}if(i.response===`bytes`)return downloaded(c);let l=c===void 0?null:JSON.parse(JSON.stringify(c));return(0,n.decodeOperationOutput)(i,l)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`)),withCaller:e=>transportActingAs(t,e)}}function createAppClient(e){let t={},r=Object.values(n.appOperationGroups);for(let i of r.flatMap(e=>Object.values(e))){let r=(0,n.operationGroup)(i),a=i.name.slice(r.length+1);t[r]??={},t[r][a]=(t,n)=>i.response===`events`?e.stream(i,t,n):e.call(i,t,n)}return t}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return uploadAll}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createInProcessTransport}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return openAgentStream}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return upload}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createAppClient}});
|
package/dist/app.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as
|
|
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, schemaApiErrorDetails };
|
|
2
|
+
import { A as OperationStreamOptions, C as schemaApiErrorCode, D as HttpTransportConfig, E as HttpTransport, F as createHttpTransport, L as readRefusal, P as UploadProgress, R as refusalOf, S as isViewNotFound, U as StandardsRequestError, V as StandardsAuthError, _ as openAgentStream, a as AttachTarget, b as isObjectNotFound, c as UploadedFile, d as parseContentDispositionFilename, f as AgentStreamControl, g as TURN_END_TYPES, h as OpenAgentStreamOptions, i as createInProcessTransport, j as OperationTransport, k as OperationCallOptions, l as upload, m as AgentStreamStatus, n as createAppClient, o as UploadInput, p as AgentStreamHandle, r as InProcessTransport, s as UploadResult, t as AppClient, u as uploadAll, v as draftConflictChanges, w as schemaApiErrorDetails, x as isPermanentRefusal, y as isDraftRevisionConflict } from "./app-KQAbWX9h.mjs";
|
|
3
|
+
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type AttachTarget, type HttpTransport, type HttpTransportConfig, type InProcessTransport, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadInput, type UploadProgress, type UploadResult, type UploadedFile, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode, schemaApiErrorDetails, upload, uploadAll };
|
package/dist/app.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as
|
|
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, schemaApiErrorDetails };
|
|
2
|
+
import { A as OperationStreamOptions, C as schemaApiErrorCode, D as HttpTransportConfig, E as HttpTransport, F as createHttpTransport, L as readRefusal, P as UploadProgress, R as refusalOf, S as isViewNotFound, U as StandardsRequestError, V as StandardsAuthError, _ as openAgentStream, a as AttachTarget, b as isObjectNotFound, c as UploadedFile, d as parseContentDispositionFilename, f as AgentStreamControl, g as TURN_END_TYPES, h as OpenAgentStreamOptions, i as createInProcessTransport, j as OperationTransport, k as OperationCallOptions, l as upload, m as AgentStreamStatus, n as createAppClient, o as UploadInput, p as AgentStreamHandle, r as InProcessTransport, s as UploadResult, t as AppClient, u as uploadAll, v as draftConflictChanges, w as schemaApiErrorDetails, x as isPermanentRefusal, y as isDraftRevisionConflict } from "./app-KQAbWX9h.js";
|
|
3
|
+
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type AttachTarget, type HttpTransport, type HttpTransportConfig, type InProcessTransport, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadInput, type UploadProgress, type UploadResult, type UploadedFile, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode, schemaApiErrorDetails, upload, uploadAll };
|
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("./app-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./http-transport-CkB0bQlR.js"),t=require("./app-oCr8yvTF.js");exports.StandardsAuthError=e.l,exports.StandardsRequestError=e.d,exports.TURN_END_TYPES=t.a,exports.createAppClient=t.t,exports.createHttpTransport=e.t,exports.createInProcessTransport=t.n,exports.draftConflictChanges=e.f,exports.isDraftRevisionConflict=e.p,exports.isObjectNotFound=e.m,exports.isPermanentRefusal=e.h,exports.isViewNotFound=e.g,exports.openAgentStream=t.o,exports.parseContentDispositionFilename=e.o,exports.readRefusal=e.r,exports.refusalOf=e.i,exports.schemaApiErrorCode=e._,exports.schemaApiErrorDetails=e.v,exports.upload=t.r,exports.uploadAll=t.i;
|
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
|
-
|
|
2
|
+
import{_ as e,d as t,f as n,g as r,h as i,i as a,l as o,m as s,o as c,p as l,r as u,t as d,v as f}from"./http-transport-CijwtqPm.mjs";import{a as p,i as m,n as h,o as g,r as _,t as v}from"./app-DQ0e_dZD.mjs";export{o as StandardsAuthError,t as StandardsRequestError,p as TURN_END_TYPES,v as createAppClient,d as createHttpTransport,h as createInProcessTransport,n as draftConflictChanges,l as isDraftRevisionConflict,s as isObjectNotFound,i as isPermanentRefusal,r as isViewNotFound,g as openAgentStream,c as parseContentDispositionFilename,u as readRefusal,a as refusalOf,e as schemaApiErrorCode,f as schemaApiErrorDetails,_ as upload,m as uploadAll};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { E as
|
|
2
|
+
import { E as HttpTransport, N as TransportConfig, j as OperationTransport, r as InProcessTransport, t as AppClient } from "./app-KQAbWX9h.js";
|
|
3
3
|
import { AggregateRecordsOptions, BundleBuilder, BundleSyncPreview, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
|
|
4
4
|
import { ActorId } from "@standards/schema/api";
|
|
5
5
|
/**
|
|
@@ -86,8 +86,11 @@ interface RecordsExportOptions {
|
|
|
86
86
|
/** The tab name the downloaded file is named after (`{object}-{tab}-{date}.csv`). */
|
|
87
87
|
filename?: string;
|
|
88
88
|
}
|
|
89
|
-
/**
|
|
90
|
-
|
|
89
|
+
/**
|
|
90
|
+
* What `aggregate()` takes: the aggregate contract minus the query, which is
|
|
91
|
+
* this one; one measure, or `series` over one date bucket.
|
|
92
|
+
*/
|
|
93
|
+
type RecordsAggregateOptions = AggregateRecordsOptions extends (infer Options) ? Options extends AggregateRecordsOptions ? Omit<Options, "query"> : never : never;
|
|
91
94
|
interface FetchResult<TBuilder> {
|
|
92
95
|
records: ExtractRecord<TBuilder>[];
|
|
93
96
|
total: number | null;
|
|
@@ -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-oCr8yvTF.js"),t=require("./http-transport-CkB0bQlR.js");let n=require("@standards/schema"),r=require("@standards/schema/api");async function readInstalled(e,n){try{return await e.call(r.bundlesOperations.get,{name:n})}catch(e){if(e instanceof t.d&&e.status===404)return null;throw e}}async function syncBundle(e,n,i={}){let a=await n.build(),{resolutions:o=[],fingerprint:s,confirmedRecords:c}=i,l=s!==void 0||c!==void 0?null:await readInstalled(e,a.name);if(l?.hash===a.hash&&l.label===a.label&&l.description===a.description&&l.uses.join(`
|
|
3
|
+
`)===a.uses.join(`
|
|
4
|
+
`))return{applied:!1,hash:a.hash,pendingRemovals:[]};let u={...a,...o.length>0?{resolutions:o}:{},...s===void 0?{}:{fingerprint:s},...c===void 0?{}:{confirmedRecords:c}};try{return await e.call(r.bundlesOperations.sync,{name:a.name,bundle:u})}catch(e){throw e instanceof t.d&&e.status===409?new t.s(e.status,e.message,e.code):e instanceof t.d&&e.status===400?new t.c(e.status,e.message,e.code):e}}async function previewBundleSync(e,t){let n=await t.build();return await e.call(r.bundlesOperations.syncPreview,{name:n.name,bundle:n})}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const i=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`,`as`]);function assertObjectKeys(e){let n=/* @__PURE__ */ new Map;for(let r of e){if(r.includes(`--`)||r.endsWith(`-`))throw new t.u(`Object "${r}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(r);if(i.has(e))throw new t.u(`Object "${r}" maps to the client key "${e}", which is reserved. Rename the object.`);let a=n.get(e);if(a!==void 0&&a!==r)throw new t.u(`Objects "${a}" and "${r}" both map to the client key "${e}". Rename one of them.`);n.set(e,r)}}function assertObjectNames(e){let t=/* @__PURE__ */ new Set;for(let r of e){if(t.has(r))throw new n.DuplicateError(`object`,r);t.add(r)}assertObjectKeys(e)}function readRecord(e,t){let{values:r,...i}=t;return(0,n.isPlainRecord)(r)?{...i,...(0,n.decodeRecordValues)(e,r)}:t}var a=class RecordsQueryImpl extends n.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(e,n={}){if(!this.transport.postRaw)throw new t.u(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:i,sorts:a}=this.body(),{ids:o,locale:s,filename:c}=n;return await this.transport.postRaw((0,r.buildOperationPath)(r.recordsOperations.export,{objectName:this.objectName}),{q:this.state.search??``,...i?{filters:i}:{},...a?{sorts:a}:{},columns:e,...o?{ids:o}:{},...s?{locale:s}:{},timezone:n.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...c?{filename:c}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new n.AggregateValidationError(n.SchemaErrorCode.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(r.recordsOperations.aggregate,{objectName:this.objectName,...t})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(r.recordsOperations.list,e):await this.transport.call(r.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(r.recordsOperations.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:t,metadata:i}={}){let a={...t!==void 0&&{allowDraft:t},...i!==void 0&&{metadata:i}},o=await this.transport.call(r.recordsOperations.create,{objectName:this.objectName,data:(0,n.encodeRecordValues)(this.definition,e),...Object.keys(a).length>0&&{options:a}});return this.revive(o)}async update(e,i,{metadata:a}={}){let o=(0,n.encodeRecordValues)(this.definition,i);if(a===void 0){let t=await this.transport.call(r.recordsOperations.update,{objectName:this.objectName,id:e,values:o});return this.revive(t)}let{objectId:s}=await this.transport.call(r.recordsOperations.get,{objectName:this.objectName,id:e}),{steps:c}=await this.transport.call(r.recordOperationsOperations.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:s,recordId:e,values:o,metadata:a}]}),[l]=c;if(l===void 0||l.status===`error`){let e=l?.code,r=e===void 0?500:n.SCHEMA_ERROR_HTTP_STATUS[e];throw t.i(r,JSON.stringify({message:l?.message,code:e}))}let u=(0,r.decodeOperationOutput)(r.recordsOperations.get,l.record);return this.revive(u)}async delete(e){await this.transport.call(r.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 t={created:[],errors:[]};return await this.inChunks(e,async(e,i)=>{let a=await this.transport.call(r.recordsOperations.bulkCreate,{objectName:this.objectName,records:e.map(e=>(0,n.encodeRecordValues)(this.definition,e))});t.created.push(...a.created.map(e=>this.revive(e))),t.errors.push(...a.errors.map(e=>({...e,index:e.index+i})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let i=await this.transport.call(r.recordsOperations.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:t})=>({id:e,data:(0,n.encodeRecordValues)(this.definition,t)}))});t.updated.push(...i.updated.map(e=>this.revive(e))),t.errors.push(...i.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(r.recordsOperations.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(r.recordAccessOperations.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,n){return await this.transport.call(r.recordAccessOperations.grant,{objectName:this.objectName,recordId:e,actorId:t,role:n})}async revokeAccess(e,t){return await this.transport.call(r.recordAccessOperations.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(r.recordAccessOperations.clear,{objectName:this.objectName,recordId:e})}};const o=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=o.get(e);if(t)return t;let n=e.build();return o.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new a(e,t,null);let n=definitionOf(t);return new a(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 t.u(`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 t.u(`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 n=readEnvironment(),r=e.baseUrl??n.baseUrl;if(r===void 0)throw new t.u(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=e.apiKey??n.apiKey;if(i===void 0)throw new t.u(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:r,apiKey:i}}function createStandards(e={}){let{bundles:n=[],transport:r,...i}=e;if(r!==void 0&&Object.values(i).some(e=>e!==void 0))throw new t.u(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(r??t.n(resolveConfig(i)),n.flatMap(e=>e.objectBuilders))}function buildStandards(t,n){let i=e.t(t),sync=((e,n)=>isBundleBuilder(e)?syncBundle(t,e,n):i.bundles.sync(e,n)),syncPreview=((e,n)=>isBundleBuilder(e)?previewBundleSync(t,e):i.bundles.syncPreview(e,n)),a={...i,bundles:{...i.bundles,sync,syncPreview},from:e=>createRecordsQuery(t,e),contract:i},o=n.map(e=>definitionOf(e).name);assertObjectNames(o),n.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,r.callerOf)(e)),n)),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,"c",{enumerable:!0,get:function(){return syncBundle}}),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 previewBundleSync}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { E as
|
|
2
|
+
import { E as HttpTransport, N as TransportConfig, j as OperationTransport, r as InProcessTransport, t as AppClient } from "./app-KQAbWX9h.mjs";
|
|
3
3
|
import { AggregateRecordsOptions, BundleBuilder, BundleSyncPreview, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
|
|
4
4
|
import { ActorId } from "@standards/schema/api";
|
|
5
5
|
/**
|
|
@@ -86,8 +86,11 @@ interface RecordsExportOptions {
|
|
|
86
86
|
/** The tab name the downloaded file is named after (`{object}-{tab}-{date}.csv`). */
|
|
87
87
|
filename?: string;
|
|
88
88
|
}
|
|
89
|
-
/**
|
|
90
|
-
|
|
89
|
+
/**
|
|
90
|
+
* What `aggregate()` takes: the aggregate contract minus the query, which is
|
|
91
|
+
* this one; one measure, or `series` over one date bucket.
|
|
92
|
+
*/
|
|
93
|
+
type RecordsAggregateOptions = AggregateRecordsOptions extends (infer Options) ? Options extends AggregateRecordsOptions ? Omit<Options, "query"> : never : never;
|
|
91
94
|
interface FetchResult<TBuilder> {
|
|
92
95
|
records: ExtractRecord<TBuilder>[];
|
|
93
96
|
total: number | null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
import{
|
|
2
|
+
import{t as e}from"./app-DQ0e_dZD.mjs";import{c as t,d as n,i as r,n as i,s as a,u as o}from"./http-transport-CijwtqPm.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(e,r,i={}){let o=await r.build(),{resolutions:s=[],fingerprint:c,confirmedRecords:l}=i,u=c!==void 0||l!==void 0?null:await readInstalled(e,o.name);if(u?.hash===o.hash&&u.label===o.label&&u.description===o.description&&u.uses.join(`
|
|
3
3
|
`)===o.uses.join(`
|
|
4
|
-
`))return{applied:!1,hash:o.hash,pendingRemovals:[]};let d={...o,...s.length>0?{resolutions:s}:{},...c===void 0?{}:{fingerprint:c},...l===void 0?{}:{confirmedRecords:l}};try{return await
|
|
4
|
+
`))return{applied:!1,hash:o.hash,pendingRemovals:[]};let d={...o,...s.length>0?{resolutions:s}:{},...c===void 0?{}:{fingerprint:c},...l===void 0?{}:{confirmedRecords:l}};try{return await e.call(g.sync,{name:o.name,bundle:d})}catch(e){throw e instanceof n&&e.status===409?new a(e.status,e.message,e.code):e instanceof n&&e.status===400?new t(e.status,e.message,e.code):e}}async function previewBundleSync(e,t){let n=await t.build();return await e.call(g.syncPreview,{name:n.name,bundle:n})}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 o(`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 o(`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 o(`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 o(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:n,sorts:r}=this.body(),{ids:i,locale:a,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,...i?{ids:i}:{},...a?{locale:a}:{},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 i=p(this.definition,t);if(n===void 0){let t=await this.transport.call(x.update,{objectName:this.objectName,id:e,values:i});return this.revive(t)}let{objectId:a}=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:a,recordId:e,values:i,metadata:n}]}),[s]=o;if(s===void 0||s.status===`error`){let e=s?.code,t=e===void 0?500:u[e];throw r(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 o(`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 o(`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 o(`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 o(`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,...r}=e;if(n!==void 0&&Object.values(r).some(e=>e!==void 0))throw new o(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(n??i(resolveConfig(r)),t.flatMap(e=>e.objectBuilders))}function buildStandards(t,n){let r=e(t),sync=((e,n)=>isBundleBuilder(e)?syncBundle(t,e,n):r.bundles.sync(e,n)),syncPreview=((e,n)=>isBundleBuilder(e)?previewBundleSync(t,e):r.bundles.syncPreview(e,n)),i={...r,bundles:{...r.bundles,sync,syncPreview},from:e=>createRecordsQuery(t,e),contract:r},a=n.map(e=>definitionOf(e).name);assertObjectNames(a),n.forEach((e,n)=>{i[objectKeyOf(a[n])]=createRecordsQuery(t,e)});let o=t.withCaller?.bind(t);return o!==void 0&&(i.as=e=>buildStandards(o(_(e)),n)),i}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}export{definitionOf as a,syncBundle as c,createRecordsQuery as i,createStandards as n,readRecord as o,resolveConfig as r,previewBundleSync as s,buildStandards as t};
|
|
@@ -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{DRAFT_CONFLICT_KINDS as e,decodeOperationOutput as t,encodePathSegment as n,splitOperationInput as r}from"@standards/schema/api/http";import{SchemaErrorCode as i,ValidationError as a}from"@standards/schema/exceptions";function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}function schemaApiErrorDetails(e){if(typeof e!=`object`||!e||!(`details`in e))return;let{details:t}=e;return typeof t==`object`&&t?t:void 0}const o=/* @__PURE__ */ new Set([i.CONFIGURATION_REQUIRED]);function isPermanentRefusal(e){let t=schemaApiErrorCode(e);return t!==void 0&&o.has(t)}function isObjectNotFound(e){if(typeof e!=`object`||!e)return!1;let{code:t,status:n}=e;return t===i.OBJECT_NOT_FOUND||n===404}function isDraftRevisionConflict(e){return schemaApiErrorCode(e)===i.DRAFT_REVISION_CONFLICT}const s=new Set(e);function draftConflictChanges(e){if(!isDraftRevisionConflict(e))return[];let t=e.details?.changes;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.key==`string`&&typeof e.label==`string`&&typeof e.seen==`string`&&s.has(e.kind)):[]}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}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`}},BundleConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},BundleValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};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,...t){return[`/records`,...[e,...t].map(n)].join(`/`)}function resolveWithinBase(e,t){let n=e.endsWith(`/`)?e:`${e}/`,r=new URL(n),i=t.replace(/^\/+/,``),[o]=i.split(/[?#]/);if((o??``).split(`/`).some(e=>e===`..`||e===`.`))throw new a(`Request path "${t}" walks outside its own collection`,[]);let s=new URL(i,r);if(s.origin!==r.origin||!s.pathname.startsWith(r.pathname))throw new a(`Request path "${t}" resolves outside the API base "${r.pathname}"`,[]);return s}const c=[400,1500];async function loadChunk(e){for(let t=0;;t++)try{return await e()}catch(e){let n=c[t];if(n===void 0)throw e;await new Promise(e=>setTimeout(e,n))}}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));else 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:i,getRetries:a=0}=e,o=e.timeoutMs??3e4,s=e.apiPrefix===void 0?void 0:trimSlashes(e.apiPrefix,!0),c=s?`${trimSlashes(n,!1)}/${s}`:n;function buildUrl(e,t){let n=resolveWithinBase(c,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 i?.())return;let r=await fetchOnce(e,t,n);return observe(r),r}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,r){let s=buildUrl(e,n.params),c=(t.method??`GET`).toUpperCase(),l=n.maxRetries??(c===`GET`?a:0),u=n.timeoutMs===void 0?o:n.timeoutMs;for(let e=0;;e++){let a=e<l,o;try{o=await fetchOnce(s,t,u)}catch(n){if(a&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(o),o.status>=500&&a){let t=await readRefusalWithin(o);if(isPermanentRefusal(t))throw t;await backoff(e)}else{if(o.status===401&&i&&(o=await refreshAndRetry(s,t,u)??o),!o.ok){let e=await o.text().catch(()=>``);throw refusalFrom(o.status,e,n.plainTextRefusal??!1)}return await r(o)}}}async function streamWire(t,n,a={}){a.signal?.throwIfAborted();let{path:o,query:s,body:c,headers:l}=r(t,n??{}),u=buildUrl(o,s),{signal:d,onRequest:f}=a,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(u,{method:t.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`||!i||!await i().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)}async function callWire(t,n,i,a){if(i.signal?.throwIfAborted(),t.response===`events`)return await streamWire(t,n,i);let{path:o,query:s,body:c,headers:l}=r(t,n??{});if(t.upload!==void 0&&i.onUploadProgress&&canReportUploadProgress(e)){i.signal?.throwIfAborted();let n=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(o,s),method:t.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...l}),token:n,form:multipartBody(t.upload.field,c),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>a(e?JSON.parse(e):null))}let u=t.upload===void 0?c===void 0?void 0:JSON.stringify(c):multipartBody(t.upload.field,c),d=t.response===`bytes`?readDownload:async e=>a(await readJson(e));return await send(o,{method:t.method,body:u,signal:i.signal,...l?{headers:l}:{},...i.keepalive?{keepalive:!0}:{}},{params:s,maxRetries:i.maxRetries,timeoutMs:i.timeoutMs},d)}return{async call(e,n,r={}){return await callWire(e,n,r,n=>t(e,n))},async callDeferred(e,n,r={}){return await callWire(e.wire,n,r,async n=>{r.signal?.throwIfAborted();let i=await decodeWithSignal(loadChunk(e.load),r.signal);return r.signal?.throwIfAborted(),t(i,n)})},stream:streamWire,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})}async function decodeWithSignal(e,t){if(!t)return e;let onAbort,n=new Promise((e,n)=>{onAbort=()=>n(t.reason),t.addEventListener(`abort`,onAbort,{once:!0}),t.aborted&&onAbort()});try{return await Promise.race([e,n])}finally{onAbort&&t.removeEventListener(`abort`,onAbort)}}export{schemaApiErrorCode as _,recordsPath as a,BundleValidationError as c,StandardsRequestError as d,draftConflictChanges as f,isViewNotFound as g,isPermanentRefusal as h,refusalOf as i,StandardsAuthError as l,isObjectNotFound as m,createTransport as n,parseContentDispositionFilename as o,isDraftRevisionConflict as p,readRefusal as r,BundleConflictError as s,createHttpTransport as t,StandardsConfigurationError as u,schemaApiErrorDetails as v};
|
|
@@ -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/api/http"),t=require("@standards/schema/exceptions");function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}function schemaApiErrorDetails(e){if(typeof e!=`object`||!e||!(`details`in e))return;let{details:t}=e;return typeof t==`object`&&t?t:void 0}const n=/* @__PURE__ */ new Set([t.SchemaErrorCode.CONFIGURATION_REQUIRED]);function isPermanentRefusal(e){let t=schemaApiErrorCode(e);return t!==void 0&&n.has(t)}function isObjectNotFound(e){if(typeof e!=`object`||!e)return!1;let{code:n,status:r}=e;return n===t.SchemaErrorCode.OBJECT_NOT_FOUND||r===404}function isDraftRevisionConflict(e){return schemaApiErrorCode(e)===t.SchemaErrorCode.DRAFT_REVISION_CONFLICT}const r=new Set(e.DRAFT_CONFLICT_KINDS);function draftConflictChanges(e){if(!isDraftRevisionConflict(e))return[];let t=e.details?.changes;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.key==`string`&&typeof e.label==`string`&&typeof e.seen==`string`&&r.has(e.kind)):[]}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}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`}},BundleConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},BundleValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};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(t,...n){return[`/records`,...[t,...n].map(e.encodePathSegment)].join(`/`)}function resolveWithinBase(e,n){let r=e.endsWith(`/`)?e:`${e}/`,i=new URL(r),a=n.replace(/^\/+/,``),[o]=a.split(/[?#]/);if((o??``).split(`/`).some(e=>e===`..`||e===`.`))throw new t.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 t.ValidationError(`Request path "${n}" resolves outside the API base "${i.pathname}"`,[]);return s}const i=[400,1500];async function loadChunk(e){for(let t=0;;t++)try{return await e()}catch(e){let n=i[t];if(n===void 0)throw e;await new Promise(e=>setTimeout(e,n))}}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));else 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(t){let{baseUrl:n,onUnauthorized:r,getRetries:i=0}=t,a=t.timeoutMs??3e4,o=t.apiPrefix===void 0?void 0:trimSlashes(t.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(e){let n={"Content-Type":`application/json`,...headerRecord(await t.headers?.()),...headerRecord(e.headers)};return e.body instanceof FormData?withoutContentType(n):n}function observe(e){try{t.onResponse?.(e)}catch{}}async function fetchOnce(e,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=t.fetch??fetch,i=await headersFor(n);return await Promise.race([r(e,{...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)}else{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 streamWire(n,i,a={}){a.signal?.throwIfAborted();let{path:o,query:s,body:c,headers:l}=(0,e.splitOperationInput)(n,i??{}),u=buildUrl(o,s),{signal:d,onRequest:f}=a,p=t.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)}async function callWire(n,r,i,a){if(i.signal?.throwIfAborted(),n.response===`events`)return await streamWire(n,r,i);let{path:o,query:s,body:c,headers:l}=(0,e.splitOperationInput)(n,r??{});if(n.upload!==void 0&&i.onUploadProgress&&canReportUploadProgress(t)){i.signal?.throwIfAborted();let e=await t.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(o,s),method:n.method,headers:withoutContentType({...headerRecord(await t.headers?.()),...l}),token:e,form:multipartBody(n.upload.field,c),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>a(e?JSON.parse(e):null))}let u=n.upload===void 0?c===void 0?void 0:JSON.stringify(c):multipartBody(n.upload.field,c),d=n.response===`bytes`?readDownload:async e=>a(await readJson(e));return await send(o,{method:n.method,body:u,signal:i.signal,...l?{headers:l}:{},...i.keepalive?{keepalive:!0}:{}},{params:s,maxRetries:i.maxRetries,timeoutMs:i.timeoutMs},d)}return{async call(t,n,r={}){return await callWire(t,n,r,n=>(0,e.decodeOperationOutput)(t,n))},async callDeferred(t,n,r={}){return await callWire(t.wire,n,r,async n=>{r.signal?.throwIfAborted();let i=await decodeWithSignal(loadChunk(t.load),r.signal);return r.signal?.throwIfAborted(),(0,e.decodeOperationOutput)(i,n)})},stream:streamWire,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})}async function decodeWithSignal(e,t){if(!t)return e;let onAbort,n=new Promise((e,n)=>{onAbort=()=>n(t.reason),t.addEventListener(`abort`,onAbort,{once:!0}),t.aborted&&onAbort()});try{return await Promise.race([e,n])}finally{onAbort&&t.removeEventListener(`abort`,onAbort)}}Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return schemaApiErrorCode}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return recordsPath}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return BundleValidationError}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return StandardsRequestError}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return draftConflictChanges}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return isViewNotFound}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return isPermanentRefusal}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return refusalOf}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return StandardsAuthError}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return isObjectNotFound}}),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 isDraftRevisionConflict}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return readRefusal}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return BundleConflictError}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createHttpTransport}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return StandardsConfigurationError}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return schemaApiErrorDetails}});
|
package/dist/http.d.mts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
|
|
2
|
+
import { D as HttpTransportConfig, E as HttpTransport, F as createHttpTransport, T as DeferredHttpTransport, t as AppClient } from "./app-KQAbWX9h.mjs";
|
|
3
|
+
/** Dispatch HTTP immediately; canonical JSON codecs are resolved only after a successful response. */
|
|
4
|
+
export declare function createHttpAppClient(transport: Pick<DeferredHttpTransport, "callDeferred">): AppClient;
|
|
5
|
+
export { type AppClient, type DeferredHttpTransport, type HttpTransport, type HttpTransportConfig, createHttpTransport };
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
|
|
2
|
+
import { D as HttpTransportConfig, E as HttpTransport, F as createHttpTransport, T as DeferredHttpTransport, t as AppClient } from "./app-KQAbWX9h.js";
|
|
3
|
+
/** Dispatch HTTP immediately; canonical JSON codecs are resolved only after a successful response. */
|
|
4
|
+
export declare function createHttpAppClient(transport: Pick<DeferredHttpTransport, "callDeferred">): AppClient;
|
|
5
|
+
export { type AppClient, type DeferredHttpTransport, type HttpTransport, type HttpTransportConfig, createHttpTransport };
|
package/dist/http.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-CkB0bQlR.js");let t=require("@standards/schema/api/http"),n=require("@standards/schema/api/wire");function createHttpAppClient(e){let r={};for(let i of n.wireAppOperationGroups)for(let n of Object.values(i.operations)){let i=(0,t.operationGroup)(n.wire),a=n.wire.name.slice(i.length+1);r[i]??={},r[i][a]=(t,r)=>e.callDeferred(n,t,r)}return r}exports.createHttpAppClient=createHttpAppClient,exports.createHttpTransport=e.t;
|
package/dist/http.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{t as e}from"./http-transport-CijwtqPm.mjs";import{operationGroup as t}from"@standards/schema/api/http";import{wireAppOperationGroups as n}from"@standards/schema/api/wire";function createHttpAppClient(e){let r={};for(let i of n)for(let n of Object.values(i.operations)){let i=t(n.wire),a=n.wire.name.slice(i.length+1);r[i]??={},r[i][a]=(t,r)=>e.callDeferred(n,t,r)}return r}export{createHttpAppClient,e as createHttpTransport};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as CamelCase, C as RecordsQuery, D as UpdateManyError, E as UpdateManyEntry, M as SyncTransport, N as previewBundleSync, O as UpdateManyResult, P as syncBundle, S as RecordsExportOptions, T as UntypedRecordsQuery, _ as RecordCreateOptions, a as ObjectsOf, b as RecordUpdateOptions, c as StandardsConfig, d as createStandards, f as CreateManyError, g as FetchResult, h as DeleteManyResult, i as BundlesSyncPreview, j as SyncBundleOptions, k as createRecordsQuery, l as StandardsOf, m as DeleteManyError, n as AnyBundle, o as ObjectsOfBundles, p as CreateManyResult, r as BundlesSync, s as Standards, t as ActingStandards, u as StandardsTransport, v as RecordInput, w as UntypedBuilder, x as RecordsAggregateOptions, y as RecordUpdate } from "./create-standards-
|
|
3
|
-
import {
|
|
2
|
+
import { A as CamelCase, C as RecordsQuery, D as UpdateManyError, E as UpdateManyEntry, M as SyncTransport, N as previewBundleSync, O as UpdateManyResult, P as syncBundle, S as RecordsExportOptions, T as UntypedRecordsQuery, _ as RecordCreateOptions, a as ObjectsOf, b as RecordUpdateOptions, c as StandardsConfig, d as createStandards, f as CreateManyError, g as FetchResult, h as DeleteManyResult, i as BundlesSyncPreview, j as SyncBundleOptions, k as createRecordsQuery, l as StandardsOf, m as DeleteManyError, n as AnyBundle, o as ObjectsOfBundles, p as CreateManyResult, r as BundlesSync, s as Standards, t as ActingStandards, u as StandardsTransport, v as RecordInput, w as UntypedBuilder, x as RecordsAggregateOptions, y as RecordUpdate } from "./create-standards-DQ9jRm9v.mjs";
|
|
3
|
+
import { B as BundleValidationError, H as StandardsConfigurationError, I as createTransport, M as Transport, N as TransportConfig, O as MultipartRequestOptions, U as StandardsRequestError, V as StandardsAuthError, a as AttachTarget, c as UploadedFile, l as upload, o as UploadInput, s as UploadResult, u as uploadAll, z as BundleConflictError } from "./app-KQAbWX9h.mjs";
|
|
4
4
|
import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, 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
5
|
import { ActorId, OperationCaller, encodePathSegment } from "@standards/schema/api";
|
|
6
6
|
/**
|
|
@@ -32,4 +32,4 @@ export declare const standards: DefaultStandards;
|
|
|
32
32
|
* never leave `/records/<object>/`.
|
|
33
33
|
*/
|
|
34
34
|
export declare function recordsPath(objectName: string, ...segments: string[]): string;
|
|
35
|
-
export { type ActingStandards, type ActorId, type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type BundlesSyncPreview, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DefaultStandards, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type OperationCaller, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type Register, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, previewBundleSync, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
|
|
35
|
+
export { type ActingStandards, type ActorId, type ActorType, type AnyBundle, type AttachTarget, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type BundlesSyncPreview, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DefaultStandards, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type OperationCaller, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type Register, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UploadInput, type UploadResult, type UploadedFile, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, previewBundleSync, query, relation, richtext, rollup, select, status, syncBundle, text, today, upload, uploadAll, user };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as CamelCase, C as RecordsQuery, D as UpdateManyError, E as UpdateManyEntry, M as SyncTransport, N as previewBundleSync, O as UpdateManyResult, P as syncBundle, S as RecordsExportOptions, T as UntypedRecordsQuery, _ as RecordCreateOptions, a as ObjectsOf, b as RecordUpdateOptions, c as StandardsConfig, d as createStandards, f as CreateManyError, g as FetchResult, h as DeleteManyResult, i as BundlesSyncPreview, j as SyncBundleOptions, k as createRecordsQuery, l as StandardsOf, m as DeleteManyError, n as AnyBundle, o as ObjectsOfBundles, p as CreateManyResult, r as BundlesSync, s as Standards, t as ActingStandards, u as StandardsTransport, v as RecordInput, w as UntypedBuilder, x as RecordsAggregateOptions, y as RecordUpdate } from "./create-standards-
|
|
3
|
-
import {
|
|
2
|
+
import { A as CamelCase, C as RecordsQuery, D as UpdateManyError, E as UpdateManyEntry, M as SyncTransport, N as previewBundleSync, O as UpdateManyResult, P as syncBundle, S as RecordsExportOptions, T as UntypedRecordsQuery, _ as RecordCreateOptions, a as ObjectsOf, b as RecordUpdateOptions, c as StandardsConfig, d as createStandards, f as CreateManyError, g as FetchResult, h as DeleteManyResult, i as BundlesSyncPreview, j as SyncBundleOptions, k as createRecordsQuery, l as StandardsOf, m as DeleteManyError, n as AnyBundle, o as ObjectsOfBundles, p as CreateManyResult, r as BundlesSync, s as Standards, t as ActingStandards, u as StandardsTransport, v as RecordInput, w as UntypedBuilder, x as RecordsAggregateOptions, y as RecordUpdate } from "./create-standards-2cgqcAYC.js";
|
|
3
|
+
import { B as BundleValidationError, H as StandardsConfigurationError, I as createTransport, M as Transport, N as TransportConfig, O as MultipartRequestOptions, U as StandardsRequestError, V as StandardsAuthError, a as AttachTarget, c as UploadedFile, l as upload, o as UploadInput, s as UploadResult, u as uploadAll, z as BundleConflictError } from "./app-KQAbWX9h.js";
|
|
4
4
|
import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, 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
5
|
import { ActorId, OperationCaller, encodePathSegment } from "@standards/schema/api";
|
|
6
6
|
/**
|
|
@@ -32,4 +32,4 @@ export declare const standards: DefaultStandards;
|
|
|
32
32
|
* never leave `/records/<object>/`.
|
|
33
33
|
*/
|
|
34
34
|
export declare function recordsPath(objectName: string, ...segments: string[]): string;
|
|
35
|
-
export { type ActingStandards, type ActorId, type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type BundlesSyncPreview, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DefaultStandards, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type OperationCaller, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type Register, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, previewBundleSync, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
|
|
35
|
+
export { type ActingStandards, type ActorId, type ActorType, type AnyBundle, type AttachTarget, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type BundlesSyncPreview, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DefaultStandards, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type OperationCaller, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type Register, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UploadInput, type UploadResult, type UploadedFile, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, previewBundleSync, query, relation, richtext, rollup, select, status, syncBundle, text, today, upload, uploadAll, user };
|
package/dist/index.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("./create-standards-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-CJY4Dt0X.js"),t=require("./http-transport-CkB0bQlR.js"),n=require("./app-oCr8yvTF.js");let r=require("@standards/schema/api"),i=require("@standards/schema");const a=/* @__PURE__ */ new WeakMap;let o;function resolved(){let i=(0,r.registeredOperationHost)();if(i!==void 0){let t=a.get(i);return t===void 0&&(t=e.t(n.n(i.host),i.objects),a.set(i,t)),t}if(o===void 0){let n;try{n=e.r({})}catch(e){throw e instanceof t.u?new t.u(`The default standards instance found no Standards host in this process (a server embedding Standards registers one at boot), so it calls the API over HTTP, and ${e.message}`):e}o=e.t(t.n(n),[])}return o}function asOverHttp(e){throw new t.u(`standards.as() acts in process only, in a server that embeds Standards: over HTTP every call acts as the API key's actor. Use a key of the actor you want instead.`)}const s=new Proxy({},{get(e,t){if(typeof t==`symbol`||t===`then`)return;let n=resolved();return t===`as`&&!(`as`in n)?asOverHttp:Reflect.get(n,t)},has:(e,t)=>Reflect.has(resolved(),t),ownKeys:()=>Reflect.ownKeys(resolved()),getOwnPropertyDescriptor(e,t){let n=Reflect.getOwnPropertyDescriptor(resolved(),t);return n===void 0?void 0:{...n,configurable:!0}}});Object.defineProperty(exports,"BUNDLE_NAME_PATTERN",{enumerable:!0,get:function(){return i.BUNDLE_NAME_PATTERN}}),exports.BundleConflictError=t.s,exports.BundleValidationError=t.c,Object.defineProperty(exports,"DuplicateError",{enumerable:!0,get:function(){return i.DuplicateError}}),Object.defineProperty(exports,"ForbiddenError",{enumerable:!0,get:function(){return i.ForbiddenError}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get:function(){return i.NotFoundError}}),Object.defineProperty(exports,"SchemaError",{enumerable:!0,get:function(){return i.SchemaError}}),Object.defineProperty(exports,"SchemaErrorCode",{enumerable:!0,get:function(){return i.SchemaErrorCode}}),exports.StandardsAuthError=t.l,exports.StandardsConfigurationError=t.u,exports.StandardsRequestError=t.d,Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return i.ValidationError}}),Object.defineProperty(exports,"assertBundleName",{enumerable:!0,get:function(){return i.assertBundleName}}),Object.defineProperty(exports,"bundle",{enumerable:!0,get:function(){return i.bundle}}),Object.defineProperty(exports,"canonicalStringify",{enumerable:!0,get:function(){return i.canonicalStringify}}),Object.defineProperty(exports,"checkbox",{enumerable:!0,get:function(){return i.checkbox}}),Object.defineProperty(exports,"content",{enumerable:!0,get:function(){return i.content}}),exports.createRecordsQuery=e.i,exports.createStandards=e.n,exports.createTransport=t.n,Object.defineProperty(exports,"currency",{enumerable:!0,get:function(){return i.currency}}),Object.defineProperty(exports,"currentActor",{enumerable:!0,get:function(){return i.currentActor}}),Object.defineProperty(exports,"date",{enumerable:!0,get:function(){return i.date}}),Object.defineProperty(exports,"detailView",{enumerable:!0,get:function(){return i.detailView}}),Object.defineProperty(exports,"document",{enumerable:!0,get:function(){return i.document}}),Object.defineProperty(exports,"encodePathSegment",{enumerable:!0,get:function(){return r.encodePathSegment}}),Object.defineProperty(exports,"formula",{enumerable:!0,get:function(){return i.formula}}),Object.defineProperty(exports,"group",{enumerable:!0,get:function(){return i.group}}),Object.defineProperty(exports,"listView",{enumerable:!0,get:function(){return i.listView}}),Object.defineProperty(exports,"location",{enumerable:!0,get:function(){return i.location}}),Object.defineProperty(exports,"multiselect",{enumerable:!0,get:function(){return i.multiselect}}),Object.defineProperty(exports,"now",{enumerable:!0,get:function(){return i.now}}),Object.defineProperty(exports,"number",{enumerable:!0,get:function(){return i.number}}),Object.defineProperty(exports,"object",{enumerable:!0,get:function(){return i.object}}),Object.defineProperty(exports,"phone",{enumerable:!0,get:function(){return i.phone}}),exports.previewBundleSync=e.s,Object.defineProperty(exports,"query",{enumerable:!0,get:function(){return i.query}}),exports.recordsPath=t.a,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return i.relation}}),Object.defineProperty(exports,"richtext",{enumerable:!0,get:function(){return i.richtext}}),Object.defineProperty(exports,"rollup",{enumerable:!0,get:function(){return i.rollup}}),Object.defineProperty(exports,"select",{enumerable:!0,get:function(){return i.select}}),exports.standards=s,Object.defineProperty(exports,"status",{enumerable:!0,get:function(){return i.status}}),exports.syncBundle=e.c,Object.defineProperty(exports,"text",{enumerable:!0,get:function(){return i.text}}),Object.defineProperty(exports,"today",{enumerable:!0,get:function(){return i.today}}),exports.upload=n.r,exports.uploadAll=n.i,Object.defineProperty(exports,"user",{enumerable:!0,get:function(){return i.user}});
|
package/dist/index.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{c as e,i as t,n,r,s as i,t as a}from"./create-standards-
|
|
2
|
+
import{c as e,i as t,n,r,s as i,t as a}from"./create-standards-Gw85x9Mb.mjs";import{a as o,c as s,d as c,l,n as u,s as d,u as f}from"./http-transport-CijwtqPm.mjs";import{i as p,n as m,r as h}from"./app-DQ0e_dZD.mjs";import{BUNDLE_NAME_PATTERN as g,DuplicateError as _,ForbiddenError as v,NotFoundError as y,SchemaError as b,SchemaErrorCode as x,ValidationError as S,assertBundleName as C,bundle as w,canonicalStringify as T,checkbox as E,content as D,currency as O,currentActor as ee,date as k,detailView as A,document as j,formula as M,group as N,listView as P,location as F,multiselect as I,now as L,number as R,object as z,phone as B,query as V,relation as H,richtext as U,rollup as W,select as G,status as K,text as q,today as J,user as Y}from"@standards/schema";import{encodePathSegment as X,registeredOperationHost as Z}from"@standards/schema/api";const Q=/* @__PURE__ */ new WeakMap;let $;function resolved(){let e=Z();if(e!==void 0){let t=Q.get(e);return t===void 0&&(t=a(m(e.host),e.objects),Q.set(e,t)),t}if($===void 0){let e;try{e=r({})}catch(e){throw e instanceof f?new f(`The default standards instance found no Standards host in this process (a server embedding Standards registers one at boot), so it calls the API over HTTP, and ${e.message}`):e}$=a(u(e),[])}return $}function asOverHttp(e){throw new f(`standards.as() acts in process only, in a server that embeds Standards: over HTTP every call acts as the API key's actor. Use a key of the actor you want instead.`)}const te=new Proxy({},{get(e,t){if(typeof t==`symbol`||t===`then`)return;let n=resolved();return t===`as`&&!(`as`in n)?asOverHttp:Reflect.get(n,t)},has:(e,t)=>Reflect.has(resolved(),t),ownKeys:()=>Reflect.ownKeys(resolved()),getOwnPropertyDescriptor(e,t){let n=Reflect.getOwnPropertyDescriptor(resolved(),t);return n===void 0?void 0:{...n,configurable:!0}}});export{g as BUNDLE_NAME_PATTERN,d as BundleConflictError,s as BundleValidationError,_ as DuplicateError,v as ForbiddenError,y as NotFoundError,b as SchemaError,x as SchemaErrorCode,l as StandardsAuthError,f as StandardsConfigurationError,c as StandardsRequestError,S as ValidationError,C as assertBundleName,w as bundle,T as canonicalStringify,E as checkbox,D as content,t as createRecordsQuery,n as createStandards,u as createTransport,O as currency,ee as currentActor,k as date,A as detailView,j as document,X as encodePathSegment,M as formula,N as group,P as listView,F as location,I as multiselect,L as now,R as number,z as object,B as phone,i as previewBundleSync,V as query,o as recordsPath,H as relation,U as richtext,W as rollup,G as select,te as standards,K as status,e as syncBundle,q as text,J as today,h as upload,p as uploadAll,Y as user};
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { l as StandardsOf, n as AnyBundle, o as ObjectsOfBundles } from "./create-standards-
|
|
3
|
-
import "./app-
|
|
2
|
+
import { l as StandardsOf, n as AnyBundle, o as ObjectsOfBundles } from "./create-standards-DQ9jRm9v.mjs";
|
|
3
|
+
import "./app-KQAbWX9h.mjs";
|
|
4
4
|
import { ExtractRecord, ExtractRecordInputStrict, ObjectBuilderLike } from "@standards/schema";
|
|
5
5
|
/**
|
|
6
6
|
* A filter rule the in-memory workspace does not serve. The server answers
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { l as StandardsOf, n as AnyBundle, o as ObjectsOfBundles } from "./create-standards-
|
|
3
|
-
import "./app-
|
|
2
|
+
import { l as StandardsOf, n as AnyBundle, o as ObjectsOfBundles } from "./create-standards-2cgqcAYC.js";
|
|
3
|
+
import "./app-KQAbWX9h.js";
|
|
4
4
|
import { ExtractRecord, ExtractRecordInputStrict, ObjectBuilderLike } from "@standards/schema";
|
|
5
5
|
/**
|
|
6
6
|
* A filter rule the in-memory workspace does not serve. The server answers
|
package/dist/testing.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("./create-standards-Drs4y84m.js"),t=require("./app-BUHCJ8SR.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=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),a=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),o=/* @__PURE__ */ new Set([`number`,`currency`]),s=/* @__PURE__ */ new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/,l=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;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}const u=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?l.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<u?null:s}function nextDay(e){let t=/* @__PURE__ */ 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 isTimedDate(e){return e?.type===`date`&&e.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,r){let i=r.attributes.find(e=>e.name===t.attribute)?.type,s=attributeValue(e,t.attribute),c=i!==void 0&&o.has(i),l=textOf(t.value),u=l===null?void 0:(0,n.foldText)(l),d=textOf(s),f=d===null?null:(0,n.foldText)(d);if((i===`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,s,t.value,a.has(t.attribute));switch(t.operator){case`is`:return i===`checkbox`||i===void 0&&typeof t.value==`boolean`?t.value===!0?s===!0:s!==!0:textOf(s)!==null&&textOf(s)===textOf(t.value);case`is_not`:return textOf(s)===null||textOf(s)!==textOf(t.value);case`contains`:return Array.isArray(s)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>s.map(String).includes(e)):f!==null&&u!==void 0&&f.includes(u);case`not_contains`:return s==null||!matchesRule(e,{...t,operator:`contains`},r);case`starts_with`:return f!==null&&u!==void 0&&f.startsWith(u);case`ends_with`:return f!==null&&u!==void 0&&f.endsWith(u);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(s,t.value,c);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(s);case`is_not_empty`:return!isEmptyValue(s);case`any_of`:{let e=members(t.value);return e===null||e.length===0||s==null?!1:Array.isArray(s)?s.some(t=>e.includes(String(t))):e.includes(textOf(s)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||s==null?!0:Array.isArray(s)?!s.some(t=>e.includes(String(t))):!e.includes(textOf(s)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const d=/* @__PURE__ */ 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(!d.has(n.operator)||n.attribute.startsWith(`metadata.`)||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);if(i&&s.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}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),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let s=sortKey(e,i.attribute,t),c=sortKey(r,i.attribute,t),l=isOptionKey(s)?s.value:s,u=isOptionKey(c)?c.value:c,d=textOf(l)===null,f=textOf(u)===null;if(d||f){if(d&&f)continue;return d?1:-1}if(isOptionKey(s)&&isOptionKey(c)){let e=compareOptionKeys(s,c,i.direction);if(e!==0)return e;continue}let p=compare(s,c,a!==void 0&&o.has(a))??0;if(p!==0)return i.direction===`desc`?-p:p}return 0}}const f=`SCHEMA_RECORD_NOT_FOUND`,p=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,m=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getObjectSystemAttributes)(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of m)delete t[e];return t}function boundOf(e,n,r){if(e==null)return r;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new t.h(400,`${n} must be a non-negative integer`);return e}function errorFor(e,n,r){return e===401||e===403?new t.p(e,n,r):new t.h(e,n,r)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof n.ValidationError?new t.h(400,e.message,e.code):e}}function notServed(e,n){return new t.h(501,`The in-memory test workspace does not serve ${e} ${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=/* @__PURE__ */ new Map;for(let t of i.builders){let n=e.a(t);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=/* @__PURE__ */ new Set,c=null,l=0,u=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-${(u++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(e){let n=a.get(e),r=o.get(e);if(!(n&&r))throw new t.h(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:a,...o}=t,c=now(),l={id:r??newId(),values:wire(o),createdAt:isoOf(i,c),updatedAt:isoOf(a,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),s.add(l.id),l}function find(e,n){let r=objectOf(e).records.find(e=>e.id===n);if(!r)throw new t.h(404,readNotFound(n),f);return r}function requireWritable(e,n){if(!objectOf(e).records.some(e=>e.id===n))throw new t.h(404,writeNotFound(n),f)}function update(e,n,r){let i=objectOf(e).records.find(e=>e.id===n);if(!i)throw new t.h(404,writeNotFound(n),f);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(e,n){let{records:r}=objectOf(e),i=r.findIndex(e=>e.id===n);if(i===-1)throw new t.h(404,writeNotFound(n),f);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(e,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new t.h(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(e).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries())if(!(0,n.isPlainRecord)(c))i.push({index:s,error:`Record data must be an object`});else try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(e,withoutSystemKeys(c)))}catch(e){if(!(e instanceof t.h))throw e;i.push({index:s,error:e.message})}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!(0,n.isPlainRecord)(c))throw new t.h(400,`Update data must be an object`,p);requireWritable(e,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(e,s,c))}catch(e){if(!(e instanceof t.h))throw e;i.push({id:s,error:e.message,code:e.code??p})}return{updated:r,errors:i}}let s=[],c=[];for(let t of a)try{remove(e,t),s.push(t)}catch{c.push({id:t,error:writeNotFound(t),code:f})}return{deleted:s,errors:c}}function operation(e,r,i){let o=Array.isArray(i.steps)?i.steps:[],[s]=o;if(o.length!==1||!(0,n.isPlainRecord)(s)||s.kind!==`record.set`)throw notServed(e,r);let c=String(s.recordId),l=(0,n.isPlainRecord)(s.values)?s.values:{},u=[...a].find(([e,t])=>(t.id??e)===s.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(u===void 0||!objectOf(u).records.some(e=>e.id===c))return answer({status:`error`,recordId:c,code:f});try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(u).definition),l))}catch(e){if(!(e instanceof t.h))throw e;let n=e.code??p;return answer({status:`error`,recordId:c,code:n,...n===p&&{message:e.message}})}return answer({status:`applied`,record:update(u,c,l)})}function route(e,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(e===`POST`&&a===`operations`&&o===void 0)return operation(e,r,(0,n.isPlainRecord)(i)?i:{});if(a!==`records`||o===void 0||c.length>0)throw notServed(e,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=(0,n.isPlainRecord)(i)?i:{};if(e===`POST`&&u===void 0){let e=(0,n.isPlainRecord)(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(e===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(e===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(e,r);if(e===`GET`)return find(l,u);if(e===`PUT`||e===`PATCH`){if(Object.keys(d).length===0)throw new t.h(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(e===`DELETE`)return remove(l,u),null;throw notServed(e,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 d={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:i}=(0,r.splitOperationInput)(e,t??{});return request(e.method,n,i).then(t=>(0,r.decodeOperationOutput)(e,t??null))}),stream:(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:d,get:d.get,post:d.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(t){let n=t.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:n}),flatten=(t,n)=>e.o(i.definitionOf(t),(0,r.decodeOperationOutput)(r.recordsOperations.get,JSON.parse(JSON.stringify(n))));return{db:e.t(i.transport,n),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-CJY4Dt0X.js"),t=require("./http-transport-CkB0bQlR.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=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),a=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),o=/* @__PURE__ */ new Set([`number`,`currency`]),s=/* @__PURE__ */ new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/,l=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;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}const u=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?l.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<u?null:s}function nextDay(e){let t=/* @__PURE__ */ 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 isTimedDate(e){return e?.type===`date`&&e.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,r){let i=r.attributes.find(e=>e.name===t.attribute)?.type,s=attributeValue(e,t.attribute),c=i!==void 0&&o.has(i),l=textOf(t.value),u=l===null?void 0:(0,n.foldText)(l),d=textOf(s),f=d===null?null:(0,n.foldText)(d);if((i===`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,s,t.value,a.has(t.attribute));switch(t.operator){case`is`:return i===`checkbox`||i===void 0&&typeof t.value==`boolean`?t.value===!0?s===!0:s!==!0:textOf(s)!==null&&textOf(s)===textOf(t.value);case`is_not`:return textOf(s)===null||textOf(s)!==textOf(t.value);case`contains`:return Array.isArray(s)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>s.map(String).includes(e)):f!==null&&u!==void 0&&f.includes(u);case`not_contains`:return s==null||!matchesRule(e,{...t,operator:`contains`},r);case`starts_with`:return f!==null&&u!==void 0&&f.startsWith(u);case`ends_with`:return f!==null&&u!==void 0&&f.endsWith(u);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(s,t.value,c);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(s);case`is_not_empty`:return!isEmptyValue(s);case`any_of`:{let e=members(t.value);return e===null||e.length===0||s==null?!1:Array.isArray(s)?s.some(t=>e.includes(String(t))):e.includes(textOf(s)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||s==null?!0:Array.isArray(s)?!s.some(t=>e.includes(String(t))):!e.includes(textOf(s)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const d=/* @__PURE__ */ 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(!d.has(n.operator)||n.attribute.startsWith(`metadata.`)||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);if(i&&s.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}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),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let s=sortKey(e,i.attribute,t),c=sortKey(r,i.attribute,t),l=isOptionKey(s)?s.value:s,u=isOptionKey(c)?c.value:c,d=textOf(l)===null,f=textOf(u)===null;if(d||f){if(d&&f)continue;return d?1:-1}if(isOptionKey(s)&&isOptionKey(c)){let e=compareOptionKeys(s,c,i.direction);if(e!==0)return e;continue}let p=compare(s,c,a!==void 0&&o.has(a))??0;if(p!==0)return i.direction===`desc`?-p:p}return 0}}const f=`SCHEMA_RECORD_NOT_FOUND`,p=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,m=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getObjectSystemAttributes)(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of m)delete t[e];return t}function boundOf(e,n,r){if(e==null)return r;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new t.d(400,`${n} must be a non-negative integer`);return e}function errorFor(e,n,r){return e===401||e===403?new t.l(e,n,r):new t.d(e,n,r)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof n.ValidationError?new t.d(400,e.message,e.code):e}}function notServed(e,n){return new t.d(501,`The in-memory test workspace does not serve ${e} ${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=/* @__PURE__ */ new Map;for(let t of i.builders){let n=e.a(t);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=/* @__PURE__ */ new Set,c=null,l=0,u=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-${(u++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(e){let n=a.get(e),r=o.get(e);if(!(n&&r))throw new t.d(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:a,...o}=t,c=now(),l={id:r??newId(),values:wire(o),createdAt:isoOf(i,c),updatedAt:isoOf(a,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),s.add(l.id),l}function find(e,n){let r=objectOf(e).records.find(e=>e.id===n);if(!r)throw new t.d(404,readNotFound(n),f);return r}function requireWritable(e,n){if(!objectOf(e).records.some(e=>e.id===n))throw new t.d(404,writeNotFound(n),f)}function update(e,n,r){let i=objectOf(e).records.find(e=>e.id===n);if(!i)throw new t.d(404,writeNotFound(n),f);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(e,n){let{records:r}=objectOf(e),i=r.findIndex(e=>e.id===n);if(i===-1)throw new t.d(404,writeNotFound(n),f);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(e,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new t.d(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(e).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries())if(!(0,n.isPlainRecord)(c))i.push({index:s,error:`Record data must be an object`});else try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(e,withoutSystemKeys(c)))}catch(e){if(!(e instanceof t.d))throw e;i.push({index:s,error:e.message})}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!(0,n.isPlainRecord)(c))throw new t.d(400,`Update data must be an object`,p);requireWritable(e,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(e,s,c))}catch(e){if(!(e instanceof t.d))throw e;i.push({id:s,error:e.message,code:e.code??p})}return{updated:r,errors:i}}let s=[],c=[];for(let t of a)try{remove(e,t),s.push(t)}catch{c.push({id:t,error:writeNotFound(t),code:f})}return{deleted:s,errors:c}}function operation(e,r,i){let o=Array.isArray(i.steps)?i.steps:[],[s]=o;if(o.length!==1||!(0,n.isPlainRecord)(s)||s.kind!==`record.set`)throw notServed(e,r);let c=String(s.recordId),l=(0,n.isPlainRecord)(s.values)?s.values:{},u=[...a].find(([e,t])=>(t.id??e)===s.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(u===void 0||!objectOf(u).records.some(e=>e.id===c))return answer({status:`error`,recordId:c,code:f});try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(u).definition),l))}catch(e){if(!(e instanceof t.d))throw e;let n=e.code??p;return answer({status:`error`,recordId:c,code:n,...n===p&&{message:e.message}})}return answer({status:`applied`,record:update(u,c,l)})}function route(e,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(e===`POST`&&a===`operations`&&o===void 0)return operation(e,r,(0,n.isPlainRecord)(i)?i:{});if(a!==`records`||o===void 0||c.length>0)throw notServed(e,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=(0,n.isPlainRecord)(i)?i:{};if(e===`POST`&&u===void 0){let e=(0,n.isPlainRecord)(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(e===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(e===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(e,r);if(e===`GET`)return find(l,u);if(e===`PUT`||e===`PATCH`){if(Object.keys(d).length===0)throw new t.d(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(e===`DELETE`)return remove(l,u),null;throw notServed(e,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 d={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:i}=(0,r.splitOperationInput)(e,t??{});return request(e.method,n,i).then(t=>(0,r.decodeOperationOutput)(e,t??null))}),stream:(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:d,get:d.get,post:d.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(t){let n=t.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:n}),flatten=(t,n)=>e.o(i.definitionOf(t),(0,r.decodeOperationOutput)(r.recordsOperations.get,JSON.parse(JSON.stringify(n))));return{db:e.t(i.transport,n),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;
|
package/dist/testing.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{a as e,o as t,t as n}from"./create-standards-Dq4tC8T6.mjs";import{h as r,p as i}from"./app-Cer-0oL4.mjs";import{ValidationError as a,foldText as o,getObjectSystemAttributes as s,isPlainRecord as c,rejectUnknownAttributesOrThrow as l,validateQualifiedRule as u}from"@standards/schema";import{decodeOperationOutput as d,recordsOperations as f,splitOperationInput as p}from"@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 m=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),h=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),g=/* @__PURE__ */ new Set([`number`,`currency`]),_=/* @__PURE__ */ new Set([`select`,`status`]),v=/^\d{4}-\d{2}-\d{2}/,y=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(m.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||!v.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const b=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?y.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<b?null:s}function nextDay(e){let t=/* @__PURE__ */ 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 isTimedDate(e){return e?.type===`date`&&e.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),a=r!==void 0&&g.has(r),s=textOf(t.value),c=s===null?void 0:o(s),l=textOf(i),u=l===null?null:o(l);if((r===`date`||h.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,h.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)):u!==null&&c!==void 0&&u.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return u!==null&&c!==void 0&&u.startsWith(c);case`ends_with`:return u!==null&&c!==void 0&&u.endsWith(c);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,a);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 x=/* @__PURE__ */ 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(!x.has(n.operator)||n.attribute.startsWith(`metadata.`)||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);if(i&&_.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}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),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let o=sortKey(e,i.attribute,t),s=sortKey(r,i.attribute,t),c=isOptionKey(o)?o.value:o,l=isOptionKey(s)?s.value:s,u=textOf(c)===null,d=textOf(l)===null;if(u||d){if(u&&d)continue;return u?1:-1}if(isOptionKey(o)&&isOptionKey(s)){let e=compareOptionKeys(o,s,i.direction);if(e!==0)return e;continue}let f=compare(o,s,a!==void 0&&g.has(a))??0;if(f!==0)return i.direction===`desc`?-f:f}return 0}}const S=`SCHEMA_RECORD_NOT_FOUND`,C=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,w=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...s(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of w)delete t[e];return t}function boundOf(e,t,n){if(e==null)return n;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new r(400,`${t} must be a non-negative integer`);return e}function errorFor(e,t,n){return e===401||e===403?new i(e,t,n):new r(e,t,n)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof a?new r(400,e.message,e.code):e}}function notServed(e,t){return new r(501,`The in-memory test workspace does not serve ${e} ${t}: 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(t){let n=/* @__PURE__ */ new Map;for(let r of t.builders){let t=e(r);n.set(t.name,t)}let i=new Map([...n.keys()].map(e=>[e,[]])),a=/* @__PURE__ */ new Set,o=null,s=0,f=1;function now(){return s=Math.max(Date.now(),s+1),new Date(s).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(a.has(e));return e}function objectOf(e){let t=n.get(e),a=i.get(e);if(!(t&&a))throw new r(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:t,records:a}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:o,...s}=t,c=now(),l={id:r??newId(),values:wire(s),createdAt:isoOf(i,c),updatedAt:isoOf(o,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),a.add(l.id),l}function find(e,t){let n=objectOf(e).records.find(e=>e.id===t);if(!n)throw new r(404,readNotFound(t),S);return n}function requireWritable(e,t){if(!objectOf(e).records.some(e=>e.id===t))throw new r(404,writeNotFound(t),S)}function update(e,t,n){let i=objectOf(e).records.find(e=>e.id===t);if(!i)throw new r(404,writeNotFound(t),S);return Object.assign(i.values,withoutSystemKeys(n)),i.updatedAt=now(),i}function remove(e,t){let{records:n}=objectOf(e),i=n.findIndex(e=>e.id===t);if(i===-1)throw new r(404,writeNotFound(t),S);n.splice(i,1)}function list(e,t,n){let{definition:r,records:i}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>u(structuredClone(e),{attributes:r.attributes}));assertServedOperators(t.filters,r);let a=Math.min(boundOf(t.limit,`limit`,20),1e3),o=boundOf(t.offset,`offset`,0);if(a===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let s=n?t.q:void 0,c=i.filter(e=>matchesFilters(e,t.filters,r)).filter(e=>s===void 0||matchesSearch(e,s)).sort(compareRecords(t.sorts,r)),l=c.slice(o,o+a);return{data:l,page:{hasMore:o+l.length<c.length,total:null,countMode:`none`}}}function bulk(e,t,n){let i=n.records??n.updates??n.ids;if(!Array.isArray(i)||i.length>100)throw new r(400,`A bulk request carries at most 100 items.`);let a=withSystemAttributes(objectOf(e).definition);if(t===`bulk-create`){let t=[],n=[];for(let[o,s]of i.entries())if(!c(s))n.push({index:o,error:`Record data must be an object`});else try{asTheServerValidates(()=>l(a,s)),t.push(insert(e,withoutSystemKeys(s)))}catch(e){if(!(e instanceof r))throw e;n.push({index:o,error:e.message})}return{created:t,errors:n}}if(t===`bulk-update`){let t=[],n=[];for(let{id:o,data:s}of i)try{if(!c(s))throw new r(400,`Update data must be an object`,C);requireWritable(e,o),asTheServerValidates(()=>l(a,s)),t.push(update(e,o,s))}catch(e){if(!(e instanceof r))throw e;n.push({id:o,error:e.message,code:e.code??C})}return{updated:t,errors:n}}let o=[],s=[];for(let t of i)try{remove(e,t),o.push(t)}catch{s.push({id:t,error:writeNotFound(t),code:S})}return{deleted:o,errors:s}}function operation(e,t,i){let a=Array.isArray(i.steps)?i.steps:[],[o]=a;if(a.length!==1||!c(o)||o.kind!==`record.set`)throw notServed(e,t);let s=String(o.recordId),u=c(o.values)?o.values:{},d=[...n].find(([e,t])=>(t.id??e)===o.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(d===void 0||!objectOf(d).records.some(e=>e.id===s))return answer({status:`error`,recordId:s,code:S});try{asTheServerValidates(()=>l(withSystemAttributes(objectOf(d).definition),u))}catch(e){if(!(e instanceof r))throw e;let t=e.code??C;return answer({status:`error`,recordId:s,code:t,...t===C&&{message:e.message}})}return answer({status:`applied`,record:update(d,s,u)})}function route(e,t,n){let[i,a,o,...s]=t.replace(/^\/+/,``).split(`/`);if(e===`POST`&&i===`operations`&&a===void 0)return operation(e,t,c(n)?n:{});if(i!==`records`||a===void 0||s.length>0)throw notServed(e,t);let u=decodeURIComponent(a),d=o===void 0?void 0:decodeURIComponent(o),f=c(n)?n:{};if(e===`POST`&&d===void 0){let e=c(f.data)?f.data:{};return asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),e)),insert(u,withoutSystemKeys(e))}if(e===`POST`&&(d===`list`||d===`search`))return list(u,f,d===`search`);if(e===`POST`&&d?.startsWith(`bulk-`))return bulk(u,d,f);if(d===void 0)throw notServed(e,t);if(e===`GET`)return find(u,d);if(e===`PUT`||e===`PATCH`){if(Object.keys(f).length===0)throw new r(400,`Request body cannot be empty`);return requireWritable(u,d),asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),f)),update(u,d,f)}if(e===`DELETE`)return remove(u,d),null;throw notServed(e,t)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(o){let{status:e,failure:t}=o;throw o=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let m={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:r}=p(e,t??{});return request(e.method,n,r).then(t=>d(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=p(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:m,get:m.get,post:m.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){o={status:e,failure:t}}}}function createTestStandards(e){let r=e.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:r}),flatten=(e,n)=>t(i.definitionOf(e),d(f.get,JSON.parse(JSON.stringify(n))));return{db:n(i.transport,r),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}export{UnsupportedFilterOperatorError,createTestStandards};
|
|
2
|
+
import{a as e,o as t,t as n}from"./create-standards-Gw85x9Mb.mjs";import{d as r,l as i}from"./http-transport-CijwtqPm.mjs";import{ValidationError as a,foldText as o,getObjectSystemAttributes as s,isPlainRecord as c,rejectUnknownAttributesOrThrow as l,validateQualifiedRule as u}from"@standards/schema";import{decodeOperationOutput as d,recordsOperations as f,splitOperationInput as p}from"@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 m=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),h=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),g=/* @__PURE__ */ new Set([`number`,`currency`]),_=/* @__PURE__ */ new Set([`select`,`status`]),v=/^\d{4}-\d{2}-\d{2}/,y=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(m.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||!v.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const b=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?y.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<b?null:s}function nextDay(e){let t=/* @__PURE__ */ 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 isTimedDate(e){return e?.type===`date`&&e.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),a=r!==void 0&&g.has(r),s=textOf(t.value),c=s===null?void 0:o(s),l=textOf(i),u=l===null?null:o(l);if((r===`date`||h.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,h.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)):u!==null&&c!==void 0&&u.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return u!==null&&c!==void 0&&u.startsWith(c);case`ends_with`:return u!==null&&c!==void 0&&u.endsWith(c);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,a);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 x=/* @__PURE__ */ 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(!x.has(n.operator)||n.attribute.startsWith(`metadata.`)||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);if(i&&_.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}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),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let o=sortKey(e,i.attribute,t),s=sortKey(r,i.attribute,t),c=isOptionKey(o)?o.value:o,l=isOptionKey(s)?s.value:s,u=textOf(c)===null,d=textOf(l)===null;if(u||d){if(u&&d)continue;return u?1:-1}if(isOptionKey(o)&&isOptionKey(s)){let e=compareOptionKeys(o,s,i.direction);if(e!==0)return e;continue}let f=compare(o,s,a!==void 0&&g.has(a))??0;if(f!==0)return i.direction===`desc`?-f:f}return 0}}const S=`SCHEMA_RECORD_NOT_FOUND`,C=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,w=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...s(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of w)delete t[e];return t}function boundOf(e,t,n){if(e==null)return n;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new r(400,`${t} must be a non-negative integer`);return e}function errorFor(e,t,n){return e===401||e===403?new i(e,t,n):new r(e,t,n)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof a?new r(400,e.message,e.code):e}}function notServed(e,t){return new r(501,`The in-memory test workspace does not serve ${e} ${t}: 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(t){let n=/* @__PURE__ */ new Map;for(let r of t.builders){let t=e(r);n.set(t.name,t)}let i=new Map([...n.keys()].map(e=>[e,[]])),a=/* @__PURE__ */ new Set,o=null,s=0,f=1;function now(){return s=Math.max(Date.now(),s+1),new Date(s).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(a.has(e));return e}function objectOf(e){let t=n.get(e),a=i.get(e);if(!(t&&a))throw new r(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:t,records:a}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:o,...s}=t,c=now(),l={id:r??newId(),values:wire(s),createdAt:isoOf(i,c),updatedAt:isoOf(o,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),a.add(l.id),l}function find(e,t){let n=objectOf(e).records.find(e=>e.id===t);if(!n)throw new r(404,readNotFound(t),S);return n}function requireWritable(e,t){if(!objectOf(e).records.some(e=>e.id===t))throw new r(404,writeNotFound(t),S)}function update(e,t,n){let i=objectOf(e).records.find(e=>e.id===t);if(!i)throw new r(404,writeNotFound(t),S);return Object.assign(i.values,withoutSystemKeys(n)),i.updatedAt=now(),i}function remove(e,t){let{records:n}=objectOf(e),i=n.findIndex(e=>e.id===t);if(i===-1)throw new r(404,writeNotFound(t),S);n.splice(i,1)}function list(e,t,n){let{definition:r,records:i}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>u(structuredClone(e),{attributes:r.attributes}));assertServedOperators(t.filters,r);let a=Math.min(boundOf(t.limit,`limit`,20),1e3),o=boundOf(t.offset,`offset`,0);if(a===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let s=n?t.q:void 0,c=i.filter(e=>matchesFilters(e,t.filters,r)).filter(e=>s===void 0||matchesSearch(e,s)).sort(compareRecords(t.sorts,r)),l=c.slice(o,o+a);return{data:l,page:{hasMore:o+l.length<c.length,total:null,countMode:`none`}}}function bulk(e,t,n){let i=n.records??n.updates??n.ids;if(!Array.isArray(i)||i.length>100)throw new r(400,`A bulk request carries at most 100 items.`);let a=withSystemAttributes(objectOf(e).definition);if(t===`bulk-create`){let t=[],n=[];for(let[o,s]of i.entries())if(!c(s))n.push({index:o,error:`Record data must be an object`});else try{asTheServerValidates(()=>l(a,s)),t.push(insert(e,withoutSystemKeys(s)))}catch(e){if(!(e instanceof r))throw e;n.push({index:o,error:e.message})}return{created:t,errors:n}}if(t===`bulk-update`){let t=[],n=[];for(let{id:o,data:s}of i)try{if(!c(s))throw new r(400,`Update data must be an object`,C);requireWritable(e,o),asTheServerValidates(()=>l(a,s)),t.push(update(e,o,s))}catch(e){if(!(e instanceof r))throw e;n.push({id:o,error:e.message,code:e.code??C})}return{updated:t,errors:n}}let o=[],s=[];for(let t of i)try{remove(e,t),o.push(t)}catch{s.push({id:t,error:writeNotFound(t),code:S})}return{deleted:o,errors:s}}function operation(e,t,i){let a=Array.isArray(i.steps)?i.steps:[],[o]=a;if(a.length!==1||!c(o)||o.kind!==`record.set`)throw notServed(e,t);let s=String(o.recordId),u=c(o.values)?o.values:{},d=[...n].find(([e,t])=>(t.id??e)===o.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(d===void 0||!objectOf(d).records.some(e=>e.id===s))return answer({status:`error`,recordId:s,code:S});try{asTheServerValidates(()=>l(withSystemAttributes(objectOf(d).definition),u))}catch(e){if(!(e instanceof r))throw e;let t=e.code??C;return answer({status:`error`,recordId:s,code:t,...t===C&&{message:e.message}})}return answer({status:`applied`,record:update(d,s,u)})}function route(e,t,n){let[i,a,o,...s]=t.replace(/^\/+/,``).split(`/`);if(e===`POST`&&i===`operations`&&a===void 0)return operation(e,t,c(n)?n:{});if(i!==`records`||a===void 0||s.length>0)throw notServed(e,t);let u=decodeURIComponent(a),d=o===void 0?void 0:decodeURIComponent(o),f=c(n)?n:{};if(e===`POST`&&d===void 0){let e=c(f.data)?f.data:{};return asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),e)),insert(u,withoutSystemKeys(e))}if(e===`POST`&&(d===`list`||d===`search`))return list(u,f,d===`search`);if(e===`POST`&&d?.startsWith(`bulk-`))return bulk(u,d,f);if(d===void 0)throw notServed(e,t);if(e===`GET`)return find(u,d);if(e===`PUT`||e===`PATCH`){if(Object.keys(f).length===0)throw new r(400,`Request body cannot be empty`);return requireWritable(u,d),asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),f)),update(u,d,f)}if(e===`DELETE`)return remove(u,d),null;throw notServed(e,t)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(o){let{status:e,failure:t}=o;throw o=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let m={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:r}=p(e,t??{});return request(e.method,n,r).then(t=>d(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=p(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:m,get:m.get,post:m.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){o={status:e,failure:t}}}}function createTestStandards(e){let r=e.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:r}),flatten=(e,n)=>t(i.definitionOf(e),d(f.get,JSON.parse(JSON.stringify(n))));return{db:n(i.transport,r),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}export{UnsupportedFilterOperatorError,createTestStandards};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@standards/client",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.447",
|
|
4
4
|
"description": "Public TypeScript client for Standards: declare schema sources with the fluent builders, sync them to a hosted tenant, and operate typed records over the REST API.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -35,6 +35,16 @@
|
|
|
35
35
|
"types": "./dist/app.d.ts",
|
|
36
36
|
"default": "./dist/app.js"
|
|
37
37
|
}
|
|
38
|
+
},
|
|
39
|
+
"./http": {
|
|
40
|
+
"import": {
|
|
41
|
+
"types": "./dist/http.d.mts",
|
|
42
|
+
"default": "./dist/http.mjs"
|
|
43
|
+
},
|
|
44
|
+
"require": {
|
|
45
|
+
"types": "./dist/http.d.ts",
|
|
46
|
+
"default": "./dist/http.js"
|
|
47
|
+
}
|
|
38
48
|
}
|
|
39
49
|
},
|
|
40
50
|
"sideEffects": false,
|
|
@@ -47,7 +57,8 @@
|
|
|
47
57
|
"node": ">=22"
|
|
48
58
|
},
|
|
49
59
|
"dependencies": {
|
|
50
|
-
"@standards/schema": "1.0.0-alpha.
|
|
60
|
+
"@standards/schema": "1.0.0-alpha.447",
|
|
61
|
+
"tus-js-client": "4.3.1"
|
|
51
62
|
},
|
|
52
63
|
"devDependencies": {
|
|
53
64
|
"@types/node": "^25.6.0",
|
package/dist/app-BUHCJ8SR.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
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");function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}function schemaApiErrorDetails(e){if(typeof e!=`object`||!e||!(`details`in e))return;let{details:t}=e;return typeof t==`object`&&t?t:void 0}const n=/* @__PURE__ */ 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}const r=new Set(e.DRAFT_CONFLICT_KINDS);function draftConflictChanges(e){if(!isDraftRevisionConflict(e))return[];let t=e.details?.changes;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.key==`string`&&typeof e.label==`string`&&typeof e.seen==`string`&&r.has(e.kind)):[]}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}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`}},BundleConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},BundleValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};const i=[1e3,2e3,5e3],a=/* @__PURE__ */ new Set([`turn.completed`,`turn.failed`,`turn.cancelled`]);function parseSseFrame(e){let t,n=`message`,r,i=[];for(let a of e.split(`
|
|
3
|
-
`)){let e=a.endsWith(`\r`)?a.slice(0,-1):a;if(e===``||e.startsWith(`:`))continue;let o=e.indexOf(`:`),s=o===-1?e:e.slice(0,o),c=o===-1?``:e.slice(o+1);c.startsWith(` `)&&(c=c.slice(1)),s===`id`?t=c:s===`event`?n=c:s===`data`?i.push(c):s===`retry`&&/^\d+$/.test(c)&&(r=Number(c))}return{id:t,event:n,data:i.join(`
|
|
4
|
-
`),retry:r}}function parseEvent(t){let n;try{n=JSON.parse(t.data)}catch{return}if((0,e.isPlainRecord)(n)&&typeof n.type==`string`&&typeof n.seq==`number`&&Number.isSafeInteger(n.seq)&&n.seq>0&&(t.id===void 0||t.id===String(n.seq)))return n}function parseControl(t){let n;try{n=JSON.parse(t.data)}catch{return}if(!(0,e.isPlainRecord)(n))return;let r=n.control;return r===`up-to-date`||r===`lease-ended`||r===`inbox`?r:void 0}function isUnresolvableActor(e){return e.status===401&&e.code===`ACTOR_RESOLUTION_FAILED`}function isTerminalRefusal(e){return e.status===400||e.status===403||e.status===404||isUnresolvableActor(e)}function isCursorExpired(e){return e instanceof StandardsRequestError&&e.status===410&&e.code===`AGENT_SESSION_STREAM_CURSOR_EXPIRED`}function openAgentStream(e){let t=!1,n,r,a,o=1e3,s=0,c,l=e.subscribeAuthChanges?.(()=>{t||(s+=1,c?.(),c=void 0)});function endWait(){r!==void 0&&clearTimeout(r),r=void 0,a?.(),a=void 0}function close(){t||(t=!0,n?.abort(),endWait(),c?.(),c=void 0,l?.())}function waitForAuthChange(e){return t||s!==e?Promise.resolve():new Promise(e=>{c=e})}function sleep(e){return new Promise(t=>{a=t,r=setTimeout(endWait,e)})}function handleFrame(t){let n=parseSseFrame(t);if(n.retry!==void 0&&(o=n.retry),n.data===``)return`skipped`;if(n.event===`control`){let t=parseControl(n);return t&&e.onControl(t),t===`lease-ended`?`lease-ended`:`skipped`}if(n.event!==`event`)return`skipped`;let r=parseEvent(n);return r?r.seq<=e.cursor()?`skipped`:(e.onEvent(r),`delivered`):`malformed`}async function consume(e,n){let r=e.body;if(r===null)return{delivered:!1,end:`failed`};let i=r.getReader(),a=new TextDecoder,o=``,s=!1;try{for(;;){let{done:e,value:r}=await i.read();if(t||e)return{delivered:s,end:`clean`};o+=a.decode(r,{stream:!0}).replace(/\r\n/g,`
|
|
5
|
-
`);let c=o.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;c!==-1;){let e=o.slice(0,c);o=o.slice(c+2);let r=handleFrame(e);if(r===`delivered`&&(s=!0),t)return{delivered:s,end:`clean`};if(r===`malformed`)return n.abort(),{delivered:s,end:`malformed`};if(r===`lease-ended`)return{delivered:s,end:`lease-ended`};c=o.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(t,n,r){if(isCursorExpired(t))try{return await e.onExpired(),r?`back-off`:`reopen`}catch{return`back-off`}return t instanceof StandardsRequestError?isTerminalRefusal(t)?(close(),e.onStatus(`error`,t),`stop`):t.status===401?(e.onStatus(`auth-blocked`,t),await waitForAuthChange(n),`reopen`):`back-off`:`back-off`}let u,d=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(d=u===t?d+1:1,u=t,d<3))return!1;u=void 0,d=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?o:i[Math.min(t,i.length-1)]??5e3}async function run(){let r=!0,i=0,a=!1;for(;!t;){e.onStatus(r?`connecting`:`reconnecting`),r=!1;let o=new AbortController;n=o;let c=s,l=`failed`;try{let n=await e.open(e.sessionId,e.cursor(),o.signal,()=>{c=s});if(t)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(n,o);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(t)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(t)return;let n=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=n,r===`stop`||t)return;if(r===`reopen`)continue}if(t)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}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));else 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)}else{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 r=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(a,o),method:n.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:r,form:multipartBody(n.upload.field,s),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>(0,t.decodeOperationOutput)(n,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:async e=>(0,t.decodeOperationOutput)(n,await readJson(e));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})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,n){let{query:r,body:i,headers:a}=(0,t.splitOperationInput)(e,n),o=Object.fromEntries((0,t.pathParamNames)(e.path).map(e=>[e,String(n[e])])),s=Object.fromEntries(Object.entries(a??{}).map(([e,t])=>[e.toLowerCase(),t])),c={params:o,query:asStrings(r),headers:s};if(e.upload===void 0)return{...c,body:i===void 0?void 0:JSON.parse(JSON.stringify(i))};let{[e.upload.field]:l,...u}=i??{},d=l==null?[]:Array.isArray(l)?l:[l];return{...c,body:asStrings(u),uploads:await Promise.all(d.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){return transportActingAs(e,void 0)}function transportActingAs(e,n){async function call(r,i,a={}){if(a.signal?.throwIfAborted(),r.response===`events`)throw Error(`Operation ${r.name} streams over HTTP only`);let o=await wireRequest(r,i??{}),s;try{s=await e.execute(r,o,n)}catch(e){throw(0,t.isOperationRefused)(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(r.response===`bytes`)return downloaded(s);let c=s===void 0?null:JSON.parse(JSON.stringify(s));return(0,t.decodeOperationOutput)(r,c)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`)),withCaller:t=>transportActingAs(e,t)}}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}Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return schemaApiErrorDetails}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return isDraftRevisionConflict}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return readRefusal}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return isViewNotFound}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return parseContentDispositionFilename}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return BundleConflictError}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return BundleValidationError}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return draftConflictChanges}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return StandardsRequestError}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return createTransport}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return StandardsConfigurationError}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createInProcessTransport}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return refusalOf}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return StandardsAuthError}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createHttpTransport}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return recordsPath}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createAppClient}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return openAgentStream}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return isObjectNotFound}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return schemaApiErrorCode}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return isPermanentRefusal}});
|
package/dist/app-Cer-0oL4.mjs
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
import{DRAFT_CONFLICT_KINDS as e,SchemaErrorCode as t,ValidationError as n,isPlainRecord as r}from"@standards/schema";import{appOperationGroups as i,decodeOperationOutput as a,encodePathSegment as o,isOperationRefused as s,operationGroup as c,pathParamNames as l,splitOperationInput as u}from"@standards/schema/api";function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}function schemaApiErrorDetails(e){if(typeof e!=`object`||!e||!(`details`in e))return;let{details:t}=e;return typeof t==`object`&&t?t:void 0}const d=/* @__PURE__ */ new Set([t.CONFIGURATION_REQUIRED]);function isPermanentRefusal(e){let t=schemaApiErrorCode(e);return t!==void 0&&d.has(t)}function isObjectNotFound(e){if(typeof e!=`object`||!e)return!1;let{code:n,status:r}=e;return n===t.OBJECT_NOT_FOUND||r===404}function isDraftRevisionConflict(e){return schemaApiErrorCode(e)===t.DRAFT_REVISION_CONFLICT}const f=new Set(e);function draftConflictChanges(e){if(!isDraftRevisionConflict(e))return[];let t=e.details?.changes;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.key==`string`&&typeof e.label==`string`&&typeof e.seen==`string`&&f.has(e.kind)):[]}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}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`}},BundleConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},BundleValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};const p=[1e3,2e3,5e3],m=/* @__PURE__ */ new Set([`turn.completed`,`turn.failed`,`turn.cancelled`]);function parseSseFrame(e){let t,n=`message`,r,i=[];for(let a of e.split(`
|
|
3
|
-
`)){let e=a.endsWith(`\r`)?a.slice(0,-1):a;if(e===``||e.startsWith(`:`))continue;let o=e.indexOf(`:`),s=o===-1?e:e.slice(0,o),c=o===-1?``:e.slice(o+1);c.startsWith(` `)&&(c=c.slice(1)),s===`id`?t=c:s===`event`?n=c:s===`data`?i.push(c):s===`retry`&&/^\d+$/.test(c)&&(r=Number(c))}return{id:t,event:n,data:i.join(`
|
|
4
|
-
`),retry:r}}function parseEvent(e){let t;try{t=JSON.parse(e.data)}catch{return}if(r(t)&&typeof t.type==`string`&&typeof t.seq==`number`&&Number.isSafeInteger(t.seq)&&t.seq>0&&(e.id===void 0||e.id===String(t.seq)))return t}function parseControl(e){let t;try{t=JSON.parse(e.data)}catch{return}if(!r(t))return;let n=t.control;return n===`up-to-date`||n===`lease-ended`||n===`inbox`?n:void 0}function isUnresolvableActor(e){return e.status===401&&e.code===`ACTOR_RESOLUTION_FAILED`}function isTerminalRefusal(e){return e.status===400||e.status===403||e.status===404||isUnresolvableActor(e)}function isCursorExpired(e){return e instanceof StandardsRequestError&&e.status===410&&e.code===`AGENT_SESSION_STREAM_CURSOR_EXPIRED`}function openAgentStream(e){let t=!1,n,r,i,a=1e3,o=0,s,c=e.subscribeAuthChanges?.(()=>{t||(o+=1,s?.(),s=void 0)});function endWait(){r!==void 0&&clearTimeout(r),r=void 0,i?.(),i=void 0}function close(){t||(t=!0,n?.abort(),endWait(),s?.(),s=void 0,c?.())}function waitForAuthChange(e){return t||o!==e?Promise.resolve():new Promise(e=>{s=e})}function sleep(e){return new Promise(t=>{i=t,r=setTimeout(endWait,e)})}function handleFrame(t){let n=parseSseFrame(t);if(n.retry!==void 0&&(a=n.retry),n.data===``)return`skipped`;if(n.event===`control`){let t=parseControl(n);return t&&e.onControl(t),t===`lease-ended`?`lease-ended`:`skipped`}if(n.event!==`event`)return`skipped`;let r=parseEvent(n);return r?r.seq<=e.cursor()?`skipped`:(e.onEvent(r),`delivered`):`malformed`}async function consume(e,n){let r=e.body;if(r===null)return{delivered:!1,end:`failed`};let i=r.getReader(),a=new TextDecoder,o=``,s=!1;try{for(;;){let{done:e,value:r}=await i.read();if(t||e)return{delivered:s,end:`clean`};o+=a.decode(r,{stream:!0}).replace(/\r\n/g,`
|
|
5
|
-
`);let c=o.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;c!==-1;){let e=o.slice(0,c);o=o.slice(c+2);let r=handleFrame(e);if(r===`delivered`&&(s=!0),t)return{delivered:s,end:`clean`};if(r===`malformed`)return n.abort(),{delivered:s,end:`malformed`};if(r===`lease-ended`)return{delivered:s,end:`lease-ended`};c=o.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(t,n,r){if(isCursorExpired(t))try{return await e.onExpired(),r?`back-off`:`reopen`}catch{return`back-off`}return t instanceof StandardsRequestError?isTerminalRefusal(t)?(close(),e.onStatus(`error`,t),`stop`):t.status===401?(e.onStatus(`auth-blocked`,t),await waitForAuthChange(n),`reopen`):`back-off`:`back-off`}let l,u=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(u=l===t?u+1:1,l=t,u<3))return!1;l=void 0,u=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?a:p[Math.min(t,p.length-1)]??5e3}async function run(){let r=!0,i=0,a=!1;for(;!t;){e.onStatus(r?`connecting`:`reconnecting`),r=!1;let s=new AbortController;n=s;let c=o,l=`failed`;try{let n=await e.open(e.sessionId,e.cursor(),s.signal,()=>{c=o});if(t)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(n,s);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(t)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(t)return;let n=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=n,r===`stop`||t)return;if(r===`reopen`)continue}if(t)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}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,...t){return[`/records`,...[e,...t].map(o)].join(`/`)}function resolveWithinBase(e,t){let r=e.endsWith(`/`)?e:`${e}/`,i=new URL(r),a=t.replace(/^\/+/,``),[o]=a.split(/[?#]/);if((o??``).split(`/`).some(e=>e===`..`||e===`.`))throw new n(`Request path "${t}" walks outside its own collection`,[]);let s=new URL(a,i);if(s.origin!==i.origin||!s.pathname.startsWith(i.pathname))throw new n(`Request path "${t}" 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));else 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:t,onUnauthorized:n,getRetries:r=0}=e,i=e.timeoutMs??3e4,o=e.apiPrefix===void 0?void 0:trimSlashes(e.apiPrefix,!0),s=o?`${trimSlashes(t,!1)}/${o}`:t;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 ${t}`):e}async function refreshAndRetry(e,t,r){try{if(!await n?.())return;let i=await fetchOnce(e,t,r);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,a,o){let s=buildUrl(e,a.params),c=(t.method??`GET`).toUpperCase(),l=a.maxRetries??(c===`GET`?r:0),u=a.timeoutMs===void 0?i:a.timeoutMs;for(let e=0;;e++){let r=e<l,i;try{i=await fetchOnce(s,t,u)}catch(n){if(r&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(i),i.status>=500&&r){let t=await readRefusalWithin(i);if(isPermanentRefusal(t))throw t;await backoff(e)}else{if(i.status===401&&n&&(i=await refreshAndRetry(s,t,u)??i),!i.ok){let e=await i.text().catch(()=>``);throw refusalFrom(i.status,e,a.plainTextRefusal??!1)}return await o(i)}}}async function stream(t,r,i={}){let{path:a,query:o,body:s,headers:c}=u(t,r??{}),l=buildUrl(a,o),{signal:d,onRequest:f}=i,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(l,{method:t.method,body:s===void 0?void 0:JSON.stringify(s),signal:d,headers:await headersFor({headers:{...c,...i.headers}})})),m=await attempt();if(m.status===401){let e=await readRefusal(m);if(e.code===`MFA_REQUIRED`||!n||!await n().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(t,n,r={}){if(t.response===`events`)return await stream(t,n,{signal:r.signal});let{path:i,query:o,body:s,headers:c}=u(t,n??{});if(t.upload!==void 0&&r.onUploadProgress&&canReportUploadProgress(e)){r.signal?.throwIfAborted();let n=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(i,o),method:t.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:n,form:multipartBody(t.upload.field,s),onUploadProgress:r.onUploadProgress,signal:r.signal},e=>a(t,e?JSON.parse(e):null))}let l=t.upload===void 0?s===void 0?void 0:JSON.stringify(s):multipartBody(t.upload.field,s),d=t.response===`bytes`?readDownload:async e=>a(t,await readJson(e));return await send(i,{method:t.method,body:l,signal:r.signal,...c?{headers:c}:{},...r.keepalive?{keepalive:!0}:{}},{params:o,maxRetries:r.maxRetries,timeoutMs:r.timeoutMs},d)},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})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,t){let{query:n,body:r,headers:i}=u(e,t),a=Object.fromEntries(l(e.path).map(e=>[e,String(t[e])])),o=Object.fromEntries(Object.entries(i??{}).map(([e,t])=>[e.toLowerCase(),t])),s={params:a,query:asStrings(n),headers:o};if(e.upload===void 0)return{...s,body:r===void 0?void 0:JSON.parse(JSON.stringify(r))};let{[e.upload.field]:c,...d}=r??{},f=c==null?[]:Array.isArray(c)?c:[c];return{...s,body:asStrings(d),uploads:await Promise.all(f.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){return transportActingAs(e,void 0)}function transportActingAs(e,t){async function call(n,r,i={}){if(i.signal?.throwIfAborted(),n.response===`events`)throw Error(`Operation ${n.name} streams over HTTP only`);let o=await wireRequest(n,r??{}),c;try{c=await e.execute(n,o,t)}catch(e){throw s(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(n.response===`bytes`)return downloaded(c);let l=c===void 0?null:JSON.parse(JSON.stringify(c));return a(n,l)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`)),withCaller:t=>transportActingAs(e,t)}}function createAppClient(e){let t={},n=Object.values(i);for(let r of n.flatMap(e=>Object.values(e))){let n=c(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{schemaApiErrorDetails as S,isDraftRevisionConflict as _,readRefusal as a,isViewNotFound as b,parseContentDispositionFilename as c,BundleConflictError as d,BundleValidationError as f,draftConflictChanges as g,StandardsRequestError as h,createTransport as i,m as l,StandardsConfigurationError as m,createInProcessTransport as n,refusalOf as o,StandardsAuthError as p,createHttpTransport as r,recordsPath as s,createAppClient as t,openAgentStream as u,isObjectNotFound as v,schemaApiErrorCode as x,isPermanentRefusal as y};
|
|
@@ -1,4 +0,0 @@
|
|
|
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-BUHCJ8SR.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(),{resolutions:o=[],fingerprint:s,confirmedRecords:c}=i,l=s!==void 0||c!==void 0?null:await readInstalled(t,a.name);if(l?.hash===a.hash&&l.label===a.label&&l.description===a.description&&l.uses.join(`
|
|
3
|
-
`)===a.uses.join(`
|
|
4
|
-
`))return{applied:!1,hash:a.hash,pendingRemovals:[]};let u={...a,...o.length>0?{resolutions:o}:{},...s===void 0?{}:{fingerprint:s},...c===void 0?{}:{confirmedRecords:c}};try{return await t.call(n.bundlesOperations.sync,{name:a.name,bundle:u})}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}}async function previewBundleSync(e,t){let r=await t.build();return await e.call(n.bundlesOperations.syncPreview,{name:r.name,bundle:r})}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)),syncPreview=((e,n)=>isBundleBuilder(e)?previewBundleSync(t,e):i.bundles.syncPreview(e,n)),a={...i,bundles:{...i.bundles,sync,syncPreview},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,"c",{enumerable:!0,get:function(){return syncBundle}}),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 previewBundleSync}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});
|