@antseed/node 0.2.128 → 0.2.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/billing/index.d.ts +1 -1
  2. package/dist/billing/index.d.ts.map +1 -1
  3. package/dist/billing/index.js +1 -1
  4. package/dist/billing/index.js.map +1 -1
  5. package/dist/buyer-identity-context.d.ts +87 -0
  6. package/dist/buyer-identity-context.d.ts.map +1 -0
  7. package/dist/buyer-identity-context.js +226 -0
  8. package/dist/buyer-identity-context.js.map +1 -0
  9. package/dist/discovery/metadata-codec.d.ts.map +1 -1
  10. package/dist/discovery/metadata-codec.js +95 -4
  11. package/dist/discovery/metadata-codec.js.map +1 -1
  12. package/dist/discovery/metadata-validator.d.ts.map +1 -1
  13. package/dist/discovery/metadata-validator.js +6 -4
  14. package/dist/discovery/metadata-validator.js.map +1 -1
  15. package/dist/discovery/peer-metadata.d.ts +1 -1
  16. package/dist/discovery/peer-metadata.d.ts.map +1 -1
  17. package/dist/discovery/peer-metadata.js +1 -1
  18. package/dist/discovery/peer-metadata.js.map +1 -1
  19. package/dist/discovery/service-catalog.d.ts +6 -2
  20. package/dist/discovery/service-catalog.d.ts.map +1 -1
  21. package/dist/discovery/service-catalog.js +13 -8
  22. package/dist/discovery/service-catalog.js.map +1 -1
  23. package/dist/health/model-health-checker.d.ts +1 -1
  24. package/dist/health/model-health-checker.d.ts.map +1 -1
  25. package/dist/health/model-health-checker.js +4 -3
  26. package/dist/health/model-health-checker.js.map +1 -1
  27. package/dist/index.d.ts +5 -2
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +4 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/interfaces/seller-provider.d.ts +4 -2
  32. package/dist/interfaces/seller-provider.d.ts.map +1 -1
  33. package/dist/node.d.ts +45 -11
  34. package/dist/node.d.ts.map +1 -1
  35. package/dist/node.js +221 -132
  36. package/dist/node.js.map +1 -1
  37. package/dist/p2p/connection-manager.d.ts.map +1 -1
  38. package/dist/p2p/connection-manager.js +7 -1
  39. package/dist/p2p/connection-manager.js.map +1 -1
  40. package/dist/p2p/outbound-connection.d.ts +14 -0
  41. package/dist/p2p/outbound-connection.d.ts.map +1 -0
  42. package/dist/p2p/outbound-connection.js +88 -0
  43. package/dist/p2p/outbound-connection.js.map +1 -0
  44. package/dist/payments/channel-store.d.ts +4 -0
  45. package/dist/payments/channel-store.d.ts.map +1 -1
  46. package/dist/payments/channel-store.js +53 -6
  47. package/dist/payments/channel-store.js.map +1 -1
  48. package/dist/payments/seller-payment-manager.d.ts +60 -1
  49. package/dist/payments/seller-payment-manager.d.ts.map +1 -1
  50. package/dist/payments/seller-payment-manager.js +399 -10
  51. package/dist/payments/seller-payment-manager.js.map +1 -1
  52. package/dist/resources/resource-ownership-store.d.ts +30 -0
  53. package/dist/resources/resource-ownership-store.d.ts.map +1 -0
  54. package/dist/resources/resource-ownership-store.js +72 -0
  55. package/dist/resources/resource-ownership-store.js.map +1 -0
  56. package/dist/seller-request-handler.d.ts +34 -0
  57. package/dist/seller-request-handler.d.ts.map +1 -1
  58. package/dist/seller-request-handler.js +322 -56
  59. package/dist/seller-request-handler.js.map +1 -1
  60. package/dist/storage/migrations/channels/006_add_video_payments.d.ts +3 -0
  61. package/dist/storage/migrations/channels/006_add_video_payments.d.ts.map +1 -0
  62. package/dist/storage/migrations/channels/006_add_video_payments.js +24 -0
  63. package/dist/storage/migrations/channels/006_add_video_payments.js.map +1 -0
  64. package/dist/storage/migrations/channels/index.d.ts.map +1 -1
  65. package/dist/storage/migrations/channels/index.js +2 -1
  66. package/dist/storage/migrations/channels/index.js.map +1 -1
  67. package/dist/storage/migrations/metering/003_create_resource_tables.d.ts +3 -0
  68. package/dist/storage/migrations/metering/003_create_resource_tables.d.ts.map +1 -0
  69. package/dist/storage/migrations/metering/003_create_resource_tables.js +34 -0
  70. package/dist/storage/migrations/metering/003_create_resource_tables.js.map +1 -0
  71. package/dist/storage/migrations/metering/index.d.ts.map +1 -1
  72. package/dist/storage/migrations/metering/index.js +2 -1
  73. package/dist/storage/migrations/metering/index.js.map +1 -1
  74. package/dist/verification/samples.d.ts.map +1 -1
  75. package/dist/verification/samples.js +2 -0
  76. package/dist/verification/samples.js.map +1 -1
  77. package/package.json +4 -4
@@ -1,2 +1,2 @@
1
- export { captureUnitBillingContext, computeFinalUnitBilling, evaluateUnitBilling, extractUnitResponseUsage, isFreeUnitBillingModel, usdToMicroUsdc, unitUsageFromReport, validateUnitBillingModelV1, validateUnitBillingUsage, validateUnitBillingUsageReportV1, type CapturedUnitBillingContext, type FinalUnitBillingResult, } from "./unit.js";
1
+ export { captureUnitBillingContext, computeFinalUnitBilling, evaluateUnitBilling, isUnitBilledProtocol, extractUnitResponseUsage, isFreeUnitBillingModel, usdToMicroUsdc, unitUsageFromReport, validateUnitBillingModelForProtocolV1, validateUnitBillingModelV1, validateUnitBillingUsage, validateUnitBillingUsageReportV1, type CapturedUnitBillingContext, type FinalUnitBillingResult, } from "./unit.js";
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,cAAc,EACd,mBAAmB,EACnB,0BAA0B,EAC1B,wBAAwB,EACxB,gCAAgC,EAChC,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,GAC5B,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,cAAc,EACd,mBAAmB,EACnB,qCAAqC,EACrC,0BAA0B,EAC1B,wBAAwB,EACxB,gCAAgC,EAChC,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,GAC5B,MAAM,WAAW,CAAC"}
@@ -1,2 +1,2 @@
1
- export { captureUnitBillingContext, computeFinalUnitBilling, evaluateUnitBilling, extractUnitResponseUsage, isFreeUnitBillingModel, usdToMicroUsdc, unitUsageFromReport, validateUnitBillingModelV1, validateUnitBillingUsage, validateUnitBillingUsageReportV1, } from "./unit.js";
1
+ export { captureUnitBillingContext, computeFinalUnitBilling, evaluateUnitBilling, isUnitBilledProtocol, extractUnitResponseUsage, isFreeUnitBillingModel, usdToMicroUsdc, unitUsageFromReport, validateUnitBillingModelForProtocolV1, validateUnitBillingModelV1, validateUnitBillingUsage, validateUnitBillingUsageReportV1, } from "./unit.js";
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,cAAc,EACd,mBAAmB,EACnB,0BAA0B,EAC1B,wBAAwB,EACxB,gCAAgC,GAGjC,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,cAAc,EACd,mBAAmB,EACnB,qCAAqC,EACrC,0BAA0B,EAC1B,wBAAwB,EACxB,gCAAgC,GAGjC,MAAM,WAAW,CAAC"}
@@ -0,0 +1,87 @@
1
+ import type { Identity } from "./p2p/identity.js";
2
+ import type { PeerId, PeerInfo } from "./types/peer.js";
3
+ import type { SerializedHttpRequest, SerializedHttpResponse } from "./types/http.js";
4
+ import { type PeerConnection } from "./p2p/connection-manager.js";
5
+ import type { VerificationStorage } from "./verification/storage.js";
6
+ import type { VerificationSampler } from "./verification/samples.js";
7
+ import { BuyerFreeUsageManager, ChannelStore, ChannelsClient, DepositsClient } from "./payments/index.js";
8
+ import { BuyerPaymentManager, type BuyerPaymentConfig } from "./payments/buyer-payment-manager.js";
9
+ import { BuyerPaymentNegotiator } from "./payments/buyer-payment-negotiator.js";
10
+ import type { SellerAddressResolver } from "./discovery/seller-address-resolver.js";
11
+ import { type RequestExecutionOptions, type RequestStreamCallbacks } from "./buyer-request-handler.js";
12
+ /** The identity loaded from the node's own data dir. */
13
+ export declare const DEFAULT_BUYER_IDENTITY = "default";
14
+ export declare function isValidBuyerIdentityName(name: string): boolean;
15
+ /** Node-wide services every buyer identity shares. */
16
+ export interface BuyerIdentitySharedServices {
17
+ channelStore: ChannelStore | null;
18
+ depositsClient: DepositsClient | null;
19
+ channelsClient: ChannelsClient | null;
20
+ sellerAddressResolver: SellerAddressResolver | null;
21
+ verificationStorage: VerificationStorage | null;
22
+ verificationSampler: VerificationSampler | null;
23
+ /** Capabilities each seller advertised in discovery; not identity-specific. */
24
+ peerCapabilities: Map<PeerId, Set<string>>;
25
+ isChainReachable: () => boolean;
26
+ onChainReadFailure: () => void;
27
+ }
28
+ export interface BuyerIdentityContextOptions {
29
+ name: string;
30
+ identity: Identity;
31
+ /** Null when payments are disabled; requests then only reach free services. */
32
+ paymentConfig: BuyerPaymentConfig | null;
33
+ freeUsage: {
34
+ chainId: number;
35
+ freeUsageContractAddress: string;
36
+ defaultAuthDurationSecs: number;
37
+ disableMetadataV2Services: boolean;
38
+ } | null;
39
+ requestHandler: {
40
+ requestTimeoutMs?: number;
41
+ maxStreamBufferBytes?: number;
42
+ maxStreamDurationMs?: number;
43
+ };
44
+ maxUploadBodyBytes?: number;
45
+ requireSecureTransport?: boolean;
46
+ shared: BuyerIdentitySharedServices;
47
+ /** Receives payment events, each tagged with this identity's name. */
48
+ emit: (event: string, payload: Record<string, unknown>) => void;
49
+ }
50
+ /**
51
+ * Buyer state that belongs to one wallet: its authenticated connections to
52
+ * sellers, payment channels and free-usage sessions. Discovery, routing and
53
+ * chain clients live on the node and are shared by every identity, so an
54
+ * extra identity costs connections and channel state, not another node.
55
+ *
56
+ * Sellers see each identity as a separate buyer, exactly as if it ran in its
57
+ * own process: connections are authenticated with the identity's key and
58
+ * channels are funded from its own deposits.
59
+ */
60
+ export declare class BuyerIdentityContext {
61
+ private readonly _options;
62
+ private readonly _connectionManager;
63
+ readonly name: string;
64
+ readonly identity: Identity;
65
+ readonly paymentManager: BuyerPaymentManager | null;
66
+ readonly negotiator: BuyerPaymentNegotiator | null;
67
+ readonly freeUsageManager: BuyerFreeUsageManager | null;
68
+ private readonly _handler;
69
+ private readonly _muxes;
70
+ private readonly _paymentMuxes;
71
+ private readonly _verificationMuxes;
72
+ private readonly _decoders;
73
+ private readonly _keepalives;
74
+ private constructor();
75
+ static create(options: BuyerIdentityContextOptions): Promise<BuyerIdentityContext>;
76
+ get address(): string;
77
+ sendRequest(peer: PeerInfo, req: SerializedHttpRequest, callbacks: RequestStreamCallbacks | undefined, options?: RequestExecutionOptions): Promise<SerializedHttpResponse>;
78
+ connect(peer: PeerInfo): Promise<PeerConnection>;
79
+ /** The live connection to a seller, if this identity has one. */
80
+ liveConnection(peerId: PeerId): PeerConnection | null;
81
+ stop(): Promise<void>;
82
+ private _getOrCreateMux;
83
+ private _getOrCreateVerificationMux;
84
+ /** Frame dispatch and keepalive for an outbound connection to a seller. */
85
+ private _wireConnection;
86
+ }
87
+ //# sourceMappingURL=buyer-identity-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buyer-identity-context.d.ts","sourceRoot":"","sources":["../src/buyer-identity-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAErF,OA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AO,CAAC,QAAQ,CAAC,WAAW,CAAuC;IAEnE,OAAO;WA6DM,MAAM,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAWxF,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,WAAW,CACT,IAAI,EAAE,QAAQ,EACd,GAAG,EAAE,qBAAqB,EAC1B,SAAS,EAAE,sBAAsB,GAAG,SAAS,EAC7C,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,CAAC,sBAAsB,CAAC;IAI5B,OAAO,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,cAAc,CAAC;IActD,iEAAiE;IACjE,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI;IAM/C,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAiB3B,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,2BAA2B;IASnC,2EAA2E;IAC3E,OAAO,CAAC,eAAe;CAuExB"}
@@ -0,0 +1,226 @@
1
+ import { ConnectionState } from "./types/connection.js";
2
+ import { ConnectionManager } from "./p2p/connection-manager.js";
3
+ import { getOrOpenOutboundConnection } from "./p2p/outbound-connection.js";
4
+ import { FrameDecoder, encodeFrame } from "./p2p/message-protocol.js";
5
+ import { KeepaliveManager, buildPongPayload } from "./p2p/keepalive.js";
6
+ import { MessageType } from "./types/protocol.js";
7
+ import { ProxyMux } from "./proxy/proxy-mux.js";
8
+ import { PaymentMux } from "./p2p/payment-mux.js";
9
+ import { VerificationMux } from "./verification/verification-mux.js";
10
+ import { BuyerFreeUsageManager, } from "./payments/index.js";
11
+ import { BuyerPaymentManager } from "./payments/buyer-payment-manager.js";
12
+ import { BuyerPaymentNegotiator } from "./payments/buyer-payment-negotiator.js";
13
+ import { BuyerRequestHandler, } from "./buyer-request-handler.js";
14
+ import { debugWarn } from "./utils/debug.js";
15
+ /** The identity loaded from the node's own data dir. */
16
+ export const DEFAULT_BUYER_IDENTITY = "default";
17
+ const BUYER_IDENTITY_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
18
+ export function isValidBuyerIdentityName(name) {
19
+ return BUYER_IDENTITY_NAME_PATTERN.test(name);
20
+ }
21
+ /**
22
+ * Buyer state that belongs to one wallet: its authenticated connections to
23
+ * sellers, payment channels and free-usage sessions. Discovery, routing and
24
+ * chain clients live on the node and are shared by every identity, so an
25
+ * extra identity costs connections and channel state, not another node.
26
+ *
27
+ * Sellers see each identity as a separate buyer, exactly as if it ran in its
28
+ * own process: connections are authenticated with the identity's key and
29
+ * channels are funded from its own deposits.
30
+ */
31
+ export class BuyerIdentityContext {
32
+ _options;
33
+ _connectionManager;
34
+ name;
35
+ identity;
36
+ paymentManager;
37
+ negotiator;
38
+ freeUsageManager;
39
+ _handler;
40
+ _muxes = new Map();
41
+ _paymentMuxes = new Map();
42
+ _verificationMuxes = new Map();
43
+ _decoders = new Map();
44
+ _keepalives = new Map();
45
+ constructor(_options, _connectionManager) {
46
+ this._options = _options;
47
+ this._connectionManager = _connectionManager;
48
+ this.name = _options.name;
49
+ this.identity = _options.identity;
50
+ const { shared } = _options;
51
+ const emitter = {
52
+ emit: (event, ...args) => {
53
+ const payload = args[0];
54
+ _options.emit(event, { ...(payload && typeof payload === "object" ? payload : {}), buyerIdentity: this.name });
55
+ return true;
56
+ },
57
+ };
58
+ this.freeUsageManager = _options.freeUsage
59
+ ? new BuyerFreeUsageManager(this.identity, _options.freeUsage, shared.sellerAddressResolver ?? undefined, shared.channelStore ?? undefined)
60
+ : null;
61
+ if (_options.paymentConfig && shared.channelStore) {
62
+ this.paymentManager = new BuyerPaymentManager(this.identity, _options.paymentConfig, shared.channelStore, shared.sellerAddressResolver ?? undefined);
63
+ this.paymentManager.setSpendListener((event) => emitter.emit("payment:spend", event));
64
+ this.negotiator = new BuyerPaymentNegotiator(this.identity, this.paymentManager, shared.depositsClient, shared.channelsClient, shared.channelStore, { isChainReachable: shared.isChainReachable, onChainReadFailure: shared.onChainReadFailure }, emitter, shared.sellerAddressResolver ?? undefined, this.freeUsageManager);
65
+ }
66
+ else {
67
+ this.paymentManager = null;
68
+ this.negotiator = null;
69
+ }
70
+ this._handler = new BuyerRequestHandler(_options.requestHandler, {
71
+ localPeerId: this.identity.peerId,
72
+ negotiator: this.negotiator,
73
+ freeUsageManager: this.freeUsageManager,
74
+ verificationStorage: shared.verificationStorage,
75
+ verificationSampler: shared.verificationSampler,
76
+ getConnection: (peer) => this.connect(peer),
77
+ getMux: (peerId, conn) => this._getOrCreateMux(peerId, conn),
78
+ getVerificationMux: (peerId, conn) => this._getOrCreateVerificationMux(peerId, conn),
79
+ registerPaymentMux: (peerId, mux) => this._paymentMuxes.set(peerId, mux),
80
+ });
81
+ }
82
+ static async create(options) {
83
+ const connectionManager = await ConnectionManager.init(undefined, {
84
+ requireSecureTransport: options.requireSecureTransport,
85
+ });
86
+ connectionManager.setLocalIdentity(options.identity);
87
+ connectionManager.on("error", (err) => {
88
+ debugWarn(`[ConnectionManager:${options.name}] ${err.message}`);
89
+ });
90
+ return new BuyerIdentityContext(options, connectionManager);
91
+ }
92
+ get address() {
93
+ return this.identity.wallet.address;
94
+ }
95
+ sendRequest(peer, req, callbacks, options) {
96
+ return this._handler.sendRequest(peer, req, callbacks, options);
97
+ }
98
+ async connect(peer) {
99
+ const conn = await getOrOpenOutboundConnection(this._connectionManager, peer, this._options.shared.peerCapabilities, (opened) => this._wireConnection(opened, peer.peerId));
100
+ this._getOrCreateMux(peer.peerId, conn);
101
+ if (this.negotiator) {
102
+ this._paymentMuxes.set(peer.peerId, this.negotiator.getOrCreatePaymentMux(peer.peerId, conn));
103
+ }
104
+ return conn;
105
+ }
106
+ /** The live connection to a seller, if this identity has one. */
107
+ liveConnection(peerId) {
108
+ const conn = this._connectionManager.getConnection(peerId);
109
+ if (!conn)
110
+ return null;
111
+ return conn.state === ConnectionState.Open || conn.state === ConnectionState.Authenticated ? conn : null;
112
+ }
113
+ async stop() {
114
+ if (this.negotiator) {
115
+ // Let in-transit NeedAuth messages land so sellers can settle what they served.
116
+ await new Promise((resolve) => setTimeout(resolve, 500));
117
+ await this.negotiator.drainPendingNeedAuth();
118
+ this.negotiator.cleanup();
119
+ }
120
+ for (const keepalive of this._keepalives.values())
121
+ keepalive.stop();
122
+ this._keepalives.clear();
123
+ for (const mux of this._verificationMuxes.values())
124
+ mux.close();
125
+ this._verificationMuxes.clear();
126
+ this._muxes.clear();
127
+ this._paymentMuxes.clear();
128
+ this._decoders.clear();
129
+ this._connectionManager.closeAll();
130
+ }
131
+ _getOrCreateMux(peerId, conn) {
132
+ let mux = this._muxes.get(peerId);
133
+ if (!mux) {
134
+ mux = new ProxyMux(conn, { maxUploadBodyBytes: this._options.maxUploadBodyBytes });
135
+ this._muxes.set(peerId, mux);
136
+ }
137
+ return mux;
138
+ }
139
+ _getOrCreateVerificationMux(peerId, conn) {
140
+ let mux = this._verificationMuxes.get(peerId);
141
+ if (!mux) {
142
+ mux = new VerificationMux(conn);
143
+ this._verificationMuxes.set(peerId, mux);
144
+ }
145
+ return mux;
146
+ }
147
+ /** Frame dispatch and keepalive for an outbound connection to a seller. */
148
+ _wireConnection(conn, peerId) {
149
+ const decoder = new FrameDecoder();
150
+ const isOpen = () => conn.state === ConnectionState.Open || conn.state === ConnectionState.Authenticated;
151
+ const logFailure = (kind) => (err) => {
152
+ debugWarn(`[Node:${this.name}] Failed to handle ${kind} frame from ${peerId.slice(0, 12)}...: ${err instanceof Error ? err.message : String(err)}`);
153
+ };
154
+ conn.on("message", (data) => {
155
+ let frames;
156
+ try {
157
+ frames = decoder.feed(data);
158
+ }
159
+ catch (err) {
160
+ const message = err instanceof Error ? err.message : String(err);
161
+ debugWarn(`[Node:${this.name}] Failed to decode frame from ${peerId.slice(0, 12)}...: ${message}`);
162
+ conn.fail(err instanceof Error ? err : new Error(message));
163
+ return;
164
+ }
165
+ const proxyMux = this._muxes.get(peerId);
166
+ const paymentMux = this._paymentMuxes.get(peerId);
167
+ const verificationMux = this._verificationMuxes.get(peerId);
168
+ for (const frame of frames) {
169
+ if (frame.type === MessageType.Ping) {
170
+ if (isOpen()) {
171
+ conn.send(encodeFrame({ type: MessageType.Pong, messageId: frame.messageId, payload: buildPongPayload(frame.payload) }));
172
+ }
173
+ }
174
+ else if (frame.type === MessageType.Pong) {
175
+ this._keepalives.get(peerId)?.handlePong(frame.payload);
176
+ }
177
+ else if (paymentMux && PaymentMux.isPaymentMessage(frame.type)) {
178
+ paymentMux.handleFrame(frame).catch(logFailure("payment"));
179
+ }
180
+ else if (verificationMux && VerificationMux.isVerificationMessage(frame.type)) {
181
+ verificationMux.handleFrame(frame).catch(logFailure("verification"));
182
+ }
183
+ else if (proxyMux) {
184
+ proxyMux.handleFrame(frame).catch((err) => {
185
+ logFailure("proxy")(err);
186
+ conn.fail(err instanceof Error ? err : new Error(String(err)));
187
+ });
188
+ }
189
+ }
190
+ });
191
+ this._decoders.set(peerId, decoder);
192
+ conn.on("stateChange", (state) => {
193
+ if (state !== ConnectionState.Closed && state !== ConnectionState.Failed)
194
+ return;
195
+ // A reconnect may already have replaced this connection's session.
196
+ if (this._decoders.get(peerId) !== decoder)
197
+ return;
198
+ this._keepalives.get(peerId)?.stop();
199
+ this._keepalives.delete(peerId);
200
+ this._muxes.get(peerId)?.abortPendingUploads();
201
+ this._muxes.delete(peerId);
202
+ this._paymentMuxes.delete(peerId);
203
+ this._verificationMuxes.get(peerId)?.close();
204
+ this._verificationMuxes.delete(peerId);
205
+ this._decoders.delete(peerId);
206
+ this.negotiator?.onPeerDisconnect(peerId);
207
+ this.freeUsageManager?.onPeerDisconnect(peerId);
208
+ });
209
+ const keepalive = new KeepaliveManager({
210
+ sendPing: (payload) => {
211
+ if (isOpen())
212
+ conn.send(encodeFrame({ type: MessageType.Ping, messageId: 0, payload }));
213
+ },
214
+ onDead: () => {
215
+ if (!isOpen())
216
+ return;
217
+ debugWarn(`[Node:${this.name}] Keepalive timeout for ${peerId.slice(0, 12)}...`);
218
+ conn.fail(new Error("Keepalive timeout"));
219
+ },
220
+ });
221
+ this._keepalives.get(peerId)?.stop();
222
+ this._keepalives.set(peerId, keepalive);
223
+ keepalive.start();
224
+ }
225
+ }
226
+ //# sourceMappingURL=buyer-identity-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buyer-identity-context.js","sourceRoot":"","sources":["../src/buyer-identity-context.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAuB,MAAM,6BAA6B,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAGrE,OAAO,EACL,qBAAqB,GAItB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAA2B,MAAM,qCAAqC,CAAC;AACnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAEhF,OAAO,EACL,mBAAmB,GAGpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,wDAAwD;AACxD,MAAM,CAAC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AAEhD,MAAM,2BAA2B,GAAG,2BAA2B,CAAC;AAEhE,MAAM,UAAU,wBAAwB,CAAC,IAAY;IACnD,OAAO,2BAA2B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC;AAuCD;;;;;;;;;G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cAAc,CAAC,IAAI,EAAE,UAAU,GAAG,YAAY,CA8b7D"}
1
+ {"version":3,"file":"metadata-codec.d.ts","sourceRoot":"","sources":["../../src/discovery/metadata-codec.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA8E,YAAY,EAAgF,MAAM,oBAAoB,CAAC;AAqCjN;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG,UAAU,CAQjE;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,YAAY,GAAG,UAAU,CAE3E;AAiuBD;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,UAAU,GAAG,YAAY,CA8b7D"}
@@ -1,4 +1,4 @@
1
- import { SERVICE_CAPABILITY_MODALITIES } from "./peer-metadata.js";
1
+ import { SERVICE_CAPABILITY_MODALITIES, VIDEO_INPUT_KINDS } from "./peer-metadata.js";
2
2
  import { hexToBytes, bytesToHex } from "../utils/hex.js";
3
3
  import { toPeerId } from "../types/peer.js";
4
4
  import { WELL_KNOWN_SERVICE_API_PROTOCOLS, isKnownServiceApiProtocol } from "../types/service-api.js";
@@ -397,13 +397,22 @@ const CAP_HAS_SUPPORTED_PARAMETERS = 1 << 7;
397
397
  const CAP_PRESENCE_MASK = CAP_HAS_CONTEXT_WINDOW | CAP_HAS_MAX_OUTPUT_TOKENS | CAP_HAS_INPUTS
398
398
  | CAP_HAS_REASONING | CAP_HAS_TOOL_USE | CAP_HAS_STRUCTURED_OUTPUT
399
399
  | CAP_HAS_OUTPUTS | CAP_HAS_SUPPORTED_PARAMETERS;
400
- // Value bits for the boolean-values byte. Deliberately a separate namespace
401
- // from the presence bits: presence says "announced", value says "true".
402
400
  const CAP_VAL_REASONING = 1 << 0;
403
401
  const CAP_VAL_TOOL_USE = 1 << 1;
404
402
  const CAP_VAL_STRUCTURED_OUTPUT = 1 << 2;
405
- const CAP_VALUE_MASK = CAP_VAL_REASONING | CAP_VAL_TOOL_USE | CAP_VAL_STRUCTURED_OUTPUT;
403
+ const CAP_VAL_VIDEO_OPTIONS = 1 << 3;
404
+ const CAP_VALUE_MASK = CAP_VAL_REASONING | CAP_VAL_TOOL_USE | CAP_VAL_STRUCTURED_OUTPUT
405
+ | CAP_VAL_VIDEO_OPTIONS;
406
406
  const CAP_MODALITY_MASK = (1 << SERVICE_CAPABILITY_MODALITIES.length) - 1;
407
+ const VIDEO_HAS_DURATIONS = 1 << 0;
408
+ const VIDEO_HAS_RESOLUTIONS = 1 << 1;
409
+ const VIDEO_HAS_ASPECT_RATIOS = 1 << 2;
410
+ const VIDEO_HAS_INPUTS = 1 << 3;
411
+ const VIDEO_HAS_REQUIRED_INPUTS = 1 << 4;
412
+ const VIDEO_HAS_AUDIO = 1 << 5;
413
+ const VIDEO_AUDIO = 1 << 6;
414
+ const VIDEO_OPTION_MASK = (1 << 7) - 1;
415
+ const VIDEO_INPUT_MASK = (1 << VIDEO_INPUT_KINDS.length) - 1;
407
416
  function encodeModalityBits(modalities) {
408
417
  let bits = 0;
409
418
  for (const modality of modalities) {
@@ -424,6 +433,82 @@ function decodeModalityBits(bits, label) {
424
433
  }
425
434
  return modalities;
426
435
  }
436
+ function encodeVideoInputs(inputs) {
437
+ return inputs.reduce((bits, input) => bits | (1 << VIDEO_INPUT_KINDS.indexOf(input)), 0);
438
+ }
439
+ function decodeVideoInputs(bits) {
440
+ if (bits & ~VIDEO_INPUT_MASK)
441
+ throw new Error(`Unknown video input bits 0x${bits.toString(16)}`);
442
+ return VIDEO_INPUT_KINDS.filter((_, id) => bits & (1 << id));
443
+ }
444
+ function encodeVideoOptions(parts, video) {
445
+ let flags = 0;
446
+ if (video.durationsSeconds)
447
+ flags |= VIDEO_HAS_DURATIONS;
448
+ if (video.resolutions)
449
+ flags |= VIDEO_HAS_RESOLUTIONS;
450
+ if (video.aspectRatios)
451
+ flags |= VIDEO_HAS_ASPECT_RATIOS;
452
+ if (video.inputs)
453
+ flags |= VIDEO_HAS_INPUTS;
454
+ if (video.requiredInputs)
455
+ flags |= VIDEO_HAS_REQUIRED_INPUTS;
456
+ if (video.audio !== undefined)
457
+ flags |= VIDEO_HAS_AUDIO | (video.audio ? VIDEO_AUDIO : 0);
458
+ parts.push(new Uint8Array([flags]));
459
+ if (video.durationsSeconds) {
460
+ parts.push(new Uint8Array([video.durationsSeconds.length]));
461
+ for (const duration of video.durationsSeconds)
462
+ parts.push(new Uint8Array([duration >> 8, duration & 0xff]));
463
+ }
464
+ for (const values of [video.resolutions, video.aspectRatios]) {
465
+ if (!values)
466
+ continue;
467
+ parts.push(new Uint8Array([values.length]));
468
+ for (const value of values)
469
+ pushUtf8(parts, value);
470
+ }
471
+ if (video.inputs)
472
+ parts.push(new Uint8Array([encodeVideoInputs(video.inputs)]));
473
+ if (video.requiredInputs)
474
+ parts.push(new Uint8Array([encodeVideoInputs(video.requiredInputs)]));
475
+ }
476
+ function decodeVideoOptions(data, offset, checkBounds) {
477
+ checkBounds(offset, 1, data.length);
478
+ const flags = data[offset++];
479
+ if (flags & ~VIDEO_OPTION_MASK || (flags & VIDEO_AUDIO && !(flags & VIDEO_HAS_AUDIO)))
480
+ throw new Error(`Unknown video option bits 0x${flags.toString(16)}`);
481
+ const video = {};
482
+ if (flags & VIDEO_HAS_DURATIONS) {
483
+ checkBounds(offset, 1, data.length);
484
+ const count = data[offset++];
485
+ checkBounds(offset, count * 2, data.length);
486
+ video.durationsSeconds = Array.from({ length: count }, (_, index) => (data[offset + index * 2] << 8) | data[offset + index * 2 + 1]);
487
+ offset += count * 2;
488
+ }
489
+ for (const [flag, field] of [[VIDEO_HAS_RESOLUTIONS, "resolutions"], [VIDEO_HAS_ASPECT_RATIOS, "aspectRatios"]]) {
490
+ if (!(flags & flag))
491
+ continue;
492
+ checkBounds(offset, 1, data.length);
493
+ const count = data[offset++];
494
+ const values = [];
495
+ for (let index = 0; index < count; index += 1) {
496
+ const [value, nextOffset] = readUtf8(data, offset, checkBounds);
497
+ values.push(value);
498
+ offset = nextOffset;
499
+ }
500
+ video[field] = values;
501
+ }
502
+ for (const [flag, field] of [[VIDEO_HAS_INPUTS, "inputs"], [VIDEO_HAS_REQUIRED_INPUTS, "requiredInputs"]]) {
503
+ if (!(flags & flag))
504
+ continue;
505
+ checkBounds(offset, 1, data.length);
506
+ video[field] = decodeVideoInputs(data[offset++]);
507
+ }
508
+ if (flags & VIDEO_HAS_AUDIO)
509
+ video.audio = (flags & VIDEO_AUDIO) !== 0;
510
+ return [video, offset];
511
+ }
427
512
  function encodeServiceCapabilities(parts, serviceCapabilities, hasWideServiceCounts) {
428
513
  // Code-unit sort, not localeCompare: buyers verify signatures by re-encoding
429
514
  // decoded metadata, so entry order must not depend on the verifier's locale.
@@ -473,6 +558,8 @@ function encodeServiceCapabilities(parts, serviceCapabilities, hasWideServiceCou
473
558
  boolBits |= CAP_VAL_TOOL_USE;
474
559
  if (caps.structuredOutput === true)
475
560
  boolBits |= CAP_VAL_STRUCTURED_OUTPUT;
561
+ if (caps.video !== undefined)
562
+ boolBits |= CAP_VAL_VIDEO_OPTIONS;
476
563
  parts.push(new Uint8Array([boolBits]));
477
564
  if (caps.supportedParameters !== undefined) {
478
565
  // Code-unit sort for the same reason as the entry sort above: buyers
@@ -486,6 +573,8 @@ function encodeServiceCapabilities(parts, serviceCapabilities, hasWideServiceCou
486
573
  pushUtf8(parts, parameter);
487
574
  }
488
575
  }
576
+ if (caps.video !== undefined)
577
+ encodeVideoOptions(parts, caps.video);
489
578
  }
490
579
  }
491
580
  function decodeServiceCapabilities(data, getOffset, setOffset, checkBounds, hasWideServiceCounts) {
@@ -550,6 +639,8 @@ function decodeServiceCapabilities(data, getOffset, setOffset, checkBounds, hasW
550
639
  }
551
640
  caps.supportedParameters = parameters;
552
641
  }
642
+ if (boolBits & CAP_VAL_VIDEO_OPTIONS)
643
+ [caps.video, offset] = decodeVideoOptions(data, offset, checkBounds);
553
644
  serviceCapabilities[serviceName] = caps;
554
645
  }
555
646
  setOffset(offset);