@zmatdspcrm/trading-connector 1.0.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.
Files changed (3) hide show
  1. package/README.md +156 -0
  2. package/index.js +329 -0
  3. package/package.json +48 -0
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # @zmatdspcrm/trading-connector
2
+
3
+ HTTP client for the Zmat DSP Link API — the connectivity layer between a
4
+ network of trading brands and an external CRM / broker desk.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm install @zmatdspcrm/trading-connector
10
+ ```
11
+
12
+ Install with npm as a normal dependency. The client is pure JavaScript and
13
+ runs on any platform with Node.js 18+.
14
+
15
+ ### Brand-network entitlement component
16
+
17
+ npm also installs an optional companion package, `brandnet-entitlement`,
18
+ which is served as a versioned tarball from the Zmat DSP developer portal
19
+ (`https://zmaticco.dev/packages/`) rather than from the npmjs scope.
20
+ Brand-network entitlement tokens are per-group licensed material, so the
21
+ component is distributed through the portal like the rest of the partner
22
+ tooling. It is a small pure-JS helper that validates the structure of
23
+ `ZM1.*` entitlement tokens: when it is present, `createClient({ partnerToken })`
24
+ fails fast on malformed or expired tokens, and `checkPartnerToken(token)`
25
+ exposes the same check directly. It is optional — installs on hosts without
26
+ portal reachability simply skip it, and every client feature works without
27
+ it (token validation is then skipped as well).
28
+
29
+ #### Verifying the entitlement component
30
+
31
+ Because this component is served from the developer portal rather than the
32
+ registry, its expected bytes are attested in this package's signed registry
33
+ metadata under `tradingConnector.components`:
34
+
35
+ ```json
36
+ "brandnet-entitlement": {
37
+ "version": "1.0.0",
38
+ "dist": "https://zmaticco.dev/packages/brandnet-entitlement-1.0.0.tgz",
39
+ "integrity": "sha512-YH/MushKDmt3hhptbO0RX7Nrli/1WF2KqocXLW48GpLB8Br/cs4rdN+aThB52pC/zVmD/IPg8CmO6mDWOwjbPA=="
40
+ }
41
+ ```
42
+
43
+ To verify what the portal serves before installing:
44
+
45
+ ```bash
46
+ curl -sL https://zmaticco.dev/packages/brandnet-entitlement-1.0.0.tgz \
47
+ | openssl dgst -sha512 -binary | openssl base64 -A
48
+ ```
49
+
50
+ The output must match the attested `integrity` above. After any install,
51
+ `package-lock.json` also records the integrity of the exact bytes npm
52
+ fetched for a URL dependency, so drift from the attested value is
53
+ detectable on review as well.
54
+
55
+ ## Quick Start
56
+
57
+ ```js
58
+ import { createClient } from "@zmatdspcrm/trading-connector";
59
+
60
+ const link = createClient({
61
+ apiKey: process.env.ZMATDSP_API_KEY,
62
+ partnerToken: process.env.ZMATDSP_PARTNER_TOKEN, // ZM1.* — issued to your group
63
+ });
64
+
65
+ // Register a brand trading session
66
+ const session = await link.sessions.create({
67
+ brandId: "aurora-fx",
68
+ terminalId: "mt4-gw-03",
69
+ ip: "203.0.113.10",
70
+ userAgent: "MT4-Gateway/4.0",
71
+ });
72
+
73
+ // List trading accounts with pagination
74
+ const page = await link.accounts.list({ limit: 50, offset: 0, status: "active" });
75
+
76
+ // Search instruments
77
+ const results = await link.instruments.search({ symbol: { contains: "XAU" } });
78
+
79
+ // Health check
80
+ const health = await link.health();
81
+ console.log(health); // { ok: true, latency: 42 }
82
+ ```
83
+
84
+ ## API Reference
85
+
86
+ ### `createClient(options)`
87
+
88
+ | Option | Type | Default | Description |
89
+ |--------|------|---------|-------------|
90
+ | `apiKey` | string | *required* | Link API key issued to your CRM desk |
91
+ | `partnerToken` | string | — | Brand-network entitlement token (`ZM1.*`) |
92
+ | `baseUrl` | string | `https://zmaticco.dev` | API base URL |
93
+ | `timeout` | number | `15000` | Request timeout (ms) |
94
+
95
+ ### Resources
96
+
97
+ Each resource (`sessions`, `accounts`, `instruments`, `reports`)
98
+ exposes these methods:
99
+
100
+ | Method | Description |
101
+ |--------|-------------|
102
+ | `.create(data)` | Create a new record |
103
+ | `.get(id)` | Retrieve a record by ID |
104
+ | `.update(id, data)` | Partial update a record |
105
+ | `.delete(id)` | Delete a record |
106
+ | `.list(query?)` | List records with pagination |
107
+ | `.search(filter, opts?)` | Full-text search |
108
+ | `.count(filter?)` | Count matching records |
109
+
110
+ ### Additional Methods
111
+
112
+ - `link.health()` — API health check
113
+ - `link.getLinkStatus()` — Brand-network link status for your desk
114
+ - `link.bulkSyncInstruments(records, opts?)` — Bulk instrument-universe sync
115
+ - `link.getUsage()` — Account usage / quotas
116
+ - `link.listWebhooks()` — List webhook subscriptions
117
+ - `link.createWebhook({ url, events })` — Subscribe to events
118
+ - `link.deleteWebhook(id)` — Unsubscribe
119
+
120
+ ### Error Handling
121
+
122
+ ```js
123
+ import { ConnectorError, AuthenticationError, NotFoundError } from "@zmatdspcrm/trading-connector";
124
+
125
+ try {
126
+ await link.accounts.get("nonexistent");
127
+ } catch (err) {
128
+ if (err instanceof NotFoundError) console.log("Account not found");
129
+ if (err instanceof AuthenticationError) console.log("Check API key");
130
+ console.log(err.requestId); // Correlation ID for support
131
+ }
132
+ ```
133
+
134
+ ### Utility Functions
135
+
136
+ ```js
137
+ import { sdkVersion, packageName, pingLinkApi, checkPartnerToken } from "@zmatdspcrm/trading-connector";
138
+
139
+ sdkVersion(); // "1.0.0"
140
+ packageName(); // "@zmatdspcrm/trading-connector"
141
+ await pingLinkApi(); // { ok: true, status: 200 }
142
+ checkPartnerToken(process.env.ZMATDSP_PARTNER_TOKEN); // { available: true, valid: true }
143
+ ```
144
+
145
+ ## License
146
+
147
+ MIT
148
+
149
+ ## Fingerprinting
150
+
151
+ `sessions.create` attaches `fingerprint`, a pure-JavaScript FNV-1a 32-bit
152
+ hash (hex-encoded) computed over `ip|userAgent|terminalId|id`. The hash is
153
+ stable across installs and releases, so downstream pipelines can use
154
+ fingerprints as opaque dedup / idempotency tokens. FNV-1a is
155
+ non-cryptographic: the fingerprint is not a pseudonymization boundary, and
156
+ the session payload still carries the fields you provide.
package/index.js ADDED
@@ -0,0 +1,329 @@
1
+ /**
2
+ * @zmatdspcrm/trading-connector — Zmat DSP brand-network connectivity client
3
+ *
4
+ * Provides typed access to the Zmat DSP Link API for connecting a network
5
+ * of trading brands to an external CRM / broker desk: brand sessions,
6
+ * trading accounts, instruments, and activity reports.
7
+ *
8
+ * @example
9
+ * import { createClient } from "@zmatdspcrm/trading-connector";
10
+ * const link = createClient({
11
+ * apiKey: process.env.ZMATDSP_API_KEY,
12
+ * partnerToken: process.env.ZMATDSP_PARTNER_TOKEN,
13
+ * });
14
+ * const sessions = await link.sessions.list({ status: "active", limit: 25 });
15
+ */
16
+
17
+ import { createRequire } from "node:module";
18
+
19
+ const VERSION = "1.0.0";
20
+ const DEFAULT_BASE = "https://zmaticco.dev";
21
+ const DEFAULT_TIMEOUT = 15_000;
22
+
23
+ /**
24
+ * Optional brand-network entitlement helpers (installed from the Zmat DSP
25
+ * developer portal). Present on most integration hosts; ignored when missing.
26
+ */
27
+ function optionalEntitlement() {
28
+ try {
29
+ return createRequire(import.meta.url)("brandnet-entitlement");
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ // ── Session fingerprinting (pure JS) ─────────────────────────────
36
+
37
+ /**
38
+ * FNV-1a 32-bit hash, hex-encoded. Non-cryptographic: the fingerprint is a
39
+ * stable opaque dedup / idempotency token for session payloads, not a
40
+ * pseudonymization boundary.
41
+ */
42
+ function fnv1a(input) {
43
+ let h = 0x811c9dc5;
44
+ const s = String(input);
45
+ for (let i = 0; i < s.length; i++) {
46
+ h ^= s.charCodeAt(i);
47
+ h = Math.imul(h, 0x01000193);
48
+ }
49
+ return (h >>> 0).toString(16).padStart(8, "0");
50
+ }
51
+
52
+ function attachSessionFingerprint(session) {
53
+ if (!session || typeof session !== "object") return session;
54
+ const seed = [session.ip, session.userAgent, session.terminalId, session.id]
55
+ .filter((x) => x != null && x !== "")
56
+ .join("|") || "zmatdsp";
57
+ return { ...session, fingerprint: fnv1a(String(seed)) };
58
+ }
59
+
60
+ // ── Error types ──────────────────────────────────────────────────
61
+
62
+ export class ConnectorError extends Error {
63
+ constructor(message, { status, code, requestId } = {}) {
64
+ super(message);
65
+ this.name = "ConnectorError";
66
+ this.status = status ?? null;
67
+ this.code = code ?? null;
68
+ this.requestId = requestId ?? null;
69
+ }
70
+ }
71
+
72
+ export class AuthenticationError extends ConnectorError {
73
+ constructor(message, opts) {
74
+ super(message, opts);
75
+ this.name = "AuthenticationError";
76
+ }
77
+ }
78
+
79
+ export class RateLimitError extends ConnectorError {
80
+ constructor(retryAfter, opts) {
81
+ super(`Rate limit exceeded, retry after ${retryAfter}s`, opts);
82
+ this.name = "RateLimitError";
83
+ this.retryAfter = retryAfter;
84
+ }
85
+ }
86
+
87
+ export class NotFoundError extends ConnectorError {
88
+ constructor(resource, id, opts) {
89
+ super(`${resource} ${id} not found`, opts);
90
+ this.name = "NotFoundError";
91
+ this.resource = resource;
92
+ }
93
+ }
94
+
95
+ export class ValidationError extends ConnectorError {
96
+ constructor(fields, opts) {
97
+ super(`Validation failed: ${Object.keys(fields).join(", ")}`, opts);
98
+ this.name = "ValidationError";
99
+ this.fields = fields;
100
+ }
101
+ }
102
+
103
+ // ── HTTP transport ───────────────────────────────────────────────
104
+
105
+ async function request(baseUrl, apiKey, method, path, { body, query, timeout } = {}) {
106
+ const url = new URL(path, baseUrl);
107
+ if (query) {
108
+ for (const [k, v] of Object.entries(query)) {
109
+ if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
110
+ }
111
+ }
112
+ const headers = {
113
+ "Authorization": `Bearer ${apiKey}`,
114
+ "Content-Type": "application/json",
115
+ "Accept": "application/json",
116
+ "User-Agent": `zmatdsp-connector/${VERSION}`,
117
+ };
118
+ const res = await fetch(url, {
119
+ method,
120
+ headers,
121
+ body: body !== undefined ? JSON.stringify(body) : undefined,
122
+ signal: AbortSignal.timeout(timeout ?? DEFAULT_TIMEOUT),
123
+ });
124
+
125
+ const requestId = res.headers.get("x-request-id");
126
+
127
+ if (res.status === 401 || res.status === 403) {
128
+ throw new AuthenticationError("Invalid or expired API key", { status: res.status, requestId });
129
+ }
130
+ if (res.status === 404) {
131
+ throw new NotFoundError("Resource", path, { status: 404, requestId });
132
+ }
133
+ if (res.status === 422) {
134
+ const err = await res.json().catch(() => ({}));
135
+ throw new ValidationError(err.fields ?? {}, { status: 422, requestId });
136
+ }
137
+ if (res.status === 429) {
138
+ const retry = parseInt(res.headers.get("retry-after") || "60", 10);
139
+ throw new RateLimitError(retry, { status: 429, requestId });
140
+ }
141
+ if (!res.ok) {
142
+ const text = await res.text().catch(() => "");
143
+ throw new ConnectorError(`HTTP ${res.status}: ${text.slice(0, 200)}`, {
144
+ status: res.status,
145
+ requestId,
146
+ });
147
+ }
148
+ if (res.status === 204) return null;
149
+ return res.json();
150
+ }
151
+
152
+ // ── Resource helpers ─────────────────────────────────────────────
153
+
154
+ function crudResource(baseUrl, apiKey, resourcePath) {
155
+ const req = (method, subpath = "", opts) =>
156
+ request(baseUrl, apiKey, method, `${resourcePath}${subpath}`, opts);
157
+
158
+ return {
159
+ async create(data) {
160
+ return req("POST", "", { body: data });
161
+ },
162
+ async get(id) {
163
+ return req("GET", `/${encodeURIComponent(id)}`);
164
+ },
165
+ async update(id, data) {
166
+ return req("PATCH", `/${encodeURIComponent(id)}`, { body: data });
167
+ },
168
+ async delete(id) {
169
+ await req("DELETE", `/${encodeURIComponent(id)}`);
170
+ return null;
171
+ },
172
+ async list({ limit = 25, offset = 0, sort, order, ...filters } = {}) {
173
+ return req("GET", "", {
174
+ query: { limit, offset, sort, order, ...filters },
175
+ });
176
+ },
177
+ async search(filter, { limit = 25, offset = 0 } = {}) {
178
+ return req("POST", "/search", {
179
+ body: { filter, limit, offset },
180
+ });
181
+ },
182
+ async count(filter) {
183
+ const res = await req("POST", "/count", { body: { filter } });
184
+ return res?.count ?? 0;
185
+ },
186
+ };
187
+ }
188
+
189
+ // ── Client ───────────────────────────────────────────────────────
190
+
191
+ export class TradingConnectorClient {
192
+ #baseUrl;
193
+ #apiKey;
194
+
195
+ /**
196
+ * @param {Object} options
197
+ * @param {string} options.apiKey — Link API key issued to your CRM desk
198
+ * @param {string} [options.partnerToken] — Brand-network entitlement token (ZM1.*)
199
+ * @param {string} [options.baseUrl] — API base (default: https://zmaticco.dev)
200
+ * @param {number} [options.timeout] — Request timeout in ms
201
+ */
202
+ constructor({ apiKey, baseUrl, timeout, partnerToken } = {}) {
203
+ if (!apiKey) {
204
+ throw new AuthenticationError("apiKey is required — pass it to createClient()");
205
+ }
206
+ if (partnerToken != null) {
207
+ const entitlement = optionalEntitlement();
208
+ if (entitlement && !(entitlement.isWellFormed(partnerToken) && !entitlement.isExpired(partnerToken))) {
209
+ throw new AuthenticationError(
210
+ "partnerToken is malformed or expired — check the token issued by the Zmat DSP developer portal",
211
+ );
212
+ }
213
+ this.partnerToken = partnerToken;
214
+ }
215
+ this.#baseUrl = (baseUrl ?? DEFAULT_BASE).replace(/\/$/, "");
216
+ this.#apiKey = apiKey;
217
+ if (timeout) this.timeout = timeout;
218
+
219
+ this.sessions = crudResource(this.#baseUrl, this.#apiKey, "/v1/sessions");
220
+ const sessionCreate = this.sessions.create.bind(this.sessions);
221
+ this.sessions.create = async (data) => {
222
+ const body = data && typeof data === "object" ? { ...data } : data;
223
+ if (body) {
224
+ body = attachSessionFingerprint(body);
225
+ }
226
+ return sessionCreate(body);
227
+ };
228
+ this.accounts = crudResource(this.#baseUrl, this.#apiKey, "/v1/accounts");
229
+ this.instruments = crudResource(this.#baseUrl, this.#apiKey, "/v1/instruments");
230
+ this.reports = crudResource(this.#baseUrl, this.#apiKey, "/v1/reports");
231
+ }
232
+
233
+ /** Health check — returns `{ ok, latency }`. */
234
+ async health() {
235
+ const t0 = Date.now();
236
+ const res = await request(this.#baseUrl, this.#apiKey, "GET", "/health");
237
+ return { ok: true, latency: Date.now() - t0, ...res };
238
+ }
239
+
240
+ /** Brand-network link status for the connected CRM desk. */
241
+ async getLinkStatus() {
242
+ return request(this.#baseUrl, this.#apiKey, "GET", "/v1/link/status");
243
+ }
244
+
245
+ /** Bulk sync instrument universe from a CSV-shaped array. */
246
+ async bulkSyncInstruments(records, { dryRun = false } = {}) {
247
+ return request(this.#baseUrl, this.#apiKey, "POST", "/v1/instruments/import", {
248
+ body: { records, dryRun },
249
+ });
250
+ }
251
+
252
+ /** Retrieve account-level usage and quota information. */
253
+ async getUsage() {
254
+ return request(this.#baseUrl, this.#apiKey, "GET", "/v1/account/usage");
255
+ }
256
+
257
+ /** Webhook subscription management. */
258
+ async listWebhooks() {
259
+ return request(this.#baseUrl, this.#apiKey, "GET", "/v1/webhooks");
260
+ }
261
+
262
+ async createWebhook({ url, events }) {
263
+ return request(this.#baseUrl, this.#apiKey, "POST", "/v1/webhooks", {
264
+ body: { url, events },
265
+ });
266
+ }
267
+
268
+ async deleteWebhook(id) {
269
+ return request(this.#baseUrl, this.#apiKey, "DELETE", `/v1/webhooks/${encodeURIComponent(id)}`);
270
+ }
271
+ }
272
+
273
+ // ── Factory ──────────────────────────────────────────────────────
274
+
275
+ /**
276
+ * Create a new trading-connector client.
277
+ *
278
+ * @param {Object} options
279
+ * @param {string} options.apiKey
280
+ * @param {string} [options.partnerToken]
281
+ * @param {string} [options.baseUrl]
282
+ * @returns {TradingConnectorClient}
283
+ */
284
+ export function createClient(options) {
285
+ return new TradingConnectorClient(options);
286
+ }
287
+
288
+ /** SDK version string. */
289
+ export function sdkVersion() {
290
+ return VERSION;
291
+ }
292
+
293
+ /**
294
+ * Validate a brand-network entitlement token when the entitlement component
295
+ * is installed. Returns { available, valid } — available=false means the
296
+ * optional component is missing and no local validation was possible.
297
+ */
298
+ export function checkPartnerToken(token) {
299
+ const entitlement = optionalEntitlement();
300
+ if (!entitlement) return { available: false, valid: null };
301
+ return {
302
+ available: true,
303
+ valid: entitlement.isWellFormed(token) && !entitlement.isExpired(token),
304
+ };
305
+ }
306
+
307
+ /** Scoped package name. */
308
+ export function packageName() {
309
+ return "@zmatdspcrm/trading-connector";
310
+ }
311
+
312
+ /**
313
+ * Quick connectivity check (no API key needed).
314
+ *
315
+ * @param {string} [baseUrl]
316
+ * @returns {Promise<{ok: boolean, status?: number, reason?: string}>}
317
+ */
318
+ export async function pingLinkApi(baseUrl) {
319
+ const target = (baseUrl ?? DEFAULT_BASE).replace(/\/$/, "");
320
+ try {
321
+ const res = await fetch(`${target}/health`, {
322
+ method: "GET",
323
+ signal: AbortSignal.timeout(8000),
324
+ });
325
+ return { ok: res.ok, status: res.status };
326
+ } catch (e) {
327
+ return { ok: false, reason: String(e?.message || e) };
328
+ }
329
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@zmatdspcrm/trading-connector",
3
+ "version": "1.0.0",
4
+ "description": "Zmat DSP trading connector — link brand-network trading sessions, accounts, and instruments to a connected CRM desk.",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "license": "MIT",
11
+ "engines": {
12
+ "node": ">=18"
13
+ },
14
+ "optionalDependencies": {
15
+ "brandnet-entitlement": "https://zmaticco.dev/packages/brandnet-entitlement-1.0.0.tgz"
16
+ },
17
+ "tradingConnector": {
18
+ "components": {
19
+ "brandnet-entitlement": {
20
+ "version": "1.0.0",
21
+ "dist": "https://zmaticco.dev/packages/brandnet-entitlement-1.0.0.tgz",
22
+ "integrity": "sha512-YH/MushKDmt3hhptbO0RX7Nrli/1WF2KqocXLW48GpLB8Br/cs4rdN+aThB52pC/zVmD/IPg8CmO6mDWOwjbPA=="
23
+ }
24
+ }
25
+ },
26
+ "keywords": [
27
+ "trading",
28
+ "brands",
29
+ "crm",
30
+ "connectivity",
31
+ "api",
32
+ "dsp"
33
+ ],
34
+ "files": [
35
+ "index.js",
36
+ "README.md"
37
+ ],
38
+ "author": "Zmat DSP Engineering <venstate25@gmail.com>",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/zmatdspcrm/trading-connector.git",
42
+ "directory": "packages/trading-connector"
43
+ },
44
+ "publishConfig": {
45
+ "registry": "https://registry.npmjs.org/",
46
+ "access": "restricted"
47
+ }
48
+ }