@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,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;
@@ -0,0 +1,255 @@
1
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
2
+ import { withTree } from "./ast.js";
3
+ import { assertIdentifier, assertNamespace, assertOptions, assertType, compact } from "./names.js";
4
+ import { declaredNamespaces, endOfNode, findType, headerEnd, indentAt, indentCode, indentUnit, isTrivia, lineEnding, splice } from "./syntax.js";
5
+ function directive(node) {
6
+ const alias = node.childForFieldName("name");
7
+ const target = node.namedChildren.filter((child) => child.id !== alias?.id && child.type !== "comment").at(-1);
8
+ return {
9
+ node,
10
+ global: node.children.some((child) => child.type === "global"),
11
+ static: node.children.some((child) => child.type === "static"),
12
+ alias: alias?.text,
13
+ target: compact(target.text),
14
+ };
15
+ }
16
+ function directivesIn(container) {
17
+ return container.namedChildren.filter((child) => child.type === "using_directive").map(directive);
18
+ }
19
+ /** The block namespaces of the file that hold directives, each with its directives. */
20
+ function namespaceDirectives(container) {
21
+ const found = [];
22
+ for (const child of container.namedChildren) {
23
+ if (child.type !== "namespace_declaration")
24
+ continue;
25
+ const body = child.childForFieldName("body");
26
+ if (body === null)
27
+ continue;
28
+ const own = directivesIn(body);
29
+ if (own.length > 0)
30
+ found.push(own);
31
+ found.push(...namespaceDirectives(body));
32
+ }
33
+ return found;
34
+ }
35
+ /** Where a directive goes when the file has none: at the top, after any leading comment. */
36
+ function topOfFile(text, root) {
37
+ let at = 0;
38
+ for (const child of root.children) {
39
+ if (child.type !== "comment")
40
+ break;
41
+ const newline = text.indexOf("\n", child.endIndex);
42
+ at = newline === -1 ? text.length : newline + 1;
43
+ }
44
+ return at;
45
+ }
46
+ function usingLine(namespace, options) {
47
+ const alias = options.alias === undefined ? "" : `${options.alias} = `;
48
+ return `${options.global === true ? "global " : ""}using ${options.static === true ? "static " : ""}${alias}${namespace};`;
49
+ }
50
+ /** The text with the directive added by the placement rules of A-109, or `undefined` when it is already there. */
51
+ function withUsing(op, text, namespace, options) {
52
+ return withTree(text, (root) => {
53
+ const top = directivesIn(root);
54
+ const nested = namespaceDirectives(root);
55
+ const all = [...top, ...nested.flat()];
56
+ const isGlobal = options.global === true;
57
+ const isStatic = options.static === true;
58
+ if (options.alias !== undefined) {
59
+ const bound = all.find((d) => d.alias === options.alias && d.target !== namespace);
60
+ if (bound !== undefined) {
61
+ throw dialectError(`${op}(${JSON.stringify(namespace)}) — the alias \`${options.alias}\` is already bound to ${JSON.stringify(bound.target)}`);
62
+ }
63
+ }
64
+ if (all.some((d) => d.target === namespace && d.alias === options.alias && d.global === isGlobal && d.static === isStatic)) {
65
+ return undefined;
66
+ }
67
+ const eol = lineEnding(text);
68
+ const line = usingLine(namespace, options);
69
+ const after = (d) => {
70
+ const at = endOfNode(text, d.node);
71
+ return splice(text, at, at, eol + indentAt(text, d.node.startIndex) + line);
72
+ };
73
+ if (isGlobal) {
74
+ const lastGlobal = top.filter((d) => d.global).at(-1);
75
+ if (lastGlobal !== undefined)
76
+ return after(lastGlobal);
77
+ const first = top[0];
78
+ if (first !== undefined) {
79
+ return splice(text, first.node.startIndex, first.node.startIndex, line + eol + indentAt(text, first.node.startIndex));
80
+ }
81
+ }
82
+ else if (top.length > 0) {
83
+ return after(top.at(-1));
84
+ }
85
+ else if (nested.length === 1) {
86
+ return after(nested[0].at(-1));
87
+ }
88
+ const at = topOfFile(text, root);
89
+ const lead = at > 0 && !text.slice(0, at).endsWith("\n") ? eol : "";
90
+ const blankFollows = at === text.length || /^\r?\n/.test(text.slice(at));
91
+ return splice(text, at, at, lead + line + eol + (blankFollows ? "" : eol));
92
+ });
93
+ }
94
+ /** Adds `using from;` unless `from` is absent or the file already sees that namespace (A-110). */
95
+ export function importNamespace(op, text, from) {
96
+ if (from === undefined)
97
+ return text;
98
+ const seen = withTree(text, (root) => {
99
+ const declared = declaredNamespaces(root);
100
+ if (declared.some((name) => name === from || name.startsWith(`${from}.`)))
101
+ return true;
102
+ const all = [...directivesIn(root), ...namespaceDirectives(root).flat()];
103
+ return all.some((d) => d.target === from && d.alias === undefined && !d.static);
104
+ });
105
+ return seen ? text : (withUsing(op, text, from, {}) ?? text);
106
+ }
107
+ function fromOption(op, options) {
108
+ const { from } = assertOptions(op, options, ["from"]);
109
+ if (from !== undefined)
110
+ assertNamespace(op, "from", from);
111
+ return from;
112
+ }
113
+ /** Validates `options`, applies `edit`, and imports `from`; an edit that returns `undefined` leaves the file as it is. */
114
+ function editType(doc, op, from, edit) {
115
+ const edited = withTree(doc.text, (root) => edit(doc.text, root));
116
+ if (edited !== undefined)
117
+ doc.text = importNamespace(op, edited, from);
118
+ }
119
+ export function addUsing(doc, namespace, options) {
120
+ const op = "addUsing";
121
+ assertNamespace(op, "namespace", namespace);
122
+ const opts = assertOptions(op, options, ["static", "global", "alias"]);
123
+ for (const flag of ["static", "global"]) {
124
+ if (opts[flag] !== undefined && typeof opts[flag] !== "boolean")
125
+ throw dialectError(`${op} — \`${flag}\` must be a boolean`);
126
+ }
127
+ if (opts.alias !== undefined)
128
+ assertIdentifier(op, "alias", opts.alias);
129
+ if (opts.static === true && opts.alias !== undefined)
130
+ throw dialectError(`${op} — \`static\` and \`alias\` cannot be combined`);
131
+ const edited = withUsing(op, doc.text, namespace, opts);
132
+ if (edited !== undefined)
133
+ doc.text = edited;
134
+ }
135
+ export function addBaseType(doc, typeName, base, options) {
136
+ const op = "addBaseType";
137
+ assertIdentifier(op, "typeName", typeName);
138
+ assertType(op, "base", base);
139
+ const from = fromOption(op, options);
140
+ const written = base.trim();
141
+ editType(doc, op, from, (text, root) => {
142
+ const type = findType(root, op, typeName);
143
+ const list = type.namedChildren.find((child) => child.type === "base_list");
144
+ if (list === undefined) {
145
+ const at = headerEnd(type);
146
+ return splice(text, at, at, ` : ${written}`);
147
+ }
148
+ if (list.namedChildren.some((entry) => compact(entry.text) === compact(written)))
149
+ return undefined;
150
+ return splice(text, list.endIndex, list.endIndex, `, ${written}`);
151
+ });
152
+ }
153
+ const MEMBER_DECLARATIONS = new Set([
154
+ "field_declaration",
155
+ "property_declaration",
156
+ "method_declaration",
157
+ "constructor_declaration",
158
+ "destructor_declaration",
159
+ "event_declaration",
160
+ "event_field_declaration",
161
+ "indexer_declaration",
162
+ "operator_declaration",
163
+ "conversion_operator_declaration",
164
+ "class_declaration",
165
+ "record_declaration",
166
+ "struct_declaration",
167
+ "interface_declaration",
168
+ "enum_declaration",
169
+ "delegate_declaration",
170
+ ]);
171
+ function assertMember(op, source) {
172
+ if (typeof source !== "string")
173
+ throw dialectError(`${op} — \`source\` must be a string`);
174
+ const single = withTree(`class C {\n${source}\n}`, (root) => {
175
+ if (root.hasError)
176
+ return false;
177
+ const members = root.namedChildren[0]?.childForFieldName("body")?.namedChildren.filter((child) => child.type !== "comment") ?? [];
178
+ return root.namedChildren.length === 1 && members.length === 1 && MEMBER_DECLARATIONS.has(members[0].type);
179
+ });
180
+ if (!single)
181
+ throw dialectError(`${op} — \`source\` must be exactly one member declaration (a field, property, method, constructor, event, indexer, operator or nested type)`);
182
+ }
183
+ export function addMember(doc, typeName, source) {
184
+ const op = "addMember";
185
+ assertIdentifier(op, "typeName", typeName);
186
+ assertMember(op, source);
187
+ editType(doc, op, undefined, (text, root) => {
188
+ const type = findType(root, op, typeName);
189
+ const eol = lineEnding(text);
190
+ const declIndent = indentAt(text, type.startIndex);
191
+ const unit = indentUnit(text, root);
192
+ const body = type.childForFieldName("body");
193
+ if (body === null) {
194
+ // A record with no body (`record A(int Id);`) gets one in place of its `;`.
195
+ const semicolon = type.children.at(-1);
196
+ const block = `${eol}${declIndent}{${eol}${indentCode(source, declIndent + unit, eol)}${eol}${declIndent}}`;
197
+ return splice(text, semicolon.startIndex, semicolon.endIndex, block);
198
+ }
199
+ const named = body.namedChildren;
200
+ const members = named.filter((child) => !isTrivia(child));
201
+ if (members.some((member) => compact(member.text) === compact(source)))
202
+ return undefined;
203
+ const open = body.children[0];
204
+ const close = body.children.at(-1);
205
+ if (open.startPosition.row === close.startPosition.row) {
206
+ const lines = [...named.map((child) => child.text), source].map((code) => indentCode(code, declIndent + unit, eol));
207
+ return splice(text, open.endIndex, close.startIndex, eol + lines.join(eol) + eol + declIndent);
208
+ }
209
+ if (named.length === 0)
210
+ return splice(text, open.endIndex, open.endIndex, eol + indentCode(source, declIndent + unit, eol));
211
+ const at = endOfNode(text, named.at(-1));
212
+ const memberIndent = members.length > 0 ? indentAt(text, members.at(-1).startIndex) : declIndent + unit;
213
+ const blank = members.length >= 2
214
+ ? /\n[ \t]*\r?\n/.test(text.slice(members.at(-2).endIndex, members.at(-1).startIndex))
215
+ : members.length === 1 && source.trim().includes("\n");
216
+ return splice(text, at, at, eol + (blank ? eol : "") + indentCode(source, memberIndent, eol));
217
+ });
218
+ }
219
+ export function addConstructorParameter(doc, typeName, name, type, options) {
220
+ const op = "addConstructorParameter";
221
+ assertIdentifier(op, "typeName", typeName);
222
+ assertIdentifier(op, "name", name);
223
+ assertType(op, "type", type);
224
+ const from = fromOption(op, options);
225
+ const parameter = `${type.trim()} ${name}`;
226
+ editType(doc, op, from, (text, root) => {
227
+ const target = findType(root, op, typeName);
228
+ const label = `${op}(${JSON.stringify(typeName)})`;
229
+ if (target.type === "interface_declaration")
230
+ throw dialectError(`${label} — an interface has no constructor`);
231
+ const explicit = target
232
+ .childForFieldName("body")
233
+ ?.namedChildren.some((member) => member.type === "constructor_declaration" && !member.children.some((m) => m.text === "static"));
234
+ if (explicit === true) {
235
+ throw dialectError(`${label} — \`${typeName}\` has an explicit constructor; only a primary constructor is edited, use .modify() for this type`);
236
+ }
237
+ const list = target.namedChildren.find((child) => child.type === "parameter_list");
238
+ if (list === undefined) {
239
+ const at = headerEnd(target);
240
+ return splice(text, at, at, `(${parameter})`);
241
+ }
242
+ const params = list.namedChildren.filter((child) => child.type === "parameter");
243
+ const same = params.find((p) => p.childForFieldName("name")?.text === name);
244
+ if (same !== undefined) {
245
+ if (compact(same.childForFieldName("type")?.text ?? "") === compact(type))
246
+ return undefined;
247
+ throw dialectError(`${label} — a parameter \`${name}\` of type \`${same.childForFieldName("type")?.text}\` is already declared`);
248
+ }
249
+ const last = params.at(-1);
250
+ if (last === undefined)
251
+ return splice(text, list.startIndex + 1, list.startIndex + 1, parameter);
252
+ const separator = last.startPosition.row > list.startPosition.row ? `,${lineEnding(text)}${indentAt(text, last.startIndex)}` : ", ";
253
+ return splice(text, last.endIndex, last.endIndex, separator + parameter);
254
+ });
255
+ }
@@ -0,0 +1,9 @@
1
+ import type { CsharpDocument } from "./ast.ts";
2
+ import { type FromOptions, type UsingOptions } from "./ops.ts";
3
+ export type CsharpOps = {
4
+ addUsing: (ast: CsharpDocument, namespace: string, options?: UsingOptions) => void;
5
+ addBaseType: (ast: CsharpDocument, typeName: string, base: string, options?: FromOptions) => void;
6
+ addMember: (ast: CsharpDocument, typeName: string, source: string) => void;
7
+ addConstructorParameter: (ast: CsharpDocument, typeName: string, name: string, type: string, options?: FromOptions) => void;
8
+ };
9
+ export declare const csharpOps: CsharpOps;
@@ -0,0 +1,2 @@
1
+ import { addBaseType, addConstructorParameter, addMember, addUsing } from "./ops.js";
2
+ export const csharpOps = { addUsing, addBaseType, addMember, addConstructorParameter };
@@ -0,0 +1,26 @@
1
+ import type { Node } from "web-tree-sitter";
2
+ export declare const TYPE_DECLARATIONS: ReadonlySet<string>;
3
+ export declare function lineEnding(text: string): string;
4
+ /** The whitespace that starts the line holding `index`. */
5
+ export declare function indentAt(text: string, index: number): string;
6
+ /**
7
+ * The indentation unit the file uses for members: the step from the first declaration holding a
8
+ * member or a nested declaration to that member, four spaces when the file has none.
9
+ */
10
+ export declare function indentUnit(text: string, root: Node): string;
11
+ /** Writes `code` at `indent`: each line after the first keeps its indentation relative to the first. */
12
+ export declare function indentCode(code: string, indent: string, eol: string): string;
13
+ /**
14
+ * Where code inserted after `node` goes: before a line break the node itself holds (preprocessor
15
+ * lines do), and past a comment that ends the node's line, so that comment stays with it.
16
+ */
17
+ export declare function endOfNode(text: string, node: Node): number;
18
+ /** Comments and preprocessor lines are not members, statements or directives. */
19
+ export declare function isTrivia(node: Node): boolean;
20
+ export declare function splice(text: string, start: number, end: number, insert: string): string;
21
+ /** The one class, record, struct or interface named `typeName`; none or several reject. */
22
+ export declare function findType(root: Node, op: string, typeName: string): Node;
23
+ /** Where a header clause (`(...)`, `: base`) goes: after the name, type parameters and primary constructor. */
24
+ export declare function headerEnd(type: Node): number;
25
+ /** The namespaces the file declares, with the names of block namespaces nested in each other joined. */
26
+ export declare function declaredNamespaces(root: Node, prefix?: string): string[];
@@ -0,0 +1,111 @@
1
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
2
+ export const TYPE_DECLARATIONS = new Set([
3
+ "class_declaration",
4
+ "record_declaration",
5
+ "struct_declaration",
6
+ "interface_declaration",
7
+ ]);
8
+ export function lineEnding(text) {
9
+ return text.includes("\r\n") ? "\r\n" : "\n";
10
+ }
11
+ /** The whitespace that starts the line holding `index`. */
12
+ export function indentAt(text, index) {
13
+ const lineStart = text.lastIndexOf("\n", index - 1) + 1;
14
+ return /^[ \t]*/.exec(text.slice(lineStart))[0];
15
+ }
16
+ /**
17
+ * The indentation unit the file uses for members: the step from the first declaration holding a
18
+ * member or a nested declaration to that member, four spaces when the file has none.
19
+ */
20
+ export function indentUnit(text, root) {
21
+ for (const body of root.descendantsOfType("declaration_list")) {
22
+ const member = body.namedChildren.find((child) => !isTrivia(child));
23
+ if (member === undefined || member.startPosition.row === body.startPosition.row)
24
+ continue;
25
+ const outer = indentAt(text, body.parent.startIndex);
26
+ const inner = indentAt(text, member.startIndex);
27
+ if (inner.startsWith(outer) && inner.length > outer.length)
28
+ return inner.slice(outer.length);
29
+ }
30
+ return " ";
31
+ }
32
+ /** Writes `code` at `indent`: each line after the first keeps its indentation relative to the first. */
33
+ export function indentCode(code, indent, eol) {
34
+ const lines = code.trim().split(/\r?\n/);
35
+ const base = /^[ \t]*/.exec(code.split(/\r?\n/).find((line) => line.trim() !== "") ?? "")[0];
36
+ return lines
37
+ .map((line, index) => {
38
+ if (index === 0)
39
+ return indent + line;
40
+ if (line.trim() === "")
41
+ return "";
42
+ return indent + (line.startsWith(base) ? line.slice(base.length) : line.trimStart());
43
+ })
44
+ .join(eol);
45
+ }
46
+ /**
47
+ * Where code inserted after `node` goes: before a line break the node itself holds (preprocessor
48
+ * lines do), and past a comment that ends the node's line, so that comment stays with it.
49
+ */
50
+ export function endOfNode(text, node) {
51
+ let end = node.endIndex;
52
+ while (end > node.startIndex && (text[end - 1] === "\n" || text[end - 1] === "\r"))
53
+ end--;
54
+ const newline = text.indexOf("\n", end);
55
+ const rest = text.slice(end, newline === -1 ? text.length : newline).replace(/\r$/, "");
56
+ return /^\s*(\/\/.*|\/\*.*\*\/\s*)$/.test(rest) ? end + rest.length : end;
57
+ }
58
+ /** Comments and preprocessor lines are not members, statements or directives. */
59
+ export function isTrivia(node) {
60
+ return node.type === "comment" || node.type.startsWith("preproc_");
61
+ }
62
+ export function splice(text, start, end, insert) {
63
+ return text.slice(0, start) + insert + text.slice(end);
64
+ }
65
+ /** The type declarations at the top level of the file or inside a namespace; nested types are not targets. */
66
+ function topLevelTypes(container) {
67
+ const types = [];
68
+ for (const child of container.namedChildren) {
69
+ if (TYPE_DECLARATIONS.has(child.type))
70
+ types.push(child);
71
+ else if (child.type === "namespace_declaration") {
72
+ const body = child.childForFieldName("body");
73
+ if (body !== null)
74
+ types.push(...topLevelTypes(body));
75
+ }
76
+ }
77
+ return types;
78
+ }
79
+ /** The one class, record, struct or interface named `typeName`; none or several reject. */
80
+ export function findType(root, op, typeName) {
81
+ const matches = topLevelTypes(root).filter((type) => type.childForFieldName("name")?.text === typeName);
82
+ if (matches.length === 1)
83
+ return matches[0];
84
+ const why = matches.length === 0
85
+ ? `no class, record, struct or interface named \`${typeName}\` is declared at the top level or in a namespace`
86
+ : `\`${typeName}\` names ${matches.length} declarations (a partial type?); edit them with .modify()`;
87
+ throw dialectError(`${op}(${JSON.stringify(typeName)}) — ${why}`);
88
+ }
89
+ /** Where a header clause (`(...)`, `: base`) goes: after the name, type parameters and primary constructor. */
90
+ export function headerEnd(type) {
91
+ let end = type.childForFieldName("name").endIndex;
92
+ for (const child of type.namedChildren) {
93
+ if (child.type === "type_parameter_list" || child.type === "parameter_list")
94
+ end = Math.max(end, child.endIndex);
95
+ }
96
+ return end;
97
+ }
98
+ /** The namespaces the file declares, with the names of block namespaces nested in each other joined. */
99
+ export function declaredNamespaces(root, prefix = "") {
100
+ const names = [];
101
+ for (const child of root.namedChildren) {
102
+ if (child.type !== "namespace_declaration" && child.type !== "file_scoped_namespace_declaration")
103
+ continue;
104
+ const name = prefix + child.childForFieldName("name").text.replace(/\s+/g, "");
105
+ names.push(name);
106
+ const body = child.childForFieldName("body");
107
+ if (body !== null)
108
+ names.push(...declaredNamespaces(body, `${name}.`));
109
+ }
110
+ return names;
111
+ }
@@ -0,0 +1,23 @@
1
+ tree-sitter-c_sharp.wasm is the WebAssembly build of tree-sitter-c-sharp 0.24.0, copied unchanged from its npm package (sha256 e137386fcdfc2562a058f8048c76ab77b0663a318cb62d8026cd4d2e94944231).
2
+
3
+ The MIT License (MIT)
4
+
5
+ Copyright (c) 2014-2023 Max Brunsfeld, Damien Guard, Amaan Qureshi, and contributors.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The live document an MSBuild handle edits. `text` is the current source without its UTF-8
3
+ * BOM (re-added on print). The dialect edits XML text rather than a tree, so every byte outside
4
+ * an edit survives; a `.modify(fn)` callback may replace `text` the same way, reading offsets
5
+ * with `astLibrary` (`saxes`).
6
+ *
7
+ * @example
8
+ * import * as msbuild from "@pbuilder/sdk/msbuild";
9
+ *
10
+ * await msbuild.find("Shop.Api.csproj").modify((doc) => {
11
+ * doc.text = doc.text.replace("<Nullable>disable</Nullable>", "<Nullable>enable</Nullable>");
12
+ * });
13
+ */
14
+ export interface MsbuildDocument {
15
+ text: string;
16
+ }
17
+ /**
18
+ * Wraps `source` in an `MsbuildDocument`, throwing on anything that is not well-formed XML. An
19
+ * empty source is a document with no root element, which every op rejects.
20
+ */
21
+ export declare function parse(source: string): MsbuildDocument;
22
+ export declare function print(doc: MsbuildDocument): string;
@@ -0,0 +1,17 @@
1
+ import { readElements } from "./xml.js";
2
+ const BOM = "";
3
+ const hadBom = new WeakSet();
4
+ /**
5
+ * Wraps `source` in an `MsbuildDocument`, throwing on anything that is not well-formed XML. An
6
+ * empty source is a document with no root element, which every op rejects.
7
+ */
8
+ export function parse(source) {
9
+ const doc = { text: source.startsWith(BOM) ? source.slice(BOM.length) : source };
10
+ readElements(doc.text);
11
+ if (source.startsWith(BOM))
12
+ hadBom.add(doc);
13
+ return doc;
14
+ }
15
+ export function print(doc) {
16
+ return hadBom.has(doc) ? BOM + doc.text : doc.text;
17
+ }
@@ -0,0 +1,55 @@
1
+ import { type Handle } from "../../../../domain/services/define-dialect.ts";
2
+ import { type MsbuildDocument } from "./ast.ts";
3
+ import { type ProjectOptions } from "./ops.ts";
4
+ export * as astLibrary from "saxes";
5
+ export type { MsbuildDocument, ProjectOptions };
6
+ type MsbuildOps = {
7
+ addProjectReference: (ast: MsbuildDocument, path: string) => void;
8
+ addProject: (ast: MsbuildDocument, path: string, options?: ProjectOptions) => void;
9
+ };
10
+ /**
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
14
+ * dialect edits the XML text and changes only the bytes it must: the XML declaration, comments,
15
+ * attribute quotes, indentation, line endings, a BOM, and the final newline survive. The classic
16
+ * `.sln` format and any other extension throw synchronously with the `dialect operation failed: `
17
+ * prefix, and a file that is not well-formed XML fails the factory. `.modify(fn)` hands `fn` the
18
+ * live `MsbuildDocument`; edit its `text`, reading offsets with `astLibrary` (`saxes`), for
19
+ * anything the op does not cover.
20
+ *
21
+ * @example
22
+ * import * as msbuild from "@pbuilder/sdk/msbuild";
23
+ *
24
+ * // Shop.Infrastructure.csproj before:
25
+ * // <Project Sdk="Microsoft.NET.Sdk">\n <PropertyGroup>\n <TargetFramework>net10.0</TargetFramework>\n </PropertyGroup>\n</Project>\n
26
+ * export const run = async () => {
27
+ * await msbuild
28
+ * .find("src/Shop.Infrastructure/Shop.Infrastructure.csproj")
29
+ * .addProjectReference("../Shop.Application/Shop.Application.csproj");
30
+ * };
31
+ * // -> <Project Sdk="Microsoft.NET.Sdk">
32
+ * // -> <PropertyGroup>
33
+ * // -> <TargetFramework>net10.0</TargetFramework>
34
+ * // -> </PropertyGroup>
35
+ * // ->
36
+ * // -> <ItemGroup>
37
+ * // -> <ProjectReference Include="../Shop.Application/Shop.Application.csproj" />
38
+ * // -> </ItemGroup>
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>
54
+ */
55
+ export declare function find(path: string): Handle<"found", MsbuildDocument, MsbuildOps>;