hackmud-script-manager 0.13.0-1a09d06 → 0.13.0-3dccdd1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1 @@
1
+ class CustomError extends Error{constructor(...r){super(...r),function _defineProperty(r,e,s){return e in r?Object.defineProperty(r,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):r[e]=s,r}(this,"name",this.constructor.name)}}class AssertError extends CustomError{}function assert(r,e="assertion failed"){if(!r)throw new AssertError(e)}function ensure(r,e="ensure failed"){return assert(r,e),r}export{assert as a,ensure as e};
package/bin/hsm.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import o from"chalk";import e from"fs";import{homedir as s}from"os";import{resolve as t,basename as r,extname as n,dirname as i,relative as a}from"path";import{supportedExtensions as l,test as c,watch as p,push as g}from"../index.js";import{DynamicMap as m,hackmudLength as b,writeFilePersist as u}from"../lib.js";import{processScript as d}from"../processScript/index.js";import{generateTypings as f}from"../generateTypings.js";import{syncMacros as h}from"../syncMacros.js";import{pull as k}from"../pull.js";import"chokidar";import"@babel/generator";import"perf_hooks";import"../processScript/compile.js";import"@babel/core";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"../processScript/minify.js";import"@babel/parser";import"acorn";import"terser";import"../processScript/postProcess.js";import"../processScript/preProcess.js";const{readFile:w,rmdir:y,writeFile:$,mkdir:j}=e.promises,v=t(s(),".config"),S=t(v,"hsm.json"),P=new Map,x=[];let N;const O=o.rgb(255,244,4),T=o.rgb(243,249,152),E=o.rgb(179,255,155),I=o.rgb(255,150,224),M=o.rgb(30,255,0),U=o.rgb(202,202,202),F=new m((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[O,T,E,I,M,U][e%6](o)}));for(const o of process.argv.slice(2))if("-"==o[0]){const[e,s]=o.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const o=Number(t);isFinite(o)&&(t=o)}else t=!0;if("-"==o[1])P.set(e.slice(2),t);else for(const o of e.slice(1))P.set(o,t)}else x.push(o);function L(){switch(x[0]){case"config":switch(x[1]){case"get":console.log("hsm config get <key>");break;case"set":console.log("hsm config set <key> <value>");break;case"delete":console.log("hsm config delete <key>");break;default:console.log("hsm config <get, delete, set>")}break;case"push":console.log('hsm push [<dir> [..."<script user>.<script name>"]]');break;case"watch":console.log("hsm watch [dir]");break;case"pull":console.log("hsm pull <script user>.<script name>");break;case"minify":case"golf":console.log(`${r(process.argv[1])} ${x[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}async function q(){console.log("0.13.0-1a09d06")}async function D(){return N||(N=await w(S,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${S}`),{}))))}function J(o,e,s=!1){for(const r of e){var t;o=s?"object"==typeof o[r]?o[r]:o[r]={}:null===(t=o)||void 0===t?void 0:t[r]}return o}function R(){if(N){const o=JSON.stringify(N);$(S,o).catch((async e=>{switch(e.code){case"EISDIR":await y(S);break;case"ENOENT":await j(v);break;default:throw e}$(S,o)}))}}function W({file:e,users:s,srcLength:i,minLength:a,error:l}){s.length&&(l?console.log(`error "${o.bold(l.message)}" in ${o.bold(e)}`):console.log(`pushed ${o.bold(e)} to ${s.map((e=>o.bold(F.get(e)))).join(", ")} | ${o.bold(String(a))} chars from ${o.bold(String(i))} | saved ${o.bold(String(i-a))} (${o.bold(`${Math.round(100*(1-a/i))}%`)}) | ${o.bold(`${t(N.hackmudPath,s[0],"scripts",r(e,n(e)))}.js`)}`))}(async()=>{if(P.get("version")||P.get("v"))q();else if(P.get("help")||P.get("h"))L();else{switch(x[0]){case"push":{const o=await D();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=x[1]||".",s=o.hackmudPath,t=x.slice(2);t.length||t.push("*.*");(await g(e,s,{scripts:t,onPush:W,minify:!P.get("skip-minify")})).length||console.warn("couldn't find any scripts to push"),R()}break;case"dev":case"watch":{var e,s,m;const o=await D();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const t=x[1]||".",r=o.hackmudPath,n=(null===(e=P.get("users"))||void 0===e?void 0:e.toString().split(","))||[],i=(null===(s=P.get("scripts"))||void 0===s?void 0:s.toString().split(","))||[],a=null===(m=P.get("gen-types"))||void 0===m?void 0:m.toString();p(t,r,n,i,W,{genTypes:a})}break;case"pull":{const o=await D();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=x[1];if(!e){L();break}const s=x[2]||".",t=o.hackmudPath;try{await k(s,t,e)}catch(o){console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:o}=await D();if(!o){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:e,usersSynced:s}=await h(o);console.log(`synced ${e} macros to ${s} users`)}break;case"test":{const e=t(x[1]||".");let s=0;console.log(`testing scripts in ${o.bold(e)}\n`);for(const{file:t,line:r,message:n}of await c(e))console.log(`error "${o.bold(n)}" in ${o.bold(t)} on line ${o.bold(String(r))}`),s++;if(!s){console.log("no errors found");break}if(s){process.exitCode=1,console.log(`\nencountered ${o.bold(String(s))} errors`);break}console.log("no errors found")}break;case"gen-types":{const o=t(x[1]||".");let e;e=x[2]?t(x[2]):t(o,"../player.d.ts"),f(o,e,(await D()).hackmudPath)}break;case"config":switch(x[1]){case"get":console.log(J(await D(),x[2].split(".")));break;case"delete":{var y;const o=x[2].split(".");if(!o.length){L();break}const e=await D();null===(y=J(e,o))||void 0===y||delete y[x[3]],console.log(e)}break;case"set":{const o=x[2].split(".");if(!o.length){L();break}const e=await D();let s=e;for(let e of o.slice(0,-1))s="object"==typeof s[e]?s[e]:s[e]={};s[o.slice(-1)[0]]=x[3],e.hackmudPath&&(e.hackmudPath=t(e.hackmudPath)),console.log(e)}break;default:x[1]&&console.log("unknown command"),L()}break;case"help":case"h":L();break;case"version":case"v":q();break;case"golf":case"minify":{if(!x[1]){console.log(`Target required\nUsage: ${r(process.argv[1])} ${x[0]} <target> [output]`);break}const e=n(x[1]);if(!l.includes(e)){console.log(`Unsupported file extension "${o.bold(e)}"\nSupported extensions are "${l.map((e=>o.bold(e))).join('", "')}"`);break}await w(x[1],{encoding:"utf-8"}).then((async s=>{const n=r(x[1],e),l=n.endsWith(".src"),c=l?n.slice(0,-4):n;let p="UNKNOWN";"scripts"==r(t(x[1],".."))&&"hackmud"==r(t(x[1],"../../.."))&&(p=r(t(x[1],"../..")));const{script:g,srcLength:m,warnings:f,timeTook:h}=await d(s,{minify:!P.get("skip-minify"),scriptUser:p,scriptName:c});for(const{message:e,line:s}of f)console.log(`warning "${o.bold(e)}" on line ${o.bold(String(s))}`);let k;k=x[2]?x[2]:t(i(x[1]),l?`${c}.js`:".js"==e?`${n}.min.js`:`${n}.js`);const w=b(g);await u(k,g).catch((async o=>{if(!x[2]||"EISDIR"!=o.code)throw o;k=t(k,`${r(x[1],e)}.js`),await u(k,g)})).then((()=>console.log(`wrote ${o.bold(w)} chars to ${o.bold(a(".",k))} | saved ${o.bold(m-w)} chars | took ${Math.round(100*h)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}break;default:x[0]&&console.log("unknown command"),L()}R()}})();
2
+ import o from"fs";import{resolve as e,basename as s,extname as t,dirname as r,relative as n}from"path";import{c as i}from"../processScript/minify.js";import{D as a,push as l}from"../push.js";import{w as c}from"../writeFilePersistent-4e3ff264.js";import p from"chalk";import{homedir as g}from"os";import{s as m,processScript as u}from"../processScript/index.js";import{generateTypings as f}from"../generateTypings.js";import{pull as b}from"../pull.js";import{syncMacros as d}from"../syncMacros.js";import{test as h}from"../test.js";import{watch as k}from"../watch.js";import"@babel/generator";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"../assert-1b7dada8.js";import"../spliceString-2c6f214f.js";import"acorn";import"terser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"../processScript/postprocess.js";import"../processScript/preprocess.js";import"../processScript/transform.js";import"chokidar";const{readFile:w,rmdir:y,writeFile:j,mkdir:$}=o.promises,v=e(g(),".config"),P=e(v,"hsm.json"),S=new Map,C=[];let x;const N=p.rgb(255,244,4),O=p.rgb(243,249,152),L=p.rgb(179,255,155),T=p.rgb(255,150,224),E=p.rgb(30,255,0),F=p.rgb(202,202,202),I=new a((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[N,O,L,T,E,F][e%6](o)}));for(const o of process.argv.slice(2))if("-"==o[0]){const[e,s]=o.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const o=Number(t);isFinite(o)&&(t=o)}else t=!0;if("-"==o[1])S.set(e.slice(2),t);else for(const o of e.slice(1))S.set(o,t)}else C.push(o);function help(){switch(C[0]){case"config":switch(C[1]){case"get":console.log("hsm config get <key>");break;case"set":console.log("hsm config set <key> <value>");break;case"delete":console.log("hsm config delete <key>");break;default:console.log("hsm config <get, delete, set>")}break;case"push":console.log('hsm push [<dir> [..."<script user>.<script name>"]]');break;case"watch":console.log("hsm watch [dir]");break;case"pull":console.log("hsm pull <script user>.<script name>");break;case"minify":case"golf":console.log(`${s(process.argv[1])} ${C[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}async function version(){console.log("0.13.0-3dccdd1")}async function getConfig(){return x||(x=await w(P,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${P}`),{}))))}function exploreObject(o,e,s=!1){for(const r of e){var t;o=s?"object"==typeof o[r]?o[r]:o[r]={}:null===(t=o)||void 0===t?void 0:t[r]}return o}function updateConfig(){if(x){const o=JSON.stringify(x);j(P,o).catch((async e=>{switch(e.code){case"EISDIR":await y(P);break;case"ENOENT":await $(v);break;default:throw e}j(P,o)}))}}function onPushLogger({file:o,users:r,srcLength:n,minLength:i,error:a}){r.length&&(a?console.log(`error "${p.bold(a.message)}" in ${p.bold(o)}`):console.log(`pushed ${p.bold(o)} to ${r.map((o=>p.bold(I.get(o)))).join(", ")} | ${p.bold(String(i))} chars from ${p.bold(String(n))} | saved ${p.bold(String(n-i))} (${p.bold(`${Math.round(100*(1-i/n))}%`)}) | ${p.bold(`${e(x.hackmudPath,r[0],"scripts",s(o,t(o)))}.js`)}`))}(async()=>{if(S.get("version")||S.get("v"))version();else if(S.get("help")||S.get("h"))help();else{switch(C[0]){case"push":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1]||".",s=o.hackmudPath,t=C.slice(2);t.length||t.push("*.*");(await l(e,s,{scripts:t,onPush:onPushLogger,minify:!S.get("skip-minify")})).length||console.warn("couldn't find any scripts to push"),updateConfig()}break;case"dev":case"watch":{var o,a,g;const e=await getConfig();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const s=C[1]||".",t=e.hackmudPath,r=(null===(o=S.get("users"))||void 0===o?void 0:o.toString().split(","))||[],n=(null===(a=S.get("scripts"))||void 0===a?void 0:a.toString().split(","))||[],i=null===(g=S.get("gen-types"))||void 0===g?void 0:g.toString();k(s,t,r,n,onPushLogger,{genTypes:i})}break;case"pull":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1];if(!e){help();break}const s=C[2]||".",t=o.hackmudPath;try{await b(s,t,e)}catch(o){console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:o}=await getConfig();if(!o){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:e,usersSynced:s}=await d(o);console.log(`synced ${e} macros to ${s} users`)}break;case"test":{const o=e(C[1]||".");let s=0;console.log(`testing scripts in ${p.bold(o)}\n`);for(const{file:e,line:t,message:r}of await h(o))console.log(`error "${p.bold(r)}" in ${p.bold(e)} on line ${p.bold(String(t))}`),s++;if(!s){console.log("no errors found");break}if(s){process.exitCode=1,console.log(`\nencountered ${p.bold(String(s))} errors`);break}console.log("no errors found")}break;case"gen-types":{const o=e(C[1]||".");let s;s=C[2]?e(C[2]):e(o,"../player.d.ts"),f(o,s,(await getConfig()).hackmudPath)}break;case"config":switch(C[1]){case"get":console.log(exploreObject(await getConfig(),C[2].split(".")));break;case"delete":{var y;const o=C[2].split(".");if(!o.length){help();break}const e=await getConfig();null===(y=exploreObject(e,o))||void 0===y||delete y[C[3]],console.log(e)}break;case"set":{const o=C[2].split(".");if(!o.length){help();break}const s=await getConfig();let t=s;for(let e of o.slice(0,-1))t="object"==typeof t[e]?t[e]:t[e]={};t[o.slice(-1)[0]]=C[3],s.hackmudPath&&(s.hackmudPath=e(s.hackmudPath)),console.log(s)}break;default:C[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{if(!C[1]){console.log(`Target required\nUsage: ${s(process.argv[1])} ${C[0]} <target> [output]`);break}const o=t(C[1]);if(!m.includes(o)){console.log(`Unsupported file extension "${p.bold(o)}"\nSupported extensions are "${m.map((o=>p.bold(o))).join('", "')}"`);break}await w(C[1],{encoding:"utf-8"}).then((async t=>{const a=s(C[1],o),l=a.endsWith(".src"),g=l?a.slice(0,-4):a;let m="UNKNOWN";"scripts"==s(e(C[1],".."))&&"hackmud"==s(e(C[1],"../../.."))&&(m=s(e(C[1],"../..")));const f=!S.get("skip-minify"),b=Boolean(S.get("mangle-names"));!f&&b&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:d,srcLength:h,warnings:k,timeTook:w}=await u(t,{minify:f,scriptUser:m,scriptName:g,filePath:C[1],mangleNames:b});for(const{message:o,line:e}of k)console.log(`warning "${p.bold(o)}" on line ${p.bold(String(e))}`);let y;y=C[2]?C[2]:e(r(C[1]),l?`${g}.js`:".js"==o?`${a}.min.js`:`${a}.js`);const j=i(d);await c(y,d).catch((async t=>{if(!C[2]||"EISDIR"!=t.code)throw t;y=e(y,`${s(C[1],o)}.js`),await c(y,d)})).then((()=>console.log(`wrote ${p.bold(j)} chars to ${p.bold(n(".",y))} | saved ${p.bold(h-j)} chars | took ${Math.round(100*w)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}break;default:C[0]&&console.log("unknown command"),help()}updateConfig()}})();
@@ -1 +1 @@
1
- import t from"fs";import{extname as e,basename as n,resolve as s}from"path";const{readdir:r,writeFile:o}=t.promises;async function a(t,a,i){const f=new Set;if(i)for(const t of await r(i,{withFileTypes:!0}))t.isFile()&&".key"==e(t.name)&&f.add(n(t.name,".key"));const c=[],l=[],m={},p={};for(const o of await r(t,{withFileTypes:!0}))if(o.isFile())".ts"==e(o.name)?c.push(n(o.name,".ts")):".js"==e(o.name)&&l.push(n(o.name,".js"));else if(o.isDirectory()){const a=m[o.name]=[],i=p[o.name]=[];f.add(o.name);for(const f of await r(s(t,o.name),{withFileTypes:!0}))f.isFile()&&(".ts"==e(f.name)?a.push(n(f.name,".ts")):".js"==e(f.name)&&i.push(n(f.name,".js")))}let $="";for(const t of c)$+=`import { script as $${t}$ } from "./src/${t}"\n`;$+="\n";for(const t in m){const e=m[t];for(const n of e)$+=`import { script as $${t}$${n}$ } from "./src/${t}/${n}"\n`}$+="\ntype ArrayRemoveFirst<A> = A extends [ infer FirstItem, ...infer Rest ] ? Rest : never\n\ntype Subscript<T extends (...args: any) => any> =\n\t(...args: ArrayRemoveFirst<Parameters<T>>) => ReturnType<T> | ScriptFailure\n\ntype WildFullsec = Record<string, () => ScriptFailure> & {\n";for(const t of c)$+=`\t${t}: Subscript<typeof $${t}$>\n`;for(const t of l)$+=`\t${t}: (...args: any) => any\n`;$+="}\n\ndeclare global {\n\tinterface PlayerFullsec {";let y=!0;for(const t of f){const e=m[t],n=p[t];if(e&&e.length||n&&n.length){y=!0,$+=`\n\t\t${t}: WildFullsec & {\n`;for(const n of e)$+=`\t\t\t${n}: Subscript<typeof $${t}$${n}$>\n`;for(const t of n)$+=`\t\t\t${t}: (...args: any) => any\n`;$+="\t\t}"}else y&&($+="\n",y=!1),$+=`\t\t${t}: WildFullsec`;$+="\n"}$+="\t}\n}\n",await o(a,$)}export{a as default,a as generateTypings};
1
+ import e from"fs";import{extname as t,basename as n,resolve as s}from"path";const{readdir:r,writeFile:o}=e.promises;async function generateTypings(e,a,i){const f=new Set;if(i)for(const e of await r(i,{withFileTypes:!0}))e.isFile()&&".key"==t(e.name)&&f.add(n(e.name,".key"));const c=[],l=[],p={},m={};for(const o of await r(e,{withFileTypes:!0}))if(o.isFile())".ts"==t(o.name)?c.push(n(o.name,".ts")):".js"==t(o.name)&&l.push(n(o.name,".js"));else if(o.isDirectory()){const a=p[o.name]=[],i=m[o.name]=[];f.add(o.name);for(const f of await r(s(e,o.name),{withFileTypes:!0}))f.isFile()&&(".ts"==t(f.name)?a.push(n(f.name,".ts")):".js"==t(f.name)&&i.push(n(f.name,".js")))}let y="";for(const e of c)y+=`import { script as $${e}$ } from "./src/${e}"\n`;y+="\n";for(const e in p){const t=p[e];for(const n of t)y+=`import { script as $${e}$${n}$ } from "./src/${e}/${n}"\n`}y+="\ntype ArrayRemoveFirst<A> = A extends [ infer FirstItem, ...infer Rest ] ? Rest : never\n\ntype Subscript<T extends (...args: any) => any> =\n\t(...args: ArrayRemoveFirst<Parameters<T>>) => ReturnType<T> | ScriptFailure\n\ntype WildFullsec = Record<string, () => ScriptFailure> & {\n";for(const e of c)y+=`\t${e}: Subscript<typeof $${e}$>\n`;for(const e of l)y+=`\t${e}: (...args: any) => any\n`;y+="}\n\ndeclare global {\n\tinterface PlayerFullsec {";let $=!0;for(const e of f){const t=p[e],n=m[e];if(t&&t.length||n&&n.length){$=!0,y+=`\n\t\t${e}: WildFullsec & {\n`;for(const n of t)y+=`\t\t\t${n}: Subscript<typeof $${e}$${n}$>\n`;for(const e of n)y+=`\t\t\t${e}: (...args: any) => any\n`;y+="\t\t}"}else $&&(y+="\n",$=!1),y+=`\t\t${e}: WildFullsec`;y+="\n"}y+="\t}\n}\n",await o(a,y)}export{generateTypings as default,generateTypings};
package/index.d.ts CHANGED
@@ -1,11 +1,4 @@
1
- export interface Info {
2
- file: string;
3
- users: string[];
4
- srcLength: number;
5
- minLength: number;
6
- error: Error | null;
7
- }
8
- export declare const supportedExtensions: string[];
1
+ export { supportedExtensions } from "./constants.json";
9
2
  export { generateTypings } from "./generateTypings";
10
3
  export { processScript } from "./processScript";
11
4
  export { pull } from "./pull";
@@ -13,3 +6,10 @@ export { push } from "./push";
13
6
  export { syncMacros } from "./syncMacros";
14
7
  export { test } from "./test";
15
8
  export { watch } from "./watch";
9
+ export interface Info {
10
+ file: string;
11
+ users: string[];
12
+ srcLength: number;
13
+ minLength: number;
14
+ error: Error | null;
15
+ }
package/index.js CHANGED
@@ -1 +1 @@
1
- import{generateTypings as e}from"./generateTypings.js";export{generateTypings}from"./generateTypings.js";import{processScript as t}from"./processScript/index.js";export{processScript}from"./processScript/index.js";export{pull}from"./pull.js";import i from"fs";import{resolve as s,extname as r,basename as n}from"path";export{syncMacros}from"./syncMacros.js";import{watch as o}from"chokidar";import{DynamicMap as a,forEachAsync as p,hackmudLength as c,writeFilePersist as l}from"./lib.js";import"@babel/generator";import"perf_hooks";import"./processScript/compile.js";import"@babel/core";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"./processScript/minify.js";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";const{readFile:m,readdir:g}=i.promises;async function f(e,i,{scripts:o="*.*",onPush:f=(e=>{}),minify:u=!0}={}){"string"==typeof o&&(o=[o]);const h=new a((e=>new Set)),w=new Set,d=new Set;let b=!1;for(const e of o){const[t,i]=e.split(".");t&&"*"!=t?i&&"*"!=i?h.get(t).add(i):w.add(t):i&&"*"!=i?d.add(i):b=!0}const y=new a((e=>new Set)),$=[],S=new a((e=>new Set));let F;if(d.size||b){const t=await g(s(i),{withFileTypes:!0}),n=new Set([...(F=await g(s(e),{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isFile()&&".key"==r(e.name))).map((e=>e.name.slice(0,-4))),...h.keys(),...w]);if(b)for(const e of n)w.add(e);else for(const e of n){const t=h.get(e);for(const e of d)t.add(e)}}return await p(w,(async o=>{await g(s(e,o),{withFileTypes:!0}).then((async a=>{await p(a,(async a=>{const p=r(a.name);if(a.isFile()&&L.includes(p)){const r=n(a.name,p),{srcLength:g,script:h}=await t(await m(s(e,o,a.name),{encoding:"utf-8"}),{minify:u,scriptUser:o,scriptName:r}),w={file:`${o}/${a.name}`,users:[o],minLength:c(h),error:null,srcLength:g};S.get(o).add(r),$.push(w),await l(s(i,o,`scripts/${r}.js`),h),f(w)}}))}),(e=>{if("ENOENT"!=e.code)throw e}))})),await p(h,(async([r,n])=>{w.has(r)||await p(n,(async n=>{let o,a;for(const t of L)try{a=`${n}${t}`,o=await m(s(e,r,a),{encoding:"utf-8"});break}catch{}if(o){const{srcLength:e,script:p}=await t(o,{minify:u,scriptUser:r,scriptName:n}),m={file:`${r}/${a}`,users:[r],minLength:c(p),error:null,srcLength:e};$.push(m),await l(s(i,r,"scripts",`${n}.js`),p),f(m)}else y.get(n).add(r)}))})),w.size?await p(F||await g(s(e),{withFileTypes:!0}),(async o=>{const a=r(o.name);if(!o.isFile()||!L.includes(a))return;const g=n(o.name,a),h=[...w,...y.get(g)].filter((e=>!S.get(e).has(g)));if(!h.length)return;const d=Math.floor(Math.random()*2**52).toString(36),{srcLength:b,script:F}=await t(await m(s(e,o.name),{encoding:"utf-8"}),{minify:u,scriptUser:!0,scriptName:g,randomString:d}),j={file:o.name,users:h,minLength:c(F),error:null,srcLength:b};await p(h,(e=>l(s(i,e,`scripts/${g}.js`),F.replace(new RegExp(`_SCRIPT_USER_${d}_`,"g"),e).replace(new RegExp(`_FULL_SCRIPT_NAME_${d}_`,"g"),`${e}.${g}`)))),$.push(j),f(j)})):await p(y,(async([r,n])=>{let o,a;for(const t of L)try{a=`${r}${t}`,o=await m(s(e,a),{encoding:"utf-8"});break}catch{}if(o){const e=Math.floor(Math.random()*2**52).toString(36),{srcLength:m,script:g}=await t(o,{minify:u,scriptUser:!0,scriptName:r,randomString:e}),h={file:a,users:[...n],minLength:c(g),error:null,srcLength:m};await p(n,(t=>l(s(i,t,`scripts/${r}.js`),g.replace(new RegExp(`_SCRIPT_USER_${e}_`,"g"),t).replace(new RegExp(`_FULL_SCRIPT_NAME_${e}_`,"g"),`${t}.${r}`)))),$.push(h),f(h)}})),$}const{readFile:u,readdir:h}=i.promises;async function w(e){const i=[],n=[];for(const o of await h(e,{withFileTypes:!0}))o.isDirectory()?i.push(h(s(e,o.name),{withFileTypes:!0}).then((i=>{const a=[];for(const p of i)p.isFile()&&L.includes(r(p.name))&&a.push(u(s(e,o.name,p.name),{encoding:"utf-8"}).then(t).then((({warnings:e})=>n.push(...e.map((({message:e,line:t})=>({file:`${o.name}/${p.name}`,message:e,line:t})))))));return Promise.all(a)}))):o.isFile()&&L.includes(r(o.name))&&i.push(u(s(e,o.name),{encoding:"utf-8"}).then(t).then((({warnings:e})=>n.push(...e.map((({message:e,line:t})=>({file:o.name,message:e,line:t})))))));return await Promise.all(i),n}const{readFile:d,readdir:b}=i.promises;function y(i,a,p,m,g,{genTypes:f}={}){const u=o("",{depth:1,cwd:i,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async e=>{const o=r(e);if(L.includes(o)){const f=n(e,o);if(e==n(e)){if(!m.length||m.includes(f)){const o=await d(s(i,e),{encoding:"utf-8"}),m=new Map,u=[];for(const e of await b(i,{withFileTypes:!0}))e.isDirectory()&&u.push(b(s(i,e.name),{withFileTypes:!0}).then((t=>{for(const i of t){if(!i.isFile())continue;const t=r(i.name);if(!L.includes(t))continue;const s=n(i.name,t),o=m.get(s);o?o.push(e.name):m.set(s,[e.name])}})));await Promise.all(u);let h=null;const{script:w,srcLength:y}=await t(o).catch((e=>(h=e,{script:"",srcLength:0}))),$={file:e,users:[],minLength:0,error:h,srcLength:y},S=[];if(!h)if(w){const e=m.get(f)||[];$.minLength=c(w),p.length||(p=(await b(a,{withFileTypes:!0})).filter((e=>e.isFile()&&".key"==r(e.name))).map((e=>n(e.name,".key"))));for(const t of p)e.includes(t)||($.users.push(t),S.push(l(s(a,t,"scripts",`${f}.js`),w)))}else $.error=new Error("processed script was empty");g&&(await Promise.all(S),g($))}}else{const r=n(s(e,".."));if((!p.length||p.includes(r))&&(!m.length||m.includes(f))){const n=await d(s(i,e),{encoding:"utf-8"});let o=null;const{script:p,srcLength:m}=await t(n).catch((e=>(o=e,{script:"",srcLength:0}))),u={file:e,users:[r],minLength:0,error:o,srcLength:m};o||(p?(u.minLength=c(p),await l(s(a,r,"scripts",`${f}.js`),p)):u.error=new Error("processed script was empty")),null==g||g(u)}}}}));f&&(e(i,s(i,f),a),u.on("add",(()=>e(i,s(i,f),a))),u.on("unlink",(()=>e(i,s(i,f),a))))}const L=[".js",".ts"];export{f as push,L as supportedExtensions,w as test,y as watch};
1
+ export{processScript,s as supportedExtensions}from"./processScript/index.js";export{generateTypings}from"./generateTypings.js";export{pull}from"./pull.js";export{push}from"./push.js";export{syncMacros}from"./syncMacros.js";export{test}from"./test.js";export{watch}from"./watch.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-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"./assert-1b7dada8.js";import"path";import"./processScript/minify.js";import"@babel/traverse";import"@babel/types";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";import"fs";import"./writeFilePersistent-4e3ff264.js";import"chokidar";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hackmud-script-manager",
3
- "version": "0.13.0-1a09d06",
3
+ "version": "0.13.0-3dccdd1",
4
4
  "description": "Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.",
5
5
  "keywords": [
6
6
  "api",
@@ -21,34 +21,18 @@
21
21
  "bugs": "https://github.com/samualtnorman/hackmud-script-manager/issues",
22
22
  "license": "GPL-3.0-or-later",
23
23
  "author": "Samual Norman",
24
- "files": [
25
- "*.d.ts",
26
- "*.js",
27
- "!*.config.js",
28
- "index.cjs",
29
- "bin",
30
- "processScript"
31
- ],
32
24
  "main": "index.js",
33
- "bin": {
34
- "hsm": "bin/hsm.js"
35
- },
36
25
  "repository": {
37
26
  "type": "git",
38
27
  "url": "https://github.com/samualtnorman/hackmud-script-manager.git"
39
28
  },
40
- "scripts": {
41
- "build": "rollup -c && tsc -p src",
42
- "dev": "rollup -cw",
43
- "prepublishOnly": "npm run build"
44
- },
45
29
  "dependencies": {
46
30
  "@babel/core": "^7.16.0",
47
31
  "@babel/generator": "^7.16.0",
48
- "@babel/parser": "^7.16.3",
32
+ "@babel/parser": "^7.16.4",
49
33
  "@babel/plugin-proposal-class-properties": "^7.16.0",
50
34
  "@babel/plugin-proposal-class-static-block": "^7.16.0",
51
- "@babel/plugin-proposal-decorators": "^7.16.0",
35
+ "@babel/plugin-proposal-decorators": "^7.16.4",
52
36
  "@babel/plugin-proposal-do-expressions": "^7.16.0",
53
37
  "@babel/plugin-proposal-function-bind": "^7.16.0",
54
38
  "@babel/plugin-proposal-function-sent": "^7.16.0",
@@ -68,26 +52,33 @@
68
52
  "@babel/plugin-transform-typescript": "^7.16.1",
69
53
  "@babel/traverse": "^7.16.3",
70
54
  "@babel/types": "^7.16.0",
71
- "acorn": "8.x",
72
- "chalk": "4.x",
73
- "chokidar": "3.x",
74
- "terser": "5.x"
75
- },
76
- "devDependencies": {
77
- "@babel/preset-env": "^7.16.0",
78
- "@babel/preset-typescript": "^7.16.0",
55
+ "@bloomberg/record-tuple-polyfill": "^0.0.4",
79
56
  "@rollup/plugin-babel": "^5.3.0",
80
57
  "@rollup/plugin-commonjs": "^21.0.1",
81
58
  "@rollup/plugin-json": "^4.1.0",
82
59
  "@rollup/plugin-node-resolve": "^13.0.6",
60
+ "acorn": "^8.5.0",
61
+ "chalk": "^4.1.2",
62
+ "chokidar": "^3.5.2",
63
+ "prettier": "^2.4.1",
64
+ "rollup": "^2.60.0",
65
+ "terser": "^5.10.0"
66
+ },
67
+ "devDependencies": {
68
+ "@babel/preset-env": "^7.16.4",
69
+ "@babel/preset-typescript": "^7.16.0",
70
+ "@samual/lib": "^0.2.0-27ea8d5",
83
71
  "@types/babel__core": "^7.1.16",
84
- "@types/node": "12.x",
85
- "@types/semver": "7.x",
86
- "rollup": "^2.56.3",
72
+ "@types/node": "^12.20.37",
73
+ "@types/prettier": "^2.4.2",
74
+ "@types/semver": "^7.3.9",
87
75
  "rollup-plugin-preserve-shebang": "^1.0.1",
88
76
  "rollup-plugin-terser": "^7.0.2",
89
- "semver": "7.x",
90
- "typescript": "^4.4.4"
77
+ "semver": "^7.3.5",
78
+ "typescript": "^4.5.2"
79
+ },
80
+ "optionalDependencies": {
81
+ "deasync": "^0.1.24"
91
82
  },
92
83
  "engines": {
93
84
  "node": "^12.20 || >=14"
@@ -95,10 +86,26 @@
95
86
  "types": "index.d.ts",
96
87
  "type": "module",
97
88
  "exports": {
98
- "require": "./index.cjs",
99
- "import": "./index.js"
89
+ ".": {
90
+ "import": "./index.js",
91
+ "require": "./index.cjs"
92
+ },
93
+ "./*": "./*",
94
+ "./generateTypings": "./generateTypings.js",
95
+ "./index": "./index.js",
96
+ "./processScript/index": "./processScript/index.js",
97
+ "./processScript": "./processScript/index.js",
98
+ "./processScript/minify": "./processScript/minify.js",
99
+ "./processScript/postprocess": "./processScript/postprocess.js",
100
+ "./processScript/preprocess": "./processScript/preprocess.js",
101
+ "./processScript/transform": "./processScript/transform.js",
102
+ "./pull": "./pull.js",
103
+ "./push": "./push.js",
104
+ "./syncMacros": "./syncMacros.js",
105
+ "./test": "./test.js",
106
+ "./watch": "./watch.js"
100
107
  },
101
- "optionalDependencies": {
102
- "deasync": "^0.1.23"
108
+ "bin": {
109
+ "hsm": "./bin/hsm.js"
103
110
  }
104
- }
111
+ }
@@ -1,18 +1,27 @@
1
- export { compile } from "./compile";
2
1
  export { minify } from "./minify";
3
- export { postProcess } from "./postProcess";
4
- export { preProcess } from "./preProcess";
2
+ export { postprocess } from "./postprocess";
3
+ export { preprocess } from "./preprocess";
4
+ export { transform as compile } from "./transform";
5
+ export declare type ProcessOptions = {
6
+ /** whether to minify the given code */
7
+ minify: boolean;
8
+ /** 11 a-z 0-9 characters */
9
+ uniqueID: string;
10
+ /** the user the script will be uploaded to (or set to `true` if it is not yet known) */
11
+ scriptUser: string | true;
12
+ /** the name of this script (or set to `true` if it is not yet known) */
13
+ scriptName: string | true;
14
+ filePath: string;
15
+ /** whether to mangle function and class names (defaults to `false`) */
16
+ mangleNames: boolean;
17
+ };
5
18
  /**
6
19
  * Minifies a given script
7
20
  *
8
21
  * @param code JavaScript or TypeScript code
22
+ * @param options {@link ProcessOptions details}
9
23
  */
10
- export declare function processScript(code: string, { minify: shouldMinify, randomString, scriptUser, scriptName }?: {
11
- minify?: boolean | undefined;
12
- randomString?: string | undefined;
13
- scriptUser?: string | true | undefined;
14
- scriptName?: string | true | undefined;
15
- }): Promise<{
24
+ export declare function processScript(code: string, { minify: shouldMinify, uniqueID, scriptUser, scriptName, filePath, mangleNames }?: Partial<ProcessOptions>): Promise<{
16
25
  srcLength: number;
17
26
  script: string;
18
27
  warnings: {
@@ -1 +1 @@
1
- import o from"@babel/generator";import{performance as p}from"perf_hooks";import{hackmudLength as r}from"../lib.js";import{compile as i}from"./compile.js";export{compile}from"./compile.js";import{minify as t}from"./minify.js";export{minify}from"./minify.js";import{postProcess as l}from"./postProcess.js";export{postProcess}from"./postProcess.js";import{preProcess as e}from"./preProcess.js";export{preProcess}from"./preProcess.js";import"fs";import"path";import"@babel/core";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@babel/parser";import"acorn";import"terser";const{default:a}=o;async function s(o,{minify:s=!0,randomString:n=Math.floor(Math.random()*2**52).toString(36),scriptUser:m="UNKNOWN",scriptName:b="UNKNOWN"}={}){var c,u,g,f,d,h;const v=p.now(),j=o;let x,y,w;({autocomplete:x,code:o,seclevel:y,semicolons:w}=e(o)),o=a(await i(o,n,j,m,b)).code;let N=r(o.replace(/^function\s*\w+\(/,"function("))-(null!==(c=null===(u=o.match(/;/g))||void 0===u?void 0:u.length)&&void 0!==c?c:0)+w+(null!==(g=null===(f=o.match(/SC\$[a-zA-Z_][a-zA-Z0-9_]*\$[a-zA-Z_][a-zA-Z0-9_]*\(/g))||void 0===f?void 0:f.length)&&void 0!==g?g:0)+(null!==(d=null===(h=o.match(/DB\$/g))||void 0===h?void 0:h.length)&&void 0!==d?d:0);return s&&(o=await t(o,x,n)),{srcLength:N,script:o=l(o,y),warnings:[],timeTook:p.now()-v}}export{s as default,s as processScript};
1
+ import o from"@babel/generator";import{parse as r}from"@babel/parser";import p from"@babel/plugin-proposal-class-properties";import e from"@babel/plugin-proposal-class-static-block";import t from"@babel/plugin-proposal-decorators";import a from"@babel/plugin-proposal-do-expressions";import i from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import s from"@babel/plugin-proposal-json-strings";import m from"@babel/plugin-proposal-logical-assignment-operators";import n from"@babel/plugin-proposal-nullish-coalescing-operator";import f from"@babel/plugin-proposal-numeric-separator";import u from"@babel/plugin-proposal-object-rest-spread";import c from"@babel/plugin-proposal-optional-catch-binding";import b from"@babel/plugin-proposal-optional-chaining";import d from"@babel/plugin-proposal-partial-application";import g from"@babel/plugin-proposal-pipeline-operator";import h from"@babel/plugin-proposal-private-property-in-object";import j from"@babel/plugin-proposal-record-and-tuple";import y from"@babel/plugin-proposal-throw-expressions";import w from"@babel/plugin-transform-exponentiation-operator";import x from"@babel/plugin-transform-typescript";import N from"@rollup/plugin-babel";import v from"@rollup/plugin-commonjs";import S from"@rollup/plugin-json";import k from"@rollup/plugin-node-resolve";import{a as q}from"../assert-1b7dada8.js";import{resolve as D}from"path";import{c as I,minify as T}from"./minify.js";export{minify}from"./minify.js";import{performance as U}from"perf_hooks";import P from"prettier";import{rollup as F}from"rollup";import{postprocess as K}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as M}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{transform as O}from"./transform.js";export{transform as compile}from"./transform.js";import"@babel/traverse";import"@babel/types";import"../spliceString-2c6f214f.js";import"acorn";import"terser";const W=[".js",".ts"],{default:$}=N,{format:B}=P,{default:E}=o;async function processScript(o,{minify:N=!0,uniqueID:P=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:H="UNKNOWN",scriptName:L="UNKNOWN",filePath:_,mangleNames:z=!1}={}){var A;q(P.match(/^\w{11}$/)),_=_?D(_):"script";const C=U.now(),G=o;let J,Q,R;({autocomplete:J,code:o,seclevel:Q,semicolons:R}=M(o,{uniqueID:P})),q(P.match(/^\w{11}$/));const V=_?D(_):"script",X=await F({plugins:[{name:"emit script",buildStart(){this.emitFile({type:"chunk",id:V})},load:r=>r==V?o:null,transform:o=>M(o,{uniqueID:P}).code},$({babelHelpers:"bundled",plugins:[[x.default],[t.default,{decoratorsBeforeExport:!0}],[a.default],[i.default],[l.default],[d.default],[g.default,{proposal:"hack",topicToken:"%"}],[y.default],[j.default,{syntaxType:"hash",importPolyfill:!0}],[p.default],[e.default],[h.default],[m.default],[f.default],[n.default],[b.default],[c.default],[s.default],[u.default],[w.default]],configFile:!1,extensions:W}),v(),k({extensions:W}),S()]});o=(await X.generate({})).output[0].code;const Y=r(o,{sourceType:"module"});o=E(await O(Y,G,{uniqueID:P,scriptUser:H,scriptName:L,seclevel:Q})).code;let Z=I(o.replace(/^function\s*\w+\(/,"function("))-((null===(A=o.match(/;/g))||void 0===A?void 0:A.length)||0)+R;return o=N?await T(o,J,{uniqueID:P,mangleNames:z}):B(o,{parser:"babel",arrowParens:"avoid",semi:!1}),{srcLength:Z,script:o=K(o,Q,P),warnings:[],timeTook:U.now()-C}}export{processScript as default,processScript,W as s};
@@ -1,2 +1,13 @@
1
- export declare function minify(code: string, autocomplete: string, randomString?: string): Promise<string>;
1
+ declare type MinifyOptions = {
2
+ /** 11 a-z 0-9 characters */
3
+ uniqueID: string;
4
+ /** whether to mangle function and class names (defaults to `false`) */
5
+ mangleNames: boolean;
6
+ };
7
+ /**
8
+ * @param code compiled code and/or hackmud compatible code
9
+ * @param autocomplete the comment inserted after the function signature
10
+ * @param options {@link MinifyOptions details}
11
+ */
12
+ export declare function minify(code: string, autocomplete: string, { uniqueID, mangleNames }?: Partial<MinifyOptions>): Promise<string>;
2
13
  export default minify;
@@ -1 +1 @@
1
- import e from"@babel/generator";import{parse as t}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{tokenizer as n,tokTypes as a}from"acorn";import*as o from"terser";import{assert as s,stringSplice as p,hackmudLength as l}from"../lib.js";import"fs";import"path";const{default:u}=e,{default:f}=r;async function c(e,r,n="0"){const a=[];let c,E=!1;e=(await o.minify(e,{ecma:2015,parse:{bare_returns:!0},compress:{passes:1/0,unsafe:!0,booleans:!1,sequences:!1}})).code||"";{const r=await t(e);f(r,{MemberExpression({node:e}){e.computed||(s("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=i.identifier(`_PROTOTYPE_PROPERTY_${n}_`)):"__proto__"==e.property.name&&(e.computed=!0,e.property=i.identifier(`_PROTO_PROPERTY_${n}_`)))}}),c=(await o.minify(u(r).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}})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${n}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${n}_`,"g"),'"__proto__"')}let b=null,$=!1;{const r=await t(e),o=[];f(r,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const t={};_(e.node,t)&&e.replaceWith(i.identifier(`_JSON_VALUE_${a.push(t)-1}_${n}_`))},ArrayExpression(e){const t=[];d(e.node,t)&&e.replaceWith(i.identifier(`_JSON_VALUE_${a.push(t)-1}_${n}_`))}}),e.traverse({TemplateLiteral(e){const t=e.node;let r=i.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];r=i.binaryExpression("+",r,n),a.value.cooked&&(r=i.binaryExpression("+",r,i.stringLiteral(a.value.cooked)))}e.replaceWith(r)},MemberExpression({node:e}){e.computed||(s("Identifier"==e.property.type),e.property.name.length<3||(e.computed=!0,e.property=i.stringLiteral(e.property.name)))},UnaryExpression(e){"void"!=e.node.operator||"NumericLiteral"!=e.node.argument.type||e.node.argument.value||(e.replaceWith(i.identifier(`_UNDEFINED_${n}_`)),E=!0)},NullLiteral(e){let t=a.indexOf(null);-1==t&&(t+=a.push(null)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${n}_`))},BooleanLiteral(e){let t=a.indexOf(e.node.value);-1==t&&(t+=a.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${n}_`))},NumericLiteral(e){o.push((async()=>{if((await m(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=a.indexOf(e.node.value);-1==t&&(t+=a.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${n}_`))})())},StringLiteral(e){if(e.node.value.includes("\0")||e.node.value.length<2)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=a.indexOf(e.node.value);-1==t&&(t+=a.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${n}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=a.indexOf(e.key.name);-1==t&&(t+=a.push(e.key.name)),e.computed=!0,e.key=i.identifier(`_JSON_VALUE_${t}_${n}_`)}}),e.skip()}}),await Promise.all(o);const[p]=r.program.body;if(s("FunctionDeclaration"==p.type),a.length)if($=!0,1==a.length)if("string"!=typeof a[0]||a[0].includes("\n")||a[0].includes("\t")){const e=i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_JSON_VALUE_0_${n}_`),i.callExpression(i.memberExpression(i.identifier("JSON"),i.identifier("parse")),[i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier("SC$scripts$quine"),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`_SPLIT_INDEX_${n}_`),!0)]))]);E&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${n}_`))),p.body.body.unshift(e),b=JSON.stringify(a[0])}else{const e=i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_JSON_VALUE_0_${n}_`),i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier("SC$scripts$quine"),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`_SPLIT_INDEX_${n}_`),!0))]);E&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${n}_`))),p.body.body.unshift(e),b=a[0]}else{const e=i.variableDeclaration("let",[i.variableDeclarator(i.arrayPattern(a.map(((e,t)=>i.identifier(`_JSON_VALUE_${t}_${n}_`)))),i.callExpression(i.memberExpression(i.identifier("JSON"),i.identifier("parse")),[i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier("SC$scripts$quine"),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`_SPLIT_INDEX_${n}_`),!0)]))]);E&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${n}_`))),p.body.body.unshift(e),b=JSON.stringify(a)}else E&&p.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_UNDEFINED_${n}_`))]));e=u(r).code}if(e=(await o.minify(e,{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}})).code||"",null!=b){e=p(e,`${r?`//${r}\n`:""}\n//\t${b}\t\n`,y(e)+1);for(const[t,r]of e.split("\t").entries())if(r==b){e=e.replace(`_SPLIT_INDEX_${n}_`,await m(t));break}}return l(c)<=l(e)+Number($)&&(e=c,r&&(e=p(e,`//${r}\n`,y(e)+1))),e}function _(e,t){if(!e.properties.length)return!1;for(const r of e.properties){if("ObjectProperty"!=r.type||r.computed)return!1;if(s("Identifier"==r.key.type||"NumericLiteral"==r.key.type||"StringLiteral"==r.key.type),"ArrayExpression"==r.value.type){const e=[];if(!d(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(!_(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)return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.value}}return!0}function d(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(!d(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!_(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)return!1;t.push(r.value)}}return!0}async function m(e){return(await o.minify(`$(${e})`,{ecma:2015})).code.match(/\$\((.+)\)/)[1]}function y(e){const t=n(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let r=1;for(;r;){const e=t.getToken();e.type==a.parenL?r++:e.type==a.parenR&&r--}return t.getToken().start}export{c as default,c as minify};
1
+ import e from"@babel/generator";import{parse as r}from"@babel/parser";import t from"@babel/traverse";import i from"@babel/types";import{a as n}from"../assert-1b7dada8.js";import{s as a}from"../spliceString-2c6f214f.js";import{tokenizer as s,tokTypes as o}from"acorn";import*as p from"terser";function countHackmudCharacters(e){return e.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]/g,"").length}const{default:l}=e,{default:u}=t;async function minify(e,t,{uniqueID:s="00000000000",mangleNames:o=!1}={}){n(s.match(/^\w{11}$/));const c=[];let f,m=!1;e=(await p.minify(e,{ecma:2015,parse:{bare_returns:!0},compress:{passes:1/0,unsafe:!0,booleans:!1,sequences:!1},keep_classnames:!o,keep_fnames:!o})).code||"";{const t=await r(e);u(t,{MemberExpression({node:e}){e.computed||(n("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=i.identifier(`_PROTOTYPE_PROPERTY_${s}_`)):"__proto__"==e.property.name&&(e.computed=!0,e.property=i.identifier(`_PROTO_PROPERTY_${s}_`)))}}),f=(await p.minify(l(t).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(`_PROTOTYPE_PROPERTY_${s}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${s}_`,"g"),'"__proto__"')}let d=null,y=!1;{const t=await r(e),a=[];u(t,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const r={};parseObjectExpression(e.node,r)&&e.replaceWith(i.identifier(`_JSON_VALUE_${c.push(r)-1}_${s}_`))},ArrayExpression(e){const r=[];parseArrayExpression(e.node,r)&&e.replaceWith(i.identifier(`_JSON_VALUE_${c.push(r)-1}_${s}_`))}}),e.traverse({TemplateLiteral(e){const r=e.node;let t=i.stringLiteral(r.quasis[0].value.cooked);for(let e=0;e<r.expressions.length;e++){const n=r.expressions[e],a=r.quasis[e+1];t=i.binaryExpression("+",t,n),a.value.cooked&&(t=i.binaryExpression("+",t,i.stringLiteral(a.value.cooked)))}e.replaceWith(t)},MemberExpression({node:e}){e.computed||(n("Identifier"==e.property.type),e.property.name.length<3||(e.computed=!0,e.property=i.stringLiteral(e.property.name)))},UnaryExpression(e){if("void"==e.node.operator)"NumericLiteral"!=e.node.argument.type||e.node.argument.value||(e.replaceWith(i.identifier(`_UNDEFINED_${s}_`)),m=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const r=-e.node.argument.value;a.push((async()=>{if((await minifyNumber(r)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=c.indexOf(r);-1==t&&(t+=c.push(r)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${s}_`))})()),e.skip()}},NullLiteral(e){let r=c.indexOf(null);-1==r&&(r+=c.push(null)),e.replaceWith(i.identifier(`_JSON_VALUE_${r}_${s}_`))},BooleanLiteral(e){let r=c.indexOf(e.node.value);-1==r&&(r+=c.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${r}_${s}_`))},NumericLiteral(e){a.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let r=c.indexOf(e.node.value);-1==r&&(r+=c.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${r}_${s}_`))})())},StringLiteral(e){if(e.node.value.includes("\0")||e.toString().length<4)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let r=c.indexOf(e.node.value);-1==r&&(r+=c.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${r}_${s}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let r=c.indexOf(e.key.name);-1==r&&(r+=c.push(e.key.name)),e.computed=!0,e.key=i.identifier(`_JSON_VALUE_${r}_${s}_`)}}),e.skip()}}),await Promise.all(a);const[o]=t.program.body;if(n("FunctionDeclaration"==o.type),c.length)if(y=!0,1==c.length)if("string"!=typeof c[0]||c[0].includes("\n")||c[0].includes("\t")){const e=i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_JSON_VALUE_0_${s}_`),i.callExpression(i.memberExpression(i.identifier("JSON"),i.identifier("parse")),[i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier(`$${s}$SUBSCRIPT$scripts$quine`),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`$${s}$SPLIT_INDEX`),!0)]))]);m&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))),o.body.body.unshift(e),d=JSON.stringify(c[0])}else{const e=i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_JSON_VALUE_0_${s}_`),i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier(`$${s}$SUBSCRIPT$scripts$quine`),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`$${s}$SPLIT_INDEX`),!0))]);m&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))),o.body.body.unshift(e),d=c[0]}else{const e=i.variableDeclaration("let",[i.variableDeclarator(i.arrayPattern(c.map(((e,r)=>i.identifier(`_JSON_VALUE_${r}_${s}_`)))),i.callExpression(i.memberExpression(i.identifier("JSON"),i.identifier("parse")),[i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier(`$${s}$SUBSCRIPT$scripts$quine`),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`$${s}$SPLIT_INDEX`),!0)]))]);m&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))),o.body.body.unshift(e),d=JSON.stringify(c)}else m&&o.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))]));e=l(t).code}if(e=(await p.minify(e,{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!=d){e=a(e,`${t?`//${t}\n`:""}\n//\t${d}\t\n`,getFunctionBodyStart(e)+1);for(const[r,t]of e.split("\t").entries())if(t==d){e=e.replace(`$${s}$SPLIT_INDEX`,await minifyNumber(r));break}}return countHackmudCharacters(f)<=countHackmudCharacters(e)+Number(y)&&(e=f,t&&(e=a(e,`//${t}\n`,getFunctionBodyStart(e)+1))),e}function parseObjectExpression(e,r){if(!e.properties.length)return!1;for(const t of e.properties){if("ObjectProperty"!=t.type||t.computed)return!1;if(n("Identifier"==t.key.type||"NumericLiteral"==t.key.type||"StringLiteral"==t.key.type),"ArrayExpression"==t.value.type){const e=[];if(!parseArrayExpression(t.value,e))return!1;r["Identifier"==t.key.type?t.key.name:t.key.value]=e}else if("ObjectExpression"==t.value.type){const e={};if(!parseObjectExpression(t.value,e))return!1;r["Identifier"==t.key.type?t.key.name:t.key.value]=e}else if("NullLiteral"==t.value.type)r["Identifier"==t.key.type?t.key.name:t.key.value]=null;else{if("BooleanLiteral"!=t.value.type&&"NumericLiteral"!=t.value.type&&"StringLiteral"!=t.value.type)return!1;r["Identifier"==t.key.type?t.key.name:t.key.value]=t.value.value}}return!0}function parseArrayExpression(e,r){if(!e.elements.length)return!1;for(const t of e.elements){if(!t)return!1;if("ArrayExpression"==t.type){const e=[];if(!parseArrayExpression(t,e))return!1;e.push(e)}else if("ObjectExpression"==t.type){const e={};if(!parseObjectExpression(t,e))return!1;r.push(e)}else if("NullLiteral"==t.type)r.push(null);else{if("BooleanLiteral"!=t.type&&"NumericLiteral"!=t.type&&"StringLiteral"!=t.type)return!1;r.push(t.value)}}return!0}async function minifyNumber(e){return(await p.minify(`$(${e})`,{ecma:2015})).code.match(/\$\((.+)\)/)[1]}function getFunctionBodyStart(e){const r=s(e,{ecmaVersion:2015});r.getToken(),r.getToken(),r.getToken();let t=1;for(;t;){const e=r.getToken();e.type==o.parenL?t++:e.type==o.parenR&&t--}return r.getToken().start}export{countHackmudCharacters as c,minify as default,minify};
@@ -0,0 +1,2 @@
1
+ export declare function postprocess(code: string, seclevel: number, uniqueID: string): string;
2
+ export default postprocess;
@@ -0,0 +1 @@
1
+ import{s as e}from"../spliceString-2c6f214f.js";function*findMatches(e,s){let t;for(;t=e.exec(s);)yield{index:t.index,match:t[0]}}function postprocess(s,t,n){s=s.replace(/^function\s*\w+\(/,"function(");for(const{index:r,match:c}of[...findMatches(new RegExp(`\\$${n}\\$[\\w$]+`,"g"),s)].reverse()){const[n,...o]=c.slice(13).split("$");switch(n){case"SUBSCRIPT":s=e(s,`#${"nlmhf"[t]}s.${o[0]}.${o[1]}`,r,c.length);break;case"DEBUG":s=e(s,"#D",r,c.length);break;case"FMCL":s=e(s,"#FMCL",r,c.length);break;case"GLOBAL":s=e(s,"#G",r,c.length);break;case"DB":s=e(s,`#db.${o[0]}`,r,c.length);break;default:throw new Error(`unknown preprocessor directive type "${n}"`)}}return s}export{postprocess as default,postprocess};
@@ -0,0 +1,15 @@
1
+ export declare type PreprocessOptions = {
2
+ /** 11 a-z 0-9 characters */
3
+ uniqueID: string;
4
+ };
5
+ /**
6
+ * @param code source code to be preprocessed
7
+ * @param options {@link PreprocessOptions details}
8
+ */
9
+ export declare function preprocess(code: string, { uniqueID }?: Partial<PreprocessOptions>): {
10
+ semicolons: number;
11
+ autocomplete: string;
12
+ seclevel: number;
13
+ code: string;
14
+ };
15
+ export default preprocess;
@@ -0,0 +1 @@
1
+ import{parse as e}from"@babel/parser";import{a as s}from"../assert-1b7dada8.js";import{s as t}from"../spliceString-2c6f214f.js";function preprocess(a,{uniqueID:o="00000000000"}={}){var l,c;let r,n,i;if(s(o.match(/^\w{11}$/)),[,r,a,n]=a.match(/((?:^\s*\/\/.*\n)*)\s*((?:.+?\/\/\s*(.+?)\s*$)?[^]*)/m),a.match(/(?:SC|DB)\$/))throw new Error("SC$ and DB$ are protected and cannot appear in a script");for(const e of r.split("\n")){let[,s,t]=e.match(/^\s*\/\/\s*(?:@autocomplete\s*([^\s].*?)|@seclevel\s*([^\s].*?))\s*$/)||[];s?n=s:t&&(t.match(/^(?:fullsec|f|4|fs|full)$/i)?i=4:t.match(/^(?:highsec|h|3|hs|high)$/i)?i=3:t.match(/^(?:midsec|m|2|ms|mid)$/i)?i=2:t.match(/^(?:lowsec|l|1|ls|low)$/i)?i=1:t.match(/^(?:nullsec|n|0|ns|null)$/i)&&(i=0))}let p=4;a.match(/[#$][n0]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?p=0:a.match(/[#$][l1]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?p=1:a.match(/[#$][m2]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?p=2:a.match(/[#$][h3]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)&&(p=3);const h=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];if(null==i)i=p;else if(p<i)throw new Error(`detected seclevel ${h[p]} is lower than stated seclevel ${h[i]}`);const m=null!==(l=null===(c=a.match(/;/g))||void 0===c?void 0:c.length)&&void 0!==l?l:0,$=a;let f;for(a=a.replace(/^function\s*\(/,"export default function (");;){let l;try{f=e(a,{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){s(e instanceof SyntaxError),l=e}var d;if("BABEL_PARSER_SYNTAX_ERROR"!=l.code||"PrivateInExpectedIn"!=l.reasonCode)throw console.log(null===(d=a.slice(l.pos).match(/.+/))||void 0===d?void 0:d[0]),l;const c=a.slice(l.pos);let r;if(r=c.match(/^#[fhmln43210]s\.scripts\.quine\(\)/))a=t(a,JSON.stringify($),l.pos,r[0].length);else if(r=c.match(/^#[fhmln43210]?s\.([a-z_][a-z_0-9]{0,24})\.([a-z_][a-z_0-9]{0,24})\(/))a=t(a,`$${o}$SUBSCRIPT$${r[1]}$${r[2]}(`,l.pos,r[0].length);else if(r=c.match(/^#D\(/))a=t(a,`$${o}$DEBUG(`,l.pos,r[0].length);else if(r=c.match(/^#FMCL/))a=t(a,`$${o}$FMCL`,l.pos,r[0].length);else if(r=c.match(/^#G/))a=t(a,`$${o}$GLOBAL`,l.pos,r[0].length);else{if(!(r=c.match(/^#db\.(i|r|f|u|u1|us|ObjectId)\(/)))throw l;a=t(a,`$${o}$DB$${r[1]}(`,l.pos,r[0].length)}}return{semicolons:m,autocomplete:n,seclevel:i,code:a}}export{preprocess as default,preprocess};
@@ -0,0 +1,19 @@
1
+ import t, { File } from "@babel/types";
2
+ export declare type TransformOptions = {
3
+ /** 11 a-z 0-9 characters */
4
+ uniqueID: string;
5
+ /** the user the script will be uploaded to (or set to `true` if it is not yet known) */
6
+ scriptUser: string | true;
7
+ /** the name of this script (or set to `true` if it is not yet known) */
8
+ scriptName: string | true;
9
+ seclevel: number;
10
+ };
11
+ /**
12
+ * transform a given babel `File` to be hackmud compatible
13
+ *
14
+ * (returned File will need `postprocess()`ing)
15
+ *
16
+ * @param options {@link TransformOptions details}
17
+ */
18
+ export declare function transform(file: File, sourceCode: string, { uniqueID, scriptUser, scriptName, seclevel }?: Partial<TransformOptions>): Promise<t.File>;
19
+ export default transform;
@@ -0,0 +1 @@
1
+ import e from"@babel/traverse";import t from"@babel/types";import{a as i,e as n}from"../assert-1b7dada8.js";function clearObject(e,t=Object.prototype){for(const t of Object.getOwnPropertyNames(e))delete e[t];for(const t of Object.getOwnPropertySymbols(e))delete e[t];return Object.setPrototypeOf(e,t),e}const{default:o}=e;async function transform(e,n,{uniqueID:r="00000000000",scriptUser:a="UNKNOWN",scriptName:s="UNKNOWN",seclevel:l=-1}={}){const c=`_SCRIPT_${r}_`,p=new Map,d=new Map;let f;if(o(e,{Program(e){f=e,e.skip()}}),f.scope.hasGlobal("_START"))for(const e of getReferencePathsToGlobal("_START",f))e.replaceWith(t.identifier("_ST"));if(f.scope.hasGlobal("_TIMEOUT"))for(const e of getReferencePathsToGlobal("_START",f))e.replaceWith(t.identifier("_TO"));if(f.scope.hasGlobal("_SOURCE"))for(const e of getReferencePathsToGlobal("_SOURCE",f))e.replaceWith(t.stringLiteral(n));if(f.scope.hasGlobal("_BUILD_DATE"))for(const e of getReferencePathsToGlobal("_BUILD_DATE",f))e.replaceWith(t.numericLiteral(Date.now()));if(f.scope.hasGlobal("_SCRIPT_USER"))for(const e of getReferencePathsToGlobal("_SCRIPT_USER",f))1==a?e.replaceWith(t.stringLiteral(`$${r}$SCRIPT_USER`)):e.replaceWith(t.stringLiteral(a));if(f.scope.hasGlobal("_SCRIPT_NAME"))for(const e of getReferencePathsToGlobal("_SCRIPT_NAME",f))1==s?e.replaceWith(t.stringLiteral(`$${r}$SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(s));if(f.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of getReferencePathsToGlobal("_FULL_SCRIPT_NAME",f))1==a||1==s?e.replaceWith(t.stringLiteral(`$${r}$FULL_SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(`${a}.${s}`));for(const e of["$fs","$hs","$ms","$ls","$ns","$4s","$3s","$2s","$1s","$0s"])if(f.scope.hasGlobal(e))for(const n of getReferencePathsToGlobal(e,f)){var b,h;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(b=n.parentPath.parentPath)||void 0===b?void 0:b.node.type)),i("Identifier"==(null===(h=n.parentPath.parentPath)||void 0===h?void 0:h.node.property.type)),n.parentPath.parentPath.replaceWith(t.identifier(`$${r}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}if(f.scope.hasGlobal("$db"))for(const e of getReferencePathsToGlobal("$db",f))i("MemberExpression"==e.parentPath.node.type),i("Identifier"==e.parentPath.node.property.type),e.parentPath.replaceWith(t.identifier(`$${r}$DB$${e.parentPath.node.property.name}`));if(f.scope.hasGlobal("$D"))for(const e of getReferencePathsToGlobal("$D",f))e.replaceWith(t.identifier(`$${r}$DEBUG`));if(f.scope.hasGlobal("$FMCL"))for(const e of getReferencePathsToGlobal("$FMCL",f))e.replaceWith(t.identifier(`$${r}$FMCL`));if(f.scope.hasGlobal("$G"))for(const e of getReferencePathsToGlobal("$G",f))e.replaceWith(t.identifier(`$${r}$GLOBAL`));if(f.scope.hasGlobal("_SECLEVEL"))for(const e of getReferencePathsToGlobal("_SECLEVEL",f))e.replaceWith(l<0?t.unaryExpression("-",t.numericLiteral(-l)):t.numericLiteral(l));const y=t.blockStatement([]);let m;const u=[];for(const e of f.node.body)if("ExportDefaultDeclaration"==e.type)"FunctionDeclaration"==e.declaration.type||"FunctionExpression"==e.declaration.type||"ArrowFunctionExpression"==e.declaration.type?m=t.functionDeclaration(t.identifier(c),e.declaration.params,"BlockStatement"==e.declaration.body.type?e.declaration.body:t.blockStatement([t.returnStatement(e.declaration.body)])):(i(t.isExpression(e.declaration)),m=t.functionDeclaration(t.identifier(c),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(e.declaration,[]))])));else if("ExportNamedDeclaration"==e.type){if(e.declaration)if("VariableDeclaration"==e.declaration.type)for(const i of e.declaration.declarations){for(const n in t.getBindingIdentifiers(i.id))"const"==e.declaration.kind?p.set(n,n):d.set(n,n),y.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(n))]));i.init&&y.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else{i("id"in e.declaration&&e.declaration.id,`unsupported export type "${e.declaration.type}"`);const t="Identifier"==e.declaration.id.type?e.declaration.id.name:e.declaration.id.value;p.set(t,t),y.body.push(e.declaration)}else if(e.specifiers)for(const n of e.specifiers){i("ExportSpecifier"==n.type,`${n.type} is currently unsupported`);const e="Identifier"==n.exported.type?n.exported.name:n.exported.value;"default"==e?m=t.functionDeclaration(t.identifier(c),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(n.local,[]))])):u.includes(n.local.name)?d.set(n.local.name,e):p.set(n.local.name,e)}}else if("VariableDeclaration"==e.type)for(const i of e.declarations){for(const n in t.getBindingIdentifiers(i.id))"const"!=e.kind&&(p.has(n)?(d.set(n,p.get(n)),p.delete(n)):u.push(n)),y.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(n))]));i.init&&y.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else"FunctionDeclaration"==e.type?y.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(null,e.params,e.body,e.generator,e.async))])):y.body.push(e);if(m||(m=t.functionDeclaration(t.identifier(c),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),f.node.body=[m],y.body.length){(p.size||d.size)&&m.body.body.push(t.returnStatement(t.objectExpression([...[...p].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...d].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),f.scope.crawl();const e=new Set;let n=0;for(const[o,a]of[...y.body.entries()].reverse())if("VariableDeclaration"==a.type){i(1==a.declarations.length);const s=a.declarations[0];if(i("Identifier"==s.id.type,`declarator.id.type was "${s.id.type}"`),f.scope.crawl(),f.scope.hasGlobal(s.id.name)){y.body.splice(o,1);const[l]=f.unshiftContainer("body",y),[c]=f.unshiftContainer("body",a);if(f.scope.crawl(),!s.init||"FunctionExpression"!=s.init.type&&"ArrowFunctionExpression"!=s.init.type||Object.keys(f.scope.globals).find((t=>e.has(t)))){const e=f.scope.getBinding(s.id.name);i(e);for(const n of e.referencePaths)i("Identifier"==n.node.type),n.replaceWith(t.memberExpression(t.identifier(`$${r}$GLOBAL`),t.identifier(n.node.name)));for(const n of e.constantViolations){i("AssignmentExpression"==n.node.type);for(const[e,i]of Object.entries(t.getBindingIdentifiers(n.node)))e==s.id.name&&Object.assign(clearObject(i),t.memberExpression(t.identifier(`$${r}$GLOBAL`),t.identifier(e)))}l.remove(),c.remove(),s.init&&y.body.splice(o,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${r}$GLOBAL`),t.identifier(s.id.name)),s.init)))}else l.remove(),c.remove(),m.body.body.unshift(a),n++}else e.add(s.id.name)}else if("ClassDeclaration"==a.type&&(f.scope.crawl(),f.scope.hasGlobal(a.id.name))){y.body.splice(o,1);const[e]=f.unshiftContainer("body",y),[n]=f.unshiftContainer("body",a);f.scope.crawl();const s=f.scope.getBinding(a.id.name);i(s);for(const e of s.referencePaths)i("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${r}$GLOBAL`),t.identifier(e.node.name)));e.remove(),n.remove(),y.body.splice(o,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${r}$GLOBAL`),t.identifier(a.id.name)),t.classExpression(null,a.superClass,a.body,a.decorators))))}if(f.scope.hasGlobal("_EXPORTS"))for(const e of getReferencePathsToGlobal("_EXPORTS",f))e.replaceWith(t.arrayExpression([...p.keys(),...d.keys()].map((e=>t.stringLiteral(e)))));y.body.length&&m.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${r}$FMCL`)),y))}o(e,{BlockStatement({node:e}){for(const[i,n]of e.body.entries())"FunctionDeclaration"!=n.type||n.generator||(e.body.splice(i,1),e.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(n.id,t.arrowFunctionExpression(n.params,n.body,n.async))])))},ClassBody({node:e,scope:n,parent:a}){i(t.isClass(a));let s=!1;for(const i of e.body){if("ClassMethod"!=i.type)continue;let e=!1;if(o(i.body,{ThisExpression(i){e=!0,s=!0,i.replaceWith(t.identifier(`_THIS_${r}_`))},Function(e){e.skip()}},n),e)if("constructor"!=i.kind)i.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${r}_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(o(i.body,{CallExpression(t){"Super"==t.node.callee.type&&e.push(t)}},n),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==i)e[0].parentPath.replaceWith(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${r}_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_THIS_${r}_`),i.node));i.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${r}_`))]))}else i.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${r}_`),t.callExpression(t.super(),[]))]))}}!a.superClass&&s&&(a.superClass=t.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(t.identifier(`_UNDEFINED_${r}_`))},BigIntLiteral(e){const i=Number(e.node.value);BigInt(i)==BigInt(e.node.value)?e.replaceWith(t.callExpression(t.identifier("BigInt"),[t.numericLiteral(i)])):e.replaceWith(t.callExpression(t.identifier("BigInt"),[t.stringLiteral(e.node.value)]))}});const $=f.get("body.0").scope;for(const e of[...m.params].reverse()){if("Identifier"==e.type){if(!$.getBinding(e.name).referenced){m.params.pop();continue}}break}for(const e in f.scope.globals){if("arguments"==e||e.startsWith(`$${r}`))continue;const i=getReferencePathsToGlobal(e,f);if(!(5+e.length+i.length>=e.length*i.length)){for(const n of i)n.replaceWith(t.identifier(`_GLOBAL_${e}_${r}_`));m.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_GLOBAL_${e}_${r}_`),t.identifier(e))]))}}return e}function getReferencePathsToGlobal(e,i){const[o]=i.unshiftContainer("body",t.variableDeclaration("let",[t.variableDeclarator(t.identifier(e))]));i.scope.crawl();const r=n(i.scope.getBinding(e));return o.remove(),r.referencePaths}export{transform as default,transform};
package/pull.js CHANGED
@@ -1 +1 @@
1
- import{resolve as t}from"path";import{copyFilePersist as s}from"./lib.js";import"fs";async function i(i,o,p){const[r,a]=p.split(".");await s(t(o,r,"scripts",`${a}.js`),t(i,r,`${a}.js`))}export{i as default,i as pull};
1
+ import{promises as t}from"fs";import{dirname as i,resolve as s}from"path";const{mkdir:c,copyFile:o}=t;async function pull(t,r,a){const[p,e]=a.split(".");await function copyFilePersistent(t,s,r){return o(t,s,r).catch((async a=>{if("ENOENT"!=a.code)throw a;await c(i(s),{recursive:!0}),await o(t,s,r)}))}(s(r,p,"scripts",`${e}.js`),s(t,p,`${e}.js`))}export{pull as default,pull};
package/push.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Info } from ".";
1
+ import type { Info } from ".";
2
2
  interface PushOptions {
3
3
  /**
4
4
  * array of scripts in the format `foo.bar`
@@ -12,6 +12,8 @@ interface PushOptions {
12
12
  onPush: (info: Info) => void;
13
13
  /** whether to do the minify step (defaults to `true`) */
14
14
  minify: boolean;
15
+ /** whether to mangle function and class names (defaults to `false`) */
16
+ mangleNames: boolean;
15
17
  }
16
18
  /**
17
19
  * Push scripts from a source directory to the hackmud directory.
@@ -22,5 +24,5 @@ interface PushOptions {
22
24
  * @param options {@link PushOptions details}
23
25
  * @returns array of info on pushed scripts
24
26
  */
25
- export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify }?: Partial<PushOptions>): Promise<Info[]>;
27
+ export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames }?: Partial<PushOptions>): Promise<Info[]>;
26
28
  export default push;
package/push.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";export{push as default,push}from"./index.js";import"./lib.js";import"./processScript/index.js";import"./generateTypings.js";import"./pull.js";import"./syncMacros.js";import"chokidar";import"@babel/generator";import"perf_hooks";import"./processScript/compile.js";import"@babel/core";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"./processScript/minify.js";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";
1
+ import r from"fs";import{resolve as e,extname as a,basename as t}from"path";import{c as i}from"./processScript/minify.js";import{w as o}from"./writeFilePersistent-4e3ff264.js";import{s,processScript as p}from"./processScript/index.js";import"@babel/generator";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"./assert-1b7dada8.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";class DynamicMap extends Map{constructor(r){super(),this.fallbackHandler=r}get(r){if(super.has(r))return super.get(r);const e=this.fallbackHandler(r);return super.set(r,e),e}}function forEachParallel(r,e){const a=[];for(const t of r)a.push(e(t));return Promise.all(a)}const{readFile:n,readdir:l}=r.promises;async function push(r,c,{scripts:m="*.*",onPush:f=(r=>{}),minify:u=!0,mangleNames:g=!1}={}){"string"==typeof m&&(m=[m]);const b=new DynamicMap((r=>new Set)),h=new Set,d=new Set;let w=!1;for(const r of m){const[e,a]=r.split(".");e&&"*"!=e?a&&"*"!=a?b.get(e).add(a):h.add(e):a&&"*"!=a?d.add(a):w=!0}const y=new DynamicMap((r=>new Set)),$=[],S=new DynamicMap((r=>new Set));let P;if(d.size||w){const t=await l(e(c),{withFileTypes:!0}),i=new Set([...(P=await l(e(r),{withFileTypes:!0})).filter((r=>r.isDirectory())).map((r=>r.name)),...t.filter((r=>r.isDirectory())).map((r=>r.name)),...t.filter((r=>r.isFile()&&".key"==a(r.name))).map((r=>r.name.slice(0,-4))),...b.keys(),...h]);if(w)for(const r of i)h.add(r);else for(const r of i){const e=b.get(r);for(const r of d)e.add(r)}}return await forEachParallel(h,(async m=>{await l(e(r,m),{withFileTypes:!0}).then((async l=>{await forEachParallel(l,(async l=>{const b=a(l.name);if(l.isFile()&&s.includes(b)){const a=t(l.name,b),s=e(r,m,l.name),{srcLength:h,script:d}=await p(await n(s,{encoding:"utf-8"}),{minify:u,scriptUser:m,scriptName:a,filePath:s,mangleNames:g}),w={file:`${m}/${l.name}`,users:[m],minLength:i(d),error:null,srcLength:h};S.get(m).add(a),$.push(w),await o(e(c,m,`scripts/${a}.js`),d),f(w)}}))}),(r=>{if("ENOENT"!=r.code)throw r}))})),await forEachParallel(b,(async([a,t])=>{h.has(a)||await forEachParallel(t,(async t=>{let l,m,b;for(const i of s)try{m=`${t}${i}`,l=await n(b=e(r,a,m),{encoding:"utf-8"});break}catch{}if(l){const{srcLength:r,script:s}=await p(l,{minify:u,scriptUser:a,scriptName:t,filePath:b,mangleNames:g}),n={file:`${a}/${m}`,users:[a],minLength:i(s),error:null,srcLength:r};$.push(n),await o(e(c,a,"scripts",`${t}.js`),s),f(n)}else y.get(t).add(a)}))})),h.size?await forEachParallel(P||await l(e(r),{withFileTypes:!0}),(async l=>{const m=a(l.name);if(!l.isFile()||!s.includes(m))return;const b=t(l.name,m),d=[...h,...y.get(b)].filter((r=>!S.get(r).has(b)));if(!d.length)return;const w=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),P=e(r,l.name),{srcLength:E,script:j}=await p(await n(P,{encoding:"utf-8"}),{minify:u,scriptUser:!0,scriptName:b,uniqueID:w,filePath:P,mangleNames:g}),L={file:l.name,users:d,minLength:i(j),error:null,srcLength:E};await forEachParallel(d,(r=>o(e(c,r,`scripts/${b}.js`),j.replace(new RegExp(`$${w}$SCRIPT_USER`,"g"),r).replace(new RegExp(`$${w}$FULL_SCRIPT_NAME`,"g"),`${r}.${b}`)))),$.push(L),f(L)})):await forEachParallel(y,(async([a,t])=>{let l,m,b;for(const t of s)try{m=`${a}${t}`,l=await n(b=e(r,m),{encoding:"utf-8"});break}catch{}if(l){const r=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:s,script:n}=await p(l,{minify:u,scriptUser:!0,scriptName:a,uniqueID:r,filePath:b,mangleNames:g}),h={file:m,users:[...t],minLength:i(n),error:null,srcLength:s};await forEachParallel(t,(t=>o(e(c,t,`scripts/${a}.js`),n.replace(new RegExp(`$${r}$SCRIPT_USER`,"g"),t).replace(new RegExp(`$${r}$FULL_SCRIPT_NAME`,"g"),`${t}.${a}`)))),$.push(h),f(h)}})),$}export{DynamicMap as D,push as default,push};
@@ -0,0 +1 @@
1
+ function spliceString(i,e,s,c=0){return i.slice(0,s)+e+i.slice(s+c)}export{spliceString as s};
package/syncMacros.js CHANGED
@@ -1 +1 @@
1
- import e from"fs";import{extname as t,basename as o,resolve as a}from"path";const{readFile:s,readdir:n,stat:r,writeFile:c}=e.promises;async function i(e){const i=await n(e,{withFileTypes:!0}),m=new Map,f=[];for(const n of i)if(n.isFile())switch(t(n.name)){case".macros":{const t=(await s(a(e,n.name),{encoding:"utf-8"})).split("\n"),o=(await r(a(e,n.name))).mtime;for(let e=0;e<t.length/2-1;e++){const a=t[2*e],s=m.get(a);(!s||o>s.date)&&m.set(a,{date:o,macro:t[2*e+1]})}}break;case".key":f.push(o(n.name,".key"))}let l="",d=0;for(const[e,{macro:t}]of[...m].sort((([e],[t])=>(e>t)-(e<t))))t[0]==t[0].toLowerCase()&&(l+=`${e}\n${t}\n`,d++);for(const t of f)c(a(e,t+".macros"),l);return{macrosSynced:d,usersSynced:f.length}}export{i as default,i as syncMacros};
1
+ import e from"fs";import{extname as t,basename as s,resolve as o}from"path";const{readFile:a,readdir:n,stat:r,writeFile:c}=e.promises;async function syncMacros(e){const i=await n(e,{withFileTypes:!0}),m=new Map,f=[];for(const n of i)if(n.isFile())switch(t(n.name)){case".macros":{const t=(await a(o(e,n.name),{encoding:"utf-8"})).split("\n"),s=(await r(o(e,n.name))).mtime;for(let e=0;e<t.length/2-1;e++){const o=t[2*e],a=m.get(o);(!a||s>a.date)&&m.set(o,{date:s,macro:t[2*e+1]})}}break;case".key":f.push(s(n.name,".key"))}let l="",d=0;for(const[e,{macro:t}]of[...m].sort((([e],[t])=>(e>t)-(e<t))))t[0]==t[0].toLowerCase()&&(l+=`${e}\n${t}\n`,d++);for(const t of f)c(o(e,t+".macros"),l);return{macrosSynced:d,usersSynced:f.length}}export{syncMacros as default,syncMacros};
package/test.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";export{test as default,test}from"./index.js";import"./processScript/index.js";import"./generateTypings.js";import"./pull.js";import"./lib.js";import"./syncMacros.js";import"chokidar";import"@babel/generator";import"perf_hooks";import"./processScript/compile.js";import"@babel/core";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"./processScript/minify.js";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";
1
+ import p from"fs";import{resolve as o,extname as r}from"path";import{s as i,processScript as e}from"./processScript/index.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-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"./assert-1b7dada8.js";import"./processScript/minify.js";import"@babel/traverse";import"@babel/types";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";const{readFile:s,readdir:t}=p.promises;async function test(p){const l=[],a=[];for(const n of await t(p,{withFileTypes:!0}))n.isDirectory()?l.push(t(o(p,n.name),{withFileTypes:!0}).then((t=>{const l=[];for(const m of t)m.isFile()&&i.includes(r(m.name))&&l.push(s(o(p,n.name,m.name),{encoding:"utf-8"}).then(e).then((({warnings:p})=>a.push(...p.map((({message:p,line:o})=>({file:`${n.name}/${m.name}`,message:p,line:o})))))));return Promise.all(l)}))):n.isFile()&&i.includes(r(n.name))&&l.push(s(o(p,n.name),{encoding:"utf-8"}).then(e).then((({warnings:p})=>a.push(...p.map((({message:p,line:o})=>({file:n.name,message:p,line:o})))))));return await Promise.all(l),a}export{test as default,test};
package/watch.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Info } from ".";
1
+ import type { Info } from ".";
2
2
  /**
3
3
  * Watches target file or folder for updates and builds and pushes updated file.
4
4
  *
package/watch.js CHANGED
@@ -1 +1 @@
1
- import"chokidar";import"fs";import"path";export{watch as default,watch}from"./index.js";import"./lib.js";import"./processScript/index.js";import"./generateTypings.js";import"./pull.js";import"./syncMacros.js";import"@babel/generator";import"perf_hooks";import"./processScript/compile.js";import"@babel/core";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"./processScript/minify.js";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";
1
+ import r from"fs";import{extname as o,basename as i,resolve as p}from"path";import{c as t}from"./processScript/minify.js";import{w as e}from"./writeFilePersistent-4e3ff264.js";import{watch as s}from"chokidar";import{s as n,processScript as a}from"./processScript/index.js";import{generateTypings as l}from"./generateTypings.js";import"@babel/generator";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"./assert-1b7dada8.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";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-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";const{readFile:c,readdir:m}=r.promises;function watch(r,b,u,g,f,{genTypes:h}={}){const d=s("",{depth:1,cwd:r,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async s=>{const l=o(s);if(n.includes(l)){const h=i(s,l);if(s==i(s)){if(!g.length||g.includes(h)){const l=await c(p(r,s),{encoding:"utf-8"}),g=new Map,d=[];for(const t of await m(r,{withFileTypes:!0}))t.isDirectory()&&d.push(m(p(r,t.name),{withFileTypes:!0}).then((r=>{for(const p of r){if(!p.isFile())continue;const r=o(p.name);if(!n.includes(r))continue;const e=i(p.name,r),s=g.get(e);s?s.push(t.name):g.set(e,[t.name])}})));await Promise.all(d);let w=null;const{script:j,srcLength:y}=await a(l).catch((r=>(w=r,{script:"",srcLength:0}))),L={file:s,users:[],minLength:0,error:w,srcLength:y},F=[];if(!w)if(j){const r=g.get(h)||[];L.minLength=t(j),u.length||(u=(await m(b,{withFileTypes:!0})).filter((r=>r.isFile()&&".key"==o(r.name))).map((r=>i(r.name,".key"))));for(const o of u)r.includes(o)||(L.users.push(o),F.push(e(p(b,o,"scripts",`${h}.js`),j)))}else L.error=new Error("processed script was empty");f&&(await Promise.all(F),f(L))}}else{const o=i(p(s,".."));if((!u.length||u.includes(o))&&(!g.length||g.includes(h))){const i=await c(p(r,s),{encoding:"utf-8"});let n=null;const{script:l,srcLength:m}=await a(i).catch((r=>(n=r,{script:"",srcLength:0}))),u={file:s,users:[o],minLength:0,error:n,srcLength:m};n||(l?(u.minLength=t(l),await e(p(b,o,"scripts",`${h}.js`),l)):u.error=new Error("processed script was empty")),null==f||f(u)}}}}));h&&(l(r,p(r,h),b),d.on("add",(()=>l(r,p(r,h),b))),d.on("unlink",(()=>l(r,p(r,h),b))))}export{watch as default,watch};
@@ -0,0 +1 @@
1
+ import{promises as t}from"fs";import{dirname as i}from"path";const{writeFile:r,mkdir:e}=t;function writeFilePersistent(t,o,s){return r(t,o,s).catch((async a=>{if("ENOENT"!=a.code)throw a;await e(i(t),{recursive:!0}),await r(t,o,s)}))}export{writeFilePersistent as w};
package/bin/hsm.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/lib.d.ts DELETED
@@ -1,23 +0,0 @@
1
- /// <reference types="node" />
2
- import { PathLike } from "fs";
3
- export declare function writeFilePersist(path: string, data: any, options?: {
4
- encoding?: string | null | undefined;
5
- mode?: string | number | undefined;
6
- flag?: string | number | undefined;
7
- } | string | null): Promise<void>;
8
- export declare function copyFilePersist(src: PathLike, dest: string, flags?: number): Promise<void>;
9
- export declare function hackmudLength(script: string): number;
10
- export declare function stringSplice(original: string, replacement: string, start: number, end?: number): string;
11
- export declare class DynamicMap<K, V> extends Map<K, V> {
12
- private fallbackHandler;
13
- constructor(fallbackHandler: (key: K) => V);
14
- get(key: K): V;
15
- }
16
- export declare class CustomError extends Error {
17
- name: string;
18
- }
19
- export declare class AssertError extends CustomError {
20
- }
21
- export declare function assert(value: any, message?: string): asserts value;
22
- export declare function ensure<T>(value: T | undefined | null, message?: string): T;
23
- export declare function forEachAsync<I, O>(iterable: Iterable<I>, callback: (value: I) => Promise<O>): Promise<O[]>;
package/lib.js DELETED
@@ -1 +0,0 @@
1
- import e from"fs";import{dirname as r}from"path";const{writeFile:t,mkdir:n,copyFile:u}=e.promises;function s(e,u,s){return t(e,u,s).catch((async a=>{if("ENOENT"!=a.code)throw a;await n(r(e),{recursive:!0}),await t(e,u,s)}))}function a(e,t,s){return u(e,t,s).catch((async a=>{if("ENOENT"!=a.code)throw a;await n(r(t),{recursive:!0}),await u(e,t,s)}))}function c(e){return e.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]/g,"").length}function i(e,r,t,n=t){return e.slice(0,t)+r+e.slice(n)}class o 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}}class f extends Error{constructor(...e){var r,t,n;super(...e),r=this,t="name",n=this.constructor.name,t in r?Object.defineProperty(r,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[t]=n}}class l extends f{}function p(e,r="assertion failed"){if(!e)throw new l(r)}function h(e,r="ensure failed"){return p(e,r),e}function d(e,r){const t=[];for(const n of e)t.push(r(n));return Promise.all(t)}export{l as AssertError,f as CustomError,o as DynamicMap,p as assert,a as copyFilePersist,h as ensure,d as forEachAsync,c as hackmudLength,i as stringSplice,s as writeFilePersist};
@@ -1,3 +0,0 @@
1
- import t from "@babel/types";
2
- export declare function compile(code: string, randomString?: string, sourceCode?: string, scriptUser?: string | true, scriptName?: string | true): Promise<t.File>;
3
- export default compile;
@@ -1 +0,0 @@
1
- import{transformAsync as e}from"@babel/core";import i from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import r from"@babel/plugin-proposal-decorators";import o from"@babel/plugin-proposal-do-expressions";import a from"@babel/plugin-proposal-function-bind";import n from"@babel/plugin-proposal-function-sent";import l from"@babel/plugin-proposal-json-strings";import s from"@babel/plugin-proposal-logical-assignment-operators";import p from"@babel/plugin-proposal-nullish-coalescing-operator";import c from"@babel/plugin-proposal-numeric-separator";import d from"@babel/plugin-proposal-object-rest-spread";import f from"@babel/plugin-proposal-optional-catch-binding";import b from"@babel/plugin-proposal-optional-chaining";import u from"@babel/plugin-proposal-partial-application";import m from"@babel/plugin-proposal-pipeline-operator";import y from"@babel/plugin-proposal-private-property-in-object";import g from"@babel/plugin-proposal-record-and-tuple";import h from"@babel/plugin-proposal-throw-expressions";import _ from"@babel/plugin-transform-exponentiation-operator";import x from"@babel/plugin-transform-typescript";import E,{NodePath as S,Hub as D}from"@babel/traverse";import v from"@babel/types";import{assert as I,ensure as T}from"../lib.js";import"fs";import"path";const{default:C}=E;async function $(E,T="0",$=E,W="UNKNOWN",k="UNKNOWN"){const P=(await e(E,{plugins:[[x.default],[r.default,{decoratorsBeforeExport:!0}],[o.default],[a.default],[n.default],[u.default],[m.default,{proposal:"hack",topicToken:"%"}],[h.default],[g.default,{syntaxType:"hash"}],[i.default],[t.default],[y.default],[s.default],[c.default],[p.default],[b.default],[f.default],[l.default],[d.default],[_.default]],code:!1,ast:!0,configFile:!1})).ast,R=`_SCRIPT_${T}_`,B=new Map,G=new Map,N=S.get({container:P,hub:new D,key:"program",parent:P,parentPath:null});if(N.scope.hasGlobal("_START"))for(const e of L("_START",N))e.replaceWith(v.identifier("_ST"));if(N.scope.hasGlobal("_TIMEOUT"))for(const e of L("_START",N))e.replaceWith(v.identifier("_TO"));if(N.scope.hasGlobal("_SOURCE"))for(const e of L("_SOURCE",N))e.replaceWith(v.stringLiteral($));if(N.scope.hasGlobal("_BUILD_TIME"))for(const e of L("_BUILD_TIME",N))e.replaceWith(v.numericLiteral(Date.now()));if(N.scope.hasGlobal("_SCRIPT_USER"))for(const e of L("_SCRIPT_USER",N))1==W?e.replaceWith(v.stringLiteral(`_SCRIPT_USER_${T}_`)):e.replaceWith(v.stringLiteral(W));if(N.scope.hasGlobal("_SCRIPT_NAME"))for(const e of L("_SCRIPT_NAME",N))1==k?e.replaceWith(v.stringLiteral(`_SCRIPT_NAME_${T}_`)):e.replaceWith(v.stringLiteral(k));if(N.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of L("_FULL_SCRIPT_NAME",N))1==W||1==k?e.replaceWith(v.stringLiteral(`_FULL_SCRIPT_NAME_${T}_`)):e.replaceWith(v.stringLiteral(`${W}.${k}`));const M=v.blockStatement([]);let w;const F=[];for(const e of N.node.body)if("ExportDefaultDeclaration"==e.type)w&&M.body.push(v.variableDeclaration("let",[v.variableDeclarator(w.id,v.functionExpression(null,w.params,w.body,w.generator,w.async))])),"FunctionDeclaration"==e.declaration.type||"FunctionExpression"==e.declaration.type||"ArrowFunctionExpression"==e.declaration.type?w=v.functionDeclaration(v.identifier(R),e.declaration.params,"BlockStatement"==e.declaration.body.type?e.declaration.body:v.blockStatement([v.returnStatement(e.declaration.body)])):(I(v.isExpression(e.declaration)),w=v.functionDeclaration(v.identifier(R),[v.identifier("context"),v.identifier("args")],v.blockStatement([v.returnStatement(v.callExpression(e.declaration,[]))])));else if("ExportNamedDeclaration"==e.type){if(e.declaration)if("VariableDeclaration"==e.declaration.type)for(const i of e.declaration.declarations)I("Identifier"==i.id.type,"global variable declarations using destructure syntax is currently unsupported"),"const"==e.declaration.kind?B.set(i.id.name,i.id.name):G.set(i.id.name,i.id.name),M.body.push(v.variableDeclaration("let",[v.variableDeclarator(i.id,i.init)]));else{I("id"in e.declaration&&e.declaration.id,`unsupported export type "${e.declaration.type}"`);const i="Identifier"==e.declaration.id.type?e.declaration.id.name:e.declaration.id.value;B.set(i,i),M.body.push(e.declaration)}else if(e.specifiers)for(const i of e.specifiers)I("ExportSpecifier"==i.type,`${i.type} is currently unsupported`),F.includes(i.local.name)?G.set(i.local.name,"Identifier"==i.exported.type?i.exported.name:i.exported.value):B.set(i.local.name,"Identifier"==i.exported.type?i.exported.name:i.exported.value)}else if("VariableDeclaration"==e.type)for(const i of e.declarations)I("Identifier"==i.id.type,"global variable declarations using destructure syntax is currently unsupported"),"const"!=e.kind&&(B.has(i.id.name)?(G.set(i.id.name,B.get(i.id.name)),B.delete(i.id.name)):F.push(i.id.name)),M.body.push(v.variableDeclaration("let",[v.variableDeclarator(i.id,i.init)]));else"FunctionDeclaration"==e.type?w||e.async||e.generator?M.body.push(v.variableDeclaration("let",[v.variableDeclarator(e.id,v.functionExpression(null,e.params,e.body,e.generator,e.async))])):w=e:M.body.push(e);if(w||(w=v.functionDeclaration(v.identifier(R),[v.identifier("context"),v.identifier("args")],v.blockStatement([]))),N.node.body=[w],M.body.length){N.scope.crawl();for(const[e,i]of M.body.entries())if("VariableDeclaration"==i.type){const t=i.declarations[0];if(I("Identifier"==t.id.type,"global variable declarations using destructure syntax is currently unsupported"),N.scope.crawl(),N.scope.hasGlobal(t.id.name)){M.body.splice(e,1);const[r]=N.unshiftContainer("body",M),[o]=N.unshiftContainer("body",i);N.scope.crawl();const a=N.scope.getBinding(t.id.name);I(a);for(const e of a.referencePaths)I("Identifier"==e.node.type),e.replaceWith(v.memberExpression(v.identifier("$G"),v.identifier(e.node.name)));r.remove(),o.remove(),t.init&&M.body.splice(e,0,v.expressionStatement(v.assignmentExpression("=",v.memberExpression(v.identifier("$G"),v.identifier(t.id.name)),t.init)))}}else if("ClassDeclaration"==i.type&&(N.scope.crawl(),N.scope.hasGlobal(i.id.name))){M.body.splice(e,1);const[t]=N.unshiftContainer("body",M),[r]=N.unshiftContainer("body",i);N.scope.crawl();const o=N.scope.getBinding(i.id.name);I(o);for(const e of o.referencePaths)I("Identifier"==e.node.type),e.replaceWith(v.memberExpression(v.identifier("$G"),v.identifier(e.node.name)));t.remove(),r.remove(),M.body.splice(e,0,v.expressionStatement(v.assignmentExpression("=",v.memberExpression(v.identifier("$G"),v.identifier(i.id.name)),v.classExpression(null,i.superClass,i.body,i.decorators))))}(B.size||G.size)&&(M.body.push(v.expressionStatement(v.assignmentExpression("=",v.memberExpression(v.identifier("$G"),v.identifier("_")),v.callExpression(v.memberExpression(v.identifier("Object"),v.identifier("freeze")),[v.objectExpression([...[...B].map((([e,i])=>v.objectProperty(v.identifier(i),v.identifier(e)))),...[...G].map((([e,i])=>v.objectMethod("get",v.identifier(i),[],v.blockStatement([v.returnStatement(v.identifier(e))]))))])])))),w.body.body.push(v.returnStatement(v.memberExpression(v.identifier("$G"),v.identifier("_"))))),w.body.body.unshift(v.ifStatement(v.unaryExpression("!",v.identifier("$FMCL")),M))}C(P,{BlockStatement({node:e}){for(const[i,t]of e.body.entries())"FunctionDeclaration"!=t.type||t.generator||(e.body.splice(i,1),e.body.unshift(v.variableDeclaration("let",[v.variableDeclarator(t.id,v.arrowFunctionExpression(t.params,t.body,t.async))])))},ClassBody({node:e,scope:i,parent:t}){I(v.isClass(t));let r=!1;for(const t of e.body){if("ClassMethod"!=t.type)continue;let e=!1;if(C(t.body,{ThisExpression(i){e=!0,r=!0,i.replaceWith(v.identifier(`_THIS_${T}_`))},Function(e){e.skip()}},i),e)if("constructor"!=t.kind)t.body.body.unshift(v.variableDeclaration("let",[v.variableDeclarator(v.identifier(`_THIS_${T}_`),v.callExpression(v.memberExpression(v.super(),v.identifier("valueOf")),[]))]));else{const e=[];if(C(t.body,{CallExpression(i){"Super"==i.node.callee.type&&e.push(i)}},i),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==t)e[0].parentPath.replaceWith(v.variableDeclaration("let",[v.variableDeclarator(v.identifier(`_THIS_${T}_`),e[0].node)]));else{for(const i of e)i.replaceWith(v.assignmentExpression("=",v.identifier(`_THIS_${T}_`),i.node));t.body.body.unshift(v.variableDeclaration("let",[v.variableDeclarator(v.identifier(`_THIS_${T}_`))]))}else t.body.body.unshift(v.variableDeclaration("let",[v.variableDeclarator(v.identifier(`_THIS_${T}_`),v.callExpression(v.super(),[]))]))}}!t.superClass&&r&&(t.superClass=v.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(v.identifier(`_UNDEFINED_${T}_`))},BigIntLiteral(e){const i=Number(e.node.value);BigInt(i)==BigInt(e.node.value)?e.replaceWith(v.callExpression(v.identifier("BigInt"),[v.numericLiteral(i)])):e.replaceWith(v.callExpression(v.identifier("BigInt"),[v.stringLiteral(e.node.value)]))}});const U=N.get("body.0").scope;for(const e of[...w.params].reverse()){if("Identifier"==e.type){if(!U.getBinding(e.name).referenced){w.params.pop();continue}}break}for(const e in N.scope.globals){if("$FMCL"==e)continue;const i=L(e,N);if(!(5+e.length+i.length>=e.length*i.length)){for(const t of i)t.replaceWith(v.identifier(`_GLOBAL_${e}_${T}_`));w.body.body.unshift(v.variableDeclaration("let",[v.variableDeclarator(v.identifier(`_GLOBAL_${e}_${T}_`),v.identifier(e))]))}}return P}function L(e,i){const[t]=i.unshiftContainer("body",v.variableDeclaration("let",[v.variableDeclarator(v.identifier(e))]));i.scope.crawl();const r=T(i.scope.getBinding(e));return t.remove(),r.referencePaths}export{$ as compile,$ as default};
@@ -1,2 +0,0 @@
1
- export declare function postProcess(code: string, seclevel: number): string;
2
- export default postProcess;
@@ -1 +0,0 @@
1
- function e(e,a){return e.replace(/^function\s*\w+\(/,"function(").replace(/SC\$([a-zA-Z_][a-zA-Z0-9_]*)\$([a-zA-Z_][a-zA-Z0-9_]*)\(/g,`#${"nlmhf"[a]}s.$1.$2(`).replace(/\$D\(/g,"#D(").replace(/\$FMCL/g,"#FMCL").replace(/\$G/g,"#G").replace(/DB\$/g,"#db.")}export{e as default,e as postProcess};
@@ -1,7 +0,0 @@
1
- export declare function preProcess(code: string): {
2
- semicolons: number;
3
- autocomplete: string;
4
- seclevel: number;
5
- code: string;
6
- };
7
- export default preProcess;
@@ -1 +0,0 @@
1
- function e(e){var a,l;let s,t,c;if([,s,e,t]=e.match(/((?:^\s*\/\/.*\n)*)\s*((?:.+?\/\/\s*(.+?)\s*$)?[^]*)/m),e.match(/(?:SC|DB)\$/))throw new Error("SC$ and DB$ are protected and cannot appear in a script");for(const e of s.split("\n")){let[,a,l]=e.match(/^\s*\/\/\s*(?:@autocomplete\s*([^\s].*?)|@seclevel\s*([^\s].*?))\s*$/)||[];a?t=a:l&&(l.match(/^(?:fullsec|f|4|fs|full)$/i)?c=4:l.match(/^(?:highsec|h|3|hs|high)$/i)?c=3:l.match(/^(?:midsec|m|2|ms|mid)$/i)?c=2:l.match(/^(?:lowsec|l|1|ls|low)$/i)?c=1:l.match(/^(?:nullsec|n|0|ns|null)$/i)&&(c=0))}let n=4;e.match(/[#$][n0]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?n=0:e.match(/[#$][l1]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?n=1:e.match(/[#$][m2]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?n=2:e.match(/[#$][h3]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)&&(n=3);const o=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];if(null==c)c=n;else if(n<c)throw new Error(`detected seclevel ${o[n]} is lower than stated seclevel ${o[c]}`);return{semicolons:null!==(a=null===(l=e.match(/;/g))||void 0===l?void 0:l.length)&&void 0!==a?a:0,autocomplete:t,seclevel:c,code:e=e.replace(/#[fhmln43210]s\.scripts\.quine\(\)/g,JSON.stringify(e)).replace(/[#$][fhmln43210]?s\.([a-z_][a-z_0-9]{0,24})\.([a-z_][a-z_0-9]{0,24})\(/g,"SC$$$1$$$2(").replace(/^function\s*\(/,"export default function (").replace(/#D\(/g,"$D(").replace(/#FMCL/g,"$FMCL").replace(/#G/g,"$G").replace(/[#$]db\./g,"DB$")}}export{e as default,e as preProcess};