@mindful-web/export-framework 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintignore ADDED
@@ -0,0 +1 @@
1
+ *.marko.js
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Parameter1 LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # Export Framework
2
+ Core app framework for Mindful Web Exports.
@@ -0,0 +1,16 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
7
+ <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
8
+ <styles />
9
+ <${input.head} />
10
+ </head>
11
+ <body class="bg-light">
12
+ <div class="container py-3 bg-white">
13
+ <${input.renderBody} />
14
+ </div>
15
+ </body>
16
+ </html>
@@ -0,0 +1,52 @@
1
+ // Compiled using marko@4.20.2 - DO NOT EDIT
2
+ "use strict";
3
+
4
+ var marko_template = module.exports = require("marko/dist/html").t(__filename),
5
+ marko_componentType = "/@mindful-web/export-framework$1.0.0/admin/components/document.marko",
6
+ marko_renderer = require("marko/dist/runtime/components/renderer"),
7
+ styles_template = require("./styles.marko"),
8
+ marko_loadTag = require("marko/dist/runtime/helpers/load-tag"),
9
+ styles_tag = marko_loadTag(styles_template),
10
+ marko_dynamicTag = require("marko/dist/runtime/helpers/dynamic-tag"),
11
+ init_components_tag = marko_loadTag(require("marko/dist/core-tags/components/init-components-tag")),
12
+ await_reorderer_tag = marko_loadTag(require("marko/dist/core-tags/core/await/reorderer-renderer")),
13
+ _preferred_script_location_tag = marko_loadTag(require("marko/dist/core-tags/components/preferred-script-location-tag"));
14
+
15
+ function render(input, out, __component, component, state) {
16
+ var data = input;
17
+
18
+ out.w("<!doctype html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"><link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">");
19
+
20
+ styles_tag({}, out, __component, "6");
21
+
22
+ marko_dynamicTag(out, input.head, null, null, null, null, __component, "7");
23
+
24
+ out.w("</head><body class=\"bg-light\"><div class=\"container py-3 bg-white\">");
25
+
26
+ marko_dynamicTag(out, input.renderBody, null, null, null, null, __component, "10");
27
+
28
+ out.w("</div>");
29
+
30
+ init_components_tag({}, out);
31
+
32
+ await_reorderer_tag({}, out, __component, "11");
33
+
34
+ _preferred_script_location_tag({}, out);
35
+
36
+ out.w("</body></html>");
37
+ }
38
+
39
+ marko_template._ = marko_renderer(render, {
40
+ d_: true,
41
+ e_: marko_componentType
42
+ });
43
+
44
+ marko_template.meta = {
45
+ id: "/@mindful-web/export-framework$1.0.0/admin/components/document.marko",
46
+ tags: [
47
+ "./styles.marko",
48
+ "marko/dist/core-tags/components/init-components-tag",
49
+ "marko/dist/core-tags/core/await/reorderer-renderer",
50
+ "marko/dist/core-tags/components/preferred-script-location-tag"
51
+ ]
52
+ };
@@ -0,0 +1,7 @@
1
+ $ const { obj } = input;
2
+
3
+ <div class="list-group-item">
4
+ <p class="mb-0">
5
+ ${obj.name} <small>[<a href=`/exports${obj.route}`>run</a>] [<a href=`/exports${obj.route}?download`>download</a>]</small>
6
+ </p>
7
+ </div>
@@ -0,0 +1,32 @@
1
+ // Compiled using marko@4.20.2 - DO NOT EDIT
2
+ "use strict";
3
+
4
+ var marko_template = module.exports = require("marko/dist/html").t(__filename),
5
+ marko_componentType = "/@mindful-web/export-framework$1.0.0/admin/components/export.marko",
6
+ marko_renderer = require("marko/dist/runtime/components/renderer"),
7
+ helpers_escape_xml = require("marko/dist/runtime/html/helpers/escape-xml"),
8
+ marko_escapeXml = helpers_escape_xml.x,
9
+ marko_attr = require("marko/dist/runtime/html/helpers/attr");
10
+
11
+ function render(input, out, __component, component, state) {
12
+ var data = input;
13
+
14
+ const { obj } = input;
15
+
16
+ out.w("<div class=\"list-group-item\"><p class=\"mb-0\">" +
17
+ marko_escapeXml(obj.name) +
18
+ " <small>[<a" +
19
+ marko_attr("href", "/exports" + obj.route) +
20
+ ">run</a>] [<a" +
21
+ marko_attr("href", ("/exports" + obj.route) + "?download") +
22
+ ">download</a>]</small></p></div>");
23
+ }
24
+
25
+ marko_template._ = marko_renderer(render, {
26
+ d_: true,
27
+ e_: marko_componentType
28
+ });
29
+
30
+ marko_template.meta = {
31
+ id: "/@mindful-web/export-framework$1.0.0/admin/components/export.marko"
32
+ };
@@ -0,0 +1,15 @@
1
+ <style>
2
+ html {
3
+ height: 100%;
4
+ }
5
+
6
+ body {
7
+ display: flex;
8
+ flex-direction: column;
9
+ height: 100%;
10
+ }
11
+
12
+ .container {
13
+ flex-grow: 1;
14
+ }
15
+ </style>
@@ -0,0 +1,21 @@
1
+ // Compiled using marko@4.20.2 - DO NOT EDIT
2
+ "use strict";
3
+
4
+ var marko_template = module.exports = require("marko/dist/html").t(__filename),
5
+ marko_componentType = "/@mindful-web/export-framework$1.0.0/admin/components/styles.marko",
6
+ marko_renderer = require("marko/dist/runtime/components/renderer");
7
+
8
+ function render(input, out, __component, component, state) {
9
+ var data = input;
10
+
11
+ out.w("<style>\n html {\n height: 100%;\n }\n\n body {\n display: flex;\n flex-direction: column;\n height: 100%;\n }\n\n .container {\n flex-grow: 1;\n }\n</style>");
12
+ }
13
+
14
+ marko_template._ = marko_renderer(render, {
15
+ d_: true,
16
+ e_: marko_componentType
17
+ });
18
+
19
+ marko_template.meta = {
20
+ id: "/@mindful-web/export-framework$1.0.0/admin/components/styles.marko"
21
+ };
package/admin/index.js ADDED
@@ -0,0 +1,8 @@
1
+ const { Router } = require('express');
2
+ const routes = require('./routes');
3
+
4
+ module.exports = ({ exports }) => {
5
+ const router = Router();
6
+ routes(router, { exports });
7
+ return router;
8
+ };
@@ -0,0 +1,39 @@
1
+ const { asyncRoute } = require('@mindful-web/utils');
2
+ const template = require('./templates/index');
3
+
4
+ const getSite = (arr, site) => {
5
+ if (arr.find(({ name }) => name === site)) {
6
+ const sites = arr.filter(({ name }) => name !== site);
7
+ const obj = arr.find(({ name }) => name === site);
8
+ return { sites, site: obj };
9
+ }
10
+ return { sites: arr, site: { name: site, exports: [] } };
11
+ };
12
+
13
+ module.exports = (router, { exports }) => {
14
+ router.get('/', asyncRoute(async (req, res) => {
15
+ const reduced = exports.reduce((obj, file) => {
16
+ const c = obj.core || [];
17
+ const s = obj.sites || [];
18
+ if (file.site) {
19
+ const { sites, site } = getSite(s, file.site);
20
+ return {
21
+ core: c,
22
+ sites: [
23
+ ...sites,
24
+ {
25
+ name: site.name,
26
+ exports: [...site.exports, file],
27
+ },
28
+ ],
29
+ };
30
+ }
31
+ return {
32
+ core: [...c, file],
33
+ sites: s,
34
+ };
35
+ }, {});
36
+ const { core, sites } = reduced;
37
+ res.marko(template, { core, sites });
38
+ }));
39
+ };
@@ -0,0 +1,49 @@
1
+ $ const { core, sites } = data;
2
+
3
+ <document>
4
+ <@head>
5
+ <title>Exports</title>
6
+ </@head>
7
+ <div class="row">
8
+ <div class="col-lg-6">
9
+ <div class="card mb-3">
10
+ <div class="card-header">Core Exports</div>
11
+ <div class="list-group list-group-flush">
12
+ <if(core.length)>
13
+ <for|obj| of=core>
14
+ <export obj=obj />
15
+ </for>
16
+ </if>
17
+ <else>
18
+ <div class="list-group-item text-muted">
19
+ No exports found
20
+ </div>
21
+ </else>
22
+ </div>
23
+ </div>
24
+ </div>
25
+
26
+ <div class="col-lg-6">
27
+ <if(sites.length)>
28
+ <for|site| of=sites>
29
+ <div class="card mb-3">
30
+ <div class="card-header">${site.name} Exports</div>
31
+ <div class="list-group list-group-flush">
32
+ <if(site.exports.length)>
33
+ <for|obj| of=site.exports>
34
+ <export obj=obj />
35
+ </for>
36
+ </if>
37
+ <else>
38
+ <div class="list-group-item text-muted">
39
+ No exports found
40
+ </div>
41
+ </else>
42
+ </div>
43
+ </div>
44
+ </for>
45
+ </if>
46
+ </div>
47
+ </div>
48
+
49
+ </document>
@@ -0,0 +1,90 @@
1
+ // Compiled using marko@4.20.2 - DO NOT EDIT
2
+ "use strict";
3
+
4
+ var marko_template = module.exports = require("marko/dist/html").t(__filename),
5
+ marko_componentType = "/@mindful-web/export-framework$1.0.0/admin/templates/index.marko",
6
+ marko_renderer = require("marko/dist/runtime/components/renderer"),
7
+ marko_forOf = require("marko/dist/runtime/helpers/for-of"),
8
+ export_template = require("../components/export.marko"),
9
+ marko_loadTag = require("marko/dist/runtime/helpers/load-tag"),
10
+ export_tag = marko_loadTag(export_template),
11
+ helpers_escape_xml = require("marko/dist/runtime/html/helpers/escape-xml"),
12
+ marko_escapeXml = helpers_escape_xml.x,
13
+ document_template = require("../components/document.marko"),
14
+ document_tag = marko_loadTag(document_template);
15
+
16
+ function render(input, out, __component, component, state) {
17
+ var data = input;
18
+
19
+ const { core, sites } = data;
20
+
21
+ document_tag({
22
+ head: {
23
+ renderBody: function(out) {
24
+ out.w("<title>Exports</title>");
25
+ }
26
+ },
27
+ renderBody: function(out) {
28
+ out.w("<div class=\"row\"><div class=\"col-lg-6\"><div class=\"card mb-3\"><div class=\"card-header\">Core Exports</div><div class=\"list-group list-group-flush\">");
29
+
30
+ if (core.length) {
31
+ var $for$0 = 0;
32
+
33
+ marko_forOf(core, function(obj) {
34
+ var $keyScope$0 = "[" + (($for$0++) + "]");
35
+
36
+ export_tag({
37
+ obj: obj
38
+ }, out, __component, "8" + $keyScope$0);
39
+ });
40
+ } else {
41
+ out.w("<div class=\"list-group-item text-muted\">No exports found</div>");
42
+ }
43
+
44
+ out.w("</div></div></div><div class=\"col-lg-6\">");
45
+
46
+ if (sites.length) {
47
+ var $for$1 = 0;
48
+
49
+ marko_forOf(sites, function(site) {
50
+ var $keyScope$1 = "[" + (($for$1++) + "]");
51
+
52
+ out.w("<div class=\"card mb-3\"><div class=\"card-header\">" +
53
+ marko_escapeXml(site.name) +
54
+ " Exports</div><div class=\"list-group list-group-flush\">");
55
+
56
+ if (site.exports.length) {
57
+ var $for$2 = 0;
58
+
59
+ marko_forOf(site.exports, function(obj) {
60
+ var $keyScope$2 = "[" + ((($for$2++) + $keyScope$1) + "]");
61
+
62
+ export_tag({
63
+ obj: obj
64
+ }, out, __component, "14" + $keyScope$2);
65
+ });
66
+ } else {
67
+ out.w("<div class=\"list-group-item text-muted\">No exports found</div>");
68
+ }
69
+
70
+ out.w("</div></div>");
71
+ });
72
+ }
73
+
74
+ out.w("</div></div>");
75
+ }
76
+ }, out, __component, "0");
77
+ }
78
+
79
+ marko_template._ = marko_renderer(render, {
80
+ d_: true,
81
+ e_: marko_componentType
82
+ });
83
+
84
+ marko_template.meta = {
85
+ id: "/@mindful-web/export-framework$1.0.0/admin/templates/index.marko",
86
+ tags: [
87
+ "../components/export.marko",
88
+ "../components/document.marko"
89
+ ]
90
+ };
@@ -0,0 +1,42 @@
1
+ const {
2
+ get,
3
+ getAsArray,
4
+ getAsObject,
5
+ } = require('@mindful-web/object-path');
6
+
7
+ class AbstractConfig {
8
+ /**
9
+ *
10
+ * @param {object} config
11
+ */
12
+ constructor(config) {
13
+ this.config = config;
14
+ }
15
+
16
+ /**
17
+ *
18
+ * @param {string} path
19
+ * @param {*} def
20
+ */
21
+ get(path, def) {
22
+ return get(this.config, path, def);
23
+ }
24
+
25
+ /**
26
+ *
27
+ * @param {string} path
28
+ */
29
+ getAsArray(path) {
30
+ return getAsArray(this.config, path);
31
+ }
32
+
33
+ /**
34
+ *
35
+ * @param {string} path
36
+ */
37
+ getAsObject(path) {
38
+ return getAsObject(this.config, path);
39
+ }
40
+ }
41
+
42
+ module.exports = AbstractConfig;
package/config/core.js ADDED
@@ -0,0 +1,27 @@
1
+ const { getAsObject } = require('@mindful-web/object-path');
2
+ const AbstractConfig = require('./abstract-config');
3
+
4
+ const defaults = {
5
+ csv: { 'Content-Type': 'text/plain' },
6
+ json: { 'Content-Type': 'application/json' },
7
+ txt: { 'Content-Type': 'text/plain' },
8
+ };
9
+
10
+ const formatTypes = (types = {}) => Object.keys(types).reduce((obj, k) => {
11
+ const headers = getAsObject(types, k);
12
+ headers['Content-Type'] = headers['Content-Type'] || 'text/plain';
13
+ return { ...obj, [k]: headers };
14
+ }, {});
15
+
16
+ class CoreConfig extends AbstractConfig {
17
+ constructor(config = {}) {
18
+ const { fileExtensions } = config;
19
+ super(config);
20
+ this.config.fileExtensions = {
21
+ ...formatTypes(defaults),
22
+ ...(fileExtensions && formatTypes(fileExtensions)),
23
+ };
24
+ }
25
+ }
26
+
27
+ module.exports = CoreConfig;
@@ -0,0 +1,6 @@
1
+ const AbstractConfig = require('./abstract-config');
2
+
3
+ class CustomConfig extends AbstractConfig {
4
+ }
5
+
6
+ module.exports = CustomConfig;
@@ -0,0 +1,22 @@
1
+ const fetch = require('node-fetch');
2
+ const { createClient } = require('@mindful-web/express-apollo');
3
+ const { buildRequestHeaders } = require('@mindful-web/tenant-context');
4
+
5
+ module.exports = ({
6
+ uri,
7
+ name,
8
+ tenantKey,
9
+ }) => (req, res, next) => {
10
+ const fetchWithSite = (url, options) => {
11
+ const { website } = res.locals;
12
+ if (!website) return fetch(url, options);
13
+ const headers = { ...options.headers, 'x-site-id': website.get('id') };
14
+ return fetch(url, { ...options, headers });
15
+ };
16
+
17
+ const headers = buildRequestHeaders({ tenantKey });
18
+ const apollo = createClient(uri, { name }, { headers, fetch: fetchWithSite });
19
+ req.apollo = apollo;
20
+ res.locals.apollo = apollo;
21
+ next();
22
+ };
@@ -0,0 +1,62 @@
1
+ const express = require('express');
2
+ const { cleanMarkoResponse, markoMiddleware } = require('@mindful-web/marko-express/middleware');
3
+ const helmet = require('helmet');
4
+ const apollo = require('./apollo');
5
+ const { version } = require('../package.json');
6
+ const admin = require('../admin');
7
+ const templateRouter = require('./template-router');
8
+
9
+ /**
10
+ */
11
+ module.exports = (config = {}) => {
12
+ const {
13
+ sitePackage,
14
+ exports,
15
+ coreConfig,
16
+ customConfig,
17
+ } = config;
18
+ const app = express();
19
+
20
+ // Add async block error handler.
21
+ app.locals.onAsyncBlockError = config.onAsyncBlockError;
22
+
23
+ // Set the core config.
24
+ app.locals.config = coreConfig;
25
+
26
+ // Set custom configuration.
27
+ app.locals.customConfig = customConfig;
28
+
29
+ // Use helmet.
30
+ app.use(helmet());
31
+
32
+ // Apply request origin.
33
+ app.use((req, res, next) => {
34
+ res.locals.requestOrigin = `${req.protocol}://${req.get('host')}`;
35
+ next();
36
+ });
37
+
38
+ // Apply versions.
39
+ app.use((req, res, next) => {
40
+ res.set('x-version', `${sitePackage.version}|${version}`);
41
+ next();
42
+ });
43
+
44
+ // Register apollo.
45
+ app.use(apollo({
46
+ uri: config.graphqlUri,
47
+ name: sitePackage.name,
48
+ tenantKey: config.tenantKey,
49
+ }));
50
+
51
+ // Register the Marko middleware.
52
+ app.use(markoMiddleware());
53
+ app.use(cleanMarkoResponse());
54
+
55
+ // Register newsletter "admin application."
56
+ app.use('/', admin({ exports }));
57
+
58
+ // Register exports
59
+ app.use('/exports', templateRouter({ exports, coreConfig, customConfig }));
60
+
61
+ return app;
62
+ };
@@ -0,0 +1,13 @@
1
+ const { get } = require('@mindful-web/object-path');
2
+ const moment = require('moment');
3
+
4
+ module.exports = ({ coreConfig, format, name }) => (req, res, next) => {
5
+ const headers = coreConfig.getAsObject(`fileExtensions.${format}`);
6
+ Object.keys(headers).forEach((k) => res.set(k, headers[k]));
7
+
8
+ const download = get(req, 'query.download');
9
+ const date = moment().format('YYYY-MM-DDTHH:mm');
10
+ if (typeof download !== 'undefined') res.set('Content-Disposition', `attachment; filename="${date}-${name}"`);
11
+
12
+ next();
13
+ };
@@ -0,0 +1,73 @@
1
+ const { Router } = require('express');
2
+ const { asyncRoute } = require('@mindful-web/utils');
3
+ const gql = require('graphql-tag');
4
+ const createError = require('http-errors');
5
+ const cleanResponse = require('@mindful-web/marko-core/middleware/clean-marko-response');
6
+ const { getAsArray } = require('@mindful-web/object-path');
7
+ const websiteFactory = require('../utils/website-factory');
8
+ const outputHeaders = require('./output-headers');
9
+
10
+ const { error } = console;
11
+ const query = gql`
12
+
13
+ query AllSites($input: WebsiteSitesQueryInput!) {
14
+ websiteSites(input: $input) {
15
+ edges {
16
+ node {
17
+ id
18
+ name
19
+ host
20
+ status
21
+ }
22
+ }
23
+ }
24
+ }
25
+ `;
26
+
27
+ module.exports = ({ exports, coreConfig, customConfig }) => {
28
+ const router = Router();
29
+
30
+ router.use(cleanResponse());
31
+
32
+ exports.forEach(({
33
+ route,
34
+ fn,
35
+ format,
36
+ site,
37
+ name,
38
+ }) => {
39
+ router.get(route, outputHeaders({ coreConfig, format, name }), asyncRoute(async (req, res) => {
40
+ const { apollo } = res.locals;
41
+ const { data } = await apollo.query({ query, variables: { input: { status: 'active' } } });
42
+ const sites = getAsArray(data, 'websiteSites.edges').map(({ node }) => node);
43
+
44
+ const context = {
45
+ apollo,
46
+ req,
47
+ coreConfig,
48
+ customConfig,
49
+ };
50
+
51
+ if (site) {
52
+ const found = sites.find(({ host }) => host === site);
53
+ if (!found || (found && found.status !== 1)) {
54
+ throw createError(404, `No site found for host '${site}'`);
55
+ }
56
+ const website = websiteFactory(found);
57
+
58
+ // Set website context.
59
+ res.setHeader('x-site', `${website.get('name')} [${website.get('id')}]`);
60
+ context.site = website;
61
+ }
62
+
63
+ try {
64
+ const body = await fn(context);
65
+ res.send(body);
66
+ } catch (e) {
67
+ if (e.networkError) error(e.networkError.result);
68
+ throw createError(500, e.message);
69
+ }
70
+ }));
71
+ });
72
+ return router;
73
+ };
package/index.js ADDED
@@ -0,0 +1,8 @@
1
+ if (process.env.MARKO_REQUIRE_PREBUILT_TEMPLATES == null) {
2
+ // force prebuilt templates if env not set
3
+ process.env.MARKO_REQUIRE_PREBUILT_TEMPLATES = true;
4
+ }
5
+
6
+ const startServer = require('./start-server');
7
+
8
+ module.exports = { startServer };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@mindful-web/export-framework",
3
+ "version": "1.0.0",
4
+ "description": "Core framework for Mindful Web Exports.",
5
+ "author": "Josh Worden <josh@parameter1.com>",
6
+ "main": "src/index.js",
7
+ "license": "MIT",
8
+ "repository": "https://github.com/parameter1/mindful-web/tree/main/packages/export-framework",
9
+ "scripts": {
10
+ "lint:fix": "yarn lint --fix",
11
+ "lint": "eslint --ext .js --max-warnings 5 ./",
12
+ "compile": "mindful-web-marko-compile compile",
13
+ "prepublish": "yarn compile --silent",
14
+ "test": "yarn compile --no-clean && yarn lint"
15
+ },
16
+ "dependencies": {
17
+ "@godaddy/terminus": "^4.11.2",
18
+ "@mindful-web/express-apollo": "^1.0.0",
19
+ "@mindful-web/image": "^1.0.0",
20
+ "@mindful-web/marko-express": "^1.0.0",
21
+ "@mindful-web/marko-node-require": "^1.0.0",
22
+ "@mindful-web/object-path": "^1.0.0",
23
+ "@mindful-web/tenant-context": "^1.0.0",
24
+ "@mindful-web/utils": "^1.0.0",
25
+ "@mindful-web/web-common": "^1.0.0",
26
+ "express": "^4.18.2",
27
+ "graphql": "^14.7.0",
28
+ "graphql-tag": "^2.12.6",
29
+ "helmet": "^3.23.3",
30
+ "http-errors": "^1.8.1",
31
+ "marko": "~4.20.0",
32
+ "moment": "^2.29.1",
33
+ "moment-timezone": "^0.5.40",
34
+ "node-fetch": "^2.6.9",
35
+ "recursive-readdir": "^2.2.3"
36
+ },
37
+ "peerDependencies": {
38
+ "@mindful-web/marko-core": "^0.0.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "gitHead": "0b77cab713eb5841202bb86c7119949866bc68b5"
44
+ }
@@ -0,0 +1,115 @@
1
+ require('@mindful-web/marko-node-require');
2
+ const http = require('http');
3
+ const path = require('path');
4
+ const { createTerminus } = require('@godaddy/terminus');
5
+ const { isFunction: isFn } = require('@mindful-web/utils');
6
+ const express = require('./express');
7
+ const loadExports = require('./utils/load-exports');
8
+ const CoreConfig = require('./config/core');
9
+ const CustomConfig = require('./config/custom');
10
+
11
+ if (!process.env.LIVERELOAD_PORT) process.env.LIVERELOAD_PORT = 5010;
12
+ if (!process.env.EXPOSED_HOST) process.env.EXPOSED_HOST = 'localhost';
13
+
14
+ const { env } = process;
15
+ process.on('unhandledRejection', (e) => { throw e; });
16
+
17
+ module.exports = async ({
18
+ rootDir,
19
+ exportPath = 'exports', // Where exports will be resolved from.
20
+ customConfig: incomingCustomConfig,
21
+ coreConfig: incomingCoreConfig,
22
+ port = env.PORT || 6008,
23
+ exposedPort = env.EXPOSED_PORT || env.PORT || 6008,
24
+ exposedHost = env.EXPOSED_HOST,
25
+ graphqlUri = env.GRAPHQL_URI,
26
+ tenantKey = env.TENANT_KEY,
27
+ onAsyncBlockError,
28
+
29
+ // Terminus settings.
30
+ timeout = 1000,
31
+ signals = ['SIGTERM', 'SIGINT', 'SIGHUP', 'SIGQUIT'],
32
+ healthCheckPath = '/_health',
33
+ onSignal,
34
+ onShutdown,
35
+ onStart,
36
+ onHealthCheck,
37
+ } = {}) => {
38
+ if (!rootDir) throw new Error('The root project directory is required.');
39
+ if (!exportPath) throw new Error('An export location is required.');
40
+ if (!graphqlUri) throw new Error('The GraphQL API URL is required.');
41
+ if (!tenantKey) throw new Error('A tenant key is required.');
42
+
43
+ // Set the core config.
44
+ const coreConfig = new CoreConfig(incomingCoreConfig);
45
+ const customConfig = new CustomConfig(incomingCustomConfig);
46
+
47
+ // Load the export package file.
48
+ // eslint-disable-next-line import/no-dynamic-require, global-require
49
+ const sitePackage = require(path.resolve(rootDir, 'package.json'));
50
+
51
+ // Load exports.
52
+ const exports = await loadExports({
53
+ rootDir,
54
+ exportPath,
55
+ coreConfig,
56
+ customConfig,
57
+ });
58
+
59
+ const app = express({
60
+ rootDir,
61
+ exports,
62
+ customConfig,
63
+ coreConfig,
64
+ graphqlUri,
65
+ tenantKey,
66
+ onAsyncBlockError,
67
+ sitePackage,
68
+ });
69
+
70
+ // Await required services here...
71
+ if (isFn(onStart)) await onStart(app);
72
+
73
+ // Apply error handlers.
74
+ // errorHandlers(app, { export: errorTemplate, redirectHandler });
75
+
76
+ const server = http.createServer(app);
77
+
78
+ createTerminus(server, {
79
+ timeout,
80
+ signals,
81
+ // Add health checks of services here...
82
+ healthChecks: {
83
+ [healthCheckPath]: async () => {
84
+ if (isFn(onHealthCheck)) return onHealthCheck();
85
+ return { ping: 'pong' };
86
+ },
87
+ },
88
+ onSignal: async () => {
89
+ // Stop required services here...
90
+ if (isFn(onSignal)) await onSignal();
91
+ },
92
+ onShutdown: async () => {
93
+ if (isFn(onShutdown)) await onShutdown();
94
+ },
95
+ });
96
+
97
+ return new Promise((res, rej) => {
98
+ server.listen(port, function listen(err) {
99
+ if (err) {
100
+ rej(err);
101
+ } else {
102
+ res(this);
103
+ if (process.send) {
104
+ process.send({
105
+ event: 'ready',
106
+ name: sitePackage.name,
107
+ tenantKey,
108
+ graphqlUri,
109
+ location: `http://${exposedHost}:${exposedPort}`,
110
+ });
111
+ }
112
+ }
113
+ });
114
+ }).catch((e) => setImmediate(() => { throw e; }));
115
+ };
@@ -0,0 +1,43 @@
1
+ const readdir = require('recursive-readdir');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ let promise;
6
+
7
+ const load = async ({ rootDir, exportPath, coreConfig }) => {
8
+ const exportDir = path.resolve(rootDir, exportPath);
9
+ if (!fs.existsSync(exportDir)) throw new Error(`The directory ${exportDir} does not exist.`);
10
+
11
+ const extensions = Object.keys(coreConfig.getAsObject('fileExtensions'));
12
+ const fileMatch = new RegExp(`/.*.(${extensions.join('|')}).js$`);
13
+
14
+ const files = await readdir(exportDir);
15
+ const filtered = files.filter((filename) => fileMatch.test(filename));
16
+
17
+ return filtered.map((filename) => {
18
+ const { groups: { filepath, format } } = /(?<filepath>.*)\.(?<format>.*)\.js/.exec(filename);
19
+ const route = `${filepath.replace(exportDir, '')}.${format}`;
20
+ const siteMatch = /site\/(?<site>.*?)\//.exec(route);
21
+ const key = route.replace(/^\//, '');
22
+ // eslint-disable-next-line global-require, import/no-dynamic-require
23
+ const fn = require(filename);
24
+ if (typeof fn !== 'function') throw new Error(`${filename} must export a function!`);
25
+ return {
26
+ key,
27
+ route,
28
+ format,
29
+ filename,
30
+ fn,
31
+ name: key.replace('core/', ''),
32
+ ...(siteMatch && {
33
+ site: siteMatch.groups.site,
34
+ name: key.replace(`site/${siteMatch.groups.site}/`, ''),
35
+ }),
36
+ };
37
+ });
38
+ };
39
+
40
+ module.exports = ({ rootDir, exportPath, coreConfig }) => {
41
+ if (!promise) promise = load({ rootDir, exportPath, coreConfig });
42
+ return promise;
43
+ };
@@ -0,0 +1,7 @@
1
+ const { get, getAsArray, getAsObject } = require('@mindful-web/object-path');
2
+
3
+ module.exports = (site) => ({
4
+ get: (path, def) => get(site, path, def),
5
+ getAsArray: (path) => getAsArray(site, path),
6
+ getAsObject: (path) => getAsObject(site, path),
7
+ });