@b2y/ai-service 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,243 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { AiServiceError, ErrorCodes, summarizeZodError } from "./Errors.js";
4
+ import { MAX_GRANTS } from "../constants/AssistantConstants.js";
5
+ import { DATA_CLASSIFICATION } from "../enums/DataClassification.js";
6
+ export { AI_ASSISTANT_PERMISSION, MAX_GRANTS } from "../constants/AssistantConstants.js";
7
+
8
+ const DATA_CLASSIFICATIONS = Object.freeze(Object.values(DATA_CLASSIFICATION));
9
+
10
+ /** Dotted lowercase identifiers such as "ticket.summary". */
11
+ export const taskIdSchema = z
12
+ .string()
13
+ .max(100)
14
+ .regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/);
15
+
16
+ export const dataClassificationSchema = z.enum(DATA_CLASSIFICATIONS);
17
+
18
+ export function classificationRank(classification) {
19
+ return DATA_CLASSIFICATIONS.indexOf(classification);
20
+ }
21
+
22
+ /**
23
+ * Roles and permissions are global across B2Y applications: a role grants named permissions, optionally
24
+ * grouped by module ("Order Management" / "Generate Order Report"), or codes ("VIEW_USERS"); a plan enables
25
+ * features ("ACCESS_ORDER").
26
+ */
27
+ export const grantNameSchema = z.string().regex(/^[a-z0-9_]{1,80}(:[a-z0-9_]{1,80})?$/);
28
+
29
+ const namePart = (value) =>
30
+ String(value ?? "")
31
+ .trim()
32
+ .toLowerCase()
33
+ .replace(/[^a-z0-9]+/g, "_")
34
+ .replace(/^_+|_+$/g, "");
35
+
36
+ /**
37
+ * The normalized key of a permission or feature: "Module:Name", a code, or a role row such as
38
+ * { Module, Name } / { module, name } / { code }. Returns null for anything without a name.
39
+ * @param {string | { module?: string, Module?: string, name?: string, Name?: string, code?: string, Code?: string }} value
40
+ */
41
+ export function permissionKey(value) {
42
+ let module;
43
+ let name;
44
+ if (typeof value === "string") {
45
+ const colon = value.indexOf(":");
46
+ [module, name] = colon >= 0 ? [value.slice(0, colon), value.slice(colon + 1)] : [undefined, value];
47
+ } else if (value && typeof value === "object") {
48
+ module = value.module ?? value.Module;
49
+ name = value.name ?? value.Name ?? value.code ?? value.Code;
50
+ } else {
51
+ return null;
52
+ }
53
+ const key = namePart(name);
54
+ if (!key) return null;
55
+ const group = module === undefined || module === null ? "" : namePart(module);
56
+ return group ? `${group}:${key}` : key;
57
+ }
58
+
59
+ /** Normalized, de-duplicated keys of a role's permissions (rows or names), ready for context.permissions. */
60
+ export function rolePermissions(values) {
61
+ return [...new Set((Array.isArray(values) ? values : []).map(permissionKey).filter(Boolean))];
62
+ }
63
+
64
+ const nameOf = (key) => key.slice(key.indexOf(":") + 1);
65
+ const moduleOf = (key) => (key.includes(":") ? key.slice(0, key.indexOf(":")) : null);
66
+
67
+ /** A granted key satisfies a required key with the same name; modules must match only when both have one. */
68
+ function grants(granted, required) {
69
+ return granted.some((key) => key === required || (nameOf(key) === nameOf(required) && (moduleOf(key) === null || moduleOf(required) === null)));
70
+ }
71
+
72
+ const referenceSchema = z
73
+ .string()
74
+ .min(1)
75
+ .max(128)
76
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:@-]*$/);
77
+
78
+ /** Identity and authorization facts about one AI request: the application context contract. */
79
+ export const trustedContextSchema = z.strictObject({
80
+ applicationId: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/),
81
+ tenantId: referenceSchema,
82
+ actor: z.strictObject({
83
+ userId: referenceSchema,
84
+ }),
85
+ requestId: referenceSchema,
86
+ permittedTasks: z.array(taskIdSchema).max(100).readonly(),
87
+ dataClassification: dataClassificationSchema,
88
+ permissions: z.array(grantNameSchema).max(MAX_GRANTS).readonly().optional(),
89
+ features: z.array(grantNameSchema).max(MAX_GRANTS).readonly().optional(),
90
+ metadata: z
91
+ .strictObject({
92
+ locale: z
93
+ .string()
94
+ .regex(/^[a-z]{2,3}(-[A-Z]{2})?$/)
95
+ .optional(),
96
+ channel: z
97
+ .string()
98
+ .regex(/^[a-z][a-z0-9-]{0,31}$/)
99
+ .optional(),
100
+ })
101
+ .optional(),
102
+ });
103
+
104
+ /** Validates the context and returns a deep-frozen copy. */
105
+ export function parseTrustedContext(value) {
106
+ // Role permissions and plan features arrive as the application stores them; normalize before checking.
107
+ const normalized =
108
+ value && typeof value === "object"
109
+ ? {
110
+ ...value,
111
+ ...(Array.isArray(value.permissions) ? { permissions: value.permissions.map((item) => permissionKey(item) ?? item) } : {}),
112
+ ...(Array.isArray(value.features) ? { features: value.features.map((item) => permissionKey(item) ?? item) } : {}),
113
+ }
114
+ : value;
115
+ const result = trustedContextSchema.safeParse(normalized);
116
+ if (!result.success) {
117
+ throw new AiServiceError(ErrorCodes.CONTEXT_INVALID, "Trusted context is invalid", {
118
+ details: summarizeZodError(result.error, trustedContextSchema),
119
+ });
120
+ }
121
+ const { actor, permittedTasks, permissions, features, metadata, ...rest } = result.data;
122
+ return Object.freeze({
123
+ ...rest,
124
+ actor: Object.freeze({ ...actor }),
125
+ permittedTasks: Object.freeze([...permittedTasks]),
126
+ ...(permissions === undefined ? {} : { permissions: Object.freeze([...new Set(permissions)]) }),
127
+ ...(features === undefined ? {} : { features: Object.freeze([...new Set(features)]) }),
128
+ ...(metadata === undefined ? {} : { metadata: Object.freeze({ ...metadata }) }),
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Access is decided from the trusted context: the role's permissions and the tenant's plan features, both
134
+ * supplied by the application from its own session. The model never grants anything. A context without
135
+ * `permissions` or `features` grants none.
136
+ *
137
+ * A requirement lists what is needed: `permission` and `feature` each take one name or a list meaning
138
+ * "any of these". Both must be met when both are given.
139
+ * @typedef {{ permission?: string | string[], feature?: string | string[] }} Requirement
140
+ */
141
+
142
+ const asList = (value) => (value === undefined ? [] : Array.isArray(value) ? value : [value]);
143
+
144
+ /** Validates and normalizes a requirement at setup time, so a typo fails at startup rather than per request. */
145
+ export function checkRequirement(requirement, where) {
146
+ if (requirement === undefined) return Object.freeze({});
147
+ const { permission, feature, ...rest } = requirement ?? {};
148
+ const permissions = asList(permission).map(permissionKey);
149
+ const features = asList(feature).map(permissionKey);
150
+ const invalid =
151
+ typeof requirement !== "object" ||
152
+ requirement === null ||
153
+ Object.keys(rest).length > 0 ||
154
+ [...permissions, ...features].some((key) => key === null || !grantNameSchema.safeParse(key).success) ||
155
+ (permission !== undefined && permissions.length === 0) ||
156
+ (feature !== undefined && features.length === 0);
157
+ if (invalid) throw new AiServiceError(ErrorCodes.CONFIG_INVALID, `${where}: a requirement is { permission?, feature? }, each a name or a list of names`);
158
+ return Object.freeze({
159
+ ...(permissions.length ? { permission: Object.freeze(permissions) } : {}),
160
+ ...(features.length ? { feature: Object.freeze(features) } : {}),
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Whether a parsed context meets a checked requirement, and if not, what is missing ("permission" is
166
+ * reported before "feature").
167
+ * @returns {{ ok: boolean, missing: "permission" | "feature" | null }}
168
+ */
169
+ export function meetsRequirement(context, requirement) {
170
+ const permitted = !requirement.permission || requirement.permission.some((key) => grants(context.permissions ?? [], key));
171
+ if (!permitted) return { ok: false, missing: "permission" };
172
+ const enabled = !requirement.feature || requirement.feature.some((key) => grants(context.features ?? [], key));
173
+ return enabled ? { ok: true, missing: null } : { ok: false, missing: "feature" };
174
+ }
175
+
176
+ /** Whether the context's role grants this permission (any of a list). */
177
+ export function hasPermission(context, permission) {
178
+ return meetsRequirement(parseTrustedContext(context), checkRequirement({ permission }, "hasPermission")).ok;
179
+ }
180
+
181
+ /** Whether the tenant's plan enables this feature (any of a list). */
182
+ export function hasFeature(context, feature) {
183
+ return meetsRequirement(parseTrustedContext(context), checkRequirement({ feature }, "hasFeature")).ok;
184
+ }
185
+
186
+ /**
187
+ * Throws NOT_AUTHORIZED or FEATURE_NOT_ENABLED unless the context meets the requirement. Returns the
188
+ * parsed, frozen context. Error details name the requirement, never the context's other grants.
189
+ * @param {TrustedContextInput} context
190
+ * @param {Requirement} requirement
191
+ */
192
+ export function assertAuthorized(context, requirement = {}) {
193
+ const parsed = parseTrustedContext(context);
194
+ const checked = checkRequirement(requirement, "assertAuthorized");
195
+ const { missing } = meetsRequirement(parsed, checked);
196
+ if (missing === "permission") {
197
+ throw new AiServiceError(ErrorCodes.NOT_AUTHORIZED, "The request is not authorized for this operation", { details: { permission: checked.permission.join("|").slice(0, 200) } });
198
+ }
199
+ if (missing === "feature") {
200
+ throw new AiServiceError(ErrorCodes.FEATURE_NOT_ENABLED, "This feature is not enabled for the tenant", { details: { feature: checked.feature.join("|").slice(0, 200) } });
201
+ }
202
+ return parsed;
203
+ }
204
+
205
+ /**
206
+ * The global tenant rule: the tenant the request arrived for (resolved from its domain) must be present and be
207
+ * the tenant of the signed-in session (token). Returns the verified tenant id; throws TENANT_MISMATCH.
208
+ * @param {{ requestTenantId: unknown, sessionTenantId: unknown }} tenants
209
+ */
210
+ export function resolveTenantId({ requestTenantId, sessionTenantId }) {
211
+ const present = (value) => value !== undefined && value !== null && String(value).trim() !== "";
212
+ if (!present(requestTenantId) || !present(sessionTenantId) || String(requestTenantId) !== String(sessionTenantId)) {
213
+ throw new AiServiceError(ErrorCodes.TENANT_MISMATCH, "The session does not belong to the tenant of this request");
214
+ }
215
+ return String(requestTenantId);
216
+ }
217
+
218
+ /**
219
+ * The trusted context for one request, built the same way in every application: the verified tenant (from
220
+ * the request and session tenants, or a fixed scope for applications without tenants), the signed-in user,
221
+ * the role's permissions and the plan's features as stored, and the tasks the assistant may run.
222
+ * @param {{ applicationId: string, requestTenantId?: unknown, sessionTenantId?: unknown, scope?: string, userId: unknown,
223
+ * permissions?: unknown[], features?: unknown[], tasks: readonly ({ id: string } | string)[], dataClassification?: string, requestId?: string }} options
224
+ */
225
+ export function buildTrustedContext({ applicationId, requestTenantId, sessionTenantId, scope, userId, permissions = [], features = [], tasks, dataClassification = DATA_CLASSIFICATION.INTERNAL, requestId = randomUUID() }) {
226
+ const tenantId = scope === undefined ? resolveTenantId({ requestTenantId, sessionTenantId }) : String(scope);
227
+ if (userId === undefined || userId === null || String(userId) === "") throw new AiServiceError(ErrorCodes.CONTEXT_INVALID, "A signed-in user is required");
228
+ return parseTrustedContext({
229
+ applicationId,
230
+ tenantId,
231
+ actor: { userId: String(userId) },
232
+ requestId,
233
+ permittedTasks: (tasks ?? []).map((task) => (typeof task === "string" ? task : task.id)),
234
+ dataClassification,
235
+ permissions: rolePermissions(permissions),
236
+ features: rolePermissions(features),
237
+ });
238
+ }
239
+
240
+ /** An authorization refusal decided by the application (for example an inactive user), handled like the package's own. */
241
+ export function accessDenied(reason) {
242
+ return new AiServiceError(ErrorCodes.NOT_AUTHORIZED, String(reason ?? "Access denied").slice(0, 200));
243
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A signal that aborts after ms, or as soon as parent aborts. Always call dispose() when the work ends:
3
+ * unlike AbortSignal.timeout with AbortSignal.any, nothing stays in memory afterwards.
4
+ */
5
+ export function createDeadline(ms, parent) {
6
+ const controller = new AbortController();
7
+ let expired = false;
8
+ const timer = setTimeout(() => {
9
+ expired = true;
10
+ controller.abort(new globalThis.DOMException("The operation timed out", "TimeoutError"));
11
+ }, ms);
12
+ const follow = () => controller.abort(parent.reason);
13
+ if (parent?.aborted) follow();
14
+ else parent?.addEventListener("abort", follow, { once: true });
15
+ return {
16
+ signal: controller.signal,
17
+ expired: () => expired,
18
+ abort: () => controller.abort(),
19
+ dispose: () => {
20
+ clearTimeout(timer);
21
+ parent?.removeEventListener("abort", follow);
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,248 @@
1
+ import { z } from "zod";
2
+ import { AI_BUSY_MESSAGE } from "../constants/ProviderConstants.js";
3
+
4
+ /** Every code an AiServiceError can carry. */
5
+ export const ErrorCodes = {
6
+ CONFIG_INVALID: "CONFIG_INVALID",
7
+ CONTEXT_INVALID: "CONTEXT_INVALID",
8
+ TASK_UNKNOWN: "TASK_UNKNOWN",
9
+ TASK_NOT_PERMITTED: "TASK_NOT_PERMITTED",
10
+ TENANT_MISMATCH: "TENANT_MISMATCH",
11
+ NOT_AUTHORIZED: "NOT_AUTHORIZED",
12
+ FEATURE_NOT_ENABLED: "FEATURE_NOT_ENABLED",
13
+ CLASSIFICATION_NOT_ALLOWED: "CLASSIFICATION_NOT_ALLOWED",
14
+ INPUT_INVALID: "INPUT_INVALID",
15
+ REQUEST_TOO_LARGE: "REQUEST_TOO_LARGE",
16
+ PROVIDER_TIMEOUT: "PROVIDER_TIMEOUT",
17
+ PROVIDER_UNAVAILABLE: "PROVIDER_UNAVAILABLE",
18
+ PROVIDER_HTTP_ERROR: "PROVIDER_HTTP_ERROR",
19
+ PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
20
+ PROVIDER_OUTPUT_REJECTED: "PROVIDER_OUTPUT_REJECTED",
21
+ PROVIDER_RESPONSE_INVALID: "PROVIDER_RESPONSE_INVALID",
22
+ CANCELLED: "CANCELLED",
23
+ OUTPUT_PARSE_FAILED: "OUTPUT_PARSE_FAILED",
24
+ OUTPUT_SCHEMA_INVALID: "OUTPUT_SCHEMA_INVALID",
25
+ OUTPUT_REJECTED: "OUTPUT_REJECTED",
26
+ DOCUMENT_SOURCE_INVALID: "DOCUMENT_SOURCE_INVALID",
27
+ DOCUMENT_SOURCE_FAILED: "DOCUMENT_SOURCE_FAILED",
28
+ CAPABILITY_FAILED: "CAPABILITY_FAILED",
29
+ CAPABILITY_TIMEOUT: "CAPABILITY_TIMEOUT",
30
+ USAGE_RECORDING_FAILED: "USAGE_RECORDING_FAILED",
31
+ INTERNAL_ERROR: "INTERNAL_ERROR",
32
+ };
33
+
34
+ /**
35
+ * What kind of failure a code is, so consumers can map errors to responses without listing codes:
36
+ * configuration the consumer's setup is invalid (fix the code or config; never retried) context the trusted
37
+ * context is malformed authorization the context does not permit this (task, permission, feature or data
38
+ * classification) validation the request or tool input is invalid provider the model provider failed or
39
+ * returned something unusable rate_limit the provider's rate limit was reached (retry later) output the
40
+ * model's output failed validation execution a consumer-supplied executor (tool, document source) failed or
41
+ * returned invalid data cancelled the caller cancelled internal a bug or an unexpected failure
42
+ */
43
+ export const ErrorCategories = Object.freeze({
44
+ CONFIG_INVALID: "configuration",
45
+ CONTEXT_INVALID: "context",
46
+ TASK_UNKNOWN: "configuration",
47
+ TASK_NOT_PERMITTED: "authorization",
48
+ TENANT_MISMATCH: "authorization",
49
+ NOT_AUTHORIZED: "authorization",
50
+ FEATURE_NOT_ENABLED: "authorization",
51
+ CLASSIFICATION_NOT_ALLOWED: "authorization",
52
+ INPUT_INVALID: "validation",
53
+ REQUEST_TOO_LARGE: "validation",
54
+ PROVIDER_TIMEOUT: "provider",
55
+ PROVIDER_UNAVAILABLE: "provider",
56
+ PROVIDER_HTTP_ERROR: "provider",
57
+ PROVIDER_RATE_LIMITED: "rate_limit",
58
+ PROVIDER_OUTPUT_REJECTED: "output",
59
+ PROVIDER_RESPONSE_INVALID: "provider",
60
+ CANCELLED: "cancelled",
61
+ OUTPUT_PARSE_FAILED: "output",
62
+ OUTPUT_SCHEMA_INVALID: "output",
63
+ OUTPUT_REJECTED: "output",
64
+ DOCUMENT_SOURCE_INVALID: "execution",
65
+ DOCUMENT_SOURCE_FAILED: "execution",
66
+ CAPABILITY_FAILED: "execution",
67
+ CAPABILITY_TIMEOUT: "execution",
68
+ USAGE_RECORDING_FAILED: "internal",
69
+ INTERNAL_ERROR: "internal",
70
+ });
71
+
72
+ /**
73
+ * @typedef {string | number | boolean} ErrorDetailValue
74
+ */
75
+
76
+ /**
77
+ * @typedef {Readonly<Record<string, ErrorDetailValue>>} ErrorDetails
78
+ */
79
+
80
+ /**
81
+ * @typedef {Object} AiServiceErrorOptions
82
+ * @property {boolean} [retryable]
83
+ * @property {ErrorDetails} [details]
84
+ * @property {unknown} [cause] - Underlying error. Only its type name and a well-formed error code are kept (see SafeErrorCause).
85
+ */
86
+
87
+ /**
88
+ * What remains of an underlying error. Raw errors are never retained because their messages can quote secrets or content: a header error quotes the header value, a JSON SyntaxError quotes the parsed text, and errors thrown by application hooks can contain anything.
89
+ * @typedef {Object} SafeErrorCause
90
+ * @property {string} name
91
+ * @property {string} [code]
92
+ */
93
+
94
+ /** What remains of an underlying error. */
95
+
96
+ const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
97
+ const SAFE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
98
+
99
+ /** The only error type the package throws. */
100
+ export class AiServiceError extends Error {
101
+ code;
102
+ retryable;
103
+ details;
104
+
105
+ constructor(code, message, options = {}) {
106
+ super(message, options.cause === undefined ? undefined : { cause: toSafeCause(options.cause) });
107
+ this.name = "AiServiceError";
108
+ this.code = code;
109
+ this.retryable = options.retryable ?? false;
110
+ this.details = Object.freeze({ ...options.details });
111
+ }
112
+ }
113
+
114
+ export function createCancelledError() {
115
+ return new AiServiceError(ErrorCodes.CANCELLED, "The AI request was cancelled");
116
+ }
117
+
118
+ /** Wraps anything that is not already an AiServiceError, keeping only a safe summary of it. */
119
+ export function toAiServiceError(error) {
120
+ if (error instanceof AiServiceError) {
121
+ return error;
122
+ }
123
+ return new AiServiceError(ErrorCodes.INTERNAL_ERROR, "Unexpected error while running the AI task", {
124
+ cause: error,
125
+ });
126
+ }
127
+
128
+ /**
129
+ * Returns a well-formed system error code (for example ECONNREFUSED or UND_ERR_SOCKET) from the error or its
130
+ * direct cause, or undefined.
131
+ */
132
+ export function systemErrorCode(error) {
133
+ for (const candidate of [error, causeOf(error)]) {
134
+ if (typeof candidate === "object" && candidate !== null && "code" in candidate) {
135
+ const code = candidate.code;
136
+ if (typeof code === "string" && SAFE_CODE.test(code)) {
137
+ return code;
138
+ }
139
+ }
140
+ }
141
+ return undefined;
142
+ }
143
+
144
+ function causeOf(error) {
145
+ return error instanceof Error ? error.cause : undefined;
146
+ }
147
+
148
+ function toSafeCause(cause) {
149
+ if (cause instanceof AiServiceError) {
150
+ return Object.freeze({ name: cause.name, code: cause.code });
151
+ }
152
+ const name = cause instanceof Error && SAFE_NAME.test(cause.name) ? cause.name : typeof cause;
153
+ const code = systemErrorCode(cause);
154
+ return Object.freeze(code === undefined ? { name } : { name, code });
155
+ }
156
+
157
+ /** The category of an error (see ErrorCategories): "rate_limit", "authorization", "provider" ... */
158
+ export function errorCategory(error) {
159
+ return error instanceof AiServiceError && Object.hasOwn(ErrorCategories, error.code) ? ErrorCategories[error.code] : "internal";
160
+ }
161
+
162
+ export function isRateLimited(error) {
163
+ return error instanceof AiServiceError && error.code === ErrorCodes.PROVIDER_RATE_LIMITED;
164
+ }
165
+
166
+ /**
167
+ * Rate-limit details for logs and metadata; cooldown is true when the provider was not called.
168
+ * @returns {{ status: number, retryAfterSeconds: number | null, cooldown: boolean } | null}
169
+ */
170
+ export function rateLimitInfo(error) {
171
+ if (!isRateLimited(error)) return null;
172
+ const seconds = Number(error.details.retryAfterSeconds);
173
+ return { status: 429, retryAfterSeconds: Number.isFinite(seconds) ? seconds : null, cooldown: error.details.cooldown === true };
174
+ }
175
+
176
+ /** The message to show a user for an AI error: AI_BUSY_MESSAGE for rate limits, otherwise the fallback. */
177
+ export function aiUserMessage(error, fallback) {
178
+ return isRateLimited(error) ? AI_BUSY_MESSAGE : fallback;
179
+ }
180
+
181
+ const MAX_REPORTED_ISSUES = 5;
182
+
183
+ /** Placeholder for a path segment that is not a property name declared by the schema. */
184
+ export const REDACTED_SEGMENT = "*";
185
+
186
+ const declaredKeysCache = new WeakMap();
187
+
188
+ /** Reduces a ZodError to issue counts, codes and paths that are safe to log. */
189
+ export function summarizeZodError(error, schema) {
190
+ const declared = declaredKeys(schema);
191
+ const paths = error.issues
192
+ .slice(0, MAX_REPORTED_ISSUES)
193
+ .map((issue) =>
194
+ issue.path.length === 0
195
+ ? "(root)"
196
+ : issue.path
197
+ .map((segment) =>
198
+ typeof segment === "number" || (typeof segment === "string" && declared.has(segment))
199
+ ? String(segment)
200
+ : REDACTED_SEGMENT,
201
+ )
202
+ .join("."),
203
+ );
204
+ const codes = [...new Set(error.issues.map((issue) => issue.code))];
205
+ return {
206
+ issueCount: error.issues.length,
207
+ paths: paths.join(",").slice(0, 300),
208
+ codes: codes.join(",").slice(0, 200),
209
+ };
210
+ }
211
+
212
+ function declaredKeys(schema) {
213
+ const cached = declaredKeysCache.get(schema);
214
+ if (cached !== undefined) {
215
+ return cached;
216
+ }
217
+ const keys = new Set();
218
+ try {
219
+ collectPropertyNames(z.toJSONSchema(schema, { io: "input", unrepresentable: "any" }), keys);
220
+ } catch {
221
+ // A schema that cannot be described yields no declared keys, so every
222
+ // named path segment is redacted: the safe outcome.
223
+ keys.clear();
224
+ }
225
+ declaredKeysCache.set(schema, keys);
226
+ return keys;
227
+ }
228
+
229
+ function collectPropertyNames(node, into) {
230
+ if (Array.isArray(node)) {
231
+ for (const item of node) {
232
+ collectPropertyNames(item, into);
233
+ }
234
+ return;
235
+ }
236
+ if (typeof node !== "object" || node === null) {
237
+ return;
238
+ }
239
+ const entries = Object.entries(node);
240
+ for (const [keyword, value] of entries) {
241
+ if (keyword === "properties" && typeof value === "object" && value !== null && !Array.isArray(value)) {
242
+ for (const name of Object.keys(value)) {
243
+ into.add(name);
244
+ }
245
+ }
246
+ collectPropertyNames(value, into);
247
+ }
248
+ }