@netgreener/runtime 0.1.8 → 0.1.10

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.
Files changed (114) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/TUTORIAL.md +120 -29
  3. package/dist/aggregator.d.ts +12 -2
  4. package/dist/aggregator.js +135 -8
  5. package/dist/analyze/buildResourceFindings.d.ts +4 -0
  6. package/dist/analyze/buildResourceFindings.js +17 -0
  7. package/dist/analyze/cli.d.ts +1 -0
  8. package/dist/analyze/cli.js +22 -1
  9. package/dist/analyze/declaredExternalApis.d.ts +31 -0
  10. package/dist/analyze/declaredExternalApis.js +174 -0
  11. package/dist/analyze/index.d.ts +1 -0
  12. package/dist/analyze/index.js +1 -0
  13. package/dist/auto.d.ts +7 -0
  14. package/dist/auto.js +8 -0
  15. package/dist/bullmq.d.ts +2 -2
  16. package/dist/bullmq.js +28 -58
  17. package/dist/carbonLedger.d.ts +28 -0
  18. package/dist/carbonLedger.js +52 -0
  19. package/dist/cgroupV2.d.ts +44 -0
  20. package/dist/cgroupV2.js +174 -0
  21. package/dist/cli/helpText.d.ts +3 -3
  22. package/dist/cli/helpText.js +42 -35
  23. package/dist/cli/netgreener.d.ts +7 -7
  24. package/dist/cli/netgreener.js +23 -16
  25. package/dist/cli/runCli.d.ts +20 -0
  26. package/dist/cli/runCli.js +249 -0
  27. package/dist/cli/runPreload.d.ts +5 -0
  28. package/dist/cli/runPreload.js +43 -0
  29. package/dist/collectorMetadata.d.ts +1 -1
  30. package/dist/collectorMetadata.js +2 -0
  31. package/dist/config.d.ts +2 -0
  32. package/dist/config.js +6 -2
  33. package/dist/exporter.d.ts +7 -2
  34. package/dist/exporter.js +12 -6
  35. package/dist/express.js +17 -6
  36. package/dist/externalApiMeter.d.ts +51 -2
  37. package/dist/externalApiMeter.js +379 -26
  38. package/dist/fastify.js +17 -6
  39. package/dist/index.d.ts +12 -2
  40. package/dist/index.js +11 -1
  41. package/dist/init.d.ts +30 -0
  42. package/dist/init.js +31 -0
  43. package/dist/lifecycle.d.ts +45 -0
  44. package/dist/lifecycle.js +112 -0
  45. package/dist/managedCollectorLauncher.d.ts +37 -0
  46. package/dist/managedCollectorLauncher.js +162 -0
  47. package/dist/mcpToolMeter.d.ts +101 -0
  48. package/dist/mcpToolMeter.js +496 -0
  49. package/dist/n4/deploymentMatrix.d.ts +9 -5
  50. package/dist/n4/deploymentMatrix.js +13 -9
  51. package/dist/n4/missingnessInventory.js +3 -3
  52. package/dist/next.d.ts +89 -0
  53. package/dist/next.js +328 -0
  54. package/dist/nextConfig.d.ts +34 -0
  55. package/dist/nextConfig.js +73 -0
  56. package/dist/nextEntryTransform.d.ts +9 -0
  57. package/dist/nextEntryTransform.js +181 -0
  58. package/dist/occupancyTracker.d.ts +27 -0
  59. package/dist/occupancyTracker.js +87 -0
  60. package/dist/optimize/apply.d.ts +38 -0
  61. package/dist/optimize/apply.js +173 -0
  62. package/dist/optimize/cli.d.ts +26 -0
  63. package/dist/optimize/cli.js +323 -0
  64. package/dist/optimize/index.d.ts +6 -0
  65. package/dist/optimize/index.js +5 -0
  66. package/dist/optimize/llmApply.d.ts +22 -0
  67. package/dist/optimize/llmApply.js +80 -0
  68. package/dist/optimize/llmSession.d.ts +88 -0
  69. package/dist/optimize/llmSession.js +135 -0
  70. package/dist/optimize/provider.d.ts +17 -0
  71. package/dist/optimize/provider.js +119 -0
  72. package/dist/optimize/safePatches.d.ts +18 -0
  73. package/dist/optimize/safePatches.js +247 -0
  74. package/dist/optimize/types.d.ts +79 -0
  75. package/dist/optimize/types.js +6 -0
  76. package/dist/optimize/verification.d.ts +16 -0
  77. package/dist/optimize/verification.js +165 -0
  78. package/dist/processResources.d.ts +5 -0
  79. package/dist/processResources.js +28 -4
  80. package/dist/processRuntime.js +7 -28
  81. package/dist/processTree.d.ts +47 -0
  82. package/dist/processTree.js +148 -0
  83. package/dist/runContextEnrichment.d.ts +11 -0
  84. package/dist/runContextEnrichment.js +92 -0
  85. package/dist/runtime.d.ts +36 -1
  86. package/dist/runtime.js +140 -17
  87. package/dist/sdk/client.d.ts +152 -0
  88. package/dist/sdk/client.js +396 -0
  89. package/dist/sdk/gitUrl.d.ts +6 -0
  90. package/dist/sdk/gitUrl.js +87 -0
  91. package/dist/sdk/index.d.ts +5 -0
  92. package/dist/sdk/index.js +5 -0
  93. package/dist/serverlessHints.d.ts +9 -6
  94. package/dist/serverlessHints.js +10 -7
  95. package/dist/taskMeter.d.ts +14 -0
  96. package/dist/taskMeter.js +53 -0
  97. package/dist/types.d.ts +43 -0
  98. package/examples/aca-container-gate/Dockerfile +20 -0
  99. package/examples/aca-container-gate/azure-container-app.yaml +27 -0
  100. package/examples/aca-container-gate/gate.env +7 -0
  101. package/examples/aca-container-gate/server.mjs +117 -0
  102. package/examples/azure-functions-gate/.funcignore +6 -0
  103. package/examples/azure-functions-gate/README.md +25 -0
  104. package/examples/azure-functions-gate/host.json +15 -0
  105. package/examples/azure-functions-gate/package-lock.json +161 -0
  106. package/examples/azure-functions-gate/package.json +14 -0
  107. package/examples/azure-functions-gate/src/functions/health.js +27 -0
  108. package/examples/express-local-live-smoke.mjs +127 -0
  109. package/examples/extractRunId.mjs +11 -0
  110. package/examples/next-pilot-dry-run.mjs +32 -0
  111. package/examples/serverless-thin-gate.mjs +89 -0
  112. package/fixtures/run-smoke/hello.mjs +4 -0
  113. package/loaders/next-entry-loader.cjs +14 -0
  114. package/package.json +25 -2
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Thin Node HTTP client twin of Python ``netgreener_sdk.NetGreenerClient``.
3
+ *
4
+ * Same api_server brain — no Node server fork. Does not flip EXPORT_MODE.
5
+ */
6
+ export declare class ApiError extends Error {
7
+ readonly statusCode: number;
8
+ readonly detail: string;
9
+ constructor(statusCode: number, detail: string);
10
+ }
11
+ export type NetGreenerSdkOptions = {
12
+ token?: string;
13
+ /** API root including ``/api/v1`` */
14
+ baseUrl?: string;
15
+ orgId?: number;
16
+ environment?: string;
17
+ userId?: number;
18
+ fetchImpl?: typeof fetch;
19
+ };
20
+ type ProjectRow = Record<string, unknown> & {
21
+ project_id?: number;
22
+ name?: string;
23
+ directory?: string;
24
+ git_url?: string | null;
25
+ };
26
+ export declare class NetGreenerClient {
27
+ baseUrl: string;
28
+ private token;
29
+ private orgId;
30
+ private environment;
31
+ private userId;
32
+ private readonly fetchImpl;
33
+ constructor(opts?: NetGreenerSdkOptions);
34
+ setToken(token: string | undefined): void;
35
+ getAccessToken(): string | undefined;
36
+ setOrgContext(orgId: number | undefined, environment?: string): void;
37
+ getOrgContext(): {
38
+ orgId: number | undefined;
39
+ environment: string | undefined;
40
+ };
41
+ /** GET /organizations/by-slug/{slug} (OP2). */
42
+ getOrganizationBySlug(slug: string): Promise<Record<string, unknown>>;
43
+ /** Resolve slug → orgId and set client org context. */
44
+ resolveOrgSlug(slug: string): Promise<number>;
45
+ private headers;
46
+ private raise;
47
+ private request;
48
+ login(email: string, password: string): Promise<Record<string, unknown>>;
49
+ getMe(): Promise<Record<string, unknown>>;
50
+ postRunSession(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
51
+ getRunSession(runId: number): Promise<Record<string, unknown>>;
52
+ getRunOutcome(runId: number): Promise<Record<string, unknown>>;
53
+ attachRunOutcome(runId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
54
+ getRunSessions(opts?: {
55
+ projectId?: number;
56
+ ciOnly?: boolean;
57
+ branch?: string;
58
+ }): Promise<unknown[]>;
59
+ createServiceToken(orgId: number, scopes: string[], opts?: {
60
+ environment?: string;
61
+ expiresInHours?: number;
62
+ }): Promise<Record<string, unknown>>;
63
+ listServiceTokens(orgId: number): Promise<Record<string, unknown>>;
64
+ revokeServiceToken(orgId: number, tokenId: number): Promise<Record<string, unknown>>;
65
+ getProjects(opts?: {
66
+ isActive?: boolean;
67
+ }): Promise<ProjectRow[]>;
68
+ createProject(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
69
+ updateProject(projectId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
70
+ getProject(projectId: number): Promise<Record<string, unknown>>;
71
+ private ensureUserId;
72
+ private maybeSyncProject;
73
+ /**
74
+ * Match by git_url → directory → name; create when none match.
75
+ * Same order as Python SDK / CLI.
76
+ */
77
+ getOrCreateProject(name: string, directory: string, opts?: {
78
+ gitUrl?: string | null;
79
+ userId?: number;
80
+ language?: string;
81
+ }): Promise<Record<string, unknown>>;
82
+ getReportSettings(orgId: number): Promise<Record<string, unknown>>;
83
+ updateReportSettings(orgId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
84
+ previewReport(orgId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
85
+ generateReport(orgId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
86
+ getReportHistory(orgId: number, opts?: {
87
+ limit?: number;
88
+ }): Promise<unknown[]>;
89
+ getEnergyBaseline(projectId: number, opts?: {
90
+ branch?: string;
91
+ }): Promise<Record<string, unknown>>;
92
+ rotateServiceToken(orgId: number, tokenId: number, opts?: {
93
+ expiresInHours?: number;
94
+ }): Promise<Record<string, unknown>>;
95
+ quoteReportAiSummary(orgId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
96
+ downloadReport(orgId: number, reportId: number, opts?: {
97
+ format?: string;
98
+ }): Promise<Record<string, unknown>>;
99
+ quoteCredits(orgId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
100
+ estimateRun(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
101
+ estimateProject(projectId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
102
+ getRunEstimate(runId: number): Promise<Record<string, unknown>>;
103
+ analyzeProjectFiles(projectId: number, perFile: Array<{
104
+ rel_path: string;
105
+ features: unknown;
106
+ }>): Promise<unknown[]>;
107
+ getProjectFindings(projectId: number): Promise<unknown[]>;
108
+ /**
109
+ * POST /findings/batch — optional ``declared_external_apis`` seeds the org
110
+ * external-API catalog (Python analyze twin). Findings may be empty.
111
+ */
112
+ postFindingsBatch(findings: Record<string, unknown>[], options?: {
113
+ projectId?: number;
114
+ replaceExisting?: boolean;
115
+ scopeFilePaths?: string[];
116
+ declaredExternalApis?: Array<{
117
+ provider_key: string;
118
+ detection_method?: string;
119
+ module_roots?: string[];
120
+ file_paths?: string[];
121
+ }>;
122
+ detectionContext?: Record<string, unknown>;
123
+ }): Promise<Record<string, unknown>>;
124
+ submitFindingFeedback(findingId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
125
+ getProjectDataSources(projectId: number): Promise<unknown[]>;
126
+ createProjectDataSource(projectId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
127
+ linkProjectDataSource(projectId: number, sourceId: number, opts?: {
128
+ isDefault?: boolean;
129
+ }): Promise<Record<string, unknown>>;
130
+ updateDataSource(sourceId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
131
+ deleteDataSource(sourceId: number): Promise<Record<string, unknown>>;
132
+ getRunDataSources(runId: number): Promise<unknown[]>;
133
+ getProjectFeatureMetadata(projectId: number): Promise<Record<string, unknown>>;
134
+ postProjectFeatureMetadata(projectId: number, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
135
+ listFeatureDefinitions(): Promise<unknown[]>;
136
+ /** POST ``/optimize/function`` — shared LLM optimize brain (Python/VSCE twin). */
137
+ optimizeFunction(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
138
+ /** POST ``/optimize/plan`` — ranked optimization plan. */
139
+ createOptimizationPlan(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
140
+ getOptimizationPlan(planId: number): Promise<Record<string, unknown>>;
141
+ listOptimizationPlans(projectId: number, opts?: {
142
+ limit?: number;
143
+ }): Promise<unknown[]>;
144
+ /** GET ``/developer/me/anomaly-briefs/pending`` — same brain as VSCE poll. */
145
+ listPendingAnomalyBriefs(): Promise<unknown[]>;
146
+ getAnomalyBrief(briefId: string): Promise<Record<string, unknown>>;
147
+ claimAnomalyBrief(briefId: string, opts?: {
148
+ claimedByDevice?: string;
149
+ }): Promise<Record<string, unknown>>;
150
+ updateAnomalyBrief(briefId: string, status: 'completed' | 'cancelled'): Promise<Record<string, unknown>>;
151
+ }
152
+ export {};
@@ -0,0 +1,396 @@
1
+ /**
2
+ * Thin Node HTTP client twin of Python ``netgreener_sdk.NetGreenerClient``.
3
+ *
4
+ * Same api_server brain — no Node server fork. Does not flip EXPORT_MODE.
5
+ */
6
+ import { normalizeGitUrl } from './gitUrl.js';
7
+ export class ApiError extends Error {
8
+ statusCode;
9
+ detail;
10
+ constructor(statusCode, detail) {
11
+ super(`HTTP ${statusCode}: ${detail}`);
12
+ this.name = 'ApiError';
13
+ this.statusCode = statusCode;
14
+ this.detail = detail;
15
+ }
16
+ }
17
+ const DEFAULT_BASE = 'https://dashboard.netgreener.com/api/v1';
18
+ export class NetGreenerClient {
19
+ baseUrl;
20
+ token;
21
+ orgId;
22
+ environment;
23
+ userId;
24
+ fetchImpl;
25
+ constructor(opts = {}) {
26
+ this.baseUrl = (opts.baseUrl || DEFAULT_BASE).replace(/\/$/, '');
27
+ this.token = opts.token;
28
+ this.orgId = opts.orgId;
29
+ this.environment = opts.environment;
30
+ this.userId = opts.userId;
31
+ this.fetchImpl = opts.fetchImpl || globalThis.fetch.bind(globalThis);
32
+ }
33
+ setToken(token) {
34
+ this.token = token;
35
+ }
36
+ getAccessToken() {
37
+ return this.token;
38
+ }
39
+ setOrgContext(orgId, environment) {
40
+ this.orgId = orgId;
41
+ if (environment !== undefined)
42
+ this.environment = environment;
43
+ }
44
+ getOrgContext() {
45
+ return { orgId: this.orgId, environment: this.environment };
46
+ }
47
+ /** GET /organizations/by-slug/{slug} (OP2). */
48
+ async getOrganizationBySlug(slug) {
49
+ const cleaned = String(slug || '')
50
+ .trim()
51
+ .toLowerCase();
52
+ if (cleaned.length < 2)
53
+ throw new ApiError(400, 'Invalid organization slug');
54
+ return this.request('GET', `/organizations/by-slug/${encodeURIComponent(cleaned)}`);
55
+ }
56
+ /** Resolve slug → orgId and set client org context. */
57
+ async resolveOrgSlug(slug) {
58
+ const org = await this.getOrganizationBySlug(slug);
59
+ const orgId = Number(org.org_id);
60
+ if (!Number.isFinite(orgId) || orgId <= 0) {
61
+ throw new ApiError(500, 'Organization response missing org_id');
62
+ }
63
+ this.setOrgContext(orgId, this.environment);
64
+ return orgId;
65
+ }
66
+ headers(json = true) {
67
+ const h = {};
68
+ if (json)
69
+ h['Content-Type'] = 'application/json';
70
+ if (this.token)
71
+ h.Authorization = `Bearer ${this.token}`;
72
+ if (this.orgId != null)
73
+ h['X-Organization-ID'] = String(this.orgId);
74
+ if (this.environment)
75
+ h['X-Environment'] = this.environment;
76
+ return h;
77
+ }
78
+ async raise(resp) {
79
+ if (resp.ok)
80
+ return;
81
+ let detail = await resp.text();
82
+ try {
83
+ const body = JSON.parse(detail);
84
+ if (body.detail != null)
85
+ detail = String(body.detail);
86
+ }
87
+ catch {
88
+ /* keep text */
89
+ }
90
+ throw new ApiError(resp.status, detail);
91
+ }
92
+ async request(method, path, body) {
93
+ const url = `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
94
+ const resp = await this.fetchImpl(url, {
95
+ method,
96
+ headers: this.headers(body !== undefined),
97
+ body: body === undefined ? undefined : JSON.stringify(body),
98
+ });
99
+ await this.raise(resp);
100
+ if (resp.status === 204)
101
+ return undefined;
102
+ return (await resp.json());
103
+ }
104
+ async login(email, password) {
105
+ const data = await this.request('POST', '/auth/login', {
106
+ email,
107
+ password,
108
+ });
109
+ const token = data.access_token;
110
+ if (typeof token === 'string')
111
+ this.token = token;
112
+ const user = data.user;
113
+ if (user && typeof user === 'object' && 'user_id' in user) {
114
+ const uid = user.user_id;
115
+ if (uid != null)
116
+ this.userId = Number(uid);
117
+ }
118
+ return data;
119
+ }
120
+ async getMe() {
121
+ return this.request('GET', '/auth/me');
122
+ }
123
+ async postRunSession(payload) {
124
+ return this.request('POST', '/runsessions/', payload);
125
+ }
126
+ async getRunSession(runId) {
127
+ return this.request('GET', `/runsessions/${runId}`);
128
+ }
129
+ async getRunOutcome(runId) {
130
+ return this.request('GET', `/runsessions/${runId}/outcome`);
131
+ }
132
+ async attachRunOutcome(runId, payload) {
133
+ return this.request('PUT', `/runsessions/${runId}/outcome`, payload);
134
+ }
135
+ async getRunSessions(opts) {
136
+ const params = new URLSearchParams();
137
+ if (opts?.projectId != null)
138
+ params.set('project_id', String(opts.projectId));
139
+ if (opts?.ciOnly)
140
+ params.set('ci_only', 'true');
141
+ if (opts?.branch)
142
+ params.set('branch', opts.branch);
143
+ const q = params.toString();
144
+ const data = await this.request('GET', q ? `/runsessions?${q}` : '/runsessions');
145
+ return Array.isArray(data) ? data : [];
146
+ }
147
+ async createServiceToken(orgId, scopes, opts) {
148
+ return this.request('POST', '/auth/service-token', {
149
+ org_id: orgId,
150
+ environment: opts?.environment ?? 'dev',
151
+ scopes,
152
+ expires_in_hours: opts?.expiresInHours ?? 24 * 30,
153
+ });
154
+ }
155
+ async listServiceTokens(orgId) {
156
+ return this.request('GET', `/auth/service-tokens?org_id=${orgId}`);
157
+ }
158
+ async revokeServiceToken(orgId, tokenId) {
159
+ return this.request('POST', `/auth/service-token/${tokenId}/revoke?org_id=${orgId}`);
160
+ }
161
+ async getProjects(opts) {
162
+ const q = opts?.isActive === undefined ? '' : `?is_active=${opts.isActive ? 'true' : 'false'}`;
163
+ const data = await this.request('GET', `/projects${q}`);
164
+ return Array.isArray(data) ? data : [];
165
+ }
166
+ async createProject(payload) {
167
+ return this.request('POST', '/projects/', payload);
168
+ }
169
+ async updateProject(projectId, payload) {
170
+ return this.request('PUT', `/projects/${projectId}`, payload);
171
+ }
172
+ async getProject(projectId) {
173
+ return this.request('GET', `/projects/${projectId}`);
174
+ }
175
+ async ensureUserId() {
176
+ if (this.userId != null)
177
+ return this.userId;
178
+ const me = await this.getMe();
179
+ const uid = me.user_id;
180
+ if (uid == null)
181
+ throw new ApiError(401, 'Could not resolve user_id from /auth/me');
182
+ this.userId = Number(uid);
183
+ return this.userId;
184
+ }
185
+ async maybeSyncProject(project, directory, gitUrl) {
186
+ const projectId = project.project_id;
187
+ if (!projectId)
188
+ return project;
189
+ const normDir = directory.replace(/\\/g, '/').replace(/\/+$/, '');
190
+ const currentDir = String(project.directory || '')
191
+ .replace(/\\/g, '/')
192
+ .replace(/\/+$/, '');
193
+ const normGit = normalizeGitUrl(gitUrl);
194
+ const currentGit = normalizeGitUrl(project.git_url);
195
+ const patch = {};
196
+ if (normDir && currentDir !== normDir)
197
+ patch.directory = normDir;
198
+ if (normGit && !currentGit)
199
+ patch.git_url = normGit;
200
+ if (!Object.keys(patch).length)
201
+ return project;
202
+ try {
203
+ return await this.updateProject(Number(projectId), patch);
204
+ }
205
+ catch {
206
+ return project;
207
+ }
208
+ }
209
+ /**
210
+ * Match by git_url → directory → name; create when none match.
211
+ * Same order as Python SDK / CLI.
212
+ */
213
+ async getOrCreateProject(name, directory, opts) {
214
+ const projects = await this.getProjects();
215
+ const normDir = directory.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
216
+ const normGit = normalizeGitUrl(opts?.gitUrl);
217
+ if (normGit) {
218
+ for (const project of projects) {
219
+ if (normalizeGitUrl(project.git_url) === normGit) {
220
+ return this.maybeSyncProject(project, directory, normGit);
221
+ }
222
+ }
223
+ }
224
+ for (const project of projects) {
225
+ const projectDir = String(project.directory || '')
226
+ .replace(/\\/g, '/')
227
+ .replace(/\/+$/, '')
228
+ .toLowerCase();
229
+ if (projectDir && projectDir === normDir) {
230
+ return this.maybeSyncProject(project, directory, normGit);
231
+ }
232
+ }
233
+ for (const project of projects) {
234
+ if (project.name === name) {
235
+ return this.maybeSyncProject(project, directory, normGit);
236
+ }
237
+ }
238
+ const userId = opts?.userId ?? (await this.ensureUserId());
239
+ const payload = {
240
+ name,
241
+ directory: directory.replace(/\\/g, '/').replace(/\/+$/, ''),
242
+ language: opts?.language ?? 'JavaScript',
243
+ user_id: userId,
244
+ };
245
+ if (normGit)
246
+ payload.git_url = normGit;
247
+ return this.createProject(payload);
248
+ }
249
+ async getReportSettings(orgId) {
250
+ return this.request('GET', `/organizations/${orgId}/reports/settings`);
251
+ }
252
+ async updateReportSettings(orgId, payload) {
253
+ return this.request('PUT', `/organizations/${orgId}/reports/settings`, payload);
254
+ }
255
+ async previewReport(orgId, payload) {
256
+ return this.request('POST', `/organizations/${orgId}/reports/preview`, payload);
257
+ }
258
+ async generateReport(orgId, payload) {
259
+ return this.request('POST', `/organizations/${orgId}/reports/generate`, payload);
260
+ }
261
+ async getReportHistory(orgId, opts) {
262
+ const limit = opts?.limit ?? 50;
263
+ const data = await this.request('GET', `/organizations/${orgId}/reports/history?limit=${limit}`);
264
+ return Array.isArray(data) ? data : [];
265
+ }
266
+ async getEnergyBaseline(projectId, opts) {
267
+ const q = opts?.branch
268
+ ? `?project_id=${projectId}&branch=${encodeURIComponent(opts.branch)}`
269
+ : `?project_id=${projectId}`;
270
+ return this.request('GET', `/energy/baseline${q}`);
271
+ }
272
+ async rotateServiceToken(orgId, tokenId, opts) {
273
+ return this.request('POST', `/auth/service-token/${tokenId}/rotate?org_id=${orgId}`, { expires_in_hours: opts?.expiresInHours ?? 24 * 30 });
274
+ }
275
+ async quoteReportAiSummary(orgId, payload) {
276
+ return this.request('POST', `/organizations/${orgId}/reports/ai-summary/quote`, payload);
277
+ }
278
+ async downloadReport(orgId, reportId, opts) {
279
+ const fmt = opts?.format ? `?format=${encodeURIComponent(opts.format)}` : '';
280
+ return this.request('GET', `/organizations/${orgId}/reports/${reportId}/download${fmt}`);
281
+ }
282
+ async quoteCredits(orgId, payload) {
283
+ return this.request('POST', `/billing/organizations/${orgId}/credit-quote`, payload);
284
+ }
285
+ async estimateRun(payload) {
286
+ return this.request('POST', '/runs/estimate', payload);
287
+ }
288
+ async estimateProject(projectId, payload) {
289
+ return this.request('POST', `/runs/projects/${projectId}/estimate`, payload);
290
+ }
291
+ async getRunEstimate(runId) {
292
+ return this.request('GET', `/runs/${runId}/estimate`);
293
+ }
294
+ async analyzeProjectFiles(projectId, perFile) {
295
+ const files = perFile
296
+ .filter((e) => e && typeof e.rel_path === 'string')
297
+ .map((e) => ({ path: e.rel_path, features: e.features }));
298
+ if (!files.length)
299
+ return [];
300
+ const data = await this.request('POST', '/analyze/project', {
301
+ project_id: projectId,
302
+ files,
303
+ });
304
+ return Array.isArray(data.findings) ? data.findings : [];
305
+ }
306
+ async getProjectFindings(projectId) {
307
+ const data = await this.request('GET', `/findings/project/${projectId}`);
308
+ return Array.isArray(data) ? data : [];
309
+ }
310
+ /**
311
+ * POST /findings/batch — optional ``declared_external_apis`` seeds the org
312
+ * external-API catalog (Python analyze twin). Findings may be empty.
313
+ */
314
+ async postFindingsBatch(findings, options) {
315
+ const payload = { findings };
316
+ if (options?.projectId != null)
317
+ payload.project_id = options.projectId;
318
+ if (options?.replaceExisting)
319
+ payload.replace_existing = true;
320
+ if (options?.scopeFilePaths != null)
321
+ payload.scope_file_paths = options.scopeFilePaths;
322
+ if (options?.declaredExternalApis?.length) {
323
+ payload.declared_external_apis = options.declaredExternalApis;
324
+ }
325
+ if (options?.detectionContext && Object.keys(options.detectionContext).length) {
326
+ payload.detection_context = options.detectionContext;
327
+ }
328
+ return this.request('POST', '/findings/batch', payload);
329
+ }
330
+ async submitFindingFeedback(findingId, payload) {
331
+ return this.request('POST', `/findings/${findingId}/feedback`, payload);
332
+ }
333
+ async getProjectDataSources(projectId) {
334
+ const data = await this.request('GET', `/projects/${projectId}/data-sources`);
335
+ return Array.isArray(data) ? data : [];
336
+ }
337
+ async createProjectDataSource(projectId, payload) {
338
+ return this.request('POST', `/projects/${projectId}/data-sources`, payload);
339
+ }
340
+ async linkProjectDataSource(projectId, sourceId, opts) {
341
+ return this.request('POST', `/projects/${projectId}/data-sources/${sourceId}/link`, { is_default: opts?.isDefault ?? false });
342
+ }
343
+ async updateDataSource(sourceId, payload) {
344
+ return this.request('PUT', `/data-sources/${sourceId}`, payload);
345
+ }
346
+ async deleteDataSource(sourceId) {
347
+ return this.request('DELETE', `/data-sources/${sourceId}`);
348
+ }
349
+ async getRunDataSources(runId) {
350
+ const data = await this.request('GET', `/runsessions/${runId}/data-sources`);
351
+ return Array.isArray(data) ? data : [];
352
+ }
353
+ async getProjectFeatureMetadata(projectId) {
354
+ return this.request('GET', `/features/project/${projectId}/feature-metadata`);
355
+ }
356
+ async postProjectFeatureMetadata(projectId, payload) {
357
+ return this.request('POST', `/features/project/${projectId}/feature-metadata`, payload);
358
+ }
359
+ async listFeatureDefinitions() {
360
+ const data = await this.request('GET', '/features/definitions');
361
+ return Array.isArray(data) ? data : [];
362
+ }
363
+ /** POST ``/optimize/function`` — shared LLM optimize brain (Python/VSCE twin). */
364
+ async optimizeFunction(payload) {
365
+ return this.request('POST', '/optimize/function', payload);
366
+ }
367
+ /** POST ``/optimize/plan`` — ranked optimization plan. */
368
+ async createOptimizationPlan(payload) {
369
+ return this.request('POST', '/optimize/plan', payload);
370
+ }
371
+ async getOptimizationPlan(planId) {
372
+ return this.request('GET', `/optimize/plan/${planId}`);
373
+ }
374
+ async listOptimizationPlans(projectId, opts) {
375
+ const limit = opts?.limit ?? 20;
376
+ const data = await this.request('GET', `/optimize/plan/project/${projectId}?limit=${limit}`);
377
+ return Array.isArray(data) ? data : [];
378
+ }
379
+ /** GET ``/developer/me/anomaly-briefs/pending`` — same brain as VSCE poll. */
380
+ async listPendingAnomalyBriefs() {
381
+ const data = await this.request('GET', '/developer/me/anomaly-briefs/pending');
382
+ return Array.isArray(data) ? data : [];
383
+ }
384
+ async getAnomalyBrief(briefId) {
385
+ return this.request('GET', `/developer/me/anomaly-briefs/${encodeURIComponent(briefId)}`);
386
+ }
387
+ async claimAnomalyBrief(briefId, opts) {
388
+ const body = opts?.claimedByDevice != null
389
+ ? { claimed_by_device: opts.claimedByDevice }
390
+ : {};
391
+ return this.request('POST', `/developer/me/anomaly-briefs/${encodeURIComponent(briefId)}/claim`, body);
392
+ }
393
+ async updateAnomalyBrief(briefId, status) {
394
+ return this.request('PATCH', `/developer/me/anomaly-briefs/${encodeURIComponent(briefId)}`, { status });
395
+ }
396
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Git remote normalization — twin of Python ``netgreener.git_context.normalize_git_url``
3
+ * / ``netgreener_sdk.git_url`` (OP1). Golden vectors:
4
+ * ``netgreener_contracts/git/canonical_git_key_vectors.v1.json``.
5
+ */
6
+ export declare function normalizeGitUrl(url: string | null | undefined): string | null;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Git remote normalization — twin of Python ``netgreener.git_context.normalize_git_url``
3
+ * / ``netgreener_sdk.git_url`` (OP1). Golden vectors:
4
+ * ``netgreener_contracts/git/canonical_git_key_vectors.v1.json``.
5
+ */
6
+ function stripGitSuffix(path) {
7
+ return path.toLowerCase().endsWith('.git') ? path.slice(0, -4) : path;
8
+ }
9
+ function adoPathSegments(path) {
10
+ const parts = [];
11
+ for (const raw of path.replace(/^\/+|\/+$/g, '').split('/')) {
12
+ if (!raw || raw.toLowerCase() === '_git')
13
+ continue;
14
+ parts.push(raw.toLowerCase());
15
+ }
16
+ return parts;
17
+ }
18
+ export function normalizeGitUrl(url) {
19
+ if (!url || !String(url).trim())
20
+ return null;
21
+ let raw = String(url).trim();
22
+ if (raw.startsWith('git@')) {
23
+ const hostPath = raw.slice(4);
24
+ const colon = hostPath.indexOf(':');
25
+ if (colon >= 0) {
26
+ const host = hostPath.slice(0, colon);
27
+ const path = hostPath.slice(colon + 1);
28
+ raw = `https://${host}/${path}`;
29
+ }
30
+ }
31
+ if (raw.startsWith('ssh://')) {
32
+ raw = `https://${raw.slice('ssh://'.length)}`;
33
+ }
34
+ raw = raw.replace(/\/+$/, '');
35
+ raw = stripGitSuffix(raw);
36
+ if (raw.startsWith('http://')) {
37
+ raw = `https://${raw.slice('http://'.length)}`;
38
+ }
39
+ let host = '';
40
+ let path = '';
41
+ try {
42
+ const parsed = new URL(raw);
43
+ host = (parsed.hostname || '').toLowerCase();
44
+ path = stripGitSuffix(parsed.pathname.replace(/^\/+|\/+$/g, ''));
45
+ }
46
+ catch {
47
+ const cleaned = raw.toLowerCase().replace('://', '/').replace(/^\/+|\/+$/g, '');
48
+ return cleaned || null;
49
+ }
50
+ if (!host) {
51
+ const cleaned = raw.toLowerCase().replace('://', '/').replace(/^\/+|\/+$/g, '');
52
+ return cleaned || null;
53
+ }
54
+ if (host === 'ssh.dev.azure.com' || host === 'vs-ssh.visualstudio.com') {
55
+ let parts = adoPathSegments(path);
56
+ if (parts[0] === 'v3')
57
+ parts = parts.slice(1);
58
+ if (parts.length >= 3) {
59
+ return `dev.azure.com/${parts[0]}/${parts[1]}/${parts[2]}`;
60
+ }
61
+ if (parts.length)
62
+ return `dev.azure.com/${parts.join('/')}`;
63
+ return null;
64
+ }
65
+ if (host.endsWith('.visualstudio.com')) {
66
+ const org = host.slice(0, -'.visualstudio.com'.length);
67
+ const parts = adoPathSegments(path);
68
+ if (org && parts.length >= 2) {
69
+ return `dev.azure.com/${org}/${parts[0]}/${parts[1]}`;
70
+ }
71
+ if (org && parts.length)
72
+ return `dev.azure.com/${org}/${parts.join('/')}`;
73
+ return null;
74
+ }
75
+ if (host === 'dev.azure.com') {
76
+ const parts = adoPathSegments(path);
77
+ if (parts.length >= 3) {
78
+ return `dev.azure.com/${parts[0]}/${parts[1]}/${parts[2]}`;
79
+ }
80
+ if (parts.length)
81
+ return `dev.azure.com/${parts.join('/')}`;
82
+ return null;
83
+ }
84
+ if (path)
85
+ return `${host}/${path.toLowerCase()}`;
86
+ return null;
87
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @netgreener/runtime/sdk — thin API client (Python netgreener_sdk twin).
3
+ */
4
+ export { ApiError, NetGreenerClient, type NetGreenerSdkOptions } from './client.js';
5
+ export { normalizeGitUrl } from './gitUrl.js';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @netgreener/runtime/sdk — thin API client (Python netgreener_sdk twin).
3
+ */
4
+ export { ApiError, NetGreenerClient } from './client.js';
5
+ export { normalizeGitUrl } from './gitUrl.js';