hackmud-script-manager 0.19.0-50a29ed → 0.19.0-7c69a3b

Sign up to get free protection for your applications and to get access to all the features.
package/watch.js CHANGED
@@ -1 +1,231 @@
1
- import{watch as r}from"chokidar";import{readdir as t,readFile as o,writeFile as e}from"fs/promises";import{extname as i,basename as s,resolve as a}from"path";import{s as n}from"./constants-9bb78688.js";import{generateTypeDeclaration as p}from"./generateTypeDeclaration.js";import{processScript as l}from"./processScript/index.js";import{D as c,w as m}from"./writeFilePersistent-ee9c9bfd.js";import{a as f}from"./assert-22a7ef8a.js";import{c as u}from"./countHackmudCharacters-a08a265f.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-transform-exponentiation-operator";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./spliceString-0e6b5d6d.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.js";import"fs";const watch=async(d,g,{scripts:h=["*.*"],onPush:b,minify:w=!0,mangleNames:y=!1,typeDeclarationPath:j,onReady:S,forceQuineCheats:$}={})=>{if(!h.length)throw new Error("scripts option was an empty array");const v=new c((r=>new Set)),E=new Set,F=new Set;let P=!1;for(const r of h){const[t,o]=r.split(".");t&&"*"!=t?o&&"*"!=o?v.get(o).add(t):E.add(t):o&&"*"!=o?F.add(o):P=!0}const D=r(["*.ts","*.js"],{depth:1,cwd:d,awaitWriteFinish:{stabilityThreshold:100},ignored:"*.d.ts"}).on("change",(async r=>{if(r.endsWith(".d.ts"))return;const e=i(r);if(!n.includes(e))return;const p=s(r,e);if(r==s(r)){if(!(P||E.size||F.has(p)||v.has(p)))return;const e=new c((r=>[]));await Promise.all((await t(d,{withFileTypes:!0})).map((async r=>{if(r.isDirectory())for(const o of await t(a(d,r.name),{withFileTypes:!0})){if(!o.isFile())continue;const t=i(o.name);n.includes(t)&&e.get(s(o.name,t)).push(r.name)}})));const h=new Set;if(P||F.has(p)){for(const r of await t(a(d),{withFileTypes:!0}))r.isDirectory()&&h.add(r.name);for(const r of await t(a(g),{withFileTypes:!0}))r.isDirectory()?h.add(r.name):r.isFile()&&r.name.endsWith(".key")&&h.add(r.name.slice(0,-4));for(const r of v.values())for(const t of r)h.add(t)}for(const r of E)h.add(r);for(const r of v.get(p))h.add(r);const j=[...h].filter((r=>!e.has(r)));if(!j.length)return void(null==b||b({file:r,users:[],minLength:0,error:new Error("no users to push to")}));const S=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),D=a(d,r);let T;try{({script:T}=await l(await o(D,{encoding:"utf-8"}),{minify:w,scriptUser:!0,scriptName:p,uniqueID:S,filePath:D,mangleNames:y,forceQuineCheats:$}))}catch(t){return f(t instanceof Error),void(null==b||b({file:r,users:[],minLength:0,error:t}))}return await Promise.all(j.map((r=>m(a(g,r,`scripts/${p}.js`),T.replace(new RegExp(`\\$${S}\\$SCRIPT_USER\\$`,"g"),r).replace(new RegExp(`\\$${S}\\$FULL_SCRIPT_NAME\\$`,"g"),`${r}.${p}`))))),void(null==b||b({file:r,users:j,minLength:u(T),error:void 0}))}const h=s(a(r,".."));if(!(P||E.size||F.has(p)||v.get(p).has(h)))return;const j=a(d,r),S=await o(j,{encoding:"utf-8"});let D;try{({script:D}=await l(S,{minify:w,scriptUser:h,scriptName:p,filePath:j,mangleNames:y,forceQuineCheats:$}))}catch(t){return f(t instanceof Error),void(null==b||b({file:r,users:[],minLength:0,error:t}))}await m(a(g,h,"scripts",`${p}.js`),D),null==b||b({file:r,users:[h],minLength:u(D),error:void 0})}));if(S&&D.on("ready",S),!j)return;let T=j;const writeTypeDeclaration=async()=>{const r=await p(d,g);try{await e(T,r)}catch(t){if(f(t instanceof Error),"EISDIR"!=t.code)throw t;T=a(T,"player.d.ts"),await e(T,r)}};await writeTypeDeclaration(),D.on("add",writeTypeDeclaration),D.on("unlink",writeTypeDeclaration)};export{watch as default,watch};
1
+ import { DynamicMap } from '@samual/lib/DynamicMap';
2
+ import { assert } from '@samual/lib/assert';
3
+ import { countHackmudCharacters } from '@samual/lib/countHackmudCharacters';
4
+ import { writeFilePersistent } from '@samual/lib/writeFilePersistent';
5
+ import { watch as watch$1 } from 'chokidar';
6
+ import { readdir, readFile, writeFile } from 'fs/promises';
7
+ import { extname, basename, resolve } from 'path';
8
+ import { supportedExtensions } from './constants.js';
9
+ import { generateTypeDeclaration } from './generateTypeDeclaration.js';
10
+ import { processScript } from './processScript/index.js';
11
+ import '@babel/generator';
12
+ import '@babel/parser';
13
+ import '@babel/plugin-proposal-decorators';
14
+ import '@babel/plugin-proposal-destructuring-private';
15
+ import '@babel/plugin-proposal-explicit-resource-management';
16
+ import '@babel/plugin-transform-class-properties';
17
+ import '@babel/plugin-transform-class-static-block';
18
+ import '@babel/plugin-transform-exponentiation-operator';
19
+ import '@babel/plugin-transform-json-strings';
20
+ import '@babel/plugin-transform-logical-assignment-operators';
21
+ import '@babel/plugin-transform-nullish-coalescing-operator';
22
+ import '@babel/plugin-transform-numeric-separator';
23
+ import '@babel/plugin-transform-object-rest-spread';
24
+ import '@babel/plugin-transform-optional-catch-binding';
25
+ import '@babel/plugin-transform-optional-chaining';
26
+ import '@babel/plugin-transform-private-property-in-object';
27
+ import '@babel/plugin-transform-unicode-sets-regex';
28
+ import '@babel/traverse';
29
+ import '@babel/types';
30
+ import '@rollup/plugin-babel';
31
+ import '@rollup/plugin-commonjs';
32
+ import '@rollup/plugin-json';
33
+ import '@rollup/plugin-node-resolve';
34
+ import 'prettier';
35
+ import 'rollup';
36
+ import './processScript/minify.js';
37
+ import '@samual/lib/spliceString';
38
+ import 'acorn';
39
+ import 'terser';
40
+ import './processScript/shared.js';
41
+ import './processScript/postprocess.js';
42
+ import './processScript/preprocess.js';
43
+ import 'import-meta-resolve';
44
+ import './processScript/transform.js';
45
+ import '@samual/lib/clearObject';
46
+
47
+ /**
48
+ * Watches target file or folder for updates and builds and pushes updated file.
49
+ *
50
+ * @param sourceDirectory path to folder containing source files
51
+ * @param hackmudDirectory path to hackmud directory
52
+ * @param options {@link WatchOptions details} and {@link PushOptions more details}
53
+ */
54
+ const watch = async (sourceDirectory, hackmudDirectory, {
55
+ scripts = [`*.*`],
56
+ onPush,
57
+ minify = true,
58
+ mangleNames = false,
59
+ typeDeclarationPath: typeDeclarationPath_,
60
+ onReady,
61
+ forceQuineCheats
62
+ } = {}) => {
63
+ if (!scripts.length) throw new Error(`scripts option was an empty array`);
64
+ const scriptNamesToUsers = new DynamicMap(_scriptName => new Set());
65
+ const wildScriptUsers = new Set();
66
+ const wildUserScripts = new Set();
67
+ let pushEverything = false;
68
+ for (const fullScriptName of scripts) {
69
+ const [user, scriptName] = fullScriptName.split(`.`);
70
+ if (!user || user == `*`) {
71
+ if (!scriptName || scriptName == `*`) pushEverything = true;else wildUserScripts.add(scriptName);
72
+ } else if (!scriptName || scriptName == `*`) wildScriptUsers.add(user);else scriptNamesToUsers.get(scriptName).add(user);
73
+ }
74
+ const watcher = watch$1([`*.ts`, `*.js`], {
75
+ depth: 1,
76
+ cwd: sourceDirectory,
77
+ awaitWriteFinish: {
78
+ stabilityThreshold: 100
79
+ },
80
+ ignored: `*.d.ts`
81
+ }).on(`change`, async path => {
82
+ if (path.endsWith(`.d.ts`)) return;
83
+ const extension = extname(path);
84
+ if (!supportedExtensions.includes(extension)) return;
85
+ const scriptName = basename(path, extension);
86
+
87
+ // if the path is still the same after getting just the base, it means it's directly in the source directory (global)
88
+ if (path == basename(path)) {
89
+ if (!pushEverything && !wildScriptUsers.size && !wildUserScripts.has(scriptName) && !scriptNamesToUsers.has(scriptName)) return;
90
+ const scriptNamesToUsersToSkip = new DynamicMap(_scriptName => []);
91
+ await Promise.all((await readdir(sourceDirectory, {
92
+ withFileTypes: true
93
+ })).map(async dirent => {
94
+ if (!dirent.isDirectory()) return;
95
+ for (const file of await readdir(resolve(sourceDirectory, dirent.name), {
96
+ withFileTypes: true
97
+ })) {
98
+ if (!file.isFile()) continue;
99
+ const fileExtension = extname(file.name);
100
+ if (supportedExtensions.includes(fileExtension)) scriptNamesToUsersToSkip.get(basename(file.name, fileExtension)).push(dirent.name);
101
+ }
102
+ }));
103
+ const usersToPushToSet = new Set();
104
+ if (pushEverything || wildUserScripts.has(scriptName)) {
105
+ for (const dirent of await readdir(resolve(sourceDirectory), {
106
+ withFileTypes: true
107
+ })) {
108
+ if (dirent.isDirectory()) usersToPushToSet.add(dirent.name);
109
+ }
110
+ for (const dirent of await readdir(resolve(hackmudDirectory), {
111
+ withFileTypes: true
112
+ })) {
113
+ if (dirent.isDirectory()) usersToPushToSet.add(dirent.name);else if (dirent.isFile() && dirent.name.endsWith(`.key`)) usersToPushToSet.add(dirent.name.slice(0, -4));
114
+ }
115
+ for (const users of scriptNamesToUsers.values()) {
116
+ for (const user of users) usersToPushToSet.add(user);
117
+ }
118
+ }
119
+ for (const user of wildScriptUsers) usersToPushToSet.add(user);
120
+ for (const user of scriptNamesToUsers.get(scriptName)) usersToPushToSet.add(user);
121
+ const usersToPushTo = [...usersToPushToSet].filter(user => !scriptNamesToUsersToSkip.has(user));
122
+ if (!usersToPushTo.length) {
123
+ onPush?.({
124
+ file: path,
125
+ users: [],
126
+ minLength: 0,
127
+ error: new Error(`no users to push to`)
128
+ });
129
+ return;
130
+ }
131
+ const uniqueID = Math.floor(Math.random() * 2 ** 52).toString(36).padStart(11, `0`);
132
+ const filePath = resolve(sourceDirectory, path);
133
+ let minifiedCode;
134
+ try {
135
+ ({
136
+ script: minifiedCode
137
+ } = await processScript(await readFile(filePath, {
138
+ encoding: `utf-8`
139
+ }), {
140
+ minify,
141
+ scriptUser: true,
142
+ scriptName,
143
+ uniqueID,
144
+ filePath,
145
+ mangleNames,
146
+ forceQuineCheats
147
+ }));
148
+ } catch (error) {
149
+ assert(error instanceof Error);
150
+ onPush?.({
151
+ file: path,
152
+ users: [],
153
+ minLength: 0,
154
+ error
155
+ });
156
+ return;
157
+ }
158
+ await Promise.all(usersToPushTo.map(user => writeFilePersistent(resolve(hackmudDirectory, user, `scripts/${scriptName}.js`), minifiedCode.replace(new RegExp(`\\$${uniqueID}\\$SCRIPT_USER\\$`, `g`), user).replace(new RegExp(`\\$${uniqueID}\\$FULL_SCRIPT_NAME\\$`, `g`), `${user}.${scriptName}`))));
159
+ onPush?.({
160
+ file: path,
161
+ users: usersToPushTo,
162
+ minLength: countHackmudCharacters(minifiedCode),
163
+ error: undefined
164
+ });
165
+ return;
166
+ }
167
+ const user = basename(resolve(path, `..`));
168
+ if (!pushEverything && !wildScriptUsers.size && !wildUserScripts.has(scriptName) && !scriptNamesToUsers.get(scriptName).has(user)) return;
169
+ const filePath = resolve(sourceDirectory, path);
170
+ const sourceCode = await readFile(filePath, {
171
+ encoding: `utf-8`
172
+ });
173
+ let script;
174
+ try {
175
+ ({
176
+ script
177
+ } = await processScript(sourceCode, {
178
+ minify,
179
+ scriptUser: user,
180
+ scriptName,
181
+ filePath,
182
+ mangleNames,
183
+ forceQuineCheats
184
+ }));
185
+ } catch (error) {
186
+ assert(error instanceof Error);
187
+ onPush?.({
188
+ file: path,
189
+ users: [],
190
+ minLength: 0,
191
+ error
192
+ });
193
+ return;
194
+ }
195
+ await writeFilePersistent(resolve(hackmudDirectory, user, `scripts`, `${scriptName}.js`), script);
196
+ onPush?.({
197
+ file: path,
198
+ users: [user],
199
+ minLength: countHackmudCharacters(script),
200
+ error: undefined
201
+ });
202
+ });
203
+ if (onReady) watcher.on(`ready`, onReady);
204
+ if (!typeDeclarationPath_) return;
205
+ let typeDeclarationPath = typeDeclarationPath_;
206
+
207
+ /*
208
+ this currently works because the generated type declaration effectively
209
+ just connects things and doesn't actually read the scripts it's
210
+ generating type declarations for
211
+ if I ever change `generateTypings()` to actually read the scripts to
212
+ grab their types, this will need to change
213
+ */
214
+
215
+ const writeTypeDeclaration = async () => {
216
+ const typeDeclaration = await generateTypeDeclaration(sourceDirectory, hackmudDirectory);
217
+ try {
218
+ await writeFile(typeDeclarationPath, typeDeclaration);
219
+ } catch (error) {
220
+ assert(error instanceof Error);
221
+ if (!(error.code == `EISDIR`)) throw error;
222
+ typeDeclarationPath = resolve(typeDeclarationPath, `player.d.ts`);
223
+ await writeFile(typeDeclarationPath, typeDeclaration);
224
+ }
225
+ };
226
+ await writeTypeDeclaration();
227
+ watcher.on(`add`, writeTypeDeclaration);
228
+ watcher.on(`unlink`, writeTypeDeclaration);
229
+ };
230
+
231
+ export { watch as default, watch };
@@ -1 +0,0 @@
1
- const e=function createErrorClass(e){const r={[e]:class extends Error{}}[e];return Object.defineProperty(r.prototype,"name",{value:e}),r}("AssertError");function assert(r,s="assertion failed"){if(!r)throw new e(s)}function ensure(e,r="ensure failed"){return assert(e,r),e}export{assert as a,ensure as e};
@@ -1 +0,0 @@
1
- const s=[".js",".ts"],t=["i","r","f","u","u1","us","ObjectId"];export{s,t as v};
@@ -1 +0,0 @@
1
- function countHackmudCharacters(u){return u.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000]/g,"").length}export{countHackmudCharacters as c};
@@ -1 +0,0 @@
1
- function spliceString(i,e,s,c=0){return i.slice(0,s)+e+i.slice(s+c)}export{spliceString as s};
@@ -1 +0,0 @@
1
- import e from"fs";import{dirname as r}from"path";class DynamicMap extends Map{constructor(e){super(),this.fallbackHandler=e}get(e){if(super.has(e))return super.get(e);const r=this.fallbackHandler(e);return super.set(e,r),r}}const{writeFile:t,mkdir:s}=e.promises;function writeFilePersistent(e,a,i){return t(e,a,i).catch((async n=>{if("ENOENT"!=n.code)throw n;await s(r(e),{recursive:!0}),await t(e,a,i)}))}export{DynamicMap as D,writeFilePersistent as w};