hackmud-script-manager 0.19.0 → 0.19.1-01c1752

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