-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
282 lines (232 loc) · 8.55 KB
/
Copy pathscripts.js
File metadata and controls
282 lines (232 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import fs from 'fs';
import path from 'path';
import luaparse from 'luaparse';
import zlib from 'node:zlib';
import { Buffer } from 'node:buffer';
function parseLuaSource(source, options = {}) {
const parseOptions = Object.assign(
{ comments: false, scope: false, locations: true, ranges: false, luaVersion: '5.3' },
options
);
return luaparse.parse(source, parseOptions);
}
function walkAst(node, visitor) {
const seen = new WeakSet();
function _walk(n) {
if (!n || typeof n !== 'object') return;
if (seen.has(n)) return;
seen.add(n);
visitor(n);
for (const key of Object.keys(n)) {
const v = n[key];
if (Array.isArray(v)) {
for (const item of v) _walk(item);
} else if (v && typeof v === 'object') {
_walk(v);
}
}
}
_walk(node);
}
function extractRequireModuleNamesFromAst(ast) {
const modules = new Set();
walkAst(ast, (node) => {
if (node.type === 'CallExpression') {
const base = node.base;
const args = node.arguments || node.arguments;
if (base && base.type === 'Identifier' && base.name === 'require') {
const first = Array.isArray(args) && args[0];
if (first && first.type === 'StringLiteral') {
modules.add(first.raw.slice(1, -1));
}
}
}
if (node.type === 'CallStatement' && node.expression && node.expression.type === 'CallExpression') {
const expr = node.expression;
const base = expr.base;
const args = expr.arguments;
if (base && base.type === 'Identifier' && base.name === 'require') {
const first = Array.isArray(args) && args[0];
if (first && first.type === 'StringLiteral') {
modules.add(first.raw.slice(1, -1));
}
}
}
});
return Array.from(modules);
}
function resolveModuleToFile(moduleName, fromFile, projectRoot = undefined) {
const fromDir = path.dirname(fromFile);
function firstExisting(candidates) {
for (const p of candidates) {
try {
const stat = fs.statSync(p);
if (stat && stat.isFile()) return p;
} catch (e) {
}
}
return null;
}
if (moduleName.startsWith('./') || moduleName.startsWith('../') || moduleName.startsWith('/')) {
const candidate = path.resolve(fromDir, moduleName);
const candidates = [
candidate,
candidate.endsWith('.lua') ? null : `${candidate}.lua`,
candidate.endsWith('.lua') ? null : path.join(candidate, 'init.lua'),
].filter(Boolean);
return firstExisting(candidates);
}
const dotPath = moduleName.includes('.') ? moduleName.split('.').join(path.sep) : moduleName;
const slashPath = moduleName.includes('/') ? moduleName : dotPath;
const tryList = [];
tryList.push(path.resolve(fromDir, `${slashPath}.lua`));
tryList.push(path.resolve(fromDir, slashPath, 'init.lua'));
tryList.push(path.resolve(fromDir, slashPath));
if (projectRoot) {
tryList.push(path.resolve(projectRoot, `${slashPath}.lua`));
tryList.push(path.resolve(projectRoot, slashPath, 'init.lua'));
tryList.push(path.resolve(projectRoot, slashPath));
}
tryList.push(path.resolve(fromDir, moduleName));
if (projectRoot) tryList.push(path.resolve(projectRoot, moduleName));
return firstExisting(tryList);
}
function collectUsedFiles(entryFile, projectRoot = process.cwd(), opts = {}) {
const parseOptions = opts.parseOptions || {};
const resolveMissing = opts.resolveMissing ?? false;
const entryAbs = path.resolve(entryFile);
const visited = new Set();
const usedFiles = new Set();
const missing = new Set();
const dependencyMap = new Map();
const stack = [entryAbs];
while (stack.length > 0) {
const file = stack.pop();
if (visited.has(file)) continue;
visited.add(file);
let src;
try {
src = fs.readFileSync(file, 'utf8');
} catch (e) {
missing.add(file);
continue;
}
usedFiles.add(file);
let ast;
try {
ast = parseLuaSource(src, parseOptions);
} catch (e) {
dependencyMap.set(file, [`<parse-error>: ${e.message}`]);
continue;
}
const modules = extractRequireModuleNamesFromAst(ast);
dependencyMap.set(file, []);
for (const modName of modules) {
const resolved = resolveModuleToFile(modName, file, projectRoot);
if (resolved) {
dependencyMap.get(file).push(resolved);
if (!visited.has(resolved)) stack.push(resolved);
} else {
dependencyMap.get(file).push(modName);
missing.add(modName);
if (resolveMissing) {
}
}
}
}
return { usedFiles, missing, dependencyMap };
}
const MAGIC = Buffer.from([0xC4, 0x19, 0x7B, 0xFA]);
const PREFIX = "GLOBED_SCRIPT";
let encodeScript = ({
prefix = PREFIX,
filename = '',
content = '',
isMain = false,
signature = null,
tail = null,
} = {}) => {
const prefixBytes = Buffer.from(prefix, 'utf8');
const headerStart = Buffer.concat([prefixBytes, Buffer.from([0x00]), MAGIC]);
const parts = [];
parts.push(Buffer.from([isMain ? 1 : 0]));
const filenameBuf = Buffer.from(filename, 'utf8');
if (filenameBuf.length > 0xFFFF) {
throw new RangeError(`Filename is too long: ${filenameBuf.length} bytes (max 65535).`);
}
const filenameSizeBuf = Buffer.alloc(2);
filenameSizeBuf.writeUInt16LE(filenameBuf.length, 0);
parts.push(filenameSizeBuf, filenameBuf);
const contentBuf = Buffer.from(content, 'utf8');
if (contentBuf.length > 0xFFFFFFFF) {
throw new RangeError(`Content is too long: ${contentBuf.length} bytes (max 2^32-1).`);
}
const contentSizeBuf = Buffer.alloc(4);
contentSizeBuf.writeUInt32LE(contentBuf.length, 0);
parts.push(contentSizeBuf, contentBuf);
if (signature != null) {
if (!Buffer.isBuffer(signature) || signature.length !== 32) {
throw new TypeError('signature must be a Buffer of length 32 if provided.');
}
parts.push(Buffer.from([1]), signature);
} else {
parts.push(Buffer.from([0]));
}
if (tail != null) {
if (!Buffer.isBuffer(tail)) throw new TypeError('tail must be a Buffer if provided.');
parts.push(tail);
}
const data = Buffer.concat(parts);
const dataSizeBuf = Buffer.alloc(4);
dataSizeBuf.writeUInt32LE(data.length, 0);
const compressed = zlib.zstdCompressSync(data, {
params: { [zlib.constants.ZSTD_c_compressionLevel]: 8 }
});
return Buffer.concat([headerStart, dataSizeBuf, compressed]);
}
function normalizeScriptFilename(filePath, projectRoot) {
const relativePath = path.relative(projectRoot, filePath).replace(/\\/g, '/');
return relativePath || path.basename(filePath);
}
function createScriptObjects(entryAbs, tree, projectRoot, opts = {}) {
const scripts = [];
const usedFiles = Array.from(tree.usedFiles);
for (const filePath of usedFiles) {
const filename = normalizeScriptFilename(filePath, projectRoot);
const content = fs.readFileSync(filePath, 'utf8');
const encoded = encodeScript({ content: 'local exports = require(".exports.lua")\n'+content, filename, isMain: filePath === entryAbs });
const script = encoded.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_');
if (opts.addObjects !== false) {
object({
OBJ_ID: 914,
Y: -10000,
TEXT: script
}).add();
}
scripts.push({
filePath,
filename,
content,
base64: script,
isMain: filePath === entryAbs,
});
}
return scripts;
}
function project(entryFile, opts = {}) {
const entryAbs = path.resolve(entryFile);
const projectRoot = opts.projectRoot ? path.resolve(opts.projectRoot) : path.dirname(entryAbs);
const tree = collectUsedFiles(entryAbs, projectRoot, opts);
const scripts = createScriptObjects(entryAbs, tree, projectRoot, opts);
return {
entry: entryAbs,
projectRoot,
usedFiles: Array.from(tree.usedFiles),
missing: Array.from(tree.missing),
dependencyMap: tree.dependencyMap,
scripts,
};
}
export { project, encodeScript }