hackmud-script-manager 0.15.0-3c27edd → 0.15.0-fcf8be4
Sign up to get free protection for your applications and to get access to all the features.
- package/bin/hsm.js +1 -1
- package/package.json +1 -1
- package/processScript/minify.js +1 -1
- package/processScript/postprocess.js +1 -1
- package/processScript/preprocess.js +1 -1
- package/processScript/transform.js +1 -1
- package/push.js +1 -1
- package/watch.js +1 -1
package/bin/hsm.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import e from"chalk";import{watch as o}from"chokidar";import s from"fs";import{homedir as n}from"os";import{resolve as t,basename as a,extname as i,dirname as c,relative as l}from"path";import{s as r}from"../constants-9bb78688.js";import{D as g,w as f}from"../writeFilePersistent-72dc81a3.js";import{generateTypings as h}from"../generateTypings.js";import{syncMacros as m}from"../syncMacros.js";import{pull as p}from"../pull.js";import{c as
|
2
|
+
import e from"chalk";import{watch as o}from"chokidar";import s from"fs";import{homedir as n}from"os";import{resolve as t,basename as a,extname as i,dirname as c,relative as l}from"path";import{s as r}from"../constants-9bb78688.js";import{D as g,w as f}from"../writeFilePersistent-72dc81a3.js";import{generateTypings as h}from"../generateTypings.js";import{syncMacros as m}from"../syncMacros.js";import{pull as p}from"../pull.js";import{c as u}from"../countHackmudCharacters-1e122984.js";const{readFile:d,rmdir:k,writeFile:b,mkdir:w}=s.promises,y=t(n(),".config"),$=t(y,"hsm.json"),j=new Map,v=[];let P;const C=e.rgb(255,244,4),N=e.rgb(243,249,152),S=e.rgb(179,255,155),x=e.rgb(255,150,224),F=e.rgb(30,255,0),O=e.rgb(202,202,202),U=new g((e=>{let o=0;for(const s of e)o+=(o>>1)+o+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[C,N,S,x,F,O][o%6](e)}));for(const e of process.argv.slice(2))if("-"==e[0]){const[o,s]=e.split("=");let n=s;if(n)if("true"==n)n=!0;else if("false"==n)n=!1;else{const e=Number(n);isFinite(e)&&(n=e)}else n=!0;if("-"==e[1])j.set(o.slice(2),n);else for(const e of o.slice(1))j.set(e,n)}else v.push(e);function help(){switch(v[0]){case"config":switch(v[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>"] [--skip-minify] [--mangle-names]');break;case"dev":case"watch":console.log(`hsm ${v[0]} <dir> [..."<script user>.<script name>"] [--skip-minify] [--mangle-names]`);break;case"pull":console.log("hsm pull <script user>.<script name>");break;case"minify":case"golf":console.log(`${a(process.argv[1])} ${v[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.15.0-fcf8be4")}async function getConfig(){return P||(P=await d($,{encoding:"utf-8"}).then((e=>{let o;try{o=JSON.parse(e)}catch{return console.log("config file was corrupted, resetting"),{}}return o&&"object"==typeof o?o:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${$}`),{}))))}function exploreObject(e,o,s=!1){for(const t of o){var n;e=s?"object"==typeof e[t]?e[t]:e[t]={}:null===(n=e)||void 0===n?void 0:n[t]}return e}function updateConfig(){if(P){const e=JSON.stringify(P,void 0,"\t");b($,e).catch((async o=>{switch(o.code){case"EISDIR":await k($);break;case"ENOENT":await w(y);break;default:throw o}b($,e)}))}}function onPushLogger({file:o,users:s,minLength:n,error:c}){c?console.log(`error "${e.bold(c.message)}" in ${e.bold(o)}`):console.log(`pushed ${e.bold(o)} to ${s.map((o=>e.bold(U.get(o)))).join(", ")} | ${e.bold(String(n))} chars | ${e.bold(`${t(P.hackmudPath,s[0],"scripts",a(o,i(o)))}.js`)}`)}(async()=>{if(j.get("version")||j.get("v"))version();else if(j.get("help")||j.get("h"))help();else{switch(v[0]){case"push":{const{push:e}=await import("../push.js"),o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const s=v[1];if(!s){console.error("specify the directory to watch"),help();break}const n=o.hackmudPath,t=v.slice(2);t.length||t.push("*.*"),j.has("skip-minify")&&j.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names");(await e(s,n,{scripts:t,onPush:onPushLogger,minify:!j.get("skip-minify"),mangleNames:Boolean(j.get("mangle-names"))})).length||console.warn("couldn't find any scripts to push"),updateConfig()}break;case"dev":case"watch":{var s;const{watch:e}=await import("../watch.js");if(!v[1]){console.error("specify the directory to watch"),help();break}const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const n=v.slice(2);n.length||n.push("*.*"),j.has("skip-minify")&&j.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names"),e(v[1],o.hackmudPath,{scripts:n,onPush:onPushLogger,typeDeclarationPath:null===(s=j.get("type-declaration-path"))||void 0===s?void 0:s.toString(),minify:!j.get("skip-minify"),mangleNames:Boolean(j.get("mangle-names")),onReady:()=>console.log("watching")})}break;case"pull":{const e=await getConfig();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const o=v[1];if(!o){help();break}const s=v[2]||".",n=e.hackmudPath;try{await p(s,n,o)}catch{console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:e}=await getConfig();if(!e){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:o,usersSynced:s}=await m(e);console.log(`synced ${o} macros to ${s} users`)}break;case"gen-types":{const e=t(v[1]||".");h(e,v[2]?t(v[2]):t(e,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(v[1]){case"get":v[2]?console.log(exploreObject(await getConfig(),v[2].split("."))):console.log(await getConfig());break;case"delete":if(v[2]){var n;const e=v[2].split("."),o=e.pop();if(!e.length){help();break}const s=await getConfig();null===(n=exploreObject(s,e))||void 0===n||delete n[o],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(v[2]&&v[3]){const e=v[2].split(".");if(!e.length){help();break}const o=e.pop(),s=await getConfig();if(e.length||"hackmudPath"!=o){let n=s;for(const o of e)"object"==typeof n[o]||(n[o]={}),n=n[o];n[o]=v[3]}else s.hackmudPath=t(v[3]);console.log(s)}else console.log("Usage:\nhsm config set <key> <value>");break;default:v[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{const s=v[1];if(!s){console.log(`Target required\nUsage: ${a(process.argv[1])} ${v[0]} <target> [output]`);break}const n=i(s);if(!r.includes(n)){console.log(`Unsupported file extension "${e.bold(n)}"\nSupported extensions are "${r.map((o=>e.bold(o))).join('", "')}"`);break}j.get("watch")?o(s,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>console.log(`watching ${s}`))).on("change",(()=>golfFile(s,n))):await golfFile(s,n)}break;default:v[0]&&console.log("unknown command"),help()}updateConfig()}async function golfFile(o,s){const{processScript:n}=await import("../processScript/index.js");await d(o,{encoding:"utf-8"}).then((async i=>{const r=a(o,s),g=r.endsWith(".src"),h=g?r.slice(0,-4):r;let m="UNKNOWN";"scripts"==a(t(o,".."))&&"hackmud"==a(t(o,"../../.."))&&(m=a(t(o,"../..")));const p=!j.get("skip-minify"),d=Boolean(j.get("mangle-names"));!p&&d&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const k=performance.now(),{script:b,warnings:w}=await n(i,{minify:p,scriptUser:m,scriptName:h,filePath:o,mangleNames:d}),y=performance.now()-k;for(const{message:o,line:s}of w)console.log(`warning "${e.bold(o)}" on line ${e.bold(String(s))}`);let $;$=v[2]?v[2]:t(c(o),g?`${h}.js`:".js"==s?`${r}.min.js`:`${r}.js`);const P=u(b);await f($,b).catch((async e=>{if(!v[2]||"EISDIR"!=e.code)throw e;$=t($,`${a(o,s)}.js`),await f($,b)})).then((()=>console.log(`wrote ${e.bold(P)} chars to ${e.bold(l(".",$))} | took ${Math.round(100*y)/100}ms`)),(e=>console.log(e.message)))}),(e=>console.log(e.message)))}})();
|
package/package.json
CHANGED
package/processScript/minify.js
CHANGED
@@ -1 +1 @@
|
|
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 o,includesIllegalString as s,replaceUnsafeStrings as p}from"./shared.js";import{a as l}from"../assert-1556d989.js";import{s as u}from"../spliceString-2c6f214f.js";import{c}from"../countHackmudCharacters-1e122984.js";const{default:d}=e,{default:f}=t;async function minify(e,t,{uniqueID:i="00000000000",mangleNames:n=!1}={}){let m;l(/^\w{11}$/.exec(i)),f(e,{Program(e){m=e,e.skip()}});const y=m.get("body.0");for(const e of[...y.node.params].reverse()){if("Identifier"==e.type){if(!y.scope.getBinding(e.name).referenced){y.node.params.pop();continue}}break}for(const e in m.scope.globals){if("arguments"==e||e.startsWith(`$${i}
|
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 o,includesIllegalString as s,replaceUnsafeStrings as p}from"./shared.js";import{a as l}from"../assert-1556d989.js";import{s as u}from"../spliceString-2c6f214f.js";import{c}from"../countHackmudCharacters-1e122984.js";const{default:d}=e,{default:f}=t;async function minify(e,t,{uniqueID:i="00000000000",mangleNames:n=!1}={}){let m;l(/^\w{11}$/.exec(i)),f(e,{Program(e){m=e,e.skip()}});const y=m.get("body.0");for(const e of[...y.node.params].reverse()){if("Identifier"==e.type){if(!y.scope.getBinding(e.name).referenced){y.node.params.pop();continue}}break}for(const e in m.scope.globals){if("arguments"==e||e.startsWith(`$${i}$`))continue;const t=o(e,m);if(!(5+e.length+t.length>=e.length*t.length)){for(const n of t)n.replaceWith(r.identifier(`_${i}_GLOBAL_${e}_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_GLOBAL_${e}_`),r.identifier(e))]))}}const _=o(`$${i}$GLOBAL$`,m);if(_.length>3){for(const e of _)e.replaceWith(r.identifier(`_${i}_G_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_G_`),r.identifier(`$${i}$GLOBAL$`))]))}const $=[];let E=!1;const g=r.cloneNode(e);f(g,{MemberExpression({node:e}){e.computed||(l("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=r.identifier(`_${i}_PROTOTYPE_PROPERTY_`)):"__proto__"==e.property.name?(e.computed=!0,e.property=r.identifier(`_${i}_PROTO_PROPERTY_`)):s(e.property.name)&&(e.computed=!0,e.property=r.stringLiteral(p(i,e.property.name))))},ObjectProperty({node:e}){"Identifier"==e.key.type&&s(e.key.name)&&(e.key=r.stringLiteral(p(i,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=p(i,e.value)},TemplateLiteral({node:e}){for(const t of e.quasis)t.value.cooked?(t.value.cooked=p(i,t.value.cooked),t.value.raw=t.value.cooked.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"$\\{")):t.value.raw=p(i,t.value.raw)},RegExpLiteral(e){e.node.pattern=p(i,e.node.pattern),delete e.node.extra}});const b=(await a.minify(d(g).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(`_${i}_PROTOTYPE_PROPERTY_`,"g"),'"prototype"').replace(new RegExp(`_${i}_PROTO_PROPERTY_`,"g"),'"__proto__"');let v,h,x=!1;{const t=[];f(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(`_${i}_JSON_VALUE_${$.push(t)-1}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${$.push(t)-1}_`))}}),e.traverse({TemplateLiteral(e){if("TaggedTemplateExpression"==e.parent.type)return;const t=e.node;let i=r.stringLiteral(t.quasis[0].value.cooked);for(let e=0;e<t.expressions.length;e++){const n=t.expressions[e],a=t.quasis[e+1];i=r.binaryExpression("+",i,n),a.value.cooked&&(i=r.binaryExpression("+",i,r.stringLiteral(a.value.cooked)))}e.replaceWith(i)},MemberExpression({node:e}){e.computed||(l("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(`_${i}_UNDEFINED_`)),E=!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=$.indexOf(n);-1==t&&(t+=$.push(n)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))})()),e.skip()}},NullLiteral(e){let t=$.indexOf(null);-1==t&&(t+=$.push(null)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))},BooleanLiteral(e){let t=$.indexOf(e.node.value);-1==t&&(t+=$.push(e.node.value)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))},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=$.indexOf(e.node.value);-1==t&&(t+=$.push(e.node.value)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))})())},StringLiteral(e){if(e.node.value=p(i,e.node.value),JSON.stringify(e.node.value).includes("\\u00")||e.toString().length<4)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=$.indexOf(e.node.value);-1==t&&(t+=$.push(e.node.value)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=$.indexOf(e.key.name);-1==t&&(t+=$.push(e.key.name)),e.computed=!0,e.key=r.identifier(`_${i}_JSON_VALUE_${t}_`)},RegExpLiteral(e){e.node.pattern=p(i,e.node.pattern),delete e.node.extra}}),e.skip()}}),await Promise.all(t);const n=e.program.body[0];if(l("FunctionDeclaration"==n.type),$.length)if(x=!0,1==$.length)if("string"!=typeof $[0]||$[0].includes("\n")||$[0].includes("\t")){const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_JSON_VALUE_0_`),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)]))]);E&&e.declarations.push(r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))),n.body.body.unshift(e),v=JSON.stringify($[0])}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_JSON_VALUE_0_`),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))]);E&&e.declarations.push(r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))),n.body.body.unshift(e),v=$[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern($.map(((e,t)=>r.identifier(`_${i}_JSON_VALUE_${t}_`)))),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)]))]);E&&e.declarations.push(r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))),n.body.body.unshift(e),v=JSON.stringify($)}else E&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))]));h=d(e).code}return h=(await a.minify(h,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!n,keep_fnames:!n})).code||"",null!=v&&(h=u(h,`${t?`//${t}\n`:""}\n//\t${v}\t\n`,getFunctionBodyStart(h)+1),h=h.replace(`$${i}$SPLIT_INDEX$`,await minifyNumber(h.split("\t").findIndex((e=>e==v))))),c(b)<=c(h)+Number(x)&&(h=b,t&&(h=u(h,`//${t}\n`,getFunctionBodyStart(h)+1))),h}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(l("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{minify as default,minify};
|
@@ -1 +1 @@
|
|
1
|
-
function postprocess($,e,p){return $.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$SC_DOLLAR\\$`,"g"),"S\\C$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$DB_DOLLAR\\$`,"g"),"D\\B$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$D\\$`,"g"),"_\\_D_S").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$FMCL\\$`,"g"),"_\\_FMCL_").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$G\\$`,"g"),"_\\_G_").replace(new RegExp(`\\$${p}\\$SUBSCRIPT\\$(\\w+)\\$(\\w+)
|
1
|
+
function postprocess($,e,p){return $.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$SC_DOLLAR\\$`,"g"),"S\\C$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$DB_DOLLAR\\$`,"g"),"D\\B$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$D\\$`,"g"),"_\\_D_S").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$FMCL\\$`,"g"),"_\\_FMCL_").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$G\\$`,"g"),"_\\_G_").replace(new RegExp(`\\$${p}\\$SUBSCRIPT\\$(\\w+)\\$(\\w+)\\$`,"g"),`#${"nlmhf"[e]}s.$1.$2`).replace(new RegExp(`\\$${p}\\$DEBUG\\$`,"g"),"#D").replace(new RegExp(`\\$${p}\\$FMCL\\$`,"g"),"#FMCL").replace(new RegExp(`\\$${p}\\$GLOBAL\\$`,"g"),"#G").replace(new RegExp(`\\$${p}\\$DB\\$(\\w+)\\$`,"g"),"#db.$1").replace(new RegExp(`\\$${p}\\$SLASH_SLASH\\$`,"g"),"/\\/").replace(new RegExp(`\\$${p}\\$NOT_A_SUBSCRIPT\\$(#[\\w\\.]+)\\(\\$`,"g"),"$1\\(").replace(new RegExp(`\\$${p}\\$NOT_A_DB_CALL\\$(\\w+)\\$`,"g"),"#db.$1\\(").replace(new RegExp(`\\$${p}\\$NOT_A_DEBUG_CALL\\$`,"g"),"#D\\(").replace(new RegExp(`\\$${p}\\$NOT_FMCL\\$`,"g"),"#\\FMCL").replace(new RegExp(`\\$${p}\\$NOT_G\\$`,"g"),"#\\G")}export{postprocess as default,postprocess};
|
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{resolve as t}from"import-meta-resolve";import{a as s}from"../assert-1556d989.js";import{s as p}from"../spliceString-2c6f214f.js";const{default:l}=r,{default:n}=e;async function preprocess(e,{uniqueID:r="00000000000"}={}){s(/^\w{11}$/.test(r));const a=e;let c,f,d;do{c=e.length,e=e.replace(/^\s+/,"").replace(/^\/\/.*/,"").replace(/^\/\*[\s\S]*?\*\//,"")}while(e.length!=c);for(e=e.replace(/^function\s*\(/,"export default function (");;){let i;try{f=o(e,{plugins:["typescript",["decorators",{decoratorsBeforeExport:!0}],"doExpressions","functionBind","functionSent","partialApplication",["pipelineOperator",{proposal:"hack",topicToken:"%"}],"throwExpressions",["recordAndTuple",{syntaxType:"hash"}],"classProperties","classPrivateProperties","classPrivateMethods","logicalAssignment","numericSeparator","nullishCoalescingOperator","optionalChaining","optionalCatchBinding","objectRestSpread"],sourceType:"module"});break}catch(e){s(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 t=e.slice(i.pos);let l;if(l=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(t))e=p(e,JSON.stringify(a),i.pos,l[0].length);else if(l=/^#[0-4fhmln]?s\./.exec(t))e=p(e,"$",i.pos,1);else if(l=/^#D[^\w$]/.exec(t))e=p(e,"$",i.pos,1);else if(l=/^#FMCL/.exec(t))e=p(e,`$${r}$FMCL
|
1
|
+
import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{resolve as t}from"import-meta-resolve";import{a as s}from"../assert-1556d989.js";import{s as p}from"../spliceString-2c6f214f.js";const{default:l}=r,{default:n}=e;async function preprocess(e,{uniqueID:r="00000000000"}={}){s(/^\w{11}$/.test(r));const a=e;let c,f,d;do{c=e.length,e=e.replace(/^\s+/,"").replace(/^\/\/.*/,"").replace(/^\/\*[\s\S]*?\*\//,"")}while(e.length!=c);for(e=e.replace(/^function\s*\(/,"export default function (");;){let i;try{f=o(e,{plugins:["typescript",["decorators",{decoratorsBeforeExport:!0}],"doExpressions","functionBind","functionSent","partialApplication",["pipelineOperator",{proposal:"hack",topicToken:"%"}],"throwExpressions",["recordAndTuple",{syntaxType:"hash"}],"classProperties","classPrivateProperties","classPrivateMethods","logicalAssignment","numericSeparator","nullishCoalescingOperator","optionalChaining","optionalCatchBinding","objectRestSpread"],sourceType:"module"});break}catch(e){s(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 t=e.slice(i.pos);let l;if(l=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(t))e=p(e,JSON.stringify(a),i.pos,l[0].length);else if(l=/^#[0-4fhmln]?s\./.exec(t))e=p(e,"$",i.pos,1);else if(l=/^#D[^\w$]/.exec(t))e=p(e,"$",i.pos,1);else if(l=/^#FMCL/.exec(t))e=p(e,`$${r}$FMCL$`,i.pos,l[0].length);else if(l=/^#G/.exec(t))e=p(e,`$${r}$GLOBAL$`,i.pos,l[0].length);else{if(!(l=/^#db\./.exec(t)))throw i;e=p(e,"$",i.pos,1)}}l(f,{Program(e){d=e,e.skip()}});const u=d.scope.hasGlobal("Record"),h=d.scope.hasGlobal("Tuple");return(u||h)&&f.program.body.unshift(i.importDeclaration(u?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"))),d.scope.hasGlobal("Proxy")&&f.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral((await t("proxy-polyfill/src/proxy.js",import.meta.url)).slice(7)))),1==d.node.body.length&&"FunctionDeclaration"==d.node.body[0].type?{code:`export default ${n(f).code}`}:{code:n(f).code}}export{preprocess as default,preprocess};
|
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/traverse";import t from"@babel/types";import{v as i}from"../constants-9bb78688.js";import{getReferencePathsToGlobal as r}from"./shared.js";import{a as n}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:o}=e,a=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,s,{uniqueID:p="00000000000",scriptUser:c="UNKNOWN",scriptName:l="UNKNOWN",seclevel:d=4}={}){const f=`_SCRIPT_${p}_`,b=new Map,y=new Map;let $;if(o(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_START"))for(const e of r("_START",$))e.replaceWith(t.identifier("_ST"));if($.scope.hasGlobal("_TIMEOUT"))for(const e of r("_START",$))e.replaceWith(t.identifier("_TO"));if($.scope.hasGlobal("_SOURCE"))for(const e of r("_SOURCE",$))e.replaceWith(t.stringLiteral(s));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of r("_BUILD_DATE",$))e.replaceWith(t.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of r("_SCRIPT_USER",$))1==c?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_USER`)):e.replaceWith(t.stringLiteral(c));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of r("_SCRIPT_NAME",$))1==l?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(l));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of r("_FULL_SCRIPT_NAME",$))1==c||1==l?e.replaceWith(t.stringLiteral(`$${p}$FULL_SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(`${c}.${l}`));let m=!1;if($.scope.hasGlobal("Function")){const e=r("Function",$);if(1==e.length){const t=e[0];n("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("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)n("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),m=!0,i.parentPath.replaceWith(t.identifier(`$${p}$FUNCTION_DOT_PROTOTYPE`));m=!0}}let h=4;for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(h=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(h=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(h=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(h=0,processFakeSubscriptObject(e));if(d=Math.min(d,h),$.scope.hasGlobal("$db"))for(const e of r("$db",$)){var E;n("MemberExpression"==e.parentPath.node.type),n("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;n(i.includes(r),`invalid db method "${r}", valid db methods are "${i.join('", "')}"`),"CallExpression"==(null===(E=e.parentPath.parentPath)||void 0===E?void 0:E.type)?e.parentPath.replaceWith(t.identifier(`$${p}$DB$${r}`)):"ObjectId"==r?e.parentPath.replaceWith(t.arrowFunctionExpression([],t.callExpression(t.identifier(`$${p}$DB$${r}`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DB$${r}`),[t.identifier("a")]))):e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a"),t.identifier("b")],t.callExpression(t.identifier(`$${p}$DB$${r}`),[t.identifier("a"),t.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of r("$D",$))"CallExpression"==e.parentPath.type?e.replaceWith(t.identifier(`$${p}$DEBUG`)):e.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DEBUG`),[t.identifier("a")])));if($.scope.hasGlobal("$FMCL"))for(const e of r("$FMCL",$))e.replaceWith(t.identifier(`$${p}$FMCL`));if($.scope.hasGlobal("$G"))for(const e of r("$G",$))e.replaceWith(t.identifier(`$${p}$GLOBAL`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of r("_SECLEVEL",$))e.replaceWith(t.numericLiteral(d));let u=!1,_=!1;if($.scope.hasGlobal("Object"))for(const e of r("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(n("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`$${p}$GET_PROTOTYPE_OF`)),u=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`$${p}$SET_PROTOTYPE_OF`)),_=!0));const P=$.node.body[$.node.body.length-1];let O;if(n(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){n("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?O=e.local.name:b.set(e.local.name,t)}}const x=t.blockStatement([]);let T;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=O||!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==O&&(T=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(O),[]))]))),"const"!=e.kind&&b.has(r)&&(y.set(r,b.get(r)),b.delete(r)),x.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&x.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else T=t.functionDeclaration(t.identifier(f),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==O?T=e:x.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):x.body.push(e);if(T||(T=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),$.node.body=[T],x.body.length){(b.size||y.size)&&T.body.body.push(t.returnStatement(t.objectExpression([...[...b].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...y].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),$.scope.crawl();const e=new Set;let i=0;for(const[r,o]of[...x.body.entries()].reverse())if("VariableDeclaration"==o.type){n(1==o.declarations.length);const a=o.declarations[0];if(n("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(a.id.name)){x.body.splice(r,1);const[s]=$.unshiftContainer("body",x),[c]=$.unshiftContainer("body",o);if($.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys($.scope.globals).some((t=>e.has(t)))){const e=$.scope.getBinding(a.id.name);n(e);for(const i of e.referencePaths)n("Identifier"==i.node.type),i.replaceWith(t.memberExpression(t.identifier(`$${p}$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(`$${p}$GLOBAL`),t.identifier(e))));s.remove(),c.remove(),a.init&&x.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL`),t.identifier(a.id.name)),a.init)))}else s.remove(),c.remove(),T.body.body.unshift(o),i++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&($.scope.crawl(),$.scope.hasGlobal(o.id.name))){x.body.splice(r,1);const[e]=$.unshiftContainer("body",x),[i]=$.unshiftContainer("body",o);$.scope.crawl();const a=$.scope.getBinding(o.id.name);n(a);for(const e of a.referencePaths)n("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${p}$GLOBAL`),t.identifier(e.node.name)));e.remove(),i.remove(),x.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL`),t.identifier(o.id.name)),t.classExpression(void 0,o.superClass,o.body,o.decorators))))}if($.scope.hasGlobal("_EXPORTS"))for(const e of r("_EXPORTS",$))e.replaceWith(t.arrayExpression([...b.keys(),...y.keys()].map((e=>t.stringLiteral(e)))));x.body.length&&T.body.body.splice(i,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${p}$FMCL`)),x))}return m&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${p}$FUNCTION_DOT_PROTOTYPE`),createGetFunctionPrototypeNode())])),_&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${p}$SET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${p}$DUNDER_PROTO_SETTER`)]))])),u&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${p}$GET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${p}$DUNDER_PROTO_GETTER`)]))])),(u||_)&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(u?_?[t.objectProperty(t.identifier("get"),t.identifier(`$${p}$DUNDER_PROTO_GETTER`)),t.objectProperty(t.identifier("set"),t.identifier(`$${p}$DUNDER_PROTO_SETTER`))]:[t.objectProperty(t.identifier("get"),t.identifier(`$${p}$DUNDER_PROTO_GETTER`))]:[t.objectProperty(t.identifier("set"),t.identifier(`$${p}$DUNDER_PROTO_SETTER`))]),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getOwnPropertyDescriptor")),[t.memberExpression(t.identifier("Object"),t.identifier("prototype")),t.stringLiteral("__proto__")]))])),o(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:r}){n(t.isClass(r));let a=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(o(r.body,{ThisExpression(i){e=!0,a=!0,i.replaceWith(t.identifier(`_THIS_${p}_`))},Function(e){e.skip()}},i),e)if("constructor"!=r.kind)r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${p}_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(o(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_${p}_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_THIS_${p}_`),i.node));r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${p}_`))]))}else r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${p}_`),t.callExpression(t.super(),[]))]))}}!r.superClass&&a&&(r.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:d};function processFakeSubscriptObject(e){for(const a of r(e,$)){var i,o;n("MemberExpression"==a.parent.type),n("Identifier"==a.parent.property.type),n("MemberExpression"==(null===(i=a.parentPath.parentPath)||void 0===i?void 0:i.node.type)),n("Identifier"==a.parentPath.parentPath.node.property.type),n(/^[_a-z][\d_a-z]{0,24}$/.test(a.parent.property.name),`invalid user "${a.parent.property.name}" in subscript`),n(/^[_a-z][\d_a-z]{0,24}$/.test(a.parentPath.parentPath.node.property.name),`invalid script name "${a.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==(null===(o=a.parentPath.parentPath.parentPath)||void 0===o?void 0:o.type)?a.parentPath.parentPath.replaceWith(t.identifier(`$${p}$SUBSCRIPT$${a.parent.property.name}$${a.parentPath.parentPath.node.property.name}`)):a.parentPath.parentPath.replaceWith(t.arrowFunctionExpression([t.restElement(t.identifier("args"))],t.callExpression(t.identifier(`$${p}$SUBSCRIPT$${a.parent.property.name}$${a.parentPath.parentPath.node.property.name}`),[t.spreadElement(t.identifier("args"))])))}}function createGetFunctionPrototypeNode(){for(const e of a)if(!$.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};
|
1
|
+
import e from"@babel/traverse";import t from"@babel/types";import{v as i}from"../constants-9bb78688.js";import{getReferencePathsToGlobal as r}from"./shared.js";import{a as n}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:o}=e,a=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,s,{uniqueID:p="00000000000",scriptUser:c="UNKNOWN",scriptName:l="UNKNOWN",seclevel:d=4}={}){const f=`_${p}_SCRIPT_`,b=new Map,y=new Map;let m;if(o(e,{Program(e){m=e,e.skip()}}),m.scope.hasGlobal("_START"))for(const e of r("_START",m))e.replaceWith(t.identifier("_ST"));if(m.scope.hasGlobal("_TIMEOUT"))for(const e of r("_START",m))e.replaceWith(t.identifier("_TO"));if(m.scope.hasGlobal("_SOURCE"))for(const e of r("_SOURCE",m))e.replaceWith(t.stringLiteral(s));if(m.scope.hasGlobal("_BUILD_DATE"))for(const e of r("_BUILD_DATE",m))e.replaceWith(t.numericLiteral(Date.now()));if(m.scope.hasGlobal("_SCRIPT_USER"))for(const e of r("_SCRIPT_USER",m))1==c?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_USER$`)):e.replaceWith(t.stringLiteral(c));if(m.scope.hasGlobal("_SCRIPT_NAME"))for(const e of r("_SCRIPT_NAME",m))1==l?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_NAME$`)):e.replaceWith(t.stringLiteral(l));if(m.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of r("_FULL_SCRIPT_NAME",m))1==c||1==l?e.replaceWith(t.stringLiteral(`$${p}$FULL_SCRIPT_NAME$`)):e.replaceWith(t.stringLiteral(`${c}.${l}`));let $=!1;if(m.scope.hasGlobal("Function")){const e=r("Function",m);if(1==e.length){const t=e[0];n("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("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)n("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),$=!0,i.parentPath.replaceWith(t.identifier(`_${p}_FUNCTION_DOT_PROTOTYPE_`));$=!0}}let h=4;for(const e of["$fs","$4s","$s"])m.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])m.scope.hasGlobal(e)&&(h=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])m.scope.hasGlobal(e)&&(h=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])m.scope.hasGlobal(e)&&(h=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])m.scope.hasGlobal(e)&&(h=0,processFakeSubscriptObject(e));if(d=Math.min(d,h),m.scope.hasGlobal("$db"))for(const e of r("$db",m)){var _;n("MemberExpression"==e.parentPath.node.type),n("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;n(i.includes(r),`invalid db method "${r}", valid db methods are "${i.join('", "')}"`),"CallExpression"==(null===(_=e.parentPath.parentPath)||void 0===_?void 0:_.type)?e.parentPath.replaceWith(t.identifier(`$${p}$DB$${r}$`)):"ObjectId"==r?e.parentPath.replaceWith(t.arrowFunctionExpression([],t.callExpression(t.identifier(`$${p}$DB$${r}$`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DB$${r}$`),[t.identifier("a")]))):e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a"),t.identifier("b")],t.callExpression(t.identifier(`$${p}$DB$${r}$`),[t.identifier("a"),t.identifier("b")])))}if(m.scope.hasGlobal("$D"))for(const e of r("$D",m))"CallExpression"==e.parentPath.type?e.replaceWith(t.identifier(`$${p}$DEBUG$`)):e.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DEBUG$`),[t.identifier("a")])));if(m.scope.hasGlobal("$FMCL"))for(const e of r("$FMCL",m))e.replaceWith(t.identifier(`$${p}$FMCL$`));if(m.scope.hasGlobal("$G"))for(const e of r("$G",m))e.replaceWith(t.identifier(`$${p}$GLOBAL$`));if(m.scope.hasGlobal("_SECLEVEL"))for(const e of r("_SECLEVEL",m))e.replaceWith(t.numericLiteral(d));let E=!1,u=!1;if(m.scope.hasGlobal("Object"))for(const e of r("Object",m))"MemberExpression"!=e.parent.type||e.parent.computed||(n("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`_${p}_GET_PROTOTYPE_OF_`)),E=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`_${p}_SET_PROTOTYPE_OF_`)),u=!0));const P=m.node.body[m.node.body.length-1];let O;if(n(P,"program is empty"),"ExportNamedDeclaration"==P.type){m.node.body.pop();for(const e of P.specifiers){n("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?O=e.local.name:b.set(e.local.name,t)}}const x=t.blockStatement([]);let T;for(const e of m.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=O||!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==O&&(T=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(O),[]))]))),"const"!=e.kind&&b.has(r)&&(y.set(r,b.get(r)),b.delete(r)),x.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&x.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else T=t.functionDeclaration(t.identifier(f),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==O?T=e:x.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):x.body.push(e);if(T||(T=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),m.node.body=[T],x.body.length){(b.size||y.size)&&T.body.body.push(t.returnStatement(t.objectExpression([...[...b].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...y].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),m.scope.crawl();const e=new Set;let i=0;for(const[r,o]of[...x.body.entries()].reverse())if("VariableDeclaration"==o.type){n(1==o.declarations.length);const a=o.declarations[0];if(n("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),m.scope.crawl(),m.scope.hasGlobal(a.id.name)){x.body.splice(r,1);const[s]=m.unshiftContainer("body",x),[c]=m.unshiftContainer("body",o);if(m.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys(m.scope.globals).some((t=>e.has(t)))){const e=m.scope.getBinding(a.id.name);n(e);for(const i of e.referencePaths)n("Identifier"==i.node.type),i.replaceWith(t.memberExpression(t.identifier(`$${p}$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(`$${p}$GLOBAL$`),t.identifier(e))));s.remove(),c.remove(),a.init&&x.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(a.id.name)),a.init)))}else s.remove(),c.remove(),T.body.body.unshift(o),i++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&(m.scope.crawl(),m.scope.hasGlobal(o.id.name))){x.body.splice(r,1);const[e]=m.unshiftContainer("body",x),[i]=m.unshiftContainer("body",o);m.scope.crawl();const a=m.scope.getBinding(o.id.name);n(a);for(const e of a.referencePaths)n("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(e.node.name)));e.remove(),i.remove(),x.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(o.id.name)),t.classExpression(void 0,o.superClass,o.body,o.decorators))))}if(m.scope.hasGlobal("_EXPORTS"))for(const e of r("_EXPORTS",m))e.replaceWith(t.arrayExpression([...b.keys(),...y.keys()].map((e=>t.stringLiteral(e)))));x.body.length&&T.body.body.splice(i,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${p}$FMCL$`)),x))}return $&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_SET_PROTOTYPE_OF_`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`_${p}_DUNDER_PROTO_SETTER_`)]))])),E&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_GET_PROTOTYPE_OF_`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`_${p}_DUNDER_PROTO_GETTER_`)]))])),(E||u)&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(E?u?[t.objectProperty(t.identifier("get"),t.identifier(`_${p}_DUNDER_PROTO_GETTER_`)),t.objectProperty(t.identifier("set"),t.identifier(`_${p}_DUNDER_PROTO_SETTER_`))]:[t.objectProperty(t.identifier("get"),t.identifier(`_${p}_DUNDER_PROTO_GETTER_`))]:[t.objectProperty(t.identifier("set"),t.identifier(`_${p}_DUNDER_PROTO_SETTER_`))]),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getOwnPropertyDescriptor")),[t.memberExpression(t.identifier("Object"),t.identifier("prototype")),t.stringLiteral("__proto__")]))])),o(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:r}){n(t.isClass(r));let a=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(o(r.body,{ThisExpression(i){e=!0,a=!0,i.replaceWith(t.identifier(`_${p}_THIS_`))},Function(e){e.skip()}},i),e)if("constructor"!=r.kind)r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(o(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(`_${p}_THIS_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_${p}_THIS_`),i.node));r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`))]))}else r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`),t.callExpression(t.super(),[]))]))}}!r.superClass&&a&&(r.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:d};function processFakeSubscriptObject(e){for(const a of r(e,m)){var i,o;n("MemberExpression"==a.parent.type),n("Identifier"==a.parent.property.type),n("MemberExpression"==(null===(i=a.parentPath.parentPath)||void 0===i?void 0:i.node.type)),n("Identifier"==a.parentPath.parentPath.node.property.type),n(/^[_a-z][\d_a-z]{0,24}$/.test(a.parent.property.name),`invalid user "${a.parent.property.name}" in subscript`),n(/^[_a-z][\d_a-z]{0,24}$/.test(a.parentPath.parentPath.node.property.name),`invalid script name "${a.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==(null===(o=a.parentPath.parentPath.parentPath)||void 0===o?void 0:o.type)?a.parentPath.parentPath.replaceWith(t.identifier(`$${p}$SUBSCRIPT$${a.parent.property.name}$${a.parentPath.parentPath.node.property.name}$`)):a.parentPath.parentPath.replaceWith(t.arrowFunctionExpression([t.restElement(t.identifier("args"))],t.callExpression(t.identifier(`$${p}$SUBSCRIPT$${a.parent.property.name}$${a.parentPath.parentPath.node.property.name}$`),[t.spreadElement(t.identifier("args"))])))}}function createGetFunctionPrototypeNode(){for(const e of a)if(!m.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/push.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"fs";import{resolve as i,extname as r,basename as t}from"path";import{s as a}from"./constants-9bb78688.js";import{processScript as o}from"./processScript/index.js";import{D as p,w as s}from"./writeFilePersistent-72dc81a3.js";import{c as n}from"./countHackmudCharacters-1e122984.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"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"import-meta-resolve";import"./processScript/transform.js";const{readFile:l,readdir:m}=e.promises;async function push(e,c,{scripts:u=["*.*"],onPush:g=(()=>{}),minify:f=!0,mangleNames:b=!1}={}){const d=new p((e=>new Set)),w=new Set,h=new Set;let $=!1;for(const e of u){const[i,r]=e.split(".");i&&"*"!=i?r&&"*"!=r?d.get(i).add(r):w.add(i):r&&"*"!=r?h.add(r):$=!0}const y=new p((e=>new Set)),S=[],j=new p((e=>new Set));let P;if(h.size||$){const t=await m(i(c),{withFileTypes:!0}),a=new Set([...(P=await m(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"==r(e.name))).map((e=>e.name.slice(0,-4))),...d.keys(),...w]);if($)for(const e of a)w.add(e);else for(const e of a){const i=d.get(e);for(const e of h)i.add(e)}}return await Promise.all([...w].map((async p=>{await m(i(e,p),{withFileTypes:!0}).then((async m=>{await Promise.all(m.map((async m=>{const u=r(m.name);if(m.isFile()&&a.includes(u)){const r=t(m.name,u),a=i(e,p,m.name),{script:d}=await o(await l(a,{encoding:"utf-8"}),{minify:f,scriptUser:p,scriptName:r,filePath:a,mangleNames:b}),w={file:`${p}/${m.name}`,users:[p],minLength:n(d),error:void 0};j.get(p).add(r),S.push(w),await s(i(c,p,`scripts/${r}.js`),d),g(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...d].map((async([r,t])=>{w.has(r)||await Promise.all([...t].map((async t=>{let p,m,u;for(const o of a)try{m=`${t}${o}`,p=await l(u=i(e,r,m),{encoding:"utf-8"});break}catch{}if(p){const{script:e}=await o(p,{minify:f,scriptUser:r,scriptName:t,filePath:u,mangleNames:b}),a={file:`${r}/${m}`,users:[r],minLength:n(e),error:void 0};S.push(a),await s(i(c,r,"scripts",`${t}.js`),e),g(a)}else y.get(t).add(r)})))}))),await(w.size?Promise.all((P||await m(i(e),{withFileTypes:!0})).map((async p=>{const m=r(p.name);if(!p.isFile()||!a.includes(m))return;const u=t(p.name,m),d=[...w,...y.get(u)].filter((e=>!j.get(e).has(u)));if(!d.length)return;const h=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),$=i(e,p.name),{script:P}=await o(await l($,{encoding:"utf-8"}),{minify:f,scriptUser:!0,scriptName:u,uniqueID:h,filePath:$,mangleNames:b}),N={file:p.name,users:d,minLength:n(P),error:void 0};await Promise.all(d.map((e=>s(i(c,e,`scripts/${u}.js`),P.replace(new RegExp(
|
1
|
+
import e from"fs";import{resolve as i,extname as r,basename as t}from"path";import{s as a}from"./constants-9bb78688.js";import{processScript as o}from"./processScript/index.js";import{D as p,w as s}from"./writeFilePersistent-72dc81a3.js";import{c as n}from"./countHackmudCharacters-1e122984.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"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"import-meta-resolve";import"./processScript/transform.js";const{readFile:l,readdir:m}=e.promises;async function push(e,c,{scripts:u=["*.*"],onPush:g=(()=>{}),minify:f=!0,mangleNames:b=!1}={}){const d=new p((e=>new Set)),w=new Set,h=new Set;let $=!1;for(const e of u){const[i,r]=e.split(".");i&&"*"!=i?r&&"*"!=r?d.get(i).add(r):w.add(i):r&&"*"!=r?h.add(r):$=!0}const y=new p((e=>new Set)),S=[],j=new p((e=>new Set));let P;if(h.size||$){const t=await m(i(c),{withFileTypes:!0}),a=new Set([...(P=await m(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"==r(e.name))).map((e=>e.name.slice(0,-4))),...d.keys(),...w]);if($)for(const e of a)w.add(e);else for(const e of a){const i=d.get(e);for(const e of h)i.add(e)}}return await Promise.all([...w].map((async p=>{await m(i(e,p),{withFileTypes:!0}).then((async m=>{await Promise.all(m.map((async m=>{const u=r(m.name);if(m.isFile()&&a.includes(u)){const r=t(m.name,u),a=i(e,p,m.name),{script:d}=await o(await l(a,{encoding:"utf-8"}),{minify:f,scriptUser:p,scriptName:r,filePath:a,mangleNames:b}),w={file:`${p}/${m.name}`,users:[p],minLength:n(d),error:void 0};j.get(p).add(r),S.push(w),await s(i(c,p,`scripts/${r}.js`),d),g(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...d].map((async([r,t])=>{w.has(r)||await Promise.all([...t].map((async t=>{let p,m,u;for(const o of a)try{m=`${t}${o}`,p=await l(u=i(e,r,m),{encoding:"utf-8"});break}catch{}if(p){const{script:e}=await o(p,{minify:f,scriptUser:r,scriptName:t,filePath:u,mangleNames:b}),a={file:`${r}/${m}`,users:[r],minLength:n(e),error:void 0};S.push(a),await s(i(c,r,"scripts",`${t}.js`),e),g(a)}else y.get(t).add(r)})))}))),await(w.size?Promise.all((P||await m(i(e),{withFileTypes:!0})).map((async p=>{const m=r(p.name);if(!p.isFile()||!a.includes(m))return;const u=t(p.name,m),d=[...w,...y.get(u)].filter((e=>!j.get(e).has(u)));if(!d.length)return;const h=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),$=i(e,p.name),{script:P}=await o(await l($,{encoding:"utf-8"}),{minify:f,scriptUser:!0,scriptName:u,uniqueID:h,filePath:$,mangleNames:b}),N={file:p.name,users:d,minLength:n(P),error:void 0};await Promise.all(d.map((e=>s(i(c,e,`scripts/${u}.js`),P.replace(new RegExp(`\\$${h}\\$SCRIPT_USER\\$`,"g"),e).replace(new RegExp(`\\$${h}\\$FULL_SCRIPT_NAME\\$`,"g"),`${e}.${u}`))))),S.push(N),g(N)}))):Promise.all([...y].map((async([r,t])=>{let p,m,u;for(const t of a)try{m=`${r}${t}`,p=await l(u=i(e,m),{encoding:"utf-8"});break}catch{}if(p){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{script:a}=await o(p,{minify:f,scriptUser:!0,scriptName:r,uniqueID:e,filePath:u,mangleNames:b}),l={file:m,users:[...t],minLength:n(a),error:void 0};await Promise.all([...t].map((t=>s(i(c,t,`scripts/${r}.js`),a.replace(new RegExp(`\\$${e}\\$SCRIPT_USER\\$`,"g"),t).replace(new RegExp(`\\$${e}\\$FULL_SCRIPT_NAME\\$`,"g"),`${t}.${r}`))))),S.push(l),g(l)}})))),S}export{push as default,push};
|
package/watch.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import{watch as r}from"chokidar";import o from"fs";import{extname as i,basename as t,resolve as e}from"path";import{s}from"./constants-9bb78688.js";import{generateTypings as p}from"./generateTypings.js";import{processScript as a}from"./processScript/index.js";import{D as n,w as l}from"./writeFilePersistent-72dc81a3.js";import{a as c}from"./assert-1556d989.js";import{c as m}from"./countHackmudCharacters-1e122984.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"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.js";const{readFile:u,readdir:f}=o.promises;function watch(o,b,{scripts:d=["*.*"],onPush:g,minify:h=!0,mangleNames:w=!1,typeDeclarationPath:y,onReady:j}={}){if(!d.length)throw new Error("scripts option was an empty array");const S=new n((r=>new Set))
|
1
|
+
import{watch as r}from"chokidar";import o from"fs";import{extname as i,basename as t,resolve as e}from"path";import{s}from"./constants-9bb78688.js";import{generateTypings as p}from"./generateTypings.js";import{processScript as a}from"./processScript/index.js";import{D as n,w as l}from"./writeFilePersistent-72dc81a3.js";import{a as c}from"./assert-1556d989.js";import{c as m}from"./countHackmudCharacters-1e122984.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"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.js";const{readFile:u,readdir:f}=o.promises;function watch(o,b,{scripts:d=["*.*"],onPush:g,minify:h=!0,mangleNames:w=!1,typeDeclarationPath:y,onReady:j}={}){if(!d.length)throw new Error("scripts option was an empty array");const S=new n((r=>new Set)),$=new Set,v=new Set;let F=!1;for(const r of d){const[o,i]=r.split(".");o&&"*"!=o?i&&"*"!=i?S.get(i).add(o):$.add(o):i&&"*"!=i?v.add(i):F=!0}const P=r("",{depth:1,cwd:o,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async r=>{const p=i(r);if(!s.includes(p))return;const d=t(r,p);if(r==t(r)){if(!(F||$.size||v.has(d)||S.has(d)))return;const p=new n((r=>[]));await Promise.all((await f(o,{withFileTypes:!0})).map((async r=>{if(r.isDirectory())for(const a of await f(e(o,r.name),{withFileTypes:!0})){if(!a.isFile())continue;const o=i(a.name);s.includes(o)&&p.get(t(a.name,o)).push(r.name)}})));const y=new Set;if(F||v.has(d)){for(const r of await f(e(o),{withFileTypes:!0}))r.isDirectory()&&y.add(r.name);for(const r of await f(e(b),{withFileTypes:!0}))r.isDirectory()?y.add(r.name):r.isFile()&&r.name.endsWith(".key")&&y.add(r.name.slice(0,-4));for(const r of S.values())for(const o of r)y.add(o)}for(const r of $)y.add(r);for(const r of S.get(d))y.add(r);const j=[...y].filter((r=>!p.has(r)));if(!j.length)return void(null==g||g({file:r,users:[],minLength:0,error:new Error("no users to push to")}));const P=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),E=e(o,r);let T;try{({script:T}=await a(await u(E,{encoding:"utf-8"}),{minify:h,scriptUser:!0,scriptName:d,uniqueID:P,filePath:E,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==g||g({file:r,users:[],minLength:0,error:o}))}return await Promise.all(j.map((r=>l(e(b,r,`scripts/${d}.js`),T.replace(new RegExp(`\\$${P}\\$SCRIPT_USER\\$`,"g"),r).replace(new RegExp(`\\$${P}\\$FULL_SCRIPT_NAME\\$`,"g"),`${r}.${d}`))))),void(null==g||g({file:r,users:j,minLength:m(T),error:void 0}))}const y=t(e(r,".."));if(!(F||$.size||v.has(d)||S.get(d).has(y)))return;const j=e(o,r),P=await u(j,{encoding:"utf-8"});let E;try{({script:E}=await a(P,{minify:h,scriptUser:y,scriptName:d,filePath:j,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==g||g({file:r,users:[],minLength:0,error:o}))}await l(e(b,y,"scripts",`${d}.js`),E),null==g||g({file:r,users:[y],minLength:m(E),error:void 0})}));j&&P.on("ready",j),y&&(p(o,e(o,y),b),P.on("add",(()=>p(o,e(o,y),b))),P.on("unlink",(()=>p(o,e(o,y),b))))}export{watch as default,watch};
|