@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
package/dist/next.js ADDED
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Next.js App Router adapter (Wave 3 pilot).
3
+ *
4
+ * Maps into the same Runtime / observation / export path as Express.
5
+ * Not a Vercel production claim — use persistent Node or pilot wording.
6
+ * Does not change NETGREENER_EXPORT_MODE defaults.
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import { createRequire } from 'node:module';
10
+ import { getRuntime, } from './runtime.js';
11
+ import { getTenantStore, resolveTenantFromHttpRequest, normalizeTenantId, runWithTenantContext, tenantConfigFromRuntime, } from './tenantContext.js';
12
+ import { runWithRequestAttribution } from './requestContext.js';
13
+ import { beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
14
+ import { getOccupancyTracker } from './occupancyTracker.js';
15
+ import { _awaitPendingUsageParses, outboundHttpInFlight, whenOutboundHttpIdle, } from './externalApiMeter.js';
16
+ export { withNetGreener } from './nextConfig.js';
17
+ /**
18
+ * Sibling ``after()`` callbacks start in parallel with ours (Next.js p-queue).
19
+ * A short quiet window lets those callbacks start their ``fetch`` before upload.
20
+ */
21
+ let invokeFlushQuietMs = 25;
22
+ /** Test hook. ``undefined`` loads ``next/server`` ``after`` when the app provides it. */
23
+ let nextAfterOverride;
24
+ export function _setNextAfterForTests(fn) {
25
+ nextAfterOverride = fn;
26
+ }
27
+ export function _setInvokeFlushQuietMsForTests(ms) {
28
+ invokeFlushQuietMs = ms;
29
+ }
30
+ export const UNKNOWN_NEXT_ROUTE_TEMPLATE = '<unmatched>';
31
+ const MAX_ROUTE_TEMPLATE_LEN = 512;
32
+ let installedTenantResolver;
33
+ /**
34
+ * Call from ``instrumentation.ts`` ``register()`` to start the Runtime singleton.
35
+ *
36
+ * ```ts
37
+ * export async function register() {
38
+ * const { registerNetGreenerNext } = await import('@netgreener/runtime/next')
39
+ * registerNetGreenerNext()
40
+ * }
41
+ * ```
42
+ */
43
+ export function registerNetGreenerNext(opts = {}) {
44
+ const runtime = getRuntime({
45
+ collector: 'next_app_router',
46
+ framework: 'next',
47
+ ...opts,
48
+ });
49
+ if (opts.resolveTenant)
50
+ installedTenantResolver = opts.resolveTenant;
51
+ runtime.start();
52
+ if (runtime.lifecycle === 'persistent') {
53
+ const onSignal = () => {
54
+ void runtime.shutdown();
55
+ };
56
+ process.once('beforeExit', onSignal);
57
+ process.once('SIGINT', onSignal);
58
+ process.once('SIGTERM', onSignal);
59
+ }
60
+ return runtime;
61
+ }
62
+ /**
63
+ * Bounded route template for service_unit attribution.
64
+ * Never use query strings; prefer an explicit ``routeTemplate`` option.
65
+ */
66
+ export function nextRouteTemplate(req, override) {
67
+ if (typeof override === 'string') {
68
+ const t = override.trim();
69
+ if (t &&
70
+ t.length <= MAX_ROUTE_TEMPLATE_LEN &&
71
+ !t.includes('?') &&
72
+ !t.includes('#')) {
73
+ return t;
74
+ }
75
+ }
76
+ const pathname = req.nextUrl?.pathname ||
77
+ (typeof req.url === 'string' ? safePathname(req.url) : '');
78
+ const template = (pathname || '').trim();
79
+ if (!template ||
80
+ template.length > MAX_ROUTE_TEMPLATE_LEN ||
81
+ template.includes('?') ||
82
+ template.includes('#')) {
83
+ return UNKNOWN_NEXT_ROUTE_TEMPLATE;
84
+ }
85
+ return template;
86
+ }
87
+ function safePathname(url) {
88
+ try {
89
+ return new URL(url, 'http://local').pathname;
90
+ }
91
+ catch {
92
+ return url.split('?')[0] || '';
93
+ }
94
+ }
95
+ function headersAsRecord(headers) {
96
+ if (!headers)
97
+ return {};
98
+ if (typeof headers.get === 'function') {
99
+ const out = {};
100
+ headers.forEach((value, key) => {
101
+ out[key] = value;
102
+ });
103
+ return out;
104
+ }
105
+ return headers;
106
+ }
107
+ /**
108
+ * Wrap an App Router route handler (``GET``/``POST``/…) with NetGreener metering.
109
+ *
110
+ * ```ts
111
+ * export const POST = withNetGreenerRoute(async (req) => {
112
+ * return Response.json({ ok: true })
113
+ * }, { routeTemplate: '/api/intake' })
114
+ * ```
115
+ */
116
+ export function withNetGreenerRoute(handler, opts = {}) {
117
+ const runtime = getRuntime({
118
+ collector: 'next_app_router',
119
+ framework: 'next',
120
+ ...opts,
121
+ });
122
+ runtime.start();
123
+ const tenantConfig = tenantConfigFromRuntime(runtime.config);
124
+ return async function netgreenerNextHandler(req, ...args) {
125
+ if (!runtime.enabled) {
126
+ return handler(req, ...args);
127
+ }
128
+ const path = nextRouteTemplate(req, opts.routeTemplate);
129
+ const cron = opts.unitType === 'cron' || path === '/api/cron' || path.startsWith('/api/cron/');
130
+ const method = (opts.recordMethod || (cron ? 'CRON' : req?.method || 'GET')).toUpperCase();
131
+ const unitType = opts.unitType || (cron ? 'cron' : 'http_route');
132
+ const resolveServiceUnit = () => `${method} ${path}`;
133
+ const fakeHttpReq = {
134
+ method,
135
+ headers: headersAsRecord(req?.headers),
136
+ };
137
+ let entryTenant = resolveTenantFromHttpRequest(fakeHttpReq, tenantConfig);
138
+ const resolver = opts.resolveTenant ?? installedTenantResolver;
139
+ if (resolver) {
140
+ try {
141
+ const tenantId = normalizeTenantId(await resolver(req));
142
+ if (tenantId)
143
+ entryTenant = { tenantId, tenantSource: 'callback' };
144
+ }
145
+ catch {
146
+ /* fail-open: a tenant callback must not break the request */
147
+ }
148
+ }
149
+ return runWithTenantContext(entryTenant, () => runWithRequestAttribution({
150
+ resolveServiceUnit,
151
+ serviceUnit: resolveServiceUnit(),
152
+ }, async () => {
153
+ const tenantStore = getTenantStore() ?? {
154
+ current: entryTenant,
155
+ };
156
+ const started = process.hrtime.bigint();
157
+ const resourceMark = beginProcessResourceSample();
158
+ const requestId = randomUUID();
159
+ getOccupancyTracker().begin(requestId);
160
+ runtime.beginRequest();
161
+ let statusCode = 200;
162
+ try {
163
+ const result = await handler(req, ...args);
164
+ statusCode = statusFromResult(result);
165
+ return result;
166
+ }
167
+ catch (err) {
168
+ statusCode = 500;
169
+ throw err;
170
+ }
171
+ finally {
172
+ const ended = process.hrtime.bigint();
173
+ const durationMs = Number(ended - started) / 1e6;
174
+ const resources = endProcessResourceSample(resourceMark);
175
+ const serviceUnit = resolveServiceUnit();
176
+ getOccupancyTracker().end(requestId, serviceUnit);
177
+ runWithTenantContext(tenantStore.current, () => {
178
+ runtime.recordHttp({
179
+ method,
180
+ path,
181
+ statusCode,
182
+ durationMs,
183
+ unitType,
184
+ cpuTimeMs: resources.cpuTimeMs,
185
+ peakRssKb: resources.rssKb,
186
+ });
187
+ });
188
+ runtime.endRequest({
189
+ deferInvokeFlush: runtime.lifecycle === 'ephemeral',
190
+ });
191
+ if (runtime.lifecycle === 'ephemeral') {
192
+ scheduleEphemeralInvokeFlush(runtime, readWaitUntil(req));
193
+ }
194
+ }
195
+ }));
196
+ };
197
+ }
198
+ /**
199
+ * Loader target for an App Router route handler.
200
+ * ``cron: true`` records the service unit as ``CRON <template>``.
201
+ */
202
+ export function observeNextRoute(handler, _method, routeTemplate, opts) {
203
+ return withNetGreenerRoute(handler, {
204
+ routeTemplate,
205
+ unitType: opts?.cron ? 'cron' : 'http_route',
206
+ recordMethod: opts?.cron ? 'CRON' : undefined,
207
+ });
208
+ }
209
+ /** Loader target for a server page. */
210
+ export function observeNextPage(component, routeTemplate) {
211
+ return withNetGreenerRoute(((props) => component(props)), { routeTemplate, unitType: 'page', recordMethod: 'GET' });
212
+ }
213
+ /** Loader target for a `'use server'` export. */
214
+ export function observeNextAction(action, name, routeTemplate) {
215
+ const template = `${routeTemplate}#${name}`.slice(0, 512);
216
+ return withNetGreenerRoute(action, {
217
+ routeTemplate: template,
218
+ unitType: 'action',
219
+ recordMethod: 'ACTION',
220
+ });
221
+ }
222
+ function statusFromResult(result) {
223
+ if (result &&
224
+ typeof result === 'object' &&
225
+ 'status' in result &&
226
+ typeof result.status === 'number') {
227
+ return result.status;
228
+ }
229
+ return 200;
230
+ }
231
+ export function getNextRuntime() {
232
+ return getRuntime({ collector: 'next_app_router', framework: 'next' });
233
+ }
234
+ /** Explicit flush helper for instrumentation ``onRequestError`` / custom hooks. */
235
+ export async function flushNetGreenerNext(kind = 'manual') {
236
+ const runtime = getNextRuntime();
237
+ if (kind === 'shutdown')
238
+ return runtime.shutdown();
239
+ if (kind === 'invoke_end')
240
+ return runtime.flushForInvokeEnd();
241
+ return runtime.flush(kind);
242
+ }
243
+ /**
244
+ * Schedule a best-effort flush after the response (Vercel ``waitUntil`` when present).
245
+ * Fail-open: never throws into the customer path.
246
+ *
247
+ * Prefers Next.js ``after()``, which runs once the response (including a stream)
248
+ * has closed and is already passed to platform ``waitUntil``.
249
+ */
250
+ export function scheduleNetGreenerFlush(waitUntil) {
251
+ scheduleEphemeralInvokeFlush(getNextRuntime(), waitUntil);
252
+ }
253
+ function readWaitUntil(req) {
254
+ const maybe = req.waitUntil;
255
+ return typeof maybe === 'function' ? maybe : undefined;
256
+ }
257
+ const requireFromHere = createRequire(import.meta.url);
258
+ let cachedNextAfter;
259
+ function scheduleEphemeralInvokeFlush(runtime, waitUntil) {
260
+ // Start the upload only when Next runs the callback. ``after(promise)`` does
261
+ // not wait for the response to close; ``after(fn)`` does.
262
+ const start = () => finishEphemeralInvoke(runtime);
263
+ if (scheduleWithNextAfter(start))
264
+ return;
265
+ const work = start();
266
+ if (typeof waitUntil === 'function') {
267
+ try {
268
+ waitUntil(work);
269
+ return;
270
+ }
271
+ catch {
272
+ /* fall through; the promise is already running */
273
+ }
274
+ }
275
+ void work;
276
+ }
277
+ function scheduleWithNextAfter(start) {
278
+ const afterFn = resolveNextAfter();
279
+ if (!afterFn)
280
+ return false;
281
+ try {
282
+ afterFn(() => start());
283
+ return true;
284
+ }
285
+ catch {
286
+ return false;
287
+ }
288
+ }
289
+ function resolveNextAfter() {
290
+ if (nextAfterOverride !== undefined)
291
+ return nextAfterOverride;
292
+ if (cachedNextAfter !== undefined)
293
+ return cachedNextAfter;
294
+ try {
295
+ const mod = requireFromHere('next/server');
296
+ cachedNextAfter = typeof mod.after === 'function' ? mod.after : null;
297
+ }
298
+ catch {
299
+ cachedNextAfter = null;
300
+ }
301
+ return cachedNextAfter;
302
+ }
303
+ async function finishEphemeralInvoke(runtime) {
304
+ try {
305
+ await waitForOutboundQuiet();
306
+ await _awaitPendingUsageParses();
307
+ await runtime.flushForInvokeEnd();
308
+ }
309
+ catch {
310
+ /* fail-open: metering must not break the customer response */
311
+ }
312
+ }
313
+ async function waitForOutboundQuiet() {
314
+ await delay(0);
315
+ for (;;) {
316
+ if (outboundHttpInFlight() === 0) {
317
+ await delay(invokeFlushQuietMs);
318
+ if (outboundHttpInFlight() === 0)
319
+ return;
320
+ }
321
+ await whenOutboundHttpIdle();
322
+ }
323
+ }
324
+ function delay(ms) {
325
+ return new Promise((resolve) => {
326
+ setTimeout(resolve, ms);
327
+ });
328
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Public Next.js config wrapper. Registers the entry loader on the Node
3
+ * server build (webpack and Turbopack). Does not change export mode.
4
+ */
5
+ export type NextConfigLike = {
6
+ webpack?: (config: WebpackConfigLike, options: WebpackOptionsLike) => WebpackConfigLike;
7
+ turbopack?: {
8
+ rules?: Record<string, unknown>;
9
+ [key: string]: unknown;
10
+ };
11
+ [key: string]: unknown;
12
+ };
13
+ type WebpackConfigLike = {
14
+ module?: {
15
+ rules?: unknown[];
16
+ };
17
+ [key: string]: unknown;
18
+ };
19
+ type WebpackOptionsLike = {
20
+ isServer?: boolean;
21
+ nextRuntime?: string;
22
+ };
23
+ /**
24
+ * Wrap an existing Next config so Node route, page, and server-action modules
25
+ * are observed. Compose outside other config wrappers:
26
+ *
27
+ * ```ts
28
+ * export default withNextIntl(withNetGreener(nextConfig))
29
+ * ```
30
+ *
31
+ * Also call ``registerNetGreenerNext`` from ``instrumentation.ts``.
32
+ */
33
+ export declare function withNetGreener<T extends NextConfigLike>(nextConfig?: T): T;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Public Next.js config wrapper. Registers the entry loader on the Node
3
+ * server build (webpack and Turbopack). Does not change export mode.
4
+ */
5
+ import { fileURLToPath } from 'node:url';
6
+ const ENTRY_GLOBS = [
7
+ '**/route.ts',
8
+ '**/route.tsx',
9
+ '**/route.js',
10
+ '**/route.jsx',
11
+ '**/page.ts',
12
+ '**/page.tsx',
13
+ '**/page.js',
14
+ '**/page.jsx',
15
+ '**/*action.ts',
16
+ '**/*action.tsx',
17
+ '**/*actions.ts',
18
+ '**/*actions.tsx',
19
+ ];
20
+ function loaderFile() {
21
+ return fileURLToPath(new URL('../loaders/next-entry-loader.cjs', import.meta.url));
22
+ }
23
+ function turbopackRule(loader) {
24
+ return {
25
+ loaders: [loader],
26
+ condition: {
27
+ all: ['node', { not: 'browser' }, { not: 'edge-light' }],
28
+ },
29
+ };
30
+ }
31
+ /**
32
+ * Wrap an existing Next config so Node route, page, and server-action modules
33
+ * are observed. Compose outside other config wrappers:
34
+ *
35
+ * ```ts
36
+ * export default withNextIntl(withNetGreener(nextConfig))
37
+ * ```
38
+ *
39
+ * Also call ``registerNetGreenerNext`` from ``instrumentation.ts``.
40
+ */
41
+ export function withNetGreener(nextConfig = {}) {
42
+ const loader = loaderFile();
43
+ const prevTurbo = nextConfig.turbopack ?? {};
44
+ const prevRules = (prevTurbo.rules ?? {});
45
+ const rules = { ...prevRules };
46
+ for (const glob of ENTRY_GLOBS) {
47
+ if (rules[glob] == null)
48
+ rules[glob] = turbopackRule(loader);
49
+ }
50
+ const prevWebpack = nextConfig.webpack;
51
+ return {
52
+ ...nextConfig,
53
+ turbopack: {
54
+ ...prevTurbo,
55
+ rules,
56
+ },
57
+ webpack(config, options) {
58
+ const serverNode = options.isServer === true && options.nextRuntime !== 'edge';
59
+ if (serverNode) {
60
+ config.module = config.module ?? {};
61
+ config.module.rules = config.module.rules ?? [];
62
+ config.module.rules.push({
63
+ test: /([\\/](route|page)\.(tsx?|jsx?)$)|([\\/][^\\/]*actions?\.(tsx?|jsx?)$)/,
64
+ enforce: 'pre',
65
+ use: [loader],
66
+ });
67
+ }
68
+ if (typeof prevWebpack === 'function')
69
+ return prevWebpack(config, options);
70
+ return config;
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Source transform for the Next.js config wrapper.
3
+ *
4
+ * Turns route, page, and `'use server'` exports into calls to the public
5
+ * runtime helpers. Does not read Next.js internals. Client modules are left
6
+ * unchanged so the server runtime is not pulled into the browser bundle.
7
+ */
8
+ export declare function routeTemplateFromAppFile(filePath: string): string;
9
+ export declare function transformNextEntrySource(source: string, filePath: string): string;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Source transform for the Next.js config wrapper.
3
+ *
4
+ * Turns route, page, and `'use server'` exports into calls to the public
5
+ * runtime helpers. Does not read Next.js internals. Client modules are left
6
+ * unchanged so the server runtime is not pulled into the browser bundle.
7
+ */
8
+ const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
9
+ const IMPORT_LINE = "import { observeNextAction as __ngObserveAction, observeNextPage as __ngObservePage, observeNextRoute as __ngObserveRoute } from '@netgreener/runtime/next'\n";
10
+ export function routeTemplateFromAppFile(filePath) {
11
+ const norm = filePath.replace(/\\/g, '/');
12
+ const marker = '/app/';
13
+ const idx = norm.lastIndexOf(marker);
14
+ if (idx < 0) {
15
+ const base = norm.split('/').pop() || 'module';
16
+ return `/${base.replace(/\.(tsx?|jsx?)$/, '')}`;
17
+ }
18
+ let rel = norm.slice(idx + marker.length - 1);
19
+ rel = rel.replace(/\/(route|page)\.(tsx?|jsx?)$/, '');
20
+ rel = rel.replace(/\/\([^/]+\)/g, '');
21
+ if (!rel.startsWith('/'))
22
+ rel = `/${rel}`;
23
+ if (rel.length > 1)
24
+ rel = rel.replace(/\/+$/, '');
25
+ return rel || '/';
26
+ }
27
+ export function transformNextEntrySource(source, filePath) {
28
+ if (isClientModule(source))
29
+ return source;
30
+ if (source.includes('__ngObserveRoute') || source.includes('withNetGreenerRoute')) {
31
+ return source;
32
+ }
33
+ const norm = filePath.replace(/\\/g, '/');
34
+ const isRoute = /\/route\.(tsx?|jsx?)$/.test(norm);
35
+ const isPage = /\/page\.(tsx?|jsx?)$/.test(norm);
36
+ const isAction = isServerActionModule(source);
37
+ if (!isRoute && !isPage && !isAction)
38
+ return source;
39
+ const template = routeTemplateFromAppFile(filePath);
40
+ let next = source;
41
+ const tails = [];
42
+ if (isRoute) {
43
+ const cron = template === '/api/cron' || template.startsWith('/api/cron/');
44
+ for (const method of HTTP_METHODS) {
45
+ const wrapped = wrapHttpExport(next, method, template, cron);
46
+ if (!wrapped)
47
+ continue;
48
+ next = wrapped.code;
49
+ tails.push(wrapped.tail);
50
+ }
51
+ }
52
+ if (isPage) {
53
+ const wrapped = wrapDefaultPage(next, template);
54
+ if (wrapped) {
55
+ next = wrapped.code;
56
+ tails.push(wrapped.tail);
57
+ }
58
+ }
59
+ if (isAction && !isRoute && !isPage) {
60
+ const wrapped = wrapServerActions(next, template);
61
+ next = wrapped.code;
62
+ tails.push(...wrapped.tails);
63
+ }
64
+ if (!tails.length)
65
+ return source;
66
+ return `${insertImport(next)}\n${tails.join('\n')}\n`;
67
+ }
68
+ function insertImport(source) {
69
+ const directive = /^(\uFEFF?\s*['"]use server['"]\s*;?\s*)/;
70
+ const match = directive.exec(source);
71
+ if (!match)
72
+ return `${IMPORT_LINE}${source}`;
73
+ return `${source.slice(0, match[0].length)}${IMPORT_LINE}${source.slice(match[0].length)}`;
74
+ }
75
+ function isClientModule(source) {
76
+ return /^\uFEFF?\s*['"]use client['"]/.test(source);
77
+ }
78
+ function isServerActionModule(source) {
79
+ return /^\uFEFF?\s*['"]use server['"]/.test(source);
80
+ }
81
+ function jsString(value) {
82
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
83
+ }
84
+ function wrapHttpExport(source, method, template, cron) {
85
+ const fn = new RegExp(`export\\s+(async\\s+)?function\\s+${method}\\b`);
86
+ const fnMatch = fn.exec(source);
87
+ if (fnMatch) {
88
+ const code = source.replace(fn, `${fnMatch[1] || ''}function __ng_${method}`);
89
+ const tail = `export const ${method} = __ngObserveRoute(__ng_${method}, ${jsString(method)}, ${jsString(template)}, { cron: ${cron ? 'true' : 'false'} })`;
90
+ return { code, tail };
91
+ }
92
+ const decl = new RegExp(`export\\s+const\\s+${method}\\s*=\\s*`);
93
+ const declMatch = decl.exec(source);
94
+ if (!declMatch || declMatch.index === undefined)
95
+ return null;
96
+ const exprStart = declMatch.index + declMatch[0].length;
97
+ const exprEnd = endOfAssignment(source, exprStart);
98
+ const expr = source.slice(exprStart, exprEnd).replace(/;\s*$/, '');
99
+ const code = source.slice(0, declMatch.index) +
100
+ `const __ng_${method} = ${expr}\n` +
101
+ source.slice(exprEnd);
102
+ const tail = `export const ${method} = __ngObserveRoute(__ng_${method}, ${jsString(method)}, ${jsString(template)}, { cron: ${cron ? 'true' : 'false'} })`;
103
+ return { code, tail };
104
+ }
105
+ function wrapDefaultPage(source, template) {
106
+ const fn = /export\s+default\s+(async\s+)?function\s+([A-Za-z0-9_]+)\b/;
107
+ const fnMatch = fn.exec(source);
108
+ if (fnMatch) {
109
+ const code = source.replace(fn, `${fnMatch[1] || ''}function ${fnMatch[2]}`);
110
+ return {
111
+ code,
112
+ tail: `export default __ngObservePage(${fnMatch[2]}, ${jsString(template)})`,
113
+ };
114
+ }
115
+ const ident = /export\s+default\s+([A-Za-z0-9_]+)\s*;?/;
116
+ const identMatch = ident.exec(source);
117
+ if (!identMatch)
118
+ return null;
119
+ const code = source.replace(ident, '');
120
+ return {
121
+ code,
122
+ tail: `export default __ngObservePage(${identMatch[1]}, ${jsString(template)})`,
123
+ };
124
+ }
125
+ function wrapServerActions(source, template) {
126
+ let code = source;
127
+ const tails = [];
128
+ const fn = /export\s+(async\s+)?function\s+([A-Za-z0-9_]+)\b/g;
129
+ const names = [];
130
+ for (const match of code.matchAll(fn)) {
131
+ const name = match[2];
132
+ if (!name || HTTP_METHODS.includes(name))
133
+ continue;
134
+ names.push({ name, asyncKw: match[1] || '' });
135
+ }
136
+ for (const { name, asyncKw } of names) {
137
+ const one = new RegExp(`export\\s+(async\\s+)?function\\s+${name}\\b`);
138
+ if (!one.test(code))
139
+ continue;
140
+ code = code.replace(one, `${asyncKw}function __ng_action_${name}`);
141
+ tails.push(`export const ${name} = __ngObserveAction(__ng_action_${name}, ${jsString(name)}, ${jsString(template)})`);
142
+ }
143
+ return { code, tails };
144
+ }
145
+ function endOfAssignment(source, exprStart) {
146
+ let i = exprStart;
147
+ let depth = 0;
148
+ let quote = null;
149
+ while (i < source.length) {
150
+ const c = source[i];
151
+ if (quote) {
152
+ if (c === '\\') {
153
+ i += 2;
154
+ continue;
155
+ }
156
+ if (c === quote)
157
+ quote = null;
158
+ i += 1;
159
+ continue;
160
+ }
161
+ if (c === '"' || c === "'" || c === '`') {
162
+ quote = c;
163
+ i += 1;
164
+ continue;
165
+ }
166
+ if (c === '(' || c === '[' || c === '{') {
167
+ depth += 1;
168
+ i += 1;
169
+ continue;
170
+ }
171
+ if (c === ')' || c === ']' || c === '}') {
172
+ depth = Math.max(0, depth - 1);
173
+ i += 1;
174
+ continue;
175
+ }
176
+ if (depth === 0 && (c === ';' || c === '\n'))
177
+ return i;
178
+ i += 1;
179
+ }
180
+ return source.length;
181
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Concurrency-normalized request occupancy (Python OccupancyTracker twin).
3
+ *
4
+ * Accrues ``dt / N`` to each active request id while N > 0. On end, share moves
5
+ * to the service unit. Window snapshots leave in-flight as unattributed.
6
+ * Additive for anomaly evidence — does not change EXPORT_MODE.
7
+ */
8
+ export type OccupancyWindowSnapshot = {
9
+ by_unit: Record<string, number>;
10
+ in_flight_seconds: number;
11
+ idle_seconds: number;
12
+ };
13
+ export declare class OccupancyTracker {
14
+ private activeIds;
15
+ private occById;
16
+ private occByUnit;
17
+ private idleSeconds;
18
+ private lastMono;
19
+ begin(requestId: string): void;
20
+ end(requestId: string, serviceUnit: string): void;
21
+ private accrue;
22
+ /** Snapshot closed-window occupancy; keep in-flight ids active with zeroed accrual. */
23
+ takeWindowSnapshot(): OccupancyWindowSnapshot;
24
+ }
25
+ export declare function getOccupancyTracker(): OccupancyTracker;
26
+ /** Test helper — swap in a fresh tracker. */
27
+ export declare function _resetOccupancyTrackerForTests(): void;