@vinaverse/server 0.1.0-alpha.1 → 0.1.0-alpha.11

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -152,6 +152,14 @@ try {
152
152
  and an already aborted signal sends nothing.
153
153
  - **Refusals throw `VinaverseApiError`**, with the problem's `status`, `code`, `retryable`, `requestId`, `retryAfter`
154
154
  and, for `invalid_request`, the field `errors`.
155
+ - **Where the person is now:** `sessions.updateContext(sessionId, body)` tells an open session the screen the person
156
+ moved to (a screen context with its `revision`, or `{ clear: true, revision }`), with no new session per screen. A
157
+ revision not greater than the session's is `409 context_stale` with `current_revision`; the same revision with the
158
+ same body is a retry. Answered once the gateway's live screen context ships.
159
+ - **History:** `conversations.list({ subject_id, agent, … })`, `conversations.listMessages(id, { subject_id })` and
160
+ `conversations.delete(id, { subject_id })` read and delete a person's past conversations; another subject's or an
161
+ unknown conversation is `not_found`, never told apart. **Served from A7**, when the gateway's history support ships:
162
+ until then every call is answered 404, which reads as `not_found` and does not mean the conversation is unknown.
155
163
  - **Every operation** is also on `vinaverse.api`, the typed openapi-fetch client (`api.GET('/v1/usage')`).
156
164
  - **Backend only.** The client refuses a client secret, and refuses to start in a browser or in React Native: a
157
165
  service key there ships to everyone who loads the app. Apps use `@vinaverse/client` with the session's client secret.
package/dist/api.cjs CHANGED
@@ -342,6 +342,17 @@ function createApiClient(options) {
342
342
  ...init(o)
343
343
  })
344
344
  ),
345
+ /**
346
+ * Where the person is now, for an open session (no new session per screen): a screen context, or
347
+ * `{ clear: true, revision }`; `revision` greater than the session's, the same revision and body a retry.
348
+ */
349
+ updateContext: (sessionId, body, o) => run(
350
+ api.PUT("/v1/sessions/{session_id}/context", {
351
+ params: { path: { session_id: sessionId } },
352
+ body,
353
+ ...init(o)
354
+ })
355
+ ),
345
356
  /** A fresh client secret for an open session: what an app's `refreshSecret(sessionId)` asks your backend for. */
346
357
  refreshClientSecret: (sessionId, o) => run(
347
358
  api.POST("/v1/sessions/{session_id}/client_secret", {
@@ -356,6 +367,24 @@ function createApiClient(options) {
356
367
  params: { path: { conversation_id: conversationId } },
357
368
  ...init(o)
358
369
  })
370
+ ),
371
+ /** A person's past conversations with an agent, newest activity first (history). */
372
+ list: (query, o) => run(
373
+ api.GET("/v1/conversations", { params: { query }, ...init(o) })
374
+ ),
375
+ /** A past conversation's messages, the newest page first and oldest first within a page. */
376
+ listMessages: (conversationId, query, o) => run(
377
+ api.GET("/v1/conversations/{conversation_id}/messages", {
378
+ params: { path: { conversation_id: conversationId }, query },
379
+ ...init(o)
380
+ })
381
+ ),
382
+ /** Deletes a person's conversation (history's delete); another subject's or an unknown one is `not_found`. */
383
+ delete: (conversationId, query, o) => run(
384
+ api.DELETE("/v1/conversations/{conversation_id}", {
385
+ params: { path: { conversation_id: conversationId }, query },
386
+ ...init(o)
387
+ })
359
388
  )
360
389
  },
361
390
  suggestions: {
package/dist/api.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/errors.ts","../src/api/random.ts","../src/api/retry.ts","../src/api/client.ts"],"names":["createClient","key"],"mappings":";;;;;;;;;;;AAQO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;AAAA,EAChB,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,cAAA;AAAA,EAET,YAAY,IAAA,EAMT;AACD,IAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAQ,GAAI,IAAA;AAC5B,IAAA,KAAA;AAAA,MACE,UACI,CAAA,EAAG,OAAA,CAAQ,KAA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What the Vinaverse API answers when it refuses a call: RFC 9457 problem details (vinaverse-v1.yaml, `Problem`),\n// as a typed error. conformance/README.md §5 lists every code with its status and whether it is retryable.\nimport type { components } from '../generated/vinaverse-v1.js';\n\nexport type ApiProblem = components['schemas']['Problem'];\nexport type ApiProblemCode = ApiProblem['code'];\n\n/** The API refused a call: its problem details, typed, with the request id to quote to support. */\nexport class VinaverseApiError extends Error {\n override readonly name = 'VinaverseApiError';\n readonly status: number;\n /** The problem's code (`invalid_request`, `rate_limited`, …), or `http_<status>` when the body was not a problem. */\n readonly code: ApiProblemCode | `http_${number}`;\n /** Whether the same call may succeed later: the problem's `retryable`, else true for 429 and 5xx. */\n readonly retryable: boolean;\n /** `Vinaverse-Request-Id`, or the problem's `request_id`. */\n readonly requestId: string | undefined;\n /** `Retry-After`, in seconds, when the API sent one. */\n readonly retryAfter: number | undefined;\n /** For `invalid_request`: the fields refused, as JSON Pointers into the request. */\n readonly errors: readonly { pointer: string; message: string }[];\n /** The problem as sent, or undefined when the body was not one. */\n readonly problem: ApiProblem | undefined;\n /** The `Idempotency-Key` the call carried: send the same call again with it to have it done once. */\n readonly idempotencyKey: string | undefined;\n\n constructor(init: {\n status: number;\n problem?: ApiProblem | undefined;\n requestId?: string | undefined;\n retryAfter?: number | undefined;\n idempotencyKey?: string | undefined;\n }) {\n const { status, problem } = init;\n super(\n problem\n ? `${problem.title} (${problem.code})${problem.detail ? `: ${problem.detail}` : ''}`\n : `The Vinaverse API answered HTTP ${status}.`,\n );\n this.idempotencyKey = init.idempotencyKey;\n this.status = status;\n this.problem = problem;\n this.code = problem?.code ?? `http_${status}`;\n this.retryable = problem?.retryable ?? (status === 429 || status >= 500);\n this.requestId = init.requestId ?? problem?.request_id;\n this.retryAfter = init.retryAfter;\n this.errors = problem?.errors ?? [];\n }\n}\n\n/** The error for a refused response and its parsed body: what every call of the API client throws. */\nexport function apiError(\n response: Response,\n body: unknown,\n idempotencyKey?: string,\n): VinaverseApiError {\n return new VinaverseApiError({\n status: response.status,\n problem: isProblem(body) ? body : undefined,\n requestId: response.headers.get('vinaverse-request-id') ?? undefined,\n retryAfter: retryAfterSeconds(response),\n idempotencyKey,\n });\n}\n\n/** `Retry-After` in seconds: a number of seconds or an HTTP date; undefined when absent or unreadable. */\nexport function retryAfterSeconds(\n response: Response,\n now: () => number = Date.now,\n): number | undefined {\n const value = response.headers.get('retry-after');\n if (value === null || value.trim() === '') return undefined;\n if (/^\\d+$/.test(value.trim())) return Number(value.trim());\n const at = Date.parse(value);\n return Number.isNaN(at)\n ? undefined\n : Math.max(0, Math.ceil((at - now()) / 1000));\n}\n\nfunction isProblem(body: unknown): body is ApiProblem {\n if (typeof body !== 'object' || body === null) return false;\n const b = body as Record<string, unknown>;\n return typeof b.code === 'string' && typeof b.status === 'number';\n}\n","// A random UUID for idempotency keys wherever the client runs. Node 20+, Deno, Bun and edge runtimes have\n// `crypto.randomUUID`; Node 18 has it only in its crypto module when loaded as an ES module, so it is loaded from\n// there, once.\nlet fromNode: Promise<() => string> | undefined;\n\nexport async function randomUUID(): Promise<string> {\n const global = (globalThis as { crypto?: { randomUUID?: () => string } })\n .crypto;\n if (global?.randomUUID) return global.randomUUID();\n // Built at run time on purpose: a bundler for an edge runtime, where this line never runs, must not resolve it.\n const specifier = ['node', 'crypto'].join(':');\n fromNode ??= import(\n /* webpackIgnore: true */ /* @vite-ignore */ specifier\n ).then((mod: { randomUUID: () => string }) => mod.randomUUID);\n return (await fromNode)();\n}\n","// Safe retries for calls to the Vinaverse API. A call is sent again only when that cannot do it twice:\n// - `429`: the API refused it before doing anything, so any call is retried, after its `Retry-After`;\n// - a retryable failure (a `5xx`, a problem with `retryable: true`, a timeout or a network error): only a read\n// (`GET`, `HEAD`, `OPTIONS`), an idempotent `PUT` or `DELETE`, or a call carrying an `Idempotency-Key`, which the\n// API answers once whatever the number of tries.\n// Delays: `Retry-After` when the API sends one, else 0.5 s doubling, with jitter; a `Retry-After` longer than\n// `maxRetryDelay` is not waited for: the refusal is returned.\n// Each try reads the whole response within its timeout, so a stalled body cannot hang a call, and the caller's\n// signal stops everything at once: a try in flight, a body being read, a wait between tries. An aborted signal never\n// sends the call. Redirects are refused: a service key never follows one.\n\nimport { retryAfterSeconds } from './errors.js';\n\nexport type FetchFn = (input: Request) => Promise<Response>;\n\nexport interface RetryOptions {\n /** Retries after the first try: a whole number, 0 or more; default 2. */\n readonly maxRetries?: number;\n /** The longest wait, in seconds, before a retry: 0 to 2 147 483 (a timer's limit); default 30. */\n readonly maxRetryDelay?: number;\n /** One try's timeout, reading the body included, in milliseconds: more than 0, at most 2 147 483 647; default 30 000. */\n readonly timeout?: number;\n /** Waits, in milliseconds; tests replace it. The wait ends early when the call is aborted. */\n readonly sleep?: (ms: number) => Promise<void>;\n readonly random?: () => number;\n}\n\nconst IDEMPOTENT = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);\n/** Statuses whose responses have no body. */\nconst NULL_BODY = new Set([101, 204, 205, 304]);\n/** A refusal's body is read up to this size: a problem is far smaller; more is an intermediary's page. */\nconst MAX_REFUSAL_BYTES = 64 * 1024;\n\n/**\n * The API did not answer within `timeout` on the last try. `idempotencyKey` is the key the call carried: pass it as\n * `{ idempotencyKey }` to try the same call again later without doing it twice.\n */\nexport class VinaverseTimeoutError extends Error {\n override readonly name = 'VinaverseTimeoutError';\n readonly idempotencyKey: string | undefined;\n constructor(ms: number, idempotencyKey?: string) {\n super(`The Vinaverse API did not answer within ${ms} ms.`);\n this.idempotencyKey = idempotencyKey;\n }\n}\n\n/** The call could not reach the API (`cause` holds why). `idempotencyKey` as for a timeout. */\nexport class VinaverseNetworkError extends Error {\n override readonly name = 'VinaverseNetworkError';\n readonly idempotencyKey: string | undefined;\n constructor(cause: unknown, idempotencyKey?: string) {\n super(\n `The Vinaverse API could not be reached: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.idempotencyKey = idempotencyKey;\n }\n}\n\n/** The longest a timer can wait: beyond it, Node fires it after 1 ms. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/**\n * `guard` checks each request's URL before anything is sent (the client allows its own origin only); what it throws\n * is thrown as is.\n */\nexport function retryingFetch(\n fetchFn: FetchFn,\n options: RetryOptions = {},\n guard: (url: string) => void = () => {},\n): FetchFn {\n const maxRetries = check(\n 'maxRetries',\n options.maxRetries ?? 2,\n (n) => Number.isSafeInteger(n) && n >= 0,\n );\n const maxDelay =\n check(\n 'maxRetryDelay',\n options.maxRetryDelay ?? 30,\n (n) => Number.isFinite(n) && n >= 0 && n * 1000 <= MAX_TIMER_MS,\n ) * 1000;\n const timeout = check(\n 'timeout',\n options.timeout ?? 30_000,\n (n) => Number.isFinite(n) && n > 0 && n <= MAX_TIMER_MS,\n );\n const sleep = options.sleep;\n const random = options.random ?? Math.random;\n\n return async (request) => {\n guard(request.url);\n const signal = request.signal;\n const key = request.headers.get('idempotency-key') ?? undefined;\n const replayable =\n IDEMPOTENT.has(request.method.toUpperCase()) || key !== undefined;\n for (let attempt = 0; ; attempt++) {\n if (signal.aborted) throw aborted(signal);\n const last = attempt >= maxRetries;\n let response: Response;\n try {\n response = await once(fetchFn, request.clone(), signal, timeout);\n } catch (error) {\n if (signal.aborted) throw aborted(signal);\n // A network error or a timeout: the call may have been done; only a replayable one goes again.\n if (last || !replayable) {\n throw error instanceof VinaverseTimeoutError\n ? new VinaverseTimeoutError(timeout, key)\n : new VinaverseNetworkError(error, key);\n }\n await wait(sleep, Math.min(backoff(attempt, random), maxDelay), signal);\n continue;\n }\n const retry =\n response.status === 429 ||\n (replayable && retryable(response, await problemOf(response)));\n if (!retry || last) return response;\n const delay = retryAfter(response) ?? backoff(attempt, random);\n if (delay > maxDelay) return response;\n await wait(sleep, delay, signal);\n }\n };\n}\n\n/** One try, its body read in full within the timeout; refused bodies up to `MAX_REFUSAL_BYTES`. */\nasync function once(\n fetchFn: FetchFn,\n request: Request,\n signal: AbortSignal,\n timeout: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n const stop = () => controller.abort();\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) controller.abort();\n try {\n // Raced against the timeout and the caller's signal too, so a transport that ignores its signal is still bounded.\n const pending = fetchFn(\n new Request(request, { signal: controller.signal, redirect: 'error' }),\n );\n pending.catch(() => {}); // when the abort wins, the transport's own failure is not reported twice\n const response = await until(pending, controller.signal);\n const empty = NULL_BODY.has(response.status);\n const body = empty\n ? null\n : await readBody(\n response,\n response.ok ? Number.POSITIVE_INFINITY : MAX_REFUSAL_BYTES,\n controller.signal,\n );\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } catch (error) {\n if (controller.signal.aborted && !signal.aborted)\n throw new VinaverseTimeoutError(timeout);\n throw error;\n } finally {\n clearTimeout(timer);\n signal.removeEventListener('abort', stop);\n }\n}\n\nasync function readBody(\n response: Response,\n limit: number,\n signal: AbortSignal,\n): Promise<Uint8Array<ArrayBuffer> | null> {\n if (!response.body) return null;\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const read = reader.read();\n read.catch(() => {}); // an abort below wins; the read's own failure is not reported twice\n const { done, value } = await until(read, signal).catch(\n async (error: unknown) => {\n void reader.cancel().catch(() => {}); // not awaited: a teed body settles its cancel only with its twin\n throw error;\n },\n );\n if (done) break;\n chunks.push(value);\n size += value.length;\n if (size >= limit) {\n void reader.cancel().catch(() => {}); // not awaited: a teed body settles its cancel only with its twin\n break;\n }\n }\n const body = new Uint8Array(new ArrayBuffer(Math.min(size, limit)));\n let at = 0;\n for (const chunk of chunks) {\n const part = chunk.subarray(0, body.length - at);\n body.set(part, at);\n at += part.length;\n if (at >= body.length) break;\n }\n return body;\n}\n\nasync function problemOf(\n response: Response,\n): Promise<{ retryable?: unknown } | undefined> {\n if (response.ok) return undefined;\n try {\n return (await response.clone().json()) as { retryable?: unknown };\n } catch {\n return undefined;\n }\n}\n\nfunction retryable(\n response: Response,\n problem: { retryable?: unknown } | undefined,\n): boolean {\n if (response.status >= 500) return true;\n // Another refusal is retried only when the API says so.\n return response.status >= 400 && problem?.retryable === true;\n}\n\n/** `promise`, or the signal's abort, whichever comes first. */\nasync function until<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw aborted(signal);\n let stop: () => void = () => {};\n const abort = new Promise<never>((_, reject) => {\n stop = () => reject(aborted(signal));\n signal.addEventListener('abort', stop, { once: true });\n });\n try {\n return await Promise.race([promise, abort]);\n } finally {\n signal.removeEventListener('abort', stop);\n }\n}\n\n/** Waits `ms`, or less: an abort ends the wait, clears its timer, and throws. */\nfunction wait(\n sleep: ((ms: number) => Promise<void>) | undefined,\n ms: number,\n signal: AbortSignal,\n): Promise<void> {\n if (sleep) return until(sleep(ms), signal);\n if (signal.aborted) return Promise.reject(aborted(signal));\n return new Promise<void>((resolve, reject) => {\n const stop = () => {\n clearTimeout(timer);\n reject(aborted(signal));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', stop);\n resolve();\n }, ms);\n signal.addEventListener('abort', stop, { once: true });\n });\n}\n\nfunction aborted(signal: AbortSignal): unknown {\n return (\n signal.reason ?? new DOMException('The call was aborted.', 'AbortError')\n );\n}\n\nfunction retryAfter(response: Response): number | undefined {\n const seconds = retryAfterSeconds(response);\n return seconds === undefined ? undefined : seconds * 1000;\n}\n\nfunction backoff(attempt: number, random: () => number): number {\n const base = 500 * 2 ** attempt;\n return Math.round(base / 2 + random() * (base / 2));\n}\n\nfunction check(\n name: string,\n value: number,\n valid: (n: number) => boolean,\n): number {\n if (typeof value !== 'number' || !valid(value)) {\n throw new TypeError(`${name} is not valid: ${String(value)}`);\n }\n return value;\n}\n","// The Vinaverse API from a Node backend: typed calls generated from the pinned public contract (vinaverse-v1.yaml,\n// through openapi-fetch), authenticated with a service key, with idempotency keys added where the contract wants\n// one, safe retries honouring `Retry-After` (./retry.ts), and refusals thrown as typed errors (./errors.ts).\n// A service key never belongs in a browser or an app: the client refuses to start there.\nimport createClient, { type Client } from 'openapi-fetch';\nimport type { operations, paths } from '../generated/vinaverse-v1.js';\nimport { apiError } from './errors.js';\nimport { randomUUID } from './random.js';\nimport { type FetchFn, type RetryOptions, retryingFetch } from './retry.js';\n\ntype Op = operations;\n/** An operation's JSON request body. */\nexport type ApiBody<K extends keyof Op> = Op[K] extends {\n requestBody?: { content: { 'application/json': infer B } };\n}\n ? B\n : never;\n/** An operation's success result. */\nexport type ApiResult<K extends keyof Op> = Success<Op[K]['responses']>;\ntype Success<R> = R extends {\n 200: { content: { 'application/json': infer B } };\n}\n ? B\n : R extends { 201: { content: { 'application/json': infer B } } }\n ? B\n : R extends { 202: { content: { 'application/json': infer B } } }\n ? B\n : undefined;\ntype QueryOf<K extends keyof Op> = Op[K]['parameters'] extends {\n query?: infer Q;\n}\n ? NonNullable<Q>\n : never;\n\n/** Per call: a signal that stops it at once, waits between tries included. */\nexport interface CallOptions {\n readonly signal?: AbortSignal;\n}\n\n/**\n * For the calls the contract makes idempotent: a key of your own, 1 to 255 characters (one is made otherwise).\n * After a `VinaverseTimeoutError` or a `VinaverseNetworkError`, try again later with the error's `idempotencyKey`,\n * so the call is done once however many times it is sent.\n */\nexport interface KeyedCallOptions extends CallOptions {\n readonly idempotencyKey?: string;\n}\n\nexport interface ApiClientOptions extends RetryOptions {\n /** A service key, `vv_sk_<mock|dev|live>_…`: from your secrets store, never from code. */\n readonly apiKey: string;\n /**\n * Default: `https://api.vinaverse.com` for a live key, `https://api-dev.vinaverse.com` for mock and dev keys. Any\n * other URL must be `https:` (a proxy you run, say), or `http:` on this machine only (`localhost`, `127.0.0.1`,\n * `[::1]`): a service key never travels in clear.\n */\n readonly baseUrl?: string;\n readonly fetch?: (request: Request) => Promise<Response>;\n /** Extra headers on every call, for example `Vinaverse-Mock-Scenario` in tests against the mock environment. */\n readonly headers?: Readonly<Record<string, string>>;\n}\n\nconst SERVICE_KEY = /^vv_sk_(mock|dev|live)_[A-Za-z0-9_-]{8,}$/;\n\n/** The client was made where a service key must never be: a browser or an app. */\nexport class ServiceKeyExposureError extends Error {\n override readonly name = 'ServiceKeyExposureError';\n}\n\nexport function createApiClient(options: ApiClientOptions) {\n refuseClientRuntime();\n const key = options.apiKey;\n if (typeof key !== 'string' || !SERVICE_KEY.test(key)) {\n throw new TypeError(\n key?.startsWith?.('vv_cs_')\n ? 'createApiClient takes a service key (vv_sk_…); a client secret (vv_cs_…) is for the app'\n : 'createApiClient needs a service key: vv_sk_<mock|dev|live>_…',\n );\n }\n const live = key.startsWith('vv_sk_live_');\n const baseUrl = safeBaseUrl(\n options.baseUrl ??\n (live ? 'https://api.vinaverse.com' : 'https://api-dev.vinaverse.com'),\n );\n const transport: FetchFn =\n options.fetch ?? ((request) => globalThis.fetch(request));\n const api: Client<paths> = createClient<paths>({\n baseUrl,\n redirect: 'error', // the API never redirects; a service key never follows one\n // Every request, from a helper or from `api` with a per-call baseUrl, goes to this origin only.\n fetch: retryingFetch(transport, options, sameOrigin(baseUrl)),\n headers: {\n ...options.headers,\n authorization: `Bearer ${key}`,\n accept: 'application/json',\n },\n });\n\n type Answer = Promise<{\n data?: unknown;\n error?: unknown;\n response: Response;\n }>;\n async function run<T>(call: Answer, idempotencyKey?: string): Promise<T> {\n const { data, error, response } = await call;\n if (!response.ok) throw apiError(response, error, idempotencyKey);\n return data as T;\n }\n /** A call the contract makes idempotent: under the caller's key, or a new one, on every try. */\n async function keyed<T>(\n o: KeyedCallOptions | undefined,\n call: (header: { 'Idempotency-Key': string }) => Answer,\n ): Promise<T> {\n const key = o?.idempotencyKey ?? (await newKey());\n if (typeof key !== 'string' || key.length < 1 || key.length > 255) {\n throw new TypeError('idempotencyKey must be 1 to 255 characters');\n }\n return run<T>(call({ 'Idempotency-Key': key }), key);\n }\n const init = (o?: CallOptions) => (o?.signal ? { signal: o.signal } : {});\n\n return {\n /** Every operation of the contract, typed, for what the helpers below do not cover (openapi-fetch). */\n api,\n sessions: {\n /** Mint a session for the person in your app; give the app its `id`, URLs and `client_secret` only. */\n create: (body: ApiBody<'createSession'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createSession'>>(o, (header) =>\n api.POST('/v1/sessions', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n get: (sessionId: string, o?: CallOptions) =>\n run<ApiResult<'getSession'>>(\n api.GET('/v1/sessions/{session_id}', {\n params: { path: { session_id: sessionId } },\n ...init(o),\n }),\n ),\n revoke: (sessionId: string, o?: CallOptions) =>\n run<ApiResult<'revokeSession'>>(\n api.POST('/v1/sessions/{session_id}/revoke', {\n params: { path: { session_id: sessionId } },\n ...init(o),\n }),\n ),\n /** A fresh client secret for an open session: what an app's `refreshSecret(sessionId)` asks your backend for. */\n refreshClientSecret: (sessionId: string, o?: CallOptions) =>\n run<ApiResult<'refreshClientSecret'>>(\n api.POST('/v1/sessions/{session_id}/client_secret', {\n params: { path: { session_id: sessionId } },\n ...init(o),\n }),\n ),\n },\n conversations: {\n get: (conversationId: string, o?: CallOptions) =>\n run<ApiResult<'getConversation'>>(\n api.GET('/v1/conversations/{conversation_id}', {\n params: { path: { conversation_id: conversationId } },\n ...init(o),\n }),\n ),\n },\n suggestions: {\n create: (body: ApiBody<'createSuggestions'>, o?: CallOptions) =>\n run<ApiResult<'createSuggestions'>>(\n api.POST('/v1/suggestions', { body, ...init(o) }),\n ),\n },\n moderation: {\n createJob: (body: ApiBody<'createModerationJob'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createModerationJob'>>(o, (header) =>\n api.POST('/v1/moderation/jobs', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n getJob: (jobId: string, o?: CallOptions) =>\n run<ApiResult<'getModerationJob'>>(\n api.GET('/v1/moderation/jobs/{job_id}', {\n params: { path: { job_id: jobId } },\n ...init(o),\n }),\n ),\n getItem: (itemId: string, o?: CallOptions) =>\n run<ApiResult<'getModerationItem'>>(\n api.GET('/v1/moderation/items/{item_id}', {\n params: { path: { item_id: itemId } },\n ...init(o),\n }),\n ),\n },\n media: {\n createJob: (body: ApiBody<'createMediaJob'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createMediaJob'>>(o, (header) =>\n api.POST('/v1/media/jobs', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n listJobs: (query: QueryOf<'listMediaJobs'> = {}, o?: CallOptions) =>\n run<ApiResult<'listMediaJobs'>>(\n api.GET('/v1/media/jobs', { params: { query }, ...init(o) }),\n ),\n getJob: (jobId: string, o?: CallOptions) =>\n run<ApiResult<'getMediaJob'>>(\n api.GET('/v1/media/jobs/{job_id}', {\n params: { path: { job_id: jobId } },\n ...init(o),\n }),\n ),\n cancelJob: (jobId: string, o?: CallOptions) =>\n run<ApiResult<'cancelMediaJob'>>(\n api.POST('/v1/media/jobs/{job_id}/cancel', {\n params: { path: { job_id: jobId } },\n ...init(o),\n }),\n ),\n listProfiles: (o?: CallOptions) =>\n run<ApiResult<'listMediaProfiles'>>(\n api.GET('/v1/media/profiles', { ...init(o) }),\n ),\n },\n screening: {\n text: (body: ApiBody<'screenText'>, o?: CallOptions) =>\n run<ApiResult<'screenText'>>(\n api.POST('/v1/screening/text', { body, ...init(o) }),\n ),\n },\n documentChecks: {\n create: (body: ApiBody<'createDocumentCheck'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createDocumentCheck'>>(o, (header) =>\n api.POST('/v1/document-checks', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n get: (checkId: string, o?: CallOptions) =>\n run<ApiResult<'getDocumentCheck'>>(\n api.GET('/v1/document-checks/{check_id}', {\n params: { path: { check_id: checkId } },\n ...init(o),\n }),\n ),\n },\n subjects: {\n erase: (subjectId: string, o?: KeyedCallOptions) =>\n keyed<ApiResult<'eraseSubject'>>(o, (header) =>\n api.POST('/v1/subjects/{subject_id}/erase', {\n params: { path: { subject_id: subjectId }, header },\n ...init(o),\n }),\n ),\n },\n feedback: {\n send: (body: ApiBody<'sendFeedback'>, o?: CallOptions) =>\n run<ApiResult<'sendFeedback'>>(\n api.POST('/v1/feedback', { body, ...init(o) }),\n ),\n },\n events: {\n send: (body: ApiBody<'sendEvents'>, o?: CallOptions) =>\n run<ApiResult<'sendEvents'>>(\n api.POST('/v1/events', { body, ...init(o) }),\n ),\n },\n knowledge: {\n sendDocument: (body: ApiBody<'sendKnowledgeDocument'>, o?: CallOptions) =>\n run<ApiResult<'sendKnowledgeDocument'>>(\n api.POST('/v1/knowledge/documents', { body, ...init(o) }),\n ),\n },\n catalog: {\n put: (\n type: Op['putCatalogEntity']['parameters']['path']['type'],\n id: string,\n body: ApiBody<'putCatalogEntity'>,\n o?: CallOptions,\n ) =>\n run<ApiResult<'putCatalogEntity'>>(\n api.PUT('/v1/catalog/{type}/{id}', {\n params: { path: { type, id } },\n body,\n ...init(o),\n }),\n ),\n },\n usage: {\n get: (query: QueryOf<'getUsage'> = {}, o?: CallOptions) =>\n run<ApiResult<'getUsage'>>(\n api.GET('/v1/usage', { params: { query }, ...init(o) }),\n ),\n },\n };\n}\n\nexport type ApiClient = ReturnType<typeof createApiClient>;\n\n/**\n * Throws in a browser (a `window` with a `document`) and in React Native: a service key there ships to everyone who\n * loads the app. Node, AWS Lambda, Deno, Bun and edge runtimes have neither.\n */\nfunction refuseClientRuntime(): void {\n const scope = globalThis as {\n window?: unknown;\n document?: unknown;\n navigator?: { product?: unknown };\n };\n if (scope.window !== undefined && scope.document !== undefined) {\n throw new ServiceKeyExposureError(\n 'The Vinaverse API client holds a service key and runs on your backend only, never in a browser. Give the app a session client secret (sessions.create).',\n );\n }\n if (scope.navigator?.product === 'ReactNative') {\n throw new ServiceKeyExposureError(\n 'The Vinaverse API client holds a service key and runs on your backend only, never in an app. Use @vinaverse/client with a session client secret.',\n );\n }\n}\n\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** The base URL, checked: `https:`, or `http:` on this machine only, so a service key never travels in clear. */\nfunction safeBaseUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new TypeError(`baseUrl is not a URL: ${value}`);\n }\n if (\n url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))\n ) {\n throw new TypeError(\n `baseUrl must be https: (or http: on localhost); a service key never travels in clear: ${url.origin}`,\n );\n }\n return value.replace(/\\/+$/, '');\n}\n\n/** A check for every request: the client's own origin, and so never in clear nor to another host. */\nfunction sameOrigin(baseUrl: string): (url: string) => void {\n const origin = new URL(baseUrl).origin;\n return (url) => {\n const target = new URL(url);\n if (target.origin !== origin) {\n throw new TypeError(\n `The Vinaverse API client sends its service key to ${origin} only, not to ${target.origin}`,\n );\n }\n };\n}\n\nfunction newKey(): Promise<string> {\n return randomUUID();\n}\n"]}
1
+ {"version":3,"sources":["../src/api/errors.ts","../src/api/random.ts","../src/api/retry.ts","../src/api/client.ts"],"names":["createClient","key"],"mappings":";;;;;;;;;;;AAQO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;AAAA,EAChB,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,cAAA;AAAA,EAET,YAAY,IAAA,EAMT;AACD,IAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAQ,GAAI,IAAA;AAC5B,IAAA,KAAA;AAAA,MACE,UACI,CAAA,EAAG,OAAA,CAAQ,KAAK,CAAA,EAAA,EAAK,QAAQ,IAAI,CAAA,CAAA,EAAI,OAAA,CAAQ,MAAA,GAAS,KAAK,OAAA,CAAQ,MAAM,KAAK,EAAE,CAAA,CAAA,GAChF,mCAAmC,MAAM,CAAA,CAAA;AAAA,KAC/C;AACA,IAAA,IAAA,CAAK,iBAAiB,IAAA,CAAK,cAAA;AAC3B,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAA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I,GAAA,CAAI,QAAQ,CAAA,CAAA,EACvD;AACA,IAAA,MAAM,IAAI,SAAA;AAAA,MACR,CAAA,sFAAA,EAAyF,IAAI,MAAM,CAAA;AAAA,KACrG;AAAA,EACF;AACA,EAAA,OAAO,KAAA,CAAM,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AACjC;AAGA,SAAS,WAAW,OAAA,EAAwC;AAC1D,EAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,OAAO,CAAA,CAAE,MAAA;AAChC,EAAA,OAAO,CAAC,GAAA,KAAQ;AACd,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,GAAG,CAAA;AAC1B,IAAA,IAAI,MAAA,CAAO,WAAW,MAAA,EAAQ;AAC5B,MAAA,MAAM,IAAI,SAAA;AAAA,QACR,CAAA,kDAAA,EAAqD,MAAM,CAAA,cAAA,EAAiB,MAAA,CAAO,MAAM,CAAA;AAAA,OAC3F;AAAA,IACF;AAAA,EACF,CAAA;AACF;AAEA,SAAS,MAAA,GAA0B;AACjC,EAAA,OAAO,UAAA,EAAW;AACpB","file":"api.cjs","sourcesContent":["// What the Vinaverse API answers when it refuses a call: RFC 9457 problem details (vinaverse-v1.yaml, `Problem`),\n// as a typed error. conformance/README.md §5 lists every code with its status and whether it is retryable.\nimport type { components } from '../generated/vinaverse-v1.js';\n\nexport type ApiProblem = components['schemas']['Problem'];\nexport type ApiProblemCode = ApiProblem['code'];\n\n/** The API refused a call: its problem details, typed, with the request id to quote to support. */\nexport class VinaverseApiError extends Error {\n override readonly name = 'VinaverseApiError';\n readonly status: number;\n /** The problem's code (`invalid_request`, `rate_limited`, …), or `http_<status>` when the body was not a problem. */\n readonly code: ApiProblemCode | `http_${number}`;\n /** Whether the same call may succeed later: the problem's `retryable`, else true for 429 and 5xx. */\n readonly retryable: boolean;\n /** `Vinaverse-Request-Id`, or the problem's `request_id`. */\n readonly requestId: string | undefined;\n /** `Retry-After`, in seconds, when the API sent one. */\n readonly retryAfter: number | undefined;\n /** For `invalid_request`: the fields refused, as JSON Pointers into the request. */\n readonly errors: readonly { pointer: string; message: string }[];\n /** The problem as sent, or undefined when the body was not one. */\n readonly problem: ApiProblem | undefined;\n /** The `Idempotency-Key` the call carried: send the same call again with it to have it done once. */\n readonly idempotencyKey: string | undefined;\n\n constructor(init: {\n status: number;\n problem?: ApiProblem | undefined;\n requestId?: string | undefined;\n retryAfter?: number | undefined;\n idempotencyKey?: string | undefined;\n }) {\n const { status, problem } = init;\n super(\n problem\n ? `${problem.title} (${problem.code})${problem.detail ? `: ${problem.detail}` : ''}`\n : `The Vinaverse API answered HTTP ${status}.`,\n );\n this.idempotencyKey = init.idempotencyKey;\n this.status = status;\n this.problem = problem;\n this.code = problem?.code ?? `http_${status}`;\n this.retryable = problem?.retryable ?? (status === 429 || status >= 500);\n this.requestId = init.requestId ?? problem?.request_id;\n this.retryAfter = init.retryAfter;\n this.errors = problem?.errors ?? [];\n }\n}\n\n/** The error for a refused response and its parsed body: what every call of the API client throws. */\nexport function apiError(\n response: Response,\n body: unknown,\n idempotencyKey?: string,\n): VinaverseApiError {\n return new VinaverseApiError({\n status: response.status,\n problem: isProblem(body) ? body : undefined,\n requestId: response.headers.get('vinaverse-request-id') ?? undefined,\n retryAfter: retryAfterSeconds(response),\n idempotencyKey,\n });\n}\n\n/** `Retry-After` in seconds: a number of seconds or an HTTP date; undefined when absent or unreadable. */\nexport function retryAfterSeconds(\n response: Response,\n now: () => number = Date.now,\n): number | undefined {\n const value = response.headers.get('retry-after');\n if (value === null || value.trim() === '') return undefined;\n if (/^\\d+$/.test(value.trim())) return Number(value.trim());\n const at = Date.parse(value);\n return Number.isNaN(at)\n ? undefined\n : Math.max(0, Math.ceil((at - now()) / 1000));\n}\n\nfunction isProblem(body: unknown): body is ApiProblem {\n if (typeof body !== 'object' || body === null) return false;\n const b = body as Record<string, unknown>;\n return typeof b.code === 'string' && typeof b.status === 'number';\n}\n","// A random UUID for idempotency keys wherever the client runs. Node 20+, Deno, Bun and edge runtimes have\n// `crypto.randomUUID`; Node 18 has it only in its crypto module when loaded as an ES module, so it is loaded from\n// there, once.\nlet fromNode: Promise<() => string> | undefined;\n\nexport async function randomUUID(): Promise<string> {\n const global = (globalThis as { crypto?: { randomUUID?: () => string } })\n .crypto;\n if (global?.randomUUID) return global.randomUUID();\n // Built at run time on purpose: a bundler for an edge runtime, where this line never runs, must not resolve it.\n const specifier = ['node', 'crypto'].join(':');\n fromNode ??= import(\n /* webpackIgnore: true */ /* @vite-ignore */ specifier\n ).then((mod: { randomUUID: () => string }) => mod.randomUUID);\n return (await fromNode)();\n}\n","// Safe retries for calls to the Vinaverse API. A call is sent again only when that cannot do it twice:\n// - `429`: the API refused it before doing anything, so any call is retried, after its `Retry-After`;\n// - a retryable failure (a `5xx`, a problem with `retryable: true`, a timeout or a network error): only a read\n// (`GET`, `HEAD`, `OPTIONS`), an idempotent `PUT` or `DELETE`, or a call carrying an `Idempotency-Key`, which the\n// API answers once whatever the number of tries.\n// Delays: `Retry-After` when the API sends one, else 0.5 s doubling, with jitter; a `Retry-After` longer than\n// `maxRetryDelay` is not waited for: the refusal is returned.\n// Each try reads the whole response within its timeout, so a stalled body cannot hang a call, and the caller's\n// signal stops everything at once: a try in flight, a body being read, a wait between tries. An aborted signal never\n// sends the call. Redirects are refused: a service key never follows one.\n\nimport { retryAfterSeconds } from './errors.js';\n\nexport type FetchFn = (input: Request) => Promise<Response>;\n\nexport interface RetryOptions {\n /** Retries after the first try: a whole number, 0 or more; default 2. */\n readonly maxRetries?: number;\n /** The longest wait, in seconds, before a retry: 0 to 2 147 483 (a timer's limit); default 30. */\n readonly maxRetryDelay?: number;\n /** One try's timeout, reading the body included, in milliseconds: more than 0, at most 2 147 483 647; default 30 000. */\n readonly timeout?: number;\n /** Waits, in milliseconds; tests replace it. The wait ends early when the call is aborted. */\n readonly sleep?: (ms: number) => Promise<void>;\n readonly random?: () => number;\n}\n\nconst IDEMPOTENT = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);\n/** Statuses whose responses have no body. */\nconst NULL_BODY = new Set([101, 204, 205, 304]);\n/** A refusal's body is read up to this size: a problem is far smaller; more is an intermediary's page. */\nconst MAX_REFUSAL_BYTES = 64 * 1024;\n\n/**\n * The API did not answer within `timeout` on the last try. `idempotencyKey` is the key the call carried: pass it as\n * `{ idempotencyKey }` to try the same call again later without doing it twice.\n */\nexport class VinaverseTimeoutError extends Error {\n override readonly name = 'VinaverseTimeoutError';\n readonly idempotencyKey: string | undefined;\n constructor(ms: number, idempotencyKey?: string) {\n super(`The Vinaverse API did not answer within ${ms} ms.`);\n this.idempotencyKey = idempotencyKey;\n }\n}\n\n/** The call could not reach the API (`cause` holds why). `idempotencyKey` as for a timeout. */\nexport class VinaverseNetworkError extends Error {\n override readonly name = 'VinaverseNetworkError';\n readonly idempotencyKey: string | undefined;\n constructor(cause: unknown, idempotencyKey?: string) {\n super(\n `The Vinaverse API could not be reached: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.idempotencyKey = idempotencyKey;\n }\n}\n\n/** The longest a timer can wait: beyond it, Node fires it after 1 ms. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/**\n * `guard` checks each request's URL before anything is sent (the client allows its own origin only); what it throws\n * is thrown as is.\n */\nexport function retryingFetch(\n fetchFn: FetchFn,\n options: RetryOptions = {},\n guard: (url: string) => void = () => {},\n): FetchFn {\n const maxRetries = check(\n 'maxRetries',\n options.maxRetries ?? 2,\n (n) => Number.isSafeInteger(n) && n >= 0,\n );\n const maxDelay =\n check(\n 'maxRetryDelay',\n options.maxRetryDelay ?? 30,\n (n) => Number.isFinite(n) && n >= 0 && n * 1000 <= MAX_TIMER_MS,\n ) * 1000;\n const timeout = check(\n 'timeout',\n options.timeout ?? 30_000,\n (n) => Number.isFinite(n) && n > 0 && n <= MAX_TIMER_MS,\n );\n const sleep = options.sleep;\n const random = options.random ?? Math.random;\n\n return async (request) => {\n guard(request.url);\n const signal = request.signal;\n const key = request.headers.get('idempotency-key') ?? undefined;\n const replayable =\n IDEMPOTENT.has(request.method.toUpperCase()) || key !== undefined;\n for (let attempt = 0; ; attempt++) {\n if (signal.aborted) throw aborted(signal);\n const last = attempt >= maxRetries;\n let response: Response;\n try {\n response = await once(fetchFn, request.clone(), signal, timeout);\n } catch (error) {\n if (signal.aborted) throw aborted(signal);\n // A network error or a timeout: the call may have been done; only a replayable one goes again.\n if (last || !replayable) {\n throw error instanceof VinaverseTimeoutError\n ? new VinaverseTimeoutError(timeout, key)\n : new VinaverseNetworkError(error, key);\n }\n await wait(sleep, Math.min(backoff(attempt, random), maxDelay), signal);\n continue;\n }\n const retry =\n response.status === 429 ||\n (replayable && retryable(response, await problemOf(response)));\n if (!retry || last) return response;\n const delay = retryAfter(response) ?? backoff(attempt, random);\n if (delay > maxDelay) return response;\n await wait(sleep, delay, signal);\n }\n };\n}\n\n/** One try, its body read in full within the timeout; refused bodies up to `MAX_REFUSAL_BYTES`. */\nasync function once(\n fetchFn: FetchFn,\n request: Request,\n signal: AbortSignal,\n timeout: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n const stop = () => controller.abort();\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) controller.abort();\n try {\n // Raced against the timeout and the caller's signal too, so a transport that ignores its signal is still bounded.\n const pending = fetchFn(\n new Request(request, { signal: controller.signal, redirect: 'error' }),\n );\n pending.catch(() => {}); // when the abort wins, the transport's own failure is not reported twice\n const response = await until(pending, controller.signal);\n const empty = NULL_BODY.has(response.status);\n const body = empty\n ? null\n : await readBody(\n response,\n response.ok ? Number.POSITIVE_INFINITY : MAX_REFUSAL_BYTES,\n controller.signal,\n );\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } catch (error) {\n if (controller.signal.aborted && !signal.aborted)\n throw new VinaverseTimeoutError(timeout);\n throw error;\n } finally {\n clearTimeout(timer);\n signal.removeEventListener('abort', stop);\n }\n}\n\nasync function readBody(\n response: Response,\n limit: number,\n signal: AbortSignal,\n): Promise<Uint8Array<ArrayBuffer> | null> {\n if (!response.body) return null;\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const read = reader.read();\n read.catch(() => {}); // an abort below wins; the read's own failure is not reported twice\n const { done, value } = await until(read, signal).catch(\n async (error: unknown) => {\n void reader.cancel().catch(() => {}); // not awaited: a teed body settles its cancel only with its twin\n throw error;\n },\n );\n if (done) break;\n chunks.push(value);\n size += value.length;\n if (size >= limit) {\n void reader.cancel().catch(() => {}); // not awaited: a teed body settles its cancel only with its twin\n break;\n }\n }\n const body = new Uint8Array(new ArrayBuffer(Math.min(size, limit)));\n let at = 0;\n for (const chunk of chunks) {\n const part = chunk.subarray(0, body.length - at);\n body.set(part, at);\n at += part.length;\n if (at >= body.length) break;\n }\n return body;\n}\n\nasync function problemOf(\n response: Response,\n): Promise<{ retryable?: unknown } | undefined> {\n if (response.ok) return undefined;\n try {\n return (await response.clone().json()) as { retryable?: unknown };\n } catch {\n return undefined;\n }\n}\n\nfunction retryable(\n response: Response,\n problem: { retryable?: unknown } | undefined,\n): boolean {\n if (response.status >= 500) return true;\n // Another refusal is retried only when the API says so.\n return response.status >= 400 && problem?.retryable === true;\n}\n\n/** `promise`, or the signal's abort, whichever comes first. */\nasync function until<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw aborted(signal);\n let stop: () => void = () => {};\n const abort = new Promise<never>((_, reject) => {\n stop = () => reject(aborted(signal));\n signal.addEventListener('abort', stop, { once: true });\n });\n try {\n return await Promise.race([promise, abort]);\n } finally {\n signal.removeEventListener('abort', stop);\n }\n}\n\n/** Waits `ms`, or less: an abort ends the wait, clears its timer, and throws. */\nfunction wait(\n sleep: ((ms: number) => Promise<void>) | undefined,\n ms: number,\n signal: AbortSignal,\n): Promise<void> {\n if (sleep) return until(sleep(ms), signal);\n if (signal.aborted) return Promise.reject(aborted(signal));\n return new Promise<void>((resolve, reject) => {\n const stop = () => {\n clearTimeout(timer);\n reject(aborted(signal));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', stop);\n resolve();\n }, ms);\n signal.addEventListener('abort', stop, { once: true });\n });\n}\n\nfunction aborted(signal: AbortSignal): unknown {\n return (\n signal.reason ?? new DOMException('The call was aborted.', 'AbortError')\n );\n}\n\nfunction retryAfter(response: Response): number | undefined {\n const seconds = retryAfterSeconds(response);\n return seconds === undefined ? undefined : seconds * 1000;\n}\n\nfunction backoff(attempt: number, random: () => number): number {\n const base = 500 * 2 ** attempt;\n return Math.round(base / 2 + random() * (base / 2));\n}\n\nfunction check(\n name: string,\n value: number,\n valid: (n: number) => boolean,\n): number {\n if (typeof value !== 'number' || !valid(value)) {\n throw new TypeError(`${name} is not valid: ${String(value)}`);\n }\n return value;\n}\n","// The Vinaverse API from a Node backend: typed calls generated from the pinned public contract (vinaverse-v1.yaml,\n// through openapi-fetch), authenticated with a service key, with idempotency keys added where the contract wants\n// one, safe retries honouring `Retry-After` (./retry.ts), and refusals thrown as typed errors (./errors.ts).\n// A service key never belongs in a browser or an app: the client refuses to start there.\nimport createClient, { type Client } from 'openapi-fetch';\nimport type { operations, paths } from '../generated/vinaverse-v1.js';\nimport { apiError } from './errors.js';\nimport { randomUUID } from './random.js';\nimport { type FetchFn, type RetryOptions, retryingFetch } from './retry.js';\n\ntype Op = operations;\n/** An operation's JSON request body. */\nexport type ApiBody<K extends keyof Op> = Op[K] extends {\n requestBody?: { content: { 'application/json': infer B } };\n}\n ? B\n : never;\n/** An operation's success result. */\nexport type ApiResult<K extends keyof Op> = Success<Op[K]['responses']>;\ntype Success<R> = R extends {\n 200: { content: { 'application/json': infer B } };\n}\n ? B\n : R extends { 201: { content: { 'application/json': infer B } } }\n ? B\n : R extends { 202: { content: { 'application/json': infer B } } }\n ? B\n : undefined;\ntype QueryOf<K extends keyof Op> = Op[K]['parameters'] extends {\n query?: infer Q;\n}\n ? NonNullable<Q>\n : never;\n\n/** Per call: a signal that stops it at once, waits between tries included. */\nexport interface CallOptions {\n readonly signal?: AbortSignal;\n}\n\n/**\n * For the calls the contract makes idempotent: a key of your own, 1 to 255 characters (one is made otherwise).\n * After a `VinaverseTimeoutError` or a `VinaverseNetworkError`, try again later with the error's `idempotencyKey`,\n * so the call is done once however many times it is sent.\n */\nexport interface KeyedCallOptions extends CallOptions {\n readonly idempotencyKey?: string;\n}\n\nexport interface ApiClientOptions extends RetryOptions {\n /** A service key, `vv_sk_<mock|dev|live>_…`: from your secrets store, never from code. */\n readonly apiKey: string;\n /**\n * Default: `https://api.vinaverse.com` for a live key, `https://api-dev.vinaverse.com` for mock and dev keys. Any\n * other URL must be `https:` (a proxy you run, say), or `http:` on this machine only (`localhost`, `127.0.0.1`,\n * `[::1]`): a service key never travels in clear.\n */\n readonly baseUrl?: string;\n readonly fetch?: (request: Request) => Promise<Response>;\n /** Extra headers on every call, for example `Vinaverse-Mock-Scenario` in tests against the mock environment. */\n readonly headers?: Readonly<Record<string, string>>;\n}\n\nconst SERVICE_KEY = /^vv_sk_(mock|dev|live)_[A-Za-z0-9_-]{8,}$/;\n\n/** The client was made where a service key must never be: a browser or an app. */\nexport class ServiceKeyExposureError extends Error {\n override readonly name = 'ServiceKeyExposureError';\n}\n\nexport function createApiClient(options: ApiClientOptions) {\n refuseClientRuntime();\n const key = options.apiKey;\n if (typeof key !== 'string' || !SERVICE_KEY.test(key)) {\n throw new TypeError(\n key?.startsWith?.('vv_cs_')\n ? 'createApiClient takes a service key (vv_sk_…); a client secret (vv_cs_…) is for the app'\n : 'createApiClient needs a service key: vv_sk_<mock|dev|live>_…',\n );\n }\n const live = key.startsWith('vv_sk_live_');\n const baseUrl = safeBaseUrl(\n options.baseUrl ??\n (live ? 'https://api.vinaverse.com' : 'https://api-dev.vinaverse.com'),\n );\n const transport: FetchFn =\n options.fetch ?? ((request) => globalThis.fetch(request));\n const api: Client<paths> = createClient<paths>({\n baseUrl,\n redirect: 'error', // the API never redirects; a service key never follows one\n // Every request, from a helper or from `api` with a per-call baseUrl, goes to this origin only.\n fetch: retryingFetch(transport, options, sameOrigin(baseUrl)),\n headers: {\n ...options.headers,\n authorization: `Bearer ${key}`,\n accept: 'application/json',\n },\n });\n\n type Answer = Promise<{\n data?: unknown;\n error?: unknown;\n response: Response;\n }>;\n async function run<T>(call: Answer, idempotencyKey?: string): Promise<T> {\n const { data, error, response } = await call;\n if (!response.ok) throw apiError(response, error, idempotencyKey);\n return data as T;\n }\n /** A call the contract makes idempotent: under the caller's key, or a new one, on every try. */\n async function keyed<T>(\n o: KeyedCallOptions | undefined,\n call: (header: { 'Idempotency-Key': string }) => Answer,\n ): Promise<T> {\n const key = o?.idempotencyKey ?? (await newKey());\n if (typeof key !== 'string' || key.length < 1 || key.length > 255) {\n throw new TypeError('idempotencyKey must be 1 to 255 characters');\n }\n return run<T>(call({ 'Idempotency-Key': key }), key);\n }\n const init = (o?: CallOptions) => (o?.signal ? { signal: o.signal } : {});\n\n return {\n /** Every operation of the contract, typed, for what the helpers below do not cover (openapi-fetch). */\n api,\n sessions: {\n /** Mint a session for the person in your app; give the app its `id`, URLs and `client_secret` only. */\n create: (body: ApiBody<'createSession'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createSession'>>(o, (header) =>\n api.POST('/v1/sessions', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n get: (sessionId: string, o?: CallOptions) =>\n run<ApiResult<'getSession'>>(\n api.GET('/v1/sessions/{session_id}', {\n params: { path: { session_id: sessionId } },\n ...init(o),\n }),\n ),\n revoke: (sessionId: string, o?: CallOptions) =>\n run<ApiResult<'revokeSession'>>(\n api.POST('/v1/sessions/{session_id}/revoke', {\n params: { path: { session_id: sessionId } },\n ...init(o),\n }),\n ),\n /**\n * Where the person is now, for an open session (no new session per screen): a screen context, or\n * `{ clear: true, revision }`; `revision` greater than the session's, the same revision and body a retry.\n */\n updateContext: (\n sessionId: string,\n body: ApiBody<'updateSessionContext'>,\n o?: CallOptions,\n ) =>\n run<ApiResult<'updateSessionContext'>>(\n api.PUT('/v1/sessions/{session_id}/context', {\n params: { path: { session_id: sessionId } },\n body,\n ...init(o),\n }),\n ),\n /** A fresh client secret for an open session: what an app's `refreshSecret(sessionId)` asks your backend for. */\n refreshClientSecret: (sessionId: string, o?: CallOptions) =>\n run<ApiResult<'refreshClientSecret'>>(\n api.POST('/v1/sessions/{session_id}/client_secret', {\n params: { path: { session_id: sessionId } },\n ...init(o),\n }),\n ),\n },\n conversations: {\n get: (conversationId: string, o?: CallOptions) =>\n run<ApiResult<'getConversation'>>(\n api.GET('/v1/conversations/{conversation_id}', {\n params: { path: { conversation_id: conversationId } },\n ...init(o),\n }),\n ),\n /** A person's past conversations with an agent, newest activity first (history). */\n list: (query: QueryOf<'listConversations'>, o?: CallOptions) =>\n run<ApiResult<'listConversations'>>(\n api.GET('/v1/conversations', { params: { query }, ...init(o) }),\n ),\n /** A past conversation's messages, the newest page first and oldest first within a page. */\n listMessages: (\n conversationId: string,\n query: QueryOf<'listConversationMessages'>,\n o?: CallOptions,\n ) =>\n run<ApiResult<'listConversationMessages'>>(\n api.GET('/v1/conversations/{conversation_id}/messages', {\n params: { path: { conversation_id: conversationId }, query },\n ...init(o),\n }),\n ),\n /** Deletes a person's conversation (history's delete); another subject's or an unknown one is `not_found`. */\n delete: (\n conversationId: string,\n query: QueryOf<'deleteConversation'>,\n o?: CallOptions,\n ) =>\n run<ApiResult<'deleteConversation'>>(\n api.DELETE('/v1/conversations/{conversation_id}', {\n params: { path: { conversation_id: conversationId }, query },\n ...init(o),\n }),\n ),\n },\n suggestions: {\n create: (body: ApiBody<'createSuggestions'>, o?: CallOptions) =>\n run<ApiResult<'createSuggestions'>>(\n api.POST('/v1/suggestions', { body, ...init(o) }),\n ),\n },\n moderation: {\n createJob: (body: ApiBody<'createModerationJob'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createModerationJob'>>(o, (header) =>\n api.POST('/v1/moderation/jobs', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n getJob: (jobId: string, o?: CallOptions) =>\n run<ApiResult<'getModerationJob'>>(\n api.GET('/v1/moderation/jobs/{job_id}', {\n params: { path: { job_id: jobId } },\n ...init(o),\n }),\n ),\n getItem: (itemId: string, o?: CallOptions) =>\n run<ApiResult<'getModerationItem'>>(\n api.GET('/v1/moderation/items/{item_id}', {\n params: { path: { item_id: itemId } },\n ...init(o),\n }),\n ),\n },\n media: {\n createJob: (body: ApiBody<'createMediaJob'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createMediaJob'>>(o, (header) =>\n api.POST('/v1/media/jobs', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n listJobs: (query: QueryOf<'listMediaJobs'> = {}, o?: CallOptions) =>\n run<ApiResult<'listMediaJobs'>>(\n api.GET('/v1/media/jobs', { params: { query }, ...init(o) }),\n ),\n getJob: (jobId: string, o?: CallOptions) =>\n run<ApiResult<'getMediaJob'>>(\n api.GET('/v1/media/jobs/{job_id}', {\n params: { path: { job_id: jobId } },\n ...init(o),\n }),\n ),\n cancelJob: (jobId: string, o?: CallOptions) =>\n run<ApiResult<'cancelMediaJob'>>(\n api.POST('/v1/media/jobs/{job_id}/cancel', {\n params: { path: { job_id: jobId } },\n ...init(o),\n }),\n ),\n listProfiles: (o?: CallOptions) =>\n run<ApiResult<'listMediaProfiles'>>(\n api.GET('/v1/media/profiles', { ...init(o) }),\n ),\n },\n screening: {\n text: (body: ApiBody<'screenText'>, o?: CallOptions) =>\n run<ApiResult<'screenText'>>(\n api.POST('/v1/screening/text', { body, ...init(o) }),\n ),\n },\n documentChecks: {\n create: (body: ApiBody<'createDocumentCheck'>, o?: KeyedCallOptions) =>\n keyed<ApiResult<'createDocumentCheck'>>(o, (header) =>\n api.POST('/v1/document-checks', {\n body,\n params: { header },\n ...init(o),\n }),\n ),\n get: (checkId: string, o?: CallOptions) =>\n run<ApiResult<'getDocumentCheck'>>(\n api.GET('/v1/document-checks/{check_id}', {\n params: { path: { check_id: checkId } },\n ...init(o),\n }),\n ),\n },\n subjects: {\n erase: (subjectId: string, o?: KeyedCallOptions) =>\n keyed<ApiResult<'eraseSubject'>>(o, (header) =>\n api.POST('/v1/subjects/{subject_id}/erase', {\n params: { path: { subject_id: subjectId }, header },\n ...init(o),\n }),\n ),\n },\n feedback: {\n send: (body: ApiBody<'sendFeedback'>, o?: CallOptions) =>\n run<ApiResult<'sendFeedback'>>(\n api.POST('/v1/feedback', { body, ...init(o) }),\n ),\n },\n events: {\n send: (body: ApiBody<'sendEvents'>, o?: CallOptions) =>\n run<ApiResult<'sendEvents'>>(\n api.POST('/v1/events', { body, ...init(o) }),\n ),\n },\n knowledge: {\n sendDocument: (body: ApiBody<'sendKnowledgeDocument'>, o?: CallOptions) =>\n run<ApiResult<'sendKnowledgeDocument'>>(\n api.POST('/v1/knowledge/documents', { body, ...init(o) }),\n ),\n },\n catalog: {\n put: (\n type: Op['putCatalogEntity']['parameters']['path']['type'],\n id: string,\n body: ApiBody<'putCatalogEntity'>,\n o?: CallOptions,\n ) =>\n run<ApiResult<'putCatalogEntity'>>(\n api.PUT('/v1/catalog/{type}/{id}', {\n params: { path: { type, id } },\n body,\n ...init(o),\n }),\n ),\n },\n usage: {\n get: (query: QueryOf<'getUsage'> = {}, o?: CallOptions) =>\n run<ApiResult<'getUsage'>>(\n api.GET('/v1/usage', { params: { query }, ...init(o) }),\n ),\n },\n };\n}\n\nexport type ApiClient = ReturnType<typeof createApiClient>;\n\n/**\n * Throws in a browser (a `window` with a `document`) and in React Native: a service key there ships to everyone who\n * loads the app. Node, AWS Lambda, Deno, Bun and edge runtimes have neither.\n */\nfunction refuseClientRuntime(): void {\n const scope = globalThis as {\n window?: unknown;\n document?: unknown;\n navigator?: { product?: unknown };\n };\n if (scope.window !== undefined && scope.document !== undefined) {\n throw new ServiceKeyExposureError(\n 'The Vinaverse API client holds a service key and runs on your backend only, never in a browser. Give the app a session client secret (sessions.create).',\n );\n }\n if (scope.navigator?.product === 'ReactNative') {\n throw new ServiceKeyExposureError(\n 'The Vinaverse API client holds a service key and runs on your backend only, never in an app. Use @vinaverse/client with a session client secret.',\n );\n }\n}\n\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** The base URL, checked: `https:`, or `http:` on this machine only, so a service key never travels in clear. */\nfunction safeBaseUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new TypeError(`baseUrl is not a URL: ${value}`);\n }\n if (\n url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))\n ) {\n throw new TypeError(\n `baseUrl must be https: (or http: on localhost); a service key never travels in clear: ${url.origin}`,\n );\n }\n return value.replace(/\\/+$/, '');\n}\n\n/** A check for every request: the client's own origin, and so never in clear nor to another host. */\nfunction sameOrigin(baseUrl: string): (url: string) => void {\n const origin = new URL(baseUrl).origin;\n return (url) => {\n const target = new URL(url);\n if (target.origin !== origin) {\n throw new TypeError(\n `The Vinaverse API client sends its service key to ${origin} only, not to ${target.origin}`,\n );\n }\n };\n}\n\nfunction newKey(): Promise<string> {\n return randomUUID();\n}\n"]}
package/dist/api.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as operations, p as paths, c as components } from './vinaverse-v1.d-BVc4uyUd.cjs';
1
+ import { o as operations, p as paths, c as components } from './vinaverse-v1.d-DiulmRgx.cjs';
2
2
  import { Client } from 'openapi-fetch';
3
3
 
4
4
  interface RetryOptions {
@@ -102,6 +102,7 @@ declare function createApiClient(options: ApiClientOptions): {
102
102
  id: string;
103
103
  version: string;
104
104
  display_name: string;
105
+ avatar_url?: string;
105
106
  };
106
107
  client_secret: components["schemas"]["ClientSecret"];
107
108
  realtime_url: string;
@@ -109,6 +110,10 @@ declare function createApiClient(options: ApiClientOptions): {
109
110
  expires_at: string;
110
111
  disclosure: string;
111
112
  conversation_id?: components["schemas"]["ConversationId"];
113
+ experience_mode?: components["schemas"]["ExperienceMode"];
114
+ business_scope_id?: components["schemas"]["BusinessScopeId"];
115
+ screen_context?: components["schemas"]["ScreenContext"];
116
+ welcome?: components["schemas"]["Welcome"];
112
117
  }>;
113
118
  get: (sessionId: string, o?: CallOptions) => Promise<{
114
119
  id: string;
@@ -117,7 +122,7 @@ declare function createApiClient(options: ApiClientOptions): {
117
122
  agent_version?: string;
118
123
  turns: number;
119
124
  handoff_ticket_ids?: string[];
120
- end_reason?: "expired" | "revoked" | "limit_reached" | "idle" | "server_restart" | "user_left";
125
+ end_reason?: "expired" | "revoked" | "limit_reached" | "idle" | "server_restart" | "user_left" | "deleted";
121
126
  created_at: string;
122
127
  closed_at?: string;
123
128
  usage?: components["schemas"]["Usage"];
@@ -129,11 +134,19 @@ declare function createApiClient(options: ApiClientOptions): {
129
134
  agent_version?: string;
130
135
  turns: number;
131
136
  handoff_ticket_ids?: string[];
132
- end_reason?: "expired" | "revoked" | "limit_reached" | "idle" | "server_restart" | "user_left";
137
+ end_reason?: "expired" | "revoked" | "limit_reached" | "idle" | "server_restart" | "user_left" | "deleted";
133
138
  created_at: string;
134
139
  closed_at?: string;
135
140
  usage?: components["schemas"]["Usage"];
136
141
  }>;
142
+ /**
143
+ * Where the person is now, for an open session (no new session per screen): a screen context, or
144
+ * `{ clear: true, revision }`; `revision` greater than the session's, the same revision and body a retry.
145
+ */
146
+ updateContext: (sessionId: string, body: ApiBody<"updateSessionContext">, o?: CallOptions) => Promise<{
147
+ revision: number;
148
+ screen_context?: components["schemas"]["ScreenContext"];
149
+ }>;
137
150
  /** A fresh client secret for an open session: what an app's `refreshSecret(sessionId)` asks your backend for. */
138
151
  refreshClientSecret: (sessionId: string, o?: CallOptions) => Promise<{
139
152
  value: string;
@@ -162,6 +175,21 @@ declare function createApiClient(options: ApiClientOptions): {
162
175
  last_activity_at: string;
163
176
  session_id: string;
164
177
  }>;
178
+ /** A person's past conversations with an agent, newest activity first (history). */
179
+ list: (query: QueryOf<"listConversations">, o?: CallOptions) => Promise<{
180
+ data: components["schemas"]["ConversationSummary"][];
181
+ next_cursor: string | null;
182
+ }>;
183
+ /** A past conversation's messages, the newest page first and oldest first within a page. */
184
+ listMessages: (conversationId: string, query: QueryOf<"listConversationMessages">, o?: CallOptions) => Promise<{
185
+ data: components["schemas"]["TimelineItem"][];
186
+ next_cursor: string | null;
187
+ }>;
188
+ /** Deletes a person's conversation (history's delete); another subject's or an unknown one is `not_found`. */
189
+ delete: (conversationId: string, query: QueryOf<"deleteConversation">, o?: CallOptions) => Promise<{
190
+ conversation_id: components["schemas"]["ConversationId"];
191
+ sessions_revoked: number;
192
+ }>;
165
193
  };
166
194
  suggestions: {
167
195
  create: (body: ApiBody<"createSuggestions">, o?: CallOptions) => Promise<{