Skip to content

Commit 24482a3

Browse files
authored
feat(helpers): add support for complex intermediate types (#2550)
1 parent c209030 commit 24482a3

File tree

6 files changed

+420
-75
lines changed

6 files changed

+420
-75
lines changed

src/modules/helpers/eval.ts

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
import { FakerError } from '../../errors/faker-error';
2+
import type { Faker } from '../../faker';
3+
4+
const REGEX_DOT_OR_BRACKET = /\.|\(/;
5+
6+
/**
7+
* Resolves the given expression and returns its result. This method should only be used when using serialized expressions.
8+
*
9+
* This method is useful if you have to build a random string from a static, non-executable source
10+
* (e.g. string coming from a developer, stored in a database or a file).
11+
*
12+
* It tries to resolve the expression on the given/default entrypoints:
13+
*
14+
* ```js
15+
* const firstName = fakeEval('person.firstName', faker);
16+
* const firstName2 = fakeEval('person.first_name', faker);
17+
* ```
18+
*
19+
* Is equivalent to:
20+
*
21+
* ```js
22+
* const firstName = faker.person.firstName();
23+
* const firstName2 = faker.helpers.arrayElement(faker.rawDefinitions.person.first_name);
24+
* ```
25+
*
26+
* You can provide parameters as well. At first, they will be parsed as json,
27+
* and if that isn't possible, it will fall back to string:
28+
*
29+
* ```js
30+
* const message = fakeEval('phone.number(+!# !## #### #####!)', faker);
31+
* ```
32+
*
33+
* It is also possible to use multiple parameters (comma separated).
34+
*
35+
* ```js
36+
* const pin = fakeEval('string.numeric(4, {"allowLeadingZeros": true})', faker);
37+
* ```
38+
*
39+
* This method can resolve expressions with varying depths (dot separated parts).
40+
*
41+
* ```ts
42+
* const airlineModule = fakeEval('airline', faker); // AirlineModule
43+
* const airlineObject = fakeEval('airline.airline', faker); // { name: 'Etihad Airways', iataCode: 'EY' }
44+
* const airlineCode = fakeEval('airline.airline.iataCode', faker); // 'EY'
45+
* const airlineName = fakeEval('airline.airline().name', faker); // 'Etihad Airways'
46+
* const airlineMethodName = fakeEval('airline.airline.name', faker); // 'bound airline'
47+
* ```
48+
*
49+
* It is NOT possible to access any values not passed as entrypoints.
50+
*
51+
* This method will never return arrays, as it will pick a random element from them instead.
52+
*
53+
* @param expression The expression to evaluate on the entrypoints.
54+
* @param faker The faker instance to resolve array elements.
55+
* @param entrypoints The entrypoints to use when evaluating the expression.
56+
*
57+
* @see faker.helpers.fake() If you wish to have a string with multiple expressions.
58+
*
59+
* @example
60+
* fakeEval('person.lastName', faker) // 'Barrows'
61+
* fakeEval('helpers.arrayElement(["heads", "tails"])', faker) // 'tails'
62+
* fakeEval('number.int(9999)', faker) // 4834
63+
*
64+
* @since 8.4.0
65+
*/
66+
export function fakeEval(
67+
expression: string,
68+
faker: Faker,
69+
entrypoints: ReadonlyArray<unknown> = [faker, faker.rawDefinitions]
70+
): unknown {
71+
if (expression.length === 0) {
72+
throw new FakerError('Eval expression cannot be empty.');
73+
}
74+
75+
if (entrypoints.length === 0) {
76+
throw new FakerError('Eval entrypoints cannot be empty.');
77+
}
78+
79+
let current = entrypoints;
80+
let remaining = expression;
81+
do {
82+
let index: number;
83+
if (remaining.startsWith('(')) {
84+
[index, current] = evalProcessFunction(remaining, current);
85+
} else {
86+
[index, current] = evalProcessExpression(remaining, current);
87+
}
88+
89+
remaining = remaining.substring(index);
90+
91+
// Remove garbage and resolve array values
92+
current = current
93+
.filter((value) => value != null)
94+
.map((value): unknown =>
95+
Array.isArray(value) ? faker.helpers.arrayElement(value) : value
96+
);
97+
} while (remaining.length > 0 && current.length > 0);
98+
99+
if (current.length === 0) {
100+
throw new FakerError(`Cannot resolve expression '${expression}'`);
101+
}
102+
103+
const value = current[0];
104+
return typeof value === 'function' ? value() : value;
105+
}
106+
107+
/**
108+
* Evaluates a function call and returns the new read index and the mapped results.
109+
*
110+
* @param input The input string to parse.
111+
* @param entrypoints The entrypoints to attempt the call on.
112+
*/
113+
function evalProcessFunction(
114+
input: string,
115+
entrypoints: ReadonlyArray<unknown>
116+
): [continueIndex: number, mapped: unknown[]] {
117+
const [index, params] = findParams(input);
118+
const nextChar = input[index + 1];
119+
switch (nextChar) {
120+
case '.':
121+
case '(':
122+
case undefined:
123+
break; // valid
124+
default:
125+
throw new FakerError(
126+
`Expected dot ('.'), open parenthesis ('('), or nothing after function call but got '${nextChar}'`
127+
);
128+
}
129+
130+
return [
131+
index + (nextChar === '.' ? 2 : 1), // one for the closing bracket, one for the dot
132+
entrypoints.map((entrypoint): unknown =>
133+
// TODO @ST-DDT 2023-12-11: Replace in v9
134+
// typeof entrypoint === 'function' ? entrypoint(...params) : undefined
135+
typeof entrypoint === 'function' ? entrypoint(...params) : entrypoint
136+
),
137+
];
138+
}
139+
140+
/**
141+
* Tries to find the parameters of a function call.
142+
*
143+
* @param input The input string to parse.
144+
*/
145+
function findParams(input: string): [continueIndex: number, params: unknown[]] {
146+
let index = input.indexOf(')', 1);
147+
if (index === -1) {
148+
throw new FakerError(`Missing closing parenthesis in '${input}'`);
149+
}
150+
151+
while (index !== -1) {
152+
const params = input.substring(1, index);
153+
try {
154+
// assuming that the params are valid JSON
155+
return [index, JSON.parse(`[${params}]`) as unknown[]];
156+
} catch {
157+
if (!params.includes("'") && !params.includes('"')) {
158+
try {
159+
// assuming that the params are a single unquoted string
160+
return [index, JSON.parse(`["${params}"]`) as unknown[]];
161+
} catch {
162+
// try again with the next index
163+
}
164+
}
165+
}
166+
167+
index = input.indexOf(')', index + 1);
168+
}
169+
170+
index = input.lastIndexOf(')');
171+
const params = input.substring(1, index);
172+
return [index, [params]];
173+
}
174+
175+
/**
176+
* Processes one expression part and returns the new read index and the mapped results.
177+
*
178+
* @param input The input string to parse.
179+
* @param entrypoints The entrypoints to resolve on.
180+
*/
181+
function evalProcessExpression(
182+
input: string,
183+
entrypoints: ReadonlyArray<unknown>
184+
): [continueIndex: number, mapped: unknown[]] {
185+
const result = REGEX_DOT_OR_BRACKET.exec(input);
186+
const dotMatch = (result?.[0] ?? '') === '.';
187+
const index = result?.index ?? input.length;
188+
const key = input.substring(0, index);
189+
if (key.length === 0) {
190+
throw new FakerError(`Expression parts cannot be empty in '${input}'`);
191+
}
192+
193+
const next = input[index + 1];
194+
if (dotMatch && (next == null || next === '.' || next === '(')) {
195+
throw new FakerError(`Found dot without property name in '${input}'`);
196+
}
197+
198+
return [
199+
index + (dotMatch ? 1 : 0),
200+
entrypoints.map((entrypoint) => resolveProperty(entrypoint, key)),
201+
];
202+
}
203+
204+
/**
205+
* Resolves the given property on the given entrypoint.
206+
*
207+
* @param entrypoint The entrypoint to resolve the property on.
208+
* @param key The property name to resolve.
209+
*/
210+
function resolveProperty(entrypoint: unknown, key: string): unknown {
211+
switch (typeof entrypoint) {
212+
case 'function': {
213+
try {
214+
entrypoint = entrypoint();
215+
} catch {
216+
return undefined;
217+
}
218+
219+
return entrypoint?.[key as keyof typeof entrypoint];
220+
}
221+
222+
case 'object': {
223+
return entrypoint?.[key as keyof typeof entrypoint];
224+
}
225+
226+
default:
227+
return undefined;
228+
}
229+
}

src/modules/helpers/index.ts

Lines changed: 5 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Faker, SimpleFaker } from '../..';
22
import { FakerError } from '../../errors/faker-error';
33
import { deprecated } from '../../internal/deprecated';
44
import { SimpleModuleBase } from '../../internal/module-base';
5+
import { fakeEval } from './eval';
56
import { luhnCheckValue } from './luhn-check';
67
import type { RecordKey } from './unique';
78
import * as uniqueExec from './unique';
@@ -1460,66 +1461,15 @@ export class HelpersModule extends SimpleHelpersModule {
14601461
// extract method name from between the {{ }} that we found
14611462
// for example: {{person.firstName}}
14621463
const token = pattern.substring(start + 2, end + 2);
1463-
let method = token.replace('}}', '').replace('{{', '');
1464-
1465-
// extract method parameters
1466-
const regExp = /\(([^)]*)\)/;
1467-
const matches = regExp.exec(method);
1468-
let parameters = '';
1469-
if (matches) {
1470-
method = method.replace(regExp, '');
1471-
parameters = matches[1];
1472-
}
1473-
1474-
// split the method into module and function
1475-
const parts = method.split('.');
1476-
1477-
let currentModuleOrMethod: unknown = this.faker;
1478-
let currentDefinitions: unknown = this.faker.rawDefinitions;
1479-
1480-
// Search for the requested method or definition
1481-
for (const part of parts) {
1482-
currentModuleOrMethod =
1483-
currentModuleOrMethod?.[part as keyof typeof currentModuleOrMethod];
1484-
currentDefinitions =
1485-
currentDefinitions?.[part as keyof typeof currentDefinitions];
1486-
}
1487-
1488-
// Make method executable
1489-
let fn: (...args: unknown[]) => unknown;
1490-
if (typeof currentModuleOrMethod === 'function') {
1491-
fn = currentModuleOrMethod as (args?: unknown) => unknown;
1492-
} else if (Array.isArray(currentDefinitions)) {
1493-
fn = () =>
1494-
this.faker.helpers.arrayElement(currentDefinitions as unknown[]);
1495-
} else {
1496-
throw new FakerError(`Invalid module method or definition: ${method}
1497-
- faker.${method} is not a function
1498-
- faker.definitions.${method} is not an array`);
1499-
}
1500-
1501-
// assign the function from the module.function namespace
1502-
fn = fn.bind(this);
1503-
1504-
// If parameters are populated here, they are always going to be of string type
1505-
// since we might actually be dealing with an object or array,
1506-
// we always attempt to the parse the incoming parameters into JSON
1507-
let params: unknown[];
1508-
// Note: we experience a small performance hit here due to JSON.parse try / catch
1509-
// If anyone actually needs to optimize this specific code path, please open a support issue on github
1510-
try {
1511-
params = JSON.parse(`[${parameters}]`);
1512-
} catch {
1513-
// since JSON.parse threw an error, assume parameters was actually a string
1514-
params = [parameters];
1515-
}
1464+
const method = token.replace('}}', '').replace('{{', '');
15161465

1517-
const result = String(fn(...params));
1466+
const result = fakeEval(method, this.faker);
1467+
const stringified = String(result);
15181468

15191469
// Replace the found tag with the returned fake value
15201470
// We cannot use string.replace here because the result might contain evaluated characters
15211471
const res =
1522-
pattern.substring(0, start) + result + pattern.substring(end + 2);
1472+
pattern.substring(0, start) + stringified + pattern.substring(end + 2);
15231473

15241474
// return the response recursively until we are done finding all tags
15251475
return this.fake(res);

test/modules/__snapshots__/person.spec.ts.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ exports[`person > 42 > suffix > with sex 1`] = `"III"`;
5050

5151
exports[`person > 42 > zodiacSign 1`] = `"Gemini"`;
5252

53-
exports[`person > 1211 > bio 1`] = `"infrastructure supporter, photographer 🙆‍♀️"`;
53+
exports[`person > 1211 > bio 1`] = `"teletype lover, dreamer 👄"`;
5454

5555
exports[`person > 1211 > firstName > noArgs 1`] = `"Tito"`;
5656

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy