@opensea/sdk 12.12.0 → 12.13.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.
@@ -0,0 +1,166 @@
1
+ import type { UploadContext } from "@opensea/api-types"
2
+
3
+ export type { UploadContext }
4
+
5
+ /**
6
+ * File bytes accepted by {@link uploadToContext}. A `File` is a `Blob`, and a
7
+ * Node `Buffer` is a `Uint8Array`.
8
+ */
9
+ export type UploadContextFile = Blob | ArrayBuffer | Uint8Array
10
+
11
+ /**
12
+ * A storage upload that returned a non-2xx status. Only the status is kept:
13
+ * the response body is never read, because storage error bodies can echo
14
+ * signed request material such as `StringToSign` or `AWSAccessKeyId`.
15
+ */
16
+ export class UploadContextError extends Error {
17
+ constructor(public status: number) {
18
+ super(`Storage upload failed with HTTP ${status}`)
19
+ this.name = "UploadContextError"
20
+ }
21
+ }
22
+
23
+ /**
24
+ * OpenSea upload contexts always point at HTTPS storage. Refusing anything else
25
+ * keeps a hand-edited or foreign context from sending the file in cleartext or
26
+ * to a non-network scheme.
27
+ */
28
+ function assertHttpsUrl(url: string): void {
29
+ let parsed: URL
30
+ try {
31
+ parsed = new URL(url)
32
+ } catch {
33
+ throw new Error("Upload context url is not a valid URL")
34
+ }
35
+ if (parsed.protocol !== "https:") {
36
+ throw new Error(
37
+ `Upload context url must use https, not ${parsed.protocol.replace(/:$/, "")}`,
38
+ )
39
+ }
40
+ }
41
+
42
+ /**
43
+ * `instanceof Blob` is false for a Blob or File from another realm (an iframe,
44
+ * a worker), and copying one through `new Uint8Array` yields zero bytes, so
45
+ * Blob-like values are recognized by shape instead.
46
+ */
47
+ function isBlobLike(file: UploadContextFile): file is Blob {
48
+ if (file instanceof Blob) return true
49
+ const candidate = file as unknown as Partial<Blob>
50
+ return (
51
+ typeof candidate.arrayBuffer === "function" &&
52
+ typeof candidate.size === "number" &&
53
+ typeof candidate.type === "string"
54
+ )
55
+ }
56
+
57
+ function toBlob(file: UploadContextFile): Blob {
58
+ if (isBlobLike(file)) return file
59
+ return new Blob([file instanceof ArrayBuffer ? file : new Uint8Array(file)])
60
+ }
61
+
62
+ /**
63
+ * Narrow a value to a single `UploadContext`. An array (the shape
64
+ * `createDropItemMediaUpload` returns) is accepted only with an `index`.
65
+ *
66
+ * This checks shape, not origin. Pass only a value that came from an OpenSea
67
+ * API response, such as the `walletAuth` upload helpers, never untrusted
68
+ * user-supplied JSON.
69
+ */
70
+ export function selectUploadContext(
71
+ value: unknown,
72
+ index?: number,
73
+ ): UploadContext {
74
+ let candidate = value
75
+ if (Array.isArray(value)) {
76
+ if (index === undefined) {
77
+ throw new Error(
78
+ `Upload context is an array of ${value.length}; pass the index of the one to use`,
79
+ )
80
+ }
81
+ if (!Number.isInteger(index) || index < 0 || index >= value.length) {
82
+ throw new Error(
83
+ `Index ${index} is out of range for ${value.length} upload contexts`,
84
+ )
85
+ }
86
+ candidate = value[index]
87
+ } else if (index !== undefined) {
88
+ throw new Error("An index applies only to an array of upload contexts")
89
+ }
90
+
91
+ const context = candidate as Partial<UploadContext> | null
92
+ if (
93
+ !context ||
94
+ typeof context !== "object" ||
95
+ typeof context.url !== "string" ||
96
+ typeof context.token !== "string" ||
97
+ (context.method !== "POST" && context.method !== "PUT") ||
98
+ !context.fields ||
99
+ typeof context.fields !== "object"
100
+ ) {
101
+ throw new Error(
102
+ "Not an upload context: expected an object with url, method (POST or PUT), fields and token",
103
+ )
104
+ }
105
+ return context as UploadContext
106
+ }
107
+
108
+ /**
109
+ * Perform the storage upload an `UploadContext` describes and return its
110
+ * token for the follow-up OpenSea call.
111
+ *
112
+ * The request goes straight to the context's storage URL through the global
113
+ * `fetch`, with no OpenSea API key or wallet token. For POST, every entry of
114
+ * `fields` is sent unchanged as a multipart text field, then the file as the
115
+ * last part, named `file`; the multipart boundary and Content-Type header are
116
+ * left to fetch. For PUT, the bytes are sent as the body with no headers of
117
+ * our own, so a `Blob` with a `type` sets the Content-Type and raw bytes set
118
+ * none. Any 2xx response is success. The url must be HTTPS, and a redirect
119
+ * fails the upload rather than resending the file elsewhere. The response
120
+ * body is never read: it is cancelled on success and on failure.
121
+ *
122
+ * The file goes to whatever HTTPS URL the context names, so the context must
123
+ * come from an OpenSea API response, such as the `walletAuth` upload helpers.
124
+ *
125
+ * @throws {UploadContextError} when storage answers with a non-2xx status.
126
+ */
127
+ export async function uploadToContext(
128
+ context: UploadContext,
129
+ file: UploadContextFile,
130
+ options?: { filename?: string; signal?: AbortSignal },
131
+ ): Promise<{ token: string }> {
132
+ const valid = selectUploadContext(context)
133
+ assertHttpsUrl(valid.url)
134
+ const blob = toBlob(file)
135
+ let response: Response
136
+ if (valid.method === "PUT") {
137
+ response = await fetch(valid.url, {
138
+ method: "PUT",
139
+ body: blob,
140
+ redirect: "error",
141
+ signal: options?.signal,
142
+ })
143
+ } else {
144
+ const form = new FormData()
145
+ for (const [name, value] of Object.entries(valid.fields)) {
146
+ form.append(name, value)
147
+ }
148
+ form.append("file", blob, options?.filename ?? "file")
149
+ response = await fetch(valid.url, {
150
+ method: "POST",
151
+ body: form,
152
+ redirect: "error",
153
+ signal: options?.signal,
154
+ })
155
+ }
156
+
157
+ await discardBody(response)
158
+ if (!response.ok) throw new UploadContextError(response.status)
159
+ return { token: valid.token }
160
+ }
161
+
162
+ async function discardBody(response: Response): Promise<void> {
163
+ await Promise.resolve()
164
+ .then(() => response.body?.cancel())
165
+ .catch(() => undefined)
166
+ }
@@ -190,6 +190,17 @@ export class WalletAuthAPI {
190
190
  )
191
191
  }
192
192
 
193
+ /**
194
+ * The drop's saved items, including a draft's, one page at a time. Only the
195
+ * collection owner or an authorized editor can list them.
196
+ */
197
+ listDropItems(slug: string, query?: WalletAuthQuery<"list_drop_items">) {
198
+ return this.fetcher.get<OperationResponse<"list_drop_items">>(
199
+ `/api/v2/drops/${segment(slug)}/items`,
200
+ query,
201
+ )
202
+ }
203
+
193
204
  saveSelfMintDropItem(
194
205
  slug: string,
195
206
  body: WalletAuthRequest<"save_self_mint_drop_item">,
@@ -409,6 +420,68 @@ export class WalletAuthAPI {
409
420
  )
410
421
  }
411
422
 
423
+ /**
424
+ * `placement` is one of hero_desktop, hero_mobile, about_preview,
425
+ * about_section, overview, overview_background or team. The response is not
426
+ * camelized, for the `UploadContext.fields` reason on
427
+ * `createCollectionImageUpload`.
428
+ */
429
+ createCollectionPageMediaUpload(
430
+ slug: string,
431
+ placement: string,
432
+ contentType: WalletAuthQuery<"upload_collection_page_media">["contentType"],
433
+ ) {
434
+ const query = new URLSearchParams({ content_type: contentType })
435
+ return this.fetcher.request<
436
+ OperationResponse<"upload_collection_page_media">
437
+ >(
438
+ "POST",
439
+ `/api/v2/collections/${segment(slug)}/media/${segment(placement)}?${query}`,
440
+ undefined,
441
+ undefined,
442
+ { camelizeResponse: false },
443
+ )
444
+ }
445
+
446
+ getCollectionMetadata(slug: string) {
447
+ return this.fetcher.get<OperationResponse<"get_collection_metadata">>(
448
+ `/api/v2/collections/${segment(slug)}/metadata`,
449
+ )
450
+ }
451
+
452
+ setCollectionPricingCurrency(
453
+ slug: string,
454
+ body: WalletAuthRequest<"set_collection_pricing_currency">,
455
+ ) {
456
+ return this.fetcher.request<
457
+ OperationResponse<"set_collection_pricing_currency">
458
+ >("POST", `/api/v2/collections/${segment(slug)}/pricing_currency`, body)
459
+ }
460
+
461
+ /**
462
+ * Send the returned transactions in order from each one's `from`, the
463
+ * contract's onchain owner. The list is empty when the contract is already
464
+ * in the requested state.
465
+ */
466
+ buildCreatorFeeEnforcementTransactions(
467
+ slug: string,
468
+ body: WalletAuthRequest<"build_creator_fee_enforcement_transactions">,
469
+ ) {
470
+ return this.fetcher.request<
471
+ OperationResponse<"build_creator_fee_enforcement_transactions">
472
+ >(
473
+ "POST",
474
+ `/api/v2/collections/${segment(slug)}/creator_fee_enforcement`,
475
+ body,
476
+ )
477
+ }
478
+
479
+ refreshCollectionMetadata(slug: string) {
480
+ return this.fetcher.request<
481
+ OperationResponse<"refresh_collection_metadata">
482
+ >("POST", `/api/v2/collections/${segment(slug)}/refresh`)
483
+ }
484
+
412
485
  /**
413
486
  * `UpdateProfileSettingsRequest` is camelCase on the wire (`displayName`,
414
487
  * `externalUrl`, `profileImageToken`, `bannerImageToken`), so the body is sent
@@ -472,6 +545,17 @@ export class WalletAuthAPI {
472
545
  )
473
546
  }
474
547
 
548
+ /**
549
+ * Public read: an API key alone is enough, and the wallet token is sent only
550
+ * when one is configured.
551
+ */
552
+ getProfileShelves(address: string) {
553
+ return this.fetcher.get<OperationResponse<"get_profile_shelves">>(
554
+ "/api/v2/profile/shelves",
555
+ { address },
556
+ )
557
+ }
558
+
475
559
  createProfileShelf(body: WalletAuthRequest<"create_profile_shelf">) {
476
560
  return this.fetcher.request<OperationResponse<"create_profile_shelf">>(
477
561
  "POST",
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import { OpenSeaOAuth } from "./auth/oauth"
4
4
  import { OpenSeaSDK } from "./sdk"
5
5
 
6
6
  export * from "./api/types"
7
+ export * from "./api/uploadContext"
7
8
  export * from "./api/walletAuth"
8
9
  export * from "./auth"
9
10
  export * from "./auth/oauth"
@@ -508,29 +508,45 @@ export class PhoenixChannelsTransport implements StreamTransport {
508
508
  subscription.joined = true
509
509
  subscription.rejoinTries = 0
510
510
  this.log(`subscribed to "${subscription.topic}"`)
511
- for (const callbacks of subscription.callbackList) {
512
- this.safeInvoke(() => callbacks.onSubscribed?.())
513
- }
511
+ this.notifyCallers(subscription, callbacks =>
512
+ callbacks.onSubscribed?.(),
513
+ )
514
514
  } else {
515
515
  this.log(`failed to subscribe to "${subscription.topic}"`)
516
516
  const error = new Error(
517
517
  `Subscribe to "${subscription.topic}" failed: ${status}`,
518
518
  )
519
- for (const callbacks of subscription.callbackList) {
520
- this.safeInvoke(() => callbacks.onSubscribeError?.(error))
521
- }
519
+ this.notifyCallers(subscription, callbacks =>
520
+ callbacks.onSubscribeError?.(error),
521
+ )
522
522
  }
523
523
  },
524
524
  reason => {
525
- for (const callbacks of subscription.callbackList) {
526
- this.safeInvoke(() => callbacks.onSubscribeError?.(reason))
527
- }
525
+ this.notifyCallers(subscription, callbacks =>
526
+ callbacks.onSubscribeError?.(reason),
527
+ )
528
528
  },
529
529
  )
530
530
 
531
531
  this.push(ref, ref, subscription.topic, PHX_JOIN, payload)
532
532
  }
533
533
 
534
+ /**
535
+ * A callback can remove its own caller, or another one, from the list being
536
+ * walked. Walking the live array would then skip whichever caller shifted
537
+ * into the removed slot, so walk a copy and skip anyone removed meanwhile.
538
+ */
539
+ private notifyCallers(
540
+ subscription: PhoenixSubscription,
541
+ notify: (callbacks: SubscribeCallbacks) => void,
542
+ ): void {
543
+ for (const callbacks of [...subscription.callbackList]) {
544
+ if (subscription.callbackList.includes(callbacks)) {
545
+ this.safeInvoke(() => notify(callbacks))
546
+ }
547
+ }
548
+ }
549
+
534
550
  /**
535
551
  * Rejoin a topic whose channel died while the socket stayed open. Uses the
536
552
  * same backoff schedule as reconnects, so a channel that keeps crashing does
package/src/viem.ts CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  // Re-export everything from the main entry point
40
40
  export { OpenSeaAPI } from "./api/api"
41
41
  export * from "./api/types"
42
+ export * from "./api/uploadContext"
42
43
  export * from "./api/walletAuth"
43
44
  export * from "./auth"
44
45
  export * from "./constants"