@pbuilder/sdk 0.17.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 (45) hide show
  1. package/README.md +26 -3
  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 +8 -5
  15. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +7 -4
  16. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +1 -1
  17. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +20 -7
  18. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +20 -2
  19. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +19 -3
  20. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +5 -0
  21. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +89 -20
  22. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +2 -2
  23. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.d.ts +2 -0
  24. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.js +4 -0
  25. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +3 -3
  26. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.d.ts +2 -0
  27. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.js +4 -0
  28. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +2 -2
  29. package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +10 -12
  30. package/dist/bounded-contexts/authoring/testing/conformance/index.js +17 -2
  31. package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +20 -0
  32. package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +129 -0
  33. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +3 -0
  34. package/dist/bounded-contexts/authoring/testing/harness/index.js +5 -1
  35. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  36. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +2 -0
  37. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +42 -3
  38. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +13 -0
  39. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +25 -1
  40. package/dist/conformance/index.d.ts +1 -0
  41. package/dist/conformance/index.js +1 -0
  42. package/dist/dialect/index.d.ts +2 -0
  43. package/dist/dialect/index.js +3 -0
  44. package/dist/runner-manifest.json +6 -6
  45. package/package.json +8 -2
@@ -40,7 +40,8 @@ function hasDeclaredExtension(path, extensions) {
40
40
  /**
41
41
  * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
42
42
  * and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
43
- * returns an open, coalescing `Handle`.
43
+ * returns an open, coalescing `Handle`. Throws when an op in `ops` takes the name of a handle
44
+ * verb (`RESERVED_HANDLE_NAMES`).
44
45
  *
45
46
  * @example
46
47
  * const myDialect = defineDialect({
@@ -50,7 +51,11 @@ function hasDeclaredExtension(path, extensions) {
50
51
  * });
51
52
  */
52
53
  export function defineDialect(d) {
54
+ // The handle spreads its ops over its verbs, so an op named after a verb would replace it.
55
+ for (const name of Object.keys(d.ops))
56
+ assertNotReserved(name);
53
57
  return {
58
+ name: d.name,
54
59
  extensions: d.extensions,
55
60
  ast: d.ast,
56
61
  ops: d.ops,
@@ -58,10 +63,29 @@ export function defineDialect(d) {
58
63
  if (!hasDeclaredExtension(path, d.extensions)) {
59
64
  throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${d.extensions.join(", ")}).`);
60
65
  }
61
- return createDialectHandle(d.ast, d.ops, path);
66
+ return createDialectHandle(d.ast, d.ops, path, d.name);
62
67
  },
63
68
  };
64
69
  }
70
+ /**
71
+ * Defines an author-defined dialect, named by the package that ships it (A-16): a factory opens
72
+ * its handles only when the schematic's library declares that name in its Manifest, and the
73
+ * conformance fixture rejects a name that is not the package's.
74
+ *
75
+ * @example
76
+ * export const ini = defineDialect({
77
+ * name: "@company/ini-dialect",
78
+ * extensions: [".ini"],
79
+ * ast: { parse: (text) => parseIni(text), print: (tree) => printIni(tree) },
80
+ * ops: {},
81
+ * });
82
+ */
83
+ export function defineAuthorDialect(d) {
84
+ if (typeof d.name !== "string" || d.name.length === 0) {
85
+ throw new Error('defineDialect failed: "name" is required, the name of the package that ships the dialect (A-16).');
86
+ }
87
+ return defineDialect(d);
88
+ }
65
89
  /**
66
90
  * The base handle's own vocabulary (REQ-DG-02, ADR-0010 amendment) — an op-pack op sharing
67
91
  * any of these names would silently shadow a base verb; `then` in particular would break the
@@ -79,6 +103,7 @@ export const RESERVED_HANDLE_NAMES = [
79
103
  "read",
80
104
  "raw",
81
105
  "modify",
106
+ "inspect",
82
107
  "replaceContent",
83
108
  "rename",
84
109
  "move",
@@ -95,14 +120,17 @@ void _reservedCoversSurface;
95
120
  * `Error`s, NOT minted via `dialectError()` — they are not run-op contained rejects and must
96
121
  * never be recognised by `isContained` as passthrough (design §4.5's own rationale).
97
122
  */
123
+ function assertNotReserved(name) {
124
+ if (!RESERVED_SET.has(name))
125
+ return;
126
+ const hint = name === "raw" ? " — the live AST-fn escape hatch is .modify(fn)" : "";
127
+ throw new Error(`op-pack composition failed: op "${name}" collides with a reserved handle verb${hint}`);
128
+ }
98
129
  function assertNoCompositionCollision(baseOpNames, packs) {
99
130
  const claimed = new Set(baseOpNames);
100
131
  for (const pack of packs) {
101
132
  for (const name of Object.keys(pack)) {
102
- if (RESERVED_SET.has(name)) {
103
- const hint = name === "raw" ? " — the live AST-fn escape hatch is .modify(fn)" : "";
104
- throw new Error(`op-pack composition failed: op "${name}" collides with a reserved handle verb${hint}`);
105
- }
133
+ assertNotReserved(name);
106
134
  if (claimed.has(name)) {
107
135
  throw new Error(`op-pack composition failed: duplicate op "${name}" declared by more than one pack.`);
108
136
  }
@@ -125,7 +153,7 @@ function assertNoCompositionCollision(baseOpNames, packs) {
125
153
  export function withOps(base, ...packs) {
126
154
  assertNoCompositionCollision(Object.keys(base.ops), packs);
127
155
  const merged = Object.assign({}, base.ops, ...packs);
128
- return defineDialect({ extensions: [...base.extensions], ast: base.ast, ops: merged });
156
+ return defineDialect({ name: base.name, extensions: [...base.extensions], ast: base.ast, ops: merged });
129
157
  }
130
158
  function assertKnownOps(ops, names, composer) {
131
159
  for (const name of names) {
@@ -151,7 +179,7 @@ export function withoutOps(dialect, names, reason) {
151
179
  throw dialectError(`${name} is not available for ${files} files — ${reason}. Use .modify() to make this edit directly.`);
152
180
  },
153
181
  ]));
154
- return defineDialect({ extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...blocked } });
182
+ return defineDialect({ name: dialect.name, extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...blocked } });
155
183
  }
156
184
  /**
157
185
  * Derives a dialect whose named ops run `overrides` instead, with the same signatures. Throws at
@@ -162,7 +190,7 @@ export function withoutOps(dialect, names, reason) {
162
190
  */
163
191
  export function overrideOps(dialect, overrides) {
164
192
  assertKnownOps(dialect.ops, Object.keys(overrides), "overrideOps");
165
- return defineDialect({ extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...overrides } });
193
+ return defineDialect({ name: dialect.name, extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...overrides } });
166
194
  }
167
195
  /**
168
196
  * Routes `find` by file extension to one dialect per extension, each with its own AST and ops —
@@ -1,5 +1,5 @@
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 { addBootstrap, addComponentImport, addComponentProvider, addComputed, addDeclaration, addInjection, addInput, addLazyRoute, addModel, addNgModuleExport, addNgModuleImport, addNgModuleProvider, addOutput, addRootProvider, addRoute, addSignal, } from "./ops.js";
5
5
  export * as astLibrary from "ts-morph";
@@ -23,7 +23,7 @@ const angularOps = defineOpPack({
23
23
  });
24
24
  const baseDialect = defineDialect({
25
25
  extensions: [".ts"],
26
- ast: { parse, print },
26
+ ast: { parse, print, retire },
27
27
  ops: {},
28
28
  });
29
29
  const angularDialect = withOps(baseDialect, typescriptOps, angularOps);
@@ -7,23 +7,26 @@ export { language } from "../csharp/ast.ts";
7
7
  export type { CsharpDocument, FromOptions, UsingOptions } from "../csharp/index.ts";
8
8
  export type { Lifetime, ServiceOptions };
9
9
  type ServiceOps = {
10
- addService: (ast: CsharpDocument, lifetime: Lifetime, service: string, implementation: string, options?: ServiceOptions) => void;
10
+ addService: (ast: CsharpDocument, lifetime: Lifetime, service: string, implementation?: string, options?: ServiceOptions) => void;
11
11
  };
12
12
  type AspnetOps = CsharpOps & ServiceOps;
13
13
  /**
14
14
  * Opens a `.cs` file of an ASP.NET Core application. The handle carries every
15
15
  * `@pbuilder/sdk/csharp` op plus `addService`, chained on one handle and written once.
16
16
  *
17
- * `addService(lifetime, service, implementation, { serviceFrom?, implementationFrom?, method? })`
17
+ * `addService(lifetime, service, implementation?, { serviceFrom?, implementationFrom?, method? })`
18
18
  * writes `<receiver>.Add<lifetime><service, implementation>();` once, `lifetime` being
19
- * `"Singleton"`, `"Scoped"` or `"Transient"`. Without `method` it edits the top-level statements
19
+ * `"Singleton"`, `"Scoped"` or `"Transient"`; when `implementation` is left out or equals
20
+ * `service`, it writes `<receiver>.Add<lifetime><service>();`. Without `method` it edits the top-level statements
20
21
  * of `Program.cs`: the receiver is `<builder>.Services` of the one variable initialized by
21
22
  * `WebApplication.CreateBuilder` (or `CreateSlimBuilder`, `CreateEmptyBuilder`), and the line
22
23
  * goes just before the statement that calls `<builder>.Build()`. With `method` it edits the one
23
24
  * static method of that name whose first parameter is `this IServiceCollection`, before its
24
25
  * `return`. `serviceFrom` and `implementationFrom` add the `using` of each type unless the file
25
- * already sees it. The same registration already there changes nothing; the same pair with
26
- * another lifetime, or a file with no such place, rejects and leaves the file as it is.
26
+ * already sees it. The same registration already there, called with no arguments, changes
27
+ * nothing (`Add<L><S>()` and `Add<L><S, S>()` are the same registration); the same pair with
28
+ * another lifetime or with arguments such as a factory, or a file with no such place, rejects and
29
+ * leaves the file as it is.
27
30
  *
28
31
  * @example
29
32
  * import * as aspnet from "@pbuilder/sdk/aspnet";
@@ -10,16 +10,19 @@ const aspnetDialect = withOps(defineDialect({ extensions: [".cs"], ast: { parse,
10
10
  * Opens a `.cs` file of an ASP.NET Core application. The handle carries every
11
11
  * `@pbuilder/sdk/csharp` op plus `addService`, chained on one handle and written once.
12
12
  *
13
- * `addService(lifetime, service, implementation, { serviceFrom?, implementationFrom?, method? })`
13
+ * `addService(lifetime, service, implementation?, { serviceFrom?, implementationFrom?, method? })`
14
14
  * writes `<receiver>.Add<lifetime><service, implementation>();` once, `lifetime` being
15
- * `"Singleton"`, `"Scoped"` or `"Transient"`. Without `method` it edits the top-level statements
15
+ * `"Singleton"`, `"Scoped"` or `"Transient"`; when `implementation` is left out or equals
16
+ * `service`, it writes `<receiver>.Add<lifetime><service>();`. Without `method` it edits the top-level statements
16
17
  * of `Program.cs`: the receiver is `<builder>.Services` of the one variable initialized by
17
18
  * `WebApplication.CreateBuilder` (or `CreateSlimBuilder`, `CreateEmptyBuilder`), and the line
18
19
  * goes just before the statement that calls `<builder>.Build()`. With `method` it edits the one
19
20
  * static method of that name whose first parameter is `this IServiceCollection`, before its
20
21
  * `return`. `serviceFrom` and `implementationFrom` add the `using` of each type unless the file
21
- * already sees it. The same registration already there changes nothing; the same pair with
22
- * another lifetime, or a file with no such place, rejects and leaves the file as it is.
22
+ * already sees it. The same registration already there, called with no arguments, changes
23
+ * nothing (`Add<L><S>()` and `Add<L><S, S>()` are the same registration); the same pair with
24
+ * another lifetime or with arguments such as a factory, or a file with no such place, rejects and
25
+ * leaves the file as it is.
23
26
  *
24
27
  * @example
25
28
  * import * as aspnet from "@pbuilder/sdk/aspnet";
@@ -8,4 +8,4 @@ export interface ServiceOptions {
8
8
  /** Edits the one `static` method of this name whose first parameter is `this IServiceCollection`. */
9
9
  method?: string;
10
10
  }
11
- export declare function addService(doc: CsharpDocument, lifetime: Lifetime, service: string, implementation: string, options?: ServiceOptions): void;
11
+ export declare function addService(doc: CsharpDocument, lifetime: Lifetime, service: string, implementation?: string, options?: ServiceOptions): void;
@@ -5,7 +5,7 @@ import { importNamespace } from "../csharp/ops.js";
5
5
  import { endOfNode, indentAt, indentUnit, isTrivia, lineEnding, splice } from "../csharp/syntax.js";
6
6
  const LIFETIMES = ["Singleton", "Scoped", "Transient"];
7
7
  const BUILDER_FACTORIES = new Set(["CreateBuilder", "CreateSlimBuilder", "CreateEmptyBuilder"]);
8
- /** `<receiver>.Add<Lifetime><Service, Implementation>();` as a registration, or `undefined`. */
8
+ /** `<receiver>.Add<Lifetime><Service>(...)` or `<receiver>.Add<Lifetime><Service, Implementation>(...)` as a registration, or `undefined`. */
9
9
  function registration(statement, receiver) {
10
10
  if (statement.type !== "expression_statement")
11
11
  return undefined;
@@ -16,9 +16,15 @@ function registration(statement, receiver) {
16
16
  const generic = callee.childForFieldName("name");
17
17
  const lifetime = /^Add(Singleton|Scoped|Transient)$/.exec(generic.namedChildren[0]?.text ?? "")?.[1];
18
18
  const types = generic.namedChildren[1]?.namedChildren ?? [];
19
- if (generic.type !== "generic_name" || lifetime === undefined || types.length !== 2)
19
+ if (generic.type !== "generic_name" || lifetime === undefined || (types.length !== 1 && types.length !== 2))
20
20
  return undefined;
21
- return { lifetime, service: compact(types[0].text), implementation: compact(types[1].text) };
21
+ const service = compact(types[0].text);
22
+ return {
23
+ lifetime,
24
+ service,
25
+ implementation: types.length === 2 ? compact(types[1].text) : service,
26
+ passesArguments: (call.childForFieldName("arguments")?.namedChildren.length ?? 0) > 0,
27
+ };
22
28
  }
23
29
  function isBuilderCall(value) {
24
30
  const callee = value?.type === "invocation_expression" ? value.childForFieldName("function") : null;
@@ -99,7 +105,10 @@ export function addService(doc, lifetime, service, implementation, options) {
99
105
  throw dialectError(`${op} — \`lifetime\` ${JSON.stringify(lifetime)} is not a lifetime; use "Singleton", "Scoped" or "Transient"`);
100
106
  }
101
107
  assertType(op, "service", service);
102
- assertType(op, "implementation", implementation);
108
+ if (implementation !== undefined)
109
+ assertType(op, "implementation", implementation);
110
+ const implementationType = implementation ?? service;
111
+ const singleType = compact(implementationType) === compact(service);
103
112
  const opts = assertOptions(op, options, ["serviceFrom", "implementationFrom", "method"]);
104
113
  if (opts.serviceFrom !== undefined)
105
114
  assertNamespace(op, "serviceFrom", opts.serviceFrom);
@@ -112,13 +121,17 @@ export function addService(doc, lifetime, service, implementation, options) {
112
121
  const receiver = compact(place.receiver);
113
122
  const existing = place.statements
114
123
  .map((statement) => registration(statement, receiver))
115
- .find((r) => r !== undefined && r.service === compact(service) && r.implementation === compact(implementation));
124
+ .find((r) => r !== undefined && r.service === compact(service) && r.implementation === compact(implementationType));
125
+ if (existing?.passesArguments) {
126
+ throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${implementationType}\` by a call that passes arguments; edit it with .modify()`);
127
+ }
116
128
  if (existing?.lifetime === lifetime)
117
129
  return undefined;
118
130
  if (existing !== undefined) {
119
- throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${implementation}\` as ${existing.lifetime}, not ${lifetime}`);
131
+ throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${implementationType}\` as ${existing.lifetime}, not ${lifetime}`);
120
132
  }
121
- return place.insert(doc.text, `${place.receiver}.Add${lifetime}<${service.trim()}, ${implementation.trim()}>();`);
133
+ const types = singleType ? service.trim() : `${service.trim()}, ${implementationType.trim()}`;
134
+ return place.insert(doc.text, `${place.receiver}.Add${lifetime}<${types}>();`);
122
135
  });
123
136
  if (edited === undefined)
124
137
  return;
@@ -1,12 +1,16 @@
1
1
  import { type Handle } from "../../../../domain/services/define-dialect.ts";
2
2
  import { type MsbuildDocument } from "./ast.ts";
3
+ import { type ProjectOptions } from "./ops.ts";
3
4
  export * as astLibrary from "saxes";
4
- export type { MsbuildDocument };
5
+ export type { MsbuildDocument, ProjectOptions };
5
6
  type MsbuildOps = {
6
7
  addProjectReference: (ast: MsbuildDocument, path: string) => void;
8
+ addProject: (ast: MsbuildDocument, path: string, options?: ProjectOptions) => void;
7
9
  };
8
10
  /**
9
- * Opens a `.csproj`, `.props`, `.targets` or `.slnx` file to add project references. The
11
+ * Opens a `.csproj`, `.props`, `.targets` or `.slnx` file. `addProjectReference(path)` edits a
12
+ * file whose root element is `Project`; `addProject(path, { folder? })` adds a project to a `.slnx`
13
+ * `<Solution>`, in the solution folder `folder` (such as `/src/`) when given. The
10
14
  * dialect edits the XML text and changes only the bytes it must: the XML declaration, comments,
11
15
  * attribute quotes, indentation, line endings, a BOM, and the final newline survive. The classic
12
16
  * `.sln` format and any other extension throw synchronously with the `dialect operation failed: `
@@ -33,5 +37,19 @@ type MsbuildOps = {
33
37
  * // -> <ProjectReference Include="../Shop.Application/Shop.Application.csproj" />
34
38
  * // -> </ItemGroup>
35
39
  * // -> </Project>
40
+ *
41
+ * @example
42
+ * import * as msbuild from "@pbuilder/sdk/msbuild";
43
+ *
44
+ * // Shop.slnx before:
45
+ * // <Solution>\n</Solution>\n
46
+ * export const run = async () => {
47
+ * await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
48
+ * };
49
+ * // -> <Solution>
50
+ * // -> <Folder Name="/src/">
51
+ * // -> <Project Path="src/Shop.Api/Shop.Api.csproj" />
52
+ * // -> </Folder>
53
+ * // -> </Solution>
36
54
  */
37
55
  export declare function find(path: string): Handle<"found", MsbuildDocument, MsbuildOps>;
@@ -1,11 +1,13 @@
1
1
  import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
2
2
  import { parse, print } from "./ast.js";
3
- import { addProjectReference } from "./ops.js";
3
+ import { addProject, addProjectReference } from "./ops.js";
4
4
  export * as astLibrary from "saxes";
5
- const opsPack = defineOpPack({ addProjectReference });
5
+ const opsPack = defineOpPack({ addProjectReference, addProject });
6
6
  const msbuildDialect = withOps(defineDialect({ extensions: [".csproj", ".props", ".targets", ".slnx"], ast: { parse, print }, ops: {} }), opsPack);
7
7
  /**
8
- * Opens a `.csproj`, `.props`, `.targets` or `.slnx` file to add project references. The
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
9
11
  * dialect edits the XML text and changes only the bytes it must: the XML declaration, comments,
10
12
  * attribute quotes, indentation, line endings, a BOM, and the final newline survive. The classic
11
13
  * `.sln` format and any other extension throw synchronously with the `dialect operation failed: `
@@ -32,6 +34,20 @@ const msbuildDialect = withOps(defineDialect({ extensions: [".csproj", ".props",
32
34
  * // -> <ProjectReference Include="../Shop.Application/Shop.Application.csproj" />
33
35
  * // -> </ItemGroup>
34
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>
35
51
  */
36
52
  export function find(path) {
37
53
  return msbuildDialect.find(path);
@@ -1,2 +1,7 @@
1
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
+ }
2
6
  export declare const addProjectReference: (ast: MsbuildDocument, path: string) => void;
7
+ export declare const addProject: (ast: MsbuildDocument, path: string, options?: ProjectOptions | undefined) => void;
@@ -2,16 +2,32 @@ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
2
2
  import { validatedOp } from "../../../../domain/services/identifier-names.js";
3
3
  import { readElements } from "./xml.js";
4
4
  const OP = "addProjectReference";
5
+ const ADD_PROJECT = "addProject";
5
6
  const DEFAULT_UNIT = " ";
6
- function assertPath(path) {
7
+ function assertPath(op, path) {
7
8
  const rule = "a relative path whose file name ends in `proj`";
8
9
  if (typeof path !== "string")
9
- throw dialectError(`${OP} — \`path\` must be ${rule}.`);
10
+ throw dialectError(`${op} — \`path\` must be ${rule}.`);
10
11
  const fileName = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
11
12
  if (/^([/\\]|[A-Za-z]:)/.test(path) || !fileName.endsWith("proj")) {
12
- throw dialectError(`${OP} — \`path\` ${JSON.stringify(path)} is not ${rule}.`);
13
+ throw dialectError(`${op} — \`path\` ${JSON.stringify(path)} is not ${rule}.`);
13
14
  }
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
+ }
15
31
  function escapeAttribute(value) {
16
32
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
17
33
  }
@@ -45,18 +61,23 @@ function* descendants(element) {
45
61
  function splice(doc, from, to, insert) {
46
62
  doc.text = doc.text.slice(0, from) + insert + doc.text.slice(to);
47
63
  }
48
- export const addProjectReference = validatedOp(([path]) => assertPath(path), (doc, path) => {
49
- let project;
50
- try {
51
- project = readElements(doc.text);
52
- }
53
- catch {
54
- throw dialectError(`${OP}(${JSON.stringify(path)}) — the file is not well-formed XML.`);
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}>`);
55
73
  }
56
- if (project?.name !== "Project") {
57
- const root = project === undefined ? "the file has no root element" : `the root element is \`${project.name}\``;
58
- throw dialectError(`${OP}(${JSON.stringify(path)}) — ${root}; it needs \`Project\`.`);
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}`);
59
77
  }
78
+ }
79
+ export const addProjectReference = validatedOp(([path]) => assertPath(OP, path), (doc, path) => {
80
+ const project = readRoot(doc, OP, path, "Project");
60
81
  for (const element of descendants(project)) {
61
82
  const include = element.attributes.get("Include");
62
83
  if (element.name === "ProjectReference" && include !== undefined && sameReference(include, path))
@@ -80,14 +101,62 @@ export const addProjectReference = validatedOp(([path]) => assertPath(path), (do
80
101
  if (last !== undefined) {
81
102
  splice(doc, last.end, last.end, `${eol}${eol}${block}`);
82
103
  }
83
- else if (project.selfClosing) {
84
- let cut = text.lastIndexOf("/", project.end - 1);
85
- while (/\s/.test(text[cut - 1]))
86
- cut--;
87
- splice(doc, cut, project.end, `>${eol}${block}${eol}${projectIndent}</Project>`);
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);
88
158
  }
89
159
  else {
90
- const closeOnOwnLine = text.slice(project.openEnd, project.closeStart).includes("\n");
91
- splice(doc, project.openEnd, project.openEnd, `${eol}${block}${closeOnOwnLine ? "" : eol + projectIndent}`);
160
+ splice(doc, first.start, first.start, `${block(firstIndent).slice(firstIndent.length)}${eol}${firstIndent}`);
92
161
  }
93
162
  });
@@ -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,