@opendatalabs/personal-server-ts-server 1.34.0 → 1.34.2

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.
@@ -42280,11 +42280,11 @@ var init_abiParameter = __esm({
42280
42280
  });
42281
42281
 
42282
42282
  // ../../node_modules/abitype/dist/esm/human-readable/errors/signature.js
42283
- var InvalidSignatureError, UnknownSignatureError, InvalidStructSignatureError;
42283
+ var InvalidSignatureError2, UnknownSignatureError, InvalidStructSignatureError;
42284
42284
  var init_signature = __esm({
42285
42285
  "../../node_modules/abitype/dist/esm/human-readable/errors/signature.js"() {
42286
42286
  init_errors();
42287
- InvalidSignatureError = class extends BaseError {
42287
+ InvalidSignatureError2 = class extends BaseError {
42288
42288
  constructor({ signature, type }) {
42289
42289
  super(`Invalid ${type} signature.`, {
42290
42290
  details: signature
@@ -42471,7 +42471,7 @@ function parseSignature(signature, structs = {}) {
42471
42471
  function parseFunctionSignature(signature, structs = {}) {
42472
42472
  const match = execFunctionSignature(signature);
42473
42473
  if (!match)
42474
- throw new InvalidSignatureError({ signature, type: "function" });
42474
+ throw new InvalidSignatureError2({ signature, type: "function" });
42475
42475
  const inputParams = splitParameters(match.parameters);
42476
42476
  const inputs = [];
42477
42477
  const inputLength = inputParams.length;
@@ -42505,7 +42505,7 @@ function parseFunctionSignature(signature, structs = {}) {
42505
42505
  function parseEventSignature(signature, structs = {}) {
42506
42506
  const match = execEventSignature(signature);
42507
42507
  if (!match)
42508
- throw new InvalidSignatureError({ signature, type: "event" });
42508
+ throw new InvalidSignatureError2({ signature, type: "event" });
42509
42509
  const params = splitParameters(match.parameters);
42510
42510
  const abiParameters = [];
42511
42511
  const length = params.length;
@@ -42520,7 +42520,7 @@ function parseEventSignature(signature, structs = {}) {
42520
42520
  function parseErrorSignature(signature, structs = {}) {
42521
42521
  const match = execErrorSignature(signature);
42522
42522
  if (!match)
42523
- throw new InvalidSignatureError({ signature, type: "error" });
42523
+ throw new InvalidSignatureError2({ signature, type: "error" });
42524
42524
  const params = splitParameters(match.parameters);
42525
42525
  const abiParameters = [];
42526
42526
  const length = params.length;
@@ -42531,7 +42531,7 @@ function parseErrorSignature(signature, structs = {}) {
42531
42531
  function parseConstructorSignature(signature, structs = {}) {
42532
42532
  const match = execConstructorSignature(signature);
42533
42533
  if (!match)
42534
- throw new InvalidSignatureError({ signature, type: "constructor" });
42534
+ throw new InvalidSignatureError2({ signature, type: "constructor" });
42535
42535
  const params = splitParameters(match.parameters);
42536
42536
  const abiParameters = [];
42537
42537
  const length = params.length;
@@ -42546,7 +42546,7 @@ function parseConstructorSignature(signature, structs = {}) {
42546
42546
  function parseFallbackSignature(signature) {
42547
42547
  const match = execFallbackSignature(signature);
42548
42548
  if (!match)
42549
- throw new InvalidSignatureError({ signature, type: "fallback" });
42549
+ throw new InvalidSignatureError2({ signature, type: "fallback" });
42550
42550
  return {
42551
42551
  type: "fallback",
42552
42552
  stateMutability: match.stateMutability ?? "nonpayable"
@@ -42670,7 +42670,7 @@ function parseStructs(signatures) {
42670
42670
  continue;
42671
42671
  const match = execStructSignature(signature);
42672
42672
  if (!match)
42673
- throw new InvalidSignatureError({ signature, type: "struct" });
42673
+ throw new InvalidSignatureError2({ signature, type: "struct" });
42674
42674
  const properties = match.properties.split(";");
42675
42675
  const components = [];
42676
42676
  const propertiesLength = properties.length;
@@ -92182,6 +92182,9 @@ var ALTERNATE_PROFILE_BINDINGS = /* @__PURE__ */ new Map([
92182
92182
  ["meta", META_040_BINDINGS],
92183
92183
  ["oura-browser", OURA_BROWSER_BINDINGS]
92184
92184
  ]);
92185
+ function alternateLegacyBindingsForScope(scope) {
92186
+ return new Map([...ALTERNATE_PROFILE_BINDINGS].filter(([, bindings]) => bindings.has(scope)).map(([profileKey, bindings]) => [profileKey, bindings.get(scope)]));
92187
+ }
92185
92188
  function legacyBindingsForProfile(profileKey) {
92186
92189
  const alternate = ALTERNATE_PROFILE_BINDINGS.get(profileKey);
92187
92190
  if (alternate)
@@ -92312,6 +92315,180 @@ function bindingFor(scope, profileKey) {
92312
92315
  return legacyBindingsForProfile(profileKey).get(scope);
92313
92316
  }
92314
92317
 
92318
+ // ../core/dist/errors/catalog.js
92319
+ var ProtocolError = class extends Error {
92320
+ code;
92321
+ errorCode;
92322
+ details;
92323
+ constructor(code, errorCode, message, details) {
92324
+ super(message);
92325
+ this.code = code;
92326
+ this.errorCode = errorCode;
92327
+ this.details = details;
92328
+ this.name = this.constructor.name;
92329
+ }
92330
+ toJSON() {
92331
+ return {
92332
+ error: {
92333
+ code: this.code,
92334
+ errorCode: this.errorCode,
92335
+ message: this.message,
92336
+ ...this.details !== void 0 && { details: this.details }
92337
+ }
92338
+ };
92339
+ }
92340
+ };
92341
+ var MissingAuthError = class extends ProtocolError {
92342
+ constructor(details) {
92343
+ super(401, "MISSING_AUTH", "Missing authentication", details);
92344
+ }
92345
+ };
92346
+ var InvalidSignatureError = class extends ProtocolError {
92347
+ constructor(details) {
92348
+ super(401, "INVALID_SIGNATURE", "Invalid signature", details);
92349
+ }
92350
+ };
92351
+ var UnregisteredBuilderError = class extends ProtocolError {
92352
+ constructor(details) {
92353
+ super(401, "UNREGISTERED_BUILDER", "Unregistered builder", details);
92354
+ }
92355
+ };
92356
+ var NotOwnerError = class extends ProtocolError {
92357
+ constructor(details) {
92358
+ super(401, "NOT_OWNER", "Not the owner", details);
92359
+ }
92360
+ };
92361
+ var ExpiredTokenError = class extends ProtocolError {
92362
+ constructor(details) {
92363
+ super(401, "EXPIRED_TOKEN", "Token has expired", details);
92364
+ }
92365
+ };
92366
+ var GrantRequiredError = class extends ProtocolError {
92367
+ constructor(details) {
92368
+ super(403, "GRANT_REQUIRED", "Grant required", details);
92369
+ }
92370
+ };
92371
+ var GrantExpiredError = class extends ProtocolError {
92372
+ constructor(details) {
92373
+ super(403, "GRANT_EXPIRED", "Grant has expired", details);
92374
+ }
92375
+ };
92376
+ var GrantRevokedError = class extends ProtocolError {
92377
+ constructor(details) {
92378
+ super(403, "GRANT_REVOKED", "Grant has been revoked", details);
92379
+ }
92380
+ };
92381
+ var ScopeMismatchError = class extends ProtocolError {
92382
+ constructor(details) {
92383
+ super(403, "SCOPE_MISMATCH", "Scope not granted", details);
92384
+ }
92385
+ };
92386
+ var GrantOwnerMismatchError = class extends ProtocolError {
92387
+ constructor(details) {
92388
+ super(403, "GRANT_OWNER_MISMATCH", "Grant was not issued by this server's owner", details);
92389
+ }
92390
+ };
92391
+ var PsUnavailableError = class extends ProtocolError {
92392
+ constructor(details) {
92393
+ super(503, "PS_UNAVAILABLE", "Personal Server runtime unavailable", details);
92394
+ }
92395
+ };
92396
+ var ServerNotConfiguredError = class extends ProtocolError {
92397
+ constructor(details) {
92398
+ super(500, "SERVER_NOT_CONFIGURED", "Server is not configured", details);
92399
+ }
92400
+ };
92401
+ var ServerSigningUnavailableError = class extends ProtocolError {
92402
+ constructor() {
92403
+ super(500, "SERVER_SIGNING_UNAVAILABLE", "Server signing is unavailable in this runtime");
92404
+ }
92405
+ };
92406
+ var ContentTooLargeError = class extends ProtocolError {
92407
+ constructor(details) {
92408
+ super(413, "CONTENT_TOO_LARGE", "Content too large", details);
92409
+ }
92410
+ };
92411
+ var LineageInvalidError = class extends ProtocolError {
92412
+ constructor(message, details) {
92413
+ super(400, "LINEAGE_INVALID", message, details);
92414
+ }
92415
+ };
92416
+ var LineageScopeUnderSourcePrefixError = class extends ProtocolError {
92417
+ constructor(details) {
92418
+ super(400, "LINEAGE_SCOPE_UNDER_SOURCE_PREFIX", `Derived scope "${details.scope}" shares its first segment with source scope "${details.sourceScope}"; a wildcard grant on that namespace would read both. Name derivatives under their own namespace.`, details);
92419
+ }
92420
+ };
92421
+ var LineageSourceUnknownError = class extends ProtocolError {
92422
+ constructor(details) {
92423
+ super(422, "LINEAGE_SOURCE_UNKNOWN", "One or more lineage sources are not data points of this owner", details);
92424
+ }
92425
+ };
92426
+ var LineageSourceLookupFailedError = class extends ProtocolError {
92427
+ constructor(details) {
92428
+ super(502, "LINEAGE_SOURCE_LOOKUP_FAILED", "Could not resolve a lineage source at the gateway", details);
92429
+ }
92430
+ };
92431
+ var LineageUnavailableError = class extends ProtocolError {
92432
+ constructor(details) {
92433
+ super(503, "LINEAGE_UNAVAILABLE", "This server is not configured to reach the gateway lineage graph (gateway URL or server signing key missing)", details);
92434
+ }
92435
+ };
92436
+ var LineageGatewayError = class extends ProtocolError {
92437
+ constructor(details) {
92438
+ super(502, "LINEAGE_GATEWAY_ERROR", `Gateway lineage request failed with status ${details.status}`, details);
92439
+ }
92440
+ };
92441
+ var LineageCascadeUnavailableError = class extends ProtocolError {
92442
+ constructor(details) {
92443
+ super(501, "LINEAGE_CASCADE_UNAVAILABLE", "DELETE ?cascade=lineage is specified but not implemented yet: the lineage walk that finds every derivative is missing. Delete scopes one at a time; each single-scope delete is durable.", details);
92444
+ }
92445
+ };
92446
+ var InvalidCascadeError = class extends ProtocolError {
92447
+ constructor(details) {
92448
+ super(400, "INVALID_CASCADE", 'Unsupported cascade mode; the only supported value is "lineage"', details);
92449
+ }
92450
+ };
92451
+ var DeleteTombstoneFailedError = class extends ProtocolError {
92452
+ constructor(details) {
92453
+ super(502, "DELETE_TOMBSTONE_FAILED", "Gateway did not acknowledge the deletion tombstone; nothing was deleted", details);
92454
+ }
92455
+ };
92456
+ var DataDeletedError = class extends ProtocolError {
92457
+ constructor(details) {
92458
+ super(410, "DATA_DELETED", "Data point has been deleted", details);
92459
+ }
92460
+ };
92461
+ var DerivativeQuestionInvalidError = class extends ProtocolError {
92462
+ constructor(message, details) {
92463
+ super(400, "DERIVATIVE_QUESTION_INVALID", message, details);
92464
+ }
92465
+ };
92466
+ var DerivativeQuestionNotFoundError = class extends ProtocolError {
92467
+ constructor(details) {
92468
+ super(404, "DERIVATIVE_QUESTION_NOT_FOUND", "Question not found", details);
92469
+ }
92470
+ };
92471
+ var DerivativeDerivedScopeRequiredError = class extends ProtocolError {
92472
+ constructor(details) {
92473
+ super(400, "DERIVATIVE_DERIVED_SCOPE_REQUIRED", "Listing questions as a builder needs a derived scope: add ?derivedScope=<scope>. The unfiltered list is the owner's", details);
92474
+ }
92475
+ };
92476
+ var DerivativeCycleError = class extends ProtocolError {
92477
+ constructor(details) {
92478
+ super(409, "DERIVATIVE_CYCLE", `Registering this question would make "${details.derivedScope}" a transitive source of itself; recompute would never settle`, details);
92479
+ }
92480
+ };
92481
+ var DerivativeSourceNotGrantedError = class extends ProtocolError {
92482
+ constructor(details) {
92483
+ super(403, "DERIVATIVE_SOURCE_NOT_GRANTED", "The builder's grant does not cover reading every source scope of this question", details);
92484
+ }
92485
+ };
92486
+ var DerivativeComputeUnavailableError = class extends ProtocolError {
92487
+ constructor(details) {
92488
+ super(503, "DERIVATIVE_COMPUTE_UNAVAILABLE", "This server has no derivative compute configured", details);
92489
+ }
92490
+ };
92491
+
92315
92492
  // ../core/dist/contracts/binary.js
92316
92493
  var BINARY_MARKER = "$binary";
92317
92494
  var BINARY_ENCODING = "base64";
@@ -93330,11 +93507,6 @@ function readJsonLiteralToken(text, startIndex) {
93330
93507
  }
93331
93508
 
93332
93509
  // ../core/dist/storage/legacy-projection.js
93333
- var PROJECTED_SOURCES = /* @__PURE__ */ new Set([
93334
- "chatgpt",
93335
- "claude",
93336
- "youtube"
93337
- ]);
93338
93510
  var SERVER_STAMP_KEYS = /* @__PURE__ */ new Set([
93339
93511
  "$writtenBy",
93340
93512
  "$lineage"
@@ -93353,21 +93525,61 @@ function withLegacyProjection(raw, options = {}) {
93353
93525
  return raw;
93354
93526
  let memo = null;
93355
93527
  const forms = /* @__PURE__ */ new Map();
93356
- const rememberForm = (version4, form) => {
93357
- forms.set(version4, form);
93528
+ const rememberForm = (key, value) => {
93529
+ forms.set(key, value);
93358
93530
  if (forms.size > FORM_CACHE_SIZE) {
93359
93531
  forms.delete(forms.keys().next().value);
93360
93532
  }
93361
93533
  };
93534
+ function failProjection(scope, collectedAt, error51) {
93535
+ options.onIssue?.({ kind: "projection_failed", scope, collectedAt, error: error51 });
93536
+ throw new ProtocolError(409, "LEGACY_PROJECTION_UNAVAILABLE", `Cannot serve the legacy view for scope "${scope}"`, {
93537
+ scope,
93538
+ collectedAt,
93539
+ reason: "reason" in error51 ? error51.reason : error51.kind,
93540
+ projectionError: error51.kind
93541
+ });
93542
+ }
93362
93543
  async function resolve(scope, collectedAt) {
93363
93544
  if (!isProjectedScope(scope))
93364
93545
  return { view: null };
93365
- const binding = LEGACY_SCOPE_BINDINGS.get(scope);
93546
+ const requestedEntry = raw.findEntry({ scope, at: collectedAt });
93547
+ const ownVersion = requestedEntry ? `${requestedEntry.id}@${requestedEntry.collectedAt}` : `unindexed@${collectedAt}`;
93548
+ const formKey = JSON.stringify([scope, ownVersion]);
93549
+ let cached2 = forms.get(formKey);
93550
+ let own;
93551
+ if (!cached2) {
93552
+ own = await raw.readEnvelope(scope, collectedAt);
93553
+ const form = classifyStoredBody(scope, own.data);
93554
+ cached2 = {
93555
+ form,
93556
+ ...form === "pdpp-projected" ? {
93557
+ selected: selectProjectionBinding(scope, own.data.records)
93558
+ } : {}
93559
+ };
93560
+ rememberForm(formKey, cached2);
93561
+ }
93562
+ if (cached2.form === "legacy")
93563
+ return { view: null, own };
93564
+ if (cached2.form === "pdpp-unprojected") {
93565
+ failProjection(scope, collectedAt, {
93566
+ kind: "incomplete_scope",
93567
+ scope,
93568
+ reason: "Stored records are not rows of one stream"
93569
+ });
93570
+ }
93571
+ if (!cached2.selected) {
93572
+ failProjection(scope, collectedAt, {
93573
+ kind: "incomplete_scope",
93574
+ scope,
93575
+ reason: "Stored records do not identify one compatible connector profile"
93576
+ });
93577
+ }
93578
+ const { binding, profileKey } = cached2.selected;
93366
93579
  const source3 = scope.slice(0, scope.indexOf("."));
93367
93580
  const supersededAt = nextVersionTime(raw, scope, collectedAt);
93368
93581
  const inputs = binding.pdppStreams.map((stream) => {
93369
93582
  const canonicalScope = `${source3}.${stream}`;
93370
- const requestedEntry = raw.findEntry({ scope, at: collectedAt });
93371
93583
  let storedScope = binding.pdppStreams.length === 1 && requestedEntry ? scope : canonicalScope;
93372
93584
  let entry = storedScope === scope ? requestedEntry : supersededAt === void 0 ? raw.findEntry({ scope: storedScope }) : nearestBefore(raw, storedScope, collectedAt, supersededAt);
93373
93585
  if (!entry && binding.pdppStreams.length === 1 && storedScope !== scope) {
@@ -93383,38 +93595,35 @@ function withLegacyProjection(raw, options = {}) {
93383
93595
  version: entry ? `${entry.id}@${entry.collectedAt}` : null
93384
93596
  };
93385
93597
  });
93386
- const ownVersion = inputs.find((input) => input.storedScope === scope)?.version;
93387
- let own;
93388
- let form = ownVersion ? forms.get(ownVersion) : void 0;
93389
- if (form === void 0) {
93390
- own = await raw.readEnvelope(scope, collectedAt);
93391
- form = classifyStoredBody(scope, own.data);
93392
- if (ownVersion)
93393
- rememberForm(ownVersion, form);
93394
- }
93395
- if (form !== "pdpp-projected")
93396
- return { view: null, own };
93397
93598
  const key = JSON.stringify([
93398
93599
  scope,
93399
93600
  ownVersion,
93601
+ profileKey,
93400
93602
  inputs.map(({ storedScope, version: version4 }) => [storedScope, version4])
93401
93603
  ]);
93402
93604
  if (memo?.key === key)
93403
93605
  return { view: memo.value, own };
93404
93606
  own ??= await raw.readEnvelope(scope, collectedAt);
93405
- let value = null;
93406
- if (form === "pdpp-projected") {
93407
- value = await project(scope, collectedAt, own, inputs);
93408
- if (value)
93409
- value.view = key;
93410
- }
93607
+ const value = await project(scope, collectedAt, own, inputs, binding, profileKey);
93608
+ if (value)
93609
+ value.view = key;
93411
93610
  memo = { key, value };
93412
93611
  return { view: value, own };
93413
93612
  }
93414
93613
  async function projected(scope, collectedAt) {
93415
93614
  return (await resolve(scope, collectedAt)).view;
93416
93615
  }
93417
- async function project(scope, collectedAt, own, inputs) {
93616
+ async function projectedForSupersede(scope, collectedAt) {
93617
+ try {
93618
+ return await projected(scope, collectedAt);
93619
+ } catch (error51) {
93620
+ if (error51 instanceof ProtocolError && error51.errorCode === "LEGACY_PROJECTION_UNAVAILABLE") {
93621
+ return null;
93622
+ }
93623
+ throw error51;
93624
+ }
93625
+ }
93626
+ async function project(scope, collectedAt, own, inputs, binding, profileKey) {
93418
93627
  const records = [];
93419
93628
  const fetchedStreams = [];
93420
93629
  let now = collectedAt;
@@ -93436,20 +93645,27 @@ function withLegacyProjection(raw, options = {}) {
93436
93645
  records.push({ stream: input.stream, data: row });
93437
93646
  }
93438
93647
  }
93439
- const result = projectPdppRecordsToLegacyPayload(scope, records, {
93648
+ if (!recordsMatchBindingSource(records, binding, alternateLegacyBindingsForScope(scope).size > 0)) {
93649
+ failProjection(scope, collectedAt, {
93650
+ kind: "incomplete_scope",
93651
+ scope,
93652
+ reason: "Joined streams have conflicting connector identities"
93653
+ });
93654
+ }
93655
+ const projectionRecords = records.map((record2) => {
93656
+ const data = { ...record2.data };
93657
+ delete data.$pdpp;
93658
+ return { ...record2, data };
93659
+ });
93660
+ const result = projectPdppRecordsToLegacyPayload(scope, projectionRecords, {
93440
93661
  fetchedStreams,
93441
93662
  now,
93442
- orderByPrimaryKey: true,
93663
+ ...profileKey ? { profileKey } : {},
93664
+ orderByPrimaryKey: binding.rowOrder !== "arrival",
93443
93665
  allowMissingJoinStreams: true
93444
93666
  });
93445
93667
  if (!result.ok) {
93446
- options.onIssue?.({
93447
- kind: "projection_failed",
93448
- scope,
93449
- collectedAt,
93450
- error: result.error
93451
- });
93452
- return null;
93668
+ failProjection(scope, collectedAt, result.error);
93453
93669
  }
93454
93670
  if (result.diagnostics?.length) {
93455
93671
  options.onIssue?.({
@@ -93477,7 +93693,7 @@ function withLegacyProjection(raw, options = {}) {
93477
93693
  }
93478
93694
  const overrides = {
93479
93695
  [SERVED]: true,
93480
- [PROJECTED_VIEW]: projected,
93696
+ [PROJECTED_VIEW]: projectedForSupersede,
93481
93697
  async readEnvelope(scope, collectedAt) {
93482
93698
  const { view, own } = await resolve(scope, collectedAt);
93483
93699
  return view?.envelope ?? own ?? raw.readEnvelope(scope, collectedAt);
@@ -93529,10 +93745,6 @@ function withLegacyProjection(raw, options = {}) {
93529
93745
  return view ? (await builtBlocks(scope, view)).manifest : rawManifest(scope, collectedAt);
93530
93746
  };
93531
93747
  }
93532
- if (raw.hasScopeBlocks) {
93533
- const rawHas = raw.hasScopeBlocks.bind(raw);
93534
- overrides.hasScopeBlocks = async (scope, collectedAt) => await rawHas(scope, collectedAt) || await projected(scope, collectedAt) !== null;
93535
- }
93536
93748
  if (raw.canReadScopeBlocks) {
93537
93749
  const rawCan = raw.canReadScopeBlocks.bind(raw);
93538
93750
  overrides.canReadScopeBlocks = async (scope, collectedAt) => await rawCan(scope, collectedAt) || await projected(scope, collectedAt) !== null;
@@ -93559,8 +93771,52 @@ function legacyScopesProjectedFrom(scope) {
93559
93771
  return [...LEGACY_SCOPE_BINDINGS.values()].filter((binding) => binding.scope !== scope && binding.scope.startsWith(`${source3}.`) && isProjectedScope(binding.scope) && binding.pdppStreams.includes(stream)).map((binding) => binding.scope);
93560
93772
  }
93561
93773
  function isProjectedScope(scope) {
93562
- const dot = scope.indexOf(".");
93563
- return dot > 0 && PROJECTED_SOURCES.has(scope.slice(0, dot)) && LEGACY_SCOPE_BINDINGS.has(scope);
93774
+ return LEGACY_SCOPE_BINDINGS.has(scope);
93775
+ }
93776
+ function selectProjectionBinding(scope, rows) {
93777
+ const original2 = LEGACY_SCOPE_BINDINGS.get(scope);
93778
+ const alternates = alternateLegacyBindingsForScope(scope);
93779
+ const identities = rows.map(recordSourceId);
93780
+ if (identities.includes(null))
93781
+ return null;
93782
+ if (alternates.size > 0 && identities.includes(void 0))
93783
+ return null;
93784
+ const sources = new Set(identities.filter((id2) => !!id2));
93785
+ if (sources.size > 1)
93786
+ return null;
93787
+ if (sources.size === 0) {
93788
+ return alternates.size === 0 ? { binding: original2 } : null;
93789
+ }
93790
+ const sourceId = [...sources][0];
93791
+ const connectorKey = sourceId.slice(sourceId.lastIndexOf("/") + 1);
93792
+ const alternate = alternates.get(connectorKey);
93793
+ if (alternate && sourceIdForBinding(alternate) === sourceId) {
93794
+ return { binding: alternate, profileKey: connectorKey };
93795
+ }
93796
+ return sourceIdForBinding(original2) === sourceId ? { binding: original2 } : null;
93797
+ }
93798
+ function recordSourceId(data) {
93799
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
93800
+ return null;
93801
+ }
93802
+ if (!("$pdpp" in data))
93803
+ return void 0;
93804
+ const metadata = data.$pdpp;
93805
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
93806
+ return null;
93807
+ }
93808
+ const sourceId = metadata.sourceId;
93809
+ return typeof sourceId === "string" && sourceId ? sourceId : null;
93810
+ }
93811
+ function sourceIdForBinding(binding) {
93812
+ return binding.pdppSource.replace("/connectors/", "/sources/");
93813
+ }
93814
+ function recordsMatchBindingSource(records, binding, requireIdentity) {
93815
+ const expected = sourceIdForBinding(binding);
93816
+ return records.every(({ data }) => {
93817
+ const actual = recordSourceId(data);
93818
+ return actual === expected || !requireIdentity && actual === void 0;
93819
+ });
93564
93820
  }
93565
93821
  var VERSION_PAGE_SIZE = 100;
93566
93822
  function walkVersions(raw, scope, stop) {
@@ -93623,6 +93879,9 @@ async function supersedeLegacyVersions(storage, scope, committedAt) {
93623
93879
  if (scope.startsWith("youtube.")) {
93624
93880
  return refuse("YouTube legacy versions are retained for read-time projection");
93625
93881
  }
93882
+ if (isProjectedScope(scope) && !scope.startsWith("chatgpt.") && !scope.startsWith("claude.")) {
93883
+ return refuse("Legacy versions are retained for read-time projection");
93884
+ }
93626
93885
  const readStored = (storage.readStoredEnvelope ?? storage.readEnvelope).bind(storage);
93627
93886
  const committed = await readStored(scope, committedAt);
93628
93887
  if (classifyStoredBody(scope, committed.data) !== "pdpp-projected") {
@@ -95286,21 +95545,21 @@ init_sha2();
95286
95545
  init_openpgp_min();
95287
95546
 
95288
95547
  // ../../node_modules/@opendatalabs/vana-sdk/dist/auth/errors.js
95289
- var MissingAuthError = class extends VanaError {
95548
+ var MissingAuthError2 = class extends VanaError {
95290
95549
  constructor(message = "Missing authentication", details) {
95291
95550
  super(message, "MISSING_AUTH");
95292
95551
  this.details = details;
95293
95552
  }
95294
95553
  details;
95295
95554
  };
95296
- var InvalidSignatureError2 = class extends VanaError {
95555
+ var InvalidSignatureError3 = class extends VanaError {
95297
95556
  constructor(details, message = "Invalid signature") {
95298
95557
  super(message, "INVALID_SIGNATURE");
95299
95558
  this.details = details;
95300
95559
  }
95301
95560
  details;
95302
95561
  };
95303
- var ExpiredTokenError = class extends VanaError {
95562
+ var ExpiredTokenError2 = class extends VanaError {
95304
95563
  constructor(details, message = "Token has expired") {
95305
95564
  super(message, "EXPIRED_TOKEN");
95306
95565
  this.details = details;
@@ -111975,14 +112234,14 @@ function isFiniteNumber(value) {
111975
112234
  }
111976
112235
  function parsePayload(value) {
111977
112236
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
111978
- throw new InvalidSignatureError2({ reason: "Invalid payload shape" });
112237
+ throw new InvalidSignatureError3({ reason: "Invalid payload shape" });
111979
112238
  }
111980
112239
  const payload = value;
111981
112240
  if (typeof payload["aud"] !== "string" || typeof payload["method"] !== "string" || typeof payload["uri"] !== "string" || typeof payload["bodyHash"] !== "string" || !isFiniteNumber(payload["iat"]) || !isFiniteNumber(payload["exp"])) {
111982
- throw new InvalidSignatureError2({ reason: "Invalid payload claims" });
112241
+ throw new InvalidSignatureError3({ reason: "Invalid payload claims" });
111983
112242
  }
111984
112243
  if (payload["grantId"] !== void 0 && typeof payload["grantId"] !== "string") {
111985
- throw new InvalidSignatureError2({ reason: "Invalid grantId claim" });
112244
+ throw new InvalidSignatureError3({ reason: "Invalid grantId claim" });
111986
112245
  }
111987
112246
  return {
111988
112247
  aud: payload["aud"],
@@ -111996,28 +112255,28 @@ function parsePayload(value) {
111996
112255
  }
111997
112256
  function parseWeb3SignedHeader(headerValue) {
111998
112257
  if (!headerValue) {
111999
- throw new MissingAuthError();
112258
+ throw new MissingAuthError2();
112000
112259
  }
112001
112260
  if (!headerValue.startsWith(WEB3_SIGNED_PREFIX)) {
112002
- throw new InvalidSignatureError2({ reason: "Missing Web3Signed prefix" });
112261
+ throw new InvalidSignatureError3({ reason: "Missing Web3Signed prefix" });
112003
112262
  }
112004
112263
  const value = headerValue.slice(WEB3_SIGNED_PREFIX.length);
112005
112264
  const dotIndex = value.indexOf(".");
112006
112265
  if (dotIndex === -1 || dotIndex === 0 || dotIndex === value.length - 1) {
112007
- throw new InvalidSignatureError2({ reason: "Invalid header format" });
112266
+ throw new InvalidSignatureError3({ reason: "Invalid header format" });
112008
112267
  }
112009
112268
  const payloadBase64 = value.slice(0, dotIndex);
112010
112269
  const signatureStr = value.slice(dotIndex + 1);
112011
112270
  if (!signatureStr.startsWith("0x")) {
112012
- throw new InvalidSignatureError2({ reason: "Invalid signature format" });
112271
+ throw new InvalidSignatureError3({ reason: "Invalid signature format" });
112013
112272
  }
112014
112273
  let payload;
112015
112274
  try {
112016
112275
  const decoded = base64urlDecode(payloadBase64);
112017
112276
  payload = parsePayload(JSON.parse(decoded));
112018
112277
  } catch (err2) {
112019
- if (err2 instanceof InvalidSignatureError2) throw err2;
112020
- throw new InvalidSignatureError2({ reason: "Invalid payload encoding" });
112278
+ if (err2 instanceof InvalidSignatureError3) throw err2;
112279
+ throw new InvalidSignatureError3({ reason: "Invalid payload encoding" });
112021
112280
  }
112022
112281
  return {
112023
112282
  payloadBase64,
@@ -112036,24 +112295,24 @@ async function verifyWeb3Signed(params) {
112036
112295
  signature
112037
112296
  });
112038
112297
  } catch {
112039
- throw new InvalidSignatureError2({ reason: "Signature recovery failed" });
112298
+ throw new InvalidSignatureError3({ reason: "Signature recovery failed" });
112040
112299
  }
112041
112300
  if (payload.aud !== params.expectedOrigin) {
112042
- throw new InvalidSignatureError2({
112301
+ throw new InvalidSignatureError3({
112043
112302
  reason: "Audience mismatch",
112044
112303
  expected: params.expectedOrigin,
112045
112304
  actual: payload.aud
112046
112305
  });
112047
112306
  }
112048
112307
  if (payload.method !== params.expectedMethod) {
112049
- throw new InvalidSignatureError2({
112308
+ throw new InvalidSignatureError3({
112050
112309
  reason: "Method mismatch",
112051
112310
  expected: params.expectedMethod,
112052
112311
  actual: payload.method
112053
112312
  });
112054
112313
  }
112055
112314
  if (payload.uri !== params.expectedPath) {
112056
- throw new InvalidSignatureError2({
112315
+ throw new InvalidSignatureError3({
112057
112316
  reason: "URI mismatch",
112058
112317
  expected: params.expectedPath,
112059
112318
  actual: payload.uri
@@ -112062,7 +112321,7 @@ async function verifyWeb3Signed(params) {
112062
112321
  if (params.bodyBytes !== void 0) {
112063
112322
  const expectedBodyHash = computeBodyHash(params.bodyBytes);
112064
112323
  if (payload.bodyHash !== expectedBodyHash) {
112065
- throw new InvalidSignatureError2({
112324
+ throw new InvalidSignatureError3({
112066
112325
  reason: "Body hash mismatch",
112067
112326
  expected: expectedBodyHash,
112068
112327
  actual: payload.bodyHash
@@ -112071,10 +112330,10 @@ async function verifyWeb3Signed(params) {
112071
112330
  }
112072
112331
  const now = params.now ?? Math.floor(Date.now() / 1e3);
112073
112332
  if (payload.exp < now - CLOCK_SKEW_SECONDS) {
112074
- throw new ExpiredTokenError({ reason: "Token expired" });
112333
+ throw new ExpiredTokenError2({ reason: "Token expired" });
112075
112334
  }
112076
112335
  if (payload.iat > now + CLOCK_SKEW_SECONDS) {
112077
- throw new ExpiredTokenError({ reason: "Token issued in the future" });
112336
+ throw new ExpiredTokenError2({ reason: "Token issued in the future" });
112078
112337
  }
112079
112338
  return { signer, payload };
112080
112339
  }
@@ -113098,180 +113357,6 @@ function createRequestSigner(account) {
113098
113357
  };
113099
113358
  }
113100
113359
 
113101
- // ../core/dist/errors/catalog.js
113102
- var ProtocolError = class extends Error {
113103
- code;
113104
- errorCode;
113105
- details;
113106
- constructor(code, errorCode, message, details) {
113107
- super(message);
113108
- this.code = code;
113109
- this.errorCode = errorCode;
113110
- this.details = details;
113111
- this.name = this.constructor.name;
113112
- }
113113
- toJSON() {
113114
- return {
113115
- error: {
113116
- code: this.code,
113117
- errorCode: this.errorCode,
113118
- message: this.message,
113119
- ...this.details !== void 0 && { details: this.details }
113120
- }
113121
- };
113122
- }
113123
- };
113124
- var MissingAuthError2 = class extends ProtocolError {
113125
- constructor(details) {
113126
- super(401, "MISSING_AUTH", "Missing authentication", details);
113127
- }
113128
- };
113129
- var InvalidSignatureError3 = class extends ProtocolError {
113130
- constructor(details) {
113131
- super(401, "INVALID_SIGNATURE", "Invalid signature", details);
113132
- }
113133
- };
113134
- var UnregisteredBuilderError = class extends ProtocolError {
113135
- constructor(details) {
113136
- super(401, "UNREGISTERED_BUILDER", "Unregistered builder", details);
113137
- }
113138
- };
113139
- var NotOwnerError = class extends ProtocolError {
113140
- constructor(details) {
113141
- super(401, "NOT_OWNER", "Not the owner", details);
113142
- }
113143
- };
113144
- var ExpiredTokenError2 = class extends ProtocolError {
113145
- constructor(details) {
113146
- super(401, "EXPIRED_TOKEN", "Token has expired", details);
113147
- }
113148
- };
113149
- var GrantRequiredError = class extends ProtocolError {
113150
- constructor(details) {
113151
- super(403, "GRANT_REQUIRED", "Grant required", details);
113152
- }
113153
- };
113154
- var GrantExpiredError = class extends ProtocolError {
113155
- constructor(details) {
113156
- super(403, "GRANT_EXPIRED", "Grant has expired", details);
113157
- }
113158
- };
113159
- var GrantRevokedError = class extends ProtocolError {
113160
- constructor(details) {
113161
- super(403, "GRANT_REVOKED", "Grant has been revoked", details);
113162
- }
113163
- };
113164
- var ScopeMismatchError = class extends ProtocolError {
113165
- constructor(details) {
113166
- super(403, "SCOPE_MISMATCH", "Scope not granted", details);
113167
- }
113168
- };
113169
- var GrantOwnerMismatchError = class extends ProtocolError {
113170
- constructor(details) {
113171
- super(403, "GRANT_OWNER_MISMATCH", "Grant was not issued by this server's owner", details);
113172
- }
113173
- };
113174
- var PsUnavailableError = class extends ProtocolError {
113175
- constructor(details) {
113176
- super(503, "PS_UNAVAILABLE", "Personal Server runtime unavailable", details);
113177
- }
113178
- };
113179
- var ServerNotConfiguredError = class extends ProtocolError {
113180
- constructor(details) {
113181
- super(500, "SERVER_NOT_CONFIGURED", "Server is not configured", details);
113182
- }
113183
- };
113184
- var ServerSigningUnavailableError = class extends ProtocolError {
113185
- constructor() {
113186
- super(500, "SERVER_SIGNING_UNAVAILABLE", "Server signing is unavailable in this runtime");
113187
- }
113188
- };
113189
- var ContentTooLargeError = class extends ProtocolError {
113190
- constructor(details) {
113191
- super(413, "CONTENT_TOO_LARGE", "Content too large", details);
113192
- }
113193
- };
113194
- var LineageInvalidError = class extends ProtocolError {
113195
- constructor(message, details) {
113196
- super(400, "LINEAGE_INVALID", message, details);
113197
- }
113198
- };
113199
- var LineageScopeUnderSourcePrefixError = class extends ProtocolError {
113200
- constructor(details) {
113201
- super(400, "LINEAGE_SCOPE_UNDER_SOURCE_PREFIX", `Derived scope "${details.scope}" shares its first segment with source scope "${details.sourceScope}"; a wildcard grant on that namespace would read both. Name derivatives under their own namespace.`, details);
113202
- }
113203
- };
113204
- var LineageSourceUnknownError = class extends ProtocolError {
113205
- constructor(details) {
113206
- super(422, "LINEAGE_SOURCE_UNKNOWN", "One or more lineage sources are not data points of this owner", details);
113207
- }
113208
- };
113209
- var LineageSourceLookupFailedError = class extends ProtocolError {
113210
- constructor(details) {
113211
- super(502, "LINEAGE_SOURCE_LOOKUP_FAILED", "Could not resolve a lineage source at the gateway", details);
113212
- }
113213
- };
113214
- var LineageUnavailableError = class extends ProtocolError {
113215
- constructor(details) {
113216
- super(503, "LINEAGE_UNAVAILABLE", "This server is not configured to reach the gateway lineage graph (gateway URL or server signing key missing)", details);
113217
- }
113218
- };
113219
- var LineageGatewayError = class extends ProtocolError {
113220
- constructor(details) {
113221
- super(502, "LINEAGE_GATEWAY_ERROR", `Gateway lineage request failed with status ${details.status}`, details);
113222
- }
113223
- };
113224
- var LineageCascadeUnavailableError = class extends ProtocolError {
113225
- constructor(details) {
113226
- super(501, "LINEAGE_CASCADE_UNAVAILABLE", "DELETE ?cascade=lineage is specified but not implemented yet: the lineage walk that finds every derivative is missing. Delete scopes one at a time; each single-scope delete is durable.", details);
113227
- }
113228
- };
113229
- var InvalidCascadeError = class extends ProtocolError {
113230
- constructor(details) {
113231
- super(400, "INVALID_CASCADE", 'Unsupported cascade mode; the only supported value is "lineage"', details);
113232
- }
113233
- };
113234
- var DeleteTombstoneFailedError = class extends ProtocolError {
113235
- constructor(details) {
113236
- super(502, "DELETE_TOMBSTONE_FAILED", "Gateway did not acknowledge the deletion tombstone; nothing was deleted", details);
113237
- }
113238
- };
113239
- var DataDeletedError = class extends ProtocolError {
113240
- constructor(details) {
113241
- super(410, "DATA_DELETED", "Data point has been deleted", details);
113242
- }
113243
- };
113244
- var DerivativeQuestionInvalidError = class extends ProtocolError {
113245
- constructor(message, details) {
113246
- super(400, "DERIVATIVE_QUESTION_INVALID", message, details);
113247
- }
113248
- };
113249
- var DerivativeQuestionNotFoundError = class extends ProtocolError {
113250
- constructor(details) {
113251
- super(404, "DERIVATIVE_QUESTION_NOT_FOUND", "Question not found", details);
113252
- }
113253
- };
113254
- var DerivativeDerivedScopeRequiredError = class extends ProtocolError {
113255
- constructor(details) {
113256
- super(400, "DERIVATIVE_DERIVED_SCOPE_REQUIRED", "Listing questions as a builder needs a derived scope: add ?derivedScope=<scope>. The unfiltered list is the owner's", details);
113257
- }
113258
- };
113259
- var DerivativeCycleError = class extends ProtocolError {
113260
- constructor(details) {
113261
- super(409, "DERIVATIVE_CYCLE", `Registering this question would make "${details.derivedScope}" a transitive source of itself; recompute would never settle`, details);
113262
- }
113263
- };
113264
- var DerivativeSourceNotGrantedError = class extends ProtocolError {
113265
- constructor(details) {
113266
- super(403, "DERIVATIVE_SOURCE_NOT_GRANTED", "The builder's grant does not cover reading every source scope of this question", details);
113267
- }
113268
- };
113269
- var DerivativeComputeUnavailableError = class extends ProtocolError {
113270
- constructor(details) {
113271
- super(503, "DERIVATIVE_COMPUTE_UNAVAILABLE", "This server has no derivative compute configured", details);
113272
- }
113273
- };
113274
-
113275
113360
  // ../core/dist/sync/data-point-id.js
113276
113361
  function computeDataPointId(ownerAddress, scope) {
113277
113362
  return keccak256(encodeAbiParameters([
@@ -117073,7 +117158,7 @@ function verifyPdppGrantBinding(input) {
117073
117158
  });
117074
117159
  }
117075
117160
  if (!sameHex(input.requestSigner, binding.granteeAddress)) {
117076
- throw new InvalidSignatureError3({
117161
+ throw new InvalidSignatureError({
117077
117162
  reason: "Request signer is not the bound grantee for this PDPP grant",
117078
117163
  expected: binding.granteeAddress,
117079
117164
  actual: input.requestSigner
@@ -117097,7 +117182,7 @@ function verifyPdppGrantBinding(input) {
117097
117182
  throw new GrantRevokedError({ grantId: chainGrant.id });
117098
117183
  }
117099
117184
  if (!grantVersionStillAuthorizes(binding.grantVersion, chainGrant.grantVersion)) {
117100
- throw new InvalidSignatureError3({
117185
+ throw new InvalidSignatureError({
117101
117186
  reason: "Chain grant version no longer matches the bound grantVersion",
117102
117187
  expected: binding.grantVersion,
117103
117188
  actual: chainGrant.grantVersion
@@ -117111,7 +117196,7 @@ function verifyPdppGrantBinding(input) {
117111
117196
  });
117112
117197
  }
117113
117198
  if (!sameHex(chainGrant.granteeId, binding.granteeId)) {
117114
- throw new InvalidSignatureError3({
117199
+ throw new InvalidSignatureError({
117115
117200
  reason: "Chain grant grantee no longer matches the bound grantee",
117116
117201
  expected: binding.granteeId,
117117
117202
  actual: chainGrant.granteeId
@@ -117242,7 +117327,7 @@ function assertGrantAuthorizesBuilder(grant, builder, input) {
117242
117327
  });
117243
117328
  }
117244
117329
  if (builder.id.toLowerCase() !== grant.granteeId.toLowerCase()) {
117245
- throw new InvalidSignatureError3({
117330
+ throw new InvalidSignatureError({
117246
117331
  reason: "Request signer is not the grant builder",
117247
117332
  expected: grant.granteeId,
117248
117333
  actual: input.signer
@@ -117333,6 +117418,27 @@ function isTombstoneRecord(record2) {
117333
117418
  var DEFAULT_SCOPE_DELETION_MAX_STALENESS_MS = 12e4;
117334
117419
  var DEFAULT_SCOPE_DELETION_GATEWAY_RETRY_MS = 15e3;
117335
117420
  var DEFAULT_MAX_LIVE_ENTRIES = 1e4;
117421
+ var DeletionLookupTimeout = class extends Error {
117422
+ };
117423
+ async function beforeDeadline(request2, timeoutMs, onTimeout) {
117424
+ if (timeoutMs === void 0)
117425
+ return request2;
117426
+ let timer;
117427
+ try {
117428
+ return await Promise.race([
117429
+ request2,
117430
+ new Promise((_11, reject) => {
117431
+ timer = setTimeout(() => {
117432
+ reject(new DeletionLookupTimeout("Deletion lookup deadline exceeded"));
117433
+ onTimeout?.();
117434
+ }, timeoutMs);
117435
+ })
117436
+ ]);
117437
+ } finally {
117438
+ if (timer !== void 0)
117439
+ clearTimeout(timer);
117440
+ }
117441
+ }
117336
117442
  function createScopeDeletionTracker(options = {}) {
117337
117443
  const maxStalenessMs = options.maxStalenessMs ?? DEFAULT_SCOPE_DELETION_MAX_STALENESS_MS;
117338
117444
  const gatewayRetryMs = options.gatewayRetryMs ?? DEFAULT_SCOPE_DELETION_GATEWAY_RETRY_MS;
@@ -117405,24 +117511,32 @@ function createScopeDeletionTracker(options = {}) {
117405
117511
  rememberLive(scope, nowMs2());
117406
117512
  return { deleted: false, source: "gateway", verified: true };
117407
117513
  }
117408
- async function lookup2(scope) {
117514
+ async function lookup2(scope, timeoutMs) {
117409
117515
  const feed = options.feed;
117410
117516
  const owner = options.serverOwner;
117411
- if (!feed || !owner)
117517
+ if (!feed || !owner || timeoutMs !== void 0 && timeoutMs <= 0)
117412
117518
  return null;
117413
117519
  if (lastGatewayFailureMs !== null && nowMs2() - lastGatewayFailureMs < gatewayRetryMs) {
117414
117520
  return null;
117415
117521
  }
117416
117522
  const pending = inflight.get(scope);
117417
- if (pending)
117418
- return pending;
117523
+ if (pending) {
117524
+ return beforeDeadline(pending, timeoutMs).catch((error51) => {
117525
+ if (error51 instanceof DeletionLookupTimeout)
117526
+ return null;
117527
+ throw error51;
117528
+ });
117529
+ }
117530
+ const deletionAtStart = deleted.get(scope);
117419
117531
  const request2 = (async () => {
117420
117532
  let record2;
117533
+ const controller = timeoutMs === void 0 ? void 0 : new AbortController();
117421
117534
  try {
117422
- record2 = await feed.getDataPoint({
117535
+ record2 = await beforeDeadline(feed.getDataPoint({
117423
117536
  ownerAddress: owner,
117424
- scope
117425
- });
117537
+ scope,
117538
+ ...controller ? { signal: controller.signal } : {}
117539
+ }), timeoutMs, () => controller?.abort());
117426
117540
  lastGatewayFailureMs = null;
117427
117541
  } catch (err2) {
117428
117542
  lastGatewayFailureMs = nowMs2();
@@ -117433,11 +117547,23 @@ function createScopeDeletionTracker(options = {}) {
117433
117547
  }, "Could not check gateway deletion state; serving last known state");
117434
117548
  return null;
117435
117549
  }
117550
+ if (deleted.get(scope) !== deletionAtStart)
117551
+ return lastKnownVerdict(scope);
117436
117552
  return verdictFromRecord(scope, record2);
117437
117553
  })().finally(() => inflight.delete(scope));
117438
117554
  inflight.set(scope, request2);
117439
117555
  return request2;
117440
117556
  }
117557
+ function lastKnownVerdict(scope) {
117558
+ const known = deleted.get(scope);
117559
+ return known ? {
117560
+ deleted: true,
117561
+ deletedAt: known.deletedAt,
117562
+ version: known.version,
117563
+ source: known.source,
117564
+ verified: false
117565
+ } : { deleted: false, source: "assumed-live", verified: false };
117566
+ }
117441
117567
  return {
117442
117568
  maxStalenessMs,
117443
117569
  deletionHistory,
@@ -117476,16 +117602,10 @@ function createScopeDeletionTracker(options = {}) {
117476
117602
  verified: true
117477
117603
  };
117478
117604
  }
117479
- const rechecked = await lookup2(scope);
117605
+ const rechecked = await lookup2(scope, resolveOptions?.gatewayTimeoutMs);
117480
117606
  if (rechecked !== null)
117481
117607
  return rechecked;
117482
- return {
117483
- deleted: true,
117484
- deletedAt: known.deletedAt,
117485
- version: known.version,
117486
- source: known.source,
117487
- verified: false
117488
- };
117608
+ return lastKnownVerdict(scope);
117489
117609
  }
117490
117610
  if (isFresh(live.get(scope) ?? null)) {
117491
117611
  return { deleted: false, source: "gateway", verified: true };
@@ -117494,11 +117614,7 @@ function createScopeDeletionTracker(options = {}) {
117494
117614
  if (consult === "if-stale" && isFresh(lastFeedSyncMs)) {
117495
117615
  return { deleted: false, source: "feed", verified: true };
117496
117616
  }
117497
- return await lookup2(scope) ?? {
117498
- deleted: false,
117499
- source: "assumed-live",
117500
- verified: false
117501
- };
117617
+ return await lookup2(scope, resolveOptions?.gatewayTimeoutMs) ?? lastKnownVerdict(scope);
117502
117618
  }
117503
117619
  };
117504
117620
  }
@@ -118566,11 +118682,12 @@ async function parseProducerProvenance(encoded, body) {
118566
118682
  return errorResponse(400, "INVALID_PROVENANCE", "Vana-Producer-Provenance is not base64url JSON");
118567
118683
  }
118568
118684
  }
118569
- async function resolveReadDeletion(deps, scope, entry, body = "file") {
118685
+ async function resolveReadDeletion(deps, scope, entry, body = "file", gatewayTimeoutMs) {
118570
118686
  if (!deps.scopeDeletions)
118571
118687
  return null;
118572
118688
  const verdict = await deps.scopeDeletions.resolve(scope, {
118573
- consultGateway: entry ? "if-stale" : "always"
118689
+ consultGateway: entry ? "if-stale" : "always",
118690
+ ...gatewayTimeoutMs === void 0 ? {} : { gatewayTimeoutMs }
118574
118691
  });
118575
118692
  const tombstone = body === "canonical" ? deps.scopeDeletions.deletionHistory?.get(scope) ?? (verdict.deleted ? verdict : null) : verdict.deleted ? verdict : null;
118576
118693
  if (!tombstone)
@@ -118594,8 +118711,8 @@ function discoveryVisibility(deps) {
118594
118711
  return void 0;
118595
118712
  return async (scope, entry) => await resolveReadDeletion(deps, scope, entry) === null;
118596
118713
  }
118597
- function listingVisibility(deps) {
118598
- const deletion = discoveryVisibility(deps);
118714
+ function listingVisibility(deps, deadlineAtMs) {
118715
+ const deletion = deps.scopeDeletions ? async (scope, entry) => await resolveReadDeletion(deps, scope, entry, "file", Math.max(0, deadlineAtMs - Date.now())) === null : void 0;
118599
118716
  const view = deps.legacyScopeView;
118600
118717
  if (!view)
118601
118718
  return deletion;
@@ -118604,10 +118721,10 @@ function listingVisibility(deps) {
118604
118721
  if (listing.kind === "refused")
118605
118722
  return false;
118606
118723
  const canonicalOwned = view.ownsScope(scope);
118607
- return await resolveReadDeletion(deps, scope, canonicalOwned ? void 0 : entry, canonicalOwned ? "canonical" : "file") === null;
118724
+ return await resolveReadDeletion(deps, scope, canonicalOwned ? void 0 : entry, canonicalOwned ? "canonical" : "file", Math.max(0, deadlineAtMs - Date.now())) === null;
118608
118725
  };
118609
118726
  }
118610
- function canonicalOnlyScopes(deps) {
118727
+ function canonicalOnlyScopes(deps, deadlineAtMs) {
118611
118728
  const view = deps.legacyScopeView;
118612
118729
  if (!view)
118613
118730
  return void 0;
@@ -118616,7 +118733,7 @@ function canonicalOnlyScopes(deps) {
118616
118733
  for (const { scope, collectedAt } of view.listCanonicalScopes(scopePrefix)) {
118617
118734
  if (stored.has(scope))
118618
118735
  continue;
118619
- if (await resolveReadDeletion(deps, scope, void 0, "canonical") !== null) {
118736
+ if (await resolveReadDeletion(deps, scope, void 0, "canonical", Math.max(0, deadlineAtMs - Date.now())) !== null) {
118620
118737
  continue;
118621
118738
  }
118622
118739
  listed.push({ scope, latestCollectedAt: collectedAt, versionCount: 0 });
@@ -118818,14 +118935,15 @@ async function handlePersonalServerDataRequest(request2, deps, options = {}) {
118818
118935
  const listAuth = await deps.auth.authorizeBuilderList(request2, {
118819
118936
  grantId: selectedGrantId(request2, url2)
118820
118937
  });
118938
+ const deletionDeadlineAtMs = Date.now() + 250;
118821
118939
  const result = await listDataScopesContract({
118822
118940
  storage: deps.storage,
118823
118941
  scopePrefix: url2.searchParams.get("scopePrefix") ?? void 0,
118824
118942
  limit: normalizeLimit2(url2.searchParams.get("limit"), 20),
118825
118943
  offset: normalizeLimit2(url2.searchParams.get("offset"), 0),
118826
- isVisible: listingVisibility(deps),
118944
+ isVisible: listingVisibility(deps, deletionDeadlineAtMs),
118827
118945
  isListable: (scope) => !isSystemScope(scope) && (!listAuth || listAuthCovers(listAuth, scope)),
118828
- extraScopes: canonicalOnlyScopes(deps)
118946
+ extraScopes: canonicalOnlyScopes(deps, deletionDeadlineAtMs)
118829
118947
  });
118830
118948
  return jsonResponse({
118831
118949
  ...result.response,
@@ -119687,7 +119805,7 @@ async function verifyDataWritePolicy(input, ports) {
119687
119805
  });
119688
119806
  }
119689
119807
  if (builder.id.toLowerCase() !== grant.granteeId.toLowerCase()) {
119690
- throw new InvalidSignatureError3({
119808
+ throw new InvalidSignatureError({
119691
119809
  reason: "Write signer is not the grant builder",
119692
119810
  expected: grant.granteeId,
119693
119811
  actual: input.signer
@@ -119769,7 +119887,7 @@ async function createWriteSession(input, options) {
119769
119887
  });
119770
119888
  }
119771
119889
  if (builder.id.toLowerCase() !== grant.granteeId.toLowerCase()) {
119772
- throw new InvalidSignatureError3({
119890
+ throw new InvalidSignatureError({
119773
119891
  reason: "Handshake signer is not the grant builder",
119774
119892
  expected: grant.granteeId,
119775
119893
  actual: input.builderAddress
@@ -119988,14 +120106,14 @@ function getErrorDetails(err2) {
119988
120106
  return void 0;
119989
120107
  }
119990
120108
  function mapSdkAuthError(err2) {
119991
- if (err2 instanceof MissingAuthError) {
119992
- return new MissingAuthError2(getErrorDetails(err2));
120109
+ if (err2 instanceof MissingAuthError2) {
120110
+ return new MissingAuthError(getErrorDetails(err2));
119993
120111
  }
119994
- if (err2 instanceof InvalidSignatureError2) {
119995
- return new InvalidSignatureError3(getErrorDetails(err2));
120112
+ if (err2 instanceof InvalidSignatureError3) {
120113
+ return new InvalidSignatureError(getErrorDetails(err2));
119996
120114
  }
119997
- if (err2 instanceof ExpiredTokenError) {
119998
- return new ExpiredTokenError2(getErrorDetails(err2));
120115
+ if (err2 instanceof ExpiredTokenError2) {
120116
+ return new ExpiredTokenError(getErrorDetails(err2));
119999
120117
  }
120000
120118
  return null;
120001
120119
  }
@@ -120539,6 +120657,7 @@ function normalizeState(state) {
120539
120657
  schemaId: entry.schemaId ?? null
120540
120658
  })),
120541
120659
  envelopes: state.envelopes,
120660
+ readyBlockManifests: state.readyBlockManifests ?? [],
120542
120661
  blockManifests: state.blockManifests ?? [],
120543
120662
  blockPayloads: state.blockPayloads ?? [],
120544
120663
  ...state.pendingLedgerDeletes?.length ? { pendingLedgerDeletes: state.pendingLedgerDeletes } : {}
@@ -120788,6 +120907,10 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
120788
120907
  envelope
120789
120908
  ]));
120790
120909
  const fallbackBlockManifests = new Map((state.blockManifests ?? []).map(({ path, manifest }) => [path, manifest]));
120910
+ const readyBlockManifests = /* @__PURE__ */ new Set([
120911
+ ...state.readyBlockManifests ?? [],
120912
+ ...fallbackBlockManifests.keys()
120913
+ ]);
120791
120914
  const fallbackBlockPayloads = new Map((state.blockPayloads ?? []).map(({ path, block }) => [path, block]));
120792
120915
  const ledgerAux = (scope) => `first-seen:${scope}`;
120793
120916
  const firstSeenLedgers = /* @__PURE__ */ new Map();
@@ -120803,6 +120926,7 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
120803
120926
  async function persist() {
120804
120927
  const snapshot = {
120805
120928
  ...state,
120929
+ readyBlockManifests: Array.from(readyBlockManifests),
120806
120930
  envelopes: fileStore.kind === "indexeddb" ? Array.from(fallbackEnvelopes.values()) : [],
120807
120931
  blockManifests: Array.from(fallbackBlockManifests.entries()).map(([path, manifest]) => ({ path, manifest })),
120808
120932
  blockPayloads: Array.from(fallbackBlockPayloads.entries()).map(([path, block]) => ({ path, block })),
@@ -120965,7 +121089,7 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
120965
121089
  return await fileStore.readBlockManifest?.(manifestPath) ?? (fileStore === fallbackStore ? null : await fallbackStore.readBlockManifest?.(manifestPath)) ?? null;
120966
121090
  },
120967
121091
  async hasScopeBlocks(scope, collectedAt) {
120968
- return Boolean(await storagePort.readBlockManifest?.(scope, collectedAt));
121092
+ return readyBlockManifests.has(blockManifestPath(scope, collectedAt));
120969
121093
  },
120970
121094
  async canReadScopeBlocks(scope, collectedAt) {
120971
121095
  if (await storagePort.hasScopeBlocks?.(scope, collectedAt)) {
@@ -120979,6 +121103,8 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
120979
121103
  return Boolean(envelope);
120980
121104
  },
120981
121105
  async writeBlockManifest(scope, collectedAt, manifest, blocks) {
121106
+ readyBlockManifests.delete(blockManifestPath(scope, collectedAt));
121107
+ await persist();
120982
121108
  const writeTree = async (store) => {
120983
121109
  if (!store.writeBlockManifest || !store.writeBlockPayload) {
120984
121110
  throw new Error("Block sidecar storage is not available");
@@ -121009,6 +121135,7 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
121009
121135
  if (wrotePrimary && fileStore.kind !== "indexeddb") {
121010
121136
  await fallbackStore.deleteBlockTree?.(blockTreePath(scope, collectedAt));
121011
121137
  }
121138
+ readyBlockManifests.add(blockManifestPath(scope, collectedAt));
121012
121139
  await persist();
121013
121140
  },
121014
121141
  async insertEntry(entry) {
@@ -121106,6 +121233,10 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
121106
121233
  deleteScope(scope) {
121107
121234
  return withScopeLock(scope, async () => {
121108
121235
  await dropLedger(scope);
121236
+ for (const entry of entriesForScope(scope)) {
121237
+ readyBlockManifests.delete(blockManifestPath(scope, entry.collectedAt));
121238
+ }
121239
+ await persist();
121109
121240
  let deleted = 0;
121110
121241
  const deletedPaths = [];
121111
121242
  const deletedBlockTrees = [];
@@ -121177,6 +121308,8 @@ async function createPersistentPsLiteStorage(adapter, persistence = createIndexe
121177
121308
  }
121178
121309
  async function removeEntryLocked(entry) {
121179
121310
  const blobPath = envelopePath(entry.scope, entry.collectedAt);
121311
+ readyBlockManifests.delete(blockManifestPath(entry.scope, entry.collectedAt));
121312
+ await persist();
121180
121313
  await Promise.all([
121181
121314
  fileStore.deleteEnvelope(blobPath),
121182
121315
  fallbackStore.deleteEnvelope(blobPath),
@@ -124268,7 +124401,15 @@ function createMcpDataReadClient(options) {
124268
124401
  fileId: selectedEntry.fileId ?? void 0,
124269
124402
  metadataOnly: true
124270
124403
  });
124271
- const manifest = await storage.readBlockManifest(scope, selectedEntry.collectedAt);
124404
+ let manifest;
124405
+ try {
124406
+ manifest = await storage.readBlockManifest(scope, selectedEntry.collectedAt);
124407
+ } catch (err2) {
124408
+ if (err2 instanceof ProtocolError) {
124409
+ throw new McpDataReadError(err2.code, err2.toJSON());
124410
+ }
124411
+ throw err2;
124412
+ }
124272
124413
  await writeReadAccessLog(request2, { scope, grantId, authResult });
124273
124414
  if (manifest && !isOwnerView(authResult)) {
124274
124415
  return {
@@ -138692,22 +138833,22 @@ function parseBearerToken(request2) {
138692
138833
  function assertBearerToken(request2, expectedToken, ownerOnly = false) {
138693
138834
  const token = parseBearerToken(request2);
138694
138835
  if (!token) {
138695
- throw new MissingAuthError2();
138836
+ throw new MissingAuthError();
138696
138837
  }
138697
138838
  if (token !== expectedToken) {
138698
- throw ownerOnly ? new NotOwnerError() : new InvalidSignatureError3();
138839
+ throw ownerOnly ? new NotOwnerError() : new InvalidSignatureError();
138699
138840
  }
138700
138841
  }
138701
138842
  function createMissingAuthAdapter() {
138702
138843
  return {
138703
138844
  async authorizeOwner() {
138704
- throw new MissingAuthError2();
138845
+ throw new MissingAuthError();
138705
138846
  },
138706
138847
  async authorizeBuilderList() {
138707
- throw new MissingAuthError2();
138848
+ throw new MissingAuthError();
138708
138849
  },
138709
138850
  async authorizeBuilderRead() {
138710
- throw new MissingAuthError2();
138851
+ throw new MissingAuthError();
138711
138852
  }
138712
138853
  };
138713
138854
  }
@@ -138878,7 +139019,7 @@ function resolveX402Settings(config2, gateway = config2?.gateway) {
138878
139019
  };
138879
139020
  }
138880
139021
  function warnLegacyProjectionIssue(issue2) {
138881
- console.warn(issue2.kind === "projection_failed" ? "[legacy-projection] projection failed; serving stored body" : "[legacy-projection] projection left rows out", issue2);
139022
+ console.warn(issue2.kind === "projection_failed" ? "[legacy-projection] served read refused" : "[legacy-projection] projection left rows out", issue2);
138882
139023
  }
138883
139024
  function createPsLiteRuntime(options) {
138884
139025
  let active = options.active ?? false;
@@ -140067,6 +140208,7 @@ function createGatewayDataPointFeed(options) {
140067
140208
  const url2 = `${base}${uri}?includeDeleted=true`;
140068
140209
  const ownerSigner = isSystemScope(input.scope) ? options.ownerRequestSigner : void 0;
140069
140210
  const res = ownerSigner ? await fetchImpl(url2, {
140211
+ ...input.signal ? { signal: input.signal } : {},
140070
140212
  headers: {
140071
140213
  Authorization: await ownerSigner.signRequest({
140072
140214
  aud: new URL(base).origin,
@@ -140074,7 +140216,7 @@ function createGatewayDataPointFeed(options) {
140074
140216
  uri
140075
140217
  })
140076
140218
  }
140077
- }) : await fetchImpl(url2);
140219
+ }) : input.signal ? await fetchImpl(url2, { signal: input.signal }) : await fetchImpl(url2);
140078
140220
  if (res.status === 404)
140079
140221
  return null;
140080
140222
  if (res.status === 410) {