@vention/vention-cli 0.36.4 → 0.37.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.
package/main.esm.js CHANGED
@@ -3591,34 +3591,246 @@ for (var COLLECTION_NAME in DOMIterables) {
3591
3591
 
3592
3592
  handlePrototype(DOMTokenListPrototype, 'DOMTokenList');
3593
3593
 
3594
- var $$B = _export;
3594
+ var defineProperty = objectDefineProperty.f;
3595
+
3596
+ var proxyAccessor$2 = function (Target, Source, key) {
3597
+ key in Target || defineProperty(Target, key, {
3598
+ configurable: true,
3599
+ get: function () { return Source[key]; },
3600
+ set: function (it) { Source[key] = it; }
3601
+ });
3602
+ };
3603
+
3604
+ var isCallable$6 = isCallable$t;
3605
+ var isObject$9 = isObject$m;
3606
+ var setPrototypeOf$4 = objectSetPrototypeOf;
3607
+
3608
+ // makes subclassing work correct for wrapped built-ins
3609
+ var inheritIfRequired$4 = function ($this, dummy, Wrapper) {
3610
+ var NewTarget, NewTargetPrototype;
3611
+ if (
3612
+ // it can work only with native `setPrototypeOf`
3613
+ setPrototypeOf$4 &&
3614
+ // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
3615
+ isCallable$6(NewTarget = dummy.constructor) &&
3616
+ NewTarget !== Wrapper &&
3617
+ isObject$9(NewTargetPrototype = NewTarget.prototype) &&
3618
+ NewTargetPrototype !== Wrapper.prototype
3619
+ ) setPrototypeOf$4($this, NewTargetPrototype);
3620
+ return $this;
3621
+ };
3622
+
3623
+ var toString$f = toString$j;
3624
+
3625
+ var normalizeStringArgument$1 = function (argument, $default) {
3626
+ return argument === undefined ? arguments.length < 2 ? '' : $default : toString$f(argument);
3627
+ };
3628
+
3629
+ var isObject$8 = isObject$m;
3630
+ var createNonEnumerableProperty$7 = createNonEnumerableProperty$d;
3631
+
3632
+ // `InstallErrorCause` abstract operation
3633
+ // https://tc39.es/ecma262/#sec-installerrorcause
3634
+ var installErrorCause$1 = function (O, options) {
3635
+ if (isObject$8(options) && 'cause' in options) {
3636
+ createNonEnumerableProperty$7(O, 'cause', options.cause);
3637
+ }
3638
+ };
3639
+
3640
+ var uncurryThis$v = functionUncurryThis;
3641
+
3642
+ var $Error = Error;
3643
+ var replace$7 = uncurryThis$v(''.replace);
3644
+
3645
+ var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
3646
+ // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
3647
+ var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
3648
+ var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
3649
+
3650
+ var errorStackClear = function (stack, dropEntries) {
3651
+ if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
3652
+ while (dropEntries--) stack = replace$7(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
3653
+ } return stack;
3654
+ };
3655
+
3656
+ var fails$m = fails$F;
3657
+ var createPropertyDescriptor$2 = createPropertyDescriptor$7;
3658
+
3659
+ var errorStackInstallable = !fails$m(function () {
3660
+ var error = new Error('a');
3661
+ if (!('stack' in error)) return true;
3662
+ // eslint-disable-next-line es/no-object-defineproperty -- safe
3663
+ Object.defineProperty(error, 'stack', createPropertyDescriptor$2(1, 7));
3664
+ return error.stack !== 7;
3665
+ });
3666
+
3667
+ var createNonEnumerableProperty$6 = createNonEnumerableProperty$d;
3668
+ var clearErrorStack = errorStackClear;
3669
+ var ERROR_STACK_INSTALLABLE = errorStackInstallable;
3670
+
3671
+ // non-standard V8
3672
+ // eslint-disable-next-line es/no-nonstandard-error-properties -- safe
3673
+ var captureStackTrace = Error.captureStackTrace;
3674
+
3675
+ var errorStackInstall = function (error, C, stack, dropEntries) {
3676
+ if (ERROR_STACK_INSTALLABLE) {
3677
+ if (captureStackTrace) captureStackTrace(error, C);
3678
+ else createNonEnumerableProperty$6(error, 'stack', clearErrorStack(stack, dropEntries));
3679
+ }
3680
+ };
3681
+
3682
+ var getBuiltIn$3 = getBuiltIn$c;
3683
+ var hasOwn$8 = hasOwnProperty_1;
3684
+ var createNonEnumerableProperty$5 = createNonEnumerableProperty$d;
3685
+ var isPrototypeOf$4 = objectIsPrototypeOf;
3686
+ var setPrototypeOf$3 = objectSetPrototypeOf;
3687
+ var copyConstructorProperties$1 = copyConstructorProperties$4;
3688
+ var proxyAccessor$1 = proxyAccessor$2;
3689
+ var inheritIfRequired$3 = inheritIfRequired$4;
3690
+ var normalizeStringArgument = normalizeStringArgument$1;
3691
+ var installErrorCause = installErrorCause$1;
3692
+ var installErrorStack = errorStackInstall;
3595
3693
  var DESCRIPTORS$c = descriptors;
3694
+
3695
+ var wrapErrorConstructorWithCause$1 = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
3696
+ var STACK_TRACE_LIMIT = 'stackTraceLimit';
3697
+ var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
3698
+ var path = FULL_NAME.split('.');
3699
+ var ERROR_NAME = path[path.length - 1];
3700
+ var OriginalError = getBuiltIn$3.apply(null, path);
3701
+
3702
+ if (!OriginalError) return;
3703
+
3704
+ var OriginalErrorPrototype = OriginalError.prototype;
3705
+
3706
+ // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
3707
+ if (hasOwn$8(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
3708
+
3709
+ if (!FORCED) return OriginalError;
3710
+
3711
+ var BaseError = getBuiltIn$3('Error');
3712
+
3713
+ var WrappedError = wrapper(function (a, b) {
3714
+ var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
3715
+ var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
3716
+ if (message !== undefined) createNonEnumerableProperty$5(result, 'message', message);
3717
+ installErrorStack(result, WrappedError, result.stack, 2);
3718
+ if (this && isPrototypeOf$4(OriginalErrorPrototype, this)) inheritIfRequired$3(result, this, WrappedError);
3719
+ if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
3720
+ return result;
3721
+ });
3722
+
3723
+ WrappedError.prototype = OriginalErrorPrototype;
3724
+
3725
+ if (ERROR_NAME !== 'Error') {
3726
+ if (setPrototypeOf$3) setPrototypeOf$3(WrappedError, BaseError);
3727
+ else copyConstructorProperties$1(WrappedError, BaseError, { name: true });
3728
+ } else if (DESCRIPTORS$c && STACK_TRACE_LIMIT in OriginalError) {
3729
+ proxyAccessor$1(WrappedError, OriginalError, STACK_TRACE_LIMIT);
3730
+ proxyAccessor$1(WrappedError, OriginalError, 'prepareStackTrace');
3731
+ }
3732
+
3733
+ copyConstructorProperties$1(WrappedError, OriginalError);
3734
+
3735
+ try {
3736
+ // Safari 13- bug: WebAssembly errors does not have a proper `.name`
3737
+ if (OriginalErrorPrototype.name !== ERROR_NAME) {
3738
+ createNonEnumerableProperty$5(OriginalErrorPrototype, 'name', ERROR_NAME);
3739
+ }
3740
+ OriginalErrorPrototype.constructor = WrappedError;
3741
+ } catch (error) { /* empty */ }
3742
+
3743
+ return WrappedError;
3744
+ };
3745
+
3746
+ /* eslint-disable no-unused-vars -- required for functions `.length` */
3747
+ var $$B = _export;
3596
3748
  var globalThis$t = globalThis_1;
3597
- var getBuiltIn$3 = getBuiltIn$c;
3598
- var uncurryThis$v = functionUncurryThis;
3749
+ var apply$2 = functionApply;
3750
+ var wrapErrorConstructorWithCause = wrapErrorConstructorWithCause$1;
3751
+
3752
+ var WEB_ASSEMBLY = 'WebAssembly';
3753
+ var WebAssembly = globalThis$t[WEB_ASSEMBLY];
3754
+
3755
+ // eslint-disable-next-line es/no-error-cause -- feature detection
3756
+ var FORCED$7 = new Error('e', { cause: 7 }).cause !== 7;
3757
+
3758
+ var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
3759
+ var O = {};
3760
+ // eslint-disable-next-line unicorn/no-immediate-mutation -- ES3 syntax limitation
3761
+ O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED$7);
3762
+ $$B({ global: true, constructor: true, arity: 1, forced: FORCED$7 }, O);
3763
+ };
3764
+
3765
+ var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
3766
+ if (WebAssembly && WebAssembly[ERROR_NAME]) {
3767
+ var O = {};
3768
+ // eslint-disable-next-line unicorn/no-immediate-mutation -- ES3 syntax limitation
3769
+ O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED$7);
3770
+ $$B({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED$7 }, O);
3771
+ }
3772
+ };
3773
+
3774
+ // https://tc39.es/ecma262/#sec-nativeerror
3775
+ exportGlobalErrorCauseWrapper('Error', function (init) {
3776
+ return function Error(message) { return apply$2(init, this, arguments); };
3777
+ });
3778
+ exportGlobalErrorCauseWrapper('EvalError', function (init) {
3779
+ return function EvalError(message) { return apply$2(init, this, arguments); };
3780
+ });
3781
+ exportGlobalErrorCauseWrapper('RangeError', function (init) {
3782
+ return function RangeError(message) { return apply$2(init, this, arguments); };
3783
+ });
3784
+ exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
3785
+ return function ReferenceError(message) { return apply$2(init, this, arguments); };
3786
+ });
3787
+ exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
3788
+ return function SyntaxError(message) { return apply$2(init, this, arguments); };
3789
+ });
3790
+ exportGlobalErrorCauseWrapper('TypeError', function (init) {
3791
+ return function TypeError(message) { return apply$2(init, this, arguments); };
3792
+ });
3793
+ exportGlobalErrorCauseWrapper('URIError', function (init) {
3794
+ return function URIError(message) { return apply$2(init, this, arguments); };
3795
+ });
3796
+ exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
3797
+ return function CompileError(message) { return apply$2(init, this, arguments); };
3798
+ });
3799
+ exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
3800
+ return function LinkError(message) { return apply$2(init, this, arguments); };
3801
+ });
3802
+ exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
3803
+ return function RuntimeError(message) { return apply$2(init, this, arguments); };
3804
+ });
3805
+
3806
+ var $$A = _export;
3807
+ var DESCRIPTORS$b = descriptors;
3808
+ var globalThis$s = globalThis_1;
3809
+ var getBuiltIn$2 = getBuiltIn$c;
3810
+ var uncurryThis$u = functionUncurryThis;
3599
3811
  var call$l = functionCall;
3600
- var isCallable$6 = isCallable$t;
3601
- var isObject$9 = isObject$m;
3812
+ var isCallable$5 = isCallable$t;
3813
+ var isObject$7 = isObject$m;
3602
3814
  var isArray$3 = isArray$5;
3603
- var hasOwn$8 = hasOwnProperty_1;
3604
- var toString$f = toString$j;
3815
+ var hasOwn$7 = hasOwnProperty_1;
3816
+ var toString$e = toString$j;
3605
3817
  var lengthOfArrayLike$d = lengthOfArrayLike$g;
3606
3818
  var createProperty$3 = createProperty$6;
3607
- var fails$m = fails$F;
3819
+ var fails$l = fails$F;
3608
3820
  var parseJSONString = parseJsonString;
3609
3821
  var NATIVE_SYMBOL = symbolConstructorDetection;
3610
3822
 
3611
- var JSON$1 = globalThis$t.JSON;
3612
- var Number$1 = globalThis$t.Number;
3613
- var SyntaxError$4 = globalThis$t.SyntaxError;
3823
+ var JSON$1 = globalThis$s.JSON;
3824
+ var Number$1 = globalThis$s.Number;
3825
+ var SyntaxError$4 = globalThis$s.SyntaxError;
3614
3826
  var nativeParse = JSON$1 && JSON$1.parse;
3615
- var enumerableOwnProperties = getBuiltIn$3('Object', 'keys');
3827
+ var enumerableOwnProperties = getBuiltIn$2('Object', 'keys');
3616
3828
  // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
3617
3829
  var getOwnPropertyDescriptor$3 = Object.getOwnPropertyDescriptor;
3618
- var at$1 = uncurryThis$v(''.charAt);
3619
- var slice$3 = uncurryThis$v(''.slice);
3620
- var exec$5 = uncurryThis$v(/./.exec);
3621
- var push$6 = uncurryThis$v([].push);
3830
+ var at$1 = uncurryThis$u(''.charAt);
3831
+ var slice$3 = uncurryThis$u(''.slice);
3832
+ var exec$5 = uncurryThis$u(/./.exec);
3833
+ var push$6 = uncurryThis$u([].push);
3622
3834
 
3623
3835
  var IS_DIGIT = /^\d$/;
3624
3836
  var IS_NON_ZERO_DIGIT = /^[1-9]$/;
@@ -3629,7 +3841,7 @@ var PRIMITIVE = 0;
3629
3841
  var OBJECT = 1;
3630
3842
 
3631
3843
  var $parse = function (source, reviver) {
3632
- source = toString$f(source);
3844
+ source = toString$e(source);
3633
3845
  var context = new Context(source, 0);
3634
3846
  var root = context.parse();
3635
3847
  var value = root.value;
@@ -3637,7 +3849,7 @@ var $parse = function (source, reviver) {
3637
3849
  if (endIndex < source.length) {
3638
3850
  throw new SyntaxError$4('Unexpected extra character: "' + at$1(source, endIndex) + '" after the parsed data at: ' + endIndex);
3639
3851
  }
3640
- return isCallable$6(reviver) ? internalize({ '': value }, '', reviver, root) : value;
3852
+ return isCallable$5(reviver) ? internalize({ '': value }, '', reviver, root) : value;
3641
3853
  };
3642
3854
 
3643
3855
  var internalize = function (holder, name, reviver, node) {
@@ -3645,7 +3857,7 @@ var internalize = function (holder, name, reviver, node) {
3645
3857
  var unmodified = node && val === node.value;
3646
3858
  var context = unmodified && typeof node.source == 'string' ? { source: node.source } : {};
3647
3859
  var elementRecordsLen, keys, len, i, P;
3648
- if (isObject$9(val)) {
3860
+ if (isObject$7(val)) {
3649
3861
  var nodeIsArray = isArray$3(val);
3650
3862
  var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {};
3651
3863
  if (nodeIsArray) {
@@ -3659,7 +3871,7 @@ var internalize = function (holder, name, reviver, node) {
3659
3871
  len = lengthOfArrayLike$d(keys);
3660
3872
  for (i = 0; i < len; i++) {
3661
3873
  P = keys[i];
3662
- internalizeProperty(val, P, internalize(val, P, reviver, hasOwn$8(nodes, P) ? nodes[P] : undefined));
3874
+ internalizeProperty(val, P, internalize(val, P, reviver, hasOwn$7(nodes, P) ? nodes[P] : undefined));
3663
3875
  }
3664
3876
  }
3665
3877
  }
@@ -3667,7 +3879,7 @@ var internalize = function (holder, name, reviver, node) {
3667
3879
  };
3668
3880
 
3669
3881
  var internalizeProperty = function (object, key, value) {
3670
- if (DESCRIPTORS$c) {
3882
+ if (DESCRIPTORS$b) {
3671
3883
  var descriptor = getOwnPropertyDescriptor$3(object, key);
3672
3884
  if (descriptor && !descriptor.configurable) return;
3673
3885
  }
@@ -3831,7 +4043,7 @@ Context.prototype = {
3831
4043
  }
3832
4044
  };
3833
4045
 
3834
- var NO_SOURCE_SUPPORT = fails$m(function () {
4046
+ var NO_SOURCE_SUPPORT = fails$l(function () {
3835
4047
  var unsafeInt = '9007199254740993';
3836
4048
  var source;
3837
4049
  nativeParse(unsafeInt, function (key, value, context) {
@@ -3840,7 +4052,7 @@ var NO_SOURCE_SUPPORT = fails$m(function () {
3840
4052
  return source !== unsafeInt;
3841
4053
  });
3842
4054
 
3843
- var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails$m(function () {
4055
+ var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails$l(function () {
3844
4056
  // Safari 9 bug
3845
4057
  return 1 / nativeParse('-0 \t') !== -Infinity;
3846
4058
  });
@@ -3848,9 +4060,42 @@ var PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails$m(function () {
3848
4060
  // `JSON.parse` method
3849
4061
  // https://tc39.es/ecma262/#sec-json.parse
3850
4062
  // https://github.com/tc39/proposal-json-parse-with-source
3851
- $$B({ target: 'JSON', stat: true, forced: NO_SOURCE_SUPPORT }, {
4063
+ $$A({ target: 'JSON', stat: true, forced: NO_SOURCE_SUPPORT }, {
3852
4064
  parse: function parse(text, reviver) {
3853
- return PROPER_BASE_PARSE && !isCallable$6(reviver) ? nativeParse(text) : $parse(text, reviver);
4065
+ return PROPER_BASE_PARSE && !isCallable$5(reviver) ? nativeParse(text) : $parse(text, reviver);
4066
+ }
4067
+ });
4068
+
4069
+ var $$z = _export;
4070
+ var uncurryThis$t = functionUncurryThisClause;
4071
+ var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
4072
+ var toLength$5 = toLength$7;
4073
+ var toString$d = toString$j;
4074
+ var notARegExp$1 = notARegexp;
4075
+ var requireObjectCoercible$6 = requireObjectCoercible$b;
4076
+ var correctIsRegExpLogic$1 = correctIsRegexpLogic;
4077
+
4078
+ var slice$2 = uncurryThis$t(''.slice);
4079
+ var min$4 = Math.min;
4080
+
4081
+ var CORRECT_IS_REGEXP_LOGIC$1 = correctIsRegExpLogic$1('endsWith');
4082
+ // https://github.com/zloirock/core-js/pull/702
4083
+ var MDN_POLYFILL_BUG$1 = !CORRECT_IS_REGEXP_LOGIC$1 && !!function () {
4084
+ var descriptor = getOwnPropertyDescriptor$2(String.prototype, 'endsWith');
4085
+ return descriptor && !descriptor.writable;
4086
+ }();
4087
+
4088
+ // `String.prototype.endsWith` method
4089
+ // https://tc39.es/ecma262/#sec-string.prototype.endswith
4090
+ $$z({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG$1 && !CORRECT_IS_REGEXP_LOGIC$1 }, {
4091
+ endsWith: function endsWith(searchString /* , endPosition = @length */) {
4092
+ var that = toString$d(requireObjectCoercible$6(this));
4093
+ notARegExp$1(searchString);
4094
+ var search = toString$d(searchString);
4095
+ var endPosition = arguments.length > 1 ? arguments[1] : undefined;
4096
+ var len = that.length;
4097
+ var end = endPosition === undefined ? len : min$4(toLength$5(endPosition), len);
4098
+ return slice$2(that, end - search.length, end) === search;
3854
4099
  }
3855
4100
  });
3856
4101
 
@@ -3882,233 +4127,34 @@ const loadSession = async ({
3882
4127
  return null;
3883
4128
  }
3884
4129
  };
4130
+ const originSchema = z.url({
4131
+ protocol: /^https$/
4132
+ }).refine(url => !url.endsWith("/"));
4133
+ const getOriginOverride = variableName => {
4134
+ const override = process.env[variableName];
4135
+ if (!override) {
4136
+ return undefined;
4137
+ }
4138
+ if (!originSchema.safeParse(override).success) {
4139
+ throw new Error(`${variableName} must be an https URL without a trailing slash`);
4140
+ }
4141
+ return override;
4142
+ };
4143
+
4144
+ var $$y = _export;
4145
+ var globalThis$r = globalThis_1;
3885
4146
 
3886
- var $$A = _export;
3887
- var globalThis$s = globalThis_1;
3888
-
3889
4147
  // `globalThis` object
3890
4148
  // https://tc39.es/ecma262/#sec-globalthis
3891
- $$A({ global: true, forced: globalThis$s.globalThis !== globalThis$s }, {
3892
- globalThis: globalThis$s
4149
+ $$y({ global: true, forced: globalThis$r.globalThis !== globalThis$r }, {
4150
+ globalThis: globalThis$r
3893
4151
  });
3894
4152
 
3895
- var version = "0.36.4";
4153
+ var version = "0.37.0";
3896
4154
  var packageJson$1 = {
3897
4155
  version: version};
3898
4156
 
3899
- var defineProperty = objectDefineProperty.f;
3900
-
3901
- var proxyAccessor$2 = function (Target, Source, key) {
3902
- key in Target || defineProperty(Target, key, {
3903
- configurable: true,
3904
- get: function () { return Source[key]; },
3905
- set: function (it) { Source[key] = it; }
3906
- });
3907
- };
3908
-
3909
- var isCallable$5 = isCallable$t;
3910
- var isObject$8 = isObject$m;
3911
- var setPrototypeOf$4 = objectSetPrototypeOf;
3912
-
3913
- // makes subclassing work correct for wrapped built-ins
3914
- var inheritIfRequired$4 = function ($this, dummy, Wrapper) {
3915
- var NewTarget, NewTargetPrototype;
3916
- if (
3917
- // it can work only with native `setPrototypeOf`
3918
- setPrototypeOf$4 &&
3919
- // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
3920
- isCallable$5(NewTarget = dummy.constructor) &&
3921
- NewTarget !== Wrapper &&
3922
- isObject$8(NewTargetPrototype = NewTarget.prototype) &&
3923
- NewTargetPrototype !== Wrapper.prototype
3924
- ) setPrototypeOf$4($this, NewTargetPrototype);
3925
- return $this;
3926
- };
3927
-
3928
- var toString$e = toString$j;
3929
-
3930
- var normalizeStringArgument$1 = function (argument, $default) {
3931
- return argument === undefined ? arguments.length < 2 ? '' : $default : toString$e(argument);
3932
- };
3933
-
3934
- var isObject$7 = isObject$m;
3935
- var createNonEnumerableProperty$7 = createNonEnumerableProperty$d;
3936
-
3937
- // `InstallErrorCause` abstract operation
3938
- // https://tc39.es/ecma262/#sec-installerrorcause
3939
- var installErrorCause$1 = function (O, options) {
3940
- if (isObject$7(options) && 'cause' in options) {
3941
- createNonEnumerableProperty$7(O, 'cause', options.cause);
3942
- }
3943
- };
3944
-
3945
- var uncurryThis$u = functionUncurryThis;
3946
-
3947
- var $Error = Error;
3948
- var replace$7 = uncurryThis$u(''.replace);
3949
-
3950
- var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
3951
- // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
3952
- var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
3953
- var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
3954
-
3955
- var errorStackClear = function (stack, dropEntries) {
3956
- if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
3957
- while (dropEntries--) stack = replace$7(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
3958
- } return stack;
3959
- };
3960
-
3961
- var fails$l = fails$F;
3962
- var createPropertyDescriptor$2 = createPropertyDescriptor$7;
3963
-
3964
- var errorStackInstallable = !fails$l(function () {
3965
- var error = new Error('a');
3966
- if (!('stack' in error)) return true;
3967
- // eslint-disable-next-line es/no-object-defineproperty -- safe
3968
- Object.defineProperty(error, 'stack', createPropertyDescriptor$2(1, 7));
3969
- return error.stack !== 7;
3970
- });
3971
-
3972
- var createNonEnumerableProperty$6 = createNonEnumerableProperty$d;
3973
- var clearErrorStack = errorStackClear;
3974
- var ERROR_STACK_INSTALLABLE = errorStackInstallable;
3975
-
3976
- // non-standard V8
3977
- // eslint-disable-next-line es/no-nonstandard-error-properties -- safe
3978
- var captureStackTrace = Error.captureStackTrace;
3979
-
3980
- var errorStackInstall = function (error, C, stack, dropEntries) {
3981
- if (ERROR_STACK_INSTALLABLE) {
3982
- if (captureStackTrace) captureStackTrace(error, C);
3983
- else createNonEnumerableProperty$6(error, 'stack', clearErrorStack(stack, dropEntries));
3984
- }
3985
- };
3986
-
3987
- var getBuiltIn$2 = getBuiltIn$c;
3988
- var hasOwn$7 = hasOwnProperty_1;
3989
- var createNonEnumerableProperty$5 = createNonEnumerableProperty$d;
3990
- var isPrototypeOf$4 = objectIsPrototypeOf;
3991
- var setPrototypeOf$3 = objectSetPrototypeOf;
3992
- var copyConstructorProperties$1 = copyConstructorProperties$4;
3993
- var proxyAccessor$1 = proxyAccessor$2;
3994
- var inheritIfRequired$3 = inheritIfRequired$4;
3995
- var normalizeStringArgument = normalizeStringArgument$1;
3996
- var installErrorCause = installErrorCause$1;
3997
- var installErrorStack = errorStackInstall;
3998
- var DESCRIPTORS$b = descriptors;
3999
-
4000
- var wrapErrorConstructorWithCause$1 = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
4001
- var STACK_TRACE_LIMIT = 'stackTraceLimit';
4002
- var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
4003
- var path = FULL_NAME.split('.');
4004
- var ERROR_NAME = path[path.length - 1];
4005
- var OriginalError = getBuiltIn$2.apply(null, path);
4006
-
4007
- if (!OriginalError) return;
4008
-
4009
- var OriginalErrorPrototype = OriginalError.prototype;
4010
-
4011
- // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
4012
- if (hasOwn$7(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
4013
-
4014
- if (!FORCED) return OriginalError;
4015
-
4016
- var BaseError = getBuiltIn$2('Error');
4017
-
4018
- var WrappedError = wrapper(function (a, b) {
4019
- var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
4020
- var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
4021
- if (message !== undefined) createNonEnumerableProperty$5(result, 'message', message);
4022
- installErrorStack(result, WrappedError, result.stack, 2);
4023
- if (this && isPrototypeOf$4(OriginalErrorPrototype, this)) inheritIfRequired$3(result, this, WrappedError);
4024
- if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
4025
- return result;
4026
- });
4027
-
4028
- WrappedError.prototype = OriginalErrorPrototype;
4029
-
4030
- if (ERROR_NAME !== 'Error') {
4031
- if (setPrototypeOf$3) setPrototypeOf$3(WrappedError, BaseError);
4032
- else copyConstructorProperties$1(WrappedError, BaseError, { name: true });
4033
- } else if (DESCRIPTORS$b && STACK_TRACE_LIMIT in OriginalError) {
4034
- proxyAccessor$1(WrappedError, OriginalError, STACK_TRACE_LIMIT);
4035
- proxyAccessor$1(WrappedError, OriginalError, 'prepareStackTrace');
4036
- }
4037
-
4038
- copyConstructorProperties$1(WrappedError, OriginalError);
4039
-
4040
- try {
4041
- // Safari 13- bug: WebAssembly errors does not have a proper `.name`
4042
- if (OriginalErrorPrototype.name !== ERROR_NAME) {
4043
- createNonEnumerableProperty$5(OriginalErrorPrototype, 'name', ERROR_NAME);
4044
- }
4045
- OriginalErrorPrototype.constructor = WrappedError;
4046
- } catch (error) { /* empty */ }
4047
-
4048
- return WrappedError;
4049
- };
4050
-
4051
- /* eslint-disable no-unused-vars -- required for functions `.length` */
4052
- var $$z = _export;
4053
- var globalThis$r = globalThis_1;
4054
- var apply$2 = functionApply;
4055
- var wrapErrorConstructorWithCause = wrapErrorConstructorWithCause$1;
4056
-
4057
- var WEB_ASSEMBLY = 'WebAssembly';
4058
- var WebAssembly = globalThis$r[WEB_ASSEMBLY];
4059
-
4060
- // eslint-disable-next-line es/no-error-cause -- feature detection
4061
- var FORCED$7 = new Error('e', { cause: 7 }).cause !== 7;
4062
-
4063
- var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
4064
- var O = {};
4065
- // eslint-disable-next-line unicorn/no-immediate-mutation -- ES3 syntax limitation
4066
- O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED$7);
4067
- $$z({ global: true, constructor: true, arity: 1, forced: FORCED$7 }, O);
4068
- };
4069
-
4070
- var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
4071
- if (WebAssembly && WebAssembly[ERROR_NAME]) {
4072
- var O = {};
4073
- // eslint-disable-next-line unicorn/no-immediate-mutation -- ES3 syntax limitation
4074
- O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED$7);
4075
- $$z({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED$7 }, O);
4076
- }
4077
- };
4078
-
4079
- // https://tc39.es/ecma262/#sec-nativeerror
4080
- exportGlobalErrorCauseWrapper('Error', function (init) {
4081
- return function Error(message) { return apply$2(init, this, arguments); };
4082
- });
4083
- exportGlobalErrorCauseWrapper('EvalError', function (init) {
4084
- return function EvalError(message) { return apply$2(init, this, arguments); };
4085
- });
4086
- exportGlobalErrorCauseWrapper('RangeError', function (init) {
4087
- return function RangeError(message) { return apply$2(init, this, arguments); };
4088
- });
4089
- exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
4090
- return function ReferenceError(message) { return apply$2(init, this, arguments); };
4091
- });
4092
- exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
4093
- return function SyntaxError(message) { return apply$2(init, this, arguments); };
4094
- });
4095
- exportGlobalErrorCauseWrapper('TypeError', function (init) {
4096
- return function TypeError(message) { return apply$2(init, this, arguments); };
4097
- });
4098
- exportGlobalErrorCauseWrapper('URIError', function (init) {
4099
- return function URIError(message) { return apply$2(init, this, arguments); };
4100
- });
4101
- exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
4102
- return function CompileError(message) { return apply$2(init, this, arguments); };
4103
- });
4104
- exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
4105
- return function LinkError(message) { return apply$2(init, this, arguments); };
4106
- });
4107
- exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
4108
- return function RuntimeError(message) { return apply$2(init, this, arguments); };
4109
- });
4110
-
4111
- var $$y = _export;
4157
+ var $$x = _export;
4112
4158
  var call$k = functionCall;
4113
4159
  var iterate$4 = iterate$8;
4114
4160
  var aCallable$b = aCallable$l;
@@ -4121,7 +4167,7 @@ var forEachWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError
4121
4167
 
4122
4168
  // `Iterator.prototype.forEach` method
4123
4169
  // https://tc39.es/ecma262/#sec-iterator.prototype.foreach
4124
- $$y({ target: 'Iterator', proto: true, real: true, forced: forEachWithoutClosingOnEarlyError }, {
4170
+ $$x({ target: 'Iterator', proto: true, real: true, forced: forEachWithoutClosingOnEarlyError }, {
4125
4171
  forEach: function forEach(fn) {
4126
4172
  anObject$c(this);
4127
4173
  try {
@@ -4140,46 +4186,304 @@ $$y({ target: 'Iterator', proto: true, real: true, forced: forEachWithoutClosing
4140
4186
  }
4141
4187
  });
4142
4188
 
4143
- class ApiError extends Error {
4144
- constructor(message, status, statusText, responseBody, url) {
4145
- super(message);
4146
- this.status = status;
4147
- this.statusText = statusText;
4148
- this.responseBody = responseBody;
4149
- this.url = url;
4150
- this.name = "ApiError";
4151
- }
4189
+ //#region src/bearer-strategy.ts
4190
+ var BearerStrategy = class {
4191
+ lastSent;
4192
+ lastRecoveryAt;
4193
+ now;
4194
+ cooldownMs;
4195
+ exchange;
4196
+ constructor(options) {
4197
+ this.now = options.now ?? Date.now;
4198
+ this.cooldownMs = options.cooldownMs ?? 5e3;
4199
+ this.exchange = options.exchange;
4200
+ }
4201
+ /** @inheritDoc */
4202
+ async attach(request) {
4203
+ const token = await this.exchange();
4204
+ this.lastSent = token;
4205
+ const headers = new Headers(request.headers);
4206
+ headers.set("Authorization", `Bearer ${token}`);
4207
+ return new Request(request, { headers });
4208
+ }
4209
+ /** @inheritDoc */
4210
+ async ensure() {
4211
+ await this.exchange();
4212
+ }
4213
+ /** @inheritDoc */
4214
+ async onUnauthorized(_response) {
4215
+ if (this.recoveredRecently()) return false;
4216
+ await this.exchange({ refused: this.lastSent });
4217
+ this.lastRecoveryAt = this.now();
4218
+ return true;
4219
+ }
4220
+ recoveredRecently() {
4221
+ return this.lastRecoveryAt !== void 0 && this.now() - this.lastRecoveryAt < this.cooldownMs;
4222
+ }
4223
+ };
4224
+
4225
+ //#region src/single-flight.ts
4226
+ /**
4227
+ * Shares one in-flight call. While a call is running, further callers get its promise instead
4228
+ * of starting their own; once it settles, the next caller starts a new one.
4229
+ */
4230
+ function singleFlight(fn) {
4231
+ let inFlight;
4232
+ return (...args) => {
4233
+ if (inFlight) return inFlight;
4234
+ inFlight = fn(...args).finally(() => {
4235
+ inFlight = void 0;
4236
+ });
4237
+ return inFlight;
4238
+ };
4152
4239
  }
4153
- async function assertApiResponseOk(res, url) {
4154
- if (!res.ok) {
4155
- let responseBody;
4156
- let text = "";
4157
- try {
4158
- text = await res.text();
4159
- responseBody = text ? JSON.parse(text) : null;
4160
- } catch (_a) {
4161
- responseBody = text || null;
4162
- }
4163
- throw new ApiError(`Request failed: ${res.status} ${res.statusText}`, res.status, res.statusText, responseBody, url);
4164
- }
4240
+
4241
+ //#region src/tracked.ts
4242
+ /** Wraps an async function, counting settled calls and remembering how the last one settled. */
4243
+ function tracked(fn) {
4244
+ let completed = 0;
4245
+ let last;
4246
+ async function call(...args) {
4247
+ try {
4248
+ const value = await fn(...args);
4249
+ last = {
4250
+ settled: "fulfilled",
4251
+ value
4252
+ };
4253
+ return value;
4254
+ } catch (reason) {
4255
+ last = {
4256
+ settled: "rejected",
4257
+ reason
4258
+ };
4259
+ throw reason;
4260
+ } finally {
4261
+ completed += 1;
4262
+ }
4263
+ }
4264
+ return {
4265
+ call,
4266
+ getCompleted: () => completed,
4267
+ getLast: () => last
4268
+ };
4165
4269
  }
4166
- const ERROR_SUGGESTIONS = {
4167
- 400: {
4168
- default: ["The request was invalid. Check the server response above for details."],
4169
- byEndpoint: {
4170
- library: ["The application data may be invalid or corrupted.", "Try running 'vention unlink' and then 'vention link' to re-link the application."]
4171
- }
4172
- },
4173
- 401: {
4174
- default: ["Authentication error. Try running 'vention login' to re-authenticate."]
4175
- },
4176
- 403: {
4177
- default: ["Authentication error. Try running 'vention login' to re-authenticate."]
4178
- },
4179
- 404: {
4180
- default: ["The requested resource was not found."],
4181
- byEndpoint: {
4182
- allocations: ["No active session found for this design.", "Make sure the design is open in your browser with a live session."],
4270
+
4271
+ //#region src/with-auth-strategy.ts
4272
+ /** Sends a clone of the request through the strategy's `attach`, leaving the original replayable. */
4273
+ async function fetchWithAuth(authStrategy, fetch, request) {
4274
+ const clonedRequest = request.clone();
4275
+ return fetch(await authStrategy.attach(clonedRequest));
4276
+ }
4277
+ /** A 401 that lands after a recovery finished takes that recovery's decision: its error, or its verdict. */
4278
+ function inheritRecovery(outcome) {
4279
+ if (outcome?.settled === "rejected") throw outcome.reason;
4280
+ return outcome?.value ?? true;
4281
+ }
4282
+ /** A fetch that attaches through the strategy, and on a 401 recovers once and retries once. */
4283
+ function withAuthStrategy(authStrategy, fetch = globalThis.fetch) {
4284
+ const { call: recover, getCompleted: getRecoveryCount, getLast: getLastRecovery } = tracked((response) => authStrategy.onUnauthorized(response));
4285
+ const tryRecover = singleFlight(recover);
4286
+ return async (input, init) => {
4287
+ const request = new Request(input, init);
4288
+ const startRecoveryCount = getRecoveryCount();
4289
+ const response = await fetchWithAuth(authStrategy, fetch, request);
4290
+ if (response.status !== 401) return response;
4291
+ if (getRecoveryCount() > startRecoveryCount ? inheritRecovery(getLastRecovery()) : await tryRecover(response)) return fetchWithAuth(authStrategy, fetch, request);
4292
+ return response;
4293
+ };
4294
+ }
4295
+
4296
+ //#region src/errors/authorization-server-unavailable.ts
4297
+ var AuthorizationServerUnavailable = class extends Error {
4298
+ name = "AuthorizationServerUnavailable";
4299
+ };
4300
+
4301
+ //#region src/discovery.ts
4302
+ const REQUEST_TIMEOUT_MS$2 = 1e4;
4303
+ async function discoverAuthorizationServer(issuer, fetch = globalThis.fetch) {
4304
+ const metadata = await readMetadata(`${issuer}/.well-known/oauth-authorization-server`, fetch);
4305
+ return {
4306
+ tokenEndpoint: metadata.token_endpoint,
4307
+ identityProviderIssuer: metadata.vention_identity_provider_issuer,
4308
+ clients: metadata.vention_clients
4309
+ };
4310
+ }
4311
+ async function discoverOpenIdProvider(issuer, fetch = globalThis.fetch) {
4312
+ const url = `${issuer}/.well-known/openid-configuration`;
4313
+ const metadata = await readMetadata(url, fetch);
4314
+ if (metadata.issuer !== issuer) throw new AuthorizationServerUnavailable(`${url} names the issuer ${metadata.issuer}, not ${issuer}`);
4315
+ return {
4316
+ authorizationEndpoint: metadata.authorization_endpoint,
4317
+ tokenEndpoint: metadata.token_endpoint
4318
+ };
4319
+ }
4320
+ async function readMetadata(url, fetch) {
4321
+ const response = await fetch(url, {
4322
+ headers: { Accept: "application/json" },
4323
+ redirect: "error",
4324
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS$2)
4325
+ }).catch((error) => {
4326
+ throw new AuthorizationServerUnavailable(`Could not reach ${url}`, { cause: error });
4327
+ });
4328
+ if (!response.ok) throw new AuthorizationServerUnavailable(`${url} answered ${response.status}`);
4329
+ return response.json().catch((error) => {
4330
+ throw new AuthorizationServerUnavailable(`${url} did not answer with JSON`, { cause: error });
4331
+ });
4332
+ }
4333
+
4334
+ //#region src/errors/exchange-rejected.ts
4335
+ var ExchangeRejected = class extends Error {
4336
+ code;
4337
+ name = "ExchangeRejected";
4338
+ constructor(code) {
4339
+ super(`The authorization server refused the token exchange (${code})`);
4340
+ this.code = code;
4341
+ }
4342
+ };
4343
+
4344
+ //#region src/errors/login-required.ts
4345
+ var LoginRequired = class extends Error {
4346
+ name = "LoginRequired";
4347
+ };
4348
+
4349
+ //#region src/errors/login-timed-out.ts
4350
+ var LoginTimedOut = class extends Error {
4351
+ name = "LoginTimedOut";
4352
+ constructor() {
4353
+ super("Login timed out");
4354
+ }
4355
+ };
4356
+
4357
+ //#region src/oauth2-token-request.ts
4358
+ const REQUEST_TIMEOUT_MS$1 = 1e4;
4359
+ function exchangeForGatewayToken(tokenEndpoint, subjectToken, fetch, now) {
4360
+ return requestToken(tokenEndpoint, subjectToken, "urn:ietf:params:oauth:token-type:access_token", fetch, now);
4361
+ }
4362
+ function renewGatewayToken(tokenEndpoint, gatewayToken, fetch, now) {
4363
+ return requestToken(tokenEndpoint, gatewayToken, "urn:ietf:params:oauth:token-type:jwt", fetch, now);
4364
+ }
4365
+ async function requestToken(tokenEndpoint, subjectToken, subjectTokenType, fetch, now) {
4366
+ const response = await fetch(tokenEndpoint, {
4367
+ method: "POST",
4368
+ headers: {
4369
+ "Content-Type": "application/x-www-form-urlencoded",
4370
+ Accept: "application/json"
4371
+ },
4372
+ body: new URLSearchParams({
4373
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
4374
+ subject_token: subjectToken,
4375
+ subject_token_type: subjectTokenType
4376
+ }),
4377
+ redirect: "error",
4378
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS$1)
4379
+ }).catch((error) => {
4380
+ throw new AuthorizationServerUnavailable("The authorization server could not be reached", { cause: error });
4381
+ });
4382
+ if (response.status >= 500 || response.status === 408 || response.status === 429) throw new AuthorizationServerUnavailable(`The authorization server answered ${response.status}`);
4383
+ if (!response.ok) {
4384
+ const refusal = await response.json().catch(() => void 0);
4385
+ throw new ExchangeRejected(refusal?.error ?? `http_${response.status}`);
4386
+ }
4387
+ return response.json().then((body) => toStoredGatewayToken(body, now())).catch(() => {
4388
+ throw new AuthorizationServerUnavailable("The authorization server returned an unusable token response");
4389
+ });
4390
+ }
4391
+ function toStoredGatewayToken({ access_token: token, expires_in: expiresIn }, receivedAt) {
4392
+ const payload = (token.split(".")[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
4393
+ const claims = JSON.parse(atob(payload));
4394
+ return {
4395
+ token,
4396
+ receivedAt,
4397
+ expiresAt: receivedAt + expiresIn * 1e3,
4398
+ capExpiresAt: receivedAt + (claims.cap_exp - claims.exp + expiresIn) * 1e3
4399
+ };
4400
+ }
4401
+
4402
+ //#region src/oauth2-token-exchange.ts
4403
+ function loginRequired() {
4404
+ return new LoginRequired("Session expired. Run 'vention login'.");
4405
+ }
4406
+ function outlivesMargin(expiresAt, now) {
4407
+ return expiresAt - now > 6e4;
4408
+ }
4409
+ function isFresh(token, now) {
4410
+ const halfLife = (token.expiresAt - token.receivedAt) / 2;
4411
+ return now - token.receivedAt < halfLife && outlivesMargin(token.expiresAt, now);
4412
+ }
4413
+ function oauth2TokenExchange({ issuer, store, now = Date.now, fetch = globalThis.fetch }) {
4414
+ const storedToken = async () => {
4415
+ const latest = await store.read();
4416
+ if (latest === void 0) throw loginRequired();
4417
+ return latest.token;
4418
+ };
4419
+ const renew = singleFlight(async (current) => {
4420
+ const beforeRenewal = await storedToken();
4421
+ if (beforeRenewal !== current.token) return beforeRenewal;
4422
+ const { tokenEndpoint } = await discoverAuthorizationServer(issuer, fetch);
4423
+ const renewed = await renewGatewayToken(tokenEndpoint, current.token, fetch, now).catch((error) => {
4424
+ throw error instanceof ExchangeRejected ? loginRequired() : error;
4425
+ });
4426
+ if (!outlivesMargin(renewed.expiresAt, now())) throw loginRequired();
4427
+ const beforeWrite = await storedToken();
4428
+ if (beforeWrite !== current.token) return beforeWrite;
4429
+ await store.write(renewed);
4430
+ return renewed.token;
4431
+ });
4432
+ return async (request) => {
4433
+ const current = await store.read();
4434
+ if (current === void 0 || now() >= current.capExpiresAt) throw loginRequired();
4435
+ const currentRefused = request?.refused === current.token;
4436
+ if (!currentRefused && isFresh(current, now())) return current.token;
4437
+ const token = await renew(current).catch((error) => {
4438
+ if (error instanceof AuthorizationServerUnavailable && !currentRefused && outlivesMargin(current.expiresAt, now())) return current.token;
4439
+ throw error;
4440
+ });
4441
+ if (token === request?.refused) throw loginRequired();
4442
+ return token;
4443
+ };
4444
+ }
4445
+
4446
+ class ApiError extends Error {
4447
+ constructor(message, status, statusText, responseBody, url) {
4448
+ super(message);
4449
+ this.status = status;
4450
+ this.statusText = statusText;
4451
+ this.responseBody = responseBody;
4452
+ this.url = url;
4453
+ this.name = "ApiError";
4454
+ }
4455
+ }
4456
+ const buildApiError = (response, responseBody, url) => new ApiError(`Request failed: ${response.status} ${response.statusText}`, response.status, response.statusText, responseBody, url);
4457
+ async function assertApiResponseOk(res, url) {
4458
+ if (!res.ok) {
4459
+ let responseBody;
4460
+ let text = "";
4461
+ try {
4462
+ text = await res.text();
4463
+ responseBody = text ? JSON.parse(text) : null;
4464
+ } catch (_a) {
4465
+ responseBody = text || null;
4466
+ }
4467
+ throw buildApiError(res, responseBody, url);
4468
+ }
4469
+ }
4470
+ const ERROR_SUGGESTIONS = {
4471
+ 400: {
4472
+ default: ["The request was invalid. Check the server response above for details."],
4473
+ byEndpoint: {
4474
+ library: ["The application data may be invalid or corrupted.", "Try running 'vention unlink' and then 'vention link' to re-link the application."]
4475
+ }
4476
+ },
4477
+ 401: {
4478
+ default: ["Authentication error. Try running 'vention login' to re-authenticate."]
4479
+ },
4480
+ 403: {
4481
+ default: ["Authentication error. Try running 'vention login' to re-authenticate."]
4482
+ },
4483
+ 404: {
4484
+ default: ["The requested resource was not found."],
4485
+ byEndpoint: {
4486
+ allocations: ["No active session found for this design.", "Make sure the design is open in your browser with a live session."],
4183
4487
  library: ["The application was not found on the digital twin.", "The application may have been deleted or the session may have expired.", "Try refreshing the design in your browser and running 'vention link' again."]
4184
4488
  }
4185
4489
  },
@@ -4221,6 +4525,8 @@ const handleCommandError = (error, context) => {
4221
4525
  console.error();
4222
4526
  suggestions.forEach(msg => console.error(chalk.yellow(msg)));
4223
4527
  }
4528
+ } else if (error instanceof LoginRequired) {
4529
+ console.error(chalk.red(error.message));
4224
4530
  } else {
4225
4531
  console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
4226
4532
  }
@@ -4237,10 +4543,11 @@ const fetchJson = async (url, options = {}) => {
4237
4543
  const {
4238
4544
  method = "GET",
4239
4545
  headers = {},
4240
- body
4546
+ body,
4547
+ fetchImpl = fetchWithUserAgent
4241
4548
  } = options;
4242
4549
  verboseLog(`${method} ${url}`);
4243
- const res = await fetchWithUserAgent(url, {
4550
+ const res = await fetchImpl(url, {
4244
4551
  method,
4245
4552
  headers,
4246
4553
  body: body !== undefined ? JSON.stringify(body) : undefined
@@ -4255,7 +4562,7 @@ const POSTHOG_PROJECT_TOKENS = {
4255
4562
  };
4256
4563
  const POSTHOG_FLAGS_URL = "https://us.i.posthog.com/flags?v=2";
4257
4564
  const CACHE_TTL_MS = 15 * 60 * 1000;
4258
- const REQUEST_TIMEOUT_MS$2 = 2000;
4565
+ const REQUEST_TIMEOUT_MS = 2000;
4259
4566
  const FlagsResponseSchema = z.object({
4260
4567
  flags: z.record(z.string(), z.object({
4261
4568
  enabled: z.boolean()
@@ -4317,7 +4624,7 @@ const fetchFlags = async (projectToken, distinctId) => {
4317
4624
  api_key: projectToken,
4318
4625
  distinct_id: distinctId
4319
4626
  }),
4320
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS$2)
4627
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4321
4628
  });
4322
4629
  if (!response.ok) {
4323
4630
  return undefined;
@@ -4375,18 +4682,18 @@ if (NOT_GENERIC || INCORRECT_NAME) {
4375
4682
  }, { unsafe: true });
4376
4683
  }
4377
4684
 
4378
- var uncurryThis$t = functionUncurryThis;
4685
+ var uncurryThis$s = functionUncurryThis;
4379
4686
  var toIntegerOrInfinity$8 = toIntegerOrInfinity$b;
4380
- var toString$d = toString$j;
4381
- var requireObjectCoercible$6 = requireObjectCoercible$b;
4687
+ var toString$c = toString$j;
4688
+ var requireObjectCoercible$5 = requireObjectCoercible$b;
4382
4689
 
4383
- var charAt$8 = uncurryThis$t(''.charAt);
4384
- var charCodeAt$1 = uncurryThis$t(''.charCodeAt);
4385
- var stringSlice$8 = uncurryThis$t(''.slice);
4690
+ var charAt$8 = uncurryThis$s(''.charAt);
4691
+ var charCodeAt$1 = uncurryThis$s(''.charCodeAt);
4692
+ var stringSlice$8 = uncurryThis$s(''.slice);
4386
4693
 
4387
4694
  var createMethod$4 = function (CONVERT_TO_STRING) {
4388
4695
  return function ($this, pos) {
4389
- var S = toString$d(requireObjectCoercible$6($this));
4696
+ var S = toString$c(requireObjectCoercible$5($this));
4390
4697
  var position = toIntegerOrInfinity$8(pos);
4391
4698
  var size = S.length;
4392
4699
  var first, second;
@@ -4413,7 +4720,7 @@ var stringMultibyte = {
4413
4720
  };
4414
4721
 
4415
4722
  var charAt$7 = stringMultibyte.charAt;
4416
- var toString$c = toString$j;
4723
+ var toString$b = toString$j;
4417
4724
  var InternalStateModule$5 = internalState;
4418
4725
  var defineIterator = iteratorDefine;
4419
4726
  var createIterResultObject$1 = createIterResultObject$4;
@@ -4427,7 +4734,7 @@ var getInternalState$4 = InternalStateModule$5.getterFor(STRING_ITERATOR);
4427
4734
  defineIterator(String, 'String', function (iterated) {
4428
4735
  setInternalState$4(this, {
4429
4736
  type: STRING_ITERATOR,
4430
- string: toString$c(iterated),
4737
+ string: toString$b(iterated),
4431
4738
  index: 0
4432
4739
  });
4433
4740
  // `%StringIteratorPrototype%.next` method
@@ -4490,7 +4797,7 @@ var isArray$2 = isArray$5;
4490
4797
 
4491
4798
  var $TypeError$b = TypeError;
4492
4799
  // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
4493
- var getOwnPropertyDescriptor$2 = Object.getOwnPropertyDescriptor;
4800
+ var getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
4494
4801
 
4495
4802
  // Safari < 13 does not throw an error in this case
4496
4803
  var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS$9 && !function () {
@@ -4505,7 +4812,7 @@ var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS$9 && !function () {
4505
4812
  }();
4506
4813
 
4507
4814
  var arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
4508
- if (isArray$2(O) && !getOwnPropertyDescriptor$2(O, 'length').writable) {
4815
+ if (isArray$2(O) && !getOwnPropertyDescriptor$1(O, 'length').writable) {
4509
4816
  throw new $TypeError$b('Cannot set read only .length');
4510
4817
  } return O.length = length;
4511
4818
  } : function (O, length) {
@@ -4565,7 +4872,7 @@ var arrayFrom$1 = function from(arrayLike /* , mapfn = undefined, thisArg = unde
4565
4872
  };
4566
4873
 
4567
4874
  // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
4568
- var uncurryThis$s = functionUncurryThis;
4875
+ var uncurryThis$r = functionUncurryThis;
4569
4876
 
4570
4877
  var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
4571
4878
  var base = 36;
@@ -4582,15 +4889,15 @@ var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
4582
4889
  var baseMinusTMin = base - tMin;
4583
4890
 
4584
4891
  var $RangeError$7 = RangeError;
4585
- var exec$4 = uncurryThis$s(regexSeparators.exec);
4892
+ var exec$4 = uncurryThis$r(regexSeparators.exec);
4586
4893
  var floor$7 = Math.floor;
4587
4894
  var fromCharCode$2 = String.fromCharCode;
4588
- var charCodeAt = uncurryThis$s(''.charCodeAt);
4589
- var join$4 = uncurryThis$s([].join);
4590
- var push$5 = uncurryThis$s([].push);
4591
- var replace$6 = uncurryThis$s(''.replace);
4592
- var split$2 = uncurryThis$s(''.split);
4593
- var toLowerCase$1 = uncurryThis$s(''.toLowerCase);
4895
+ var charCodeAt = uncurryThis$r(''.charCodeAt);
4896
+ var join$4 = uncurryThis$r([].join);
4897
+ var push$5 = uncurryThis$r([].push);
4898
+ var replace$6 = uncurryThis$r(''.replace);
4899
+ var split$2 = uncurryThis$r(''.split);
4900
+ var toLowerCase$1 = uncurryThis$r(''.toLowerCase);
4594
4901
 
4595
4902
  /**
4596
4903
  * Creates an array containing the numeric code points of each Unicode
@@ -4745,22 +5052,22 @@ var stringPunycodeToAscii = function (input) {
4745
5052
  return join$4(encoded, '.');
4746
5053
  };
4747
5054
 
4748
- var $$x = _export;
4749
- var uncurryThis$r = functionUncurryThis;
5055
+ var $$w = _export;
5056
+ var uncurryThis$q = functionUncurryThis;
4750
5057
  var toAbsoluteIndex$2 = toAbsoluteIndex$4;
4751
5058
 
4752
5059
  var $RangeError$6 = RangeError;
4753
5060
  var fromCharCode$1 = String.fromCharCode;
4754
5061
  // eslint-disable-next-line es/no-string-fromcodepoint -- required for testing
4755
5062
  var $fromCodePoint = String.fromCodePoint;
4756
- var join$3 = uncurryThis$r([].join);
5063
+ var join$3 = uncurryThis$q([].join);
4757
5064
 
4758
5065
  // length should be 1, old FF problem
4759
5066
  var INCORRECT_LENGTH = !!$fromCodePoint && $fromCodePoint.length !== 1;
4760
5067
 
4761
5068
  // `String.fromCodePoint` method
4762
5069
  // https://tc39.es/ecma262/#sec-string.fromcodepoint
4763
- $$x({ target: 'String', stat: true, arity: 1, forced: INCORRECT_LENGTH }, {
5070
+ $$w({ target: 'String', stat: true, arity: 1, forced: INCORRECT_LENGTH }, {
4764
5071
  // eslint-disable-next-line no-unused-vars -- required for `.length`
4765
5072
  fromCodePoint: function fromCodePoint(x) {
4766
5073
  var elements = [];
@@ -4822,12 +5129,12 @@ var arraySort$1 = sort$1;
4822
5129
  // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
4823
5130
 
4824
5131
 
4825
- var $$w = _export;
5132
+ var $$v = _export;
4826
5133
  var globalThis$q = globalThis_1;
4827
5134
  var safeGetBuiltIn = safeGetBuiltIn$2;
4828
5135
  var getBuiltIn$1 = getBuiltIn$c;
4829
5136
  var call$h = functionCall;
4830
- var uncurryThis$q = functionUncurryThis;
5137
+ var uncurryThis$p = functionUncurryThis;
4831
5138
  var DESCRIPTORS$8 = descriptors;
4832
5139
  var USE_NATIVE_URL$1 = urlConstructorDetection;
4833
5140
  var defineBuiltIn$6 = defineBuiltIn$e;
@@ -4862,23 +5169,23 @@ var getInternalIteratorState = InternalStateModule$4.getterFor(URL_SEARCH_PARAMS
4862
5169
 
4863
5170
  var nativeFetch = safeGetBuiltIn('fetch');
4864
5171
  var NativeRequest = safeGetBuiltIn('Request');
4865
- var Headers = safeGetBuiltIn('Headers');
5172
+ var Headers$1 = safeGetBuiltIn('Headers');
4866
5173
  var RequestPrototype = NativeRequest && NativeRequest.prototype;
4867
- var HeadersPrototype = Headers && Headers.prototype;
5174
+ var HeadersPrototype = Headers$1 && Headers$1.prototype;
4868
5175
  var TypeError$5 = globalThis$q.TypeError;
4869
- var encodeURIComponent$1 = globalThis$q.encodeURIComponent;
5176
+ var encodeURIComponent$2 = globalThis$q.encodeURIComponent;
4870
5177
  var fromCharCode = String.fromCharCode;
4871
5178
  var fromCodePoint = getBuiltIn$1('String', 'fromCodePoint');
4872
5179
  var $parseInt = parseInt;
4873
- var charAt$6 = uncurryThis$q(''.charAt);
4874
- var join$2 = uncurryThis$q([].join);
4875
- var push$4 = uncurryThis$q([].push);
4876
- var replace$5 = uncurryThis$q(''.replace);
4877
- var shift$1 = uncurryThis$q([].shift);
4878
- var splice = uncurryThis$q([].splice);
4879
- var split$1 = uncurryThis$q(''.split);
4880
- var stringSlice$7 = uncurryThis$q(''.slice);
4881
- var exec$3 = uncurryThis$q(/./.exec);
5180
+ var charAt$6 = uncurryThis$p(''.charAt);
5181
+ var join$2 = uncurryThis$p([].join);
5182
+ var push$4 = uncurryThis$p([].push);
5183
+ var replace$5 = uncurryThis$p(''.replace);
5184
+ var shift$1 = uncurryThis$p([].shift);
5185
+ var splice = uncurryThis$p([].splice);
5186
+ var split$1 = uncurryThis$p(''.split);
5187
+ var stringSlice$7 = uncurryThis$p(''.slice);
5188
+ var exec$3 = uncurryThis$p(/./.exec);
4882
5189
 
4883
5190
  var plus = /\+/g;
4884
5191
  var FALLBACK_REPLACER = '\uFFFD';
@@ -5031,7 +5338,7 @@ var replacer = function (match) {
5031
5338
  };
5032
5339
 
5033
5340
  var serialize = function (it) {
5034
- return replace$5(encodeURIComponent$1(it), find, replacer);
5341
+ return replace$5(encodeURIComponent$2(it), find, replacer);
5035
5342
  };
5036
5343
 
5037
5344
  var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
@@ -5291,21 +5598,21 @@ if (DESCRIPTORS$8) defineBuiltInAccessor$7(URLSearchParamsPrototype$3, 'size', {
5291
5598
 
5292
5599
  setToStringTag$2(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
5293
5600
 
5294
- $$w({ global: true, constructor: true, forced: !USE_NATIVE_URL$1 }, {
5601
+ $$v({ global: true, constructor: true, forced: !USE_NATIVE_URL$1 }, {
5295
5602
  URLSearchParams: URLSearchParamsConstructor
5296
5603
  });
5297
5604
 
5298
5605
  // Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams`
5299
- if (!USE_NATIVE_URL$1 && isCallable$4(Headers)) {
5300
- var headersHas = uncurryThis$q(HeadersPrototype.has);
5301
- var headersSet = uncurryThis$q(HeadersPrototype.set);
5606
+ if (!USE_NATIVE_URL$1 && isCallable$4(Headers$1)) {
5607
+ var headersHas = uncurryThis$p(HeadersPrototype.has);
5608
+ var headersSet = uncurryThis$p(HeadersPrototype.set);
5302
5609
 
5303
5610
  var wrapRequestOptions = function (init) {
5304
5611
  if (isObject$6(init)) {
5305
5612
  var body = init.body;
5306
5613
  var headers;
5307
5614
  if (classof$8(body) === URL_SEARCH_PARAMS) {
5308
- headers = init.headers ? new Headers(init.headers) : new Headers();
5615
+ headers = init.headers ? new Headers$1(init.headers) : new Headers$1();
5309
5616
  if (!headersHas(headers, 'content-type')) {
5310
5617
  headersSet(headers, 'content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
5311
5618
  }
@@ -5318,7 +5625,7 @@ if (!USE_NATIVE_URL$1 && isCallable$4(Headers)) {
5318
5625
  };
5319
5626
 
5320
5627
  if (isCallable$4(nativeFetch)) {
5321
- $$w({ global: true, enumerable: true, dontCallGetSet: true, forced: true }, {
5628
+ $$v({ global: true, enumerable: true, dontCallGetSet: true, forced: true }, {
5322
5629
  fetch: function fetch(input /* , init */) {
5323
5630
  return nativeFetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
5324
5631
  }
@@ -5334,7 +5641,7 @@ if (!USE_NATIVE_URL$1 && isCallable$4(Headers)) {
5334
5641
  RequestPrototype.constructor = RequestConstructor;
5335
5642
  RequestConstructor.prototype = RequestPrototype;
5336
5643
 
5337
- $$w({ global: true, constructor: true, dontCallGetSet: true, forced: true }, {
5644
+ $$v({ global: true, constructor: true, dontCallGetSet: true, forced: true }, {
5338
5645
  Request: RequestConstructor
5339
5646
  });
5340
5647
  }
@@ -5347,12 +5654,12 @@ var web_urlSearchParams_constructor = {
5347
5654
 
5348
5655
  // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
5349
5656
 
5350
- var $$v = _export;
5657
+ var $$u = _export;
5351
5658
  var DESCRIPTORS$7 = descriptors;
5352
5659
  var USE_NATIVE_URL = urlConstructorDetection;
5353
5660
  var globalThis$p = globalThis_1;
5354
5661
  var bind$4 = functionBindContext;
5355
- var uncurryThis$p = functionUncurryThis;
5662
+ var uncurryThis$o = functionUncurryThis;
5356
5663
  var defineBuiltIn$5 = defineBuiltIn$e;
5357
5664
  var defineBuiltInAccessor$6 = defineBuiltInAccessor$c;
5358
5665
  var anInstance$2 = anInstance$6;
@@ -5375,22 +5682,22 @@ var getInternalSearchParamsState = URLSearchParamsModule.getState;
5375
5682
 
5376
5683
  var NativeURL = globalThis$p.URL;
5377
5684
  var TypeError$4 = globalThis$p.TypeError;
5378
- var encodeURIComponent = globalThis$p.encodeURIComponent;
5685
+ var encodeURIComponent$1 = globalThis$p.encodeURIComponent;
5379
5686
  var parseInt$1 = globalThis$p.parseInt;
5380
5687
  var floor$5 = Math.floor;
5381
5688
  var pow$1 = Math.pow;
5382
- var charAt$5 = uncurryThis$p(''.charAt);
5383
- var exec$2 = uncurryThis$p(/./.exec);
5384
- var join$1 = uncurryThis$p([].join);
5385
- var numberToString$1 = uncurryThis$p(1.1.toString);
5386
- var pop = uncurryThis$p([].pop);
5387
- var push$3 = uncurryThis$p([].push);
5388
- var replace$4 = uncurryThis$p(''.replace);
5389
- var shift = uncurryThis$p([].shift);
5390
- var split = uncurryThis$p(''.split);
5391
- var stringSlice$6 = uncurryThis$p(''.slice);
5392
- var toLowerCase = uncurryThis$p(''.toLowerCase);
5393
- var unshift = uncurryThis$p([].unshift);
5689
+ var charAt$5 = uncurryThis$o(''.charAt);
5690
+ var exec$2 = uncurryThis$o(/./.exec);
5691
+ var join$1 = uncurryThis$o([].join);
5692
+ var numberToString$1 = uncurryThis$o(1.1.toString);
5693
+ var pop = uncurryThis$o([].pop);
5694
+ var push$3 = uncurryThis$o([].push);
5695
+ var replace$4 = uncurryThis$o(''.replace);
5696
+ var shift = uncurryThis$o([].shift);
5697
+ var split = uncurryThis$o(''.split);
5698
+ var stringSlice$6 = uncurryThis$o(''.slice);
5699
+ var toLowerCase = uncurryThis$o(''.toLowerCase);
5700
+ var unshift = uncurryThis$o([].unshift);
5394
5701
 
5395
5702
  var INVALID_AUTHORITY = 'Invalid authority';
5396
5703
  var INVALID_SCHEME = 'Invalid scheme';
@@ -5625,7 +5932,7 @@ var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, {
5625
5932
  var percentEncode = function (chr, set) {
5626
5933
  var code = codeAt(chr, 0);
5627
5934
  // encodeURIComponent does not encode ', which is in the special-query percent-encode set
5628
- return code >= 0x20 && code < 0x7F && !hasOwn$4(set, chr) ? chr : chr === "'" && hasOwn$4(set, chr) ? '%27' : encodeURIComponent(chr);
5935
+ return code >= 0x20 && code < 0x7F && !hasOwn$4(set, chr) ? chr : chr === "'" && hasOwn$4(set, chr) ? '%27' : encodeURIComponent$1(chr);
5629
5936
  };
5630
5937
 
5631
5938
  // https://url.spec.whatwg.org/#special-scheme
@@ -6421,32 +6728,32 @@ if (NativeURL) {
6421
6728
 
6422
6729
  setToStringTag$1(URLConstructor, 'URL');
6423
6730
 
6424
- $$v({ global: true, constructor: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS$7 }, {
6731
+ $$u({ global: true, constructor: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS$7 }, {
6425
6732
  URL: URLConstructor
6426
6733
  });
6427
6734
 
6428
- var $$u = _export;
6735
+ var $$t = _export;
6429
6736
  var call$g = functionCall;
6430
6737
 
6431
6738
  // `URL.prototype.toJSON` method
6432
6739
  // https://url.spec.whatwg.org/#dom-url-tojson
6433
- $$u({ target: 'URL', proto: true, enumerable: true }, {
6740
+ $$t({ target: 'URL', proto: true, enumerable: true }, {
6434
6741
  toJSON: function toJSON() {
6435
6742
  return call$g(URL.prototype.toString, this);
6436
6743
  }
6437
6744
  });
6438
6745
 
6439
6746
  var defineBuiltIn$4 = defineBuiltIn$e;
6440
- var uncurryThis$o = functionUncurryThis;
6441
- var toString$b = toString$j;
6747
+ var uncurryThis$n = functionUncurryThis;
6748
+ var toString$a = toString$j;
6442
6749
  var validateArgumentsLength$1 = validateArgumentsLength$5;
6443
6750
 
6444
6751
  var $URLSearchParams$1 = URLSearchParams;
6445
6752
  var URLSearchParamsPrototype$2 = $URLSearchParams$1.prototype;
6446
- var append = uncurryThis$o(URLSearchParamsPrototype$2.append);
6447
- var $delete = uncurryThis$o(URLSearchParamsPrototype$2['delete']);
6448
- var forEach$3 = uncurryThis$o(URLSearchParamsPrototype$2.forEach);
6449
- var push$2 = uncurryThis$o([].push);
6753
+ var append = uncurryThis$n(URLSearchParamsPrototype$2.append);
6754
+ var $delete = uncurryThis$n(URLSearchParamsPrototype$2['delete']);
6755
+ var forEach$3 = uncurryThis$n(URLSearchParamsPrototype$2.forEach);
6756
+ var push$2 = uncurryThis$n([].push);
6450
6757
  var params$1 = new $URLSearchParams$1('a=1&a=2&b=3');
6451
6758
 
6452
6759
  params$1['delete']('a', 1);
@@ -6464,8 +6771,8 @@ if (params$1 + '' !== 'a=2') {
6464
6771
  push$2(entries, { key: k, value: v });
6465
6772
  });
6466
6773
  validateArgumentsLength$1(length, 1);
6467
- var key = toString$b(name);
6468
- var value = toString$b($value);
6774
+ var key = toString$a(name);
6775
+ var value = toString$a($value);
6469
6776
  var index = 0;
6470
6777
  var entriesLength = entries.length;
6471
6778
  var entry;
@@ -6483,14 +6790,14 @@ if (params$1 + '' !== 'a=2') {
6483
6790
  }
6484
6791
 
6485
6792
  var defineBuiltIn$3 = defineBuiltIn$e;
6486
- var uncurryThis$n = functionUncurryThis;
6487
- var toString$a = toString$j;
6793
+ var uncurryThis$m = functionUncurryThis;
6794
+ var toString$9 = toString$j;
6488
6795
  var validateArgumentsLength = validateArgumentsLength$5;
6489
6796
 
6490
6797
  var $URLSearchParams = URLSearchParams;
6491
6798
  var URLSearchParamsPrototype$1 = $URLSearchParams.prototype;
6492
- var getAll = uncurryThis$n(URLSearchParamsPrototype$1.getAll);
6493
- var $has = uncurryThis$n(URLSearchParamsPrototype$1.has);
6799
+ var getAll = uncurryThis$m(URLSearchParamsPrototype$1.getAll);
6800
+ var $has = uncurryThis$m(URLSearchParamsPrototype$1.has);
6494
6801
  var params = new $URLSearchParams('a=1');
6495
6802
 
6496
6803
  // `undefined` case is a Chromium 117 bug
@@ -6502,7 +6809,7 @@ if (params.has('a', 2) || !params.has('a', undefined)) {
6502
6809
  if (length && $value === undefined) return $has(this, name);
6503
6810
  var values = getAll(this, name); // also validates `this`
6504
6811
  validateArgumentsLength(length, 1);
6505
- var value = toString$a($value);
6812
+ var value = toString$9($value);
6506
6813
  var index = 0;
6507
6814
  while (index < values.length) {
6508
6815
  if (values[index++] === value) return true;
@@ -6511,11 +6818,11 @@ if (params.has('a', 2) || !params.has('a', undefined)) {
6511
6818
  }
6512
6819
 
6513
6820
  var DESCRIPTORS$6 = descriptors;
6514
- var uncurryThis$m = functionUncurryThis;
6821
+ var uncurryThis$l = functionUncurryThis;
6515
6822
  var defineBuiltInAccessor$5 = defineBuiltInAccessor$c;
6516
6823
 
6517
6824
  var URLSearchParamsPrototype = URLSearchParams.prototype;
6518
- var forEach$2 = uncurryThis$m(URLSearchParamsPrototype.forEach);
6825
+ var forEach$2 = uncurryThis$l(URLSearchParamsPrototype.forEach);
6519
6826
 
6520
6827
  // `URLSearchParams.prototype.size` getter
6521
6828
  // https://github.com/whatwg/url/pull/734
@@ -6769,39 +7076,6 @@ const loginWithSso = async environment => {
6769
7076
  };
6770
7077
  const getSsoEnvironmentConfig = getSsoConfig;
6771
7078
 
6772
- var $$t = _export;
6773
- var uncurryThis$l = functionUncurryThisClause;
6774
- var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
6775
- var toLength$5 = toLength$7;
6776
- var toString$9 = toString$j;
6777
- var notARegExp$1 = notARegexp;
6778
- var requireObjectCoercible$5 = requireObjectCoercible$b;
6779
- var correctIsRegExpLogic$1 = correctIsRegexpLogic;
6780
-
6781
- var slice$2 = uncurryThis$l(''.slice);
6782
- var min$4 = Math.min;
6783
-
6784
- var CORRECT_IS_REGEXP_LOGIC$1 = correctIsRegExpLogic$1('endsWith');
6785
- // https://github.com/zloirock/core-js/pull/702
6786
- var MDN_POLYFILL_BUG$1 = !CORRECT_IS_REGEXP_LOGIC$1 && !!function () {
6787
- var descriptor = getOwnPropertyDescriptor$1(String.prototype, 'endsWith');
6788
- return descriptor && !descriptor.writable;
6789
- }();
6790
-
6791
- // `String.prototype.endsWith` method
6792
- // https://tc39.es/ecma262/#sec-string.prototype.endswith
6793
- $$t({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG$1 && !CORRECT_IS_REGEXP_LOGIC$1 }, {
6794
- endsWith: function endsWith(searchString /* , endPosition = @length */) {
6795
- var that = toString$9(requireObjectCoercible$5(this));
6796
- notARegExp$1(searchString);
6797
- var search = toString$9(searchString);
6798
- var endPosition = arguments.length > 1 ? arguments[1] : undefined;
6799
- var len = that.length;
6800
- var end = endPosition === undefined ? len : min$4(toLength$5(endPosition), len);
6801
- return slice$2(that, end - search.length, end) === search;
6802
- }
6803
- });
6804
-
6805
7079
  /******************************************************************************
6806
7080
  Copyright (c) Microsoft Corporation.
6807
7081
 
@@ -6836,123 +7110,25 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
6836
7110
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
6837
7111
  };
6838
7112
 
6839
- //#region src/errors/authorization-server-unavailable.ts
6840
- var AuthorizationServerUnavailable = class extends Error {
6841
- name = "AuthorizationServerUnavailable";
7113
+ //#region src/id-token.ts
7114
+ const decodeClaims = (idToken = "") => {
7115
+ const segments = idToken.split(".");
7116
+ if (segments.length !== 3 || segments.some((segment) => segment === "")) return {};
7117
+ try {
7118
+ return JSON.parse(Buffer.from(segments[1] ?? "", "base64url").toString()) ?? {};
7119
+ } catch {
7120
+ return {};
7121
+ }
6842
7122
  };
6843
-
6844
- //#region src/discovery.ts
6845
- const REQUEST_TIMEOUT_MS$1 = 1e4;
6846
- async function discoverAuthorizationServer(issuer, fetch = globalThis.fetch) {
6847
- const metadata = await readMetadata(`${issuer}/.well-known/oauth-authorization-server`, fetch);
6848
- return {
6849
- tokenEndpoint: metadata.token_endpoint,
6850
- identityProviderIssuer: metadata.vention_identity_provider_issuer,
6851
- clients: metadata.vention_clients
6852
- };
6853
- }
6854
- async function discoverOpenIdProvider(issuer, fetch = globalThis.fetch) {
6855
- const url = `${issuer}/.well-known/openid-configuration`;
6856
- const metadata = await readMetadata(url, fetch);
6857
- if (metadata.issuer !== issuer) throw new AuthorizationServerUnavailable(`${url} names the issuer ${metadata.issuer}, not ${issuer}`);
7123
+ const isValidFor = (claims, { issuer, clientId, now }) => claims.iss === issuer && (Array.isArray(claims.aud) ? claims.aud.includes(clientId) : claims.aud === clientId) && typeof claims.exp === "number" && claims.exp * 1e3 > now();
7124
+ const toOptionalString = (value) => typeof value === "string" ? value : void 0;
7125
+ const readSignedInUser = (idToken, validation) => {
7126
+ const claims = decodeClaims(idToken);
7127
+ if (typeof claims.sub !== "string" || claims.sub === "" || !isValidFor(claims, validation)) throw new Error("The identity provider returned no usable ID token for this client");
6858
7128
  return {
6859
- authorizationEndpoint: metadata.authorization_endpoint,
6860
- tokenEndpoint: metadata.token_endpoint
6861
- };
6862
- }
6863
- async function readMetadata(url, fetch) {
6864
- const response = await fetch(url, {
6865
- headers: { Accept: "application/json" },
6866
- redirect: "error",
6867
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS$1)
6868
- }).catch((error) => {
6869
- throw new AuthorizationServerUnavailable(`Could not reach ${url}`, { cause: error });
6870
- });
6871
- if (!response.ok) throw new AuthorizationServerUnavailable(`${url} answered ${response.status}`);
6872
- return response.json().catch((error) => {
6873
- throw new AuthorizationServerUnavailable(`${url} did not answer with JSON`, { cause: error });
6874
- });
6875
- }
6876
-
6877
- //#region src/errors/exchange-rejected.ts
6878
- var ExchangeRejected = class extends Error {
6879
- code;
6880
- name = "ExchangeRejected";
6881
- constructor(code) {
6882
- super(`The authorization server refused the token exchange (${code})`);
6883
- this.code = code;
6884
- }
6885
- };
6886
-
6887
- //#region src/errors/login-timed-out.ts
6888
- var LoginTimedOut = class extends Error {
6889
- name = "LoginTimedOut";
6890
- constructor() {
6891
- super("Login timed out");
6892
- }
6893
- };
6894
-
6895
- //#region src/oauth2-token-request.ts
6896
- const REQUEST_TIMEOUT_MS = 1e4;
6897
- function exchangeForGatewayToken(tokenEndpoint, subjectToken, fetch, now) {
6898
- return requestToken(tokenEndpoint, subjectToken, "urn:ietf:params:oauth:token-type:access_token", fetch, now);
6899
- }
6900
- async function requestToken(tokenEndpoint, subjectToken, subjectTokenType, fetch, now) {
6901
- const response = await fetch(tokenEndpoint, {
6902
- method: "POST",
6903
- headers: {
6904
- "Content-Type": "application/x-www-form-urlencoded",
6905
- Accept: "application/json"
6906
- },
6907
- body: new URLSearchParams({
6908
- grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
6909
- subject_token: subjectToken,
6910
- subject_token_type: subjectTokenType
6911
- }),
6912
- redirect: "error",
6913
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
6914
- }).catch((error) => {
6915
- throw new AuthorizationServerUnavailable("The authorization server could not be reached", { cause: error });
6916
- });
6917
- if (response.status >= 500 || response.status === 408 || response.status === 429) throw new AuthorizationServerUnavailable(`The authorization server answered ${response.status}`);
6918
- if (!response.ok) {
6919
- const refusal = await response.json().catch(() => void 0);
6920
- throw new ExchangeRejected(refusal?.error ?? `http_${response.status}`);
6921
- }
6922
- return response.json().then((body) => toStoredGatewayToken(body, now())).catch(() => {
6923
- throw new AuthorizationServerUnavailable("The authorization server returned an unusable token response");
6924
- });
6925
- }
6926
- function toStoredGatewayToken({ access_token: token, expires_in: expiresIn }, receivedAt) {
6927
- const payload = (token.split(".")[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
6928
- const claims = JSON.parse(atob(payload));
6929
- return {
6930
- token,
6931
- receivedAt,
6932
- expiresAt: receivedAt + expiresIn * 1e3,
6933
- capExpiresAt: receivedAt + (claims.cap_exp - claims.exp + expiresIn) * 1e3
6934
- };
6935
- }
6936
-
6937
- //#region src/id-token.ts
6938
- const decodeClaims = (idToken = "") => {
6939
- const segments = idToken.split(".");
6940
- if (segments.length !== 3 || segments.some((segment) => segment === "")) return {};
6941
- try {
6942
- return JSON.parse(Buffer.from(segments[1] ?? "", "base64url").toString()) ?? {};
6943
- } catch {
6944
- return {};
6945
- }
6946
- };
6947
- const isValidFor = (claims, { issuer, clientId, now }) => claims.iss === issuer && (Array.isArray(claims.aud) ? claims.aud.includes(clientId) : claims.aud === clientId) && typeof claims.exp === "number" && claims.exp * 1e3 > now();
6948
- const toOptionalString = (value) => typeof value === "string" ? value : void 0;
6949
- const readSignedInUser = (idToken, validation) => {
6950
- const claims = decodeClaims(idToken);
6951
- if (typeof claims.sub !== "string" || claims.sub === "" || !isValidFor(claims, validation)) throw new Error("The identity provider returned no usable ID token for this client");
6952
- return {
6953
- memberId: claims.sub,
6954
- email: toOptionalString(claims.email),
6955
- displayName: toOptionalString(claims.name)
7129
+ memberId: claims.sub,
7130
+ email: toOptionalString(claims.email),
7131
+ displayName: toOptionalString(claims.name)
6956
7132
  };
6957
7133
  };
6958
7134
 
@@ -7028,6 +7204,7 @@ const startCallbackServer = async (expectedState, timeoutMs) => {
7028
7204
  const close = () => {
7029
7205
  clearTimeout(timer);
7030
7206
  callbackServer.close();
7207
+ callbackServer.closeAllConnections();
7031
7208
  };
7032
7209
  const authorizationCodeReceived = new Promise((resolve, reject) => {
7033
7210
  timer = setTimeout(() => {
@@ -7037,7 +7214,7 @@ const startCallbackServer = async (expectedState, timeoutMs) => {
7037
7214
  callbackServer.on("request", (req, res) => {
7038
7215
  const outcome = readCallback(req, res, expectedState);
7039
7216
  if (outcome === void 0) return;
7040
- close();
7217
+ res.once("close", close);
7041
7218
  if ("error" in outcome) reject(outcome.error);
7042
7219
  else resolve(outcome.authorizationCode);
7043
7220
  });
@@ -7068,7 +7245,7 @@ const redeemAuthorizationCode = async (options, authorizationCode, codeVerifier,
7068
7245
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
7069
7246
  body,
7070
7247
  redirect: "error",
7071
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
7248
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS$1)
7072
7249
  }).catch((error) => {
7073
7250
  throw new Error("Could not reach the identity provider", { cause: error });
7074
7251
  });
@@ -7135,22 +7312,9 @@ const PLATFORM_AUTH_ORIGINS = {
7135
7312
  demo: "https://platform-auth.vention.foo",
7136
7313
  prod: "https://platform-auth.vention.com"
7137
7314
  };
7138
- const originSchema = z.url({
7139
- protocol: /^https$/
7140
- }).refine(url => !url.endsWith("/"));
7141
- const originOverride = variableName => {
7142
- const override = process.env[variableName];
7143
- if (!override) {
7144
- return undefined;
7145
- }
7146
- if (!originSchema.safeParse(override).success) {
7147
- throw new Error(`${variableName} must be an https URL without a trailing slash`);
7148
- }
7149
- return override;
7150
- };
7151
7315
  const getPlatformAuthOrigin = environment => {
7152
7316
  var _a;
7153
- return (_a = originOverride("VENTION_CLI_PLATFORM_AUTH_ORIGIN")) !== null && _a !== void 0 ? _a : PLATFORM_AUTH_ORIGINS[environment];
7317
+ return (_a = getOriginOverride("VENTION_CLI_PLATFORM_AUTH_ORIGIN")) !== null && _a !== void 0 ? _a : PLATFORM_AUTH_ORIGINS[environment];
7154
7318
  };
7155
7319
  const gatewayTokenStore = session => ({
7156
7320
  read: async () => {
@@ -7382,44 +7546,23 @@ $$r({ target: 'Iterator', proto: true, real: true, forced: findWithoutClosingOnE
7382
7546
  }
7383
7547
  });
7384
7548
 
7385
- const getDigitalTwinUrl = (environment, sessionId) => {
7386
- switch (environment) {
7387
- case "local":
7388
- return `http://localhost:3101`;
7389
- case "demo":
7390
- return `https://digital-twin.vention.foo/digital-twin/machine-motion/passthrough/${sessionId}/80`;
7391
- case "prod":
7392
- return `https://digital-twin.vention.com/digital-twin/machine-motion/passthrough/${sessionId}/80`;
7393
- default:
7394
- throw new Error("Invalid environment");
7395
- }
7396
- };
7397
- const getAllApplicationsWithSourceCode = async (environment, designId, sessionId) => {
7398
- if (!sessionId) {
7399
- throw new Error("Linked session token is not set");
7400
- }
7401
- const digitalTwinUrl = getDigitalTwinUrl(environment, sessionId);
7402
- const url = `${digitalTwinUrl}/v2/library?shouldIncludeSourceCode=true`;
7403
- const response = await fetchJson(url, {
7404
- headers: {
7405
- Accept: "application/json",
7406
- Cookie: `digital-twin-session-${designId}=s%3A${sessionId}.s`
7407
- }
7549
+ const getAllApplicationsWithSourceCode = async connection => {
7550
+ const response = await fetchJson(`${connection.baseUrl}/v2/library?shouldIncludeSourceCode=true`, {
7551
+ headers: Object.assign({
7552
+ Accept: "application/json"
7553
+ }, connection.headers),
7554
+ fetchImpl: connection.fetch
7408
7555
  });
7409
7556
  return response.applications || [];
7410
7557
  };
7411
- const getLibraryAssets = async (environment, designId, sessionId) => {
7412
- if (!sessionId) {
7413
- throw new Error("Linked session token is not set");
7414
- }
7415
- const digitalTwinUrl = getDigitalTwinUrl(environment, sessionId);
7416
- const url = `${digitalTwinUrl}/v2/library/assets`;
7558
+ const getLibraryAssets = async connection => {
7559
+ const url = `${connection.baseUrl}/v2/library/assets`;
7417
7560
  try {
7418
7561
  const response = await fetchJson(url, {
7419
- headers: {
7420
- Accept: "application/json",
7421
- Cookie: `digital-twin-session-${designId}=s%3A${sessionId}.s`
7422
- }
7562
+ headers: Object.assign({
7563
+ Accept: "application/json"
7564
+ }, connection.headers),
7565
+ fetchImpl: connection.fetch
7423
7566
  });
7424
7567
  return response.assets;
7425
7568
  } catch (error) {
@@ -7429,47 +7572,33 @@ const getLibraryAssets = async (environment, designId, sessionId) => {
7429
7572
  throw error;
7430
7573
  }
7431
7574
  };
7432
- const getMmConfiguration = async (environment, designId, sessionId) => {
7433
- if (!sessionId) {
7434
- throw new Error("Linked session token is not set");
7435
- }
7436
- const digitalTwinUrl = getDigitalTwinUrl(environment, sessionId);
7437
- const url = `${digitalTwinUrl}/v2/mm-configuration`;
7575
+ const getMmConfiguration = async connection => {
7576
+ const url = `${connection.baseUrl}/v2/mm-configuration`;
7438
7577
  const response = await fetchJson(url, {
7439
- headers: {
7440
- Accept: "application/json",
7441
- Cookie: `digital-twin-session-${designId}=s%3A${sessionId}.s`
7442
- }
7578
+ headers: Object.assign({
7579
+ Accept: "application/json"
7580
+ }, connection.headers),
7581
+ fetchImpl: connection.fetch
7443
7582
  });
7444
7583
  return response.mmConfiguration;
7445
7584
  };
7446
- const pushApplicationToDigitalTwin = async (environment, designId, sessionId, application) => {
7447
- if (!sessionId) {
7448
- throw new Error("Linked session token is not set");
7449
- }
7450
- const digitalTwinUrl = getDigitalTwinUrl(environment, sessionId);
7451
- const url = `${digitalTwinUrl}/v1/library`;
7585
+ const pushApplicationToDigitalTwin = async (connection, application) => {
7586
+ const url = `${connection.baseUrl}/v1/library`;
7452
7587
  return await fetchJson(url, {
7453
7588
  method: "PUT",
7454
- headers: {
7589
+ headers: Object.assign({
7455
7590
  "Content-Type": "application/json",
7456
- Accept: "application/json",
7457
- Cookie: `digital-twin-session-${designId}=s%3A${sessionId}.s`
7458
- },
7459
- body: application
7591
+ Accept: "application/json"
7592
+ }, connection.headers),
7593
+ body: application,
7594
+ fetchImpl: connection.fetch
7460
7595
  });
7461
7596
  };
7462
- const getApplicationLogs = async (environment, designId, sessionId, applicationId) => {
7463
- if (!sessionId) {
7464
- throw new Error("Linked session token is not set");
7465
- }
7466
- const digitalTwinUrl = getDigitalTwinUrl(environment, sessionId);
7467
- const url = `${digitalTwinUrl}/v1/application/${applicationId}/logs`;
7468
- const response = await fetchWithUserAgent(url, {
7597
+ const getApplicationLogs = async (connection, applicationId) => {
7598
+ const url = `${connection.baseUrl}/v1/application/${applicationId}/logs`;
7599
+ const response = await connection.fetch(url, {
7469
7600
  method: "GET",
7470
- headers: {
7471
- Cookie: `digital-twin-session-${designId}=s%3A${sessionId}.s`
7472
- }
7601
+ headers: connection.headers
7473
7602
  });
7474
7603
  if (!response.ok) {
7475
7604
  throw new Error("Could not find logs for application");
@@ -7477,60 +7606,6 @@ const getApplicationLogs = async (environment, designId, sessionId, applicationI
7477
7606
  return await response.text();
7478
7607
  };
7479
7608
 
7480
- const getBaseRailsUrl = environment => {
7481
- switch (environment) {
7482
- case "local":
7483
- return "http://localhost:3000";
7484
- case "demo":
7485
- return "https://vention.foo";
7486
- case "prod":
7487
- return "https://vention.com";
7488
- default:
7489
- throw new Error("Invalid environment");
7490
- }
7491
- };
7492
- const getUserAllocations = async session => {
7493
- const baseUrl = getBaseRailsUrl(session.environment);
7494
- const headers = await getAuthHeaders(session);
7495
- const url = `${baseUrl}/api/v3/digital_twin_infrastructure/allocations`;
7496
- return await fetchJson(url, {
7497
- headers
7498
- });
7499
- };
7500
- const getAuthHeaders = async session => {
7501
- var _a;
7502
- const baseUrl = getBaseRailsUrl(session.environment);
7503
- const baseHeaders = {
7504
- Accept: "application/json",
7505
- Origin: baseUrl,
7506
- Referer: `${baseUrl}/`
7507
- };
7508
- if (session.environment === "local") {
7509
- if (!session.ventionSession) {
7510
- throw new Error("Local environment requires vention_session. Please run 'vention login' and provide the cookie value.");
7511
- }
7512
- return Object.assign(Object.assign({}, baseHeaders), {
7513
- Cookie: `vention_session=${session.ventionSession}`
7514
- });
7515
- }
7516
- if (!((_a = session.oauth) === null || _a === void 0 ? void 0 : _a.accessToken)) {
7517
- throw new Error("Not authenticated. Please run 'vention login' to authenticate via SSO.");
7518
- }
7519
- const bufferMs = 5 * 60 * 1000;
7520
- const shouldRefreshToken = session.oauth.expiresAt && Date.now() >= session.oauth.expiresAt - bufferMs;
7521
- if (shouldRefreshToken && session.oauth.refreshToken !== undefined) {
7522
- const ssoConfig = getSsoEnvironmentConfig(session.environment);
7523
- const refreshed = await refreshAccessToken(ssoConfig, session.oauth.refreshToken);
7524
- session.oauth.accessToken = refreshed.accessToken;
7525
- session.oauth.refreshToken = refreshed.refreshToken;
7526
- session.oauth.expiresAt = refreshed.expiresInSeconds ? Date.now() + refreshed.expiresInSeconds * 1000 : session.oauth.expiresAt;
7527
- await saveSession(session);
7528
- }
7529
- return Object.assign(Object.assign({}, baseHeaders), {
7530
- Authorization: `Bearer ${session.oauth.accessToken}`
7531
- });
7532
- };
7533
-
7534
7609
  // eslint-disable-next-line es/no-typed-arrays -- safe
7535
7610
  var arrayBufferBasicDetection = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';
7536
7611
 
@@ -10970,285 +11045,98 @@ const readMachineCodeAppDirectoryInfo = async projectPath => {
10970
11045
  }
10971
11046
  };
10972
11047
 
10973
- const checkIfDesignHasLiveAllocation = async (session, designId) => {
10974
- const allocations = await getUserAllocations(session);
10975
- const linkedAllocation = allocations.find(a => a.designId === designId);
10976
- return linkedAllocation;
10977
- };
10978
- const getAppFromDigitalTwin = async (environment, machineCodeAppDirectoryInfo, sessionId) => {
10979
- console.log(chalk.blue("Fetching all applications with source code from digital twin..."));
10980
- const allApplications = await getAllApplicationsWithSourceCode(environment, machineCodeAppDirectoryInfo.designId, sessionId);
10981
- const targetApp = allApplications.find(app => app.id === machineCodeAppDirectoryInfo.applicationId);
10982
- if (!targetApp) {
10983
- console.log();
10984
- console.error(chalk.red(`Application "${machineCodeAppDirectoryInfo.appName}" (ID: ${machineCodeAppDirectoryInfo.applicationId}) not found in the digital twin.`));
10985
- process.exit(1);
11048
+ const getBaseRailsUrl = environment => {
11049
+ switch (environment) {
11050
+ case "local":
11051
+ return "http://localhost:3000";
11052
+ case "demo":
11053
+ return "https://vention.foo";
11054
+ case "prod":
11055
+ return "https://vention.com";
11056
+ default:
11057
+ throw new Error("Invalid environment");
10986
11058
  }
10987
- return targetApp;
10988
11059
  };
10989
- const getAvailableAppsFromDigitalTwin = async (environment, designId, sessionId) => {
10990
- const allApplications = await getAllApplicationsWithSourceCode(environment, designId, sessionId);
10991
- return allApplications.filter(app => app.type === "machine_code");
11060
+ const getUserAllocations = async session => {
11061
+ const baseUrl = getBaseRailsUrl(session.environment);
11062
+ const headers = await getAuthHeaders(session);
11063
+ const url = `${baseUrl}/api/v3/digital_twin_infrastructure/allocations`;
11064
+ return await fetchJson(url, {
11065
+ headers
11066
+ });
10992
11067
  };
10993
- const createNewAppDirectory = async (session, currentDir) => {
10994
- const {
10995
- selectedDesign,
10996
- selectedApp
10997
- } = await selectDesignAndApp(session);
10998
- if (!selectedApp.sourceCode) {
10999
- console.log();
11000
- console.log(chalk.yellow("No source code found for this application."));
11001
- process.exit(1);
11002
- }
11003
- const appDirectoryExists = await checkIfAppDirectoryExists(selectedApp.name, currentDir);
11004
- const safeFileName = sanitizeFileName(selectedApp.name);
11005
- if (appDirectoryExists) {
11006
- console.log();
11007
- console.error(chalk.red(`You already have a directory with name "${safeFileName}" here.`));
11008
- console.error(chalk.red("If that is the machine code app you are trying to pull, please navigate to the root folder of the app and run the 'vention pull' command from there."));
11009
- console.error(chalk.red("If not, please rename that directory and try again."));
11010
- process.exit(1);
11068
+ const getAuthHeaders = async session => {
11069
+ var _a;
11070
+ const baseUrl = getBaseRailsUrl(session.environment);
11071
+ const baseHeaders = {
11072
+ Accept: "application/json",
11073
+ Origin: baseUrl,
11074
+ Referer: `${baseUrl}/`
11075
+ };
11076
+ if (session.environment === "local") {
11077
+ if (!session.ventionSession) {
11078
+ throw new Error("Local environment requires vention_session. Please run 'vention login' and provide the cookie value.");
11079
+ }
11080
+ return Object.assign(Object.assign({}, baseHeaders), {
11081
+ Cookie: `vention_session=${session.ventionSession}`
11082
+ });
11011
11083
  }
11012
- const appDirectoryPath = await writeApplicationToDisk(selectedApp.name, selectedApp.sourceCode, currentDir);
11013
- const [assets, mmConfiguration] = await Promise.all([getLibraryAssets(session.environment, selectedDesign.id, selectedDesign.sessionId), getMmConfiguration(session.environment, selectedDesign.id, selectedDesign.sessionId)]);
11014
- if (assets !== undefined) {
11015
- await writeReadonlyJsonFile(appDirectoryPath, ".vention-design-scene-assets.json", assets);
11084
+ if (!((_a = session.oauth) === null || _a === void 0 ? void 0 : _a.accessToken)) {
11085
+ throw new Error("Not authenticated. Please run 'vention login' to authenticate via SSO.");
11016
11086
  }
11017
- await writeReadonlyJsonFile(appDirectoryPath, ".vention-design-configuration.json", mmConfiguration);
11018
- await writeMachineCodeAppDirectoryInfo(appDirectoryPath, {
11019
- appName: selectedApp.name,
11020
- designId: selectedDesign.id,
11021
- applicationId: selectedApp.id,
11022
- lastPulledAt: new Date().toISOString(),
11023
- environment: session.environment,
11024
- uuid: selectedApp.uuid
11087
+ const bufferMs = 5 * 60 * 1000;
11088
+ const shouldRefreshToken = session.oauth.expiresAt && Date.now() >= session.oauth.expiresAt - bufferMs;
11089
+ if (shouldRefreshToken && session.oauth.refreshToken !== undefined) {
11090
+ const ssoConfig = getSsoEnvironmentConfig(session.environment);
11091
+ const refreshed = await refreshAccessToken(ssoConfig, session.oauth.refreshToken);
11092
+ session.oauth.accessToken = refreshed.accessToken;
11093
+ session.oauth.refreshToken = refreshed.refreshToken;
11094
+ session.oauth.expiresAt = refreshed.expiresInSeconds ? Date.now() + refreshed.expiresInSeconds * 1000 : session.oauth.expiresAt;
11095
+ await saveSession(session);
11096
+ }
11097
+ return Object.assign(Object.assign({}, baseHeaders), {
11098
+ Authorization: `Bearer ${session.oauth.accessToken}`
11025
11099
  });
11026
- console.log();
11027
- console.log(chalk.green(`✅ Successfully pulled "${selectedApp.name}" to: ${appDirectoryPath}`));
11028
- console.log(chalk.blue(`📁 To navigate to your project, run:`));
11029
- console.log(chalk.cyan(`cd "${safeFileName}"`));
11030
- console.log(chalk.blue("💡 You can now start working on your application!"));
11031
11100
  };
11032
- const updateExistingAppDirectory = async (session, machineCodeAppDirectoryInfo, currentDir) => {
11033
- console.log(chalk.blue(`Found existing project: ${machineCodeAppDirectoryInfo.appName}`));
11034
- console.log(chalk.blue(`Design ID: ${machineCodeAppDirectoryInfo.designId}, App ID: ${machineCodeAppDirectoryInfo.applicationId}`));
11035
- const linkedAllocation = await checkIfDesignHasLiveAllocation(session, machineCodeAppDirectoryInfo.designId);
11036
- if (!linkedAllocation) {
11037
- console.log();
11038
- console.error(chalk.red("Sorry, it seems you do not have that design open with the MachineLogic tab selected."));
11039
- console.error(chalk.red("Please go to your browser, open your design, and navigate to the MachineLogic page."));
11040
- process.exit(1);
11041
- }
11042
- const appWithSourceCode = await getAppFromDigitalTwin(session.environment, machineCodeAppDirectoryInfo, linkedAllocation.sessionId);
11043
- await writeApplicationToDisk(appWithSourceCode.name, appWithSourceCode.sourceCode, currentDir, true);
11044
- const [assets, mmConfiguration] = await Promise.all([getLibraryAssets(session.environment, machineCodeAppDirectoryInfo.designId, linkedAllocation.sessionId), getMmConfiguration(session.environment, machineCodeAppDirectoryInfo.designId, linkedAllocation.sessionId)]);
11045
- if (assets !== undefined) {
11046
- await writeReadonlyJsonFile(currentDir, ".vention-design-scene-assets.json", assets);
11101
+
11102
+ const getDigitalTwinUrl = (environment, sessionId) => {
11103
+ switch (environment) {
11104
+ case "local":
11105
+ return `http://localhost:3101`;
11106
+ case "demo":
11107
+ return `https://digital-twin.vention.foo/digital-twin/machine-motion/passthrough/${sessionId}/80`;
11108
+ case "prod":
11109
+ return `https://digital-twin.vention.com/digital-twin/machine-motion/passthrough/${sessionId}/80`;
11110
+ default:
11111
+ throw new Error("Invalid environment");
11047
11112
  }
11048
- await writeReadonlyJsonFile(currentDir, ".vention-design-configuration.json", mmConfiguration);
11049
- await writeMachineCodeAppDirectoryInfo(currentDir, Object.assign(Object.assign({}, machineCodeAppDirectoryInfo), {
11050
- lastPulledAt: new Date().toISOString()
11051
- }));
11052
- console.log();
11053
- console.log(chalk.green(`✅ Successfully pulled "${appWithSourceCode.name}" to: ${currentDir}`));
11054
- console.log(chalk.blue("💡 Your project has been updated with the latest changes!"));
11055
11113
  };
11056
- const linkDirectory = async (session, currentDir) => {
11057
- const {
11058
- selectedDesign,
11059
- selectedApp
11060
- } = await selectDesignAndApp(session);
11061
- await writeMachineCodeAppDirectoryInfo(currentDir, {
11062
- appName: selectedApp.name,
11063
- designId: selectedDesign.id,
11064
- applicationId: selectedApp.id,
11065
- lastPulledAt: new Date().toISOString(),
11066
- environment: session.environment,
11067
- uuid: selectedApp.uuid
11068
- });
11069
- console.log(chalk.green(`Successfully linked current directory to design "${selectedDesign.name}" (ID: ${selectedDesign.id})`));
11070
- console.log(chalk.green(`Application: "${selectedApp.name}" (ID: ${selectedApp.id})`));
11071
- return {
11072
- selectedDesign,
11073
- selectedApp
11074
- };
11114
+ const rejectMissingSession = async () => {
11115
+ throw new Error("Linked session token is not set");
11075
11116
  };
11076
- const selectDesignAndApp = async session => {
11117
+ const buildConnection$1 = (environment, designId, sessionId) => ({
11118
+ baseUrl: getDigitalTwinUrl(environment, sessionId),
11119
+ headers: {
11120
+ Cookie: `digital-twin-session-${designId}=s%3A${sessionId}.s`
11121
+ },
11122
+ fetch: sessionId ? fetchWithUserAgent : rejectMissingSession
11123
+ });
11124
+ const resolveConnection$1 = async (session, designId) => {
11077
11125
  const allocations = await getUserAllocations(session);
11078
- if (allocations.length === 0) {
11079
- console.log();
11080
- console.log(chalk.yellow("No active allocations found. Please open a design and navigate to the machine logic tab to activate a digital twin."));
11081
- process.exit(1);
11082
- }
11083
- const selectedDesign = await select({
11084
- message: "Select a design:",
11085
- choices: allocations.map(allocation => ({
11086
- name: `${allocation.designName} (ID: ${allocation.designId})`,
11087
- value: {
11088
- id: allocation.designId,
11089
- name: allocation.designName,
11090
- sessionId: allocation.sessionId
11091
- }
11092
- }))
11093
- });
11094
- const availableApps = await getAvailableAppsFromDigitalTwin(session.environment, selectedDesign.id, selectedDesign.sessionId);
11095
- if (availableApps.length === 0) {
11096
- console.log();
11097
- console.log(chalk.yellow("No machine code applications found in the digital twin"));
11098
- process.exit(1);
11126
+ const allocation = allocations.find(candidate => candidate.designId === designId);
11127
+ if (!allocation) {
11128
+ return undefined;
11099
11129
  }
11100
- const selectedApp = await select({
11101
- message: "Select an application:",
11102
- choices: availableApps.map(app => ({
11103
- name: app.name,
11104
- value: app
11105
- }))
11106
- });
11107
- return {
11108
- selectedDesign,
11109
- selectedApp
11110
- };
11130
+ return buildConnection$1(session.environment, designId, allocation.sessionId);
11131
+ };
11132
+ const listDesigns$2 = async session => {
11133
+ const allocations = await getUserAllocations(session);
11134
+ return allocations.map(allocation => ({
11135
+ id: allocation.designId,
11136
+ name: allocation.designName,
11137
+ connection: buildConnection$1(session.environment, allocation.designId, allocation.sessionId)
11138
+ }));
11111
11139
  };
11112
-
11113
- function createLinkCommand() {
11114
- return new Command("link").description("Link current directory to a Vention design application").action(async () => {
11115
- try {
11116
- const session = await loadSession();
11117
- if (!session) {
11118
- console.error(chalk.red("Not logged in. Please run 'vention login' first."));
11119
- process.exit(1);
11120
- }
11121
- const currentDir = process.cwd();
11122
- console.log();
11123
- await linkDirectory(session, currentDir);
11124
- console.log(chalk.blue("You can now use 'vention pull' to download app content or 'vention push' to upload local changes."));
11125
- } catch (error) {
11126
- handleCommandError(error, "Failed to link directory");
11127
- }
11128
- });
11129
- }
11130
-
11131
- function createPushCommand() {
11132
- return new Command("push").description("Push local changes from this directory to the linked digital twin").action(async () => {
11133
- try {
11134
- const session = await loadSession();
11135
- if (!session) {
11136
- console.error(chalk.red("Not logged in. Please run 'vention login' first."));
11137
- process.exit(1);
11138
- }
11139
- const currentDir = process.cwd();
11140
- const machineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
11141
- if (!machineCodeAppDirectoryInfo) {
11142
- console.log();
11143
- console.log(chalk.yellow("This directory is not linked to a Vention application."));
11144
- const shouldLink = await select({
11145
- message: "Would you like to link this directory to an application?",
11146
- choices: [{
11147
- name: "Yes, link this directory",
11148
- value: true
11149
- }, {
11150
- name: "No, cancel push operation",
11151
- value: false
11152
- }]
11153
- });
11154
- if (!shouldLink) {
11155
- console.log(chalk.blue("Push operation cancelled. Run 'vention link' when you're ready to link this directory."));
11156
- process.exit(0);
11157
- }
11158
- await linkDirectory(session, currentDir);
11159
- console.log(chalk.blue("Continuing with push operation..."));
11160
- }
11161
- const updatedMachineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
11162
- if (!updatedMachineCodeAppDirectoryInfo) {
11163
- console.log(chalk.red("Error reading directory metadata after linking."));
11164
- process.exit(1);
11165
- }
11166
- console.log();
11167
- console.log(chalk.blue(`Pushing changes for project: ${updatedMachineCodeAppDirectoryInfo.appName}`));
11168
- console.log(chalk.blue(`Design ID: ${updatedMachineCodeAppDirectoryInfo.designId}, App ID: ${updatedMachineCodeAppDirectoryInfo.applicationId}`));
11169
- const linkedAllocation = await checkIfDesignHasLiveAllocation(session, updatedMachineCodeAppDirectoryInfo.designId);
11170
- if (!linkedAllocation) {
11171
- console.log();
11172
- console.error(chalk.red("Sorry, it seems you do not have that design open with the MachineLogic tab selected."));
11173
- console.error(chalk.red("Please go to your browser, open your design, and navigate to the MachineLogic page."));
11174
- process.exit(1);
11175
- }
11176
- console.log();
11177
- console.log(chalk.blue("Serializing local files..."));
11178
- const ignorePatterns = getDefaultIgnorePatterns();
11179
- const serializedSourceCode = serializeFileSystem(currentDir, ignorePatterns, true);
11180
- const applicationToPush = {
11181
- name: updatedMachineCodeAppDirectoryInfo.appName,
11182
- id: updatedMachineCodeAppDirectoryInfo.applicationId,
11183
- type: "machine_code",
11184
- sourceCode: serializedSourceCode,
11185
- uuid: updatedMachineCodeAppDirectoryInfo.uuid
11186
- };
11187
- console.log(chalk.blue("Pushing to digital twin..."));
11188
- await pushApplicationToDigitalTwin(session.environment, updatedMachineCodeAppDirectoryInfo.designId, linkedAllocation.sessionId, applicationToPush);
11189
- await writeMachineCodeAppDirectoryInfo(currentDir, Object.assign(Object.assign({}, updatedMachineCodeAppDirectoryInfo), {
11190
- lastPushedAt: new Date().toISOString()
11191
- }));
11192
- console.log();
11193
- console.log(chalk.green(`✅ Successfully pushed to digital twin`));
11194
- console.log(chalk.blue("💡 Your changes have been uploaded!"));
11195
- } catch (error) {
11196
- handleCommandError(error, "Failed to push application");
11197
- }
11198
- });
11199
- }
11200
-
11201
- function createPullCommand() {
11202
- return new Command("pull").description("Pull an application from a design to this directory").action(async () => {
11203
- try {
11204
- const session = await loadSession();
11205
- if (!session) {
11206
- console.error(chalk.red("Not logged in. Please run 'vention login' first."));
11207
- process.exit(1);
11208
- }
11209
- const currentDir = process.cwd();
11210
- const machineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
11211
- if (machineCodeAppDirectoryInfo) {
11212
- console.log(chalk.blue(`This directory is linked to app: ${machineCodeAppDirectoryInfo.appName}`));
11213
- console.log(chalk.blue(`Pulling latest content from design ID: ${machineCodeAppDirectoryInfo.designId}`));
11214
- await updateExistingAppDirectory(session, machineCodeAppDirectoryInfo, currentDir);
11215
- } else {
11216
- await createNewAppDirectory(session, currentDir);
11217
- }
11218
- } catch (error) {
11219
- handleCommandError(error, "Failed to pull application");
11220
- }
11221
- });
11222
- }
11223
-
11224
- function createLogsCommand() {
11225
- return new Command("logs").description("Fetch application logs from the linked digital twin").action(async () => {
11226
- try {
11227
- const session = await loadSession();
11228
- if (!session) {
11229
- console.error(chalk.red("Not logged in. Please run 'vention login' first."));
11230
- process.exit(1);
11231
- }
11232
- const currentDir = process.cwd();
11233
- const machineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
11234
- if (!machineCodeAppDirectoryInfo) {
11235
- console.error(chalk.red("This directory is not linked to a Vention application."));
11236
- console.error(chalk.red("Please run 'vention pull' or 'vention link' first."));
11237
- process.exit(1);
11238
- }
11239
- const linkedAllocation = await checkIfDesignHasLiveAllocation(session, machineCodeAppDirectoryInfo.designId);
11240
- if (!linkedAllocation) {
11241
- console.error(chalk.red("Sorry, it seems you do not have that design open with the MachineLogic tab selected."));
11242
- console.error(chalk.red("Please go to your browser, open your design, and navigate to the MachineLogic page."));
11243
- process.exit(1);
11244
- }
11245
- const logs = await getApplicationLogs(session.environment, linkedAllocation.designId, linkedAllocation.sessionId, machineCodeAppDirectoryInfo.applicationId);
11246
- console.log(logs);
11247
- } catch (error) {
11248
- handleCommandError(error, "Failed to fetch application logs");
11249
- }
11250
- });
11251
- }
11252
11140
 
11253
11141
  var $TypeError$1 = TypeError;
11254
11142
  var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
@@ -11531,6 +11419,1172 @@ $$6({ target: 'Iterator', proto: true, real: true, forced: FORCED }, {
11531
11419
  }
11532
11420
  });
11533
11421
 
11422
+ //#region src/generated/core/bodySerializer.gen.ts
11423
+ const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
11424
+
11425
+ //#region src/generated/core/pathSerializer.gen.ts
11426
+ const separatorArrayExplode = (style) => {
11427
+ switch (style) {
11428
+ case "label": return ".";
11429
+ case "matrix": return ";";
11430
+ case "simple": return ",";
11431
+ default: return "&";
11432
+ }
11433
+ };
11434
+ const separatorArrayNoExplode = (style) => {
11435
+ switch (style) {
11436
+ case "form": return ",";
11437
+ case "pipeDelimited": return "|";
11438
+ case "spaceDelimited": return "%20";
11439
+ default: return ",";
11440
+ }
11441
+ };
11442
+ const separatorObjectExplode = (style) => {
11443
+ switch (style) {
11444
+ case "label": return ".";
11445
+ case "matrix": return ";";
11446
+ case "simple": return ",";
11447
+ default: return "&";
11448
+ }
11449
+ };
11450
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
11451
+ if (!explode) {
11452
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
11453
+ switch (style) {
11454
+ case "label": return `.${joinedValues}`;
11455
+ case "matrix": return `;${name}=${joinedValues}`;
11456
+ case "simple": return joinedValues;
11457
+ default: return `${name}=${joinedValues}`;
11458
+ }
11459
+ }
11460
+ const separator = separatorArrayExplode(style);
11461
+ const joinedValues = value.map((v) => {
11462
+ if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
11463
+ return serializePrimitiveParam({
11464
+ allowReserved,
11465
+ name,
11466
+ value: v
11467
+ });
11468
+ }).join(separator);
11469
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
11470
+ };
11471
+ const serializePrimitiveParam = ({ allowReserved, name, value }) => {
11472
+ if (value === void 0 || value === null) return "";
11473
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
11474
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
11475
+ };
11476
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
11477
+ if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
11478
+ if (style !== "deepObject" && !explode) {
11479
+ let values = [];
11480
+ Object.entries(value).forEach(([key, v]) => {
11481
+ values = [
11482
+ ...values,
11483
+ key,
11484
+ allowReserved ? v : encodeURIComponent(v)
11485
+ ];
11486
+ });
11487
+ const joinedValues = values.join(",");
11488
+ switch (style) {
11489
+ case "form": return `${name}=${joinedValues}`;
11490
+ case "label": return `.${joinedValues}`;
11491
+ case "matrix": return `;${name}=${joinedValues}`;
11492
+ default: return joinedValues;
11493
+ }
11494
+ }
11495
+ const separator = separatorObjectExplode(style);
11496
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
11497
+ allowReserved,
11498
+ name: style === "deepObject" ? `${name}[${key}]` : key,
11499
+ value: v
11500
+ })).join(separator);
11501
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
11502
+ };
11503
+
11504
+ //#region src/generated/core/utils.gen.ts
11505
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
11506
+ const defaultPathSerializer = ({ path, url: _url }) => {
11507
+ let url = _url;
11508
+ const matches = _url.match(PATH_PARAM_RE);
11509
+ if (matches) for (const match of matches) {
11510
+ let explode = false;
11511
+ let name = match.substring(1, match.length - 1);
11512
+ let style = "simple";
11513
+ if (name.endsWith("*")) {
11514
+ explode = true;
11515
+ name = name.substring(0, name.length - 1);
11516
+ }
11517
+ if (name.startsWith(".")) {
11518
+ name = name.substring(1);
11519
+ style = "label";
11520
+ } else if (name.startsWith(";")) {
11521
+ name = name.substring(1);
11522
+ style = "matrix";
11523
+ }
11524
+ const value = path[name];
11525
+ if (value === void 0 || value === null) continue;
11526
+ if (Array.isArray(value)) {
11527
+ url = url.replace(match, serializeArrayParam({
11528
+ explode,
11529
+ name,
11530
+ style,
11531
+ value
11532
+ }));
11533
+ continue;
11534
+ }
11535
+ if (typeof value === "object") {
11536
+ url = url.replace(match, serializeObjectParam({
11537
+ explode,
11538
+ name,
11539
+ style,
11540
+ value,
11541
+ valueOnly: true
11542
+ }));
11543
+ continue;
11544
+ }
11545
+ if (style === "matrix") {
11546
+ url = url.replace(match, `;${serializePrimitiveParam({
11547
+ name,
11548
+ value
11549
+ })}`);
11550
+ continue;
11551
+ }
11552
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
11553
+ url = url.replace(match, replaceValue);
11554
+ }
11555
+ return url;
11556
+ };
11557
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
11558
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
11559
+ let url = (baseUrl ?? "") + pathUrl;
11560
+ if (path) url = defaultPathSerializer({
11561
+ path,
11562
+ url
11563
+ });
11564
+ let search = query ? querySerializer(query) : "";
11565
+ if (search.startsWith("?")) search = search.substring(1);
11566
+ if (search) url += `?${search}`;
11567
+ return url;
11568
+ };
11569
+ function getValidRequestBody(options) {
11570
+ const hasBody = options.body !== void 0;
11571
+ if (hasBody && options.bodySerializer) {
11572
+ if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
11573
+ return options.body !== "" ? options.body : null;
11574
+ }
11575
+ if (hasBody) return options.body;
11576
+ }
11577
+
11578
+ //#region src/generated/core/auth.gen.ts
11579
+ const getAuthToken = async (auth, callback) => {
11580
+ const token = typeof callback === "function" ? await callback(auth) : callback;
11581
+ if (!token) return;
11582
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
11583
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
11584
+ return token;
11585
+ };
11586
+
11587
+ //#region src/generated/client/utils.gen.ts
11588
+ const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
11589
+ const querySerializer = (queryParams) => {
11590
+ const search = [];
11591
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
11592
+ const value = queryParams[name];
11593
+ if (value === void 0 || value === null) continue;
11594
+ const options = parameters[name] || args;
11595
+ if (Array.isArray(value)) {
11596
+ const serializedArray = serializeArrayParam({
11597
+ allowReserved: options.allowReserved,
11598
+ explode: true,
11599
+ name,
11600
+ style: "form",
11601
+ value,
11602
+ ...options.array
11603
+ });
11604
+ if (serializedArray) search.push(serializedArray);
11605
+ } else if (typeof value === "object") {
11606
+ const serializedObject = serializeObjectParam({
11607
+ allowReserved: options.allowReserved,
11608
+ explode: true,
11609
+ name,
11610
+ style: "deepObject",
11611
+ value,
11612
+ ...options.object
11613
+ });
11614
+ if (serializedObject) search.push(serializedObject);
11615
+ } else {
11616
+ const serializedPrimitive = serializePrimitiveParam({
11617
+ allowReserved: options.allowReserved,
11618
+ name,
11619
+ value
11620
+ });
11621
+ if (serializedPrimitive) search.push(serializedPrimitive);
11622
+ }
11623
+ }
11624
+ return search.join("&");
11625
+ };
11626
+ return querySerializer;
11627
+ };
11628
+ /**
11629
+ * Infers parseAs value from provided Content-Type header.
11630
+ */
11631
+ const getParseAs = (contentType) => {
11632
+ if (!contentType) return "stream";
11633
+ const cleanContent = contentType.split(";")[0]?.trim();
11634
+ if (!cleanContent) return;
11635
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
11636
+ if (cleanContent === "multipart/form-data") return "formData";
11637
+ if ([
11638
+ "application/",
11639
+ "audio/",
11640
+ "image/",
11641
+ "video/"
11642
+ ].some((type) => cleanContent.startsWith(type))) return "blob";
11643
+ if (cleanContent.startsWith("text/")) return "text";
11644
+ };
11645
+ const checkForExistence = (options, name) => {
11646
+ if (!name) return false;
11647
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
11648
+ return false;
11649
+ };
11650
+ async function setAuthParams(options) {
11651
+ for (const auth of options.security ?? []) {
11652
+ if (checkForExistence(options, auth.name)) continue;
11653
+ const token = await getAuthToken(auth, options.auth);
11654
+ if (!token) continue;
11655
+ const name = auth.name ?? "Authorization";
11656
+ switch (auth.in) {
11657
+ case "query":
11658
+ if (!options.query) options.query = {};
11659
+ options.query[name] = token;
11660
+ break;
11661
+ case "cookie":
11662
+ options.headers.append("Cookie", `${name}=${token}`);
11663
+ break;
11664
+ default: options.headers.set(name, token);
11665
+ }
11666
+ }
11667
+ }
11668
+ const buildUrl = (options) => getUrl({
11669
+ baseUrl: options.baseUrl,
11670
+ path: options.path,
11671
+ query: options.query,
11672
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
11673
+ url: options.url
11674
+ });
11675
+ const mergeConfigs = (a, b) => {
11676
+ const config = {
11677
+ ...a,
11678
+ ...b
11679
+ };
11680
+ if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
11681
+ config.headers = mergeHeaders(a.headers, b.headers);
11682
+ return config;
11683
+ };
11684
+ const headersEntries = (headers) => {
11685
+ const entries = [];
11686
+ headers.forEach((value, key) => {
11687
+ entries.push([key, value]);
11688
+ });
11689
+ return entries;
11690
+ };
11691
+ const mergeHeaders = (...headers) => {
11692
+ const mergedHeaders = new Headers();
11693
+ for (const header of headers) {
11694
+ if (!header) continue;
11695
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
11696
+ for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
11697
+ else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
11698
+ else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
11699
+ }
11700
+ return mergedHeaders;
11701
+ };
11702
+ var Interceptors = class {
11703
+ fns = [];
11704
+ clear() {
11705
+ this.fns = [];
11706
+ }
11707
+ eject(id) {
11708
+ const index = this.getInterceptorIndex(id);
11709
+ if (this.fns[index]) this.fns[index] = null;
11710
+ }
11711
+ exists(id) {
11712
+ const index = this.getInterceptorIndex(id);
11713
+ return Boolean(this.fns[index]);
11714
+ }
11715
+ getInterceptorIndex(id) {
11716
+ if (typeof id === "number") return this.fns[id] ? id : -1;
11717
+ return this.fns.indexOf(id);
11718
+ }
11719
+ update(id, fn) {
11720
+ const index = this.getInterceptorIndex(id);
11721
+ if (this.fns[index]) {
11722
+ this.fns[index] = fn;
11723
+ return id;
11724
+ }
11725
+ return false;
11726
+ }
11727
+ use(fn) {
11728
+ this.fns.push(fn);
11729
+ return this.fns.length - 1;
11730
+ }
11731
+ };
11732
+ const createInterceptors = () => ({
11733
+ error: new Interceptors(),
11734
+ request: new Interceptors(),
11735
+ response: new Interceptors()
11736
+ });
11737
+ const defaultQuerySerializer = createQuerySerializer({
11738
+ allowReserved: false,
11739
+ array: {
11740
+ explode: true,
11741
+ style: "form"
11742
+ },
11743
+ object: {
11744
+ explode: true,
11745
+ style: "deepObject"
11746
+ }
11747
+ });
11748
+ const defaultHeaders = { "Content-Type": "application/json" };
11749
+ const createConfig = (override = {}) => ({
11750
+ ...jsonBodySerializer,
11751
+ headers: defaultHeaders,
11752
+ parseAs: "auto",
11753
+ querySerializer: defaultQuerySerializer,
11754
+ ...override
11755
+ });
11756
+
11757
+ //#region src/generated/core/serverSentEvents.gen.ts
11758
+ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
11759
+ let lastEventId;
11760
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
11761
+ const createStream = async function* () {
11762
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
11763
+ let attempt = 0;
11764
+ const signal = options.signal ?? new AbortController().signal;
11765
+ while (true) {
11766
+ if (signal.aborted) break;
11767
+ attempt++;
11768
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
11769
+ if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
11770
+ try {
11771
+ const requestInit = {
11772
+ redirect: "follow",
11773
+ ...options,
11774
+ body: options.serializedBody,
11775
+ headers,
11776
+ signal
11777
+ };
11778
+ let request = new Request(url, requestInit);
11779
+ if (onRequest) request = await onRequest(url, requestInit);
11780
+ const response = await (options.fetch ?? globalThis.fetch)(request);
11781
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
11782
+ if (!response.body) throw new Error("No body in SSE response");
11783
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
11784
+ let buffer = "";
11785
+ const abortHandler = () => {
11786
+ try {
11787
+ reader.cancel();
11788
+ } catch {}
11789
+ };
11790
+ signal.addEventListener("abort", abortHandler);
11791
+ try {
11792
+ while (true) {
11793
+ const { done, value } = await reader.read();
11794
+ if (done) break;
11795
+ buffer += value;
11796
+ buffer = buffer.replace(/\r\n?/g, "\n");
11797
+ const chunks = buffer.split("\n\n");
11798
+ buffer = chunks.pop() ?? "";
11799
+ for (const chunk of chunks) {
11800
+ const lines = chunk.split("\n");
11801
+ const dataLines = [];
11802
+ let eventName;
11803
+ for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
11804
+ else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
11805
+ else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
11806
+ else if (line.startsWith("retry:")) {
11807
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
11808
+ if (!Number.isNaN(parsed)) retryDelay = parsed;
11809
+ }
11810
+ let data;
11811
+ let parsedJson = false;
11812
+ if (dataLines.length) {
11813
+ const rawData = dataLines.join("\n");
11814
+ try {
11815
+ data = JSON.parse(rawData);
11816
+ parsedJson = true;
11817
+ } catch {
11818
+ data = rawData;
11819
+ }
11820
+ }
11821
+ if (parsedJson) {
11822
+ if (responseValidator) await responseValidator(data);
11823
+ if (responseTransformer) data = await responseTransformer(data);
11824
+ }
11825
+ onSseEvent?.({
11826
+ data,
11827
+ event: eventName,
11828
+ id: lastEventId,
11829
+ retry: retryDelay
11830
+ });
11831
+ if (dataLines.length) yield data;
11832
+ }
11833
+ }
11834
+ } finally {
11835
+ signal.removeEventListener("abort", abortHandler);
11836
+ reader.releaseLock();
11837
+ }
11838
+ break;
11839
+ } catch (error) {
11840
+ onSseError?.(error);
11841
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
11842
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
11843
+ await sleep(backoff);
11844
+ }
11845
+ }
11846
+ };
11847
+ return { stream: createStream() };
11848
+ }
11849
+
11850
+ //#region src/generated/client/client.gen.ts
11851
+ const createClient$1 = (config = {}) => {
11852
+ let _config = mergeConfigs(createConfig(), config);
11853
+ const getConfig = () => ({ ..._config });
11854
+ const setConfig = (config) => {
11855
+ _config = mergeConfigs(_config, config);
11856
+ return getConfig();
11857
+ };
11858
+ const interceptors = createInterceptors();
11859
+ const beforeRequest = async (options) => {
11860
+ const opts = {
11861
+ ..._config,
11862
+ ...options,
11863
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
11864
+ headers: mergeHeaders(_config.headers, options.headers),
11865
+ serializedBody: void 0
11866
+ };
11867
+ if (opts.security) await setAuthParams(opts);
11868
+ if (opts.requestValidator) await opts.requestValidator(opts);
11869
+ if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
11870
+ if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
11871
+ const resolvedOpts = opts;
11872
+ return {
11873
+ opts: resolvedOpts,
11874
+ url: buildUrl(resolvedOpts)
11875
+ };
11876
+ };
11877
+ const request = async (options) => {
11878
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
11879
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
11880
+ let request;
11881
+ let response;
11882
+ try {
11883
+ const { opts, url } = await beforeRequest(options);
11884
+ const requestInit = {
11885
+ redirect: "follow",
11886
+ ...opts,
11887
+ body: getValidRequestBody(opts)
11888
+ };
11889
+ request = new Request(url, requestInit);
11890
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
11891
+ const _fetch = opts.fetch;
11892
+ response = await _fetch(request);
11893
+ for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
11894
+ const result = {
11895
+ request,
11896
+ response
11897
+ };
11898
+ if (response.ok) {
11899
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
11900
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
11901
+ let emptyData;
11902
+ switch (parseAs) {
11903
+ case "arrayBuffer":
11904
+ case "blob":
11905
+ case "text":
11906
+ emptyData = await response[parseAs]();
11907
+ break;
11908
+ case "formData":
11909
+ emptyData = new FormData();
11910
+ break;
11911
+ case "stream":
11912
+ emptyData = response.body;
11913
+ break;
11914
+ default: emptyData = {};
11915
+ }
11916
+ return opts.responseStyle === "data" ? emptyData : {
11917
+ data: emptyData,
11918
+ ...result
11919
+ };
11920
+ }
11921
+ let data;
11922
+ switch (parseAs) {
11923
+ case "arrayBuffer":
11924
+ case "blob":
11925
+ case "formData":
11926
+ case "text":
11927
+ data = await response[parseAs]();
11928
+ break;
11929
+ case "json": {
11930
+ const text = await response.text();
11931
+ data = text ? JSON.parse(text) : {};
11932
+ break;
11933
+ }
11934
+ case "stream": return opts.responseStyle === "data" ? response.body : {
11935
+ data: response.body,
11936
+ ...result
11937
+ };
11938
+ }
11939
+ if (parseAs === "json") {
11940
+ if (opts.responseValidator) await opts.responseValidator(data);
11941
+ if (opts.responseTransformer) data = await opts.responseTransformer(data);
11942
+ }
11943
+ return opts.responseStyle === "data" ? data : {
11944
+ data,
11945
+ ...result
11946
+ };
11947
+ }
11948
+ const textError = await response.text();
11949
+ let jsonError;
11950
+ try {
11951
+ jsonError = JSON.parse(textError);
11952
+ } catch {}
11953
+ throw jsonError ?? textError;
11954
+ } catch (error) {
11955
+ let finalError = error;
11956
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
11957
+ finalError = finalError || {};
11958
+ if (throwOnError) throw finalError;
11959
+ return responseStyle === "data" ? void 0 : {
11960
+ error: finalError,
11961
+ request,
11962
+ response
11963
+ };
11964
+ }
11965
+ };
11966
+ const makeMethodFn = (method) => (options) => request({
11967
+ ...options,
11968
+ method
11969
+ });
11970
+ const makeSseFn = (method) => async (options) => {
11971
+ const { opts, url } = await beforeRequest(options);
11972
+ return createSseClient({
11973
+ ...opts,
11974
+ body: opts.body,
11975
+ method,
11976
+ onRequest: async (url, init) => {
11977
+ let request = new Request(url, init);
11978
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
11979
+ return request;
11980
+ },
11981
+ serializedBody: getValidRequestBody(opts),
11982
+ url
11983
+ });
11984
+ };
11985
+ const _buildUrl = (options) => buildUrl({
11986
+ ..._config,
11987
+ ...options
11988
+ });
11989
+ return {
11990
+ buildUrl: _buildUrl,
11991
+ connect: makeMethodFn("CONNECT"),
11992
+ delete: makeMethodFn("DELETE"),
11993
+ get: makeMethodFn("GET"),
11994
+ getConfig,
11995
+ head: makeMethodFn("HEAD"),
11996
+ interceptors,
11997
+ options: makeMethodFn("OPTIONS"),
11998
+ patch: makeMethodFn("PATCH"),
11999
+ post: makeMethodFn("POST"),
12000
+ put: makeMethodFn("PUT"),
12001
+ request,
12002
+ setConfig,
12003
+ sse: {
12004
+ connect: makeSseFn("CONNECT"),
12005
+ delete: makeSseFn("DELETE"),
12006
+ get: makeSseFn("GET"),
12007
+ head: makeSseFn("HEAD"),
12008
+ options: makeSseFn("OPTIONS"),
12009
+ patch: makeSseFn("PATCH"),
12010
+ post: makeSseFn("POST"),
12011
+ put: makeSseFn("PUT"),
12012
+ trace: makeSseFn("TRACE")
12013
+ },
12014
+ trace: makeMethodFn("TRACE")
12015
+ };
12016
+ };
12017
+
12018
+ //#region src/generated/sdk.gen.ts
12019
+ var HeyApiClient = class {
12020
+ client;
12021
+ constructor(args) {
12022
+ this.client = args.client;
12023
+ }
12024
+ };
12025
+ var HeyApiRegistry = class {
12026
+ defaultKey = "default";
12027
+ instances = /* @__PURE__ */ new Map();
12028
+ get(key) {
12029
+ const instance = this.instances.get(key ?? this.defaultKey);
12030
+ if (!instance) throw new Error(`No SDK client found. Create one with "new DigitalTwinApi()" to fix this error.`);
12031
+ return instance;
12032
+ }
12033
+ set(value, key) {
12034
+ this.instances.set(key ?? this.defaultKey, value);
12035
+ }
12036
+ };
12037
+ var DigitalTwinApi = class DigitalTwinApi extends HeyApiClient {
12038
+ static __registry = new HeyApiRegistry();
12039
+ constructor(args) {
12040
+ super(args);
12041
+ DigitalTwinApi.__registry.set(this, args.key);
12042
+ }
12043
+ /**
12044
+ * List the caller's digital twin instances
12045
+ */
12046
+ listInstances(options) {
12047
+ return (options?.client ?? this.client).get({
12048
+ security: [{
12049
+ in: "cookie",
12050
+ name: "__Host-vention_auth",
12051
+ type: "apiKey"
12052
+ }, {
12053
+ scheme: "bearer",
12054
+ type: "http"
12055
+ }],
12056
+ url: "/api/instances",
12057
+ ...options
12058
+ });
12059
+ }
12060
+ /**
12061
+ * Allocate a digital twin instance
12062
+ */
12063
+ allocate(options) {
12064
+ return (options.client ?? this.client).post({
12065
+ security: [{
12066
+ in: "cookie",
12067
+ name: "__Host-vention_auth",
12068
+ type: "apiKey"
12069
+ }, {
12070
+ scheme: "bearer",
12071
+ type: "http"
12072
+ }],
12073
+ url: "/api/instances",
12074
+ ...options,
12075
+ headers: {
12076
+ "Content-Type": "application/json",
12077
+ ...options.headers
12078
+ }
12079
+ });
12080
+ }
12081
+ /**
12082
+ * Deallocate a digital twin instance
12083
+ */
12084
+ deallocate(options) {
12085
+ return (options.client ?? this.client).delete({
12086
+ security: [{
12087
+ in: "cookie",
12088
+ name: "__Host-vention_auth",
12089
+ type: "apiKey"
12090
+ }, {
12091
+ scheme: "bearer",
12092
+ type: "http"
12093
+ }],
12094
+ url: "/api/instances/{instanceId}",
12095
+ ...options
12096
+ });
12097
+ }
12098
+ /**
12099
+ * Get a single digital twin instance
12100
+ */
12101
+ getInstance(options) {
12102
+ return (options.client ?? this.client).get({
12103
+ security: [{
12104
+ in: "cookie",
12105
+ name: "__Host-vention_auth",
12106
+ type: "apiKey"
12107
+ }, {
12108
+ scheme: "bearer",
12109
+ type: "http"
12110
+ }],
12111
+ url: "/api/instances/{instanceId}",
12112
+ ...options
12113
+ });
12114
+ }
12115
+ /**
12116
+ * List the releases available to instantiate
12117
+ */
12118
+ listReleases(options) {
12119
+ return (options?.client ?? this.client).get({
12120
+ security: [{
12121
+ in: "cookie",
12122
+ name: "__Host-vention_auth",
12123
+ type: "apiKey"
12124
+ }, {
12125
+ scheme: "bearer",
12126
+ type: "http"
12127
+ }],
12128
+ url: "/api/releases",
12129
+ ...options
12130
+ });
12131
+ }
12132
+ /**
12133
+ * Get a release and the container images it ships
12134
+ */
12135
+ getRelease(options) {
12136
+ return (options.client ?? this.client).get({
12137
+ security: [{
12138
+ in: "cookie",
12139
+ name: "__Host-vention_auth",
12140
+ type: "apiKey"
12141
+ }, {
12142
+ scheme: "bearer",
12143
+ type: "http"
12144
+ }],
12145
+ url: "/api/releases/{release}",
12146
+ ...options
12147
+ });
12148
+ }
12149
+ /**
12150
+ * List the release channels available to instantiate from
12151
+ */
12152
+ listChannels(options) {
12153
+ return (options?.client ?? this.client).get({
12154
+ security: [{
12155
+ in: "cookie",
12156
+ name: "__Host-vention_auth",
12157
+ type: "apiKey"
12158
+ }, {
12159
+ scheme: "bearer",
12160
+ type: "http"
12161
+ }],
12162
+ url: "/api/channels",
12163
+ ...options
12164
+ });
12165
+ }
12166
+ };
12167
+
12168
+ //#region src/errors.ts
12169
+ /**
12170
+ * The wait ended without a ready instance. Carries the identifiers a caller needs to log the
12171
+ * failure or deallocate the twin, so none of it has to be dug back out of the response —
12172
+ * `response.statusText` is empty over HTTP/2 and tells a caller nothing.
12173
+ */
12174
+ /** The instance is ready but does not expose the service the caller asked for. */
12175
+ var EndpointNotFoundError = class extends Error {
12176
+ instanceId;
12177
+ endpoint;
12178
+ available;
12179
+ constructor(instanceId, endpoint, available) {
12180
+ super(`Instance ${instanceId} exposed no endpoint named "${endpoint}" — it exposes ${available.length > 0 ? available.join(", ") : "none"}`);
12181
+ this.instanceId = instanceId;
12182
+ this.endpoint = endpoint;
12183
+ this.available = available;
12184
+ this.name = "EndpointNotFoundError";
12185
+ }
12186
+ };
12187
+
12188
+ //#region src/find-endpoint.ts
12189
+ /**
12190
+ * Reads the URL of one of an instance's exposed services.
12191
+ *
12192
+ * @param instance A ready instance. Endpoints are absent until it is.
12193
+ * @param name The service to reach, as the release names it.
12194
+ * @returns The absolute URL serving that service, or an {@link EndpointNotFoundError} naming the services the instance
12195
+ * does expose.
12196
+ */
12197
+ function findEndpoint(instance, name) {
12198
+ const endpoint = instance.endpoints?.find((candidate) => candidate.name === name);
12199
+ if (!endpoint) return {
12200
+ success: false,
12201
+ error: new EndpointNotFoundError(instance.id, name, instance.endpoints?.map((each) => each.name) ?? [])
12202
+ };
12203
+ return {
12204
+ success: true,
12205
+ url: endpoint.url
12206
+ };
12207
+ }
12208
+
12209
+ //#region src/index.ts
12210
+ /**
12211
+ * Auth runs in the wrapped fetch, below the generated code. hey-api's own `auth` option stays
12212
+ * unset: it would turn the cookie scheme into a `Cookie` header browsers drop.
12213
+ */
12214
+ function createDigitalTwinApi({ baseUrl, authStrategy, fetch = globalThis.fetch }) {
12215
+ const client = createClient$1(createConfig({
12216
+ baseUrl,
12217
+ fetch: authStrategy ? withAuthStrategy(authStrategy, fetch) : fetch
12218
+ }));
12219
+ return new DigitalTwinApi({ client });
12220
+ }
12221
+
12222
+ const DIGITAL_TWIN_API_ORIGINS = {
12223
+ demo: "https://twins.vention.foo",
12224
+ prod: "https://twins.vention.com"
12225
+ };
12226
+ const getOrigin = environment => {
12227
+ var _a;
12228
+ return (_a = getOriginOverride("VENTION_CLI_DIGITAL_TWIN_API_ORIGIN")) !== null && _a !== void 0 ? _a : DIGITAL_TWIN_API_ORIGINS[environment];
12229
+ };
12230
+ const createClient = (session, origins) => {
12231
+ const strategy = new BearerStrategy({
12232
+ exchange: oauth2TokenExchange({
12233
+ issuer: origins.auth,
12234
+ store: gatewayTokenStore(session),
12235
+ fetch: fetchWithUserAgent
12236
+ })
12237
+ });
12238
+ return {
12239
+ api: createDigitalTwinApi({
12240
+ baseUrl: origins.api,
12241
+ authStrategy: strategy,
12242
+ fetch: fetchWithUserAgent
12243
+ }),
12244
+ fetch: withAuthStrategy(strategy, fetchWithUserAgent)
12245
+ };
12246
+ };
12247
+ const compareNewestFirst = (left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt);
12248
+ const listReadyInstances = async api => {
12249
+ const {
12250
+ data,
12251
+ error,
12252
+ response
12253
+ } = await api.listInstances();
12254
+ if (data !== undefined) {
12255
+ return data.filter(instance => instance.state === "ready").sort(compareNewestFirst);
12256
+ }
12257
+ if ((response === null || response === void 0 ? void 0 : response.ok) === false) {
12258
+ throw buildApiError(response, typeof error === "object" && error !== null && Object.keys(error).length === 0 ? null : error, response.url);
12259
+ }
12260
+ throw error;
12261
+ };
12262
+ const buildConnection = (engineUrl, fetch) => ({
12263
+ baseUrl: engineUrl,
12264
+ headers: {},
12265
+ fetch
12266
+ });
12267
+ const listDesigns$1 = async (session, origins) => {
12268
+ const {
12269
+ api,
12270
+ fetch
12271
+ } = createClient(session, origins);
12272
+ const instances = await listReadyInstances(api);
12273
+ const newestInstancePerDesign = instances.filter((instance, index) => instances.findIndex(other => other.designId === instance.designId) === index);
12274
+ return newestInstancePerDesign.flatMap(instance => {
12275
+ const engineLookup = findEndpoint(instance, "execution-engine");
12276
+ return engineLookup.success ? [{
12277
+ id: instance.designId,
12278
+ name: instance.designName,
12279
+ connection: buildConnection(engineLookup.url, fetch)
12280
+ }] : [];
12281
+ });
12282
+ };
12283
+ const resolveConnection = async (session, origins, designId) => {
12284
+ var _a;
12285
+ const designs = await listDesigns$1(session, origins);
12286
+ return (_a = designs.find(design => design.id === designId)) === null || _a === void 0 ? void 0 : _a.connection;
12287
+ };
12288
+
12289
+ const findDigitalTwinApiOrigins = session => {
12290
+ if (!isDigitalTwinV3Enabled(session)) {
12291
+ return undefined;
12292
+ }
12293
+ const auth = getPlatformAuthOrigin(session.environment);
12294
+ const api = getOrigin(session.environment);
12295
+ if (!auth || !api) {
12296
+ verboseLog(`${DIGITAL_TWIN_V3.key} is on but ${session.environment} has no digital twin API configured, using the Rails API path`);
12297
+ return undefined;
12298
+ }
12299
+ return {
12300
+ auth,
12301
+ api
12302
+ };
12303
+ };
12304
+ const resolveDigitalTwinConnection = async (session, designId) => {
12305
+ const origins = findDigitalTwinApiOrigins(session);
12306
+ return origins ? resolveConnection(session, origins, designId) : resolveConnection$1(session, designId);
12307
+ };
12308
+ const listDesigns = async session => {
12309
+ const origins = findDigitalTwinApiOrigins(session);
12310
+ return origins ? listDesigns$1(session, origins) : listDesigns$2(session);
12311
+ };
12312
+
12313
+ const getAppFromDigitalTwin = async (connection, machineCodeAppDirectoryInfo) => {
12314
+ console.log(chalk.blue("Fetching all applications with source code from digital twin..."));
12315
+ const allApplications = await getAllApplicationsWithSourceCode(connection);
12316
+ const targetApp = allApplications.find(app => app.id === machineCodeAppDirectoryInfo.applicationId);
12317
+ if (!targetApp) {
12318
+ console.log();
12319
+ console.error(chalk.red(`Application "${machineCodeAppDirectoryInfo.appName}" (ID: ${machineCodeAppDirectoryInfo.applicationId}) not found in the digital twin.`));
12320
+ process.exit(1);
12321
+ }
12322
+ return targetApp;
12323
+ };
12324
+ const getAvailableAppsFromDigitalTwin = async connection => {
12325
+ const allApplications = await getAllApplicationsWithSourceCode(connection);
12326
+ return allApplications.filter(app => app.type === "machine_code");
12327
+ };
12328
+ const createNewAppDirectory = async (session, currentDir) => {
12329
+ const {
12330
+ selectedDesign,
12331
+ selectedApp
12332
+ } = await selectDesignAndApp(session);
12333
+ if (!selectedApp.sourceCode) {
12334
+ console.log();
12335
+ console.log(chalk.yellow("No source code found for this application."));
12336
+ process.exit(1);
12337
+ }
12338
+ const appDirectoryExists = await checkIfAppDirectoryExists(selectedApp.name, currentDir);
12339
+ const safeFileName = sanitizeFileName(selectedApp.name);
12340
+ if (appDirectoryExists) {
12341
+ console.log();
12342
+ console.error(chalk.red(`You already have a directory with name "${safeFileName}" here.`));
12343
+ console.error(chalk.red("If that is the machine code app you are trying to pull, please navigate to the root folder of the app and run the 'vention pull' command from there."));
12344
+ console.error(chalk.red("If not, please rename that directory and try again."));
12345
+ process.exit(1);
12346
+ }
12347
+ const appDirectoryPath = await writeApplicationToDisk(selectedApp.name, selectedApp.sourceCode, currentDir);
12348
+ const [assets, mmConfiguration] = await Promise.all([getLibraryAssets(selectedDesign.connection), getMmConfiguration(selectedDesign.connection)]);
12349
+ if (assets !== undefined) {
12350
+ await writeReadonlyJsonFile(appDirectoryPath, ".vention-design-scene-assets.json", assets);
12351
+ }
12352
+ await writeReadonlyJsonFile(appDirectoryPath, ".vention-design-configuration.json", mmConfiguration);
12353
+ await writeMachineCodeAppDirectoryInfo(appDirectoryPath, {
12354
+ appName: selectedApp.name,
12355
+ designId: selectedDesign.id,
12356
+ applicationId: selectedApp.id,
12357
+ lastPulledAt: new Date().toISOString(),
12358
+ environment: session.environment,
12359
+ uuid: selectedApp.uuid
12360
+ });
12361
+ console.log();
12362
+ console.log(chalk.green(`✅ Successfully pulled "${selectedApp.name}" to: ${appDirectoryPath}`));
12363
+ console.log(chalk.blue(`📁 To navigate to your project, run:`));
12364
+ console.log(chalk.cyan(`cd "${safeFileName}"`));
12365
+ console.log(chalk.blue("💡 You can now start working on your application!"));
12366
+ };
12367
+ const updateExistingAppDirectory = async (session, machineCodeAppDirectoryInfo, currentDir) => {
12368
+ console.log(chalk.blue(`Found existing project: ${machineCodeAppDirectoryInfo.appName}`));
12369
+ console.log(chalk.blue(`Design ID: ${machineCodeAppDirectoryInfo.designId}, App ID: ${machineCodeAppDirectoryInfo.applicationId}`));
12370
+ const connection = await resolveDigitalTwinConnection(session, machineCodeAppDirectoryInfo.designId);
12371
+ if (!connection) {
12372
+ console.log();
12373
+ console.error(chalk.red("Sorry, it seems you do not have that design open with the MachineLogic tab selected."));
12374
+ console.error(chalk.red("Please go to your browser, open your design, and navigate to the MachineLogic page."));
12375
+ process.exit(1);
12376
+ }
12377
+ const appWithSourceCode = await getAppFromDigitalTwin(connection, machineCodeAppDirectoryInfo);
12378
+ await writeApplicationToDisk(appWithSourceCode.name, appWithSourceCode.sourceCode, currentDir, true);
12379
+ const [assets, mmConfiguration] = await Promise.all([getLibraryAssets(connection), getMmConfiguration(connection)]);
12380
+ if (assets !== undefined) {
12381
+ await writeReadonlyJsonFile(currentDir, ".vention-design-scene-assets.json", assets);
12382
+ }
12383
+ await writeReadonlyJsonFile(currentDir, ".vention-design-configuration.json", mmConfiguration);
12384
+ await writeMachineCodeAppDirectoryInfo(currentDir, Object.assign(Object.assign({}, machineCodeAppDirectoryInfo), {
12385
+ lastPulledAt: new Date().toISOString()
12386
+ }));
12387
+ console.log();
12388
+ console.log(chalk.green(`✅ Successfully pulled "${appWithSourceCode.name}" to: ${currentDir}`));
12389
+ console.log(chalk.blue("💡 Your project has been updated with the latest changes!"));
12390
+ };
12391
+ const linkDirectory = async (session, currentDir) => {
12392
+ const {
12393
+ selectedDesign,
12394
+ selectedApp
12395
+ } = await selectDesignAndApp(session);
12396
+ await writeMachineCodeAppDirectoryInfo(currentDir, {
12397
+ appName: selectedApp.name,
12398
+ designId: selectedDesign.id,
12399
+ applicationId: selectedApp.id,
12400
+ lastPulledAt: new Date().toISOString(),
12401
+ environment: session.environment,
12402
+ uuid: selectedApp.uuid
12403
+ });
12404
+ console.log(chalk.green(`Successfully linked current directory to design "${selectedDesign.name}" (ID: ${selectedDesign.id})`));
12405
+ console.log(chalk.green(`Application: "${selectedApp.name}" (ID: ${selectedApp.id})`));
12406
+ return {
12407
+ selectedDesign,
12408
+ selectedApp
12409
+ };
12410
+ };
12411
+ const selectDesignAndApp = async session => {
12412
+ const designs = await listDesigns(session);
12413
+ if (designs.length === 0) {
12414
+ console.log();
12415
+ console.log(chalk.yellow("No active allocations found. Please open a design and navigate to the machine logic tab to activate a digital twin."));
12416
+ process.exit(1);
12417
+ }
12418
+ const selectedDesign = await select({
12419
+ message: "Select a design:",
12420
+ choices: designs.map(design => ({
12421
+ name: `${design.name} (ID: ${design.id})`,
12422
+ value: design
12423
+ }))
12424
+ });
12425
+ const availableApps = await getAvailableAppsFromDigitalTwin(selectedDesign.connection);
12426
+ if (availableApps.length === 0) {
12427
+ console.log();
12428
+ console.log(chalk.yellow("No machine code applications found in the digital twin"));
12429
+ process.exit(1);
12430
+ }
12431
+ const selectedApp = await select({
12432
+ message: "Select an application:",
12433
+ choices: availableApps.map(app => ({
12434
+ name: app.name,
12435
+ value: app
12436
+ }))
12437
+ });
12438
+ return {
12439
+ selectedDesign,
12440
+ selectedApp
12441
+ };
12442
+ };
12443
+
12444
+ function createLinkCommand() {
12445
+ return new Command("link").description("Link current directory to a Vention design application").action(async () => {
12446
+ try {
12447
+ const session = await loadSession();
12448
+ if (!session) {
12449
+ console.error(chalk.red("Not logged in. Please run 'vention login' first."));
12450
+ process.exit(1);
12451
+ }
12452
+ const currentDir = process.cwd();
12453
+ console.log();
12454
+ await linkDirectory(session, currentDir);
12455
+ console.log(chalk.blue("You can now use 'vention pull' to download app content or 'vention push' to upload local changes."));
12456
+ } catch (error) {
12457
+ handleCommandError(error, "Failed to link directory");
12458
+ }
12459
+ });
12460
+ }
12461
+
12462
+ function createPushCommand() {
12463
+ return new Command("push").description("Push local changes from this directory to the linked digital twin").action(async () => {
12464
+ try {
12465
+ const session = await loadSession();
12466
+ if (!session) {
12467
+ console.error(chalk.red("Not logged in. Please run 'vention login' first."));
12468
+ process.exit(1);
12469
+ }
12470
+ const currentDir = process.cwd();
12471
+ const machineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
12472
+ let linkedConnection;
12473
+ if (!machineCodeAppDirectoryInfo) {
12474
+ console.log();
12475
+ console.log(chalk.yellow("This directory is not linked to a Vention application."));
12476
+ const shouldLink = await select({
12477
+ message: "Would you like to link this directory to an application?",
12478
+ choices: [{
12479
+ name: "Yes, link this directory",
12480
+ value: true
12481
+ }, {
12482
+ name: "No, cancel push operation",
12483
+ value: false
12484
+ }]
12485
+ });
12486
+ if (!shouldLink) {
12487
+ console.log(chalk.blue("Push operation cancelled. Run 'vention link' when you're ready to link this directory."));
12488
+ process.exit(0);
12489
+ }
12490
+ const {
12491
+ selectedDesign
12492
+ } = await linkDirectory(session, currentDir);
12493
+ linkedConnection = selectedDesign.connection;
12494
+ console.log(chalk.blue("Continuing with push operation..."));
12495
+ }
12496
+ const updatedMachineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
12497
+ if (!updatedMachineCodeAppDirectoryInfo) {
12498
+ console.log(chalk.red("Error reading directory metadata after linking."));
12499
+ process.exit(1);
12500
+ }
12501
+ console.log();
12502
+ console.log(chalk.blue(`Pushing changes for project: ${updatedMachineCodeAppDirectoryInfo.appName}`));
12503
+ console.log(chalk.blue(`Design ID: ${updatedMachineCodeAppDirectoryInfo.designId}, App ID: ${updatedMachineCodeAppDirectoryInfo.applicationId}`));
12504
+ const connection = linkedConnection !== null && linkedConnection !== void 0 ? linkedConnection : await resolveDigitalTwinConnection(session, updatedMachineCodeAppDirectoryInfo.designId);
12505
+ if (!connection) {
12506
+ console.log();
12507
+ console.error(chalk.red("Sorry, it seems you do not have that design open with the MachineLogic tab selected."));
12508
+ console.error(chalk.red("Please go to your browser, open your design, and navigate to the MachineLogic page."));
12509
+ process.exit(1);
12510
+ }
12511
+ console.log();
12512
+ console.log(chalk.blue("Serializing local files..."));
12513
+ const ignorePatterns = getDefaultIgnorePatterns();
12514
+ const serializedSourceCode = serializeFileSystem(currentDir, ignorePatterns, true);
12515
+ const applicationToPush = {
12516
+ name: updatedMachineCodeAppDirectoryInfo.appName,
12517
+ id: updatedMachineCodeAppDirectoryInfo.applicationId,
12518
+ type: "machine_code",
12519
+ sourceCode: serializedSourceCode,
12520
+ uuid: updatedMachineCodeAppDirectoryInfo.uuid
12521
+ };
12522
+ console.log(chalk.blue("Pushing to digital twin..."));
12523
+ await pushApplicationToDigitalTwin(connection, applicationToPush);
12524
+ await writeMachineCodeAppDirectoryInfo(currentDir, Object.assign(Object.assign({}, updatedMachineCodeAppDirectoryInfo), {
12525
+ lastPushedAt: new Date().toISOString()
12526
+ }));
12527
+ console.log();
12528
+ console.log(chalk.green(`✅ Successfully pushed to digital twin`));
12529
+ console.log(chalk.blue("💡 Your changes have been uploaded!"));
12530
+ } catch (error) {
12531
+ handleCommandError(error, "Failed to push application");
12532
+ }
12533
+ });
12534
+ }
12535
+
12536
+ function createPullCommand() {
12537
+ return new Command("pull").description("Pull an application from a design to this directory").action(async () => {
12538
+ try {
12539
+ const session = await loadSession();
12540
+ if (!session) {
12541
+ console.error(chalk.red("Not logged in. Please run 'vention login' first."));
12542
+ process.exit(1);
12543
+ }
12544
+ const currentDir = process.cwd();
12545
+ const machineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
12546
+ if (machineCodeAppDirectoryInfo) {
12547
+ console.log(chalk.blue(`This directory is linked to app: ${machineCodeAppDirectoryInfo.appName}`));
12548
+ console.log(chalk.blue(`Pulling latest content from design ID: ${machineCodeAppDirectoryInfo.designId}`));
12549
+ await updateExistingAppDirectory(session, machineCodeAppDirectoryInfo, currentDir);
12550
+ } else {
12551
+ await createNewAppDirectory(session, currentDir);
12552
+ }
12553
+ } catch (error) {
12554
+ handleCommandError(error, "Failed to pull application");
12555
+ }
12556
+ });
12557
+ }
12558
+
12559
+ function createLogsCommand() {
12560
+ return new Command("logs").description("Fetch application logs from the linked digital twin").action(async () => {
12561
+ try {
12562
+ const session = await loadSession();
12563
+ if (!session) {
12564
+ console.error(chalk.red("Not logged in. Please run 'vention login' first."));
12565
+ process.exit(1);
12566
+ }
12567
+ const currentDir = process.cwd();
12568
+ const machineCodeAppDirectoryInfo = await readMachineCodeAppDirectoryInfo(currentDir);
12569
+ if (!machineCodeAppDirectoryInfo) {
12570
+ console.error(chalk.red("This directory is not linked to a Vention application."));
12571
+ console.error(chalk.red("Please run 'vention pull' or 'vention link' first."));
12572
+ process.exit(1);
12573
+ }
12574
+ const connection = await resolveDigitalTwinConnection(session, machineCodeAppDirectoryInfo.designId);
12575
+ if (!connection) {
12576
+ console.error(chalk.red("Sorry, it seems you do not have that design open with the MachineLogic tab selected."));
12577
+ console.error(chalk.red("Please go to your browser, open your design, and navigate to the MachineLogic page."));
12578
+ process.exit(1);
12579
+ }
12580
+ const logs = await getApplicationLogs(connection, machineCodeAppDirectoryInfo.applicationId);
12581
+ console.log(logs);
12582
+ } catch (error) {
12583
+ handleCommandError(error, "Failed to fetch application logs");
12584
+ }
12585
+ });
12586
+ }
12587
+
11534
12588
  var $$5 = _export;
11535
12589
  var call = functionCall;
11536
12590
  var iterate = iterate$8;