@mwam/sdk 0.0.0-stage → 0.4.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.
- package/README.md +191 -2
- package/dist/index.d.ts +2351 -0
- package/dist/index.js +873 -0
- package/package.json +42 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,873 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
// ../schemas/src/content/nodes.ts
|
|
4
|
+
var noNul = (s) => !s.includes("\0");
|
|
5
|
+
var NUL_ISSUE = { message: "must not contain the NUL character (U+0000)" };
|
|
6
|
+
var storableString = () => z.string().refine(noNul, NUL_ISSUE);
|
|
7
|
+
|
|
8
|
+
// ../schemas/src/content/nodes.ts
|
|
9
|
+
var markSchema = z.discriminatedUnion("type", [
|
|
10
|
+
z.object({ type: z.literal("bold") }),
|
|
11
|
+
z.object({ type: z.literal("italic") }),
|
|
12
|
+
z.object({ type: z.literal("underline") }),
|
|
13
|
+
z.object({ type: z.literal("strike") }),
|
|
14
|
+
z.object({ type: z.literal("link"), attrs: z.object({ href: storableString() }) })
|
|
15
|
+
]);
|
|
16
|
+
var textNode = z.object({
|
|
17
|
+
type: z.literal("text"),
|
|
18
|
+
text: storableString(),
|
|
19
|
+
marks: z.array(markSchema).optional()
|
|
20
|
+
});
|
|
21
|
+
var imageRef = z.object({ assetId: storableString(), alt: storableString().nullable() });
|
|
22
|
+
var ALIGNMENTS = ["small", "medium", "normal", "wide", "full"];
|
|
23
|
+
var TEXT_ALIGNMENTS = ["center", "right"];
|
|
24
|
+
var textAlign = z.enum(TEXT_ALIGNMENTS).nullable().optional();
|
|
25
|
+
var imageBlock = imageRef.extend({
|
|
26
|
+
caption: storableString().nullable().optional(),
|
|
27
|
+
align: z.enum(ALIGNMENTS).optional()
|
|
28
|
+
});
|
|
29
|
+
var nodeSchema = z.lazy(
|
|
30
|
+
() => z.discriminatedUnion("type", [
|
|
31
|
+
textNode,
|
|
32
|
+
// attrs OPTIONAL on a paragraph: every paragraph stored before alignment existed has none.
|
|
33
|
+
z.object({ type: z.literal("paragraph"), attrs: z.object({ textAlign }).optional(), content: z.array(nodeSchema).optional() }),
|
|
34
|
+
z.object({ type: z.literal("heading"), attrs: z.object({ level: z.union([z.literal(2), z.literal(3), z.literal(4)]), textAlign }), content: z.array(nodeSchema).optional() }),
|
|
35
|
+
z.object({ type: z.literal("blockquote"), content: z.array(nodeSchema).optional() }),
|
|
36
|
+
z.object({ type: z.literal("bulletList"), content: z.array(nodeSchema).optional() }),
|
|
37
|
+
z.object({ type: z.literal("orderedList"), content: z.array(nodeSchema).optional() }),
|
|
38
|
+
z.object({ type: z.literal("horizontalRule") }),
|
|
39
|
+
z.object({ type: z.literal("listItem"), content: z.array(nodeSchema).optional() }),
|
|
40
|
+
z.object({ type: z.literal("image"), attrs: imageBlock }),
|
|
41
|
+
z.object({ type: z.literal("beforeAfter"), attrs: z.object({ before: imageRef, after: imageRef, caption: storableString().nullable() }) }),
|
|
42
|
+
z.object({ type: z.literal("eventCard"), attrs: z.object({ eventId: storableString() }) })
|
|
43
|
+
])
|
|
44
|
+
);
|
|
45
|
+
var MAX_DEPTH = 100;
|
|
46
|
+
var MAX_NODES = 5e4;
|
|
47
|
+
function outOfBounds(value) {
|
|
48
|
+
if (typeof value !== "object" || value === null) return null;
|
|
49
|
+
const root = value.content;
|
|
50
|
+
const stack = [{ list: root, depth: 1 }];
|
|
51
|
+
let count = 0;
|
|
52
|
+
while (stack.length > 0) {
|
|
53
|
+
const item = stack.pop();
|
|
54
|
+
if (item === void 0 || !Array.isArray(item.list)) continue;
|
|
55
|
+
if (item.depth > MAX_DEPTH) return `document nesting exceeds ${MAX_DEPTH} levels`;
|
|
56
|
+
count += item.list.length;
|
|
57
|
+
if (count > MAX_NODES) return `document has more than ${MAX_NODES} nodes and marks`;
|
|
58
|
+
for (const child of item.list) {
|
|
59
|
+
if (typeof child === "object" && child !== null) {
|
|
60
|
+
const marks = child.marks;
|
|
61
|
+
if (Array.isArray(marks)) {
|
|
62
|
+
count += marks.length;
|
|
63
|
+
if (count > MAX_NODES) return `document has more than ${MAX_NODES} nodes and marks`;
|
|
64
|
+
}
|
|
65
|
+
stack.push({ list: child.content, depth: item.depth + 1 });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
var docShape = z.object({
|
|
72
|
+
type: z.literal("doc"),
|
|
73
|
+
content: z.array(nodeSchema)
|
|
74
|
+
});
|
|
75
|
+
var docSchema = z.unknown().superRefine((value, ctx) => {
|
|
76
|
+
const refused = outOfBounds(value);
|
|
77
|
+
if (refused !== null) ctx.addIssue({ code: z.ZodIssueCode.custom, message: refused });
|
|
78
|
+
}).pipe(docShape);
|
|
79
|
+
var objectBody = { required_error: "A JSON object body is required", invalid_type_error: "The body must be a JSON object" };
|
|
80
|
+
var EVENT_CATEGORIES = ["MEDITATION", "RETREAT", "DHAMMA_CLASS", "CEREMONY", "OTHER"];
|
|
81
|
+
var ATTENDANCE_MODES = ["OFFLINE", "ONLINE", "MIXED"];
|
|
82
|
+
var EVENT_STATUSES = ["DRAFT", "IN_REVIEW", "PUBLISHED", "ARCHIVED"];
|
|
83
|
+
var SESSION_STATUSES = ["SCHEDULED", "CANCELLED", "POSTPONED", "RESCHEDULED", "MOVED_ONLINE"];
|
|
84
|
+
var REGISTRATION_MODES = ["NONE", "EXTERNAL", "OURS"];
|
|
85
|
+
var eventCategorySchema = z.enum(EVENT_CATEGORIES);
|
|
86
|
+
var attendanceModeSchema = z.enum(ATTENDANCE_MODES);
|
|
87
|
+
z.enum(EVENT_STATUSES);
|
|
88
|
+
var sessionStatusSchema = z.enum(SESSION_STATUSES);
|
|
89
|
+
var registrationModeSchema = z.enum(REGISTRATION_MODES);
|
|
90
|
+
var EVENT_TITLE_MAX = 200;
|
|
91
|
+
var EVENT_SUMMARY_MAX = 500;
|
|
92
|
+
var SEGMENT_LABEL_MAX = 120;
|
|
93
|
+
var SESSION_MAX_MINUTES = 24 * 60;
|
|
94
|
+
var text = (max) => z.string().trim().max(max).refine(noNul, NUL_ISSUE);
|
|
95
|
+
var eventSlugSchema = z.string().min(1).max(120).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use lowercase letters, numbers and single hyphens");
|
|
96
|
+
var eventTitleSchema = z.string().trim().min(1).max(EVENT_TITLE_MAX).refine(noNul, NUL_ISSUE);
|
|
97
|
+
var eventSummarySchema = z.string().trim().max(EVENT_SUMMARY_MAX).refine(noNul, NUL_ISSUE);
|
|
98
|
+
var timezoneSchema = z.string().min(1).max(64).refine((tz) => {
|
|
99
|
+
if (tz !== "UTC" && !tz.includes("/")) return false;
|
|
100
|
+
try {
|
|
101
|
+
new Intl.DateTimeFormat("en-CA", { timeZone: tz });
|
|
102
|
+
return true;
|
|
103
|
+
} catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}, "Use a Region/City time zone, such as America/Winnipeg \u2014 not a fixed offset like EST");
|
|
107
|
+
var instantSchema = z.string().datetime({ offset: true });
|
|
108
|
+
var priceCentsSchema = z.number().int().min(0).max(1e8);
|
|
109
|
+
var currencySchema = z.string().regex(/^[A-Z]{3}$/, "Use a three-letter currency code, such as USD");
|
|
110
|
+
var segmentInput = z.object({
|
|
111
|
+
/** Minutes from the session's start, never a clock time — see the table's own comment. */
|
|
112
|
+
startsMinute: z.number().int().min(0).max(SESSION_MAX_MINUTES),
|
|
113
|
+
endsMinute: z.number().int().min(0).max(SESSION_MAX_MINUTES),
|
|
114
|
+
label: text(SEGMENT_LABEL_MAX).refine((v) => v.length > 0, "A segment needs a label")
|
|
115
|
+
}, objectBody).strict().refine((s) => s.endsMinute > s.startsMinute, {
|
|
116
|
+
message: "A segment has to end after it starts",
|
|
117
|
+
path: ["endsMinute"]
|
|
118
|
+
});
|
|
119
|
+
var placeFields = {
|
|
120
|
+
venueName: text(200).nullable().optional(),
|
|
121
|
+
streetAddress: text(200).nullable().optional(),
|
|
122
|
+
locality: text(120).nullable().optional(),
|
|
123
|
+
region: text(120).nullable().optional(),
|
|
124
|
+
postalCode: text(20).nullable().optional(),
|
|
125
|
+
country: z.string().regex(/^[A-Z]{2}$/, "Use a two-letter country code, such as US").nullable().optional(),
|
|
126
|
+
onlineUrl: z.string().url().max(2e3).nullable().optional()
|
|
127
|
+
};
|
|
128
|
+
z.object(placeFields, objectBody).strict();
|
|
129
|
+
var sessionInput = z.object({
|
|
130
|
+
...placeFields,
|
|
131
|
+
startsAt: instantSchema,
|
|
132
|
+
endsAt: instantSchema,
|
|
133
|
+
status: sessionStatusSchema.optional(),
|
|
134
|
+
/** Said out loud when a date is called off, rather than letting it vanish from the list. */
|
|
135
|
+
statusNote: text(300).nullable().optional(),
|
|
136
|
+
/** Null is unlimited, which is not zero — and zero is a real answer meaning full. */
|
|
137
|
+
capacity: z.number().int().min(0).max(1e6).nullable().optional()
|
|
138
|
+
}, objectBody).strict().refine((s) => Date.parse(s.endsAt) > Date.parse(s.startsAt), {
|
|
139
|
+
message: "A session has to end after it starts",
|
|
140
|
+
path: ["endsAt"]
|
|
141
|
+
});
|
|
142
|
+
var tellSchema = z.array(z.string().min(1).max(64)).max(1e3);
|
|
143
|
+
z.object({
|
|
144
|
+
statusNote: text(300).nullable().optional(),
|
|
145
|
+
tell: tellSchema.optional()
|
|
146
|
+
}, objectBody).strict();
|
|
147
|
+
sessionInput.innerType().partial().extend({ tell: tellSchema.optional() }).strict();
|
|
148
|
+
z.object({ tell: tellSchema.optional() }, objectBody).strict();
|
|
149
|
+
z.object({ tell: z.boolean() }, objectBody).strict();
|
|
150
|
+
var onlineViaSchema = z.enum(["LINK", "ZOOM"]);
|
|
151
|
+
var signUpModeSchema = z.enum(["EACH_DATE", "ALL_DATES"]);
|
|
152
|
+
var eventPricingSchema = z.enum(["FREE", "DONATION"]);
|
|
153
|
+
var eventCapacitySchema = z.number().int().min(1).max(1e6).nullable();
|
|
154
|
+
z.object({ sessions: z.array(sessionInput).min(1).max(100) }, objectBody).strict();
|
|
155
|
+
var eventFields = {
|
|
156
|
+
slug: eventSlugSchema,
|
|
157
|
+
title: eventTitleSchema,
|
|
158
|
+
summary: eventSummarySchema.nullable().optional(),
|
|
159
|
+
bodyJson: docSchema,
|
|
160
|
+
seriesId: z.string().min(1).max(64).nullable().optional(),
|
|
161
|
+
coverAssetId: z.string().min(1).max(64).nullable().optional(),
|
|
162
|
+
category: eventCategorySchema.optional(),
|
|
163
|
+
attendance: attendanceModeSchema.optional(),
|
|
164
|
+
/** LINK: each date's own published link. ZOOM: a meeting per date in the monastery's Zoom. */
|
|
165
|
+
onlineVia: onlineViaSchema.optional(),
|
|
166
|
+
timezone: timezoneSchema,
|
|
167
|
+
/** Display only — the badge reading "MONTHLY". The dates that exist are the sessions. */
|
|
168
|
+
recurrenceLabel: text(60).nullable().optional(),
|
|
169
|
+
teacherName: text(200).nullable().optional(),
|
|
170
|
+
teacherBio: text(2e3).nullable().optional(),
|
|
171
|
+
whatToBring: text(2e3).nullable().optional(),
|
|
172
|
+
priceCents: priceCentsSchema.optional(),
|
|
173
|
+
priceCurrency: currencySchema.optional(),
|
|
174
|
+
registration: registrationModeSchema.optional(),
|
|
175
|
+
externalRegistrationUrl: z.string().url().max(2e3).nullable().optional(),
|
|
176
|
+
signUp: signUpModeSchema.optional(),
|
|
177
|
+
capacity: eventCapacitySchema.optional(),
|
|
178
|
+
pricing: eventPricingSchema.optional(),
|
|
179
|
+
/** Where a DONATION event's amount starts; null starts at the least. */
|
|
180
|
+
suggestedCents: priceCentsSchema.nullable().optional()
|
|
181
|
+
};
|
|
182
|
+
var registrationIsReachable = (v) => v.registration !== "EXTERNAL" || (v.externalRegistrationUrl ?? "") !== "";
|
|
183
|
+
var REGISTRATION_ISSUE = {
|
|
184
|
+
message: "An event that registers somewhere else needs the address people go to",
|
|
185
|
+
path: ["externalRegistrationUrl"]
|
|
186
|
+
};
|
|
187
|
+
z.object(eventFields, objectBody).strict().refine(registrationIsReachable, REGISTRATION_ISSUE);
|
|
188
|
+
z.object({
|
|
189
|
+
slug: eventSlugSchema.optional(),
|
|
190
|
+
title: eventTitleSchema.optional(),
|
|
191
|
+
summary: eventSummarySchema.nullable().optional(),
|
|
192
|
+
bodyJson: docSchema.optional(),
|
|
193
|
+
seriesId: z.string().min(1).max(64).nullable().optional(),
|
|
194
|
+
coverAssetId: z.string().min(1).max(64).nullable().optional(),
|
|
195
|
+
category: eventCategorySchema.optional(),
|
|
196
|
+
attendance: attendanceModeSchema.optional(),
|
|
197
|
+
/** LINK: each date's own published link. ZOOM: a meeting per date in the monastery's Zoom. */
|
|
198
|
+
onlineVia: onlineViaSchema.optional(),
|
|
199
|
+
timezone: timezoneSchema.optional(),
|
|
200
|
+
recurrenceLabel: text(60).nullable().optional(),
|
|
201
|
+
teacherName: text(200).nullable().optional(),
|
|
202
|
+
teacherBio: text(2e3).nullable().optional(),
|
|
203
|
+
whatToBring: text(2e3).nullable().optional(),
|
|
204
|
+
priceCents: priceCentsSchema.optional(),
|
|
205
|
+
priceCurrency: currencySchema.optional(),
|
|
206
|
+
registration: registrationModeSchema.optional(),
|
|
207
|
+
externalRegistrationUrl: z.string().url().max(2e3).nullable().optional(),
|
|
208
|
+
signUp: signUpModeSchema.optional(),
|
|
209
|
+
capacity: eventCapacitySchema.optional(),
|
|
210
|
+
pricing: eventPricingSchema.optional(),
|
|
211
|
+
/** Where a DONATION event's amount starts; null starts at the least. */
|
|
212
|
+
suggestedCents: priceCentsSchema.nullable().optional(),
|
|
213
|
+
/** The whole running order at once: a list is a set, not a delta. Omitted leaves it alone. */
|
|
214
|
+
segments: z.array(segmentInput).max(50).optional(),
|
|
215
|
+
/**
|
|
216
|
+
* The `updatedAt` this edit was made against, passed back exactly as the API gave it.
|
|
217
|
+
* Optional, as on a post: without it a PATCH is last-write-wins; with it, the write is
|
|
218
|
+
* refused (409, `details.currentUpdatedAt`) unless the event is still at that revision.
|
|
219
|
+
* The CRM's autosave always sends it, because two people can have one event open.
|
|
220
|
+
*/
|
|
221
|
+
expectedUpdatedAt: z.string().datetime().optional()
|
|
222
|
+
}, objectBody).strict("`status` is not changed here: publishing is a transition with its own route").refine(registrationIsReachable, REGISTRATION_ISSUE);
|
|
223
|
+
z.object({
|
|
224
|
+
slug: eventSlugSchema,
|
|
225
|
+
name: eventTitleSchema,
|
|
226
|
+
summary: eventSummarySchema.nullable().optional()
|
|
227
|
+
}, objectBody).strict();
|
|
228
|
+
z.object({
|
|
229
|
+
slug: eventSlugSchema.optional(),
|
|
230
|
+
name: eventTitleSchema.optional(),
|
|
231
|
+
summary: eventSummarySchema.nullable().optional()
|
|
232
|
+
}, objectBody).strict();
|
|
233
|
+
var objectBody2 = { required_error: "A JSON object body is required", invalid_type_error: "The body must be a JSON object" };
|
|
234
|
+
var GALLERY_STATUSES = ["DRAFT", "IN_REVIEW", "PUBLISHED", "ARCHIVED"];
|
|
235
|
+
z.enum(GALLERY_STATUSES);
|
|
236
|
+
var GALLERY_MAX_PICTURES = 300;
|
|
237
|
+
var id = z.string().min(1).max(64);
|
|
238
|
+
var caption = z.string().trim().max(500).refine(noNul, NUL_ISSUE);
|
|
239
|
+
var galleryItemInput = z.object({
|
|
240
|
+
assetId: id,
|
|
241
|
+
caption: caption.nullable().optional()
|
|
242
|
+
}).strict();
|
|
243
|
+
z.object({
|
|
244
|
+
slug: eventSlugSchema,
|
|
245
|
+
title: eventTitleSchema,
|
|
246
|
+
summary: eventSummarySchema.nullable().optional(),
|
|
247
|
+
eventId: id.nullable().optional()
|
|
248
|
+
}, objectBody2).strict();
|
|
249
|
+
z.object({
|
|
250
|
+
slug: eventSlugSchema.optional(),
|
|
251
|
+
title: eventTitleSchema.optional(),
|
|
252
|
+
summary: eventSummarySchema.nullable().optional(),
|
|
253
|
+
eventId: id.nullable().optional(),
|
|
254
|
+
coverAssetId: id.nullable().optional(),
|
|
255
|
+
items: z.array(galleryItemInput).max(GALLERY_MAX_PICTURES, `A gallery holds at most ${String(GALLERY_MAX_PICTURES)} pictures`).optional()
|
|
256
|
+
}, objectBody2).strict("`status` is not changed here: publishing is a transition with its own route");
|
|
257
|
+
var publicPictureSchema = z.object({
|
|
258
|
+
url: z.string(),
|
|
259
|
+
alt: z.string(),
|
|
260
|
+
caption: z.string().nullable(),
|
|
261
|
+
width: z.number().int(),
|
|
262
|
+
height: z.number().int()
|
|
263
|
+
});
|
|
264
|
+
var publicGallerySummarySchema = z.object({
|
|
265
|
+
slug: z.string(),
|
|
266
|
+
title: z.string(),
|
|
267
|
+
summary: z.string().nullable(),
|
|
268
|
+
/** The chosen cover, or the first picture. */
|
|
269
|
+
cover: publicPictureSchema.nullable(),
|
|
270
|
+
pictureCount: z.number().int(),
|
|
271
|
+
publishedAt: z.string().nullable()
|
|
272
|
+
});
|
|
273
|
+
var publicGallerySchema = publicGallerySummarySchema.extend({
|
|
274
|
+
pictures: z.array(publicPictureSchema),
|
|
275
|
+
/** The occasion, while its event is itself on the site. */
|
|
276
|
+
event: z.object({ slug: z.string(), title: z.string() }).nullable()
|
|
277
|
+
});
|
|
278
|
+
var publicGalleryListSchema = z.object({ galleries: z.array(publicGallerySummarySchema) });
|
|
279
|
+
var POST_BODY_FORMATS = ["html", "json", "text"];
|
|
280
|
+
var publicPostSourceSchema = z.object({
|
|
281
|
+
org: z.string(),
|
|
282
|
+
author: z.string().nullable()
|
|
283
|
+
});
|
|
284
|
+
var publicCoverSchema = publicPictureSchema.omit({ caption: true });
|
|
285
|
+
var publicCategorySchema = z.object({ slug: z.string(), name: z.string() });
|
|
286
|
+
var publicPostSummarySchema = z.object({
|
|
287
|
+
slug: z.string(),
|
|
288
|
+
title: z.string(),
|
|
289
|
+
summary: z.string().nullable(),
|
|
290
|
+
publishedAt: z.string().datetime().nullable(),
|
|
291
|
+
cover: publicCoverSchema.nullable(),
|
|
292
|
+
category: publicCategorySchema.nullable(),
|
|
293
|
+
source: publicPostSourceSchema.optional()
|
|
294
|
+
});
|
|
295
|
+
var publicPostBodySchema = z.object({
|
|
296
|
+
html: z.string().optional(),
|
|
297
|
+
json: z.unknown().optional(),
|
|
298
|
+
text: z.string().optional()
|
|
299
|
+
});
|
|
300
|
+
var publicPostSchema = publicPostSummarySchema.extend({ body: publicPostBodySchema });
|
|
301
|
+
var publicPostListSchema = z.object({
|
|
302
|
+
posts: z.array(publicPostSummarySchema),
|
|
303
|
+
page: z.number().int(),
|
|
304
|
+
pageCount: z.number().int(),
|
|
305
|
+
total: z.number().int()
|
|
306
|
+
});
|
|
307
|
+
var publicCategoryListSchema = z.object({
|
|
308
|
+
categories: z.array(publicCategorySchema.extend({ postCount: z.number().int() }))
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// ../schemas/src/event-public.ts
|
|
312
|
+
var publicPlaceSchema = z.object({
|
|
313
|
+
name: z.string().nullable(),
|
|
314
|
+
streetAddress: z.string().nullable(),
|
|
315
|
+
locality: z.string().nullable(),
|
|
316
|
+
region: z.string().nullable(),
|
|
317
|
+
postalCode: z.string().nullable(),
|
|
318
|
+
country: z.string().nullable(),
|
|
319
|
+
onlineUrl: z.string().nullable()
|
|
320
|
+
});
|
|
321
|
+
var publicSessionSchema = z.object({
|
|
322
|
+
id: z.string(),
|
|
323
|
+
/**
|
|
324
|
+
* ISO 8601 **with the event's offset**: `2026-11-19T18:30:00-05:00`.
|
|
325
|
+
*
|
|
326
|
+
* One field, not two, and that is the point. `new Date(…)` of it is the right instant, and
|
|
327
|
+
* copying it into JSON-LD's `startDate` is the right local time with the right offset. A
|
|
328
|
+
* bare `…Z` would be correct and useless — every consumer would have to re-derive the
|
|
329
|
+
* offset, and deriving it is exactly where this goes wrong.
|
|
330
|
+
*/
|
|
331
|
+
startsAt: z.string(),
|
|
332
|
+
endsAt: z.string(),
|
|
333
|
+
status: sessionStatusSchema,
|
|
334
|
+
statusNote: z.string().nullable(),
|
|
335
|
+
place: publicPlaceSchema,
|
|
336
|
+
capacity: z.number().int().nullable(),
|
|
337
|
+
/**
|
|
338
|
+
* Seats still free, or null when the date takes everybody. With `capacity` it is what
|
|
339
|
+
* "8 of 100 registered" is made of — and it is the only number here that changes between
|
|
340
|
+
* one request and the next, which is why the list carries a short cache and an ETag.
|
|
341
|
+
*/
|
|
342
|
+
seatsLeft: z.number().int().nullable()
|
|
343
|
+
});
|
|
344
|
+
var publicSeriesRefSchema = z.object({ slug: z.string(), name: z.string() });
|
|
345
|
+
var publicEventSummarySchema = z.object({
|
|
346
|
+
slug: z.string(),
|
|
347
|
+
title: z.string(),
|
|
348
|
+
summary: z.string().nullable(),
|
|
349
|
+
category: eventCategorySchema,
|
|
350
|
+
attendance: attendanceModeSchema,
|
|
351
|
+
timezone: z.string(),
|
|
352
|
+
recurrenceLabel: z.string().nullable(),
|
|
353
|
+
priceCents: z.number().int(),
|
|
354
|
+
priceCurrency: z.string(),
|
|
355
|
+
registration: registrationModeSchema,
|
|
356
|
+
/**
|
|
357
|
+
* EACH_DATE: a place is booked a date at a time. ALL_DATES: people sign up once for every date
|
|
358
|
+
* (`signUp` in the SDK), and each date's `capacity` and `seatsLeft` are the event's.
|
|
359
|
+
*/
|
|
360
|
+
signUp: z.enum(["EACH_DATE", "ALL_DATES"]).default("EACH_DATE"),
|
|
361
|
+
/**
|
|
362
|
+
* DONATION: booking a date takes a donation by card of at least `priceCents` a place —
|
|
363
|
+
* `register` with `card` and `amountCents`, the card box started with what `giving()`
|
|
364
|
+
* answers as `card`. FREE: nothing is taken, whatever `priceCents` shows.
|
|
365
|
+
*/
|
|
366
|
+
pricing: z.enum(["FREE", "DONATION"]).default("FREE"),
|
|
367
|
+
/** Where a DONATION's amount starts; null starts at `priceCents`. */
|
|
368
|
+
suggestedCents: z.number().int().nullable().default(null),
|
|
369
|
+
/** Where registering happens when `registration` is EXTERNAL. Null otherwise. */
|
|
370
|
+
registrationUrl: z.string().nullable(),
|
|
371
|
+
series: publicSeriesRefSchema.nullable(),
|
|
372
|
+
/**
|
|
373
|
+
* The picture a schedule shows beside the event and its page above it, null when none was
|
|
374
|
+
* chosen. The same shape as a post's: `url` absolute, `alt` "" when it has no description.
|
|
375
|
+
*/
|
|
376
|
+
cover: publicCoverSchema.nullable()
|
|
377
|
+
});
|
|
378
|
+
var publicSessionRowSchema = publicSessionSchema.extend({ event: publicEventSummarySchema });
|
|
379
|
+
var publicSessionListSchema = z.object({ sessions: z.array(publicSessionRowSchema) });
|
|
380
|
+
var publicEventGallerySchema = publicGallerySchema.omit({ event: true });
|
|
381
|
+
var publicEventDetailSchema = publicEventSummarySchema.extend({
|
|
382
|
+
bodyHtml: z.string(),
|
|
383
|
+
teacherName: z.string().nullable(),
|
|
384
|
+
teacherBio: z.string().nullable(),
|
|
385
|
+
whatToBring: z.string().nullable(),
|
|
386
|
+
sessions: z.array(publicSessionSchema),
|
|
387
|
+
/** Minutes from the session's start — the running order, not clock times. */
|
|
388
|
+
segments: z.array(z.object({ startsMinute: z.number().int(), endsMinute: z.number().int(), label: z.string() })),
|
|
389
|
+
/** Galleries linked to this event in the CRM, published ones only, newest first. */
|
|
390
|
+
galleries: z.array(publicEventGallerySchema)
|
|
391
|
+
});
|
|
392
|
+
var publicSeriesSchema = publicSeriesRefSchema.extend({
|
|
393
|
+
summary: z.string().nullable(),
|
|
394
|
+
events: z.array(publicEventSummarySchema.extend({
|
|
395
|
+
/** The soonest date still to come, or null when they have all passed. */
|
|
396
|
+
nextSession: publicSessionSchema.nullable()
|
|
397
|
+
}))
|
|
398
|
+
});
|
|
399
|
+
var publicSeriesListSchema = z.object({
|
|
400
|
+
series: z.array(publicSeriesRefSchema.extend({ summary: z.string().nullable(), eventCount: z.number().int() }))
|
|
401
|
+
});
|
|
402
|
+
var registerInput = z.object({
|
|
403
|
+
name: z.string().trim().min(1, "A name is needed").max(200),
|
|
404
|
+
email: z.string().trim().email("That does not look like an email address").max(320),
|
|
405
|
+
/** Them plus anyone they are bringing. Capacity counts seats, not bookings. */
|
|
406
|
+
seats: z.number().int().min(1).max(20).optional(),
|
|
407
|
+
/**
|
|
408
|
+
* For a DONATION event: the card box's one-use token, held for the booking and taken only
|
|
409
|
+
* once the place is (never stored), with the bank's confirmation where it asked for one.
|
|
410
|
+
*/
|
|
411
|
+
card: z.object({
|
|
412
|
+
sourceId: z.string().min(1).max(2e3).regex(/^\S+$/, "That is not a card box's token"),
|
|
413
|
+
verificationToken: z.string().min(1).max(4e3).regex(/^\S+$/, "That is not a verification token").optional()
|
|
414
|
+
}).strict().optional(),
|
|
415
|
+
/** What they give, in minor units: at least the event's `priceCents` for each place. */
|
|
416
|
+
amountCents: z.number().int().min(1).max(1e8).optional()
|
|
417
|
+
}).strict();
|
|
418
|
+
var signUpInput = z.object({
|
|
419
|
+
name: z.string().trim().min(1, "A name is needed").max(200),
|
|
420
|
+
email: z.string().trim().email("That does not look like an email address").max(320)
|
|
421
|
+
}).strict();
|
|
422
|
+
var signedUpSchema = z.object({ status: z.enum(["CONFIRMED", "WAITLISTED"]) });
|
|
423
|
+
var bookingSchema = z.object({
|
|
424
|
+
status: z.enum(["CONFIRMED", "WAITLISTED", "CANCELLED"]),
|
|
425
|
+
seats: z.number().int(),
|
|
426
|
+
event: z.object({ title: z.string(), slug: z.string() }),
|
|
427
|
+
session: z.object({ startsAt: z.string(), endsAt: z.string(), venueName: z.string().nullable() })
|
|
428
|
+
});
|
|
429
|
+
var DONATION_MIN_CENTS = 100;
|
|
430
|
+
var DONATION_MAX_CENTS = 1e7;
|
|
431
|
+
var donationInput = z.object({
|
|
432
|
+
amountCents: z.number().int().min(DONATION_MIN_CENTS, "That is smaller than the smallest gift the card fees allow").max(DONATION_MAX_CENTS, "For a gift this size, please speak to the monastery directly"),
|
|
433
|
+
currency: z.string().regex(/^[A-Z]{3}$/, "Use a three-letter currency code, such as USD").optional(),
|
|
434
|
+
name: z.string().trim().min(1).max(200).optional(),
|
|
435
|
+
email: z.string().trim().email("That does not look like an email address").max(320).optional(),
|
|
436
|
+
/** Read out or written on a wall: "in memory of…". Never required. */
|
|
437
|
+
dedication: z.string().trim().max(300).optional(),
|
|
438
|
+
/**
|
|
439
|
+
* A PATH on the monastery's own site, never a URL.
|
|
440
|
+
*
|
|
441
|
+
* The full address is built by the API from the monastery's own public base, so a caller
|
|
442
|
+
* cannot name where the provider sends somebody afterwards. Taking a URL here would be an
|
|
443
|
+
* open redirect wearing a payment page's clothes.
|
|
444
|
+
*/
|
|
445
|
+
returnPath: z.string().max(300).regex(/^\/(?![/\\])[^\s?#\\]*$/, "Use a path on your own site, such as /thank-you").optional()
|
|
446
|
+
}).strict();
|
|
447
|
+
var DONATION_STATUSES = ["PENDING", "PAID", "FAILED", "REFUNDED"];
|
|
448
|
+
z.enum(DONATION_STATUSES);
|
|
449
|
+
var givingAvailabilitySchema = z.object({
|
|
450
|
+
available: z.boolean(),
|
|
451
|
+
currency: z.string().nullable(),
|
|
452
|
+
/**
|
|
453
|
+
* What a site starts the provider's card box with, to take a gift on its own page
|
|
454
|
+
* (`cardDonationInput`). Null when this monastery's gifts can only be taken on the
|
|
455
|
+
* provider's page. Nothing in it is secret: the box needs both in the browser.
|
|
456
|
+
*/
|
|
457
|
+
card: z.object({
|
|
458
|
+
provider: z.literal("square"),
|
|
459
|
+
/** This platform's Square application — the same for every monastery. */
|
|
460
|
+
applicationId: z.string(),
|
|
461
|
+
/** The monastery's own location: where the gift lands. */
|
|
462
|
+
locationId: z.string(),
|
|
463
|
+
environment: z.enum(["production", "sandbox"])
|
|
464
|
+
}).nullable().default(null),
|
|
465
|
+
/**
|
|
466
|
+
* Whether a MONTHLY gift can be taken (`POST /orgs/{slug}/donations/monthly`): the monastery's
|
|
467
|
+
* Square connection has agreed to keeping a card and charging it each month. False for a
|
|
468
|
+
* connection made before monthly gifts existed, until an Admin connects again.
|
|
469
|
+
*/
|
|
470
|
+
monthly: z.boolean().default(false)
|
|
471
|
+
});
|
|
472
|
+
var donationStartedSchema = z.object({ url: z.string(), donationId: z.string() });
|
|
473
|
+
var cardDonationInput = donationInput.omit({ returnPath: true }).extend({
|
|
474
|
+
/** The card box's token (Square's `cnon:…`): for one payment, never stored. */
|
|
475
|
+
sourceId: z.string().min(1).max(2e3).regex(/^\S+$/, "That is not a card box's token"),
|
|
476
|
+
/**
|
|
477
|
+
* The box's answer to the card's bank asking the buyer to confirm (Square's
|
|
478
|
+
* `verifyBuyer`), where the bank asked. Passed through with the payment.
|
|
479
|
+
*/
|
|
480
|
+
verificationToken: z.string().min(1).max(4e3).regex(/^\S+$/, "That is not a verification token").optional()
|
|
481
|
+
}).strict();
|
|
482
|
+
var cardDonationSchema = z.object({ donationId: z.string(), status: z.enum(["PAID", "PENDING"]) });
|
|
483
|
+
var monthlyDonationInput = donationInput.omit({ returnPath: true, name: true, email: true }).extend({
|
|
484
|
+
name: z.string().trim().min(1, "A name is needed").max(200),
|
|
485
|
+
email: z.string().trim().email("That does not look like an email address").max(320),
|
|
486
|
+
/** The card box's token (Square's `cnon:…`): kept by Square as the card on file, never here. */
|
|
487
|
+
sourceId: z.string().min(1).max(2e3).regex(/^\S+$/, "That is not a card box's token"),
|
|
488
|
+
/** The box's `verifyBuyer` answer for keeping a card (intent STORE), where the bank asked. */
|
|
489
|
+
verificationToken: z.string().min(1).max(4e3).regex(/^\S+$/, "That is not a verification token").optional()
|
|
490
|
+
}).strict();
|
|
491
|
+
var MONTHLY_GIFT_STATUSES = ["ACTIVE", "STOPPED"];
|
|
492
|
+
var monthlyStartedSchema = z.object({ monthlyGiftId: z.string(), status: z.literal("ACTIVE") });
|
|
493
|
+
var monthlyGiftSchema = z.object({
|
|
494
|
+
status: z.enum(MONTHLY_GIFT_STATUSES),
|
|
495
|
+
amountCents: z.number().int(),
|
|
496
|
+
currency: z.string(),
|
|
497
|
+
dedication: z.string().nullable(),
|
|
498
|
+
monastery: z.object({ name: z.string(), slug: z.string() }),
|
|
499
|
+
startedAt: z.string().nullable(),
|
|
500
|
+
stoppedAt: z.string().nullable()
|
|
501
|
+
});
|
|
502
|
+
var publicSiteSchema = z.object({
|
|
503
|
+
slug: z.string(),
|
|
504
|
+
name: z.string()
|
|
505
|
+
});
|
|
506
|
+
var MwamError = class extends Error {
|
|
507
|
+
// `cause` is kept: a tenant debugging why their events are blank wants the DNS failure
|
|
508
|
+
// underneath, not just the sentence this class puts on top of it.
|
|
509
|
+
constructor(code, message, status, cause) {
|
|
510
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
511
|
+
this.code = code;
|
|
512
|
+
this.status = status;
|
|
513
|
+
this.name = "MwamError";
|
|
514
|
+
}
|
|
515
|
+
code;
|
|
516
|
+
status;
|
|
517
|
+
};
|
|
518
|
+
var DEFAULT_BASE_URL = "https://apps-api.meditatewithamonk.org";
|
|
519
|
+
var UNREADABLE = "The mwam service could not be read";
|
|
520
|
+
function createClient({ baseUrl = DEFAULT_BASE_URL, tenant, fetch: given, revalidate, apiKey }) {
|
|
521
|
+
const call = given ?? globalThis.fetch;
|
|
522
|
+
const api = `${baseUrl.replace(/\/+$/, "")}/v1`;
|
|
523
|
+
const notTenanted = (path) => path === "/site" || path.startsWith("/sessions/") || path.startsWith("/bookings/") || path.startsWith("/monthly-gifts/");
|
|
524
|
+
let slug = tenant === void 0 ? null : Promise.resolve(tenant);
|
|
525
|
+
const root = async () => {
|
|
526
|
+
slug ??= site().then((s) => s.slug, (err) => {
|
|
527
|
+
slug = null;
|
|
528
|
+
throw err;
|
|
529
|
+
});
|
|
530
|
+
return `${api}/orgs/${encodeURIComponent(await slug)}`;
|
|
531
|
+
};
|
|
532
|
+
async function site() {
|
|
533
|
+
const parsed = publicSiteSchema.safeParse(await read("/site"));
|
|
534
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
535
|
+
return parsed.data;
|
|
536
|
+
}
|
|
537
|
+
async function read(path, query = {}, init, visitor) {
|
|
538
|
+
const qs = new URLSearchParams(query).toString();
|
|
539
|
+
const base = notTenanted(path) ? api : await root();
|
|
540
|
+
let res;
|
|
541
|
+
try {
|
|
542
|
+
res = await call(`${base}${path}${qs === "" ? "" : `?${qs}`}`, {
|
|
543
|
+
...init,
|
|
544
|
+
headers: {
|
|
545
|
+
accept: "application/json",
|
|
546
|
+
...init?.body === void 0 ? {} : { "content-type": "application/json" },
|
|
547
|
+
authorization: `Bearer ${apiKey}`,
|
|
548
|
+
...visitor === void 0 ? {} : { "x-mwam-visitor": visitor }
|
|
549
|
+
},
|
|
550
|
+
// Understood by Next's fetch and ignored elsewhere, so one client serves both.
|
|
551
|
+
// Never on a write: a cached registration is a seat taken twice, or not at all.
|
|
552
|
+
...revalidate === void 0 || init?.method !== void 0 ? {} : { next: { revalidate } }
|
|
553
|
+
});
|
|
554
|
+
} catch (cause) {
|
|
555
|
+
throw new MwamError("unreachable", UNREADABLE, void 0, cause);
|
|
556
|
+
}
|
|
557
|
+
if (res.status === 404) {
|
|
558
|
+
if (path === "/site") throw new MwamError("not_found", "The mwam service did not say whose key this is; give the client its tenant", 404);
|
|
559
|
+
const what = path.startsWith("/monthly-gifts/") ? "No such monthly gift" : notTenanted(path) ? "No such date or booking" : path.startsWith("/donations") || path === "/giving" ? "No such monastery" : path.startsWith("/series") ? "No such series" : path.startsWith("/galleries") ? "No such gallery" : path.startsWith("/posts") ? "No such post" : "No such event";
|
|
560
|
+
throw new MwamError("not_found", what, 404);
|
|
561
|
+
}
|
|
562
|
+
if (!res.ok) {
|
|
563
|
+
if (res.status < 500) {
|
|
564
|
+
const body = await res.json().catch(() => null);
|
|
565
|
+
const { code, message } = body?.error ?? {};
|
|
566
|
+
if (typeof code === "string" && typeof message === "string") throw new MwamError(code, message, res.status);
|
|
567
|
+
}
|
|
568
|
+
throw new MwamError("http_error", `${UNREADABLE} (${String(res.status)})`, res.status);
|
|
569
|
+
}
|
|
570
|
+
try {
|
|
571
|
+
return await res.json();
|
|
572
|
+
} catch {
|
|
573
|
+
throw new MwamError("not_json", `${UNREADABLE}: the reply was not JSON`, res.status);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
return {
|
|
577
|
+
/**
|
|
578
|
+
* The monastery this client's key belongs to, `{ slug, name }`. The client asks for it on
|
|
579
|
+
* its own when it was not given a `tenant`; a site can also use it for its name.
|
|
580
|
+
*/
|
|
581
|
+
site,
|
|
582
|
+
/**
|
|
583
|
+
* One page of the monastery's blog: its own posts and the posts other monasteries share
|
|
584
|
+
* with it, newest first by the date it publishes each under — or best match first, when
|
|
585
|
+
* searching. Each comes with its cover and category; no bodies — fetch a post to read it.
|
|
586
|
+
*
|
|
587
|
+
* `total` and `pageCount` count what was asked for, search and filters included, so a
|
|
588
|
+
* pager can say "Page 2 of 4" of the search results themselves.
|
|
589
|
+
*/
|
|
590
|
+
async listPosts({ page, limit, q, category, from, to } = {}) {
|
|
591
|
+
const query = {};
|
|
592
|
+
if (page !== void 0) query["page"] = String(page);
|
|
593
|
+
if (limit !== void 0) query["limit"] = String(limit);
|
|
594
|
+
if (q !== void 0 && q.trim() !== "") query["q"] = q;
|
|
595
|
+
if (category !== void 0) query["category"] = category;
|
|
596
|
+
if (from !== void 0) query["from"] = typeof from === "string" ? from : from.toISOString();
|
|
597
|
+
if (to !== void 0) query["to"] = typeof to === "string" ? to : to.toISOString();
|
|
598
|
+
const parsed = publicPostListSchema.safeParse(await read("/posts", query));
|
|
599
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
600
|
+
return parsed.data;
|
|
601
|
+
},
|
|
602
|
+
/**
|
|
603
|
+
* The categories the blog has published posts in, by name, each with how many — what a
|
|
604
|
+
* filter offers. A category with nothing published is not in it.
|
|
605
|
+
*/
|
|
606
|
+
async listCategories() {
|
|
607
|
+
const parsed = publicCategoryListSchema.safeParse(await read("/categories"));
|
|
608
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
609
|
+
return parsed.data.categories;
|
|
610
|
+
},
|
|
611
|
+
/**
|
|
612
|
+
* One post, as this monastery publishes it: a post shared from elsewhere carries this
|
|
613
|
+
* monastery's title, summary, address, date and cover, and `source` when its author's
|
|
614
|
+
* monastery asked to be credited. `body.html` goes into a page as it is — the service rendered it
|
|
615
|
+
* from a closed set of elements, escaped, with every picture's address absolute. Throws
|
|
616
|
+
* `not_found` for a draft, a withdrawn post and an address nothing is at alike.
|
|
617
|
+
*/
|
|
618
|
+
async getPost(slug2, { format } = {}) {
|
|
619
|
+
const wanted = postFormats.safeParse(format);
|
|
620
|
+
if (!wanted.success) throw new MwamError("invalid", `format must list one or more of ${POST_BODY_FORMATS.join(", ")}`);
|
|
621
|
+
const query = wanted.data === void 0 ? {} : { format: wanted.data.join(",") };
|
|
622
|
+
const parsed = publicPostSchema.safeParse(await read(`/posts/${encodeURIComponent(slug2)}`, query));
|
|
623
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
624
|
+
return parsed.data;
|
|
625
|
+
},
|
|
626
|
+
/**
|
|
627
|
+
* The monastery's dates, soonest first — what an /events index page is. SESSIONS, not
|
|
628
|
+
* events: three dates are three rows even when two belong to one programme.
|
|
629
|
+
*/
|
|
630
|
+
async listSessions(query = {}) {
|
|
631
|
+
const q = {};
|
|
632
|
+
if (query.from !== void 0) q["from"] = typeof query.from === "string" ? query.from : query.from.toISOString();
|
|
633
|
+
if (query.limit !== void 0) q["limit"] = String(query.limit);
|
|
634
|
+
if (query.category !== void 0) q["category"] = query.category;
|
|
635
|
+
const parsed = publicSessionListSchema.safeParse(await read("/events", q));
|
|
636
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
637
|
+
return parsed.data.sessions;
|
|
638
|
+
},
|
|
639
|
+
/** One event, with every date it has. Throws `not_found` for an address nothing is at. */
|
|
640
|
+
async getEvent(slug2) {
|
|
641
|
+
const parsed = publicEventDetailSchema.safeParse(await read(`/events/${encodeURIComponent(slug2)}`));
|
|
642
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
643
|
+
return parsed.data;
|
|
644
|
+
},
|
|
645
|
+
/**
|
|
646
|
+
* The monastery's series that have something on the site — for a menu, or an index of
|
|
647
|
+
* programmes. A series with nothing published is not in it.
|
|
648
|
+
*/
|
|
649
|
+
async listSeries() {
|
|
650
|
+
const parsed = publicSeriesListSchema.safeParse(await read("/series"));
|
|
651
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
652
|
+
return parsed.data.series;
|
|
653
|
+
},
|
|
654
|
+
/**
|
|
655
|
+
* One series page — what the middle of `Home > Meditate With A Monk > Plainsboro` links
|
|
656
|
+
* to — with each published event in it and that event's next date. Throws `not_found`
|
|
657
|
+
* when nothing in it is published.
|
|
658
|
+
*/
|
|
659
|
+
async getSeries(slug2) {
|
|
660
|
+
const parsed = publicSeriesSchema.safeParse(await read(`/series/${encodeURIComponent(slug2)}`));
|
|
661
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
662
|
+
return parsed.data;
|
|
663
|
+
},
|
|
664
|
+
/** The monastery's published galleries, most recent first, each with its cover. */
|
|
665
|
+
async listGalleries(query = {}) {
|
|
666
|
+
const parsed = publicGalleryListSchema.safeParse(await read("/galleries", query.limit === void 0 ? {} : { limit: String(query.limit) }));
|
|
667
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
668
|
+
return parsed.data.galleries;
|
|
669
|
+
},
|
|
670
|
+
/**
|
|
671
|
+
* One gallery, every picture in order. Each `url` is absolute and each `alt` is present —
|
|
672
|
+
* a gallery cannot be published until every picture is described — so an `<img>` needs
|
|
673
|
+
* nothing added.
|
|
674
|
+
*/
|
|
675
|
+
async getGallery(slug2) {
|
|
676
|
+
const parsed = publicGallerySchema.safeParse(await read(`/galleries/${encodeURIComponent(slug2)}`));
|
|
677
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
678
|
+
return parsed.data;
|
|
679
|
+
},
|
|
680
|
+
/**
|
|
681
|
+
* Takes a place at one date.
|
|
682
|
+
*
|
|
683
|
+
* A full date answers WAITLISTED rather than throwing: it is a different outcome, not an
|
|
684
|
+
* error, and a site that treated it as one would tell somebody their booking failed when
|
|
685
|
+
* they are in fact next in line. **Check `status`.**
|
|
686
|
+
*
|
|
687
|
+
* The person's link to their booking reaches them by email, and only by email: the answer
|
|
688
|
+
* carries no token (since 0.4.0). An address that had already booked the date is answered
|
|
689
|
+
* as a newcomer would be — `status` is what a new booking gets now — and is sent an email
|
|
690
|
+
* saying how things really stand, so this cannot be used to ask who has booked.
|
|
691
|
+
*
|
|
692
|
+
* A date whose event's `pricing` is DONATION takes `card` — the card box's token, the box
|
|
693
|
+
* started with what `giving()` answers as `card` — and `amountCents`, at least the event's
|
|
694
|
+
* `priceCents` for each place. The card is held, the place taken, and only then is the money
|
|
695
|
+
* taken: a full date throws (`conflict`, 409) with nothing taken, never waitlisting; a
|
|
696
|
+
* refused card throws `declined` (402) whose message is for the person. The confirmation
|
|
697
|
+
* email is their receipt.
|
|
698
|
+
*/
|
|
699
|
+
async register(sessionId, who, { visitor } = {}) {
|
|
700
|
+
const input = registerInput.safeParse(who);
|
|
701
|
+
if (!input.success) throw new MwamError("invalid", shapeProblem(input.error.issues));
|
|
702
|
+
const parsed = takenSchema.safeParse(await read(`/sessions/${encodeURIComponent(sessionId)}/register`, {}, {
|
|
703
|
+
method: "POST",
|
|
704
|
+
body: JSON.stringify(input.data)
|
|
705
|
+
}, visitor));
|
|
706
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
707
|
+
return parsed.data;
|
|
708
|
+
},
|
|
709
|
+
/**
|
|
710
|
+
* Signs somebody up once for every date of an event whose `signUp` is ALL_DATES — the
|
|
711
|
+
* dates it has and any added later; booking one of its dates with `register` is refused.
|
|
712
|
+
*
|
|
713
|
+
* The same rules as `register`: WAITLISTED when it is full, **check `status`**; an address
|
|
714
|
+
* already signed up is answered as a newcomer would be and emailed how things stand. The
|
|
715
|
+
* email carries the person's own page, which is where they leave.
|
|
716
|
+
*/
|
|
717
|
+
async signUp(eventSlug, who, { visitor } = {}) {
|
|
718
|
+
const input = signUpInput.safeParse(who);
|
|
719
|
+
if (!input.success) throw new MwamError("invalid", shapeProblem(input.error.issues));
|
|
720
|
+
const parsed = signedUpSchema.safeParse(await read(`/events/${encodeURIComponent(eventSlug)}/sign-up`, {}, {
|
|
721
|
+
method: "POST",
|
|
722
|
+
body: JSON.stringify(input.data)
|
|
723
|
+
}, visitor));
|
|
724
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
725
|
+
return parsed.data;
|
|
726
|
+
},
|
|
727
|
+
/** One booking, by the token from its link. */
|
|
728
|
+
async booking(token) {
|
|
729
|
+
const parsed = bookingSchema.safeParse(await read(`/bookings/${encodeURIComponent(token)}`));
|
|
730
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
731
|
+
return parsed.data;
|
|
732
|
+
},
|
|
733
|
+
/** Gives the place back. Whoever is next and fits is confirmed and written to at once. */
|
|
734
|
+
async cancelBooking(token) {
|
|
735
|
+
await read(`/bookings/${encodeURIComponent(token)}/cancel`, {}, { method: "POST" });
|
|
736
|
+
},
|
|
737
|
+
/**
|
|
738
|
+
* Whether the monastery can take a gift online right now, and the currency it takes one
|
|
739
|
+
* in. Ask before drawing a gift form: a monastery whose Admin has not connected its
|
|
740
|
+
* payment account yet answers `available: false`, and a form shown then could only fail.
|
|
741
|
+
*
|
|
742
|
+
* `card` is what to start Square's card box with to take the gift on your own page
|
|
743
|
+
* (`giveByCard`): `Square.payments(card.applicationId, card.locationId)`, from
|
|
744
|
+
* `web.squarecdn.com` — or `sandbox.web.squarecdn.com` when `card.environment` says so.
|
|
745
|
+
* Null when only Square's own page can take a gift (`give`).
|
|
746
|
+
*/
|
|
747
|
+
async giving() {
|
|
748
|
+
const parsed = givingAvailabilitySchema.safeParse(await read("/giving"));
|
|
749
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
750
|
+
return parsed.data;
|
|
751
|
+
},
|
|
752
|
+
/**
|
|
753
|
+
* Starts a gift and answers with the provider's page to send the donor to. Nothing is
|
|
754
|
+
* paid until the provider says so; the page the donor comes back to proves nothing.
|
|
755
|
+
* `returnPath` is a path on the monastery's own site, never a URL.
|
|
756
|
+
*/
|
|
757
|
+
async give(gift, { visitor } = {}) {
|
|
758
|
+
const input = donationInput.safeParse(gift);
|
|
759
|
+
if (!input.success) throw new MwamError("invalid", shapeProblem(input.error.issues));
|
|
760
|
+
const parsed = donationStartedSchema.safeParse(await read("/donations", {}, { method: "POST", body: JSON.stringify(input.data) }, visitor));
|
|
761
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
762
|
+
return parsed.data;
|
|
763
|
+
},
|
|
764
|
+
/**
|
|
765
|
+
* Takes a gift on your own page: nobody leaves it. Square's card box there, started with
|
|
766
|
+
* `card` from `giving()`, turns the card into a one-use token (`sourceId`) — and
|
|
767
|
+
* `verifyBuyer`'s answer, where the bank asked, is `verificationToken`. Send them from
|
|
768
|
+
* YOUR SERVER, with the amount; the card number itself never reaches you or the API.
|
|
769
|
+
*
|
|
770
|
+
* Answers `PAID` — settled, the receipt has gone — or, rarely, `PENDING`: Square is still
|
|
771
|
+
* deciding, and it settles itself. A refused card throws `MwamError` with code `declined`
|
|
772
|
+
* and a message written for the donor; show it, and ask for the card again.
|
|
773
|
+
*
|
|
774
|
+
* Sending the same token again — after a timeout, say — never pays twice: it answers with
|
|
775
|
+
* how the first try ended.
|
|
776
|
+
*/
|
|
777
|
+
async giveByCard(gift, { visitor } = {}) {
|
|
778
|
+
const input = cardDonationInput.safeParse(gift);
|
|
779
|
+
if (!input.success) throw new MwamError("invalid", shapeProblem(input.error.issues));
|
|
780
|
+
const parsed = cardDonationSchema.safeParse(await read("/donations/card", {}, { method: "POST", body: JSON.stringify(input.data) }, visitor));
|
|
781
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
782
|
+
return parsed.data;
|
|
783
|
+
},
|
|
784
|
+
/**
|
|
785
|
+
* Starts a monthly gift, on your own page. Ask `giving()` first: `monthly` says whether the
|
|
786
|
+
* monastery's Square connection can keep a card. The card box is started with `card` from
|
|
787
|
+
* `giving()`, as for `giveByCard`; ask `verifyBuyer` with intent `STORE` and pass its token.
|
|
788
|
+
* Square keeps the card in the monastery's own account and charges it each month; each
|
|
789
|
+
* month is receipted like any gift, and the donor is emailed their own link to stop it —
|
|
790
|
+
* your page at `/give/monthly/{token}` (see `monthlyGift` and `stopMonthlyGift`).
|
|
791
|
+
*
|
|
792
|
+
* A refused card throws `MwamError` with code `declined` and a message for the donor. The
|
|
793
|
+
* same token sent again never starts a second gift.
|
|
794
|
+
*/
|
|
795
|
+
async giveMonthly(gift, { visitor } = {}) {
|
|
796
|
+
const input = monthlyDonationInput.safeParse(gift);
|
|
797
|
+
if (!input.success) throw new MwamError("invalid", shapeProblem(input.error.issues));
|
|
798
|
+
const parsed = monthlyStartedSchema.safeParse(await read("/donations/monthly", {}, { method: "POST", body: JSON.stringify(input.data) }, visitor));
|
|
799
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
800
|
+
return parsed.data;
|
|
801
|
+
},
|
|
802
|
+
/** A monthly gift, by the token in its donor's link — for your `/give/monthly/{token}` page. */
|
|
803
|
+
async monthlyGift(token) {
|
|
804
|
+
const parsed = monthlyGiftSchema.safeParse(await read(`/monthly-gifts/${encodeURIComponent(token)}`));
|
|
805
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
806
|
+
return parsed.data;
|
|
807
|
+
},
|
|
808
|
+
/** Stops it: nothing more is taken after the month already paid, and the donor is told. */
|
|
809
|
+
async stopMonthlyGift(token) {
|
|
810
|
+
const parsed = monthlyGiftSchema.safeParse(await read(`/monthly-gifts/${encodeURIComponent(token)}/stop`, {}, { method: "POST" }));
|
|
811
|
+
if (!parsed.success) throw new MwamError("unexpected_shape", shapeProblem(parsed.error.issues));
|
|
812
|
+
return parsed.data;
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
var postFormats = z.array(z.enum(POST_BODY_FORMATS)).min(1).optional();
|
|
817
|
+
var takenSchema = z.object({
|
|
818
|
+
status: z.enum(["CONFIRMED", "WAITLISTED"]),
|
|
819
|
+
seats: z.number().int()
|
|
820
|
+
});
|
|
821
|
+
var shapeProblem = (issues) => {
|
|
822
|
+
const first = issues[0];
|
|
823
|
+
const where = first === void 0 ? "" : ` at ${first.path.join(".")}`;
|
|
824
|
+
return `The mwam service answered in a shape this client does not know${where}: ${first?.message ?? "unknown"}`;
|
|
825
|
+
};
|
|
826
|
+
function eventJsonLd(session, event, opts = { url: "" }) {
|
|
827
|
+
const online = session.place.onlineUrl !== null;
|
|
828
|
+
const attendance = event.attendance === "MIXED" ? "MixedEventAttendanceMode" : event.attendance === "ONLINE" || online ? "OnlineEventAttendanceMode" : "OfflineEventAttendanceMode";
|
|
829
|
+
const STATUS = {
|
|
830
|
+
SCHEDULED: "EventScheduled",
|
|
831
|
+
CANCELLED: "EventCancelled",
|
|
832
|
+
POSTPONED: "EventPostponed",
|
|
833
|
+
RESCHEDULED: "EventRescheduled",
|
|
834
|
+
MOVED_ONLINE: "EventMovedOnline"
|
|
835
|
+
};
|
|
836
|
+
return {
|
|
837
|
+
"@context": "https://schema.org",
|
|
838
|
+
"@type": "Event",
|
|
839
|
+
name: event.title,
|
|
840
|
+
...event.summary === null ? {} : { description: event.summary },
|
|
841
|
+
startDate: session.startsAt,
|
|
842
|
+
endDate: session.endsAt,
|
|
843
|
+
eventStatus: `https://schema.org/${STATUS[session.status] ?? "EventScheduled"}`,
|
|
844
|
+
eventAttendanceMode: `https://schema.org/${attendance}`,
|
|
845
|
+
url: opts.url,
|
|
846
|
+
location: online ? { "@type": "VirtualLocation", url: session.place.onlineUrl } : {
|
|
847
|
+
"@type": "Place",
|
|
848
|
+
...session.place.name === null ? {} : { name: session.place.name },
|
|
849
|
+
address: {
|
|
850
|
+
"@type": "PostalAddress",
|
|
851
|
+
...session.place.streetAddress === null ? {} : { streetAddress: session.place.streetAddress },
|
|
852
|
+
...session.place.locality === null ? {} : { addressLocality: session.place.locality },
|
|
853
|
+
...session.place.region === null ? {} : { addressRegion: session.place.region },
|
|
854
|
+
...session.place.postalCode === null ? {} : { postalCode: session.place.postalCode },
|
|
855
|
+
...session.place.country === null ? {} : { addressCountry: session.place.country }
|
|
856
|
+
}
|
|
857
|
+
},
|
|
858
|
+
...opts.organizer === void 0 ? {} : { organizer: { "@type": "Organization", ...opts.organizer } },
|
|
859
|
+
// schema.org's own word for the programme an event belongs to. Only with a URL: a
|
|
860
|
+
// superEvent Google cannot follow is a name with nothing behind it.
|
|
861
|
+
...event.series === void 0 || event.series === null || opts.seriesUrl === void 0 ? {} : { superEvent: { "@type": "EventSeries", name: event.series.name, url: opts.seriesUrl } },
|
|
862
|
+
offers: {
|
|
863
|
+
"@type": "Offer",
|
|
864
|
+
price: (event.priceCents / 100).toFixed(2),
|
|
865
|
+
priceCurrency: event.priceCurrency,
|
|
866
|
+
// A date that is not going ahead is not on sale, whatever the price says.
|
|
867
|
+
availability: `https://schema.org/${session.status === "CANCELLED" ? "SoldOut" : "InStock"}`,
|
|
868
|
+
url: event.registrationUrl ?? opts.url
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
export { DEFAULT_BASE_URL, MwamError, createClient, eventJsonLd };
|