@metaobjectsdev/codegen-ts 0.7.0-rc.10 → 0.7.0-rc.12
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.
- package/dist/generators/docs-data-builder.d.ts +16 -0
- package/dist/generators/docs-data-builder.d.ts.map +1 -0
- package/dist/generators/docs-data-builder.js +375 -0
- package/dist/generators/docs-data-builder.js.map +1 -0
- package/dist/generators/docs-data.d.ts +87 -0
- package/dist/generators/docs-data.d.ts.map +1 -0
- package/dist/generators/docs-data.js +13 -0
- package/dist/generators/docs-data.js.map +1 -0
- package/dist/generators/docs-file.d.ts +1 -1
- package/dist/generators/docs-file.d.ts.map +1 -1
- package/dist/generators/docs-file.js +50 -33
- package/dist/generators/docs-file.js.map +1 -1
- package/dist/generators/index.d.ts +3 -0
- package/dist/generators/index.d.ts.map +1 -1
- package/dist/generators/index.js +2 -0
- package/dist/generators/index.js.map +1 -1
- package/dist/generators/template-generator.d.ts +40 -0
- package/dist/generators/template-generator.d.ts.map +1 -0
- package/dist/generators/template-generator.js +43 -0
- package/dist/generators/template-generator.js.map +1 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/overwrite-policy.d.ts +39 -2
- package/dist/overwrite-policy.d.ts.map +1 -1
- package/dist/overwrite-policy.js +233 -13
- package/dist/overwrite-policy.js.map +1 -1
- package/dist/render-engine/framework-provider.d.ts +28 -0
- package/dist/render-engine/framework-provider.d.ts.map +1 -0
- package/dist/render-engine/framework-provider.js +99 -0
- package/dist/render-engine/framework-provider.js.map +1 -0
- package/dist/runner.d.ts +15 -1
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +43 -6
- package/dist/runner.js.map +1 -1
- package/dist/templates/docs-file.d.ts +5 -36
- package/dist/templates/docs-file.d.ts.map +1 -1
- package/dist/templates/docs-file.js +33 -441
- package/dist/templates/docs-file.js.map +1 -1
- package/package.json +5 -5
- package/src/generators/docs-data-builder.ts +467 -0
- package/src/generators/docs-data.ts +113 -0
- package/src/generators/docs-file.ts +64 -43
- package/src/generators/index.ts +15 -0
- package/src/generators/template-generator.ts +84 -0
- package/src/index.ts +33 -2
- package/src/overwrite-policy.ts +325 -14
- package/src/render-engine/framework-provider.ts +98 -0
- package/src/runner.ts +64 -6
- package/src/templates/docs-file.ts +36 -530
- package/templates/docs/entity-page.md.mustache +54 -0
|
@@ -1,64 +1,85 @@
|
|
|
1
1
|
// docsFile() — emits `<Entity>.md` next to each generated entity module.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
3
|
+
// rc.12+: refactored to use templateGenerator(). The Markdown structure now
|
|
4
|
+
// lives in `templates/docs/entity-page.md.mustache`; the data extraction lives
|
|
5
|
+
// in `buildEntityDocData()`. Adopters can override the framework template by
|
|
6
|
+
// dropping their own `templates/docs/entity-page.md.mustache` into the project
|
|
7
|
+
// root (resolved via the project-then-framework provider chain).
|
|
8
|
+
//
|
|
9
|
+
// The conformance fixture (`fixtures/conformance/docs-file-basic`) gates
|
|
10
|
+
// byte-identity through the refactor — the codegen output must match the
|
|
11
|
+
// hand-coded rc.11 byte-for-byte. If you're hacking on this and the
|
|
12
|
+
// conformance test breaks, the refactor is the bug, not the fixture.
|
|
9
13
|
|
|
10
14
|
import type { MetaObject } from "@metaobjectsdev/metadata";
|
|
11
|
-
import {
|
|
12
|
-
import { renderDocsFile } from "../templates/docs-file.js";
|
|
15
|
+
import type { Generator, GeneratorFactory, GenContext } from "../generator.js";
|
|
13
16
|
import { entityOutputPath } from "../import-path.js";
|
|
17
|
+
import {
|
|
18
|
+
templateGenerator,
|
|
19
|
+
type TemplateGeneratorOpts,
|
|
20
|
+
} from "./template-generator.js";
|
|
21
|
+
import { buildEntityDocData } from "./docs-data-builder.js";
|
|
14
22
|
|
|
15
23
|
export interface DocsFileOpts {
|
|
16
24
|
filter?: (entity: MetaObject) => boolean;
|
|
17
25
|
target?: string;
|
|
18
26
|
}
|
|
19
27
|
|
|
28
|
+
/** The names of the generators that may emit sibling files for an entity.
|
|
29
|
+
* We always list them in the "Generated code" section — adopters cross-
|
|
30
|
+
* reference their own metaobjects.config.ts to confirm which are wired in.
|
|
31
|
+
* Matches the rc.11 behavior. */
|
|
32
|
+
const KNOWN_SIBLING_GENERATORS = new Set([
|
|
33
|
+
"queries-file",
|
|
34
|
+
"routes-file",
|
|
35
|
+
"routes-file-hono",
|
|
36
|
+
]);
|
|
37
|
+
|
|
20
38
|
export const docsFile = function docsFile(opts?: DocsFileOpts): Generator {
|
|
39
|
+
// We can't fully delegate to templateGenerator's `walk(root)` because the
|
|
40
|
+
// per-entity output path depends on the runtime `outputLayout` (flat /
|
|
41
|
+
// package), which only lives on `GenContext.config`. So docsFile wraps
|
|
42
|
+
// templateGenerator and threads ctx through.
|
|
43
|
+
const tgOpts: TemplateGeneratorOpts = {
|
|
44
|
+
name: "docs-file",
|
|
45
|
+
template: "docs/entity-page.md",
|
|
46
|
+
format: "markdown",
|
|
47
|
+
walk: () => [], // placeholder — real walk happens inside generate() below
|
|
48
|
+
};
|
|
49
|
+
const inner = templateGenerator(tgOpts);
|
|
50
|
+
|
|
21
51
|
const generator: Generator = {
|
|
22
52
|
name: "docs-file",
|
|
23
|
-
generate:
|
|
53
|
+
async generate(ctx: GenContext) {
|
|
24
54
|
if (!ctx.renderContext) {
|
|
25
55
|
throw new Error("docs-file: renderContext is required (provided by runGen)");
|
|
26
56
|
}
|
|
27
57
|
const rc = ctx.renderContext;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
58
|
+
// Drive the templateGenerator by populating its walk via closure.
|
|
59
|
+
const realWalk = (root: typeof ctx.loadedRoot) =>
|
|
60
|
+
root.objects().filter(ctx.matches).map((entity: MetaObject) => ({
|
|
61
|
+
data: buildEntityDocData(entity, {
|
|
62
|
+
dialect: rc.dialect,
|
|
63
|
+
...(rc.columnNamingStrategy !== undefined
|
|
64
|
+
? { columnNamingStrategy: rc.columnNamingStrategy }
|
|
65
|
+
: {}),
|
|
66
|
+
loadedRoot: rc.loadedRoot,
|
|
67
|
+
generatorNames: KNOWN_SIBLING_GENERATORS,
|
|
68
|
+
}),
|
|
69
|
+
outputPath: entityOutputPath(
|
|
70
|
+
ctx.config.outputLayout ?? "flat",
|
|
71
|
+
entity.package,
|
|
72
|
+
`${entity.name}.md`,
|
|
73
|
+
),
|
|
74
|
+
}));
|
|
75
|
+
// Hot-swap walk on the underlying templateGenerator. (The factory
|
|
76
|
+
// closes over `opts.walk`, so we mutate the options object's walk
|
|
77
|
+
// reference here.)
|
|
78
|
+
(tgOpts as { walk: typeof realWalk }).walk = realWalk;
|
|
79
|
+
return inner.generate(ctx);
|
|
80
|
+
},
|
|
43
81
|
};
|
|
44
|
-
if (opts?.filter)
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
if (opts?.target) {
|
|
48
|
-
generator.target = opts.target;
|
|
49
|
-
}
|
|
82
|
+
if (opts?.filter) generator.filter = opts.filter;
|
|
83
|
+
if (opts?.target) generator.target = opts.target;
|
|
50
84
|
return generator;
|
|
51
85
|
} as GeneratorFactory<DocsFileOpts>;
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* `GenContext` does not currently carry the full generator list — that lives on
|
|
55
|
-
* the resolved config inside the runner. Rather than thread a new field through
|
|
56
|
-
* just to populate one optional markdown section, we always list every
|
|
57
|
-
* potential companion. The "Generated code" section becomes "files that may be
|
|
58
|
-
* generated alongside this one" — adopters cross-reference their own
|
|
59
|
-
* `metaobjects.config.ts` to confirm which they actually wired in. This matches
|
|
60
|
-
* the spec guidance "list them all and let the reader figure out which exist."
|
|
61
|
-
*/
|
|
62
|
-
function readGeneratorNames(_ctx: unknown): ReadonlySet<string> {
|
|
63
|
-
return new Set(["queries-file", "routes-file", "routes-file-hono"]);
|
|
64
|
-
}
|
package/src/generators/index.ts
CHANGED
|
@@ -7,3 +7,18 @@ export { mermaidErDiagram, type MermaidErOptions } from "./mermaid-er.js";
|
|
|
7
7
|
export { promptRender, type PromptRenderOpts } from "./prompt-render-file.js";
|
|
8
8
|
export { outputParser, type OutputParserOpts } from "./output-parser-file.js";
|
|
9
9
|
export { docsFile, type DocsFileOpts } from "./docs-file.js";
|
|
10
|
+
export {
|
|
11
|
+
templateGenerator,
|
|
12
|
+
type TemplateGeneratorOpts,
|
|
13
|
+
type TemplateWalkResult,
|
|
14
|
+
type TemplateFormat,
|
|
15
|
+
} from "./template-generator.js";
|
|
16
|
+
export type {
|
|
17
|
+
EntityDocData,
|
|
18
|
+
StorageFieldDoc,
|
|
19
|
+
IdentityDoc,
|
|
20
|
+
RelationshipDoc,
|
|
21
|
+
UsedByDoc,
|
|
22
|
+
GeneratedFileDoc,
|
|
23
|
+
} from "./docs-data.js";
|
|
24
|
+
export { buildEntityDocData } from "./docs-data-builder.js";
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// templateGenerator() — the missing primitive identified by the
|
|
2
|
+
// template-driven-codegen design (2026-05-28). Walks the loaded MetaRoot
|
|
3
|
+
// → renders shared Mustache templates via @metaobjectsdev/render → emits
|
|
4
|
+
// EmittedFile[]. Same Generator interface as the per-port hand-coded
|
|
5
|
+
// generators; just adds the "Mustache template" + "walk that yields a
|
|
6
|
+
// data dict per output" primitives.
|
|
7
|
+
//
|
|
8
|
+
// Design line we adopted (from the design doc):
|
|
9
|
+
// Code → hand-coded generators (ts-poet, idiomatic per-port).
|
|
10
|
+
// Documents → templateGenerator (shared Mustache templates).
|
|
11
|
+
//
|
|
12
|
+
// docsFile() is the first templateGenerator instance (rc.12). OpenAPI specs,
|
|
13
|
+
// Mermaid diagrams, HTML doc sites, etc. follow as templates + a walk
|
|
14
|
+
// function each.
|
|
15
|
+
|
|
16
|
+
import type { MetaRoot, MetaObject } from "@metaobjectsdev/metadata";
|
|
17
|
+
import { render, type Provider, type RenderFormat } from "@metaobjectsdev/render";
|
|
18
|
+
import type { Generator, GenContext, EmittedFile, GeneratorFactory } from "../generator.js";
|
|
19
|
+
import { projectProvider } from "../render-engine/framework-provider.js";
|
|
20
|
+
|
|
21
|
+
export type TemplateFormat = RenderFormat;
|
|
22
|
+
|
|
23
|
+
export interface TemplateWalkResult {
|
|
24
|
+
/** The data dict to render against. Templates reference its keys; the
|
|
25
|
+
* shape is the public-API contract template authors consume. */
|
|
26
|
+
data: object;
|
|
27
|
+
/** Output path RELATIVE to the generator's target outDir. */
|
|
28
|
+
outputPath: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface TemplateGeneratorOpts {
|
|
32
|
+
/** kebab-case identifier; surfaces in diagnostics and the overwrite-policy
|
|
33
|
+
* per-file snapshot key. */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Walk the loaded metadata tree and produce `{ data, outputPath }` tuples
|
|
36
|
+
* — one per emitted file. Pattern A (per-entity), pattern B (single
|
|
37
|
+
* aggregator), pattern C (mixed), pattern D (filter inline) all fit. */
|
|
38
|
+
walk: (root: MetaRoot) => TemplateWalkResult[] | Promise<TemplateWalkResult[]>;
|
|
39
|
+
/** Template reference. Resolved by the configured Provider chain — by
|
|
40
|
+
* default the project's `templates/<ref>.mustache` first, then the
|
|
41
|
+
* framework defaults at `codegen-ts/templates/<ref>.mustache`. */
|
|
42
|
+
template: string;
|
|
43
|
+
/** Drives the render engine's escaper. Defaults to "text". */
|
|
44
|
+
format?: TemplateFormat;
|
|
45
|
+
/** Optional per-entity filter for adopters who want to scope a generator
|
|
46
|
+
* via the standard `Generator.filter` plumbing. Not consulted by the
|
|
47
|
+
* default `walk` — adopters apply filters inside their walk function. */
|
|
48
|
+
filter?: (entity: MetaObject) => boolean;
|
|
49
|
+
/** Override the Provider used for template resolution. When omitted the
|
|
50
|
+
* generator resolves via `projectProvider(<projectRoot>)`, which layers
|
|
51
|
+
* the project's `templates/` over the framework defaults. (The project
|
|
52
|
+
* root is taken from `process.cwd()` at run time — adopters needing a
|
|
53
|
+
* different lookup chain can pass an explicit provider.) */
|
|
54
|
+
provider?: Provider;
|
|
55
|
+
/** Optional named target — same as the other generators. */
|
|
56
|
+
target?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const templateGenerator = function templateGenerator(
|
|
60
|
+
opts: TemplateGeneratorOpts,
|
|
61
|
+
): Generator {
|
|
62
|
+
const fmt: TemplateFormat = opts.format ?? "text";
|
|
63
|
+
const generator: Generator = {
|
|
64
|
+
name: opts.name,
|
|
65
|
+
async generate(ctx: GenContext): Promise<EmittedFile[]> {
|
|
66
|
+
const provider = opts.provider ?? projectProvider(process.cwd());
|
|
67
|
+
const walkRes = await opts.walk(ctx.loadedRoot);
|
|
68
|
+
const files: EmittedFile[] = [];
|
|
69
|
+
for (const { data, outputPath } of walkRes) {
|
|
70
|
+
const content = render({
|
|
71
|
+
ref: opts.template,
|
|
72
|
+
payload: data,
|
|
73
|
+
provider,
|
|
74
|
+
format: fmt,
|
|
75
|
+
});
|
|
76
|
+
files.push({ path: outputPath, content });
|
|
77
|
+
}
|
|
78
|
+
return files;
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
if (opts.filter) generator.filter = opts.filter;
|
|
82
|
+
if (opts.target) generator.target = opts.target;
|
|
83
|
+
return generator;
|
|
84
|
+
} as GeneratorFactory<TemplateGeneratorOpts>;
|
package/src/index.ts
CHANGED
|
@@ -24,8 +24,14 @@ export { buildRelationMap } from "./relation-resolver.js";
|
|
|
24
24
|
export type { RenderContext } from "./render-context.js";
|
|
25
25
|
export { makeRenderContext } from "./render-context.js";
|
|
26
26
|
|
|
27
|
-
export type {
|
|
28
|
-
|
|
27
|
+
export type {
|
|
28
|
+
WriteStatus,
|
|
29
|
+
WriteResult,
|
|
30
|
+
MergeStrategy,
|
|
31
|
+
BaselineMode,
|
|
32
|
+
DecideAndWriteOpts,
|
|
33
|
+
} from "./overwrite-policy.js";
|
|
34
|
+
export { decideAndWrite, GitMissingError } from "./overwrite-policy.js";
|
|
29
35
|
|
|
30
36
|
export { CodegenError } from "./errors.js";
|
|
31
37
|
export { GENERATED_HEADER, EXTRA_SUFFIX, DEFAULT_OUT_DIR } from "./constants.js";
|
|
@@ -45,3 +51,28 @@ export type { EmitOptions as ViewDdlEmitOptions } from "./projection/view-ddl-em
|
|
|
45
51
|
export type { JoinNode, JoinTree, SelectColumn, SelectSpec, ViewSpec } from "./projection/view-spec.js";
|
|
46
52
|
// Prompt construction (FR-004): typed payload + render-handle codegen.
|
|
47
53
|
export { generatePayloadInterfaces, generatePayloadInterfacesBatch, generateRenderHandle } from "./payload-codegen.js";
|
|
54
|
+
|
|
55
|
+
// Template-driven codegen (rc.12). Factory + framework Provider for adopters
|
|
56
|
+
// who want to wire their own templateGenerator instances. The default
|
|
57
|
+
// docsFile() uses this internally.
|
|
58
|
+
export {
|
|
59
|
+
templateGenerator,
|
|
60
|
+
type TemplateGeneratorOpts,
|
|
61
|
+
type TemplateWalkResult,
|
|
62
|
+
type TemplateFormat,
|
|
63
|
+
} from "./generators/template-generator.js";
|
|
64
|
+
export {
|
|
65
|
+
FileSystemProvider,
|
|
66
|
+
ProviderChain,
|
|
67
|
+
frameworkTemplatesProvider,
|
|
68
|
+
projectProvider,
|
|
69
|
+
} from "./render-engine/framework-provider.js";
|
|
70
|
+
export type {
|
|
71
|
+
EntityDocData,
|
|
72
|
+
StorageFieldDoc,
|
|
73
|
+
IdentityDoc,
|
|
74
|
+
RelationshipDoc,
|
|
75
|
+
UsedByDoc,
|
|
76
|
+
GeneratedFileDoc,
|
|
77
|
+
} from "./generators/docs-data.js";
|
|
78
|
+
export { buildEntityDocData } from "./generators/docs-data-builder.js";
|
package/src/overwrite-policy.ts
CHANGED
|
@@ -1,39 +1,350 @@
|
|
|
1
|
-
// Overwrite policy:
|
|
2
|
-
//
|
|
1
|
+
// Overwrite policy: per-file write decision using three-way merge against a
|
|
2
|
+
// canonical snapshot kept under `.metaobjects/.gen-state/`.
|
|
3
|
+
//
|
|
4
|
+
// Replaces the rc.11 marker-based clobber-or-refuse policy (strategy (a) from
|
|
5
|
+
// spike 002) with strategy (b) — git-merge-file-driven three-way merge. The
|
|
6
|
+
// `@generated` marker becomes purely informational (templates may still emit
|
|
7
|
+
// it for human readers); the policy no longer consults it.
|
|
8
|
+
//
|
|
9
|
+
// Per-file flow:
|
|
10
|
+
//
|
|
11
|
+
// 1. Render fresh content to a tmpfile.
|
|
12
|
+
// 2. If the output doesn't exist → write + copy to .gen-state/.
|
|
13
|
+
// 3. If .gen-state/<relPath> exists → run `git merge-file --diff3` against
|
|
14
|
+
// (current, .gen-state snapshot, fresh tmpfile). Exit 0 → clean merge,
|
|
15
|
+
// advance .gen-state to fresh content. Exit > 0 → leave conflict markers
|
|
16
|
+
// in the output file, do NOT advance .gen-state; status "conflict".
|
|
17
|
+
// 4. If .gen-state/<relPath> is absent but the file exists ("first-time
|
|
18
|
+
// regen on an existing file") → write-if-different against the existing
|
|
19
|
+
// file as the baseline (no merge, no clobber). The `baseline: "fresh"`
|
|
20
|
+
// flag opts into "overwrite from fresh and re-baseline".
|
|
21
|
+
//
|
|
22
|
+
// Integrity (caveat 2 from the spike): we keep a sha-256 of each canonical
|
|
23
|
+
// snapshot at `.gen-state/.hashes.json`. On load, mismatch → fall back to
|
|
24
|
+
// first-time semantics and warn naming the file so the user can investigate.
|
|
3
25
|
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
26
|
+
import {
|
|
27
|
+
existsSync,
|
|
28
|
+
readFileSync,
|
|
29
|
+
writeFileSync,
|
|
30
|
+
mkdirSync,
|
|
31
|
+
copyFileSync,
|
|
32
|
+
} from "node:fs";
|
|
33
|
+
import { dirname, join, isAbsolute, relative, resolve } from "node:path";
|
|
34
|
+
import { spawnSync } from "node:child_process";
|
|
35
|
+
import { tmpdir } from "node:os";
|
|
36
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
37
|
|
|
8
|
-
export type WriteStatus =
|
|
38
|
+
export type WriteStatus =
|
|
39
|
+
| "new"
|
|
40
|
+
| "unchanged"
|
|
41
|
+
| "overwrite"
|
|
42
|
+
| "merged"
|
|
43
|
+
| "conflict"
|
|
44
|
+
| "refused"
|
|
45
|
+
| "skipped";
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* "overwrite" — default; three-way merge if .gen-state exists, else write-if-
|
|
49
|
+
* different / first-time-existing flow.
|
|
50
|
+
* "skip-existing" — never write over an existing file; status "skipped".
|
|
51
|
+
* Useful for `meta gen --dry-run` style flows.
|
|
52
|
+
*/
|
|
9
53
|
export type MergeStrategy = "overwrite" | "skip-existing";
|
|
10
54
|
|
|
55
|
+
/** "default" — the standard three-way merge flow described in the file header.
|
|
56
|
+
* "fresh" — opt-in via `meta gen --baseline=fresh`. When .gen-state is absent
|
|
57
|
+
* but the file exists, OVERWRITE with fresh content and seed .gen-state from
|
|
58
|
+
* the fresh content (caveat 3 escape hatch). */
|
|
59
|
+
export type BaselineMode = "default" | "fresh";
|
|
60
|
+
|
|
61
|
+
export interface DecideAndWriteOpts {
|
|
62
|
+
strategy?: MergeStrategy;
|
|
63
|
+
/** Absolute path to the .gen-state/ root for this project. When undefined,
|
|
64
|
+
* we fall back to a process-isolated tmpdir — fine for tests but the CLI
|
|
65
|
+
* always supplies the real project value via runGen(). */
|
|
66
|
+
genStateDir?: string;
|
|
67
|
+
/** Path the snapshot is keyed by — usually the path relative to the
|
|
68
|
+
* project root, but ANY stable identifier works. When undefined, derived
|
|
69
|
+
* from `path` (so unit tests can call without supplying it). */
|
|
70
|
+
outputRelPath?: string;
|
|
71
|
+
/** First-time-existing-file behavior. */
|
|
72
|
+
baseline?: BaselineMode;
|
|
73
|
+
}
|
|
74
|
+
|
|
11
75
|
export interface WriteResult {
|
|
12
76
|
path: string;
|
|
13
77
|
status: WriteStatus;
|
|
78
|
+
/** Present when status is "conflict" — human-readable hint identifying the
|
|
79
|
+
* file the user must resolve. */
|
|
80
|
+
conflictHint?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const HASHES_FILE = ".hashes.json";
|
|
84
|
+
|
|
85
|
+
type HashesFile = Record<string, string>;
|
|
86
|
+
|
|
87
|
+
function sha256(content: string | Buffer): string {
|
|
88
|
+
return createHash("sha256").update(content).digest("hex");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function loadHashes(genStateDir: string): HashesFile {
|
|
92
|
+
const f = join(genStateDir, HASHES_FILE);
|
|
93
|
+
if (!existsSync(f)) return {};
|
|
94
|
+
try {
|
|
95
|
+
const txt = readFileSync(f, "utf-8");
|
|
96
|
+
const parsed: unknown = JSON.parse(txt);
|
|
97
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
98
|
+
return parsed as HashesFile;
|
|
99
|
+
}
|
|
100
|
+
return {};
|
|
101
|
+
} catch {
|
|
102
|
+
return {};
|
|
103
|
+
}
|
|
14
104
|
}
|
|
15
105
|
|
|
106
|
+
function saveHashes(genStateDir: string, hashes: HashesFile): void {
|
|
107
|
+
mkdirSync(genStateDir, { recursive: true });
|
|
108
|
+
writeFileSync(join(genStateDir, HASHES_FILE), JSON.stringify(hashes, null, 2) + "\n");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function snapshotPath(genStateDir: string, relPath: string): string {
|
|
112
|
+
// `.hashes.json` is reserved at the top of .gen-state/; relPath must never
|
|
113
|
+
// collide with it. Output paths derived from entity names ("Post.ts" etc.)
|
|
114
|
+
// are JS-identifier-shape so this is a non-issue in practice.
|
|
115
|
+
return join(genStateDir, relPath);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Synchronously copy `src` content into the snapshot at `<genStateDir>/<relPath>`
|
|
119
|
+
* and refresh the hash for `relPath`. */
|
|
120
|
+
function advanceSnapshot(
|
|
121
|
+
genStateDir: string,
|
|
122
|
+
relPath: string,
|
|
123
|
+
content: string,
|
|
124
|
+
): void {
|
|
125
|
+
const dest = snapshotPath(genStateDir, relPath);
|
|
126
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
127
|
+
writeFileSync(dest, content);
|
|
128
|
+
const hashes = loadHashes(genStateDir);
|
|
129
|
+
hashes[relPath] = sha256(content);
|
|
130
|
+
saveHashes(genStateDir, hashes);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Return the snapshot text iff present AND the hash matches; else undefined. */
|
|
134
|
+
function readSnapshotChecked(
|
|
135
|
+
genStateDir: string,
|
|
136
|
+
relPath: string,
|
|
137
|
+
): { text: string } | undefined {
|
|
138
|
+
const path = snapshotPath(genStateDir, relPath);
|
|
139
|
+
if (!existsSync(path)) return undefined;
|
|
140
|
+
const text = readFileSync(path, "utf-8");
|
|
141
|
+
const hashes = loadHashes(genStateDir);
|
|
142
|
+
const expected = hashes[relPath];
|
|
143
|
+
if (expected !== undefined && expected !== sha256(text)) {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
return { text };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Thrown when git is unavailable. Surfaces as a clear CLI error rather than
|
|
150
|
+
* a generic ENOENT halfway through a regen. */
|
|
151
|
+
export class GitMissingError extends Error {
|
|
152
|
+
constructor() {
|
|
153
|
+
super(
|
|
154
|
+
"meta gen: `git` binary not found on PATH. Three-way-merge regen " +
|
|
155
|
+
"requires git (any modern version). Install git and re-run.",
|
|
156
|
+
);
|
|
157
|
+
this.name = "GitMissingError";
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
interface MergeOutcome {
|
|
162
|
+
/** 0 → clean merge; > 0 → conflicts present (file contains diff3 markers). */
|
|
163
|
+
exitCode: number;
|
|
164
|
+
/** stderr text — surfaced on unexpected errors. */
|
|
165
|
+
stderr: string;
|
|
166
|
+
/** Resulting file contents on disk after the merge (always read; clean or
|
|
167
|
+
* conflicting). */
|
|
168
|
+
mergedContent: string;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Run `git merge-file --diff3 -L<...> <out> <base> <fresh>`. The output is
|
|
172
|
+
* written in-place into `outPath`. Returns the exit code (0 = clean, > 0 =
|
|
173
|
+
* conflicts) and the resulting file contents.
|
|
174
|
+
*
|
|
175
|
+
* The git binary is "git" by default; set `META_GEN_GIT` in the environment
|
|
176
|
+
* to a different path (useful for tests that simulate "git not installed"). */
|
|
177
|
+
function runGitMergeFile(
|
|
178
|
+
outPath: string,
|
|
179
|
+
basePath: string,
|
|
180
|
+
freshPath: string,
|
|
181
|
+
): MergeOutcome {
|
|
182
|
+
const gitBin = process.env.META_GEN_GIT ?? "git";
|
|
183
|
+
let res;
|
|
184
|
+
try {
|
|
185
|
+
res = spawnSync(
|
|
186
|
+
gitBin,
|
|
187
|
+
[
|
|
188
|
+
"merge-file",
|
|
189
|
+
"--diff3",
|
|
190
|
+
"-L",
|
|
191
|
+
"your edits",
|
|
192
|
+
"-L",
|
|
193
|
+
"last generated",
|
|
194
|
+
"-L",
|
|
195
|
+
"fresh from meta gen",
|
|
196
|
+
outPath,
|
|
197
|
+
basePath,
|
|
198
|
+
freshPath,
|
|
199
|
+
],
|
|
200
|
+
{ encoding: "utf-8" },
|
|
201
|
+
);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
const msg = (err as Error).message ?? "";
|
|
204
|
+
if (msg.includes("ENOENT")) throw new GitMissingError();
|
|
205
|
+
throw err;
|
|
206
|
+
}
|
|
207
|
+
if (res.error) {
|
|
208
|
+
const code = (res.error as NodeJS.ErrnoException).code;
|
|
209
|
+
if (code === "ENOENT") throw new GitMissingError();
|
|
210
|
+
throw res.error;
|
|
211
|
+
}
|
|
212
|
+
// `git merge-file` returns the conflict count (0 = clean, > 0 = conflicts,
|
|
213
|
+
// < 0 = error). Negative is unexpected — surface verbatim.
|
|
214
|
+
const exitCode = res.status ?? 0;
|
|
215
|
+
if (exitCode < 0) {
|
|
216
|
+
throw new Error(
|
|
217
|
+
`git merge-file failed for ${outPath}: ${res.stderr || res.stdout}`,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
const mergedContent = readFileSync(outPath, "utf-8");
|
|
221
|
+
return { exitCode, stderr: res.stderr ?? "", mergedContent };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Write `content` to a freshly-named tmpfile under the OS tmpdir; return the
|
|
225
|
+
* path. Caller is responsible for cleanup (acceptable for codegen — tmpdir
|
|
226
|
+
* is process-scoped). */
|
|
227
|
+
function writeTmpfile(content: string): string {
|
|
228
|
+
const dir = join(tmpdir(), "meta-gen-merge");
|
|
229
|
+
mkdirSync(dir, { recursive: true });
|
|
230
|
+
const path = join(dir, `${Date.now()}-${randomBytes(6).toString("hex")}.tmp`);
|
|
231
|
+
writeFileSync(path, content);
|
|
232
|
+
return path;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Resolve the snapshot key for a given output path. Falls back to a stable
|
|
236
|
+
* hash-of-path so unit tests that pass arbitrary tmpdir outputs still get a
|
|
237
|
+
* consistent .gen-state key. */
|
|
238
|
+
function defaultOutputRelPath(outputPath: string): string {
|
|
239
|
+
// Use sha256 of the absolute path → hex; lets tests work without supplying
|
|
240
|
+
// an explicit relPath. NOT used by the runner — runGen always passes the
|
|
241
|
+
// real project-relative path.
|
|
242
|
+
return sha256(resolve(outputPath)).slice(0, 32);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The main entry point. Backward-compatible with the rc.11 signature: passing
|
|
247
|
+
* a `MergeStrategy` string as the third argument continues to work; passing
|
|
248
|
+
* an options object opts into three-way merge.
|
|
249
|
+
*/
|
|
16
250
|
export function decideAndWrite(
|
|
17
251
|
path: string,
|
|
18
252
|
content: string,
|
|
19
|
-
|
|
253
|
+
optsOrStrategy: DecideAndWriteOpts | MergeStrategy = {},
|
|
20
254
|
): WriteResult {
|
|
21
|
-
|
|
255
|
+
const opts: DecideAndWriteOpts =
|
|
256
|
+
typeof optsOrStrategy === "string"
|
|
257
|
+
? { strategy: optsOrStrategy }
|
|
258
|
+
: optsOrStrategy;
|
|
259
|
+
const strategy: MergeStrategy = opts.strategy ?? "overwrite";
|
|
260
|
+
const baseline: BaselineMode = opts.baseline ?? "default";
|
|
261
|
+
const genStateDir =
|
|
262
|
+
opts.genStateDir !== undefined
|
|
263
|
+
? (isAbsolute(opts.genStateDir)
|
|
264
|
+
? opts.genStateDir
|
|
265
|
+
: resolve(opts.genStateDir))
|
|
266
|
+
: join(tmpdir(), "meta-gen-state-fallback");
|
|
267
|
+
const relPath = opts.outputRelPath ?? defaultOutputRelPath(path);
|
|
268
|
+
|
|
269
|
+
// 1. First-time write — file doesn't exist.
|
|
22
270
|
if (!existsSync(path)) {
|
|
23
271
|
mkdirSync(dirname(path), { recursive: true });
|
|
24
272
|
writeFileSync(path, content);
|
|
273
|
+
advanceSnapshot(genStateDir, relPath, content);
|
|
25
274
|
return { path, status: "new" };
|
|
26
275
|
}
|
|
27
276
|
|
|
277
|
+
if (strategy === "skip-existing") {
|
|
278
|
+
return { path, status: "skipped" };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 2. File exists. Load the canonical snapshot if any.
|
|
282
|
+
const snapshot = readSnapshotChecked(genStateDir, relPath);
|
|
283
|
+
|
|
284
|
+
// 3. First-time regen on a pre-existing file (no snapshot).
|
|
285
|
+
if (snapshot === undefined) {
|
|
286
|
+
const current = readFileSync(path, "utf-8");
|
|
287
|
+
|
|
288
|
+
if (baseline === "fresh") {
|
|
289
|
+
// Opt-in escape hatch: overwrite and seed the snapshot from fresh.
|
|
290
|
+
if (current === content) {
|
|
291
|
+
advanceSnapshot(genStateDir, relPath, content);
|
|
292
|
+
return { path, status: "unchanged" };
|
|
293
|
+
}
|
|
294
|
+
writeFileSync(path, content);
|
|
295
|
+
advanceSnapshot(genStateDir, relPath, content);
|
|
296
|
+
return { path, status: "overwrite" };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Default: write-if-different. The EXISTING file is treated as the
|
|
300
|
+
// canonical baseline so subsequent runs do real three-way merges. If
|
|
301
|
+
// fresh output is identical, just seed the snapshot. If different, write
|
|
302
|
+
// the fresh content + seed snapshot — there's no marker policy left to
|
|
303
|
+
// refuse on, but this is the contract documented in the runbook (no
|
|
304
|
+
// marker check; users with hand-written files should never have the
|
|
305
|
+
// codegen output path colliding with them).
|
|
306
|
+
if (current === content) {
|
|
307
|
+
advanceSnapshot(genStateDir, relPath, current);
|
|
308
|
+
return { path, status: "unchanged" };
|
|
309
|
+
}
|
|
310
|
+
writeFileSync(path, content);
|
|
311
|
+
advanceSnapshot(genStateDir, relPath, content);
|
|
312
|
+
return { path, status: "overwrite" };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// 4. Snapshot exists — real three-way merge.
|
|
28
316
|
const current = readFileSync(path, "utf-8");
|
|
29
|
-
|
|
30
|
-
|
|
317
|
+
|
|
318
|
+
// Fast path: nothing changed.
|
|
319
|
+
if (current === content && snapshot.text === content) {
|
|
320
|
+
return { path, status: "unchanged" };
|
|
31
321
|
}
|
|
32
322
|
|
|
33
|
-
|
|
34
|
-
|
|
323
|
+
const baseTmp = writeTmpfile(snapshot.text);
|
|
324
|
+
const freshTmp = writeTmpfile(content);
|
|
325
|
+
|
|
326
|
+
const outcome = runGitMergeFile(path, baseTmp, freshTmp);
|
|
327
|
+
|
|
328
|
+
if (outcome.exitCode === 0) {
|
|
329
|
+
// Clean merge — advance the canonical snapshot to fresh.
|
|
330
|
+
advanceSnapshot(genStateDir, relPath, content);
|
|
331
|
+
// Distinguish "user had no changes vs canonical" from "merge integrated
|
|
332
|
+
// edits". The fresh equals snapshot case happened above (fast path) — so
|
|
333
|
+
// if outcome.mergedContent equals fresh we report a plain overwrite,
|
|
334
|
+
// otherwise it's a merge that pulled in user edits.
|
|
335
|
+
if (outcome.mergedContent === content) {
|
|
336
|
+
return { path, status: "overwrite" };
|
|
337
|
+
}
|
|
338
|
+
return { path, status: "merged" };
|
|
35
339
|
}
|
|
36
340
|
|
|
37
|
-
|
|
38
|
-
|
|
341
|
+
// Conflict — do NOT advance the snapshot. The output now contains diff3
|
|
342
|
+
// markers from git merge-file.
|
|
343
|
+
return {
|
|
344
|
+
path,
|
|
345
|
+
status: "conflict",
|
|
346
|
+
conflictHint:
|
|
347
|
+
"merge conflict — resolve `<<<<<<<` markers and re-run `meta gen` to " +
|
|
348
|
+
"advance the canonical state.",
|
|
349
|
+
};
|
|
39
350
|
}
|