@rasputin-ai/core 0.13.0 → 0.14.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.
Files changed (70) hide show
  1. package/dist/announce-deploy/announce-deploy.d.ts +2 -1
  2. package/dist/announce-deploy/announce-deploy.d.ts.map +1 -1
  3. package/dist/create-client/create-client-types.d.ts +4 -4
  4. package/dist/create-client/create-client-types.d.ts.map +1 -1
  5. package/dist/create-client/create-client.d.ts.map +1 -1
  6. package/dist/create-client/is-client-enabled.d.ts +3 -0
  7. package/dist/create-client/is-client-enabled.d.ts.map +1 -1
  8. package/dist/create-client/resolve-endpoint-urls.d.ts +2 -0
  9. package/dist/create-client/resolve-endpoint-urls.d.ts.map +1 -1
  10. package/dist/create-ingest-event/create-ingest-event-types.d.ts +3 -2
  11. package/dist/create-ingest-event/create-ingest-event-types.d.ts.map +1 -1
  12. package/dist/create-ingest-event/runtime-execution-state-types.d.ts +3 -2
  13. package/dist/create-ingest-event/runtime-execution-state-types.d.ts.map +1 -1
  14. package/dist/derivation/hash-instrumentation-manifest.d.ts.map +1 -1
  15. package/dist/environment.d.ts +3 -0
  16. package/dist/environment.d.ts.map +1 -0
  17. package/dist/execution-metrics/execution-metrics-config.d.ts +5 -0
  18. package/dist/execution-metrics/execution-metrics-config.d.ts.map +1 -0
  19. package/dist/execution-metrics/execution-metrics-schema-version.d.ts +2 -0
  20. package/dist/execution-metrics/execution-metrics-schema-version.d.ts.map +1 -0
  21. package/dist/execution-metrics/execution-metrics-wire.d.ts +45 -0
  22. package/dist/execution-metrics/execution-metrics-wire.d.ts.map +1 -0
  23. package/dist/function-metrics/function-identity.d.ts +46 -0
  24. package/dist/function-metrics/function-identity.d.ts.map +1 -0
  25. package/dist/function-metrics/function-metrics-batch.d.ts +18 -0
  26. package/dist/function-metrics/function-metrics-batch.d.ts.map +1 -0
  27. package/dist/function-metrics/function-metrics-bucket.d.ts +3 -0
  28. package/dist/function-metrics/function-metrics-bucket.d.ts.map +1 -0
  29. package/dist/function-metrics/function-metrics-coalesce.d.ts +10 -0
  30. package/dist/function-metrics/function-metrics-coalesce.d.ts.map +1 -0
  31. package/dist/function-metrics/function-metrics-config.d.ts +5 -0
  32. package/dist/function-metrics/function-metrics-config.d.ts.map +1 -0
  33. package/dist/function-metrics/function-metrics-execution-key.d.ts +6 -0
  34. package/dist/function-metrics/function-metrics-execution-key.d.ts.map +1 -0
  35. package/dist/function-metrics/function-metrics-histogram.d.ts +4 -0
  36. package/dist/function-metrics/function-metrics-histogram.d.ts.map +1 -0
  37. package/dist/function-metrics/function-metrics-issues.d.ts +13 -0
  38. package/dist/function-metrics/function-metrics-issues.d.ts.map +1 -0
  39. package/dist/function-metrics/function-metrics-limits.d.ts +35 -0
  40. package/dist/function-metrics/function-metrics-limits.d.ts.map +1 -0
  41. package/dist/function-metrics/function-metrics-minute.d.ts +5 -0
  42. package/dist/function-metrics/function-metrics-minute.d.ts.map +1 -0
  43. package/dist/function-metrics/function-metrics-parse.d.ts +8 -0
  44. package/dist/function-metrics/function-metrics-parse.d.ts.map +1 -0
  45. package/dist/function-metrics/function-metrics-read-batch.d.ts +8 -0
  46. package/dist/function-metrics/function-metrics-read-batch.d.ts.map +1 -0
  47. package/dist/function-metrics/function-metrics-trace-declaration.d.ts +9 -0
  48. package/dist/function-metrics/function-metrics-trace-declaration.d.ts.map +1 -0
  49. package/dist/function-metrics/function-metrics-wire.d.ts +74 -0
  50. package/dist/function-metrics/function-metrics-wire.d.ts.map +1 -0
  51. package/dist/generic/is-record.d.ts +2 -0
  52. package/dist/generic/is-record.d.ts.map +1 -0
  53. package/dist/generic/sha256-hex.d.ts +2 -0
  54. package/dist/generic/sha256-hex.d.ts.map +1 -0
  55. package/dist/index.d.ts +20 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +1085 -15
  58. package/dist/instrumentation-manifest/instrumentation-manifest-types.d.ts +3 -0
  59. package/dist/instrumentation-manifest/instrumentation-manifest-types.d.ts.map +1 -1
  60. package/dist/sdk-meta.d.ts +1 -1
  61. package/dist/suppression/create-suppression.d.ts.map +1 -1
  62. package/dist/suppression/suppression-types.d.ts +3 -2
  63. package/dist/suppression/suppression-types.d.ts.map +1 -1
  64. package/dist/transport/encode-json-request-body.d.ts.map +1 -1
  65. package/dist/transport/node-http-fetch.d.ts.map +1 -1
  66. package/dist/type-values.d.ts +5 -0
  67. package/dist/type-values.d.ts.map +1 -0
  68. package/package.json +1 -1
  69. package/dist/derivation/sha256.d.ts +0 -2
  70. package/dist/derivation/sha256.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -72,10 +72,11 @@ var tryParseHttpResponse = (raw, connectionClosed) => {
72
72
  if (colon < 0) continue;
73
73
  headers.append(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
74
74
  }
75
+ const statusCode = Number(status[1]);
75
76
  const body = raw.subarray(split + 4);
76
77
  if (headers.get("transfer-encoding")?.toLowerCase().includes("chunked")) {
77
78
  const decoded = tryDecodeChunked(body);
78
- return decoded === null ? null : new Response(toResponseBody(decoded), { status: Number(status[1]), headers });
79
+ return decoded === null ? null : new Response(toResponseBody(decoded), { status: statusCode, headers });
79
80
  }
80
81
  const lengthHeader = headers.get("content-length");
81
82
  if (lengthHeader !== null) {
@@ -83,11 +84,14 @@ var tryParseHttpResponse = (raw, connectionClosed) => {
83
84
  if (!Number.isInteger(length) || length < 0) throw new Error("invalid content-length");
84
85
  if (body.length < length) return null;
85
86
  return new Response(toResponseBody(body.subarray(0, length)), {
86
- status: Number(status[1]),
87
+ status: statusCode,
87
88
  headers
88
89
  });
89
90
  }
90
- return connectionClosed ? new Response(toResponseBody(body), { status: Number(status[1]), headers }) : null;
91
+ if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode < 200) {
92
+ return new Response(null, { status: statusCode, headers });
93
+ }
94
+ return connectionClosed ? new Response(toResponseBody(body), { status: statusCode, headers }) : null;
91
95
  };
92
96
  var defaultIngestFetch = () => (input, init) => new Promise((resolve4, reject) => {
93
97
  let parsed;
@@ -192,8 +196,7 @@ var announceDeploy = async (options) => {
192
196
  try {
193
197
  if (options.enabled === false) return "skipped";
194
198
  const release = trimmedString(options.release);
195
- const environment = trimmedString(options.environment);
196
- if (!environment) return "skipped";
199
+ const environment = options.environment;
197
200
  const fetchFn = options.fetch ?? defaultIngestFetch();
198
201
  const timeout = new AbortController();
199
202
  const timer = setTimeout(() => timeout.abort(), 5e3);
@@ -899,7 +902,7 @@ var resolveSourceMaps = async (frames) => {
899
902
 
900
903
  // src/sdk-meta.ts
901
904
  var SDK_NAME = "@rasputin-ai/core";
902
- var SDK_VERSION = "0.13.0";
905
+ var SDK_VERSION = "0.14.0";
903
906
 
904
907
  // src/suppression/parameterize-message.ts
905
908
  var MAX_INPUT_LENGTH = 8192;
@@ -1331,6 +1334,7 @@ var gzipAsyncPayload = (raw, gzipLevel, signal) => new Promise((resolve4, reject
1331
1334
  };
1332
1335
  const onAbort = () => finish(abortError2());
1333
1336
  signal?.addEventListener("abort", onAbort, { once: true });
1337
+ if (signal?.aborted) onAbort();
1334
1338
  const options = gzipOptions(gzipLevel);
1335
1339
  if (options) gzip(raw, options, finish);
1336
1340
  else gzip(raw, finish);
@@ -2030,6 +2034,9 @@ var createTransport = (options) => {
2030
2034
  };
2031
2035
  };
2032
2036
 
2037
+ // src/environment.ts
2038
+ var isRasputinEnvironment = (value) => value === "local" || value === "staging" || value === "production";
2039
+
2033
2040
  // src/parse-release-sha.ts
2034
2041
  var SHA_RE = /^[0-9a-f]{7,40}$/i;
2035
2042
  var parseReleaseSha = (release) => {
@@ -2074,13 +2081,15 @@ var resolveClientActivation = (options) => {
2074
2081
  if (!projectApiKey) return { enabled: false };
2075
2082
  const release = parseReleaseSha(options.release);
2076
2083
  if (!release) return { enabled: false };
2084
+ if (!isRasputinEnvironment(options.environment)) return { enabled: false };
2077
2085
  const apiUrl = typeof options.apiUrl === "string" ? options.apiUrl.trim() : "";
2078
2086
  return {
2079
2087
  enabled: true,
2080
2088
  ingestToken: parsed.publicKey,
2081
2089
  projectApiKey,
2082
2090
  apiUrl: apiUrl || parsed.apiUrl,
2083
- release
2091
+ release,
2092
+ environment: options.environment
2084
2093
  };
2085
2094
  };
2086
2095
  var isClientEnabled = (options) => resolveClientActivation(options).enabled;
@@ -2126,7 +2135,9 @@ var resolveEndpointUrls = (apiUrl = DEFAULT_API_URL) => {
2126
2135
  instrumentationManifestUrl: `${base}/instrumentationManifest`,
2127
2136
  executionRecordingActivateUrl: `${base}/ingest/executionRecording/activate`,
2128
2137
  executionRecordingSyncUrl: `${base}/ingest/executionRecording/sync`,
2129
- executionRecordingRecordingsUrl: `${base}/ingest/executionRecording/recordings`
2138
+ executionRecordingRecordingsUrl: `${base}/ingest/executionRecording/recordings`,
2139
+ functionMetricsUrl: `${base}/ingest/functionMetrics`,
2140
+ executionMetricsUrl: `${base}/ingest/executionMetrics`
2130
2141
  };
2131
2142
  };
2132
2143
 
@@ -2229,8 +2240,7 @@ var createClient = (options, hooks = {}) => {
2229
2240
  try {
2230
2241
  const activation = resolveClientActivation(options);
2231
2242
  if (!activation.enabled) return noopClient();
2232
- const { ingestToken, projectApiKey, apiUrl, release } = activation;
2233
- const environment = options.environment;
2243
+ const { ingestToken, projectApiKey, apiUrl, release, environment } = activation;
2234
2244
  const { ingestUrl, deployUrl } = resolveEndpointUrls(apiUrl);
2235
2245
  const repoRoot = resolveRepoRoot(options);
2236
2246
  if (repoRoot) warnIfSuspiciousRepoRoot(repoRoot);
@@ -2392,6 +2402,10 @@ var copyRedactKeys = (keys) => {
2392
2402
  return copied.length > 0 ? copied : void 0;
2393
2403
  };
2394
2404
 
2405
+ // src/generic/sha256-hex.ts
2406
+ import { createHash as createHash2 } from "node:crypto";
2407
+ var sha256Hex = (input) => createHash2("sha256").update(input).digest("hex");
2408
+
2395
2409
  // src/derivation/canonical-json.ts
2396
2410
  var sortedKeys = (value) => Object.keys(value).sort();
2397
2411
  var canonicalJson = (value) => {
@@ -2421,10 +2435,6 @@ var canonicalJson = (value) => {
2421
2435
  return "null";
2422
2436
  };
2423
2437
 
2424
- // src/derivation/sha256.ts
2425
- import { createHash as createHash2 } from "node:crypto";
2426
- var sha256Hex = (input) => createHash2("sha256").update(input).digest("hex");
2427
-
2428
2438
  // src/derivation/hash-instrumentation-manifest.ts
2429
2439
  var hashCache = /* @__PURE__ */ new WeakMap();
2430
2440
  var hashableSource = (source) => {
@@ -2530,6 +2540,1023 @@ var propertyNameIsSensitive = (key) => {
2530
2540
  return false;
2531
2541
  };
2532
2542
 
2543
+ // src/execution-metrics/execution-metrics-schema-version.ts
2544
+ var EXECUTION_METRICS_SCHEMA_VERSION = 1;
2545
+
2546
+ // src/generic/is-record.ts
2547
+ var isRecord = (value) => {
2548
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2549
+ return false;
2550
+ }
2551
+ const prototype = Object.getPrototypeOf(value);
2552
+ return prototype === Object.prototype || prototype === null;
2553
+ };
2554
+
2555
+ // src/type-values.ts
2556
+ var fieldNames = (fields) => Object.keys(fields);
2557
+ var valuesOf = () => (values) => values;
2558
+
2559
+ // src/function-metrics/function-metrics-issues.ts
2560
+ var FUNCTION_METRICS_ISSUE_LIMIT = 32;
2561
+ var createFunctionMetricsIssues = () => {
2562
+ const items = [];
2563
+ return {
2564
+ items,
2565
+ add: (code, path) => {
2566
+ if (items.length < FUNCTION_METRICS_ISSUE_LIMIT) items.push({ code, path });
2567
+ }
2568
+ };
2569
+ };
2570
+
2571
+ // src/function-metrics/function-metrics-limits.ts
2572
+ var FUNCTION_METRICS_SCHEMA_VERSION = 1;
2573
+ var FUNCTION_IDENTITY_VERSION = 1;
2574
+ var FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT = 295;
2575
+ var FUNCTION_METRICS_HISTOGRAM_FINITE_BOUNDS = 293;
2576
+ var FUNCTION_METRICS_MAX_DECODED_BYTES = 2 * 1024 * 1024;
2577
+ var FUNCTION_METRICS_MAX_FUNCTIONS = 512;
2578
+ var FUNCTION_METRICS_MAX_EXECUTION_TYPES = 64;
2579
+ var FUNCTION_METRICS_MAX_MINUTE_ROWS = 2048;
2580
+ var FUNCTION_METRICS_MAX_COVERED_BUCKETS = 10;
2581
+ var FUNCTION_METRICS_MAX_ACTIVE_SERIES = 4096;
2582
+ var FUNCTION_METRICS_MAX_STATE_BYTES = 16 * 1024 * 1024;
2583
+ var FUNCTION_METRICS_MAX_BUFFERED_MS = 10 * 6e4;
2584
+ var FUNCTION_METRICS_MINUTE_MS = 6e4;
2585
+ var FUNCTION_METRICS_BUCKET_LATENESS_MS = 10 * 6e4;
2586
+ var FUNCTION_METRICS_FUTURE_SKEW_MS = 6e4;
2587
+ var FUNCTION_METRICS_MAX_PATH_LENGTH = 512;
2588
+ var FUNCTION_METRICS_MAX_BINDING_LENGTH = 256;
2589
+ var FUNCTION_METRICS_MAX_SCOPES = 32;
2590
+ var FUNCTION_METRICS_MAX_PACKAGE_NAME_LENGTH = 214;
2591
+ var FUNCTION_METRICS_MAX_RUNTIME_ID_LENGTH = 128;
2592
+ var FUNCTION_METRICS_MAX_SOURCE_POSITION = 1e6;
2593
+ var FUNCTION_METRICS_MAX_EXECUTION_KEY_LENGTH = 256;
2594
+ var FUNCTION_METRICS_MEASUREMENT_FORMAT = "timing_full_v1";
2595
+ var FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT = "timing_sampled_v1";
2596
+ var FUNCTION_METRICS_MEASUREMENT_FORMATS = [
2597
+ FUNCTION_METRICS_MEASUREMENT_FORMAT,
2598
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT
2599
+ ];
2600
+ var isFunctionMetricsMeasurementFormat = (value) => value === FUNCTION_METRICS_MEASUREMENT_FORMAT || value === FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT;
2601
+
2602
+ // src/function-metrics/function-metrics-parse.ts
2603
+ var isMember = (values, value) => typeof value === "string" && values.some((candidate) => candidate === value);
2604
+ var exactKeys = (value, keys, path, issues) => {
2605
+ let ok = true;
2606
+ const present = new Set(Object.keys(value));
2607
+ for (const key of keys) {
2608
+ if (!present.has(key)) {
2609
+ issues.add("missing_field", `${path}.${key}`);
2610
+ ok = false;
2611
+ }
2612
+ }
2613
+ for (const key of present) {
2614
+ if (!keys.includes(key)) {
2615
+ issues.add("unknown_field", `${path}.${key}`);
2616
+ ok = false;
2617
+ }
2618
+ }
2619
+ return ok;
2620
+ };
2621
+ var readCount = (value, path, issues) => {
2622
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
2623
+ issues.add("invalid_count", path);
2624
+ return void 0;
2625
+ }
2626
+ return value;
2627
+ };
2628
+ var readDuration = (value, path, issues) => {
2629
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {
2630
+ issues.add("invalid_duration", path);
2631
+ return void 0;
2632
+ }
2633
+ return value;
2634
+ };
2635
+ var addCount = (left, right) => {
2636
+ const sum = left + right;
2637
+ return Number.isSafeInteger(sum) ? sum : void 0;
2638
+ };
2639
+ var addDuration = (left, right) => {
2640
+ const sum = left + right;
2641
+ if (!Number.isFinite(sum) || sum < 0 || sum > Number.MAX_SAFE_INTEGER) return void 0;
2642
+ return sum;
2643
+ };
2644
+
2645
+ // src/function-metrics/function-identity.ts
2646
+ var FUNCTION_IDENTITY_SCOPE_KINDS = valuesOf()([
2647
+ "namespace",
2648
+ "function",
2649
+ "class",
2650
+ "object",
2651
+ "property"
2652
+ ]);
2653
+ var FUNCTION_IDENTITY_DECLARATION_KINDS = valuesOf()([
2654
+ "function",
2655
+ "arrow",
2656
+ "method",
2657
+ "getter",
2658
+ "setter",
2659
+ "constructor"
2660
+ ]);
2661
+ var FUNCTION_IDENTITY_SOURCE_BASES = valuesOf()([
2662
+ "repository",
2663
+ "package"
2664
+ ]);
2665
+ var SCOPE_FIELDS = fieldNames({
2666
+ kind: true,
2667
+ name: true
2668
+ });
2669
+ var STABLE_IDENTITY_FIELDS = fieldNames({
2670
+ identity_version: true,
2671
+ identity_kind: true,
2672
+ source_basis: true,
2673
+ package_name: true,
2674
+ path: true,
2675
+ scopes: true,
2676
+ declaration_kind: true,
2677
+ binding_name: true,
2678
+ is_static: true
2679
+ });
2680
+ var RELEASE_SCOPED_IDENTITY_FIELDS = fieldNames({
2681
+ identity_version: true,
2682
+ identity_kind: true,
2683
+ declaration_id: true
2684
+ });
2685
+ var PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
2686
+ var RECORDER_PLACEHOLDER = /^\(anonymous\)$|^anonymous@\d+:\d+$/;
2687
+ var RUNTIME_ID_PATTERN = /^[A-Za-z0-9._:-]+$/;
2688
+ var canonicalizeFunctionIdentityPath = (input) => {
2689
+ let value = input.replaceAll("\\", "/").trim();
2690
+ if (!value || value.length > FUNCTION_METRICS_MAX_PATH_LENGTH) return void 0;
2691
+ if (/^[A-Za-z]:/.test(value) || value.startsWith("/")) return void 0;
2692
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)) return void 0;
2693
+ if (value.includes("?") || value.includes("#") || value.includes("\0")) return void 0;
2694
+ while (value.startsWith("./")) value = value.slice(2);
2695
+ value = value.replaceAll(/\/{2,}/g, "/");
2696
+ if (!value || value.endsWith("/") || value.length > FUNCTION_METRICS_MAX_PATH_LENGTH) {
2697
+ return void 0;
2698
+ }
2699
+ const segments = value.split("/");
2700
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
2701
+ return void 0;
2702
+ }
2703
+ return value;
2704
+ };
2705
+ var isBindingName = (value) => {
2706
+ if (value.length === 0 || value.length > FUNCTION_METRICS_MAX_BINDING_LENGTH) return false;
2707
+ if (value.trim() !== value) return false;
2708
+ if (value.includes("\0") || value.includes("\n") || value.includes("\r")) return false;
2709
+ if (RECORDER_PLACEHOLDER.test(value)) return false;
2710
+ return true;
2711
+ };
2712
+ var isRuntimeDeclarationId = (value) => value.length <= FUNCTION_METRICS_MAX_RUNTIME_ID_LENGTH && RUNTIME_ID_PATTERN.test(value);
2713
+ var canonicalIdentity = (descriptor) => {
2714
+ if (descriptor.identity_kind === "release_scoped") {
2715
+ return {
2716
+ identity_version: FUNCTION_IDENTITY_VERSION,
2717
+ identity_kind: "release_scoped",
2718
+ declaration_id: descriptor.declaration_id
2719
+ };
2720
+ }
2721
+ return {
2722
+ identity_version: FUNCTION_IDENTITY_VERSION,
2723
+ identity_kind: "stable",
2724
+ source_basis: descriptor.source_basis,
2725
+ package_name: descriptor.package_name,
2726
+ path: descriptor.path,
2727
+ scopes: descriptor.scopes.map((scope) => ({ kind: scope.kind, name: scope.name })),
2728
+ declaration_kind: descriptor.declaration_kind,
2729
+ binding_name: descriptor.binding_name,
2730
+ is_static: descriptor.is_static
2731
+ };
2732
+ };
2733
+ var functionIdentityCanonicalJson = (descriptor) => canonicalJson(canonicalIdentity(descriptor));
2734
+ var functionIdentityKey = (descriptor) => sha256Hex(functionIdentityCanonicalJson(descriptor));
2735
+ var readScope = (value, path, issues) => {
2736
+ if (!isRecord(value)) {
2737
+ issues.add("invalid_scope", path);
2738
+ return void 0;
2739
+ }
2740
+ if (!exactKeys(value, SCOPE_FIELDS, path, issues)) return void 0;
2741
+ if (!isMember(FUNCTION_IDENTITY_SCOPE_KINDS, value.kind)) {
2742
+ issues.add("invalid_scope", `${path}.kind`);
2743
+ return void 0;
2744
+ }
2745
+ if (typeof value.name !== "string" || !isBindingName(value.name)) {
2746
+ issues.add("invalid_scope", `${path}.name`);
2747
+ return void 0;
2748
+ }
2749
+ return { kind: value.kind, name: value.name };
2750
+ };
2751
+ var readStableDescriptor = (value, path, issues) => {
2752
+ if (!exactKeys(value, STABLE_IDENTITY_FIELDS, path, issues)) return void 0;
2753
+ if (value.identity_version !== FUNCTION_IDENTITY_VERSION) {
2754
+ issues.add("invalid_identity_version", `${path}.identity_version`);
2755
+ return void 0;
2756
+ }
2757
+ if (!isMember(FUNCTION_IDENTITY_SOURCE_BASES, value.source_basis)) {
2758
+ issues.add("invalid_source_basis", `${path}.source_basis`);
2759
+ return void 0;
2760
+ }
2761
+ if (typeof value.path !== "string" || canonicalizeFunctionIdentityPath(value.path) !== value.path) {
2762
+ issues.add("invalid_path", `${path}.path`);
2763
+ return void 0;
2764
+ }
2765
+ let packageName;
2766
+ if (value.source_basis === "repository") {
2767
+ if (value.package_name !== null) {
2768
+ issues.add("package_basis_mismatch", `${path}.package_name`);
2769
+ return void 0;
2770
+ }
2771
+ packageName = null;
2772
+ } else if (typeof value.package_name !== "string" || value.package_name.length > FUNCTION_METRICS_MAX_PACKAGE_NAME_LENGTH || !PACKAGE_NAME_PATTERN.test(value.package_name)) {
2773
+ issues.add(
2774
+ value.package_name === null ? "package_basis_mismatch" : "invalid_package_name",
2775
+ `${path}.package_name`
2776
+ );
2777
+ return void 0;
2778
+ } else {
2779
+ packageName = value.package_name;
2780
+ }
2781
+ if (!Array.isArray(value.scopes)) {
2782
+ issues.add("invalid_scope", `${path}.scopes`);
2783
+ return void 0;
2784
+ }
2785
+ if (value.scopes.length > FUNCTION_METRICS_MAX_SCOPES) {
2786
+ issues.add("too_many_scopes", `${path}.scopes`);
2787
+ return void 0;
2788
+ }
2789
+ const scopes = [];
2790
+ for (let index = 0; index < value.scopes.length; index++) {
2791
+ const scope = readScope(value.scopes[index], `${path}.scopes[${index}]`, issues);
2792
+ if (!scope) return void 0;
2793
+ scopes.push(scope);
2794
+ }
2795
+ if (!isMember(FUNCTION_IDENTITY_DECLARATION_KINDS, value.declaration_kind)) {
2796
+ issues.add("invalid_declaration_kind", `${path}.declaration_kind`);
2797
+ return void 0;
2798
+ }
2799
+ if (typeof value.binding_name !== "string" || !isBindingName(value.binding_name)) {
2800
+ issues.add("invalid_binding_name", `${path}.binding_name`);
2801
+ return void 0;
2802
+ }
2803
+ if (typeof value.is_static !== "boolean") {
2804
+ issues.add("invalid_static", `${path}.is_static`);
2805
+ return void 0;
2806
+ }
2807
+ if (value.declaration_kind === "constructor" && value.is_static) {
2808
+ issues.add("invalid_static", `${path}.is_static`);
2809
+ return void 0;
2810
+ }
2811
+ return {
2812
+ identity_version: FUNCTION_IDENTITY_VERSION,
2813
+ identity_kind: "stable",
2814
+ source_basis: value.source_basis,
2815
+ package_name: packageName,
2816
+ path: value.path,
2817
+ scopes,
2818
+ declaration_kind: value.declaration_kind,
2819
+ binding_name: value.binding_name,
2820
+ is_static: value.is_static
2821
+ };
2822
+ };
2823
+ var readReleaseScopedDescriptor = (value, path, issues) => {
2824
+ if (!exactKeys(value, RELEASE_SCOPED_IDENTITY_FIELDS, path, issues)) return void 0;
2825
+ if (value.identity_version !== FUNCTION_IDENTITY_VERSION) {
2826
+ issues.add("invalid_identity_version", `${path}.identity_version`);
2827
+ return void 0;
2828
+ }
2829
+ if (typeof value.declaration_id !== "string" || !isRuntimeDeclarationId(value.declaration_id)) {
2830
+ issues.add("invalid_runtime_id", `${path}.declaration_id`);
2831
+ return void 0;
2832
+ }
2833
+ return {
2834
+ identity_version: FUNCTION_IDENTITY_VERSION,
2835
+ identity_kind: "release_scoped",
2836
+ declaration_id: value.declaration_id
2837
+ };
2838
+ };
2839
+ var parseFunctionIdentityDescriptor = (value, issues, path) => {
2840
+ if (!isRecord(value)) {
2841
+ issues.add("invalid_type", path);
2842
+ return void 0;
2843
+ }
2844
+ if (value.identity_kind === "stable") return readStableDescriptor(value, path, issues);
2845
+ if (value.identity_kind === "release_scoped") {
2846
+ return readReleaseScopedDescriptor(value, path, issues);
2847
+ }
2848
+ if (!("identity_kind" in value)) {
2849
+ issues.add("missing_field", `${path}.identity_kind`);
2850
+ return void 0;
2851
+ }
2852
+ issues.add("invalid_identity_kind", `${path}.identity_kind`);
2853
+ return void 0;
2854
+ };
2855
+ var validateFunctionIdentityDescriptor = (value) => {
2856
+ const issues = createFunctionMetricsIssues();
2857
+ const descriptor = parseFunctionIdentityDescriptor(value, issues, "$");
2858
+ if (!descriptor || issues.items.length > 0) return { ok: false, issues: issues.items };
2859
+ return { ok: true, descriptor };
2860
+ };
2861
+
2862
+ // src/function-metrics/function-metrics-bucket.ts
2863
+ var BUCKET_START_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00\.000Z$/;
2864
+ var parseFunctionMetricsBucketStart = (value) => {
2865
+ if (!BUCKET_START_PATTERN.test(value)) return void 0;
2866
+ const parsed = Date.parse(value);
2867
+ if (Number.isNaN(parsed) || new Date(parsed).toISOString() !== value) return void 0;
2868
+ return parsed;
2869
+ };
2870
+ var isFunctionMetricsBucketInWindow = (bucketStartMs, observedAtMs) => bucketStartMs <= observedAtMs + FUNCTION_METRICS_FUTURE_SKEW_MS && observedAtMs <= bucketStartMs + FUNCTION_METRICS_MINUTE_MS + FUNCTION_METRICS_BUCKET_LATENESS_MS;
2871
+
2872
+ // src/function-metrics/function-metrics-coalesce.ts
2873
+ var mergeHistogram = (left, right) => {
2874
+ const counts = /* @__PURE__ */ new Map();
2875
+ for (const cells of [left, right]) {
2876
+ for (const cell of cells) {
2877
+ const index = cell[0];
2878
+ const count = cell[1];
2879
+ const sum = addCount(counts.get(index) ?? 0, count);
2880
+ if (sum === void 0) return void 0;
2881
+ counts.set(index, sum);
2882
+ }
2883
+ }
2884
+ return [...counts.entries()].sort((leftCell, rightCell) => leftCell[0] - rightCell[0]);
2885
+ };
2886
+ var mergeBound = (left, right, pick) => {
2887
+ if (left === null) return right;
2888
+ if (right === null) return left;
2889
+ return pick(left, right);
2890
+ };
2891
+ var copyMinute = (row) => ({
2892
+ ...row,
2893
+ duration_histogram: row.duration_histogram.map((cell) => [cell[0], cell[1]])
2894
+ });
2895
+ var minuteKey = (row) => `${row.function_index}\0${row.execution_type_index}\0${row.bucket_start}`;
2896
+ var compareMinutes = (left, right) => {
2897
+ if (left.function_index !== right.function_index) {
2898
+ return left.function_index - right.function_index;
2899
+ }
2900
+ if (left.execution_type_index !== right.execution_type_index) {
2901
+ return left.execution_type_index - right.execution_type_index;
2902
+ }
2903
+ if (left.bucket_start < right.bucket_start) return -1;
2904
+ if (left.bucket_start > right.bucket_start) return 1;
2905
+ return 0;
2906
+ };
2907
+ var coalesceFunctionMetricMinutes = (rows) => {
2908
+ const groups = /* @__PURE__ */ new Map();
2909
+ for (const row of rows) {
2910
+ const key = minuteKey(row);
2911
+ const existing = groups.get(key);
2912
+ if (!existing) {
2913
+ groups.set(key, copyMinute(row));
2914
+ continue;
2915
+ }
2916
+ const started = addCount(existing.started_calls, row.started_calls);
2917
+ const completed = addCount(existing.completed_calls, row.completed_calls);
2918
+ const failed = addCount(existing.failed_calls, row.failed_calls);
2919
+ const sampleCount = addCount(existing.duration_sample_count, row.duration_sample_count);
2920
+ const invalidTiming = addCount(existing.invalid_timing_count, row.invalid_timing_count);
2921
+ const sampleSum = addDuration(existing.duration_sample_sum_us, row.duration_sample_sum_us);
2922
+ const histogram = mergeHistogram(existing.duration_histogram, row.duration_histogram);
2923
+ if (started === void 0 || completed === void 0 || failed === void 0 || sampleCount === void 0 || invalidTiming === void 0 || sampleSum === void 0 || !histogram) {
2924
+ return { ok: false, code: "integer_overflow" };
2925
+ }
2926
+ groups.set(key, {
2927
+ ...existing,
2928
+ started_calls: started,
2929
+ completed_calls: completed,
2930
+ failed_calls: failed,
2931
+ duration_sample_count: sampleCount,
2932
+ invalid_timing_count: invalidTiming,
2933
+ duration_sample_sum_us: sampleSum,
2934
+ duration_sample_min_us: mergeBound(
2935
+ existing.duration_sample_min_us,
2936
+ row.duration_sample_min_us,
2937
+ Math.min
2938
+ ),
2939
+ duration_sample_max_us: mergeBound(
2940
+ existing.duration_sample_max_us,
2941
+ row.duration_sample_max_us,
2942
+ Math.max
2943
+ ),
2944
+ duration_histogram: histogram
2945
+ });
2946
+ }
2947
+ return { ok: true, rows: [...groups.values()].sort(compareMinutes) };
2948
+ };
2949
+
2950
+ // src/function-metrics/function-metrics-wire.ts
2951
+ var FUNCTION_METRICS_SOURCE_RANGE_FIELDS = fieldNames({
2952
+ start_line: true,
2953
+ start_column: true,
2954
+ end_line: true,
2955
+ end_column: true
2956
+ });
2957
+ var FUNCTION_METRICS_DECLARATION_FIELDS = fieldNames({
2958
+ runtime_id: true,
2959
+ logical_key: true,
2960
+ identity_kind: true,
2961
+ descriptor: true,
2962
+ source_range: true,
2963
+ implementation_fingerprint: true
2964
+ });
2965
+ var FUNCTION_METRICS_EXECUTION_TYPE_FIELDS = fieldNames({
2966
+ execution_key: true
2967
+ });
2968
+ var FUNCTION_METRICS_MINUTE_FIELDS = fieldNames({
2969
+ function_index: true,
2970
+ execution_type_index: true,
2971
+ bucket_start: true,
2972
+ started_calls: true,
2973
+ completed_calls: true,
2974
+ failed_calls: true,
2975
+ duration_sample_count: true,
2976
+ duration_sample_sum_us: true,
2977
+ duration_sample_min_us: true,
2978
+ duration_sample_max_us: true,
2979
+ duration_histogram: true,
2980
+ invalid_timing_count: true
2981
+ });
2982
+ var FUNCTION_METRICS_COVERAGE_COUNTERS = valuesOf()([
2983
+ "skipped_unresolved_execution_type",
2984
+ "dropped_active_series",
2985
+ "dropped_byte_budget",
2986
+ "dropped_queue_budget",
2987
+ "dropped_late_completion",
2988
+ "dropped_unexportable"
2989
+ ]);
2990
+ var FUNCTION_METRICS_COVERAGE_FIELDS = fieldNames({
2991
+ covered_bucket_starts: true,
2992
+ skipped_unresolved_execution_type: true,
2993
+ dropped_active_series: true,
2994
+ dropped_byte_budget: true,
2995
+ dropped_queue_budget: true,
2996
+ dropped_late_completion: true,
2997
+ dropped_unexportable: true
2998
+ });
2999
+ var FUNCTION_METRICS_BATCH_FIELDS = fieldNames({
3000
+ schema_version: true,
3001
+ measurement_format: true,
3002
+ producer_id: true,
3003
+ batch_id: true,
3004
+ environment: true,
3005
+ release: true,
3006
+ functions: true,
3007
+ execution_types: true,
3008
+ minutes: true,
3009
+ coverage: true
3010
+ });
3011
+
3012
+ // src/function-metrics/function-metrics-minute.ts
3013
+ var readHistogram = (value, path, issues) => {
3014
+ if (!Array.isArray(value) || value.length > FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT) {
3015
+ issues.add("histogram_invalid", path);
3016
+ return void 0;
3017
+ }
3018
+ const cells = [];
3019
+ let previous = -1;
3020
+ for (let index = 0; index < value.length; index++) {
3021
+ const cell = value[index];
3022
+ const cellPath = `${path}[${index}]`;
3023
+ if (!Array.isArray(cell) || cell.length !== 2) {
3024
+ issues.add("histogram_invalid", cellPath);
3025
+ return void 0;
3026
+ }
3027
+ const bucket = cell[0];
3028
+ const count = cell[1];
3029
+ const bucketIsValid = typeof bucket === "number" && Number.isSafeInteger(bucket) && bucket > previous && bucket < FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT;
3030
+ const countIsValid = typeof count === "number" && Number.isSafeInteger(count) && count >= 1;
3031
+ if (!bucketIsValid || !countIsValid) {
3032
+ issues.add("histogram_invalid", cellPath);
3033
+ return void 0;
3034
+ }
3035
+ previous = bucket;
3036
+ cells.push([bucket, count]);
3037
+ }
3038
+ return cells;
3039
+ };
3040
+ var histogramTotal = (cells) => {
3041
+ let total = 0;
3042
+ for (const cell of cells) {
3043
+ const count = cell[1];
3044
+ const sum = addCount(total, count);
3045
+ if (sum === void 0) return void 0;
3046
+ total = sum;
3047
+ }
3048
+ return total;
3049
+ };
3050
+ var readNullableDuration = (value, path, issues) => {
3051
+ if (value === null) return null;
3052
+ return readDuration(value, path, issues);
3053
+ };
3054
+ var checkTiming = (path, format, completed, sampleCount, sampleSum, sampleMin, sampleMax, histogram, invalidTiming, issues) => {
3055
+ const countedSamples = addCount(sampleCount, invalidTiming);
3056
+ if (countedSamples === void 0) {
3057
+ issues.add("integer_overflow", `${path}.duration_sample_count`);
3058
+ } else if (format === FUNCTION_METRICS_MEASUREMENT_FORMAT && countedSamples !== completed) {
3059
+ issues.add("full_timing_sample_mismatch", path);
3060
+ } else if (format === FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT && countedSamples > completed) {
3061
+ issues.add("invalid_count", `${path}.duration_sample_count`);
3062
+ }
3063
+ const total = histogramTotal(histogram);
3064
+ if (total === void 0) {
3065
+ issues.add("integer_overflow", `${path}.duration_histogram`);
3066
+ } else if (total !== sampleCount) {
3067
+ issues.add("histogram_count_mismatch", `${path}.duration_histogram`);
3068
+ }
3069
+ if (sampleCount === 0) {
3070
+ if (sampleMin !== null || sampleMax !== null || sampleSum !== 0) {
3071
+ issues.add("min_max_invalid", path);
3072
+ }
3073
+ return;
3074
+ }
3075
+ const boundsAreValid = sampleMin !== null && sampleMax !== null && sampleMin <= sampleMax && sampleSum >= sampleMin && sampleSum / sampleCount <= sampleMax;
3076
+ if (!boundsAreValid) issues.add("min_max_invalid", path);
3077
+ };
3078
+ var readFunctionMetricsMinute = (value, path, format, issues) => {
3079
+ if (!isRecord(value)) {
3080
+ issues.add("invalid_type", path);
3081
+ return void 0;
3082
+ }
3083
+ if (!exactKeys(value, FUNCTION_METRICS_MINUTE_FIELDS, path, issues)) return void 0;
3084
+ const functionIndex = readCount(value.function_index, `${path}.function_index`, issues);
3085
+ const executionTypeIndex = readCount(
3086
+ value.execution_type_index,
3087
+ `${path}.execution_type_index`,
3088
+ issues
3089
+ );
3090
+ const bucketStart = typeof value.bucket_start === "string" ? parseFunctionMetricsBucketStart(value.bucket_start) : void 0;
3091
+ if (typeof value.bucket_start !== "string" || bucketStart === void 0) {
3092
+ issues.add("invalid_bucket_start", `${path}.bucket_start`);
3093
+ }
3094
+ const started = readCount(value.started_calls, `${path}.started_calls`, issues);
3095
+ const completed = readCount(value.completed_calls, `${path}.completed_calls`, issues);
3096
+ const failed = readCount(value.failed_calls, `${path}.failed_calls`, issues);
3097
+ const sampleCount = readCount(
3098
+ value.duration_sample_count,
3099
+ `${path}.duration_sample_count`,
3100
+ issues
3101
+ );
3102
+ const sampleSum = readDuration(
3103
+ value.duration_sample_sum_us,
3104
+ `${path}.duration_sample_sum_us`,
3105
+ issues
3106
+ );
3107
+ const sampleMin = readNullableDuration(
3108
+ value.duration_sample_min_us,
3109
+ `${path}.duration_sample_min_us`,
3110
+ issues
3111
+ );
3112
+ const sampleMax = readNullableDuration(
3113
+ value.duration_sample_max_us,
3114
+ `${path}.duration_sample_max_us`,
3115
+ issues
3116
+ );
3117
+ const histogram = readHistogram(value.duration_histogram, `${path}.duration_histogram`, issues);
3118
+ const invalidTiming = readCount(
3119
+ value.invalid_timing_count,
3120
+ `${path}.invalid_timing_count`,
3121
+ issues
3122
+ );
3123
+ if (functionIndex === void 0 || executionTypeIndex === void 0 || bucketStart === void 0 || typeof value.bucket_start !== "string" || started === void 0 || completed === void 0 || failed === void 0 || sampleCount === void 0 || sampleSum === void 0 || sampleMin === void 0 || sampleMax === void 0 || histogram === void 0 || invalidTiming === void 0) {
3124
+ return void 0;
3125
+ }
3126
+ if (failed > completed) {
3127
+ issues.add("failed_exceeds_completed", `${path}.failed_calls`);
3128
+ }
3129
+ checkTiming(
3130
+ path,
3131
+ format,
3132
+ completed,
3133
+ sampleCount,
3134
+ sampleSum,
3135
+ sampleMin,
3136
+ sampleMax,
3137
+ histogram,
3138
+ invalidTiming,
3139
+ issues
3140
+ );
3141
+ return {
3142
+ function_index: functionIndex,
3143
+ execution_type_index: executionTypeIndex,
3144
+ bucket_start: value.bucket_start,
3145
+ started_calls: started,
3146
+ completed_calls: completed,
3147
+ failed_calls: failed,
3148
+ duration_sample_count: sampleCount,
3149
+ duration_sample_sum_us: sampleSum,
3150
+ duration_sample_min_us: sampleMin,
3151
+ duration_sample_max_us: sampleMax,
3152
+ duration_histogram: histogram,
3153
+ invalid_timing_count: invalidTiming
3154
+ };
3155
+ };
3156
+
3157
+ // src/function-metrics/function-metrics-execution-key.ts
3158
+ var NAMED_EXECUTION_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
3159
+ var isCanonicalFunctionMetricsExecutionKey = (key) => {
3160
+ if (key.length === 0 || key.length > FUNCTION_METRICS_MAX_EXECUTION_KEY_LENGTH) return false;
3161
+ if (key.startsWith("http:")) {
3162
+ const rest = key.slice("http:".length);
3163
+ const colon2 = rest.indexOf(":");
3164
+ if (colon2 <= 0 || colon2 === rest.length - 1) return false;
3165
+ const method = rest.slice(0, colon2);
3166
+ const route = rest.slice(colon2 + 1);
3167
+ if (!method || method.trim().toUpperCase() !== method) return false;
3168
+ if (!route || route.trim() !== route || route.includes("?") || route.includes("://")) {
3169
+ return false;
3170
+ }
3171
+ return true;
3172
+ }
3173
+ const colon = key.indexOf(":");
3174
+ if (colon <= 0 || colon === key.length - 1) return false;
3175
+ const kind = key.slice(0, colon);
3176
+ const name = key.slice(colon + 1);
3177
+ if (!NAMED_EXECUTION_KINDS.has(kind) || !name || name.trim() !== name) return false;
3178
+ return true;
3179
+ };
3180
+
3181
+ // src/function-metrics/function-metrics-read-batch.ts
3182
+ var SOURCE_REVISION_PATTERN = /^[0-9a-f]{7,40}$/;
3183
+ var LOGICAL_KEY_PATTERN = /^[0-9a-f]{64}$/;
3184
+ var RUNTIME_ID_PATTERN2 = /^[A-Za-z0-9._:-]+$/;
3185
+ var FINGERPRINT_PATTERN = /^fp1_[0-9a-f]{64}$/;
3186
+ var readSourceRange = (value, path, issues) => {
3187
+ if (value === null) return null;
3188
+ if (!isRecord(value)) {
3189
+ issues.add("invalid_source_range", path);
3190
+ return void 0;
3191
+ }
3192
+ if (!exactKeys(value, FUNCTION_METRICS_SOURCE_RANGE_FIELDS, path, issues)) return void 0;
3193
+ const positions = [];
3194
+ for (const field of FUNCTION_METRICS_SOURCE_RANGE_FIELDS) {
3195
+ const position = value[field];
3196
+ const inRange = typeof position === "number" && Number.isSafeInteger(position) && position >= 1 && position <= FUNCTION_METRICS_MAX_SOURCE_POSITION;
3197
+ if (!inRange) {
3198
+ issues.add("invalid_source_range", `${path}.${field}`);
3199
+ return void 0;
3200
+ }
3201
+ positions.push(position);
3202
+ }
3203
+ const startLine = positions[0];
3204
+ const startColumn = positions[1];
3205
+ const endLine = positions[2];
3206
+ const endColumn = positions[3];
3207
+ if (startLine === void 0 || startColumn === void 0 || endLine === void 0 || endColumn === void 0) {
3208
+ return void 0;
3209
+ }
3210
+ if (endLine < startLine || endLine === startLine && endColumn < startColumn) {
3211
+ issues.add("invalid_source_range", path);
3212
+ return void 0;
3213
+ }
3214
+ return {
3215
+ start_line: startLine,
3216
+ start_column: startColumn,
3217
+ end_line: endLine,
3218
+ end_column: endColumn
3219
+ };
3220
+ };
3221
+ var readFunctionMetricsRelease = (value, issues) => {
3222
+ if (typeof value !== "string" || !SOURCE_REVISION_PATTERN.test(value)) {
3223
+ issues.add("invalid_source_revision", "$.release");
3224
+ return void 0;
3225
+ }
3226
+ return value;
3227
+ };
3228
+ var readDeclaration = (value, path, issues) => {
3229
+ if (!isRecord(value)) {
3230
+ issues.add("invalid_type", path);
3231
+ return void 0;
3232
+ }
3233
+ if (!exactKeys(value, FUNCTION_METRICS_DECLARATION_FIELDS, path, issues)) return void 0;
3234
+ if (typeof value.runtime_id !== "string" || value.runtime_id.length > FUNCTION_METRICS_MAX_RUNTIME_ID_LENGTH || !RUNTIME_ID_PATTERN2.test(value.runtime_id)) {
3235
+ issues.add("invalid_runtime_id", `${path}.runtime_id`);
3236
+ return void 0;
3237
+ }
3238
+ if (typeof value.logical_key !== "string" || !LOGICAL_KEY_PATTERN.test(value.logical_key)) {
3239
+ issues.add("invalid_logical_key", `${path}.logical_key`);
3240
+ return void 0;
3241
+ }
3242
+ if (value.identity_kind !== "stable" && value.identity_kind !== "release_scoped") {
3243
+ issues.add("invalid_identity_kind", `${path}.identity_kind`);
3244
+ return void 0;
3245
+ }
3246
+ const descriptor = parseFunctionIdentityDescriptor(
3247
+ value.descriptor,
3248
+ issues,
3249
+ `${path}.descriptor`
3250
+ );
3251
+ const sourceRange = readSourceRange(value.source_range, `${path}.source_range`, issues);
3252
+ const fingerprint = value.implementation_fingerprint;
3253
+ if (fingerprint !== null && (typeof fingerprint !== "string" || !FINGERPRINT_PATTERN.test(fingerprint))) {
3254
+ issues.add("invalid_fingerprint", `${path}.implementation_fingerprint`);
3255
+ return void 0;
3256
+ }
3257
+ if (!descriptor || sourceRange === void 0) return void 0;
3258
+ return {
3259
+ runtime_id: value.runtime_id,
3260
+ logical_key: value.logical_key,
3261
+ identity_kind: value.identity_kind,
3262
+ descriptor,
3263
+ source_range: sourceRange,
3264
+ implementation_fingerprint: fingerprint
3265
+ };
3266
+ };
3267
+ var readFunctionMetricsDeclarations = (value, issues) => {
3268
+ if (!Array.isArray(value)) {
3269
+ issues.add("invalid_type", "$.functions");
3270
+ return void 0;
3271
+ }
3272
+ if (value.length > FUNCTION_METRICS_MAX_FUNCTIONS) {
3273
+ issues.add("too_many_functions", "$.functions");
3274
+ return void 0;
3275
+ }
3276
+ const declarations = [];
3277
+ let ok = true;
3278
+ for (let index = 0; index < value.length; index++) {
3279
+ const declaration = readDeclaration(value[index], `$.functions[${index}]`, issues);
3280
+ if (!declaration) ok = false;
3281
+ else declarations.push(declaration);
3282
+ }
3283
+ return ok ? declarations : void 0;
3284
+ };
3285
+ var readFunctionMetricsExecutionTypes = (value, issues) => {
3286
+ if (!Array.isArray(value)) {
3287
+ issues.add("invalid_type", "$.execution_types");
3288
+ return void 0;
3289
+ }
3290
+ if (value.length > FUNCTION_METRICS_MAX_EXECUTION_TYPES) {
3291
+ issues.add("too_many_execution_types", "$.execution_types");
3292
+ return void 0;
3293
+ }
3294
+ const types = [];
3295
+ const seen = /* @__PURE__ */ new Set();
3296
+ let ok = true;
3297
+ for (let index = 0; index < value.length; index++) {
3298
+ const entry = value[index];
3299
+ const path = `$.execution_types[${index}]`;
3300
+ if (!isRecord(entry)) {
3301
+ issues.add("invalid_type", path);
3302
+ ok = false;
3303
+ continue;
3304
+ }
3305
+ if (!exactKeys(entry, FUNCTION_METRICS_EXECUTION_TYPE_FIELDS, path, issues)) {
3306
+ ok = false;
3307
+ continue;
3308
+ }
3309
+ if (typeof entry.execution_key !== "string" || !isCanonicalFunctionMetricsExecutionKey(entry.execution_key)) {
3310
+ issues.add("invalid_execution_key", `${path}.execution_key`);
3311
+ ok = false;
3312
+ continue;
3313
+ }
3314
+ if (seen.has(entry.execution_key)) {
3315
+ issues.add("duplicate_execution_type", `${path}.execution_key`);
3316
+ ok = false;
3317
+ continue;
3318
+ }
3319
+ seen.add(entry.execution_key);
3320
+ types.push({ execution_key: entry.execution_key });
3321
+ }
3322
+ return ok ? types : void 0;
3323
+ };
3324
+ var readFunctionMetricsCoverage = (value, issues) => {
3325
+ if (!isRecord(value)) {
3326
+ issues.add("invalid_type", "$.coverage");
3327
+ return void 0;
3328
+ }
3329
+ if (!exactKeys(value, FUNCTION_METRICS_COVERAGE_FIELDS, "$.coverage", issues)) return void 0;
3330
+ if (!Array.isArray(value.covered_bucket_starts)) {
3331
+ issues.add("coverage_invalid", "$.coverage.covered_bucket_starts");
3332
+ return void 0;
3333
+ }
3334
+ if (value.covered_bucket_starts.length > FUNCTION_METRICS_MAX_COVERED_BUCKETS) {
3335
+ issues.add("too_many_buckets", "$.coverage.covered_bucket_starts");
3336
+ return void 0;
3337
+ }
3338
+ const covered = [];
3339
+ let previous = "";
3340
+ for (let index = 0; index < value.covered_bucket_starts.length; index++) {
3341
+ const entry = value.covered_bucket_starts[index];
3342
+ if (typeof entry !== "string" || parseFunctionMetricsBucketStart(entry) === void 0) {
3343
+ issues.add("invalid_bucket_start", `$.coverage.covered_bucket_starts[${index}]`);
3344
+ return void 0;
3345
+ }
3346
+ if (previous && entry <= previous) {
3347
+ issues.add("coverage_invalid", `$.coverage.covered_bucket_starts[${index}]`);
3348
+ return void 0;
3349
+ }
3350
+ previous = entry;
3351
+ covered.push(entry);
3352
+ }
3353
+ const counters = {
3354
+ skipped_unresolved_execution_type: 0,
3355
+ dropped_active_series: 0,
3356
+ dropped_byte_budget: 0,
3357
+ dropped_queue_budget: 0,
3358
+ dropped_late_completion: 0,
3359
+ dropped_unexportable: 0
3360
+ };
3361
+ for (const field of FUNCTION_METRICS_COVERAGE_COUNTERS) {
3362
+ const count = readCount(value[field], `$.coverage.${field}`, issues);
3363
+ if (count === void 0) return void 0;
3364
+ counters[field] = count;
3365
+ }
3366
+ return { covered_bucket_starts: covered, ...counters };
3367
+ };
3368
+ var checkFunctionMetricsIdentities = (declarations, issues) => {
3369
+ const runtimeIds = /* @__PURE__ */ new Set();
3370
+ const canonicalByKey = /* @__PURE__ */ new Map();
3371
+ for (let index = 0; index < declarations.length; index++) {
3372
+ const declaration = declarations[index];
3373
+ if (!declaration) continue;
3374
+ const path = `$.functions[${index}]`;
3375
+ if (runtimeIds.has(declaration.runtime_id)) {
3376
+ issues.add("duplicate_runtime_id", `${path}.runtime_id`);
3377
+ }
3378
+ runtimeIds.add(declaration.runtime_id);
3379
+ const canonical = functionIdentityCanonicalJson(declaration.descriptor);
3380
+ if (declaration.logical_key !== functionIdentityKey(declaration.descriptor)) {
3381
+ issues.add("identity_key_mismatch", `${path}.logical_key`);
3382
+ }
3383
+ if (declaration.identity_kind !== declaration.descriptor.identity_kind) {
3384
+ issues.add("identity_kind_mismatch", `${path}.identity_kind`);
3385
+ }
3386
+ const previous = canonicalByKey.get(declaration.logical_key);
3387
+ if (previous === void 0) {
3388
+ canonicalByKey.set(declaration.logical_key, canonical);
3389
+ } else if (previous !== canonical) {
3390
+ issues.add("identity_conflict", `${path}.logical_key`);
3391
+ } else if (declaration.identity_kind === "stable") {
3392
+ issues.add("duplicate_stable_identity", `${path}.logical_key`);
3393
+ }
3394
+ if (declaration.descriptor.identity_kind !== "release_scoped") continue;
3395
+ if (declaration.descriptor.declaration_id !== declaration.runtime_id) {
3396
+ issues.add("declaration_id_mismatch", `${path}.descriptor.declaration_id`);
3397
+ }
3398
+ }
3399
+ };
3400
+
3401
+ // src/function-metrics/function-metrics-batch.ts
3402
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3403
+ var decodedSizeIsAllowed = (decodedByteLength) => Number.isSafeInteger(decodedByteLength) && decodedByteLength >= 0 && decodedByteLength <= FUNCTION_METRICS_MAX_DECODED_BYTES;
3404
+ var readMinutes = (value, format, issues) => {
3405
+ const minutes = [];
3406
+ let ok = true;
3407
+ for (let index = 0; index < value.length; index++) {
3408
+ const minute = readFunctionMetricsMinute(value[index], `$.minutes[${index}]`, format, issues);
3409
+ if (!minute) ok = false;
3410
+ else minutes.push(minute);
3411
+ }
3412
+ return ok ? minutes : void 0;
3413
+ };
3414
+ var checkMinuteReferences = (minutes, functionCount, executionTypeCount, covered, observedAtMs, issues) => {
3415
+ for (const minute of minutes) {
3416
+ if (functionCount !== void 0 && minute.function_index >= functionCount) {
3417
+ issues.add("invalid_dictionary_index", "$.minutes");
3418
+ }
3419
+ if (executionTypeCount !== void 0 && minute.execution_type_index >= executionTypeCount) {
3420
+ issues.add("invalid_dictionary_index", "$.minutes");
3421
+ }
3422
+ if (covered && !covered.has(minute.bucket_start)) {
3423
+ issues.add("coverage_bucket_missing", "$.minutes");
3424
+ }
3425
+ const start = parseFunctionMetricsBucketStart(minute.bucket_start);
3426
+ if (start !== void 0 && !isFunctionMetricsBucketInWindow(start, observedAtMs)) {
3427
+ issues.add("bucket_outside_window", "$.minutes");
3428
+ }
3429
+ }
3430
+ const coalesced = coalesceFunctionMetricMinutes(minutes);
3431
+ if (!coalesced.ok) issues.add("integer_overflow", "$.minutes");
3432
+ };
3433
+ var functionMetricsBatchDigest = (decodedPayload) => sha256Hex(decodedPayload);
3434
+ var encodeFunctionMetricsBatch = (batch) => new TextEncoder().encode(JSON.stringify(batch));
3435
+ var validateFunctionMetricsBatch = (value, options) => {
3436
+ const issues = createFunctionMetricsIssues();
3437
+ const observedAtMs = options.observedAt.getTime();
3438
+ if (Number.isNaN(observedAtMs)) {
3439
+ issues.add("invalid_observed_at", "$");
3440
+ return { ok: false, issues: issues.items };
3441
+ }
3442
+ if (!decodedSizeIsAllowed(options.decodedByteLength)) {
3443
+ issues.add("decoded_payload_too_large", "$");
3444
+ }
3445
+ if (!isRecord(value)) {
3446
+ issues.add("invalid_type", "$");
3447
+ return { ok: false, issues: issues.items };
3448
+ }
3449
+ if (!exactKeys(value, FUNCTION_METRICS_BATCH_FIELDS, "$", issues)) {
3450
+ return { ok: false, issues: issues.items };
3451
+ }
3452
+ if (value.schema_version !== FUNCTION_METRICS_SCHEMA_VERSION) {
3453
+ issues.add("invalid_schema_version", "$.schema_version");
3454
+ }
3455
+ const format = isFunctionMetricsMeasurementFormat(value.measurement_format) ? value.measurement_format : void 0;
3456
+ if (!format) issues.add("invalid_measurement_format", "$.measurement_format");
3457
+ if (typeof value.producer_id !== "string" || !UUID_PATTERN.test(value.producer_id)) {
3458
+ issues.add("invalid_uuid", "$.producer_id");
3459
+ }
3460
+ if (typeof value.batch_id !== "string" || !UUID_PATTERN.test(value.batch_id)) {
3461
+ issues.add("invalid_uuid", "$.batch_id");
3462
+ }
3463
+ if (!isRasputinEnvironment(value.environment)) {
3464
+ issues.add("invalid_environment", "$.environment");
3465
+ }
3466
+ const release = readFunctionMetricsRelease(value.release, issues);
3467
+ const functions = readFunctionMetricsDeclarations(value.functions, issues);
3468
+ const executionTypes = readFunctionMetricsExecutionTypes(value.execution_types, issues);
3469
+ const coverage = readFunctionMetricsCoverage(value.coverage, issues);
3470
+ if (!Array.isArray(value.minutes)) {
3471
+ issues.add("invalid_type", "$.minutes");
3472
+ return { ok: false, issues: issues.items };
3473
+ }
3474
+ if (value.minutes.length > FUNCTION_METRICS_MAX_MINUTE_ROWS) {
3475
+ issues.add("too_many_rows", "$.minutes");
3476
+ return { ok: false, issues: issues.items };
3477
+ }
3478
+ const minutes = readMinutes(value.minutes, format, issues);
3479
+ if (functions) checkFunctionMetricsIdentities(functions, issues);
3480
+ if (coverage) {
3481
+ for (const bucket of coverage.covered_bucket_starts) {
3482
+ const start = parseFunctionMetricsBucketStart(bucket);
3483
+ if (start !== void 0 && !isFunctionMetricsBucketInWindow(start, observedAtMs)) {
3484
+ issues.add("bucket_outside_window", "$.coverage.covered_bucket_starts");
3485
+ }
3486
+ }
3487
+ }
3488
+ if (minutes) {
3489
+ checkMinuteReferences(
3490
+ minutes,
3491
+ functions?.length,
3492
+ executionTypes?.length,
3493
+ coverage ? new Set(coverage.covered_bucket_starts) : void 0,
3494
+ observedAtMs,
3495
+ issues
3496
+ );
3497
+ }
3498
+ if (issues.items.length > 0 || value.schema_version !== FUNCTION_METRICS_SCHEMA_VERSION || !format || typeof value.producer_id !== "string" || typeof value.batch_id !== "string" || !isRasputinEnvironment(value.environment) || !release || !functions || !executionTypes || !coverage || !minutes) {
3499
+ return { ok: false, issues: issues.items };
3500
+ }
3501
+ return {
3502
+ ok: true,
3503
+ batch: {
3504
+ schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
3505
+ measurement_format: format,
3506
+ producer_id: value.producer_id,
3507
+ batch_id: value.batch_id,
3508
+ environment: value.environment,
3509
+ release,
3510
+ functions,
3511
+ execution_types: executionTypes,
3512
+ minutes,
3513
+ coverage
3514
+ }
3515
+ };
3516
+ };
3517
+
3518
+ // src/function-metrics/function-metrics-histogram.ts
3519
+ var UPPER_BOUND_US = Array.from(
3520
+ { length: FUNCTION_METRICS_HISTOGRAM_FINITE_BOUNDS },
3521
+ (_, index) => 2 ** (index / 8)
3522
+ );
3523
+ var functionMetricsHistogramUpperBoundUs = (index) => {
3524
+ if (!Number.isInteger(index) || index < 0 || index >= UPPER_BOUND_US.length) return void 0;
3525
+ return UPPER_BOUND_US[index];
3526
+ };
3527
+ var durationHistogramBucket = (durationUs) => {
3528
+ if (typeof durationUs !== "number" || !Number.isFinite(durationUs) || durationUs < 0) {
3529
+ return void 0;
3530
+ }
3531
+ if (durationUs === 0) return 0;
3532
+ let low = 0;
3533
+ let high = UPPER_BOUND_US.length;
3534
+ while (low < high) {
3535
+ const mid = low + high >> 1;
3536
+ const upper = UPPER_BOUND_US[mid];
3537
+ if (upper !== void 0 && durationUs <= upper) high = mid;
3538
+ else low = mid + 1;
3539
+ }
3540
+ return low === UPPER_BOUND_US.length ? FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT - 1 : low + 1;
3541
+ };
3542
+
3543
+ // src/function-metrics/function-metrics-trace-declaration.ts
3544
+ var functionMetricsTraceDeclaration = (input) => {
3545
+ const descriptor = {
3546
+ identity_version: FUNCTION_IDENTITY_VERSION,
3547
+ identity_kind: "release_scoped",
3548
+ declaration_id: input.runtimeId
3549
+ };
3550
+ return {
3551
+ runtime_id: input.runtimeId,
3552
+ logical_key: functionIdentityKey(descriptor),
3553
+ identity_kind: "release_scoped",
3554
+ descriptor,
3555
+ source_range: null,
3556
+ implementation_fingerprint: null
3557
+ };
3558
+ };
3559
+
2533
3560
  // src/instrumentation-manifest/instrumentation-manifest-types.ts
2534
3561
  var INSTRUMENTATION_MANIFEST_SCHEMA_VERSION = 3;
2535
3562
 
@@ -2560,12 +3587,40 @@ var uploadInstrumentationManifest = async (options) => {
2560
3587
  }
2561
3588
  };
2562
3589
  export {
3590
+ EXECUTION_METRICS_SCHEMA_VERSION,
3591
+ FUNCTION_IDENTITY_VERSION,
3592
+ FUNCTION_METRICS_BUCKET_LATENESS_MS,
3593
+ FUNCTION_METRICS_FUTURE_SKEW_MS,
3594
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
3595
+ FUNCTION_METRICS_HISTOGRAM_FINITE_BOUNDS,
3596
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES,
3597
+ FUNCTION_METRICS_MAX_BINDING_LENGTH,
3598
+ FUNCTION_METRICS_MAX_BUFFERED_MS,
3599
+ FUNCTION_METRICS_MAX_COVERED_BUCKETS,
3600
+ FUNCTION_METRICS_MAX_DECODED_BYTES,
3601
+ FUNCTION_METRICS_MAX_EXECUTION_KEY_LENGTH,
3602
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES,
3603
+ FUNCTION_METRICS_MAX_FUNCTIONS,
3604
+ FUNCTION_METRICS_MAX_MINUTE_ROWS,
3605
+ FUNCTION_METRICS_MAX_PACKAGE_NAME_LENGTH,
3606
+ FUNCTION_METRICS_MAX_PATH_LENGTH,
3607
+ FUNCTION_METRICS_MAX_RUNTIME_ID_LENGTH,
3608
+ FUNCTION_METRICS_MAX_SCOPES,
3609
+ FUNCTION_METRICS_MAX_SOURCE_POSITION,
3610
+ FUNCTION_METRICS_MAX_STATE_BYTES,
3611
+ FUNCTION_METRICS_MEASUREMENT_FORMAT,
3612
+ FUNCTION_METRICS_MEASUREMENT_FORMATS,
3613
+ FUNCTION_METRICS_MINUTE_MS,
3614
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT,
3615
+ FUNCTION_METRICS_SCHEMA_VERSION,
2563
3616
  INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
2564
3617
  MAX_REDACT_KEYS,
2565
3618
  MAX_REDACT_KEY_LENGTH,
2566
3619
  RASPUTIN_REDACTED,
2567
3620
  RASPUTIN_WIRE_TAG,
2568
3621
  announceDeploy,
3622
+ canonicalizeFunctionIdentityPath,
3623
+ coalesceFunctionMetricMinutes,
2569
3624
  copyRedactKeys,
2570
3625
  createClient,
2571
3626
  createIngestEvent,
@@ -2573,17 +3628,29 @@ export {
2573
3628
  createTransport,
2574
3629
  defaultIngestFetch,
2575
3630
  defaultSensitivePropertyNames,
3631
+ durationHistogramBucket,
3632
+ encodeFunctionMetricsBatch,
2576
3633
  encodeJsonRequestBody,
2577
3634
  encodeJsonRequestBodyAsync,
2578
3635
  foldSyntheticFrames,
3636
+ functionIdentityCanonicalJson,
3637
+ functionIdentityKey,
3638
+ functionMetricsBatchDigest,
3639
+ functionMetricsHistogramUpperBoundUs,
3640
+ functionMetricsTraceDeclaration,
2579
3641
  hashInstrumentationManifest,
3642
+ isCanonicalFunctionMetricsExecutionKey,
2580
3643
  isClientEnabled,
3644
+ isFunctionMetricsBucketInWindow,
3645
+ isFunctionMetricsMeasurementFormat,
2581
3646
  isLocalDsnPublicKey,
3647
+ isRasputinEnvironment,
2582
3648
  isRasputinHandleRunFrame,
2583
3649
  isRasputinShellFrame,
2584
3650
  isRasputinTaggedValue,
2585
3651
  normalizeFrames,
2586
3652
  parseDsn,
3653
+ parseFunctionMetricsBucketStart,
2587
3654
  parseReleaseSha,
2588
3655
  parseStack,
2589
3656
  propertyNameIsSensitive,
@@ -2602,8 +3669,11 @@ export {
2602
3669
  runtimeFunctionId,
2603
3670
  runtimeStateUnavailable,
2604
3671
  scheduleAnnounceDeploy,
3672
+ sha256Hex,
2605
3673
  sourceDisplayPath,
2606
3674
  sourceLocatorFromFile,
2607
3675
  sourceLocatorKey,
2608
- uploadInstrumentationManifest
3676
+ uploadInstrumentationManifest,
3677
+ validateFunctionIdentityDescriptor,
3678
+ validateFunctionMetricsBatch
2609
3679
  };