mastra-ai/mastra · error
Failed to parse existing package.json at ${targetPkgPath}: $
Error message
Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)} What it means
The template-builder workflow attempted to JSON.parse an existing package.json found in the cloned template directory, but the file content is not valid JSON. This error wraps the underlying parse exception and includes the file path plus the original JSON.parse message (e.g. 'Unexpected token ... in JSON at position N') so you can locate the malformed syntax.
Source
Thrown at packages/agent-builder/src/workflows/template-builder/template-builder.ts:405
console.info('Package merge step starting...');
const { slug, packageInfo } = inputData;
const targetPath = resolveTargetPath(inputData, requestContext);
try {
const targetPkgPath = join(targetPath, 'package.json');
let targetPkgRaw = '{}';
try {
targetPkgRaw = await readFile(targetPkgPath, 'utf-8');
} catch {
console.warn(`No existing package.json at ${targetPkgPath}, creating a new one`);
}
let targetPkg: any;
try {
targetPkg = JSON.parse(targetPkgRaw || '{}');
} catch (e) {
throw new Error(
`Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}`,
);
}
const ensureObj = (o: any) => (o && typeof o === 'object' ? o : {});
targetPkg.dependencies = ensureObj(targetPkg.dependencies);
targetPkg.devDependencies = ensureObj(targetPkg.devDependencies);
targetPkg.peerDependencies = ensureObj(targetPkg.peerDependencies);
targetPkg.scripts = ensureObj(targetPkg.scripts);
const tplDeps = ensureObj(packageInfo.dependencies);
const tplDevDeps = ensureObj(packageInfo.devDependencies);
const tplPeerDeps = ensureObj(packageInfo.peerDependencies);
const tplScripts = ensureObj(packageInfo.scripts);
const existsAnywhere = (name: string) =>
name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;View on GitHub (pinned to 75dd419e61)
Solutions
- Open the package.json at the path named in the error and fix the JSON syntax at the position given in the wrapped JSON.parse message
- Validate the template's package.json with a linter (node -e 'JSON.parse(require("fs").readFileSync("package.json","utf8"))') before publishing the template
- Re-clone the template repository to rule out a truncated/partial checkout
- If the template legitimately uses JSONC, convert it to strict JSON or pre-process comments out before parse
Example fix
// before (template package.json)
{ "name": "tmpl", "version": "1.0.0", }
// after
{ "name": "tmpl", "version": "1.0.0" } Defensive patterns
Strategy: validation
Validate before calling
import { readFileSync } from 'node:fs';
export function assertValidJsonFile(path: string) {
const raw = readFileSync(path, 'utf8').replace(/^\uFEFF/, '');
try { JSON.parse(raw); } catch (e) {
throw new Error(`${path} is not valid JSON: ${e instanceof Error ? e.message : e}`);
}
}
// run against the template's package.json before invoking the template-builder workflow Type guard
export function isParseableJson(raw: string): boolean {
try { JSON.parse(raw); return true; } catch { return false; }
} Try / catch
try {
await templateBuilderWorkflow.start(...);
} catch (e) {
if (e instanceof Error && e.message.includes('Failed to parse existing package.json')) {
// surface path+parse detail to the template author
}
throw e;
} Prevention
- Validate every template's package.json in CI before publishing the template
- Strip BOM and disallow comments/trailing commas (strict JSON only)
- Commit generated package.json via tooling, never hand-edits without a JSON lint step
- Re-clone and verify templates after ref bumps to catch truncated checkouts
When it happens
Trigger: The template repository being cloned contains a package.json with syntax errors: trailing commas, comments, BOM characters, truncated files (bad commit/partial checkout), or a non-JSON placeholder file at that path. JSON.parse(targetPkgRaw || '{}') only falls back when the file is empty, not when it is invalid.
Common situations: Cloning a hand-edited or generated template whose package.json was written with comments (JSON5/JSONC), a tool wrote a corrupt file, a git LFS/partial clone truncated it, or the wrong file (e.g. an error page) ended up at the path.
Understand the failure class
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- Failed to load course state: ${error}
- Failed to parse A2A stream event: ${error instanceof Error ?
- MASTRA_ENTRY_FILE_NOT_FOUND
- Failed to copy studio assets from "${studioSource}" to "${st
- Failed to copy studio assets from "${studioSource}" to "${st
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/5cd17c2f780ba250.
Report an issue: GitHub.