@pbuilder/sdk 0.16.0 → 0.18.0

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 (69) hide show
  1. package/README.md +75 -1
  2. package/dist/bin/pbuilder-conformance.d.ts +2 -0
  3. package/dist/bin/pbuilder-conformance.js +26 -0
  4. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +7 -1
  5. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +2 -1
  6. package/dist/bounded-contexts/authoring/application/usecases/scaffold/expander.js +4 -4
  7. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +1 -0
  8. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +54 -4
  9. package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.d.ts +2 -1
  10. package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.js +108 -30
  11. package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +48 -10
  12. package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +37 -9
  13. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +2 -2
  14. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +51 -0
  15. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +49 -0
  16. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +11 -0
  17. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +139 -0
  18. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ast.d.ts +29 -0
  19. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ast.js +41 -0
  20. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.d.ts +44 -0
  21. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.js +45 -0
  22. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/names.d.ts +7 -0
  23. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/names.js +72 -0
  24. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ops.d.ts +19 -0
  25. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ops.js +255 -0
  26. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/pack.d.ts +9 -0
  27. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/pack.js +2 -0
  28. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/syntax.d.ts +26 -0
  29. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/syntax.js +111 -0
  30. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/tree-sitter-c_sharp.LICENSE +23 -0
  31. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/tree-sitter-c_sharp.wasm +0 -0
  32. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ast.d.ts +22 -0
  33. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ast.js +17 -0
  34. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +55 -0
  35. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +54 -0
  36. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +7 -0
  37. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +162 -0
  38. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/xml.d.ts +20 -0
  39. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/xml.js +50 -0
  40. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +2 -2
  41. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.d.ts +2 -0
  42. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.js +4 -0
  43. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +3 -3
  44. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.d.ts +2 -0
  45. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.js +4 -0
  46. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +2 -2
  47. package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +10 -12
  48. package/dist/bounded-contexts/authoring/testing/conformance/index.js +17 -2
  49. package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +20 -0
  50. package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +129 -0
  51. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +3 -0
  52. package/dist/bounded-contexts/authoring/testing/harness/index.js +5 -1
  53. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  54. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +2 -0
  55. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +42 -3
  56. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +13 -0
  57. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +25 -1
  58. package/dist/conformance/index.d.ts +1 -0
  59. package/dist/conformance/index.js +1 -0
  60. package/dist/dialect/index.d.ts +2 -0
  61. package/dist/dialect/index.js +3 -0
  62. package/dist/dialects/aspnet/index.d.ts +1 -0
  63. package/dist/dialects/aspnet/index.js +1 -0
  64. package/dist/dialects/csharp/index.d.ts +1 -0
  65. package/dist/dialects/csharp/index.js +1 -0
  66. package/dist/dialects/msbuild/index.d.ts +1 -0
  67. package/dist/dialects/msbuild/index.js +1 -0
  68. package/dist/runner-manifest.json +10 -6
  69. package/package.json +27 -3
@@ -0,0 +1,54 @@
1
+ import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
2
+ import { parse, print } from "./ast.js";
3
+ import { addProject, addProjectReference } from "./ops.js";
4
+ export * as astLibrary from "saxes";
5
+ const opsPack = defineOpPack({ addProjectReference, addProject });
6
+ const msbuildDialect = withOps(defineDialect({ extensions: [".csproj", ".props", ".targets", ".slnx"], ast: { parse, print }, ops: {} }), opsPack);
7
+ /**
8
+ * Opens a `.csproj`, `.props`, `.targets` or `.slnx` file. `addProjectReference(path)` edits a
9
+ * file whose root element is `Project`; `addProject(path, { folder? })` adds a project to a `.slnx`
10
+ * `<Solution>`, in the solution folder `folder` (such as `/src/`) when given. The
11
+ * dialect edits the XML text and changes only the bytes it must: the XML declaration, comments,
12
+ * attribute quotes, indentation, line endings, a BOM, and the final newline survive. The classic
13
+ * `.sln` format and any other extension throw synchronously with the `dialect operation failed: `
14
+ * prefix, and a file that is not well-formed XML fails the factory. `.modify(fn)` hands `fn` the
15
+ * live `MsbuildDocument`; edit its `text`, reading offsets with `astLibrary` (`saxes`), for
16
+ * anything the op does not cover.
17
+ *
18
+ * @example
19
+ * import * as msbuild from "@pbuilder/sdk/msbuild";
20
+ *
21
+ * // Shop.Infrastructure.csproj before:
22
+ * // <Project Sdk="Microsoft.NET.Sdk">\n <PropertyGroup>\n <TargetFramework>net10.0</TargetFramework>\n </PropertyGroup>\n</Project>\n
23
+ * export const run = async () => {
24
+ * await msbuild
25
+ * .find("src/Shop.Infrastructure/Shop.Infrastructure.csproj")
26
+ * .addProjectReference("../Shop.Application/Shop.Application.csproj");
27
+ * };
28
+ * // -> <Project Sdk="Microsoft.NET.Sdk">
29
+ * // -> <PropertyGroup>
30
+ * // -> <TargetFramework>net10.0</TargetFramework>
31
+ * // -> </PropertyGroup>
32
+ * // ->
33
+ * // -> <ItemGroup>
34
+ * // -> <ProjectReference Include="../Shop.Application/Shop.Application.csproj" />
35
+ * // -> </ItemGroup>
36
+ * // -> </Project>
37
+ *
38
+ * @example
39
+ * import * as msbuild from "@pbuilder/sdk/msbuild";
40
+ *
41
+ * // Shop.slnx before:
42
+ * // <Solution>\n</Solution>\n
43
+ * export const run = async () => {
44
+ * await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
45
+ * };
46
+ * // -> <Solution>
47
+ * // -> <Folder Name="/src/">
48
+ * // -> <Project Path="src/Shop.Api/Shop.Api.csproj" />
49
+ * // -> </Folder>
50
+ * // -> </Solution>
51
+ */
52
+ export function find(path) {
53
+ return msbuildDialect.find(path);
54
+ }
@@ -0,0 +1,7 @@
1
+ import type { MsbuildDocument } from "./ast.ts";
2
+ export interface ProjectOptions {
3
+ /** The solution folder that holds the project, such as `/src/`; it is created when missing. */
4
+ folder?: string;
5
+ }
6
+ export declare const addProjectReference: (ast: MsbuildDocument, path: string) => void;
7
+ export declare const addProject: (ast: MsbuildDocument, path: string, options?: ProjectOptions | undefined) => void;
@@ -0,0 +1,162 @@
1
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
2
+ import { validatedOp } from "../../../../domain/services/identifier-names.js";
3
+ import { readElements } from "./xml.js";
4
+ const OP = "addProjectReference";
5
+ const ADD_PROJECT = "addProject";
6
+ const DEFAULT_UNIT = " ";
7
+ function assertPath(op, path) {
8
+ const rule = "a relative path whose file name ends in `proj`";
9
+ if (typeof path !== "string")
10
+ throw dialectError(`${op} — \`path\` must be ${rule}.`);
11
+ const fileName = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
12
+ if (/^([/\\]|[A-Za-z]:)/.test(path) || !fileName.endsWith("proj")) {
13
+ throw dialectError(`${op} — \`path\` ${JSON.stringify(path)} is not ${rule}.`);
14
+ }
15
+ }
16
+ /** The root element of `doc`, rejecting malformed XML and any root not named `name`. */
17
+ function readRoot(doc, op, path, name) {
18
+ let root;
19
+ try {
20
+ root = readElements(doc.text);
21
+ }
22
+ catch {
23
+ throw dialectError(`${op}(${JSON.stringify(path)}) — the file is not well-formed XML.`);
24
+ }
25
+ if (root?.name !== name) {
26
+ const found = root === undefined ? "the file has no root element" : `the root element is \`${root.name}\``;
27
+ throw dialectError(`${op}(${JSON.stringify(path)}) — ${found}; it needs \`${name}\`.`);
28
+ }
29
+ return root;
30
+ }
31
+ function escapeAttribute(value) {
32
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
33
+ }
34
+ const sameReference = (a, b) => a.replace(/\\/g, "/") === b.replace(/\\/g, "/");
35
+ /** The whitespace before `offset` on its line, or `undefined` when other text precedes it there. */
36
+ function lineIndent(text, offset) {
37
+ const prefix = text.slice(text.lastIndexOf("\n", offset - 1) + 1, offset);
38
+ return /^[ \t]*$/.test(prefix) ? prefix : undefined;
39
+ }
40
+ /** The first indentation step the file shows between an element and its parent, else two spaces. */
41
+ function indentUnit(text, root) {
42
+ const parents = [root];
43
+ for (const parent of parents) {
44
+ const outer = lineIndent(text, parent.start);
45
+ for (const child of parent.children) {
46
+ const inner = lineIndent(text, child.start);
47
+ if (outer !== undefined && inner !== undefined && inner.length > outer.length && inner.startsWith(outer)) {
48
+ return inner.slice(outer.length);
49
+ }
50
+ parents.push(child);
51
+ }
52
+ }
53
+ return DEFAULT_UNIT;
54
+ }
55
+ function* descendants(element) {
56
+ for (const child of element.children) {
57
+ yield child;
58
+ yield* descendants(child);
59
+ }
60
+ }
61
+ function splice(doc, from, to, insert) {
62
+ doc.text = doc.text.slice(0, from) + insert + doc.text.slice(to);
63
+ }
64
+ /** Puts `block`, already indented one unit deeper than `element`, inside an `element` with no children. */
65
+ function openEmpty(doc, element, block, eol) {
66
+ const text = doc.text;
67
+ const indent = lineIndent(text, element.start) ?? "";
68
+ if (element.selfClosing) {
69
+ let cut = text.lastIndexOf("/", element.end - 1);
70
+ while (/\s/.test(text[cut - 1]))
71
+ cut--;
72
+ splice(doc, cut, element.end, `>${eol}${block}${eol}${indent}</${element.name}>`);
73
+ }
74
+ else {
75
+ const closeOnOwnLine = text.slice(element.openEnd, element.closeStart).includes("\n");
76
+ splice(doc, element.openEnd, element.openEnd, `${eol}${block}${closeOnOwnLine ? "" : eol + indent}`);
77
+ }
78
+ }
79
+ export const addProjectReference = validatedOp(([path]) => assertPath(OP, path), (doc, path) => {
80
+ const project = readRoot(doc, OP, path, "Project");
81
+ for (const element of descendants(project)) {
82
+ const include = element.attributes.get("Include");
83
+ if (element.name === "ProjectReference" && include !== undefined && sameReference(include, path))
84
+ return;
85
+ }
86
+ const text = doc.text;
87
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
88
+ const unit = indentUnit(text, project);
89
+ const reference = `<ProjectReference Include="${escapeAttribute(path)}" />`;
90
+ const group = project.children.find((child) => child.name === "ItemGroup" && !child.attributes.has("Condition") && child.children.some((c) => c.name === "ProjectReference"));
91
+ if (group !== undefined) {
92
+ const last = group.children.filter((c) => c.name === "ProjectReference").at(-1);
93
+ const indent = lineIndent(text, last.start) ?? (lineIndent(text, group.start) ?? "") + unit;
94
+ splice(doc, last.end, last.end, `${eol}${indent}${reference}`);
95
+ return;
96
+ }
97
+ const projectIndent = lineIndent(text, project.start) ?? "";
98
+ const last = project.children.at(-1);
99
+ const indent = (last && lineIndent(text, last.start)) ?? projectIndent + unit;
100
+ const block = `${indent}<ItemGroup>${eol}${indent}${unit}${reference}${eol}${indent}</ItemGroup>`;
101
+ if (last !== undefined) {
102
+ splice(doc, last.end, last.end, `${eol}${eol}${block}`);
103
+ }
104
+ else {
105
+ openEmpty(doc, project, block, eol);
106
+ }
107
+ });
108
+ function assertFolder(folder) {
109
+ if (typeof folder !== "string" || !/^\/([^/]+\/)+$/.test(folder)) {
110
+ throw dialectError(`${ADD_PROJECT} — \`options.folder\` ${JSON.stringify(folder)} is not a solution folder name: \`/\` followed by one or more non-empty segments that each end in \`/\`, such as "/src/" or "/src/Core/".`);
111
+ }
112
+ }
113
+ const isProject = (element) => element.name === "Project";
114
+ export const addProject = validatedOp(([path, options]) => {
115
+ assertPath(ADD_PROJECT, path);
116
+ if (options === undefined)
117
+ return;
118
+ if (typeof options !== "object" || options === null || Array.isArray(options) || Object.keys(options).some((key) => key !== "folder")) {
119
+ throw dialectError(`${ADD_PROJECT} — \`options\` must be an object holding only \`folder\`.`);
120
+ }
121
+ if (options.folder !== undefined)
122
+ assertFolder(options.folder);
123
+ }, (doc, path, options) => {
124
+ const solution = readRoot(doc, ADD_PROJECT, path, "Solution");
125
+ const folderName = options?.folder;
126
+ const folder = folderName === undefined ? solution : solution.children.find((c) => c.name === "Folder" && c.attributes.get("Name") === folderName);
127
+ const samePath = (element) => {
128
+ const projectPath = element.attributes.get("Path");
129
+ return isProject(element) && projectPath !== undefined && sameReference(projectPath, path);
130
+ };
131
+ if (folder?.children.some(samePath))
132
+ return;
133
+ if ([...descendants(solution)].some(samePath)) {
134
+ throw dialectError(`${ADD_PROJECT}(${JSON.stringify(path)}) — the solution already holds this project at another place; move it with .modify().`);
135
+ }
136
+ const text = doc.text;
137
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
138
+ const unit = indentUnit(text, solution);
139
+ const entry = `<Project Path="${escapeAttribute(path)}" />`;
140
+ /** `line` indented under `parent`, after its child `after`, or as its only child. */
141
+ const append = (parent, after, line) => {
142
+ const indent = (after && lineIndent(text, after.start)) ?? (lineIndent(text, parent.start) ?? "") + unit;
143
+ if (after === undefined)
144
+ openEmpty(doc, parent, line(indent), eol);
145
+ else
146
+ splice(doc, after.end, after.end, `${eol}${line(indent)}`);
147
+ };
148
+ if (folder !== undefined) {
149
+ append(folder, folder.children.filter(isProject).at(-1) ?? folder.children.at(-1), (indent) => `${indent}${entry}`);
150
+ return;
151
+ }
152
+ const block = (indent) => `${indent}<Folder Name="${escapeAttribute(folderName)}">${eol}${indent}${unit}${entry}${eol}${indent}</Folder>`;
153
+ const lastFolder = solution.children.filter((c) => c.name === "Folder").at(-1);
154
+ const first = solution.children[0];
155
+ const firstIndent = first && lineIndent(text, first.start);
156
+ if (lastFolder !== undefined || first === undefined || firstIndent === undefined) {
157
+ append(solution, lastFolder ?? solution.children.at(-1), block);
158
+ }
159
+ else {
160
+ splice(doc, first.start, first.start, `${block(firstIndent).slice(firstIndent.length)}${eol}${firstIndent}`);
161
+ }
162
+ });
@@ -0,0 +1,20 @@
1
+ /**
2
+ * One element with its source offsets: `start` is its `<`, `openEnd` is just past its open
3
+ * tag's `>`, `closeStart` is the `<` of its close tag, and `end` is just past the element.
4
+ * A self-closing element has `openEnd === closeStart === end`.
5
+ */
6
+ export interface XmlElement {
7
+ name: string;
8
+ attributes: ReadonlyMap<string, string>;
9
+ start: number;
10
+ openEnd: number;
11
+ closeStart: number;
12
+ end: number;
13
+ selfClosing: boolean;
14
+ children: XmlElement[];
15
+ }
16
+ /**
17
+ * Reads the element tree of `text`, or `undefined` for an empty text, throwing on anything
18
+ * that is not well-formed XML 1.0.
19
+ */
20
+ export declare function readElements(text: string): XmlElement | undefined;
@@ -0,0 +1,50 @@
1
+ import { SaxesParser } from "saxes";
2
+ /**
3
+ * Reads the element tree of `text`, or `undefined` for an empty text, throwing on anything
4
+ * that is not well-formed XML 1.0.
5
+ */
6
+ export function readElements(text) {
7
+ if (text === "")
8
+ return undefined;
9
+ const parser = new SaxesParser({ position: true });
10
+ const stack = [];
11
+ let root;
12
+ let failed = false;
13
+ parser.on("error", () => {
14
+ failed = true;
15
+ });
16
+ // `position` sits just past the tag's `>`; a raw `<` cannot occur inside a tag, so the last
17
+ // one before it is the tag's start.
18
+ parser.on("opentag", (node) => {
19
+ const openEnd = parser.position;
20
+ const element = {
21
+ name: node.name,
22
+ attributes: new Map(Object.entries(node.attributes)),
23
+ start: text.lastIndexOf("<", openEnd - 1),
24
+ openEnd,
25
+ closeStart: openEnd,
26
+ end: openEnd,
27
+ selfClosing: node.isSelfClosing,
28
+ children: [],
29
+ };
30
+ (stack.at(-1)?.children ?? []).push(element);
31
+ root ??= element;
32
+ stack.push(element);
33
+ });
34
+ parser.on("closetag", () => {
35
+ const element = stack.pop();
36
+ if (element.selfClosing)
37
+ return;
38
+ element.end = parser.position;
39
+ element.closeStart = text.lastIndexOf("<", element.end - 1);
40
+ });
41
+ try {
42
+ parser.write(text).close();
43
+ }
44
+ catch {
45
+ failed = true;
46
+ }
47
+ if (failed || root === undefined)
48
+ throw new Error("invalid XML");
49
+ return root;
50
+ }
@@ -1,12 +1,12 @@
1
1
  import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
2
- import { parse, print } from "../typescript/ast.js";
2
+ import { parse, print, retire } from "../typescript/ast.js";
3
3
  import { typescriptOps } from "../typescript/pack.js";
4
4
  import { addController, addExport, addModuleImport, addProvider } from "./ops.js";
5
5
  export * as astLibrary from "ts-morph";
6
6
  const moduleOps = defineOpPack({ addProvider, addController, addModuleImport, addExport });
7
7
  const baseDialect = defineDialect({
8
8
  extensions: [".ts"],
9
- ast: { parse, print },
9
+ ast: { parse, print, retire },
10
10
  ops: {},
11
11
  });
12
12
  const nestjsDialect = withOps(baseDialect, typescriptOps, moduleOps);
@@ -26,3 +26,5 @@ export declare function parseJsx(source: string): SourceFile;
26
26
  * own `getFullText()` does not carry it.
27
27
  */
28
28
  export declare function print(ast: SourceFile): string;
29
+ /** Forgets a tree the handle re-parsed away from, so every node kept from it throws when used (A-8). */
30
+ export declare function retire(ast: SourceFile): void;
@@ -98,3 +98,7 @@ export function print(ast) {
98
98
  const text = ast.getFullText();
99
99
  return hadBom.get(ast) === true ? BOM + text : text;
100
100
  }
101
+ /** Forgets a tree the handle re-parsed away from, so every node kept from it throws when used (A-8). */
102
+ export function retire(ast) {
103
+ ast.forget();
104
+ }
@@ -8,12 +8,12 @@ import { byExtension, defineDialect, defineOpPack, overrideOps, withOps, without
8
8
  import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
9
9
  import { addClassProperty } from "../typescript/class-property.js";
10
10
  import { typescriptOps } from "../typescript/pack.js";
11
- import { parse, parseJsx, print } from "./ast.js";
11
+ import { parse, parseJsx, print, retire } from "./ast.js";
12
12
  import { addComponentProp, addHookCall, addJsxChild, removeJsxProp, renameJsxElement, setJsxProp, wrapJsxElement, } from "./ops.js";
13
13
  export * as astLibrary from "ts-morph";
14
14
  const jsxOps = defineOpPack({ setJsxProp, removeJsxProp, addJsxChild, wrapJsxElement, addHookCall, addComponentProp, renameJsxElement });
15
- const tsxDialect = withOps(defineDialect({ extensions: [".tsx"], ast: { parse, print }, ops: {} }), typescriptOps, jsxOps);
16
- const jsxDialect = overrideOps(withoutOps(defineDialect({ extensions: [".jsx"], ast: { parse: parseJsx, print }, ops: tsxDialect.ops }), ["addTypeImport", "addComponentProp"], "they write TypeScript type syntax, which a .jsx file cannot hold"), {
15
+ const tsxDialect = withOps(defineDialect({ extensions: [".tsx"], ast: { parse, print, retire }, ops: {} }), typescriptOps, jsxOps);
16
+ const jsxDialect = overrideOps(withoutOps(defineDialect({ extensions: [".jsx"], ast: { parse: parseJsx, print, retire }, ops: tsxDialect.ops }), ["addTypeImport", "addComponentProp"], "they write TypeScript type syntax, which a .jsx file cannot hold"), {
17
17
  addClassProperty: (ast, className, name, initializer, options) => {
18
18
  if (options?.scope !== undefined || options?.readonly !== undefined) {
19
19
  throw dialectError("addClassProperty's `scope` and `readonly` are TypeScript modifiers, which a .jsx file cannot hold — " +
@@ -45,3 +45,5 @@ export declare function parse(source: string, extension?: ".ts" | ".tsx" | ".jsx
45
45
  */
46
46
  export declare function print(ast: SourceFile): string;
47
47
  export declare function omitsSemicolons(ast: SourceFile): boolean;
48
+ /** Forgets a tree the handle re-parsed away from, so every node kept from it throws when used (A-8). */
49
+ export declare function retire(ast: SourceFile): void;
@@ -121,3 +121,7 @@ export function omitsSemicolons(ast) {
121
121
  const terminated = terminable.filter((statement) => statement.getText().endsWith(";")).length;
122
122
  return terminable.length - terminated > terminated;
123
123
  }
124
+ /** Forgets a tree the handle re-parsed away from, so every node kept from it throws when used (A-8). */
125
+ export function retire(ast) {
126
+ ast.forget();
127
+ }
@@ -6,13 +6,13 @@
6
6
  // Namespace import surface (ADR-0003): `import * as ts from "@pbuilder/sdk/typescript"`,
7
7
  // then `ts.find(path)`.
8
8
  import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
9
- import { parse, print } from "./ast.js";
9
+ import { parse, print, retire } from "./ast.js";
10
10
  import { typescriptOps } from "./pack.js";
11
11
  export * as astLibrary from "ts-morph";
12
12
  const opsPack = defineOpPack(typescriptOps);
13
13
  const baseDialect = defineDialect({
14
14
  extensions: [".ts"],
15
- ast: { parse, print },
15
+ ast: { parse, print, retire },
16
16
  ops: {},
17
17
  });
18
18
  const typescriptDialect = withOps(baseDialect, opsPack);
@@ -59,6 +59,16 @@ export interface DialectFixture<Library extends object = object> {
59
59
  expect: string;
60
60
  modify: (ast: unknown, library: Library) => void;
61
61
  };
62
+ /**
63
+ * A-11 stale nodes, for a dialect whose AST hands out nodes: `keep` takes a node from a tree
64
+ * parsed from `seed`, and `use` edits through it. After the tree is re-parsed and retired,
65
+ * `use` must throw.
66
+ */
67
+ staleNode?: {
68
+ seed: string;
69
+ keep: (ast: unknown) => unknown;
70
+ use: (node: unknown) => void;
71
+ };
62
72
  }
63
73
  /**
64
74
  * One op-invocation recipe `testOpPack` applies to a seeded target: seed the file, run the
@@ -117,18 +127,6 @@ export interface OpPackFixture {
117
127
  /** The op-invocation recipes `testOpPack` applies — REQUIRED (rev 5, ADR-0012 amendment). */
118
128
  exercises: readonly OpExercise[];
119
129
  }
120
- /**
121
- * Runs the conformance suite for a dialect: asserts parse/print no-op round-trip fidelity
122
- * (REQ-DC-01) — `print(parse(sample)) === sample` BYTE-EXACT, never AST-equal, for every
123
- * sample in `fixture.samples` PLUS the four mandatory adversarial samples the kit injects on
124
- * every run (REQ-DC-06 — additive, not opt-out-able). Before each round-trip check, verifies
125
- * `fixture.dialect.ast.parse` is a REAL parser, not an identity/stub function (REQ-DC-08): a
126
- * `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
127
- * round-trip assertion could vacuously pass.
128
- *
129
- * Requires runtime library exports matching independent adapter evidence, then exercises
130
- * the actual module's `find().modify()` through a real run with byte-exact emitted output.
131
- */
132
130
  export declare function testDialect<Library extends object>(fixture: DialectFixture<Library>): Promise<void>;
133
131
  /**
134
132
  * Runs the conformance suite for an op-pack against a REAL base dialect (never a mock,
@@ -61,7 +61,7 @@ async function runExercise(dialect, exercise, opts) {
61
61
  }
62
62
  }
63
63
  await handle;
64
- });
64
+ }, { declaredDialects: dialect.name === undefined ? [] : [dialect.name] });
65
65
  await runner(undefined, { client });
66
66
  const directives = emitted.flatMap((b) => b.instructions);
67
67
  const modifies = directives
@@ -150,6 +150,19 @@ function runRoundTripProbe(dialectAst, samples, label) {
150
150
  * Requires runtime library exports matching independent adapter evidence, then exercises
151
151
  * the actual module's `find().modify()` through a real run with byte-exact emitted output.
152
152
  */
153
+ function probeStaleNode(ast, staleNode) {
154
+ const old = ast.parse(staleNode.seed);
155
+ const node = staleNode.keep(old);
156
+ ast.parse(staleNode.seed);
157
+ ast.retire?.(old);
158
+ try {
159
+ staleNode.use(node);
160
+ }
161
+ catch {
162
+ return;
163
+ }
164
+ throw new Error("testDialect: A-11 stale node — a node kept from before a re-parse is still usable; give the dialect's ast a retire(ast) that makes the old tree's nodes fail");
165
+ }
153
166
  export async function testDialect(fixture) {
154
167
  const module = fixture.module;
155
168
  if (!module || typeof module.find !== "function") {
@@ -170,6 +183,8 @@ export async function testDialect(fixture) {
170
183
  }
171
184
  const samples = [...fixture.samples, ...mandatoryAdversarialSamples(fixture.libraryExercise.seed)];
172
185
  runRoundTripProbe(fixture.dialect.ast, samples, "testDialect");
186
+ if (fixture.staleNode !== undefined)
187
+ probeStaleNode(fixture.dialect.ast, fixture.staleNode);
173
188
  const exercise = fixture.libraryExercise;
174
189
  const { client, emitted } = createRunVehicle({ [exercise.path]: exercise.seed });
175
190
  // A-11: `find` must reject an extension the dialect does not declare. Probed inside the run,
@@ -184,7 +199,7 @@ export async function testDialect(fixture) {
184
199
  acceptedUndeclared = false;
185
200
  }
186
201
  await module.find(exercise.path).modify((ast) => exercise.modify(ast, module.astLibrary));
187
- });
202
+ }, { declaredDialects: fixture.dialect.name === undefined ? [] : [fixture.dialect.name] });
188
203
  await run(undefined, { client });
189
204
  if (acceptedUndeclared) {
190
205
  throw new Error(`testDialect: find accepted "${undeclaredPath}", an undeclared extension (A-11)`);
@@ -0,0 +1,20 @@
1
+ export interface ConformanceFailure {
2
+ case: string;
3
+ reason: string;
4
+ }
5
+ export interface ConformanceReport {
6
+ passed: boolean;
7
+ dialect: string;
8
+ version: string;
9
+ failures: ConformanceFailure[];
10
+ }
11
+ /**
12
+ * Loads the fixture of the dialect package in `dir` and runs it. Throws only when the fixture
13
+ * cannot run: the package.json is unreadable or has no name, or a module the fixture imports
14
+ * cannot be resolved. Every finding about the dialect is a failure in the report.
15
+ *
16
+ * @example
17
+ * const report = await checkDialectPackage("/cache/npm/@company/ini-dialect/1.0.0/package");
18
+ * if (!report.passed) console.log(report.failures.map((failure) => failure.case));
19
+ */
20
+ export declare function checkDialectPackage(dir: string): Promise<ConformanceReport>;
@@ -0,0 +1,129 @@
1
+ // CA-13 / A-16: runs the conformance fixture a dialect package ships as `<pkg>/conformance`. The
2
+ // report names each broken check by a fixed case and reason, never by the fixture's own message,
3
+ // which may carry the author's samples or the text of an error their code threw (A-87).
4
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
5
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
6
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
7
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
8
+ });
9
+ }
10
+ return path;
11
+ };
12
+ import { readFileSync } from "node:fs";
13
+ import { isAbsolute, join, relative, resolve } from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import { testDialect } from "./index.js";
16
+ const FIXTURE_MISSING = {
17
+ case: "fixture_missing",
18
+ reason: "CA-13: the package exports no ./conformance fixture",
19
+ };
20
+ const FIXTURE_INVALID = {
21
+ case: "fixture_invalid",
22
+ reason: "CA-13: the default export of ./conformance is not a DialectFixture",
23
+ };
24
+ const NAME_MISMATCH = {
25
+ case: "name_mismatch",
26
+ reason: "A-16: the dialect's name is not the name of its package",
27
+ };
28
+ // Matched against testDialect's own message text, first match wins.
29
+ const CHECKS = [
30
+ ["REQ-DC-08", { case: "real_parse", reason: "A-11: parse must return an AST distinct from the source" }],
31
+ ["REQ-DC-01", { case: "round_trip", reason: "A-11: print(parse(source)) must give back the source byte for byte" }],
32
+ ["stale node", { case: "stale_node", reason: "A-11: a node kept from before a re-parse must fail when used" }],
33
+ ["undeclared extension", { case: "undeclared_extension", reason: "A-11: find must reject an extension the dialect does not declare" }],
34
+ ["library exercise", { case: "library_exercise", reason: "A-11: the library exercise must emit exactly the expected modify" }],
35
+ ["testDialect: module must", { case: "module_shape", reason: "A-11: the module must expose a callable find and its runtime astLibrary" }],
36
+ ["expectedAstLibrary", { case: "module_shape", reason: "A-11: the module must expose a callable find and its runtime astLibrary" }],
37
+ ["astLibrary runtime library mismatch", { case: "module_shape", reason: "A-11: the module's astLibrary must be the adapter's own library" }],
38
+ ];
39
+ const FIXTURE_THREW = { case: "fixture_threw", reason: "A-11: the fixture's own code threw while it ran" };
40
+ function classify(err) {
41
+ const message = err instanceof Error ? err.message : "";
42
+ return CHECKS.find(([marker]) => message.includes(marker))?.[1] ?? FIXTURE_THREW;
43
+ }
44
+ function conformanceTarget(exports) {
45
+ if (typeof exports !== "object" || exports === null)
46
+ return undefined;
47
+ const entry = exports["./conformance"];
48
+ if (typeof entry === "string")
49
+ return entry;
50
+ if (typeof entry !== "object" || entry === null)
51
+ return undefined;
52
+ const conditions = entry;
53
+ const target = conditions.bun ?? conditions.import ?? conditions.default;
54
+ return typeof target === "string" ? target : undefined;
55
+ }
56
+ // A resolution failure says the install is incomplete, not that the dialect is wrong.
57
+ function isUnresolvedModule(err) {
58
+ if (typeof err !== "object" || err === null)
59
+ return false;
60
+ const { code, name, message } = err;
61
+ return (code === "ERR_MODULE_NOT_FOUND" ||
62
+ name === "ResolveMessage" ||
63
+ (typeof message === "string" && /Cannot find (module|package)/.test(message)));
64
+ }
65
+ function isInside(dir, file) {
66
+ const path = relative(dir, file);
67
+ return path !== "" && !path.startsWith("..") && !isAbsolute(path);
68
+ }
69
+ function isFixture(value) {
70
+ if (typeof value !== "object" || value === null)
71
+ return false;
72
+ const fixture = value;
73
+ return typeof fixture.dialect === "object" && fixture.dialect !== null && Array.isArray(fixture.samples);
74
+ }
75
+ /**
76
+ * Loads the fixture of the dialect package in `dir` and runs it. Throws only when the fixture
77
+ * cannot run: the package.json is unreadable or has no name, or a module the fixture imports
78
+ * cannot be resolved. Every finding about the dialect is a failure in the report.
79
+ *
80
+ * @example
81
+ * const report = await checkDialectPackage("/cache/npm/@company/ini-dialect/1.0.0/package");
82
+ * if (!report.passed) console.log(report.failures.map((failure) => failure.case));
83
+ */
84
+ export async function checkDialectPackage(dir) {
85
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
86
+ if (typeof pkg.name !== "string" || pkg.name.length === 0) {
87
+ throw new Error(`pbuilder-conformance: the package.json in --dialect has no name`);
88
+ }
89
+ const report = {
90
+ passed: false,
91
+ dialect: pkg.name,
92
+ version: typeof pkg.version === "string" ? pkg.version : "",
93
+ failures: [],
94
+ };
95
+ const target = conformanceTarget(pkg.exports);
96
+ if (target === undefined) {
97
+ report.failures.push(FIXTURE_MISSING);
98
+ return report;
99
+ }
100
+ const file = resolve(dir, target);
101
+ if (!isInside(dir, file)) {
102
+ report.failures.push(FIXTURE_INVALID);
103
+ return report;
104
+ }
105
+ let fixture;
106
+ try {
107
+ fixture = (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href))).default;
108
+ }
109
+ catch (err) {
110
+ if (isUnresolvedModule(err))
111
+ throw new Error("pbuilder-conformance: a module the fixture imports could not be resolved");
112
+ report.failures.push(FIXTURE_THREW);
113
+ return report;
114
+ }
115
+ if (!isFixture(fixture)) {
116
+ report.failures.push(FIXTURE_INVALID);
117
+ return report;
118
+ }
119
+ if (fixture.dialect.name !== pkg.name)
120
+ report.failures.push(NAME_MISMATCH);
121
+ try {
122
+ await testDialect(fixture);
123
+ }
124
+ catch (err) {
125
+ report.failures.push(classify(err));
126
+ }
127
+ report.passed = report.failures.length === 0;
128
+ return report;
129
+ }
@@ -57,6 +57,8 @@ export type { Batch, Directive };
57
57
  * against an adjacent `schema.json` (pass `import.meta.dir`, never `import.meta.url`); when
58
58
  * absent the run is the untyped, unvalidated tier, byte-identical to a run with no
59
59
  * `packageDir` at all.
60
+ * @param options.declaredDialects - the names of the author-defined dialects the schematic's
61
+ * library declares in its Manifest; a handle of any other named dialect fails the run (A-16).
60
62
  *
61
63
  * @example
62
64
  * import { runFactoryForTest } from "@pbuilder/sdk/testing";
@@ -86,4 +88,5 @@ export type { Batch, Directive };
86
88
  export declare function runFactoryForTest<O>(fn: (input: O) => void | Promise<void>, input: O, options?: {
87
89
  seed?: Record<string, string>;
88
90
  packageDir?: string | URL;
91
+ declaredDialects?: readonly string[];
89
92
  }): Promise<RunResult>;
@@ -27,6 +27,8 @@ import { nodePackageFiles } from "../../infrastructure/out/fs/package-files.js";
27
27
  * against an adjacent `schema.json` (pass `import.meta.dir`, never `import.meta.url`); when
28
28
  * absent the run is the untyped, unvalidated tier, byte-identical to a run with no
29
29
  * `packageDir` at all.
30
+ * @param options.declaredDialects - the names of the author-defined dialects the schematic's
31
+ * library declares in its Manifest; a handle of any other named dialect fails the run (A-16).
30
32
  *
31
33
  * @example
32
34
  * import { runFactoryForTest } from "@pbuilder/sdk/testing";
@@ -73,7 +75,9 @@ export async function runFactoryForTest(fn, input, options) {
73
75
  return fake.discard();
74
76
  },
75
77
  };
76
- const run = defineFactory(fn, options?.packageDir !== undefined ? { packageDir: options.packageDir, packageFiles: nodePackageFiles } : undefined);
78
+ const run = defineFactory(fn, options?.packageDir !== undefined
79
+ ? { packageDir: options.packageDir, packageFiles: nodePackageFiles, declaredDialects: options.declaredDialects }
80
+ : { declaredDialects: options?.declaredDialects });
77
81
  let error;
78
82
  try {
79
83
  await run(input, { client });