-
Notifications
You must be signed in to change notification settings - Fork 0
/
hizzy.min.js
37 lines (32 loc) · 10.7 KB
/
hizzy.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env node
const random=()=>crypto.getRandomValues(new Uint32Array([0]))[0].toString(36),self=module.exports={defineConfig:e=>e},sT=Date.now(),fs=(global.__sT__=sT,global.__PRODUCT__="hizzy",global.__PRODUCT_U__="Hizzy",global.__VERSION__=require("./package.json").version,require("fs")),dotenv=require("dotenv"),path=require("path"),os=require("os"),url=require("url"),argv=process["argv"],exit=(require("fancy-printer").makeGlobal(!0),dotenv.config(),(...e)=>{printer.dev.error(...e),process.exit(1)}),checkDefault=(printer.title(__PRODUCT_U__+" v"+__VERSION__),printer.makeGlobal(!0).setOptions({format:e=>printer.css("color: "+printer.getTag(e.tag||"log").c)+" %tag %time %stack > %text",timeBackgroundColor:"",timeColor:"",stackColor:"",filenameColor:"",lineColor:"",columnColor:"",timePadding:0,tagPadding:0,styleSubstitutionsEnabled:!0}),printer.dev=printer.create({format:e=>printer.css("color: "+printer.getTag(e.tag||"log").c)+" %tag %text",tagPadding:0,styleSubstitutionsEnabled:!0}),printer.tags=printer.dev.tags={pass:{text:"✓",c:"greenBright",textColor:"green"},fail:{text:"X",c:"redBright",textColor:"redBright"},error:{text:"",c:"red",textColor:"red"},warn:{text:"✩",c:"yellow",textColor:"yellow"},info:{text:"?",c:"blueBright",textColor:"blue"},debug:{text:"~",c:"gray",textColor:"gray"},notice:{text:"!",c:"cyanBright",textColor:"cyan"},log:{text:'"',c:"gray",textColor:"white"},assert:{text:">",c:"white",textColor:"gray"}},printer.inline.options.format="%text",Object.keys(printer.styles).forEach(e=>{"t"!==e&&(delete printer.styles[e],delete printer.dev.styles[e])}),(e,r={},o=[])=>{var t,i=[];for(const n in r)void 0===e[n]?(e[n]=r[n],i.push([...o,n])):e[n].constructor===Object&&"addons"!==n&&"static"!==n&&(t=checkDefault(e[n],r[n],[...o,n]),i.push(...t));return i}),propExpect=(e,r,o)=>exit("The config file %c"+__PRODUCT__+".json%c's %c"+e+"%c property was expected as: %c"+r+"%c, got:%c","color: orange","color: red","color: orange","color: red","color: orange","color: red","color: orange",o),isTerminal=require.main===module;isTerminal||exit(__PRODUCT_U__+"'s module mode has not been developed yet. Its API can still be reached by importing/requiring '"+__PRODUCT__+"/api'.");let dir=process.cwd(),file;const args=argv.slice(2).filter(e=>!e.startsWith("-")),optList=argv.slice(2).filter(e=>e.startsWith("-")),_argv_={},shortcuts={"-h":"help","-v":"version","-b":"build","-p":"port","-d":"dev","-o":"open","-c":"config","-f":"force"};if(optList.forEach(e=>{e=e.toLowerCase();e=(e=shortcuts[e]?"--"+shortcuts[e]:e).substring(2).split("=");_argv_[e[0]]=e[1]&&e.slice(1).join("=")||!0}),Object.freeze(_argv_),self.args=_argv_,isTerminal&&_argv_.help&&(printer.raw.log("%c "+__PRODUCT_U__+" v"+__VERSION__,"color: yellow"),printer.println(""),printer.raw.log("%c Usage: "+__PRODUCT__+" [root]","color: magenta"),printer.println(""),printer.raw.log("%c Options:","color: orange"),printer.raw.log("%c -h, --help%c shows this page","color: green","color: yellow"),printer.raw.log("%c -v, --version%c shows the version","color: green","color: yellow"),printer.raw.log("%c --advanced-version%c shows advanced information","color: green","color: yellow"),printer.raw.log("%c -b, --build%c only builds the project and exits","color: green","color: yellow"),printer.raw.log("%c --host%c toggles the view of IPv4","color: green","color: yellow"),printer.raw.log("%c --config=PATH%c sets the config file's path","color: green","color: yellow"),printer.raw.log("%c -p=PORT, --port=PORT%c sets the port (0 = random)","color: green","color: yellow"),printer.raw.log("%c -f, --force%c forces auto build","color: green","color: yellow"),printer.raw.log("%c -d, --dev%c enables developer mode","color: green","color: yellow"),printer.raw.log("%c -o, --open%c opens the app on start","color: green","color: yellow"),printer.raw.log("%c --debug%c enables debug messages","color: green","color: yellow"),printer.raw.log("%c --debug-socket%c sends debug messages of sockets","color: green","color: yellow"),printer.raw.log("%c --injections%c builds html/jsx injection files","color: green","color: yellow"),printer.raw.log("%c --addon-init%c initializes up an addon environment","color: green","color: yellow"),printer.raw.log("%c --no-clear%c disables the initial screen clear","color: green","color: yellow"),process.exit()),isTerminal&&_argv_.version&&(printer.raw.log(__PRODUCT_U__+" v"+__VERSION__),process.exit()),isTerminal&&_argv_["advanced-version"]&&(printer.raw.log(`${__PRODUCT__}: v${__VERSION__}
node: ${process.version}
device: ${os.platform()}-`+os.arch()),process.exit()),isTerminal&&_argv_["addon-init"]){const t=args[0]||process.cwd().split(path.sep).slice(-1)[0],u=path.join(process.cwd(),args[0]||"");/^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(t)||exit("Please select a valid addon name!"),fs.existsSync(u)&&exit("There is already a directory at '%c"+u+"&t'!","color: orange"),fs.mkdirSync(u),fs.writeFileSync(path.join(u,"index.js"),`const {AddonModule} = Hizzy;
module.exports = class MyAddon extends AddonModule {
onLoad() {
this.log("Loaded!");
};
onEnable() {
this.log("Enabled!");
};
onDisable(reason) {
this.log("Disabled for the reason:", reason);
}
onClientSideLoad() {
this.log("Addon has been loaded in client side!");
};
onClientSideRendered() {
this.log("A page has been rendered in the client side!");
};
onClientSideError(error) {
this.log("An error occurred in the client side:", error);
};
};`),fs.writeFileSync(path.join(u,"package.json"),`{
"name": ${JSON.stringify(t)},
"description": "This is an addon!",
"version": "1.0.0",
"main": "index.js"
}`),printer.dev.pass("A new addon has been set up at '%c"+u+"&t'!","color: orange"),process.exit()}if(_argv_.build||_argv_["no-clear"]||(printer.clear(),printer.print("\n")),isTerminal&&args[0]){const v=path.join(process.cwd(),args[0]);fs.existsSync(v)||exit("Couldn't open the file %c'"+v+"'%c.","color: orange","color: red"),dir=fs.statSync(v).isDirectory()?v:(file=v,path.dirname(v))}(async()=>{var e={dev:!0,port:1881,fileRefresh:!0,autoBuild:!0,listen:!0,main:"Server.jsx",mainModule:!0,checkConfig:!0,realtime:!0,static:{},https:!1,srcFolder:"src",connectionTimeout:6e4,keepaliveTimeout:3e4,clientKeepalive:2e4,minClientKeepalive:8e3,addons:[],includeOriginalInBuild:!0,cache:{addons:0,npm:0,preact:0,"preact-hooks":0,static:{}}};let r=_argv_.config;if(r&&!fs.existsSync(path.join(dir,r)))return exit("Config file %c"+r+"&t given in the command line arguments is invalid:","color: orange");if(!r)for(const c of["json","config.json","config.ts","config.js","config.mts","config.mjs"])if(r=__PRODUCT__+"."+c,fs.existsSync(path.join(dir,r)))break;var o=path.join(dir,r),t=fs.existsSync(o);t&&fs.statSync(o).isFile()||(t&&fs.rmSync(o),_argv_.debug&&printer.dev.debug("Creating the %c/"+r+"&t file...","color: orange"),fs.writeFileSync(o,"export default Hizzy.defineConfig({});"));let i;if(r.endsWith(".json"))try{i=JSON.parse(fs.readFileSync(o,"utf8"))}catch(e){return exit("Invalid JSON in the file %c'"+o+"'%c: %c"+e.toString()+"%c.","color: orange","color: red","color: orange","color: red")}else if(r.endsWith(".js")||r.endsWith(".mjs")||r.endsWith(".ts")||r.endsWith(".mts"))if(global[__PRODUCT_U__]={defineConfig:e=>e},r.endsWith(".js")||r.endsWith(".mjs"))i=(await import(url.pathToFileURL(o))).default;else{t=path.join(path.dirname(o),random()+"."+(r.endsWith(".mjs")?"m":"")+"js");fs.writeFileSync(t,require("@babel/core").transformSync(fs.readFileSync(o),{filename:path.basename(o),presets:[require("@babel/preset-typescript")]}).code);try{i=(await import(url.pathToFileURL(o))).default}finally{fs.rmSync(t)}}"function"==typeof i&&await i({argv:_argv_,isDev:_argv_.dev});var t=i.checkConfig,n=checkDefault(i,e);if(!_argv_.build&&n.length&&t&&r.endsWith(".json")&&(fs.writeFileSync(o,JSON.stringify(i,null,2)),printer.dev.warn("Updated following properties in "+__PRODUCT__+".json: "+n.map(e=>e.join("->")).join(", "))),Array.isArray(i.extensionRemovals)||(i.extensionRemovals=e.extensionRemovals),i.extensionRemovals=[...new Set(i.extensionRemovals)],-1!==i.keepaliveTimeout&&i.clientKeepalive>=i.keepaliveTimeout)return exit("Config's 'clientKeepalive' property has to be smaller than 'keepaliveTimeout'.");if(Array.isArray(i.static)){t=i.static;i.static={};for(const d of t)i.static[d]=d}Object.freeze(i),self.config=i,_argv_.debug||(printer.options.disabledTags.push("debug"),printer.dev.options.disabledTags.push("debug"));o=fs.existsSync(path.join(dir,".build")),n=path.join(dir,i.srcFolder),e=fs.existsSync(n),e&&fs.statSync(n).isDirectory()||(o?printer.dev.debug("Skipping the creation of %c/"+i.srcFolder+"&t because there is an existing build.","color: orange"):(e&&fs.rmSync(n),printer.dev.debug("Creating the %c/"+i.srcFolder+"&t folder...","color: orange"),fs.mkdirSync(n),fs.writeFileSync(path.join(n,"App.jsx"),`const foo = 20;
export default <div>Hello, world! { foo * 2 }</div>`))),self.config=i,t=path.join(__dirname,"api.js"),o=path.join(__dirname,"api.min.js"),global[__PRODUCT_U__]=new(require(fs.existsSync(t)?t:o))(dir),i.fileRefresh&&(Hizzy.autoRefresh=!0),e=path.join(dir,i.srcFolder,i.main),n=path.extname(e);if(fs.existsSync(e)||(printer.dev.debug("Creating the %c/src/"+i.main+"&t file...","color: orange"),fs.writeFileSync(e,{".jsx":`export default <Routes>
<Route path="/" route="./App.jsx"/>
</Routes>;`}[n])),_argv_.build)_argv_["just-build"]=!0,Hizzy.build().then(()=>process.exit());else{var s=e=>null===e?"null":e&&e.constructor===Array?"array":typeof e;if("object"!=typeof i.addons)return exit("Config's 'conf.addons' property has to be an object or an array, got: "+s(i.addons)+".");if(0<Object.keys(i.addons).length){var a=i.addons;if(Array.isArray(a))for(let e=0;e<a.length;e++){var l=a[e];if("string"==typeof l)await Hizzy.Addon.create(l,{});else{if(!Array.isArray(l))return exit("Config's 'conf.addons["+e+"]' property should either be an array or a string, got: "+s(k));if(l[1]&&l[1].constructor!==Object)return exit("Config's 'conf.addons["+e+"][1]' property should be an object or empty, got: "+s(l[1]));await Hizzy.Addon.create(l[0],l[1])}}else for(const k in a){if(a[k].constructor!==Object)return exit("Config's 'conf.addons["+k+"] property should be an object, got: "+s(a[k]));await Hizzy.Addon.create(k,a[k])}}await Hizzy.init(),(_argv_.dev||i.dev)&&(Hizzy.dev=!0,await Hizzy.processMain(Hizzy.jsxToJS(fs.readFileSync(e),n))),i.realtime&&Hizzy.enableRealtime(),Hizzy.dev?i.listen&&Hizzy.listen().then(e=>e):_argv_.build||i.autoBuild||_argv_.force?Hizzy.build().then(e=>e):i.listen&&Hizzy.scanBuild().then(e=>e)}})();