@fireproof/core 0.20.0-dev-preview-54 → 0.20.0-dev-preview-57

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/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/ledger.ts
8
- import { BuildURI as BuildURI2, KeyedResolvOnce as KeyedResolvOnce6, ResolveOnce as ResolveOnce7, URI as URI13 } from "@adviser/cement";
8
+ import { BuildURI as BuildURI2, KeyedResolvOnce as KeyedResolvOnce5, ResolveOnce as ResolveOnce7, URI as URI13 } from "@adviser/cement";
9
9
 
10
10
  // src/utils.ts
11
11
  import {
@@ -2113,6 +2113,9 @@ var DatabaseImpl = class {
2113
2113
  const result = await this.ledger.writeQueue.push({ id, del: true });
2114
2114
  return { id, clock: result?.head, name: this.name };
2115
2115
  }
2116
+ async remove(id) {
2117
+ return this.del(id);
2118
+ }
2116
2119
  async changes(since = [], opts = {}) {
2117
2120
  await this.ready();
2118
2121
  this.logger.Debug().Any("since", since).Any("opts", opts).Msg("changes");
@@ -2179,6 +2182,7 @@ __export(blockstore_exports, {
2179
2182
  MetaActiveStore: () => MetaActiveStore,
2180
2183
  PassThroughGateway: () => PassThroughGateway,
2181
2184
  TaskManager: () => TaskManager,
2185
+ URIInterceptor: () => URIInterceptor,
2182
2186
  WALActiveStore: () => WALActiveStore,
2183
2187
  createAttachedStores: () => createAttachedStores,
2184
2188
  createDbMetaEvent: () => createDbMetaEvent,
@@ -2186,7 +2190,7 @@ __export(blockstore_exports, {
2186
2190
  ensureStoreEnDeFile: () => ensureStoreEnDeFile,
2187
2191
  getDefaultURI: () => getDefaultURI,
2188
2192
  getGatewayFactoryItem: () => getGatewayFactoryItem,
2189
- getStartedGateway: () => getStartedGateway,
2193
+ getInterceptableGateway: () => getInterceptableGateway,
2190
2194
  parseCarFile: () => parseCarFile,
2191
2195
  registerStoreProtocol: () => registerStoreProtocol,
2192
2196
  toCIDBlock: () => toCIDBlock,
@@ -2246,10 +2250,10 @@ var WALActiveStore = class extends BaseActiveStore {
2246
2250
  };
2247
2251
 
2248
2252
  // src/blockstore/store-factory.ts
2249
- import { KeyedResolvOnce as KeyedResolvOnce5, Result as Result11 } from "@adviser/cement";
2253
+ import { Result as Result11 } from "@adviser/cement";
2250
2254
 
2251
2255
  // src/blockstore/store.ts
2252
- import { exception2Result as exception2Result4, ResolveOnce as ResolveOnce4, Result as Result10 } from "@adviser/cement";
2256
+ import { exception2Result as exception2Result4, ResolveOnce as ResolveOnce4, Result as Result9 } from "@adviser/cement";
2253
2257
 
2254
2258
  // src/blockstore/loader.ts
2255
2259
  import pLimit from "p-limit";
@@ -3579,151 +3583,11 @@ import { EventBlock as EventBlock2 } from "@fireproof/vendor/@web3-storage/pail/
3579
3583
  import { format as format2 } from "@ipld/dag-json";
3580
3584
  import pRetry from "p-retry";
3581
3585
  import pMap from "p-map";
3582
-
3583
- // src/blockstore/interceptor-gateway.ts
3584
- import { Result as Result9 } from "@adviser/cement";
3585
- var PassThroughGateway = class {
3586
- async buildUrl(ctx, url, key) {
3587
- const op = { url, key };
3588
- return Result9.Ok({ op });
3589
- }
3590
- async start(ctx, url) {
3591
- const op = { url };
3592
- return Result9.Ok({ op });
3593
- }
3594
- async close(ctx, url) {
3595
- const op = { url };
3596
- return Result9.Ok({ op });
3597
- }
3598
- async delete(ctx, url) {
3599
- const op = { url };
3600
- return Result9.Ok({ op });
3601
- }
3602
- async destroy(ctx, url) {
3603
- const op = { url };
3604
- return Result9.Ok({ op });
3605
- }
3606
- async put(ctx, url, body) {
3607
- const op = { url, body };
3608
- return Result9.Ok({ op });
3609
- }
3610
- async get(ctx, url) {
3611
- const op = { url };
3612
- return Result9.Ok({ op });
3613
- }
3614
- async subscribe(ctx, url, callback) {
3615
- const op = { url, callback };
3616
- return Result9.Ok({ op });
3617
- }
3618
- };
3619
- var passThrougthGateway = new PassThroughGateway();
3620
- var InterceptorGateway = class {
3621
- constructor(sthis, innerGW, interceptor) {
3622
- this.innerGW = innerGW;
3623
- this.interceptor = interceptor || passThrougthGateway;
3624
- }
3625
- async buildUrl(ctx, baseUrl, key) {
3626
- const rret = await this.interceptor.buildUrl(ctx, baseUrl, key);
3627
- if (rret.isErr()) {
3628
- return Result9.Err(rret.Err());
3629
- }
3630
- const ret = rret.unwrap();
3631
- if (ret.stop && ret.value) {
3632
- return ret.value;
3633
- }
3634
- return this.innerGW.buildUrl(ctx, ret.op.url, ret.op.key);
3635
- }
3636
- async destroy(ctx, iurl) {
3637
- const rret = await this.interceptor.destroy(ctx, iurl);
3638
- if (rret.isErr()) {
3639
- return Result9.Err(rret.Err());
3640
- }
3641
- const ret = rret.unwrap();
3642
- if (ret.stop && ret.value) {
3643
- return ret.value;
3644
- }
3645
- return this.innerGW.destroy(ctx, ret.op.url);
3646
- }
3647
- async start(ctx, url) {
3648
- const rret = await this.interceptor.start(ctx, url);
3649
- if (rret.isErr()) {
3650
- return Result9.Err(rret.Err());
3651
- }
3652
- const ret = rret.unwrap();
3653
- if (ret.stop && ret.value) {
3654
- return ret.value;
3655
- }
3656
- return await this.innerGW.start(ctx, ret.op.url);
3657
- }
3658
- async close(ctx, url) {
3659
- const rret = await this.interceptor.close(ctx, url);
3660
- if (rret.isErr()) {
3661
- return Result9.Err(rret.Err());
3662
- }
3663
- const ret = rret.unwrap();
3664
- if (ret.stop && ret.value) {
3665
- return ret.value;
3666
- }
3667
- return await this.innerGW.close(ctx, ret.op.url);
3668
- }
3669
- async put(ctx, url, fpEnv) {
3670
- const rret = await this.interceptor.put(ctx, url, fpEnv);
3671
- if (rret.isErr()) {
3672
- return Result9.Err(rret.Err());
3673
- }
3674
- const ret = rret.unwrap();
3675
- if (ret.stop && ret.value) {
3676
- return ret.value;
3677
- }
3678
- return this.innerGW.put(ctx, ret.op.url, ret.op.body);
3679
- }
3680
- async get(ctx, url) {
3681
- const rret = await this.interceptor.get(ctx, url);
3682
- if (rret.isErr()) {
3683
- return Result9.Err(rret.Err());
3684
- }
3685
- const ret = rret.unwrap();
3686
- if (ret.stop && ret.value) {
3687
- return ret.value;
3688
- }
3689
- return this.innerGW.get(ctx, ret.op.url);
3690
- }
3691
- async subscribe(ctx, url, callback) {
3692
- if (!this.innerGW.subscribe) {
3693
- return Result9.Err(ctx.loader.sthis.logger.Error().Url(url).Msg("subscribe not supported").AsError());
3694
- }
3695
- const rret = await this.interceptor.subscribe(ctx, url, callback);
3696
- if (rret.isErr()) {
3697
- return Result9.Err(rret.Err());
3698
- }
3699
- const ret = rret.unwrap();
3700
- if (ret.stop && ret.value) {
3701
- return ret.value;
3702
- }
3703
- return this.innerGW.subscribe(ctx, ret.op.url, ret.op.callback);
3704
- }
3705
- async delete(ctx, url) {
3706
- const rret = await this.interceptor.delete(ctx, url);
3707
- if (rret.isErr()) {
3708
- return Result9.Err(rret.Err());
3709
- }
3710
- const ret = rret.unwrap();
3711
- if (ret.stop && ret.value) {
3712
- return ret.value;
3713
- }
3714
- return this.innerGW.delete(ctx, url);
3715
- }
3716
- async getPlain(ctx, url, key) {
3717
- return this.innerGW.getPlain(ctx, url, key);
3718
- }
3719
- };
3720
-
3721
- // src/blockstore/store.ts
3722
3586
  function guardVersion(url) {
3723
3587
  if (!url.hasParam("version")) {
3724
- return Result10.Err(`missing version: ${url.toString()}`);
3588
+ return Result9.Err(`missing version: ${url.toString()}`);
3725
3589
  }
3726
- return Result10.Ok(url);
3590
+ return Result9.Ok(url);
3727
3591
  }
3728
3592
  var BaseStoreImpl = class {
3729
3593
  // readonly loader: Loadable;
@@ -3739,8 +3603,10 @@ var BaseStoreImpl = class {
3739
3603
  throw logger.Error().Url(this._url).Msg("missing name").AsError();
3740
3604
  }
3741
3605
  this.logger = logger.With().Str("this", this.sthis.nextId().str).Ref("url", () => this._url.toString()).Logger();
3742
- this.realGateway = opts.gateway;
3743
- this.gateway = new InterceptorGateway(this.sthis, opts.gateway, opts.gatewayInterceptor);
3606
+ this.gateway = opts.gateway;
3607
+ }
3608
+ get realGateway() {
3609
+ return this.gateway.innerGW;
3744
3610
  }
3745
3611
  url() {
3746
3612
  return this._url;
@@ -3890,7 +3756,7 @@ var MetaStoreImpl = class extends BaseStoreImpl {
3890
3756
  async close() {
3891
3757
  await this.gateway.close({ loader: this.loader }, this.url());
3892
3758
  this._onClosed.forEach((fn) => fn());
3893
- return Result10.Ok(void 0);
3759
+ return Result9.Ok(void 0);
3894
3760
  }
3895
3761
  async destroy() {
3896
3762
  this.logger.Debug().Msg("destroy");
@@ -3957,7 +3823,7 @@ var DataStoreImpl = class extends BaseStoreImpl {
3957
3823
  async close() {
3958
3824
  await this.gateway.close({ loader: this.loader }, this.url());
3959
3825
  this._onClosed.forEach((fn) => fn());
3960
- return Result10.Ok(void 0);
3826
+ return Result9.Ok(void 0);
3961
3827
  }
3962
3828
  destroy() {
3963
3829
  this.logger.Debug().Msg("destroy");
@@ -4044,7 +3910,7 @@ var WALStoreImpl = class extends BaseStoreImpl {
4044
3910
  const retryableUpload = (fn, description) => pRetry(fn, {
4045
3911
  retries: 5,
4046
3912
  onFailedAttempt: (error) => {
4047
- this.logger.Warn().Msg(`Attempt ${error.attemptNumber} failed for ${description}. There are ${error.retriesLeft} retries left.`);
3913
+ this.logger.Warn().Any("error", error).Any("fn", fn.toString()).Msg(`Attempt ${error.attemptNumber} failed for ${description}. There are ${error.retriesLeft} retries left.`);
4048
3914
  }
4049
3915
  });
4050
3916
  try {
@@ -4159,7 +4025,7 @@ var WALStoreImpl = class extends BaseStoreImpl {
4159
4025
  async close() {
4160
4026
  await this.gateway.close({ loader: this.loader }, this.url());
4161
4027
  this._onClosed.forEach((fn) => fn());
4162
- return Result10.Ok(void 0);
4028
+ return Result9.Ok(void 0);
4163
4029
  }
4164
4030
  destroy() {
4165
4031
  this.logger.Debug().Msg("destroy");
@@ -4167,81 +4033,200 @@ var WALStoreImpl = class extends BaseStoreImpl {
4167
4033
  }
4168
4034
  };
4169
4035
 
4170
- // src/blockstore/store-factory.ts
4171
- var onceGateway = new KeyedResolvOnce5();
4172
- var gatewayInstances = new KeyedResolvOnce5();
4173
- async function getStartedGateway(ctx, url) {
4174
- return onceGateway.get(url.toString()).once(async () => {
4175
- const item = getGatewayFactoryItem(url.protocol);
4176
- if (item) {
4177
- const ret = {
4178
- url,
4179
- ...await gatewayInstances.get(url.protocol).once(async () => ({
4180
- gateway: await item.serdegateway(ctx.loader.sthis)
4181
- }))
4182
- };
4183
- const res = await ret.gateway.start(ctx, url);
4184
- if (res.isErr()) {
4185
- return Result11.Err(ctx.loader.sthis.logger.Error().Result("start", res).Msg("start failed").AsError());
4186
- }
4187
- ret.url = res.Ok();
4188
- return Result11.Ok(ret);
4036
+ // src/blockstore/interceptor-gateway.ts
4037
+ import { Result as Result10 } from "@adviser/cement";
4038
+ var PassThroughGateway = class {
4039
+ async buildUrl(ctx, url, key) {
4040
+ const op = { url, key };
4041
+ return Result10.Ok({ op });
4042
+ }
4043
+ async start(ctx, url) {
4044
+ const op = { url };
4045
+ return Result10.Ok({ op });
4046
+ }
4047
+ async close(ctx, url) {
4048
+ const op = { url };
4049
+ return Result10.Ok({ op });
4050
+ }
4051
+ async delete(ctx, url) {
4052
+ const op = { url };
4053
+ return Result10.Ok({ op });
4054
+ }
4055
+ async destroy(ctx, url) {
4056
+ const op = { url };
4057
+ return Result10.Ok({ op });
4058
+ }
4059
+ async put(ctx, url, body) {
4060
+ const op = { url, body };
4061
+ return Result10.Ok({ op });
4062
+ }
4063
+ async get(ctx, url) {
4064
+ const op = { url };
4065
+ return Result10.Ok({ op });
4066
+ }
4067
+ async subscribe(ctx, url, callback) {
4068
+ const op = { url, callback };
4069
+ return Result10.Ok({ op });
4070
+ }
4071
+ };
4072
+ var passThrougthGateway = new PassThroughGateway();
4073
+ var InterceptorGateway = class {
4074
+ constructor(sthis, innerGW, interceptor) {
4075
+ this.innerGW = innerGW;
4076
+ this.interceptor = interceptor || passThrougthGateway;
4077
+ }
4078
+ async buildUrl(ctx, baseUrl, key) {
4079
+ const rret = await this.interceptor.buildUrl(ctx, baseUrl, key);
4080
+ if (rret.isErr()) {
4081
+ return Result10.Err(rret.Err());
4189
4082
  }
4190
- return Result11.Err(ctx.loader.sthis.logger.Warn().Url(url).Msg("unsupported protocol").AsError());
4191
- });
4083
+ const ret = rret.unwrap();
4084
+ if (ret.stop && ret.value) {
4085
+ return ret.value;
4086
+ }
4087
+ return this.innerGW.buildUrl(ctx, ret.op.url, ret.op.key);
4088
+ }
4089
+ async destroy(ctx, iurl) {
4090
+ const rret = await this.interceptor.destroy(ctx, iurl);
4091
+ if (rret.isErr()) {
4092
+ return Result10.Err(rret.Err());
4093
+ }
4094
+ const ret = rret.unwrap();
4095
+ if (ret.stop && ret.value) {
4096
+ return ret.value;
4097
+ }
4098
+ return this.innerGW.destroy(ctx, ret.op.url);
4099
+ }
4100
+ async start(ctx, url) {
4101
+ const rret = await this.interceptor.start(ctx, url);
4102
+ if (rret.isErr()) {
4103
+ return Result10.Err(rret.Err());
4104
+ }
4105
+ const ret = rret.unwrap();
4106
+ if (ret.stop && ret.value) {
4107
+ return ret.value;
4108
+ }
4109
+ return await this.innerGW.start(ctx, ret.op.url);
4110
+ }
4111
+ async close(ctx, url) {
4112
+ const rret = await this.interceptor.close(ctx, url);
4113
+ if (rret.isErr()) {
4114
+ return Result10.Err(rret.Err());
4115
+ }
4116
+ const ret = rret.unwrap();
4117
+ if (ret.stop && ret.value) {
4118
+ return ret.value;
4119
+ }
4120
+ return await this.innerGW.close(ctx, ret.op.url);
4121
+ }
4122
+ async put(ctx, url, fpEnv) {
4123
+ const rret = await this.interceptor.put(ctx, url, fpEnv);
4124
+ if (rret.isErr()) {
4125
+ return Result10.Err(rret.Err());
4126
+ }
4127
+ const ret = rret.unwrap();
4128
+ if (ret.stop && ret.value) {
4129
+ return ret.value;
4130
+ }
4131
+ return this.innerGW.put(ctx, ret.op.url, ret.op.body);
4132
+ }
4133
+ async get(ctx, url) {
4134
+ const rret = await this.interceptor.get(ctx, url);
4135
+ if (rret.isErr()) {
4136
+ return Result10.Err(rret.Err());
4137
+ }
4138
+ const ret = rret.unwrap();
4139
+ if (ret.stop && ret.value) {
4140
+ return ret.value;
4141
+ }
4142
+ return this.innerGW.get(ctx, ret.op.url);
4143
+ }
4144
+ async subscribe(ctx, url, callback) {
4145
+ if (!this.innerGW.subscribe) {
4146
+ return Result10.Err(ctx.loader.sthis.logger.Error().Url(url).Msg("subscribe not supported").AsError());
4147
+ }
4148
+ const rret = await this.interceptor.subscribe(ctx, url, callback);
4149
+ if (rret.isErr()) {
4150
+ return Result10.Err(rret.Err());
4151
+ }
4152
+ const ret = rret.unwrap();
4153
+ if (ret.stop && ret.value) {
4154
+ return ret.value;
4155
+ }
4156
+ return this.innerGW.subscribe(ctx, ret.op.url, ret.op.callback);
4157
+ }
4158
+ async delete(ctx, url) {
4159
+ const rret = await this.interceptor.delete(ctx, url);
4160
+ if (rret.isErr()) {
4161
+ return Result10.Err(rret.Err());
4162
+ }
4163
+ const ret = rret.unwrap();
4164
+ if (ret.stop && ret.value) {
4165
+ return ret.value;
4166
+ }
4167
+ return this.innerGW.delete(ctx, url);
4168
+ }
4169
+ async getPlain(ctx, url, key) {
4170
+ return this.innerGW.getPlain(ctx, url, key);
4171
+ }
4172
+ };
4173
+
4174
+ // src/blockstore/store-factory.ts
4175
+ async function getInterceptableGateway(ctx, url, opt) {
4176
+ const item = getGatewayFactoryItem(url.protocol);
4177
+ if (item) {
4178
+ return Result11.Ok(new InterceptorGateway(ctx.loader.sthis, await item.serdegateway(ctx.loader.sthis), opt.gatewayInterceptor));
4179
+ }
4180
+ return Result11.Err(ctx.loader.sthis.logger.Warn().Url(url).Msg("unsupported protocol").AsError());
4192
4181
  }
4193
4182
  async function carStoreFactory(ctx, uai) {
4194
4183
  const storeUrl = uai.url.build().setParam(PARAM.STORE, "car").URI();
4195
- const rgateway = await getStartedGateway(ctx, storeUrl);
4184
+ const rgateway = await getInterceptableGateway(ctx, storeUrl, uai);
4196
4185
  if (rgateway.isErr()) {
4197
4186
  throw ctx.loader.sthis.logger.Error().Result("err", rgateway).Url(uai.url).Msg("notfound").AsError();
4198
4187
  }
4199
4188
  const gateway = rgateway.Ok();
4200
- const store = new CarStoreImpl(ctx.loader.sthis, gateway.url, {
4201
- gateway: gateway.gateway,
4202
- gatewayInterceptor: uai.gatewayInterceptor,
4189
+ const store = new CarStoreImpl(ctx.loader.sthis, uai.url, {
4190
+ gateway,
4203
4191
  loader: ctx.loader
4204
4192
  });
4205
4193
  return store;
4206
4194
  }
4207
4195
  async function fileStoreFactory(ctx, uai) {
4208
4196
  const storeUrl = uai.url.build().setParam(PARAM.STORE, "file").URI();
4209
- const rgateway = await getStartedGateway(ctx, storeUrl);
4197
+ const rgateway = await getInterceptableGateway(ctx, storeUrl, uai);
4210
4198
  if (rgateway.isErr()) {
4211
4199
  throw ctx.loader.sthis.logger.Error().Result("err", rgateway).Url(uai.url).Msg("notfound").AsError();
4212
4200
  }
4213
4201
  const gateway = rgateway.Ok();
4214
- const store = new FileStoreImpl(ctx.loader.sthis, gateway.url, {
4215
- gateway: gateway.gateway,
4216
- gatewayInterceptor: uai.gatewayInterceptor,
4202
+ const store = new FileStoreImpl(ctx.loader.sthis, uai.url, {
4203
+ gateway,
4217
4204
  loader: ctx.loader
4218
4205
  });
4219
4206
  return store;
4220
4207
  }
4221
4208
  async function metaStoreFactory(ctx, uai) {
4222
4209
  const storeUrl = uai.url.build().setParam(PARAM.STORE, "meta").URI();
4223
- const rgateway = await getStartedGateway(ctx, storeUrl);
4210
+ const rgateway = await getInterceptableGateway(ctx, storeUrl, uai);
4224
4211
  if (rgateway.isErr()) {
4225
4212
  throw ctx.loader.sthis.logger.Error().Result("err", rgateway).Url(uai.url).Msg("notfound").AsError();
4226
4213
  }
4227
4214
  const gateway = rgateway.Ok();
4228
- const store = new MetaStoreImpl(ctx.loader.sthis, gateway.url, {
4229
- gateway: gateway.gateway,
4230
- gatewayInterceptor: uai.gatewayInterceptor,
4215
+ const store = new MetaStoreImpl(ctx.loader.sthis, uai.url, {
4216
+ gateway,
4231
4217
  loader: ctx.loader
4232
4218
  });
4233
4219
  return store;
4234
4220
  }
4235
4221
  async function WALStoreFactory(ctx, uai) {
4236
4222
  const storeUrl = uai.url.build().setParam(PARAM.STORE, "wal").URI();
4237
- const rgateway = await getStartedGateway(ctx, storeUrl);
4223
+ const rgateway = await getInterceptableGateway(ctx, storeUrl, uai);
4238
4224
  if (rgateway.isErr()) {
4239
4225
  throw ctx.loader.sthis.logger.Error().Result("err", rgateway).Url(uai.url).Msg("notfound").AsError();
4240
4226
  }
4241
4227
  const gateway = rgateway.Ok();
4242
- const store = new WALStoreImpl(ctx.loader.sthis, gateway.url, {
4243
- gateway: gateway.gateway,
4244
- gatewayInterceptor: uai.gatewayInterceptor,
4228
+ const store = new WALStoreImpl(ctx.loader.sthis, uai.url, {
4229
+ gateway,
4245
4230
  loader: ctx.loader
4246
4231
  });
4247
4232
  return store;
@@ -4289,11 +4274,62 @@ function toStoreRuntime(sthis, endeOpts = {}) {
4289
4274
  };
4290
4275
  }
4291
4276
 
4292
- // src/crdt-helpers.ts
4293
- import { parse as parse2 } from "multiformats/link";
4294
- import { sha256 as hasher6 } from "multiformats/hashes/sha2";
4295
- import * as codec2 from "@ipld/dag-cbor";
4296
- import { put, get, entries, root } from "@fireproof/vendor/@web3-storage/pail/crdt";
4277
+ // src/blockstore/uri-interceptor.ts
4278
+ var URIInterceptor = class _URIInterceptor extends PassThroughGateway {
4279
+ static withMapper(mapper) {
4280
+ return new _URIInterceptor().addMapper(mapper);
4281
+ }
4282
+ #uriMapper = /* @__PURE__ */ new Set();
4283
+ addMapper(mapper) {
4284
+ this.#uriMapper.add(mapper);
4285
+ return this;
4286
+ }
4287
+ async #map(uri) {
4288
+ let ret = uri;
4289
+ for (const mapper of this.#uriMapper) {
4290
+ ret = await mapper(ret);
4291
+ }
4292
+ return ret;
4293
+ }
4294
+ async buildUrl(ctx, url, key) {
4295
+ const ret = await super.buildUrl(ctx, await this.#map(url), key);
4296
+ return ret;
4297
+ }
4298
+ async start(ctx, url) {
4299
+ const ret = await super.start(ctx, await this.#map(url));
4300
+ return ret;
4301
+ }
4302
+ async close(ctx, url) {
4303
+ const ret = await super.close(ctx, await this.#map(url));
4304
+ return ret;
4305
+ }
4306
+ async delete(ctx, url) {
4307
+ const ret = await super.delete(ctx, await this.#map(url));
4308
+ return ret;
4309
+ }
4310
+ async destroy(ctx, url) {
4311
+ const ret = await super.destroy(ctx, await this.#map(url));
4312
+ return ret;
4313
+ }
4314
+ async put(ctx, url, body) {
4315
+ const ret = await super.put(ctx, await this.#map(url), body);
4316
+ return ret;
4317
+ }
4318
+ async get(ctx, url) {
4319
+ const ret = await super.get(ctx, await this.#map(url));
4320
+ return ret;
4321
+ }
4322
+ async subscribe(ctx, url, callback) {
4323
+ const ret = await super.subscribe(ctx, await this.#map(url), callback);
4324
+ return ret;
4325
+ }
4326
+ };
4327
+
4328
+ // src/crdt-helpers.ts
4329
+ import { parse as parse2 } from "multiformats/link";
4330
+ import { sha256 as hasher6 } from "multiformats/hashes/sha2";
4331
+ import * as codec2 from "@ipld/dag-cbor";
4332
+ import { put, get, entries, root } from "@fireproof/vendor/@web3-storage/pail/crdt";
4297
4333
  import { EventFetcher, vis } from "@fireproof/vendor/@web3-storage/pail/clock";
4298
4334
  import * as Batch from "@fireproof/vendor/@web3-storage/pail/crdt/batch";
4299
4335
  function time(tag) {
@@ -4942,7 +4978,7 @@ var Context = class {
4942
4978
  };
4943
4979
 
4944
4980
  // src/ledger.ts
4945
- var ledgers = new KeyedResolvOnce6();
4981
+ var ledgers = new KeyedResolvOnce5();
4946
4982
  function keyConfigOpts(sthis, name, opts) {
4947
4983
  return JSON.stringify(
4948
4984
  toSortedArray({
@@ -5173,11 +5209,18 @@ function fireproof(name, opts) {
5173
5209
  // src/runtime/index.ts
5174
5210
  var runtime_exports = {};
5175
5211
  __export(runtime_exports, {
5212
+ AddKeyToDbMetaGateway: () => AddKeyToDbMetaGateway,
5176
5213
  FILESTORE_VERSION: () => FILESTORE_VERSION,
5177
5214
  INDEXEDDB_VERSION: () => INDEXEDDB_VERSION,
5178
5215
  KeyBag: () => KeyBag,
5216
+ V2SerializedMetaKeyExtractKey: () => V2SerializedMetaKeyExtractKey,
5217
+ addKeyToDbMetaDecoder: () => addKeyToDbMetaDecoder,
5218
+ addKeyToDbMetaEncoder: () => addKeyToDbMetaEncoder,
5219
+ decodeAsToSerializedMeta: () => decodeAsToSerializedMeta,
5179
5220
  defaultKeyBagOpts: () => defaultKeyBagOpts,
5180
5221
  defaultKeyBagUrl: () => defaultKeyBagUrl,
5222
+ encodeAsV1SerializedMetaKey: () => encodeAsV1SerializedMetaKey,
5223
+ encodeAsV2SerializedMetaKey: () => encodeAsV2SerializedMetaKey,
5181
5224
  files: () => files_exports,
5182
5225
  getFileName: () => getFileName,
5183
5226
  getKeyBag: () => getKeyBag,
@@ -5188,7 +5231,8 @@ __export(runtime_exports, {
5188
5231
  keysByFingerprint: () => keysByFingerprint,
5189
5232
  mf: () => wait_pr_multiformats_exports,
5190
5233
  registerKeyBagProviderFactory: () => registerKeyBagProviderFactory,
5191
- runtimeFn: () => runtimeFn4,
5234
+ runtimeFn: () => runtimeFn5,
5235
+ sts: () => sts_service_exports,
5192
5236
  toKeyWithFingerPrint: () => toKeyWithFingerPrint
5193
5237
  });
5194
5238
 
@@ -5202,13 +5246,109 @@ __export(wait_pr_multiformats_exports, {
5202
5246
  // src/runtime/wait-pr-multiformats/codec-interface.ts
5203
5247
  var codec_interface_exports = {};
5204
5248
 
5249
+ // src/runtime/sts-service/index.ts
5250
+ var sts_service_exports = {};
5251
+ __export(sts_service_exports, {
5252
+ SessionTokenService: () => SessionTokenService,
5253
+ env2jwk: () => env2jwk,
5254
+ envKeyDefaults: () => envKeyDefaults,
5255
+ jwk2env: () => jwk2env
5256
+ });
5257
+ import { exception2Result as exception2Result5 } from "@adviser/cement";
5258
+ import { exportJWK, importJWK, jwtVerify, SignJWT } from "jose";
5259
+ import { generateKeyPair } from "jose/key/generate/keypair";
5260
+ import { base58btc as base58btc4 } from "multiformats/bases/base58";
5261
+ var envKeyDefaults = {
5262
+ SECRET: "CLOUD_SESSION_TOKEN_SECRET",
5263
+ PUBLIC: "CLOUD_SESSION_TOKEN_PUBLIC"
5264
+ };
5265
+ async function jwk2env(jwk, sthis = ensureSuperThis()) {
5266
+ const inPubKey = await exportJWK(jwk);
5267
+ return base58btc4.encode(sthis.txt.encode(JSON.stringify(inPubKey)));
5268
+ }
5269
+ async function env2jwk(env, alg, sthis = ensureSuperThis()) {
5270
+ const inJWT = JSON.parse(sthis.txt.decode(base58btc4.decode(env)));
5271
+ return importJWK(inJWT, alg, { extractable: true });
5272
+ }
5273
+ var SessionTokenService = class _SessionTokenService {
5274
+ #key;
5275
+ #param;
5276
+ static async generateKeyPair(alg = "ES256", options = { extractable: true }, generateKeyPairFN = (alg2, options2) => generateKeyPair(alg2, options2)) {
5277
+ const material = await generateKeyPairFN(alg, options);
5278
+ return {
5279
+ material,
5280
+ strings: {
5281
+ publicKey: await jwk2env(material.publicKey),
5282
+ privateKey: await jwk2env(material.privateKey)
5283
+ }
5284
+ };
5285
+ }
5286
+ static async createFromEnv(sp = {}, sthis = ensureSuperThis()) {
5287
+ let envToken = sthis.env.get(sp.privateEnvKey ?? envKeyDefaults.SECRET);
5288
+ if (!envToken) {
5289
+ envToken = sthis.env.get(sp.publicEnvKey ?? envKeyDefaults.PUBLIC);
5290
+ }
5291
+ if (!envToken) {
5292
+ throw new Error(
5293
+ `env not found for: ${sp.privateEnvKey ?? envKeyDefaults.SECRET} or ${sp.publicEnvKey ?? envKeyDefaults.PUBLIC}`
5294
+ );
5295
+ }
5296
+ return _SessionTokenService.create({ token: envToken }, sthis);
5297
+ }
5298
+ static async create(stsparam, sthis = ensureSuperThis()) {
5299
+ const key = await env2jwk(stsparam.token, stsparam.alg ?? "ES256", sthis);
5300
+ return new _SessionTokenService(key, stsparam);
5301
+ }
5302
+ constructor(key, stsparam) {
5303
+ this.#key = key;
5304
+ this.#param = stsparam;
5305
+ }
5306
+ get validFor() {
5307
+ let validFor = this.#param.validFor ?? 3600;
5308
+ if (!(0 <= validFor && validFor <= 36e5)) {
5309
+ validFor = 36e5;
5310
+ }
5311
+ return validFor;
5312
+ }
5313
+ get alg() {
5314
+ return this.#param.alg ?? "ES256";
5315
+ }
5316
+ get isssuer() {
5317
+ return this.#param.issuer ?? "fireproof";
5318
+ }
5319
+ get audience() {
5320
+ return this.#param.audience ?? "fireproof";
5321
+ }
5322
+ async validate(token) {
5323
+ return exception2Result5(async () => {
5324
+ const ret = await jwtVerify(token, this.#key);
5325
+ return ret;
5326
+ });
5327
+ }
5328
+ // async getEnvKey(): Promise<string> {
5329
+ // return jwk2env(ensureSuperThis(), this.#key);
5330
+ // }
5331
+ async tokenFor(p) {
5332
+ if (this.#key.type !== "private") {
5333
+ throw new Error("key must be private");
5334
+ }
5335
+ const token = await new SignJWT({
5336
+ userId: p.userId,
5337
+ tenants: p.tenants,
5338
+ ledgers: p.ledgers
5339
+ }).setProtectedHeader({ alg: this.alg }).setIssuedAt().setIssuer(p.issuer ?? this.isssuer).setAudience(p.audience ?? this.audience).setExpirationTime(Date.now() + (p.validFor ?? this.validFor)).sign(this.#key);
5340
+ return token;
5341
+ }
5342
+ };
5343
+
5205
5344
  // src/runtime/index.ts
5206
- import { runtimeFn as runtimeFn4 } from "@adviser/cement";
5345
+ import { runtimeFn as runtimeFn5 } from "@adviser/cement";
5207
5346
 
5208
5347
  // src/runtime/gateways/index.ts
5209
5348
  var gateways_exports = {};
5210
5349
  __export(gateways_exports, {
5211
5350
  DefSerdeGateway: () => DefSerdeGateway,
5351
+ cloud: () => gateway_exports2,
5212
5352
  dbMetaEvent2Serialized: () => dbMetaEvent2Serialized,
5213
5353
  decode2DbMetaEvents: () => decode2DbMetaEvents,
5214
5354
  file: () => file_exports,
@@ -5224,9 +5364,1838 @@ __export(file_exports, {
5224
5364
  sysFileSystemFactory: () => sysFileSystemFactory
5225
5365
  });
5226
5366
 
5367
+ // src/runtime/gateways/cloud/gateway.ts
5368
+ var gateway_exports2 = {};
5369
+ __export(gateway_exports2, {
5370
+ FireproofCloudGateway: () => FireproofCloudGateway,
5371
+ registerFireproofCloudStoreProtocol: () => registerFireproofCloudStoreProtocol,
5372
+ toCloud: () => toCloud
5373
+ });
5374
+ import {
5375
+ Result as Result17,
5376
+ URI as URI17,
5377
+ KeyedResolvOnce as KeyedResolvOnce6,
5378
+ exception2Result as exception2Result9,
5379
+ param,
5380
+ ResolveOnce as ResolveOnce8,
5381
+ to_uint8
5382
+ } from "@adviser/cement";
5383
+
5384
+ // src/protocols/cloud/msg-types.ts
5385
+ var VERSION = "FP-MSG-1.0";
5386
+ function isAuthTypeFPCloudJWK(a) {
5387
+ return a.type === "fp-cloud-jwk";
5388
+ }
5389
+ function isAuthTypeFPCloud(a) {
5390
+ return a.type === "fp-cloud";
5391
+ }
5392
+ function keyTenantLedger(t) {
5393
+ return `${t.tenant}:${t.ledger}`;
5394
+ }
5395
+ function qsidEqual(a, b) {
5396
+ return a.reqId === b.reqId && a.resId === b.resId;
5397
+ }
5398
+ function qsidKey(qsid) {
5399
+ return `${qsid.reqId}:${qsid.resId}`;
5400
+ }
5401
+ function MsgIsTid(msg, tid) {
5402
+ return msg.tid === tid;
5403
+ }
5404
+ function MsgIsError(rq) {
5405
+ return rq.type === "error";
5406
+ }
5407
+ function MsgIsQSError(rq) {
5408
+ return rq.res.type === "error" || rq.req.type === "error";
5409
+ }
5410
+ function coerceFPStoreTypes(s) {
5411
+ const x = s?.trim();
5412
+ if (x === "meta" || x === "car" || x === "wal" || x === "file") {
5413
+ return x;
5414
+ }
5415
+ throw new Error(`Invalid FPStoreTypes: ${s}`);
5416
+ }
5417
+ function isProtocolCapabilities(s) {
5418
+ const x = s.trim();
5419
+ return x === "reqRes" || x === "stream";
5420
+ }
5421
+ function defaultGestalt(msgP, gestalt) {
5422
+ return {
5423
+ storeTypes: ["meta", "file", "car", "wal"],
5424
+ httpEndpoints: ["/fp"],
5425
+ wsEndpoints: ["/ws"],
5426
+ encodings: ["JSON"],
5427
+ protocolCapabilities: msgP.protocolCapabilities || ["reqRes", "stream"],
5428
+ auth: [],
5429
+ requiresAuth: false,
5430
+ data: msgP.hasPersistent ? {
5431
+ inband: true,
5432
+ outband: true
5433
+ } : void 0,
5434
+ meta: msgP.hasPersistent ? {
5435
+ inband: true,
5436
+ outband: true
5437
+ } : void 0,
5438
+ wal: msgP.hasPersistent ? {
5439
+ inband: true,
5440
+ outband: true
5441
+ } : void 0,
5442
+ reqTypes: [
5443
+ "reqOpen",
5444
+ "reqGestalt",
5445
+ // "reqSignedUrl",
5446
+ "reqSubscribeMeta",
5447
+ "reqPutMeta",
5448
+ "reqBindMeta",
5449
+ "reqDelMeta",
5450
+ "reqPutData",
5451
+ "reqGetData",
5452
+ "reqDelData",
5453
+ "reqPutWAL",
5454
+ "reqGetWAL",
5455
+ "reqDelWAL",
5456
+ "reqUpdateMeta"
5457
+ ],
5458
+ resTypes: [
5459
+ "resOpen",
5460
+ "resGestalt",
5461
+ // "resSignedUrl",
5462
+ "resSubscribeMeta",
5463
+ "resPutMeta",
5464
+ "resGetMeta",
5465
+ "resDelMeta",
5466
+ "resPutData",
5467
+ "resGetData",
5468
+ "resDelData",
5469
+ "resPutWAL",
5470
+ "resGetWAL",
5471
+ "resDelWAL",
5472
+ "updateMeta"
5473
+ ],
5474
+ eventTypes: ["updateMeta"],
5475
+ ...gestalt
5476
+ };
5477
+ }
5478
+ function buildReqChat(sthis, auth, conn, message, targets) {
5479
+ return {
5480
+ tid: sthis.nextId().str,
5481
+ type: "reqChat",
5482
+ version: VERSION,
5483
+ auth,
5484
+ conn,
5485
+ message,
5486
+ targets: targets ?? []
5487
+ };
5488
+ }
5489
+ function buildResChat(req, conn, message, targets, auth) {
5490
+ return {
5491
+ ...req,
5492
+ auth: auth || req.auth,
5493
+ conn: conn || req.conn,
5494
+ message: message || req.message,
5495
+ targets: targets || req.targets,
5496
+ type: "resChat",
5497
+ version: VERSION
5498
+ };
5499
+ }
5500
+ function MsgIsReqChat(msg) {
5501
+ return msg.type === "reqChat";
5502
+ }
5503
+ function MsgIsResChat(msg) {
5504
+ return msg.type === "resChat";
5505
+ }
5506
+ function MsgIsReqGestalt(msg) {
5507
+ return msg.type === "reqGestalt";
5508
+ }
5509
+ function buildReqGestalt(sthis, auth, gestalt, publish) {
5510
+ return {
5511
+ tid: sthis.nextId().str,
5512
+ auth,
5513
+ type: "reqGestalt",
5514
+ version: VERSION,
5515
+ gestalt,
5516
+ publish
5517
+ };
5518
+ }
5519
+ function buildResGestalt(req, gestalt, auth) {
5520
+ return {
5521
+ tid: req.tid,
5522
+ auth: auth || req.auth,
5523
+ type: "resGestalt",
5524
+ version: VERSION,
5525
+ gestalt
5526
+ };
5527
+ }
5528
+ function MsgIsResGestalt(msg) {
5529
+ return msg.type === "resGestalt";
5530
+ }
5531
+ function buildReqOpen(sthis, auth, conn) {
5532
+ return {
5533
+ tid: sthis.nextId().str,
5534
+ auth,
5535
+ type: "reqOpen",
5536
+ version: VERSION,
5537
+ conn: {
5538
+ ...conn,
5539
+ reqId: conn.reqId || sthis.nextId().str
5540
+ }
5541
+ };
5542
+ }
5543
+ function MsgIsReqOpen(imsg) {
5544
+ const msg = imsg;
5545
+ return msg.type === "reqOpen" && !!msg.conn && !!msg.conn.reqId;
5546
+ }
5547
+ function MsgIsWithConn(msg) {
5548
+ const mwc = msg.conn;
5549
+ return mwc && !!mwc.reqId && !!mwc.resId;
5550
+ }
5551
+ function MsgIsWithConnAuth(msg) {
5552
+ return MsgIsWithConn(msg) && !!msg.auth && typeof msg.auth.type === "string";
5553
+ }
5554
+ function MsgIsConnected(msg, qsid) {
5555
+ return MsgIsWithConn(msg) && msg.conn.reqId === qsid.reqId && msg.conn.resId === qsid.resId;
5556
+ }
5557
+ function buildResOpen(sthis, req, resStreamId) {
5558
+ if (!(req.conn && req.conn.reqId)) {
5559
+ throw new Error("req.conn.reqId is required");
5560
+ }
5561
+ return {
5562
+ ...req,
5563
+ type: "resOpen",
5564
+ conn: {
5565
+ ...req.conn,
5566
+ resId: req.conn.resId || resStreamId || sthis.nextId().str
5567
+ }
5568
+ };
5569
+ }
5570
+ function MsgIsResOpen(msg) {
5571
+ return msg.type === "resOpen";
5572
+ }
5573
+ function MsgIsReqClose(msg) {
5574
+ return msg.type === "reqClose" && MsgIsWithConn(msg);
5575
+ }
5576
+ function MsgIsResClose(msg) {
5577
+ return msg.type === "resClose" && MsgIsWithConn(msg);
5578
+ }
5579
+ function buildResClose(req, conn) {
5580
+ return {
5581
+ ...req,
5582
+ type: "resClose",
5583
+ conn
5584
+ };
5585
+ }
5586
+ function buildReqClose(sthis, auth, conn) {
5587
+ return {
5588
+ tid: sthis.nextId().str,
5589
+ auth,
5590
+ type: "reqClose",
5591
+ version: VERSION,
5592
+ conn
5593
+ };
5594
+ }
5595
+ function buildErrorMsg(msgCtx, base, error, body, stack) {
5596
+ if (!stack && msgCtx.sthis.env.get("FP_STACK")) {
5597
+ stack = error.stack?.split("\n");
5598
+ }
5599
+ const msg = {
5600
+ auth: base.auth || { type: "error" },
5601
+ src: base,
5602
+ type: "error",
5603
+ tid: base.tid || "internal",
5604
+ message: error.message,
5605
+ version: VERSION,
5606
+ body,
5607
+ stack
5608
+ };
5609
+ msgCtx.logger.Any("ErrorMsg", msg);
5610
+ return msg;
5611
+ }
5612
+ function MsgIsTenantLedger(msg) {
5613
+ if (MsgIsWithConnAuth(msg)) {
5614
+ const t = msg.tenant;
5615
+ return !!t && !!t.tenant && !!t.ledger;
5616
+ }
5617
+ return false;
5618
+ }
5619
+ function buildReqSignedUrl(sthis, type, rparam, gwCtx) {
5620
+ return {
5621
+ tid: sthis.nextId().str,
5622
+ type,
5623
+ auth: rparam.auth,
5624
+ methodParams: rparam.methodParam,
5625
+ version: VERSION,
5626
+ ...gwCtx,
5627
+ params: rparam.params
5628
+ };
5629
+ }
5630
+ function resAuth(msg) {
5631
+ return msg.auth ? Promise.resolve(msg.auth) : Promise.reject(new Error("No Auth"));
5632
+ }
5633
+ async function buildRes(methodParams, type, msgCtx, req, ctx) {
5634
+ const psm = {
5635
+ type: "reqSignedUrl",
5636
+ auth: await resAuth(req),
5637
+ version: req.version,
5638
+ methodParams,
5639
+ params: {
5640
+ ...req.params
5641
+ },
5642
+ conn: req.conn,
5643
+ tenant: req.tenant,
5644
+ tid: req.tid
5645
+ };
5646
+ const rSignedUrl = await ctx.calculatePreSignedUrl(msgCtx, psm);
5647
+ if (rSignedUrl.isErr()) {
5648
+ return buildErrorMsg(msgCtx, req, rSignedUrl.Err());
5649
+ }
5650
+ return {
5651
+ ...req,
5652
+ params: psm.params,
5653
+ methodParams,
5654
+ type,
5655
+ signedUrl: rSignedUrl.Ok().toString()
5656
+ };
5657
+ }
5658
+
5659
+ // src/protocols/cloud/msger.ts
5660
+ import { BuildURI as BuildURI3, Result as Result15, runtimeFn as runtimeFn4, URI as URI15 } from "@adviser/cement";
5661
+
5662
+ // src/protocols/cloud/http-connection.ts
5663
+ import { HttpHeader, Result as Result13, exception2Result as exception2Result6 } from "@adviser/cement";
5664
+
5665
+ // src/protocols/cloud/msg-raw-connection-base.ts
5666
+ var MsgRawConnectionBase = class {
5667
+ constructor(sthis, exGestalt) {
5668
+ this.onErrorFns = /* @__PURE__ */ new Map();
5669
+ this.sthis = sthis;
5670
+ this.exchangedGestalt = exGestalt;
5671
+ }
5672
+ onError(fn) {
5673
+ const key = this.sthis.nextId().str;
5674
+ this.onErrorFns.set(key, fn);
5675
+ return () => this.onErrorFns.delete(key);
5676
+ }
5677
+ buildErrorMsg(msgCtx, msg, err) {
5678
+ const rmsg = Array.from(this.onErrorFns.values()).reduce((msg2, fn) => {
5679
+ return fn(msg2, err);
5680
+ }, msg);
5681
+ const emsg = buildErrorMsg(msgCtx, rmsg, err);
5682
+ msgCtx.logger.Error().Err(err).Any("msg", rmsg).Msg("connection error");
5683
+ return emsg;
5684
+ }
5685
+ };
5686
+
5687
+ // src/protocols/cloud/http-connection.ts
5688
+ function toHttpProtocol(uri) {
5689
+ const protocol = (uri.getParam("protocol") ?? uri.protocol).replace(/:$/, "");
5690
+ const toFix = uri.build();
5691
+ switch (protocol) {
5692
+ case "ws":
5693
+ case "http":
5694
+ toFix.protocol("http");
5695
+ break;
5696
+ case "https":
5697
+ case "wss":
5698
+ default:
5699
+ toFix.protocol("https");
5700
+ break;
5701
+ }
5702
+ return toFix.URI();
5703
+ }
5704
+ var HttpConnection = class extends MsgRawConnectionBase {
5705
+ constructor(sthis, uris, msgP, exGestalt) {
5706
+ super(sthis, exGestalt);
5707
+ this.#onMsg = /* @__PURE__ */ new Map();
5708
+ this.activeBinds = /* @__PURE__ */ new Map();
5709
+ this.logger = ensureLogger(sthis, "HttpConnection");
5710
+ this.baseURIs = uris.map((uri) => ({
5711
+ in: uri,
5712
+ cleaned: toHttpProtocol(uri)
5713
+ }));
5714
+ this.msgP = msgP;
5715
+ }
5716
+ #onMsg;
5717
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5718
+ send(_msg) {
5719
+ throw new Error("Method not implemented.");
5720
+ }
5721
+ async start() {
5722
+ return Result13.Ok(void 0);
5723
+ }
5724
+ async close() {
5725
+ await Promise.all(Array.from(this.activeBinds.values()).map((state) => state.controller?.close()));
5726
+ this.#onMsg.clear();
5727
+ return Result13.Ok(void 0);
5728
+ }
5729
+ toMsg(msg) {
5730
+ this.#onMsg.forEach((fn) => fn(msg));
5731
+ return msg;
5732
+ }
5733
+ onMsg(fn) {
5734
+ const key = this.sthis.nextId().str;
5735
+ this.#onMsg.set(key, fn);
5736
+ return () => this.#onMsg.delete(key);
5737
+ }
5738
+ #poll(state) {
5739
+ this.request(state.bind.msg, state.bind.opts).then((msg) => {
5740
+ try {
5741
+ state.controller?.enqueue(msg);
5742
+ if (MsgIsError(msg)) {
5743
+ state.controller?.close();
5744
+ } else {
5745
+ state.timeout = setTimeout(() => this.#poll(state), state.bind.opts.pollInterval ?? 1e3);
5746
+ }
5747
+ } catch (err) {
5748
+ state.controller?.error(err);
5749
+ state.controller?.close();
5750
+ }
5751
+ }).catch((err) => {
5752
+ state.controller?.error(err);
5753
+ });
5754
+ }
5755
+ bind(req, opts) {
5756
+ const state = {
5757
+ id: this.sthis.nextId().str,
5758
+ bind: {
5759
+ msg: req,
5760
+ opts
5761
+ }
5762
+ };
5763
+ this.activeBinds.set(state.id, state);
5764
+ return new ReadableStream({
5765
+ cancel: () => {
5766
+ clearTimeout(state.timeout);
5767
+ this.activeBinds.delete(state.id);
5768
+ },
5769
+ start: (controller) => {
5770
+ state.controller = controller;
5771
+ this.#poll(state);
5772
+ }
5773
+ });
5774
+ }
5775
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5776
+ async request(req, _opts) {
5777
+ const headers = HttpHeader.from();
5778
+ headers.Set("Content-Type", this.msgP.mime);
5779
+ headers.Set("Accept", this.msgP.mime);
5780
+ const rReqBody = exception2Result6(() => this.msgP.ende.encode(req));
5781
+ if (rReqBody.isErr()) {
5782
+ return this.toMsg(
5783
+ buildErrorMsg(this, req, this.logger.Error().Err(rReqBody.Err()).Any("req", req).Msg("encode error").AsError())
5784
+ );
5785
+ }
5786
+ headers.Set("Content-Length", rReqBody.Ok().byteLength.toString());
5787
+ const url = selectRandom(this.baseURIs);
5788
+ this.logger.Debug().Any(url).Any("body", req).Msg("request");
5789
+ const rRes = await exception2Result6(
5790
+ () => timeout(
5791
+ this.msgP.timeout,
5792
+ fetch(url.cleaned.toString(), {
5793
+ method: "PUT",
5794
+ headers: headers.AsHeaderInit(),
5795
+ body: rReqBody.Ok()
5796
+ })
5797
+ )
5798
+ );
5799
+ this.logger.Debug().Any(url).Any("body", rRes).Msg("response");
5800
+ if (rRes.isErr()) {
5801
+ return this.toMsg(buildErrorMsg(this, req, this.logger.Error().Err(rRes).Any(url).Msg("fetch error").AsError()));
5802
+ }
5803
+ const res = rRes.Ok();
5804
+ if (!res.ok) {
5805
+ const data2 = new Uint8Array(await res.arrayBuffer());
5806
+ const ret2 = await exception2Result6(async () => this.msgP.ende.decode(data2));
5807
+ if (ret2.isErr() || !MsgIsError(ret2.Ok())) {
5808
+ return this.toMsg(
5809
+ buildErrorMsg(
5810
+ this,
5811
+ req,
5812
+ this.logger.Error().Any(url).Str("status", res.status.toString()).Str("statusText", res.statusText).Msg("HTTP Error").AsError(),
5813
+ await res.text()
5814
+ )
5815
+ );
5816
+ }
5817
+ return this.toMsg(ret2.Ok());
5818
+ }
5819
+ const data = new Uint8Array(await res.arrayBuffer());
5820
+ const ret = await exception2Result6(async () => this.msgP.ende.decode(data));
5821
+ if (ret.isErr()) {
5822
+ return this.toMsg(
5823
+ buildErrorMsg(this, req, this.logger.Error().Err(ret.Err()).Msg("decode error").AsError(), this.sthis.txt.decode(data))
5824
+ );
5825
+ }
5826
+ return this.toMsg(ret.Ok());
5827
+ }
5828
+ // toOnMessage<T extends MsgBase>(msg: WithErrorMsg<T>): Result<WithErrorMsg<T>> {
5829
+ // this.mec.msgFn?.(msg as unknown as MessageEvent<MsgBase>);
5830
+ // return Result.Ok(msg);
5831
+ // }
5832
+ };
5833
+
5834
+ // src/protocols/cloud/ws-connection.ts
5835
+ import { exception2Result as exception2Result7, Future as Future3, Result as Result14 } from "@adviser/cement";
5836
+ var WSConnection = class extends MsgRawConnectionBase {
5837
+ constructor(sthis, ws, msgP, exGestalt) {
5838
+ super(sthis, exGestalt);
5839
+ // readonly baseURI: URI;
5840
+ this.#onMsg = /* @__PURE__ */ new Map();
5841
+ this.#onClose = /* @__PURE__ */ new Map();
5842
+ this.waitForTid = /* @__PURE__ */ new Map();
5843
+ this.opened = false;
5844
+ this.#wsOnMessage = async (event) => {
5845
+ const rMsg = await exception2Result7(() => this.msgP.ende.decode(event.data));
5846
+ if (rMsg.isErr()) {
5847
+ this.logger.Error().Err(rMsg).Any(event.data).Msg("Invalid message");
5848
+ return;
5849
+ }
5850
+ const msg = rMsg.Ok();
5851
+ const waitFor = this.waitForTid.get(msg.tid);
5852
+ Array.from(this.#onMsg.values()).forEach((cb) => {
5853
+ cb(msg);
5854
+ });
5855
+ if (waitFor) {
5856
+ if (MsgIsError(msg)) {
5857
+ this.waitForTid.delete(msg.tid);
5858
+ waitFor.future.resolve(msg);
5859
+ } else if (waitFor.waitFor(msg)) {
5860
+ this.waitForTid.delete(msg.tid);
5861
+ waitFor.future.resolve(msg);
5862
+ } else {
5863
+ this.waitForTid.delete(msg.tid);
5864
+ waitFor.future.resolve(msg);
5865
+ }
5866
+ }
5867
+ };
5868
+ this.activeBinds = /* @__PURE__ */ new Map();
5869
+ this.id = sthis.nextId().str;
5870
+ this.logger = ensureLogger(sthis, "WSConnection");
5871
+ this.msgP = msgP;
5872
+ this.ws = ws;
5873
+ }
5874
+ #onMsg;
5875
+ #onClose;
5876
+ async start() {
5877
+ const onOpenFuture = new Future3();
5878
+ const timer = setTimeout(() => {
5879
+ const err = this.logger.Error().Dur("timeout", this.msgP.timeout).Msg("Timeout").AsError();
5880
+ this.toMsg(buildErrorMsg(this, {}, err));
5881
+ onOpenFuture.resolve(Result14.Err(err));
5882
+ }, this.msgP.timeout);
5883
+ this.ws.onopen = () => {
5884
+ onOpenFuture.resolve(Result14.Ok(void 0));
5885
+ this.opened = true;
5886
+ };
5887
+ this.ws.onerror = (ierr) => {
5888
+ const err = this.logger.Error().Err(ierr).Msg("WS Error").AsError();
5889
+ onOpenFuture.resolve(Result14.Err(err));
5890
+ const res = this.buildErrorMsg(this, {}, err);
5891
+ this.toMsg(res);
5892
+ };
5893
+ this.ws.onmessage = (evt) => {
5894
+ if (!this.opened) {
5895
+ this.toMsg(buildErrorMsg(this, {}, this.logger.Error().Msg("Received message before onOpen").AsError()));
5896
+ }
5897
+ this.#wsOnMessage(evt);
5898
+ };
5899
+ this.ws.onclose = () => {
5900
+ this.opened = false;
5901
+ this.close().catch((ierr) => {
5902
+ const err = this.logger.Error().Err(ierr).Msg("close error").AsError();
5903
+ onOpenFuture.resolve(Result14.Err(err));
5904
+ this.toMsg(buildErrorMsg(this, { tid: "internal" }, err));
5905
+ });
5906
+ };
5907
+ const rOpen = await onOpenFuture.asPromise().finally(() => {
5908
+ clearTimeout(timer);
5909
+ });
5910
+ if (rOpen.isErr()) {
5911
+ return rOpen;
5912
+ }
5913
+ return Result14.Ok(void 0);
5914
+ }
5915
+ #wsOnMessage;
5916
+ async close() {
5917
+ this.#onClose.forEach((fn) => fn());
5918
+ this.#onClose.clear();
5919
+ this.#onMsg.clear();
5920
+ this.ws.close();
5921
+ return Result14.Ok(void 0);
5922
+ }
5923
+ toMsg(msg) {
5924
+ this.#onMsg.forEach((fn) => fn(msg));
5925
+ return msg;
5926
+ }
5927
+ send(msg) {
5928
+ this.ws.send(this.msgP.ende.encode(msg));
5929
+ return Promise.resolve(msg);
5930
+ }
5931
+ onMsg(fn) {
5932
+ const key = this.sthis.nextId().str;
5933
+ this.#onMsg.set(key, fn);
5934
+ return () => this.#onMsg.delete(key);
5935
+ }
5936
+ onClose(fn) {
5937
+ const key = this.sthis.nextId().str;
5938
+ this.#onClose.set(key, fn);
5939
+ return () => this.#onClose.delete(key);
5940
+ }
5941
+ bind(req, opts) {
5942
+ const state = {
5943
+ id: this.sthis.nextId().str,
5944
+ bind: {
5945
+ msg: req,
5946
+ opts
5947
+ }
5948
+ // timeout: undefined,
5949
+ // controller: undefined,
5950
+ };
5951
+ this.activeBinds.set(state.id, state);
5952
+ return new ReadableStream({
5953
+ cancel: () => {
5954
+ this.activeBinds.delete(state.id);
5955
+ },
5956
+ start: (controller) => {
5957
+ this.onMsg((msg) => {
5958
+ if (MsgIsError(msg)) {
5959
+ controller.enqueue(msg);
5960
+ return;
5961
+ }
5962
+ if (!MsgIsTid(msg, req.tid)) {
5963
+ return;
5964
+ }
5965
+ if (opts.waitFor && opts.waitFor(msg)) {
5966
+ controller.enqueue(msg);
5967
+ }
5968
+ });
5969
+ this.send(req);
5970
+ const future = new Future3();
5971
+ this.waitForTid.set(req.tid, { tid: req.tid, future, waitFor: opts.waitFor, timeout: opts.timeout });
5972
+ future.asPromise().then((msg) => {
5973
+ if (MsgIsError(msg)) {
5974
+ controller.enqueue(msg);
5975
+ controller.close();
5976
+ }
5977
+ });
5978
+ }
5979
+ });
5980
+ }
5981
+ async request(req, opts) {
5982
+ if (!this.opened) {
5983
+ return buildErrorMsg(this, req, this.logger.Error().Msg("Connection not open").AsError());
5984
+ }
5985
+ const future = new Future3();
5986
+ this.waitForTid.set(req.tid, { tid: req.tid, future, waitFor: opts.waitFor, timeout: opts.timeout });
5987
+ await this.send(req);
5988
+ return future.asPromise();
5989
+ }
5990
+ // toOnMessage<T extends MsgBase>(msg: WithErrorMsg<T>): Result<WithErrorMsg<T>> {
5991
+ // this.mec.msgFn?.(msg as unknown as MessageEvent<MsgBase>);
5992
+ // return Result.Ok(msg);
5993
+ // }
5994
+ };
5995
+
5996
+ // src/protocols/cloud/msger.ts
5997
+ function selectRandom(arr) {
5998
+ return arr[Math.floor(Math.random() * arr.length)];
5999
+ }
6000
+ function timeout(ms, promise) {
6001
+ return new Promise((resolve, reject) => {
6002
+ const timer = setTimeout(() => {
6003
+ reject(new Error(`TIMEOUT after ${ms}ms`));
6004
+ }, ms);
6005
+ promise.then(resolve).catch(reject).finally(() => clearTimeout(timer));
6006
+ });
6007
+ }
6008
+ function jsonEnDe(sthis) {
6009
+ return {
6010
+ encode: (node) => sthis.txt.encode(JSON.stringify(node)),
6011
+ decode: (data) => JSON.parse(sthis.txt.decode(data))
6012
+ };
6013
+ }
6014
+ function defaultMsgParams(sthis, igs) {
6015
+ return {
6016
+ mime: "application/json",
6017
+ ende: jsonEnDe(sthis),
6018
+ timeout: 3e3,
6019
+ protocolCapabilities: ["reqRes", "stream"],
6020
+ ...igs
6021
+ };
6022
+ }
6023
+ async function applyStart(prC) {
6024
+ const rC = await prC;
6025
+ if (rC.isErr()) {
6026
+ return rC;
6027
+ }
6028
+ const c = rC.Ok();
6029
+ const r = await c.start();
6030
+ if (r.isErr()) {
6031
+ return Result15.Err(r.Err());
6032
+ }
6033
+ return rC;
6034
+ }
6035
+ async function authTypeFromUri(logger, curi) {
6036
+ const uri = URI15.from(curi);
6037
+ const authJWK = uri.getParam("authJWK");
6038
+ if (!authJWK) {
6039
+ return logger.Error().Url(uri).Msg("authJWK is required").ResultError();
6040
+ }
6041
+ return Result15.Ok({
6042
+ type: "fp-cloud-jwk",
6043
+ params: {
6044
+ // claim: fpc.Ok().payload,
6045
+ jwk: authJWK
6046
+ }
6047
+ });
6048
+ }
6049
+ var MsgConnected = class _MsgConnected {
6050
+ static async connect(auth, mrc, conn = {}) {
6051
+ if (Result15.Is(mrc)) {
6052
+ if (mrc.isErr()) {
6053
+ return Result15.Err(mrc.Err());
6054
+ }
6055
+ mrc = mrc.Ok();
6056
+ }
6057
+ const res = await mrc.request(buildReqOpen(mrc.sthis, auth, conn), { waitFor: MsgIsResOpen });
6058
+ if (MsgIsError(res) || !MsgIsResOpen(res)) {
6059
+ return mrc.sthis.logger.Error().Err(res).Msg("unexpected response").ResultError();
6060
+ }
6061
+ return Result15.Ok(new _MsgConnected(mrc, res.conn));
6062
+ }
6063
+ constructor(raw2, conn) {
6064
+ this.sthis = raw2.sthis;
6065
+ this.raw = raw2;
6066
+ this.exchangedGestalt = raw2.exchangedGestalt;
6067
+ this.conn = conn;
6068
+ this.activeBinds = raw2.activeBinds;
6069
+ this.id = this.sthis.nextId().str;
6070
+ }
6071
+ attachAuth(auth) {
6072
+ return new MsgConnectedAuth(this, auth);
6073
+ }
6074
+ };
6075
+ var MsgConnectedAuth = class {
6076
+ constructor(conn, authFactory) {
6077
+ this.id = conn.id;
6078
+ this.raw = conn.raw;
6079
+ this.conn = conn.conn;
6080
+ this.sthis = conn.sthis;
6081
+ this.authFactory = authFactory;
6082
+ this.exchangedGestalt = conn.exchangedGestalt;
6083
+ this.activeBinds = conn.activeBinds;
6084
+ }
6085
+ bind(req, opts) {
6086
+ const stream = this.raw.bind({ ...req, conn: req.conn || this.conn }, opts);
6087
+ const ts = new TransformStream({
6088
+ transform: (chunk, controller) => {
6089
+ if (!MsgIsTid(chunk, req.tid)) {
6090
+ return;
6091
+ }
6092
+ if (MsgIsConnected(chunk, this.conn)) {
6093
+ if (opts.waitFor?.(chunk) || MsgIsError(chunk)) {
6094
+ controller.enqueue(chunk);
6095
+ }
6096
+ }
6097
+ }
6098
+ });
6099
+ stream.pipeThrough(ts);
6100
+ return ts.readable;
6101
+ }
6102
+ authType() {
6103
+ return this.authFactory();
6104
+ }
6105
+ msgConnAuth() {
6106
+ return this.authType().then((r) => {
6107
+ if (r.isErr()) {
6108
+ return Result15.Err(r);
6109
+ }
6110
+ return Result15.Ok({ conn: this.conn, auth: r.Ok() });
6111
+ });
6112
+ }
6113
+ request(req, opts) {
6114
+ return this.raw.request({ ...req, conn: req.conn || this.conn }, opts);
6115
+ }
6116
+ send(msg) {
6117
+ return this.raw.send({ ...msg, conn: msg.conn || this.conn });
6118
+ }
6119
+ start() {
6120
+ return this.raw.start();
6121
+ }
6122
+ async close(t) {
6123
+ await this.request(buildReqClose(this.sthis, t.auth, this.conn), { waitFor: MsgIsResClose });
6124
+ return await this.raw.close(t);
6125
+ }
6126
+ onMsg(msgFn) {
6127
+ return this.raw.onMsg((msg) => {
6128
+ if (MsgIsConnected(msg, this.conn)) {
6129
+ msgFn(msg);
6130
+ }
6131
+ });
6132
+ }
6133
+ };
6134
+ function initialFPUri(curl) {
6135
+ let gestaltUrl = URI15.from(curl);
6136
+ if (["", "/"].includes(gestaltUrl.pathname)) {
6137
+ gestaltUrl = gestaltUrl.build().appendRelative("/fp").URI();
6138
+ }
6139
+ return gestaltUrl;
6140
+ }
6141
+ var Msger = class _Msger {
6142
+ static async openHttp(sthis, urls, msgP, exGestalt) {
6143
+ return Result15.Ok(new HttpConnection(sthis, urls, msgP, exGestalt));
6144
+ }
6145
+ static async openWS(sthis, url, msgP, exGestalt) {
6146
+ let ws;
6147
+ url = url.build().setParam("random", sthis.nextId().str).URI();
6148
+ if (runtimeFn4().isNodeIsh) {
6149
+ const { WebSocket: WebSocket2 } = await import("ws");
6150
+ ws = new WebSocket2(url.toString());
6151
+ } else {
6152
+ ws = new WebSocket(url.toString());
6153
+ }
6154
+ return Result15.Ok(new WSConnection(sthis, ws, msgP, exGestalt));
6155
+ }
6156
+ static async open(sthis, auth, curl, imsgP = {}) {
6157
+ const jsMsgP = defaultMsgParams(sthis, { ...imsgP, mime: "application/json", ende: jsonEnDe(sthis) });
6158
+ const gestaltUrl = initialFPUri(curl);
6159
+ const gs = defaultGestalt(defaultMsgParams(sthis, imsgP), { id: "FP-Universal-Client" });
6160
+ const rHC = await _Msger.openHttp(sthis, [gestaltUrl], jsMsgP, { my: gs, remote: gs });
6161
+ if (rHC.isErr()) {
6162
+ return rHC;
6163
+ }
6164
+ const hc = rHC.Ok();
6165
+ const resGestalt = await hc.request(buildReqGestalt(sthis, auth, gs), {
6166
+ waitFor: MsgIsResGestalt
6167
+ });
6168
+ if (!MsgIsResGestalt(resGestalt)) {
6169
+ return sthis.logger.Error().Any({ resGestalt }).Msg("should be ResGestalt").ResultError();
6170
+ }
6171
+ await hc.close(
6172
+ resGestalt
6173
+ /* as MsgWithConnAuth */
6174
+ );
6175
+ const exGt = { my: gs, remote: resGestalt.gestalt };
6176
+ const msgP = defaultMsgParams(sthis, imsgP);
6177
+ if (exGt.remote.protocolCapabilities.includes("reqRes") && !exGt.remote.protocolCapabilities.includes("stream")) {
6178
+ return applyStart(
6179
+ _Msger.openHttp(
6180
+ sthis,
6181
+ exGt.remote.httpEndpoints.map((i) => BuildURI3.from(curl).resolve(i).URI()),
6182
+ msgP,
6183
+ exGt
6184
+ )
6185
+ );
6186
+ }
6187
+ const wsUrl = BuildURI3.from(gestaltUrl).resolve(selectRandom(exGt.remote.wsEndpoints)).URI();
6188
+ return applyStart(_Msger.openWS(sthis, wsUrl, msgP, exGt));
6189
+ }
6190
+ static connect(sthis, auth, curl, imsgP = {}, conn = {}) {
6191
+ return _Msger.open(sthis, auth, curl, imsgP).then((srv) => MsgConnected.connect(auth, srv, conn));
6192
+ }
6193
+ constructor() {
6194
+ }
6195
+ };
6196
+
6197
+ // src/protocols/cloud/msg-types-data.ts
6198
+ function buildReqGetData(sthis, sup, ctx) {
6199
+ return buildReqSignedUrl(sthis, "reqGetData", sup, ctx);
6200
+ }
6201
+ function MsgIsReqGetData(msg) {
6202
+ return msg.type === "reqGetData";
6203
+ }
6204
+ function MsgIsResGetData(msg) {
6205
+ return msg.type === "resGetData" && MsgIsTenantLedger(msg);
6206
+ }
6207
+ function buildResGetData(msgCtx, req, ctx) {
6208
+ return buildRes(
6209
+ { method: "GET", store: req.methodParams.store },
6210
+ "resGetData",
6211
+ msgCtx,
6212
+ req,
6213
+ ctx
6214
+ );
6215
+ }
6216
+ function MsgIsReqPutData(msg) {
6217
+ return msg.type === "reqPutData";
6218
+ }
6219
+ function buildReqPutData(sthis, sup, ctx) {
6220
+ return buildReqSignedUrl(sthis, "reqPutData", sup, ctx);
6221
+ }
6222
+ function MsgIsResPutData(msg) {
6223
+ return msg.type === "resPutData";
6224
+ }
6225
+ function buildResPutData(msgCtx, req, ctx) {
6226
+ return buildRes(
6227
+ { method: "PUT", store: req.methodParams.store },
6228
+ "resPutData",
6229
+ msgCtx,
6230
+ req,
6231
+ ctx
6232
+ );
6233
+ }
6234
+ function MsgIsReqDelData(msg) {
6235
+ return msg.type === "reqDelData";
6236
+ }
6237
+ function buildReqDelData(sthis, sup, ctx) {
6238
+ return buildReqSignedUrl(sthis, "reqDelData", sup, ctx);
6239
+ }
6240
+ function MsgIsResDelData(msg) {
6241
+ return msg.type === "resDelData";
6242
+ }
6243
+ function buildResDelData(msgCtx, req, ctx) {
6244
+ return buildRes(
6245
+ { method: "DELETE", store: req.methodParams.store },
6246
+ "resDelData",
6247
+ msgCtx,
6248
+ req,
6249
+ ctx
6250
+ );
6251
+ }
6252
+
6253
+ // src/protocols/cloud/msg-types-meta.ts
6254
+ import { VERSION as VERSION2 } from "@adviser/cement";
6255
+ function buildReqPutMeta(sthis, auth, signedUrlParams, meta, gwCtx) {
6256
+ return {
6257
+ auth,
6258
+ tid: sthis.nextId().str,
6259
+ type: "reqPutMeta",
6260
+ ...gwCtx,
6261
+ version: VERSION2,
6262
+ methodParams: {
6263
+ method: "PUT",
6264
+ store: "meta"
6265
+ },
6266
+ params: signedUrlParams,
6267
+ meta
6268
+ };
6269
+ }
6270
+ function MsgIsReqPutMeta(msg) {
6271
+ return msg.type === "reqPutMeta";
6272
+ }
6273
+ function buildResPutMeta(_msgCtx, req, meta, signedUrl) {
6274
+ return {
6275
+ meta,
6276
+ tid: req.tid,
6277
+ conn: req.conn,
6278
+ auth: req.auth,
6279
+ methodParams: req.methodParams,
6280
+ params: req.params,
6281
+ tenant: req.tenant,
6282
+ type: "resPutMeta",
6283
+ signedUrl,
6284
+ version: VERSION2
6285
+ };
6286
+ }
6287
+ function MsgIsResPutMeta(qs) {
6288
+ return qs.type === "resPutMeta";
6289
+ }
6290
+ function MsgIsBindGetMeta(msg) {
6291
+ return msg.type === "bindGetMeta";
6292
+ }
6293
+ function buildBindGetMeta(sthis, auth, params, gwCtx) {
6294
+ return {
6295
+ auth,
6296
+ tid: sthis.nextId().str,
6297
+ ...gwCtx,
6298
+ type: "bindGetMeta",
6299
+ version: VERSION2,
6300
+ params
6301
+ };
6302
+ }
6303
+ function buildEventGetMeta(_msgCtx, req, meta, gwCtx, signedUrl) {
6304
+ return {
6305
+ conn: gwCtx.conn,
6306
+ tenant: req.tenant,
6307
+ auth: req.auth,
6308
+ tid: req.tid,
6309
+ meta,
6310
+ signedUrl,
6311
+ type: "eventGetMeta",
6312
+ params: req.params,
6313
+ methodParams: { method: "GET", store: "meta" },
6314
+ version: VERSION2
6315
+ };
6316
+ }
6317
+ function MsgIsEventGetMeta(qs) {
6318
+ return qs.type === "eventGetMeta";
6319
+ }
6320
+ function buildReqDelMeta(sthis, auth, params, gwCtx, meta) {
6321
+ return {
6322
+ auth,
6323
+ tid: sthis.nextId().str,
6324
+ tenant: gwCtx.tenant,
6325
+ conn: gwCtx.conn,
6326
+ params,
6327
+ meta,
6328
+ type: "reqDelMeta",
6329
+ version: VERSION2
6330
+ // params: signedUrlParams,
6331
+ };
6332
+ }
6333
+ function MsgIsReqDelMeta(msg) {
6334
+ return msg.type === "reqDelMeta";
6335
+ }
6336
+ function buildResDelMeta(req, params, signedUrl) {
6337
+ return {
6338
+ auth: req.auth,
6339
+ methodParams: { method: "DELETE", store: "meta" },
6340
+ params,
6341
+ signedUrl,
6342
+ tid: req.tid,
6343
+ conn: req.conn,
6344
+ tenant: req.tenant,
6345
+ type: "resDelMeta",
6346
+ // key: req.key,
6347
+ version: VERSION2
6348
+ };
6349
+ }
6350
+ function MsgIsResDelMeta(qs) {
6351
+ return qs.type === "resDelMeta";
6352
+ }
6353
+
6354
+ // src/runtime/meta-key-hack.ts
6355
+ import { exception2Result as exception2Result8, Result as Result16 } from "@adviser/cement";
6356
+ function fromV1toV2SerializedMetaKey(v1s, keys = []) {
6357
+ const res = v1s.reduce(
6358
+ (acc, v1) => {
6359
+ const keys2 = [];
6360
+ if (v1.key) {
6361
+ if (typeof v1.key === "string") {
6362
+ acc.keys.add(v1.key);
6363
+ } else {
6364
+ keys2.push(...v1.key);
6365
+ }
6366
+ }
6367
+ if (v1.keys) {
6368
+ keys2.push(...v1.keys);
6369
+ }
6370
+ for (const key of keys2) {
6371
+ acc.keys.add(key);
6372
+ }
6373
+ if (typeof v1.cid === "string" && (!v1.data || typeof v1.data === "string") && (!v1.parents || Array.isArray(v1.parents))) {
6374
+ acc.metas.set(v1.cid, {
6375
+ data: v1.data ?? "",
6376
+ parents: v1.parents ?? [],
6377
+ cid: v1.cid
6378
+ });
6379
+ }
6380
+ return acc;
6381
+ },
6382
+ {
6383
+ metas: /* @__PURE__ */ new Map(),
6384
+ keys: new Set(keys)
6385
+ }
6386
+ );
6387
+ return {
6388
+ metas: Array.from(res.metas.values()),
6389
+ keys: Array.from(res.keys)
6390
+ };
6391
+ }
6392
+ function isV2SerializedMetaKey(or) {
6393
+ const my = or;
6394
+ return my !== null && (!my.keys || Array.isArray(my.keys)) && (!my.metas || Array.isArray(my.metas));
6395
+ }
6396
+ function toV2SerializedMetaKey(or) {
6397
+ if (Array.isArray(or)) {
6398
+ return fromV1toV2SerializedMetaKey(or);
6399
+ }
6400
+ if (isV2SerializedMetaKey(or)) {
6401
+ return fromV1toV2SerializedMetaKey(or.metas ?? [], or.keys ?? []);
6402
+ }
6403
+ throw new Error("not a valid serialized meta key");
6404
+ }
6405
+ async function V2SerializedMetaKeyExtractKey(ctx, v2) {
6406
+ const kb = await ctx.loader.keyBag();
6407
+ if (!kb) {
6408
+ return Promise.resolve(Result16.Err(new Error("missing keybag")));
6409
+ }
6410
+ const dataUrl = await ctx.loader.attachedStores.local().active.car.url();
6411
+ const keyName = dataUrl.getParam(PARAM.STORE_KEY);
6412
+ if (!keyName) {
6413
+ ctx.loader.sthis.logger.Warn().Url(dataUrl).Msg("missing store key");
6414
+ } else {
6415
+ const rKey = await kb.getNamedKey(keyName);
6416
+ if (rKey.isErr()) {
6417
+ ctx.loader.sthis.logger.Warn().Str("keyName", keyName).Msg("did not found a extractable key");
6418
+ } else {
6419
+ for (const keyStr of v2.keys) {
6420
+ const res = await rKey.Ok().upsert(keyStr, false);
6421
+ if (res.isErr()) {
6422
+ ctx.loader.sthis.logger.Warn().Str("keyStr", keyStr).Msg("failed to upsert key");
6423
+ }
6424
+ }
6425
+ }
6426
+ }
6427
+ return Promise.resolve(Result16.Ok(v2.metas));
6428
+ }
6429
+ async function decodeAsToSerializedMeta(ctx, raw2) {
6430
+ const rJsObj = exception2Result8(() => JSON.parse(ctx.loader.sthis.txt.decode(raw2)));
6431
+ if (rJsObj.isErr()) {
6432
+ return Result16.Err(rJsObj);
6433
+ }
6434
+ const v2 = toV2SerializedMetaKey(rJsObj.unwrap());
6435
+ const metas = await V2SerializedMetaKeyExtractKey(ctx, v2);
6436
+ if (metas.isErr()) {
6437
+ return Result16.Err(metas);
6438
+ }
6439
+ return Result16.Ok({
6440
+ metas: metas.Ok(),
6441
+ keys: v2.keys
6442
+ });
6443
+ }
6444
+ function addKeyToDbMetaDecoder(ctx) {
6445
+ const lastDecodedMetas = ctx.lastDecodedMetas ?? [];
6446
+ return {
6447
+ ...ctx,
6448
+ lastDecodedMetas,
6449
+ decoder: {
6450
+ meta: async (sthis, raw2) => {
6451
+ const r = await decodeAsToSerializedMeta(ctx, raw2);
6452
+ if (r.isErr()) {
6453
+ return Promise.resolve(Result16.Err(r));
6454
+ }
6455
+ if (lastDecodedMetas.length > 2) {
6456
+ lastDecodedMetas.shift();
6457
+ }
6458
+ lastDecodedMetas.push(r.Ok());
6459
+ return Promise.resolve(Result16.Ok(r.Ok().metas));
6460
+ }
6461
+ }
6462
+ };
6463
+ }
6464
+ async function wrapEncode(ctx, payload, fn) {
6465
+ const carStore = ctx.loader.attachedStores.local().active.car;
6466
+ const kb = await ctx.loader.keyBag();
6467
+ if (!kb) {
6468
+ return Promise.resolve(Result16.Err(new Error("missing keybag")));
6469
+ }
6470
+ const keyName = carStore.url().getParam(PARAM.STORE_KEY) ?? "";
6471
+ const rKex = await kb.getNamedKey(keyName);
6472
+ if (rKex.isErr()) {
6473
+ return Promise.resolve(Result16.Err(rKex.Err()));
6474
+ }
6475
+ const keyMaterials = await rKex.Ok().asKeysItem().then((i) => Object.values(i.keys).map((i2) => i2.key));
6476
+ return Promise.resolve(Result16.Ok(fn(payload, keyMaterials)));
6477
+ }
6478
+ function encodeAsV1SerializedMetaKey(ctx, payload) {
6479
+ return wrapEncode(ctx, payload, (payload2, keyM) => payload2.map((p) => ({ ...p, key: keyM })));
6480
+ }
6481
+ function encodeAsV2SerializedMetaKey(ctx, payload) {
6482
+ return wrapEncode(
6483
+ ctx,
6484
+ payload,
6485
+ (payload2, keyM) => ({
6486
+ metas: payload2,
6487
+ keys: keyM
6488
+ })
6489
+ );
6490
+ }
6491
+ function addKeyToDbMetaEncoder(ctx, version) {
6492
+ return {
6493
+ ...ctx,
6494
+ encoder: {
6495
+ meta: async (sthis, payload) => {
6496
+ let obj;
6497
+ switch (version) {
6498
+ case "v1":
6499
+ obj = await encodeAsV1SerializedMetaKey(ctx, payload);
6500
+ break;
6501
+ case "v2":
6502
+ obj = await encodeAsV2SerializedMetaKey(ctx, payload);
6503
+ break;
6504
+ default:
6505
+ return Promise.resolve(Result16.Err(`unknown version:[${version}]`));
6506
+ }
6507
+ if (obj.isErr()) {
6508
+ return Promise.resolve(Result16.Err(obj));
6509
+ }
6510
+ try {
6511
+ return Promise.resolve(Result16.Ok(sthis.txt.encode(JSON.stringify(obj.Ok()))));
6512
+ } catch (e) {
6513
+ return Promise.resolve(Result16.Err(e));
6514
+ }
6515
+ }
6516
+ }
6517
+ };
6518
+ }
6519
+ var AddKeyToDbMetaGateway = class {
6520
+ constructor(gw, version) {
6521
+ // only for tests
6522
+ this.lastDecodedMetas = [];
6523
+ this.sdGw = new DefSerdeGateway(gw);
6524
+ this.version = version;
6525
+ }
6526
+ buildUrl(ctx, baseUrl, key) {
6527
+ return this.sdGw.buildUrl(ctx, baseUrl, key);
6528
+ }
6529
+ start(ctx, baseUrl) {
6530
+ return this.sdGw.start(ctx, baseUrl);
6531
+ }
6532
+ close(ctx, baseUrl) {
6533
+ return this.sdGw.close(ctx, baseUrl);
6534
+ }
6535
+ async put(ctx, url, body) {
6536
+ return this.sdGw.put(addKeyToDbMetaEncoder(ctx, this.version), url, body);
6537
+ }
6538
+ async get(ctx, url) {
6539
+ return this.sdGw.get(addKeyToDbMetaDecoder({ ...ctx, lastDecodedMetas: this.lastDecodedMetas }), url);
6540
+ }
6541
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6542
+ delete(ctx, url, loader) {
6543
+ return this.sdGw.delete(ctx, url);
6544
+ }
6545
+ subscribe(ctx, url, callback) {
6546
+ return this.sdGw.subscribe(addKeyToDbMetaDecoder({ ...ctx, lastDecodedMetas: this.lastDecodedMetas }), url, callback);
6547
+ }
6548
+ getPlain(ctx, url, key) {
6549
+ return this.sdGw.getPlain(ctx, url, key);
6550
+ }
6551
+ destroy(ctx, baseUrl) {
6552
+ return this.sdGw.destroy(ctx, baseUrl);
6553
+ }
6554
+ };
6555
+
6556
+ // src/runtime/gateways/cloud/gateway.ts
6557
+ var VERSION3 = "v0.1-fp-cloud";
6558
+ var BaseGateway = class {
6559
+ constructor(sthis, module) {
6560
+ this.sthis = sthis;
6561
+ this.logger = ensureLogger(sthis, module);
6562
+ }
6563
+ async buildReqSignedUrl(type, method, store, uri, conn) {
6564
+ const rParams = uri.getParamsResult({
6565
+ key: param.REQUIRED,
6566
+ store: param.REQUIRED,
6567
+ path: param.OPTIONAL,
6568
+ tenant: param.REQUIRED,
6569
+ name: param.REQUIRED,
6570
+ index: param.OPTIONAL
6571
+ });
6572
+ if (rParams.isErr()) {
6573
+ return buildErrorMsg(this, {}, rParams.Err());
6574
+ }
6575
+ const params = rParams.Ok();
6576
+ if (store !== params.store) {
6577
+ return buildErrorMsg(this, {}, new Error("store mismatch"));
6578
+ }
6579
+ const rAuth = await authTypeFromUri(this.logger, uri);
6580
+ if (rAuth.isErr()) {
6581
+ return buildErrorMsg(this, {}, rAuth.Err());
6582
+ }
6583
+ return {
6584
+ tid: this.sthis.nextId().str,
6585
+ auth: rAuth.Ok(),
6586
+ type,
6587
+ conn: conn.conn.Ok().conn,
6588
+ tenant: {
6589
+ tenant: params.tenant,
6590
+ ledger: params.name
6591
+ },
6592
+ // tenant: conn.tenant,
6593
+ methodParams: {
6594
+ method,
6595
+ store
6596
+ },
6597
+ params: {
6598
+ ...params,
6599
+ key: params.key
6600
+ },
6601
+ version: VERSION3
6602
+ };
6603
+ }
6604
+ async getReqSignedUrl(type, method, store, waitForFn, uri, conn) {
6605
+ const rsu = await this.buildReqSignedUrl(type, method, store, uri, conn);
6606
+ if (MsgIsError(rsu)) {
6607
+ return rsu;
6608
+ }
6609
+ return conn.conn.Ok().request(rsu, { waitFor: waitForFn });
6610
+ }
6611
+ async putObject(uri, uploadUrl, body, conn) {
6612
+ this.logger.Debug().Any("url", { uploadUrl, uri }).Msg("put-fetch-url");
6613
+ const rUpload = await exception2Result9(async () => fetch(uploadUrl, { method: "PUT", body }));
6614
+ if (rUpload.isErr()) {
6615
+ return this.logger.Error().Url(uploadUrl, "uploadUrl").Err(rUpload).Msg("Error in put fetch").ResultError();
6616
+ }
6617
+ if (!rUpload.Ok().ok) {
6618
+ return this.logger.Error().Url(uploadUrl, "uploadUrl").Http(rUpload.Ok()).Msg("Error in put fetch").ResultError();
6619
+ }
6620
+ if (uri.getParam("testMode")) {
6621
+ conn.citem.trackPuts.add(uri.toString());
6622
+ }
6623
+ return Result17.Ok(void 0);
6624
+ }
6625
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6626
+ async getObject(uri, downloadUrl, _conn) {
6627
+ this.logger.Debug().Any("url", { downloadUrl, uri }).Msg("get-fetch-url");
6628
+ const rDownload = await exception2Result9(async () => fetch(downloadUrl.toString(), { method: "GET" }));
6629
+ if (rDownload.isErr()) {
6630
+ return this.logger.Error().Url(downloadUrl, "uploadUrl").Err(rDownload).Msg("Error in get downloadUrl").ResultError();
6631
+ }
6632
+ const download = rDownload.Ok();
6633
+ if (!download.ok) {
6634
+ if (download.status === 404) {
6635
+ return Result17.Err(new NotFoundError("Not found"));
6636
+ }
6637
+ return this.logger.Error().Url(downloadUrl, "uploadUrl").Err(rDownload).Msg("Error in get fetch").ResultError();
6638
+ }
6639
+ return Result17.Ok(to_uint8(await download.arrayBuffer()));
6640
+ }
6641
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6642
+ async delObject(uri, deleteUrl, _conn) {
6643
+ this.logger.Debug().Any("url", { deleteUrl, uri }).Msg("get-fetch-url");
6644
+ const rDelete = await exception2Result9(async () => fetch(deleteUrl.toString(), { method: "DELETE" }));
6645
+ if (rDelete.isErr()) {
6646
+ return this.logger.Error().Url(deleteUrl, "deleteUrl").Err(rDelete).Msg("Error in get deleteURL").ResultError();
6647
+ }
6648
+ const download = rDelete.Ok();
6649
+ if (!download.ok) {
6650
+ if (download.status === 404) {
6651
+ return Result17.Err(new NotFoundError("Not found"));
6652
+ }
6653
+ return this.logger.Error().Url(deleteUrl, "deleteUrl").Err(rDelete).Msg("Error in del fetch").ResultError();
6654
+ }
6655
+ return Result17.Ok(void 0);
6656
+ }
6657
+ };
6658
+ var DataGateway = class extends BaseGateway {
6659
+ constructor(sthis) {
6660
+ super(sthis, "DataGateway");
6661
+ }
6662
+ async get(ctx, uri) {
6663
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6664
+ const rResSignedUrl = await this.getReqSignedUrl("reqGetData", "GET", store, MsgIsResGetData, uri, ctx.conn);
6665
+ if (MsgIsError(rResSignedUrl)) {
6666
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6667
+ }
6668
+ const { signedUrl: downloadUrl } = rResSignedUrl;
6669
+ const r = await fpDeserialize(this.sthis, uri, this.getObject(uri, downloadUrl, ctx.conn));
6670
+ return r;
6671
+ }
6672
+ async put(ctx, uri, data) {
6673
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6674
+ const rResSignedUrl = await this.getReqSignedUrl("reqPutData", "PUT", store, MsgIsResPutData, uri, ctx.conn);
6675
+ if (MsgIsError(rResSignedUrl)) {
6676
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6677
+ }
6678
+ const { signedUrl: uploadUrl } = rResSignedUrl;
6679
+ const rBlob = await fpSerialize(ctx.loader.sthis, data);
6680
+ if (rBlob.isErr()) {
6681
+ return rBlob;
6682
+ }
6683
+ const r = await this.putObject(uri, uploadUrl, rBlob.Ok(), ctx.conn);
6684
+ return r;
6685
+ }
6686
+ async delete(ctx, uri) {
6687
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6688
+ const rResSignedUrl = await this.getReqSignedUrl("reqDelData", "DELETE", store, MsgIsResDelData, uri, ctx.conn);
6689
+ if (MsgIsError(rResSignedUrl)) {
6690
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6691
+ }
6692
+ const { signedUrl: deleteUrl } = rResSignedUrl;
6693
+ return this.delObject(uri, deleteUrl, ctx.conn);
6694
+ }
6695
+ };
6696
+ function getGwCtx(conn, uri) {
6697
+ const rParams = uri.getParamsResult({
6698
+ tid: param.OPTIONAL,
6699
+ tenant: param.REQUIRED,
6700
+ ledger: param.REQUIRED
6701
+ });
6702
+ if (rParams.isErr()) {
6703
+ return Result17.Err(rParams);
6704
+ }
6705
+ const r = rParams.Ok();
6706
+ return Result17.Ok({
6707
+ tid: r.tid,
6708
+ conn,
6709
+ tenant: {
6710
+ tenant: r.tenant,
6711
+ ledger: r.ledger
6712
+ }
6713
+ });
6714
+ }
6715
+ var MetaGateway = class extends BaseGateway {
6716
+ constructor(sthis) {
6717
+ super(sthis, "MetaGateway");
6718
+ }
6719
+ async get(ctx, uri) {
6720
+ const reqSignedUrl = await this.buildReqSignedUrl("bindGetMeta", "GET", "meta", uri, ctx.conn);
6721
+ if (MsgIsError(reqSignedUrl)) {
6722
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6723
+ }
6724
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6725
+ if (rGwCtx.isErr()) {
6726
+ return Result17.Err(rGwCtx);
6727
+ }
6728
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6729
+ if (rAuthType.isErr()) {
6730
+ return Result17.Err(rAuthType);
6731
+ }
6732
+ const res = await ctx.conn.conn.Ok().request(buildBindGetMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rGwCtx.Ok()), {
6733
+ waitFor: MsgIsEventGetMeta
6734
+ });
6735
+ if (MsgIsError(res)) {
6736
+ return this.logger.Error().Err(res).Msg("Error in buildBindGetMeta").ResultError();
6737
+ }
6738
+ const rV2Meta = await V2SerializedMetaKeyExtractKey(ctx, res.meta);
6739
+ const rMeta = await decode2DbMetaEvents(ctx.loader.sthis, rV2Meta);
6740
+ if (rMeta.isErr()) {
6741
+ return Result17.Err(rMeta);
6742
+ }
6743
+ return Result17.Ok({
6744
+ type: "meta",
6745
+ payload: rMeta.Ok()
6746
+ });
6747
+ }
6748
+ async put(ctx, uri, imeta) {
6749
+ const meta = imeta;
6750
+ const reqSignedUrl = await this.buildReqSignedUrl("reqPutMeta", "PUT", "meta", uri, ctx.conn);
6751
+ if (MsgIsError(reqSignedUrl)) {
6752
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6753
+ }
6754
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6755
+ if (rGwCtx.isErr()) {
6756
+ return Result17.Err(rGwCtx);
6757
+ }
6758
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6759
+ if (rAuthType.isErr()) {
6760
+ return Result17.Err(rAuthType);
6761
+ }
6762
+ const serializedMeta = await dbMetaEvent2Serialized(ctx.loader.sthis, meta.payload);
6763
+ const rKeyedMeta = await encodeAsV2SerializedMetaKey(ctx, serializedMeta);
6764
+ if (rKeyedMeta.isErr()) {
6765
+ return rKeyedMeta;
6766
+ }
6767
+ const reqPutMeta = buildReqPutMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rKeyedMeta.Ok(), rGwCtx.Ok());
6768
+ const resMsg = await ctx.conn.conn.Ok().request(reqPutMeta, {
6769
+ waitFor: MsgIsResPutMeta
6770
+ });
6771
+ if (MsgIsError(resMsg)) {
6772
+ return this.logger.Error().Err(resMsg).Msg("Error in buildResSignedUrl").ResultError();
6773
+ }
6774
+ return Result17.Ok(void 0);
6775
+ }
6776
+ async delete(ctx, uri) {
6777
+ const reqSignedUrl = await this.getReqSignedUrl("reqDelMeta", "DELETE", "meta", MsgIsResDelData, uri, ctx.conn);
6778
+ if (MsgIsError(reqSignedUrl)) {
6779
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6780
+ }
6781
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6782
+ if (rGwCtx.isErr()) {
6783
+ return Result17.Err(rGwCtx);
6784
+ }
6785
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6786
+ if (rAuthType.isErr()) {
6787
+ return Result17.Err(rAuthType);
6788
+ }
6789
+ const reqDelMeta = buildReqDelMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rGwCtx.Ok());
6790
+ const resMsg = await ctx.conn.conn.Ok().request(reqDelMeta, {
6791
+ waitFor: MsgIsResDelData
6792
+ });
6793
+ if (MsgIsError(resMsg)) {
6794
+ return this.logger.Error().Err(resMsg).Msg("Error in buildResSignedUrl").ResultError();
6795
+ }
6796
+ return Result17.Ok(void 0);
6797
+ }
6798
+ };
6799
+ var WALGateway = class extends BaseGateway {
6800
+ constructor(sthis) {
6801
+ super(sthis, "WALGateway");
6802
+ // WAL will not pollute to the cloud
6803
+ this.wals = /* @__PURE__ */ new Map();
6804
+ }
6805
+ getWalKeyFromUri(uri) {
6806
+ const rKey = uri.getParamsResult({
6807
+ key: 0,
6808
+ name: 0
6809
+ });
6810
+ if (rKey.isErr()) {
6811
+ return Result17.Err(rKey.Err());
6812
+ }
6813
+ const { name, key } = rKey.Ok();
6814
+ return Result17.Ok(`${name}:${key}`);
6815
+ }
6816
+ async get(ctx, uri) {
6817
+ const rKey = this.getWalKeyFromUri(uri);
6818
+ if (rKey.isErr()) {
6819
+ return Result17.Err(rKey.Err());
6820
+ }
6821
+ const wal = this.wals.get(rKey.Ok());
6822
+ if (!wal) {
6823
+ return Result17.Err(new NotFoundError("Not found"));
6824
+ }
6825
+ return Result17.Ok(wal);
6826
+ }
6827
+ async put(ctx, uri, body) {
6828
+ const rKey = this.getWalKeyFromUri(uri);
6829
+ if (rKey.isErr()) {
6830
+ return Result17.Err(rKey.Err());
6831
+ }
6832
+ this.wals.set(rKey.Ok(), body);
6833
+ return Result17.Ok(void 0);
6834
+ }
6835
+ async delete(ctx, uri) {
6836
+ const rKey = this.getWalKeyFromUri(uri);
6837
+ if (rKey.isErr()) {
6838
+ return Result17.Err(rKey.Err());
6839
+ }
6840
+ this.wals.delete(rKey.Ok());
6841
+ return Result17.Ok(void 0);
6842
+ }
6843
+ };
6844
+ var storeTypedGateways = new KeyedResolvOnce6();
6845
+ function getStoreTypeGateway(sthis, uri) {
6846
+ const store = uri.getParam("store");
6847
+ switch (store) {
6848
+ case "file":
6849
+ case "car":
6850
+ return storeTypedGateways.get(store).once(() => new DataGateway(sthis));
6851
+ case "meta":
6852
+ return storeTypedGateways.get(store).once(() => new MetaGateway(sthis));
6853
+ case "wal":
6854
+ return storeTypedGateways.get(store).once(() => new WALGateway(sthis));
6855
+ default:
6856
+ throw ensureLogger(sthis, "getStoreTypeGateway").Error().Str("store", store).Msg("Invalid store type").ResultError();
6857
+ }
6858
+ }
6859
+ function connectionURI(uri) {
6860
+ return uri.build().delParam("authJWK").delParam("key").delParam("store").delParam("suffix").delParam("storekey").URI();
6861
+ }
6862
+ var subscriptions = /* @__PURE__ */ new Map();
6863
+ var FireproofCloudGateway = class {
6864
+ #connectionURIs = /* @__PURE__ */ new Map();
6865
+ constructor(sthis) {
6866
+ this.sthis = sthis;
6867
+ this.logger = ensureLogger(sthis, "FireproofCloudGateway", {
6868
+ this: true
6869
+ });
6870
+ }
6871
+ async buildUrl(ctx, baseUrl, key) {
6872
+ return Result17.Ok(baseUrl.build().setParam("key", key).URI());
6873
+ }
6874
+ async start(ctx, uri) {
6875
+ await this.sthis.start();
6876
+ const rName = uri.getParamResult("name");
6877
+ if (rName.isErr()) {
6878
+ return this.logger.Error().Err(rName).Msg("name not found").ResultError();
6879
+ }
6880
+ const ret = uri.build().defParam("version", VERSION3);
6881
+ ret.defParam("protocol", "wss");
6882
+ const retURI = ret.URI();
6883
+ const matchURI = connectionURI(retURI);
6884
+ this.#connectionURIs.set(matchURI.toString(), {
6885
+ uri: matchURI,
6886
+ matchRes: matchURI.match(matchURI),
6887
+ connection: new ResolveOnce8(),
6888
+ trackPuts: /* @__PURE__ */ new Set()
6889
+ });
6890
+ return Result17.Ok(retURI);
6891
+ }
6892
+ async get(ctx, uri) {
6893
+ const conn = await this.getCloudConnectionItem(uri);
6894
+ if (conn.conn.isErr()) {
6895
+ return Result17.Err(conn.conn);
6896
+ }
6897
+ const ret = await getStoreTypeGateway(ctx.loader.sthis, uri).get({ ...ctx, conn }, uri);
6898
+ return ret;
6899
+ }
6900
+ async put(ctx, uri, body) {
6901
+ const conn = await this.getCloudConnectionItem(uri);
6902
+ if (conn.conn.isErr()) {
6903
+ return conn.conn;
6904
+ }
6905
+ const ret = await getStoreTypeGateway(ctx.loader.sthis, uri).put({ ...ctx, conn }, uri, body);
6906
+ if (ret.isOk()) {
6907
+ if (uri.getParam("testMode")) {
6908
+ conn.citem.trackPuts.add(uri.toString());
6909
+ }
6910
+ }
6911
+ return ret;
6912
+ }
6913
+ async delete(ctx, uri) {
6914
+ const conn = await this.getCloudConnectionItem(uri);
6915
+ if (conn.conn.isErr()) {
6916
+ return conn.conn;
6917
+ }
6918
+ conn.citem.trackPuts.delete(uri.toString());
6919
+ return getStoreTypeGateway(ctx.loader.sthis, uri).delete({ ...ctx, conn }, uri);
6920
+ }
6921
+ async close(ctx, uri) {
6922
+ const uriStr = uri.toString();
6923
+ for (const sub of Array.from(subscriptions.values())) {
6924
+ for (const s of sub) {
6925
+ if (s.uri.toString() === uriStr) {
6926
+ s.unsub();
6927
+ }
6928
+ }
6929
+ }
6930
+ const rConn = await this.getCloudConnectionItem(uri);
6931
+ if (rConn.conn.isErr()) {
6932
+ return this.logger.Error().Err(rConn).Msg("Error in getCloudConnection").ResultError();
6933
+ }
6934
+ const conn = rConn.conn.Ok();
6935
+ const rAuth = await conn.msgConnAuth();
6936
+ await conn.close(rAuth.Ok());
6937
+ this.#connectionURIs.delete(rConn.citem.uri.toString());
6938
+ return Result17.Ok(void 0);
6939
+ }
6940
+ // fireproof://localhost:1999/?name=test-public-api&protocol=ws&store=meta
6941
+ async getCloudConnection(uri) {
6942
+ return this.getCloudConnectionItem(uri).then((r) => {
6943
+ return r.conn;
6944
+ });
6945
+ }
6946
+ async getCloudConnectionItem(uri) {
6947
+ const matchURI = connectionURI(uri);
6948
+ let bestMatch;
6949
+ for (const ci of this.#connectionURIs.values()) {
6950
+ const mci = ci.uri.match(matchURI);
6951
+ if (mci.score >= ci.matchRes.score) {
6952
+ bestMatch = ci;
6953
+ break;
6954
+ }
6955
+ }
6956
+ if (!bestMatch) {
6957
+ return {
6958
+ conn: this.logger.Error().Url(matchURI).Any("conns", Object.fromEntries(this.#connectionURIs.entries())).Msg("No connection found").ResultError(),
6959
+ citem: {}
6960
+ };
6961
+ }
6962
+ const conn = await bestMatch.connection.once(async () => {
6963
+ const rParams = uri.getParamsResult({
6964
+ name: param.REQUIRED,
6965
+ protocol: "https",
6966
+ store: param.REQUIRED,
6967
+ storekey: param.OPTIONAL,
6968
+ tenant: param.REQUIRED
6969
+ });
6970
+ if (rParams.isErr()) {
6971
+ return this.logger.Error().Url(uri).Err(rParams).Msg("getCloudConnection:err").ResultError();
6972
+ }
6973
+ const params = rParams.Ok();
6974
+ const rAuth = await authTypeFromUri(this.logger, uri);
6975
+ if (rAuth.isErr()) {
6976
+ return Result17.Err(rAuth);
6977
+ }
6978
+ const qOpen = buildReqOpen(this.sthis, rAuth.Ok(), {});
6979
+ const cUrl = uri.build().protocol(params.protocol).cleanParams().URI();
6980
+ return Msger.connect(this.sthis, rAuth.Ok(), cUrl, qOpen);
6981
+ });
6982
+ if (conn.isErr()) {
6983
+ return { conn: Result17.Err(conn), citem: bestMatch };
6984
+ }
6985
+ return { conn: Result17.Ok(conn.Ok().attachAuth(() => authTypeFromUri(this.logger, uri))), citem: bestMatch };
6986
+ }
6987
+ // private notifySubscribers(data: Uint8Array, callbacks: ((msg: Uint8Array) => void)[] = []): void {
6988
+ // for (const cb of callbacks) {
6989
+ // try {
6990
+ // cb(data);
6991
+ // } catch (error) {
6992
+ // this.logger.Error().Err(error).Msg("Error in subscriber callback execution");
6993
+ // }
6994
+ // }
6995
+ // }
6996
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6997
+ async subscribe(ctx, url, callback) {
6998
+ return Result17.Err(new Error("Not implemented"));
6999
+ }
7000
+ async destroy(ctx, uri) {
7001
+ const item = await this.getCloudConnectionItem(uri);
7002
+ if (item.conn.isErr()) {
7003
+ return item.conn;
7004
+ }
7005
+ await Promise.all(Array.from(item.citem.trackPuts).map(async (k) => this.delete(ctx, URI17.from(k))));
7006
+ return Result17.Ok(void 0);
7007
+ }
7008
+ async getPlain() {
7009
+ return Result17.Err(new Error("Not implemented"));
7010
+ }
7011
+ };
7012
+ var onceRegisterFireproofCloudStoreProtocol = new KeyedResolvOnce6();
7013
+ function registerFireproofCloudStoreProtocol(protocol = "fpcloud:") {
7014
+ return onceRegisterFireproofCloudStoreProtocol.get(protocol).once(() => {
7015
+ URI17.protocolHasHostpart(protocol);
7016
+ return registerStoreProtocol({
7017
+ protocol,
7018
+ defaultURI() {
7019
+ return URI17.from("fpcloud://fireproof.cloud/");
7020
+ },
7021
+ serdegateway: async (sthis) => {
7022
+ return new FireproofCloudGateway(sthis);
7023
+ }
7024
+ });
7025
+ });
7026
+ }
7027
+ registerFireproofCloudStoreProtocol();
7028
+ function toCloud(url) {
7029
+ const urlObj = URI17.from(url);
7030
+ if (urlObj.protocol !== "fpcloud:") {
7031
+ throw new Error("url must have fireproof protocol");
7032
+ }
7033
+ return {
7034
+ name: urlObj.protocol,
7035
+ prepare() {
7036
+ return Promise.resolve({
7037
+ car: { url: urlObj },
7038
+ file: { url: urlObj },
7039
+ meta: { url: urlObj }
7040
+ });
7041
+ }
7042
+ };
7043
+ }
7044
+
7045
+ // src/protocols/index.ts
7046
+ var protocols_exports = {};
7047
+ __export(protocols_exports, {
7048
+ cloud: () => cloud_exports
7049
+ });
7050
+
7051
+ // src/protocols/cloud/index.ts
7052
+ var cloud_exports = {};
7053
+ __export(cloud_exports, {
7054
+ HttpConnection: () => HttpConnection,
7055
+ MsgConnected: () => MsgConnected,
7056
+ MsgConnectedAuth: () => MsgConnectedAuth,
7057
+ MsgIsBindGetMeta: () => MsgIsBindGetMeta,
7058
+ MsgIsConnected: () => MsgIsConnected,
7059
+ MsgIsError: () => MsgIsError,
7060
+ MsgIsEventGetMeta: () => MsgIsEventGetMeta,
7061
+ MsgIsQSError: () => MsgIsQSError,
7062
+ MsgIsReqChat: () => MsgIsReqChat,
7063
+ MsgIsReqClose: () => MsgIsReqClose,
7064
+ MsgIsReqDelData: () => MsgIsReqDelData,
7065
+ MsgIsReqDelMeta: () => MsgIsReqDelMeta,
7066
+ MsgIsReqDelWAL: () => MsgIsReqDelWAL,
7067
+ MsgIsReqGestalt: () => MsgIsReqGestalt,
7068
+ MsgIsReqGetData: () => MsgIsReqGetData,
7069
+ MsgIsReqGetWAL: () => MsgIsReqGetWAL,
7070
+ MsgIsReqOpen: () => MsgIsReqOpen,
7071
+ MsgIsReqPutData: () => MsgIsReqPutData,
7072
+ MsgIsReqPutMeta: () => MsgIsReqPutMeta,
7073
+ MsgIsReqPutWAL: () => MsgIsReqPutWAL,
7074
+ MsgIsResChat: () => MsgIsResChat,
7075
+ MsgIsResClose: () => MsgIsResClose,
7076
+ MsgIsResDelData: () => MsgIsResDelData,
7077
+ MsgIsResDelMeta: () => MsgIsResDelMeta,
7078
+ MsgIsResDelWAL: () => MsgIsResDelWAL,
7079
+ MsgIsResGestalt: () => MsgIsResGestalt,
7080
+ MsgIsResGetData: () => MsgIsResGetData,
7081
+ MsgIsResGetWAL: () => MsgIsResGetWAL,
7082
+ MsgIsResOpen: () => MsgIsResOpen,
7083
+ MsgIsResPutData: () => MsgIsResPutData,
7084
+ MsgIsResPutMeta: () => MsgIsResPutMeta,
7085
+ MsgIsResPutWAL: () => MsgIsResPutWAL,
7086
+ MsgIsTenantLedger: () => MsgIsTenantLedger,
7087
+ MsgIsTid: () => MsgIsTid,
7088
+ MsgIsWithConn: () => MsgIsWithConn,
7089
+ MsgIsWithConnAuth: () => MsgIsWithConnAuth,
7090
+ MsgRawConnectionBase: () => MsgRawConnectionBase,
7091
+ Msger: () => Msger,
7092
+ VERSION: () => VERSION,
7093
+ WSConnection: () => WSConnection,
7094
+ applyStart: () => applyStart,
7095
+ authTypeFromUri: () => authTypeFromUri,
7096
+ buildBindGetMeta: () => buildBindGetMeta,
7097
+ buildErrorMsg: () => buildErrorMsg,
7098
+ buildEventGetMeta: () => buildEventGetMeta,
7099
+ buildReqChat: () => buildReqChat,
7100
+ buildReqClose: () => buildReqClose,
7101
+ buildReqDelData: () => buildReqDelData,
7102
+ buildReqDelMeta: () => buildReqDelMeta,
7103
+ buildReqDelWAL: () => buildReqDelWAL,
7104
+ buildReqGestalt: () => buildReqGestalt,
7105
+ buildReqGetData: () => buildReqGetData,
7106
+ buildReqGetWAL: () => buildReqGetWAL,
7107
+ buildReqOpen: () => buildReqOpen,
7108
+ buildReqPutData: () => buildReqPutData,
7109
+ buildReqPutMeta: () => buildReqPutMeta,
7110
+ buildReqPutWAL: () => buildReqPutWAL,
7111
+ buildReqSignedUrl: () => buildReqSignedUrl,
7112
+ buildRes: () => buildRes,
7113
+ buildResChat: () => buildResChat,
7114
+ buildResClose: () => buildResClose,
7115
+ buildResDelData: () => buildResDelData,
7116
+ buildResDelMeta: () => buildResDelMeta,
7117
+ buildResDelWAL: () => buildResDelWAL,
7118
+ buildResGestalt: () => buildResGestalt,
7119
+ buildResGetData: () => buildResGetData,
7120
+ buildResGetWAL: () => buildResGetWAL,
7121
+ buildResOpen: () => buildResOpen,
7122
+ buildResPutData: () => buildResPutData,
7123
+ buildResPutMeta: () => buildResPutMeta,
7124
+ buildResPutWAL: () => buildResPutWAL,
7125
+ coerceFPStoreTypes: () => coerceFPStoreTypes,
7126
+ defaultGestalt: () => defaultGestalt,
7127
+ defaultMsgParams: () => defaultMsgParams,
7128
+ isAuthTypeFPCloud: () => isAuthTypeFPCloud,
7129
+ isAuthTypeFPCloudJWK: () => isAuthTypeFPCloudJWK,
7130
+ isProtocolCapabilities: () => isProtocolCapabilities,
7131
+ jsonEnDe: () => jsonEnDe,
7132
+ keyTenantLedger: () => keyTenantLedger,
7133
+ qsidEqual: () => qsidEqual,
7134
+ qsidKey: () => qsidKey,
7135
+ resAuth: () => resAuth,
7136
+ selectRandom: () => selectRandom,
7137
+ timeout: () => timeout
7138
+ });
7139
+
7140
+ // src/protocols/cloud/msg-types-wal.ts
7141
+ function MsgIsReqGetWAL(msg) {
7142
+ return msg.type === "reqGetWAL";
7143
+ }
7144
+ function buildReqGetWAL(sthis, sup, ctx) {
7145
+ return buildReqSignedUrl(sthis, "reqGetWAL", sup, ctx);
7146
+ }
7147
+ function MsgIsResGetWAL(msg) {
7148
+ return msg.type === "resGetWAL";
7149
+ }
7150
+ function buildResGetWAL(msgCtx, req, ctx) {
7151
+ return buildRes(
7152
+ { method: "GET", store: "wal" },
7153
+ "resGetWAL",
7154
+ msgCtx,
7155
+ req,
7156
+ ctx
7157
+ );
7158
+ }
7159
+ function MsgIsReqPutWAL(msg) {
7160
+ return msg.type === "reqPutWAL";
7161
+ }
7162
+ function buildReqPutWAL(sthis, sup, ctx) {
7163
+ return buildReqSignedUrl(sthis, "reqPutWAL", sup, ctx);
7164
+ }
7165
+ function MsgIsResPutWAL(msg) {
7166
+ return msg.type === "resPutWAL";
7167
+ }
7168
+ function buildResPutWAL(msgCtx, req, ctx) {
7169
+ return buildRes(
7170
+ { method: "PUT", store: "wal" },
7171
+ "resPutWAL",
7172
+ msgCtx,
7173
+ req,
7174
+ ctx
7175
+ );
7176
+ }
7177
+ function MsgIsReqDelWAL(msg) {
7178
+ return msg.type === "reqDelWAL";
7179
+ }
7180
+ function buildReqDelWAL(sthis, sup, ctx) {
7181
+ return buildReqSignedUrl(sthis, "reqDelWAL", sup, ctx);
7182
+ }
7183
+ function MsgIsResDelWAL(msg) {
7184
+ return msg.type === "resDelWAL" && MsgIsTenantLedger(msg);
7185
+ }
7186
+ function buildResDelWAL(msgCtx, req, ctx) {
7187
+ return buildRes(
7188
+ { method: "DELETE", store: "wal" },
7189
+ "resDelWAL",
7190
+ msgCtx,
7191
+ req,
7192
+ ctx
7193
+ );
7194
+ }
7195
+
5227
7196
  // src/version.ts
5228
7197
  var PACKAGE_VERSION = Object.keys({
5229
- "0.20.0-dev-preview-54": "xxxx"
7198
+ "0.20.0-dev-preview-57": "xxxx"
5230
7199
  })[0];
5231
7200
  export {
5232
7201
  CRDTImpl,
@@ -5263,6 +7232,8 @@ export {
5263
7232
  keyConfigOpts,
5264
7233
  makeName,
5265
7234
  onSuperThis,
7235
+ protocols_exports as protocols,
7236
+ protocols_exports as ps,
5266
7237
  runtime_exports as rt,
5267
7238
  runtime_exports as runtime,
5268
7239
  storeType2DataMetaWal,