@carddb/browser 0.1.3 → 0.1.5

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/README.md CHANGED
@@ -25,10 +25,7 @@ const client = new CardDBClient({
25
25
  // Search for cards with filtering
26
26
  const cards = await client.records.search({
27
27
  datasetKey: 'cards',
28
- filter: (f) =>
29
- f
30
- .where('hp', gte(100))
31
- .where('name', ilike('%pikachu%')),
28
+ filter: (f) => f.where('hp', gte(100)).where('name', ilike('%pikachu%')),
32
29
  })
33
30
 
34
31
  // Iterate through all results (auto-paginates)
@@ -1,4 +1,4 @@
1
- var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";this.storage=r==="sessionStorage"?globalThis.sessionStorage:globalThis.localStorage,this.prefix=t.prefix??"carddb:";}get(t){try{let r=this.storage.getItem(this.prefix+t);if(!r)return null;let s=JSON.parse(r);return s.expiresAt!==null&&Date.now()>s.expiresAt?(this.storage.removeItem(this.prefix+t),null):s.value}catch{return this.storage.removeItem(this.prefix+t),null}}set(t,r,s){try{let i={value:r,expiresAt:s!==void 0?Date.now()+s*1e3:null};this.storage.setItem(this.prefix+t,JSON.stringify(i));}catch(i){console.warn("[CardDB] Failed to write to cache:",i);}}delete(t){this.storage.removeItem(this.prefix+t);}clear(){let t=[];for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t.push(s);}for(let r of t)this.storage.removeItem(r);}has(t){return this.get(t)!==null}get size(){let t=0;for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t++;}return t}cleanup(){let t=Date.now(),r=[];for(let s=0;s<this.storage.length;s++){let i=this.storage.key(s);if(i&&i.startsWith(this.prefix))try{let a=this.storage.getItem(i);if(a){let n=JSON.parse(a);n.expiresAt!==null&&t>n.expiresAt&&r.push(i);}}catch{r.push(i);}}for(let s of r)this.storage.removeItem(s);}};var l=class L extends Error{response;constructor(t,r){super(t),this.name="CardDBError",this.response=r,Error.captureStackTrace&&Error.captureStackTrace(this,L);}},D=class extends l{constructor(e="Invalid or missing API key",t){super(e,t),this.name="AuthenticationError";}},b=class extends l{retryAfter;limit;remaining;resetAt;constructor(e="Rate limit exceeded",t={}){super(e,t.response),this.name="RateLimitError",this.retryAfter=t.retryAfter??null,this.limit=t.limit??null,this.remaining=t.remaining??null,this.resetAt=t.resetAt??null;}},ye=class extends l{constructor(e="Resource not found",t){super(e,t),this.name="NotFoundError";}},R=class extends l{errors;constructor(e="Validation error",t={}){super(e,t.response),this.name="ValidationError",this.errors=t.errors??[];}},x=class extends l{constructor(e,t){super(e,t),this.name="RestrictedError";}},B=class extends l{errors;constructor(e="GraphQL error",t={}){super(e,t.response),this.name="GraphQLError",this.errors=t.errors??[];}},k=class extends l{constructor(e="Connection error",t){super(e,t),this.name="ConnectionError";}},S=class extends k{constructor(e="Request timed out",t){super(e,t),this.name="TimeoutError";}},I=class extends l{status;constructor(e="Server error",t={}){super(e,t.response),this.name="ServerError",this.status=t.status??null;}},ge=class extends l{failures;partialResults;constructor(e="Some links could not be resolved",t={}){super(e,t.response),this.name="LinkResolutionError",this.failures=t.failures??[],this.partialResults=t.partialResults;}getFailuresForField(e){return this.failures.filter(t=>t.field===e)}hasFailuresForField(e){return this.failures.some(t=>t.field===e)}};function me(e){return {eq:e}}function ke(e){return {neq:e}}function we(e){return {gt:e}}function ve(e){return {gte:e}}function pe(e){return {lt:e}}function be(e){return {lte:e}}function $e(e){return {in:e}}function De(e){return {nin:e}}function Re(e){return {contains:e}}function xe(e){return {like:e}}function Se(e){return {ilike:e}}function Ie(){return {is_null:true}}function Ce(){return {is_null:false}}var M=class A{conditions=[];orGroups=[];where(t,r){if(typeof t=="string")this.conditions.push({[t]:r});else for(let[s,i]of Object.entries(t))this.conditions.push({[s]:i});return this}any(t){let r=new A;t(r);let s=r.getConditions();return s.length>0&&this.orGroups.push({$or:s}),this}whereLink(t,r){let s={};for(let[i,a]of Object.entries(r))s[i]=a;return this.conditions.push({[`${t}._link`]:s}),this}whereAny(t,r){let s={};for(let[i,a]of Object.entries(r))s[i]=a;return this.conditions.push({[`${t}._any`]:s}),this}getConditions(){return this.conditions}build(){let t=[...this.conditions,...this.orGroups];return t.length===0?{}:t.length===1?t[0]:{$and:t}}};function C(e){if(e!==void 0){if(typeof e=="function"){let t=new M;e(t);let r=t.build();return Object.keys(r).length>0?r:void 0}return Object.keys(e).length>0?e:void 0}}var w=`
1
+ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";this.storage=r==="sessionStorage"?globalThis.sessionStorage:globalThis.localStorage,this.prefix=t.prefix??"carddb:";}get(t){try{let r=this.storage.getItem(this.prefix+t);if(!r)return null;let s=JSON.parse(r);return s.expiresAt!==null&&Date.now()>s.expiresAt?(this.storage.removeItem(this.prefix+t),null):s.value}catch{return this.storage.removeItem(this.prefix+t),null}}set(t,r,s){try{let i={value:r,expiresAt:s!==void 0?Date.now()+s*1e3:null};this.storage.setItem(this.prefix+t,JSON.stringify(i));}catch(i){console.warn("[CardDB] Failed to write to cache:",i);}}delete(t){this.storage.removeItem(this.prefix+t);}clear(){let t=[];for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t.push(s);}for(let r of t)this.storage.removeItem(r);}has(t){return this.get(t)!==null}get size(){let t=0;for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t++;}return t}cleanup(){let t=Date.now(),r=[];for(let s=0;s<this.storage.length;s++){let i=this.storage.key(s);if(i&&i.startsWith(this.prefix))try{let n=this.storage.getItem(i);if(n){let a=JSON.parse(n);a.expiresAt!==null&&t>a.expiresAt&&r.push(i);}}catch{r.push(i);}}for(let s of r)this.storage.removeItem(s);}};var l=class L extends Error{response;constructor(t,r){super(t),this.name="CardDBError",this.response=r,Error.captureStackTrace&&Error.captureStackTrace(this,L);}},D=class extends l{constructor(e="Invalid or missing API key",t){super(e,t),this.name="AuthenticationError";}},p=class extends l{retryAfter;limit;remaining;resetAt;constructor(e="Rate limit exceeded",t={}){super(e,t.response),this.name="RateLimitError",this.retryAfter=t.retryAfter??null,this.limit=t.limit??null,this.remaining=t.remaining??null,this.resetAt=t.resetAt??null;}},we=class extends l{constructor(e="Resource not found",t){super(e,t),this.name="NotFoundError";}},R=class extends l{errors;constructor(e="Validation error",t={}){super(e,t.response),this.name="ValidationError",this.errors=t.errors??[];}},S=class extends l{constructor(e,t){super(e,t),this.name="RestrictedError";}},B=class extends l{errors;constructor(e="GraphQL error",t={}){super(e,t.response),this.name="GraphQLError",this.errors=t.errors??[];}},k=class extends l{constructor(e="Connection error",t){super(e,t),this.name="ConnectionError";}},x=class extends k{constructor(e="Request timed out",t){super(e,t),this.name="TimeoutError";}},I=class extends l{status;constructor(e="Server error",t={}){super(e,t.response),this.name="ServerError",this.status=t.status??null;}},ve=class extends l{failures;partialResults;constructor(e="Some links could not be resolved",t={}){super(e,t.response),this.name="LinkResolutionError",this.failures=t.failures??[],this.partialResults=t.partialResults;}getFailuresForField(e){return this.failures.filter(t=>t.field===e)}hasFailuresForField(e){return this.failures.some(t=>t.field===e)}};function be(e){return {eq:e}}function pe(e){return {neq:e}}function $e(e){return {gt:e}}function De(e){return {gte:e}}function Re(e){return {lt:e}}function Se(e){return {lte:e}}function xe(e){return {in:e}}function Ie(e){return {nin:e}}function Pe(e){return {contains:e}}function Ee(e){return {like:e}}function Ce(e){return {ilike:e}}function Te(){return {is_null:true}}function Ke(){return {is_null:false}}var V=class A{conditions=[];orGroups=[];where(t,r){if(typeof t=="string")this.conditions.push({[t]:r});else for(let[s,i]of Object.entries(t))this.conditions.push({[s]:i});return this}any(t){let r=new A;t(r);let s=r.getConditions();return s.length>0&&this.orGroups.push({$or:s}),this}whereLink(t,r){let s={};for(let[i,n]of Object.entries(r))s[i]=n;return this.conditions.push({[`${t}._link`]:s}),this}whereAny(t,r){let s={};for(let[i,n]of Object.entries(r))s[i]=n;return this.conditions.push({[`${t}._any`]:s}),this}getConditions(){return this.conditions}build(){let t=[...this.conditions,...this.orGroups];return t.length===0?{}:t.length===1?t[0]:{$and:t}}};function P(e){if(e!==void 0){if(typeof e=="function"){let t=new V;e(t);let r=t.build();return Object.keys(r).length>0?r:void 0}return Object.keys(e).length>0?e:void 0}}var w=`
2
2
  id
3
3
  name
4
4
  slug
@@ -47,6 +47,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
47
47
  name
48
48
  description
49
49
  purpose
50
+ tcgplayerProductIdFieldKey
50
51
  visibility
51
52
  isArchived
52
53
  createdAt
@@ -61,9 +62,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
61
62
  key
62
63
  name
63
64
  }
64
- `,T=`
65
- schema {
66
- fields {
65
+ `,O=4;function U(e){return `
67
66
  key
68
67
  label
69
68
  description
@@ -76,17 +75,14 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
76
75
  displayFormat
77
76
  semanticType
78
77
  allowedValues
78
+ ${e>0?`
79
79
  nestedFields {
80
- key
81
- label
82
- description
83
- type
84
- isRequired
85
- filterable
86
- searchable
87
- itemType
88
- semanticType
89
- }
80
+ ${U(e-1)}
81
+ }`:""}
82
+ `}var T=`
83
+ schema {
84
+ fields {
85
+ ${U(O)}
90
86
  }
91
87
  filterableFields
92
88
  searchableFields
@@ -98,20 +94,33 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
98
94
  targetDatasetId
99
95
  }
100
96
  }
101
- `,f=`
102
- id
103
- datasetId
104
- data
105
- createdAt
106
- updatedAt
107
- dataset {
108
- id
109
- key
110
- name
111
- gameId
112
- publisherId
97
+ `,j=`
98
+ pricing {
99
+ productId
100
+ prices {
101
+ subTypeName
102
+ lowPrice
103
+ midPrice
104
+ highPrice
105
+ marketPrice
106
+ directLowPrice
107
+ }
113
108
  }
114
- `,p=`
109
+ `;function y(e={}){return `
110
+ id
111
+ datasetId
112
+ data
113
+ ${e.includePricing?j:""}
114
+ createdAt
115
+ updatedAt
116
+ dataset {
117
+ id
118
+ key
119
+ name
120
+ gameId
121
+ publisherId
122
+ }
123
+ `}var F=y(),b=`
115
124
  id
116
125
  deckId
117
126
  versionNumber
@@ -139,7 +148,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
139
148
  sortOrder
140
149
  annotations
141
150
  record {
142
- ${f}
151
+ ${F}
143
152
  }
144
153
  }
145
154
  `,K=`
@@ -174,7 +183,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
174
183
  sourceUrl
175
184
  metadata
176
185
  latestPublishedVersion {
177
- ${p}
186
+ ${b}
178
187
  }
179
188
  publishedAt
180
189
  hasUnpublishedChanges
@@ -193,10 +202,10 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
193
202
  sortOrder
194
203
  annotations
195
204
  record {
196
- ${f}
205
+ ${F}
197
206
  }
198
207
  }
199
- `,_=`
208
+ `,X=`
200
209
  resolvedLinks {
201
210
  field
202
211
  linkFieldKey
@@ -207,7 +216,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
207
216
  data
208
217
  }
209
218
  }
210
- `;function y(e){return `
219
+ `;function f(e){return `
211
220
  totalCount
212
221
  pageInfo {
213
222
  hasNextPage
@@ -221,10 +230,10 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
221
230
  ${e}
222
231
  }
223
232
  }
224
- `}var c={searchPublishers(e={}){let t={},r=[],s=[];e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
233
+ `}var c={searchPublishers(e={}){let t={},r=[],s=[];e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
225
234
  query SearchPublishers${i} {
226
- searchPublishers${a} {
227
- ${y(w)}
235
+ searchPublishers${n} {
236
+ ${f(w)}
228
237
  }
229
238
  }
230
239
  `,variables:t}},fetchPublisherById(){return {query:`
@@ -245,10 +254,10 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
245
254
  ${w}
246
255
  }
247
256
  }
248
- `}},searchGames(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
257
+ `}},searchGames(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
249
258
  query SearchGames${i} {
250
- searchGames${a} {
251
- ${y(m)}
259
+ searchGames${n} {
260
+ ${f(m)}
252
261
  }
253
262
  }
254
263
  `,variables:t}},fetchGameById(){return {query:`
@@ -269,10 +278,10 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
269
278
  ${m}
270
279
  }
271
280
  }
272
- `}},searchDatasets(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.gameKey!==void 0&&(s.push("$gameKey: String"),r.push("gameKey: $gameKey"),t.gameKey=e.gameKey),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.purpose!==void 0&&(s.push("$purpose: DatasetPurpose"),r.push("purpose: $purpose"),t.purpose=e.purpose),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
281
+ `}},searchDatasets(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.gameKey!==void 0&&(s.push("$gameKey: String"),r.push("gameKey: $gameKey"),t.gameKey=e.gameKey),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.purpose!==void 0&&(s.push("$purpose: DatasetPurpose"),r.push("purpose: $purpose"),t.purpose=e.purpose),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
273
282
  query SearchDatasets${i} {
274
- searchDatasets${a} {
275
- ${y(v)}
283
+ searchDatasets${n} {
284
+ ${f(v)}
276
285
  }
277
286
  }
278
287
  `,variables:t}},fetchDatasetById(){return {query:`
@@ -295,41 +304,41 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
295
304
  ${v}
296
305
  }
297
306
  }
298
- `}},searchRecords(e){let t={publisherSlug:e.publisherSlug,gameKey:e.gameKey,datasetKey:e.datasetKey},r=["publisherSlug: $publisherSlug","gameKey: $gameKey","datasetKey: $datasetKey"],s=["$publisherSlug: String!","$gameKey: String!","$datasetKey: String!"];e.filter!==void 0&&(s.push("$filter: JSON"),r.push("filter: $filter"),t.filter=e.filter),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.orderBy!==void 0&&(s.push("$orderBy: String"),r.push("orderBy: $orderBy"),t.orderBy=e.orderBy),e.resolveLinks!==void 0&&(s.push("$resolveLinks: [String!]"),r.push("resolveLinks: $resolveLinks"),t.resolveLinks=e.resolveLinks),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after),e.validateSchema!==void 0&&(s.push("$validateSchema: Boolean"),r.push("validateSchema: $validateSchema"),t.validateSchema=e.validateSchema);let a=e.resolveLinks&&e.resolveLinks.length>0?`${f}
299
- ${_}`:f;return {query:`
307
+ `}},searchRecords(e){let t={publisherSlug:e.publisherSlug,gameKey:e.gameKey,datasetKey:e.datasetKey},r=["publisherSlug: $publisherSlug","gameKey: $gameKey","datasetKey: $datasetKey"],s=["$publisherSlug: String!","$gameKey: String!","$datasetKey: String!"];e.filter!==void 0&&(s.push("$filter: JSON"),r.push("filter: $filter"),t.filter=e.filter),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.orderBy!==void 0&&(s.push("$orderBy: String"),r.push("orderBy: $orderBy"),t.orderBy=e.orderBy),e.resolveLinks!==void 0&&(s.push("$resolveLinks: [String!]"),r.push("resolveLinks: $resolveLinks"),t.resolveLinks=e.resolveLinks),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after),e.validateSchema!==void 0&&(s.push("$validateSchema: Boolean"),r.push("validateSchema: $validateSchema"),t.validateSchema=e.validateSchema);let i=e.resolveLinks&&e.resolveLinks.length>0,n=y({includePricing:e.includePricing}),a=i?`${n}
308
+ ${X}`:n;return {query:`
300
309
  query SearchRecords(${s.join(", ")}) {
301
310
  searchRecords(${r.join(", ")}) {
302
- ${y(a)}
311
+ ${f(a)}
303
312
  }
304
313
  }
305
- `,variables:t}},fetchRecordById(){return {query:`
314
+ `,variables:t}},fetchRecordById(e={}){return {query:`
306
315
  query FetchRecord($id: UUID!) {
307
316
  fetchRecord(id: $id) {
308
- ${f}
317
+ ${y(e)}
309
318
  }
310
319
  }
311
- `}},fetchRecordByIdentifier(){return {query:`
320
+ `}},fetchRecordByIdentifier(e={}){return {query:`
312
321
  query FetchRecordByIdentifier($publisherSlug: String!, $gameKey: String!, $datasetKey: String!, $identifier: String!) {
313
322
  fetchRecordByIdentifier(publisherSlug: $publisherSlug, gameKey: $gameKey, datasetKey: $datasetKey, identifier: $identifier) {
314
- ${f}
323
+ ${y(e)}
315
324
  }
316
325
  }
317
- `}},fetchRecordsByIdentifier(){return {query:`
326
+ `}},fetchRecordsByIdentifier(e={}){return {query:`
318
327
  query FetchRecordsByIdentifier($publisherSlug: String!, $gameKey: String!, $datasetKey: String!, $identifiers: [String!]!) {
319
328
  fetchRecordsByIdentifier(publisherSlug: $publisherSlug, gameKey: $gameKey, datasetKey: $datasetKey, identifiers: $identifiers) {
320
- ${f}
329
+ ${y(e)}
321
330
  }
322
331
  }
323
- `}},fetchRecords(){return {query:`
332
+ `}},fetchRecords(e={}){return {query:`
324
333
  query FetchRecords($ids: [UUID!]!) {
325
334
  fetchRecords(ids: $ids) {
326
- ${f}
335
+ ${y(e)}
327
336
  }
328
337
  }
329
- `}},listMyDecks(e={}){let t={},r=[],s=[];e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
338
+ `}},listMyDecks(e={}){let t={},r=[],s=[];e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
330
339
  query MyDecks${i} {
331
- myDecks${a} {
332
- ${y(d)}
340
+ myDecks${n} {
341
+ ${f(d)}
333
342
  }
334
343
  }
335
344
  `,variables:t}},fetchDeckById(){return {query:`
@@ -359,13 +368,13 @@ ${_}`:f;return {query:`
359
368
  `}},deckVersion(){return {query:`
360
369
  query DeckVersion($id: UUID!) {
361
370
  deckVersion(id: $id) {
362
- ${p}
371
+ ${b}
363
372
  }
364
373
  }
365
374
  `}},deckVersions(e={}){let t={},r=["deckId: $deckId"],s=["$deckId: UUID!"];return e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after),{query:`
366
375
  query DeckVersions(${s.join(", ")}) {
367
376
  deckVersions(${r.join(", ")}) {
368
- ${y(p)}
377
+ ${f(b)}
369
378
  }
370
379
  }
371
380
  `,variables:t}},deckPreview(){return {query:`
@@ -405,7 +414,7 @@ ${_}`:f;return {query:`
405
414
  `}},publishDeck(){return {query:`
406
415
  mutation DeckPublish($id: UUID!, $input: DeckPublishInput!) {
407
416
  deckPublish(id: $id, input: $input) {
408
- ${p}
417
+ ${b}
409
418
  }
410
419
  }
411
420
  `}},upsertDeckCollaborator(){return {query:`
@@ -453,6 +462,6 @@ ${_}`:f;return {query:`
453
462
  }
454
463
  }
455
464
  }
456
- `}}},h=class{totalCount;pageInfo;items;nextPageLoader;constructor(e,t={}){this.totalCount=e.totalCount,this.pageInfo=e.pageInfo,this.items=e.edges.map(r=>t.itemTransformer?t.itemTransformer(r.node):r.node),this.nextPageLoader=t.nextPageLoader;}get hasNextPage(){return this.pageInfo.hasNextPage}get hasPreviousPage(){return this.pageInfo.hasPreviousPage}get endCursor(){return this.pageInfo.endCursor}get startCursor(){return this.pageInfo.startCursor}get length(){return this.items.length}get isEmpty(){return this.items.length===0}get first(){return this.items[0]}get last(){return this.items[this.items.length-1]}async nextPage(){if(!this.hasNextPage)return null;if(!this.nextPageLoader)throw new Error("No next page loader configured");return this.endCursor?this.nextPageLoader(this.endCursor):null}async*[Symbol.asyncIterator](){let e=this;for(;e;){for(let t of e.items)yield t;if(!e.hasNextPage)break;e=await e.nextPage();}}async forEach(e){let t=0;for await(let r of this)await e(r,t++);}async map(e){let t=[],r=0;for await(let s of this)t.push(await e(s,r++));return t}async filter(e){let t=[],r=0;for await(let s of this)await e(s,r++)&&t.push(s);return t}async find(e){let t=0;for await(let r of this)if(await e(r,t++))return r}async take(e){let t=[];for await(let r of this){if(t.length>=e)break;t.push(r);}return t}async toArray(){let e=[];for await(let t of this)e.push(t);return e}async*batches(){let e=this;for(;e&&(e.items.length>0&&(yield e.items),!!e.hasNextPage);)e=await e.nextPage();}each(){return this}};var V="https://carddb.xtda.org/query",O=3e4,j=1e4,X=300,Q=3,J=2,W=1e3,H=3e4,Y=class U{apiKey;endpoint;timeout;openTimeout;defaultPublisher;defaultGame;allowedPublishers;allowedGames;logger;logLevel;retryOnRateLimit;maxRetries;retryOnNetworkError;maxNetworkRetries;retryBaseDelay;retryMaxDelay;cache;cacheTtl;cacheTtls;constructor(t={}){this.apiKey=t.apiKey,this.endpoint=t.endpoint??V,this.timeout=t.timeout??O,this.openTimeout=t.openTimeout??j,this.defaultPublisher=t.defaultPublisher,this.defaultGame=t.defaultGame,this.allowedPublishers=t.allowedPublishers,this.allowedGames=t.allowedGames,this.logger=t.logger,this.logLevel=t.logLevel??"info",this.retryOnRateLimit=t.retryOnRateLimit??false,this.maxRetries=t.maxRetries??Q,this.retryOnNetworkError=t.retryOnNetworkError??true,this.maxNetworkRetries=t.maxNetworkRetries??J,this.retryBaseDelay=t.retryBaseDelay??W,this.retryMaxDelay=t.retryMaxDelay??H,this.cache=t.cache,this.cacheTtl=t.cacheTtl??X,this.cacheTtls=t.cacheTtls??{};}calculateRetryDelay(t){let r=this.retryBaseDelay*Math.pow(2,t),s=Math.min(r,this.retryMaxDelay),i=s*.25*(Math.random()*2-1);return Math.round(s+i)}cacheTtlFor(t){return this.cacheTtls[t]??this.cacheTtl}resolvePublisher(t){return t??this.defaultPublisher}resolveGame(t){return t??this.defaultGame}validatePublisher(t){if(this.allowedPublishers&&!this.allowedPublishers.includes(t))throw new x(`Publisher '${t}' is not in the allowed publishers list`)}validateGame(t,r){if(!this.allowedGames)return;let s=this.allowedGames[t];if(s&&!s.includes(r))throw new x(`Game '${r}' is not allowed for publisher '${t}'`)}validateAccess(t,r){t&&(this.validatePublisher(t),r&&this.validateGame(t,r));}shouldLog(t){let r={debug:0,info:1,warn:2,error:3};return r[t]>=r[this.logLevel]}merge(t){return new U({apiKey:t.apiKey??this.apiKey,endpoint:t.endpoint??this.endpoint,timeout:t.timeout??this.timeout,openTimeout:t.openTimeout??this.openTimeout,defaultPublisher:t.defaultPublisher??this.defaultPublisher,defaultGame:t.defaultGame??this.defaultGame,allowedPublishers:t.allowedPublishers??this.allowedPublishers,allowedGames:t.allowedGames??this.allowedGames,logger:t.logger??this.logger,logLevel:t.logLevel??this.logLevel,retryOnRateLimit:t.retryOnRateLimit??this.retryOnRateLimit,maxRetries:t.maxRetries??this.maxRetries,retryOnNetworkError:t.retryOnNetworkError??this.retryOnNetworkError,maxNetworkRetries:t.maxNetworkRetries??this.maxNetworkRetries,retryBaseDelay:t.retryBaseDelay??this.retryBaseDelay,retryMaxDelay:t.retryMaxDelay??this.retryMaxDelay,cache:t.cache??this.cache,cacheTtl:t.cacheTtl??this.cacheTtl,cacheTtls:t.cacheTtls??this.cacheTtls})}},F="0.1.0";function z(){if(typeof globalThis<"u"&&"Bun"in globalThis){let e=globalThis.Bun&&typeof globalThis.Bun=="object"&&globalThis.Bun.version;return {name:"bun",version:typeof e=="string"?e:"unknown"}}if(typeof globalThis<"u"&&"Deno"in globalThis){let e=globalThis.Deno&&typeof globalThis.Deno=="object"&&globalThis.Deno.version&&typeof globalThis.Deno.version=="object"&&globalThis.Deno.version.deno;return {name:"deno",version:typeof e=="string"?e:"unknown"}}return typeof process<"u"&&process.versions&&process.versions.node?{name:"node",version:process.versions.node}:typeof navigator<"u"&&navigator.userAgent?Z(navigator.userAgent):{name:"unknown",version:"unknown"}}function Z(e){let t=e.match(/Edg\/(\d+(?:\.\d+)*)/);if(t)return {name:"edge",version:t[1]};let r=e.match(/Chrome\/(\d+(?:\.\d+)*)/);if(r&&!e.includes("Edg/"))return {name:"chrome",version:r[1]};let s=e.match(/Firefox\/(\d+(?:\.\d+)*)/);if(s)return {name:"firefox",version:s[1]};let i=e.match(/Version\/(\d+(?:\.\d+)*).*Safari/);return i?{name:"safari",version:i[1]}:{name:"browser",version:"unknown"}}function ee(){let e=z();return `CardDB-SDK/js/${F} (${e.name}/${e.version})`}function _e(){return F}var N=null;function te(){return N}var re=class{config;constructor(e){this.config=e;}async execute(e,t={}){let r=this.extractOperationName(e),s=0,i=0;for(;;)try{let a=Date.now();this.logRequest(r,t);let n=await this.fetch(e,t),o=Date.now()-a,u=await this.handleResponse(n);return this.logResponse(r,o),u}catch(a){if(a instanceof b&&this.config.retryOnRateLimit&&s<this.config.maxRetries){s++;let n=a.retryAfter??60;this.logRateLimitRetry(r,s,n),await this.sleep(n*1e3);continue}if(this.isRetryableNetworkError(a)&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let n=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,n,a),i++,await this.sleep(n);continue}if(a instanceof I&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let n=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,n,a),i++,await this.sleep(n);continue}throw a}}isRetryableNetworkError(e){return e instanceof k||e instanceof S}async fetch(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{return await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":ee(),...this.config.apiKey?{"X-API-Key":this.config.apiKey}:{}},body:JSON.stringify({query:e,variables:t}),signal:r.signal})}catch(i){throw i instanceof Error?i.name==="AbortError"?(this.logError("Request timed out"),new S("Request timed out")):(this.logError(`Connection failed: ${i.message}`),new k(`Connection failed: ${i.message}`)):new k("Connection failed")}finally{clearTimeout(s);}}async handleResponse(e){switch(this.extractRateLimitInfo(e),e.status){case 200:return this.handleSuccessResponse(e);case 401:throw new D("Invalid or missing API key");case 429:return this.handleRateLimitResponse(e);default:if(e.status>=400&&e.status<500)return this.handleClientError(e);if(e.status>=500){let t=await this.parseBody(e);throw new I(`Server error (${e.status})`,{status:e.status,response:t})}throw new l(`Unexpected response status: ${e.status}`)}}async handleSuccessResponse(e){let t=await this.parseBody(e);return t.errors&&t.errors.length>0&&this.handleGraphQLErrors(t.errors,t),t.data??{}}handleGraphQLErrors(e,t){let r=e[0],s=r.message||"GraphQL error";switch(r.extensions?.code){case "UNAUTHENTICATED":throw new D(s,t);case "RATE_LIMITED":throw new b(s,{response:t});case "NOT_FOUND":throw new l(s,t);case "VALIDATION_ERROR":case "BAD_USER_INPUT":throw new R(s,{errors:e,response:t});default:throw new B(s,{errors:e,response:t})}}async handleRateLimitResponse(e){let t=parseInt(e.headers.get("Retry-After")??"60",10),r=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,i=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null,a=i?new Date(i*1e3):null,n=await this.parseBody(e);throw new b("Rate limit exceeded",{retryAfter:t,limit:r,remaining:s,resetAt:a,response:n})}async handleClientError(e){let t=await this.parseBody(e),r=t.errors?.[0]?.message??`Client error (${e.status})`;throw new R(r,{response:t})}async parseBody(e){try{return await e.json()}catch{return {raw:await e.text()}}}extractRateLimitInfo(e){let t=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,r=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null;N={limit:t,remaining:r,reset:s};}extractOperationName(e){let t=e.match(/(?:query|mutation)\s+(\w+)/);return t?t[1]:"Unknown"}sleep(e){return new Promise(t=>setTimeout(t,e))}logRequest(e,t){!this.config.logger||!this.config.shouldLog("debug")||this.config.logger.debug(`[CardDB] Executing ${e}`,{variables:t});}logResponse(e,t){!this.config.logger||!this.config.shouldLog("info")||this.config.logger.info(`[CardDB] ${e} completed in ${t}ms`);}logRateLimitRetry(e,t,r){!this.config.logger||!this.config.shouldLog("warn")||this.config.logger.warn(`[CardDB] Rate limited on ${e}, retry ${t}/${this.config.maxRetries} after ${r}s`);}logNetworkRetry(e,t,r,s){if(!this.config.logger||!this.config.shouldLog("warn"))return;let i=s instanceof Error?s.name:"Unknown";this.config.logger.warn(`[CardDB] ${i} on ${e}, retry ${t}/${this.config.maxNetworkRetries} after ${r}ms`);}logError(e){!this.config.logger||!this.config.shouldLog("error")||this.config.logger.error(`[CardDB] ${e}`);}};function se(e,t,r){let s=Object.entries(r).filter(([,i])=>i!==void 0).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}=${JSON.stringify(a)}`).join("&");return `carddb:${e}:${t}:${s}`}async function ie(e,t){let r=e.get(t);return r}async function ae(e,t,r,s){let i=e.set(t,r,s);i instanceof Promise&&await i;}var g=class{connection;config;constructor(e,t){this.connection=e,this.config=t;}resolvePublisher(e){let t=this.config.resolvePublisher(e);if(!t)throw new Error("publisher_slug is required (no default configured)");return t}resolveGame(e){let t=this.config.resolveGame(e);if(!t)throw new Error("game_key is required (no default configured)");return t}validateAccess(e,t){this.config.validateAccess(e,t);}async withCache(e,t,r,s){let i=r.cache??!!this.config.cache,a=this.config.cache;if(!i||!a)return s();let n=await ie(a,e);if(n!==null)return n;let o=await s();if(o!=null){let u=this.config.cacheTtlFor(t);await ae(a,e,o,u);}return o}cacheKey(e,t,r){return se(e,t,r)}},ne=class extends g{constructor(e,t){super(e,t);}async search(e={}){let{query:t,variables:r}=c.searchPublishers({search:e.search,first:e.first,after:e.after}),s=this.cacheKey("publishers","search",r),i=await this.withCache(s,"publishers",e,async()=>(await this.connection.execute(t,r)).searchPublishers);return new h(i,{nextPageLoader:async a=>this.search({...e,after:a})})}async get(e,t={}){let r=this.isUUID(e),s=this.cacheKey("publishers","get",{[r?"id":"slug"]:e});return this.withCache(s,"publishers",t,async()=>{if(r){let{query:i}=c.fetchPublisherById();return (await this.connection.execute(i,{id:e})).fetchPublisher??null}else {let{query:i}=c.fetchPublisherBySlug();return (await this.connection.execute(i,{slug:e})).fetchPublisher??null}})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("publishers","getMany",{slugs:e});return this.withCache(r,"publishers",t,async()=>{let{query:s}=c.fetchPublishers();return (await this.connection.execute(s,{slugs:e})).fetchPublishers??[]})}isUUID(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}},ce=class extends g{constructor(e,t){super(e,t);}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug);t&&this.validateAccess(t);let{query:r,variables:s}=c.searchGames({publisherSlug:t,search:e.search,first:e.first,after:e.after}),i=this.cacheKey("games","search",s),a=await this.withCache(i,"games",e,async()=>(await this.connection.execute(r,s)).searchGames);return new h(a,{nextPageLoader:async n=>this.search({...e,after:n})})}async get(e,t,r){if(typeof t=="string"){let s=e,i=t,a=r??{};this.validateAccess(s,i);let n=this.cacheKey("games","getByKeys",{publisherSlug:s,gameKey:i});return this.withCache(n,"games",a,async()=>{let{query:o}=c.fetchGameByKeys();return (await this.connection.execute(o,{publisherSlug:s,gameKey:i})).fetchGame??null})}else {let s=e,i=t??{},a=this.cacheKey("games","get",{id:s});return this.withCache(a,"games",i,async()=>{let{query:n}=c.fetchGameById();return (await this.connection.execute(n,{id:s})).fetchGame??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("games","getMany",{ids:e});return this.withCache(r,"games",t,async()=>{let{query:s}=c.fetchGames();return (await this.connection.execute(s,{ids:e})).fetchGames??[]})}},oe=class extends g{constructor(e,t){super(e,t);}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug),r=this.config.resolveGame(e.gameKey);t&&this.validateAccess(t,r);let{query:s,variables:i}=c.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:e.purpose,first:e.first,after:e.after}),a=this.cacheKey("datasets","search",i),n=await this.withCache(a,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new h(n,{nextPageLoader:async o=>this.search({...e,after:o})})}async get(e,t,r,s){if(typeof t=="string"&&typeof r=="string"){let i=e,a=t,n=s??{};this.validateAccess(i,a);let o=this.cacheKey("datasets","getByKeys",{publisherSlug:i,gameKey:a,datasetKey:r});return this.withCache(o,"datasets",n,async()=>{let{query:u}=c.fetchDatasetByKeys();return (await this.connection.execute(u,{publisherSlug:i,gameKey:a,datasetKey:r})).fetchDataset??null})}else {let i=e,a=t??{},n=this.cacheKey("datasets","get",{id:i});return this.withCache(n,"datasets",a,async()=>{let{query:o}=c.fetchDatasetById();return (await this.connection.execute(o,{id:i})).fetchDataset??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("datasets","getMany",{ids:e});return this.withCache(r,"datasets",t,async()=>{let{query:s}=c.fetchDatasets();return (await this.connection.execute(s,{ids:e})).fetchDatasets??[]})}},ue=class extends g{constructor(e,t){super(e,t);}async fetch(e,t={}){let r=this.cacheKey("decks","fetch",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.fetchDeckById();return (await this.connection.execute(s,{id:e})).fetchDeck??null})}async fetchMine(e,t={}){let r=this.cacheKey("decks","fetchMine",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.myDeck();return (await this.connection.execute(s,{id:e})).myDeck??null})}async fetchBySlug(e,t,r,s={}){let i=this.cacheKey("decks","fetchBySlug",{publisherSlug:e,gameKey:t,slug:r});return this.withCache(i,"decks",s,async()=>{let{query:a}=c.fetchDeckBySlug();return (await this.connection.execute(a,{publisherSlug:e,gameKey:t,slug:r})).fetchDeckBySlug??null})}async fetchByExternalRef(e,t={}){let r=this.cacheKey("decks","fetchByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.fetchDeckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).fetchDeckByExternalRef??null})}async listMine(e={}){let{query:t,variables:r}=c.listMyDecks({first:e.first,after:e.after}),s=this.cacheKey("decks","listMine",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).myDecks);return new h(i,{nextPageLoader:async a=>this.listMine({...e,after:a})})}async fetchVersion(e,t={}){let r=this.cacheKey("decks","fetchVersion",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckVersion();return (await this.connection.execute(s,{id:e})).deckVersion??null})}async listVersions(e,t={}){let{query:r,variables:s}=c.deckVersions({first:t.first,after:t.after}),i={deckId:e,...s},a=this.cacheKey("decks","listVersions",i),n=await this.withCache(a,"decks",t,async()=>(await this.connection.execute(r,i)).deckVersions);return new h(n,{nextPageLoader:async o=>this.listVersions(e,{...t,after:o})})}async preview(e,t={}){let r=this.cacheKey("decks","preview",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckPreview();return (await this.connection.execute(s,{token:e})).deckPreview??null})}async listCollaborators(e,t={}){let r=this.cacheKey("decks","listCollaborators",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckCollaborators();return (await this.connection.execute(s,{deckId:e})).deckCollaborators})}async listPreviewTokens(e,t={}){let r=this.cacheKey("decks","listPreviewTokens",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckPreviewTokens();return (await this.connection.execute(s,{deckId:e})).deckPreviewTokens})}async create(e){let{query:t}=c.createDeck(),r=c.deckCreateVariables(e);return (await this.connection.execute(t,r)).deckCreate}async update(e,t){let{query:r}=c.updateDeck(),s=c.deckUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckUpdate}async delete(e){let{query:t}=c.deleteDeck();return !!(await this.connection.execute(t,{id:e})).deckDelete}async publish(e,t={}){let{query:r}=c.publishDeck(),s=c.deckPublishVariables(e,t);return (await this.connection.execute(r,s)).deckPublish}async upsertCollaborator(e,t,r){let{query:s}=c.upsertDeckCollaborator(),i=c.deckCollaboratorVariables(e,t,r);return (await this.connection.execute(s,i)).deckCollaboratorUpsert}async removeCollaborator(e,t){let{query:r}=c.removeDeckCollaborator(),s=c.deckCollaboratorVariables(e,t);return !!(await this.connection.execute(r,s)).deckCollaboratorRemove}async createPreviewToken(e){let{query:t}=c.createDeckPreviewToken(),r=c.deckPreviewTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckPreviewTokenCreate}async revokePreviewToken(e){let{query:t}=c.revokeDeckPreviewToken();return !!(await this.connection.execute(t,{id:e})).deckPreviewTokenRevoke}async hydrateEntries(e){if(e.entries.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=e.entries.map(o=>o.identifier),i=this.cacheKey("decks","hydrateEntries",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s}),a=await this.withCache(i,"decks",e,async()=>{let{query:o}=c.fetchRecordsByIdentifier();return (await this.connection.execute(o,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s})).fetchRecordsByIdentifier}),n=le(a,s,e.identifierField);return e.entries.map(o=>({...o,record:n.get(o.identifier)??null}))}};function le(e,t,r){let s=new Set(t),i=new Map;for(let a of e){let n=r?a.data[r]:Object.values(a.data).find(u=>s.has(String(u)));if(n==null)continue;let o=String(n);s.has(o)&&(i.set(o,a),s.delete(o));}return i}var he=class extends g{constructor(e,t){super(e,t);}async search(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=C(e.filter),{query:i,variables:a}=c.searchRecords({publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,filter:s,search:e.search,orderBy:e.orderBy,resolveLinks:e.resolveLinks,first:e.first,after:e.after,validateSchema:e.validateSchema}),n=this.cacheKey("records","search",a),o=await this.withCache(n,"records",e,async()=>(await this.connection.execute(i,a)).searchRecords);return new h(o,{nextPageLoader:async u=>this.search({...e,after:u})})}async get(e,t={}){let r=this.cacheKey("records","get",{id:e});return this.withCache(r,"records",t,async()=>{let{query:s}=c.fetchRecordById();return (await this.connection.execute(s,{id:e})).fetchRecord??null})}async getByIdentifier(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier});return this.withCache(s,"records",e,async()=>{let{query:i}=c.fetchRecordByIdentifier();return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier})).fetchRecordByIdentifier??null})}async getManyByIdentifier(e){if(e.identifiers.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getManyByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers});return this.withCache(s,"records",e,async()=>{let{query:i}=c.fetchRecordsByIdentifier();return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers})).fetchRecordsByIdentifier??[]})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("records","getMany",{ids:e});return this.withCache(r,"records",t,async()=>{let{query:s}=c.fetchRecords();return (await this.connection.execute(s,{ids:e})).fetchRecords??[]})}},de=class extends g{constructor(e,t){super(e,t);}async datasets(e={}){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let{query:s,variables:i}=c.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:"RULES",first:e.first,after:e.after}),a=this.cacheKey("rules","datasets",i),n=await this.withCache(a,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new h(n,{nextPageLoader:async o=>this.datasets({...e,after:o})})}async list(e={}){return this.searchRuleRecords("rules",e)}async formats(e={}){return this.searchRuleRecords(e.datasetKey??"formats",e)}async searchRuleRecords(e,t){let r=this.resolvePublisher(t.publisherSlug),s=this.resolveGame(t.gameKey),i=t.datasetKey??e;this.validateAccess(r,s);let a=C(t.filter),{query:n,variables:o}=c.searchRecords({publisherSlug:r,gameKey:s,datasetKey:i,filter:a,search:t.search,orderBy:t.orderBy,resolveLinks:t.resolveLinks,first:t.first,after:t.after,validateSchema:t.validateSchema}),u=this.cacheKey("rules","records",o),E=await this.withCache(u,"records",t,async()=>(await this.connection.execute(n,o)).searchRecords);return new h(E,{nextPageLoader:async P=>this.searchRuleRecords(e,{...t,after:P})})}},Ve=class G{config;connection;publishers;games;datasets;records;decks;rules;constructor(t={}){this.config=new Y(t),this.connection=new re(this.config),this.publishers=new ne(this.connection,this.config),this.games=new ce(this.connection,this.config),this.datasets=new oe(this.connection,this.config),this.records=new he(this.connection,this.config),this.decks=new ue(this.connection,this.config),this.rules=new de(this.connection,this.config);}async me(){let{query:t}=c.fetchMe();return (await this.connection.execute(t)).fetchMe??null}getRateLimitInfo(){return te()}withConfig(t){let r=this.config.merge(t);return new G({apiKey:r.apiKey,endpoint:r.endpoint,timeout:r.timeout,openTimeout:r.openTimeout,defaultPublisher:r.defaultPublisher,defaultGame:r.defaultGame,allowedPublishers:r.allowedPublishers,allowedGames:r.allowedGames,logger:r.logger,logLevel:r.logLevel,retryOnRateLimit:r.retryOnRateLimit,maxRetries:r.maxRetries,retryOnNetworkError:r.retryOnNetworkError,maxNetworkRetries:r.maxNetworkRetries,retryBaseDelay:r.retryBaseDelay,retryMaxDelay:r.retryMaxDelay,cache:r.cache,cacheTtl:r.cacheTtl,cacheTtls:r.cacheTtls})}};
457
- export{D as AuthenticationError,g as BaseResource,$ as BrowserCache,Ve as CardDBClient,l as CardDBError,h as Collection,Y as Configuration,re as Connection,k as ConnectionError,X as DEFAULT_CACHE_TTL,V as DEFAULT_ENDPOINT,J as DEFAULT_MAX_NETWORK_RETRIES,Q as DEFAULT_MAX_RETRIES,j as DEFAULT_OPEN_TIMEOUT,W as DEFAULT_RETRY_BASE_DELAY,H as DEFAULT_RETRY_MAX_DELAY,O as DEFAULT_TIMEOUT,oe as DatasetsResource,ue as DecksResource,M as FilterBuilder,ce as GamesResource,B as GraphQLError,ge as LinkResolutionError,ye as NotFoundError,ne as PublishersResource,c as QueryBuilder,b as RateLimitError,he as RecordsResource,x as RestrictedError,de as RulesResource,I as ServerError,S as TimeoutError,R as ValidationError,se as cacheKey,Re as contains,me as eq,te as getRateLimitInfo,_e as getSDKVersion,ee as getUserAgent,we as gt,ve as gte,Se as ilike,Ce as isNotNull,Ie as isNull,xe as like,pe as lt,be as lte,ke as neq,De as notWithin,ie as readCache,C as resolveFilter,$e as within,ae as writeCache};//# sourceMappingURL=index.js.map
465
+ `}}},h=class{totalCount;pageInfo;items;nextPageLoader;constructor(e,t={}){this.totalCount=e.totalCount,this.pageInfo=e.pageInfo,this.items=e.edges.map(r=>t.itemTransformer?t.itemTransformer(r.node):r.node),this.nextPageLoader=t.nextPageLoader;}get hasNextPage(){return this.pageInfo.hasNextPage}get hasPreviousPage(){return this.pageInfo.hasPreviousPage}get endCursor(){return this.pageInfo.endCursor}get startCursor(){return this.pageInfo.startCursor}get length(){return this.items.length}get isEmpty(){return this.items.length===0}get first(){return this.items[0]}get last(){return this.items[this.items.length-1]}async nextPage(){if(!this.hasNextPage)return null;if(!this.nextPageLoader)throw new Error("No next page loader configured");return this.endCursor?this.nextPageLoader(this.endCursor):null}async*[Symbol.asyncIterator](){let e=this;for(;e;){for(let t of e.items)yield t;if(!e.hasNextPage)break;e=await e.nextPage();}}async forEach(e){let t=0;for await(let r of this)await e(r,t++);}async map(e){let t=[],r=0;for await(let s of this)t.push(await e(s,r++));return t}async filter(e){let t=[],r=0;for await(let s of this)await e(s,r++)&&t.push(s);return t}async find(e){let t=0;for await(let r of this)if(await e(r,t++))return r}async take(e){let t=[];for await(let r of this){if(t.length>=e)break;t.push(r);}return t}async toArray(){let e=[];for await(let t of this)e.push(t);return e}async*batches(){let e=this;for(;e&&(e.items.length>0&&(yield e.items),!!e.hasNextPage);)e=await e.nextPage();}each(){return this}};var Q="https://carddb.xtda.org/query",H=3e4,J=1e4,W=300,Y=3,z=2,Z=1e3,ee=3e4,te=class N{apiKey;endpoint;timeout;openTimeout;defaultPublisher;defaultGame;allowedPublishers;allowedGames;logger;logLevel;retryOnRateLimit;maxRetries;retryOnNetworkError;maxNetworkRetries;retryBaseDelay;retryMaxDelay;cache;cacheTtl;cacheTtls;constructor(t={}){this.apiKey=t.apiKey,this.endpoint=t.endpoint??Q,this.timeout=t.timeout??H,this.openTimeout=t.openTimeout??J,this.defaultPublisher=t.defaultPublisher,this.defaultGame=t.defaultGame,this.allowedPublishers=t.allowedPublishers,this.allowedGames=t.allowedGames,this.logger=t.logger,this.logLevel=t.logLevel??"info",this.retryOnRateLimit=t.retryOnRateLimit??false,this.maxRetries=t.maxRetries??Y,this.retryOnNetworkError=t.retryOnNetworkError??true,this.maxNetworkRetries=t.maxNetworkRetries??z,this.retryBaseDelay=t.retryBaseDelay??Z,this.retryMaxDelay=t.retryMaxDelay??ee,this.cache=t.cache,this.cacheTtl=t.cacheTtl??W,this.cacheTtls=t.cacheTtls??{};}calculateRetryDelay(t){let r=this.retryBaseDelay*Math.pow(2,t),s=Math.min(r,this.retryMaxDelay),i=s*.25*(Math.random()*2-1);return Math.round(s+i)}cacheTtlFor(t){return this.cacheTtls[t]??this.cacheTtl}resolvePublisher(t){return t??this.defaultPublisher}resolveGame(t){return t??this.defaultGame}validatePublisher(t){if(this.allowedPublishers&&!this.allowedPublishers.includes(t))throw new S(`Publisher '${t}' is not in the allowed publishers list`)}validateGame(t,r){if(!this.allowedGames)return;let s=this.allowedGames[t];if(s&&!s.includes(r))throw new S(`Game '${r}' is not allowed for publisher '${t}'`)}validateAccess(t,r){t&&(this.validatePublisher(t),r&&this.validateGame(t,r));}shouldLog(t){let r={debug:0,info:1,warn:2,error:3};return r[t]>=r[this.logLevel]}merge(t){return new N({apiKey:t.apiKey??this.apiKey,endpoint:t.endpoint??this.endpoint,timeout:t.timeout??this.timeout,openTimeout:t.openTimeout??this.openTimeout,defaultPublisher:t.defaultPublisher??this.defaultPublisher,defaultGame:t.defaultGame??this.defaultGame,allowedPublishers:t.allowedPublishers??this.allowedPublishers,allowedGames:t.allowedGames??this.allowedGames,logger:t.logger??this.logger,logLevel:t.logLevel??this.logLevel,retryOnRateLimit:t.retryOnRateLimit??this.retryOnRateLimit,maxRetries:t.maxRetries??this.maxRetries,retryOnNetworkError:t.retryOnNetworkError??this.retryOnNetworkError,maxNetworkRetries:t.maxNetworkRetries??this.maxNetworkRetries,retryBaseDelay:t.retryBaseDelay??this.retryBaseDelay,retryMaxDelay:t.retryMaxDelay??this.retryMaxDelay,cache:t.cache??this.cache,cacheTtl:t.cacheTtl??this.cacheTtl,cacheTtls:t.cacheTtls??this.cacheTtls})}},G="0.1.0";function re(){if(typeof globalThis<"u"&&"Bun"in globalThis){let e=globalThis.Bun&&typeof globalThis.Bun=="object"&&globalThis.Bun.version;return {name:"bun",version:typeof e=="string"?e:"unknown"}}if(typeof globalThis<"u"&&"Deno"in globalThis){let e=globalThis.Deno&&typeof globalThis.Deno=="object"&&globalThis.Deno.version&&typeof globalThis.Deno.version=="object"&&globalThis.Deno.version.deno;return {name:"deno",version:typeof e=="string"?e:"unknown"}}return typeof process<"u"&&process.versions&&process.versions.node?{name:"node",version:process.versions.node}:typeof navigator<"u"&&navigator.userAgent?se(navigator.userAgent):{name:"unknown",version:"unknown"}}function se(e){let t=e.match(/Edg\/(\d+(?:\.\d+)*)/);if(t)return {name:"edge",version:t[1]};let r=e.match(/Chrome\/(\d+(?:\.\d+)*)/);if(r&&!e.includes("Edg/"))return {name:"chrome",version:r[1]};let s=e.match(/Firefox\/(\d+(?:\.\d+)*)/);if(s)return {name:"firefox",version:s[1]};let i=e.match(/Version\/(\d+(?:\.\d+)*).*Safari/);return i?{name:"safari",version:i[1]}:{name:"browser",version:"unknown"}}function ie(){let e=re();return `CardDB-SDK/js/${G} (${e.name}/${e.version})`}function Xe(){return G}var M=null;function ne(){return M}var ae=class{config;constructor(e){this.config=e;}async execute(e,t={}){let r=this.extractOperationName(e),s=0,i=0;for(;;)try{let n=Date.now();this.logRequest(r,t);let a=await this.fetch(e,t),o=Date.now()-n,u=await this.handleResponse(a);return this.logResponse(r,o),u}catch(n){if(n instanceof p&&this.config.retryOnRateLimit&&s<this.config.maxRetries){s++;let a=n.retryAfter??60;this.logRateLimitRetry(r,s,a),await this.sleep(a*1e3);continue}if(this.isRetryableNetworkError(n)&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let a=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,a,n),i++,await this.sleep(a);continue}if(n instanceof I&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let a=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,a,n),i++,await this.sleep(a);continue}throw n}}isRetryableNetworkError(e){return e instanceof k||e instanceof x}async fetch(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{return await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":ie(),...this.config.apiKey?{"X-API-Key":this.config.apiKey}:{}},body:JSON.stringify({query:e,variables:t}),signal:r.signal})}catch(i){throw i instanceof Error?i.name==="AbortError"?(this.logError("Request timed out"),new x("Request timed out")):(this.logError(`Connection failed: ${i.message}`),new k(`Connection failed: ${i.message}`)):new k("Connection failed")}finally{clearTimeout(s);}}async handleResponse(e){switch(this.extractRateLimitInfo(e),e.status){case 200:return this.handleSuccessResponse(e);case 401:throw new D("Invalid or missing API key");case 429:return this.handleRateLimitResponse(e);default:if(e.status>=400&&e.status<500)return this.handleClientError(e);if(e.status>=500){let t=await this.parseBody(e);throw new I(`Server error (${e.status})`,{status:e.status,response:t})}throw new l(`Unexpected response status: ${e.status}`)}}async handleSuccessResponse(e){let t=await this.parseBody(e);return t.errors&&t.errors.length>0&&this.handleGraphQLErrors(t.errors,t),t.data??{}}handleGraphQLErrors(e,t){let r=e[0],s=r.message||"GraphQL error";switch(r.extensions?.code){case "UNAUTHENTICATED":throw new D(s,t);case "RATE_LIMITED":throw new p(s,{response:t});case "NOT_FOUND":throw new l(s,t);case "VALIDATION_ERROR":case "BAD_USER_INPUT":throw new R(s,{errors:e,response:t});default:throw new B(s,{errors:e,response:t})}}async handleRateLimitResponse(e){let t=parseInt(e.headers.get("Retry-After")??"60",10),r=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,i=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null,n=i?new Date(i*1e3):null,a=await this.parseBody(e);throw new p("Rate limit exceeded",{retryAfter:t,limit:r,remaining:s,resetAt:n,response:a})}async handleClientError(e){let t=await this.parseBody(e),r=t.errors?.[0]?.message??`Client error (${e.status})`;throw new R(r,{response:t})}async parseBody(e){try{return await e.json()}catch{return {raw:await e.text()}}}extractRateLimitInfo(e){let t=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,r=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null;M={limit:t,remaining:r,reset:s};}extractOperationName(e){let t=e.match(/(?:query|mutation)\s+(\w+)/);return t?t[1]:"Unknown"}sleep(e){return new Promise(t=>setTimeout(t,e))}logRequest(e,t){!this.config.logger||!this.config.shouldLog("debug")||this.config.logger.debug(`[CardDB] Executing ${e}`,{variables:t});}logResponse(e,t){!this.config.logger||!this.config.shouldLog("info")||this.config.logger.info(`[CardDB] ${e} completed in ${t}ms`);}logRateLimitRetry(e,t,r){!this.config.logger||!this.config.shouldLog("warn")||this.config.logger.warn(`[CardDB] Rate limited on ${e}, retry ${t}/${this.config.maxRetries} after ${r}s`);}logNetworkRetry(e,t,r,s){if(!this.config.logger||!this.config.shouldLog("warn"))return;let i=s instanceof Error?s.name:"Unknown";this.config.logger.warn(`[CardDB] ${i} on ${e}, retry ${t}/${this.config.maxNetworkRetries} after ${r}ms`);}logError(e){!this.config.logger||!this.config.shouldLog("error")||this.config.logger.error(`[CardDB] ${e}`);}};function ce(e,t,r){let s=Object.entries(r).filter(([,i])=>i!==void 0).sort(([i],[n])=>i.localeCompare(n)).map(([i,n])=>`${i}=${JSON.stringify(n)}`).join("&");return `carddb:${e}:${t}:${s}`}async function oe(e,t){let r=e.get(t);return r}async function ue(e,t,r,s){let i=e.set(t,r,s);i instanceof Promise&&await i;}var g=class{connection;config;constructor(e,t){this.connection=e,this.config=t;}resolvePublisher(e){let t=this.config.resolvePublisher(e);if(!t)throw new Error("publisher_slug is required (no default configured)");return t}resolveGame(e){let t=this.config.resolveGame(e);if(!t)throw new Error("game_key is required (no default configured)");return t}validateAccess(e,t){this.config.validateAccess(e,t);}async withCache(e,t,r,s){let i=r.cache??!!this.config.cache,n=this.config.cache;if(!i||!n)return s();let a=await oe(n,e);if(a!==null)return a;let o=await s();if(o!=null){let u=this.config.cacheTtlFor(t);await ue(n,e,o,u);}return o}cacheKey(e,t,r){return ce(e,t,r)}},le=class extends g{constructor(e,t){super(e,t);}async search(e={}){let{query:t,variables:r}=c.searchPublishers({search:e.search,first:e.first,after:e.after}),s=this.cacheKey("publishers","search",r),i=await this.withCache(s,"publishers",e,async()=>(await this.connection.execute(t,r)).searchPublishers);return new h(i,{nextPageLoader:async n=>this.search({...e,after:n})})}async get(e,t={}){let r=this.isUUID(e),s=this.cacheKey("publishers","get",{[r?"id":"slug"]:e});return this.withCache(s,"publishers",t,async()=>{if(r){let{query:i}=c.fetchPublisherById();return (await this.connection.execute(i,{id:e})).fetchPublisher??null}else {let{query:i}=c.fetchPublisherBySlug();return (await this.connection.execute(i,{slug:e})).fetchPublisher??null}})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("publishers","getMany",{slugs:e});return this.withCache(r,"publishers",t,async()=>{let{query:s}=c.fetchPublishers();return (await this.connection.execute(s,{slugs:e})).fetchPublishers??[]})}isUUID(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}},he=class extends g{constructor(e,t){super(e,t);}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug);t&&this.validateAccess(t);let{query:r,variables:s}=c.searchGames({publisherSlug:t,search:e.search,first:e.first,after:e.after}),i=this.cacheKey("games","search",s),n=await this.withCache(i,"games",e,async()=>(await this.connection.execute(r,s)).searchGames);return new h(n,{nextPageLoader:async a=>this.search({...e,after:a})})}async get(e,t,r){if(typeof t=="string"){let s=e,i=t,n=r??{};this.validateAccess(s,i);let a=this.cacheKey("games","getByKeys",{publisherSlug:s,gameKey:i});return this.withCache(a,"games",n,async()=>{let{query:o}=c.fetchGameByKeys();return (await this.connection.execute(o,{publisherSlug:s,gameKey:i})).fetchGame??null})}else {let s=e,i=t??{},n=this.cacheKey("games","get",{id:s});return this.withCache(n,"games",i,async()=>{let{query:a}=c.fetchGameById();return (await this.connection.execute(a,{id:s})).fetchGame??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("games","getMany",{ids:e});return this.withCache(r,"games",t,async()=>{let{query:s}=c.fetchGames();return (await this.connection.execute(s,{ids:e})).fetchGames??[]})}},de=class extends g{constructor(e,t){super(e,t);}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug),r=this.config.resolveGame(e.gameKey);t&&this.validateAccess(t,r);let{query:s,variables:i}=c.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:e.purpose,first:e.first,after:e.after}),n=this.cacheKey("datasets","search",i),a=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new h(a,{nextPageLoader:async o=>this.search({...e,after:o})})}async get(e,t,r,s){if(typeof t=="string"&&typeof r=="string"){let i=e,n=t,a=s??{};this.validateAccess(i,n);let o=this.cacheKey("datasets","getByKeys",{publisherSlug:i,gameKey:n,datasetKey:r});return this.withCache(o,"datasets",a,async()=>{let{query:u}=c.fetchDatasetByKeys();return (await this.connection.execute(u,{publisherSlug:i,gameKey:n,datasetKey:r})).fetchDataset??null})}else {let i=e,n=t??{},a=this.cacheKey("datasets","get",{id:i});return this.withCache(a,"datasets",n,async()=>{let{query:o}=c.fetchDatasetById();return (await this.connection.execute(o,{id:i})).fetchDataset??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("datasets","getMany",{ids:e});return this.withCache(r,"datasets",t,async()=>{let{query:s}=c.fetchDatasets();return (await this.connection.execute(s,{ids:e})).fetchDatasets??[]})}},fe=class extends g{constructor(e,t){super(e,t);}async fetch(e,t={}){let r=this.cacheKey("decks","fetch",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.fetchDeckById();return (await this.connection.execute(s,{id:e})).fetchDeck??null})}async fetchMine(e,t={}){let r=this.cacheKey("decks","fetchMine",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.myDeck();return (await this.connection.execute(s,{id:e})).myDeck??null})}async fetchBySlug(e,t,r,s={}){let i=this.cacheKey("decks","fetchBySlug",{publisherSlug:e,gameKey:t,slug:r});return this.withCache(i,"decks",s,async()=>{let{query:n}=c.fetchDeckBySlug();return (await this.connection.execute(n,{publisherSlug:e,gameKey:t,slug:r})).fetchDeckBySlug??null})}async fetchByExternalRef(e,t={}){let r=this.cacheKey("decks","fetchByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.fetchDeckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).fetchDeckByExternalRef??null})}async listMine(e={}){let{query:t,variables:r}=c.listMyDecks({first:e.first,after:e.after}),s=this.cacheKey("decks","listMine",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).myDecks);return new h(i,{nextPageLoader:async n=>this.listMine({...e,after:n})})}async fetchVersion(e,t={}){let r=this.cacheKey("decks","fetchVersion",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckVersion();return (await this.connection.execute(s,{id:e})).deckVersion??null})}async listVersions(e,t={}){let{query:r,variables:s}=c.deckVersions({first:t.first,after:t.after}),i={deckId:e,...s},n=this.cacheKey("decks","listVersions",i),a=await this.withCache(n,"decks",t,async()=>(await this.connection.execute(r,i)).deckVersions);return new h(a,{nextPageLoader:async o=>this.listVersions(e,{...t,after:o})})}async preview(e,t={}){let r=this.cacheKey("decks","preview",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckPreview();return (await this.connection.execute(s,{token:e})).deckPreview??null})}async listCollaborators(e,t={}){let r=this.cacheKey("decks","listCollaborators",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckCollaborators();return (await this.connection.execute(s,{deckId:e})).deckCollaborators})}async listPreviewTokens(e,t={}){let r=this.cacheKey("decks","listPreviewTokens",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.deckPreviewTokens();return (await this.connection.execute(s,{deckId:e})).deckPreviewTokens})}async create(e){let{query:t}=c.createDeck(),r=c.deckCreateVariables(e);return (await this.connection.execute(t,r)).deckCreate}async update(e,t){let{query:r}=c.updateDeck(),s=c.deckUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckUpdate}async delete(e){let{query:t}=c.deleteDeck();return !!(await this.connection.execute(t,{id:e})).deckDelete}async publish(e,t={}){let{query:r}=c.publishDeck(),s=c.deckPublishVariables(e,t);return (await this.connection.execute(r,s)).deckPublish}async upsertCollaborator(e,t,r){let{query:s}=c.upsertDeckCollaborator(),i=c.deckCollaboratorVariables(e,t,r);return (await this.connection.execute(s,i)).deckCollaboratorUpsert}async removeCollaborator(e,t){let{query:r}=c.removeDeckCollaborator(),s=c.deckCollaboratorVariables(e,t);return !!(await this.connection.execute(r,s)).deckCollaboratorRemove}async createPreviewToken(e){let{query:t}=c.createDeckPreviewToken(),r=c.deckPreviewTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckPreviewTokenCreate}async revokePreviewToken(e){let{query:t}=c.revokeDeckPreviewToken();return !!(await this.connection.execute(t,{id:e})).deckPreviewTokenRevoke}async hydrateEntries(e){if(e.entries.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=e.entries.map(o=>o.identifier),i=this.cacheKey("decks","hydrateEntries",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s}),n=await this.withCache(i,"decks",e,async()=>{let{query:o}=c.fetchRecordsByIdentifier();return (await this.connection.execute(o,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s})).fetchRecordsByIdentifier}),a=ye(n,s,e.identifierField);return e.entries.map(o=>({...o,record:a.get(o.identifier)??null}))}};function ye(e,t,r){let s=new Set(t),i=new Map;for(let n of e){let a=r?n.data[r]:Object.values(n.data).find(u=>s.has(String(u)));if(a==null)continue;let o=String(a);s.has(o)&&(i.set(o,n),s.delete(o));}return i}var ge=class extends g{constructor(e,t){super(e,t);}async search(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=P(e.filter),{query:i,variables:n}=c.searchRecords({publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,filter:s,search:e.search,orderBy:e.orderBy,resolveLinks:e.resolveLinks,first:e.first,after:e.after,validateSchema:e.validateSchema,includePricing:e.includePricing}),a=this.cacheKey("records","search",{...n,includePricing:e.includePricing??false}),o=await this.withCache(a,"records",e,async()=>(await this.connection.execute(i,n)).searchRecords);return new h(o,{nextPageLoader:async u=>this.search({...e,after:u})})}async get(e,t={}){let r=this.cacheKey("records","get",{id:e,includePricing:t.includePricing??false});return this.withCache(r,"records",t,async()=>{let{query:s}=c.fetchRecordById({includePricing:t.includePricing});return (await this.connection.execute(s,{id:e})).fetchRecord??null})}async getByIdentifier(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier,includePricing:e.includePricing??false});return this.withCache(s,"records",e,async()=>{let{query:i}=c.fetchRecordByIdentifier({includePricing:e.includePricing});return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier})).fetchRecordByIdentifier??null})}async getManyByIdentifier(e){if(e.identifiers.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getManyByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers,includePricing:e.includePricing??false});return this.withCache(s,"records",e,async()=>{let{query:i}=c.fetchRecordsByIdentifier({includePricing:e.includePricing});return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers})).fetchRecordsByIdentifier??[]})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("records","getMany",{ids:e,includePricing:t.includePricing??false});return this.withCache(r,"records",t,async()=>{let{query:s}=c.fetchRecords({includePricing:t.includePricing});return (await this.connection.execute(s,{ids:e})).fetchRecords??[]})}},me=class extends g{constructor(e,t){super(e,t);}async datasets(e={}){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let{query:s,variables:i}=c.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:"RULES",first:e.first,after:e.after}),n=this.cacheKey("rules","datasets",i),a=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new h(a,{nextPageLoader:async o=>this.datasets({...e,after:o})})}async list(e={}){return this.searchRuleRecords("rules",e)}async formats(e={}){return this.searchRuleRecords(e.datasetKey??"formats",e)}async searchRuleRecords(e,t){let r=this.resolvePublisher(t.publisherSlug),s=this.resolveGame(t.gameKey),i=t.datasetKey??e;this.validateAccess(r,s);let n=P(t.filter),{query:a,variables:o}=c.searchRecords({publisherSlug:r,gameKey:s,datasetKey:i,filter:n,search:t.search,orderBy:t.orderBy,resolveLinks:t.resolveLinks,first:t.first,after:t.after,validateSchema:t.validateSchema}),u=this.cacheKey("rules","records",o),E=await this.withCache(u,"records",t,async()=>(await this.connection.execute(a,o)).searchRecords);return new h(E,{nextPageLoader:async C=>this.searchRuleRecords(e,{...t,after:C})})}},Qe=class _{config;connection;publishers;games;datasets;records;decks;rules;constructor(t={}){this.config=new te(t),this.connection=new ae(this.config),this.publishers=new le(this.connection,this.config),this.games=new he(this.connection,this.config),this.datasets=new de(this.connection,this.config),this.records=new ge(this.connection,this.config),this.decks=new fe(this.connection,this.config),this.rules=new me(this.connection,this.config);}async me(){let{query:t}=c.fetchMe();return (await this.connection.execute(t)).fetchMe??null}getRateLimitInfo(){return ne()}withConfig(t){let r=this.config.merge(t);return new _({apiKey:r.apiKey,endpoint:r.endpoint,timeout:r.timeout,openTimeout:r.openTimeout,defaultPublisher:r.defaultPublisher,defaultGame:r.defaultGame,allowedPublishers:r.allowedPublishers,allowedGames:r.allowedGames,logger:r.logger,logLevel:r.logLevel,retryOnRateLimit:r.retryOnRateLimit,maxRetries:r.maxRetries,retryOnNetworkError:r.retryOnNetworkError,maxNetworkRetries:r.maxNetworkRetries,retryBaseDelay:r.retryBaseDelay,retryMaxDelay:r.retryMaxDelay,cache:r.cache,cacheTtl:r.cacheTtl,cacheTtls:r.cacheTtls})}};
466
+ export{D as AuthenticationError,g as BaseResource,$ as BrowserCache,Qe as CardDBClient,l as CardDBError,h as Collection,te as Configuration,ae as Connection,k as ConnectionError,W as DEFAULT_CACHE_TTL,Q as DEFAULT_ENDPOINT,z as DEFAULT_MAX_NETWORK_RETRIES,Y as DEFAULT_MAX_RETRIES,J as DEFAULT_OPEN_TIMEOUT,Z as DEFAULT_RETRY_BASE_DELAY,ee as DEFAULT_RETRY_MAX_DELAY,H as DEFAULT_TIMEOUT,de as DatasetsResource,fe as DecksResource,V as FilterBuilder,he as GamesResource,B as GraphQLError,ve as LinkResolutionError,we as NotFoundError,le as PublishersResource,c as QueryBuilder,p as RateLimitError,ge as RecordsResource,S as RestrictedError,me as RulesResource,I as ServerError,x as TimeoutError,R as ValidationError,ce as cacheKey,Pe as contains,be as eq,ne as getRateLimitInfo,Xe as getSDKVersion,ie as getUserAgent,$e as gt,De as gte,Ce as ilike,Ke as isNotNull,Te as isNull,Ee as like,Re as lt,Se as lte,pe as neq,Ie as notWithin,oe as readCache,P as resolveFilter,xe as within,ue as writeCache};//# sourceMappingURL=index.js.map
458
467
  //# sourceMappingURL=index.js.map