@btps/sdk 1.1.2 → 1.1.3

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/CHANGELOG.md CHANGED
@@ -4,6 +4,58 @@ All notable changes to `@btps/sdk` and the BTPS protocol it implements. The
4
4
  format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
5
5
  versions follow [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.1.3] — 2026-10-30 (alpha)
8
+
9
+ A patch release. Every document a compliant sender sent before is still
10
+ valid; what is new only adds.
11
+
12
+ ### Security
13
+
14
+ - **A crafted document can no longer exhaust a receiver's memory**
15
+ (GHSA-mrhx-c7xc-m3w5, in zod 3). zod makes one issue for every invalid
16
+ entry of a list, with no cap, and keeps reading after a `.max()` fails: one
17
+ 5 MB document cost 2 GB to check. Every list and record in a document now
18
+ has a protocol limit, far above any real document, and is checked before
19
+ zod reads inside it. Over its limit, a list is refused with one issue; a
20
+ list of more than 100 entries stops at its first invalid entry. Both crafted
21
+ documents now cost one issue and under a megabyte. The limits are on the
22
+ [Limits](https://www.openbtps.org/docs/protocol/specifications/limits) page and
23
+ in `BTPS_FIELD_LIMITS`.
24
+ - **`generateUserToken` draws every character from a secure random source**,
25
+ about 60 bits for a 12-character token, where it had about 32.
26
+
27
+ ### Added
28
+
29
+ - `encryptBtpPayload`, `decryptBtpPayload` and
30
+ `decryptBtpPayloadWithDecrypter` take an optional document type. Given one,
31
+ they check the document against it, limits included. Without one they
32
+ behave as before.
33
+ - `BtpsAgent.command` takes `options.id`, a UUID: the artifact is sent under
34
+ it, so a document sent again after a lost answer keeps its id. On
35
+ `event.send` it may only be the event's own id.
36
+ - `trust.fetch` may answer with trust records (`BTPTrustRecord`), which now
37
+ have a schema, as well as with the requests' `TRUST_REQ` artifacts.
38
+ - `BTP_ERROR_TEMPORARILY_UNAVAILABLE` (503), for a trust or identity store to
39
+ throw when it is briefly unreachable, so a sender sends again later.
40
+
41
+ ### Fixed
42
+
43
+ - **An error on one artifact no longer ends its connection**, and every other
44
+ artifact in flight on it. The server answers that artifact's error and
45
+ keeps the connection; only framing, socket, size and timeout failures end
46
+ it.
47
+ - **Each artifact on a connection is attributed to its own sender.**
48
+ `getIdentity()` returned the first artifact's sender for every later one,
49
+ in middleware, rate limits and logs.
50
+ - **An identity lookup whose store throws is answered with an error**, where
51
+ it was left unanswered as an unhandled rejection.
52
+ - **A client keeps an identity lookup's answer when the host closes the
53
+ connection first**, as it does right after answering. The lookup failed
54
+ with `BTP_ERROR_CONNECTION_CLOSED` whenever the close arrived while the
55
+ answer was being verified.
56
+ - **A `BtpsTransporter`'s idle connections no longer keep a process alive**
57
+ for up to five minutes after its work is done.
58
+
7
59
  ## [1.1.2] — 2026-10-19 (alpha)
8
60
 
9
61
  A patch release: the protocol and the API are unchanged.
@@ -190,6 +242,7 @@ of an exchange must upgrade together.
190
242
  - The default middleware counts an identity's rate limit after signature
191
243
  verification. Rate limiting is off unless a provider enables it.
192
244
 
245
+ [1.1.3]: https://github.com/openbtps/btps-node/releases/tag/v1.1.3
193
246
  [1.1.2]: https://github.com/openbtps/btps-node/releases/tag/v1.1.2
194
247
  [1.1.1]: https://github.com/openbtps/btps-node/releases/tag/v1.1.1
195
248
  [1.1.0]: https://github.com/openbtps/btps-node/releases/tag/v1.1.0
@@ -120,7 +120,7 @@ class BtpsAgent extends BtpsClient {
120
120
  })
121
121
  );
122
122
  const transporterArtifact = {
123
- id: event?.success ? event.data.id : randomUUID(),
123
+ id: event?.success ? event.data.id : options?.id ?? randomUUID(),
124
124
  issuedAt: ( new Date()).toISOString(),
125
125
  version: this.getProtocolVersion(),
126
126
  type: artifactType,
@@ -501,16 +501,23 @@ class BtpsClient {
501
501
  };
502
502
  socket.write(JSON.stringify(identityLookupRequest) + `
503
503
  `);
504
- let received = "";
504
+ let received = "", answerRead = !1;
505
505
  socket.on("data", async (chunk) => {
506
506
  received += chunk.toString();
507
507
  const end = received.indexOf(`
508
508
  `);
509
- if (end === -1) return;
510
- socket.removeAllListeners("data");
509
+ if (end !== -1) {
510
+ socket.removeAllListeners("data"), answerRead = !0;
511
+ try {
512
+ await verifyAnswer(received.slice(0, end));
513
+ } catch (error) {
514
+ fail(transformToBTPErrorException(error));
515
+ }
516
+ }
517
+ });
518
+ const verifyAnswer = async (line) => {
511
519
  let msg;
512
520
  try {
513
- const line = received.slice(0, end);
514
521
  assertStrictJson(line), msg = JSON.parse(line);
515
522
  } catch (error) {
516
523
  fail(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: error }));
@@ -581,10 +588,14 @@ class BtpsClient {
581
588
  },
582
589
  error: void 0
583
590
  });
584
- }), socket.on("error", (err) => fail(transformToBTPErrorException(err))), socket.on(
585
- "close",
586
- () => fail(new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "connection closed" }))
587
- );
591
+ };
592
+ socket.on("error", (err) => {
593
+ answerRead || fail(transformToBTPErrorException(err));
594
+ }), socket.on("close", () => {
595
+ answerRead || fail(
596
+ new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "connection closed" })
597
+ );
598
+ });
588
599
  }) : await this.buildClientErrorResponse(
589
600
  new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
590
601
  cause: `${identity} has no key in DNS, and its domain declares no operator to answer for it`
@@ -125,7 +125,7 @@ class BtpsTransporter {
125
125
  });
126
126
  }
127
127
  createConnectionTimeout(connectionId, ttlSeconds) {
128
- return setTimeout(
128
+ const timeout = setTimeout(
129
129
  () => {
130
130
  const connection = this.connections.get(connectionId);
131
131
  if (connection && connection.inFlight > 0) {
@@ -136,6 +136,7 @@ class BtpsTransporter {
136
136
  },
137
137
  (ttlSeconds ?? this.connectionTTLSeconds) * 1e3
138
138
  );
139
+ return timeout.unref(), timeout;
139
140
  }
140
141
  touch(connection) {
141
142
  clearTimeout(connection.timeout), connection.timeout = this.createConnectionTimeout(connection.id, connection.ttlSeconds), connection.lastUsedAt = ( new Date()).toISOString();
@@ -37,17 +37,29 @@ const BtpsAgentOptionsSchema = BtpCryptoOptionsSchema.optional(), BtpsAgentComma
37
37
  actionType: BtpsAgentActionTypeSchema,
38
38
  to: identitySchema,
39
39
  document: BtpsAgentCommandDocumentSchema.optional(),
40
- options: BtpCryptoOptionsSchema.extend({ relatesTo: z.string().min(1).optional() }).optional()
40
+ options: BtpCryptoOptionsSchema.extend({
41
+ relatesTo: z.string().min(1).optional(),
42
+ id: z.string().uuid().optional()
43
+ }).optional()
41
44
  }), BtpsAgentCommandCallSchema = BtpsAgentCommandSchema.refine(
42
45
  (data) => validateAgentDocument(data.actionType, null, data.document),
43
46
  {
44
47
  message: "Document is required for this action type or document format is invalid",
45
48
  path: ["document"]
46
49
  }
47
- ).refine((data) => data.actionType === "event.send" == (data.options?.relatesTo !== void 0), {
48
- message: "options.relatesTo is required on event.send and only there",
49
- path: ["options", "relatesTo"]
50
- });
50
+ ).refine(
51
+ (data) => data.actionType === "event.send" == (data.options?.relatesTo !== void 0),
52
+ {
53
+ message: "options.relatesTo is required on event.send and only there",
54
+ path: ["options", "relatesTo"]
55
+ }
56
+ ).refine(
57
+ (data) => data.actionType !== "event.send" || data.options?.id === void 0 || data.options.id === data.document?.id,
58
+ {
59
+ message: "an event travels under its own id: options.id may only be that id",
60
+ path: ["options", "id"]
61
+ }
62
+ );
51
63
  export {
52
64
  BtpsAgentCommandCallSchema,
53
65
  BtpsAgentCommandDocumentSchema,
@@ -56,6 +56,12 @@ export type BtpsAgentDoc = BTPDocType | BTPAuthReqDoc | BTPAgentMutation | BTPId
56
56
  export type BtpsAgentCommandOptions = BTPCryptoOptions & {
57
57
  /** Required on `event.send`, refused elsewhere: the id of the `BTPS_DOC` artifact that delivered the invoice. */
58
58
  relatesTo?: string;
59
+ /**
60
+ * The id of the artifact the command sends, a UUID. Sending the same document again after a lost answer under
61
+ * the same id lets the receiver keep it once. Without it, a new id. An event always travels under its own id, so
62
+ * on `event.send` it may only be that id.
63
+ */
64
+ id?: string;
59
65
  };
60
66
  export type BtpsAgentCommandParams = {
61
67
  actionType: AgentAction;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { BTPCryptoOptions, BTPEncryption, BTPSignature, PemKeys } from './types.js';
8
8
  import { BTPErrorException } from '../error/index.js';
9
+ import type { BTPArtifactType } from '../server/types.js';
9
10
  import type { Signer } from './signer-interface.js';
10
11
  import type { Decrypter } from './decrypter-interface.js';
11
12
  export * from './decryptVerify.js';
@@ -17,7 +18,13 @@ export * from './signer-interface.js';
17
18
  export * from './decrypter-interface.js';
18
19
  export * from './pem-signer.js';
19
20
  export * from './pem-decrypter.js';
20
- export declare const encryptBtpPayload: (payload: unknown | undefined, receiverPubPem: string, options?: BTPCryptoOptions["encryption"]) => {
21
+ /**
22
+ * Encrypts a document to the receiver's key. Given `documentType`, the
23
+ * document is checked against that type first, and an invalid one throws
24
+ * `BTP_ERROR_VALIDATION`. Without it, nothing is checked: a direct caller
25
+ * validates the document itself. `signEncrypt` and the clients always do.
26
+ */
27
+ export declare const encryptBtpPayload: (payload: unknown | undefined, receiverPubPem: string, options?: BTPCryptoOptions["encryption"], documentType?: BTPArtifactType) => {
21
28
  data: string;
22
29
  encryption: {
23
30
  algorithm: "aes-256-gcm";
@@ -27,7 +34,13 @@ export declare const encryptBtpPayload: (payload: unknown | undefined, receiverP
27
34
  type: import("./types.js").EncryptionMode;
28
35
  };
29
36
  };
30
- export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, receiverPrivPem: string) => {
37
+ /**
38
+ * Decrypts a document with the receiver's key. Given `documentType`, the
39
+ * decrypted document is checked against that type, and an invalid one is
40
+ * returned as a `BTP_ERROR_VALIDATION` error. Without it, nothing is checked:
41
+ * a direct caller validates the document itself. `decryptVerify` always does.
42
+ */
43
+ export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, receiverPrivPem: string, documentType?: BTPArtifactType) => {
31
44
  data?: T;
32
45
  error?: BTPErrorException;
33
46
  };
@@ -35,7 +48,7 @@ export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefin
35
48
  * Decrypts like `decryptBtpPayload`, through a Decrypter that holds the
36
49
  * receiver's private key elsewhere (a KMS, a device) instead of a PEM key.
37
50
  */
38
- export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter) => Promise<{
51
+ export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter, documentType?: BTPArtifactType) => Promise<{
39
52
  data?: T;
40
53
  error?: BTPErrorException;
41
54
  }>;
@@ -5,16 +5,17 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
 
8
- import crypto, { constants, createHash, randomBytes } from "crypto";
9
- import { performance } from "perf_hooks";
8
+ import crypto, { constants } from "crypto";
10
9
  import {
11
10
  BTP_ERROR_UNSUPPORTED_ENCRYPT,
12
11
  BTP_ERROR_DECRYPTION_UNINTENDED,
13
12
  BTP_ERROR_SIG_MISMATCH,
14
13
  BTP_ERROR_SIG_VERIFICATION,
15
- BTP_ERROR_UNKNOWN
14
+ BTP_ERROR_UNKNOWN,
15
+ BTP_ERROR_VALIDATION
16
16
  } from "../error/constant.js";
17
17
  import { BTPErrorException } from "../error/index.js";
18
+ import { processBtpDocSchema } from "../server/schemas/helpers.js";
18
19
  import { assertStrictJson, canonicalize, canonicalizeValue } from "./jcs.js";
19
20
  import { assertFullLengthAuthTag } from "./pem-decrypter.js";
20
21
  export * from "./decryptVerify.js";
@@ -26,10 +27,20 @@ export * from "./signer-interface.js";
26
27
  export * from "./decrypter-interface.js";
27
28
  export * from "./pem-signer.js";
28
29
  export * from "./pem-decrypter.js";
29
- const encryptBtpPayload = (payload = "", receiverPubPem, options = {
30
+ const documentTypeError = (document, documentType) => {
31
+ if (!documentType) return;
32
+ const parsed = processBtpDocSchema(documentType)?.safeParse(document);
33
+ if (!(!parsed || parsed.success))
34
+ return new BTPErrorException(BTP_ERROR_VALIDATION, {
35
+ cause: `Document is not a valid ${documentType} document`,
36
+ meta: { issues: parsed.error.issues }
37
+ });
38
+ }, encryptBtpPayload = (payload = "", receiverPubPem, options = {
30
39
  algorithm: "aes-256-gcm",
31
40
  mode: "standardEncrypt"
32
- }) => {
41
+ }, documentType) => {
42
+ const invalid = documentTypeError(payload, documentType);
43
+ if (invalid) throw invalid;
33
44
  const aesKey = crypto.randomBytes(32), iv = crypto.randomBytes(12), algorithm = options.algorithm, stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload, cipher = crypto.createCipheriv(algorithm, aesKey, iv);
34
45
  let encryptedPayload = cipher.update(stringifiedPayload, "utf8", "base64");
35
46
  encryptedPayload += cipher.final("base64");
@@ -44,7 +55,7 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
44
55
  type: options.mode
45
56
  }
46
57
  };
47
- }, decryptBtpPayload = (payload = "", encryption, receiverPrivPem) => {
58
+ }, decryptBtpPayload = (payload = "", encryption, receiverPrivPem, documentType) => {
48
59
  if (encryption.algorithm !== "aes-256-gcm")
49
60
  return {
50
61
  data: void 0,
@@ -65,14 +76,13 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
65
76
  decipher.setAuthTag(authTag);
66
77
  const stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload;
67
78
  let decryptedPayload = decipher.update(stringifiedPayload, "base64", "utf8");
68
- return decryptedPayload += decipher.final("utf8"), assertStrictJson(decryptedPayload), {
69
- data: JSON.parse(decryptedPayload),
70
- error: void 0
71
- };
79
+ decryptedPayload += decipher.final("utf8"), assertStrictJson(decryptedPayload);
80
+ const data = JSON.parse(decryptedPayload), invalid = documentTypeError(data, documentType);
81
+ return invalid ? { data: void 0, error: invalid } : { data, error: void 0 };
72
82
  } catch (err) {
73
83
  return { data: void 0, error: decryptionError(err) };
74
84
  }
75
- }, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter) => {
85
+ }, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter, documentType) => {
76
86
  if (encryption.algorithm !== "aes-256-gcm")
77
87
  return {
78
88
  data: void 0,
@@ -85,10 +95,9 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
85
95
  ciphertext: Buffer.from(stringifiedPayload, "base64"),
86
96
  authTag: Buffer.from(encryption.authTag, "base64")
87
97
  }), decryptedPayload = Buffer.from(plaintext).toString("utf8");
88
- return assertStrictJson(decryptedPayload), {
89
- data: JSON.parse(decryptedPayload),
90
- error: void 0
91
- };
98
+ assertStrictJson(decryptedPayload);
99
+ const data = JSON.parse(decryptedPayload), invalid = documentTypeError(data, documentType);
100
+ return invalid ? { data: void 0, error: invalid } : { data, error: void 0 };
92
101
  } catch (err) {
93
102
  return { data: void 0, error: decryptionError(err) };
94
103
  }
@@ -189,10 +198,9 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
189
198
  function generateUserToken(userIdentity, length = 12, charactersFrom = DEFAULT_ALPHABET) {
190
199
  if (length < 8 || length > 24)
191
200
  throw new BTPErrorException({ message: "Token length must be between 8 and 24 characters." });
192
- const entropyInput = userIdentity + performance.now().toString() + randomBytes(4).toString("hex"), hash = createHash("sha256");
193
- hash.update(entropyInput);
194
- const digest = hash.digest(), sliced = new Uint8Array(digest).slice(0, length);
195
- return Array.from(sliced).map((byte) => charactersFrom[byte % charactersFrom.length]).join("").toUpperCase();
201
+ let token = "";
202
+ for (let i = 0; i < length; i++) token += charactersFrom[crypto.randomInt(charactersFrom.length)];
203
+ return token.toUpperCase();
196
204
  }
197
205
  export {
198
206
  DEFAULT_ALPHABET,
@@ -59,6 +59,8 @@ export declare const BTP_ERROR_ARTIFACT_TOO_LARGE: BTPError;
59
59
  export declare const BTP_ERROR_VERSION_UNSUPPORTED: BTPError;
60
60
  export declare const BTP_ERROR_PRIVACY_TYPE: BTPError;
61
61
  export declare const BTP_ERROR_ARTIFACT_NOT_ACCEPTED: BTPError;
62
+ /** For a store (trust, identity) to throw when it is briefly unreachable: the sender may send again later. */
63
+ export declare const BTP_ERROR_TEMPORARILY_UNAVAILABLE: BTPError;
62
64
  export declare const BTP_ERROR_SOCKET_TIMEOUT: BTPError;
63
65
  export declare const BTP_ERROR_AUTHENTICATION_INVALID: BTPError;
64
66
  export declare const BTP_ERROR_TIMEOUT: BTPError;
@@ -134,6 +134,10 @@ const BTP_ERROR_SOCKET_CLOSED = {
134
134
  code: "BTP_ERROR_ARTIFACT_NOT_ACCEPTED",
135
135
  message: "This server does not accept this kind of artifact",
136
136
  status: 503
137
+ }, BTP_ERROR_TEMPORARILY_UNAVAILABLE = {
138
+ code: "BTP_ERROR_TEMPORARILY_UNAVAILABLE",
139
+ message: "The server cannot take this artifact right now. Send it again later",
140
+ status: 503
137
141
  }, BTP_ERROR_SOCKET_TIMEOUT = {
138
142
  code: "BTP_ERROR_SOCKET_TIMEOUT",
139
143
  message: "Socket timeout. Connection closed",
@@ -180,6 +184,7 @@ export {
180
184
  BTP_ERROR_SIG_VERIFICATION,
181
185
  BTP_ERROR_SOCKET_CLOSED,
182
186
  BTP_ERROR_SOCKET_TIMEOUT,
187
+ BTP_ERROR_TEMPORARILY_UNAVAILABLE,
183
188
  BTP_ERROR_TIMEOUT,
184
189
  BTP_ERROR_TRUST_ALREADY_ACTIVE,
185
190
  BTP_ERROR_TRUST_BLOCKED,
@@ -5,7 +5,8 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  /**
8
- * The longest each field may be, in characters. The protocol fixes these,
8
+ * The longest each field may be: a text in characters, a list in entries, a
9
+ * record in keys. The protocol fixes these,
9
10
  * so every provider accepts the same documents: a provider may be stricter
10
11
  * in its own middleware, but cannot raise them. They are raised only by a
11
12
  * protocol version.
@@ -38,6 +39,10 @@ export declare const BTPS_FIELD_LIMITS: {
38
39
  };
39
40
  readonly payslip: {
40
41
  readonly code: 64;
42
+ readonly earnings: 200;
43
+ readonly deductions: 200;
44
+ readonly contributions: 200;
45
+ readonly leave: 200;
41
46
  };
42
47
  readonly letter: {
43
48
  readonly title: 200;
@@ -45,6 +50,23 @@ export declare const BTPS_FIELD_LIMITS: {
45
50
  readonly attachments: 10;
46
51
  readonly references: 20;
47
52
  };
53
+ readonly attachments: 10;
54
+ readonly references: 20;
55
+ readonly lineItems: {
56
+ readonly rows: 10000;
57
+ readonly columns: 50;
58
+ };
59
+ readonly query: {
60
+ readonly in: 1000;
61
+ readonly notIn: 1000;
62
+ readonly results: 1000;
63
+ };
64
+ readonly ids: 1000;
65
+ readonly agentInfoValues: 50;
66
+ readonly trustRecord: {
67
+ readonly keyHistory: 1000;
68
+ };
69
+ readonly recordKeys: 100;
48
70
  readonly documentId: 100;
49
71
  readonly referenceType: 64;
50
72
  };
@@ -33,7 +33,11 @@ const BTPS_FIELD_LIMITS = {
33
33
  },
34
34
  payslip: {
35
35
 
36
- code: 64
36
+ code: 64,
37
+ earnings: 200,
38
+ deductions: 200,
39
+ contributions: 200,
40
+ leave: 200
37
41
  },
38
42
  letter: {
39
43
  title: 200,
@@ -42,6 +46,27 @@ const BTPS_FIELD_LIMITS = {
42
46
  references: 20
43
47
  },
44
48
 
49
+ attachments: 10,
50
+ references: 20,
51
+
52
+ lineItems: {
53
+ rows: 1e4,
54
+ columns: 50
55
+ },
56
+ query: {
57
+ in: 1e3,
58
+ notIn: 1e3,
59
+ results: 1e3
60
+ },
61
+
62
+ ids: 1e3,
63
+ agentInfoValues: 50,
64
+ trustRecord: {
65
+ keyHistory: 1e3
66
+ },
67
+
68
+ recordKeys: 100,
69
+
45
70
  documentId: 100,
46
71
  referenceType: 64
47
72
  };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { z } from "zod";
9
+ const PRECHECK_THRESHOLD = 100, tooMany = (ctx, max, unit) => ctx.addIssue({
10
+ code: z.ZodIssueCode.custom,
11
+ message: `must have at most ${max} ${unit}`,
12
+ params: { maximum: max },
13
+ fatal: !0
14
+ }), boundedArray = (element, max) => z.preprocess((value, ctx) => {
15
+ if (!Array.isArray(value)) return value;
16
+ if (value.length > max)
17
+ return tooMany(ctx, max, "entries"), value;
18
+ if (value.length <= PRECHECK_THRESHOLD) return value;
19
+ for (let i = 0; i < value.length; i++) {
20
+ const result = element.safeParse(value[i]);
21
+ if (!result.success) {
22
+ const [issue] = result.error.issues;
23
+ ctx.addIssue({
24
+ code: z.ZodIssueCode.custom,
25
+ path: [i, ...issue?.path ?? []],
26
+ message: issue?.message ?? "Invalid",
27
+ fatal: !0
28
+ });
29
+ break;
30
+ }
31
+ }
32
+ return value;
33
+ }, z.array(element)), boundedRecord = (valueSchema, max, keySchema = z.string()) => z.preprocess(
34
+ (value, ctx) => (typeof value != "object" || value === null || Array.isArray(value) || Object.keys(value).length > max && tooMany(ctx, max, "keys"), value),
35
+ z.record(keySchema, valueSchema)
36
+ );
37
+ export {
38
+ PRECHECK_THRESHOLD,
39
+ boundedArray,
40
+ boundedRecord
41
+ };