@odla-ai/chapter 0.0.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +305 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +356 -5
- package/dist/index.d.ts +356 -5
- package/dist/index.js +305 -4
- package/dist/index.js.map +1 -1
- package/dist/worker/index.cjs +167 -6
- package/dist/worker/index.cjs.map +1 -1
- package/dist/worker/index.d.cts +81 -0
- package/dist/worker/index.d.ts +81 -0
- package/dist/worker/index.js +165 -4
- package/dist/worker/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -21,10 +21,30 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
buildGroupSeed: () => buildGroupSeed,
|
|
24
|
+
canApprove: () => canApprove,
|
|
25
|
+
canBook: () => canBook,
|
|
26
|
+
canChangeRole: () => canChangeRole,
|
|
27
|
+
canTransition: () => canTransition,
|
|
24
28
|
chapterDb: () => chapterDb,
|
|
25
29
|
createChapterIntegration: () => createChapterIntegration,
|
|
26
30
|
defaultCrm: () => defaultCrm,
|
|
27
|
-
defineChapter: () => defineChapter
|
|
31
|
+
defineChapter: () => defineChapter,
|
|
32
|
+
getVaultSecret: () => getVaultSecret,
|
|
33
|
+
isAdminRole: () => isAdminRole,
|
|
34
|
+
isAlreadySent: () => isAlreadySent,
|
|
35
|
+
joinConfig: () => joinConfig,
|
|
36
|
+
planDelivery: () => planDelivery,
|
|
37
|
+
projectSharedRecord: () => projectSharedRecord,
|
|
38
|
+
render: () => render,
|
|
39
|
+
renderTemplateBody: () => renderTemplateBody,
|
|
40
|
+
resolveApplication: () => resolveApplication,
|
|
41
|
+
resolveAuth: () => resolveAuth,
|
|
42
|
+
resolvePipeline: () => resolvePipeline,
|
|
43
|
+
roleFromClaim: () => roleFromClaim,
|
|
44
|
+
sharedPersonInput: () => sharedPersonInput,
|
|
45
|
+
stageIndex: () => stageIndex,
|
|
46
|
+
submitApplication: () => submitApplication,
|
|
47
|
+
verifyStripeSignature: () => verifyStripeSignature
|
|
28
48
|
});
|
|
29
49
|
module.exports = __toCommonJS(index_exports);
|
|
30
50
|
|
|
@@ -49,6 +69,14 @@ var admins = {
|
|
|
49
69
|
note: attr("string", { optional: true })
|
|
50
70
|
}
|
|
51
71
|
};
|
|
72
|
+
var superAdmins = {
|
|
73
|
+
attrs: {
|
|
74
|
+
id: id(),
|
|
75
|
+
email: attr("string", { unique: true, indexed: true }),
|
|
76
|
+
note: attr("string", { optional: true }),
|
|
77
|
+
createdAt: attr("number", { indexed: true })
|
|
78
|
+
}
|
|
79
|
+
};
|
|
52
80
|
var applications = {
|
|
53
81
|
attrs: {
|
|
54
82
|
id: id(),
|
|
@@ -136,8 +164,16 @@ var emailLog = {
|
|
|
136
164
|
sentAt: attr("number", { indexed: true })
|
|
137
165
|
}
|
|
138
166
|
};
|
|
139
|
-
function chapterDb(mode) {
|
|
140
|
-
const entities =
|
|
167
|
+
function chapterDb(mode, auth) {
|
|
168
|
+
const entities = {};
|
|
169
|
+
if (mode === "chapter") {
|
|
170
|
+
entities.applications = applications;
|
|
171
|
+
entities.groups = groups;
|
|
172
|
+
entities.meetings = meetings;
|
|
173
|
+
entities.emailLog = emailLog;
|
|
174
|
+
}
|
|
175
|
+
if (auth.source === "table") entities.admins = admins;
|
|
176
|
+
if (auth.superAdmins) entities.superAdmins = superAdmins;
|
|
141
177
|
const schema = { entities, links: {} };
|
|
142
178
|
const rules = {};
|
|
143
179
|
for (const ns of Object.keys(entities)) {
|
|
@@ -294,6 +330,168 @@ function buildGroupSeed(config) {
|
|
|
294
330
|
return row;
|
|
295
331
|
}
|
|
296
332
|
|
|
333
|
+
// src/auth.ts
|
|
334
|
+
function resolveAuth(mode, auth) {
|
|
335
|
+
const a = auth ?? {};
|
|
336
|
+
const source = a.source ?? (mode === "hub" ? "table" : "claim");
|
|
337
|
+
if (source !== "claim" && source !== "table") {
|
|
338
|
+
throw new Error(`defineChapter.auth.source: must be "claim" or "table" \u2014 got ${JSON.stringify(a.source)}`);
|
|
339
|
+
}
|
|
340
|
+
const claim = a.claim ?? "role";
|
|
341
|
+
if (typeof claim !== "string" || claim === "") {
|
|
342
|
+
throw new Error("defineChapter.auth.claim: must be a non-empty string");
|
|
343
|
+
}
|
|
344
|
+
const ladder = a.ladder ?? ["provisional", "member", "admin"];
|
|
345
|
+
if (!Array.isArray(ladder) || ladder.length === 0 || !ladder.every((r) => typeof r === "string" && r !== "")) {
|
|
346
|
+
throw new Error("defineChapter.auth.ladder: must be a non-empty array of role strings");
|
|
347
|
+
}
|
|
348
|
+
const adminRole = ladder[ladder.length - 1];
|
|
349
|
+
const superAdmins2 = a.superAdmins ?? source === "claim";
|
|
350
|
+
return { source, claim, ladder, adminRole, superAdmins: superAdmins2 };
|
|
351
|
+
}
|
|
352
|
+
function roleFromClaim(payload, auth) {
|
|
353
|
+
const raw = payload[auth.claim];
|
|
354
|
+
return typeof raw === "string" && auth.ladder.includes(raw) ? raw : auth.ladder[0];
|
|
355
|
+
}
|
|
356
|
+
function isAdminRole(role, auth) {
|
|
357
|
+
return role === auth.adminRole;
|
|
358
|
+
}
|
|
359
|
+
function canChangeRole(ctx) {
|
|
360
|
+
const { auth } = ctx;
|
|
361
|
+
if (!auth.ladder.includes(ctx.newRole)) {
|
|
362
|
+
return { ok: false, status: 400, error: `role must be one of: ${auth.ladder.join(", ")}` };
|
|
363
|
+
}
|
|
364
|
+
if (ctx.actorId === ctx.targetId) {
|
|
365
|
+
return { ok: false, status: 400, error: "you cannot change your own role" };
|
|
366
|
+
}
|
|
367
|
+
if (ctx.targetIsSuper && !ctx.actorIsSuper) {
|
|
368
|
+
return { ok: false, status: 403, error: "this person is a super-admin; their access is managed in odla Studio" };
|
|
369
|
+
}
|
|
370
|
+
const touchesAdmin = ctx.newRole === auth.adminRole || ctx.targetCurrentRole === auth.adminRole;
|
|
371
|
+
if (auth.superAdmins && touchesAdmin && !ctx.actorIsSuper) {
|
|
372
|
+
return { ok: false, status: 403, error: `only super-admins can create or change an ${auth.adminRole}` };
|
|
373
|
+
}
|
|
374
|
+
return { ok: true };
|
|
375
|
+
}
|
|
376
|
+
async function getVaultSecret(db, name) {
|
|
377
|
+
try {
|
|
378
|
+
const value = await db.secrets.get(name);
|
|
379
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
380
|
+
} catch {
|
|
381
|
+
return void 0;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// src/pipeline.ts
|
|
386
|
+
var DEFAULT_STAGES = [
|
|
387
|
+
"submitted",
|
|
388
|
+
"paid_pending_vetting",
|
|
389
|
+
"call_scheduled",
|
|
390
|
+
"interviewed",
|
|
391
|
+
"approved",
|
|
392
|
+
"declined",
|
|
393
|
+
"refunded"
|
|
394
|
+
];
|
|
395
|
+
var DEFAULT_BOOKABLE = ["submitted", "paid_pending_vetting", "call_scheduled"];
|
|
396
|
+
var DEFAULT_APPROVABLE = ["paid_pending_vetting", "call_scheduled", "interviewed"];
|
|
397
|
+
function resolvePipeline(p) {
|
|
398
|
+
const usingDefaults = !p?.stages;
|
|
399
|
+
const stages = p?.stages ?? [...DEFAULT_STAGES];
|
|
400
|
+
if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => typeof s === "string" && s !== "")) {
|
|
401
|
+
throw new Error("defineChapter.pipeline.stages: must be a non-empty array of status strings");
|
|
402
|
+
}
|
|
403
|
+
if (new Set(stages).size !== stages.length) {
|
|
404
|
+
throw new Error("defineChapter.pipeline.stages: statuses must be unique");
|
|
405
|
+
}
|
|
406
|
+
const initial = p?.initial ?? stages[0];
|
|
407
|
+
if (!stages.includes(initial)) {
|
|
408
|
+
throw new Error(`defineChapter.pipeline.initial: "${initial}" is not one of the stages`);
|
|
409
|
+
}
|
|
410
|
+
const bookableFrom = p?.bookableFrom ?? (usingDefaults ? [...DEFAULT_BOOKABLE] : []);
|
|
411
|
+
const approvableFrom = p?.approvableFrom ?? (usingDefaults ? [...DEFAULT_APPROVABLE] : []);
|
|
412
|
+
for (const [name, subset] of [
|
|
413
|
+
["bookableFrom", bookableFrom],
|
|
414
|
+
["approvableFrom", approvableFrom]
|
|
415
|
+
]) {
|
|
416
|
+
for (const s of subset) {
|
|
417
|
+
if (!stages.includes(s)) throw new Error(`defineChapter.pipeline.${name}: "${s}" is not one of the stages`);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return { stages, bookableFrom, approvableFrom, initial };
|
|
421
|
+
}
|
|
422
|
+
function stageIndex(status, p) {
|
|
423
|
+
return p.stages.indexOf(status);
|
|
424
|
+
}
|
|
425
|
+
function canTransition(from, to, p) {
|
|
426
|
+
const fi = p.stages.indexOf(from);
|
|
427
|
+
const ti = p.stages.indexOf(to);
|
|
428
|
+
return fi >= 0 && ti >= 0 && ti >= fi;
|
|
429
|
+
}
|
|
430
|
+
function canBook(status, p) {
|
|
431
|
+
return p.bookableFrom.includes(status);
|
|
432
|
+
}
|
|
433
|
+
function canApprove(status, p) {
|
|
434
|
+
return p.approvableFrom.includes(status);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/member.ts
|
|
438
|
+
var DEFAULT_REQUIRED = ["firstName", "lastName", "email", "referral", "whoYouAre", "message"];
|
|
439
|
+
var DEFAULT_OPTIONAL = ["referralName", "linkedin", "phone", "state"];
|
|
440
|
+
function resolveApplication(a) {
|
|
441
|
+
const required = a?.required ?? DEFAULT_REQUIRED;
|
|
442
|
+
const optional = a?.optional ?? DEFAULT_OPTIONAL;
|
|
443
|
+
for (const [name, arr] of [["required", required], ["optional", optional]]) {
|
|
444
|
+
if (!Array.isArray(arr) || !arr.every((f) => typeof f === "string" && f !== "")) {
|
|
445
|
+
throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return {
|
|
449
|
+
required,
|
|
450
|
+
optional,
|
|
451
|
+
maxLen: a?.maxLen ?? {},
|
|
452
|
+
defaultMaxLen: a?.defaultMaxLen ?? 2e3,
|
|
453
|
+
bodyCap: a?.bodyCap ?? 32768
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
async function submitApplication(db, chapter, fields, opts) {
|
|
457
|
+
const app = chapter.application;
|
|
458
|
+
for (const f of app.required) {
|
|
459
|
+
const v = fields[f];
|
|
460
|
+
if (typeof v !== "string" || v.trim() === "") return { ok: false, error: `${f} is required` };
|
|
461
|
+
}
|
|
462
|
+
for (const f of [...app.required, ...app.optional]) {
|
|
463
|
+
const v = fields[f];
|
|
464
|
+
const cap = app.maxLen[f] ?? app.defaultMaxLen;
|
|
465
|
+
if (typeof v === "string" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };
|
|
466
|
+
}
|
|
467
|
+
const id2 = opts.newId();
|
|
468
|
+
const row = { id: id2, status: chapter.pipeline.initial, createdAt: opts.now };
|
|
469
|
+
for (const f of [...app.required, ...app.optional]) {
|
|
470
|
+
if (typeof fields[f] === "string") row[f] = fields[f].trim();
|
|
471
|
+
}
|
|
472
|
+
if (fields.focus !== void 0) row.focus = fields.focus;
|
|
473
|
+
if (opts.groupId) row.groupId = opts.groupId;
|
|
474
|
+
const { duplicate } = await db.transact(
|
|
475
|
+
[{ t: "update", ns: "applications", id: id2, attrs: row }],
|
|
476
|
+
opts.submissionId ? { mutationId: `join:${opts.submissionId}` } : void 0
|
|
477
|
+
);
|
|
478
|
+
return { ok: true, id: id2, duplicate, status: chapter.pipeline.initial };
|
|
479
|
+
}
|
|
480
|
+
function joinConfig(group, paymentsReady) {
|
|
481
|
+
return {
|
|
482
|
+
id: group.id,
|
|
483
|
+
name: group.name,
|
|
484
|
+
standardPriceCents: group.standardPriceCents ?? 0,
|
|
485
|
+
foundingDiscountCents: group.foundingDiscountCents ?? 0,
|
|
486
|
+
disclaimerText: group.disclaimerText ?? "",
|
|
487
|
+
refundPolicyText: group.refundPolicyText ?? "",
|
|
488
|
+
trustCopy: group.trustCopy ?? "",
|
|
489
|
+
commitmentText: group.commitmentText ?? "",
|
|
490
|
+
normsText: group.normsText ?? "",
|
|
491
|
+
paymentsReady
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
297
495
|
// src/config.ts
|
|
298
496
|
var SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;
|
|
299
497
|
function isResolvedCrm(x) {
|
|
@@ -317,7 +515,10 @@ function defineChapter(config) {
|
|
|
317
515
|
throw new Error("defineChapter.prices.standardCents: required in chapter mode");
|
|
318
516
|
}
|
|
319
517
|
}
|
|
320
|
-
const
|
|
518
|
+
const auth = resolveAuth(mode, config.auth);
|
|
519
|
+
const pipeline = resolvePipeline(config.pipeline);
|
|
520
|
+
const application = resolveApplication(config.application);
|
|
521
|
+
const { schema, rules } = chapterDb(mode, auth);
|
|
321
522
|
const services = config.services ?? ["db", "calendar", "o11y"];
|
|
322
523
|
const chapter = {
|
|
323
524
|
config,
|
|
@@ -325,6 +526,9 @@ function defineChapter(config) {
|
|
|
325
526
|
name,
|
|
326
527
|
mode,
|
|
327
528
|
crm,
|
|
529
|
+
auth,
|
|
530
|
+
pipeline,
|
|
531
|
+
application,
|
|
328
532
|
schema,
|
|
329
533
|
rules,
|
|
330
534
|
services,
|
|
@@ -365,4 +569,101 @@ function createChapterIntegration(chapter, options = {}) {
|
|
|
365
569
|
probes: [...crmDesc.probes ?? []]
|
|
366
570
|
};
|
|
367
571
|
}
|
|
572
|
+
|
|
573
|
+
// src/email.ts
|
|
574
|
+
function render(template, vars) {
|
|
575
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] ?? "");
|
|
576
|
+
}
|
|
577
|
+
function groupVars(group, vars) {
|
|
578
|
+
return {
|
|
579
|
+
...vars,
|
|
580
|
+
refundPolicyText: group.refundPolicyText ?? "",
|
|
581
|
+
commitmentText: group.commitmentText ?? "",
|
|
582
|
+
normsText: group.normsText ?? ""
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
function renderTemplateBody(group, template, vars) {
|
|
586
|
+
const tpl = group.emailTemplates?.[template];
|
|
587
|
+
if (!tpl) return null;
|
|
588
|
+
return render(tpl.text, groupVars(group, vars));
|
|
589
|
+
}
|
|
590
|
+
function isAlreadySent(priorRows) {
|
|
591
|
+
return priorRows.some((row) => !row.error);
|
|
592
|
+
}
|
|
593
|
+
function planDelivery(input) {
|
|
594
|
+
const tpl = input.group.emailTemplates?.[input.template];
|
|
595
|
+
if (!tpl) return { deliver: false, reason: "template-missing" };
|
|
596
|
+
if (tpl.enabled === false && !input.force) return { deliver: false, reason: "disabled" };
|
|
597
|
+
const vars = groupVars(input.group, input.vars);
|
|
598
|
+
const isProd = input.envName === "prod";
|
|
599
|
+
const redirect = !isProd && !!input.group.debugEmail;
|
|
600
|
+
const transport = !isProd && !redirect ? "log-only" : input.cloudflareReady ? "cloudflare" : "log-only";
|
|
601
|
+
const to = redirect ? input.group.debugEmail : input.to;
|
|
602
|
+
const subject = (redirect ? "[dev] " : "") + render(tpl.subject, vars);
|
|
603
|
+
const text = redirect ? `(dev redirect; original recipient: ${input.to})
|
|
604
|
+
|
|
605
|
+
` + render(tpl.text, vars) : render(tpl.text, vars);
|
|
606
|
+
return { deliver: true, transport, to, subject, text, redirected: redirect };
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// src/payments.ts
|
|
610
|
+
function parseSigHeader(header) {
|
|
611
|
+
const parts = {};
|
|
612
|
+
for (const p of header.split(",")) {
|
|
613
|
+
const [k, v] = p.split("=", 2);
|
|
614
|
+
if (k && v !== void 0) parts[k] = v;
|
|
615
|
+
}
|
|
616
|
+
return { t: parts.t, v1: parts.v1 };
|
|
617
|
+
}
|
|
618
|
+
function toHex(buf) {
|
|
619
|
+
return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
620
|
+
}
|
|
621
|
+
function timingSafeEqual(a, b) {
|
|
622
|
+
if (a.length !== b.length) return false;
|
|
623
|
+
let diff = 0;
|
|
624
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
625
|
+
return diff === 0;
|
|
626
|
+
}
|
|
627
|
+
async function verifyStripeSignature(payload, header, secret, opts = {}) {
|
|
628
|
+
const { t, v1 } = parseSigHeader(header);
|
|
629
|
+
if (!t || !v1) return false;
|
|
630
|
+
const ts = Number(t);
|
|
631
|
+
if (!Number.isFinite(ts)) return false;
|
|
632
|
+
const nowSec = (opts.now ?? Date.now()) / 1e3;
|
|
633
|
+
const tolerance = opts.toleranceSec ?? 300;
|
|
634
|
+
if (Math.abs(nowSec - ts) > tolerance) return false;
|
|
635
|
+
const enc = new TextEncoder();
|
|
636
|
+
const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
637
|
+
const mac = await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${payload}`));
|
|
638
|
+
return timingSafeEqual(toHex(mac), v1);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// src/network.ts
|
|
642
|
+
var import_crm3 = require("@odla-ai/crm");
|
|
643
|
+
function sharedPersonInput(person) {
|
|
644
|
+
const email = person.email.toLowerCase();
|
|
645
|
+
const fullName = [person.firstName, person.lastName].filter(Boolean).join(" ").trim();
|
|
646
|
+
const input = { name: person.name ?? fullName ?? email, email };
|
|
647
|
+
if (input.name === "") input.name = email;
|
|
648
|
+
if (person.firstName) input.firstName = person.firstName;
|
|
649
|
+
if (person.lastName) input.lastName = person.lastName;
|
|
650
|
+
if (person.phone) input.phone = person.phone;
|
|
651
|
+
if (person.linkedin) input.linkedin = person.linkedin;
|
|
652
|
+
return input;
|
|
653
|
+
}
|
|
654
|
+
async function projectSharedRecord(deps, person) {
|
|
655
|
+
const email = person.email.toLowerCase();
|
|
656
|
+
const input = sharedPersonInput(person);
|
|
657
|
+
const crmDeps = { crm: deps.crm, db: deps.db, now: deps.now, newId: deps.newId };
|
|
658
|
+
const { crm_record } = await deps.db.query({
|
|
659
|
+
crm_record: { $: { where: { type: "person", primaryEmail: email }, limit: 1 } }
|
|
660
|
+
});
|
|
661
|
+
const existing = crm_record?.[0];
|
|
662
|
+
if (existing && typeof existing.id === "string") {
|
|
663
|
+
await (0, import_crm3.updateRecord)(crmDeps, { id: existing.id, input });
|
|
664
|
+
return { recordId: existing.id };
|
|
665
|
+
}
|
|
666
|
+
const created = await (0, import_crm3.createRecord)(crmDeps, { type: "person", input, mutationId: `share:${person.hubRecordId}` });
|
|
667
|
+
return { recordId: created.id };
|
|
668
|
+
}
|
|
368
669
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/schema.ts","../src/defaults.ts","../src/group.ts","../src/descriptor.ts"],"sourcesContent":["// @odla-ai/chapter — core (platform-neutral). The UI kit lives at ./ui.\n// chapterWorker (the full Cloudflare handler) lands with the worker port.\nexport { defineChapter } from \"./config\";\nexport { createChapterIntegration } from \"./descriptor\";\nexport { chapterDb } from \"./schema\";\nexport { defaultCrm } from \"./defaults\";\nexport { buildGroupSeed } from \"./group\";\n\nexport type { ChapterIntegrationDescriptor, ChapterIntegrationOptions } from \"./descriptor\";\nexport type {\n Chapter,\n ChapterConfig,\n ChapterMode,\n ChapterBrand,\n ChapterPrices,\n ChapterPolicy,\n ChapterEmails,\n ChapterScheduling,\n EmailTemplate,\n DbSchema,\n DbRules,\n Attr,\n AttrType,\n Entity,\n Rule,\n} from \"./types\";\n","// defineChapter — validate-at-import config, reusing @odla-ai/crm's defineCrm.\n// A bad config throws here (startup), never at request time.\nimport { defineCrm } from \"@odla-ai/crm\";\nimport type { CrmConfig, Crm } from \"@odla-ai/crm\";\nimport type { Chapter, ChapterConfig, ChapterMode } from \"./types\";\nimport { chapterDb } from \"./schema\";\nimport { defaultCrm } from \"./defaults\";\nimport { buildGroupSeed } from \"./group\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\n\nfunction isResolvedCrm(x: CrmConfig | Crm | undefined): x is Crm {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"prepare\" in x &&\n typeof (x as { prepare?: unknown }).prepare === \"function\"\n );\n}\n\n/**\n * Validate a chapter/hub config and resolve its engine — the CRM, the chapter's\n * odla-db schema/rules, and the seed groups row. Throws at import on a bad\n * config (bad slug, wrong mode, missing chapter-mode prices/emails), never at\n * request time.\n */\nexport function defineChapter(config: ChapterConfig): Chapter {\n if (!config || typeof config !== \"object\") throw new Error(\"defineChapter: a config object is required\");\n const { id, name } = config;\n if (typeof id !== \"string\" || !SLUG.test(id)) {\n throw new Error(`defineChapter.id: must be a lowercase slug [a-z0-9-] (2-63 chars) — got ${JSON.stringify(id)}`);\n }\n if (typeof name !== \"string\" || name.trim() === \"\") throw new Error(\"defineChapter.name: a non-empty name is required\");\n\n const mode: ChapterMode = config.mode ?? \"chapter\";\n if (mode !== \"chapter\" && mode !== \"hub\") throw new Error(`defineChapter.mode: must be \"chapter\" or \"hub\" — got ${JSON.stringify(config.mode)}`);\n\n const crm: Crm = isResolvedCrm(config.crm) ? config.crm : defineCrm(config.crm ?? defaultCrm(mode));\n\n if (mode === \"chapter\") {\n if (!config.emails || typeof config.emails.notificationEmail !== \"string\" || config.emails.notificationEmail === \"\") {\n throw new Error(\"defineChapter.emails.notificationEmail: required in chapter mode\");\n }\n if (!config.prices || typeof config.prices.standardCents !== \"number\") {\n throw new Error(\"defineChapter.prices.standardCents: required in chapter mode\");\n }\n }\n\n const { schema, rules } = chapterDb(mode);\n const services = config.services ?? [\"db\", \"calendar\", \"o11y\"];\n\n const chapter: Chapter = {\n config,\n id,\n name,\n mode,\n crm,\n schema,\n rules,\n services,\n groupSeed: () => (mode === \"chapter\" ? buildGroupSeed(config) : null),\n };\n if (config.url !== undefined) chapter.url = config.url;\n return chapter;\n}\n","// The chapter's own odla-db namespaces: applications, groups, meetings, and\n// emailLog, plus a single default-deny `admins` allowlist. The `crm_*`\n// namespaces are contributed separately by @odla-ai/crm's integration and\n// merged by the CLI.\nimport type { Attr, AttrType, DbRules, DbSchema, Entity, ChapterMode } from \"./types\";\n\nfunction attr(type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr {\n return {\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n };\n}\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n// The allowlist that gates admin access in BOTH modes. Studio-write-only:\n// deny-all, and no worker route ever writes it. Creation time is odla-db's\n// built-in $createdAt. One row per admin, keyed by lowercased email.\nconst admins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n name: attr(\"string\", { optional: true }),\n note: attr(\"string\", { optional: true }),\n },\n};\n\n// One row per membership application (chapter mode). Field names mirror the\n// join form. status pipeline drives the provisional -> member promotion.\nconst applications: Entity = {\n attrs: {\n id: id(),\n firstName: attr(\"string\"),\n lastName: attr(\"string\"),\n email: attr(\"string\", { indexed: true }),\n referral: attr(\"string\"),\n referralName: attr(\"string\", { optional: true }),\n whoYouAre: attr(\"string\"),\n focus: attr(\"json\"),\n linkedin: attr(\"string\", { optional: true }),\n message: attr(\"string\"),\n status: attr(\"string\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n meetingAt: attr(\"number\", { indexed: true, optional: true }),\n meetingLink: attr(\"string\", { optional: true }),\n clerkUserId: attr(\"string\", { indexed: true, optional: true }),\n phone: attr(\"string\", { optional: true }),\n state: attr(\"string\", { optional: true }),\n groupId: attr(\"string\", { indexed: true, optional: true }),\n stripeCustomerId: attr(\"string\", { indexed: true, optional: true }),\n stripeSubscriptionId: attr(\"string\", { indexed: true, optional: true }),\n renewalAt: attr(\"number\", { optional: true }),\n disclaimerAckAt: attr(\"number\", { optional: true }),\n refundPolicyAckAt: attr(\"number\", { optional: true }),\n prepEmailSentAt: attr(\"number\", { optional: true }),\n canceled: attr(\"boolean\", { optional: true }),\n },\n};\n\n// Per-group settings — prices, policy copy, email templates, scheduling — never\n// in code. Seeded once from the defineChapter config (see group.ts).\nconst groups: Entity = {\n attrs: {\n id: id(),\n name: attr(\"string\"),\n standardPriceCents: attr(\"number\"),\n foundingDiscountCents: attr(\"number\"),\n stripePriceId: attr(\"string\", { optional: true }),\n stripePublishableKey: attr(\"string\", { optional: true }),\n notificationEmail: attr(\"string\"),\n replyTo: attr(\"string\"),\n debugEmail: attr(\"string\", { optional: true }),\n calendarLink: attr(\"string\", { optional: true }),\n disclaimerText: attr(\"string\"),\n refundPolicyText: attr(\"string\"),\n trustCopy: attr(\"string\"),\n commitmentText: attr(\"string\", { optional: true }),\n normsText: attr(\"string\", { optional: true }),\n emailTemplates: attr(\"json\"),\n schedulingJson: attr(\"json\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Intro-call meetings: the source of truth for scheduling; Google Calendar is a\n// projection. Drift fields record when Google disagrees with us.\nconst meetings: Entity = {\n attrs: {\n id: id(),\n applicationId: attr(\"string\", { indexed: true }),\n groupId: attr(\"string\", { indexed: true }),\n startAt: attr(\"number\", { indexed: true }),\n endAt: attr(\"number\"),\n timezone: attr(\"string\"),\n status: attr(\"string\", { indexed: true }),\n googleEventId: attr(\"string\", { indexed: true, optional: true }),\n meetUrl: attr(\"string\", { optional: true }),\n htmlLink: attr(\"string\", { optional: true }),\n drift: attr(\"string\", { indexed: true, optional: true }),\n driftGoogleStartAt: attr(\"number\", { optional: true }),\n driftDetectedAt: attr(\"number\", { optional: true }),\n adoptedFromGoogleAt: attr(\"number\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Audit of every transactional send.\nconst emailLog: Entity = {\n attrs: {\n id: id(),\n groupId: attr(\"string\", { indexed: true }),\n applicationId: attr(\"string\", { indexed: true, optional: true }),\n to: attr(\"string\", { indexed: true }),\n template: attr(\"string\", { indexed: true }),\n subject: attr(\"string\"),\n body: attr(\"string\", { optional: true }),\n transport: attr(\"string\"),\n messageId: attr(\"string\", { optional: true }),\n redirected: attr(\"boolean\", { optional: true }),\n dedupeKey: attr(\"string\", { indexed: true, optional: true }),\n error: attr(\"string\", { optional: true }),\n sentAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** The chapter's own schema + deny-all rules for a mode. `hub` needs only the\n * `admins` allowlist (its records live in `crm_*`); `chapter` adds the\n * operational membership tables. */\nexport function chapterDb(mode: ChapterMode): { schema: DbSchema; rules: DbRules } {\n const entities: Record<string, Entity> =\n mode === \"hub\" ? { admins } : { admins, applications, groups, meetings, emailLog };\n const schema: DbSchema = { entities, links: {} };\n const rules: DbRules = {};\n for (const ns of Object.keys(entities)) {\n rules[ns] = { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" };\n }\n return { schema, rules };\n}\n","// Per-mode default CRM configs. Consumers pass their own via defineChapter's\n// `crm`; these are sensible starting points. `chapter` is a person lead pipeline\n// (fed from `applications`); `hub` adds businesses (people + companies).\nimport type { CrmConfig } from \"@odla-ai/crm\";\nimport type { ChapterMode } from \"./types\";\n\nconst TEMPLATES: CrmConfig[\"templates\"] = {\n personal: {\n class: \"transactional\",\n vars: [\"firstName\", \"subject\", \"body\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\" },\n },\n announcement: {\n class: \"marketing\",\n vars: [\"firstName\", \"subject\", \"body\", \"unsubscribeUrl\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\\n\\n{{unsubscribeUrl}}\" },\n },\n};\n\nfunction personType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Person\",\n labelPlural: \"People\",\n nameField: \"name\",\n emailField: \"email\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n email: { type: \"email\", label: \"Email\" },\n firstName: { type: \"string\", label: \"First name\" },\n lastName: { type: \"string\", label: \"Last name\" },\n phone: { type: \"string\", label: \"Phone\" },\n state: { type: \"string\", label: \"State\", slot: \"s1\" },\n whoYouAre: { type: \"string\", label: \"Who they are\", slot: \"s2\" },\n referral: { type: \"string\", label: \"Referral source\", slot: \"s3\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n focus: { type: \"json\", label: \"Focus areas\" },\n message: { type: \"string\", label: \"Intro message\" },\n },\n pipeline: {\n stages: [\n { id: \"submitted\", label: \"Submitted\" },\n { id: \"paid_pending_vetting\", label: \"Paid, pending vetting\" },\n { id: \"call_scheduled\", label: \"Call scheduled\" },\n { id: \"interviewed\", label: \"Interviewed\" },\n { id: \"approved\", label: \"Approved\" },\n { id: \"declined\", label: \"Declined\" },\n { id: \"refunded\", label: \"Refunded\" },\n ],\n },\n facets: { identity: true, email: true, rank: \"manual\" },\n };\n}\n\nfunction companyType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Business\",\n labelPlural: \"Businesses\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n domain: { type: \"string\", label: \"Domain / website\", slot: \"s1\" },\n industry: { type: \"string\", label: \"Industry\", slot: \"s2\" },\n location: { type: \"string\", label: \"Location\", slot: \"s3\" },\n chapter: { type: \"string\", label: \"Chapter\", slot: \"s4\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n facets: { rank: \"manual\" },\n };\n}\n\n/** The per-mode default CRM config: `chapter` = a person lead pipeline;\n * `hub` = people + businesses with a works_at relation. */\nexport function defaultCrm(mode: ChapterMode): CrmConfig {\n if (mode === \"hub\") {\n return {\n types: { person: personType(), company: companyType() },\n relations: { works_at: { from: \"person\", to: \"company\", label: \"works at\", reverseLabel: \"team\" } },\n templates: TEMPLATES,\n };\n }\n return {\n types: { person: personType() },\n templates: TEMPLATES,\n };\n}\n","// Build the seed `groups` row from a defineChapter config. This is the whole\n// per-chapter payload the worker reads at runtime (prices/policy/emails/\n// scheduling), so nothing brand-specific is hardcoded in the worker. createdAt\n// is stamped by the integration/seed layer, not here.\nimport type { ChapterConfig, ChapterScheduling } from \"./types\";\n\nconst DEFAULT_SCHEDULING: Required<Omit<ChapterScheduling, \"summaryTemplate\">> = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n};\n\nfunction defaultEmailTemplates(name: string): Record<string, { subject: string; text: string }> {\n const sign = `\\n\\nWarmly,\\n${name}`;\n return {\n adminNotification: {\n subject: `New application — {{firstName}} {{lastName}}`,\n text: `A new application came in for ${name}.\\n\\nName: {{firstName}} {{lastName}}\\nEmail: {{email}}`,\n },\n paymentConfirmation: {\n subject: `Welcome to ${name}`,\n text: `Hi {{firstName}},\\n\\nYour membership payment is confirmed. We'll be in touch to schedule your intro call.${sign}`,\n },\n prepEmail: {\n subject: `Your ${name} intro call`,\n text: `Hi {{firstName}},\\n\\nLooking forward to our call at {{meetingTime}}. {{meetingLink}}${sign}`,\n },\n onboardingInvite: {\n subject: `You're in — ${name}`,\n text: `Hi {{firstName}},\\n\\nWelcome to ${name}. Your member area is here: {{membersUrl}}${sign}`,\n },\n };\n}\n\n/** The `groups` row (attrs) for `chapter` mode. Missing config falls back to\n * empty copy / defaults, so a minimal config still provisions cleanly. */\nexport function buildGroupSeed(config: ChapterConfig): Record<string, unknown> {\n const prices = config.prices;\n const emails = config.emails;\n const policy = config.policy ?? {};\n const scheduling = {\n ...DEFAULT_SCHEDULING,\n ...(config.scheduling ?? {}),\n summaryTemplate:\n config.scheduling?.summaryTemplate ?? `${config.name}: introduction call with {{firstName}} {{lastName}}`,\n };\n const row: Record<string, unknown> = {\n id: config.id,\n name: config.name,\n standardPriceCents: prices?.standardCents ?? 0,\n foundingDiscountCents: prices?.foundingDiscountCents ?? 0,\n notificationEmail: emails?.notificationEmail ?? \"\",\n replyTo: emails?.replyTo ?? emails?.notificationEmail ?? \"\",\n disclaimerText: policy.disclaimerText ?? \"\",\n refundPolicyText: policy.refundPolicyText ?? \"\",\n trustCopy: policy.trustCopy ?? \"\",\n emailTemplates: emails?.templates ?? defaultEmailTemplates(config.name),\n schedulingJson: scheduling,\n };\n if (emails?.debugEmail) row.debugEmail = emails.debugEmail;\n if (policy.commitmentText) row.commitmentText = policy.commitmentText;\n if (policy.normsText) row.normsText = policy.normsText;\n return row;\n}\n","// The CLI-consumable provisioning descriptor. It composes @odla-ai/crm's\n// integration (crm_* namespaces + crm_config seed + route probe) with the\n// chapter's own namespaces and a guarded `groups`-row seed, so a site's\n// odla.config.mjs lists ONE integration. The CLI reads it structurally\n// (matching OdlaIntegration) and merges schema/rules by namespace.\nimport { createCrmIntegration } from \"@odla-ai/crm\";\nimport type { Chapter } from \"./types\";\n\n/** Options for {@link createChapterIntegration}. */\nexport interface ChapterIntegrationOptions {\n /** CRM route mount point. Default \"/api/crm\". */\n basePath?: string;\n /** Seed timestamp override for reproducible builds/tests. */\n now?: number;\n}\n\ninterface IntegrationSeed {\n id: string;\n ns: string;\n key: { attr: string; value: string };\n attrs: Record<string, unknown>;\n}\n\n/** Structural match for the CLI's `OdlaIntegration`. */\nexport interface ChapterIntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n schema: { entities: Record<string, unknown>; links: Record<string, unknown> };\n rules: Record<string, unknown>;\n seeds: IntegrationSeed[];\n probes: Array<{ path: string; expectedStatus: number }>;\n}\n\n/**\n * Build the one CLI-consumable integration for a chapter/hub: the crm_*\n * namespaces + crm_config seed + route probe, merged with the chapter's own\n * namespaces and a guarded `groups`-row seed. Drop it in odla.config.mjs's\n * `integrations` array.\n */\nexport function createChapterIntegration(\n chapter: Chapter,\n options: ChapterIntegrationOptions = {},\n): ChapterIntegrationDescriptor {\n const basePath = options.basePath ?? \"/api/crm\";\n const now = options.now ?? Date.now();\n const emails = chapter.config.emails;\n\n const crmDesc = createCrmIntegration(chapter.crm, {\n basePath,\n now,\n ...(emails?.notificationEmail ? { notificationEmail: emails.notificationEmail } : {}),\n ...(emails?.replyTo ? { replyTo: emails.replyTo } : {}),\n ...(emails?.debugEmail ? { debugEmail: emails.debugEmail } : {}),\n });\n\n const seeds: IntegrationSeed[] = [...(crmDesc.seeds ?? [])];\n const group = chapter.groupSeed();\n if (group) {\n seeds.push({ id: \"group\", ns: \"groups\", key: { attr: \"id\", value: chapter.id }, attrs: { ...group, createdAt: now } });\n }\n\n return {\n id: \"chapter\",\n title: `Chapter — ${chapter.name}`,\n npm: \"@odla-ai/chapter\",\n schema: {\n entities: { ...crmDesc.schema.entities, ...chapter.schema.entities },\n links: { ...crmDesc.schema.links, ...chapter.schema.links },\n },\n rules: { ...crmDesc.rules, ...chapter.rules },\n seeds,\n probes: [...(crmDesc.probes ?? [])],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,iBAA0B;;;ACI1B,SAAS,KAAK,MAAgB,QAAqE,CAAC,GAAS;AAC3G,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,MAAM,UAAU;AAAA,IACxB,SAAS,MAAM,WAAW;AAAA,IAC1B,UAAU,MAAM,YAAY;AAAA,EAC9B;AACF;AACA,IAAM,KAAK,MAAY,KAAK,UAAU,EAAE,QAAQ,MAAM,SAAS,KAAK,CAAC;AAKrE,IAAM,SAAiB;AAAA,EACrB,OAAO;AAAA,IACL,IAAI,GAAG;AAAA,IACP,OAAO,KAAK,UAAU,EAAE,QAAQ,MAAM,SAAS,KAAK,CAAC;AAAA,IACrD,MAAM,KAAK,UAAU,EAAE,UAAU,KAAK,CAAC;AAAA,IACvC,MAAM,KAAK,UAAU,EAAE,UAAU,KAAK,CAAC;AAAA,EACzC;AACF;AAIA,IAAM,eAAuB;AAAA,EAC3B,OAAO;AAAA,IACL,IAAI,GAAG;AAAA,IACP,WAAW,KAAK,QAAQ;AAAA,IACxB,UAAU,KAAK,QAAQ;AAAA,IACvB,OAAO,K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AAO,WAAW,IAAI,EAAE,CAAC;AAAA,EACvH;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,OAAO,kBAAa,QAAQ,IAAI;AAAA,IAChC,KAAK;AAAA,IACL,QAAQ;AAAA,MACN,UAAU,EAAE,GAAG,QAAQ,OAAO,UAAU,GAAG,QAAQ,OAAO,SAAS;AAAA,MACnE,OAAO,EAAE,GAAG,QAAQ,OAAO,OAAO,GAAG,QAAQ,OAAO,MAAM;AAAA,IAC5D;AAAA,IACA,OAAO,EAAE,GAAG,QAAQ,OAAO,GAAG,QAAQ,MAAM;AAAA,IAC5C;AAAA,IACA,QAAQ,CAAC,GAAI,QAAQ,UAAU,CAAC,CAAE;AAAA,EACpC;AACF;","names":["id","import_crm"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/schema.ts","../src/defaults.ts","../src/group.ts","../src/auth.ts","../src/pipeline.ts","../src/member.ts","../src/descriptor.ts","../src/email.ts","../src/payments.ts","../src/network.ts"],"sourcesContent":["// @odla-ai/chapter — core (platform-neutral). The UI kit lives at ./ui.\n// chapterWorker (the full Cloudflare handler) lands with the worker port.\nexport { defineChapter } from \"./config\";\nexport { createChapterIntegration } from \"./descriptor\";\nexport { chapterDb } from \"./schema\";\nexport { defaultCrm } from \"./defaults\";\nexport { buildGroupSeed } from \"./group\";\nexport { resolveAuth, roleFromClaim, isAdminRole, canChangeRole, getVaultSecret } from \"./auth\";\nexport { render, renderTemplateBody, isAlreadySent, planDelivery } from \"./email\";\nexport { resolvePipeline, canTransition, canBook, canApprove, stageIndex } from \"./pipeline\";\nexport { verifyStripeSignature } from \"./payments\";\nexport { resolveApplication, submitApplication, joinConfig } from \"./member\";\nexport { sharedPersonInput, projectSharedRecord } from \"./network\";\n\nexport type { ChapterIntegrationDescriptor, ChapterIntegrationOptions } from \"./descriptor\";\nexport type { RoleChangeContext, GuardResult, SecretStore } from \"./auth\";\nexport type { EmailTemplateRow, EmailGroup, DeliveryDecision } from \"./email\";\nexport type { SubmitResult, JoinConfigGroup } from \"./member\";\nexport type { SharedPerson, ProjectionDeps } from \"./network\";\nexport type {\n Chapter,\n ChapterConfig,\n ChapterMode,\n ChapterAuth,\n ResolvedAuth,\n ChapterPipeline,\n ResolvedPipeline,\n ChapterApplication,\n ResolvedApplication,\n DbOp,\n ChapterDb,\n ChapterBrand,\n ChapterPrices,\n ChapterPolicy,\n ChapterEmails,\n ChapterScheduling,\n EmailTemplate,\n DbSchema,\n DbRules,\n Attr,\n AttrType,\n Entity,\n Rule,\n} from \"./types\";\n","// defineChapter — validate-at-import config, reusing @odla-ai/crm's defineCrm.\n// A bad config throws here (startup), never at request time.\nimport { defineCrm } from \"@odla-ai/crm\";\nimport type { CrmConfig, Crm } from \"@odla-ai/crm\";\nimport type { Chapter, ChapterConfig, ChapterMode } from \"./types\";\nimport { chapterDb } from \"./schema\";\nimport { defaultCrm } from \"./defaults\";\nimport { buildGroupSeed } from \"./group\";\nimport { resolveAuth } from \"./auth\";\nimport { resolvePipeline } from \"./pipeline\";\nimport { resolveApplication } from \"./member\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\n\nfunction isResolvedCrm(x: CrmConfig | Crm | undefined): x is Crm {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"prepare\" in x &&\n typeof (x as { prepare?: unknown }).prepare === \"function\"\n );\n}\n\n/**\n * Validate a chapter/hub config and resolve its engine — the CRM, the chapter's\n * odla-db schema/rules, and the seed groups row. Throws at import on a bad\n * config (bad slug, wrong mode, missing chapter-mode prices/emails), never at\n * request time.\n */\nexport function defineChapter(config: ChapterConfig): Chapter {\n if (!config || typeof config !== \"object\") throw new Error(\"defineChapter: a config object is required\");\n const { id, name } = config;\n if (typeof id !== \"string\" || !SLUG.test(id)) {\n throw new Error(`defineChapter.id: must be a lowercase slug [a-z0-9-] (2-63 chars) — got ${JSON.stringify(id)}`);\n }\n if (typeof name !== \"string\" || name.trim() === \"\") throw new Error(\"defineChapter.name: a non-empty name is required\");\n\n const mode: ChapterMode = config.mode ?? \"chapter\";\n if (mode !== \"chapter\" && mode !== \"hub\") throw new Error(`defineChapter.mode: must be \"chapter\" or \"hub\" — got ${JSON.stringify(config.mode)}`);\n\n const crm: Crm = isResolvedCrm(config.crm) ? config.crm : defineCrm(config.crm ?? defaultCrm(mode));\n\n if (mode === \"chapter\") {\n if (!config.emails || typeof config.emails.notificationEmail !== \"string\" || config.emails.notificationEmail === \"\") {\n throw new Error(\"defineChapter.emails.notificationEmail: required in chapter mode\");\n }\n if (!config.prices || typeof config.prices.standardCents !== \"number\") {\n throw new Error(\"defineChapter.prices.standardCents: required in chapter mode\");\n }\n }\n\n const auth = resolveAuth(mode, config.auth);\n const pipeline = resolvePipeline(config.pipeline);\n const application = resolveApplication(config.application);\n const { schema, rules } = chapterDb(mode, auth);\n const services = config.services ?? [\"db\", \"calendar\", \"o11y\"];\n\n const chapter: Chapter = {\n config,\n id,\n name,\n mode,\n crm,\n auth,\n pipeline,\n application,\n schema,\n rules,\n services,\n groupSeed: () => (mode === \"chapter\" ? buildGroupSeed(config) : null),\n };\n if (config.url !== undefined) chapter.url = config.url;\n return chapter;\n}\n","// The chapter's own odla-db namespaces: the operational membership tables\n// (applications, groups, meetings, emailLog) plus the auth tables the resolved\n// auth policy selects — the `admins` allowlist (source \"table\") and/or the\n// read-only `superAdmins` tier. All deny-all. The `crm_*` namespaces are\n// contributed separately by @odla-ai/crm's integration and merged by the CLI.\nimport type { Attr, AttrType, DbRules, DbSchema, Entity, ChapterMode, ResolvedAuth } from \"./types\";\n\nfunction attr(type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr {\n return {\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n };\n}\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n// The allowlist that gates admin access in BOTH modes. Studio-write-only:\n// deny-all, and no worker route ever writes it. Creation time is odla-db's\n// built-in $createdAt. One row per admin, keyed by lowercased email.\nconst admins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n name: attr(\"string\", { optional: true }),\n note: attr(\"string\", { optional: true }),\n },\n};\n\n// The super-admin tier: the ONLY tier that may create or modify admins. A\n// separate, app-READ-ONLY entity — deny-all like every namespace AND no worker\n// route ever writes it, so membership can only be set in the odla Studio data\n// browser, never from the app or an injected page script. One row per\n// super-admin, keyed by lowercased email.\nconst superAdmins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n note: attr(\"string\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One row per membership application (chapter mode). Field names mirror the\n// join form. status pipeline drives the provisional -> member promotion.\nconst applications: Entity = {\n attrs: {\n id: id(),\n firstName: attr(\"string\"),\n lastName: attr(\"string\"),\n email: attr(\"string\", { indexed: true }),\n referral: attr(\"string\"),\n referralName: attr(\"string\", { optional: true }),\n whoYouAre: attr(\"string\"),\n focus: attr(\"json\"),\n linkedin: attr(\"string\", { optional: true }),\n message: attr(\"string\"),\n status: attr(\"string\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n meetingAt: attr(\"number\", { indexed: true, optional: true }),\n meetingLink: attr(\"string\", { optional: true }),\n clerkUserId: attr(\"string\", { indexed: true, optional: true }),\n phone: attr(\"string\", { optional: true }),\n state: attr(\"string\", { optional: true }),\n groupId: attr(\"string\", { indexed: true, optional: true }),\n stripeCustomerId: attr(\"string\", { indexed: true, optional: true }),\n stripeSubscriptionId: attr(\"string\", { indexed: true, optional: true }),\n renewalAt: attr(\"number\", { optional: true }),\n disclaimerAckAt: attr(\"number\", { optional: true }),\n refundPolicyAckAt: attr(\"number\", { optional: true }),\n prepEmailSentAt: attr(\"number\", { optional: true }),\n canceled: attr(\"boolean\", { optional: true }),\n },\n};\n\n// Per-group settings — prices, policy copy, email templates, scheduling — never\n// in code. Seeded once from the defineChapter config (see group.ts).\nconst groups: Entity = {\n attrs: {\n id: id(),\n name: attr(\"string\"),\n standardPriceCents: attr(\"number\"),\n foundingDiscountCents: attr(\"number\"),\n stripePriceId: attr(\"string\", { optional: true }),\n stripePublishableKey: attr(\"string\", { optional: true }),\n notificationEmail: attr(\"string\"),\n replyTo: attr(\"string\"),\n debugEmail: attr(\"string\", { optional: true }),\n calendarLink: attr(\"string\", { optional: true }),\n disclaimerText: attr(\"string\"),\n refundPolicyText: attr(\"string\"),\n trustCopy: attr(\"string\"),\n commitmentText: attr(\"string\", { optional: true }),\n normsText: attr(\"string\", { optional: true }),\n emailTemplates: attr(\"json\"),\n schedulingJson: attr(\"json\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Intro-call meetings: the source of truth for scheduling; Google Calendar is a\n// projection. Drift fields record when Google disagrees with us.\nconst meetings: Entity = {\n attrs: {\n id: id(),\n applicationId: attr(\"string\", { indexed: true }),\n groupId: attr(\"string\", { indexed: true }),\n startAt: attr(\"number\", { indexed: true }),\n endAt: attr(\"number\"),\n timezone: attr(\"string\"),\n status: attr(\"string\", { indexed: true }),\n googleEventId: attr(\"string\", { indexed: true, optional: true }),\n meetUrl: attr(\"string\", { optional: true }),\n htmlLink: attr(\"string\", { optional: true }),\n drift: attr(\"string\", { indexed: true, optional: true }),\n driftGoogleStartAt: attr(\"number\", { optional: true }),\n driftDetectedAt: attr(\"number\", { optional: true }),\n adoptedFromGoogleAt: attr(\"number\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Audit of every transactional send.\nconst emailLog: Entity = {\n attrs: {\n id: id(),\n groupId: attr(\"string\", { indexed: true }),\n applicationId: attr(\"string\", { indexed: true, optional: true }),\n to: attr(\"string\", { indexed: true }),\n template: attr(\"string\", { indexed: true }),\n subject: attr(\"string\"),\n body: attr(\"string\", { optional: true }),\n transport: attr(\"string\"),\n messageId: attr(\"string\", { optional: true }),\n redirected: attr(\"boolean\", { optional: true }),\n dedupeKey: attr(\"string\", { indexed: true, optional: true }),\n error: attr(\"string\", { optional: true }),\n sentAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** The chapter's own schema + deny-all rules for a mode + auth policy.\n *\n * Operational tables (`applications`/`groups`/`meetings`/`emailLog`) are added in\n * `chapter` mode only. The auth tables follow {@link ResolvedAuth}: `source:\n * \"table\"` adds the `admins` allowlist (hub/BNF); `superAdmins` adds the\n * read-only super-admin tier (default on for the `\"claim\"` ladder). A `\"claim\"`\n * chapter therefore emits exactly Silver & Salt's namespace set — `applications`,\n * `groups`, `meetings`, `emailLog`, `superAdmins` — with no `admins` table. */\nexport function chapterDb(mode: ChapterMode, auth: ResolvedAuth): { schema: DbSchema; rules: DbRules } {\n const entities: Record<string, Entity> = {};\n if (mode === \"chapter\") {\n entities.applications = applications;\n entities.groups = groups;\n entities.meetings = meetings;\n entities.emailLog = emailLog;\n }\n if (auth.source === \"table\") entities.admins = admins;\n if (auth.superAdmins) entities.superAdmins = superAdmins;\n const schema: DbSchema = { entities, links: {} };\n const rules: DbRules = {};\n for (const ns of Object.keys(entities)) {\n rules[ns] = { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" };\n }\n return { schema, rules };\n}\n","// Per-mode default CRM configs. Consumers pass their own via defineChapter's\n// `crm`; these are sensible starting points. `chapter` is a person lead pipeline\n// (fed from `applications`); `hub` adds businesses (people + companies).\nimport type { CrmConfig } from \"@odla-ai/crm\";\nimport type { ChapterMode } from \"./types\";\n\nconst TEMPLATES: CrmConfig[\"templates\"] = {\n personal: {\n class: \"transactional\",\n vars: [\"firstName\", \"subject\", \"body\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\" },\n },\n announcement: {\n class: \"marketing\",\n vars: [\"firstName\", \"subject\", \"body\", \"unsubscribeUrl\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\\n\\n{{unsubscribeUrl}}\" },\n },\n};\n\nfunction personType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Person\",\n labelPlural: \"People\",\n nameField: \"name\",\n emailField: \"email\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n email: { type: \"email\", label: \"Email\" },\n firstName: { type: \"string\", label: \"First name\" },\n lastName: { type: \"string\", label: \"Last name\" },\n phone: { type: \"string\", label: \"Phone\" },\n state: { type: \"string\", label: \"State\", slot: \"s1\" },\n whoYouAre: { type: \"string\", label: \"Who they are\", slot: \"s2\" },\n referral: { type: \"string\", label: \"Referral source\", slot: \"s3\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n focus: { type: \"json\", label: \"Focus areas\" },\n message: { type: \"string\", label: \"Intro message\" },\n },\n pipeline: {\n stages: [\n { id: \"submitted\", label: \"Submitted\" },\n { id: \"paid_pending_vetting\", label: \"Paid, pending vetting\" },\n { id: \"call_scheduled\", label: \"Call scheduled\" },\n { id: \"interviewed\", label: \"Interviewed\" },\n { id: \"approved\", label: \"Approved\" },\n { id: \"declined\", label: \"Declined\" },\n { id: \"refunded\", label: \"Refunded\" },\n ],\n },\n facets: { identity: true, email: true, rank: \"manual\" },\n };\n}\n\nfunction companyType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Business\",\n labelPlural: \"Businesses\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n domain: { type: \"string\", label: \"Domain / website\", slot: \"s1\" },\n industry: { type: \"string\", label: \"Industry\", slot: \"s2\" },\n location: { type: \"string\", label: \"Location\", slot: \"s3\" },\n chapter: { type: \"string\", label: \"Chapter\", slot: \"s4\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n facets: { rank: \"manual\" },\n };\n}\n\n/** The per-mode default CRM config: `chapter` = a person lead pipeline;\n * `hub` = people + businesses with a works_at relation. */\nexport function defaultCrm(mode: ChapterMode): CrmConfig {\n if (mode === \"hub\") {\n return {\n types: { person: personType(), company: companyType() },\n relations: { works_at: { from: \"person\", to: \"company\", label: \"works at\", reverseLabel: \"team\" } },\n templates: TEMPLATES,\n };\n }\n return {\n types: { person: personType() },\n templates: TEMPLATES,\n };\n}\n","// Build the seed `groups` row from a defineChapter config. This is the whole\n// per-chapter payload the worker reads at runtime (prices/policy/emails/\n// scheduling), so nothing brand-specific is hardcoded in the worker. createdAt\n// is stamped by the integration/seed layer, not here.\nimport type { ChapterConfig, ChapterScheduling } from \"./types\";\n\nconst DEFAULT_SCHEDULING: Required<Omit<ChapterScheduling, \"summaryTemplate\">> = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n};\n\nfunction defaultEmailTemplates(name: string): Record<string, { subject: string; text: string }> {\n const sign = `\\n\\nWarmly,\\n${name}`;\n return {\n adminNotification: {\n subject: `New application — {{firstName}} {{lastName}}`,\n text: `A new application came in for ${name}.\\n\\nName: {{firstName}} {{lastName}}\\nEmail: {{email}}`,\n },\n paymentConfirmation: {\n subject: `Welcome to ${name}`,\n text: `Hi {{firstName}},\\n\\nYour membership payment is confirmed. We'll be in touch to schedule your intro call.${sign}`,\n },\n prepEmail: {\n subject: `Your ${name} intro call`,\n text: `Hi {{firstName}},\\n\\nLooking forward to our call at {{meetingTime}}. {{meetingLink}}${sign}`,\n },\n onboardingInvite: {\n subject: `You're in — ${name}`,\n text: `Hi {{firstName}},\\n\\nWelcome to ${name}. Your member area is here: {{membersUrl}}${sign}`,\n },\n };\n}\n\n/** The `groups` row (attrs) for `chapter` mode. Missing config falls back to\n * empty copy / defaults, so a minimal config still provisions cleanly. */\nexport function buildGroupSeed(config: ChapterConfig): Record<string, unknown> {\n const prices = config.prices;\n const emails = config.emails;\n const policy = config.policy ?? {};\n const scheduling = {\n ...DEFAULT_SCHEDULING,\n ...(config.scheduling ?? {}),\n summaryTemplate:\n config.scheduling?.summaryTemplate ?? `${config.name}: introduction call with {{firstName}} {{lastName}}`,\n };\n const row: Record<string, unknown> = {\n id: config.id,\n name: config.name,\n standardPriceCents: prices?.standardCents ?? 0,\n foundingDiscountCents: prices?.foundingDiscountCents ?? 0,\n notificationEmail: emails?.notificationEmail ?? \"\",\n replyTo: emails?.replyTo ?? emails?.notificationEmail ?? \"\",\n disclaimerText: policy.disclaimerText ?? \"\",\n refundPolicyText: policy.refundPolicyText ?? \"\",\n trustCopy: policy.trustCopy ?? \"\",\n emailTemplates: emails?.templates ?? defaultEmailTemplates(config.name),\n schedulingJson: scheduling,\n };\n if (emails?.debugEmail) row.debugEmail = emails.debugEmail;\n if (policy.commitmentText) row.commitmentText = policy.commitmentText;\n if (policy.normsText) row.normsText = policy.normsText;\n return row;\n}\n","// Identity + authorization for a chapter/hub site — the pieces every membership\n// site needs and none should re-derive: a resolved role policy, role resolution\n// from a JWT claim, the privilege-escalation guard, and a tenant-vault read.\n// Everything here is pure or structural (no runtime @odla-ai/db import), so it is\n// trivially testable and the worker stays the only thing that talks to odla-db.\nimport type { ChapterAuth, ChapterMode, ResolvedAuth } from \"./types\";\n\n/**\n * Apply defaults + validate the auth config into a {@link ResolvedAuth}. Defaults\n * by mode: `chapter` → the `provisional/member/admin` claim ladder with the\n * `superAdmins` tier (Silver & Salt); `hub` → the `admins` allowlist table, no\n * super tier (Built Not Found). Throws at import on a bad policy.\n */\nexport function resolveAuth(mode: ChapterMode, auth: ChapterAuth | undefined): ResolvedAuth {\n const a = auth ?? {};\n const source = a.source ?? (mode === \"hub\" ? \"table\" : \"claim\");\n if (source !== \"claim\" && source !== \"table\") {\n throw new Error(`defineChapter.auth.source: must be \"claim\" or \"table\" — got ${JSON.stringify(a.source)}`);\n }\n const claim = a.claim ?? \"role\";\n if (typeof claim !== \"string\" || claim === \"\") {\n throw new Error(\"defineChapter.auth.claim: must be a non-empty string\");\n }\n const ladder = a.ladder ?? [\"provisional\", \"member\", \"admin\"];\n if (!Array.isArray(ladder) || ladder.length === 0 || !ladder.every((r) => typeof r === \"string\" && r !== \"\")) {\n throw new Error(\"defineChapter.auth.ladder: must be a non-empty array of role strings\");\n }\n const adminRole = ladder[ladder.length - 1] as string;\n const superAdmins = a.superAdmins ?? source === \"claim\";\n return { source, claim, ladder, adminRole, superAdmins };\n}\n\n/** The role from a verified JWT payload, per the resolved policy. An unknown or\n * missing claim falls back to the lowest ladder rung (fail safe, never admin). */\nexport function roleFromClaim(payload: Record<string, unknown>, auth: ResolvedAuth): string {\n const raw = payload[auth.claim];\n return typeof raw === \"string\" && auth.ladder.includes(raw) ? raw : (auth.ladder[0] as string);\n}\n\n/** Does a role meet the admin bar (the highest ladder rung)? */\nexport function isAdminRole(role: string, auth: ResolvedAuth): boolean {\n return role === auth.adminRole;\n}\n\n/** Inputs to the role-change guard — resolved by the caller (route) from the\n * identity provider + the read-only `superAdmins` table. */\nexport interface RoleChangeContext {\n actorId: string;\n actorIsSuper: boolean;\n targetId: string;\n targetCurrentRole: string;\n targetIsSuper: boolean;\n newRole: string;\n auth: ResolvedAuth;\n}\n\n/** The result of {@link canChangeRole}: allow, or deny with the HTTP status +\n * message the route should return. */\nexport type GuardResult = { ok: true } | { ok: false; status: number; error: string };\n\n/**\n * The privilege-escalation guard — package-enforced so every site gets it and\n * none re-derives it. Denies: an out-of-ladder role; changing your own role;\n * touching a super-admin unless you are one; and (when a `superAdmins` tier\n * exists) creating or altering an admin unless you are a super-admin. Note the\n * super-admin tier itself is never writable here — it lives in the read-only\n * `superAdmins` table, set only in odla Studio.\n */\nexport function canChangeRole(ctx: RoleChangeContext): GuardResult {\n const { auth } = ctx;\n if (!auth.ladder.includes(ctx.newRole)) {\n return { ok: false, status: 400, error: `role must be one of: ${auth.ladder.join(\", \")}` };\n }\n if (ctx.actorId === ctx.targetId) {\n return { ok: false, status: 400, error: \"you cannot change your own role\" };\n }\n if (ctx.targetIsSuper && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: \"this person is a super-admin; their access is managed in odla Studio\" };\n }\n const touchesAdmin = ctx.newRole === auth.adminRole || ctx.targetCurrentRole === auth.adminRole;\n if (auth.superAdmins && touchesAdmin && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: `only super-admins can create or change an ${auth.adminRole}` };\n }\n return { ok: true };\n}\n\n/** Structural view of odla-db's tenant-vault read, so chapter takes no runtime\n * dependency on @odla-ai/db. The worker's admin client satisfies this. */\nexport interface SecretStore {\n secrets: { get(name: string): Promise<string> };\n}\n\n/**\n * Read a tenant-vault secret by name; `undefined` when it is absent or the vault\n * errors, so callers degrade gracefully (e.g. `paymentsReady: false`) rather than\n * throwing. Never logs the value.\n */\nexport async function getVaultSecret(db: SecretStore, name: string): Promise<string | undefined> {\n try {\n const value = await db.secrets.get(name);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","// The application status pipeline — config, not code. Which statuses exist, which\n// a member can book an intro call from, and which an admin can approve from\n// differ per site; the one invariant every site wants is that status never moves\n// backwards. All of this is pure + tested here; the worker enforces it on every\n// status write, and the CRM record.stage mirrors application.status (never the\n// reverse). Defaults reproduce Silver & Salt's pipeline exactly.\nimport type { ChapterPipeline, ResolvedPipeline } from \"./types\";\n\nconst DEFAULT_STAGES = [\n \"submitted\",\n \"paid_pending_vetting\",\n \"call_scheduled\",\n \"interviewed\",\n \"approved\",\n \"declined\",\n \"refunded\",\n] as const;\nconst DEFAULT_BOOKABLE = [\"submitted\", \"paid_pending_vetting\", \"call_scheduled\"] as const;\nconst DEFAULT_APPROVABLE = [\"paid_pending_vetting\", \"call_scheduled\", \"interviewed\"] as const;\n\n/**\n * Apply defaults + validate the pipeline config. With no config, the full Silver\n * & Salt pipeline. With `stages` given but the subsets omitted, the subsets\n * default to empty (a site opts in to bookable/approvable states explicitly).\n * Throws at import on a bad pipeline (empty/duplicate stages, an initial or a\n * subset entry not on the ladder).\n */\nexport function resolvePipeline(p: ChapterPipeline | undefined): ResolvedPipeline {\n const usingDefaults = !p?.stages;\n const stages = p?.stages ?? [...DEFAULT_STAGES];\n if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => typeof s === \"string\" && s !== \"\")) {\n throw new Error(\"defineChapter.pipeline.stages: must be a non-empty array of status strings\");\n }\n if (new Set(stages).size !== stages.length) {\n throw new Error(\"defineChapter.pipeline.stages: statuses must be unique\");\n }\n const initial = p?.initial ?? (stages[0] as string);\n if (!stages.includes(initial)) {\n throw new Error(`defineChapter.pipeline.initial: \"${initial}\" is not one of the stages`);\n }\n const bookableFrom = p?.bookableFrom ?? (usingDefaults ? [...DEFAULT_BOOKABLE] : []);\n const approvableFrom = p?.approvableFrom ?? (usingDefaults ? [...DEFAULT_APPROVABLE] : []);\n for (const [name, subset] of [\n [\"bookableFrom\", bookableFrom],\n [\"approvableFrom\", approvableFrom],\n ] as const) {\n for (const s of subset) {\n if (!stages.includes(s)) throw new Error(`defineChapter.pipeline.${name}: \"${s}\" is not one of the stages`);\n }\n }\n return { stages, bookableFrom, approvableFrom, initial };\n}\n\n/** The ordinal of a status in the ladder, or -1 if unknown. */\nexport function stageIndex(status: string, p: ResolvedPipeline): number {\n return p.stages.indexOf(status);\n}\n\n/**\n * The status-never-moves-backwards invariant: a transition is allowed only when\n * both statuses are on the ladder and `to` is at or ahead of `from`. The worker\n * calls this before every status write; a violation is a 409, never a silent\n * downgrade.\n */\nexport function canTransition(from: string, to: string, p: ResolvedPipeline): boolean {\n const fi = p.stages.indexOf(from);\n const ti = p.stages.indexOf(to);\n return fi >= 0 && ti >= 0 && ti >= fi;\n}\n\n/** May an intro call be booked from this status? */\nexport function canBook(status: string, p: ResolvedPipeline): boolean {\n return p.bookableFrom.includes(status);\n}\n\n/** May an application be approved (→ member) from this status? */\nexport function canApprove(status: string, p: ResolvedPipeline): boolean {\n return p.approvableFrom.includes(status);\n}\n","// The public member surface logic: the join config a site's join page reads (B1)\n// and the idempotent application submit (B2 validation + B3 exactly-once). Both\n// take the structural ChapterDb, so they're tested against an in-memory fake and\n// carry no runtime @odla-ai/db import. The worker builds the real db client, does\n// Clerk verification, enforces the body cap, and mounts these on chapter routes.\nimport type { Chapter, ChapterApplication, ChapterDb, ResolvedApplication } from \"./types\";\n\n// Silver & Salt's join form. `focus` (a json field) is always accepted.\nconst DEFAULT_REQUIRED = [\"firstName\", \"lastName\", \"email\", \"referral\", \"whoYouAre\", \"message\"];\nconst DEFAULT_OPTIONAL = [\"referralName\", \"linkedin\", \"phone\", \"state\"];\n\n/** Apply defaults + validate the application config. Throws at import on bad shape. */\nexport function resolveApplication(a: ChapterApplication | undefined): ResolvedApplication {\n const required = a?.required ?? DEFAULT_REQUIRED;\n const optional = a?.optional ?? DEFAULT_OPTIONAL;\n for (const [name, arr] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(arr) || !arr.every((f) => typeof f === \"string\" && f !== \"\")) {\n throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);\n }\n }\n return {\n required,\n optional,\n maxLen: a?.maxLen ?? {},\n defaultMaxLen: a?.defaultMaxLen ?? 2000,\n bodyCap: a?.bodyCap ?? 32768,\n };\n}\n\n/** A validated submission, or a 400-worthy validation error the route returns. */\nexport type SubmitResult =\n | { ok: true; id: string; duplicate: boolean; status: string }\n | { ok: false; error: string };\n\n/**\n * Submit a membership application (B2 + B3). Validates the configured required\n * fields + max lengths, writes the `applications` row at the pipeline's initial\n * status, and — when the client supplies a `submissionId` — stamps it as the\n * transaction's mutationId (`join:${submissionId}`) so a double-tap can never\n * create two applications (the second returns `duplicate: true`). Idempotency is\n * package-enforced. `now`/`newId` are injected (deterministic in tests).\n */\nexport async function submitApplication(\n db: ChapterDb,\n chapter: Chapter,\n fields: Record<string, unknown>,\n opts: { submissionId?: string; groupId?: string; now: number; newId: () => string },\n): Promise<SubmitResult> {\n const app = chapter.application;\n for (const f of app.required) {\n const v = fields[f];\n if (typeof v !== \"string\" || v.trim() === \"\") return { ok: false, error: `${f} is required` };\n }\n for (const f of [...app.required, ...app.optional]) {\n const v = fields[f];\n const cap = app.maxLen[f] ?? app.defaultMaxLen;\n if (typeof v === \"string\" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };\n }\n\n const id = opts.newId();\n const row: Record<string, unknown> = { id, status: chapter.pipeline.initial, createdAt: opts.now };\n for (const f of [...app.required, ...app.optional]) {\n if (typeof fields[f] === \"string\") row[f] = (fields[f] as string).trim();\n }\n if (fields.focus !== undefined) row.focus = fields.focus;\n if (opts.groupId) row.groupId = opts.groupId;\n\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: \"applications\", id, attrs: row }],\n opts.submissionId ? { mutationId: `join:${opts.submissionId}` } : undefined,\n );\n return { ok: true, id, duplicate, status: chapter.pipeline.initial };\n}\n\n/** The `groups`-row fields the join config exposes. */\nexport interface JoinConfigGroup {\n id: string;\n name: string;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n disclaimerText?: string;\n refundPolicyText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n}\n\n/**\n * The public join config (B1) a site's join page reads: copy + prices from the\n * group row plus `paymentsReady`. When payments aren't wired the join flow drops\n * the payment step (C2) — the worker computes `paymentsReady` from the group's\n * Stripe keys + vault secret. Pure.\n */\nexport function joinConfig(group: JoinConfigGroup, paymentsReady: boolean): Record<string, unknown> {\n return {\n id: group.id,\n name: group.name,\n standardPriceCents: group.standardPriceCents ?? 0,\n foundingDiscountCents: group.foundingDiscountCents ?? 0,\n disclaimerText: group.disclaimerText ?? \"\",\n refundPolicyText: group.refundPolicyText ?? \"\",\n trustCopy: group.trustCopy ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n paymentsReady,\n };\n}\n","// The CLI-consumable provisioning descriptor. It composes @odla-ai/crm's\n// integration (crm_* namespaces + crm_config seed + route probe) with the\n// chapter's own namespaces and a guarded `groups`-row seed, so a site's\n// odla.config.mjs lists ONE integration. The CLI reads it structurally\n// (matching OdlaIntegration) and merges schema/rules by namespace.\nimport { createCrmIntegration } from \"@odla-ai/crm\";\nimport type { Chapter } from \"./types\";\n\n/** Options for {@link createChapterIntegration}. */\nexport interface ChapterIntegrationOptions {\n /** CRM route mount point. Default \"/api/crm\". */\n basePath?: string;\n /** Seed timestamp override for reproducible builds/tests. */\n now?: number;\n}\n\ninterface IntegrationSeed {\n id: string;\n ns: string;\n key: { attr: string; value: string };\n attrs: Record<string, unknown>;\n}\n\n/** Structural match for the CLI's `OdlaIntegration`. */\nexport interface ChapterIntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n schema: { entities: Record<string, unknown>; links: Record<string, unknown> };\n rules: Record<string, unknown>;\n seeds: IntegrationSeed[];\n probes: Array<{ path: string; expectedStatus: number }>;\n}\n\n/**\n * Build the one CLI-consumable integration for a chapter/hub: the crm_*\n * namespaces + crm_config seed + route probe, merged with the chapter's own\n * namespaces and a guarded `groups`-row seed. Drop it in odla.config.mjs's\n * `integrations` array.\n */\nexport function createChapterIntegration(\n chapter: Chapter,\n options: ChapterIntegrationOptions = {},\n): ChapterIntegrationDescriptor {\n const basePath = options.basePath ?? \"/api/crm\";\n const now = options.now ?? Date.now();\n const emails = chapter.config.emails;\n\n const crmDesc = createCrmIntegration(chapter.crm, {\n basePath,\n now,\n ...(emails?.notificationEmail ? { notificationEmail: emails.notificationEmail } : {}),\n ...(emails?.replyTo ? { replyTo: emails.replyTo } : {}),\n ...(emails?.debugEmail ? { debugEmail: emails.debugEmail } : {}),\n });\n\n const seeds: IntegrationSeed[] = [...(crmDesc.seeds ?? [])];\n const group = chapter.groupSeed();\n if (group) {\n seeds.push({ id: \"group\", ns: \"groups\", key: { attr: \"id\", value: chapter.id }, attrs: { ...group, createdAt: now } });\n }\n\n return {\n id: \"chapter\",\n title: `Chapter — ${chapter.name}`,\n npm: \"@odla-ai/chapter\",\n schema: {\n entities: { ...crmDesc.schema.entities, ...chapter.schema.entities },\n links: { ...crmDesc.schema.links, ...chapter.schema.links },\n },\n rules: { ...crmDesc.rules, ...chapter.rules },\n seeds,\n probes: [...(crmDesc.probes ?? [])],\n };\n}\n","// The chapter email pipeline: exactly-once delivery, a non-production fail-safe,\n// and template rendering. Every property here is easy to get wrong and expensive\n// to get wrong, so the correctness-critical decisions — the dedupe check (E1),\n// the dev-redirect / log-only fail-safe (E2), and template rendering (E4) — are\n// PURE and fully tested in this module. The worker supplies the transport +\n// odla-db and performs the actual send + emailLog write around these decisions.\n//\n// Chapter's operational templates ({ subject, text, enabled? }) are\n// transactional lifecycle mail by construction — a site owner edits the copy in\n// Settings but cannot reclassify one as marketing. Consent-gated marketing blasts\n// go through @odla-ai/crm, which owns the transactional-vs-marketing template\n// class as code (E3), so relabeling copy can never bypass the consent gate.\n\n/** One owner-editable template row on the group. `enabled` absent = enabled. */\nexport interface EmailTemplateRow {\n subject: string;\n text: string;\n enabled?: boolean;\n}\n\n/** The `groups`-row fields the email pipeline reads. */\nexport interface EmailGroup {\n id: string;\n name: string;\n replyTo: string;\n /** Non-prod debug inbox: all mail redirects here outside prod (E2). */\n debugEmail?: string;\n refundPolicyText?: string;\n commitmentText?: string;\n normsText?: string;\n emailTemplates: Record<string, EmailTemplateRow>;\n}\n\n/** `{{placeholder}}` substitution; unknown placeholders render empty. */\nexport function render(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => vars[key] ?? \"\");\n}\n\n/** Group-level vars every template receives, under the caller's vars. */\nfunction groupVars(group: EmailGroup, vars: Record<string, string>): Record<string, string> {\n return {\n ...vars,\n refundPolicyText: group.refundPolicyText ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n };\n}\n\n/**\n * Re-render a template's body for history/preview (E4): the CRM comms history\n * reads back emails whose body predates `emailLog.body` by rendering the current\n * template with the recipient's vars. Same substitution + group vars as the send\n * path. `null` for an unknown template. Reflects the copy as it reads today, not\n * necessarily the exact bytes originally sent (only `emailLog.body` is byte-exact).\n */\nexport function renderTemplateBody(group: EmailGroup, template: string, vars: Record<string, string>): string | null {\n const tpl = group.emailTemplates?.[template];\n if (!tpl) return null;\n return render(tpl.text, groupVars(group, vars));\n}\n\n/**\n * E1 (exactly-once): given the prior `emailLog` rows for a `dedupeKey`, has the\n * mail already been delivered? A prior row with **no error** means yes — the\n * caller short-circuits the resend. Failure rows (which carry an `error` and are\n * written without the dedupe mutationId) do not count, so a retry after a failure\n * can still succeed.\n */\nexport function isAlreadySent(priorRows: ReadonlyArray<{ error?: unknown }>): boolean {\n return priorRows.some((row) => !row.error);\n}\n\n/** The pure delivery decision produced by {@link planDelivery}. */\nexport type DeliveryDecision =\n | { deliver: false; reason: \"template-missing\" | \"disabled\" }\n | {\n deliver: true;\n /** Which transport to use — `log-only` records the send but delivers nothing. */\n transport: \"cloudflare\" | \"log-only\";\n to: string;\n subject: string;\n text: string;\n /** True when redirected to the non-prod debug inbox. */\n redirected: boolean;\n };\n\n/**\n * The pure delivery decision (E2 fail-safe + E3 enabled). Given the env, group,\n * template, recipient, and whether a real Cloudflare transport is wired:\n * - missing template → not delivered (`template-missing`);\n * - disabled template and not forced → not delivered (`disabled`);\n * - **non-prod with a debug inbox** → REDIRECT to it, `\"[dev] \"` subject prefix,\n * a dev-redirect note in the body, so test applicants never receive real mail;\n * - **non-prod with NO debug inbox** → force `log-only` (deliver nothing) — the\n * fail-safe that protects every site's test data;\n * - prod → deliver via the real transport (`cloudflare` if wired, else `log-only`).\n */\nexport function planDelivery(input: {\n envName: string;\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n /** Whether a Cloudflare Email Service transport (binding + verified from) is wired. */\n cloudflareReady: boolean;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}): DeliveryDecision {\n const tpl = input.group.emailTemplates?.[input.template];\n if (!tpl) return { deliver: false, reason: \"template-missing\" };\n if (tpl.enabled === false && !input.force) return { deliver: false, reason: \"disabled\" };\n\n const vars = groupVars(input.group, input.vars);\n const isProd = input.envName === \"prod\";\n const redirect = !isProd && !!input.group.debugEmail;\n const transport: \"cloudflare\" | \"log-only\" =\n !isProd && !redirect ? \"log-only\" : input.cloudflareReady ? \"cloudflare\" : \"log-only\";\n const to = redirect ? (input.group.debugEmail as string) : input.to;\n const subject = (redirect ? \"[dev] \" : \"\") + render(tpl.subject, vars);\n const text = redirect\n ? `(dev redirect; original recipient: ${input.to})\\n\\n` + render(tpl.text, vars)\n : render(tpl.text, vars);\n return { deliver: true, transport, to, subject, text, redirected: redirect };\n}\n","// Payments primitives. The webhook-integrity check below is security-critical and\n// easy to get wrong, so it is pure and tested here; the worker wires a payments\n// provider (Stripe first — subscription create, webhook ingest, refund) around\n// it, and every resulting db write carries an event-derived mutationId for\n// exactly-once. Sites that don't charge omit payments entirely (paymentsReady:\n// false), so nothing here is imported unless a chapter runs the payment flow.\n\n/** Parse a Stripe-style `Stripe-Signature` header (`t=<unix>,v1=<hex>`). */\nfunction parseSigHeader(header: string): { t?: string; v1?: string } {\n const parts: Record<string, string> = {};\n for (const p of header.split(\",\")) {\n const [k, v] = p.split(\"=\", 2);\n if (k && v !== undefined) parts[k] = v;\n }\n return { t: parts.t, v1: parts.v1 };\n}\n\nfunction toHex(buf: ArrayBuffer): string {\n return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time compare of two equal-length hex strings. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * Verify a Stripe webhook signature (C3): HMAC-SHA256 over `` `${t}.${payload}` ``\n * with the endpoint signing secret, a replay window (default 5 minutes), and a\n * constant-time compare. Package-enforced — never left to a site. Returns `false`\n * (never throws) on a malformed header, a non-numeric or stale timestamp, or a\n * signature mismatch. `now`/`toleranceSec` are injectable for tests.\n */\nexport async function verifyStripeSignature(\n payload: string,\n header: string,\n secret: string,\n opts: { now?: number; toleranceSec?: number } = {},\n): Promise<boolean> {\n const { t, v1 } = parseSigHeader(header);\n if (!t || !v1) return false;\n const ts = Number(t);\n if (!Number.isFinite(ts)) return false;\n const nowSec = (opts.now ?? Date.now()) / 1000;\n const tolerance = opts.toleranceSec ?? 300;\n if (Math.abs(nowSec - ts) > tolerance) return false;\n\n const enc = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const mac = await crypto.subtle.sign(\"HMAC\", key, enc.encode(`${t}.${payload}`));\n return timingSafeEqual(toHex(mac), v1);\n}\n","// The hub → chapter people projection (push model). The network hub curates\n// prospects and pushes a person's contact data into THIS chapter's own\n// crm_record, so a chapter admin sees network prospects beside their applicants.\n//\n// Invariants (package-enforced so no site re-derives them):\n// - One-way: the chapter never writes back to the hub through this path.\n// - Idempotent: keyed by the hub's record id (a re-share updates, never\n// duplicates) AND unified by primaryEmail — a shared prospect who later\n// submits an application lands on the SAME crm_record, so the two projections\n// compose instead of forking the person.\n// - A person may be shared with many chapters; that fan-out is hub-side, so each\n// chapter's projection here is independent.\n//\n// Reuses @odla-ai/crm's record ops (full validation via crm.prepare), driven by\n// the resolved chapter CRM engine + the structural ChapterDb.\nimport { createRecord, updateRecord } from \"@odla-ai/crm\";\nimport type { Crm } from \"@odla-ai/crm\";\nimport type { ChapterDb } from \"./types\";\n\n/** The contact data the hub shares for a prospect. `hubRecordId` is the stable\n * idempotency key (the hub's crm_record id). */\nexport interface SharedPerson {\n email: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n hubRecordId: string;\n}\n\n/** Map a shared prospect to a crm `person` input (only the fields the default\n * person type accepts). Name falls back to first+last, then the email. */\nexport function sharedPersonInput(person: SharedPerson): Record<string, unknown> {\n const email = person.email.toLowerCase();\n const fullName = [person.firstName, person.lastName].filter(Boolean).join(\" \").trim();\n const input: Record<string, unknown> = { name: person.name ?? fullName ?? email, email };\n if (input.name === \"\") input.name = email;\n if (person.firstName) input.firstName = person.firstName;\n if (person.lastName) input.lastName = person.lastName;\n if (person.phone) input.phone = person.phone;\n if (person.linkedin) input.linkedin = person.linkedin;\n return input;\n}\n\n/** Deps for the projection — the resolved CRM engine, the structural db, and\n * injected clock/id (deterministic in tests). */\nexport interface ProjectionDeps {\n crm: Crm;\n db: ChapterDb;\n now: () => number;\n newId: () => string;\n}\n\n/**\n * Upsert a hub-shared prospect into this chapter's `crm_record` (push\n * projection). Resolves an existing person by lowercased `primaryEmail` and\n * updates it, else creates one with a `share:${hubRecordId}` mutationId. Returns\n * the chapter-side record id. Callers wrap this in `.catch` so a projection\n * failure never fails the hub's share request.\n */\nexport async function projectSharedRecord(deps: ProjectionDeps, person: SharedPerson): Promise<{ recordId: string }> {\n const email = person.email.toLowerCase();\n const input = sharedPersonInput(person);\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const { crm_record } = await deps.db.query({\n crm_record: { $: { where: { type: \"person\", primaryEmail: email }, limit: 1 } },\n });\n const existing = crm_record?.[0];\n if (existing && typeof existing.id === \"string\") {\n await updateRecord(crmDeps, { id: existing.id, input });\n return { recordId: existing.id };\n }\n const created = await createRecord(crmDeps, { type: \"person\", input, mutationId: `share:${person.hubRecordId}` });\n return { recordId: created.id };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,iBAA0B;;;ACK1B,SAAS,KAAK,MAAgB,QAAqE,CAAC,GAAS;AAC3G,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,MAAM,UAAU;AAAA,IACxB,SAAS,MAAM,WAAW;AAAA,IAC1B,UAAU,MAAM,YAAY;AAAA,EAC9B;AACF;AACA,IAAM,KAAK,MAAY,KAAK,UAAU,EAAE,QAAQ,MAAM,SAAS,KAAK,CAAC;AAKrE,IAAM,S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