@player-lang/metrics-output-plugin 0.0.2-next.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.
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // ../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ MetricsOutput: () => MetricsOutput,
34
+ extractByData: () => extractByData,
35
+ extractFromDiagnostics: () => extractFromDiagnostics
36
+ });
37
+ module.exports = __toCommonJS(src_exports);
38
+
39
+ // ../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/metrics-output.ts
40
+ var fs = __toESM(require("fs"));
41
+ var path = __toESM(require("path"));
42
+ var import_ts_deepmerge = require("ts-deepmerge");
43
+ function normalizePath(filePath) {
44
+ const normalized = filePath.replace(/\\/g, "/");
45
+ return normalized.replace(/^file:\/\//, "");
46
+ }
47
+ var merge = import_ts_deepmerge.merge;
48
+ var MetricsOutput = class {
49
+ name = "metrics-output-plugin";
50
+ outputDir;
51
+ fileName;
52
+ rootProperties;
53
+ stats;
54
+ features;
55
+ // In-memory storage of all results
56
+ aggregatedResults = {
57
+ content: {}
58
+ };
59
+ get outputFilePath() {
60
+ return path.resolve(this.outputDir, `${this.fileName}.json`);
61
+ }
62
+ constructor(options = {}) {
63
+ this.outputDir = options.outputDir || process.cwd();
64
+ let fileName = options.fileName || "metrics";
65
+ if (fileName.endsWith(".json")) {
66
+ fileName = fileName.split(".")[0];
67
+ }
68
+ this.fileName = fileName;
69
+ this.rootProperties = options.rootProperties || {};
70
+ this.stats = options.stats || {};
71
+ this.features = options.features || {};
72
+ }
73
+ apply(service) {
74
+ service.hooks.onValidateEnd.tap(
75
+ this.name,
76
+ (diagnostics, { documentContext }) => {
77
+ if (fs.existsSync(this.outputFilePath)) {
78
+ this.loadExistingMetrics();
79
+ }
80
+ this.generateFile(diagnostics, documentContext);
81
+ return diagnostics;
82
+ }
83
+ );
84
+ }
85
+ loadExistingMetrics() {
86
+ try {
87
+ const fileContent = fs.readFileSync(this.outputFilePath, "utf-8");
88
+ if (!fileContent.trim()) {
89
+ return;
90
+ }
91
+ const parsed = JSON.parse(fileContent);
92
+ const existingMetrics = parsed && typeof parsed === "object" ? parsed : {};
93
+ this.aggregatedResults = merge(
94
+ existingMetrics,
95
+ this.aggregatedResults
96
+ );
97
+ } catch (error) {
98
+ console.warn(
99
+ `Warning: Could not parse existing metrics file ${this.outputFilePath}. Continuing with current metrics. Error: ${error}`
100
+ );
101
+ }
102
+ }
103
+ /**
104
+ * Evaluates a value, executing it if it's a function
105
+ */
106
+ evaluateValue(value, diagnostics, documentContext) {
107
+ if (typeof value === "function") {
108
+ try {
109
+ return value(diagnostics, documentContext);
110
+ } catch (error) {
111
+ documentContext.log.error(`Error evaluating value: ${error}`);
112
+ return { error: `Value evaluation failed: ${error}` };
113
+ }
114
+ }
115
+ return value;
116
+ }
117
+ generateMetrics(diagnostics, documentContext) {
118
+ const statsSource = this.stats;
119
+ if (typeof statsSource === "function") {
120
+ try {
121
+ const result2 = statsSource(diagnostics, documentContext);
122
+ if (typeof result2 === "object" && result2 !== null) {
123
+ return result2;
124
+ }
125
+ return { dynamicStatsValue: result2 };
126
+ } catch (error) {
127
+ documentContext.log.error(`Error evaluating stats function: ${error}`);
128
+ return { error: `Stats function evaluation failed: ${error}` };
129
+ }
130
+ }
131
+ const result = {};
132
+ Object.entries(statsSource).forEach(([key, value]) => {
133
+ result[key] = this.evaluateValue(value, diagnostics, documentContext);
134
+ });
135
+ return result;
136
+ }
137
+ generateFeatures(diagnostics, documentContext) {
138
+ const featuresSource = this.features;
139
+ if (typeof featuresSource === "function") {
140
+ try {
141
+ const result2 = featuresSource(diagnostics, documentContext);
142
+ if (typeof result2 === "object" && result2 !== null) {
143
+ return result2;
144
+ }
145
+ return { dynamicFeaturesValue: result2 };
146
+ } catch (error) {
147
+ documentContext.log.error(
148
+ `Error evaluating features function: ${error}`
149
+ );
150
+ return { error: `Features function evaluation failed: ${error}` };
151
+ }
152
+ }
153
+ const result = {};
154
+ Object.entries(featuresSource).forEach(([key, value]) => {
155
+ result[key] = this.evaluateValue(value, diagnostics, documentContext);
156
+ });
157
+ return result;
158
+ }
159
+ generateFile(diagnostics, documentContext) {
160
+ const fullOutputDir = path.resolve(process.cwd(), this.outputDir);
161
+ fs.mkdirSync(fullOutputDir, { recursive: true });
162
+ const filePath = normalizePath(documentContext.document.uri);
163
+ const stats = this.generateMetrics(
164
+ diagnostics,
165
+ documentContext
166
+ );
167
+ const features = this.generateFeatures(
168
+ diagnostics,
169
+ documentContext
170
+ );
171
+ const newEntry = {
172
+ stats,
173
+ ...Object.keys(features).length > 0 ? { features } : {}
174
+ };
175
+ let rootProps;
176
+ if (typeof this.rootProperties === "function") {
177
+ try {
178
+ const result = this.rootProperties(diagnostics, documentContext);
179
+ if (typeof result === "object" && result !== null) {
180
+ rootProps = result;
181
+ } else {
182
+ rootProps = { dynamicRootValue: result };
183
+ }
184
+ } catch (error) {
185
+ documentContext.log.error(`Error evaluating root properties: ${error}`);
186
+ rootProps = { error: `Root properties evaluation failed: ${error}` };
187
+ }
188
+ } else {
189
+ rootProps = this.rootProperties;
190
+ }
191
+ this.aggregatedResults = merge(
192
+ this.aggregatedResults,
193
+ rootProps,
194
+ { content: { [filePath]: newEntry } }
195
+ );
196
+ const outputFilePath = path.join(fullOutputDir, `${this.fileName}.json`);
197
+ const { content, ...root } = this.aggregatedResults;
198
+ fs.writeFileSync(
199
+ outputFilePath,
200
+ JSON.stringify({ ...root, content }, null, 2),
201
+ "utf-8"
202
+ );
203
+ return outputFilePath;
204
+ }
205
+ };
206
+
207
+ // ../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/utils.ts
208
+ function extractFromDiagnostics(pattern, parser) {
209
+ return (diagnostics) => {
210
+ for (const diagnostic of diagnostics) {
211
+ const match = diagnostic.message.match(pattern);
212
+ if (match && match[1]) {
213
+ try {
214
+ const result = parser(match[1]);
215
+ if (typeof result === "number" && isNaN(result)) {
216
+ console.warn(`Failed to parse diagnostic value: ${match[1]}`);
217
+ return void 0;
218
+ }
219
+ return result;
220
+ } catch (e) {
221
+ console.warn(`Failed to parse diagnostic value: ${match[1]}`, e);
222
+ return void 0;
223
+ }
224
+ }
225
+ }
226
+ return void 0;
227
+ };
228
+ }
229
+ function extractByData(data, diagnostics, parser) {
230
+ const filteredDiagnostics = diagnostics.filter(
231
+ (diagnostic) => diagnostic.data === data
232
+ );
233
+ if (filteredDiagnostics.length === 0) {
234
+ return {};
235
+ }
236
+ const defaultParser = (diagnostic) => {
237
+ try {
238
+ if (diagnostic.message) {
239
+ return JSON.parse(diagnostic.message);
240
+ }
241
+ return diagnostic.message || {};
242
+ } catch (e) {
243
+ return diagnostic.message || {};
244
+ }
245
+ };
246
+ const actualParser = parser || defaultParser;
247
+ const result = {};
248
+ for (const diagnostic of filteredDiagnostics) {
249
+ try {
250
+ const extractedData = actualParser(diagnostic);
251
+ if (typeof extractedData === "object" && extractedData !== null) {
252
+ Object.assign(result, extractedData);
253
+ } else {
254
+ const key = `entry_${Object.keys(result).length}`;
255
+ result[key] = extractedData;
256
+ }
257
+ } catch (e) {
258
+ console.warn(
259
+ `Failed to process diagnostic from data ${String(data)}:`,
260
+ e
261
+ );
262
+ }
263
+ }
264
+ return result;
265
+ }
266
+ // Annotate the CommonJS export names for ESM import in node:
267
+ 0 && (module.exports = {
268
+ MetricsOutput,
269
+ extractByData,
270
+ extractFromDiagnostics
271
+ });
272
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/index.ts","../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/metrics-output.ts","../../../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/utils.ts"],"sourcesContent":["export * from \"./metrics-output\";\nexport * from \"./utils\";\nexport * from \"./types\";\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { merge as deepMerge } from \"ts-deepmerge\";\nimport { Diagnostic } from \"vscode-languageserver-types\";\nimport type {\n PlayerLanguageService,\n PlayerLanguageServicePlugin,\n DocumentContext,\n} from \"@player-lang/json-language-service\";\nimport type {\n MetricsRoot,\n MetricsStats,\n MetricsFeatures,\n MetricsContent,\n MetricsReport,\n MetricValue,\n} from \"./types\";\n\nexport interface MetricsOutputConfig {\n /** Directory where the output file will be written */\n outputDir?: string;\n\n /** Name of the JSON output file */\n fileName?: string;\n\n /**\n * Custom properties to include at the root level of the output\n */\n rootProperties?: MetricsRoot;\n\n /**\n * Content-specific stats\n */\n stats?: MetricsStats;\n\n /**\n * Content-specific features\n */\n features?: MetricsFeatures;\n}\n\n/**\n * Normalizes a file path to use consistent separators and format\n */\nfunction normalizePath(filePath: string): string {\n // Convert backslashes to forward slashes for consistency\n const normalized = filePath.replace(/\\\\/g, \"/\");\n\n // Remove file:// protocol if present\n return normalized.replace(/^file:\\/\\//, \"\");\n}\n\n// Narrow ts-deepmerge’s generic return type to what's needed\nconst merge = deepMerge as <T>(...objects: Array<Partial<T>>) => T;\n\n/**\n * A plugin that writes diagnostic results to a JSON file in a specified output directory.\n * NOTE: This plugin is designed for CLI usage only and should not be used in an IDE.\n */\nexport class MetricsOutput implements PlayerLanguageServicePlugin {\n name = \"metrics-output-plugin\";\n\n private outputDir: string;\n private fileName: string;\n private rootProperties: MetricsRoot;\n private stats: MetricsStats;\n private features: MetricsFeatures;\n\n // In-memory storage of all results\n private aggregatedResults: MetricsReport = {\n content: {},\n };\n\n private get outputFilePath(): string {\n return path.resolve(this.outputDir, `${this.fileName}.json`);\n }\n\n constructor(options: MetricsOutputConfig = {}) {\n this.outputDir = options.outputDir || process.cwd();\n\n // Handle file name, stripping .json extension if provided\n let fileName = options.fileName || \"metrics\";\n if (fileName.endsWith(\".json\")) {\n fileName = fileName.split(\".\")[0]; // Remove extension\n }\n this.fileName = fileName;\n this.rootProperties = options.rootProperties || {};\n this.stats = options.stats || {};\n this.features = options.features || {};\n }\n\n apply(service: PlayerLanguageService): void {\n // Hook into the validation end to capture diagnostics and write output\n service.hooks.onValidateEnd.tap(\n this.name,\n (\n diagnostics: Diagnostic[],\n { documentContext }: { documentContext: DocumentContext },\n ): Diagnostic[] => {\n // If metrics file exists, load it\n if (fs.existsSync(this.outputFilePath)) {\n this.loadExistingMetrics();\n }\n\n this.generateFile(diagnostics, documentContext);\n\n return diagnostics;\n },\n );\n }\n\n private loadExistingMetrics(): void {\n try {\n const fileContent = fs.readFileSync(this.outputFilePath, \"utf-8\");\n\n // Handle empty file case - treat it as if no file exists\n if (!fileContent.trim()) {\n return;\n }\n\n const parsed: unknown = JSON.parse(fileContent);\n const existingMetrics: Partial<MetricsReport> =\n parsed && typeof parsed === \"object\"\n ? (parsed as Partial<MetricsReport>)\n : {};\n\n // Recursively merge existing metrics with current aggregated results\n this.aggregatedResults = merge<MetricsReport>(\n existingMetrics,\n this.aggregatedResults,\n );\n } catch (error) {\n // If we can't parse existing file, continue with current state\n console.warn(\n `Warning: Could not parse existing metrics file ${this.outputFilePath}. Continuing with current metrics. Error: ${error}`,\n );\n }\n }\n\n /**\n * Evaluates a value, executing it if it's a function\n */\n private evaluateValue(\n value: MetricValue,\n diagnostics: Diagnostic[],\n documentContext: DocumentContext,\n ) {\n if (typeof value === \"function\") {\n try {\n return value(diagnostics, documentContext);\n } catch (error) {\n documentContext.log.error(`Error evaluating value: ${error}`);\n return { error: `Value evaluation failed: ${error}` };\n }\n }\n return value;\n }\n\n private generateMetrics(\n diagnostics: Diagnostic[],\n documentContext: DocumentContext,\n ): MetricsStats {\n const statsSource = this.stats;\n // If stats is a function, evaluate it directly\n if (typeof statsSource === \"function\") {\n try {\n const result = statsSource(diagnostics, documentContext);\n if (typeof result === \"object\" && result !== null) {\n return result;\n }\n return { dynamicStatsValue: result };\n } catch (error) {\n documentContext.log.error(`Error evaluating stats function: ${error}`);\n return { error: `Stats function evaluation failed: ${error}` };\n }\n }\n\n // Otherwise process each metric in the record\n const result: MetricsStats = {};\n Object.entries(statsSource).forEach(([key, value]) => {\n result[key] = this.evaluateValue(value, diagnostics, documentContext);\n });\n\n return result;\n }\n\n private generateFeatures(\n diagnostics: Diagnostic[],\n documentContext: DocumentContext,\n ): Record<string, MetricValue> {\n const featuresSource = this.features;\n // If features is a function, evaluate it directly\n if (typeof featuresSource === \"function\") {\n try {\n const result = featuresSource(diagnostics, documentContext);\n if (typeof result === \"object\" && result !== null) {\n return result;\n }\n return { dynamicFeaturesValue: result };\n } catch (error) {\n documentContext.log.error(\n `Error evaluating features function: ${error}`,\n );\n return { error: `Features function evaluation failed: ${error}` };\n }\n }\n\n // Otherwise process each feature in the record\n const result: Record<string, MetricValue> = {};\n Object.entries(featuresSource).forEach(([key, value]) => {\n result[key] = this.evaluateValue(value, diagnostics, documentContext);\n });\n\n return result;\n }\n\n private generateFile(\n diagnostics: Diagnostic[],\n documentContext: DocumentContext,\n ): string {\n // Ensure the output directory exists\n const fullOutputDir = path.resolve(process.cwd(), this.outputDir);\n fs.mkdirSync(fullOutputDir, { recursive: true });\n\n // Get the file path from the document URI and normalize it\n const filePath = normalizePath(documentContext.document.uri);\n\n // Generate metrics\n const stats: MetricsStats = this.generateMetrics(\n diagnostics,\n documentContext,\n );\n const features: MetricsFeatures = this.generateFeatures(\n diagnostics,\n documentContext,\n );\n\n // Build this file's entry\n const newEntry: MetricsContent = {\n stats,\n ...(Object.keys(features).length > 0 ? { features } : {}),\n };\n\n // Evaluate root properties\n let rootProps: MetricsRoot;\n if (typeof this.rootProperties === \"function\") {\n try {\n const result = this.rootProperties(diagnostics, documentContext);\n if (typeof result === \"object\" && result !== null) {\n rootProps = result as Record<string, any>;\n } else {\n rootProps = { dynamicRootValue: result };\n }\n } catch (error) {\n documentContext.log.error(`Error evaluating root properties: ${error}`);\n rootProps = { error: `Root properties evaluation failed: ${error}` };\n }\n } else {\n rootProps = this.rootProperties as Record<string, any>;\n }\n\n // Single deep merge of root properties and content for this file\n this.aggregatedResults = merge<MetricsReport>(\n this.aggregatedResults,\n rootProps,\n { content: { [filePath]: newEntry } },\n );\n\n // Write ordered results: all root properties first, then content last\n const outputFilePath = path.join(fullOutputDir, `${this.fileName}.json`);\n const { content, ...root } = this.aggregatedResults;\n fs.writeFileSync(\n outputFilePath,\n JSON.stringify({ ...root, content }, null, 2),\n \"utf-8\",\n );\n\n return outputFilePath;\n }\n}\n","import { Diagnostic } from \"vscode-languageserver-types\";\n\n/**\n * Extracts data from diagnostic messages using a pattern\n */\nexport function extractFromDiagnostics<T>(\n pattern: RegExp,\n parser: (value: string) => T,\n): (diagnostics: Diagnostic[]) => T | undefined {\n return (diagnostics: Diagnostic[]): T | undefined => {\n for (const diagnostic of diagnostics) {\n const match = diagnostic.message.match(pattern);\n if (match && match[1]) {\n try {\n const result = parser(match[1]);\n // Check if result is NaN (only relevant for numeric parsers)\n if (typeof result === \"number\" && isNaN(result)) {\n console.warn(`Failed to parse diagnostic value: ${match[1]}`);\n return undefined;\n }\n return result;\n } catch (e) {\n console.warn(`Failed to parse diagnostic value: ${match[1]}`, e);\n return undefined;\n }\n }\n }\n return undefined;\n };\n}\n\n/**\n * Extracts data from diagnostics\n */\nexport function extractByData(\n data: string | symbol,\n diagnostics: Diagnostic[],\n parser?: (diagnostic: Diagnostic) => any,\n): Record<string, any> {\n const filteredDiagnostics = diagnostics.filter(\n (diagnostic) => diagnostic.data === data,\n );\n if (filteredDiagnostics.length === 0) {\n return {};\n }\n\n // Default parser that attempts to parse the message as JSON or returns the raw message\n const defaultParser = (diagnostic: Diagnostic): any => {\n try {\n if (diagnostic.message) {\n return JSON.parse(diagnostic.message);\n }\n return diagnostic.message || {};\n } catch (e) {\n return diagnostic.message || {};\n }\n };\n\n const actualParser = parser || defaultParser;\n\n // Collect all information from the specified source\n const result: Record<string, any> = {};\n for (const diagnostic of filteredDiagnostics) {\n try {\n const extractedData = actualParser(diagnostic);\n\n if (typeof extractedData === \"object\" && extractedData !== null) {\n // If object, merge with existing data\n Object.assign(result, extractedData);\n } else {\n // Otherwise store as separate entries\n const key = `entry_${Object.keys(result).length}`;\n result[key] = extractedData;\n }\n } catch (e) {\n console.warn(\n `Failed to process diagnostic from data ${String(data)}:`,\n e,\n );\n }\n }\n\n return result; // Always returns an object, even if empty\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACA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AACV,aAAO,WAAW,WAAW,CAAC;AAAA,IAChC;AAAA,EACF;AAEA,QAAM,eAAe,UAAU;AAG/B,QAAM,SAA8B,CAAC;AACrC,aAAW,cAAc,qBAAqB;AAC5C,QAAI;AACF,YAAM,gBAAgB,aAAa,UAAU;AAE7C,UAAI,OAAO,kBAAkB,YAAY,kBAAkB,MAAM;AAE/D,eAAO,OAAO,QAAQ,aAAa;AAAA,MACrC,OAAO;AAEL,cAAM,MAAM,SAAS,OAAO,KAAK,MAAM,EAAE,MAAM;AAC/C,eAAO,GAAG,IAAI;AAAA,MAChB;AAAA,IACF,SAAS,GAAG;AACV,cAAQ;AAAA,QACN,0CAA0C,OAAO,IAAI,CAAC;AAAA,QACtD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["deepMerge","result"]}
@@ -0,0 +1,233 @@
1
+ // ../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/metrics-output.ts
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ import { merge as deepMerge } from "ts-deepmerge";
5
+ function normalizePath(filePath) {
6
+ const normalized = filePath.replace(/\\/g, "/");
7
+ return normalized.replace(/^file:\/\//, "");
8
+ }
9
+ var merge = deepMerge;
10
+ var MetricsOutput = class {
11
+ name = "metrics-output-plugin";
12
+ outputDir;
13
+ fileName;
14
+ rootProperties;
15
+ stats;
16
+ features;
17
+ // In-memory storage of all results
18
+ aggregatedResults = {
19
+ content: {}
20
+ };
21
+ get outputFilePath() {
22
+ return path.resolve(this.outputDir, `${this.fileName}.json`);
23
+ }
24
+ constructor(options = {}) {
25
+ this.outputDir = options.outputDir || process.cwd();
26
+ let fileName = options.fileName || "metrics";
27
+ if (fileName.endsWith(".json")) {
28
+ fileName = fileName.split(".")[0];
29
+ }
30
+ this.fileName = fileName;
31
+ this.rootProperties = options.rootProperties || {};
32
+ this.stats = options.stats || {};
33
+ this.features = options.features || {};
34
+ }
35
+ apply(service) {
36
+ service.hooks.onValidateEnd.tap(
37
+ this.name,
38
+ (diagnostics, { documentContext }) => {
39
+ if (fs.existsSync(this.outputFilePath)) {
40
+ this.loadExistingMetrics();
41
+ }
42
+ this.generateFile(diagnostics, documentContext);
43
+ return diagnostics;
44
+ }
45
+ );
46
+ }
47
+ loadExistingMetrics() {
48
+ try {
49
+ const fileContent = fs.readFileSync(this.outputFilePath, "utf-8");
50
+ if (!fileContent.trim()) {
51
+ return;
52
+ }
53
+ const parsed = JSON.parse(fileContent);
54
+ const existingMetrics = parsed && typeof parsed === "object" ? parsed : {};
55
+ this.aggregatedResults = merge(
56
+ existingMetrics,
57
+ this.aggregatedResults
58
+ );
59
+ } catch (error) {
60
+ console.warn(
61
+ `Warning: Could not parse existing metrics file ${this.outputFilePath}. Continuing with current metrics. Error: ${error}`
62
+ );
63
+ }
64
+ }
65
+ /**
66
+ * Evaluates a value, executing it if it's a function
67
+ */
68
+ evaluateValue(value, diagnostics, documentContext) {
69
+ if (typeof value === "function") {
70
+ try {
71
+ return value(diagnostics, documentContext);
72
+ } catch (error) {
73
+ documentContext.log.error(`Error evaluating value: ${error}`);
74
+ return { error: `Value evaluation failed: ${error}` };
75
+ }
76
+ }
77
+ return value;
78
+ }
79
+ generateMetrics(diagnostics, documentContext) {
80
+ const statsSource = this.stats;
81
+ if (typeof statsSource === "function") {
82
+ try {
83
+ const result2 = statsSource(diagnostics, documentContext);
84
+ if (typeof result2 === "object" && result2 !== null) {
85
+ return result2;
86
+ }
87
+ return { dynamicStatsValue: result2 };
88
+ } catch (error) {
89
+ documentContext.log.error(`Error evaluating stats function: ${error}`);
90
+ return { error: `Stats function evaluation failed: ${error}` };
91
+ }
92
+ }
93
+ const result = {};
94
+ Object.entries(statsSource).forEach(([key, value]) => {
95
+ result[key] = this.evaluateValue(value, diagnostics, documentContext);
96
+ });
97
+ return result;
98
+ }
99
+ generateFeatures(diagnostics, documentContext) {
100
+ const featuresSource = this.features;
101
+ if (typeof featuresSource === "function") {
102
+ try {
103
+ const result2 = featuresSource(diagnostics, documentContext);
104
+ if (typeof result2 === "object" && result2 !== null) {
105
+ return result2;
106
+ }
107
+ return { dynamicFeaturesValue: result2 };
108
+ } catch (error) {
109
+ documentContext.log.error(
110
+ `Error evaluating features function: ${error}`
111
+ );
112
+ return { error: `Features function evaluation failed: ${error}` };
113
+ }
114
+ }
115
+ const result = {};
116
+ Object.entries(featuresSource).forEach(([key, value]) => {
117
+ result[key] = this.evaluateValue(value, diagnostics, documentContext);
118
+ });
119
+ return result;
120
+ }
121
+ generateFile(diagnostics, documentContext) {
122
+ const fullOutputDir = path.resolve(process.cwd(), this.outputDir);
123
+ fs.mkdirSync(fullOutputDir, { recursive: true });
124
+ const filePath = normalizePath(documentContext.document.uri);
125
+ const stats = this.generateMetrics(
126
+ diagnostics,
127
+ documentContext
128
+ );
129
+ const features = this.generateFeatures(
130
+ diagnostics,
131
+ documentContext
132
+ );
133
+ const newEntry = {
134
+ stats,
135
+ ...Object.keys(features).length > 0 ? { features } : {}
136
+ };
137
+ let rootProps;
138
+ if (typeof this.rootProperties === "function") {
139
+ try {
140
+ const result = this.rootProperties(diagnostics, documentContext);
141
+ if (typeof result === "object" && result !== null) {
142
+ rootProps = result;
143
+ } else {
144
+ rootProps = { dynamicRootValue: result };
145
+ }
146
+ } catch (error) {
147
+ documentContext.log.error(`Error evaluating root properties: ${error}`);
148
+ rootProps = { error: `Root properties evaluation failed: ${error}` };
149
+ }
150
+ } else {
151
+ rootProps = this.rootProperties;
152
+ }
153
+ this.aggregatedResults = merge(
154
+ this.aggregatedResults,
155
+ rootProps,
156
+ { content: { [filePath]: newEntry } }
157
+ );
158
+ const outputFilePath = path.join(fullOutputDir, `${this.fileName}.json`);
159
+ const { content, ...root } = this.aggregatedResults;
160
+ fs.writeFileSync(
161
+ outputFilePath,
162
+ JSON.stringify({ ...root, content }, null, 2),
163
+ "utf-8"
164
+ );
165
+ return outputFilePath;
166
+ }
167
+ };
168
+
169
+ // ../../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/lsp/metrics-output-plugin/src/utils.ts
170
+ function extractFromDiagnostics(pattern, parser) {
171
+ return (diagnostics) => {
172
+ for (const diagnostic of diagnostics) {
173
+ const match = diagnostic.message.match(pattern);
174
+ if (match && match[1]) {
175
+ try {
176
+ const result = parser(match[1]);
177
+ if (typeof result === "number" && isNaN(result)) {
178
+ console.warn(`Failed to parse diagnostic value: ${match[1]}`);
179
+ return void 0;
180
+ }
181
+ return result;
182
+ } catch (e) {
183
+ console.warn(`Failed to parse diagnostic value: ${match[1]}`, e);
184
+ return void 0;
185
+ }
186
+ }
187
+ }
188
+ return void 0;
189
+ };
190
+ }
191
+ function extractByData(data, diagnostics, parser) {
192
+ const filteredDiagnostics = diagnostics.filter(
193
+ (diagnostic) => diagnostic.data === data
194
+ );
195
+ if (filteredDiagnostics.length === 0) {
196
+ return {};
197
+ }
198
+ const defaultParser = (diagnostic) => {
199
+ try {
200
+ if (diagnostic.message) {
201
+ return JSON.parse(diagnostic.message);
202
+ }
203
+ return diagnostic.message || {};
204
+ } catch (e) {
205
+ return diagnostic.message || {};
206
+ }
207
+ };
208
+ const actualParser = parser || defaultParser;
209
+ const result = {};
210
+ for (const diagnostic of filteredDiagnostics) {
211
+ try {
212
+ const extractedData = actualParser(diagnostic);
213
+ if (typeof extractedData === "object" && extractedData !== null) {
214
+ Object.assign(result, extractedData);
215
+ } else {
216
+ const key = `entry_${Object.keys(result).length}`;
217
+ result[key] = extractedData;
218
+ }
219
+ } catch (e) {
220
+ console.warn(
221
+ `Failed to process diagnostic from data ${String(data)}:`,
222
+ e
223
+ );
224
+ }
225
+ }
226
+ return result;
227
+ }
228
+ export {
229
+ MetricsOutput,
230
+ extractByData,
231
+ extractFromDiagnostics
232
+ };
233
+ //# sourceMappingURL=index.mjs.map