Skip to content

Commit

Permalink
Browser target codes added
Browse files Browse the repository at this point in the history
  • Loading branch information
darsan-in committed Nov 19, 2024
1 parent 450437a commit f14ddb7
Show file tree
Hide file tree
Showing 5 changed files with 200 additions and 1 deletion.
23 changes: 23 additions & 0 deletions lib/browser/branding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export default function branding() {
const asciiArt = `
_______ _____ ______
| \\ | \\ / \\
| $$$$$$$\\ \\$$$$$ | $$$$$$\\
| $$__| $$ | $$ | $$___\\$$
| $$ $$ __ | $$ \\$$ \\
| $$$$$$$\\ | \\ | $$ _\\$$$$$$\\
| $$ | $$ | $$__| $$ | \\__| $$
| $$ | $$ \\$$ $$ \\$$ $$
\\$$ \\$$ \\$$$$$$ \\$$$$$$
`;

console.log(
asciiArt,
"\n",
"Rich results are powered by Richie JS,",
"\n",
"an open source SEO project.",
"\n",
"https://richiejs.cresteem.com/",
);
}
38 changes: 38 additions & 0 deletions lib/browser/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Plugins } from "../types";
import {
basename,
cwd,
dirname,
join,
relative,
resolve,
} from "./pathlib";

import { load } from "cheerio/slim";
import baseConfig from "../base-config";
import { configurationOptions } from "../types";

const browPlugins: Plugins = {
htmlParser: load,
fetchGeoLocation: (_meta: any) => "",
pathLib: {
dirname: dirname,
basename: basename,
join: join,
relative: relative,
resolve: resolve,
sep: "/",
cwd: cwd,
},
cryptoLib: { createHash: () => {}, randomBytes: () => {} },
fsLib: {
readFileSync: (_, __) => "",
stat: () => "" as any,
existsSync: () => false,
},
};

export const config: Partial<configurationOptions> = {
...baseConfig,
...browPlugins,
};
65 changes: 65 additions & 0 deletions lib/browser/core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import functionMapper from "../function-map";
import { config } from "./config";

import branding from "./branding";

import { richieGroupA, richieGroupB, richieReactOptions } from "../types";

/* not supported
1-breadcrumb
*/

function createJsonLDElem(
innerDataObject: Record<string, any>,
): HTMLScriptElement | null {
if (!innerDataObject) {
return null;
}

const script = document.createElement("script");
script.setAttribute("type", "application/ld+json");
script.innerHTML = JSON.stringify(innerDataObject);

return script;
}

export default async function richieReact({
richieNames,
}: richieReactOptions): Promise<void> {
branding();

const functionMap = functionMapper(config);

const source: string = document.documentElement.outerHTML;
const docPath: string = location.pathname;

for (const richieName of richieNames) {
//standardize parameters
const aggregatorParams: string[] | boolean =
richieGroupA.includes(richieName) ? [source]
: richieGroupB.includes(richieName) ? [source, docPath]
: false;

if (!aggregatorParams) {
throw new Error("Unsupported Richie name");
} else {
const aggregator: Function = functionMap[richieName].aggregator;
const serializer: Function = functionMap[richieName].serializer;

const aggregatedData = await aggregator(...aggregatorParams);

const serializerParams: any[] =
richieName === "productwv" ?
[...Object.values(aggregatedData)] // [productMeta,variesBy]
: richieName === "product" ?
[Object.values(aggregatedData)[0]] // [productMeta]
: [aggregatedData];

const serializedData = serializer(...serializerParams);
const jsonLDElem = createJsonLDElem(serializedData);
if (jsonLDElem) {
document.head.appendChild(jsonLDElem);
}
}
}
}
72 changes: 72 additions & 0 deletions lib/browser/pathlib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
export function dirname(filePath: string) {
return filePath.substring(0, filePath.lastIndexOf("/"));
}

export function basename(path: string, ext: string = "") {
// Extract the base name of the path
const base: string = path.split("/").pop() ?? "";

// If an extension is provided, remove it
if (ext && base.endsWith(ext)) {
return base.slice(0, -ext.length);
}

return base;
}

export function join(...args: string[]) {
// Normalize paths and remove leading/trailing slashes, if any
return args
.map((segment) =>
segment.replace(/[/\\]+$/, "").replace(/^[/\\]+/, ""),
)
.filter(Boolean) // Remove empty strings
.join("/");
}

export function relative(from: string, to: string) {
// Normalize paths by splitting into segments
const fromParts = from.replace(/[/\\]+$/, "").split("/");
const toParts = to.replace(/[/\\]+$/, "").split("/");

// Remove common leading segments
while (
fromParts.length &&
toParts.length &&
fromParts[0] === toParts[0]
) {
fromParts.shift();
toParts.shift();
}

// Calculate the number of steps back needed in the 'from' path
const stepsUp = fromParts.length;

// Create the relative path: go up from 'from' and then go down to 'to'
const relativePath = "../".repeat(stepsUp) + toParts.join("/");

return relativePath || ".";
}

export function resolve(...paths: string[]) {
// Initialize an array to hold the resolved path segments
let resolvedPath: string[] = [];

// Process each path from right to left (similar to how Node.js resolve works)
paths.reverse().forEach((path) => {
// If the path is absolute (starts with '/'), it becomes the new base
if (path.startsWith("/") || path.startsWith("\\")) {
resolvedPath = [path.replace(/[/\\]+$/, "")];
} else {
// Otherwise, append the path to the current resolvedPath
resolvedPath.unshift(path.replace(/[/\\]+$/, ""));
}
});

// Join the resolved path segments and normalize by ensuring only one leading '/'
return resolvedPath.join("/").replace(/\/+/g, "/");
}

export function cwd() {
return document.baseURI;
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"exclude": [
"node_modules",
"test",
"jest.config.ts"
"jest.config.ts",
"lib/browser"
]
}

0 comments on commit f14ddb7

Please sign in to comment.