Skip to content

Commit

Permalink
fix(Schema generation): ensure Buffer api is only used when in nodejs…
Browse files Browse the repository at this point in the history
… environment
  • Loading branch information
zak-cloudnc committed Nov 10, 2024
1 parent 38b114c commit f0b35cd
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
17 changes: 15 additions & 2 deletions integration/options/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,7 @@ export const protoMetadata: ProtoMetadata = {
options: { "my_message_option": 1234 },
fields: {
"foo": { "my_field_option": 4.5 },
"foo_2": { "something": Something.decode(Buffer.from("CgV3b3JsZBIDe9kC", "base64")) },
"foo_2": { "something": Something.decode(bytesFromBase64("CgV3b3JsZBIDe9kC")) },
},
oneof: { "qux": { "my_oneof_option": 42 } },
},
Expand All @@ -482,7 +482,7 @@ export const protoMetadata: ProtoMetadata = {
options: { "my_service_option": 0 },
methods: {
"MyMethod": {
"my_method_option": MyMessage.decode(Buffer.from("CJYBEJYBGgtTb21lIHN0cmluZyILU29tZSBzdHJpbmc=", "base64")),
"my_method_option": MyMessage.decode(bytesFromBase64("CJYBEJYBGgtTb21lIHN0cmluZyILU29tZSBzdHJpbmc=")),
},
},
},
Expand All @@ -491,6 +491,19 @@ export const protoMetadata: ProtoMetadata = {
},
};

function bytesFromBase64(b64: string): Uint8Array {
if ((globalThis as any).Buffer) {
return Uint8Array.from(globalThis.Buffer.from(b64, "base64"));
} else {
const bin = globalThis.atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
}

export interface MessageFns<T> {
encode(message: T, writer?: BinaryWriter): BinaryWriter;
decode(input: BinaryReader | Uint8Array, length?: number): T;
Expand Down
8 changes: 6 additions & 2 deletions src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import SourceInfo from "./sourceInfo";
import { impFile, maybePrefixPackage } from "./utils";
import { basicTypeName, toReaderCall } from "./types";
import { BinaryReader } from "@bufbuild/protobuf/wire";
import { OutputSchemaOption } from "./options";
import { EnvOption, OutputSchemaOption } from "./options";

const fileDescriptorProto = imp("FileDescriptorProto@ts-proto-descriptors");

Expand Down Expand Up @@ -216,7 +216,11 @@ function getExtensionValue(ctx: Context, extension: FieldDescriptorProto, data:
}),
);
const result = resultBuffer.toString("base64");
return code`'${extension.name}': ${typeName}.decode(Buffer.from('${result}', 'base64'))`;
const encoded =
ctx.options.env === EnvOption.NODE
? code`Buffer.from('${result}', 'base64')`
: code`${ctx.utils.bytesFromBase64}("${result}")`;
return code`'${extension.name}': ${typeName}.decode(${encoded})`;
} else {
const reader = new BinaryReader(data[0]);
let value = (reader as any)[toReaderCall(extension)]();
Expand Down

0 comments on commit f0b35cd

Please sign in to comment.