UNPKG

98.4 kBJavaScriptView Raw
1/*!
2 Stencil Dev Server Process v2.18.0 | MIT Licensed | https://stenciljs.com
3 */
4'use strict';
5
6const fs$1 = require('../sys/node/graceful-fs.js');
7const path = require('path');
8const util = require('util');
9const zlib = require('zlib');
10const buffer = require('buffer');
11const openInEditorApi = require('./open-in-editor-api.js');
12const http = require('http');
13const https = require('https');
14const net = require('net');
15const index_js = require('../sys/node/index.js');
16const ws = require('./ws.js');
17const childProcess = require('child_process');
18const fs$2 = require('fs');
19const os = require('os');
20
21function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
22
23function _interopNamespace(e) {
24 if (e && e.__esModule) return e;
25 var n = Object.create(null);
26 if (e) {
27 Object.keys(e).forEach(function (k) {
28 if (k !== 'default') {
29 var d = Object.getOwnPropertyDescriptor(e, k);
30 Object.defineProperty(n, k, d.get ? d : {
31 enumerable: true,
32 get: function () {
33 return e[k];
34 }
35 });
36 }
37 });
38 }
39 n['default'] = e;
40 return Object.freeze(n);
41}
42
43const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
44const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
45const util__default = /*#__PURE__*/_interopDefaultLegacy(util);
46const zlib__namespace = /*#__PURE__*/_interopNamespace(zlib);
47const openInEditorApi__default = /*#__PURE__*/_interopDefaultLegacy(openInEditorApi);
48const http__namespace = /*#__PURE__*/_interopNamespace(http);
49const https__namespace = /*#__PURE__*/_interopNamespace(https);
50const net__namespace = /*#__PURE__*/_interopNamespace(net);
51const ws__namespace = /*#__PURE__*/_interopNamespace(ws);
52const childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
53const fs__default$1 = /*#__PURE__*/_interopDefaultLegacy(fs$2);
54const os__default = /*#__PURE__*/_interopDefaultLegacy(os);
55
56const DEV_SERVER_URL = '/~dev-server';
57const DEV_MODULE_URL = '/~dev-module';
58const DEV_SERVER_INIT_URL = `${DEV_SERVER_URL}-init`;
59const OPEN_IN_EDITOR_URL = `${DEV_SERVER_URL}-open-in-editor`;
60
61const contentTypes = {"123":"application/vnd.lotus-1-2-3","1km":"application/vnd.1000minds.decision-model+xml","3dml":"text/vnd.in3d.3dml","3ds":"image/x-3ds","3g2":"video/3gpp2","3gp":"video/3gpp","3gpp":"video/3gpp","3mf":"model/3mf","7z":"application/x-7z-compressed","aab":"application/x-authorware-bin","aac":"audio/x-aac","aam":"application/x-authorware-map","aas":"application/x-authorware-seg","abw":"application/x-abiword","ac":"application/vnd.nokia.n-gage.ac+xml","acc":"application/vnd.americandynamics.acc","ace":"application/x-ace-compressed","acu":"application/vnd.acucobol","acutc":"application/vnd.acucorp","adp":"audio/adpcm","aep":"application/vnd.audiograph","afm":"application/x-font-type1","afp":"application/vnd.ibm.modcap","age":"application/vnd.age","ahead":"application/vnd.ahead.space","ai":"application/postscript","aif":"audio/x-aiff","aifc":"audio/x-aiff","aiff":"audio/x-aiff","air":"application/vnd.adobe.air-application-installer-package+zip","ait":"application/vnd.dvb.ait","ami":"application/vnd.amiga.ami","amr":"audio/amr","apk":"application/vnd.android.package-archive","apng":"image/apng","appcache":"text/cache-manifest","application":"application/x-ms-application","apr":"application/vnd.lotus-approach","arc":"application/x-freearc","arj":"application/x-arj","asc":"application/pgp-signature","asf":"video/x-ms-asf","asm":"text/x-asm","aso":"application/vnd.accpac.simply.aso","asx":"video/x-ms-asf","atc":"application/vnd.acucorp","atom":"application/atom+xml","atomcat":"application/atomcat+xml","atomdeleted":"application/atomdeleted+xml","atomsvc":"application/atomsvc+xml","atx":"application/vnd.antix.game-component","au":"audio/basic","avci":"image/avci","avcs":"image/avcs","avi":"video/x-msvideo","avif":"image/avif","aw":"application/applixware","azf":"application/vnd.airzip.filesecure.azf","azs":"application/vnd.airzip.filesecure.azs","azv":"image/vnd.airzip.accelerator.azv","azw":"application/vnd.amazon.ebook","b16":"image/vnd.pco.b16","bat":"application/x-msdownload","bcpio":"application/x-bcpio","bdf":"application/x-font-bdf","bdm":"application/vnd.syncml.dm+wbxml","bdoc":"application/x-bdoc","bed":"application/vnd.realvnc.bed","bh2":"application/vnd.fujitsu.oasysprs","bin":"application/octet-stream","blb":"application/x-blorb","blorb":"application/x-blorb","bmi":"application/vnd.bmi","bmml":"application/vnd.balsamiq.bmml+xml","bmp":"image/x-ms-bmp","book":"application/vnd.framemaker","box":"application/vnd.previewsystems.box","boz":"application/x-bzip2","bpk":"application/octet-stream","bsp":"model/vnd.valve.source.compiled-map","btif":"image/prs.btif","buffer":"application/octet-stream","bz":"application/x-bzip","bz2":"application/x-bzip2","c":"text/x-c","c11amc":"application/vnd.cluetrust.cartomobile-config","c11amz":"application/vnd.cluetrust.cartomobile-config-pkg","c4d":"application/vnd.clonk.c4group","c4f":"application/vnd.clonk.c4group","c4g":"application/vnd.clonk.c4group","c4p":"application/vnd.clonk.c4group","c4u":"application/vnd.clonk.c4group","cab":"application/vnd.ms-cab-compressed","caf":"audio/x-caf","cap":"application/vnd.tcpdump.pcap","car":"application/vnd.curl.car","cat":"application/vnd.ms-pki.seccat","cb7":"application/x-cbr","cba":"application/x-cbr","cbr":"application/x-cbr","cbt":"application/x-cbr","cbz":"application/x-cbr","cc":"text/x-c","cco":"application/x-cocoa","cct":"application/x-director","ccxml":"application/ccxml+xml","cdbcmsg":"application/vnd.contact.cmsg","cdf":"application/x-netcdf","cdfx":"application/cdfx+xml","cdkey":"application/vnd.mediastation.cdkey","cdmia":"application/cdmi-capability","cdmic":"application/cdmi-container","cdmid":"application/cdmi-domain","cdmio":"application/cdmi-object","cdmiq":"application/cdmi-queue","cdx":"chemical/x-cdx","cdxml":"application/vnd.chemdraw+xml","cdy":"application/vnd.cinderella","cer":"application/pkix-cert","cfs":"application/x-cfs-compressed","cgm":"image/cgm","chat":"application/x-chat","chm":"application/vnd.ms-htmlhelp","chrt":"application/vnd.kde.kchart","cif":"chemical/x-cif","cii":"application/vnd.anser-web-certificate-issue-initiation","cil":"application/vnd.ms-artgalry","cjs":"application/node","cla":"application/vnd.claymore","class":"application/java-vm","clkk":"application/vnd.crick.clicker.keyboard","clkp":"application/vnd.crick.clicker.palette","clkt":"application/vnd.crick.clicker.template","clkw":"application/vnd.crick.clicker.wordbank","clkx":"application/vnd.crick.clicker","clp":"application/x-msclip","cmc":"application/vnd.cosmocaller","cmdf":"chemical/x-cmdf","cml":"chemical/x-cml","cmp":"application/vnd.yellowriver-custom-menu","cmx":"image/x-cmx","cod":"application/vnd.rim.cod","coffee":"text/coffeescript","com":"application/x-msdownload","conf":"text/plain","cpio":"application/x-cpio","cpl":"application/cpl+xml","cpp":"text/x-c","cpt":"application/mac-compactpro","crd":"application/x-mscardfile","crl":"application/pkix-crl","crt":"application/x-x509-ca-cert","crx":"application/x-chrome-extension","cryptonote":"application/vnd.rig.cryptonote","csh":"application/x-csh","csl":"application/vnd.citationstyles.style+xml","csml":"chemical/x-csml","csp":"application/vnd.commonspace","css":"text/css","cst":"application/x-director","csv":"text/csv","cu":"application/cu-seeme","curl":"text/vnd.curl","cww":"application/prs.cww","cxt":"application/x-director","cxx":"text/x-c","dae":"model/vnd.collada+xml","daf":"application/vnd.mobius.daf","dart":"application/vnd.dart","dataless":"application/vnd.fdsn.seed","davmount":"application/davmount+xml","dbf":"application/vnd.dbf","dbk":"application/docbook+xml","dcr":"application/x-director","dcurl":"text/vnd.curl.dcurl","dd2":"application/vnd.oma.dd2+xml","ddd":"application/vnd.fujixerox.ddd","ddf":"application/vnd.syncml.dmddf+xml","dds":"image/vnd.ms-dds","deb":"application/x-debian-package","def":"text/plain","deploy":"application/octet-stream","der":"application/x-x509-ca-cert","dfac":"application/vnd.dreamfactory","dgc":"application/x-dgc-compressed","dic":"text/x-c","dir":"application/x-director","dis":"application/vnd.mobius.dis","disposition-notification":"message/disposition-notification","dist":"application/octet-stream","distz":"application/octet-stream","djv":"image/vnd.djvu","djvu":"image/vnd.djvu","dll":"application/x-msdownload","dmg":"application/x-apple-diskimage","dmp":"application/vnd.tcpdump.pcap","dms":"application/octet-stream","dna":"application/vnd.dna","doc":"application/msword","docm":"application/vnd.ms-word.document.macroenabled.12","docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","dot":"application/msword","dotm":"application/vnd.ms-word.template.macroenabled.12","dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template","dp":"application/vnd.osgi.dp","dpg":"application/vnd.dpgraph","dra":"audio/vnd.dra","drle":"image/dicom-rle","dsc":"text/prs.lines.tag","dssc":"application/dssc+der","dtb":"application/x-dtbook+xml","dtd":"application/xml-dtd","dts":"audio/vnd.dts","dtshd":"audio/vnd.dts.hd","dump":"application/octet-stream","dvb":"video/vnd.dvb.file","dvi":"application/x-dvi","dwd":"application/atsc-dwd+xml","dwf":"model/vnd.dwf","dwg":"image/vnd.dwg","dxf":"image/vnd.dxf","dxp":"application/vnd.spotfire.dxp","dxr":"application/x-director","ear":"application/java-archive","ecelp4800":"audio/vnd.nuera.ecelp4800","ecelp7470":"audio/vnd.nuera.ecelp7470","ecelp9600":"audio/vnd.nuera.ecelp9600","ecma":"application/ecmascript","edm":"application/vnd.novadigm.edm","edx":"application/vnd.novadigm.edx","efif":"application/vnd.picsel","ei6":"application/vnd.pg.osasli","elc":"application/octet-stream","emf":"image/emf","eml":"message/rfc822","emma":"application/emma+xml","emotionml":"application/emotionml+xml","emz":"application/x-msmetafile","eol":"audio/vnd.digital-winds","eot":"application/vnd.ms-fontobject","eps":"application/postscript","epub":"application/epub+zip","es":"application/ecmascript","es3":"application/vnd.eszigno3+xml","esa":"application/vnd.osgi.subsystem","esf":"application/vnd.epson.esf","et3":"application/vnd.eszigno3+xml","etx":"text/x-setext","eva":"application/x-eva","evy":"application/x-envoy","exe":"application/x-msdownload","exi":"application/exi","exp":"application/express","exr":"image/aces","ext":"application/vnd.novadigm.ext","ez":"application/andrew-inset","ez2":"application/vnd.ezpix-album","ez3":"application/vnd.ezpix-package","f":"text/x-fortran","f4v":"video/x-f4v","f77":"text/x-fortran","f90":"text/x-fortran","fbs":"image/vnd.fastbidsheet","fcdt":"application/vnd.adobe.formscentral.fcdt","fcs":"application/vnd.isac.fcs","fdf":"application/vnd.fdf","fdt":"application/fdt+xml","fe_launch":"application/vnd.denovo.fcselayout-link","fg5":"application/vnd.fujitsu.oasysgp","fgd":"application/x-director","fh":"image/x-freehand","fh4":"image/x-freehand","fh5":"image/x-freehand","fh7":"image/x-freehand","fhc":"image/x-freehand","fig":"application/x-xfig","fits":"image/fits","flac":"audio/x-flac","fli":"video/x-fli","flo":"application/vnd.micrografx.flo","flv":"video/x-flv","flw":"application/vnd.kde.kivio","flx":"text/vnd.fmi.flexstor","fly":"text/vnd.fly","fm":"application/vnd.framemaker","fnc":"application/vnd.frogans.fnc","fo":"application/vnd.software602.filler.form+xml","for":"text/x-fortran","fpx":"image/vnd.fpx","frame":"application/vnd.framemaker","fsc":"application/vnd.fsc.weblaunch","fst":"image/vnd.fst","ftc":"application/vnd.fluxtime.clip","fti":"application/vnd.anser-web-funds-transfer-initiation","fvt":"video/vnd.fvt","fxp":"application/vnd.adobe.fxp","fxpl":"application/vnd.adobe.fxp","fzs":"application/vnd.fuzzysheet","g2w":"application/vnd.geoplan","g3":"image/g3fax","g3w":"application/vnd.geospace","gac":"application/vnd.groove-account","gam":"application/x-tads","gbr":"application/rpki-ghostbusters","gca":"application/x-gca-compressed","gdl":"model/vnd.gdl","gdoc":"application/vnd.google-apps.document","ged":"text/vnd.familysearch.gedcom","geo":"application/vnd.dynageo","geojson":"application/geo+json","gex":"application/vnd.geometry-explorer","ggb":"application/vnd.geogebra.file","ggt":"application/vnd.geogebra.tool","ghf":"application/vnd.groove-help","gif":"image/gif","gim":"application/vnd.groove-identity-message","glb":"model/gltf-binary","gltf":"model/gltf+json","gml":"application/gml+xml","gmx":"application/vnd.gmx","gnumeric":"application/x-gnumeric","gph":"application/vnd.flographit","gpx":"application/gpx+xml","gqf":"application/vnd.grafeq","gqs":"application/vnd.grafeq","gram":"application/srgs","gramps":"application/x-gramps-xml","gre":"application/vnd.geometry-explorer","grv":"application/vnd.groove-injector","grxml":"application/srgs+xml","gsf":"application/x-font-ghostscript","gsheet":"application/vnd.google-apps.spreadsheet","gslides":"application/vnd.google-apps.presentation","gtar":"application/x-gtar","gtm":"application/vnd.groove-tool-message","gtw":"model/vnd.gtw","gv":"text/vnd.graphviz","gxf":"application/gxf","gxt":"application/vnd.geonext","gz":"application/gzip","h":"text/x-c","h261":"video/h261","h263":"video/h263","h264":"video/h264","hal":"application/vnd.hal+xml","hbci":"application/vnd.hbci","hbs":"text/x-handlebars-template","hdd":"application/x-virtualbox-hdd","hdf":"application/x-hdf","heic":"image/heic","heics":"image/heic-sequence","heif":"image/heif","heifs":"image/heif-sequence","hej2":"image/hej2k","held":"application/atsc-held+xml","hh":"text/x-c","hjson":"application/hjson","hlp":"application/winhlp","hpgl":"application/vnd.hp-hpgl","hpid":"application/vnd.hp-hpid","hps":"application/vnd.hp-hps","hqx":"application/mac-binhex40","hsj2":"image/hsj2","htc":"text/x-component","htke":"application/vnd.kenameaapp","htm":"text/html","html":"text/html","hvd":"application/vnd.yamaha.hv-dic","hvp":"application/vnd.yamaha.hv-voice","hvs":"application/vnd.yamaha.hv-script","i2g":"application/vnd.intergeo","icc":"application/vnd.iccprofile","ice":"x-conference/x-cooltalk","icm":"application/vnd.iccprofile","ico":"image/x-icon","ics":"text/calendar","ief":"image/ief","ifb":"text/calendar","ifm":"application/vnd.shana.informed.formdata","iges":"model/iges","igl":"application/vnd.igloader","igm":"application/vnd.insors.igm","igs":"model/iges","igx":"application/vnd.micrografx.igx","iif":"application/vnd.shana.informed.interchange","img":"application/octet-stream","imp":"application/vnd.accpac.simply.imp","ims":"application/vnd.ms-ims","in":"text/plain","ini":"text/plain","ink":"application/inkml+xml","inkml":"application/inkml+xml","install":"application/x-install-instructions","iota":"application/vnd.astraea-software.iota","ipfix":"application/ipfix","ipk":"application/vnd.shana.informed.package","irm":"application/vnd.ibm.rights-management","irp":"application/vnd.irepository.package+xml","iso":"application/x-iso9660-image","itp":"application/vnd.shana.informed.formtemplate","its":"application/its+xml","ivp":"application/vnd.immervision-ivp","ivu":"application/vnd.immervision-ivu","jad":"text/vnd.sun.j2me.app-descriptor","jade":"text/jade","jam":"application/vnd.jam","jar":"application/java-archive","jardiff":"application/x-java-archive-diff","java":"text/x-java-source","jhc":"image/jphc","jisp":"application/vnd.jisp","jls":"image/jls","jlt":"application/vnd.hp-jlyt","jng":"image/x-jng","jnlp":"application/x-java-jnlp-file","joda":"application/vnd.joost.joda-archive","jp2":"image/jp2","jpe":"image/jpeg","jpeg":"image/jpeg","jpf":"image/jpx","jpg":"image/jpeg","jpg2":"image/jp2","jpgm":"video/jpm","jpgv":"video/jpeg","jph":"image/jph","jpm":"video/jpm","jpx":"image/jpx","js":"application/javascript","json":"application/json","json5":"application/json5","jsonld":"application/ld+json","jsonml":"application/jsonml+json","jsx":"text/jsx","jxr":"image/jxr","jxra":"image/jxra","jxrs":"image/jxrs","jxs":"image/jxs","jxsc":"image/jxsc","jxsi":"image/jxsi","jxss":"image/jxss","kar":"audio/midi","karbon":"application/vnd.kde.karbon","kdbx":"application/x-keepass2","key":"application/x-iwork-keynote-sffkey","kfo":"application/vnd.kde.kformula","kia":"application/vnd.kidspiration","kml":"application/vnd.google-earth.kml+xml","kmz":"application/vnd.google-earth.kmz","kne":"application/vnd.kinar","knp":"application/vnd.kinar","kon":"application/vnd.kde.kontour","kpr":"application/vnd.kde.kpresenter","kpt":"application/vnd.kde.kpresenter","kpxx":"application/vnd.ds-keypoint","ksp":"application/vnd.kde.kspread","ktr":"application/vnd.kahootz","ktx":"image/ktx","ktx2":"image/ktx2","ktz":"application/vnd.kahootz","kwd":"application/vnd.kde.kword","kwt":"application/vnd.kde.kword","lasxml":"application/vnd.las.las+xml","latex":"application/x-latex","lbd":"application/vnd.llamagraphics.life-balance.desktop","lbe":"application/vnd.llamagraphics.life-balance.exchange+xml","les":"application/vnd.hhe.lesson-player","less":"text/less","lgr":"application/lgr+xml","lha":"application/x-lzh-compressed","link66":"application/vnd.route66.link66+xml","list":"text/plain","list3820":"application/vnd.ibm.modcap","listafp":"application/vnd.ibm.modcap","litcoffee":"text/coffeescript","lnk":"application/x-ms-shortcut","log":"text/plain","lostxml":"application/lost+xml","lrf":"application/octet-stream","lrm":"application/vnd.ms-lrm","ltf":"application/vnd.frogans.ltf","lua":"text/x-lua","luac":"application/x-lua-bytecode","lvp":"audio/vnd.lucent.voice","lwp":"application/vnd.lotus-wordpro","lzh":"application/x-lzh-compressed","m13":"application/x-msmediaview","m14":"application/x-msmediaview","m1v":"video/mpeg","m21":"application/mp21","m2a":"audio/mpeg","m2v":"video/mpeg","m3a":"audio/mpeg","m3u":"audio/x-mpegurl","m3u8":"application/vnd.apple.mpegurl","m4a":"audio/x-m4a","m4p":"application/mp4","m4s":"video/iso.segment","m4u":"video/vnd.mpegurl","m4v":"video/x-m4v","ma":"application/mathematica","mads":"application/mads+xml","maei":"application/mmt-aei+xml","mag":"application/vnd.ecowin.chart","maker":"application/vnd.framemaker","man":"text/troff","manifest":"text/cache-manifest","map":"application/json","mar":"application/octet-stream","markdown":"text/markdown","mathml":"application/mathml+xml","mb":"application/mathematica","mbk":"application/vnd.mobius.mbk","mbox":"application/mbox","mc1":"application/vnd.medcalcdata","mcd":"application/vnd.mcd","mcurl":"text/vnd.curl.mcurl","md":"text/markdown","mdb":"application/x-msaccess","mdi":"image/vnd.ms-modi","mdx":"text/mdx","me":"text/troff","mesh":"model/mesh","meta4":"application/metalink4+xml","metalink":"application/metalink+xml","mets":"application/mets+xml","mfm":"application/vnd.mfmp","mft":"application/rpki-manifest","mgp":"application/vnd.osgeo.mapguide.package","mgz":"application/vnd.proteus.magazine","mid":"audio/midi","midi":"audio/midi","mie":"application/x-mie","mif":"application/vnd.mif","mime":"message/rfc822","mj2":"video/mj2","mjp2":"video/mj2","mjs":"application/javascript","mk3d":"video/x-matroska","mka":"audio/x-matroska","mkd":"text/x-markdown","mks":"video/x-matroska","mkv":"video/x-matroska","mlp":"application/vnd.dolby.mlp","mmd":"application/vnd.chipnuts.karaoke-mmd","mmf":"application/vnd.smaf","mml":"text/mathml","mmr":"image/vnd.fujixerox.edmics-mmr","mng":"video/x-mng","mny":"application/x-msmoney","mobi":"application/x-mobipocket-ebook","mods":"application/mods+xml","mov":"video/quicktime","movie":"video/x-sgi-movie","mp2":"audio/mpeg","mp21":"application/mp21","mp2a":"audio/mpeg","mp3":"audio/mpeg","mp4":"video/mp4","mp4a":"audio/mp4","mp4s":"application/mp4","mp4v":"video/mp4","mpc":"application/vnd.mophun.certificate","mpd":"application/dash+xml","mpe":"video/mpeg","mpeg":"video/mpeg","mpf":"application/media-policy-dataset+xml","mpg":"video/mpeg","mpg4":"video/mp4","mpga":"audio/mpeg","mpkg":"application/vnd.apple.installer+xml","mpm":"application/vnd.blueice.multipass","mpn":"application/vnd.mophun.application","mpp":"application/vnd.ms-project","mpt":"application/vnd.ms-project","mpy":"application/vnd.ibm.minipay","mqy":"application/vnd.mobius.mqy","mrc":"application/marc","mrcx":"application/marcxml+xml","ms":"text/troff","mscml":"application/mediaservercontrol+xml","mseed":"application/vnd.fdsn.mseed","mseq":"application/vnd.mseq","msf":"application/vnd.epson.msf","msg":"application/vnd.ms-outlook","msh":"model/mesh","msi":"application/x-msdownload","msl":"application/vnd.mobius.msl","msm":"application/octet-stream","msp":"application/octet-stream","msty":"application/vnd.muvee.style","mtl":"model/mtl","mts":"model/vnd.mts","mus":"application/vnd.musician","musd":"application/mmt-usd+xml","musicxml":"application/vnd.recordare.musicxml+xml","mvb":"application/x-msmediaview","mvt":"application/vnd.mapbox-vector-tile","mwf":"application/vnd.mfer","mxf":"application/mxf","mxl":"application/vnd.recordare.musicxml","mxmf":"audio/mobile-xmf","mxml":"application/xv+xml","mxs":"application/vnd.triscape.mxs","mxu":"video/vnd.mpegurl","n-gage":"application/vnd.nokia.n-gage.symbian.install","n3":"text/n3","nb":"application/mathematica","nbp":"application/vnd.wolfram.player","nc":"application/x-netcdf","ncx":"application/x-dtbncx+xml","nfo":"text/x-nfo","ngdat":"application/vnd.nokia.n-gage.data","nitf":"application/vnd.nitf","nlu":"application/vnd.neurolanguage.nlu","nml":"application/vnd.enliven","nnd":"application/vnd.noblenet-directory","nns":"application/vnd.noblenet-sealer","nnw":"application/vnd.noblenet-web","npx":"image/vnd.net-fpx","nq":"application/n-quads","nsc":"application/x-conference","nsf":"application/vnd.lotus-notes","nt":"application/n-triples","ntf":"application/vnd.nitf","numbers":"application/x-iwork-numbers-sffnumbers","nzb":"application/x-nzb","oa2":"application/vnd.fujitsu.oasys2","oa3":"application/vnd.fujitsu.oasys3","oas":"application/vnd.fujitsu.oasys","obd":"application/x-msbinder","obgx":"application/vnd.openblox.game+xml","obj":"model/obj","oda":"application/oda","odb":"application/vnd.oasis.opendocument.database","odc":"application/vnd.oasis.opendocument.chart","odf":"application/vnd.oasis.opendocument.formula","odft":"application/vnd.oasis.opendocument.formula-template","odg":"application/vnd.oasis.opendocument.graphics","odi":"application/vnd.oasis.opendocument.image","odm":"application/vnd.oasis.opendocument.text-master","odp":"application/vnd.oasis.opendocument.presentation","ods":"application/vnd.oasis.opendocument.spreadsheet","odt":"application/vnd.oasis.opendocument.text","oga":"audio/ogg","ogex":"model/vnd.opengex","ogg":"audio/ogg","ogv":"video/ogg","ogx":"application/ogg","omdoc":"application/omdoc+xml","onepkg":"application/onenote","onetmp":"application/onenote","onetoc":"application/onenote","onetoc2":"application/onenote","opf":"application/oebps-package+xml","opml":"text/x-opml","oprc":"application/vnd.palm","opus":"audio/ogg","org":"text/x-org","osf":"application/vnd.yamaha.openscoreformat","osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml","osm":"application/vnd.openstreetmap.data+xml","otc":"application/vnd.oasis.opendocument.chart-template","otf":"font/otf","otg":"application/vnd.oasis.opendocument.graphics-template","oth":"application/vnd.oasis.opendocument.text-web","oti":"application/vnd.oasis.opendocument.image-template","otp":"application/vnd.oasis.opendocument.presentation-template","ots":"application/vnd.oasis.opendocument.spreadsheet-template","ott":"application/vnd.oasis.opendocument.text-template","ova":"application/x-virtualbox-ova","ovf":"application/x-virtualbox-ovf","owl":"application/rdf+xml","oxps":"application/oxps","oxt":"application/vnd.openofficeorg.extension","p":"text/x-pascal","p10":"application/pkcs10","p12":"application/x-pkcs12","p7b":"application/x-pkcs7-certificates","p7c":"application/pkcs7-mime","p7m":"application/pkcs7-mime","p7r":"application/x-pkcs7-certreqresp","p7s":"application/pkcs7-signature","p8":"application/pkcs8","pac":"application/x-ns-proxy-autoconfig","pages":"application/x-iwork-pages-sffpages","pas":"text/x-pascal","paw":"application/vnd.pawaafile","pbd":"application/vnd.powerbuilder6","pbm":"image/x-portable-bitmap","pcap":"application/vnd.tcpdump.pcap","pcf":"application/x-font-pcf","pcl":"application/vnd.hp-pcl","pclxl":"application/vnd.hp-pclxl","pct":"image/x-pict","pcurl":"application/vnd.curl.pcurl","pcx":"image/x-pcx","pdb":"application/x-pilot","pde":"text/x-processing","pdf":"application/pdf","pem":"application/x-x509-ca-cert","pfa":"application/x-font-type1","pfb":"application/x-font-type1","pfm":"application/x-font-type1","pfr":"application/font-tdpfr","pfx":"application/x-pkcs12","pgm":"image/x-portable-graymap","pgn":"application/x-chess-pgn","pgp":"application/pgp-encrypted","php":"application/x-httpd-php","pic":"image/x-pict","pkg":"application/octet-stream","pki":"application/pkixcmp","pkipath":"application/pkix-pkipath","pkpass":"application/vnd.apple.pkpass","pl":"application/x-perl","plb":"application/vnd.3gpp.pic-bw-large","plc":"application/vnd.mobius.plc","plf":"application/vnd.pocketlearn","pls":"application/pls+xml","pm":"application/x-perl","pml":"application/vnd.ctc-posml","png":"image/png","pnm":"image/x-portable-anymap","portpkg":"application/vnd.macports.portpkg","pot":"application/vnd.ms-powerpoint","potm":"application/vnd.ms-powerpoint.template.macroenabled.12","potx":"application/vnd.openxmlformats-officedocument.presentationml.template","ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12","ppd":"application/vnd.cups-ppd","ppm":"image/x-portable-pixmap","pps":"application/vnd.ms-powerpoint","ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12","ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow","ppt":"application/vnd.ms-powerpoint","pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12","pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation","pqa":"application/vnd.palm","prc":"application/x-pilot","pre":"application/vnd.lotus-freelance","prf":"application/pics-rules","provx":"application/provenance+xml","ps":"application/postscript","psb":"application/vnd.3gpp.pic-bw-small","psd":"image/vnd.adobe.photoshop","psf":"application/x-font-linux-psf","pskcxml":"application/pskc+xml","pti":"image/prs.pti","ptid":"application/vnd.pvi.ptid1","pub":"application/x-mspublisher","pvb":"application/vnd.3gpp.pic-bw-var","pwn":"application/vnd.3m.post-it-notes","pya":"audio/vnd.ms-playready.media.pya","pyv":"video/vnd.ms-playready.media.pyv","qam":"application/vnd.epson.quickanime","qbo":"application/vnd.intu.qbo","qfx":"application/vnd.intu.qfx","qps":"application/vnd.publishare-delta-tree","qt":"video/quicktime","qwd":"application/vnd.quark.quarkxpress","qwt":"application/vnd.quark.quarkxpress","qxb":"application/vnd.quark.quarkxpress","qxd":"application/vnd.quark.quarkxpress","qxl":"application/vnd.quark.quarkxpress","qxt":"application/vnd.quark.quarkxpress","ra":"audio/x-realaudio","ram":"audio/x-pn-realaudio","raml":"application/raml+yaml","rapd":"application/route-apd+xml","rar":"application/x-rar-compressed","ras":"image/x-cmu-raster","rcprofile":"application/vnd.ipunplugged.rcprofile","rdf":"application/rdf+xml","rdz":"application/vnd.data-vision.rdz","relo":"application/p2p-overlay+xml","rep":"application/vnd.businessobjects","res":"application/x-dtbresource+xml","rgb":"image/x-rgb","rif":"application/reginfo+xml","rip":"audio/vnd.rip","ris":"application/x-research-info-systems","rl":"application/resource-lists+xml","rlc":"image/vnd.fujixerox.edmics-rlc","rld":"application/resource-lists-diff+xml","rm":"application/vnd.rn-realmedia","rmi":"audio/midi","rmp":"audio/x-pn-realaudio-plugin","rms":"application/vnd.jcp.javame.midlet-rms","rmvb":"application/vnd.rn-realmedia-vbr","rnc":"application/relax-ng-compact-syntax","rng":"application/xml","roa":"application/rpki-roa","roff":"text/troff","rp9":"application/vnd.cloanto.rp9","rpm":"application/x-redhat-package-manager","rpss":"application/vnd.nokia.radio-presets","rpst":"application/vnd.nokia.radio-preset","rq":"application/sparql-query","rs":"application/rls-services+xml","rsat":"application/atsc-rsat+xml","rsd":"application/rsd+xml","rsheet":"application/urc-ressheet+xml","rss":"application/rss+xml","rtf":"text/rtf","rtx":"text/richtext","run":"application/x-makeself","rusd":"application/route-usd+xml","s":"text/x-asm","s3m":"audio/s3m","saf":"application/vnd.yamaha.smaf-audio","sass":"text/x-sass","sbml":"application/sbml+xml","sc":"application/vnd.ibm.secure-container","scd":"application/x-msschedule","scm":"application/vnd.lotus-screencam","scq":"application/scvp-cv-request","scs":"application/scvp-cv-response","scss":"text/x-scss","scurl":"text/vnd.curl.scurl","sda":"application/vnd.stardivision.draw","sdc":"application/vnd.stardivision.calc","sdd":"application/vnd.stardivision.impress","sdkd":"application/vnd.solent.sdkm+xml","sdkm":"application/vnd.solent.sdkm+xml","sdp":"application/sdp","sdw":"application/vnd.stardivision.writer","sea":"application/x-sea","see":"application/vnd.seemail","seed":"application/vnd.fdsn.seed","sema":"application/vnd.sema","semd":"application/vnd.semd","semf":"application/vnd.semf","senmlx":"application/senml+xml","sensmlx":"application/sensml+xml","ser":"application/java-serialized-object","setpay":"application/set-payment-initiation","setreg":"application/set-registration-initiation","sfd-hdstx":"application/vnd.hydrostatix.sof-data","sfs":"application/vnd.spotfire.sfs","sfv":"text/x-sfv","sgi":"image/sgi","sgl":"application/vnd.stardivision.writer-global","sgm":"text/sgml","sgml":"text/sgml","sh":"application/x-sh","shar":"application/x-shar","shex":"text/shex","shf":"application/shf+xml","shtml":"text/html","sid":"image/x-mrsid-image","sieve":"application/sieve","sig":"application/pgp-signature","sil":"audio/silk","silo":"model/mesh","sis":"application/vnd.symbian.install","sisx":"application/vnd.symbian.install","sit":"application/x-stuffit","sitx":"application/x-stuffitx","siv":"application/sieve","skd":"application/vnd.koan","skm":"application/vnd.koan","skp":"application/vnd.koan","skt":"application/vnd.koan","sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12","sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide","slim":"text/slim","slm":"text/slim","sls":"application/route-s-tsid+xml","slt":"application/vnd.epson.salt","sm":"application/vnd.stepmania.stepchart","smf":"application/vnd.stardivision.math","smi":"application/smil+xml","smil":"application/smil+xml","smv":"video/x-smv","smzip":"application/vnd.stepmania.package","snd":"audio/basic","snf":"application/x-font-snf","so":"application/octet-stream","spc":"application/x-pkcs7-certificates","spdx":"text/spdx","spf":"application/vnd.yamaha.smaf-phrase","spl":"application/x-futuresplash","spot":"text/vnd.in3d.spot","spp":"application/scvp-vp-response","spq":"application/scvp-vp-request","spx":"audio/ogg","sql":"application/x-sql","src":"application/x-wais-source","srt":"application/x-subrip","sru":"application/sru+xml","srx":"application/sparql-results+xml","ssdl":"application/ssdl+xml","sse":"application/vnd.kodak-descriptor","ssf":"application/vnd.epson.ssf","ssml":"application/ssml+xml","st":"application/vnd.sailingtracker.track","stc":"application/vnd.sun.xml.calc.template","std":"application/vnd.sun.xml.draw.template","stf":"application/vnd.wt.stf","sti":"application/vnd.sun.xml.impress.template","stk":"application/hyperstudio","stl":"model/stl","stpx":"model/step+xml","stpxz":"model/step-xml+zip","stpz":"model/step+zip","str":"application/vnd.pg.format","stw":"application/vnd.sun.xml.writer.template","styl":"text/stylus","stylus":"text/stylus","sub":"text/vnd.dvb.subtitle","sus":"application/vnd.sus-calendar","susp":"application/vnd.sus-calendar","sv4cpio":"application/x-sv4cpio","sv4crc":"application/x-sv4crc","svc":"application/vnd.dvb.service","svd":"application/vnd.svd","svg":"image/svg+xml","svgz":"image/svg+xml","swa":"application/x-director","swf":"application/x-shockwave-flash","swi":"application/vnd.aristanetworks.swi","swidtag":"application/swid+xml","sxc":"application/vnd.sun.xml.calc","sxd":"application/vnd.sun.xml.draw","sxg":"application/vnd.sun.xml.writer.global","sxi":"application/vnd.sun.xml.impress","sxm":"application/vnd.sun.xml.math","sxw":"application/vnd.sun.xml.writer","t":"text/troff","t3":"application/x-t3vm-image","t38":"image/t38","taglet":"application/vnd.mynfc","tao":"application/vnd.tao.intent-module-archive","tap":"image/vnd.tencent.tap","tar":"application/x-tar","tcap":"application/vnd.3gpp2.tcap","tcl":"application/x-tcl","td":"application/urc-targetdesc+xml","teacher":"application/vnd.smart.teacher","tei":"application/tei+xml","teicorpus":"application/tei+xml","tex":"application/x-tex","texi":"application/x-texinfo","texinfo":"application/x-texinfo","text":"text/plain","tfi":"application/thraud+xml","tfm":"application/x-tex-tfm","tfx":"image/tiff-fx","tga":"image/x-tga","thmx":"application/vnd.ms-officetheme","tif":"image/tiff","tiff":"image/tiff","tk":"application/x-tcl","tmo":"application/vnd.tmobile-livetv","toml":"application/toml","torrent":"application/x-bittorrent","tpl":"application/vnd.groove-tool-template","tpt":"application/vnd.trid.tpt","tr":"text/troff","tra":"application/vnd.trueapp","trig":"application/trig","trm":"application/x-msterminal","ts":"video/mp2t","tsd":"application/timestamped-data","tsv":"text/tab-separated-values","ttc":"font/collection","ttf":"font/ttf","ttl":"text/turtle","ttml":"application/ttml+xml","twd":"application/vnd.simtech-mindmapper","twds":"application/vnd.simtech-mindmapper","txd":"application/vnd.genomatix.tuxedo","txf":"application/vnd.mobius.txf","txt":"text/plain","u32":"application/x-authorware-bin","u8dsn":"message/global-delivery-status","u8hdr":"message/global-headers","u8mdn":"message/global-disposition-notification","u8msg":"message/global","ubj":"application/ubjson","udeb":"application/x-debian-package","ufd":"application/vnd.ufdl","ufdl":"application/vnd.ufdl","ulx":"application/x-glulx","umj":"application/vnd.umajin","unityweb":"application/vnd.unity","uoml":"application/vnd.uoml+xml","uri":"text/uri-list","uris":"text/uri-list","urls":"text/uri-list","usdz":"model/vnd.usdz+zip","ustar":"application/x-ustar","utz":"application/vnd.uiq.theme","uu":"text/x-uuencode","uva":"audio/vnd.dece.audio","uvd":"application/vnd.dece.data","uvf":"application/vnd.dece.data","uvg":"image/vnd.dece.graphic","uvh":"video/vnd.dece.hd","uvi":"image/vnd.dece.graphic","uvm":"video/vnd.dece.mobile","uvp":"video/vnd.dece.pd","uvs":"video/vnd.dece.sd","uvt":"application/vnd.dece.ttml+xml","uvu":"video/vnd.uvvu.mp4","uvv":"video/vnd.dece.video","uvva":"audio/vnd.dece.audio","uvvd":"application/vnd.dece.data","uvvf":"application/vnd.dece.data","uvvg":"image/vnd.dece.graphic","uvvh":"video/vnd.dece.hd","uvvi":"image/vnd.dece.graphic","uvvm":"video/vnd.dece.mobile","uvvp":"video/vnd.dece.pd","uvvs":"video/vnd.dece.sd","uvvt":"application/vnd.dece.ttml+xml","uvvu":"video/vnd.uvvu.mp4","uvvv":"video/vnd.dece.video","uvvx":"application/vnd.dece.unspecified","uvvz":"application/vnd.dece.zip","uvx":"application/vnd.dece.unspecified","uvz":"application/vnd.dece.zip","vbox":"application/x-virtualbox-vbox","vbox-extpack":"application/x-virtualbox-vbox-extpack","vcard":"text/vcard","vcd":"application/x-cdlink","vcf":"text/x-vcard","vcg":"application/vnd.groove-vcard","vcs":"text/x-vcalendar","vcx":"application/vnd.vcx","vdi":"application/x-virtualbox-vdi","vds":"model/vnd.sap.vds","vhd":"application/x-virtualbox-vhd","vis":"application/vnd.visionary","viv":"video/vnd.vivo","vmdk":"application/x-virtualbox-vmdk","vob":"video/x-ms-vob","vor":"application/vnd.stardivision.writer","vox":"application/x-authorware-bin","vrml":"model/vrml","vsd":"application/vnd.visio","vsf":"application/vnd.vsf","vss":"application/vnd.visio","vst":"application/vnd.visio","vsw":"application/vnd.visio","vtf":"image/vnd.valve.source.texture","vtt":"text/vtt","vtu":"model/vnd.vtu","vxml":"application/voicexml+xml","w3d":"application/x-director","wad":"application/x-doom","wadl":"application/vnd.sun.wadl+xml","war":"application/java-archive","wasm":"application/wasm","wav":"audio/x-wav","wax":"audio/x-ms-wax","wbmp":"image/vnd.wap.wbmp","wbs":"application/vnd.criticaltools.wbs+xml","wbxml":"application/vnd.wap.wbxml","wcm":"application/vnd.ms-works","wdb":"application/vnd.ms-works","wdp":"image/vnd.ms-photo","weba":"audio/webm","webapp":"application/x-web-app-manifest+json","webm":"video/webm","webmanifest":"application/manifest+json","webp":"image/webp","wg":"application/vnd.pmi.widget","wgt":"application/widget","wif":"application/watcherinfo+xml","wks":"application/vnd.ms-works","wm":"video/x-ms-wm","wma":"audio/x-ms-wma","wmd":"application/x-ms-wmd","wmf":"image/wmf","wml":"text/vnd.wap.wml","wmlc":"application/vnd.wap.wmlc","wmls":"text/vnd.wap.wmlscript","wmlsc":"application/vnd.wap.wmlscriptc","wmv":"video/x-ms-wmv","wmx":"video/x-ms-wmx","wmz":"application/x-msmetafile","woff":"font/woff","woff2":"font/woff2","wpd":"application/vnd.wordperfect","wpl":"application/vnd.ms-wpl","wps":"application/vnd.ms-works","wqd":"application/vnd.wqd","wri":"application/x-mswrite","wrl":"model/vrml","wsc":"message/vnd.wfa.wsc","wsdl":"application/wsdl+xml","wspolicy":"application/wspolicy+xml","wtb":"application/vnd.webturbo","wvx":"video/x-ms-wvx","x32":"application/x-authorware-bin","x3d":"model/x3d+xml","x3db":"model/x3d+fastinfoset","x3dbz":"model/x3d+binary","x3dv":"model/x3d-vrml","x3dvz":"model/x3d+vrml","x3dz":"model/x3d+xml","x_b":"model/vnd.parasolid.transmit.binary","x_t":"model/vnd.parasolid.transmit.text","xaml":"application/xaml+xml","xap":"application/x-silverlight-app","xar":"application/vnd.xara","xav":"application/xcap-att+xml","xbap":"application/x-ms-xbap","xbd":"application/vnd.fujixerox.docuworks.binder","xbm":"image/x-xbitmap","xca":"application/xcap-caps+xml","xcs":"application/calendar+xml","xdf":"application/xcap-diff+xml","xdm":"application/vnd.syncml.dm+xml","xdp":"application/vnd.adobe.xdp+xml","xdssc":"application/dssc+xml","xdw":"application/vnd.fujixerox.docuworks","xel":"application/xcap-el+xml","xenc":"application/xenc+xml","xer":"application/patch-ops-error+xml","xfdf":"application/vnd.adobe.xfdf","xfdl":"application/vnd.xfdl","xht":"application/xhtml+xml","xhtml":"application/xhtml+xml","xhvml":"application/xv+xml","xif":"image/vnd.xiff","xla":"application/vnd.ms-excel","xlam":"application/vnd.ms-excel.addin.macroenabled.12","xlc":"application/vnd.ms-excel","xlf":"application/xliff+xml","xlm":"application/vnd.ms-excel","xls":"application/vnd.ms-excel","xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12","xlsm":"application/vnd.ms-excel.sheet.macroenabled.12","xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlt":"application/vnd.ms-excel","xltm":"application/vnd.ms-excel.template.macroenabled.12","xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template","xlw":"application/vnd.ms-excel","xm":"audio/xm","xml":"text/xml","xns":"application/xcap-ns+xml","xo":"application/vnd.olpc-sugar","xop":"application/xop+xml","xpi":"application/x-xpinstall","xpl":"application/xproc+xml","xpm":"image/x-xpixmap","xpr":"application/vnd.is-xpr","xps":"application/vnd.ms-xpsdocument","xpw":"application/vnd.intercon.formnet","xpx":"application/vnd.intercon.formnet","xsd":"application/xml","xsl":"application/xslt+xml","xslt":"application/xslt+xml","xsm":"application/vnd.syncml+xml","xspf":"application/xspf+xml","xul":"application/vnd.mozilla.xul+xml","xvm":"application/xv+xml","xvml":"application/xv+xml","xwd":"image/x-xwindowdump","xyz":"chemical/x-xyz","xz":"application/x-xz","yaml":"text/yaml","yang":"application/yang","yin":"application/yin+xml","yml":"text/yaml","ymp":"text/x-suse-ymp","z1":"application/x-zmachine","z2":"application/x-zmachine","z3":"application/x-zmachine","z4":"application/x-zmachine","z5":"application/x-zmachine","z6":"application/x-zmachine","z7":"application/x-zmachine","z8":"application/x-zmachine","zaz":"application/vnd.zzazz.deck+xml","zip":"application/zip","zir":"application/vnd.zul","zirz":"application/vnd.zul","zmm":"application/vnd.handheld-entertainment+xml"};
62
63const version = '2.18.0';
64
65function responseHeaders(headers, httpCache = false) {
66 headers = { ...DEFAULT_HEADERS, ...headers };
67 if (httpCache) {
68 headers['cache-control'] = 'max-age=3600';
69 delete headers['date'];
70 delete headers['expires'];
71 }
72 return headers;
73}
74const DEFAULT_HEADERS = {
75 'cache-control': 'no-cache, no-store, must-revalidate, max-age=0',
76 expires: '0',
77 date: 'Wed, 1 Jan 2000 00:00:00 GMT',
78 server: 'Stencil Dev Server ' + version,
79 'access-control-allow-origin': '*',
80 'access-control-expose-headers': '*',
81};
82function getBrowserUrl(protocol, address, port, basePath, pathname) {
83 address = address === `0.0.0.0` ? `localhost` : address;
84 const portSuffix = !port || port === 80 || port === 443 ? '' : ':' + port;
85 let path = basePath;
86 if (pathname.startsWith('/')) {
87 pathname = pathname.substring(1);
88 }
89 path += pathname;
90 protocol = protocol.replace(/\:/g, '');
91 return `${protocol}://${address}${portSuffix}${path}`;
92}
93function getDevServerClientUrl(devServerConfig, host, protocol) {
94 let address = devServerConfig.address;
95 let port = devServerConfig.port;
96 if (host) {
97 address = host;
98 port = null;
99 }
100 return getBrowserUrl(protocol !== null && protocol !== void 0 ? protocol : devServerConfig.protocol, address, port, devServerConfig.basePath, DEV_SERVER_URL);
101}
102function getContentType(filePath) {
103 const last = filePath.replace(/^.*[/\\]/, '').toLowerCase();
104 const ext = last.replace(/^.*\./, '').toLowerCase();
105 const hasPath = last.length < filePath.length;
106 const hasDot = ext.length < last.length - 1;
107 return ((hasDot || !hasPath) && contentTypes[ext]) || 'application/octet-stream';
108}
109function isHtmlFile(filePath) {
110 filePath = filePath.toLowerCase().trim();
111 return filePath.endsWith('.html') || filePath.endsWith('.htm');
112}
113function isCssFile(filePath) {
114 filePath = filePath.toLowerCase().trim();
115 return filePath.endsWith('.css');
116}
117const TXT_EXT = ['css', 'html', 'htm', 'js', 'json', 'svg', 'xml'];
118function isSimpleText(filePath) {
119 const ext = filePath.toLowerCase().trim().split('.').pop();
120 return TXT_EXT.includes(ext);
121}
122function isExtensionLessPath(pathname) {
123 const parts = pathname.split('/');
124 const lastPart = parts[parts.length - 1];
125 return !lastPart.includes('.');
126}
127function isSsrStaticDataPath(pathname) {
128 const parts = pathname.split('/');
129 const fileName = parts[parts.length - 1].split('?')[0];
130 return fileName === 'page.state.json';
131}
132function getSsrStaticDataPath(req) {
133 const parts = req.url.href.split('/');
134 const fileName = parts[parts.length - 1];
135 const fileNameParts = fileName.split('?');
136 parts.pop();
137 let ssrPath = new URL(parts.join('/')).href;
138 if (!ssrPath.endsWith('/') && req.headers) {
139 const h = new Headers(req.headers);
140 if (h.get('referer').endsWith('/')) {
141 ssrPath += '/';
142 }
143 }
144 return {
145 ssrPath,
146 fileName: fileNameParts[0],
147 hasQueryString: typeof fileNameParts[1] === 'string' && fileNameParts[1].length > 0,
148 };
149}
150function isDevClient(pathname) {
151 return pathname.startsWith(DEV_SERVER_URL);
152}
153function isDevModule(pathname) {
154 return pathname.includes(DEV_MODULE_URL);
155}
156function isOpenInEditor(pathname) {
157 return pathname === OPEN_IN_EDITOR_URL;
158}
159function isInitialDevServerLoad(pathname) {
160 return pathname === DEV_SERVER_INIT_URL;
161}
162function isDevServerClient(pathname) {
163 return pathname === DEV_SERVER_URL;
164}
165function shouldCompress(devServerConfig, req) {
166 if (!devServerConfig.gzip) {
167 return false;
168 }
169 if (req.method !== 'GET') {
170 return false;
171 }
172 const acceptEncoding = req.headers && req.headers['accept-encoding'];
173 if (typeof acceptEncoding !== 'string') {
174 return false;
175 }
176 if (!acceptEncoding.includes('gzip')) {
177 return false;
178 }
179 return true;
180}
181
182function createServerContext(sys, sendMsg, devServerConfig, buildResultsResolves, compilerRequestResolves) {
183 const logRequest = (req, status) => {
184 if (devServerConfig) {
185 sendMsg({
186 requestLog: {
187 method: req.method || '?',
188 url: req.pathname || '?',
189 status,
190 },
191 });
192 }
193 };
194 const serve500 = (req, res, error, xSource) => {
195 try {
196 res.writeHead(500, responseHeaders({
197 'content-type': 'text/plain; charset=utf-8',
198 'x-source': xSource,
199 }));
200 res.write(util__default['default'].inspect(error));
201 res.end();
202 logRequest(req, 500);
203 }
204 catch (e) {
205 sendMsg({ error: { message: 'serve500: ' + e } });
206 }
207 };
208 const serve404 = (req, res, xSource, content = null) => {
209 try {
210 if (req.pathname === '/favicon.ico') {
211 const defaultFavicon = path__default['default'].join(devServerConfig.devServerDir, 'static', 'favicon.ico');
212 res.writeHead(200, responseHeaders({
213 'content-type': 'image/x-icon',
214 'x-source': `favicon: ${xSource}`,
215 }));
216 const rs = fs__default['default'].createReadStream(defaultFavicon);
217 rs.on('error', (err) => {
218 res.writeHead(404, responseHeaders({
219 'content-type': 'text/plain; charset=utf-8',
220 'x-source': `createReadStream error: ${err}, ${xSource}`,
221 }));
222 res.write(util__default['default'].inspect(err));
223 res.end();
224 });
225 rs.pipe(res);
226 return;
227 }
228 if (content == null) {
229 content = ['404 File Not Found', 'Url: ' + req.pathname, 'File: ' + req.filePath].join('\n');
230 }
231 res.writeHead(404, responseHeaders({
232 'content-type': 'text/plain; charset=utf-8',
233 'x-source': xSource,
234 }));
235 res.write(content);
236 res.end();
237 logRequest(req, 400);
238 }
239 catch (e) {
240 serve500(req, res, e, xSource);
241 }
242 };
243 const serve302 = (req, res, pathname = null) => {
244 logRequest(req, 302);
245 res.writeHead(302, { location: pathname || devServerConfig.basePath || '/' });
246 res.end();
247 };
248 const getBuildResults = () => new Promise((resolve, reject) => {
249 if (serverCtx.isServerListening) {
250 buildResultsResolves.push({ resolve, reject });
251 sendMsg({ requestBuildResults: true });
252 }
253 else {
254 reject('dev server closed');
255 }
256 });
257 const getCompilerRequest = (compilerRequestPath) => new Promise((resolve, reject) => {
258 if (serverCtx.isServerListening) {
259 compilerRequestResolves.push({
260 path: compilerRequestPath,
261 resolve,
262 reject,
263 });
264 sendMsg({ compilerRequestPath });
265 }
266 else {
267 reject('dev server closed');
268 }
269 });
270 const serverCtx = {
271 connectorHtml: null,
272 dirTemplate: null,
273 getBuildResults,
274 getCompilerRequest,
275 isServerListening: false,
276 logRequest,
277 prerenderConfig: null,
278 serve302,
279 serve404,
280 serve500,
281 sys,
282 };
283 return serverCtx;
284}
285
286const noop = () => {
287 /* noop*/
288};
289const isFunction = (v) => typeof v === 'function';
290const isString = (v) => typeof v === 'string';
291
292/**
293 * Builds a diagnostic from an `Error`, appends it to the `diagnostics` parameter, and returns the created diagnostic
294 * @param diagnostics the series of diagnostics the newly created diagnostics should be added to
295 * @param err the error to derive information from in generating the diagnostic
296 * @param msg an optional message to use in place of `err` to generate the diagnostic
297 * @returns the generated diagnostic
298 */
299const catchError = (diagnostics, err, msg) => {
300 const diagnostic = {
301 level: 'error',
302 type: 'build',
303 header: 'Build Error',
304 messageText: 'build error',
305 relFilePath: null,
306 absFilePath: null,
307 lines: [],
308 };
309 if (isString(msg)) {
310 diagnostic.messageText = msg.length ? msg : 'UNKNOWN ERROR';
311 }
312 else if (err != null) {
313 if (err.stack != null) {
314 diagnostic.messageText = err.stack.toString();
315 }
316 else {
317 if (err.message != null) {
318 diagnostic.messageText = err.message.length ? err.message : 'UNKNOWN ERROR';
319 }
320 else {
321 diagnostic.messageText = err.toString();
322 }
323 }
324 }
325 if (diagnostics != null && !shouldIgnoreError(diagnostic.messageText)) {
326 diagnostics.push(diagnostic);
327 }
328 return diagnostic;
329};
330const shouldIgnoreError = (msg) => {
331 return msg === TASK_CANCELED_MSG;
332};
333const TASK_CANCELED_MSG = `task canceled`;
334
335/**
336 * Convert Windows backslash paths to slash paths: foo\\bar ➔ foo/bar
337 * Forward-slash paths can be used in Windows as long as they're not
338 * extended-length paths and don't contain any non-ascii characters.
339 * This was created since the path methods in Node.js outputs \\ paths on Windows.
340 * @param path the Windows-based path to convert
341 * @returns the converted path
342 */
343const normalizePath = (path) => {
344 if (typeof path !== 'string') {
345 throw new Error(`invalid path to normalize`);
346 }
347 path = normalizeSlashes(path.trim());
348 const components = pathComponents(path, getRootLength(path));
349 const reducedComponents = reducePathComponents(components);
350 const rootPart = reducedComponents[0];
351 const secondPart = reducedComponents[1];
352 const normalized = rootPart + reducedComponents.slice(1).join('/');
353 if (normalized === '') {
354 return '.';
355 }
356 if (rootPart === '' &&
357 secondPart &&
358 path.includes('/') &&
359 !secondPart.startsWith('.') &&
360 !secondPart.startsWith('@')) {
361 return './' + normalized;
362 }
363 return normalized;
364};
365const normalizeSlashes = (path) => path.replace(backslashRegExp, '/');
366const altDirectorySeparator = '\\';
367const urlSchemeSeparator = '://';
368const backslashRegExp = /\\/g;
369const reducePathComponents = (components) => {
370 if (!Array.isArray(components) || components.length === 0) {
371 return [];
372 }
373 const reduced = [components[0]];
374 for (let i = 1; i < components.length; i++) {
375 const component = components[i];
376 if (!component)
377 continue;
378 if (component === '.')
379 continue;
380 if (component === '..') {
381 if (reduced.length > 1) {
382 if (reduced[reduced.length - 1] !== '..') {
383 reduced.pop();
384 continue;
385 }
386 }
387 else if (reduced[0])
388 continue;
389 }
390 reduced.push(component);
391 }
392 return reduced;
393};
394const getRootLength = (path) => {
395 const rootLength = getEncodedRootLength(path);
396 return rootLength < 0 ? ~rootLength : rootLength;
397};
398const getEncodedRootLength = (path) => {
399 if (!path)
400 return 0;
401 const ch0 = path.charCodeAt(0);
402 // POSIX or UNC
403 if (ch0 === 47 /* CharacterCodes.slash */ || ch0 === 92 /* CharacterCodes.backslash */) {
404 if (path.charCodeAt(1) !== ch0)
405 return 1; // POSIX: "/" (or non-normalized "\")
406 const p1 = path.indexOf(ch0 === 47 /* CharacterCodes.slash */ ? '/' : altDirectorySeparator, 2);
407 if (p1 < 0)
408 return path.length; // UNC: "//server" or "\\server"
409 return p1 + 1; // UNC: "//server/" or "\\server\"
410 }
411 // DOS
412 if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* CharacterCodes.colon */) {
413 const ch2 = path.charCodeAt(2);
414 if (ch2 === 47 /* CharacterCodes.slash */ || ch2 === 92 /* CharacterCodes.backslash */)
415 return 3; // DOS: "c:/" or "c:\"
416 if (path.length === 2)
417 return 2; // DOS: "c:" (but not "c:d")
418 }
419 // URL
420 const schemeEnd = path.indexOf(urlSchemeSeparator);
421 if (schemeEnd !== -1) {
422 const authorityStart = schemeEnd + urlSchemeSeparator.length;
423 const authorityEnd = path.indexOf('/', authorityStart);
424 if (authorityEnd !== -1) {
425 // URL: "file:///", "file://server/", "file://server/path"
426 // For local "file" URLs, include the leading DOS volume (if present).
427 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
428 // special case interpreted as "the machine from which the URL is being interpreted".
429 const scheme = path.slice(0, schemeEnd);
430 const authority = path.slice(authorityStart, authorityEnd);
431 if (scheme === 'file' &&
432 (authority === '' || authority === 'localhost') &&
433 isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
434 const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
435 if (volumeSeparatorEnd !== -1) {
436 if (path.charCodeAt(volumeSeparatorEnd) === 47 /* CharacterCodes.slash */) {
437 // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
438 return ~(volumeSeparatorEnd + 1);
439 }
440 if (volumeSeparatorEnd === path.length) {
441 // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
442 // but not "file:///c:d" or "file:///c%3ad"
443 return ~volumeSeparatorEnd;
444 }
445 }
446 }
447 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
448 }
449 return ~path.length; // URL: "file://server", "http://server"
450 }
451 // relative
452 return 0;
453};
454const isVolumeCharacter = (charCode) => (charCode >= 97 /* CharacterCodes.a */ && charCode <= 122 /* CharacterCodes.z */) ||
455 (charCode >= 65 /* CharacterCodes.A */ && charCode <= 90 /* CharacterCodes.Z */);
456const getFileUrlVolumeSeparatorEnd = (url, start) => {
457 const ch0 = url.charCodeAt(start);
458 if (ch0 === 58 /* CharacterCodes.colon */)
459 return start + 1;
460 if (ch0 === 37 /* CharacterCodes.percent */ && url.charCodeAt(start + 1) === 51 /* CharacterCodes._3 */) {
461 const ch2 = url.charCodeAt(start + 2);
462 if (ch2 === 97 /* CharacterCodes.a */ || ch2 === 65 /* CharacterCodes.A */)
463 return start + 3;
464 }
465 return -1;
466};
467const pathComponents = (path, rootLength) => {
468 const root = path.substring(0, rootLength);
469 const rest = path.substring(rootLength).split('/');
470 const restLen = rest.length;
471 if (restLen > 0 && !rest[restLen - 1]) {
472 rest.pop();
473 }
474 return [root, ...rest];
475};
476
477async function serveFile(devServerConfig, serverCtx, req, res) {
478 try {
479 if (isSimpleText(req.filePath)) {
480 // easy text file, use the internal cache
481 let content = await serverCtx.sys.readFile(req.filePath, 'utf8');
482 if (devServerConfig.websocket && isHtmlFile(req.filePath) && !isDevServerClient(req.pathname)) {
483 // auto inject our dev server script
484 content = appendDevServerClientScript(devServerConfig, req, content);
485 }
486 else if (isCssFile(req.filePath)) {
487 content = updateStyleUrls(req.url, content);
488 }
489 if (shouldCompress(devServerConfig, req)) {
490 // let's gzip this well known web dev text file
491 res.writeHead(200, responseHeaders({
492 'content-type': getContentType(req.filePath) + '; charset=utf-8',
493 'content-encoding': 'gzip',
494 vary: 'Accept-Encoding',
495 }));
496 zlib__namespace.gzip(content, { level: 9 }, (_, data) => {
497 res.end(data);
498 });
499 }
500 else {
501 // let's not gzip this file
502 res.writeHead(200, responseHeaders({
503 'content-type': getContentType(req.filePath) + '; charset=utf-8',
504 'content-length': buffer.Buffer.byteLength(content, 'utf8'),
505 }));
506 res.write(content);
507 res.end();
508 }
509 }
510 else {
511 // non-well-known text file or other file, probably best we use a stream
512 // but don't bother trying to gzip this file for the dev server
513 res.writeHead(200, responseHeaders({
514 'content-type': getContentType(req.filePath),
515 'content-length': req.stats.size,
516 }));
517 fs__default['default'].createReadStream(req.filePath).pipe(res);
518 }
519 serverCtx.logRequest(req, 200);
520 }
521 catch (e) {
522 serverCtx.serve500(req, res, e, 'serveFile');
523 }
524}
525function updateStyleUrls(url, oldCss) {
526 const versionId = url.searchParams.get('s-hmr');
527 const hmrUrls = url.searchParams.get('s-hmr-urls');
528 if (versionId && hmrUrls) {
529 hmrUrls.split(',').forEach((hmrUrl) => {
530 urlVersionIds.set(hmrUrl, versionId);
531 });
532 }
533 const reg = /url\((['"]?)(.*)\1\)/gi;
534 let result;
535 let newCss = oldCss;
536 while ((result = reg.exec(oldCss)) !== null) {
537 const oldUrl = result[2];
538 const parsedUrl = new URL(oldUrl, url);
539 const fileName = path__default['default'].basename(parsedUrl.pathname);
540 const versionId = urlVersionIds.get(fileName);
541 if (!versionId) {
542 continue;
543 }
544 parsedUrl.searchParams.set('s-hmr', versionId);
545 newCss = newCss.replace(oldUrl, parsedUrl.pathname);
546 }
547 return newCss;
548}
549const urlVersionIds = new Map();
550function appendDevServerClientScript(devServerConfig, req, content) {
551 var _a, _b, _c;
552 const devServerClientUrl = getDevServerClientUrl(devServerConfig, (_b = (_a = req.headers) === null || _a === void 0 ? void 0 : _a['x-forwarded-host']) !== null && _b !== void 0 ? _b : req.host, (_c = req.headers) === null || _c === void 0 ? void 0 : _c['x-forwarded-proto']);
553 const iframe = `<iframe title="Stencil Dev Server Connector ${version} &#9889;" src="${devServerClientUrl}" style="display:block;width:0;height:0;border:0;visibility:hidden" aria-hidden="true"></iframe>`;
554 return appendDevServerClientIframe(content, iframe);
555}
556function appendDevServerClientIframe(content, iframe) {
557 if (content.includes('</body>')) {
558 return content.replace('</body>', `${iframe}</body>`);
559 }
560 if (content.includes('</html>')) {
561 return content.replace('</html>', `${iframe}</html>`);
562 }
563 return `${content}${iframe}`;
564}
565
566async function serveOpenInEditor(serverCtx, req, res) {
567 let status = 200;
568 const data = {};
569 try {
570 const editors = await getEditors();
571 if (editors.length > 0) {
572 await parseData(editors, serverCtx.sys, req, data);
573 await openDataInEditor(data);
574 }
575 else {
576 data.error = `no editors available`;
577 }
578 }
579 catch (e) {
580 data.error = e + '';
581 status = 500;
582 }
583 serverCtx.logRequest(req, status);
584 res.writeHead(status, responseHeaders({
585 'content-type': 'application/json; charset=utf-8',
586 }));
587 res.write(JSON.stringify(data, null, 2));
588 res.end();
589}
590async function parseData(editors, sys, req, data) {
591 const qs = req.searchParams;
592 if (!qs.has('file')) {
593 data.error = `missing file`;
594 return;
595 }
596 data.file = qs.get('file');
597 if (qs.has('line') && !isNaN(qs.get('line'))) {
598 data.line = parseInt(qs.get('line'), 10);
599 }
600 if (typeof data.line !== 'number' || data.line < 1) {
601 data.line = 1;
602 }
603 if (qs.has('column') && !isNaN(qs.get('column'))) {
604 data.column = parseInt(qs.get('column'), 10);
605 }
606 if (typeof data.column !== 'number' || data.column < 1) {
607 data.column = 1;
608 }
609 let editor = qs.get('editor');
610 if (typeof editor === 'string') {
611 editor = editor.trim().toLowerCase();
612 if (editors.some((e) => e.id === editor)) {
613 data.editor = editor;
614 }
615 else {
616 data.error = `invalid editor: ${editor}`;
617 return;
618 }
619 }
620 else {
621 data.editor = editors[0].id;
622 }
623 const stat = await sys.stat(data.file);
624 data.exists = stat.isFile;
625}
626async function openDataInEditor(data) {
627 if (!data.exists || data.error) {
628 return;
629 }
630 try {
631 const opts = {
632 editor: data.editor,
633 };
634 const editor = openInEditorApi__default['default'].configure(opts, (err) => (data.error = err + ''));
635 if (data.error) {
636 return;
637 }
638 data.open = `${data.file}:${data.line}:${data.column}`;
639 await editor.open(data.open);
640 }
641 catch (e) {
642 data.error = e + '';
643 }
644}
645let editors = null;
646function getEditors() {
647 if (!editors) {
648 editors = new Promise(async (resolve) => {
649 const editors = [];
650 try {
651 await Promise.all(Object.keys(openInEditorApi__default['default'].editors).map(async (editorId) => {
652 const isSupported = await isEditorSupported(editorId);
653 editors.push({
654 id: editorId,
655 priority: EDITOR_PRIORITY[editorId],
656 supported: isSupported,
657 });
658 }));
659 }
660 catch (e) { }
661 resolve(editors
662 .filter((e) => e.supported)
663 .sort((a, b) => {
664 if (a.priority < b.priority)
665 return -1;
666 if (a.priority > b.priority)
667 return 1;
668 return 0;
669 })
670 .map((e) => {
671 return {
672 id: e.id,
673 name: EDITORS[e.id],
674 };
675 }));
676 });
677 }
678 return editors;
679}
680async function isEditorSupported(editorId) {
681 let isSupported = false;
682 try {
683 await openInEditorApi__default['default'].editors[editorId].detect();
684 isSupported = true;
685 }
686 catch (e) { }
687 return isSupported;
688}
689const EDITORS = {
690 atom: 'Atom',
691 code: 'Code',
692 emacs: 'Emacs',
693 idea14ce: 'IDEA 14 Community Edition',
694 phpstorm: 'PhpStorm',
695 sublime: 'Sublime',
696 webstorm: 'WebStorm',
697 vim: 'Vim',
698 visualstudio: 'Visual Studio',
699};
700const EDITOR_PRIORITY = {
701 code: 1,
702 atom: 2,
703 sublime: 3,
704 visualstudio: 4,
705 idea14ce: 5,
706 webstorm: 6,
707 phpstorm: 7,
708 vim: 8,
709 emacs: 9,
710};
711
712async function serveDevClient(devServerConfig, serverCtx, req, res) {
713 try {
714 if (isOpenInEditor(req.pathname)) {
715 return serveOpenInEditor(serverCtx, req, res);
716 }
717 if (isDevServerClient(req.pathname)) {
718 return serveDevClientScript(devServerConfig, serverCtx, req, res);
719 }
720 if (isInitialDevServerLoad(req.pathname)) {
721 req.filePath = path__default['default'].join(devServerConfig.devServerDir, 'templates', 'initial-load.html');
722 }
723 else {
724 const staticFile = req.pathname.replace(DEV_SERVER_URL + '/', '');
725 req.filePath = path__default['default'].join(devServerConfig.devServerDir, 'static', staticFile);
726 }
727 try {
728 req.stats = await serverCtx.sys.stat(req.filePath);
729 if (req.stats.isFile) {
730 return serveFile(devServerConfig, serverCtx, req, res);
731 }
732 return serverCtx.serve404(req, res, 'serveDevClient not file');
733 }
734 catch (e) {
735 return serverCtx.serve404(req, res, `serveDevClient stats error ${e}`);
736 }
737 }
738 catch (e) {
739 return serverCtx.serve500(req, res, e, 'serveDevClient');
740 }
741}
742async function serveDevClientScript(devServerConfig, serverCtx, req, res) {
743 try {
744 if (serverCtx.connectorHtml == null) {
745 const filePath = path__default['default'].join(devServerConfig.devServerDir, 'connector.html');
746 serverCtx.connectorHtml = serverCtx.sys.readFileSync(filePath, 'utf8');
747 if (typeof serverCtx.connectorHtml !== 'string') {
748 return serverCtx.serve404(req, res, `serveDevClientScript`);
749 }
750 const devClientConfig = {
751 basePath: devServerConfig.basePath,
752 editors: await getEditors(),
753 reloadStrategy: devServerConfig.reloadStrategy,
754 };
755 serverCtx.connectorHtml = serverCtx.connectorHtml.replace('window.__DEV_CLIENT_CONFIG__', JSON.stringify(devClientConfig));
756 }
757 res.writeHead(200, responseHeaders({
758 'content-type': 'text/html; charset=utf-8',
759 }));
760 res.write(serverCtx.connectorHtml);
761 res.end();
762 }
763 catch (e) {
764 return serverCtx.serve500(req, res, e, `serveDevClientScript`);
765 }
766}
767
768async function serveDevNodeModule(serverCtx, req, res) {
769 try {
770 const results = await serverCtx.getCompilerRequest(req.pathname);
771 const headers = {
772 'content-type': 'application/javascript; charset=utf-8',
773 'content-length': Buffer.byteLength(results.content, 'utf8'),
774 'x-dev-node-module-id': results.nodeModuleId,
775 'x-dev-node-module-version': results.nodeModuleVersion,
776 'x-dev-node-module-resolved-path': results.nodeResolvedPath,
777 'x-dev-node-module-cache-path': results.cachePath,
778 'x-dev-node-module-cache-hit': results.cacheHit,
779 };
780 res.writeHead(results.status, responseHeaders(headers));
781 res.write(results.content);
782 res.end();
783 }
784 catch (e) {
785 serverCtx.serve500(req, res, e, `serveDevNodeModule`);
786 }
787}
788
789async function serveDirectoryIndex(devServerConfig, serverCtx, req, res) {
790 const indexFilePath = path__default['default'].join(req.filePath, 'index.html');
791 req.stats = await serverCtx.sys.stat(indexFilePath);
792 if (req.stats.isFile) {
793 req.filePath = indexFilePath;
794 return serveFile(devServerConfig, serverCtx, req, res);
795 }
796 if (!req.pathname.endsWith('/')) {
797 return serverCtx.serve302(req, res, req.pathname + '/');
798 }
799 try {
800 const dirFilePaths = await serverCtx.sys.readDir(req.filePath);
801 try {
802 if (serverCtx.dirTemplate == null) {
803 const dirTemplatePath = path__default['default'].join(devServerConfig.devServerDir, 'templates', 'directory-index.html');
804 serverCtx.dirTemplate = serverCtx.sys.readFileSync(dirTemplatePath);
805 }
806 const files = await getFiles(serverCtx.sys, req.url, dirFilePaths);
807 const templateHtml = serverCtx.dirTemplate
808 .replace('{{title}}', getTitle(req.pathname))
809 .replace('{{nav}}', getName(req.pathname))
810 .replace('{{files}}', files);
811 serverCtx.logRequest(req, 200);
812 res.writeHead(200, responseHeaders({
813 'content-type': 'text/html; charset=utf-8',
814 'x-directory-index': req.pathname,
815 }));
816 res.write(templateHtml);
817 res.end();
818 }
819 catch (e) {
820 return serverCtx.serve500(req, res, e, 'serveDirectoryIndex');
821 }
822 }
823 catch (e) {
824 return serverCtx.serve404(req, res, 'serveDirectoryIndex');
825 }
826}
827async function getFiles(sys, baseUrl, dirItemNames) {
828 const items = await getDirectoryItems(sys, baseUrl, dirItemNames);
829 if (baseUrl.pathname !== '/') {
830 items.unshift({
831 isDirectory: true,
832 pathname: '../',
833 name: '..',
834 });
835 }
836 return items
837 .map((item) => {
838 return `
839 <li class="${item.isDirectory ? 'directory' : 'file'}">
840 <a href="${item.pathname}">
841 <span class="icon"></span>
842 <span>${item.name}</span>
843 </a>
844 </li>`;
845 })
846 .join('');
847}
848async function getDirectoryItems(sys, baseUrl, dirFilePaths) {
849 const items = await Promise.all(dirFilePaths.map(async (dirFilePath) => {
850 const fileName = path__default['default'].basename(dirFilePath);
851 const url = new URL(fileName, baseUrl);
852 const stats = await sys.stat(dirFilePath);
853 const item = {
854 name: fileName,
855 pathname: url.pathname,
856 isDirectory: stats.isDirectory,
857 };
858 return item;
859 }));
860 return items;
861}
862function getTitle(pathName) {
863 return pathName;
864}
865function getName(pathName) {
866 const dirs = pathName.split('/');
867 dirs.pop();
868 let url = '';
869 return (dirs
870 .map((dir, index) => {
871 url += dir + '/';
872 const text = index === 0 ? `~` : dir;
873 return `<a href="${url}">${text}</a>`;
874 })
875 .join('<span>/</span>') + '<span>/</span>');
876}
877
878async function ssrPageRequest(devServerConfig, serverCtx, req, res) {
879 try {
880 let status = 500;
881 let content = '';
882 const { hydrateApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
883 if (!diagnostics.some((diagnostic) => diagnostic.level === 'error')) {
884 try {
885 const opts = getSsrHydrateOptions(devServerConfig, serverCtx, req.url);
886 const ssrResults = await hydrateApp.renderToString(srcIndexHtml, opts);
887 diagnostics.push(...ssrResults.diagnostics);
888 status = ssrResults.httpStatus;
889 content = ssrResults.html;
890 }
891 catch (e) {
892 catchError(diagnostics, e);
893 }
894 }
895 if (diagnostics.some((diagnostic) => diagnostic.level === 'error')) {
896 content = getSsrErrorContent(diagnostics);
897 status = 500;
898 }
899 if (devServerConfig.websocket) {
900 content = appendDevServerClientScript(devServerConfig, req, content);
901 }
902 serverCtx.logRequest(req, status);
903 res.writeHead(status, responseHeaders({
904 'content-type': 'text/html; charset=utf-8',
905 'content-length': Buffer.byteLength(content, 'utf8'),
906 }));
907 res.write(content);
908 res.end();
909 }
910 catch (e) {
911 serverCtx.serve500(req, res, e, `ssrPageRequest`);
912 }
913}
914async function ssrStaticDataRequest(devServerConfig, serverCtx, req, res) {
915 try {
916 const data = {};
917 let httpCache = false;
918 const { hydrateApp, srcIndexHtml, diagnostics } = await setupHydrateApp(devServerConfig, serverCtx);
919 if (!diagnostics.some((diagnostic) => diagnostic.level === 'error')) {
920 try {
921 const { ssrPath, hasQueryString } = getSsrStaticDataPath(req);
922 const url = new URL(ssrPath, req.url);
923 const opts = getSsrHydrateOptions(devServerConfig, serverCtx, url);
924 const ssrResults = await hydrateApp.renderToString(srcIndexHtml, opts);
925 diagnostics.push(...ssrResults.diagnostics);
926 ssrResults.staticData.forEach((s) => {
927 if (s.type === 'application/json') {
928 data[s.id] = JSON.parse(s.content);
929 }
930 else {
931 data[s.id] = s.content;
932 }
933 });
934 data.components = ssrResults.components.map((c) => c.tag).sort();
935 httpCache = hasQueryString;
936 }
937 catch (e) {
938 catchError(diagnostics, e);
939 }
940 }
941 if (diagnostics.length > 0) {
942 data.diagnostics = diagnostics;
943 }
944 const status = diagnostics.some((diagnostic) => diagnostic.level === 'error') ? 500 : 200;
945 const content = JSON.stringify(data);
946 serverCtx.logRequest(req, status);
947 res.writeHead(status, responseHeaders({
948 'content-type': 'application/json; charset=utf-8',
949 'content-length': Buffer.byteLength(content, 'utf8'),
950 }, httpCache && status === 200));
951 res.write(content);
952 res.end();
953 }
954 catch (e) {
955 serverCtx.serve500(req, res, e, `ssrStaticDataRequest`);
956 }
957}
958async function setupHydrateApp(devServerConfig, serverCtx) {
959 let srcIndexHtml = null;
960 let hydrateApp = null;
961 const buildResults = await serverCtx.getBuildResults();
962 const diagnostics = [];
963 if (serverCtx.prerenderConfig == null && isString(devServerConfig.prerenderConfig)) {
964 const compilerPath = path__default['default'].join(devServerConfig.devServerDir, '..', 'compiler', 'stencil.js');
965 const compiler = require(compilerPath);
966 const prerenderConfigResults = compiler.nodeRequire(devServerConfig.prerenderConfig);
967 diagnostics.push(...prerenderConfigResults.diagnostics);
968 if (prerenderConfigResults.module && prerenderConfigResults.module.config) {
969 serverCtx.prerenderConfig = prerenderConfigResults.module.config;
970 }
971 }
972 if (!isString(buildResults.hydrateAppFilePath)) {
973 diagnostics.push({ messageText: `Missing hydrateAppFilePath`, level: `error`, type: `ssr` });
974 }
975 else if (!isString(devServerConfig.srcIndexHtml)) {
976 diagnostics.push({ messageText: `Missing srcIndexHtml`, level: `error`, type: `ssr` });
977 }
978 else {
979 srcIndexHtml = await serverCtx.sys.readFile(devServerConfig.srcIndexHtml);
980 if (!isString(srcIndexHtml)) {
981 diagnostics.push({
982 messageText: `Unable to load src index html: ${devServerConfig.srcIndexHtml}`,
983 level: `error`,
984 type: `ssr`,
985 });
986 }
987 else {
988 // ensure we cleared out node's internal require() cache for this file
989 const hydrateAppFilePath = path__default['default'].resolve(buildResults.hydrateAppFilePath);
990 // brute force way of clearning node's module cache
991 // not using `delete require.cache[id]` since it'll cause memory leaks
992 require.cache = {};
993 const Module = require('module');
994 Module._cache[hydrateAppFilePath] = undefined;
995 hydrateApp = require(hydrateAppFilePath);
996 }
997 }
998 return {
999 hydrateApp,
1000 srcIndexHtml,
1001 diagnostics,
1002 };
1003}
1004function getSsrHydrateOptions(devServerConfig, serverCtx, url) {
1005 const opts = {
1006 url: url.href,
1007 addModulePreloads: false,
1008 approximateLineWidth: 120,
1009 inlineExternalStyleSheets: false,
1010 minifyScriptElements: false,
1011 minifyStyleElements: false,
1012 removeAttributeQuotes: false,
1013 removeBooleanAttributeQuotes: false,
1014 removeEmptyAttributes: false,
1015 removeHtmlComments: false,
1016 prettyHtml: true,
1017 };
1018 const prerenderConfig = serverCtx === null || serverCtx === void 0 ? void 0 : serverCtx.prerenderConfig;
1019 if (isFunction(prerenderConfig === null || prerenderConfig === void 0 ? void 0 : prerenderConfig.hydrateOptions)) {
1020 const userOpts = prerenderConfig.hydrateOptions(url);
1021 if (userOpts) {
1022 Object.assign(opts, userOpts);
1023 }
1024 }
1025 if (isFunction(serverCtx.sys.applyPrerenderGlobalPatch)) {
1026 const orgBeforeHydrate = opts.beforeHydrate;
1027 opts.beforeHydrate = (document) => {
1028 // patch this new window with the fetch global from node-fetch
1029 const devServerBaseUrl = new URL(devServerConfig.browserUrl);
1030 const devServerHostUrl = devServerBaseUrl.origin;
1031 serverCtx.sys.applyPrerenderGlobalPatch({
1032 devServerHostUrl: devServerHostUrl,
1033 window: document.defaultView,
1034 });
1035 if (typeof orgBeforeHydrate === 'function') {
1036 return orgBeforeHydrate(document);
1037 }
1038 };
1039 }
1040 return opts;
1041}
1042function getSsrErrorContent(diagnostics) {
1043 return `<!doctype html>
1044<html>
1045<head>
1046 <title>SSR Error</title>
1047 <style>
1048 body {
1049 font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace !important;
1050 }
1051 </style>
1052</head>
1053<body>
1054 <h1>SSR Dev Error</h1>
1055 ${diagnostics.map((diagnostic) => `
1056 <p>
1057 ${diagnostic.messageText}
1058 </p>
1059 `)}
1060</body>
1061</html>`;
1062}
1063
1064function createRequestHandler(devServerConfig, serverCtx) {
1065 let userRequestHandler = null;
1066 if (typeof devServerConfig.requestListenerPath === 'string') {
1067 userRequestHandler = require(devServerConfig.requestListenerPath);
1068 }
1069 return async function (incomingReq, res) {
1070 async function defaultHandler() {
1071 try {
1072 const req = normalizeHttpRequest(devServerConfig, incomingReq);
1073 if (!req.url) {
1074 return serverCtx.serve302(req, res);
1075 }
1076 if (isDevClient(req.pathname) && devServerConfig.websocket) {
1077 return serveDevClient(devServerConfig, serverCtx, req, res);
1078 }
1079 if (isDevModule(req.pathname)) {
1080 return serveDevNodeModule(serverCtx, req, res);
1081 }
1082 if (!isValidUrlBasePath(devServerConfig.basePath, req.url)) {
1083 return serverCtx.serve404(req, res, `invalid basePath`, `404 File Not Found, base path: ${devServerConfig.basePath}`);
1084 }
1085 if (devServerConfig.ssr) {
1086 if (isExtensionLessPath(req.url.pathname)) {
1087 return ssrPageRequest(devServerConfig, serverCtx, req, res);
1088 }
1089 if (isSsrStaticDataPath(req.url.pathname)) {
1090 return ssrStaticDataRequest(devServerConfig, serverCtx, req, res);
1091 }
1092 }
1093 req.stats = await serverCtx.sys.stat(req.filePath);
1094 if (req.stats.isFile) {
1095 return serveFile(devServerConfig, serverCtx, req, res);
1096 }
1097 if (req.stats.isDirectory) {
1098 return serveDirectoryIndex(devServerConfig, serverCtx, req, res);
1099 }
1100 const xSource = ['notfound'];
1101 const validHistoryApi = isValidHistoryApi(devServerConfig, req);
1102 xSource.push(`validHistoryApi: ${validHistoryApi}`);
1103 if (validHistoryApi) {
1104 try {
1105 const indexFilePath = path__default['default'].join(devServerConfig.root, devServerConfig.historyApiFallback.index);
1106 xSource.push(`indexFilePath: ${indexFilePath}`);
1107 req.stats = await serverCtx.sys.stat(indexFilePath);
1108 if (req.stats.isFile) {
1109 req.filePath = indexFilePath;
1110 return serveFile(devServerConfig, serverCtx, req, res);
1111 }
1112 }
1113 catch (e) {
1114 xSource.push(`notfound error: ${e}`);
1115 }
1116 }
1117 return serverCtx.serve404(req, res, xSource.join(', '));
1118 }
1119 catch (e) {
1120 return serverCtx.serve500(incomingReq, res, e, `not found error`);
1121 }
1122 }
1123 if (typeof userRequestHandler === 'function') {
1124 await userRequestHandler(incomingReq, res, defaultHandler);
1125 }
1126 else {
1127 await defaultHandler();
1128 }
1129 };
1130}
1131function isValidUrlBasePath(basePath, url) {
1132 // normalize the paths to always end with a slash for the check
1133 let pathname = url.pathname;
1134 if (!pathname.endsWith('/')) {
1135 pathname += '/';
1136 }
1137 if (!basePath.endsWith('/')) {
1138 basePath += '/';
1139 }
1140 return pathname.startsWith(basePath);
1141}
1142function normalizeHttpRequest(devServerConfig, incomingReq) {
1143 const req = {
1144 method: (incomingReq.method || 'GET').toUpperCase(),
1145 headers: incomingReq.headers,
1146 acceptHeader: (incomingReq.headers && typeof incomingReq.headers.accept === 'string' && incomingReq.headers.accept) || '',
1147 host: (incomingReq.headers && typeof incomingReq.headers.host === 'string' && incomingReq.headers.host) || null,
1148 url: null,
1149 searchParams: null,
1150 };
1151 const incomingUrl = (incomingReq.url || '').trim() || null;
1152 if (incomingUrl) {
1153 if (req.host) {
1154 req.url = new URL(incomingReq.url, `http://${req.host}`);
1155 }
1156 else {
1157 req.url = new URL(incomingReq.url, `http://dev.stenciljs.com`);
1158 }
1159 req.searchParams = req.url.searchParams;
1160 }
1161 if (req.url) {
1162 const parts = req.url.pathname.replace(/\\/g, '/').split('/');
1163 req.pathname = parts.map((part) => decodeURIComponent(part)).join('/');
1164 if (req.pathname.length > 0 && !isDevClient(req.pathname)) {
1165 req.pathname = '/' + req.pathname.substring(devServerConfig.basePath.length);
1166 }
1167 req.filePath = normalizePath(path__default['default'].normalize(path__default['default'].join(devServerConfig.root, path__default['default'].relative('/', req.pathname))));
1168 }
1169 return req;
1170}
1171function isValidHistoryApi(devServerConfig, req) {
1172 if (!devServerConfig.historyApiFallback) {
1173 return false;
1174 }
1175 if (req.method !== 'GET') {
1176 return false;
1177 }
1178 if (!req.acceptHeader.includes('text/html')) {
1179 return false;
1180 }
1181 if (!devServerConfig.historyApiFallback.disableDotRule && req.pathname.includes('.')) {
1182 return false;
1183 }
1184 return true;
1185}
1186
1187function createHttpServer(devServerConfig, serverCtx) {
1188 // create our request handler
1189 const reqHandler = createRequestHandler(devServerConfig, serverCtx);
1190 const credentials = devServerConfig.https;
1191 return credentials ? https__namespace.createServer(credentials, reqHandler) : http__namespace.createServer(reqHandler);
1192}
1193async function findClosestOpenPort(host, port) {
1194 async function t(portToCheck) {
1195 const isTaken = await isPortTaken(host, portToCheck);
1196 if (!isTaken) {
1197 return portToCheck;
1198 }
1199 return t(portToCheck + 1);
1200 }
1201 return t(port);
1202}
1203function isPortTaken(host, port) {
1204 return new Promise((resolve, reject) => {
1205 const tester = net__namespace
1206 .createServer()
1207 .once('error', () => {
1208 resolve(true);
1209 })
1210 .once('listening', () => {
1211 tester
1212 .once('close', () => {
1213 resolve(false);
1214 })
1215 .close();
1216 })
1217 .on('error', (err) => {
1218 reject(err);
1219 })
1220 .listen(port, host);
1221 });
1222}
1223
1224function createWebSocket(httpServer, onMessageFromClient) {
1225 const wsConfig = {
1226 server: httpServer,
1227 };
1228 const wsServer = new ws__namespace.Server(wsConfig);
1229 function heartbeat() {
1230 this.isAlive = true;
1231 }
1232 wsServer.on('connection', (ws) => {
1233 ws.on('message', (data) => {
1234 // the server process has received a message from the browser
1235 // pass the message received from the browser to the main cli process
1236 try {
1237 onMessageFromClient(JSON.parse(data.toString()));
1238 }
1239 catch (e) {
1240 console.error(e);
1241 }
1242 });
1243 ws.isAlive = true;
1244 ws.on('pong', heartbeat);
1245 // ignore invalid close frames sent by Safari 15
1246 ws.on('error', console.error);
1247 });
1248 const pingInternval = setInterval(() => {
1249 wsServer.clients.forEach((ws) => {
1250 if (!ws.isAlive) {
1251 return ws.close(1000);
1252 }
1253 ws.isAlive = false;
1254 ws.ping(noop);
1255 });
1256 }, 10000);
1257 return {
1258 sendToBrowser: (msg) => {
1259 if (msg && wsServer && wsServer.clients) {
1260 const data = JSON.stringify(msg);
1261 wsServer.clients.forEach((ws) => {
1262 if (ws.readyState === ws.OPEN) {
1263 ws.send(data);
1264 }
1265 });
1266 }
1267 },
1268 close: () => {
1269 return new Promise((resolve, reject) => {
1270 clearInterval(pingInternval);
1271 wsServer.clients.forEach((ws) => {
1272 ws.close(1000);
1273 });
1274 wsServer.close((err) => {
1275 if (err) {
1276 reject(err);
1277 }
1278 else {
1279 resolve();
1280 }
1281 });
1282 });
1283 },
1284 };
1285}
1286
1287function createCommonjsModule(fn, basedir, module) {
1288 return module = {
1289 path: basedir,
1290 exports: {},
1291 require: function (path, base) {
1292 return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
1293 }
1294 }, fn(module, module.exports), module.exports;
1295}
1296
1297function commonjsRequire () {
1298 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
1299}
1300
1301let isDocker;
1302
1303function hasDockerEnv() {
1304 try {
1305 fs__default$1['default'].statSync('/.dockerenv');
1306 return true;
1307 } catch (_) {
1308 return false;
1309 }
1310}
1311
1312function hasDockerCGroup() {
1313 try {
1314 return fs__default$1['default'].readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
1315 } catch (_) {
1316 return false;
1317 }
1318}
1319
1320var isDocker_1 = () => {
1321 if (isDocker === undefined) {
1322 isDocker = hasDockerEnv() || hasDockerCGroup();
1323 }
1324
1325 return isDocker;
1326};
1327
1328var isWsl_1 = createCommonjsModule(function (module) {
1329
1330
1331
1332
1333const isWsl = () => {
1334 if (process.platform !== 'linux') {
1335 return false;
1336 }
1337
1338 if (os__default['default'].release().toLowerCase().includes('microsoft')) {
1339 if (isDocker_1()) {
1340 return false;
1341 }
1342
1343 return true;
1344 }
1345
1346 try {
1347 return fs__default$1['default'].readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
1348 !isDocker_1() : false;
1349 } catch (_) {
1350 return false;
1351 }
1352};
1353
1354if (process.env.__IS_WSL_TEST__) {
1355 module.exports = isWsl;
1356} else {
1357 module.exports = isWsl();
1358}
1359});
1360
1361var defineLazyProp = (object, propertyName, fn) => {
1362 const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
1363
1364 Object.defineProperty(object, propertyName, {
1365 configurable: true,
1366 enumerable: true,
1367 get() {
1368 const result = fn();
1369 define(result);
1370 return result;
1371 },
1372 set(value) {
1373 define(value);
1374 }
1375 });
1376
1377 return object;
1378};
1379
1380const {promises: fs, constants: fsConstants} = fs__default$1['default'];
1381
1382
1383
1384
1385// Path to included `xdg-open`.
1386const localXdgOpenPath = path__default['default'].join(__dirname, 'xdg-open');
1387
1388const {platform, arch} = process;
1389
1390/**
1391Get the mount point for fixed drives in WSL.
1392
1393@inner
1394@returns {string} The mount point.
1395*/
1396const getWslDrivesMountPoint = (() => {
1397 // Default value for "root" param
1398 // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
1399 const defaultMountPoint = '/mnt/';
1400
1401 let mountPoint;
1402
1403 return async function () {
1404 if (mountPoint) {
1405 // Return memoized mount point value
1406 return mountPoint;
1407 }
1408
1409 const configFilePath = '/etc/wsl.conf';
1410
1411 let isConfigFileExists = false;
1412 try {
1413 await fs.access(configFilePath, fsConstants.F_OK);
1414 isConfigFileExists = true;
1415 } catch {}
1416
1417 if (!isConfigFileExists) {
1418 return defaultMountPoint;
1419 }
1420
1421 const configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});
1422 const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
1423
1424 if (!configMountPoint) {
1425 return defaultMountPoint;
1426 }
1427
1428 mountPoint = configMountPoint.groups.mountPoint.trim();
1429 mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
1430
1431 return mountPoint;
1432 };
1433})();
1434
1435const pTryEach = async (array, mapper) => {
1436 let latestError;
1437
1438 for (const item of array) {
1439 try {
1440 return await mapper(item); // eslint-disable-line no-await-in-loop
1441 } catch (error) {
1442 latestError = error;
1443 }
1444 }
1445
1446 throw latestError;
1447};
1448
1449const open = async (target, options) => {
1450 if (typeof target !== 'string') {
1451 throw new TypeError('Expected a `target`');
1452 }
1453
1454 options = {
1455 wait: false,
1456 background: false,
1457 newInstance: false,
1458 allowNonzeroExitCode: false,
1459 ...options
1460 };
1461
1462 if (Array.isArray(options.app)) {
1463 return pTryEach(options.app, singleApp => open(target, {
1464 ...options,
1465 app: singleApp
1466 }));
1467 }
1468
1469 let {name: app, arguments: appArguments = []} = options.app || {};
1470 appArguments = [...appArguments];
1471
1472 if (Array.isArray(app)) {
1473 return pTryEach(app, appName => open(target, {
1474 ...options,
1475 app: {
1476 name: appName,
1477 arguments: appArguments
1478 }
1479 }));
1480 }
1481
1482 let command;
1483 const cliArguments = [];
1484 const childProcessOptions = {};
1485
1486 if (platform === 'darwin') {
1487 command = 'open';
1488
1489 if (options.wait) {
1490 cliArguments.push('--wait-apps');
1491 }
1492
1493 if (options.background) {
1494 cliArguments.push('--background');
1495 }
1496
1497 if (options.newInstance) {
1498 cliArguments.push('--new');
1499 }
1500
1501 if (app) {
1502 cliArguments.push('-a', app);
1503 }
1504 } else if (platform === 'win32' || (isWsl_1 && !isDocker_1())) {
1505 const mountPoint = await getWslDrivesMountPoint();
1506
1507 command = isWsl_1 ?
1508 `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
1509 `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
1510
1511 cliArguments.push(
1512 '-NoProfile',
1513 '-NonInteractive',
1514 '–ExecutionPolicy',
1515 'Bypass',
1516 '-EncodedCommand'
1517 );
1518
1519 if (!isWsl_1) {
1520 childProcessOptions.windowsVerbatimArguments = true;
1521 }
1522
1523 const encodedArguments = ['Start'];
1524
1525 if (options.wait) {
1526 encodedArguments.push('-Wait');
1527 }
1528
1529 if (app) {
1530 // Double quote with double quotes to ensure the inner quotes are passed through.
1531 // Inner quotes are delimited for PowerShell interpretation with backticks.
1532 encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
1533 appArguments.unshift(target);
1534 } else {
1535 encodedArguments.push(`"${target}"`);
1536 }
1537
1538 if (appArguments.length > 0) {
1539 appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
1540 encodedArguments.push(appArguments.join(','));
1541 }
1542
1543 // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
1544 target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
1545 } else {
1546 if (app) {
1547 command = app;
1548 } else {
1549 // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
1550 const isBundled = !__dirname || __dirname === '/';
1551
1552 // Check if local `xdg-open` exists and is executable.
1553 let exeLocalXdgOpen = false;
1554 try {
1555 await fs.access(localXdgOpenPath, fsConstants.X_OK);
1556 exeLocalXdgOpen = true;
1557 } catch {}
1558
1559 const useSystemXdgOpen = process.versions.electron ||
1560 platform === 'android' || isBundled || !exeLocalXdgOpen;
1561 command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
1562 }
1563
1564 if (appArguments.length > 0) {
1565 cliArguments.push(...appArguments);
1566 }
1567
1568 if (!options.wait) {
1569 // `xdg-open` will block the process unless stdio is ignored
1570 // and it's detached from the parent even if it's unref'd.
1571 childProcessOptions.stdio = 'ignore';
1572 childProcessOptions.detached = true;
1573 }
1574 }
1575
1576 cliArguments.push(target);
1577
1578 if (platform === 'darwin' && appArguments.length > 0) {
1579 cliArguments.push('--args', ...appArguments);
1580 }
1581
1582 const subprocess = childProcess__default['default'].spawn(command, cliArguments, childProcessOptions);
1583
1584 if (options.wait) {
1585 return new Promise((resolve, reject) => {
1586 subprocess.once('error', reject);
1587
1588 subprocess.once('close', exitCode => {
1589 if (options.allowNonzeroExitCode && exitCode > 0) {
1590 reject(new Error(`Exited with code ${exitCode}`));
1591 return;
1592 }
1593
1594 resolve(subprocess);
1595 });
1596 });
1597 }
1598
1599 subprocess.unref();
1600
1601 return subprocess;
1602};
1603
1604function detectArchBinary(binary) {
1605 if (typeof binary === 'string' || Array.isArray(binary)) {
1606 return binary;
1607 }
1608
1609 const {[arch]: archBinary} = binary;
1610
1611 if (!archBinary) {
1612 throw new Error(`${arch} is not supported`);
1613 }
1614
1615 return archBinary;
1616}
1617
1618function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
1619 if (wsl && isWsl_1) {
1620 return detectArchBinary(wsl);
1621 }
1622
1623 if (!platformBinary) {
1624 throw new Error(`${platform} is not supported`);
1625 }
1626
1627 return detectArchBinary(platformBinary);
1628}
1629
1630const apps = {};
1631
1632defineLazyProp(apps, 'chrome', () => detectPlatformBinary({
1633 darwin: 'google chrome',
1634 win32: 'chrome',
1635 linux: ['google-chrome', 'google-chrome-stable']
1636}, {
1637 wsl: {
1638 ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
1639 x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
1640 }
1641}));
1642
1643defineLazyProp(apps, 'firefox', () => detectPlatformBinary({
1644 darwin: 'firefox',
1645 win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
1646 linux: 'firefox'
1647}, {
1648 wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
1649}));
1650
1651defineLazyProp(apps, 'edge', () => detectPlatformBinary({
1652 darwin: 'microsoft edge',
1653 win32: 'msedge',
1654 linux: 'microsoft-edge'
1655}, {
1656 wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
1657}));
1658
1659open.apps = apps;
1660
1661var open_1 = open;
1662
1663async function openInBrowser(opts) {
1664 // await open(opts.url, { app: ['google chrome', '--auto-open-devtools-for-tabs'] });
1665 await open_1(opts.url);
1666}
1667
1668function initServerProcess(sendMsg) {
1669 let server = null;
1670 let webSocket = null;
1671 let serverCtx = null;
1672 const buildResultsResolves = [];
1673 const compilerRequestResolves = [];
1674 const startServer = async (msg) => {
1675 const devServerConfig = msg.startServer;
1676 devServerConfig.port = await findClosestOpenPort(devServerConfig.address, devServerConfig.port);
1677 devServerConfig.browserUrl = getBrowserUrl(devServerConfig.protocol, devServerConfig.address, devServerConfig.port, devServerConfig.basePath, '/');
1678 devServerConfig.root = normalizePath(devServerConfig.root);
1679 const sys = index_js.createNodeSys({ process });
1680 serverCtx = createServerContext(sys, sendMsg, devServerConfig, buildResultsResolves, compilerRequestResolves);
1681 server = createHttpServer(devServerConfig, serverCtx);
1682 webSocket = devServerConfig.websocket ? createWebSocket(server, sendMsg) : null;
1683 server.listen(devServerConfig.port, devServerConfig.address);
1684 serverCtx.isServerListening = true;
1685 if (devServerConfig.openBrowser) {
1686 const initialLoadUrl = getBrowserUrl(devServerConfig.protocol, devServerConfig.address, devServerConfig.port, devServerConfig.basePath, devServerConfig.initialLoadUrl || DEV_SERVER_INIT_URL);
1687 openInBrowser({ url: initialLoadUrl });
1688 }
1689 sendMsg({ serverStarted: devServerConfig });
1690 };
1691 const closeServer = () => {
1692 const promises = [];
1693 buildResultsResolves.forEach((r) => r.reject('dev server closed'));
1694 buildResultsResolves.length = 0;
1695 compilerRequestResolves.forEach((r) => r.reject('dev server closed'));
1696 compilerRequestResolves.length = 0;
1697 if (serverCtx) {
1698 if (serverCtx.sys) {
1699 promises.push(serverCtx.sys.destroy());
1700 }
1701 }
1702 if (webSocket) {
1703 promises.push(webSocket.close());
1704 webSocket = null;
1705 }
1706 if (server) {
1707 promises.push(new Promise((resolve) => {
1708 server.close((err) => {
1709 if (err) {
1710 console.error(`close error: ${err}`);
1711 }
1712 resolve();
1713 });
1714 }));
1715 }
1716 Promise.all(promises).finally(() => {
1717 sendMsg({
1718 serverClosed: true,
1719 });
1720 });
1721 };
1722 const receiveMessageFromMain = (msg) => {
1723 // the server process received a message from main thread
1724 try {
1725 if (msg) {
1726 if (msg.startServer) {
1727 startServer(msg);
1728 }
1729 else if (msg.closeServer) {
1730 closeServer();
1731 }
1732 else if (msg.compilerRequestResults) {
1733 for (let i = compilerRequestResolves.length - 1; i >= 0; i--) {
1734 const r = compilerRequestResolves[i];
1735 if (r.path === msg.compilerRequestResults.path) {
1736 r.resolve(msg.compilerRequestResults);
1737 compilerRequestResolves.splice(i, 1);
1738 }
1739 }
1740 }
1741 else if (serverCtx) {
1742 if (msg.buildResults && !msg.isActivelyBuilding) {
1743 buildResultsResolves.forEach((r) => r.resolve(msg.buildResults));
1744 buildResultsResolves.length = 0;
1745 }
1746 if (webSocket) {
1747 webSocket.sendToBrowser(msg);
1748 }
1749 }
1750 }
1751 }
1752 catch (e) {
1753 let stack = null;
1754 if (e instanceof Error) {
1755 stack = e.stack;
1756 }
1757 sendMsg({
1758 error: { message: e + '', stack },
1759 });
1760 }
1761 };
1762 return receiveMessageFromMain;
1763}
1764
1765exports.initServerProcess = initServerProcess;