Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add strict option to v1 #1043

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/protobuf/src/codegen-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ type RuntimeSymbolName =
| "proto3"
| "Message"
| "PartialMessage"
| "PartialStrictMessage"
| "PlainMessage"
| "FieldList"
| "MessageType"
Expand Down Expand Up @@ -116,6 +117,7 @@ export const codegenInfo: CodegenInfo = {
proto3: {typeOnly: false, privateImportPath: "./proto3.js", publicImportPath: packageName},
Message: {typeOnly: false, privateImportPath: "./message.js", publicImportPath: packageName},
PartialMessage: {typeOnly: true, privateImportPath: "./message.js", publicImportPath: packageName},
PartialStrictMessage: {typeOnly: true, privateImportPath: "./message.js", publicImportPath: packageName},
PlainMessage: {typeOnly: true, privateImportPath: "./message.js", publicImportPath: packageName},
FieldList: {typeOnly: true, privateImportPath: "./field-list.js", publicImportPath: packageName},
MessageType: {typeOnly: true, privateImportPath: "./message-type.js", publicImportPath: packageName},
Expand Down
7 changes: 6 additions & 1 deletion packages/protobuf/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ export { protoDelimited } from "./proto-delimited.js";
export { codegenInfo } from "./codegen-info.js";

export { Message } from "./message.js";
export type { AnyMessage, PartialMessage, PlainMessage } from "./message.js";
export type {
AnyMessage,
PartialMessage,
PartialStrictMessage,
PlainMessage,
} from "./message.js";
export { isMessage } from "./is-message.js";

export type { FieldInfo, OneofInfo } from "./field.js";
Expand Down
16 changes: 16 additions & 0 deletions packages/protobuf/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,22 @@ export type PartialMessage<T extends Message<T>> = {
[P in keyof T as T[P] extends Function ? never : P]?: PartialField<T[P]>;
};

export type PartialStrictMessage<T extends Message<T>> = {
// eslint-disable-next-line @typescript-eslint/ban-types -- we use `Function` to identify methods
[P in keyof T as T[P] extends Function ? never : P]: PartialStrictField<T[P]>;
};

// prettier-ignore
type PartialStrictField<F> =
F extends (Date | Uint8Array | bigint | boolean | string | number) ? F
: F extends Array<infer U> ? Array<PartialField<U>>
: F extends ReadonlyArray<infer U> ? ReadonlyArray<PartialField<U>>
: F extends Message<infer U> ? PartialStrictMessage<U>
: F extends OneofSelectedMessage<infer C, infer V> ? {case: C; value: PartialStrictMessage<V>}
: F extends { case: string | undefined; value?: unknown; } ? F
: F extends {[key: string|number]: Message<infer U>} ? {[key: string|number]: PartialStrictMessage<U>}
: F ;

// prettier-ignore
type PartialField<F> =
F extends (Date | Uint8Array | bigint | boolean | string | number) ? F
Expand Down
13 changes: 7 additions & 6 deletions packages/protoc-gen-es/src/declaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,11 @@ function generateEnum(schema: Schema, f: GeneratedFile, enumeration: DescEnum) {
function generateMessage(schema: Schema, f: GeneratedFile, message: DescMessage) {
const protoN = getNonEditionRuntime(schema, message.file);
const {
PartialMessage,
FieldList,
Message,
PlainMessage,
PartialStrictMessage,
PartialMessage,
BinaryReadOptions,
JsonReadOptions,
JsonValue
Expand All @@ -86,7 +87,7 @@ function generateMessage(schema: Schema, f: GeneratedFile, message: DescMessage)
}
f.print();
}
f.print(" constructor(data?: ", PartialMessage, "<", m, ">);");
f.print(" constructor(data?: ", schema.strict ? PartialStrictMessage : PartialMessage, "<", m, ">);");
f.print();
generateWktMethods(schema, f, message);
f.print(" static readonly runtime: typeof ", protoN, ";");
Expand Down Expand Up @@ -125,7 +126,7 @@ function generateOneof(schema: Schema, f: GeneratedFile, oneof: DescOneof) {
f.print(` } | {`);
}
f.print(f.jsDoc(field, " "));
const { typing } = getFieldTypeInfo(field);
const { typing } = getFieldTypeInfo(field, schema.strict);
f.print(` value: `, typing, `;`);
f.print(` case: "`, localName(field), `";`);
}
Expand All @@ -136,7 +137,7 @@ function generateOneof(schema: Schema, f: GeneratedFile, oneof: DescOneof) {
function generateField(schema: Schema, f: GeneratedFile, field: DescField) {
f.print(f.jsDoc(field, " "));
const e: Printable = [];
const { typing, optional } = getFieldTypeInfo(field);
const { typing, optional } = getFieldTypeInfo(field, schema.strict);
if (!optional) {
e.push(" ", localName(field), ": ", typing, ";");
} else {
Expand All @@ -151,7 +152,7 @@ function generateExtension(
f: GeneratedFile,
ext: DescExtension,
) {
const { typing } = getFieldTypeInfo(ext);
const { typing } = getFieldTypeInfo(ext, schema.strict);
const e = f.import(ext.extendee).toTypeOnly();
f.print(f.jsDoc(ext));
f.print(f.exportDecl("declare const", localName(ext)), ": ", schema.runtime.Extension, "<", e, ", ", typing, ">;");
Expand Down Expand Up @@ -232,7 +233,7 @@ function generateWktStaticMethods(schema: Schema, f: GeneratedFile, message: Des
case "google.protobuf.BoolValue":
case "google.protobuf.StringValue":
case "google.protobuf.BytesValue": {
const {typing} = getFieldTypeInfo(ref.value);
const {typing} = getFieldTypeInfo(ref.value, schema.strict);
f.print(" static readonly fieldWrapper: {")
f.print(" wrapField(value: ", typing, "): ", message, ",")
f.print(" unwrapField(value: ", message, "): ", typing, ",")
Expand Down
11 changes: 6 additions & 5 deletions packages/protoc-gen-es/src/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ function generateMessage(schema: Schema, f: GeneratedFile, message: DescMessage)
const protoN = getNonEditionRuntime(schema, message.file);
const {
PartialMessage,
PartialStrictMessage,
FieldList,
Message,
PlainMessage,
Expand All @@ -94,7 +95,7 @@ function generateMessage(schema: Schema, f: GeneratedFile, message: DescMessage)
}
f.print();
}
f.print(" constructor(data?: ", PartialMessage, "<", message, ">) {");
f.print(" constructor(data?: ", schema.strict ? PartialStrictMessage : PartialMessage, "<", message, ">) {");
f.print(" super();");
f.print(" ", protoN, ".util.initPartial(data, this);");
f.print(" }");
Expand Down Expand Up @@ -148,7 +149,7 @@ function generateOneof(schema: Schema, f: GeneratedFile, oneof: DescOneof) {
f.print(` } | {`);
}
f.print(f.jsDoc(field, " "));
const { typing } = getFieldTypeInfo(field);
const { typing } = getFieldTypeInfo(field, schema.strict);
f.print(` value: `, typing, `;`);
f.print(` case: "`, localName(field), `";`);
}
Expand All @@ -159,7 +160,7 @@ function generateOneof(schema: Schema, f: GeneratedFile, oneof: DescOneof) {
function generateField(schema: Schema, f: GeneratedFile, field: DescField) {
f.print(f.jsDoc(field, " "));
const e: Printable = [];
const { typing, optional, typingInferrableFromZeroValue } = getFieldTypeInfo(field);
const { typing, optional, typingInferrableFromZeroValue } = getFieldTypeInfo(field, schema.strict);
if (optional) {
e.push(" ", localName(field), "?: ", typing, ";");
} else {
Expand All @@ -184,7 +185,7 @@ function generateExtension(
ext: DescExtension,
) {
const protoN = getNonEditionRuntime(schema, ext.file);
const { typing } = getFieldTypeInfo(ext);
const { typing } = getFieldTypeInfo(ext, schema.strict);
f.print(f.jsDoc(ext));
f.print(f.exportDecl("const", ext), " = ", protoN, ".makeExtension<", ext.extendee, ", ", typing, ">(");
f.print(" ", f.string(ext.typeName), ", ");
Expand Down Expand Up @@ -651,7 +652,7 @@ function generateWktStaticMethods(schema: Schema, f: GeneratedFile, message: Des
case "google.protobuf.BoolValue":
case "google.protobuf.StringValue":
case "google.protobuf.BytesValue": {
const {typing} = getFieldTypeInfo(ref.value);
const {typing} = getFieldTypeInfo(ref.value, schema.strict);
f.print(" static readonly fieldWrapper = {")
f.print(" wrapField(value: ", typing, "): ", message, " {")
f.print(" return new ", message, "({value});")
Expand Down
9 changes: 6 additions & 3 deletions packages/protoc-gen-es/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import {
import type { Printable } from "@bufbuild/protoplugin/ecmascript";
import { localName } from "@bufbuild/protoplugin/ecmascript";

export function getFieldTypeInfo(field: DescField | DescExtension): {
export function getFieldTypeInfo(
field: DescField | DescExtension,
strict: boolean,
): {
typing: Printable;
optional: boolean;
typingInferrableFromZeroValue: boolean;
Expand All @@ -38,7 +41,7 @@ export function getFieldTypeInfo(field: DescField | DescExtension): {
typing.push(scalarTypeScriptType(field.scalar, field.longType));
optional =
field.optional ||
field.proto.label === FieldDescriptorProto_Label.REQUIRED;
(!strict && field.proto.label === FieldDescriptorProto_Label.REQUIRED);
typingInferrableFromZeroValue = true;
break;
case "message": {
Expand All @@ -64,7 +67,7 @@ export function getFieldTypeInfo(field: DescField | DescExtension): {
});
optional =
field.optional ||
field.proto.label === FieldDescriptorProto_Label.REQUIRED;
(!strict && field.proto.label === FieldDescriptorProto_Label.REQUIRED);
typingInferrableFromZeroValue = true;
break;
case "map": {
Expand Down
18 changes: 18 additions & 0 deletions packages/protoplugin/src/ecmascript/parameter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface ParsedParameter {
importExtension: string;
jsImportStyle: "module" | "legacy_commonjs";
sanitizedParameter: string;
strict: boolean;
}

export function parseParameter(
Expand All @@ -38,6 +39,7 @@ export function parseParameter(
const rewriteImports: RewriteImports = [];
let importExtension = ".js";
let jsImportStyle: "module" | "legacy_commonjs" = "module";
let strict = false;
const rawParameters: string[] = [];
for (const { key, value, raw } of splitParameter(parameter)) {
// Whether this key/value plugin parameter pair should be
Expand Down Expand Up @@ -135,6 +137,21 @@ export function parseParameter(
}
break;
}
case "strict": {
switch (value) {
case "true":
case "1":
strict = true;
break;
case "false":
case "0":
strict = false;
break;
default:
throw new PluginOptionError(raw);
}
break;
}
default:
if (parseExtraOption === undefined) {
throw new PluginOptionError(raw);
Expand All @@ -154,6 +171,7 @@ export function parseParameter(
const sanitizedParameter = rawParameters.join(",");

return {
strict,
targets,
tsNocheck,
bootstrapWkt,
Expand Down
2 changes: 2 additions & 0 deletions packages/protoplugin/src/ecmascript/runtime-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface RuntimeImports {
proto3: ImportSymbol;
Message: ImportSymbol;
PartialMessage: ImportSymbol;
PartialStrictMessage: ImportSymbol;
PlainMessage: ImportSymbol;
FieldList: ImportSymbol;
MessageType: ImportSymbol;
Expand All @@ -47,6 +48,7 @@ export function createRuntimeImports(bootstrapWkt: boolean): RuntimeImports {
proto3: infoToSymbol("proto3", bootstrapWkt),
Message: infoToSymbol("Message", bootstrapWkt),
PartialMessage: infoToSymbol("PartialMessage", bootstrapWkt),
PartialStrictMessage: infoToSymbol("PartialStrictMessage", bootstrapWkt),
PlainMessage: infoToSymbol("PlainMessage", bootstrapWkt),
FieldList: infoToSymbol("FieldList", bootstrapWkt),
MessageType: infoToSymbol("MessageType", bootstrapWkt),
Expand Down
6 changes: 6 additions & 0 deletions packages/protoplugin/src/ecmascript/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ export interface Schema {
* The original google.protobuf.compiler.CodeGeneratorRequest.
*/
readonly proto: CodeGeneratorRequest;

/**
* strict mode with `required` support
*/
readonly strict: boolean;
}

interface SchemaController extends Schema {
Expand Down Expand Up @@ -120,6 +125,7 @@ export function createSchema(
const generatedFiles: GeneratedFileController[] = [];
return {
targets: parameter.targets,
strict: parameter.strict,
runtime,
proto: request,
files: filesToGenerate,
Expand Down