cel-proto-parser 0.2.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.
package/parser.js ADDED
@@ -0,0 +1,251 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.CelProtoParser = void 0;
40
+ const protobufjs_1 = require("@launchql/protobufjs");
41
+ const fs_1 = require("fs");
42
+ const path_1 = require("path");
43
+ const t = __importStar(require("@babel/types"));
44
+ const generator_1 = __importDefault(require("@babel/generator"));
45
+ const options_1 = require("./options");
46
+ const ast_1 = require("./ast");
47
+ const enums_1 = require("./ast/enums");
48
+ const utils_1 = require("./utils");
49
+ const deparser_1 = require("./deparser");
50
+ const GENERATED_HEADER = `/**
51
+ * This file was automatically generated by cel-proto-parser.
52
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source proto file,
53
+ * and run the cel-proto-parser generate command to regenerate this file.
54
+ */`;
55
+ function isProtoType(obj) {
56
+ return 'fields' in obj;
57
+ }
58
+ function isProtoEnum(obj) {
59
+ return 'values' in obj && !('fields' in obj);
60
+ }
61
+ class CelProtoParser {
62
+ protoPath;
63
+ options;
64
+ root = null;
65
+ types = [];
66
+ enums = [];
67
+ constructor(protoPath, options) {
68
+ this.protoPath = protoPath;
69
+ this.options = (0, options_1.getOptionsWithDefaults)(options);
70
+ }
71
+ /**
72
+ * Parse the proto file and extract types and enums
73
+ */
74
+ parse() {
75
+ const protoContent = (0, fs_1.readFileSync)(this.protoPath, 'utf-8');
76
+ this.root = (0, protobufjs_1.parse)(protoContent, {
77
+ keepCase: this.options.parser.keepCase
78
+ }).root;
79
+ this.extractTypesAndEnums(this.root);
80
+ }
81
+ /**
82
+ * Extract types and enums from the parsed proto root
83
+ */
84
+ extractTypesAndEnums(root) {
85
+ const exclude = new Set(this.options.exclude);
86
+ // Helper to recursively extract from nested structures
87
+ const extract = (obj, prefix = '') => {
88
+ for (const [key, value] of Object.entries(obj)) {
89
+ if (!value || typeof value !== 'object')
90
+ continue;
91
+ const fullName = prefix ? `${prefix}.${key}` : key;
92
+ // Skip excluded types
93
+ if (exclude.has(key) || exclude.has(fullName))
94
+ continue;
95
+ const item = value;
96
+ if (isProtoType(item)) {
97
+ // It's a message type
98
+ this.types.push({
99
+ name: key,
100
+ fields: this.normalizeFields(item.fields),
101
+ nested: item.nested
102
+ });
103
+ // Extract nested types
104
+ if (item.nested) {
105
+ extract(item.nested, fullName);
106
+ }
107
+ }
108
+ else if (isProtoEnum(item)) {
109
+ // It's an enum
110
+ this.enums.push({
111
+ name: key,
112
+ values: item.values
113
+ });
114
+ }
115
+ }
116
+ };
117
+ // Start extraction from root.nested
118
+ if (root.nested) {
119
+ extract(root.nested);
120
+ }
121
+ }
122
+ /**
123
+ * Normalize fields to ensure consistent structure
124
+ */
125
+ normalizeFields(fields) {
126
+ if (!fields)
127
+ return {};
128
+ const normalized = {};
129
+ for (const [key, field] of Object.entries(fields)) {
130
+ normalized[key] = {
131
+ name: field.name || key,
132
+ type: field.type,
133
+ rule: field.rule
134
+ };
135
+ }
136
+ return normalized;
137
+ }
138
+ /**
139
+ * Generate all output files
140
+ */
141
+ write() {
142
+ if (!this.root) {
143
+ this.parse();
144
+ }
145
+ const { outDir } = this.options;
146
+ (0, fs_1.mkdirSync)(outDir, { recursive: true });
147
+ if (this.options.enums.enabled) {
148
+ this.writeEnums();
149
+ }
150
+ if (this.options.types.enabled) {
151
+ this.writeTypes();
152
+ }
153
+ if (this.options.utils.astHelpers.enabled) {
154
+ this.writeAstHelpers();
155
+ }
156
+ if (this.options.deparser.enabled) {
157
+ this.writeDeparser();
158
+ }
159
+ }
160
+ /**
161
+ * Write enum definitions to file
162
+ */
163
+ writeEnums() {
164
+ const { outDir, enums: enumOptions } = this.options;
165
+ const filePath = (0, path_1.join)(outDir, enumOptions.filename);
166
+ const statements = [];
167
+ for (const enumNode of this.enums) {
168
+ if (enumOptions.enumsAsTypeUnion) {
169
+ statements.push((0, enums_1.convertEnumToTsUnionType)(enumNode));
170
+ }
171
+ else {
172
+ statements.push((0, enums_1.convertEnumToTsEnumDeclaration)(enumNode));
173
+ }
174
+ }
175
+ const code = this.generateCode(statements);
176
+ (0, fs_1.writeFileSync)(filePath, code, 'utf-8');
177
+ }
178
+ /**
179
+ * Write type definitions to file
180
+ */
181
+ writeTypes() {
182
+ const { outDir, types: typeOptions, enums: enumOptions } = this.options;
183
+ const filePath = (0, path_1.join)(outDir, typeOptions.filename);
184
+ const statements = [];
185
+ // Add enum imports if there are enums
186
+ if (this.enums.length > 0 && enumOptions.enabled) {
187
+ const enumImport = (0, ast_1.generateEnumImports)(this.enums, typeOptions.enumsSource);
188
+ statements.push(enumImport);
189
+ }
190
+ // Generate Node union type
191
+ if (this.types.length > 0) {
192
+ statements.push((0, ast_1.generateNodeUnionType)(this.types));
193
+ }
194
+ // Generate interfaces for each type
195
+ for (const type of this.types) {
196
+ statements.push((0, ast_1.convertTypeToTsInterface)(type, this.options));
197
+ }
198
+ const code = this.generateCode(statements);
199
+ (0, fs_1.writeFileSync)(filePath, code, 'utf-8');
200
+ }
201
+ /**
202
+ * Write AST helper functions to file
203
+ */
204
+ writeAstHelpers() {
205
+ const { outDir, utils } = this.options;
206
+ const filePath = (0, path_1.join)(outDir, utils.astHelpers.filename);
207
+ const statements = [];
208
+ // Add nested-obj import
209
+ statements.push((0, utils_1.createDefaultImport)('_o', 'nested-obj'));
210
+ // Add type imports
211
+ if (this.types.length > 0) {
212
+ statements.push((0, ast_1.generateTypeImportSpecifiers)(this.types, this.options));
213
+ }
214
+ // Generate helper methods
215
+ if (this.types.length > 0) {
216
+ statements.push((0, ast_1.generateAstHelperMethods)(this.types));
217
+ }
218
+ const code = this.generateCode(statements);
219
+ (0, fs_1.writeFileSync)(filePath, code, 'utf-8');
220
+ }
221
+ /**
222
+ * Write deparser module to file
223
+ */
224
+ writeDeparser() {
225
+ const { outDir, deparser: deparserOptions } = this.options;
226
+ const filePath = (0, path_1.join)(outDir, deparserOptions.filename);
227
+ const code = (0, deparser_1.generateDeparserCode)();
228
+ (0, fs_1.writeFileSync)(filePath, code, 'utf-8');
229
+ }
230
+ /**
231
+ * Generate TypeScript code from AST statements
232
+ */
233
+ generateCode(statements) {
234
+ const program = t.program(statements);
235
+ const { code } = (0, generator_1.default)(program, { comments: true });
236
+ return `${GENERATED_HEADER}\n${code}\n`;
237
+ }
238
+ /**
239
+ * Get the parsed types
240
+ */
241
+ getTypes() {
242
+ return this.types;
243
+ }
244
+ /**
245
+ * Get the parsed enums
246
+ */
247
+ getEnums() {
248
+ return this.enums;
249
+ }
250
+ }
251
+ exports.CelProtoParser = CelProtoParser;
@@ -0,0 +1,46 @@
1
+ import * as t from '@babel/types';
2
+ import { ResolvedCelProtoParserOptions } from '../options';
3
+ /**
4
+ * Convert a string to camelCase
5
+ */
6
+ export declare function toCamelCase(str: string): string;
7
+ /**
8
+ * Convert a string to PascalCase
9
+ */
10
+ export declare function toPascalCase(str: string): string;
11
+ /**
12
+ * Get the field name, handling protobuf naming conventions
13
+ */
14
+ export declare function getFieldName(field: {
15
+ name: string;
16
+ }, fallback: string): string;
17
+ /**
18
+ * Convert Babel AST nodes to TypeScript code string
19
+ */
20
+ export declare function convertAstToCode(nodes: t.Statement | t.Statement[]): string;
21
+ /**
22
+ * Create a named import statement
23
+ */
24
+ export declare function createNamedImport(names: string[], source: string): t.ImportDeclaration;
25
+ /**
26
+ * Create a default import statement
27
+ */
28
+ export declare function createDefaultImport(name: string, source: string): t.ImportDeclaration;
29
+ /**
30
+ * Write content to a file, creating directories as needed
31
+ */
32
+ export declare function writeFileToDisk(filePath: string, content: string, _options: ResolvedCelProtoParserOptions): void;
33
+ /**
34
+ * Clone a protobuf node and add a name property
35
+ */
36
+ export declare function cloneAndNameNode<T extends object>(node: T, name: string): T & {
37
+ name: string;
38
+ };
39
+ /**
40
+ * Strip file extension from a path
41
+ */
42
+ export declare function stripExtension(filename: string): string;
43
+ /**
44
+ * Ensure a filename has the correct extension
45
+ */
46
+ export declare function ensureExtension(filename: string, ext: string): string;
package/utils/index.js ADDED
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.toCamelCase = toCamelCase;
40
+ exports.toPascalCase = toPascalCase;
41
+ exports.getFieldName = getFieldName;
42
+ exports.convertAstToCode = convertAstToCode;
43
+ exports.createNamedImport = createNamedImport;
44
+ exports.createDefaultImport = createDefaultImport;
45
+ exports.writeFileToDisk = writeFileToDisk;
46
+ exports.cloneAndNameNode = cloneAndNameNode;
47
+ exports.stripExtension = stripExtension;
48
+ exports.ensureExtension = ensureExtension;
49
+ const t = __importStar(require("@babel/types"));
50
+ const generator_1 = __importDefault(require("@babel/generator"));
51
+ const fs_1 = require("fs");
52
+ const path_1 = require("path");
53
+ /**
54
+ * Convert a string to camelCase
55
+ */
56
+ function toCamelCase(str) {
57
+ return str.charAt(0).toLowerCase() + str.slice(1);
58
+ }
59
+ /**
60
+ * Convert a string to PascalCase
61
+ */
62
+ function toPascalCase(str) {
63
+ return str.charAt(0).toUpperCase() + str.slice(1);
64
+ }
65
+ /**
66
+ * Get the field name, handling protobuf naming conventions
67
+ */
68
+ function getFieldName(field, fallback) {
69
+ return field.name || fallback;
70
+ }
71
+ /**
72
+ * Convert Babel AST nodes to TypeScript code string
73
+ */
74
+ function convertAstToCode(nodes) {
75
+ const program = t.program(Array.isArray(nodes) ? nodes : [nodes]);
76
+ const { code } = (0, generator_1.default)(program, {
77
+ comments: true
78
+ });
79
+ return code;
80
+ }
81
+ /**
82
+ * Create a named import statement
83
+ */
84
+ function createNamedImport(names, source) {
85
+ const specifiers = names.map((name) => t.importSpecifier(t.identifier(name), t.identifier(name)));
86
+ return t.importDeclaration(specifiers, t.stringLiteral(source));
87
+ }
88
+ /**
89
+ * Create a default import statement
90
+ */
91
+ function createDefaultImport(name, source) {
92
+ return t.importDeclaration([t.importDefaultSpecifier(t.identifier(name))], t.stringLiteral(source));
93
+ }
94
+ /**
95
+ * Write content to a file, creating directories as needed
96
+ */
97
+ function writeFileToDisk(filePath, content, _options) {
98
+ const dir = (0, path_1.dirname)(filePath);
99
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
100
+ (0, fs_1.writeFileSync)(filePath, content, 'utf-8');
101
+ }
102
+ /**
103
+ * Clone a protobuf node and add a name property
104
+ */
105
+ function cloneAndNameNode(node, name) {
106
+ return { ...node, name };
107
+ }
108
+ /**
109
+ * Strip file extension from a path
110
+ */
111
+ function stripExtension(filename) {
112
+ return filename.replace(/\.[^/.]+$/, '');
113
+ }
114
+ /**
115
+ * Ensure a filename has the correct extension
116
+ */
117
+ function ensureExtension(filename, ext) {
118
+ if (!ext.startsWith('.')) {
119
+ ext = '.' + ext;
120
+ }
121
+ if (filename.endsWith(ext)) {
122
+ return filename;
123
+ }
124
+ // Remove any existing extension and add the new one
125
+ const base = stripExtension(filename);
126
+ return base + ext;
127
+ }