Skip to content

Commit

Permalink
refactor: refactored more old codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
USERSATOSHI committed Jul 24, 2024
1 parent 566179a commit 5f8cfb4
Show file tree
Hide file tree
Showing 17 changed files with 769 additions and 26 deletions.
9 changes: 9 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ export default [
{ selector: 'parameter', format: ['camelCase'] },
{ selector: 'typeLike', format: ['PascalCase'] },
],
'@typescript-eslint/prefer-literal-enum-member': [
'error',
[
'error',
{
allowBitwiseExpressions: true,
},
],
],
},
},
{
Expand Down
74 changes: 74 additions & 0 deletions lib/aoi.js/src/core/AoiReader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { BundlerCustoms } from "@aoi.js/typings/enum";
import { TranspilerError } from "./Error";
import Transpiler from "./Transpiler.js";

export default class AoiReader {

_parseEmbeddedJS(code: string) {
let cntr = 0, isPotentialStart = false, tmp = '';
const embeds = [];

for (let i = 0; i < code.length; i++) {
const char = code[i];

if ( char === '$') {
if (cntr) {
tmp += char;
}

if (!isPotentialStart) {
isPotentialStart = true;
}
} else if (char === '{') {
if (isPotentialStart && !cntr) {
cntr++;
} else if (cntr) {
tmp += char;
cntr++;
}
} else if (char === '}') {
if (cntr) {
cntr--;

if (!cntr) {
embeds.push(tmp);
tmp = '';
isPotentialStart = false;
} else {
tmp += char;
}
} else if (isPotentialStart) {
isPotentialStart = false;
}
} else {
if (cntr) {
tmp += char;
}
}
}

if (cntr) {
throw TranspilerError.AoiReaderError('Invalid embedded JS', { code });
}

return embeds;
}

_updateEmbedJs(compiled: string, embeds: string[]) {
while (embeds.length) {
const embed = embeds.pop()!;
compiled = this._replaceLast(compiled, BundlerCustoms.EJS, embed);
}

return compiled;
}

_replaceLast(str: string, find: string, replace: string) {
const index = str.lastIndexOf(find);
if (index === -1) {
return str;
}

return str.slice(0, index) + replace + str.slice(index + find.length);
}
}
4 changes: 4 additions & 0 deletions lib/aoi.js/src/core/Error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export class TranspilerError extends Error {
return new TranspilerError(`RunTimeError: ${msg}`, data);
}

static AoiReaderError(msg: string, data?: { function?: { name: string; code: string }; cmd?: string; path?: string; code?: string }) {
return new TranspilerError(`AoiReaderError: ${msg}`, data);
}

cause: TranspilerError;
function?: { name: string; code: string };
cmd?: string;
Expand Down
15 changes: 1 addition & 14 deletions lib/aoi.js/src/core/Transpiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export default class Transpiler {
ast,
);

scope.addVariables(this.scopeData.vars ?? []);
scope.addVariables( ...(this.scopeData.vars ?? []) );
scope.addEmbeds(this.scopeData.embeds ?? []);
scope.env.push(...(this.scopeData.env ?? []));
scope.objects = { ...scope.objects, ...this.scopeData.object };
Expand Down Expand Up @@ -381,17 +381,4 @@ export default class Transpiler {

return scope.generate(ast.executed);
}

// updateEmbedJs() {
// const embeds = [...this.embeddedJS.reverse()];
// for (const embed of embeds) {
// const old = this.rest;
// this.rest = this.replaceLast(this.rest, BundlerCustoms.EJS, embed);
// if (this.rest === old) {
// this.packages = this.embeddedJS.shift() + '\n' + this.packages;
// } else {
// this.embeddedJS.shift();
// }
// }
// }
}
142 changes: 142 additions & 0 deletions lib/aoi.js/src/core/builders/Condition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { inspect } from 'util';
import { parseData } from '@aoi.js/utils/helpers.js';
import { parseString } from '../parsers/string.js';
import { BundlerCustoms, TranspilerCustoms } from '@aoi.js/typings/enum.js';

export const OPERATORS = ['==', '!=', '>=', '<=', '>', '<', '===', '!=='] as const;

export default class Condition {
condition: string;
children: Condition[] = [];
parent: Condition | undefined;

constructor(condition: string, parent?: Condition) {
this.condition = condition;
this.parent = parent;
}

_handlePart(part: string) {
let result;
if (part.split(' ').length === 1) {
result = parseData(part);

if (typeof result === 'object') {
try {
result = JSON.stringify(result);
} catch {
result = inspect(result, { depth: null });
}
} else if (typeof result === 'string') {
if (
!(
(result.startsWith(TranspilerCustoms.FS) &&
result.endsWith(TranspilerCustoms.FE)) ||
result.startsWith('__$DISCORD_DATA$__') ||
result.trim() === (BundlerCustoms.EJS as string)
)
) {
result = parseString(result);

if (typeof parseData(result.slice(1, -1)) !== 'string') {
result = parseData(result.slice(1, -1));
}
}
} else if (typeof result === 'bigint') {
result = result.toString() + 'n';
}
} else {
result = parseString(part);
}

return result;
}

_handleConditionWithOperator(condition: string, op: string) {
let [left, right] = condition.split(op);
left = left.trim();
right = right.trim();

const leftResult = this._handlePart(left) as string;
const rightResult = this._handlePart(right) as string;

return `${leftResult}${op}${rightResult}`;
}

_solve(condition: string) {
condition = condition
.replaceAll(TranspilerCustoms.SBL, '(')
.replaceAll(TranspilerCustoms.SBR, ')');

if (this.children.length) {
for (const child of this.children) {
const solved = child.solve();
condition = condition.replace('#CONDITION#', `(${solved})`);
}

return condition;
}

const op = OPERATORS.find((op) => condition.includes(op));
let result;

if (op) {
result = this._handleConditionWithOperator(condition, op);
} else {
result = parseData(condition);

if (
typeof result === 'string' &&
(!result.endsWith(TranspilerCustoms.FE) ||
result.trim().split(' ').length > 1) &&
!result.startsWith(TranspilerCustoms.FS) &&
result.trim() !== (BundlerCustoms.EJS as string)
) {
result = parseString(result);
}
}

return result as string;
}

_solveOr(condition: string) {
const subConditions = condition.split('||');
const results = [];

for (const subCondition of subConditions) {
results.push(this._solve(subCondition));
}

return results.join(' || ');
}

_solveAnd(condition: string) {
const subConditions = condition.split('&&');
const results = [];

for (const subCondition of subConditions) {
if (subCondition.includes('||')) {
results.push(this._solveOr(subCondition));
} else {
results.push(this._solve(subCondition));
}
}

return results.join(' && ');
}

solve() {
if (this.children.length) {
return this._solve(this.condition);
}

return this._solveAnd(this.condition);
}

add(part: string) {
this.condition += part;
}

addChild(child: Condition) {
this.children.push(child);
}
}
4 changes: 2 additions & 2 deletions lib/aoi.js/src/core/builders/Function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,9 @@ export default class FunctionBuilder implements IFunctionData {

defineVar(name: string, value: string, redefined = false) {
if (redefined) {
return `${escapeVars(name)} = ${value};`;
return `${escapeVars(name)} = ${value};\n`;
} else {
return `let ${escapeVars(name)} = ${value}`;
return `let ${escapeVars(name)} = ${value};\n`;
}
}

Expand Down
6 changes: 5 additions & 1 deletion lib/aoi.js/src/core/builders/Scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,14 @@ export default class Scope {
);
}

addVariables(scopeVars: string[]) {
addVariables(...scopeVars: string[]) {
this.variables.push(...scopeVars);
}

hasVariable(name: string) {
return this.variables.includes(name);
}

addEmbeds(embeds: unknown[]) {
this.embeds.push(...embeds);
}
Expand Down
62 changes: 62 additions & 0 deletions lib/aoi.js/src/core/parsers/condition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { TranspilerCustoms } from '@aoi.js/typings/enum.js';
import Condition, { OPERATORS } from '../builders/Condition.js';

export function _countSmoothBrackets(condition: string) {
const start = condition.split('(').length - 1;
const end = condition.split(')').length - 1;

return {
start,
end,
};
}

export function _areSmoothBracketsBalanced(condition: string) {
const { start, end } = _countSmoothBrackets(condition);

return start === end;
}

export function parseCondition(condition: string) {
if (condition.includes(TranspilerCustoms.FS)) {
const matches = condition.match(
/((#FUNCTION_START#([$a-z.0-9\s?(){}[\]._:'"`;=><,!-]|\n)+#FUNCTION_END#)|(__\$[a-z_?.()]+\$__))/gim,
);

if (matches) {
for (const match of matches) {
const updated = match
.replaceAll('(', TranspilerCustoms.SBL)
.replaceAll(')', TranspilerCustoms.SBR);

condition = condition.replace(match, updated);
}
}
}

let i = 0,
starter = new Condition('');

while (i < condition.length) {
const char = condition[i];

if (char === '(') {
const child = new Condition('', starter);
starter.add('#CONDITION#');
starter.addChild(child);
starter = child;
} else if (char === ')') {
if (starter.parent) {
starter = starter.parent;
} else {
break;
}
} else {
starter.add(char);
}

i++;
}

return starter;
}
Loading

0 comments on commit 5f8cfb4

Please sign in to comment.