@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
@@ -11,9 +11,10 @@
11
11
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
- import { createSchema, toResponse } from "./ecmascript/schema.js";
14
+ import { createSchema } from "./ecmascript/schema.js";
15
15
  import { transpile } from "./ecmascript/transpile.js";
16
- import { PluginOptionError } from "./error.js";
16
+ import { parseParameter } from "./ecmascript/parameter.js";
17
+ import { CodeGeneratorResponse, CodeGeneratorResponse_Feature, protoInt64, } from "@bufbuild/protobuf";
17
18
  /**
18
19
  * Create a new code generator plugin for ECMAScript.
19
20
  * The plugin can generate JavaScript, TypeScript, or TypeScript declaration
@@ -27,8 +28,8 @@ export function createEcmaScriptPlugin(init) {
27
28
  version: init.version,
28
29
  run(req) {
29
30
  var _a;
30
- const { targets, tsNocheck, bootstrapWkt, rewriteImports, importExtension, keepEmptyFiles, pluginParameter, } = parseParameter(req.parameter, init.parseOption);
31
- const { schema, getFileInfo } = createSchema(req, targets, tsNocheck, bootstrapWkt, rewriteImports, importExtension, keepEmptyFiles, init.name, init.version, pluginParameter);
31
+ const parameter = parseParameter(req.parameter, init.parseOption);
32
+ const schema = createSchema(req, parameter, init.name, init.version);
32
33
  const targetTs = schema.targets.includes("ts");
33
34
  const targetJs = schema.targets.includes("js");
34
35
  const targetDts = schema.targets.includes("dts");
@@ -42,6 +43,7 @@ export function createEcmaScriptPlugin(init) {
42
43
  if (targetTs ||
43
44
  (targetJs && !init.generateJs) ||
44
45
  (targetDts && !init.generateDts)) {
46
+ schema.prepareGenerate("ts");
45
47
  init.generateTs(schema, "ts");
46
48
  // Save off the generated TypeScript files so that we can pass these
47
49
  // to the transpilation process if necessary. We do not want to pass
@@ -53,10 +55,11 @@ export function createEcmaScriptPlugin(init) {
53
55
  // a generateJs function and expect to transpile declarations.
54
56
  // 3. Transpiling is somewhat expensive and situations with an
55
57
  // extremely large amount of files could have performance impacts.
56
- tsFiles = getFileInfo();
58
+ tsFiles = schema.getFileInfo();
57
59
  }
58
60
  if (targetJs) {
59
61
  if (init.generateJs) {
62
+ schema.prepareGenerate("js");
60
63
  init.generateJs(schema, "js");
61
64
  }
62
65
  else {
@@ -65,6 +68,7 @@ export function createEcmaScriptPlugin(init) {
65
68
  }
66
69
  if (targetDts) {
67
70
  if (init.generateDts) {
71
+ schema.prepareGenerate("dts");
68
72
  init.generateDts(schema, "dts");
69
73
  }
70
74
  else {
@@ -76,7 +80,7 @@ export function createEcmaScriptPlugin(init) {
76
80
  // generated TypeScript files to assist in transpilation. If they were
77
81
  // generated but not specified in the target out, we shouldn't produce
78
82
  // these files in the CodeGeneratorResponse.
79
- let files = getFileInfo();
83
+ let files = schema.getFileInfo();
80
84
  if (!targetTs && tsFiles.length > 0) {
81
85
  files = files.filter((file) => !tsFiles.some((tsFile) => tsFile.name === file.name));
82
86
  }
@@ -86,139 +90,21 @@ export function createEcmaScriptPlugin(init) {
86
90
  if (transpileJs || transpileDts) {
87
91
  const transpileFn = (_a = init.transpile) !== null && _a !== void 0 ? _a : transpile;
88
92
  // Transpile the TypeScript files and add to the master list of files
89
- const transpiledFiles = transpileFn(tsFiles, transpileJs, transpileDts);
93
+ const transpiledFiles = transpileFn(tsFiles, transpileJs, transpileDts, parameter.jsImportStyle);
90
94
  files.push(...transpiledFiles);
91
95
  }
92
96
  return toResponse(files);
93
97
  },
94
98
  };
95
99
  }
96
- function parseParameter(parameter, parseOption) {
97
- let targets = ["js", "dts"];
98
- let tsNocheck = true;
99
- let bootstrapWkt = false;
100
- let keepEmptyFiles = false;
101
- const rewriteImports = [];
102
- let importExtension = ".js";
103
- const rawParameters = [];
104
- for (const { key, value, raw } of splitParameter(parameter)) {
105
- // Whether this key/value plugin parameter pair should be
106
- // printed to the generated file preamble
107
- let printToFile = true;
108
- switch (key) {
109
- case "target":
110
- targets = [];
111
- for (const rawTarget of value.split("+")) {
112
- switch (rawTarget) {
113
- case "js":
114
- case "ts":
115
- case "dts":
116
- if (targets.indexOf(rawTarget) < 0) {
117
- targets.push(rawTarget);
118
- }
119
- break;
120
- default:
121
- throw new PluginOptionError(`${key}=${value}`);
122
- }
123
- }
124
- value.split("+");
125
- break;
126
- case "ts_nocheck":
127
- switch (value) {
128
- case "true":
129
- case "1":
130
- tsNocheck = true;
131
- break;
132
- case "false":
133
- case "0":
134
- tsNocheck = false;
135
- break;
136
- default:
137
- throw new PluginOptionError(`${key}=${value}`);
138
- }
139
- break;
140
- case "bootstrap_wkt":
141
- switch (value) {
142
- case "true":
143
- case "1":
144
- bootstrapWkt = true;
145
- break;
146
- case "false":
147
- case "0":
148
- bootstrapWkt = false;
149
- break;
150
- default:
151
- throw new PluginOptionError(`${key}=${value}`);
152
- }
153
- break;
154
- case "rewrite_imports": {
155
- const parts = value.split(":");
156
- if (parts.length !== 2) {
157
- throw new PluginOptionError(`${key}=${value}`, "must be in the form of <pattern>:<target>");
158
- }
159
- const [pattern, target] = parts;
160
- rewriteImports.push({ pattern, target });
161
- // rewrite_imports can be noisy and is more of an implementation detail
162
- // so we strip it out of the preamble
163
- printToFile = false;
164
- break;
165
- }
166
- case "import_extension": {
167
- importExtension = value === "none" ? "" : value;
168
- break;
169
- }
170
- case "keep_empty_files": {
171
- switch (value) {
172
- case "true":
173
- case "1":
174
- keepEmptyFiles = true;
175
- break;
176
- case "false":
177
- case "0":
178
- keepEmptyFiles = false;
179
- break;
180
- default:
181
- throw new PluginOptionError(`${key}=${value}`);
182
- }
183
- break;
100
+ function toResponse(files) {
101
+ return new CodeGeneratorResponse({
102
+ supportedFeatures: protoInt64.parse(CodeGeneratorResponse_Feature.PROTO3_OPTIONAL),
103
+ file: files.map((f) => {
104
+ if (f.preamble !== undefined) {
105
+ f.content = f.preamble + "\n" + f.content;
184
106
  }
185
- default:
186
- if (parseOption === undefined) {
187
- throw new PluginOptionError(`${key}=${value}`);
188
- }
189
- try {
190
- parseOption(key, value);
191
- }
192
- catch (e) {
193
- throw new PluginOptionError(`${key}=${value}`, e);
194
- }
195
- break;
196
- }
197
- if (printToFile) {
198
- rawParameters.push(raw);
199
- }
200
- }
201
- const pluginParameter = rawParameters.join(",");
202
- return {
203
- targets,
204
- tsNocheck,
205
- bootstrapWkt,
206
- rewriteImports,
207
- importExtension,
208
- keepEmptyFiles,
209
- pluginParameter,
210
- };
211
- }
212
- function splitParameter(parameter) {
213
- if (parameter == undefined) {
214
- return [];
215
- }
216
- return parameter.split(",").map((raw) => {
217
- const i = raw.indexOf("=");
218
- return {
219
- key: i === -1 ? raw : raw.substring(0, i),
220
- value: i === -1 ? "" : raw.substring(i + 1),
221
- raw,
222
- };
107
+ return f;
108
+ }),
223
109
  });
224
110
  }
@@ -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,20 @@
1
+ // Copyright 2021-2023 Buf Technologies, Inc.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ export function createExportDeclaration(declaration, name) {
15
+ return {
16
+ kind: "es_export_decl",
17
+ declaration,
18
+ name,
19
+ };
20
+ }
@@ -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.
@@ -11,7 +11,7 @@
11
11
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
- import { codegenInfo, LongType, ScalarType, } from "@bufbuild/protobuf";
14
+ import { codegenInfo, Edition, LongType, ScalarType, } from "@bufbuild/protobuf";
15
15
  const { localName, getUnwrappedFieldType, scalarDefaultValue } = codegenInfo;
16
16
  export function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsNoCheck) {
17
17
  const builder = [];
@@ -42,7 +42,25 @@ export function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsN
42
42
  if (file.proto.package !== undefined) {
43
43
  builder.push(`package ${file.proto.package}, `);
44
44
  }
45
- builder.push(`syntax ${file.syntax})\n`);
45
+ switch (file.edition) {
46
+ case Edition.EDITION_PROTO2:
47
+ builder.push(`syntax proto2)\n`);
48
+ break;
49
+ case Edition.EDITION_PROTO3:
50
+ builder.push(`syntax proto3)\n`);
51
+ break;
52
+ default: {
53
+ const editionString = Edition[file.edition];
54
+ if (typeof editionString == "string") {
55
+ const e = editionString.replace("EDITION_", "").toLowerCase();
56
+ builder.push(`edition ${e})\n`);
57
+ }
58
+ else {
59
+ builder.push(`unknown edition\n`);
60
+ }
61
+ break;
62
+ }
63
+ }
46
64
  builder.push("/* eslint-disable */\n");
47
65
  if (tsNoCheck) {
48
66
  builder.push("// @ts-nocheck\n");
@@ -51,78 +69,6 @@ export function makeFilePreamble(file, pluginName, pluginVersion, parameter, tsN
51
69
  writeLeadingComments(file.getPackageComments());
52
70
  return trimSuffix(builder.join(""), "\n");
53
71
  }
54
- export function createJsDocBlock(text, indentation = "") {
55
- if (text.trim().length == 0) {
56
- return [];
57
- }
58
- let lines = text.split("\n");
59
- if (lines.length === 0) {
60
- return [];
61
- }
62
- lines = lines.map((l) => l.split("*/").join("*\\/"));
63
- lines = lines.map((l) => (l.length > 0 ? " " + l : l));
64
- // prettier-ignore
65
- return [
66
- `${indentation}/**\n`,
67
- ...lines.map((l) => `${indentation} *${l}\n`),
68
- `${indentation} */`
69
- ];
70
- }
71
- export function makeJsDoc(desc, indentation = "") {
72
- var _a, _b;
73
- const comments = desc.getComments();
74
- let text = "";
75
- if (comments.leading !== undefined) {
76
- text += comments.leading;
77
- if (text.endsWith("\n")) {
78
- text = text.substring(0, text.length - 1);
79
- }
80
- }
81
- if (comments.trailing !== undefined) {
82
- if (text.length > 0) {
83
- text += "\n\n";
84
- }
85
- text += comments.trailing;
86
- if (text.endsWith("\n")) {
87
- text = text.substring(0, text.length - 1);
88
- }
89
- }
90
- if (text.length > 0) {
91
- text += "\n\n";
92
- }
93
- text = text
94
- .split("\n")
95
- .map((line) => (line.startsWith(" ") ? line.substring(1) : line))
96
- .join("\n");
97
- switch (desc.kind) {
98
- case "enum_value":
99
- text += `@generated from enum value: ${desc.declarationString()};`;
100
- break;
101
- case "field":
102
- text += `@generated from field: ${desc.declarationString()};`;
103
- break;
104
- default:
105
- text += `@generated from ${desc.toString()}`;
106
- break;
107
- }
108
- let deprecated = desc.deprecated;
109
- switch (desc.kind) {
110
- case "enum":
111
- case "message":
112
- case "service":
113
- deprecated = deprecated || ((_b = (_a = desc.file.proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false);
114
- break;
115
- default:
116
- break;
117
- }
118
- if (deprecated) {
119
- text += "\n@deprecated";
120
- }
121
- if (text.length > 0) {
122
- return createJsDocBlock(text, indentation);
123
- }
124
- return [];
125
- }
126
72
  /**
127
73
  * Returns an expression for the TypeScript typing of a field,
128
74
  * 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 {};
@@ -14,7 +14,9 @@
14
14
  import { createImportSymbol } from "./import-symbol.js";
15
15
  import { literalString, makeFilePreamble } from "./gencommon.js";
16
16
  import { makeImportPathRelative } from "./import-path.js";
17
- export function createGeneratedFile(name, importPath, rewriteImportPath, createTypeImport, runtimeImports, preambleSettings, keepEmpty) {
17
+ import { createExportDeclaration } from "./export-declaration.js";
18
+ import { createJsDocBlock } from "./jsdoc.js";
19
+ export function createGeneratedFile(name, importPath, jsImportStyle, rewriteImportPath, createTypeImport, runtimeImports, preambleSettings) {
18
20
  let preamble;
19
21
  const el = [];
20
22
  return {
@@ -41,6 +43,15 @@ export function createGeneratedFile(name, importPath, rewriteImportPath, createT
41
43
  export(name) {
42
44
  return createImportSymbol(name, importPath);
43
45
  },
46
+ exportDecl(declaration, name) {
47
+ return createExportDeclaration(declaration, name);
48
+ },
49
+ string(string) {
50
+ return literalString(string);
51
+ },
52
+ jsDoc(textOrDesc, indentation) {
53
+ return createJsDocBlock(textOrDesc, indentation);
54
+ },
44
55
  import(typeOrName, from) {
45
56
  if (typeof typeOrName == "string") {
46
57
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -48,42 +59,81 @@ export function createGeneratedFile(name, importPath, rewriteImportPath, createT
48
59
  }
49
60
  return createTypeImport(typeOrName);
50
61
  },
62
+ jsImportStyle,
51
63
  getFileInfo() {
52
- const content = elToContent(el, importPath, rewriteImportPath);
53
- if (!keepEmpty && content.length === 0) {
54
- return;
55
- }
56
64
  return {
57
65
  name,
58
- content,
66
+ content: elToContent(el, importPath, rewriteImportPath, jsImportStyle == "legacy_commonjs"),
59
67
  preamble,
60
68
  };
61
69
  },
62
70
  };
63
71
  }
64
- function elToContent(el, importerPath, rewriteImportPath) {
72
+ function elToContent(el, importerPath, rewriteImportPath, legacyCommonJs) {
73
+ if (el.length == 0) {
74
+ return "";
75
+ }
65
76
  const c = [];
77
+ if (legacyCommonJs) {
78
+ c.push(`"use strict";\n`);
79
+ c.push(`Object.defineProperty(exports, "__esModule", { value: true });\n`);
80
+ c.push(`\n`);
81
+ }
66
82
  const symbolToIdentifier = processImports(el, importerPath, rewriteImportPath, (typeOnly, from, names) => {
67
- const p = names.map(({ name, alias }) => alias == undefined ? name : `${name} as ${alias}`);
68
- const what = `{ ${p.join(", ")} }`;
69
- if (typeOnly) {
70
- c.push(`import type ${what} from ${literalString(from)};\n`);
83
+ if (legacyCommonJs) {
84
+ const p = names.map(({ name, alias }) => alias == undefined ? name : `${name}: ${alias}`);
85
+ const what = `{ ${p.join(", ")} }`;
86
+ c.push(`const ${what} = require(${literalString(from)});\n`);
71
87
  }
72
88
  else {
73
- c.push(`import ${what} from ${literalString(from)};\n`);
89
+ const p = names.map(({ name, alias }) => alias == undefined ? name : `${name} as ${alias}`);
90
+ const what = `{ ${p.join(", ")} }`;
91
+ if (typeOnly) {
92
+ c.push(`import type ${what} from ${literalString(from)};\n`);
93
+ }
94
+ else {
95
+ c.push(`import ${what} from ${literalString(from)};\n`);
96
+ }
74
97
  }
75
98
  });
76
99
  if (c.length > 0) {
77
100
  c.push("\n");
78
101
  }
102
+ const legacyCommonJsExportNames = [];
79
103
  for (const e of el) {
80
104
  if (typeof e == "string") {
81
105
  c.push(e);
82
- continue;
83
106
  }
84
- const ident = symbolToIdentifier.get(e.id);
85
- if (ident != undefined) {
86
- c.push(ident);
107
+ else {
108
+ switch (e.kind) {
109
+ case "es_symbol": {
110
+ const ident = symbolToIdentifier.get(e.id);
111
+ if (ident != undefined) {
112
+ c.push(ident);
113
+ }
114
+ break;
115
+ }
116
+ case "es_export_stmt":
117
+ if (legacyCommonJs) {
118
+ legacyCommonJsExportNames.push(e.name);
119
+ }
120
+ else {
121
+ c.push("export ");
122
+ }
123
+ if (e.declaration !== undefined && e.declaration.length > 0) {
124
+ c.push(e.declaration, " ");
125
+ }
126
+ c.push(e.name);
127
+ break;
128
+ }
129
+ }
130
+ }
131
+ if (legacyCommonJs) {
132
+ if (legacyCommonJsExportNames.length > 0) {
133
+ c.push(`\n`);
134
+ }
135
+ for (const name of legacyCommonJsExportNames) {
136
+ c.push(`exports.`, name, " = ", name, ";\n");
87
137
  }
88
138
  }
89
139
  return c.join("");
@@ -116,6 +166,18 @@ function printableToEl(printables, el, createTypeImport, runtimeImports) {
116
166
  case "es_symbol":
117
167
  el.push(p);
118
168
  break;
169
+ case "es_jsdoc":
170
+ el.push(p.toString());
171
+ break;
172
+ case "es_export_decl":
173
+ el.push({
174
+ kind: "es_export_stmt",
175
+ declaration: p.declaration,
176
+ name: typeof p.name == "string"
177
+ ? p.name
178
+ : createTypeImport(p.name).name,
179
+ });
180
+ break;
119
181
  case "message":
120
182
  case "enum":
121
183
  el.push(createTypeImport(p));
@@ -149,7 +211,7 @@ function processImports(el, importerPath, rewriteImportPath, makeImportStatement
149
211
  const foreignSymbols = [];
150
212
  // Walk through all symbols used and populate the collections above.
151
213
  for (const s of el) {
152
- if (typeof s == "string") {
214
+ if (typeof s != "object" || s.kind !== "es_symbol") {
153
215
  continue;
154
216
  }
155
217
  symbolToIdentifier.set(s.id, s.name);
@@ -1,9 +1,24 @@
1
+ import { AnyDesc, DescExtension, DescFile } from "@bufbuild/protobuf";
2
+ import { Printable } from "./generated-file.js";
1
3
  export { reifyWkt } from "./reify-wkt.js";
2
- export { Target } from "./target.js";
3
- export { Schema } from "./schema.js";
4
- export { RuntimeImports } from "./runtime-imports.js";
5
- export { GeneratedFile, FileInfo, Printable } from "./generated-file.js";
6
- export { ImportSymbol } from "./import-symbol.js";
4
+ export type { Target } from "./target.js";
5
+ export type { Schema } from "./schema.js";
6
+ export type { RuntimeImports } from "./runtime-imports.js";
7
+ export type { GeneratedFile, FileInfo, Printable } from "./generated-file.js";
8
+ export type { ImportSymbol } from "./import-symbol.js";
9
+ export { createImportSymbol } from "./import-symbol.js";
7
10
  export declare const localName: (desc: import("@bufbuild/protobuf").DescEnum | import("@bufbuild/protobuf").DescMessage | import("@bufbuild/protobuf").DescService | import("@bufbuild/protobuf").DescEnumValue | import("@bufbuild/protobuf").DescField | import("@bufbuild/protobuf").DescOneof | import("@bufbuild/protobuf").DescMethod) => string;
8
- export { createJsDocBlock, getFieldExplicitDefaultValue, getFieldIntrinsicDefaultValue, getFieldTyping, makeJsDoc, literalString, } from "./gencommon.js";
11
+ export { getFieldExplicitDefaultValue, getFieldIntrinsicDefaultValue, getFieldTyping, } from "./gencommon.js";
9
12
  export { findCustomScalarOption, findCustomMessageOption, findCustomEnumOption, } from "./custom-options.js";
13
+ /**
14
+ * @deprecated Please use GeneratedFile.string() instead
15
+ */
16
+ export declare function literalString(value: string): string;
17
+ /**
18
+ * @deprecated Please use GeneratedFile.jsDoc() instead
19
+ */
20
+ export declare function makeJsDoc(desc: Exclude<AnyDesc, DescFile | DescExtension>, indentation?: string): Printable;
21
+ /**
22
+ * @deprecated Please use GeneratedFile.jsDoc() instead
23
+ */
24
+ export declare function createJsDocBlock(text: string, indentation?: string): Printable;
@@ -11,8 +11,29 @@
11
11
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
- import { codegenInfo } from "@bufbuild/protobuf";
14
+ import { codegenInfo, } from "@bufbuild/protobuf";
15
+ import { createJsDocBlock as createJsDocBlockInternal } from "./jsdoc.js";
16
+ import { literalString as literalStringInternal } from "./gencommon.js";
15
17
  export { reifyWkt } from "./reify-wkt.js";
18
+ export { createImportSymbol } from "./import-symbol.js";
16
19
  export const { localName } = codegenInfo;
17
- export { createJsDocBlock, getFieldExplicitDefaultValue, getFieldIntrinsicDefaultValue, getFieldTyping, makeJsDoc, literalString, } from "./gencommon.js";
20
+ export { getFieldExplicitDefaultValue, getFieldIntrinsicDefaultValue, getFieldTyping, } from "./gencommon.js";
18
21
  export { findCustomScalarOption, findCustomMessageOption, findCustomEnumOption, } from "./custom-options.js";
22
+ /**
23
+ * @deprecated Please use GeneratedFile.string() instead
24
+ */
25
+ export function literalString(value) {
26
+ return literalStringInternal(value);
27
+ }
28
+ /**
29
+ * @deprecated Please use GeneratedFile.jsDoc() instead
30
+ */
31
+ export function makeJsDoc(desc, indentation = "") {
32
+ return createJsDocBlockInternal(desc, indentation).toString();
33
+ }
34
+ /**
35
+ * @deprecated Please use GeneratedFile.jsDoc() instead
36
+ */
37
+ export function createJsDocBlock(text, indentation = "") {
38
+ return createJsDocBlockInternal(text, indentation).toString();
39
+ }