bash-ast 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # bash-ast
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/Safegres/brand/refs/heads/main/safegres.svg" />
5
+ </p>
6
+
7
+ Bash/shell command parser and deparser for JavaScript/TypeScript.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install bash-ast
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Parsing
18
+
19
+ ```typescript
20
+ import { parse } from 'bash-ast';
21
+
22
+ const source = 'echo hello | grep h && ls -la';
23
+ const ast = parse(source);
24
+ console.log(JSON.stringify(ast, null, 2));
25
+ ```
26
+
27
+ ### Deparsing
28
+
29
+ ```typescript
30
+ import { parse, deparse } from 'bash-ast';
31
+
32
+ const source = 'echo hello';
33
+ const ast = parse(source);
34
+ const output = deparse(ast);
35
+ console.log(output); // echo hello
36
+ ```
37
+
38
+ ### AST Comparison
39
+
40
+ ```typescript
41
+ import { parse, cleanTree } from 'bash-ast';
42
+
43
+ const ast1 = parse('echo hello');
44
+ const ast2 = parse('echo hello');
45
+
46
+ const clean1 = cleanTree(ast1);
47
+ const clean2 = cleanTree(ast2);
48
+
49
+ // Compare ASTs without position information
50
+ console.log(JSON.stringify(clean1) === JSON.stringify(clean2)); // true
51
+ ```
52
+
53
+ ## Supported Constructs
54
+
55
+ ### Commands
56
+ - Simple commands with arguments
57
+ - Pipelines (`cmd1 | cmd2`)
58
+ - Logical operators (`&&`, `||`)
59
+ - Subshells (`(cmd)`)
60
+ - Brace groups (`{ cmd; }`)
61
+
62
+ ### Control Flow
63
+ - if/then/else/elif/fi
64
+ - while/do/done
65
+ - until/do/done
66
+ - for/in/do/done
67
+ - case/esac
68
+
69
+ ### Redirections
70
+ - Input (`<`)
71
+ - Output (`>`, `>>`)
72
+ - Here strings (`<<<`)
73
+ - File descriptor redirects (`2>&1`)
74
+
75
+ ### Other
76
+ - Variable assignments (`VAR=value`)
77
+ - Function definitions
78
+ - Quoted strings (single and double)
79
+ - Variable expansion (`$VAR`, `${VAR}`)
80
+ - Command substitution (`$(cmd)`, `` `cmd` ``)
81
+ - Arithmetic expansion (`$((expr))`)
82
+
83
+ ## License
84
+
85
+ MIT
86
+
87
+ ---
88
+
89
+ ## Development
90
+
91
+ ### Setup
92
+
93
+ 1. Clone the repository:
94
+
95
+ ```bash
96
+ git clone https://github.com/constructive-io/dev-utils.git
97
+ ```
98
+
99
+ 2. Install dependencies:
100
+
101
+ ```bash
102
+ cd dev-utils
103
+ pnpm install
104
+ pnpm build
105
+ ```
106
+
107
+ 3. Test the package of interest:
108
+
109
+ ```bash
110
+ cd packages/<packagename>
111
+ pnpm test:watch
112
+ ```
113
+
114
+ ## Credits
115
+
116
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
117
+
118
+ ## Disclaimer
119
+
120
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
121
+
122
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/clean.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { Node, Script } from './types';
2
+ /**
3
+ * No-op transform function - removes the property
4
+ */
5
+ export declare const noop: () => undefined;
6
+ /**
7
+ * Clean AST tree by removing location/position information
8
+ * This is used for comparing ASTs in round-trip testing
9
+ */
10
+ export declare function cleanTree<T extends Node | Script>(tree: T): T;
11
+ /**
12
+ * Compare two ASTs for equality after cleaning
13
+ */
14
+ export declare function compareAst(ast1: any, ast2: any): boolean;
package/clean.js ADDED
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.noop = void 0;
4
+ exports.cleanTree = cleanTree;
5
+ exports.compareAst = compareAst;
6
+ /**
7
+ * No-op transform function - removes the property
8
+ */
9
+ const noop = () => undefined;
10
+ exports.noop = noop;
11
+ /**
12
+ * Deep transform an object
13
+ */
14
+ function transform(obj, options) {
15
+ if (obj === null || obj === undefined) {
16
+ return obj;
17
+ }
18
+ if (Array.isArray(obj)) {
19
+ return obj.map(item => transform(item, options));
20
+ }
21
+ if (typeof obj === 'object') {
22
+ const result = {};
23
+ for (const key of Object.keys(obj)) {
24
+ const value = obj[key];
25
+ // Check if there's a transform function for this key
26
+ if (key in options) {
27
+ const transformed = options[key](value, key, obj);
28
+ if (transformed !== undefined) {
29
+ result[key] = transformed;
30
+ }
31
+ // If undefined, skip the property (remove it)
32
+ }
33
+ else {
34
+ // Recursively transform nested objects
35
+ result[key] = transform(value, options);
36
+ }
37
+ }
38
+ return result;
39
+ }
40
+ return obj;
41
+ }
42
+ /**
43
+ * Clean AST tree by removing location/position information
44
+ * This is used for comparing ASTs in round-trip testing
45
+ */
46
+ function cleanTree(tree) {
47
+ return transform(tree, {
48
+ // Remove range/position information
49
+ range: exports.noop,
50
+ // Normalize text strings (trim whitespace)
51
+ text: (value) => {
52
+ if (typeof value === 'string') {
53
+ return value.trim();
54
+ }
55
+ return value;
56
+ }
57
+ });
58
+ }
59
+ /**
60
+ * Compare two ASTs for equality after cleaning
61
+ */
62
+ function compareAst(ast1, ast2) {
63
+ const clean1 = cleanTree(ast1);
64
+ const clean2 = cleanTree(ast2);
65
+ return JSON.stringify(clean1) === JSON.stringify(clean2);
66
+ }
package/deparser.d.ts ADDED
@@ -0,0 +1,100 @@
1
+ import { Node, Script } from './types';
2
+ /**
3
+ * Deparser options
4
+ */
5
+ export interface DeparserOptions {
6
+ newline?: string;
7
+ indent?: string;
8
+ }
9
+ /**
10
+ * Bash Deparser - converts AST back to source
11
+ */
12
+ export declare class Deparser {
13
+ private options;
14
+ private indentLevel;
15
+ constructor(options?: DeparserOptions);
16
+ /**
17
+ * Deparse AST to source string
18
+ */
19
+ deparse(node: Script | Node): string;
20
+ /**
21
+ * Get current indentation
22
+ */
23
+ private getIndent;
24
+ /**
25
+ * Deparse script
26
+ */
27
+ private deparseScript;
28
+ /**
29
+ * Deparse any command
30
+ */
31
+ private deparseCommand;
32
+ /**
33
+ * Deparse simple command
34
+ */
35
+ private deparseSimpleCommand;
36
+ /**
37
+ * Deparse word
38
+ */
39
+ private deparseWord;
40
+ /**
41
+ * Deparse redirect
42
+ */
43
+ private deparseRedirect;
44
+ /**
45
+ * Deparse pipeline
46
+ */
47
+ private deparsePipeline;
48
+ /**
49
+ * Deparse logical expression
50
+ */
51
+ private deparseLogicalExpression;
52
+ /**
53
+ * Deparse subshell
54
+ */
55
+ private deparseSubshell;
56
+ /**
57
+ * Deparse compound list
58
+ */
59
+ private deparseCompoundList;
60
+ /**
61
+ * Deparse compound list inline (for subshells, etc.)
62
+ */
63
+ private deparseCompoundListInline;
64
+ /**
65
+ * Deparse if clause
66
+ */
67
+ private deparseIf;
68
+ /**
69
+ * Deparse while clause
70
+ */
71
+ private deparseWhile;
72
+ /**
73
+ * Deparse until clause
74
+ */
75
+ private deparseUntil;
76
+ /**
77
+ * Deparse for clause
78
+ */
79
+ private deparseFor;
80
+ /**
81
+ * Deparse case clause
82
+ */
83
+ private deparseCase;
84
+ /**
85
+ * Deparse case item
86
+ */
87
+ private deparseCaseItem;
88
+ /**
89
+ * Deparse function definition
90
+ */
91
+ private deparseFunction;
92
+ }
93
+ /**
94
+ * Deparse AST to source string
95
+ */
96
+ export declare function deparse(node: Script | Node, options?: DeparserOptions): string;
97
+ /**
98
+ * Synchronous deparse (same as deparse, for API consistency)
99
+ */
100
+ export declare const deparseSync: typeof deparse;
package/deparser.js ADDED
@@ -0,0 +1,299 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deparseSync = exports.Deparser = void 0;
4
+ exports.deparse = deparse;
5
+ /**
6
+ * Bash Deparser - converts AST back to source
7
+ */
8
+ class Deparser {
9
+ options;
10
+ indentLevel = 0;
11
+ constructor(options = {}) {
12
+ this.options = {
13
+ newline: '\n',
14
+ indent: ' ',
15
+ ...options
16
+ };
17
+ }
18
+ /**
19
+ * Deparse AST to source string
20
+ */
21
+ deparse(node) {
22
+ if ('type' in node) {
23
+ switch (node.type) {
24
+ case 'Script':
25
+ return this.deparseScript(node);
26
+ case 'SimpleCommand':
27
+ return this.deparseSimpleCommand(node);
28
+ case 'Pipeline':
29
+ return this.deparsePipeline(node);
30
+ case 'LogicalExpression':
31
+ return this.deparseLogicalExpression(node);
32
+ case 'Subshell':
33
+ return this.deparseSubshell(node);
34
+ case 'CompoundList':
35
+ return this.deparseCompoundList(node);
36
+ case 'IfClause':
37
+ return this.deparseIf(node);
38
+ case 'WhileClause':
39
+ return this.deparseWhile(node);
40
+ case 'UntilClause':
41
+ return this.deparseUntil(node);
42
+ case 'ForClause':
43
+ return this.deparseFor(node);
44
+ case 'CaseClause':
45
+ return this.deparseCase(node);
46
+ case 'FunctionDefinition':
47
+ return this.deparseFunction(node);
48
+ case 'Word':
49
+ return this.deparseWord(node);
50
+ case 'AssignmentWord':
51
+ return node.text;
52
+ case 'Redirect':
53
+ return this.deparseRedirect(node);
54
+ default:
55
+ throw new Error(`Unknown node type: ${node.type}`);
56
+ }
57
+ }
58
+ throw new Error('Invalid node');
59
+ }
60
+ /**
61
+ * Get current indentation
62
+ */
63
+ getIndent() {
64
+ return this.options.indent.repeat(this.indentLevel);
65
+ }
66
+ /**
67
+ * Deparse script
68
+ */
69
+ deparseScript(script) {
70
+ return script.commands
71
+ .map(cmd => this.deparseCommand(cmd))
72
+ .join(this.options.newline);
73
+ }
74
+ /**
75
+ * Deparse any command
76
+ */
77
+ deparseCommand(command) {
78
+ switch (command.type) {
79
+ case 'SimpleCommand':
80
+ return this.deparseSimpleCommand(command);
81
+ case 'Pipeline':
82
+ return this.deparsePipeline(command);
83
+ case 'LogicalExpression':
84
+ return this.deparseLogicalExpression(command);
85
+ case 'Subshell':
86
+ return this.deparseSubshell(command);
87
+ case 'CompoundList':
88
+ return this.deparseCompoundList(command);
89
+ case 'IfClause':
90
+ return this.deparseIf(command);
91
+ case 'WhileClause':
92
+ return this.deparseWhile(command);
93
+ case 'UntilClause':
94
+ return this.deparseUntil(command);
95
+ case 'ForClause':
96
+ return this.deparseFor(command);
97
+ case 'CaseClause':
98
+ return this.deparseCase(command);
99
+ case 'FunctionDefinition':
100
+ return this.deparseFunction(command);
101
+ default:
102
+ throw new Error(`Unknown command type: ${command.type}`);
103
+ }
104
+ }
105
+ /**
106
+ * Deparse simple command
107
+ */
108
+ deparseSimpleCommand(cmd) {
109
+ const parts = [];
110
+ // Prefix (assignments)
111
+ if (cmd.prefix) {
112
+ for (const assignment of cmd.prefix) {
113
+ parts.push(assignment.text);
114
+ }
115
+ }
116
+ // Command name
117
+ if (cmd.name) {
118
+ parts.push(this.deparseWord(cmd.name));
119
+ }
120
+ // Suffix (arguments and redirections)
121
+ if (cmd.suffix) {
122
+ for (const item of cmd.suffix) {
123
+ if (item.type === 'Word') {
124
+ parts.push(this.deparseWord(item));
125
+ }
126
+ else if (item.type === 'Redirect') {
127
+ parts.push(this.deparseRedirect(item));
128
+ }
129
+ }
130
+ }
131
+ return parts.join(' ');
132
+ }
133
+ /**
134
+ * Deparse word
135
+ */
136
+ deparseWord(word) {
137
+ return word.text;
138
+ }
139
+ /**
140
+ * Deparse redirect
141
+ */
142
+ deparseRedirect(redirect) {
143
+ let result = '';
144
+ if (redirect.numberIo !== undefined) {
145
+ result += redirect.numberIo;
146
+ }
147
+ result += redirect.op;
148
+ if (redirect.file) {
149
+ result += this.deparseWord(redirect.file);
150
+ }
151
+ return result;
152
+ }
153
+ /**
154
+ * Deparse pipeline
155
+ */
156
+ deparsePipeline(pipeline) {
157
+ const parts = [];
158
+ if (pipeline.bang) {
159
+ parts.push('!');
160
+ }
161
+ parts.push(pipeline.commands
162
+ .map(cmd => this.deparseCommand(cmd))
163
+ .join(' | '));
164
+ return parts.join(' ');
165
+ }
166
+ /**
167
+ * Deparse logical expression
168
+ */
169
+ deparseLogicalExpression(expr) {
170
+ const left = this.deparseCommand(expr.left);
171
+ const right = this.deparseCommand(expr.right);
172
+ return `${left} ${expr.op} ${right}`;
173
+ }
174
+ /**
175
+ * Deparse subshell
176
+ */
177
+ deparseSubshell(subshell) {
178
+ const list = this.deparseCompoundListInline(subshell.list);
179
+ return `(${list})`;
180
+ }
181
+ /**
182
+ * Deparse compound list
183
+ */
184
+ deparseCompoundList(list) {
185
+ return list.commands
186
+ .map(cmd => this.deparseCommand(cmd))
187
+ .join('; ');
188
+ }
189
+ /**
190
+ * Deparse compound list inline (for subshells, etc.)
191
+ */
192
+ deparseCompoundListInline(list) {
193
+ return list.commands
194
+ .map(cmd => this.deparseCommand(cmd))
195
+ .join('; ');
196
+ }
197
+ /**
198
+ * Deparse if clause
199
+ */
200
+ deparseIf(ifClause) {
201
+ const parts = [];
202
+ parts.push('if');
203
+ parts.push(this.deparseCompoundListInline(ifClause.condition));
204
+ parts.push('; then');
205
+ parts.push(this.deparseCompoundListInline(ifClause.then));
206
+ if (ifClause.else) {
207
+ if (ifClause.else.type === 'IfClause') {
208
+ // elif
209
+ parts.push('; el' + this.deparseIf(ifClause.else).substring(0));
210
+ return parts.join(' ').replace('; elif', '; elif').replace('; fi; fi', '; fi');
211
+ }
212
+ else {
213
+ parts.push('; else');
214
+ parts.push(this.deparseCompoundListInline(ifClause.else));
215
+ }
216
+ }
217
+ parts.push('; fi');
218
+ return parts.join(' ');
219
+ }
220
+ /**
221
+ * Deparse while clause
222
+ */
223
+ deparseWhile(whileClause) {
224
+ const condition = this.deparseCompoundListInline(whileClause.condition);
225
+ const body = this.deparseCompoundListInline(whileClause.body);
226
+ return `while ${condition}; do ${body}; done`;
227
+ }
228
+ /**
229
+ * Deparse until clause
230
+ */
231
+ deparseUntil(untilClause) {
232
+ const condition = this.deparseCompoundListInline(untilClause.condition);
233
+ const body = this.deparseCompoundListInline(untilClause.body);
234
+ return `until ${condition}; do ${body}; done`;
235
+ }
236
+ /**
237
+ * Deparse for clause
238
+ */
239
+ deparseFor(forClause) {
240
+ const parts = ['for', forClause.name];
241
+ if (forClause.wordlist && forClause.wordlist.length > 0) {
242
+ parts.push('in');
243
+ parts.push(forClause.wordlist.map(w => this.deparseWord(w)).join(' '));
244
+ }
245
+ parts.push(';');
246
+ parts.push('do');
247
+ parts.push(this.deparseCompoundListInline(forClause.body));
248
+ parts.push(';');
249
+ parts.push('done');
250
+ return parts.join(' ');
251
+ }
252
+ /**
253
+ * Deparse case clause
254
+ */
255
+ deparseCase(caseClause) {
256
+ const parts = [];
257
+ parts.push('case');
258
+ parts.push(this.deparseWord(caseClause.word));
259
+ parts.push('in');
260
+ for (const caseItem of caseClause.cases) {
261
+ parts.push(this.deparseCaseItem(caseItem));
262
+ }
263
+ parts.push('esac');
264
+ return parts.join(' ');
265
+ }
266
+ /**
267
+ * Deparse case item
268
+ */
269
+ deparseCaseItem(caseItem) {
270
+ const pattern = caseItem.pattern.map(w => this.deparseWord(w)).join('|');
271
+ let result = `${pattern})`;
272
+ if (caseItem.body) {
273
+ result += ' ' + this.deparseCompoundListInline(caseItem.body);
274
+ }
275
+ result += ' ;;';
276
+ return result;
277
+ }
278
+ /**
279
+ * Deparse function definition
280
+ */
281
+ deparseFunction(func) {
282
+ const body = func.body.type === 'Subshell'
283
+ ? this.deparseSubshell(func.body)
284
+ : `{ ${this.deparseCompoundListInline(func.body)}; }`;
285
+ return `${func.name}() ${body}`;
286
+ }
287
+ }
288
+ exports.Deparser = Deparser;
289
+ /**
290
+ * Deparse AST to source string
291
+ */
292
+ function deparse(node, options) {
293
+ const deparser = new Deparser(options);
294
+ return deparser.deparse(node);
295
+ }
296
+ /**
297
+ * Synchronous deparse (same as deparse, for API consistency)
298
+ */
299
+ exports.deparseSync = deparse;
package/esm/clean.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * No-op transform function - removes the property
3
+ */
4
+ export const noop = () => undefined;
5
+ /**
6
+ * Deep transform an object
7
+ */
8
+ function transform(obj, options) {
9
+ if (obj === null || obj === undefined) {
10
+ return obj;
11
+ }
12
+ if (Array.isArray(obj)) {
13
+ return obj.map(item => transform(item, options));
14
+ }
15
+ if (typeof obj === 'object') {
16
+ const result = {};
17
+ for (const key of Object.keys(obj)) {
18
+ const value = obj[key];
19
+ // Check if there's a transform function for this key
20
+ if (key in options) {
21
+ const transformed = options[key](value, key, obj);
22
+ if (transformed !== undefined) {
23
+ result[key] = transformed;
24
+ }
25
+ // If undefined, skip the property (remove it)
26
+ }
27
+ else {
28
+ // Recursively transform nested objects
29
+ result[key] = transform(value, options);
30
+ }
31
+ }
32
+ return result;
33
+ }
34
+ return obj;
35
+ }
36
+ /**
37
+ * Clean AST tree by removing location/position information
38
+ * This is used for comparing ASTs in round-trip testing
39
+ */
40
+ export function cleanTree(tree) {
41
+ return transform(tree, {
42
+ // Remove range/position information
43
+ range: noop,
44
+ // Normalize text strings (trim whitespace)
45
+ text: (value) => {
46
+ if (typeof value === 'string') {
47
+ return value.trim();
48
+ }
49
+ return value;
50
+ }
51
+ });
52
+ }
53
+ /**
54
+ * Compare two ASTs for equality after cleaning
55
+ */
56
+ export function compareAst(ast1, ast2) {
57
+ const clean1 = cleanTree(ast1);
58
+ const clean2 = cleanTree(ast2);
59
+ return JSON.stringify(clean1) === JSON.stringify(clean2);
60
+ }