routerino 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Nerds With Keyboards
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,65 @@
1
+ # Routerino
2
+
3
+ Tiny, SEO-focused router for React CSR websites, such as JAMStack or Vite.js sites. Supports [Prerender](https://github.com/prerender/prerender) tags for handling redirects and 404 codes for SEO bots. Routerino can even generate your sitemap.xml file from your routes!
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm i routerino
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Here is a basic usage example:
14
+
15
+ ```jsx
16
+ import Routerino from "routerino";
17
+
18
+ const routes = [
19
+ {
20
+ path: "/",
21
+ element: <p>Hello, world!</p>,
22
+ title: "Hello!",
23
+ description: "Lorem ipsum......",
24
+ },
25
+ ];
26
+
27
+ const App = () => (
28
+ <div>
29
+ <header>
30
+ <a href="/">Home</a>
31
+ </header>
32
+
33
+ <Routerino routes={routes} titlePostfix=" | Foo.com" />
34
+
35
+ <footer>
36
+ <p>Copyright 2048 Foo.com</p>
37
+ </footer>
38
+ </div>
39
+ );
40
+
41
+ export default App;
42
+ ```
43
+
44
+ ## Generating a sitemap from routes
45
+
46
+ Run the command `build-sitemap` to create a sitemap.xml for your site. Adjust the arguments to your needs.
47
+
48
+ Arguments:
49
+
50
+ - routeFilePath: The path to whichever file contains your routes. The routes array can be defined either directly in the props to Routerino, or stored in an array called routes/Routes.
51
+ - hostname: The domain to use as the base for the URLs in the sitemap.
52
+ - outputPath: The path to write the new sitemap XML file.
53
+
54
+ Example:
55
+
56
+ ```sh
57
+ build-sitemap routeFilePath=src/routes.jsx hostname=https://example.com outputPath=dist/sitemap.xml
58
+ # sitemap.xml with 12 URLs written to dist/sitemap.xml
59
+ ```
60
+
61
+ Add `build-sitemap` to your build command to update automatically on every build. This sitemap only includes the location entry, as the rest are [mostly ignored by Google](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap#additional-notes-about-xml-sitemaps).
62
+
63
+ ### License
64
+
65
+ Routerino is [MIT licensed](./LICENSE).
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ import fs from "fs";
3
+
4
+ // parse the args
5
+ const { routeFilePath, hostname, outputPath } = process.argv
6
+ .filter((arg) => arg.includes("="))
7
+ .reduce((acc, cur) => {
8
+ const split = cur.split("=");
9
+ acc[split[0]] = split[1];
10
+ return acc;
11
+ }, {});
12
+
13
+ // input checks
14
+ if (!(routeFilePath && hostname && outputPath)) {
15
+ console.error(
16
+ `Error: missing some args! Cannot create sitemap.\nRequired args:\n - routeFilePath: ${routeFilePath}\n - hostname: ${hostname}\n - outputPath: ${outputPath}`
17
+ );
18
+ process.exit(1);
19
+ }
20
+
21
+ function getPathsFromFile(routeFilePath) {
22
+ // get file contents as a string, stripping comments
23
+ const routeFileString =
24
+ fs
25
+ .readFileSync(routeFilePath)
26
+ ?.toString()
27
+ ?.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, "") ?? "";
28
+
29
+ // match the routes array
30
+ //
31
+ // 1: routes or Routes
32
+ // 2: any spacing
33
+ // 3: = or :
34
+ // 4: any spacing
35
+ // 5: optional open brace
36
+ // 6: any spacing
37
+ // 7: group capture start - open bracket
38
+ // 8: any characters
39
+ // 9: group capture end - close bracket
40
+ //
41
+ // examples:
42
+ // - Routes = [...]
43
+ // - routes = [...]
44
+ // - <Router routes={[...]} />
45
+ // - <Router {...{ routes: [...] }} />
46
+ const arrayMatch = routeFileString.match(
47
+ /[rR]outes\s*[=:]\s*\{?\s*(\[[\s\S]*\])/
48
+ );
49
+ const routeString = arrayMatch[0] ?? "";
50
+
51
+ // match the paths
52
+ const matches = routeString.match(/path:\s*(["'`]).*?\1/g);
53
+ const paths =
54
+ matches.length > 0
55
+ ? matches.map((pathString) =>
56
+ pathString.match(/(["'`]).*?\1/)[0].slice(1, -1)
57
+ )
58
+ : [];
59
+ return paths;
60
+ }
61
+
62
+ function createSitemap({ hostname, paths }) {
63
+ return `<?xml version="1.0" encoding="UTF-8"?>
64
+ <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
65
+ ${paths.map((path) => ` <url><loc>${hostname}${path}</loc></url>`).join("\n")}
66
+ </urlset>`;
67
+ }
68
+
69
+ const paths = getPathsFromFile(routeFilePath);
70
+ const sitemap = createSitemap({ hostname, paths });
71
+
72
+ if (sitemap) {
73
+ fs.writeFileSync(outputPath, sitemap);
74
+ console.log(`sitemap.xml with ${paths.length} URLs written to ${outputPath}`);
75
+ }
@@ -0,0 +1,103 @@
1
+ import { jsx as s, jsxs as g, Fragment as $ } from "react/jsx-runtime";
2
+ import e from "prop-types";
3
+ function o({ tag: d = "meta", ...l }) {
4
+ const a = Object.keys(l);
5
+ if (a.length < 1)
6
+ return console.error(
7
+ `updateHeadTag() received no attributes to set for ${d} tag`
8
+ );
9
+ let c = null;
10
+ for (let r = 0; r < a.length && (a[r] !== "content" && (c = document.querySelector(
11
+ `${d}[${a[r]}='${l[a[r]]}']`
12
+ )), !c); r++)
13
+ ;
14
+ c || (c = document.createElement(d)), Object.keys(l).forEach(
15
+ (r) => c.setAttribute(r, l[r])
16
+ ), document.querySelector("head").appendChild(c);
17
+ }
18
+ function y({
19
+ routes: d,
20
+ notFoundTemplate: l,
21
+ notFoundTitle: a,
22
+ errorTemplate: c,
23
+ errorTitle: r,
24
+ useTrailingSlash: h,
25
+ usePrerenderTags: p,
26
+ titlePrefix: u,
27
+ titlePostfix: f
28
+ }) {
29
+ var m;
30
+ try {
31
+ let n = ((m = window == null ? void 0 : window.location) == null ? void 0 : m.pathname) ?? "/";
32
+ n === "/index.html" && (n = "/");
33
+ const T = d.find((i) => i.path === n), b = d.find(
34
+ (i) => `${i.path}/` === n || i.path === `${n}/`
35
+ ), t = T ?? b;
36
+ if (t) {
37
+ if (t.title) {
38
+ const i = `${t.titlePrefix ?? u}${t.title}${t.titlePostfix ?? f}`;
39
+ document.title = i, o({ property: "og:title", content: t.title });
40
+ }
41
+ return t.description && (o({ name: "description", content: t.description }), o({
42
+ property: "og:description",
43
+ content: t.description
44
+ })), p && (h && !n.endsWith("/") ? (o({ name: "prerender-status-code", content: "301" }), o({
45
+ name: "prerender-header",
46
+ content: `Location: ${window.location.href}/`
47
+ })) : !h && n.endsWith("/") && (o({ name: "prerender-status-code", content: "301" }), o({
48
+ name: "prerender-header",
49
+ content: `Location: ${window.location.href.slice(0, -1)}`
50
+ }))), t.tags && t.tags.length ? (t.tags.find(({ property: i }) => i === "og:type") || o({ property: "og:type", content: "website" }), t.tags.forEach((i) => o(i))) : o({ property: "og:type", content: "website" }), t.element ? t.element : (console.error(`No element found for ${n}`), document.title = `${u}${a}${f}`, p && o({ name: "prerender-status-code", content: "404" }), l);
51
+ }
52
+ return console.error(`No route found for ${n}`), document.title = `${u}${a}${f}`, p && o({ name: "prerender-status-code", content: "404" }), l;
53
+ } catch (n) {
54
+ return console.error(`Routerino error: ${n}`), p && o({ name: "prerender-status-code", content: "500" }), document.title = `${u}${r}${f}`, c;
55
+ }
56
+ }
57
+ y.defaultProps = {
58
+ routes: [
59
+ {
60
+ path: "/",
61
+ element: /* @__PURE__ */ s("p", { children: "This is the default route. Pass an array of routes to the Routerino component in order to configure your own pages." }),
62
+ description: "The default route example description.",
63
+ tags: [{ property: "og:locale", content: "en_US" }]
64
+ }
65
+ ],
66
+ notFoundTemplate: /* @__PURE__ */ g($, { children: [
67
+ /* @__PURE__ */ s("p", { children: "No page found for this URL. [404]" }),
68
+ /* @__PURE__ */ s("p", { children: /* @__PURE__ */ s("a", { href: "/", children: "Home" }) })
69
+ ] }),
70
+ notFoundTitle: "Page not found [404]",
71
+ errorTemplate: /* @__PURE__ */ g($, { children: [
72
+ /* @__PURE__ */ s("p", { children: "Page failed to load. [500]" }),
73
+ /* @__PURE__ */ s("p", { children: /* @__PURE__ */ s("a", { href: "/", children: "Home" }) })
74
+ ] }),
75
+ errorTitle: "Page error [500]",
76
+ useTrailingSlash: !0,
77
+ usePrerenderTags: !0,
78
+ titlePrefix: "",
79
+ titlePostfix: ""
80
+ };
81
+ const w = e.exact({
82
+ path: e.string.isRequired,
83
+ element: e.element.isRequired,
84
+ title: e.string,
85
+ description: e.string,
86
+ tags: e.arrayOf(e.object),
87
+ titlePrefix: e.string,
88
+ titlePostfix: e.string
89
+ });
90
+ y.propTypes = {
91
+ routes: e.arrayOf(w),
92
+ notFoundTemplate: e.element,
93
+ notFoundTitle: e.string,
94
+ errorTemplate: e.element,
95
+ errorTitle: e.string,
96
+ useTrailingSlash: e.bool,
97
+ usePrerenderTags: e.bool,
98
+ titlePrefix: e.string,
99
+ titlePostfix: e.string
100
+ };
101
+ export {
102
+ y as default
103
+ };
@@ -0,0 +1 @@
1
+ (function(t,e){typeof exports=="object"&&typeof module<"u"?module.exports=e(require("react/jsx-runtime"),require("prop-types")):typeof define=="function"&&define.amd?define(["react/jsx-runtime","prop-types"],e):(t=typeof globalThis<"u"?globalThis:t||self,t.routerino=e(t["react/jsx-runtime"],t.PropTypes))})(this,function(t,e){"use strict";function o({tag:s="meta",...l}){const c=Object.keys(l);if(c.length<1)return console.error(`updateHeadTag() received no attributes to set for ${s} tag`);let d=null;for(let i=0;i<c.length&&(c[i]!=="content"&&(d=document.querySelector(`${s}[${c[i]}='${l[c[i]]}']`)),!d);i++);d||(d=document.createElement(s)),Object.keys(l).forEach(i=>d.setAttribute(i,l[i])),document.querySelector("head").appendChild(d)}function p({routes:s,notFoundTemplate:l,notFoundTitle:c,errorTemplate:d,errorTitle:i,useTrailingSlash:m,usePrerenderTags:f,titlePrefix:u,titlePostfix:h}){var g;try{let r=((g=window==null?void 0:window.location)==null?void 0:g.pathname)??"/";r==="/index.html"&&(r="/");const x=s.find(a=>a.path===r),b=s.find(a=>`${a.path}/`===r||a.path===`${r}/`),n=x??b;if(n){if(n.title){const a=`${n.titlePrefix??u}${n.title}${n.titlePostfix??h}`;document.title=a,o({property:"og:title",content:n.title})}return n.description&&(o({name:"description",content:n.description}),o({property:"og:description",content:n.description})),f&&(m&&!r.endsWith("/")?(o({name:"prerender-status-code",content:"301"}),o({name:"prerender-header",content:`Location: ${window.location.href}/`})):!m&&r.endsWith("/")&&(o({name:"prerender-status-code",content:"301"}),o({name:"prerender-header",content:`Location: ${window.location.href.slice(0,-1)}`}))),n.tags&&n.tags.length?(n.tags.find(({property:a})=>a==="og:type")||o({property:"og:type",content:"website"}),n.tags.forEach(a=>o(a))):o({property:"og:type",content:"website"}),n.element?n.element:(console.error(`No element found for ${r}`),document.title=`${u}${c}${h}`,f&&o({name:"prerender-status-code",content:"404"}),l)}return console.error(`No route found for ${r}`),document.title=`${u}${c}${h}`,f&&o({name:"prerender-status-code",content:"404"}),l}catch(r){return console.error(`Routerino error: ${r}`),f&&o({name:"prerender-status-code",content:"500"}),document.title=`${u}${i}${h}`,d}}p.defaultProps={routes:[{path:"/",element:t.jsx("p",{children:"This is the default route. Pass an array of routes to the Routerino component in order to configure your own pages."}),description:"The default route example description.",tags:[{property:"og:locale",content:"en_US"}]}],notFoundTemplate:t.jsxs(t.Fragment,{children:[t.jsx("p",{children:"No page found for this URL. [404]"}),t.jsx("p",{children:t.jsx("a",{href:"/",children:"Home"})})]}),notFoundTitle:"Page not found [404]",errorTemplate:t.jsxs(t.Fragment,{children:[t.jsx("p",{children:"Page failed to load. [500]"}),t.jsx("p",{children:t.jsx("a",{href:"/",children:"Home"})})]}),errorTitle:"Page error [500]",useTrailingSlash:!0,usePrerenderTags:!0,titlePrefix:"",titlePostfix:""};const $=e.exact({path:e.string.isRequired,element:e.element.isRequired,title:e.string,description:e.string,tags:e.arrayOf(e.object),titlePrefix:e.string,titlePostfix:e.string});return p.propTypes={routes:e.arrayOf($),notFoundTemplate:e.element,notFoundTitle:e.string,errorTemplate:e.element,errorTitle:e.string,useTrailingSlash:e.bool,usePrerenderTags:e.bool,titlePrefix:e.string,titlePostfix:e.string},p});
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "routerino",
3
+ "version": "1.0.0",
4
+ "description": "Tiny, SEO-focused router for React websites",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/nerds-with-keyboards/routerino.git"
8
+ },
9
+ "keywords": [
10
+ "router",
11
+ "react",
12
+ "seo",
13
+ "prerender"
14
+ ],
15
+ "license": "MIT",
16
+ "bugs": {
17
+ "url": "https://github.com/nerds-with-keyboards/routerino/issues"
18
+ },
19
+ "homepage": "https://github.com/nerds-with-keyboards/routerino#readme",
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "bin": {
24
+ "build-sitemap": "build-sitemap.js"
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ "import": "./dist/routerino.js",
29
+ "require": "./dist/routerino.umd.cjs"
30
+ },
31
+ "scripts": {
32
+ "build": "vite build",
33
+ "test": "echo TODO",
34
+ "prepublishOnly": "vite build"
35
+ },
36
+ "devDependencies": {
37
+ "@vitejs/plugin-react": "^4.1.0",
38
+ "prop-types": "^15.8.1",
39
+ "react": "^18.2.0",
40
+ "react-dom": "^18.2.0",
41
+ "vite": "^4.4.9"
42
+ },
43
+ "peerDependencies": {
44
+ "prop-types": "^15.0.0",
45
+ "react": "^18.0.0",
46
+ "react-dom": "^18.0.0"
47
+ },
48
+ "engines": {
49
+ "node": ">=20"
50
+ },
51
+ "volta": {
52
+ "node": "20.7.0",
53
+ "npm": "10.1.0"
54
+ }
55
+ }