Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(deployments): add framework detection endpoint (#58484)

Richard Solomoue4b908092662
diff --git a/products/deployments/backend/api/deployment_projects.py b/products/deployments/backend/api/deployment_projects.py
index 929297c1f4da..95c864ba18d5 100644
--- a/products/deployments/backend/api/deployment_projects.py
+++ b/products/deployments/backend/api/deployment_projects.py
@@ -21,6 +21,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
from posthog.models.integration import Integration
@@ -38,6 +39,7 @@ from ..serializers import (
DeploymentProjectWriteSerializer,
)
from ..services import provision_project
+from ..services.detection import PackageManager, detect_config
class DeploymentsAccessPermission(BasePermission):
@@ -121,6 +123,70 @@ def _resolve_repository_config(
)
+class DetectConfigRequestSerializer(serializers.Serializer):
+ """Inputs the `/detect/` endpoint needs to suggest a project config.
+
+ Decouples detection from any one git provider — callers fetch
+ `package.json` and the list of lockfiles however they like (GitHub
+ raw content via the team's existing integration, a temporary clone,
+ user-pasted JSON during early development) and pass them here.
+ """
+
+ package_json = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Parsed contents of the repo's `package.json`. Pass null or omit if the "
+ "repo doesn't have one — the response is then the plain-HTML fallback."
+ ),
+ )
+ lockfiles = serializers.ListField(
+ child=serializers.CharField(max_length=64),
+ required=False,
+ default=list,
+ help_text=(
+ "Filenames of package-manager lockfiles found in the repo root "
+ '(e.g. ["pnpm-lock.yaml"]). Used to pick the package manager.'
+ ),
+ )
+
+
+class DetectConfigResponseSerializer(serializers.Serializer):
+ """Suggested project config. Every field is overridable in the connect-repo UI.
+
+ `build_command`, `output_dir`, and `framework` map directly to the
+ `DeploymentProject` model fields. `package_manager`, `install_command`,
+ and `node_version` are informational hints — the model doesn't store
+ them today, but the UI can display them so the user knows what the
+ build worker will end up running.
+ """
+
+ package_manager = serializers.ChoiceField(
+ choices=[(m.value, m.value) for m in PackageManager],
+ help_text="Detected package manager from lockfile presence.",
+ )
+ install_command = serializers.CharField(
+ allow_blank=True,
+ help_text="Suggested install command, or empty when no install is needed.",
+ )
+ build_command = serializers.CharField(
+ allow_blank=True,
+ help_text="Suggested build command, or empty when no known framework matched.",
+ )
+ output_dir = serializers.CharField(help_text="Suggested output directory relative to repo root.")
+ node_version = serializers.CharField(
+ help_text="Suggested Node major version, parsed from `engines.node` or defaulted to 20.",
+ )
+ framework = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Detected framework hint (e.g. `nextjs`, `vite`, `astro`) to write into "
+ "`DeploymentProject.framework`. Null when no framework matched — leaving the "
+ "field null lets the build worker fall back to its own auto-detection."
+ ),
+ )
+
+
class DeploymentProjectRefreshResponseSerializer(serializers.Serializer):
"""Response shape for refreshing a deployment project's GitHub branch."""
@@ -329,6 +395,34 @@ class DeploymentProjectViewSet(
instance.save(update_fields=["deleted", "deleted_at", "updated_at"])
return Response(status=status.HTTP_204_NO_CONTENT)
+ @validated_request(
+ request_serializer=DetectConfigRequestSerializer,
+ responses={status.HTTP_200_OK: OpenApiResponse(response=DetectConfigResponseSerializer)},
+ summary="Suggest project config from a repo's package.json and lockfiles",
+ description=(
+ "Pure inspection — no git access, no DB writes. The connect-repo "
+ "UI calls this after fetching `package.json` (via the team's "
+ "GitHub integration) and uses the response to prefill the form."
+ ),
+ )
+ @action(detail=False, methods=["post"], pagination_class=None)
+ def detect(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ package_json = request.validated_data.get("package_json")
+ lockfiles = request.validated_data.get("lockfiles", [])
+ detected = detect_config(package_json, lockfiles)
+ return Response(
+ DetectConfigResponseSerializer(
+ {
+ "package_manager": detected.package_manager.value,
+ "install_command": detected.install_command,
+ "build_command": detected.build_command,
+ "output_dir": detected.output_dir,
+ "node_version": detected.node_version,
+ "framework": detected.framework,
+ }
+ ).data,
+ )
+
class DeploymentProjectActionResponseSerializer(serializers.Serializer):
"""Generic action response shape (e.g. for 502 on Cloudflare failure)."""
diff --git a/products/deployments/backend/services/detection.py b/products/deployments/backend/services/detection.py
new file mode 100644
index 000000000000..751a1aac91e3
--- /dev/null
+++ b/products/deployments/backend/services/detection.py
@@ -0,0 +1,226 @@
+"""Framework + package-manager detection for connected repositories.
+
+Pure inspection — no I/O, no DB. The caller fetches `package.json` and the
+list of present lockfiles from the repo root (via GitHub raw content, a
+temporary clone, or wherever) and hands them in; we return a suggested
+build configuration the UI can prefill.
+
+The detection table is the only place where framework signatures live;
+new frameworks land here as one entry rather than scattered specials in
+the build worker. Framework names match the free-text convention on
+`DeploymentProject.framework` (lowercase, no spaces, e.g. `nextjs`,
+`vite`, `astro`).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import Any
+
+
+class PackageManager(StrEnum):
+ NPM = "npm"
+ PNPM = "pnpm"
+ YARN = "yarn"
+ BUN = "bun"
+
+
+@dataclass(frozen=True)
+class DetectedConfig:
+ """Suggested config from a repo's `package.json` + lockfile presence.
+
+ `framework` is `None` when no signature matched — the UI should leave
+ `DeploymentProject.framework` null so the build worker falls back to
+ its own auto-detection. `install_command` and `node_version` are
+ informational; `DeploymentProject` doesn't store them today.
+ """
+
+ package_manager: PackageManager
+ install_command: str
+ build_command: str
+ output_dir: str
+ node_version: str
+ framework: str | None
+
+
+# (lockfile_name, package_manager) — order matters: if a repo has both a
+# pnpm lockfile and a leftover `package-lock.json`, pnpm wins because the
+# pnpm lockfile is the explicit signal a developer is using pnpm. npm is
+# the last-resort default because `package-lock.json` is what npm happily
+# generates on top of anything.
+#
+# Bun has two lockfile names in the wild: `bun.lockb` (binary, pre-1.2) and
+# `bun.lock` (text, 1.2+ default). Both are listed so a fresh Bun 1.2 repo
+# doesn't fall through to npm.
+_LOCKFILE_PRECEDENCE: tuple[tuple[str, PackageManager], ...] = (
+ ("bun.lock", PackageManager.BUN),
+ ("bun.lockb", PackageManager.BUN),
+ ("pnpm-lock.yaml", PackageManager.PNPM),
+ ("yarn.lock", PackageManager.YARN),
+ ("package-lock.json", PackageManager.NPM),
+)
+
+
+def detect_package_manager(lockfile_names: list[str]) -> PackageManager:
+ """Pick a package manager from the lockfiles present in the repo root."""
+ present = set(lockfile_names)
+ for lockfile, manager in _LOCKFILE_PRECEDENCE:
+ if lockfile in present:
+ return manager
+ return PackageManager.NPM
+
+
+def _install_command_for(manager: PackageManager) -> str:
+ return {
+ PackageManager.NPM: "npm ci",
+ PackageManager.PNPM: "pnpm install --frozen-lockfile",
+ PackageManager.YARN: "yarn install --frozen-lockfile",
+ PackageManager.BUN: "bun install --frozen-lockfile",
+ }[manager]
+
+
+def _build_invocation(manager: PackageManager, script: str) -> str:
+ """`<manager> run <script>` for all four — `npm run build`, `pnpm build`, etc."""
+ prefix = {
+ PackageManager.NPM: "npm run",
+ PackageManager.PNPM: "pnpm",
+ PackageManager.YARN: "yarn",
+ PackageManager.BUN: "bun run",
+ }[manager]
+ return f"{prefix} {script}"
+
+
+@dataclass(frozen=True)
+class _FrameworkSignature:
+ """Detection rule for one framework.
+
+ `dep_keys` is the set of dependencies that must *all* be present in the
+ union of `dependencies` + `devDependencies` for this framework to match.
+ First signature whose deps all match wins, so order in
+ `_FRAMEWORK_SIGNATURES` is significant — more specific frameworks
+ (Remix, SvelteKit, Nuxt) come before more general ones that share a
+ transitive dep (Vite, React).
+
+ `all()` (not `any()`): a repo carrying only `@remix-run/react` without
+ `@remix-run/node` is some downstream package's transitive dep, not a
+ Remix project. Picking Remix here would suggest the wrong build
+ command and break the user's deploy.
+ """
+
+ framework: str
+ dep_keys: tuple[str, ...]
+ build_script: str
+ output_dir: str
+
+
+_FRAMEWORK_SIGNATURES: tuple[_FrameworkSignature, ...] = (
+ _FrameworkSignature("nextjs", ("next",), "build", "out"),
+ _FrameworkSignature("remix", ("@remix-run/react", "@remix-run/node"), "build", "public"),
+ _FrameworkSignature("sveltekit", ("@sveltejs/kit",), "build", "build"),
+ _FrameworkSignature("nuxt", ("nuxt",), "generate", ".output/public"),
+ _FrameworkSignature("astro", ("astro",), "build", "dist"),
+ _FrameworkSignature("gatsby", ("gatsby",), "build", "public"),
+ _FrameworkSignature("eleventy", ("@11ty/eleventy",), "build", "_site"),
+ _FrameworkSignature("vite", ("vite",), "build", "dist"),
+ _FrameworkSignature("create-react-app", ("react-scripts",), "build", "build"),
+)
+
+
+def _collect_dependency_keys(package_json: dict[str, Any]) -> set[str]:
+ deps = package_json.get("dependencies") or {}
+ dev_deps = package_json.get("devDependencies") or {}
+ if not isinstance(deps, dict) or not isinstance(dev_deps, dict):
+ return set()
+ return set(deps.keys()) | set(dev_deps.keys())
+
+
+def _detect_framework_signature(package_json: dict[str, Any]) -> _FrameworkSignature | None:
+ all_deps = _collect_dependency_keys(package_json)
+ for signature in _FRAMEWORK_SIGNATURES:
+ if all(dep in all_deps for dep in signature.dep_keys):
+ return signature
+ return None
+
+
+def _detect_node_version(package_json: dict[str, Any]) -> str:
+ """Extract a Node major version from `engines.node`, falling back to "20".
+
+ `engines.node` is a semver range. We don't need to evaluate the range —
+ just pull the leading major number so we know which Node line to
+ install. "Doesn't pick the freshest patch" is fine; the build env can
+ decide that.
+ """
+ engines = package_json.get("engines") or {}
+ if not isinstance(engines, dict):
+ return "20"
+ node_constraint = engines.get("node")
+ if not isinstance(node_constraint, str):
+ return "20"
+ for char in node_constraint:
+ if char.isdigit():
+ return _read_leading_int(node_constraint[node_constraint.index(char) :])
+ return "20"
+
+
+def _read_leading_int(s: str) -> str:
+ digits: list[str] = []
+ for char in s:
+ if char.isdigit():
+ digits.append(char)
+ else:
+ break
+ return "".join(digits) or "20"
+
+
+def detect_config(
+ package_json: dict[str, Any] | None,
+ lockfile_names: list[str],
+) -> DetectedConfig:
+ """Suggest a config from a repo's `package.json` + lockfile presence.
+
+ `package_json=None` (or an empty dict) means "no package.json found" —
+ treated as a plain-HTML repo: no install, no build, serve the root.
+
+ The returned config is a suggestion; the user can override every field
+ in the connect-repo UI. Detection should never raise — bad inputs land
+ on the plain-HTML fallback so the connect flow can still complete and
+ the user fixes things in the form.
+ """
+ manager = detect_package_manager(lockfile_names)
+
+ if not package_json:
+ return DetectedConfig(
+ package_manager=manager,
+ install_command="",
+ build_command="",
+ output_dir=".",
+ node_version="20",
+ framework=None,
+ )
+
+ signature = _detect_framework_signature(package_json)
+ node_version = _detect_node_version(package_json)
+
+ if signature is None:
+ # `package.json` present but no known framework — leave the build
+ # command empty so the user has to fill it in. We return
+ # `framework=None` so the build worker's own auto-detection can
+ # have a go.
+ return DetectedConfig(
+ package_manager=manager,
+ install_command=_install_command_for(manager),
+ build_command="",
+ output_dir="dist",
+ node_version=node_version,
+ framework=None,
+ )
+
+ return DetectedConfig(
+ package_manager=manager,
+ install_command=_install_command_for(manager),
+ build_command=_build_invocation(manager, signature.build_script),
+ output_dir=signature.output_dir,
+ node_version=node_version,
+ framework=signature.framework,
+ )
diff --git a/products/deployments/backend/test/test_detect_endpoint.py b/products/deployments/backend/test/test_detect_endpoint.py
new file mode 100644
index 000000000000..c2ef5ccdfcc1
--- /dev/null
+++ b/products/deployments/backend/test/test_detect_endpoint.py
@@ -0,0 +1,79 @@
+"""HTTP-level tests for `POST /deployment_projects/detect/`."""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+
+
+class _BaseDetectTest(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self._flag_patcher = patch(
+ "products.deployments.backend.access.posthoganalytics.feature_enabled",
+ return_value=True,
+ )
+ self._flag_patcher.start()
+ self.addCleanup(self._flag_patcher.stop)
+
+ @property
+ def _detect_url(self) -> str:
+ return f"/api/projects/{self.team.id}/deployment_projects/detect/"
+
+
+class TestDetectEndpoint(_BaseDetectTest):
+ def test_returns_suggested_config_for_known_framework(self) -> None:
+ response = self.client.post(
+ self._detect_url,
+ data={
+ "package_json": {"dependencies": {"vite": "^5"}, "engines": {"node": ">=20"}},
+ "lockfiles": ["pnpm-lock.yaml"],
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ body = response.json()
+ self.assertEqual(body["framework"], "vite")
+ self.assertEqual(body["package_manager"], "pnpm")
+ self.assertEqual(body["install_command"], "pnpm install --frozen-lockfile")
+ self.assertEqual(body["build_command"], "pnpm build")
+ self.assertEqual(body["output_dir"], "dist")
+ self.assertEqual(body["node_version"], "20")
+
+ def test_plain_html_repo_returns_null_framework_and_empty_build(self) -> None:
+ # Real case — a static-site repo with no package.json. Endpoint must
+ # not 500 and must return `framework=None` so the UI saves null into
+ # `DeploymentProject.framework` rather than the literal string
+ # "plain", letting the build worker do its own thing.
+ response = self.client.post(
+ self._detect_url,
+ data={"lockfiles": []},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ body = response.json()
+ self.assertIsNone(body["framework"])
+ self.assertEqual(body["build_command"], "")
+ self.assertEqual(body["install_command"], "")
+ self.assertEqual(body["output_dir"], ".")
+
+
+class TestDetectEndpointFeatureFlag(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ # Separate class so this one *doesn't* force the flag on.
+ def test_returns_403_when_feature_flag_off(self) -> None:
+ with patch(
+ "products.deployments.backend.access.posthoganalytics.feature_enabled",
+ return_value=False,
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/detect/",
+ data={"lockfiles": []},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
diff --git a/products/deployments/backend/test/test_detection.py b/products/deployments/backend/test/test_detection.py
new file mode 100644
index 000000000000..fa6958284f9c
--- /dev/null
+++ b/products/deployments/backend/test/test_detection.py
@@ -0,0 +1,140 @@
+"""Pure-function tests for the framework + package-manager detector."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from products.deployments.backend.services.detection import PackageManager, detect_config, detect_package_manager
+
+
+ "lockfiles, expected",
+ [
+ (["package-lock.json"], PackageManager.NPM),
+ (["pnpm-lock.yaml"], PackageManager.PNPM),
+ (["yarn.lock"], PackageManager.YARN),
+ # Bun pre-1.2 — binary lockfile.
+ (["bun.lockb"], PackageManager.BUN),
+ # Bun 1.2+ — text lockfile is the new default and must not fall through to npm.
+ (["bun.lock"], PackageManager.BUN),
+ # Mid-upgrade repo with both Bun lockfiles still resolves to Bun.
+ (["bun.lock", "bun.lockb"], PackageManager.BUN),
+ # Bun wins over everything — explicit lockfile beats accidental siblings.
+ (["bun.lockb", "package-lock.json", "yarn.lock"], PackageManager.BUN),
+ (["bun.lock", "package-lock.json", "yarn.lock"], PackageManager.BUN),
+ # pnpm beats a leftover npm lockfile from before a migration.
+ (["pnpm-lock.yaml", "package-lock.json"], PackageManager.PNPM),
+ # Nothing recognisable → npm as the conservative default.
+ ([], PackageManager.NPM),
+ (["README.md", "Dockerfile"], PackageManager.NPM),
+ ],
+)
+def test_detect_package_manager(lockfiles: list[str], expected: PackageManager) -> None:
+ assert detect_package_manager(lockfiles) == expected
+
+
+ "deps, expected_framework, expected_build, expected_output",
+ [
+ ({"next": "^14"}, "nextjs", "npm run build", "out"),
+ ({"vite": "^5"}, "vite", "npm run build", "dist"),
+ ({"react-scripts": "5.0.0"}, "create-react-app", "npm run build", "build"),
+ ({"astro": "^4"}, "astro", "npm run build", "dist"),
+ ({"gatsby": "^5"}, "gatsby", "npm run build", "public"),
+ ({"@11ty/eleventy": "^2"}, "eleventy", "npm run build", "_site"),
+ ({"@remix-run/react": "^2", "@remix-run/node": "^2"}, "remix", "npm run build", "public"),
+ ({"@sveltejs/kit": "^2"}, "sveltekit", "npm run build", "build"),
+ ({"nuxt": "^3"}, "nuxt", "npm run generate", ".output/public"),
+ ],
+)
+def test_detect_framework_returns_expected_hint(
+ deps: dict[str, str],
+ expected_framework: str,
+ expected_build: str,
+ expected_output: str,
+) -> None:
+ result = detect_config({"dependencies": deps}, ["package-lock.json"])
+ assert result.framework == expected_framework
+ assert result.build_command == expected_build
+ assert result.output_dir == expected_output
+
+
+def test_detect_framework_respects_dev_dependencies() -> None:
+ # Most projects pin Vite in devDependencies rather than runtime deps.
+ result = detect_config({"devDependencies": {"vite": "^5"}}, ["pnpm-lock.yaml"])
+ assert result.framework == "vite"
+ assert result.build_command == "pnpm build"
+ assert result.install_command == "pnpm install --frozen-lockfile"
+
+
+def test_detect_framework_uses_first_matching_signature() -> None:
+ # Remix repos commonly carry React + Vite as transitive concerns; the
+ # Remix signature is checked first so it wins over Vite.
+ package_json = {"dependencies": {"@remix-run/react": "^2", "@remix-run/node": "^2", "vite": "^5"}}
+ result = detect_config(package_json, ["package-lock.json"])
+ assert result.framework == "remix"
+
+
+def test_remix_signature_requires_all_dep_keys_present() -> None:
+ # A repo carrying only `@remix-run/react` (as some downstream library's
+ # transitive concern) but no Remix runtime is not a Remix project. The
+ # signature must require *all* listed deps so we don't suggest a
+ # wrong build command that breaks the deploy.
+ package_json = {"dependencies": {"@remix-run/react": "^2", "vite": "^5"}}
+ result = detect_config(package_json, ["package-lock.json"])
+ assert result.framework == "vite"
+
+
+def test_no_package_json_means_null_framework_with_no_build() -> None:
+ # The connect-repo flow should still complete for a static-site repo
+ # that's literally just HTML — empty install/build, serve repo root,
+ # framework null so the build worker doesn't pretend a framework is in play.
+ result = detect_config(None, [])
+ assert result.framework is None
+ assert result.install_command == ""
+ assert result.build_command == ""
+ assert result.output_dir == "."
+
+
+def test_package_json_with_no_known_framework_leaves_build_empty() -> None:
+ # Detected the package manager, but nothing we recognise. Install deps
+ # but make the user fill in the build command — better than guessing
+ # `npm run build` and silently producing the wrong output. Framework
+ # stays null so the build worker can have its own go at detection.
+ result = detect_config({"dependencies": {"left-pad": "^1.3.0"}}, ["package-lock.json"])
+ assert result.framework is None
+ assert result.install_command == "npm ci"
+ assert result.build_command == ""
+
+
+ "engines, expected",
+ [
+ ({"node": ">=20"}, "20"),
+ ({"node": "^18.17.0"}, "18"),
+ ({"node": "22"}, "22"),
+ ({"node": "20.x"}, "20"),
+ ({}, "20"),
+ ],
+)
+def test_node_version_extracted_from_engines_with_default(
+ engines: dict[str, Any],
+ expected: str,
+) -> None:
+ package_json = {"engines": engines, "dependencies": {"vite": "^5"}}
+ result = detect_config(package_json, ["package-lock.json"])
+ assert result.node_version == expected
+
+
+def test_install_command_matches_package_manager() -> None:
+ for manager, lockfile, expected_install in [
+ (PackageManager.NPM, "package-lock.json", "npm ci"),
+ (PackageManager.PNPM, "pnpm-lock.yaml", "pnpm install --frozen-lockfile"),
+ (PackageManager.YARN, "yarn.lock", "yarn install --frozen-lockfile"),
+ (PackageManager.BUN, "bun.lockb", "bun install --frozen-lockfile"),
+ ]:
+ result = detect_config({"dependencies": {"vite": "^5"}}, [lockfile])
+ assert result.package_manager == manager
+ assert result.install_command == expected_install
diff --git a/products/deployments/frontend/generated/api.schemas.ts b/products/deployments/frontend/generated/api.schemas.ts
index 053a0b5090ee..b3ecb87b469a 100644
--- a/products/deployments/frontend/generated/api.schemas.ts
+++ b/products/deployments/frontend/generated/api.schemas.ts
@@ -468,6 +468,68 @@ export interface DeploymentProjectRefreshResponseApi {
commit_sha: string
}
+/**
+ * Inputs the `/detect/` endpoint needs to suggest a project config.
+
+Decouples detection from any one git provider — callers fetch
+`package.json` and the list of lockfiles however they like (GitHub
+raw content via the team's existing integration, a temporary clone,
+user-pasted JSON during early development) and pass them here.
+ */
+export interface DetectConfigRequestApi {
+ /** Parsed contents of the repo's `package.json`. Pass null or omit if the repo doesn't have one — the response is then the plain-HTML fallback. */
+ package_json?: unknown
+ /** Filenames of package-manager lockfiles found in the repo root (e.g. ["pnpm-lock.yaml"]). Used to pick the package manager. */
+ lockfiles?: string[]
+}
+
+/**
+ * * `npm` - npm
+ * `pnpm` - pnpm
+ * `yarn` - yarn
+ * `bun` - bun
+ */
+export type PackageManagerEnumApi = (typeof PackageManagerEnumApi)[keyof typeof PackageManagerEnumApi]
+
+export const PackageManagerEnumApi = {
+ Npm: 'npm',
+ Pnpm: 'pnpm',
+ Yarn: 'yarn',
+ Bun: 'bun',
+} as const
+
+/**
+ * Suggested project config. Every field is overridable in the connect-repo UI.
+
+`build_command`, `output_dir`, and `framework` map directly to the
+`DeploymentProject` model fields. `package_manager`, `install_command`,
+and `node_version` are informational hints — the model doesn't store
+them today, but the UI can display them so the user knows what the
+build worker will end up running.
+ */
+export interface DetectConfigResponseApi {
+ /** Detected package manager from lockfile presence.
+
+ * `npm` - npm
+ * `pnpm` - pnpm
+ * `yarn` - yarn
+ * `bun` - bun */
+ package_manager: PackageManagerEnumApi
+ /** Suggested install command, or empty when no install is needed. */
+ install_command: string
+ /** Suggested build command, or empty when no known framework matched. */
+ build_command: string
+ /** Suggested output directory relative to repo root. */
+ output_dir: string
+ /** Suggested Node major version, parsed from `engines.node` or defaulted to 20. */
+ node_version: string
+ /**
+ * Detected framework hint (e.g. `nextjs`, `vite`, `astro`) to write into `DeploymentProject.framework`. Null when no framework matched — leaving the field null lets the build worker fall back to its own auto-detection.
+ * @nullable
+ */
+ framework: string | null
+}
+
export type DeploymentProjectsListParams = {
/**
* Number of results to return per page.
diff --git a/products/deployments/frontend/generated/api.ts b/products/deployments/frontend/generated/api.ts
index a8e260a48d76..988006ea8ac4 100644
--- a/products/deployments/frontend/generated/api.ts
+++ b/products/deployments/frontend/generated/api.ts
@@ -19,6 +19,8 @@ import type {
DeploymentProjectsDeploymentsEventsListParams,
DeploymentProjectsDeploymentsListParams,
DeploymentProjectsListParams,
+ DetectConfigRequestApi,
+ DetectConfigResponseApi,
PaginatedDeploymentEventListApi,
PaginatedDeploymentListApi,
PaginatedDeploymentProjectListApi,
@@ -503,3 +505,24 @@ export const deploymentProjectsRefreshCreate = async (
method: 'POST',
})
}
+
+export const getDeploymentProjectsDetectCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/deployment_projects/detect/`
+}
+
+/**
+ * Pure inspection — no git access, no DB writes. The connect-repo UI calls this after fetching `package.json` (via the team's GitHub integration) and uses the response to prefill the form.
+ * @summary Suggest project config from a repo's package.json and lockfiles
+ */
+export const deploymentProjectsDetectCreate = async (
+ projectId: string,
+ detectConfigRequestApi?: DetectConfigRequestApi,
+ options?: RequestInit
+): Promise<DetectConfigResponseApi> => {
+ return apiMutator<DetectConfigResponseApi>(getDeploymentProjectsDetectCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(detectConfigRequestApi),
+ })
+}
diff --git a/products/deployments/frontend/generated/api.zod.ts b/products/deployments/frontend/generated/api.zod.ts
index b6bee138ef63..719ec1a68d84 100644
--- a/products/deployments/frontend/generated/api.zod.ts
+++ b/products/deployments/frontend/generated/api.zod.ts
@@ -246,3 +246,28 @@ export const DeploymentProjectsPartialUpdateBody = /* @__PURE__ */ zod.object({
'If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them.'
),
})
+
+/**
+ * Pure inspection — no git access, no DB writes. The connect-repo UI calls this after fetching `package.json` (via the team's GitHub integration) and uses the response to prefill the form.
+ * @summary Suggest project config from a repo's package.json and lockfiles
+ */
+export const deploymentProjectsDetectCreateBodyLockfilesItemMax = 64
+
+export const DeploymentProjectsDetectCreateBody = /* @__PURE__ */ zod
+ .object({
+ package_json: zod
+ .unknown()
+ .optional()
+ .describe(
+ "Parsed contents of the repo's `package.json`. Pass null or omit if the repo doesn't have one — the response is then the plain-HTML fallback."
+ ),
+ lockfiles: zod
+ .array(zod.string().max(deploymentProjectsDetectCreateBodyLockfilesItemMax))
+ .optional()
+ .describe(
+ 'Filenames of package-manager lockfiles found in the repo root (e.g. [\"pnpm-lock.yaml\"]). Used to pick the package manager.'
+ ),
+ })
+ .describe(
+ "Inputs the `\/detect\/` endpoint needs to suggest a project config.\n\nDecouples detection from any one git provider — callers fetch\n`package.json` and the list of lockfiles however they like (GitHub\nraw content via the team's existing integration, a temporary clone,\nuser-pasted JSON during early development) and pass them here."
+ )
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ae915671a005..b4201f9e6384 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12307,6 +12307,69 @@ export namespace Schemas {
readonly updated_at: string;
}
+ /**
+ * Inputs the `/detect/` endpoint needs to suggest a project config.
+
+ Decouples detection from any one git provider — callers fetch
+ `package.json` and the list of lockfiles however they like (GitHub
+ raw content via the team's existing integration, a temporary clone,
+ user-pasted JSON during early development) and pass them here.
+ */
+ export interface DetectConfigRequest {
+ /** Parsed contents of the repo's `package.json`. Pass null or omit if the repo doesn't have one — the response is then the plain-HTML fallback. */
+ package_json?: unknown;
+ /** Filenames of package-manager lockfiles found in the repo root (e.g. ["pnpm-lock.yaml"]). Used to pick the package manager. */
+ lockfiles?: string[];
+ }
+
+ /**
+ * * `npm` - npm
+ * `pnpm` - pnpm
+ * `yarn` - yarn
+ * `bun` - bun
+ */
+ export type PackageManagerEnum = typeof PackageManagerEnum[keyof typeof PackageManagerEnum];
+
+
+ export const PackageManagerEnum = {
+ Npm: 'npm',
+ Pnpm: 'pnpm',
+ Yarn: 'yarn',
+ Bun: 'bun',
+ } as const;
+
+ /**
+ * Suggested project config. Every field is overridable in the connect-repo UI.
+
+ `build_command`, `output_dir`, and `framework` map directly to the
+ `DeploymentProject` model fields. `package_manager`, `install_command`,
+ and `node_version` are informational hints — the model doesn't store
+ them today, but the UI can display them so the user knows what the
+ build worker will end up running.
+ */
+ export interface DetectConfigResponse {
+ /** Detected package manager from lockfile presence.
+
+ * `npm` - npm
+ * `pnpm` - pnpm
+ * `yarn` - yarn
+ * `bun` - bun */
+ package_manager: PackageManagerEnum;
+ /** Suggested install command, or empty when no install is needed. */
+ install_command: string;
+ /** Suggested build command, or empty when no known framework matched. */
+ build_command: string;
+ /** Suggested output directory relative to repo root. */
+ output_dir: string;
+ /** Suggested Node major version, parsed from `engines.node` or defaulted to 20. */
+ node_version: string;
+ /**
+ * Detected framework hint (e.g. `nextjs`, `vite`, `astro`) to write into `DeploymentProject.framework`. Null when no framework matched — leaving the field null lets the build worker fall back to its own auto-detection.
+ * @nullable
+ */
+ framework: string | null;
+ }
+
/**
* * `Desktop` - Desktop
* `Mobile` - Mobile