hackmud-script-manager 0.13.0-f0c874d → 0.14.0-496fb0f

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1 @@
1
+ const e=function createErrorClass(e){const r={[e]:class extends Error{}}[e];return Object.defineProperty(r.prototype,"name",{value:e}),r}("AssertError");function assert(r,s="assertion failed"){if(!r)throw new e(s)}function ensure(e,r="ensure failed"){return assert(e,r),e}export{assert as a,ensure as e};
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 i,dirname as n,relative as a}from"path";import{supportedExtensions as l,test as c,watch as p,push as g}from"../index.js";import{DynamicMap as b,hackmudLength as m,writeFilePersist as u}from"../lib.js";import{syncMacros as d}from"../syncMacros.js";import{pull as f}from"../pull.js";import{processScript as h}from"../processScript/index.js";import{generateTypings as k}from"../generateTypings.js";import"chokidar";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/generator";import"@babel/parser";import"acorn";import"terser";import"../processScript/postProcess.js";import"../processScript/preProcess.js";import"perf_hooks";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 T=o.rgb(255,244,4),E=o.rgb(243,249,152),I=o.rgb(179,255,155),M=o.rgb(255,150,224),O=o.rgb(30,255,0),F=o.rgb(202,202,202),L=new b((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[T,E,I,M,O,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])P.set(e.slice(2),t);else for(const o of e.slice(1))P.set(o,t)}else x.push(o);function q(){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 D(){console.log("0.13.0-f0c874d")}async function J(){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 R(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 U(){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 _({file:e,users:s,srcLength:n,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(L.get(e)))).join(", ")} | ${o.bold(String(a))} chars from ${o.bold(String(n))} | saved ${o.bold(String(n-a))} (${o.bold(`${Math.round(100*(1-a/n))}%`)}) | ${o.bold(`${t(N.hackmudPath,s[0],"scripts",r(e,i(e)))}.js`)}`))}(async()=>{if(P.get("version")||P.get("v"))D();else if(P.get("help")||P.get("h"))q();else{switch(x[0]){case"push":{const o=await J();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:_,minify:!P.get("skip-minify")}),U()}break;case"dev":case"watch":{var e,s,b;const o=await J();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,i=(null===(e=P.get("users"))||void 0===e?void 0:e.toString().split(","))||[],n=(null===(s=P.get("scripts"))||void 0===s?void 0:s.toString().split(","))||[],a=null===(b=P.get("gen-types"))||void 0===b?void 0:b.toString();p(t,r,i,n,_,{genTypes:a})}break;case"pull":{const o=await J();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){q();break}const s=x[2]||".",t=o.hackmudPath;try{await f(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 J();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 e=t(x[1]||".");let s=0;console.log(`testing scripts in ${o.bold(e)}\n`);for(const{file:t,line:r,message:i}of await c(e))console.log(`error "${o.bold(i)}" 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"),k(o,e,(await J()).hackmudPath)}break;case"config":switch(x[1]){case"get":console.log(R(await J(),x[2].split(".")));break;case"delete":{var y;const o=x[2].split(".");if(!o.length){q();break}const e=await J();null===(y=R(e,o))||void 0===y||delete y[x[3]],console.log(e)}break;case"set":{const o=x[2].split(".");if(!o.length){q();break}const e=await J();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"),q()}break;case"help":case"h":q();break;case"version":case"v":D();break;case"golf":case"minify":{if(!x[1]){console.log(`Target required\nUsage: ${r(process.argv[1])} ${x[0]} <target> [output]`);break}const e=i(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{script:i,srcLength:l,warnings:c,timeTook:p}=await h(s,{minify:!P.get("skip-minify")});for(const{message:e,line:s}of c)console.log(`warning "${o.bold(e)}" on line ${o.bold(String(s))}`);let g;if(x[2])g=x[2];else{const o=r(x[1],e);g=t(n(x[1]),o.endsWith(".src")?`${o.slice(0,-4)}.js`:".js"==e?`${o}.min.js`:`${o}.js`)}const b=m(i);await u(g,i).catch((async o=>{if(!x[2]||"EISDIR"!=o.code)throw o;g=t(g,`${r(x[1],e)}.js`),await u(g,i)})).then((()=>console.log(`wrote ${o.bold(b)} chars to ${o.bold(a(".",g))} | saved ${o.bold(l-b)} chars | took ${Math.round(100*p)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}break;default:x[0]&&console.log("unknown command"),q()}U()}})();
2
+ import o from"chalk";import e from"fs";import{homedir as s}from"os";import{resolve as t,basename as i,extname as n,dirname as r,relative as a}from"path";import{s as l,processScript as c}from"../processScript/index.js";import{D as p,w as g,push as m}from"../push.js";import{c as u}from"../processScript/minify.js";import{generateTypings as f}from"../generateTypings.js";import{syncMacros as b}from"../syncMacros.js";import{pull as h}from"../pull.js";import{watch as d}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"@babel/traverse";import"@babel/types";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"../assert-1556d989.js";import"../spliceString-2c6f214f.js";import"../processScript/preprocess.js";import"../processScript/transform.js";import"../processScript/shared.js";import"acorn";import"terser";import"chokidar";const{readFile:k,rmdir:w,writeFile:y,mkdir:j}=e.promises,v=t(s(),".config"),$=t(v,"hsm.json"),S=new Map,P=[];let C;const x=o.rgb(255,244,4),N=o.rgb(243,249,152),O=o.rgb(179,255,155),L=o.rgb(255,150,224),U=o.rgb(30,255,0),T=o.rgb(202,202,202),E=new p((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[x,N,O,L,U,T][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 P.push(o);function help(){switch(P[0]){case"config":switch(P[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(`${i(process.argv[1])} ${P[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.14.0-496fb0f")}async function getConfig(){return C||(C=await k($,{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 ${$}`),{}))))}function exploreObject(o,e,s=!1){for(const i of e){var t;o=s?"object"==typeof o[i]?o[i]:o[i]={}:null===(t=o)||void 0===t?void 0:t[i]}return o}function updateConfig(){if(C){const o=JSON.stringify(C,void 0,"\t");y($,o).catch((async e=>{switch(e.code){case"EISDIR":await w($);break;case"ENOENT":await j(v);break;default:throw e}y($,o)}))}}function onPushLogger({file:e,users:s,srcLength:r,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(E.get(e)))).join(", ")} | ${o.bold(String(a))} chars from ${o.bold(String(r))} | saved ${o.bold(String(r-a))} (${o.bold(`${Math.round(100*(1-a/r))}%`)}) | ${o.bold(`${t(C.hackmudPath,s[0],"scripts",i(e,n(e)))}.js`)}`))}(async()=>{if(S.get("version")||S.get("v"))version();else if(S.get("help")||S.get("h"))help();else{switch(P[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=P[1]||".",s=o.hackmudPath,t=P.slice(2);t.length||t.push("*.*");(await m(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 e,s,p;const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const t=P[1]||".",i=o.hackmudPath,n=(null===(e=S.get("users"))||void 0===e?void 0:e.toString().split(","))||[],r=(null===(s=S.get("scripts"))||void 0===s?void 0:s.toString().split(","))||[],a=null===(p=S.get("gen-types"))||void 0===p?void 0:p.toString();d(t,i,n,r,onPushLogger,{genTypes:a})}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=P[1];if(!e){help();break}const s=P[2]||".",t=o.hackmudPath;try{await h(s,t,e)}catch{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 b(o);console.log(`synced ${e} macros to ${s} users`)}break;case"gen-types":{const o=t(P[1]||".");f(o,P[2]?t(P[2]):t(o,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(P[1]){case"get":P[2]?console.log(exploreObject(await getConfig(),P[2].split("."))):console.log(await getConfig());break;case"delete":if(P[2]){var w;const o=P[2].split("."),e=o.pop();if(!o.length){help();break}const s=await getConfig();null===(w=exploreObject(s,o))||void 0===w||delete w[e],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(P[2]&&P[3]){const o=P[2].split(".");if(!o.length){help();break}const e=o.pop(),s=await getConfig();if(o.length||"hackmudPath"!=e){let t=s;for(const e of o)"object"==typeof t[e]||(t[e]={}),t=t[e];t[e]=P[3]}else s.hackmudPath=t(P[3]);console.log(s)}else console.log("Usage:\nhsm config set <key> <value>");break;default:P[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{const e=P[1];if(!e){console.log(`Target required\nUsage: ${i(process.argv[1])} ${P[0]} <target> [output]`);break}const s=n(e);if(!l.includes(s)){console.log(`Unsupported file extension "${o.bold(s)}"\nSupported extensions are "${l.map((e=>o.bold(e))).join('", "')}"`);break}await k(e,{encoding:"utf-8"}).then((async n=>{const l=i(e,s),p=l.endsWith(".src"),m=p?l.slice(0,-4):l;let f="UNKNOWN";"scripts"==i(t(e,".."))&&"hackmud"==i(t(e,"../../.."))&&(f=i(t(e,"../..")));const b=!S.get("skip-minify"),h=Boolean(S.get("mangle-names"));!b&&h&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:d,srcLength:k,warnings:w,timeTook:y}=await c(n,{minify:b,scriptUser:f,scriptName:m,filePath:e,mangleNames:h});for(const{message:e,line:s}of w)console.log(`warning "${o.bold(e)}" on line ${o.bold(String(s))}`);let j;j=P[2]?P[2]:t(r(e),p?`${m}.js`:".js"==s?`${l}.min.js`:`${l}.js`);const v=u(d);await g(j,d).catch((async o=>{if(!P[2]||"EISDIR"!=o.code)throw o;j=t(j,`${i(e,s)}.js`),await g(j,d)})).then((()=>console.log(`wrote ${o.bold(v)} chars to ${o.bold(a(".",j))} | saved ${o.bold(k-v)} chars | took ${Math.round(100*y)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}break;default:P[0]&&console.log("unknown command"),help()}updateConfig()}})();
@@ -1,2 +1,2 @@
1
- export declare function generateTypings(srcDir: string, target: string, hackmudPath?: string): Promise<void>;
1
+ export declare function generateTypings(sourceDirectory: string, target: string, hackmudPath?: string): Promise<void>;
2
2
  export default generateTypings;
@@ -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 n,basename as t,resolve as s,relative as r}from"path";const{readdir:i,writeFile:a}=e.promises;async function generateTypings(e,o,f){const c=new Set;if(f)for(const e of await i(f,{withFileTypes:!0}))e.isFile()&&".key"==n(e.name)&&c.add(t(e.name,".key"));const l=[],m=[],p={},$={};await Promise.all((await i(e,{withFileTypes:!0})).map((async r=>{if(r.isFile())".ts"==n(r.name)?l.push(t(r.name,".ts")):".js"==n(r.name)&&m.push(t(r.name,".js"));else if(r.isDirectory()){const a=[],o=[];p[r.name]=a,$[r.name]=o,c.add(r.name);for(const f of await i(s(e,r.name),{withFileTypes:!0}))f.isFile()&&(".ts"==n(f.name)?a.push(t(f.name,".ts")):".js"==n(f.name)&&o.push(t(f.name,".js")))}}))),e=r(".",e);let y="";for(const n of l)y+=`import $${n}$ from "./${e}/${n}"\n`;y+="\n";for(const n in p){const t=p[n];for(const s of t)y+=`import $${n}$${s}$ from "./${e}/${n}/${s}"\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 l)y+=`\t${e}: Subscript<typeof $${e}$>\n`;for(const e of m)y+=`\t${e}: (...args: any) => any\n`;y+="}\n\ninterface PlayerFullsec {";let u=!0;for(const e of c){const n=p[e],t=$[e];if(n&&n.length||t&&t.length){if(u=!0,y+=`\n\t${e}: WildFullsec & {\n`,n)for(const t of n)y+=`\t\t${t}: Subscript<typeof $${e}$${t}$>\n`;if(t)for(const e of t)y+=`\t\t${e}: (...args: any) => any\n`;y+="\t}"}else u&&(y+="\n",u=!1),y+=`\t${e}: WildFullsec`;y+="\n"}y+="}\n",await a(o,y)}export{generateTypings as default,generateTypings};
package/index.d.ts CHANGED
@@ -1,15 +1,14 @@
1
- export interface Info {
1
+ export { supportedExtensions } from "./constants.json";
2
+ export { generateTypings } from "./generateTypings";
3
+ export { processScript } from "./processScript";
4
+ export { pull } from "./pull";
5
+ export { push } from "./push";
6
+ export { syncMacros } from "./syncMacros";
7
+ export { watch } from "./watch";
8
+ export declare type Info = {
2
9
  file: string;
3
10
  users: string[];
4
11
  srcLength: number;
5
12
  minLength: number;
6
- error: Error | null;
7
- }
8
- export declare const supportedExtensions: string[];
9
- export * from "./push";
10
- export * from "./watch";
11
- export * from "./pull";
12
- export * from "./syncMacros";
13
- export * from "./test";
14
- export * from "./generateTypings";
15
- export * from "./processScript";
13
+ error: Error | undefined;
14
+ };
package/index.js CHANGED
@@ -1 +1 @@
1
- import e from"fs";import{resolve as i,extname as s,basename as t}from"path";import{watch as r}from"chokidar";import{DynamicMap as n,forEachAsync as o,hackmudLength as a,writeFilePersist as p}from"./lib.js";import{generateTypings as l}from"./generateTypings.js";export{generateTypings}from"./generateTypings.js";import{processScript as c}from"./processScript/index.js";export{processScript}from"./processScript/index.js";export{pull}from"./pull.js";export{syncMacros}from"./syncMacros.js";export{compile}from"./processScript/compile.js";export{minify}from"./processScript/minify.js";export{postProcess}from"./processScript/postProcess.js";export{preProcess}from"./processScript/preProcess.js";import"@babel/generator";import"perf_hooks";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{readFile:m,readdir:f}=e.promises;async function g(e,r,{scripts:l="*.*",onPush:g=(e=>{}),minify:u=!0}={}){"string"==typeof l&&(l=[l]);const h=new n((e=>new Set)),w=new Set,b=new Set;let d=!1;for(const e of l){const[i,s]=e.split(".");i&&"*"!=i?s&&"*"!=s?h.get(i).add(s):w.add(i):s&&"*"!=s?b.add(s):d=!0}const y=new n((e=>new Set)),j=[],F=new n((e=>new Set));let $;if(b.size||d){const t=await f(i(r),{withFileTypes:!0}),n=new Set([...($=await f(i(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"==s(e.name))).map((e=>e.name.slice(0,-4))),...h.keys(),...w]);if(d)for(const e of n)w.add(e);else for(const e of n){const i=h.get(e);for(const e of b)i.add(e)}}return await o(w,(async n=>{await f(i(e,n),{withFileTypes:!0}).then((async l=>{await o(l,(async o=>{const l=s(o.name);if(o.isFile()&&L.includes(l)){const{srcLength:s,script:f}=await c(await m(i(e,n,o.name),{encoding:"utf-8"}),{minify:u}),h={file:`${n}/${o.name}`,users:[n],minLength:a(f),error:null,srcLength:s},w=t(o.name,l);F.get(n).add(w),j.push(h),await p(i(r,n,`scripts/${w}.js`),f),g(h)}}))}),(e=>{if("ENOENT"!=e.code)throw e}))})),await o(h,(async([s,t])=>{w.has(s)||await o(t,(async t=>{let n,o;for(const r of L)try{o=`${t}${r}`,n=await m(i(e,s,o),{encoding:"utf-8"});break}catch{}if(n){const{srcLength:e,script:l}=await c(n,{minify:u}),m={file:`${s}/${o}`,users:[s],minLength:a(l),error:null,srcLength:e};j.push(m),await p(i(r,s,"scripts",`${t}.js`),l),g(m)}else y.get(t).add(s)}))})),w.size?await o($||await f(i(e),{withFileTypes:!0}),(async n=>{const l=s(n.name);if(!n.isFile()||!L.includes(l))return;const f=t(n.name,l),h=[...w,...y.get(f)].filter((e=>!F.get(e).has(f)));if(!h.length)return;const{srcLength:b,script:d}=await c(await m(i(e,n.name),{encoding:"utf-8"}),{minify:u}),$={file:n.name,users:h,minLength:a(d),error:null,srcLength:b};await o(h,(e=>p(i(r,e,`scripts/${f}.js`),d))),j.push($),g($)})):await o(y,(async([s,t])=>{let n,l;for(const t of L)try{l=`${s}${t}`,n=await m(i(e,l),{encoding:"utf-8"});break}catch{}if(n){const{srcLength:e,script:m}=await c(n,{minify:u}),f={file:l,users:[...t],minLength:a(m),error:null,srcLength:e};await o(t,(e=>p(i(r,e,"scripts",`${s}.js`),m))),j.push(f),g(f)}})),j}const{readFile:u,readdir:h}=e.promises;function w(e,n,o,m,f,{genTypes:g}={}){const w=r("",{depth:1,cwd:e,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async r=>{const l=s(r);if(L.includes(l)){const g=t(r,l);if(r==t(r)){if(!m.length||m.includes(g)){const l=await u(i(e,r),{encoding:"utf-8"}),m=new Map,w=[];for(const r of await h(e,{withFileTypes:!0}))r.isDirectory()&&w.push(h(i(e,r.name),{withFileTypes:!0}).then((e=>{for(const i of e){if(!i.isFile())continue;const e=s(i.name);if(!L.includes(e))continue;const n=t(i.name,e),o=m.get(n);o?o.push(r.name):m.set(n,[r.name])}})));await Promise.all(w);let b=null;const{script:d,srcLength:y}=await c(l).catch((e=>(b=e,{script:"",srcLength:0}))),j={file:r,users:[],minLength:0,error:b,srcLength:y},F=[];if(!b)if(d){const e=m.get(g)||[];j.minLength=a(d),o.length||(o=(await h(n,{withFileTypes:!0})).filter((e=>e.isFile()&&".key"==s(e.name))).map((e=>t(e.name,".key"))));for(const s of o)e.includes(s)||(j.users.push(s),F.push(p(i(n,s,"scripts",`${g}.js`),d)))}else j.error=new Error("processed script was empty");f&&(await Promise.all(F),f(j))}}else{const s=t(i(r,".."));if((!o.length||o.includes(s))&&(!m.length||m.includes(g))){const t=await u(i(e,r),{encoding:"utf-8"});let o=null;const{script:l,srcLength:m}=await c(t).catch((e=>(o=e,{script:"",srcLength:0}))),h={file:r,users:[s],minLength:0,error:o,srcLength:m};o||(l?(h.minLength=a(l),await p(i(n,s,"scripts",`${g}.js`),l)):h.error=new Error("processed script was empty")),null==f||f(h)}}}}));g&&(l(e,i(e,g),n),w.on("add",(()=>l(e,i(e,g),n))),w.on("unlink",(()=>l(e,i(e,g),n))))}const{readFile:b,readdir:d}=e.promises;async function y(e){const t=[],r=[];for(const n of await d(e,{withFileTypes:!0}))n.isDirectory()?t.push(d(i(e,n.name),{withFileTypes:!0}).then((t=>{const o=[];for(const a of t)a.isFile()&&L.includes(s(a.name))&&o.push(b(i(e,n.name,a.name),{encoding:"utf-8"}).then(c).then((({warnings:e})=>r.push(...e.map((({message:e,line:i})=>({file:`${n.name}/${a.name}`,message:e,line:i})))))));return Promise.all(o)}))):n.isFile()&&L.includes(s(n.name))&&t.push(b(i(e,n.name),{encoding:"utf-8"}).then(c).then((({warnings:e})=>r.push(...e.map((({message:e,line:i})=>({file:n.name,message:e,line:i})))))));return await Promise.all(t),r}const L=[".js",".ts"];export{g as push,L as supportedExtensions,y as test,w 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{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"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"path";import"perf_hooks";import"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./assert-1556d989.js";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";import"fs";import"chokidar";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hackmud-script-manager",
3
- "version": "0.13.0-f0c874d",
3
+ "version": "0.14.0-496fb0f",
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,44 @@
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": "^5.0.0",
62
+ "chokidar": "^3.5.2",
63
+ "prettier": "^2.4.1",
64
+ "proxy-polyfill": "^0.3.2",
65
+ "rollup": "^2.60.0",
66
+ "terser": "^5.10.0"
67
+ },
68
+ "devDependencies": {
69
+ "@babel/preset-env": "^7.16.4",
70
+ "@babel/preset-typescript": "^7.16.0",
71
+ "@samual/lib": "^0.3.0-ac21d09",
83
72
  "@types/babel__core": "^7.1.16",
84
- "@types/node": "12.x",
85
- "@types/semver": "7.x",
86
- "rollup": "^2.56.3",
73
+ "@types/node": "^12.20.37",
74
+ "@types/prettier": "^2.4.2",
75
+ "@types/semver": "^7.3.9",
76
+ "@typescript-eslint/eslint-plugin": "^5.8.0",
77
+ "@typescript-eslint/parser": "^5.8.1",
78
+ "eslint": "^8.5.0",
79
+ "eslint-plugin-array-func": "^3.1.7",
80
+ "eslint-plugin-eslint-comments": "^3.2.0",
81
+ "eslint-plugin-optimize-regex": "^1.2.1",
82
+ "eslint-plugin-regexp": "^1.5.1",
83
+ "eslint-plugin-unicorn": "^40.1.0",
84
+ "eslint-plugin-write-good-comments": "^0.1.3",
85
+ "latest-version": "^6.0.0",
87
86
  "rollup-plugin-preserve-shebang": "^1.0.1",
88
87
  "rollup-plugin-terser": "^7.0.2",
89
- "semver": "7.x",
90
- "typescript": "^4.4.4"
88
+ "semver": "^7.3.5",
89
+ "typescript": "^4.5.2"
90
+ },
91
+ "optionalDependencies": {
92
+ "deasync": "^0.1.24"
91
93
  },
92
94
  "engines": {
93
95
  "node": "^12.20 || >=14"
@@ -95,10 +97,27 @@
95
97
  "types": "index.d.ts",
96
98
  "type": "module",
97
99
  "exports": {
98
- "require": "./index.cjs",
99
- "import": "./index.js"
100
+ ".": {
101
+ "import": "./index.js",
102
+ "require": "./index.cjs"
103
+ },
104
+ "./*": "./*",
105
+ "./generateTypings": "./generateTypings.js",
106
+ "./index": "./index.js",
107
+ "./pull": "./pull.js",
108
+ "./push": "./push.js",
109
+ "./syncMacros": "./syncMacros.js",
110
+ "./watch": "./watch.js",
111
+ "./bin/hsm": "./bin/hsm.js",
112
+ "./processScript/index": "./processScript/index.js",
113
+ "./processScript": "./processScript/index.js",
114
+ "./processScript/minify": "./processScript/minify.js",
115
+ "./processScript/postprocess": "./processScript/postprocess.js",
116
+ "./processScript/preprocess": "./processScript/preprocess.js",
117
+ "./processScript/shared": "./processScript/shared.js",
118
+ "./processScript/transform": "./processScript/transform.js"
100
119
  },
101
- "optionalDependencies": {
102
- "deasync": "^0.1.23"
120
+ "bin": {
121
+ "hsm": "./bin/hsm.js"
103
122
  }
104
- }
123
+ }
@@ -1,15 +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 going to be hosting this script (or set to `true` if not yet known) */
11
+ scriptUser: string | true;
12
+ /** the name of this script (or set to `true` if 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 }?: {
11
- minify?: boolean | undefined;
12
- }): Promise<{
24
+ export declare function processScript(code: string, { minify: shouldMinify, uniqueID, scriptUser, scriptName, filePath, mangleNames }?: Partial<ProcessOptions>): Promise<{
13
25
  srcLength: number;
14
26
  script: string;
15
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}={}){var n,m,b,c,u,g;const f=p.now(),d=Math.floor(Math.random()*2**52).toString(36);let h,v,j;({autocomplete:h,code:o,seclevel:v,semicolons:j}=e(o)),o=a(await i(o,d)).code;let x=r(o.replace(/^function\s*\w+\(/,"function("))-(null!==(n=null===(m=o.match(/;/g))||void 0===m?void 0:m.length)&&void 0!==n?n:0)+j+(null!==(b=null===(c=o.match(/SC\$[a-zA-Z_][a-zA-Z0-9_]*\$[a-zA-Z_][a-zA-Z0-9_]*\(/g))||void 0===c?void 0:c.length)&&void 0!==b?b:0)+(null!==(u=null===(g=o.match(/DB\$/g))||void 0===g?void 0:g.length)&&void 0!==u?u:0);return s&&(o=await t(o,h,d)),{srcLength:x,script:o=l(o,v),warnings:[],timeTook:p.now()-f}}export{s as default,s as processScript};
1
+ import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import s from"@babel/plugin-proposal-decorators";import p from"@babel/plugin-proposal-do-expressions";import a from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import i from"@babel/plugin-proposal-json-strings";import n from"@babel/plugin-proposal-logical-assignment-operators";import m from"@babel/plugin-proposal-nullish-coalescing-operator";import c from"@babel/plugin-proposal-numeric-separator";import f from"@babel/plugin-proposal-object-rest-spread";import u 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 w from"@babel/plugin-proposal-record-and-tuple";import y from"@babel/plugin-proposal-throw-expressions";import x from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import S from"@babel/traverse";import k from"@babel/types";import v from"@rollup/plugin-babel";import E from"@rollup/plugin-commonjs";import N from"@rollup/plugin-json";import C from"@rollup/plugin-node-resolve";import{resolve as L}from"path";import{performance as _}from"perf_hooks";import I from"prettier";import{rollup as D}from"rollup";import{c as U,minify as $}from"./minify.js";export{minify}from"./minify.js";import{postprocess as M}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as W}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{transform as q}from"./transform.js";export{transform as compile}from"./transform.js";import{a as F}from"../assert-1556d989.js";import"acorn";import"terser";import"./shared.js";import"../spliceString-2c6f214f.js";const T=[".js",".ts"],{default:H}=v,{format:O}=I,{default:P}=e,{default:K}=S;async function processScript(e,{minify:S=!0,uniqueID:v=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:I="UNKNOWN",scriptName:z="UNKNOWN",filePath:B,mangleNames:G=!1}={}){F(/^\w{11}$/.exec(v)),B=B?L(B):"script";const A=_.now(),J=e;let Q,R;const V=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(V)e=`export default ${e}`,({autocomplete:Q}=V.groups);else for(const o of e.split("\n")){const e=/^\s*\/\/(?<commentContent>.+)/.exec(o);if(!e)break;const r=e.groups.commentContent.trim();if(r.startsWith("@autocomplete "))Q=r.slice(14).trimStart();else if(r.startsWith("@seclevel ")){const e=r.slice(10).trimStart().toLowerCase();switch(e){case"fullsec":case"full":case"fs":case"4s":case"f":case"4":R=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":R=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":R=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":R=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":R=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}F(/^\w{11}$/.exec(v));const X=B?L(B):"script";let Y=4;const Z=await D({plugins:[{name:"emit script",buildStart(){this.emitFile({type:"chunk",id:X})},load(o){if(o==X)return e},transform(e){const{code:o,seclevel:r}=W(e,{uniqueID:v});return Y=Math.min(Y,r),o}},H({babelHelpers:"bundled",plugins:[[j.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[s.default,{decoratorsBeforeExport:!0}],[p.default],[a.default],[l.default],[d.default],[g.default,{proposal:"hack",topicToken:"%"}],[y.default],[w.default,{syntaxType:"hash",importPolyfill:!0}],[r.default],[t.default],[h.default],[n.default],[c.default],[m.default],[b.default],[u.default],[i.default],[f.default],[x.default]],configFile:!1,extensions:T}),E(),C({extensions:T}),N()],treeshake:{moduleSideEffects:!1}}),ee=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];let oe;if(e=(await Z.generate({})).output[0].code,({file:oe,seclevel:Y}=await q(o(e,{sourceType:"module"}),J,{uniqueID:v,scriptUser:I,scriptName:z,seclevel:Y})),null!=R&&Y<R)throw new Error(`detected seclevel ${ee[Y]} is lower than stated seclevel ${ee[R]}`);e=P(oe).code;const re=U(e.replace(/^function\s*\w+\(/,"function("));return S?e=await $(oe,Q,{uniqueID:v,mangleNames:G}):(K(oe,{MemberExpression({node:e}){e.computed||(F("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=k.stringLiteral("prototype")):"__proto__"==e.property.name&&(e.computed=!0,e.property=k.stringLiteral("__proto__")))}}),e=O(P(oe).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),{srcLength:re,script:e=M(e,Y,v),warnings:[],timeTook:_.now()-A}}export{processScript as default,processScript,T as s};
@@ -1,2 +1,14 @@
1
- export declare function minify(code: string, autocomplete: string, randomString?: string): Promise<string>;
1
+ import { File } from "@babel/types";
2
+ declare type MinifyOptions = {
3
+ /** 11 a-z 0-9 characters */
4
+ uniqueID: string;
5
+ /** whether to mangle function and class names (defaults to `false`) */
6
+ mangleNames: boolean;
7
+ };
8
+ /**
9
+ * @param code compiled code and/or hackmud compatible code
10
+ * @param autocomplete the comment inserted after the function signature
11
+ * @param options {@link MinifyOptions details}
12
+ */
13
+ export declare function minify(file: File, autocomplete?: string, { uniqueID, mangleNames }?: Partial<MinifyOptions>): Promise<string>;
2
14
  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 t from"@babel/traverse";import r from"@babel/types";import{tokenizer as i,tokTypes as n}from"acorn";import*as a from"terser";import{getReferencePathsToGlobal as s}from"./shared.js";import{a as o}from"../assert-1556d989.js";import{s as p}from"../spliceString-2c6f214f.js";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:i="00000000000",mangleNames:n=!1}={}){let c;o(/^\w{11}$/.exec(i)),u(e,{Program(e){c=e,e.skip()}});const f=c.get("body.0");for(const e of[...f.node.params].reverse()){if("Identifier"==e.type){if(!f.scope.getBinding(e.name).referenced){f.node.params.pop();continue}}break}for(const e in c.scope.globals){if("arguments"==e||e.startsWith(`$${i}`))continue;const t=s(e,c);if(!(5+e.length+t.length>=e.length*t.length)){for(const n of t)n.replaceWith(r.identifier(`_GLOBAL_${e}_${i}_`));f.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_GLOBAL_${e}_${i}_`),r.identifier(e))]))}}const d=s(`$${i}$GLOBAL`,c);if(d.length>3){for(const e of d)e.replaceWith(r.identifier(`_G_${i}_`));f.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_G_${i}_`),r.identifier(`$${i}$GLOBAL`))]))}const m=[];let y=!1;const _=r.cloneNode(e);u(_,{MemberExpression({node:e}){e.computed||(o("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=r.identifier(`_PROTOTYPE_PROPERTY_${i}_`)):"__proto__"==e.property.name&&(e.computed=!0,e.property=r.identifier(`_PROTO_PROPERTY_${i}_`)))}});const $=(await a.minify(l(_).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:!n,keep_fnames:!n})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${i}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${i}_`,"g"),'"__proto__"');let E,b,g=!1;{const t=[];u(e,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const t={};parseObjectExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${m.push(t)-1}_${i}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${m.push(t)-1}_${i}_`))}}),e.traverse({TemplateLiteral(e){const t=e.node;let i=r.stringLiteral(t.quasis[0].value.cooked);for(let e=0;e<t.expressions.length;e++){const n=t.expressions[e],a=t.quasis[e+1];i=r.binaryExpression("+",i,n),a.value.cooked&&(i=r.binaryExpression("+",i,r.stringLiteral(a.value.cooked)))}e.replaceWith(i)},MemberExpression({node:e}){e.computed||(o("Identifier"==e.property.type),e.property.name.length<3||(e.computed=!0,e.property=r.stringLiteral(e.property.name)))},UnaryExpression(e){if("void"==e.node.operator)"NumericLiteral"!=e.node.argument.type||e.node.argument.value||(e.replaceWith(r.identifier(`_UNDEFINED_${i}_`)),y=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const n=-e.node.argument.value;t.push((async()=>{if((await minifyNumber(n)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=m.indexOf(n);-1==t&&(t+=m.push(n)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))})()),e.skip()}},NullLiteral(e){let t=m.indexOf(null);-1==t&&(t+=m.push(null)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},BooleanLiteral(e){let t=m.indexOf(e.node.value);-1==t&&(t+=m.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},NumericLiteral(e){t.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=m.indexOf(e.node.value);-1==t&&(t+=m.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))})())},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 t=m.indexOf(e.node.value);-1==t&&(t+=m.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=m.indexOf(e.key.name);-1==t&&(t+=m.push(e.key.name)),e.computed=!0,e.key=r.identifier(`_JSON_VALUE_${t}_${i}_`)}}),e.skip()}}),await Promise.all(t);const n=e.program.body[0];if(o("FunctionDeclaration"==n.type),m.length)if(g=!0,1==m.length)if("string"!=typeof m[0]||m[0].includes("\n")||m[0].includes("\t")){const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_JSON_VALUE_0_${i}_`),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX`),!0)]))]);y&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),E=JSON.stringify(m[0])}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_JSON_VALUE_0_${i}_`),r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX`),!0))]);y&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),E=m[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern(m.map(((e,t)=>r.identifier(`_JSON_VALUE_${t}_${i}_`)))),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX`),!0)]))]);y&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),E=JSON.stringify(m)}else y&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))]));b=l(e).code}return b=(await a.minify(b,{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:!n,keep_fnames:!n})).code||"",null!=E&&(b=p(b,`${t?`//${t}\n`:""}\n//\t${E}\t\n`,getFunctionBodyStart(b)+1),b=b.replace(`$${i}$SPLIT_INDEX`,await minifyNumber(b.split("\t").findIndex((e=>e==E))))),countHackmudCharacters($)<=countHackmudCharacters(b)+Number(g)&&(b=$,t&&(b=p(b,`//${t}\n`,getFunctionBodyStart(b)+1))),b}function parseObjectExpression(e,t){if(!e.properties.length)return!1;for(const r of e.properties){if("ObjectProperty"!=r.type||r.computed)return!1;if(o("Identifier"==r.key.type||"NumericLiteral"==r.key.type||"StringLiteral"==r.key.type),"ArrayExpression"==r.value.type){const e=[];if(!parseArrayExpression(r.value,e))return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=e}else if("ObjectExpression"==r.value.type){const e={};if(!parseObjectExpression(r.value,e))return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=e}else if("NullLiteral"==r.value.type)t["Identifier"==r.key.type?r.key.name:r.key.value]=null;else if("BooleanLiteral"==r.value.type||"NumericLiteral"==r.value.type||"StringLiteral"==r.value.type)t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.value;else{if("TemplateLiteral"!=r.value.type||r.value.expressions.length)return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.quasis[0].value.cooked}}return!0}function parseArrayExpression(e,t){if(!e.elements.length)return!1;for(const r of e.elements){if(!r)return!1;if("ArrayExpression"==r.type){const e=[];if(!parseArrayExpression(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!parseObjectExpression(r,e))return!1;t.push(e)}else if("NullLiteral"==r.type)t.push(null);else if("BooleanLiteral"==r.type||"NumericLiteral"==r.type||"StringLiteral"==r.type)t.push(r.value);else{if("TemplateLiteral"!=r.type||r.expressions.length)return!1;t.push(r.quasis[0].value.cooked)}}return!0}async function minifyNumber(e){return/\$\((?<number>.+)\)/.exec((await a.minify(`$(${e})`,{ecma:2015})).code).groups.number}function getFunctionBodyStart(e){const t=i(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let r=1;for(;r;){const e=t.getToken();e.type==n.parenL?r++:e.type==n.parenR&&r--}return t.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{a as e}from"../assert-1556d989.js";import{s}from"../spliceString-2c6f214f.js";function*findMatches(s,t){let n;for(e(s.global,"regex must have global flag");n=s.exec(t);)yield{index:n.index,match:n[1]||n[0]}}function postprocess(e,t,n){e=e.replace(/^function\s*\w+\(/,"function(");for(const{index:r,match:a}of[...findMatches(new RegExp(`\\$${n}\\$[\\w$]+`,"g"),e)].reverse()){const[n,...o]=a.slice(13).split("$");switch(n){case"SUBSCRIPT":e=s(e,`#${"nlmhf"[t]}s.${o[0]}.${o[1]}`,r,a.length);break;case"DEBUG":e=s(e,"#D",r,a.length);break;case"FMCL":e=s(e,"#FMCL",r,a.length);break;case"GLOBAL":e=s(e,"#G",r,a.length);break;case"DB":e=s(e,`#db.${o[0]}`,r,a.length);break;default:throw new Error(`unknown type "${n}"`)}}return e}export{postprocess as default,postprocess};
@@ -0,0 +1,13 @@
1
+ export declare type PreprocessOptions = {
2
+ /** 11 a-z 0-9 characters */
3
+ uniqueID: string;
4
+ };
5
+ /**
6
+ * @param code source code for preprocessing
7
+ * @param options {@link PreprocessOptions details}
8
+ */
9
+ export declare function preprocess(code: string, { uniqueID }?: Partial<PreprocessOptions>): {
10
+ code: string;
11
+ seclevel: number;
12
+ };
13
+ export default preprocess;
@@ -0,0 +1 @@
1
+ import e from"@babel/generator";import{parse as r}from"@babel/parser";import o from"@babel/traverse";import i from"@babel/types";import{a as t}from"../assert-1556d989.js";import{s}from"../spliceString-2c6f214f.js";const{default:p}=o,{default:l}=e;function preprocess(e,{uniqueID:o="00000000000"}={}){if(t(/^\w{11}$/.test(o)),/(?:SC|DB)\$/.test(e))throw new Error("SC$ and DB$ are protected and cannot appear in a script");const n=e;let a;do{a=e.length,e=e.replace(/^\s+/,"").replace(/^\/\/.*/,"").replace(/^\/\*[\s\S]*?\*\//,"")}while(e.length!=a);e=e.replace(/^function\s*\(/,"export default function (");const c={f:4,h:3,m:2,l:1,n:0,4:4,3:3,2:2,1:1,0:0};let d,f,u=4;for(;;){let i;try{d=r(e,{plugins:["typescript",["decorators",{decoratorsBeforeExport:!0}],"doExpressions","functionBind","functionSent","partialApplication",["pipelineOperator",{proposal:"hack",topicToken:"%"}],"throwExpressions",["recordAndTuple",{syntaxType:"hash"}],"classProperties","classPrivateProperties","classPrivateMethods","logicalAssignment","numericSeparator","nullishCoalescingOperator","optionalChaining","optionalCatchBinding","objectRestSpread"],sourceType:"module"});break}catch(e){t(e instanceof SyntaxError),i=e}var m;if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(null===(m=/.+/.exec(e.slice(i.pos)))||void 0===m?void 0:m[0]),i;const p=e.slice(i.pos);let l;if(l=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(p))e=s(e,JSON.stringify(n),i.pos,l[0].length);else if(l=/^#(?<seclevel>[0-4fhmln])?s\.(?<userName>[_a-z][\d_a-z]{0,24})\.(?<scriptName>[_a-z][\d_a-z]{0,24})\(/.exec(p))l[1]&&(u=Math.min(u,c[l[1]])),e=s(e,`$${o}$SUBSCRIPT$${l[2]}$${l[3]}(`,i.pos,l[0].length);else if(l=/^#D\(/.exec(p))e=s(e,`$${o}$DEBUG(`,i.pos,l[0].length);else if(l=/^#FMCL/.exec(p))e=s(e,`$${o}$FMCL`,i.pos,l[0].length);else if(l=/^#G/.exec(p))e=s(e,`$${o}$GLOBAL`,i.pos,l[0].length);else{if(!(l=/^#db\.(?<methodName>[irfu]|u1|us|ObjectId)\(/.exec(p)))throw i;e=s(e,`$${o}$DB$${l[1]}(`,i.pos,l[0].length)}}p(d,{Program(e){f=e,e.skip()}});const h=f.scope.hasGlobal("Record"),$=f.scope.hasGlobal("Tuple");return(h||$)&&d.program.body.unshift(i.importDeclaration(h?$?[i.importSpecifier(i.identifier("Record"),i.identifier("Record")),i.importSpecifier(i.identifier("Tuple"),i.identifier("Tuple"))]:[i.importSpecifier(i.identifier("Record"),i.identifier("Record"))]:[i.importSpecifier(i.identifier("Tuple"),i.identifier("Tuple"))],i.stringLiteral("@bloomberg/record-tuple-polyfill"))),f.scope.hasGlobal("Proxy")&&d.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral("proxy-polyfill/src/proxy.js"))),1==f.node.body.length&&"FunctionDeclaration"==f.node.body[0].type?{code:`export default ${l(d).code}`,seclevel:u}:{code:l(d).code,seclevel:u}}export{preprocess as default,preprocess};
@@ -0,0 +1,3 @@
1
+ import { NodePath } from "@babel/traverse";
2
+ import t, { Program } from "@babel/types";
3
+ export declare function getReferencePathsToGlobal(name: string, program: NodePath<Program>): NodePath<t.Identifier>[];
@@ -0,0 +1 @@
1
+ import e from"@babel/types";import{e as r}from"../assert-1556d989.js";function getReferencePathsToGlobal(t,o){const[a]=o.unshiftContainer("body",e.variableDeclaration("let",[e.variableDeclarator(e.identifier(t))]));o.scope.crawl();const n=r(o.scope.getBinding(t));return a.remove(),n.referencePaths}export{getReferencePathsToGlobal};
@@ -0,0 +1,22 @@
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 going to be hosting this script (or set to `true` if not yet known) */
6
+ scriptUser: string | true;
7
+ /** the name of this script (or set to `true` if 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>): {
19
+ file: t.File;
20
+ seclevel: number;
21
+ };
22
+ export default transform;
@@ -0,0 +1 @@
1
+ import e from"@babel/traverse";import t from"@babel/types";import{getReferencePathsToGlobal as i}from"./shared.js";import{a as r}from"../assert-1556d989.js";function clearObject(e,t){for(const t of Object.getOwnPropertyNames(e))delete e[t];for(const t of Object.getOwnPropertySymbols(e))delete e[t];void 0!==t&&Object.setPrototypeOf(e,t)}const{default:n}=e,o=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,a,{uniqueID:s="00000000000",scriptUser:p="UNKNOWN",scriptName:l="UNKNOWN",seclevel:c=4}={}){const d=`_SCRIPT_${s}_`,f=new Map,b=new Map;let y;if(n(e,{Program(e){y=e,e.skip()}}),y.scope.hasGlobal("_START"))for(const e of i("_START",y))e.replaceWith(t.identifier("_ST"));if(y.scope.hasGlobal("_TIMEOUT"))for(const e of i("_START",y))e.replaceWith(t.identifier("_TO"));if(y.scope.hasGlobal("_SOURCE"))for(const e of i("_SOURCE",y))e.replaceWith(t.stringLiteral(a));if(y.scope.hasGlobal("_BUILD_DATE"))for(const e of i("_BUILD_DATE",y))e.replaceWith(t.numericLiteral(Date.now()));if(y.scope.hasGlobal("_SCRIPT_USER"))for(const e of i("_SCRIPT_USER",y))1==p?e.replaceWith(t.stringLiteral(`$${s}$SCRIPT_USER`)):e.replaceWith(t.stringLiteral(p));if(y.scope.hasGlobal("_SCRIPT_NAME"))for(const e of i("_SCRIPT_NAME",y))1==l?e.replaceWith(t.stringLiteral(`$${s}$SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(l));if(y.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of i("_FULL_SCRIPT_NAME",y))1==p||1==l?e.replaceWith(t.stringLiteral(`$${s}$FULL_SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(`${p}.${l}`));let h=!1;if(y.scope.hasGlobal("Function")){const e=i("Function",y);if(1==e.length){const t=e[0];r("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("prototype"==t.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const i of e)r("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,i.parentPath.replaceWith(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`));h=!0}}let m=4;for(const e of["$fs","$4s","$s"])if(y.scope.hasGlobal(e))for(const n of i(e,y)){var $;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===($=n.parentPath.parentPath)||void 0===$?void 0:$.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}for(const e of["$hs","$3s"])if(y.scope.hasGlobal(e)){m=3;for(const n of i(e,y)){var E;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(E=n.parentPath.parentPath)||void 0===E?void 0:E.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ms","$2s"])if(y.scope.hasGlobal(e)){m=2;for(const n of i(e,y)){var P;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(P=n.parentPath.parentPath)||void 0===P?void 0:P.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ls","$1s"])if(y.scope.hasGlobal(e)){m=1;for(const n of i(e,y)){var u;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(u=n.parentPath.parentPath)||void 0===u?void 0:u.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ns","$0s"])if(y.scope.hasGlobal(e)){m=0;for(const n of i(e,y)){var _;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(_=n.parentPath.parentPath)||void 0===_?void 0:_.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}if(c=Math.min(c,m),y.scope.hasGlobal("$db"))for(const e of i("$db",y))r("MemberExpression"==e.parentPath.node.type),r("Identifier"==e.parentPath.node.property.type),e.parentPath.replaceWith(t.identifier(`$${s}$DB$${e.parentPath.node.property.name}`));if(y.scope.hasGlobal("$D"))for(const e of i("$D",y))e.replaceWith(t.identifier(`$${s}$DEBUG`));if(y.scope.hasGlobal("$FMCL"))for(const e of i("$FMCL",y))e.replaceWith(t.identifier(`$${s}$FMCL`));if(y.scope.hasGlobal("$G"))for(const e of i("$G",y))e.replaceWith(t.identifier(`$${s}$GLOBAL`));if(y.scope.hasGlobal("_SECLEVEL"))for(const e of i("_SECLEVEL",y))e.replaceWith(t.numericLiteral(c));let T=!1,O=!1;if(y.scope.hasGlobal("Object"))for(const e of i("Object",y))"MemberExpression"!=e.parent.type||e.parent.computed||(r("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`$${s}$GET_PROTOTYPE_OF`)),T=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`$${s}$SET_PROTOTYPE_OF`)),O=!0));const x=y.node.body[y.node.body.length-1];let S;if(r(x,"program is empty"),"ExportNamedDeclaration"==x.type){y.node.body.pop();for(const e of x.specifiers){r("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?S=e.local.name:f.set(e.local.name,t)}}const v=t.blockStatement([]);let D;for(const e of y.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=S||!i.init||"FunctionExpression"!=i.init.type&&"ArrowFunctionExpression"!=i.init.type||i.init.async||i.init.generator){for(const r in t.getBindingIdentifiers(i.id))r==S&&(D=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(S),[]))]))),"const"!=e.kind&&f.has(r)&&(b.set(r,f.get(r)),f.delete(r)),v.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&v.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else D=t.functionDeclaration(t.identifier(d),i.init.params,"BlockStatement"==i.init.body.type?i.init.body:t.blockStatement([t.returnStatement(i.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==S?D=e:v.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):v.body.push(e);if(D||(D=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),y.node.body=[D],v.body.length){(f.size||b.size)&&D.body.body.push(t.returnStatement(t.objectExpression([...[...f].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...b].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),y.scope.crawl();const e=new Set;let n=0;for(const[i,o]of[...v.body.entries()].reverse())if("VariableDeclaration"==o.type){r(1==o.declarations.length);const a=o.declarations[0];if(r("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),y.scope.crawl(),y.scope.hasGlobal(a.id.name)){v.body.splice(i,1);const[p]=y.unshiftContainer("body",v),[l]=y.unshiftContainer("body",o);if(y.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys(y.scope.globals).some((t=>e.has(t)))){const e=y.scope.getBinding(a.id.name);r(e);for(const i of e.referencePaths)r("Identifier"==i.node.type),i.replaceWith(t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(i.node.name)));for(const i of e.constantViolations)if("AssignmentExpression"==i.node.type)for(const[e,r]of Object.entries(t.getBindingIdentifiers(i.node)))e==a.id.name&&(clearObject(r),Object.assign(r,t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(e))));p.remove(),l.remove(),a.init&&v.body.splice(i,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(a.id.name)),a.init)))}else p.remove(),l.remove(),D.body.body.unshift(o),n++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&(y.scope.crawl(),y.scope.hasGlobal(o.id.name))){v.body.splice(i,1);const[e]=y.unshiftContainer("body",v),[n]=y.unshiftContainer("body",o);y.scope.crawl();const a=y.scope.getBinding(o.id.name);r(a);for(const e of a.referencePaths)r("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(e.node.name)));e.remove(),n.remove(),v.body.splice(i,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(o.id.name)),t.classExpression(void 0,o.superClass,o.body,o.decorators))))}if(y.scope.hasGlobal("_EXPORTS"))for(const e of i("_EXPORTS",y))e.replaceWith(t.arrayExpression([...f.keys(),...b.keys()].map((e=>t.stringLiteral(e)))));v.body.length&&D.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${s}$FMCL`)),v))}return h&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`),createGetFunctionPrototypeNode())])),O&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$SET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${s}$DUNDER_PROTO_SETTER`)]))])),T&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$GET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${s}$DUNDER_PROTO_GETTER`)]))])),(T||O)&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(T?O?[t.objectProperty(t.identifier("get"),t.identifier(`$${s}$DUNDER_PROTO_GETTER`)),t.objectProperty(t.identifier("set"),t.identifier(`$${s}$DUNDER_PROTO_SETTER`))]:[t.objectProperty(t.identifier("get"),t.identifier(`$${s}$DUNDER_PROTO_GETTER`))]:[t.objectProperty(t.identifier("set"),t.identifier(`$${s}$DUNDER_PROTO_SETTER`))]),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getOwnPropertyDescriptor")),[t.memberExpression(t.identifier("Object"),t.identifier("prototype")),t.stringLiteral("__proto__")]))])),n(e,{BlockStatement({node:e}){for(const[i,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(i,1),e.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(r.id,t.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:i,parent:o}){r(t.isClass(o));let a=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(n(r.body,{ThisExpression(i){e=!0,a=!0,i.replaceWith(t.identifier(`_THIS_${s}_`))},Function(e){e.skip()}},i),e)if("constructor"!=r.kind)r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(n(r.body,{CallExpression(t){"Super"==t.node.callee.type&&e.push(t)}},i),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==r)e[0].parentPath.replaceWith(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_THIS_${s}_`),i.node));r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`))]))}else r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`),t.callExpression(t.super(),[]))]))}}!o.superClass&&a&&(o.superClass=t.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(t.identifier("undefined"))},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)]))}}),{file:e,seclevel:c};function createGetFunctionPrototypeNode(){for(const e of o)if(!y.scope.hasOwnBinding(e))return t.memberExpression(t.memberExpression(t.identifier(e),t.identifier("constructor")),t.identifier("prototype"));return t.memberExpression(t.memberExpression(t.arrowFunctionExpression([t.identifier("_")],t.identifier("_")),t.identifier("constructor")),t.identifier("prototype"))}}export{transform as default,transform};
package/pull.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @param sourceFolderPath path to folder containing source files
5
5
  * @param hackmudPath path to hackmud directory
6
- * @param script script to pull in `user.name` format
6
+ * @param script to pull in `user.name` format
7
7
  */
8
8
  export declare function pull(sourceFolderPath: string, hackmudPath: string, script: string): Promise<void>;
9
9
  export default pull;
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{dirname as t,resolve as r}from"path";import i from"fs";const{mkdir:s,copyFile:o}=i.promises;async function pull(i,e,a){const[c,n]=a.split(".");if(!c||!n)throw new Error('`script` argument must be in "user.name" format');await function copyFilePersistent(r,i,e){return o(r,i,e).catch((async a=>{if("ENOENT"!=a.code)throw a;await s(t(i),{recursive:!0}),await o(r,i,e)}))}(r(e,c,"scripts",`${n}.js`),r(i,c,`${n}.js`))}export{pull as default,pull};
package/push.d.ts CHANGED
@@ -1,26 +1,28 @@
1
1
  import { Info } from ".";
2
- interface PushOptions {
2
+ declare type PushOptions = {
3
+ /** whether to do the minify step (defaults to `true`) */
4
+ minify: boolean;
5
+ /** whether to mangle function and class names (defaults to `false`) */
6
+ mangleNames: boolean;
3
7
  /**
4
8
  * array of scripts in the format `foo.bar`
5
9
  *
6
- * also accepts wild card e.g. `*.bar` or `foo.*`
10
+ * also accepts wild card (`*`) e.g. `*.bar` or `foo.*`
7
11
  *
8
- * pushes everything by default
12
+ * pushes everything by default (`*.*`)
9
13
  */
10
14
  scripts: string | string[];
11
- /** callback when a script is pushed */
15
+ /** callback called on script push */
12
16
  onPush: (info: Info) => void;
13
- /** whether to do the minify step (defaults to `true`) */
14
- minify: boolean;
15
- }
17
+ };
16
18
  /**
17
19
  * Push scripts from a source directory to the hackmud directory.
18
20
  *
19
- * Files directly in the source folder are pushed to all users
21
+ * Pushes files directly in the source folder to all users
20
22
  * @param sourceDirectory directory containing source code
21
23
  * @param hackmudDirectory directory created by hackmud containing user data including scripts
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"chokidar";import"./generateTypings.js";import"./pull.js";import"./syncMacros.js";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/generator";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";import"perf_hooks";
1
+ import e from"fs";import{dirname as i,resolve as r,extname as t,basename as s}from"path";import{s as a,processScript as o}from"./processScript/index.js";import{c as p}from"./processScript/minify.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"@babel/traverse";import"@babel/types";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"./assert-1556d989.js";import"./spliceString-2c6f214f.js";import"./processScript/preprocess.js";import"./processScript/transform.js";import"./processScript/shared.js";import"acorn";import"terser";class DynamicMap extends Map{constructor(e){super(),this.fallbackHandler=e}get(e){if(super.has(e))return super.get(e);const i=this.fallbackHandler(e);return super.set(e,i),i}}const{writeFile:n,mkdir:l}=e.promises;function writeFilePersistent(e,r,t){return n(e,r,t).catch((async s=>{if("ENOENT"!=s.code)throw s;await l(i(e),{recursive:!0}),await n(e,r,t)}))}const{readFile:c,readdir:m}=e.promises;async function push(e,i,{scripts:n="*.*",onPush:l=(()=>{}),minify:g=!0,mangleNames:u=!1}={}){"string"==typeof n&&(n=[n]);const f=new DynamicMap((e=>new Set)),b=new Set,h=new Set;let w=!1;for(const e of n){const[i,r]=e.split(".");i&&"*"!=i?r&&"*"!=r?f.get(i).add(r):b.add(i):r&&"*"!=r?h.add(r):w=!0}const d=new DynamicMap((e=>new Set)),y=[],$=new DynamicMap((e=>new Set));let P;if(h.size||w){const s=await m(r(i),{withFileTypes:!0}),a=new Set([...(P=await m(r(e),{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name)),...s.filter((e=>e.isDirectory())).map((e=>e.name)),...s.filter((e=>e.isFile()&&".key"==t(e.name))).map((e=>e.name.slice(0,-4))),...f.keys(),...b]);if(w)for(const e of a)b.add(e);else for(const e of a){const i=f.get(e);for(const e of h)i.add(e)}}return await Promise.all([...b].map((async n=>{await m(r(e,n),{withFileTypes:!0}).then((async m=>{await Promise.all(m.map((async m=>{const f=t(m.name);if(m.isFile()&&a.includes(f)){const t=s(m.name,f),a=r(e,n,m.name),{srcLength:b,script:h}=await o(await c(a,{encoding:"utf-8"}),{minify:g,scriptUser:n,scriptName:t,filePath:a,mangleNames:u}),w={file:`${n}/${m.name}`,users:[n],minLength:p(h),error:void 0,srcLength:b};$.get(n).add(t),y.push(w),await writeFilePersistent(r(i,n,`scripts/${t}.js`),h),l(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...f].map((async([t,s])=>{b.has(t)||await Promise.all([...s].map((async s=>{let n,m,f;for(const i of a)try{m=`${s}${i}`,n=await c(f=r(e,t,m),{encoding:"utf-8"});break}catch{}if(n){const{srcLength:e,script:a}=await o(n,{minify:g,scriptUser:t,scriptName:s,filePath:f,mangleNames:u}),c={file:`${t}/${m}`,users:[t],minLength:p(a),error:void 0,srcLength:e};y.push(c),await writeFilePersistent(r(i,t,"scripts",`${s}.js`),a),l(c)}else d.get(s).add(t)})))}))),await(b.size?Promise.all((P||await m(r(e),{withFileTypes:!0})).map((async n=>{const m=t(n.name);if(!n.isFile()||!a.includes(m))return;const f=s(n.name,m),h=[...b,...d.get(f)].filter((e=>!$.get(e).has(f)));if(!h.length)return;const w=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),P=r(e,n.name),{srcLength:S,script:j}=await o(await c(P,{encoding:"utf-8"}),{minify:g,scriptUser:!0,scriptName:f,uniqueID:w,filePath:P,mangleNames:u}),F={file:n.name,users:h,minLength:p(j),error:void 0,srcLength:S};await Promise.all(h.map((e=>writeFilePersistent(r(i,e,`scripts/${f}.js`),j.replace(new RegExp(`$${w}$SCRIPT_USER`,"g"),e).replace(new RegExp(`$${w}$FULL_SCRIPT_NAME`,"g"),`${e}.${f}`))))),y.push(F),l(F)}))):Promise.all([...d].map((async([t,s])=>{let n,m,f;for(const i of a)try{m=`${t}${i}`,n=await c(f=r(e,m),{encoding:"utf-8"});break}catch{}if(n){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:a,script:c}=await o(n,{minify:g,scriptUser:!0,scriptName:t,uniqueID:e,filePath:f,mangleNames:u}),b={file:m,users:[...s],minLength:p(c),error:void 0,srcLength:a};await Promise.all([...s].map((s=>writeFilePersistent(r(i,s,`scripts/${t}.js`),c.replace(new RegExp(`$${e}$SCRIPT_USER`,"g"),s).replace(new RegExp(`$${e}$FULL_SCRIPT_NAME`,"g"),`${s}.${t}`))))),y.push(b),l(b)}})))),y}export{DynamicMap as D,push as default,push,writeFilePersistent as w};
@@ -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 a,basename as s,resolve as t}from"path";const{readFile:o,readdir:n,stat:r,writeFile:c}=e.promises;async function syncMacros(e){const i=await n(e,{withFileTypes:!0}),m=new Map,l=[];await Promise.all(i.map((async n=>{if(n.isFile())switch(a(n.name)){case".macros":{const[a,s]=await Promise.all([o(t(e,n.name),{encoding:"utf-8"}).then((e=>e.split("\n"))),r(t(e,n.name)).then((({mtime:e})=>e))]);for(let e=0;e<a.length/2-1;e++){const t=a[2*e],o=m.get(t);(!o||s>o.date)&&m.set(t,{date:s,macro:a[2*e+1]})}}break;case".key":l.push(s(n.name,".key"))}})));let f="",p=0;for(const[e,{macro:a}]of[...m].sort((([e],[a])=>(e>a)-(e<a))))a[0]==a[0].toLowerCase()&&(f+=`${e}\n${a}\n`,p++);for(const a of l)c(t(e,`${a}.macros`),f);return{macrosSynced:p,usersSynced:l.length}}export{syncMacros as default,syncMacros};
package/watch.d.ts CHANGED
@@ -2,13 +2,13 @@ import { Info } from ".";
2
2
  /**
3
3
  * Watches target file or folder for updates and builds and pushes updated file.
4
4
  *
5
- * @param srcDir path to folder containing source files
6
- * @param hackmudDir path to hackmud directory
7
- * @param users users to push to (pushes to all if empty)
8
- * @param scripts scripts to push from (pushes from all if empty)
9
- * @param onPush function that's called after each script has been built and written
5
+ * @param sourceDirectory path to folder containing source files
6
+ * @param hackmudDirectory path to hackmud directory
7
+ * @param users to push to (pushes to all if empty)
8
+ * @param scripts to push from (pushes from all if empty)
9
+ * @param onPush function that's called on each script push
10
10
  */
11
- export declare function watch(srcDir: string, hackmudDir: string, users: string[], scripts: string[], onPush?: (info: Info) => void, { genTypes }?: {
11
+ export declare function watch(sourceDirectory: string, hackmudDirectory: string, users: string[], scripts: string[], onPush?: (info: Info) => void, { genTypes }?: {
12
12
  genTypes?: string | undefined;
13
13
  }): void;
14
14
  export default watch;
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"./generateTypings.js";import"./processScript/index.js";import"./pull.js";import"./syncMacros.js";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/generator";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";import"perf_hooks";
1
+ import{watch as o}from"chokidar";import p from"fs";import{extname as r,basename as i,resolve as t}from"path";import{s as e,processScript as s}from"./processScript/index.js";import{generateTypings as n}from"./generateTypings.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"@babel/traverse";import"@babel/types";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/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./assert-1556d989.js";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";const{readFile:a,readdir:l}=p.promises;function watch(p,c,m,b,g,{genTypes:u}={}){const h=o("",{depth:1,cwd:p,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async o=>{const n=r(o);if(e.includes(n)){const c=i(o,n);if(o==i(o)){if(!b.length||b.includes(c)){const n=await a(t(p,o),{encoding:"utf-8"}),c=new Map;let m;await Promise.all((await l(p,{withFileTypes:!0})).map((async o=>{o.isDirectory()&&await l(t(p,o.name),{withFileTypes:!0}).then((p=>{for(const t of p){if(!t.isFile())continue;const p=r(t.name);if(!e.includes(p))continue;const s=i(t.name,p),n=c.get(s);n?n.push(o.name):c.set(s,[o.name])}}))})));const{srcLength:b}=await s(n).catch((o=>(m=o,{script:"",srcLength:0}))),u={file:o,users:[],minLength:0,error:m,srcLength:b};g&&g(u)}}else{const r=i(t(o,".."));if((!m.length||m.includes(r))&&(!b.length||b.includes(c))){const i=await a(t(p,o),{encoding:"utf-8"});let e;const{srcLength:n}=await s(i).catch((o=>(e=o,{script:"",srcLength:0}))),l={file:o,users:[r],minLength:0,error:e,srcLength:n};null==g||g(l)}}}}));u&&(n(p,t(p,u),c),h.on("add",(()=>n(p,t(p,u),c))),h.on("unlink",(()=>n(p,t(p,u),c))))}export{watch as default,watch};
package/index.cjs DELETED
@@ -1,3 +0,0 @@
1
- module.exports = null
2
- import("./index.js").then(esModule => module.exports = esModule)
3
- require("deasync").loopWhile(() => !module.exports)
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};
package/modules.d.js DELETED
@@ -1 +0,0 @@
1
-
@@ -1,3 +0,0 @@
1
- import t from "@babel/types";
2
- export declare function compile(code: string, randomString?: string): 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 d from"@babel/plugin-proposal-numeric-separator";import c 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 x from"@babel/plugin-transform-exponentiation-operator";import E from"@babel/plugin-transform-typescript";import v,{NodePath as D,Hub as _}from"@babel/traverse";import S from"@babel/types";import{assert as I,ensure as T}from"../lib.js";import"fs";import"path";const{default:k}=v;async function $(v,T="0"){const $=(await e(v,{plugins:[[E.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],[d.default],[p.default],[b.default],[f.default],[l.default],[c.default],[x.default]],code:!1,ast:!0,configFile:!1})).ast,w=`_SCRIPT_${T}_`,B=new Map,F=new Map,G=D.get({container:$,hub:new _,key:"program",parent:$,parentPath:null});if(G.scope.hasGlobal("_START"))for(const e of C("_START",G))e.replaceWith(S.identifier("_ST"));if(G.scope.hasGlobal("_TIMEOUT"))for(const e of C("_START",G))e.replaceWith(S.identifier("_TO"));const W=S.blockStatement([]);let j;const P=[];for(const e of G.node.body)if("ExportDefaultDeclaration"==e.type)"FunctionDeclaration"==e.declaration.type||"FunctionExpression"==e.declaration.type||"ArrowFunctionExpression"==e.declaration.type?j=S.functionDeclaration(S.identifier(w),e.declaration.params,"BlockStatement"==e.declaration.body.type?e.declaration.body:S.blockStatement([S.returnStatement(e.declaration.body)])):(I(S.isExpression(e.declaration)),j=S.functionDeclaration(S.identifier(w),[S.identifier("context"),S.identifier("args")],S.blockStatement([S.returnStatement(S.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):F.set(i.id.name,i.id.name),W.body.push(S.variableDeclaration("let",[S.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),W.body.push(e.declaration)}else if(e.specifiers)for(const i of e.specifiers)I("ExportSpecifier"==i.type,`${i.type} is currently unsupported`),P.includes(i.local.name)?F.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)?(F.set(i.id.name,B.get(i.id.name)),B.delete(i.id.name)):P.push(i.id.name)),W.body.push(S.variableDeclaration("let",[S.variableDeclarator(i.id,i.init)]));else"FunctionDeclaration"==e.type?W.body.push(S.variableDeclaration("let",[S.variableDeclarator(e.id,S.functionExpression(null,e.params,e.body,e.generator,e.async))])):W.body.push(e);if(j||(j=S.functionDeclaration(S.identifier(w),[S.identifier("context"),S.identifier("args")],S.blockStatement([]))),G.node.body=[j],W.body.length){G.scope.crawl();for(const[e,i]of W.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"),G.scope.crawl(),G.scope.hasGlobal(t.id.name)){W.body.splice(e,1);const[r]=G.unshiftContainer("body",W),[o]=G.unshiftContainer("body",i);G.scope.crawl();const a=G.scope.getBinding(t.id.name);I(a);for(const e of a.referencePaths)I("Identifier"==e.node.type),e.replaceWith(S.memberExpression(S.identifier("$G"),S.identifier(e.node.name)));r.remove(),o.remove(),t.init&&W.body.splice(e,0,S.expressionStatement(S.assignmentExpression("=",S.memberExpression(S.identifier("$G"),S.identifier(t.id.name)),t.init)))}}else if("ClassDeclaration"==i.type&&(G.scope.crawl(),G.scope.hasGlobal(i.id.name))){W.body.splice(e,1);const[t]=G.unshiftContainer("body",W),[r]=G.unshiftContainer("body",i);G.scope.crawl();const o=G.scope.getBinding(i.id.name);I(o);for(const e of o.referencePaths)I("Identifier"==e.node.type),e.replaceWith(S.memberExpression(S.identifier("$G"),S.identifier(e.node.name)));t.remove(),r.remove(),W.body.splice(e,0,S.expressionStatement(S.assignmentExpression("=",S.memberExpression(S.identifier("$G"),S.identifier(i.id.name)),S.classExpression(null,i.superClass,i.body,i.decorators))))}(B.size||F.size)&&(W.body.push(S.expressionStatement(S.assignmentExpression("=",S.memberExpression(S.identifier("$G"),S.identifier("_")),S.callExpression(S.memberExpression(S.identifier("Object"),S.identifier("freeze")),[S.objectExpression([...[...B].map((([e,i])=>S.objectProperty(S.identifier(i),S.identifier(e)))),...[...F].map((([e,i])=>S.objectMethod("get",S.identifier(i),[],S.blockStatement([S.returnStatement(S.identifier(e))]))))])])))),j.body.body.push(S.returnStatement(S.memberExpression(S.identifier("$G"),S.identifier("_"))))),j.body.body.unshift(S.ifStatement(S.unaryExpression("!",S.identifier("$FMCL")),W))}return k($,{BlockStatement({node:e}){for(const[i,t]of e.body.entries())"FunctionDeclaration"!=t.type||t.generator||(e.body.splice(i,1),e.body.unshift(S.variableDeclaration("let",[S.variableDeclarator(t.id,S.arrowFunctionExpression(t.params,t.body,t.async))])))},ClassBody({node:e,scope:i,parent:t}){I(S.isClass(t));let r=!1;for(const t of e.body){if("ClassMethod"!=t.type)continue;let e=!1;if(k(t.body,{ThisExpression(i){e=!0,r=!0,i.replaceWith(S.identifier(`_THIS_${T}_`))},Function(e){e.skip()}},i),e)if("constructor"!=t.kind)t.body.body.unshift(S.variableDeclaration("let",[S.variableDeclarator(S.identifier(`_THIS_${T}_`),S.callExpression(S.memberExpression(S.super(),S.identifier("valueOf")),[]))]));else{const e=[];if(k(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(S.variableDeclaration("let",[S.variableDeclarator(S.identifier(`_THIS_${T}_`),e[0].node)]));else{for(const i of e)i.replaceWith(S.assignmentExpression("=",S.identifier(`_THIS_${T}_`),i.node));t.body.body.unshift(S.variableDeclaration("let",[S.variableDeclarator(S.identifier(`_THIS_${T}_`))]))}else t.body.body.unshift(S.variableDeclaration("let",[S.variableDeclarator(S.identifier(`_THIS_${T}_`),S.callExpression(S.super(),[]))]))}}!t.superClass&&r&&(t.superClass=S.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(S.identifier(`_UNDEFINED_${T}_`))},BigIntLiteral(e){const i=Number(e.node.value);BigInt(i)==BigInt(e.node.value)?e.replaceWith(S.callExpression(S.identifier("BigInt"),[S.numericLiteral(i)])):e.replaceWith(S.callExpression(S.identifier("BigInt"),[S.stringLiteral(e.node.value)]))}}),$}function C(e,i){const[t]=i.unshiftContainer("body",S.variableDeclaration("let",[S.variableDeclarator(S.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};
package/test.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export declare function test(srcPath: string): Promise<{
2
- file: string;
3
- message: string;
4
- line: number;
5
- }[]>;
6
- export default test;
package/test.js DELETED
@@ -1 +0,0 @@
1
- import"fs";import"path";export{test as default,test}from"./index.js";import"./processScript/index.js";import"chokidar";import"./lib.js";import"./generateTypings.js";import"./pull.js";import"./syncMacros.js";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/generator";import"@babel/parser";import"acorn";import"terser";import"./processScript/postProcess.js";import"./processScript/preProcess.js";import"perf_hooks";