@gibwork/sdk 0.0.1

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,788 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var sanitizeHtml = require('sanitize-html');
5
+ var web3_js = require('@solana/web3.js');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var sanitizeHtml__default = /*#__PURE__*/_interopDefault(sanitizeHtml);
10
+
11
+ // src/config.ts
12
+ var FALLBACK_GIBWORK_API_URL = "https://sdk.gib.work";
13
+ var DEFAULT_GIBWORK_API_URL = "https://sdk.gib.work"?.trim() || FALLBACK_GIBWORK_API_URL;
14
+
15
+ // src/errors/index.ts
16
+ var GibworkError = class extends Error {
17
+ name = "GibworkError";
18
+ };
19
+ var GibworkConfigurationError = class extends GibworkError {
20
+ name = "GibworkConfigurationError";
21
+ };
22
+ var GibworkApiError = class extends GibworkError {
23
+ constructor(status, body, method, path, requestId) {
24
+ super(`Gibwork API request failed with HTTP ${status}`);
25
+ this.status = status;
26
+ this.body = body;
27
+ this.method = method;
28
+ this.path = path;
29
+ this.requestId = requestId;
30
+ }
31
+ status;
32
+ body;
33
+ method;
34
+ path;
35
+ requestId;
36
+ name = "GibworkApiError";
37
+ };
38
+ var GibworkNetworkError = class extends GibworkError {
39
+ constructor(message, method, path, options) {
40
+ super(message, options);
41
+ this.method = method;
42
+ this.path = path;
43
+ }
44
+ method;
45
+ path;
46
+ name = "GibworkNetworkError";
47
+ };
48
+ var GibworkTimeoutError = class extends GibworkNetworkError {
49
+ constructor(method, path, timeoutMs, options) {
50
+ super(
51
+ `Gibwork API request timed out after ${timeoutMs}ms`,
52
+ method,
53
+ path,
54
+ options
55
+ );
56
+ this.timeoutMs = timeoutMs;
57
+ }
58
+ timeoutMs;
59
+ name = "GibworkTimeoutError";
60
+ };
61
+ var GibworkRequestAbortedError = class extends GibworkNetworkError {
62
+ name = "GibworkRequestAbortedError";
63
+ constructor(method, path, options) {
64
+ super("Gibwork API request was aborted", method, path, options);
65
+ }
66
+ };
67
+ var GibworkAmbiguousSubmitError = class extends GibworkNetworkError {
68
+ constructor(method, path, context, options) {
69
+ super(
70
+ "The transaction submit outcome is unknown; do not submit the same intent again",
71
+ method,
72
+ path,
73
+ options
74
+ );
75
+ this.context = context;
76
+ }
77
+ context;
78
+ name = "GibworkAmbiguousSubmitError";
79
+ };
80
+ var HTML_SANITIZE_OPTIONS = {
81
+ allowedTags: sanitizeHtml__default.default.defaults.allowedTags.concat(["img"]),
82
+ allowedAttributes: {
83
+ ...sanitizeHtml__default.default.defaults.allowedAttributes,
84
+ "*": ["class", "id", "style", "data-type"],
85
+ a: ["href", "name", "target"],
86
+ img: [
87
+ "src",
88
+ "srcset",
89
+ "alt",
90
+ "title",
91
+ "limit",
92
+ "width",
93
+ "height",
94
+ "loading",
95
+ "maxSize",
96
+ "fileid"
97
+ ]
98
+ },
99
+ transformTags: {
100
+ a: (tagName, attributes) => {
101
+ if (isAllowedExternalUrl(attributes.href)) {
102
+ return { tagName, attribs: attributes };
103
+ }
104
+ const safeAttributes = { ...attributes };
105
+ delete safeAttributes.href;
106
+ return { tagName: "span", attribs: safeAttributes };
107
+ }
108
+ }
109
+ };
110
+ function sanitizeContent(content) {
111
+ return sanitizeHtml__default.default(content, HTML_SANITIZE_OPTIONS).trim();
112
+ }
113
+ function isAllowedExternalUrl(value) {
114
+ if (!value) return false;
115
+ const normalized = value.toLowerCase().startsWith("www.") ? `https://${value}` : value;
116
+ try {
117
+ const url = new URL(normalized);
118
+ return (url.protocol === "http:" || url.protocol === "https:") && Boolean(url.hostname) && !url.username && !url.password;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ // src/auth/normalize.ts
125
+ function normalizeCreateTask(input, walletAddress) {
126
+ const normalized = {
127
+ walletAddress: walletAddress.trim(),
128
+ title: input.title.trim(),
129
+ content: sanitizeContent(input.content),
130
+ tags: input.tags.map((tag) => tag.trim()),
131
+ payment: {
132
+ mintAddress: input.payment.mintAddress.trim(),
133
+ amount: input.payment.amount.trim()
134
+ },
135
+ minSubmissionAmount: input.minSubmissionAmount.trim(),
136
+ deadline: input.deadline ?? null,
137
+ allowOnlyVerifiedSubmissions: input.allowOnlyVerifiedSubmissions ?? false
138
+ };
139
+ const primarySkillSlug = trimOptional(input.primarySkillSlug)?.toLowerCase();
140
+ if (primarySkillSlug !== void 0 && primarySkillSlug !== null) {
141
+ normalized.primarySkillSlug = primarySkillSlug;
142
+ }
143
+ if (input.refundFeeOverride !== void 0 && input.refundFeeOverride !== null) {
144
+ normalized.refundFeeOverride = input.refundFeeOverride;
145
+ }
146
+ if (input.allowOnlyDiscordGuildSubmissions !== void 0) {
147
+ normalized.allowOnlyDiscordGuildSubmissions = input.allowOnlyDiscordGuildSubmissions;
148
+ }
149
+ const requiredDiscordGuildId = trimOptional(input.requiredDiscordGuildId);
150
+ if (requiredDiscordGuildId !== void 0) {
151
+ normalized.requiredDiscordGuildId = requiredDiscordGuildId;
152
+ }
153
+ const requiredDiscordGuildName = trimOptional(input.requiredDiscordGuildName);
154
+ if (requiredDiscordGuildName !== void 0) {
155
+ normalized.requiredDiscordGuildName = requiredDiscordGuildName;
156
+ }
157
+ const discordGuildInvitationUrl = trimOptional(
158
+ input.discordGuildInvitationUrl
159
+ );
160
+ if (discordGuildInvitationUrl !== void 0) {
161
+ normalized.discordGuildInvitationUrl = discordGuildInvitationUrl;
162
+ }
163
+ if (input.requiredDiscordRoleIds !== void 0) {
164
+ const roles = input.requiredDiscordRoleIds.map((role) => role.trim()).filter(Boolean);
165
+ if (roles.length > 0) normalized.requiredDiscordRoleIds = roles;
166
+ }
167
+ return normalized;
168
+ }
169
+ function normalizeTaskPagination(query = {}) {
170
+ return {
171
+ page: query.page ?? 1,
172
+ limit: query.limit ?? 15,
173
+ pageAll: query.pageAll ?? false
174
+ };
175
+ }
176
+ function normalizeSubmissionPagination(query = {}) {
177
+ return {
178
+ page: query.page ?? 1,
179
+ limit: query.limit ?? 15,
180
+ pageAll: query.pageAll ?? false,
181
+ status: query.status ?? null
182
+ };
183
+ }
184
+ function normalizeApproval(input, walletAddress) {
185
+ const normalized = {
186
+ walletAddress,
187
+ amount: input.amount.trim()
188
+ };
189
+ if (input.rating !== void 0) normalized.rating = input.rating;
190
+ return normalized;
191
+ }
192
+ function normalizeRejection(reason, walletAddress) {
193
+ return {
194
+ walletAddress,
195
+ rejectReason: typeof reason === "string" ? reason.trim() : reason ?? null
196
+ };
197
+ }
198
+ function normalizeComment(content, walletAddress) {
199
+ return {
200
+ walletAddress,
201
+ content: sanitizeContent(content)
202
+ };
203
+ }
204
+ function sha256Json(value) {
205
+ return crypto.createHash("sha256").update(JSON.stringify(value), "utf8").digest("hex");
206
+ }
207
+ function toQueryString(values) {
208
+ const query = new URLSearchParams();
209
+ for (const [key, value] of Object.entries(values)) {
210
+ if (value !== void 0 && value !== null) query.set(key, String(value));
211
+ }
212
+ return query.toString();
213
+ }
214
+ function trimOptional(value) {
215
+ if (typeof value !== "string") return value;
216
+ const trimmed = value.trim();
217
+ return trimmed === "" ? void 0 : trimmed;
218
+ }
219
+ async function createWalletAuthHeaders(signer, descriptor, dependencies = {}) {
220
+ const values = {
221
+ walletAddress: signer.publicKey.toBase58(),
222
+ timestamp: Math.floor(
223
+ (dependencies.now?.() ?? Date.now()) / 1e3
224
+ ).toString(),
225
+ nonce: dependencies.nonce?.() ?? crypto.randomUUID()
226
+ };
227
+ const message = buildWalletAuthMessage(descriptor, values);
228
+ const signature = await signer.signMessage(new TextEncoder().encode(message));
229
+ if (!(signature instanceof Uint8Array) || signature.length !== 64) {
230
+ throw new GibworkConfigurationError(
231
+ "WalletSigner.signMessage must return a 64-byte Ed25519 signature"
232
+ );
233
+ }
234
+ return {
235
+ "x-gibwork-wallet-address": values.walletAddress,
236
+ "x-gibwork-timestamp": values.timestamp,
237
+ "x-gibwork-nonce": values.nonce,
238
+ "x-gibwork-signature": Buffer.from(signature).toString("base64")
239
+ };
240
+ }
241
+ function buildWalletAuthMessage(descriptor, values) {
242
+ return [
243
+ descriptor.operation,
244
+ `method:${descriptor.method}`,
245
+ `path:${descriptor.path}`,
246
+ ...(descriptor.resourceFields ?? []).map(
247
+ ([name, value]) => `${name}:${value}`
248
+ ),
249
+ `walletAddress:${values.walletAddress}`,
250
+ `timestamp:${values.timestamp}`,
251
+ `nonce:${values.nonce}`,
252
+ `${descriptor.hash[0]}:${descriptor.hash[1]}`
253
+ ].join("\n");
254
+ }
255
+ async function signPreparedTransaction(serializedTransaction, signer) {
256
+ if (typeof serializedTransaction !== "string" || !serializedTransaction) {
257
+ throw new GibworkConfigurationError(
258
+ "serializedTransaction must be a non-empty base64 string"
259
+ );
260
+ }
261
+ let transaction;
262
+ try {
263
+ transaction = web3_js.VersionedTransaction.deserialize(
264
+ Buffer.from(serializedTransaction, "base64")
265
+ );
266
+ } catch (cause) {
267
+ throw new GibworkConfigurationError(
268
+ "serializedTransaction is not a valid Solana VersionedTransaction",
269
+ { cause }
270
+ );
271
+ }
272
+ const signed = await signer.signTransaction(transaction);
273
+ if (!(signed instanceof web3_js.VersionedTransaction)) {
274
+ throw new GibworkConfigurationError(
275
+ "WalletSigner.signTransaction must return a VersionedTransaction"
276
+ );
277
+ }
278
+ return Buffer.from(signed.serialize()).toString("base64");
279
+ }
280
+
281
+ // src/resources/submissions/submission-comments-resource.ts
282
+ var SubmissionCommentsResource = class {
283
+ constructor(transport, signer) {
284
+ this.transport = transport;
285
+ this.signer = signer;
286
+ }
287
+ transport;
288
+ signer;
289
+ async list(taskId, submissionId, options) {
290
+ const path = commentsPath(taskId, submissionId);
291
+ const headers = await createWalletAuthHeaders(this.signer, {
292
+ operation: "gibwork:view-task-submission-comments",
293
+ method: "GET",
294
+ path,
295
+ resourceFields: [
296
+ ["taskId", taskId],
297
+ ["taskSubmissionId", submissionId]
298
+ ],
299
+ hash: ["queryHash", sha256Json({})]
300
+ });
301
+ return this.transport.request({
302
+ method: "GET",
303
+ path,
304
+ headers,
305
+ ...options ? { options } : {}
306
+ });
307
+ }
308
+ async create(taskId, submissionId, content, options) {
309
+ const path = commentsPath(taskId, submissionId);
310
+ const body = normalizeComment(content, this.signer.publicKey.toBase58());
311
+ const headers = await createWalletAuthHeaders(this.signer, {
312
+ operation: "gibwork:create-task-submission-comment",
313
+ method: "POST",
314
+ path,
315
+ resourceFields: [
316
+ ["taskId", taskId],
317
+ ["taskSubmissionId", submissionId]
318
+ ],
319
+ hash: ["payloadHash", sha256Json(body)]
320
+ });
321
+ return this.transport.request({
322
+ method: "POST",
323
+ path,
324
+ headers,
325
+ body,
326
+ ...options ? { options } : {}
327
+ });
328
+ }
329
+ };
330
+ function commentsPath(taskId, submissionId) {
331
+ return `/v2/int/tasks/${encodeURIComponent(taskId)}/submission/${encodeURIComponent(submissionId)}/comments`;
332
+ }
333
+
334
+ // src/resources/submissions/submissions-resource.ts
335
+ var SubmissionsResource = class {
336
+ constructor(transport, signer) {
337
+ this.transport = transport;
338
+ this.signer = signer;
339
+ this.comments = new SubmissionCommentsResource(transport, signer);
340
+ }
341
+ transport;
342
+ signer;
343
+ comments;
344
+ async list(taskId, query = {}, options) {
345
+ const normalized = normalizeSubmissionPagination(query);
346
+ const path = `/v2/int/tasks/${encodeURIComponent(taskId)}/submissions`;
347
+ const headers = await createWalletAuthHeaders(this.signer, {
348
+ operation: "gibwork:view-task-submissions",
349
+ method: "GET",
350
+ path,
351
+ resourceFields: [["taskId", taskId]],
352
+ hash: ["queryHash", sha256Json(normalized)]
353
+ });
354
+ const requestQuery = { ...normalized };
355
+ if (requestQuery.status === null) delete requestQuery.status;
356
+ return this.transport.request({
357
+ method: "GET",
358
+ path: `${path}?${toQueryString(requestQuery)}`,
359
+ headers,
360
+ ...options ? { options } : {}
361
+ });
362
+ }
363
+ async approve(taskId, submissionId, input, options) {
364
+ const prepared = await this.prepareApproval(
365
+ taskId,
366
+ submissionId,
367
+ input,
368
+ options
369
+ );
370
+ const submitPath = approvalSubmitPath(
371
+ taskId,
372
+ submissionId,
373
+ prepared.intentId
374
+ );
375
+ assertNotAborted(options, submitPath);
376
+ const signedTransaction = await signPreparedTransaction(
377
+ prepared.serializedTransaction,
378
+ this.signer
379
+ );
380
+ assertNotAborted(options, submitPath);
381
+ const submitted = await this.submitApproval(
382
+ taskId,
383
+ submissionId,
384
+ prepared.intentId,
385
+ signedTransaction,
386
+ options
387
+ );
388
+ return {
389
+ ...submitted,
390
+ intentId: prepared.intentId,
391
+ lastValidBlockHeight: prepared.lastValidBlockHeight,
392
+ approvalQuote: prepared.approvalQuote
393
+ };
394
+ }
395
+ async reject(taskId, submissionId, reason, options) {
396
+ const path = `/v2/int/tasks/${encodeURIComponent(taskId)}/submission/${encodeURIComponent(submissionId)}/reject`;
397
+ const body = normalizeRejection(reason, this.walletAddress);
398
+ const headers = await createWalletAuthHeaders(this.signer, {
399
+ operation: "gibwork:reject-task-submission",
400
+ method: "POST",
401
+ path,
402
+ resourceFields: [
403
+ ["taskId", taskId],
404
+ ["taskSubmissionId", submissionId]
405
+ ],
406
+ hash: ["payloadHash", sha256Json(body)]
407
+ });
408
+ return this.transport.request({
409
+ method: "POST",
410
+ path,
411
+ headers,
412
+ body,
413
+ ...options ? { options } : {}
414
+ });
415
+ }
416
+ async prepareApproval(taskId, submissionId, input, options) {
417
+ const path = `/v2/int/tasks/${encodeURIComponent(taskId)}/submission/${encodeURIComponent(submissionId)}/pay`;
418
+ const body = normalizeApproval(input, this.walletAddress);
419
+ const headers = await createWalletAuthHeaders(this.signer, {
420
+ operation: "gibwork:approve-task-submission-intent",
421
+ method: "POST",
422
+ path,
423
+ resourceFields: [
424
+ ["taskId", taskId],
425
+ ["taskSubmissionId", submissionId]
426
+ ],
427
+ hash: ["payloadHash", sha256Json(body)]
428
+ });
429
+ return this.transport.request({
430
+ method: "POST",
431
+ path,
432
+ headers,
433
+ body,
434
+ ...options ? { options } : {}
435
+ });
436
+ }
437
+ async submitApproval(taskId, submissionId, intentId, signedTransaction, options) {
438
+ const path = approvalSubmitPath(taskId, submissionId, intentId);
439
+ return this.transport.request({
440
+ method: "POST",
441
+ path,
442
+ body: { signedTransaction },
443
+ ...options ? { options } : {},
444
+ ambiguousSubmit: {
445
+ operation: "approve-submission",
446
+ taskId,
447
+ submissionId,
448
+ intentId
449
+ }
450
+ });
451
+ }
452
+ get walletAddress() {
453
+ return this.signer.publicKey.toBase58();
454
+ }
455
+ };
456
+ function approvalSubmitPath(taskId, submissionId, intentId) {
457
+ return `/v2/int/tasks/${encodeURIComponent(taskId)}/submission/${encodeURIComponent(submissionId)}/pay/${encodeURIComponent(intentId)}/submit`;
458
+ }
459
+ function assertNotAborted(options, path) {
460
+ if (options?.signal?.aborted) {
461
+ throw new GibworkRequestAbortedError("POST", path, {
462
+ cause: options.signal.reason
463
+ });
464
+ }
465
+ }
466
+
467
+ // src/resources/tasks/tasks-resource.ts
468
+ var TasksResource = class {
469
+ constructor(transport, signer) {
470
+ this.transport = transport;
471
+ this.signer = signer;
472
+ }
473
+ transport;
474
+ signer;
475
+ async create(input, options) {
476
+ const prepared = await this.prepareCreate(input, options);
477
+ assertNotAborted2(options, "/v2/int/tasks");
478
+ const signedTransaction = await signPreparedTransaction(
479
+ prepared.serializedTransaction,
480
+ this.signer
481
+ );
482
+ assertNotAborted2(
483
+ options,
484
+ `/v2/int/tasks/${encodeURIComponent(prepared.intentId)}/submit`
485
+ );
486
+ const submitted = await this.submitCreate(
487
+ prepared.intentId,
488
+ signedTransaction,
489
+ options
490
+ );
491
+ return {
492
+ ...submitted,
493
+ intentId: prepared.intentId,
494
+ lastValidBlockHeight: prepared.lastValidBlockHeight,
495
+ paymentQuote: prepared.paymentQuote
496
+ };
497
+ }
498
+ async list(query = {}, options) {
499
+ const normalized = normalizeTaskPagination(query);
500
+ const path = "/v2/int/tasks";
501
+ const headers = await this.auth({
502
+ operation: "gibwork:view-created-tasks",
503
+ method: "GET",
504
+ path,
505
+ hash: ["queryHash", sha256Json(normalized)]
506
+ });
507
+ return this.transport.request({
508
+ method: "GET",
509
+ path: `${path}?${toQueryString(normalized)}`,
510
+ headers,
511
+ ...options ? { options } : {}
512
+ });
513
+ }
514
+ async refund(taskId, options) {
515
+ const prepared = await this.prepareRefund(taskId, options);
516
+ const submitPath = `/v2/int/tasks/${encodeURIComponent(taskId)}/refund/${encodeURIComponent(prepared.intentId)}/submit`;
517
+ assertNotAborted2(options, submitPath);
518
+ const signedTransaction = await signPreparedTransaction(
519
+ prepared.serializedTransaction,
520
+ this.signer
521
+ );
522
+ assertNotAborted2(options, submitPath);
523
+ const submitted = await this.submitRefund(
524
+ taskId,
525
+ prepared.intentId,
526
+ signedTransaction,
527
+ options
528
+ );
529
+ return {
530
+ ...submitted,
531
+ intentId: prepared.intentId,
532
+ lastValidBlockHeight: prepared.lastValidBlockHeight,
533
+ refundQuote: prepared.refundQuote
534
+ };
535
+ }
536
+ async prepareCreate(input, options) {
537
+ const path = "/v2/int/tasks";
538
+ const body = normalizeCreateTask(input, this.walletAddress);
539
+ const headers = await this.auth({
540
+ operation: "gibwork:create-task-intent",
541
+ method: "POST",
542
+ path,
543
+ hash: ["payloadHash", sha256Json(body)]
544
+ });
545
+ return this.transport.request({
546
+ method: "POST",
547
+ path,
548
+ headers,
549
+ body,
550
+ ...options ? { options } : {}
551
+ });
552
+ }
553
+ async submitCreate(intentId, signedTransaction, options) {
554
+ const path = `/v2/int/tasks/${encodeURIComponent(intentId)}/submit`;
555
+ return this.transport.request({
556
+ method: "POST",
557
+ path,
558
+ body: { signedTransaction },
559
+ ...options ? { options } : {},
560
+ ambiguousSubmit: {
561
+ operation: "create-task",
562
+ intentId
563
+ }
564
+ });
565
+ }
566
+ async prepareRefund(taskId, options) {
567
+ const path = `/v2/int/tasks/${encodeURIComponent(taskId)}/refund`;
568
+ const body = { walletAddress: this.walletAddress };
569
+ const headers = await this.auth({
570
+ operation: "gibwork:refund-task-intent",
571
+ method: "POST",
572
+ path,
573
+ resourceFields: [["taskId", taskId]],
574
+ hash: ["payloadHash", sha256Json(body)]
575
+ });
576
+ return this.transport.request({
577
+ method: "POST",
578
+ path,
579
+ headers,
580
+ body,
581
+ ...options ? { options } : {}
582
+ });
583
+ }
584
+ async submitRefund(taskId, intentId, signedTransaction, options) {
585
+ const path = `/v2/int/tasks/${encodeURIComponent(taskId)}/refund/${encodeURIComponent(intentId)}/submit`;
586
+ return this.transport.request({
587
+ method: "POST",
588
+ path,
589
+ body: { signedTransaction },
590
+ ...options ? { options } : {},
591
+ ambiguousSubmit: {
592
+ operation: "refund-task",
593
+ taskId,
594
+ intentId
595
+ }
596
+ });
597
+ }
598
+ get walletAddress() {
599
+ return this.signer.publicKey.toBase58();
600
+ }
601
+ auth(descriptor) {
602
+ return createWalletAuthHeaders(this.signer, descriptor);
603
+ }
604
+ };
605
+ function assertNotAborted2(options, path) {
606
+ if (options?.signal?.aborted) {
607
+ throw new GibworkRequestAbortedError("POST", path, {
608
+ cause: options.signal.reason
609
+ });
610
+ }
611
+ }
612
+
613
+ // src/transport/http-transport.ts
614
+ var HttpTransport = class {
615
+ baseUrl;
616
+ fetchImplementation;
617
+ timeoutMs;
618
+ constructor(options) {
619
+ this.baseUrl = normalizeBaseUrl(options.baseUrl);
620
+ this.fetchImplementation = options.fetch ?? globalThis.fetch;
621
+ this.timeoutMs = options.timeoutMs ?? 6e4;
622
+ if (typeof this.fetchImplementation !== "function") {
623
+ throw new GibworkConfigurationError(
624
+ "A fetch implementation is required in this environment"
625
+ );
626
+ }
627
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
628
+ throw new GibworkConfigurationError(
629
+ "timeoutMs must be a positive number"
630
+ );
631
+ }
632
+ }
633
+ async request(request) {
634
+ const controller = new AbortController();
635
+ const callerSignal = request.options?.signal;
636
+ let timedOut = false;
637
+ if (callerSignal?.aborted) {
638
+ throw new GibworkRequestAbortedError(request.method, request.path, {
639
+ cause: callerSignal.reason
640
+ });
641
+ }
642
+ const abortFromCaller = () => controller.abort(callerSignal?.reason);
643
+ callerSignal?.addEventListener("abort", abortFromCaller, { once: true });
644
+ const timeout = setTimeout(() => {
645
+ timedOut = true;
646
+ controller.abort();
647
+ }, this.timeoutMs);
648
+ const headers = {
649
+ accept: "application/json",
650
+ ...request.headers
651
+ };
652
+ const init = {
653
+ method: request.method,
654
+ headers,
655
+ signal: controller.signal
656
+ };
657
+ if (request.body !== void 0) {
658
+ headers["content-type"] = "application/json";
659
+ init.body = JSON.stringify(request.body);
660
+ }
661
+ let response;
662
+ try {
663
+ response = await this.fetchImplementation(
664
+ `${this.baseUrl}${request.path}`,
665
+ init
666
+ );
667
+ } catch (cause) {
668
+ if (request.ambiguousSubmit) {
669
+ throw new GibworkAmbiguousSubmitError(
670
+ request.method,
671
+ request.path,
672
+ request.ambiguousSubmit,
673
+ { cause }
674
+ );
675
+ }
676
+ if (timedOut) {
677
+ throw new GibworkTimeoutError(
678
+ request.method,
679
+ request.path,
680
+ this.timeoutMs,
681
+ { cause }
682
+ );
683
+ }
684
+ if (callerSignal?.aborted) {
685
+ throw new GibworkRequestAbortedError(request.method, request.path, {
686
+ cause
687
+ });
688
+ }
689
+ throw new GibworkNetworkError(
690
+ "Could not reach the Gibwork API",
691
+ request.method,
692
+ request.path,
693
+ { cause }
694
+ );
695
+ } finally {
696
+ clearTimeout(timeout);
697
+ callerSignal?.removeEventListener("abort", abortFromCaller);
698
+ }
699
+ const body = await parseResponseBody(response);
700
+ if (!response.ok) {
701
+ const requestId = response.headers.get("x-request-id") ?? void 0;
702
+ const apiError = new GibworkApiError(
703
+ response.status,
704
+ body,
705
+ request.method,
706
+ request.path,
707
+ requestId
708
+ );
709
+ if (request.ambiguousSubmit && response.status >= 500) {
710
+ throw new GibworkAmbiguousSubmitError(
711
+ request.method,
712
+ request.path,
713
+ request.ambiguousSubmit,
714
+ { cause: apiError }
715
+ );
716
+ }
717
+ throw apiError;
718
+ }
719
+ return body;
720
+ }
721
+ };
722
+ function normalizeBaseUrl(value) {
723
+ if (typeof value !== "string" || !value.trim()) {
724
+ throw new GibworkConfigurationError("baseUrl is required");
725
+ }
726
+ let url;
727
+ try {
728
+ url = new URL(value.trim());
729
+ } catch (cause) {
730
+ throw new GibworkConfigurationError("baseUrl must be a valid URL", {
731
+ cause
732
+ });
733
+ }
734
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
735
+ throw new GibworkConfigurationError("baseUrl must use http or https");
736
+ }
737
+ if (url.search || url.hash) {
738
+ throw new GibworkConfigurationError(
739
+ "baseUrl must not include a query string or fragment"
740
+ );
741
+ }
742
+ return url.toString().replace(/\/+$/, "");
743
+ }
744
+ async function parseResponseBody(response) {
745
+ const text = await response.text();
746
+ if (!text) return void 0;
747
+ try {
748
+ return JSON.parse(text);
749
+ } catch {
750
+ return text;
751
+ }
752
+ }
753
+
754
+ // src/client/gibwork-client.ts
755
+ var GibworkClient = class {
756
+ tasks;
757
+ submissions;
758
+ constructor(options) {
759
+ assertSigner(options.signer);
760
+ const transport = new HttpTransport({
761
+ baseUrl: options.baseUrl ?? DEFAULT_GIBWORK_API_URL,
762
+ ...options.fetch ? { fetch: options.fetch } : {},
763
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
764
+ });
765
+ this.tasks = new TasksResource(transport, options.signer);
766
+ this.submissions = new SubmissionsResource(transport, options.signer);
767
+ }
768
+ };
769
+ function assertSigner(signer) {
770
+ if (!signer || typeof signer.publicKey?.toBase58 !== "function" || typeof signer.signMessage !== "function" || typeof signer.signTransaction !== "function") {
771
+ throw new GibworkConfigurationError(
772
+ "signer must provide publicKey, signMessage, and signTransaction"
773
+ );
774
+ }
775
+ }
776
+
777
+ exports.DEFAULT_GIBWORK_API_URL = DEFAULT_GIBWORK_API_URL;
778
+ exports.GibworkAmbiguousSubmitError = GibworkAmbiguousSubmitError;
779
+ exports.GibworkApiError = GibworkApiError;
780
+ exports.GibworkClient = GibworkClient;
781
+ exports.GibworkConfigurationError = GibworkConfigurationError;
782
+ exports.GibworkError = GibworkError;
783
+ exports.GibworkNetworkError = GibworkNetworkError;
784
+ exports.GibworkRequestAbortedError = GibworkRequestAbortedError;
785
+ exports.GibworkTimeoutError = GibworkTimeoutError;
786
+ exports.signPreparedTransaction = signPreparedTransaction;
787
+ //# sourceMappingURL=index.cjs.map
788
+ //# sourceMappingURL=index.cjs.map