sol-trade-sdk 0.1.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 (87) hide show
  1. package/README.md +390 -0
  2. package/dist/chunk-MMQAMIKR.mjs +3735 -0
  3. package/dist/chunk-NEZDFAYA.mjs +7744 -0
  4. package/dist/clients-VITWK7B6.mjs +1370 -0
  5. package/dist/index-1BK_FXsW.d.mts +2327 -0
  6. package/dist/index-1BK_FXsW.d.ts +2327 -0
  7. package/dist/index.d.mts +2659 -0
  8. package/dist/index.d.ts +2659 -0
  9. package/dist/index.js +13265 -0
  10. package/dist/index.mjs +562 -0
  11. package/dist/perf/index.d.mts +2 -0
  12. package/dist/perf/index.d.ts +2 -0
  13. package/dist/perf/index.js +3742 -0
  14. package/dist/perf/index.mjs +214 -0
  15. package/package.json +101 -0
  16. package/src/__tests__/complete_sdk.test.ts +354 -0
  17. package/src/__tests__/hotpath.test.ts +486 -0
  18. package/src/__tests__/nonce.test.ts +45 -0
  19. package/src/__tests__/sdk.test.ts +425 -0
  20. package/src/address-lookup/index.ts +197 -0
  21. package/src/cache/cache.ts +308 -0
  22. package/src/calc/index.ts +1058 -0
  23. package/src/calc/pumpfun.ts +124 -0
  24. package/src/common/bonding_curve.ts +272 -0
  25. package/src/common/compute-budget.ts +148 -0
  26. package/src/common/confirm-any-signature.ts +184 -0
  27. package/src/common/fast-timing.ts +481 -0
  28. package/src/common/fast_fn.ts +150 -0
  29. package/src/common/gas-fee-strategy.ts +253 -0
  30. package/src/common/map-pool.ts +23 -0
  31. package/src/common/nonce.ts +40 -0
  32. package/src/common/sdk-log.ts +460 -0
  33. package/src/common/seed.ts +381 -0
  34. package/src/common/spl-token.ts +578 -0
  35. package/src/common/subscription-handle.ts +644 -0
  36. package/src/common/trading-utils.ts +239 -0
  37. package/src/common/wsol-manager.ts +325 -0
  38. package/src/compute/compute_budget_manager.ts +187 -0
  39. package/src/compute/index.ts +21 -0
  40. package/src/constants/index.ts +96 -0
  41. package/src/execution/execution.ts +532 -0
  42. package/src/execution/index.ts +42 -0
  43. package/src/hotpath/executor.ts +464 -0
  44. package/src/hotpath/index.ts +64 -0
  45. package/src/hotpath/state.ts +435 -0
  46. package/src/index.ts +2117 -0
  47. package/src/instruction/bonk_builder.ts +730 -0
  48. package/src/instruction/index.ts +24 -0
  49. package/src/instruction/meteora_damm_v2_builder.ts +509 -0
  50. package/src/instruction/pumpfun_builder.ts +1183 -0
  51. package/src/instruction/pumpswap.ts +1123 -0
  52. package/src/instruction/raydium_amm_v4_builder.ts +692 -0
  53. package/src/instruction/raydium_cpmm_builder.ts +795 -0
  54. package/src/middleware/traits.ts +407 -0
  55. package/src/params/index.ts +483 -0
  56. package/src/perf/compiler-optimization.ts +529 -0
  57. package/src/perf/hardware.ts +631 -0
  58. package/src/perf/index.ts +9 -0
  59. package/src/perf/kernel-bypass.ts +656 -0
  60. package/src/perf/protocol.ts +682 -0
  61. package/src/perf/realtime.ts +592 -0
  62. package/src/perf/simd.ts +668 -0
  63. package/src/perf/syscall-bypass.ts +331 -0
  64. package/src/perf/ultra-low-latency.ts +505 -0
  65. package/src/perf/zero-copy.ts +589 -0
  66. package/src/pool/pool.ts +294 -0
  67. package/src/rpc/client.ts +345 -0
  68. package/src/sdk-errors.ts +13 -0
  69. package/src/security/index.ts +26 -0
  70. package/src/security/secure-key.ts +303 -0
  71. package/src/security/validators.ts +281 -0
  72. package/src/seed/pda.ts +262 -0
  73. package/src/serialization/index.ts +28 -0
  74. package/src/serialization/serialization.ts +288 -0
  75. package/src/swqos/clients.ts +1754 -0
  76. package/src/swqos/index.ts +50 -0
  77. package/src/swqos/providers.ts +1707 -0
  78. package/src/trading/core/async-executor.ts +702 -0
  79. package/src/trading/core/confirmation-monitor.ts +711 -0
  80. package/src/trading/core/index.ts +82 -0
  81. package/src/trading/core/retry-handler.ts +683 -0
  82. package/src/trading/core/transaction-pool.ts +780 -0
  83. package/src/trading/executor.ts +385 -0
  84. package/src/trading/factory.ts +282 -0
  85. package/src/trading/index.ts +30 -0
  86. package/src/types.ts +8 -0
  87. package/src/utils/index.ts +155 -0
@@ -0,0 +1,3742 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/perf/index.ts
21
+ var perf_exports = {};
22
+ __export(perf_exports, {
23
+ AlignedBuffer: () => AlignedBuffer,
24
+ AsyncSocket: () => AsyncSocket,
25
+ BranchOptimizer: () => BranchOptimizer,
26
+ BufferPool: () => BufferPool,
27
+ CACHE_LINE_SIZE: () => CACHE_LINE_SIZE,
28
+ CPUAffinity: () => CPUAffinity,
29
+ CacheOptimizer: () => CacheOptimizer,
30
+ ComputeBudgetOptimizer: () => ComputeBudgetOptimizer,
31
+ CryptoSIMD: () => CryptoSIMD,
32
+ DirectIOFile: () => DirectIOFile,
33
+ FastTimeProvider: () => FastTimeProvider,
34
+ FixedBufferView: () => FixedBufferView,
35
+ Float32x4: () => Float32x4,
36
+ FuncCache: () => FuncCache,
37
+ HardwareMonitor: () => HardwareMonitor,
38
+ IOBatchProcessor: () => IOBatchProcessor,
39
+ IOOperation: () => IOOperation,
40
+ InstructionBatcher: () => InstructionBatcher,
41
+ KernelBypassManager: () => KernelBypassManager,
42
+ LatencyMonitor: () => LatencyMonitor,
43
+ LatencyOptimizer: () => LatencyOptimizer,
44
+ LockFreeQueue: () => LockFreeQueue,
45
+ LoopOptimizer: () => LoopOptimizer,
46
+ MPMCQueue: () => MPMCQueue,
47
+ MemoryMappedFile: () => MemoryMappedFile,
48
+ MemoryOps: () => MemoryOps,
49
+ MemoryPool: () => MemoryPool,
50
+ NUMAOptimizer: () => NUMAOptimizer,
51
+ OptimizedMath: () => OptimizedMath,
52
+ PerformanceGovernor: () => PerformanceGovernor,
53
+ ProfileGuidedOptimizer: () => ProfileGuidedOptimizer,
54
+ RealtimeTuner: () => RealtimeTuner,
55
+ SIMDDetector: () => SIMDDetector,
56
+ SchedulerPolicy: () => SchedulerPolicy,
57
+ SpinLock: () => SpinLock,
58
+ SyscallBypassManager: () => SyscallBypassManager,
59
+ ThreadPriority: () => ThreadPriority,
60
+ ThreadPriorityLevel: () => ThreadPriorityLevel,
61
+ TransactionBuilder: () => TransactionBuilder,
62
+ TransactionOptimizer: () => TransactionOptimizer,
63
+ VectorizedMath: () => VectorizedMath,
64
+ ZeroCopyBuffer: () => ZeroCopyBuffer,
65
+ ZeroCopySerializer: () => ZeroCopySerializer,
66
+ busySpin: () => busySpin,
67
+ busyWait: () => busyWait,
68
+ calculateOptimalPrice: () => calculateOptimalPrice,
69
+ coldPath: () => coldPath,
70
+ copyBytes: () => copyBytes,
71
+ createBufferPool: () => createBufferPool,
72
+ createCPUAffinity: () => createCPUAffinity,
73
+ createCacheOptimizer: () => createCacheOptimizer,
74
+ createComputeBudgetOptimizer: () => createComputeBudgetOptimizer,
75
+ createCryptoSIMD: () => createCryptoSIMD,
76
+ createHardwareMonitor: () => createHardwareMonitor,
77
+ createInstructionBatcher: () => createInstructionBatcher,
78
+ createLatencyMonitor: () => createLatencyMonitor,
79
+ createLockFreeQueue: () => createLockFreeQueue,
80
+ createMPMCQueue: () => createMPMCQueue,
81
+ createMemoryPool: () => createMemoryPool,
82
+ createNUMAOptimizer: () => createNUMAOptimizer,
83
+ createPerformanceGovernor: () => createPerformanceGovernor,
84
+ createRealtimeTuner: () => createRealtimeTuner,
85
+ createSIMDDetector: () => createSIMDDetector,
86
+ createSerializer: () => createSerializer,
87
+ createSyscallBypassManager: () => createSyscallBypassManager,
88
+ createThreadPriority: () => createThreadPriority,
89
+ createTimer: () => createTimer,
90
+ createTransactionBuilder: () => createTransactionBuilder,
91
+ createTransactionOptimizer: () => createTransactionOptimizer,
92
+ createVectorizedMath: () => createVectorizedMath,
93
+ createView: () => createView,
94
+ createZeroCopyBuffer: () => createZeroCopyBuffer,
95
+ defaultAffinityConfig: () => defaultAffinityConfig,
96
+ defaultBufferPoolConfig: () => defaultBufferPoolConfig,
97
+ defaultIOUringConfig: () => defaultIOUringConfig,
98
+ defaultJITConfig: () => defaultJITConfig,
99
+ defaultNUMAConfig: () => defaultNUMAConfig,
100
+ defaultRealtimeConfig: () => defaultRealtimeConfig,
101
+ defaultSIMDConfig: () => defaultSIMDConfig,
102
+ defaultSyscallBypassConfig: () => defaultSyscallBypassConfig,
103
+ defaultTransactionConfig: () => defaultTransactionConfig,
104
+ defaultUltraLowLatencyConfig: () => defaultUltraLowLatencyConfig,
105
+ detectCPUFeatures: () => detectCPUFeatures,
106
+ estimateCompute: () => estimateCompute,
107
+ fastInvSqrt: () => fastInvSqrt,
108
+ fastNowMs: () => fastNowMs,
109
+ fastNowNs: () => fastNowNs,
110
+ fastNowUs: () => fastNowUs,
111
+ getGlobalTimeProvider: () => getGlobalTimeProvider,
112
+ getKernelBypassManager: () => getKernelBypassManager,
113
+ getOptimalSIMDWidth: () => getOptimalSIMDWidth,
114
+ getProfileOptimizer: () => getProfileOptimizer,
115
+ getSystemCPUInfo: () => getSystemCPUInfo,
116
+ getSystemMemoryInfo: () => getSystemMemoryInfo,
117
+ hotPath: () => hotPath,
118
+ isSIMDAvailable: () => isSIMDAvailable,
119
+ likely: () => likely,
120
+ measureTime: () => measureTime,
121
+ prefetch: () => prefetch,
122
+ prefetchArray: () => prefetchArray,
123
+ prefetchHint: () => prefetchHint,
124
+ profile: () => profile,
125
+ spinLock: () => spinLock,
126
+ unlikely: () => unlikely,
127
+ yieldToEventLoop: () => yieldToEventLoop
128
+ });
129
+ module.exports = __toCommonJS(perf_exports);
130
+
131
+ // src/perf/compiler-optimization.ts
132
+ function defaultJITConfig() {
133
+ return {
134
+ enabled: true,
135
+ cacheSize: 128,
136
+ optimizationLevel: "O3",
137
+ inlineThreshold: 1e3,
138
+ loopVectorize: true,
139
+ slpVectorize: true
140
+ };
141
+ }
142
+ var BranchOptimizer = class {
143
+ /**
144
+ * Hint that the condition is likely true
145
+ * Use this to guide branch prediction in hot paths
146
+ */
147
+ static likely(condition) {
148
+ return condition;
149
+ }
150
+ /**
151
+ * Hint that the condition is likely false
152
+ * Use this to guide branch prediction in error handling paths
153
+ */
154
+ static unlikely(condition) {
155
+ return condition;
156
+ }
157
+ };
158
+ function likely(condition) {
159
+ return condition;
160
+ }
161
+ function unlikely(condition) {
162
+ return condition;
163
+ }
164
+ var LoopOptimizer = class {
165
+ /**
166
+ * Hint that a loop should be unrolled
167
+ */
168
+ static unrollHint(factor) {
169
+ return factor;
170
+ }
171
+ /**
172
+ * Hint that a loop should be vectorized
173
+ */
174
+ static vectorizeHint() {
175
+ }
176
+ /**
177
+ * Hint that a loop should be parallelized
178
+ */
179
+ static parallelHint() {
180
+ }
181
+ };
182
+ var CACHE_LINE_SIZE = 64;
183
+ var AlignedBuffer = class {
184
+ data;
185
+ offset;
186
+ constructor(size, align = CACHE_LINE_SIZE) {
187
+ const padded = size + align;
188
+ this.data = Buffer.alloc(padded);
189
+ this.offset = 0;
190
+ }
191
+ /**
192
+ * Get the aligned buffer
193
+ */
194
+ get buffer() {
195
+ return this.data.slice(this.offset);
196
+ }
197
+ /**
198
+ * Get the underlying buffer
199
+ */
200
+ get underlying() {
201
+ return this.data;
202
+ }
203
+ };
204
+ function prefetchHint(address) {
205
+ }
206
+ var ProfileGuidedOptimizer = class {
207
+ profileData = /* @__PURE__ */ new Map();
208
+ callCounts = /* @__PURE__ */ new Map();
209
+ /**
210
+ * Instrument a function for profiling
211
+ */
212
+ instrument(name, fn) {
213
+ const self = this;
214
+ return (function(...args) {
215
+ const count = (self.callCounts.get(name) || 0) + 1;
216
+ self.callCounts.set(name, count);
217
+ const start = performance.now();
218
+ const result = fn.apply(this, args);
219
+ const elapsed = performance.now() - start;
220
+ let profile2 = self.profileData.get(name);
221
+ if (!profile2) {
222
+ profile2 = {
223
+ calls: 0,
224
+ totalTime: 0,
225
+ minTime: Infinity,
226
+ maxTime: 0
227
+ };
228
+ self.profileData.set(name, profile2);
229
+ }
230
+ profile2.calls = count;
231
+ profile2.totalTime += elapsed;
232
+ if (elapsed < profile2.minTime) {
233
+ profile2.minTime = elapsed;
234
+ }
235
+ if (elapsed > profile2.maxTime) {
236
+ profile2.maxTime = elapsed;
237
+ }
238
+ return result;
239
+ });
240
+ }
241
+ /**
242
+ * Get the most frequently called functions
243
+ */
244
+ getHotFunctions(topN = 10) {
245
+ const results = [];
246
+ this.callCounts.forEach((count, name) => {
247
+ results.push({ name, count });
248
+ });
249
+ results.sort((a, b) => b.count - a.count);
250
+ return results.slice(0, topN);
251
+ }
252
+ /**
253
+ * Get functions with highest average execution time
254
+ */
255
+ getSlowFunctions(topN = 10) {
256
+ const results = [];
257
+ this.profileData.forEach((profile2, name) => {
258
+ if (profile2.calls > 0) {
259
+ results.push({
260
+ name,
261
+ avgTime: profile2.totalTime / profile2.calls
262
+ });
263
+ }
264
+ });
265
+ results.sort((a, b) => b.avgTime - a.avgTime);
266
+ return results.slice(0, topN);
267
+ }
268
+ };
269
+ var OptimizedMath = class {
270
+ /**
271
+ * Fast exponential approximation
272
+ */
273
+ static fastExp(x) {
274
+ if (x < -708) return 0;
275
+ if (x > 709) return Infinity;
276
+ return Math.exp(x);
277
+ }
278
+ /**
279
+ * Fast logarithm
280
+ */
281
+ static fastLog(x) {
282
+ return Math.log(x);
283
+ }
284
+ /**
285
+ * Fast square root
286
+ */
287
+ static fastSqrt(x) {
288
+ return Math.sqrt(x);
289
+ }
290
+ /**
291
+ * Fast inverse square root (Quake III algorithm)
292
+ */
293
+ static fastInvSqrt(x) {
294
+ if (x <= 0) return Infinity;
295
+ const threehalfs = 1.5;
296
+ const x2 = x * 0.5;
297
+ let y = x;
298
+ const buf = new ArrayBuffer(4);
299
+ const f32 = new Float32Array(buf);
300
+ const u32 = new Uint32Array(buf);
301
+ f32[0] = y;
302
+ u32[0] = 1597463007 - (u32[0] >> 1);
303
+ y = f32[0];
304
+ y = y * (threehalfs - x2 * y * y);
305
+ return y;
306
+ }
307
+ /**
308
+ * Fast power
309
+ */
310
+ static fastPow(base, exp) {
311
+ return Math.pow(base, exp);
312
+ }
313
+ /**
314
+ * Fast absolute value for integers
315
+ */
316
+ static fastAbs(x) {
317
+ return x < 0 ? -x : x;
318
+ }
319
+ };
320
+ function fastInvSqrt(x) {
321
+ return OptimizedMath.fastInvSqrt(x);
322
+ }
323
+ var FuncCache = class {
324
+ cache = /* @__PURE__ */ new Map();
325
+ hits = 0;
326
+ misses = 0;
327
+ maxSize;
328
+ constructor(maxSize = 128) {
329
+ this.maxSize = maxSize;
330
+ }
331
+ /**
332
+ * Get a cached value
333
+ */
334
+ get(key) {
335
+ const value = this.cache.get(key);
336
+ if (value !== void 0) {
337
+ this.hits++;
338
+ return value;
339
+ }
340
+ this.misses++;
341
+ return void 0;
342
+ }
343
+ /**
344
+ * Set a cached value
345
+ */
346
+ set(key, value) {
347
+ if (this.cache.size >= this.maxSize) {
348
+ const firstKey = this.cache.keys().next().value;
349
+ if (firstKey !== void 0) {
350
+ this.cache.delete(firstKey);
351
+ }
352
+ }
353
+ this.cache.set(key, value);
354
+ }
355
+ /**
356
+ * Get cache statistics
357
+ */
358
+ stats() {
359
+ const total = this.hits + this.misses;
360
+ return {
361
+ hits: this.hits,
362
+ misses: this.misses,
363
+ hitRate: total > 0 ? this.hits / total : 0
364
+ };
365
+ }
366
+ /**
367
+ * Clear the cache
368
+ */
369
+ clear() {
370
+ this.cache.clear();
371
+ this.hits = 0;
372
+ this.misses = 0;
373
+ }
374
+ };
375
+ var SpinLock = class {
376
+ locked = false;
377
+ /**
378
+ * Acquire the lock
379
+ */
380
+ async lock() {
381
+ while (this.locked) {
382
+ await new Promise((resolve) => setImmediate(resolve));
383
+ }
384
+ this.locked = true;
385
+ }
386
+ /**
387
+ * Release the lock
388
+ */
389
+ unlock() {
390
+ this.locked = false;
391
+ }
392
+ /**
393
+ * Try to acquire the lock without blocking
394
+ */
395
+ tryLock() {
396
+ if (this.locked) {
397
+ return false;
398
+ }
399
+ this.locked = true;
400
+ return true;
401
+ }
402
+ };
403
+ function hotPath() {
404
+ }
405
+ function coldPath() {
406
+ }
407
+ var MemoryOps = class {
408
+ /**
409
+ * Copy memory with potential SIMD optimization
410
+ */
411
+ static memCopy(dst, src) {
412
+ const n = Math.min(dst.length, src.length);
413
+ dst.set(src.slice(0, n));
414
+ return n;
415
+ }
416
+ /**
417
+ * Set memory with potential SIMD optimization
418
+ */
419
+ static memSet(dst, value) {
420
+ dst.fill(value);
421
+ }
422
+ /**
423
+ * Zero memory
424
+ */
425
+ static memZero(dst) {
426
+ dst.fill(0);
427
+ }
428
+ };
429
+ function detectCPUFeatures() {
430
+ return {
431
+ hasSIMD: true,
432
+ // V8 has SIMD optimizations
433
+ hasAVX: false,
434
+ // Not detectable in JS
435
+ hasAVX2: false,
436
+ hasSSE: false,
437
+ hasSSE2: false,
438
+ hasSSE3: false,
439
+ hasSSE41: false,
440
+ hasSSE42: false,
441
+ hasFMA: false,
442
+ hasBMI: false,
443
+ hasBMI2: false,
444
+ hasPopcnt: false,
445
+ cacheLine: CACHE_LINE_SIZE,
446
+ numCPU: require("os").cpus().length
447
+ };
448
+ }
449
+ var globalProfileOptimizer = null;
450
+ function getProfileOptimizer() {
451
+ if (!globalProfileOptimizer) {
452
+ globalProfileOptimizer = new ProfileGuidedOptimizer();
453
+ }
454
+ return globalProfileOptimizer;
455
+ }
456
+ function profile(target, propertyKey, descriptor) {
457
+ const original = descriptor.value;
458
+ const optimizer = getProfileOptimizer();
459
+ const name = `${target.constructor.name}.${propertyKey}`;
460
+ descriptor.value = optimizer.instrument(name, original);
461
+ return descriptor;
462
+ }
463
+
464
+ // src/perf/hardware.ts
465
+ function defaultAffinityConfig() {
466
+ return {
467
+ enablePinning: false,
468
+ preferredCores: [],
469
+ avoidSMT: true,
470
+ numaNode: 0
471
+ };
472
+ }
473
+ function defaultNUMAConfig() {
474
+ return {
475
+ enableNUMA: false,
476
+ preferredNode: 0,
477
+ interleave: false
478
+ };
479
+ }
480
+ var CPUAffinity = class {
481
+ config;
482
+ pinnedCores = /* @__PURE__ */ new Set();
483
+ constructor(config = defaultAffinityConfig()) {
484
+ this.config = config;
485
+ }
486
+ /**
487
+ * Get CPU topology information
488
+ */
489
+ getTopology() {
490
+ const os = require("os");
491
+ const cpus = os.cpus();
492
+ const logicalCores = cpus.length;
493
+ const physicalCores = Math.ceil(logicalCores / 2);
494
+ return {
495
+ physicalCores,
496
+ logicalCores,
497
+ numaNodes: 1,
498
+ // Node.js doesn't expose NUMA info
499
+ cacheLevels: [
500
+ { level: 1, size: 32 * 1024, lineSize: 64, associativity: 8 },
501
+ { level: 2, size: 256 * 1024, lineSize: 64, associativity: 8 },
502
+ { level: 3, size: 8 * 1024 * 1024, lineSize: 64, associativity: 16 }
503
+ ]
504
+ };
505
+ }
506
+ /**
507
+ * Pin current execution context to a specific core
508
+ * Note: In Node.js, this is advisory only via worker threads
509
+ */
510
+ pinToCore(coreId) {
511
+ if (!this.config.enablePinning) {
512
+ return false;
513
+ }
514
+ this.pinnedCores.add(coreId);
515
+ return true;
516
+ }
517
+ /**
518
+ * Pin to multiple cores
519
+ */
520
+ pinToCores(coreIds) {
521
+ if (!this.config.enablePinning) {
522
+ return false;
523
+ }
524
+ for (const coreId of coreIds) {
525
+ this.pinnedCores.add(coreId);
526
+ }
527
+ return true;
528
+ }
529
+ /**
530
+ * Get recommended cores for pinning
531
+ */
532
+ getRecommendedCores(count = 1) {
533
+ const topology = this.getTopology();
534
+ const cores = [];
535
+ if (this.config.preferredCores.length > 0) {
536
+ for (let i = 0; i < count && i < this.config.preferredCores.length; i++) {
537
+ cores.push(this.config.preferredCores[i]);
538
+ }
539
+ } else {
540
+ const step = this.config.avoidSMT ? 2 : 1;
541
+ for (let i = 0; i < count * step && i < topology.physicalCores; i += step) {
542
+ cores.push(i);
543
+ }
544
+ }
545
+ return cores;
546
+ }
547
+ /**
548
+ * Check if a core is available
549
+ */
550
+ isCoreAvailable(coreId) {
551
+ const topology = this.getTopology();
552
+ return coreId >= 0 && coreId < topology.logicalCores;
553
+ }
554
+ /**
555
+ * Get current core (simulated)
556
+ */
557
+ getCurrentCore() {
558
+ return 0;
559
+ }
560
+ /**
561
+ * Get pinned cores
562
+ */
563
+ getPinnedCores() {
564
+ return Array.from(this.pinnedCores);
565
+ }
566
+ /**
567
+ * Unpin all cores
568
+ */
569
+ unpinAll() {
570
+ this.pinnedCores.clear();
571
+ }
572
+ };
573
+ var NUMAOptimizer = class {
574
+ config;
575
+ allocations = /* @__PURE__ */ new Map();
576
+ constructor(config = defaultNUMAConfig()) {
577
+ this.config = config;
578
+ }
579
+ /**
580
+ * Allocate memory with NUMA awareness
581
+ */
582
+ allocate(size, tag = "default") {
583
+ const buffer = new ArrayBuffer(size);
584
+ this.allocations.set(tag, {
585
+ buffer,
586
+ size,
587
+ node: this.config.preferredNode,
588
+ timestamp: Date.now()
589
+ });
590
+ return buffer;
591
+ }
592
+ /**
593
+ * Allocate typed array with NUMA awareness
594
+ */
595
+ allocateTypedArray(constructor, length, tag = "default") {
596
+ const bytesPerElement = constructor.BYTES_PER_ELEMENT;
597
+ const buffer = this.allocate(length * bytesPerElement, tag);
598
+ return new constructor(buffer);
599
+ }
600
+ /**
601
+ * Get allocation information
602
+ */
603
+ getAllocation(tag) {
604
+ return this.allocations.get(tag);
605
+ }
606
+ /**
607
+ * Get local memory node for current thread
608
+ */
609
+ getLocalNode() {
610
+ return this.config.preferredNode;
611
+ }
612
+ /**
613
+ * Get number of NUMA nodes
614
+ */
615
+ getNodeCount() {
616
+ return 1;
617
+ }
618
+ /**
619
+ * Check if NUMA is available
620
+ */
621
+ isNUMAAvailable() {
622
+ return false;
623
+ }
624
+ /**
625
+ * Migrate allocation to preferred node
626
+ * Note: No-op in JavaScript
627
+ */
628
+ migrateToNode(tag, node) {
629
+ const allocation = this.allocations.get(tag);
630
+ if (!allocation) {
631
+ return false;
632
+ }
633
+ allocation.node = node;
634
+ return true;
635
+ }
636
+ /**
637
+ * Free allocation tracking
638
+ */
639
+ free(tag) {
640
+ this.allocations.delete(tag);
641
+ }
642
+ /**
643
+ * Get all allocations
644
+ */
645
+ getAllAllocations() {
646
+ return new Map(this.allocations);
647
+ }
648
+ };
649
+ var CacheOptimizer = class {
650
+ cacheLineSize = 64;
651
+ l1Size = 32 * 1024;
652
+ l2Size = 256 * 1024;
653
+ l3Size = 8 * 1024 * 1024;
654
+ constructor() {
655
+ }
656
+ /**
657
+ * Set cache parameters
658
+ */
659
+ setCacheParams(params) {
660
+ if (params.cacheLineSize) this.cacheLineSize = params.cacheLineSize;
661
+ if (params.l1Size) this.l1Size = params.l1Size;
662
+ if (params.l2Size) this.l2Size = params.l2Size;
663
+ if (params.l3Size) this.l3Size = params.l3Size;
664
+ }
665
+ /**
666
+ * Align size to cache line boundary
667
+ */
668
+ alignToCacheLine(size) {
669
+ const mask = this.cacheLineSize - 1;
670
+ return size + mask & ~mask;
671
+ }
672
+ /**
673
+ * Check if address is cache line aligned
674
+ */
675
+ isCacheLineAligned(address) {
676
+ return (address & this.cacheLineSize - 1) === 0;
677
+ }
678
+ /**
679
+ * Calculate cache-friendly array stride
680
+ */
681
+ calculateStride(elementSize) {
682
+ return Math.max(elementSize, this.cacheLineSize);
683
+ }
684
+ /**
685
+ * Create cache-friendly layout for array of objects
686
+ */
687
+ createSoALayout(count, schema) {
688
+ const typeSizes = {
689
+ u8: 1,
690
+ u16: 2,
691
+ u32: 4,
692
+ u64: 8,
693
+ f32: 4,
694
+ f64: 8
695
+ };
696
+ const arrays = {};
697
+ const offsets = {};
698
+ let currentOffset = 0;
699
+ for (const [key, type] of Object.entries(schema)) {
700
+ const size = typeSizes[type];
701
+ if (size === void 0) {
702
+ throw new Error(`Unsupported struct field type: ${type}`);
703
+ }
704
+ const alignedOffset = this.alignToCacheLine(currentOffset);
705
+ offsets[key] = alignedOffset;
706
+ const totalSize = alignedOffset + count * size;
707
+ const buffer = new ArrayBuffer(totalSize);
708
+ switch (type) {
709
+ case "u8":
710
+ arrays[key] = new Uint8Array(buffer, alignedOffset, count);
711
+ break;
712
+ case "u16":
713
+ arrays[key] = new Uint16Array(buffer, alignedOffset, count);
714
+ break;
715
+ case "u32":
716
+ arrays[key] = new Uint32Array(buffer, alignedOffset, count);
717
+ break;
718
+ case "u64":
719
+ arrays[key] = new BigUint64Array(buffer, alignedOffset, count);
720
+ break;
721
+ case "f32":
722
+ arrays[key] = new Float32Array(buffer, alignedOffset, count);
723
+ break;
724
+ case "f64":
725
+ arrays[key] = new Float64Array(buffer, alignedOffset, count);
726
+ break;
727
+ }
728
+ currentOffset = alignedOffset + count * size;
729
+ }
730
+ return {
731
+ arrays,
732
+ offsets,
733
+ count,
734
+ get(index) {
735
+ const result = {};
736
+ for (const key of Object.keys(arrays)) {
737
+ result[key] = arrays[key][index];
738
+ }
739
+ return result;
740
+ },
741
+ set(index, value) {
742
+ for (const key of Object.keys(arrays)) {
743
+ arrays[key][index] = value[key];
744
+ }
745
+ }
746
+ };
747
+ }
748
+ /**
749
+ * Get cache line size
750
+ */
751
+ getCacheLineSize() {
752
+ return this.cacheLineSize;
753
+ }
754
+ /**
755
+ * Get L1 cache size
756
+ */
757
+ getL1Size() {
758
+ return this.l1Size;
759
+ }
760
+ /**
761
+ * Get L2 cache size
762
+ */
763
+ getL2Size() {
764
+ return this.l2Size;
765
+ }
766
+ /**
767
+ * Get L3 cache size
768
+ */
769
+ getL3Size() {
770
+ return this.l3Size;
771
+ }
772
+ };
773
+ var HardwareMonitor = class {
774
+ startTime = 0;
775
+ measurements = [];
776
+ /**
777
+ * Start monitoring
778
+ */
779
+ start() {
780
+ this.startTime = performance.now();
781
+ }
782
+ /**
783
+ * Take a measurement
784
+ */
785
+ measure(label) {
786
+ this.measurements.push({
787
+ label,
788
+ timestamp: performance.now() - this.startTime,
789
+ memory: this.getMemoryInfo()
790
+ });
791
+ }
792
+ /**
793
+ * Get memory information
794
+ */
795
+ getMemoryInfo() {
796
+ if (typeof process !== "undefined" && process.memoryUsage) {
797
+ const usage = process.memoryUsage();
798
+ return {
799
+ used: usage.heapUsed,
800
+ total: usage.heapTotal,
801
+ external: usage.external,
802
+ rss: usage.rss
803
+ };
804
+ }
805
+ if (typeof performance !== "undefined" && performance.memory) {
806
+ const mem = performance.memory;
807
+ return {
808
+ used: mem.usedJSHeapSize,
809
+ total: mem.totalJSHeapSize,
810
+ external: 0,
811
+ rss: 0
812
+ };
813
+ }
814
+ return { used: 0, total: 0, external: 0, rss: 0 };
815
+ }
816
+ /**
817
+ * Get all measurements
818
+ */
819
+ getMeasurements() {
820
+ return [...this.measurements];
821
+ }
822
+ /**
823
+ * Reset measurements
824
+ */
825
+ reset() {
826
+ this.measurements = [];
827
+ this.startTime = performance.now();
828
+ }
829
+ };
830
+ function createCPUAffinity(config) {
831
+ const fullConfig = { ...defaultAffinityConfig(), ...config };
832
+ return new CPUAffinity(fullConfig);
833
+ }
834
+ function createNUMAOptimizer(config) {
835
+ const fullConfig = { ...defaultNUMAConfig(), ...config };
836
+ return new NUMAOptimizer(fullConfig);
837
+ }
838
+ function createCacheOptimizer() {
839
+ return new CacheOptimizer();
840
+ }
841
+ function createHardwareMonitor() {
842
+ return new HardwareMonitor();
843
+ }
844
+ function getSystemCPUInfo() {
845
+ const os = require("os");
846
+ const cpus = os.cpus();
847
+ return {
848
+ cores: cpus.length,
849
+ model: cpus[0]?.model || "Unknown"
850
+ };
851
+ }
852
+ function getSystemMemoryInfo() {
853
+ const os = require("os");
854
+ return {
855
+ total: os.totalmem(),
856
+ free: os.freemem()
857
+ };
858
+ }
859
+
860
+ // src/perf/kernel-bypass.ts
861
+ var IOOperation = /* @__PURE__ */ ((IOOperation2) => {
862
+ IOOperation2["READ"] = "READ";
863
+ IOOperation2["WRITE"] = "WRITE";
864
+ IOOperation2["FSYNC"] = "FSYNC";
865
+ IOOperation2["POLL"] = "POLL";
866
+ IOOperation2["TIMEOUT"] = "TIMEOUT";
867
+ return IOOperation2;
868
+ })(IOOperation || {});
869
+ function defaultIOUringConfig() {
870
+ return {
871
+ queueDepth: 256,
872
+ sqThreadIdle: 2e3,
873
+ sqThreadCpu: -1,
874
+ cqSize: 0,
875
+ flags: 0,
876
+ features: []
877
+ };
878
+ }
879
+ var KernelBypassManager = class {
880
+ config;
881
+ uringAvailable = false;
882
+ requestCounter = 0;
883
+ pendingRequests = /* @__PURE__ */ new Map();
884
+ running = false;
885
+ processTimer = null;
886
+ constructor(config) {
887
+ this.config = config || defaultIOUringConfig();
888
+ this.checkUringAvailability();
889
+ }
890
+ /**
891
+ * Check if io_uring-like functionality is available
892
+ */
893
+ checkUringAvailability() {
894
+ if (process.platform !== "linux") {
895
+ return false;
896
+ }
897
+ this.uringAvailable = false;
898
+ return false;
899
+ }
900
+ /**
901
+ * Check if io_uring is available
902
+ */
903
+ isUringAvailable() {
904
+ return this.uringAvailable;
905
+ }
906
+ /**
907
+ * Start the I/O processing loop
908
+ */
909
+ start() {
910
+ if (this.running) return;
911
+ this.running = true;
912
+ this.processTimer = setInterval(() => {
913
+ this.processPendingRequests();
914
+ }, 0.1);
915
+ setImmediate(() => this.processLoop());
916
+ }
917
+ /**
918
+ * Stop the I/O processing loop
919
+ */
920
+ stop() {
921
+ this.running = false;
922
+ if (this.processTimer) {
923
+ clearInterval(this.processTimer);
924
+ this.processTimer = null;
925
+ }
926
+ }
927
+ /**
928
+ * Main processing loop
929
+ */
930
+ processLoop() {
931
+ if (!this.running) return;
932
+ this.processPendingRequests();
933
+ if (this.running) {
934
+ setImmediate(() => this.processLoop());
935
+ }
936
+ }
937
+ /**
938
+ * Process pending I/O requests
939
+ */
940
+ processPendingRequests() {
941
+ const toDelete = [];
942
+ this.pendingRequests.forEach((request, id) => {
943
+ switch (request.op) {
944
+ case "READ" /* READ */:
945
+ this.processRead(id, request);
946
+ break;
947
+ case "WRITE" /* WRITE */:
948
+ this.processWrite(id, request);
949
+ break;
950
+ }
951
+ toDelete.push(id);
952
+ });
953
+ toDelete.forEach((id) => this.pendingRequests.delete(id));
954
+ }
955
+ /**
956
+ * Process a read request
957
+ */
958
+ processRead(id, request) {
959
+ try {
960
+ const fs = require("fs");
961
+ const buffer = Buffer.alloc(request.size);
962
+ fs.read(request.fd, buffer, 0, request.size, request.offset, (err, bytesRead) => {
963
+ if (request.callback) {
964
+ request.callback(id, err ? null : buffer.slice(0, bytesRead), bytesRead);
965
+ }
966
+ });
967
+ } catch (error) {
968
+ if (request.callback) {
969
+ request.callback(id, null, 0);
970
+ }
971
+ }
972
+ }
973
+ /**
974
+ * Process a write request
975
+ */
976
+ processWrite(id, request) {
977
+ try {
978
+ const fs = require("fs");
979
+ fs.write(request.fd, request.buffer, 0, request.buffer.length, request.offset, (err, bytesWritten) => {
980
+ if (request.callback) {
981
+ request.callback(id, null, bytesWritten);
982
+ }
983
+ });
984
+ } catch (error) {
985
+ if (request.callback) {
986
+ request.callback(id, null, 0);
987
+ }
988
+ }
989
+ }
990
+ /**
991
+ * Submit an async read request
992
+ */
993
+ submitRead(fd, size, offset = 0, callback, userData) {
994
+ const id = ++this.requestCounter;
995
+ const request = {
996
+ op: "READ" /* READ */,
997
+ fd,
998
+ offset,
999
+ size,
1000
+ callback,
1001
+ userData
1002
+ };
1003
+ this.pendingRequests.set(id, request);
1004
+ return id;
1005
+ }
1006
+ /**
1007
+ * Submit an async write request
1008
+ */
1009
+ submitWrite(fd, buffer, offset = 0, callback, userData) {
1010
+ const id = ++this.requestCounter;
1011
+ const request = {
1012
+ op: "WRITE" /* WRITE */,
1013
+ fd,
1014
+ buffer,
1015
+ offset,
1016
+ size: buffer.length,
1017
+ callback,
1018
+ userData
1019
+ };
1020
+ this.pendingRequests.set(id, request);
1021
+ return id;
1022
+ }
1023
+ };
1024
+ var DirectIOFile = class {
1025
+ path;
1026
+ fd = null;
1027
+ directIO = false;
1028
+ constructor(path) {
1029
+ this.path = path;
1030
+ }
1031
+ /**
1032
+ * Open file with direct I/O if available
1033
+ */
1034
+ async open() {
1035
+ const fs = require("fs").promises;
1036
+ try {
1037
+ this.fd = await fs.open(this.path, "r+");
1038
+ this.directIO = process.platform === "linux";
1039
+ return true;
1040
+ } catch (error) {
1041
+ try {
1042
+ this.fd = await fs.open(this.path, "w+");
1043
+ return true;
1044
+ } catch {
1045
+ return false;
1046
+ }
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Close the file
1051
+ */
1052
+ async close() {
1053
+ if (this.fd !== null) {
1054
+ const fs = require("fs").promises;
1055
+ await fs.close(this.fd);
1056
+ this.fd = null;
1057
+ }
1058
+ }
1059
+ /**
1060
+ * Read from file
1061
+ */
1062
+ async read(size, offset = 0) {
1063
+ if (this.fd === null) {
1064
+ throw new Error("File not open");
1065
+ }
1066
+ if (this.directIO) {
1067
+ return this.readDirect(size, offset);
1068
+ }
1069
+ const fs = require("fs").promises;
1070
+ const buffer = Buffer.alloc(size);
1071
+ await fs.read(this.fd, buffer, 0, size, offset);
1072
+ return buffer;
1073
+ }
1074
+ /**
1075
+ * Read using direct I/O with aligned buffer
1076
+ */
1077
+ async readDirect(size, offset) {
1078
+ const align = 512;
1079
+ const alignedOffset = Math.floor(offset / align) * align;
1080
+ const offsetDiff = offset - alignedOffset;
1081
+ const alignedSize = Math.ceil((size + offsetDiff + align - 1) / align) * align;
1082
+ const buffer = Buffer.alloc(alignedSize);
1083
+ const fs = require("fs").promises;
1084
+ await fs.read(this.fd, buffer, 0, alignedSize, alignedOffset);
1085
+ return buffer.slice(offsetDiff, offsetDiff + size);
1086
+ }
1087
+ /**
1088
+ * Write to file
1089
+ */
1090
+ async write(data, offset = 0) {
1091
+ if (this.fd === null) {
1092
+ throw new Error("File not open");
1093
+ }
1094
+ const fs = require("fs").promises;
1095
+ const { bytesWritten } = await fs.write(this.fd, data, 0, data.length, offset);
1096
+ return bytesWritten;
1097
+ }
1098
+ /**
1099
+ * Sync file to disk
1100
+ */
1101
+ async fsync() {
1102
+ if (this.fd !== null) {
1103
+ const fs = require("fs").promises;
1104
+ await fs.fsync(this.fd);
1105
+ }
1106
+ }
1107
+ };
1108
+ var MemoryMappedFile = class {
1109
+ path;
1110
+ fd = null;
1111
+ buffer = null;
1112
+ constructor(path) {
1113
+ this.path = path;
1114
+ }
1115
+ /**
1116
+ * Open and memory-map the file
1117
+ */
1118
+ async open(size = 0) {
1119
+ const fs = require("fs");
1120
+ const fsPromises = fs.promises;
1121
+ try {
1122
+ const fileHandle = await fsPromises.open(this.path, "r+");
1123
+ this.fd = fileHandle.fd;
1124
+ const stats = await fileHandle.stat();
1125
+ let fileSize = stats.size;
1126
+ if (size > 0 && size > fileSize) {
1127
+ await fileHandle.truncate(size);
1128
+ fileSize = size;
1129
+ }
1130
+ if (fileSize === 0) {
1131
+ fileSize = 4096;
1132
+ await fileHandle.truncate(fileSize);
1133
+ }
1134
+ this.buffer = Buffer.alloc(fileSize);
1135
+ await fileHandle.read(this.buffer, 0, fileSize, 0);
1136
+ return true;
1137
+ } catch (error) {
1138
+ return false;
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Close the memory-mapped file
1143
+ */
1144
+ async close() {
1145
+ if (this.buffer) {
1146
+ const fs = require("fs").promises;
1147
+ if (this.fd !== null) {
1148
+ await fs.write(this.fd, this.buffer, 0, this.buffer.length, 0);
1149
+ }
1150
+ this.buffer = null;
1151
+ }
1152
+ if (this.fd !== null) {
1153
+ const fs = require("fs").promises;
1154
+ await fs.close(this.fd);
1155
+ this.fd = null;
1156
+ }
1157
+ }
1158
+ /**
1159
+ * Read from memory-mapped file
1160
+ */
1161
+ read(offset, size) {
1162
+ if (!this.buffer) {
1163
+ throw new Error("File not mapped");
1164
+ }
1165
+ return this.buffer.slice(offset, offset + size);
1166
+ }
1167
+ /**
1168
+ * Write to memory-mapped file
1169
+ */
1170
+ write(offset, data) {
1171
+ if (!this.buffer) {
1172
+ throw new Error("File not mapped");
1173
+ }
1174
+ data.copy(this.buffer, offset);
1175
+ }
1176
+ /**
1177
+ * Flush changes to disk
1178
+ */
1179
+ async flush() {
1180
+ if (this.buffer && this.fd !== null) {
1181
+ const fs = require("fs").promises;
1182
+ await fs.write(this.fd, this.buffer, 0, this.buffer.length, 0);
1183
+ }
1184
+ }
1185
+ };
1186
+ var AsyncSocket = class {
1187
+ socket = null;
1188
+ /**
1189
+ * Set the underlying socket
1190
+ */
1191
+ setSocket(socket) {
1192
+ this.socket = socket;
1193
+ }
1194
+ /**
1195
+ * Enable kernel bypass optimizations for this socket
1196
+ */
1197
+ enableKernelBypass() {
1198
+ if (!this.socket) {
1199
+ return false;
1200
+ }
1201
+ try {
1202
+ this.socket.setNoDelay(true);
1203
+ this.socket.setKeepAlive(true, 1e3);
1204
+ return true;
1205
+ } catch (error) {
1206
+ return false;
1207
+ }
1208
+ }
1209
+ /**
1210
+ * Async receive with optimization
1211
+ */
1212
+ async recv(size) {
1213
+ return new Promise((resolve, reject) => {
1214
+ if (!this.socket) {
1215
+ reject(new Error("Socket not set"));
1216
+ return;
1217
+ }
1218
+ this.socket.once("data", (data) => {
1219
+ resolve(data);
1220
+ });
1221
+ this.socket.once("error", reject);
1222
+ });
1223
+ }
1224
+ /**
1225
+ * Async send with optimization
1226
+ */
1227
+ async send(data) {
1228
+ return new Promise((resolve, reject) => {
1229
+ if (!this.socket) {
1230
+ reject(new Error("Socket not set"));
1231
+ return;
1232
+ }
1233
+ this.socket.write(data, (err) => {
1234
+ if (err) {
1235
+ reject(err);
1236
+ } else {
1237
+ resolve();
1238
+ }
1239
+ });
1240
+ });
1241
+ }
1242
+ };
1243
+ var IOBatchProcessor = class {
1244
+ maxBatchSize;
1245
+ readBatch = [];
1246
+ writeBatch = [];
1247
+ manager;
1248
+ constructor(maxBatchSize = 32) {
1249
+ this.maxBatchSize = maxBatchSize;
1250
+ this.manager = new KernelBypassManager();
1251
+ }
1252
+ /**
1253
+ * Add read to batch
1254
+ */
1255
+ addRead(fd, size, offset = 0, callback = () => {
1256
+ }) {
1257
+ this.readBatch.push({ fd, size, offset, callback });
1258
+ if (this.readBatch.length >= this.maxBatchSize) {
1259
+ this.flushReads();
1260
+ }
1261
+ }
1262
+ /**
1263
+ * Add write to batch
1264
+ */
1265
+ addWrite(fd, data, offset = 0, callback = () => {
1266
+ }) {
1267
+ this.writeBatch.push({ fd, data, offset, callback });
1268
+ if (this.writeBatch.length >= this.maxBatchSize) {
1269
+ this.flushWrites();
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Flush all pending reads
1274
+ */
1275
+ flushReads() {
1276
+ if (this.readBatch.length === 0) {
1277
+ return [];
1278
+ }
1279
+ const requestIds = this.readBatch.map(
1280
+ (req) => this.manager.submitRead(req.fd, req.size, req.offset, req.callback)
1281
+ );
1282
+ this.readBatch = [];
1283
+ return requestIds;
1284
+ }
1285
+ /**
1286
+ * Flush all pending writes
1287
+ */
1288
+ flushWrites() {
1289
+ if (this.writeBatch.length === 0) {
1290
+ return [];
1291
+ }
1292
+ const requestIds = this.writeBatch.map(
1293
+ (req) => this.manager.submitWrite(req.fd, req.data, req.offset, req.callback)
1294
+ );
1295
+ this.writeBatch = [];
1296
+ return requestIds;
1297
+ }
1298
+ /**
1299
+ * Flush all pending operations
1300
+ */
1301
+ flushAll() {
1302
+ return {
1303
+ readIds: this.flushReads(),
1304
+ writeIds: this.flushWrites()
1305
+ };
1306
+ }
1307
+ };
1308
+ var globalKBManager = null;
1309
+ function getKernelBypassManager(config) {
1310
+ if (!globalKBManager) {
1311
+ globalKBManager = new KernelBypassManager(config);
1312
+ }
1313
+ return globalKBManager;
1314
+ }
1315
+
1316
+ // src/perf/protocol.ts
1317
+ var import_web3 = require("@solana/web3.js");
1318
+ function defaultTransactionConfig() {
1319
+ return {
1320
+ computeUnitLimit: 2e5,
1321
+ computeUnitPrice: 1e5,
1322
+ priorityFee: 1e5,
1323
+ dynamicComputeBudget: true,
1324
+ packInstructions: true,
1325
+ maxTransactionSize: 1232,
1326
+ // Solana transaction size limit
1327
+ useAddressLookupTables: true
1328
+ };
1329
+ }
1330
+ var TransactionBuilder = class {
1331
+ instructions = [];
1332
+ config;
1333
+ computeEstimates = /* @__PURE__ */ new Map();
1334
+ signers = [];
1335
+ constructor(config = defaultTransactionConfig()) {
1336
+ this.config = config;
1337
+ this.initializeComputeEstimates();
1338
+ }
1339
+ /**
1340
+ * Initialize default compute estimates for common instructions
1341
+ */
1342
+ initializeComputeEstimates() {
1343
+ this.computeEstimates.set("transfer", 450);
1344
+ this.computeEstimates.set("createAccount", 2500);
1345
+ this.computeEstimates.set("createATA", 3500);
1346
+ this.computeEstimates.set("closeAccount", 2500);
1347
+ this.computeEstimates.set("syncNative", 500);
1348
+ this.computeEstimates.set("setComputeUnitLimit", 100);
1349
+ this.computeEstimates.set("setComputeUnitPrice", 100);
1350
+ this.computeEstimates.set("pumpFunBuy", 45e3);
1351
+ this.computeEstimates.set("pumpFunSell", 4e4);
1352
+ this.computeEstimates.set("pumpSwapBuy", 5e4);
1353
+ this.computeEstimates.set("pumpSwapSell", 45e3);
1354
+ this.computeEstimates.set("raydiumSwap", 55e3);
1355
+ this.computeEstimates.set("meteoraSwap", 6e4);
1356
+ }
1357
+ /**
1358
+ * Add an instruction to the transaction
1359
+ */
1360
+ addInstruction(instruction, computeEstimate, priority = 0) {
1361
+ this.instructions.push(instruction);
1362
+ for (const key of instruction.keys) {
1363
+ if (key.isSigner && !this.signers.some((s) => s.equals(key.pubkey))) {
1364
+ this.signers.push(key.pubkey);
1365
+ }
1366
+ }
1367
+ return this;
1368
+ }
1369
+ /**
1370
+ * Add multiple instructions
1371
+ */
1372
+ addInstructions(instructions) {
1373
+ for (const ix of instructions) {
1374
+ this.addInstruction(ix);
1375
+ }
1376
+ return this;
1377
+ }
1378
+ /**
1379
+ * Add compute budget instructions
1380
+ */
1381
+ addComputeBudget(units, price) {
1382
+ this.instructions.unshift(
1383
+ import_web3.ComputeBudgetProgram.setComputeUnitLimit({ units }),
1384
+ import_web3.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: price })
1385
+ );
1386
+ return this;
1387
+ }
1388
+ /**
1389
+ * Estimate total compute units
1390
+ */
1391
+ estimateCompute() {
1392
+ let total = 0;
1393
+ for (const ix of this.instructions) {
1394
+ const estimate = this.computeEstimates.get(ix.programId.toBase58()) || 3e3;
1395
+ total += estimate;
1396
+ }
1397
+ total += 200;
1398
+ return total;
1399
+ }
1400
+ /**
1401
+ * Build optimized transaction instructions
1402
+ */
1403
+ build() {
1404
+ let optimizedInstructions = [...this.instructions];
1405
+ const optimizations = [];
1406
+ if (this.config.packInstructions) {
1407
+ optimizedInstructions = this.packInstructions(optimizedInstructions);
1408
+ optimizations.push("instruction_packing");
1409
+ }
1410
+ const computeEstimate = this.estimateCompute();
1411
+ let computeLimit = this.config.computeUnitLimit;
1412
+ if (this.config.dynamicComputeBudget) {
1413
+ computeLimit = this.calculateOptimalComputeLimit(computeEstimate);
1414
+ optimizations.push("dynamic_compute_budget");
1415
+ }
1416
+ const computePrice = this.calculateOptimalPrice();
1417
+ const estimatedSize = this.estimateTransactionSize(optimizedInstructions);
1418
+ optimizedInstructions = this.addComputeBudgetInstructions(
1419
+ optimizedInstructions,
1420
+ computeLimit,
1421
+ computePrice
1422
+ );
1423
+ return {
1424
+ instructions: optimizedInstructions,
1425
+ computeLimit,
1426
+ computePrice,
1427
+ estimatedSize,
1428
+ optimizations
1429
+ };
1430
+ }
1431
+ /**
1432
+ * Build and return only the instructions (without compute budget)
1433
+ */
1434
+ buildInstructions() {
1435
+ return [...this.instructions];
1436
+ }
1437
+ /**
1438
+ * Clear all instructions
1439
+ */
1440
+ clear() {
1441
+ this.instructions = [];
1442
+ this.signers = [];
1443
+ return this;
1444
+ }
1445
+ /**
1446
+ * Get current instruction count
1447
+ */
1448
+ getInstructionCount() {
1449
+ return this.instructions.length;
1450
+ }
1451
+ /**
1452
+ * Get current signer count
1453
+ */
1454
+ getSignerCount() {
1455
+ return this.signers.length;
1456
+ }
1457
+ packInstructions(instructions) {
1458
+ return instructions;
1459
+ }
1460
+ calculateOptimalComputeLimit(estimate) {
1461
+ const withBuffer = Math.ceil(estimate * 1.2);
1462
+ return Math.ceil(withBuffer / 1e4) * 1e4;
1463
+ }
1464
+ calculateOptimalPrice() {
1465
+ return this.config.computeUnitPrice;
1466
+ }
1467
+ estimateTransactionSize(instructions) {
1468
+ let size = 64;
1469
+ size += 3;
1470
+ size += 32 * (this.signers.length + 1);
1471
+ for (const ix of instructions) {
1472
+ size += 1;
1473
+ size += 1;
1474
+ size += ix.keys.length * 33;
1475
+ size += 2;
1476
+ size += ix.data.length;
1477
+ }
1478
+ return size;
1479
+ }
1480
+ addComputeBudgetInstructions(instructions, limit, price) {
1481
+ return instructions;
1482
+ }
1483
+ };
1484
+ var ComputeBudgetOptimizer = class {
1485
+ baseConfig;
1486
+ networkStats = {
1487
+ averageComputePrice: 0,
1488
+ congestionLevel: 0,
1489
+ recentSuccessRate: 1
1490
+ };
1491
+ history = [];
1492
+ maxHistorySize = 100;
1493
+ constructor(config = defaultTransactionConfig()) {
1494
+ this.baseConfig = config;
1495
+ }
1496
+ /**
1497
+ * Update network statistics
1498
+ */
1499
+ updateNetworkStats(stats) {
1500
+ this.networkStats = { ...this.networkStats, ...stats };
1501
+ }
1502
+ /**
1503
+ * Get optimized compute budget for current conditions
1504
+ */
1505
+ getOptimizedBudget(priority = "normal") {
1506
+ const multipliers = {
1507
+ low: 0.5,
1508
+ normal: 1,
1509
+ high: 2,
1510
+ critical: 5
1511
+ };
1512
+ const multiplier = multipliers[priority] ?? 1;
1513
+ const congestionMultiplier = 1 + this.networkStats.congestionLevel;
1514
+ const successMultiplier = this.networkStats.recentSuccessRate < 0.8 ? 1.5 : 1;
1515
+ const computeLimit = this.baseConfig.computeUnitLimit;
1516
+ const computePrice = Math.floor(
1517
+ this.baseConfig.computeUnitPrice * multiplier * congestionMultiplier * successMultiplier
1518
+ );
1519
+ const priorityFee = Math.floor(
1520
+ this.baseConfig.priorityFee * multiplier * congestionMultiplier * successMultiplier
1521
+ );
1522
+ return {
1523
+ computeLimit,
1524
+ computePrice,
1525
+ priorityFee
1526
+ };
1527
+ }
1528
+ /**
1529
+ * Record transaction result for learning
1530
+ */
1531
+ recordResult(computeUsed, computeLimit, success, confirmationTimeMs) {
1532
+ this.history.push({
1533
+ computeUsed,
1534
+ computeLimit,
1535
+ success,
1536
+ confirmationTimeMs,
1537
+ timestamp: Date.now()
1538
+ });
1539
+ if (this.history.length > this.maxHistorySize) {
1540
+ this.history.shift();
1541
+ }
1542
+ const recent = this.history.slice(-20);
1543
+ const successes = recent.filter((h) => h.success).length;
1544
+ this.networkStats.recentSuccessRate = successes / recent.length;
1545
+ }
1546
+ /**
1547
+ * Get recommended compute limit based on history
1548
+ */
1549
+ getRecommendedComputeLimit() {
1550
+ if (this.history.length === 0) {
1551
+ return this.baseConfig.computeUnitLimit;
1552
+ }
1553
+ const computeUsed = this.history.map((h) => h.computeUsed).sort((a, b) => a - b);
1554
+ const p95Index = Math.floor(computeUsed.length * 0.95);
1555
+ const p95Compute = computeUsed[p95Index] ?? computeUsed[computeUsed.length - 1] ?? this.baseConfig.computeUnitLimit;
1556
+ return Math.ceil(p95Compute * 1.2);
1557
+ }
1558
+ /**
1559
+ * Get optimization statistics
1560
+ */
1561
+ getStats() {
1562
+ if (this.history.length === 0) {
1563
+ return {
1564
+ totalComputeUsed: 0,
1565
+ totalComputeLimit: 0,
1566
+ averageComputePerInstruction: 0,
1567
+ estimatedFee: 0,
1568
+ efficiency: 0
1569
+ };
1570
+ }
1571
+ const totalUsed = this.history.reduce((sum, h) => sum + h.computeUsed, 0);
1572
+ const totalLimit = this.history.reduce((sum, h) => sum + h.computeLimit, 0);
1573
+ return {
1574
+ totalComputeUsed: totalUsed,
1575
+ totalComputeLimit: totalLimit,
1576
+ averageComputePerInstruction: totalUsed / this.history.length,
1577
+ estimatedFee: this.calculateEstimatedFee(),
1578
+ efficiency: totalLimit > 0 ? totalUsed / totalLimit : 0
1579
+ };
1580
+ }
1581
+ /**
1582
+ * Reset history
1583
+ */
1584
+ reset() {
1585
+ this.history = [];
1586
+ this.networkStats = {
1587
+ averageComputePrice: 0,
1588
+ congestionLevel: 0,
1589
+ recentSuccessRate: 1
1590
+ };
1591
+ }
1592
+ calculateEstimatedFee() {
1593
+ const recent = this.history.slice(-10);
1594
+ if (recent.length === 0) return 0;
1595
+ const avgCompute = recent.reduce((sum, h) => sum + h.computeUsed, 0) / recent.length;
1596
+ return avgCompute * this.baseConfig.computeUnitPrice;
1597
+ }
1598
+ };
1599
+ var InstructionBatcher = class {
1600
+ groups = [];
1601
+ maxComputePerGroup = 12e5;
1602
+ // 1.2M compute units
1603
+ /**
1604
+ * Add an instruction group
1605
+ */
1606
+ addGroup(group) {
1607
+ this.groups.push(group);
1608
+ return this;
1609
+ }
1610
+ /**
1611
+ * Batch all groups into optimal transaction sets
1612
+ */
1613
+ batch() {
1614
+ const batches = [];
1615
+ let currentBatch = [];
1616
+ let currentCompute = 0;
1617
+ const sorted = [...this.groups].sort((a, b) => b.priority - a.priority);
1618
+ for (const group of sorted) {
1619
+ if (currentCompute + group.computeEstimate > this.maxComputePerGroup) {
1620
+ if (currentBatch.length > 0) {
1621
+ batches.push(currentBatch);
1622
+ }
1623
+ currentBatch = [group];
1624
+ currentCompute = group.computeEstimate;
1625
+ } else {
1626
+ currentBatch.push(group);
1627
+ currentCompute += group.computeEstimate;
1628
+ }
1629
+ }
1630
+ if (currentBatch.length > 0) {
1631
+ batches.push(currentBatch);
1632
+ }
1633
+ return batches;
1634
+ }
1635
+ /**
1636
+ * Set maximum compute per batch
1637
+ */
1638
+ setMaxComputePerGroup(compute) {
1639
+ this.maxComputePerGroup = compute;
1640
+ return this;
1641
+ }
1642
+ /**
1643
+ * Clear all groups
1644
+ */
1645
+ clear() {
1646
+ this.groups = [];
1647
+ return this;
1648
+ }
1649
+ };
1650
+ var TransactionOptimizer = class {
1651
+ config;
1652
+ budgetOptimizer;
1653
+ constructor(config = defaultTransactionConfig()) {
1654
+ this.config = config;
1655
+ this.budgetOptimizer = new ComputeBudgetOptimizer(config);
1656
+ }
1657
+ /**
1658
+ * Optimize a set of instructions
1659
+ */
1660
+ optimize(instructions, options = {}) {
1661
+ const builder = new TransactionBuilder(this.config);
1662
+ builder.addInstructions(instructions);
1663
+ const result = builder.build();
1664
+ if (options.priority) {
1665
+ const budget = this.budgetOptimizer.getOptimizedBudget(options.priority);
1666
+ result.computeLimit = budget.computeLimit;
1667
+ result.computePrice = budget.computePrice;
1668
+ }
1669
+ return result;
1670
+ }
1671
+ /**
1672
+ * Optimize for minimum latency
1673
+ */
1674
+ optimizeForLatency(instructions) {
1675
+ return this.optimize(instructions, { priority: "critical" });
1676
+ }
1677
+ /**
1678
+ * Optimize for minimum cost
1679
+ */
1680
+ optimizeForCost(instructions) {
1681
+ return this.optimize(instructions, { priority: "low" });
1682
+ }
1683
+ /**
1684
+ * Get the compute budget optimizer
1685
+ */
1686
+ getBudgetOptimizer() {
1687
+ return this.budgetOptimizer;
1688
+ }
1689
+ /**
1690
+ * Update configuration
1691
+ */
1692
+ updateConfig(config) {
1693
+ this.config = { ...this.config, ...config };
1694
+ this.budgetOptimizer = new ComputeBudgetOptimizer(this.config);
1695
+ }
1696
+ };
1697
+ function createTransactionBuilder(config) {
1698
+ const fullConfig = { ...defaultTransactionConfig(), ...config };
1699
+ return new TransactionBuilder(fullConfig);
1700
+ }
1701
+ function createComputeBudgetOptimizer(config) {
1702
+ const fullConfig = { ...defaultTransactionConfig(), ...config };
1703
+ return new ComputeBudgetOptimizer(fullConfig);
1704
+ }
1705
+ function createInstructionBatcher() {
1706
+ return new InstructionBatcher();
1707
+ }
1708
+ function createTransactionOptimizer(config) {
1709
+ const fullConfig = { ...defaultTransactionConfig(), ...config };
1710
+ return new TransactionOptimizer(fullConfig);
1711
+ }
1712
+ function estimateCompute(operation) {
1713
+ const estimates = {
1714
+ transfer: 450,
1715
+ createAccount: 2500,
1716
+ createATA: 3500,
1717
+ closeAccount: 2500,
1718
+ syncNative: 500,
1719
+ pumpFunBuy: 45e3,
1720
+ pumpFunSell: 4e4,
1721
+ pumpSwapBuy: 5e4,
1722
+ pumpSwapSell: 45e3,
1723
+ raydiumSwap: 55e3,
1724
+ meteoraSwap: 6e4
1725
+ };
1726
+ return estimates[operation] || 3e3;
1727
+ }
1728
+ function calculateOptimalPrice(targetLatencyMs, currentCongestion) {
1729
+ const basePrice = 1e5;
1730
+ const latencyMultiplier = Math.max(1, 100 / targetLatencyMs);
1731
+ const congestionMultiplier = 1 + currentCongestion;
1732
+ return Math.floor(basePrice * latencyMultiplier * congestionMultiplier);
1733
+ }
1734
+
1735
+ // src/perf/realtime.ts
1736
+ var ThreadPriorityLevel = /* @__PURE__ */ ((ThreadPriorityLevel2) => {
1737
+ ThreadPriorityLevel2[ThreadPriorityLevel2["Idle"] = 0] = "Idle";
1738
+ ThreadPriorityLevel2[ThreadPriorityLevel2["Lowest"] = 1] = "Lowest";
1739
+ ThreadPriorityLevel2[ThreadPriorityLevel2["Low"] = 2] = "Low";
1740
+ ThreadPriorityLevel2[ThreadPriorityLevel2["Normal"] = 3] = "Normal";
1741
+ ThreadPriorityLevel2[ThreadPriorityLevel2["High"] = 4] = "High";
1742
+ ThreadPriorityLevel2[ThreadPriorityLevel2["Highest"] = 5] = "Highest";
1743
+ ThreadPriorityLevel2[ThreadPriorityLevel2["Realtime"] = 6] = "Realtime";
1744
+ return ThreadPriorityLevel2;
1745
+ })(ThreadPriorityLevel || {});
1746
+ var SchedulerPolicy = /* @__PURE__ */ ((SchedulerPolicy2) => {
1747
+ SchedulerPolicy2["Normal"] = "normal";
1748
+ SchedulerPolicy2["FIFO"] = "fifo";
1749
+ SchedulerPolicy2["RoundRobin"] = "rr";
1750
+ SchedulerPolicy2["Batch"] = "batch";
1751
+ SchedulerPolicy2["Idle"] = "idle";
1752
+ return SchedulerPolicy2;
1753
+ })(SchedulerPolicy || {});
1754
+ function defaultRealtimeConfig() {
1755
+ return {
1756
+ enableRealtime: false,
1757
+ targetLatencyUs: 100,
1758
+ // 100 microseconds
1759
+ cpuCore: -1,
1760
+ // No pinning
1761
+ priority: 4 /* High */,
1762
+ busyWait: false,
1763
+ scheduler: "normal" /* Normal */,
1764
+ lockMemory: false
1765
+ };
1766
+ }
1767
+ var ThreadPriority = class {
1768
+ currentPriority = 3 /* Normal */;
1769
+ config;
1770
+ constructor(config = defaultRealtimeConfig()) {
1771
+ this.config = config;
1772
+ }
1773
+ /**
1774
+ * Set thread priority
1775
+ */
1776
+ setPriority(priority) {
1777
+ this.currentPriority = priority;
1778
+ if (this.config.enableRealtime) {
1779
+ console.log(`Thread priority set to: ${ThreadPriorityLevel[priority]}`);
1780
+ }
1781
+ return true;
1782
+ }
1783
+ /**
1784
+ * Get current priority
1785
+ */
1786
+ getPriority() {
1787
+ return this.currentPriority;
1788
+ }
1789
+ /**
1790
+ * Increase priority by one level
1791
+ */
1792
+ increasePriority() {
1793
+ if (this.currentPriority < 6 /* Realtime */) {
1794
+ return this.setPriority(this.currentPriority + 1);
1795
+ }
1796
+ return false;
1797
+ }
1798
+ /**
1799
+ * Decrease priority by one level
1800
+ */
1801
+ decreasePriority() {
1802
+ if (this.currentPriority > 0 /* Idle */) {
1803
+ return this.setPriority(this.currentPriority - 1);
1804
+ }
1805
+ return false;
1806
+ }
1807
+ /**
1808
+ * Set realtime priority
1809
+ */
1810
+ setRealtime() {
1811
+ return this.setPriority(6 /* Realtime */);
1812
+ }
1813
+ /**
1814
+ * Set normal priority
1815
+ */
1816
+ setNormal() {
1817
+ return this.setPriority(3 /* Normal */);
1818
+ }
1819
+ /**
1820
+ * Check if running at realtime priority
1821
+ */
1822
+ isRealtime() {
1823
+ return this.currentPriority === 6 /* Realtime */;
1824
+ }
1825
+ };
1826
+ var RealtimeTuner = class {
1827
+ config;
1828
+ running = false;
1829
+ tunerInterval = null;
1830
+ latencies = [];
1831
+ stats;
1832
+ callbacks = [];
1833
+ lastAdjustment = 0;
1834
+ adjustmentCooldownMs = 1e3;
1835
+ constructor(config = defaultRealtimeConfig()) {
1836
+ this.config = config;
1837
+ this.stats = {
1838
+ adjustments: 0,
1839
+ averageLatencyUs: 0,
1840
+ minLatencyUs: Infinity,
1841
+ maxLatencyUs: 0,
1842
+ violations: 0,
1843
+ lastAdjustmentTime: 0
1844
+ };
1845
+ }
1846
+ /**
1847
+ * Start the realtime tuner
1848
+ */
1849
+ start() {
1850
+ if (this.running) return;
1851
+ this.running = true;
1852
+ this.applyConfiguration();
1853
+ this.tunerInterval = setInterval(() => {
1854
+ this.tune();
1855
+ }, 100);
1856
+ console.log("Realtime tuner started");
1857
+ }
1858
+ /**
1859
+ * Stop the realtime tuner
1860
+ */
1861
+ stop() {
1862
+ this.running = false;
1863
+ if (this.tunerInterval) {
1864
+ clearInterval(this.tunerInterval);
1865
+ this.tunerInterval = null;
1866
+ }
1867
+ console.log("Realtime tuner stopped");
1868
+ }
1869
+ /**
1870
+ * Record a latency measurement
1871
+ */
1872
+ recordLatency(latencyUs) {
1873
+ this.latencies.push(latencyUs);
1874
+ if (this.latencies.length > 1e3) {
1875
+ this.latencies.shift();
1876
+ }
1877
+ if (latencyUs > this.config.targetLatencyUs) {
1878
+ this.stats.violations++;
1879
+ }
1880
+ this.stats.minLatencyUs = Math.min(this.stats.minLatencyUs, latencyUs);
1881
+ this.stats.maxLatencyUs = Math.max(this.stats.maxLatencyUs, latencyUs);
1882
+ }
1883
+ /**
1884
+ * Get current tuning statistics
1885
+ */
1886
+ getStats() {
1887
+ if (this.latencies.length > 0) {
1888
+ this.stats.averageLatencyUs = this.latencies.reduce((a, b) => a + b, 0) / this.latencies.length;
1889
+ }
1890
+ return { ...this.stats };
1891
+ }
1892
+ /**
1893
+ * Register a callback for tuning events
1894
+ */
1895
+ onTune(callback) {
1896
+ this.callbacks.push(callback);
1897
+ }
1898
+ /**
1899
+ * Reset statistics
1900
+ */
1901
+ resetStats() {
1902
+ this.latencies = [];
1903
+ this.stats = {
1904
+ adjustments: 0,
1905
+ averageLatencyUs: 0,
1906
+ minLatencyUs: Infinity,
1907
+ maxLatencyUs: 0,
1908
+ violations: 0,
1909
+ lastAdjustmentTime: 0
1910
+ };
1911
+ }
1912
+ applyConfiguration() {
1913
+ const priority = new ThreadPriority(this.config);
1914
+ priority.setPriority(this.config.priority);
1915
+ console.log("Realtime configuration applied:", {
1916
+ targetLatencyUs: this.config.targetLatencyUs,
1917
+ cpuCore: this.config.cpuCore,
1918
+ priority: ThreadPriorityLevel[this.config.priority],
1919
+ busyWait: this.config.busyWait
1920
+ });
1921
+ }
1922
+ tune() {
1923
+ if (!this.running) return;
1924
+ const now = Date.now();
1925
+ if (now - this.lastAdjustment < this.adjustmentCooldownMs) {
1926
+ return;
1927
+ }
1928
+ if (this.latencies.length === 0) return;
1929
+ const avgLatency = this.latencies.reduce((a, b) => a + b, 0) / this.latencies.length;
1930
+ this.stats.averageLatencyUs = avgLatency;
1931
+ const violationRate = this.stats.violations / this.latencies.length;
1932
+ if (violationRate > 0.1) {
1933
+ this.adjustForLowerLatency();
1934
+ this.stats.adjustments++;
1935
+ this.stats.lastAdjustmentTime = now;
1936
+ this.lastAdjustment = now;
1937
+ }
1938
+ for (const callback of this.callbacks) {
1939
+ try {
1940
+ callback(this.getStats());
1941
+ } catch (error) {
1942
+ console.error("Tuning callback error:", error);
1943
+ }
1944
+ }
1945
+ }
1946
+ adjustForLowerLatency() {
1947
+ console.log("Adjusting for lower latency...");
1948
+ }
1949
+ };
1950
+ function busyWait(microseconds) {
1951
+ const start = process.hrtime.bigint();
1952
+ const target = start + BigInt(microseconds) * BigInt(1e3);
1953
+ while (process.hrtime.bigint() < target) {
1954
+ }
1955
+ }
1956
+ function spinLock(condition, timeoutUs) {
1957
+ const start = process.hrtime.bigint();
1958
+ const timeoutNs = BigInt(timeoutUs) * BigInt(1e3);
1959
+ while (!condition()) {
1960
+ if (process.hrtime.bigint() - start > timeoutNs) {
1961
+ return false;
1962
+ }
1963
+ }
1964
+ return true;
1965
+ }
1966
+ var LatencyMonitor = class {
1967
+ measurements = [];
1968
+ maxMeasurements;
1969
+ histogram = /* @__PURE__ */ new Map();
1970
+ bucketSize;
1971
+ constructor(maxMeasurements = 1e4, bucketSize = 10) {
1972
+ this.maxMeasurements = maxMeasurements;
1973
+ this.bucketSize = bucketSize;
1974
+ }
1975
+ /**
1976
+ * Record a latency measurement
1977
+ */
1978
+ record(latencyUs) {
1979
+ this.measurements.push(latencyUs);
1980
+ if (this.measurements.length > this.maxMeasurements) {
1981
+ this.measurements.shift();
1982
+ }
1983
+ const bucket = Math.floor(latencyUs / this.bucketSize) * this.bucketSize;
1984
+ const count = this.histogram.get(bucket) || 0;
1985
+ this.histogram.set(bucket, count + 1);
1986
+ }
1987
+ /**
1988
+ * Get percentile latency
1989
+ */
1990
+ getPercentile(percentile) {
1991
+ if (this.measurements.length === 0) return 0;
1992
+ const sorted = [...this.measurements].sort((a, b) => a - b);
1993
+ const index = Math.floor(percentile / 100 * sorted.length);
1994
+ return sorted[Math.min(index, sorted.length - 1)] ?? 0;
1995
+ }
1996
+ /**
1997
+ * Get average latency
1998
+ */
1999
+ getAverage() {
2000
+ if (this.measurements.length === 0) return 0;
2001
+ return this.measurements.reduce((a, b) => a + b, 0) / this.measurements.length;
2002
+ }
2003
+ /**
2004
+ * Get minimum latency
2005
+ */
2006
+ getMin() {
2007
+ if (this.measurements.length === 0) return 0;
2008
+ return Math.min(...this.measurements);
2009
+ }
2010
+ /**
2011
+ * Get maximum latency
2012
+ */
2013
+ getMax() {
2014
+ if (this.measurements.length === 0) return 0;
2015
+ return Math.max(...this.measurements);
2016
+ }
2017
+ /**
2018
+ * Get histogram
2019
+ */
2020
+ getHistogram() {
2021
+ return new Map(this.histogram);
2022
+ }
2023
+ /**
2024
+ * Reset all measurements
2025
+ */
2026
+ reset() {
2027
+ this.measurements = [];
2028
+ this.histogram.clear();
2029
+ }
2030
+ /**
2031
+ * Get summary statistics
2032
+ */
2033
+ getSummary() {
2034
+ return {
2035
+ count: this.measurements.length,
2036
+ min: this.getMin(),
2037
+ max: this.getMax(),
2038
+ avg: this.getAverage(),
2039
+ p50: this.getPercentile(50),
2040
+ p95: this.getPercentile(95),
2041
+ p99: this.getPercentile(99),
2042
+ p999: this.getPercentile(99.9)
2043
+ };
2044
+ }
2045
+ };
2046
+ var PerformanceGovernor = class {
2047
+ targetThroughput = 0;
2048
+ currentThroughput = 0;
2049
+ adjustments = 0;
2050
+ /**
2051
+ * Set target throughput (operations per second)
2052
+ */
2053
+ setTargetThroughput(opsPerSecond) {
2054
+ this.targetThroughput = opsPerSecond;
2055
+ }
2056
+ /**
2057
+ * Report actual throughput
2058
+ */
2059
+ reportThroughput(opsPerSecond) {
2060
+ this.currentThroughput = opsPerSecond;
2061
+ }
2062
+ /**
2063
+ * Get recommended batch size
2064
+ */
2065
+ getRecommendedBatchSize() {
2066
+ if (this.targetThroughput === 0) return 1;
2067
+ const ratio = this.currentThroughput / this.targetThroughput;
2068
+ if (ratio < 0.5) {
2069
+ return 1;
2070
+ } else if (ratio > 1.5) {
2071
+ return 10;
2072
+ }
2073
+ return 5;
2074
+ }
2075
+ /**
2076
+ * Get adjustment count
2077
+ */
2078
+ getAdjustments() {
2079
+ return this.adjustments;
2080
+ }
2081
+ };
2082
+ function createRealtimeTuner(config) {
2083
+ const fullConfig = { ...defaultRealtimeConfig(), ...config };
2084
+ return new RealtimeTuner(fullConfig);
2085
+ }
2086
+ function createThreadPriority(config) {
2087
+ const fullConfig = { ...defaultRealtimeConfig(), ...config };
2088
+ return new ThreadPriority(fullConfig);
2089
+ }
2090
+ function createLatencyMonitor(maxMeasurements, bucketSize) {
2091
+ return new LatencyMonitor(maxMeasurements, bucketSize);
2092
+ }
2093
+ function createPerformanceGovernor() {
2094
+ return new PerformanceGovernor();
2095
+ }
2096
+ function measureTime(fn) {
2097
+ const start = process.hrtime.bigint();
2098
+ const result = fn();
2099
+ const elapsed = Number(process.hrtime.bigint() - start) / 1e3;
2100
+ return { result, elapsedUs: elapsed };
2101
+ }
2102
+ function createTimer() {
2103
+ let startTime = BigInt(0);
2104
+ return {
2105
+ start: () => {
2106
+ startTime = process.hrtime.bigint();
2107
+ },
2108
+ elapsed: () => {
2109
+ return Number(process.hrtime.bigint() - startTime) / 1e3;
2110
+ },
2111
+ reset: () => {
2112
+ startTime = process.hrtime.bigint();
2113
+ }
2114
+ };
2115
+ }
2116
+
2117
+ // src/perf/simd.ts
2118
+ function defaultSIMDConfig() {
2119
+ return {
2120
+ enableSIMD: true,
2121
+ preferredWidth: 128,
2122
+ enableWasmSIMD: true,
2123
+ fallbackToScalar: true
2124
+ };
2125
+ }
2126
+ var SIMDDetector = class {
2127
+ capabilities = null;
2128
+ /**
2129
+ * Detect SIMD capabilities
2130
+ */
2131
+ detect() {
2132
+ if (this.capabilities) {
2133
+ return this.capabilities;
2134
+ }
2135
+ this.capabilities = {
2136
+ sse: false,
2137
+ sse2: false,
2138
+ sse3: false,
2139
+ ssse3: false,
2140
+ sse41: false,
2141
+ sse42: false,
2142
+ avx: false,
2143
+ avx2: false,
2144
+ avx512: false,
2145
+ neon: this.detectNEON(),
2146
+ wasmSimd128: this.detectWasmSIMD128()
2147
+ };
2148
+ return this.capabilities;
2149
+ }
2150
+ /**
2151
+ * Check if WebAssembly SIMD128 is available
2152
+ */
2153
+ detectWasmSIMD128() {
2154
+ if (typeof WebAssembly === "undefined") {
2155
+ return false;
2156
+ }
2157
+ try {
2158
+ const simdTest = new Uint8Array([
2159
+ 0,
2160
+ 97,
2161
+ 115,
2162
+ 109,
2163
+ // WASM magic
2164
+ 1,
2165
+ 0,
2166
+ 0,
2167
+ 0,
2168
+ // version
2169
+ 1,
2170
+ 5,
2171
+ 1,
2172
+ // type section
2173
+ 96,
2174
+ 0,
2175
+ 1,
2176
+ 123,
2177
+ // func type with v128 return
2178
+ 3,
2179
+ 2,
2180
+ 1,
2181
+ 0,
2182
+ // func section
2183
+ 10,
2184
+ 11,
2185
+ 1,
2186
+ // code section
2187
+ 9,
2188
+ 0,
2189
+ // func body
2190
+ 253,
2191
+ 15,
2192
+ 0,
2193
+ 0,
2194
+ // v128.const
2195
+ 0,
2196
+ 0,
2197
+ 0,
2198
+ 0,
2199
+ 0,
2200
+ 0,
2201
+ 0,
2202
+ 0,
2203
+ 11
2204
+ // end
2205
+ ]);
2206
+ WebAssembly.compile(simdTest);
2207
+ return true;
2208
+ } catch {
2209
+ return false;
2210
+ }
2211
+ }
2212
+ /**
2213
+ * Detect NEON support (ARM)
2214
+ */
2215
+ detectNEON() {
2216
+ if (typeof process !== "undefined" && process.arch === "arm64") {
2217
+ return true;
2218
+ }
2219
+ return false;
2220
+ }
2221
+ /**
2222
+ * Check if specific capability is available
2223
+ */
2224
+ hasCapability(capability) {
2225
+ const caps = this.detect();
2226
+ return caps[capability];
2227
+ }
2228
+ /**
2229
+ * Get optimal vector width
2230
+ */
2231
+ getOptimalWidth() {
2232
+ const caps = this.detect();
2233
+ if (caps.avx512) return 512;
2234
+ if (caps.avx || caps.avx2) return 256;
2235
+ if (caps.sse || caps.sse2 || caps.neon || caps.wasmSimd128) return 128;
2236
+ return 64;
2237
+ }
2238
+ /**
2239
+ * Check if any SIMD is available
2240
+ */
2241
+ hasAnySIMD() {
2242
+ const caps = this.detect();
2243
+ return Object.values(caps).some((v) => v);
2244
+ }
2245
+ };
2246
+ var VectorizedMath = class {
2247
+ config;
2248
+ detector;
2249
+ constructor(config = defaultSIMDConfig()) {
2250
+ this.config = config;
2251
+ this.detector = new SIMDDetector();
2252
+ }
2253
+ /**
2254
+ * Vector addition: result = a + b
2255
+ */
2256
+ add(a, b, result) {
2257
+ const len = Math.min(a.length, b.length);
2258
+ const out = result || new Float32Array(len);
2259
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2260
+ const simdLen = len - len % 4;
2261
+ for (let i = 0; i < simdLen; i += 4) {
2262
+ out[i] = a[i] + b[i];
2263
+ out[i + 1] = a[i + 1] + b[i + 1];
2264
+ out[i + 2] = a[i + 2] + b[i + 2];
2265
+ out[i + 3] = a[i + 3] + b[i + 3];
2266
+ }
2267
+ for (let i = simdLen; i < len; i++) {
2268
+ out[i] = a[i] + b[i];
2269
+ }
2270
+ } else {
2271
+ for (let i = 0; i < len; i++) {
2272
+ out[i] = a[i] + b[i];
2273
+ }
2274
+ }
2275
+ return out;
2276
+ }
2277
+ /**
2278
+ * Vector subtraction: result = a - b
2279
+ */
2280
+ subtract(a, b, result) {
2281
+ const len = Math.min(a.length, b.length);
2282
+ const out = result || new Float32Array(len);
2283
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2284
+ const simdLen = len - len % 4;
2285
+ for (let i = 0; i < simdLen; i += 4) {
2286
+ out[i] = a[i] - b[i];
2287
+ out[i + 1] = a[i + 1] - b[i + 1];
2288
+ out[i + 2] = a[i + 2] - b[i + 2];
2289
+ out[i + 3] = a[i + 3] - b[i + 3];
2290
+ }
2291
+ for (let i = simdLen; i < len; i++) {
2292
+ out[i] = a[i] - b[i];
2293
+ }
2294
+ } else {
2295
+ for (let i = 0; i < len; i++) {
2296
+ out[i] = a[i] - b[i];
2297
+ }
2298
+ }
2299
+ return out;
2300
+ }
2301
+ /**
2302
+ * Vector multiplication: result = a * b
2303
+ */
2304
+ multiply(a, b, result) {
2305
+ const len = Math.min(a.length, b.length);
2306
+ const out = result || new Float32Array(len);
2307
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2308
+ const simdLen = len - len % 4;
2309
+ for (let i = 0; i < simdLen; i += 4) {
2310
+ out[i] = a[i] * b[i];
2311
+ out[i + 1] = a[i + 1] * b[i + 1];
2312
+ out[i + 2] = a[i + 2] * b[i + 2];
2313
+ out[i + 3] = a[i + 3] * b[i + 3];
2314
+ }
2315
+ for (let i = simdLen; i < len; i++) {
2316
+ out[i] = a[i] * b[i];
2317
+ }
2318
+ } else {
2319
+ for (let i = 0; i < len; i++) {
2320
+ out[i] = a[i] * b[i];
2321
+ }
2322
+ }
2323
+ return out;
2324
+ }
2325
+ /**
2326
+ * Vector division: result = a / b
2327
+ */
2328
+ divide(a, b, result) {
2329
+ const len = Math.min(a.length, b.length);
2330
+ const out = result || new Float32Array(len);
2331
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2332
+ const simdLen = len - len % 4;
2333
+ for (let i = 0; i < simdLen; i += 4) {
2334
+ out[i] = a[i] / b[i];
2335
+ out[i + 1] = a[i + 1] / b[i + 1];
2336
+ out[i + 2] = a[i + 2] / b[i + 2];
2337
+ out[i + 3] = a[i + 3] / b[i + 3];
2338
+ }
2339
+ for (let i = simdLen; i < len; i++) {
2340
+ out[i] = a[i] / b[i];
2341
+ }
2342
+ } else {
2343
+ for (let i = 0; i < len; i++) {
2344
+ out[i] = a[i] / b[i];
2345
+ }
2346
+ }
2347
+ return out;
2348
+ }
2349
+ /**
2350
+ * Vector dot product
2351
+ */
2352
+ dot(a, b) {
2353
+ const len = Math.min(a.length, b.length);
2354
+ let sum = 0;
2355
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2356
+ const simdLen = len - len % 4;
2357
+ let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
2358
+ for (let i = 0; i < simdLen; i += 4) {
2359
+ sum0 += a[i] * b[i];
2360
+ sum1 += a[i + 1] * b[i + 1];
2361
+ sum2 += a[i + 2] * b[i + 2];
2362
+ sum3 += a[i + 3] * b[i + 3];
2363
+ }
2364
+ sum = sum0 + sum1 + sum2 + sum3;
2365
+ for (let i = simdLen; i < len; i++) {
2366
+ sum += a[i] * b[i];
2367
+ }
2368
+ } else {
2369
+ for (let i = 0; i < len; i++) {
2370
+ sum += a[i] * b[i];
2371
+ }
2372
+ }
2373
+ return sum;
2374
+ }
2375
+ /**
2376
+ * Vector sum
2377
+ */
2378
+ sum(a) {
2379
+ let sum = 0;
2380
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2381
+ const len = a.length;
2382
+ const simdLen = len - len % 4;
2383
+ let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
2384
+ for (let i = 0; i < simdLen; i += 4) {
2385
+ sum0 += a[i];
2386
+ sum1 += a[i + 1];
2387
+ sum2 += a[i + 2];
2388
+ sum3 += a[i + 3];
2389
+ }
2390
+ sum = sum0 + sum1 + sum2 + sum3;
2391
+ for (let i = simdLen; i < len; i++) {
2392
+ sum += a[i];
2393
+ }
2394
+ } else {
2395
+ for (let i = 0; i < a.length; i++) {
2396
+ sum += a[i];
2397
+ }
2398
+ }
2399
+ return sum;
2400
+ }
2401
+ /**
2402
+ * Vector minimum
2403
+ */
2404
+ min(a) {
2405
+ if (a.length === 0) return NaN;
2406
+ let min = a[0];
2407
+ for (let i = 1; i < a.length; i++) {
2408
+ if (a[i] < min) min = a[i];
2409
+ }
2410
+ return min;
2411
+ }
2412
+ /**
2413
+ * Vector maximum
2414
+ */
2415
+ max(a) {
2416
+ if (a.length === 0) return NaN;
2417
+ let max = a[0];
2418
+ for (let i = 1; i < a.length; i++) {
2419
+ if (a[i] > max) max = a[i];
2420
+ }
2421
+ return max;
2422
+ }
2423
+ /**
2424
+ * Element-wise absolute value
2425
+ */
2426
+ abs(a, result) {
2427
+ const out = result || new Float32Array(a.length);
2428
+ for (let i = 0; i < a.length; i++) {
2429
+ out[i] = Math.abs(a[i]);
2430
+ }
2431
+ return out;
2432
+ }
2433
+ /**
2434
+ * Element-wise square root
2435
+ */
2436
+ sqrt(a, result) {
2437
+ const out = result || new Float32Array(a.length);
2438
+ for (let i = 0; i < a.length; i++) {
2439
+ out[i] = Math.sqrt(a[i]);
2440
+ }
2441
+ return out;
2442
+ }
2443
+ };
2444
+ var CryptoSIMD = class {
2445
+ config;
2446
+ detector;
2447
+ constructor(config = defaultSIMDConfig()) {
2448
+ this.config = config;
2449
+ this.detector = new SIMDDetector();
2450
+ }
2451
+ /**
2452
+ * XOR two byte arrays (SIMD-accelerated)
2453
+ */
2454
+ xor(a, b, result) {
2455
+ const len = Math.min(a.length, b.length);
2456
+ const out = result || new Uint8Array(len);
2457
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2458
+ const simdLen = len - len % 16;
2459
+ for (let i = 0; i < simdLen; i += 16) {
2460
+ for (let j = 0; j < 16; j++) {
2461
+ out[i + j] = a[i + j] ^ b[i + j];
2462
+ }
2463
+ }
2464
+ for (let i = simdLen; i < len; i++) {
2465
+ out[i] = a[i] ^ b[i];
2466
+ }
2467
+ } else {
2468
+ for (let i = 0; i < len; i++) {
2469
+ out[i] = a[i] ^ b[i];
2470
+ }
2471
+ }
2472
+ return out;
2473
+ }
2474
+ /**
2475
+ * Compare two byte arrays for equality (SIMD-accelerated)
2476
+ */
2477
+ equals(a, b) {
2478
+ if (a.length !== b.length) return false;
2479
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2480
+ const len = a.length;
2481
+ const simdLen = len - len % 16;
2482
+ for (let i = 0; i < simdLen; i += 16) {
2483
+ for (let j = 0; j < 16; j++) {
2484
+ if (a[i + j] !== b[i + j]) return false;
2485
+ }
2486
+ }
2487
+ for (let i = simdLen; i < len; i++) {
2488
+ if (a[i] !== b[i]) return false;
2489
+ }
2490
+ } else {
2491
+ for (let i = 0; i < a.length; i++) {
2492
+ if (a[i] !== b[i]) return false;
2493
+ }
2494
+ }
2495
+ return true;
2496
+ }
2497
+ /**
2498
+ * Fill array with value (SIMD-accelerated)
2499
+ */
2500
+ fill(buffer, value) {
2501
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2502
+ const len = buffer.length;
2503
+ const simdLen = len - len % 16;
2504
+ for (let i = 0; i < simdLen; i += 16) {
2505
+ for (let j = 0; j < 16; j++) {
2506
+ buffer[i + j] = value;
2507
+ }
2508
+ }
2509
+ for (let i = simdLen; i < len; i++) {
2510
+ buffer[i] = value;
2511
+ }
2512
+ } else {
2513
+ buffer.fill(value);
2514
+ }
2515
+ }
2516
+ /**
2517
+ * Copy bytes (SIMD-accelerated)
2518
+ */
2519
+ copy(src, dst, srcOffset = 0, dstOffset = 0, length) {
2520
+ const len = length || Math.min(src.length - srcOffset, dst.length - dstOffset);
2521
+ if (this.config.enableSIMD && this.detector.hasAnySIMD()) {
2522
+ const simdLen = len - len % 16;
2523
+ for (let i = 0; i < simdLen; i += 16) {
2524
+ for (let j = 0; j < 16; j++) {
2525
+ dst[dstOffset + i + j] = src[srcOffset + i + j];
2526
+ }
2527
+ }
2528
+ for (let i = simdLen; i < len; i++) {
2529
+ dst[dstOffset + i] = src[srcOffset + i];
2530
+ }
2531
+ } else {
2532
+ dst.set(src.subarray(srcOffset, srcOffset + len), dstOffset);
2533
+ }
2534
+ }
2535
+ /**
2536
+ * Compute parity of byte array
2537
+ */
2538
+ parity(data) {
2539
+ let parity = 0;
2540
+ for (let i = 0; i < data.length; i++) {
2541
+ parity ^= data[i];
2542
+ }
2543
+ return parity;
2544
+ }
2545
+ /**
2546
+ * Rotate bytes left
2547
+ */
2548
+ rotateLeft(data, bits, result) {
2549
+ const out = result || new Uint8Array(data.length);
2550
+ const bytes = Math.floor(bits / 8);
2551
+ const remainingBits = bits % 8;
2552
+ if (remainingBits === 0) {
2553
+ for (let i = 0; i < data.length; i++) {
2554
+ out[i] = data[(i + bytes) % data.length];
2555
+ }
2556
+ } else {
2557
+ for (let i = 0; i < data.length; i++) {
2558
+ const srcIdx = (i + bytes) % data.length;
2559
+ const nextIdx = (srcIdx + 1) % data.length;
2560
+ out[i] = data[srcIdx] << remainingBits | data[nextIdx] >> 8 - remainingBits;
2561
+ }
2562
+ }
2563
+ return out;
2564
+ }
2565
+ };
2566
+ var Float32x4 = class _Float32x4 {
2567
+ data;
2568
+ constructor(x, y, z, w) {
2569
+ this.data = new Float32Array(4);
2570
+ if (x !== void 0) this.data[0] = x;
2571
+ if (y !== void 0) this.data[1] = y;
2572
+ if (z !== void 0) this.data[2] = z;
2573
+ if (w !== void 0) this.data[3] = w;
2574
+ }
2575
+ static fromArray(arr, offset = 0) {
2576
+ return new _Float32x4(arr[offset], arr[offset + 1], arr[offset + 2], arr[offset + 3]);
2577
+ }
2578
+ add(other) {
2579
+ return new _Float32x4(
2580
+ this.data[0] + other.data[0],
2581
+ this.data[1] + other.data[1],
2582
+ this.data[2] + other.data[2],
2583
+ this.data[3] + other.data[3]
2584
+ );
2585
+ }
2586
+ subtract(other) {
2587
+ return new _Float32x4(
2588
+ this.data[0] - other.data[0],
2589
+ this.data[1] - other.data[1],
2590
+ this.data[2] - other.data[2],
2591
+ this.data[3] - other.data[3]
2592
+ );
2593
+ }
2594
+ multiply(other) {
2595
+ return new _Float32x4(
2596
+ this.data[0] * other.data[0],
2597
+ this.data[1] * other.data[1],
2598
+ this.data[2] * other.data[2],
2599
+ this.data[3] * other.data[3]
2600
+ );
2601
+ }
2602
+ toArray() {
2603
+ return this.data.slice();
2604
+ }
2605
+ get x() {
2606
+ return this.data[0];
2607
+ }
2608
+ get y() {
2609
+ return this.data[1];
2610
+ }
2611
+ get z() {
2612
+ return this.data[2];
2613
+ }
2614
+ get w() {
2615
+ return this.data[3];
2616
+ }
2617
+ };
2618
+ function createSIMDDetector() {
2619
+ return new SIMDDetector();
2620
+ }
2621
+ function createVectorizedMath(config) {
2622
+ const fullConfig = { ...defaultSIMDConfig(), ...config };
2623
+ return new VectorizedMath(fullConfig);
2624
+ }
2625
+ function createCryptoSIMD(config) {
2626
+ const fullConfig = { ...defaultSIMDConfig(), ...config };
2627
+ return new CryptoSIMD(fullConfig);
2628
+ }
2629
+ function isSIMDAvailable() {
2630
+ return new SIMDDetector().hasAnySIMD();
2631
+ }
2632
+ function getOptimalSIMDWidth() {
2633
+ return new SIMDDetector().getOptimalWidth();
2634
+ }
2635
+
2636
+ // src/perf/syscall-bypass.ts
2637
+ function defaultSyscallBypassConfig() {
2638
+ return {
2639
+ enableFastTime: true,
2640
+ timeCacheIntervalUs: 1e3,
2641
+ // 1ms
2642
+ enableBatching: true,
2643
+ maxBatchSize: 64,
2644
+ useVdsoTime: true
2645
+ };
2646
+ }
2647
+ var FastTimeProvider = class {
2648
+ cachedTimeNs = BigInt(0);
2649
+ cachedTimeMs = 0;
2650
+ lastUpdateNs = BigInt(0);
2651
+ updateIntervalNs;
2652
+ running = false;
2653
+ updateTimer = null;
2654
+ useHighRes;
2655
+ constructor(updateIntervalUs = 1e3, useHighRes = true) {
2656
+ this.updateIntervalNs = BigInt(updateIntervalUs * 1e3);
2657
+ this.useHighRes = useHighRes;
2658
+ this.updateTime();
2659
+ }
2660
+ /**
2661
+ * Start the background time update loop
2662
+ */
2663
+ start() {
2664
+ if (this.running) return;
2665
+ this.running = true;
2666
+ const intervalMs = Number(this.updateIntervalNs) / 1e6;
2667
+ this.updateTimer = setInterval(() => {
2668
+ this.updateTime();
2669
+ }, Math.max(1, intervalMs));
2670
+ }
2671
+ /**
2672
+ * Stop the background time update loop
2673
+ */
2674
+ stop() {
2675
+ this.running = false;
2676
+ if (this.updateTimer) {
2677
+ clearInterval(this.updateTimer);
2678
+ this.updateTimer = null;
2679
+ }
2680
+ }
2681
+ /**
2682
+ * Get cached time in nanoseconds (fast, no syscall)
2683
+ */
2684
+ nowNs() {
2685
+ return this.cachedTimeNs;
2686
+ }
2687
+ /**
2688
+ * Get cached time in microseconds (fast, no syscall)
2689
+ */
2690
+ nowUs() {
2691
+ return this.cachedTimeNs / BigInt(1e3);
2692
+ }
2693
+ /**
2694
+ * Get cached time in milliseconds (fast, no syscall)
2695
+ */
2696
+ nowMs() {
2697
+ return this.cachedTimeMs;
2698
+ }
2699
+ /**
2700
+ * Get precise time (may involve syscall)
2701
+ */
2702
+ preciseNowNs() {
2703
+ if (this.useHighRes && typeof process !== "undefined" && process.hrtime) {
2704
+ const [seconds, nanoseconds] = process.hrtime();
2705
+ return BigInt(seconds) * BigInt(1e9) + BigInt(nanoseconds);
2706
+ }
2707
+ return BigInt(Date.now()) * BigInt(1e6);
2708
+ }
2709
+ /**
2710
+ * Get precise time in microseconds
2711
+ */
2712
+ preciseNowUs() {
2713
+ return this.preciseNowNs() / BigInt(1e3);
2714
+ }
2715
+ updateTime() {
2716
+ this.cachedTimeNs = this.preciseNowNs();
2717
+ this.cachedTimeMs = Date.now();
2718
+ this.lastUpdateNs = this.cachedTimeNs;
2719
+ }
2720
+ };
2721
+ var SyscallBypassManager = class {
2722
+ config;
2723
+ timeProvider;
2724
+ syscallQueue = [];
2725
+ batchTimer = null;
2726
+ stats;
2727
+ constructor(config = defaultSyscallBypassConfig()) {
2728
+ this.config = config;
2729
+ this.timeProvider = new FastTimeProvider(config.timeCacheIntervalUs);
2730
+ this.stats = {
2731
+ totalCalls: 0,
2732
+ bypassedCalls: 0,
2733
+ batchedCalls: 0,
2734
+ timeSavedNs: BigInt(0)
2735
+ };
2736
+ }
2737
+ /**
2738
+ * Initialize the syscall bypass manager
2739
+ */
2740
+ initialize() {
2741
+ if (this.config.enableFastTime) {
2742
+ this.timeProvider.start();
2743
+ }
2744
+ if (this.config.enableBatching) {
2745
+ this.startBatching();
2746
+ }
2747
+ }
2748
+ /**
2749
+ * Shutdown the syscall bypass manager
2750
+ */
2751
+ shutdown() {
2752
+ this.timeProvider.stop();
2753
+ if (this.batchTimer) {
2754
+ clearInterval(this.batchTimer);
2755
+ this.batchTimer = null;
2756
+ }
2757
+ this.flushBatch();
2758
+ }
2759
+ /**
2760
+ * Get fast cached time in nanoseconds
2761
+ */
2762
+ fastTimeNs() {
2763
+ this.stats.totalCalls++;
2764
+ this.stats.bypassedCalls++;
2765
+ return this.timeProvider.nowNs();
2766
+ }
2767
+ /**
2768
+ * Get fast cached time in microseconds
2769
+ */
2770
+ fastTimeUs() {
2771
+ return this.timeProvider.nowUs();
2772
+ }
2773
+ /**
2774
+ * Get fast cached time in milliseconds
2775
+ */
2776
+ fastTimeMs() {
2777
+ return this.timeProvider.nowMs();
2778
+ }
2779
+ /**
2780
+ * Queue a syscall for batching
2781
+ */
2782
+ queueSyscall(syscall) {
2783
+ if (!this.config.enableBatching) {
2784
+ syscall();
2785
+ return;
2786
+ }
2787
+ this.syscallQueue.push(syscall);
2788
+ this.stats.batchedCalls++;
2789
+ if (this.syscallQueue.length >= this.config.maxBatchSize) {
2790
+ this.flushBatch();
2791
+ }
2792
+ }
2793
+ /**
2794
+ * Execute a function with syscall bypass timing
2795
+ */
2796
+ measure(fn) {
2797
+ const start = this.timeProvider.preciseNowNs();
2798
+ const result = fn();
2799
+ const elapsed = this.timeProvider.preciseNowNs() - start;
2800
+ return { result, elapsedNs: elapsed };
2801
+ }
2802
+ /**
2803
+ * Get syscall bypass statistics
2804
+ */
2805
+ getStats() {
2806
+ const bypassRate = this.stats.totalCalls > 0 ? this.stats.bypassedCalls / this.stats.totalCalls : 0;
2807
+ return {
2808
+ ...this.stats,
2809
+ bypassRate
2810
+ };
2811
+ }
2812
+ /**
2813
+ * Reset statistics
2814
+ */
2815
+ resetStats() {
2816
+ this.stats = {
2817
+ totalCalls: 0,
2818
+ bypassedCalls: 0,
2819
+ batchedCalls: 0,
2820
+ timeSavedNs: BigInt(0)
2821
+ };
2822
+ }
2823
+ startBatching() {
2824
+ this.batchTimer = setInterval(() => {
2825
+ this.flushBatch();
2826
+ }, 1);
2827
+ }
2828
+ flushBatch() {
2829
+ while (this.syscallQueue.length > 0) {
2830
+ const syscall = this.syscallQueue.shift();
2831
+ if (syscall) {
2832
+ try {
2833
+ syscall();
2834
+ } catch (error) {
2835
+ console.error("Batched syscall error:", error);
2836
+ }
2837
+ }
2838
+ }
2839
+ }
2840
+ };
2841
+ function createSyscallBypassManager(config) {
2842
+ const fullConfig = { ...defaultSyscallBypassConfig(), ...config };
2843
+ return new SyscallBypassManager(fullConfig);
2844
+ }
2845
+ var globalTimeProvider = null;
2846
+ function getGlobalTimeProvider() {
2847
+ if (!globalTimeProvider) {
2848
+ globalTimeProvider = new FastTimeProvider();
2849
+ globalTimeProvider.start();
2850
+ }
2851
+ return globalTimeProvider;
2852
+ }
2853
+ function fastNowNs() {
2854
+ return getGlobalTimeProvider().nowNs();
2855
+ }
2856
+ function fastNowUs() {
2857
+ return getGlobalTimeProvider().nowUs();
2858
+ }
2859
+ function fastNowMs() {
2860
+ return getGlobalTimeProvider().nowMs();
2861
+ }
2862
+
2863
+ // src/perf/ultra-low-latency.ts
2864
+ function defaultUltraLowLatencyConfig() {
2865
+ return {
2866
+ memoryPoolSize: 1024,
2867
+ queueCapacity: 4096,
2868
+ enableBusySpin: true,
2869
+ spinCount: 1e3,
2870
+ enablePrefetch: true,
2871
+ numaAware: false
2872
+ };
2873
+ }
2874
+ var MemoryPool = class {
2875
+ pool = [];
2876
+ factory;
2877
+ resetFn;
2878
+ maxSize;
2879
+ leased = 0;
2880
+ constructor(factory, resetFn, maxSize = 1024) {
2881
+ this.factory = factory;
2882
+ this.resetFn = resetFn;
2883
+ this.maxSize = maxSize;
2884
+ for (let i = 0; i < maxSize; i++) {
2885
+ this.pool.push(factory());
2886
+ }
2887
+ }
2888
+ /**
2889
+ * Acquire an object from the pool
2890
+ */
2891
+ acquire() {
2892
+ this.leased++;
2893
+ if (this.pool.length > 0) {
2894
+ return this.pool.pop();
2895
+ }
2896
+ return this.factory();
2897
+ }
2898
+ /**
2899
+ * Release an object back to the pool
2900
+ */
2901
+ release(obj) {
2902
+ if (this.leased <= 0) return;
2903
+ this.leased--;
2904
+ if (this.pool.length < this.maxSize) {
2905
+ this.resetFn(obj);
2906
+ this.pool.push(obj);
2907
+ }
2908
+ }
2909
+ /**
2910
+ * Execute a function with a pooled object
2911
+ */
2912
+ with(fn) {
2913
+ const obj = this.acquire();
2914
+ try {
2915
+ return fn(obj);
2916
+ } finally {
2917
+ this.release(obj);
2918
+ }
2919
+ }
2920
+ /**
2921
+ * Get pool statistics
2922
+ */
2923
+ getStats() {
2924
+ return {
2925
+ available: this.pool.length,
2926
+ inUse: this.leased,
2927
+ total: this.pool.length + this.leased
2928
+ };
2929
+ }
2930
+ };
2931
+ var LockFreeQueue = class {
2932
+ buffer;
2933
+ capacity;
2934
+ mask;
2935
+ head = 0;
2936
+ // Write position
2937
+ tail = 0;
2938
+ // Read position
2939
+ config;
2940
+ constructor(capacity = 4096, config) {
2941
+ this.capacity = Math.pow(2, Math.ceil(Math.log2(capacity)));
2942
+ this.mask = this.capacity - 1;
2943
+ this.buffer = new Array(this.capacity).fill(void 0);
2944
+ this.config = config || defaultUltraLowLatencyConfig();
2945
+ }
2946
+ /**
2947
+ * Enqueue an item (producer only)
2948
+ */
2949
+ enqueue(item) {
2950
+ const nextHead = this.head + 1 & this.mask;
2951
+ if (nextHead === this.tail) {
2952
+ return false;
2953
+ }
2954
+ this.buffer[this.head] = item;
2955
+ this.head = nextHead;
2956
+ return true;
2957
+ }
2958
+ /**
2959
+ * Dequeue an item (consumer only)
2960
+ */
2961
+ dequeue() {
2962
+ if (this.tail === this.head) {
2963
+ return void 0;
2964
+ }
2965
+ const item = this.buffer[this.tail];
2966
+ this.buffer[this.tail] = void 0;
2967
+ this.tail = this.tail + 1 & this.mask;
2968
+ return item;
2969
+ }
2970
+ /**
2971
+ * Try dequeue with spinning
2972
+ */
2973
+ dequeueSpin(timeoutUs = 1e3) {
2974
+ const startTime = performance.now();
2975
+ const timeoutMs = timeoutUs / 1e3;
2976
+ let spins = 0;
2977
+ while (performance.now() - startTime < timeoutMs) {
2978
+ const item = this.dequeue();
2979
+ if (item !== void 0) {
2980
+ return item;
2981
+ }
2982
+ if (this.config.enableBusySpin && spins < this.config.spinCount) {
2983
+ spins++;
2984
+ continue;
2985
+ }
2986
+ spins = 0;
2987
+ }
2988
+ return void 0;
2989
+ }
2990
+ /**
2991
+ * Get current size
2992
+ */
2993
+ size() {
2994
+ return this.head - this.tail & this.mask;
2995
+ }
2996
+ /**
2997
+ * Check if empty
2998
+ */
2999
+ isEmpty() {
3000
+ return this.head === this.tail;
3001
+ }
3002
+ /**
3003
+ * Check if full
3004
+ */
3005
+ isFull() {
3006
+ return (this.head + 1 & this.mask) === this.tail;
3007
+ }
3008
+ /**
3009
+ * Clear the queue
3010
+ */
3011
+ clear() {
3012
+ this.head = 0;
3013
+ this.tail = 0;
3014
+ this.buffer.fill(void 0);
3015
+ }
3016
+ };
3017
+ var MPMCQueue = class {
3018
+ buffer;
3019
+ capacity;
3020
+ mask;
3021
+ enqueuePos = 0;
3022
+ dequeuePos = 0;
3023
+ constructor(capacity = 4096) {
3024
+ this.capacity = Math.pow(2, Math.ceil(Math.log2(capacity)));
3025
+ this.mask = this.capacity - 1;
3026
+ this.buffer = new Array(this.capacity);
3027
+ for (let i = 0; i < this.capacity; i++) {
3028
+ this.buffer[i] = { item: void 0, sequence: i };
3029
+ }
3030
+ }
3031
+ /**
3032
+ * Enqueue an item (thread-safe)
3033
+ */
3034
+ enqueue(item) {
3035
+ let pos = this.enqueuePos;
3036
+ while (true) {
3037
+ const slot = this.buffer[pos & this.mask];
3038
+ const seq = slot.sequence;
3039
+ const diff = seq - pos;
3040
+ if (diff === 0) {
3041
+ if (this.compareAndSwapEnqueuePos(pos, pos + 1)) {
3042
+ slot.item = item;
3043
+ slot.sequence = pos + 1;
3044
+ return true;
3045
+ }
3046
+ pos = this.enqueuePos;
3047
+ } else if (diff < 0) {
3048
+ return false;
3049
+ } else {
3050
+ pos = this.enqueuePos;
3051
+ }
3052
+ }
3053
+ }
3054
+ /**
3055
+ * Dequeue an item (thread-safe)
3056
+ */
3057
+ dequeue() {
3058
+ let pos = this.dequeuePos;
3059
+ while (true) {
3060
+ const slot = this.buffer[pos & this.mask];
3061
+ const seq = slot.sequence;
3062
+ const diff = seq - (pos + 1);
3063
+ if (diff === 0) {
3064
+ if (this.compareAndSwapDequeuePos(pos, pos + 1)) {
3065
+ const item = slot.item;
3066
+ slot.item = void 0;
3067
+ slot.sequence = pos + this.mask + 1;
3068
+ return item;
3069
+ }
3070
+ pos = this.dequeuePos;
3071
+ } else if (diff < 0) {
3072
+ return void 0;
3073
+ } else {
3074
+ pos = this.dequeuePos;
3075
+ }
3076
+ }
3077
+ }
3078
+ compareAndSwapEnqueuePos(expected, value) {
3079
+ if (this.enqueuePos === expected) {
3080
+ this.enqueuePos = value;
3081
+ return true;
3082
+ }
3083
+ return false;
3084
+ }
3085
+ compareAndSwapDequeuePos(expected, value) {
3086
+ if (this.dequeuePos === expected) {
3087
+ this.dequeuePos = value;
3088
+ return true;
3089
+ }
3090
+ return false;
3091
+ }
3092
+ };
3093
+ var LatencyOptimizer = class {
3094
+ latencies = [];
3095
+ maxSamples;
3096
+ config;
3097
+ optimizationCallbacks = [];
3098
+ constructor(maxSamples = 1e4, config) {
3099
+ this.maxSamples = maxSamples;
3100
+ this.config = config || defaultUltraLowLatencyConfig();
3101
+ }
3102
+ /**
3103
+ * Record a latency measurement
3104
+ */
3105
+ recordLatency(latencyUs) {
3106
+ this.latencies.push(latencyUs);
3107
+ if (this.latencies.length > this.maxSamples) {
3108
+ this.latencies.shift();
3109
+ }
3110
+ }
3111
+ /**
3112
+ * Measure and record function execution time
3113
+ */
3114
+ measure(fn) {
3115
+ const start = performance.now();
3116
+ const result = fn();
3117
+ const latencyUs = (performance.now() - start) * 1e3;
3118
+ this.recordLatency(latencyUs);
3119
+ return { result, latencyUs };
3120
+ }
3121
+ /**
3122
+ * Get latency statistics
3123
+ */
3124
+ getStats() {
3125
+ if (this.latencies.length === 0) {
3126
+ return {
3127
+ minLatencyUs: 0,
3128
+ maxLatencyUs: 0,
3129
+ avgLatencyUs: 0,
3130
+ p50LatencyUs: 0,
3131
+ p99LatencyUs: 0,
3132
+ p999LatencyUs: 0,
3133
+ totalOperations: 0
3134
+ };
3135
+ }
3136
+ const sorted = [...this.latencies].sort((a, b) => a - b);
3137
+ const n = sorted.length;
3138
+ return {
3139
+ minLatencyUs: sorted[0] ?? 0,
3140
+ maxLatencyUs: sorted[n - 1] ?? 0,
3141
+ avgLatencyUs: sorted.reduce((a, b) => a + b, 0) / n,
3142
+ p50LatencyUs: sorted[Math.floor(n * 0.5)] ?? 0,
3143
+ p99LatencyUs: sorted[Math.floor(n * 0.99)] ?? 0,
3144
+ p999LatencyUs: sorted[Math.floor(n * 0.999)] ?? 0,
3145
+ totalOperations: n
3146
+ };
3147
+ }
3148
+ /**
3149
+ * Register an optimization callback
3150
+ */
3151
+ onOptimization(callback) {
3152
+ this.optimizationCallbacks.push(callback);
3153
+ }
3154
+ /**
3155
+ * Trigger optimization
3156
+ */
3157
+ optimize() {
3158
+ for (const callback of this.optimizationCallbacks) {
3159
+ try {
3160
+ callback();
3161
+ } catch (error) {
3162
+ console.error("Optimization callback error:", error);
3163
+ }
3164
+ }
3165
+ }
3166
+ /**
3167
+ * Reset statistics
3168
+ */
3169
+ reset() {
3170
+ this.latencies = [];
3171
+ }
3172
+ };
3173
+ function prefetch(obj) {
3174
+ if (obj && typeof obj === "object") {
3175
+ const key = Object.keys(obj)[0];
3176
+ const _ = key === void 0 ? void 0 : obj[key];
3177
+ }
3178
+ }
3179
+ function prefetchArray(arr, index) {
3180
+ const _ = arr[index];
3181
+ }
3182
+ function createMemoryPool(factory, resetFn, size) {
3183
+ return new MemoryPool(factory, resetFn, size || defaultUltraLowLatencyConfig().memoryPoolSize);
3184
+ }
3185
+ function createLockFreeQueue(capacity) {
3186
+ return new LockFreeQueue(capacity);
3187
+ }
3188
+ function createMPMCQueue(capacity) {
3189
+ return new MPMCQueue(capacity);
3190
+ }
3191
+ function busySpin(iterations) {
3192
+ for (let i = 0; i < iterations; i++) {
3193
+ Math.random();
3194
+ }
3195
+ }
3196
+ function yieldToEventLoop() {
3197
+ return new Promise((resolve) => setImmediate(resolve));
3198
+ }
3199
+
3200
+ // src/perf/zero-copy.ts
3201
+ function defaultBufferPoolConfig() {
3202
+ return {
3203
+ bufferSize: 4096,
3204
+ poolSize: 128,
3205
+ autoExpand: true,
3206
+ maxPoolSize: 1024
3207
+ };
3208
+ }
3209
+ var ZeroCopyBuffer = class _ZeroCopyBuffer {
3210
+ buffer;
3211
+ view;
3212
+ uint8View;
3213
+ offset = 0;
3214
+ constructor(size = 4096) {
3215
+ this.buffer = new ArrayBuffer(size);
3216
+ this.view = new DataView(this.buffer);
3217
+ this.uint8View = new Uint8Array(this.buffer);
3218
+ }
3219
+ /**
3220
+ * Create from existing buffer (zero-copy)
3221
+ */
3222
+ static from(buffer) {
3223
+ const zc = new _ZeroCopyBuffer(0);
3224
+ zc.buffer = buffer;
3225
+ zc.view = new DataView(buffer);
3226
+ zc.uint8View = new Uint8Array(buffer);
3227
+ return zc;
3228
+ }
3229
+ /**
3230
+ * Create a view into this buffer without copying
3231
+ */
3232
+ slice(start, end) {
3233
+ return new Uint8Array(this.buffer, start, end - start);
3234
+ }
3235
+ /**
3236
+ * Get current write offset
3237
+ */
3238
+ getOffset() {
3239
+ return this.offset;
3240
+ }
3241
+ /**
3242
+ * Set write offset
3243
+ */
3244
+ setOffset(offset) {
3245
+ this.offset = offset;
3246
+ }
3247
+ /**
3248
+ * Get buffer capacity
3249
+ */
3250
+ capacity() {
3251
+ return this.buffer.byteLength;
3252
+ }
3253
+ /**
3254
+ * Write Uint8 at current offset
3255
+ */
3256
+ writeUint8(value) {
3257
+ this.view.setUint8(this.offset, value);
3258
+ this.offset += 1;
3259
+ }
3260
+ /**
3261
+ * Write Uint16 at current offset (little-endian)
3262
+ */
3263
+ writeUint16(value) {
3264
+ this.view.setUint16(this.offset, value, true);
3265
+ this.offset += 2;
3266
+ }
3267
+ /**
3268
+ * Write Uint32 at current offset (little-endian)
3269
+ */
3270
+ writeUint32(value) {
3271
+ this.view.setUint32(this.offset, value, true);
3272
+ this.offset += 4;
3273
+ }
3274
+ /**
3275
+ * Write BigUint64 at current offset (little-endian)
3276
+ */
3277
+ writeUint64(value) {
3278
+ this.view.setBigUint64(this.offset, value, true);
3279
+ this.offset += 8;
3280
+ }
3281
+ /**
3282
+ * Write bytes at current offset
3283
+ */
3284
+ writeBytes(bytes) {
3285
+ this.uint8View.set(bytes, this.offset);
3286
+ this.offset += bytes.length;
3287
+ }
3288
+ /**
3289
+ * Read Uint8 at offset
3290
+ */
3291
+ readUint8(offset) {
3292
+ return this.view.getUint8(offset);
3293
+ }
3294
+ /**
3295
+ * Read Uint16 at offset (little-endian)
3296
+ */
3297
+ readUint16(offset) {
3298
+ return this.view.getUint16(offset, true);
3299
+ }
3300
+ /**
3301
+ * Read Uint32 at offset (little-endian)
3302
+ */
3303
+ readUint32(offset) {
3304
+ return this.view.getUint32(offset, true);
3305
+ }
3306
+ /**
3307
+ * Read BigUint64 at offset (little-endian)
3308
+ */
3309
+ readUint64(offset) {
3310
+ return this.view.getBigUint64(offset, true);
3311
+ }
3312
+ /**
3313
+ * Read bytes at offset
3314
+ */
3315
+ readBytes(offset, length) {
3316
+ return new Uint8Array(this.buffer, offset, length);
3317
+ }
3318
+ /**
3319
+ * Get the underlying ArrayBuffer
3320
+ */
3321
+ getBuffer() {
3322
+ return this.buffer;
3323
+ }
3324
+ /**
3325
+ * Get as Uint8Array (full buffer)
3326
+ */
3327
+ asUint8Array() {
3328
+ return this.uint8View;
3329
+ }
3330
+ /**
3331
+ * Get used portion as Uint8Array (zero-copy view)
3332
+ */
3333
+ asUsedUint8Array() {
3334
+ return new Uint8Array(this.buffer, 0, this.offset);
3335
+ }
3336
+ /**
3337
+ * Reset offset to beginning
3338
+ */
3339
+ reset() {
3340
+ this.offset = 0;
3341
+ }
3342
+ /**
3343
+ * Ensure capacity (creates new buffer if needed, copies data)
3344
+ */
3345
+ ensureCapacity(minCapacity) {
3346
+ if (this.buffer.byteLength >= minCapacity) {
3347
+ return;
3348
+ }
3349
+ const newCapacity = Math.max(minCapacity, this.buffer.byteLength * 2);
3350
+ const newBuffer = new ArrayBuffer(newCapacity);
3351
+ const newUint8 = new Uint8Array(newBuffer);
3352
+ newUint8.set(this.uint8View);
3353
+ this.buffer = newBuffer;
3354
+ this.view = new DataView(newBuffer);
3355
+ this.uint8View = newUint8;
3356
+ }
3357
+ };
3358
+ var BufferPool = class {
3359
+ pool = [];
3360
+ inUse = /* @__PURE__ */ new Set();
3361
+ config;
3362
+ constructor(config = defaultBufferPoolConfig()) {
3363
+ this.config = config;
3364
+ for (let i = 0; i < config.poolSize; i++) {
3365
+ this.pool.push(new ArrayBuffer(config.bufferSize));
3366
+ }
3367
+ }
3368
+ /**
3369
+ * Acquire a buffer from the pool
3370
+ */
3371
+ acquire() {
3372
+ if (this.pool.length > 0) {
3373
+ const buffer = this.pool.pop();
3374
+ this.inUse.add(buffer);
3375
+ return buffer;
3376
+ }
3377
+ if (this.config.autoExpand && this.pool.length + this.inUse.size < this.config.maxPoolSize) {
3378
+ const buffer = new ArrayBuffer(this.config.bufferSize);
3379
+ this.inUse.add(buffer);
3380
+ return buffer;
3381
+ }
3382
+ throw new Error("Buffer pool exhausted");
3383
+ }
3384
+ /**
3385
+ * Acquire a ZeroCopyBuffer wrapper
3386
+ */
3387
+ acquireZeroCopyBuffer() {
3388
+ const buffer = this.acquire();
3389
+ return ZeroCopyBuffer.from(buffer);
3390
+ }
3391
+ /**
3392
+ * Release a buffer back to the pool
3393
+ */
3394
+ release(buffer) {
3395
+ if (!this.inUse.has(buffer)) {
3396
+ return;
3397
+ }
3398
+ this.inUse.delete(buffer);
3399
+ if (this.pool.length < this.config.maxPoolSize) {
3400
+ this.pool.push(buffer);
3401
+ }
3402
+ }
3403
+ /**
3404
+ * Execute a function with a pooled buffer
3405
+ */
3406
+ with(fn) {
3407
+ const buffer = this.acquire();
3408
+ try {
3409
+ return fn(buffer);
3410
+ } finally {
3411
+ this.release(buffer);
3412
+ }
3413
+ }
3414
+ /**
3415
+ * Get pool statistics
3416
+ */
3417
+ getStats() {
3418
+ return {
3419
+ available: this.pool.length,
3420
+ inUse: this.inUse.size,
3421
+ total: this.pool.length + this.inUse.size
3422
+ };
3423
+ }
3424
+ /**
3425
+ * Clear all buffers
3426
+ */
3427
+ clear() {
3428
+ this.pool = [];
3429
+ this.inUse.clear();
3430
+ }
3431
+ };
3432
+ var ZeroCopySerializer = class {
3433
+ buffer;
3434
+ textEncoder;
3435
+ textDecoder;
3436
+ constructor(initialSize = 4096) {
3437
+ this.buffer = new ZeroCopyBuffer(initialSize);
3438
+ this.textEncoder = new TextEncoder();
3439
+ this.textDecoder = new TextDecoder();
3440
+ }
3441
+ /**
3442
+ * Serialize a string (length-prefixed)
3443
+ */
3444
+ writeString(value) {
3445
+ const bytes = this.textEncoder.encode(value);
3446
+ this.buffer.writeUint32(bytes.length);
3447
+ this.buffer.writeBytes(bytes);
3448
+ }
3449
+ /**
3450
+ * Serialize a PublicKey (32 bytes)
3451
+ */
3452
+ writePublicKey(bytes) {
3453
+ if (bytes.length !== 32) {
3454
+ throw new Error("PublicKey must be 32 bytes");
3455
+ }
3456
+ this.buffer.writeBytes(bytes);
3457
+ }
3458
+ /**
3459
+ * Serialize a BigInt (8 bytes)
3460
+ */
3461
+ writeBigInt(value) {
3462
+ this.buffer.writeUint64(value);
3463
+ }
3464
+ /**
3465
+ * Serialize a number (4 bytes)
3466
+ */
3467
+ writeNumber(value) {
3468
+ this.buffer.writeUint32(value);
3469
+ }
3470
+ /**
3471
+ * Serialize a boolean (1 byte)
3472
+ */
3473
+ writeBoolean(value) {
3474
+ this.buffer.writeUint8(value ? 1 : 0);
3475
+ }
3476
+ /**
3477
+ * Serialize bytes with length prefix
3478
+ */
3479
+ writeByteArray(bytes) {
3480
+ this.buffer.writeUint32(bytes.length);
3481
+ this.buffer.writeBytes(bytes);
3482
+ }
3483
+ /**
3484
+ * Deserialize a string
3485
+ */
3486
+ readString(offset) {
3487
+ const length = this.buffer.readUint32(offset);
3488
+ const bytes = this.buffer.readBytes(offset + 4, length);
3489
+ const value = this.textDecoder.decode(bytes);
3490
+ return { value, nextOffset: offset + 4 + length };
3491
+ }
3492
+ /**
3493
+ * Deserialize a PublicKey
3494
+ */
3495
+ readPublicKey(offset) {
3496
+ const value = this.buffer.readBytes(offset, 32);
3497
+ return { value, nextOffset: offset + 32 };
3498
+ }
3499
+ /**
3500
+ * Deserialize a BigInt
3501
+ */
3502
+ readBigInt(offset) {
3503
+ const value = this.buffer.readUint64(offset);
3504
+ return { value, nextOffset: offset + 8 };
3505
+ }
3506
+ /**
3507
+ * Deserialize a number
3508
+ */
3509
+ readNumber(offset) {
3510
+ const value = this.buffer.readUint32(offset);
3511
+ return { value, nextOffset: offset + 4 };
3512
+ }
3513
+ /**
3514
+ * Deserialize a boolean
3515
+ */
3516
+ readBoolean(offset) {
3517
+ const value = this.buffer.readUint8(offset) !== 0;
3518
+ return { value, nextOffset: offset + 1 };
3519
+ }
3520
+ /**
3521
+ * Deserialize a byte array
3522
+ */
3523
+ readByteArray(offset) {
3524
+ const length = this.buffer.readUint32(offset);
3525
+ const value = this.buffer.readBytes(offset + 4, length);
3526
+ return { value, nextOffset: offset + 4 + length };
3527
+ }
3528
+ /**
3529
+ * Get serialized data as Uint8Array (zero-copy view)
3530
+ */
3531
+ getData() {
3532
+ return this.buffer.asUsedUint8Array();
3533
+ }
3534
+ /**
3535
+ * Reset for reuse
3536
+ */
3537
+ reset() {
3538
+ this.buffer.reset();
3539
+ }
3540
+ /**
3541
+ * Get current offset
3542
+ */
3543
+ getOffset() {
3544
+ return this.buffer.getOffset();
3545
+ }
3546
+ };
3547
+ var FixedBufferView = class {
3548
+ buffer;
3549
+ view;
3550
+ uint8View;
3551
+ baseOffset;
3552
+ constructor(buffer, offset, size) {
3553
+ this.buffer = buffer;
3554
+ this.view = new DataView(buffer, offset, size);
3555
+ this.uint8View = new Uint8Array(buffer, offset, size);
3556
+ this.baseOffset = offset;
3557
+ }
3558
+ /**
3559
+ * Get Uint8 at relative offset
3560
+ */
3561
+ getUint8(offset) {
3562
+ return this.view.getUint8(offset);
3563
+ }
3564
+ /**
3565
+ * Set Uint8 at relative offset
3566
+ */
3567
+ setUint8(offset, value) {
3568
+ this.view.setUint8(offset, value);
3569
+ }
3570
+ /**
3571
+ * Get Uint32 at relative offset
3572
+ */
3573
+ getUint32(offset) {
3574
+ return this.view.getUint32(offset, true);
3575
+ }
3576
+ /**
3577
+ * Set Uint32 at relative offset
3578
+ */
3579
+ setUint32(offset, value) {
3580
+ this.view.setUint32(offset, value, true);
3581
+ }
3582
+ /**
3583
+ * Get BigUint64 at relative offset
3584
+ */
3585
+ getUint64(offset) {
3586
+ return this.view.getBigUint64(offset, true);
3587
+ }
3588
+ /**
3589
+ * Set BigUint64 at relative offset
3590
+ */
3591
+ setUint64(offset, value) {
3592
+ this.view.setBigUint64(offset, value, true);
3593
+ }
3594
+ /**
3595
+ * Get bytes at relative offset
3596
+ */
3597
+ getBytes(offset, length) {
3598
+ return new Uint8Array(this.buffer, this.baseOffset + offset, length);
3599
+ }
3600
+ /**
3601
+ * Set bytes at relative offset
3602
+ */
3603
+ setBytes(offset, bytes) {
3604
+ this.uint8View.set(bytes, offset);
3605
+ }
3606
+ /**
3607
+ * Get the underlying ArrayBuffer
3608
+ */
3609
+ getBuffer() {
3610
+ return this.buffer;
3611
+ }
3612
+ /**
3613
+ * Get the base offset
3614
+ */
3615
+ getBaseOffset() {
3616
+ return this.baseOffset;
3617
+ }
3618
+ };
3619
+ function createBufferPool(config) {
3620
+ const fullConfig = { ...defaultBufferPoolConfig(), ...config };
3621
+ return new BufferPool(fullConfig);
3622
+ }
3623
+ function createZeroCopyBuffer(size) {
3624
+ return new ZeroCopyBuffer(size);
3625
+ }
3626
+ function createSerializer(initialSize) {
3627
+ return new ZeroCopySerializer(initialSize);
3628
+ }
3629
+ function copyBytes(src, dst, dstOffset = 0) {
3630
+ dst.set(src, dstOffset);
3631
+ }
3632
+ function createView(buffer, offset, length) {
3633
+ return new Uint8Array(buffer, offset, length);
3634
+ }
3635
+ // Annotate the CommonJS export names for ESM import in node:
3636
+ 0 && (module.exports = {
3637
+ AlignedBuffer,
3638
+ AsyncSocket,
3639
+ BranchOptimizer,
3640
+ BufferPool,
3641
+ CACHE_LINE_SIZE,
3642
+ CPUAffinity,
3643
+ CacheOptimizer,
3644
+ ComputeBudgetOptimizer,
3645
+ CryptoSIMD,
3646
+ DirectIOFile,
3647
+ FastTimeProvider,
3648
+ FixedBufferView,
3649
+ Float32x4,
3650
+ FuncCache,
3651
+ HardwareMonitor,
3652
+ IOBatchProcessor,
3653
+ IOOperation,
3654
+ InstructionBatcher,
3655
+ KernelBypassManager,
3656
+ LatencyMonitor,
3657
+ LatencyOptimizer,
3658
+ LockFreeQueue,
3659
+ LoopOptimizer,
3660
+ MPMCQueue,
3661
+ MemoryMappedFile,
3662
+ MemoryOps,
3663
+ MemoryPool,
3664
+ NUMAOptimizer,
3665
+ OptimizedMath,
3666
+ PerformanceGovernor,
3667
+ ProfileGuidedOptimizer,
3668
+ RealtimeTuner,
3669
+ SIMDDetector,
3670
+ SchedulerPolicy,
3671
+ SpinLock,
3672
+ SyscallBypassManager,
3673
+ ThreadPriority,
3674
+ ThreadPriorityLevel,
3675
+ TransactionBuilder,
3676
+ TransactionOptimizer,
3677
+ VectorizedMath,
3678
+ ZeroCopyBuffer,
3679
+ ZeroCopySerializer,
3680
+ busySpin,
3681
+ busyWait,
3682
+ calculateOptimalPrice,
3683
+ coldPath,
3684
+ copyBytes,
3685
+ createBufferPool,
3686
+ createCPUAffinity,
3687
+ createCacheOptimizer,
3688
+ createComputeBudgetOptimizer,
3689
+ createCryptoSIMD,
3690
+ createHardwareMonitor,
3691
+ createInstructionBatcher,
3692
+ createLatencyMonitor,
3693
+ createLockFreeQueue,
3694
+ createMPMCQueue,
3695
+ createMemoryPool,
3696
+ createNUMAOptimizer,
3697
+ createPerformanceGovernor,
3698
+ createRealtimeTuner,
3699
+ createSIMDDetector,
3700
+ createSerializer,
3701
+ createSyscallBypassManager,
3702
+ createThreadPriority,
3703
+ createTimer,
3704
+ createTransactionBuilder,
3705
+ createTransactionOptimizer,
3706
+ createVectorizedMath,
3707
+ createView,
3708
+ createZeroCopyBuffer,
3709
+ defaultAffinityConfig,
3710
+ defaultBufferPoolConfig,
3711
+ defaultIOUringConfig,
3712
+ defaultJITConfig,
3713
+ defaultNUMAConfig,
3714
+ defaultRealtimeConfig,
3715
+ defaultSIMDConfig,
3716
+ defaultSyscallBypassConfig,
3717
+ defaultTransactionConfig,
3718
+ defaultUltraLowLatencyConfig,
3719
+ detectCPUFeatures,
3720
+ estimateCompute,
3721
+ fastInvSqrt,
3722
+ fastNowMs,
3723
+ fastNowNs,
3724
+ fastNowUs,
3725
+ getGlobalTimeProvider,
3726
+ getKernelBypassManager,
3727
+ getOptimalSIMDWidth,
3728
+ getProfileOptimizer,
3729
+ getSystemCPUInfo,
3730
+ getSystemMemoryInfo,
3731
+ hotPath,
3732
+ isSIMDAvailable,
3733
+ likely,
3734
+ measureTime,
3735
+ prefetch,
3736
+ prefetchArray,
3737
+ prefetchHint,
3738
+ profile,
3739
+ spinLock,
3740
+ unlikely,
3741
+ yieldToEventLoop
3742
+ });