@cohostvip/cohost-node 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -512,7 +512,7 @@ type Customer = Person & PersonContact & {
512
512
  uid: string | null;
513
513
  };
514
514
  type AttendeeStatus = "attending" | "checkedIn" | "cancelled" | "refunded" | "noShow" | "unknown" | string;
515
- interface Attendee3 extends DataRecord {
515
+ interface Attendee extends DataRecord {
516
516
  /**
517
517
  * Order ID, from /orders/:orderId
518
518
  */
@@ -521,6 +521,11 @@ interface Attendee3 extends DataRecord {
521
521
  * For event it will be the ticket's id
522
522
  */
523
523
  offeringId: string;
524
+ /**
525
+ *
526
+ */
527
+ orderNumber: string;
528
+ uid: string | null;
524
529
  offeringSnapshot: Partial<Offering>;
525
530
  profile: Customer | null;
526
531
  checkedIn: boolean;
@@ -957,7 +962,7 @@ interface OrderItem {
957
962
  options: any | null;
958
963
  offering: OrderItemOffering;
959
964
  }
960
- interface OrderItemOffering extends Pick<Offering, "id" | "name" | "type" | "includes" | "status" | "description" | "options" | "maximumQuantity" | "minimumQuantity" | "sorting"> {
965
+ interface OrderItemOffering extends Pick<Offering, "id" | "name" | "type" | "description" | "sorting"> {
961
966
  costs?: OfferingCosts;
962
967
  /**
963
968
  * doc assicated with this offering in the DB.
@@ -1160,9 +1165,13 @@ interface Order extends VCDataRecord {
1160
1165
  * Includes IPs, referrer, user agent, cart session ID, and tracking info.
1161
1166
  */
1162
1167
  context: OrderContext;
1168
+ /**
1169
+ * userId
1170
+ */
1171
+ uid: string | null;
1163
1172
  version: ApiVersion;
1164
1173
  }
1165
- type OrderContext = {
1174
+ type OrderContext = ({
1166
1175
  type: "event";
1167
1176
  event: EventProfile;
1168
1177
  venue?: Venue;
@@ -1170,6 +1179,8 @@ type OrderContext = {
1170
1179
  type: "venue";
1171
1180
  event?: EventProfile;
1172
1181
  venue: Venue;
1182
+ }) & {
1183
+ [key: string]: any;
1173
1184
  };
1174
1185
  interface OrderContext$1 {
1175
1186
  /**
@@ -1206,20 +1217,17 @@ interface OrderContext$1 {
1206
1217
  * @example "examplepartner.com"
1207
1218
  */
1208
1219
  originDomain?: string;
1209
- /**
1210
- * (Optional) Campaign ID, UTM source, or tracking label.
1211
- * Useful for affiliate and analytics systems.
1212
- * @example "utm_campaign=spring_launch"
1213
- */
1214
- trackingId?: string;
1215
- /**
1216
- * Allows custom fields for analytics, partners, or experiment data.
1217
- */
1218
- [custom: string]: unknown;
1220
+ tracking?: Record<string, string>;
1221
+ forward?: Record<string, any>;
1219
1222
  }
1223
+ type StartCartSessionInput = {
1224
+ contextId: string;
1225
+ sessionContext: Partial<OrderContext$1>;
1226
+ };
1227
+ type CartSessionItemOffering = OrderItemOffering & Pick<Offering, "options" | "maximumQuantity" | "minimumQuantity" | "status" | "includes">;
1220
1228
  type CartSessionItem = Pick<OrderItem, "id" | "details" | "offeringId" | "quantity" | "options" | "tableCommitmentId"> & {
1221
1229
  costs?: OrderItemCosts;
1222
- offering: OrderItemOffering;
1230
+ offering: CartSessionItemOffering;
1223
1231
  };
1224
1232
  /**
1225
1233
  * Represents a temporary or persisted cart before order placement.
@@ -1388,7 +1396,7 @@ declare class EventsAPI extends CohostEndpoint {
1388
1396
  * @param id - The ID of the event.
1389
1397
  * @returns List of tickets (attendees) for the event.
1390
1398
  */
1391
- attendees(id: string, filters?: PaginatedRequest<any>): Promise<PaginatedResponse<Attendee3>>;
1399
+ attendees(id: string, filters?: PaginatedRequest<any>): Promise<PaginatedResponse<Attendee>>;
1392
1400
  }
1393
1401
 
1394
1402
  /**
@@ -1411,6 +1419,15 @@ declare class OrdersAPI extends CohostEndpoint {
1411
1419
  * @throws Will throw an error if the request fails or the order is not found
1412
1420
  */
1413
1421
  fetch(id: string, uid: string): Promise<any>;
1422
+ /**
1423
+ * Fetch a single order by ID.
1424
+ *
1425
+ * @param id - The unique identifier of the order
1426
+ * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)
1427
+ * @returns A Promise resolving to the order object
1428
+ * @throws Will throw an error if the request fails or the order is not found
1429
+ */
1430
+ attendees(id: string, uid: string): Promise<any>;
1414
1431
  /**
1415
1432
  * List orders with optional filters.
1416
1433
  *
@@ -1427,13 +1444,6 @@ declare class OrdersAPI extends CohostEndpoint {
1427
1444
  }): Promise<any>;
1428
1445
  }
1429
1446
 
1430
- interface StartCartSessionInput {
1431
- contextId: string;
1432
- userAgent?: string;
1433
- referrer?: string;
1434
- ipAddresses?: string[];
1435
- }
1436
-
1437
1447
  /**
1438
1448
  * Provides methods to interact with cart sessions in the Cohost API.
1439
1449
  *
@@ -1606,4 +1616,4 @@ declare class CohostClient {
1606
1616
  */
1607
1617
  declare function createCohostClient(options: CohostClientOptions): CohostClient;
1608
1618
 
1609
- export { type ActiveOfferingStatus, type Address, type ApiVersion, type Attendee3, type AttendeeStatus, type BuzzBuilder, type CalculatedCostComponent, type CartSession, type CartSessionItem, CohostClient, type CohostClientSettings, type ContextId, type CostBase, type CostBucket, type CostComponent, type CostComponentCap, type CostComponentRule, type CostComponentRuleCondition, type CostOp, type Coupon, type CouponSummary, type CurrencyAmount, type Customer, type DataRecord, type EqualOperator, type EventBase, type EventFeature, type EventProfile, type EventStatus, type GeometryPoint, type Location, type LocationGeometry, type MultipartText, type Offering, type OfferingCosts, type OfferingOption, type OfferingOptionsGroup, type OfferingStatus, type OfferingType, type Order, type OrderContext, type OrderCosts, type OrderItem, type OrderItemCosts, type OrderItemOffering, type OrderStatus, type PackageInclude, type PaginatedRequest, type PaginatedResponse, type Pagination$1 as Pagination, type PaginationResponse, type Person, type PersonContact, type Photo, type PriceCategory, type ResolvedCartContext, type ResolvedCartContextOffering, type Schedule, type StructuredCost, type StructuredDate, type Ticket, type TimeOrOffset, type UpdatableCartSession, type VCDataRecord, type Venue, type VenueBase, type VersionedDataRecord, createCohostClient };
1619
+ export { type ActiveOfferingStatus, type Address, type ApiVersion, type Attendee, type AttendeeStatus, type BuzzBuilder, type CalculatedCostComponent, type CartSession, type CartSessionItem, type CartSessionItemOffering, CohostClient, type CohostClientSettings, type ContextId, type CostBase, type CostBucket, type CostComponent, type CostComponentCap, type CostComponentRule, type CostComponentRuleCondition, type CostOp, type Coupon, type CouponSummary, type CurrencyAmount, type Customer, type DataRecord, type EqualOperator, type EventBase, type EventFeature, type EventProfile, type EventStatus, type GeometryPoint, type Location, type LocationGeometry, type MultipartText, type Offering, type OfferingCosts, type OfferingOption, type OfferingOptionsGroup, type OfferingStatus, type OfferingType, type Order, type OrderContext, type OrderCosts, type OrderItem, type OrderItemCosts, type OrderItemOffering, type OrderStatus, type PackageInclude, type PaginatedRequest, type PaginatedResponse, type Pagination$1 as Pagination, type PaginationResponse, type Person, type PersonContact, type Photo, type PriceCategory, type ResolvedCartContext, type ResolvedCartContextOffering, type Schedule, type StartCartSessionInput, type StructuredCost, type StructuredDate, type Ticket, type TimeOrOffset, type UpdatableCartSession, type VCDataRecord, type Venue, type VenueBase, type VersionedDataRecord, createCohostClient };
package/dist/index.d.ts CHANGED
@@ -512,7 +512,7 @@ type Customer = Person & PersonContact & {
512
512
  uid: string | null;
513
513
  };
514
514
  type AttendeeStatus = "attending" | "checkedIn" | "cancelled" | "refunded" | "noShow" | "unknown" | string;
515
- interface Attendee3 extends DataRecord {
515
+ interface Attendee extends DataRecord {
516
516
  /**
517
517
  * Order ID, from /orders/:orderId
518
518
  */
@@ -521,6 +521,11 @@ interface Attendee3 extends DataRecord {
521
521
  * For event it will be the ticket's id
522
522
  */
523
523
  offeringId: string;
524
+ /**
525
+ *
526
+ */
527
+ orderNumber: string;
528
+ uid: string | null;
524
529
  offeringSnapshot: Partial<Offering>;
525
530
  profile: Customer | null;
526
531
  checkedIn: boolean;
@@ -957,7 +962,7 @@ interface OrderItem {
957
962
  options: any | null;
958
963
  offering: OrderItemOffering;
959
964
  }
960
- interface OrderItemOffering extends Pick<Offering, "id" | "name" | "type" | "includes" | "status" | "description" | "options" | "maximumQuantity" | "minimumQuantity" | "sorting"> {
965
+ interface OrderItemOffering extends Pick<Offering, "id" | "name" | "type" | "description" | "sorting"> {
961
966
  costs?: OfferingCosts;
962
967
  /**
963
968
  * doc assicated with this offering in the DB.
@@ -1160,9 +1165,13 @@ interface Order extends VCDataRecord {
1160
1165
  * Includes IPs, referrer, user agent, cart session ID, and tracking info.
1161
1166
  */
1162
1167
  context: OrderContext;
1168
+ /**
1169
+ * userId
1170
+ */
1171
+ uid: string | null;
1163
1172
  version: ApiVersion;
1164
1173
  }
1165
- type OrderContext = {
1174
+ type OrderContext = ({
1166
1175
  type: "event";
1167
1176
  event: EventProfile;
1168
1177
  venue?: Venue;
@@ -1170,6 +1179,8 @@ type OrderContext = {
1170
1179
  type: "venue";
1171
1180
  event?: EventProfile;
1172
1181
  venue: Venue;
1182
+ }) & {
1183
+ [key: string]: any;
1173
1184
  };
1174
1185
  interface OrderContext$1 {
1175
1186
  /**
@@ -1206,20 +1217,17 @@ interface OrderContext$1 {
1206
1217
  * @example "examplepartner.com"
1207
1218
  */
1208
1219
  originDomain?: string;
1209
- /**
1210
- * (Optional) Campaign ID, UTM source, or tracking label.
1211
- * Useful for affiliate and analytics systems.
1212
- * @example "utm_campaign=spring_launch"
1213
- */
1214
- trackingId?: string;
1215
- /**
1216
- * Allows custom fields for analytics, partners, or experiment data.
1217
- */
1218
- [custom: string]: unknown;
1220
+ tracking?: Record<string, string>;
1221
+ forward?: Record<string, any>;
1219
1222
  }
1223
+ type StartCartSessionInput = {
1224
+ contextId: string;
1225
+ sessionContext: Partial<OrderContext$1>;
1226
+ };
1227
+ type CartSessionItemOffering = OrderItemOffering & Pick<Offering, "options" | "maximumQuantity" | "minimumQuantity" | "status" | "includes">;
1220
1228
  type CartSessionItem = Pick<OrderItem, "id" | "details" | "offeringId" | "quantity" | "options" | "tableCommitmentId"> & {
1221
1229
  costs?: OrderItemCosts;
1222
- offering: OrderItemOffering;
1230
+ offering: CartSessionItemOffering;
1223
1231
  };
1224
1232
  /**
1225
1233
  * Represents a temporary or persisted cart before order placement.
@@ -1388,7 +1396,7 @@ declare class EventsAPI extends CohostEndpoint {
1388
1396
  * @param id - The ID of the event.
1389
1397
  * @returns List of tickets (attendees) for the event.
1390
1398
  */
1391
- attendees(id: string, filters?: PaginatedRequest<any>): Promise<PaginatedResponse<Attendee3>>;
1399
+ attendees(id: string, filters?: PaginatedRequest<any>): Promise<PaginatedResponse<Attendee>>;
1392
1400
  }
1393
1401
 
1394
1402
  /**
@@ -1411,6 +1419,15 @@ declare class OrdersAPI extends CohostEndpoint {
1411
1419
  * @throws Will throw an error if the request fails or the order is not found
1412
1420
  */
1413
1421
  fetch(id: string, uid: string): Promise<any>;
1422
+ /**
1423
+ * Fetch a single order by ID.
1424
+ *
1425
+ * @param id - The unique identifier of the order
1426
+ * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)
1427
+ * @returns A Promise resolving to the order object
1428
+ * @throws Will throw an error if the request fails or the order is not found
1429
+ */
1430
+ attendees(id: string, uid: string): Promise<any>;
1414
1431
  /**
1415
1432
  * List orders with optional filters.
1416
1433
  *
@@ -1427,13 +1444,6 @@ declare class OrdersAPI extends CohostEndpoint {
1427
1444
  }): Promise<any>;
1428
1445
  }
1429
1446
 
1430
- interface StartCartSessionInput {
1431
- contextId: string;
1432
- userAgent?: string;
1433
- referrer?: string;
1434
- ipAddresses?: string[];
1435
- }
1436
-
1437
1447
  /**
1438
1448
  * Provides methods to interact with cart sessions in the Cohost API.
1439
1449
  *
@@ -1606,4 +1616,4 @@ declare class CohostClient {
1606
1616
  */
1607
1617
  declare function createCohostClient(options: CohostClientOptions): CohostClient;
1608
1618
 
1609
- export { type ActiveOfferingStatus, type Address, type ApiVersion, type Attendee3, type AttendeeStatus, type BuzzBuilder, type CalculatedCostComponent, type CartSession, type CartSessionItem, CohostClient, type CohostClientSettings, type ContextId, type CostBase, type CostBucket, type CostComponent, type CostComponentCap, type CostComponentRule, type CostComponentRuleCondition, type CostOp, type Coupon, type CouponSummary, type CurrencyAmount, type Customer, type DataRecord, type EqualOperator, type EventBase, type EventFeature, type EventProfile, type EventStatus, type GeometryPoint, type Location, type LocationGeometry, type MultipartText, type Offering, type OfferingCosts, type OfferingOption, type OfferingOptionsGroup, type OfferingStatus, type OfferingType, type Order, type OrderContext, type OrderCosts, type OrderItem, type OrderItemCosts, type OrderItemOffering, type OrderStatus, type PackageInclude, type PaginatedRequest, type PaginatedResponse, type Pagination$1 as Pagination, type PaginationResponse, type Person, type PersonContact, type Photo, type PriceCategory, type ResolvedCartContext, type ResolvedCartContextOffering, type Schedule, type StructuredCost, type StructuredDate, type Ticket, type TimeOrOffset, type UpdatableCartSession, type VCDataRecord, type Venue, type VenueBase, type VersionedDataRecord, createCohostClient };
1619
+ export { type ActiveOfferingStatus, type Address, type ApiVersion, type Attendee, type AttendeeStatus, type BuzzBuilder, type CalculatedCostComponent, type CartSession, type CartSessionItem, type CartSessionItemOffering, CohostClient, type CohostClientSettings, type ContextId, type CostBase, type CostBucket, type CostComponent, type CostComponentCap, type CostComponentRule, type CostComponentRuleCondition, type CostOp, type Coupon, type CouponSummary, type CurrencyAmount, type Customer, type DataRecord, type EqualOperator, type EventBase, type EventFeature, type EventProfile, type EventStatus, type GeometryPoint, type Location, type LocationGeometry, type MultipartText, type Offering, type OfferingCosts, type OfferingOption, type OfferingOptionsGroup, type OfferingStatus, type OfferingType, type Order, type OrderContext, type OrderCosts, type OrderItem, type OrderItemCosts, type OrderItemOffering, type OrderStatus, type PackageInclude, type PaginatedRequest, type PaginatedResponse, type Pagination$1 as Pagination, type PaginationResponse, type Person, type PersonContact, type Photo, type PriceCategory, type ResolvedCartContext, type ResolvedCartContextOffering, type Schedule, type StartCartSessionInput, type StructuredCost, type StructuredDate, type Ticket, type TimeOrOffset, type UpdatableCartSession, type VCDataRecord, type Venue, type VenueBase, type VersionedDataRecord, createCohostClient };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var l=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var $=(n,e,t)=>e in n?l(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var D=(n,e)=>{for(var t in e)l(n,t,{get:e[t],enumerable:!0})},z=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of w(e))!U.call(n,s)&&s!==t&&l(n,s,{get:()=>e[s],enumerable:!(r=E(e,s))||r.enumerable});return n};var B=n=>z(l({},"__esModule",{value:!0}),n);var o=(n,e,t)=>$(n,typeof e!="symbol"?e+"":e,t);var _={};D(_,{CohostClient:()=>p,createCohostClient:()=>L});module.exports=B(_);var u=class{constructor(e,t){o(this,"request");o(this,"settings");this.request=e,this.settings=t}};var g="https://api.cohost.com/v1";var m=class n extends Error{constructor(t,r){super(t);o(this,"errorCode");o(this,"statusCode");this.name="CohostError",this.errorCode=r?.errorCode,this.statusCode=r?.statusCode}static fromError(t,r){return new n(t.message,{...r,errorCode:r?.errorCode||t.name})}};var v={baseUrl:"https://api.cohost.vip",headers:{"Content-Type":"application/json"}},O={};var R=(n,e)=>{let{pagination:t,...r}=n;return{query:r,pagination:t,...e}},V=n=>{if(!n)return"";let e=new URLSearchParams;for(let[t,r]of Object.entries(n))r!==void 0&&(Array.isArray(r)?r.forEach(s=>e.append(t,String(s))):e.set(t,String(r)));return e.toString()?`?${e.toString()}`:""},S=({token:n,baseUrl:e=g,debug:t=!1})=>async function(r,s={}){let{method:i="GET",data:c,query:q,pagination:I,headers:A={}}=s,k={...q,...I},T=V(k),x=`${O.baseUrl??e}${r}${T}`,h={...v.headers,...O.headers,...A};n&&(h.Authorization=`Bearer ${n}`);let b=c&&i!=="GET"?JSON.stringify(c):void 0;t&&(console.log(`[Cohost SDK] Request: ${i} ${x}`),b&&console.log("[Cohost SDK] Body:",b),console.log("[Cohost SDK] Headers:",h));let d=await fetch(x,{method:i,headers:h,body:b}),a=d.headers.get("content-type")?.includes("application/json")?await d.json():await d.text();if(!d.ok){let P=typeof a=="string"?a:JSON.stringify(a);throw console.error(`[Cohost SDK] Error: ${P}`,{url:x}),new m(P||d.statusText,{errorCode:d.statusText||"API_ERROR",statusCode:d.status})}return typeof a=="object"&&a!==null&&a.status==="ok"&&"data"in a?a.data:a};var f=class extends u{async list(){return this.request("/events")}async fetch(e){return this.request(`/events/${e}`)}async tickets(e){return this.request(`/events/${e}/tickets`)}async attendees(e,t){return this.request(`/events/${e}/attendees`,R(t))}};var y=class extends u{async fetch(e,t){return this.request(`/orders/${e}?uid=${t}`)}async list(e){let t=new URLSearchParams(e).toString();return this.request(`/orders${t?`?${t}`:""}`)}};var C=class extends u{async start(e){return this.request("/cart/sessions",{method:"POST",data:e})}async get(e){return this.request(`/cart/sessions/${e}`)}async update(e,t){return this.request(`/cart/sessions/${e}`,{method:"PATCH",data:t})}async cancel(e){return this.request(`/cart/sessions/${e}`,{method:"DELETE"})}async updateItem(e,t){return this.request(`/cart/sessions/${e}/item`,{method:"POST",data:t})}async preValidate(e,t){return this.request(`/cart/sessions/${e}/payment/pre-validate`,{method:"POST",data:t})}async processPayment(e,t){return this.request(`/cart/sessions/${e}/payment/process`,{method:"POST",data:t})}async placeOrder(e,t){return this.request(`/cart/sessions/${e}/place-order`,{method:"POST",data:t})}async deleteItem(e,t){return this.updateItem(e,{itemId:t,quantity:0})}async joinTableCommitment(e,t){return this.request(`/cart/sessions/${e}/join-table`,{method:"POST",data:{tableCommitmentId:t}})}async applyCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons`,{method:"POST",data:{code:t}})}async deleteCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons/${t}`,{method:"DELETE"})}};var p=class n{constructor(e,t){o(this,"events");o(this,"orders");o(this,"cart");o(this,"baseOptions");this.baseOptions=e;let{token:r,settings:s={}}=e,i=t??S({token:r,baseUrl:s.apiUrl||g,debug:s.debug});this.events=new f(i,s),this.orders=new y(i,s),this.cart=new C(i,s)}requestWithOverrides(e){let{token:t,settings:r={}}=this.baseOptions,s=(i,c={})=>S({token:e.token??t,baseUrl:e.baseUrl??r.apiUrl??g,debug:r.debug})(i,{...c,headers:{...e.headers||{},...c.headers||{}}});return new n({token:e.token??t,settings:{...r,apiUrl:e.baseUrl??r.apiUrl}},s)}};function L(n){return new p(n)}0&&(module.exports={CohostClient,createCohostClient});
1
+ "use strict";var l=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var U=(r,e,t)=>e in r?l(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var D=(r,e)=>{for(var t in e)l(r,t,{get:e[t],enumerable:!0})},z=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $(e))!w.call(r,s)&&s!==t&&l(r,s,{get:()=>e[s],enumerable:!(n=E(e,s))||n.enumerable});return r};var B=r=>z(l({},"__esModule",{value:!0}),r);var o=(r,e,t)=>U(r,typeof e!="symbol"?e+"":e,t);var _={};D(_,{CohostClient:()=>p,createCohostClient:()=>L});module.exports=B(_);var d=class{constructor(e,t){o(this,"request");o(this,"settings");this.request=e,this.settings=t}};var g="https://api.cohost.com/v1";var m=class r extends Error{constructor(t,n){super(t);o(this,"errorCode");o(this,"statusCode");this.name="CohostError",this.errorCode=n?.errorCode,this.statusCode=n?.statusCode}static fromError(t,n){return new r(t.message,{...n,errorCode:n?.errorCode||t.name})}};var v={baseUrl:"https://api.cohost.vip",headers:{"Content-Type":"application/json"}},O={};var R=(r,e)=>{let{pagination:t,...n}=r;return{query:n,pagination:t,...e}},V=r=>{if(!r)return"";let e=new URLSearchParams;for(let[t,n]of Object.entries(r))n!==void 0&&(Array.isArray(n)?n.forEach(s=>e.append(t,String(s))):e.set(t,String(n)));return e.toString()?`?${e.toString()}`:""},S=({token:r,baseUrl:e=g,debug:t=!1})=>async function(n,s={}){let{method:i="GET",data:c,query:q,pagination:I,headers:A={}}=s,k={...q,...I},T=V(k),x=`${O.baseUrl??e}${n}${T}`,h={...v.headers,...O.headers,...A};r&&(h.Authorization=`Bearer ${r}`);let b=c&&i!=="GET"?JSON.stringify(c):void 0;t&&(console.log(`[Cohost SDK] Request: ${i} ${x}`),b&&console.log("[Cohost SDK] Body:",b),console.log("[Cohost SDK] Headers:",h));let u=await fetch(x,{method:i,headers:h,body:b}),a=u.headers.get("content-type")?.includes("application/json")?await u.json():await u.text();if(!u.ok){let P=typeof a=="string"?a:JSON.stringify(a);throw console.error(`[Cohost SDK] Error: ${P}`,{url:x}),new m(P||u.statusText,{errorCode:u.statusText||"API_ERROR",statusCode:u.status})}return typeof a=="object"&&a!==null&&a.status==="ok"&&"data"in a?a.data:a};var f=class extends d{async list(){return this.request("/events")}async fetch(e){return this.request(`/events/${e}`)}async tickets(e){return this.request(`/events/${e}/tickets`)}async attendees(e,t){return this.request(`/events/${e}/attendees`,R(t))}};var y=class extends d{async fetch(e,t){return this.request(`/orders/${e}?uid=${t}`)}async attendees(e,t){return this.request(`/orders/${e}/attendees?uid=${t}`)}async list(e){let t=new URLSearchParams(e).toString();return this.request(`/orders${t?`?${t}`:""}`)}};var C=class extends d{async start(e){return this.request("/cart/sessions",{method:"POST",data:e})}async get(e){return this.request(`/cart/sessions/${e}`)}async update(e,t){return this.request(`/cart/sessions/${e}`,{method:"PATCH",data:t})}async cancel(e){return this.request(`/cart/sessions/${e}`,{method:"DELETE"})}async updateItem(e,t){return this.request(`/cart/sessions/${e}/item`,{method:"POST",data:t})}async preValidate(e,t){return this.request(`/cart/sessions/${e}/payment/pre-validate`,{method:"POST",data:t})}async processPayment(e,t){return this.request(`/cart/sessions/${e}/payment/process`,{method:"POST",data:t})}async placeOrder(e,t){return this.request(`/cart/sessions/${e}/place-order`,{method:"POST",data:t})}async deleteItem(e,t){return this.updateItem(e,{itemId:t,quantity:0})}async joinTableCommitment(e,t){return this.request(`/cart/sessions/${e}/join-table`,{method:"POST",data:{tableCommitmentId:t}})}async applyCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons`,{method:"POST",data:{code:t}})}async deleteCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons/${t}`,{method:"DELETE"})}};var p=class r{constructor(e,t){o(this,"events");o(this,"orders");o(this,"cart");o(this,"baseOptions");this.baseOptions=e;let{token:n,settings:s={}}=e,i=t??S({token:n,baseUrl:s.apiUrl||g,debug:s.debug});this.events=new f(i,s),this.orders=new y(i,s),this.cart=new C(i,s)}requestWithOverrides(e){let{token:t,settings:n={}}=this.baseOptions,s=(i,c={})=>S({token:e.token??t,baseUrl:e.baseUrl??n.apiUrl??g,debug:n.debug})(i,{...c,headers:{...e.headers||{},...c.headers||{}}});return new r({token:e.token??t,settings:{...n,apiUrl:e.baseUrl??n.apiUrl}},s)}};function L(r){return new p(r)}0&&(module.exports={CohostClient,createCohostClient});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/apiVersion.ts","../src/error/CohostError.ts","../src/settings.ts","../src/http/request.ts","../src/api/events.ts","../src/api/orders.ts","../src/api/sessions.ts","../src/client.ts"],"sourcesContent":["import { CohostClient, CohostClientOptions } from './client';\nexport { type CohostClientSettings } from './settings';\n\n/**\n * Factory method for creating a CohostClient instance.\n * \n * Example:\n * ```ts\n * const client = createCohostClient({ token: 'your-token' });\n * ```\n */\nexport function createCohostClient(options: CohostClientOptions): CohostClient {\n return new CohostClient(options);\n}\n\n\nexport { CohostClient }\n\nexport * from '../types';","import { RequestFn } from \"./http/request\";\nimport { CohostClientSettings } from \"./settings\";\n\n/**\n * Base class for all API endpoint groups within the Cohost SDK.\n * Provides shared access to the configured request function and settings.\n */\nexport class CohostEndpoint {\n /** Shared request function injected from the client */\n protected request: RequestFn;\n\n /** Client settings passed during instantiation */\n protected settings: CohostClientSettings;\n\n /**\n * Constructs a new endpoint group.\n *\n * @param request - The shared request function for performing API calls\n * @param settings - The client-wide settings passed from the parent client\n */\n constructor(request: RequestFn, settings: CohostClientSettings) {\n this.request = request;\n this.settings = settings;\n }\n}\n","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","\nexport interface CohostErrorProps {\n /**\n * Optional error code.\n * @default undefined\n */\n errorCode?: string;\n\n /**\n * Optional status code.\n * @default undefined\n */\n statusCode?: number;\n};\n\nexport class CohostError extends Error {\n errorCode: string | undefined;\n statusCode: number | undefined;\n\n /**\n * Custom error class for Cohost SDK errors.\n * @param message - The error message.\n */\n constructor(message: string, props?: CohostErrorProps) {\n // Call the parent constructor with the message\n super(message);\n\n // Set the name of the error to \"CohostError\"\n this.name = \"CohostError\";\n\n // Set the error code if provided\n this.errorCode = props?.errorCode;\n // Set the status code if provided\n this.statusCode = props?.statusCode;\n }\n\n static fromError(err: Error, props?: CohostErrorProps): CohostError {\n // Create a new CohostError instance from an existing error\n return new CohostError(err.message, {\n ...props,\n errorCode: props?.errorCode || err.name,\n });\n }\n\n}\n\n\n\n\n","/**\n * Optional settings for customizing the behavior of the CohostClient.\n */\nexport interface CohostClientSettings {\n /** Enable verbose debug output for all API requests. */\n debug?: boolean;\n\n /** Override the default API base URL (defaults to apiBaseUrl). */\n apiUrl?: string;\n}\n\n// settings.ts\nexport const defaultSettings = {\n baseUrl: 'https://api.cohost.vip',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\n// In dev or testing, you can override this in the browser or Node\nexport let runtimeOverrides: {\n baseUrl?: string;\n headers?: Record<string, string>;\n} = {};\n\nexport function setSdkOverrides(overrides: typeof runtimeOverrides) {\n runtimeOverrides = overrides;\n}\n\n","import { PaginatedRequest } from \"../../types\";\nimport { apiBaseUrl } from \"../apiVersion\";\nimport { CohostError } from \"../error/CohostError\";\nimport { defaultSettings, runtimeOverrides } from \"../settings\";\nimport { Pagination } from \"../types/pagination\";\n\n/**\n * Options for configuring the request handler.\n */\ninterface RequestProps {\n /** API token for authentication (Bearer token). */\n token: string | null;\n\n /** Base URL of the API (defaults to versioned `apiBaseUrl`). */\n baseUrl?: string;\n\n /** Enable debug logging of requests/responses. */\n debug?: boolean;\n}\n\n/**\n * Supported HTTP methods.\n */\ntype RequestMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\ntype RequestOptions = {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | string[] | undefined>;\n headers?: Record<string, string>;\n pagination?: Pagination;\n};\n\nexport const paginatedOptions = (req: PaginatedRequest<any>, options?: Partial<RequestOptions>): RequestOptions => {\n const { pagination, ...rest } = req;\n return {\n query: rest,\n pagination,\n ...options,\n };\n};\n\n/**\n * Builds a query string from a flat object, supporting array values via repeated keys.\n */\nconst buildQueryString = (\n input?: Record<string, string | number | boolean | string[] | undefined>\n): string => {\n if (!input) return \"\";\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n value.forEach((v) => params.append(key, String(v)));\n } else {\n params.set(key, String(value));\n }\n }\n return params.toString() ? `?${params.toString()}` : \"\";\n};\n\n/**\n * A function that performs a request to the Cohost API.\n * The generic <T> allows you to specify the expected response type.\n */\ntype RequestFn = <T = any>(\n path: string,\n options?: RequestOptions\n) => Promise<T>;\n\n/**\n * Creates a request function configured with authentication and client defaults.\n * The returned function supports generic return typing via <T>.\n */\nconst request = ({ token, baseUrl = apiBaseUrl, debug = false }: RequestProps): RequestFn => {\n return async function <T = any>(\n path: string,\n options: RequestOptions = {}\n ): Promise<T> {\n const { method = \"GET\", data, query, pagination, headers = {} } = options;\n\n const _query = {\n ...query,\n ...pagination,\n };\n\n const queryString = buildQueryString(_query);\n const finalBaseUrl = runtimeOverrides.baseUrl ?? baseUrl;\n const url = `${finalBaseUrl}${path}${queryString}`;\n\n const reqHeaders: Record<string, string> = {\n ...defaultSettings.headers,\n ...runtimeOverrides.headers,\n ...headers,\n };\n\n if (token) {\n reqHeaders[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const body = data && method !== \"GET\" ? JSON.stringify(data) : undefined;\n\n if (debug) {\n console.log(`[Cohost SDK] Request: ${method} ${url}`);\n if (body) console.log(`[Cohost SDK] Body:`, body);\n console.log(`[Cohost SDK] Headers:`, reqHeaders);\n }\n\n const res = await fetch(url, {\n method,\n headers: reqHeaders,\n body,\n });\n\n const isJson = res.headers.get(\"content-type\")?.includes(\"application/json\");\n const responseBody = isJson ? await res.json() : await res.text();\n\n if (!res.ok) {\n const message = typeof responseBody === \"string\" ? responseBody : JSON.stringify(responseBody);\n console.error(`[Cohost SDK] Error: ${message}`, { url });\n throw new CohostError(message || res.statusText, {\n errorCode: res.statusText || \"API_ERROR\",\n statusCode: res.status,\n });\n }\n\n if (\n typeof responseBody === \"object\" &&\n responseBody !== null &&\n (responseBody as any).status === \"ok\" &&\n \"data\" in responseBody\n ) {\n return (responseBody as { data: T }).data;\n }\n\n return responseBody as T;\n };\n};\n\nexport { type RequestProps, type RequestFn };\nexport { request };\n","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\nimport { Attendee3, EventProfile, PaginatedRequest, PaginatedResponse, Ticket } from '../../types/index';\nimport { paginatedOptions } from '../http/request';\n\n/**\n * Provides methods to interact with the Cohost Events API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const list = await client.events.list();\n * const event = await client.events.fetch('event-id');\n * const tickets = await client.events.tickets('event-id');\n * ```\n */\nexport class EventsAPI extends CohostEndpoint {\n\n /**\n * Fetch a list of all events.\n * \n * @returns A Promise resolving to an array of event objects\n * @throws Will throw an error if the request fails\n * \n * @todo Implement pagination and filtering options\n */\n async list() {\n return this.request<EventProfile[]>('/events');\n }\n\n\n /**\n * Fetch a single event by ID.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to the event object\n * @throws Will throw an error if the request fails or the event is not found\n */\n async fetch(id: string) {\n return this.request<EventProfile>(`/events/${id}`);\n }\n\n\n\n /**\n * List all tickets associated with a specific event.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to an array of ticket objects\n * @throws Will throw an error if the request fails or the event does not exist\n */\n async tickets(id: string) {\n return this.request<Ticket[]>(`/events/${id}/tickets`);\n }\n\n /**\n * List attendees in the event.\n *\n * Requires: valid authentication token. This endpoint is not public.\n * \n * @param id - The ID of the event.\n * @returns List of tickets (attendees) for the event.\n */\n async attendees(id: string, filters?: PaginatedRequest<any>) {\n return this.request<PaginatedResponse<Attendee3>>(`/events/${id}/attendees`, paginatedOptions(filters));\n }\n\n \n\n}\n","import { CohostEndpoint } from '../endpoint';\n\n/**\n * Provides methods to interact with the Cohost Orders API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const order = await client.orders.fetch('order-id', 'user-id');\n * const list = await client.orders.list({ status: 'completed' });\n * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\n\n /**\n * Fetch a single order by ID.\n * \n * @param id - The unique identifier of the order\n * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)\n * @returns A Promise resolving to the order object\n * @throws Will throw an error if the request fails or the order is not found\n */\n async fetch(id: string, uid: string) {\n // uid is reserved for future scoped access/auth features\n return this.request(`/orders/${id}?uid=${uid}`);\n }\n\n /**\n * List orders with optional filters.\n * \n * @param filters - Optional filters to apply when retrieving orders\n * @returns A Promise resolving to an array of order summaries\n * @throws Will throw an error if the request fails\n */\n async list(filters?: {\n status?: string;\n startDate?: string;\n endDate?: string;\n page?: number;\n pageSize?: number;\n }) {\n const query = new URLSearchParams(filters as Record<string, string>).toString();\n return this.request(`/orders${query ? `?${query}` : ''}`);\n }\n}\n","import { CartSession, UpdatableCartSession } from '../../types';\nimport { CohostEndpoint } from '../endpoint';\nimport { FindTablesProps, StartCartSessionInput, ViableTableOption } from '../types/sessions';\n\n/**\n * Provides methods to interact with cart sessions in the Cohost API.\n *\n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const session = await client.sessions.start({ contextId: 'evt_abc123' });\n * ```\n */\nexport class SessionsAPI extends CohostEndpoint {\n\n /**\n * Start a new cart session.\n *\n * @param input - Data to start the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the request fails\n */\n async start(input: StartCartSessionInput) {\n return this.request<CartSession>('/cart/sessions', {\n method: 'POST',\n data: input,\n });\n }\n\n /**\n * Get a cart session by its ID.\n *\n * @param id - The unique session ID\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the session is not found or request fails\n */\n async get(id: string) {\n return this.request<CartSession>(`/cart/sessions/${id}`);\n }\n\n /**\n * Update a cart session.\n *\n * @param id - The ID of the session to update\n * @param input - Data to update the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async update(id: string, input: Partial<UpdatableCartSession>) {\n return this.request<CartSession>(`/cart/sessions/${id}`, {\n method: 'PATCH',\n data: input,\n });\n }\n\n /**\n * Cancel (soft delete) a cart session.\n *\n * @param id - The ID of the session to cancel\n * @returns Nothing if successful\n * \n * @throws Will throw an error if the cancel operation fails\n */\n async cancel(id: string) {\n return this.request<void>(`/cart/sessions/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Update an item in the cart session.\n *\n * @param sessionId - The ID of the session\n * @param props - Properties to update\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async updateItem(sessionId: string, props: {\n itemId: string;\n quantity: number;\n options?: {\n [key: string]: any;\n };\n }) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/item`, {\n method: 'POST',\n data: props,\n });\n }\n\n /**\n * Pre-validate the cart session for payment and checkout.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for validation\n * @returns {CartSession} The validated cart session\n * \n * @throws Will throw an error if validation fails\n */\n async preValidate(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/pre-validate`, {\n method: 'POST',\n data: data,\n });\n }\n\n\n\n /**\n * Prepare the cart session for payment.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for payment preparation\n * @returns {CartSession} The prepared cart session\n * \n * @throws Will throw an error if preparation fails\n */\n async processPayment(sessionId: string, data: unknown) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/process`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Close the cart session, and place the order.\n * \n * @param sessionId - The ID of the session\n * @param data - Data to place the order\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the order placement fails\n */\n async placeOrder(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/place-order`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Remove an item from the cart session.\n * The same as setting the quantity to 0.\n * \n * @param sessionId - The ID of the cart session\n * @param itemId - The ID of the item to remove\n * @returns {CartSession} The latest cart session\n */\n async deleteItem(sessionId: string, itemId: string) {\n return this.updateItem(sessionId, {\n itemId,\n quantity: 0,\n });\n }\n\n\n\n\n\n /**\n * Join a table commitment within an active cart session.\n *\n * @param id - The ID of the cart session\n * @param tableCommitmentId - The table commitment ID to join\n * @returns {CartSession} Updated cart session with joined table\n * \n * @throws Will throw an error if the join operation fails\n */\n async joinTableCommitment(id: string, tableCommitmentId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/join-table`, {\n method: 'POST',\n data: {\n tableCommitmentId,\n }\n });\n }\n\n\n /**\n * Apply a coupon code to the cart session.\n *\n * @param id - The ID of the cart session\n * @param code - The coupon code to apply\n * @returns {CartSession} Updated cart session with applied coupon\n * \n * @throws Will throw an error if the coupon application fails\n */\n async applyCoupon(id: string, code: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons`, {\n method: 'POST',\n data: {\n code\n }\n });\n }\n\n /**\n * Find viable table options for a cart session.\n *\n * @param id - The ID of the cart session\n * @param props - Properties to find viable tables\n * @returns {ViableTableOption[]} List of viable table options\n * \n * @throws Will throw an error if the request fails\n */\n async deleteCoupon(id: string, couponId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons/${couponId}`, {\n method: 'DELETE'\n });\n }\n}\n","import { EventsAPI } from './api/events';\nimport { OrdersAPI } from './api/orders';\nimport { SessionsAPI } from './api/sessions';\nimport { apiBaseUrl } from './apiVersion';\nimport { request, RequestFn } from './http/request';\nimport { CohostClientSettings } from './settings';\n\n/**\n * Configuration options for instantiating a CohostClient.\n */\nexport interface CohostClientOptions {\n /** API token used for authenticated requests. */\n token: string;\n\n /** Optional client settings such as debug mode or custom API URL. */\n settings?: CohostClientSettings;\n}\n\n/**\n * CohostClient provides grouped access to various API modules such as Events and Orders.\n */\nexport class CohostClient {\n public readonly events: EventsAPI;\n public readonly orders: OrdersAPI;\n public readonly cart: SessionsAPI;\n\n private readonly baseOptions: CohostClientOptions;\n\n constructor(options: CohostClientOptions, customRequestFn?: RequestFn) {\n this.baseOptions = options;\n\n const { token, settings = {} } = options;\n\n const sharedRequest = customRequestFn ?? request({\n token,\n baseUrl: settings.apiUrl || apiBaseUrl,\n debug: settings.debug,\n });\n\n this.events = new EventsAPI(sharedRequest, settings);\n this.orders = new OrdersAPI(sharedRequest, settings);\n this.cart = new SessionsAPI(sharedRequest, settings);\n }\n\n /**\n * Returns a new CohostClient instance with overridden request behavior\n */\n public requestWithOverrides(overrides: {\n token?: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n }): CohostClient {\n const { token, settings = {} } = this.baseOptions;\n\n const overriddenRequest: RequestFn = (path, options = {}) =>\n request({\n token: overrides.token ?? token,\n baseUrl: overrides.baseUrl ?? settings.apiUrl ?? apiBaseUrl,\n debug: settings.debug,\n })(path, {\n ...options,\n headers: {\n ...(overrides.headers || {}),\n ...(options.headers || {}),\n },\n });\n\n return new CohostClient(\n {\n token: overrides.token ?? token,\n settings: {\n ...settings,\n apiUrl: overrides.baseUrl ?? settings.apiUrl,\n },\n },\n overriddenRequest\n );\n }\n}\n"],"mappings":"ijBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,uBAAAC,I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K,KAAO,IAAIM,EAAYL,EAAeD,CAAQ,CACrD,CAKO,qBAAqBO,EAIX,CACf,GAAM,CAAE,MAAAR,EAAO,SAAAC,EAAW,CAAC,CAAE,EAAI,KAAK,YAEhCQ,EAA+B,CAACC,EAAMb,EAAU,CAAC,IACrDM,EAAQ,CACN,MAAOK,EAAU,OAASR,EAC1B,QAASQ,EAAU,SAAWP,EAAS,QAAUG,EACjD,MAAOH,EAAS,KAClB,CAAC,EAAES,EAAM,CACP,GAAGb,EACH,QAAS,CACP,GAAIW,EAAU,SAAW,CAAC,EAC1B,GAAIX,EAAQ,SAAW,CAAC,CAC1B,CACF,CAAC,EAEH,OAAO,IAAID,EACT,CACE,MAAOY,EAAU,OAASR,EAC1B,SAAU,CACR,GAAGC,EACH,OAAQO,EAAU,SAAWP,EAAS,MACxC,CACF,EACAQ,CACF,CACF,CACF,ETnEO,SAASE,EAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["index_exports","__export","CohostClient","createCohostClient","__toCommonJS","CohostEndpoint","request","settings","__publicField","apiBaseUrl","CohostError","_CohostError","message","props","__publicField","err","defaultSettings","runtimeOverrides","paginatedOptions","req","options","pagination","rest","buildQueryString","input","params","key","value","v","request","token","baseUrl","apiBaseUrl","debug","path","method","data","query","headers","_query","queryString","url","runtimeOverrides","reqHeaders","defaultSettings","body","res","responseBody","message","CohostError","EventsAPI","CohostEndpoint","id","filters","paginatedOptions","OrdersAPI","CohostEndpoint","id","uid","filters","query","SessionsAPI","CohostEndpoint","input","id","sessionId","props","data","itemId","tableCommitmentId","code","couponId","CohostClient","_CohostClient","options","customRequestFn","__publicField","token","settings","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","SessionsAPI","overrides","overriddenRequest","path","createCohostClient","options","CohostClient"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/apiVersion.ts","../src/error/CohostError.ts","../src/settings.ts","../src/http/request.ts","../src/api/events.ts","../src/api/orders.ts","../src/api/sessions.ts","../src/client.ts"],"sourcesContent":["import { CohostClient, CohostClientOptions } from './client';\nexport { type CohostClientSettings } from './settings';\n\n/**\n * Factory method for creating a CohostClient instance.\n * \n * Example:\n * ```ts\n * const client = createCohostClient({ token: 'your-token' });\n * ```\n */\nexport function createCohostClient(options: CohostClientOptions): CohostClient {\n return new CohostClient(options);\n}\n\n\nexport { CohostClient }\n\nexport * from '../types';","import { RequestFn } from \"./http/request\";\nimport { CohostClientSettings } from \"./settings\";\n\n/**\n * Base class for all API endpoint groups within the Cohost SDK.\n * Provides shared access to the configured request function and settings.\n */\nexport class CohostEndpoint {\n /** Shared request function injected from the client */\n protected request: RequestFn;\n\n /** Client settings passed during instantiation */\n protected settings: CohostClientSettings;\n\n /**\n * Constructs a new endpoint group.\n *\n * @param request - The shared request function for performing API calls\n * @param settings - The client-wide settings passed from the parent client\n */\n constructor(request: RequestFn, settings: CohostClientSettings) {\n this.request = request;\n this.settings = settings;\n }\n}\n","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","\nexport interface CohostErrorProps {\n /**\n * Optional error code.\n * @default undefined\n */\n errorCode?: string;\n\n /**\n * Optional status code.\n * @default undefined\n */\n statusCode?: number;\n};\n\nexport class CohostError extends Error {\n errorCode: string | undefined;\n statusCode: number | undefined;\n\n /**\n * Custom error class for Cohost SDK errors.\n * @param message - The error message.\n */\n constructor(message: string, props?: CohostErrorProps) {\n // Call the parent constructor with the message\n super(message);\n\n // Set the name of the error to \"CohostError\"\n this.name = \"CohostError\";\n\n // Set the error code if provided\n this.errorCode = props?.errorCode;\n // Set the status code if provided\n this.statusCode = props?.statusCode;\n }\n\n static fromError(err: Error, props?: CohostErrorProps): CohostError {\n // Create a new CohostError instance from an existing error\n return new CohostError(err.message, {\n ...props,\n errorCode: props?.errorCode || err.name,\n });\n }\n\n}\n\n\n\n\n","/**\n * Optional settings for customizing the behavior of the CohostClient.\n */\nexport interface CohostClientSettings {\n /** Enable verbose debug output for all API requests. */\n debug?: boolean;\n\n /** Override the default API base URL (defaults to apiBaseUrl). */\n apiUrl?: string;\n}\n\n// settings.ts\nexport const defaultSettings = {\n baseUrl: 'https://api.cohost.vip',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\n// In dev or testing, you can override this in the browser or Node\nexport let runtimeOverrides: {\n baseUrl?: string;\n headers?: Record<string, string>;\n} = {};\n\nexport function setSdkOverrides(overrides: typeof runtimeOverrides) {\n runtimeOverrides = overrides;\n}\n\n","import { PaginatedRequest } from \"../../types\";\nimport { apiBaseUrl } from \"../apiVersion\";\nimport { CohostError } from \"../error/CohostError\";\nimport { defaultSettings, runtimeOverrides } from \"../settings\";\nimport { Pagination } from \"../types/pagination\";\n\n/**\n * Options for configuring the request handler.\n */\ninterface RequestProps {\n /** API token for authentication (Bearer token). */\n token: string | null;\n\n /** Base URL of the API (defaults to versioned `apiBaseUrl`). */\n baseUrl?: string;\n\n /** Enable debug logging of requests/responses. */\n debug?: boolean;\n}\n\n/**\n * Supported HTTP methods.\n */\ntype RequestMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\ntype RequestOptions = {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | string[] | undefined>;\n headers?: Record<string, string>;\n pagination?: Pagination;\n};\n\nexport const paginatedOptions = (req: PaginatedRequest<any>, options?: Partial<RequestOptions>): RequestOptions => {\n const { pagination, ...rest } = req;\n return {\n query: rest,\n pagination,\n ...options,\n };\n};\n\n/**\n * Builds a query string from a flat object, supporting array values via repeated keys.\n */\nconst buildQueryString = (\n input?: Record<string, string | number | boolean | string[] | undefined>\n): string => {\n if (!input) return \"\";\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n value.forEach((v) => params.append(key, String(v)));\n } else {\n params.set(key, String(value));\n }\n }\n return params.toString() ? `?${params.toString()}` : \"\";\n};\n\n/**\n * A function that performs a request to the Cohost API.\n * The generic <T> allows you to specify the expected response type.\n */\ntype RequestFn = <T = any>(\n path: string,\n options?: RequestOptions\n) => Promise<T>;\n\n/**\n * Creates a request function configured with authentication and client defaults.\n * The returned function supports generic return typing via <T>.\n */\nconst request = ({ token, baseUrl = apiBaseUrl, debug = false }: RequestProps): RequestFn => {\n return async function <T = any>(\n path: string,\n options: RequestOptions = {}\n ): Promise<T> {\n const { method = \"GET\", data, query, pagination, headers = {} } = options;\n\n const _query = {\n ...query,\n ...pagination,\n };\n\n const queryString = buildQueryString(_query);\n const finalBaseUrl = runtimeOverrides.baseUrl ?? baseUrl;\n const url = `${finalBaseUrl}${path}${queryString}`;\n\n const reqHeaders: Record<string, string> = {\n ...defaultSettings.headers,\n ...runtimeOverrides.headers,\n ...headers,\n };\n\n if (token) {\n reqHeaders[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const body = data && method !== \"GET\" ? JSON.stringify(data) : undefined;\n\n if (debug) {\n console.log(`[Cohost SDK] Request: ${method} ${url}`);\n if (body) console.log(`[Cohost SDK] Body:`, body);\n console.log(`[Cohost SDK] Headers:`, reqHeaders);\n }\n\n const res = await fetch(url, {\n method,\n headers: reqHeaders,\n body,\n });\n\n const isJson = res.headers.get(\"content-type\")?.includes(\"application/json\");\n const responseBody = isJson ? await res.json() : await res.text();\n\n if (!res.ok) {\n const message = typeof responseBody === \"string\" ? responseBody : JSON.stringify(responseBody);\n console.error(`[Cohost SDK] Error: ${message}`, { url });\n throw new CohostError(message || res.statusText, {\n errorCode: res.statusText || \"API_ERROR\",\n statusCode: res.status,\n });\n }\n\n if (\n typeof responseBody === \"object\" &&\n responseBody !== null &&\n (responseBody as any).status === \"ok\" &&\n \"data\" in responseBody\n ) {\n return (responseBody as { data: T }).data;\n }\n\n return responseBody as T;\n };\n};\n\nexport { type RequestProps, type RequestFn };\nexport { request };\n","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\nimport { Attendee, EventProfile, PaginatedRequest, PaginatedResponse, Ticket } from '../../types/index';\nimport { paginatedOptions } from '../http/request';\n\n/**\n * Provides methods to interact with the Cohost Events API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const list = await client.events.list();\n * const event = await client.events.fetch('event-id');\n * const tickets = await client.events.tickets('event-id');\n * ```\n */\nexport class EventsAPI extends CohostEndpoint {\n\n /**\n * Fetch a list of all events.\n * \n * @returns A Promise resolving to an array of event objects\n * @throws Will throw an error if the request fails\n * \n * @todo Implement pagination and filtering options\n */\n async list() {\n return this.request<EventProfile[]>('/events');\n }\n\n\n /**\n * Fetch a single event by ID.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to the event object\n * @throws Will throw an error if the request fails or the event is not found\n */\n async fetch(id: string) {\n return this.request<EventProfile>(`/events/${id}`);\n }\n\n\n\n /**\n * List all tickets associated with a specific event.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to an array of ticket objects\n * @throws Will throw an error if the request fails or the event does not exist\n */\n async tickets(id: string) {\n return this.request<Ticket[]>(`/events/${id}/tickets`);\n }\n\n /**\n * List attendees in the event.\n *\n * Requires: valid authentication token. This endpoint is not public.\n * \n * @param id - The ID of the event.\n * @returns List of tickets (attendees) for the event.\n */\n async attendees(id: string, filters?: PaginatedRequest<any>) {\n return this.request<PaginatedResponse<Attendee>>(`/events/${id}/attendees`, paginatedOptions(filters));\n }\n\n \n\n}\n","import { CohostEndpoint } from '../endpoint';\n\n/**\n * Provides methods to interact with the Cohost Orders API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const order = await client.orders.fetch('order-id', 'user-id');\n * const list = await client.orders.list({ status: 'completed' });\n * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\n\n /**\n * Fetch a single order by ID.\n * \n * @param id - The unique identifier of the order\n * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)\n * @returns A Promise resolving to the order object\n * @throws Will throw an error if the request fails or the order is not found\n */\n async fetch(id: string, uid: string) {\n // uid is reserved for future scoped access/auth features\n return this.request(`/orders/${id}?uid=${uid}`);\n }\n\n /**\n * Fetch a single order by ID.\n * \n * @param id - The unique identifier of the order\n * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)\n * @returns A Promise resolving to the order object\n * @throws Will throw an error if the request fails or the order is not found\n */\n async attendees(id: string, uid: string) {\n // uid is reserved for future scoped access/auth features\n return this.request(`/orders/${id}/attendees?uid=${uid}`);\n }\n\n /**\n * List orders with optional filters.\n * \n * @param filters - Optional filters to apply when retrieving orders\n * @returns A Promise resolving to an array of order summaries\n * @throws Will throw an error if the request fails\n */\n async list(filters?: {\n status?: string;\n startDate?: string;\n endDate?: string;\n page?: number;\n pageSize?: number;\n }) {\n const query = new URLSearchParams(filters as Record<string, string>).toString();\n return this.request(`/orders${query ? `?${query}` : ''}`);\n }\n}\n","import { CartSession, StartCartSessionInput, UpdatableCartSession } from '../../types';\nimport { CohostEndpoint } from '../endpoint';\n\n/**\n * Provides methods to interact with cart sessions in the Cohost API.\n *\n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const session = await client.sessions.start({ contextId: 'evt_abc123' });\n * ```\n */\nexport class SessionsAPI extends CohostEndpoint {\n\n /**\n * Start a new cart session.\n *\n * @param input - Data to start the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the request fails\n */\n async start(input: StartCartSessionInput) {\n return this.request<CartSession>('/cart/sessions', {\n method: 'POST',\n data: input,\n });\n }\n\n /**\n * Get a cart session by its ID.\n *\n * @param id - The unique session ID\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the session is not found or request fails\n */\n async get(id: string) {\n return this.request<CartSession>(`/cart/sessions/${id}`);\n }\n\n /**\n * Update a cart session.\n *\n * @param id - The ID of the session to update\n * @param input - Data to update the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async update(id: string, input: Partial<UpdatableCartSession>) {\n return this.request<CartSession>(`/cart/sessions/${id}`, {\n method: 'PATCH',\n data: input,\n });\n }\n\n /**\n * Cancel (soft delete) a cart session.\n *\n * @param id - The ID of the session to cancel\n * @returns Nothing if successful\n * \n * @throws Will throw an error if the cancel operation fails\n */\n async cancel(id: string) {\n return this.request<void>(`/cart/sessions/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Update an item in the cart session.\n *\n * @param sessionId - The ID of the session\n * @param props - Properties to update\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async updateItem(sessionId: string, props: {\n itemId: string;\n quantity: number;\n options?: {\n [key: string]: any;\n };\n }) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/item`, {\n method: 'POST',\n data: props,\n });\n }\n\n /**\n * Pre-validate the cart session for payment and checkout.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for validation\n * @returns {CartSession} The validated cart session\n * \n * @throws Will throw an error if validation fails\n */\n async preValidate(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/pre-validate`, {\n method: 'POST',\n data: data,\n });\n }\n\n\n\n /**\n * Prepare the cart session for payment.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for payment preparation\n * @returns {CartSession} The prepared cart session\n * \n * @throws Will throw an error if preparation fails\n */\n async processPayment(sessionId: string, data: unknown) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/process`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Close the cart session, and place the order.\n * \n * @param sessionId - The ID of the session\n * @param data - Data to place the order\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the order placement fails\n */\n async placeOrder(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/place-order`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Remove an item from the cart session.\n * The same as setting the quantity to 0.\n * \n * @param sessionId - The ID of the cart session\n * @param itemId - The ID of the item to remove\n * @returns {CartSession} The latest cart session\n */\n async deleteItem(sessionId: string, itemId: string) {\n return this.updateItem(sessionId, {\n itemId,\n quantity: 0,\n });\n }\n\n\n\n\n\n /**\n * Join a table commitment within an active cart session.\n *\n * @param id - The ID of the cart session\n * @param tableCommitmentId - The table commitment ID to join\n * @returns {CartSession} Updated cart session with joined table\n * \n * @throws Will throw an error if the join operation fails\n */\n async joinTableCommitment(id: string, tableCommitmentId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/join-table`, {\n method: 'POST',\n data: {\n tableCommitmentId,\n }\n });\n }\n\n\n /**\n * Apply a coupon code to the cart session.\n *\n * @param id - The ID of the cart session\n * @param code - The coupon code to apply\n * @returns {CartSession} Updated cart session with applied coupon\n * \n * @throws Will throw an error if the coupon application fails\n */\n async applyCoupon(id: string, code: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons`, {\n method: 'POST',\n data: {\n code\n }\n });\n }\n\n /**\n * Find viable table options for a cart session.\n *\n * @param id - The ID of the cart session\n * @param props - Properties to find viable tables\n * @returns {ViableTableOption[]} List of viable table options\n * \n * @throws Will throw an error if the request fails\n */\n async deleteCoupon(id: string, couponId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons/${couponId}`, {\n method: 'DELETE'\n });\n }\n}\n","import { EventsAPI } from './api/events';\nimport { OrdersAPI } from './api/orders';\nimport { SessionsAPI } from './api/sessions';\nimport { apiBaseUrl } from './apiVersion';\nimport { request, RequestFn } from './http/request';\nimport { CohostClientSettings } from './settings';\n\n/**\n * Configuration options for instantiating a CohostClient.\n */\nexport interface CohostClientOptions {\n /** API token used for authenticated requests. */\n token: string;\n\n /** Optional client settings such as debug mode or custom API URL. */\n settings?: CohostClientSettings;\n}\n\n/**\n * CohostClient provides grouped access to various API modules such as Events and Orders.\n */\nexport class CohostClient {\n public readonly events: EventsAPI;\n public readonly orders: OrdersAPI;\n public readonly cart: SessionsAPI;\n\n private readonly baseOptions: CohostClientOptions;\n\n constructor(options: CohostClientOptions, customRequestFn?: RequestFn) {\n this.baseOptions = options;\n\n const { token, settings = {} } = options;\n\n const sharedRequest = customRequestFn ?? request({\n token,\n baseUrl: settings.apiUrl || apiBaseUrl,\n debug: settings.debug,\n });\n\n this.events = new EventsAPI(sharedRequest, settings);\n this.orders = new OrdersAPI(sharedRequest, settings);\n this.cart = new SessionsAPI(sharedRequest, settings);\n }\n\n /**\n * Returns a new CohostClient instance with overridden request behavior\n */\n public requestWithOverrides(overrides: {\n token?: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n }): CohostClient {\n const { token, settings = {} } = this.baseOptions;\n\n const overriddenRequest: RequestFn = (path, options = {}) =>\n request({\n token: overrides.token ?? token,\n baseUrl: overrides.baseUrl ?? settings.apiUrl ?? apiBaseUrl,\n debug: settings.debug,\n })(path, {\n ...options,\n headers: {\n ...(overrides.headers || {}),\n ...(options.headers || {}),\n },\n });\n\n return new CohostClient(\n {\n token: overrides.token ?? token,\n settings: {\n ...settings,\n apiUrl: overrides.baseUrl ?? settings.apiUrl,\n },\n },\n overriddenRequest\n );\n }\n}\n"],"mappings":"ijBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,uBAAAC,IAAA,eAAAC,EAAAJ,GCOO,IAAMK,EAAN,KAAqB,CAa1B,YAAYC,EAAoBC,EAAgC,CAXhEC,EAAA,KAAU,WAGVA,EAAA,KAAU,YASR,KAAK,QAAUF,EACf,KAAK,SAAWC,CAClB,CACF,ECtBO,IAAME,EAAa,4BCanB,IAAMC,EAAN,MAAMC,UAAoB,KAAM,CAQnC,YAAYC,EAAiBC,EAA0B,CAEnD,MAAMD,CAAO,EATjBE,EAAA,kBACAA,EAAA,mBAWI,KAAK,KAAO,cAGZ,KAAK,UAAYD,GAAO,UAExB,KAAK,WAAaA,GAAO,UAC7B,CAEA,OAAO,UAAUE,EAAYF,EAAuC,CAEhE,OAAO,IAAIF,EAAYI,EAAI,QAAS,CAChC,GAAGF,EACH,UAAWA,GAAO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,CAC1B,CACF,CAAC,EAEH,OAAO,IAAID,EACT,CACE,MAAOY,EAAU,OAASR,EAC1B,SAAU,CACR,GAAGC,EACH,OAAQO,EAAU,SAAWP,EAAS,MACxC,CACF,EACAQ,CACF,CACF,CACF,ETnEO,SAASE,EAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["index_exports","__export","CohostClient","createCohostClient","__toCommonJS","CohostEndpoint","request","settings","__publicField","apiBaseUrl","CohostError","_CohostError","message","props","__publicField","err","defaultSettings","runtimeOverrides","paginatedOptions","req","options","pagination","rest","buildQueryString","input","params","key","value","v","request","token","baseUrl","apiBaseUrl","debug","path","method","data","query","headers","_query","queryString","url","runtimeOverrides","reqHeaders","defaultSettings","body","res","responseBody","message","CohostError","EventsAPI","CohostEndpoint","id","filters","paginatedOptions","OrdersAPI","CohostEndpoint","id","uid","filters","query","SessionsAPI","CohostEndpoint","input","id","sessionId","props","data","itemId","tableCommitmentId","code","couponId","CohostClient","_CohostClient","options","customRequestFn","__publicField","token","settings","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","SessionsAPI","overrides","overriddenRequest","path","createCohostClient","options","CohostClient"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var T=Object.defineProperty;var E=(n,e,t)=>e in n?T(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var o=(n,e,t)=>E(n,typeof e!="symbol"?e+"":e,t);var u=class{constructor(e,t){o(this,"request");o(this,"settings");this.request=e,this.settings=t}};var g="https://api.cohost.com/v1";var p=class n extends Error{constructor(t,r){super(t);o(this,"errorCode");o(this,"statusCode");this.name="CohostError",this.errorCode=r?.errorCode,this.statusCode=r?.statusCode}static fromError(t,r){return new n(t.message,{...r,errorCode:r?.errorCode||t.name})}};var P={baseUrl:"https://api.cohost.vip",headers:{"Content-Type":"application/json"}},b={};var v=(n,e)=>{let{pagination:t,...r}=n;return{query:r,pagination:t,...e}},w=n=>{if(!n)return"";let e=new URLSearchParams;for(let[t,r]of Object.entries(n))r!==void 0&&(Array.isArray(r)?r.forEach(s=>e.append(t,String(s))):e.set(t,String(r)));return e.toString()?`?${e.toString()}`:""},O=({token:n,baseUrl:e=g,debug:t=!1})=>async function(r,s={}){let{method:i="GET",data:c,query:R,pagination:q,headers:I={}}=s,A={...R,...q},k=w(A),C=`${b.baseUrl??e}${r}${k}`,x={...P.headers,...b.headers,...I};n&&(x.Authorization=`Bearer ${n}`);let h=c&&i!=="GET"?JSON.stringify(c):void 0;t&&(console.log(`[Cohost SDK] Request: ${i} ${C}`),h&&console.log("[Cohost SDK] Body:",h),console.log("[Cohost SDK] Headers:",x));let d=await fetch(C,{method:i,headers:x,body:h}),a=d.headers.get("content-type")?.includes("application/json")?await d.json():await d.text();if(!d.ok){let S=typeof a=="string"?a:JSON.stringify(a);throw console.error(`[Cohost SDK] Error: ${S}`,{url:C}),new p(S||d.statusText,{errorCode:d.statusText||"API_ERROR",statusCode:d.status})}return typeof a=="object"&&a!==null&&a.status==="ok"&&"data"in a?a.data:a};var l=class extends u{async list(){return this.request("/events")}async fetch(e){return this.request(`/events/${e}`)}async tickets(e){return this.request(`/events/${e}/tickets`)}async attendees(e,t){return this.request(`/events/${e}/attendees`,v(t))}};var m=class extends u{async fetch(e,t){return this.request(`/orders/${e}?uid=${t}`)}async list(e){let t=new URLSearchParams(e).toString();return this.request(`/orders${t?`?${t}`:""}`)}};var f=class extends u{async start(e){return this.request("/cart/sessions",{method:"POST",data:e})}async get(e){return this.request(`/cart/sessions/${e}`)}async update(e,t){return this.request(`/cart/sessions/${e}`,{method:"PATCH",data:t})}async cancel(e){return this.request(`/cart/sessions/${e}`,{method:"DELETE"})}async updateItem(e,t){return this.request(`/cart/sessions/${e}/item`,{method:"POST",data:t})}async preValidate(e,t){return this.request(`/cart/sessions/${e}/payment/pre-validate`,{method:"POST",data:t})}async processPayment(e,t){return this.request(`/cart/sessions/${e}/payment/process`,{method:"POST",data:t})}async placeOrder(e,t){return this.request(`/cart/sessions/${e}/place-order`,{method:"POST",data:t})}async deleteItem(e,t){return this.updateItem(e,{itemId:t,quantity:0})}async joinTableCommitment(e,t){return this.request(`/cart/sessions/${e}/join-table`,{method:"POST",data:{tableCommitmentId:t}})}async applyCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons`,{method:"POST",data:{code:t}})}async deleteCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons/${t}`,{method:"DELETE"})}};var y=class n{constructor(e,t){o(this,"events");o(this,"orders");o(this,"cart");o(this,"baseOptions");this.baseOptions=e;let{token:r,settings:s={}}=e,i=t??O({token:r,baseUrl:s.apiUrl||g,debug:s.debug});this.events=new l(i,s),this.orders=new m(i,s),this.cart=new f(i,s)}requestWithOverrides(e){let{token:t,settings:r={}}=this.baseOptions,s=(i,c={})=>O({token:e.token??t,baseUrl:e.baseUrl??r.apiUrl??g,debug:r.debug})(i,{...c,headers:{...e.headers||{},...c.headers||{}}});return new n({token:e.token??t,settings:{...r,apiUrl:e.baseUrl??r.apiUrl}},s)}};function de(n){return new y(n)}export{y as CohostClient,de as createCohostClient};
1
+ var T=Object.defineProperty;var E=(r,e,t)=>e in r?T(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>E(r,typeof e!="symbol"?e+"":e,t);var d=class{constructor(e,t){o(this,"request");o(this,"settings");this.request=e,this.settings=t}};var g="https://api.cohost.com/v1";var p=class r extends Error{constructor(t,n){super(t);o(this,"errorCode");o(this,"statusCode");this.name="CohostError",this.errorCode=n?.errorCode,this.statusCode=n?.statusCode}static fromError(t,n){return new r(t.message,{...n,errorCode:n?.errorCode||t.name})}};var P={baseUrl:"https://api.cohost.vip",headers:{"Content-Type":"application/json"}},b={};var v=(r,e)=>{let{pagination:t,...n}=r;return{query:n,pagination:t,...e}},$=r=>{if(!r)return"";let e=new URLSearchParams;for(let[t,n]of Object.entries(r))n!==void 0&&(Array.isArray(n)?n.forEach(s=>e.append(t,String(s))):e.set(t,String(n)));return e.toString()?`?${e.toString()}`:""},O=({token:r,baseUrl:e=g,debug:t=!1})=>async function(n,s={}){let{method:i="GET",data:c,query:R,pagination:q,headers:I={}}=s,A={...R,...q},k=$(A),C=`${b.baseUrl??e}${n}${k}`,x={...P.headers,...b.headers,...I};r&&(x.Authorization=`Bearer ${r}`);let h=c&&i!=="GET"?JSON.stringify(c):void 0;t&&(console.log(`[Cohost SDK] Request: ${i} ${C}`),h&&console.log("[Cohost SDK] Body:",h),console.log("[Cohost SDK] Headers:",x));let u=await fetch(C,{method:i,headers:x,body:h}),a=u.headers.get("content-type")?.includes("application/json")?await u.json():await u.text();if(!u.ok){let S=typeof a=="string"?a:JSON.stringify(a);throw console.error(`[Cohost SDK] Error: ${S}`,{url:C}),new p(S||u.statusText,{errorCode:u.statusText||"API_ERROR",statusCode:u.status})}return typeof a=="object"&&a!==null&&a.status==="ok"&&"data"in a?a.data:a};var l=class extends d{async list(){return this.request("/events")}async fetch(e){return this.request(`/events/${e}`)}async tickets(e){return this.request(`/events/${e}/tickets`)}async attendees(e,t){return this.request(`/events/${e}/attendees`,v(t))}};var m=class extends d{async fetch(e,t){return this.request(`/orders/${e}?uid=${t}`)}async attendees(e,t){return this.request(`/orders/${e}/attendees?uid=${t}`)}async list(e){let t=new URLSearchParams(e).toString();return this.request(`/orders${t?`?${t}`:""}`)}};var f=class extends d{async start(e){return this.request("/cart/sessions",{method:"POST",data:e})}async get(e){return this.request(`/cart/sessions/${e}`)}async update(e,t){return this.request(`/cart/sessions/${e}`,{method:"PATCH",data:t})}async cancel(e){return this.request(`/cart/sessions/${e}`,{method:"DELETE"})}async updateItem(e,t){return this.request(`/cart/sessions/${e}/item`,{method:"POST",data:t})}async preValidate(e,t){return this.request(`/cart/sessions/${e}/payment/pre-validate`,{method:"POST",data:t})}async processPayment(e,t){return this.request(`/cart/sessions/${e}/payment/process`,{method:"POST",data:t})}async placeOrder(e,t){return this.request(`/cart/sessions/${e}/place-order`,{method:"POST",data:t})}async deleteItem(e,t){return this.updateItem(e,{itemId:t,quantity:0})}async joinTableCommitment(e,t){return this.request(`/cart/sessions/${e}/join-table`,{method:"POST",data:{tableCommitmentId:t}})}async applyCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons`,{method:"POST",data:{code:t}})}async deleteCoupon(e,t){return this.request(`/cart/sessions/${e}/coupons/${t}`,{method:"DELETE"})}};var y=class r{constructor(e,t){o(this,"events");o(this,"orders");o(this,"cart");o(this,"baseOptions");this.baseOptions=e;let{token:n,settings:s={}}=e,i=t??O({token:n,baseUrl:s.apiUrl||g,debug:s.debug});this.events=new l(i,s),this.orders=new m(i,s),this.cart=new f(i,s)}requestWithOverrides(e){let{token:t,settings:n={}}=this.baseOptions,s=(i,c={})=>O({token:e.token??t,baseUrl:e.baseUrl??n.apiUrl??g,debug:n.debug})(i,{...c,headers:{...e.headers||{},...c.headers||{}}});return new r({token:e.token??t,settings:{...n,apiUrl:e.baseUrl??n.apiUrl}},s)}};function ue(r){return new y(r)}export{y as CohostClient,ue as createCohostClient};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/endpoint.ts","../src/apiVersion.ts","../src/error/CohostError.ts","../src/settings.ts","../src/http/request.ts","../src/api/events.ts","../src/api/orders.ts","../src/api/sessions.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["import { RequestFn } from \"./http/request\";\nimport { CohostClientSettings } from \"./settings\";\n\n/**\n * Base class for all API endpoint groups within the Cohost SDK.\n * Provides shared access to the configured request function and settings.\n */\nexport class CohostEndpoint {\n /** Shared request function injected from the client */\n protected request: RequestFn;\n\n /** Client settings passed during instantiation */\n protected settings: CohostClientSettings;\n\n /**\n * Constructs a new endpoint group.\n *\n * @param request - The shared request function for performing API calls\n * @param settings - The client-wide settings passed from the parent client\n */\n constructor(request: RequestFn, settings: CohostClientSettings) {\n this.request = request;\n this.settings = settings;\n }\n}\n","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","\nexport interface CohostErrorProps {\n /**\n * Optional error code.\n * @default undefined\n */\n errorCode?: string;\n\n /**\n * Optional status code.\n * @default undefined\n */\n statusCode?: number;\n};\n\nexport class CohostError extends Error {\n errorCode: string | undefined;\n statusCode: number | undefined;\n\n /**\n * Custom error class for Cohost SDK errors.\n * @param message - The error message.\n */\n constructor(message: string, props?: CohostErrorProps) {\n // Call the parent constructor with the message\n super(message);\n\n // Set the name of the error to \"CohostError\"\n this.name = \"CohostError\";\n\n // Set the error code if provided\n this.errorCode = props?.errorCode;\n // Set the status code if provided\n this.statusCode = props?.statusCode;\n }\n\n static fromError(err: Error, props?: CohostErrorProps): CohostError {\n // Create a new CohostError instance from an existing error\n return new CohostError(err.message, {\n ...props,\n errorCode: props?.errorCode || err.name,\n });\n }\n\n}\n\n\n\n\n","/**\n * Optional settings for customizing the behavior of the CohostClient.\n */\nexport interface CohostClientSettings {\n /** Enable verbose debug output for all API requests. */\n debug?: boolean;\n\n /** Override the default API base URL (defaults to apiBaseUrl). */\n apiUrl?: string;\n}\n\n// settings.ts\nexport const defaultSettings = {\n baseUrl: 'https://api.cohost.vip',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\n// In dev or testing, you can override this in the browser or Node\nexport let runtimeOverrides: {\n baseUrl?: string;\n headers?: Record<string, string>;\n} = {};\n\nexport function setSdkOverrides(overrides: typeof runtimeOverrides) {\n runtimeOverrides = overrides;\n}\n\n","import { PaginatedRequest } from \"../../types\";\nimport { apiBaseUrl } from \"../apiVersion\";\nimport { CohostError } from \"../error/CohostError\";\nimport { defaultSettings, runtimeOverrides } from \"../settings\";\nimport { Pagination } from \"../types/pagination\";\n\n/**\n * Options for configuring the request handler.\n */\ninterface RequestProps {\n /** API token for authentication (Bearer token). */\n token: string | null;\n\n /** Base URL of the API (defaults to versioned `apiBaseUrl`). */\n baseUrl?: string;\n\n /** Enable debug logging of requests/responses. */\n debug?: boolean;\n}\n\n/**\n * Supported HTTP methods.\n */\ntype RequestMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\ntype RequestOptions = {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | string[] | undefined>;\n headers?: Record<string, string>;\n pagination?: Pagination;\n};\n\nexport const paginatedOptions = (req: PaginatedRequest<any>, options?: Partial<RequestOptions>): RequestOptions => {\n const { pagination, ...rest } = req;\n return {\n query: rest,\n pagination,\n ...options,\n };\n};\n\n/**\n * Builds a query string from a flat object, supporting array values via repeated keys.\n */\nconst buildQueryString = (\n input?: Record<string, string | number | boolean | string[] | undefined>\n): string => {\n if (!input) return \"\";\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n value.forEach((v) => params.append(key, String(v)));\n } else {\n params.set(key, String(value));\n }\n }\n return params.toString() ? `?${params.toString()}` : \"\";\n};\n\n/**\n * A function that performs a request to the Cohost API.\n * The generic <T> allows you to specify the expected response type.\n */\ntype RequestFn = <T = any>(\n path: string,\n options?: RequestOptions\n) => Promise<T>;\n\n/**\n * Creates a request function configured with authentication and client defaults.\n * The returned function supports generic return typing via <T>.\n */\nconst request = ({ token, baseUrl = apiBaseUrl, debug = false }: RequestProps): RequestFn => {\n return async function <T = any>(\n path: string,\n options: RequestOptions = {}\n ): Promise<T> {\n const { method = \"GET\", data, query, pagination, headers = {} } = options;\n\n const _query = {\n ...query,\n ...pagination,\n };\n\n const queryString = buildQueryString(_query);\n const finalBaseUrl = runtimeOverrides.baseUrl ?? baseUrl;\n const url = `${finalBaseUrl}${path}${queryString}`;\n\n const reqHeaders: Record<string, string> = {\n ...defaultSettings.headers,\n ...runtimeOverrides.headers,\n ...headers,\n };\n\n if (token) {\n reqHeaders[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const body = data && method !== \"GET\" ? JSON.stringify(data) : undefined;\n\n if (debug) {\n console.log(`[Cohost SDK] Request: ${method} ${url}`);\n if (body) console.log(`[Cohost SDK] Body:`, body);\n console.log(`[Cohost SDK] Headers:`, reqHeaders);\n }\n\n const res = await fetch(url, {\n method,\n headers: reqHeaders,\n body,\n });\n\n const isJson = res.headers.get(\"content-type\")?.includes(\"application/json\");\n const responseBody = isJson ? await res.json() : await res.text();\n\n if (!res.ok) {\n const message = typeof responseBody === \"string\" ? responseBody : JSON.stringify(responseBody);\n console.error(`[Cohost SDK] Error: ${message}`, { url });\n throw new CohostError(message || res.statusText, {\n errorCode: res.statusText || \"API_ERROR\",\n statusCode: res.status,\n });\n }\n\n if (\n typeof responseBody === \"object\" &&\n responseBody !== null &&\n (responseBody as any).status === \"ok\" &&\n \"data\" in responseBody\n ) {\n return (responseBody as { data: T }).data;\n }\n\n return responseBody as T;\n };\n};\n\nexport { type RequestProps, type RequestFn };\nexport { request };\n","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\nimport { Attendee3, EventProfile, PaginatedRequest, PaginatedResponse, Ticket } from '../../types/index';\nimport { paginatedOptions } from '../http/request';\n\n/**\n * Provides methods to interact with the Cohost Events API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const list = await client.events.list();\n * const event = await client.events.fetch('event-id');\n * const tickets = await client.events.tickets('event-id');\n * ```\n */\nexport class EventsAPI extends CohostEndpoint {\n\n /**\n * Fetch a list of all events.\n * \n * @returns A Promise resolving to an array of event objects\n * @throws Will throw an error if the request fails\n * \n * @todo Implement pagination and filtering options\n */\n async list() {\n return this.request<EventProfile[]>('/events');\n }\n\n\n /**\n * Fetch a single event by ID.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to the event object\n * @throws Will throw an error if the request fails or the event is not found\n */\n async fetch(id: string) {\n return this.request<EventProfile>(`/events/${id}`);\n }\n\n\n\n /**\n * List all tickets associated with a specific event.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to an array of ticket objects\n * @throws Will throw an error if the request fails or the event does not exist\n */\n async tickets(id: string) {\n return this.request<Ticket[]>(`/events/${id}/tickets`);\n }\n\n /**\n * List attendees in the event.\n *\n * Requires: valid authentication token. This endpoint is not public.\n * \n * @param id - The ID of the event.\n * @returns List of tickets (attendees) for the event.\n */\n async attendees(id: string, filters?: PaginatedRequest<any>) {\n return this.request<PaginatedResponse<Attendee3>>(`/events/${id}/attendees`, paginatedOptions(filters));\n }\n\n \n\n}\n","import { CohostEndpoint } from '../endpoint';\n\n/**\n * Provides methods to interact with the Cohost Orders API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const order = await client.orders.fetch('order-id', 'user-id');\n * const list = await client.orders.list({ status: 'completed' });\n * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\n\n /**\n * Fetch a single order by ID.\n * \n * @param id - The unique identifier of the order\n * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)\n * @returns A Promise resolving to the order object\n * @throws Will throw an error if the request fails or the order is not found\n */\n async fetch(id: string, uid: string) {\n // uid is reserved for future scoped access/auth features\n return this.request(`/orders/${id}?uid=${uid}`);\n }\n\n /**\n * List orders with optional filters.\n * \n * @param filters - Optional filters to apply when retrieving orders\n * @returns A Promise resolving to an array of order summaries\n * @throws Will throw an error if the request fails\n */\n async list(filters?: {\n status?: string;\n startDate?: string;\n endDate?: string;\n page?: number;\n pageSize?: number;\n }) {\n const query = new URLSearchParams(filters as Record<string, string>).toString();\n return this.request(`/orders${query ? `?${query}` : ''}`);\n }\n}\n","import { CartSession, UpdatableCartSession } from '../../types';\nimport { CohostEndpoint } from '../endpoint';\nimport { FindTablesProps, StartCartSessionInput, ViableTableOption } from '../types/sessions';\n\n/**\n * Provides methods to interact with cart sessions in the Cohost API.\n *\n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const session = await client.sessions.start({ contextId: 'evt_abc123' });\n * ```\n */\nexport class SessionsAPI extends CohostEndpoint {\n\n /**\n * Start a new cart session.\n *\n * @param input - Data to start the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the request fails\n */\n async start(input: StartCartSessionInput) {\n return this.request<CartSession>('/cart/sessions', {\n method: 'POST',\n data: input,\n });\n }\n\n /**\n * Get a cart session by its ID.\n *\n * @param id - The unique session ID\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the session is not found or request fails\n */\n async get(id: string) {\n return this.request<CartSession>(`/cart/sessions/${id}`);\n }\n\n /**\n * Update a cart session.\n *\n * @param id - The ID of the session to update\n * @param input - Data to update the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async update(id: string, input: Partial<UpdatableCartSession>) {\n return this.request<CartSession>(`/cart/sessions/${id}`, {\n method: 'PATCH',\n data: input,\n });\n }\n\n /**\n * Cancel (soft delete) a cart session.\n *\n * @param id - The ID of the session to cancel\n * @returns Nothing if successful\n * \n * @throws Will throw an error if the cancel operation fails\n */\n async cancel(id: string) {\n return this.request<void>(`/cart/sessions/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Update an item in the cart session.\n *\n * @param sessionId - The ID of the session\n * @param props - Properties to update\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async updateItem(sessionId: string, props: {\n itemId: string;\n quantity: number;\n options?: {\n [key: string]: any;\n };\n }) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/item`, {\n method: 'POST',\n data: props,\n });\n }\n\n /**\n * Pre-validate the cart session for payment and checkout.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for validation\n * @returns {CartSession} The validated cart session\n * \n * @throws Will throw an error if validation fails\n */\n async preValidate(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/pre-validate`, {\n method: 'POST',\n data: data,\n });\n }\n\n\n\n /**\n * Prepare the cart session for payment.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for payment preparation\n * @returns {CartSession} The prepared cart session\n * \n * @throws Will throw an error if preparation fails\n */\n async processPayment(sessionId: string, data: unknown) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/process`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Close the cart session, and place the order.\n * \n * @param sessionId - The ID of the session\n * @param data - Data to place the order\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the order placement fails\n */\n async placeOrder(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/place-order`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Remove an item from the cart session.\n * The same as setting the quantity to 0.\n * \n * @param sessionId - The ID of the cart session\n * @param itemId - The ID of the item to remove\n * @returns {CartSession} The latest cart session\n */\n async deleteItem(sessionId: string, itemId: string) {\n return this.updateItem(sessionId, {\n itemId,\n quantity: 0,\n });\n }\n\n\n\n\n\n /**\n * Join a table commitment within an active cart session.\n *\n * @param id - The ID of the cart session\n * @param tableCommitmentId - The table commitment ID to join\n * @returns {CartSession} Updated cart session with joined table\n * \n * @throws Will throw an error if the join operation fails\n */\n async joinTableCommitment(id: string, tableCommitmentId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/join-table`, {\n method: 'POST',\n data: {\n tableCommitmentId,\n }\n });\n }\n\n\n /**\n * Apply a coupon code to the cart session.\n *\n * @param id - The ID of the cart session\n * @param code - The coupon code to apply\n * @returns {CartSession} Updated cart session with applied coupon\n * \n * @throws Will throw an error if the coupon application fails\n */\n async applyCoupon(id: string, code: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons`, {\n method: 'POST',\n data: {\n code\n }\n });\n }\n\n /**\n * Find viable table options for a cart session.\n *\n * @param id - The ID of the cart session\n * @param props - Properties to find viable tables\n * @returns {ViableTableOption[]} List of viable table options\n * \n * @throws Will throw an error if the request fails\n */\n async deleteCoupon(id: string, couponId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons/${couponId}`, {\n method: 'DELETE'\n });\n }\n}\n","import { EventsAPI } from './api/events';\nimport { OrdersAPI } from './api/orders';\nimport { SessionsAPI } from './api/sessions';\nimport { apiBaseUrl } from './apiVersion';\nimport { request, RequestFn } from './http/request';\nimport { CohostClientSettings } from './settings';\n\n/**\n * Configuration options for instantiating a CohostClient.\n */\nexport interface CohostClientOptions {\n /** API token used for authenticated requests. */\n token: string;\n\n /** Optional client settings such as debug mode or custom API URL. */\n settings?: CohostClientSettings;\n}\n\n/**\n * CohostClient provides grouped access to various API modules such as Events and Orders.\n */\nexport class CohostClient {\n public readonly events: EventsAPI;\n public readonly orders: OrdersAPI;\n public readonly cart: SessionsAPI;\n\n private readonly baseOptions: CohostClientOptions;\n\n constructor(options: CohostClientOptions, customRequestFn?: RequestFn) {\n this.baseOptions = options;\n\n const { token, settings = {} } = options;\n\n const sharedRequest = customRequestFn ?? request({\n token,\n baseUrl: settings.apiUrl || apiBaseUrl,\n debug: settings.debug,\n });\n\n this.events = new EventsAPI(sharedRequest, settings);\n this.orders = new OrdersAPI(sharedRequest, settings);\n this.cart = new SessionsAPI(sharedRequest, settings);\n }\n\n /**\n * Returns a new CohostClient instance with overridden request behavior\n */\n public requestWithOverrides(overrides: {\n token?: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n }): CohostClient {\n const { token, settings = {} } = this.baseOptions;\n\n const overriddenRequest: RequestFn = (path, options = {}) =>\n request({\n token: overrides.token ?? token,\n baseUrl: overrides.baseUrl ?? settings.apiUrl ?? apiBaseUrl,\n debug: settings.debug,\n })(path, {\n ...options,\n headers: {\n ...(overrides.headers || {}),\n ...(options.headers || {}),\n },\n });\n\n return new CohostClient(\n {\n token: overrides.token ?? token,\n settings: {\n ...settings,\n apiUrl: overrides.baseUrl ?? settings.apiUrl,\n },\n },\n overriddenRequest\n );\n }\n}\n","import { CohostClient, CohostClientOptions } from './client';\nexport { type CohostClientSettings } from './settings';\n\n/**\n * Factory method for creating a CohostClient instance.\n * \n * Example:\n * ```ts\n * const client = createCohostClient({ token: 'your-token' });\n * ```\n */\nexport function createCohostClient(options: CohostClientOptions): CohostClient {\n return new CohostClient(options);\n}\n\n\nexport { CohostClient }\n\nexport * from '../types';"],"mappings":"oKAOO,IAAMA,EAAN,KAAqB,CAa1B,YAAYC,EAAoBC,EAAgC,CAXhEC,EAAA,KAAU,WAGVA,EAAA,KAAU,YASR,KAAK,QAAUF,EACf,KAAK,SAAWC,CAClB,CACF,ECtBO,IAAME,EAAa,4BCanB,IAAMC,EAAN,MAAMC,UAAoB,KAAM,CAQnC,YAAYC,EAAiBC,EAA0B,CAEnD,MAAMD,CAAO,EATjBE,EAAA,kBACAA,EAAA,mBAWI,KAAK,KAAO,cAGZ,KAAK,UAAYD,GAAO,UAExB,KAAK,WAAaA,GAAO,UAC7B,CAEA,OAAO,UAAUE,EAAYF,EAAuC,CAEhE,OAAO,IAAIF,EAAYI,EAAI,QAAS,CAChC,GAAGF,EACH,UAAWA,GAAO,WAAaE,EAAI,IACvC,CAAC,CACL,CAEJ,EChCO,IAAMC,EAAkB,CAC3B,QAAS,yBACT,QAAS,CACL,eAAgB,kBACpB,CACJ,EAGWC,EAGP,CAAC,ECUE,IAAMC,EAAmB,CAACC,EAA4BC,IAAsD,CACjH,GAAM,CAAE,WAAAC,EAAY,GAAGC,CAAK,EAAIH,EAChC,MAAO,CACL,MAAOG,EACP,WAAAD,EACA,GAAGD,CACL,CACF,EAKMG,EACJC,GACW,CACX,GAAI,CAACA,EAAO,MAAO,GAEnB,IAAMC,EAAS,IAAI,gBACnB,OAAW,CAACC,EAAKC,CAAK,IAAK,OAAO,QAAQH,CAAK,EACzCG,IAAU,SACV,MAAM,QAAQA,CAAK,EACrBA,EAAM,QAASC,GAAMH,EAAO,OAAOC,EAAK,OAAOE,CAAC,CAAC,CAAC,EAElDH,EAAO,IAAIC,EAAK,OAAOC,CAAK,CAAC,GAGjC,OAAOF,EAAO,SAAS,EAAI,IAAIA,EAAO,SAAS,CAAC,GAAK,EACvD,EAeMI,EAAU,CAAC,CAAE,MAAAC,EAAO,QAAAC,EAAUC,EAAY,MAAA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AAK,OAAS,IAAIK,EAAUJ,EAAeD,CAAQ,EACnD,KAAK,KAAO,IAAIM,EAAYL,EAAeD,CAAQ,CACrD,CAKO,qBAAqBO,EAIX,CACf,GAAM,CAAE,MAAAR,EAAO,SAAAC,EAAW,CAAC,CAAE,EAAI,KAAK,YAEhCQ,EAA+B,CAACC,EAAMb,EAAU,CAAC,IACrDM,EAAQ,CACN,MAAOK,EAAU,OAASR,EAC1B,QAASQ,EAAU,SAAWP,EAAS,QAAUG,EACjD,MAAOH,EAAS,KAClB,CAAC,EAAES,EAAM,CACP,GAAGb,EACH,QAAS,CACP,GAAIW,EAAU,SAAW,CAAC,EAC1B,GAAIX,EAAQ,SAAW,CAAC,CAC1B,CACF,CAAC,EAEH,OAAO,IAAID,EACT,CACE,MAAOY,EAAU,OAASR,EAC1B,SAAU,CACR,GAAGC,EACH,OAAQO,EAAU,SAAWP,EAAS,MACxC,CACF,EACAQ,CACF,CACF,CACF,ECnEO,SAASE,GAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["CohostEndpoint","request","settings","__publicField","apiBaseUrl","CohostError","_CohostError","message","props","__publicField","err","defaultSettings","runtimeOverrides","paginatedOptions","req","options","pagination","rest","buildQueryString","input","params","key","value","v","request","token","baseUrl","apiBaseUrl","debug","path","method","data","query","headers","_query","queryString","url","runtimeOverrides","reqHeaders","defaultSettings","body","res","responseBody","message","CohostError","EventsAPI","CohostEndpoint","id","filters","paginatedOptions","OrdersAPI","CohostEndpoint","id","uid","filters","query","SessionsAPI","CohostEndpoint","input","id","sessionId","props","data","itemId","tableCommitmentId","code","couponId","CohostClient","_CohostClient","options","customRequestFn","__publicField","token","settings","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","SessionsAPI","overrides","overriddenRequest","path","createCohostClient","options","CohostClient"]}
1
+ {"version":3,"sources":["../src/endpoint.ts","../src/apiVersion.ts","../src/error/CohostError.ts","../src/settings.ts","../src/http/request.ts","../src/api/events.ts","../src/api/orders.ts","../src/api/sessions.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["import { RequestFn } from \"./http/request\";\nimport { CohostClientSettings } from \"./settings\";\n\n/**\n * Base class for all API endpoint groups within the Cohost SDK.\n * Provides shared access to the configured request function and settings.\n */\nexport class CohostEndpoint {\n /** Shared request function injected from the client */\n protected request: RequestFn;\n\n /** Client settings passed during instantiation */\n protected settings: CohostClientSettings;\n\n /**\n * Constructs a new endpoint group.\n *\n * @param request - The shared request function for performing API calls\n * @param settings - The client-wide settings passed from the parent client\n */\n constructor(request: RequestFn, settings: CohostClientSettings) {\n this.request = request;\n this.settings = settings;\n }\n}\n","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","\nexport interface CohostErrorProps {\n /**\n * Optional error code.\n * @default undefined\n */\n errorCode?: string;\n\n /**\n * Optional status code.\n * @default undefined\n */\n statusCode?: number;\n};\n\nexport class CohostError extends Error {\n errorCode: string | undefined;\n statusCode: number | undefined;\n\n /**\n * Custom error class for Cohost SDK errors.\n * @param message - The error message.\n */\n constructor(message: string, props?: CohostErrorProps) {\n // Call the parent constructor with the message\n super(message);\n\n // Set the name of the error to \"CohostError\"\n this.name = \"CohostError\";\n\n // Set the error code if provided\n this.errorCode = props?.errorCode;\n // Set the status code if provided\n this.statusCode = props?.statusCode;\n }\n\n static fromError(err: Error, props?: CohostErrorProps): CohostError {\n // Create a new CohostError instance from an existing error\n return new CohostError(err.message, {\n ...props,\n errorCode: props?.errorCode || err.name,\n });\n }\n\n}\n\n\n\n\n","/**\n * Optional settings for customizing the behavior of the CohostClient.\n */\nexport interface CohostClientSettings {\n /** Enable verbose debug output for all API requests. */\n debug?: boolean;\n\n /** Override the default API base URL (defaults to apiBaseUrl). */\n apiUrl?: string;\n}\n\n// settings.ts\nexport const defaultSettings = {\n baseUrl: 'https://api.cohost.vip',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\n// In dev or testing, you can override this in the browser or Node\nexport let runtimeOverrides: {\n baseUrl?: string;\n headers?: Record<string, string>;\n} = {};\n\nexport function setSdkOverrides(overrides: typeof runtimeOverrides) {\n runtimeOverrides = overrides;\n}\n\n","import { PaginatedRequest } from \"../../types\";\nimport { apiBaseUrl } from \"../apiVersion\";\nimport { CohostError } from \"../error/CohostError\";\nimport { defaultSettings, runtimeOverrides } from \"../settings\";\nimport { Pagination } from \"../types/pagination\";\n\n/**\n * Options for configuring the request handler.\n */\ninterface RequestProps {\n /** API token for authentication (Bearer token). */\n token: string | null;\n\n /** Base URL of the API (defaults to versioned `apiBaseUrl`). */\n baseUrl?: string;\n\n /** Enable debug logging of requests/responses. */\n debug?: boolean;\n}\n\n/**\n * Supported HTTP methods.\n */\ntype RequestMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\ntype RequestOptions = {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | string[] | undefined>;\n headers?: Record<string, string>;\n pagination?: Pagination;\n};\n\nexport const paginatedOptions = (req: PaginatedRequest<any>, options?: Partial<RequestOptions>): RequestOptions => {\n const { pagination, ...rest } = req;\n return {\n query: rest,\n pagination,\n ...options,\n };\n};\n\n/**\n * Builds a query string from a flat object, supporting array values via repeated keys.\n */\nconst buildQueryString = (\n input?: Record<string, string | number | boolean | string[] | undefined>\n): string => {\n if (!input) return \"\";\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n value.forEach((v) => params.append(key, String(v)));\n } else {\n params.set(key, String(value));\n }\n }\n return params.toString() ? `?${params.toString()}` : \"\";\n};\n\n/**\n * A function that performs a request to the Cohost API.\n * The generic <T> allows you to specify the expected response type.\n */\ntype RequestFn = <T = any>(\n path: string,\n options?: RequestOptions\n) => Promise<T>;\n\n/**\n * Creates a request function configured with authentication and client defaults.\n * The returned function supports generic return typing via <T>.\n */\nconst request = ({ token, baseUrl = apiBaseUrl, debug = false }: RequestProps): RequestFn => {\n return async function <T = any>(\n path: string,\n options: RequestOptions = {}\n ): Promise<T> {\n const { method = \"GET\", data, query, pagination, headers = {} } = options;\n\n const _query = {\n ...query,\n ...pagination,\n };\n\n const queryString = buildQueryString(_query);\n const finalBaseUrl = runtimeOverrides.baseUrl ?? baseUrl;\n const url = `${finalBaseUrl}${path}${queryString}`;\n\n const reqHeaders: Record<string, string> = {\n ...defaultSettings.headers,\n ...runtimeOverrides.headers,\n ...headers,\n };\n\n if (token) {\n reqHeaders[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const body = data && method !== \"GET\" ? JSON.stringify(data) : undefined;\n\n if (debug) {\n console.log(`[Cohost SDK] Request: ${method} ${url}`);\n if (body) console.log(`[Cohost SDK] Body:`, body);\n console.log(`[Cohost SDK] Headers:`, reqHeaders);\n }\n\n const res = await fetch(url, {\n method,\n headers: reqHeaders,\n body,\n });\n\n const isJson = res.headers.get(\"content-type\")?.includes(\"application/json\");\n const responseBody = isJson ? await res.json() : await res.text();\n\n if (!res.ok) {\n const message = typeof responseBody === \"string\" ? responseBody : JSON.stringify(responseBody);\n console.error(`[Cohost SDK] Error: ${message}`, { url });\n throw new CohostError(message || res.statusText, {\n errorCode: res.statusText || \"API_ERROR\",\n statusCode: res.status,\n });\n }\n\n if (\n typeof responseBody === \"object\" &&\n responseBody !== null &&\n (responseBody as any).status === \"ok\" &&\n \"data\" in responseBody\n ) {\n return (responseBody as { data: T }).data;\n }\n\n return responseBody as T;\n };\n};\n\nexport { type RequestProps, type RequestFn };\nexport { request };\n","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\nimport { Attendee, EventProfile, PaginatedRequest, PaginatedResponse, Ticket } from '../../types/index';\nimport { paginatedOptions } from '../http/request';\n\n/**\n * Provides methods to interact with the Cohost Events API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const list = await client.events.list();\n * const event = await client.events.fetch('event-id');\n * const tickets = await client.events.tickets('event-id');\n * ```\n */\nexport class EventsAPI extends CohostEndpoint {\n\n /**\n * Fetch a list of all events.\n * \n * @returns A Promise resolving to an array of event objects\n * @throws Will throw an error if the request fails\n * \n * @todo Implement pagination and filtering options\n */\n async list() {\n return this.request<EventProfile[]>('/events');\n }\n\n\n /**\n * Fetch a single event by ID.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to the event object\n * @throws Will throw an error if the request fails or the event is not found\n */\n async fetch(id: string) {\n return this.request<EventProfile>(`/events/${id}`);\n }\n\n\n\n /**\n * List all tickets associated with a specific event.\n * \n * @param id - The unique identifier of the event\n * @returns A Promise resolving to an array of ticket objects\n * @throws Will throw an error if the request fails or the event does not exist\n */\n async tickets(id: string) {\n return this.request<Ticket[]>(`/events/${id}/tickets`);\n }\n\n /**\n * List attendees in the event.\n *\n * Requires: valid authentication token. This endpoint is not public.\n * \n * @param id - The ID of the event.\n * @returns List of tickets (attendees) for the event.\n */\n async attendees(id: string, filters?: PaginatedRequest<any>) {\n return this.request<PaginatedResponse<Attendee>>(`/events/${id}/attendees`, paginatedOptions(filters));\n }\n\n \n\n}\n","import { CohostEndpoint } from '../endpoint';\n\n/**\n * Provides methods to interact with the Cohost Orders API.\n * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const order = await client.orders.fetch('order-id', 'user-id');\n * const list = await client.orders.list({ status: 'completed' });\n * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\n\n /**\n * Fetch a single order by ID.\n * \n * @param id - The unique identifier of the order\n * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)\n * @returns A Promise resolving to the order object\n * @throws Will throw an error if the request fails or the order is not found\n */\n async fetch(id: string, uid: string) {\n // uid is reserved for future scoped access/auth features\n return this.request(`/orders/${id}?uid=${uid}`);\n }\n\n /**\n * Fetch a single order by ID.\n * \n * @param id - The unique identifier of the order\n * @param uid - The unique user ID associated with the order (currently unused but reserved for future auth context)\n * @returns A Promise resolving to the order object\n * @throws Will throw an error if the request fails or the order is not found\n */\n async attendees(id: string, uid: string) {\n // uid is reserved for future scoped access/auth features\n return this.request(`/orders/${id}/attendees?uid=${uid}`);\n }\n\n /**\n * List orders with optional filters.\n * \n * @param filters - Optional filters to apply when retrieving orders\n * @returns A Promise resolving to an array of order summaries\n * @throws Will throw an error if the request fails\n */\n async list(filters?: {\n status?: string;\n startDate?: string;\n endDate?: string;\n page?: number;\n pageSize?: number;\n }) {\n const query = new URLSearchParams(filters as Record<string, string>).toString();\n return this.request(`/orders${query ? `?${query}` : ''}`);\n }\n}\n","import { CartSession, StartCartSessionInput, UpdatableCartSession } from '../../types';\nimport { CohostEndpoint } from '../endpoint';\n\n/**\n * Provides methods to interact with cart sessions in the Cohost API.\n *\n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const session = await client.sessions.start({ contextId: 'evt_abc123' });\n * ```\n */\nexport class SessionsAPI extends CohostEndpoint {\n\n /**\n * Start a new cart session.\n *\n * @param input - Data to start the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the request fails\n */\n async start(input: StartCartSessionInput) {\n return this.request<CartSession>('/cart/sessions', {\n method: 'POST',\n data: input,\n });\n }\n\n /**\n * Get a cart session by its ID.\n *\n * @param id - The unique session ID\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the session is not found or request fails\n */\n async get(id: string) {\n return this.request<CartSession>(`/cart/sessions/${id}`);\n }\n\n /**\n * Update a cart session.\n *\n * @param id - The ID of the session to update\n * @param input - Data to update the session\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async update(id: string, input: Partial<UpdatableCartSession>) {\n return this.request<CartSession>(`/cart/sessions/${id}`, {\n method: 'PATCH',\n data: input,\n });\n }\n\n /**\n * Cancel (soft delete) a cart session.\n *\n * @param id - The ID of the session to cancel\n * @returns Nothing if successful\n * \n * @throws Will throw an error if the cancel operation fails\n */\n async cancel(id: string) {\n return this.request<void>(`/cart/sessions/${id}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * Update an item in the cart session.\n *\n * @param sessionId - The ID of the session\n * @param props - Properties to update\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the update fails\n */\n async updateItem(sessionId: string, props: {\n itemId: string;\n quantity: number;\n options?: {\n [key: string]: any;\n };\n }) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/item`, {\n method: 'POST',\n data: props,\n });\n }\n\n /**\n * Pre-validate the cart session for payment and checkout.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for validation\n * @returns {CartSession} The validated cart session\n * \n * @throws Will throw an error if validation fails\n */\n async preValidate(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/pre-validate`, {\n method: 'POST',\n data: data,\n });\n }\n\n\n\n /**\n * Prepare the cart session for payment.\n *\n * @param sessionId - The ID of the cart session\n * @param data - Data required for payment preparation\n * @returns {CartSession} The prepared cart session\n * \n * @throws Will throw an error if preparation fails\n */\n async processPayment(sessionId: string, data: unknown) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/payment/process`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Close the cart session, and place the order.\n * \n * @param sessionId - The ID of the session\n * @param data - Data to place the order\n * @returns {CartSession} The latest cart session\n * \n * @throws Will throw an error if the order placement fails\n */\n async placeOrder(sessionId: string, data: any) {\n return this.request<CartSession>(`/cart/sessions/${sessionId}/place-order`, {\n method: 'POST',\n data: data,\n });\n }\n\n /**\n * Remove an item from the cart session.\n * The same as setting the quantity to 0.\n * \n * @param sessionId - The ID of the cart session\n * @param itemId - The ID of the item to remove\n * @returns {CartSession} The latest cart session\n */\n async deleteItem(sessionId: string, itemId: string) {\n return this.updateItem(sessionId, {\n itemId,\n quantity: 0,\n });\n }\n\n\n\n\n\n /**\n * Join a table commitment within an active cart session.\n *\n * @param id - The ID of the cart session\n * @param tableCommitmentId - The table commitment ID to join\n * @returns {CartSession} Updated cart session with joined table\n * \n * @throws Will throw an error if the join operation fails\n */\n async joinTableCommitment(id: string, tableCommitmentId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/join-table`, {\n method: 'POST',\n data: {\n tableCommitmentId,\n }\n });\n }\n\n\n /**\n * Apply a coupon code to the cart session.\n *\n * @param id - The ID of the cart session\n * @param code - The coupon code to apply\n * @returns {CartSession} Updated cart session with applied coupon\n * \n * @throws Will throw an error if the coupon application fails\n */\n async applyCoupon(id: string, code: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons`, {\n method: 'POST',\n data: {\n code\n }\n });\n }\n\n /**\n * Find viable table options for a cart session.\n *\n * @param id - The ID of the cart session\n * @param props - Properties to find viable tables\n * @returns {ViableTableOption[]} List of viable table options\n * \n * @throws Will throw an error if the request fails\n */\n async deleteCoupon(id: string, couponId: string): Promise<CartSession> {\n return this.request<CartSession>(`/cart/sessions/${id}/coupons/${couponId}`, {\n method: 'DELETE'\n });\n }\n}\n","import { EventsAPI } from './api/events';\nimport { OrdersAPI } from './api/orders';\nimport { SessionsAPI } from './api/sessions';\nimport { apiBaseUrl } from './apiVersion';\nimport { request, RequestFn } from './http/request';\nimport { CohostClientSettings } from './settings';\n\n/**\n * Configuration options for instantiating a CohostClient.\n */\nexport interface CohostClientOptions {\n /** API token used for authenticated requests. */\n token: string;\n\n /** Optional client settings such as debug mode or custom API URL. */\n settings?: CohostClientSettings;\n}\n\n/**\n * CohostClient provides grouped access to various API modules such as Events and Orders.\n */\nexport class CohostClient {\n public readonly events: EventsAPI;\n public readonly orders: OrdersAPI;\n public readonly cart: SessionsAPI;\n\n private readonly baseOptions: CohostClientOptions;\n\n constructor(options: CohostClientOptions, customRequestFn?: RequestFn) {\n this.baseOptions = options;\n\n const { token, settings = {} } = options;\n\n const sharedRequest = customRequestFn ?? request({\n token,\n baseUrl: settings.apiUrl || apiBaseUrl,\n debug: settings.debug,\n });\n\n this.events = new EventsAPI(sharedRequest, settings);\n this.orders = new OrdersAPI(sharedRequest, settings);\n this.cart = new SessionsAPI(sharedRequest, settings);\n }\n\n /**\n * Returns a new CohostClient instance with overridden request behavior\n */\n public requestWithOverrides(overrides: {\n token?: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n }): CohostClient {\n const { token, settings = {} } = this.baseOptions;\n\n const overriddenRequest: RequestFn = (path, options = {}) =>\n request({\n token: overrides.token ?? token,\n baseUrl: overrides.baseUrl ?? settings.apiUrl ?? apiBaseUrl,\n debug: settings.debug,\n })(path, {\n ...options,\n headers: {\n ...(overrides.headers || {}),\n ...(options.headers || {}),\n },\n });\n\n return new CohostClient(\n {\n token: overrides.token ?? token,\n settings: {\n ...settings,\n apiUrl: overrides.baseUrl ?? settings.apiUrl,\n },\n },\n overriddenRequest\n );\n }\n}\n","import { CohostClient, CohostClientOptions } from './client';\nexport { type CohostClientSettings } from './settings';\n\n/**\n * Factory method for creating a CohostClient instance.\n * \n * Example:\n * ```ts\n * const client = createCohostClient({ token: 'your-token' });\n * ```\n */\nexport function createCohostClient(options: CohostClientOptions): CohostClient {\n return new CohostClient(options);\n}\n\n\nexport { CohostClient }\n\nexport * from '../types';"],"mappings":"oKAOO,IAAMA,EAAN,KAAqB,CAa1B,YAAYC,EAAoBC,EAAgC,CAXhEC,EAAA,KAAU,WAGVA,EAAA,KAAU,YASR,KAAK,QAAUF,EACf,KAAK,SAAWC,CAClB,CACF,ECtBO,IAAME,EAAa,4BCanB,IAAMC,EAAN,MAAMC,UAAoB,KAAM,CAQnC,YAAYC,EAAiBC,EAA0B,CAEnD,MAAMD,CAAO,EATjBE,EAAA,kBACAA,EAAA,mBAWI,KAAK,KAAO,cAGZ,KAAK,UAAYD,GAAO,UAExB,KAAK,WAAaA,GAAO,UAC7B,CAEA,OAAO,UAAUE,EAAYF,EAAuC,CAEhE,OAAO,IAAIF,EAAYI,EAAI,QAAS,CAChC,GAAGF,EACH,UAAWA,GAAO,WAAaE,EAAI,IACvC,CAAC,CACL,CAEJ,EChCO,IAAMC,EAAkB,CAC3B,QAA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1B,SAAU,CACR,GAAGC,EACH,OAAQO,EAAU,SAAWP,EAAS,MACxC,CACF,EACAQ,CACF,CACF,CACF,ECnEO,SAASE,GAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["CohostEndpoint","request","settings","__publicField","apiBaseUrl","CohostError","_CohostError","message","props","__publicField","err","defaultSettings","runtimeOverrides","paginatedOptions","req","options","pagination","rest","buildQueryString","input","params","key","value","v","request","token","baseUrl","apiBaseUrl","debug","path","method","data","query","headers","_query","queryString","url","runtimeOverrides","reqHeaders","defaultSettings","body","res","responseBody","message","CohostError","EventsAPI","CohostEndpoint","id","filters","paginatedOptions","OrdersAPI","CohostEndpoint","id","uid","filters","query","SessionsAPI","CohostEndpoint","input","id","sessionId","props","data","itemId","tableCommitmentId","code","couponId","CohostClient","_CohostClient","options","customRequestFn","__publicField","token","settings","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","SessionsAPI","overrides","overriddenRequest","path","createCohostClient","options","CohostClient"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cohostvip/cohost-node",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Cohost API wrapper",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",