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

handles JavaScript reserved words #19

Closed
wants to merge 1 commit 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
Binary file modified packages/generated-react/dist/descriptorset.bin
Binary file not shown.
17 changes: 17 additions & 0 deletions packages/generated-react/dist/example-TodoService_connectquery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,20 @@ export const addTodo = createQueryService({
typeName: "buf.connect.demo.example.v1.TodoService",
},
}).addTodo;

/**
* @generated from rpc buf.connect.demo.example.v1.TodoService.Delete
*/
export const delete_RPC = createQueryService({
service: {
methods: {
delete: {
name: "Delete",
kind: MethodKind.Unary,
I: Empty,
O: Empty,
},
},
typeName: "buf.connect.demo.example.v1.TodoService",
},
}).delete;
9 changes: 9 additions & 0 deletions packages/generated-react/dist/example_connectweb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ export const TodoService = {
O: Todos,
kind: MethodKind.Unary,
},
/**
* @generated from rpc buf.connect.demo.example.v1.TodoService.Delete
*/
delete: {
name: "Delete",
I: Empty,
O: Empty,
kind: MethodKind.Unary,
},
}
} as const;

1 change: 1 addition & 0 deletions packages/generated-react/example.proto
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ service TodoService {
// A helpful RPC to get all current Todos
rpc GetTodos(Empty) returns (Todos);
rpc AddTodo(Todo) returns (Todos);
rpc Delete(Empty) returns (Empty);
}
5 changes: 3 additions & 2 deletions packages/protoc-gen-connect-query/src/generateDts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import { MethodKind } from '@bufbuild/protobuf';
import type { Schema } from '@bufbuild/protoplugin';
import { localName } from '@bufbuild/protoplugin/ecmascript';

import type { PluginInit } from './utils';
import type { PluginInit} from './utils';
import { sanitizeIdentifiers } from './utils';

/**
* Handles generating a TypeScript Declaration file for a given Schema, DescFile (protobuf definition) and protobuf Service.
Expand All @@ -36,7 +37,7 @@ const generateServiceFile =
{
f.print(
`export const `,
localName(method),
sanitizeIdentifiers(localName(method)),
`: `,
f.import('UnaryHooks', '@bufbuild/connect-query'),
`<`,
Expand Down
6 changes: 3 additions & 3 deletions packages/protoc-gen-connect-query/src/generateTs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import {
makeJsDoc,
} from '@bufbuild/protoplugin/ecmascript';

import type { PluginInit } from './utils';
import type { PluginInit} from './utils';
import { sanitizeIdentifiers } from './utils';

/**
* Handles generating a source code file for a given Schema, DescFile (protobuf definition) and protobuf Service.
Expand All @@ -43,10 +44,9 @@ const generateServiceFile =
service.methods
.filter((method) => method.methodKind === MethodKind.Unary)
.forEach((method, index, filteredMethods) => {
// TODO idempotency
f.print(makeJsDoc(method));
f.print(
`export const ${localName(method)} = `,
`export const ${sanitizeIdentifiers(localName(method))} = `,
f.import('createQueryService', '@bufbuild/connect-query'),
`({`,
);
Expand Down
39 changes: 39 additions & 0 deletions packages/protoc-gen-connect-query/src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright 2021-2022 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { describe, expect, it } from "@jest/globals";

import { isReservedWord, sanitizeIdentifiers } from "./utils";

describe('isReservedWord', () => {
it('returns true for reserved words', () => {
expect(isReservedWord('delete')).toStrictEqual(true)
});

it('returns false for non reserved words', () => {
expect(isReservedWord('deleteRPC')).toStrictEqual(false)
});
});

describe('sanitizeIdentifiers', () => {
it('sanitizes reserved words', () => {
const actual = sanitizeIdentifiers('delete');
expect(actual).toStrictEqual('delete_RPC')
});

it('does nothing to non reserved words', () => {
const actual = sanitizeIdentifiers('deleteRPC');
expect(actual).toStrictEqual('deleteRPC')
});
});
106 changes: 106 additions & 0 deletions packages/protoc-gen-connect-query/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,109 @@ import type { createEcmaScriptPlugin } from '@bufbuild/protoplugin';
* Extracts the type of PluginInit from @bufbuild/protoplugin
*/
export type PluginInit = Required<Parameters<typeof createEcmaScriptPlugin>[0]>;

/**
* a list of reserved words that cannot be used as identifiers.
*/
const reservedWords = [
'abstract',
'as',
'arguments',
'await',
'boolean',
'break',
'byte',
'case',
'catch',
'char',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'double',
'else',
'enum',
'eval',
'export',
'extends',
'false',
'final',
'finally',
'float',
'for',
'function',
'goto',
'if',
'implements',
'import',
'in',
'instanceof',
'int',
'interface',
'let',
'long',
'native',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'short',
'static',
'super',
'switch',
'synchronized',
'this',
'throw',
'throws',
'transient',
'true',
'try',
'typeof',
'var',
'void',
'volatile',
'while',
'with',
'yield',
] as const;

type ReservedWord = (typeof reservedWords)[number];

/**
* Predicate for indicating whether a given identifier is a reserved word in JavaScript
*/
export const isReservedWord = <T extends string>(word: ReservedWord | T): word is ReservedWord => (
reservedWords.includes(word as ReservedWord)
);

/**
* When JavaScript identifiers are formed from the names of Service RPCs, it is possible to hit a situation where the names collide.
*
* For example, `delete` is a reserved word in JavaScript. Therefore the input protofile:
* ```proto
* service MyService {
* rpc Delete(empty) returns (Empty)
* }
* ```
*
* would otherwise be serialized to:
* ```ts
* const delete = ....
* ```
*
* which is a syntax error.
*
* This function fixes that by appending `_RPC` to the end of the identifier.
*/
export const sanitizeIdentifiers = <T extends string>(word: T) => {
if (isReservedWord(word)) {
return `${word}_RPC` as const;
}
return word;
}