hackmud-script-manager 0.14.0-66846c3 → 0.14.0-f09e93a
Sign up to get free protection for your applications and to get access to all the features.
- package/bin/hsm.js +1 -1
- package/index.js +1 -1
- package/package.json +2 -2
- package/processScript/index.js +1 -1
- package/processScript/minify.js +1 -1
- package/processScript/postprocess.js +1 -1
- package/processScript/preprocess.d.ts +0 -1
- package/processScript/preprocess.js +1 -1
- package/processScript/shared.d.ts +2 -0
- package/processScript/shared.js +1 -1
- package/processScript/transform.js +1 -1
- package/push.d.ts +4 -3
- package/push.js +1 -1
- package/watch.d.ts +11 -4
- package/watch.js +1 -1
- package/writeFilePersistent-72dc81a3.js +1 -0
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
|
2
|
+
import o from"chalk";import{watch as e}from"chokidar";import s from"fs";import{homedir as t}from"os";import{resolve as i,basename as n,extname as a,dirname as r,relative as l}from"path";import{s as c}from"../processScript/transform.js";import{D as p,w as g}from"../writeFilePersistent-72dc81a3.js";import{generateTypings as m}from"../generateTypings.js";import{syncMacros as f}from"../syncMacros.js";import{pull as h}from"../pull.js";import{watch as u}from"../watch.js";import{push as b}from"../push.js";import{processScript as d}from"../processScript/index.js";import{c as k}from"../processScript/minify.js";import"@babel/traverse";import"@babel/types";import"../processScript/shared.js";import"../assert-1556d989.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"../processScript/postprocess.js";import"../spliceString-2c6f214f.js";import"../processScript/preprocess.js";import"acorn";import"terser";const{readFile:y,rmdir:w,writeFile:j,mkdir:$}=s.promises,v=i(t(),".config"),P=i(v,"hsm.json"),S=new Map,C=[];let x;const N=o.rgb(255,244,4),F=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),D=new p((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[N,F,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 C.push(o);function help(){switch(C[0]){case"config":switch(C[1]){case"get":console.log("hsm config get <key>");break;case"set":console.log("hsm config set <key> <value>");break;case"delete":console.log("hsm config delete <key>");break;default:console.log("hsm config <get, delete, set>")}break;case"push":console.log('hsm push [<dir> [..."<script user>.<script name>"]]');break;case"dev":case"watch":console.log(`hsm ${C[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(`${n(process.argv[1])} ${C[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.14.0-f09e93a")}async function getConfig(){return x||(x=await y(P,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${P}`),{}))))}function exploreObject(o,e,s=!1){for(const 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(x){const o=JSON.stringify(x,void 0,"\t");j(P,o).catch((async e=>{switch(e.code){case"EISDIR":await w(P);break;case"ENOENT":await $(v);break;default:throw e}j(P,o)}))}}function onPushLogger({file:e,users:s,srcLength:t,minLength:r,error:l}){l?console.log(`error "${o.bold(l.message)}" in ${o.bold(e)}`):console.log(`pushed ${o.bold(e)} to ${s.map((e=>o.bold(D.get(e)))).join(", ")} | ${o.bold(String(r))} chars from ${o.bold(String(t))} | saved ${o.bold(String(t-r))} (${o.bold(`${Math.round(100*(1-r/t))}%`)}) | ${o.bold(`${i(x.hackmudPath,s[0],"scripts",n(e,a(e)))}.js`)}`)}(async()=>{if(S.get("version")||S.get("v"))version();else if(S.get("help")||S.get("h"))help();else{switch(C[0]){case"push":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1]||".",s=o.hackmudPath,t=C.slice(2);t.length||t.push("*.*");(await b(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 s;if(!C[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 e=C.slice(2);e.length||e.push("*.*"),S.has("skip-minify")&&S.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names"),u(C[1],o.hackmudPath,{scripts:e,onPush:onPushLogger,typeDeclarationPath:null===(s=S.get("type-declaration-path"))||void 0===s?void 0:s.toString(),minify:!S.get("skip-minify"),mangleNames:Boolean(S.get("mangle-names"))})}break;case"pull":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1];if(!e){help();break}const s=C[2]||".",t=o.hackmudPath;try{await 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 f(o);console.log(`synced ${e} macros to ${s} users`)}break;case"gen-types":{const o=i(C[1]||".");m(o,C[2]?i(C[2]):i(o,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(C[1]){case"get":C[2]?console.log(exploreObject(await getConfig(),C[2].split("."))):console.log(await getConfig());break;case"delete":if(C[2]){var t;const o=C[2].split("."),e=o.pop();if(!o.length){help();break}const s=await getConfig();null===(t=exploreObject(s,o))||void 0===t||delete t[e],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(C[2]&&C[3]){const o=C[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]=C[3]}else s.hackmudPath=i(C[3]);console.log(s)}else console.log("Usage:\nhsm config set <key> <value>");break;default:C[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{const s=C[1];if(!s){console.log(`Target required\nUsage: ${n(process.argv[1])} ${C[0]} <target> [output]`);break}const t=a(s);if(!c.includes(t)){console.log(`Unsupported file extension "${o.bold(t)}"\nSupported extensions are "${c.map((e=>o.bold(e))).join('", "')}"`);break}S.get("watch")?e(s,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>console.log(`watching ${s}`))).on("change",(()=>golfFile(s,t))):await golfFile(s,t)}break;default:C[0]&&console.log("unknown command"),help()}updateConfig()}async function golfFile(e,s){await y(e,{encoding:"utf-8"}).then((async t=>{const a=n(e,s),c=a.endsWith(".src"),p=c?a.slice(0,-4):a;let m="UNKNOWN";"scripts"==n(i(e,".."))&&"hackmud"==n(i(e,"../../.."))&&(m=n(i(e,"../..")));const f=!S.get("skip-minify"),h=Boolean(S.get("mangle-names"));!f&&h&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:u,srcLength:b,warnings:y,timeTook:w}=await d(t,{minify:f,scriptUser:m,scriptName:p,filePath:e,mangleNames:h});for(const{message:e,line:s}of y)console.log(`warning "${o.bold(e)}" on line ${o.bold(String(s))}`);let j;j=C[2]?C[2]:i(r(e),c?`${p}.js`:".js"==s?`${a}.min.js`:`${a}.js`);const $=k(u);await g(j,u).catch((async o=>{if(!C[2]||"EISDIR"!=o.code)throw o;j=i(j,`${n(e,s)}.js`),await g(j,u)})).then((()=>console.log(`wrote ${o.bold($)} chars to ${o.bold(l(".",j))} | saved ${o.bold(b-$)} chars | took ${Math.round(100*w)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}})();
|
package/index.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
export{
|
1
|
+
export{s as supportedExtensions}from"./processScript/transform.js";export{generateTypings}from"./generateTypings.js";export{processScript}from"./processScript/index.js";export{pull}from"./pull.js";export{push}from"./push.js";export{syncMacros}from"./syncMacros.js";export{watch}from"./watch.js";import"@babel/traverse";import"@babel/types";import"./processScript/shared.js";import"./assert-1556d989.js";import"fs";import"path";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./writeFilePersistent-72dc81a3.js";import"chokidar";
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "hackmud-script-manager",
|
3
|
-
"version": "0.14.0-
|
3
|
+
"version": "0.14.0-f09e93a",
|
4
4
|
"description": "Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.",
|
5
5
|
"keywords": [
|
6
6
|
"api",
|
@@ -68,7 +68,7 @@
|
|
68
68
|
"devDependencies": {
|
69
69
|
"@babel/preset-env": "^7.16.4",
|
70
70
|
"@babel/preset-typescript": "^7.16.0",
|
71
|
-
"@samual/lib": "^0.
|
71
|
+
"@samual/lib": "^0.3.0",
|
72
72
|
"@types/babel__core": "^7.1.16",
|
73
73
|
"@types/node": "^12.20.37",
|
74
74
|
"@types/prettier": "^2.4.2",
|
package/processScript/index.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/generator";import{parse as
|
1
|
+
import e from"@babel/generator";import{parse as r}from"@babel/parser";import o from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import a from"@babel/plugin-proposal-decorators";import s from"@babel/plugin-proposal-do-expressions";import p 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 d from"@babel/plugin-proposal-optional-chaining";import b 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 y from"@babel/plugin-proposal-record-and-tuple";import w from"@babel/plugin-proposal-throw-expressions";import k from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import v from"@babel/traverse";import x from"@babel/types";import S from"@rollup/plugin-babel";import E from"@rollup/plugin-commonjs";import L from"@rollup/plugin-json";import $ from"@rollup/plugin-node-resolve";import{resolve as C}from"path";import{performance as N}from"perf_hooks";import I from"prettier";import{rollup as _}from"rollup";import{s as D,transform as P}from"./transform.js";export{transform as compile}from"./transform.js";import{c as M,minify as O}from"./minify.js";export{minify}from"./minify.js";import{postprocess as U}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as q}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{includesIllegalString as T,replaceIllegalStrings as V}from"./shared.js";import{a as W}from"../assert-1556d989.js";import"acorn";import"terser";import"../spliceString-2c6f214f.js";const{default:F}=S,{format:H}=I,{default:K}=e,{default:z}=v;async function processScript(e,{minify:v=!0,uniqueID:S=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:I="UNKNOWN",scriptName:A="UNKNOWN",filePath:B,mangleNames:G=!1}={}){W(/^\w{11}$/.exec(S));const J=N.now(),Q=e;let R,X;const Y=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(Y)e=`export default ${e}`,({autocomplete:R}=Y.groups);else for(const r of e.split("\n")){const e=/^\s*\/\/(?<commentContent>.+)/.exec(r);if(!e)break;const o=e.groups.commentContent.trim();if(o.startsWith("@autocomplete "))R=o.slice(14).trimStart();else if(o.startsWith("@seclevel ")){const e=o.slice(10).trimStart().toLowerCase();switch(e){case"fullsec":case"full":case"fs":case"4s":case"f":case"4":X=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":X=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":X=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":X=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":X=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}W(/^\w{11}$/.exec(S));const Z=B?C(B):`${S}.ts`,ee=await _({input:Z,plugins:[{name:"hackmud-script-manager",transform:e=>q(e,{uniqueID:S}).code},F({babelHelpers:"bundled",plugins:[[j.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[a.default,{decoratorsBeforeExport:!0}],[s.default],[p.default],[l.default],[b.default],[g.default,{proposal:"hack",topicToken:"%"}],[w.default],[y.default,{syntaxType:"hash",importPolyfill:!0}],[o.default],[t.default],[h.default],[n.default],[c.default],[m.default],[d.default],[u.default],[i.default],[f.default],[k.default]],configFile:!1,extensions:D}),E(),$({extensions:D}),L()],treeshake:{moduleSideEffects:!1}}),re=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];e=(await ee.generate({})).output[0].code;const{file:oe,seclevel:te}=P(r(e,{sourceType:"module"}),Q,{uniqueID:S,scriptUser:I,scriptName:A});if(null!=X&&te<X)throw new Error(`detected seclevel ${re[te]} is lower than stated seclevel ${re[X]}`);e=K(oe).code;const ae=M(e.replace(/^function\s*\w+\(/,"function("));if(v?e=await O(oe,R,{uniqueID:S,mangleNames:G}):(z(oe,{MemberExpression({node:e}){e.computed||(W("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=x.stringLiteral("prototype")):"__proto__"==e.property.name?(e.computed=!0,e.property=x.stringLiteral("__proto__")):T(e.property.name)&&(e.computed=!0,e.property=x.stringLiteral(V(S,e.property.name))))},VariableDeclarator(e){!function renameVariables(r){switch(r.type){case"Identifier":T(r.name)&&e.scope.rename(r.name,`$${Math.floor(Math.random()*2**52).toString(36).padStart(11,"0")}`);break;case"ObjectPattern":for(const e of r.properties)W("ObjectProperty"==e.type),renameVariables(e.value);break;case"ArrayPattern":for(const e of r.elements)e&&renameVariables(e);break;default:throw new Error(`unknown lValue type "${r.type}"`)}}(e.node.id)},ObjectProperty({node:e}){"Identifier"==e.key.type&&T(e.key.name)&&(e.key=x.stringLiteral(V(S,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=V(S,e.value)},TemplateLiteral({node:e}){for(const r of e.quasis)r.value.cooked?(r.value.cooked=V(S,r.value.cooked),r.value.raw=r.value.cooked.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"$\\{")):r.value.raw=V(S,r.value.raw)}}),e=H(K(oe,{comments:!1}).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),e=U(e,te,S),T(e))throw new Error('you found a weird edge case where I wasn\'t able to replace illegal strings like "SC$", please report thx');return{srcLength:ae,script:e,warnings:[],timeTook:N.now()-J}}export{processScript as default,processScript};
|
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 s}from"./shared.js";import{a as
|
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,replaceIllegalStrings as p}from"./shared.js";import{a as l}from"../assert-1556d989.js";import{s as u}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:c}=e,{default:f}=t;async function minify(e,t,{uniqueID:i="00000000000",mangleNames:n=!1}={}){let d;l(/^\w{11}$/.exec(i)),f(e,{Program(e){d=e,e.skip()}});const m=d.get("body.0");for(const e of[...m.node.params].reverse()){if("Identifier"==e.type){if(!m.scope.getBinding(e.name).referenced){m.node.params.pop();continue}}break}for(const e in d.scope.globals){if("arguments"==e||e.startsWith(`$${i}`))continue;const t=o(e,d);if(!(5+e.length+t.length>=e.length*t.length)){for(const n of t)n.replaceWith(r.identifier(`_GLOBAL_${e}_${i}_`));m.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_GLOBAL_${e}_${i}_`),r.identifier(e))]))}}const y=o(`$${i}$GLOBAL`,d);if(y.length>3){for(const e of y)e.replaceWith(r.identifier(`_G_${i}_`));m.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_G_${i}_`),r.identifier(`$${i}$GLOBAL`))]))}const _=[];let $=!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(`_PROTOTYPE_PROPERTY_${i}_`)):"__proto__"==e.property.name?(e.computed=!0,e.property=r.identifier(`_PROTO_PROPERTY_${i}_`)):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)}});const E=(await a.minify(c(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(`_PROTOTYPE_PROPERTY_${i}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${i}_`,"g"),'"__proto__"');let b,v,h=!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(`_JSON_VALUE_${_.push(t)-1}_${i}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${_.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||(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(`_UNDEFINED_${i}_`)),$=!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(`_JSON_VALUE_${t}_${i}_`))})()),e.skip()}},NullLiteral(e){let t=_.indexOf(null);-1==t&&(t+=_.push(null)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},BooleanLiteral(e){let t=_.indexOf(e.node.value);-1==t&&(t+=_.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=_.indexOf(e.node.value);-1==t&&(t+=_.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))})())},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(`_JSON_VALUE_${t}_${i}_`))},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(`_JSON_VALUE_${t}_${i}_`)}}),e.skip()}}),await Promise.all(t);const n=e.program.body[0];if(l("FunctionDeclaration"==n.type),_.length)if(h=!0,1==_.length)if("string"!=typeof _[0]||_[0].includes("\n")||_[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)]))]);$&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),b=JSON.stringify(_[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))]);$&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),b=_[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern(_.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)]))]);$&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),b=JSON.stringify(_)}else $&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))]));v=c(e).code}return v=(await a.minify(v,{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!=b&&(v=u(v,`${t?`//${t}\n`:""}\n//\t${b}\t\n`,getFunctionBodyStart(v)+1),v=v.replace(`$${i}$SPLIT_INDEX`,await minifyNumber(v.split("\t").findIndex((e=>e==b))))),countHackmudCharacters(E)<=countHackmudCharacters(v)+Number(h)&&(v=E,t&&(v=u(v,`//${t}\n`,getFunctionBodyStart(v)+1))),v}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{countHackmudCharacters as c,minify as default,minify};
|
@@ -1 +1 @@
|
|
1
|
-
import{a as e}from"../assert-1556d989.js";import{s}from"../spliceString-2c6f214f.js";function*findMatches(s
|
1
|
+
import{a as e}from"../assert-1556d989.js";import{s as $}from"../spliceString-2c6f214f.js";function*findMatches($,s){let n;for(e($.global,"regex must have global flag");n=$.exec(s);)yield{index:n.index,match:n[1]||n[0]}}function postprocess(e,s,n){e=e.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${n}\\$\\\\\\\\0\\$SC_DOLLAR\\$`,"g"),"SC\\$").replace(new RegExp(`\\$${n}\\$\\\\\\\\0\\$DB_DOLLAR\\$`,"g"),"DB\\$").replace(new RegExp(`\\$${n}\\$\\\\\\\\0\\$D\\$`,"g"),"__D_\\S").replace(new RegExp(`\\$${n}\\$\\\\\\\\0\\$FMCL\\$`,"g"),"__FMCL\\_").replace(new RegExp(`\\$${n}\\$\\\\\\\\0\\$G\\$`,"g"),"__G\\_");for(const{index:r,match:t}of[...findMatches(new RegExp(`\\$${n}\\$[\\w$]+`,"g"),e)].reverse()){const[n,...a]=t.slice(13).split("$");switch(n){case"SUBSCRIPT":e=$(e,`#${"nlmhf"[s]}s.${a[0]}.${a[1]}`,r,t.length);break;case"DEBUG":e=$(e,"#D",r,t.length);break;case"FMCL":e=$(e,"#FMCL",r,t.length);break;case"GLOBAL":e=$(e,"#G",r,t.length);break;case"DB":e=$(e,`#db.${a[0]}`,r,t.length);break;default:throw new Error(`unknown type "${n}"`)}}return e}export{postprocess as default,postprocess};
|
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/generator";import{parse as
|
1
|
+
import e from"@babel/generator";import{parse as o}from"@babel/parser";import r 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}=r,{default:l}=e;function preprocess(e,{uniqueID:r="00000000000"}={}){t(/^\w{11}$/.test(r));const n=e;let c,a,f;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{a=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){t(e instanceof SyntaxError),i=e}var d;if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(null===(d=/.+/.exec(e.slice(i.pos)))||void 0===d?void 0:d[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=/^#[0-4fhmln]?s\./.exec(p))e=s(e,"$",i.pos,1);else if(l=/^#D[^\w$]/.exec(p))e=s(e,"$",i.pos,1);else if(l=/^#FMCL/.exec(p))e=s(e,`$${r}$FMCL`,i.pos,l[0].length);else if(l=/^#G/.exec(p))e=s(e,`$${r}$GLOBAL`,i.pos,l[0].length);else{if(!(l=/^#db\./.exec(p)))throw i;e=s(e,"$",i.pos,1)}}p(a,{Program(e){f=e,e.skip()}});const u=f.scope.hasGlobal("Record"),m=f.scope.hasGlobal("Tuple");return(u||m)&&a.program.body.unshift(i.importDeclaration(u?m?[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")&&a.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(a).code}`}:{code:l(a).code}}export{preprocess as default,preprocess};
|
@@ -1,3 +1,5 @@
|
|
1
1
|
import { NodePath } from "@babel/traverse";
|
2
2
|
import t, { Program } from "@babel/types";
|
3
3
|
export declare function getReferencePathsToGlobal(name: string, program: NodePath<Program>): NodePath<t.Identifier>[];
|
4
|
+
export declare function includesIllegalString(toCheck: string): boolean;
|
5
|
+
export declare function replaceIllegalStrings(uniqueID: string, toReplace: string): string;
|
package/processScript/shared.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/types";import{e as
|
1
|
+
import e from"@babel/types";import{e as l}from"../assert-1556d989.js";function getReferencePathsToGlobal(r,n){const[a]=n.unshiftContainer("body",e.variableDeclaration("let",[e.variableDeclarator(e.identifier(r))]));n.scope.crawl();const t=l(n.scope.getBinding(r));return a.remove(),t.referencePaths}function includesIllegalString(e){return e.includes("SC$")||e.includes("DB$")||e.includes("__D_S")||e.includes("__FMCL_")||e.includes("__G_")}function replaceIllegalStrings(e,l){return l.replace(/SC\$/g,`$${e}$\\0$SC_DOLLAR$`).replace(/DB\$/g,`$${e}$\\0$DB_DOLLAR$`).replace(/__D_S/g,`$${e}$\\0$D$`).replace(/__FMCL_/g,`$${e}$\\0$FMCL$`).replace(/__G_/g,`$${e}$\\0$G$`)}export{getReferencePathsToGlobal,includesIllegalString,replaceIllegalStrings};
|
@@ -1 +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};
|
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";const n=[".js",".ts"],o=["i","r","f","u","u1","us","ObjectId"];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:a}=e,s=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,n,{uniqueID:p="00000000000",scriptUser:c="UNKNOWN",scriptName:l="UNKNOWN",seclevel:d=4}={}){const f=`_SCRIPT_${p}_`,b=new Map,y=new Map;let $;if(a(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_START"))for(const e of i("_START",$))e.replaceWith(t.identifier("_ST"));if($.scope.hasGlobal("_TIMEOUT"))for(const e of i("_START",$))e.replaceWith(t.identifier("_TO"));if($.scope.hasGlobal("_SOURCE"))for(const e of i("_SOURCE",$))e.replaceWith(t.stringLiteral(n));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of i("_BUILD_DATE",$))e.replaceWith(t.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of i("_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 i("_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 i("_FULL_SCRIPT_NAME",$))1==c||1==l?e.replaceWith(t.stringLiteral(`$${p}$FULL_SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(`${c}.${l}`));let h=!1;if($.scope.hasGlobal("Function")){const e=i("Function",$);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(`$${p}$FUNCTION_DOT_PROTOTYPE`));h=!0}}let m=4;for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(m=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(m=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(m=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(m=0,processFakeSubscriptObject(e));if(d=Math.min(d,m),$.scope.hasGlobal("$db"))for(const e of i("$db",$)){var E;r("MemberExpression"==e.parentPath.node.type),r("Identifier"==e.parentPath.node.property.type);const i=e.parentPath.node.property.name;r(o.includes(i),`invalid db method "${i}", valid db methods are "${o.join('", "')}"`),"CallExpression"==(null===(E=e.parentPath.parentPath)||void 0===E?void 0:E.type)?e.parentPath.replaceWith(t.identifier(`$${p}$DB$${i}`)):"ObjectId"==i?e.parentPath.replaceWith(t.arrowFunctionExpression([],t.callExpression(t.identifier(`$${p}$DB$${i}`),[]))):"i"==i||"r"==i?e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DB$${i}`),[t.identifier("a")]))):e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a"),t.identifier("b")],t.callExpression(t.identifier(`$${p}$DB$${i}`),[t.identifier("a"),t.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of i("$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 i("$FMCL",$))e.replaceWith(t.identifier(`$${p}$FMCL`));if($.scope.hasGlobal("$G"))for(const e of i("$G",$))e.replaceWith(t.identifier(`$${p}$GLOBAL`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of i("_SECLEVEL",$))e.replaceWith(t.numericLiteral(d));let u=!1,_=!1;if($.scope.hasGlobal("Object"))for(const e of i("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(r("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(r(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){r("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 n=0;for(const[i,o]of[...x.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}"`),$.scope.crawl(),$.scope.hasGlobal(a.id.name)){x.body.splice(i,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);r(e);for(const i of e.referencePaths)r("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(i,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),n++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&($.scope.crawl(),$.scope.hasGlobal(o.id.name))){x.body.splice(i,1);const[e]=$.unshiftContainer("body",x),[n]=$.unshiftContainer("body",o);$.scope.crawl();const a=$.scope.getBinding(o.id.name);r(a);for(const e of a.referencePaths)r("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${p}$GLOBAL`),t.identifier(e.node.name)));e.remove(),n.remove(),x.body.splice(i,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 i("_EXPORTS",$))e.replaceWith(t.arrayExpression([...b.keys(),...y.keys()].map((e=>t.stringLiteral(e)))));x.body.length&&T.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${p}$FMCL`)),x))}return h&&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__")]))])),a(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:n}){r(t.isClass(n));let o=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(a(r.body,{ThisExpression(i){e=!0,o=!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(a(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(),[]))]))}}!n.superClass&&o&&(n.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 i(e,$)){var n,o;r("MemberExpression"==a.parent.type),r("Identifier"==a.parent.property.type),r("MemberExpression"==(null===(n=a.parentPath.parentPath)||void 0===n?void 0:n.node.type)),r("Identifier"==a.parentPath.parentPath.node.property.type),r(/^[_a-z][\d_a-z]{0,24}$/.test(a.parent.property.name),`invalid user "${a.parent.property.name}" in subscript`),r(/^[_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 s)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,n as s,transform};
|
package/push.d.ts
CHANGED
@@ -1,5 +1,6 @@
|
|
1
|
+
import { LaxPartial } from "@samual/lib";
|
1
2
|
import { Info } from ".";
|
2
|
-
declare type PushOptions = {
|
3
|
+
export declare type PushOptions = {
|
3
4
|
/** whether to do the minify step (defaults to `true`) */
|
4
5
|
minify: boolean;
|
5
6
|
/** whether to mangle function and class names (defaults to `false`) */
|
@@ -11,7 +12,7 @@ declare type PushOptions = {
|
|
11
12
|
*
|
12
13
|
* pushes everything by default (`*.*`)
|
13
14
|
*/
|
14
|
-
scripts: string
|
15
|
+
scripts: string[];
|
15
16
|
/** callback called on script push */
|
16
17
|
onPush: (info: Info) => void;
|
17
18
|
};
|
@@ -24,5 +25,5 @@ declare type PushOptions = {
|
|
24
25
|
* @param options {@link PushOptions details}
|
25
26
|
* @returns array of info on pushed scripts
|
26
27
|
*/
|
27
|
-
export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames }?:
|
28
|
+
export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames }?: LaxPartial<PushOptions>): Promise<Info[]>;
|
28
29
|
export default push;
|
package/push.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"fs";import{
|
1
|
+
import e from"fs";import{resolve as r,extname as i,basename as t}from"path";import{s as a}from"./processScript/transform.js";import{processScript as o}from"./processScript/index.js";import{D as s,w as p}from"./writeFilePersistent-72dc81a3.js";import{c as n}from"./processScript/minify.js";import"@babel/traverse";import"@babel/types";import"./processScript/shared.js";import"./assert-1556d989.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./spliceString-2c6f214f.js";import"./processScript/preprocess.js";import"acorn";import"terser";const{readFile:l,readdir:m}=e.promises;async function push(e,c,{scripts:g=["*.*"],onPush:f=(()=>{}),minify:u=!0,mangleNames:b=!1}={}){const h=new s((e=>new Set)),d=new Set,w=new Set;let $=!1;for(const e of g){const[r,i]=e.split(".");r&&"*"!=r?i&&"*"!=i?h.get(r).add(i):d.add(r):i&&"*"!=i?w.add(i):$=!0}const y=new s((e=>new Set)),S=[],j=new s((e=>new Set));let P;if(w.size||$){const t=await m(r(c),{withFileTypes:!0}),a=new Set([...(P=await m(r(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"==i(e.name))).map((e=>e.name.slice(0,-4))),...h.keys(),...d]);if($)for(const e of a)d.add(e);else for(const e of a){const r=h.get(e);for(const e of w)r.add(e)}}return await Promise.all([...d].map((async s=>{await m(r(e,s),{withFileTypes:!0}).then((async m=>{await Promise.all(m.map((async m=>{const g=i(m.name);if(m.isFile()&&a.includes(g)){const i=t(m.name,g),a=r(e,s,m.name),{srcLength:h,script:d}=await o(await l(a,{encoding:"utf-8"}),{minify:u,scriptUser:s,scriptName:i,filePath:a,mangleNames:b}),w={file:`${s}/${m.name}`,users:[s],minLength:n(d),error:void 0,srcLength:h};j.get(s).add(i),S.push(w),await p(r(c,s,`scripts/${i}.js`),d),f(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...h].map((async([i,t])=>{d.has(i)||await Promise.all([...t].map((async t=>{let s,m,g;for(const o of a)try{m=`${t}${o}`,s=await l(g=r(e,i,m),{encoding:"utf-8"});break}catch{}if(s){const{srcLength:e,script:a}=await o(s,{minify:u,scriptUser:i,scriptName:t,filePath:g,mangleNames:b}),l={file:`${i}/${m}`,users:[i],minLength:n(a),error:void 0,srcLength:e};S.push(l),await p(r(c,i,"scripts",`${t}.js`),a),f(l)}else y.get(t).add(i)})))}))),await(d.size?Promise.all((P||await m(r(e),{withFileTypes:!0})).map((async s=>{const m=i(s.name);if(!s.isFile()||!a.includes(m))return;const g=t(s.name,m),h=[...d,...y.get(g)].filter((e=>!j.get(e).has(g)));if(!h.length)return;const w=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),$=r(e,s.name),{srcLength:P,script:L}=await o(await l($,{encoding:"utf-8"}),{minify:u,scriptUser:!0,scriptName:g,uniqueID:w,filePath:$,mangleNames:b}),N={file:s.name,users:h,minLength:n(L),error:void 0,srcLength:P};await Promise.all(h.map((e=>p(r(c,e,`scripts/${g}.js`),L.replace(new RegExp(`$${w}$SCRIPT_USER`,"g"),e).replace(new RegExp(`$${w}$FULL_SCRIPT_NAME`,"g"),`${e}.${g}`))))),S.push(N),f(N)}))):Promise.all([...y].map((async([i,t])=>{let s,m,g;for(const t of a)try{m=`${i}${t}`,s=await l(g=r(e,m),{encoding:"utf-8"});break}catch{}if(s){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:a,script:l}=await o(s,{minify:u,scriptUser:!0,scriptName:i,uniqueID:e,filePath:g,mangleNames:b}),h={file:m,users:[...t],minLength:n(l),error:void 0,srcLength:a};await Promise.all([...t].map((t=>p(r(c,t,`scripts/${i}.js`),l.replace(new RegExp(`$${e}$SCRIPT_USER`,"g"),t).replace(new RegExp(`$${e}$FULL_SCRIPT_NAME`,"g"),`${t}.${i}`))))),S.push(h),f(h)}})))),S}export{push as default,push};
|
package/watch.d.ts
CHANGED
@@ -1,4 +1,13 @@
|
|
1
|
-
import {
|
1
|
+
import { LaxPartial } from "@samual/lib";
|
2
|
+
import { PushOptions } from "./push";
|
3
|
+
export declare type WatchOptions = PushOptions & {
|
4
|
+
/**
|
5
|
+
* if provided, will write typescript type declarations for all the scripts on every change detected
|
6
|
+
*
|
7
|
+
* writing the type declarations enables interscript type checking and autocompletetes for the args
|
8
|
+
*/
|
9
|
+
typeDeclarationPath: string;
|
10
|
+
};
|
2
11
|
/**
|
3
12
|
* Watches target file or folder for updates and builds and pushes updated file.
|
4
13
|
*
|
@@ -8,7 +17,5 @@ import { Info } from ".";
|
|
8
17
|
* @param scripts to push from (pushes from all if empty)
|
9
18
|
* @param onPush function that's called on each script push
|
10
19
|
*/
|
11
|
-
export declare function watch(sourceDirectory: string, hackmudDirectory: string,
|
12
|
-
genTypes?: string | undefined;
|
13
|
-
}): void;
|
20
|
+
export declare function watch(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames, typeDeclarationPath }?: LaxPartial<WatchOptions>): void;
|
14
21
|
export default watch;
|
package/watch.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import{watch as
|
1
|
+
import{watch as r}from"chokidar";import o from"fs";import{extname as t,basename as i,resolve as e}from"path";import{s}from"./processScript/transform.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"./processScript/minify.js";import"@babel/traverse";import"@babel/types";import"./processScript/shared.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./spliceString-2c6f214f.js";import"./processScript/preprocess.js";import"acorn";import"terser";const{readFile:u,readdir:g}=o.promises;function watch(o,f,{scripts:b=["*.*"],onPush:d,minify:h=!0,mangleNames:w=!1,typeDeclarationPath:y}={}){if(!b.length)throw new Error("scripts option was an empty array");const j=new n((r=>new Set)),S=new Set,L=new Set;let v=!1;for(const r of b){const[o,t]=r.split(".");o&&"*"!=o?t&&"*"!=t?j.get(t).add(o):S.add(o):t&&"*"!=t?L.add(t):v=!0}const F=r("",{depth:1,cwd:o,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async r=>{const p=t(r);if(!s.includes(p))return;const b=i(r,p);if(r==i(r)){if(!(v||S.size||L.has(b)||j.has(b)))return;const p=new n((r=>[]));await Promise.all((await g(o,{withFileTypes:!0})).map((async r=>{if(r.isDirectory())for(const a of await g(e(o,r.name),{withFileTypes:!0})){if(!a.isFile())continue;const o=t(a.name);s.includes(o)&&p.get(i(a.name,o)).push(r.name)}})));const y=new Set;if(v||L.has(b)){for(const r of await g(e(o),{withFileTypes:!0}))r.isDirectory()&&y.add(r.name);for(const r of await g(e(f),{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 j.values())for(const o of r)y.add(o)}for(const r of S)y.add(r);for(const r of j.get(b))y.add(r);const F=[...y].filter((r=>!p.has(r)));if(!F.length)return void(null==d||d({file:r,users:[],srcLength:0,minLength:0,error:new Error("no users to push to")}));const $=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),P=e(o,r);let E,T;try{({srcLength:E,script:T}=await a(await u(P,{encoding:"utf-8"}),{minify:h,scriptUser:!0,scriptName:b,uniqueID:$,filePath:P,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==d||d({file:r,users:[],srcLength:0,minLength:0,error:o}))}return await Promise.all(F.map((r=>l(e(f,r,`scripts/${b}.js`),T.replace(new RegExp(`$${$}$SCRIPT_USER`,"g"),r).replace(new RegExp(`$${$}$FULL_SCRIPT_NAME`,"g"),`${r}.${b}`))))),void(null==d||d({file:r,users:F,minLength:m(T),error:void 0,srcLength:E}))}const y=i(e(r,".."));if(!(v||S.size||L.has(b)||j.get(b).has(y)))return;const F=e(o,r),$=await u(F,{encoding:"utf-8"});let P,E;try{({srcLength:P,script:E}=await a($,{minify:h,scriptUser:y,scriptName:b,filePath:F,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==d||d({file:r,users:[],srcLength:0,minLength:0,error:o}))}await l(e(f,y,"scripts",`${b}.js`),E),null==d||d({file:r,users:[y],srcLength:P,minLength:m(E),error:void 0})}));y&&(p(o,e(o,y),f),F.on("add",(()=>p(o,e(o,y),f))),F.on("unlink",(()=>p(o,e(o,y),f))))}export{watch as default,watch};
|
@@ -0,0 +1 @@
|
|
1
|
+
import e from"fs";import{dirname as r}from"path";class DynamicMap extends Map{constructor(e){super(),this.fallbackHandler=e}get(e){if(super.has(e))return super.get(e);const r=this.fallbackHandler(e);return super.set(e,r),r}}const{writeFile:t,mkdir:s}=e.promises;function writeFilePersistent(e,a,i){return t(e,a,i).catch((async n=>{if("ENOENT"!=n.code)throw n;await s(r(e),{recursive:!0}),await t(e,a,i)}))}export{DynamicMap as D,writeFilePersistent as w};
|