@schmock/faker 1.8.0 → 1.9.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,10 @@
1
+ import { Faker } from "@faker-js/faker";
2
+ import jsf from "json-schema-faker";
3
+ /**
4
+ * Create isolated faker instance to avoid race conditions
5
+ * Each generation gets its own faker instance to ensure thread-safety
6
+ * @returns Fresh Faker instance with English locale
7
+ */
8
+ export declare function createFakerInstance(seed?: number): Faker;
9
+ export declare function getJsf(seed?: number): typeof jsf;
10
+ //# sourceMappingURL=jsf-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsf-config.d.ts","sourceRoot":"","sources":["../src/jsf-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAM,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,GAAG,MAAM,mBAAmB,CAAC;AAEpC;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,CAAC,EAAE,MAAM,SAMhD;AAoBD,wBAAgB,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,CAqBhD"}
@@ -0,0 +1,52 @@
1
+ import { en, Faker } from "@faker-js/faker";
2
+ import jsf from "json-schema-faker";
3
+ /**
4
+ * Create isolated faker instance to avoid race conditions
5
+ * Each generation gets its own faker instance to ensure thread-safety
6
+ * @returns Fresh Faker instance with English locale
7
+ */
8
+ export function createFakerInstance(seed) {
9
+ const faker = new Faker({ locale: [en] });
10
+ if (seed !== undefined) {
11
+ faker.seed(seed);
12
+ }
13
+ return faker;
14
+ }
15
+ let jsfConfigured = false;
16
+ let currentSeed;
17
+ /**
18
+ * Create a seeded PRNG using the mulberry32 algorithm.
19
+ * Returns a function that produces deterministic values in [0, 1).
20
+ */
21
+ function createSeededRandom(seed) {
22
+ let state = seed | 0;
23
+ return () => {
24
+ state = (state + 0x6d2b79f5) | 0;
25
+ let t = state;
26
+ t = Math.imul(t ^ (t >>> 15), t | 1);
27
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
28
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
29
+ };
30
+ }
31
+ export function getJsf(seed) {
32
+ const seedChanged = seed !== currentSeed;
33
+ if (!jsfConfigured || seedChanged) {
34
+ currentSeed = seed;
35
+ jsf.extend("faker", () => createFakerInstance(seed));
36
+ jsf.option({
37
+ requiredOnly: false,
38
+ alwaysFakeOptionals: true,
39
+ useDefaultValue: true,
40
+ ignoreMissingRefs: true,
41
+ failOnInvalidTypes: false,
42
+ failOnInvalidFormat: false,
43
+ });
44
+ jsfConfigured = true;
45
+ }
46
+ // Always reset PRNG for deterministic output per call
47
+ if (seed !== undefined) {
48
+ jsf.option({ random: createSeededRandom(seed) });
49
+ jsf.extend("faker", () => createFakerInstance(seed));
50
+ }
51
+ return jsf;
52
+ }
@@ -0,0 +1,21 @@
1
+ import type { JSONSchema7 } from "json-schema";
2
+ /**
3
+ * Determine number of items to generate for array schema
4
+ * Prefers explicit count, then schema minItems/maxItems, with sane defaults
5
+ * @param schema - Array schema with optional minItems/maxItems
6
+ * @param explicitCount - Explicit count override from plugin options
7
+ * @returns Number of array items to generate
8
+ */
9
+ export declare function determineArrayCount(schema: JSONSchema7, explicitCount?: number): number;
10
+ /**
11
+ * Apply overrides to generated data with support for templates
12
+ * Supports nested paths (dot notation), templates with {{params.id}}, and state access
13
+ * @param data - Generated data to apply overrides to
14
+ * @param overrides - Override values (can use templates)
15
+ * @param params - Route parameters for template expansion
16
+ * @param state - Plugin state for template expansion
17
+ * @param query - Query parameters for template expansion
18
+ * @returns Data with overrides applied
19
+ */
20
+ export declare function applyOverrides(data: any, overrides?: Record<string, any>, params?: Record<string, string>, state?: any, query?: Record<string, string>): any;
21
+ //# sourceMappingURL=overrides.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"overrides.d.ts","sourceRoot":"","sources":["../src/overrides.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG/C;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,EACnB,aAAa,CAAC,EAAE,MAAM,GACrB,MAAM,CAyBR;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,GAAG,EACT,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC/B,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC/B,KAAK,CAAC,EAAE,GAAG,EACX,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC7B,GAAG,CAsCL"}
@@ -0,0 +1,127 @@
1
+ import { DEFAULT_ARRAY_COUNT } from "./constants.js";
2
+ /**
3
+ * Determine number of items to generate for array schema
4
+ * Prefers explicit count, then schema minItems/maxItems, with sane defaults
5
+ * @param schema - Array schema with optional minItems/maxItems
6
+ * @param explicitCount - Explicit count override from plugin options
7
+ * @returns Number of array items to generate
8
+ */
9
+ export function determineArrayCount(schema, explicitCount) {
10
+ if (explicitCount !== undefined) {
11
+ // Handle negative or invalid counts
12
+ if (explicitCount < 0) {
13
+ return 0;
14
+ }
15
+ return explicitCount;
16
+ }
17
+ if (schema.minItems !== undefined && schema.maxItems !== undefined) {
18
+ return (Math.floor(Math.random() * (schema.maxItems - schema.minItems + 1)) +
19
+ schema.minItems);
20
+ }
21
+ if (schema.minItems !== undefined) {
22
+ return Math.max(schema.minItems, DEFAULT_ARRAY_COUNT);
23
+ }
24
+ if (schema.maxItems !== undefined) {
25
+ return Math.min(schema.maxItems, DEFAULT_ARRAY_COUNT);
26
+ }
27
+ return DEFAULT_ARRAY_COUNT;
28
+ }
29
+ /**
30
+ * Apply overrides to generated data with support for templates
31
+ * Supports nested paths (dot notation), templates with {{params.id}}, and state access
32
+ * @param data - Generated data to apply overrides to
33
+ * @param overrides - Override values (can use templates)
34
+ * @param params - Route parameters for template expansion
35
+ * @param state - Plugin state for template expansion
36
+ * @param query - Query parameters for template expansion
37
+ * @returns Data with overrides applied
38
+ */
39
+ export function applyOverrides(data, overrides, params, state, query) {
40
+ if (!overrides)
41
+ return data;
42
+ const result = structuredClone(data);
43
+ for (const [key, value] of Object.entries(overrides)) {
44
+ // Handle nested paths like "data.id" or "pagination.page"
45
+ if (key.includes(".")) {
46
+ setNestedProperty(result, key, value, { params, state, query });
47
+ }
48
+ else {
49
+ // Handle flat keys and nested objects
50
+ if (typeof value === "object" &&
51
+ value !== null &&
52
+ !Array.isArray(value)) {
53
+ // Recursively apply nested overrides
54
+ if (result[key] && typeof result[key] === "object") {
55
+ result[key] = applyOverrides(result[key], value, params, state, query);
56
+ }
57
+ else {
58
+ result[key] = applyOverrides({}, value, params, state, query);
59
+ }
60
+ }
61
+ else if (typeof value === "string" && value.includes("{{")) {
62
+ // Template processing
63
+ result[key] = processTemplate(value, { params, state, query });
64
+ }
65
+ else {
66
+ result[key] = value;
67
+ }
68
+ }
69
+ }
70
+ return result;
71
+ }
72
+ function setNestedProperty(obj, path, value, context) {
73
+ const parts = path.split(".");
74
+ let current = obj;
75
+ // Navigate to the parent of the target property
76
+ for (let i = 0; i < parts.length - 1; i++) {
77
+ const part = parts[i];
78
+ if (!(part in current) ||
79
+ typeof current[part] !== "object" ||
80
+ current[part] === null) {
81
+ current[part] = {};
82
+ }
83
+ current = current[part];
84
+ }
85
+ // Set the final property
86
+ const finalKey = parts[parts.length - 1];
87
+ if (typeof value === "string" && value.includes("{{")) {
88
+ current[finalKey] = processTemplate(value, context);
89
+ }
90
+ else {
91
+ current[finalKey] = value;
92
+ }
93
+ }
94
+ function processTemplate(template, context) {
95
+ // Check if the template is just a single template expression
96
+ const singleTemplateMatch = template.match(/^\{\{\s*([^}]+)\s*\}\}$/);
97
+ if (singleTemplateMatch) {
98
+ // For single templates, return the actual value without string conversion
99
+ const expression = singleTemplateMatch[1];
100
+ const parts = expression.trim().split(".");
101
+ let result = context;
102
+ for (const part of parts) {
103
+ if (result && typeof result === "object") {
104
+ result = result[part];
105
+ }
106
+ else {
107
+ return template; // Return original if can't resolve
108
+ }
109
+ }
110
+ return result !== undefined ? result : template;
111
+ }
112
+ // For templates mixed with other text, do string replacement
113
+ const processed = template.replace(/\{\{\s*([^}]+)\s*\}\}/g, (match, expression) => {
114
+ const parts = expression.trim().split(".");
115
+ let result = context;
116
+ for (const part of parts) {
117
+ if (result && typeof result === "object") {
118
+ result = result[part];
119
+ }
120
+ else {
121
+ return match; // Return original if can't resolve
122
+ }
123
+ }
124
+ return result !== undefined ? String(result) : match;
125
+ });
126
+ return processed;
127
+ }
@@ -0,0 +1,3 @@
1
+ import type { JSONSchema7 } from "json-schema";
2
+ export declare function enhanceSchemaWithSmartMapping(schema: JSONSchema7): JSONSchema7;
3
+ //# sourceMappingURL=schema-enhancement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-enhancement.d.ts","sourceRoot":"","sources":["../src/schema-enhancement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAQ/C,wBAAgB,6BAA6B,CAC3C,MAAM,EAAE,WAAW,GAClB,WAAW,CAwBb"}
@@ -0,0 +1,81 @@
1
+ import { isJSONSchema7, validateFakerMethod } from "./validation.js";
2
+ export function enhanceSchemaWithSmartMapping(schema) {
3
+ if (!schema || typeof schema !== "object") {
4
+ return schema;
5
+ }
6
+ const enhanced = { ...schema };
7
+ // Handle object properties
8
+ if (enhanced.type === "object" && enhanced.properties) {
9
+ enhanced.properties = { ...enhanced.properties };
10
+ for (const [fieldName, fieldSchema] of Object.entries(enhanced.properties)) {
11
+ if (isJSONSchema7(fieldSchema)) {
12
+ enhanced.properties[fieldName] = enhanceFieldSchema(fieldName, fieldSchema);
13
+ }
14
+ }
15
+ }
16
+ return enhanced;
17
+ }
18
+ function enhanceFieldSchema(fieldName, fieldSchema) {
19
+ const enhanced = { ...fieldSchema };
20
+ // If already has faker extension, validate it and don't override
21
+ if (enhanced.faker) {
22
+ validateFakerMethod(enhanced.faker);
23
+ return enhanced;
24
+ }
25
+ // Apply smart field name mapping
26
+ const lowerFieldName = fieldName.toLowerCase();
27
+ // Email fields
28
+ if (lowerFieldName.includes("email")) {
29
+ enhanced.format = "email";
30
+ enhanced.faker = "internet.email";
31
+ }
32
+ // Name fields
33
+ else if (lowerFieldName === "firstname" || lowerFieldName === "first_name") {
34
+ enhanced.faker = "person.firstName";
35
+ }
36
+ else if (lowerFieldName === "lastname" || lowerFieldName === "last_name") {
37
+ enhanced.faker = "person.lastName";
38
+ }
39
+ else if (lowerFieldName === "name" || lowerFieldName === "fullname") {
40
+ enhanced.faker = "person.fullName";
41
+ }
42
+ // Phone fields
43
+ else if (lowerFieldName.includes("phone") || lowerFieldName === "mobile") {
44
+ enhanced.faker = "phone.number";
45
+ }
46
+ // Address fields
47
+ else if (lowerFieldName === "street" || lowerFieldName === "address") {
48
+ enhanced.faker = "location.streetAddress";
49
+ }
50
+ else if (lowerFieldName === "city") {
51
+ enhanced.faker = "location.city";
52
+ }
53
+ else if (lowerFieldName === "zipcode" || lowerFieldName === "zip") {
54
+ enhanced.faker = "location.zipCode";
55
+ }
56
+ // UUID fields
57
+ else if (lowerFieldName === "uuid" ||
58
+ (lowerFieldName === "id" && enhanced.format === "uuid")) {
59
+ enhanced.faker = "string.uuid";
60
+ }
61
+ // Date fields
62
+ else if (lowerFieldName.includes("createdat") ||
63
+ lowerFieldName.includes("created_at") ||
64
+ lowerFieldName.includes("updatedat") ||
65
+ lowerFieldName.includes("updated_at")) {
66
+ enhanced.format = "date-time";
67
+ enhanced.faker = "date.recent";
68
+ }
69
+ // Company fields
70
+ else if (lowerFieldName.includes("company")) {
71
+ enhanced.faker = "company.name";
72
+ }
73
+ else if (lowerFieldName === "position" || lowerFieldName === "jobtitle") {
74
+ enhanced.faker = "person.jobTitle";
75
+ }
76
+ // Price/money fields
77
+ else if (lowerFieldName === "price" || lowerFieldName === "amount") {
78
+ enhanced.faker = "commerce.price";
79
+ }
80
+ return enhanced;
81
+ }
@@ -0,0 +1,20 @@
1
+ import type { JSONSchema7 } from "json-schema";
2
+ export declare function isJSONSchema7(value: unknown): value is JSONSchema7;
3
+ /**
4
+ * Validate JSON Schema structure and enforce resource limits
5
+ * Checks for malformed schemas, circular references, excessive nesting,
6
+ * and dangerous patterns that could cause memory issues
7
+ * @param schema - JSON Schema to validate
8
+ * @param path - Current path in schema tree (for error messages)
9
+ * @throws {SchemaValidationError} When schema structure is invalid
10
+ * @throws {ResourceLimitError} When schema exceeds safety limits
11
+ */
12
+ export declare function validateSchema(schema: JSONSchema7, path?: string): void;
13
+ /**
14
+ * Validate that faker method string references a valid Faker.js API
15
+ * Checks format (namespace.method) and validates against known namespaces
16
+ * @param fakerMethod - Faker method string (e.g., "person.fullName")
17
+ * @throws {SchemaValidationError} When faker method format or namespace is invalid
18
+ */
19
+ export declare function validateFakerMethod(fakerMethod: string): void;
20
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAU/C,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAElE;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE,IAAI,SAAM,GAAG,IAAI,CAiJpE;AA+MD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAgC7D"}
@@ -0,0 +1,298 @@
1
+ import { ResourceLimitError, SchemaValidationError } from "@schmock/core";
2
+ import { DEEP_NESTING_THRESHOLD, DEFAULT_ARRAY_COUNT, LARGE_ARRAY_THRESHOLD, MAX_ARRAY_SIZE, MAX_NESTING_DEPTH, } from "./constants.js";
3
+ import { createFakerInstance } from "./jsf-config.js";
4
+ export function isJSONSchema7(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ /**
8
+ * Validate JSON Schema structure and enforce resource limits
9
+ * Checks for malformed schemas, circular references, excessive nesting,
10
+ * and dangerous patterns that could cause memory issues
11
+ * @param schema - JSON Schema to validate
12
+ * @param path - Current path in schema tree (for error messages)
13
+ * @throws {SchemaValidationError} When schema structure is invalid
14
+ * @throws {ResourceLimitError} When schema exceeds safety limits
15
+ */
16
+ export function validateSchema(schema, path = "$") {
17
+ if (!schema || typeof schema !== "object") {
18
+ throw new SchemaValidationError(path, "Schema must be a valid JSON Schema object");
19
+ }
20
+ if (Object.keys(schema).length === 0) {
21
+ throw new SchemaValidationError(path, "Schema cannot be empty");
22
+ }
23
+ // Check for invalid schema types
24
+ const validTypes = [
25
+ "object",
26
+ "array",
27
+ "string",
28
+ "number",
29
+ "integer",
30
+ "boolean",
31
+ "null",
32
+ ];
33
+ if (schema.type &&
34
+ typeof schema.type === "string" &&
35
+ !validTypes.includes(schema.type)) {
36
+ throw new SchemaValidationError(path, `Invalid schema type: "${schema.type}"`, "Supported types are: object, array, string, number, integer, boolean, null");
37
+ }
38
+ // Check for malformed properties (must be object, not string)
39
+ if (schema.type === "object" && schema.properties) {
40
+ if (typeof schema.properties !== "object" ||
41
+ Array.isArray(schema.properties)) {
42
+ throw new SchemaValidationError(`${path}.properties`, "Properties must be an object mapping property names to schemas", 'Use { "propertyName": { "type": "string" } } format');
43
+ }
44
+ // Validate each property recursively
45
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
46
+ if (typeof propSchema === "object" && propSchema !== null) {
47
+ // Check for invalid faker methods in property schemas
48
+ const fakerProp = "faker" in propSchema ? String(propSchema.faker) : undefined;
49
+ if (fakerProp) {
50
+ try {
51
+ validateFakerMethod(fakerProp);
52
+ }
53
+ catch (error) {
54
+ // Re-throw with proper path context
55
+ if (error instanceof SchemaValidationError) {
56
+ const ctx = error.context;
57
+ let issue = "Invalid faker method";
58
+ let suggestion;
59
+ if (ctx && typeof ctx === "object") {
60
+ if ("issue" in ctx && typeof ctx.issue === "string")
61
+ issue = ctx.issue;
62
+ if ("suggestion" in ctx && typeof ctx.suggestion === "string")
63
+ suggestion = ctx.suggestion;
64
+ }
65
+ throw new SchemaValidationError(`${path}.properties.${propName}.faker`, issue, suggestion);
66
+ }
67
+ if (error instanceof Error)
68
+ throw error;
69
+ throw new Error(String(error));
70
+ }
71
+ }
72
+ validateSchema(propSchema, `${path}.properties.${propName}`);
73
+ }
74
+ }
75
+ }
76
+ // Check for invalid array items
77
+ if (schema.type === "array") {
78
+ // Array must have items defined and non-null
79
+ if (schema.items === null || schema.items === undefined) {
80
+ throw new SchemaValidationError(`${path}.items`, "Array schema must have valid items definition", "Define items as a schema object or array of schemas");
81
+ }
82
+ if (Array.isArray(schema.items)) {
83
+ if (schema.items.length === 0) {
84
+ throw new SchemaValidationError(`${path}.items`, "Array items cannot be empty array", "Provide at least one item schema");
85
+ }
86
+ schema.items.forEach((item, index) => {
87
+ if (typeof item === "object" && item !== null) {
88
+ validateSchema(item, `${path}.items[${index}]`);
89
+ }
90
+ });
91
+ }
92
+ else if (typeof schema.items === "object" && schema.items !== null) {
93
+ validateSchema(schema.items, `${path}.items`);
94
+ }
95
+ }
96
+ // Check for circular references
97
+ if (hasCircularReference(schema)) {
98
+ throw new SchemaValidationError(path, "Schema contains circular references which are not supported");
99
+ }
100
+ // Check nesting depth
101
+ const depth = calculateNestingDepth(schema);
102
+ if (depth > MAX_NESTING_DEPTH) {
103
+ throw new ResourceLimitError("schema_nesting_depth", MAX_NESTING_DEPTH, depth);
104
+ }
105
+ // Check for dangerous combination of deep nesting + large arrays
106
+ if (depth >= 4) {
107
+ checkForDeepNestingWithArrays(schema, path);
108
+ }
109
+ // Check for potentially dangerous array sizes in schema definition
110
+ checkArraySizeLimits(schema, path);
111
+ // Check for forbidden features
112
+ if (schema.$ref === "#") {
113
+ throw new SchemaValidationError(path, "Self-referencing schemas are not supported");
114
+ }
115
+ }
116
+ /**
117
+ * Detect circular references in JSON Schema using path-based traversal
118
+ * Uses backtracking to distinguish between cycles and legitimate schema reuse
119
+ * @param schema - Schema to check for cycles
120
+ * @param currentPath - Set of schemas currently in traversal path
121
+ * @returns true if circular reference detected, false otherwise
122
+ * @example
123
+ * // Detects: schema A -> B -> A (cycle)
124
+ * // Allows: schema A -> B, A -> C (reuse of A)
125
+ */
126
+ function hasCircularReference(schema, currentPath = new Set()) {
127
+ // Check if this schema is currently being traversed (cycle detected)
128
+ if (currentPath.has(schema)) {
129
+ return true;
130
+ }
131
+ if (schema.$ref === "#") {
132
+ return true;
133
+ }
134
+ // Add to current path for this traversal branch
135
+ currentPath.add(schema);
136
+ if (schema.type === "object" && schema.properties) {
137
+ for (const prop of Object.values(schema.properties)) {
138
+ if (isJSONSchema7(prop)) {
139
+ if (hasCircularReference(prop, currentPath)) {
140
+ return true;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ if (schema.type === "array" && schema.items) {
146
+ const items = Array.isArray(schema.items) ? schema.items : [schema.items];
147
+ for (const item of items) {
148
+ if (isJSONSchema7(item)) {
149
+ if (hasCircularReference(item, currentPath)) {
150
+ return true;
151
+ }
152
+ }
153
+ }
154
+ }
155
+ // Remove from current path after checking all children (backtrack)
156
+ currentPath.delete(schema);
157
+ return false;
158
+ }
159
+ /**
160
+ * Calculate maximum nesting depth of a JSON Schema
161
+ * Recursively traverses object properties and array items
162
+ * @param schema - Schema to measure
163
+ * @param depth - Current depth (internal recursion parameter)
164
+ * @returns Maximum nesting depth found
165
+ */
166
+ function calculateNestingDepth(schema, depth = 0) {
167
+ if (depth > MAX_NESTING_DEPTH) {
168
+ return depth;
169
+ }
170
+ let maxDepth = depth;
171
+ if (schema.type === "object" && schema.properties) {
172
+ for (const prop of Object.values(schema.properties)) {
173
+ if (isJSONSchema7(prop)) {
174
+ maxDepth = Math.max(maxDepth, calculateNestingDepth(prop, depth + 1));
175
+ }
176
+ }
177
+ }
178
+ if (schema.type === "array" && schema.items) {
179
+ const items = Array.isArray(schema.items) ? schema.items : [schema.items];
180
+ for (const item of items) {
181
+ if (isJSONSchema7(item)) {
182
+ maxDepth = Math.max(maxDepth, calculateNestingDepth(item, depth + 1));
183
+ }
184
+ }
185
+ }
186
+ return maxDepth;
187
+ }
188
+ /**
189
+ * Check for dangerous patterns of deep nesting combined with large arrays
190
+ * Prevents memory issues from schemas like: depth 3+ with 100+ item arrays
191
+ * @param schema - Schema to check
192
+ * @param _path - Path in schema (unused but kept for signature consistency)
193
+ * @throws {ResourceLimitError} When dangerous nesting pattern detected
194
+ */
195
+ function checkForDeepNestingWithArrays(schema, _path) {
196
+ // Look for arrays in deeply nested structures that could cause memory issues
197
+ function findArraysInDeepNesting(node, currentDepth) {
198
+ const schemaType = node.type;
199
+ const isArray = Array.isArray(schemaType)
200
+ ? schemaType.includes("array")
201
+ : schemaType === "array";
202
+ if (isArray) {
203
+ const maxItems = node.maxItems || DEFAULT_ARRAY_COUNT;
204
+ // Be more aggressive about deep nesting detection
205
+ if (currentDepth >= DEEP_NESTING_THRESHOLD &&
206
+ maxItems >= LARGE_ARRAY_THRESHOLD) {
207
+ throw new ResourceLimitError("deep_nesting_memory_risk", DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD, currentDepth * maxItems);
208
+ }
209
+ // Check items if they exist
210
+ if (node.items) {
211
+ const items = Array.isArray(node.items) ? node.items : [node.items];
212
+ for (const item of items) {
213
+ if (isJSONSchema7(item)) {
214
+ if (findArraysInDeepNesting(item, currentDepth + 1)) {
215
+ return true;
216
+ }
217
+ }
218
+ }
219
+ }
220
+ return true;
221
+ }
222
+ if (schemaType === "object" && node.properties) {
223
+ for (const prop of Object.values(node.properties)) {
224
+ if (isJSONSchema7(prop)) {
225
+ if (findArraysInDeepNesting(prop, currentDepth + 1)) {
226
+ return true;
227
+ }
228
+ }
229
+ }
230
+ }
231
+ return false;
232
+ }
233
+ findArraysInDeepNesting(schema, 0);
234
+ }
235
+ function checkArraySizeLimits(schema, path) {
236
+ // Recursively check all array constraints in the schema
237
+ if (schema.type === "array") {
238
+ // Check for dangerously large maxItems
239
+ if (schema.maxItems && schema.maxItems > MAX_ARRAY_SIZE) {
240
+ throw new ResourceLimitError("array_max_items", MAX_ARRAY_SIZE, schema.maxItems);
241
+ }
242
+ // Check for combination of deep nesting and large arrays
243
+ const depth = calculateNestingDepth(schema);
244
+ const estimatedSize = schema.maxItems || schema.minItems || DEFAULT_ARRAY_COUNT;
245
+ // If we have deep nesting and large arrays, it could cause memory issues
246
+ if (depth > DEEP_NESTING_THRESHOLD &&
247
+ estimatedSize > LARGE_ARRAY_THRESHOLD) {
248
+ throw new ResourceLimitError("memory_estimation", DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD, depth * estimatedSize);
249
+ }
250
+ }
251
+ // Recursively check nested schemas
252
+ if (schema.type === "object" && schema.properties) {
253
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
254
+ if (isJSONSchema7(propSchema)) {
255
+ checkArraySizeLimits(propSchema, `${path}.properties.${propName}`);
256
+ }
257
+ }
258
+ }
259
+ if (schema.type === "array" && schema.items) {
260
+ if (Array.isArray(schema.items)) {
261
+ schema.items.forEach((item, index) => {
262
+ if (isJSONSchema7(item)) {
263
+ checkArraySizeLimits(item, `${path}.items[${index}]`);
264
+ }
265
+ });
266
+ }
267
+ else if (isJSONSchema7(schema.items)) {
268
+ checkArraySizeLimits(schema.items, `${path}.items`);
269
+ }
270
+ }
271
+ }
272
+ /**
273
+ * Validate that faker method string references a valid Faker.js API
274
+ * Checks format (namespace.method) and validates against known namespaces
275
+ * @param fakerMethod - Faker method string (e.g., "person.fullName")
276
+ * @throws {SchemaValidationError} When faker method format or namespace is invalid
277
+ */
278
+ export function validateFakerMethod(fakerMethod) {
279
+ // Check if faker method follows valid format (namespace.method)
280
+ const parts = fakerMethod.split(".");
281
+ if (parts.length < 2) {
282
+ throw new SchemaValidationError("$.faker", `Invalid faker method format: "${fakerMethod}"`, "Use format like 'person.firstName' or 'internet.email'");
283
+ }
284
+ // Validate by resolving the method path on a real faker instance
285
+ const faker = createFakerInstance();
286
+ let current = faker;
287
+ for (const part of parts) {
288
+ if (current && typeof current === "object" && part in current) {
289
+ current = current[part];
290
+ }
291
+ else {
292
+ throw new SchemaValidationError("$.faker", `Invalid faker method: "${fakerMethod}"`, "Check faker.js documentation for valid methods");
293
+ }
294
+ }
295
+ if (typeof current !== "function") {
296
+ throw new SchemaValidationError("$.faker", `Invalid faker method: "${fakerMethod}" is not a function`, "Check faker.js documentation for valid methods");
297
+ }
298
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@schmock/faker",
3
3
  "description": "Faker-powered automatic data generation for Schmock",
4
- "version": "1.8.0",
4
+ "version": "1.9.1",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -34,12 +34,12 @@
34
34
  "json-schema-faker": "^0.5.6"
35
35
  },
36
36
  "peerDependencies": {
37
- "@schmock/core": "^1.8.0"
37
+ "@schmock/core": "^1.9.1"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@amiceli/vitest-cucumber": "^6.2.0",
41
41
  "@types/json-schema": "^7.0.15",
42
- "@types/node": "^25.2.1",
42
+ "@types/node": "^25.2.3",
43
43
  "vitest": "^4.0.18"
44
44
  }
45
45
  }
@@ -0,0 +1,6 @@
1
+ // Resource limits for safety
2
+ export const MAX_ARRAY_SIZE = 10000;
3
+ export const MAX_NESTING_DEPTH = 10; // Reasonable limit for schema nesting
4
+ export const DEFAULT_ARRAY_COUNT = 3; // Default items to generate when not specified
5
+ export const DEEP_NESTING_THRESHOLD = 3; // Depth at which to check for memory risks
6
+ export const LARGE_ARRAY_THRESHOLD = 100; // Array size considered "large"