prezense 0.0.0-stage → 1.4.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.

Potentially problematic release.


This version of prezense might be problematic. Click here for more details.

package/cli.js ADDED
@@ -0,0 +1,483 @@
1
+ #!/usr/bin/env node
2
+ // `prezense deploy` — publish a storefront built on your own computer to its
3
+ // Prezense store. Run it from the project's root folder:
4
+ //
5
+ // npx prezense deploy
6
+ //
7
+ // It reads the same PREZENSE_API_KEY and PREZENSE_PLATFORM_KEY the storefront
8
+ // uses (from the environment, then .env.local, then .env), uploads the source —
9
+ // never node_modules, build output, .git or .env files — and Prezense installs,
10
+ // builds and publishes it, then switches the store's live address over. A
11
+ // failed publish leaves the live site as it was.
12
+ //
13
+ // `prezense upload` — put images, videos and audio from your computer into the
14
+ // store's media library, optionally on a product:
15
+ //
16
+ // npx prezense upload ./photos --product "Diamond necklace"
17
+ //
18
+ // It asks the store's MCP server (the same tools an AI agent uses:
19
+ // start_media_upload, finish_media_upload, get_media_upload_status) for a
20
+ // one-time upload link per file, sends each file straight to it with a
21
+ // progress bar, then waits while videos and audio are processed.
22
+
23
+ import { spawn } from 'node:child_process';
24
+ import { createReadStream, existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
25
+ import http from 'node:http';
26
+ import https from 'node:https';
27
+ import path from 'node:path';
28
+
29
+ const DEFAULT_DEPLOY_URL = 'https://deploy.prezense.app';
30
+ const POLL_MS = 3000;
31
+ const TIMEOUT_MS = 20 * 60 * 1000;
32
+ const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
33
+
34
+ // Never uploaded. `./x` entries are anchored at the project root; the rest
35
+ // match anywhere (nothing needs a nested node_modules or .git).
36
+ const EXCLUDES = [
37
+ 'node_modules', '.git', '.DS_Store',
38
+ './.next', './.svelte-kit', './build', './.vercel', './.turbo', './.cache',
39
+ './.env', './.env.*',
40
+ ];
41
+
42
+ const HELP = `Usage:
43
+ prezense deploy [folder]
44
+ prezense upload <files or folders…> [--product <id or name>] [--as thumbnail|gallery]
45
+
46
+ deploy Publishes the storefront in [folder] (default: the current folder) to
47
+ the Prezense store whose keys it uses.
48
+
49
+ upload Adds images (png, jpg, gif, webp), videos (mp4, mov) and audio
50
+ (mp3, wav) to the store's media library. A folder adds every such file
51
+ directly inside it. --product links them to a product (its id, or its
52
+ name); --as thumbnail makes an image the product's main picture
53
+ (default: gallery). Shows each file's upload and processing progress
54
+ and prints its media link when done.
55
+
56
+ Both read PREZENSE_API_KEY and PREZENSE_PLATFORM_KEY from the environment,
57
+ .env.local or .env. Copy those keys from the Prezense app: Settings → Your own
58
+ agents.`;
59
+
60
+ function readEnvFile(file) {
61
+ const values = {};
62
+ if (!existsSync(file)) return values;
63
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
64
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/);
65
+ if (!m) continue;
66
+ let value = m[2];
67
+ if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
68
+ else value = value.replace(/\s+#.*$/, '');
69
+ values[m[1]] = value;
70
+ }
71
+ return values;
72
+ }
73
+
74
+ function setting(name, dir) {
75
+ return process.env[name]
76
+ || readEnvFile(path.join(dir, '.env.local'))[name]
77
+ || readEnvFile(path.join(dir, '.env'))[name]
78
+ || '';
79
+ }
80
+
81
+ function packSource(dir) {
82
+ return new Promise((resolve, reject) => {
83
+ const args = ['czf', '-', ...EXCLUDES.map((p) => `--exclude=${p}`), '-C', dir, '.'];
84
+ // COPYFILE_DISABLE stops macOS tar adding ._ metadata files.
85
+ const tar = spawn('tar', args, { env: { ...process.env, COPYFILE_DISABLE: '1' } });
86
+ const chunks = [];
87
+ let size = 0;
88
+ let stderr = '';
89
+ tar.stdout.on('data', (c) => {
90
+ size += c.length;
91
+ chunks.push(c);
92
+ });
93
+ tar.stderr.on('data', (c) => { stderr += c; });
94
+ tar.on('error', (err) => reject(new Error(`couldn't run tar (${err.message})`)));
95
+ tar.on('close', (code) => {
96
+ if (code !== 0) reject(new Error(`tar failed: ${stderr.trim() || `exit ${code}`}`));
97
+ else resolve(Buffer.concat(chunks, size));
98
+ });
99
+ });
100
+ }
101
+
102
+ async function call(url, init) {
103
+ let res;
104
+ try {
105
+ res = await fetch(url, init);
106
+ } catch (err) {
107
+ throw new Error(`couldn't reach Prezense at ${url} (${err.cause?.code || err.message})`);
108
+ }
109
+ const body = await res.json().catch(() => ({}));
110
+ if (!res.ok) throw new Error(body.error || `Prezense answered ${res.status}`);
111
+ return body;
112
+ }
113
+
114
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
115
+
116
+ async function deploy(folder) {
117
+ const dir = path.resolve(folder || '.');
118
+ if (!existsSync(path.join(dir, 'package.json'))) {
119
+ throw new Error(`there's no package.json in ${dir} — run this from your storefront's root folder`);
120
+ }
121
+ const apiKey = setting('PREZENSE_API_KEY', dir);
122
+ const platformKey = setting('PREZENSE_PLATFORM_KEY', dir);
123
+ if (!apiKey || !platformKey) {
124
+ throw new Error('PREZENSE_API_KEY and PREZENSE_PLATFORM_KEY are not set. Copy them into .env.local from Settings → Your own agents in the Prezense app.');
125
+ }
126
+ const base = (setting('PREZENSE_DEPLOY_URL', dir) || DEFAULT_DEPLOY_URL).replace(/\/+$/, '');
127
+ const headers = { 'x-api-key': apiKey, 'x-platform-key': platformKey };
128
+
129
+ console.log(`Packing ${dir}…`);
130
+ const archive = await packSource(dir);
131
+ if (archive.length > MAX_UPLOAD_BYTES) {
132
+ throw new Error(`the source is ${(archive.length / 1048576).toFixed(0)} MB packed — over the 50 MB limit. Leave large files out of the project folder.`);
133
+ }
134
+ console.log(`Uploading ${(archive.length / 1024).toFixed(0)} KB to store "${platformKey}"…`);
135
+ const { deployment } = await call(`${base}/v1/deployments`, {
136
+ method: 'POST',
137
+ headers: { ...headers, 'content-type': 'application/gzip' },
138
+ body: archive,
139
+ });
140
+
141
+ // Print each new progress line once. The server keeps a rolling tail, so
142
+ // match on the last line seen rather than on a count.
143
+ let lastLine = null;
144
+ const printNew = (log) => {
145
+ const from = lastLine === null ? 0 : log.lastIndexOf(lastLine) + 1;
146
+ for (const line of log.slice(from)) console.log(` ${line}`);
147
+ if (log.length) lastLine = log[log.length - 1];
148
+ };
149
+
150
+ const started = Date.now();
151
+ let current = deployment;
152
+ for (;;) {
153
+ printNew(current.log || []);
154
+ if (current.status === 'done') {
155
+ console.log(`\nPublished. Live at ${current.url}`);
156
+ return;
157
+ }
158
+ if (current.status === 'failed') {
159
+ throw new Error(`the publish failed: ${current.error || 'unknown error'}. Your live site is unchanged.`);
160
+ }
161
+ if (Date.now() - started > TIMEOUT_MS) {
162
+ throw new Error(`still ${current.status} after 20 minutes — check the Publish menu in the Prezense app.`);
163
+ }
164
+ await sleep(POLL_MS);
165
+ current = (await call(`${base}/v1/deployments/${encodeURIComponent(deployment.id)}`, { headers })).deployment;
166
+ }
167
+ }
168
+
169
+ // ── prezense upload ─────────────────────────────────────────────────────────
170
+
171
+ const DEFAULT_STORE_MCP_URL = 'https://mcp.prezense.app/mcp';
172
+ const MEDIA_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'mp4', 'mov', 'mp3', 'wav']);
173
+ const PARALLEL_UPLOADS = 3;
174
+ const STATUS_POLL_MS = 3000;
175
+ const PROCESSING_TIMEOUT_MS = 30 * 60 * 1000;
176
+
177
+ function parseUploadArgs(args) {
178
+ const paths = [];
179
+ let product = null;
180
+ let as = null;
181
+ for (let i = 0; i < args.length; i += 1) {
182
+ const arg = args[i];
183
+ const [flag, inline] = arg.startsWith('--') ? arg.split(/=(.*)/s) : [arg];
184
+ if (flag === '--product' || flag === '--as') {
185
+ const value = inline ?? args[++i];
186
+ if (!value) throw new Error(`${flag} needs a value`);
187
+ if (flag === '--product') product = value;
188
+ else as = value;
189
+ } else if (arg.startsWith('--')) {
190
+ throw new Error(`unknown option ${arg}`);
191
+ } else {
192
+ paths.push(arg);
193
+ }
194
+ }
195
+ if (as && as !== 'thumbnail' && as !== 'gallery') throw new Error('--as must be thumbnail or gallery');
196
+ if (as && !product) throw new Error('--as needs --product as well');
197
+ if (!paths.length) throw new Error('name at least one file or folder to upload');
198
+ return { paths, product, as };
199
+ }
200
+
201
+ const extOf = (file) => path.extname(file).slice(1).toLowerCase();
202
+
203
+ /* Files to send: each file named, and the media files directly inside each folder. */
204
+ function collectFiles(paths) {
205
+ const files = [];
206
+ for (const raw of paths) {
207
+ const full = path.resolve(raw);
208
+ if (!existsSync(full)) throw new Error(`${raw} doesn't exist`);
209
+ if (statSync(full).isDirectory()) {
210
+ const found = readdirSync(full)
211
+ .filter((name) => !name.startsWith('.') && MEDIA_EXTENSIONS.has(extOf(name)))
212
+ .map((name) => path.join(full, name))
213
+ .filter((file) => statSync(file).isFile())
214
+ .sort();
215
+ if (!found.length) console.log(`No images, videos or audio in ${raw}.`);
216
+ files.push(...found);
217
+ } else if (MEDIA_EXTENSIONS.has(extOf(full))) {
218
+ files.push(full);
219
+ } else {
220
+ throw new Error(`${raw} isn't a file type the media library takes (${[...MEDIA_EXTENSIONS].join(', ')})`);
221
+ }
222
+ }
223
+ return [...new Set(files)];
224
+ }
225
+
226
+ /* One MCP tool call over HTTP (JSON-RPC tools/call; the server is stateless).
227
+ The answer may come back as plain JSON or as one server-sent event. */
228
+ let rpcId = 0;
229
+ async function callTool(endpoint, headers, name, args) {
230
+ rpcId += 1;
231
+ const id = rpcId; // calls run in parallel, so each keeps its own id
232
+ let res;
233
+ try {
234
+ res = await fetch(endpoint, {
235
+ method: 'POST',
236
+ headers: { ...headers, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
237
+ body: JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } }),
238
+ });
239
+ } catch (err) {
240
+ throw new Error(`couldn't reach Prezense at ${endpoint} (${err.cause?.code || err.message})`);
241
+ }
242
+ const text = await res.text();
243
+ let message = null;
244
+ if ((res.headers.get('content-type') || '').includes('text/event-stream')) {
245
+ for (const line of text.split(/\r?\n/)) {
246
+ if (!line.startsWith('data:')) continue;
247
+ try {
248
+ const parsed = JSON.parse(line.slice(5));
249
+ if (parsed.id === id) message = parsed;
250
+ } catch { /* not JSON */ }
251
+ }
252
+ } else {
253
+ try { message = JSON.parse(text); } catch { /* below */ }
254
+ }
255
+ if (!message) throw new Error(`Prezense answered ${res.status} to ${name}`);
256
+ if (message.error) throw new Error(message.error.message || `${name} failed`);
257
+ const content = message.result?.content?.[0]?.text;
258
+ let body;
259
+ try { body = JSON.parse(content); } catch { body = { success: false, error: content || `${name} gave no answer` }; }
260
+ if (message.result?.isError && body.success !== false) body = { success: false, error: content };
261
+ return body;
262
+ }
263
+
264
+ /* PUTs a file to its upload link, reporting bytes sent. */
265
+ function putFile(url, file, size, contentType, onProgress) {
266
+ return new Promise((resolve, reject) => {
267
+ const target = new URL(url);
268
+ const request = (target.protocol === 'http:' ? http : https).request(target, {
269
+ method: 'PUT',
270
+ headers: { 'Content-Type': contentType, 'Content-Length': size },
271
+ }, (res) => {
272
+ let body = '';
273
+ res.on('data', (c) => { body += c; });
274
+ res.on('end', () => {
275
+ if (res.statusCode >= 200 && res.statusCode < 300) resolve();
276
+ else reject(new Error(`the upload was refused (HTTP ${res.statusCode}${/<Code>([^<]+)/.exec(body)?.[1] ? `, ${/<Code>([^<]+)/.exec(body)[1]}` : ''})`));
277
+ });
278
+ });
279
+ request.on('error', (err) => reject(new Error(`the upload failed (${err.code || err.message})`)));
280
+ let sent = 0;
281
+ const stream = createReadStream(file);
282
+ stream.on('data', (chunk) => {
283
+ sent += chunk.length;
284
+ onProgress(sent);
285
+ });
286
+ stream.on('error', (err) => request.destroy(err));
287
+ stream.pipe(request);
288
+ });
289
+ }
290
+
291
+ /* The per-file lines. On a terminal they are redrawn in place; otherwise each
292
+ change of stage is printed once. */
293
+ function progressBoard(names) {
294
+ const tty = process.stdout.isTTY;
295
+ const width = Math.min(40, Math.max(...names.map((n) => n.length)));
296
+ const rows = names.map(() => ({ text: 'waiting', bar: null, last: '' }));
297
+ let drawn = 0;
298
+ const bar = (pct) => {
299
+ const filled = Math.round((pct / 100) * 20);
300
+ return `[${'█'.repeat(filled)}${'░'.repeat(20 - filled)}] ${String(Math.round(pct)).padStart(3)}%`;
301
+ };
302
+ const line = (i) => {
303
+ const name = names[i].length > width ? `${names[i].slice(0, width - 1)}…` : names[i].padEnd(width);
304
+ const { text, bar: pct } = rows[i];
305
+ return ` ${name} ${pct === null ? '' : `${bar(pct)} `}${text}`;
306
+ };
307
+ const draw = () => {
308
+ if (!tty) return;
309
+ if (drawn) process.stdout.write(`\x1b[${drawn}A`);
310
+ for (let i = 0; i < rows.length; i += 1) process.stdout.write(`\x1b[2K${line(i)}\n`);
311
+ drawn = rows.length;
312
+ };
313
+ let timer = null;
314
+ return {
315
+ set(i, text, pct = null) {
316
+ rows[i].text = text;
317
+ rows[i].bar = pct;
318
+ if (tty) {
319
+ if (!timer) timer = setTimeout(() => { timer = null; draw(); }, 100);
320
+ } else if (rows[i].last !== text) {
321
+ rows[i].last = text;
322
+ console.log(line(i));
323
+ }
324
+ },
325
+ flush() {
326
+ if (timer) { clearTimeout(timer); timer = null; }
327
+ draw();
328
+ },
329
+ };
330
+ }
331
+
332
+ async function mapLimit(items, limit, fn) {
333
+ let next = 0;
334
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
335
+ while (next < items.length) {
336
+ const i = next++;
337
+ await fn(items[i], i);
338
+ }
339
+ });
340
+ await Promise.all(workers);
341
+ }
342
+
343
+ const CONTENT_TYPES = {
344
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp',
345
+ mp4: 'video/mp4', mov: 'video/quicktime', mp3: 'audio/mpeg', wav: 'audio/wav',
346
+ };
347
+
348
+ async function upload(args) {
349
+ const { paths, product, as } = parseUploadArgs(args);
350
+ const files = collectFiles(paths);
351
+ if (!files.length) throw new Error('nothing to upload');
352
+
353
+ const dir = process.cwd();
354
+ const apiKey = setting('PREZENSE_API_KEY', dir);
355
+ const platformKey = setting('PREZENSE_PLATFORM_KEY', dir);
356
+ if (!apiKey || !platformKey) {
357
+ throw new Error('PREZENSE_API_KEY and PREZENSE_PLATFORM_KEY are not set. Copy them into .env.local from Settings → Your own agents in the Prezense app.');
358
+ }
359
+ const endpoint = setting('PREZENSE_STORE_MCP_URL', dir) || DEFAULT_STORE_MCP_URL;
360
+ const headers = { 'x-api-key': apiKey, 'x-platform-key': platformKey };
361
+
362
+ console.log(`Uploading ${files.length} file${files.length === 1 ? '' : 's'} to store "${platformKey}"${product ? `, for product ${product}${as ? ` (${as})` : ''}` : ''}:`);
363
+ const names = files.map((f) => path.basename(f));
364
+ const board = progressBoard(names);
365
+ const results = files.map(() => ({ uploadId: null, done: false, url: null, error: null }));
366
+
367
+ await mapLimit(files, PARALLEL_UPLOADS, async (file, i) => {
368
+ const result = results[i];
369
+ try {
370
+ const size = statSync(file).size;
371
+ board.set(i, 'starting');
372
+ const started = await callTool(endpoint, headers, 'start_media_upload', {
373
+ file_name: file,
374
+ size_bytes: size,
375
+ content_type: CONTENT_TYPES[extOf(file)],
376
+ ...(product ? { product } : {}),
377
+ ...(as ? { as } : {}),
378
+ });
379
+ if (!started.success) throw new Error(started.error);
380
+ const { upload_id: uploadId, upload } = started.data;
381
+ result.uploadId = uploadId;
382
+ // The link is signed with this exact Content-Type; sending any
383
+ // other is refused by S3.
384
+ const contentType = upload.headers?.['Content-Type'] ?? CONTENT_TYPES[extOf(file)];
385
+ await putFile(upload.url, file, size, contentType, (sent) => {
386
+ board.set(i, 'uploading', (sent / size) * 100);
387
+ });
388
+ board.set(i, 'uploaded', 100);
389
+ const finished = await callTool(endpoint, headers, 'finish_media_upload', { upload_id: uploadId });
390
+ if (!finished.success) throw new Error(finished.error);
391
+ applyStatus(board, i, result, finished.data);
392
+ } catch (err) {
393
+ result.done = true;
394
+ result.error = err.message;
395
+ board.set(i, `failed: ${err.message}`);
396
+ }
397
+ });
398
+
399
+ // Videos and audio are processed after they arrive; wait for them.
400
+ const started = Date.now();
401
+ for (;;) {
402
+ const pending = results.map((r, i) => [r, i]).filter(([r]) => !r.done && r.uploadId);
403
+ if (!pending.length) break;
404
+ if (Date.now() - started > PROCESSING_TIMEOUT_MS) {
405
+ for (const [r, i] of pending) {
406
+ r.done = true;
407
+ board.set(i, 'still processing — check the Media page in the Prezense app');
408
+ }
409
+ break;
410
+ }
411
+ await sleep(STATUS_POLL_MS);
412
+ try {
413
+ const status = await callTool(endpoint, headers, 'get_media_upload_status', {
414
+ upload_ids: pending.map(([r]) => r.uploadId),
415
+ });
416
+ if (!status.success) throw new Error(status.error);
417
+ for (const u of status.data.uploads) {
418
+ const hit = pending.find(([r]) => r.uploadId === u.upload_id);
419
+ if (hit) applyStatus(board, hit[1], hit[0], u);
420
+ }
421
+ } catch (err) {
422
+ // A blip while polling isn't a failed upload; try again next round.
423
+ if (process.env.DEBUG) console.error(err.message);
424
+ }
425
+ }
426
+ board.flush();
427
+
428
+ const failed = results.filter((r) => r.error).length;
429
+ console.log('');
430
+ results.forEach((r, i) => {
431
+ if (r.url) console.log(` ${names[i]} → ${r.url}`);
432
+ });
433
+ console.log(failed
434
+ ? `\n${files.length - failed} of ${files.length} done; ${failed} failed.`
435
+ : `\nDone: ${files.length} file${files.length === 1 ? '' : 's'} in the media library.`);
436
+ if (failed) process.exitCode = 1;
437
+ }
438
+
439
+ function applyStatus(board, i, result, data) {
440
+ switch (data.stage) {
441
+ case 'completed':
442
+ result.done = true;
443
+ result.url = data.url;
444
+ board.set(i, 'done', 100);
445
+ break;
446
+ case 'failed':
447
+ result.done = true;
448
+ result.error = data.message || data.reason;
449
+ board.set(i, `failed: ${data.message || data.reason}`);
450
+ break;
451
+ case 'processing':
452
+ board.set(i, 'processing', Number(data.percent) || 0);
453
+ break;
454
+ case 'file_received':
455
+ board.set(i, 'uploaded, waiting to process', 100);
456
+ break;
457
+ case 'waiting_for_file':
458
+ board.set(i, 'waiting for the file to arrive');
459
+ break;
460
+ default:
461
+ result.done = true;
462
+ result.error = data.error || 'unknown upload';
463
+ board.set(i, `failed: ${result.error}`);
464
+ }
465
+ }
466
+
467
+ const [command, ...rest] = process.argv.slice(2);
468
+ if (command === 'deploy') {
469
+ deploy(rest[0]).catch((err) => {
470
+ console.error(`\nprezense deploy: ${err.message}`);
471
+ process.exit(1);
472
+ });
473
+ } else if (command === 'upload' && !rest.some((a) => a === '--help' || a === '-h')) {
474
+ upload(rest).catch((err) => {
475
+ console.error(`\nprezense upload: ${err.message}`);
476
+ process.exit(1);
477
+ });
478
+ } else if (command === 'upload') {
479
+ console.log(HELP);
480
+ } else {
481
+ console.log(HELP);
482
+ process.exit(command && command !== 'help' && command !== '--help' && command !== '-h' ? 1 : 0);
483
+ }
package/collections.js ADDED
@@ -0,0 +1,30 @@
1
+ import { operation, text, number } from './graphql.js';
2
+
3
+ // A store's own collections (hand-picked or imported from another platform),
4
+ // each with its products in the collection's order. Storefront route:
5
+ // /collections/<handle>. Only published collections are returned.
6
+ //
7
+ // Not to be confused with products.collectionProducts, which filters products
8
+ // by the free-text `collection` field on each product.
9
+
10
+ export class Collections {
11
+ constructor(client) {
12
+ this.client = client;
13
+ }
14
+
15
+ /** Every published collection, A–Z. `data` selects Collection fields. */
16
+ async allCollections({ data, limit, offset }) {
17
+ const args = { limit: ['Int', number(limit)], offset: ['Int', number(offset)] };
18
+ return this.client.sendRequest(operation('query', 'getCollections', args, data), 'getCollections');
19
+ }
20
+
21
+ /** One collection by handle. Select `products { … }` in `data` for its products. */
22
+ async collection({ handle, data, limit, offset }) {
23
+ const args = {
24
+ handle: ['String!', text(handle)],
25
+ limit: ['Int', number(limit)],
26
+ offset: ['Int', number(offset)],
27
+ };
28
+ return this.client.sendRequest(operation('query', 'getCollection', args, data), 'getCollection');
29
+ }
30
+ }
package/currency.js ADDED
@@ -0,0 +1,95 @@
1
+ import { operation, text, number } from './graphql.js';
2
+
3
+ export class Currency {
4
+ constructor(client) {
5
+ this.client = client;
6
+ }
7
+
8
+ /**
9
+ * Detect the customer's currency based on their IP address.
10
+ * Requires X-Currency: auto header (set via currency: 'auto' in constructor)
11
+ * or X-Forwarded-For / X-Real-IP headers for GeoIP detection.
12
+ */
13
+ async detect() {
14
+ const query = `query {
15
+ detectCurrency {
16
+ detected
17
+ currency
18
+ country
19
+ source
20
+ }
21
+ }`;
22
+ return this.client.sendRequest({ query }, 'detectCurrency');
23
+ }
24
+
25
+ /**
26
+ * Get current exchange rates for a base currency.
27
+ * @param {Object} options
28
+ * @param {string} [options.baseCurrency] - Base currency code (defaults to merchant's base currency)
29
+ */
30
+ async rates({ baseCurrency } = {}) {
31
+ // Values go in as GraphQL variables, never spliced into the query text.
32
+ const args = { baseCurrency: ['String', text(baseCurrency || undefined)] };
33
+ const selection = `
34
+ baseCurrency
35
+ targetCurrency
36
+ rate
37
+ `;
38
+ return this.client.sendRequest(operation('query', 'getExchangeRates', args, selection), 'getExchangeRates');
39
+ }
40
+
41
+ /**
42
+ * Convert a specific price between two currencies.
43
+ * @param {Object} options
44
+ * @param {number} options.amount - Amount to convert
45
+ * @param {string} options.from - Source currency code
46
+ * @param {string} options.to - Target currency code
47
+ */
48
+ async convert({ amount, from, to }) {
49
+ const args = {
50
+ amount: ['Float!', number(amount)],
51
+ fromCurrency: ['String!', text(from)],
52
+ toCurrency: ['String!', text(to)],
53
+ };
54
+ const selection = `
55
+ originalAmount
56
+ convertedAmount
57
+ roundedAmount
58
+ fromCurrency
59
+ toCurrency
60
+ rate
61
+ `;
62
+ return this.client.sendRequest(operation('query', 'convertPrice', args, selection), 'convertPrice');
63
+ }
64
+
65
+ /**
66
+ * Get all currency codes supported by the platform's exchange rate service.
67
+ */
68
+ async supported() {
69
+ const query = `query {
70
+ getSupportedCurrencies
71
+ }`;
72
+ return this.client.sendRequest({ query }, 'getSupportedCurrencies');
73
+ }
74
+
75
+ /**
76
+ * Get the merchant's currency settings.
77
+ */
78
+ async settings() {
79
+ const query = `query {
80
+ getCurrencySettings {
81
+ baseCurrency
82
+ multiCurrencyEnabled
83
+ conversionMode
84
+ priceRounding
85
+ roundingDirection
86
+ supportedCurrencies {
87
+ currencyCode
88
+ manualRate
89
+ enabled
90
+ }
91
+ }
92
+ }`;
93
+ return this.client.sendRequest({ query }, 'getCurrencySettings');
94
+ }
95
+ }
package/fraud.js ADDED
@@ -0,0 +1,47 @@
1
+ import { operation, text } from './graphql.js';
2
+
3
+ export class Fraud {
4
+ constructor(client) {
5
+ this.client = client;
6
+ }
7
+
8
+ // Every value goes in as a GraphQL variable, never spliced into the query
9
+ // text — cart ids and codes come from the shopper's request.
10
+
11
+ /**
12
+ * Assess the fraud risk of a cart before authorizing payment.
13
+ */
14
+ async assessCartFraudRisk({ cartID, data }) {
15
+ const args = { cartID: ['String!', text(cartID)] };
16
+ return this.client.sendRequest(operation('query', 'assessCartFraudRisk', args, data), 'assessCartFraudRisk');
17
+ }
18
+
19
+ /**
20
+ * Issue an email OTP fraud challenge for the cart. The code is emailed to
21
+ * the cart's customer email; the response carries only a masked hint.
22
+ */
23
+ async issueFraudChallenge({ cartID, data }) {
24
+ const args = { cartID: ['String!', text(cartID)] };
25
+ return this.client.sendRequest(operation('mutation', 'issueFraudChallenge', args, data), 'issueFraudChallenge');
26
+ }
27
+
28
+ /**
29
+ * Verify a previously issued fraud challenge code.
30
+ */
31
+ async verifyFraudChallenge({ cartID, code, data }) {
32
+ const args = { cartID: ['String!', text(cartID)], code: ['String!', text(code)] };
33
+ return this.client.sendRequest(operation('mutation', 'verifyFraudChallenge', args, data), 'verifyFraudChallenge');
34
+ }
35
+
36
+ /**
37
+ * Report a Stripe chargeback against an order. Pushes high-confidence
38
+ * entries to the shared fraud blocklist.
39
+ */
40
+ async reportChargeback({ order_id, stripe_charge_id, data }) {
41
+ const args = {
42
+ orderId: ['String!', text(order_id)],
43
+ stripeChargeId: ['String', text(stripe_charge_id)],
44
+ };
45
+ return this.client.sendRequest(operation('mutation', 'reportChargeback', args, data), 'reportChargeback');
46
+ }
47
+ }