mosaic 1.0.12 → 1.0.14

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/package.json CHANGED
@@ -1,27 +1,25 @@
1
1
  {
2
2
  "name": "mosaic",
3
3
  "type": "module",
4
- "version": "1.0.12",
4
+ "version": "1.0.14",
5
5
  "description": "",
6
- "main": "index.js",
6
+ "main": "src/index.js",
7
7
  "scripts": {
8
8
  "test": "echo \"Error: no test specified\" && exit 1"
9
9
  },
10
10
  "keywords": [],
11
- "author": "",
11
+ "author": "defx",
12
12
  "license": "MIT",
13
13
  "dependencies": {
14
- "chokidar": "^3.5.3",
15
- "express": "^4.17.3",
16
- "fs-extra": "^10.0.1",
17
- "glob": "^7.2.0",
18
- "glob-promise": "^4.2.2",
19
- "html-minifier-terser": "^7.0.0-alpha.2",
20
- "http-proxy-middleware": "^2.0.5",
21
- "postcss": "^8.4.14",
22
- "postcss-import": "^14.1.0"
14
+ "customelementincludes": "^1.0.1",
15
+ "express": "^4.18.2",
16
+ "fs-extra": "^11.1.0",
17
+ "globby": "^13.1.3",
18
+ "highlight.js": "^11.7.0",
19
+ "markdown-it": "^13.0.1",
20
+ "nodemon": "^2.0.20"
23
21
  },
24
22
  "bin": {
25
- "mosaic": "index.js"
23
+ "mosaic": "node src/index.js"
26
24
  }
27
25
  }
@@ -0,0 +1,23 @@
1
+ import { html } from "./utils.js"
2
+
3
+ export const document = ({ title, head = "", main = "" }) => html`
4
+ <!DOCTYPE html>
5
+ <html lang="en">
6
+ <head>
7
+ <meta charset="UTF-8" />
8
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
9
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
10
+ ${title && `<title>${title}</title>`} ${head}
11
+ <!--<link
12
+ rel="stylesheet"
13
+ href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/base16/tomorrow.min.css"
14
+ integrity="sha512-5D/fcZ3y3nuaeHSxDbFwWDEy1Fvj5qQKsU0tilD7bhWAA+IN/Jl9fzGdUotzvA7wgXtsnZmafcuunH+6nyuA0A=="
15
+ crossorigin="anonymous"
16
+ referrerpolicy="no-referrer"
17
+ />-->
18
+ </head>
19
+ <body>
20
+ <main>${main}</main>
21
+ </body>
22
+ </html>
23
+ `
package/src/head.js ADDED
File without changes
package/src/index.js ADDED
@@ -0,0 +1,67 @@
1
+ import { customElementIncludes } from "customelementincludes"
2
+ import fs from "fs-extra"
3
+ import express from "express"
4
+ import { globby } from "globby"
5
+ import hljs from "highlight.js"
6
+ import MarkdownIt from "markdown-it"
7
+
8
+ // import postcss from "postcss"
9
+ // import prefixer from "postcss-prefix-selector"
10
+ import { decapitate } from "./head.js"
11
+ import { document } from "./document.js"
12
+
13
+ let md = new MarkdownIt({
14
+ html: true,
15
+ highlight: function (str, language) {
16
+ if (language && hljs.getLanguage(language)) {
17
+ try {
18
+ return (
19
+ '<pre class="hljs"><code>' +
20
+ hljs.highlight(str, { language, ignoreIllegals: true }).value +
21
+ "</code></pre>"
22
+ )
23
+ } catch (__) {}
24
+ }
25
+ return (
26
+ '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
27
+ )
28
+ },
29
+ })
30
+
31
+ ;(async () => {
32
+ const app = express()
33
+ const port = process.env.port || 3000
34
+
35
+ app.use(express.static("public"))
36
+
37
+ app.use("/components", express.static("components"))
38
+
39
+ app.use(async function (req, res, next) {
40
+ if (req.originalUrl.includes(".")) return next()
41
+
42
+ const route = req.originalUrl.split("?")[0]
43
+
44
+ const [filepath] = await globby([
45
+ `./pages${route === "/" ? "/index" : route}.(md|html)`,
46
+ ])
47
+
48
+ if (!file) return next()
49
+
50
+ const contents = await fs.readFile(filepath, "utf8")
51
+ const result = decapitate(contents)
52
+ const head = result.head
53
+ const main =
54
+ path.extname(filepath) === ".md" ? md.render(result.body) : result.body
55
+
56
+ const html = document({
57
+ head,
58
+ main,
59
+ })
60
+
61
+ res.send(await customElementIncludes(html))
62
+ })
63
+
64
+ app.listen(port, () => {
65
+ console.log(`Server running on port ${port}`)
66
+ })
67
+ })()
package/src/utils.js ADDED
@@ -0,0 +1,16 @@
1
+ function _(value) {
2
+ if (typeof value === "undefined") return ""
3
+ return String(Array.isArray(value) ? value.join("") : value)
4
+ }
5
+
6
+ function identity(template, ...args) {
7
+ let str = ""
8
+ for (let i = 0; i < args.length; i++) {
9
+ str += template[i] + _(args[i])
10
+ }
11
+ return str + template[template.length - 1]
12
+ }
13
+
14
+ export const html = identity
15
+ export const css = identity
16
+ export const gql = identity
package/css.js DELETED
@@ -1,71 +0,0 @@
1
- import path from "path"
2
-
3
- import postcss from "postcss"
4
- import atImport from "postcss-import"
5
-
6
- export function resolveImports(css, filepath) {
7
- return postcss()
8
- .use(atImport())
9
- .process(css, {
10
- from: filepath,
11
- })
12
- .then(({ css }) => css)
13
- }
14
-
15
- function nextWord(css, count) {
16
- return css.slice(count - 1).split(/[\s+|\n+|,]/)[0]
17
- }
18
-
19
- export function prefixSelectors(prefix, css) {
20
- let insideBlock = false
21
- let look = true
22
- let output = ""
23
- let count = 0
24
-
25
- for (let char of css) {
26
- if (char === "}") {
27
- insideBlock = false
28
- look = true
29
- } else if (char === ",") {
30
- look = true
31
- } else if (char === "{") {
32
- insideBlock = true
33
- } else if (look && !insideBlock && !char.match(/\s/)) {
34
- let w = nextWord(css, count + 1)
35
-
36
- // console.log({ w })
37
-
38
- if (
39
- w !== prefix &&
40
- w.charAt(0) !== "@" &&
41
- w.charAt(0) !== ":" &&
42
- w.charAt(0) !== "*" &&
43
- w !== "html" &&
44
- w !== "body"
45
- ) {
46
- output += prefix + " "
47
- }
48
- look = false
49
- }
50
- output += char
51
- count += 1
52
- }
53
-
54
- return output
55
- }
56
-
57
- function tagName(v) {
58
- return path.dirname(v.filepath).split(path.sep).pop()
59
- }
60
-
61
- export function scopeComponentCSSWithElementSelectors(v) {
62
- return {
63
- ...v,
64
- componentCSS: v.componentCSS.map((v) => {
65
- return {
66
- ...v,
67
- content: prefixSelectors(tagName(v), v.content),
68
- }
69
- }),
70
- }
71
- }
package/helix.js DELETED
@@ -1,40 +0,0 @@
1
- import chokidar from "chokidar"
2
- import fs from "fs-extra"
3
- import glob from "glob-promise"
4
- import path from "path"
5
-
6
- export const helix = (config) => {
7
- const cache = {}
8
-
9
- const updateCache = (key, filepath) =>
10
- fs.promises.readFile(filepath, "utf8").then((content) => {
11
- let { transform = {} } = config
12
- ;(transform[key] || [])
13
- .reduce((p, f) => p.then(f), Promise.resolve({ content, filepath }))
14
- .then((v) => {
15
- cache[key][filepath] = v
16
- transform.afterEach?.(v, cache)
17
- })
18
- })
19
-
20
- const populateCache = () =>
21
- Promise.all(
22
- Object.entries(config.input).map(([key, globPath]) => {
23
- cache[key] = {}
24
- return glob(globPath).then((paths) =>
25
- Promise.all(paths.map((f) => updateCache(key, path.normalize(f))))
26
- )
27
- })
28
- )
29
-
30
- return populateCache().then(() => {
31
- if (config.watch) {
32
- Object.entries(config.input).forEach(([key, glob]) => {
33
- chokidar.watch(glob).on("change", (filepath) => {
34
- updateCache(key, filepath)
35
- })
36
- })
37
- }
38
- return cache
39
- })
40
- }
package/helpers.js DELETED
@@ -1,67 +0,0 @@
1
- import fs from "fs-extra"
2
- import path from "path"
3
-
4
- export async function write({ filepath, content }) {
5
- return fs
6
- .ensureDir(path.dirname(filepath))
7
- .then(() => fs.promises.writeFile(filepath, content))
8
- }
9
-
10
- export const tagName = (filepath) => {
11
- return path.dirname(filepath).split(path.sep).pop()
12
- }
13
-
14
- const ANON = /<([a-z]\w*-\w*)/gm
15
-
16
- export function customTags(html = "") {
17
- return (html.match(ANON) || []).map((v) => v.slice(1))
18
- }
19
-
20
- export function resolveTagNames(
21
- component,
22
- components,
23
- o = { [component.tagName]: true },
24
- f = true
25
- ) {
26
- for (let k of component.tags) {
27
- let c = components.find(({ tagName }) => tagName === k)
28
- if (c && !(k in o)) {
29
- o[k] = true
30
- o = resolveTagNames(c, components, o, false)
31
- }
32
- }
33
- return f ? Object.keys(o) : o
34
- }
35
-
36
- export function groupBy(key, arr) {
37
- return arr.reduce((a, v) => {
38
- let k = v[key]
39
- a[k] = a[k] || []
40
- a[k].push(v)
41
- return a
42
- }, {})
43
- }
44
-
45
- export function withTemplate({ filepath, content }) {
46
- return `
47
- <template id="${tagName(filepath)}">
48
- ${content}
49
- </template>
50
- `
51
- }
52
-
53
- export const splice = (str, START_MARKER, END_MARKER) => {
54
- let start = str.indexOf(START_MARKER)
55
-
56
- if (start === -1) return str
57
-
58
- let end = str.indexOf(END_MARKER, start)
59
-
60
- if (end === -1) return str
61
-
62
- return splice(
63
- str.slice(0, start) + str.slice(end + END_MARKER.length),
64
- START_MARKER,
65
- END_MARKER
66
- )
67
- }
package/index.js DELETED
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import path from "path"
4
- import { start } from "./server.js"
5
-
6
- const [cmd] = process.argv.slice(2)
7
-
8
- switch (cmd) {
9
- default: {
10
- import(path.resolve("./mosaic.config.js")).then(({ default: config }) =>
11
- start(config)
12
- )
13
- break
14
- }
15
- }
package/router.js DELETED
@@ -1,33 +0,0 @@
1
- export function matchRoute(pathname, routes) {
2
- let a = pathname.split("/")
3
- for (let route of routes) {
4
- let b = (route.match || "").split("/")
5
- if (b.length !== a.length) continue
6
- if (b.every((x, i) => x.charAt(0) === ":" || x === a[i])) {
7
- return route
8
- }
9
- }
10
- }
11
-
12
- export function getParamsAsObject(pathname, route) {
13
- let a = pathname.split("/")
14
- let b = route.match.split("/")
15
- return b.reduce((o, k, i) => {
16
- if (k.charAt(0) === ":") {
17
- o[k.slice(1)] = a[i]
18
- }
19
- return o
20
- }, {})
21
- }
22
-
23
- export function getParams(pathname, route) {
24
- let a = pathname.split("/")
25
- let b = route.match.split("/")
26
- let result = ""
27
- b.forEach((k, i) => {
28
- if (k.charAt(0) === ":") {
29
- result += ` ${k.slice(1)}="${a[i]}"`
30
- }
31
- })
32
- return result
33
- }
package/server.js DELETED
@@ -1,186 +0,0 @@
1
- import path from "path"
2
- import express from "express"
3
-
4
- import { helix } from "./helix.js"
5
- import { prefixSelectors, resolveImports } from "./css.js"
6
- import { tagName, customTags, resolveTagNames } from "./helpers.js"
7
- import { matchRoute, getParams } from "./router.js"
8
- import { createProxyMiddleware } from "http-proxy-middleware"
9
-
10
- export const start = async (config) => {
11
- let port = config.port || 3000
12
- let app = express()
13
-
14
- let components = await helix({
15
- watch: true,
16
- input: {
17
- mosaicjs: "./node_modules/synergy/dist/synergy.js",
18
- html: "./components/**/index.html",
19
- css: "./components/**/index.css",
20
- js: "./components/**/index.js",
21
- },
22
- transform: {
23
- html: [
24
- (v) => {
25
- let { filepath, content } = v
26
-
27
- return {
28
- ...v,
29
- tags: customTags(content),
30
- tagName: tagName(filepath),
31
- }
32
- },
33
- ],
34
- css: [
35
- (v) => {
36
- let { filepath, content } = v
37
- return {
38
- ...v,
39
- content: prefixSelectors(tagName(filepath), content),
40
- }
41
- },
42
- ],
43
- js: [],
44
- synergyjs: [],
45
- afterEach: (v, cache) => {
46
- let { filepath } = v
47
- let k = tagName(filepath)
48
- let ext = path.extname(filepath).slice(1)
49
- cache[k] = cache[k] || {}
50
- cache[k][ext] = v
51
- },
52
- },
53
- })
54
-
55
- app.use("/components", express.static("components"))
56
- app.use(express.static("public"))
57
-
58
- function expandPartials(html) {
59
- let tags = customTags(html)
60
-
61
- for (let tag of tags) {
62
- if (components[tag] && !components[tag].js && components[tag].html) {
63
- // this component has no js module so lets treat it as a partial...
64
- html = html.replaceAll(
65
- `</${tag}>`,
66
- `${expandPartials(components[tag].html.content)}</${tag}>`
67
- )
68
- }
69
- }
70
- return html
71
- }
72
-
73
- app.get("/components/:id/entry.js", (req, res, next) => {
74
- let name = req.params.id
75
-
76
- if (name in components) {
77
- let component = components[name]
78
-
79
- let tags = resolveTagNames(component.html, Object.values(components.html))
80
-
81
- res.type(".js")
82
- res.send(`
83
- import factory from "./index.js";
84
- const template = \`${expandPartials(component.html.content, tags)}\`;
85
- export { factory, template }
86
- `)
87
- } else {
88
- next()
89
- }
90
- })
91
-
92
- app.get("/synergy.js", (_, res) => {
93
- res.type(".js")
94
- res.send(
95
- components.synergyjs["node_modules/synergy/dist/synergy.js"].content
96
- )
97
- })
98
-
99
- app.use(async function (req, res, next) {
100
- let k = "/" + req.originalUrl.split("?")[0].replace(/^\/|\/$/g, "")
101
-
102
- let route = matchRoute(k, config.routes)
103
-
104
- if (!route) return next()
105
-
106
- let params = getParams(k, route)
107
-
108
- let templates = Object.values(components.html)
109
-
110
- let pageTemplate = templates.find(
111
- ({ tagName }) => tagName === route.component
112
- )
113
-
114
- let tagNames = resolveTagNames(pageTemplate, templates)
115
-
116
- if (config.wrapper) tagNames.unshift(config.wrapper)
117
-
118
- let cssComponents = tagNames.reduce((styles, t) => {
119
- let x = Object.values(components.css).find(
120
- ({ filepath }) => tagName(filepath) === t
121
- )
122
- if (x) styles.push(x)
123
- return styles
124
- }, [])
125
-
126
- let componentStyles = ""
127
-
128
- for (let { content, filepath } of cssComponents) {
129
- let css = await resolveImports(content, filepath)
130
- componentStyles += css
131
- }
132
-
133
- let componentHTML = `<${route.component}${params}></${route.component}>`
134
-
135
- let html = `
136
- <!DOCTYPE html>
137
- <html lang="en">
138
- <head>
139
- <meta charset="UTF-8">
140
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
141
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
142
- <style>${componentStyles}</style>
143
- </head>
144
- <body>
145
-
146
- ${componentHTML}
147
- <script type="module">
148
-
149
- import { define } from "/synergy.js";
150
-
151
- ${JSON.stringify(
152
- tagNames.filter((name) => components[name].js)
153
- )}.forEach(name => import(\`/components/\${name}/entry.js\`).then(({ factory, template }) => define(name, factory, template)));
154
- </script>
155
- </body>
156
- </html>
157
- `
158
-
159
- res.send(html)
160
- })
161
-
162
- app.use("/node_modules", express.static("node_modules"))
163
-
164
- app.use(
165
- "/api",
166
- createProxyMiddleware({
167
- target: {
168
- host: "localhost",
169
- port: 4000,
170
- },
171
- secure: false,
172
- pathRewrite: {
173
- [`^/api`]: "",
174
- },
175
- })
176
- )
177
-
178
- app.listen(port, () =>
179
- console.log(`Express server listening on port ${port}`)
180
- )
181
-
182
- return {
183
- config,
184
- components,
185
- }
186
- }