@pbuilder/sdk 0.15.1 → 0.17.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 (44) hide show
  1. package/README.md +52 -1
  2. package/dist/bounded-contexts/authoring/domain/services/repeatable.d.ts +19 -0
  3. package/dist/bounded-contexts/authoring/domain/services/repeatable.js +24 -0
  4. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +48 -0
  5. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +46 -0
  6. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +11 -0
  7. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +126 -0
  8. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ast.d.ts +29 -0
  9. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ast.js +41 -0
  10. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.d.ts +44 -0
  11. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.js +45 -0
  12. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/names.d.ts +7 -0
  13. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/names.js +72 -0
  14. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ops.d.ts +19 -0
  15. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ops.js +255 -0
  16. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/pack.d.ts +9 -0
  17. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/pack.js +2 -0
  18. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/syntax.d.ts +26 -0
  19. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/syntax.js +111 -0
  20. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/tree-sitter-c_sharp.LICENSE +23 -0
  21. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/tree-sitter-c_sharp.wasm +0 -0
  22. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/ops.d.ts +4 -4
  23. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/ops.js +9 -8
  24. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ast.d.ts +22 -0
  25. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ast.js +17 -0
  26. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +37 -0
  27. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +38 -0
  28. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +2 -0
  29. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +93 -0
  30. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/xml.d.ts +20 -0
  31. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/xml.js +50 -0
  32. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/documents.d.ts +3 -3
  33. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/documents.js +5 -4
  34. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/structural.d.ts +5 -5
  35. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/structural.js +9 -8
  36. package/dist/bounded-contexts/authoring/testing/conformance/index.js +27 -0
  37. package/dist/dialects/aspnet/index.d.ts +1 -0
  38. package/dist/dialects/aspnet/index.js +1 -0
  39. package/dist/dialects/csharp/index.d.ts +1 -0
  40. package/dist/dialects/csharp/index.js +1 -0
  41. package/dist/dialects/msbuild/index.d.ts +1 -0
  42. package/dist/dialects/msbuild/index.js +1 -0
  43. package/dist/runner-manifest.json +6 -2
  44. package/package.json +20 -2
package/README.md CHANGED
@@ -576,7 +576,8 @@ When string-level mutation isn't enough — "add an import to this module", "set
576
576
  this JSX element" — **dialects** provide structured, AST-aware operations for one file
577
577
  type: see [authoring a dialect](./docs/guides/authoring-a-dialect.md) for the full story. Seven
578
578
  ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/nestjs`,
579
- `@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, `@pbuilder/sdk/yaml`, and `@pbuilder/sdk/css`.
579
+ `@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, `@pbuilder/sdk/yaml`, `@pbuilder/sdk/css`,
580
+ `@pbuilder/sdk/csharp`, `@pbuilder/sdk/aspnet`, and `@pbuilder/sdk/msbuild`.
580
581
 
581
582
  A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
582
583
  handle**. Every op you chain mutates the same live AST, and the handle serializes to
@@ -713,6 +714,56 @@ which ends the chain and resolves to `{ value, important }` (also exported as
713
714
  `getDeclaration(root, target, property)` for use inside `.modify(fn)`). `.modify(fn)` exposes
714
715
  [postcss](https://postcss.org/). See [the CSS dialect guide](./docs/guides/css-dialect.md).
715
716
 
717
+ ### `@pbuilder/sdk/csharp`
718
+
719
+ Adds using directives, base types, members and primary constructor parameters to `.cs` files.
720
+ An op that takes a type name can import its namespace with `from`; everything else keeps its bytes.
721
+
722
+ ```ts
723
+ import * as csharp from "@pbuilder/sdk/csharp";
724
+
725
+ await csharp
726
+ .find("src/Shop.Infrastructure/SqlOrders.cs")
727
+ .addBaseType("SqlOrders", "IOrders", { from: "Shop.Application.Ports" })
728
+ .addConstructorParameter("SqlOrders", "db", "ShopDb", { from: "Shop.Data" });
729
+ ```
730
+
731
+ Named ops: `addUsing`, `addBaseType`, `addMember`, `addConstructorParameter`. `.modify(fn)` exposes
732
+ [web-tree-sitter](https://github.com/tree-sitter/tree-sitter/tree/master/lib/binding_web) and the
733
+ C# `language`. See [the C# dialect guide](./docs/guides/csharp-dialect.md).
734
+
735
+ ### `@pbuilder/sdk/aspnet`
736
+
737
+ Every `@pbuilder/sdk/csharp` op, plus `addService`, which registers a service in the dependency
738
+ injection container: in the top-level statements of `Program.cs`, or in one
739
+ `IServiceCollection` extension method.
740
+
741
+ ```ts
742
+ import * as aspnet from "@pbuilder/sdk/aspnet";
743
+
744
+ await aspnet
745
+ .find("Program.cs")
746
+ .addService("Scoped", "IOrders", "SqlOrders", { serviceFrom: "Shop.Application.Ports", implementationFrom: "Shop.Infrastructure" });
747
+ ```
748
+
749
+ See [the ASP.NET dialect guide](./docs/guides/aspnet-dialect.md).
750
+
751
+ ### `@pbuilder/sdk/msbuild`
752
+
753
+ Adds project references to `.csproj`, `.props`, `.targets` and `.slnx` files by editing the XML
754
+ text, never through the `dotnet` CLI; the classic `.sln` is rejected.
755
+
756
+ ```ts
757
+ import * as msbuild from "@pbuilder/sdk/msbuild";
758
+
759
+ await msbuild
760
+ .find("src/Shop.Infrastructure/Shop.Infrastructure.csproj")
761
+ .addProjectReference("../Shop.Application/Shop.Application.csproj");
762
+ ```
763
+
764
+ Named op: `addProjectReference`. `.modify(fn)` exposes [saxes](https://github.com/lddubeau/saxes).
765
+ See [the MSBuild dialect guide](./docs/guides/msbuild-dialect.md).
766
+
716
767
  ### `@pbuilder/sdk/nestjs`
717
768
 
718
769
  Every `@pbuilder/sdk/typescript` op, plus ops that import a class and register it in the
@@ -0,0 +1,19 @@
1
+ import type { Op } from "./define-dialect.ts";
2
+ /**
3
+ * Declares an op repeatable: its effect depends on how many times it is applied. It adds again
4
+ * on every application, or it acts on a position, so applied again it reaches another element.
5
+ * The conformance kit checks every other op for idempotency (A-11) and skips a chain holding a
6
+ * repeatable op. The op itself is marked and returned, so it stays repeatable in every pack
7
+ * that reuses it.
8
+ *
9
+ * @example
10
+ * export const push = repeatable(function push(ast: string[], line: string): void {
11
+ * ast.push(line);
12
+ * });
13
+ * const pack = defineOpPack({
14
+ * setLine(ast: string[], index: number, line: string) { ast[index] = line; },
15
+ * push,
16
+ * });
17
+ */
18
+ export declare function repeatable<F extends Op>(op: F): F;
19
+ export declare function isRepeatable(op: unknown): boolean;
@@ -0,0 +1,24 @@
1
+ const repeatableOps = new WeakSet();
2
+ /**
3
+ * Declares an op repeatable: its effect depends on how many times it is applied. It adds again
4
+ * on every application, or it acts on a position, so applied again it reaches another element.
5
+ * The conformance kit checks every other op for idempotency (A-11) and skips a chain holding a
6
+ * repeatable op. The op itself is marked and returned, so it stays repeatable in every pack
7
+ * that reuses it.
8
+ *
9
+ * @example
10
+ * export const push = repeatable(function push(ast: string[], line: string): void {
11
+ * ast.push(line);
12
+ * });
13
+ * const pack = defineOpPack({
14
+ * setLine(ast: string[], index: number, line: string) { ast[index] = line; },
15
+ * push,
16
+ * });
17
+ */
18
+ export function repeatable(op) {
19
+ repeatableOps.add(op);
20
+ return op;
21
+ }
22
+ export function isRepeatable(op) {
23
+ return typeof op === "function" && repeatableOps.has(op);
24
+ }
@@ -0,0 +1,48 @@
1
+ import { type Handle } from "../../../../domain/services/define-dialect.ts";
2
+ import { type CsharpDocument } from "../csharp/ast.ts";
3
+ import { type CsharpOps } from "../csharp/pack.ts";
4
+ import { type Lifetime, type ServiceOptions } from "./ops.ts";
5
+ export * as astLibrary from "web-tree-sitter";
6
+ export { language } from "../csharp/ast.ts";
7
+ export type { CsharpDocument, FromOptions, UsingOptions } from "../csharp/index.ts";
8
+ export type { Lifetime, ServiceOptions };
9
+ type ServiceOps = {
10
+ addService: (ast: CsharpDocument, lifetime: Lifetime, service: string, implementation: string, options?: ServiceOptions) => void;
11
+ };
12
+ type AspnetOps = CsharpOps & ServiceOps;
13
+ /**
14
+ * Opens a `.cs` file of an ASP.NET Core application. The handle carries every
15
+ * `@pbuilder/sdk/csharp` op plus `addService`, chained on one handle and written once.
16
+ *
17
+ * `addService(lifetime, service, implementation, { serviceFrom?, implementationFrom?, method? })`
18
+ * writes `<receiver>.Add<lifetime><service, implementation>();` once, `lifetime` being
19
+ * `"Singleton"`, `"Scoped"` or `"Transient"`. Without `method` it edits the top-level statements
20
+ * of `Program.cs`: the receiver is `<builder>.Services` of the one variable initialized by
21
+ * `WebApplication.CreateBuilder` (or `CreateSlimBuilder`, `CreateEmptyBuilder`), and the line
22
+ * goes just before the statement that calls `<builder>.Build()`. With `method` it edits the one
23
+ * static method of that name whose first parameter is `this IServiceCollection`, before its
24
+ * `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.
27
+ *
28
+ * @example
29
+ * import * as aspnet from "@pbuilder/sdk/aspnet";
30
+ *
31
+ * // Program.cs before:
32
+ * // var builder = WebApplication.CreateBuilder(args);
33
+ * //
34
+ * // var app = builder.Build();
35
+ * export const run = async () => {
36
+ * await aspnet
37
+ * .find("Program.cs")
38
+ * .addService("Scoped", "IOrders", "SqlOrders", { serviceFrom: "Shop.Application.Ports", implementationFrom: "Shop.Infrastructure" });
39
+ * };
40
+ * // -> using Shop.Application.Ports;
41
+ * // -> using Shop.Infrastructure;
42
+ * // ->
43
+ * // -> var builder = WebApplication.CreateBuilder(args);
44
+ * // -> builder.Services.AddScoped<IOrders, SqlOrders>();
45
+ * // ->
46
+ * // -> var app = builder.Build();
47
+ */
48
+ export declare function find(path: string): Handle<"found", CsharpDocument, AspnetOps>;
@@ -0,0 +1,46 @@
1
+ import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
2
+ import { parse, print } from "../csharp/ast.js";
3
+ import { csharpOps } from "../csharp/pack.js";
4
+ import { addService } from "./ops.js";
5
+ export * as astLibrary from "web-tree-sitter";
6
+ export { language } from "../csharp/ast.js";
7
+ const serviceOps = defineOpPack({ addService });
8
+ const aspnetDialect = withOps(defineDialect({ extensions: [".cs"], ast: { parse, print }, ops: {} }), csharpOps, serviceOps);
9
+ /**
10
+ * Opens a `.cs` file of an ASP.NET Core application. The handle carries every
11
+ * `@pbuilder/sdk/csharp` op plus `addService`, chained on one handle and written once.
12
+ *
13
+ * `addService(lifetime, service, implementation, { serviceFrom?, implementationFrom?, method? })`
14
+ * writes `<receiver>.Add<lifetime><service, implementation>();` once, `lifetime` being
15
+ * `"Singleton"`, `"Scoped"` or `"Transient"`. Without `method` it edits the top-level statements
16
+ * of `Program.cs`: the receiver is `<builder>.Services` of the one variable initialized by
17
+ * `WebApplication.CreateBuilder` (or `CreateSlimBuilder`, `CreateEmptyBuilder`), and the line
18
+ * goes just before the statement that calls `<builder>.Build()`. With `method` it edits the one
19
+ * static method of that name whose first parameter is `this IServiceCollection`, before its
20
+ * `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.
23
+ *
24
+ * @example
25
+ * import * as aspnet from "@pbuilder/sdk/aspnet";
26
+ *
27
+ * // Program.cs before:
28
+ * // var builder = WebApplication.CreateBuilder(args);
29
+ * //
30
+ * // var app = builder.Build();
31
+ * export const run = async () => {
32
+ * await aspnet
33
+ * .find("Program.cs")
34
+ * .addService("Scoped", "IOrders", "SqlOrders", { serviceFrom: "Shop.Application.Ports", implementationFrom: "Shop.Infrastructure" });
35
+ * };
36
+ * // -> using Shop.Application.Ports;
37
+ * // -> using Shop.Infrastructure;
38
+ * // ->
39
+ * // -> var builder = WebApplication.CreateBuilder(args);
40
+ * // -> builder.Services.AddScoped<IOrders, SqlOrders>();
41
+ * // ->
42
+ * // -> var app = builder.Build();
43
+ */
44
+ export function find(path) {
45
+ return aspnetDialect.find(path);
46
+ }
@@ -0,0 +1,11 @@
1
+ import { type CsharpDocument } from "../csharp/ast.ts";
2
+ export type Lifetime = "Singleton" | "Scoped" | "Transient";
3
+ export interface ServiceOptions {
4
+ /** The namespace that declares the service type; its `using` is added unless the file already sees it. */
5
+ serviceFrom?: string;
6
+ /** The namespace that declares the implementation type, imported like `serviceFrom`. */
7
+ implementationFrom?: string;
8
+ /** Edits the one `static` method of this name whose first parameter is `this IServiceCollection`. */
9
+ method?: string;
10
+ }
11
+ export declare function addService(doc: CsharpDocument, lifetime: Lifetime, service: string, implementation: string, options?: ServiceOptions): void;
@@ -0,0 +1,126 @@
1
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
2
+ import { withTree } from "../csharp/ast.js";
3
+ import { assertIdentifier, assertNamespace, assertOptions, assertType, compact } from "../csharp/names.js";
4
+ import { importNamespace } from "../csharp/ops.js";
5
+ import { endOfNode, indentAt, indentUnit, isTrivia, lineEnding, splice } from "../csharp/syntax.js";
6
+ const LIFETIMES = ["Singleton", "Scoped", "Transient"];
7
+ const BUILDER_FACTORIES = new Set(["CreateBuilder", "CreateSlimBuilder", "CreateEmptyBuilder"]);
8
+ /** `<receiver>.Add<Lifetime><Service, Implementation>();` as a registration, or `undefined`. */
9
+ function registration(statement, receiver) {
10
+ if (statement.type !== "expression_statement")
11
+ return undefined;
12
+ const call = statement.namedChildren[0];
13
+ const callee = call?.type === "invocation_expression" ? call.childForFieldName("function") : null;
14
+ if (callee?.type !== "member_access_expression" || compact(callee.childForFieldName("expression").text) !== receiver)
15
+ return undefined;
16
+ const generic = callee.childForFieldName("name");
17
+ const lifetime = /^Add(Singleton|Scoped|Transient)$/.exec(generic.namedChildren[0]?.text ?? "")?.[1];
18
+ const types = generic.namedChildren[1]?.namedChildren ?? [];
19
+ if (generic.type !== "generic_name" || lifetime === undefined || types.length !== 2)
20
+ return undefined;
21
+ return { lifetime, service: compact(types[0].text), implementation: compact(types[1].text) };
22
+ }
23
+ function isBuilderCall(value) {
24
+ const callee = value?.type === "invocation_expression" ? value.childForFieldName("function") : null;
25
+ return (callee?.type === "member_access_expression" &&
26
+ callee.childForFieldName("expression").text === "WebApplication" &&
27
+ BUILDER_FACTORIES.has(callee.childForFieldName("name").text));
28
+ }
29
+ function callsBuild(statement, builder) {
30
+ return statement.descendantsOfType("invocation_expression").some((call) => {
31
+ const callee = call.childForFieldName("function");
32
+ return (callee?.type === "member_access_expression" &&
33
+ callee.childForFieldName("expression").text === builder &&
34
+ callee.childForFieldName("name").text === "Build");
35
+ });
36
+ }
37
+ /** The top-level statements: the builder, and the line after the last statement before the one calling `Build()`. */
38
+ function programPlace(op, root) {
39
+ const statements = root.namedChildren.filter((child) => child.type === "global_statement").map((child) => child.namedChildren[0]);
40
+ const builders = statements.flatMap((statement) => statement.type === "local_declaration_statement"
41
+ ? statement.descendantsOfType("variable_declarator").filter((d) => isBuilderCall(d.namedChildren.at(-1) ?? null))
42
+ : []);
43
+ if (builders.length !== 1) {
44
+ throw dialectError(`${op} — the top-level statements need exactly one variable initialized by WebApplication.CreateBuilder, CreateSlimBuilder or CreateEmptyBuilder; found ${builders.length}. Pass \`method\` to edit a service collection extension method instead`);
45
+ }
46
+ const builder = builders[0].childForFieldName("name").text;
47
+ const build = statements.findIndex((statement) => callsBuild(statement, builder));
48
+ if (build < 1)
49
+ throw dialectError(`${op} — no top-level statement after the builder calls \`${builder}.Build()\``);
50
+ const before = statements[build - 1];
51
+ return {
52
+ receiver: `${builder}.Services`,
53
+ statements,
54
+ insert: (source, line) => {
55
+ const at = endOfNode(source, before);
56
+ return splice(source, at, at, lineEnding(source) + indentAt(source, before.startIndex) + line);
57
+ },
58
+ };
59
+ }
60
+ function isServiceCollectionExtension(method) {
61
+ if (!method.children.some((child) => child.type === "modifier" && child.text === "static"))
62
+ return false;
63
+ const first = method.childForFieldName("parameters")?.namedChildren.find((child) => child.type === "parameter");
64
+ const isThis = first?.children.some((child) => child.type === "modifier" && child.text === "this") === true;
65
+ return isThis && /(^|\.)IServiceCollection$/.test(compact(first.childForFieldName("type")?.text ?? ""));
66
+ }
67
+ /** The one `static` method `name(this IServiceCollection ...)`: before its last statement when that is a `return`, else after it. */
68
+ function methodPlace(op, root, name) {
69
+ const methods = root
70
+ .descendantsOfType("method_declaration")
71
+ .filter((method) => method.childForFieldName("name").text === name && isServiceCollectionExtension(method));
72
+ if (methods.length !== 1) {
73
+ throw dialectError(`${op} — the file needs exactly one static method \`${name}\` whose first parameter is \`this IServiceCollection\`; found ${methods.length}`);
74
+ }
75
+ const method = methods[0];
76
+ const body = method.childForFieldName("body");
77
+ if (body?.type !== "block")
78
+ throw dialectError(`${op} — \`${name}\` has an expression body; edit it with .modify()`);
79
+ const receiver = method.childForFieldName("parameters").namedChildren.find((child) => child.type === "parameter").childForFieldName("name").text;
80
+ const statements = body.namedChildren.filter((child) => !isTrivia(child));
81
+ const last = statements.at(-1);
82
+ const insert = (source, line) => {
83
+ const eol = lineEnding(source);
84
+ if (last === undefined) {
85
+ const open = body.children[0];
86
+ return splice(source, open.endIndex, open.endIndex, eol + indentAt(source, method.startIndex) + indentUnit(source, root) + line);
87
+ }
88
+ const indent = indentAt(source, last.startIndex);
89
+ if (last.type === "return_statement")
90
+ return splice(source, last.startIndex, last.startIndex, line + eol + indent);
91
+ const at = endOfNode(source, last);
92
+ return splice(source, at, at, eol + indent + line);
93
+ };
94
+ return { receiver, statements, insert };
95
+ }
96
+ export function addService(doc, lifetime, service, implementation, options) {
97
+ const op = "addService";
98
+ if (typeof lifetime !== "string" || !LIFETIMES.includes(lifetime)) {
99
+ throw dialectError(`${op} — \`lifetime\` ${JSON.stringify(lifetime)} is not a lifetime; use "Singleton", "Scoped" or "Transient"`);
100
+ }
101
+ assertType(op, "service", service);
102
+ assertType(op, "implementation", implementation);
103
+ const opts = assertOptions(op, options, ["serviceFrom", "implementationFrom", "method"]);
104
+ if (opts.serviceFrom !== undefined)
105
+ assertNamespace(op, "serviceFrom", opts.serviceFrom);
106
+ if (opts.implementationFrom !== undefined)
107
+ assertNamespace(op, "implementationFrom", opts.implementationFrom);
108
+ if (opts.method !== undefined)
109
+ assertIdentifier(op, "method", opts.method);
110
+ const edited = withTree(doc.text, (root) => {
111
+ const place = opts.method === undefined ? programPlace(op, root) : methodPlace(op, root, opts.method);
112
+ const receiver = compact(place.receiver);
113
+ const existing = place.statements
114
+ .map((statement) => registration(statement, receiver))
115
+ .find((r) => r !== undefined && r.service === compact(service) && r.implementation === compact(implementation));
116
+ if (existing?.lifetime === lifetime)
117
+ return undefined;
118
+ if (existing !== undefined) {
119
+ throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${implementation}\` as ${existing.lifetime}, not ${lifetime}`);
120
+ }
121
+ return place.insert(doc.text, `${place.receiver}.Add${lifetime}<${service.trim()}, ${implementation.trim()}>();`);
122
+ });
123
+ if (edited === undefined)
124
+ return;
125
+ doc.text = importNamespace(op, importNamespace(op, edited, opts.serviceFrom), opts.implementationFrom);
126
+ }
@@ -0,0 +1,29 @@
1
+ import { Language, type Node } from "web-tree-sitter";
2
+ /** The tree-sitter C# grammar (tree-sitter-c-sharp 0.24.0) the dialect parses with. */
3
+ export declare const language: Language;
4
+ /**
5
+ * The live document a C# handle edits. `text` is the current source without its UTF-8 BOM
6
+ * (re-added on print). tree-sitter trees are read-only views of a text, so named ops replace
7
+ * `text` with spliced edits; a `.modify(fn)` callback may do the same, parsing `text` with
8
+ * `astLibrary` (`web-tree-sitter`) and `language`.
9
+ *
10
+ * @example
11
+ * import * as csharp from "@pbuilder/sdk/csharp";
12
+ *
13
+ * await csharp.find("Orders.cs").modify((doc) => {
14
+ * doc.text = doc.text.replace("internal class", "public class");
15
+ * });
16
+ */
17
+ export interface CsharpDocument {
18
+ text: string;
19
+ }
20
+ /** Runs `fn` over a fresh tree of `text`, freeing the tree's WASM memory afterwards. */
21
+ export declare function withTree<T>(text: string, fn: (root: Node) => T): T;
22
+ /** True when `text` parses as C# with no ERROR or MISSING node. */
23
+ export declare function isValidCsharp(text: string): boolean;
24
+ /**
25
+ * Wraps `source` in a `CsharpDocument`, throwing when it is not valid C# syntax. A compile
26
+ * error that is not a syntax error, such as an unknown type, parses.
27
+ */
28
+ export declare function parse(source: string): CsharpDocument;
29
+ export declare function print(doc: CsharpDocument): string;
@@ -0,0 +1,41 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { Language, Parser } from "web-tree-sitter";
3
+ const BOM = "";
4
+ // `ast.parse` is synchronous and loading WASM is not, so the module loads it once at import.
5
+ await Parser.init();
6
+ /** The tree-sitter C# grammar (tree-sitter-c-sharp 0.24.0) the dialect parses with. */
7
+ export const language = await Language.load(fileURLToPath(new URL("./tree-sitter-c_sharp.wasm", import.meta.url)));
8
+ const parser = new Parser();
9
+ parser.setLanguage(language);
10
+ const hadBom = new WeakSet();
11
+ /** Runs `fn` over a fresh tree of `text`, freeing the tree's WASM memory afterwards. */
12
+ export function withTree(text, fn) {
13
+ const tree = parser.parse(text);
14
+ if (tree === null)
15
+ throw new Error("invalid C#");
16
+ try {
17
+ return fn(tree.rootNode);
18
+ }
19
+ finally {
20
+ tree.delete();
21
+ }
22
+ }
23
+ /** True when `text` parses as C# with no ERROR or MISSING node. */
24
+ export function isValidCsharp(text) {
25
+ return withTree(text, (root) => !root.hasError);
26
+ }
27
+ /**
28
+ * Wraps `source` in a `CsharpDocument`, throwing when it is not valid C# syntax. A compile
29
+ * error that is not a syntax error, such as an unknown type, parses.
30
+ */
31
+ export function parse(source) {
32
+ const doc = { text: source.startsWith(BOM) ? source.slice(BOM.length) : source };
33
+ if (!isValidCsharp(doc.text))
34
+ throw new Error("invalid C#");
35
+ if (source.startsWith(BOM))
36
+ hadBom.add(doc);
37
+ return doc;
38
+ }
39
+ export function print(doc) {
40
+ return hadBom.has(doc) ? BOM + doc.text : doc.text;
41
+ }
@@ -0,0 +1,44 @@
1
+ import { type Handle } from "../../../../domain/services/define-dialect.ts";
2
+ import { type CsharpDocument } from "./ast.ts";
3
+ import type { FromOptions, UsingOptions } from "./ops.ts";
4
+ import { type CsharpOps } from "./pack.ts";
5
+ export * as astLibrary from "web-tree-sitter";
6
+ export { language } from "./ast.ts";
7
+ export type { CsharpDocument, FromOptions, UsingOptions };
8
+ /**
9
+ * Opens a `.cs` file for editing (`.csx` excluded). A file that is not valid C# syntax fails the
10
+ * factory; a compile error such as an unknown type does not, since the dialect has no compiler.
11
+ * Every op edits only the bytes it must, and inserted code follows the file's line ending, BOM
12
+ * and member indentation (four spaces when it has none); `.editorconfig` is never read.
13
+ *
14
+ * - `addUsing(namespace, { static?, global?, alias? })` adds a using directive once.
15
+ * - `addBaseType(typeName, base, { from? })` appends a base type to the base list once.
16
+ * - `addMember(typeName, source)` appends one member; an identical member changes nothing.
17
+ * - `addConstructorParameter(typeName, name, type, { from? })` appends a primary constructor
18
+ * parameter; a type with an explicit constructor, or an interface, rejects.
19
+ *
20
+ * `typeName` names the one class, record, struct or interface of that name at the top level or
21
+ * in a namespace. `from` names the namespace that declares the type and adds its `using`
22
+ * unless the file already sees it. `.modify(fn)` hands `fn` the live `CsharpDocument`; parse its
23
+ * `text` with `astLibrary` (`web-tree-sitter`) and `language` for anything the ops do not cover.
24
+ *
25
+ * @example
26
+ * import * as csharp from "@pbuilder/sdk/csharp";
27
+ *
28
+ * // Orders.cs before: namespace Shop.Infrastructure;\n\npublic class Orders\n{\n}\n
29
+ * export const run = async () => {
30
+ * await csharp
31
+ * .find("Orders.cs")
32
+ * .addBaseType("Orders", "IOrders", { from: "Shop.Application.Ports" })
33
+ * .addConstructorParameter("Orders", "db", "ShopDb", { from: "Shop.Data" });
34
+ * };
35
+ * // -> using Shop.Application.Ports;
36
+ * // -> using Shop.Data;
37
+ * // ->
38
+ * // -> namespace Shop.Infrastructure;
39
+ * // ->
40
+ * // -> public class Orders(ShopDb db) : IOrders
41
+ * // -> {
42
+ * // -> }
43
+ */
44
+ export declare function find(path: string): Handle<"found", CsharpDocument, CsharpOps>;
@@ -0,0 +1,45 @@
1
+ import { defineDialect, withOps } from "../../../../domain/services/define-dialect.js";
2
+ import { parse, print } from "./ast.js";
3
+ import { csharpOps } from "./pack.js";
4
+ export * as astLibrary from "web-tree-sitter";
5
+ export { language } from "./ast.js";
6
+ const csharpDialect = withOps(defineDialect({ extensions: [".cs"], ast: { parse, print }, ops: {} }), csharpOps);
7
+ /**
8
+ * Opens a `.cs` file for editing (`.csx` excluded). A file that is not valid C# syntax fails the
9
+ * factory; a compile error such as an unknown type does not, since the dialect has no compiler.
10
+ * Every op edits only the bytes it must, and inserted code follows the file's line ending, BOM
11
+ * and member indentation (four spaces when it has none); `.editorconfig` is never read.
12
+ *
13
+ * - `addUsing(namespace, { static?, global?, alias? })` adds a using directive once.
14
+ * - `addBaseType(typeName, base, { from? })` appends a base type to the base list once.
15
+ * - `addMember(typeName, source)` appends one member; an identical member changes nothing.
16
+ * - `addConstructorParameter(typeName, name, type, { from? })` appends a primary constructor
17
+ * parameter; a type with an explicit constructor, or an interface, rejects.
18
+ *
19
+ * `typeName` names the one class, record, struct or interface of that name at the top level or
20
+ * in a namespace. `from` names the namespace that declares the type and adds its `using`
21
+ * unless the file already sees it. `.modify(fn)` hands `fn` the live `CsharpDocument`; parse its
22
+ * `text` with `astLibrary` (`web-tree-sitter`) and `language` for anything the ops do not cover.
23
+ *
24
+ * @example
25
+ * import * as csharp from "@pbuilder/sdk/csharp";
26
+ *
27
+ * // Orders.cs before: namespace Shop.Infrastructure;\n\npublic class Orders\n{\n}\n
28
+ * export const run = async () => {
29
+ * await csharp
30
+ * .find("Orders.cs")
31
+ * .addBaseType("Orders", "IOrders", { from: "Shop.Application.Ports" })
32
+ * .addConstructorParameter("Orders", "db", "ShopDb", { from: "Shop.Data" });
33
+ * };
34
+ * // -> using Shop.Application.Ports;
35
+ * // -> using Shop.Data;
36
+ * // ->
37
+ * // -> namespace Shop.Infrastructure;
38
+ * // ->
39
+ * // -> public class Orders(ShopDb db) : IOrders
40
+ * // -> {
41
+ * // -> }
42
+ */
43
+ export function find(path) {
44
+ return csharpDialect.find(path);
45
+ }
@@ -0,0 +1,7 @@
1
+ export declare function assertIdentifier(op: string, argument: string, value: unknown): asserts value is string;
2
+ export declare function assertNamespace(op: string, argument: string, value: unknown): asserts value is string;
3
+ /** A type must parse as exactly one C# type: a name, qualified, generic, nullable, array or tuple type. */
4
+ export declare function assertType(op: string, argument: string, value: unknown): asserts value is string;
5
+ export declare function assertOptions(op: string, value: unknown, allowed: readonly string[]): Record<string, unknown>;
6
+ /** Text with every whitespace removed, to compare code as written ignoring whitespace. */
7
+ export declare function compact(text: string): string;
@@ -0,0 +1,72 @@
1
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
2
+ import { withTree } from "./ast.js";
3
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
4
+ // The reserved keywords of C#. Contextual keywords (`var`, `async`, `record`, ...) are valid names.
5
+ const KEYWORDS = new Set(("abstract as base bool break byte case catch char checked class const continue decimal default delegate do " +
6
+ "double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface " +
7
+ "internal is lock long namespace new null object operator out override params private protected public readonly " +
8
+ "ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint " +
9
+ "ulong unchecked unsafe ushort using virtual void volatile while").split(" "));
10
+ const TYPE_NODES = new Set([
11
+ "identifier",
12
+ "qualified_name",
13
+ "alias_qualified_name",
14
+ "generic_name",
15
+ "predefined_type",
16
+ "nullable_type",
17
+ "array_type",
18
+ "tuple_type",
19
+ ]);
20
+ /** Rejects `value` for the argument `argument` of `op`, quoting it as the rules phrase it. */
21
+ function refuse(op, argument, value, why) {
22
+ throw dialectError(`${op} — \`${argument}\` ${JSON.stringify(value)} is ${why}`);
23
+ }
24
+ export function assertIdentifier(op, argument, value) {
25
+ if (typeof value !== "string")
26
+ throw dialectError(`${op} — \`${argument}\` must be a string`);
27
+ if (!IDENTIFIER.test(value))
28
+ refuse(op, argument, value, "not a C# identifier (letters, digits and _, not starting with a digit)");
29
+ if (KEYWORDS.has(value))
30
+ refuse(op, argument, value, "a reserved keyword of C#");
31
+ }
32
+ export function assertNamespace(op, argument, value) {
33
+ if (typeof value !== "string")
34
+ throw dialectError(`${op} — \`${argument}\` must be a string`);
35
+ const parts = value.split(".");
36
+ if (!parts.every((part) => IDENTIFIER.test(part)))
37
+ refuse(op, argument, value, "not a namespace (identifiers joined by dots)");
38
+ if (parts.some((part) => KEYWORDS.has(part)))
39
+ refuse(op, argument, value, "a namespace with a reserved keyword of C#");
40
+ }
41
+ /** A type must parse as exactly one C# type: a name, qualified, generic, nullable, array or tuple type. */
42
+ export function assertType(op, argument, value) {
43
+ if (typeof value !== "string")
44
+ throw dialectError(`${op} — \`${argument}\` must be a string`);
45
+ const type = value.trim();
46
+ const single = type.length > 0 &&
47
+ withTree(`class C { ${type} f; }`, (root) => {
48
+ if (root.hasError || root.descendantsOfType("comment").length > 0)
49
+ return false;
50
+ const members = root.namedChildren[0]?.childForFieldName("body")?.namedChildren ?? [];
51
+ const node = members.length === 1 ? members[0].namedChildren[0]?.childForFieldName("type") : undefined;
52
+ return node !== null && node !== undefined && TYPE_NODES.has(node.type) && node.text === type;
53
+ });
54
+ if (!single)
55
+ refuse(op, argument, value, "not exactly one C# type");
56
+ }
57
+ export function assertOptions(op, value, allowed) {
58
+ if (value === undefined)
59
+ return {};
60
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
61
+ throw dialectError(`${op} — \`options\` must be an object`);
62
+ }
63
+ for (const key of Object.keys(value)) {
64
+ if (!allowed.includes(key))
65
+ throw dialectError(`${op} — \`options\` must hold only ${allowed.map((k) => `\`${k}\``).join(", ")}`);
66
+ }
67
+ return value;
68
+ }
69
+ /** Text with every whitespace removed, to compare code as written ignoring whitespace. */
70
+ export function compact(text) {
71
+ return text.replace(/\s+/g, "");
72
+ }
@@ -0,0 +1,19 @@
1
+ import { type CsharpDocument } from "./ast.ts";
2
+ export interface UsingOptions {
3
+ /** Writes `using static namespace;`. */
4
+ static?: boolean;
5
+ /** Writes `global using namespace;`, placed with the other global directives. */
6
+ global?: boolean;
7
+ /** Writes `using alias = namespace;`. */
8
+ alias?: string;
9
+ }
10
+ export interface FromOptions {
11
+ /** The namespace that declares the type; its `using` is added unless the file already sees it. */
12
+ from?: string;
13
+ }
14
+ /** Adds `using from;` unless `from` is absent or the file already sees that namespace (A-110). */
15
+ export declare function importNamespace(op: string, text: string, from: string | undefined): string;
16
+ export declare function addUsing(doc: CsharpDocument, namespace: string, options?: UsingOptions): void;
17
+ export declare function addBaseType(doc: CsharpDocument, typeName: string, base: string, options?: FromOptions): void;
18
+ export declare function addMember(doc: CsharpDocument, typeName: string, source: string): void;
19
+ export declare function addConstructorParameter(doc: CsharpDocument, typeName: string, name: string, type: string, options?: FromOptions): void;