@bufbuild/protoplugin 1.5.0 → 1.6.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 (42) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/create-es-plugin.d.ts +11 -7
  3. package/dist/cjs/create-es-plugin.js +19 -133
  4. package/dist/cjs/ecmascript/export-declaration.d.ts +7 -0
  5. package/dist/cjs/ecmascript/export-declaration.js +24 -0
  6. package/dist/cjs/ecmascript/gencommon.d.ts +1 -3
  7. package/dist/cjs/ecmascript/gencommon.js +20 -76
  8. package/dist/cjs/ecmascript/generated-file.d.ts +46 -7
  9. package/dist/cjs/ecmascript/generated-file.js +79 -17
  10. package/dist/cjs/ecmascript/index.d.ts +21 -6
  11. package/dist/cjs/ecmascript/index.js +30 -8
  12. package/dist/cjs/ecmascript/jsdoc.d.ts +8 -0
  13. package/dist/cjs/ecmascript/jsdoc.js +90 -0
  14. package/dist/cjs/ecmascript/parameter.d.ts +13 -0
  15. package/dist/cjs/ecmascript/parameter.js +161 -0
  16. package/dist/cjs/ecmascript/schema.d.ts +4 -6
  17. package/dist/cjs/ecmascript/schema.js +21 -33
  18. package/dist/cjs/ecmascript/transpile.d.ts +1 -1
  19. package/dist/cjs/ecmascript/transpile.js +4 -1
  20. package/dist/cjs/error.js +4 -3
  21. package/dist/cjs/index.d.ts +5 -1
  22. package/dist/esm/create-es-plugin.d.ts +11 -7
  23. package/dist/esm/create-es-plugin.js +19 -133
  24. package/dist/esm/ecmascript/export-declaration.d.ts +7 -0
  25. package/dist/esm/ecmascript/export-declaration.js +20 -0
  26. package/dist/esm/ecmascript/gencommon.d.ts +1 -3
  27. package/dist/esm/ecmascript/gencommon.js +20 -74
  28. package/dist/esm/ecmascript/generated-file.d.ts +46 -7
  29. package/dist/esm/ecmascript/generated-file.js +79 -17
  30. package/dist/esm/ecmascript/index.d.ts +21 -6
  31. package/dist/esm/ecmascript/index.js +23 -2
  32. package/dist/esm/ecmascript/jsdoc.d.ts +8 -0
  33. package/dist/esm/ecmascript/jsdoc.js +86 -0
  34. package/dist/esm/ecmascript/parameter.d.ts +13 -0
  35. package/dist/esm/ecmascript/parameter.js +157 -0
  36. package/dist/esm/ecmascript/schema.d.ts +4 -6
  37. package/dist/esm/ecmascript/schema.js +21 -32
  38. package/dist/esm/ecmascript/transpile.d.ts +1 -1
  39. package/dist/esm/ecmascript/transpile.js +4 -1
  40. package/dist/esm/error.js +4 -3
  41. package/dist/esm/index.d.ts +5 -1
  42. package/package.json +14 -6
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
 
@@ -11,10 +11,10 @@ interface PluginInit {
11
11
  */
12
12
  version: string;
13
13
  /**
14
- * A optional parsing function which can be used to customize parameter
15
- * parsing of the plugin.
14
+ * An optional parsing function which can be used to parse your own plugin
15
+ * options.
16
16
  */
17
- parseOption?: PluginOptionParseFn;
17
+ parseOption?: (key: string, value: string) => void;
18
18
  /**
19
19
  * A function which will generate TypeScript files based on proto input.
20
20
  * This function will be invoked by the plugin framework when the plugin runs.
@@ -45,16 +45,20 @@ interface PluginInit {
45
45
  */
46
46
  generateDts?: (schema: Schema, target: "dts") => void;
47
47
  /**
48
- * A optional function which will transpile a given set of files.
48
+ * An optional function which will transpile a given set of files.
49
49
  *
50
- * This funcion is meant to be used in place of either generateJs,
50
+ * This function is meant to be used in place of either generateJs,
51
51
  * generateDts, or both. However, those functions will take precedence.
52
52
  * This means that if generateJs, generateDts, and this transpile function
53
53
  * are all provided, this transpile function will be ignored.
54
+ *
55
+ * If jsImportStyle is "module" (the standard behavior), the function is
56
+ * expected to use ECMAScript module import and export statements when
57
+ * transpiling to JS. If jsImportStyle is "legacy_commonjs", the function is
58
+ * expected to use CommonJs require() and exports when transpiling to JS.
54
59
  */
55
- transpile?: (files: FileInfo[], transpileJs: boolean, transpileDts: boolean) => FileInfo[];
60
+ transpile?: (files: FileInfo[], transpileJs: boolean, transpileDts: boolean, jsImportStyle: "module" | "legacy_commonjs") => FileInfo[];
56
61
  }
57
- type PluginOptionParseFn = (key: string, value: string | undefined) => void;
58
62
  /**
59
63
  * Create a new code generator plugin for ECMAScript.
60
64
  * The plugin can generate JavaScript, TypeScript, or TypeScript declaration
@@ -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
@@ -30,8 +31,8 @@ function createEcmaScriptPlugin(init) {
30
31
  version: init.version,
31
32
  run(req) {
32
33
  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);
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);
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,22 @@ 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);
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(`${key}=${value}`);
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(`${key}=${value}`);
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(`${key}=${value}`);
156
- }
157
- break;
158
- case "rewrite_imports": {
159
- const parts = value.split(":");
160
- if (parts.length !== 2) {
161
- throw new error_js_1.PluginOptionError(`${key}=${value}`, "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(`${key}=${value}`);
186
- }
187
- break;
104
+ function toResponse(files) {
105
+ return new protobuf_1.CodeGeneratorResponse({
106
+ supportedFeatures: protobuf_1.protoInt64.parse(protobuf_1.CodeGeneratorResponse_Feature.PROTO3_OPTIONAL),
107
+ file: files.map((f) => {
108
+ if (f.preamble !== undefined) {
109
+ f.content = f.preamble + "\n" + f.content;
188
110
  }
189
- default:
190
- if (parseOption === undefined) {
191
- throw new error_js_1.PluginOptionError(`${key}=${value}`);
192
- }
193
- try {
194
- parseOption(key, value);
195
- }
196
- catch (e) {
197
- throw new error_js_1.PluginOptionError(`${key}=${value}`, 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 [];
219
- }
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
- };
111
+ return f;
112
+ }),
227
113
  });
228
114
  }
@@ -0,0 +1,7 @@
1
+ import { DescEnum, DescMessage } from "@bufbuild/protobuf";
2
+ export type ExportDeclaration = {
3
+ readonly kind: "es_export_decl";
4
+ declaration: string;
5
+ name: string | DescMessage | DescEnum;
6
+ };
7
+ export declare function createExportDeclaration(declaration: string, name: ExportDeclaration["name"]): ExportDeclaration;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ // Copyright 2021-2023 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,9 +1,7 @@
1
- import { DescEnum, DescEnumValue, DescField, DescFile, DescMessage, DescMethod, DescOneof, DescService, LongType, ScalarType } from "@bufbuild/protobuf";
1
+ import { DescField, DescFile, LongType, ScalarType } from "@bufbuild/protobuf";
2
2
  import type { GeneratedFile, Printable } from "./generated-file.js";
3
3
  import type { ImportSymbol } from "./import-symbol.js";
4
4
  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
5
  /**
8
6
  * Returns an expression for the TypeScript typing of a field,
9
7
  * and whether the property should be optional.
@@ -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) {
@@ -45,7 +45,25 @@ function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsNoCheck)
45
45
  if (file.proto.package !== undefined) {
46
46
  builder.push(`package ${file.proto.package}, `);
47
47
  }
48
- builder.push(`syntax ${file.syntax})\n`);
48
+ switch (file.edition) {
49
+ case protobuf_1.Edition.EDITION_PROTO2:
50
+ builder.push(`syntax proto2)\n`);
51
+ break;
52
+ case protobuf_1.Edition.EDITION_PROTO3:
53
+ builder.push(`syntax proto3)\n`);
54
+ break;
55
+ default: {
56
+ const editionString = protobuf_1.Edition[file.edition];
57
+ if (typeof editionString == "string") {
58
+ const e = editionString.replace("EDITION_", "").toLowerCase();
59
+ builder.push(`edition ${e})\n`);
60
+ }
61
+ else {
62
+ builder.push(`unknown edition\n`);
63
+ }
64
+ break;
65
+ }
66
+ }
49
67
  builder.push("/* eslint-disable */\n");
50
68
  if (tsNoCheck) {
51
69
  builder.push("// @ts-nocheck\n");
@@ -55,80 +73,6 @@ function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsNoCheck)
55
73
  return trimSuffix(builder.join(""), "\n");
56
74
  }
57
75
  exports.makeFilePreamble = makeFilePreamble;
58
- function createJsDocBlock(text, indentation = "") {
59
- if (text.trim().length == 0) {
60
- return [];
61
- }
62
- let lines = text.split("\n");
63
- if (lines.length === 0) {
64
- return [];
65
- }
66
- lines = lines.map((l) => l.split("*/").join("*\\/"));
67
- lines = lines.map((l) => (l.length > 0 ? " " + l : l));
68
- // prettier-ignore
69
- return [
70
- `${indentation}/**\n`,
71
- ...lines.map((l) => `${indentation} *${l}\n`),
72
- `${indentation} */`
73
- ];
74
- }
75
- exports.createJsDocBlock = createJsDocBlock;
76
- function makeJsDoc(desc, indentation = "") {
77
- var _a, _b;
78
- const comments = desc.getComments();
79
- let text = "";
80
- if (comments.leading !== undefined) {
81
- text += comments.leading;
82
- if (text.endsWith("\n")) {
83
- text = text.substring(0, text.length - 1);
84
- }
85
- }
86
- if (comments.trailing !== undefined) {
87
- if (text.length > 0) {
88
- text += "\n\n";
89
- }
90
- text += comments.trailing;
91
- if (text.endsWith("\n")) {
92
- text = text.substring(0, text.length - 1);
93
- }
94
- }
95
- if (text.length > 0) {
96
- text += "\n\n";
97
- }
98
- text = text
99
- .split("\n")
100
- .map((line) => (line.startsWith(" ") ? line.substring(1) : line))
101
- .join("\n");
102
- switch (desc.kind) {
103
- case "enum_value":
104
- text += `@generated from enum value: ${desc.declarationString()};`;
105
- break;
106
- case "field":
107
- text += `@generated from field: ${desc.declarationString()};`;
108
- break;
109
- default:
110
- text += `@generated from ${desc.toString()}`;
111
- break;
112
- }
113
- let deprecated = desc.deprecated;
114
- switch (desc.kind) {
115
- case "enum":
116
- case "message":
117
- case "service":
118
- deprecated = deprecated || ((_b = (_a = desc.file.proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false);
119
- break;
120
- default:
121
- break;
122
- }
123
- if (deprecated) {
124
- text += "\n@deprecated";
125
- }
126
- if (text.length > 0) {
127
- return createJsDocBlock(text, indentation);
128
- }
129
- return [];
130
- }
131
- exports.makeJsDoc = makeJsDoc;
132
76
  /**
133
77
  * Returns an expression for the TypeScript typing of a field,
134
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 | Printable[];
8
10
  /**
9
11
  * FileInfo represents an intermediate type using for transpiling TypeScript internally.
10
12
  */
@@ -48,9 +50,41 @@ 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 | DescExtension>, 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): Printable;
54
88
  /**
55
89
  * Import a message or enumeration generated by protoc-gen-es.
56
90
  */
@@ -66,16 +100,21 @@ 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
112
  type CreateTypeImportFn = (desc: DescMessage | DescEnum) => ImportSymbol;
74
113
  type RewriteImportPathFn = (path: string) => string;
75
- export declare function createGeneratedFile(name: string, importPath: string, rewriteImportPath: RewriteImportPathFn, createTypeImport: CreateTypeImportFn, runtimeImports: RuntimeImports, preambleSettings: {
114
+ export declare function createGeneratedFile(name: string, importPath: string, jsImportStyle: "module" | "legacy_commonjs", rewriteImportPath: RewriteImportPathFn, createTypeImport: CreateTypeImportFn, runtimeImports: RuntimeImports, preambleSettings: {
76
115
  pluginName: string;
77
116
  pluginVersion: string;
78
117
  pluginParameter: string;
79
118
  tsNocheck: boolean;
80
- }, keepEmpty: boolean): GeneratedFile & GenerateFileToFileInfo;
119
+ }): GeneratedFileController;
81
120
  export {};
@@ -17,7 +17,9 @@ exports.createGeneratedFile = void 0;
17
17
  const import_symbol_js_1 = require("./import-symbol.js");
18
18
  const gencommon_js_1 = require("./gencommon.js");
19
19
  const import_path_js_1 = require("./import-path.js");
20
- function createGeneratedFile(name, importPath, rewriteImportPath, createTypeImport, runtimeImports, preambleSettings, keepEmpty) {
20
+ const export_declaration_js_1 = require("./export-declaration.js");
21
+ const jsdoc_js_1 = require("./jsdoc.js");
22
+ function createGeneratedFile(name, importPath, jsImportStyle, rewriteImportPath, createTypeImport, runtimeImports, preambleSettings) {
21
23
  let preamble;
22
24
  const el = [];
23
25
  return {
@@ -44,6 +46,15 @@ function createGeneratedFile(name, importPath, rewriteImportPath, createTypeImpo
44
46
  export(name) {
45
47
  return (0, import_symbol_js_1.createImportSymbol)(name, importPath);
46
48
  },
49
+ exportDecl(declaration, name) {
50
+ return (0, export_declaration_js_1.createExportDeclaration)(declaration, name);
51
+ },
52
+ string(string) {
53
+ return (0, gencommon_js_1.literalString)(string);
54
+ },
55
+ jsDoc(textOrDesc, indentation) {
56
+ return (0, jsdoc_js_1.createJsDocBlock)(textOrDesc, indentation);
57
+ },
47
58
  import(typeOrName, from) {
48
59
  if (typeof typeOrName == "string") {
49
60
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -51,43 +62,82 @@ function createGeneratedFile(name, importPath, rewriteImportPath, createTypeImpo
51
62
  }
52
63
  return createTypeImport(typeOrName);
53
64
  },
65
+ jsImportStyle,
54
66
  getFileInfo() {
55
- const content = elToContent(el, importPath, rewriteImportPath);
56
- if (!keepEmpty && content.length === 0) {
57
- return;
58
- }
59
67
  return {
60
68
  name,
61
- content,
69
+ content: elToContent(el, importPath, rewriteImportPath, jsImportStyle == "legacy_commonjs"),
62
70
  preamble,
63
71
  };
64
72
  },
65
73
  };
66
74
  }
67
75
  exports.createGeneratedFile = createGeneratedFile;
68
- function elToContent(el, importerPath, rewriteImportPath) {
76
+ function elToContent(el, importerPath, rewriteImportPath, legacyCommonJs) {
77
+ if (el.length == 0) {
78
+ return "";
79
+ }
69
80
  const c = [];
81
+ if (legacyCommonJs) {
82
+ c.push(`"use strict";\n`);
83
+ c.push(`Object.defineProperty(exports, "__esModule", { value: true });\n`);
84
+ c.push(`\n`);
85
+ }
70
86
  const symbolToIdentifier = processImports(el, importerPath, rewriteImportPath, (typeOnly, from, names) => {
71
- const p = names.map(({ name, alias }) => alias == undefined ? name : `${name} as ${alias}`);
72
- const what = `{ ${p.join(", ")} }`;
73
- if (typeOnly) {
74
- c.push(`import type ${what} from ${(0, gencommon_js_1.literalString)(from)};\n`);
87
+ if (legacyCommonJs) {
88
+ const p = names.map(({ name, alias }) => alias == undefined ? name : `${name}: ${alias}`);
89
+ const what = `{ ${p.join(", ")} }`;
90
+ c.push(`const ${what} = require(${(0, gencommon_js_1.literalString)(from)});\n`);
75
91
  }
76
92
  else {
77
- c.push(`import ${what} from ${(0, gencommon_js_1.literalString)(from)};\n`);
93
+ const p = names.map(({ name, alias }) => alias == undefined ? name : `${name} as ${alias}`);
94
+ const what = `{ ${p.join(", ")} }`;
95
+ if (typeOnly) {
96
+ c.push(`import type ${what} from ${(0, gencommon_js_1.literalString)(from)};\n`);
97
+ }
98
+ else {
99
+ c.push(`import ${what} from ${(0, gencommon_js_1.literalString)(from)};\n`);
100
+ }
78
101
  }
79
102
  });
80
103
  if (c.length > 0) {
81
104
  c.push("\n");
82
105
  }
106
+ const legacyCommonJsExportNames = [];
83
107
  for (const e of el) {
84
108
  if (typeof e == "string") {
85
109
  c.push(e);
86
- continue;
87
110
  }
88
- const ident = symbolToIdentifier.get(e.id);
89
- if (ident != undefined) {
90
- c.push(ident);
111
+ else {
112
+ switch (e.kind) {
113
+ case "es_symbol": {
114
+ const ident = symbolToIdentifier.get(e.id);
115
+ if (ident != undefined) {
116
+ c.push(ident);
117
+ }
118
+ break;
119
+ }
120
+ case "es_export_stmt":
121
+ if (legacyCommonJs) {
122
+ legacyCommonJsExportNames.push(e.name);
123
+ }
124
+ else {
125
+ c.push("export ");
126
+ }
127
+ if (e.declaration !== undefined && e.declaration.length > 0) {
128
+ c.push(e.declaration, " ");
129
+ }
130
+ c.push(e.name);
131
+ break;
132
+ }
133
+ }
134
+ }
135
+ if (legacyCommonJs) {
136
+ if (legacyCommonJsExportNames.length > 0) {
137
+ c.push(`\n`);
138
+ }
139
+ for (const name of legacyCommonJsExportNames) {
140
+ c.push(`exports.`, name, " = ", name, ";\n");
91
141
  }
92
142
  }
93
143
  return c.join("");
@@ -120,6 +170,18 @@ function printableToEl(printables, el, createTypeImport, runtimeImports) {
120
170
  case "es_symbol":
121
171
  el.push(p);
122
172
  break;
173
+ case "es_jsdoc":
174
+ el.push(p.toString());
175
+ break;
176
+ case "es_export_decl":
177
+ el.push({
178
+ kind: "es_export_stmt",
179
+ declaration: p.declaration,
180
+ name: typeof p.name == "string"
181
+ ? p.name
182
+ : createTypeImport(p.name).name,
183
+ });
184
+ break;
123
185
  case "message":
124
186
  case "enum":
125
187
  el.push(createTypeImport(p));
@@ -153,7 +215,7 @@ function processImports(el, importerPath, rewriteImportPath, makeImportStatement
153
215
  const foreignSymbols = [];
154
216
  // Walk through all symbols used and populate the collections above.
155
217
  for (const s of el) {
156
- if (typeof s == "string") {
218
+ if (typeof s != "object" || s.kind !== "es_symbol") {
157
219
  continue;
158
220
  }
159
221
  symbolToIdentifier.set(s.id, s.name);