@bind-protocol/sdk 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,317 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ // src/core/errors.ts
6
+ var BindError = class extends Error {
7
+ constructor(message, code, details) {
8
+ super(message);
9
+ this.code = code;
10
+ this.details = details;
11
+ this.name = "BindError";
12
+ }
13
+ };
14
+ var ApiError = class extends BindError {
15
+ constructor(message, status, response) {
16
+ super(message, "API_ERROR", { status, response });
17
+ this.status = status;
18
+ this.response = response;
19
+ this.name = "ApiError";
20
+ }
21
+ };
22
+ var AuthenticationError = class extends BindError {
23
+ constructor(message = "Authentication failed") {
24
+ super(message, "AUTH_ERROR");
25
+ this.name = "AuthenticationError";
26
+ }
27
+ };
28
+ var TimeoutError = class extends BindError {
29
+ constructor(message, timeoutMs) {
30
+ super(message, "TIMEOUT_ERROR", { timeoutMs });
31
+ this.timeoutMs = timeoutMs;
32
+ this.name = "TimeoutError";
33
+ }
34
+ };
35
+ var InsufficientCreditsError = class extends BindError {
36
+ constructor(required, available) {
37
+ super(
38
+ `Insufficient credits: need ${required}, have ${available}`,
39
+ "INSUFFICIENT_CREDITS",
40
+ { required, available }
41
+ );
42
+ this.required = required;
43
+ this.available = available;
44
+ this.name = "InsufficientCreditsError";
45
+ }
46
+ };
47
+
48
+ // src/core/client.ts
49
+ var DEFAULT_BASE_URL = "https://api.bindprotocol.com";
50
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
51
+ var DEFAULT_TIMEOUT_MS = 3e5;
52
+ var BindClient = class {
53
+ apiKey;
54
+ baseUrl;
55
+ headers;
56
+ constructor(options) {
57
+ this.apiKey = options.apiKey;
58
+ this.baseUrl = options.baseUrl || process.env.BIND_API_URL || DEFAULT_BASE_URL;
59
+ this.headers = {
60
+ "X-API-Key": this.apiKey,
61
+ "Content-Type": "application/json"
62
+ };
63
+ }
64
+ // ==========================================================================
65
+ // Prove Job Methods
66
+ // ==========================================================================
67
+ /**
68
+ * Submit a prove job for async processing
69
+ * @param circuitId - The circuit identifier (e.g., "bind.mobility.riskband.v1")
70
+ * @param inputs - Circuit inputs as key-value pairs (all values must be strings)
71
+ * @returns The submitted job details
72
+ * @throws {ApiError} If the API request fails
73
+ * @throws {InsufficientCreditsError} If there aren't enough credits
74
+ */
75
+ async submitProveJob(circuitId, inputs) {
76
+ const response = await this.fetch("/api/prove", {
77
+ method: "POST",
78
+ body: JSON.stringify({ circuitId, inputs })
79
+ });
80
+ const result = await response.json();
81
+ if (!result.success && result.requiredCredits !== void 0 && result.availableCredits !== void 0) {
82
+ throw new InsufficientCreditsError(result.requiredCredits, result.availableCredits);
83
+ }
84
+ return result;
85
+ }
86
+ /**
87
+ * Get the status and results of a prove job
88
+ * @param jobId - The unique job identifier
89
+ * @returns The job details including status and outputs
90
+ */
91
+ async getProveJob(jobId) {
92
+ const response = await this.fetch(`/api/prove/${encodeURIComponent(jobId)}`);
93
+ return response.json();
94
+ }
95
+ /**
96
+ * List prove jobs for the authenticated organization
97
+ * @param options - Optional filters for status, limit, and offset
98
+ * @returns Paginated list of prove jobs
99
+ */
100
+ async listProveJobs(options = {}) {
101
+ const params = new URLSearchParams();
102
+ if (options.status) params.set("status", options.status);
103
+ if (options.limit !== void 0) params.set("limit", options.limit.toString());
104
+ if (options.offset !== void 0) params.set("offset", options.offset.toString());
105
+ const queryString = params.toString();
106
+ const path = queryString ? `/api/prove?${queryString}` : "/api/prove";
107
+ const response = await this.fetch(path);
108
+ return response.json();
109
+ }
110
+ /**
111
+ * Poll for prove job completion
112
+ * @param jobId - The unique job identifier
113
+ * @param options - Polling options
114
+ * @returns The completed or failed job
115
+ * @throws {TimeoutError} If the job doesn't complete within the timeout
116
+ */
117
+ async waitForProveJob(jobId, options = {}) {
118
+ const intervalMs = options.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
119
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
120
+ const startTime = Date.now();
121
+ while (Date.now() - startTime < timeoutMs) {
122
+ const result = await this.getProveJob(jobId);
123
+ if (!result.success || !result.data) {
124
+ throw new ApiError(
125
+ result.error || "Failed to get prove job",
126
+ 500,
127
+ result
128
+ );
129
+ }
130
+ const job = result.data;
131
+ if (options.onProgress) {
132
+ options.onProgress(job);
133
+ }
134
+ if (job.status === "completed" || job.status === "failed") {
135
+ return job;
136
+ }
137
+ await this.sleep(intervalMs);
138
+ }
139
+ throw new TimeoutError(
140
+ `Timeout waiting for prove job ${jobId} after ${timeoutMs}ms`,
141
+ timeoutMs
142
+ );
143
+ }
144
+ // ==========================================================================
145
+ // Policy Methods (Public, no authentication required)
146
+ // ==========================================================================
147
+ /**
148
+ * List all available public policies
149
+ * @returns Array of public policy specifications
150
+ */
151
+ async listPolicies() {
152
+ const response = await fetch(`${this.baseUrl}/api/policies`, {
153
+ method: "GET"
154
+ });
155
+ if (!response.ok) {
156
+ throw new ApiError(
157
+ `Failed to fetch policies: ${response.statusText}`,
158
+ response.status
159
+ );
160
+ }
161
+ return response.json();
162
+ }
163
+ /**
164
+ * Get a specific policy by ID
165
+ * @param policyId - The unique policy identifier
166
+ * @returns The public policy specification, or null if not found
167
+ */
168
+ async getPolicy(policyId) {
169
+ const response = await fetch(
170
+ `${this.baseUrl}/api/policies/${encodeURIComponent(policyId)}`,
171
+ { method: "GET" }
172
+ );
173
+ if (response.status === 404) {
174
+ return null;
175
+ }
176
+ if (!response.ok) {
177
+ throw new ApiError(
178
+ `Failed to fetch policy: ${response.statusText}`,
179
+ response.status
180
+ );
181
+ }
182
+ return response.json();
183
+ }
184
+ // ==========================================================================
185
+ // Private Helpers
186
+ // ==========================================================================
187
+ async fetch(path, init) {
188
+ const response = await fetch(`${this.baseUrl}${path}`, {
189
+ ...init,
190
+ headers: {
191
+ ...this.headers,
192
+ ...init?.headers
193
+ }
194
+ });
195
+ if (response.status === 401) {
196
+ throw new AuthenticationError();
197
+ }
198
+ return response;
199
+ }
200
+ sleep(ms) {
201
+ return new Promise((resolve) => setTimeout(resolve, ms));
202
+ }
203
+ };
204
+
205
+ // src/adapters/dimo/queries.ts
206
+ function buildTelemetryQuery(vehicleTokenId, from, to) {
207
+ return `{
208
+ signals(
209
+ tokenId: ${vehicleTokenId},
210
+ interval: "1h",
211
+ from: ${from},
212
+ to: ${to}
213
+ ) {
214
+ powertrainTransmissionTravelledDistance(agg: AVG)
215
+ speed(agg: AVG)
216
+ powertrainCombustionEngineSpeed(agg: AVG)
217
+ obdEngineLoad(agg: AVG)
218
+ obdDTCList(agg: UNIQUE)
219
+ obdRunTime(agg: AVG)
220
+ timestamp
221
+ }
222
+ }`;
223
+ }
224
+ function buildCustomTelemetryQuery(vehicleTokenId, from, to, signals, interval = "1h") {
225
+ const signalLines = signals.map((s) => {
226
+ if (s.aggregation) {
227
+ return ` ${s.name}(agg: ${s.aggregation})`;
228
+ }
229
+ return ` ${s.name}`;
230
+ }).join("\n");
231
+ return `{
232
+ signals(
233
+ tokenId: ${vehicleTokenId},
234
+ interval: "${interval}",
235
+ from: ${from},
236
+ to: ${to}
237
+ ) {
238
+ ${signalLines}
239
+ timestamp
240
+ }
241
+ }`;
242
+ }
243
+
244
+ // src/adapters/dimo/adapter.ts
245
+ var SUPPORTED_CIRCUITS = [
246
+ "bind.mobility.riskband.v1"
247
+ ];
248
+ var DimoAdapter = class {
249
+ id = "dimo";
250
+ name = "DIMO Network";
251
+ description = "Fetches vehicle telemetry data from the DIMO decentralized network";
252
+ dimoClient;
253
+ constructor(config) {
254
+ this.dimoClient = config.dimoClient;
255
+ }
256
+ /**
257
+ * Fetch telemetry data from DIMO for a vehicle
258
+ * @param query - Query parameters including vehicle token ID and date range
259
+ * @returns Raw telemetry data from DIMO
260
+ */
261
+ async fetchData(query) {
262
+ const graphqlQuery = buildTelemetryQuery(query.vehicleTokenId, query.from, query.to);
263
+ const result = await this.dimoClient.telemetry.query(graphqlQuery);
264
+ return result;
265
+ }
266
+ /**
267
+ * Transform DIMO telemetry data into circuit inputs
268
+ * @param data - Raw telemetry data from DIMO
269
+ * @param circuitId - Target circuit ID
270
+ * @returns Inputs ready for prove job submission
271
+ */
272
+ toCircuitInputs(data, circuitId) {
273
+ if (!SUPPORTED_CIRCUITS.includes(circuitId)) {
274
+ throw new Error(
275
+ `Circuit "${circuitId}" is not supported by the DIMO adapter. Supported circuits: ${SUPPORTED_CIRCUITS.join(", ")}`
276
+ );
277
+ }
278
+ switch (circuitId) {
279
+ case "bind.mobility.riskband.v1":
280
+ return this.toRiskBandInputs(data);
281
+ default:
282
+ throw new Error(`No input transformer for circuit: ${circuitId}`);
283
+ }
284
+ }
285
+ /**
286
+ * Get the list of circuits this adapter supports
287
+ */
288
+ getSupportedCircuits() {
289
+ return [...SUPPORTED_CIRCUITS];
290
+ }
291
+ // ===========================================================================
292
+ // Private transformers
293
+ // ===========================================================================
294
+ toRiskBandInputs(data) {
295
+ return {
296
+ signals: JSON.stringify(data.signals),
297
+ timestamp: data.timestamp
298
+ };
299
+ }
300
+ };
301
+ function createDimoAdapter(config) {
302
+ return new DimoAdapter(config);
303
+ }
304
+
305
+ exports.ApiError = ApiError;
306
+ exports.AuthenticationError = AuthenticationError;
307
+ exports.BindClient = BindClient;
308
+ exports.BindError = BindError;
309
+ exports.DimoAdapter = DimoAdapter;
310
+ exports.InsufficientCreditsError = InsufficientCreditsError;
311
+ exports.TimeoutError = TimeoutError;
312
+ exports.buildCustomTelemetryQuery = buildCustomTelemetryQuery;
313
+ exports.buildTelemetryQuery = buildTelemetryQuery;
314
+ exports.createDimoAdapter = createDimoAdapter;
315
+ exports.default = BindClient;
316
+ //# sourceMappingURL=index.cjs.map
317
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/core/client.ts","../src/adapters/dimo/queries.ts","../src/adapters/dimo/adapter.ts"],"names":[],"mappings":";;;;;AA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,CAAM,gBAAgB,KAAA,CAAM,IAAA,EAAM,MAAM,EAAE,CAAA;AACnF,IAAA,MAAM,SAAS,MAAM,IAAA,CAAK,UAAA,CAAW,SAAA,CAAU,MAAM,YAAY,CAAA;AACjE,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,eAAA,CAAgB,MAAyB,SAAA,EAAmC;AAC1E,IAAA,IAAI,CAAC,kBAAA,CAAmB,QAAA,CAAS,SAAS,CAAA,EAAG;AAC3C,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,YAAY,SAAS,CAAA,4DAAA,EACE,kBAAA,CAAmB,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,OACtD;AAAA,IACF;AAGA,IAAA,QAAQ,SAAA;AAAW,MACjB,KAAK,2BAAA;AACH,QAAA,OAAO,IAAA,CAAK,iBAAiB,IAAI,CAAA;AAAA,MACnC;AACE,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,SAAS,CAAA,CAAE,CAAA;AAAA;AACpE,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,oBAAA,GAAiC;AAC/B,IAAA,OAAO,CAAC,GAAG,kBAAkB,CAAA;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA,EAMQ,iBAAiB,IAAA,EAAyC;AAChE,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,OAAO,CAAA;AAAA,MACpC,WAAW,IAAA,CAAK;AAAA,KAClB;AAAA,EACF;AACF;AAKO,SAAS,kBAAkB,MAAA,EAAwC;AACxE,EAAA,OAAO,IAAI,YAAY,MAAM,CAAA;AAC/B","file":"index.cjs","sourcesContent":["/**\n * Custom error classes for the Bind Protocol SDK\n */\n\nexport class BindError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'BindError';\n }\n}\n\nexport class ApiError extends BindError {\n constructor(\n message: string,\n public readonly status: number,\n public readonly response?: unknown\n ) {\n super(message, 'API_ERROR', { status, response });\n this.name = 'ApiError';\n }\n}\n\nexport class AuthenticationError extends BindError {\n constructor(message = 'Authentication failed') {\n super(message, 'AUTH_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\nexport class TimeoutError extends BindError {\n constructor(message: string, public readonly timeoutMs: number) {\n super(message, 'TIMEOUT_ERROR', { timeoutMs });\n this.name = 'TimeoutError';\n }\n}\n\nexport class InsufficientCreditsError extends BindError {\n constructor(\n public readonly required: number,\n public readonly available: number\n ) {\n super(\n `Insufficient credits: need ${required}, have ${available}`,\n 'INSUFFICIENT_CREDITS',\n { required, available }\n );\n this.name = 'InsufficientCreditsError';\n }\n}\n","/**\n * BindClient - Main client for interacting with the Bind Protocol API\n */\nimport type { PublicPolicySpec } from '@bind-protocol/policy-spec';\nimport {\n ApiError,\n AuthenticationError,\n InsufficientCreditsError,\n TimeoutError,\n} from './errors';\nimport type {\n BindClientOptions,\n ProveJobInputs,\n SubmitProveJobResponse,\n GetProveJobResponse,\n ListProveJobsOptions,\n ListProveJobsResponse,\n ProveJob,\n} from './types';\n\nconst DEFAULT_BASE_URL = 'https://api.bindprotocol.com';\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 300000; // 5 minutes\n\nexport class BindClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n\n constructor(options: BindClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl || process.env.BIND_API_URL || DEFAULT_BASE_URL;\n this.headers = {\n 'X-API-Key': this.apiKey,\n 'Content-Type': 'application/json',\n };\n }\n\n // ==========================================================================\n // Prove Job Methods\n // ==========================================================================\n\n /**\n * Submit a prove job for async processing\n * @param circuitId - The circuit identifier (e.g., \"bind.mobility.riskband.v1\")\n * @param inputs - Circuit inputs as key-value pairs (all values must be strings)\n * @returns The submitted job details\n * @throws {ApiError} If the API request fails\n * @throws {InsufficientCreditsError} If there aren't enough credits\n */\n async submitProveJob(\n circuitId: string,\n inputs: ProveJobInputs\n ): Promise<SubmitProveJobResponse> {\n const response = await this.fetch('/api/prove', {\n method: 'POST',\n body: JSON.stringify({ circuitId, inputs }),\n });\n\n const result: SubmitProveJobResponse = await response.json();\n\n // Check for insufficient credits\n if (!result.success && result.requiredCredits !== undefined && result.availableCredits !== undefined) {\n throw new InsufficientCreditsError(result.requiredCredits, result.availableCredits);\n }\n\n return result;\n }\n\n /**\n * Get the status and results of a prove job\n * @param jobId - The unique job identifier\n * @returns The job details including status and outputs\n */\n async getProveJob(jobId: string): Promise<GetProveJobResponse> {\n const response = await this.fetch(`/api/prove/${encodeURIComponent(jobId)}`);\n return response.json();\n }\n\n /**\n * List prove jobs for the authenticated organization\n * @param options - Optional filters for status, limit, and offset\n * @returns Paginated list of prove jobs\n */\n async listProveJobs(options: ListProveJobsOptions = {}): Promise<ListProveJobsResponse> {\n const params = new URLSearchParams();\n if (options.status) params.set('status', options.status);\n if (options.limit !== undefined) params.set('limit', options.limit.toString());\n if (options.offset !== undefined) params.set('offset', options.offset.toString());\n\n const queryString = params.toString();\n const path = queryString ? `/api/prove?${queryString}` : '/api/prove';\n\n const response = await this.fetch(path);\n return response.json();\n }\n\n /**\n * Poll for prove job completion\n * @param jobId - The unique job identifier\n * @param options - Polling options\n * @returns The completed or failed job\n * @throws {TimeoutError} If the job doesn't complete within the timeout\n */\n async waitForProveJob(\n jobId: string,\n options: {\n intervalMs?: number;\n timeoutMs?: number;\n onProgress?: (job: ProveJob) => void;\n } = {}\n ): Promise<ProveJob> {\n const intervalMs = options.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeoutMs) {\n const result = await this.getProveJob(jobId);\n\n if (!result.success || !result.data) {\n throw new ApiError(\n result.error || 'Failed to get prove job',\n 500,\n result\n );\n }\n\n const job = result.data;\n\n if (options.onProgress) {\n options.onProgress(job);\n }\n\n if (job.status === 'completed' || job.status === 'failed') {\n return job;\n }\n\n await this.sleep(intervalMs);\n }\n\n throw new TimeoutError(\n `Timeout waiting for prove job ${jobId} after ${timeoutMs}ms`,\n timeoutMs\n );\n }\n\n // ==========================================================================\n // Policy Methods (Public, no authentication required)\n // ==========================================================================\n\n /**\n * List all available public policies\n * @returns Array of public policy specifications\n */\n async listPolicies(): Promise<PublicPolicySpec[]> {\n const response = await fetch(`${this.baseUrl}/api/policies`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new ApiError(\n `Failed to fetch policies: ${response.statusText}`,\n response.status\n );\n }\n\n return response.json();\n }\n\n /**\n * Get a specific policy by ID\n * @param policyId - The unique policy identifier\n * @returns The public policy specification, or null if not found\n */\n async getPolicy(policyId: string): Promise<PublicPolicySpec | null> {\n const response = await fetch(\n `${this.baseUrl}/api/policies/${encodeURIComponent(policyId)}`,\n { method: 'GET' }\n );\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n throw new ApiError(\n `Failed to fetch policy: ${response.statusText}`,\n response.status\n );\n }\n\n return response.json();\n }\n\n // ==========================================================================\n // Private Helpers\n // ==========================================================================\n\n private async fetch(path: string, init?: RequestInit): Promise<Response> {\n const response = await fetch(`${this.baseUrl}${path}`, {\n ...init,\n headers: {\n ...this.headers,\n ...init?.headers,\n },\n });\n\n if (response.status === 401) {\n throw new AuthenticationError();\n }\n\n return response;\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * DIMO GraphQL query builders\n */\n\n/**\n * Build a GraphQL query for fetching vehicle telemetry\n * @param vehicleTokenId - The DIMO vehicle token ID\n * @param from - Start date (ISO 8601 or date string)\n * @param to - End date (ISO 8601 or date string)\n * @returns GraphQL query string\n */\nexport function buildTelemetryQuery(\n vehicleTokenId: string,\n from: string,\n to: string\n): string {\n return `{\n signals(\n tokenId: ${vehicleTokenId},\n interval: \"1h\",\n from: ${from},\n to: ${to}\n ) {\n powertrainTransmissionTravelledDistance(agg: AVG)\n speed(agg: AVG)\n powertrainCombustionEngineSpeed(agg: AVG)\n obdEngineLoad(agg: AVG)\n obdDTCList(agg: UNIQUE)\n obdRunTime(agg: AVG)\n timestamp\n }\n}`;\n}\n\n/**\n * Build a GraphQL query for fetching specific signals\n * Allows customization of which signals to fetch and their aggregation\n */\nexport function buildCustomTelemetryQuery(\n vehicleTokenId: string,\n from: string,\n to: string,\n signals: Array<{\n name: string;\n aggregation?: 'AVG' | 'SUM' | 'MIN' | 'MAX' | 'UNIQUE' | 'COUNT';\n }>,\n interval = '1h'\n): string {\n const signalLines = signals\n .map((s) => {\n if (s.aggregation) {\n return ` ${s.name}(agg: ${s.aggregation})`;\n }\n return ` ${s.name}`;\n })\n .join('\\n');\n\n return `{\n signals(\n tokenId: ${vehicleTokenId},\n interval: \"${interval}\",\n from: ${from},\n to: ${to}\n ) {\n${signalLines}\n timestamp\n }\n}`;\n}\n","/**\n * DIMO Adapter\n *\n * Fetches vehicle telemetry data from the DIMO network and transforms it\n * into circuit inputs for Bind Protocol prove jobs.\n */\n\nimport type { DataAdapter } from '../types';\nimport type { ProveJobInputs } from '../../core/types';\nimport type { DimoAdapterConfig, DimoQuery, DimoTelemetryData, DimoClient } from './types';\nimport { buildTelemetryQuery } from './queries';\n\nconst SUPPORTED_CIRCUITS = [\n 'bind.mobility.riskband.v1',\n];\n\nexport class DimoAdapter implements DataAdapter<DimoAdapterConfig, DimoQuery, DimoTelemetryData> {\n readonly id = 'dimo';\n readonly name = 'DIMO Network';\n readonly description = 'Fetches vehicle telemetry data from the DIMO decentralized network';\n\n private readonly dimoClient: DimoClient;\n\n constructor(config: DimoAdapterConfig) {\n this.dimoClient = config.dimoClient;\n }\n\n /**\n * Fetch telemetry data from DIMO for a vehicle\n * @param query - Query parameters including vehicle token ID and date range\n * @returns Raw telemetry data from DIMO\n */\n async fetchData(query: DimoQuery): Promise<DimoTelemetryData> {\n const graphqlQuery = buildTelemetryQuery(query.vehicleTokenId, query.from, query.to);\n const result = await this.dimoClient.telemetry.query(graphqlQuery);\n return result;\n }\n\n /**\n * Transform DIMO telemetry data into circuit inputs\n * @param data - Raw telemetry data from DIMO\n * @param circuitId - Target circuit ID\n * @returns Inputs ready for prove job submission\n */\n toCircuitInputs(data: DimoTelemetryData, circuitId: string): ProveJobInputs {\n if (!SUPPORTED_CIRCUITS.includes(circuitId)) {\n throw new Error(\n `Circuit \"${circuitId}\" is not supported by the DIMO adapter. ` +\n `Supported circuits: ${SUPPORTED_CIRCUITS.join(', ')}`\n );\n }\n\n // Transform based on circuit type\n switch (circuitId) {\n case 'bind.mobility.riskband.v1':\n return this.toRiskBandInputs(data);\n default:\n throw new Error(`No input transformer for circuit: ${circuitId}`);\n }\n }\n\n /**\n * Get the list of circuits this adapter supports\n */\n getSupportedCircuits(): string[] {\n return [...SUPPORTED_CIRCUITS];\n }\n\n // ===========================================================================\n // Private transformers\n // ===========================================================================\n\n private toRiskBandInputs(data: DimoTelemetryData): ProveJobInputs {\n return {\n signals: JSON.stringify(data.signals),\n timestamp: data.timestamp,\n };\n }\n}\n\n/**\n * Factory function to create a DIMO adapter\n */\nexport function createDimoAdapter(config: DimoAdapterConfig): DimoAdapter {\n return new DimoAdapter(config);\n}\n"]}
@@ -0,0 +1,5 @@
1
+ export { ApiError, AuthenticationError, BindClient, BindError, InsufficientCreditsError, TimeoutError, BindClient as default } from './core/index.cjs';
2
+ export { B as BindClientOptions, g as BindCredential, G as GetProveJobResponse, L as ListProveJobsOptions, f as ListProveJobsResponse, c as ProveJob, a as ProveJobInputs, b as ProveJobOutputs, P as ProveJobStatus, d as ProveJobSummary, S as SubmitProveJobRequest, e as SubmitProveJobResponse } from './types-o4sbOK_a.cjs';
3
+ export { A as AdapterRegistration, g as DataAdapter, D as DimoAdapter, a as DimoAdapterConfig, f as DimoClient, b as DimoQuery, e as DimoSignal, d as DimoTelemetryData, T as TelemetryData, h as TelemetrySignal, c as createDimoAdapter } from './index-5j-fuebC.cjs';
4
+ export { buildCustomTelemetryQuery, buildTelemetryQuery } from './adapters/dimo/index.cjs';
5
+ export { DisclosureSpec, OutputClaimSpec, PolicyId, PolicyMetadata, PublicPolicySpec, SubjectSpec, ValiditySpec } from '@bind-protocol/policy-spec';
@@ -0,0 +1,5 @@
1
+ export { ApiError, AuthenticationError, BindClient, BindError, InsufficientCreditsError, TimeoutError, BindClient as default } from './core/index.js';
2
+ export { B as BindClientOptions, g as BindCredential, G as GetProveJobResponse, L as ListProveJobsOptions, f as ListProveJobsResponse, c as ProveJob, a as ProveJobInputs, b as ProveJobOutputs, P as ProveJobStatus, d as ProveJobSummary, S as SubmitProveJobRequest, e as SubmitProveJobResponse } from './types-o4sbOK_a.js';
3
+ export { A as AdapterRegistration, g as DataAdapter, D as DimoAdapter, a as DimoAdapterConfig, f as DimoClient, b as DimoQuery, e as DimoSignal, d as DimoTelemetryData, T as TelemetryData, h as TelemetrySignal, c as createDimoAdapter } from './index-CASjN9Qe.js';
4
+ export { buildCustomTelemetryQuery, buildTelemetryQuery } from './adapters/dimo/index.js';
5
+ export { DisclosureSpec, OutputClaimSpec, PolicyId, PolicyMetadata, PublicPolicySpec, SubjectSpec, ValiditySpec } from '@bind-protocol/policy-spec';
package/dist/index.js ADDED
@@ -0,0 +1,303 @@
1
+ // src/core/errors.ts
2
+ var BindError = class extends Error {
3
+ constructor(message, code, details) {
4
+ super(message);
5
+ this.code = code;
6
+ this.details = details;
7
+ this.name = "BindError";
8
+ }
9
+ };
10
+ var ApiError = class extends BindError {
11
+ constructor(message, status, response) {
12
+ super(message, "API_ERROR", { status, response });
13
+ this.status = status;
14
+ this.response = response;
15
+ this.name = "ApiError";
16
+ }
17
+ };
18
+ var AuthenticationError = class extends BindError {
19
+ constructor(message = "Authentication failed") {
20
+ super(message, "AUTH_ERROR");
21
+ this.name = "AuthenticationError";
22
+ }
23
+ };
24
+ var TimeoutError = class extends BindError {
25
+ constructor(message, timeoutMs) {
26
+ super(message, "TIMEOUT_ERROR", { timeoutMs });
27
+ this.timeoutMs = timeoutMs;
28
+ this.name = "TimeoutError";
29
+ }
30
+ };
31
+ var InsufficientCreditsError = class extends BindError {
32
+ constructor(required, available) {
33
+ super(
34
+ `Insufficient credits: need ${required}, have ${available}`,
35
+ "INSUFFICIENT_CREDITS",
36
+ { required, available }
37
+ );
38
+ this.required = required;
39
+ this.available = available;
40
+ this.name = "InsufficientCreditsError";
41
+ }
42
+ };
43
+
44
+ // src/core/client.ts
45
+ var DEFAULT_BASE_URL = "https://api.bindprotocol.com";
46
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
47
+ var DEFAULT_TIMEOUT_MS = 3e5;
48
+ var BindClient = class {
49
+ apiKey;
50
+ baseUrl;
51
+ headers;
52
+ constructor(options) {
53
+ this.apiKey = options.apiKey;
54
+ this.baseUrl = options.baseUrl || process.env.BIND_API_URL || DEFAULT_BASE_URL;
55
+ this.headers = {
56
+ "X-API-Key": this.apiKey,
57
+ "Content-Type": "application/json"
58
+ };
59
+ }
60
+ // ==========================================================================
61
+ // Prove Job Methods
62
+ // ==========================================================================
63
+ /**
64
+ * Submit a prove job for async processing
65
+ * @param circuitId - The circuit identifier (e.g., "bind.mobility.riskband.v1")
66
+ * @param inputs - Circuit inputs as key-value pairs (all values must be strings)
67
+ * @returns The submitted job details
68
+ * @throws {ApiError} If the API request fails
69
+ * @throws {InsufficientCreditsError} If there aren't enough credits
70
+ */
71
+ async submitProveJob(circuitId, inputs) {
72
+ const response = await this.fetch("/api/prove", {
73
+ method: "POST",
74
+ body: JSON.stringify({ circuitId, inputs })
75
+ });
76
+ const result = await response.json();
77
+ if (!result.success && result.requiredCredits !== void 0 && result.availableCredits !== void 0) {
78
+ throw new InsufficientCreditsError(result.requiredCredits, result.availableCredits);
79
+ }
80
+ return result;
81
+ }
82
+ /**
83
+ * Get the status and results of a prove job
84
+ * @param jobId - The unique job identifier
85
+ * @returns The job details including status and outputs
86
+ */
87
+ async getProveJob(jobId) {
88
+ const response = await this.fetch(`/api/prove/${encodeURIComponent(jobId)}`);
89
+ return response.json();
90
+ }
91
+ /**
92
+ * List prove jobs for the authenticated organization
93
+ * @param options - Optional filters for status, limit, and offset
94
+ * @returns Paginated list of prove jobs
95
+ */
96
+ async listProveJobs(options = {}) {
97
+ const params = new URLSearchParams();
98
+ if (options.status) params.set("status", options.status);
99
+ if (options.limit !== void 0) params.set("limit", options.limit.toString());
100
+ if (options.offset !== void 0) params.set("offset", options.offset.toString());
101
+ const queryString = params.toString();
102
+ const path = queryString ? `/api/prove?${queryString}` : "/api/prove";
103
+ const response = await this.fetch(path);
104
+ return response.json();
105
+ }
106
+ /**
107
+ * Poll for prove job completion
108
+ * @param jobId - The unique job identifier
109
+ * @param options - Polling options
110
+ * @returns The completed or failed job
111
+ * @throws {TimeoutError} If the job doesn't complete within the timeout
112
+ */
113
+ async waitForProveJob(jobId, options = {}) {
114
+ const intervalMs = options.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
115
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
116
+ const startTime = Date.now();
117
+ while (Date.now() - startTime < timeoutMs) {
118
+ const result = await this.getProveJob(jobId);
119
+ if (!result.success || !result.data) {
120
+ throw new ApiError(
121
+ result.error || "Failed to get prove job",
122
+ 500,
123
+ result
124
+ );
125
+ }
126
+ const job = result.data;
127
+ if (options.onProgress) {
128
+ options.onProgress(job);
129
+ }
130
+ if (job.status === "completed" || job.status === "failed") {
131
+ return job;
132
+ }
133
+ await this.sleep(intervalMs);
134
+ }
135
+ throw new TimeoutError(
136
+ `Timeout waiting for prove job ${jobId} after ${timeoutMs}ms`,
137
+ timeoutMs
138
+ );
139
+ }
140
+ // ==========================================================================
141
+ // Policy Methods (Public, no authentication required)
142
+ // ==========================================================================
143
+ /**
144
+ * List all available public policies
145
+ * @returns Array of public policy specifications
146
+ */
147
+ async listPolicies() {
148
+ const response = await fetch(`${this.baseUrl}/api/policies`, {
149
+ method: "GET"
150
+ });
151
+ if (!response.ok) {
152
+ throw new ApiError(
153
+ `Failed to fetch policies: ${response.statusText}`,
154
+ response.status
155
+ );
156
+ }
157
+ return response.json();
158
+ }
159
+ /**
160
+ * Get a specific policy by ID
161
+ * @param policyId - The unique policy identifier
162
+ * @returns The public policy specification, or null if not found
163
+ */
164
+ async getPolicy(policyId) {
165
+ const response = await fetch(
166
+ `${this.baseUrl}/api/policies/${encodeURIComponent(policyId)}`,
167
+ { method: "GET" }
168
+ );
169
+ if (response.status === 404) {
170
+ return null;
171
+ }
172
+ if (!response.ok) {
173
+ throw new ApiError(
174
+ `Failed to fetch policy: ${response.statusText}`,
175
+ response.status
176
+ );
177
+ }
178
+ return response.json();
179
+ }
180
+ // ==========================================================================
181
+ // Private Helpers
182
+ // ==========================================================================
183
+ async fetch(path, init) {
184
+ const response = await fetch(`${this.baseUrl}${path}`, {
185
+ ...init,
186
+ headers: {
187
+ ...this.headers,
188
+ ...init?.headers
189
+ }
190
+ });
191
+ if (response.status === 401) {
192
+ throw new AuthenticationError();
193
+ }
194
+ return response;
195
+ }
196
+ sleep(ms) {
197
+ return new Promise((resolve) => setTimeout(resolve, ms));
198
+ }
199
+ };
200
+
201
+ // src/adapters/dimo/queries.ts
202
+ function buildTelemetryQuery(vehicleTokenId, from, to) {
203
+ return `{
204
+ signals(
205
+ tokenId: ${vehicleTokenId},
206
+ interval: "1h",
207
+ from: ${from},
208
+ to: ${to}
209
+ ) {
210
+ powertrainTransmissionTravelledDistance(agg: AVG)
211
+ speed(agg: AVG)
212
+ powertrainCombustionEngineSpeed(agg: AVG)
213
+ obdEngineLoad(agg: AVG)
214
+ obdDTCList(agg: UNIQUE)
215
+ obdRunTime(agg: AVG)
216
+ timestamp
217
+ }
218
+ }`;
219
+ }
220
+ function buildCustomTelemetryQuery(vehicleTokenId, from, to, signals, interval = "1h") {
221
+ const signalLines = signals.map((s) => {
222
+ if (s.aggregation) {
223
+ return ` ${s.name}(agg: ${s.aggregation})`;
224
+ }
225
+ return ` ${s.name}`;
226
+ }).join("\n");
227
+ return `{
228
+ signals(
229
+ tokenId: ${vehicleTokenId},
230
+ interval: "${interval}",
231
+ from: ${from},
232
+ to: ${to}
233
+ ) {
234
+ ${signalLines}
235
+ timestamp
236
+ }
237
+ }`;
238
+ }
239
+
240
+ // src/adapters/dimo/adapter.ts
241
+ var SUPPORTED_CIRCUITS = [
242
+ "bind.mobility.riskband.v1"
243
+ ];
244
+ var DimoAdapter = class {
245
+ id = "dimo";
246
+ name = "DIMO Network";
247
+ description = "Fetches vehicle telemetry data from the DIMO decentralized network";
248
+ dimoClient;
249
+ constructor(config) {
250
+ this.dimoClient = config.dimoClient;
251
+ }
252
+ /**
253
+ * Fetch telemetry data from DIMO for a vehicle
254
+ * @param query - Query parameters including vehicle token ID and date range
255
+ * @returns Raw telemetry data from DIMO
256
+ */
257
+ async fetchData(query) {
258
+ const graphqlQuery = buildTelemetryQuery(query.vehicleTokenId, query.from, query.to);
259
+ const result = await this.dimoClient.telemetry.query(graphqlQuery);
260
+ return result;
261
+ }
262
+ /**
263
+ * Transform DIMO telemetry data into circuit inputs
264
+ * @param data - Raw telemetry data from DIMO
265
+ * @param circuitId - Target circuit ID
266
+ * @returns Inputs ready for prove job submission
267
+ */
268
+ toCircuitInputs(data, circuitId) {
269
+ if (!SUPPORTED_CIRCUITS.includes(circuitId)) {
270
+ throw new Error(
271
+ `Circuit "${circuitId}" is not supported by the DIMO adapter. Supported circuits: ${SUPPORTED_CIRCUITS.join(", ")}`
272
+ );
273
+ }
274
+ switch (circuitId) {
275
+ case "bind.mobility.riskband.v1":
276
+ return this.toRiskBandInputs(data);
277
+ default:
278
+ throw new Error(`No input transformer for circuit: ${circuitId}`);
279
+ }
280
+ }
281
+ /**
282
+ * Get the list of circuits this adapter supports
283
+ */
284
+ getSupportedCircuits() {
285
+ return [...SUPPORTED_CIRCUITS];
286
+ }
287
+ // ===========================================================================
288
+ // Private transformers
289
+ // ===========================================================================
290
+ toRiskBandInputs(data) {
291
+ return {
292
+ signals: JSON.stringify(data.signals),
293
+ timestamp: data.timestamp
294
+ };
295
+ }
296
+ };
297
+ function createDimoAdapter(config) {
298
+ return new DimoAdapter(config);
299
+ }
300
+
301
+ export { ApiError, AuthenticationError, BindClient, BindError, DimoAdapter, InsufficientCreditsError, TimeoutError, buildCustomTelemetryQuery, buildTelemetryQuery, createDimoAdapter, BindClient as default };
302
+ //# sourceMappingURL=index.js.map
303
+ //# sourceMappingURL=index.js.map