hackmud-script-manager-ng 0.26.5 → 0.26.6

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.
Files changed (69) hide show
  1. package/bin/hsm.d.ts +2 -0
  2. package/bin/hsm.js +493 -0
  3. package/constants.d.ts +2 -0
  4. package/constants.js +3 -0
  5. package/generateTypeDeclaration.d.ts +1 -0
  6. package/generateTypeDeclaration.js +70 -0
  7. package/index.d.ts +16 -0
  8. package/index.js +52 -0
  9. package/package.json +3 -22
  10. package/processScript/index.d.ts +34 -0
  11. package/processScript/index.js +362 -0
  12. package/processScript/minify.d.ts +20 -0
  13. package/processScript/minify.js +431 -0
  14. package/processScript/postprocess.d.ts +1 -0
  15. package/processScript/postprocess.js +21 -0
  16. package/processScript/preprocess.d.ts +11 -0
  17. package/processScript/preprocess.js +107 -0
  18. package/processScript/shared.d.ts +5 -0
  19. package/processScript/shared.js +32 -0
  20. package/processScript/transform.d.ts +24 -0
  21. package/processScript/transform.js +803 -0
  22. package/pull.d.ts +7 -0
  23. package/pull.js +11 -0
  24. package/push.d.ts +42 -0
  25. package/push.js +164 -0
  26. package/syncMacros.d.ts +4 -0
  27. package/syncMacros.js +42 -0
  28. package/watch.d.ts +19 -0
  29. package/watch.js +220 -0
  30. package/.envrc +0 -1
  31. package/.github/FUNDING.yml +0 -14
  32. package/.github/workflows/publish.yml +0 -27
  33. package/.github/workflows/test.yml +0 -18
  34. package/.vscode/settings.json +0 -55
  35. package/CONTRIBUTING.md +0 -68
  36. package/eslint.config.js +0 -81
  37. package/game-scripts-tests/array-rest-works.ts +0 -6
  38. package/game-scripts-tests/this_array_in_object.ts +0 -16
  39. package/game-scripts-tests/this_function_array.ts +0 -9
  40. package/game-scripts-tests/this_in_default_argument.ts +0 -35
  41. package/game-scripts-tests/this_in_lambda_in_object.ts +0 -26
  42. package/pnpm-workspace.yaml +0 -2
  43. package/rollup.config.js +0 -69
  44. package/scripts/dev.sh +0 -3
  45. package/scripts/emit-declarations.sh +0 -3
  46. package/scripts/emit-package-json.js +0 -9
  47. package/scripts/lint.sh +0 -5
  48. package/scripts/package.sh +0 -7
  49. package/scripts/update.sh +0 -4
  50. package/scripts/version-dev.js +0 -14
  51. package/src/bin/hsm.ts +0 -754
  52. package/src/constants.ts +0 -2
  53. package/src/env.d.ts +0 -13
  54. package/src/generateTypeDeclaration.ts +0 -119
  55. package/src/index.ts +0 -13
  56. package/src/processScript/__snapshots__/index.ts.snap +0 -8
  57. package/src/processScript/index.ts +0 -474
  58. package/src/processScript/minify.ts +0 -594
  59. package/src/processScript/postprocess.ts +0 -19
  60. package/src/processScript/preprocess.ts +0 -130
  61. package/src/processScript/shared.ts +0 -33
  62. package/src/processScript/transform.ts +0 -978
  63. package/src/pull.ts +0 -20
  64. package/src/push.ts +0 -200
  65. package/src/syncMacros.ts +0 -53
  66. package/src/tsconfig.json +0 -14
  67. package/src/watch.ts +0 -258
  68. package/tsconfig.json +0 -23
  69. package/vitest.config.ts +0 -19
@@ -0,0 +1,431 @@
1
+ import ahc5w59yx7outk8kyghgeyuy from "@babel/generator"
2
+ import w5m3g6w58my4352jqaq8zmhm from "@babel/traverse"
3
+ import t from "@babel/types"
4
+ import { assert } from "@samual/lib/assert"
5
+ import { countHackmudCharacters } from "@samual/lib/countHackmudCharacters"
6
+ import { spliceString } from "@samual/lib/spliceString"
7
+ import { tokenizer, tokTypes } from "acorn"
8
+ import * as terser from "terser"
9
+ import { getReferencePathsToGlobal, replaceUnsafeStrings, includesIllegalString } from "./shared.js"
10
+ const generate = ahc5w59yx7outk8kyghgeyuy.default,
11
+ traverse = w5m3g6w58my4352jqaq8zmhm.default,
12
+ minifyNumber = async number =>
13
+ /\$\((?<number>.+)\)/.exec((await terser.minify(`$(${number})`, { ecma: 2015 })).code).groups.number
14
+ async function minify(file, { uniqueId = "00000000000", mangleNames = !1, forceQuineCheats } = {}) {
15
+ assert(/^\w{11}$/.exec(uniqueId), "src/processScript/minify.ts:46:36")
16
+ let program
17
+ traverse(file, {
18
+ Program(path) {
19
+ program = path
20
+ path.skip()
21
+ }
22
+ })
23
+ if (program.scope.hasGlobal("_START"))
24
+ for (const referencePath of getReferencePathsToGlobal("_START", program))
25
+ referencePath.replaceWith(t.identifier("_ST"))
26
+ if (program.scope.hasGlobal("_TIMEOUT"))
27
+ for (const referencePath of getReferencePathsToGlobal("_TIMEOUT", program))
28
+ referencePath.replaceWith(t.identifier("_TO"))
29
+ const mainFunctionPath = program.get("body.0")
30
+ for (const parameter of [...mainFunctionPath.node.params].reverse()) {
31
+ if ("Identifier" != parameter.type || mainFunctionPath.scope.getBinding(parameter.name).referenced) break
32
+ mainFunctionPath.node.params.pop()
33
+ }
34
+ for (const global in program.scope.globals) {
35
+ if ("arguments" == global || global.startsWith(`$${uniqueId}$`)) continue
36
+ const referencePaths = getReferencePathsToGlobal(global, program)
37
+ if (!(5 + global.length + referencePaths.length >= global.length * referencePaths.length)) {
38
+ for (const path of referencePaths) path.replaceWith(t.identifier(`_${uniqueId}_GLOBAL_${global}_`))
39
+ mainFunctionPath.node.body.body.unshift(
40
+ t.variableDeclaration("let", [
41
+ t.variableDeclarator(t.identifier(`_${uniqueId}_GLOBAL_${global}_`), t.identifier(global))
42
+ ])
43
+ )
44
+ }
45
+ }
46
+ const jsonValues = []
47
+ let scriptBeforeJSONValueReplacement,
48
+ comment,
49
+ undefinedIsReferenced = !1
50
+ if (1 != forceQuineCheats) {
51
+ const fileBeforeJSONValueReplacement = t.cloneNode(file)
52
+ traverse(fileBeforeJSONValueReplacement, {
53
+ MemberExpression({ node: memberExpression }) {
54
+ if (!memberExpression.computed) {
55
+ assert("Identifier" == memberExpression.property.type, "src/processScript/minify.ts:114:60")
56
+ if ("prototype" == memberExpression.property.name) {
57
+ memberExpression.computed = !0
58
+ memberExpression.property = t.identifier(`_${uniqueId}_PROTOTYPE_PROPERTY_`)
59
+ } else if ("__proto__" == memberExpression.property.name) {
60
+ memberExpression.computed = !0
61
+ memberExpression.property = t.identifier(`_${uniqueId}_PROTO_PROPERTY_`)
62
+ } else if (includesIllegalString(memberExpression.property.name)) {
63
+ memberExpression.computed = !0
64
+ memberExpression.property = t.stringLiteral(
65
+ replaceUnsafeStrings(uniqueId, memberExpression.property.name)
66
+ )
67
+ }
68
+ }
69
+ },
70
+ ObjectProperty({ node: objectProperty }) {
71
+ if ("Identifier" == objectProperty.key.type && includesIllegalString(objectProperty.key.name)) {
72
+ objectProperty.key = t.stringLiteral(replaceUnsafeStrings(uniqueId, objectProperty.key.name))
73
+ objectProperty.shorthand = !1
74
+ }
75
+ },
76
+ StringLiteral({ node }) {
77
+ node.value = replaceUnsafeStrings(uniqueId, node.value)
78
+ },
79
+ TemplateLiteral({ node }) {
80
+ for (const templateElement of node.quasis)
81
+ if (templateElement.value.cooked) {
82
+ templateElement.value.cooked = replaceUnsafeStrings(uniqueId, templateElement.value.cooked)
83
+ templateElement.value.raw = templateElement.value.cooked
84
+ .replaceAll("\\", "\\\\")
85
+ .replaceAll("`", "\\`")
86
+ .replaceAll("${", "$\\{")
87
+ } else templateElement.value.raw = replaceUnsafeStrings(uniqueId, templateElement.value.raw)
88
+ },
89
+ RegExpLiteral(path) {
90
+ path.node.pattern = replaceUnsafeStrings(uniqueId, path.node.pattern)
91
+ delete path.node.extra
92
+ }
93
+ })
94
+ scriptBeforeJSONValueReplacement = (
95
+ await terser.minify(generate(fileBeforeJSONValueReplacement).code, {
96
+ ecma: 2015,
97
+ compress: {
98
+ passes: 1 / 0,
99
+ unsafe: !0,
100
+ unsafe_arrows: !0,
101
+ unsafe_comps: !1,
102
+ unsafe_symbols: !0,
103
+ unsafe_methods: !0,
104
+ unsafe_proto: !0,
105
+ unsafe_regexp: !0,
106
+ unsafe_undefined: !0,
107
+ sequences: !1
108
+ },
109
+ format: { semicolons: !1 },
110
+ keep_classnames: !mangleNames,
111
+ keep_fnames: !mangleNames
112
+ })
113
+ ).code
114
+ .replace(RegExp(`_${uniqueId}_PROTOTYPE_PROPERTY_`, "g"), '"prototype"')
115
+ .replace(RegExp(`_${uniqueId}_PROTO_PROPERTY_`, "g"), '"__proto__"')
116
+ if (0 == forceQuineCheats) return scriptBeforeJSONValueReplacement
117
+ }
118
+ let code,
119
+ hasComment = !1
120
+ {
121
+ const promises = []
122
+ traverse(file, {
123
+ FunctionDeclaration(path) {
124
+ const body = path.get("body")
125
+ body.traverse({
126
+ Function(path) {
127
+ "CallExpression" != path.parent.type && "callee" != path.parentKey && path.skip()
128
+ },
129
+ Loop: path => path.skip(),
130
+ ObjectExpression(path) {
131
+ const o = {}
132
+ parseObjectExpression(path.node, o) &&
133
+ path.replaceWith(t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValues.push(o) - 1}_`))
134
+ },
135
+ ArrayExpression(path) {
136
+ const o = []
137
+ parseArrayExpression(path.node, o) &&
138
+ path.replaceWith(t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValues.push(o) - 1}_`))
139
+ }
140
+ })
141
+ body.traverse({
142
+ TemplateLiteral(path) {
143
+ if ("TaggedTemplateExpression" == path.parent.type) return
144
+ const templateLiteral = path.node
145
+ let replacement = t.stringLiteral(templateLiteral.quasis[0].value.cooked)
146
+ for (let index = 0; index < templateLiteral.expressions.length; index++) {
147
+ const expression = templateLiteral.expressions[index],
148
+ templateElement = templateLiteral.quasis[index + 1]
149
+ replacement = t.binaryExpression("+", replacement, expression)
150
+ templateElement.value.cooked &&
151
+ (replacement = t.binaryExpression(
152
+ "+",
153
+ replacement,
154
+ t.stringLiteral(templateElement.value.cooked)
155
+ ))
156
+ }
157
+ path.replaceWith(replacement)
158
+ },
159
+ MemberExpression({ node: memberExpression }) {
160
+ if (!memberExpression.computed) {
161
+ assert("Identifier" == memberExpression.property.type, "src/processScript/minify.ts:250:62")
162
+ if (!(memberExpression.property.name.length < 3)) {
163
+ memberExpression.computed = !0
164
+ memberExpression.property = t.stringLiteral(memberExpression.property.name)
165
+ }
166
+ }
167
+ },
168
+ UnaryExpression(path) {
169
+ if ("void" == path.node.operator) {
170
+ if ("NumericLiteral" == path.node.argument.type && !path.node.argument.value) {
171
+ path.replaceWith(t.identifier(`_${uniqueId}_UNDEFINED_`))
172
+ undefinedIsReferenced = !0
173
+ }
174
+ } else if ("-" == path.node.operator && "NumericLiteral" == path.node.argument.type) {
175
+ const value = -path.node.argument.value
176
+ promises.push(
177
+ (async () => {
178
+ if ((await minifyNumber(value)).length <= 3) return
179
+ "key" == path.parentKey &&
180
+ "ObjectProperty" == path.parent.type &&
181
+ (path.parent.computed = !0)
182
+ let jsonValueIndex = jsonValues.indexOf(value)
183
+ ;-1 == jsonValueIndex && (jsonValueIndex += jsonValues.push(value))
184
+ path.replaceWith(t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValueIndex}_`))
185
+ })()
186
+ )
187
+ path.skip()
188
+ }
189
+ },
190
+ NullLiteral(path) {
191
+ let jsonValueIndex = jsonValues.indexOf(null)
192
+ ;-1 == jsonValueIndex && (jsonValueIndex += jsonValues.push(null))
193
+ path.replaceWith(t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValueIndex}_`))
194
+ },
195
+ NumericLiteral(path) {
196
+ promises.push(
197
+ (async () => {
198
+ if ((await minifyNumber(path.node.value)).length <= 3) return
199
+ "key" == path.parentKey &&
200
+ "ObjectProperty" == path.parent.type &&
201
+ (path.parent.computed = !0)
202
+ let jsonValueIndex = jsonValues.indexOf(path.node.value)
203
+ ;-1 == jsonValueIndex && (jsonValueIndex += jsonValues.push(path.node.value))
204
+ path.replaceWith(t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValueIndex}_`))
205
+ })()
206
+ )
207
+ },
208
+ StringLiteral(path) {
209
+ if (JSON.stringify(path.node.value).includes("\\u00") || path.toString().length < 4) {
210
+ path.node.value = replaceUnsafeStrings(uniqueId, path.node.value)
211
+ return
212
+ }
213
+ "key" == path.parentKey && "ObjectProperty" == path.parent.type && (path.parent.computed = !0)
214
+ let jsonValueIndex = jsonValues.indexOf(path.node.value)
215
+ ;-1 == jsonValueIndex && (jsonValueIndex += jsonValues.push(path.node.value))
216
+ path.replaceWith(t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValueIndex}_`))
217
+ },
218
+ ObjectProperty({ node }) {
219
+ if (node.computed || "Identifier" != node.key.type || node.key.name.length < 4) return
220
+ let jsonValueIndex = jsonValues.indexOf(node.key.name)
221
+ ;-1 == jsonValueIndex && (jsonValueIndex += jsonValues.push(node.key.name))
222
+ node.computed = !0
223
+ node.key = t.identifier(`_${uniqueId}_JSON_VALUE_${jsonValueIndex}_`)
224
+ },
225
+ RegExpLiteral(path) {
226
+ path.node.pattern = replaceUnsafeStrings(uniqueId, path.node.pattern)
227
+ delete path.node.extra
228
+ }
229
+ })
230
+ path.skip()
231
+ }
232
+ })
233
+ await Promise.all(promises)
234
+ const functionDeclaration = file.program.body[0]
235
+ assert("FunctionDeclaration" == functionDeclaration.type, "src/processScript/minify.ts:352:61")
236
+ if (jsonValues.length) {
237
+ hasComment = !0
238
+ if (1 == jsonValues.length)
239
+ if ("string" != typeof jsonValues[0] || jsonValues[0].includes("\n") || jsonValues[0].includes("\t")) {
240
+ const variableDeclaration = t.variableDeclaration("let", [
241
+ t.variableDeclarator(
242
+ t.identifier(`_${uniqueId}_JSON_VALUE_0_`),
243
+ t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [
244
+ t.memberExpression(
245
+ t.taggedTemplateExpression(
246
+ t.memberExpression(
247
+ t.callExpression(
248
+ t.identifier(`$${uniqueId}$4$SUBSCRIPT$scripts$quine$`),
249
+ []
250
+ ),
251
+ t.identifier("split")
252
+ ),
253
+ t.templateLiteral([t.templateElement({ raw: "\t", cooked: "\t" }, !0)], [])
254
+ ),
255
+ t.identifier(`$${uniqueId}$SPLIT_INDEX$`),
256
+ !0
257
+ )
258
+ ])
259
+ )
260
+ ])
261
+ undefinedIsReferenced &&
262
+ variableDeclaration.declarations.push(
263
+ t.variableDeclarator(t.identifier(`_${uniqueId}_UNDEFINED_`))
264
+ )
265
+ functionDeclaration.body.body.unshift(variableDeclaration)
266
+ comment = JSON.stringify(jsonValues[0])
267
+ } else {
268
+ const variableDeclaration = t.variableDeclaration("let", [
269
+ t.variableDeclarator(
270
+ t.identifier(`_${uniqueId}_JSON_VALUE_0_`),
271
+ t.memberExpression(
272
+ t.taggedTemplateExpression(
273
+ t.memberExpression(
274
+ t.callExpression(t.identifier(`$${uniqueId}$4$SUBSCRIPT$scripts$quine$`), []),
275
+ t.identifier("split")
276
+ ),
277
+ t.templateLiteral([t.templateElement({ raw: "\t", cooked: "\t" }, !0)], [])
278
+ ),
279
+ t.identifier(`$${uniqueId}$SPLIT_INDEX$`),
280
+ !0
281
+ )
282
+ )
283
+ ])
284
+ undefinedIsReferenced &&
285
+ variableDeclaration.declarations.push(
286
+ t.variableDeclarator(t.identifier(`_${uniqueId}_UNDEFINED_`))
287
+ )
288
+ functionDeclaration.body.body.unshift(variableDeclaration)
289
+ comment = jsonValues[0]
290
+ }
291
+ else {
292
+ const variableDeclaration = t.variableDeclaration("let", [
293
+ t.variableDeclarator(
294
+ t.arrayPattern(jsonValues.map((_, index) => t.identifier(`_${uniqueId}_JSON_VALUE_${index}_`))),
295
+ t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [
296
+ t.memberExpression(
297
+ t.taggedTemplateExpression(
298
+ t.memberExpression(
299
+ t.callExpression(t.identifier(`$${uniqueId}$4$SUBSCRIPT$scripts$quine$`), []),
300
+ t.identifier("split")
301
+ ),
302
+ t.templateLiteral([t.templateElement({ raw: "\t", cooked: "\t" }, !0)], [])
303
+ ),
304
+ t.identifier(`$${uniqueId}$SPLIT_INDEX$`),
305
+ !0
306
+ )
307
+ ])
308
+ )
309
+ ])
310
+ undefinedIsReferenced &&
311
+ variableDeclaration.declarations.push(t.variableDeclarator(t.identifier(`_${uniqueId}_UNDEFINED_`)))
312
+ functionDeclaration.body.body.unshift(variableDeclaration)
313
+ comment = JSON.stringify(jsonValues)
314
+ }
315
+ } else
316
+ undefinedIsReferenced &&
317
+ functionDeclaration.body.body.unshift(
318
+ t.variableDeclaration("let", [t.variableDeclarator(t.identifier(`_${uniqueId}_UNDEFINED_`))])
319
+ )
320
+ code = generate(file).code
321
+ }
322
+ code =
323
+ (
324
+ await terser.minify(code, {
325
+ ecma: 2015,
326
+ compress: {
327
+ passes: 1 / 0,
328
+ unsafe: !0,
329
+ unsafe_arrows: !0,
330
+ unsafe_comps: !1,
331
+ unsafe_symbols: !0,
332
+ unsafe_methods: !0,
333
+ unsafe_proto: !0,
334
+ unsafe_regexp: !0,
335
+ unsafe_undefined: !0,
336
+ sequences: !1
337
+ },
338
+ format: { semicolons: !1, wrap_func_args: !1 },
339
+ keep_classnames: !mangleNames,
340
+ keep_fnames: !mangleNames
341
+ })
342
+ ).code || ""
343
+ if (null != comment) {
344
+ code = spliceString(
345
+ code,
346
+ `\n//\t${comment}\t\n`,
347
+ (function (code) {
348
+ const tokens = tokenizer(code, { ecmaVersion: 2015 })
349
+ tokens.getToken()
350
+ tokens.getToken()
351
+ tokens.getToken()
352
+ let nests = 1
353
+ for (; nests; ) {
354
+ const token = tokens.getToken()
355
+ token.type == tokTypes.parenL ? nests++ : token.type == tokTypes.parenR && nests--
356
+ }
357
+ return tokens.getToken().start
358
+ })(code) + 1
359
+ )
360
+ code = code.replace(
361
+ `$${uniqueId}$SPLIT_INDEX$`,
362
+ await minifyNumber(code.split("\t").findIndex(part => part == comment))
363
+ )
364
+ }
365
+ if (1 == forceQuineCheats) return code
366
+ assert(scriptBeforeJSONValueReplacement, "src/processScript/minify.ts:485:43")
367
+ return countHackmudCharacters(scriptBeforeJSONValueReplacement) <= countHackmudCharacters(code) + Number(hasComment)
368
+ ? scriptBeforeJSONValueReplacement
369
+ : code
370
+ }
371
+ function parseObjectExpression(node, o) {
372
+ if (!node.properties.length) return !1
373
+ for (const property of node.properties) {
374
+ if ("ObjectProperty" != property.type || property.computed) return !1
375
+ assert(
376
+ "Identifier" == property.key.type ||
377
+ "NumericLiteral" == property.key.type ||
378
+ "StringLiteral" == property.key.type,
379
+ "src/processScript/minify.ts:507:4"
380
+ )
381
+ if ("ArrayExpression" == property.value.type) {
382
+ const childArray = []
383
+ if (property.value.elements.length && !parseArrayExpression(property.value, childArray)) return !1
384
+ o["Identifier" == property.key.type ? property.key.name : property.key.value] = childArray
385
+ } else if ("ObjectExpression" == property.value.type) {
386
+ const childObject = {}
387
+ if (property.value.properties.length && !parseObjectExpression(property.value, childObject)) return !1
388
+ o["Identifier" == property.key.type ? property.key.name : property.key.value] = childObject
389
+ } else if ("NullLiteral" == property.value.type)
390
+ o["Identifier" == property.key.type ? property.key.name : property.key.value] = null
391
+ else if (
392
+ "BooleanLiteral" == property.value.type ||
393
+ "NumericLiteral" == property.value.type ||
394
+ "StringLiteral" == property.value.type
395
+ )
396
+ o["Identifier" == property.key.type ? property.key.name : property.key.value] = property.value.value
397
+ else {
398
+ if ("TemplateLiteral" != property.value.type || property.value.expressions.length) return !1
399
+ o["Identifier" == property.key.type ? property.key.name : property.key.value] =
400
+ property.value.quasis[0].value.cooked
401
+ }
402
+ }
403
+ return !0
404
+ }
405
+ function parseArrayExpression(node, o) {
406
+ if (!node.elements.length) return !1
407
+ for (const element of node.elements) {
408
+ if (!element) return !1
409
+ if ("ArrayExpression" == element.type) {
410
+ const childArray = []
411
+ if (element.elements.length && !parseArrayExpression(element, childArray)) return !1
412
+ o.push(childArray)
413
+ } else if ("ObjectExpression" == element.type) {
414
+ const childObject = {}
415
+ if (element.properties.length && !parseObjectExpression(element, childObject)) return !1
416
+ o.push(childObject)
417
+ } else if ("NullLiteral" == element.type) o.push(null)
418
+ else if (
419
+ "BooleanLiteral" == element.type ||
420
+ "NumericLiteral" == element.type ||
421
+ "StringLiteral" == element.type
422
+ )
423
+ o.push(element.value)
424
+ else {
425
+ if ("TemplateLiteral" != element.type || element.expressions.length) return !1
426
+ o.push(element.quasis[0].value.cooked)
427
+ }
428
+ }
429
+ return !0
430
+ }
431
+ export { minify }
@@ -0,0 +1 @@
1
+ export declare const postprocess: (code: string, uniqueId: string, autocomplete: string | undefined) => string;
@@ -0,0 +1,21 @@
1
+ const postprocess = (code, uniqueId, autocomplete) =>
2
+ code
3
+ .replace(/^function\s*[\w$]+\(/, "function(")
4
+ .replace(/(^.+\{)/, "$1" + (autocomplete ? "//" + autocomplete : ""))
5
+ .replace(RegExp(`\\$${uniqueId}\\$\\\\(?:\\\\)?\\$SC_DOLLAR\\$`, "g"), "S\\C$")
6
+ .replace(RegExp(`\\$${uniqueId}\\$\\\\(?:\\\\)?\\$DB_DOLLAR\\$`, "g"), "D\\B$")
7
+ .replace(RegExp(`\\$${uniqueId}\\$\\\\(?:\\\\)?\\$D\\$`, "g"), "_\\_D_S")
8
+ .replace(RegExp(`\\$${uniqueId}\\$\\\\(?:\\\\)?\\$FMCL\\$`, "g"), "_\\_FMCL_")
9
+ .replace(RegExp(`\\$${uniqueId}\\$\\\\(?:\\\\)?\\$G\\$`, "g"), "_\\_G_")
10
+ .replace(RegExp(`\\$${uniqueId}\\$(\\d)\\$SUBSCRIPT\\$(\\w+)\\$(\\w+)\\$`, "g"), "#$1s.$2.$3")
11
+ .replace(RegExp(`\\$${uniqueId}\\$DEBUG\\$`, "g"), "#D")
12
+ .replace(RegExp(`\\$${uniqueId}\\$FMCL\\$`, "g"), "#FMCL")
13
+ .replace(RegExp(`\\$${uniqueId}\\$GLOBAL\\$`, "g"), "#G")
14
+ .replace(RegExp(`\\$${uniqueId}\\$DB\\$(\\w+)\\$`, "g"), "#db.$1")
15
+ .replace(RegExp(`\\$${uniqueId}\\$SLASH_SLASH\\$`, "g"), "/\\/")
16
+ .replace(RegExp(`\\$${uniqueId}\\$NOT_A_SUBSCRIPT\\$(#[\\w\\.]+)\\(\\$`, "g"), "$1\\(")
17
+ .replace(RegExp(`\\$${uniqueId}\\$NOT_A_DB_CALL\\$(\\w+)\\$`, "g"), "#db.$1\\(")
18
+ .replace(RegExp(`\\$${uniqueId}\\$NOT_A_DEBUG_CALL\\$`, "g"), "#D\\(")
19
+ .replace(RegExp(`\\$${uniqueId}\\$NOT_FMCL\\$`, "g"), "#\\FMCL")
20
+ .replace(RegExp(`\\$${uniqueId}\\$NOT_G\\$`, "g"), "#\\G")
21
+ export { postprocess }
@@ -0,0 +1,11 @@
1
+ import type { LaxPartial } from "@samual/lib";
2
+ export type PreprocessOptions = LaxPartial<{
3
+ uniqueId: string;
4
+ }>;
5
+ /**
6
+ * @param code source code for preprocessing
7
+ * @param options {@link PreprocessOptions details}
8
+ */
9
+ export declare function preprocess(code: string, { uniqueId }?: PreprocessOptions): Promise<{
10
+ code: string;
11
+ }>;
@@ -0,0 +1,107 @@
1
+ import ahc5w59yx7outk8kyghgeyuy from "@babel/generator"
2
+ import { parse } from "@babel/parser"
3
+ import w5m3g6w58my4352jqaq8zmhm from "@babel/traverse"
4
+ import t from "@babel/types"
5
+ import { assert } from "@samual/lib/assert"
6
+ import { spliceString } from "@samual/lib/spliceString"
7
+ import { resolve } from "import-meta-resolve"
8
+ const generate = ahc5w59yx7outk8kyghgeyuy.default,
9
+ traverse = w5m3g6w58my4352jqaq8zmhm.default
10
+ async function preprocess(code, { uniqueId = "00000000000" } = {}) {
11
+ assert(/^\w{11}$/.test(uniqueId), "src/processScript/preprocess.ts:20:36")
12
+ const sourceCode = code
13
+ let lengthBefore, file, program
14
+ do {
15
+ lengthBefore = code.length
16
+ code = code
17
+ .replace(/^\s+/, "")
18
+ .replace(/^\/\/.*/, "")
19
+ .replace(/^\/\*[\s\S]*?\*\//, "")
20
+ } while (code.length != lengthBefore)
21
+ code = code.replace(/^function\s*\(/, "export default function (")
22
+ for (;;) {
23
+ let error
24
+ try {
25
+ file = parse(code, {
26
+ plugins: [
27
+ "typescript",
28
+ ["decorators", { decoratorsBeforeExport: !0 }],
29
+ "doExpressions",
30
+ "functionBind",
31
+ "functionSent",
32
+ "partialApplication",
33
+ ["pipelineOperator", { proposal: "hack", topicToken: "%" }],
34
+ "throwExpressions",
35
+ ["recordAndTuple", { syntaxType: "hash" }],
36
+ "classProperties",
37
+ "classPrivateProperties",
38
+ "classPrivateMethods",
39
+ "logicalAssignment",
40
+ "numericSeparator",
41
+ "nullishCoalescingOperator",
42
+ "optionalChaining",
43
+ "optionalCatchBinding",
44
+ "objectRestSpread"
45
+ ],
46
+ sourceType: "module"
47
+ })
48
+ break
49
+ } catch (error_) {
50
+ assert(error_ instanceof SyntaxError, "src/processScript/preprocess.ts:64:42")
51
+ error = error_
52
+ }
53
+ if ("BABEL_PARSER_SYNTAX_ERROR" != error.code || "PrivateInExpectedIn" != error.reasonCode) {
54
+ console.error(/.+/.exec(code.slice(error.pos))?.[0])
55
+ throw error
56
+ }
57
+ const codeSlice = code.slice(error.pos)
58
+ let match
59
+ if ((match = /^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(codeSlice)))
60
+ code = spliceString(code, JSON.stringify(sourceCode), error.pos, match[0].length)
61
+ else if ((match = /^#[0-4fhmln]?s\./.exec(codeSlice))) code = spliceString(code, "$", error.pos, 1)
62
+ else if ((match = /^#D[^\w$]/.exec(codeSlice))) code = spliceString(code, "$", error.pos, 1)
63
+ else if ((match = /^#FMCL/.exec(codeSlice)))
64
+ code = spliceString(code, `$${uniqueId}$FMCL$`, error.pos, match[0].length)
65
+ else if ((match = /^#G/.exec(codeSlice)))
66
+ code = spliceString(code, `$${uniqueId}$GLOBAL$`, error.pos, match[0].length)
67
+ else {
68
+ if (!(match = /^#db\./.exec(codeSlice))) throw error
69
+ code = spliceString(code, "$", error.pos, 1)
70
+ }
71
+ }
72
+ traverse(file, {
73
+ Program(path) {
74
+ program = path
75
+ path.skip()
76
+ }
77
+ })
78
+ const needRecord = program.scope.hasGlobal("Record"),
79
+ needTuple = program.scope.hasGlobal("Tuple")
80
+ ;(needRecord || needTuple) &&
81
+ file.program.body.unshift(
82
+ t.importDeclaration(
83
+ needRecord
84
+ ? needTuple
85
+ ? [
86
+ t.importSpecifier(t.identifier("Record"), t.identifier("Record")),
87
+ t.importSpecifier(t.identifier("Tuple"), t.identifier("Tuple"))
88
+ ]
89
+ : [t.importSpecifier(t.identifier("Record"), t.identifier("Record"))]
90
+ : [t.importSpecifier(t.identifier("Tuple"), t.identifier("Tuple"))],
91
+ t.stringLiteral("@bloomberg/record-tuple-polyfill")
92
+ )
93
+ )
94
+ program.scope.hasGlobal("Proxy") &&
95
+ file.program.body.unshift(
96
+ t.importDeclaration(
97
+ [t.importDefaultSpecifier(t.identifier("Proxy"))],
98
+ t.stringLiteral(resolve("proxy-polyfill/src/proxy.js", import.meta.url).slice(7))
99
+ )
100
+ )
101
+ if (1 == program.node.body.length && "FunctionDeclaration" == program.node.body[0].type)
102
+ throw Error(
103
+ "Scripts that only contain a single function declaration are no longer supported.\nPrefix the function declaration with `export default`."
104
+ )
105
+ return { code: generate(file).code }
106
+ }
107
+ export { preprocess }
@@ -0,0 +1,5 @@
1
+ import type { NodePath } from "@babel/traverse";
2
+ import type { Identifier, Program } from "@babel/types";
3
+ export declare function getReferencePathsToGlobal(name: string, program: NodePath<Program>): NodePath<Identifier>[];
4
+ export declare const includesIllegalString: (toCheck: string) => boolean;
5
+ export declare const replaceUnsafeStrings: (uniqueId: string, toReplace: string) => string;
@@ -0,0 +1,32 @@
1
+ import t from "@babel/types"
2
+ import { ensure } from "@samual/lib/assert"
3
+ function getReferencePathsToGlobal(name, program) {
4
+ const [variableDeclaration] = program.unshiftContainer(
5
+ "body",
6
+ t.variableDeclaration("let", [t.variableDeclarator(t.identifier(name))])
7
+ )
8
+ program.scope.crawl()
9
+ const binding = ensure(program.scope.getBinding(name), "src/processScript/shared.ts:12:57")
10
+ variableDeclaration.remove()
11
+ return binding.referencePaths
12
+ }
13
+ const includesIllegalString = toCheck =>
14
+ toCheck.includes("SC$") ||
15
+ toCheck.includes("DB$") ||
16
+ toCheck.includes("__D_S") ||
17
+ toCheck.includes("__FMCL_") ||
18
+ toCheck.includes("__G_"),
19
+ replaceUnsafeStrings = (uniqueId, toReplace) =>
20
+ toReplace
21
+ .replaceAll("SC$", `$${uniqueId}$\\$SC_DOLLAR$`)
22
+ .replaceAll("DB$", `$${uniqueId}$\\$DB_DOLLAR$`)
23
+ .replaceAll("__D_S", `$${uniqueId}$\\$D$`)
24
+ .replaceAll("__FMCL_", `$${uniqueId}$\\$FMCL$`)
25
+ .replaceAll("__G_", `$${uniqueId}$\\$G$`)
26
+ .replaceAll("//", `$${uniqueId}$SLASH_SLASH$`)
27
+ .replaceAll(/#[0-4fhmln]?s(?:\.[_a-z][\d_a-z]{0,24}){2}\(/g, `$${uniqueId}$NOT_A_SUBSCRIPT$$$&$`)
28
+ .replaceAll(/#db\.(?<methodName>[irfu]|u1|us|ObjectId)\(/g, `$${uniqueId}$NOT_A_DB_CALL$$$1$`)
29
+ .replaceAll("#D(", `$${uniqueId}$NOT_A_DEBUG_CALL$`)
30
+ .replaceAll("#FMCL", `$${uniqueId}$NOT_FMCL$`)
31
+ .replaceAll("#G", `$${uniqueId}$NOT_G$`)
32
+ export { getReferencePathsToGlobal, includesIllegalString, replaceUnsafeStrings }
@@ -0,0 +1,24 @@
1
+ import type { File } from "@babel/types";
2
+ import type { LaxPartial } from "@samual/lib";
3
+ export type TransformOptions = LaxPartial<{
4
+ /** 11 a-z 0-9 characters */ uniqueId: string;
5
+ /** the user going to be hosting this script (or set to `true` if not yet known) */ scriptUser: string | true;
6
+ seclevel: number;
7
+ }> & {
8
+ scriptName: string | true;
9
+ };
10
+ /**
11
+ * transform a given babel `File` to be hackmud compatible
12
+ *
13
+ * (returned File will need `postprocess()`ing)
14
+ * @param file babel ast node representing a file containing preprocessed code
15
+ * @param sourceCode the original untouched source code
16
+ * @param options {@link TransformOptions details}
17
+ */
18
+ export declare function transform(file: File, sourceCode: string, { uniqueId, scriptUser, scriptName, seclevel }: TransformOptions): {
19
+ file: File;
20
+ seclevel: number;
21
+ warnings: {
22
+ message: string;
23
+ }[];
24
+ };