@seangalie/precast 0.0.0-stage → 0.2.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.
Files changed (104) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +202 -0
  3. package/README.md +274 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +3 -0
  6. package/dist/cli.d.ts +7 -0
  7. package/dist/cli.js +251 -0
  8. package/dist/collect.d.ts +17 -0
  9. package/dist/collect.js +143 -0
  10. package/dist/context.d.ts +38 -0
  11. package/dist/context.js +206 -0
  12. package/dist/errors.d.ts +8 -0
  13. package/dist/errors.js +8 -0
  14. package/dist/fnmatch.d.ts +9 -0
  15. package/dist/fnmatch.js +110 -0
  16. package/dist/generate.d.ts +23 -0
  17. package/dist/generate.js +76 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +7 -0
  20. package/dist/output-path.d.ts +30 -0
  21. package/dist/output-path.js +84 -0
  22. package/dist/platforms.d.ts +22 -0
  23. package/dist/platforms.js +81 -0
  24. package/dist/profiles.d.ts +23 -0
  25. package/dist/profiles.js +79 -0
  26. package/dist/prompts.d.ts +30 -0
  27. package/dist/prompts.js +103 -0
  28. package/dist/style.d.ts +14 -0
  29. package/dist/style.js +34 -0
  30. package/dist/tiers.d.ts +23 -0
  31. package/dist/tiers.js +96 -0
  32. package/package.json +44 -4
  33. package/platforms/forgejo/files/.forgejo/CODEOWNERS.tmpl +2 -0
  34. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/01_bug_report.yml.tmpl +83 -0
  35. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/02_feature_request.yml.tmpl +57 -0
  36. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/03_codebase_improvement.yml.tmpl +44 -0
  37. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/04_support_question.yml.tmpl +47 -0
  38. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/config.yml.tmpl +13 -0
  39. package/platforms/forgejo/files/.forgejo/PULL_REQUEST_TEMPLATE.md.tmpl +49 -0
  40. package/platforms/forgejo/files/.forgejo/SETUP.md.tmpl +65 -0
  41. package/platforms/forgejo/files/.forgejo/labels.yml.tmpl +99 -0
  42. package/platforms/forgejo/files/.forgejo/scripts/check-labels.sh.tmpl +91 -0
  43. package/platforms/forgejo/files/.forgejo/scripts/sync-labels.sh.tmpl +165 -0
  44. package/platforms/forgejo/files/.forgejo/workflows/labels.yml.tmpl +45 -0
  45. package/platforms/forgejo/files/.forgejo/workflows/lint.yml.tmpl +78 -0
  46. package/platforms/forgejo/files/.forgejo/workflows/pr-labels.yml.tmpl +51 -0
  47. package/platforms/forgejo/files/.forgejo/workflows/pre-commit.yml.tmpl +24 -0
  48. package/platforms/forgejo/files/.forgejo/workflows/release.yml.tmpl +130 -0
  49. package/platforms/forgejo/files/.forgejo/workflows/renovate.yml.tmpl +61 -0
  50. package/platforms/forgejo/files/.forgejo/workflows/stale.yml.tmpl +260 -0
  51. package/platforms/forgejo/files/renovate.json +36 -0
  52. package/platforms/forgejo/platform.json +41 -0
  53. package/platforms/github/files/.github/CODEOWNERS.tmpl +2 -0
  54. package/platforms/github/files/.github/ISSUE_TEMPLATE/01_bug_report.yml.tmpl +83 -0
  55. package/platforms/github/files/.github/ISSUE_TEMPLATE/02_feature_request.yml.tmpl +57 -0
  56. package/platforms/github/files/.github/ISSUE_TEMPLATE/03_codebase_improvement.yml.tmpl +44 -0
  57. package/platforms/github/files/.github/ISSUE_TEMPLATE/04_support_question.yml.tmpl +47 -0
  58. package/platforms/github/files/.github/ISSUE_TEMPLATE/config.yml.tmpl +16 -0
  59. package/platforms/github/files/.github/PULL_REQUEST_TEMPLATE.md.tmpl +49 -0
  60. package/platforms/github/files/.github/SETUP.md.tmpl +46 -0
  61. package/platforms/github/files/.github/dependabot.yml.tmpl +75 -0
  62. package/platforms/github/files/.github/labels.yml.tmpl +103 -0
  63. package/platforms/github/files/.github/release.yml.tmpl +47 -0
  64. package/platforms/github/files/.github/workflows/ci.yml.tmpl +55 -0
  65. package/platforms/github/files/.github/workflows/codeql.yml.tmpl +63 -0
  66. package/platforms/github/files/.github/workflows/labels.yml.tmpl +34 -0
  67. package/platforms/github/files/.github/workflows/lint-workflows.yml.tmpl +75 -0
  68. package/platforms/github/files/.github/workflows/lint.yml.tmpl +69 -0
  69. package/platforms/github/files/.github/workflows/lock.yml.tmpl +46 -0
  70. package/platforms/github/files/.github/workflows/pr-labels.yml.tmpl +26 -0
  71. package/platforms/github/files/.github/workflows/pre-commit.yml.tmpl +25 -0
  72. package/platforms/github/files/.github/workflows/release.yml.tmpl +101 -0
  73. package/platforms/github/files/.github/workflows/stale.yml.tmpl +57 -0
  74. package/platforms/github/platform.json +44 -0
  75. package/platforms/gitlab/files/.gitlab/CODEOWNERS.tmpl +2 -0
  76. package/platforms/gitlab/files/.gitlab/SETUP.md.tmpl +65 -0
  77. package/platforms/gitlab/files/.gitlab/issue_templates/01_bug_report.md +18 -0
  78. package/platforms/gitlab/files/.gitlab/issue_templates/02_feature_request.md +11 -0
  79. package/platforms/gitlab/files/.gitlab/issue_templates/03_codebase_improvement.md +11 -0
  80. package/platforms/gitlab/files/.gitlab/issue_templates/04_support_question.md +12 -0
  81. package/platforms/gitlab/files/.gitlab/labels.json +122 -0
  82. package/platforms/gitlab/files/.gitlab/merge_request_templates/Default.md +14 -0
  83. package/platforms/gitlab/files/.gitlab/scripts/project.py +159 -0
  84. package/platforms/gitlab/files/.gitlab-ci.yml.tmpl +56 -0
  85. package/platforms/gitlab/platform.json +38 -0
  86. package/template/.editorconfig.tmpl +54 -0
  87. package/template/.gitattributes +107 -0
  88. package/template/.gitignore.tmpl +244 -0
  89. package/template/.pre-commit-config.yaml.tmpl +55 -0
  90. package/template/.repo/check-secrets.py +40 -0
  91. package/template/.repo/ci-checks.sh +20 -0
  92. package/template/AGENTS.md.tmpl +78 -0
  93. package/template/CHANGELOG.md.tmpl +24 -0
  94. package/template/CLAUDE.md +1 -0
  95. package/template/LICENSE +202 -0
  96. package/template/README.md.tmpl +101 -0
  97. package/template/SETUP.md.tmpl +56 -0
  98. package/template/docs/CODE_OF_CONDUCT.md +85 -0
  99. package/template/docs/CONTRIBUTING.md.tmpl +59 -0
  100. package/template/docs/SECURITY.md.tmpl +26 -0
  101. package/template/docs/SUPPORT.md.tmpl +19 -0
  102. package/template/docs/logo.svg +84 -0
  103. package/template/docs/screenshot.png +0 -0
  104. package/tiers.json +10 -0
package/dist/cli.js ADDED
@@ -0,0 +1,251 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { DEFAULT_BRANCH, DEFAULT_DESCRIPTION } from "./context.js";
5
+ import { isSystemError, PrecastError } from "./errors.js";
6
+ import { generate, ROOT } from "./generate.js";
7
+ import { platformNames } from "./platforms.js";
8
+ import { defaultConfigPath, readProfile } from "./profiles.js";
9
+ import { Cancelled, promptForMissing, shellQuote, withTerminal, } from "./prompts.js";
10
+ import { header, paint } from "./style.js";
11
+ import { DEFAULT_TIER, isTier, TIERS } from "./tiers.js";
12
+ const OPTIONS = {
13
+ platform: { type: "string" },
14
+ namespace: { type: "string" },
15
+ repo: { type: "string" },
16
+ output: { type: "string" },
17
+ tier: { type: "string" },
18
+ "server-url": { type: "string" },
19
+ "project-name": { type: "string" },
20
+ author: { type: "string" },
21
+ description: { type: "string" },
22
+ "default-branch": { type: "string" },
23
+ codeowner: { type: "string" },
24
+ runner: { type: "string" },
25
+ profile: { type: "string" },
26
+ config: { type: "string" },
27
+ "dry-run": { type: "boolean" },
28
+ "no-input": { type: "boolean" },
29
+ help: { type: "boolean", short: "h" },
30
+ version: { type: "boolean", short: "v" },
31
+ };
32
+ function usage(root) {
33
+ return `Usage:
34
+ precast Ask for everything needed (at a terminal)
35
+ precast --platform <id> --namespace <owner> --repo <name> --output <dir> [options]
36
+ precast --profile <name> --repo <name> --output <dir> [options]
37
+
38
+ Render shared files and one platform's native files into a new project directory.
39
+
40
+ Required. At a terminal, Precast asks for any that are missing:
41
+ --platform <id> ${platformNames(root).join(", ")}
42
+ --namespace <owner> Owner, organization, or GitLab group/subgroup
43
+ --repo <name> Repository slug
44
+ --output <dir> New directory outside the Precast source directory
45
+
46
+ Optional. When Precast is asking, it also asks for these (defaults shown):
47
+ --tier <tier> ${TIERS.join(", ")}; each adds to the one before (default: ${DEFAULT_TIER})
48
+
49
+ Never asked; set these as options:
50
+ --project-name <name> Human-readable title; defaults to the repository slug
51
+ --author <name> Display name; defaults to the namespace
52
+ --description <text> Defaults to "${DEFAULT_DESCRIPTION}"
53
+ --default-branch <name> Defaults to ${DEFAULT_BRANCH}
54
+ --codeowner <@owner> Explicit @user or @namespace/team; omitted means a commented example
55
+ --server-url <url> Override the platform's default instance URL
56
+ --runner <label> Actions runner label or GitLab runner tag
57
+
58
+ Profiles (a profile can set everything above except the repository, output, and title):
59
+ --profile <name> Use saved settings, such as a self-hosted server; options given here win
60
+ --config <file> Settings file for --profile (default: ${defaultConfigPath()})
61
+
62
+ Other options:
63
+ --dry-run Validate and list files without writing
64
+ --no-input Never ask questions; report missing options instead
65
+ -h, --help Show this help
66
+ -v, --version Show the version
67
+ `;
68
+ }
69
+ /** Thrown for unusable command lines, which exit with status 2 like other CLIs. */
70
+ class UsageError extends Error {
71
+ }
72
+ const nodeTerminal = {
73
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
74
+ prompt: (use) => withTerminal(process.stdin, process.stdout, use),
75
+ };
76
+ export async function main(argv, root = ROOT, terminal = nodeTerminal) {
77
+ let values;
78
+ try {
79
+ values = parse(argv);
80
+ }
81
+ catch (error) {
82
+ return usageFailure(error);
83
+ }
84
+ if (values.help) {
85
+ process.stdout.write(usage(root));
86
+ return 0;
87
+ }
88
+ if (values.version) {
89
+ process.stdout.write(`${readVersion(root)}\n`);
90
+ return 0;
91
+ }
92
+ try {
93
+ let profile;
94
+ try {
95
+ // Compare with undefined so an empty `--profile=` is rejected, not ignored.
96
+ profile =
97
+ values.profile !== undefined
98
+ ? readProfile(values.config ?? defaultConfigPath(), values.profile)
99
+ : undefined;
100
+ }
101
+ catch (error) {
102
+ return failure(error);
103
+ }
104
+ let options;
105
+ let nextTime;
106
+ let tier;
107
+ try {
108
+ const required = merge(values, profile);
109
+ // Reject a bad platform or tier before asking anything about it.
110
+ checkChoices(required.platform, values.tier ?? profile?.tier, root);
111
+ const missing = missingNames(required);
112
+ if (missing.length > 0 && terminal.interactive && !values["no-input"]) {
113
+ process.stdout.write(header(readVersion(root)));
114
+ // A session that is already asking also offers the tier, unless one was chosen.
115
+ const askTier = (values.tier ?? profile?.tier) === undefined;
116
+ const answers = await terminal.prompt((ask) => promptForMissing(required, ask, (text) => process.stdout.write(text), root, {
117
+ askTier,
118
+ }));
119
+ // `--key=value` keeps a value such as `-draft` from reading as an option,
120
+ // and the new options go before any `--` that ended the original options.
121
+ const added = missing.map((name) => `--${name}=${answers[name]}`);
122
+ if (answers.tier !== undefined)
123
+ added.push(`--tier=${answers.tier}`);
124
+ tier = answers.tier;
125
+ const end = argv.indexOf("--");
126
+ const replay = end < 0 ? [...argv, ...added] : [...argv.slice(0, end), ...added, ...argv.slice(end)];
127
+ nextTime = `precast ${replay.map(shellQuote).join(" ")}`;
128
+ Object.assign(required, {
129
+ platform: answers.platform,
130
+ namespace: answers.namespace,
131
+ repo: answers.repo,
132
+ output: answers.output,
133
+ });
134
+ }
135
+ options = resolve(values, profile, required, root, tier);
136
+ }
137
+ catch (error) {
138
+ if (error instanceof Cancelled) {
139
+ process.stderr.write(`\n${error.message}\n`);
140
+ return 130;
141
+ }
142
+ return usageFailure(error);
143
+ }
144
+ const { destination, files } = generate(options, root);
145
+ const verb = options.dryRun ? "Would generate" : "Generated";
146
+ const lines = [
147
+ `${verb} ${files.length} files for ${options.platform} (${options.tier} tier): ${destination}`,
148
+ ];
149
+ if (options.dryRun) {
150
+ lines.push(...files.map((file) => ` ${file}`));
151
+ }
152
+ else {
153
+ lines.push("Review SETUP.md before creating the destination repository and pushing.");
154
+ }
155
+ if (nextTime) {
156
+ // A prompted session marks success and shows how to skip the questions.
157
+ // Only a prompted run is styled; complete commands print plain text.
158
+ lines[0] = `\n${paint("green", `✓ ${lines[0]}`)}`;
159
+ lines.push("", paint("dim", "Next time, run:"), ` ${paint("cyan", nextTime)}`);
160
+ }
161
+ process.stdout.write(`${lines.join("\n")}\n`);
162
+ return 0;
163
+ }
164
+ catch (error) {
165
+ return failure(error);
166
+ }
167
+ }
168
+ /** Report an expected failure without a stack trace; rethrow anything else. */
169
+ function failure(error) {
170
+ if (error instanceof PrecastError || isSystemError(error)) {
171
+ process.stderr.write(`error: ${error.message}\n`);
172
+ return 1;
173
+ }
174
+ throw error;
175
+ }
176
+ function usageFailure(error) {
177
+ if (error instanceof UsageError ||
178
+ (isSystemError(error) && error.code.startsWith("ERR_PARSE_ARGS"))) {
179
+ process.stderr.write(`error: ${error.message}\nRun precast --help for usage.\n`);
180
+ return 2;
181
+ }
182
+ throw error;
183
+ }
184
+ function parse(argv) {
185
+ const { values } = parseArgs({
186
+ args: argv,
187
+ options: OPTIONS,
188
+ strict: true,
189
+ allowPositionals: false,
190
+ });
191
+ if (values.config !== undefined && values.profile === undefined) {
192
+ throw new UsageError("--config only applies with --profile");
193
+ }
194
+ return values;
195
+ }
196
+ /** The required values from the command line and profile; options given explicitly win. */
197
+ function merge(values, profile) {
198
+ if (profile && values.platform !== undefined && values.platform !== profile.platform) {
199
+ throw new UsageError(`--platform ${values.platform} conflicts with profile ${values.profile}, which uses ${profile.platform}`);
200
+ }
201
+ return {
202
+ platform: values.platform ?? profile?.platform,
203
+ namespace: values.namespace ?? profile?.namespace,
204
+ repo: values.repo,
205
+ output: values.output,
206
+ };
207
+ }
208
+ function missingNames(required) {
209
+ return ["platform", "namespace", "repo", "output"].filter((name) => required[name] === undefined);
210
+ }
211
+ /** Validate the platform and tier and fill in the optional values. */
212
+ function resolve(values, profile, required, root, answeredTier) {
213
+ const missing = missingNames(required);
214
+ if (missing.length > 0) {
215
+ throw new UsageError(`missing required options: ${missing.map((name) => `--${name}`).join(", ")}`);
216
+ }
217
+ const tier = values.tier ?? profile?.tier ?? answeredTier ?? DEFAULT_TIER;
218
+ checkChoices(required.platform, tier, root);
219
+ if (!isTier(tier)) {
220
+ throw new Error("unreachable: checkChoices validates the tier");
221
+ }
222
+ return {
223
+ platform: required.platform,
224
+ namespace: required.namespace,
225
+ repo: required.repo,
226
+ output: required.output,
227
+ tier,
228
+ serverUrl: values["server-url"] ?? profile?.serverUrl,
229
+ projectName: values["project-name"],
230
+ author: values.author ?? profile?.author,
231
+ description: values.description ?? profile?.description,
232
+ defaultBranch: values["default-branch"] ?? profile?.defaultBranch,
233
+ codeowner: values.codeowner ?? profile?.codeowner,
234
+ runner: values.runner ?? profile?.runner,
235
+ dryRun: values["dry-run"],
236
+ };
237
+ }
238
+ /** Validate a platform and tier when they are known; either may still be missing. */
239
+ function checkChoices(platform, tier, root) {
240
+ const platforms = platformNames(root);
241
+ if (platform !== undefined && !platforms.includes(platform)) {
242
+ throw new UsageError(`--platform must be one of: ${platforms.join(", ")}`);
243
+ }
244
+ if (tier !== undefined && !isTier(tier)) {
245
+ throw new UsageError(`--tier must be one of: ${TIERS.join(", ")}`);
246
+ }
247
+ }
248
+ function readVersion(root) {
249
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
250
+ return manifest.version;
251
+ }
@@ -0,0 +1,17 @@
1
+ import { type Context } from "./context.ts";
2
+ import { type Tier } from "./tiers.ts";
3
+ export interface OutputFile {
4
+ data: Buffer;
5
+ /** Permission bits copied from the source file. */
6
+ mode: number;
7
+ }
8
+ /** Output files keyed by POSIX relative path, in source order. */
9
+ export type OutputFiles = Map<string, OutputFile>;
10
+ /**
11
+ * Render `template/` and the platform's `files/` for one tier. Every source is
12
+ * checked for collisions, even files the tier omits, so a smaller tier cannot
13
+ * hide one.
14
+ */
15
+ export declare function collectFiles(root: string, platformName: string, context: Context, tier?: Tier): OutputFiles;
16
+ /** Compare POSIX paths component by component, matching the dry-run listing order. */
17
+ export declare function comparePaths(left: string, right: string): number;
@@ -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,38 @@
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
+ /** Validate an owner, organization, or group path; only some platforms allow subgroups. */
20
+ export declare function checkNamespace(value: string, nestedAllowed: boolean): string;
21
+ /** Validate a repository slug. */
22
+ export declare function checkRepo(value: string): string;
23
+ export declare function makeContext(options: ContextOptions, platform: PlatformDescriptor): Context;
24
+ /** Reject empty values, control characters, and anything that would read as a template token. */
25
+ export declare function textValue(value: string | undefined, label: string): string;
26
+ /** Escape characters that Markdown would otherwise interpret in display text. */
27
+ export declare function markdown(value: string): string;
28
+ /** Percent-encode UTF-8 bytes outside unreserved characters and `safe`. */
29
+ export declare function quote(value: string, safe?: string): string;
30
+ /**
31
+ * Serialize a string as an ASCII YAML double-quoted scalar. JSON's escapes for
32
+ * quotes, backslashes, and control characters are also YAML escapes, but JSON
33
+ * writes characters outside the Basic Multilingual Plane as two surrogate
34
+ * escapes, which YAML parsers reject. Those become one `\UXXXXXXXX` escape.
35
+ */
36
+ export declare function yamlString(value: string): string;
37
+ /** Replace `{KEY}` with earlier context values; `{{` and `}}` are literal braces. */
38
+ export declare function formatValue(value: string, context: Context, key: string): string;
@@ -0,0 +1,206 @@
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
+ /** Validate an owner, organization, or group path; only some platforms allow subgroups. */
8
+ export function checkNamespace(value, nestedAllowed) {
9
+ const namespace = textValue(value, "Namespace");
10
+ const components = namespace.split("/");
11
+ if (!nestedAllowed && components.length !== 1) {
12
+ throw new PrecastError("This platform does not support nested namespaces");
13
+ }
14
+ for (const component of components) {
15
+ checkComponent(component);
16
+ }
17
+ return namespace;
18
+ }
19
+ /** Validate a repository slug. */
20
+ export function checkRepo(value) {
21
+ checkComponent(value);
22
+ return value;
23
+ }
24
+ function checkComponent(component) {
25
+ if (!COMPONENT.test(component) || component.endsWith(".git") || component.endsWith(".")) {
26
+ throw new PrecastError(`Invalid repository or namespace component: '${component}'`);
27
+ }
28
+ }
29
+ export function makeContext(options, platform) {
30
+ const namespace = checkNamespace(options.namespace, platform.nested_namespaces);
31
+ checkRepo(options.repo);
32
+ const server = serverUrl(options.serverUrl || platform.server_url);
33
+ const branch = defaultBranch(options.defaultBranch ?? DEFAULT_BRANCH);
34
+ const name = textValue(options.projectName || options.repo, "Project name");
35
+ const author = textValue(options.author || namespace, "Author");
36
+ const description = textValue(options.description ?? DEFAULT_DESCRIPTION, "Description");
37
+ const owner = options.codeowner;
38
+ if (owner && !CODEOWNER.test(owner)) {
39
+ throw new PrecastError("Code owner must be @username or @namespace/team");
40
+ }
41
+ const runner = options.runner ? textValue(options.runner, "Runner") : undefined;
42
+ const context = {
43
+ PLATFORM: options.platform,
44
+ SERVER_URL: server,
45
+ NAMESPACE: namespace,
46
+ REPO: options.repo,
47
+ REPO_URL: `${server}/${quote(namespace, "/")}/${quote(options.repo)}`,
48
+ NAMESPACE_URL: `${server}/${quote(namespace, "/")}`,
49
+ PROJECT_NAME: markdown(name),
50
+ AUTHOR: markdown(author),
51
+ DESCRIPTION: markdown(description),
52
+ DEFAULT_BRANCH: branch,
53
+ DEFAULT_BRANCH_YAML: yamlString(branch),
54
+ BRANCH_URL: quote(branch),
55
+ RUNNER_YAML: yamlString(runner ?? platform.runner),
56
+ RUNNER_TAGS_YAML: runner ? `[${yamlString(runner)}]` : "[]",
57
+ CODEOWNER: owner || "",
58
+ CODEOWNERS_RULE: owner
59
+ ? `${platform.codeowners_pattern} ${owner}`
60
+ : "# Set a user or team with access, then uncomment the example below.\n" +
61
+ `# ${platform.codeowners_pattern} @username-or-team`,
62
+ };
63
+ // Descriptor entries are ordered so later values can refer to earlier URLs.
64
+ const onDefaultServer = sameServer(server, platform.server_url);
65
+ for (const [key, value] of Object.entries(platform.context)) {
66
+ if (Object.hasOwn(context, key)) {
67
+ throw new PrecastError(`Platform descriptor overrides reserved context key: ${key}`);
68
+ }
69
+ const hosted = platform.default_server_context;
70
+ const chosen = onDefaultServer && hosted && Object.hasOwn(hosted, key) ? hosted[key] : value;
71
+ context[key] = formatValue(chosen, context, key);
72
+ }
73
+ return context;
74
+ }
75
+ /**
76
+ * Compare server URLs as the same origin and path: the URL parser lowercases
77
+ * the scheme and host and drops a default port, so `https://GitLab.com:443/`
78
+ * matches `https://gitlab.com`. Both URLs passed `serverUrl` first, but that
79
+ * check accepts some the URL parser rejects, such as an IPv6 address with a
80
+ * zone ID; such a server is never a hosted default, so it is not a match.
81
+ */
82
+ function sameServer(left, right) {
83
+ const normalize = (url) => {
84
+ const parsed = URL.parse(url);
85
+ return parsed && `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, "")}`;
86
+ };
87
+ const a = normalize(left);
88
+ return a !== null && a === normalize(right);
89
+ }
90
+ /** Reject empty values, control characters, and anything that would read as a template token. */
91
+ export function textValue(value, label) {
92
+ if (!value || [...value].some(isControl)) {
93
+ throw new PrecastError(`${label} must be nonempty and contain no control characters`);
94
+ }
95
+ if (new RegExp(TOKEN.source).test(value)) {
96
+ throw new PrecastError(`${label} must not contain template tokens`);
97
+ }
98
+ return value;
99
+ }
100
+ function isControl(char) {
101
+ const code = char.charCodeAt(0);
102
+ return code < 0x20 || code === 0x7f;
103
+ }
104
+ /** Escape characters that Markdown would otherwise interpret in display text. */
105
+ export function markdown(value) {
106
+ return value.replace(/([\\`*_{}[\]()<>#!|])/g, "\\$1");
107
+ }
108
+ function serverUrl(value) {
109
+ const invalid = () => new PrecastError("Server URL must be an HTTP(S) URL without credentials, query or fragment");
110
+ const parts = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)$/.exec(value);
111
+ if (!parts || /\s/.test(value) || /[\\<>"{}'`$]/.test(value)) {
112
+ throw invalid();
113
+ }
114
+ const [, scheme = "", authority = "", path = ""] = parts;
115
+ if (!["http", "https"].includes(scheme.toLowerCase()) || authority.includes("@")) {
116
+ throw invalid();
117
+ }
118
+ if (!/^(?:\/[A-Za-z0-9._~%/-]*)?$/.test(path)) {
119
+ throw invalid();
120
+ }
121
+ const host = /^(\[[^\]]*\]|[^:]*)(?::(.*))?$/.exec(authority);
122
+ const port = host?.[2];
123
+ if (!host?.[1] ||
124
+ (port !== undefined && port !== "" && !(/^\d+$/.test(port) && Number(port) <= 65535))) {
125
+ throw invalid();
126
+ }
127
+ const decoded = path.replace(/%([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
128
+ if (decoded.split("/").some((part) => part === "." || part === "..")) {
129
+ throw new PrecastError("Server URL must not contain dot path segments");
130
+ }
131
+ return value.replace(/\/+$/, "");
132
+ }
133
+ /** Apply the rules of `git check-ref-format` that matter for a branch name. */
134
+ function defaultBranch(value) {
135
+ const branch = textValue(value, "Default branch");
136
+ if (branch.startsWith("-") ||
137
+ branch.startsWith("/") ||
138
+ branch.endsWith("/") ||
139
+ branch.endsWith(".") ||
140
+ branch === "@" ||
141
+ branch.includes("..") ||
142
+ branch.includes("@{") ||
143
+ /[\s~^:?*[\\]/.test(branch) ||
144
+ branch.includes("//") ||
145
+ branch.split("/").some((part) => part.startsWith(".") || part.endsWith(".lock"))) {
146
+ throw new PrecastError(`Invalid default branch: '${branch}'`);
147
+ }
148
+ return branch;
149
+ }
150
+ /** Percent-encode UTF-8 bytes outside unreserved characters and `safe`. */
151
+ export function quote(value, safe = "") {
152
+ let result = "";
153
+ for (const byte of new TextEncoder().encode(value)) {
154
+ const char = String.fromCharCode(byte);
155
+ if (/[A-Za-z0-9_.~-]/.test(char) || (byte < 128 && safe.includes(char))) {
156
+ result += char;
157
+ }
158
+ else {
159
+ result += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
160
+ }
161
+ }
162
+ return result;
163
+ }
164
+ /**
165
+ * Serialize a string as an ASCII YAML double-quoted scalar. JSON's escapes for
166
+ * quotes, backslashes, and control characters are also YAML escapes, but JSON
167
+ * writes characters outside the Basic Multilingual Plane as two surrogate
168
+ * escapes, which YAML parsers reject. Those become one `\UXXXXXXXX` escape.
169
+ */
170
+ export function yamlString(value) {
171
+ let result = "";
172
+ for (const char of JSON.stringify(value)) {
173
+ const code = char.codePointAt(0) ?? 0;
174
+ if (code > 0xffff) {
175
+ result += `\\U${code.toString(16).padStart(8, "0")}`;
176
+ }
177
+ else if (code > 0x7f) {
178
+ result += `\\u${code.toString(16).padStart(4, "0")}`;
179
+ }
180
+ else {
181
+ result += char;
182
+ }
183
+ }
184
+ return result;
185
+ }
186
+ /** Replace `{KEY}` with earlier context values; `{{` and `}}` are literal braces. */
187
+ export function formatValue(value, context, key) {
188
+ return value.replace(/\{\{|\}\}|\{([^{}]*)\}|[{}]/g, (match, name) => {
189
+ if (match === "{{")
190
+ return "{";
191
+ if (match === "}}")
192
+ return "}";
193
+ if (name === undefined) {
194
+ throw new PrecastError(`Unmatched brace in platform context value ${key}`);
195
+ }
196
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
197
+ throw new PrecastError(`Platform context value ${key} has an invalid reference: {${name}}`);
198
+ }
199
+ // Own properties only: `{constructor}` must not find Object.prototype.
200
+ const replacement = Object.hasOwn(context, name) ? context[name] : undefined;
201
+ if (replacement === undefined) {
202
+ throw new PrecastError(`Platform context value ${key} refers to unknown key: ${name}`);
203
+ }
204
+ return replacement;
205
+ });
206
+ }
@@ -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
+ }