projectops 4.109.0 → 4.110.1

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.
@@ -1,35 +1,77 @@
1
- // Classify package.json content — substring matching on the raw file text.
2
- // Checks raw text rather than parsing dependencies (works even on broken JSON).
3
- // Input is the raw package.json string. Order matters.
4
- export function classifyPackageText(raw) {
5
- const s = String(raw || "");
6
- if (s.includes("@react-native") || s.includes("react-native")) {
7
- return s.includes("expo") ? "react-native-expo" : "react-native";
1
+ import { PROJECT_TYPES, typeById } from "./project-types.js";
2
+
3
+ // Types decided by package.json (registry entries with a package_json rule or fallback_only)
4
+ const PACKAGE_TYPES = PROJECT_TYPES.filter((type) => type.detect.package_json || type.detect.fallback_only);
5
+
6
+ // Dependency keys of a parsed package.json (dependencies + devDependencies; peer and optional are ignored)
7
+ function dependencyNames(packageJson) {
8
+ return Object.keys({ ...(packageJson?.dependencies || {}), ...(packageJson?.devDependencies || {}) });
9
+ }
10
+
11
+ // One registry package_json rule against a dependency name list
12
+ function matchesPackageRule(rule, names) {
13
+ const hasName = (name) => names.includes(name);
14
+ const hasPrefix = (prefix) => names.some((name) => name.startsWith(prefix));
15
+ if ((rule.requires_all || []).some((name) => !hasName(name))) return false;
16
+ const anyNames = rule.requires_any || [];
17
+ const anyPrefixes = rule.requires_any_prefix || [];
18
+ if ((anyNames.length || anyPrefixes.length) && !anyNames.some(hasName) && !anyPrefixes.some(hasPrefix)) return false;
19
+ if ((rule.excludes_any || []).some(hasName)) return false;
20
+ if ((rule.excludes_any_prefix || []).some(hasPrefix)) return false;
21
+ return true;
22
+ }
23
+
24
+ // Broken JSON: substring rule on the raw text, so detection never fails on a half-written file
25
+ function classifyBrokenPackageText(raw) {
26
+ if (raw.includes("@react-native") || raw.includes("react-native")) {
27
+ return raw.includes("expo") ? "react-native-expo" : "react-native";
8
28
  }
9
- // The next type was merged into react in v4.1.0 — a "next" dependency still classifies as react
10
- if (s.includes('"react"') || s.includes('"next"')) return "react";
29
+ if (raw.includes('"react"') || raw.includes('"next"')) return "react";
11
30
  return "node";
12
31
  }
13
32
 
33
+ /**
34
+ * Raw package.json text > package type id (registry dependency rules; fallback_only type when none match)
35
+ */
36
+ export function classifyPackageText(raw) {
37
+ const text = String(raw || "");
38
+ let packageJson;
39
+ try {
40
+ packageJson = JSON.parse(text);
41
+ } catch {
42
+ return classifyBrokenPackageText(text);
43
+ }
44
+ const names = dependencyNames(packageJson);
45
+ const matched = PACKAGE_TYPES.find((type) => type.detect.package_json && matchesPackageRule(type.detect.package_json, names));
46
+ return (matched || PACKAGE_TYPES.find((type) => type.detect.fallback_only)).id;
47
+ }
48
+
14
49
  // Convenience: for a parsed object, re-serialize to text and apply the rules above
15
50
  export function classifyPackageJson(pkgOrRaw) {
16
51
  const raw = typeof pkgOrRaw === "string" ? pkgOrRaw : JSON.stringify(pkgOrRaw || {});
17
52
  return classifyPackageText(raw);
18
53
  }
19
54
 
20
- // Marker scan (behavior spec §3.1). Injects has(relpath)=>bool. node is not added when another type exists.
21
- // Receives raw package.json via read(relpath)=>string|null and passes it to classifyPackageText.
55
+ /**
56
+ * Marker scan of one folder > type ids in registry order (["basic"] when nothing matches)
57
+ * has(relpath)=>bool, read(relpath)=>raw text|null. A fallback_only type counts only when nothing else matched.
58
+ */
22
59
  export function detectTypesFromMarkers({ has, read }) {
23
60
  const types = [];
24
- if (has("pubspec.yaml")) types.push("flutter");
25
- if (has("build.gradle") || has("build.gradle.kts") || has("pom.xml")) types.push("spring");
26
- if (has("pyproject.toml") || has("setup.py") || has("requirements.txt")) types.push("python");
27
- if (has("package.json")) {
28
- const cls = classifyPackageText(read ? read("package.json") : "");
29
- if (cls === "node") { if (types.length === 0) types.push("node"); }
30
- else types.push(cls);
61
+ let packageTypeId = null;
62
+ for (const type of PROJECT_TYPES) {
63
+ if (!type.detect.markers.some((marker) => has(marker))) continue;
64
+ if (type.detect.package_json || type.detect.fallback_only) {
65
+ // All package types share package.json: classify once, at the position of the first package type
66
+ if (packageTypeId === null) packageTypeId = classifyPackageText(read ? read("package.json") : "");
67
+ if (packageTypeId === type.id) types.push(type.id);
68
+ continue;
69
+ }
70
+ types.push(type.id);
31
71
  }
32
- return types.length ? [...new Set(types)] : ["basic"];
72
+ const fallbackIds = new Set(PROJECT_TYPES.filter((type) => type.detect.fallback_only).map((type) => type.id));
73
+ const result = types.length > 1 ? types.filter((id) => !fallbackIds.has(id)) : types;
74
+ return result.length ? [...new Set(result)] : ["basic"];
33
75
  }
34
76
 
35
77
  const VERSION_RE = /^\d+\.\d+\.\d+$/;
@@ -53,26 +95,24 @@ export function detectVersionFromFiles({ read, readJson, hasJq, gitTag }) {
53
95
  return "0.0.1";
54
96
  }
55
97
 
98
+ // Main marker file of a type for path display and search (first path_search file; package.json when the type has none)
56
99
  export function markerForType(type) {
57
- return { flutter: "pubspec.yaml", "react-native-expo": "app.json", python: "pyproject.toml", spring: "build.gradle" }[type] || "package.json";
100
+ return typeById(type)?.path_search.files[0] ?? "package.json";
58
101
  }
59
102
 
103
+ // Secondary marker files of a type (spring build.gradle.kts/pom.xml, python setup.py/requirements.txt)
60
104
  export function extraMarkers(type) {
61
- return { python: ["setup.py", "requirements.txt"], spring: ["build.gradle.kts", "pom.xml"] }[type] || [];
105
+ return typeById(type)?.path_search.files.slice(1) ?? [];
62
106
  }
63
107
 
64
108
  // Extension frequency scan recommendation (step 2 when there are no markers, #458).
65
109
  // Secondary recommendation used only when there are no markers at all (= basic fallback). files = pruned relative paths.
66
- // Thresholds: dart≥1→flutter, java+kt+gradle≥3→spring, tsx+jsx≥3→react, py≥3→python,
67
- // none of those and ts+js≥3→node. Returned in menu definition order.
110
+ // Thresholds come from registry detect.extensions; a fallback_only type is suggested only when nothing else is.
68
111
  export function suggestTypesByExtScan(files) {
69
- const count = (re) => files.filter((f) => re.test(f)).length;
70
- const found = new Set();
71
- if (count(/\.dart$/) >= 1) found.add("flutter");
72
- if (count(/\.java$/) + count(/\.kt$/) + count(/\.gradle$/) >= 3) found.add("spring");
73
- if (count(/\.tsx$/) + count(/\.jsx$/) >= 3) found.add("react");
74
- if (count(/\.py$/) >= 3) found.add("python");
75
- if (found.size === 0 && count(/\.ts$/) + count(/\.js$/) >= 3) found.add("node");
76
- const order = ["spring", "flutter", "react", "react-native", "react-native-expo", "node", "python"];
77
- return order.filter((t) => found.has(t));
112
+ const countMatches = (patterns) => patterns.reduce(
113
+ (total, pattern) => total + files.filter((file) => new RegExp(pattern).test(file)).length, 0);
114
+ const meetsThreshold = (type) => type.detect.extensions && countMatches(type.detect.extensions.patterns) >= type.detect.extensions.min_count;
115
+ const found = PROJECT_TYPES.filter((type) => !type.detect.fallback_only && meetsThreshold(type)).map((type) => type.id);
116
+ if (found.length) return found;
117
+ return PROJECT_TYPES.filter((type) => type.detect.fallback_only && meetsThreshold(type)).map((type) => type.id);
78
118
  }
@@ -17,10 +17,10 @@ const OWNED_SKILL_NAME = /^(pro|suh)-/;
17
17
  const SHARED_SCRIPTS_MARKER = join("common", "__init__.py");
18
18
  export const SHARED_SCRIPTS_DIR_NAME = "scripts";
19
19
  const PYTHON_CACHE_DIR_NAME = "__pycache__";
20
- // 3 top-level shared Python entries used only by repo maintainers: guide doc, troubleshooting index generator, extras copy sync (#988)
20
+ // Top-level shared entries used only by repo maintainers: guide doc, troubleshooting index generator, extras copy sync (#988), project type generator (#1244)
21
21
  // Why an exclude list, not an allow list: missing a new runtime module kills skills on import,
22
22
  // while missing a new dev file only ships one extra file. test/ide-home-install-e2e.test.js catches runtime entries landing here
23
- export const SHARED_SCRIPTS_DEV_ONLY = new Set(["README.md", "build_troubleshooting.py", "sync_extras.py"]);
23
+ export const SHARED_SCRIPTS_DEV_ONLY = new Set(["README.md", "build_troubleshooting.py", "sync_extras.py", "build_project_types.mjs"]);
24
24
 
25
25
  // Skill source: downloaded template (TEMP)/skills first, else local skills/
26
26
  export function resolveSkillsSrc(ctx = {}) {
@@ -13,6 +13,7 @@ import { t as msg } from "../i18n/index.js";
13
13
  import { parseTemplateOptions, inferIntent } from "./version-yml.js";
14
14
  import { branchStatus, createBranch, pushBranch } from "./git-branch.js";
15
15
  import { DEPLOY_TARGETS, PUBLISH_TARGETS, CHANGELOG_PROVIDERS, DEFAULT_CODE_REVIEW_CODERABBIT } from "./constants.js";
16
+ import { PROJECT_TYPES } from "./project-types.js";
16
17
 
17
18
  // Check the development (release) branch exists + offer to create it (#477) — interactive only.
18
19
  // If missing locally and missing (or unknown) on the remote, offer to create it from the default branch, then ask whether to push.
@@ -24,7 +25,12 @@ import { DEPLOY_TARGETS, PUBLISH_TARGETS, CHANGELOG_PROVIDERS, DEFAULT_CODE_REVI
24
25
  // Returns state (#715 — for recording non-interactive results): not-checked · not-a-repo · exists-local · exists-remote ·
25
26
  // declined · create-failed · push-declined · pushed · push-failed
26
27
  // isNonInteractive: blocks credential prompts in remote lookup and push (#988 — interactive unchanged)
27
- export async function ensureDeployBranch({ targetRoot = ".", deployBranch = "", defaultBranch = "", io = {}, say = () => {}, isNonInteractive = false }) {
28
+ // missingMessageKey · createInitialValue · pushInitialValue: the deploy branch (#1248) reuses this flow with its own
29
+ // notice and both answers defaulting to no (its first push runs the deploy workflows)
30
+ export async function ensureDeployBranch({
31
+ targetRoot = ".", deployBranch = "", defaultBranch = "", io = {}, say = () => {}, isNonInteractive = false,
32
+ missingMessageKey = "options.branch.missing", createInitialValue = true, pushInitialValue = true,
33
+ }) {
28
34
  if (!deployBranch || typeof io.confirm !== "function") return { created: false, pushed: false, ready: null, state: "not-checked" };
29
35
  const st = branchStatus(targetRoot, deployBranch, { isNonInteractive });
30
36
  if (!st.isRepo) return { created: false, pushed: false, ready: null, state: "not-a-repo" };
@@ -33,8 +39,8 @@ export async function ensureDeployBranch({ targetRoot = ".", deployBranch = "",
33
39
  say(msg("options.branch.remoteOnly", { branch: deployBranch }));
34
40
  return { created: false, pushed: false, ready: true, state: "exists-remote" };
35
41
  }
36
- say(msg("options.branch.missing", { branch: deployBranch, base: defaultBranch || msg("options.branch.baseFallback") }));
37
- const mk = await io.confirm({ message: msg("options.branch.createPrompt", { base: defaultBranch || msg("options.branch.currentFallback"), branch: deployBranch }), initialValue: true });
42
+ say(msg(missingMessageKey, { branch: deployBranch, base: defaultBranch || msg("options.branch.baseFallback") }));
43
+ const mk = await io.confirm({ message: msg("options.branch.createPrompt", { base: defaultBranch || msg("options.branch.currentFallback"), branch: deployBranch }), initialValue: createInitialValue });
38
44
  if (mk !== true) {
39
45
  say(msg("options.branch.skipped", { branch: deployBranch }));
40
46
  return { created: false, pushed: false, ready: false, state: "declined" };
@@ -45,7 +51,7 @@ export async function ensureDeployBranch({ targetRoot = ".", deployBranch = "",
45
51
  }
46
52
  say(msg("options.branch.created", { branch: deployBranch }));
47
53
  // #481 — name the branch in the push question (avoids "which branch is being pushed" confusion)
48
- const up = await io.confirm({ message: msg("options.branch.pushPrompt", { branch: deployBranch }), initialValue: true });
54
+ const up = await io.confirm({ message: msg("options.branch.pushPrompt", { branch: deployBranch }), initialValue: pushInitialValue });
49
55
  if (up !== true) return { created: true, pushed: false, ready: true, state: "push-declined" };
50
56
  if (pushBranch(targetRoot, deployBranch, { isNonInteractive })) {
51
57
  say(msg("options.branch.pushed", { branch: deployBranch }));
@@ -66,29 +72,12 @@ export { DEPLOY_TARGETS, PUBLISH_TARGETS, CHANGELOG_PROVIDERS };
66
72
  // (Play Store/TestFlight/Firebase, etc.) workflows in the type itself, so the server deploy axis does not
67
73
  // apply and there is no registry publish either. If only types with both axes empty are selected, the questions are skipped.
68
74
  // Server types keep all current choices (behavior unchanged — per-type refinement is follow-up work).
69
- export const TYPE_DEPLOY_TARGETS = {
70
- spring: ["docker-ssh", "vercel"],
71
- react: ["docker-ssh", "vercel"],
72
- node: ["docker-ssh", "vercel"],
73
- python: ["docker-ssh", "vercel"],
74
- flutter: [],
75
- "react-native": [],
76
- "react-native-expo": [],
77
- basic: [],
78
- };
79
- export const TYPE_PUBLISH_TARGETS = {
80
- spring: ["nexus", "npm", "github-packages"],
81
- react: ["nexus", "npm", "github-packages"],
82
- node: ["nexus", "npm", "github-packages"],
83
- python: ["nexus", "npm", "github-packages"],
84
- flutter: [],
85
- "react-native": [],
86
- "react-native-expo": [],
87
- basic: [],
88
- };
75
+ // Values come from the registry axes (src/core/project-types.json).
76
+ export const TYPE_DEPLOY_TARGETS = Object.fromEntries(PROJECT_TYPES.map((type) => [type.id, [...type.axes.deploy]]));
77
+ export const TYPE_PUBLISH_TARGETS = Object.fromEntries(PROJECT_TYPES.map((type) => [type.id, [...type.axes.publish]]));
89
78
 
90
79
  // Applicable targets = union over the selected types (#498). 'none' is always allowed, so it is left out of the list.
91
- // Undeclared types allow everything conservatively (question kept) — when adding a new type, add its declaration above too.
80
+ // Undeclared types allow everything conservatively (question kept); registered types always declare their axes.
92
81
  export function applicableTargets(types = []) {
93
82
  const deployAll = DEPLOY_TARGETS.filter((t) => t !== "none");
94
83
  return {
@@ -142,6 +131,30 @@ async function askOptionalWorkflow({ dir, icon, short, desc, current, force, tty
142
131
  return include;
143
132
  }
144
133
 
134
+ /**
135
+ * Deploy (trigger) branch question (#1248): explain the 3 branches > typed value > existence check (create only if asked)
136
+ * Default = current value, else the default branch. Answering the default branch means no separate deploy branch ("").
137
+ * Returns { deployTriggerBranch, deployTriggerBranchReady }
138
+ */
139
+ async function askDeployTriggerBranch({ targetRoot, defaultBranch, current, io, say }) {
140
+ say("");
141
+ say(msg("options.deployBranch.intro"));
142
+ say(msg("options.deployBranch.roles", { base: defaultBranch }));
143
+ say(msg("options.deployBranch.why", { base: defaultBranch }));
144
+ const ans = await io.text({ message: msg("options.deployBranch.prompt"), initialValue: current || defaultBranch });
145
+ const typed = (typeof ans === "string" && !isCancel(ans) && ans.trim()) ? ans.trim() : (current || defaultBranch);
146
+ if (typed === defaultBranch) {
147
+ say(msg("options.deployBranch.chosenDefault", { base: defaultBranch }));
148
+ return { deployTriggerBranch: "", deployTriggerBranchReady: null };
149
+ }
150
+ say(msg("options.deployBranch.chosen", { value: typed }));
151
+ const br = await ensureDeployBranch({
152
+ targetRoot, deployBranch: typed, defaultBranch, io, say,
153
+ missingMessageKey: "options.deployBranch.missing", createInitialValue: false, pushInitialValue: false,
154
+ });
155
+ return { deployTriggerBranch: typed, deployTriggerBranchReady: br.ready };
156
+ }
157
+
145
158
  // Axis keys of the option questions (#483 edit scope unit) — the edit menu re-asks one axis at a time.
146
159
  // intent (#485) is the project nature — re-asking it re-derives the deploy/publish axes.
147
160
  export const OPTION_AXES = ["intent", "deploy", "publish", "code-review", "changelog", "release-branch", "secret"];
@@ -155,7 +168,7 @@ const INTENT_ASKS_PUBLISH = { library: true, both: true, manual: true, app: fals
155
168
  // current: { deploy: string|null, publish: string[]|null, secretBackup: bool|null } — explicit CLI values
156
169
  // scope: null means all axes (initial integration, re-ask all). A Set/array limits forceAsk to those axes (#483 edit menu isolation).
157
170
  // Axes outside the scope keep current/saved values even with forceAsk and are not asked again.
158
- // Returns { deploy, publish, secretBackup, codeReviewCoderabbit, aiPrSummary, changelogProvider, changelogBaseUrl, deployBranch }
171
+ // Returns { deploy, publish, secretBackup, codeReviewCoderabbit, aiPrSummary, changelogProvider, changelogBaseUrl, deployBranch, deployTriggerBranch }
159
172
  export async function askAllOptionalWorkflows({
160
173
  tempDir, types = [], current = {}, targetRoot = ".",
161
174
  force = false, tty = true, io = {}, forceAsk = false, defaultBranch = "", scope = null,
@@ -174,6 +187,8 @@ export async function askAllOptionalWorkflows({
174
187
  let deployBranch = current.deployBranch ?? null; // #456 release PR head branch
175
188
  let deployBranchReady = null; // #490 — whether the branch was confirmed/created in this run (null = not checked)
176
189
  let deployBranchCreated = null; // #493 — whether the wizard created it in this run (for the guide record)
190
+ let deployTriggerBranch = current.deployTriggerBranch ?? null; // #1248 deploy branch ("" = the default branch)
191
+ let deployTriggerBranchReady = null; // #1248 — same meaning as deployBranchReady
177
192
  let intent = current.intent ?? null; // #485 project nature (app/library/both/none/manual)
178
193
 
179
194
  // Type combinations with both axes empty (#498 — basic alone, or a mobile app like flutter alone) have neither server deploy
@@ -208,6 +223,7 @@ export async function askAllOptionalWorkflows({
208
223
  if (changelogBaseUrl === null && saved.changelogBaseUrl !== null) changelogBaseUrl = saved.changelogBaseUrl;
209
224
  // #456 reuse the saved development branch
210
225
  if (deployBranch === null && saved.deployBranch != null) deployBranch = saved.deployBranch;
226
+ if (deployTriggerBranch === null && saved.deployTriggerBranch != null) deployTriggerBranch = saved.deployTriggerBranch;
211
227
  // #485 reuse the saved intent — if missing, infer it from saved deploy/publish (compat with old version.yml)
212
228
  if (intent === null) intent = saved.intent ?? inferIntent(saved.deploy, saved.publish);
213
229
  }
@@ -414,6 +430,9 @@ export async function askAllOptionalWorkflows({
414
430
  const br = await ensureDeployBranch({ targetRoot, deployBranch, defaultBranch, io, say });
415
431
  deployBranchReady = br.ready;
416
432
  deployBranchCreated = br.created;
433
+ // Deploy branch right after the development branch (#1248) — typed by the user, never created without asking
434
+ ({ deployTriggerBranch, deployTriggerBranchReady } = await askDeployTriggerBranch({
435
+ targetRoot, defaultBranch: base, current: deployTriggerBranch, io, say }));
417
436
  }
418
437
  }
419
438
 
@@ -439,6 +458,8 @@ export async function askAllOptionalWorkflows({
439
458
  deployBranch: deployBranch ?? "",
440
459
  deployBranchReady, // #490 — true = confirmed/created, false = declined/failed, null = not checked
441
460
  deployBranchCreated, // #493 — true = created by the wizard in this run, null = not checked
461
+ deployTriggerBranch: deployTriggerBranch ?? "", // #1248 — "" = deploys run on the default branch
462
+ deployTriggerBranchReady, // #1248 — null = not asked or not checked
442
463
 
443
464
  // #485 intent — settled value first, else inferred from the final deploy/publish (fixes basic and non-interactive paths)
444
465
  intent: intent ?? inferIntent(finalDeploy, finalPublish) ?? "manual",
@@ -194,13 +194,13 @@ export const FLAG_DETAILS = {
194
194
  },
195
195
  "--deploy-trigger-branch": {
196
196
  when: "Only if deploys must run from a branch other than the default branch (for example develop > main > deploy).",
197
- effect: "Writes metadata.template.options.deploy_trigger_branch and rewrites main to that branch in the deploy workflows only: push trigger, checkout ref, git pull, branch check. Version bump, README version, release notes and issue closing keep following the default branch. Create the branch yourself first.",
197
+ effect: "Writes metadata.template.options.deploy_trigger_branch and rewrites main to that branch in the deploy workflows only: push trigger, checkout ref, git pull, branch check. Version bump, README version, release notes and issue closing keep following the default branch. Written in every mode, including workflows. The branch is NOT created by this flag; if it is missing on origin, the run summary says so. The interactive wizard asks this right after the development branch.",
198
198
  omitted: "The deploy workflows follow the default branch, unchanged.",
199
199
  example: "npx projectops --mode workflows --force --deploy-trigger-branch deploy",
200
200
  },
201
201
  "--deploy-branch": {
202
202
  when: "Only if your development branch is not named develop.",
203
- effect: "Writes metadata.development_branch (and the old deploy_branch with the same value) and rewrites the branch name inside the installed workflows (release PR head, CI triggers, PR summary base). The branch is NOT created by this flag (use --create-development-branch).",
203
+ effect: "Writes metadata.development_branch (and the old deploy_branch with the same value) in every mode, including workflows, and rewrites the branch name inside the installed workflows (release PR head, CI triggers, PR summary base). Workflows you modified whose only difference is the branch name are updated too (original kept as .bak). The branch is NOT created by this flag (use --create-development-branch).",
204
204
  omitted: "develop.",
205
205
  example: "npx projectops --mode full --force --deploy-branch dev",
206
206
  caution: "Despite the name this is the development branch (head of the release PR), not the branch that deploys. The deploying branch is the repository default branch.",
@@ -10,6 +10,7 @@ import { existsSync, readdirSync } from "node:fs";
10
10
  import { join } from "node:path";
11
11
  import { t as msg } from "../i18n/index.js";
12
12
  import { markerForType as baseMarkerForType, extraMarkers } from "./detect.js";
13
+ import { PROJECT_TYPES, typeById } from "./project-types.js";
13
14
  import { normalizePath } from "../cli/args.js";
14
15
 
15
16
  // Cancel (ESC/Ctrl+C) is the CANCEL symbol — judged only by symbol identity, without importing ui (avoids a core→ui back reference)
@@ -17,9 +18,7 @@ const isCancel = (v) => typeof v === "symbol";
17
18
 
18
19
  // Main marker file name of a type.
19
20
  // detect.js returns package.json for unknown types by default — wrapped here so it becomes an empty string.
20
- const KNOWN_MARKER_TYPES = new Set([
21
- "flutter", "react", "node", "react-native", "react-native-expo", "python", "spring",
22
- ]);
21
+ const KNOWN_MARKER_TYPES = new Set(PROJECT_TYPES.filter((type) => type.path_search.files.length).map((type) => type.id));
23
22
  export function markerForType(type) {
24
23
  return KNOWN_MARKER_TYPES.has(type) ? baseMarkerForType(type) : "";
25
24
  }
@@ -64,10 +63,13 @@ function walkFindDirs(root, { prune, match, maxDepth = 3 }) {
64
63
  // Search marker file candidates per type.
65
64
  // Returns an array of candidate directory relative paths (root is ".").
66
65
  export function findTypePathCandidates(root, type) {
66
+ const search = typeById(type)?.path_search;
67
+ if (!search || !search.files.length) return [];
68
+
67
69
  // ── Spring multi-module: collapse to the settings.gradle(.kts) folder = module root ──
68
70
  // version_manager updates every build.gradle under that folder, so submodules are not expanded.
69
71
  // settings.gradle under android/ (Flutter/RN) is not spring, so prune it.
70
- if (type === "spring") {
72
+ if (search.gradle_settings_root) {
71
73
  const mm = walkFindDirs(root, {
72
74
  prune: new Set(["node_modules", ".git", "build", "dist", ".gradle", "android", "ios"]),
73
75
  match: (n) => n === "settings.gradle" || n === "settings.gradle.kts",
@@ -76,39 +78,22 @@ export function findTypePathCandidates(root, type) {
76
78
  // No settings.gradle → single module, fall back to build.gradle below
77
79
  }
78
80
 
79
- const namesByType = {
80
- flutter: ["pubspec.yaml"],
81
- react: ["package.json"], node: ["package.json"],
82
- "react-native": ["package.json"],
83
- "react-native-expo": ["app.json"],
84
- python: ["pyproject.toml", "setup.py", "requirements.txt"],
85
- spring: ["build.gradle", "build.gradle.kts", "pom.xml"],
86
- };
87
- const names = namesByType[type];
88
- if (!names) return [];
89
-
90
81
  const prune = new Set([
91
82
  "node_modules", ".git", "build", "dist", ".dart_tool", "android", "ios",
92
83
  ".gradle", "venv", ".venv", "__pycache__",
93
84
  ]);
94
85
  // If found by a higher-priority marker, use only that
95
86
  let found = [];
96
- for (const n of names) {
87
+ for (const n of search.files) {
97
88
  found = walkFindDirs(root, { prune, match: (name) => name === n });
98
89
  if (found.length) break;
99
90
  }
100
91
 
101
92
  return found.filter((d) => {
102
- if (type === "flutter") {
103
- // Exclude example/ + require lib/ alongside — avoids false hits
104
- if (d.includes("example")) return false;
105
- const libDir = d === "." ? join(root, "lib") : join(root, d, "lib");
106
- if (!existsSync(libDir)) return false;
107
- }
108
- if (type === "spring") {
109
- // Exclude false hits on android/build.gradle from Flutter/RN
110
- if (d.includes("android")) return false;
111
- }
93
+ // Exclude false hits: example apps (flutter), android/build.gradle of app projects (spring)
94
+ if ((search.exclude_parts || []).some((part) => d.includes(part))) return false;
95
+ // Required sibling folder (flutter lib/) — avoids false hits
96
+ if (search.require_dir && !existsSync(d === "." ? join(root, search.require_dir) : join(root, d, search.require_dir))) return false;
112
97
  return true;
113
98
  });
114
99
  }
@@ -0,0 +1,98 @@
1
+ // Project type registry (#1244): src/core/project-types.json is the only source of type facts.
2
+ // User repos and skills get generated copies (scripts/build_project_types.mjs); array order = detection and primary order.
3
+ import { readFileSync } from "node:fs";
4
+
5
+ // Allowed keys per level. Unknown keys are errors so a typo cannot silently do nothing
6
+ const ENTRY_KEYS = ["id", "label", "description", "detect", "path_search", "version", "axes", "is_app",
7
+ "launch_kinds", "root_resolver", "deploy_trigger_workflows"];
8
+ const DETECT_KEYS = ["markers", "package_json", "fallback_only", "extensions", "secondary"];
9
+ const PACKAGE_JSON_KEYS = ["requires_any", "requires_any_prefix", "requires_all", "excludes_any", "excludes_any_prefix"];
10
+ const EXTENSIONS_KEYS = ["patterns", "min_count"];
11
+ const PATH_SEARCH_KEYS = ["files", "require_dir", "exclude_parts", "gradle_settings_root"];
12
+ const VERSION_KEYS = ["format", "build_number", "display", "comment", "example"];
13
+ const AXES_KEYS = ["deploy", "publish"];
14
+ // Type id shape: lowercase words joined by hyphens (also the workflow folder name)
15
+ const TYPE_ID_PATTERN = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
16
+
17
+ // Keys of `value` not in `allowedKeys` > one problem line each
18
+ function unknownKeyProblems(value, allowedKeys, where) {
19
+ if (!value || typeof value !== "object" || Array.isArray(value)) return [`${where}: must be an object`];
20
+ return Object.keys(value).filter((key) => !allowedKeys.includes(key)).map((key) => `${where}: unknown field "${key}"`);
21
+ }
22
+
23
+ function isStringList(value) {
24
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
25
+ }
26
+
27
+ /**
28
+ * Registry entries > problem list (empty = valid): fields, required values, unique ids
29
+ */
30
+ export function validateRegistry(entries) {
31
+ if (!Array.isArray(entries) || entries.length === 0) return ["registry: must be a non-empty array"];
32
+ const problems = [];
33
+ const seenIds = new Set();
34
+ for (const [index, entry] of entries.entries()) {
35
+ const where = `type ${entry?.id ?? `#${index}`}`;
36
+ problems.push(...unknownKeyProblems(entry, ENTRY_KEYS, where));
37
+ if (!entry || typeof entry !== "object") continue;
38
+ // Required scalar fields
39
+ if (!TYPE_ID_PATTERN.test(entry.id ?? "")) problems.push(`${where}: id must be lowercase words joined by hyphens`);
40
+ if (seenIds.has(entry.id)) problems.push(`${where}: duplicate id`);
41
+ seenIds.add(entry.id);
42
+ for (const key of ["label", "description"]) {
43
+ if (typeof entry[key] !== "string" || !entry[key]) problems.push(`${where}: ${key} is required`);
44
+ }
45
+ if (typeof entry.is_app !== "boolean") problems.push(`${where}: is_app must be true or false`);
46
+ // @wizard auto:<name> resolver for the type folder (APP_ROOT), or null
47
+ if (entry.root_resolver !== null && !/^[a-z]+-root$/.test(entry.root_resolver ?? "")) {
48
+ problems.push(`${where}: root_resolver must be null or a name like "flutter-root"`);
49
+ }
50
+ for (const key of ["launch_kinds", "deploy_trigger_workflows"]) {
51
+ if (!isStringList(entry[key])) problems.push(`${where}: ${key} must be a list of strings`);
52
+ }
53
+ // Nested objects (detect, path_search, version, axes)
54
+ problems.push(...unknownKeyProblems(entry.detect, DETECT_KEYS, `${where}.detect`));
55
+ if (entry.detect && !isStringList(entry.detect.markers)) problems.push(`${where}.detect: markers must be a list of strings`);
56
+ if (entry.detect?.package_json !== undefined) {
57
+ problems.push(...unknownKeyProblems(entry.detect.package_json, PACKAGE_JSON_KEYS, `${where}.detect.package_json`));
58
+ }
59
+ if (entry.detect?.extensions !== undefined) {
60
+ problems.push(...unknownKeyProblems(entry.detect.extensions, EXTENSIONS_KEYS, `${where}.detect.extensions`));
61
+ }
62
+ problems.push(...unknownKeyProblems(entry.path_search, PATH_SEARCH_KEYS, `${where}.path_search`));
63
+ if (entry.path_search && !isStringList(entry.path_search.files)) problems.push(`${where}.path_search: files must be a list of strings`);
64
+ problems.push(...unknownKeyProblems(entry.version, VERSION_KEYS, `${where}.version`));
65
+ for (const key of ["display", "comment", "example"]) {
66
+ if (entry.version && typeof entry.version[key] !== "string") problems.push(`${where}.version: ${key} is required`);
67
+ }
68
+ problems.push(...unknownKeyProblems(entry.axes, AXES_KEYS, `${where}.axes`));
69
+ if (entry.axes && !(isStringList(entry.axes.deploy) && isStringList(entry.axes.publish))) {
70
+ problems.push(`${where}.axes: deploy and publish must be lists of strings`);
71
+ }
72
+ }
73
+ return problems;
74
+ }
75
+
76
+ /**
77
+ * src/core/project-types.json > validated, frozen entries (throws with every problem)
78
+ */
79
+ function loadRegistry() {
80
+ const entries = JSON.parse(readFileSync(new URL("./project-types.json", import.meta.url), "utf8"));
81
+ const problems = validateRegistry(entries);
82
+ if (problems.length) throw new Error(`project type registry is invalid:\n- ${problems.join("\n- ")}`);
83
+ return Object.freeze(entries.map((entry) => Object.freeze(entry)));
84
+ }
85
+
86
+ export const PROJECT_TYPES = loadRegistry();
87
+ export const VALID_TYPES = Object.freeze(PROJECT_TYPES.map((type) => type.id));
88
+
89
+ export function typeById(typeId) {
90
+ return PROJECT_TYPES.find((type) => type.id === typeId);
91
+ }
92
+
93
+ /**
94
+ * Push-to-deploy workflow file names owned by types (branch-sub.js adds the type-independent ones)
95
+ */
96
+ export function deployTriggerWorkflows() {
97
+ return PROJECT_TYPES.flatMap((type) => type.deploy_trigger_workflows);
98
+ }