├── .husky
├── .gitignore
└── pre-commit
├── .prettierrc
├── .gitattributes
├── spec
├── helpers
│ ├── configs
│ │ ├── js-or-json
│ │ │ ├── index.html
│ │ │ ├── spandx.config.json
│ │ │ └── spandx.config.js
│ │ ├── port-auto
│ │ │ ├── index.html
│ │ │ └── spandx.config.js
│ │ ├── route-order
│ │ │ ├── a
│ │ │ │ └── index.html
│ │ │ ├── index.html
│ │ │ ├── b
│ │ │ │ └── index.html
│ │ │ ├── c
│ │ │ │ └── index.html
│ │ │ └── spandx.config.js
│ │ ├── single
│ │ │ ├── foo
│ │ │ │ ├── index.html
│ │ │ │ └── bar
│ │ │ │ │ └── test.txt
│ │ │ └── spandx.config.js
│ │ ├── path-setting
│ │ │ ├── foo
│ │ │ │ ├── index.html
│ │ │ │ └── bar
│ │ │ │ │ └── index.html
│ │ │ └── index.html
│ │ ├── unconfigured-hostname
│ │ │ ├── index.html
│ │ │ └── spandx.config.js
│ │ ├── url-rewriting
│ │ │ ├── otherpage.html
│ │ │ ├── esi-fragment.html
│ │ │ ├── spandx.remote.js
│ │ │ ├── index.html
│ │ │ ├── index-esi.html
│ │ │ └── spandx.local.js
│ │ ├── root-and-subdir
│ │ │ ├── index.html
│ │ │ ├── subdir
│ │ │ │ └── index.html
│ │ │ ├── spandx.local.js
│ │ │ └── spandx.remote.js
│ │ ├── primer
│ │ │ ├── mock-primer-file
│ │ │ │ ├── head
│ │ │ │ │ ├── en
│ │ │ │ │ └── ko
│ │ │ │ ├── footer
│ │ │ │ │ ├── en
│ │ │ │ │ └── ko
│ │ │ │ └── header
│ │ │ │ │ ├── en
│ │ │ │ │ └── ko
│ │ │ ├── mock-primer-http
│ │ │ │ └── services
│ │ │ │ │ └── primer
│ │ │ │ │ ├── head
│ │ │ │ │ └── en
│ │ │ │ │ ├── footer
│ │ │ │ │ └── en
│ │ │ │ │ └── header
│ │ │ │ │ └── en
│ │ │ ├── spandx.preview-off.js
│ │ │ ├── spandx.local.js
│ │ │ ├── spandx.single.js
│ │ │ ├── spandx.remote.js
│ │ │ ├── test-page.html
│ │ │ └── spandx.multi.js
│ │ ├── remote-fallback
│ │ │ ├── remote-files
│ │ │ │ ├── index.html
│ │ │ │ └── subdir
│ │ │ │ │ ├── index.html
│ │ │ │ │ └── remote-only.html
│ │ │ ├── local-files
│ │ │ │ └── subdir
│ │ │ │ │ └── index.html
│ │ │ └── spandx.config.js
│ │ ├── esi-conf
│ │ │ ├── abs-path-root-snippet.html
│ │ │ ├── rel-path-root-snippet.html
│ │ │ ├── subdir
│ │ │ │ ├── abs-path-subdir-snippet.html
│ │ │ │ └── rel-path-subdir-snippet.html
│ │ │ ├── esi-file-rel-paths.html
│ │ │ ├── esi-domain-rel-paths.html
│ │ │ ├── spandx.esi-disabled.js
│ │ │ ├── spandx.esi-enabled.js
│ │ │ ├── esi-abs-paths.html
│ │ │ └── with-esi.html
│ │ ├── esi-include
│ │ │ ├── abs-path-root-snippet.html
│ │ │ ├── rel-path-root-snippet.html
│ │ │ ├── subdir
│ │ │ │ ├── abs-path-subdir-snippet.html
│ │ │ │ └── rel-path-subdir-snippet.html
│ │ │ ├── esi-file-rel-paths.html
│ │ │ ├── esi-domain-rel-paths.html
│ │ │ ├── spandx.local.js
│ │ │ ├── esi-abs-paths.html
│ │ │ ├── spandx.remote.js
│ │ │ ├── with-esi.html
│ │ │ └── spandx.https.js
│ │ ├── portal-chrome
│ │ │ ├── mock-chrome
│ │ │ │ ├── head
│ │ │ │ │ ├── en
│ │ │ │ │ └── ko
│ │ │ │ ├── footer
│ │ │ │ │ ├── en
│ │ │ │ │ └── ko
│ │ │ │ └── header
│ │ │ │ │ ├── en
│ │ │ │ │ └── ko
│ │ │ ├── spandx.chrome-off.js
│ │ │ ├── test-page.html
│ │ │ ├── spandx.single.js
│ │ │ ├── spandx.local.js
│ │ │ └── spandx.multi.js
│ │ ├── invalid
│ │ │ └── syntax.js
│ │ ├── single-multi
│ │ │ ├── spandx.single.js
│ │ │ ├── dev
│ │ │ │ └── index.html
│ │ │ ├── prod
│ │ │ │ └── index.html
│ │ │ └── spandx.multi.js
│ │ ├── bad-gateway
│ │ │ └── spandx.config.js
│ │ ├── multi-host
│ │ │ └── spandx.config.js
│ │ └── bs-override
│ │ │ └── spandx.config.js
│ ├── websites
│ │ ├── abs-path-root-snippet.html
│ │ ├── rel-path-root-snippet.html
│ │ ├── esi-abs-paths.html
│ │ ├── esi-rel-paths.html
│ │ └── with-esi.html
│ ├── reporter.js
│ ├── hush.js
│ └── serve.js
├── support
│ └── jasmine.json
└── spandx
│ ├── configSpec.js
│ ├── routerSpec.js
│ └── spandxSpec.js
├── renovate.json
├── spandx-logo.png
├── examples
├── js-overlay
│ ├── local
│ │ └── js
│ │ │ └── main.js
│ ├── remote
│ │ ├── js
│ │ │ └── main.js
│ │ └── index.html
│ ├── start.sh
│ └── spandx.config.js
├── multi-host
│ ├── remote1
│ │ ├── js
│ │ │ └── main.js
│ │ └── index.html
│ ├── remote2
│ │ ├── js
│ │ │ └── main.js
│ │ └── index.html
│ ├── start.sh
│ └── spandx.config.js
└── README.md
├── app
├── resolveHome.js
├── splash
│ └── index.html
├── cli.js
├── init.js
├── esiMiddleware.js
├── chromeCache.js
├── chromeMiddleware.js
├── router.js
├── inits
│ └── cp
│ │ └── init.js
├── config.js
└── spandx.js
├── .lvimrc
├── test
├── dist
│ └── index.html
└── spandx.config.js
├── spandx.config.js
├── .gitignore
├── .github
└── workflows
│ └── node.js.yml
├── package.json
├── RH.md
├── README.md
├── CHANGELOG.md
└── LICENSE
/.husky/.gitignore:
--------------------------------------------------------------------------------
1 | _
2 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | tabWidth: 4
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | package-lock.json -diff -merge
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/js-or-json/index.html:
--------------------------------------------------------------------------------
1 | INDEX
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/port-auto/index.html:
--------------------------------------------------------------------------------
1 | INDEX
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/route-order/a/index.html:
--------------------------------------------------------------------------------
1 | /a
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/route-order/index.html:
--------------------------------------------------------------------------------
1 | /
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single/foo/index.html:
--------------------------------------------------------------------------------
1 | FOO
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/path-setting/foo/index.html:
--------------------------------------------------------------------------------
1 | foo
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/route-order/b/index.html:
--------------------------------------------------------------------------------
1 | /a/b
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/route-order/c/index.html:
--------------------------------------------------------------------------------
1 | /a/b/c
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single/foo/bar/test.txt:
--------------------------------------------------------------------------------
1 | TEXT FILE
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/path-setting/foo/bar/index.html:
--------------------------------------------------------------------------------
1 | bar
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/path-setting/index.html:
--------------------------------------------------------------------------------
1 | path-setting
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/unconfigured-hostname/index.html:
--------------------------------------------------------------------------------
1 | INDEX
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/url-rewriting/otherpage.html:
--------------------------------------------------------------------------------
1 | OTHER PAGE
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/root-and-subdir/index.html:
--------------------------------------------------------------------------------
1 | INDEX IN ROOT DIR
2 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": [
3 | "config:base"
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-file/head/en:
--------------------------------------------------------------------------------
1 | HEAD_AFTER (file)
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-file/head/ko:
--------------------------------------------------------------------------------
1 | KO HEAD_AFTER (file)
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/remote-fallback/remote-files/index.html:
--------------------------------------------------------------------------------
1 | REMOTE INDEX
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/root-and-subdir/subdir/index.html:
--------------------------------------------------------------------------------
1 | INDEX IN SUBDIR
2 |
--------------------------------------------------------------------------------
/spec/helpers/websites/abs-path-root-snippet.html:
--------------------------------------------------------------------------------
1 | ABS PATH ROOT SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/websites/rel-path-root-snippet.html:
--------------------------------------------------------------------------------
1 | REL PATH ROOT SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/abs-path-root-snippet.html:
--------------------------------------------------------------------------------
1 | ABS PATH ROOT SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/rel-path-root-snippet.html:
--------------------------------------------------------------------------------
1 | REL PATH ROOT SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-file/footer/en:
--------------------------------------------------------------------------------
1 | FOOTER_AFTER (file)
2 |
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-file/header/en:
--------------------------------------------------------------------------------
1 | HEADER_AFTER (file)
2 |
3 |
--------------------------------------------------------------------------------
/spandx-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/redhataccess/spandx/HEAD/spandx-logo.png
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/abs-path-root-snippet.html:
--------------------------------------------------------------------------------
1 | ABS PATH ROOT SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/rel-path-root-snippet.html:
--------------------------------------------------------------------------------
1 | REL PATH ROOT SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-file/footer/ko:
--------------------------------------------------------------------------------
1 | KO FOOTER_AFTER (file)
2 |
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-file/header/ko:
--------------------------------------------------------------------------------
1 | KO HEADER_AFTER (file)
2 |
3 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | npx lint-staged
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/subdir/abs-path-subdir-snippet.html:
--------------------------------------------------------------------------------
1 | ABS PATH SUBDIR SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/subdir/rel-path-subdir-snippet.html:
--------------------------------------------------------------------------------
1 | REL PATH SUBDIR SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/remote-fallback/local-files/subdir/index.html:
--------------------------------------------------------------------------------
1 | LOCAL SUBDIR INDEX
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/remote-fallback/remote-files/subdir/index.html:
--------------------------------------------------------------------------------
1 | REMOTE SUBDIR INDEX
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/remote-fallback/remote-files/subdir/remote-only.html:
--------------------------------------------------------------------------------
1 | REMOTE ONLY
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/subdir/abs-path-subdir-snippet.html:
--------------------------------------------------------------------------------
1 | ABS PATH SUBDIR SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/subdir/rel-path-subdir-snippet.html:
--------------------------------------------------------------------------------
1 | REL PATH SUBDIR SNIPPET
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/mock-chrome/head/en:
--------------------------------------------------------------------------------
1 | HEAD CONTENT (http://localhost:4014 http://localhost:4015)
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/mock-chrome/head/ko:
--------------------------------------------------------------------------------
1 | HEAD CONTENT KO (http://localhost:4014 http://localhost:4015)
2 |
--------------------------------------------------------------------------------
/examples/js-overlay/local/js/main.js:
--------------------------------------------------------------------------------
1 | // prettier-ignore
2 | window.document.querySelector("#msg").textContent = "DEV JS!";
3 |
--------------------------------------------------------------------------------
/examples/js-overlay/remote/js/main.js:
--------------------------------------------------------------------------------
1 | // prettier-ignore
2 | window.document.querySelector("#msg").textContent = "PROD JS!";
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/mock-chrome/footer/en:
--------------------------------------------------------------------------------
1 | FOOTER CONTENT (http://localhost:4014 http://localhost:4015)
2 |
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/mock-chrome/footer/ko:
--------------------------------------------------------------------------------
1 | FOOTER CONTENT KO (http://localhost:4014 http://localhost:4015)
2 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/mock-chrome/header/en:
--------------------------------------------------------------------------------
1 | HEADER CONTENT (http://localhost:4014 http://localhost:4015)
2 |
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/mock-chrome/header/ko:
--------------------------------------------------------------------------------
1 | HEADER CONTENT KO (http://localhost:4014 http://localhost:4015)
2 |
--------------------------------------------------------------------------------
/examples/multi-host/remote1/js/main.js:
--------------------------------------------------------------------------------
1 | // prettier-ignore
2 | window.document.querySelector("#msg").textContent = "PROD JS!";
3 |
--------------------------------------------------------------------------------
/examples/multi-host/remote2/js/main.js:
--------------------------------------------------------------------------------
1 | // prettier-ignore
2 | window.document.querySelector("#msg").textContent = "PROD JS!";
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/invalid/syntax.js:
--------------------------------------------------------------------------------
1 | /*global fjdskfsklvner_sytax_error*/
2 | // prettier-ignore
3 | fjdskfsklvner_sytax_error();
4 |
--------------------------------------------------------------------------------
/spec/helpers/configs/url-rewriting/esi-fragment.html:
--------------------------------------------------------------------------------
1 | ESI fragment
2 |
3 | A link
4 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-http/services/primer/head/en:
--------------------------------------------------------------------------------
1 | HEAD_AFTER (http)
2 | (http://localhost:4014 http://localhost:4015)
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-http/services/primer/footer/en:
--------------------------------------------------------------------------------
1 | FOOTER_AFTER (http)
2 | (http://localhost:4014 http://localhost:4015)
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/mock-primer-http/services/primer/header/en:
--------------------------------------------------------------------------------
1 | HEADER_AFTER (http)
2 | (http://localhost:4014 http://localhost:4015)
3 |
--------------------------------------------------------------------------------
/spec/helpers/configs/js-or-json/spandx.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "host": "localhost",
3 | "port": 1337,
4 | "silent": true,
5 | "routes": {
6 | "/": "./"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/spec/helpers/websites/esi-abs-paths.html:
--------------------------------------------------------------------------------
1 | ESI ABS PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/websites/esi-rel-paths.html:
--------------------------------------------------------------------------------
1 | ESI REL PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/js-or-json/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": "./"
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/port-auto/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: "auto",
4 | silent: true,
5 | routes: {
6 | "/": "./"
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/spandx.preview-off.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": "./"
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/esi-file-rel-paths.html:
--------------------------------------------------------------------------------
1 | ESI FILE REL PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/root-and-subdir/spandx.local.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: false,
5 | routes: {
6 | "/": "./"
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/esi-domain-rel-paths.html:
--------------------------------------------------------------------------------
1 | ESI DOMAIN REL PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/esi-file-rel-paths.html:
--------------------------------------------------------------------------------
1 | ESI FILE REL PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/spandx.chrome-off.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": "./"
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/examples/js-overlay/start.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # launch a webserver to act as the 'remote' server
4 | ../../node_modules/.bin/http-server remote &
5 |
6 | # launch spandx
7 | ../../app/cli.js
8 |
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/esi-domain-rel-paths.html:
--------------------------------------------------------------------------------
1 | ESI DOMAIN REL PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/unconfigured-hostname/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: "auto",
4 | silent: true,
5 | routes: {
6 | "/": "./"
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/support/jasmine.json:
--------------------------------------------------------------------------------
1 | {
2 | "spec_dir": "spec",
3 | "spec_files": ["**/*[sS]pec.js"],
4 | "helpers": ["helpers/reporter.js"],
5 | "stopSpecOnExpectationFailure": false,
6 | "random": false
7 | }
8 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/spandx.local.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | esi: true,
6 | routes: {
7 | "/": "./"
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single-multi/spandx.single.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": { host: "http://localhost:4014" }
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/spandx.esi-disabled.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | esi: false,
6 | routes: {
7 | "/": "./"
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/spandx.esi-enabled.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | esi: true,
6 | routes: {
7 | "/": "./"
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/test-page.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/spec/helpers/configs/root-and-subdir/spandx.remote.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": { host: "http://localhost:4014" }
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/url-rewriting/spandx.remote.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": { host: "http://localhost:4014" }
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/esi-abs-paths.html:
--------------------------------------------------------------------------------
1 | ESI ABS PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/esi-abs-paths.html:
--------------------------------------------------------------------------------
1 | ESI ABS PATH PARENT
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/spandx.remote.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | esi: true,
6 | routes: {
7 | "/": { host: "http://localhost:4014" }
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/spec/helpers/configs/bad-gateway/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": {
7 | host: "http://localhost:4014"
8 | }
9 | }
10 | };
11 |
--------------------------------------------------------------------------------
/app/resolveHome.js:
--------------------------------------------------------------------------------
1 | const path = require("path");
2 |
3 | function resolveHome(filepath) {
4 | if (filepath[0] === "~") {
5 | return path.join(process.env.HOME, filepath.slice(1));
6 | }
7 | return filepath;
8 | }
9 |
10 | module.exports = resolveHome;
11 |
--------------------------------------------------------------------------------
/spec/helpers/configs/remote-fallback/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/subdir": "./local-files/subdir",
7 | "/": { host: "http://localhost:4014" }
8 | }
9 | };
10 |
--------------------------------------------------------------------------------
/spec/helpers/websites/with-esi.html:
--------------------------------------------------------------------------------
1 | ESI PARENT
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/multi-host/start.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # launch a webserver to act as the 'remote' server
4 | ../../node_modules/.bin/http-server remote1 -p 8081 &
5 | ../../node_modules/.bin/http-server remote2 -p 8082 &
6 |
7 | # launch spandx
8 | ../../app/cli.js
9 |
10 |
--------------------------------------------------------------------------------
/spec/helpers/configs/route-order/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": "./",
7 | "/a/b/c": "./c",
8 | "/a": "./a",
9 | "/a/b": "./b"
10 | }
11 | };
12 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-conf/with-esi.html:
--------------------------------------------------------------------------------
1 | ESI PARENT
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/with-esi.html:
--------------------------------------------------------------------------------
1 | ESI PARENT
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/spec/helpers/configs/esi-include/spandx.https.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | esi: true,
6 | routes: {
7 | "/": { host: "http://localhost:4014" }
8 | },
9 | bs: {
10 | https: true
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/spandx.local.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | primer: {
6 | preview: true
7 | },
8 | routes: {
9 | "/services/primer/": "./mock-primer-file",
10 | "/": "./"
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/examples/js-overlay/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | open: true,
5 | startPath: "/",
6 | verbose: true,
7 | routes: {
8 | "/js": "./local/js/",
9 | "/": {
10 | host: "http://localhost:8081"
11 | }
12 | }
13 | };
14 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/spandx.single.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | primer: {
6 | preview: true
7 | },
8 | routes: {
9 | "/services/primer/": "./services/primer/",
10 | "/": {host: "http://localhost:4014"}
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/spandx.remote.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | primer: {
6 | preview: true
7 | },
8 | routes: {
9 | "/services/primer/": {
10 | host: "http://localhost:4014"
11 | },
12 | "/": "./"
13 | }
14 | };
15 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/spandx.single.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | portalChrome: {
6 | resolveSPAComments: true
7 | },
8 | routes: {
9 | "/services/chrome/": "./mock-chrome",
10 | "/": { host: "http://localhost:4014" }
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/.lvimrc:
--------------------------------------------------------------------------------
1 | let g:ale_linters = {
2 | \ 'javascript': ['prettier'],
3 | \ 'json': ['prettier'],
4 | \}
5 |
6 | let g:ale_fixers = {}
7 | let g:ale_fixers['javascript'] = ['prettier']
8 | let g:ale_fixers['json'] = ['prettier']
9 |
10 | let g:ale_fix_on_save = 1
11 |
12 | let g:ale_javascript_prettier_use_local_config = 1
13 |
--------------------------------------------------------------------------------
/spec/helpers/configs/url-rewriting/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | URL REWRITING INDEX
9 |
10 | A link
11 |
12 |
13 |
--------------------------------------------------------------------------------
/test/dist/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/spec/helpers/configs/url-rewriting/index-esi.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | URL REWRITING INDEX w/ ESI FRAGMENT
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/spec/helpers/configs/multi-host/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: {
3 | dev: "localhost"
4 | },
5 | port: 1337,
6 | silent: true,
7 | routes: {
8 | "/": {
9 | host: {
10 | dev: "http://localhost:4014",
11 | prod: "http://localhost:4015"
12 | }
13 | }
14 | }
15 | };
16 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single-multi/dev/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | multi-host spandx
7 |
8 |
9 | DEV
10 |
11 | About
12 |
13 |
14 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single-multi/prod/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | multi-host spandx
7 |
8 |
9 | PROD
10 |
11 | About
12 |
13 |
14 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/foo": {
7 | host: "http://localhost:4014",
8 | path: "/foo/",
9 | single: true
10 | },
11 | "/": {
12 | host: "http://localhost:4014"
13 | }
14 | }
15 | };
16 |
--------------------------------------------------------------------------------
/spec/helpers/reporter.js:
--------------------------------------------------------------------------------
1 | const SpecReporter = require("jasmine-spec-reporter").SpecReporter;
2 |
3 | jasmine.getEnv().clearReporters(); // remove default reporter logs
4 | jasmine.getEnv().addReporter(
5 | new SpecReporter({
6 | // add jasmine-spec-reporter
7 | spec: {
8 | displayPending: true,
9 | displayDuration: true
10 | }
11 | })
12 | );
13 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/spandx.local.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | portalChrome: {
6 | resolveSPAComments: true,
7 | },
8 | bs: {
9 | codeSync: false,
10 | tunnel: false,
11 | },
12 | routes: {
13 | "/services/chrome/": "./mock-chrome",
14 | "/": "./",
15 | },
16 | };
17 |
--------------------------------------------------------------------------------
/app/splash/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | spandx splash page
7 |
8 |
9 | spandx is running! Time to configure it.
10 | TODO: add configuration guide here, or link to one
11 |
12 |
13 |
--------------------------------------------------------------------------------
/spec/helpers/configs/single-multi/spandx.multi.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: {
3 | dev: "localhost",
4 | prod: "127.0.0.1"
5 | },
6 | port: 1337,
7 | silent: true,
8 | routes: {
9 | "/": {
10 | host: {
11 | dev: "http://localhost:4014",
12 | prod: "http://localhost:4015"
13 | }
14 | }
15 | }
16 | };
17 |
--------------------------------------------------------------------------------
/spec/helpers/configs/url-rewriting/spandx.local.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": "./",
7 | // this is a hacky way to get the host to be rewritten when serving from static dirs.
8 | // TODO implement a better approach
9 | "/fake/path/for/host/rewrites": { host: "http://localhost:4014" }
10 | }
11 | };
12 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/test-page.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | HEAD_BEFORE
7 |
8 |
9 |
10 |
11 |
12 | HEADER_BEFORE
13 |
14 |
15 |
16 | FOOTER_BEFORE
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/spec/helpers/hush.js:
--------------------------------------------------------------------------------
1 | const log = console.log;
2 | const warn = console.warn;
3 | const error = console.error;
4 |
5 | function yourMouth() {
6 | const noop = () => {};
7 |
8 | console.log = noop;
9 | console.warn = noop;
10 | console.error = noop;
11 | }
12 |
13 | function speakUp() {
14 | console.log = log;
15 | console.warn = warn;
16 | console.error = error;
17 | }
18 |
19 | module.exports = { yourMouth, speakUp };
20 |
--------------------------------------------------------------------------------
/examples/multi-host/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: {
3 | localhost: "localhost",
4 | localip: "127.0.0.1"
5 | },
6 | port: 1337,
7 | open: true,
8 | startPath: "/",
9 | verbose: true,
10 | routes: {
11 | "/": {
12 | host: {
13 | localhost: "http://localhost:8081",
14 | localip: "http://localhost:8082"
15 | }
16 | }
17 | }
18 | };
19 |
--------------------------------------------------------------------------------
/spec/helpers/configs/primer/spandx.multi.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: {
3 | dev: "localhost",
4 | prod: "127.0.0.1"
5 | },
6 | port: 1337,
7 | silent: true,
8 | primer: {
9 | preview: true
10 | },
11 | routes: {
12 | "/services/primer/": "./services/primer/",
13 | "/": {
14 | host: {
15 | dev: "http://localhost:4014",
16 | prod: "http://localhost:4015"
17 | }
18 | }
19 | }
20 | };
21 |
--------------------------------------------------------------------------------
/spec/helpers/configs/portal-chrome/spandx.multi.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: {
3 | dev: "localhost",
4 | prod: "127.0.0.1"
5 | },
6 | port: 1337,
7 | silent: true,
8 | portalChrome: {
9 | resolveSPAComments: true
10 | },
11 | routes: {
12 | "/services/chrome/": "./mock-chrome",
13 | "/": {
14 | host: {
15 | dev: "http://localhost:4014",
16 | prod: "http://localhost:4015"
17 | }
18 | }
19 | }
20 | };
21 |
--------------------------------------------------------------------------------
/spec/helpers/configs/bs-override/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: "localhost",
3 | port: 1337,
4 | silent: true,
5 | routes: {
6 | "/": "./",
7 | // this is a hacky way to get the host to be rewritten when serving from static dirs.
8 | // TODO implement a better approach
9 | "/fake/path/for/host/rewrites": { host: "http://localhost:4014" }
10 | },
11 | bs: {
12 | ghostMode: {
13 | clicks: false,
14 | scroll: false,
15 | location: false
16 | }
17 | }
18 | };
19 |
--------------------------------------------------------------------------------
/spec/helpers/serve.js:
--------------------------------------------------------------------------------
1 | const http = require("http");
2 | const serveStatic = require("serve-static");
3 | const finalhandler = require("finalhandler");
4 |
5 | function serve(path, requestedPort = null) {
6 | return new Promise(resolve => {
7 | const serve = serveStatic(path);
8 | const server = http.createServer((req, res) => {
9 | const fh = finalhandler(req, res);
10 | serve(req, res, fh);
11 | });
12 | server.listen(requestedPort, null, null, () => {
13 | const port = server.address().port;
14 | resolve({ server, port });
15 | });
16 | });
17 | }
18 |
19 | module.exports = serve;
20 |
--------------------------------------------------------------------------------
/app/cli.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | const fs = require("fs");
4 | const path = require("path");
5 |
6 | const argv = require("yargs").argv;
7 |
8 | const spandx = require("./spandx");
9 | const config = require("./config");
10 | const init = require("./init");
11 |
12 | async function handleCli() {
13 | if (argv.v || argv.version) {
14 | // spandx -v --veresion
15 | const package = require("../package.json");
16 | console.log(package.version);
17 | } else if (argv._[0] === "init") {
18 | // spandx init
19 | await init(argv);
20 | } else {
21 | // spandx
22 | const confArg = argv.c || argv.config || "spandx.config.js";
23 | const confFile = path.resolve(process.cwd(), confArg);
24 | await spandx.init(confFile);
25 | }
26 | }
27 |
28 | handleCli();
29 |
--------------------------------------------------------------------------------
/spandx.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | host: {
3 | local: "localhost",
4 | },
5 | port: "auto",
6 | open: !true,
7 | startPath: "/",
8 | verbose: true,
9 | routes: {
10 | // Here are some routing examples to get started.
11 |
12 | // Route a URL path to an app server.
13 | // This is most useful for testing local files (esp JS and CSS) against
14 | // a remote QA or production server.
15 | "/foo/bar": {
16 | host: {
17 | local: "http://localhost:8081",
18 | },
19 | path: "/",
20 | },
21 |
22 | "/baz/bat": {
23 | host: {
24 | local: "http://localhost:8081",
25 | },
26 | },
27 | // Route a URL path to an app server, and watch local files for changes.
28 | // This is most useful for putting a local development at a certain
29 | // path on your spandx server. Includes browser-sync auto-reloading.
30 | // '/': { host: 'http://localhost:8080/', watch: '~/projects/my-app' },
31 | },
32 | };
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (http://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # Typescript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 |
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | # spandx examples
2 |
3 | Here are some examples of spandx configurations. Many more can be found in the test suite, but these examples are more real-world than what you'll find in the test suite.
4 |
5 | All examples have `verbose: true` so you can see where each request is being routed.
6 |
7 | ## List of examples
8 |
9 | - [JavaScript Overlay](./js-overlay): overlaying your local JavaScript files on top of a remote env
10 | - [Multi-host](./multi-host): change remote env based on current hostname (very useful for pointing at dev, qa, stage, and prod servers)
11 |
12 | ## Running the examples
13 |
14 | To launch an example, simply `cd` to the example that interests you and run the `./start.sh` script.
15 |
16 | cd examples/js-overlay
17 | ./start.sh
18 |
19 | In the case of `js-overlay`, the start script will launch an HTTP Server that we'll call the "remote" server. Imagine this is your production server. It has an `index.html` and a `main.js`. If you view this directly, you'll see "PROD JS!". If you view it through spandx instead, you'll see the same `index.html`, but the development copy of `main.js` is run instead of the prod version.
20 |
21 |
--------------------------------------------------------------------------------
/examples/js-overlay/remote/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | spandx multi-host example
7 |
11 |
12 |
13 |
14 | spandx JS overlay example
15 |
16 | This example demonstrates using spandx to
18 | overlay local JavaScript files onto a remote environment. Test in
19 | production. :]
20 |
21 | Currently using...
22 |
23 |
24 |
25 | Switch to...
26 |
27 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.github/workflows/node.js.yml:
--------------------------------------------------------------------------------
1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3 |
4 | name: Node.js CI
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | strategy:
18 | matrix:
19 | node-version: [18.x, 20.x]
20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
21 |
22 | steps:
23 | - uses: actions/checkout@v2
24 | # - uses: actions/cache@v2
25 | # with:
26 | # path: ~/.npm
27 | # key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
28 | # restore-keys: |
29 | # ${{ runner.os }}-node-
30 | - name: Use Node.js ${{ matrix.node-version }}
31 | uses: actions/setup-node@v2
32 | with:
33 | node-version: ${{ matrix.node-version }}
34 | cache: 'yarn'
35 | - run: yarn install --frozen-lockfile
36 | - run: yarn test
37 |
38 |
--------------------------------------------------------------------------------
/spec/spandx/configSpec.js:
--------------------------------------------------------------------------------
1 | /*global describe, it, require, expect*/
2 |
3 | const config = require("../../app/config.js");
4 |
5 | const shouldNotResolve = () => {
6 | throw new Error("This promise should have been rejected!");
7 | };
8 |
9 | const catchSpecificError = (e, name) => {
10 | if (e.name === name) {
11 | return;
12 | }
13 | throw new Error(`Expected to see a ${name} but got ${e.toString()}`);
14 | };
15 |
16 | describe("fromFile", () => {
17 | it("should load the default config", () => {
18 | return config.fromFile("../spandx.config.js");
19 | });
20 |
21 | it("should throw ConfigProcessError on syntax error file", () => {
22 | return config
23 | .fromFile("../spec/helpers/configs/invalid/syntax.js")
24 | .then(shouldNotResolve)
25 | .catch(e => {
26 | catchSpecificError(e, "ConfigProcessError");
27 | });
28 | });
29 |
30 | it("should throw ConfigOpenError on missing file", () => {
31 | return config
32 | .fromFile("/tmp/foo/nonexist/blah/test.js")
33 | .then(shouldNotResolve)
34 | .catch(e => {
35 | catchSpecificError(e, "ConfigOpenError");
36 | });
37 | });
38 | });
39 |
--------------------------------------------------------------------------------
/app/init.js:
--------------------------------------------------------------------------------
1 | const fs = require("fs");
2 | const path = require("path");
3 |
4 | const c = require("print-colors");
5 |
6 | module.exports = async function spandxInit(argv) {
7 | // if a site name is provided to init, look for and run that site's init script
8 | const siteProvided = argv._.length >= 2;
9 |
10 | if (siteProvided) {
11 | const siteName = argv._[1];
12 |
13 | const initScript = path.resolve(
14 | __dirname,
15 | `./inits/${siteName}/init.js`
16 | );
17 |
18 | const siteExists = fs.existsSync(initScript);
19 | if (siteExists) {
20 | console.log(
21 | `Initializing ${c.fg.l.cyan}${siteName}${c.end} config`
22 | );
23 | await require(initScript)(argv);
24 | } else {
25 | console.error(
26 | `No init script found for site ${c.fg.l.cyan}${siteName}${
27 | c.end
28 | }`
29 | );
30 | }
31 | } else {
32 | const configName = "spandx.config.js";
33 | const sampleConfigPath = path.resolve(__dirname, `../${configName}`);
34 | const sampleConfig = fs.readFileSync(sampleConfigPath);
35 | console.log(sampleConfig.toString());
36 | }
37 | };
38 |
--------------------------------------------------------------------------------
/test/spandx.config.js:
--------------------------------------------------------------------------------
1 | const fs = require("fs");
2 |
3 | const sslReady =
4 | fs.existsSync("ssl/spandx.pem") && fs.existsSync("ssl/spandx-key.pem");
5 |
6 | if (!sslReady) {
7 | console.log("Launching with invalid SSL cert 🔓");
8 | } else {
9 | console.log("Launching with valid SSL cert 🔒");
10 | }
11 |
12 | module.exports = {
13 | host: {
14 | prod: "prod.foo.redhat.com",
15 | stage: "stage.foo.redhat.com",
16 | qa: "qa.foo.redhat.com",
17 | dev: "dev.foo.redhat.com",
18 | },
19 | port: 1337,
20 | open: false,
21 | startPath: "/foo",
22 | verbose: true,
23 | portalChrome: {
24 | resolveSPAComments: true,
25 | },
26 | primer: {
27 | // preview: true
28 | },
29 | proxy: {
30 | host: "http://squid.corp.redhat.com:3128",
31 | pattern: "^https://(.*?).redhat.com",
32 | },
33 | bs: {
34 | https: sslReady
35 | ? { cert: "ssl/spandx.pem", key: "ssl/spandx-key.pem" } // 🔒
36 | : true, // 🔓
37 | codeSync: true,
38 | },
39 | routes: {
40 | "/foo": "dist",
41 |
42 | "/": {
43 | host: {
44 | dev: "https://access.dev.redhat.com",
45 | qa: "https://access.qa.redhat.com",
46 | stage: "https://access.stage.redhat.com",
47 | prod: "https://access.redhat.com",
48 | },
49 | },
50 | },
51 | };
52 |
--------------------------------------------------------------------------------
/examples/multi-host/remote2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | spandx multi-host example
7 |
13 |
14 |
15 |
16 |
17 | spandx mult-host example
18 |
19 | This example demonstrates using spandx to
21 | point at different remote environments based on the current local hostname.
22 |
23 |
24 |
25 | For example, visiting localhost:1337 will cause
27 | spandx to proxy to Remote Server 1, and visiting 127.0.0.1:1337 will cause
29 | spandx to proxy to Remote Server 2.
30 |
31 |
32 | Currently remote environment... REMOTE SERVER 2
33 |
34 | Switch to...
35 |
36 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/esiMiddleware.js:
--------------------------------------------------------------------------------
1 | const _ = require("lodash");
2 | const ESI = require("nodesi");
3 |
4 | function buildEsiMap(conf) {
5 | const esi = _(conf.host)
6 | .mapValues((host, env) => {
7 | const esiconfDefaults = {
8 | baseUrl: `${conf.protocol}//${host}:${conf.port}`, // baseUrl enables relative paths in esi:include tags
9 | onError: (src, error) => {
10 | console.error(
11 | `An error occurred while resolving an ESI tag for the ${env} host`
12 | );
13 | console.error(error);
14 | },
15 | cache: false
16 | };
17 |
18 | const config = _.defaultsDeep(
19 | _.cloneDeep(conf.esi),
20 | esiconfDefaults
21 | );
22 |
23 | const esi = new ESI(config);
24 |
25 | esi.spandxGeneratedConfig = config;
26 |
27 | return esi;
28 | })
29 | .value();
30 |
31 | return esi;
32 | }
33 |
34 | function createEsiMiddleware(conf) {
35 | const esi = buildEsiMap(conf);
36 |
37 | function applyESI(data, req, res) {
38 | return new Promise(function(resolve, reject) {
39 | const env = req.headers["x-spandx-env"];
40 | const isHTML = (res.getHeader("content-type") || "").includes(
41 | "html"
42 | );
43 | if (isHTML) {
44 | esi[env]
45 | .process(data.toString())
46 | .then(data => Buffer.from(data))
47 | .then(resolve)
48 | .catch(reject);
49 | } else {
50 | resolve(data);
51 | }
52 | });
53 | }
54 | return applyESI;
55 | }
56 |
57 | module.exports = { buildEsiMap, createEsiMiddleware };
58 |
--------------------------------------------------------------------------------
/app/chromeCache.js:
--------------------------------------------------------------------------------
1 | const got = require("got");
2 |
3 | const DEFAULT_CHROME_HOST = "https://access.redhat.com";
4 | const DEFAULT_CHROME_PATH = "/services/chrome/";
5 | const LOCALES = ["en", "ja", "ko", "zh_CN", "fr"];
6 |
7 | const cache = {};
8 | let chromeHost;
9 | let chromePath;
10 |
11 | async function getParts({
12 | host = DEFAULT_CHROME_HOST,
13 | path = DEFAULT_CHROME_PATH,
14 | useCached = true,
15 | legacy = false,
16 | locale = "en",
17 | } = {}) {
18 | const cacheKey = host + path + locale;
19 | if (useCached && cache[cacheKey]) {
20 | return cache[cacheKey];
21 | }
22 |
23 | const headReq = fetchChromePart({
24 | host,
25 | part: "head",
26 | path,
27 | legacy,
28 | locale,
29 | });
30 | const headerReq = fetchChromePart({
31 | host,
32 | part: "header",
33 | path,
34 | legacy,
35 | locale,
36 | });
37 | const footerReq = fetchChromePart({
38 | host,
39 | part: "footer",
40 | path,
41 | legacy,
42 | locale,
43 | });
44 |
45 | const [head, header, footer] = await Promise.all([
46 | headReq,
47 | headerReq,
48 | footerReq,
49 | ]);
50 |
51 | const parts = { head, header, footer };
52 |
53 | if (useCached) {
54 | cache[cacheKey] = parts;
55 | chromeHost = host;
56 | chromePath = path;
57 | }
58 |
59 | return parts;
60 | }
61 |
62 | async function fetchChromePart({
63 | host = DEFAULT_CHROME_HOST,
64 | path = DEFAULT_CHROME_PATH,
65 | part,
66 | legacy = false,
67 | locale = "en",
68 | } = {}) {
69 | const url = `${host}${path}${part}/${locale}${
70 | legacy ? "?legacy=false" : ""
71 | }`;
72 | console.log(`fetching chrome from ${url}`);
73 |
74 | try {
75 | const res = await got(url);
76 | return res.body;
77 | } catch (e) {
78 | console.error(`attempting to fetch ${url} failed`);
79 | }
80 | }
81 |
82 | module.exports = {
83 | chromeHost,
84 | chromePath,
85 | getParts,
86 | fetchChromePart,
87 | LOCALES,
88 | };
89 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "spandx",
3 | "version": "3.0.0",
4 | "description": "Develop locally, proxy to prod, browser-sync, inject Portal Chrome.",
5 | "main": "app/spandx.js",
6 | "bin": "app/cli.js",
7 | "files": [
8 | "app",
9 | "spandx.config.js"
10 | ],
11 | "scripts": {
12 | "test": "jasmine spec/spandx/*.js",
13 | "start": "node app/spandx.js",
14 | "dev": "npx nodemon spandx.js",
15 | "debug": "node-debug spandx.js",
16 | "version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md",
17 | "update-readme-toc": "markdown-toc -i README.md",
18 | "prepare": "husky install"
19 | },
20 | "lint-staged": {
21 | "{app,spec}/**/*.{js,json}": [
22 | "prettier --write"
23 | ],
24 | "examples/**/*.{js,json}": [
25 | "prettier --write"
26 | ]
27 | },
28 | "repository": {
29 | "type": "git",
30 | "url": "git+ssh://git@github.com/redhataccess/spandx.git"
31 | },
32 | "keywords": [
33 | "proxy",
34 | "local"
35 | ],
36 | "license": "GPL-3.0",
37 | "bugs": {
38 | "url": "https://github.com/redhataccess/spandx/issues"
39 | },
40 | "homepage": "https://github.com/redhataccess/spandx#readme",
41 | "dependencies": {
42 | "browser-sync": "2.25.0",
43 | "connect": "3.7.0",
44 | "conventional-changelog-cli": "2.1.1",
45 | "finalhandler": "1.2.0",
46 | "got": "11.8.3",
47 | "hostile": "1.3.3",
48 | "http-proxy": "1.18.1",
49 | "https-proxy-agent": "7.0.0",
50 | "inquirer": "8.2.6",
51 | "lodash": "4.17.21",
52 | "nodesi": "1.17.0",
53 | "opn": "5.5.0",
54 | "porty": "3.1.1",
55 | "print-colors": "1.0.1",
56 | "proxy-agent": "6.2.1",
57 | "serve-static": "1.15.0",
58 | "transformer-proxy": "0.3.5",
59 | "yargs": "17.4.1"
60 | },
61 | "devDependencies": {
62 | "frisby": "2.1.3",
63 | "http-server": "14.1.0",
64 | "husky": "7.0.4",
65 | "jasmine": "3.9.0",
66 | "jasmine-spec-reporter": "7.0.0",
67 | "lint-staged": "13.2.2",
68 | "markdown-toc": "1.2.0",
69 | "nodemon": "2.0.22",
70 | "opn": "5.5.0",
71 | "prettier": "2.3.1"
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/spec/spandx/routerSpec.js:
--------------------------------------------------------------------------------
1 | /*global describe, it, require, expect, beforeEach, process*/
2 | process.env.NODE_ENV = "test";
3 | const router = require("../../app/router.js");
4 | const URL = "https://access.redhat.com";
5 |
6 | describe("doProxy", () => {
7 | describe("with target", () => {
8 | it("should proxy the connection to the target", done => {
9 | const proxy = {
10 | web: (req, res, opts) => {
11 | expect(opts.target).toBeDefined();
12 | expect(opts.target).toEqual(URL);
13 | done();
14 | }
15 | };
16 | router.priv.doProxy(proxy, {}, {}, URL);
17 | });
18 | });
19 | describe("without target", () => {
20 | it("should 404", done => {
21 | const proxy = {
22 | web: (req, res, opts) => {
23 | throw new Error("should not reach the proxy.web call");
24 | }
25 | };
26 |
27 | let state = {};
28 |
29 | router.priv.doProxy(
30 | proxy,
31 | {},
32 | {
33 | writeHead: code => {
34 | state.code = code;
35 | },
36 | end: () => {
37 | expect(state.code).toBeDefined();
38 | expect(state.code).toEqual(404);
39 | done();
40 | }
41 | }
42 | );
43 | });
44 | });
45 | });
46 |
47 | describe("routerPlugin", () => {
48 | it("should run the plugin if passed in", done => {
49 | const plugin = (req, res, target) => {
50 | return {
51 | then: cb => {
52 | cb(target);
53 | } // Poor mans Promise
54 | };
55 | };
56 |
57 | router.priv.tryPlugin(plugin, {}, {}, URL, target => {
58 | expect(target).toEqual(URL);
59 | done();
60 | });
61 | });
62 |
63 | it("should let plugins return a new target and modify req, res", done => {
64 | const plugin = (req, res, target) => {
65 | req.pluginmod = "foo";
66 | res.pluginmod = "bar";
67 | target = `${target}?foo=bar`;
68 | return {
69 | then: cb => {
70 | cb(target);
71 | } // Poor mans Promise
72 | };
73 | };
74 |
75 | const req = {};
76 | const res = {};
77 |
78 | router.priv.tryPlugin(plugin, req, res, URL, target => {
79 | expect(true).toBe(true);
80 | expect(req.pluginmod).toEqual("foo");
81 | expect(res.pluginmod).toEqual("bar");
82 | expect(target).toEqual(`${URL}?foo=bar`);
83 | done();
84 | });
85 | });
86 |
87 | it("should fail if callback is not a function", () => {
88 | expect(() => {
89 | router.tryPlugin();
90 | }).toThrowError(TypeError);
91 | });
92 | });
93 |
--------------------------------------------------------------------------------
/examples/multi-host/remote1/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | spandx multi-host example
7 |
13 |
14 |
15 |
16 |
17 | spandx mult-host example
18 |
19 | This example demonstrates using spandx to
21 | point at different remote environments based on the current local hostname.
22 |
23 |
24 |
25 | For example, visiting localhost:1337 will cause
27 | spandx to proxy to Remote Server 1, and visiting 127.0.0.1:1337 will cause
29 | spandx to proxy to Remote Server 2.
30 |
31 |
32 | Currently remote environment... REMOTE SERVER 1
33 |
34 | Switch to...
35 |
36 |
40 |
41 | Using multi-host in your own project
42 |
43 | This example is a very simplified version, using localhost and 127.0.0.1 because they work out of the box. To fully utilize this feature in your own project, please read on.
44 |
45 |
46 | This feature is most useful when paired with /etc/hosts to create custom local hostnames. If you work on the website for Foo, Inc, which has these environments:
47 |
48 |
49 |
50 | - dev.foo.com
51 | - qa.foo.com
52 | - stage.foo.com
53 | - www.foo.com
54 |
55 |
56 |
57 | You may want to use spandx to test your JS/CSS/images on each environment before deploying. To do that, you could maintain four spandx config files, which point to each of the four envs. Or, you can utilize mult-host routing.
58 |
59 |
60 |
61 | Create local hostnames for each remote environment by adding this to /etc/hosts:
62 |
63 | dev-local.foo.com 127.0.0.1
64 | qa-local.foo.com 127.0.0.1
65 | stage-local.foo.com 127.0.0.1
66 | www-local.foo.com 127.0.0.1
67 |
68 | Now visiting any of the new hostnames will simply point to localhost. Perfect. Now update your spandx config (only 'host' and 'routes' properties included for clarity).
69 |
70 | Before:
71 |
72 | module.exports = {
73 | host: "localhost",
74 | routes: {
75 | "/": {
76 | host: "http://localhost:8081"
77 | }
78 | }
79 | };
80 |
81 | After:
82 |
83 | module.exports = {
84 | host: {
85 | dev: "dev-local.foo.com",
86 | qa: "qa-local.foo.com"
87 | +---> stage: "stage-local.foo.com"
88 | | production: "wwww-local.foo.com"
89 | | },
90 | | routes: {
91 | | "/": {
92 | | host: {
93 | | dev: "http://dev.foo.com",
94 | | qa: "http://qa.foo.com",
95 | +-----------> stage: "http://stage.foo.com",
96 | production: "http://www.foo.com",
97 | }
98 | }
99 | }
100 | };
101 |
102 | The ASCII arrow is drawn to show how the name "stage" (and similarly dev,
103 | qa, and production), links the local hostname to the remote URL. It can be
104 | read as "If you visit spandx via stage-local.foo.com, then proxy to the 'stage' host, which lives at http://stage.foo.com".
105 |
106 |
107 | These names can be a string of your choice, they are not hard-coded.
108 |
109 |
110 |
111 |
112 |
113 |
--------------------------------------------------------------------------------
/app/chromeMiddleware.js:
--------------------------------------------------------------------------------
1 | const chromeCache = require("./chromeCache");
2 | const config = require("./config");
3 |
4 | function SPACommentResolver(conf) {
5 | return async function SPACommentResolverMiddleware(data, req, res) {
6 | const isHTML = (res.getHeader("content-type") || "").includes("html");
7 | if (isHTML) {
8 | const locale = getLocaleCookie(req.headers["cookie"]);
9 | const host = config.getTargetHost(
10 | conf,
11 | req.headers["x-spandx-env"],
12 | "/services/chrome/",
13 | req.headers["x-spandx-origin"]
14 | );
15 | const chromeParts = await chromeCache.getParts({
16 | host,
17 | legacy: true,
18 | locale,
19 | });
20 |
21 | return data
22 | .toString()
23 | .replace(//, chromeParts.head)
24 | .replace(//, chromeParts.header)
25 | .replace(//, chromeParts.footer);
26 | } else {
27 | return data;
28 | }
29 | };
30 | }
31 |
32 | function chromeSwapper(conf) {
33 | return async function ChromeSwapperMiddleware(data, req, res) {
34 | const isHTML = (res.getHeader("content-type") || "").includes("html");
35 | const isPrimerAlready = req.url.startsWith("/services/primer");
36 | if (isHTML && !isPrimerAlready) {
37 | const host = config.getTargetHost(
38 | conf,
39 | req.headers["x-spandx-env"],
40 | "/services/primer/",
41 | req.headers["x-spandx-origin"]
42 | );
43 | const locale = getLocaleCookie(req.headers["cookie"]);
44 | const chromeParts = await chromeCache.getParts({
45 | host,
46 | path: "/services/primer/",
47 | locale,
48 | });
49 |
50 | return data
51 | .toString()
52 | .replace(
53 | /.*/s,
54 | `${chromeParts.head}`
55 | )
56 | .replace(
57 | /.*/s,
58 | `${chromeParts.header}`
59 | )
60 | .replace(
61 | /.*/s,
62 | `${chromeParts.footer}`
63 | );
64 |
65 | // if any tokens were found, swap them
66 | // if (tokens.result.length) {
67 | // tokens.result.sort(
68 | // (a, b) => a.outer.startIndex - b.outer.startIndex
69 | // );
70 |
71 | // // TODO make this work when only 1 or 2 of the token pairs were found
72 | // const ret =
73 | // // body pre-head
74 | // body.slice(0, tokens.result[0].outer.startIndex) +
75 | // // head
76 | // chromeParts.head +
77 | // // body post-head
78 | // body.slice(
79 | // tokens.result[0].outer.endIndex,
80 | // tokens.result[1].outer.startIndex
81 | // ) +
82 | // // header
83 | // chromeParts.header +
84 | // // body post-header
85 | // body.slice(
86 | // tokens.result[1].outer.endIndex,
87 | // tokens.result[2].outer.startIndex
88 | // ) +
89 | // // footer
90 | // chromeParts.footer +
91 | // // body post-footer
92 | // body.slice(tokens.result[2].outer.endIndex, body.length);
93 |
94 | // return "HELLO";
95 | // }
96 | }
97 |
98 | return data;
99 | };
100 | }
101 |
102 | function getLocaleCookie(cookies) {
103 | let locale = "en"; // default
104 | if (cookies && cookies.includes("rh_locale")) {
105 | const localeCookie = cookies
106 | .split(";")
107 | .filter((c) => c.split("=")[0].trim() === "rh_locale")[0];
108 | if (localeCookie) {
109 | const localeCookieValue = localeCookie.split("=")[1].trim();
110 | if (chromeCache.LOCALES.includes(localeCookieValue)) {
111 | locale = localeCookieValue;
112 | } else {
113 | console.warn(
114 | `spandx received rh_locale cookie "${locale}" which is not a supported locale, falling back to "en". supported locales are ${chromeCache.LOCALES}`
115 | );
116 | }
117 | }
118 | }
119 | return locale;
120 | }
121 |
122 | module.exports = { SPACommentResolver, chromeSwapper };
123 |
--------------------------------------------------------------------------------
/RH.md:
--------------------------------------------------------------------------------
1 | # spandx & Red Hat Customer Portal
2 |
3 | This is a guide for adding spandx to any application that is part of the Red Hat Customer Portal ([access.redhat.com](https://access.redhat.com)).
4 |
5 | ## Quick-start
6 |
7 | First, add spandx as a devDependency of your project.
8 |
9 | ```
10 | npm i -D spandx
11 | ```
12 |
13 | Then, answer a few questions to create a `spandx.config.js`.
14 |
15 | ```
16 | npx spandx init cp
17 | ```
18 |
19 | If you need to, add local DNS entries for `*.foo.redhat.com`. If you aren't sure if you nee this, it's safe to go ahead and run it. Note: you'll probably need to `sudo` this command, but if you aren't comfortable doing that, run it without sudo and it will print out what you need to paste into `/etc/hosts`.
20 |
21 | ```
22 | npx spandx init cp addhosts
23 | ```
24 |
25 | ## Portal Chrome settings
26 |
27 | This section describes the Portal Chrome-specific settings in more detail. The `spandx init cp` command sets good defaults for Customer Portal work, but if you need to customize the settings, read on.
28 |
29 | Portal Chrome settings live in your spandx config file under the `portalChrome` property.
30 |
31 | ### Resolving SPA comments, such as ``
32 |
33 | spandx can replace these comments with their corresponding Portal Chrome parts:
34 |
35 | - `` ← `/services/chrome/head`
36 | - `` ← `/services/chrome/header`
37 | - `` ← `/services/chrome/footer`
38 |
39 | This can be enabled in your spandx.config.js file with the following setting.
40 |
41 | ```js
42 | module.exports = {
43 | portalChrome: {
44 | resolveSPAComments: true,
45 | },
46 | };
47 | ```
48 |
49 | If `resolveSPAComments` is true, spandx will inject Portal Chrome into any `text/html` request that passes through. It looks for the following placeholder comments and will replace them with the corresponding chrome part.
50 |
51 | | comment | location | description |
52 | | --------------------- | ------------------------ | --------------------------------------------------------------- |
53 | | `` | within your `` tag | will be replaced with the contents of `/services/chrome/head` |
54 | | `` | just after `` | will be replaced with the contents of `/services/chrome/header` |
55 | | `` | just before `` | will be replaced with the contents of `/services/chrome/footer` |
56 |
57 | This setting involves making requests to `/services/chrome/*`, which brings up the question of which host to fetch the chroming from. To make this as easy as possible, this feature taps into your existing spandx routes. In short, if you can hit `/services/chrome/head` from your spandx host, you'll be fine.
58 |
59 | For example, if you're routing `/app` to your local application and everything else to the Customer Portal, spandx will be able to resolve `/services/chrome/*` just fine.
60 |
61 | ```js
62 | routes: {
63 | '/app' : { host: "http://localhost:8080" },
64 | '/' : { host: 'https://access.redhat.com' }
65 | }
66 | ```
67 |
68 | ### Valid self-signed certs 🔒
69 |
70 | To set up valid local SSL certificates, [install mkcert](https://github.com/FiloSottile/mkcert#installation). Then run `mkcert -install` (you only need to do this once).
71 |
72 | Then you can this `mkcert` script to your package.json's `"scripts"` object. It creates self-signed certificates for spandx to use, and places them in a `ssl` directory (which should be gitignored).
73 |
74 | ```json
75 | "mkcert": "mkdir ssl > /dev/null; mkcert --cert-file ssl/spandx.pem --key-file ssl/spandx-key.pem dev.foo.redhat.com qa.foo.redhat.com stage.foo.redhat.com prod.foo.redhat.com",
76 | ```
77 |
78 | Each developer should run `npm run mkcert` or `yarn mkcert` once per clone of the project (or for users of [git worktree](https://git-scm.com/docs/git-worktree), once per worktree).
79 |
80 | Starting with spandx 2.2.4, spandx configs generated with `spandx init cp` automatically detect and use certs generated by the mkcert command above (ie, it looks for `ssl/spandx.pem` and `ssl/spandx-key.pem`). If your spandx.config.js was created before spandx 2.2.4, set your `bs.https` configuration to look like this:
81 |
82 | ```js
83 | bs: {
84 | https: { cert: "ssl/spandx.pem", key: "ssl/spandx-key.pem" }
85 | },
86 | ```
87 |
88 | And don't forget to gitignore the certs!
89 |
90 | **.gitignore**
91 | ```
92 | ssl/*
93 | ```
94 |
95 |
96 | ## Primer settings
97 |
98 | Primer is an upcoming re-imagining of Portal Chrome.
99 |
100 | ### Preview Primer head/header/footer
101 |
102 | This feature allows grafting HTML template changes into an existing page, even on a remote server, effectively previewing what the changes will look like when they are deployed to that server.
103 |
104 | With `primer.preview` set to `true`, spandx detects the head, header, and footer (the "parts") in Customer Portal pages you visit and replaces them with fresh Primer parts fetched from `/services/primer`. You can control the routing of this request in your `routes` object.
105 | ```js
106 | module.exports = {
107 | primer: {
108 | preview: true,
109 | },
110 | };
111 | ```
112 |
113 | Primer's head, header, and footer parts are wrapped with comments which are used as tokens to identify the location of each part. These tokens facilitate the removal of old parts and injection of fresh parts.
114 |
115 | The wrapper comment tokens look like this:
116 |
117 | - ` ... `
118 | - ` ... `
119 | - ` ... `
120 |
--------------------------------------------------------------------------------
/app/router.js:
--------------------------------------------------------------------------------
1 | const fs = require("fs");
2 | const path = require("path");
3 | const URL = require("url");
4 | const c = require("print-colors");
5 | const _ = require("lodash");
6 | const { flow, includes, get } = require("lodash/fp");
7 | const finalhandler = require("finalhandler");
8 | const serveStatic = require("serve-static");
9 | const resolveHome = require("./resolveHome");
10 | const ProxyAgent = require("proxy-agent");
11 | const priv = {};
12 |
13 | priv.tryPlugin = (plugin, req, res, target, cb) => {
14 | if (typeof plugin === "function") {
15 | plugin(req, res, target).then((t) => {
16 | // Plugin may have sent back a new target
17 | // if they did use it
18 | t = t || target;
19 | cb(t);
20 | }); // TODO what to do if the plugin Promise fails ??
21 | } else {
22 | // Run with the default target
23 | cb(target);
24 | }
25 | };
26 |
27 | priv.doProxy = (proxy, req, res, target, confProxy = null) => {
28 | if (target) {
29 | const options = {
30 | target,
31 | ignorePath: true,
32 | };
33 |
34 | if (confProxy) {
35 | const regex = RegExp(confProxy.pattern);
36 |
37 | // if the target URL passes the regex test based on the
38 | // pattern provided in the proxy.pattern property,
39 | // add a new HttpsProxyAgent
40 | if (regex.test(target)) {
41 | options.agent = new ProxyAgent.ProxyAgent(confProxy.host);
42 | }
43 | }
44 |
45 | proxy.web(req, res, options, (e) => {
46 | console.error(e);
47 | res.writeHead(502, { "Content-Type": "text/plain" });
48 | res.write(
49 | `HTTP 502 Bad gateway\n\nRequest to ${req.url} was proxied to ${target} which did not respond.`
50 | );
51 | res.end();
52 | });
53 | } else {
54 | res.writeHead(404);
55 | res.end();
56 | }
57 | };
58 |
59 | module.exports = (conf, proxy) => {
60 | // for each local file path in the conf, create a serveStatic object for
61 | // serving that dir
62 | const serveLocal = _(conf.routes)
63 | .omitBy(_.isObject)
64 | .mapValues((dir) =>
65 | serveStatic(path.resolve(conf.configDir, resolveHome(dir)), {
66 | redirect: true,
67 | })
68 | )
69 | .value();
70 | return (req, res, next) => {
71 | // figure out which target to proxy to based on the requested resource path
72 | const sortedRoutes = _(conf.routes)
73 | .toPairs()
74 | .filter((v) => _.startsWith(req.url, v[0]))
75 | .sortBy((v) => -v[0].length)
76 | .value();
77 |
78 | const env = req.headers["x-spandx-env"];
79 |
80 | for (let routeCandidate of sortedRoutes) {
81 | const routeKey = routeCandidate[0];
82 | const route = conf.routes[routeKey];
83 | const acceptHTML = flow(
84 | get("headers.accept"),
85 | includes("text/html")
86 | )(req);
87 | const hasExtension = URL.parse(req.url).path.includes(".");
88 | const isDoc = acceptHTML && !hasExtension;
89 | const useSingle = route.single && isDoc;
90 | const routePath = route.path || routeKey;
91 | const targetPath = useSingle
92 | ? routePath
93 | : req.url.replace(new RegExp(`^${routeKey}`), routePath);
94 |
95 | const targetHost = route.host && route.host[env];
96 | let fileExists;
97 | let needsSlash = false;
98 | const localFile = !targetHost;
99 | let target = targetHost + targetPath;
100 |
101 | // determine if the URL path maps to a local directory
102 | // if it maps to a local directory, and if the file exists, serve it
103 | // up. if the URL path maps to an HTTP server, OR if it maps to a file
104 | // but the file doesn't exist, in either case proxy to a remote server.
105 | if (localFile) {
106 | const url = URL.parse(req.url);
107 | const relativeFilePath = url.pathname.replace(
108 | new RegExp(`^${routeKey}/?`),
109 | "/"
110 | ); // remove route path (will be replaced with disk path)
111 |
112 | const absoluteFilePath = path.resolve(
113 | conf.configDir,
114 | resolveHome(route),
115 | relativeFilePath.replace(/^\//, "")
116 | );
117 | fileExists = fs.existsSync(absoluteFilePath);
118 |
119 | if (fileExists) {
120 | if (conf.verbose) {
121 | console.log(
122 | `GET ${c.fg.l.green}${req.url}${c.end} from ${c.fg.l.cyan}${absoluteFilePath}${c.end} ${env}`
123 | );
124 | }
125 |
126 | req.url = relativeFilePath; // update the request's url to be relative to the on-disk dir
127 | serveLocal[routeKey](req, res);
128 | return; // stop here, don't continue to HTTP proxy section
129 | }
130 | }
131 |
132 | if (localFile && !fileExists && routeKey.length > 1) {
133 | continue;
134 | }
135 |
136 | if (localFile && (!fileExists || needsSlash)) {
137 | target = conf.routes["/"].host
138 | ? conf.routes["/"].host[env]
139 | : undefined;
140 | }
141 |
142 | if (target === undefined) continue;
143 |
144 | if (conf.verbose) {
145 | const targetURL = URL.parse(target);
146 | console.log(
147 | `GET ${c.fg.l.green}${req.url}${c.end} from ${
148 | c.fg.l.blue
149 | }${`${targetURL.protocol}//${targetURL.host}`}${c.end}${
150 | c.fg.l.green
151 | }${req.url}${c.end}`
152 | );
153 | }
154 |
155 | priv.tryPlugin(conf.routerPlugin, req, res, target, (t) => {
156 | priv.doProxy(proxy, req, res, t, conf.proxy);
157 | });
158 |
159 | return;
160 | }
161 | };
162 | };
163 |
164 | if (process.env.NODE_ENV === "test") {
165 | // only leak in test
166 | module.exports.priv = priv;
167 | }
168 |
--------------------------------------------------------------------------------
/app/inits/cp/init.js:
--------------------------------------------------------------------------------
1 | const fs = require("fs");
2 | const { promisify } = require("util");
3 |
4 | const inquirer = require("inquirer");
5 | const c = require("print-colors");
6 |
7 | const writeFileAsync = promisify(fs.writeFile);
8 |
9 | function generateConfig(answers) {
10 | return `const fs = require("fs");
11 |
12 | const sslReady =
13 | fs.existsSync("ssl/spandx.pem") && fs.existsSync("ssl/spandx-key.pem");
14 |
15 | if (!sslReady) {
16 | console.log("Launching with invalid SSL cert 🔓");
17 | } else {
18 | console.log("Launching with valid SSL cert 🔒");
19 | }
20 |
21 | module.exports = {
22 | host: {
23 | prod: "prod.foo.redhat.com",
24 | stage: "stage.foo.redhat.com",
25 | qa: "qa.foo.redhat.com",
26 | dev: "dev.foo.redhat.com",
27 | },
28 | port: 1337,
29 | open: true,
30 | startPath: "${answers.path}",
31 | verbose: true,
32 | portalChrome: {
33 | resolveSPAComments: true
34 | },
35 | primer: {
36 | // preview: true
37 | },
38 | proxy: {
39 | host: "http://squid.corp.redhat.com:3128",
40 | pattern: "^https:\/\/(.*?).redhat.com"
41 | },
42 | bs: {
43 | https: sslReady
44 | ? { cert: "ssl/spandx.pem", key: "ssl/spandx-key.pem" } // 🔒
45 | : true, // 🔓
46 | codeSync: ${answers.livereload || true}
47 | },
48 | routes: {${
49 | /* sorry about this formatting... */
50 | answers.location === "dir"
51 | ? `
52 | "${answers.path}": "${answers.dir}",
53 | `
54 | : ""
55 | }${
56 | answers.location === "server"
57 | ? `
58 | "${answers.path}": {
59 | host: "${answers.host}"
60 | },
61 | `
62 | : ""
63 | }
64 | "/": {
65 | host: {
66 | dev: "https://access.dev.redhat.com",
67 | qa: "https://access.qa.redhat.com",
68 | stage: "https://access.stage.redhat.com",
69 | prod: "https://access.redhat.com",
70 | }
71 | }
72 | }
73 | }`;
74 | }
75 |
76 | async function writeHosts() {
77 | const hostile = require("hostile");
78 | const set = promisify(hostile.set);
79 |
80 | const hostnames = [
81 | "dev.foo.redhat.com",
82 | "qa.foo.redhat.com",
83 | "stage.foo.redhat.com",
84 | "prod.foo.redhat.com",
85 | ];
86 |
87 | try {
88 | await set("127.0.0.1", hostnames.join(" "));
89 | console.log(
90 | `Added ${c.fg.l.cyan}cp${c.end} hostnames to ${hostile.HOSTS}`
91 | );
92 | } catch (e) {
93 | console.error(
94 | `Unable to write ${hostile.HOSTS}. Either try again with sudo, or copy the following into your ${hostile.HOSTS} file.
95 | `
96 | );
97 | console.error(`127.0.0.1 ${hostnames.join(" ")}`);
98 | }
99 | }
100 |
101 | async function writeConfig() {
102 | const dirCheck = await inquirer.prompt([
103 | {
104 | type: "confirm",
105 | name: "confirmDir",
106 | message: `Your current directory, \`${process.cwd()}\`, has no package.json file, do you still wish to generate spandx.config.js here?`,
107 | when: () => !fs.existsSync("./package.json"),
108 | },
109 | {
110 | type: "confirm",
111 | name: "confirmOverwrite",
112 | message: `spandx.config.js already exists in your current directory, do you wish to overwrite it?`,
113 | when: () => fs.existsSync("./spandx.config.js"),
114 | },
115 | ]);
116 |
117 | ["confirmDir", "confirmOverwrite"].forEach((confirm) => {
118 | if (dirCheck.hasOwnProperty(confirm) && !dirCheck[confirm]) {
119 | console.log(`Aborting.`);
120 | process.exit(0);
121 | }
122 | });
123 |
124 | const answers = await inquirer.prompt([
125 | {
126 | type: "input",
127 | name: "path",
128 | message: "Path (ex: /support/cases or /search)",
129 | validate: (value) => {
130 | console.log(value);
131 | const startsWithSlash = value.startsWith("/");
132 | const noWhitespace = !/\s/.test(value);
133 | const valid = startsWithSlash && noWhitespace;
134 |
135 | const messages = [];
136 |
137 | if (!startsWithSlash) {
138 | messages.push("path must start with '/'");
139 | }
140 | if (!noWhitespace) {
141 | messages.push("path must not contain whitespace");
142 | }
143 |
144 | return valid || messages.join(", ");
145 | },
146 | },
147 | {
148 | type: "list",
149 | name: "location",
150 | message:
151 | "Should spandx load your app from a static dist directory, or from a local dev server (such as webpack-dev-server)?",
152 | choices: [
153 | {
154 | name: "dev server",
155 | value: "server",
156 | },
157 | { name: "dist directory", value: "dir" },
158 | ],
159 | },
160 | {
161 | type: "input",
162 | name: "host",
163 | default: "localhost:8080",
164 | message: "What is your local dev server's URL?",
165 | when: (answers) => answers.location === "server",
166 | filter: (answer) => {
167 | const missingProtocol = !/https?:\/\//.test(answer);
168 | if (missingProtocol) {
169 | // default to http
170 | return `http://${answer}`;
171 | } else {
172 | return answer;
173 | }
174 | },
175 | },
176 | {
177 | type: "confirm",
178 | name: "livereload",
179 | default: true,
180 | message:
181 | "Enable spandx's livereload? If your dev server provides LiveReload/browser-sync, choose No.",
182 | when: (answers) => answers.location === "server",
183 | },
184 | {
185 | type: "input",
186 | name: "dir",
187 | default: "dist",
188 | message:
189 | "What is the path to your dist directory? It should be relative to your project root (where package.json is).",
190 | when: (answers) => answers.location === "dir",
191 | },
192 | ]);
193 |
194 | try {
195 | await writeFileAsync("spandx.config.js", generateConfig(answers));
196 | } catch (e) {
197 | console.error(
198 | `Writing spandx.config.js failed. Original error below:`
199 | );
200 | console.error(e);
201 | process.exit(1);
202 | }
203 |
204 | console.log(`Created spandx.config.js`);
205 | console.log(
206 | "One last step to enable resolving local hostnames like 'stage.foo.redhat.com'"
207 | );
208 | console.log();
209 | console.log(" spandx init cp addhosts");
210 | }
211 |
212 | module.exports = async function initCP(argv) {
213 | if (argv._.length === 2) {
214 | writeConfig(argv);
215 | } else if (argv._.length === 3) {
216 | writeHosts();
217 | } else {
218 | console.error(`Couldn't initialize cp, invalid arguments given.`);
219 | }
220 | };
221 |
--------------------------------------------------------------------------------
/app/config.js:
--------------------------------------------------------------------------------
1 | const fs = require("fs");
2 | const path = require("path");
3 |
4 | const _ = require("lodash");
5 | const resolveHome = require("./resolveHome");
6 | const c = require("print-colors");
7 | const porty = require("porty");
8 |
9 | class ConfigProcessError extends Error {
10 | constructor(...args) {
11 | super(...args);
12 | this.name = this.constructor.name;
13 | Error.captureStackTrace(this, ConfigProcessError);
14 | }
15 | }
16 |
17 | class ConfigOpenError extends Error {
18 | constructor(...args) {
19 | super(...args);
20 | this.name = this.constructor.name;
21 | Error.captureStackTrace(this, ConfigOpenError);
22 | }
23 | }
24 |
25 | class PortUnavailableError extends Error {
26 | constructor(...args) {
27 | super(...args);
28 | this.name = this.constructor.name;
29 | Error.captureStackTrace(this, PortUnavailableError);
30 | }
31 | }
32 |
33 | const defaultConfig = {
34 | protocol: "http:",
35 | host: "localhost",
36 | port: 1337,
37 | verbose: false,
38 | silent: false,
39 | routes: {
40 | "/": path.resolve(__dirname, "splash"),
41 | },
42 | bs: {},
43 | };
44 |
45 | let configState = {};
46 |
47 | async function create(incomingConfig = {}, configDir = __dirname) {
48 | configState.currentConfig = _.defaults(incomingConfig, defaultConfig);
49 |
50 | if (incomingConfig.port === "auto") {
51 | incomingConfig.port = await porty.find();
52 | } else if (!(await porty.test(incomingConfig.port))) {
53 | throw new PortUnavailableError(
54 | `port ${incomingConfig.port} is already in use.`
55 | );
56 | }
57 |
58 | // choose a port for the internal proxy, avoiding the external port just chosen
59 | incomingConfig.internalPort = await porty.find({
60 | min: incomingConfig.port,
61 | avoids: [incomingConfig.port],
62 | });
63 |
64 | _.extend(
65 | configState.currentConfig,
66 | processConf(configState.currentConfig, configDir)
67 | );
68 |
69 | validateHosts(configState.currentConfig);
70 |
71 | return configState.currentConfig;
72 | }
73 |
74 | function get() {
75 | return configState.currentConfig;
76 | }
77 |
78 | async function fromFile(filePath = `${process.cwd()}/spandx.config.js`) {
79 | let confObj;
80 | const fullPath = path.resolve(__dirname, filePath);
81 | try {
82 | confObj = require(fullPath);
83 | } catch (e) {
84 | if (e.toString().indexOf("Error: Cannot find module") === 0) {
85 | throw new ConfigOpenError(
86 | `Tried to open spandx config file ${c.fg.l.cyan}${filePath}${c.end} but couldn't find it, or couldn't access it.`
87 | );
88 | } else {
89 | throw new ConfigProcessError(
90 | `Tried to process spandx config file ${c.fg.l.cyan}${filePath}${c.end} ` +
91 | `but. Got an exception loading the config: ${e}`
92 | );
93 | }
94 | }
95 | const conf = await create(confObj, path.parse(fullPath).dir);
96 | return conf;
97 | }
98 |
99 | function isSingleHost(conf) {
100 | const singleHost = _.isString(conf.host);
101 | const multiHost = _.isPlainObject(conf.host);
102 |
103 | if (singleHost === multiHost) {
104 | throw new Error(
105 | "'host' is the wrong type, must be either string or object"
106 | );
107 | }
108 |
109 | return singleHost;
110 | }
111 |
112 | function validateHosts(conf) {
113 | const routeHostMaps = _(conf.routes)
114 | .filter(_.isPlainObject) // only look at routes that are object, not strings (strings indicate local file paths)
115 | .map("host") // grab the host vaule
116 | .filter(_.isPlainObject); // grab any host values that are object
117 |
118 | // ERROR if any route hosts have maps with different keys than the spandx host map
119 | if (!validateEnvsMatch(conf, routeHostMaps)) {
120 | throw new Error(
121 | `spandx is configured for multi-host mode ('host' is an object map), but one or more routes have environment names that don't match the names from 'host'`
122 | );
123 | }
124 |
125 | return true;
126 | }
127 |
128 | function validateEnvsMatch(conf, routeHostMaps) {
129 | const sortKeys = (obj) => _(obj).keys().sortBy().value();
130 |
131 | const hasSameKeys = _.curry((envs1, envs2) =>
132 | _.isEqual(sortKeys(envs1), sortKeys(envs2))
133 | );
134 |
135 | const spandxHosts = sortKeys(conf.host);
136 |
137 | const matchesSpandxHosts = hasSameKeys(spandxHosts);
138 |
139 | const allEnvsMatch = routeHostMaps
140 | .map((h) => sortKeys(h))
141 | .filter((envs) => !matchesSpandxHosts(envs)) // filter *out* the ones that match spandx hosts
142 | .isEmpty(); // if empty, then every single route host matched
143 |
144 | return allEnvsMatch;
145 | }
146 |
147 | function processConf(conf, configDir = __dirname) {
148 | // add a conf entry indicating whetehr spandx is running in multi-host mode
149 | conf.multiHost = !isSingleHost(conf);
150 |
151 | // separate the local disk routes from the web routes
152 | const routeGroups = _(conf.routes)
153 | .toPairs()
154 | .partition((pair) => _.isObject(pair[1])); // filter out URLs, only want local file paths here
155 |
156 | const webRoutes = routeGroups.get(0);
157 | const diskRoutes = routeGroups.get(1);
158 |
159 | const webRouteHosts = _(webRoutes)
160 | .map(1) // get route value
161 | .filter((r) => _.isString(r.host)); // only select routes with strings for their host; at this point it should be ALL of them, but playing it safe anyway
162 |
163 | // convert any simplified host values into explicit host config (ie,
164 | // convert from a string like "localhost" to an object like
165 | // { default: "localhost" }
166 | if (conf.multiHost) {
167 | // multi host mode
168 |
169 | // for any web routes that have a single host, change them into a
170 | // multi-host entry where each env points to the same place
171 | webRouteHosts.forEach((r) => {
172 | const routeHost = r.host;
173 | r.host = _({})
174 | .extend(conf.host)
175 | .mapValues((v) => routeHost)
176 | .value();
177 | });
178 | } else {
179 | // single host mode
180 | conf.host = { default: conf.host };
181 | webRouteHosts.forEach((r) => (r.host = { default: r.host })); // convert host string to object
182 | }
183 |
184 | // build a list of file paths to watch for auto-reload, by combining the
185 | // local disk route paths with the web routes that provided local paths
186 | // (web routes can provide an optional path to local files if they want
187 | // browser-sync to auto-reload their stuff)
188 | const diskRouteFiles = _(diskRoutes)
189 | .map(1)
190 | .map((filePath) => path.resolve(configDir, resolveHome(filePath)))
191 | .value();
192 | const otherLocalFiles = _(webRoutes)
193 | .map(1)
194 | .filter("watch")
195 | .map("watch")
196 | .map((filePath) => path.resolve(configDir, resolveHome(filePath)))
197 | .value();
198 |
199 | const files = _.concat(diskRouteFiles, otherLocalFiles);
200 |
201 | // create a list of browserSync 'rewriteRules' that will modify the
202 | // contents of requests coming back from the proxied remote servers. this
203 | // is mainly useful for rewriting links from, say 'www.foo.com' to
204 | // 'localhost:1337' so that when you click on a link, you stay in your
205 | // spandx'd environment.
206 | const protocol = conf.bs.https ? "https:" : "http:";
207 | const rewriteRules = _(webRoutes)
208 | .map("1.host")
209 | .map((h) =>
210 | _.map(h, (v, env) => ({
211 | match: new RegExp(v, "g"),
212 | replace: `${protocol}//${conf.host[env]}:${conf.port}`,
213 | }))
214 | )
215 | .flatten()
216 | .value();
217 |
218 | const startPath = conf.startPath || "";
219 | const spandxUrl = _.map(conf.host, (host, env) => ({
220 | env,
221 | url: `${protocol}//${host}:${conf.port}${startPath}`,
222 | }));
223 |
224 | // allow 'silent' to override 'verbose'
225 | const verbose = conf.silent ? false : conf.verbose;
226 |
227 | return {
228 | routeGroups,
229 | verbose,
230 | webRoutes,
231 | diskRoutes,
232 | diskRouteFiles,
233 | otherLocalFiles,
234 | files,
235 | rewriteRules,
236 | protocol,
237 | spandxUrl,
238 | startPath,
239 | configDir,
240 | };
241 | }
242 |
243 | function getRoute(conf, urlPath) {
244 | // figure out which route to proxy to based on the requested resource path
245 | const bestMatchedRoute = _(conf.routes)
246 | .toPairs()
247 | .filter((v) => _.startsWith(urlPath, v[0]))
248 | .sortBy((v) => -v[0].length)
249 | .first();
250 | return bestMatchedRoute[1];
251 | }
252 |
253 | function getTargetURL(conf, spandxEnv, urlPath) {
254 | // figure out which target URL to proxy to based on the requested resource path
255 | const route = getRoute(conf, urlPath);
256 |
257 | if (typeof route == "string") {
258 | // local disk route
259 | return { route, routeType: "disk" };
260 | } else if (typeof route.host == "string") {
261 | return { route: route.host, routeType: "network" };
262 | } else {
263 | return { route: route.host[spandxEnv], routetype: "network" };
264 | }
265 | }
266 |
267 | function getTargetHost(conf, spandxEnv, urlPath, spandxOrigin) {
268 | const { route, routeType } = getTargetURL(conf, spandxEnv, urlPath);
269 | let host = routeType === "disk" ? spandxOrigin : route;
270 | return host;
271 | }
272 |
273 | module.exports = {
274 | create,
275 | get,
276 | fromFile,
277 | defaultConfig,
278 | process: processConf,
279 | getRoute,
280 | getTargetURL,
281 | getTargetHost,
282 | };
283 |
--------------------------------------------------------------------------------
/app/spandx.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | const http = require("http");
4 | const path = require("path");
5 | const https = require("https");
6 |
7 | const browserSync = require("browser-sync");
8 | const connect = require("connect");
9 | const httpProxy = require("http-proxy");
10 | const transformerProxy = require("transformer-proxy");
11 | const _ = require("lodash");
12 | const c = require("print-colors");
13 | const opn = require("opn");
14 |
15 | const router = require("./router.js");
16 | const config = require("./config");
17 | const resolveHome = require("./resolveHome");
18 | const chromeMiddleware = require("./chromeMiddleware");
19 | const { createEsiMiddleware } = require("./esiMiddleware");
20 |
21 | let proxy;
22 | let internalProxy;
23 | let bs;
24 |
25 | async function init(confIn) {
26 | // if initialized with a string, assume it's a file path to a config file
27 | // if initialized with an object, assume it's a configuration object
28 | // if initialized with no arguments, use default configuration
29 | switch (typeof confIn) {
30 | case "string":
31 | conf = await config.fromFile(confIn);
32 | if (conf.verbose && !conf.silent) {
33 | console.log(`configuration: ${c.fg.l.cyan}${confIn}${c.end}`);
34 | }
35 | break;
36 | case "object":
37 | conf = await config.create(confIn);
38 | if (conf.verbose && !conf.silent) {
39 | console.log("configuration: custom object");
40 | }
41 | break;
42 | default:
43 | conf = await config.create();
44 | if (conf.verbose && !conf.silent) {
45 | console.log("configuration: defaults");
46 | }
47 | }
48 |
49 | // since this is a local development tool, allow self-signed ssl certificates.
50 | https.globalAgent.options.rejectUnauthorized = false;
51 |
52 | bs = browserSync.create();
53 |
54 | // connect server w/ proxy
55 |
56 | const internalProxyPort = conf.internalPort;
57 | const internalProxyOrigin = `http://localhost:${internalProxyPort}`;
58 |
59 | const app = connect();
60 |
61 | proxy = httpProxy.createProxyServer({
62 | changeOrigin: true,
63 | preserveHeaderKeyCase: true,
64 | autoRewrite: true,
65 | secure: false, // don't validate SSL/HTTPS
66 | protocolRewrite: conf.protocol.replace(":", ""),
67 | cookieDomainRewrite: true,
68 | });
69 |
70 | //
71 | // app.use((req, res, next) => {
72 | // next();
73 | // });
74 |
75 | // if configuration says to, replace Drupal SPA comments for chroming
76 | if (_.get(conf, "portalChrome.resolveSPAComments")) {
77 | app.use(transformerProxy(chromeMiddleware.SPACommentResolver(conf)));
78 | }
79 |
80 | // if configuration says to, inject fresh chrome into prechromed pages
81 | if (_.get(conf, "primer.preview")) {
82 | app.use(transformerProxy(chromeMiddleware.chromeSwapper(conf)));
83 | }
84 |
85 | if (_.get(conf, "esi")) {
86 | console.log("ESI enabled");
87 | app.use((res, req, next) => {
88 | console.log("request received");
89 | if (
90 | res.headers.accept.includes("text/html") ||
91 | res.headers.accept.includes("*/*")
92 | ) {
93 | console.log("it is html; applying ESI");
94 | transformerProxy(createEsiMiddleware(conf))(res, req, next);
95 | } else {
96 | console.log("it is not html");
97 | next();
98 | }
99 | });
100 | }
101 |
102 | // dynamically proxy to local filesystem or remote webserver
103 | app.use(router(conf, proxy));
104 | internalProxy = http.createServer(app).listen(internalProxyPort);
105 |
106 | // output for humans
107 | if (conf.verbose) {
108 | console.log("Launching spandx with the following configuration");
109 | console.log();
110 |
111 | console.log("These paths will be routed to the following remote hosts");
112 | console.log();
113 | console.log(
114 | _.map(conf.webRoutes, (route) => {
115 | return conf.spandxUrl
116 | .map(({ url }) => {
117 | const env = _.findKey(conf.host, (host) =>
118 | new RegExp(`${host}`).test(url)
119 | );
120 |
121 | return ` ${c.fg.l.blue}${url
122 | .replace(/\/$/, "")
123 | .replace(new RegExp(`${conf.startPath}$`), "")}${
124 | c.end
125 | }${c.fg.l.green}${route[0]}${c.e} will be routed to ${
126 | c.fg.l.blue
127 | }${route[1].host[env] || route[1].host}${c.e}${
128 | c.fg.l.green
129 | }${route[0]}${c.e}`;
130 | })
131 | .join("\n");
132 | }).join("\n")
133 | );
134 | console.log();
135 |
136 | console.log("These paths will be routed to your local filesystem");
137 | console.log();
138 | console.log(
139 | _.map(conf.diskRoutes, (route) => {
140 | return conf.spandxUrl
141 | .map(
142 | ({ url }) =>
143 | ` ${c.fg.l.blue}${url
144 | .replace(/\/$/, "")
145 | .replace(
146 | new RegExp(`${conf.startPath}$`),
147 | ""
148 | )}${c.end}${c.fg.l.green}${route[0]}${
149 | c.end
150 | } will be routed to ${c.fg.l.cyan}${path.resolve(
151 | conf.configDir,
152 | resolveHome(route[1])
153 | )}${c.e}`
154 | )
155 | .join("\n");
156 | }).join("\n")
157 | );
158 |
159 | console.log();
160 |
161 | console.log(
162 | "Your browser will refresh when files change under these paths"
163 | );
164 | console.log();
165 | console.log(
166 | _.map(conf.files, (file) => ` ${c.fg.l.cyan}${file}${c.e}`).join(
167 | "\n"
168 | )
169 | );
170 | console.log();
171 |
172 | console.log(
173 | "These find/replace rules will be used to fix links in remote server responses"
174 | );
175 | console.log();
176 | console.log(
177 | _.map(
178 | conf.rewriteRules,
179 | (rule) =>
180 | ` ${c.fg.l.pink}${rule.match}${c.e} will be replaced with "${c.fg.d.green}${rule.replace}${c.e}"`
181 | ).join("\n")
182 | );
183 | console.log();
184 | }
185 |
186 | // launch!
187 |
188 | // create a promise that resolves when browsersync is ready
189 | const bsReadyPromise = new Promise((resolve) => {
190 | const bsOptions = _.defaultsDeep(
191 | {
192 | // this object's browser-sync settings cannot be overridden by a user's spandx.config.js
193 | port: conf.port,
194 | open: false,
195 | startPath: conf.startPath,
196 | logLevel: "silent",
197 | files: conf.files,
198 | proxy: {
199 | target: internalProxyOrigin,
200 | proxyReq: [
201 | function (proxyReq, req, res) {
202 | // find and set a header to keep track of the spandx origin
203 | const url = new URL("http://localhost/");
204 | url.hostname = req.headers.host.split(":")[0];
205 | url.port = conf.port;
206 | url.protocol = conf.bs.https ? "https:" : "http:";
207 | const origin = url.origin;
208 |
209 | // set a header for spandx origin and env on both the request and response
210 | const env = _.findKey(
211 | conf.host,
212 | (host) => host === url.hostname
213 | );
214 |
215 | [res, proxyReq].forEach((r) => {
216 | r.setHeader("X-Spandx-Env", env || "default");
217 | r.setHeader("X-Spandx-Origin", origin);
218 | });
219 |
220 | if (typeof env === "undefined") {
221 | if (!config.silent) {
222 | console.warn(
223 | `WARN request received at ${origin} which is not in the spandx config`
224 | );
225 | }
226 | }
227 | },
228 | ],
229 | },
230 | rewriteRules: _.concat(conf.rewriteRules, conf.bs.rewriteRules),
231 | },
232 | _.omit(conf.bs, "rewriteRules"),
233 | {
234 | // this object's browser-sync settings can be overridden by a user's spandx.config.js
235 | ghostMode: false,
236 | cors: true,
237 | online: false,
238 | ui: false,
239 | }
240 | );
241 | bs.init(bsOptions, () => {
242 | if (conf.open) {
243 | opn(conf.spandxUrl[0].url);
244 | }
245 | resolve(bs);
246 | });
247 | });
248 |
249 | if (!conf.silent) {
250 | const maxEnvLength = conf.spandxUrl.reduce(
251 | (m, { env }) => Math.max(m, env.length),
252 | 0
253 | );
254 | console.log(
255 | `spandx URL${
256 | conf.spandxUrl.length > 1 ? "s" : ""
257 | }:\n\n${conf.spandxUrl
258 | .map(
259 | ({ env, url }) =>
260 | ` ${
261 | env === "default"
262 | ? ""
263 | : `${env.padEnd(maxEnvLength + 1)}: `
264 | }${c.fg.l.blue}${url}${c.end}`
265 | )
266 | .join("\n")}\n`
267 | );
268 | }
269 |
270 | return bsReadyPromise;
271 | }
272 |
273 | function exit() {
274 | if (bs && bs.exit) {
275 | bs.exit();
276 | }
277 | if (internalProxy && internalProxy.close) {
278 | internalProxy.close();
279 | }
280 | if (proxy && proxy.close) {
281 | proxy.close();
282 | }
283 | }
284 |
285 | if (require.main === module) {
286 | init();
287 | }
288 |
289 | module.exports = { init, exit };
290 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [![Build Status][build-img]][build]
4 |
5 | # What is spandx?
6 |
7 | spandx is an **HTTP switchboard**. With it, you can weave together pieces of a large, complex website by choosing which resources should come from your local system and which should come from a remote environment.
8 |
9 | For example, you could point spandx at your production site, but route `/static/js` to a local directory, which allows you to test your local JS against the production environment. Code in production, it's fun.
10 |
11 | More technically, spandx is a flexible, configuration-based reverse proxy for local development.
12 |
13 | # Quick-start
14 |
15 | *(Note: if you're a developer on the Customer Portal, please use [this guide][rh-quickstart])*
16 |
17 | While I recommend [local install][local-dep], if you want to quickly take spandx for a whirl, the fastest way to get started is by installing spandx as a global package.
18 |
19 | npm install -g spandx
20 |
21 | Generate a sample configuration file:
22 |
23 | spandx init > spandx.config.js
24 |
25 | Launch!
26 |
27 | spandx
28 |
29 | ---
30 |
31 | # Table of Contents
32 |
33 |
34 |
35 | - [Commands](#commands)
36 | * [spandx](#spandx)
37 | * [init](#init)
38 | - [Configuration](#configuration)
39 | * [spandx.config.js](#spandxconfigjs)
40 | * [Routes](#routes)
41 | + [Routing to a local directory](#routing-to-a-local-directory)
42 | + [Routing to a server](#routing-to-a-server)
43 | - [Multi-host routing](#multi-host-routing)
44 | - [Path rewriting](#path-rewriting)
45 | - [single mode](#single-mode)
46 | * [Setting up the proxy object](#setting-up-the-proxy-object)
47 | * [Overriding Browsersync options](#overriding-browsersync-options)
48 | + [Enabling HTTPS](#enabling-https)
49 | - [spandx as a local dependency](#spandx-as-a-local-dependency)
50 | - [Contributing](#contributing)
51 | * [Commit messages](#commit-messages)
52 | * [Running specific tests](#running-specific-tests)
53 | - [Known issues](#known-issues)
54 | * [cURLing spandx](#curling-spandx)
55 | + [Body URL rewriting](#body-url-rewriting)
56 | + [single mode URL rewriting](#single-mode-url-rewriting)
57 | - [Alternatives](#alternatives)
58 |
59 |
60 |
61 | # Commands
62 |
63 | ## spandx
64 |
65 | To launch spandx, simply run `spandx`. If a `spandx.config.js` file exists in the current directory, it will be used.
66 |
67 | Option | Description | Example
68 | --- | --- | ---
69 | `-c`, `--config` | Specify an alternate config file. Config files are JS by default (to enable commenting), but JSON is also accepted. | `spandx -c ./configs/spandx.json`
70 | `-v`, `--version` | Print the current version of spandx. | `spandx -v`
71 |
72 | ## init
73 |
74 | Generate a configuration file. When invoked with no arguments, it prints a barebones config file. Redirect to a file (this could be improved by writing the file automatically).
75 |
76 | ```
77 | spandx init > spandx.config.js
78 | ```
79 |
80 | # Configuration
81 |
82 | After `spandx init` has generated a configuration file for you, there are many ways you can tweak it.
83 |
84 | ## spandx.config.js
85 |
86 | Here are the configuration options accepted by the config file.
87 |
88 | Option | Description | Type
89 | ---|---|---
90 | `host` | The hostname you wish to use to access spandx. Usually "localhost", or a [multi-host](#multi-host-routing) object. | string or object
91 | `port` | The port for spandx to listen on, or "auto". | number or "auto"
92 | `open` | Whether to open a browser tab when spandx is launched. | boolean
93 | `startPath` | The URL path to open, if `open` is true. ex: `"/site"`. | string
94 | `verbose` | Display English summary of configuration settings and display Browsersync logs, or not. | boolean
95 | `silent` | Print nothing to stdout. | boolean
96 | `routes` | Define where to send requests for any number of URL paths, best explained in [routes by example](#routes). | object
97 | `bs` | A [Browsersync config object][bs-options], in case you need to further customize spandx's Browsersync instance. | object
98 | `portalChrome` | Settings related to Portal Chrome, see [Portal Chrome settings][portal-chrome-settings]. | object
99 | `esi` | Set to `true` to enable processing [ESI][esi] tags, or pass in a [nodesi][nodesi] config object. | boolean or object
100 | `proxy` | Define a proxy host and a URL regex pattern for target URLs that should be proxied. | object
101 |
102 | ## Routes
103 |
104 | Routes are the core of spandx's flexibility. They allow you to define where to pull assets at any given URL path.
105 |
106 | Route all requests to palebluepixel.org (a perfect reverse proxy), *unless* the request falls under `/theme`, in which case look for files in `~/projects/pbp/theme`.
107 |
108 | routes: {
109 | "/theme" : "~/projects/pbp/theme/",
110 | "/" : { host: "https://palebluepixel.org/" },
111 | },
112 |
113 | Here's how this configuration would play out.
114 |
115 | 1. visit localhost:1337 and you see what looks like palebluepixel.org
116 | 2. one exception, the page includes `/theme/site.css`
117 | 3. because it falls under the `/theme` route, spandx fetches `~/projects/pbp/theme/site.css` instead of `palebluepixel.org/theme/site.css`
118 |
119 | This effectively _overlays_ a local directory of static files on top of a remote server. In other words... test in production!
120 |
121 | In addition, because `~/projects/pbp/theme` is a local directory, changes to files inside it will trigger a Browsersync refresh.
122 |
123 | ### Routing to a local directory
124 |
125 | To route to a local directory, the destination should be a string. The directory path can be absolute or relative. If relative, it's resolved relative to the spandx.config.js file.
126 |
127 | ```
128 | routes: {
129 | "/incoming": "./destination"
130 | }
131 | ```
132 |
133 | ### Routing to a server
134 |
135 | To route to a server, the destination should be an object with a `host` property.
136 |
137 | ```js
138 | routes: {
139 | "/incoming": {
140 | host: "http://localhost:8080"
141 | }
142 | }
143 | ```
144 |
145 | In this form, requests to `/incoming` will route to `http://localhost:8080/incoming`. If you would rather route to a different path (such as `http://localhost:8080`), you can specify a `path` property as follows.
146 |
147 | #### Multi-host routing
148 |
149 | Many projects have multiple remote webservers, for example a dev server, qa, staging, and production. To simplify dealing with multiple remotes, spandx offers multi-host routing, whether the local hostname determines which remote host to proxy to. Here's an example config.
150 |
151 |
152 | ```js
153 | module.exports = {
154 | host: {
155 | +---< dev: "dev-local.foo.com",
156 | | prod: "prod-local.foo.com"
157 | | },
158 | | routes: {
159 | | "/": {
160 | | host: {
161 | +-----------> dev: "http://dev.foo.com",
162 | prod: "http://www.foo.com"
163 | }
164 | }
165 | }
166 | };
167 | ```
168 |
169 | In this case, dev-local.foo.com and prod-local.foo.com should be entered in `/etc/hosts`, pointing to `127.0.0.1`. Then, when spandx is visited at dev-local.foo.com, spandx knows it's the "dev" host and proxies to dev.foo.com. The names "dev" and "prod" can be any names you choose. See the [examples](examples) dir for a working example.
170 |
171 |
172 | #### Path rewriting
173 |
174 | ```js
175 | routes: {
176 | "/my-app": {
177 | host: "http://localhost:8080",
178 | path: "/"
179 | }
180 | }
181 | ```
182 |
183 | With this path setting, requests to `/my-app` will route to `http://localhost:8080/`. This is particularly useful when using a local development server (like webpack-dev-server) where your app lives at `/`.
184 |
185 | #### single mode
186 |
187 | When a route has `single: true`, spandx will send all requests under that route to a single index.html file (except requests for assets).
188 |
189 | This is intended to be used with [`pushState`][pushstate] and enables hash-free user-friendly URLs for single-page apps.
190 |
191 | ```js
192 | routes: {
193 | "/my-app": {
194 | host: "http://localhost:8080",
195 | single: true
196 | }
197 | }
198 | ```
199 |
200 | With this config, a request to `/my-app/users/active` would be routed to `http://localhost:8080/my-app/index.html`.
201 |
202 | `single` can also be combined with `path`.
203 |
204 | ```js
205 | routes: {
206 | "/my-app": {
207 | host: "http://localhost:8080",
208 | path: "/",
209 | single: true
210 | }
211 | }
212 | ```
213 |
214 | Here, a request to `/my-app/users/active` would be routed to `http://localhost:8080/`.
215 |
216 | ## Setting up the proxy object
217 |
218 | If you're developing an app that needs to connect to a proxy, use the proxy object to define the proxy host and define a URL regex pattern for request that should go through the proxy.
219 |
220 | ```js
221 | proxy: {
222 | host: "http://someproxy.com:1234",
223 | pattern: "^https:\/\/(.*?).someurl.com"
224 | }
225 | ```
226 |
227 | Here, when a URL like `https://api.qa.someurl.com` is requested, it would be routed through the proxy.
228 |
229 | ## Overriding Browsersync options
230 |
231 | Internally, spandx uses Browsersync to power some features like live-reloading. Custom [Browsersync options][bs-options] can be embedded in your spandx.config.js file under the `bs` property.
232 |
233 | For example, let's enable HTTPS.
234 |
235 | ### Enabling HTTPS
236 |
237 | You can enable HTTPS by
238 |
239 | ```js
240 | module.exports = {
241 | bs: {
242 | https: true,
243 | }
244 | };
245 | ```
246 |
247 | For extra customization (like providing your own certs), see [Browsersync's HTTPS options][bs-https].
248 |
249 | # spandx as a local dependency
250 |
251 | The quick-start has you install spandx as a global package for simplicity, but installing it locally per-project is a better approach in many ways.
252 |
253 | Go to your project, install spandx as a dev dependency, and create a config file:
254 |
255 | cd $YOUR_PROJECT
256 | npm install --save-dev spandx
257 | npx spandx init > spandx.config.js
258 |
259 | Modify `spandx.config.js` to reflect the needs of your application.
260 |
261 | Then edit your `package.json` and add a `start` script which launches spandx.
262 |
263 | ```json
264 | "scripts": {
265 | "start": "spandx"
266 | }
267 | ```
268 |
269 | Now you and your fellow contributors can run `yarn start` without having to install or even understand spandx!
270 |
271 | # Contributing
272 |
273 | Contributions are very welcome! There's not much here yet, but when there's enough content it can be split out into a dedicated CONTRIBUTING.md.
274 |
275 | ## Commit messages
276 |
277 | Starting with spandx v2.0.0, one goal is to adhere to the [Conventional Commits][conv-comm] style of writing commit messages. The rewards of doing so are automating semantic version bumps and CHANGELOG updates. For now, the commit style will be used and later on, the tooling ([conventional-changelog-cli][conv-cli] perhaps) will be added.
278 |
279 | ## Running specific tests
280 |
281 | When writing a test, or debugging a failing test, you may want to run *only* that test instead of the entire suite. To do that, you can filter by the name of the test. Just be specific enough to target only the test (or tests) you want to run.
282 |
283 | For example, to run the test named "should reject invalid multi-host configs":
284 |
285 | yarn test -- --filter="invalid multi"
286 |
287 | # Known issues
288 |
289 | ## cURLing spandx
290 |
291 | When curling spandx, if you are requesting an HTML document, it's important to include an appropriate `Accept` header. There are two spandx features, described below, that will not work without that header.
292 |
293 | ### Body URL rewriting
294 |
295 | The URL-rewriting feature is powered by browserSync's rewriteRules. However, Browsersync will only perform the rewrites if `text/html` is present in the request's `Accept` header. Web browsers include it by default, but if you're using [cURL][curl], you'll need to add that header in order for URLs to be rewritten.
296 |
297 | For example:
298 |
299 | curl -H 'Accept: text/html' localhost:1337
300 |
301 | ### single mode URL rewriting
302 |
303 | Just like body URL rewriting, the URL rewrite associated with the [`single`][single-mode] also needs the incoming `Accept` header to include `text/html`.
304 |
305 | All other spandx features work with or without `text/html` in the `Accept` header.
306 |
307 | # Alternatives
308 |
309 | If spandx doesn't fit, here are a few other tools that offer similar features.
310 |
311 | - [devd][devd], a local development server with a focus on flexible reverse proxying, much like spandx. Written in Go.
312 | - [http-server][http-server], a simple command-line HTTP server. The `--proxy` flag provides a remote fallback for requests that can't be resolved locally. Written in JS.
313 | - [dprox][dprox], a declarative reverse proxy for local development. Similar configuration philosophy to spandx.'
314 | - [traefik][traefik]
315 |
316 |
317 |
318 | [curl]: https://curl.haxx.se/
319 | [npm]: https://www.npmjs.com/package/spandx
320 | [build-img]: https://travis-ci.org/redhataccess/spandx.png?branch=master
321 | [build]: https://travis-ci.org/redhataccess/spandx
322 | [bs-options]: https://browsersync.io/docs/options
323 | [devd]: https://github.com/cortesi/devd
324 | [http-server]: https://github.com/http-party/http-server#readme
325 | [dprox]: https://github.com/FND/dprox
326 | [single-mode]: #single-mode
327 | [local-dep]: #spandx-as-a-local-dependency
328 | [bs-https]: https://www.browsersync.io/docs/options#option-https
329 | [rh-quickstart]: ./RH.md
330 | [portal-chrome-settings]: ./RH.md#portal-chrome-settings
331 | [pushstate]: https://developer.mozilla.org/en-US/docs/Web/API/History_API
332 | [esi]: https://en.wikipedia.org/wiki/Edge_Side_Includes
333 | [nodesi]: https://github.com/Schibsted-Tech-Polska/nodesi
334 | [conv-comm]: https://www.conventionalcommits.org/#summary
335 | [conv-cli]: https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-cli
336 | [traefik]: https://github.com/traefik/traefik
337 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # [3.0.0](https://github.com/redhataccess/spandx/compare/v2.2.7...v3.0.0) (2023-10-23)
2 |
3 | * test!: remove support for node 16 ([111e79a](https://github.com/redhataccess/spandx/commit/111e79a409a43de55962e94ed08752f68cbc9d0c))
4 |
5 | ### Features
6 |
7 | * apply localized primer/chrome based on rh_locale cookie ([86dff14](https://github.com/redhataccess/spandx/commit/86dff145dca27689782068d4c44a6b05a5f739b2))
8 |
9 | ### BREAKING CHANGES
10 |
11 | * remove support for node 16
12 |
13 | ## [2.2.7](https://github.com/redhataccess/spandx/compare/v2.2.6...v2.2.7) (2023-08-30)
14 |
15 | This patch reverts the breakage caused by a browser-sync upgrade in 2.2.6.
16 |
17 | ## [2.2.6](https://github.com/redhataccess/spandx/compare/v2.2.5...v2.2.6) (2023-06-20)
18 |
19 | DEPRECATED: This patch inadvertently introduced a breakage caused an upgrade of browser-sync. Please use 2.2.7 instead.
20 |
21 | ### Bug Fixes
22 |
23 | * **deps:** downgrade browsersync ([#282](https://github.com/redhataccess/spandx/issues/282)) ([8445edb](https://github.com/redhataccess/spandx/commit/8445edbfc86d2a931c8a3307de3ca57bfbf1ff82))
24 | * **deps:** update dependency conventional-changelog-cli to v2.2.2 ([#276](https://github.com/redhataccess/spandx/issues/276)) ([11c144d](https://github.com/redhataccess/spandx/commit/11c144d8022c6ce636f7ead712e752f195f2bd92))
25 | * **deps:** update dependency finalhandler to v1.2.0 ([#301](https://github.com/redhataccess/spandx/issues/301)) ([9fb4e74](https://github.com/redhataccess/spandx/commit/9fb4e74fd4e47e681e17f626794861963a6caa71))
26 | * **deps:** update dependency got to v11.8.6 ([#270](https://github.com/redhataccess/spandx/issues/270)) ([448b9e3](https://github.com/redhataccess/spandx/commit/448b9e3c733c212e12141111e7233b6fa20c4a16))
27 | * **deps:** update dependency http-proxy to v1.18.1 ([#304](https://github.com/redhataccess/spandx/issues/304)) ([b0922b3](https://github.com/redhataccess/spandx/commit/b0922b32b5d71876d07818a7efcfcf8711b4b82b))
28 | * **deps:** update dependency https-proxy-agent to v5.0.1 ([#296](https://github.com/redhataccess/spandx/issues/296)) ([ed5a2b3](https://github.com/redhataccess/spandx/commit/ed5a2b3fe8080ab51f8cf06fd6eaafff06f4677f))
29 | * **deps:** update dependency https-proxy-agent to v6 ([#322](https://github.com/redhataccess/spandx/issues/322)) ([d2ade82](https://github.com/redhataccess/spandx/commit/d2ade820539b56cdba06f4e5802b841f305f6bf4))
30 | * **deps:** update dependency https-proxy-agent to v7 ([#329](https://github.com/redhataccess/spandx/issues/329)) ([a0bebfa](https://github.com/redhataccess/spandx/commit/a0bebfa0e0d6046d20272c2b713037e1d07e167b))
31 | * **deps:** update dependency inquirer to v8.2.5 ([#244](https://github.com/redhataccess/spandx/issues/244)) ([dbb4ebf](https://github.com/redhataccess/spandx/commit/dbb4ebf55824117585393f2b59475d2b2b56ece1))
32 | * **deps:** update dependency inquirer to v9 ([#316](https://github.com/redhataccess/spandx/issues/316)) ([3d9ac91](https://github.com/redhataccess/spandx/commit/3d9ac911b2d742dd7d6d94173bd89b5914a0cb97))
33 | * **deps:** update dependency inquirer to v9.2.4 ([#321](https://github.com/redhataccess/spandx/issues/321)) ([f0b6eb5](https://github.com/redhataccess/spandx/commit/f0b6eb5dd6bed5da38dc2eee2e74552dacc51861))
34 | * **deps:** update dependency inquirer to v9.2.6 ([#326](https://github.com/redhataccess/spandx/issues/326)) ([ecf1f99](https://github.com/redhataccess/spandx/commit/ecf1f990065b48e8356d84d1d50248e52453e55e))
35 | * **deps:** update dependency proxy-agent to v6 ([#323](https://github.com/redhataccess/spandx/issues/323)) ([884888a](https://github.com/redhataccess/spandx/commit/884888a0f3891dc1a18a5e92e59232708b0b06b4))
36 | * **deps:** update dependency proxy-agent to v6.2.1 ([#328](https://github.com/redhataccess/spandx/issues/328)) ([86ed53b](https://github.com/redhataccess/spandx/commit/86ed53b229ab66684372ec4ed61023d101c3f466))
37 | * **deps:** update dependency serve-static to v1.15.0 ([#305](https://github.com/redhataccess/spandx/issues/305)) ([8d229a2](https://github.com/redhataccess/spandx/commit/8d229a22cd36d7b0f2f23934c9f8f62ee269b6f7))
38 | * **deps:** update dependency yargs to v17.7.1 ([#306](https://github.com/redhataccess/spandx/issues/306)) ([fe2d533](https://github.com/redhataccess/spandx/commit/fe2d53375a6424401ffa8e4f471b349be0c12dcb))
39 | * **deps:** update dependency yargs to v17.7.2 ([#320](https://github.com/redhataccess/spandx/issues/320)) ([af9fcf5](https://github.com/redhataccess/spandx/commit/af9fcf5b1710c53c8dd8b8901663d4ccc44d82a1))
40 |
41 |
42 |
43 | ## [2.2.5](https://github.com/redhataccess/spandx/compare/v2.2.4...v2.2.5) (2022-03-25)
44 |
45 |
46 | ### Bug Fixes
47 |
48 | * **deps:** update dependency browser-sync to v2.27.9 ([#248](https://github.com/redhataccess/spandx/issues/248)) ([f7dfa3a](https://github.com/redhataccess/spandx/commit/f7dfa3afd049fa6fa3b5e39bd5c9243de267cd59))
49 |
50 |
51 |
52 | ## [2.2.4](https://github.com/redhataccess/spandx/compare/v2.2.3...v2.2.4) (2022-03-23)
53 |
54 |
55 | ### Features
56 |
57 | * update `init cp` config, including valid SSL support and proxy settings ([9c2c9a7](https://github.com/redhataccess/spandx/commit/9c2c9a73ff010dae31a46a30d1b9dd54f33667a1))
58 |
59 |
60 |
61 | ## [2.2.3](https://github.com/redhataccess/spandx/compare/v2.2.2...v2.2.3) (2021-12-14)
62 |
63 |
64 | ### Bug Fixes
65 |
66 | * **deps:** update dependency inquirer to v8.1.5 ([#238](https://github.com/redhataccess/spandx/issues/238)) ([ee40f73](https://github.com/redhataccess/spandx/commit/ee40f73cc1dcda34bb6c1d276dc0d55943818466))
67 | * **deps:** update dependency token-slice to v0.0.6 ([#232](https://github.com/redhataccess/spandx/issues/232)) ([5fdca7f](https://github.com/redhataccess/spandx/commit/5fdca7f8b7504315a42210aaf72ca196aca01843))
68 | * **deps:** update dependency yargs to v17.1.0 ([#227](https://github.com/redhataccess/spandx/issues/227)) ([9778cc8](https://github.com/redhataccess/spandx/commit/9778cc8636fcc324318d8ed6523e196a8de1f3fd))
69 | * **deps:** update dependency yargs to v17.1.1 ([#233](https://github.com/redhataccess/spandx/issues/233)) ([f3ee374](https://github.com/redhataccess/spandx/commit/f3ee3748b12ceb299bb71c23fbe342256312c491))
70 |
71 |
72 |
73 | ## [2.2.2](https://github.com/redhataccess/spandx/compare/v2.2.1...v2.2.2) (2021-08-03)
74 |
75 |
76 | ### Bug Fixes
77 |
78 | * declutter up startup logs ([#226](https://github.com/redhataccess/spandx/issues/226)) ([29c4833](https://github.com/redhataccess/spandx/commit/29c4833d2c6f9e06f9b3c1570b93a8d4bb8b3101))
79 |
80 |
81 |
82 | ## [2.2.1](https://github.com/redhataccess/spandx/compare/v2.2.0...v2.2.1) (2021-07-27)
83 |
84 |
85 | ### Bug Fixes
86 |
87 | * de-dupe URL path logging ([#225](https://github.com/redhataccess/spandx/issues/225)) ([bcfa416](https://github.com/redhataccess/spandx/commit/bcfa416091c512a4ac34dda5946f0e7d8f7ee8cd))
88 |
89 |
90 |
91 | # [2.2.0](https://github.com/redhataccess/spandx/compare/v2.1.2...v2.2.0) (2021-07-26)
92 |
93 |
94 | ### Bug Fixes
95 |
96 | * allow certain bs settings to be overridden ([#167](https://github.com/redhataccess/spandx/issues/167)) ([3b55ea1](https://github.com/redhataccess/spandx/commit/3b55ea11d7bb5c0c52bb1f2cd3964128b89b0045))
97 | * **deps:** update dependency connect to v3.7.0 ([#213](https://github.com/redhataccess/spandx/issues/213)) ([7126e16](https://github.com/redhataccess/spandx/commit/7126e16d61aa70c9760b91789d152a32dd9c39ba))
98 | * **deps:** update dependency conventional-changelog-cli to v2.1.1 ([#214](https://github.com/redhataccess/spandx/issues/214)) ([9763b14](https://github.com/redhataccess/spandx/commit/9763b143182fcbefdf86f5f3c9dfd5c314c5b4a4))
99 | * **deps:** update dependency finalhandler to v1.1.2 ([#208](https://github.com/redhataccess/spandx/issues/208)) ([fd4b7e1](https://github.com/redhataccess/spandx/commit/fd4b7e1aadd83e01872646d409324b3aeac80c24))
100 | * **deps:** update dependency hostile to v1.3.3 ([#209](https://github.com/redhataccess/spandx/issues/209)) ([c20b887](https://github.com/redhataccess/spandx/commit/c20b887bfd095e3fb759f77654e596f1f4b4a401))
101 | * **deps:** update dependency http-proxy to v1.18.1 [security] ([#178](https://github.com/redhataccess/spandx/issues/178)) ([57f4f9a](https://github.com/redhataccess/spandx/commit/57f4f9af5041d18f95c99e8ece534cb5551c01fd))
102 | * **deps:** update dependency inquirer to v7.3.2 ([#155](https://github.com/redhataccess/spandx/issues/155)) ([d4f7ec8](https://github.com/redhataccess/spandx/commit/d4f7ec8bd706d2e502341857eadce7dec6bab948))
103 | * **deps:** update dependency inquirer to v7.3.3 ([#157](https://github.com/redhataccess/spandx/issues/157)) ([df66f07](https://github.com/redhataccess/spandx/commit/df66f073c1fd879a45603d3e119a27719c57d44c))
104 | * **deps:** update dependency inquirer to v8 ([#180](https://github.com/redhataccess/spandx/issues/180)) ([67e95b9](https://github.com/redhataccess/spandx/commit/67e95b9fbeb50058cd275d2b1629914544aee1cb))
105 | * **deps:** update dependency inquirer to v8.1.2 ([#210](https://github.com/redhataccess/spandx/issues/210)) ([60953d0](https://github.com/redhataccess/spandx/commit/60953d02f5a5263c4ee44be4e8e17cf6a74986c3))
106 | * **deps:** update dependency lodash to v4.17.21 [security] ([#179](https://github.com/redhataccess/spandx/issues/179)) ([3d01eae](https://github.com/redhataccess/spandx/commit/3d01eae3e0241b1d7112793afbea4e63a6fa79b8))
107 | * **deps:** update dependency proxy-agent to v5 ([#218](https://github.com/redhataccess/spandx/issues/218)) ([d2c2673](https://github.com/redhataccess/spandx/commit/d2c2673a1ba0203f81d2d562d7e371629602c778))
108 | * **deps:** update dependency serve-static to v1.14.1 ([#215](https://github.com/redhataccess/spandx/issues/215)) ([17f0bb3](https://github.com/redhataccess/spandx/commit/17f0bb3d6d8d30d9c756c71501cab26851db5298))
109 | * **deps:** update dependency transformer-proxy to v0.3.5 ([#211](https://github.com/redhataccess/spandx/issues/211)) ([646d551](https://github.com/redhataccess/spandx/commit/646d551a2e59dd783a23b842004de3ab6ab0e025))
110 | * **deps:** update dependency yargs to v16 ([#164](https://github.com/redhataccess/spandx/issues/164)) ([64dd001](https://github.com/redhataccess/spandx/commit/64dd001be12ca6200d1d9a0bbc7edfeac52c9b58))
111 | * **deps:** update dependency yargs to v16.2.0 ([#216](https://github.com/redhataccess/spandx/issues/216)) ([d58e5dc](https://github.com/redhataccess/spandx/commit/d58e5dc31d64ecf4942910682da7eb648ef6aa7a))
112 | * **deps:** update dependency yargs to v17 ([#203](https://github.com/redhataccess/spandx/issues/203)) ([dd088e5](https://github.com/redhataccess/spandx/commit/dd088e55cd6d57966e9565e01d619e9b0efbce6a))
113 | * lock dependency versions ([#207](https://github.com/redhataccess/spandx/issues/207)) ([5c17e73](https://github.com/redhataccess/spandx/commit/5c17e739b84cf1c9276a830b53e8044a213e69d0))
114 | * print correct target url for remote requests ([012b011](https://github.com/redhataccess/spandx/commit/012b01167e44329bec7a94a12333a8154940f5e6))
115 |
116 |
117 | ### Features
118 |
119 | * add primer preview ([#205](https://github.com/redhataccess/spandx/issues/205)) ([2c07cce](https://github.com/redhataccess/spandx/commit/2c07cce8dd0b0d2e3711abd39bfdc13aee1c03e2)), closes [#151](https://github.com/redhataccess/spandx/issues/151) [#180](https://github.com/redhataccess/spandx/issues/180) [#190](https://github.com/redhataccess/spandx/issues/190) [#178](https://github.com/redhataccess/spandx/issues/178) [#175](https://github.com/redhataccess/spandx/issues/175) [#172](https://github.com/redhataccess/spandx/issues/172)
120 |
121 |
122 |
123 | ## [2.1.2](https://github.com/redhataccess/spandx/compare/v2.1.1...v2.1.2) (2020-07-01)
124 |
125 |
126 | ### Bug Fixes
127 |
128 | * Do not use ESI middleware for text streams ([#141](https://github.com/redhataccess/spandx/issues/141)) ([8a291d6](https://github.com/redhataccess/spandx/commit/8a291d6006e55d465d863bfbc8742a8448c9de0c))
129 |
130 |
131 |
132 | ## [2.1.1](https://github.com/redhataccess/spandx/compare/v2.1.0...v2.1.1) (2020-06-25)
133 |
134 | ### Bug Fixes
135 |
136 | * respond with a 502 when remote is unreachable ([#145](https://github.com/redhataccess/spandx/issues/145)) ([4ac3e24](https://github.com/redhataccess/spandx/commit/4ac3e24f8c3752c4691b08d9285fda4ac8932f6d))
137 |
138 |
139 | # [2.1.0](https://github.com/redhataccess/spandx/compare/v2.0.1...v2.1.0) (2020-05-27)
140 |
141 |
142 | ### Features
143 |
144 | * adding the ability to use a proxy server for certain paths ([#143](https://github.com/redhataccess/spandx/issues/143)) ([a220c9e](https://github.com/redhataccess/spandx/commit/a220c9eb189aed3f7dfe0721c793ac39e1fd090c))
145 |
146 |
147 |
148 | ## [2.0.1](https://github.com/redhataccess/spandx/compare/v2.0.0...v2.0.1) (2019-10-18)
149 |
150 |
151 | ### Bug Fixes
152 |
153 | * npm install error related to 'opn' dependency ([fcbf726](https://github.com/redhataccess/spandx/commit/fcbf726e014b5609726c95e96240dcea4b992e50))
154 |
155 |
156 | # 2.0.0
157 |
158 | ## Breaking changes
159 |
160 | ESI is no longer enabled by default. Adding `esi: true` to spandx.config.js will re-enable it.
161 |
162 | ## Changes
163 |
164 | - 28b8a39 allow custom configuration of ESI
165 | - b614c96 revamp README
166 | - 62e285c add `single` setting for routes
167 | - 6c03e75 add `path` setting for routes
168 | - f6da858 fix esi config with multiple hosts, allow overwriting esi config
169 | - c21e2bb extract esi middleware into a separate file
170 | - 2ac5661 restore esi
171 | - cdd9f39 add `init cp` for bootstrapping Customer Portal spandx projects
172 | - 83e9a77 set X-Spandx headers to responses as well as requests
173 | - addde0d fix remote route logging of [object Object] (#56)
174 | - bb8cb2e fix console output of path in local filesystem routes
175 | - c58af4b ensure that test cases wait for static server to close (#53)
176 | - fcb00d9 add Portal Chrome injection settings
177 | - adff1fb Introduce a plugin system for router.js (#31)
178 | - 530f8aa Add renovate for automatic dependency version updates
179 | -
180 | ## Dependency updates
181 |
182 | - a3cad89 Bump lodash from 4.17.10 to 4.17.11
183 | - 80eeb68 Bump ecstatic from 3.2.0 to 3.3.2
184 | - 194ec24 Update dependency nodemon to v1.19.2
185 | - 4248c2d Update dependency husky to v3.0.5
186 | - 9761bae Update dependency lint-staged to v9.2.5
187 | - 69128d9 Update dependency inquirer to v7
188 | - 5f877c7 Update dependency yargs to v14
189 | - fdd9692 Update dependency prettier to v1.18.2
190 | - b4424e2 Update dependency frisby to v2.1.2
191 | - 81e268e Update dependency jasmine to v3.4.0 (#47)
192 | - dfbaadd Update dependency opn to v5.5.0 (#32)
193 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/spec/spandx/spandxSpec.js:
--------------------------------------------------------------------------------
1 | const hush = require("../helpers/hush");
2 |
3 | describe("spandx", () => {
4 | const http = require("http");
5 | const fs = require("fs");
6 | const path = require("path");
7 | const execSync = require("child_process").execSync;
8 | const execFile = require("child_process").execFile;
9 | const frisby = require("frisby");
10 |
11 | const serve = require("../helpers/serve");
12 |
13 | const spandxPath = "../../app/spandx";
14 | let spandx;
15 |
16 | beforeEach(() => {
17 | spandx = require(spandxPath);
18 | hush.yourMouth();
19 | });
20 |
21 | afterEach(() => {
22 | spandx.exit();
23 | delete require.cache[require.resolve(spandxPath)];
24 | hush.speakUp();
25 | });
26 |
27 | describe("spandx.init()", () => {
28 | it("should accept default configuration", async (done) => {
29 | await spandx.init();
30 |
31 | frisby
32 | .get("http://localhost:1337")
33 | .expect("status", 200)
34 | .expect("bodyContains", /spandx/)
35 | .done(done);
36 | });
37 |
38 | it("should accept a js file", async (done) => {
39 | // launch a static file server, then init spandx, make a test
40 | // request, then close the static file server
41 | await spandx.init(
42 | "../spec/helpers/configs/js-or-json/spandx.config.js"
43 | );
44 | frisby
45 | .get("http://localhost:1337/")
46 | .expect("status", 200)
47 | .expect("bodyContains", /INDEX/)
48 | .done(done);
49 | });
50 |
51 | it("should accept a json file", async (done) => {
52 | await spandx.init(
53 | "../spec/helpers/configs/js-or-json/spandx.config.json"
54 | );
55 |
56 | frisby
57 | .get("http://localhost:1337/")
58 | .expect("status", 200)
59 | .expect("bodyContains", /INDEX/)
60 | .done(done);
61 | });
62 |
63 | it("should accept a config object", async (done) => {
64 | const { server, port } = await serve(
65 | "spec/helpers/configs/js-or-json/",
66 | 4014
67 | );
68 |
69 | await spandx.init({
70 | /* config object! */
71 | silent: true,
72 | routes: {
73 | "/": { host: "http://localhost:4014" },
74 | },
75 | });
76 |
77 | frisby
78 | .get("http://localhost:1337/")
79 | .expect("status", 200)
80 | .expect("bodyContains", /INDEX/)
81 | .done(() => {
82 | server.close(done);
83 | });
84 | });
85 |
86 | it("should accept single-host config", async (done) => {
87 | const { server, port } = await serve(
88 | "spec/helpers/configs/js-or-json/",
89 | 4014
90 | );
91 |
92 | await spandx.init({
93 | /* config object! */
94 | silent: true,
95 | routes: {
96 | "/": { host: "http://localhost:4014" },
97 | },
98 | });
99 |
100 | frisby
101 | .get("http://localhost:1337/")
102 | .expect("status", 200)
103 | .expect("bodyContains", /INDEX/)
104 | .done(() => {
105 | server.close(done);
106 | });
107 | });
108 |
109 | it("should accept multi-host config", async (done) => {
110 | // serve prod dir and dev dir on different ports
111 | const { server: prodServer, port: prodPort } = await serve(
112 | "spec/helpers/configs/single-multi/dev",
113 | 4014
114 | );
115 | const { server: devServer, port: devPort } = await serve(
116 | "spec/helpers/configs/single-multi/prod",
117 | 4015
118 | );
119 |
120 | // launch spandx with two 'environments', dev and prod. accessing
121 | // spandx by localhost should route requests to the 'dev' host, and
122 | // accessing spandx by 127.0.0.1 should route to the prod host.
123 | await spandx.init({
124 | host: {
125 | dev: "localhost",
126 | prod: "127.0.0.1",
127 | },
128 | port: 1337,
129 | silent: true,
130 | routes: {
131 | "/": {
132 | host: {
133 | dev: "http://localhost:4014",
134 | prod: "http://localhost:4015",
135 | },
136 | },
137 | },
138 | });
139 |
140 | const reqs = [
141 | frisby
142 | .get("http://localhost:1337/")
143 | .expect("status", 200)
144 | .expect("header", "x-spandx-env", "dev")
145 | .expect(
146 | "header",
147 | "x-spandx-origin",
148 | "http://localhost:1337"
149 | )
150 | .expect("bodyContains", /DEV/),
151 | frisby
152 | .get("http://127.0.0.1:1337/")
153 | .expect("status", 200)
154 | .expect("header", "x-spandx-env", "prod")
155 | .expect(
156 | "header",
157 | "x-spandx-origin",
158 | "http://127.0.0.1:1337"
159 | )
160 | .expect("bodyContains", /PROD/),
161 | ];
162 |
163 | // wait for all request promises to resolve, then close up shop
164 | await Promise.all(reqs.map((r) => r._fetch));
165 | let runningServers = reqs.length;
166 | devServer.close(() => --runningServers == 0 && done());
167 | prodServer.close(() => --runningServers == 0 && done());
168 | });
169 |
170 | it("should reject invalid multi-host configs", async (done) => {
171 | try {
172 | await spandx.init(
173 | "../spec/helpers/configs/multi-host/spandx.config.js"
174 | );
175 | fail();
176 | } catch (e) {
177 | done();
178 | }
179 | });
180 |
181 | it("should accept overriding browserSync settings", async (done) => {
182 | const bs = await spandx.init(
183 | "../spec/helpers/configs/bs-override/spandx.config.js"
184 | );
185 | const opts = bs.getOption("ghostMode");
186 | expect(opts.get("clicks")).toEqual(false);
187 | expect(opts.get("scroll")).toEqual(false);
188 | expect(opts.get("location")).toEqual(false);
189 | done();
190 | });
191 |
192 | it("should support port: 'auto'", async (done) => {
193 | const bs = await spandx.init(
194 | "../spec/helpers/configs/port-auto/spandx.config.js"
195 | );
196 |
197 | const port = bs.getOption("port");
198 |
199 | const devReq = frisby
200 | .get(`http://localhost:${port}/`)
201 | .expect("status", 200)
202 | .expect("bodyContains", /INDEX/)
203 | .done(done);
204 | });
205 |
206 | it("should send requests to an unconfigured hostname to the default hostname", async (done) => {
207 | const bs = await spandx.init(
208 | "../spec/helpers/configs/unconfigured-hostname/spandx.config.js"
209 | );
210 |
211 | const port = bs.getOption("port");
212 |
213 | frisby
214 | .get(`http://127.0.0.1:${port}/`)
215 | .expect("status", 200)
216 | .expect("bodyContains", /INDEX/)
217 | .done(done);
218 | });
219 |
220 | it("should fail when port is already in use", async (done) => {
221 | try {
222 | await spandx.init({
223 | host: "localhost",
224 | port: 1337,
225 | silent: true,
226 | routes: { "/": "./" },
227 | });
228 | await spandx.init({
229 | host: "localhost",
230 | port: 1337,
231 | silent: true,
232 | routes: { "/": "./" },
233 | });
234 | } catch (e) {
235 | done();
236 | }
237 | });
238 | });
239 |
240 | describe("single mode", () => {
241 | it("should rewrite requests for html to index.html", async (done) => {
242 | const { server } = await serve("spec/helpers/configs/single", 4014);
243 |
244 | const bs = await spandx.init(
245 | "../spec/helpers/configs/single/spandx.config.js"
246 | );
247 |
248 | const accept = {
249 | request: {
250 | headers: {
251 | Accept: "text/html",
252 | },
253 | },
254 | };
255 |
256 | const reqs = [
257 | frisby
258 | .setup(accept)
259 | .get(`http://localhost:1337/foo`)
260 | .expect("status", 200)
261 | .expect("bodyContains", /FOO/),
262 | frisby
263 | .setup(accept)
264 | .get(`http://localhost:1337/foo/bar`)
265 | .expect("status", 200)
266 | .expect("bodyContains", /FOO/),
267 | frisby
268 | .setup(accept)
269 | .get(`http://localhost:1337/foo/bar/baz`)
270 | .expect("status", 200)
271 | .expect("bodyContains", /FOO/),
272 | ];
273 |
274 | // wait for all request promises to resolve, then close up shop
275 | await Promise.all(reqs.map((r) => r._fetch));
276 | server.close(done);
277 | });
278 | it("should not rewrite requests for non-html assets", async (done) => {
279 | const { server } = await serve("spec/helpers/configs/single", 4014);
280 |
281 | const bs = await spandx.init(
282 | "../spec/helpers/configs/single/spandx.config.js"
283 | );
284 |
285 | const reqs = [
286 | // test fetching a URL with a file extension, it shouldn't
287 | // rewrite to the single path
288 | frisby
289 | .get(`http://localhost:1337/foo/bar/test.txt`)
290 | .expect("status", 200)
291 | .expect("bodyContains", /TEXT FILE/),
292 | // test making a request that doesn't accept text/html
293 | frisby
294 | .setup({
295 | request: {
296 | headers: {
297 | Accept: "text/plain",
298 | },
299 | },
300 | })
301 | .get(`http://localhost:1337/foo/bar`)
302 | .expect("status", 404),
303 | ];
304 |
305 | // wait for all request promises to resolve, then close up shop
306 | await Promise.all(reqs.map((r) => r._fetch));
307 | server.close(done);
308 | });
309 | });
310 |
311 | describe("ESI", () => {
312 | describe("ESI configuration", () => {
313 | it("should process ESI tags when ESI is enabled", async (done) => {
314 | await spandx.init(
315 | "../spec/helpers/configs/esi-conf/spandx.esi-enabled.js"
316 | );
317 | frisby
318 | .get("http://localhost:1337/esi-abs-paths.html")
319 | .expect("status", 200)
320 | .expect("bodyContains", /ESI ABS PATH PARENT/)
321 | .expect("bodyContains", /ABS PATH ROOT SNIPPET/)
322 | .expect("bodyContains", /ABS PATH SUBDIR SNIPPET/)
323 | .done(done);
324 | });
325 | it("should not process ESI tags when ESI is disabled", async (done) => {
326 | await spandx.init(
327 | "../spec/helpers/configs/esi-conf/spandx.esi-disabled.js"
328 | );
329 | frisby
330 | .get("http://localhost:1337/esi-abs-paths.html")
331 | .expect("status", 200)
332 | .expect("bodyContains", /ESI ABS PATH PARENT/)
333 | .expectNot("bodyContains", /ABS PATH ROOT SNIPPET/)
334 | .expectNot("bodyContains", /ABS PATH SUBDIR SNIPPET/)
335 | .done(done);
336 | });
337 | });
338 |
339 | describe("ESI baseUrl", () => {
340 | it("should properly set ESI baseUrls when conf.esi is not set", () => {
341 | const map = require("../../app/esiMiddleware").buildEsiMap({
342 | protocol: "https:",
343 | port: 1337,
344 | host: {
345 | "ci.foo.redhat.com": "ci.foo.redhat.com",
346 | "qa.foo.redhat.com": "qa.foo.redhat.com",
347 | "stage.foo.redhat.com": "stage.foo.redhat.com",
348 | "prod.foo.redhat.com": "prod.foo.redhat.com",
349 | },
350 | });
351 |
352 | for (const env of [
353 | "ci.foo.redhat.com",
354 | "qa.foo.redhat.com",
355 | "stage.foo.redhat.com",
356 | "prod.foo.redhat.com",
357 | ]) {
358 | expect(map[env]).toBeDefined();
359 | expect(map[env].spandxGeneratedConfig).toBeDefined();
360 | expect(
361 | map[env].spandxGeneratedConfig.baseUrl
362 | ).toBeDefined();
363 | expect(map[env].spandxGeneratedConfig.baseUrl).toMatch(
364 | `https://${env}:1337`
365 | );
366 | }
367 | });
368 |
369 | it("should properly set ESI baseUrls even when conf.esi is set", () => {
370 | const map = require("../../app/esiMiddleware").buildEsiMap({
371 | esi: { allowedHosts: [/^https:\/\/access.*.redhat.com$/] },
372 | protocol: "https:",
373 | port: 1337,
374 | host: {
375 | "ci.foo.redhat.com": "ci.foo.redhat.com",
376 | "qa.foo.redhat.com": "qa.foo.redhat.com",
377 | "stage.foo.redhat.com": "stage.foo.redhat.com",
378 | "prod.foo.redhat.com": "prod.foo.redhat.com",
379 | },
380 | });
381 |
382 | for (const env of [
383 | "ci.foo.redhat.com",
384 | "qa.foo.redhat.com",
385 | "stage.foo.redhat.com",
386 | "prod.foo.redhat.com",
387 | ]) {
388 | expect(map[env]).toBeDefined();
389 | expect(map[env].spandxGeneratedConfig).toBeDefined();
390 | expect(
391 | map[env].spandxGeneratedConfig.baseUrl
392 | ).toBeDefined();
393 | expect(map[env].spandxGeneratedConfig.baseUrl).toMatch(
394 | `https://${env}:1337`
395 | );
396 | }
397 | });
398 | });
399 | describe("esi:include", () => {
400 | describe("when routing to local directories", () => {
401 | it("should resolve esi:include with absolute paths", async (done) => {
402 | await spandx.init(
403 | "../spec/helpers/configs/esi-include/spandx.local.js"
404 | );
405 | frisby
406 | .get("http://localhost:1337/esi-abs-paths.html")
407 | .expect("status", 200)
408 | .expect("bodyContains", /ESI ABS PATH PARENT/)
409 | .expect("bodyContains", /ABS PATH ROOT SNIPPET/)
410 | .expect("bodyContains", /ABS PATH SUBDIR SNIPPET/)
411 | .done(done);
412 | });
413 | it("should resolve esi:include with domain-relative paths", async (done) => {
414 | await spandx.init(
415 | "../spec/helpers/configs/esi-include/spandx.local.js"
416 | );
417 | frisby
418 | .get("http://localhost:1337/esi-domain-rel-paths.html")
419 | .expect("status", 200)
420 | .expect("bodyContains", /ESI DOMAIN REL PATH PARENT/)
421 | .expect("bodyContains", /ABS PATH ROOT SNIPPET/)
422 | .expect("bodyContains", /ABS PATH SUBDIR SNIPPET/)
423 | .done(done);
424 | });
425 | it("should resolve esi:include with file-relative paths", async (done) => {
426 | await spandx.init(
427 | "../spec/helpers/configs/esi-include/spandx.local.js"
428 | );
429 | frisby
430 | .get("http://localhost:1337/esi-file-rel-paths.html")
431 | .expect("status", 200)
432 | .expect("bodyContains", /ESI FILE REL PATH PARENT/)
433 | .expect("bodyContains", /REL PATH ROOT SNIPPET/)
434 | .expect("bodyContains", /REL PATH SUBDIR SNIPPET/)
435 | .done(done);
436 | });
437 | });
438 |
439 | describe("when routing to remote host", () => {
440 | it("should resolve esi:include with absolute paths", async (done) => {
441 | const { server, port } = await serve(
442 | "spec/helpers/configs/esi-include/",
443 | 4014
444 | );
445 | await spandx.init(
446 | "../spec/helpers/configs/esi-include/spandx.remote.js"
447 | );
448 | frisby
449 | .get("http://localhost:1337/esi-abs-paths.html")
450 | .expect("status", 200)
451 | .expect("bodyContains", /ESI ABS PATH PARENT/)
452 | .expect("bodyContains", /ABS PATH ROOT SNIPPET/)
453 | .expect("bodyContains", /ABS PATH SUBDIR SNIPPET/)
454 | .done(() => {
455 | server.close();
456 | done();
457 | });
458 | });
459 | it("should resolve esi:include with domain-relative paths", async (done) => {
460 | const { server, port } = await serve(
461 | "spec/helpers/configs/esi-include/",
462 | 4014
463 | );
464 | await spandx.init(
465 | "../spec/helpers/configs/esi-include/spandx.remote.js"
466 | );
467 | frisby
468 | .get("http://localhost:1337/esi-domain-rel-paths.html")
469 | .expect("status", 200)
470 | .expect("bodyContains", /ESI DOMAIN REL PATH PARENT/)
471 | .expect("bodyContains", /ABS PATH ROOT SNIPPET/)
472 | .expect("bodyContains", /ABS PATH SUBDIR SNIPPET/)
473 | .done(() => {
474 | server.close();
475 | done();
476 | });
477 | });
478 | it("should resolve esi:include with file-relative paths", async (done) => {
479 | const { server, port } = await serve(
480 | "spec/helpers/configs/esi-include/",
481 | 4014
482 | );
483 | await spandx.init(
484 | "../spec/helpers/configs/esi-include/spandx.remote.js"
485 | );
486 | frisby
487 | .get("http://localhost:1337/esi-file-rel-paths.html")
488 | .expect("status", 200)
489 | .expect("bodyContains", /ESI FILE REL PATH PARENT/)
490 | .expect("bodyContains", /REL PATH ROOT SNIPPET/)
491 | .expect("bodyContains", /REL PATH SUBDIR SNIPPET/)
492 | .done(() => {
493 | server.close();
494 | done();
495 | });
496 | });
497 | it("should resolve esi:include relative paths over https if https: true", async (done) => {
498 | // this test covers the case where the esi:include src points
499 | // to a host with a self-signed cert, and the bug where an
500 | // esi:include src with a relative path would get routed to
501 | // http://host/path even if https is true.
502 | const { server, port } = await serve(
503 | "spec/helpers/configs/esi-include/",
504 | 4014
505 | );
506 | await spandx.init(
507 | "../spec/helpers/configs/esi-include/spandx.https.js"
508 | );
509 | frisby
510 | .get("https://localhost:1337/esi-domain-rel-paths.html")
511 | .expect("status", 200)
512 | .expect("bodyContains", /ESI DOMAIN REL PATH PARENT/)
513 | .expect("bodyContains", /ABS PATH ROOT SNIPPET/)
514 | .expect("bodyContains", /ABS PATH SUBDIR SNIPPET/)
515 | .done(() => {
516 | server.close();
517 | done();
518 | })
519 | .catch((err) => {
520 | server.close();
521 | fail(err);
522 | });
523 | });
524 | });
525 | });
526 | });
527 |
528 | describe("trailing slashes", () => {
529 | describe("when routing to local directories", () => {
530 | it("should resolve root dir without trailing slash", async (done) => {
531 | await spandx.init(
532 | "../spec/helpers/configs/root-and-subdir/spandx.local.js"
533 | );
534 | frisby
535 | .get("http://localhost:1337")
536 | .expect("status", 200)
537 | .expect("bodyContains", /INDEX IN ROOT DIR/)
538 | .done(done);
539 | });
540 | it("should resolve root dir with trailing slash", async (done) => {
541 | await spandx.init(
542 | "../spec/helpers/configs/root-and-subdir/spandx.local.js"
543 | );
544 | frisby
545 | .get("http://localhost:1337/")
546 | .expect("status", 200)
547 | .expect("bodyContains", /INDEX IN ROOT DIR/)
548 | .done(done);
549 | });
550 | it("should resolve subdir without trailing slash", async (done) => {
551 | await spandx.init(
552 | "../spec/helpers/configs/root-and-subdir/spandx.local.js"
553 | );
554 | frisby
555 | .get("http://localhost:1337/subdir")
556 | .expect("status", 200)
557 | .expect("bodyContains", /INDEX IN SUBDIR/)
558 | .done(done);
559 | });
560 | it("should resolve subdir with trailing slash", async (done) => {
561 | await spandx.init(
562 | "../spec/helpers/configs/root-and-subdir/spandx.local.js"
563 | );
564 | frisby
565 | .get("http://localhost:1337/subdir/")
566 | .expect("status", 200)
567 | .expect("bodyContains", /INDEX IN SUBDIR/)
568 | .done(done);
569 | });
570 | });
571 |
572 | describe("when routing to remote host", () => {
573 | it("should resolve root dir without trailing slash", async (done) => {
574 | const { server, port } = await serve(
575 | "spec/helpers/configs/root-and-subdir/",
576 | 4014
577 | );
578 | await spandx.init(
579 | "../spec/helpers/configs/root-and-subdir/spandx.remote.js"
580 | );
581 | frisby
582 | .get("http://localhost:1337")
583 | .expect("status", 200)
584 | .expect("bodyContains", /INDEX IN ROOT DIR/)
585 | .done(() => {
586 | server.close(done);
587 | });
588 | });
589 | it("should resolve root dir with trailing slash", async (done) => {
590 | const { server, port } = await serve(
591 | "spec/helpers/configs/root-and-subdir/",
592 | 4014
593 | );
594 | await spandx.init(
595 | "../spec/helpers/configs/root-and-subdir/spandx.remote.js"
596 | );
597 | frisby
598 | .get("http://localhost:1337/")
599 | .expect("status", 200)
600 | .expect("bodyContains", /INDEX IN ROOT DIR/)
601 | .done(() => {
602 | server.close(done);
603 | });
604 | });
605 | it("should resolve subdir without trailing slash", async (done) => {
606 | const { server, port } = await serve(
607 | "spec/helpers/configs/root-and-subdir/",
608 | 4014
609 | );
610 | await spandx.init(
611 | "../spec/helpers/configs/root-and-subdir/spandx.remote.js"
612 | );
613 | frisby
614 | .get("http://localhost:1337/subdir")
615 | .expect("status", 200)
616 | .expect("bodyContains", /INDEX IN SUBDIR/)
617 | .done(() => {
618 | server.close(done);
619 | });
620 | });
621 | it("should resolve subdir with trailing slash", async (done) => {
622 | const { server, port } = await serve(
623 | "spec/helpers/configs/root-and-subdir/",
624 | 4014
625 | );
626 | await spandx.init(
627 | "../spec/helpers/configs/root-and-subdir/spandx.remote.js"
628 | );
629 | frisby
630 | .get("http://localhost:1337/subdir/")
631 | .expect("status", 200)
632 | .expect("bodyContains", /INDEX IN SUBDIR/)
633 | .done(() => {
634 | server.close(done);
635 | });
636 | });
637 | });
638 | });
639 |
640 | describe("portal chrome", () => {
641 | it("should honor rh_locale value when applying chrome", async () => {
642 | await spandx.init(
643 | "../spec/helpers/configs/portal-chrome/spandx.local.js"
644 | );
645 | const res = await frisby
646 | .setup({
647 | request: {
648 | headers: {
649 | cookie: "rh_locale=ko",
650 | },
651 | },
652 | })
653 | .get("http://localhost:1337/test-page.html");
654 |
655 | expect(res.body).toMatch(/HEAD CONTENT KO/);
656 | expect(res.body).toMatch(/HEADER CONTENT KO/);
657 | expect(res.body).toMatch(/FOOTER CONTENT KO/);
658 | });
659 | it("should resolve SPA comments into Portal Chrome on local routes", async () => {
660 | await spandx.init(
661 | "../spec/helpers/configs/portal-chrome/spandx.local.js"
662 | );
663 | const res = await frisby
664 | .setup()
665 | .get("http://localhost:1337/test-page.html");
666 |
667 | expect(res.body).toMatch(/HEAD CONTENT/);
668 | expect(res.body).toMatch(/HEADER CONTENT/);
669 | expect(res.body).toMatch(/FOOTER CONTENT/);
670 | });
671 | it("should resolve SPA comments into Portal Chrome on single host routes", async (done) => {
672 | const { server, port } = await serve(
673 | "spec/helpers/configs/portal-chrome/",
674 | 4014
675 | );
676 | await spandx.init(
677 | "../spec/helpers/configs/portal-chrome/spandx.single.js"
678 | );
679 | const res = await frisby
680 | .setup()
681 | .get("http://localhost:1337/test-page.html");
682 |
683 | expect(res.body).toMatch(/HEAD CONTENT/);
684 | expect(res.body).toMatch(/HEADER CONTENT/);
685 | expect(res.body).toMatch(/FOOTER CONTENT/);
686 |
687 | server.close(done);
688 | });
689 | it("should resolve SPA comments into Portal Chrome on multi host routes", async (done) => {
690 | const { server: server1 } = await serve(
691 | "spec/helpers/configs/portal-chrome/",
692 | 4014
693 | );
694 | const { server: server2 } = await serve(
695 | "spec/helpers/configs/portal-chrome/",
696 | 4015
697 | );
698 | await spandx.init(
699 | "../spec/helpers/configs/portal-chrome/spandx.single.js"
700 | );
701 | const res = await frisby
702 | .setup()
703 | .get("http://localhost:1337/test-page.html");
704 |
705 | expect(res.body).toMatch(/HEAD CONTENT/);
706 | expect(res.body).toMatch(/HEADER CONTENT/);
707 | expect(res.body).toMatch(/FOOTER CONTENT/);
708 |
709 | const res2 = await frisby
710 | .setup()
711 | .get("http://127.0.0.1:1337/test-page.html");
712 |
713 | expect(res2.body).toMatch(/HEAD CONTENT/);
714 | expect(res2.body).toMatch(/HEADER CONTENT/);
715 | expect(res2.body).toMatch(/FOOTER CONTENT/);
716 |
717 | let runningServers = 2;
718 | server1.close(() => --runningServers == 0 && done());
719 | server2.close(() => --runningServers == 0 && done());
720 | });
721 | it("should rewrite body URLs within Portal Chrome snippets, on single host routes", async (done) => {
722 | const { server, port } = await serve(
723 | "spec/helpers/configs/portal-chrome/",
724 | 4014
725 | );
726 | await spandx.init(
727 | "../spec/helpers/configs/portal-chrome/spandx.single.js"
728 | );
729 | const res = await frisby
730 | .setup({
731 | request: {
732 | headers: {
733 | Accept: "text/html,*/*",
734 | },
735 | },
736 | })
737 | .get("http://localhost:1337/test-page.html");
738 |
739 | expect(res.body).toMatch(/localhost:1337/);
740 | expect(res.body).not.toMatch(/localhost:4014/);
741 |
742 | server.close(done);
743 | });
744 | it("should rewrite body URLs within Portal Chrome snippets, on multi host routes", async (done) => {
745 | const { server: server1 } = await serve(
746 | "spec/helpers/configs/portal-chrome/",
747 | 4014
748 | );
749 | const { server: server2 } = await serve(
750 | "spec/helpers/configs/portal-chrome/",
751 | 4015
752 | );
753 | await spandx.init(
754 | "../spec/helpers/configs/portal-chrome/spandx.multi.js"
755 | );
756 | const res = await frisby
757 | .setup({
758 | request: {
759 | headers: {
760 | Accept: "text/html,*/*",
761 | },
762 | },
763 | })
764 | .get("http://localhost:1337/test-page.html");
765 |
766 | expect(res.body).toMatch(/localhost:1337/);
767 | expect(res.body).not.toMatch(/localhost:4014/);
768 |
769 | const res2 = await frisby
770 | .setup({
771 | request: {
772 | headers: {
773 | Accept: "text/html,*/*",
774 | },
775 | },
776 | })
777 | .get("http://127.0.0.1:1337/test-page.html");
778 |
779 | expect(res2.body).toMatch(/localhost:1337/);
780 | expect(res2.body).not.toMatch(/localhost:4015/);
781 |
782 | let runningServers = 2;
783 | server1.close(() => --runningServers == 0 && done());
784 | server2.close(() => --runningServers == 0 && done());
785 | });
786 | it("should not resolve SPA comments into Portal Chrome when config says not to", async (done) => {
787 | await spandx.init(
788 | "../spec/helpers/configs/portal-chrome/spandx.chrome-off.js"
789 | );
790 | const res = await frisby
791 | .setup({
792 | request: {
793 | headers: {
794 | Accept: "text/html,*/*",
795 | },
796 | },
797 | })
798 | .get("http://localhost:1337/test-page.html");
799 |
800 | expect(res.body).not.toMatch(/HEAD CONTENT/);
801 | expect(res.body).not.toMatch(/HEADER CONTENT/);
802 | expect(res.body).not.toMatch(/FOOTER CONTENT/);
803 |
804 | done();
805 | });
806 | });
807 |
808 | describe("primer", () => {
809 | it("should honor rh_locale value when applying primer", async () => {
810 | await spandx.init("../spec/helpers/configs/primer/spandx.local.js");
811 | const res = await frisby
812 | .setup({
813 | request: {
814 | headers: {
815 | cookie: "rh_locale=ko",
816 | },
817 | },
818 | })
819 | .get("http://localhost:1337/test-page.html");
820 |
821 | expect(res.body).toMatch(/KO HEAD_AFTER \(file\)/);
822 | expect(res.body).toMatch(/KO HEADER_AFTER \(file\)/);
823 | expect(res.body).toMatch(/KO FOOTER_AFTER \(file\)/);
824 | });
825 | it("should allow local preview of Primer parts", async (done) => {
826 | await spandx.init("../spec/helpers/configs/primer/spandx.local.js");
827 | const res = await frisby
828 | .setup()
829 | .get("http://localhost:1337/test-page.html");
830 |
831 | expect(res.body).toMatch(/HEAD_AFTER \(file\)/);
832 | expect(res.body).toMatch(/HEADER_AFTER \(file\)/);
833 | expect(res.body).toMatch(/FOOTER_AFTER \(file\)/);
834 |
835 | done();
836 | });
837 | it("should allow remote preview of Primer parts", async (done) => {
838 | const { server } = await serve(
839 | "spec/helpers/configs/primer/mock-primer-http",
840 | 4014
841 | );
842 | await spandx.init(
843 | "../spec/helpers/configs/primer/spandx.remote.js"
844 | );
845 | const res = await frisby
846 | .setup()
847 | .get("http://localhost:1337/test-page.html");
848 |
849 | expect(res.body).toMatch(/HEAD_AFTER \(http\)/);
850 | expect(res.body).toMatch(/HEADER_AFTER \(http\)/);
851 | expect(res.body).toMatch(/FOOTER_AFTER \(http\)/);
852 |
853 | server.close(done);
854 | });
855 | });
856 |
857 | describe("URL rewriting", () => {
858 | describe("when routing to local directories", () => {
859 | it("should rewrite body URLs to match the spandx origin", async (done) => {
860 | await spandx.init(
861 | "../spec/helpers/configs/url-rewriting/spandx.local.js"
862 | );
863 | frisby
864 | .setup({
865 | request: {
866 | headers: {
867 | accept: "text/html",
868 | },
869 | },
870 | })
871 | .get("http://localhost:1337/")
872 | .expect("status", 200)
873 | .expect("bodyContains", /URL REWRITING INDEX/)
874 | .expect("bodyContains", "//localhost:1337")
875 | .done(done);
876 | });
877 | });
878 | describe("when routing to remote directories", () => {
879 | it("should honor the path setting when resolving a route", async (done) => {
880 | const { server, port } = await serve(
881 | "spec/helpers/configs/path-setting/",
882 | 4014
883 | );
884 | await spandx.init({
885 | host: "localhost",
886 | port: 1337,
887 | silent: true,
888 | routes: {
889 | "/foo/bar": {
890 | host: "http://localhost:4014",
891 | path: "/",
892 | },
893 | "/foo": {
894 | host: "http://localhost:4014",
895 | path: "/",
896 | },
897 | "/": {
898 | host: "http://localhost:4014",
899 | path: "/",
900 | },
901 | "/realfoo": {
902 | host: "http://localhost:4014",
903 | path: "/foo/",
904 | },
905 | "/realbar": {
906 | host: "http://localhost:4014",
907 | path: "/foo/bar/",
908 | },
909 | },
910 | });
911 | frisby
912 | .setup()
913 | // .get("http://localhost:1337/foo/bar/")
914 | // .expect("status", 200)
915 | // .expect("bodyContains", /path-setting/)
916 | // .get("http://localhost:1337/foo/")
917 | // .expect("status", 200)
918 | // .expect("bodyContains", /path-setting/)
919 | // .get("http://localhost:1337/")
920 | // .expect("status", 200)
921 | // .expect("bodyContains", /path-setting/)
922 | // .get("http://localhost:1337/realfoo/")
923 | // .expect("status", 200)
924 | // .expect("bodyContains", /foo/)
925 | .get("http://localhost:1337/realfoo/bar/")
926 | .expect("status", 200)
927 | .expect("bodyContains", /bar/)
928 | // .get("http://localhost:1337/realbar/")
929 | // .expect("status", 200)
930 | // .expect("bodyContains", /bar/)
931 | .done(() => {
932 | server.close(done);
933 | });
934 | });
935 | it("should rewrite body URLs to match the spandx origin", async (done) => {
936 | const { server, port } = await serve(
937 | "spec/helpers/configs/url-rewriting/",
938 | 4014
939 | );
940 | await spandx.init(
941 | "../spec/helpers/configs/url-rewriting/spandx.remote.js"
942 | );
943 | frisby
944 | .setup({
945 | request: {
946 | headers: {
947 | Accept: "text/html,*/*",
948 | },
949 | },
950 | })
951 | .get("http://localhost:1337/")
952 | .expect("status", 200)
953 | .expect("bodyContains", /URL REWRITING INDEX/)
954 | .expect("bodyContains", "//localhost:1337")
955 | .done(() => {
956 | server.close(done);
957 | });
958 | });
959 | it("should rewrite body URLs when using multi-host", async (done) => {
960 | // serve prod dir and dev dir on different ports
961 | const { server: prodServer, port: prodPort } = await serve(
962 | "spec/helpers/configs/single-multi/dev",
963 | 4014
964 | );
965 | const { server: devServer, port: devPort } = await serve(
966 | "spec/helpers/configs/single-multi/prod",
967 | 4015
968 | );
969 |
970 | // launch spandx with two 'environments', dev and prod. accessing
971 | // spandx by localhost should route requests to the 'dev' host, and
972 | // accessing spandx by 127.0.0.1 should route to the prod host.
973 | await spandx.init({
974 | host: {
975 | dev: "localhost",
976 | prod: "127.0.0.1",
977 | },
978 | port: 1337,
979 | silent: true,
980 | routes: {
981 | "/": {
982 | host: {
983 | dev: "http://localhost:4014",
984 | prod: "http://localhost:4015",
985 | },
986 | },
987 | },
988 | });
989 |
990 | const devReq = frisby
991 | .setup({
992 | request: {
993 | headers: {
994 | Accept: "text/html,*/*",
995 | },
996 | },
997 | })
998 | .get("http://localhost:1337/")
999 | .expect("status", 200)
1000 | .expect("bodyContains", /localhost/);
1001 |
1002 | const prodReq = frisby
1003 | .setup({
1004 | request: {
1005 | headers: {
1006 | Accept: "text/html,*/*",
1007 | },
1008 | },
1009 | })
1010 | .get("http://127.0.0.1:1337/")
1011 | .expect("status", 200)
1012 | .expect("bodyContains", /127\.0\.0\.1/);
1013 |
1014 | // wait for all request promises to resolve, then close up shop
1015 | await Promise.all([devReq._fetch, prodReq._fetch]);
1016 | let runningServers = 2;
1017 | devServer.close(() => --runningServers == 0 && done());
1018 | prodServer.close(() => --runningServers == 0 && done());
1019 | });
1020 | });
1021 | });
1022 |
1023 | describe("remote fallback", () => {
1024 | it("if a file is not found on a local route, attempt to fetch it from the '/' remote route", async (done) => {
1025 | const { server, port } = await serve(
1026 | "spec/helpers/configs/remote-fallback/remote-files",
1027 | 4014
1028 | );
1029 | await spandx.init(
1030 | "../spec/helpers/configs/remote-fallback/spandx.config.js"
1031 | );
1032 | frisby
1033 | .get("http://localhost:1337/subdir/remote-only.html")
1034 | .expect("status", 200)
1035 | .expect("bodyContains", /REMOTE ONLY/)
1036 | .done(() => {
1037 | server.close(done);
1038 | });
1039 | });
1040 | it("if a file exists in both a local route and a remote '/' route, serve the local one", async (done) => {
1041 | const { server, port } = await serve(
1042 | "spec/helpers/configs/remote-fallback/remote-files",
1043 | 4014
1044 | );
1045 | await spandx.init(
1046 | "../spec/helpers/configs/remote-fallback/spandx.config.js"
1047 | );
1048 | frisby
1049 | .get("http://localhost:1337/subdir/index.html")
1050 | .expect("status", 200)
1051 | .expect("bodyContains", /LOCAL SUBDIR INDEX/)
1052 | .done(() => {
1053 | server.close(done);
1054 | });
1055 | });
1056 | it("if the remote is unreachable, return bad gateway", async (done) => {
1057 | await spandx.init(
1058 | "../spec/helpers/configs/bad-gateway/spandx.config.js"
1059 | );
1060 | frisby
1061 | .get("http://localhost:1337/")
1062 | .expect("status", 502)
1063 | .expect("bodyContains", /bad gateway/i)
1064 | .done(() => {
1065 | done();
1066 | });
1067 | });
1068 | });
1069 |
1070 | describe("routing order", () => {
1071 | it("should pick longer routes over shorter routes", async (done) => {
1072 | const { server, port } = await serve(
1073 | "spec/helpers/configs/route-order/",
1074 | 4014
1075 | );
1076 |
1077 | await spandx.init(
1078 | "../spec/helpers/configs/route-order/spandx.config.js"
1079 | );
1080 |
1081 | frisby
1082 | .get("http://localhost:1337/")
1083 | .expect("status", 200)
1084 | .expect("bodyContains", /^\//)
1085 | .get("http://localhost:1337/a")
1086 | .expect("status", 200)
1087 | .expect("bodyContains", /^\/a/)
1088 | .get("http://localhost:1337/a/b")
1089 | .expect("status", 200)
1090 | .expect("bodyContains", /^\/a\/b/)
1091 | .get("http://localhost:1337/a/b/c")
1092 | .expect("status", 200)
1093 | .expect("bodyContains", /^\/a\/b\/c/)
1094 | .done(() => {
1095 | server.close(done);
1096 | });
1097 | });
1098 | });
1099 |
1100 | describe("command-line flags and output", () => {
1101 | const configPathRel = "./spandx.config.js";
1102 | it("init should generate a sample config", () => {
1103 | const sampleConfig = fs.readFileSync("spandx.config.js").toString();
1104 | const stdout = execSync("node app/cli.js init").toString();
1105 | // ensure `spandx init` output matches the sample config file
1106 | expect(stdout.trim() === sampleConfig.trim()).toBeTruthy();
1107 | });
1108 | it("can be executed with no arguments", async (done) => {
1109 | // launch spandx and scan the output for desired strings
1110 | const shell = execFile(`app/cli.js`);
1111 | let urlPrompted = false;
1112 | let urlPrinted = false;
1113 | shell.stdout.on("data", (data) => {
1114 | // these ifs look weird, but since the stdout is available only
1115 | // in chunks, we need to check if this is the right chunk
1116 | // before expect()ing it toContain() the strings we're looking
1117 | // for.
1118 | if (!urlPrompted && data.includes("spandx URL")) {
1119 | urlPrompted = true;
1120 | expect(data).toContain("spandx URL");
1121 | }
1122 | if (!urlPrinted && data.includes("http://localhost:")) {
1123 | urlPrinted = true;
1124 | expect(data).toContain("http://localhost:");
1125 | }
1126 | if (urlPrompted && urlPrinted) {
1127 | shell.kill();
1128 | done();
1129 | }
1130 | });
1131 | shell.stderr.on("data", (err) => {
1132 | fail(err);
1133 | done();
1134 | });
1135 | });
1136 | it("-c should accept a relative config file path", async (done) => {
1137 | // launch spandx and scan the output for desired strings
1138 | const shell = execFile(`app/cli.js`, [`-c`, `${configPathRel}`]);
1139 | let urlPrompted = false;
1140 | let urlPrinted = false;
1141 | shell.stdout.on("data", (data) => {
1142 | // these ifs look weird, but since the stdout is available only
1143 | // in chunks, we need to check if this is the right chunk
1144 | // before expect()ing it toContain() the strings we're looking
1145 | // for.
1146 | if (!urlPrompted && data.includes("spandx URL")) {
1147 | urlPrompted = true;
1148 | expect(data).toContain("spandx URL");
1149 | }
1150 | if (!urlPrinted && data.includes("http://localhost:")) {
1151 | urlPrinted = true;
1152 | expect(data).toContain("http://localhost:");
1153 | }
1154 | if (urlPrompted && urlPrinted) {
1155 | shell.kill();
1156 | done();
1157 | }
1158 | });
1159 | shell.stderr.on("data", (err) => {
1160 | fail(err);
1161 | });
1162 | });
1163 | it("-c should accept a absolute config file path", async (done) => {
1164 | // launch spandx and scan the output for desired strings
1165 | const shell = execFile(`app/cli.js`, [
1166 | `-c`,
1167 | `${path.resolve(__dirname, "../../", configPathRel)}`,
1168 | ]);
1169 | let urlPrompted = false;
1170 | let urlPrinted = false;
1171 | shell.stdout.on("data", (data) => {
1172 | // these ifs look weird, but since the stdout is available only
1173 | // in chunks, we need to check if this is the right chunk
1174 | // before expect()ing it toContain() the strings we're looking
1175 | // for.
1176 | if (!urlPrompted && data.includes("spandx URL")) {
1177 | urlPrompted = true;
1178 | expect(data).toContain("spandx URL");
1179 | }
1180 | if (!urlPrinted && data.includes("http://localhost:")) {
1181 | urlPrinted = true;
1182 | expect(data).toContain("http://localhost:");
1183 | }
1184 | if (urlPrompted && urlPrinted) {
1185 | shell.kill();
1186 | done();
1187 | }
1188 | });
1189 | shell.stderr.on("data", (err) => {
1190 | fail(err);
1191 | });
1192 | });
1193 | });
1194 | });
1195 |
--------------------------------------------------------------------------------