Skip to content

Commit

Permalink
fix(core): make simplae compatible with newer node versions
Browse files Browse the repository at this point in the history
  • Loading branch information
mnaumanali94 committed Nov 11, 2024
1 parent acaecda commit 174661a
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions packages/core/src/utils/replacer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Dictionary } from '@stoplight/types';
import reduce from 'simple-eval';
// @ts-expect-error: no types
import parse from 'nimma/parser';
// @ts-expect-error: needs new ts resolution
import reduce from 'simple-eval/eval';

export type Transformer<V = Record<string, unknown>> = (this: V, ...args: unknown[]) => string;

export class Replacer<V extends Record<string, unknown>> {
protected readonly regex: RegExp;
protected readonly functions: Dictionary<Transformer<V>>;
protected readonly functions: Record<string, Transformer<V>>;

constructor(count: number) {
this.regex = new RegExp(`#?${'{'.repeat(count)}([^}\n]+)${'}'.repeat(count)}`, 'g');
Expand All @@ -18,14 +20,13 @@ export class Replacer<V extends Record<string, unknown>> {
}

public print(input: string, values: V): string {
return input.replace(this.regex, (substr, identifier, index) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return input.replace(this.regex, (substr, identifier: string, index: number) => {
const shouldEvaluate = input[index] === '#';

if (shouldEvaluate) {
return String(
reduce(identifier, {
...Object.entries(this.functions).reduce((fns, [name, fn]) => {
simpleEval(identifier, {
...Object.entries(this.functions).reduce<Record<string, Transformer<V>>>((fns, [name, fn]) => {
fns[name] = fn.bind(values);
return fns;
}, {}),
Expand All @@ -38,8 +39,12 @@ export class Replacer<V extends Record<string, unknown>> {
return '';
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return String(values[identifier]);
});
}
}

function simpleEval(expression: string, ctx: Record<string, unknown>): unknown {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
return reduce(parse(`$[?(${expression})]`)[0].value, ctx);
}

0 comments on commit 174661a

Please sign in to comment.