@seangalie/precast 0.0.0-stage → 0.1.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/CHANGELOG.md +28 -0
- package/LICENSE +202 -0
- package/README.md +217 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +140 -0
- package/dist/collect.d.ts +17 -0
- package/dist/collect.js +143 -0
- package/dist/context.d.ts +32 -0
- package/dist/context.js +159 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +8 -0
- package/dist/fnmatch.d.ts +9 -0
- package/dist/fnmatch.js +110 -0
- package/dist/generate.d.ts +17 -0
- package/dist/generate.js +67 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/output-path.d.ts +30 -0
- package/dist/output-path.js +84 -0
- package/dist/platforms.d.ts +17 -0
- package/dist/platforms.js +62 -0
- package/dist/tiers.d.ts +23 -0
- package/dist/tiers.js +96 -0
- package/package.json +44 -4
- package/platforms/forgejo/files/.forgejo/CODEOWNERS.tmpl +2 -0
- package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/01_bug_report.yml.tmpl +83 -0
- package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/02_feature_request.yml.tmpl +57 -0
- package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/03_codebase_improvement.yml.tmpl +44 -0
- package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/04_support_question.yml.tmpl +47 -0
- package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/config.yml.tmpl +13 -0
- package/platforms/forgejo/files/.forgejo/PULL_REQUEST_TEMPLATE.md.tmpl +49 -0
- package/platforms/forgejo/files/.forgejo/SETUP.md.tmpl +61 -0
- package/platforms/forgejo/files/.forgejo/labels.yml.tmpl +99 -0
- package/platforms/forgejo/files/.forgejo/scripts/check-labels.sh.tmpl +91 -0
- package/platforms/forgejo/files/.forgejo/scripts/sync-labels.sh.tmpl +165 -0
- package/platforms/forgejo/files/.forgejo/workflows/labels.yml.tmpl +45 -0
- package/platforms/forgejo/files/.forgejo/workflows/lint.yml.tmpl +78 -0
- package/platforms/forgejo/files/.forgejo/workflows/pr-labels.yml.tmpl +51 -0
- package/platforms/forgejo/files/.forgejo/workflows/pre-commit.yml.tmpl +24 -0
- package/platforms/forgejo/files/.forgejo/workflows/release.yml.tmpl +130 -0
- package/platforms/forgejo/files/.forgejo/workflows/renovate.yml.tmpl +61 -0
- package/platforms/forgejo/files/.forgejo/workflows/stale.yml.tmpl +260 -0
- package/platforms/forgejo/files/renovate.json +36 -0
- package/platforms/forgejo/platform.json +41 -0
- package/platforms/github/files/.github/CODEOWNERS.tmpl +2 -0
- package/platforms/github/files/.github/ISSUE_TEMPLATE/01_bug_report.yml.tmpl +83 -0
- package/platforms/github/files/.github/ISSUE_TEMPLATE/02_feature_request.yml.tmpl +57 -0
- package/platforms/github/files/.github/ISSUE_TEMPLATE/03_codebase_improvement.yml.tmpl +44 -0
- package/platforms/github/files/.github/ISSUE_TEMPLATE/04_support_question.yml.tmpl +47 -0
- package/platforms/github/files/.github/ISSUE_TEMPLATE/config.yml.tmpl +16 -0
- package/platforms/github/files/.github/PULL_REQUEST_TEMPLATE.md.tmpl +49 -0
- package/platforms/github/files/.github/SETUP.md.tmpl +46 -0
- package/platforms/github/files/.github/dependabot.yml.tmpl +75 -0
- package/platforms/github/files/.github/labels.yml.tmpl +103 -0
- package/platforms/github/files/.github/release.yml.tmpl +47 -0
- package/platforms/github/files/.github/workflows/ci.yml.tmpl +55 -0
- package/platforms/github/files/.github/workflows/codeql.yml.tmpl +63 -0
- package/platforms/github/files/.github/workflows/labels.yml.tmpl +34 -0
- package/platforms/github/files/.github/workflows/lint-workflows.yml.tmpl +75 -0
- package/platforms/github/files/.github/workflows/lint.yml.tmpl +69 -0
- package/platforms/github/files/.github/workflows/lock.yml.tmpl +46 -0
- package/platforms/github/files/.github/workflows/pr-labels.yml.tmpl +26 -0
- package/platforms/github/files/.github/workflows/pre-commit.yml.tmpl +25 -0
- package/platforms/github/files/.github/workflows/release.yml.tmpl +101 -0
- package/platforms/github/files/.github/workflows/stale.yml.tmpl +57 -0
- package/platforms/github/platform.json +44 -0
- package/platforms/gitlab/files/.gitlab/CODEOWNERS.tmpl +2 -0
- package/platforms/gitlab/files/.gitlab/SETUP.md.tmpl +62 -0
- package/platforms/gitlab/files/.gitlab/issue_templates/01_bug_report.md +18 -0
- package/platforms/gitlab/files/.gitlab/issue_templates/02_feature_request.md +11 -0
- package/platforms/gitlab/files/.gitlab/issue_templates/03_codebase_improvement.md +11 -0
- package/platforms/gitlab/files/.gitlab/issue_templates/04_support_question.md +12 -0
- package/platforms/gitlab/files/.gitlab/labels.json +122 -0
- package/platforms/gitlab/files/.gitlab/merge_request_templates/Default.md +14 -0
- package/platforms/gitlab/files/.gitlab/scripts/project.py +159 -0
- package/platforms/gitlab/files/.gitlab-ci.yml.tmpl +54 -0
- package/platforms/gitlab/platform.json +34 -0
- package/template/.editorconfig.tmpl +54 -0
- package/template/.gitattributes +107 -0
- package/template/.gitignore.tmpl +244 -0
- package/template/.pre-commit-config.yaml.tmpl +43 -0
- package/template/.repo/check-secrets.py +40 -0
- package/template/.repo/ci-checks.sh +18 -0
- package/template/AGENTS.md.tmpl +75 -0
- package/template/CHANGELOG.md.tmpl +24 -0
- package/template/CLAUDE.md +1 -0
- package/template/LICENSE +202 -0
- package/template/README.md.tmpl +101 -0
- package/template/SETUP.md.tmpl +47 -0
- package/template/docs/CODE_OF_CONDUCT.md +85 -0
- package/template/docs/CONTRIBUTING.md.tmpl +54 -0
- package/template/docs/SECURITY.md.tmpl +26 -0
- package/template/docs/SUPPORT.md.tmpl +19 -0
- package/template/docs/logo.svg +84 -0
- package/template/docs/screenshot.png +0 -0
- package/tiers.json +10 -0
package/dist/collect.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { basename, join, posix, relative, sep } from "node:path";
|
|
3
|
+
import { TOKEN } from "./context.js";
|
|
4
|
+
import { PrecastError } from "./errors.js";
|
|
5
|
+
import { readJson, readRawPlatform } from "./platforms.js";
|
|
6
|
+
import { renderTierBlocks, tierIndex, tierPatterns } from "./tiers.js";
|
|
7
|
+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
8
|
+
/**
|
|
9
|
+
* Render `template/` and the platform's `files/` for one tier. Every source is
|
|
10
|
+
* checked for collisions, even files the tier omits, so a smaller tier cannot
|
|
11
|
+
* hide one.
|
|
12
|
+
*/
|
|
13
|
+
export function collectFiles(root, platformName, context, tier = "full") {
|
|
14
|
+
const files = new Map();
|
|
15
|
+
const seen = new Set();
|
|
16
|
+
const shared = join(root, "tiers.json");
|
|
17
|
+
const sources = [
|
|
18
|
+
[
|
|
19
|
+
join(root, "template"),
|
|
20
|
+
tierPatterns(existsSync(shared) ? readJson(shared) : {}, "tiers.json"),
|
|
21
|
+
],
|
|
22
|
+
[
|
|
23
|
+
join(root, "platforms", platformName, "files"),
|
|
24
|
+
tierPatterns(readRawPlatform(root, platformName).tiers, `${platformName} descriptor`),
|
|
25
|
+
],
|
|
26
|
+
];
|
|
27
|
+
for (const [sourceRoot, assigned] of sources) {
|
|
28
|
+
const unmatched = new Set(assigned.keys());
|
|
29
|
+
if (!existsSync(sourceRoot) || !statSync(sourceRoot).isDirectory()) {
|
|
30
|
+
throw new PrecastError(`Missing template directory: ${sourceRoot}`);
|
|
31
|
+
}
|
|
32
|
+
for (const source of walk(sourceRoot)) {
|
|
33
|
+
const parts = relative(sourceRoot, source).split(sep);
|
|
34
|
+
if (basename(source) === ".DS_Store" || parts.includes("__pycache__")) {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const stats = lstatSync(source);
|
|
38
|
+
if (stats.isSymbolicLink()) {
|
|
39
|
+
throw new PrecastError(`Symlinks are not supported in template sources: ${source}`);
|
|
40
|
+
}
|
|
41
|
+
if (!stats.isFile()) {
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const rendered = suffix(source) === ".tmpl";
|
|
45
|
+
let output = parts.join("/");
|
|
46
|
+
if (rendered) {
|
|
47
|
+
output = output.slice(0, -".tmpl".length);
|
|
48
|
+
}
|
|
49
|
+
if (output.split("/").includes(".git") || seen.has(output)) {
|
|
50
|
+
throw new PrecastError(`Reserved path or template collision: ${output}`);
|
|
51
|
+
}
|
|
52
|
+
seen.add(output);
|
|
53
|
+
const matches = [...assigned]
|
|
54
|
+
.filter(([, { regex }]) => regex.test(output))
|
|
55
|
+
.map(([pattern]) => pattern);
|
|
56
|
+
for (const pattern of matches) {
|
|
57
|
+
unmatched.delete(pattern);
|
|
58
|
+
}
|
|
59
|
+
const matchedTiers = new Set(matches.map((pattern) => assigned.get(pattern)?.tier));
|
|
60
|
+
if (matchedTiers.size > 1) {
|
|
61
|
+
throw new PrecastError(`Conflicting tier assignments for ${output}: ${matches.map((m) => `'${m}'`).join(", ")}`);
|
|
62
|
+
}
|
|
63
|
+
const first = matches[0] === undefined ? undefined : assigned.get(matches[0])?.tier;
|
|
64
|
+
if (first !== undefined && tierIndex(tier) < tierIndex(first)) {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
let data = readFileSync(source);
|
|
68
|
+
if (rendered) {
|
|
69
|
+
data = Buffer.from(render(data, tier, context, source), "utf8");
|
|
70
|
+
}
|
|
71
|
+
files.set(output, { data, mode: stats.mode & 0o777 });
|
|
72
|
+
}
|
|
73
|
+
// A stale entry would silently stop placing a renamed file in its tier.
|
|
74
|
+
if (unmatched.size > 0) {
|
|
75
|
+
const stale = [...unmatched].sort().map((pattern) => `'${pattern}'`);
|
|
76
|
+
throw new PrecastError(`Tier patterns match no files in ${sourceRoot}: ${stale.join(", ")}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// A file cannot also be the parent directory of another output file. Every
|
|
80
|
+
// source path is checked, not only this tier's, so a smaller tier cannot hide one.
|
|
81
|
+
for (const output of seen) {
|
|
82
|
+
for (let parent = posix.dirname(output); parent !== "."; parent = posix.dirname(parent)) {
|
|
83
|
+
if (seen.has(parent)) {
|
|
84
|
+
throw new PrecastError(`File/directory collision: ${output}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return files;
|
|
89
|
+
}
|
|
90
|
+
function render(data, tier, context, source) {
|
|
91
|
+
let text;
|
|
92
|
+
try {
|
|
93
|
+
text = decoder.decode(data);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new PrecastError(`Template source is not valid UTF-8: ${source}`);
|
|
97
|
+
}
|
|
98
|
+
// Blocks resolve before tokens, so user input can never open or close one.
|
|
99
|
+
// Replacement is a single pass, so substituted values are never re-read as tokens.
|
|
100
|
+
return renderTierBlocks(text, tier, source).replace(TOKEN, (_, key) => {
|
|
101
|
+
const value = Object.hasOwn(context, key) ? context[key] : undefined;
|
|
102
|
+
if (value === undefined) {
|
|
103
|
+
throw new PrecastError(`Unknown token ${key} in ${source}`);
|
|
104
|
+
}
|
|
105
|
+
return value;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* List every path below `directory` without following symlinks. Paths sort
|
|
110
|
+
* component by component, so a directory's contents follow it directly.
|
|
111
|
+
*/
|
|
112
|
+
function walk(directory) {
|
|
113
|
+
const result = [];
|
|
114
|
+
const names = readdirSync(directory).sort(compareNames);
|
|
115
|
+
for (const name of names) {
|
|
116
|
+
const path = join(directory, name);
|
|
117
|
+
result.push(path);
|
|
118
|
+
if (lstatSync(path).isDirectory()) {
|
|
119
|
+
result.push(...walk(path));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
function compareNames(left, right) {
|
|
125
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
126
|
+
}
|
|
127
|
+
/** Compare POSIX paths component by component, matching the dry-run listing order. */
|
|
128
|
+
export function comparePaths(left, right) {
|
|
129
|
+
const a = left.split("/");
|
|
130
|
+
const b = right.split("/");
|
|
131
|
+
for (let index = 0; index < Math.min(a.length, b.length); index++) {
|
|
132
|
+
const order = compareNames(a[index], b[index]);
|
|
133
|
+
if (order !== 0)
|
|
134
|
+
return order;
|
|
135
|
+
}
|
|
136
|
+
return a.length - b.length;
|
|
137
|
+
}
|
|
138
|
+
/** The final extension, ignoring a leading dot, as in `name.tmpl` but not `.tmpl`. */
|
|
139
|
+
function suffix(path) {
|
|
140
|
+
const name = basename(path);
|
|
141
|
+
const index = name.lastIndexOf(".");
|
|
142
|
+
return index > 0 && index < name.length - 1 ? name.slice(index) : "";
|
|
143
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { PlatformDescriptor } from "./platforms.ts";
|
|
2
|
+
export declare const TOKEN: RegExp;
|
|
3
|
+
export type Context = Record<string, string>;
|
|
4
|
+
/** User-supplied values; unset or empty optional values fall back to defaults. */
|
|
5
|
+
export interface ContextOptions {
|
|
6
|
+
platform: string;
|
|
7
|
+
namespace: string;
|
|
8
|
+
repo: string;
|
|
9
|
+
serverUrl?: string | undefined;
|
|
10
|
+
projectName?: string | undefined;
|
|
11
|
+
author?: string | undefined;
|
|
12
|
+
description?: string | undefined;
|
|
13
|
+
defaultBranch?: string | undefined;
|
|
14
|
+
codeowner?: string | undefined;
|
|
15
|
+
runner?: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
export declare const DEFAULT_DESCRIPTION = "Describe this project.";
|
|
18
|
+
export declare const DEFAULT_BRANCH = "main";
|
|
19
|
+
export declare function makeContext(options: ContextOptions, platform: PlatformDescriptor): Context;
|
|
20
|
+
/** Reject empty values, control characters, and anything that would read as a template token. */
|
|
21
|
+
export declare function textValue(value: string | undefined, label: string): string;
|
|
22
|
+
/** Escape characters that Markdown would otherwise interpret in display text. */
|
|
23
|
+
export declare function markdown(value: string): string;
|
|
24
|
+
/** Percent-encode UTF-8 bytes outside unreserved characters and `safe`. */
|
|
25
|
+
export declare function quote(value: string, safe?: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Serialize a string as JSON with non-ASCII characters escaped. The result is
|
|
28
|
+
* also a valid YAML scalar, and ASCII output stays readable in any editor.
|
|
29
|
+
*/
|
|
30
|
+
export declare function jsonAscii(value: string): string;
|
|
31
|
+
/** Replace `{KEY}` with earlier context values; `{{` and `}}` are literal braces. */
|
|
32
|
+
export declare function formatValue(value: string, context: Context, key: string): string;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { PrecastError } from "./errors.js";
|
|
2
|
+
export const TOKEN = /@@([A-Z][A-Z0-9_]*)@@/g;
|
|
3
|
+
export const DEFAULT_DESCRIPTION = "Describe this project.";
|
|
4
|
+
export const DEFAULT_BRANCH = "main";
|
|
5
|
+
const COMPONENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
|
|
6
|
+
const CODEOWNER = /^@[A-Za-z0-9_][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]*)*$/;
|
|
7
|
+
export function makeContext(options, platform) {
|
|
8
|
+
const namespace = textValue(options.namespace, "Namespace");
|
|
9
|
+
const components = namespace.split("/");
|
|
10
|
+
if (!platform.nested_namespaces && components.length !== 1) {
|
|
11
|
+
throw new PrecastError("This platform does not support nested namespaces");
|
|
12
|
+
}
|
|
13
|
+
for (const component of [...components, options.repo]) {
|
|
14
|
+
if (!COMPONENT.test(component) || component.endsWith(".git") || component.endsWith(".")) {
|
|
15
|
+
throw new PrecastError(`Invalid repository or namespace component: '${component}'`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const server = serverUrl(options.serverUrl || platform.server_url);
|
|
19
|
+
const branch = defaultBranch(options.defaultBranch ?? DEFAULT_BRANCH);
|
|
20
|
+
const name = textValue(options.projectName || options.repo, "Project name");
|
|
21
|
+
const author = textValue(options.author || namespace, "Author");
|
|
22
|
+
const description = textValue(options.description ?? DEFAULT_DESCRIPTION, "Description");
|
|
23
|
+
const owner = options.codeowner;
|
|
24
|
+
if (owner && !CODEOWNER.test(owner)) {
|
|
25
|
+
throw new PrecastError("Code owner must be @username or @namespace/team");
|
|
26
|
+
}
|
|
27
|
+
const runner = options.runner ? textValue(options.runner, "Runner") : undefined;
|
|
28
|
+
const context = {
|
|
29
|
+
PLATFORM: options.platform,
|
|
30
|
+
SERVER_URL: server,
|
|
31
|
+
NAMESPACE: namespace,
|
|
32
|
+
REPO: options.repo,
|
|
33
|
+
REPO_URL: `${server}/${quote(namespace, "/")}/${quote(options.repo)}`,
|
|
34
|
+
NAMESPACE_URL: `${server}/${quote(namespace, "/")}`,
|
|
35
|
+
PROJECT_NAME: markdown(name),
|
|
36
|
+
AUTHOR: markdown(author),
|
|
37
|
+
DESCRIPTION: markdown(description),
|
|
38
|
+
DEFAULT_BRANCH: branch,
|
|
39
|
+
DEFAULT_BRANCH_YAML: jsonAscii(branch),
|
|
40
|
+
BRANCH_URL: quote(branch),
|
|
41
|
+
RUNNER_YAML: jsonAscii(runner ?? platform.runner),
|
|
42
|
+
RUNNER_TAGS_YAML: runner ? `[${jsonAscii(runner)}]` : "[]",
|
|
43
|
+
CODEOWNER: owner || "",
|
|
44
|
+
CODEOWNERS_RULE: owner
|
|
45
|
+
? `${platform.codeowners_pattern} ${owner}`
|
|
46
|
+
: "# Set a user or team with access, then uncomment the example below.\n" +
|
|
47
|
+
`# ${platform.codeowners_pattern} @username-or-team`,
|
|
48
|
+
};
|
|
49
|
+
// Descriptor entries are ordered so later values can refer to earlier URLs.
|
|
50
|
+
for (const [key, value] of Object.entries(platform.context)) {
|
|
51
|
+
if (Object.hasOwn(context, key)) {
|
|
52
|
+
throw new PrecastError(`Platform descriptor overrides reserved context key: ${key}`);
|
|
53
|
+
}
|
|
54
|
+
context[key] = formatValue(value, context, key);
|
|
55
|
+
}
|
|
56
|
+
return context;
|
|
57
|
+
}
|
|
58
|
+
/** Reject empty values, control characters, and anything that would read as a template token. */
|
|
59
|
+
export function textValue(value, label) {
|
|
60
|
+
if (!value || [...value].some(isControl)) {
|
|
61
|
+
throw new PrecastError(`${label} must be nonempty and contain no control characters`);
|
|
62
|
+
}
|
|
63
|
+
if (new RegExp(TOKEN.source).test(value)) {
|
|
64
|
+
throw new PrecastError(`${label} must not contain template tokens`);
|
|
65
|
+
}
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
function isControl(char) {
|
|
69
|
+
const code = char.charCodeAt(0);
|
|
70
|
+
return code < 0x20 || code === 0x7f;
|
|
71
|
+
}
|
|
72
|
+
/** Escape characters that Markdown would otherwise interpret in display text. */
|
|
73
|
+
export function markdown(value) {
|
|
74
|
+
return value.replace(/([\\`*_{}[\]()<>#!|])/g, "\\$1");
|
|
75
|
+
}
|
|
76
|
+
function serverUrl(value) {
|
|
77
|
+
const invalid = () => new PrecastError("Server URL must be an HTTP(S) URL without credentials, query or fragment");
|
|
78
|
+
const parts = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)$/.exec(value);
|
|
79
|
+
if (!parts || /\s/.test(value) || /[\\<>"{}'`$]/.test(value)) {
|
|
80
|
+
throw invalid();
|
|
81
|
+
}
|
|
82
|
+
const [, scheme = "", authority = "", path = ""] = parts;
|
|
83
|
+
if (!["http", "https"].includes(scheme.toLowerCase()) || authority.includes("@")) {
|
|
84
|
+
throw invalid();
|
|
85
|
+
}
|
|
86
|
+
if (!/^(?:\/[A-Za-z0-9._~%/-]*)?$/.test(path)) {
|
|
87
|
+
throw invalid();
|
|
88
|
+
}
|
|
89
|
+
const host = /^(\[[^\]]*\]|[^:]*)(?::(.*))?$/.exec(authority);
|
|
90
|
+
const port = host?.[2];
|
|
91
|
+
if (!host?.[1] ||
|
|
92
|
+
(port !== undefined && port !== "" && !(/^\d+$/.test(port) && Number(port) <= 65535))) {
|
|
93
|
+
throw invalid();
|
|
94
|
+
}
|
|
95
|
+
const decoded = path.replace(/%([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
96
|
+
if (decoded.split("/").some((part) => part === "." || part === "..")) {
|
|
97
|
+
throw new PrecastError("Server URL must not contain dot path segments");
|
|
98
|
+
}
|
|
99
|
+
return value.replace(/\/+$/, "");
|
|
100
|
+
}
|
|
101
|
+
/** Apply the rules of `git check-ref-format` that matter for a branch name. */
|
|
102
|
+
function defaultBranch(value) {
|
|
103
|
+
const branch = textValue(value, "Default branch");
|
|
104
|
+
if (branch.startsWith("-") ||
|
|
105
|
+
branch.startsWith("/") ||
|
|
106
|
+
branch.endsWith("/") ||
|
|
107
|
+
branch.endsWith(".") ||
|
|
108
|
+
branch === "@" ||
|
|
109
|
+
branch.includes("..") ||
|
|
110
|
+
branch.includes("@{") ||
|
|
111
|
+
/[\s~^:?*[\\]/.test(branch) ||
|
|
112
|
+
branch.includes("//") ||
|
|
113
|
+
branch.split("/").some((part) => part.startsWith(".") || part.endsWith(".lock"))) {
|
|
114
|
+
throw new PrecastError(`Invalid default branch: '${branch}'`);
|
|
115
|
+
}
|
|
116
|
+
return branch;
|
|
117
|
+
}
|
|
118
|
+
/** Percent-encode UTF-8 bytes outside unreserved characters and `safe`. */
|
|
119
|
+
export function quote(value, safe = "") {
|
|
120
|
+
let result = "";
|
|
121
|
+
for (const byte of new TextEncoder().encode(value)) {
|
|
122
|
+
const char = String.fromCharCode(byte);
|
|
123
|
+
if (/[A-Za-z0-9_.~-]/.test(char) || (byte < 128 && safe.includes(char))) {
|
|
124
|
+
result += char;
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
result += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Serialize a string as JSON with non-ASCII characters escaped. The result is
|
|
134
|
+
* also a valid YAML scalar, and ASCII output stays readable in any editor.
|
|
135
|
+
*/
|
|
136
|
+
export function jsonAscii(value) {
|
|
137
|
+
return JSON.stringify(value).replace(/[\u0080-]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
138
|
+
}
|
|
139
|
+
/** Replace `{KEY}` with earlier context values; `{{` and `}}` are literal braces. */
|
|
140
|
+
export function formatValue(value, context, key) {
|
|
141
|
+
return value.replace(/\{\{|\}\}|\{([^{}]*)\}|[{}]/g, (match, name) => {
|
|
142
|
+
if (match === "{{")
|
|
143
|
+
return "{";
|
|
144
|
+
if (match === "}}")
|
|
145
|
+
return "}";
|
|
146
|
+
if (name === undefined) {
|
|
147
|
+
throw new PrecastError(`Unmatched brace in platform context value ${key}`);
|
|
148
|
+
}
|
|
149
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
150
|
+
throw new PrecastError(`Platform context value ${key} has an invalid reference: {${name}}`);
|
|
151
|
+
}
|
|
152
|
+
// Own properties only: `{constructor}` must not find Object.prototype.
|
|
153
|
+
const replacement = Object.hasOwn(context, name) ? context[name] : undefined;
|
|
154
|
+
if (replacement === undefined) {
|
|
155
|
+
throw new PrecastError(`Platform context value ${key} refers to unknown key: ${name}`);
|
|
156
|
+
}
|
|
157
|
+
return replacement;
|
|
158
|
+
});
|
|
159
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** An expected failure caused by input or template sources, reported without a stack trace. */
|
|
2
|
+
export declare class PrecastError extends Error {
|
|
3
|
+
name: string;
|
|
4
|
+
}
|
|
5
|
+
/** Node's file-system failures carry a string `code`, such as `EACCES`. */
|
|
6
|
+
export declare function isSystemError(error: unknown): error is NodeJS.ErrnoException & {
|
|
7
|
+
code: string;
|
|
8
|
+
};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** An expected failure caused by input or template sources, reported without a stack trace. */
|
|
2
|
+
export class PrecastError extends Error {
|
|
3
|
+
name = "PrecastError";
|
|
4
|
+
}
|
|
5
|
+
/** Node's file-system failures carry a string `code`, such as `EACCES`. */
|
|
6
|
+
export function isSystemError(error) {
|
|
7
|
+
return error instanceof Error && typeof error.code === "string";
|
|
8
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shell-style patterns with the semantics of Python's `fnmatch.fnmatchcase`,
|
|
3
|
+
* which the tier lists were written against: the pattern matches the whole
|
|
4
|
+
* path, `*` matches any characters including `/`, `?` matches one character,
|
|
5
|
+
* and `[...]` is a character class with `!` for negation.
|
|
6
|
+
*/
|
|
7
|
+
/** Translate a pattern to a regular expression; throws a `SyntaxError` if JavaScript rejects it. */
|
|
8
|
+
export declare function compilePattern(pattern: string): RegExp;
|
|
9
|
+
export declare function fnmatch(name: string, pattern: string): boolean;
|
package/dist/fnmatch.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shell-style patterns with the semantics of Python's `fnmatch.fnmatchcase`,
|
|
3
|
+
* which the tier lists were written against: the pattern matches the whole
|
|
4
|
+
* path, `*` matches any characters including `/`, `?` matches one character,
|
|
5
|
+
* and `[...]` is a character class with `!` for negation.
|
|
6
|
+
*/
|
|
7
|
+
const SYNTAX = new Set("^$\\.*+?()[]{}|/");
|
|
8
|
+
/** Translate a pattern to a regular expression; throws a `SyntaxError` if JavaScript rejects it. */
|
|
9
|
+
export function compilePattern(pattern) {
|
|
10
|
+
// Work in code points so `?` and ranges treat astral characters as one character.
|
|
11
|
+
const chars = [...pattern];
|
|
12
|
+
const length = chars.length;
|
|
13
|
+
let source = "";
|
|
14
|
+
let lastWasStar = false;
|
|
15
|
+
let index = 0;
|
|
16
|
+
while (index < length) {
|
|
17
|
+
const char = chars[index++];
|
|
18
|
+
if (char === "*") {
|
|
19
|
+
if (!lastWasStar)
|
|
20
|
+
source += ".*";
|
|
21
|
+
lastWasStar = true;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
lastWasStar = false;
|
|
25
|
+
if (char === "?") {
|
|
26
|
+
source += ".";
|
|
27
|
+
}
|
|
28
|
+
else if (char === "[") {
|
|
29
|
+
let end = index;
|
|
30
|
+
if (end < length && chars[end] === "!")
|
|
31
|
+
end++;
|
|
32
|
+
if (end < length && chars[end] === "]")
|
|
33
|
+
end++;
|
|
34
|
+
while (end < length && chars[end] !== "]")
|
|
35
|
+
end++;
|
|
36
|
+
if (end >= length) {
|
|
37
|
+
source += "\\[";
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
source += characterClass(chars.slice(index, end));
|
|
41
|
+
index = end + 1;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
source += SYNTAX.has(char) ? `\\${char}` : char;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return new RegExp(`^(?:${source})$`, "su");
|
|
49
|
+
}
|
|
50
|
+
/** Translate the contents of `[...]`, following Python's handling of ranges. */
|
|
51
|
+
function characterClass(stuff) {
|
|
52
|
+
let body;
|
|
53
|
+
if (!stuff.includes("-")) {
|
|
54
|
+
body = stuff.map(escapeInClass).join("");
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
// Split at range hyphens. A leading `!` or the first character can never
|
|
58
|
+
// start a range, so the search for hyphens starts after them.
|
|
59
|
+
const chunks = [];
|
|
60
|
+
let start = 0;
|
|
61
|
+
let search = stuff[0] === "!" ? 2 : 1;
|
|
62
|
+
for (;;) {
|
|
63
|
+
const hyphen = stuff.indexOf("-", search);
|
|
64
|
+
if (hyphen < 0)
|
|
65
|
+
break;
|
|
66
|
+
chunks.push(stuff.slice(start, hyphen));
|
|
67
|
+
start = hyphen + 1;
|
|
68
|
+
search = hyphen + 3;
|
|
69
|
+
}
|
|
70
|
+
const rest = stuff.slice(start);
|
|
71
|
+
if (rest.length > 0) {
|
|
72
|
+
chunks.push(rest);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
chunks.at(-1)?.push("-");
|
|
76
|
+
}
|
|
77
|
+
// Drop empty ranges such as `z-a`, which are invalid in a regular expression.
|
|
78
|
+
for (let k = chunks.length - 1; k > 0; k--) {
|
|
79
|
+
const before = chunks[k - 1];
|
|
80
|
+
const after = chunks[k];
|
|
81
|
+
const last = before.at(-1);
|
|
82
|
+
const first = after[0];
|
|
83
|
+
if (last !== undefined && first !== undefined && codePoint(last) > codePoint(first)) {
|
|
84
|
+
chunks[k - 1] = [...before.slice(0, -1), ...after.slice(1)];
|
|
85
|
+
chunks.splice(k, 1);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
body = chunks.map((chunk) => chunk.map(escapeInClass).join("")).join("-");
|
|
89
|
+
}
|
|
90
|
+
if (body === "") {
|
|
91
|
+
return "(?!)";
|
|
92
|
+
}
|
|
93
|
+
if (body === "!") {
|
|
94
|
+
return ".";
|
|
95
|
+
}
|
|
96
|
+
if (body.startsWith("!")) {
|
|
97
|
+
return `[^${body.slice(1)}]`;
|
|
98
|
+
}
|
|
99
|
+
return `[${body}]`;
|
|
100
|
+
}
|
|
101
|
+
function escapeInClass(char) {
|
|
102
|
+
// `^` only needs escaping first, but escaping it anywhere is harmless.
|
|
103
|
+
return "\\]^-[".includes(char) ? `\\${char}` : char;
|
|
104
|
+
}
|
|
105
|
+
function codePoint(char) {
|
|
106
|
+
return char.codePointAt(0) ?? 0;
|
|
107
|
+
}
|
|
108
|
+
export function fnmatch(name, pattern) {
|
|
109
|
+
return compilePattern(pattern).test(name);
|
|
110
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type ContextOptions } from "./context.ts";
|
|
2
|
+
import { type Tier } from "./tiers.ts";
|
|
3
|
+
/** The package root, which holds `template/`, `platforms/`, and `tiers.json`. */
|
|
4
|
+
export declare const ROOT: string;
|
|
5
|
+
export interface GenerateOptions extends ContextOptions {
|
|
6
|
+
/** A new directory outside the source root. */
|
|
7
|
+
output: string;
|
|
8
|
+
tier?: Tier | undefined;
|
|
9
|
+
/** Validate and list the files without writing anything. */
|
|
10
|
+
dryRun?: boolean | undefined;
|
|
11
|
+
}
|
|
12
|
+
export interface GenerateResult {
|
|
13
|
+
destination: string;
|
|
14
|
+
/** POSIX relative paths, sorted. */
|
|
15
|
+
files: string[];
|
|
16
|
+
}
|
|
17
|
+
export declare function generate(options: GenerateOptions, root?: string): GenerateResult;
|
package/dist/generate.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { collectFiles, comparePaths } from "./collect.js";
|
|
5
|
+
import { makeContext } from "./context.js";
|
|
6
|
+
import { PrecastError } from "./errors.js";
|
|
7
|
+
import { canonicalPath } from "./output-path.js";
|
|
8
|
+
import { readPlatform } from "./platforms.js";
|
|
9
|
+
import { DEFAULT_TIER } from "./tiers.js";
|
|
10
|
+
/** The package root, which holds `template/`, `platforms/`, and `tiers.json`. */
|
|
11
|
+
export const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url)));
|
|
12
|
+
export function generate(options, root = ROOT) {
|
|
13
|
+
const platform = readPlatform(root, options.platform);
|
|
14
|
+
const context = makeContext(options, platform);
|
|
15
|
+
const files = collectFiles(root, options.platform, context, options.tier ?? DEFAULT_TIER);
|
|
16
|
+
// The same canonical path is checked and written, so `..` after a symlink or a
|
|
17
|
+
// case-only alias of the source directory cannot slip past the checks.
|
|
18
|
+
const destination = canonicalPath(options.output);
|
|
19
|
+
if (exists(destination)) {
|
|
20
|
+
throw new PrecastError(`Output already exists; choose a new directory: ${destination}`);
|
|
21
|
+
}
|
|
22
|
+
if (isInside(destination, realpathSync.native(root))) {
|
|
23
|
+
throw new PrecastError("Output must be outside the Precast source directory");
|
|
24
|
+
}
|
|
25
|
+
const listing = [...files.keys()].sort(comparePaths);
|
|
26
|
+
if (options.dryRun) {
|
|
27
|
+
return { destination, files: listing };
|
|
28
|
+
}
|
|
29
|
+
const parent = dirname(destination);
|
|
30
|
+
mkdirSync(parent, { recursive: true });
|
|
31
|
+
// Stage every file before reserving the output directory. mkdir is exclusive,
|
|
32
|
+
// so a competing process cannot cause an existing repository to be replaced.
|
|
33
|
+
const staging = mkdtempSync(join(parent, ".precast-"));
|
|
34
|
+
try {
|
|
35
|
+
for (const [path, { data, mode }] of files) {
|
|
36
|
+
const target = join(staging, ...path.split("/"));
|
|
37
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
38
|
+
writeFileSync(target, data);
|
|
39
|
+
chmodSync(target, mode);
|
|
40
|
+
}
|
|
41
|
+
mkdirSync(destination);
|
|
42
|
+
for (const entry of readdirSync(staging)) {
|
|
43
|
+
renameSync(join(staging, entry), join(destination, entry));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
rmSync(staging, { recursive: true, force: true });
|
|
48
|
+
}
|
|
49
|
+
return { destination, files: listing };
|
|
50
|
+
}
|
|
51
|
+
/** True for anything at the path, including a dangling symlink. */
|
|
52
|
+
function exists(path) {
|
|
53
|
+
try {
|
|
54
|
+
lstatSync(path);
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error.code === "ENOENT") {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function isInside(path, directory) {
|
|
65
|
+
const offset = relative(directory, path);
|
|
66
|
+
return offset === "" || !(offset === ".." || offset.startsWith(`..${sep}`) || isAbsolute(offset));
|
|
67
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { collectFiles, type OutputFile, type OutputFiles } from "./collect.ts";
|
|
2
|
+
export { type Context, type ContextOptions, makeContext } from "./context.ts";
|
|
3
|
+
export { PrecastError } from "./errors.ts";
|
|
4
|
+
export { type GenerateOptions, type GenerateResult, generate, ROOT } from "./generate.ts";
|
|
5
|
+
export { type PlatformDescriptor, platformNames, readPlatform } from "./platforms.ts";
|
|
6
|
+
export { DEFAULT_TIER, TIERS, type Tier } from "./tiers.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { collectFiles } from "./collect.js";
|
|
2
|
+
export { makeContext } from "./context.js";
|
|
3
|
+
export { PrecastError } from "./errors.js";
|
|
4
|
+
export { generate, ROOT } from "./generate.js";
|
|
5
|
+
export { platformNames, readPlatform } from "./platforms.js";
|
|
6
|
+
export { DEFAULT_TIER, TIERS } from "./tiers.js";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type PlatformPath } from "node:path";
|
|
2
|
+
/** The path rules and file-system lookups `canonicalPath` depends on. */
|
|
3
|
+
export interface PathHost {
|
|
4
|
+
path: PlatformPath;
|
|
5
|
+
cwd(): string;
|
|
6
|
+
/** The working directory for a Windows drive such as `D:`; unused elsewhere. */
|
|
7
|
+
driveCwd(drive: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* The real path of an existing entry, or undefined when nothing is there.
|
|
10
|
+
* Throws `PrecastError` for an entry that exists but cannot be followed,
|
|
11
|
+
* such as a dangling or looping symlink.
|
|
12
|
+
*/
|
|
13
|
+
realpath(entry: string): string | undefined;
|
|
14
|
+
/** Whether an existing entry is a directory, following symlinks. */
|
|
15
|
+
isDirectory(entry: string): boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare const nodeHost: PathHost;
|
|
18
|
+
/**
|
|
19
|
+
* Resolve `output` the way the operating system would: each existing directory
|
|
20
|
+
* becomes its real path, with symlinks followed and letter case corrected,
|
|
21
|
+
* before the next `..` applies. Path normalization alone would apply `..` to
|
|
22
|
+
* a link's name instead. The final component stays as written, so a symlink
|
|
23
|
+
* there still counts as an existing output.
|
|
24
|
+
*
|
|
25
|
+
* Only the host's separators split the path, so a backslash is part of a name
|
|
26
|
+
* outside Windows, and the root (`/`, `C:\`, or `\\server\share\`) is never
|
|
27
|
+
* split. An existing file cannot be followed by more components, as the
|
|
28
|
+
* operating system would refuse it with ENOTDIR.
|
|
29
|
+
*/
|
|
30
|
+
export declare function canonicalPath(output: string, host?: PathHost): string;
|