@opensea/sdk 12.11.4 → 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.
Files changed (45) hide show
  1. package/README.md +2 -2
  2. package/lib/api/api.d.ts +3 -0
  3. package/lib/api/api.js +4 -0
  4. package/lib/api/api.js.map +1 -1
  5. package/lib/api/apiPaths.d.ts +10 -0
  6. package/lib/api/apiPaths.js +43 -2
  7. package/lib/api/apiPaths.js.map +1 -1
  8. package/lib/api/collections.d.ts +16 -1
  9. package/lib/api/collections.js +21 -0
  10. package/lib/api/collections.js.map +1 -1
  11. package/lib/api/nfts.d.ts +14 -1
  12. package/lib/api/nfts.js +17 -0
  13. package/lib/api/nfts.js.map +1 -1
  14. package/lib/api/tools.d.ts +45 -0
  15. package/lib/api/tools.js +64 -0
  16. package/lib/api/tools.js.map +1 -0
  17. package/lib/api/types.d.ts +155 -1
  18. package/lib/api/types.js.map +1 -1
  19. package/lib/api/uploadContext.d.ts +50 -0
  20. package/lib/api/uploadContext.js +144 -0
  21. package/lib/api/uploadContext.js.map +1 -0
  22. package/lib/api/walletAuth.d.ts +268 -0
  23. package/lib/api/walletAuth.js +41 -0
  24. package/lib/api/walletAuth.js.map +1 -1
  25. package/lib/index.d.ts +1 -0
  26. package/lib/index.js +1 -0
  27. package/lib/index.js.map +1 -1
  28. package/lib/stream/transport/phoenix.d.ts +6 -0
  29. package/lib/stream/transport/phoenix.js +15 -9
  30. package/lib/stream/transport/phoenix.js.map +1 -1
  31. package/lib/viem.d.ts +1 -0
  32. package/lib/viem.js +1 -0
  33. package/lib/viem.js.map +1 -1
  34. package/package.json +2 -2
  35. package/src/api/api.ts +4 -0
  36. package/src/api/apiPaths.ts +48 -0
  37. package/src/api/collections.ts +47 -0
  38. package/src/api/nfts.ts +37 -0
  39. package/src/api/tools.ts +99 -0
  40. package/src/api/types.ts +209 -0
  41. package/src/api/uploadContext.ts +166 -0
  42. package/src/api/walletAuth.ts +84 -0
  43. package/src/index.ts +1 -0
  44. package/src/stream/transport/phoenix.ts +25 -9
  45. package/src/viem.ts +1 -0
@@ -1,4 +1,4 @@
1
- import type { AccountResolveResponse, AccountSearchResponse as ApiAccountSearchResponse, AgentProfileRelationshipsResponse as ApiAgentProfileRelationshipsResponse, BuildOfferResponse as ApiBuildOfferResponse, CancelResponse as ApiCancelResponse, CollectionSearchResponse as ApiCollectionSearchResponse, DropMintRequest as ApiDropMintRequest, DropMintResponse as ApiDropMintResponse, Listing as ApiListing, Nft as ApiNft, NftSearchResponse as ApiNftSearchResponse, Offer as ApiOffer, Order as ApiOrder, OrderAsset as ApiOrderAsset, Payment as ApiPayment, Price as ApiPrice, SearchResponse as ApiSearchResponse, SearchResultResponse as ApiSearchResultResponse, SvmInstructionAccountResponse as ApiSvmInstructionAccountResponse, SvmInstructionResponse as ApiSvmInstructionResponse, SvmTransactionDetailsResponse as ApiSvmTransactionDetailsResponse, SwapExecuteRequest as ApiSwapExecuteRequest, SwapExecuteResponse as ApiSwapExecuteResponse, SwapQuoteResponse as ApiSwapQuoteResponse, SweepCollectionRequest as ApiSweepCollectionRequest, SweepCollectionResponse as ApiSweepCollectionResponse, TokenDetailedResponse as ApiTokenDetailedResponse, TokenResponse as ApiTokenResponse, TokenSearchResponse as ApiTokenSearchResponse, Trait as ApiTrait, TraitFloorResponse as ApiTraitFloorResponse, TraitFloorsResponse as ApiTraitFloorsResponse, TransactionReceiptRequest as ApiTransactionReceiptRequest, TransactionReceiptResponse as ApiTransactionReceiptResponse, ValidateMetadataResponse as ApiValidateMetadataResponse, WalletVisibilityResponse as ApiWalletVisibilityResponse, AssetMetadataResponse, ChainIdentifier, ChainListResponse, ChainResponse, ContractResponse, DropDetailedResponse, DropResponse, DropStageResponse, InstantApiKeyResponse, ListingsResponse, NftDetailed, NftListResponse, NftResponse, OffersResponse, paths, TokenAccountActivityPaginatedResponse, TokenBalancePaginatedResponse, TokenBalanceResponse, TokenGroupPaginatedResponse, TokenGroupResponse, TokenPaginatedResponse } from "@opensea/api-types";
1
+ import type { AccountResolveResponse, AccountSearchResponse as ApiAccountSearchResponse, AgentProfileRelationshipsResponse as ApiAgentProfileRelationshipsResponse, BuildOfferResponse as ApiBuildOfferResponse, CancelResponse as ApiCancelResponse, CollectionPfpProfilesResponse as ApiCollectionPfpProfilesResponse, CollectionSearchResponse as ApiCollectionSearchResponse, CreatorFeeEnforcementStatusResponse as ApiCreatorFeeEnforcementStatusResponse, DropMintRequest as ApiDropMintRequest, DropMintResponse as ApiDropMintResponse, Listing as ApiListing, Nft as ApiNft, NftSearchResponse as ApiNftSearchResponse, Offer as ApiOffer, Order as ApiOrder, OrderAsset as ApiOrderAsset, Payment as ApiPayment, Price as ApiPrice, SearchResponse as ApiSearchResponse, SearchResultResponse as ApiSearchResultResponse, SvmInstructionAccountResponse as ApiSvmInstructionAccountResponse, SvmInstructionResponse as ApiSvmInstructionResponse, SvmTransactionDetailsResponse as ApiSvmTransactionDetailsResponse, SwapExecuteRequest as ApiSwapExecuteRequest, SwapExecuteResponse as ApiSwapExecuteResponse, SwapQuoteResponse as ApiSwapQuoteResponse, SweepCollectionRequest as ApiSweepCollectionRequest, SweepCollectionResponse as ApiSweepCollectionResponse, TokenDetailedResponse as ApiTokenDetailedResponse, TokenResponse as ApiTokenResponse, TokenSearchResponse as ApiTokenSearchResponse, TopPfpCollectionsResponse as ApiTopPfpCollectionsResponse, Trait as ApiTrait, TraitFloorResponse as ApiTraitFloorResponse, TraitFloorsResponse as ApiTraitFloorsResponse, TransactionReceiptRequest as ApiTransactionReceiptRequest, TransactionReceiptResponse as ApiTransactionReceiptResponse, ValidateMetadataResponse as ApiValidateMetadataResponse, WalletVisibilityResponse as ApiWalletVisibilityResponse, AssetMetadataResponse, ChainIdentifier, ChainListResponse, ChainResponse, ContractResponse, DropDetailedResponse, DropResponse, DropStageResponse, InstantApiKeyResponse, ListingsResponse, NftDetailed, NftListResponse, NftResponse, OffersResponse, OperationQueryParams, paths, RegisteredToolResponse, StandardizedNft, StandardizedNftFacetsResponse, StandardizedNftListResponse, TokenAccountActivityPaginatedResponse, TokenBalancePaginatedResponse, TokenBalanceResponse, TokenGroupPaginatedResponse, TokenGroupResponse, TokenPaginatedResponse, ToolActivityPaginatedResponse, ToolListPaginatedResponse, ToolSearchPaginatedResponse, ToolUsageRequest, ToolUsageResponse } from "@opensea/api-types";
2
2
  import type { OrderType, ProtocolData } from "../orders/types";
3
3
  import type { OpenSeaCollection } from "../types";
4
4
  import type { Camelize } from "../utils/case";
@@ -1032,6 +1032,33 @@ export type TraitFloor = Camelize<ApiTraitFloorResponse>;
1032
1032
  * @category API Response Types
1033
1033
  */
1034
1034
  export type TraitFloorsResponse = Camelize<ApiTraitFloorsResponse>;
1035
+ /**
1036
+ * Whether a collection enforces creator fees onchain, and whether its contract supports turning
1037
+ * enforcement on.
1038
+ * @category API Response Types
1039
+ */
1040
+ export type CreatorFeeEnforcementStatusResponse = Camelize<ApiCreatorFeeEnforcementStatusResponse>;
1041
+ /**
1042
+ * Query args for `GET /api/v2/collections/{slug}/pfp-profiles`, derived from the spec.
1043
+ * @category API Query Args
1044
+ */
1045
+ export type GetCollectionPfpProfilesArgs = Camelize<OperationQueryParams<"get_collection_pfp_profiles">>;
1046
+ /**
1047
+ * Profiles wearing a verified NFT from a collection as their profile picture.
1048
+ * @category API Response Types
1049
+ */
1050
+ export type CollectionPfpProfilesResponse = Camelize<ApiCollectionPfpProfilesResponse>;
1051
+ /**
1052
+ * Query args for `GET /api/v2/pfp/top-collections`, derived from the spec. `limit` (1-50) is
1053
+ * required.
1054
+ * @category API Query Args
1055
+ */
1056
+ export type GetTopPfpCollectionsArgs = Camelize<OperationQueryParams<"get_top_pfp_collections">>;
1057
+ /**
1058
+ * Collections ranked by verified NFT profile-picture wearer count.
1059
+ * @category API Response Types
1060
+ */
1061
+ export type TopPfpCollectionsResponse = Camelize<ApiTopPfpCollectionsResponse>;
1035
1062
  export type CreateOfferActionsResponse = Camelize<ApiCreateOfferActionsResponse>;
1036
1063
  export type CreateOfferFulfillmentActionsResponse = Camelize<ApiFulfillmentActionsResponse>;
1037
1064
  export type CrossChainDropMintResponse = Camelize<ApiCrossChainDropMintResponse>;
@@ -1188,6 +1215,83 @@ export interface GetNFTsByAccountOptions {
1188
1215
  */
1189
1216
  includeAutoHidden?: boolean;
1190
1217
  }
1218
+ /**
1219
+ * Normalized-attribute filters shared by the collection group NFT search and
1220
+ * facets endpoints. Each value list is sent as a repeated query parameter
1221
+ * (`?grader=PSA&grader=CGC`) and matches any of its values; separate filters
1222
+ * are AND-combined. Discover the values with `getNFTGroupFacets`.
1223
+ *
1224
+ * @category API Query Args
1225
+ */
1226
+ export interface NFTGroupFacetFilters {
1227
+ franchise?: string[];
1228
+ grader?: string[];
1229
+ grade?: string[];
1230
+ subject?: string[];
1231
+ year?: string[];
1232
+ set?: string[];
1233
+ language?: string[];
1234
+ edition?: string[];
1235
+ /** Serialized as `product_type`. */
1236
+ productType?: string[];
1237
+ }
1238
+ /**
1239
+ * Sort fields accepted by the collection group NFT search endpoint.
1240
+ * @category API Query Args
1241
+ */
1242
+ export type NFTGroupSortBy = "price" | "top_offer" | "last_sale" | "last_sale_date" | "created_date" | "received_date" | "listing_created_date" | "best_deal" | "estimated_value";
1243
+ /**
1244
+ * Query args for `GET /api/v2/nfts/group/{group}`.
1245
+ * @category API Query Args
1246
+ */
1247
+ export interface GetNFTsByGroupArgs extends NFTGroupFacetFilters {
1248
+ /** Restrict results to these collections in the group (max 10). Defaults to the whole group. */
1249
+ collectionSlugs?: string[];
1250
+ /** Full-text match on NFT name, up to 100 characters. */
1251
+ query?: string;
1252
+ /** Only return NFTs that are listed (`true`) or unlisted (`false`). */
1253
+ isListed?: boolean;
1254
+ /** Minimum estimated value in USD, inclusive. */
1255
+ minEstimatedValueUsd?: number;
1256
+ /** Maximum estimated value in USD, inclusive. */
1257
+ maxEstimatedValueUsd?: number;
1258
+ /** Sort field. The server default is `best_deal`. */
1259
+ sortBy?: NFTGroupSortBy;
1260
+ /** Sort direction. The server default is `desc`. */
1261
+ sortDirection?: "asc" | "desc";
1262
+ /** Number of NFTs to return (1-100, server default 50). */
1263
+ limit?: number;
1264
+ /** Pagination cursor from a previous response's `next`. */
1265
+ next?: string;
1266
+ }
1267
+ /**
1268
+ * Query args for `GET /api/v2/nfts/group/{group}/facets`.
1269
+ * @category API Query Args
1270
+ */
1271
+ export interface GetNFTGroupFacetsArgs extends NFTGroupFacetFilters {
1272
+ /** Only return these facet types, e.g. `["grader", "grade"]`. Defaults to all. */
1273
+ facetTypes?: string[];
1274
+ /** Restrict counts to these collections in the group (max 10). */
1275
+ collectionSlugs?: string[];
1276
+ }
1277
+ /**
1278
+ * NFT with normalized, issuer-independent attributes, returned by the
1279
+ * collection group search. Camelized from api-types `StandardizedNft`.
1280
+ * @category API Models
1281
+ */
1282
+ export type StandardizedNFT = Camelize<StandardizedNft>;
1283
+ /**
1284
+ * Response from the collection group NFT search.
1285
+ * Camelized from api-types `StandardizedNftListResponse`.
1286
+ * @category API Response Types
1287
+ */
1288
+ export type GetNFTsByGroupResponse = Camelize<StandardizedNftListResponse>;
1289
+ /**
1290
+ * Facet values and counts for a collection group.
1291
+ * Camelized from api-types `StandardizedNftFacetsResponse`.
1292
+ * @category API Response Types
1293
+ */
1294
+ export type GetNFTGroupFacetsResponse = Camelize<StandardizedNftFacetsResponse>;
1191
1295
  /**
1192
1296
  * Query args for the account portfolio and portfolio history endpoints.
1193
1297
  * @category API Query Args
@@ -1273,4 +1377,54 @@ export type ProfileListingsResponse = Camelize<ListingsResponse>;
1273
1377
  * @category API Response Types
1274
1378
  */
1275
1379
  export type ProfileOffersResponse = Camelize<OffersResponse>;
1380
+ /**
1381
+ * Query args for `GET /api/v2/tools`. Derived from the spec. Beta: the endpoint may change
1382
+ * without notice.
1383
+ * @category API Query Args
1384
+ */
1385
+ export type ListToolsArgs = Camelize<OperationQueryParams<"list_tools">>;
1386
+ /**
1387
+ * Query args for `GET /api/v2/tools/search`. Derived from the spec. Beta: the endpoint may change
1388
+ * without notice.
1389
+ * @category API Query Args
1390
+ */
1391
+ export type SearchToolsArgs = Camelize<OperationQueryParams<"search_tools">>;
1392
+ /**
1393
+ * Query args for `GET /api/v2/tools/{registry_chain}/{registry_addr}/{tool_id}/activity`.
1394
+ * Derived from the spec. Beta: the endpoint may change without notice.
1395
+ * @category API Query Args
1396
+ */
1397
+ export type GetToolActivityArgs = Camelize<OperationQueryParams<"get_tool_activity">>;
1398
+ /**
1399
+ * Body for `POST /api/v2/tools/usage`. Identify the tool by `toolChainId`, `toolRegistryAddress`
1400
+ * and `toolOnchainId`, or by `toolEndpoint` alone. Beta: the endpoint may change without notice.
1401
+ * @category API Models
1402
+ */
1403
+ export type ReportToolUsageRequest = Camelize<ToolUsageRequest>;
1404
+ /**
1405
+ * Response from `POST /api/v2/tools/usage`. Beta.
1406
+ * @category API Response Types
1407
+ */
1408
+ export type ReportToolUsageResponse = Camelize<ToolUsageResponse>;
1409
+ /**
1410
+ * Response from `GET /api/v2/tools`. Beta.
1411
+ * @category API Response Types
1412
+ */
1413
+ export type ListToolsResponse = Camelize<ToolListPaginatedResponse>;
1414
+ /**
1415
+ * Response from `GET /api/v2/tools/search`. Beta.
1416
+ * @category API Response Types
1417
+ */
1418
+ export type SearchToolsResponse = Camelize<ToolSearchPaginatedResponse>;
1419
+ /**
1420
+ * A registered tool. `inputs` and `outputs` are the tool's own JSON Schemas and keep their
1421
+ * wire keys; every other field is camelized. Beta.
1422
+ * @category API Response Types
1423
+ */
1424
+ export type GetToolResponse = Omit<Camelize<RegisteredToolResponse>, "inputs" | "outputs"> & Pick<RegisteredToolResponse, "inputs" | "outputs">;
1425
+ /**
1426
+ * Response from the tool activity endpoint. Beta.
1427
+ * @category API Response Types
1428
+ */
1429
+ export type GetToolActivityResponse = Camelize<ToolActivityPaginatedResponse>;
1276
1430
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings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B;AAED;;;GAGG;AACH,IAAY,cAKX;AALD,WAAY,cAAc;IACxB,qCAAmB,CAAA;IACnB,2CAAyB,CAAA;IACzB,uDAAqC,CAAA;IACrC,6CAA2B,CAAA;AAC7B,CAAC,EALW,cAAc,8BAAd,cAAc,QAKzB"}
@@ -0,0 +1,50 @@
1
+ import type { UploadContext } from "@opensea/api-types";
2
+ export type { UploadContext };
3
+ /**
4
+ * File bytes accepted by {@link uploadToContext}. A `File` is a `Blob`, and a
5
+ * Node `Buffer` is a `Uint8Array`.
6
+ */
7
+ export type UploadContextFile = Blob | ArrayBuffer | Uint8Array;
8
+ /**
9
+ * A storage upload that returned a non-2xx status. Only the status is kept:
10
+ * the response body is never read, because storage error bodies can echo
11
+ * signed request material such as `StringToSign` or `AWSAccessKeyId`.
12
+ */
13
+ export declare class UploadContextError extends Error {
14
+ status: number;
15
+ constructor(status: number);
16
+ }
17
+ /**
18
+ * Narrow a value to a single `UploadContext`. An array (the shape
19
+ * `createDropItemMediaUpload` returns) is accepted only with an `index`.
20
+ *
21
+ * This checks shape, not origin. Pass only a value that came from an OpenSea
22
+ * API response, such as the `walletAuth` upload helpers, never untrusted
23
+ * user-supplied JSON.
24
+ */
25
+ export declare function selectUploadContext(value: unknown, index?: number): UploadContext;
26
+ /**
27
+ * Perform the storage upload an `UploadContext` describes and return its
28
+ * token for the follow-up OpenSea call.
29
+ *
30
+ * The request goes straight to the context's storage URL through the global
31
+ * `fetch`, with no OpenSea API key or wallet token. For POST, every entry of
32
+ * `fields` is sent unchanged as a multipart text field, then the file as the
33
+ * last part, named `file`; the multipart boundary and Content-Type header are
34
+ * left to fetch. For PUT, the bytes are sent as the body with no headers of
35
+ * our own, so a `Blob` with a `type` sets the Content-Type and raw bytes set
36
+ * none. Any 2xx response is success. The url must be HTTPS, and a redirect
37
+ * fails the upload rather than resending the file elsewhere. The response
38
+ * body is never read: it is cancelled on success and on failure.
39
+ *
40
+ * The file goes to whatever HTTPS URL the context names, so the context must
41
+ * come from an OpenSea API response, such as the `walletAuth` upload helpers.
42
+ *
43
+ * @throws {UploadContextError} when storage answers with a non-2xx status.
44
+ */
45
+ export declare function uploadToContext(context: UploadContext, file: UploadContextFile, options?: {
46
+ filename?: string;
47
+ signal?: AbortSignal;
48
+ }): Promise<{
49
+ token: string;
50
+ }>;
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UploadContextError = void 0;
4
+ exports.selectUploadContext = selectUploadContext;
5
+ exports.uploadToContext = uploadToContext;
6
+ /**
7
+ * A storage upload that returned a non-2xx status. Only the status is kept:
8
+ * the response body is never read, because storage error bodies can echo
9
+ * signed request material such as `StringToSign` or `AWSAccessKeyId`.
10
+ */
11
+ class UploadContextError extends Error {
12
+ status;
13
+ constructor(status) {
14
+ super(`Storage upload failed with HTTP ${status}`);
15
+ this.status = status;
16
+ this.name = "UploadContextError";
17
+ }
18
+ }
19
+ exports.UploadContextError = UploadContextError;
20
+ /**
21
+ * OpenSea upload contexts always point at HTTPS storage. Refusing anything else
22
+ * keeps a hand-edited or foreign context from sending the file in cleartext or
23
+ * to a non-network scheme.
24
+ */
25
+ function assertHttpsUrl(url) {
26
+ let parsed;
27
+ try {
28
+ parsed = new URL(url);
29
+ }
30
+ catch {
31
+ throw new Error("Upload context url is not a valid URL");
32
+ }
33
+ if (parsed.protocol !== "https:") {
34
+ throw new Error(`Upload context url must use https, not ${parsed.protocol.replace(/:$/, "")}`);
35
+ }
36
+ }
37
+ /**
38
+ * `instanceof Blob` is false for a Blob or File from another realm (an iframe,
39
+ * a worker), and copying one through `new Uint8Array` yields zero bytes, so
40
+ * Blob-like values are recognized by shape instead.
41
+ */
42
+ function isBlobLike(file) {
43
+ if (file instanceof Blob)
44
+ return true;
45
+ const candidate = file;
46
+ return (typeof candidate.arrayBuffer === "function" &&
47
+ typeof candidate.size === "number" &&
48
+ typeof candidate.type === "string");
49
+ }
50
+ function toBlob(file) {
51
+ if (isBlobLike(file))
52
+ return file;
53
+ return new Blob([file instanceof ArrayBuffer ? file : new Uint8Array(file)]);
54
+ }
55
+ /**
56
+ * Narrow a value to a single `UploadContext`. An array (the shape
57
+ * `createDropItemMediaUpload` returns) is accepted only with an `index`.
58
+ *
59
+ * This checks shape, not origin. Pass only a value that came from an OpenSea
60
+ * API response, such as the `walletAuth` upload helpers, never untrusted
61
+ * user-supplied JSON.
62
+ */
63
+ function selectUploadContext(value, index) {
64
+ let candidate = value;
65
+ if (Array.isArray(value)) {
66
+ if (index === undefined) {
67
+ throw new Error(`Upload context is an array of ${value.length}; pass the index of the one to use`);
68
+ }
69
+ if (!Number.isInteger(index) || index < 0 || index >= value.length) {
70
+ throw new Error(`Index ${index} is out of range for ${value.length} upload contexts`);
71
+ }
72
+ candidate = value[index];
73
+ }
74
+ else if (index !== undefined) {
75
+ throw new Error("An index applies only to an array of upload contexts");
76
+ }
77
+ const context = candidate;
78
+ if (!context ||
79
+ typeof context !== "object" ||
80
+ typeof context.url !== "string" ||
81
+ typeof context.token !== "string" ||
82
+ (context.method !== "POST" && context.method !== "PUT") ||
83
+ !context.fields ||
84
+ typeof context.fields !== "object") {
85
+ throw new Error("Not an upload context: expected an object with url, method (POST or PUT), fields and token");
86
+ }
87
+ return context;
88
+ }
89
+ /**
90
+ * Perform the storage upload an `UploadContext` describes and return its
91
+ * token for the follow-up OpenSea call.
92
+ *
93
+ * The request goes straight to the context's storage URL through the global
94
+ * `fetch`, with no OpenSea API key or wallet token. For POST, every entry of
95
+ * `fields` is sent unchanged as a multipart text field, then the file as the
96
+ * last part, named `file`; the multipart boundary and Content-Type header are
97
+ * left to fetch. For PUT, the bytes are sent as the body with no headers of
98
+ * our own, so a `Blob` with a `type` sets the Content-Type and raw bytes set
99
+ * none. Any 2xx response is success. The url must be HTTPS, and a redirect
100
+ * fails the upload rather than resending the file elsewhere. The response
101
+ * body is never read: it is cancelled on success and on failure.
102
+ *
103
+ * The file goes to whatever HTTPS URL the context names, so the context must
104
+ * come from an OpenSea API response, such as the `walletAuth` upload helpers.
105
+ *
106
+ * @throws {UploadContextError} when storage answers with a non-2xx status.
107
+ */
108
+ async function uploadToContext(context, file, options) {
109
+ const valid = selectUploadContext(context);
110
+ assertHttpsUrl(valid.url);
111
+ const blob = toBlob(file);
112
+ let response;
113
+ if (valid.method === "PUT") {
114
+ response = await fetch(valid.url, {
115
+ method: "PUT",
116
+ body: blob,
117
+ redirect: "error",
118
+ signal: options?.signal,
119
+ });
120
+ }
121
+ else {
122
+ const form = new FormData();
123
+ for (const [name, value] of Object.entries(valid.fields)) {
124
+ form.append(name, value);
125
+ }
126
+ form.append("file", blob, options?.filename ?? "file");
127
+ response = await fetch(valid.url, {
128
+ method: "POST",
129
+ body: form,
130
+ redirect: "error",
131
+ signal: options?.signal,
132
+ });
133
+ }
134
+ await discardBody(response);
135
+ if (!response.ok)
136
+ throw new UploadContextError(response.status);
137
+ return { token: valid.token };
138
+ }
139
+ async function discardBody(response) {
140
+ await Promise.resolve()
141
+ .then(() => response.body?.cancel())
142
+ .catch(() => undefined);
143
+ }
144
+ //# sourceMappingURL=uploadContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploadContext.js","sourceRoot":"","sources":["../../src/api/uploadContext.ts"],"names":[],"mappings":";;;AAqEA,kDAoCC;AAqBD,0CAiCC;AArJD;;;;GAIG;AACH,MAAa,kBAAmB,SAAQ,KAAK;IACxB;IAAnB,YAAmB,MAAc;QAC/B,KAAK,CAAC,mCAAmC,MAAM,EAAE,CAAC,CAAA;QADjC,WAAM,GAAN,MAAM,CAAQ;QAE/B,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAA;IAClC,CAAC;CACF;AALD,gDAKC;AAED;;;;GAIG;AACH,SAAS,cAAc,CAAC,GAAW;IACjC,IAAI,MAAW,CAAA;IACf,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,K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