generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpyodide-worker.ts
More file actions
312 lines (262 loc) · 10.2 KB
/
pyodide-worker.ts
File metadata and controls
312 lines (262 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import { parentPort } from 'worker_threads';
import { loadPyodide, type PyodideInterface } from 'pyodide';
import { PublishDiagnosticsParams } from 'vscode-languageserver';
import { CloudFormationFileType } from '../../document/Document';
// Instead of sending stdout/stderr messages back to the main thread,
// we'll just log them in the worker thread
const customStdout = (_text: string): void => {
// No-op in production, used for debugging
// console.log(text);
};
const customStderr = (_text: string): void => {
// No-op in production, used for debugging
// console.error(text);
};
interface WorkerMessage {
id: string;
action: string;
payload: Record<string, unknown>;
}
interface InitializeResult {
status: 'initialized' | 'already-initialized' | 'already-initializing';
}
interface MountResult {
mounted: boolean;
mountDir: string;
}
let pyodide: PyodideInterface | undefined;
let initialized = false;
let initializing = false;
// Handle messages from main thread
if (parentPort) {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
parentPort.on('message', async (message: WorkerMessage) => {
const { id, action, payload } = message;
try {
let result: unknown;
switch (action) {
case 'initialize': {
result = await initializePyodide();
break;
}
case 'lint': {
result = await lintTemplate(
payload.content as string,
payload.uri as string,
payload.fileType as CloudFormationFileType,
);
break;
}
case 'lintFile': {
result = await lintFile(
payload.path as string,
payload.uri as string,
payload.fileType as CloudFormationFileType,
);
break;
}
case 'mountFolder': {
result = mountFolder(payload.fsDir as string, payload.mountDir as string);
break;
}
default: {
throw new Error(`Unknown action: ${action}`);
}
}
// Send successful result back to main thread
if (parentPort !== null && parentPort !== undefined) {
parentPort.postMessage({ id, result, success: true });
}
} catch (error) {
// Send error back to main thread
if (parentPort !== null && parentPort !== undefined) {
parentPort.postMessage({
id,
error: error instanceof Error ? error.message : String(error),
success: false,
});
}
}
});
}
// Initialize Pyodide with cfn-lint
async function initializePyodide(): Promise<InitializeResult> {
if (initialized) {
return { status: 'already-initialized' };
}
if (initializing) {
return { status: 'already-initializing' };
}
initializing = true;
try {
// Load Pyodide with explicit stdout/stderr handlers
pyodide = await loadPyodide({
stdout: customStdout,
stderr: customStderr,
});
if (!pyodide) {
throw new Error('Failed to initialize Pyodide: returned null');
}
// Load required packages
await pyodide.loadPackage('micropip');
await pyodide.loadPackage('ssl');
await pyodide.loadPackage('pyyaml');
// Replace CSafeLoader with SafeLoader to avoid Pyodide parsing issues
await pyodide.runPythonAsync(`
import yaml
if hasattr(yaml, 'CSafeLoader'):
yaml.CSafeLoader = yaml.SafeLoader
`);
// Install cfn-lint
await pyodide.runPythonAsync(`
import micropip
await micropip.install('cfn-lint')
`);
// Setup Python functions for linting
await pyodide.runPythonAsync(`
import json
from cfnlint.version import __version__
print('cfn-lint version:', __version__)
import json
from pathlib import Path
from cfnlint import lint, lint_by_config, ManualArgs
def match_to_diagnostics(matches, uri):
filename_results = {}
for match in matches:
# Map severity levels to LSP DiagnosticSeverity
severity = 1 # Default: Error
if match.rule.severity.lower() == 'warning':
severity = 2
elif match.rule.severity.lower() == 'informational':
severity = 3
if match.filename not in filename_results:
filename_results[match.filename] = []
filename_results[match.filename].append({
'severity': severity,
'range': {
'start': {
'line': match.linenumber - 1,
'character': match.columnnumber - 1,
},
'end': {
'line': match.linenumberend - 1,
'character': match.columnnumberend - 1,
}
},
'message': match.message,
'source': 'cfn-lint',
'code': match.rule.id,
'codeDescription': {
'href': match.rule.source_url,
}
})
results = []
for filename, diagnostics in filename_results.items():
# For single-file linting, all diagnostics should map to the original file URI
# Multi-file scenarios (like GitSync referencing templates) should be handled
# by separate linting sessions for each file
results.append({
'uri': uri,
'diagnostics': diagnostics
})
return results
def lint_str(template_str, uri, template_args=None):
"""
Lint a CloudFormation template string and return LSP diagnostics
Args:
template_str (str): CloudFormation template as a string
uri (str): Document URI
template_args (dict, optional): Additional template arguments
Returns:
dict: LSP PublishDiagnosticsParams
"""
return match_to_diagnostics(lint(template_str), uri)
def lint_uri(lint_path, uri, lint_type, template_args=None):
args = ManualArgs()
path = Path(lint_path)
if lint_type == "template":
args["templates"] = [str(path)]
elif lint_type == "gitsync-deployment":
args["deployment_files"] = [str(path)]
return match_to_diagnostics(lint_by_config(args), uri)
`);
// Create result object first
const result = { status: 'initialized' as const };
// eslint-disable-next-line require-atomic-updates
initialized = true;
// eslint-disable-next-line require-atomic-updates
initializing = false;
return result;
} catch (error) {
// eslint-disable-next-line require-atomic-updates
initializing = false;
throw error;
}
}
function convertPythonResultToDiagnostics(result: unknown): PublishDiagnosticsParams[] {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
if (!result || typeof (result as any).toJs !== 'function') {
throw new Error('Invalid result from Python linting');
}
// Type assertion for the conversion result
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
const diagnostics = (result as any).toJs({
dict_converter: Object.fromEntries,
});
return (Array.isArray(diagnostics) ? diagnostics : []) as PublishDiagnosticsParams[];
}
// Lint template content as string
async function lintTemplate(
content: string,
uri: string,
_fileType: CloudFormationFileType,
): Promise<PublishDiagnosticsParams[]> {
if (!initialized || !pyodide) {
throw new Error('Pyodide not initialized');
}
// Safe type assertions since we know the expected types
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pyUri = pyodide.toPy(uri);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pyContent = pyodide.toPy(content.replaceAll('"""', '\\"\\"\\"'));
// Execute Python code and get result
const pythonCode = `lint_str(r"""${pyContent}""", r"""${pyUri}""")`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const result = await pyodide.runPythonAsync(pythonCode);
return convertPythonResultToDiagnostics(result);
}
// Lint file using path
async function lintFile(
path: string,
uri: string,
fileType: CloudFormationFileType,
): Promise<PublishDiagnosticsParams[]> {
if (!initialized || !pyodide) {
throw new Error('Pyodide not initialized');
}
// Execute Python code and get result
const pythonCode = `lint_uri(r"""${path}""", r"""${uri}""", r"""${fileType}""")`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const result = await pyodide.runPythonAsync(pythonCode);
return convertPythonResultToDiagnostics(result);
}
// Mount folder to Pyodide filesystem
function mountFolder(fsDir: string, mountDir: string): MountResult {
if (!initialized || !pyodide) {
throw new Error('Pyodide not initialized');
}
try {
pyodide.FS.mkdirTree(mountDir);
// The first parameter should be the mount point, the second parameter should be the host path
pyodide.mountNodeFS(mountDir, fsDir);
return { mounted: true, mountDir };
} catch (error) {
// Clean up if mounting fails
try {
pyodide.FS.rmdir(mountDir);
} catch {
// Ignore cleanup errors
}
throw error;
}
}