@zimmerstack/connect 0.4.1 → 0.6.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.
@@ -4,7 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.OPERATIONS = exports.MODIFIER_TAKES_EFFECT = exports.SCOPES = exports.ERROR_CODES = exports.LIMITS = exports.PROPERTY_HEADER = exports.IDEMPOTENCY_HEADER = exports.API_PREFIX = exports.API_ORIGIN = exports.SDK_VERSION = void 0;
6
6
  /** This package's version, sent as the user agent so ZimmerStack can tell which client a request came from. */
7
- exports.SDK_VERSION = "0.4.1";
7
+ exports.SDK_VERSION = "0.6.0";
8
8
  /** Where the API lives. The key is sent nowhere else. */
9
9
  exports.API_ORIGIN = "https://api.zimmerstack.com";
10
10
  exports.API_PREFIX = "/api/v1/connect-api/v1";
@@ -89,7 +89,15 @@ exports.ERROR_CODES = [
89
89
  "RATE_OUT_OF_BAND",
90
90
  "CHANNEL_NOT_FOUND",
91
91
  "CHANNEL_SHARED",
92
- "MODIFIER_OUT_OF_BAND"
92
+ "MODIFIER_OUT_OF_BAND",
93
+ "COMPANY_KEY_REQUIRED",
94
+ "BILLING_SETUP_REQUIRED",
95
+ "OWNER_HAS_ACCOUNT",
96
+ "SANDBOX_LIMIT",
97
+ "CONFIRMATION_MISMATCH",
98
+ "PROPERTY_NOT_REMOVABLE",
99
+ "PROPERTY_BUSY",
100
+ "PRICE_UNAVAILABLE"
93
101
  ];
94
102
  /** What a key may do. The hotel's owner (or, for a vendor's key, the vendor) chose them when the key was made. */
95
103
  exports.SCOPES = [
@@ -102,13 +110,16 @@ exports.SCOPES = [
102
110
  "direct-bookings:cancel",
103
111
  "bookings:read",
104
112
  "bookings:write",
105
- "bookings:payments"
113
+ "bookings:payments",
114
+ "properties:write"
106
115
  ];
107
116
  /** When a channel's price modifier takes effect. Show it where a person saves one. */
108
- exports.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.";
117
+ exports.MODIFIER_TAKES_EFFECT = "Saving a modifier makes the channel manager send that channel every date again, so prices already on the channel move to the new rule within minutes.";
109
118
  /** idempotent: the server replays the stored answer when the idempotency key repeats, so the client may resend the request after a network failure. */
110
119
  exports.OPERATIONS = {
111
120
  "GET /properties": { idempotent: false, bodyRequired: false },
121
+ "POST /properties": { idempotent: true, bodyRequired: true },
122
+ "DELETE /properties/{propertyId}": { idempotent: false, bodyRequired: false },
112
123
  "GET /property": { idempotent: false, bodyRequired: false },
113
124
  "GET /catalog": { idempotent: false, bodyRequired: false },
114
125
  "PUT /catalog/room-types": { idempotent: true, bodyRequired: true },
@@ -5,7 +5,7 @@
5
5
  * mobile app, a repository or a log line.
6
6
  */
7
7
  export { ZimmerStack } from "./client.js";
8
- export type { ClientEvent, ReadOptions, RequestArgs, WriteOptions, ZimmerStackOptions } from "./client.js";
8
+ export type { ClientEvent, RatePlanInput, ReadOptions, RequestArgs, RoomTypeInput, StructureSaved, WriteOptions, ZimmerStackOptions } from "./client.js";
9
9
  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";
@@ -6,13 +6,19 @@ import type { ChannelBooking } from "./generated.js";
6
6
  /** An OTA booking arrived, changed or was cancelled (through the channel manager). */
7
7
  export declare const OTA_BOOKING_EVENT_TYPES: readonly ["channel.booking.created", "channel.booking.modified", "channel.booking.cancelled"];
8
8
  /**
9
- * A guest booked, or cancelled, on the hotel's own website through ZimmerStack's booking engine. The same
10
- * booking object as the OTA events, in a family of its own: an endpoint receives these only when it lists
11
- * the two types. There is no modified event.
9
+ * A booking on the hotel's own website through ZimmerStack's booking engine: the guest booked, the hotel
10
+ * recorded that the guest did not arrive (or undid that), or the booking was cancelled. The same booking
11
+ * object as the OTA events, in a family of its own: an endpoint receives each of these only when it lists
12
+ * that type.
13
+ *
14
+ * `direct.booking.modified` (from 0.6.0; the API sends it since 21 Nov 2026) is a no-show and its undo.
15
+ * The booking is not cancelled: `status` stays CONFIRMED and the payment is untouched. Read
16
+ * `data.booking.stayStatus`: NOSHOW means the nights are on sale again (free the room), UPCOMING again
17
+ * means the no-show was undone (hold the room). Nothing else sends it yet.
12
18
  */
13
- export declare const WEBSITE_BOOKING_EVENT_TYPES: readonly ["direct.booking.created", "direct.booking.cancelled"];
19
+ export declare const WEBSITE_BOOKING_EVENT_TYPES: readonly ["direct.booking.created", "direct.booking.modified", "direct.booking.cancelled"];
14
20
  /** Every event whose `data.booking` is a booking, of either family. */
15
- export declare const BOOKING_EVENT_TYPES: readonly ["channel.booking.created", "channel.booking.modified", "channel.booking.cancelled", "direct.booking.created", "direct.booking.cancelled"];
21
+ export declare const BOOKING_EVENT_TYPES: readonly ["channel.booking.created", "channel.booking.modified", "channel.booking.cancelled", "direct.booking.created", "direct.booking.modified", "direct.booking.cancelled"];
16
22
  export type OtaBookingEventType = (typeof OTA_BOOKING_EVENT_TYPES)[number];
17
23
  export type WebsiteBookingEventType = (typeof WEBSITE_BOOKING_EVENT_TYPES)[number];
18
24
  export type BookingEventType = (typeof BOOKING_EVENT_TYPES)[number];
@@ -24,7 +30,7 @@ export interface WebhookEvent {
24
30
  id: string;
25
31
  /**
26
32
  * channel.booking.created · channel.booking.modified · channel.booking.cancelled (an OTA booking) ·
27
- * direct.booking.created · direct.booking.cancelled (a booking on the hotel's own website) ·
33
+ * direct.booking.created · direct.booking.modified · direct.booking.cancelled (a booking on the hotel's own website) ·
28
34
  * channel.sync.* · zimmerstack.ping. Narrow it with `isOtaBookingEvent` and `isWebsiteBookingEvent`.
29
35
  */
30
36
  type: string;
@@ -43,9 +49,9 @@ export interface WebhookEvent {
43
49
  booking?: ChannelBooking;
44
50
  [key: string]: unknown;
45
51
  };
46
- /** Dotted paths that changed, on a modification ("stay.checkOut"). */
52
+ /** Dotted paths that changed, on a modification ("stay.checkOut"; on a website booking's no-show, "stayStatus" and "rooms[0].status"). */
47
53
  changes?: string[] | null;
48
- /** What those fields held before, on a modification. */
54
+ /** What those fields held before, on a modification. A website booking's carries `stayStatus` too. */
49
55
  previous?: Record<string, unknown> | null;
50
56
  truncated?: boolean;
51
57
  }
@@ -57,7 +63,10 @@ export type BookingEvent = WebhookEvent & {
57
63
  [key: string]: unknown;
58
64
  };
59
65
  };
60
- /** A booking a guest made on the hotel's own website. `finance` is null and `changes` and `previous` always are. */
66
+ /**
67
+ * A booking a guest made on the hotel's own website. `finance` is always null; `changes` and `previous`
68
+ * are set on `direct.booking.modified` (a no-show, or its undo) and null on the other two.
69
+ */
61
70
  export type WebsiteBookingEvent = BookingEvent & {
62
71
  type: WebsiteBookingEventType;
63
72
  };
@@ -66,8 +75,9 @@ export type OtaBookingEvent = BookingEvent & {
66
75
  type: OtaBookingEventType;
67
76
  };
68
77
  /**
69
- * True for `direct.booking.created` and `direct.booking.cancelled`: a booking made on the hotel's own
70
- * website. A PMS that pushes room counts must put it in its own calendar before its next push.
78
+ * True for `direct.booking.created`, `direct.booking.modified` and `direct.booking.cancelled`: a booking
79
+ * made on the hotel's own website. A PMS that pushes room counts must put it in its own calendar before its
80
+ * next push, and give the nights back when the booking is cancelled or reads `stayStatus` NOSHOW.
71
81
  */
72
82
  export declare function isWebsiteBookingEvent(event: WebhookEvent): event is WebsiteBookingEvent;
73
83
  /** True for `channel.booking.created`, `.modified` and `.cancelled`: a booking an OTA sent. */
@@ -11,17 +11,24 @@ exports.verifyWebhook = verifyWebhook;
11
11
  /** An OTA booking arrived, changed or was cancelled (through the channel manager). */
12
12
  exports.OTA_BOOKING_EVENT_TYPES = ["channel.booking.created", "channel.booking.modified", "channel.booking.cancelled"];
13
13
  /**
14
- * A guest booked, or cancelled, on the hotel's own website through ZimmerStack's booking engine. The same
15
- * booking object as the OTA events, in a family of its own: an endpoint receives these only when it lists
16
- * the two types. There is no modified event.
14
+ * A booking on the hotel's own website through ZimmerStack's booking engine: the guest booked, the hotel
15
+ * recorded that the guest did not arrive (or undid that), or the booking was cancelled. The same booking
16
+ * object as the OTA events, in a family of its own: an endpoint receives each of these only when it lists
17
+ * that type.
18
+ *
19
+ * `direct.booking.modified` (from 0.6.0; the API sends it since 21 Nov 2026) is a no-show and its undo.
20
+ * The booking is not cancelled: `status` stays CONFIRMED and the payment is untouched. Read
21
+ * `data.booking.stayStatus`: NOSHOW means the nights are on sale again (free the room), UPCOMING again
22
+ * means the no-show was undone (hold the room). Nothing else sends it yet.
17
23
  */
18
- exports.WEBSITE_BOOKING_EVENT_TYPES = ["direct.booking.created", "direct.booking.cancelled"];
24
+ exports.WEBSITE_BOOKING_EVENT_TYPES = ["direct.booking.created", "direct.booking.modified", "direct.booking.cancelled"];
19
25
  /** Every event whose `data.booking` is a booking, of either family. */
20
26
  exports.BOOKING_EVENT_TYPES = [...exports.OTA_BOOKING_EVENT_TYPES, ...exports.WEBSITE_BOOKING_EVENT_TYPES];
21
27
  const isType = (list, event) => typeof event?.type === "string" && list.includes(event.type);
22
28
  /**
23
- * True for `direct.booking.created` and `direct.booking.cancelled`: a booking made on the hotel's own
24
- * website. A PMS that pushes room counts must put it in its own calendar before its next push.
29
+ * True for `direct.booking.created`, `direct.booking.modified` and `direct.booking.cancelled`: a booking
30
+ * made on the hotel's own website. A PMS that pushes room counts must put it in its own calendar before its
31
+ * next push, and give the nights back when the booking is cancelled or reads `stayStatus` NOSHOW.
25
32
  */
26
33
  function isWebsiteBookingEvent(event) {
27
34
  return isType(exports.WEBSITE_BOOKING_EVENT_TYPES, event) && Boolean(event.data?.booking);
@@ -1,4 +1,4 @@
1
- import { type AvailabilityWrite, type BatchStatus, type Booking, type BookingCancel, type BookingCreate, type Catalog, type ChannelBooking, type DirectBookingCancel, type DirectBookingCancelResult, type ModifierResult, type OperationKey, type Operations, type RatePlansUpsert, type RatesResendAccepted, type RatesWrite, type RestrictionsWrite, type RoomTypesUpsert, type SandboxBookingCreate, type SandboxBookingModify, type WriteAccepted } from "./generated.js";
1
+ import { type AvailabilityWrite, type BatchStatus, type Booking, type BookingCancel, type BookingCreate, type Catalog, type CatalogDeleteResult, type CatalogUpsertResult, type ChannelBooking, type DirectBookingCancel, type DirectBookingCancelResult, type ModifierResult, type OperationKey, type Operations, type PropertyCreate, type PropertyCreated, type PropertyRemoved, type RatePlansUpsert, type RatesResendAccepted, type RatesWrite, type RestrictionsWrite, type RoomTypesUpsert, type SandboxBookingCreate, type SandboxBookingModify, type WriteAccepted } from "./generated.js";
2
2
  import { type Grid, type GridEdits, type ModifierStep } from "./grid.js";
3
3
  export interface ZimmerStackOptions {
4
4
  /**
@@ -12,7 +12,7 @@ export interface ZimmerStackOptions {
12
12
  baseUrl?: string;
13
13
  /** A replacement for the global `fetch`, for tests. */
14
14
  fetch?: typeof fetch;
15
- /** How long one attempt may take. Default 30 s. */
15
+ /** How long one attempt may take. Default 30 s. Adding a hotel and removing one are given at least 95 s. */
16
16
  timeoutMs?: number;
17
17
  /** How many times a request that may pass later is sent again. Default 3 (four attempts in all), at most 5. */
18
18
  maxRetries?: number;
@@ -56,6 +56,18 @@ export interface WriteOptions {
56
56
  export interface ReadOptions {
57
57
  signal?: AbortSignal;
58
58
  }
59
+ /** One room type, as `zs.roomTypes.save` takes it. */
60
+ export type RoomTypeInput = RoomTypesUpsert["roomTypes"][number];
61
+ /** One rate plan, as `zs.ratePlans.save` takes it. */
62
+ export type RatePlanInput = RatePlansUpsert["ratePlans"][number];
63
+ /**
64
+ * What saving one room type or one rate plan answers: its ZimmerStack `id`, what was done (`action`),
65
+ * how far it has travelled (`sync`), anything to know (`notice`), and where the hotel stands on its
66
+ * channels after the save (`channelManager`).
67
+ */
68
+ export type StructureSaved = CatalogUpsertResult["items"][number] & {
69
+ channelManager: CatalogUpsertResult["channelManager"];
70
+ };
59
71
  type Op<K extends OperationKey> = Operations[K];
60
72
  /** What `request` takes for an operation: its path values, its query, its body. */
61
73
  export type RequestArgs<K extends OperationKey> = (Op<K>["path"] extends undefined ? {
@@ -71,6 +83,8 @@ export type RequestArgs<K extends OperationKey> = (Op<K>["path"] extends undefin
71
83
  } : {
72
84
  body: Op<K>["body"];
73
85
  }) & WriteOptions;
86
+ /** How long one attempt of an operation may take: the client's `timeoutMs`, or longer for the slow ones above. */
87
+ export declare function attemptTimeoutMs(operation: string, timeoutMs: number): number;
74
88
  /**
75
89
  * The ZimmerStack Connect API, from your server.
76
90
  *
@@ -115,6 +129,61 @@ export declare class ZimmerStack {
115
129
  readonly properties: {
116
130
  /** The hotels this key may act on. A company key names one of them on every other call (`forProperty`). */
117
131
  list: (options?: ReadOptions) => Promise<import("./generated.js").Properties>;
132
+ /**
133
+ * Add a hotel. Only a software partner's COMPANY key that holds the scope properties:write can; tick
134
+ * "Also add and remove hotels" when you make the key in the partner portal. A hotel's own key is refused.
135
+ *
136
+ * The answer's `id` is the hotel: act on it with `zs.forProperty(id)`. Its owner gets the sign-in details
137
+ * by email; they are never sent to you. `billing.state` says whether it is on your invoice yet, and
138
+ * `channelManager` turns true with your first `roomTypes.save` or `catalog.upsertRoomTypes` for it.
139
+ *
140
+ * With a test key (zsk_test_) the same call makes a sandbox instead: a practice hotel no booking site
141
+ * sees, never billed. Safe to retry: the same `idempotencyKey` answers with the same hotel and
142
+ * `replay: true`, and never makes a second one.
143
+ *
144
+ * @example
145
+ * const hotel = await zs.properties.create({
146
+ * name: "Sea Breeze Apartments",
147
+ * owner: { name: "Nimal Perera", email: "nimal@seabreeze.example", phone: "+94 77 123 4567" },
148
+ * address: { line1: "12 Beach Road", city: "Galle", country: "LK" },
149
+ * roomTypes: [{ ref: "deluxe", name: "Deluxe Room", roomCount: 6, defaultRate: "90.00" }],
150
+ * });
151
+ * const seaBreeze = zs.forProperty(hotel.id);
152
+ */
153
+ create: (hotel: PropertyCreate, options?: WriteOptions) => Promise<PropertyCreated>;
154
+ /**
155
+ * Remove a hotel YOU ADDED, for good. A company key with the scope properties:write.
156
+ *
157
+ * One call does what ZimmerStack does when a hotel's service ends, in this order: its booking sites
158
+ * are disconnected, its rate plans are removed from the channel manager, then its room types, then the
159
+ * hotel is closed (its owner can no longer sign in, and no key reaches it). It comes off your invoice
160
+ * from the next 1st; the month already billed is not refunded. Bookings already made stay with the
161
+ * booking sites and the hotel.
162
+ *
163
+ * THERE IS NO UNDO. Call it when a person chose to remove that hotel; never from a loop, a timer or a
164
+ * sync job. `confirm` is the hotel's exact name, as `zs.properties.list()` prints it, so a wrong id never
165
+ * removes a hotel. Move the hotel's booking sites to its next channel manager first, so it keeps selling.
166
+ *
167
+ * The answer: `channelManager.state` is REMOVED when nothing is left on the channel manager, or
168
+ * RETRYING when the hotel is closed and off your bill but one step there is still finishing (ZimmerStack
169
+ * retries it; you do nothing). Calling it again later answers `replay: true`. A hotel you did not add,
170
+ * or one that uses more than the channel manager, is refused with PROPERTY_NOT_REMOVABLE and who can do
171
+ * it. With a test key it deletes a sandbox.
172
+ *
173
+ * @example
174
+ * const { properties } = await zs.properties.list();
175
+ * const hotel = properties.find((p) => p.id === 61);
176
+ * if (hotel) await zs.properties.delete(hotel.id, { confirm: hotel.name });
177
+ */
178
+ delete: (propertyId: number, options: {
179
+ confirm: string;
180
+ signal?: AbortSignal;
181
+ }) => Promise<PropertyRemoved>;
182
+ /** The same as `delete`, under the word the partner portal uses ("Remove hotel"). */
183
+ remove: (propertyId: number, options: {
184
+ confirm: string;
185
+ signal?: AbortSignal;
186
+ }) => Promise<PropertyRemoved>;
118
187
  };
119
188
  readonly property: {
120
189
  /** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
@@ -124,12 +193,72 @@ export declare class ZimmerStack {
124
193
  /** Room types and rate plans, with the numeric ids every write uses. */
125
194
  get: (options?: ReadOptions) => Promise<Catalog>;
126
195
  /** Create or change room types by your own `ref`. Needs the scope catalog:write. */
127
- upsertRoomTypes: (body: RoomTypesUpsert, options?: WriteOptions) => Promise<import("./generated.js").CatalogUpsertResult>;
196
+ upsertRoomTypes: (body: RoomTypesUpsert, options?: WriteOptions) => Promise<CatalogUpsertResult>;
128
197
  /** Delete a room type; its rate plans go with it. */
129
- deleteRoomType: (roomTypeId: number, options?: ReadOptions) => Promise<import("./generated.js").CatalogDeleteResult>;
198
+ deleteRoomType: (roomTypeId: number, options?: ReadOptions) => Promise<CatalogDeleteResult>;
130
199
  /** Create or change rate plans by your own `ref`. */
131
- upsertRatePlans: (body: RatePlansUpsert, options?: WriteOptions) => Promise<import("./generated.js").CatalogUpsertResult>;
132
- deleteRatePlan: (ratePlanId: number, options?: ReadOptions) => Promise<import("./generated.js").CatalogDeleteResult>;
200
+ upsertRatePlans: (body: RatePlansUpsert, options?: WriteOptions) => Promise<CatalogUpsertResult>;
201
+ /** Delete a rate plan. Refused while a channel still sells it. */
202
+ deleteRatePlan: (ratePlanId: number, options?: ReadOptions) => Promise<CatalogDeleteResult>;
203
+ };
204
+ readonly roomTypes: {
205
+ /** Every room type of the hotel, each with the numeric `id` that room counts and bookings name. */
206
+ list: (options?: ReadOptions) => Promise<Catalog["roomTypes"]>;
207
+ /**
208
+ * Create a room type, or change it if you sent this `ref` before. `ref` is your own id for it; the
209
+ * answer's `id` is ZimmerStack's, the one every later call names. Needs the scope catalog:write.
210
+ * To send several in one request use `catalog.upsertRoomTypes`.
211
+ *
212
+ * @example
213
+ * const room = await zs.roomTypes.save({ ref: "deluxe", name: "Deluxe Room", roomCount: 8, adults: 2 });
214
+ * room.id; // use it in availability.set and in a rate plan's roomTypeId
215
+ */
216
+ save: (roomType: RoomTypeInput, options?: WriteOptions) => Promise<StructureSaved>;
217
+ /**
218
+ * Delete a room type for good, by its `id` (a number) or by your own `ref` (a string). Its rate
219
+ * plans are deleted with it; the answer's `deletedRatePlanIds` names them. Needs the scope
220
+ * catalog:write.
221
+ *
222
+ * THERE IS NO UNDO. Call it when a person chose to delete; never from a loop, a timer or a sync job.
223
+ * It is refused while a booking site still sells one of its rate plans (unmap the plan on the
224
+ * channel first), while an upcoming stay holds one of its rooms, or while rooms are still assigned
225
+ * to it on a hotel that runs the ZimmerStack PMS: CATALOG_CONFLICT, or CHANNEL_MANAGER_ERROR when
226
+ * the refusal is the channel manager's. Show the message; nothing was deleted. Deletes have a daily
227
+ * budget per hotel (RATE_LIMITED, scope structure-deletes-day).
228
+ *
229
+ * @example
230
+ * await zs.roomTypes.delete("deluxe"); // by your ref
231
+ * await zs.roomTypes.delete(412); // by ZimmerStack's id
232
+ */
233
+ delete: (idOrRef: number | string, options?: ReadOptions) => Promise<CatalogDeleteResult>;
234
+ };
235
+ readonly ratePlans: {
236
+ /** Every rate plan of the hotel, each with the numeric `id` that prices and stay rules name. */
237
+ list: (options?: ReadOptions) => Promise<Catalog["ratePlans"]>;
238
+ /**
239
+ * Create a rate plan, or change it if you sent this `ref` before. Name its room type by
240
+ * `roomTypeRef` (the ref you gave the room type) or by `roomTypeId`. `defaultRate` is its standing
241
+ * price in major units (4500 = 4,500.00). Needs the scope catalog:write. To send several in one
242
+ * request use `catalog.upsertRatePlans`.
243
+ *
244
+ * @example
245
+ * const plan = await zs.ratePlans.save({ ref: "deluxe-bb", roomTypeRef: "deluxe", name: "Bed and breakfast", mealPlan: "CP", defaultRate: 4500 });
246
+ * plan.id; // use it in rates.set and restrictions.set
247
+ */
248
+ save: (ratePlan: RatePlanInput, options?: WriteOptions) => Promise<StructureSaved>;
249
+ /**
250
+ * Delete a rate plan for good, by its `id` (a number) or by your own `ref` (a string). Needs the
251
+ * scope catalog:write.
252
+ *
253
+ * THERE IS NO UNDO. Call it when a person chose to delete; never from a loop, a timer or a sync job.
254
+ * It is refused with CATALOG_CONFLICT while a booking site still sells the plan: unmap it on the
255
+ * channel first. Deletes have a daily budget per hotel (RATE_LIMITED, scope structure-deletes-day).
256
+ *
257
+ * @example
258
+ * await zs.ratePlans.delete("deluxe-bb"); // by your ref
259
+ * await zs.ratePlans.delete(901); // by ZimmerStack's id
260
+ */
261
+ delete: (idOrRef: number | string, options?: ReadOptions) => Promise<CatalogDeleteResult>;
133
262
  };
134
263
  readonly availability: {
135
264
  /** Rooms left to sell per room type per night, as ZimmerStack's record holds them. Up to 500 days. */
@@ -201,9 +330,9 @@ export declare class ZimmerStack {
201
330
  * Replace a channel's modifier with these steps (`[]` removes it). Needs the scope
202
331
  * channel-modifiers:write.
203
332
  *
204
- * ONE CALL MOVES EVERY PRICE SENT TO THAT CHANNEL FROM THEN ON. Call it when a person saved the
205
- * setting; never from a loop, a timer or a test against a live key. Prices already on the channel
206
- * stay as they are until those nights are sent again (`rates.resend`).
333
+ * ONE CALL MOVES EVERY PRICE ON THAT CHANNEL. Call it when a person saved the setting; never from
334
+ * a loop, a timer or a test against a live key. The channel manager then sends that channel every
335
+ * date again, so prices already on sale move within minutes; no `rates.resend` is needed.
207
336
  */
208
337
  setModifier: (channelId: string, steps: ModifierStep[], options?: WriteOptions) => Promise<ModifierResult>;
209
338
  };
@@ -233,7 +362,7 @@ export declare class ZimmerStack {
233
362
  };
234
363
  readonly directBookings: {
235
364
  /**
236
- * Website bookings, in the webhook's shape (`direct.booking.*`), cancellations included. Scope
365
+ * Website bookings, in the webhook's shape (`direct.booking.*`), cancellations and no-shows included. Scope
237
366
  * `direct-bookings:read`. Follow `nextCursor`, or use `all`.
238
367
  */
239
368
  list: (query?: Op<"GET /direct-bookings">["query"], options?: ReadOptions) => Promise<import("./generated.js").ChannelBookingsList>;
@@ -1,6 +1,13 @@
1
1
  import { ZimmerStackError, ZimmerStackUsageError } from "./errors.js";
2
2
  import { API_ORIGIN, API_PREFIX, IDEMPOTENCY_HEADER, OPERATIONS, PROPERTY_HEADER, SDK_VERSION, } from "./generated.js";
3
3
  import { buildGrid, chunk, toRanges } from "./grid.js";
4
+ /** One entity was sent, so the answer names exactly one. */
5
+ function savedOne(result) {
6
+ const item = result.items[0];
7
+ if (!item)
8
+ throw new Error("ZimmerStack's answer named no entity for this save. Read zs.catalog.get() to see what the hotel holds before sending it again.");
9
+ return { ...item, channelManager: result.channelManager };
10
+ }
4
11
  /* ───────────────────────────── the shared core ───────────────────────────── */
5
12
  /** Requests in flight at once. Writes go one at a time on top of that. */
6
13
  const PARALLEL = 4;
@@ -46,6 +53,20 @@ function resolveBase(baseUrl) {
46
53
  }
47
54
  return url.origin;
48
55
  }
56
+ /**
57
+ * Operations that do a long thing while you wait: adding a hotel creates its account, and removing one takes
58
+ * it off its booking sites one step at a time. One attempt of these is given at least this long, however
59
+ * short `timeoutMs` is, because giving up early leaves you not knowing whether a hotel was added or removed.
60
+ * (The API's own edge answers within 100 s.)
61
+ */
62
+ const PATIENCE_MS = {
63
+ "POST /properties": 95_000,
64
+ "DELETE /properties/{propertyId}": 95_000,
65
+ };
66
+ /** How long one attempt of an operation may take: the client's `timeoutMs`, or longer for the slow ones above. */
67
+ export function attemptTimeoutMs(operation, timeoutMs) {
68
+ return Math.max(timeoutMs, PATIENCE_MS[operation] ?? 0);
69
+ }
49
70
  class Core {
50
71
  #key;
51
72
  mode;
@@ -179,7 +200,7 @@ class Core {
179
200
  let res;
180
201
  let json;
181
202
  try {
182
- const timeout = AbortSignal.timeout(this.#timeoutMs);
203
+ const timeout = AbortSignal.timeout(attemptTimeoutMs(wire.operation, this.#timeoutMs));
183
204
  res = await this.#fetch(wire.url, {
184
205
  method: wire.method,
185
206
  headers: wire.headers,
@@ -334,7 +355,10 @@ export class ZimmerStack {
334
355
  if (value !== undefined && value !== null)
335
356
  url.searchParams.set(name, String(value));
336
357
  const headers = { authorization: this.#core.authorization(), accept: "application/json", "user-agent": `zimmerstack-connect-node/${SDK_VERSION}` };
337
- const hotel = this.propertyId ?? (operation === "GET /properties" ? undefined : this.#core.soleSandboxId);
358
+ // Adding a hotel and removing one name no hotel in the header: the one to add does not exist yet, and the
359
+ // one to remove is in the path. Listing them sends the header only when this client was made for one hotel.
360
+ const aboutTheList = operation === "POST /properties" || operation === "DELETE /properties/{propertyId}";
361
+ const hotel = aboutTheList ? undefined : (this.propertyId ?? (operation === "GET /properties" ? undefined : this.#core.soleSandboxId));
338
362
  if (hotel)
339
363
  headers[PROPERTY_HEADER] = String(hotel);
340
364
  const body = args.body === undefined ? undefined : JSON.stringify(args.body);
@@ -393,7 +417,78 @@ export class ZimmerStack {
393
417
  properties = {
394
418
  /** The hotels this key may act on. A company key names one of them on every other call (`forProperty`). */
395
419
  list: (options) => this.request("GET /properties", options),
420
+ /**
421
+ * Add a hotel. Only a software partner's COMPANY key that holds the scope properties:write can; tick
422
+ * "Also add and remove hotels" when you make the key in the partner portal. A hotel's own key is refused.
423
+ *
424
+ * The answer's `id` is the hotel: act on it with `zs.forProperty(id)`. Its owner gets the sign-in details
425
+ * by email; they are never sent to you. `billing.state` says whether it is on your invoice yet, and
426
+ * `channelManager` turns true with your first `roomTypes.save` or `catalog.upsertRoomTypes` for it.
427
+ *
428
+ * With a test key (zsk_test_) the same call makes a sandbox instead: a practice hotel no booking site
429
+ * sees, never billed. Safe to retry: the same `idempotencyKey` answers with the same hotel and
430
+ * `replay: true`, and never makes a second one.
431
+ *
432
+ * @example
433
+ * const hotel = await zs.properties.create({
434
+ * name: "Sea Breeze Apartments",
435
+ * owner: { name: "Nimal Perera", email: "nimal@seabreeze.example", phone: "+94 77 123 4567" },
436
+ * address: { line1: "12 Beach Road", city: "Galle", country: "LK" },
437
+ * roomTypes: [{ ref: "deluxe", name: "Deluxe Room", roomCount: 6, defaultRate: "90.00" }],
438
+ * });
439
+ * const seaBreeze = zs.forProperty(hotel.id);
440
+ */
441
+ create: async (hotel, options) => {
442
+ const created = await this.request("POST /properties", { body: hotel, ...options });
443
+ this.#forgetWhichHotels();
444
+ return created;
445
+ },
446
+ /**
447
+ * Remove a hotel YOU ADDED, for good. A company key with the scope properties:write.
448
+ *
449
+ * One call does what ZimmerStack does when a hotel's service ends, in this order: its booking sites
450
+ * are disconnected, its rate plans are removed from the channel manager, then its room types, then the
451
+ * hotel is closed (its owner can no longer sign in, and no key reaches it). It comes off your invoice
452
+ * from the next 1st; the month already billed is not refunded. Bookings already made stay with the
453
+ * booking sites and the hotel.
454
+ *
455
+ * THERE IS NO UNDO. Call it when a person chose to remove that hotel; never from a loop, a timer or a
456
+ * sync job. `confirm` is the hotel's exact name, as `zs.properties.list()` prints it, so a wrong id never
457
+ * removes a hotel. Move the hotel's booking sites to its next channel manager first, so it keeps selling.
458
+ *
459
+ * The answer: `channelManager.state` is REMOVED when nothing is left on the channel manager, or
460
+ * RETRYING when the hotel is closed and off your bill but one step there is still finishing (ZimmerStack
461
+ * retries it; you do nothing). Calling it again later answers `replay: true`. A hotel you did not add,
462
+ * or one that uses more than the channel manager, is refused with PROPERTY_NOT_REMOVABLE and who can do
463
+ * it. With a test key it deletes a sandbox.
464
+ *
465
+ * @example
466
+ * const { properties } = await zs.properties.list();
467
+ * const hotel = properties.find((p) => p.id === 61);
468
+ * if (hotel) await zs.properties.delete(hotel.id, { confirm: hotel.name });
469
+ */
470
+ delete: (propertyId, options) => this.#removeProperty(propertyId, options),
471
+ /** The same as `delete`, under the word the partner portal uses ("Remove hotel"). */
472
+ remove: (propertyId, options) => this.#removeProperty(propertyId, options),
396
473
  };
474
+ async #removeProperty(propertyId, options) {
475
+ if (!Number.isInteger(propertyId) || propertyId <= 0) {
476
+ throw new ZimmerStackUsageError("zs.properties.delete needs the hotel's numeric id (zs.properties.list() names them)");
477
+ }
478
+ const confirm = typeof options?.confirm === "string" ? options.confirm.trim() : "";
479
+ if (!confirm) {
480
+ throw new ZimmerStackUsageError("zs.properties.delete needs { confirm: <the hotel's exact name> }, as zs.properties.list() prints it. Removing a hotel cannot be undone, so the name is asked for.");
481
+ }
482
+ const removed = await this.request("DELETE /properties/{propertyId}", { path: { propertyId }, query: { confirm }, signal: options.signal });
483
+ this.#core.catalogs.delete(propertyId);
484
+ this.#forgetWhichHotels();
485
+ return removed;
486
+ }
487
+ /** The hotels this key reaches just changed: the one sandbox a test key was assumed to act on is looked up afresh. */
488
+ #forgetWhichHotels() {
489
+ this.#core.soleSandboxProperty = undefined;
490
+ this.#core.soleSandboxId = undefined;
491
+ }
397
492
  property = {
398
493
  /** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
399
494
  get: (options) => this.request("GET /property", options),
@@ -412,8 +507,90 @@ export class ZimmerStack {
412
507
  deleteRoomType: (roomTypeId, options) => this.#structure("DELETE /catalog/room-types/{roomTypeId}", { path: { roomTypeId }, ...options }),
413
508
  /** Create or change rate plans by your own `ref`. */
414
509
  upsertRatePlans: (body, options) => this.#structure("PUT /catalog/rate-plans", { body, ...options }),
510
+ /** Delete a rate plan. Refused while a channel still sells it. */
415
511
  deleteRatePlan: (ratePlanId, options) => this.#structure("DELETE /catalog/rate-plans/{ratePlanId}", { path: { ratePlanId }, ...options }),
416
512
  };
513
+ /* ── the same room types and rate plans, one at a time, under the names you would look for ── */
514
+ roomTypes = {
515
+ /** Every room type of the hotel, each with the numeric `id` that room counts and bookings name. */
516
+ list: async (options) => (await this.catalog.get(options)).roomTypes,
517
+ /**
518
+ * Create a room type, or change it if you sent this `ref` before. `ref` is your own id for it; the
519
+ * answer's `id` is ZimmerStack's, the one every later call names. Needs the scope catalog:write.
520
+ * To send several in one request use `catalog.upsertRoomTypes`.
521
+ *
522
+ * @example
523
+ * const room = await zs.roomTypes.save({ ref: "deluxe", name: "Deluxe Room", roomCount: 8, adults: 2 });
524
+ * room.id; // use it in availability.set and in a rate plan's roomTypeId
525
+ */
526
+ save: async (roomType, options) => savedOne(await this.catalog.upsertRoomTypes({ roomTypes: [roomType] }, options)),
527
+ /**
528
+ * Delete a room type for good, by its `id` (a number) or by your own `ref` (a string). Its rate
529
+ * plans are deleted with it; the answer's `deletedRatePlanIds` names them. Needs the scope
530
+ * catalog:write.
531
+ *
532
+ * THERE IS NO UNDO. Call it when a person chose to delete; never from a loop, a timer or a sync job.
533
+ * It is refused while a booking site still sells one of its rate plans (unmap the plan on the
534
+ * channel first), while an upcoming stay holds one of its rooms, or while rooms are still assigned
535
+ * to it on a hotel that runs the ZimmerStack PMS: CATALOG_CONFLICT, or CHANNEL_MANAGER_ERROR when
536
+ * the refusal is the channel manager's. Show the message; nothing was deleted. Deletes have a daily
537
+ * budget per hotel (RATE_LIMITED, scope structure-deletes-day).
538
+ *
539
+ * @example
540
+ * await zs.roomTypes.delete("deluxe"); // by your ref
541
+ * await zs.roomTypes.delete(412); // by ZimmerStack's id
542
+ */
543
+ delete: async (idOrRef, options) => this.catalog.deleteRoomType(await this.#structureId("roomTypes", idOrRef, options?.signal), options),
544
+ };
545
+ ratePlans = {
546
+ /** Every rate plan of the hotel, each with the numeric `id` that prices and stay rules name. */
547
+ list: async (options) => (await this.catalog.get(options)).ratePlans,
548
+ /**
549
+ * Create a rate plan, or change it if you sent this `ref` before. Name its room type by
550
+ * `roomTypeRef` (the ref you gave the room type) or by `roomTypeId`. `defaultRate` is its standing
551
+ * price in major units (4500 = 4,500.00). Needs the scope catalog:write. To send several in one
552
+ * request use `catalog.upsertRatePlans`.
553
+ *
554
+ * @example
555
+ * const plan = await zs.ratePlans.save({ ref: "deluxe-bb", roomTypeRef: "deluxe", name: "Bed and breakfast", mealPlan: "CP", defaultRate: 4500 });
556
+ * plan.id; // use it in rates.set and restrictions.set
557
+ */
558
+ save: async (ratePlan, options) => savedOne(await this.catalog.upsertRatePlans({ ratePlans: [ratePlan] }, options)),
559
+ /**
560
+ * Delete a rate plan for good, by its `id` (a number) or by your own `ref` (a string). Needs the
561
+ * scope catalog:write.
562
+ *
563
+ * THERE IS NO UNDO. Call it when a person chose to delete; never from a loop, a timer or a sync job.
564
+ * It is refused with CATALOG_CONFLICT while a booking site still sells the plan: unmap it on the
565
+ * channel first. Deletes have a daily budget per hotel (RATE_LIMITED, scope structure-deletes-day).
566
+ *
567
+ * @example
568
+ * await zs.ratePlans.delete("deluxe-bb"); // by your ref
569
+ * await zs.ratePlans.delete(901); // by ZimmerStack's id
570
+ */
571
+ delete: async (idOrRef, options) => this.catalog.deleteRatePlan(await this.#structureId("ratePlans", idOrRef, options?.signal), options),
572
+ };
573
+ /**
574
+ * The id a delete acts on. A number is ZimmerStack's id already. A string is your own `ref`: it is
575
+ * looked up in a fresh read of the catalog, never a kept copy, because a delete must act on what
576
+ * exists now.
577
+ */
578
+ async #structureId(kind, idOrRef, signal) {
579
+ const what = kind === "roomTypes" ? "room type" : "rate plan";
580
+ if (typeof idOrRef === "number") {
581
+ if (!Number.isInteger(idOrRef) || idOrRef <= 0)
582
+ throw new ZimmerStackUsageError(`A ${what}'s id is a whole number above 0; zs.${kind}.list() names them`);
583
+ return idOrRef;
584
+ }
585
+ if (typeof idOrRef !== "string" || idOrRef.trim() === "") {
586
+ throw new ZimmerStackUsageError(`zs.${kind}.delete takes the ${what}'s id (a number) or your own ref for it (a string)`);
587
+ }
588
+ const hit = (await this.catalog.get({ signal }))[kind].find((entity) => entity.ref === idOrRef);
589
+ if (!hit) {
590
+ throw new ZimmerStackUsageError(`This hotel has no ${what} with the ref "${idOrRef}". zs.${kind}.list() names every one with its id and ref; a ${what} made on ZimmerStack's own screens has no ref, so delete it by its id.`);
591
+ }
592
+ return hit.id;
593
+ }
417
594
  async #structure(operation, args) {
418
595
  try {
419
596
  return await this.request(operation, ...[args]);
@@ -516,9 +693,9 @@ export class ZimmerStack {
516
693
  * Replace a channel's modifier with these steps (`[]` removes it). Needs the scope
517
694
  * channel-modifiers:write.
518
695
  *
519
- * ONE CALL MOVES EVERY PRICE SENT TO THAT CHANNEL FROM THEN ON. Call it when a person saved the
520
- * setting; never from a loop, a timer or a test against a live key. Prices already on the channel
521
- * stay as they are until those nights are sent again (`rates.resend`).
696
+ * ONE CALL MOVES EVERY PRICE ON THAT CHANNEL. Call it when a person saved the setting; never from
697
+ * a loop, a timer or a test against a live key. The channel manager then sends that channel every
698
+ * date again, so prices already on sale move within minutes; no `rates.resend` is needed.
522
699
  */
523
700
  setModifier: (channelId, steps, options) => this.request("PUT /channels/{channelId}/modifier", { path: { channelId }, body: { steps }, ...options }),
524
701
  };
@@ -551,7 +728,7 @@ export class ZimmerStack {
551
728
  /* ── bookings guests made on the hotel's own website (our booking engine) ── */
552
729
  directBookings = {
553
730
  /**
554
- * Website bookings, in the webhook's shape (`direct.booking.*`), cancellations included. Scope
731
+ * Website bookings, in the webhook's shape (`direct.booking.*`), cancellations and no-shows included. Scope
555
732
  * `direct-bookings:read`. Follow `nextCursor`, or use `all`.
556
733
  */
557
734
  list: (query, options) => this.request("GET /direct-bookings", { query, ...options }),