@schmock/faker 1.9.0 → 1.9.2

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,414 @@
1
+ import type { Faker } from "@faker-js/faker";
2
+ import { ResourceLimitError, SchemaValidationError } from "@schmock/core";
3
+ import type { JSONSchema7 } from "json-schema";
4
+ import {
5
+ DEEP_NESTING_THRESHOLD,
6
+ DEFAULT_ARRAY_COUNT,
7
+ LARGE_ARRAY_THRESHOLD,
8
+ MAX_ARRAY_SIZE,
9
+ MAX_NESTING_DEPTH,
10
+ } from "./constants.js";
11
+ import { createFakerInstance } from "./jsf-config.js";
12
+
13
+ let validationFaker: Faker | undefined;
14
+
15
+ export function isJSONSchema7(value: unknown): value is JSONSchema7 {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+
19
+ /**
20
+ * Validate JSON Schema structure and enforce resource limits
21
+ * Checks for malformed schemas, circular references, excessive nesting,
22
+ * and dangerous patterns that could cause memory issues
23
+ * @param schema - JSON Schema to validate
24
+ * @param path - Current path in schema tree (for error messages)
25
+ * @throws {SchemaValidationError} When schema structure is invalid
26
+ * @throws {ResourceLimitError} When schema exceeds safety limits
27
+ */
28
+ export function validateSchema(schema: JSONSchema7, path = "$"): void {
29
+ if (!schema || typeof schema !== "object") {
30
+ throw new SchemaValidationError(
31
+ path,
32
+ "Schema must be a valid JSON Schema object",
33
+ );
34
+ }
35
+
36
+ if (Object.keys(schema).length === 0) {
37
+ throw new SchemaValidationError(path, "Schema cannot be empty");
38
+ }
39
+
40
+ // Check for invalid schema types
41
+ const validTypes = [
42
+ "object",
43
+ "array",
44
+ "string",
45
+ "number",
46
+ "integer",
47
+ "boolean",
48
+ "null",
49
+ ];
50
+ if (
51
+ schema.type &&
52
+ typeof schema.type === "string" &&
53
+ !validTypes.includes(schema.type)
54
+ ) {
55
+ throw new SchemaValidationError(
56
+ path,
57
+ `Invalid schema type: "${schema.type}"`,
58
+ "Supported types are: object, array, string, number, integer, boolean, null",
59
+ );
60
+ }
61
+
62
+ // Check for malformed properties (must be object, not string)
63
+ if (schema.type === "object" && schema.properties) {
64
+ if (
65
+ typeof schema.properties !== "object" ||
66
+ Array.isArray(schema.properties)
67
+ ) {
68
+ throw new SchemaValidationError(
69
+ `${path}.properties`,
70
+ "Properties must be an object mapping property names to schemas",
71
+ 'Use { "propertyName": { "type": "string" } } format',
72
+ );
73
+ }
74
+
75
+ // Validate each property recursively
76
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
77
+ if (typeof propSchema === "object" && propSchema !== null) {
78
+ // Check for invalid faker methods in property schemas
79
+ const fakerProp =
80
+ "faker" in propSchema ? String(propSchema.faker) : undefined;
81
+ if (fakerProp) {
82
+ try {
83
+ validateFakerMethod(fakerProp);
84
+ } catch (error: unknown) {
85
+ // Re-throw with proper path context
86
+ if (error instanceof SchemaValidationError) {
87
+ const ctx = error.context;
88
+ let issue = "Invalid faker method";
89
+ let suggestion: string | undefined;
90
+ if (ctx && typeof ctx === "object") {
91
+ if ("issue" in ctx && typeof ctx.issue === "string")
92
+ issue = ctx.issue;
93
+ if ("suggestion" in ctx && typeof ctx.suggestion === "string")
94
+ suggestion = ctx.suggestion;
95
+ }
96
+ throw new SchemaValidationError(
97
+ `${path}.properties.${propName}.faker`,
98
+ issue,
99
+ suggestion,
100
+ );
101
+ }
102
+ if (error instanceof Error) throw error;
103
+ throw new Error(String(error));
104
+ }
105
+ }
106
+ validateSchema(propSchema, `${path}.properties.${propName}`);
107
+ }
108
+ }
109
+ }
110
+
111
+ // Check for invalid array items
112
+ if (schema.type === "array") {
113
+ // Array must have items defined and non-null
114
+ if (schema.items === null || schema.items === undefined) {
115
+ throw new SchemaValidationError(
116
+ `${path}.items`,
117
+ "Array schema must have valid items definition",
118
+ "Define items as a schema object or array of schemas",
119
+ );
120
+ }
121
+
122
+ if (Array.isArray(schema.items)) {
123
+ if (schema.items.length === 0) {
124
+ throw new SchemaValidationError(
125
+ `${path}.items`,
126
+ "Array items cannot be empty array",
127
+ "Provide at least one item schema",
128
+ );
129
+ }
130
+ schema.items.forEach((item, index) => {
131
+ if (typeof item === "object" && item !== null) {
132
+ validateSchema(item, `${path}.items[${index}]`);
133
+ }
134
+ });
135
+ } else if (typeof schema.items === "object" && schema.items !== null) {
136
+ validateSchema(schema.items, `${path}.items`);
137
+ }
138
+ }
139
+
140
+ // Check for circular references
141
+ if (hasCircularReference(schema)) {
142
+ throw new SchemaValidationError(
143
+ path,
144
+ "Schema contains circular references which are not supported",
145
+ );
146
+ }
147
+
148
+ // Check nesting depth
149
+ const depth = calculateNestingDepth(schema);
150
+ if (depth > MAX_NESTING_DEPTH) {
151
+ throw new ResourceLimitError(
152
+ "schema_nesting_depth",
153
+ MAX_NESTING_DEPTH,
154
+ depth,
155
+ );
156
+ }
157
+
158
+ // Check for dangerous combination of deep nesting + large arrays
159
+ if (depth >= DEEP_NESTING_THRESHOLD) {
160
+ checkForDeepNestingWithArrays(schema, path);
161
+ }
162
+
163
+ // Check for potentially dangerous array sizes in schema definition
164
+ checkArraySizeLimits(schema, path);
165
+
166
+ // Check for forbidden features
167
+ if (schema.$ref === "#") {
168
+ throw new SchemaValidationError(
169
+ path,
170
+ "Self-referencing schemas are not supported",
171
+ );
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Detect circular references in JSON Schema using path-based traversal
177
+ * Uses backtracking to distinguish between cycles and legitimate schema reuse
178
+ * @param schema - Schema to check for cycles
179
+ * @param currentPath - Set of schemas currently in traversal path
180
+ * @returns true if circular reference detected, false otherwise
181
+ * @example
182
+ * // Detects: schema A -> B -> A (cycle)
183
+ * // Allows: schema A -> B, A -> C (reuse of A)
184
+ */
185
+ function hasCircularReference(
186
+ schema: JSONSchema7,
187
+ currentPath = new Set(),
188
+ ): boolean {
189
+ // Check if this schema is currently being traversed (cycle detected)
190
+ if (currentPath.has(schema)) {
191
+ return true;
192
+ }
193
+
194
+ if (schema.$ref === "#") {
195
+ return true;
196
+ }
197
+
198
+ // Add to current path for this traversal branch
199
+ currentPath.add(schema);
200
+
201
+ if (schema.type === "object" && schema.properties) {
202
+ for (const prop of Object.values(schema.properties)) {
203
+ if (isJSONSchema7(prop)) {
204
+ if (hasCircularReference(prop, currentPath)) {
205
+ return true;
206
+ }
207
+ }
208
+ }
209
+ }
210
+
211
+ if (schema.type === "array" && schema.items) {
212
+ const items = Array.isArray(schema.items) ? schema.items : [schema.items];
213
+ for (const item of items) {
214
+ if (isJSONSchema7(item)) {
215
+ if (hasCircularReference(item, currentPath)) {
216
+ return true;
217
+ }
218
+ }
219
+ }
220
+ }
221
+
222
+ // Remove from current path after checking all children (backtrack)
223
+ currentPath.delete(schema);
224
+
225
+ return false;
226
+ }
227
+
228
+ /**
229
+ * Calculate maximum nesting depth of a JSON Schema
230
+ * Recursively traverses object properties and array items
231
+ * @param schema - Schema to measure
232
+ * @param depth - Current depth (internal recursion parameter)
233
+ * @returns Maximum nesting depth found
234
+ */
235
+ function calculateNestingDepth(schema: JSONSchema7, depth = 0): number {
236
+ if (depth > MAX_NESTING_DEPTH) {
237
+ return depth;
238
+ }
239
+
240
+ let maxDepth = depth;
241
+
242
+ if (schema.type === "object" && schema.properties) {
243
+ for (const prop of Object.values(schema.properties)) {
244
+ if (isJSONSchema7(prop)) {
245
+ maxDepth = Math.max(maxDepth, calculateNestingDepth(prop, depth + 1));
246
+ }
247
+ }
248
+ }
249
+
250
+ if (schema.type === "array" && schema.items) {
251
+ const items = Array.isArray(schema.items) ? schema.items : [schema.items];
252
+ for (const item of items) {
253
+ if (isJSONSchema7(item)) {
254
+ maxDepth = Math.max(maxDepth, calculateNestingDepth(item, depth + 1));
255
+ }
256
+ }
257
+ }
258
+
259
+ return maxDepth;
260
+ }
261
+
262
+ /**
263
+ * Check for dangerous patterns of deep nesting combined with large arrays
264
+ * Prevents memory issues from schemas like: depth 3+ with 100+ item arrays
265
+ * @param schema - Schema to check
266
+ * @param _path - Path in schema (unused but kept for signature consistency)
267
+ * @throws {ResourceLimitError} When dangerous nesting pattern detected
268
+ */
269
+ function checkForDeepNestingWithArrays(
270
+ schema: JSONSchema7,
271
+ _path: string,
272
+ ): void {
273
+ // Look for arrays in deeply nested structures that could cause memory issues
274
+ function findArraysInDeepNesting(
275
+ node: JSONSchema7,
276
+ currentDepth: number,
277
+ ): void {
278
+ const schemaType = node.type;
279
+ const isArray = Array.isArray(schemaType)
280
+ ? schemaType.includes("array")
281
+ : schemaType === "array";
282
+
283
+ if (isArray) {
284
+ const maxItems = node.maxItems || DEFAULT_ARRAY_COUNT;
285
+ // Be more aggressive about deep nesting detection
286
+ if (
287
+ currentDepth >= DEEP_NESTING_THRESHOLD &&
288
+ maxItems >= LARGE_ARRAY_THRESHOLD
289
+ ) {
290
+ throw new ResourceLimitError(
291
+ "deep_nesting_memory_risk",
292
+ DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD,
293
+ currentDepth * maxItems,
294
+ );
295
+ }
296
+
297
+ // Check items if they exist
298
+ if (node.items) {
299
+ const items = Array.isArray(node.items) ? node.items : [node.items];
300
+ for (const item of items) {
301
+ if (isJSONSchema7(item)) {
302
+ findArraysInDeepNesting(item, currentDepth + 1);
303
+ }
304
+ }
305
+ }
306
+ return;
307
+ }
308
+
309
+ if (schemaType === "object" && node.properties) {
310
+ for (const prop of Object.values(node.properties)) {
311
+ if (isJSONSchema7(prop)) {
312
+ findArraysInDeepNesting(prop, currentDepth + 1);
313
+ }
314
+ }
315
+ }
316
+ }
317
+
318
+ findArraysInDeepNesting(schema, 0);
319
+ }
320
+
321
+ function checkArraySizeLimits(schema: JSONSchema7, path: string): void {
322
+ // Recursively check all array constraints in the schema
323
+ if (schema.type === "array") {
324
+ // Check for dangerously large maxItems
325
+ if (schema.maxItems && schema.maxItems > MAX_ARRAY_SIZE) {
326
+ throw new ResourceLimitError(
327
+ "array_max_items",
328
+ MAX_ARRAY_SIZE,
329
+ schema.maxItems,
330
+ );
331
+ }
332
+
333
+ // Check for combination of deep nesting and large arrays
334
+ const depth = calculateNestingDepth(schema);
335
+ const estimatedSize =
336
+ schema.maxItems || schema.minItems || DEFAULT_ARRAY_COUNT;
337
+
338
+ // If we have deep nesting and large arrays, it could cause memory issues
339
+ if (
340
+ depth > DEEP_NESTING_THRESHOLD &&
341
+ estimatedSize > LARGE_ARRAY_THRESHOLD
342
+ ) {
343
+ throw new ResourceLimitError(
344
+ "memory_estimation",
345
+ DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD,
346
+ depth * estimatedSize,
347
+ );
348
+ }
349
+ }
350
+
351
+ // Recursively check nested schemas
352
+ if (schema.type === "object" && schema.properties) {
353
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
354
+ if (isJSONSchema7(propSchema)) {
355
+ checkArraySizeLimits(propSchema, `${path}.properties.${propName}`);
356
+ }
357
+ }
358
+ }
359
+
360
+ if (schema.type === "array" && schema.items) {
361
+ if (Array.isArray(schema.items)) {
362
+ schema.items.forEach((item, index) => {
363
+ if (isJSONSchema7(item)) {
364
+ checkArraySizeLimits(item, `${path}.items[${index}]`);
365
+ }
366
+ });
367
+ } else if (isJSONSchema7(schema.items)) {
368
+ checkArraySizeLimits(schema.items, `${path}.items`);
369
+ }
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Validate that faker method string references a valid Faker.js API
375
+ * Checks format (namespace.method) and validates against known namespaces
376
+ * @param fakerMethod - Faker method string (e.g., "person.fullName")
377
+ * @throws {SchemaValidationError} When faker method format or namespace is invalid
378
+ */
379
+ export function validateFakerMethod(fakerMethod: string): void {
380
+ // Check if faker method follows valid format (namespace.method)
381
+ const parts = fakerMethod.split(".");
382
+ if (parts.length < 2) {
383
+ throw new SchemaValidationError(
384
+ "$.faker",
385
+ `Invalid faker method format: "${fakerMethod}"`,
386
+ "Use format like 'person.firstName' or 'internet.email'",
387
+ );
388
+ }
389
+
390
+ // Validate by resolving the method path on a cached faker instance
391
+ if (!validationFaker) {
392
+ validationFaker = createFakerInstance();
393
+ }
394
+ const faker = validationFaker;
395
+ let current: any = faker;
396
+ for (const part of parts) {
397
+ if (current && typeof current === "object" && part in current) {
398
+ current = current[part];
399
+ } else {
400
+ throw new SchemaValidationError(
401
+ "$.faker",
402
+ `Invalid faker method: "${fakerMethod}"`,
403
+ "Check faker.js documentation for valid methods",
404
+ );
405
+ }
406
+ }
407
+ if (typeof current !== "function") {
408
+ throw new SchemaValidationError(
409
+ "$.faker",
410
+ `Invalid faker method: "${fakerMethod}" is not a function`,
411
+ "Check faker.js documentation for valid methods",
412
+ );
413
+ }
414
+ }