hackmud-script-manager 0.19.0-f21e319 → 0.19.0-fa82f73

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,394 +1 @@
1
- import babelTraverse from '@babel/traverse';
2
- import t from '@babel/types';
3
- import { assert } from '@samual/lib/assert';
4
- import { clearObject } from '@samual/lib/clearObject';
5
- import { validDBMethods } from '../constants.js';
6
- import { getReferencePathsToGlobal } from './shared.js';
7
-
8
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports
9
- const {
10
- default: traverse
11
- } = babelTraverse;
12
- const globalFunctionsUnder7Characters = [`Map`, `Set`, `Date`, `JSON`, `Math`, `Array`, `Error`, `isNaN`, `Number`, `Object`, `RegExp`, `String`, `Symbol`, `BigInt`];
13
-
14
- /**
15
- * transform a given babel `File` to be hackmud compatible
16
- *
17
- * (returned File will need `postprocess()`ing)
18
- *
19
- * @param file babel ast node representing a file containing preprocessed code
20
- * @param sourceCode the original untouched source code
21
- * @param options {@link TransformOptions details}
22
- */
23
- const transform = (file, sourceCode, {
24
- uniqueID = `00000000000`,
25
- scriptUser = `UNKNOWN`,
26
- scriptName = `UNKNOWN`,
27
- seclevel = 4
28
- } = {}) => {
29
- const topFunctionName = `_${uniqueID}_SCRIPT_`;
30
- const exports = new Map();
31
- const liveExports = new Map();
32
- let program;
33
- traverse(file, {
34
- Program(path) {
35
- program = path;
36
- path.skip();
37
- }
38
- });
39
- if (program.scope.hasGlobal(`_SOURCE`)) {
40
- for (const referencePath of getReferencePathsToGlobal(`_SOURCE`, program)) referencePath.replaceWith(t.stringLiteral(sourceCode));
41
- }
42
- if (program.scope.hasGlobal(`_BUILD_DATE`)) {
43
- for (const referencePath of getReferencePathsToGlobal(`_BUILD_DATE`, program)) referencePath.replaceWith(t.numericLiteral(Date.now()));
44
- }
45
- if (program.scope.hasGlobal(`_SCRIPT_USER`)) {
46
- for (const referencePath of getReferencePathsToGlobal(`_SCRIPT_USER`, program)) {
47
- if (scriptUser == true) referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$SCRIPT_USER$`));else referencePath.replaceWith(t.stringLiteral(scriptUser));
48
- }
49
- }
50
- if (program.scope.hasGlobal(`_SCRIPT_NAME`)) {
51
- for (const referencePath of getReferencePathsToGlobal(`_SCRIPT_NAME`, program)) {
52
- if (scriptName == true) referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$SCRIPT_NAME$`));else referencePath.replaceWith(t.stringLiteral(scriptName));
53
- }
54
- }
55
- if (program.scope.hasGlobal(`_FULL_SCRIPT_NAME`)) {
56
- for (const referencePath of getReferencePathsToGlobal(`_FULL_SCRIPT_NAME`, program)) {
57
- if (scriptUser == true || scriptName == true) referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$FULL_SCRIPT_NAME$`));else referencePath.replaceWith(t.stringLiteral(`${scriptUser}.${scriptName}`));
58
- }
59
- }
60
- let functionDotPrototypeIsReferencedMultipleTimes = false;
61
- const createGetFunctionPrototypeNode = () => {
62
- for (const globalFunction of globalFunctionsUnder7Characters) {
63
- if (program.scope.hasOwnBinding(globalFunction)) continue;
64
- return t.memberExpression(t.memberExpression(t.identifier(globalFunction), t.identifier(`constructor`)), t.identifier(`prototype`));
65
- }
66
- return t.memberExpression(t.memberExpression(t.arrowFunctionExpression([t.identifier(`_`)], t.identifier(`_`)), t.identifier(`constructor`)), t.identifier(`prototype`));
67
- };
68
- if (program.scope.hasGlobal(`Function`)) {
69
- const FunctionReferencePaths = getReferencePathsToGlobal(`Function`, program);
70
- if (FunctionReferencePaths.length == 1) {
71
- const referencePath = FunctionReferencePaths[0];
72
- assert(referencePath.parent.type == `MemberExpression`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
73
- assert(referencePath.parent.property.type == `Identifier`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
74
- assert(referencePath.parent.property.name == `prototype`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
75
- referencePath.parentPath.replaceWith(createGetFunctionPrototypeNode());
76
- } else {
77
- for (const referencePath of FunctionReferencePaths) {
78
- assert(referencePath.parent.type == `MemberExpression`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
79
- assert(referencePath.parent.property.type == `Identifier`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
80
- assert(referencePath.parent.property.name == `prototype`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
81
- functionDotPrototypeIsReferencedMultipleTimes = true;
82
- referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_FUNCTION_DOT_PROTOTYPE_`));
83
- }
84
- functionDotPrototypeIsReferencedMultipleTimes = true;
85
- }
86
- }
87
- let detectedSeclevel = 4;
88
- const processFakeSubscriptObject = fakeSubscriptObjectName => {
89
- for (const referencePath of getReferencePathsToGlobal(fakeSubscriptObjectName, program)) {
90
- var _referencePath$parent, _referencePath$parent2;
91
- assert(referencePath.parent.type == `MemberExpression`);
92
- assert(referencePath.parent.property.type == `Identifier`);
93
- assert(((_referencePath$parent = referencePath.parentPath.parentPath) === null || _referencePath$parent === void 0 ? void 0 : _referencePath$parent.node.type) == `MemberExpression`);
94
- assert(referencePath.parentPath.parentPath.node.property.type == `Identifier`);
95
- assert(/^[_a-z][\d_a-z]{0,24}$/.test(referencePath.parent.property.name), `invalid user "${referencePath.parent.property.name}" in subscript`);
96
- assert(/^[_a-z][\d_a-z]{0,24}$/.test(referencePath.parentPath.parentPath.node.property.name), `invalid script name "${referencePath.parentPath.parentPath.node.property.name}" in subscript`);
97
- if (((_referencePath$parent2 = referencePath.parentPath.parentPath.parentPath) === null || _referencePath$parent2 === void 0 ? void 0 : _referencePath$parent2.type) == `CallExpression`) {
98
- // BUG this is causing typescript to be slow
99
- referencePath.parentPath.parentPath.replaceWith(t.identifier(`$${uniqueID}$SUBSCRIPT$${referencePath.parent.property.name}$${referencePath.parentPath.parentPath.node.property.name}$`));
100
- } else {
101
- // BUG this is causing typescript to be slow
102
- referencePath.parentPath.parentPath.replaceWith(t.arrowFunctionExpression([t.restElement(t.identifier(`args`))], t.callExpression(t.identifier(`$${uniqueID}$SUBSCRIPT$${referencePath.parent.property.name}$${referencePath.parentPath.parentPath.node.property.name}$`), [t.spreadElement(t.identifier(`args`))])));
103
- }
104
- }
105
- };
106
- for (const fakeSubscriptObjectName of [`$fs`, `$4s`, `$s`]) {
107
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) processFakeSubscriptObject(fakeSubscriptObjectName);
108
- }
109
- for (const fakeSubscriptObjectName of [`$hs`, `$3s`]) {
110
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
111
- detectedSeclevel = 3;
112
- processFakeSubscriptObject(fakeSubscriptObjectName);
113
- }
114
- }
115
- for (const fakeSubscriptObjectName of [`$ms`, `$2s`]) {
116
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
117
- detectedSeclevel = 2;
118
- processFakeSubscriptObject(fakeSubscriptObjectName);
119
- }
120
- }
121
- for (const fakeSubscriptObjectName of [`$ls`, `$1s`]) {
122
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
123
- detectedSeclevel = 1;
124
- processFakeSubscriptObject(fakeSubscriptObjectName);
125
- }
126
- }
127
- for (const fakeSubscriptObjectName of [`$ns`, `$0s`]) {
128
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
129
- detectedSeclevel = 0;
130
- processFakeSubscriptObject(fakeSubscriptObjectName);
131
- }
132
- }
133
- seclevel = Math.min(seclevel, detectedSeclevel);
134
- if (program.scope.hasGlobal(`$db`)) {
135
- for (const referencePath of getReferencePathsToGlobal(`$db`, program)) {
136
- var _referencePath$parent3;
137
- assert(referencePath.parentPath.node.type == `MemberExpression`);
138
- assert(referencePath.parentPath.node.property.type == `Identifier`);
139
- const databaseOpMethodName = referencePath.parentPath.node.property.name;
140
- assert(validDBMethods.includes(databaseOpMethodName), `invalid db method "${databaseOpMethodName}", valid db methods are "${validDBMethods.join(`", "`)}"`);
141
- if (((_referencePath$parent3 = referencePath.parentPath.parentPath) === null || _referencePath$parent3 === void 0 ? void 0 : _referencePath$parent3.type) == `CallExpression`) referencePath.parentPath.replaceWith(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`));else if (databaseOpMethodName == `ObjectId`) {
142
- referencePath.parentPath.replaceWith(t.arrowFunctionExpression([], t.callExpression(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`), [])));
143
- } else if (databaseOpMethodName == `i` || databaseOpMethodName == `r`) {
144
- referencePath.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier(`a`)], t.callExpression(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`), [t.identifier(`a`)])));
145
- } else {
146
- referencePath.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier(`a`), t.identifier(`b`)], t.callExpression(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`), [t.identifier(`a`), t.identifier(`b`)])));
147
- }
148
- }
149
- }
150
- if (program.scope.hasGlobal(`$D`)) {
151
- for (const referencePath of getReferencePathsToGlobal(`$D`, program)) {
152
- if (referencePath.parentPath.type == `CallExpression`) referencePath.replaceWith(t.identifier(`$${uniqueID}$DEBUG$`));else {
153
- referencePath.replaceWith(t.arrowFunctionExpression([t.identifier(`a`)], t.callExpression(t.identifier(`$${uniqueID}$DEBUG$`), [t.identifier(`a`)])));
154
- }
155
- }
156
- }
157
- if (program.scope.hasGlobal(`$FMCL`)) {
158
- for (const referencePath of getReferencePathsToGlobal(`$FMCL`, program)) referencePath.replaceWith(t.identifier(`$${uniqueID}$FMCL$`));
159
- }
160
- if (program.scope.hasGlobal(`$G`)) {
161
- for (const referencePath of getReferencePathsToGlobal(`$G`, program)) referencePath.replaceWith(t.identifier(`$${uniqueID}$GLOBAL$`));
162
- }
163
- if (program.scope.hasGlobal(`_SECLEVEL`)) {
164
- for (const referencePath of getReferencePathsToGlobal(`_SECLEVEL`, program)) referencePath.replaceWith(t.numericLiteral(seclevel));
165
- }
166
- let needGetPrototypeOf = false;
167
- let needSetPrototypeOf = false;
168
- if (program.scope.hasGlobal(`Object`)) {
169
- for (const referencePath of getReferencePathsToGlobal(`Object`, program)) {
170
- if (referencePath.parent.type != `MemberExpression` || referencePath.parent.computed) continue;
171
- assert(referencePath.parent.property.type == `Identifier`);
172
- if (referencePath.parent.property.name == `getPrototypeOf`) {
173
- referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_GET_PROTOTYPE_OF_`));
174
- needGetPrototypeOf = true;
175
- } else if (referencePath.parent.property.name == `setPrototypeOf`) {
176
- referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_SET_PROTOTYPE_OF_`));
177
- needSetPrototypeOf = true;
178
- }
179
- }
180
- }
181
-
182
- // rollup removes all the inline exports and places a statement at the end instead
183
- const lastStatement = program.node.body.at(-1);
184
- let exportDefaultName;
185
- assert(lastStatement, `program is empty`);
186
- if (lastStatement.type == `ExportNamedDeclaration`) {
187
- program.node.body.pop();
188
- for (const specifier of lastStatement.specifiers) {
189
- assert(specifier.type == `ExportSpecifier`, `${specifier.type} is currently unsupported`);
190
- const exportedName = specifier.exported.type == `Identifier` ? specifier.exported.name : specifier.exported.value;
191
- if (exportedName == `default`) exportDefaultName = specifier.local.name;else exports.set(specifier.local.name, exportedName);
192
- }
193
- }
194
- const globalBlock = t.blockStatement([]);
195
- let mainFunction;
196
- for (const statement of program.node.body) {
197
- if (statement.type == `VariableDeclaration`) {
198
- for (const declarator of statement.declarations) {
199
- if (declarator.id.type == `Identifier` && declarator.id.name == exportDefaultName && declarator.init && (declarator.init.type == `FunctionExpression` || declarator.init.type == `ArrowFunctionExpression`) && !declarator.init.async && !declarator.init.generator) {
200
- mainFunction = t.functionDeclaration(t.identifier(topFunctionName), declarator.init.params, declarator.init.body.type == `BlockStatement` ? declarator.init.body : t.blockStatement([t.returnStatement(declarator.init.body)]));
201
- continue;
202
- }
203
- for (const identifierName in t.getBindingIdentifiers(declarator.id)) {
204
- if (identifierName == exportDefaultName) {
205
- mainFunction = t.functionDeclaration(t.identifier(topFunctionName), [t.identifier(`context`), t.identifier(`args`)], t.blockStatement([t.returnStatement(t.callExpression(t.identifier(exportDefaultName), []))]));
206
- }
207
- if (statement.kind != `const` && exports.has(identifierName)) {
208
- liveExports.set(identifierName, exports.get(identifierName));
209
- exports.delete(identifierName);
210
- }
211
- globalBlock.body.push(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(identifierName))]));
212
- }
213
- if (declarator.init) {
214
- globalBlock.body.push(t.expressionStatement(t.assignmentExpression(`=`, declarator.id, declarator.init)));
215
- }
216
- }
217
- } else if (statement.type == `FunctionDeclaration`) {
218
- if (statement.id.name == exportDefaultName) mainFunction = statement;else {
219
- globalBlock.body.push(t.variableDeclaration(`let`, [t.variableDeclarator(statement.id, t.functionExpression(undefined, statement.params, statement.body, statement.generator, statement.async))]));
220
- }
221
- } else globalBlock.body.push(statement);
222
- }
223
- mainFunction || (mainFunction = t.functionDeclaration(t.identifier(topFunctionName), [t.identifier(`context`), t.identifier(`args`)], t.blockStatement([])));
224
- program.node.body = [mainFunction];
225
- if (globalBlock.body.length) {
226
- if (exports.size || liveExports.size) {
227
- mainFunction.body.body.push(t.returnStatement(t.objectExpression([...[...exports].map(([local, exported]) => t.objectProperty(t.identifier(exported), t.identifier(local))), ...[...liveExports].map(([local, exported]) => t.objectMethod(`get`, t.identifier(exported), [], t.blockStatement([t.returnStatement(t.identifier(local))])))])));
228
- }
229
- program.scope.crawl();
230
- const globalBlockVariables = new Set();
231
- let hoistedGlobalBlockFunctions = 0;
232
- for (const [globalBlockIndex, globalBlockStatement] of [...globalBlock.body.entries()].reverse()) {
233
- if (globalBlockStatement.type == `VariableDeclaration`) {
234
- assert(globalBlockStatement.declarations.length == 1);
235
- const declarator = globalBlockStatement.declarations[0];
236
- assert(declarator.id.type == `Identifier`, `declarator.id.type was "${declarator.id.type}"`);
237
- program.scope.crawl();
238
- if (program.scope.hasGlobal(declarator.id.name)) {
239
- globalBlock.body.splice(globalBlockIndex, 1);
240
- const [globalBlockPath] = program.unshiftContainer(`body`, globalBlock);
241
- const [globalBlockStatementPath] = program.unshiftContainer(`body`, globalBlockStatement);
242
- program.scope.crawl();
243
- if (!declarator.init || declarator.init.type != `FunctionExpression` && declarator.init.type != `ArrowFunctionExpression` || Object.keys(program.scope.globals).some(global => globalBlockVariables.has(global))) {
244
- const binding = program.scope.getBinding(declarator.id.name);
245
- assert(binding);
246
- for (const referencePath of binding.referencePaths) {
247
- assert(referencePath.node.type == `Identifier`);
248
- referencePath.replaceWith(t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(referencePath.node.name)));
249
- }
250
- for (const referencePath of binding.constantViolations) {
251
- if (referencePath.node.type != `AssignmentExpression`) continue;
252
- for (const [name, node] of Object.entries(t.getBindingIdentifiers(referencePath.node))) {
253
- if (name == declarator.id.name) {
254
- clearObject(node);
255
- Object.assign(node, t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(name)));
256
- }
257
- }
258
- }
259
- globalBlockPath.remove();
260
- globalBlockStatementPath.remove();
261
- if (declarator.init) {
262
- globalBlock.body.splice(globalBlockIndex, 0, t.expressionStatement(t.assignmentExpression(`=`, t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(declarator.id.name)), declarator.init)));
263
- }
264
- } else {
265
- globalBlockPath.remove();
266
- globalBlockStatementPath.remove();
267
- mainFunction.body.body.unshift(globalBlockStatement);
268
- hoistedGlobalBlockFunctions++;
269
- }
270
- } else globalBlockVariables.add(declarator.id.name);
271
- } else if (globalBlockStatement.type == `ClassDeclaration`) {
272
- program.scope.crawl();
273
- if (program.scope.hasGlobal(globalBlockStatement.id.name)) {
274
- globalBlock.body.splice(globalBlockIndex, 1);
275
- const [globalBlockPath] = program.unshiftContainer(`body`, globalBlock);
276
- const [globalBlockStatementPath] = program.unshiftContainer(`body`, globalBlockStatement);
277
- program.scope.crawl();
278
- const binding = program.scope.getBinding(globalBlockStatement.id.name);
279
- assert(binding);
280
- for (const referencePath of binding.referencePaths) {
281
- assert(referencePath.node.type == `Identifier`);
282
- referencePath.replaceWith(t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(referencePath.node.name)));
283
- }
284
- globalBlockPath.remove();
285
- globalBlockStatementPath.remove();
286
- globalBlock.body.splice(globalBlockIndex, 0, t.expressionStatement(t.assignmentExpression(`=`, t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(globalBlockStatement.id.name)), t.classExpression(undefined, globalBlockStatement.superClass, globalBlockStatement.body, globalBlockStatement.decorators))));
287
- }
288
- }
289
- }
290
- if (program.scope.hasGlobal(`_EXPORTS`)) {
291
- for (const referencePath of getReferencePathsToGlobal(`_EXPORTS`, program)) {
292
- referencePath.replaceWith(t.arrayExpression([...exports.keys(), ...liveExports.keys()].map(name => t.stringLiteral(name))));
293
- }
294
- }
295
- if (globalBlock.body.length) {
296
- mainFunction.body.body.splice(hoistedGlobalBlockFunctions, 0, t.ifStatement(t.unaryExpression(`!`, t.identifier(`$${uniqueID}$FMCL$`)), globalBlock));
297
- }
298
- }
299
- if (functionDotPrototypeIsReferencedMultipleTimes) {
300
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_FUNCTION_DOT_PROTOTYPE_`), createGetFunctionPrototypeNode())]));
301
- }
302
- if (needSetPrototypeOf) {
303
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_SET_PROTOTYPE_OF_`), t.callExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`), t.identifier(`call`)), t.identifier(`bind`)), [t.identifier(`_${uniqueID}_DUNDER_PROTO_SETTER_`)]))]));
304
- }
305
- if (needGetPrototypeOf) {
306
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_GET_PROTOTYPE_OF_`), t.callExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`), t.identifier(`call`)), t.identifier(`bind`)), [t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`)]))]));
307
- }
308
- if (needGetPrototypeOf || needSetPrototypeOf) {
309
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.objectPattern(needGetPrototypeOf ? needSetPrototypeOf ? [t.objectProperty(t.identifier(`get`), t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`)), t.objectProperty(t.identifier(`set`), t.identifier(`_${uniqueID}_DUNDER_PROTO_SETTER_`))] : [t.objectProperty(t.identifier(`get`), t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`))] : [t.objectProperty(t.identifier(`set`), t.identifier(`_${uniqueID}_DUNDER_PROTO_SETTER_`))]), t.callExpression(t.memberExpression(t.identifier(`Object`), t.identifier(`getOwnPropertyDescriptor`)), [t.memberExpression(t.identifier(`Object`), t.identifier(`prototype`)), t.stringLiteral(`__proto__`)]))]));
310
- }
311
- traverse(file, {
312
- BlockStatement({
313
- node: blockStatement
314
- }) {
315
- for (const [index, functionDeclaration] of blockStatement.body.entries()) {
316
- if (functionDeclaration.type != `FunctionDeclaration` || functionDeclaration.generator) continue;
317
- blockStatement.body.splice(index, 1);
318
- blockStatement.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(functionDeclaration.id, t.arrowFunctionExpression(functionDeclaration.params, functionDeclaration.body, functionDeclaration.async))]));
319
- }
320
- },
321
- ClassBody({
322
- node: classBody,
323
- scope,
324
- parent
325
- }) {
326
- assert(t.isClass(parent));
327
- let thisIsReferenced = false;
328
- for (const classMethod of classBody.body) {
329
- if (classMethod.type != `ClassMethod`) continue;
330
- let methodReferencesThis = false;
331
- traverse(classMethod.body, {
332
- ThisExpression(path) {
333
- methodReferencesThis = true;
334
- thisIsReferenced = true;
335
- path.replaceWith(t.identifier(`_${uniqueID}_THIS_`));
336
- },
337
- Function(path) {
338
- path.skip();
339
- }
340
- }, scope);
341
- if (!methodReferencesThis) continue;
342
- if (classMethod.kind == `constructor`) {
343
- const superCalls = [];
344
- traverse(classMethod.body, {
345
- CallExpression(path) {
346
- if (path.node.callee.type == `Super`) superCalls.push(path);
347
- }
348
- }, scope);
349
- if (!superCalls.length) {
350
- classMethod.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), t.callExpression(t.super(), []))]));
351
- } else if (superCalls.length == 1 && superCalls[0].parent.type == `ExpressionStatement` && superCalls[0].parentPath.parentPath.parent == classMethod) {
352
- superCalls[0].parentPath.replaceWith(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), superCalls[0].node)]));
353
- } else {
354
- for (const path of superCalls) {
355
- path.replaceWith(t.assignmentExpression(`=`, t.identifier(`_${uniqueID}_THIS_`), path.node));
356
- }
357
- classMethod.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`))]));
358
- }
359
- continue;
360
- }
361
-
362
- // BUG if the class or a super class overwrites `valueOf()` (or `Object.prototype` isn't even in the chain), this breaks
363
- // TODO track whether the class is extending a class that at some point extends from `Object` (if unsure, assume no)
364
- // TODO track whether any class in the chain overwrites `valueOf()` (if unsure, assume yes)
365
- // TODO for classes that need it, create a super class for this one to extend from with `valueOf()` assigned to an unused name
366
-
367
- classMethod.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), t.callExpression(t.memberExpression(t.super(), t.identifier(`valueOf`)), []))]));
368
- }
369
- if (!parent.superClass && thisIsReferenced) parent.superClass = t.identifier(`Object`);
370
- },
371
- VariableDeclaration({
372
- node: variableDeclaration
373
- }) {
374
- if (variableDeclaration.kind == `const`) variableDeclaration.kind = `let`;
375
- },
376
- ThisExpression(path) {
377
- path.replaceWith(t.identifier(`undefined`));
378
- },
379
- BigIntLiteral(path) {
380
- const bigIntAsNumber = Number(path.node.value);
381
- if (BigInt(bigIntAsNumber) == BigInt(path.node.value)) {
382
- path.replaceWith(t.callExpression(t.identifier(`BigInt`), [t.numericLiteral(bigIntAsNumber)]));
383
- } else {
384
- path.replaceWith(t.callExpression(t.identifier(`BigInt`), [t.stringLiteral(path.node.value)]));
385
- }
386
- }
387
- });
388
- return {
389
- file,
390
- seclevel
391
- };
392
- };
393
-
394
- export { transform as default, transform };
1
+ import e from"@babel/traverse";import i from"@babel/types";import{assert as t}from"@samual/lib/assert";import{clearObject as r}from"@samual/lib/clearObject";import{validDBMethods as n}from"../constants.js";import{getReferencePathsToGlobal as o}from"./shared.js";const{default:a}=e,s=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"],transform=(e,p,{uniqueID:l="00000000000",scriptUser:c="UNKNOWN",scriptName:d="UNKNOWN",seclevel:f=4}={})=>{const b=`_${l}_SCRIPT_`,y=new Map,m=new Map;let $;if(a(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_SOURCE"))for(const e of o("_SOURCE",$))e.replaceWith(i.stringLiteral(p));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of o("_BUILD_DATE",$))e.replaceWith(i.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of o("_SCRIPT_USER",$))1==c?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_USER$`)):e.replaceWith(i.stringLiteral(c));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of o("_SCRIPT_NAME",$))1==d?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(d));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of o("_FULL_SCRIPT_NAME",$))1==c||1==d?e.replaceWith(i.stringLiteral(`$${l}$FULL_SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(`${c}.${d}`));let h=!1;const createGetFunctionPrototypeNode=()=>{for(const e of s)if(!$.scope.hasOwnBinding(e))return i.memberExpression(i.memberExpression(i.identifier(e),i.identifier("constructor")),i.identifier("prototype"));return i.memberExpression(i.memberExpression(i.arrowFunctionExpression([i.identifier("_")],i.identifier("_")),i.identifier("constructor")),i.identifier("prototype"))};if($.scope.hasGlobal("Function")){const e=o("Function",$);if(1==e.length){const i=e[0];t("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const r of e)t("MemberExpression"==r.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==r.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==r.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,r.parentPath.replaceWith(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`));h=!0}}let E=4;const processFakeSubscriptObject=e=>{for(const r of o(e,$))t("MemberExpression"==r.parent.type),t("Identifier"==r.parent.property.type),t("MemberExpression"==r.parentPath.parentPath?.node.type),t("Identifier"==r.parentPath.parentPath.node.property.type),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parent.property.name),`invalid user "${r.parent.property.name}" in subscript`),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parentPath.parentPath.node.property.name),`invalid script name "${r.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==r.parentPath.parentPath.parentPath?.type?r.parentPath.parentPath.replaceWith(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`)):r.parentPath.parentPath.replaceWith(i.arrowFunctionExpression([i.restElement(i.identifier("args"))],i.callExpression(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`),[i.spreadElement(i.identifier("args"))])))};for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(E=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(E=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(E=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(E=0,processFakeSubscriptObject(e));if(f=Math.min(f,E),$.scope.hasGlobal("$db"))for(const e of o("$db",$)){t("MemberExpression"==e.parentPath.node.type),t("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;t(n.includes(r),`invalid db method "${r}", valid db methods are "${n.join('", "')}"`),"CallExpression"==e.parentPath.parentPath?.type?e.parentPath.replaceWith(i.identifier(`$${l}$DB$${r}$`)):"ObjectId"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a")]))):e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a"),i.identifier("b")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a"),i.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of o("$D",$))"CallExpression"==e.parentPath.type?e.replaceWith(i.identifier(`$${l}$DEBUG$`)):e.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DEBUG$`),[i.identifier("a")])));if($.scope.hasGlobal("$FMCL"))for(const e of o("$FMCL",$))e.replaceWith(i.identifier(`$${l}$FMCL$`));if($.scope.hasGlobal("$G"))for(const e of o("$G",$))e.replaceWith(i.identifier(`$${l}$GLOBAL$`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of o("_SECLEVEL",$))e.replaceWith(i.numericLiteral(f));let _=!1,u=!1;if($.scope.hasGlobal("Object"))for(const e of o("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(t("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(i.identifier(`_${l}_GET_PROTOTYPE_OF_`)),_=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(i.identifier(`_${l}_SET_PROTOTYPE_OF_`)),u=!0));const P=$.node.body.at(-1);let x;if(t(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){t("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const i="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==i?x=e.local.name:y.set(e.local.name,i)}}const O=i.blockStatement([]);let D;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const t of e.declarations)if("Identifier"!=t.id.type||t.id.name!=x||!t.init||"FunctionExpression"!=t.init.type&&"ArrowFunctionExpression"!=t.init.type||t.init.async||t.init.generator){for(const r in i.getBindingIdentifiers(t.id))r==x&&(D=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([i.returnStatement(i.callExpression(i.identifier(x),[]))]))),"const"!=e.kind&&y.has(r)&&(m.set(r,y.get(r)),y.delete(r)),O.body.push(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(r))]));t.init&&O.body.push(i.expressionStatement(i.assignmentExpression("=",t.id,t.init)))}else D=i.functionDeclaration(i.identifier(b),t.init.params,"BlockStatement"==t.init.body.type?t.init.body:i.blockStatement([i.returnStatement(t.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==x?D=e:O.body.push(i.variableDeclaration("let",[i.variableDeclarator(e.id,i.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):O.body.push(e);if(D||=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([])),$.node.body=[D],O.body.length){(y.size||m.size)&&D.body.body.push(i.returnStatement(i.objectExpression([...[...y].map((([e,t])=>i.objectProperty(i.identifier(t),i.identifier(e)))),...[...m].map((([e,t])=>i.objectMethod("get",i.identifier(t),[],i.blockStatement([i.returnStatement(i.identifier(e))]))))]))),$.scope.crawl();const e=new Set;let n=0;for(const[o,a]of[...O.body.entries()].reverse())if("VariableDeclaration"==a.type){t(1==a.declarations.length);const s=a.declarations[0];if(t("Identifier"==s.id.type,`declarator.id.type was "${s.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(s.id.name)){O.body.splice(o,1);const[p]=$.unshiftContainer("body",O),[c]=$.unshiftContainer("body",a);if($.scope.crawl(),!s.init||"FunctionExpression"!=s.init.type&&"ArrowFunctionExpression"!=s.init.type||Object.keys($.scope.globals).some((i=>e.has(i)))){const e=$.scope.getBinding(s.id.name);t(e);for(const r of e.referencePaths)t("Identifier"==r.node.type),r.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(r.node.name)));for(const t of e.constantViolations)if("AssignmentExpression"==t.node.type)for(const[e,n]of Object.entries(i.getBindingIdentifiers(t.node)))e==s.id.name&&(r(n),Object.assign(n,i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e))));p.remove(),c.remove(),s.init&&O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(s.id.name)),s.init)))}else p.remove(),c.remove(),D.body.body.unshift(a),n++}else e.add(s.id.name)}else if("ClassDeclaration"==a.type&&($.scope.crawl(),t(a.id,"src/processScript/transform.ts:564:37"),$.scope.hasGlobal(a.id.name))){O.body.splice(o,1);const[e]=$.unshiftContainer("body",O),[r]=$.unshiftContainer("body",a);$.scope.crawl();const n=$.scope.getBinding(a.id.name);t(n);for(const e of n.referencePaths)t("Identifier"==e.node.type),e.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e.node.name)));e.remove(),r.remove(),O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(a.id.name)),i.classExpression(void 0,a.superClass,a.body,a.decorators))))}if($.scope.hasGlobal("_EXPORTS"))for(const e of o("_EXPORTS",$))e.replaceWith(i.arrayExpression([...y.keys(),...m.keys()].map((e=>i.stringLiteral(e)))));O.body.length&&D.body.body.splice(n,0,i.ifStatement(i.unaryExpression("!",i.identifier(`$${l}$FMCL$`)),O))}return h&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_SET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_SETTER_`)]))])),_&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_GET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)]))])),(_||u)&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.objectPattern(_?u?[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)),i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]:[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`))]:[i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]),i.callExpression(i.memberExpression(i.identifier("Object"),i.identifier("getOwnPropertyDescriptor")),[i.memberExpression(i.identifier("Object"),i.identifier("prototype")),i.stringLiteral("__proto__")]))])),a(e,{BlockStatement({node:e}){for(const[t,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(t,1),e.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(r.id,i.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:r,parent:n}){t(i.isClass(n));let o=!1;for(const t of e.body){if("ClassMethod"!=t.type)continue;let e=!1;if(a(t.body,{ThisExpression(t){e=!0,o=!0,t.replaceWith(i.identifier(`_${l}_THIS_`))},Function(e){e.skip()}},r),e)if("constructor"!=t.kind)t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.memberExpression(i.super(),i.identifier("valueOf")),[]))]));else{const e=[];if(a(t.body,{CallExpression(i){"Super"==i.node.callee.type&&e.push(i)}},r),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==t)e[0].parentPath.replaceWith(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),e[0].node)]));else{for(const t of e)t.replaceWith(i.assignmentExpression("=",i.identifier(`_${l}_THIS_`),t.node));t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`))]))}else t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.super(),[]))]))}}!n.superClass&&o&&(n.superClass=i.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(i.identifier("undefined"))},BigIntLiteral(e){const t=Number(e.node.value);BigInt(t)==BigInt(e.node.value)?e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.numericLiteral(t)])):e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.stringLiteral(e.node.value)]))}}),{file:e,seclevel:f}};export{transform as default,transform};
package/pull.js CHANGED
@@ -1,17 +1 @@
1
- import { copyFilePersistent } from '@samual/lib/copyFilePersistent';
2
- import { resolve } from 'path';
3
-
4
- /**
5
- * Copies script from hackmud to local source folder.
6
- *
7
- * @param sourceFolderPath path to folder containing source files
8
- * @param hackmudPath path to hackmud directory
9
- * @param script to pull in `user.name` format
10
- */
11
- const pull = async (sourceFolderPath, hackmudPath, script) => {
12
- const [user, name] = script.split(`.`);
13
- if (!user || !name) throw new Error(`\`script\` argument must be in "user.name" format`);
14
- await copyFilePersistent(resolve(hackmudPath, user, `scripts`, `${name}.js`), resolve(sourceFolderPath, user, `${name}.js`));
15
- };
16
-
17
- export { pull as default, pull };
1
+ import{copyFilePersistent as t}from"@samual/lib/copyFilePersistent";import{resolve as r}from"path";const pull=async(s,a,i)=>{const[o,e]=i.split(".");if(!o||!e)throw new Error('`script` argument must be in "user.name" format');await t(r(a,o,"scripts",`${e}.js`),r(s,o,`${e}.js`))};export{pull as default,pull};