@bufbuild/protoplugin 1.5.1 → 1.7.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 (64) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/create-es-plugin.d.ts +23 -3
  3. package/dist/cjs/create-es-plugin.js +26 -135
  4. package/dist/cjs/ecmascript/custom-options.d.ts +8 -0
  5. package/dist/cjs/ecmascript/custom-options.js +7 -1
  6. package/dist/cjs/ecmascript/export-declaration.d.ts +7 -0
  7. package/dist/cjs/ecmascript/export-declaration.js +24 -0
  8. package/dist/cjs/ecmascript/gencommon.d.ts +4 -5
  9. package/dist/cjs/ecmascript/gencommon.js +2 -76
  10. package/dist/cjs/ecmascript/generated-file.d.ts +48 -13
  11. package/dist/cjs/ecmascript/generated-file.js +82 -19
  12. package/dist/cjs/ecmascript/import-path.js +1 -1
  13. package/dist/cjs/ecmascript/import-symbol.js +1 -1
  14. package/dist/cjs/ecmascript/index.d.ts +22 -7
  15. package/dist/cjs/ecmascript/index.js +31 -9
  16. package/dist/cjs/ecmascript/jsdoc.d.ts +8 -0
  17. package/dist/cjs/ecmascript/jsdoc.js +93 -0
  18. package/dist/cjs/ecmascript/parameter.d.ts +13 -0
  19. package/dist/cjs/ecmascript/parameter.js +161 -0
  20. package/dist/cjs/ecmascript/reify-wkt.js +1 -1
  21. package/dist/cjs/ecmascript/runtime-imports.d.ts +1 -0
  22. package/dist/cjs/ecmascript/runtime-imports.js +2 -1
  23. package/dist/cjs/ecmascript/schema.d.ts +5 -6
  24. package/dist/cjs/ecmascript/schema.js +24 -37
  25. package/dist/cjs/ecmascript/target.js +1 -1
  26. package/dist/cjs/ecmascript/transpile.d.ts +1 -1
  27. package/dist/cjs/ecmascript/transpile.js +5 -2
  28. package/dist/cjs/error.js +1 -1
  29. package/dist/cjs/index.d.ts +5 -1
  30. package/dist/cjs/index.js +1 -1
  31. package/dist/cjs/plugin.js +1 -1
  32. package/dist/cjs/run-node.js +1 -1
  33. package/dist/esm/create-es-plugin.d.ts +23 -3
  34. package/dist/esm/create-es-plugin.js +27 -136
  35. package/dist/esm/ecmascript/custom-options.d.ts +8 -0
  36. package/dist/esm/ecmascript/custom-options.js +7 -1
  37. package/dist/esm/ecmascript/export-declaration.d.ts +7 -0
  38. package/dist/esm/ecmascript/export-declaration.js +20 -0
  39. package/dist/esm/ecmascript/gencommon.d.ts +4 -5
  40. package/dist/esm/ecmascript/gencommon.js +1 -73
  41. package/dist/esm/ecmascript/generated-file.d.ts +48 -13
  42. package/dist/esm/ecmascript/generated-file.js +83 -20
  43. package/dist/esm/ecmascript/import-path.js +1 -1
  44. package/dist/esm/ecmascript/import-symbol.js +1 -1
  45. package/dist/esm/ecmascript/index.d.ts +22 -7
  46. package/dist/esm/ecmascript/index.js +24 -3
  47. package/dist/esm/ecmascript/jsdoc.d.ts +8 -0
  48. package/dist/esm/ecmascript/jsdoc.js +89 -0
  49. package/dist/esm/ecmascript/parameter.d.ts +13 -0
  50. package/dist/esm/ecmascript/parameter.js +157 -0
  51. package/dist/esm/ecmascript/reify-wkt.js +1 -1
  52. package/dist/esm/ecmascript/runtime-imports.d.ts +1 -0
  53. package/dist/esm/ecmascript/runtime-imports.js +2 -1
  54. package/dist/esm/ecmascript/schema.d.ts +5 -6
  55. package/dist/esm/ecmascript/schema.js +24 -36
  56. package/dist/esm/ecmascript/target.js +1 -1
  57. package/dist/esm/ecmascript/transpile.d.ts +1 -1
  58. package/dist/esm/ecmascript/transpile.js +5 -2
  59. package/dist/esm/error.js +1 -1
  60. package/dist/esm/index.d.ts +5 -1
  61. package/dist/esm/index.js +1 -1
  62. package/dist/esm/plugin.js +1 -1
  63. package/dist/esm/run-node.js +1 -1
  64. package/package.json +2 -2
package/README.md CHANGED
@@ -26,8 +26,8 @@ declaration files automatically using our internal TypeScript compiler.
26
26
  it to generate JavaScript and declaration files with your own version of
27
27
  TypeScript and your own compiler options.
28
28
 
29
- With `protoplugin`, you have all the tools at your disposal to produce ECMAScript-compliant
30
- code.
29
+ With `@bufbuild/protoplugin`, you have all the tools at your disposal to produce
30
+ ECMAScript-compliant code.
31
31
 
32
32
  ## Usage
33
33
 
@@ -1,6 +1,7 @@
1
1
  import { Schema } from "./ecmascript/schema.js";
2
2
  import type { FileInfo } from "./ecmascript/generated-file.js";
3
3
  import type { Plugin } from "./plugin.js";
4
+ import type { FeatureSetDefaults } from "@bufbuild/protobuf";
4
5
  interface PluginInit {
5
6
  /**
6
7
  * Name of this code generator plugin.
@@ -15,6 +16,20 @@ interface PluginInit {
15
16
  * options.
16
17
  */
17
18
  parseOption?: (key: string, value: string) => void;
19
+ /**
20
+ * Whether the plugin supports editions.
21
+ */
22
+ supportsEditions?: boolean;
23
+ /**
24
+ * By default, plugins support all editions supported by createDescriptorSet()
25
+ * from @bufbuild/protobuf, if supportsEditions is enabled.
26
+ *
27
+ * This option can be used to limit support for specific editions, by providing
28
+ * your own google.protobuf.FeatureSetDefaults generated by protoc with the
29
+ * flags --experimental_edition_defaults_out, --experimental_edition_defaults_minimum,
30
+ * and --experimental_edition_defaults_maximum.
31
+ */
32
+ featureSetDefaults?: FeatureSetDefaults;
18
33
  /**
19
34
  * A function which will generate TypeScript files based on proto input.
20
35
  * This function will be invoked by the plugin framework when the plugin runs.
@@ -45,14 +60,19 @@ interface PluginInit {
45
60
  */
46
61
  generateDts?: (schema: Schema, target: "dts") => void;
47
62
  /**
48
- * A optional function which will transpile a given set of files.
63
+ * An optional function which will transpile a given set of files.
49
64
  *
50
- * This funcion is meant to be used in place of either generateJs,
65
+ * This function is meant to be used in place of either generateJs,
51
66
  * generateDts, or both. However, those functions will take precedence.
52
67
  * This means that if generateJs, generateDts, and this transpile function
53
68
  * are all provided, this transpile function will be ignored.
69
+ *
70
+ * If jsImportStyle is "module" (the standard behavior), the function is
71
+ * expected to use ECMAScript module import and export statements when
72
+ * transpiling to JS. If jsImportStyle is "legacy_commonjs", the function is
73
+ * expected to use CommonJs require() and exports when transpiling to JS.
54
74
  */
55
- transpile?: (files: FileInfo[], transpileJs: boolean, transpileDts: boolean) => FileInfo[];
75
+ transpile?: (files: FileInfo[], transpileJs: boolean, transpileDts: boolean, jsImportStyle: "module" | "legacy_commonjs") => FileInfo[];
56
76
  }
57
77
  /**
58
78
  * Create a new code generator plugin for ECMAScript.
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // Copyright 2021-2023 Buf Technologies, Inc.
2
+ // Copyright 2021-2024 Buf Technologies, Inc.
3
3
  //
4
4
  // Licensed under the Apache License, Version 2.0 (the "License");
5
5
  // you may not use this file except in compliance with the License.
@@ -16,7 +16,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.createEcmaScriptPlugin = void 0;
17
17
  const schema_js_1 = require("./ecmascript/schema.js");
18
18
  const transpile_js_1 = require("./ecmascript/transpile.js");
19
- const error_js_1 = require("./error.js");
19
+ const parameter_js_1 = require("./ecmascript/parameter.js");
20
+ const protobuf_1 = require("@bufbuild/protobuf");
20
21
  /**
21
22
  * Create a new code generator plugin for ECMAScript.
22
23
  * The plugin can generate JavaScript, TypeScript, or TypeScript declaration
@@ -29,9 +30,9 @@ function createEcmaScriptPlugin(init) {
29
30
  name: init.name,
30
31
  version: init.version,
31
32
  run(req) {
32
- var _a;
33
- const { targets, tsNocheck, bootstrapWkt, rewriteImports, importExtension, keepEmptyFiles, pluginParameter, } = parseParameter(req.parameter, init.parseOption);
34
- const { schema, getFileInfo } = (0, schema_js_1.createSchema)(req, targets, tsNocheck, bootstrapWkt, rewriteImports, importExtension, keepEmptyFiles, init.name, init.version, pluginParameter);
33
+ var _a, _b;
34
+ const parameter = (0, parameter_js_1.parseParameter)(req.parameter, init.parseOption);
35
+ const schema = (0, schema_js_1.createSchema)(req, parameter, init.name, init.version, init.featureSetDefaults);
35
36
  const targetTs = schema.targets.includes("ts");
36
37
  const targetJs = schema.targets.includes("js");
37
38
  const targetDts = schema.targets.includes("dts");
@@ -45,6 +46,7 @@ function createEcmaScriptPlugin(init) {
45
46
  if (targetTs ||
46
47
  (targetJs && !init.generateJs) ||
47
48
  (targetDts && !init.generateDts)) {
49
+ schema.prepareGenerate("ts");
48
50
  init.generateTs(schema, "ts");
49
51
  // Save off the generated TypeScript files so that we can pass these
50
52
  // to the transpilation process if necessary. We do not want to pass
@@ -56,10 +58,11 @@ function createEcmaScriptPlugin(init) {
56
58
  // a generateJs function and expect to transpile declarations.
57
59
  // 3. Transpiling is somewhat expensive and situations with an
58
60
  // extremely large amount of files could have performance impacts.
59
- tsFiles = getFileInfo();
61
+ tsFiles = schema.getFileInfo();
60
62
  }
61
63
  if (targetJs) {
62
64
  if (init.generateJs) {
65
+ schema.prepareGenerate("js");
63
66
  init.generateJs(schema, "js");
64
67
  }
65
68
  else {
@@ -68,6 +71,7 @@ function createEcmaScriptPlugin(init) {
68
71
  }
69
72
  if (targetDts) {
70
73
  if (init.generateDts) {
74
+ schema.prepareGenerate("dts");
71
75
  init.generateDts(schema, "dts");
72
76
  }
73
77
  else {
@@ -79,7 +83,7 @@ function createEcmaScriptPlugin(init) {
79
83
  // generated TypeScript files to assist in transpilation. If they were
80
84
  // generated but not specified in the target out, we shouldn't produce
81
85
  // these files in the CodeGeneratorResponse.
82
- let files = getFileInfo();
86
+ let files = schema.getFileInfo();
83
87
  if (!targetTs && tsFiles.length > 0) {
84
88
  files = files.filter((file) => !tsFiles.some((tsFile) => tsFile.name === file.name));
85
89
  }
@@ -89,140 +93,27 @@ function createEcmaScriptPlugin(init) {
89
93
  if (transpileJs || transpileDts) {
90
94
  const transpileFn = (_a = init.transpile) !== null && _a !== void 0 ? _a : transpile_js_1.transpile;
91
95
  // Transpile the TypeScript files and add to the master list of files
92
- const transpiledFiles = transpileFn(tsFiles, transpileJs, transpileDts);
96
+ const transpiledFiles = transpileFn(tsFiles, transpileJs, transpileDts, parameter.jsImportStyle);
93
97
  files.push(...transpiledFiles);
94
98
  }
95
- return (0, schema_js_1.toResponse)(files);
99
+ return toResponse(files, (_b = init.supportsEditions) !== null && _b !== void 0 ? _b : false);
96
100
  },
97
101
  };
98
102
  }
99
103
  exports.createEcmaScriptPlugin = createEcmaScriptPlugin;
100
- function parseParameter(parameter, parseOption) {
101
- let targets = ["js", "dts"];
102
- let tsNocheck = true;
103
- let bootstrapWkt = false;
104
- let keepEmptyFiles = false;
105
- const rewriteImports = [];
106
- let importExtension = ".js";
107
- const rawParameters = [];
108
- for (const { key, value, raw } of splitParameter(parameter)) {
109
- // Whether this key/value plugin parameter pair should be
110
- // printed to the generated file preamble
111
- let printToFile = true;
112
- switch (key) {
113
- case "target":
114
- targets = [];
115
- for (const rawTarget of value.split("+")) {
116
- switch (rawTarget) {
117
- case "js":
118
- case "ts":
119
- case "dts":
120
- if (targets.indexOf(rawTarget) < 0) {
121
- targets.push(rawTarget);
122
- }
123
- break;
124
- default:
125
- throw new error_js_1.PluginOptionError(raw);
126
- }
127
- }
128
- value.split("+");
129
- break;
130
- case "ts_nocheck":
131
- switch (value) {
132
- case "true":
133
- case "1":
134
- tsNocheck = true;
135
- break;
136
- case "false":
137
- case "0":
138
- tsNocheck = false;
139
- break;
140
- default:
141
- throw new error_js_1.PluginOptionError(raw);
142
- }
143
- break;
144
- case "bootstrap_wkt":
145
- switch (value) {
146
- case "true":
147
- case "1":
148
- bootstrapWkt = true;
149
- break;
150
- case "false":
151
- case "0":
152
- bootstrapWkt = false;
153
- break;
154
- default:
155
- throw new error_js_1.PluginOptionError(raw);
156
- }
157
- break;
158
- case "rewrite_imports": {
159
- const parts = value.split(":");
160
- if (parts.length !== 2) {
161
- throw new error_js_1.PluginOptionError(raw, "must be in the form of <pattern>:<target>");
162
- }
163
- const [pattern, target] = parts;
164
- rewriteImports.push({ pattern, target });
165
- // rewrite_imports can be noisy and is more of an implementation detail
166
- // so we strip it out of the preamble
167
- printToFile = false;
168
- break;
169
- }
170
- case "import_extension": {
171
- importExtension = value === "none" ? "" : value;
172
- break;
173
- }
174
- case "keep_empty_files": {
175
- switch (value) {
176
- case "true":
177
- case "1":
178
- keepEmptyFiles = true;
179
- break;
180
- case "false":
181
- case "0":
182
- keepEmptyFiles = false;
183
- break;
184
- default:
185
- throw new error_js_1.PluginOptionError(raw);
186
- }
187
- break;
188
- }
189
- default:
190
- if (parseOption === undefined) {
191
- throw new error_js_1.PluginOptionError(raw);
192
- }
193
- try {
194
- parseOption(key, value);
195
- }
196
- catch (e) {
197
- throw new error_js_1.PluginOptionError(raw, e);
198
- }
199
- break;
200
- }
201
- if (printToFile) {
202
- rawParameters.push(raw);
203
- }
204
- }
205
- const pluginParameter = rawParameters.join(",");
206
- return {
207
- targets,
208
- tsNocheck,
209
- bootstrapWkt,
210
- rewriteImports,
211
- importExtension,
212
- keepEmptyFiles,
213
- pluginParameter,
214
- };
215
- }
216
- function splitParameter(parameter) {
217
- if (parameter == undefined) {
218
- return [];
104
+ function toResponse(files, supportsEditions) {
105
+ let supportedFeatures = protobuf_1.CodeGeneratorResponse_Feature.PROTO3_OPTIONAL;
106
+ if (supportsEditions) {
107
+ supportedFeatures =
108
+ supportedFeatures | protobuf_1.CodeGeneratorResponse_Feature.SUPPORTS_EDITIONS;
219
109
  }
220
- return parameter.split(",").map((raw) => {
221
- const i = raw.indexOf("=");
222
- return {
223
- key: i === -1 ? raw : raw.substring(0, i),
224
- value: i === -1 ? "" : raw.substring(i + 1),
225
- raw,
226
- };
110
+ return new protobuf_1.CodeGeneratorResponse({
111
+ supportedFeatures: protobuf_1.protoInt64.parse(supportedFeatures),
112
+ file: files.map((f) => {
113
+ if (f.preamble !== undefined) {
114
+ f.content = f.preamble + "\n" + f.content;
115
+ }
116
+ return f;
117
+ }),
227
118
  });
228
119
  }
@@ -1,12 +1,16 @@
1
1
  import type { AnyDesc } from "@bufbuild/protobuf";
2
2
  import { Message, MessageType, ScalarType } from "@bufbuild/protobuf";
3
3
  /**
4
+ * @deprecated Please use extensions instead.
5
+ *
4
6
  * Returns the value of a custom option with a scalar type.
5
7
  *
6
8
  * If no option is found, returns undefined.
7
9
  */
8
10
  export declare function findCustomScalarOption<T extends ScalarType>(desc: AnyDesc, extensionNumber: number, scalarType: T): ScalarValue<T> | undefined;
9
11
  /**
12
+ * @deprecated Please use extensions instead.
13
+ *
10
14
  * Returns the value of a custom message option for the given descriptor and
11
15
  * extension number.
12
16
  * The msgType param is then used to deserialize the message for returning to
@@ -19,6 +23,8 @@ export declare function findCustomScalarOption<T extends ScalarType>(desc: AnyDe
19
23
  */
20
24
  export declare function findCustomMessageOption<T extends Message<T>>(desc: AnyDesc, extensionNumber: number, msgType: MessageType<T>): T | undefined;
21
25
  /**
26
+ * @deprecated Please use extensions instead.
27
+ *
22
28
  * Returns the value of a custom enum option for the given descriptor and
23
29
  * extension number.
24
30
  *
@@ -26,6 +32,8 @@ export declare function findCustomMessageOption<T extends Message<T>>(desc: AnyD
26
32
  */
27
33
  export declare function findCustomEnumOption(desc: AnyDesc, extensionNumber: number): number | undefined;
28
34
  /**
35
+ * @deprecated Please use extensions instead.
36
+ *
29
37
  * ScalarValue is a conditional type that pairs a ScalarType value with its concrete type.
30
38
  */
31
39
  type ScalarValue<T> = T extends ScalarType.STRING ? string : T extends ScalarType.INT32 ? number : T extends ScalarType.UINT32 ? number : T extends ScalarType.UINT32 ? number : T extends ScalarType.SINT32 ? number : T extends ScalarType.FIXED32 ? number : T extends ScalarType.SFIXED32 ? number : T extends ScalarType.FLOAT ? number : T extends ScalarType.DOUBLE ? number : T extends ScalarType.INT64 ? bigint | string : T extends ScalarType.SINT64 ? bigint | string : T extends ScalarType.SFIXED64 ? bigint | string : T extends ScalarType.UINT64 ? bigint | string : T extends ScalarType.FIXED64 ? bigint | string : T extends ScalarType.BOOL ? boolean : T extends ScalarType.BYTES ? Uint8Array : never;
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // Copyright 2021-2023 Buf Technologies, Inc.
2
+ // Copyright 2021-2024 Buf Technologies, Inc.
3
3
  //
4
4
  // Licensed under the Apache License, Version 2.0 (the "License");
5
5
  // you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.findCustomEnumOption = exports.findCustomMessageOption = exports.findCustomScalarOption = void 0;
17
17
  const protobuf_1 = require("@bufbuild/protobuf");
18
18
  /**
19
+ * @deprecated Please use extensions instead.
20
+ *
19
21
  * Returns the value of a custom option with a scalar type.
20
22
  *
21
23
  * If no option is found, returns undefined.
@@ -63,6 +65,8 @@ function findCustomScalarOption(desc, extensionNumber, scalarType) {
63
65
  }
64
66
  exports.findCustomScalarOption = findCustomScalarOption;
65
67
  /**
68
+ * @deprecated Please use extensions instead.
69
+ *
66
70
  * Returns the value of a custom message option for the given descriptor and
67
71
  * extension number.
68
72
  * The msgType param is then used to deserialize the message for returning to
@@ -89,6 +93,8 @@ function findCustomMessageOption(desc, extensionNumber, msgType) {
89
93
  }
90
94
  exports.findCustomMessageOption = findCustomMessageOption;
91
95
  /**
96
+ * @deprecated Please use extensions instead.
97
+ *
92
98
  * Returns the value of a custom enum option for the given descriptor and
93
99
  * extension number.
94
100
  *
@@ -0,0 +1,7 @@
1
+ import { DescEnum, DescExtension, DescMessage } from "@bufbuild/protobuf";
2
+ export type ExportDeclaration = {
3
+ readonly kind: "es_export_decl";
4
+ declaration: string;
5
+ name: string | DescMessage | DescEnum | DescExtension;
6
+ };
7
+ export declare function createExportDeclaration(declaration: string, name: ExportDeclaration["name"]): ExportDeclaration;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ // Copyright 2021-2024 Buf Technologies, Inc.
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.createExportDeclaration = void 0;
17
+ function createExportDeclaration(declaration, name) {
18
+ return {
19
+ kind: "es_export_decl",
20
+ declaration,
21
+ name,
22
+ };
23
+ }
24
+ exports.createExportDeclaration = createExportDeclaration;
@@ -1,20 +1,19 @@
1
- import { DescEnum, DescEnumValue, DescField, DescFile, DescMessage, DescMethod, DescOneof, DescService, LongType, ScalarType } from "@bufbuild/protobuf";
1
+ import type { DescExtension } from "@bufbuild/protobuf";
2
+ import { DescField, DescFile, LongType, ScalarType } from "@bufbuild/protobuf";
2
3
  import type { GeneratedFile, Printable } from "./generated-file.js";
3
4
  import type { ImportSymbol } from "./import-symbol.js";
4
5
  export declare function makeFilePreamble(file: DescFile, pluginName: string, pluginVersion: string, parameter: string, tsNoCheck: boolean): string;
5
- export declare function createJsDocBlock(text: string, indentation?: string): Printable;
6
- export declare function makeJsDoc(desc: DescEnum | DescEnumValue | DescMessage | DescOneof | DescField | DescService | DescMethod, indentation?: string): Printable;
7
6
  /**
8
7
  * Returns an expression for the TypeScript typing of a field,
9
8
  * and whether the property should be optional.
10
9
  */
11
- export declare function getFieldTyping(field: DescField, file: GeneratedFile): {
10
+ export declare function getFieldTyping(field: DescField | DescExtension, file: GeneratedFile): {
12
11
  typing: Printable;
13
12
  optional: boolean;
14
13
  };
15
14
  export declare function scalarTypeScriptType(type: ScalarType, longType: LongType): Printable;
16
15
  export declare function literalString(value: string): string;
17
- export declare function getFieldExplicitDefaultValue(field: DescField, protoInt64Symbol: ImportSymbol): Printable | undefined;
16
+ export declare function getFieldExplicitDefaultValue(field: DescField | DescExtension, protoInt64Symbol: ImportSymbol): Printable | undefined;
18
17
  export declare function getFieldIntrinsicDefaultValue(field: DescField): {
19
18
  defaultValue: Printable | undefined;
20
19
  typingInferrable: boolean;
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // Copyright 2021-2023 Buf Technologies, Inc.
2
+ // Copyright 2021-2024 Buf Technologies, Inc.
3
3
  //
4
4
  // Licensed under the Apache License, Version 2.0 (the "License");
5
5
  // you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
13
13
  // See the License for the specific language governing permissions and
14
14
  // limitations under the License.
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.getFieldIntrinsicDefaultValue = exports.getFieldExplicitDefaultValue = exports.literalString = exports.scalarTypeScriptType = exports.getFieldTyping = exports.makeJsDoc = exports.createJsDocBlock = exports.makeFilePreamble = void 0;
16
+ exports.getFieldIntrinsicDefaultValue = exports.getFieldExplicitDefaultValue = exports.literalString = exports.scalarTypeScriptType = exports.getFieldTyping = exports.makeFilePreamble = void 0;
17
17
  const protobuf_1 = require("@bufbuild/protobuf");
18
18
  const { localName, getUnwrappedFieldType, scalarDefaultValue } = protobuf_1.codegenInfo;
19
19
  function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsNoCheck) {
@@ -73,80 +73,6 @@ function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsNoCheck)
73
73
  return trimSuffix(builder.join(""), "\n");
74
74
  }
75
75
  exports.makeFilePreamble = makeFilePreamble;
76
- function createJsDocBlock(text, indentation = "") {
77
- if (text.trim().length == 0) {
78
- return [];
79
- }
80
- let lines = text.split("\n");
81
- if (lines.length === 0) {
82
- return [];
83
- }
84
- lines = lines.map((l) => l.split("*/").join("*\\/"));
85
- lines = lines.map((l) => (l.length > 0 ? " " + l : l));
86
- // prettier-ignore
87
- return [
88
- `${indentation}/**\n`,
89
- ...lines.map((l) => `${indentation} *${l}\n`),
90
- `${indentation} */`
91
- ];
92
- }
93
- exports.createJsDocBlock = createJsDocBlock;
94
- function makeJsDoc(desc, indentation = "") {
95
- var _a, _b;
96
- const comments = desc.getComments();
97
- let text = "";
98
- if (comments.leading !== undefined) {
99
- text += comments.leading;
100
- if (text.endsWith("\n")) {
101
- text = text.substring(0, text.length - 1);
102
- }
103
- }
104
- if (comments.trailing !== undefined) {
105
- if (text.length > 0) {
106
- text += "\n\n";
107
- }
108
- text += comments.trailing;
109
- if (text.endsWith("\n")) {
110
- text = text.substring(0, text.length - 1);
111
- }
112
- }
113
- if (text.length > 0) {
114
- text += "\n\n";
115
- }
116
- text = text
117
- .split("\n")
118
- .map((line) => (line.startsWith(" ") ? line.substring(1) : line))
119
- .join("\n");
120
- switch (desc.kind) {
121
- case "enum_value":
122
- text += `@generated from enum value: ${desc.declarationString()};`;
123
- break;
124
- case "field":
125
- text += `@generated from field: ${desc.declarationString()};`;
126
- break;
127
- default:
128
- text += `@generated from ${desc.toString()}`;
129
- break;
130
- }
131
- let deprecated = desc.deprecated;
132
- switch (desc.kind) {
133
- case "enum":
134
- case "message":
135
- case "service":
136
- deprecated = deprecated || ((_b = (_a = desc.file.proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false);
137
- break;
138
- default:
139
- break;
140
- }
141
- if (deprecated) {
142
- text += "\n@deprecated";
143
- }
144
- if (text.length > 0) {
145
- return createJsDocBlock(text, indentation);
146
- }
147
- return [];
148
- }
149
- exports.makeJsDoc = makeJsDoc;
150
76
  /**
151
77
  * Returns an expression for the TypeScript typing of a field,
152
78
  * and whether the property should be optional.
@@ -1,10 +1,12 @@
1
- import type { DescEnum, DescFile, DescMessage } from "@bufbuild/protobuf";
1
+ import type { AnyDesc, DescEnum, DescExtension, DescFile, DescMessage } from "@bufbuild/protobuf";
2
2
  import type { ImportSymbol } from "./import-symbol.js";
3
3
  import type { RuntimeImports } from "./runtime-imports.js";
4
+ import type { ExportDeclaration } from "./export-declaration.js";
5
+ import type { JSDocBlock } from "./jsdoc.js";
4
6
  /**
5
7
  * All types that can be passed to GeneratedFile.print()
6
8
  */
7
- export type Printable = string | number | boolean | bigint | Uint8Array | ImportSymbol | DescMessage | DescEnum | Printable[];
9
+ export type Printable = string | number | boolean | bigint | Uint8Array | ImportSymbol | ExportDeclaration | JSDocBlock | DescMessage | DescEnum | DescExtension | Printable[];
8
10
  /**
9
11
  * FileInfo represents an intermediate type using for transpiling TypeScript internally.
10
12
  */
@@ -48,13 +50,45 @@ export interface GeneratedFile {
48
50
  */
49
51
  print(fragments: TemplateStringsArray, ...printables: Printable[]): void;
50
52
  /**
51
- * Reserves an identifier in this file.
53
+ * @deprecated Please use createImportSymbol() from @bufbuild/protoplugin/ecmascript instead
52
54
  */
53
55
  export(name: string): ImportSymbol;
56
+ /**
57
+ * Create a string literal.
58
+ */
59
+ string(string: string): Printable;
60
+ /**
61
+ * Create a JSDoc comment block with the given text. Line breaks and white-space
62
+ * stay intact.
63
+ */
64
+ jsDoc(text: string, indentation?: string): JSDocBlock;
65
+ /**
66
+ * Create a JSDoc comment block for the given message, enumeration, or other
67
+ * descriptor. The comment block will contain the original comments from the
68
+ * protobuf source, and annotations such as `@generated from message MyMessage`.
69
+ */
70
+ jsDoc(desc: Exclude<AnyDesc, DescFile>, indentation?: string): JSDocBlock;
71
+ /**
72
+ * Create a printable export statement. For example:
73
+ *
74
+ * ```ts
75
+ * f.print(f.exportDecl("abstract class", "MyClass"), " {}")
76
+ * ```
77
+ *
78
+ * Will generate as:
79
+ * ```ts
80
+ * export abstract class MyClass {}
81
+ * ```
82
+ *
83
+ * Using this method is preferred over a calling print() with a literal export
84
+ * statement. If the plugin option `js_import_style=legacy_commonjs` is set,
85
+ * exports will automatically be generated for CommonJS.
86
+ */
87
+ exportDecl(declaration: string, name: string | DescMessage | DescEnum | DescExtension): Printable;
54
88
  /**
55
89
  * Import a message or enumeration generated by protoc-gen-es.
56
90
  */
57
- import(type: DescMessage | DescEnum): ImportSymbol;
91
+ import(type: DescMessage | DescEnum | DescExtension): ImportSymbol;
58
92
  /**
59
93
  * Import any symbol from a file or package.
60
94
  *
@@ -66,16 +100,17 @@ export interface GeneratedFile {
66
100
  * relative to the current file.
67
101
  */
68
102
  import(name: string, from: string): ImportSymbol;
103
+ /**
104
+ * In case you need full control over exports and imports, use print() and
105
+ * formulate your own imports and exports based on this property.
106
+ */
107
+ readonly jsImportStyle: "module" | "legacy_commonjs";
69
108
  }
70
- export interface GenerateFileToFileInfo {
71
- getFileInfo(): FileInfo | undefined;
109
+ export interface GeneratedFileController extends GeneratedFile {
110
+ getFileInfo(): FileInfo;
72
111
  }
73
- type CreateTypeImportFn = (desc: DescMessage | DescEnum) => ImportSymbol;
112
+ type CreateTypeImportFn = (desc: DescMessage | DescEnum | DescExtension) => ImportSymbol;
74
113
  type RewriteImportPathFn = (path: string) => string;
75
- export declare function createGeneratedFile(name: string, importPath: string, rewriteImportPath: RewriteImportPathFn, createTypeImport: CreateTypeImportFn, runtimeImports: RuntimeImports, preambleSettings: {
76
- pluginName: string;
77
- pluginVersion: string;
78
- pluginParameter: string;
79
- tsNocheck: boolean;
80
- }, keepEmpty: boolean): GeneratedFile & GenerateFileToFileInfo;
114
+ type CreatePreambleFn = (descFile: DescFile) => string;
115
+ export declare function createGeneratedFile(name: string, importPath: string, jsImportStyle: "module" | "legacy_commonjs", rewriteImportPath: RewriteImportPathFn, createTypeImport: CreateTypeImportFn, runtimeImports: RuntimeImports, createPreamble: CreatePreambleFn): GeneratedFileController;
81
116
  export {};