@zimmerstack/connect 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -231,10 +231,30 @@ export declare class ZimmerStack {
231
231
  */
232
232
  all: (query?: Omit<NonNullable<Op<"GET /channel-bookings">["query"]>, "cursor">, options?: ReadOptions) => AsyncGenerator<ChannelBooking, void, undefined>;
233
233
  };
234
+ readonly directBookings: {
235
+ /**
236
+ * Website bookings, in the webhook's shape (`direct.booking.*`), cancellations included. Scope
237
+ * `direct-bookings:read`. Follow `nextCursor`, or use `all`.
238
+ */
239
+ list: (query?: Op<"GET /direct-bookings">["query"], options?: ReadOptions) => Promise<import("./generated.js").ChannelBookingsList>;
240
+ get: (bookingId: number, options?: ReadOptions) => Promise<ChannelBooking>;
241
+ /**
242
+ * Every website booking changed since `since`, page by page. A PMS that pushes room counts reads this
243
+ * before a full push, so the sold rooms are in its own calendar first.
244
+ *
245
+ * @example
246
+ * for await (const booking of zs.directBookings.all({ since: lastSeen })) applyToMyCalendar(booking);
247
+ */
248
+ all: (query?: Omit<NonNullable<Op<"GET /direct-bookings">["query"]>, "cursor">, options?: ReadOptions) => AsyncGenerator<ChannelBooking, void, undefined>;
249
+ };
234
250
  readonly sandbox: {
235
251
  bookings: {
236
252
  list: (options?: ReadOptions) => Promise<import("./generated.js").SandboxBookingsList>;
237
- /** Pretend an OTA booked: the booking, the availability moved down, and the real webhook to your endpoint. */
253
+ /**
254
+ * Pretend an OTA booked: the booking, the availability moved down, and the real webhook to your endpoint.
255
+ * With `otaName: "Website"` it pretends a guest booked on the hotel's own website instead, and the webhook
256
+ * is `direct.booking.created`.
257
+ */
238
258
  create: (body: SandboxBookingCreate, options?: WriteOptions) => Promise<import("./generated.js").SandboxBooking>;
239
259
  cancel: (bookingId: number, options?: ReadOptions) => Promise<import("./generated.js").SandboxBooking>;
240
260
  modify: (bookingId: number, body: SandboxBookingModify, options?: ReadOptions) => Promise<import("./generated.js").SandboxBooking>;
@@ -63,10 +63,14 @@ class Core {
63
63
  #writeTail = Promise.resolve();
64
64
  #dead;
65
65
  catalogs = new Map();
66
+ /** A sandbox company key's one hotel, found once when a call asked for a hotel and none was named. */
67
+ soleSandboxProperty;
68
+ /** The same, once known: sent with every later call that names no hotel, so the refusal is met once. */
69
+ soleSandboxId;
66
70
  constructor(options) {
67
71
  const g = globalThis;
68
72
  if ((typeof g.window !== "undefined" && typeof g.window.document !== "undefined") || g.navigator?.product === "ReactNative") {
69
- throw new ZimmerStackUsageError("@zimmerstack/connect runs on a server only. A key in a browser or a mobile app can be read by anyone and can change a hotel's prices on every channel: call your own server from here, and ZimmerStack from your server.");
73
+ throw new ZimmerStackUsageError("@zimmerstack/connect runs on a server only. A key in a browser or a mobile app can be read by anyone and can change a hotel's prices on every channel: call your own server from here, and ZimmerStack from your server (https://docs.zimmerstack.com/sdk#no-server shows the smallest one). If a key was built into this page, anyone can read it now: revoke it and make a new one.");
70
74
  }
71
75
  const key = options.apiKey ?? env("ZIMMERSTACK_CONNECT_KEY");
72
76
  if (!key)
@@ -271,10 +275,16 @@ export class ZimmerStack {
271
275
  handoff = undefined;
272
276
  this.#core = shared ?? new Core(options);
273
277
  this.mode = this.#core.mode;
274
- if (options.propertyId !== undefined && (!Number.isInteger(options.propertyId) || options.propertyId <= 0)) {
278
+ // A company key's hotel: the option, else (for a client made from the environment) ZIMMERSTACK_PROPERTY_ID.
279
+ const fromEnv = shared ? undefined : env("ZIMMERSTACK_PROPERTY_ID")?.trim();
280
+ if (fromEnv && !/^[1-9]\d*$/.test(fromEnv)) {
281
+ throw new ZimmerStackUsageError("ZIMMERSTACK_PROPERTY_ID must be a property's numeric id (zs.properties.list() names them)");
282
+ }
283
+ const propertyId = options.propertyId ?? (fromEnv ? Number(fromEnv) : undefined);
284
+ if (propertyId !== undefined && (!Number.isInteger(propertyId) || propertyId <= 0)) {
275
285
  throw new ZimmerStackUsageError("propertyId must be a property's numeric id (zs.properties.list() names them)");
276
286
  }
277
- this.propertyId = options.propertyId;
287
+ this.propertyId = propertyId;
278
288
  }
279
289
  /**
280
290
  * A software vendor's company key: the same client, acting on one hotel. Shares this client's pace,
@@ -324,8 +334,9 @@ export class ZimmerStack {
324
334
  if (value !== undefined && value !== null)
325
335
  url.searchParams.set(name, String(value));
326
336
  const headers = { authorization: this.#core.authorization(), accept: "application/json", "user-agent": `zimmerstack-connect-node/${SDK_VERSION}` };
327
- if (this.propertyId)
328
- headers[PROPERTY_HEADER] = String(this.propertyId);
337
+ const hotel = this.propertyId ?? (operation === "GET /properties" ? undefined : this.#core.soleSandboxId);
338
+ if (hotel)
339
+ headers[PROPERTY_HEADER] = String(hotel);
329
340
  const body = args.body === undefined ? undefined : JSON.stringify(args.body);
330
341
  if (body !== undefined)
331
342
  headers["content-type"] = "application/json";
@@ -336,8 +347,47 @@ export class ZimmerStack {
336
347
  }
337
348
  headers[IDEMPOTENCY_HEADER] = args.idempotencyKey ?? crypto.randomUUID();
338
349
  }
339
- const data = await this.#core.send({ operation, method, url, headers, body, write: method !== "GET", resendable: method === "GET" || meta.idempotent, signal: args.signal });
340
- return data;
350
+ const wire = { operation, method, url, headers, body, write: method !== "GET", resendable: method === "GET" || meta.idempotent, signal: args.signal };
351
+ try {
352
+ return (await this.#core.send(wire));
353
+ }
354
+ catch (err) {
355
+ // A company key that named no hotel. The API refused before anything ran, so sending again is safe.
356
+ if (!(err instanceof ZimmerStackError) || err.code !== "PROPERTY_REQUIRED" || this.propertyId !== undefined)
357
+ throw err;
358
+ const sole = await this.#soleSandboxProperty(args.signal);
359
+ if (sole === undefined) {
360
+ throw new ZimmerStackError({
361
+ status: err.status,
362
+ code: err.code,
363
+ message: "This is a company key: say which hotel each call acts on. Use zs.forProperty(id), new ZimmerStack({ propertyId }) or the environment variable ZIMMERSTACK_PROPERTY_ID; zs.properties.list() names the hotels this key reaches.",
364
+ operation,
365
+ details: err.details,
366
+ retryable: false,
367
+ });
368
+ }
369
+ // The same request (same idempotency key) naming the hotel, on its own copy of the headers.
370
+ return (await this.#core.send({ ...wire, headers: { ...headers, [PROPERTY_HEADER]: String(sole) } }));
371
+ }
372
+ }
373
+ /**
374
+ * The one hotel a SANDBOX company key reaches (its sandbox), so the first call of a new integration works
375
+ * without naming it. A live key never guesses: a hotel it acts on is always named.
376
+ */
377
+ #soleSandboxProperty(signal) {
378
+ if (this.mode !== "test")
379
+ return Promise.resolve(undefined);
380
+ this.#core.soleSandboxProperty ??= this.request("GET /properties", { signal })
381
+ .then((list) => {
382
+ const only = list.keyKind === "company" && list.properties.length === 1 && list.properties[0].sandbox ? list.properties[0].id : undefined;
383
+ this.#core.soleSandboxId = only;
384
+ return only;
385
+ })
386
+ .catch(() => {
387
+ this.#core.soleSandboxProperty = undefined; // a failed lookup is asked again next time
388
+ return undefined;
389
+ });
390
+ return this.#core.soleSandboxProperty;
341
391
  }
342
392
  /* ── which hotel ── */
343
393
  properties = {
@@ -496,12 +546,30 @@ export class ZimmerStack {
496
546
  * @example
497
547
  * for await (const booking of zs.channelBookings.all({ since: lastSeen })) save(booking);
498
548
  */
499
- all: (query, options) => this.#allChannelBookings(query, options),
549
+ all: (query, options) => this.#allPages((cursor) => this.channelBookings.list({ limit: 100, ...query, cursor }, options)),
550
+ };
551
+ /* ── bookings guests made on the hotel's own website (our booking engine) ── */
552
+ directBookings = {
553
+ /**
554
+ * Website bookings, in the webhook's shape (`direct.booking.*`), cancellations included. Scope
555
+ * `direct-bookings:read`. Follow `nextCursor`, or use `all`.
556
+ */
557
+ list: (query, options) => this.request("GET /direct-bookings", { query, ...options }),
558
+ get: (bookingId, options) => this.request("GET /direct-bookings/{bookingId}", { path: { bookingId }, ...options }),
559
+ /**
560
+ * Every website booking changed since `since`, page by page. A PMS that pushes room counts reads this
561
+ * before a full push, so the sold rooms are in its own calendar first.
562
+ *
563
+ * @example
564
+ * for await (const booking of zs.directBookings.all({ since: lastSeen })) applyToMyCalendar(booking);
565
+ */
566
+ all: (query, options) => this.#allPages((cursor) => this.directBookings.list({ limit: 100, ...query, cursor }, options)),
500
567
  };
501
- async *#allChannelBookings(query, options) {
568
+ /** Follow a booking list's `nextCursor` to its last page. */
569
+ async *#allPages(read) {
502
570
  let cursor;
503
571
  do {
504
- const page = await this.channelBookings.list({ limit: 100, ...query, cursor }, options);
572
+ const page = await read(cursor);
505
573
  yield* page.items;
506
574
  cursor = page.nextCursor ?? undefined;
507
575
  } while (cursor);
@@ -510,7 +578,11 @@ export class ZimmerStack {
510
578
  sandbox = {
511
579
  bookings: {
512
580
  list: (options) => this.request("GET /sandbox/bookings", options),
513
- /** Pretend an OTA booked: the booking, the availability moved down, and the real webhook to your endpoint. */
581
+ /**
582
+ * Pretend an OTA booked: the booking, the availability moved down, and the real webhook to your endpoint.
583
+ * With `otaName: "Website"` it pretends a guest booked on the hotel's own website instead, and the webhook
584
+ * is `direct.booking.created`.
585
+ */
514
586
  create: (body, options) => this.request("POST /sandbox/bookings", { body, ...options }),
515
587
  cancel: (bookingId, options) => this.request("POST /sandbox/bookings/{bookingId}/cancel", { path: { bookingId }, ...options }),
516
588
  modify: (bookingId, body, options) => this.request("POST /sandbox/bookings/{bookingId}/modify", { path: { bookingId }, body, ...options }),
@@ -1,5 +1,5 @@
1
1
  /** This package's version, sent as the user agent so ZimmerStack can tell which client a request came from. */
2
- export declare const SDK_VERSION = "0.1.0";
2
+ export declare const SDK_VERSION = "0.3.0";
3
3
  /** Where the API lives. The key is sent nowhere else. */
4
4
  export declare const API_ORIGIN = "https://api.zimmerstack.com";
5
5
  export declare const API_PREFIX = "/api/v1/connect-api/v1";
@@ -28,7 +28,7 @@ export declare const LIMITS: {
28
28
  export declare const ERROR_CODES: readonly ["API_KEY_INVALID", "API_KEY_REVOKED", "API_KEY_EXPIRED", "CONNECT_API_NOT_CONFIGURED", "IP_NOT_ALLOWED", "SCOPE_MISSING", "PROPERTY_UNAVAILABLE", "CHANNEL_MANAGER_DISABLED", "PMS_NOT_AVAILABLE", "VALIDATION", "RANGE_INVALID", "HORIZON", "TOO_MANY_UPDATES", "TOO_MANY_CELLS", "UNKNOWN_ROOM_TYPE", "UNKNOWN_RATE_PLAN", "CURRENCY_MISMATCH", "RATE_LIMITED", "NOTHING_ACCEPTED", "BATCH_NOT_FOUND", "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_REUSED", "IDEMPOTENCY_IN_FLIGHT", "STAY_INVALID", "UNKNOWN_ROOM_TYPE_FOR_PLAN", "OCCUPANCY_EXCEEDED", "NO_AVAILABILITY", "EXTERNAL_REFERENCE_REUSED", "PAYMENT_NOT_ALLOWED", "PAYMENT_EXCEEDS_TOTAL", "BOOKING_NOT_FOUND", "BOOKING_NOT_CANCELLABLE", "MODULE_NOT_ENTITLED", "SANDBOX_ONLY", "ROOM_TYPE_NOT_FOUND", "RATE_PLAN_NOT_FOUND", "CATALOG_CONFLICT", "CATALOG_BUSY", "CHANNEL_MANAGER_ERROR", "PROPERTY_REQUIRED", "PROPERTY_NOT_FOUND", "ARI_NOT_AUTHORITATIVE", "ROUTE_NOT_FOUND", "PAYLOAD_TOO_LARGE", "AUTH_BACKEND_UNAVAILABLE", "BOOKING_NOT_MODIFIABLE", "SANDBOX_NOT_FOUND", "SANDBOX_INCOMPLETE", "WRITES_FROZEN", "WRITES_SUSPENDED", "SHIELD_UNAVAILABLE", "CATALOG_LIMIT_REACHED", "TOO_MANY_NEW_ENTITIES", "RATE_OUT_OF_BAND", "CHANNEL_NOT_FOUND", "CHANNEL_SHARED", "MODIFIER_OUT_OF_BAND"];
29
29
  export type ErrorCode = (typeof ERROR_CODES)[number];
30
30
  /** What a key may do. The hotel's owner (or, for a vendor's key, the vendor) chose them when the key was made. */
31
- export declare const SCOPES: readonly ["ari:read", "ari:write", "catalog:write", "channel-modifiers:write", "channel-bookings:read", "bookings:read", "bookings:write", "bookings:payments"];
31
+ export declare const SCOPES: readonly ["ari:read", "ari:write", "catalog:write", "channel-modifiers:write", "channel-bookings:read", "direct-bookings:read", "bookings:read", "bookings:write", "bookings:payments"];
32
32
  export type Scope = (typeof SCOPES)[number];
33
33
  /** When a channel's price modifier takes effect. Show it where a person saves one. */
34
34
  export declare const MODIFIER_TAKES_EFFECT = "A modifier applies to prices sent to the channel after the change. Prices already on the channel stay as they are until those nights are sent again.";
@@ -166,7 +166,7 @@ export interface RoomTypesUpsert {
166
166
  ref: string;
167
167
  /** Shown to the owner and sent to the channel manager as the title */
168
168
  name: string;
169
- /** Sellable rooms of this type. Read on create; a later change is made in the channel manager (the count there is the truth the channels sell) */
169
+ /** Sellable rooms of this type. On a channel-manager-only hotel a later change is written too, to the channel manager first (its count caps what the channels sell); a count below the rooms holding upcoming stays is refused. On a hotel that runs our PMS the count comes from its room list and a different value is not written (the answer's notice says so) */
170
170
  roomCount: number;
171
171
  /** Most adults one room takes */
172
172
  adults: number;
@@ -585,9 +585,9 @@ export interface SandboxBookingCreate {
585
585
  adults?: number;
586
586
  /** The guest's name; default a fictional one */
587
587
  guestName?: string;
588
- /** The channel the booking pretends to arrive from; default Booking.com */
589
- otaName?: "Booking.com" | "Expedia" | "Agoda" | "Airbnb" | "MakeMyTrip" | "Goibibo";
590
- /** true = the channel collected the money, so totalPaid equals the total; default false (pay at the property) */
588
+ /** The channel the booking pretends to arrive from; default Booking.com. "Website" simulates a booking on the hotel's own website (our booking engine): it sends direct.booking.created and is listed by GET /direct-bookings, not GET /channel-bookings */
589
+ otaName?: "Booking.com" | "Expedia" | "Agoda" | "Airbnb" | "MakeMyTrip" | "Goibibo" | "Website";
590
+ /** true = the channel collected the money (for Website: the guest paid online), so totalPaid equals the total; default false (pay at the property) */
591
591
  paidByOta?: boolean;
592
592
  }
593
593
  export interface SandboxBookingModify {
@@ -872,13 +872,13 @@ export interface SandboxBooking {
872
872
  createdAt: string;
873
873
  /** What this call put on the wire for the sandbox's webhook endpoints */
874
874
  webhook: {
875
- eventType: "channel.booking.created" | "channel.booking.modified" | "channel.booking.cancelled";
875
+ eventType: "channel.booking.created" | "channel.booking.modified" | "channel.booking.cancelled" | "direct.booking.created" | "direct.booking.cancelled";
876
876
  /** The event is in the outbox; every active endpoint on the sandbox receives it within seconds */
877
877
  queued: boolean;
878
878
  };
879
879
  }
880
880
  export interface SandboxBookingsList {
881
- /** Simulated OTA bookings on the sandbox, newest first */
881
+ /** Simulated bookings on the sandbox (OTA and website), newest first */
882
882
  bookings: Array<{
883
883
  /** The PMS booking id, the one the webhook carries */
884
884
  bookingId: number;
@@ -905,7 +905,7 @@ export interface SandboxBookingsList {
905
905
  createdAt: string;
906
906
  /** What this call put on the wire for the sandbox's webhook endpoints */
907
907
  webhook: {
908
- eventType: "channel.booking.created" | "channel.booking.modified" | "channel.booking.cancelled";
908
+ eventType: "channel.booking.created" | "channel.booking.modified" | "channel.booking.cancelled" | "direct.booking.created" | "direct.booking.cancelled";
909
909
  /** The event is in the outbox; every active endpoint on the sandbox receives it within seconds */
910
910
  queued: boolean;
911
911
  };
@@ -1103,6 +1103,27 @@ export interface Operations {
1103
1103
  body: undefined;
1104
1104
  response: ChannelBooking;
1105
1105
  };
1106
+ /** The bookings guests made on the hotel's own website, in the webhook's shape */
1107
+ "GET /direct-bookings": {
1108
+ path: undefined;
1109
+ query: {
1110
+ since?: string;
1111
+ status?: "CONFIRMED" | "CANCELLED";
1112
+ limit?: number;
1113
+ cursor?: string;
1114
+ };
1115
+ body: undefined;
1116
+ response: ChannelBookingsList;
1117
+ };
1118
+ /** One website booking, the webhook's shape */
1119
+ "GET /direct-bookings/{bookingId}": {
1120
+ path: {
1121
+ bookingId: string | number;
1122
+ };
1123
+ query: undefined;
1124
+ body: undefined;
1125
+ response: ChannelBooking;
1126
+ };
1106
1127
  /** Simulated OTA bookings on the sandbox, newest first */
1107
1128
  "GET /sandbox/bookings": {
1108
1129
  path: undefined;
@@ -1,7 +1,7 @@
1
1
  // GENERATED by scripts/generate.mjs from the Connect API's public contract (ZimmerStack Connect API v1).
2
2
  // Do not edit: change the contract, then run `pnpm --dir apps/connect-sdk run generate`.
3
3
  /** This package's version, sent as the user agent so ZimmerStack can tell which client a request came from. */
4
- export const SDK_VERSION = "0.1.0";
4
+ export const SDK_VERSION = "0.3.0";
5
5
  /** Where the API lives. The key is sent nowhere else. */
6
6
  export const API_ORIGIN = "https://api.zimmerstack.com";
7
7
  export const API_PREFIX = "/api/v1/connect-api/v1";
@@ -93,6 +93,7 @@ export const SCOPES = [
93
93
  "catalog:write",
94
94
  "channel-modifiers:write",
95
95
  "channel-bookings:read",
96
+ "direct-bookings:read",
96
97
  "bookings:read",
97
98
  "bookings:write",
98
99
  "bookings:payments"
@@ -124,6 +125,8 @@ export const OPERATIONS = {
124
125
  "POST /rates/resend": { idempotent: true, bodyRequired: false },
125
126
  "GET /channel-bookings": { idempotent: false, bodyRequired: false },
126
127
  "GET /channel-bookings/{bookingId}": { idempotent: false, bodyRequired: false },
128
+ "GET /direct-bookings": { idempotent: false, bodyRequired: false },
129
+ "GET /direct-bookings/{bookingId}": { idempotent: false, bodyRequired: false },
127
130
  "GET /sandbox/bookings": { idempotent: false, bodyRequired: false },
128
131
  "POST /sandbox/bookings": { idempotent: true, bodyRequired: true },
129
132
  "POST /sandbox/bookings/{bookingId}/cancel": { idempotent: false, bodyRequired: false },
@@ -10,7 +10,7 @@ export { ZimmerStackError, ZimmerStackUsageError } from "./errors.js";
10
10
  export type { LocalErrorCode } from "./errors.js";
11
11
  export { addDays, buildGrid, channelPrice, chunk, eachDate, toRanges } from "./grid.js";
12
12
  export type { Grid, GridEdits, ModifierStep, Range, Restrictions } from "./grid.js";
13
- export { verifyWebhook, ZimmerStackWebhookError } from "./webhooks.js";
14
- export type { WebhookEvent } from "./webhooks.js";
13
+ export { BOOKING_EVENT_TYPES, OTA_BOOKING_EVENT_TYPES, WEBSITE_BOOKING_EVENT_TYPES, isOtaBookingEvent, isWebsiteBookingEvent, verifyWebhook, ZimmerStackWebhookError } from "./webhooks.js";
14
+ export type { BookingEvent, BookingEventType, OtaBookingEvent, OtaBookingEventType, WebhookEvent, WebhookEventType, WebsiteBookingEvent, WebsiteBookingEventType } from "./webhooks.js";
15
15
  export { ERROR_CODES, LIMITS, MODIFIER_TAKES_EFFECT, SCOPES, SDK_VERSION } from "./generated.js";
16
16
  export type * from "./generated.js";
package/dist/esm/index.js CHANGED
@@ -7,5 +7,5 @@
7
7
  export { ZimmerStack } from "./client.js";
8
8
  export { ZimmerStackError, ZimmerStackUsageError } from "./errors.js";
9
9
  export { addDays, buildGrid, channelPrice, chunk, eachDate, toRanges } from "./grid.js";
10
- export { verifyWebhook, ZimmerStackWebhookError } from "./webhooks.js";
10
+ export { BOOKING_EVENT_TYPES, OTA_BOOKING_EVENT_TYPES, WEBSITE_BOOKING_EVENT_TYPES, isOtaBookingEvent, isWebsiteBookingEvent, verifyWebhook, ZimmerStackWebhookError } from "./webhooks.js";
11
11
  export { ERROR_CODES, LIMITS, MODIFIER_TAKES_EFFECT, SCOPES, SDK_VERSION } from "./generated.js";