protobuf.js icon indicating copy to clipboard operation
protobuf.js copied to clipboard

illegal token 'import' when imports follow messages

Open seshness opened this issue 6 months ago • 0 comments

I have a proto file with this structure:

syntax = "proto3";

package sample;

message Foo {
  string name = 1;
}

import "imports.proto";

[email protected] (latest at the time of filing this issue) fails to parse this file because the import comes after a message:

Error: illegal token 'import' (sample.proto, line 9)
    at illegal (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs/src/parse.js:107:16)
    at parse (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs/src/parse.js:909:27)
    at process (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs/src/root.js:136:30)
    at fetch (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs/src/root.js:190:13)
    at Root.load (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs/src/root.js:220:13)
    at Root.loadSync (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs/src/root.js:264:17)
    at Object.main (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs-cli/pbjs.js:247:18)
    at Object.<anonymous> (/Users/sesh/HouseOfCode/test-proto-import/node_modules/protobufjs-cli/bin/pbjs:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1226:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)

Node.js v18.14.0

Although the proto3 language guide says

To import another .proto’s definitions, you add an import statement to the top of your file

the language specification allows for interleaved imports and messages:

proto = [syntax] { import | package | option | topLevelDef | emptyStatement }
topLevelDef = message | enum | service

The current behaviour is at odds with protoc (at version libprotoc 29.3) which does support this syntax.

seshness avatar May 12 '25 22:05 seshness