@shware/workflow 2.0.0 → 2.0.1
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/config.cjs +2 -2
- package/dist/config.cjs.map +1 -1
- package/dist/config.d.cts +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +2 -2
- package/dist/config.mjs.map +1 -1
- package/dist/contract.cjs.map +1 -1
- package/dist/contract.d.cts +1 -1
- package/dist/contract.d.cts.map +1 -1
- package/dist/contract.d.mts +1 -1
- package/dist/contract.d.mts.map +1 -1
- package/dist/contract.mjs.map +1 -1
- package/dist/dsl/action.cjs.map +1 -1
- package/dist/dsl/action.d.cts +2 -2
- package/dist/dsl/action.d.cts.map +1 -1
- package/dist/dsl/action.d.mts +2 -2
- package/dist/dsl/action.d.mts.map +1 -1
- package/dist/dsl/action.mjs.map +1 -1
- package/dist/dsl/bundle.cjs.map +1 -1
- package/dist/dsl/bundle.d.cts +1 -1
- package/dist/dsl/bundle.d.mts +1 -1
- package/dist/dsl/bundle.mjs.map +1 -1
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +1 -1
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +1 -1
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/refs.cjs.map +1 -1
- package/dist/dsl/refs.d.cts +5 -4
- package/dist/dsl/refs.d.cts.map +1 -1
- package/dist/dsl/refs.d.mts +5 -4
- package/dist/dsl/refs.d.mts.map +1 -1
- package/dist/dsl/refs.mjs.map +1 -1
- package/dist/dsl/template.cjs.map +1 -1
- package/dist/dsl/template.d.cts +2 -2
- package/dist/dsl/template.d.cts.map +1 -1
- package/dist/dsl/template.d.mts +2 -2
- package/dist/dsl/template.d.mts.map +1 -1
- package/dist/dsl/template.mjs.map +1 -1
- package/dist/engine/interpreter.cjs.map +1 -1
- package/dist/engine/interpreter.d.cts.map +1 -1
- package/dist/engine/interpreter.d.mts.map +1 -1
- package/dist/engine/interpreter.mjs.map +1 -1
- package/dist/reporting/tracking.cjs +5 -1
- package/dist/reporting/tracking.cjs.map +1 -1
- package/dist/reporting/tracking.d.cts.map +1 -1
- package/dist/reporting/tracking.d.mts.map +1 -1
- package/dist/reporting/tracking.mjs +5 -1
- package/dist/reporting/tracking.mjs.map +1 -1
- package/dist/store/postgres-reporting.cjs +5 -5
- package/dist/store/postgres-reporting.cjs.map +1 -1
- package/dist/store/postgres-reporting.mjs +5 -5
- package/dist/store/postgres-reporting.mjs.map +1 -1
- package/dist/templates.cjs.map +1 -1
- package/dist/templates.mjs.map +1 -1
- package/package.json +1 -1
package/dist/templates.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.cjs","names":["z"],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as core.$ZodType | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mappings":";;;;;;;AA4KA,SAAgB,gBACd,YACyB;CACzB,iBAAiB,WAAW,IAAI,iBAAiB;CACjD,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,s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;;;AAYA,SAAgB,kBAAkB,UAEhC;CACA,MAAM,QAAQ,eAAe,SAAS,SAAS,KAAK;CACpD,MAAM,OAAO,eAAe,QAAQ,SAAS,IAAI;CACjD,MAAM,UAAU,eAAe,WAAW,SAAS,OAAO;CAC1D,MAAM,QAAQ,eAAe,SAAS,SAAS,KAAK;CACpD,OAAO,EACL,SAAS,EAAE,SAAS,UAAU,SAAS;EACrC,IAAI,YAAY,SAEd,OAAO,mBADO,eAAe,OAAO,SAAS,QACf,GAAG,KAAK;EAExC,IAAI,YAAY,QAAQ;GACtB,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ;GACnD,kBAAkB,OAAO,KAAK;GAC9B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,WAAW;GACzB,MAAM,QAAQ,eAAe,SAAS,WAAW,QAAQ;GACzD,qBAAqB,OAAO,KAAK;GACjC,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,SAAS;GACvB,MAAM,QAAQ,eAAe,OAAO,SAAS,QAAQ;GACrD,mBAAmB,OAAO,KAAK;GAC/B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,OAAO;CACT,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"templates.cjs","names":["z"],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as { _zod?: { def?: core.$ZodTypeDef } } | null | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mapp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AU,GAAG,MAAM,GAAG,SAAS,IAAI;CACxD;AACF;;;;;;;;AASA,SAAS,mBAAmB,KAAuB,OAAe,MAAiC;CACjG,KAAK,MAAM,SAAS,IAAI,UAAU,CAAC,GAAG;EACpC,IAAI,MAAM,KAAK,IAAI,UAAU,UAC3B,KAAK,IAAI,MAAM,uEAAuE;EAExF,IAAI,MAAM,KAAK,IAAI,UAAU,aAC3B,KACE,IAAI,MAAM,qGACZ;CAEJ;AACF;;;;;;;;AAYA,SAAgB,kBAAkB,UAEhC;CACA,MAAM,QAAQ,eAAe,SAAS,SAAS,KAAK;CACpD,MAAM,OAAO,eAAe,QAAQ,SAAS,IAAI;CACjD,MAAM,UAAU,eAAe,WAAW,SAAS,OAAO;CAC1D,MAAM,QAAQ,eAAe,SAAS,SAAS,KAAK;CACpD,OAAO,EACL,SAAS,EAAE,SAAS,UAAU,SAAS;EACrC,IAAI,YAAY,SAEd,OAAO,mBADO,eAAe,OAAO,SAAS,QACf,GAAG,KAAK;EAExC,IAAI,YAAY,QAAQ;GACtB,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ;GACnD,kBAAkB,OAAO,KAAK;GAC9B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,WAAW;GACzB,MAAM,QAAQ,eAAe,SAAS,WAAW,QAAQ;GACzD,qBAAqB,OAAO,KAAK;GACjC,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,SAAS;GACvB,MAAM,QAAQ,eAAe,OAAO,SAAS,QAAQ;GACrD,mBAAmB,OAAO,KAAK;GAC/B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,OAAO;CACT,EACF;AACF"}
|
package/dist/templates.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.mjs","names":[],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as core.$ZodType | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mappings":";;;;AA4KA,SAAgB,gBACd,YACyB;CACzB,iBAAiB,WAAW,IAAI,iBAAiB;CACjD,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;;;;AAMA,SAAgB,cACd,YACkB;CAClB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,oBAAoB,YAAY,kBAAkB,WAAW,GAAG,GAAG;CACnE,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;AAGA,SAAgB,aACd,YACiB;CACjB,iBAAiB,WAAW,IAAI,cAAc;CAC9C,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,QAAQ,WAAW,KAAK;CAC3E,OAAO;EAAE,MAAM;EAAiB,SAAS;EAAG,GAAG;CAAW;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SAAS,QAAQ;GACrD,mBAAmB,OAAO,KAAK;GAC/B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,OAAO;CACT,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"templates.mjs","names":[],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as { _zod?: { def?: core.$ZodTypeDef } } | null | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mappings":";;;;AA4KA,SAAgB,gBACd,YACyB;CACzB,iBAAiB,WAAW,IAAI,iBAAiB;CACjD,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;;;;AAMA,SAAgB,cACd,YACkB;CAClB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,oBAAoB,YAAY,kBAAkB,WAAW,GAAG,GAAG;CACnE,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E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