@fireproof/core 0.20.0-dev-preview-55 → 0.20.0-dev-preview-58

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.cjs CHANGED
@@ -64,8 +64,11 @@ __export(index_exports, {
64
64
  keyConfigOpts: () => keyConfigOpts,
65
65
  makeName: () => makeName,
66
66
  onSuperThis: () => onSuperThis,
67
+ protocols: () => protocols_exports,
68
+ ps: () => protocols_exports,
67
69
  rt: () => runtime_exports,
68
70
  runtime: () => runtime_exports,
71
+ setPresetEnv: () => setPresetEnv,
69
72
  storeType2DataMetaWal: () => storeType2DataMetaWal,
70
73
  throwFalsy: () => throwFalsy,
71
74
  toSortedArray: () => toSortedArray,
@@ -184,15 +187,21 @@ var SuperThisImpl = class _SuperThisImpl {
184
187
  });
185
188
  }
186
189
  };
187
- function presetEnv() {
190
+ function presetEnv(ipreset) {
191
+ let preset = {};
192
+ if (ipreset instanceof Map) {
193
+ preset = Object.fromEntries(ipreset.entries());
194
+ } else if (typeof ipreset === "object" && ipreset !== null) {
195
+ preset = ipreset;
196
+ }
188
197
  const penv = new Map([
189
198
  // ["FP_DEBUG", "xxx"],
190
199
  // ["FP_ENV", "development"],
191
200
  ...Array.from(
192
- Object.entries(
193
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
194
- globalThis[Symbol.for("FP_PRESET_ENV")] || {}
195
- )
201
+ Object.entries({
202
+ ...setPresetEnv({}),
203
+ ...preset
204
+ })
196
205
  )
197
206
  // .map(([k, v]) => [k, v as string])
198
207
  ]);
@@ -229,7 +238,7 @@ function onSuperThis(fn) {
229
238
  function ensureSuperThis(osthis) {
230
239
  const env = (0, import_cement.envFactory)({
231
240
  symbol: osthis?.env?.symbol || "FP_ENV",
232
- presetEnv: osthis?.env?.presetEnv || presetEnv()
241
+ presetEnv: presetEnv(osthis?.env?.presetEnv)
233
242
  });
234
243
  const ret = new SuperThisImpl({
235
244
  logger: osthis?.logger || globalLogger(),
@@ -495,6 +504,14 @@ function ensureURIDefaults(sthis, name, curi, uri, store, ctx) {
495
504
  }
496
505
  return ret.URI();
497
506
  }
507
+ function setPresetEnv(o, symbol = "FP_PRESET_ENV") {
508
+ const key = Symbol.for(symbol);
509
+ const env = globalThis[key] ?? {};
510
+ for (const [k, v] of Object.entries(o)) {
511
+ env[k] = v;
512
+ }
513
+ return env;
514
+ }
498
515
 
499
516
  // src/write-queue.ts
500
517
  var import_cement2 = require("@adviser/cement");
@@ -5259,11 +5276,18 @@ function fireproof(name, opts) {
5259
5276
  // src/runtime/index.ts
5260
5277
  var runtime_exports = {};
5261
5278
  __export(runtime_exports, {
5279
+ AddKeyToDbMetaGateway: () => AddKeyToDbMetaGateway,
5262
5280
  FILESTORE_VERSION: () => FILESTORE_VERSION,
5263
5281
  INDEXEDDB_VERSION: () => INDEXEDDB_VERSION,
5264
5282
  KeyBag: () => KeyBag,
5283
+ V2SerializedMetaKeyExtractKey: () => V2SerializedMetaKeyExtractKey,
5284
+ addKeyToDbMetaDecoder: () => addKeyToDbMetaDecoder,
5285
+ addKeyToDbMetaEncoder: () => addKeyToDbMetaEncoder,
5286
+ decodeAsToSerializedMeta: () => decodeAsToSerializedMeta,
5265
5287
  defaultKeyBagOpts: () => defaultKeyBagOpts,
5266
5288
  defaultKeyBagUrl: () => defaultKeyBagUrl,
5289
+ encodeAsV1SerializedMetaKey: () => encodeAsV1SerializedMetaKey,
5290
+ encodeAsV2SerializedMetaKey: () => encodeAsV2SerializedMetaKey,
5267
5291
  files: () => files_exports,
5268
5292
  getFileName: () => getFileName,
5269
5293
  getKeyBag: () => getKeyBag,
@@ -5274,7 +5298,8 @@ __export(runtime_exports, {
5274
5298
  keysByFingerprint: () => keysByFingerprint,
5275
5299
  mf: () => wait_pr_multiformats_exports,
5276
5300
  registerKeyBagProviderFactory: () => registerKeyBagProviderFactory,
5277
- runtimeFn: () => import_cement22.runtimeFn,
5301
+ runtimeFn: () => import_cement29.runtimeFn,
5302
+ sts: () => sts_service_exports,
5278
5303
  toKeyWithFingerPrint: () => toKeyWithFingerPrint
5279
5304
  });
5280
5305
 
@@ -5288,13 +5313,109 @@ __export(wait_pr_multiformats_exports, {
5288
5313
  // src/runtime/wait-pr-multiformats/codec-interface.ts
5289
5314
  var codec_interface_exports = {};
5290
5315
 
5291
- // src/runtime/index.ts
5316
+ // src/runtime/sts-service/index.ts
5317
+ var sts_service_exports = {};
5318
+ __export(sts_service_exports, {
5319
+ SessionTokenService: () => SessionTokenService,
5320
+ env2jwk: () => env2jwk,
5321
+ envKeyDefaults: () => envKeyDefaults,
5322
+ jwk2env: () => jwk2env
5323
+ });
5292
5324
  var import_cement22 = require("@adviser/cement");
5325
+ var import_jose = require("jose");
5326
+ var import_keypair = require("jose/key/generate/keypair");
5327
+ var import_base584 = require("multiformats/bases/base58");
5328
+ var envKeyDefaults = {
5329
+ SECRET: "CLOUD_SESSION_TOKEN_SECRET",
5330
+ PUBLIC: "CLOUD_SESSION_TOKEN_PUBLIC"
5331
+ };
5332
+ async function jwk2env(jwk, sthis = ensureSuperThis()) {
5333
+ const inPubKey = await (0, import_jose.exportJWK)(jwk);
5334
+ return import_base584.base58btc.encode(sthis.txt.encode(JSON.stringify(inPubKey)));
5335
+ }
5336
+ async function env2jwk(env, alg, sthis = ensureSuperThis()) {
5337
+ const inJWT = JSON.parse(sthis.txt.decode(import_base584.base58btc.decode(env)));
5338
+ return (0, import_jose.importJWK)(inJWT, alg, { extractable: true });
5339
+ }
5340
+ var SessionTokenService = class _SessionTokenService {
5341
+ #key;
5342
+ #param;
5343
+ static async generateKeyPair(alg = "ES256", options = { extractable: true }, generateKeyPairFN = (alg2, options2) => (0, import_keypair.generateKeyPair)(alg2, options2)) {
5344
+ const material = await generateKeyPairFN(alg, options);
5345
+ return {
5346
+ material,
5347
+ strings: {
5348
+ publicKey: await jwk2env(material.publicKey),
5349
+ privateKey: await jwk2env(material.privateKey)
5350
+ }
5351
+ };
5352
+ }
5353
+ static async createFromEnv(sthis, sp = {}) {
5354
+ let envToken = sthis.env.get(sp.privateEnvKey ?? envKeyDefaults.SECRET);
5355
+ if (!envToken) {
5356
+ envToken = sthis.env.get(sp.publicEnvKey ?? envKeyDefaults.PUBLIC);
5357
+ }
5358
+ if (!envToken) {
5359
+ throw new Error(
5360
+ `env not found for: ${sp.privateEnvKey ?? envKeyDefaults.SECRET} or ${sp.publicEnvKey ?? envKeyDefaults.PUBLIC}`
5361
+ );
5362
+ }
5363
+ return _SessionTokenService.create({ token: envToken }, sthis);
5364
+ }
5365
+ static async create(stsparam, sthis = ensureSuperThis()) {
5366
+ const key = await env2jwk(stsparam.token, stsparam.alg ?? "ES256", sthis);
5367
+ return new _SessionTokenService(key, stsparam);
5368
+ }
5369
+ constructor(key, stsparam) {
5370
+ this.#key = key;
5371
+ this.#param = stsparam;
5372
+ }
5373
+ get validFor() {
5374
+ let validFor = this.#param.validFor ?? 3600;
5375
+ if (!(0 <= validFor && validFor <= 36e5)) {
5376
+ validFor = 36e5;
5377
+ }
5378
+ return validFor;
5379
+ }
5380
+ get alg() {
5381
+ return this.#param.alg ?? "ES256";
5382
+ }
5383
+ get isssuer() {
5384
+ return this.#param.issuer ?? "fireproof";
5385
+ }
5386
+ get audience() {
5387
+ return this.#param.audience ?? "fireproof";
5388
+ }
5389
+ async validate(token) {
5390
+ return (0, import_cement22.exception2Result)(async () => {
5391
+ const ret = await (0, import_jose.jwtVerify)(token, this.#key);
5392
+ return ret;
5393
+ });
5394
+ }
5395
+ // async getEnvKey(): Promise<string> {
5396
+ // return jwk2env(ensureSuperThis(), this.#key);
5397
+ // }
5398
+ async tokenFor(p) {
5399
+ if (this.#key.type !== "private") {
5400
+ throw new Error("key must be private");
5401
+ }
5402
+ const token = await new import_jose.SignJWT({
5403
+ userId: p.userId,
5404
+ tenants: p.tenants,
5405
+ ledgers: p.ledgers
5406
+ }).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);
5407
+ return token;
5408
+ }
5409
+ };
5410
+
5411
+ // src/runtime/index.ts
5412
+ var import_cement29 = require("@adviser/cement");
5293
5413
 
5294
5414
  // src/runtime/gateways/index.ts
5295
5415
  var gateways_exports = {};
5296
5416
  __export(gateways_exports, {
5297
5417
  DefSerdeGateway: () => DefSerdeGateway,
5418
+ cloud: () => gateway_exports2,
5298
5419
  dbMetaEvent2Serialized: () => dbMetaEvent2Serialized,
5299
5420
  decode2DbMetaEvents: () => decode2DbMetaEvents,
5300
5421
  file: () => file_exports,
@@ -5310,8 +5431,1839 @@ __export(file_exports, {
5310
5431
  sysFileSystemFactory: () => sysFileSystemFactory
5311
5432
  });
5312
5433
 
5434
+ // src/runtime/gateways/cloud/gateway.ts
5435
+ var gateway_exports2 = {};
5436
+ __export(gateway_exports2, {
5437
+ FireproofCloudGateway: () => FireproofCloudGateway,
5438
+ registerFireproofCloudStoreProtocol: () => registerFireproofCloudStoreProtocol,
5439
+ toCloud: () => toCloud
5440
+ });
5441
+ var import_cement28 = require("@adviser/cement");
5442
+
5443
+ // src/protocols/cloud/msg-types.ts
5444
+ var VERSION = "FP-MSG-1.0";
5445
+ function isAuthTypeFPCloudJWK(a) {
5446
+ return a.type === "fp-cloud-jwk";
5447
+ }
5448
+ function isAuthTypeFPCloud(a) {
5449
+ return a.type === "fp-cloud";
5450
+ }
5451
+ function keyTenantLedger(t) {
5452
+ return `${t.tenant}:${t.ledger}`;
5453
+ }
5454
+ function qsidEqual(a, b) {
5455
+ return a.reqId === b.reqId && a.resId === b.resId;
5456
+ }
5457
+ function qsidKey(qsid) {
5458
+ return `${qsid.reqId}:${qsid.resId}`;
5459
+ }
5460
+ function MsgIsTid(msg, tid) {
5461
+ return msg.tid === tid;
5462
+ }
5463
+ function MsgIsError(rq) {
5464
+ return rq.type === "error";
5465
+ }
5466
+ function MsgIsQSError(rq) {
5467
+ return rq.res.type === "error" || rq.req.type === "error";
5468
+ }
5469
+ function coerceFPStoreTypes(s) {
5470
+ const x = s?.trim();
5471
+ if (x === "meta" || x === "car" || x === "wal" || x === "file") {
5472
+ return x;
5473
+ }
5474
+ throw new Error(`Invalid FPStoreTypes: ${s}`);
5475
+ }
5476
+ function isProtocolCapabilities(s) {
5477
+ const x = s.trim();
5478
+ return x === "reqRes" || x === "stream";
5479
+ }
5480
+ function defaultGestalt(msgP, gestalt) {
5481
+ return {
5482
+ storeTypes: ["meta", "file", "car", "wal"],
5483
+ httpEndpoints: ["/fp"],
5484
+ wsEndpoints: ["/ws"],
5485
+ encodings: ["JSON"],
5486
+ protocolCapabilities: msgP.protocolCapabilities || ["reqRes", "stream"],
5487
+ auth: [],
5488
+ requiresAuth: false,
5489
+ data: msgP.hasPersistent ? {
5490
+ inband: true,
5491
+ outband: true
5492
+ } : void 0,
5493
+ meta: msgP.hasPersistent ? {
5494
+ inband: true,
5495
+ outband: true
5496
+ } : void 0,
5497
+ wal: msgP.hasPersistent ? {
5498
+ inband: true,
5499
+ outband: true
5500
+ } : void 0,
5501
+ reqTypes: [
5502
+ "reqOpen",
5503
+ "reqGestalt",
5504
+ // "reqSignedUrl",
5505
+ "reqSubscribeMeta",
5506
+ "reqPutMeta",
5507
+ "reqBindMeta",
5508
+ "reqDelMeta",
5509
+ "reqPutData",
5510
+ "reqGetData",
5511
+ "reqDelData",
5512
+ "reqPutWAL",
5513
+ "reqGetWAL",
5514
+ "reqDelWAL",
5515
+ "reqUpdateMeta"
5516
+ ],
5517
+ resTypes: [
5518
+ "resOpen",
5519
+ "resGestalt",
5520
+ // "resSignedUrl",
5521
+ "resSubscribeMeta",
5522
+ "resPutMeta",
5523
+ "resGetMeta",
5524
+ "resDelMeta",
5525
+ "resPutData",
5526
+ "resGetData",
5527
+ "resDelData",
5528
+ "resPutWAL",
5529
+ "resGetWAL",
5530
+ "resDelWAL",
5531
+ "updateMeta"
5532
+ ],
5533
+ eventTypes: ["updateMeta"],
5534
+ ...gestalt
5535
+ };
5536
+ }
5537
+ function buildReqChat(sthis, auth, conn, message, targets) {
5538
+ return {
5539
+ tid: sthis.nextId().str,
5540
+ type: "reqChat",
5541
+ version: VERSION,
5542
+ auth,
5543
+ conn,
5544
+ message,
5545
+ targets: targets ?? []
5546
+ };
5547
+ }
5548
+ function buildResChat(req, conn, message, targets, auth) {
5549
+ return {
5550
+ ...req,
5551
+ auth: auth || req.auth,
5552
+ conn: conn || req.conn,
5553
+ message: message || req.message,
5554
+ targets: targets || req.targets,
5555
+ type: "resChat",
5556
+ version: VERSION
5557
+ };
5558
+ }
5559
+ function MsgIsReqChat(msg) {
5560
+ return msg.type === "reqChat";
5561
+ }
5562
+ function MsgIsResChat(msg) {
5563
+ return msg.type === "resChat";
5564
+ }
5565
+ function MsgIsReqGestalt(msg) {
5566
+ return msg.type === "reqGestalt";
5567
+ }
5568
+ function buildReqGestalt(sthis, auth, gestalt, publish) {
5569
+ return {
5570
+ tid: sthis.nextId().str,
5571
+ auth,
5572
+ type: "reqGestalt",
5573
+ version: VERSION,
5574
+ gestalt,
5575
+ publish
5576
+ };
5577
+ }
5578
+ function buildResGestalt(req, gestalt, auth) {
5579
+ return {
5580
+ tid: req.tid,
5581
+ auth: auth || req.auth,
5582
+ type: "resGestalt",
5583
+ version: VERSION,
5584
+ gestalt
5585
+ };
5586
+ }
5587
+ function MsgIsResGestalt(msg) {
5588
+ return msg.type === "resGestalt";
5589
+ }
5590
+ function buildReqOpen(sthis, auth, conn) {
5591
+ return {
5592
+ tid: sthis.nextId().str,
5593
+ auth,
5594
+ type: "reqOpen",
5595
+ version: VERSION,
5596
+ conn: {
5597
+ ...conn,
5598
+ reqId: conn.reqId || sthis.nextId().str
5599
+ }
5600
+ };
5601
+ }
5602
+ function MsgIsReqOpen(imsg) {
5603
+ const msg = imsg;
5604
+ return msg.type === "reqOpen" && !!msg.conn && !!msg.conn.reqId;
5605
+ }
5606
+ function MsgIsWithConn(msg) {
5607
+ const mwc = msg.conn;
5608
+ return mwc && !!mwc.reqId && !!mwc.resId;
5609
+ }
5610
+ function MsgIsWithConnAuth(msg) {
5611
+ return MsgIsWithConn(msg) && !!msg.auth && typeof msg.auth.type === "string";
5612
+ }
5613
+ function MsgIsConnected(msg, qsid) {
5614
+ return MsgIsWithConn(msg) && msg.conn.reqId === qsid.reqId && msg.conn.resId === qsid.resId;
5615
+ }
5616
+ function buildResOpen(sthis, req, resStreamId) {
5617
+ if (!(req.conn && req.conn.reqId)) {
5618
+ throw new Error("req.conn.reqId is required");
5619
+ }
5620
+ return {
5621
+ ...req,
5622
+ type: "resOpen",
5623
+ conn: {
5624
+ ...req.conn,
5625
+ resId: req.conn.resId || resStreamId || sthis.nextId().str
5626
+ }
5627
+ };
5628
+ }
5629
+ function MsgIsResOpen(msg) {
5630
+ return msg.type === "resOpen";
5631
+ }
5632
+ function MsgIsReqClose(msg) {
5633
+ return msg.type === "reqClose" && MsgIsWithConn(msg);
5634
+ }
5635
+ function MsgIsResClose(msg) {
5636
+ return msg.type === "resClose" && MsgIsWithConn(msg);
5637
+ }
5638
+ function buildResClose(req, conn) {
5639
+ return {
5640
+ ...req,
5641
+ type: "resClose",
5642
+ conn
5643
+ };
5644
+ }
5645
+ function buildReqClose(sthis, auth, conn) {
5646
+ return {
5647
+ tid: sthis.nextId().str,
5648
+ auth,
5649
+ type: "reqClose",
5650
+ version: VERSION,
5651
+ conn
5652
+ };
5653
+ }
5654
+ function buildErrorMsg(msgCtx, base, error, body, stack) {
5655
+ if (!stack && msgCtx.sthis.env.get("FP_STACK")) {
5656
+ stack = error.stack?.split("\n");
5657
+ }
5658
+ const msg = {
5659
+ auth: base.auth || { type: "error" },
5660
+ src: base,
5661
+ type: "error",
5662
+ tid: base.tid || "internal",
5663
+ message: error.message,
5664
+ version: VERSION,
5665
+ body,
5666
+ stack
5667
+ };
5668
+ msgCtx.logger.Any("ErrorMsg", msg);
5669
+ return msg;
5670
+ }
5671
+ function MsgIsTenantLedger(msg) {
5672
+ if (MsgIsWithConnAuth(msg)) {
5673
+ const t = msg.tenant;
5674
+ return !!t && !!t.tenant && !!t.ledger;
5675
+ }
5676
+ return false;
5677
+ }
5678
+ function buildReqSignedUrl(sthis, type, rparam, gwCtx) {
5679
+ return {
5680
+ tid: sthis.nextId().str,
5681
+ type,
5682
+ auth: rparam.auth,
5683
+ methodParams: rparam.methodParam,
5684
+ version: VERSION,
5685
+ ...gwCtx,
5686
+ params: rparam.params
5687
+ };
5688
+ }
5689
+ function resAuth(msg) {
5690
+ return msg.auth ? Promise.resolve(msg.auth) : Promise.reject(new Error("No Auth"));
5691
+ }
5692
+ async function buildRes(methodParams, type, msgCtx, req, ctx) {
5693
+ const psm = {
5694
+ type: "reqSignedUrl",
5695
+ auth: await resAuth(req),
5696
+ version: req.version,
5697
+ methodParams,
5698
+ params: {
5699
+ ...req.params
5700
+ },
5701
+ conn: req.conn,
5702
+ tenant: req.tenant,
5703
+ tid: req.tid
5704
+ };
5705
+ const rSignedUrl = await ctx.calculatePreSignedUrl(msgCtx, psm);
5706
+ if (rSignedUrl.isErr()) {
5707
+ return buildErrorMsg(msgCtx, req, rSignedUrl.Err());
5708
+ }
5709
+ return {
5710
+ ...req,
5711
+ params: psm.params,
5712
+ methodParams,
5713
+ type,
5714
+ signedUrl: rSignedUrl.Ok().toString()
5715
+ };
5716
+ }
5717
+
5718
+ // src/protocols/cloud/msger.ts
5719
+ var import_cement25 = require("@adviser/cement");
5720
+
5721
+ // src/protocols/cloud/http-connection.ts
5722
+ var import_cement23 = require("@adviser/cement");
5723
+
5724
+ // src/protocols/cloud/msg-raw-connection-base.ts
5725
+ var MsgRawConnectionBase = class {
5726
+ constructor(sthis, exGestalt) {
5727
+ this.onErrorFns = /* @__PURE__ */ new Map();
5728
+ this.sthis = sthis;
5729
+ this.exchangedGestalt = exGestalt;
5730
+ }
5731
+ onError(fn) {
5732
+ const key = this.sthis.nextId().str;
5733
+ this.onErrorFns.set(key, fn);
5734
+ return () => this.onErrorFns.delete(key);
5735
+ }
5736
+ buildErrorMsg(msgCtx, msg, err) {
5737
+ const rmsg = Array.from(this.onErrorFns.values()).reduce((msg2, fn) => {
5738
+ return fn(msg2, err);
5739
+ }, msg);
5740
+ const emsg = buildErrorMsg(msgCtx, rmsg, err);
5741
+ msgCtx.logger.Error().Err(err).Any("msg", rmsg).Msg("connection error");
5742
+ return emsg;
5743
+ }
5744
+ };
5745
+
5746
+ // src/protocols/cloud/http-connection.ts
5747
+ function toHttpProtocol(uri) {
5748
+ const protocol = (uri.getParam("protocol") ?? uri.protocol).replace(/:$/, "");
5749
+ const toFix = uri.build();
5750
+ switch (protocol) {
5751
+ case "ws":
5752
+ case "http":
5753
+ toFix.protocol("http");
5754
+ break;
5755
+ case "https":
5756
+ case "wss":
5757
+ default:
5758
+ toFix.protocol("https");
5759
+ break;
5760
+ }
5761
+ return toFix.URI();
5762
+ }
5763
+ function ensurePath(uri, fp) {
5764
+ const path = uri.pathname.replace(/\/$/, "").replace(/^\//, "");
5765
+ const buri = uri.build();
5766
+ if (path === "") {
5767
+ buri.appendRelative(fp);
5768
+ }
5769
+ return buri.toString();
5770
+ }
5771
+ var HttpConnection = class extends MsgRawConnectionBase {
5772
+ constructor(sthis, uris, msgP, exGestalt) {
5773
+ super(sthis, exGestalt);
5774
+ this.#onMsg = /* @__PURE__ */ new Map();
5775
+ this.activeBinds = /* @__PURE__ */ new Map();
5776
+ this.logger = ensureLogger(sthis, "HttpConnection");
5777
+ this.baseURIs = uris.map((uri) => ({
5778
+ in: uri,
5779
+ cleaned: toHttpProtocol(uri)
5780
+ }));
5781
+ this.msgP = msgP;
5782
+ }
5783
+ #onMsg;
5784
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5785
+ send(_msg) {
5786
+ throw new Error("Method not implemented.");
5787
+ }
5788
+ async start() {
5789
+ return import_cement23.Result.Ok(void 0);
5790
+ }
5791
+ async close() {
5792
+ await Promise.all(Array.from(this.activeBinds.values()).map((state) => state.controller?.close()));
5793
+ this.#onMsg.clear();
5794
+ return import_cement23.Result.Ok(void 0);
5795
+ }
5796
+ toMsg(msg) {
5797
+ this.#onMsg.forEach((fn) => fn(msg));
5798
+ return msg;
5799
+ }
5800
+ onMsg(fn) {
5801
+ const key = this.sthis.nextId().str;
5802
+ this.#onMsg.set(key, fn);
5803
+ return () => this.#onMsg.delete(key);
5804
+ }
5805
+ #poll(state) {
5806
+ this.request(state.bind.msg, state.bind.opts).then((msg) => {
5807
+ try {
5808
+ state.controller?.enqueue(msg);
5809
+ if (MsgIsError(msg)) {
5810
+ state.controller?.close();
5811
+ } else {
5812
+ state.timeout = setTimeout(() => this.#poll(state), state.bind.opts.pollInterval ?? 1e3);
5813
+ }
5814
+ } catch (err) {
5815
+ state.controller?.error(err);
5816
+ state.controller?.close();
5817
+ }
5818
+ }).catch((err) => {
5819
+ state.controller?.error(err);
5820
+ });
5821
+ }
5822
+ bind(req, opts) {
5823
+ const state = {
5824
+ id: this.sthis.nextId().str,
5825
+ bind: {
5826
+ msg: req,
5827
+ opts
5828
+ }
5829
+ };
5830
+ this.activeBinds.set(state.id, state);
5831
+ return new ReadableStream({
5832
+ cancel: () => {
5833
+ clearTimeout(state.timeout);
5834
+ this.activeBinds.delete(state.id);
5835
+ },
5836
+ start: (controller) => {
5837
+ state.controller = controller;
5838
+ this.#poll(state);
5839
+ }
5840
+ });
5841
+ }
5842
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5843
+ async request(req, _opts) {
5844
+ const headers = import_cement23.HttpHeader.from();
5845
+ headers.Set("Content-Type", this.msgP.mime);
5846
+ headers.Set("Accept", this.msgP.mime);
5847
+ const rReqBody = (0, import_cement23.exception2Result)(() => this.msgP.ende.encode(req));
5848
+ if (rReqBody.isErr()) {
5849
+ return this.toMsg(
5850
+ buildErrorMsg(this, req, this.logger.Error().Err(rReqBody.Err()).Any("req", req).Msg("encode error").AsError())
5851
+ );
5852
+ }
5853
+ headers.Set("Content-Length", rReqBody.Ok().byteLength.toString());
5854
+ const url = selectRandom(this.baseURIs);
5855
+ this.logger.Debug().Any(url).Any("body", req).Msg("request");
5856
+ const rRes = await (0, import_cement23.exception2Result)(
5857
+ () => timeout(
5858
+ this.msgP.timeout,
5859
+ fetch(ensurePath(url.cleaned, "fp"), {
5860
+ method: "PUT",
5861
+ headers: headers.AsHeaderInit(),
5862
+ body: rReqBody.Ok()
5863
+ })
5864
+ )
5865
+ );
5866
+ this.logger.Debug().Any(url).Any("body", rRes).Msg("response");
5867
+ if (rRes.isErr()) {
5868
+ return this.toMsg(buildErrorMsg(this, req, this.logger.Error().Err(rRes).Any(url).Msg("fetch error").AsError()));
5869
+ }
5870
+ const res = rRes.Ok();
5871
+ if (!res.ok) {
5872
+ const data2 = new Uint8Array(await res.arrayBuffer());
5873
+ const ret2 = await (0, import_cement23.exception2Result)(async () => this.msgP.ende.decode(data2));
5874
+ if (ret2.isErr() || !MsgIsError(ret2.Ok())) {
5875
+ return this.toMsg(
5876
+ buildErrorMsg(
5877
+ this,
5878
+ req,
5879
+ this.logger.Error().Any(url).Str("status", res.status.toString()).Str("statusText", res.statusText).Msg("HTTP Error").AsError(),
5880
+ await res.text()
5881
+ )
5882
+ );
5883
+ }
5884
+ return this.toMsg(ret2.Ok());
5885
+ }
5886
+ const data = new Uint8Array(await res.arrayBuffer());
5887
+ const ret = await (0, import_cement23.exception2Result)(async () => this.msgP.ende.decode(data));
5888
+ if (ret.isErr()) {
5889
+ return this.toMsg(
5890
+ buildErrorMsg(this, req, this.logger.Error().Err(ret.Err()).Msg("decode error").AsError(), this.sthis.txt.decode(data))
5891
+ );
5892
+ }
5893
+ return this.toMsg(ret.Ok());
5894
+ }
5895
+ // toOnMessage<T extends MsgBase>(msg: WithErrorMsg<T>): Result<WithErrorMsg<T>> {
5896
+ // this.mec.msgFn?.(msg as unknown as MessageEvent<MsgBase>);
5897
+ // return Result.Ok(msg);
5898
+ // }
5899
+ };
5900
+
5901
+ // src/protocols/cloud/ws-connection.ts
5902
+ var import_cement24 = require("@adviser/cement");
5903
+ var WSConnection = class extends MsgRawConnectionBase {
5904
+ constructor(sthis, ws, msgP, exGestalt) {
5905
+ super(sthis, exGestalt);
5906
+ // readonly baseURI: URI;
5907
+ this.#onMsg = /* @__PURE__ */ new Map();
5908
+ this.#onClose = /* @__PURE__ */ new Map();
5909
+ this.waitForTid = /* @__PURE__ */ new Map();
5910
+ this.opened = false;
5911
+ this.#wsOnMessage = async (event) => {
5912
+ const rMsg = await (0, import_cement24.exception2Result)(() => this.msgP.ende.decode(event.data));
5913
+ if (rMsg.isErr()) {
5914
+ this.logger.Error().Err(rMsg).Any(event.data).Msg("Invalid message");
5915
+ return;
5916
+ }
5917
+ const msg = rMsg.Ok();
5918
+ const waitFor = this.waitForTid.get(msg.tid);
5919
+ Array.from(this.#onMsg.values()).forEach((cb) => {
5920
+ cb(msg);
5921
+ });
5922
+ if (waitFor) {
5923
+ if (MsgIsError(msg)) {
5924
+ this.waitForTid.delete(msg.tid);
5925
+ waitFor.future.resolve(msg);
5926
+ } else if (waitFor.waitFor(msg)) {
5927
+ this.waitForTid.delete(msg.tid);
5928
+ waitFor.future.resolve(msg);
5929
+ } else {
5930
+ this.waitForTid.delete(msg.tid);
5931
+ waitFor.future.resolve(msg);
5932
+ }
5933
+ }
5934
+ };
5935
+ this.activeBinds = /* @__PURE__ */ new Map();
5936
+ this.id = sthis.nextId().str;
5937
+ this.logger = ensureLogger(sthis, "WSConnection");
5938
+ this.msgP = msgP;
5939
+ this.ws = ws;
5940
+ }
5941
+ #onMsg;
5942
+ #onClose;
5943
+ async start() {
5944
+ const onOpenFuture = new import_cement24.Future();
5945
+ const timer = setTimeout(() => {
5946
+ const err = this.logger.Error().Dur("timeout", this.msgP.timeout).Msg("Timeout").AsError();
5947
+ this.toMsg(buildErrorMsg(this, {}, err));
5948
+ onOpenFuture.resolve(import_cement24.Result.Err(err));
5949
+ }, this.msgP.timeout);
5950
+ this.ws.onopen = () => {
5951
+ onOpenFuture.resolve(import_cement24.Result.Ok(void 0));
5952
+ this.opened = true;
5953
+ };
5954
+ this.ws.onerror = (ierr) => {
5955
+ const err = this.logger.Error().Err(ierr).Msg("WS Error").AsError();
5956
+ onOpenFuture.resolve(import_cement24.Result.Err(err));
5957
+ const res = this.buildErrorMsg(this, {}, err);
5958
+ this.toMsg(res);
5959
+ };
5960
+ this.ws.onmessage = (evt) => {
5961
+ if (!this.opened) {
5962
+ this.toMsg(buildErrorMsg(this, {}, this.logger.Error().Msg("Received message before onOpen").AsError()));
5963
+ }
5964
+ this.#wsOnMessage(evt);
5965
+ };
5966
+ this.ws.onclose = () => {
5967
+ this.opened = false;
5968
+ this.close().catch((ierr) => {
5969
+ const err = this.logger.Error().Err(ierr).Msg("close error").AsError();
5970
+ onOpenFuture.resolve(import_cement24.Result.Err(err));
5971
+ this.toMsg(buildErrorMsg(this, { tid: "internal" }, err));
5972
+ });
5973
+ };
5974
+ const rOpen = await onOpenFuture.asPromise().finally(() => {
5975
+ clearTimeout(timer);
5976
+ });
5977
+ if (rOpen.isErr()) {
5978
+ return rOpen;
5979
+ }
5980
+ return import_cement24.Result.Ok(void 0);
5981
+ }
5982
+ #wsOnMessage;
5983
+ async close() {
5984
+ this.#onClose.forEach((fn) => fn());
5985
+ this.#onClose.clear();
5986
+ this.#onMsg.clear();
5987
+ this.ws.close();
5988
+ return import_cement24.Result.Ok(void 0);
5989
+ }
5990
+ toMsg(msg) {
5991
+ this.#onMsg.forEach((fn) => fn(msg));
5992
+ return msg;
5993
+ }
5994
+ send(msg) {
5995
+ this.ws.send(this.msgP.ende.encode(msg));
5996
+ return Promise.resolve(msg);
5997
+ }
5998
+ onMsg(fn) {
5999
+ const key = this.sthis.nextId().str;
6000
+ this.#onMsg.set(key, fn);
6001
+ return () => this.#onMsg.delete(key);
6002
+ }
6003
+ onClose(fn) {
6004
+ const key = this.sthis.nextId().str;
6005
+ this.#onClose.set(key, fn);
6006
+ return () => this.#onClose.delete(key);
6007
+ }
6008
+ bind(req, opts) {
6009
+ const state = {
6010
+ id: this.sthis.nextId().str,
6011
+ bind: {
6012
+ msg: req,
6013
+ opts
6014
+ }
6015
+ // timeout: undefined,
6016
+ // controller: undefined,
6017
+ };
6018
+ this.activeBinds.set(state.id, state);
6019
+ return new ReadableStream({
6020
+ cancel: () => {
6021
+ this.activeBinds.delete(state.id);
6022
+ },
6023
+ start: (controller) => {
6024
+ this.onMsg((msg) => {
6025
+ if (MsgIsError(msg)) {
6026
+ controller.enqueue(msg);
6027
+ return;
6028
+ }
6029
+ if (!MsgIsTid(msg, req.tid)) {
6030
+ return;
6031
+ }
6032
+ if (opts.waitFor && opts.waitFor(msg)) {
6033
+ controller.enqueue(msg);
6034
+ }
6035
+ });
6036
+ this.send(req);
6037
+ const future = new import_cement24.Future();
6038
+ this.waitForTid.set(req.tid, { tid: req.tid, future, waitFor: opts.waitFor, timeout: opts.timeout });
6039
+ future.asPromise().then((msg) => {
6040
+ if (MsgIsError(msg)) {
6041
+ controller.enqueue(msg);
6042
+ controller.close();
6043
+ }
6044
+ });
6045
+ }
6046
+ });
6047
+ }
6048
+ async request(req, opts) {
6049
+ if (!this.opened) {
6050
+ return buildErrorMsg(this, req, this.logger.Error().Msg("Connection not open").AsError());
6051
+ }
6052
+ const future = new import_cement24.Future();
6053
+ this.waitForTid.set(req.tid, { tid: req.tid, future, waitFor: opts.waitFor, timeout: opts.timeout });
6054
+ await this.send(req);
6055
+ return future.asPromise();
6056
+ }
6057
+ // toOnMessage<T extends MsgBase>(msg: WithErrorMsg<T>): Result<WithErrorMsg<T>> {
6058
+ // this.mec.msgFn?.(msg as unknown as MessageEvent<MsgBase>);
6059
+ // return Result.Ok(msg);
6060
+ // }
6061
+ };
6062
+
6063
+ // src/protocols/cloud/msger.ts
6064
+ function selectRandom(arr) {
6065
+ return arr[Math.floor(Math.random() * arr.length)];
6066
+ }
6067
+ function timeout(ms, promise) {
6068
+ return new Promise((resolve, reject) => {
6069
+ const timer = setTimeout(() => {
6070
+ reject(new Error(`TIMEOUT after ${ms}ms`));
6071
+ }, ms);
6072
+ promise.then(resolve).catch(reject).finally(() => clearTimeout(timer));
6073
+ });
6074
+ }
6075
+ function jsonEnDe(sthis) {
6076
+ return {
6077
+ encode: (node) => sthis.txt.encode(JSON.stringify(node)),
6078
+ decode: (data) => JSON.parse(sthis.txt.decode(data))
6079
+ };
6080
+ }
6081
+ function defaultMsgParams(sthis, igs) {
6082
+ return {
6083
+ mime: "application/json",
6084
+ ende: jsonEnDe(sthis),
6085
+ timeout: 3e3,
6086
+ protocolCapabilities: ["reqRes", "stream"],
6087
+ ...igs
6088
+ };
6089
+ }
6090
+ async function applyStart(prC) {
6091
+ const rC = await prC;
6092
+ if (rC.isErr()) {
6093
+ return rC;
6094
+ }
6095
+ const c = rC.Ok();
6096
+ const r = await c.start();
6097
+ if (r.isErr()) {
6098
+ return import_cement25.Result.Err(r.Err());
6099
+ }
6100
+ return rC;
6101
+ }
6102
+ async function authTypeFromUri(logger, curi) {
6103
+ const uri = import_cement25.URI.from(curi);
6104
+ const authJWK = uri.getParam("authJWK");
6105
+ if (!authJWK) {
6106
+ return logger.Error().Url(uri).Msg("authJWK is required").ResultError();
6107
+ }
6108
+ return import_cement25.Result.Ok({
6109
+ type: "fp-cloud-jwk",
6110
+ params: {
6111
+ // claim: fpc.Ok().payload,
6112
+ jwk: authJWK
6113
+ }
6114
+ });
6115
+ }
6116
+ var MsgConnected = class _MsgConnected {
6117
+ static async connect(auth, mrc, conn = {}) {
6118
+ if (import_cement25.Result.Is(mrc)) {
6119
+ if (mrc.isErr()) {
6120
+ return import_cement25.Result.Err(mrc.Err());
6121
+ }
6122
+ mrc = mrc.Ok();
6123
+ }
6124
+ const res = await mrc.request(buildReqOpen(mrc.sthis, auth, conn), { waitFor: MsgIsResOpen });
6125
+ if (MsgIsError(res) || !MsgIsResOpen(res)) {
6126
+ return mrc.sthis.logger.Error().Err(res).Msg("unexpected response").ResultError();
6127
+ }
6128
+ return import_cement25.Result.Ok(new _MsgConnected(mrc, res.conn));
6129
+ }
6130
+ constructor(raw2, conn) {
6131
+ this.sthis = raw2.sthis;
6132
+ this.raw = raw2;
6133
+ this.exchangedGestalt = raw2.exchangedGestalt;
6134
+ this.conn = conn;
6135
+ this.activeBinds = raw2.activeBinds;
6136
+ this.id = this.sthis.nextId().str;
6137
+ }
6138
+ attachAuth(auth) {
6139
+ return new MsgConnectedAuth(this, auth);
6140
+ }
6141
+ };
6142
+ var MsgConnectedAuth = class {
6143
+ constructor(conn, authFactory) {
6144
+ this.id = conn.id;
6145
+ this.raw = conn.raw;
6146
+ this.conn = conn.conn;
6147
+ this.sthis = conn.sthis;
6148
+ this.authFactory = authFactory;
6149
+ this.exchangedGestalt = conn.exchangedGestalt;
6150
+ this.activeBinds = conn.activeBinds;
6151
+ }
6152
+ bind(req, opts) {
6153
+ const stream = this.raw.bind({ ...req, conn: req.conn || this.conn }, opts);
6154
+ const ts = new TransformStream({
6155
+ transform: (chunk, controller) => {
6156
+ if (!MsgIsTid(chunk, req.tid)) {
6157
+ return;
6158
+ }
6159
+ if (MsgIsConnected(chunk, this.conn)) {
6160
+ if (opts.waitFor?.(chunk) || MsgIsError(chunk)) {
6161
+ controller.enqueue(chunk);
6162
+ }
6163
+ }
6164
+ }
6165
+ });
6166
+ stream.pipeThrough(ts);
6167
+ return ts.readable;
6168
+ }
6169
+ authType() {
6170
+ return this.authFactory();
6171
+ }
6172
+ msgConnAuth() {
6173
+ return this.authType().then((r) => {
6174
+ if (r.isErr()) {
6175
+ return import_cement25.Result.Err(r);
6176
+ }
6177
+ return import_cement25.Result.Ok({ conn: this.conn, auth: r.Ok() });
6178
+ });
6179
+ }
6180
+ request(req, opts) {
6181
+ return this.raw.request({ ...req, conn: req.conn || this.conn }, opts);
6182
+ }
6183
+ send(msg) {
6184
+ return this.raw.send({ ...msg, conn: msg.conn || this.conn });
6185
+ }
6186
+ start() {
6187
+ return this.raw.start();
6188
+ }
6189
+ async close(t) {
6190
+ await this.request(buildReqClose(this.sthis, t.auth, this.conn), { waitFor: MsgIsResClose });
6191
+ return await this.raw.close(t);
6192
+ }
6193
+ onMsg(msgFn) {
6194
+ return this.raw.onMsg((msg) => {
6195
+ if (MsgIsConnected(msg, this.conn)) {
6196
+ msgFn(msg);
6197
+ }
6198
+ });
6199
+ }
6200
+ };
6201
+ function initialFPUri(curl) {
6202
+ let gestaltUrl = import_cement25.URI.from(curl);
6203
+ if (["", "/"].includes(gestaltUrl.pathname)) {
6204
+ gestaltUrl = gestaltUrl.build().appendRelative("/fp").URI();
6205
+ }
6206
+ return gestaltUrl;
6207
+ }
6208
+ var Msger = class _Msger {
6209
+ static async openHttp(sthis, urls, msgP, exGestalt) {
6210
+ return import_cement25.Result.Ok(new HttpConnection(sthis, urls, msgP, exGestalt));
6211
+ }
6212
+ static async openWS(sthis, url, msgP, exGestalt) {
6213
+ let ws;
6214
+ url = url.build().setParam("random", sthis.nextId().str).URI();
6215
+ const wsUrl = ensurePath(url, "ws");
6216
+ if ((0, import_cement25.runtimeFn)().isNodeIsh) {
6217
+ const { WebSocket: WebSocket2 } = await import("ws");
6218
+ ws = new WebSocket2(wsUrl);
6219
+ } else {
6220
+ ws = new WebSocket(wsUrl);
6221
+ }
6222
+ return import_cement25.Result.Ok(new WSConnection(sthis, ws, msgP, exGestalt));
6223
+ }
6224
+ static async open(sthis, auth, curl, imsgP = {}) {
6225
+ const jsMsgP = defaultMsgParams(sthis, { ...imsgP, mime: "application/json", ende: jsonEnDe(sthis) });
6226
+ const gestaltUrl = initialFPUri(curl);
6227
+ const gs = defaultGestalt(defaultMsgParams(sthis, imsgP), { id: "FP-Universal-Client" });
6228
+ const rHC = await _Msger.openHttp(sthis, [gestaltUrl], jsMsgP, { my: gs, remote: gs });
6229
+ if (rHC.isErr()) {
6230
+ return rHC;
6231
+ }
6232
+ const hc = rHC.Ok();
6233
+ const resGestalt = await hc.request(buildReqGestalt(sthis, auth, gs), {
6234
+ waitFor: MsgIsResGestalt
6235
+ });
6236
+ if (!MsgIsResGestalt(resGestalt)) {
6237
+ return sthis.logger.Error().Any({ resGestalt }).Msg("should be ResGestalt").ResultError();
6238
+ }
6239
+ await hc.close(
6240
+ resGestalt
6241
+ /* as MsgWithConnAuth */
6242
+ );
6243
+ const exGt = { my: gs, remote: resGestalt.gestalt };
6244
+ const msgP = defaultMsgParams(sthis, imsgP);
6245
+ if (exGt.remote.protocolCapabilities.includes("reqRes") && !exGt.remote.protocolCapabilities.includes("stream")) {
6246
+ return applyStart(
6247
+ _Msger.openHttp(
6248
+ sthis,
6249
+ exGt.remote.httpEndpoints.map((i) => import_cement25.BuildURI.from(curl).resolve(i).URI()),
6250
+ msgP,
6251
+ exGt
6252
+ )
6253
+ );
6254
+ }
6255
+ const wsUrl = import_cement25.BuildURI.from(gestaltUrl).resolve(selectRandom(exGt.remote.wsEndpoints)).URI();
6256
+ return applyStart(_Msger.openWS(sthis, wsUrl, msgP, exGt));
6257
+ }
6258
+ static connect(sthis, auth, curl, imsgP = {}, conn = {}) {
6259
+ return _Msger.open(sthis, auth, curl, imsgP).then((srv) => MsgConnected.connect(auth, srv, conn));
6260
+ }
6261
+ constructor() {
6262
+ }
6263
+ };
6264
+
6265
+ // src/protocols/cloud/msg-types-data.ts
6266
+ function buildReqGetData(sthis, sup, ctx) {
6267
+ return buildReqSignedUrl(sthis, "reqGetData", sup, ctx);
6268
+ }
6269
+ function MsgIsReqGetData(msg) {
6270
+ return msg.type === "reqGetData";
6271
+ }
6272
+ function MsgIsResGetData(msg) {
6273
+ return msg.type === "resGetData" && MsgIsTenantLedger(msg);
6274
+ }
6275
+ function buildResGetData(msgCtx, req, ctx) {
6276
+ return buildRes(
6277
+ { method: "GET", store: req.methodParams.store },
6278
+ "resGetData",
6279
+ msgCtx,
6280
+ req,
6281
+ ctx
6282
+ );
6283
+ }
6284
+ function MsgIsReqPutData(msg) {
6285
+ return msg.type === "reqPutData";
6286
+ }
6287
+ function buildReqPutData(sthis, sup, ctx) {
6288
+ return buildReqSignedUrl(sthis, "reqPutData", sup, ctx);
6289
+ }
6290
+ function MsgIsResPutData(msg) {
6291
+ return msg.type === "resPutData";
6292
+ }
6293
+ function buildResPutData(msgCtx, req, ctx) {
6294
+ return buildRes(
6295
+ { method: "PUT", store: req.methodParams.store },
6296
+ "resPutData",
6297
+ msgCtx,
6298
+ req,
6299
+ ctx
6300
+ );
6301
+ }
6302
+ function MsgIsReqDelData(msg) {
6303
+ return msg.type === "reqDelData";
6304
+ }
6305
+ function buildReqDelData(sthis, sup, ctx) {
6306
+ return buildReqSignedUrl(sthis, "reqDelData", sup, ctx);
6307
+ }
6308
+ function MsgIsResDelData(msg) {
6309
+ return msg.type === "resDelData";
6310
+ }
6311
+ function buildResDelData(msgCtx, req, ctx) {
6312
+ return buildRes(
6313
+ { method: "DELETE", store: req.methodParams.store },
6314
+ "resDelData",
6315
+ msgCtx,
6316
+ req,
6317
+ ctx
6318
+ );
6319
+ }
6320
+
6321
+ // src/protocols/cloud/msg-types-meta.ts
6322
+ var import_cement26 = require("@adviser/cement");
6323
+ function buildReqPutMeta(sthis, auth, signedUrlParams, meta, gwCtx) {
6324
+ return {
6325
+ auth,
6326
+ tid: sthis.nextId().str,
6327
+ type: "reqPutMeta",
6328
+ ...gwCtx,
6329
+ version: import_cement26.VERSION,
6330
+ methodParams: {
6331
+ method: "PUT",
6332
+ store: "meta"
6333
+ },
6334
+ params: signedUrlParams,
6335
+ meta
6336
+ };
6337
+ }
6338
+ function MsgIsReqPutMeta(msg) {
6339
+ return msg.type === "reqPutMeta";
6340
+ }
6341
+ function buildResPutMeta(_msgCtx, req, meta, signedUrl) {
6342
+ return {
6343
+ meta,
6344
+ tid: req.tid,
6345
+ conn: req.conn,
6346
+ auth: req.auth,
6347
+ methodParams: req.methodParams,
6348
+ params: req.params,
6349
+ tenant: req.tenant,
6350
+ type: "resPutMeta",
6351
+ signedUrl,
6352
+ version: import_cement26.VERSION
6353
+ };
6354
+ }
6355
+ function MsgIsResPutMeta(qs) {
6356
+ return qs.type === "resPutMeta";
6357
+ }
6358
+ function MsgIsBindGetMeta(msg) {
6359
+ return msg.type === "bindGetMeta";
6360
+ }
6361
+ function buildBindGetMeta(sthis, auth, params, gwCtx) {
6362
+ return {
6363
+ auth,
6364
+ tid: sthis.nextId().str,
6365
+ ...gwCtx,
6366
+ type: "bindGetMeta",
6367
+ version: import_cement26.VERSION,
6368
+ params
6369
+ };
6370
+ }
6371
+ function buildEventGetMeta(_msgCtx, req, meta, gwCtx, signedUrl) {
6372
+ return {
6373
+ conn: gwCtx.conn,
6374
+ tenant: req.tenant,
6375
+ auth: req.auth,
6376
+ tid: req.tid,
6377
+ meta,
6378
+ signedUrl,
6379
+ type: "eventGetMeta",
6380
+ params: req.params,
6381
+ methodParams: { method: "GET", store: "meta" },
6382
+ version: import_cement26.VERSION
6383
+ };
6384
+ }
6385
+ function MsgIsEventGetMeta(qs) {
6386
+ return qs.type === "eventGetMeta";
6387
+ }
6388
+ function buildReqDelMeta(sthis, auth, params, gwCtx, meta) {
6389
+ return {
6390
+ auth,
6391
+ tid: sthis.nextId().str,
6392
+ tenant: gwCtx.tenant,
6393
+ conn: gwCtx.conn,
6394
+ params,
6395
+ meta,
6396
+ type: "reqDelMeta",
6397
+ version: import_cement26.VERSION
6398
+ // params: signedUrlParams,
6399
+ };
6400
+ }
6401
+ function MsgIsReqDelMeta(msg) {
6402
+ return msg.type === "reqDelMeta";
6403
+ }
6404
+ function buildResDelMeta(req, params, signedUrl) {
6405
+ return {
6406
+ auth: req.auth,
6407
+ methodParams: { method: "DELETE", store: "meta" },
6408
+ params,
6409
+ signedUrl,
6410
+ tid: req.tid,
6411
+ conn: req.conn,
6412
+ tenant: req.tenant,
6413
+ type: "resDelMeta",
6414
+ // key: req.key,
6415
+ version: import_cement26.VERSION
6416
+ };
6417
+ }
6418
+ function MsgIsResDelMeta(qs) {
6419
+ return qs.type === "resDelMeta";
6420
+ }
6421
+
6422
+ // src/runtime/meta-key-hack.ts
6423
+ var import_cement27 = require("@adviser/cement");
6424
+ function fromV1toV2SerializedMetaKey(v1s, keys = []) {
6425
+ const res = v1s.reduce(
6426
+ (acc, v1) => {
6427
+ const keys2 = [];
6428
+ if (v1.key) {
6429
+ if (typeof v1.key === "string") {
6430
+ acc.keys.add(v1.key);
6431
+ } else {
6432
+ keys2.push(...v1.key);
6433
+ }
6434
+ }
6435
+ if (v1.keys) {
6436
+ keys2.push(...v1.keys);
6437
+ }
6438
+ for (const key of keys2) {
6439
+ acc.keys.add(key);
6440
+ }
6441
+ if (typeof v1.cid === "string" && (!v1.data || typeof v1.data === "string") && (!v1.parents || Array.isArray(v1.parents))) {
6442
+ acc.metas.set(v1.cid, {
6443
+ data: v1.data ?? "",
6444
+ parents: v1.parents ?? [],
6445
+ cid: v1.cid
6446
+ });
6447
+ }
6448
+ return acc;
6449
+ },
6450
+ {
6451
+ metas: /* @__PURE__ */ new Map(),
6452
+ keys: new Set(keys)
6453
+ }
6454
+ );
6455
+ return {
6456
+ metas: Array.from(res.metas.values()),
6457
+ keys: Array.from(res.keys)
6458
+ };
6459
+ }
6460
+ function isV2SerializedMetaKey(or) {
6461
+ const my = or;
6462
+ return my !== null && (!my.keys || Array.isArray(my.keys)) && (!my.metas || Array.isArray(my.metas));
6463
+ }
6464
+ function toV2SerializedMetaKey(or) {
6465
+ if (Array.isArray(or)) {
6466
+ return fromV1toV2SerializedMetaKey(or);
6467
+ }
6468
+ if (isV2SerializedMetaKey(or)) {
6469
+ return fromV1toV2SerializedMetaKey(or.metas ?? [], or.keys ?? []);
6470
+ }
6471
+ throw new Error("not a valid serialized meta key");
6472
+ }
6473
+ async function V2SerializedMetaKeyExtractKey(ctx, v2) {
6474
+ const kb = await ctx.loader.keyBag();
6475
+ if (!kb) {
6476
+ return Promise.resolve(import_cement27.Result.Err(new Error("missing keybag")));
6477
+ }
6478
+ const dataUrl = await ctx.loader.attachedStores.local().active.car.url();
6479
+ const keyName = dataUrl.getParam(PARAM.STORE_KEY);
6480
+ if (!keyName) {
6481
+ ctx.loader.sthis.logger.Warn().Url(dataUrl).Msg("missing store key");
6482
+ } else {
6483
+ const rKey = await kb.getNamedKey(keyName);
6484
+ if (rKey.isErr()) {
6485
+ ctx.loader.sthis.logger.Warn().Str("keyName", keyName).Msg("did not found a extractable key");
6486
+ } else {
6487
+ for (const keyStr of v2.keys) {
6488
+ const res = await rKey.Ok().upsert(keyStr, false);
6489
+ if (res.isErr()) {
6490
+ ctx.loader.sthis.logger.Warn().Str("keyStr", keyStr).Msg("failed to upsert key");
6491
+ }
6492
+ }
6493
+ }
6494
+ }
6495
+ return Promise.resolve(import_cement27.Result.Ok(v2.metas));
6496
+ }
6497
+ async function decodeAsToSerializedMeta(ctx, raw2) {
6498
+ const rJsObj = (0, import_cement27.exception2Result)(() => JSON.parse(ctx.loader.sthis.txt.decode(raw2)));
6499
+ if (rJsObj.isErr()) {
6500
+ return import_cement27.Result.Err(rJsObj);
6501
+ }
6502
+ const v2 = toV2SerializedMetaKey(rJsObj.unwrap());
6503
+ const metas = await V2SerializedMetaKeyExtractKey(ctx, v2);
6504
+ if (metas.isErr()) {
6505
+ return import_cement27.Result.Err(metas);
6506
+ }
6507
+ return import_cement27.Result.Ok({
6508
+ metas: metas.Ok(),
6509
+ keys: v2.keys
6510
+ });
6511
+ }
6512
+ function addKeyToDbMetaDecoder(ctx) {
6513
+ const lastDecodedMetas = ctx.lastDecodedMetas ?? [];
6514
+ return {
6515
+ ...ctx,
6516
+ lastDecodedMetas,
6517
+ decoder: {
6518
+ meta: async (sthis, raw2) => {
6519
+ const r = await decodeAsToSerializedMeta(ctx, raw2);
6520
+ if (r.isErr()) {
6521
+ return Promise.resolve(import_cement27.Result.Err(r));
6522
+ }
6523
+ if (lastDecodedMetas.length > 2) {
6524
+ lastDecodedMetas.shift();
6525
+ }
6526
+ lastDecodedMetas.push(r.Ok());
6527
+ return Promise.resolve(import_cement27.Result.Ok(r.Ok().metas));
6528
+ }
6529
+ }
6530
+ };
6531
+ }
6532
+ async function wrapEncode(ctx, payload, fn) {
6533
+ const carStore = ctx.loader.attachedStores.local().active.car;
6534
+ const kb = await ctx.loader.keyBag();
6535
+ if (!kb) {
6536
+ return Promise.resolve(import_cement27.Result.Err(new Error("missing keybag")));
6537
+ }
6538
+ const keyName = carStore.url().getParam(PARAM.STORE_KEY) ?? "";
6539
+ const rKex = await kb.getNamedKey(keyName);
6540
+ if (rKex.isErr()) {
6541
+ return Promise.resolve(import_cement27.Result.Err(rKex.Err()));
6542
+ }
6543
+ const keyMaterials = await rKex.Ok().asKeysItem().then((i) => Object.values(i.keys).map((i2) => i2.key));
6544
+ return Promise.resolve(import_cement27.Result.Ok(fn(payload, keyMaterials)));
6545
+ }
6546
+ function encodeAsV1SerializedMetaKey(ctx, payload) {
6547
+ return wrapEncode(ctx, payload, (payload2, keyM) => payload2.map((p) => ({ ...p, key: keyM })));
6548
+ }
6549
+ function encodeAsV2SerializedMetaKey(ctx, payload) {
6550
+ return wrapEncode(
6551
+ ctx,
6552
+ payload,
6553
+ (payload2, keyM) => ({
6554
+ metas: payload2,
6555
+ keys: keyM
6556
+ })
6557
+ );
6558
+ }
6559
+ function addKeyToDbMetaEncoder(ctx, version) {
6560
+ return {
6561
+ ...ctx,
6562
+ encoder: {
6563
+ meta: async (sthis, payload) => {
6564
+ let obj;
6565
+ switch (version) {
6566
+ case "v1":
6567
+ obj = await encodeAsV1SerializedMetaKey(ctx, payload);
6568
+ break;
6569
+ case "v2":
6570
+ obj = await encodeAsV2SerializedMetaKey(ctx, payload);
6571
+ break;
6572
+ default:
6573
+ return Promise.resolve(import_cement27.Result.Err(`unknown version:[${version}]`));
6574
+ }
6575
+ if (obj.isErr()) {
6576
+ return Promise.resolve(import_cement27.Result.Err(obj));
6577
+ }
6578
+ try {
6579
+ return Promise.resolve(import_cement27.Result.Ok(sthis.txt.encode(JSON.stringify(obj.Ok()))));
6580
+ } catch (e) {
6581
+ return Promise.resolve(import_cement27.Result.Err(e));
6582
+ }
6583
+ }
6584
+ }
6585
+ };
6586
+ }
6587
+ var AddKeyToDbMetaGateway = class {
6588
+ constructor(gw, version) {
6589
+ // only for tests
6590
+ this.lastDecodedMetas = [];
6591
+ this.sdGw = new DefSerdeGateway(gw);
6592
+ this.version = version;
6593
+ }
6594
+ buildUrl(ctx, baseUrl, key) {
6595
+ return this.sdGw.buildUrl(ctx, baseUrl, key);
6596
+ }
6597
+ start(ctx, baseUrl) {
6598
+ return this.sdGw.start(ctx, baseUrl);
6599
+ }
6600
+ close(ctx, baseUrl) {
6601
+ return this.sdGw.close(ctx, baseUrl);
6602
+ }
6603
+ async put(ctx, url, body) {
6604
+ return this.sdGw.put(addKeyToDbMetaEncoder(ctx, this.version), url, body);
6605
+ }
6606
+ async get(ctx, url) {
6607
+ return this.sdGw.get(addKeyToDbMetaDecoder({ ...ctx, lastDecodedMetas: this.lastDecodedMetas }), url);
6608
+ }
6609
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6610
+ delete(ctx, url, loader) {
6611
+ return this.sdGw.delete(ctx, url);
6612
+ }
6613
+ subscribe(ctx, url, callback) {
6614
+ return this.sdGw.subscribe(addKeyToDbMetaDecoder({ ...ctx, lastDecodedMetas: this.lastDecodedMetas }), url, callback);
6615
+ }
6616
+ getPlain(ctx, url, key) {
6617
+ return this.sdGw.getPlain(ctx, url, key);
6618
+ }
6619
+ destroy(ctx, baseUrl) {
6620
+ return this.sdGw.destroy(ctx, baseUrl);
6621
+ }
6622
+ };
6623
+
6624
+ // src/runtime/gateways/cloud/gateway.ts
6625
+ var VERSION3 = "v0.1-fp-cloud";
6626
+ var BaseGateway = class {
6627
+ constructor(sthis, module2) {
6628
+ this.sthis = sthis;
6629
+ this.logger = ensureLogger(sthis, module2);
6630
+ }
6631
+ async buildReqSignedUrl(type, method, store, uri, conn) {
6632
+ const rParams = uri.getParamsResult({
6633
+ key: import_cement28.param.REQUIRED,
6634
+ store: import_cement28.param.REQUIRED,
6635
+ path: import_cement28.param.OPTIONAL,
6636
+ tenant: import_cement28.param.REQUIRED,
6637
+ name: import_cement28.param.REQUIRED,
6638
+ index: import_cement28.param.OPTIONAL
6639
+ });
6640
+ if (rParams.isErr()) {
6641
+ return buildErrorMsg(this, {}, rParams.Err());
6642
+ }
6643
+ const params = rParams.Ok();
6644
+ if (store !== params.store) {
6645
+ return buildErrorMsg(this, {}, new Error("store mismatch"));
6646
+ }
6647
+ const rAuth = await authTypeFromUri(this.logger, uri);
6648
+ if (rAuth.isErr()) {
6649
+ return buildErrorMsg(this, {}, rAuth.Err());
6650
+ }
6651
+ return {
6652
+ tid: this.sthis.nextId().str,
6653
+ auth: rAuth.Ok(),
6654
+ type,
6655
+ conn: conn.conn.Ok().conn,
6656
+ tenant: {
6657
+ tenant: params.tenant,
6658
+ ledger: params.name
6659
+ },
6660
+ // tenant: conn.tenant,
6661
+ methodParams: {
6662
+ method,
6663
+ store
6664
+ },
6665
+ params: {
6666
+ ...params,
6667
+ key: params.key
6668
+ },
6669
+ version: VERSION3
6670
+ };
6671
+ }
6672
+ async getReqSignedUrl(type, method, store, waitForFn, uri, conn) {
6673
+ const rsu = await this.buildReqSignedUrl(type, method, store, uri, conn);
6674
+ if (MsgIsError(rsu)) {
6675
+ return rsu;
6676
+ }
6677
+ return conn.conn.Ok().request(rsu, { waitFor: waitForFn });
6678
+ }
6679
+ async putObject(uri, uploadUrl, body, conn) {
6680
+ this.logger.Debug().Any("url", { uploadUrl, uri }).Msg("put-fetch-url");
6681
+ const rUpload = await (0, import_cement28.exception2Result)(async () => fetch(uploadUrl, { method: "PUT", body }));
6682
+ if (rUpload.isErr()) {
6683
+ return this.logger.Error().Url(uploadUrl, "uploadUrl").Err(rUpload).Msg("Error in put fetch").ResultError();
6684
+ }
6685
+ if (!rUpload.Ok().ok) {
6686
+ return this.logger.Error().Url(uploadUrl, "uploadUrl").Http(rUpload.Ok()).Msg("Error in put fetch").ResultError();
6687
+ }
6688
+ if (uri.getParam("testMode")) {
6689
+ conn.citem.trackPuts.add(uri.toString());
6690
+ }
6691
+ return import_cement28.Result.Ok(void 0);
6692
+ }
6693
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6694
+ async getObject(uri, downloadUrl, _conn) {
6695
+ this.logger.Debug().Any("url", { downloadUrl, uri }).Msg("get-fetch-url");
6696
+ const rDownload = await (0, import_cement28.exception2Result)(async () => fetch(downloadUrl.toString(), { method: "GET" }));
6697
+ if (rDownload.isErr()) {
6698
+ return this.logger.Error().Url(downloadUrl, "uploadUrl").Err(rDownload).Msg("Error in get downloadUrl").ResultError();
6699
+ }
6700
+ const download = rDownload.Ok();
6701
+ if (!download.ok) {
6702
+ if (download.status === 404) {
6703
+ return import_cement28.Result.Err(new NotFoundError("Not found"));
6704
+ }
6705
+ return this.logger.Error().Url(downloadUrl, "uploadUrl").Err(rDownload).Msg("Error in get fetch").ResultError();
6706
+ }
6707
+ return import_cement28.Result.Ok((0, import_cement28.to_uint8)(await download.arrayBuffer()));
6708
+ }
6709
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6710
+ async delObject(uri, deleteUrl, _conn) {
6711
+ this.logger.Debug().Any("url", { deleteUrl, uri }).Msg("get-fetch-url");
6712
+ const rDelete = await (0, import_cement28.exception2Result)(async () => fetch(deleteUrl.toString(), { method: "DELETE" }));
6713
+ if (rDelete.isErr()) {
6714
+ return this.logger.Error().Url(deleteUrl, "deleteUrl").Err(rDelete).Msg("Error in get deleteURL").ResultError();
6715
+ }
6716
+ const download = rDelete.Ok();
6717
+ if (!download.ok) {
6718
+ if (download.status === 404) {
6719
+ return import_cement28.Result.Err(new NotFoundError("Not found"));
6720
+ }
6721
+ return this.logger.Error().Url(deleteUrl, "deleteUrl").Err(rDelete).Msg("Error in del fetch").ResultError();
6722
+ }
6723
+ return import_cement28.Result.Ok(void 0);
6724
+ }
6725
+ };
6726
+ var DataGateway = class extends BaseGateway {
6727
+ constructor(sthis) {
6728
+ super(sthis, "DataGateway");
6729
+ }
6730
+ async get(ctx, uri) {
6731
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6732
+ const rResSignedUrl = await this.getReqSignedUrl("reqGetData", "GET", store, MsgIsResGetData, uri, ctx.conn);
6733
+ if (MsgIsError(rResSignedUrl)) {
6734
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6735
+ }
6736
+ const { signedUrl: downloadUrl } = rResSignedUrl;
6737
+ const r = await fpDeserialize(this.sthis, uri, this.getObject(uri, downloadUrl, ctx.conn));
6738
+ return r;
6739
+ }
6740
+ async put(ctx, uri, data) {
6741
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6742
+ const rResSignedUrl = await this.getReqSignedUrl("reqPutData", "PUT", store, MsgIsResPutData, uri, ctx.conn);
6743
+ if (MsgIsError(rResSignedUrl)) {
6744
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6745
+ }
6746
+ const { signedUrl: uploadUrl } = rResSignedUrl;
6747
+ const rBlob = await fpSerialize(ctx.loader.sthis, data);
6748
+ if (rBlob.isErr()) {
6749
+ return rBlob;
6750
+ }
6751
+ const r = await this.putObject(uri, uploadUrl, rBlob.Ok(), ctx.conn);
6752
+ return r;
6753
+ }
6754
+ async delete(ctx, uri) {
6755
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6756
+ const rResSignedUrl = await this.getReqSignedUrl("reqDelData", "DELETE", store, MsgIsResDelData, uri, ctx.conn);
6757
+ if (MsgIsError(rResSignedUrl)) {
6758
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6759
+ }
6760
+ const { signedUrl: deleteUrl } = rResSignedUrl;
6761
+ return this.delObject(uri, deleteUrl, ctx.conn);
6762
+ }
6763
+ };
6764
+ function getGwCtx(conn, uri) {
6765
+ const rParams = uri.getParamsResult({
6766
+ tid: import_cement28.param.OPTIONAL,
6767
+ tenant: import_cement28.param.REQUIRED,
6768
+ ledger: import_cement28.param.REQUIRED
6769
+ });
6770
+ if (rParams.isErr()) {
6771
+ return import_cement28.Result.Err(rParams);
6772
+ }
6773
+ const r = rParams.Ok();
6774
+ return import_cement28.Result.Ok({
6775
+ tid: r.tid,
6776
+ conn,
6777
+ tenant: {
6778
+ tenant: r.tenant,
6779
+ ledger: r.ledger
6780
+ }
6781
+ });
6782
+ }
6783
+ var MetaGateway = class extends BaseGateway {
6784
+ constructor(sthis) {
6785
+ super(sthis, "MetaGateway");
6786
+ }
6787
+ async get(ctx, uri) {
6788
+ const reqSignedUrl = await this.buildReqSignedUrl("bindGetMeta", "GET", "meta", uri, ctx.conn);
6789
+ if (MsgIsError(reqSignedUrl)) {
6790
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6791
+ }
6792
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6793
+ if (rGwCtx.isErr()) {
6794
+ return import_cement28.Result.Err(rGwCtx);
6795
+ }
6796
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6797
+ if (rAuthType.isErr()) {
6798
+ return import_cement28.Result.Err(rAuthType);
6799
+ }
6800
+ const res = await ctx.conn.conn.Ok().request(buildBindGetMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rGwCtx.Ok()), {
6801
+ waitFor: MsgIsEventGetMeta
6802
+ });
6803
+ if (MsgIsError(res)) {
6804
+ return this.logger.Error().Err(res).Msg("Error in buildBindGetMeta").ResultError();
6805
+ }
6806
+ const rV2Meta = await V2SerializedMetaKeyExtractKey(ctx, res.meta);
6807
+ const rMeta = await decode2DbMetaEvents(ctx.loader.sthis, rV2Meta);
6808
+ if (rMeta.isErr()) {
6809
+ return import_cement28.Result.Err(rMeta);
6810
+ }
6811
+ return import_cement28.Result.Ok({
6812
+ type: "meta",
6813
+ payload: rMeta.Ok()
6814
+ });
6815
+ }
6816
+ async put(ctx, uri, imeta) {
6817
+ const meta = imeta;
6818
+ const reqSignedUrl = await this.buildReqSignedUrl("reqPutMeta", "PUT", "meta", uri, ctx.conn);
6819
+ if (MsgIsError(reqSignedUrl)) {
6820
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6821
+ }
6822
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6823
+ if (rGwCtx.isErr()) {
6824
+ return import_cement28.Result.Err(rGwCtx);
6825
+ }
6826
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6827
+ if (rAuthType.isErr()) {
6828
+ return import_cement28.Result.Err(rAuthType);
6829
+ }
6830
+ const serializedMeta = await dbMetaEvent2Serialized(ctx.loader.sthis, meta.payload);
6831
+ const rKeyedMeta = await encodeAsV2SerializedMetaKey(ctx, serializedMeta);
6832
+ if (rKeyedMeta.isErr()) {
6833
+ return rKeyedMeta;
6834
+ }
6835
+ const reqPutMeta = buildReqPutMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rKeyedMeta.Ok(), rGwCtx.Ok());
6836
+ const resMsg = await ctx.conn.conn.Ok().request(reqPutMeta, {
6837
+ waitFor: MsgIsResPutMeta
6838
+ });
6839
+ if (MsgIsError(resMsg)) {
6840
+ return this.logger.Error().Err(resMsg).Msg("Error in buildResSignedUrl").ResultError();
6841
+ }
6842
+ return import_cement28.Result.Ok(void 0);
6843
+ }
6844
+ async delete(ctx, uri) {
6845
+ const reqSignedUrl = await this.getReqSignedUrl("reqDelMeta", "DELETE", "meta", MsgIsResDelData, uri, ctx.conn);
6846
+ if (MsgIsError(reqSignedUrl)) {
6847
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6848
+ }
6849
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6850
+ if (rGwCtx.isErr()) {
6851
+ return import_cement28.Result.Err(rGwCtx);
6852
+ }
6853
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6854
+ if (rAuthType.isErr()) {
6855
+ return import_cement28.Result.Err(rAuthType);
6856
+ }
6857
+ const reqDelMeta = buildReqDelMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rGwCtx.Ok());
6858
+ const resMsg = await ctx.conn.conn.Ok().request(reqDelMeta, {
6859
+ waitFor: MsgIsResDelData
6860
+ });
6861
+ if (MsgIsError(resMsg)) {
6862
+ return this.logger.Error().Err(resMsg).Msg("Error in buildResSignedUrl").ResultError();
6863
+ }
6864
+ return import_cement28.Result.Ok(void 0);
6865
+ }
6866
+ };
6867
+ var WALGateway = class extends BaseGateway {
6868
+ constructor(sthis) {
6869
+ super(sthis, "WALGateway");
6870
+ // WAL will not pollute to the cloud
6871
+ this.wals = /* @__PURE__ */ new Map();
6872
+ }
6873
+ getWalKeyFromUri(uri) {
6874
+ const rKey = uri.getParamsResult({
6875
+ key: 0,
6876
+ name: 0
6877
+ });
6878
+ if (rKey.isErr()) {
6879
+ return import_cement28.Result.Err(rKey.Err());
6880
+ }
6881
+ const { name, key } = rKey.Ok();
6882
+ return import_cement28.Result.Ok(`${name}:${key}`);
6883
+ }
6884
+ async get(ctx, uri) {
6885
+ const rKey = this.getWalKeyFromUri(uri);
6886
+ if (rKey.isErr()) {
6887
+ return import_cement28.Result.Err(rKey.Err());
6888
+ }
6889
+ const wal = this.wals.get(rKey.Ok());
6890
+ if (!wal) {
6891
+ return import_cement28.Result.Err(new NotFoundError("Not found"));
6892
+ }
6893
+ return import_cement28.Result.Ok(wal);
6894
+ }
6895
+ async put(ctx, uri, body) {
6896
+ const rKey = this.getWalKeyFromUri(uri);
6897
+ if (rKey.isErr()) {
6898
+ return import_cement28.Result.Err(rKey.Err());
6899
+ }
6900
+ this.wals.set(rKey.Ok(), body);
6901
+ return import_cement28.Result.Ok(void 0);
6902
+ }
6903
+ async delete(ctx, uri) {
6904
+ const rKey = this.getWalKeyFromUri(uri);
6905
+ if (rKey.isErr()) {
6906
+ return import_cement28.Result.Err(rKey.Err());
6907
+ }
6908
+ this.wals.delete(rKey.Ok());
6909
+ return import_cement28.Result.Ok(void 0);
6910
+ }
6911
+ };
6912
+ var storeTypedGateways = new import_cement28.KeyedResolvOnce();
6913
+ function getStoreTypeGateway(sthis, uri) {
6914
+ const store = uri.getParam("store");
6915
+ switch (store) {
6916
+ case "file":
6917
+ case "car":
6918
+ return storeTypedGateways.get(store).once(() => new DataGateway(sthis));
6919
+ case "meta":
6920
+ return storeTypedGateways.get(store).once(() => new MetaGateway(sthis));
6921
+ case "wal":
6922
+ return storeTypedGateways.get(store).once(() => new WALGateway(sthis));
6923
+ default:
6924
+ throw ensureLogger(sthis, "getStoreTypeGateway").Error().Str("store", store).Msg("Invalid store type").ResultError();
6925
+ }
6926
+ }
6927
+ function connectionURI(uri) {
6928
+ return uri.build().delParam("authJWK").delParam("key").delParam("store").delParam("suffix").delParam("storekey").URI();
6929
+ }
6930
+ var subscriptions = /* @__PURE__ */ new Map();
6931
+ var FireproofCloudGateway = class {
6932
+ #connectionURIs = /* @__PURE__ */ new Map();
6933
+ constructor(sthis) {
6934
+ this.sthis = sthis;
6935
+ this.logger = ensureLogger(sthis, "FireproofCloudGateway", {
6936
+ this: true
6937
+ });
6938
+ }
6939
+ async buildUrl(ctx, baseUrl, key) {
6940
+ return import_cement28.Result.Ok(baseUrl.build().setParam("key", key).URI());
6941
+ }
6942
+ async start(ctx, uri) {
6943
+ await this.sthis.start();
6944
+ const rName = uri.getParamResult("name");
6945
+ if (rName.isErr()) {
6946
+ return this.logger.Error().Err(rName).Msg("name not found").ResultError();
6947
+ }
6948
+ const ret = uri.build().defParam("version", VERSION3);
6949
+ ret.defParam("protocol", "wss");
6950
+ const retURI = ret.URI();
6951
+ const matchURI = connectionURI(retURI);
6952
+ this.#connectionURIs.set(matchURI.toString(), {
6953
+ uri: matchURI,
6954
+ matchRes: matchURI.match(matchURI),
6955
+ connection: new import_cement28.ResolveOnce(),
6956
+ trackPuts: /* @__PURE__ */ new Set()
6957
+ });
6958
+ return import_cement28.Result.Ok(retURI);
6959
+ }
6960
+ async get(ctx, uri) {
6961
+ const conn = await this.getCloudConnectionItem(uri);
6962
+ if (conn.conn.isErr()) {
6963
+ return import_cement28.Result.Err(conn.conn);
6964
+ }
6965
+ const ret = await getStoreTypeGateway(ctx.loader.sthis, uri).get({ ...ctx, conn }, uri);
6966
+ return ret;
6967
+ }
6968
+ async put(ctx, uri, body) {
6969
+ const conn = await this.getCloudConnectionItem(uri);
6970
+ if (conn.conn.isErr()) {
6971
+ return conn.conn;
6972
+ }
6973
+ const ret = await getStoreTypeGateway(ctx.loader.sthis, uri).put({ ...ctx, conn }, uri, body);
6974
+ if (ret.isOk()) {
6975
+ if (uri.getParam("testMode")) {
6976
+ conn.citem.trackPuts.add(uri.toString());
6977
+ }
6978
+ }
6979
+ return ret;
6980
+ }
6981
+ async delete(ctx, uri) {
6982
+ const conn = await this.getCloudConnectionItem(uri);
6983
+ if (conn.conn.isErr()) {
6984
+ return conn.conn;
6985
+ }
6986
+ conn.citem.trackPuts.delete(uri.toString());
6987
+ return getStoreTypeGateway(ctx.loader.sthis, uri).delete({ ...ctx, conn }, uri);
6988
+ }
6989
+ async close(ctx, uri) {
6990
+ const uriStr = uri.toString();
6991
+ for (const sub of Array.from(subscriptions.values())) {
6992
+ for (const s of sub) {
6993
+ if (s.uri.toString() === uriStr) {
6994
+ s.unsub();
6995
+ }
6996
+ }
6997
+ }
6998
+ const rConn = await this.getCloudConnectionItem(uri);
6999
+ if (rConn.conn.isErr()) {
7000
+ return this.logger.Error().Err(rConn).Msg("Error in getCloudConnection").ResultError();
7001
+ }
7002
+ const conn = rConn.conn.Ok();
7003
+ const rAuth = await conn.msgConnAuth();
7004
+ await conn.close(rAuth.Ok());
7005
+ this.#connectionURIs.delete(rConn.citem.uri.toString());
7006
+ return import_cement28.Result.Ok(void 0);
7007
+ }
7008
+ // fireproof://localhost:1999/?name=test-public-api&protocol=ws&store=meta
7009
+ async getCloudConnection(uri) {
7010
+ return this.getCloudConnectionItem(uri).then((r) => {
7011
+ return r.conn;
7012
+ });
7013
+ }
7014
+ async getCloudConnectionItem(uri) {
7015
+ const matchURI = connectionURI(uri);
7016
+ let bestMatch;
7017
+ for (const ci of this.#connectionURIs.values()) {
7018
+ const mci = ci.uri.match(matchURI);
7019
+ if (mci.score >= ci.matchRes.score) {
7020
+ bestMatch = ci;
7021
+ break;
7022
+ }
7023
+ }
7024
+ if (!bestMatch) {
7025
+ return {
7026
+ conn: this.logger.Error().Url(matchURI).Any("conns", Object.fromEntries(this.#connectionURIs.entries())).Msg("No connection found").ResultError(),
7027
+ citem: {}
7028
+ };
7029
+ }
7030
+ const conn = await bestMatch.connection.once(async () => {
7031
+ const rParams = uri.getParamsResult({
7032
+ name: import_cement28.param.REQUIRED,
7033
+ protocol: "https",
7034
+ store: import_cement28.param.REQUIRED,
7035
+ storekey: import_cement28.param.OPTIONAL,
7036
+ tenant: import_cement28.param.REQUIRED
7037
+ });
7038
+ if (rParams.isErr()) {
7039
+ return this.logger.Error().Url(uri).Err(rParams).Msg("getCloudConnection:err").ResultError();
7040
+ }
7041
+ const params = rParams.Ok();
7042
+ const rAuth = await authTypeFromUri(this.logger, uri);
7043
+ if (rAuth.isErr()) {
7044
+ return import_cement28.Result.Err(rAuth);
7045
+ }
7046
+ const qOpen = buildReqOpen(this.sthis, rAuth.Ok(), {});
7047
+ const cUrl = uri.build().protocol(params.protocol).cleanParams().URI();
7048
+ return Msger.connect(this.sthis, rAuth.Ok(), cUrl, qOpen);
7049
+ });
7050
+ if (conn.isErr()) {
7051
+ return { conn: import_cement28.Result.Err(conn), citem: bestMatch };
7052
+ }
7053
+ return { conn: import_cement28.Result.Ok(conn.Ok().attachAuth(() => authTypeFromUri(this.logger, uri))), citem: bestMatch };
7054
+ }
7055
+ // private notifySubscribers(data: Uint8Array, callbacks: ((msg: Uint8Array) => void)[] = []): void {
7056
+ // for (const cb of callbacks) {
7057
+ // try {
7058
+ // cb(data);
7059
+ // } catch (error) {
7060
+ // this.logger.Error().Err(error).Msg("Error in subscriber callback execution");
7061
+ // }
7062
+ // }
7063
+ // }
7064
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
7065
+ async subscribe(ctx, url, callback) {
7066
+ return import_cement28.Result.Err(new Error("Not implemented"));
7067
+ }
7068
+ async destroy(ctx, uri) {
7069
+ const item = await this.getCloudConnectionItem(uri);
7070
+ if (item.conn.isErr()) {
7071
+ return item.conn;
7072
+ }
7073
+ await Promise.all(Array.from(item.citem.trackPuts).map(async (k) => this.delete(ctx, import_cement28.URI.from(k))));
7074
+ return import_cement28.Result.Ok(void 0);
7075
+ }
7076
+ async getPlain() {
7077
+ return import_cement28.Result.Err(new Error("Not implemented"));
7078
+ }
7079
+ };
7080
+ var onceRegisterFireproofCloudStoreProtocol = new import_cement28.KeyedResolvOnce();
7081
+ function registerFireproofCloudStoreProtocol(protocol = "fpcloud:") {
7082
+ return onceRegisterFireproofCloudStoreProtocol.get(protocol).once(() => {
7083
+ import_cement28.URI.protocolHasHostpart(protocol);
7084
+ return registerStoreProtocol({
7085
+ protocol,
7086
+ defaultURI() {
7087
+ return import_cement28.URI.from("fpcloud://fireproof.cloud/");
7088
+ },
7089
+ serdegateway: async (sthis) => {
7090
+ return new FireproofCloudGateway(sthis);
7091
+ }
7092
+ });
7093
+ });
7094
+ }
7095
+ registerFireproofCloudStoreProtocol();
7096
+ function toCloud(url) {
7097
+ const urlObj = import_cement28.URI.from(url);
7098
+ if (urlObj.protocol !== "fpcloud:") {
7099
+ throw new Error("url must have fireproof protocol");
7100
+ }
7101
+ return {
7102
+ name: urlObj.protocol,
7103
+ prepare() {
7104
+ return Promise.resolve({
7105
+ car: { url: urlObj },
7106
+ file: { url: urlObj },
7107
+ meta: { url: urlObj }
7108
+ });
7109
+ }
7110
+ };
7111
+ }
7112
+
7113
+ // src/protocols/index.ts
7114
+ var protocols_exports = {};
7115
+ __export(protocols_exports, {
7116
+ cloud: () => cloud_exports
7117
+ });
7118
+
7119
+ // src/protocols/cloud/index.ts
7120
+ var cloud_exports = {};
7121
+ __export(cloud_exports, {
7122
+ HttpConnection: () => HttpConnection,
7123
+ MsgConnected: () => MsgConnected,
7124
+ MsgConnectedAuth: () => MsgConnectedAuth,
7125
+ MsgIsBindGetMeta: () => MsgIsBindGetMeta,
7126
+ MsgIsConnected: () => MsgIsConnected,
7127
+ MsgIsError: () => MsgIsError,
7128
+ MsgIsEventGetMeta: () => MsgIsEventGetMeta,
7129
+ MsgIsQSError: () => MsgIsQSError,
7130
+ MsgIsReqChat: () => MsgIsReqChat,
7131
+ MsgIsReqClose: () => MsgIsReqClose,
7132
+ MsgIsReqDelData: () => MsgIsReqDelData,
7133
+ MsgIsReqDelMeta: () => MsgIsReqDelMeta,
7134
+ MsgIsReqDelWAL: () => MsgIsReqDelWAL,
7135
+ MsgIsReqGestalt: () => MsgIsReqGestalt,
7136
+ MsgIsReqGetData: () => MsgIsReqGetData,
7137
+ MsgIsReqGetWAL: () => MsgIsReqGetWAL,
7138
+ MsgIsReqOpen: () => MsgIsReqOpen,
7139
+ MsgIsReqPutData: () => MsgIsReqPutData,
7140
+ MsgIsReqPutMeta: () => MsgIsReqPutMeta,
7141
+ MsgIsReqPutWAL: () => MsgIsReqPutWAL,
7142
+ MsgIsResChat: () => MsgIsResChat,
7143
+ MsgIsResClose: () => MsgIsResClose,
7144
+ MsgIsResDelData: () => MsgIsResDelData,
7145
+ MsgIsResDelMeta: () => MsgIsResDelMeta,
7146
+ MsgIsResDelWAL: () => MsgIsResDelWAL,
7147
+ MsgIsResGestalt: () => MsgIsResGestalt,
7148
+ MsgIsResGetData: () => MsgIsResGetData,
7149
+ MsgIsResGetWAL: () => MsgIsResGetWAL,
7150
+ MsgIsResOpen: () => MsgIsResOpen,
7151
+ MsgIsResPutData: () => MsgIsResPutData,
7152
+ MsgIsResPutMeta: () => MsgIsResPutMeta,
7153
+ MsgIsResPutWAL: () => MsgIsResPutWAL,
7154
+ MsgIsTenantLedger: () => MsgIsTenantLedger,
7155
+ MsgIsTid: () => MsgIsTid,
7156
+ MsgIsWithConn: () => MsgIsWithConn,
7157
+ MsgIsWithConnAuth: () => MsgIsWithConnAuth,
7158
+ MsgRawConnectionBase: () => MsgRawConnectionBase,
7159
+ Msger: () => Msger,
7160
+ VERSION: () => VERSION,
7161
+ WSConnection: () => WSConnection,
7162
+ applyStart: () => applyStart,
7163
+ authTypeFromUri: () => authTypeFromUri,
7164
+ buildBindGetMeta: () => buildBindGetMeta,
7165
+ buildErrorMsg: () => buildErrorMsg,
7166
+ buildEventGetMeta: () => buildEventGetMeta,
7167
+ buildReqChat: () => buildReqChat,
7168
+ buildReqClose: () => buildReqClose,
7169
+ buildReqDelData: () => buildReqDelData,
7170
+ buildReqDelMeta: () => buildReqDelMeta,
7171
+ buildReqDelWAL: () => buildReqDelWAL,
7172
+ buildReqGestalt: () => buildReqGestalt,
7173
+ buildReqGetData: () => buildReqGetData,
7174
+ buildReqGetWAL: () => buildReqGetWAL,
7175
+ buildReqOpen: () => buildReqOpen,
7176
+ buildReqPutData: () => buildReqPutData,
7177
+ buildReqPutMeta: () => buildReqPutMeta,
7178
+ buildReqPutWAL: () => buildReqPutWAL,
7179
+ buildReqSignedUrl: () => buildReqSignedUrl,
7180
+ buildRes: () => buildRes,
7181
+ buildResChat: () => buildResChat,
7182
+ buildResClose: () => buildResClose,
7183
+ buildResDelData: () => buildResDelData,
7184
+ buildResDelMeta: () => buildResDelMeta,
7185
+ buildResDelWAL: () => buildResDelWAL,
7186
+ buildResGestalt: () => buildResGestalt,
7187
+ buildResGetData: () => buildResGetData,
7188
+ buildResGetWAL: () => buildResGetWAL,
7189
+ buildResOpen: () => buildResOpen,
7190
+ buildResPutData: () => buildResPutData,
7191
+ buildResPutMeta: () => buildResPutMeta,
7192
+ buildResPutWAL: () => buildResPutWAL,
7193
+ coerceFPStoreTypes: () => coerceFPStoreTypes,
7194
+ defaultGestalt: () => defaultGestalt,
7195
+ defaultMsgParams: () => defaultMsgParams,
7196
+ ensurePath: () => ensurePath,
7197
+ isAuthTypeFPCloud: () => isAuthTypeFPCloud,
7198
+ isAuthTypeFPCloudJWK: () => isAuthTypeFPCloudJWK,
7199
+ isProtocolCapabilities: () => isProtocolCapabilities,
7200
+ jsonEnDe: () => jsonEnDe,
7201
+ keyTenantLedger: () => keyTenantLedger,
7202
+ qsidEqual: () => qsidEqual,
7203
+ qsidKey: () => qsidKey,
7204
+ resAuth: () => resAuth,
7205
+ selectRandom: () => selectRandom,
7206
+ timeout: () => timeout
7207
+ });
7208
+
7209
+ // src/protocols/cloud/msg-types-wal.ts
7210
+ function MsgIsReqGetWAL(msg) {
7211
+ return msg.type === "reqGetWAL";
7212
+ }
7213
+ function buildReqGetWAL(sthis, sup, ctx) {
7214
+ return buildReqSignedUrl(sthis, "reqGetWAL", sup, ctx);
7215
+ }
7216
+ function MsgIsResGetWAL(msg) {
7217
+ return msg.type === "resGetWAL";
7218
+ }
7219
+ function buildResGetWAL(msgCtx, req, ctx) {
7220
+ return buildRes(
7221
+ { method: "GET", store: "wal" },
7222
+ "resGetWAL",
7223
+ msgCtx,
7224
+ req,
7225
+ ctx
7226
+ );
7227
+ }
7228
+ function MsgIsReqPutWAL(msg) {
7229
+ return msg.type === "reqPutWAL";
7230
+ }
7231
+ function buildReqPutWAL(sthis, sup, ctx) {
7232
+ return buildReqSignedUrl(sthis, "reqPutWAL", sup, ctx);
7233
+ }
7234
+ function MsgIsResPutWAL(msg) {
7235
+ return msg.type === "resPutWAL";
7236
+ }
7237
+ function buildResPutWAL(msgCtx, req, ctx) {
7238
+ return buildRes(
7239
+ { method: "PUT", store: "wal" },
7240
+ "resPutWAL",
7241
+ msgCtx,
7242
+ req,
7243
+ ctx
7244
+ );
7245
+ }
7246
+ function MsgIsReqDelWAL(msg) {
7247
+ return msg.type === "reqDelWAL";
7248
+ }
7249
+ function buildReqDelWAL(sthis, sup, ctx) {
7250
+ return buildReqSignedUrl(sthis, "reqDelWAL", sup, ctx);
7251
+ }
7252
+ function MsgIsResDelWAL(msg) {
7253
+ return msg.type === "resDelWAL" && MsgIsTenantLedger(msg);
7254
+ }
7255
+ function buildResDelWAL(msgCtx, req, ctx) {
7256
+ return buildRes(
7257
+ { method: "DELETE", store: "wal" },
7258
+ "resDelWAL",
7259
+ msgCtx,
7260
+ req,
7261
+ ctx
7262
+ );
7263
+ }
7264
+
5313
7265
  // src/version.ts
5314
7266
  var PACKAGE_VERSION = Object.keys({
5315
- "0.20.0-dev-preview-55": "xxxx"
7267
+ "0.20.0-dev-preview-58": "xxxx"
5316
7268
  })[0];
5317
7269
  //# sourceMappingURL=index.cjs.map