@typeberry/lib 0.4.1-bb6dbac → 0.4.1-c2b0fdd

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 (4) hide show
  1. package/index.cjs +989 -108
  2. package/index.d.ts +99 -10
  3. package/index.js +989 -108
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -101,6 +101,15 @@ class Compatibility {
101
101
  function isBrowser() {
102
102
  return typeof process === "undefined" || typeof process.abort === "undefined";
103
103
  }
104
+ /**
105
+ * Get current time in milliseconds (works in both Node and browser).
106
+ *
107
+ * Node.js implementation converts hrtime bigint nanoseconds to milliseconds.
108
+ * This is safe because dividing nanoseconds by 1_000_000 yields milliseconds,
109
+ * which remain well below Number.MAX_SAFE_INTEGER for practical runtimes
110
+ * (would take ~285 years to overflow).
111
+ */
112
+ const now = isBrowser() ? () => performance.now() : () => Number(process.hrtime.bigint() / 1000000n);
104
113
  /**
105
114
  * A function to perform runtime assertions.
106
115
  *
@@ -189,19 +198,10 @@ function inspect(val) {
189
198
  return v;
190
199
  }
191
200
  /** Utility function to measure time taken for some operation [ms]. */
192
- const measure = isBrowser()
193
- ? (id) => {
194
- const start = performance.now();
195
- return () => `${id} took ${performance.now() - start}ms`;
196
- }
197
- : (id) => {
198
- const start = process.hrtime.bigint();
199
- return () => {
200
- const tookNano = process.hrtime.bigint() - start;
201
- const tookMilli = Number(tookNano / 1000000n).toFixed(2);
202
- return `${id} took ${tookMilli}ms`;
203
- };
204
- };
201
+ function measure(id) {
202
+ const start = now();
203
+ return () => `${id} took ${(now() - start).toFixed(2)}ms`;
204
+ }
205
205
  /** A class that adds `toString` method that prints all properties of an object. */
206
206
  class WithDebug {
207
207
  toString() {
@@ -606,10 +606,12 @@ var index$y = /*#__PURE__*/Object.freeze({
606
606
  assertNever: assertNever,
607
607
  check: check,
608
608
  deepEqual: deepEqual,
609
+ env: env,
609
610
  inspect: inspect,
610
611
  isBrowser: isBrowser,
611
612
  lazyInspect: lazyInspect,
612
613
  measure: measure,
614
+ now: now,
613
615
  resultToString: resultToString,
614
616
  safeAllocUint8Array: safeAllocUint8Array,
615
617
  seeThrough: seeThrough,
@@ -3848,7 +3850,7 @@ class Mutex {
3848
3850
  }
3849
3851
 
3850
3852
  var _a;
3851
- function getGlobal() {
3853
+ function getGlobal$1() {
3852
3854
  if (typeof globalThis !== "undefined")
3853
3855
  return globalThis;
3854
3856
  if (typeof self !== "undefined")
@@ -3857,7 +3859,7 @@ function getGlobal() {
3857
3859
  return window;
3858
3860
  return global;
3859
3861
  }
3860
- const globalObject = getGlobal();
3862
+ const globalObject = getGlobal$1();
3861
3863
  const nodeBuffer = (_a = globalObject.Buffer) !== null && _a !== void 0 ? _a : null;
3862
3864
  const textEncoder = globalObject.TextEncoder
3863
3865
  ? new globalObject.TextEncoder()
@@ -7794,7 +7796,7 @@ class JipChainSpec extends WithDebug {
7794
7796
  }
7795
7797
 
7796
7798
  var $schema$1 = "https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json";
7797
- var version$1 = 1;
7799
+ var version$2 = 1;
7798
7800
  var flavor$1 = "tiny";
7799
7801
  var authorship$1 = {
7800
7802
  omit_seal_verification: false
@@ -7833,7 +7835,7 @@ var chain_spec$1 = {
7833
7835
  var database_base_path$1 = "./database";
7834
7836
  var defaultConfig = {
7835
7837
  $schema: $schema$1,
7836
- version: version$1,
7838
+ version: version$2,
7837
7839
  flavor: flavor$1,
7838
7840
  authorship: authorship$1,
7839
7841
  chain_spec: chain_spec$1,
@@ -7841,7 +7843,7 @@ var defaultConfig = {
7841
7843
  };
7842
7844
 
7843
7845
  var $schema = "https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json";
7844
- var version = 1;
7846
+ var version$1 = 1;
7845
7847
  var flavor = "tiny";
7846
7848
  var authorship = {
7847
7849
  omit_seal_verification: true
@@ -7879,7 +7881,7 @@ var chain_spec = {
7879
7881
  var database_base_path = "./database";
7880
7882
  var devConfig = {
7881
7883
  $schema: $schema,
7882
- version: version,
7884
+ version: version$1,
7883
7885
  flavor: flavor,
7884
7886
  authorship: authorship,
7885
7887
  chain_spec: chain_spec,
@@ -8146,13 +8148,13 @@ class Logger {
8146
8148
  *
8147
8149
  * Changing the options affects all previously created loggers.
8148
8150
  */
8149
- static configureAllFromOptions(options) {
8151
+ static configureAllFromOptions(options, createTransport = ConsoleTransport.create) {
8150
8152
  // find minimal level to optimise logging in case
8151
8153
  // we don't care about low-level logs.
8152
8154
  const minimalLevel = Array.from(options.modules.values()).reduce((level, modLevel) => {
8153
8155
  return level < modLevel ? level : modLevel;
8154
8156
  }, options.defaultLevel);
8155
- const transport = ConsoleTransport.create(minimalLevel, options);
8157
+ const transport = createTransport(minimalLevel, options);
8156
8158
  // set the global config
8157
8159
  GLOBAL_CONFIG.options = options;
8158
8160
  GLOBAL_CONFIG.transport = transport;
@@ -8178,8 +8180,11 @@ class Logger {
8178
8180
  }
8179
8181
  getLevelAndName() {
8180
8182
  if (this.cachedLevelAndName === undefined) {
8181
- const level = findLevel(this.config.options, this.moduleName);
8182
- const shortName = this.moduleName.replace(this.config.options.workingDir, "");
8183
+ // since we pad module name for better alignment, we need to
8184
+ // trim it for the lookup
8185
+ const moduleTrimmed = this.moduleName.trim();
8186
+ const level = findLevel(this.config.options, moduleTrimmed);
8187
+ const shortName = moduleTrimmed.replace(this.config.options.workingDir, "");
8183
8188
  this.cachedLevelAndName = [level, shortName];
8184
8189
  }
8185
8190
  return this.cachedLevelAndName;
@@ -8212,8 +8217,10 @@ class Logger {
8212
8217
 
8213
8218
  var index$m = /*#__PURE__*/Object.freeze({
8214
8219
  __proto__: null,
8220
+ ConsoleTransport: ConsoleTransport,
8215
8221
  get Level () { return Level; },
8216
8222
  Logger: Logger,
8223
+ findLevel: findLevel,
8217
8224
  parseLoggerOptions: parseLoggerOptions
8218
8225
  });
8219
8226
 
@@ -18117,7 +18124,7 @@ function emptyRegistersBuffer() {
18117
18124
  return safeAllocUint8Array(NO_OF_REGISTERS$1 * REGISTER_BYTE_SIZE);
18118
18125
  }
18119
18126
 
18120
- const IN_OUT_REG$f = 7;
18127
+ const IN_OUT_REG$g = 7;
18121
18128
  const OFFSET_REG = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? 9 : 11;
18122
18129
  const LEN_REG = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? 10 : 12;
18123
18130
  /**
@@ -18143,14 +18150,14 @@ class Info {
18143
18150
  account;
18144
18151
  index = tryAsHostCallIndex(5);
18145
18152
  basicGasCost = tryAsSmallGas(10);
18146
- tracedRegisters = traceRegisters(IN_OUT_REG$f, 8, OFFSET_REG, LEN_REG);
18153
+ tracedRegisters = traceRegisters(IN_OUT_REG$g, 8, OFFSET_REG, LEN_REG);
18147
18154
  constructor(currentServiceId, account) {
18148
18155
  this.currentServiceId = currentServiceId;
18149
18156
  this.account = account;
18150
18157
  }
18151
18158
  async execute(_gas, regs, memory) {
18152
18159
  // t
18153
- const serviceId = getServiceIdOrCurrent(IN_OUT_REG$f, regs, this.currentServiceId);
18160
+ const serviceId = getServiceIdOrCurrent(IN_OUT_REG$g, regs, this.currentServiceId);
18154
18161
  // o
18155
18162
  const outputStart = regs.get(8);
18156
18163
  // v
@@ -18176,10 +18183,10 @@ class Info {
18176
18183
  }
18177
18184
  logger$7.trace `[${this.currentServiceId}] INFO(${serviceId}, off: ${offset}, len: ${length}) <- ${BytesBlob.blobFrom(chunk)}`;
18178
18185
  if (accountInfo === null) {
18179
- regs.set(IN_OUT_REG$f, HostCallResult.NONE);
18186
+ regs.set(IN_OUT_REG$g, HostCallResult.NONE);
18180
18187
  return;
18181
18188
  }
18182
- regs.set(IN_OUT_REG$f, valueLength);
18189
+ regs.set(IN_OUT_REG$g, valueLength);
18183
18190
  }
18184
18191
  }
18185
18192
  /**
@@ -19723,7 +19730,7 @@ function finalize(mergeContext) {
19723
19730
  };
19724
19731
  }
19725
19732
 
19726
- const IN_OUT_REG$e = 7;
19733
+ const IN_OUT_REG$f = 7;
19727
19734
  /**
19728
19735
  * Assign new fixed-length authorization queue to some core and authorize a service for this core.
19729
19736
  *
@@ -19735,7 +19742,7 @@ class Assign {
19735
19742
  chainSpec;
19736
19743
  index = tryAsHostCallIndex(15);
19737
19744
  basicGasCost = tryAsSmallGas(10);
19738
- tracedRegisters = traceRegisters(IN_OUT_REG$e, 8);
19745
+ tracedRegisters = traceRegisters(IN_OUT_REG$f, 8);
19739
19746
  constructor(currentServiceId, partialState, chainSpec) {
19740
19747
  this.currentServiceId = currentServiceId;
19741
19748
  this.partialState = partialState;
@@ -19743,7 +19750,7 @@ class Assign {
19743
19750
  }
19744
19751
  async execute(_gas, regs, memory) {
19745
19752
  // c
19746
- const maybeCoreIndex = regs.get(IN_OUT_REG$e);
19753
+ const maybeCoreIndex = regs.get(IN_OUT_REG$f);
19747
19754
  // o
19748
19755
  const authorizationQueueStart = regs.get(8);
19749
19756
  // a
@@ -19756,7 +19763,7 @@ class Assign {
19756
19763
  return PvmExecution.Panic;
19757
19764
  }
19758
19765
  if (maybeCoreIndex >= this.chainSpec.coresCount) {
19759
- regs.set(IN_OUT_REG$e, HostCallResult.CORE);
19766
+ regs.set(IN_OUT_REG$f, HostCallResult.CORE);
19760
19767
  return;
19761
19768
  }
19762
19769
  // NOTE: Here we know the core index is valid
@@ -19766,18 +19773,18 @@ class Assign {
19766
19773
  const fixedSizeAuthQueue = FixedSizeArray.new(authQueue, AUTHORIZATION_QUEUE_SIZE);
19767
19774
  const result = this.partialState.updateAuthorizationQueue(coreIndex, fixedSizeAuthQueue, assigners);
19768
19775
  if (result.isOk) {
19769
- regs.set(IN_OUT_REG$e, HostCallResult.OK);
19776
+ regs.set(IN_OUT_REG$f, HostCallResult.OK);
19770
19777
  logger$7.trace `[${this.currentServiceId}] ASSIGN(${coreIndex}, ${fixedSizeAuthQueue}) <- OK`;
19771
19778
  return;
19772
19779
  }
19773
19780
  const e = result.error;
19774
19781
  if (e === UpdatePrivilegesError.UnprivilegedService) {
19775
- regs.set(IN_OUT_REG$e, HostCallResult.HUH);
19782
+ regs.set(IN_OUT_REG$f, HostCallResult.HUH);
19776
19783
  logger$7.trace `[${this.currentServiceId}] ASSIGN(${coreIndex}, ${fixedSizeAuthQueue}) <- HUH`;
19777
19784
  return;
19778
19785
  }
19779
19786
  if (e === UpdatePrivilegesError.InvalidServiceId) {
19780
- regs.set(IN_OUT_REG$e, HostCallResult.WHO);
19787
+ regs.set(IN_OUT_REG$f, HostCallResult.WHO);
19781
19788
  logger$7.trace `[${this.currentServiceId}] ASSIGN(${coreIndex}, ${fixedSizeAuthQueue}) <- HUH`;
19782
19789
  return;
19783
19790
  }
@@ -19785,7 +19792,7 @@ class Assign {
19785
19792
  }
19786
19793
  }
19787
19794
 
19788
- const IN_OUT_REG$d = 7;
19795
+ const IN_OUT_REG$e = 7;
19789
19796
  const serviceIdAndGasCodec = object({
19790
19797
  serviceId: u32.convert((i) => i, (o) => asOpaqueType(o)),
19791
19798
  gas: u64.convert((i) => tryAsU64(i), (o) => tryAsServiceGas(o)),
@@ -19802,8 +19809,8 @@ class Bless {
19802
19809
  index = tryAsHostCallIndex(14);
19803
19810
  basicGasCost = tryAsSmallGas(10);
19804
19811
  tracedRegisters = Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
19805
- ? traceRegisters(IN_OUT_REG$d, 8, 9, 10, 11, 12)
19806
- : traceRegisters(IN_OUT_REG$d, 8, 9, 10, 11);
19812
+ ? traceRegisters(IN_OUT_REG$e, 8, 9, 10, 11, 12)
19813
+ : traceRegisters(IN_OUT_REG$e, 8, 9, 10, 11);
19807
19814
  constructor(currentServiceId, partialState, chainSpec) {
19808
19815
  this.currentServiceId = currentServiceId;
19809
19816
  this.partialState = partialState;
@@ -19811,7 +19818,7 @@ class Bless {
19811
19818
  }
19812
19819
  async execute(_gas, regs, memory) {
19813
19820
  // `m`: manager service (can change privileged services)
19814
- const manager = getServiceId(regs.get(IN_OUT_REG$d));
19821
+ const manager = getServiceId(regs.get(IN_OUT_REG$e));
19815
19822
  // `a`: manages authorization queue
19816
19823
  const authorization = regs.get(8);
19817
19824
  // `v`: manages validator keys
@@ -19858,19 +19865,19 @@ class Bless {
19858
19865
  const updateResult = this.partialState.updatePrivilegedServices(manager, authorizers, delegator, registrar, autoAccumulate);
19859
19866
  if (updateResult.isOk) {
19860
19867
  logger$7.trace `[${this.currentServiceId}] BLESS(m: ${manager}, a: [${authorizers}], v: ${delegator}, r: ${registrar}, ${lazyInspect(autoAccumulate)}) <- OK`;
19861
- regs.set(IN_OUT_REG$d, HostCallResult.OK);
19868
+ regs.set(IN_OUT_REG$e, HostCallResult.OK);
19862
19869
  return;
19863
19870
  }
19864
19871
  const e = updateResult.error;
19865
19872
  // NOTE: `UpdatePrivilegesError.UnprivilegedService` won't happen in 0.7.1+
19866
19873
  if (e === UpdatePrivilegesError.UnprivilegedService) {
19867
19874
  logger$7.trace `[${this.currentServiceId}] BLESS(m: ${manager}, a: [${authorizers}], v: ${delegator}, r: ${registrar}, ${lazyInspect(autoAccumulate)}) <- HUH`;
19868
- regs.set(IN_OUT_REG$d, HostCallResult.HUH);
19875
+ regs.set(IN_OUT_REG$e, HostCallResult.HUH);
19869
19876
  return;
19870
19877
  }
19871
19878
  if (e === UpdatePrivilegesError.InvalidServiceId) {
19872
19879
  logger$7.trace `[${this.currentServiceId}] BLESS(m: ${manager}, a: [${authorizers}], v: ${delegator}, r: ${registrar}, ${lazyInspect(autoAccumulate)}) <- WHO`;
19873
- regs.set(IN_OUT_REG$d, HostCallResult.WHO);
19880
+ regs.set(IN_OUT_REG$e, HostCallResult.WHO);
19874
19881
  return;
19875
19882
  }
19876
19883
  assertNever(e);
@@ -19926,7 +19933,7 @@ class Checkpoint {
19926
19933
  }
19927
19934
  }
19928
19935
 
19929
- const IN_OUT_REG$c = 7;
19936
+ const IN_OUT_REG$d = 7;
19930
19937
  const VALIDATOR_DATA_BYTES = tryAsExactBytes(ValidatorData.Codec.sizeHint);
19931
19938
  /**
19932
19939
  * Designate a new set of validator keys.
@@ -19939,7 +19946,7 @@ class Designate {
19939
19946
  chainSpec;
19940
19947
  index = tryAsHostCallIndex(16);
19941
19948
  basicGasCost = tryAsSmallGas(10);
19942
- tracedRegisters = traceRegisters(IN_OUT_REG$c);
19949
+ tracedRegisters = traceRegisters(IN_OUT_REG$d);
19943
19950
  constructor(currentServiceId, partialState, chainSpec) {
19944
19951
  this.currentServiceId = currentServiceId;
19945
19952
  this.partialState = partialState;
@@ -19947,7 +19954,7 @@ class Designate {
19947
19954
  }
19948
19955
  async execute(_gas, regs, memory) {
19949
19956
  // `o`
19950
- const validatorsStart = regs.get(IN_OUT_REG$c);
19957
+ const validatorsStart = regs.get(IN_OUT_REG$d);
19951
19958
  const res = safeAllocUint8Array(VALIDATOR_DATA_BYTES * this.chainSpec.validatorsCount);
19952
19959
  const memoryReadResult = memory.loadInto(res, validatorsStart);
19953
19960
  // error while reading the memory.
@@ -19960,16 +19967,16 @@ class Designate {
19960
19967
  const result = this.partialState.updateValidatorsData(tryAsPerValidator(validatorsData, this.chainSpec));
19961
19968
  if (result.isError) {
19962
19969
  logger$7.trace `[${this.currentServiceId}] DESIGNATE([${validatorsData[0]}, ${validatorsData[1]}, ...]) <- HUH`;
19963
- regs.set(IN_OUT_REG$c, HostCallResult.HUH);
19970
+ regs.set(IN_OUT_REG$d, HostCallResult.HUH);
19964
19971
  }
19965
19972
  else {
19966
19973
  logger$7.trace `[${this.currentServiceId}] DESIGNATE([${validatorsData[0]}, ${validatorsData[1]}, ...]) <- OK`;
19967
- regs.set(IN_OUT_REG$c, HostCallResult.OK);
19974
+ regs.set(IN_OUT_REG$d, HostCallResult.OK);
19968
19975
  }
19969
19976
  }
19970
19977
  }
19971
19978
 
19972
- const IN_OUT_REG$b = 7;
19979
+ const IN_OUT_REG$c = 7;
19973
19980
  /**
19974
19981
  * Remove the provided service account and transfer the remaining balance to current service account.
19975
19982
  *
@@ -19980,14 +19987,14 @@ class Eject {
19980
19987
  partialState;
19981
19988
  index = tryAsHostCallIndex(21);
19982
19989
  basicGasCost = tryAsSmallGas(10);
19983
- tracedRegisters = traceRegisters(IN_OUT_REG$b, 8);
19990
+ tracedRegisters = traceRegisters(IN_OUT_REG$c, 8);
19984
19991
  constructor(currentServiceId, partialState) {
19985
19992
  this.currentServiceId = currentServiceId;
19986
19993
  this.partialState = partialState;
19987
19994
  }
19988
19995
  async execute(_gas, regs, memory) {
19989
19996
  // `d`: account to eject from (source)
19990
- const serviceId = getServiceId(regs.get(IN_OUT_REG$b));
19997
+ const serviceId = getServiceId(regs.get(IN_OUT_REG$c));
19991
19998
  // `o`: preimage hash start memory index
19992
19999
  const preimageHashStart = regs.get(8);
19993
20000
  // `h`: hash
@@ -19999,7 +20006,7 @@ class Eject {
19999
20006
  }
20000
20007
  // cannot eject self
20001
20008
  if (serviceId === this.currentServiceId) {
20002
- regs.set(IN_OUT_REG$b, HostCallResult.WHO);
20009
+ regs.set(IN_OUT_REG$c, HostCallResult.WHO);
20003
20010
  logger$7.trace `[${this.currentServiceId}] EJECT(${serviceId}, ${previousCodeHash}) <- WHO`;
20004
20011
  return;
20005
20012
  }
@@ -20007,17 +20014,17 @@ class Eject {
20007
20014
  // All good!
20008
20015
  if (result.isOk) {
20009
20016
  logger$7.trace `[${this.currentServiceId}] EJECT(${serviceId}, ${previousCodeHash}) <- OK`;
20010
- regs.set(IN_OUT_REG$b, HostCallResult.OK);
20017
+ regs.set(IN_OUT_REG$c, HostCallResult.OK);
20011
20018
  return;
20012
20019
  }
20013
20020
  const e = result.error;
20014
20021
  if (e === EjectError.InvalidService) {
20015
20022
  logger$7.trace `[${this.currentServiceId}] EJECT(${serviceId}, ${previousCodeHash}) <- WHO ${resultToString(result)}`;
20016
- regs.set(IN_OUT_REG$b, HostCallResult.WHO);
20023
+ regs.set(IN_OUT_REG$c, HostCallResult.WHO);
20017
20024
  }
20018
20025
  else if (e === EjectError.InvalidPreimage) {
20019
20026
  logger$7.trace `[${this.currentServiceId}] EJECT(${serviceId}, ${previousCodeHash}) <- HUH ${resultToString(result)}`;
20020
- regs.set(IN_OUT_REG$b, HostCallResult.HUH);
20027
+ regs.set(IN_OUT_REG$c, HostCallResult.HUH);
20021
20028
  }
20022
20029
  else {
20023
20030
  assertNever(e);
@@ -20025,7 +20032,7 @@ class Eject {
20025
20032
  }
20026
20033
  }
20027
20034
 
20028
- const IN_OUT_REG$a = 7;
20035
+ const IN_OUT_REG$b = 7;
20029
20036
  /**
20030
20037
  * Delete preimage hash or mark as unavailable if it was available.
20031
20038
  *
@@ -20036,14 +20043,14 @@ class Forget {
20036
20043
  partialState;
20037
20044
  index = tryAsHostCallIndex(24);
20038
20045
  basicGasCost = tryAsSmallGas(10);
20039
- tracedRegisters = traceRegisters(IN_OUT_REG$a, 8);
20046
+ tracedRegisters = traceRegisters(IN_OUT_REG$b, 8);
20040
20047
  constructor(currentServiceId, partialState) {
20041
20048
  this.currentServiceId = currentServiceId;
20042
20049
  this.partialState = partialState;
20043
20050
  }
20044
20051
  async execute(_gas, regs, memory) {
20045
20052
  // `o`
20046
- const hashStart = regs.get(IN_OUT_REG$a);
20053
+ const hashStart = regs.get(IN_OUT_REG$b);
20047
20054
  // `z`
20048
20055
  const length = regs.get(8);
20049
20056
  const hash = Bytes.zero(HASH_SIZE);
@@ -20056,15 +20063,15 @@ class Forget {
20056
20063
  const result = this.partialState.forgetPreimage(hash.asOpaque(), length);
20057
20064
  logger$7.trace `[${this.currentServiceId}] FORGET(${hash}, ${length}) <- ${resultToString(result)}`;
20058
20065
  if (result.isOk) {
20059
- regs.set(IN_OUT_REG$a, HostCallResult.OK);
20066
+ regs.set(IN_OUT_REG$b, HostCallResult.OK);
20060
20067
  }
20061
20068
  else {
20062
- regs.set(IN_OUT_REG$a, HostCallResult.HUH);
20069
+ regs.set(IN_OUT_REG$b, HostCallResult.HUH);
20063
20070
  }
20064
20071
  }
20065
20072
  }
20066
20073
 
20067
- const IN_OUT_REG$9 = 7;
20074
+ const IN_OUT_REG$a = 7;
20068
20075
  /**
20069
20076
  * Create a new service account.
20070
20077
  *
@@ -20076,15 +20083,15 @@ class New {
20076
20083
  index = tryAsHostCallIndex(18);
20077
20084
  basicGasCost = tryAsSmallGas(10);
20078
20085
  tracedRegisters = Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
20079
- ? traceRegisters(IN_OUT_REG$9, 8, 9, 10, 11, 12)
20080
- : traceRegisters(IN_OUT_REG$9, 8, 9, 10, 11);
20086
+ ? traceRegisters(IN_OUT_REG$a, 8, 9, 10, 11, 12)
20087
+ : traceRegisters(IN_OUT_REG$a, 8, 9, 10, 11);
20081
20088
  constructor(currentServiceId, partialState) {
20082
20089
  this.currentServiceId = currentServiceId;
20083
20090
  this.partialState = partialState;
20084
20091
  }
20085
20092
  async execute(_gas, regs, memory) {
20086
20093
  // `o`
20087
- const codeHashStart = regs.get(IN_OUT_REG$9);
20094
+ const codeHashStart = regs.get(IN_OUT_REG$a);
20088
20095
  // `l`
20089
20096
  const codeLength = regs.get(8);
20090
20097
  // `g`
@@ -20106,28 +20113,28 @@ class New {
20106
20113
  const assignedId = this.partialState.newService(codeHash.asOpaque(), codeLength, gas, allowance, gratisStorage, requestedServiceId);
20107
20114
  logger$7.trace `[${this.currentServiceId}] NEW(${codeHash}, ${codeLength}, ${gas}, ${allowance}, ${gratisStorage}, ${requestedServiceId}) <- ${resultToString(assignedId)}`;
20108
20115
  if (assignedId.isOk) {
20109
- regs.set(IN_OUT_REG$9, tryAsU64(assignedId.ok));
20116
+ regs.set(IN_OUT_REG$a, tryAsU64(assignedId.ok));
20110
20117
  return;
20111
20118
  }
20112
20119
  const e = assignedId.error;
20113
20120
  if (e === NewServiceError.InsufficientFunds) {
20114
- regs.set(IN_OUT_REG$9, HostCallResult.CASH);
20121
+ regs.set(IN_OUT_REG$a, HostCallResult.CASH);
20115
20122
  return;
20116
20123
  }
20117
20124
  if (e === NewServiceError.UnprivilegedService) {
20118
- regs.set(IN_OUT_REG$9, HostCallResult.HUH);
20125
+ regs.set(IN_OUT_REG$a, HostCallResult.HUH);
20119
20126
  return;
20120
20127
  }
20121
20128
  // Post 0.7.1
20122
20129
  if (e === NewServiceError.RegistrarServiceIdAlreadyTaken) {
20123
- regs.set(IN_OUT_REG$9, HostCallResult.FULL);
20130
+ regs.set(IN_OUT_REG$a, HostCallResult.FULL);
20124
20131
  return;
20125
20132
  }
20126
20133
  assertNever(e);
20127
20134
  }
20128
20135
  }
20129
20136
 
20130
- const IN_OUT_REG$8 = 7;
20137
+ const IN_OUT_REG$9 = 7;
20131
20138
  /**
20132
20139
  * Provide a preimage for a given service.
20133
20140
  *
@@ -20138,14 +20145,14 @@ class Provide {
20138
20145
  partialState;
20139
20146
  index = tryAsHostCallIndex(26);
20140
20147
  basicGasCost = tryAsSmallGas(10);
20141
- tracedRegisters = traceRegisters(IN_OUT_REG$8, 8, 9);
20148
+ tracedRegisters = traceRegisters(IN_OUT_REG$9, 8, 9);
20142
20149
  constructor(currentServiceId, partialState) {
20143
20150
  this.currentServiceId = currentServiceId;
20144
20151
  this.partialState = partialState;
20145
20152
  }
20146
20153
  async execute(_gas, regs, memory) {
20147
20154
  // `s`
20148
- const serviceId = getServiceIdOrCurrent(IN_OUT_REG$8, regs, this.currentServiceId);
20155
+ const serviceId = getServiceIdOrCurrent(IN_OUT_REG$9, regs, this.currentServiceId);
20149
20156
  // `o`
20150
20157
  const preimageStart = regs.get(8);
20151
20158
  // `z`
@@ -20161,16 +20168,16 @@ class Provide {
20161
20168
  const result = this.partialState.providePreimage(serviceId, preimage);
20162
20169
  logger$7.trace `[${this.currentServiceId}] PROVIDE(${serviceId}, ${preimage.toStringTruncated()}) <- ${resultToString(result)}`;
20163
20170
  if (result.isOk) {
20164
- regs.set(IN_OUT_REG$8, HostCallResult.OK);
20171
+ regs.set(IN_OUT_REG$9, HostCallResult.OK);
20165
20172
  return;
20166
20173
  }
20167
20174
  const e = result.error;
20168
20175
  if (e === ProvidePreimageError.ServiceNotFound) {
20169
- regs.set(IN_OUT_REG$8, HostCallResult.WHO);
20176
+ regs.set(IN_OUT_REG$9, HostCallResult.WHO);
20170
20177
  return;
20171
20178
  }
20172
20179
  if (e === ProvidePreimageError.WasNotRequested || e === ProvidePreimageError.AlreadyProvided) {
20173
- regs.set(IN_OUT_REG$8, HostCallResult.HUH);
20180
+ regs.set(IN_OUT_REG$9, HostCallResult.HUH);
20174
20181
  return;
20175
20182
  }
20176
20183
  assertNever(e);
@@ -20242,7 +20249,7 @@ class Query {
20242
20249
  }
20243
20250
  }
20244
20251
 
20245
- const IN_OUT_REG$7 = 7;
20252
+ const IN_OUT_REG$8 = 7;
20246
20253
  /**
20247
20254
  * Request a preimage to be available.
20248
20255
  *
@@ -20253,14 +20260,14 @@ class Solicit {
20253
20260
  partialState;
20254
20261
  index = tryAsHostCallIndex(23);
20255
20262
  basicGasCost = tryAsSmallGas(10);
20256
- tracedRegisters = traceRegisters(IN_OUT_REG$7, 8);
20263
+ tracedRegisters = traceRegisters(IN_OUT_REG$8, 8);
20257
20264
  constructor(currentServiceId, partialState) {
20258
20265
  this.currentServiceId = currentServiceId;
20259
20266
  this.partialState = partialState;
20260
20267
  }
20261
20268
  async execute(_gas, regs, memory) {
20262
20269
  // `o`
20263
- const hashStart = regs.get(IN_OUT_REG$7);
20270
+ const hashStart = regs.get(IN_OUT_REG$8);
20264
20271
  // `z`
20265
20272
  const length = regs.get(8);
20266
20273
  const hash = Bytes.zero(HASH_SIZE);
@@ -20272,23 +20279,23 @@ class Solicit {
20272
20279
  const result = this.partialState.requestPreimage(hash.asOpaque(), length);
20273
20280
  logger$7.trace `[${this.currentServiceId}] SOLICIT(${hash}, ${length}) <- ${resultToString(result)}`;
20274
20281
  if (result.isOk) {
20275
- regs.set(IN_OUT_REG$7, HostCallResult.OK);
20282
+ regs.set(IN_OUT_REG$8, HostCallResult.OK);
20276
20283
  return;
20277
20284
  }
20278
20285
  const e = result.error;
20279
20286
  if (e === RequestPreimageError.AlreadyAvailable || e === RequestPreimageError.AlreadyRequested) {
20280
- regs.set(IN_OUT_REG$7, HostCallResult.HUH);
20287
+ regs.set(IN_OUT_REG$8, HostCallResult.HUH);
20281
20288
  return;
20282
20289
  }
20283
20290
  if (e === RequestPreimageError.InsufficientFunds) {
20284
- regs.set(IN_OUT_REG$7, HostCallResult.FULL);
20291
+ regs.set(IN_OUT_REG$8, HostCallResult.FULL);
20285
20292
  return;
20286
20293
  }
20287
20294
  assertNever(e);
20288
20295
  }
20289
20296
  }
20290
20297
 
20291
- const IN_OUT_REG$6 = 7; // `d`
20298
+ const IN_OUT_REG$7 = 7; // `d`
20292
20299
  const AMOUNT_REG = 8; // `a`
20293
20300
  const TRANSFER_GAS_FEE_REG = 9; // `l`
20294
20301
  const MEMO_START_REG = 10; // `o`
@@ -20319,14 +20326,14 @@ class Transfer {
20319
20326
  basicGasCost = Compatibility.isGreaterOrEqual(GpVersion.V0_7_2)
20320
20327
  ? tryAsSmallGas(10)
20321
20328
  : (regs) => tryAsGas(10n + regs.get(TRANSFER_GAS_FEE_REG));
20322
- tracedRegisters = traceRegisters(IN_OUT_REG$6, AMOUNT_REG, TRANSFER_GAS_FEE_REG, MEMO_START_REG);
20329
+ tracedRegisters = traceRegisters(IN_OUT_REG$7, AMOUNT_REG, TRANSFER_GAS_FEE_REG, MEMO_START_REG);
20323
20330
  constructor(currentServiceId, partialState) {
20324
20331
  this.currentServiceId = currentServiceId;
20325
20332
  this.partialState = partialState;
20326
20333
  }
20327
20334
  async execute(gas, regs, memory) {
20328
20335
  // `d`: destination
20329
- const destination = getServiceId(regs.get(IN_OUT_REG$6));
20336
+ const destination = getServiceId(regs.get(IN_OUT_REG$7));
20330
20337
  // `a`: amount
20331
20338
  const amount = regs.get(AMOUNT_REG);
20332
20339
  // `l`: gas
@@ -20351,27 +20358,27 @@ class Transfer {
20351
20358
  return PvmExecution.OOG;
20352
20359
  }
20353
20360
  }
20354
- regs.set(IN_OUT_REG$6, HostCallResult.OK);
20361
+ regs.set(IN_OUT_REG$7, HostCallResult.OK);
20355
20362
  return;
20356
20363
  }
20357
20364
  const e = transferResult.error;
20358
20365
  if (e === TransferError.DestinationNotFound) {
20359
- regs.set(IN_OUT_REG$6, HostCallResult.WHO);
20366
+ regs.set(IN_OUT_REG$7, HostCallResult.WHO);
20360
20367
  return;
20361
20368
  }
20362
20369
  if (e === TransferError.GasTooLow) {
20363
- regs.set(IN_OUT_REG$6, HostCallResult.LOW);
20370
+ regs.set(IN_OUT_REG$7, HostCallResult.LOW);
20364
20371
  return;
20365
20372
  }
20366
20373
  if (e === TransferError.BalanceBelowThreshold) {
20367
- regs.set(IN_OUT_REG$6, HostCallResult.CASH);
20374
+ regs.set(IN_OUT_REG$7, HostCallResult.CASH);
20368
20375
  return;
20369
20376
  }
20370
20377
  assertNever(e);
20371
20378
  }
20372
20379
  }
20373
20380
 
20374
- const IN_OUT_REG$5 = 7; // `o`
20381
+ const IN_OUT_REG$6 = 7; // `o`
20375
20382
  const GAS_REG = 8; // `g`
20376
20383
  const ALLOWANCE_REG = 9; // `m`
20377
20384
  /**
@@ -20384,14 +20391,14 @@ class Upgrade {
20384
20391
  partialState;
20385
20392
  index = tryAsHostCallIndex(19);
20386
20393
  basicGasCost = tryAsSmallGas(10);
20387
- tracedRegisters = traceRegisters(IN_OUT_REG$5, GAS_REG, ALLOWANCE_REG);
20394
+ tracedRegisters = traceRegisters(IN_OUT_REG$6, GAS_REG, ALLOWANCE_REG);
20388
20395
  constructor(currentServiceId, partialState) {
20389
20396
  this.currentServiceId = currentServiceId;
20390
20397
  this.partialState = partialState;
20391
20398
  }
20392
20399
  async execute(_gas, regs, memory) {
20393
20400
  // `o`
20394
- const codeHashStart = regs.get(IN_OUT_REG$5);
20401
+ const codeHashStart = regs.get(IN_OUT_REG$6);
20395
20402
  // `g`
20396
20403
  const gas = regs.get(GAS_REG);
20397
20404
  // `m`
@@ -20405,11 +20412,11 @@ class Upgrade {
20405
20412
  }
20406
20413
  this.partialState.upgradeService(codeHash.asOpaque(), gas, allowance);
20407
20414
  logger$7.trace `[${this.currentServiceId}] UPGRADE(${codeHash}, ${gas}, ${allowance})`;
20408
- regs.set(IN_OUT_REG$5, HostCallResult.OK);
20415
+ regs.set(IN_OUT_REG$6, HostCallResult.OK);
20409
20416
  }
20410
20417
  }
20411
20418
 
20412
- const IN_OUT_REG$4 = 7;
20419
+ const IN_OUT_REG$5 = 7;
20413
20420
  /**
20414
20421
  * Yield accumulation trie result.
20415
20422
  *
@@ -20420,14 +20427,14 @@ class Yield {
20420
20427
  partialState;
20421
20428
  index = tryAsHostCallIndex(25);
20422
20429
  basicGasCost = tryAsSmallGas(10);
20423
- tracedRegisters = traceRegisters(IN_OUT_REG$4);
20430
+ tracedRegisters = traceRegisters(IN_OUT_REG$5);
20424
20431
  constructor(currentServiceId, partialState) {
20425
20432
  this.currentServiceId = currentServiceId;
20426
20433
  this.partialState = partialState;
20427
20434
  }
20428
20435
  async execute(_gas, regs, memory) {
20429
20436
  // `o`
20430
- const hashStart = regs.get(IN_OUT_REG$4);
20437
+ const hashStart = regs.get(IN_OUT_REG$5);
20431
20438
  const hash = Bytes.zero(HASH_SIZE);
20432
20439
  const memoryReadResult = memory.loadInto(hash.raw, hashStart);
20433
20440
  if (memoryReadResult.isError) {
@@ -20436,11 +20443,11 @@ class Yield {
20436
20443
  }
20437
20444
  this.partialState.yield(hash);
20438
20445
  logger$7.trace `[${this.currentServiceId}] YIELD(${hash})`;
20439
- regs.set(IN_OUT_REG$4, HostCallResult.OK);
20446
+ regs.set(IN_OUT_REG$5, HostCallResult.OK);
20440
20447
  }
20441
20448
  }
20442
20449
 
20443
- const IN_OUT_REG$3 = 7;
20450
+ const IN_OUT_REG$4 = 7;
20444
20451
  /**
20445
20452
  * https://graypaper.fluffylabs.dev/#/7e6ff6a/324000324000?v=0.6.7
20446
20453
  */
@@ -20449,7 +20456,7 @@ class Fetch {
20449
20456
  fetch;
20450
20457
  index = tryAsHostCallIndex(1);
20451
20458
  basicGasCost = tryAsSmallGas(10);
20452
- tracedRegisters = traceRegisters(IN_OUT_REG$3, 8, 9, 10, 11, 12);
20459
+ tracedRegisters = traceRegisters(IN_OUT_REG$4, 8, 9, 10, 11, 12);
20453
20460
  constructor(currentServiceId, fetch) {
20454
20461
  this.currentServiceId = currentServiceId;
20455
20462
  this.fetch = fetch;
@@ -20459,7 +20466,7 @@ class Fetch {
20459
20466
  const kind = clampU64ToU32(fetchKindU64);
20460
20467
  const value = this.getValue(kind, regs);
20461
20468
  // o
20462
- const output = regs.get(IN_OUT_REG$3);
20469
+ const output = regs.get(IN_OUT_REG$4);
20463
20470
  const valueLength = tryAsU64(value?.length ?? 0);
20464
20471
  // f
20465
20472
  const offset = minU64(regs.get(8), valueLength);
@@ -20475,7 +20482,7 @@ class Fetch {
20475
20482
  }
20476
20483
  logger$7.trace `[${this.currentServiceId}] FETCH(${kind}) <- ${value?.toStringTruncated()}`;
20477
20484
  // write result
20478
- regs.set(IN_OUT_REG$3, value === null ? HostCallResult.NONE : valueLength);
20485
+ regs.set(IN_OUT_REG$4, value === null ? HostCallResult.NONE : valueLength);
20479
20486
  }
20480
20487
  getValue(kind, regs) {
20481
20488
  if (kind === FetchKind.Constants) {
@@ -20590,6 +20597,7 @@ var Levels;
20590
20597
  Levels[Levels["NIT"] = 4] = "NIT";
20591
20598
  Levels[Levels["UNKNOWN"] = 5] = "UNKNOWN";
20592
20599
  })(Levels || (Levels = {}));
20600
+ const IN_OUT_REG$3 = 7;
20593
20601
  /**
20594
20602
  * Log message to the console
20595
20603
  *
@@ -20598,13 +20606,13 @@ var Levels;
20598
20606
  class LogHostCall {
20599
20607
  currentServiceId;
20600
20608
  index = tryAsHostCallIndex(100);
20601
- basicGasCost = tryAsSmallGas(0);
20609
+ basicGasCost = Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? tryAsSmallGas(10) : tryAsSmallGas(0);
20602
20610
  // intentionally not tracing anything here, since the message will be printed anyway.
20603
20611
  tracedRegisters = traceRegisters();
20604
20612
  constructor(currentServiceId) {
20605
20613
  this.currentServiceId = currentServiceId;
20606
20614
  }
20607
- execute(_gas, regs, memory) {
20615
+ async execute(_gas, regs, memory) {
20608
20616
  const lvl = regs.get(7);
20609
20617
  const targetStart = regs.get(8);
20610
20618
  const targetLength = regs.get(9);
@@ -20618,7 +20626,9 @@ class LogHostCall {
20618
20626
  memory.loadInto(message, msgStart);
20619
20627
  const level = clampU64ToU32(lvl);
20620
20628
  logger$7.trace `[${this.currentServiceId}] LOG(${this.currentServiceId}, ${level < Levels.UNKNOWN ? Levels[level] : Levels[Levels.UNKNOWN]}(${lvl}), ${decoder.decode(target)}, ${decoder.decode(message)})`;
20621
- return Promise.resolve(undefined);
20629
+ if (Compatibility.isGreaterOrEqual(GpVersion.V0_7_2)) {
20630
+ regs.set(IN_OUT_REG$3, HostCallResult.WHAT);
20631
+ }
20622
20632
  }
20623
20633
  }
20624
20634
 
@@ -24166,6 +24176,863 @@ var index$4 = /*#__PURE__*/Object.freeze({
24166
24176
  stfError: stfError
24167
24177
  });
24168
24178
 
24179
+ /*
24180
+ * Copyright The OpenTelemetry Authors
24181
+ *
24182
+ * Licensed under the Apache License, Version 2.0 (the "License");
24183
+ * you may not use this file except in compliance with the License.
24184
+ * You may obtain a copy of the License at
24185
+ *
24186
+ * https://www.apache.org/licenses/LICENSE-2.0
24187
+ *
24188
+ * Unless required by applicable law or agreed to in writing, software
24189
+ * distributed under the License is distributed on an "AS IS" BASIS,
24190
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24191
+ * See the License for the specific language governing permissions and
24192
+ * limitations under the License.
24193
+ */
24194
+ /** only globals that common to node and browsers are allowed */
24195
+ // eslint-disable-next-line node/no-unsupported-features/es-builtins
24196
+ var _globalThis = typeof globalThis === 'object' ? globalThis : global;
24197
+
24198
+ /*
24199
+ * Copyright The OpenTelemetry Authors
24200
+ *
24201
+ * Licensed under the Apache License, Version 2.0 (the "License");
24202
+ * you may not use this file except in compliance with the License.
24203
+ * You may obtain a copy of the License at
24204
+ *
24205
+ * https://www.apache.org/licenses/LICENSE-2.0
24206
+ *
24207
+ * Unless required by applicable law or agreed to in writing, software
24208
+ * distributed under the License is distributed on an "AS IS" BASIS,
24209
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24210
+ * See the License for the specific language governing permissions and
24211
+ * limitations under the License.
24212
+ */
24213
+ // this is autogenerated file, see scripts/version-update.js
24214
+ var VERSION = '1.9.0';
24215
+
24216
+ /*
24217
+ * Copyright The OpenTelemetry Authors
24218
+ *
24219
+ * Licensed under the Apache License, Version 2.0 (the "License");
24220
+ * you may not use this file except in compliance with the License.
24221
+ * You may obtain a copy of the License at
24222
+ *
24223
+ * https://www.apache.org/licenses/LICENSE-2.0
24224
+ *
24225
+ * Unless required by applicable law or agreed to in writing, software
24226
+ * distributed under the License is distributed on an "AS IS" BASIS,
24227
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24228
+ * See the License for the specific language governing permissions and
24229
+ * limitations under the License.
24230
+ */
24231
+ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
24232
+ /**
24233
+ * Create a function to test an API version to see if it is compatible with the provided ownVersion.
24234
+ *
24235
+ * The returned function has the following semantics:
24236
+ * - Exact match is always compatible
24237
+ * - Major versions must match exactly
24238
+ * - 1.x package cannot use global 2.x package
24239
+ * - 2.x package cannot use global 1.x package
24240
+ * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
24241
+ * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
24242
+ * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
24243
+ * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
24244
+ * - Patch and build tag differences are not considered at this time
24245
+ *
24246
+ * @param ownVersion version which should be checked against
24247
+ */
24248
+ function _makeCompatibilityCheck(ownVersion) {
24249
+ var acceptedVersions = new Set([ownVersion]);
24250
+ var rejectedVersions = new Set();
24251
+ var myVersionMatch = ownVersion.match(re);
24252
+ if (!myVersionMatch) {
24253
+ // we cannot guarantee compatibility so we always return noop
24254
+ return function () { return false; };
24255
+ }
24256
+ var ownVersionParsed = {
24257
+ major: +myVersionMatch[1],
24258
+ minor: +myVersionMatch[2],
24259
+ patch: +myVersionMatch[3],
24260
+ prerelease: myVersionMatch[4],
24261
+ };
24262
+ // if ownVersion has a prerelease tag, versions must match exactly
24263
+ if (ownVersionParsed.prerelease != null) {
24264
+ return function isExactmatch(globalVersion) {
24265
+ return globalVersion === ownVersion;
24266
+ };
24267
+ }
24268
+ function _reject(v) {
24269
+ rejectedVersions.add(v);
24270
+ return false;
24271
+ }
24272
+ function _accept(v) {
24273
+ acceptedVersions.add(v);
24274
+ return true;
24275
+ }
24276
+ return function isCompatible(globalVersion) {
24277
+ if (acceptedVersions.has(globalVersion)) {
24278
+ return true;
24279
+ }
24280
+ if (rejectedVersions.has(globalVersion)) {
24281
+ return false;
24282
+ }
24283
+ var globalVersionMatch = globalVersion.match(re);
24284
+ if (!globalVersionMatch) {
24285
+ // cannot parse other version
24286
+ // we cannot guarantee compatibility so we always noop
24287
+ return _reject(globalVersion);
24288
+ }
24289
+ var globalVersionParsed = {
24290
+ major: +globalVersionMatch[1],
24291
+ minor: +globalVersionMatch[2],
24292
+ patch: +globalVersionMatch[3],
24293
+ prerelease: globalVersionMatch[4],
24294
+ };
24295
+ // if globalVersion has a prerelease tag, versions must match exactly
24296
+ if (globalVersionParsed.prerelease != null) {
24297
+ return _reject(globalVersion);
24298
+ }
24299
+ // major versions must match
24300
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
24301
+ return _reject(globalVersion);
24302
+ }
24303
+ if (ownVersionParsed.major === 0) {
24304
+ if (ownVersionParsed.minor === globalVersionParsed.minor &&
24305
+ ownVersionParsed.patch <= globalVersionParsed.patch) {
24306
+ return _accept(globalVersion);
24307
+ }
24308
+ return _reject(globalVersion);
24309
+ }
24310
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
24311
+ return _accept(globalVersion);
24312
+ }
24313
+ return _reject(globalVersion);
24314
+ };
24315
+ }
24316
+ /**
24317
+ * Test an API version to see if it is compatible with this API.
24318
+ *
24319
+ * - Exact match is always compatible
24320
+ * - Major versions must match exactly
24321
+ * - 1.x package cannot use global 2.x package
24322
+ * - 2.x package cannot use global 1.x package
24323
+ * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
24324
+ * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
24325
+ * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
24326
+ * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
24327
+ * - Patch and build tag differences are not considered at this time
24328
+ *
24329
+ * @param version version of the API requesting an instance of the global API
24330
+ */
24331
+ var isCompatible = _makeCompatibilityCheck(VERSION);
24332
+
24333
+ /*
24334
+ * Copyright The OpenTelemetry Authors
24335
+ *
24336
+ * Licensed under the Apache License, Version 2.0 (the "License");
24337
+ * you may not use this file except in compliance with the License.
24338
+ * You may obtain a copy of the License at
24339
+ *
24340
+ * https://www.apache.org/licenses/LICENSE-2.0
24341
+ *
24342
+ * Unless required by applicable law or agreed to in writing, software
24343
+ * distributed under the License is distributed on an "AS IS" BASIS,
24344
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24345
+ * See the License for the specific language governing permissions and
24346
+ * limitations under the License.
24347
+ */
24348
+ var major = VERSION.split('.')[0];
24349
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
24350
+ var _global = _globalThis;
24351
+ function registerGlobal(type, instance, diag, allowOverride) {
24352
+ var _a;
24353
+ if (allowOverride === void 0) { allowOverride = false; }
24354
+ var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
24355
+ version: VERSION,
24356
+ });
24357
+ if (!allowOverride && api[type]) {
24358
+ // already registered an API of this type
24359
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
24360
+ diag.error(err.stack || err.message);
24361
+ return false;
24362
+ }
24363
+ if (api.version !== VERSION) {
24364
+ // All registered APIs must be of the same version exactly
24365
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
24366
+ diag.error(err.stack || err.message);
24367
+ return false;
24368
+ }
24369
+ api[type] = instance;
24370
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
24371
+ return true;
24372
+ }
24373
+ function getGlobal(type) {
24374
+ var _a, _b;
24375
+ var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
24376
+ if (!globalVersion || !isCompatible(globalVersion)) {
24377
+ return;
24378
+ }
24379
+ return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
24380
+ }
24381
+ function unregisterGlobal(type, diag) {
24382
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
24383
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
24384
+ if (api) {
24385
+ delete api[type];
24386
+ }
24387
+ }
24388
+
24389
+ /*
24390
+ * Copyright The OpenTelemetry Authors
24391
+ *
24392
+ * Licensed under the Apache License, Version 2.0 (the "License");
24393
+ * you may not use this file except in compliance with the License.
24394
+ * You may obtain a copy of the License at
24395
+ *
24396
+ * https://www.apache.org/licenses/LICENSE-2.0
24397
+ *
24398
+ * Unless required by applicable law or agreed to in writing, software
24399
+ * distributed under the License is distributed on an "AS IS" BASIS,
24400
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24401
+ * See the License for the specific language governing permissions and
24402
+ * limitations under the License.
24403
+ */
24404
+ var __read$1 = (undefined && undefined.__read) || function (o, n) {
24405
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
24406
+ if (!m) return o;
24407
+ var i = m.call(o), r, ar = [], e;
24408
+ try {
24409
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
24410
+ }
24411
+ catch (error) { e = { error: error }; }
24412
+ finally {
24413
+ try {
24414
+ if (r && !r.done && (m = i["return"])) m.call(i);
24415
+ }
24416
+ finally { if (e) throw e.error; }
24417
+ }
24418
+ return ar;
24419
+ };
24420
+ var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) {
24421
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
24422
+ if (ar || !(i in from)) {
24423
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
24424
+ ar[i] = from[i];
24425
+ }
24426
+ }
24427
+ return to.concat(ar || Array.prototype.slice.call(from));
24428
+ };
24429
+ /**
24430
+ * Component Logger which is meant to be used as part of any component which
24431
+ * will add automatically additional namespace in front of the log message.
24432
+ * It will then forward all message to global diag logger
24433
+ * @example
24434
+ * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });
24435
+ * cLogger.debug('test');
24436
+ * // @opentelemetry/instrumentation-http test
24437
+ */
24438
+ var DiagComponentLogger = /** @class */ (function () {
24439
+ function DiagComponentLogger(props) {
24440
+ this._namespace = props.namespace || 'DiagComponentLogger';
24441
+ }
24442
+ DiagComponentLogger.prototype.debug = function () {
24443
+ var args = [];
24444
+ for (var _i = 0; _i < arguments.length; _i++) {
24445
+ args[_i] = arguments[_i];
24446
+ }
24447
+ return logProxy('debug', this._namespace, args);
24448
+ };
24449
+ DiagComponentLogger.prototype.error = function () {
24450
+ var args = [];
24451
+ for (var _i = 0; _i < arguments.length; _i++) {
24452
+ args[_i] = arguments[_i];
24453
+ }
24454
+ return logProxy('error', this._namespace, args);
24455
+ };
24456
+ DiagComponentLogger.prototype.info = function () {
24457
+ var args = [];
24458
+ for (var _i = 0; _i < arguments.length; _i++) {
24459
+ args[_i] = arguments[_i];
24460
+ }
24461
+ return logProxy('info', this._namespace, args);
24462
+ };
24463
+ DiagComponentLogger.prototype.warn = function () {
24464
+ var args = [];
24465
+ for (var _i = 0; _i < arguments.length; _i++) {
24466
+ args[_i] = arguments[_i];
24467
+ }
24468
+ return logProxy('warn', this._namespace, args);
24469
+ };
24470
+ DiagComponentLogger.prototype.verbose = function () {
24471
+ var args = [];
24472
+ for (var _i = 0; _i < arguments.length; _i++) {
24473
+ args[_i] = arguments[_i];
24474
+ }
24475
+ return logProxy('verbose', this._namespace, args);
24476
+ };
24477
+ return DiagComponentLogger;
24478
+ }());
24479
+ function logProxy(funcName, namespace, args) {
24480
+ var logger = getGlobal('diag');
24481
+ // shortcut if logger not set
24482
+ if (!logger) {
24483
+ return;
24484
+ }
24485
+ args.unshift(namespace);
24486
+ return logger[funcName].apply(logger, __spreadArray$1([], __read$1(args), false));
24487
+ }
24488
+
24489
+ /*
24490
+ * Copyright The OpenTelemetry Authors
24491
+ *
24492
+ * Licensed under the Apache License, Version 2.0 (the "License");
24493
+ * you may not use this file except in compliance with the License.
24494
+ * You may obtain a copy of the License at
24495
+ *
24496
+ * https://www.apache.org/licenses/LICENSE-2.0
24497
+ *
24498
+ * Unless required by applicable law or agreed to in writing, software
24499
+ * distributed under the License is distributed on an "AS IS" BASIS,
24500
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24501
+ * See the License for the specific language governing permissions and
24502
+ * limitations under the License.
24503
+ */
24504
+ /**
24505
+ * Defines the available internal logging levels for the diagnostic logger, the numeric values
24506
+ * of the levels are defined to match the original values from the initial LogLevel to avoid
24507
+ * compatibility/migration issues for any implementation that assume the numeric ordering.
24508
+ */
24509
+ var DiagLogLevel;
24510
+ (function (DiagLogLevel) {
24511
+ /** Diagnostic Logging level setting to disable all logging (except and forced logs) */
24512
+ DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE";
24513
+ /** Identifies an error scenario */
24514
+ DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR";
24515
+ /** Identifies a warning scenario */
24516
+ DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN";
24517
+ /** General informational log message */
24518
+ DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO";
24519
+ /** General debug log message */
24520
+ DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG";
24521
+ /**
24522
+ * Detailed trace level logging should only be used for development, should only be set
24523
+ * in a development environment.
24524
+ */
24525
+ DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE";
24526
+ /** Used to set the logging level to include all logging */
24527
+ DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
24528
+ })(DiagLogLevel || (DiagLogLevel = {}));
24529
+
24530
+ /*
24531
+ * Copyright The OpenTelemetry Authors
24532
+ *
24533
+ * Licensed under the Apache License, Version 2.0 (the "License");
24534
+ * you may not use this file except in compliance with the License.
24535
+ * You may obtain a copy of the License at
24536
+ *
24537
+ * https://www.apache.org/licenses/LICENSE-2.0
24538
+ *
24539
+ * Unless required by applicable law or agreed to in writing, software
24540
+ * distributed under the License is distributed on an "AS IS" BASIS,
24541
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24542
+ * See the License for the specific language governing permissions and
24543
+ * limitations under the License.
24544
+ */
24545
+ function createLogLevelDiagLogger(maxLevel, logger) {
24546
+ if (maxLevel < DiagLogLevel.NONE) {
24547
+ maxLevel = DiagLogLevel.NONE;
24548
+ }
24549
+ else if (maxLevel > DiagLogLevel.ALL) {
24550
+ maxLevel = DiagLogLevel.ALL;
24551
+ }
24552
+ // In case the logger is null or undefined
24553
+ logger = logger || {};
24554
+ function _filterFunc(funcName, theLevel) {
24555
+ var theFunc = logger[funcName];
24556
+ if (typeof theFunc === 'function' && maxLevel >= theLevel) {
24557
+ return theFunc.bind(logger);
24558
+ }
24559
+ return function () { };
24560
+ }
24561
+ return {
24562
+ error: _filterFunc('error', DiagLogLevel.ERROR),
24563
+ warn: _filterFunc('warn', DiagLogLevel.WARN),
24564
+ info: _filterFunc('info', DiagLogLevel.INFO),
24565
+ debug: _filterFunc('debug', DiagLogLevel.DEBUG),
24566
+ verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),
24567
+ };
24568
+ }
24569
+
24570
+ /*
24571
+ * Copyright The OpenTelemetry Authors
24572
+ *
24573
+ * Licensed under the Apache License, Version 2.0 (the "License");
24574
+ * you may not use this file except in compliance with the License.
24575
+ * You may obtain a copy of the License at
24576
+ *
24577
+ * https://www.apache.org/licenses/LICENSE-2.0
24578
+ *
24579
+ * Unless required by applicable law or agreed to in writing, software
24580
+ * distributed under the License is distributed on an "AS IS" BASIS,
24581
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24582
+ * See the License for the specific language governing permissions and
24583
+ * limitations under the License.
24584
+ */
24585
+ var __read = (undefined && undefined.__read) || function (o, n) {
24586
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
24587
+ if (!m) return o;
24588
+ var i = m.call(o), r, ar = [], e;
24589
+ try {
24590
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
24591
+ }
24592
+ catch (error) { e = { error: error }; }
24593
+ finally {
24594
+ try {
24595
+ if (r && !r.done && (m = i["return"])) m.call(i);
24596
+ }
24597
+ finally { if (e) throw e.error; }
24598
+ }
24599
+ return ar;
24600
+ };
24601
+ var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
24602
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
24603
+ if (ar || !(i in from)) {
24604
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
24605
+ ar[i] = from[i];
24606
+ }
24607
+ }
24608
+ return to.concat(ar || Array.prototype.slice.call(from));
24609
+ };
24610
+ var API_NAME$1 = 'diag';
24611
+ /**
24612
+ * Singleton object which represents the entry point to the OpenTelemetry internal
24613
+ * diagnostic API
24614
+ */
24615
+ var DiagAPI = /** @class */ (function () {
24616
+ /**
24617
+ * Private internal constructor
24618
+ * @private
24619
+ */
24620
+ function DiagAPI() {
24621
+ function _logProxy(funcName) {
24622
+ return function () {
24623
+ var args = [];
24624
+ for (var _i = 0; _i < arguments.length; _i++) {
24625
+ args[_i] = arguments[_i];
24626
+ }
24627
+ var logger = getGlobal('diag');
24628
+ // shortcut if logger not set
24629
+ if (!logger)
24630
+ return;
24631
+ return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
24632
+ };
24633
+ }
24634
+ // Using self local variable for minification purposes as 'this' cannot be minified
24635
+ var self = this;
24636
+ // DiagAPI specific functions
24637
+ var setLogger = function (logger, optionsOrLogLevel) {
24638
+ var _a, _b, _c;
24639
+ if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; }
24640
+ if (logger === self) {
24641
+ // There isn't much we can do here.
24642
+ // Logging to the console might break the user application.
24643
+ // Try to log to self. If a logger was previously registered it will receive the log.
24644
+ var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');
24645
+ self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
24646
+ return false;
24647
+ }
24648
+ if (typeof optionsOrLogLevel === 'number') {
24649
+ optionsOrLogLevel = {
24650
+ logLevel: optionsOrLogLevel,
24651
+ };
24652
+ }
24653
+ var oldLogger = getGlobal('diag');
24654
+ var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
24655
+ // There already is an logger registered. We'll let it know before overwriting it.
24656
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
24657
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '<failed to generate stacktrace>';
24658
+ oldLogger.warn("Current logger will be overwritten from " + stack);
24659
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
24660
+ }
24661
+ return registerGlobal('diag', newLogger, self, true);
24662
+ };
24663
+ self.setLogger = setLogger;
24664
+ self.disable = function () {
24665
+ unregisterGlobal(API_NAME$1, self);
24666
+ };
24667
+ self.createComponentLogger = function (options) {
24668
+ return new DiagComponentLogger(options);
24669
+ };
24670
+ self.verbose = _logProxy('verbose');
24671
+ self.debug = _logProxy('debug');
24672
+ self.info = _logProxy('info');
24673
+ self.warn = _logProxy('warn');
24674
+ self.error = _logProxy('error');
24675
+ }
24676
+ /** Get the singleton instance of the DiagAPI API */
24677
+ DiagAPI.instance = function () {
24678
+ if (!this._instance) {
24679
+ this._instance = new DiagAPI();
24680
+ }
24681
+ return this._instance;
24682
+ };
24683
+ return DiagAPI;
24684
+ }());
24685
+
24686
+ /*
24687
+ * Copyright The OpenTelemetry Authors
24688
+ *
24689
+ * Licensed under the Apache License, Version 2.0 (the "License");
24690
+ * you may not use this file except in compliance with the License.
24691
+ * You may obtain a copy of the License at
24692
+ *
24693
+ * https://www.apache.org/licenses/LICENSE-2.0
24694
+ *
24695
+ * Unless required by applicable law or agreed to in writing, software
24696
+ * distributed under the License is distributed on an "AS IS" BASIS,
24697
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24698
+ * See the License for the specific language governing permissions and
24699
+ * limitations under the License.
24700
+ */
24701
+ var __extends = (undefined && undefined.__extends) || (function () {
24702
+ var extendStatics = function (d, b) {
24703
+ extendStatics = Object.setPrototypeOf ||
24704
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24705
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
24706
+ return extendStatics(d, b);
24707
+ };
24708
+ return function (d, b) {
24709
+ if (typeof b !== "function" && b !== null)
24710
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
24711
+ extendStatics(d, b);
24712
+ function __() { this.constructor = d; }
24713
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24714
+ };
24715
+ })();
24716
+ /**
24717
+ * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses
24718
+ * constant NoopMetrics for all of its methods.
24719
+ */
24720
+ var NoopMeter = /** @class */ (function () {
24721
+ function NoopMeter() {
24722
+ }
24723
+ /**
24724
+ * @see {@link Meter.createGauge}
24725
+ */
24726
+ NoopMeter.prototype.createGauge = function (_name, _options) {
24727
+ return NOOP_GAUGE_METRIC;
24728
+ };
24729
+ /**
24730
+ * @see {@link Meter.createHistogram}
24731
+ */
24732
+ NoopMeter.prototype.createHistogram = function (_name, _options) {
24733
+ return NOOP_HISTOGRAM_METRIC;
24734
+ };
24735
+ /**
24736
+ * @see {@link Meter.createCounter}
24737
+ */
24738
+ NoopMeter.prototype.createCounter = function (_name, _options) {
24739
+ return NOOP_COUNTER_METRIC;
24740
+ };
24741
+ /**
24742
+ * @see {@link Meter.createUpDownCounter}
24743
+ */
24744
+ NoopMeter.prototype.createUpDownCounter = function (_name, _options) {
24745
+ return NOOP_UP_DOWN_COUNTER_METRIC;
24746
+ };
24747
+ /**
24748
+ * @see {@link Meter.createObservableGauge}
24749
+ */
24750
+ NoopMeter.prototype.createObservableGauge = function (_name, _options) {
24751
+ return NOOP_OBSERVABLE_GAUGE_METRIC;
24752
+ };
24753
+ /**
24754
+ * @see {@link Meter.createObservableCounter}
24755
+ */
24756
+ NoopMeter.prototype.createObservableCounter = function (_name, _options) {
24757
+ return NOOP_OBSERVABLE_COUNTER_METRIC;
24758
+ };
24759
+ /**
24760
+ * @see {@link Meter.createObservableUpDownCounter}
24761
+ */
24762
+ NoopMeter.prototype.createObservableUpDownCounter = function (_name, _options) {
24763
+ return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
24764
+ };
24765
+ /**
24766
+ * @see {@link Meter.addBatchObservableCallback}
24767
+ */
24768
+ NoopMeter.prototype.addBatchObservableCallback = function (_callback, _observables) { };
24769
+ /**
24770
+ * @see {@link Meter.removeBatchObservableCallback}
24771
+ */
24772
+ NoopMeter.prototype.removeBatchObservableCallback = function (_callback) { };
24773
+ return NoopMeter;
24774
+ }());
24775
+ var NoopMetric = /** @class */ (function () {
24776
+ function NoopMetric() {
24777
+ }
24778
+ return NoopMetric;
24779
+ }());
24780
+ var NoopCounterMetric = /** @class */ (function (_super) {
24781
+ __extends(NoopCounterMetric, _super);
24782
+ function NoopCounterMetric() {
24783
+ return _super !== null && _super.apply(this, arguments) || this;
24784
+ }
24785
+ NoopCounterMetric.prototype.add = function (_value, _attributes) { };
24786
+ return NoopCounterMetric;
24787
+ }(NoopMetric));
24788
+ var NoopUpDownCounterMetric = /** @class */ (function (_super) {
24789
+ __extends(NoopUpDownCounterMetric, _super);
24790
+ function NoopUpDownCounterMetric() {
24791
+ return _super !== null && _super.apply(this, arguments) || this;
24792
+ }
24793
+ NoopUpDownCounterMetric.prototype.add = function (_value, _attributes) { };
24794
+ return NoopUpDownCounterMetric;
24795
+ }(NoopMetric));
24796
+ var NoopGaugeMetric = /** @class */ (function (_super) {
24797
+ __extends(NoopGaugeMetric, _super);
24798
+ function NoopGaugeMetric() {
24799
+ return _super !== null && _super.apply(this, arguments) || this;
24800
+ }
24801
+ NoopGaugeMetric.prototype.record = function (_value, _attributes) { };
24802
+ return NoopGaugeMetric;
24803
+ }(NoopMetric));
24804
+ var NoopHistogramMetric = /** @class */ (function (_super) {
24805
+ __extends(NoopHistogramMetric, _super);
24806
+ function NoopHistogramMetric() {
24807
+ return _super !== null && _super.apply(this, arguments) || this;
24808
+ }
24809
+ NoopHistogramMetric.prototype.record = function (_value, _attributes) { };
24810
+ return NoopHistogramMetric;
24811
+ }(NoopMetric));
24812
+ var NoopObservableMetric = /** @class */ (function () {
24813
+ function NoopObservableMetric() {
24814
+ }
24815
+ NoopObservableMetric.prototype.addCallback = function (_callback) { };
24816
+ NoopObservableMetric.prototype.removeCallback = function (_callback) { };
24817
+ return NoopObservableMetric;
24818
+ }());
24819
+ var NoopObservableCounterMetric = /** @class */ (function (_super) {
24820
+ __extends(NoopObservableCounterMetric, _super);
24821
+ function NoopObservableCounterMetric() {
24822
+ return _super !== null && _super.apply(this, arguments) || this;
24823
+ }
24824
+ return NoopObservableCounterMetric;
24825
+ }(NoopObservableMetric));
24826
+ var NoopObservableGaugeMetric = /** @class */ (function (_super) {
24827
+ __extends(NoopObservableGaugeMetric, _super);
24828
+ function NoopObservableGaugeMetric() {
24829
+ return _super !== null && _super.apply(this, arguments) || this;
24830
+ }
24831
+ return NoopObservableGaugeMetric;
24832
+ }(NoopObservableMetric));
24833
+ var NoopObservableUpDownCounterMetric = /** @class */ (function (_super) {
24834
+ __extends(NoopObservableUpDownCounterMetric, _super);
24835
+ function NoopObservableUpDownCounterMetric() {
24836
+ return _super !== null && _super.apply(this, arguments) || this;
24837
+ }
24838
+ return NoopObservableUpDownCounterMetric;
24839
+ }(NoopObservableMetric));
24840
+ var NOOP_METER = new NoopMeter();
24841
+ // Synchronous instruments
24842
+ var NOOP_COUNTER_METRIC = new NoopCounterMetric();
24843
+ var NOOP_GAUGE_METRIC = new NoopGaugeMetric();
24844
+ var NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();
24845
+ var NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();
24846
+ // Asynchronous instruments
24847
+ var NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
24848
+ var NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
24849
+ var NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
24850
+
24851
+ /*
24852
+ * Copyright The OpenTelemetry Authors
24853
+ *
24854
+ * Licensed under the Apache License, Version 2.0 (the "License");
24855
+ * you may not use this file except in compliance with the License.
24856
+ * You may obtain a copy of the License at
24857
+ *
24858
+ * https://www.apache.org/licenses/LICENSE-2.0
24859
+ *
24860
+ * Unless required by applicable law or agreed to in writing, software
24861
+ * distributed under the License is distributed on an "AS IS" BASIS,
24862
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24863
+ * See the License for the specific language governing permissions and
24864
+ * limitations under the License.
24865
+ */
24866
+ /**
24867
+ * An implementation of the {@link MeterProvider} which returns an impotent Meter
24868
+ * for all calls to `getMeter`
24869
+ */
24870
+ var NoopMeterProvider = /** @class */ (function () {
24871
+ function NoopMeterProvider() {
24872
+ }
24873
+ NoopMeterProvider.prototype.getMeter = function (_name, _version, _options) {
24874
+ return NOOP_METER;
24875
+ };
24876
+ return NoopMeterProvider;
24877
+ }());
24878
+ var NOOP_METER_PROVIDER = new NoopMeterProvider();
24879
+
24880
+ /*
24881
+ * Copyright The OpenTelemetry Authors
24882
+ *
24883
+ * Licensed under the Apache License, Version 2.0 (the "License");
24884
+ * you may not use this file except in compliance with the License.
24885
+ * You may obtain a copy of the License at
24886
+ *
24887
+ * https://www.apache.org/licenses/LICENSE-2.0
24888
+ *
24889
+ * Unless required by applicable law or agreed to in writing, software
24890
+ * distributed under the License is distributed on an "AS IS" BASIS,
24891
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24892
+ * See the License for the specific language governing permissions and
24893
+ * limitations under the License.
24894
+ */
24895
+ var API_NAME = 'metrics';
24896
+ /**
24897
+ * Singleton object which represents the entry point to the OpenTelemetry Metrics API
24898
+ */
24899
+ var MetricsAPI = /** @class */ (function () {
24900
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
24901
+ function MetricsAPI() {
24902
+ }
24903
+ /** Get the singleton instance of the Metrics API */
24904
+ MetricsAPI.getInstance = function () {
24905
+ if (!this._instance) {
24906
+ this._instance = new MetricsAPI();
24907
+ }
24908
+ return this._instance;
24909
+ };
24910
+ /**
24911
+ * Set the current global meter provider.
24912
+ * Returns true if the meter provider was successfully registered, else false.
24913
+ */
24914
+ MetricsAPI.prototype.setGlobalMeterProvider = function (provider) {
24915
+ return registerGlobal(API_NAME, provider, DiagAPI.instance());
24916
+ };
24917
+ /**
24918
+ * Returns the global meter provider.
24919
+ */
24920
+ MetricsAPI.prototype.getMeterProvider = function () {
24921
+ return getGlobal(API_NAME) || NOOP_METER_PROVIDER;
24922
+ };
24923
+ /**
24924
+ * Returns a meter from the global meter provider.
24925
+ */
24926
+ MetricsAPI.prototype.getMeter = function (name, version, options) {
24927
+ return this.getMeterProvider().getMeter(name, version, options);
24928
+ };
24929
+ /** Remove the global meter provider */
24930
+ MetricsAPI.prototype.disable = function () {
24931
+ unregisterGlobal(API_NAME, DiagAPI.instance());
24932
+ };
24933
+ return MetricsAPI;
24934
+ }());
24935
+
24936
+ /*
24937
+ * Copyright The OpenTelemetry Authors
24938
+ *
24939
+ * Licensed under the Apache License, Version 2.0 (the "License");
24940
+ * you may not use this file except in compliance with the License.
24941
+ * You may obtain a copy of the License at
24942
+ *
24943
+ * https://www.apache.org/licenses/LICENSE-2.0
24944
+ *
24945
+ * Unless required by applicable law or agreed to in writing, software
24946
+ * distributed under the License is distributed on an "AS IS" BASIS,
24947
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24948
+ * See the License for the specific language governing permissions and
24949
+ * limitations under the License.
24950
+ */
24951
+ // Split module-level variable definition into separate files to allow
24952
+ // tree-shaking on each api instance.
24953
+ /** Entrypoint for metrics API */
24954
+ var metrics = MetricsAPI.getInstance();
24955
+
24956
+ var name = "@typeberry/importer";
24957
+ var version = "0.4.1";
24958
+ var packageJson = {
24959
+ name: name,
24960
+ version: version};
24961
+
24962
+ /**
24963
+ * Block importer metrics for JAM implementation.
24964
+ *
24965
+ * https://github.com/polkadot-fellows/JIPs/blob/main/JIP-3.md#block-authoringimporting-events
24966
+ */
24967
+ function createMetrics() {
24968
+ const meter = metrics.getMeter(packageJson.name, packageJson.version);
24969
+ const blockVerificationDuration = meter.createHistogram("jam.blockVerificationTime", {
24970
+ description: "Duration of block verification",
24971
+ unit: "ms",
24972
+ });
24973
+ const blockExecutionDuration = meter.createHistogram("jam.blockExecutionTime", {
24974
+ description: "Duration of block execution",
24975
+ unit: "ms",
24976
+ });
24977
+ const blockExecutionCost = meter.createHistogram("jam.blockExecutionGas", {
24978
+ description: "Block execution cost (gas)",
24979
+ unit: "gas",
24980
+ });
24981
+ const blockImportDuration = meter.createHistogram("jam.blockImportTime", {
24982
+ description: "Total duration of block import (verification + execution)",
24983
+ unit: "ms",
24984
+ });
24985
+ // JIP-3
24986
+ // 43
24987
+ const blockImportingCounter = meter.createCounter("jam.jip3.importing", {
24988
+ description: "Block importing started",
24989
+ unit: "blocks",
24990
+ });
24991
+ // 44
24992
+ const blockVerificationFailedCounter = meter.createCounter("jam.jip3.verification_failed", {
24993
+ description: "Block verification failed",
24994
+ unit: "errors",
24995
+ });
24996
+ // 45
24997
+ const blockVerifiedCounter = meter.createCounter("jam.jip3.verified", {
24998
+ description: "Block verified successfully",
24999
+ unit: "blocks",
25000
+ });
25001
+ // 46
25002
+ const blockExecutionFailedCounter = meter.createCounter("jam.jip3.execution_failed", {
25003
+ description: "Block execution failed",
25004
+ unit: "errors",
25005
+ });
25006
+ // 47
25007
+ const blockExecutedCounter = meter.createCounter("jam.jip3.executed", {
25008
+ description: "Block executed successfully",
25009
+ unit: "blocks",
25010
+ });
25011
+ return {
25012
+ recordBlockImportComplete(totalDurationMs, success) {
25013
+ blockImportDuration.record(totalDurationMs, { success });
25014
+ },
25015
+ recordBlockImportingStarted(slot) {
25016
+ blockImportingCounter.add(1, { slot });
25017
+ },
25018
+ recordBlockVerificationFailed(reason) {
25019
+ blockVerificationFailedCounter.add(1, { reason });
25020
+ },
25021
+ recordBlockVerified(durationMs) {
25022
+ blockVerifiedCounter.add(1);
25023
+ blockVerificationDuration.record(durationMs);
25024
+ },
25025
+ recordBlockExecutionFailed(reason) {
25026
+ blockExecutionFailedCounter.add(1, { reason });
25027
+ },
25028
+ recordBlockExecuted(durationMs, cost) {
25029
+ blockExecutedCounter.add(1);
25030
+ blockExecutionDuration.record(durationMs);
25031
+ blockExecutionCost.record(cost);
25032
+ },
25033
+ };
25034
+ }
25035
+
24169
25036
  var ImporterErrorKind;
24170
25037
  (function (ImporterErrorKind) {
24171
25038
  ImporterErrorKind[ImporterErrorKind["Verifier"] = 0] = "Verifier";
@@ -24184,11 +25051,13 @@ class Importer {
24184
25051
  state;
24185
25052
  // Hash of the block that we have the posterior state for in `state`.
24186
25053
  currentHash;
25054
+ metrics;
24187
25055
  constructor(spec, pvm, hasher, logger, blocks, states) {
24188
25056
  this.hasher = hasher;
24189
25057
  this.logger = logger;
24190
25058
  this.blocks = blocks;
24191
25059
  this.states = states;
25060
+ this.metrics = createMetrics();
24192
25061
  const currentBestHeaderHash = this.blocks.getBestHeaderHash();
24193
25062
  const state = states.getState(currentBestHeaderHash);
24194
25063
  if (state === null) {
@@ -24221,26 +25090,35 @@ class Importer {
24221
25090
  async importBlock(block, omitSealVerification) {
24222
25091
  const timer = measure("importBlock");
24223
25092
  const timeSlot = extractTimeSlot(block);
25093
+ this.metrics.recordBlockImportingStarted(timeSlot);
25094
+ const startTime = now();
24224
25095
  const maybeBestHeader = await this.importBlockInternal(block, omitSealVerification);
25096
+ const duration = now() - startTime;
24225
25097
  if (maybeBestHeader.isOk) {
24226
25098
  const bestHeader = maybeBestHeader.ok;
24227
25099
  this.logger.info `🧊 Best block: #${timeSlot} (${bestHeader.hash})`;
24228
25100
  this.logger.log `${timer()}`;
25101
+ this.metrics.recordBlockImportComplete(duration, true);
24229
25102
  return maybeBestHeader;
24230
25103
  }
24231
25104
  this.logger.log `❌ Rejected block #${timeSlot}: ${resultToString(maybeBestHeader)}`;
24232
25105
  this.logger.log `${timer()}`;
25106
+ this.metrics.recordBlockImportComplete(duration, false);
24233
25107
  return maybeBestHeader;
24234
25108
  }
24235
25109
  async importBlockInternal(block, omitSealVerification = false) {
24236
25110
  const logger = this.logger;
24237
25111
  logger.log `🧱 Attempting to import a new block`;
24238
25112
  const timerVerify = measure("import:verify");
25113
+ const verifyStart = now();
24239
25114
  const hash = await this.verifier.verifyBlock(block);
25115
+ const verifyDuration = now() - verifyStart;
24240
25116
  logger.log `${timerVerify()}`;
24241
25117
  if (hash.isError) {
25118
+ this.metrics.recordBlockVerificationFailed(resultToString(hash));
24242
25119
  return importerError(ImporterErrorKind.Verifier, hash);
24243
25120
  }
25121
+ this.metrics.recordBlockVerified(verifyDuration);
24244
25122
  // TODO [ToDr] This is incomplete/temporary fork support!
24245
25123
  const parentHash = block.header.view().parentHeaderHash.materialize();
24246
25124
  if (!this.currentHash.isEqualTo(parentHash)) {
@@ -24260,11 +25138,15 @@ class Importer {
24260
25138
  const headerHash = hash.ok;
24261
25139
  logger.log `🧱 Verified block: Got hash ${headerHash} for block at slot ${timeSlot}.`;
24262
25140
  const timerStf = measure("import:stf");
25141
+ const stfStart = now();
24263
25142
  const res = await this.stf.transition(block, headerHash, omitSealVerification);
25143
+ const stfDuration = now() - stfStart;
24264
25144
  logger.log `${timerStf()}`;
24265
25145
  if (res.isError) {
25146
+ this.metrics.recordBlockExecutionFailed(resultToString(res));
24266
25147
  return importerError(ImporterErrorKind.Stf, res);
24267
25148
  }
25149
+ this.metrics.recordBlockExecuted(stfDuration, 0);
24268
25150
  // modify the state
24269
25151
  const update = res.ok;
24270
25152
  const timerState = measure("import:state");
@@ -24447,10 +25329,8 @@ class Channel {
24447
25329
  // listen to request incoming to worker
24448
25330
  this.port.on(key, val.request, async ({ responseId, data }) => {
24449
25331
  try {
24450
- console.log(`[${this.port.threadId}] handling ${key}. Responseid: ${responseId}`);
24451
25332
  // handle them
24452
25333
  const response = await handler(data);
24453
- console.log(`[${this.port.threadId}] sending response: ${responseId}`);
24454
25334
  // and send response back on dedicated event
24455
25335
  this.port.postMessage(responseId, val.response, {
24456
25336
  responseId,
@@ -24468,14 +25348,12 @@ class Channel {
24468
25348
  return (data) => {
24469
25349
  this.nextResponseId++;
24470
25350
  const responseId = `${key}:${this.nextResponseId}`;
24471
- console.log(`[${this.port.threadId}] will wait for ${key}`);
24472
25351
  return new Promise((resolve, reject) => {
24473
25352
  this.pendingPromises.add(reject);
24474
25353
  // attach response listener first
24475
25354
  this.port.once(responseId, val.response, (msg) => {
24476
25355
  // we got response, so will resolve
24477
25356
  this.pendingPromises.delete(reject);
24478
- console.log(`[${this.port.threadId}] got ${key}`);
24479
25357
  resolve(msg.data);
24480
25358
  });
24481
25359
  // send message to the port
@@ -24504,14 +25382,16 @@ function isMessageCodecs(val) {
24504
25382
  * Worker config with in-thread database.
24505
25383
  */
24506
25384
  class DirectWorkerConfig {
25385
+ nodeName;
24507
25386
  chainSpec;
24508
25387
  workerParams;
24509
25388
  blocksDb;
24510
25389
  statesDb;
24511
- static new({ chainSpec, blocksDb, statesDb, params, }) {
24512
- return new DirectWorkerConfig(chainSpec, params, blocksDb, statesDb);
25390
+ static new({ nodeName, chainSpec, blocksDb, statesDb, params, }) {
25391
+ return new DirectWorkerConfig(nodeName, chainSpec, params, blocksDb, statesDb);
24513
25392
  }
24514
- constructor(chainSpec, workerParams, blocksDb, statesDb) {
25393
+ constructor(nodeName, chainSpec, workerParams, blocksDb, statesDb) {
25394
+ this.nodeName = nodeName;
24515
25395
  this.chainSpec = chainSpec;
24516
25396
  this.workerParams = workerParams;
24517
25397
  this.blocksDb = blocksDb;
@@ -25043,6 +25923,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
25043
25923
  ImporterConfig: ImporterConfig,
25044
25924
  WORKER: WORKER,
25045
25925
  createImporter: createImporter,
25926
+ createMetrics: createMetrics,
25046
25927
  main: main,
25047
25928
  protocol: protocol
25048
25929
  });