cvx-kit 0.1.21 → 0.1.22

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/errors.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { DeclaredError, DeclaredFailure, DecodedFailure, ErrorContract, ErrorDefinitions, ErrorDetailParser, UnknownFailure, defineErrorContract, queryErrors } from "./modules/contracts/errors.mjs";
2
- import { FailureHandlers, decodeFailure, matchFailure } from "./react/failures.mjs";
1
+ import { DeclaredError, DeclaredFailure, DecodedFailure, ErrorContract, ErrorDefinitions, ErrorDetailParser, UnknownFailure, combineErrorContracts, decodeFailure, defineErrorContract, queryErrors } from "./modules/contracts/errors.mjs";
2
+ import { FailureHandlers, failureOf, isFailure, matchFailure } from "./react/failures.mjs";
3
3
  //#region src/errors.d.ts
4
4
  /** Structured application error carried across Convex function boundaries. */
5
5
  export declare class KitError extends Error {
@@ -22,5 +22,5 @@ export type ErrorFactory = {
22
22
  };
23
23
  export declare const defaultErrors: ErrorFactory;
24
24
  //#endregion
25
- export { type DeclaredError, type DeclaredFailure, type DecodedFailure, type ErrorContract, type ErrorDefinitions, type ErrorDetailParser, type FailureHandlers, type UnknownFailure, decodeFailure, defineErrorContract, matchFailure, queryErrors };
25
+ export { type DeclaredError, type DeclaredFailure, type DecodedFailure, type ErrorContract, type ErrorDefinitions, type ErrorDetailParser, type FailureHandlers, type UnknownFailure, combineErrorContracts, decodeFailure, defineErrorContract, failureOf, isFailure, matchFailure, queryErrors };
26
26
  //# sourceMappingURL=errors.d.mts.map
package/dist/errors.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{defineErrorContract as e,queryErrors as t}from"./modules/contracts/errors.mjs";import{decodeFailure as n,matchFailure as r}from"./react/failures.mjs";var i=class extends Error{code;constructor(e){super(e.message??e.code),this.name=`KitError`,this.code=e.code}};const a={throw(e){throw new i(e)}};export{i as KitError,n as decodeFailure,a as defaultErrors,e as defineErrorContract,r as matchFailure,t as queryErrors};
1
+ import{combineErrorContracts as e,decodeFailure as t,defineErrorContract as n,queryErrors as r}from"./modules/contracts/errors.mjs";import{failureOf as i,isFailure as a,matchFailure as o}from"./react/failures.mjs";var s=class extends Error{code;constructor(e){super(e.message??e.code),this.name=`KitError`,this.code=e.code}};const c={throw(e){throw new s(e)}};export{s as KitError,e as combineErrorContracts,t as decodeFailure,c as defaultErrors,n as defineErrorContract,i as failureOf,a as isFailure,o as matchFailure,r as queryErrors};
2
2
  //# sourceMappingURL=errors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":["KitError","input","defaultErrors","decodeFailure","defineErrorContract","matchFailure","queryErrors"],"sources":["../src/errors.ts"],"sourcesContent":["/** Structured application error carried across Convex function boundaries. */\nexport class KitError extends Error {\n\treadonly code: string\n\n\tconstructor(input: { code: string; message?: string }) {\n\t\tsuper(input.message ?? input.code)\n\t\tthis.name = 'KitError'\n\t\tthis.code = input.code\n\t}\n}\n\nexport {\n\tdefineErrorContract,\n\tqueryErrors,\n\ttype ErrorContract,\n\ttype ErrorDefinitions,\n\ttype ErrorDetailParser,\n\ttype DeclaredError,\n\ttype DeclaredFailure,\n\ttype DecodedFailure,\n\ttype UnknownFailure,\n} from './modules/contracts/errors'\n\n/**\n * Injection seam for host error policy. Hosts with their own error taxonomy\n * (e.g. an App.errors singleton) adapt it to this shape; everyone else uses\n * the default factory below.\n */\nexport type ErrorFactory = {\n\tthrow(input: { code: string; message?: string }): never\n}\n\nexport const defaultErrors: ErrorFactory = {\n\tthrow(input) {\n\t\tthrow new KitError(input)\n\t},\n}\n\n// Pure helpers do not import React or server query-engine modules.\nexport { decodeFailure, matchFailure, type FailureHandlers } from './react/failures'\n"],"mappings":"6JACA,IAAaA,EAAb,cAA8B,KAAM,CACnC,KAEA,YAAY,EAA2C,CACtD,MAAMC,EAAM,SAAWA,EAAM,IAAI,EACjC,KAAK,KAAO,WACZ,KAAK,KAAOA,EAAM,IACnB,CACD,EAuBA,MAAaC,EAA8B,CAC1C,MAAM,EAAO,CACZ,MAAM,IAAIF,EAASC,CAAK,CACzB,CACD"}
1
+ {"version":3,"file":"errors.mjs","names":["KitError","input","defaultErrors","combineErrorContracts","decodeFailure","defineErrorContract","failureOf","isFailure","matchFailure","queryErrors"],"sources":["../src/errors.ts"],"sourcesContent":["/** Structured application error carried across Convex function boundaries. */\nexport class KitError extends Error {\n\treadonly code: string\n\n\tconstructor(input: { code: string; message?: string }) {\n\t\tsuper(input.message ?? input.code)\n\t\tthis.name = 'KitError'\n\t\tthis.code = input.code\n\t}\n}\n\nexport {\n\tdefineErrorContract,\n\tqueryErrors,\n\tcombineErrorContracts,\n\ttype ErrorContract,\n\ttype ErrorDefinitions,\n\ttype ErrorDetailParser,\n\ttype DeclaredError,\n\ttype DeclaredFailure,\n\ttype DecodedFailure,\n\ttype UnknownFailure,\n} from './modules/contracts/errors'\n\n/**\n * Injection seam for host error policy. Hosts with their own error taxonomy\n * (e.g. an App.errors singleton) adapt it to this shape; everyone else uses\n * the default factory below.\n */\nexport type ErrorFactory = {\n\tthrow(input: { code: string; message?: string }): never\n}\n\nexport const defaultErrors: ErrorFactory = {\n\tthrow(input) {\n\t\tthrow new KitError(input)\n\t},\n}\n\n// Pure helpers do not import React or server query-engine modules.\nexport {\n\tdecodeFailure,\n\tmatchFailure,\n\tfailureOf,\n\tisFailure,\n\ttype FailureHandlers,\n} from './react/failures'\n"],"mappings":"sNACA,IAAaA,EAAb,cAA8B,KAAM,CACnC,KAEA,YAAY,EAA2C,CACtD,MAAMC,EAAM,SAAWA,EAAM,IAAI,EACjC,KAAK,KAAO,WACZ,KAAK,KAAOA,EAAM,IACnB,CACD,EAwBA,MAAaC,EAA8B,CAC1C,MAAM,EAAO,CACZ,MAAM,IAAIF,EAASC,CAAK,CACzB,CACD"}
@@ -1,3 +1,4 @@
1
+ import { ConvexError } from "convex/values";
1
2
  //#region src/modules/contracts/errors.d.ts
2
3
  /** Explicit synchronous validators for the final public detail representation. */
3
4
  export type ErrorDetailParser<Output = unknown> = Readonly<{
@@ -33,12 +34,30 @@ export type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{
33
34
  create: <Key extends Code<Definitions>>(code: Key, details: Details<Definitions[NoInfer<Key>]>) => Extract<DeclaredError<Definitions>, {
34
35
  code: Key;
35
36
  }>;
37
+ envelope: <Key extends Code<Definitions>>(code: Key, details: Details<Definitions[NoInfer<Key>]>) => Extract<DeclaredFailure<Definitions>, {
38
+ code: Key;
39
+ }>;
40
+ toConvexError: <Key extends Code<Definitions>>(code: Key, details: Details<Definitions[NoInfer<Key>]>) => ConvexError<Extract<DeclaredFailure<Definitions>, {
41
+ code: Key;
42
+ }>>;
36
43
  project: (error: unknown) => DecodedFailure<Definitions>;
37
44
  /** Receives envelope data, e.g. ConvexError.data; never parses error messages. */
38
45
  decode: (payload: unknown) => DecodedFailure<Definitions>;
39
46
  }>;
40
47
  /** Closed safe codes, allowlisted details, and a versioned checked transport union. */
41
48
  export declare function defineErrorContract<const Definitions extends ErrorDefinitions>(definitions: Definitions): ErrorContract<Definitions>;
49
+ /** A structural decoder also accepts combined contracts without requiring constructors. */
50
+ export type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>;
51
+ export type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>;
52
+ type ProjectingContract = FailureContract & Pick<ErrorContract<ErrorDefinitions>, 'project'>;
53
+ /** Extract only ConvexError.data, including one bounded serialized JSON envelope. */
54
+ export declare function decodeFailure<Contract extends FailureContract>(error: unknown, contract: Contract): FailureOf<Contract>;
55
+ type CombinedErrorContract<Contracts extends readonly ProjectingContract[]> = Readonly<{
56
+ project: (error: unknown) => FailureOf<Contracts[number]> | UnknownFailure;
57
+ decode: (payload: unknown) => FailureOf<Contracts[number]> | UnknownFailure;
58
+ }>;
59
+ /** Ordered projection and decoding; duplicate codes retain the union of member details. */
60
+ export declare function combineErrorContracts<const Contracts extends readonly ProjectingContract[]>(...contracts: Contracts): CombinedErrorContract<Contracts>;
42
61
  /** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */
43
62
  export declare const queryErrors: Readonly<{
44
63
  create: <Key extends Code<{
@@ -179,6 +198,300 @@ export declare const queryErrors: Readonly<{
179
198
  }>, {
180
199
  code: Key;
181
200
  }>;
201
+ envelope: <Key extends Code<{
202
+ readonly 'invalid-cursor': {
203
+ readonly message: "Invalid cursor";
204
+ readonly details: {};
205
+ };
206
+ readonly FIELD_GROUP_DENIED: {
207
+ readonly message: "Field group access denied";
208
+ readonly details: {};
209
+ };
210
+ readonly QUERY_FANOUT: {
211
+ readonly message: "Query fan-out limit exceeded";
212
+ readonly details: {};
213
+ };
214
+ readonly SEARCH_TEXT_REQUIRED: {
215
+ readonly message: "Search text required";
216
+ readonly details: {};
217
+ };
218
+ readonly SEARCH_END_CURSOR_UNSUPPORTED: {
219
+ readonly message: "Search end cursor unsupported";
220
+ readonly details: {};
221
+ };
222
+ readonly SEARCH_ORDER_UNSUPPORTED: {
223
+ readonly message: "Search ordering unsupported";
224
+ readonly details: {};
225
+ };
226
+ readonly SEARCH_RELATION_UNSUPPORTED: {
227
+ readonly message: "Relation search unsupported";
228
+ readonly details: {};
229
+ };
230
+ readonly SEARCH_OPTIONS_UNSUPPORTED: {
231
+ readonly message: "Search options unsupported";
232
+ readonly details: {};
233
+ };
234
+ readonly SEARCH_PROTOCOL_UNSUPPORTED: {
235
+ readonly message: "Search pagination protocol unsupported";
236
+ readonly details: {};
237
+ };
238
+ }>>(code: Key, details: Details<{
239
+ readonly 'invalid-cursor': {
240
+ readonly message: "Invalid cursor";
241
+ readonly details: {};
242
+ };
243
+ readonly FIELD_GROUP_DENIED: {
244
+ readonly message: "Field group access denied";
245
+ readonly details: {};
246
+ };
247
+ readonly QUERY_FANOUT: {
248
+ readonly message: "Query fan-out limit exceeded";
249
+ readonly details: {};
250
+ };
251
+ readonly SEARCH_TEXT_REQUIRED: {
252
+ readonly message: "Search text required";
253
+ readonly details: {};
254
+ };
255
+ readonly SEARCH_END_CURSOR_UNSUPPORTED: {
256
+ readonly message: "Search end cursor unsupported";
257
+ readonly details: {};
258
+ };
259
+ readonly SEARCH_ORDER_UNSUPPORTED: {
260
+ readonly message: "Search ordering unsupported";
261
+ readonly details: {};
262
+ };
263
+ readonly SEARCH_RELATION_UNSUPPORTED: {
264
+ readonly message: "Relation search unsupported";
265
+ readonly details: {};
266
+ };
267
+ readonly SEARCH_OPTIONS_UNSUPPORTED: {
268
+ readonly message: "Search options unsupported";
269
+ readonly details: {};
270
+ };
271
+ readonly SEARCH_PROTOCOL_UNSUPPORTED: {
272
+ readonly message: "Search pagination protocol unsupported";
273
+ readonly details: {};
274
+ };
275
+ }[NoInfer<Key>]>) => Extract<Readonly<{
276
+ _tag: 'DeclaredFailure';
277
+ version: 1;
278
+ code: "FIELD_GROUP_DENIED";
279
+ message: string;
280
+ details: {};
281
+ }>, {
282
+ code: Key;
283
+ }> | Extract<Readonly<{
284
+ _tag: 'DeclaredFailure';
285
+ version: 1;
286
+ code: "QUERY_FANOUT";
287
+ message: string;
288
+ details: {};
289
+ }>, {
290
+ code: Key;
291
+ }> | Extract<Readonly<{
292
+ _tag: 'DeclaredFailure';
293
+ version: 1;
294
+ code: "SEARCH_END_CURSOR_UNSUPPORTED";
295
+ message: string;
296
+ details: {};
297
+ }>, {
298
+ code: Key;
299
+ }> | Extract<Readonly<{
300
+ _tag: 'DeclaredFailure';
301
+ version: 1;
302
+ code: "SEARCH_OPTIONS_UNSUPPORTED";
303
+ message: string;
304
+ details: {};
305
+ }>, {
306
+ code: Key;
307
+ }> | Extract<Readonly<{
308
+ _tag: 'DeclaredFailure';
309
+ version: 1;
310
+ code: "SEARCH_ORDER_UNSUPPORTED";
311
+ message: string;
312
+ details: {};
313
+ }>, {
314
+ code: Key;
315
+ }> | Extract<Readonly<{
316
+ _tag: 'DeclaredFailure';
317
+ version: 1;
318
+ code: "SEARCH_PROTOCOL_UNSUPPORTED";
319
+ message: string;
320
+ details: {};
321
+ }>, {
322
+ code: Key;
323
+ }> | Extract<Readonly<{
324
+ _tag: 'DeclaredFailure';
325
+ version: 1;
326
+ code: "SEARCH_RELATION_UNSUPPORTED";
327
+ message: string;
328
+ details: {};
329
+ }>, {
330
+ code: Key;
331
+ }> | Extract<Readonly<{
332
+ _tag: 'DeclaredFailure';
333
+ version: 1;
334
+ code: "SEARCH_TEXT_REQUIRED";
335
+ message: string;
336
+ details: {};
337
+ }>, {
338
+ code: Key;
339
+ }> | Extract<Readonly<{
340
+ _tag: 'DeclaredFailure';
341
+ version: 1;
342
+ code: "invalid-cursor";
343
+ message: string;
344
+ details: {};
345
+ }>, {
346
+ code: Key;
347
+ }>;
348
+ toConvexError: <Key extends Code<{
349
+ readonly 'invalid-cursor': {
350
+ readonly message: "Invalid cursor";
351
+ readonly details: {};
352
+ };
353
+ readonly FIELD_GROUP_DENIED: {
354
+ readonly message: "Field group access denied";
355
+ readonly details: {};
356
+ };
357
+ readonly QUERY_FANOUT: {
358
+ readonly message: "Query fan-out limit exceeded";
359
+ readonly details: {};
360
+ };
361
+ readonly SEARCH_TEXT_REQUIRED: {
362
+ readonly message: "Search text required";
363
+ readonly details: {};
364
+ };
365
+ readonly SEARCH_END_CURSOR_UNSUPPORTED: {
366
+ readonly message: "Search end cursor unsupported";
367
+ readonly details: {};
368
+ };
369
+ readonly SEARCH_ORDER_UNSUPPORTED: {
370
+ readonly message: "Search ordering unsupported";
371
+ readonly details: {};
372
+ };
373
+ readonly SEARCH_RELATION_UNSUPPORTED: {
374
+ readonly message: "Relation search unsupported";
375
+ readonly details: {};
376
+ };
377
+ readonly SEARCH_OPTIONS_UNSUPPORTED: {
378
+ readonly message: "Search options unsupported";
379
+ readonly details: {};
380
+ };
381
+ readonly SEARCH_PROTOCOL_UNSUPPORTED: {
382
+ readonly message: "Search pagination protocol unsupported";
383
+ readonly details: {};
384
+ };
385
+ }>>(code: Key, details: Details<{
386
+ readonly 'invalid-cursor': {
387
+ readonly message: "Invalid cursor";
388
+ readonly details: {};
389
+ };
390
+ readonly FIELD_GROUP_DENIED: {
391
+ readonly message: "Field group access denied";
392
+ readonly details: {};
393
+ };
394
+ readonly QUERY_FANOUT: {
395
+ readonly message: "Query fan-out limit exceeded";
396
+ readonly details: {};
397
+ };
398
+ readonly SEARCH_TEXT_REQUIRED: {
399
+ readonly message: "Search text required";
400
+ readonly details: {};
401
+ };
402
+ readonly SEARCH_END_CURSOR_UNSUPPORTED: {
403
+ readonly message: "Search end cursor unsupported";
404
+ readonly details: {};
405
+ };
406
+ readonly SEARCH_ORDER_UNSUPPORTED: {
407
+ readonly message: "Search ordering unsupported";
408
+ readonly details: {};
409
+ };
410
+ readonly SEARCH_RELATION_UNSUPPORTED: {
411
+ readonly message: "Relation search unsupported";
412
+ readonly details: {};
413
+ };
414
+ readonly SEARCH_OPTIONS_UNSUPPORTED: {
415
+ readonly message: "Search options unsupported";
416
+ readonly details: {};
417
+ };
418
+ readonly SEARCH_PROTOCOL_UNSUPPORTED: {
419
+ readonly message: "Search pagination protocol unsupported";
420
+ readonly details: {};
421
+ };
422
+ }[NoInfer<Key>]>) => ConvexError<Extract<Readonly<{
423
+ _tag: 'DeclaredFailure';
424
+ version: 1;
425
+ code: "FIELD_GROUP_DENIED";
426
+ message: string;
427
+ details: {};
428
+ }>, {
429
+ code: Key;
430
+ }> | Extract<Readonly<{
431
+ _tag: 'DeclaredFailure';
432
+ version: 1;
433
+ code: "QUERY_FANOUT";
434
+ message: string;
435
+ details: {};
436
+ }>, {
437
+ code: Key;
438
+ }> | Extract<Readonly<{
439
+ _tag: 'DeclaredFailure';
440
+ version: 1;
441
+ code: "SEARCH_END_CURSOR_UNSUPPORTED";
442
+ message: string;
443
+ details: {};
444
+ }>, {
445
+ code: Key;
446
+ }> | Extract<Readonly<{
447
+ _tag: 'DeclaredFailure';
448
+ version: 1;
449
+ code: "SEARCH_OPTIONS_UNSUPPORTED";
450
+ message: string;
451
+ details: {};
452
+ }>, {
453
+ code: Key;
454
+ }> | Extract<Readonly<{
455
+ _tag: 'DeclaredFailure';
456
+ version: 1;
457
+ code: "SEARCH_ORDER_UNSUPPORTED";
458
+ message: string;
459
+ details: {};
460
+ }>, {
461
+ code: Key;
462
+ }> | Extract<Readonly<{
463
+ _tag: 'DeclaredFailure';
464
+ version: 1;
465
+ code: "SEARCH_PROTOCOL_UNSUPPORTED";
466
+ message: string;
467
+ details: {};
468
+ }>, {
469
+ code: Key;
470
+ }> | Extract<Readonly<{
471
+ _tag: 'DeclaredFailure';
472
+ version: 1;
473
+ code: "SEARCH_RELATION_UNSUPPORTED";
474
+ message: string;
475
+ details: {};
476
+ }>, {
477
+ code: Key;
478
+ }> | Extract<Readonly<{
479
+ _tag: 'DeclaredFailure';
480
+ version: 1;
481
+ code: "SEARCH_TEXT_REQUIRED";
482
+ message: string;
483
+ details: {};
484
+ }>, {
485
+ code: Key;
486
+ }> | Extract<Readonly<{
487
+ _tag: 'DeclaredFailure';
488
+ version: 1;
489
+ code: "invalid-cursor";
490
+ message: string;
491
+ details: {};
492
+ }>, {
493
+ code: Key;
494
+ }>>;
182
495
  project: (error: unknown) => DecodedFailure<{
183
496
  readonly 'invalid-cursor': {
184
497
  readonly message: "Invalid cursor";
@@ -1,2 +1,2 @@
1
- const e=Object.freeze({_tag:`UnknownFailure`,version:1});function t(t){let n=Object.fromEntries(Object.entries(t).map(([e,t])=>{if(!e||!t.message||t.message.length>200)throw Error(`Declared errors require a code and a public message of 1–200 characters`);return[e,{message:t.message,details:{...t.details}}]})),o=/* @__PURE__ */ new WeakMap;return{create(e,t){let r;try{if(!Object.hasOwn(n,e))throw Error(`Undeclared code`);let i=n[e];r={_tag:`DeclaredFailure`,version:1,code:e,message:i.message,details:a(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let s=Object.freeze({_tag:`DeclaredError`,code:e,details:i(r.details)});return o.set(s,r),s},project(t){if(typeof t!=`object`||!t)return e;let n=o.get(t);return n?i(n):e},decode(t){try{if(!r(t)||t._tag!==`DeclaredFailure`||t.version!==1||typeof t.code!=`string`||!Object.hasOwn(n,t.code)||Object.keys(t).length!==5||![`message`,`details`,`_tag`,`version`,`code`].every(e=>Object.hasOwn(t,e)))return e;let o=n[t.code];return t.message===o.message?(i(t.details),{_tag:`DeclaredFailure`,version:1,code:t.code,message:o.message,details:a(o,t.details,!0)}):e}catch{return e}}}}const n=t({"invalid-cursor":{message:`Invalid cursor`,details:{}},FIELD_GROUP_DENIED:{message:`Field group access denied`,details:{}},QUERY_FANOUT:{message:`Query fan-out limit exceeded`,details:{}},SEARCH_TEXT_REQUIRED:{message:`Search text required`,details:{}},SEARCH_END_CURSOR_UNSUPPORTED:{message:`Search end cursor unsupported`,details:{}},SEARCH_ORDER_UNSUPPORTED:{message:`Search ordering unsupported`,details:{}},SEARCH_RELATION_UNSUPPORTED:{message:`Relation search unsupported`,details:{}},SEARCH_OPTIONS_UNSUPPORTED:{message:`Search options unsupported`,details:{}},SEARCH_PROTOCOL_UNSUPPORTED:{message:`Search pagination protocol unsupported`,details:{}}});function r(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function i(e,t=/* @__PURE__ */ new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||!e||t.has(e))throw Error(`Invalid JSON`);t.add(e);try{if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n.push(i(e[r],t));return n}if(!r(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,i(n,t)]))}finally{t.delete(e)}}function a(e,t,n){if(!r(t))throw Error(`Invalid details`);let a=Object.keys(e.details);if(n&&Object.keys(t).some(t=>!Object.hasOwn(e.details,t)))throw Error(`Undeclared detail`);return Object.fromEntries(a.map(n=>{if(!Object.hasOwn(t,n))throw Error(`Missing detail`);return[n,i(e.details[n].parse(t[n]))]}))}export{t as defineErrorContract,n as queryErrors};
1
+ import{ConvexError as e}from"convex/values";const t=Object.freeze({_tag:`UnknownFailure`,version:1});function n(n){let r=Object.fromEntries(Object.entries(n).map(([e,t])=>{if(!e||!t.message||t.message.length>200)throw Error(`Declared errors require a code and a public message of 1–200 characters`);return[e,{message:t.message,details:{...t.details}}]})),i=/* @__PURE__ */ new WeakMap,a={create(e,t){let n;try{if(!Object.hasOwn(r,e))throw Error(`Undeclared code`);let i=r[e];n={_tag:`DeclaredFailure`,version:1,code:e,message:i.message,details:c(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let a=Object.freeze({_tag:`DeclaredError`,code:e,details:s(n.details)});return i.set(a,n),a},envelope(e,t){return a.project(a.create(e,t))},toConvexError(t,n){return new e(a.envelope(t,n))},project(e){if(typeof e!=`object`||!e)return t;let n=i.get(e);return n?s(n):t},decode(e){try{if(!o(e)||e._tag!==`DeclaredFailure`||e.version!==1||typeof e.code!=`string`||!Object.hasOwn(r,e.code)||Object.keys(e).length!==5||![`message`,`details`,`_tag`,`version`,`code`].every(t=>Object.hasOwn(e,t)))return t;let n=r[e.code];return e.message===n.message?(s(e.details),{_tag:`DeclaredFailure`,version:1,code:e.code,message:n.message,details:c(n,e.details,!0)}):t}catch{return t}}};return a}function r(n,r){try{if(n instanceof e){let e=n.data;if(typeof e==`string`){if(e.length>65536||new TextEncoder().encode(e).byteLength>65536)return t;e=JSON.parse(e)}return r.decode(e)}}catch{}return t}function i(...e){let n=t;return{project(t){for(let n of e){let e=n.project(t);if(e._tag===`DeclaredFailure`)return e;let i=r(t,n);if(i._tag===`DeclaredFailure`)return i}return n},decode(t){for(let n of e){let e=n.decode(t);if(e._tag===`DeclaredFailure`)return e}return n}}}const a=n({"invalid-cursor":{message:`Invalid cursor`,details:{}},FIELD_GROUP_DENIED:{message:`Field group access denied`,details:{}},QUERY_FANOUT:{message:`Query fan-out limit exceeded`,details:{}},SEARCH_TEXT_REQUIRED:{message:`Search text required`,details:{}},SEARCH_END_CURSOR_UNSUPPORTED:{message:`Search end cursor unsupported`,details:{}},SEARCH_ORDER_UNSUPPORTED:{message:`Search ordering unsupported`,details:{}},SEARCH_RELATION_UNSUPPORTED:{message:`Relation search unsupported`,details:{}},SEARCH_OPTIONS_UNSUPPORTED:{message:`Search options unsupported`,details:{}},SEARCH_PROTOCOL_UNSUPPORTED:{message:`Search pagination protocol unsupported`,details:{}}});function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function s(e,t=/* @__PURE__ */ new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||!e||t.has(e))throw Error(`Invalid JSON`);t.add(e);try{if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n.push(s(e[r],t));return n}if(!o(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,s(n,t)]))}finally{t.delete(e)}}function c(e,t,n){if(!o(t))throw Error(`Invalid details`);let r=Object.keys(e.details);if(n&&Object.keys(t).some(t=>!Object.hasOwn(e.details,t)))throw Error(`Undeclared detail`);return Object.fromEntries(r.map(n=>{if(!Object.hasOwn(t,n))throw Error(`Missing detail`);return[n,s(e.details[n].parse(t[n]))]}))}export{i as combineErrorContracts,r as decodeFailure,n as defineErrorContract,a as queryErrors};
2
2
  //# sourceMappingURL=errors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":["unknownFailure","defineErrorContract","declarations","definitions","code","definition","trusted","envelope","parseDetails","details","error","copyJson","isRecord","payload","key","queryErrors","value","prototype","ancestors","result","index","child","fields","strict","field"],"sources":["../../../src/modules/contracts/errors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- This neutral contract validates unknown transport data and an explicitly keyed code/detail declaration. */\n\n/** Explicit synchronous validators for the final public detail representation. */\nexport type ErrorDetailParser<Output = unknown> = Readonly<{\n\tparse: (value: unknown) => Output\n}>\n\nexport type ErrorDefinitions = Readonly<\n\tRecord<\n\t\tstring,\n\t\tReadonly<{\n\t\t\tmessage: string\n\t\t\tdetails: Readonly<Record<string, ErrorDetailParser>>\n\t\t}>\n\t>\n>\n\ntype Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>\ntype Details<Definition extends ErrorDefinitions[string]> =\n\tDefinition extends ErrorDefinitions[string]\n\t\t? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']> }\n\t\t: never\n\ndeclare const declaredErrorBrand: unique symbol\n\n/** Server failures are trusted only by the contract that created them. */\nexport type DeclaredError<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredError'\n\t\tcode: Key\n\t\tdetails: Details<Definitions[Key]>\n\t\t[declaredErrorBrand]: true\n\t}>\n}[Code<Definitions>]\n\nexport type DeclaredFailure<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredFailure'\n\t\tversion: 1\n\t\tcode: Key\n\t\tmessage: string\n\t\tdetails: Details<Definitions[Key]>\n\t}>\n}[Code<Definitions>]\n\nexport type UnknownFailure = Readonly<{ _tag: 'UnknownFailure'; version: 1 }>\nexport type DecodedFailure<Definitions extends ErrorDefinitions> =\n\tDeclaredFailure<Definitions> | UnknownFailure\n\nexport type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{\n\tcreate: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredError<Definitions>, { code: Key }>\n\tproject: (error: unknown) => DecodedFailure<Definitions>\n\t/** Receives envelope data, e.g. ConvexError.data; never parses error messages. */\n\tdecode: (payload: unknown) => DecodedFailure<Definitions>\n}>\n\nconst unknownFailure: UnknownFailure = Object.freeze({\n\t_tag: 'UnknownFailure',\n\tversion: 1,\n})\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n/** Closed safe codes, allowlisted details, and a versioned checked transport union. */\nexport function defineErrorContract<const Definitions extends ErrorDefinitions>(\n\tdefinitions: Definitions,\n): ErrorContract<Definitions> {\n\t// SAFETY: the snapshot copies every declaration without changing its code, message or paired parsers.\n\tconst declarations = Object.fromEntries(\n\t\tObject.entries(definitions).map(([code, definition]) => {\n\t\t\tif (!code || !definition.message || definition.message.length > 200) {\n\t\t\t\tthrow Error('Declared errors require a code and a public message of 1–200 characters')\n\t\t\t}\n\t\t\treturn [code, { message: definition.message, details: { ...definition.details } }]\n\t\t}),\n\t) as Definitions\n\tconst trusted = new WeakMap<object, DeclaredFailure<Definitions>>()\n\treturn {\n\t\tcreate(code, details) {\n\t\t\tlet envelope: DeclaredFailure<Definitions>\n\t\t\ttry {\n\t\t\t\tif (!Object.hasOwn(declarations, code)) throw Error('Undeclared code')\n\t\t\t\tconst definition = declarations[code]\n\t\t\t\t// SAFETY: the selected closed declaration validates every field before construction.\n\t\t\t\tenvelope = {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, details, false),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\t// Validator messages, issue paths and provider causes remain private.\n\t\t\t\tthrow Error('Invalid declared error details')\n\t\t\t}\n\t\t\t// SAFETY: identity is registered below; the inaccessible brand cannot confer trust by itself.\n\t\t\tconst error = Object.freeze({\n\t\t\t\t_tag: 'DeclaredError',\n\t\t\t\tcode,\n\t\t\t\tdetails: copyJson(envelope.details),\n\t\t\t}) as Extract<DeclaredError<Definitions>, { code: typeof code }>\n\t\t\ttrusted.set(error, envelope)\n\t\t\treturn error\n\t\t},\n\t\tproject(error) {\n\t\t\tif (error === null || typeof error !== 'object') return unknownFailure\n\t\t\tconst envelope = trusted.get(error)\n\t\t\t// SAFETY: only validated contract-owned envelopes enter the private map.\n\t\t\treturn envelope ? (copyJson(envelope) as DeclaredFailure<Definitions>) : unknownFailure\n\t\t},\n\t\tdecode(payload) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(payload) ||\n\t\t\t\t\tpayload._tag !== 'DeclaredFailure' ||\n\t\t\t\t\tpayload.version !== 1 ||\n\t\t\t\t\ttypeof payload.code !== 'string' ||\n\t\t\t\t\t!Object.hasOwn(declarations, payload.code) ||\n\t\t\t\t\tObject.keys(payload).length !== 5 ||\n\t\t\t\t\t!['message', 'details', '_tag', 'version', 'code'].every((key) =>\n\t\t\t\t\t\tObject.hasOwn(payload, key),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn unknownFailure\n\t\t\t\t}\n\t\t\t\tconst definition = declarations[payload.code]\n\t\t\t\tif (payload.message !== definition.message) return unknownFailure\n\t\t\t\t// Validate raw transport JSON too: parsers must not hide non-JSON payloads.\n\t\t\t\tcopyJson(payload.details)\n\t\t\t\t// SAFETY: code membership and every allowlisted field have been checked independently.\n\t\t\t\treturn {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode: payload.code,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, payload.details, true),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\treturn unknownFailure\n\t\t\t}\n\t\t},\n\t}\n}\n\n/** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */\nexport const queryErrors = defineErrorContract({\n\t'invalid-cursor': { message: 'Invalid cursor', details: {} },\n\tFIELD_GROUP_DENIED: { message: 'Field group access denied', details: {} },\n\tQUERY_FANOUT: { message: 'Query fan-out limit exceeded', details: {} },\n\tSEARCH_TEXT_REQUIRED: { message: 'Search text required', details: {} },\n\tSEARCH_END_CURSOR_UNSUPPORTED: {\n\t\tmessage: 'Search end cursor unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_ORDER_UNSUPPORTED: {\n\t\tmessage: 'Search ordering unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_RELATION_UNSUPPORTED: {\n\t\tmessage: 'Relation search unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_OPTIONS_UNSUPPORTED: {\n\t\tmessage: 'Search options unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_PROTOCOL_UNSUPPORTED: {\n\t\tmessage: 'Search pagination protocol unsupported',\n\t\tdetails: {},\n\t},\n})\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n\n/** Copy data without invoking toJSON or retaining mutable provider objects. */\nfunction copyJson(value: unknown, ancestors = new Set<object>()): Json {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\tif (typeof value !== 'object' || value === null || ancestors.has(value))\n\t\tthrow Error('Invalid JSON')\n\tancestors.add(value)\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst result: Json[] = []\n\t\t\tfor (let index = 0; index < value.length; index++)\n\t\t\t\tresult.push(copyJson(value[index], ancestors))\n\t\t\treturn result\n\t\t}\n\t\tif (!isRecord(value)) throw Error('Invalid JSON')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, child]) => [key, copyJson(child, ancestors)]),\n\t\t)\n\t} finally {\n\t\tancestors.delete(value)\n\t}\n}\n\nfunction parseDetails<const Definition extends ErrorDefinitions[string]>(\n\tdefinition: Definition,\n\tvalue: unknown,\n\tstrict: boolean,\n): Details<Definition> {\n\tif (!isRecord(value)) throw Error('Invalid details')\n\tconst fields = Object.keys(definition.details)\n\tif (strict && Object.keys(value).some((key) => !Object.hasOwn(definition.details, key))) {\n\t\tthrow Error('Undeclared detail')\n\t}\n\t// SAFETY: each declared field is validated by its paired parser before its JSON-safe copy is returned.\n\treturn Object.fromEntries(\n\t\tfields.map((field) => {\n\t\t\tif (!Object.hasOwn(value, field)) throw Error('Missing detail')\n\t\t\treturn [field, copyJson(definition.details[field].parse(value[field]))]\n\t\t}),\n\t) as Details<Definition>\n}\n"],"mappings":"AA2DA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,QACpB,MAAO,CACN,OAAO,EAAM,EAAS,CACrB,IAAIC,EACJ,GAAI,CACH,GAAI,CAAC,OAAO,OAAOL,EAAcE,CAAI,EAAG,MAAM,MAAM,iBAAiB,EACrE,IAAMC,EAAaH,EAAaE,GAEhC,EAAW,CACV,KAAM,kBACN,QAAS,EACT,OACA,QAASC,EAAW,QACpB,QAASG,EAAaH,EAAYI,EAAS,EAAK,CACjD,CACD,MAAQ,CAEP,MAAM,MAAM,gCAAgC,CAC7C,CAEA,IAAMC,EAAQ,OAAO,OAAO,CAC3B,KAAM,gBACN,OACA,QAASC,EAASJ,EAAS,OAAO,CACnC,CAAC,EAED,OADAD,EAAQ,IAAII,EAAOH,CAAQ,EACpBG,CACR,EACA,QAAQ,EAAO,CACd,GAAsB,OAAOA,GAAU,WAAnCA,EAA6C,OAAOV,EACxD,IAAMO,EAAWD,EAAQ,IAAII,CAAK,EAElC,OAAOH,EAAYI,EAASJ,CAAQ,EAAqCP,CAC1E,EACA,OAAO,EAAS,CACf,GAAI,CAC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"version":3,"file":"errors.mjs","names":["unknownFailure","defineErrorContract","declarations","definitions","code","definition","trusted","contract","envelope","parseDetails","details","error","copyJson","ConvexError","isRecord","payload","key","decodeFailure","combineErrorContracts","contracts","unmatched","projected","decoded","queryErrors","value","prototype","ancestors","result","index","child","fields","strict","field"],"sources":["../../../src/modules/contracts/errors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- This neutral contract validates unknown transport data and an explicitly keyed code/detail declaration. */\n\nimport { ConvexError } from 'convex/values'\n\n/** Explicit synchronous validators for the final public detail representation. */\nexport type ErrorDetailParser<Output = unknown> = Readonly<{\n\tparse: (value: unknown) => Output\n}>\n\nexport type ErrorDefinitions = Readonly<\n\tRecord<\n\t\tstring,\n\t\tReadonly<{\n\t\t\tmessage: string\n\t\t\tdetails: Readonly<Record<string, ErrorDetailParser>>\n\t\t}>\n\t>\n>\n\ntype Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>\ntype Details<Definition extends ErrorDefinitions[string]> =\n\tDefinition extends ErrorDefinitions[string]\n\t\t? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']> }\n\t\t: never\n\ndeclare const declaredErrorBrand: unique symbol\n\n/** Server failures are trusted only by the contract that created them. */\nexport type DeclaredError<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredError'\n\t\tcode: Key\n\t\tdetails: Details<Definitions[Key]>\n\t\t[declaredErrorBrand]: true\n\t}>\n}[Code<Definitions>]\n\nexport type DeclaredFailure<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredFailure'\n\t\tversion: 1\n\t\tcode: Key\n\t\tmessage: string\n\t\tdetails: Details<Definitions[Key]>\n\t}>\n}[Code<Definitions>]\n\nexport type UnknownFailure = Readonly<{ _tag: 'UnknownFailure'; version: 1 }>\nexport type DecodedFailure<Definitions extends ErrorDefinitions> =\n\t| DeclaredFailure<Definitions>\n\t| UnknownFailure\n\nexport type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{\n\tcreate: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredError<Definitions>, { code: Key }>\n\tenvelope: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredFailure<Definitions>, { code: Key }>\n\ttoConvexError: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => ConvexError<Extract<DeclaredFailure<Definitions>, { code: Key }>>\n\tproject: (error: unknown) => DecodedFailure<Definitions>\n\t/** Receives envelope data, e.g. ConvexError.data; never parses error messages. */\n\tdecode: (payload: unknown) => DecodedFailure<Definitions>\n}>\n\nconst unknownFailure: UnknownFailure = Object.freeze({\n\t_tag: 'UnknownFailure',\n\tversion: 1,\n})\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n/** Closed safe codes, allowlisted details, and a versioned checked transport union. */\nexport function defineErrorContract<const Definitions extends ErrorDefinitions>(\n\tdefinitions: Definitions,\n): ErrorContract<Definitions> {\n\t// SAFETY: the snapshot copies every declaration without changing its code, message or paired parsers.\n\tconst declarations = Object.fromEntries(\n\t\tObject.entries(definitions).map(([code, definition]) => {\n\t\t\tif (!code || !definition.message || definition.message.length > 200) {\n\t\t\t\tthrow Error('Declared errors require a code and a public message of 1–200 characters')\n\t\t\t}\n\t\t\treturn [code, { message: definition.message, details: { ...definition.details } }]\n\t\t}),\n\t) as Definitions\n\tconst trusted = new WeakMap<object, DeclaredFailure<Definitions>>()\n\tconst contract: ErrorContract<Definitions> = {\n\t\tcreate(code, details) {\n\t\t\tlet envelope: DeclaredFailure<Definitions>\n\t\t\ttry {\n\t\t\t\tif (!Object.hasOwn(declarations, code)) throw Error('Undeclared code')\n\t\t\t\tconst definition = declarations[code]\n\t\t\t\t// SAFETY: the selected closed declaration validates every field before construction.\n\t\t\t\tenvelope = {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, details, false),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\t// Validator messages, issue paths and provider causes remain private.\n\t\t\t\tthrow Error('Invalid declared error details')\n\t\t\t}\n\t\t\t// SAFETY: identity is registered below; the inaccessible brand cannot confer trust by itself.\n\t\t\tconst error = Object.freeze({\n\t\t\t\t_tag: 'DeclaredError',\n\t\t\t\tcode,\n\t\t\t\tdetails: copyJson(envelope.details),\n\t\t\t}) as Extract<DeclaredError<Definitions>, { code: typeof code }>\n\t\t\ttrusted.set(error, envelope)\n\t\t\treturn error\n\t\t},\n\t\tenvelope(code, details) {\n\t\t\t// SAFETY: create validates the selected code; project retrieves its private validated envelope.\n\t\t\treturn contract.project(contract.create(code, details)) as Extract<\n\t\t\t\tDeclaredFailure<Definitions>,\n\t\t\t\t{ code: typeof code }\n\t\t\t>\n\t\t},\n\t\ttoConvexError(code, details) {\n\t\t\treturn new ConvexError(contract.envelope(code, details))\n\t\t},\n\t\tproject(error) {\n\t\t\tif (error === null || typeof error !== 'object') return unknownFailure\n\t\t\tconst envelope = trusted.get(error)\n\t\t\t// SAFETY: only validated contract-owned envelopes enter the private map.\n\t\t\treturn envelope ? (copyJson(envelope) as DeclaredFailure<Definitions>) : unknownFailure\n\t\t},\n\t\tdecode(payload) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(payload) ||\n\t\t\t\t\tpayload._tag !== 'DeclaredFailure' ||\n\t\t\t\t\tpayload.version !== 1 ||\n\t\t\t\t\ttypeof payload.code !== 'string' ||\n\t\t\t\t\t!Object.hasOwn(declarations, payload.code) ||\n\t\t\t\t\tObject.keys(payload).length !== 5 ||\n\t\t\t\t\t!['message', 'details', '_tag', 'version', 'code'].every((key) =>\n\t\t\t\t\t\tObject.hasOwn(payload, key),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn unknownFailure\n\t\t\t\t}\n\t\t\t\tconst definition = declarations[payload.code]\n\t\t\t\tif (payload.message !== definition.message) return unknownFailure\n\t\t\t\t// Validate raw transport JSON too: parsers must not hide non-JSON payloads.\n\t\t\t\tcopyJson(payload.details)\n\t\t\t\t// SAFETY: code membership and every allowlisted field have been checked independently.\n\t\t\t\treturn {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode: payload.code,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, payload.details, true),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\treturn unknownFailure\n\t\t\t}\n\t\t},\n\t}\n\treturn contract\n}\n\n/** A structural decoder also accepts combined contracts without requiring constructors. */\nexport type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>\nexport type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>\ntype ProjectingContract = FailureContract & Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\n/** Extract only ConvexError.data, including one bounded serialized JSON envelope. */\nexport function decodeFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n): FailureOf<Contract> {\n\ttry {\n\t\tif (error instanceof ConvexError) {\n\t\t\tlet payload: unknown = error.data\n\t\t\tif (typeof payload === 'string') {\n\t\t\t\tif (payload.length > 65536 || new TextEncoder().encode(payload).byteLength > 65536)\n\t\t\t\t\t// SAFETY: every failure decoder includes UnknownFailure.\n\t\t\t\t\treturn unknownFailure as FailureOf<Contract>\n\t\t\t\tpayload = JSON.parse(payload)\n\t\t\t}\n\t\t\t// SAFETY: the structural contract owns the decoded union.\n\t\t\treturn contract.decode(payload) as FailureOf<Contract>\n\t\t}\n\t} catch {\n\t\t// Foreign errors, accessors and invalid JSON expose no diagnostics.\n\t}\n\t// SAFETY: every failure decoder includes UnknownFailure.\n\treturn unknownFailure as FailureOf<Contract>\n}\n\ntype CombinedErrorContract<Contracts extends readonly ProjectingContract[]> = Readonly<{\n\tproject: (error: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n\tdecode: (payload: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n}>\n\n/** Ordered projection and decoding; duplicate codes retain the union of member details. */\nexport function combineErrorContracts<const Contracts extends readonly ProjectingContract[]>(\n\t...contracts: Contracts\n): CombinedErrorContract<Contracts> {\n\tconst unmatched = unknownFailure\n\treturn {\n\t\tproject(error) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst projected = contract.project(error)\n\t\t\t\tif (projected._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn projected as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t\tconst decoded = decodeFailure(error, contract)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: strict transported decoding preserves the same member union.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t\tdecode(payload) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst decoded = contract.decode(payload)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t}\n}\n\n/** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */\nexport const queryErrors = defineErrorContract({\n\t'invalid-cursor': { message: 'Invalid cursor', details: {} },\n\tFIELD_GROUP_DENIED: { message: 'Field group access denied', details: {} },\n\tQUERY_FANOUT: { message: 'Query fan-out limit exceeded', details: {} },\n\tSEARCH_TEXT_REQUIRED: { message: 'Search text required', details: {} },\n\tSEARCH_END_CURSOR_UNSUPPORTED: {\n\t\tmessage: 'Search end cursor unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_ORDER_UNSUPPORTED: {\n\t\tmessage: 'Search ordering unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_RELATION_UNSUPPORTED: {\n\t\tmessage: 'Relation search unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_OPTIONS_UNSUPPORTED: {\n\t\tmessage: 'Search options unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_PROTOCOL_UNSUPPORTED: {\n\t\tmessage: 'Search pagination protocol unsupported',\n\t\tdetails: {},\n\t},\n})\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n\n/** Copy data without invoking toJSON or retaining mutable provider objects. */\nfunction copyJson(value: unknown, ancestors = new Set<object>()): Json {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\tif (typeof value !== 'object' || value === null || ancestors.has(value))\n\t\tthrow Error('Invalid JSON')\n\tancestors.add(value)\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst result: Json[] = []\n\t\t\tfor (let index = 0; index < value.length; index++)\n\t\t\t\tresult.push(copyJson(value[index], ancestors))\n\t\t\treturn result\n\t\t}\n\t\tif (!isRecord(value)) throw Error('Invalid JSON')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, child]) => [key, copyJson(child, ancestors)]),\n\t\t)\n\t} finally {\n\t\tancestors.delete(value)\n\t}\n}\n\nfunction parseDetails<const Definition extends ErrorDefinitions[string]>(\n\tdefinition: Definition,\n\tvalue: unknown,\n\tstrict: boolean,\n): Details<Definition> {\n\tif (!isRecord(value)) throw Error('Invalid details')\n\tconst fields = Object.keys(definition.details)\n\tif (strict && Object.keys(value).some((key) => !Object.hasOwn(definition.details, key))) {\n\t\tthrow Error('Undeclared detail')\n\t}\n\t// SAFETY: each declared field is validated by its paired parser before its JSON-safe copy is returned.\n\treturn Object.fromEntries(\n\t\tfields.map((field) => {\n\t\t\tif (!Object.hasOwn(value, field)) throw Error('Missing detail')\n\t\t\treturn [field, copyJson(definition.details[field].parse(value[field]))]\n\t\t}),\n\t) as Details<Definition>\n}\n"],"mappings":"4CAsEA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,QACdC,EAAuC,CAC5C,OAAO,EAAM,EAAS,CACrB,IAAIC,EACJ,GAAI,CACH,GAAI,CAAC,OAAO,OAAON,EAAcE,CAAI,EAAG,MAAM,MAAM,iBAAiB,EACrE,IAAMC,EAAaH,EAAaE,GAEhC,EAAW,CACV,KAAM,kBACN,QAAS,EACT,OACA,QAASC,EAAW,QACpB,QAASI,EAAaJ,EAAYK,EAAS,EAAK,CACjD,CACD,MAAQ,CAEP,MAAM,MAAM,gCAAgC,CAC7C,CAEA,IAAMC,EAAQ,OAAO,OAAO,CAC3B,KAAM,gBACN,OACA,QAASC,EAASJ,EAAS,OAAO,CACnC,CAAC,EAED,OADAF,EAAQ,IAAIK,EAAOH,CAAQ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utor, OperationPublicResult, OperationTool, OperationToolC
2
2
  import { ContractDecoderError, ContractDecoderRequirements, ContractValidationError, EffectDecoder, decodeEffectContract, effectContract, effectSchema, effectStandardSchema } from "./schema.mjs";
3
3
  import { CallbackError, CallbackRequirements, EffectMiddlewareInput, EffectOperationArgument, EffectOperationError, EffectOperationHandlerResult, EffectOperationInput, EffectOperationRequirements, EffectOperationResult, EffectPreparation, EffectValue, effectOperationFactory } from "./operation.mjs";
4
4
  import { EffectZodApiBuilder, effectZodApiBuilder } from "./api-zod.mjs";
5
+ import "./agent-tools.mjs";
5
6
  import { EffectFoundationOptions, createEffectFoundation } from "./foundation.mjs";
6
7
  import { EffectIdempotencyPreparation, effectTransactionalIdempotency } from "./idempotency.mjs";
7
8
  import { EffectCrudConfig, EffectCrudContext, EffectCrudPage, EffectCrudPagination, EffectCrudRepository, EffectCrudTable, createEffectCrud } from "./crud.mjs";
@@ -1,12 +1,14 @@
1
- import { ErrorContract, ErrorDefinitions, UnknownFailure } from "../modules/contracts/errors.mjs";
1
+ import { FailureContract, FailureOf, UnknownFailure, decodeFailure } from "../modules/contracts/errors.mjs";
2
2
  //#region src/react/failures.d.ts
3
- export type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>;
4
- export type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>;
5
3
  type DeclaredOf<Contract extends FailureContract> = Extract<FailureOf<Contract>, {
6
4
  _tag: 'DeclaredFailure';
7
5
  }>;
8
- /** Extract ConvexError.data only. Contract validation owns the public envelope. */
9
- export declare function decodeFailure<Contract extends FailureContract>(error: unknown, contract: Contract): FailureOf<Contract>;
6
+ /** Return a selected validated failure; never mutate or narrow the caught error itself. */
7
+ export declare function failureOf<Contract extends FailureContract, const Codes extends readonly DeclaredOf<Contract>['code'][]>(error: unknown, contract: Contract, ...codes: Codes): Extract<DeclaredOf<Contract>, {
8
+ code: Codes[number];
9
+ }> | undefined;
10
+ /** Boolean convenience predicate; use failureOf to access narrowed details. */
11
+ export declare function isFailure<Contract extends FailureContract, const Codes extends readonly DeclaredOf<Contract>['code'][]>(error: unknown, contract: Contract, ...codes: Codes): boolean;
10
12
  type DeclaredHandlers<Contract extends FailureContract> = { [Code in DeclaredOf<Contract>['code']]: (failure: Code extends '_' ? FailureOf<Contract> : Extract<DeclaredOf<Contract>, {
11
13
  code: Code;
12
14
  }>) => unknown; };
@@ -20,4 +22,5 @@ export declare function matchFailure<Contract extends FailureContract, const Han
20
22
  } & Handlers & Record<Exclude<keyof Handlers, keyof DeclaredHandlers<Contract> | '_'>, never>): HandlerResult<Handlers>;
21
23
  export declare function matchFailure<Contract extends FailureContract, const Handlers extends object>(error: unknown, contract: Contract, handlers: DeclaredHandlers<NoInfer<Contract>> & Handlers & Record<Exclude<keyof Handlers, keyof DeclaredHandlers<Contract>>, never>): HandlerResult<Handlers> | UnknownFailure;
22
24
  //#endregion
25
+ export { type FailureContract, type FailureOf, decodeFailure };
23
26
  //# sourceMappingURL=failures.d.mts.map
@@ -1,2 +1,2 @@
1
- import{ConvexError as e}from"convex/values";function t(t,n){let r={_tag:`UnknownFailure`,version:1};try{t instanceof e&&(r=n.decode(t.data))}catch{}return r}function n(e,n,r){let i=t(e,n),a=r,o=i._tag===`DeclaredFailure`&&Object.hasOwn(r,i.code)?a[i.code]:void 0;return o?o(i):Object.hasOwn(r,`_`)&&a._?a._(i):i}export{t as decodeFailure,n as matchFailure};
1
+ import{decodeFailure as e}from"../modules/contracts/errors.mjs";function t(t,n,...r){let i=e(t,n);if(i._tag===`DeclaredFailure`&&r.includes(i.code))return i}function n(e,n,...r){return t(e,n,...r)!==void 0}function r(t,n,r){let i=e(t,n),a=r,o=i._tag===`DeclaredFailure`&&Object.hasOwn(r,i.code)?a[i.code]:void 0;return o?o(i):Object.hasOwn(r,`_`)&&a._?a._(i):i}export{e as decodeFailure,t as failureOf,n as isFailure,r as matchFailure};
2
2
  //# sourceMappingURL=failures.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"failures.mjs","names":["decodeFailure","failure","error","ConvexError","contract","matchFailure","callbacks","handlers","handler"],"sources":["../../src/react/failures.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Transport errors are untrusted; callback results are inferred independently. */\nimport { ConvexError } from 'convex/values'\nimport type { ErrorContract, ErrorDefinitions, UnknownFailure } from '../modules/contracts/errors'\n\nexport type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>\nexport type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>\ntype DeclaredOf<Contract extends FailureContract> = Extract<\n\tFailureOf<Contract>,\n\t{ _tag: 'DeclaredFailure' }\n>\n\n/** Extract ConvexError.data only. Contract validation owns the public envelope. */\nexport function decodeFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n): FailureOf<Contract> {\n\tlet failure: ReturnType<FailureContract['decode']> = { _tag: 'UnknownFailure', version: 1 }\n\ttry {\n\t\tif (error instanceof ConvexError) failure = contract.decode(error.data)\n\t} catch {\n\t\t// Malformed proxies/getters and foreign errors never expose their diagnostics.\n\t}\n\t// SAFETY: the explicit contract owns its decode result; every error contract includes UnknownFailure.\n\treturn failure as FailureOf<Contract>\n}\n\ntype DeclaredHandlers<Contract extends FailureContract> = {\n\t[Code in DeclaredOf<Contract>['code']]: (\n\t\tfailure: Code extends '_' ? FailureOf<Contract> : Extract<DeclaredOf<Contract>, { code: Code }>,\n\t) => unknown\n}\nexport type FailureHandlers<Contract extends FailureContract> =\n\t| DeclaredHandlers<Contract>\n\t| (Partial<DeclaredHandlers<Contract>> & { _: (failure: FailureOf<Contract>) => unknown })\ntype HandlerResult<Handlers> = {\n\t[Key in keyof Handlers]: Handlers[Key] extends (...args: never[]) => infer Result ? Result : never\n}[keyof Handlers]\n\n/** Dispatch on code after validation. Without `_`, unknown errors return UnknownFailure. */\nexport function matchFailure<Contract extends FailureContract, const Handlers extends object>(\n\terror: unknown,\n\tcontract: Contract,\n\thandlers: Partial<DeclaredHandlers<NoInfer<Contract>>> & {\n\t\t_: (failure: FailureOf<NoInfer<Contract>>) => unknown\n\t} & Handlers &\n\t\tRecord<Exclude<keyof Handlers, keyof DeclaredHandlers<Contract> | '_'>, never>,\n): HandlerResult<Handlers>\nexport function matchFailure<Contract extends FailureContract, const Handlers extends object>(\n\terror: unknown,\n\tcontract: Contract,\n\thandlers: DeclaredHandlers<NoInfer<Contract>> &\n\t\tHandlers &\n\t\tRecord<Exclude<keyof Handlers, keyof DeclaredHandlers<Contract>>, never>,\n): HandlerResult<Handlers> | UnknownFailure\nexport function matchFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n\thandlers: FailureHandlers<Contract>,\n): unknown {\n\tconst failure = decodeFailure(error, contract)\n\t// SAFETY: the checked declaration pairs each callback with its code; only the validated code selects it.\n\tconst callbacks = handlers as Record<\n\t\tstring,\n\t\t((failure: FailureOf<Contract>) => unknown) | undefined\n\t>\n\tconst handler =\n\t\tfailure._tag === 'DeclaredFailure' && Object.hasOwn(handlers, failure.code)\n\t\t\t? callbacks[failure.code]\n\t\t\t: undefined\n\treturn handler\n\t\t? handler(failure)\n\t\t: Object.hasOwn(handlers, '_') && callbacks._\n\t\t\t? callbacks._(failure)\n\t\t\t: failure\n}\n"],"mappings":"4CAYA,SAAgBA,EACf,EACA,EACsB,CACtB,IAAIC,EAAiD,CAAE,KAAM,iBAAkB,QAAS,CAAE,EAC1F,GAAI,CACCC,aAAiBC,IAAa,EAAUC,EAAS,OAAOF,EAAM,IAAI,EACvE,MAAQ,CAER,CAEA,OAAOD,CACR,CA8BA,SAAgBI,EACf,EACA,EACA,EACU,CACV,IAAMJ,EAAUD,EAAcE,EAAOE,CAAQ,EAEvCE,EAAYC,EAIZC,EACLP,EAAQ,OAAS,mBAAqB,OAAO,OAAOM,EAAUN,EAAQ,IAAI,EACvEK,EAAUL,EAAQ,MAClB,IAAA,GACJ,OAAOO,EACJA,EAAQP,CAAO,EACf,OAAO,OAAOM,EAAU,GAAG,GAAKD,EAAU,EACzCA,EAAU,EAAEL,CAAO,EACnBA,CACL"}
1
+ {"version":3,"file":"failures.mjs","names":["failureOf","codes","failure","decodeFailure","error","contract","isFailure","matchFailure","callbacks","handlers","handler"],"sources":["../../src/react/failures.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Transport errors are untrusted; callback results are inferred independently. */\nimport type { UnknownFailure, FailureContract, FailureOf } from '../modules/contracts/errors'\nimport { decodeFailure } from '../modules/contracts/errors'\n// oxlint-disable-next-line cvx/no-internal-reexports -- Preserve existing helper imports while sharing transport decoding with neutral contract composition.\nexport { decodeFailure, type FailureContract, type FailureOf } from '../modules/contracts/errors'\n\ntype DeclaredOf<Contract extends FailureContract> = Extract<\n\tFailureOf<Contract>,\n\t{ _tag: 'DeclaredFailure' }\n>\n\n/** Return a selected validated failure; never mutate or narrow the caught error itself. */\nexport function failureOf<\n\tContract extends FailureContract,\n\tconst Codes extends readonly DeclaredOf<Contract>['code'][],\n>(\n\terror: unknown,\n\tcontract: Contract,\n\t...codes: Codes\n): Extract<DeclaredOf<Contract>, { code: Codes[number] }> | undefined {\n\tconst failure = decodeFailure(error, contract)\n\tif (failure._tag !== 'DeclaredFailure' || !codes.includes(failure.code)) return undefined\n\t// SAFETY: only a decoded declared failure whose code occurs in the requested set is returned.\n\treturn failure as Extract<DeclaredOf<Contract>, { code: Codes[number] }>\n}\n\n/** Boolean convenience predicate; use failureOf to access narrowed details. */\nexport function isFailure<\n\tContract extends FailureContract,\n\tconst Codes extends readonly DeclaredOf<Contract>['code'][],\n>(error: unknown, contract: Contract, ...codes: Codes): boolean {\n\treturn failureOf(error, contract, ...codes) !== undefined\n}\n\ntype DeclaredHandlers<Contract extends FailureContract> = {\n\t[Code in DeclaredOf<Contract>['code']]: (\n\t\tfailure: Code extends '_' ? FailureOf<Contract> : Extract<DeclaredOf<Contract>, { code: Code }>,\n\t) => unknown\n}\nexport type FailureHandlers<Contract extends FailureContract> =\n\t| DeclaredHandlers<Contract>\n\t| (Partial<DeclaredHandlers<Contract>> & { _: (failure: FailureOf<Contract>) => unknown })\ntype HandlerResult<Handlers> = {\n\t[Key in keyof Handlers]: Handlers[Key] extends (...args: never[]) => infer Result ? Result : never\n}[keyof Handlers]\n\n/** Dispatch on code after validation. Without `_`, unknown errors return UnknownFailure. */\nexport function matchFailure<Contract extends FailureContract, const Handlers extends object>(\n\terror: unknown,\n\tcontract: Contract,\n\thandlers: Partial<DeclaredHandlers<NoInfer<Contract>>> & {\n\t\t_: (failure: FailureOf<NoInfer<Contract>>) => unknown\n\t} & Handlers &\n\t\tRecord<Exclude<keyof Handlers, keyof DeclaredHandlers<Contract> | '_'>, never>,\n): HandlerResult<Handlers>\nexport function matchFailure<Contract extends FailureContract, const Handlers extends object>(\n\terror: unknown,\n\tcontract: Contract,\n\thandlers: DeclaredHandlers<NoInfer<Contract>> &\n\t\tHandlers &\n\t\tRecord<Exclude<keyof Handlers, keyof DeclaredHandlers<Contract>>, never>,\n): HandlerResult<Handlers> | UnknownFailure\nexport function matchFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n\thandlers: FailureHandlers<Contract>,\n): unknown {\n\tconst failure = decodeFailure(error, contract)\n\t// SAFETY: the checked declaration pairs each callback with its code; only the validated code selects it.\n\tconst callbacks = handlers as Record<\n\t\tstring,\n\t\t((failure: FailureOf<Contract>) => unknown) | undefined\n\t>\n\tconst handler =\n\t\tfailure._tag === 'DeclaredFailure' && Object.hasOwn(handlers, failure.code)\n\t\t\t? callbacks[failure.code]\n\t\t\t: undefined\n\treturn handler\n\t\t? handler(failure)\n\t\t: Object.hasOwn(handlers, '_') && callbacks._\n\t\t\t? callbacks._(failure)\n\t\t\t: failure\n}\n"],"mappings":"gEAYA,SAAgBA,EAIf,EACA,EACA,GAAGC,EACkE,CACrE,IAAMC,EAAUC,EAAcC,EAAOC,CAAQ,EAC7C,GAAIH,EAAQ,OAAS,mBAAsBD,EAAM,SAASC,EAAQ,IAAI,EAEtE,OAAOA,CACR,CAGA,SAAgBI,EAGd,EAAgB,EAAoB,GAAGL,EAAuB,CAC/D,OAAOD,EAAUI,EAAOC,EAAU,GAAGJ,CAAK,IAAM,IAAA,EACjD,CA8BA,SAAgBM,EACf,EACA,EACA,EACU,CACV,IAAML,EAAUC,EAAcC,EAAOC,CAAQ,EAEvCG,EAAYC,EAIZC,EACLR,EAAQ,OAAS,mBAAqB,OAAO,OAAOO,EAAUP,EAAQ,IAAI,EACvEM,EAAUN,EAAQ,MAClB,IAAA,GACJ,OAAOQ,EACJA,EAAQR,CAAO,EACf,OAAO,OAAOO,EAAU,GAAG,GAAKD,EAAU,EACzCA,EAAU,EAAEN,CAAO,EACnBA,CACL"}
@@ -1,4 +1,5 @@
1
- import { FailureContract, FailureOf } from "./failures.mjs";
1
+ import { FailureContract, FailureOf } from "../modules/contracts/errors.mjs";
2
+ import "./failures.mjs";
2
3
  import { FunctionArgs, FunctionReference, FunctionReturnType, OptionalRestArgs } from "convex/server";
3
4
  import { OptimisticUpdate } from "convex/browser";
4
5
  //#region src/react/use-command.d.ts
@@ -1,2 +1,2 @@
1
- import{decodeFailure as e}from"./failures.mjs";import{useCallback as t,useMemo as n,useRef as r,useState as i}from"react";import{useMutation as a}from"convex/react";function o(o,s){let c=a(o),{errors:l,optimisticUpdate:u}=s,d=n(()=>u?c.withOptimisticUpdate(u):c,[c,u]),[f,p]=i(0),[m,h]=i(),g=r(0),_=t(async(...t)=>{let n=++g.current;p(e=>e+1);let r;try{r={ok:!0,value:await d(...t)}}catch(t){r={ok:!1,failure:e(t,l)}}return p(e=>e-1),g.current===n&&h(r),r},[d,l]);return n(()=>Object.assign((...e)=>_(...e),{isPending:f>0,result:m}),[_,f,m])}export{o as useCommand};
1
+ import{decodeFailure as e}from"../modules/contracts/errors.mjs";import{useCallback as t,useMemo as n,useRef as r,useState as i}from"react";import{useMutation as a}from"convex/react";function o(o,s){let c=a(o),{errors:l,optimisticUpdate:u}=s,d=n(()=>u?c.withOptimisticUpdate(u):c,[c,u]),[f,p]=i(0),[m,h]=i(),g=r(0),_=t(async(...t)=>{let n=++g.current;p(e=>e+1);let r;try{r={ok:!0,value:await d(...t)}}catch(t){r={ok:!1,failure:e(t,l)}}return p(e=>e-1),g.current===n&&h(r),r},[d,l]);return n(()=>Object.assign((...e)=>_(...e),{isPending:f>0,result:m}),[_,f,m])}export{o as useCommand};
2
2
  //# sourceMappingURL=use-command.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-command.mjs","names":["useCommand","mutation","useMutation","reference","options","run","useMemo","optimisticUpdate","pending","setPending","useState","result","setResult","latest","useRef","execute","useCallback","args","invocation","count","settled","error","decodeFailure","errors"],"sources":["../../src/react/use-command.ts"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from 'react'\nimport { useMutation } from 'convex/react'\nimport type { OptimisticUpdate } from 'convex/browser'\nimport type {\n\tFunctionArgs,\n\tFunctionReference,\n\tFunctionReturnType,\n\tOptionalRestArgs,\n} from 'convex/server'\nimport { decodeFailure, type FailureContract, type FailureOf } from './failures'\n\nexport type CommandResult<Result, Contract extends FailureContract> =\n\t| Readonly<{ ok: true; value: Result }>\n\t| Readonly<{ ok: false; failure: FailureOf<Contract> }>\nexport type Command<\n\tMutation extends FunctionReference<'mutation'>,\n\tContract extends FailureContract,\n> = ((\n\t...args: OptionalRestArgs<Mutation>\n) => Promise<CommandResult<FunctionReturnType<Mutation>, Contract>>) & {\n\treadonly isPending: boolean\n\t/** The latest invocation's settled result; older concurrent completions cannot overwrite it. */\n\treadonly result: CommandResult<FunctionReturnType<Mutation>, Contract> | undefined\n}\n\n/** Explicit failures plus Convex-owned optimistic execution, replay and rollback. */\nexport function useCommand<\n\tMutation extends FunctionReference<'mutation'>,\n\tContract extends FailureContract,\n\tUpdate extends OptimisticUpdate<FunctionArgs<Mutation>> = OptimisticUpdate<\n\t\tFunctionArgs<Mutation>\n\t>,\n>(\n\treference: Mutation,\n\toptions: {\n\t\terrors: Contract\n\t\toptimisticUpdate?: Update &\n\t\t\t(ReturnType<Update> extends Promise<any>\n\t\t\t\t? 'Optimistic update handlers must be synchronous'\n\t\t\t\t: {})\n\t},\n): Command<Mutation, Contract> {\n\tconst mutation = useMutation(reference)\n\tconst { errors, optimisticUpdate } = options\n\t// Attach once per mutation/callback identity. Convex may invoke this callback repeatedly while pending.\n\tconst run = useMemo(\n\t\t() => (optimisticUpdate ? mutation.withOptimisticUpdate<Update>(optimisticUpdate) : mutation),\n\t\t[mutation, optimisticUpdate],\n\t)\n\tconst [pending, setPending] = useState(0)\n\tconst [result, setResult] = useState<CommandResult<FunctionReturnType<Mutation>, Contract>>()\n\tconst latest = useRef(0)\n\tconst execute = useCallback(\n\t\tasync (...args: OptionalRestArgs<Mutation>) => {\n\t\t\tconst invocation = ++latest.current\n\t\t\tsetPending((count) => count + 1)\n\t\t\tlet settled: CommandResult<FunctionReturnType<Mutation>, Contract>\n\t\t\ttry {\n\t\t\t\tsettled = { ok: true, value: await run(...args) }\n\t\t\t} catch (error) {\n\t\t\t\tsettled = { ok: false, failure: decodeFailure(error, errors) }\n\t\t\t}\n\t\t\tsetPending((count) => count - 1)\n\t\t\tif (latest.current === invocation) setResult(settled)\n\t\t\treturn settled\n\t\t},\n\t\t[run, errors],\n\t)\n\treturn useMemo(\n\t\t() =>\n\t\t\tObject.assign((...args: OptionalRestArgs<Mutation>) => execute(...args), {\n\t\t\t\tisPending: pending > 0,\n\t\t\t\tresult,\n\t\t\t}),\n\t\t[execute, pending, result],\n\t)\n}\n"],"mappings":"qKA0BA,SAAgBA,EAOf,EACA,EAO8B,CAC9B,IAAMC,EAAWC,EAAYC,CAAS,EAChC,CAAE,SAAQ,oBAAqBC,EAE/BC,EAAMC,MACJC,EAAmBN,EAAS,qBAA6BM,CAAgB,EAAIN,EACpF,CAACA,EAAUM,CAAgB,CAC5B,EACM,CAACC,EAASC,GAAcC,EAAS,CAAC,EAClC,CAACC,EAAQC,GAAaF,EAAgE,EACtFG,EAASC,EAAO,CAAC,EACjBC,EAAUC,EACf,MAAO,GAAGC,IAAqC,CAC9C,IAAMC,EAAa,EAAEL,EAAO,QAC5BJ,EAAY,GAAUU,EAAQ,CAAC,EAC/B,IAAIC,EACJ,GAAI,CACH,EAAU,CAAE,GAAI,GAAM,MAAO,MAAMf,EAAI,GAAGY,CAAI,CAAE,CACjD,OAASI,EAAO,CACf,EAAU,CAAE,GAAI,GAAO,QAASC,EAAcD,EAAOE,CAAM,CAAE,CAC9D,CAGA,OAFAd,EAAY,GAAUU,EAAQ,CAAC,EAC3BN,EAAO,UAAYK,GAAYN,EAAUQ,CAAO,EAC7CA,CACR,EACA,CAACf,EAAKkB,CAAM,CACb,EACA,OAAOjB,MAEL,OAAO,QAAQ,GAAGW,IAAqCF,EAAQ,GAAGE,CAAI,EAAG,CACxE,UAAWT,EAAU,EACrB,QACD,CAAC,EACF,CAACO,EAASP,EAASG,CAAM,CAC1B,CACD"}
1
+ {"version":3,"file":"use-command.mjs","names":["useCommand","mutation","useMutation","reference","options","run","useMemo","optimisticUpdate","pending","setPending","useState","result","setResult","latest","useRef","execute","useCallback","args","invocation","count","settled","error","decodeFailure","errors"],"sources":["../../src/react/use-command.ts"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from 'react'\nimport { useMutation } from 'convex/react'\nimport type { OptimisticUpdate } from 'convex/browser'\nimport type {\n\tFunctionArgs,\n\tFunctionReference,\n\tFunctionReturnType,\n\tOptionalRestArgs,\n} from 'convex/server'\nimport { decodeFailure, type FailureContract, type FailureOf } from './failures'\n\nexport type CommandResult<Result, Contract extends FailureContract> =\n\t| Readonly<{ ok: true; value: Result }>\n\t| Readonly<{ ok: false; failure: FailureOf<Contract> }>\nexport type Command<\n\tMutation extends FunctionReference<'mutation'>,\n\tContract extends FailureContract,\n> = ((\n\t...args: OptionalRestArgs<Mutation>\n) => Promise<CommandResult<FunctionReturnType<Mutation>, Contract>>) & {\n\treadonly isPending: boolean\n\t/** The latest invocation's settled result; older concurrent completions cannot overwrite it. */\n\treadonly result: CommandResult<FunctionReturnType<Mutation>, Contract> | undefined\n}\n\n/** Explicit failures plus Convex-owned optimistic execution, replay and rollback. */\nexport function useCommand<\n\tMutation extends FunctionReference<'mutation'>,\n\tContract extends FailureContract,\n\tUpdate extends OptimisticUpdate<FunctionArgs<Mutation>> = OptimisticUpdate<\n\t\tFunctionArgs<Mutation>\n\t>,\n>(\n\treference: Mutation,\n\toptions: {\n\t\terrors: Contract\n\t\toptimisticUpdate?: Update &\n\t\t\t(ReturnType<Update> extends Promise<any>\n\t\t\t\t? 'Optimistic update handlers must be synchronous'\n\t\t\t\t: {})\n\t},\n): Command<Mutation, Contract> {\n\tconst mutation = useMutation(reference)\n\tconst { errors, optimisticUpdate } = options\n\t// Attach once per mutation/callback identity. Convex may invoke this callback repeatedly while pending.\n\tconst run = useMemo(\n\t\t() => (optimisticUpdate ? mutation.withOptimisticUpdate<Update>(optimisticUpdate) : mutation),\n\t\t[mutation, optimisticUpdate],\n\t)\n\tconst [pending, setPending] = useState(0)\n\tconst [result, setResult] = useState<CommandResult<FunctionReturnType<Mutation>, Contract>>()\n\tconst latest = useRef(0)\n\tconst execute = useCallback(\n\t\tasync (...args: OptionalRestArgs<Mutation>) => {\n\t\t\tconst invocation = ++latest.current\n\t\t\tsetPending((count) => count + 1)\n\t\t\tlet settled: CommandResult<FunctionReturnType<Mutation>, Contract>\n\t\t\ttry {\n\t\t\t\tsettled = { ok: true, value: await run(...args) }\n\t\t\t} catch (error) {\n\t\t\t\tsettled = { ok: false, failure: decodeFailure(error, errors) }\n\t\t\t}\n\t\t\tsetPending((count) => count - 1)\n\t\t\tif (latest.current === invocation) setResult(settled)\n\t\t\treturn settled\n\t\t},\n\t\t[run, errors],\n\t)\n\treturn useMemo(\n\t\t() =>\n\t\t\tObject.assign((...args: OptionalRestArgs<Mutation>) => execute(...args), {\n\t\t\t\tisPending: pending > 0,\n\t\t\t\tresult,\n\t\t\t}),\n\t\t[execute, pending, result],\n\t)\n}\n"],"mappings":"sLA0BA,SAAgBA,EAOf,EACA,EAO8B,CAC9B,IAAMC,EAAWC,EAAYC,CAAS,EAChC,CAAE,SAAQ,oBAAqBC,EAE/BC,EAAMC,MACJC,EAAmBN,EAAS,qBAA6BM,CAAgB,EAAIN,EACpF,CAACA,EAAUM,CAAgB,CAC5B,EACM,CAACC,EAASC,GAAcC,EAAS,CAAC,EAClC,CAACC,EAAQC,GAAaF,EAAgE,EACtFG,EAASC,EAAO,CAAC,EACjBC,EAAUC,EACf,MAAO,GAAGC,IAAqC,CAC9C,IAAMC,EAAa,EAAEL,EAAO,QAC5BJ,EAAY,GAAUU,EAAQ,CAAC,EAC/B,IAAIC,EACJ,GAAI,CACH,EAAU,CAAE,GAAI,GAAM,MAAO,MAAMf,EAAI,GAAGY,CAAI,CAAE,CACjD,OAASI,EAAO,CACf,EAAU,CAAE,GAAI,GAAO,QAASC,EAAcD,EAAOE,CAAM,CAAE,CAC9D,CAGA,OAFAd,EAAY,GAAUU,EAAQ,CAAC,EAC3BN,EAAO,UAAYK,GAAYN,EAAUQ,CAAO,EAC7CA,CACR,EACA,CAACf,EAAKkB,CAAM,CACb,EACA,OAAOjB,MAEL,OAAO,QAAQ,GAAGW,IAAqCF,EAAQ,GAAGE,CAAI,EAAG,CACxE,UAAWT,EAAU,EACrB,QACD,CAAC,EACF,CAACO,EAASP,EAASG,CAAM,CAC1B,CACD"}
@@ -1,5 +1,5 @@
1
- import { queryErrors } from "../modules/contracts/errors.mjs";
2
- import { FailureContract, FailureOf } from "./failures.mjs";
1
+ import { FailureContract, FailureOf, queryErrors } from "../modules/contracts/errors.mjs";
2
+ import "./failures.mjs";
3
3
  import { ListPage } from "./pagination-state.mjs";
4
4
  import { FunctionArgs, FunctionReference, FunctionReturnType, PaginationOptions } from "convex/server";
5
5
  import { Value } from "convex/values";
@@ -16,11 +16,15 @@ export type PaginatedList<Query extends ListQueryReference, Contract extends Fai
16
16
  resetKey: string;
17
17
  completeness: FunctionReturnType<Query>['completeness'] | undefined;
18
18
  failure: FailureOf<Contract> | undefined;
19
+ /** Original subscription error, without decoding or mutation. */
20
+ error: Error | undefined;
19
21
  };
20
22
  export type PaginatedListOptions<Contract extends FailureContract = typeof queryErrors> = {
21
23
  /** Integer 1..100. Initial target for native search; browse uses fixed adjacent pages. */
22
24
  pageSize: number;
23
25
  onInvalidCursor?: 'restart' | 'throw';
26
+ /** Keep failures in state (default), or throw the original error to a React boundary. */
27
+ onFailure?: 'state' | 'throw';
24
28
  /** Explicit server contract; generated references do not carry error metadata. Defaults to queryErrors. */
25
29
  errors?: Contract;
26
30
  /** Convex value identifying the current auth/scope/reset generation. Never a credential. */
@@ -1,2 +1,2 @@
1
- import{queryErrors as e}from"../modules/contracts/errors.mjs";import{decodeFailure as t}from"./failures.mjs";import{initialPagination as n,nextPagination as r,paginationView as i,reconcilePagination as a}from"./pagination-state.mjs";import{getFunctionName as o}from"convex/server";import{convexToJson as s}from"convex/values";import{useMemo as c,useState as l}from"react";import{useQueries as u}from"convex/react";let d=0;function f(f,p,m){let{pageSize:h}=m;if(!Number.isInteger(h)||h<1||h>100)throw Error(`pageSize must be an integer from 1 to 100`);let g=p===`skip`,_=g?{}:p,v=JSON.stringify([o(f),s(_),s(m.resetIdentity??null),h,g]),[y,b]=l(()=>n(v,++d,g)),x=y;x.identity!==v&&(x=n(v,++d,g));let S=c(()=>Object.fromEntries(Object.entries(x.intervals).map(([e,t])=>{let n={numItems:h,cursor:t.cursor,id:x.epoch};return t.endCursor!==void 0&&(n.endCursor=t.endCursor),[e,{query:f,args:{..._,paginationOpts:n}}]})),[x.intervals,x.epoch,v]),C=u(S);x=a(x,C);let w=m.errors??e,T=x.error?t(x.error,w):void 0,E=x.error?t(x.error,e):void 0,D=x.error&&T?._tag===`DeclaredFailure`&&T.code===`invalid-cursor`&&E?._tag===`DeclaredFailure`&&E.code===`invalid-cursor`;if(D&&m.onInvalidCursor!==`throw`&&!x.restarted&&(x=n(v,++d,g,!0),T=void 0),x!==y&&b(x),D&&m.onInvalidCursor===`throw`)throw x.error;let O=i(x),k=x.epoch;return{...O,rows:O.rows,completeness:O.completeness,failure:T,resetKey:`${v}:${+!!x.restarted}`,fetchNextPage:()=>b(e=>e.epoch===k&&e.identity===v?r(e):e)}}export{f as usePaginatedList};
1
+ import{decodeFailure as e,queryErrors as t}from"../modules/contracts/errors.mjs";import{initialPagination as n,nextPagination as r,paginationView as i,reconcilePagination as a}from"./pagination-state.mjs";import{getFunctionName as o}from"convex/server";import{convexToJson as s}from"convex/values";import{useMemo as c,useState as l}from"react";import{useQueries as u}from"convex/react";let d=0;function f(f,p,m){let{pageSize:h}=m;if(!Number.isInteger(h)||h<1||h>100)throw Error(`pageSize must be an integer from 1 to 100`);let g=p===`skip`,_=g?{}:p,v=JSON.stringify([o(f),s(_),s(m.resetIdentity??null),h,g]),[y,b]=l(()=>n(v,++d,g)),x=y;x.identity!==v&&(x=n(v,++d,g));let S=c(()=>Object.fromEntries(Object.entries(x.intervals).map(([e,t])=>{let n={numItems:h,cursor:t.cursor,id:x.epoch};return t.endCursor!==void 0&&(n.endCursor=t.endCursor),[e,{query:f,args:{..._,paginationOpts:n}}]})),[x.intervals,x.epoch,v]),C=u(S);x=a(x,C);let w=m.errors??t,T=x.error?e(x.error,w):void 0,E=x.error?e(x.error,t):void 0,D=x.error&&T?._tag===`DeclaredFailure`&&T.code===`invalid-cursor`&&E?._tag===`DeclaredFailure`&&E.code===`invalid-cursor`;if(D&&m.onInvalidCursor!==`throw`&&!x.restarted&&(x=n(v,++d,g,!0),T=void 0),x!==y&&b(x),x.error&&(m.onFailure===`throw`||D&&m.onInvalidCursor===`throw`))throw x.error;let O=i(x),k=x.epoch;return{...O,rows:O.rows,completeness:O.completeness,failure:T,error:x.error,resetKey:`${v}:${+!!x.restarted}`,fetchNextPage:()=>b(e=>e.epoch===k&&e.identity===v?r(e):e)}}export{f as usePaginatedList};
2
2
  //# sourceMappingURL=use-paginated-list.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-paginated-list.mjs","names":["epoch","usePaginatedList","options","pageSize","skip","args","effectiveArgs","identity","getFunctionName","query","convexToJson","stored","setState","useState","initialPagination","state","queries","useMemo","key","interval","paginationOpts","results","useQueries","reconcilePagination","errors","queryErrors","failure","decodeFailure","queryFailure","invalid","view","paginationView","currentEpoch","previous","nextPagination"],"sources":["../../src/react/use-paginated-list.ts"],"sourcesContent":["import { useMemo, useState } from 'react'\nimport { useQueries } from 'convex/react'\nimport {\n\tgetFunctionName,\n\ttype FunctionArgs,\n\ttype FunctionReference,\n\ttype FunctionReturnType,\n\ttype PaginationOptions,\n} from 'convex/server'\nimport { convexToJson, type Value } from 'convex/values'\nimport { queryErrors } from '../modules/contracts/errors'\nimport { decodeFailure, type FailureContract, type FailureOf } from './failures'\nimport {\n\tinitialPagination,\n\treconcilePagination,\n\tnextPagination,\n\tpaginationView,\n\ttype ListPage,\n} from './pagination-state'\n\nexport type ListQueryReference = FunctionReference<\n\t'query',\n\t'public',\n\t{ paginationOpts: PaginationOptions },\n\tListPage\n>\nexport type PaginatedList<\n\tQuery extends ListQueryReference,\n\tContract extends FailureContract = typeof queryErrors,\n> = {\n\trows: FunctionReturnType<Query>['page']\n\tisLoading: boolean\n\thasNextPage: boolean\n\tisFetchingNextPage: boolean\n\tfetchNextPage: () => void\n\tresetKey: string\n\tcompleteness: FunctionReturnType<Query>['completeness'] | undefined\n\tfailure: FailureOf<Contract> | undefined\n}\nexport type PaginatedListOptions<Contract extends FailureContract = typeof queryErrors> = {\n\t/** Integer 1..100. Initial target for native search; browse uses fixed adjacent pages. */\n\tpageSize: number\n\tonInvalidCursor?: 'restart' | 'throw'\n\t/** Explicit server contract; generated references do not carry error metadata. Defaults to queryErrors. */\n\terrors?: Contract\n\t/** Convex value identifying the current auth/scope/reset generation. Never a credential. */\n\tresetIdentity?: Value\n}\ntype IntervalPagination = {\n\tnumItems: number\n\tcursor: string | null\n\tid: number\n\tendCursor?: string\n}\nlet epoch = 0\n/** Reactive engine-backed list: fixed browse ranges or SDK-journal search windows. Empty pages advance manually. */\nexport function usePaginatedList<\n\tQuery extends ListQueryReference,\n\tContract extends FailureContract = typeof queryErrors,\n>(\n\tquery: Query,\n\targs: Omit<FunctionArgs<Query>, 'paginationOpts'> | 'skip',\n\toptions: PaginatedListOptions<Contract>,\n): PaginatedList<Query, Contract> {\n\tconst { pageSize } = options\n\tif (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100)\n\t\tthrow new Error('pageSize must be an integer from 1 to 100')\n\tconst skip = args === 'skip'\n\t// Convex's public encoder sorts object keys recursively and preserves array order, IDs, bytes and int64.\n\t// SAFETY: FunctionArgs are Convex values; pagination transport is owned exclusively by this hook.\n\tconst effectiveArgs = skip ? {} : (args as Record<string, Value>)\n\tconst identity = JSON.stringify([\n\t\tgetFunctionName(query),\n\t\tconvexToJson(effectiveArgs),\n\t\tconvexToJson(options.resetIdentity ?? null),\n\t\tpageSize,\n\t\tskip,\n\t])\n\tconst [stored, setState] = useState(() =>\n\t\tinitialPagination<FunctionReturnType<Query>>(identity, ++epoch, skip),\n\t)\n\tlet state = stored\n\tif (state.identity !== identity) state = initialPagination(identity, ++epoch, skip)\n\tconst queries = useMemo(\n\t\t() =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(state.intervals).map(([key, interval]) => {\n\t\t\t\t\tconst paginationOpts: IntervalPagination = {\n\t\t\t\t\t\tnumItems: pageSize,\n\t\t\t\t\t\tcursor: interval.cursor,\n\t\t\t\t\t\tid: state.epoch,\n\t\t\t\t\t}\n\t\t\t\t\tif (interval.endCursor !== undefined) paginationOpts.endCursor = interval.endCursor\n\t\t\t\t\treturn [key, { query, args: { ...effectiveArgs, paginationOpts } }]\n\t\t\t\t}),\n\t\t\t),\n\t\t// Equivalent args/references must keep subscriptions stable; identity encodes their effective values.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[state.intervals, state.epoch, identity],\n\t)\n\t// SAFETY: useQueries returns each complete endpoint result or an Error for the keyed subscription.\n\tconst results = useQueries(queries) as Record<\n\t\tstring,\n\t\tFunctionReturnType<Query> | Error | undefined\n\t>\n\tstate = reconcilePagination(state, results)\n\tconst errors = options.errors ?? queryErrors\n\tlet failure = state.error ? decodeFailure(state.error, errors) : undefined\n\t// Both the explicit decoder and the fixed query contract must validate the actual transported envelope.\n\tconst queryFailure = state.error ? decodeFailure(state.error, queryErrors) : undefined\n\tconst invalid =\n\t\tstate.error &&\n\t\tfailure?._tag === 'DeclaredFailure' &&\n\t\tfailure.code === 'invalid-cursor' &&\n\t\tqueryFailure?._tag === 'DeclaredFailure' &&\n\t\tqueryFailure.code === 'invalid-cursor'\n\tif (invalid && options.onInvalidCursor !== 'throw' && !state.restarted) {\n\t\tstate = initialPagination(identity, ++epoch, skip, true)\n\t\tfailure = undefined\n\t}\n\tif (state !== stored) setState(state)\n\tif (invalid && options.onInvalidCursor === 'throw') throw state.error\n\tconst view = paginationView(state)\n\tconst currentEpoch = state.epoch\n\treturn {\n\t\t...view,\n\t\t// SAFETY: the controller concatenates unmodified elements from this query's validated page DTOs.\n\t\trows: view.rows as FunctionReturnType<Query>['page'],\n\t\tcompleteness: view.completeness,\n\t\t// SAFETY: omitted errors selects the default Contract parameter; an explicit contract owns its decoder.\n\t\tfailure: failure as FailureOf<Contract> | undefined,\n\t\tresetKey: `${identity}:${state.restarted ? 1 : 0}`,\n\t\tfetchNextPage: () =>\n\t\t\tsetState((previous) =>\n\t\t\t\tprevious.epoch === currentEpoch && previous.identity === identity\n\t\t\t\t\t? nextPagination(previous)\n\t\t\t\t\t: previous,\n\t\t\t),\n\t}\n}\n"],"mappings":"8ZAsDA,IAAIA,EAAQ,EAEZ,SAAgBC,EAIf,EACA,EACA,EACiC,CACjC,GAAM,CAAE,YAAaC,EACrB,GAAI,CAAC,OAAO,UAAUC,CAAQ,GAAKA,EAAW,GAAKA,EAAW,IAC7D,MAAU,MAAM,2CAA2C,EAC5D,IAAMC,EAA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EAAQ,kBAAoB,QAAS,MAAMa,EAAM,MAChE,IAAMe,EAAOC,EAAehB,CAAK,EAC3BiB,EAAejB,EAAM,MAC3B,MAAO,CACN,GAAGe,EAEH,KAAMA,EAAK,KACX,aAAcA,EAAK,aAEV,UACT,SAAU,GAAGvB,EAAS,GAAG,KAAM,YAC/B,kBACCK,EAAU,GACTqB,EAAS,QAAUD,GAAgBC,EAAS,WAAa1B,EACtD2B,EAAeD,CAAQ,EACvBA,CACJ,CACF,CACD"}
1
+ {"version":3,"file":"use-paginated-list.mjs","names":["epoch","usePaginatedList","options","pageSize","skip","args","effectiveArgs","identity","getFunctionName","query","convexToJson","stored","setState","useState","initialPagination","state","queries","useMemo","key","interval","paginationOpts","results","useQueries","reconcilePagination","errors","queryErrors","failure","decodeFailure","queryFailure","invalid","view","paginationView","currentEpoch","previous","nextPagination"],"sources":["../../src/react/use-paginated-list.ts"],"sourcesContent":["import { useMemo, useState } from 'react'\nimport { useQueries } from 'convex/react'\nimport {\n\tgetFunctionName,\n\ttype FunctionArgs,\n\ttype FunctionReference,\n\ttype FunctionReturnType,\n\ttype PaginationOptions,\n} from 'convex/server'\nimport { convexToJson, type Value } from 'convex/values'\nimport { queryErrors } from '../modules/contracts/errors'\nimport { decodeFailure, type FailureContract, type FailureOf } from './failures'\nimport {\n\tinitialPagination,\n\treconcilePagination,\n\tnextPagination,\n\tpaginationView,\n\ttype ListPage,\n} from './pagination-state'\n\nexport type ListQueryReference = FunctionReference<\n\t'query',\n\t'public',\n\t{ paginationOpts: PaginationOptions },\n\tListPage\n>\nexport type PaginatedList<\n\tQuery extends ListQueryReference,\n\tContract extends FailureContract = typeof queryErrors,\n> = {\n\trows: FunctionReturnType<Query>['page']\n\tisLoading: boolean\n\thasNextPage: boolean\n\tisFetchingNextPage: boolean\n\tfetchNextPage: () => void\n\tresetKey: string\n\tcompleteness: FunctionReturnType<Query>['completeness'] | undefined\n\tfailure: FailureOf<Contract> | undefined\n\t/** Original subscription error, without decoding or mutation. */\n\terror: Error | undefined\n}\nexport type PaginatedListOptions<Contract extends FailureContract = typeof queryErrors> = {\n\t/** Integer 1..100. Initial target for native search; browse uses fixed adjacent pages. */\n\tpageSize: number\n\tonInvalidCursor?: 'restart' | 'throw'\n\t/** Keep failures in state (default), or throw the original error to a React boundary. */\n\tonFailure?: 'state' | 'throw'\n\t/** Explicit server contract; generated references do not carry error metadata. Defaults to queryErrors. */\n\terrors?: Contract\n\t/** Convex value identifying the current auth/scope/reset generation. Never a credential. */\n\tresetIdentity?: Value\n}\ntype IntervalPagination = {\n\tnumItems: number\n\tcursor: string | null\n\tid: number\n\tendCursor?: string\n}\nlet epoch = 0\n/** Reactive engine-backed list: fixed browse ranges or SDK-journal search windows. Empty pages advance manually. */\nexport function usePaginatedList<\n\tQuery extends ListQueryReference,\n\tContract extends FailureContract = typeof queryErrors,\n>(\n\tquery: Query,\n\targs: Omit<FunctionArgs<Query>, 'paginationOpts'> | 'skip',\n\toptions: PaginatedListOptions<Contract>,\n): PaginatedList<Query, Contract> {\n\tconst { pageSize } = options\n\tif (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100)\n\t\tthrow new Error('pageSize must be an integer from 1 to 100')\n\tconst skip = args === 'skip'\n\t// Convex's public encoder sorts object keys recursively and preserves array order, IDs, bytes and int64.\n\t// SAFETY: FunctionArgs are Convex values; pagination transport is owned exclusively by this hook.\n\tconst effectiveArgs = skip ? {} : (args as Record<string, Value>)\n\tconst identity = JSON.stringify([\n\t\tgetFunctionName(query),\n\t\tconvexToJson(effectiveArgs),\n\t\tconvexToJson(options.resetIdentity ?? null),\n\t\tpageSize,\n\t\tskip,\n\t])\n\tconst [stored, setState] = useState(() =>\n\t\tinitialPagination<FunctionReturnType<Query>>(identity, ++epoch, skip),\n\t)\n\tlet state = stored\n\tif (state.identity !== identity) state = initialPagination(identity, ++epoch, skip)\n\tconst queries = useMemo(\n\t\t() =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(state.intervals).map(([key, interval]) => {\n\t\t\t\t\tconst paginationOpts: IntervalPagination = {\n\t\t\t\t\t\tnumItems: pageSize,\n\t\t\t\t\t\tcursor: interval.cursor,\n\t\t\t\t\t\tid: state.epoch,\n\t\t\t\t\t}\n\t\t\t\t\tif (interval.endCursor !== undefined) paginationOpts.endCursor = interval.endCursor\n\t\t\t\t\treturn [key, { query, args: { ...effectiveArgs, paginationOpts } }]\n\t\t\t\t}),\n\t\t\t),\n\t\t// Equivalent args/references must keep subscriptions stable; identity encodes their effective values.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[state.intervals, state.epoch, identity],\n\t)\n\t// SAFETY: useQueries returns each complete endpoint result or an Error for the keyed subscription.\n\tconst results = useQueries(queries) as Record<\n\t\tstring,\n\t\tFunctionReturnType<Query> | Error | undefined\n\t>\n\tstate = reconcilePagination(state, results)\n\tconst errors = options.errors ?? queryErrors\n\tlet failure = state.error ? decodeFailure(state.error, errors) : undefined\n\t// Both the explicit decoder and the fixed query contract must validate the actual transported envelope.\n\tconst queryFailure = state.error ? decodeFailure(state.error, queryErrors) : undefined\n\tconst invalid =\n\t\tstate.error &&\n\t\tfailure?._tag === 'DeclaredFailure' &&\n\t\tfailure.code === 'invalid-cursor' &&\n\t\tqueryFailure?._tag === 'DeclaredFailure' &&\n\t\tqueryFailure.code === 'invalid-cursor'\n\tif (invalid && options.onInvalidCursor !== 'throw' && !state.restarted) {\n\t\tstate = initialPagination(identity, ++epoch, skip, true)\n\t\tfailure = undefined\n\t}\n\tif (state !== stored) setState(state)\n\t// Recovery runs first. A boundary unmount releases useQueries subscriptions even\n\t// when the render-phase state update above cannot commit because this render throws.\n\tif (\n\t\tstate.error &&\n\t\t(options.onFailure === 'throw' || (invalid && options.onInvalidCursor === 'throw'))\n\t)\n\t\tthrow state.error\n\tconst view = paginationView(state)\n\tconst currentEpoch = state.epoch\n\treturn {\n\t\t...view,\n\t\t// SAFETY: the controller concatenates unmodified elements from this query's validated page DTOs.\n\t\trows: view.rows as FunctionReturnType<Query>['page'],\n\t\tcompleteness: view.completeness,\n\t\t// SAFETY: omitted errors selects the default Contract parameter; an explicit contract owns its decoder.\n\t\tfailure: failure as FailureOf<Contract> | undefined,\n\t\terror: state.error,\n\t\tresetKey: `${identity}:${state.restarted ? 1 : 0}`,\n\t\tfetchNextPage: () =>\n\t\t\tsetState((previous) =>\n\t\t\t\tprevious.epoch === currentEpoch && previous.identity === identity\n\t\t\t\t\t? nextPagination(previous)\n\t\t\t\t\t: previous,\n\t\t\t),\n\t}\n}\n"],"mappings":"kYA0DA,IAAIA,EAAQ,EAEZ,SAAgBC,EAIf,EACA,EACA,EACiC,CACjC,GAAM,CAAE,YAAaC,EACrB,GAAI,CAAC,OAAO,UAAUC,CAAQ,GAAKA,EAAW,GAAKA,EAAW,IAC7D,MAAU,MAAM,2CAA2C,EAC5D,IAAMC,EAAOC,IAAS,OAGhBC,EAAgBF,EAAO,CAAC,EAAKC,EAC7BE,EAAW,KAAK,UAAU,CAC/BC,EAAgBC,CAAK,EACrBC,EAAaJ,CAAa,EAC1BI,EAAaR,EAAQ,eAAiB,IAAI,EAC1CC,EACAC,CACD,CAAC,EACK,CAACO,EAAQC,GAAYC,MAC1BC,EAA6CP,EAAU,EAAEP,EAAOI,CAAI,CACrE,EACIW,EAAQJ,EACRI,EAAM,WAAaR,IAAU,EAAQO,EAAkBP,EAAU,EAAEP,EAAOI,CAAI,GAClF,IAAMY,EAAUC,MAEd,OAAO,YACN,OAAO,QAAQF,EAAM,SAAS,CAAC,CAAC,KAAK,CAACG,EAAKC,KAAc,CACxD,IAAMC,EAAqC,CAC1C,SAAUjB,EACV,OAAQgB,EAAS,OACjB,GAAIJ,EAAM,KACX,EAEA,OADII,EAAS,YAAc,IAAA,KAAW,EAAe,UAAYA,EAAS,WACnE,CAACD,EAAK,CAAE,QAAO,KAAM,CAAE,GAAGZ,EAAe,gBAAe,CAAE,CAAC,CACnE,CAAC,CACF,EAGD,CAACS,EAAM,UAAWA,EAAM,MAAOR,CAAQ,CACxC,EAEMc,EAAUC,EAAWN,CAAO,EAIlC,EAAQO,EAAoBR,EAAOM,CAAO,EAC1C,IAAMG,EAAStB,EAAQ,QAAUuB,EAC7BC,EAAUX,EAAM,MAAQY,EAAcZ,EAAM,MAAOS,CAAM,EAAI,IAAA,GAE3DI,EAAeb,EAAM,MAAQY,EAAcZ,EAAM,MAAOU,CAAW,EAAI,IAAA,GACvEI,EACLd,EAAM,OACNW,GAAS,OAAS,mBAClBA,EAAQ,OAAS,kBACjBE,GAAc,OAAS,mBACvBA,EAAa,OAAS,iBAQvB,GAPIC,GAAW3B,EAAQ,kBAAoB,SAAW,CAACa,EAAM,YAC5D,EAAQD,EAAkBP,EAAU,EAAEP,EAAOI,EAAM,EAAI,EACvD,EAAU,IAAA,IAEPW,IAAUJ,GAAQC,EAASG,CAAK,EAInCA,EAAM,QACLb,EAAQ,YAAc,SAAY2B,GAAW3B,EAAQ,kBAAoB,SAE1E,MAAMa,EAAM,MACb,IAAMe,EAAOC,EAAehB,CAAK,EAC3BiB,EAAejB,EAAM,MAC3B,MAAO,CACN,GAAGe,EAEH,KAAMA,EAAK,KACX,aAAcA,EAAK,aAEV,UACT,MAAOf,EAAM,MACb,SAAU,GAAGR,EAAS,GAAG,KAAM,YAC/B,kBACCK,EAAU,GACTqB,EAAS,QAAUD,GAAgBC,EAAS,WAAa1B,EACtD2B,EAAeD,CAAQ,EACvBA,CACJ,CACF,CACD"}
package/dist/react.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { DeclaredFailure, DecodedFailure, ErrorContract, UnknownFailure, queryErrors } from "./modules/contracts/errors.mjs";
2
- import { FailureHandlers, decodeFailure, matchFailure } from "./react/failures.mjs";
1
+ import { DeclaredFailure, DecodedFailure, ErrorContract, UnknownFailure, combineErrorContracts, decodeFailure, queryErrors } from "./modules/contracts/errors.mjs";
2
+ import { FailureHandlers, failureOf, isFailure, matchFailure } from "./react/failures.mjs";
3
3
  import { Command, CommandResult, useCommand } from "./react/use-command.mjs";
4
4
  import { ListQueryReference, PaginatedList, PaginatedListOptions, usePaginatedList } from "./react/use-paginated-list.mjs";
5
5
  import { OptimisticInterval, OptimisticList, OptimisticListDescriptor, OptimisticOrder, defineOptimisticList } from "./react/optimistic.mjs";
6
- export { type Command, type CommandResult, type DeclaredFailure, type DecodedFailure, type ErrorContract, type FailureHandlers, type ListQueryReference, type OptimisticInterval, type OptimisticList, type OptimisticListDescriptor, type OptimisticOrder, type PaginatedList, type PaginatedListOptions, type UnknownFailure, decodeFailure, defineOptimisticList, matchFailure, queryErrors, useCommand, usePaginatedList };
6
+ export { type Command, type CommandResult, type DeclaredFailure, type DecodedFailure, type ErrorContract, type FailureHandlers, type ListQueryReference, type OptimisticInterval, type OptimisticList, type OptimisticListDescriptor, type OptimisticOrder, type PaginatedList, type PaginatedListOptions, type UnknownFailure, combineErrorContracts, decodeFailure, defineOptimisticList, failureOf, isFailure, matchFailure, queryErrors, useCommand, usePaginatedList };
package/dist/react.mjs CHANGED
@@ -1 +1 @@
1
- import{queryErrors as e}from"./modules/contracts/errors.mjs";import{decodeFailure as t,matchFailure as n}from"./react/failures.mjs";import{useCommand as r}from"./react/use-command.mjs";import{usePaginatedList as i}from"./react/use-paginated-list.mjs";import{defineOptimisticList as a}from"./react/optimistic.mjs";export{t as decodeFailure,a as defineOptimisticList,n as matchFailure,e as queryErrors,r as useCommand,i as usePaginatedList};
1
+ import{combineErrorContracts as e,decodeFailure as t,queryErrors as n}from"./modules/contracts/errors.mjs";import{failureOf as r,isFailure as i,matchFailure as a}from"./react/failures.mjs";import{useCommand as o}from"./react/use-command.mjs";import{usePaginatedList as s}from"./react/use-paginated-list.mjs";import{defineOptimisticList as c}from"./react/optimistic.mjs";export{e as combineErrorContracts,t as decodeFailure,c as defineOptimisticList,r as failureOf,i as isFailure,a as matchFailure,n as queryErrors,o as useCommand,s as usePaginatedList};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cvx-kit",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "description": "Reusable Convex application kit: foundation kernels, approvals component, zod table boundaries, WorkOS-backed auth function constructors, and audited command protocol.",
5
5
  "keywords": [
6
6
  "component",