MCPcopy Create free account
hub / github.com/boringstack-xyz/boringstack / patchRelations

Function patchRelations

apps/api/scripts/codegen/new-resource.ts:132–205  ·  view source on GitHub ↗
(content: string, filePrefix: string)

Source from the content-addressed store, hash-verified

130const patchRelations = (content: string, filePrefix: string): string => {
131 if (content.includes(`export const ${filePrefix}Relations`)) {
132 throw new Error(
133 `Relation "${filePrefix}Relations" already exists in relations.ts`
134 );
135 }
136
137 let next = content;
138
139 // 1. Add the import for the new table from app.schema.
140 const appImportRegex = /import\s+{([^}]*)}\s+from\s+"\.\/app\.schema";/;
141 const match = appImportRegex.exec(next);
142
143 if (match) {
144 const inner = (match[1] ?? "").trim().replace(/,$/, "");
145 const items = inner
146 .split(",")
147 .map((segment) => segment.trim())
148 .filter((segment) => segment.length > 0);
149
150 if (!items.includes(filePrefix)) {
151 items.push(filePrefix);
152 items.sort();
153 next = next.replace(
154 appImportRegex,
155 `import { ${items.join(", ")} } from "./app.schema";`
156 );
157 }
158 } else {
159 next = next.replace(
160 /(import\s+{[^}]*}\s+from\s+"\.\/auth\.schema";)/,
161 `import { ${filePrefix} } from "./app.schema";\n$1`
162 );
163 }
164
165 // 2. Append the new relation declaration.
166 const relation = `
167export const ${filePrefix}Relations = relations(${filePrefix}, ({ one }) => ({
168 user: one(users, {
169 fields: [${filePrefix}.userId],
170 references: [users.id],
171 }),
172}));
173`;
174
175 next = next.trimEnd() + "\n" + relation;
176
177 // 3. Add `<filePrefix>: many(<filePrefix>),` inside usersRelations.
178 const manyLine = ` ${filePrefix}: many(${filePrefix}),`;
179
180 if (!next.includes(manyLine)) {
181 /*
182 * Capture the `usersRelations` block body so we can insert a new
183 * `many: many(...)` line just before the closing `}));`. The body
184 * uses `[\s\S]*?` rather than the earlier `(?:[^}]*\n)*?`: a
185 * quantifier-inside-a-quantifier pattern that CodeQL flags as
186 * ReDoS-prone on input with many bare newlines. Single lazy
187 * quantifier = linear scan, no backtracking blowup.
188 */
189 const usersBlock =

Callers 1

new-resource.tsFile · 0.85

Calls 1

warnMethod · 0.80

Tested by

no test coverage detected