Skip to content

Commit

Permalink
chore: update dist
Browse files Browse the repository at this point in the history
  • Loading branch information
double-beep committed Oct 14, 2024
1 parent 7ae724f commit ffcf691
Show file tree
Hide file tree
Showing 25 changed files with 110 additions and 101 deletions.
12 changes: 6 additions & 6 deletions dist/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const sharedOpts = {
du: {
alias: "download-url",
description: "URL for the @downloadURL header",
type: "string"
type: "string",
},
e: {
alias: "eol",
Expand Down Expand Up @@ -96,7 +96,7 @@ const sharedOpts = {
q: {
alias: "require",
description: "Generates valid @require headers (repeatable)",
type: "array"
type: "array",
},
r: {
alias: "run",
Expand All @@ -113,7 +113,7 @@ const sharedOpts = {
u: {
alias: "update-url",
description: "URL for the @updateURL header for Tampermonkey, no-op otherwise",
type: "string"
type: "string",
},
w: {
alias: "whitelist",
Expand All @@ -131,7 +131,7 @@ const sharedOpts = {
description: "Prettifies outputted headers where possible",
},
};
names.forEach((name) => cli.command(name, `generates ${scase(name)} headers`, sharedOpts, ({ c, ch = [], d, du, e, h, g = [], i, l, lf, m = [], n, nf, q = [], o, p, r = "start", s, pretty, u, w = [], x = [] }) => void generate(name, {
names.forEach(name => cli.command(name, `generates ${scase(name)} headers`, sharedOpts, ({ c, ch = [], d, du, e, h, g = [], i, l, lf, m = [], n, nf, q = [], o, p, r = "start", s, pretty, u, w = [], x = [] }) => void generate(name, {
collapse: c,
custom: ch,
direct: !!d,
Expand All @@ -153,6 +153,6 @@ names.forEach((name) => cli.command(name, `generates ${scase(name)} headers`, sh
spaces: s,
pretty,
updateURL: u,
whitelist: w.map(String)
whitelist: w.map(String),
}, import.meta.url === pathToFileURL(process.argv[1]).href)));
cli.demandCommand().help().parse();
void cli.demandCommand().help().parse();
6 changes: 3 additions & 3 deletions dist/generate.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ export type GeneratorOptions<T extends GrantOptions> = CommonGeneratorOptions &
run?: RunAtOption;
spaces?: number;
updateURL?: string;
whitelist?: Array<"self" | "localhost" | "*"> | string[];
whitelist?: ("self" | "localhost" | "*")[] | string[];
};
export type WriteHeadersOptions = {
export interface WriteHeadersOptions {
cli: boolean;
direct: boolean;
eol?: string;
output: string;
};
}
export declare const managersSupportingHomepage: Set<UserScriptManagerName>;
export declare const writeHeaders: (content: string, options: WriteHeadersOptions) => Promise<string>;
export declare const generate: <T extends GrantOptions>(type: UserScriptManagerName, options: GeneratorOptions<T>, cli?: boolean) => Promise<string>;
21 changes: 11 additions & 10 deletions dist/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { generateViolentmonkeyHeaders } from "./generators/violentmonkey/index.j
import { lintHeaders } from "./linters/index.js";
import { replaceFileContent } from "./utils/filesystem.js";
import { getPackage } from "./utils/package.js";
import { getExistingHeadersOffset, validateConnectHeaders, validateExcludeHeaders, validateMatchHeaders, validateOptionalHeaders, validateRequiredHeaders } from "./utils/validators.js";
import { getExistingHeadersOffset, validateConnectHeaders, validateExcludeHeaders, validateMatchHeaders, validateOptionalHeaders, validateRequiredHeaders, } from "./utils/validators.js";
export const managersSupportingHomepage = new Set(["tampermonkey", "violentmonkey"]);
export const writeHeaders = async (content, options) => {
const { cli, direct, eol, output } = options;
Expand All @@ -21,7 +21,7 @@ export const writeHeaders = async (content, options) => {
await replaceFileContent(output, openOffset, closeOffset, content);
return content;
}
await replaceFileContent(output, 0, 0, `${content}${eol}`);
await replaceFileContent(output, 0, 0, `${content}${eol || ""}`);
return content;
}
if (cli)
Expand All @@ -41,15 +41,15 @@ export const generate = async (type, options, cli = false) => {
console.error(chulk.bgRed `missing or corrupted package`);
return "";
}
const { invalid: matchInvalid, status: matchStatus, valid: validMatches } = validateMatchHeaders(matches);
const { invalid: matchInvalid, status: matchStatus, valid: validMatches, } = validateMatchHeaders(matches);
if (!matchStatus) {
console.error(chulk.bgRed `Invalid @match headers:\n` + matchInvalid.join("\n"));
}
const { invalid: excludeInvalid, status: excludeStatus, valid: validExcludes } = validateExcludeHeaders(excludes);
const { invalid: excludeInvalid, status: excludeStatus, valid: validExcludes, } = validateExcludeHeaders(excludes);
if (!excludeStatus) {
console.error(chulk.bgRed `Invalid @exclude headers:\n` + excludeInvalid.join("\n"));
}
const { invalid: connectInvalid, status: connectStatus, valid: validConnects } = validateConnectHeaders(whitelist);
const { invalid: connectInvalid, status: connectStatus, valid: validConnects, } = validateConnectHeaders(whitelist);
if (!connectStatus) {
console.error(chulk.bgRed `Invalid @connect headers:\n` + connectInvalid.join("\n"));
}
Expand All @@ -58,7 +58,7 @@ export const generate = async (type, options, cli = false) => {
console.error(chulk.bgRed `Invalid homepage URL:\n` + parsedPackage.homepage);
}
const { isValidDownloadURL } = validateOptionalHeaders(options);
if (!isValidDownloadURL) {
if (!isValidDownloadURL && options.downloadURL) {
console.error(chulk.bgRed `Invalid @downloadURL:\n` + options.downloadURL);
}
if (!isValidVersion) {
Expand Down Expand Up @@ -88,19 +88,20 @@ export const generate = async (type, options, cli = false) => {
});
if (error)
console.error(error);
return writeHeaders(headers, { cli, direct, eol, output });
return await writeHeaders(headers, { cli, direct, eol, output });
}
return writeHeaders(content, { cli, direct, eol, output });
return await writeHeaders(content, { cli, direct, eol, output });
}
catch (error) {
const exceptionObject = error;
const { code, name } = exceptionObject;
const errMap = {
ENOENT: ({ path }) => ["Missing path:", path],
ENOENT: ({ path }) => ["Missing path:", path || ""],
ENOTFOUND: ({ message }) => ["Network failure:", message],
default: ({ message }) => ["Something went wrong:", message],
};
const handler = errMap[code || "default"] || errMap.default;
const key = code === "ENOENT" || code === "ENOTFOUND" ? code : "default";
const handler = errMap[key];
const [postfix, message] = handler(exceptionObject);
console.error(chulk.bgRed `[${name}] ${postfix}` + `\n\n${message}`);
return "";
Expand Down
4 changes: 2 additions & 2 deletions dist/generators/common/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ export type CommonHeaders<T extends object = {}> = T & {
export type CommonGrantOptions = "get" | "set" | "list" | "delete" | "unsafe";
export type CommonGrants = "none" | "unsafeWindow";
export type CommonRunAt = "document-start" | "document-end" | "document-idle";
export type CommonGeneratorOptions = {
export interface CommonGeneratorOptions {
namespace?: string;
noframes?: boolean;
pretty?: boolean;
};
}
export declare const generateCommonHeaders: (pkg: PackageInfo, options: CommonGeneratorOptions) => HeaderEntries<{
author: PackagePerson;
contributors?: PackagePerson[];
Expand Down
7 changes: 4 additions & 3 deletions dist/generators/common/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { formatAuthor, parseAuthor } from "../../utils/author.js";
import { parseName, prettifyName } from "../../utils/name.js";
;
export const generateCommonHeaders = (pkg, options) => {
const { namespace, noframes = false, pretty = false } = options;
const { author, description, name, version, icon, contributors = [], license } = pkg;
const { namespace, noframes = false, pretty = false, } = options;
const { author, description, name, version, icon, contributors = [], license, } = pkg;
const parsedAuthor = parseAuthor(author);
const { packageName, scope } = parseName(name);
const headers = [
Expand All @@ -21,7 +22,7 @@ export const generateCommonHeaders = (pkg, options) => {
if (noframes)
headers.push(["noframes", ""]);
if (contributors.length) {
const formatted = contributors.map((contributor) => formatAuthor(parseAuthor(contributor)));
const formatted = contributors.map(contributor => formatAuthor(parseAuthor(contributor)));
headers.push(["contributors", formatted.join(", ")]);
}
return headers;
Expand Down
19 changes: 17 additions & 2 deletions dist/generators/common/monkey.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,28 @@ export const makeMonkeyTags = (name = "UserScript") => [
`// ==/${name}==`,
];
export const makeMonkeyHeader = (header) => {
const [name, value,] = header;
const [name, value] = header;
return (value ? `// @${name} ${value}` : `// @${name}`);
};
export const finalizeMonkeyHeaders = (headers, spaces) => {
const [openTag, closeTag] = makeMonkeyTags();
const longest = getLongest(headers.map(([key]) => key)) + spaces - 1;
const sortedHeaders = headers.sort(([a], [b]) => a === "name" ? -1 : a < b ? -1 : 1);
const important = [
"name",
"namespace",
"version",
"author",
"contributor",
"contributors",
];
const primary = important
.map(name => headers.find(([header]) => header === name))
.filter(Boolean);
const secondary = headers.filter(([header]) => !important.includes(header));
const sortedHeaders = [
...primary,
...secondary,
];
const indentedHeaders = sortedHeaders.map(([key, val]) => [
key.padEnd(longest),
val,
Expand Down
4 changes: 1 addition & 3 deletions dist/generators/custom.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import type { HeaderEntries } from "./index.js";
export type CustomHeaders = {
contributors: string;
} & {
[name: string]: string;
};
} & Record<string, string>;
export declare const generateCustomHeaders: (custom: string[]) => HeaderEntries<CustomHeaders>;
2 changes: 1 addition & 1 deletion dist/generators/greasemonkey/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { scrapeNetworkSites } from "../../utils/scraper.js";
import { generateCommonHeaders } from "../common/index.js";
import { finalizeMonkeyHeaders } from "../common/monkey.js";
import { generateCustomHeaders } from "../custom.js";
import { generateExcludeHeaders, generateGrantHeaders, generateMatchHeaders, generateRequireHeaders, generateRunAtHeaders } from "../index.js";
import { generateExcludeHeaders, generateGrantHeaders, generateMatchHeaders, generateRequireHeaders, generateRunAtHeaders, } from "../index.js";
export const generateGreasemonkeyHeaders = async (packageInfo, options) => {
const { collapse = false, custom = [], excludes = [], grants = [], matches = [], namespace, noframes = false, pretty = false, requires = [], run = "start", } = options;
const commonHeaders = generateCommonHeaders(packageInfo, { namespace, noframes, pretty });
Expand Down
9 changes: 1 addition & 8 deletions dist/generators/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ import type { CommonHeaders } from "./common/index.js";
import type { GreasemonkeyGrantOptions } from "./greasemonkey/types.js";
import type { TampermonkeyGrantOptions } from "./tampermonkey/types.js";
import type { ViolentmonkeyGrantOptions } from "./violentmonkey/types.js";
declare global {
interface String {
padEnd<T extends string>(maxLength: number, fillString?: string): T;
}
}
export type GrantOptions = GreasemonkeyGrantOptions | TampermonkeyGrantOptions | ViolentmonkeyGrantOptions | "all";
export type UserScriptManagerName = "tampermonkey" | "violentmonkey" | "greasemonkey";
export type HeaderGenerator<T extends GrantOptions> = (info: PackageInfo, options: RequiredProps<GeneratorOptions<T>, "spaces">) => Promise<string>;
Expand All @@ -24,9 +19,7 @@ export declare const generateExcludeMatchHeaders: <T extends {
export declare const generateMatchHeaders: <T extends CommonHeaders>(matches: string[], networkSiteScraper: () => Promise<NetworkSiteInfo[]>, collapse?: boolean) => Promise<HeaderEntries<T>>;
export declare const generateRunAtHeaders: <T extends {
"run-at": string;
}>(runAtMap: { [P in RunAtOption]?: T["run-at"]; } & {
[x: string]: unknown;
}, runAt: T["run-at"]) => HeaderEntries<Pick<T, "run-at">>;
}>(runAtMap: { [P in RunAtOption]?: T["run-at"]; } & Record<string, unknown>, runAt: T["run-at"]) => HeaderEntries<Pick<T, "run-at">>;
export declare const generateRequireHeaders: (requires: string[]) => HeaderEntries<{
require: string;
}>;
31 changes: 12 additions & 19 deletions dist/generators/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,37 @@ import validator from "validator";
import { uniquify } from "../utils/common.js";
import { explodePaths } from "../utils/urls.js";
export const generateGrantHeaders = (grantMap, grants) => {
if (grants.find((g) => g === "all")) {
if (grants.find(g => g === "all")) {
return Object.entries(grantMap).map(([, v]) => [
"grant",
v,
]);
}
const headers = grants.map((g) => ["grant", grantMap[g]]);
const headers = grants.map(g => ["grant", grantMap[g]]);
return headers.length
? headers
: [["grant", "none"]];
};
export const generateExcludeHeaders = (excludes) => {
return excludes.flatMap(explodePaths).map((uri) => ["exclude", uri]);
return excludes.flatMap(explodePaths).map(uri => ["exclude", uri]);
};
export const generateExcludeMatchHeaders = (excludes) => {
return excludes.flatMap(explodePaths).map((uri) => ["exclude-match", uri]);
return excludes.flatMap(explodePaths).map(uri => ["exclude-match", uri]);
};
export const generateMatchHeaders = async (matches, networkSiteScraper, collapse = true) => {
if (matches.includes("all")) {
const match = matches.find((m) => /domain/.test(m)) || "https://domain/*";
const sites = await networkSiteScraper();
if (matches.includes("meta")) {
const metaSites = sites.flatMap(({ site, ...rest }) => {
return collapse && /stackexchange/.test(site) || /stackapps/.test(site) ? [] : [{
...rest, site: site.replace(/^(.+?\.(?=.+\.)|)/, "$1meta.")
}];
});
sites.push(...metaSites);
}
const match = matches.find(m => m.includes("domain")) || "https://domain/*";
const sites = (await networkSiteScraper())
.filter(({ isMeta }) => matches.includes("meta") || !isMeta);
const all = sites.map(({ site }) => {
const domain = collapse && /stackexchange/.test(site)
const domain = collapse && site.includes("stackexchange")
? "*.stackexchange.com"
: site;
return match.replace("domain", domain);
});
return generateMatchHeaders(uniquify(all), networkSiteScraper);
}
return matches.flatMap(explodePaths).map((uri) => ["match", uri]);
return matches.flatMap(explodePaths).map(uri => ["match", uri]);
};
export const generateRunAtHeaders = (runAtMap, runAt) => {
const runsAt = runAtMap[runAt];
Expand All @@ -49,9 +42,9 @@ export const generateRunAtHeaders = (runAtMap, runAt) => {
};
export const generateRequireHeaders = (requires) => {
return requires
.filter((url) => validator.isURL(url, {
allow_protocol_relative_urls: true
.filter(url => validator.isURL(url, {
allow_protocol_relative_urls: true,
}))
.flatMap(explodePaths)
.map((url) => ["require", url]);
.map(url => ["require", url]);
};
2 changes: 1 addition & 1 deletion dist/generators/tampermonkey/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { scrapeNetworkSites } from "../../utils/scraper.js";
import { generateCommonHeaders } from "../common/index.js";
import { finalizeMonkeyHeaders } from "../common/monkey.js";
import { generateCustomHeaders } from "../custom.js";
import { generateExcludeHeaders, generateGrantHeaders, generateMatchHeaders, generateRequireHeaders, generateRunAtHeaders } from "../index.js";
import { generateExcludeHeaders, generateGrantHeaders, generateMatchHeaders, generateRequireHeaders, generateRunAtHeaders, } from "../index.js";
export const generateTampermonkeyHeaders = async (packageInfo, options) => {
const { collapse = false, custom = [], downloadURL, excludes = [], grants = [], homepage, matches = [], namespace, noframes = false, pretty = false, requires = [], run = "start", spaces, updateURL, whitelist = [], } = options;
const commonHeaders = generateCommonHeaders(packageInfo, { namespace, noframes, pretty });
Expand Down
2 changes: 1 addition & 1 deletion dist/generators/violentmonkey/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { scrapeNetworkSites } from "../../utils/scraper.js";
import { generateCommonHeaders } from "../common/index.js";
import { finalizeMonkeyHeaders } from "../common/monkey.js";
import { generateCustomHeaders } from "../custom.js";
import { generateExcludeMatchHeaders, generateGrantHeaders, generateMatchHeaders, generateRequireHeaders, generateRunAtHeaders } from "../index.js";
import { generateExcludeMatchHeaders, generateGrantHeaders, generateMatchHeaders, generateRequireHeaders, generateRunAtHeaders, } from "../index.js";
export const generateViolentmonkeyHeaders = async (packageInfo, options) => {
const { collapse = false, custom = [], downloadURL, excludes = [], grants = [], homepage, inject = "page", matches = [], namespace, noframes = false, pretty = false, requires = [], run = "start", spaces, } = options;
const commonHeaders = generateCommonHeaders(packageInfo, { namespace, noframes, pretty });
Expand Down
8 changes: 4 additions & 4 deletions dist/linters/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
export type LintOptions = {
export interface LintOptions {
fix?: boolean;
isHomepageAllowed?: boolean;
spaces?: number;
};
export type LintResult = {
}
export interface LintResult {
error: string;
headers: string;
};
}
export declare const lintHeaders: (metadataBlock: string, options?: LintOptions) => Promise<LintResult>;
11 changes: 6 additions & 5 deletions dist/linters/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
import { ESLint } from "eslint";
import { configs } from "eslint-plugin-userscripts";
import userscripts from "eslint-plugin-userscripts";
export const lintHeaders = async (metadataBlock, options = {}) => {
const { fix = false, isHomepageAllowed = false, spaces = 4 } = options;
const eslint = new ESLint({
baseConfig: {
plugins: ["userscripts"],
plugins: { userscripts },
rules: {
...configs.recommended.rules,
...userscripts.configs.recommended.rules,
"userscripts/align-attributes": ["error", spaces],
"userscripts/use-homepage-and-url": isHomepageAllowed ? "error" : "off",
"userscripts/filename-user": "off",
},
},
useEslintrc: false,
overrideConfigFile: true,
fix,
});
const results = await eslint.lintText(metadataBlock);
const [{ output }] = results;
const formatter = await eslint.loadFormatter("stylish");
return {
error: await formatter.format(results),
headers: fix && output ? output : metadataBlock
headers: fix && output ? output : metadataBlock,
};
};
2 changes: 1 addition & 1 deletion dist/utils/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const parseAuthor = (info) => {
const match = authorRegex.exec(info);
if (!match)
throw new Error(`unable to parse author field: ${info}`);
const [_full, name, email, url] = match;
const [, name, email, url] = match;
return {
name,
email,
Expand Down
4 changes: 2 additions & 2 deletions dist/utils/filesystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ export const replaceFileContent = async (pathlike, startOffset, endOffset, newCo
const { writeFile, readFile } = await import("fs/promises");
const original = await readFile(pathlike);
const update = Buffer.concat([
original.slice(0, startOffset),
original.subarray(0, startOffset),
Buffer.from(newContent),
original.slice(endOffset)
original.subarray(endOffset),
]);
return writeFile(pathlike, update);
};
Loading

0 comments on commit ffcf691

Please sign in to comment.