@metaobjectsdev/cli 1.0.10 → 1.0.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.
Files changed (55) hide show
  1. package/dist/src/commands/eject.d.ts.map +1 -1
  2. package/dist/src/commands/eject.js +5 -1
  3. package/dist/src/commands/eject.js.map +1 -1
  4. package/dist/src/commands/fmt.d.ts +2 -0
  5. package/dist/src/commands/fmt.d.ts.map +1 -0
  6. package/dist/src/commands/fmt.js +80 -0
  7. package/dist/src/commands/fmt.js.map +1 -0
  8. package/dist/src/commands/gen.d.ts.map +1 -1
  9. package/dist/src/commands/gen.js +7 -0
  10. package/dist/src/commands/gen.js.map +1 -1
  11. package/dist/src/commands/migrate.d.ts.map +1 -1
  12. package/dist/src/commands/migrate.js +1 -0
  13. package/dist/src/commands/migrate.js.map +1 -1
  14. package/dist/src/commands/verify.d.ts.map +1 -1
  15. package/dist/src/commands/verify.js +74 -1
  16. package/dist/src/commands/verify.js.map +1 -1
  17. package/dist/src/index.d.ts.map +1 -1
  18. package/dist/src/index.js +76 -0
  19. package/dist/src/index.js.map +1 -1
  20. package/dist/src/lib/args.d.ts +36 -0
  21. package/dist/src/lib/args.d.ts.map +1 -1
  22. package/dist/src/lib/args.js +20 -0
  23. package/dist/src/lib/args.js.map +1 -1
  24. package/dist/src/lib/deprecation-lint.d.ts +11 -0
  25. package/dist/src/lib/deprecation-lint.d.ts.map +1 -0
  26. package/dist/src/lib/deprecation-lint.js +273 -0
  27. package/dist/src/lib/deprecation-lint.js.map +1 -0
  28. package/dist/src/lib/fk-index-advisory.d.ts.map +1 -1
  29. package/dist/src/lib/fk-index-advisory.js +4 -1
  30. package/dist/src/lib/fk-index-advisory.js.map +1 -1
  31. package/dist/src/lib/fmt-engine.d.ts +22 -0
  32. package/dist/src/lib/fmt-engine.d.ts.map +1 -0
  33. package/dist/src/lib/fmt-engine.js +128 -0
  34. package/dist/src/lib/fmt-engine.js.map +1 -0
  35. package/dist/src/lib/name-lint.d.ts +12 -0
  36. package/dist/src/lib/name-lint.d.ts.map +1 -0
  37. package/dist/src/lib/name-lint.js +95 -0
  38. package/dist/src/lib/name-lint.js.map +1 -0
  39. package/dist/src/lib/runtime-boundary-advisory.d.ts +24 -0
  40. package/dist/src/lib/runtime-boundary-advisory.d.ts.map +1 -0
  41. package/dist/src/lib/runtime-boundary-advisory.js +47 -0
  42. package/dist/src/lib/runtime-boundary-advisory.js.map +1 -0
  43. package/package.json +10 -10
  44. package/src/commands/eject.ts +6 -1
  45. package/src/commands/fmt.ts +90 -0
  46. package/src/commands/gen.ts +9 -0
  47. package/src/commands/migrate.ts +1 -0
  48. package/src/commands/verify.ts +90 -1
  49. package/src/index.ts +76 -0
  50. package/src/lib/args.ts +47 -0
  51. package/src/lib/deprecation-lint.ts +327 -0
  52. package/src/lib/fk-index-advisory.ts +4 -1
  53. package/src/lib/fmt-engine.ts +179 -0
  54. package/src/lib/name-lint.ts +106 -0
  55. package/src/lib/runtime-boundary-advisory.ts +74 -0
@@ -0,0 +1,179 @@
1
+ // server/typescript/packages/cli/src/lib/fmt-engine.ts
2
+ //
3
+ // `meta fmt` (#304) orchestration: resolve the project's own metadata files
4
+ // (resolveCollection — never a hardcoded `metaobjects/`), format each one
5
+ // standalone (@metaobjectsdev/metadata's formatMetadataFile — own-mode,
6
+ // declared-here layer only), and gate every rewrite behind a whole-project
7
+ // reload-and-compare safety check before it ever touches disk.
8
+ //
9
+ // The safety check (design rule 4): swap a candidate in via an in-memory
10
+ // source carrying the SAME file id the real load would use, reload the WHOLE
11
+ // project, and require both that it loads with no errors AND that its
12
+ // canonical serialization is byte-identical to the untouched baseline. Only
13
+ // then is the candidate written — so `--check` (which skips the write) and a
14
+ // real run share one code path, and a bug in the formatter can only ever
15
+ // leave a file unchanged plus an error, never a corrupted file.
16
+ import { basename, extname, resolve as resolvePath } from "node:path";
17
+ import { readFile, writeFile } from "node:fs/promises";
18
+ import type { MetaDataTypeProvider } from "@metaobjectsdev/metadata";
19
+ import {
20
+ composeRegistry,
21
+ MetaDataLoader,
22
+ InMemoryStringSource,
23
+ canonicalSerialize,
24
+ formatMetadataFile,
25
+ } from "@metaobjectsdev/metadata";
26
+ import { FileSource } from "@metaobjectsdev/metadata/core";
27
+ import { resolveCollection, defaultLoadMemoryProviders, type Collection } from "@metaobjectsdev/sdk";
28
+ import { loadMetaobjectsConfig, loadMemoryOptionsFrom } from "./load-metaobjects-config.js";
29
+
30
+ export type FmtFileStatus =
31
+ | "formatted"
32
+ | "would-format"
33
+ | "unchanged"
34
+ | "skipped-yaml"
35
+ | "skipped-overlay"
36
+ | "error";
37
+
38
+ export interface FmtFileReport {
39
+ readonly path: string;
40
+ readonly status: FmtFileStatus;
41
+ readonly detail?: string;
42
+ }
43
+
44
+ export interface FmtRunResult {
45
+ readonly files: readonly FmtFileReport[];
46
+ /** Set when the run could not even start — an unresolvable collection, an
47
+ * explicit file argument outside the project's sources, or metadata that
48
+ * does not currently load cleanly. Nothing was attempted. */
49
+ readonly fatal?: string;
50
+ }
51
+
52
+ export interface FmtRunOptions {
53
+ readonly projectRoot: string;
54
+ readonly check: boolean;
55
+ /** Explicit paths (cwd-relative or absolute) narrowing the run. Omit/empty
56
+ * for every file the project owns. */
57
+ readonly files?: readonly string[];
58
+ }
59
+
60
+ async function projectProviders(collection: Collection): Promise<readonly MetaDataTypeProvider[]> {
61
+ try {
62
+ const cfg = await loadMetaobjectsConfig(collection.configDir);
63
+ return loadMemoryOptionsFrom(cfg).providers ?? [];
64
+ } catch {
65
+ // No metaobjects.config.ts (common for a non-TS-server project running
66
+ // `meta fmt` just for schema-neutral formatting) — format against the
67
+ // core vocabulary only, exactly like a project with no custom providers.
68
+ return [];
69
+ }
70
+ }
71
+
72
+ export async function runFmt(opts: FmtRunOptions): Promise<FmtRunResult> {
73
+ let collection: Collection;
74
+ try {
75
+ collection = await resolveCollection(opts.projectRoot);
76
+ } catch (err) {
77
+ return { files: [], fatal: err instanceof Error ? err.message : String(err) };
78
+ }
79
+
80
+ const providers = await projectProviders(collection);
81
+ const registry = composeRegistry([...defaultLoadMemoryProviders, ...providers]);
82
+
83
+ let targets: readonly string[];
84
+ if (opts.files !== undefined && opts.files.length > 0) {
85
+ const want = new Set(opts.files.map((f) => resolvePath(opts.projectRoot, f)));
86
+ const owned = new Set(collection.ownFiles);
87
+ const missing = [...want].filter((f) => !owned.has(f));
88
+ if (missing.length > 0) {
89
+ return {
90
+ files: [],
91
+ fatal:
92
+ `not among this project's resolved metadata sources: ${missing.join(", ")}\n` +
93
+ "meta fmt only formats files resolveCollection() already resolves — pass no " +
94
+ "arguments to format every one of them.",
95
+ };
96
+ }
97
+ targets = collection.ownFiles.filter((f) => want.has(f));
98
+ } else {
99
+ targets = collection.ownFiles;
100
+ }
101
+
102
+ const sourceId = (p: string): string => collection.fileIds.get(p) ?? basename(p);
103
+
104
+ const libSources =
105
+ collection.libraries.length > 0
106
+ ? (await import("@metaobjectsdev/metadata/library")).librarySources([...collection.libraries])
107
+ : [];
108
+
109
+ const buildSources = (overridePath?: string, overrideText?: string) => [
110
+ ...libSources,
111
+ ...collection.files.map((p) => {
112
+ const id = sourceId(p);
113
+ return overridePath !== undefined && p === overridePath
114
+ ? new InMemoryStringSource(overrideText ?? "", { id })
115
+ : new FileSource(p, { id });
116
+ }),
117
+ ];
118
+
119
+ const baseline = await new MetaDataLoader({ registry }).load(buildSources());
120
+ if (baseline.errors.length > 0) {
121
+ return {
122
+ files: [],
123
+ fatal:
124
+ "this project's metadata does not currently load cleanly — fix the error(s) below, " +
125
+ "then re-run fmt:\n" +
126
+ baseline.errors.map((e) => ` ${e.message}`).join("\n"),
127
+ };
128
+ }
129
+ const baselineCanonical = canonicalSerialize(baseline.root);
130
+
131
+ const reports: FmtFileReport[] = [];
132
+ for (const path of targets) {
133
+ const ext = extname(path).toLowerCase();
134
+ if (ext === ".yaml" || ext === ".yml") {
135
+ reports.push({
136
+ path,
137
+ status: "skipped-yaml",
138
+ detail: "no canonical YAML emitter exists (ADR-0006: JSON is the canonical interchange form) — left untouched",
139
+ });
140
+ continue;
141
+ }
142
+
143
+ const content = await readFile(path, "utf8");
144
+ const formatted = formatMetadataFile(content, { registry, sourceId: sourceId(path) });
145
+ if (!formatted.ok) {
146
+ reports.push(
147
+ formatted.overlay
148
+ ? { path, status: "skipped-overlay", detail: formatted.message }
149
+ : { path, status: "error", detail: formatted.message },
150
+ );
151
+ continue;
152
+ }
153
+
154
+ if (formatted.text === content) {
155
+ reports.push({ path, status: "unchanged" });
156
+ continue;
157
+ }
158
+
159
+ const testLoad = await new MetaDataLoader({ registry }).load(buildSources(path, formatted.text));
160
+ const safe = testLoad.errors.length === 0 && canonicalSerialize(testLoad.root) === baselineCanonical;
161
+ if (!safe) {
162
+ reports.push({
163
+ path,
164
+ status: "error",
165
+ detail: "formatting this file would change the loaded model's meaning — left unchanged",
166
+ });
167
+ continue;
168
+ }
169
+
170
+ if (opts.check) {
171
+ reports.push({ path, status: "would-format" });
172
+ } else {
173
+ await writeFile(path, formatted.text, "utf8");
174
+ reports.push({ path, status: "formatted" });
175
+ }
176
+ }
177
+
178
+ return { files: reports };
179
+ }
@@ -0,0 +1,106 @@
1
+ // `meta verify` — the node-name AUTHORING lint.
2
+ //
3
+ // The loader accepts any string as a node `name`, on every port. An adopter's metadata
4
+ // carried a field named `"defaultCurrencyId "` (a trailing space, copied from legacy XML)
5
+ // and an identity named `"account_defaultCurrencyId _fk"`; both loaded with no error.
6
+ //
7
+ // WHY THIS IS A WARNING AND NOT A LOAD ERROR. It was weighed against the correction bar
8
+ // in docs/compatibility-policy.md and does not pass it: whitespace names WORK today on
9
+ // the core path — `meta migrate` emits a quoted column (`"default_currency_id "`) and the
10
+ // ObjectManager round-trips the key — and multi-word requirement names are documented to
11
+ // load. Refusing them at load would break metadata that does what its author asked, so
12
+ // the honest instrument is an advisory that names the edit.
13
+ //
14
+ // EVERY FINDING IS A WARNING, BY CONSTRUCTION — the same rule, and the same reasoning,
15
+ // as requirement-lint.ts's header. Nothing here reaches the exit code.
16
+ //
17
+ // REQUIREMENTS ARE NOT LINTED HERE. A requirement's name is its dotted ADDRESS and the
18
+ // requirement lint already owns it (WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE reports
19
+ // leading/trailing whitespace; a short multi-word label such as "Order Recording" is
20
+ // deliberately NOT reported, because renaming one moves its address and its emitted
21
+ // stub file for no gain). Reporting the same name twice under two codes would make
22
+ // one edit look like two problems.
23
+ //
24
+ // IT READS THE LOADED MODEL, NEVER THE FILES — and walks DECLARATIONS (see `walk`).
25
+
26
+ import { PACKAGE_SEPARATOR, TYPE_FIELD, TYPE_REQUIREMENT, type MetaData } from "@metaobjectsdev/metadata";
27
+ import type { Diagnostic } from "./requirement-check.js";
28
+
29
+ /** Leading or trailing whitespace — the strong finding. */
30
+ export const WARN_NAME_SURROUNDING_WHITESPACE = "WARN_NAME_SURROUNDING_WHITESPACE";
31
+ /** Whitespace inside an otherwise trimmed name — the plain advisory. */
32
+ export const WARN_NAME_INTERNAL_WHITESPACE = "WARN_NAME_INTERNAL_WHITESPACE";
33
+
34
+ /**
35
+ * What counts as whitespace: the ECMAScript `\s` class. That is ASCII space, tab, LF,
36
+ * CR, VT and FF, plus U+00A0 (no-break space), U+FEFF, U+1680, U+2000–U+200A, U+2028,
37
+ * U+2029, U+202F, U+205F and U+3000. The non-ASCII members matter for this lint's
38
+ * actual source of input: a no-break space survives a copy out of a document or a
39
+ * legacy export and is invisible in every editor.
40
+ */
41
+ const WHITESPACE = /\s/u;
42
+
43
+ function warn(path: string, code: string, message: string): Diagnostic {
44
+ return { severity: "warn", code, path, message };
45
+ }
46
+
47
+ /** One segment of a node's address. A name with whitespace is quoted so the
48
+ * whitespace is visible in the printed path rather than vanishing into it. */
49
+ function segment(name: string): string {
50
+ return WHITESPACE.test(name) ? JSON.stringify(name) : name;
51
+ }
52
+
53
+ function check(node: MetaData, path: string, out: Diagnostic[]): void {
54
+ const name = node.name;
55
+ if (name === "" || !WHITESPACE.test(name)) return;
56
+
57
+ const kind = `${node.type}.${node.subType}`;
58
+ const quoted = JSON.stringify(name);
59
+ // @column is a FIELD attribute. Advising an object or identity author to pin it
60
+ // would send them looking for a slot that does not exist on the node.
61
+ const pin = node.type === TYPE_FIELD ? ", and pin @column if the physical column must keep its name" : "";
62
+ const trimmed = name.trim();
63
+
64
+ if (trimmed !== name) {
65
+ const inner = WHITESPACE.test(trimmed) ? " It also contains whitespace inside it." : "";
66
+ const target = trimmed === "" ? "" : ` (to ${JSON.stringify(trimmed)}, presumably)`;
67
+ out.push(warn(path, WARN_NAME_SURROUNDING_WHITESPACE,
68
+ `${kind} name ${quoted} has leading or trailing whitespace, which is almost certainly ` +
69
+ `unintended — rename it${target}${pin}. The whitespace is carried into every identifier, ` +
70
+ `column and wire key derived from the name.${inner}`));
71
+ return;
72
+ }
73
+
74
+ out.push(warn(path, WARN_NAME_INTERNAL_WHITESPACE,
75
+ `${kind} name ${quoted} contains whitespace. A name is an identifier: derived column names ` +
76
+ `and wire keys carry the space, and generated code cannot use it as one. Consider ` +
77
+ `renaming it${pin}.`));
78
+ }
79
+
80
+ /** A root-level node's address: package-qualified the way `resolutionKey()` is, so the
81
+ * path reads like every other reference to the node. */
82
+ function topLevelAddress(node: MetaData): string {
83
+ const pkg = node.package ?? node.fileDefaultPackage;
84
+ return pkg !== undefined && pkg !== "" ? `${pkg}${PACKAGE_SEPARATOR}${segment(node.name)}` : segment(node.name);
85
+ }
86
+
87
+ /**
88
+ * Lint the name of every named node in the loaded model, requirements excepted.
89
+ * Returns `[]` for a model with no whitespace in any name.
90
+ */
91
+ export function lintNodeNames(root: MetaData): Diagnostic[] {
92
+ const out: Diagnostic[] = [];
93
+ const walk = (n: MetaData, prefix: string): void => {
94
+ // OWN-ONLY (ADR-0039 sanctioned case): this reports each DECLARATION once, at the
95
+ // node that declares it. A field inherited through `extends` is one declaration and
96
+ // one rename; the resolving `children()` would repeat it on every subtype.
97
+ for (const c of n.ownChildren()) {
98
+ if (c.type === TYPE_REQUIREMENT) continue; // owned by requirement-lint.ts — see header
99
+ const path = prefix === "" ? topLevelAddress(c) : `${prefix}.${segment(c.name)}`;
100
+ check(c, path, out);
101
+ walk(c, path);
102
+ }
103
+ };
104
+ walk(root, "");
105
+ return out;
106
+ }
@@ -0,0 +1,74 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
+ import { OWNED_RUNTIME_DIR, HTTP_RUNTIME_PACKAGE } from "@metaobjectsdev/codegen-ts";
4
+
5
+ /**
6
+ * Generated code that imports the owned HTTP-adapter copy from OUTSIDE its own
7
+ * workspace package.
8
+ *
9
+ * Since 1.0.9 an ejected `entity` / `routes` / `routes-hono` generator points its output
10
+ * at `codegen/runtime/` (the adapter source `meta eject` copied) by a path relative to
11
+ * the output directory. In a single-package project that is exactly right. In a monorepo
12
+ * whose output sits inside a workspace package (`apps/api/src/generated`), the path climbs
13
+ * out of that package: `tsc` rejects the file (`TS6059 … is not under 'rootDir'`), and the
14
+ * copy's own bare imports (`qs`, `fastify`) do not resolve from the repository root. The
15
+ * `meta gen` run itself is green; the adopter's build is the first thing that disagrees.
16
+ *
17
+ * Found upgrading a pnpm monorepo. This names the package and the two ways out. It is a
18
+ * warning and never changes an exit code.
19
+ */
20
+ export interface RuntimeBoundaryFinding {
21
+ /** Project-relative directory of the workspace package the generated file sits in. */
22
+ packageDir: string;
23
+ /** One generated file (project-relative) that crosses the boundary. */
24
+ example: string;
25
+ }
26
+
27
+ const IMPORT_SPEC = /\bfrom\s+["'](\.{1,2}\/[^"']+)["']/g;
28
+
29
+ function nearestPackageDir(fileDir: string, projectRoot: string): string | undefined {
30
+ for (let d = fileDir; ; d = dirname(d)) {
31
+ if (d === projectRoot || !d.startsWith(projectRoot + sep)) return undefined;
32
+ if (existsSync(join(d, "package.json"))) return d;
33
+ }
34
+ }
35
+
36
+ function isInside(child: string, parent: string): boolean {
37
+ return child === parent || child.startsWith(parent + sep);
38
+ }
39
+
40
+ export function findRuntimeBoundaryCrossings(
41
+ projectRoot: string,
42
+ generatedFiles: readonly string[],
43
+ ): RuntimeBoundaryFinding[] {
44
+ const root = resolve(projectRoot);
45
+ const runtimeRoot = join(root, OWNED_RUNTIME_DIR);
46
+ const byPackage = new Map<string, RuntimeBoundaryFinding>();
47
+ for (const file of generatedFiles) {
48
+ if (!/\.(ts|tsx|mts)$/.test(file) || !existsSync(file)) continue;
49
+ const abs = resolve(file);
50
+ const pkgDir = nearestPackageDir(dirname(abs), root);
51
+ if (pkgDir === undefined || isInside(runtimeRoot, pkgDir) || byPackage.has(pkgDir)) continue;
52
+ const text = readFileSync(abs, "utf8");
53
+ for (const m of text.matchAll(IMPORT_SPEC)) {
54
+ if (isInside(resolve(dirname(abs), m[1]!), runtimeRoot)) {
55
+ byPackage.set(pkgDir, {
56
+ packageDir: relative(root, pkgDir).split(sep).join("/"),
57
+ example: relative(root, abs).split(sep).join("/"),
58
+ });
59
+ break;
60
+ }
61
+ }
62
+ }
63
+ return [...byPackage.values()];
64
+ }
65
+
66
+ export function runtimeBoundaryWarnings(findings: readonly RuntimeBoundaryFinding[]): string[] {
67
+ return findings.map((f) =>
68
+ `generated code in ${f.packageDir}/ imports the owned HTTP adapter from ${OWNED_RUNTIME_DIR}/, ` +
69
+ `outside that workspace package (e.g. ${f.example}); its build will not resolve it. ` +
70
+ `Either keep importing the published adapter — pass \`runtimeImport: "${HTTP_RUNTIME_PACKAGE}"\` ` +
71
+ `to the ejected entity/routes generators — or move ${OWNED_RUNTIME_DIR}/ inside ${f.packageDir}/ ` +
72
+ `and point \`runtimeImport\` at it.`,
73
+ );
74
+ }