@standards/client 1.0.0-alpha.418 → 1.0.0-alpha.421
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-CjHQKAwu.mjs +9 -0
- package/dist/app-TCIe_XWO.d.mts +282 -0
- package/dist/app-TCIe_XWO.d.ts +282 -0
- package/dist/app-d25WfBqA.js +9 -0
- package/dist/app.d.mts +2 -67
- package/dist/app.d.ts +2 -67
- package/dist/app.js +1 -1
- package/dist/app.mjs +1 -1
- package/dist/{create-standards-BWOo2EZw.d.ts → create-standards-B4fQnzl5.d.mts} +105 -163
- package/dist/create-standards-CqOOm8eg.js +4 -0
- package/dist/{create-standards-HiWpTAlP.d.mts → create-standards-YjhWkQYe.d.ts} +105 -163
- package/dist/create-standards-orKjtGR6.mjs +4 -0
- package/dist/index.d.mts +4 -10
- package/dist/index.d.ts +4 -10
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/testing.d.mts +6 -4
- package/dist/testing.d.ts +6 -4
- package/dist/testing.js +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/create-standards-B63SENMD.mjs +0 -4
- package/dist/create-standards-DH5Om9n4.js +0 -4
- package/dist/http-transport-BxJhcXjy.d.mts +0 -161
- package/dist/http-transport-BxJhcXjy.d.ts +0 -161
- package/dist/http-transport-CfM3m5S2.js +0 -2
- package/dist/http-transport-DHYafmv-.mjs +0 -2
|
@@ -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
|
+
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}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){async function call(n,r,i={}){if(i.signal?.throwIfAborted(),n.response===`events`)throw Error(`Operation ${n.name} streams over HTTP only`);let a=await wireRequest(n,r??{}),o;try{o=await e.execute(n,a)}catch(e){throw(0,t.isOperationRefused)(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(n.response===`bytes`)return downloaded(o);let s=o===void 0?null:JSON.parse(JSON.stringify(o));return(0,t.decodeOperationOutput)(n,s)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`))}}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,"_",{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.d.mts
CHANGED
|
@@ -1,68 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { Operation, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
5
|
-
/** The server's `SchemaErrorCode` on a failed call, when it sent one. */
|
|
6
|
-
export declare function schemaApiErrorCode(error: unknown): string | undefined;
|
|
7
|
-
/** Whether a failure is an answer, and so must not be asked again. */
|
|
8
|
-
export declare function isPermanentRefusal(error: unknown): boolean;
|
|
9
|
-
/**
|
|
10
|
-
* Whether a failure says the object does not exist, rather than that the read
|
|
11
|
-
* failed (#3290): with a definition seeded from the cached catalogue, a 500 and
|
|
12
|
-
* a 404 are opposite answers — a transient failure may be ridden out, an
|
|
13
|
-
* authoritative not-found may not.
|
|
14
|
-
*
|
|
15
|
-
* Either signal is enough, deliberately: reading only the code would tolerate a
|
|
16
|
-
* deleted object behind a plainer not-found, reading only the status would miss
|
|
17
|
-
* a coded refusal carrying no status.
|
|
18
|
-
*/
|
|
19
|
-
export declare function isObjectNotFound(error: unknown): boolean;
|
|
20
|
-
/**
|
|
21
|
-
* Whether a write was refused because the draft moved since it was read
|
|
22
|
-
* (`DRAFT_REVISION_CONFLICT`, a 409): only a fresh read of the draft makes the
|
|
23
|
-
* next attempt mean something (#4899).
|
|
24
|
-
*/
|
|
25
|
-
export declare function isDraftRevisionConflict(error: unknown): boolean;
|
|
26
|
-
/**
|
|
27
|
-
* What a publish refused for a conflict found published on its targets since
|
|
28
|
-
* the draft captured them (#5936). Empty for any other refusal, a conflict on
|
|
29
|
-
* the draft's own revision included: that one is answered by reading it again.
|
|
30
|
-
*/
|
|
31
|
-
export declare function draftConflictChanges(error: unknown): DraftConflictChange[];
|
|
32
|
-
/**
|
|
33
|
-
* Whether a view read failed because the object simply has no view for that
|
|
34
|
-
* context (#2659) — a working object not laid out yet, not a failure.
|
|
35
|
-
*
|
|
36
|
-
* Status-only: the view routes' not-found carries the generic
|
|
37
|
-
* `SCHEMA_RECORD_NOT_FOUND` code, which says nothing view-specific. Call it
|
|
38
|
-
* ONLY on a view query's error — on any other query a 404 means something
|
|
39
|
-
* else entirely.
|
|
40
|
-
*/
|
|
41
|
-
export declare function isViewNotFound(error: unknown): boolean;
|
|
42
|
-
/**
|
|
43
|
-
* Parse the download filename out of a `Content-Disposition` response header.
|
|
44
|
-
*
|
|
45
|
-
* The server is the single naming source (see `contentDispositionFilename` in
|
|
46
|
-
* adapter-nestjs): it emits both the RFC 5987 `filename*=UTF-8''...` form
|
|
47
|
-
* (accent-safe, percent-encoded) and a sanitized ASCII `filename="..."`
|
|
48
|
-
* fallback. We prefer the extended form and percent-decode it so accented,
|
|
49
|
-
* title-based names ("Pièce d'identité – 2.jpg") survive the round trip.
|
|
50
|
-
*
|
|
51
|
-
* Returns `undefined` when the header is absent or carries no filename, letting
|
|
52
|
-
* callers fall back to a client-side name.
|
|
53
|
-
*/
|
|
54
|
-
export declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
|
|
55
|
-
type AppOperationGroups = typeof appOperationGroups;
|
|
56
|
-
type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
|
|
57
|
-
type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
|
|
58
|
-
type VerbOf<N> = N extends `${string}.${infer V}` ? V : never;
|
|
59
|
-
/** An `"events"` operation opens a stream (`transport.stream`); any other is one call. */
|
|
60
|
-
type OptionsOf<O extends Operation> = O extends {
|
|
61
|
-
readonly response: "events";
|
|
62
|
-
} ? OperationStreamOptions : OperationCallOptions;
|
|
63
|
-
/** An input the schema defaults (`.default({})`) may be left out; `options` carries the call's signal. */
|
|
64
|
-
type OperationCall<O extends Operation> = (...args: undefined extends OperationInput<O> ? [input?: OperationInput<O>, options?: OptionsOf<O>] : [input: OperationInput<O>, options?: OptionsOf<O>]) => Promise<OperationResult<O>>;
|
|
65
|
-
export type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
|
|
66
|
-
/** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
|
|
67
|
-
export declare function createAppClient(transport: HttpTransport): AppClient;
|
|
68
|
-
export { type HttpTransport, type HttpTransportConfig, type OperationCallOptions, type OperationStreamOptions, StandardsAuthError, StandardsRequestError, type UploadProgress, createHttpTransport, readRefusal, refusalOf };
|
|
2
|
+
import { E as createHttpTransport, M as StandardsAuthError, O as readRefusal, P as StandardsRequestError, S as OperationTransport, T as UploadProgress, _ as HttpTransport, a as AgentStreamControl, b as OperationCallOptions, c as OpenAgentStreamOptions, d as draftConflictChanges, f as isDraftRevisionConflict, g as schemaApiErrorCode, h as isViewNotFound, i as parseContentDispositionFilename, k as refusalOf, l as TURN_END_TYPES, m as isPermanentRefusal, n as createAppClient, o as AgentStreamHandle, p as isObjectNotFound, r as createInProcessTransport, s as AgentStreamStatus, t as AppClient, u as openAgentStream, v as HttpTransportConfig, x as OperationStreamOptions } from "./app-TCIe_XWO.mjs";
|
|
3
|
+
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
|
package/dist/app.d.ts
CHANGED
|
@@ -1,68 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { Operation, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
5
|
-
/** The server's `SchemaErrorCode` on a failed call, when it sent one. */
|
|
6
|
-
export declare function schemaApiErrorCode(error: unknown): string | undefined;
|
|
7
|
-
/** Whether a failure is an answer, and so must not be asked again. */
|
|
8
|
-
export declare function isPermanentRefusal(error: unknown): boolean;
|
|
9
|
-
/**
|
|
10
|
-
* Whether a failure says the object does not exist, rather than that the read
|
|
11
|
-
* failed (#3290): with a definition seeded from the cached catalogue, a 500 and
|
|
12
|
-
* a 404 are opposite answers — a transient failure may be ridden out, an
|
|
13
|
-
* authoritative not-found may not.
|
|
14
|
-
*
|
|
15
|
-
* Either signal is enough, deliberately: reading only the code would tolerate a
|
|
16
|
-
* deleted object behind a plainer not-found, reading only the status would miss
|
|
17
|
-
* a coded refusal carrying no status.
|
|
18
|
-
*/
|
|
19
|
-
export declare function isObjectNotFound(error: unknown): boolean;
|
|
20
|
-
/**
|
|
21
|
-
* Whether a write was refused because the draft moved since it was read
|
|
22
|
-
* (`DRAFT_REVISION_CONFLICT`, a 409): only a fresh read of the draft makes the
|
|
23
|
-
* next attempt mean something (#4899).
|
|
24
|
-
*/
|
|
25
|
-
export declare function isDraftRevisionConflict(error: unknown): boolean;
|
|
26
|
-
/**
|
|
27
|
-
* What a publish refused for a conflict found published on its targets since
|
|
28
|
-
* the draft captured them (#5936). Empty for any other refusal, a conflict on
|
|
29
|
-
* the draft's own revision included: that one is answered by reading it again.
|
|
30
|
-
*/
|
|
31
|
-
export declare function draftConflictChanges(error: unknown): DraftConflictChange[];
|
|
32
|
-
/**
|
|
33
|
-
* Whether a view read failed because the object simply has no view for that
|
|
34
|
-
* context (#2659) — a working object not laid out yet, not a failure.
|
|
35
|
-
*
|
|
36
|
-
* Status-only: the view routes' not-found carries the generic
|
|
37
|
-
* `SCHEMA_RECORD_NOT_FOUND` code, which says nothing view-specific. Call it
|
|
38
|
-
* ONLY on a view query's error — on any other query a 404 means something
|
|
39
|
-
* else entirely.
|
|
40
|
-
*/
|
|
41
|
-
export declare function isViewNotFound(error: unknown): boolean;
|
|
42
|
-
/**
|
|
43
|
-
* Parse the download filename out of a `Content-Disposition` response header.
|
|
44
|
-
*
|
|
45
|
-
* The server is the single naming source (see `contentDispositionFilename` in
|
|
46
|
-
* adapter-nestjs): it emits both the RFC 5987 `filename*=UTF-8''...` form
|
|
47
|
-
* (accent-safe, percent-encoded) and a sanitized ASCII `filename="..."`
|
|
48
|
-
* fallback. We prefer the extended form and percent-decode it so accented,
|
|
49
|
-
* title-based names ("Pièce d'identité – 2.jpg") survive the round trip.
|
|
50
|
-
*
|
|
51
|
-
* Returns `undefined` when the header is absent or carries no filename, letting
|
|
52
|
-
* callers fall back to a client-side name.
|
|
53
|
-
*/
|
|
54
|
-
export declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
|
|
55
|
-
type AppOperationGroups = typeof appOperationGroups;
|
|
56
|
-
type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
|
|
57
|
-
type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
|
|
58
|
-
type VerbOf<N> = N extends `${string}.${infer V}` ? V : never;
|
|
59
|
-
/** An `"events"` operation opens a stream (`transport.stream`); any other is one call. */
|
|
60
|
-
type OptionsOf<O extends Operation> = O extends {
|
|
61
|
-
readonly response: "events";
|
|
62
|
-
} ? OperationStreamOptions : OperationCallOptions;
|
|
63
|
-
/** An input the schema defaults (`.default({})`) may be left out; `options` carries the call's signal. */
|
|
64
|
-
type OperationCall<O extends Operation> = (...args: undefined extends OperationInput<O> ? [input?: OperationInput<O>, options?: OptionsOf<O>] : [input: OperationInput<O>, options?: OptionsOf<O>]) => Promise<OperationResult<O>>;
|
|
65
|
-
export type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
|
|
66
|
-
/** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
|
|
67
|
-
export declare function createAppClient(transport: HttpTransport): AppClient;
|
|
68
|
-
export { type HttpTransport, type HttpTransportConfig, type OperationCallOptions, type OperationStreamOptions, StandardsAuthError, StandardsRequestError, type UploadProgress, createHttpTransport, readRefusal, refusalOf };
|
|
2
|
+
import { E as createHttpTransport, M as StandardsAuthError, O as readRefusal, P as StandardsRequestError, S as OperationTransport, T as UploadProgress, _ as HttpTransport, a as AgentStreamControl, b as OperationCallOptions, c as OpenAgentStreamOptions, d as draftConflictChanges, f as isDraftRevisionConflict, g as schemaApiErrorCode, h as isViewNotFound, i as parseContentDispositionFilename, k as refusalOf, l as TURN_END_TYPES, m as isPermanentRefusal, n as createAppClient, o as AgentStreamHandle, p as isObjectNotFound, r as createInProcessTransport, s as AgentStreamStatus, t as AppClient, u as openAgentStream, v as HttpTransportConfig, x as OperationStreamOptions } from "./app-TCIe_XWO.js";
|
|
3
|
+
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
|
package/dist/app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./app-d25WfBqA.js");exports.StandardsAuthError=e.p,exports.StandardsRequestError=e.h,exports.TURN_END_TYPES=e.l,exports.createAppClient=e.t,exports.createHttpTransport=e.r,exports.createInProcessTransport=e.n,exports.draftConflictChanges=e.g,exports.isDraftRevisionConflict=e._,exports.isObjectNotFound=e.v,exports.isPermanentRefusal=e.y,exports.isViewNotFound=e.b,exports.openAgentStream=e.u,exports.parseContentDispositionFilename=e.c,exports.readRefusal=e.a,exports.refusalOf=e.o,exports.schemaApiErrorCode=e.x;
|
package/dist/app.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
|
|
2
|
+
export{p as StandardsAuthError,h as StandardsRequestError,l as TURN_END_TYPES,t as createAppClient,r as createHttpTransport,n as createInProcessTransport,g as draftConflictChanges,_ as isDraftRevisionConflict,v as isObjectNotFound,y as isPermanentRefusal,b as isViewNotFound,u as openAgentStream,c as parseContentDispositionFilename,a as readRefusal,o as refusalOf,x as schemaApiErrorCode}from"./app-CjHQKAwu.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import { AggregateRecordsOptions, BundleBuilder,
|
|
2
|
+
import { S as OperationTransport, _ as HttpTransport, t as AppClient, w as TransportConfig } from "./app-TCIe_XWO.mjs";
|
|
3
|
+
import { AggregateRecordsOptions, BundleBuilder, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
|
|
4
4
|
/**
|
|
5
5
|
* What a sync carries besides the bundle itself.
|
|
6
6
|
*
|
|
@@ -12,123 +12,10 @@ import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, Ex
|
|
|
12
12
|
interface SyncBundleOptions {
|
|
13
13
|
resolutions?: SchemaSourceResolution[];
|
|
14
14
|
}
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
* satisfies it, and so does a hand-rolled stub, which a `Pick` of the generic
|
|
18
|
-
* signatures would reject.
|
|
19
|
-
*/
|
|
20
|
-
interface SyncTransport {
|
|
21
|
-
get(path: string): Promise<unknown>;
|
|
22
|
-
put(path: string, body?: unknown): Promise<unknown>;
|
|
23
|
-
}
|
|
15
|
+
/** Both calls are contract operations, on any transport. */
|
|
16
|
+
type SyncTransport = Pick<HttpTransport, "call">;
|
|
24
17
|
/** GET the installed summary; PUT the built bundle when its hash, label, description or uses differ, or it was never synced. */
|
|
25
18
|
declare function syncBundle(transport: SyncTransport, bundle: BundleBuilder<string, readonly ObjectBuilderLike[]>, options?: SyncBundleOptions): Promise<SyncBundleResult>;
|
|
26
|
-
/**
|
|
27
|
-
* What the files and documents methods upload: a `File` (or any `Blob` carrying
|
|
28
|
-
* a `name`) with a non-empty filename and MIME type. The server checks the MIME
|
|
29
|
-
* type, the extension and the file signature against each other, so all three
|
|
30
|
-
* travel with the bytes. A `Buffer` or a path is not an input: wrap the bytes in
|
|
31
|
-
* `new File([bytes], "name.png", { type: "image/png" })`.
|
|
32
|
-
*/
|
|
33
|
-
type FileInput = Blob & {
|
|
34
|
-
readonly name: string;
|
|
35
|
-
};
|
|
36
|
-
/**
|
|
37
|
-
* The timeout of one upload's request, in ms (#4741). A large file on a slow
|
|
38
|
-
* link outlives the client's `timeoutMs` (30 s by default) and surfaces as a
|
|
39
|
-
* connection failure, possibly after the server stored it — so raise it for
|
|
40
|
-
* large uploads rather than retrying a timed-out attach.
|
|
41
|
-
*/
|
|
42
|
-
interface UploadTimeoutOption {
|
|
43
|
-
timeoutMs?: number;
|
|
44
|
-
}
|
|
45
|
-
interface AttachToRecordInput extends UploadTimeoutOption {
|
|
46
|
-
objectName: string;
|
|
47
|
-
recordId: string;
|
|
48
|
-
/** The record's `document` attribute; the server defaults to `attachments`. */
|
|
49
|
-
attributeName?: string;
|
|
50
|
-
/** Append to this existing document's pack instead of creating a document. */
|
|
51
|
-
documentId?: string;
|
|
52
|
-
/** The new document's title; the server defaults to the filename without its extension. */
|
|
53
|
-
title?: string;
|
|
54
|
-
/**
|
|
55
|
-
* The bytes to upload, private, in the same request — the input
|
|
56
|
-
* `files.upload` takes. The attach route takes one file per call: append
|
|
57
|
-
* more by passing the returned `document.id` as `documentId`. An
|
|
58
|
-
* already-uploaded file is not an input, so a public upload can never end up
|
|
59
|
-
* in a document.
|
|
60
|
-
*/
|
|
61
|
-
file: FileInput;
|
|
62
|
-
}
|
|
63
|
-
interface AttachToRecordResult {
|
|
64
|
-
document: {
|
|
65
|
-
id: string;
|
|
66
|
-
title: string;
|
|
67
|
-
};
|
|
68
|
-
file: DocumentFile;
|
|
69
|
-
/** `created`: a new document on the record; `appended`: added to `documentId`'s pack. */
|
|
70
|
-
action: "created" | "appended";
|
|
71
|
-
}
|
|
72
|
-
interface DocumentsApi {
|
|
73
|
-
/**
|
|
74
|
-
* Upload a file and attach it to a record's document attribute in ONE
|
|
75
|
-
* multipart `POST /records/:object/:id/documents/attach`. The server
|
|
76
|
-
* validates the file against the attribute and deletes the upload if the
|
|
77
|
-
* attach fails, so an error never leaves an orphaned file.
|
|
78
|
-
*/
|
|
79
|
-
attachToRecord(input: AttachToRecordInput): Promise<AttachToRecordResult>;
|
|
80
|
-
/** The document's files in pack order (`GET /documents/:id/files`). */
|
|
81
|
-
listFiles(documentId: string): Promise<DocumentFile[]>;
|
|
82
|
-
}
|
|
83
|
-
/** The two verbs this module needs, typed non-generically so a stub satisfies it. */
|
|
84
|
-
interface DocumentsTransport {
|
|
85
|
-
get(path: string): Promise<unknown>;
|
|
86
|
-
postMultipart(path: string, form: FormData, options?: MultipartRequestOptions): Promise<unknown>;
|
|
87
|
-
}
|
|
88
|
-
declare function createDocumentsApi(transport: DocumentsTransport): DocumentsApi;
|
|
89
|
-
interface UploadFileBase extends UploadTimeoutOption {
|
|
90
|
-
file: FileInput;
|
|
91
|
-
/** Stored as the file's folder (`folderPath` on `POST /files/upload`). */
|
|
92
|
-
folderPath?: string;
|
|
93
|
-
}
|
|
94
|
-
/** Anyone holding the returned `publicUrl` can open the file. A public file never joins a document. */
|
|
95
|
-
interface UploadPublicFileInput extends UploadFileBase {
|
|
96
|
-
public: true;
|
|
97
|
-
}
|
|
98
|
-
/** The default: readable through a signed URL from `getDownloadUrl`. */
|
|
99
|
-
interface UploadPrivateFileInput extends UploadFileBase {
|
|
100
|
-
public?: false;
|
|
101
|
-
}
|
|
102
|
-
type UploadFileInput = UploadPublicFileInput | UploadPrivateFileInput;
|
|
103
|
-
interface UploadedFileBase {
|
|
104
|
-
id: string;
|
|
105
|
-
/** The stored (sanitized) filename. */
|
|
106
|
-
name: string;
|
|
107
|
-
mimeType: string;
|
|
108
|
-
size: number;
|
|
109
|
-
}
|
|
110
|
-
interface PublicUploadedFile extends UploadedFileBase {
|
|
111
|
-
isPublic: true;
|
|
112
|
-
/** `{publicFilesUrl}/{id}`: permanent, and never carries a credential. */
|
|
113
|
-
publicUrl: string;
|
|
114
|
-
}
|
|
115
|
-
interface PrivateUploadedFile extends UploadedFileBase {
|
|
116
|
-
isPublic: false;
|
|
117
|
-
publicUrl?: never;
|
|
118
|
-
}
|
|
119
|
-
/** Discriminated on `isPublic`: only the public branch has a `publicUrl`. */
|
|
120
|
-
type UploadedFile = PublicUploadedFile | PrivateUploadedFile;
|
|
121
|
-
interface FilesApi {
|
|
122
|
-
/** One multipart `POST /files/upload`. */
|
|
123
|
-
upload(input: UploadPublicFileInput): Promise<PublicUploadedFile>;
|
|
124
|
-
upload(input: UploadPrivateFileInput): Promise<PrivateUploadedFile>;
|
|
125
|
-
upload(input: UploadFileInput): Promise<UploadedFile>;
|
|
126
|
-
/** A fresh signed read URL (`GET /files/:id/url`); it expires, so ask again each time. */
|
|
127
|
-
getDownloadUrl(fileId: string): Promise<string>;
|
|
128
|
-
}
|
|
129
|
-
/** The one verb this module needs: the `files` operations. */
|
|
130
|
-
type FilesTransport = Pick<HttpTransport, "call">;
|
|
131
|
-
declare function createFilesApi(transport: FilesTransport): FilesApi;
|
|
132
19
|
/** `daily-stats` → `dailyStats`. Object names are kebab-case (enforced by the builder). */
|
|
133
20
|
type CamelCase<S extends string> = S extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
|
|
134
21
|
type Attr<TBuilder> = keyof ExtractRecord<TBuilder> & string;
|
|
@@ -145,6 +32,33 @@ type RecordInput<TBuilder> = ExtractRecordInputStrict<TBuilder> & {
|
|
|
145
32
|
type RecordUpdate<TBuilder> = ExtractRecordUpdateStrict<TBuilder> & {
|
|
146
33
|
[key: string]: unknown;
|
|
147
34
|
};
|
|
35
|
+
/** What `create()` takes beside the values. */
|
|
36
|
+
interface RecordCreateOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Create the record even when required attributes are missing. The values
|
|
39
|
+
* given are still validated.
|
|
40
|
+
* @default false
|
|
41
|
+
*/
|
|
42
|
+
allowDraft?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* The record's `metadata`: application state kept beside its values, never
|
|
45
|
+
* shown as an attribute. System keys are dropped.
|
|
46
|
+
*/
|
|
47
|
+
metadata?: Record<string, unknown>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* What `update()` takes beside the patch. No `allowDraft`: the server already
|
|
51
|
+
* validates every update as a draft, so a required attribute the patch leaves
|
|
52
|
+
* out is never refused.
|
|
53
|
+
*/
|
|
54
|
+
interface RecordUpdateOptions {
|
|
55
|
+
/**
|
|
56
|
+
* Keys shallow-merged into the record's `metadata`: each one replaced whole,
|
|
57
|
+
* `null` removes it, the keys not named stay. Written with the patch in one
|
|
58
|
+
* transaction.
|
|
59
|
+
*/
|
|
60
|
+
metadata?: Record<string, unknown>;
|
|
61
|
+
}
|
|
148
62
|
/** What `export()` takes beside its columns. */
|
|
149
63
|
interface RecordsExportOptions {
|
|
150
64
|
/** Export only these records (at most `EXPORT_MAX_IDS`, 20 000). */
|
|
@@ -257,8 +171,27 @@ interface RecordsQuery<TBuilder> {
|
|
|
257
171
|
all(): Promise<ExtractRecord<TBuilder>[]>;
|
|
258
172
|
single(): Promise<ExtractRecord<TBuilder> | null>;
|
|
259
173
|
get(id: string): Promise<ExtractRecord<TBuilder>>;
|
|
260
|
-
|
|
261
|
-
|
|
174
|
+
/**
|
|
175
|
+
* `POST /records/<object>`. `allowDraft` creates the record with required
|
|
176
|
+
* attributes missing (so its input types every attribute as optional);
|
|
177
|
+
* `metadata` is the record's application state.
|
|
178
|
+
*/
|
|
179
|
+
create(input: RecordInput<TBuilder>, options?: RecordCreateOptions): Promise<ExtractRecord<TBuilder>>;
|
|
180
|
+
create(input: RecordUpdate<TBuilder>, options: RecordCreateOptions & {
|
|
181
|
+
allowDraft: true;
|
|
182
|
+
}): Promise<ExtractRecord<TBuilder>>;
|
|
183
|
+
/**
|
|
184
|
+
* `PUT /records/<object>/<id>`: merges the patch into the record. The server
|
|
185
|
+
* validates every update as a draft, so there is no `allowDraft`.
|
|
186
|
+
*
|
|
187
|
+
* With `metadata`, the patch and the metadata are written together by one
|
|
188
|
+
* `record.set` step of `POST /operations`, in one transaction; the record is
|
|
189
|
+
* read first (`GET /records/<object>/<id>`) for the object id the step
|
|
190
|
+
* names. A refused step rejects with the `StandardsRequestError` its code
|
|
191
|
+
* maps to (`StandardsAuthError` for a 403), with that code and status but
|
|
192
|
+
* no field `details`, which the same refusal on `PUT` carries.
|
|
193
|
+
*/
|
|
194
|
+
update(id: string, patch: RecordUpdate<TBuilder>, options?: RecordUpdateOptions): Promise<ExtractRecord<TBuilder>>;
|
|
262
195
|
delete(id: string): Promise<void>;
|
|
263
196
|
/**
|
|
264
197
|
* `POST /records/<object>/bulk-create`, 100 inputs per request, sent one after
|
|
@@ -299,38 +232,16 @@ interface UntypedBuilder {
|
|
|
299
232
|
/** What `standards.from("object-name")` hands back. */
|
|
300
233
|
type UntypedRecordsQuery = RecordsQuery<UntypedBuilder>;
|
|
301
234
|
/**
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
* when a stub leaves it out. Each path is its contract operation's
|
|
306
|
-
* (`buildOperationPath`, every parameter one encoded segment); the verbs stay
|
|
307
|
-
* the transport's.
|
|
235
|
+
* Every records call is a contract operation (`call`), on any transport, the
|
|
236
|
+
* in-process one included. `export()` alone reads the CSV as it streams, so it
|
|
237
|
+
* needs an HTTP transport's `postRaw`.
|
|
308
238
|
*/
|
|
309
|
-
|
|
310
|
-
get(path: string): Promise<unknown>;
|
|
311
|
-
post(path: string, body?: unknown): Promise<unknown>;
|
|
239
|
+
type RecordsTransport = Pick<HttpTransport, "call"> & {
|
|
312
240
|
postRaw?(path: string, body: unknown): Promise<Response>;
|
|
313
|
-
|
|
314
|
-
delete(path: string): Promise<unknown>;
|
|
315
|
-
}
|
|
241
|
+
};
|
|
316
242
|
/** A builder gives typed records; a bare object name is the untyped escape hatch. */
|
|
317
243
|
declare function createRecordsQuery<TBuilder extends ObjectBuilderLike>(transport: RecordsTransport, target: TBuilder): RecordsQuery<TBuilder>;
|
|
318
244
|
declare function createRecordsQuery(transport: RecordsTransport, target: string): UntypedRecordsQuery;
|
|
319
|
-
interface UsageReportInput {
|
|
320
|
-
/** First day of the window, `YYYY-MM-DD` (UTC, inclusive). */
|
|
321
|
-
from: string;
|
|
322
|
-
/** Last day of the window, `YYYY-MM-DD` (UTC, inclusive); at most 366 days after `from`. */
|
|
323
|
-
to: string;
|
|
324
|
-
/** `me` (the default): the caller's own usage. `workspace`: every member's, gated on `billing:read`. */
|
|
325
|
-
scope?: UsageScope;
|
|
326
|
-
}
|
|
327
|
-
interface UsageApi {
|
|
328
|
-
/** AI usage and cost over an inclusive UTC day window (`GET /ai/usage`). */
|
|
329
|
-
report(input: UsageReportInput): Promise<UsageReport>;
|
|
330
|
-
}
|
|
331
|
-
/** The one verb this module needs: the `ai.usage` operation. */
|
|
332
|
-
type UsageTransport = Pick<HttpTransport, "call">;
|
|
333
|
-
declare function createUsageApi(transport: UsageTransport): UsageApi;
|
|
334
245
|
type NameOf<B> = B extends {
|
|
335
246
|
_types: {
|
|
336
247
|
name: infer N extends string;
|
|
@@ -342,28 +253,59 @@ type ObjectsOf<TObjects extends readonly ObjectBuilderLike[]> = { readonly [B in
|
|
|
342
253
|
type AnyBundle = BundleBuilder<string, readonly ObjectBuilderLike[]>;
|
|
343
254
|
/** The object builders of every bundle in a tuple: what the typed client infers from. */
|
|
344
255
|
type ObjectsOfBundles<TBundles extends readonly AnyBundle[]> = TBundles[number]["objectBuilders"];
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
256
|
+
type ContractSync = AppClient["bundles"]["sync"];
|
|
257
|
+
/** `bundles.sync`, either way: from your bundle's builder, or the contract's call. */
|
|
258
|
+
interface BundlesSync {
|
|
259
|
+
/**
|
|
260
|
+
* Build `bundle`, compare it with the version the workspace holds, and put
|
|
261
|
+
* it only when it changed: `{ applied: false }` when it already holds it.
|
|
262
|
+
*/
|
|
263
|
+
(bundle: AnyBundle, options?: SyncBundleOptions): Promise<SyncBundleResult>;
|
|
264
|
+
/** The contract's call, with an artifact you built yourself. */
|
|
265
|
+
(...args: Parameters<ContractSync>): ReturnType<ContractSync>;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* The client: every operation of the contract at the root, by group and
|
|
269
|
+
* verb (`decisions.list`, `users.get`, `files.upload`…), with your bundles'
|
|
270
|
+
* objects beside them as typed queries (see {@link StandardsOf}).
|
|
271
|
+
*/
|
|
272
|
+
type Standards = Omit<AppClient, "bundles"> & {
|
|
273
|
+
readonly bundles: Omit<AppClient["bundles"], "sync"> & {
|
|
274
|
+
readonly sync: BundlesSync;
|
|
349
275
|
};
|
|
350
276
|
/** Untyped access to an object the code does not declare (created at runtime). */
|
|
351
277
|
from(objectName: string): UntypedRecordsQuery;
|
|
352
|
-
/**
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
}
|
|
278
|
+
/**
|
|
279
|
+
* Every operation of the contract, under its own name only: the way to a
|
|
280
|
+
* group one of your objects shares a name with, since the object wins at
|
|
281
|
+
* the root.
|
|
282
|
+
*/
|
|
283
|
+
readonly contract: AppClient;
|
|
284
|
+
};
|
|
285
|
+
/**
|
|
286
|
+
* The client with your objects: each one a typed query at the root. An object
|
|
287
|
+
* named like a contract group takes its place there (the group stays under
|
|
288
|
+
* `contract`), so a group Standards adds later never changes what your code
|
|
289
|
+
* reads.
|
|
290
|
+
*/
|
|
291
|
+
type StandardsOf<TObjects extends readonly ObjectBuilderLike[]> = Omit<Standards, keyof ObjectsOf<TObjects>> & ObjectsOf<TObjects>;
|
|
359
292
|
/**
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
293
|
+
* Every call `createStandards` makes is a contract operation (`call`, and
|
|
294
|
+
* `stream` for an `"events"` one); a records `export()` also
|
|
295
|
+
* needs an HTTP transport's `postRaw`.
|
|
363
296
|
*/
|
|
364
|
-
type
|
|
297
|
+
type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "postRaw">>;
|
|
298
|
+
/**
|
|
299
|
+
* The options `createStandards` takes: an API key's HTTP connection
|
|
300
|
+
* (`baseUrl`, `apiKey`, read from the environment when absent), or a
|
|
301
|
+
* `transport` of your own (the in-process one in a server that embeds
|
|
302
|
+
* Standards, `createInProcessTransport`), never both.
|
|
303
|
+
*/
|
|
304
|
+
type StandardsConfig = Partial<TransportConfig> & {
|
|
305
|
+
transport?: StandardsTransport;
|
|
306
|
+
};
|
|
365
307
|
declare function createStandards<const TBundles extends readonly AnyBundle[]>(config: StandardsConfig & {
|
|
366
308
|
bundles: TBundles;
|
|
367
|
-
}):
|
|
309
|
+
}): StandardsOf<ObjectsOfBundles<TBundles>>;
|
|
368
310
|
declare function createStandards(config?: StandardsConfig): Standards;
|
|
369
|
-
export {
|
|
311
|
+
export { SyncTransport as A, UntypedRecordsQuery as C, createRecordsQuery as D, UpdateManyResult as E, CamelCase as O, UntypedBuilder as S, UpdateManyError as T, RecordUpdate as _, Standards as a, RecordsExportOptions as b, StandardsTransport as c, CreateManyResult as d, DeleteManyError as f, RecordInput as g, RecordCreateOptions as h, ObjectsOfBundles as i, syncBundle as j, SyncBundleOptions as k, createStandards as l, FetchResult as m, BundlesSync as n, StandardsConfig as o, DeleteManyResult as p, ObjectsOf as r, StandardsOf as s, AnyBundle as t, CreateManyError as u, RecordUpdateOptions as v, UpdateManyEntry as w, RecordsQuery as x, RecordsAggregateOptions as y };
|
|
@@ -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-d25WfBqA.js");let t=require("@standards/schema"),n=require("@standards/schema/api");async function readInstalled(t,r){try{return await t.call(n.bundlesOperations.get,{name:r})}catch(t){if(t instanceof e.h&&t.status===404)return null;throw t}}async function syncBundle(t,r,i={}){let a=await r.build(),o=await readInstalled(t,a.name);if(o?.hash===a.hash&&o.label===a.label&&o.description===a.description&&o.uses.join(`
|
|
3
|
+
`)===a.uses.join(`
|
|
4
|
+
`))return{applied:!1,hash:a.hash};let s=i.resolutions&&i.resolutions.length>0?{...a,resolutions:i.resolutions}:a;try{return await t.call(n.bundlesOperations.sync,{name:a.name,bundle:s})}catch(t){throw t instanceof e.h&&t.status===409?new e.d(t.status,t.message,t.code):t instanceof e.h&&t.status===400?new e.f(t.status,t.message,t.code):t}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`]);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,n){let r=e.t(t),sync=((e,n)=>isBundleBuilder(e)?syncBundle(t,e,n):r.bundles.sync(e,n)),i={...r,bundles:{...r.bundles,sync},from:e=>createRecordsQuery(t,e),contract:r},a=n.map(e=>definitionOf(e).name);return assertObjectNames(a),n.forEach((e,n)=>{i[objectKeyOf(a[n])]=createRecordsQuery(t,e)}),i}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return readRecord}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createStandards}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return syncBundle}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createRecordsQuery}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});
|