@cohostvip/cohost-node 0.0.2 → 0.0.4
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 +889 -21
- package/dist/index.d.ts +889 -21
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var g=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var w=(e,t,s)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var F=(e,t)=>{for(var s in t)g(e,s,{get:t[s],enumerable:!0})},B=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of $(t))!v.call(e,r)&&r!==s&&g(e,r,{get:()=>t[r],enumerable:!(n=k(t,r))||n.enumerable});return e};var D=e=>B(g({},"__esModule",{value:!0}),e);var a=(e,t,s)=>w(e,typeof t!="symbol"?t+"":t,s);var j={};F(j,{CohostClient:()=>l,createCohostClient:()=>A});module.exports=D(j);var u=class{constructor(t,s){a(this,"request");a(this,"settings");this.request=t,this.settings=s}};var m=class extends u{async list(){return this.request("/events")}async fetch(t){return this.request(`/events/${t}`)}async tickets(t){return this.request(`/events/${t}/tickets`)}};var f=class extends u{async fetch(t,s){return this.request(`/orders/${t}`)}};var C=class extends u{async start(t){return this.request("/cart/sessions",{method:"POST",data:t})}async get(t){return this.request(`/cart/sessions/${t}`)}async update(t,s){return this.request(`/cart/sessions/${t}`,{method:"PATCH",data:s})}async cancel(t){return this.request(`/cart/sessions/${t}`,{method:"DELETE"})}};var p="https://api.cohost.com/v1";var T={baseUrl:"https://api.cohost.vip",headers:{"Content-Type":"application/json"}},b={};var S=({token:e,baseUrl:t=p,debug:s=!1})=>async function(n,r={}){let{method:o="GET",data:c,query:R,headers:O={}}=r,P=R?"?"+new URLSearchParams(Object.entries(R).reduce((h,[E,x])=>(x!==void 0&&(h[E]=String(x)),h),{})).toString():"",U=`${b.baseUrl??t}${n}${P}`,q={...T.headers,...b.headers,...O};e&&(q.Authorization=`Bearer ${e}`);let y=c&&o!=="GET"?JSON.stringify(c):void 0;s&&(console.log(`[Cohost SDK] Request: ${o} ${U}`),y&&console.log("[Cohost SDK] Body:",y),console.log("[Cohost SDK] Headers:",q));let d=await fetch(U,{method:o,headers:q,body:y}),i=d.headers.get("content-type")?.includes("application/json")?await d.json():await d.text();if(!d.ok){let h=typeof i=="string"?i:JSON.stringify(i);throw new Error(`[Cohost SDK] ${d.status} ${d.statusText}: ${h}`)}return typeof i=="object"&&i!==null&&i.status==="ok"&&"data"in i?i.data:i};var l=class e{constructor(t,s){a(this,"events");a(this,"orders");a(this,"cart");a(this,"baseOptions");this.baseOptions=t;let{token:n,settings:r={}}=t,o=s??S({token:n,baseUrl:r.apiUrl||p,debug:r.debug});this.events=new m(o,r),this.orders=new f(o,r),this.cart=new C(o,r)}requestWithOverrides(t){let{token:s,settings:n={}}=this.baseOptions,r=(o,c={})=>S({token:t.token??s,baseUrl:t.baseUrl??n.apiUrl??p,debug:n.debug})(o,{...c,headers:{...t.headers||{},...c.headers||{}}});return new e({token:t.token??s,settings:{...n,apiUrl:t.baseUrl??n.apiUrl}},r)}};function A(e){return new l(e)}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/api/events.ts","../src/api/orders.ts","../src/apiVersion.ts","../src/http/request.ts","../src/client.ts"],"sourcesContent":["import { CohostClient, CohostClientOptions } from './client';\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 }","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","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\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 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 * 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(`/events/${id}`);\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(`/events/${id}/tickets`);\n }\n}\n","// src/api/OrdersAPI.ts\n\nimport { 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 * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\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}`);\n }\n}\n","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","import { apiBaseUrl } from \"../apiVersion\";\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\n/**\n * A function that performs a request to the Cohost API.\n */\ntype RequestFn = (\n /** Path of the request relative to baseUrl */\n path: string,\n options?: {\n /** HTTP method (defaults to 'GET') */\n method?: RequestMethod;\n\n /** Request body data (auto-serialized as JSON) */\n data?: any;\n\n /** Query parameters to be appended to the URL */\n query?: Record<string, string | number | boolean | undefined>;\n\n /** Additional headers to merge into the request */\n headers?: Record<string, string>;\n }\n) => Promise<any>;\n\n/**\n * Creates a request function configured with authentication and defaults.\n */\nconst request = ({ token, baseUrl = apiBaseUrl, debug = false }: RequestProps): RequestFn => {\n return async (path, { method = 'GET', data, query, headers = {} } = {}) => {\n const queryString = query\n ? '?' + new URLSearchParams(\n Object.entries(query).reduce((acc, [key, value]) => {\n if (value !== undefined) acc[key] = String(value);\n return acc;\n }, {} as Record<string, string>)\n ).toString()\n : '';\n\n const url = `${baseUrl}${path}${queryString}`;\n\n const reqHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\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 }\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 throw new Error(`[Cohost SDK] ${res.status} ${res.statusText}: ${message}`);\n }\n\n if (typeof responseBody === 'object' && responseBody !== null && responseBody.status === 'ok' && 'data' in responseBody) {\n return responseBody.data;\n }\n\n return responseBody;\n };\n};\n\nexport { request, RequestProps, RequestFn };\n","import { EventsAPI } from './api/events';\nimport { OrdersAPI } from './api/orders';\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 * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const event = await client.events.fetch('event-id');\n * const order = await client.orders.fetch('order-id', 'user-id');\n * ```\n */\nexport class CohostClient {\n /** Access to Event-related endpoints */\n readonly events: EventsAPI;\n\n /** Access to Order-related endpoints */\n readonly orders: OrdersAPI;\n\n constructor({ token, settings = {} }: CohostClientOptions) {\n const sharedRequest: RequestFn = 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 }\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,SA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MA,EAAI,KAAK,EAAI,MAAMA,EAAI,KAAK,EAEhE,GAAI,CAACA,EAAI,GAAI,CACT,IAAME,EAAU,OAAOD,GAAiB,SAAWA,EAAe,KAAK,UAAUA,CAAY,EAC7F,MAAM,IAAI,MAAM,gBAAgBD,EAAI,MAAM,IAAIA,EAAI,UAAU,KAAKE,CAAO,EAAE,CAC9E,CAEA,OAAI,OAAOD,GAAiB,UAAYA,IAAiB,MAAQA,EAAa,SAAW,MAAQ,SAAUA,EAChGA,EAAa,KAGjBA,CACX,EClEG,IAAME,EAAN,KAAmB,CAOxB,YAAY,CAAE,MAAAC,EAAO,SAAAC,EAAW,CAAC,CAAE,EAAwB,CAL3DC,EAAA,KAAS,UAGTA,EAAA,KAAS,UAGP,IAAMC,EAA2BC,EAAQ,CACvC,MAAAJ,EACA,QAASC,EAAS,QAAUI,EAC5B,MAAOJ,EAAS,KAClB,CAAC,EAED,KAAK,OAAS,IAAIK,EAAUH,EAAeF,CAAQ,EACnD,KAAK,OAAS,IAAIM,EAAUJ,EAAeF,CAAQ,CACrD,CACF,ENlCO,SAASO,EAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["index_exports","__export","CohostClient","createCohostClient","__toCommonJS","CohostEndpoint","request","settings","__publicField","EventsAPI","CohostEndpoint","id","OrdersAPI","CohostEndpoint","id","uid","apiBaseUrl","request","token","baseUrl","apiBaseUrl","debug","path","method","data","query","headers","queryString","acc","key","value","url","reqHeaders","body","res","responseBody","message","CohostClient","token","settings","__publicField","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","createCohostClient","options","CohostClient"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/endpoint.ts","../src/api/events.ts","../src/api/orders.ts","../src/api/sessions.ts","../src/apiVersion.ts","../src/settings.ts","../src/http/request.ts","../src/client.ts"],"sourcesContent":["import { CohostClient, CohostClientOptions } from './client';\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 }","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","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\nimport { EventProfile, Ticket } from '../../types/index';\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","// src/api/OrdersAPI.ts\n\nimport { 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 * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\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}`);\n }\n}\n","import { CohostEndpoint } from '../endpoint';\nimport {\n CartSession,\n UpdatableCartSession,\n} from '../../types/index';\nimport { StartCartSessionInput } 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 * Start a new cart session.\n *\n * @param input - Data to start the session\n * @returns The newly created cart session\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 The cart session object\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 The updated session\n * @throws Will throw an error if the update fails\n */\n async update(id: string, input: 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 * @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","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","/**\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 { apiBaseUrl } from \"../apiVersion\";\nimport { defaultSettings, runtimeOverrides } from \"../settings\";\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\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?: {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n }\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: {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n } = {}\n ): Promise<T> {\n const { method = \"GET\", data, query, headers = {} } = options;\n\n // Construct query string from `query` object\n const queryString = query\n ? \"?\" +\n new URLSearchParams(\n Object.entries(query).reduce((acc, [key, value]) => {\n if (value !== undefined) acc[key] = String(value);\n return acc;\n }, {} as Record<string, string>)\n ).toString()\n : \"\";\n\n const finalBaseUrl = runtimeOverrides.baseUrl ?? baseUrl;\n const url = `${finalBaseUrl}${path}${queryString}`;\n\n // Merge default, runtime, and per-request headers\n const reqHeaders: Record<string, string> = {\n ...defaultSettings.headers,\n ...runtimeOverrides.headers,\n ...headers,\n };\n\n // Add Authorization header if token is present\n if (token) {\n reqHeaders[\"Authorization\"] = `Bearer ${token}`;\n }\n\n // Only send body if method allows it\n const body = data && method !== \"GET\" ? JSON.stringify(data) : undefined;\n\n // Optional debug logging\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 // Parse the response based on content type\n const isJson = res.headers.get(\"content-type\")?.includes(\"application/json\");\n const responseBody = isJson ? await res.json() : await res.text();\n\n // Handle error responses\n if (!res.ok) {\n const message = typeof responseBody === \"string\" ? responseBody : JSON.stringify(responseBody);\n throw new Error(`[Cohost SDK] ${res.status} ${res.statusText}: ${message}`);\n }\n\n // If wrapped response structure with { status: 'ok', data }, return `data`\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 // Fallback for raw/unwrapped responses\n return responseBody as T;\n };\n};\n\nexport { request, RequestProps, RequestFn };\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,ECRO,IAAME,EAAN,cAAwBC,CAAe,CAU5C,MAAM,MAAO,CACX,OAAO,KAAK,QAAwB,SAAS,CAC/C,CAUA,MAAM,MAAMC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AK,OAAS,IAAII,EAAUH,EAAeD,CAAQ,EACnD,KAAK,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,ERpEO,SAASE,EAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["index_exports","__export","CohostClient","createCohostClient","__toCommonJS","CohostEndpoint","request","settings","__publicField","EventsAPI","CohostEndpoint","id","OrdersAPI","CohostEndpoint","id","uid","SessionsAPI","CohostEndpoint","input","id","apiBaseUrl","defaultSettings","runtimeOverrides","request","token","baseUrl","apiBaseUrl","debug","path","options","method","data","query","headers","queryString","acc","key","value","url","runtimeOverrides","reqHeaders","defaultSettings","body","res","responseBody","message","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
|
|
1
|
+
var E=Object.defineProperty;var k=(e,t,s)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var a=(e,t,s)=>k(e,typeof t!="symbol"?t+"":t,s);var u=class{constructor(t,s){a(this,"request");a(this,"settings");this.request=t,this.settings=s}};var h=class extends u{async list(){return this.request("/events")}async fetch(t){return this.request(`/events/${t}`)}async tickets(t){return this.request(`/events/${t}/tickets`)}};var g=class extends u{async fetch(t,s){return this.request(`/orders/${t}`)}};var m=class extends u{async start(t){return this.request("/cart/sessions",{method:"POST",data:t})}async get(t){return this.request(`/cart/sessions/${t}`)}async update(t,s){return this.request(`/cart/sessions/${t}`,{method:"PATCH",data:s})}async cancel(t){return this.request(`/cart/sessions/${t}`,{method:"DELETE"})}};var p="https://api.cohost.com/v1";var x={baseUrl:"https://api.cohost.vip",headers:{"Content-Type":"application/json"}},y={};var b=({token:e,baseUrl:t=p,debug:s=!1})=>async function(i,r={}){let{method:n="GET",data:c,query:S,headers:T={}}=r,O=S?"?"+new URLSearchParams(Object.entries(S).reduce((l,[P,U])=>(U!==void 0&&(l[P]=String(U)),l),{})).toString():"",R=`${y.baseUrl??t}${i}${O}`,C={...x.headers,...y.headers,...T};e&&(C.Authorization=`Bearer ${e}`);let q=c&&n!=="GET"?JSON.stringify(c):void 0;s&&(console.log(`[Cohost SDK] Request: ${n} ${R}`),q&&console.log("[Cohost SDK] Body:",q),console.log("[Cohost SDK] Headers:",C));let d=await fetch(R,{method:n,headers:C,body:q}),o=d.headers.get("content-type")?.includes("application/json")?await d.json():await d.text();if(!d.ok){let l=typeof o=="string"?o:JSON.stringify(o);throw new Error(`[Cohost SDK] ${d.status} ${d.statusText}: ${l}`)}return typeof o=="object"&&o!==null&&o.status==="ok"&&"data"in o?o.data:o};var f=class e{constructor(t,s){a(this,"events");a(this,"orders");a(this,"cart");a(this,"baseOptions");this.baseOptions=t;let{token:i,settings:r={}}=t,n=s??b({token:i,baseUrl:r.apiUrl||p,debug:r.debug});this.events=new h(n,r),this.orders=new g(n,r),this.cart=new m(n,r)}requestWithOverrides(t){let{token:s,settings:i={}}=this.baseOptions,r=(n,c={})=>b({token:t.token??s,baseUrl:t.baseUrl??i.apiUrl??p,debug:i.debug})(n,{...c,headers:{...t.headers||{},...c.headers||{}}});return new e({token:t.token??s,settings:{...i,apiUrl:t.baseUrl??i.apiUrl}},r)}};function st(e){return new f(e)}export{f as CohostClient,st as createCohostClient};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/endpoint.ts","../src/api/events.ts","../src/api/orders.ts","../src/apiVersion.ts","../src/http/request.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","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\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 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 * 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(`/events/${id}`);\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(`/events/${id}/tickets`);\n }\n}\n","// src/api/OrdersAPI.ts\n\nimport { 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 * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\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}`);\n }\n}\n","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","import { apiBaseUrl } from \"../apiVersion\";\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\n/**\n * A function that performs a request to the Cohost API.\n */\ntype RequestFn = (\n /** Path of the request relative to baseUrl */\n path: string,\n options?: {\n /** HTTP method (defaults to 'GET') */\n method?: RequestMethod;\n\n /** Request body data (auto-serialized as JSON) */\n data?: any;\n\n /** Query parameters to be appended to the URL */\n query?: Record<string, string | number | boolean | undefined>;\n\n /** Additional headers to merge into the request */\n headers?: Record<string, string>;\n }\n) => Promise<any>;\n\n/**\n * Creates a request function configured with authentication and defaults.\n */\nconst request = ({ token, baseUrl = apiBaseUrl, debug = false }: RequestProps): RequestFn => {\n return async (path, { method = 'GET', data, query, headers = {} } = {}) => {\n const queryString = query\n ? '?' + new URLSearchParams(\n Object.entries(query).reduce((acc, [key, value]) => {\n if (value !== undefined) acc[key] = String(value);\n return acc;\n }, {} as Record<string, string>)\n ).toString()\n : '';\n\n const url = `${baseUrl}${path}${queryString}`;\n\n const reqHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\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 }\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 throw new Error(`[Cohost SDK] ${res.status} ${res.statusText}: ${message}`);\n }\n\n if (typeof responseBody === 'object' && responseBody !== null && responseBody.status === 'ok' && 'data' in responseBody) {\n return responseBody.data;\n }\n\n return responseBody;\n };\n};\n\nexport { request, RequestProps, RequestFn };\n","import { EventsAPI } from './api/events';\nimport { OrdersAPI } from './api/orders';\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 * \n * Usage:\n * ```ts\n * const client = new CohostClient({ token: 'your-token' });\n * const event = await client.events.fetch('event-id');\n * const order = await client.orders.fetch('order-id', 'user-id');\n * ```\n */\nexport class CohostClient {\n /** Access to Event-related endpoints */\n readonly events: EventsAPI;\n\n /** Access to Order-related endpoints */\n readonly orders: OrdersAPI;\n\n constructor({ token, settings = {} }: CohostClientOptions) {\n const sharedRequest: RequestFn = 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 }\n}\n","import { CohostClient, CohostClientOptions } from './client';\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 }"],"mappings":"oKAOO,IAAMA,EAAN,KAAqB,CAa1B,YAAYC,EAAoBC,EAAgC,CAXhEC,EAAA,KAAU,WAGVA,EAAA,KAAU,YASR,KAAK,QAAUF,EACf,KAAK,SAAWC,CAClB,CACF,ECVO,IAAME,EAAN,cAAwBC,CAAe,CAQ5C,MAAM,MAAMC,EAAY,CACtB,OAAO,KAAK,QAAQ,WAAWA,CAAE,EAAE,CACrC,CASA,MAAM,QAAQA,EAAY,CACxB,OAAO,KAAK,QAAQ,WAAWA,CAAE,UAAU,CAC7C,CACF,ECvBO,IAAMC,EAAN,cAAwBC,CAAe,CAS5C,MAAM,MAAMC,EAAYC,EAAa,CAEnC,OAAO,KAAK,QAAQ,WAAWD,CAAE,EAAE,CACrC,CACF,ECxBO,IAAME,EAAa,4BC2C1B,IAAMC,EAAU,CAAC,CAAE,MAAAC,EAAO,QAAAC,EAAUC,EAAY,MAAAC,EAAQ,EAAM,IACnD,MAAOC,EAAM,CAAE,OAAAC,EAAS,MAAO,KAAAC,EAAM,MAAAC,EAAO,QAAAC,EAAU,CAAC,CAAE,EAAI,CAAC,IAAM,CACvE,IAAMC,EAAcF,EACd,IAAM,IAAI,gBACR,OAAO,QAAQA,CAAK,EAAE,OAAO,CAACG,EAAK,CAACC,EAAKC,CAAK,KACtCA,IAAU,SAAWF,EAAIC,CAAG,EAAI,OAAOC,CAAK,GACzCF,GACR,CAAC,CAA2B,CACnC,EAAE,SAAS,EACT,GAEAG,EAAM,GAAGZ,CAAO,GAAGG,CAAI,GAAGK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iBaseUrl","request","token","baseUrl","apiBaseUrl","debug","path","method","data","query","headers","queryString","acc","key","value","url","reqHeaders","body","res","responseBody","message","CohostClient","token","settings","__publicField","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","createCohostClient","options","CohostClient"]}
|
|
1
|
+
{"version":3,"sources":["../src/endpoint.ts","../src/api/events.ts","../src/api/orders.ts","../src/api/sessions.ts","../src/apiVersion.ts","../src/settings.ts","../src/http/request.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","// src/api/EventsAPI.ts\n\nimport { CohostEndpoint } from '../endpoint';\nimport { EventProfile, Ticket } from '../../types/index';\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","// src/api/OrdersAPI.ts\n\nimport { 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 * ```\n */\nexport class OrdersAPI extends CohostEndpoint {\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}`);\n }\n}\n","import { CohostEndpoint } from '../endpoint';\nimport {\n CartSession,\n UpdatableCartSession,\n} from '../../types/index';\nimport { StartCartSessionInput } 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 * Start a new cart session.\n *\n * @param input - Data to start the session\n * @returns The newly created cart session\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 The cart session object\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 The updated session\n * @throws Will throw an error if the update fails\n */\n async update(id: string, input: 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 * @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","export const apiVersion = '0.1.0';\nexport const apiVersionDate = '2025-04-15';\nexport const apiBaseUrl = 'https://api.cohost.com/v1'","/**\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 { apiBaseUrl } from \"../apiVersion\";\nimport { defaultSettings, runtimeOverrides } from \"../settings\";\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\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?: {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n }\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: {\n method?: RequestMethod;\n data?: any;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n } = {}\n ): Promise<T> {\n const { method = \"GET\", data, query, headers = {} } = options;\n\n // Construct query string from `query` object\n const queryString = query\n ? \"?\" +\n new URLSearchParams(\n Object.entries(query).reduce((acc, [key, value]) => {\n if (value !== undefined) acc[key] = String(value);\n return acc;\n }, {} as Record<string, string>)\n ).toString()\n : \"\";\n\n const finalBaseUrl = runtimeOverrides.baseUrl ?? baseUrl;\n const url = `${finalBaseUrl}${path}${queryString}`;\n\n // Merge default, runtime, and per-request headers\n const reqHeaders: Record<string, string> = {\n ...defaultSettings.headers,\n ...runtimeOverrides.headers,\n ...headers,\n };\n\n // Add Authorization header if token is present\n if (token) {\n reqHeaders[\"Authorization\"] = `Bearer ${token}`;\n }\n\n // Only send body if method allows it\n const body = data && method !== \"GET\" ? JSON.stringify(data) : undefined;\n\n // Optional debug logging\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 // Parse the response based on content type\n const isJson = res.headers.get(\"content-type\")?.includes(\"application/json\");\n const responseBody = isJson ? await res.json() : await res.text();\n\n // Handle error responses\n if (!res.ok) {\n const message = typeof responseBody === \"string\" ? responseBody : JSON.stringify(responseBody);\n throw new Error(`[Cohost SDK] ${res.status} ${res.statusText}: ${message}`);\n }\n\n // If wrapped response structure with { status: 'ok', data }, return `data`\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 // Fallback for raw/unwrapped responses\n return responseBody as T;\n };\n};\n\nexport { request, RequestProps, RequestFn };\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';\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): Coh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AAYC,EAA8BC,EAA6B,CANvEC,EAAA,KAAgB,UAChBA,EAAA,KAAgB,UAChBA,EAAA,KAAgB,QAEhBA,EAAA,KAAiB,eAGf,KAAK,YAAcF,EAEnB,GAAM,CAAE,MAAAG,EAAO,SAAAC,EAAW,CAAC,CAAE,EAAIJ,EAE3BK,EAAgBJ,GAAmBK,EAAQ,CAC/C,MAAAH,EACA,QAASC,EAAS,QAAUG,EAC5B,MAAOH,EAAS,KAClB,CAAC,EAED,KAAK,OAAS,IAAII,EAAUH,EAAeD,CAAQ,EACnD,KAAK,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,ECpEO,SAASE,GAAmBC,EAA4C,CAC3E,OAAO,IAAIC,EAAaD,CAAO,CACnC","names":["CohostEndpoint","request","settings","__publicField","EventsAPI","CohostEndpoint","id","OrdersAPI","CohostEndpoint","id","uid","SessionsAPI","CohostEndpoint","input","id","apiBaseUrl","defaultSettings","runtimeOverrides","request","token","baseUrl","apiBaseUrl","debug","path","options","method","data","query","headers","queryString","acc","key","value","url","runtimeOverrides","reqHeaders","defaultSettings","body","res","responseBody","message","CohostClient","_CohostClient","options","customRequestFn","__publicField","token","settings","sharedRequest","request","apiBaseUrl","EventsAPI","OrdersAPI","SessionsAPI","overrides","overriddenRequest","path","createCohostClient","options","CohostClient"]}
|