@gnosticdev/highlevel-sdk
Version:
SDK for the HighLevel API
105 lines (102 loc) • 3.16 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/lib/errors.ts
var HighLevelSDKErrorCodes = {
INVALID_AUTH_HEADER: "INVALID_AUTH_HEADER",
INVALID_AUTH_TYPE: "INVALID_AUTH_TYPE",
NO_HANDLER_REGISTERED: "NO_HANDLER_REGISTERED",
INVALID_WEBHOOK_PAYLOAD: "INVALID_WEBHOOK_PAYLOAD",
API_KEY_REQUIRED: "API_KEY_REQUIRED"
};
var ERROR_MESSAGES = {
[]: 'Authorization header must start with "Bearer "',
[]: "Invalid authentication type provided",
[]: "No handler registered for webhook event: {event}",
[]: "Invalid webhook payload",
[]: "apiKey is required"
};
var HighLevelSDKError = class extends Error {
static {
__name(this, "HighLevelSDKError");
}
constructor(message, options) {
const finalMessage = options?.event ? ERROR_MESSAGES[message].replace("{event}", options.event) : ERROR_MESSAGES[message];
super(finalMessage, options);
this.name = "HighLevelSDKError";
this.cause = HighLevelSDKErrorCodes[message];
}
};
// src/v2/webhooks.ts
var WebhooksClient = class {
static {
__name(this, "WebhooksClient");
}
// Use keyof webhooks instead of string to ensure type safety
handlers = /* @__PURE__ */ new Map();
/**
* Register a handler for a specific webhook event
*
* @example
* ```ts
* const webhooks = new WebhooksClient()
*
* webhooks.on('ContactCreate', async (payload) => {
* // payload is fully typed as ContactCreate schema
* const { firstName, lastName, email } = payload
* await db.contacts.create({ firstName, lastName, email })
* })
* ```
*/
on(event, handler) {
this.handlers.set(event, handler);
return this;
}
/**
* Validate and handle an incoming webhook payload
*
* @example
* ```ts
* app.post('/webhooks/:event', async (ctx) => {
* try {
* await webhooks.handle(ctx.params.event, ctx.request.body)
* return ctx.status(200).end()
* } catch (error) {
* return ctx.status(400).json({ error: error.message })
* }
* })
* ```
*/
async handle(event, payload) {
const handler = this.handlers.get(event);
if (!handler) {
throw new HighLevelSDKError("NO_HANDLER_REGISTERED", { event });
}
if (!payload || typeof payload !== "object") {
throw new HighLevelSDKError("INVALID_WEBHOOK_PAYLOAD");
}
await handler(payload);
}
/**
* Get the TypeScript type for a webhook payload
* Useful for type checking in your IDE
*
* @example
* ```ts
* const webhooks = new WebhooksClient()
*
* const contactType = webhooks.type<'ContactCreate'>()
* // contactType is fully typed as ContactCreate schema
* ```
*/
type() {
return {};
}
};
function createWebhooksClient() {
return new WebhooksClient();
}
__name(createWebhooksClient, "createWebhooksClient");
export {
WebhooksClient,
createWebhooksClient
};