@geekmidas/constructs 10.0.0-alpha.139 → 10.0.0-alpha.140
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/{ObjectSubscriberBuilder-l-64yUiF.d.cts → ObjectSubscriberBuilder-BuuaYcrm.d.cts} +2 -2
- package/dist/{ObjectSubscriberBuilder-HmBwFn2o.d.mts.map → ObjectSubscriberBuilder-BuuaYcrm.d.cts.map} +1 -1
- package/dist/{ObjectSubscriberBuilder-HmBwFn2o.d.mts → ObjectSubscriberBuilder-CzgYmOUH.d.mts} +2 -2
- package/dist/{ObjectSubscriberBuilder-l-64yUiF.d.cts.map → ObjectSubscriberBuilder-CzgYmOUH.d.mts.map} +1 -1
- package/dist/{Subscriber-BdCtfFXL.d.cts → Subscriber-5rCX1Nph.d.cts} +11 -1
- package/dist/{Subscriber-BdCtfFXL.d.cts.map → Subscriber-5rCX1Nph.d.cts.map} +1 -1
- package/dist/{Subscriber-DDo4HFNn.d.mts → Subscriber-CW_Dl-YR.d.mts} +11 -1
- package/dist/{Subscriber-DDo4HFNn.d.mts.map → Subscriber-CW_Dl-YR.d.mts.map} +1 -1
- package/dist/{SubscriberBuilder-3msj1U2w.mjs → SubscriberBuilder-BL_GTcwh.mjs} +8 -1
- package/dist/SubscriberBuilder-BL_GTcwh.mjs.map +1 -0
- package/dist/{SubscriberBuilder-CQst6Iz3.cjs → SubscriberBuilder-CWzKwX1p.cjs} +8 -1
- package/dist/SubscriberBuilder-CWzKwX1p.cjs.map +1 -0
- package/dist/adaptors/aws.cjs +1 -1
- package/dist/adaptors/aws.d.cts +1 -1
- package/dist/adaptors/aws.d.mts +1 -1
- package/dist/adaptors/aws.mjs +1 -1
- package/dist/adaptors/testing.cjs +121 -3
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +73 -4
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +73 -4
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +119 -5
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/inbox-DZdICa8F.d.mts +195 -0
- package/dist/inbox-DZdICa8F.d.mts.map +1 -0
- package/dist/inbox-DqaxrpEk.d.cts +195 -0
- package/dist/inbox-DqaxrpEk.d.cts.map +1 -0
- package/dist/inbox.cjs +291 -0
- package/dist/inbox.cjs.map +1 -0
- package/dist/inbox.d.cts +2 -0
- package/dist/inbox.d.mts +2 -0
- package/dist/inbox.mjs +283 -0
- package/dist/inbox.mjs.map +1 -0
- package/dist/{runSubscriber-B1Yg4dID.cjs → runSubscriber-CC_2C9F2.cjs} +7 -2
- package/dist/runSubscriber-CC_2C9F2.cjs.map +1 -0
- package/dist/{runSubscriber-JCgkeYbE.mjs → runSubscriber-DyHWp_Lf.mjs} +7 -2
- package/dist/runSubscriber-DyHWp_Lf.mjs.map +1 -0
- package/dist/subscribers/index.cjs +2 -2
- package/dist/subscribers/index.d.cts +2 -2
- package/dist/subscribers/index.d.mts +2 -2
- package/dist/subscribers/index.mjs +2 -2
- package/dist/worker.cjs +71 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +54 -5
- package/dist/worker.d.cts.map +1 -1
- package/dist/worker.d.mts +54 -5
- package/dist/worker.d.mts.map +1 -1
- package/dist/worker.mjs +72 -2
- package/dist/worker.mjs.map +1 -1
- package/package.json +41 -31
- package/dist/SubscriberBuilder-3msj1U2w.mjs.map +0 -1
- package/dist/SubscriberBuilder-CQst6Iz3.cjs.map +0 -1
- package/dist/runSubscriber-B1Yg4dID.cjs.map +0 -1
- package/dist/runSubscriber-JCgkeYbE.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inbox.cjs","names":["canonicalId","provideKey","Topic","INBOX_EVENT","serviceKey","inboxRecipient","parseEmail","createStorageClient"],"sources":["../src/inbox.ts"],"sourcesContent":["/**\n * `Inbox` — mail received at addresses on the stage's domain, each message\n * handled in a worker.\n *\n * ```ts\n * export const requests = new Inbox('Requests', {\n * addresses: ['requests'], // local parts: structural\n * subdomains: true, // requests@<tenant>.<stage domain>\n * });\n *\n * export const onRequest = worker\n * .inbox(requests)\n * .handle(async ({ messages }) => {\n * for (const message of messages) {\n * message.recipient.subdomain; // the tenant, from the envelope\n * message.recipient.tag; // requests+<tag>@\n * }\n * });\n * ```\n *\n * **Its own bucket, and a topic.** An inbox owns the bucket its raw messages\n * are kept in — each target creates it for the inbox, never one the stack\n * already runs — and provides its URL itself, so the bucket is no `objects`\n * node and no object subscriber can be bound to it. It declares the topic\n * each message is announced on, which only the provider publishes to.\n *\n * **One decoder.** Deployed, SES's receipt rule stores the raw message and\n * publishes its receipt notification on the topic. Locally `gkm dev` brings a\n * message in from Mailpit and publishes the same notification; in a feature\n * test `mailbox.receive` does. The handler is handed what {@link InboxClient}\n * makes of that notification, wherever it came from.\n *\n * **The envelope routes.** Which inbox, which tenant and which tag come from\n * the envelope recipient, never from `From:` or `To:`, which the sender wrote.\n */\n\nimport { type ParsedEmail, parseEmail } from '@geekmidas/emailkit/inbound';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tINBOX_EVENT,\n\ttype InboxAddressing,\n\ttype InboxRecipient,\n\tinboxRecipient,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Construct } from './construct-interface';\nimport { Topic } from './topic/Topic';\n\nexport interface InboxOptions {\n\t/**\n\t * The local parts it receives at: `['requests']`. Each also takes a\n\t * `+tag` — `requests+t_8f3k@` — handed to the handler as `recipient.tag`.\n\t */\n\taddresses: readonly string[];\n\t/**\n\t * Receive at `<address>@<label>.<domain>` — one label, a tenant's — rather\n\t * than at the stage's domain itself.\n\t */\n\tsubdomains?: boolean;\n}\n\n/** An inbox declared with no address receives nothing. */\nexport class InboxHasNoAddresses extends Error {\n\tconstructor(readonly inbox: string) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names no address, so it would receive nothing. ` +\n\t\t\t\t`Name the local parts it receives at: addresses: ['requests'].`,\n\t\t);\n\t\tthis.name = 'InboxHasNoAddresses';\n\t}\n}\n\n/** An address that is not a bare local part: `requests@x`, `a+b`, `''`. */\nexport class InboxAddressInvalid extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly address: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names '${address}', which is not a local part. ` +\n\t\t\t\t`Name only what goes before the @ — the domain is the stage's — ` +\n\t\t\t\t`and no '+': every address takes a +tag already.`,\n\t\t);\n\t\tthis.name = 'InboxAddressInvalid';\n\t}\n}\n\n/**\n * A receipt notification the inbox cannot read: not SES's shape, or an action\n * other than the S3 one that stores the message where the decoder reads it.\n */\nexport class ReceiptNotificationMalformed extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' was handed a notification it cannot read: ${reason}. ` +\n\t\t\t\t`It reads SES receipt notifications whose action stored the message in S3.`,\n\t\t);\n\t\tthis.name = 'ReceiptNotificationMalformed';\n\t}\n}\n\n/**\n * A provider's verdict on a message.\n *\n * `'unavailable'` where nothing judged it — locally, always — and never a\n * faked `'pass'`.\n */\nexport type Verdict = 'pass' | 'fail' | 'gray' | 'unavailable';\n\n/** What the provider judged of a message, which the message cannot say of itself. */\nexport interface Verdicts {\n\tspf: Verdict;\n\tdkim: Verdict;\n\tdmarc: Verdict;\n\tspam: Verdict;\n\tvirus: Verdict;\n}\n\n/**\n * One received message, for one recipient it was delivered to.\n *\n * `recipient` is the envelope's; every other address is a header, written by\n * the sender. Inbound mail is untrusted input: route on `recipient`, treat\n * `from` as a claim until `verdicts.dmarc` passes *and* the address is known,\n * sanitise `html`, and never use an attachment's filename as a key or path.\n */\nexport interface InboxMessage\n\textends Omit<ParsedEmail, 'attachments'>,\n\t\tPick<ParsedEmail, 'attachments'> {\n\trecipient: InboxRecipient;\n\t/**\n\t * Where the raw message is kept: the bucket SES stored it in (`mailpit`\n\t * locally), and its key there.\n\t */\n\traw: { bucket: string; key: string };\n\tverdicts: Verdicts;\n}\n\n/** A status as SES writes one: `PASS`, `FAIL`, `GRAY`, `PROCESSING_FAILED`, `DISABLED`. */\ninterface ReceiptVerdict {\n\tstatus: string;\n}\n\n/**\n * SES's receipt notification — the part an inbox reads.\n *\n * `gkm dev` and the test mailbox publish the same shape, with every verdict\n * `UNAVAILABLE`, so one decoder serves all three.\n */\nexport interface ReceiptNotification {\n\tnotificationType: 'Received';\n\tmail: {\n\t\tmessageId: string;\n\t\ttimestamp: string;\n\t\t/** The envelope sender (`MAIL FROM`). */\n\t\tsource: string;\n\t\tdestination: string[];\n\t};\n\treceipt: {\n\t\ttimestamp: string;\n\t\t/** The envelope recipients this receipt rule matched. */\n\t\trecipients: string[];\n\t\tspamVerdict?: ReceiptVerdict;\n\t\tvirusVerdict?: ReceiptVerdict;\n\t\tspfVerdict?: ReceiptVerdict;\n\t\tdkimVerdict?: ReceiptVerdict;\n\t\tdmarcVerdict?: ReceiptVerdict;\n\t\taction: {\n\t\t\ttype: string;\n\t\t\tbucketName?: string;\n\t\t\tobjectKey?: string;\n\t\t\ttopicArn?: string;\n\t\t};\n\t};\n}\n\n/** What the handler's inbox is: its domain, its raw messages, the decoder. */\nexport interface InboxClient {\n\t/** The stage's domain it receives on. */\n\treadonly domain: string;\n\t/** A raw message's bytes, by its key in the bucket. */\n\traw(key: string): Promise<Uint8Array>;\n\t/**\n\t * The messages a notification announces: one per envelope recipient this\n\t * inbox receives at, parsed. Empty when none is — a receipt rule that takes\n\t * a whole domain stores mail for addresses no inbox declared.\n\t */\n\tmessages(notification: ReceiptNotification): Promise<InboxMessage[]>;\n}\n\n/** A schema that takes a receipt notification as it is — SES wrote it, not the app. */\nconst RECEIPT_NOTIFICATION: StandardSchemaV1<ReceiptNotification> = {\n\t'~standard': {\n\t\tversion: 1,\n\t\tvendor: 'geekmidas',\n\t\tvalidate: (value) => ({ value: value as ReceiptNotification }),\n\t},\n};\n\ntype InboxTopic = Topic<string, { [INBOX_EVENT]: typeof RECEIPT_NOTIFICATION }>;\n\nexport class Inbox<TName extends string = string>\n\timplements Construct<TName, InboxClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, InboxClient>;\n\t/** Where each received message is announced. Published to by the provider only. */\n\treadonly topic: InboxTopic;\n\n\t/** The local parts it receives at, and whether on a tenant's subdomain. */\n\treadonly addressing: InboxAddressing;\n\tprivate readonly addresses: readonly string[];\n\tprivate readonly subdomains: boolean;\n\tprivate readonly keys: { url: string; domain: string };\n\n\tconstructor(name: ConstructName<TName>, options: InboxOptions) {\n\t\tconst canonical = canonicalId(name as string);\n\t\tif (options.addresses.length === 0) {\n\t\t\tthrow new InboxHasNoAddresses(canonical);\n\t\t}\n\t\tfor (const address of options.addresses) {\n\t\t\tif (!/^[a-z0-9][a-z0-9._-]*$/i.test(address)) {\n\t\t\t\tthrow new InboxAddressInvalid(canonical, address);\n\t\t\t}\n\t\t}\n\n\t\tthis.id = canonical as TName;\n\t\tthis.addresses = options.addresses.map((a) => a.toLowerCase());\n\t\tthis.subdomains = options.subdomains === true;\n\t\tthis.addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t};\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tdomain: provideKey(canonical, 'domain'),\n\t\t};\n\t\tthis.topic = new Topic(`${canonical}Mail`, {\n\t\t\tevents: { [INBOX_EVENT]: RECEIPT_NOTIFICATION },\n\t\t}) as InboxTopic;\n\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (register) => this.connect(register),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t...this.topic.declare(),\n\t\t\t{\n\t\t\t\tkind: 'inbox',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.url, this.keys.domain],\n\t\t\t\taddresses: this.addresses,\n\t\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t\t\ttopic: this.topic.id,\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(\n\t\tregister: ServiceRegisterOptions,\n\t): Promise<InboxClient> {\n\t\tconst { url, domain } = register.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.keys.url).string(),\n\t\t\t\tdomain: get(this.keys.domain).string(),\n\t\t\t}))\n\t\t\t.parse();\n\t\tconst read = rawReader(url);\n\t\tconst addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\tsubdomains: this.subdomains,\n\t\t};\n\t\tconst inbox = this.id;\n\n\t\tconst raw = async (key: string): Promise<Uint8Array> => {\n\t\t\tconst response = await fetch(await read(key));\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new RawMessageUnreadable(inbox, key, response.status);\n\t\t\t}\n\t\t\treturn new Uint8Array(await response.arrayBuffer());\n\t\t};\n\n\t\treturn {\n\t\t\tdomain,\n\t\t\traw,\n\t\t\tasync messages(notification) {\n\t\t\t\tconst { receipt } = assertReceipt(inbox, notification);\n\t\t\t\tconst recipients = receipt.recipients.flatMap((address) => {\n\t\t\t\t\tconst recipient = inboxRecipient(address, addressing, domain);\n\t\t\t\t\treturn recipient ? [recipient] : [];\n\t\t\t\t});\n\t\t\t\tif (recipients.length === 0) return [];\n\n\t\t\t\tconst key = receipt.action.objectKey!;\n\t\t\t\tconst parsed = await parseEmail(await raw(key));\n\t\t\t\tconst verdicts = verdictsOf(receipt);\n\t\t\t\treturn recipients.map((recipient) => ({\n\t\t\t\t\t...parsed,\n\t\t\t\t\trecipient,\n\t\t\t\t\traw: { bucket: receipt.action.bucketName!, key },\n\t\t\t\t\tverdicts,\n\t\t\t\t}));\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * Where a raw message is read from, by its key, for the store `url` names:\n * an `s3://` bucket deployed — SES stored it at `messages/<id>` — or, locally,\n * Mailpit's API, which keeps every message it receives under its own id.\n *\n * The one place local and deployed differ; everything that reads a message\n * goes through it.\n */\nfunction rawReader(url: string): (key: string) => Promise<string> {\n\tif (url.startsWith('s3:')) {\n\t\tconst bucket = createStorageClient(url);\n\t\treturn async (key) => (await bucket).getDownloadURL({ path: key });\n\t}\n\tconst base = url.replace(/\\/+$/, '');\n\treturn async (key) => `${base}/api/v1/message/${encodeURIComponent(key)}/raw`;\n}\n\n/** The raw message a notification names could not be read from its store. */\nexport class RawMessageUnreadable extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly key: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' could not read its raw message '${key}' (HTTP ${status}). ` +\n\t\t\t\t`It is written by the receipt rule before the notification is sent; ` +\n\t\t\t\t`check the bucket's policy lets the process that runs the handler read it.`,\n\t\t);\n\t\tthis.name = 'RawMessageUnreadable';\n\t}\n}\n\nfunction assertReceipt(inbox: string, value: unknown): ReceiptNotification {\n\tconst notification = value as Partial<ReceiptNotification> | undefined;\n\tif (notification?.notificationType !== 'Received') {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its notificationType is '${String(notification?.notificationType)}', not 'Received'`,\n\t\t);\n\t}\n\tconst action = notification.receipt?.action;\n\tif (action?.type !== 'S3' || !action.objectKey || !action.bucketName) {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its action is '${String(action?.type)}' without an S3 object`,\n\t\t);\n\t}\n\tif (!Array.isArray(notification.receipt?.recipients)) {\n\t\tthrow new ReceiptNotificationMalformed(inbox, 'it names no recipients');\n\t}\n\treturn notification as ReceiptNotification;\n}\n\nfunction verdict(status: ReceiptVerdict | undefined): Verdict {\n\tswitch (status?.status) {\n\t\tcase 'PASS':\n\t\t\treturn 'pass';\n\t\tcase 'FAIL':\n\t\t\treturn 'fail';\n\t\tcase 'GRAY':\n\t\t\treturn 'gray';\n\t\tdefault:\n\t\t\treturn 'unavailable';\n\t}\n}\n\nfunction verdictsOf(receipt: ReceiptNotification['receipt']): Verdicts {\n\treturn {\n\t\tspf: verdict(receipt.spfVerdict),\n\t\tdkim: verdict(receipt.dkimVerdict),\n\t\tdmarc: verdict(receipt.dmarcVerdict),\n\t\tspam: verdict(receipt.spamVerdict),\n\t\tvirus: verdict(receipt.virusVerdict),\n\t};\n}\n\n/**\n * The receipt notification a provider that judges nothing publishes —\n * `gkm dev` and the test mailbox — for a message stored at `objectKey`.\n */\nexport function unjudgedReceipt(options: {\n\tmessageId: string;\n\tsource: string;\n\trecipients: readonly string[];\n\tbucketName: string;\n\tobjectKey: string;\n\tverdicts?: Partial<Verdicts>;\n\ttimestamp?: Date;\n}): ReceiptNotification {\n\tconst at = (options.timestamp ?? new Date()).toISOString();\n\tconst status = (v: Verdict | undefined): ReceiptVerdict => ({\n\t\tstatus: v ? v.toUpperCase() : 'UNAVAILABLE',\n\t});\n\treturn {\n\t\tnotificationType: 'Received',\n\t\tmail: {\n\t\t\tmessageId: options.messageId,\n\t\t\ttimestamp: at,\n\t\t\tsource: options.source,\n\t\t\tdestination: [...options.recipients],\n\t\t},\n\t\treceipt: {\n\t\t\ttimestamp: at,\n\t\t\trecipients: [...options.recipients],\n\t\t\tspfVerdict: status(options.verdicts?.spf),\n\t\t\tdkimVerdict: status(options.verdicts?.dkim),\n\t\t\tdmarcVerdict: status(options.verdicts?.dmarc),\n\t\t\tspamVerdict: status(options.verdicts?.spam),\n\t\t\tvirusVerdict: status(options.verdicts?.virus),\n\t\t\taction: {\n\t\t\t\ttype: 'S3',\n\t\t\t\tbucketName: options.bucketName,\n\t\t\t\tobjectKey: options.objectKey,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** An inbox, as the receiver routes to it. */\nexport interface ReceivingInbox {\n\tid: string;\n\taddressing: InboxAddressing;\n\t/** The stage's domain it receives on. */\n\tdomain: string;\n\t/** Announce a received message on the inbox's topic. */\n\tpublish(notification: ReceiptNotification): Promise<void>;\n}\n\n/** A message that arrived where a provider that judges nothing stores mail. */\nexport interface ArrivedMessage {\n\t/** Its key in that store — Mailpit's message id locally. */\n\tkey: string;\n\t/** Where the store is, as a notification names it: `mailpit`. */\n\tstore: string;\n\t/** The envelope sender. */\n\tfrom: string;\n\t/** The envelope recipients — never `To:`. */\n\trecipients: readonly string[];\n\t/** What a test says the provider judged; `'unavailable'` otherwise. */\n\tverdicts?: Partial<Verdicts>;\n}\n\n/**\n * Receive a message the way a receipt rule does: for each inbox one of its\n * envelope recipients is addressed to, publish the receipt notification for\n * those recipients on the inbox's topic. What no inbox receives at goes\n * nowhere — mail the app sent to anyone else included.\n *\n * The one receiver for every local path: Mailpit's webhook under `gkm dev`\n * and a local compose stack, and `mailbox.receive` in a feature test. SES is\n * the receiver deployed. Returns the ids of the inboxes it announced to.\n */\nexport async function receiveMail(\n\tmessage: ArrivedMessage,\n\tinboxes: readonly ReceivingInbox[],\n): Promise<string[]> {\n\tconst received: string[] = [];\n\tfor (const inbox of inboxes) {\n\t\tconst recipients = message.recipients.filter((address) =>\n\t\t\tinboxRecipient(address, inbox.addressing, inbox.domain),\n\t\t);\n\t\tif (recipients.length === 0) continue;\n\t\tawait inbox.publish(\n\t\t\tunjudgedReceipt({\n\t\t\t\tmessageId: message.key,\n\t\t\t\tsource: message.from,\n\t\t\t\trecipients,\n\t\t\t\tbucketName: message.store,\n\t\t\t\tobjectKey: message.key,\n\t\t\t\t...(message.verdicts ? { verdicts: message.verdicts } : {}),\n\t\t\t}),\n\t\t);\n\t\treceived.push(inbox.id);\n\t}\n\treturn received;\n}\n\n/** Whether `value` is an {@link Inbox}. */\nexport function isInbox(value: unknown): value is Inbox {\n\treturn value instanceof Inbox;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,GAC7CF,oBAAAA,eAAAA,CAAe,SAAS,MAAM,YAAY,MAAM,MAAM,CACvD;EACA,IAAI,WAAW,WAAW,GAAG;EAC7B,MAAM,MAAM,QACX,gBAAgB;GACf,WAAW,QAAQ;GACnB,QAAQ,QAAQ;GAChB;GACA,YAAY,QAAQ;GACpB,WAAW,QAAQ;GACnB,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;EAC1D,CAAC,CACF;EACA,SAAS,KAAK,MAAM,EAAE;CACvB;CACA,OAAO;AACR;;AAGA,SAAgB,QAAQ,OAAgC;CACvD,OAAO,iBAAiB;AACzB"}
|
package/dist/inbox.d.cts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as InboxHasNoAddresses, c as RawMessageUnreadable, d as ReceivingInbox, f as Verdict, g as unjudgedReceipt, h as receiveMail, i as InboxClient, l as ReceiptNotification, m as isInbox, n as Inbox, o as InboxMessage, p as Verdicts, r as InboxAddressInvalid, s as InboxOptions, t as ArrivedMessage, u as ReceiptNotificationMalformed } from "./inbox-DqaxrpEk.cjs";
|
|
2
|
+
export { ArrivedMessage, Inbox, InboxAddressInvalid, InboxClient, InboxHasNoAddresses, InboxMessage, InboxOptions, RawMessageUnreadable, ReceiptNotification, ReceiptNotificationMalformed, ReceivingInbox, Verdict, Verdicts, isInbox, receiveMail, unjudgedReceipt };
|
package/dist/inbox.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as InboxHasNoAddresses, c as RawMessageUnreadable, d as ReceivingInbox, f as Verdict, g as unjudgedReceipt, h as receiveMail, i as InboxClient, l as ReceiptNotification, m as isInbox, n as Inbox, o as InboxMessage, p as Verdicts, r as InboxAddressInvalid, s as InboxOptions, t as ArrivedMessage, u as ReceiptNotificationMalformed } from "./inbox-DZdICa8F.mjs";
|
|
2
|
+
export { ArrivedMessage, Inbox, InboxAddressInvalid, InboxClient, InboxHasNoAddresses, InboxMessage, InboxOptions, RawMessageUnreadable, ReceiptNotification, ReceiptNotificationMalformed, ReceivingInbox, Verdict, Verdicts, isInbox, receiveMail, unjudgedReceipt };
|
package/dist/inbox.mjs
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { t as Topic } from "./Topic-DN2gYJ-p.mjs";
|
|
2
|
+
import { INBOX_EVENT, canonicalId, inboxRecipient, provideKey, serviceKey } from "@geekmidas/manifest";
|
|
3
|
+
import { createStorageClient } from "@geekmidas/storage";
|
|
4
|
+
import { parseEmail } from "@geekmidas/emailkit/inbound";
|
|
5
|
+
//#region src/inbox.ts
|
|
6
|
+
/**
|
|
7
|
+
* `Inbox` — mail received at addresses on the stage's domain, each message
|
|
8
|
+
* handled in a worker.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* export const requests = new Inbox('Requests', {
|
|
12
|
+
* addresses: ['requests'], // local parts: structural
|
|
13
|
+
* subdomains: true, // requests@<tenant>.<stage domain>
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* export const onRequest = worker
|
|
17
|
+
* .inbox(requests)
|
|
18
|
+
* .handle(async ({ messages }) => {
|
|
19
|
+
* for (const message of messages) {
|
|
20
|
+
* message.recipient.subdomain; // the tenant, from the envelope
|
|
21
|
+
* message.recipient.tag; // requests+<tag>@
|
|
22
|
+
* }
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* **Its own bucket, and a topic.** An inbox owns the bucket its raw messages
|
|
27
|
+
* are kept in — each target creates it for the inbox, never one the stack
|
|
28
|
+
* already runs — and provides its URL itself, so the bucket is no `objects`
|
|
29
|
+
* node and no object subscriber can be bound to it. It declares the topic
|
|
30
|
+
* each message is announced on, which only the provider publishes to.
|
|
31
|
+
*
|
|
32
|
+
* **One decoder.** Deployed, SES's receipt rule stores the raw message and
|
|
33
|
+
* publishes its receipt notification on the topic. Locally `gkm dev` brings a
|
|
34
|
+
* message in from Mailpit and publishes the same notification; in a feature
|
|
35
|
+
* test `mailbox.receive` does. The handler is handed what {@link InboxClient}
|
|
36
|
+
* makes of that notification, wherever it came from.
|
|
37
|
+
*
|
|
38
|
+
* **The envelope routes.** Which inbox, which tenant and which tag come from
|
|
39
|
+
* the envelope recipient, never from `From:` or `To:`, which the sender wrote.
|
|
40
|
+
*/
|
|
41
|
+
/** An inbox declared with no address receives nothing. */
|
|
42
|
+
var InboxHasNoAddresses = class extends Error {
|
|
43
|
+
inbox;
|
|
44
|
+
constructor(inbox) {
|
|
45
|
+
super(`The inbox '${inbox}' names no address, so it would receive nothing. Name the local parts it receives at: addresses: ['requests'].`);
|
|
46
|
+
this.inbox = inbox;
|
|
47
|
+
this.name = "InboxHasNoAddresses";
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/** An address that is not a bare local part: `requests@x`, `a+b`, `''`. */
|
|
51
|
+
var InboxAddressInvalid = class extends Error {
|
|
52
|
+
inbox;
|
|
53
|
+
address;
|
|
54
|
+
constructor(inbox, address) {
|
|
55
|
+
super(`The inbox '${inbox}' names '${address}', which is not a local part. Name only what goes before the @ — the domain is the stage's — and no '+': every address takes a +tag already.`);
|
|
56
|
+
this.inbox = inbox;
|
|
57
|
+
this.address = address;
|
|
58
|
+
this.name = "InboxAddressInvalid";
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* A receipt notification the inbox cannot read: not SES's shape, or an action
|
|
63
|
+
* other than the S3 one that stores the message where the decoder reads it.
|
|
64
|
+
*/
|
|
65
|
+
var ReceiptNotificationMalformed = class extends Error {
|
|
66
|
+
inbox;
|
|
67
|
+
reason;
|
|
68
|
+
constructor(inbox, reason) {
|
|
69
|
+
super(`The inbox '${inbox}' was handed a notification it cannot read: ${reason}. It reads SES receipt notifications whose action stored the message in S3.`);
|
|
70
|
+
this.inbox = inbox;
|
|
71
|
+
this.reason = reason;
|
|
72
|
+
this.name = "ReceiptNotificationMalformed";
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
/** A schema that takes a receipt notification as it is — SES wrote it, not the app. */
|
|
76
|
+
const RECEIPT_NOTIFICATION = { "~standard": {
|
|
77
|
+
version: 1,
|
|
78
|
+
vendor: "geekmidas",
|
|
79
|
+
validate: (value) => ({ value })
|
|
80
|
+
} };
|
|
81
|
+
var Inbox = class {
|
|
82
|
+
id;
|
|
83
|
+
service;
|
|
84
|
+
/** Where each received message is announced. Published to by the provider only. */
|
|
85
|
+
topic;
|
|
86
|
+
/** The local parts it receives at, and whether on a tenant's subdomain. */
|
|
87
|
+
addressing;
|
|
88
|
+
addresses;
|
|
89
|
+
subdomains;
|
|
90
|
+
keys;
|
|
91
|
+
constructor(name, options) {
|
|
92
|
+
const canonical = canonicalId(name);
|
|
93
|
+
if (options.addresses.length === 0) throw new InboxHasNoAddresses(canonical);
|
|
94
|
+
for (const address of options.addresses) if (!/^[a-z0-9][a-z0-9._-]*$/i.test(address)) throw new InboxAddressInvalid(canonical, address);
|
|
95
|
+
this.id = canonical;
|
|
96
|
+
this.addresses = options.addresses.map((a) => a.toLowerCase());
|
|
97
|
+
this.subdomains = options.subdomains === true;
|
|
98
|
+
this.addressing = {
|
|
99
|
+
addresses: this.addresses,
|
|
100
|
+
...this.subdomains ? { subdomains: true } : {}
|
|
101
|
+
};
|
|
102
|
+
this.keys = {
|
|
103
|
+
url: provideKey(canonical, "url"),
|
|
104
|
+
domain: provideKey(canonical, "domain")
|
|
105
|
+
};
|
|
106
|
+
this.topic = new Topic(`${canonical}Mail`, { events: { [INBOX_EVENT]: RECEIPT_NOTIFICATION } });
|
|
107
|
+
this.service = {
|
|
108
|
+
serviceName: serviceKey(canonical),
|
|
109
|
+
register: (register) => this.connect(register)
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
declare() {
|
|
113
|
+
return [...this.topic.declare(), {
|
|
114
|
+
kind: "inbox",
|
|
115
|
+
id: this.id,
|
|
116
|
+
provides: [this.keys.url, this.keys.domain],
|
|
117
|
+
addresses: this.addresses,
|
|
118
|
+
...this.subdomains ? { subdomains: true } : {},
|
|
119
|
+
topic: this.topic.id
|
|
120
|
+
}];
|
|
121
|
+
}
|
|
122
|
+
async connect(register) {
|
|
123
|
+
const { url, domain } = register.envParser.create((get) => ({
|
|
124
|
+
url: get(this.keys.url).string(),
|
|
125
|
+
domain: get(this.keys.domain).string()
|
|
126
|
+
})).parse();
|
|
127
|
+
const read = rawReader(url);
|
|
128
|
+
const addressing = {
|
|
129
|
+
addresses: this.addresses,
|
|
130
|
+
subdomains: this.subdomains
|
|
131
|
+
};
|
|
132
|
+
const inbox = this.id;
|
|
133
|
+
const raw = async (key) => {
|
|
134
|
+
const response = await fetch(await read(key));
|
|
135
|
+
if (!response.ok) throw new RawMessageUnreadable(inbox, key, response.status);
|
|
136
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
domain,
|
|
140
|
+
raw,
|
|
141
|
+
async messages(notification) {
|
|
142
|
+
const { receipt } = assertReceipt(inbox, notification);
|
|
143
|
+
const recipients = receipt.recipients.flatMap((address) => {
|
|
144
|
+
const recipient = inboxRecipient(address, addressing, domain);
|
|
145
|
+
return recipient ? [recipient] : [];
|
|
146
|
+
});
|
|
147
|
+
if (recipients.length === 0) return [];
|
|
148
|
+
const key = receipt.action.objectKey;
|
|
149
|
+
const parsed = await parseEmail(await raw(key));
|
|
150
|
+
const verdicts = verdictsOf(receipt);
|
|
151
|
+
return recipients.map((recipient) => ({
|
|
152
|
+
...parsed,
|
|
153
|
+
recipient,
|
|
154
|
+
raw: {
|
|
155
|
+
bucket: receipt.action.bucketName,
|
|
156
|
+
key
|
|
157
|
+
},
|
|
158
|
+
verdicts
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Where a raw message is read from, by its key, for the store `url` names:
|
|
166
|
+
* an `s3://` bucket deployed — SES stored it at `messages/<id>` — or, locally,
|
|
167
|
+
* Mailpit's API, which keeps every message it receives under its own id.
|
|
168
|
+
*
|
|
169
|
+
* The one place local and deployed differ; everything that reads a message
|
|
170
|
+
* goes through it.
|
|
171
|
+
*/
|
|
172
|
+
function rawReader(url) {
|
|
173
|
+
if (url.startsWith("s3:")) {
|
|
174
|
+
const bucket = createStorageClient(url);
|
|
175
|
+
return async (key) => (await bucket).getDownloadURL({ path: key });
|
|
176
|
+
}
|
|
177
|
+
const base = url.replace(/\/+$/, "");
|
|
178
|
+
return async (key) => `${base}/api/v1/message/${encodeURIComponent(key)}/raw`;
|
|
179
|
+
}
|
|
180
|
+
/** The raw message a notification names could not be read from its store. */
|
|
181
|
+
var RawMessageUnreadable = class extends Error {
|
|
182
|
+
inbox;
|
|
183
|
+
key;
|
|
184
|
+
status;
|
|
185
|
+
constructor(inbox, key, status) {
|
|
186
|
+
super(`The inbox '${inbox}' could not read its raw message '${key}' (HTTP ${status}). It is written by the receipt rule before the notification is sent; check the bucket's policy lets the process that runs the handler read it.`);
|
|
187
|
+
this.inbox = inbox;
|
|
188
|
+
this.key = key;
|
|
189
|
+
this.status = status;
|
|
190
|
+
this.name = "RawMessageUnreadable";
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
function assertReceipt(inbox, value) {
|
|
194
|
+
const notification = value;
|
|
195
|
+
if (notification?.notificationType !== "Received") throw new ReceiptNotificationMalformed(inbox, `its notificationType is '${String(notification?.notificationType)}', not 'Received'`);
|
|
196
|
+
const action = notification.receipt?.action;
|
|
197
|
+
if (action?.type !== "S3" || !action.objectKey || !action.bucketName) throw new ReceiptNotificationMalformed(inbox, `its action is '${String(action?.type)}' without an S3 object`);
|
|
198
|
+
if (!Array.isArray(notification.receipt?.recipients)) throw new ReceiptNotificationMalformed(inbox, "it names no recipients");
|
|
199
|
+
return notification;
|
|
200
|
+
}
|
|
201
|
+
function verdict(status) {
|
|
202
|
+
switch (status?.status) {
|
|
203
|
+
case "PASS": return "pass";
|
|
204
|
+
case "FAIL": return "fail";
|
|
205
|
+
case "GRAY": return "gray";
|
|
206
|
+
default: return "unavailable";
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function verdictsOf(receipt) {
|
|
210
|
+
return {
|
|
211
|
+
spf: verdict(receipt.spfVerdict),
|
|
212
|
+
dkim: verdict(receipt.dkimVerdict),
|
|
213
|
+
dmarc: verdict(receipt.dmarcVerdict),
|
|
214
|
+
spam: verdict(receipt.spamVerdict),
|
|
215
|
+
virus: verdict(receipt.virusVerdict)
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The receipt notification a provider that judges nothing publishes —
|
|
220
|
+
* `gkm dev` and the test mailbox — for a message stored at `objectKey`.
|
|
221
|
+
*/
|
|
222
|
+
function unjudgedReceipt(options) {
|
|
223
|
+
const at = (options.timestamp ?? /* @__PURE__ */ new Date()).toISOString();
|
|
224
|
+
const status = (v) => ({ status: v ? v.toUpperCase() : "UNAVAILABLE" });
|
|
225
|
+
return {
|
|
226
|
+
notificationType: "Received",
|
|
227
|
+
mail: {
|
|
228
|
+
messageId: options.messageId,
|
|
229
|
+
timestamp: at,
|
|
230
|
+
source: options.source,
|
|
231
|
+
destination: [...options.recipients]
|
|
232
|
+
},
|
|
233
|
+
receipt: {
|
|
234
|
+
timestamp: at,
|
|
235
|
+
recipients: [...options.recipients],
|
|
236
|
+
spfVerdict: status(options.verdicts?.spf),
|
|
237
|
+
dkimVerdict: status(options.verdicts?.dkim),
|
|
238
|
+
dmarcVerdict: status(options.verdicts?.dmarc),
|
|
239
|
+
spamVerdict: status(options.verdicts?.spam),
|
|
240
|
+
virusVerdict: status(options.verdicts?.virus),
|
|
241
|
+
action: {
|
|
242
|
+
type: "S3",
|
|
243
|
+
bucketName: options.bucketName,
|
|
244
|
+
objectKey: options.objectKey
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Receive a message the way a receipt rule does: for each inbox one of its
|
|
251
|
+
* envelope recipients is addressed to, publish the receipt notification for
|
|
252
|
+
* those recipients on the inbox's topic. What no inbox receives at goes
|
|
253
|
+
* nowhere — mail the app sent to anyone else included.
|
|
254
|
+
*
|
|
255
|
+
* The one receiver for every local path: Mailpit's webhook under `gkm dev`
|
|
256
|
+
* and a local compose stack, and `mailbox.receive` in a feature test. SES is
|
|
257
|
+
* the receiver deployed. Returns the ids of the inboxes it announced to.
|
|
258
|
+
*/
|
|
259
|
+
async function receiveMail(message, inboxes) {
|
|
260
|
+
const received = [];
|
|
261
|
+
for (const inbox of inboxes) {
|
|
262
|
+
const recipients = message.recipients.filter((address) => inboxRecipient(address, inbox.addressing, inbox.domain));
|
|
263
|
+
if (recipients.length === 0) continue;
|
|
264
|
+
await inbox.publish(unjudgedReceipt({
|
|
265
|
+
messageId: message.key,
|
|
266
|
+
source: message.from,
|
|
267
|
+
recipients,
|
|
268
|
+
bucketName: message.store,
|
|
269
|
+
objectKey: message.key,
|
|
270
|
+
...message.verdicts ? { verdicts: message.verdicts } : {}
|
|
271
|
+
}));
|
|
272
|
+
received.push(inbox.id);
|
|
273
|
+
}
|
|
274
|
+
return received;
|
|
275
|
+
}
|
|
276
|
+
/** Whether `value` is an {@link Inbox}. */
|
|
277
|
+
function isInbox(value) {
|
|
278
|
+
return value instanceof Inbox;
|
|
279
|
+
}
|
|
280
|
+
//#endregion
|
|
281
|
+
export { Inbox, InboxAddressInvalid, InboxHasNoAddresses, RawMessageUnreadable, ReceiptNotificationMalformed, isInbox, receiveMail, unjudgedReceipt };
|
|
282
|
+
|
|
283
|
+
//# sourceMappingURL=inbox.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inbox.mjs","names":[],"sources":["../src/inbox.ts"],"sourcesContent":["/**\n * `Inbox` — mail received at addresses on the stage's domain, each message\n * handled in a worker.\n *\n * ```ts\n * export const requests = new Inbox('Requests', {\n * addresses: ['requests'], // local parts: structural\n * subdomains: true, // requests@<tenant>.<stage domain>\n * });\n *\n * export const onRequest = worker\n * .inbox(requests)\n * .handle(async ({ messages }) => {\n * for (const message of messages) {\n * message.recipient.subdomain; // the tenant, from the envelope\n * message.recipient.tag; // requests+<tag>@\n * }\n * });\n * ```\n *\n * **Its own bucket, and a topic.** An inbox owns the bucket its raw messages\n * are kept in — each target creates it for the inbox, never one the stack\n * already runs — and provides its URL itself, so the bucket is no `objects`\n * node and no object subscriber can be bound to it. It declares the topic\n * each message is announced on, which only the provider publishes to.\n *\n * **One decoder.** Deployed, SES's receipt rule stores the raw message and\n * publishes its receipt notification on the topic. Locally `gkm dev` brings a\n * message in from Mailpit and publishes the same notification; in a feature\n * test `mailbox.receive` does. The handler is handed what {@link InboxClient}\n * makes of that notification, wherever it came from.\n *\n * **The envelope routes.** Which inbox, which tenant and which tag come from\n * the envelope recipient, never from `From:` or `To:`, which the sender wrote.\n */\n\nimport { type ParsedEmail, parseEmail } from '@geekmidas/emailkit/inbound';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tINBOX_EVENT,\n\ttype InboxAddressing,\n\ttype InboxRecipient,\n\tinboxRecipient,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Construct } from './construct-interface';\nimport { Topic } from './topic/Topic';\n\nexport interface InboxOptions {\n\t/**\n\t * The local parts it receives at: `['requests']`. Each also takes a\n\t * `+tag` — `requests+t_8f3k@` — handed to the handler as `recipient.tag`.\n\t */\n\taddresses: readonly string[];\n\t/**\n\t * Receive at `<address>@<label>.<domain>` — one label, a tenant's — rather\n\t * than at the stage's domain itself.\n\t */\n\tsubdomains?: boolean;\n}\n\n/** An inbox declared with no address receives nothing. */\nexport class InboxHasNoAddresses extends Error {\n\tconstructor(readonly inbox: string) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names no address, so it would receive nothing. ` +\n\t\t\t\t`Name the local parts it receives at: addresses: ['requests'].`,\n\t\t);\n\t\tthis.name = 'InboxHasNoAddresses';\n\t}\n}\n\n/** An address that is not a bare local part: `requests@x`, `a+b`, `''`. */\nexport class InboxAddressInvalid extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly address: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names '${address}', which is not a local part. ` +\n\t\t\t\t`Name only what goes before the @ — the domain is the stage's — ` +\n\t\t\t\t`and no '+': every address takes a +tag already.`,\n\t\t);\n\t\tthis.name = 'InboxAddressInvalid';\n\t}\n}\n\n/**\n * A receipt notification the inbox cannot read: not SES's shape, or an action\n * other than the S3 one that stores the message where the decoder reads it.\n */\nexport class ReceiptNotificationMalformed extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' was handed a notification it cannot read: ${reason}. ` +\n\t\t\t\t`It reads SES receipt notifications whose action stored the message in S3.`,\n\t\t);\n\t\tthis.name = 'ReceiptNotificationMalformed';\n\t}\n}\n\n/**\n * A provider's verdict on a message.\n *\n * `'unavailable'` where nothing judged it — locally, always — and never a\n * faked `'pass'`.\n */\nexport type Verdict = 'pass' | 'fail' | 'gray' | 'unavailable';\n\n/** What the provider judged of a message, which the message cannot say of itself. */\nexport interface Verdicts {\n\tspf: Verdict;\n\tdkim: Verdict;\n\tdmarc: Verdict;\n\tspam: Verdict;\n\tvirus: Verdict;\n}\n\n/**\n * One received message, for one recipient it was delivered to.\n *\n * `recipient` is the envelope's; every other address is a header, written by\n * the sender. Inbound mail is untrusted input: route on `recipient`, treat\n * `from` as a claim until `verdicts.dmarc` passes *and* the address is known,\n * sanitise `html`, and never use an attachment's filename as a key or path.\n */\nexport interface InboxMessage\n\textends Omit<ParsedEmail, 'attachments'>,\n\t\tPick<ParsedEmail, 'attachments'> {\n\trecipient: InboxRecipient;\n\t/**\n\t * Where the raw message is kept: the bucket SES stored it in (`mailpit`\n\t * locally), and its key there.\n\t */\n\traw: { bucket: string; key: string };\n\tverdicts: Verdicts;\n}\n\n/** A status as SES writes one: `PASS`, `FAIL`, `GRAY`, `PROCESSING_FAILED`, `DISABLED`. */\ninterface ReceiptVerdict {\n\tstatus: string;\n}\n\n/**\n * SES's receipt notification — the part an inbox reads.\n *\n * `gkm dev` and the test mailbox publish the same shape, with every verdict\n * `UNAVAILABLE`, so one decoder serves all three.\n */\nexport interface ReceiptNotification {\n\tnotificationType: 'Received';\n\tmail: {\n\t\tmessageId: string;\n\t\ttimestamp: string;\n\t\t/** The envelope sender (`MAIL FROM`). */\n\t\tsource: string;\n\t\tdestination: string[];\n\t};\n\treceipt: {\n\t\ttimestamp: string;\n\t\t/** The envelope recipients this receipt rule matched. */\n\t\trecipients: string[];\n\t\tspamVerdict?: ReceiptVerdict;\n\t\tvirusVerdict?: ReceiptVerdict;\n\t\tspfVerdict?: ReceiptVerdict;\n\t\tdkimVerdict?: ReceiptVerdict;\n\t\tdmarcVerdict?: ReceiptVerdict;\n\t\taction: {\n\t\t\ttype: string;\n\t\t\tbucketName?: string;\n\t\t\tobjectKey?: string;\n\t\t\ttopicArn?: string;\n\t\t};\n\t};\n}\n\n/** What the handler's inbox is: its domain, its raw messages, the decoder. */\nexport interface InboxClient {\n\t/** The stage's domain it receives on. */\n\treadonly domain: string;\n\t/** A raw message's bytes, by its key in the bucket. */\n\traw(key: string): Promise<Uint8Array>;\n\t/**\n\t * The messages a notification announces: one per envelope recipient this\n\t * inbox receives at, parsed. Empty when none is — a receipt rule that takes\n\t * a whole domain stores mail for addresses no inbox declared.\n\t */\n\tmessages(notification: ReceiptNotification): Promise<InboxMessage[]>;\n}\n\n/** A schema that takes a receipt notification as it is — SES wrote it, not the app. */\nconst RECEIPT_NOTIFICATION: StandardSchemaV1<ReceiptNotification> = {\n\t'~standard': {\n\t\tversion: 1,\n\t\tvendor: 'geekmidas',\n\t\tvalidate: (value) => ({ value: value as ReceiptNotification }),\n\t},\n};\n\ntype InboxTopic = Topic<string, { [INBOX_EVENT]: typeof RECEIPT_NOTIFICATION }>;\n\nexport class Inbox<TName extends string = string>\n\timplements Construct<TName, InboxClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, InboxClient>;\n\t/** Where each received message is announced. Published to by the provider only. */\n\treadonly topic: InboxTopic;\n\n\t/** The local parts it receives at, and whether on a tenant's subdomain. */\n\treadonly addressing: InboxAddressing;\n\tprivate readonly addresses: readonly string[];\n\tprivate readonly subdomains: boolean;\n\tprivate readonly keys: { url: string; domain: string };\n\n\tconstructor(name: ConstructName<TName>, options: InboxOptions) {\n\t\tconst canonical = canonicalId(name as string);\n\t\tif (options.addresses.length === 0) {\n\t\t\tthrow new InboxHasNoAddresses(canonical);\n\t\t}\n\t\tfor (const address of options.addresses) {\n\t\t\tif (!/^[a-z0-9][a-z0-9._-]*$/i.test(address)) {\n\t\t\t\tthrow new InboxAddressInvalid(canonical, address);\n\t\t\t}\n\t\t}\n\n\t\tthis.id = canonical as TName;\n\t\tthis.addresses = options.addresses.map((a) => a.toLowerCase());\n\t\tthis.subdomains = options.subdomains === true;\n\t\tthis.addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t};\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tdomain: provideKey(canonical, 'domain'),\n\t\t};\n\t\tthis.topic = new Topic(`${canonical}Mail`, {\n\t\t\tevents: { [INBOX_EVENT]: RECEIPT_NOTIFICATION },\n\t\t}) as InboxTopic;\n\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (register) => this.connect(register),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t...this.topic.declare(),\n\t\t\t{\n\t\t\t\tkind: 'inbox',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.url, this.keys.domain],\n\t\t\t\taddresses: this.addresses,\n\t\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t\t\ttopic: this.topic.id,\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(\n\t\tregister: ServiceRegisterOptions,\n\t): Promise<InboxClient> {\n\t\tconst { url, domain } = register.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.keys.url).string(),\n\t\t\t\tdomain: get(this.keys.domain).string(),\n\t\t\t}))\n\t\t\t.parse();\n\t\tconst read = rawReader(url);\n\t\tconst addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\tsubdomains: this.subdomains,\n\t\t};\n\t\tconst inbox = this.id;\n\n\t\tconst raw = async (key: string): Promise<Uint8Array> => {\n\t\t\tconst response = await fetch(await read(key));\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new RawMessageUnreadable(inbox, key, response.status);\n\t\t\t}\n\t\t\treturn new Uint8Array(await response.arrayBuffer());\n\t\t};\n\n\t\treturn {\n\t\t\tdomain,\n\t\t\traw,\n\t\t\tasync messages(notification) {\n\t\t\t\tconst { receipt } = assertReceipt(inbox, notification);\n\t\t\t\tconst recipients = receipt.recipients.flatMap((address) => {\n\t\t\t\t\tconst recipient = inboxRecipient(address, addressing, domain);\n\t\t\t\t\treturn recipient ? [recipient] : [];\n\t\t\t\t});\n\t\t\t\tif (recipients.length === 0) return [];\n\n\t\t\t\tconst key = receipt.action.objectKey!;\n\t\t\t\tconst parsed = await parseEmail(await raw(key));\n\t\t\t\tconst verdicts = verdictsOf(receipt);\n\t\t\t\treturn recipients.map((recipient) => ({\n\t\t\t\t\t...parsed,\n\t\t\t\t\trecipient,\n\t\t\t\t\traw: { bucket: receipt.action.bucketName!, key },\n\t\t\t\t\tverdicts,\n\t\t\t\t}));\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * Where a raw message is read from, by its key, for the store `url` names:\n * an `s3://` bucket deployed — SES stored it at `messages/<id>` — or, locally,\n * Mailpit's API, which keeps every message it receives under its own id.\n *\n * The one place local and deployed differ; everything that reads a message\n * goes through it.\n */\nfunction rawReader(url: string): (key: string) => Promise<string> {\n\tif (url.startsWith('s3:')) {\n\t\tconst bucket = createStorageClient(url);\n\t\treturn async (key) => (await bucket).getDownloadURL({ path: key });\n\t}\n\tconst base = url.replace(/\\/+$/, '');\n\treturn async (key) => `${base}/api/v1/message/${encodeURIComponent(key)}/raw`;\n}\n\n/** The raw message a notification names could not be read from its store. */\nexport class RawMessageUnreadable extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly key: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' could not read its raw message '${key}' (HTTP ${status}). ` +\n\t\t\t\t`It is written by the receipt rule before the notification is sent; ` +\n\t\t\t\t`check the bucket's policy lets the process that runs the handler read it.`,\n\t\t);\n\t\tthis.name = 'RawMessageUnreadable';\n\t}\n}\n\nfunction assertReceipt(inbox: string, value: unknown): ReceiptNotification {\n\tconst notification = value as Partial<ReceiptNotification> | undefined;\n\tif (notification?.notificationType !== 'Received') {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its notificationType is '${String(notification?.notificationType)}', not 'Received'`,\n\t\t);\n\t}\n\tconst action = notification.receipt?.action;\n\tif (action?.type !== 'S3' || !action.objectKey || !action.bucketName) {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its action is '${String(action?.type)}' without an S3 object`,\n\t\t);\n\t}\n\tif (!Array.isArray(notification.receipt?.recipients)) {\n\t\tthrow new ReceiptNotificationMalformed(inbox, 'it names no recipients');\n\t}\n\treturn notification as ReceiptNotification;\n}\n\nfunction verdict(status: ReceiptVerdict | undefined): Verdict {\n\tswitch (status?.status) {\n\t\tcase 'PASS':\n\t\t\treturn 'pass';\n\t\tcase 'FAIL':\n\t\t\treturn 'fail';\n\t\tcase 'GRAY':\n\t\t\treturn 'gray';\n\t\tdefault:\n\t\t\treturn 'unavailable';\n\t}\n}\n\nfunction verdictsOf(receipt: ReceiptNotification['receipt']): Verdicts {\n\treturn {\n\t\tspf: verdict(receipt.spfVerdict),\n\t\tdkim: verdict(receipt.dkimVerdict),\n\t\tdmarc: verdict(receipt.dmarcVerdict),\n\t\tspam: verdict(receipt.spamVerdict),\n\t\tvirus: verdict(receipt.virusVerdict),\n\t};\n}\n\n/**\n * The receipt notification a provider that judges nothing publishes —\n * `gkm dev` and the test mailbox — for a message stored at `objectKey`.\n */\nexport function unjudgedReceipt(options: {\n\tmessageId: string;\n\tsource: string;\n\trecipients: readonly string[];\n\tbucketName: string;\n\tobjectKey: string;\n\tverdicts?: Partial<Verdicts>;\n\ttimestamp?: Date;\n}): ReceiptNotification {\n\tconst at = (options.timestamp ?? new Date()).toISOString();\n\tconst status = (v: Verdict | undefined): ReceiptVerdict => ({\n\t\tstatus: v ? v.toUpperCase() : 'UNAVAILABLE',\n\t});\n\treturn {\n\t\tnotificationType: 'Received',\n\t\tmail: {\n\t\t\tmessageId: options.messageId,\n\t\t\ttimestamp: at,\n\t\t\tsource: options.source,\n\t\t\tdestination: [...options.recipients],\n\t\t},\n\t\treceipt: {\n\t\t\ttimestamp: at,\n\t\t\trecipients: [...options.recipients],\n\t\t\tspfVerdict: status(options.verdicts?.spf),\n\t\t\tdkimVerdict: status(options.verdicts?.dkim),\n\t\t\tdmarcVerdict: status(options.verdicts?.dmarc),\n\t\t\tspamVerdict: status(options.verdicts?.spam),\n\t\t\tvirusVerdict: status(options.verdicts?.virus),\n\t\t\taction: {\n\t\t\t\ttype: 'S3',\n\t\t\t\tbucketName: options.bucketName,\n\t\t\t\tobjectKey: options.objectKey,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** An inbox, as the receiver routes to it. */\nexport interface ReceivingInbox {\n\tid: string;\n\taddressing: InboxAddressing;\n\t/** The stage's domain it receives on. */\n\tdomain: string;\n\t/** Announce a received message on the inbox's topic. */\n\tpublish(notification: ReceiptNotification): Promise<void>;\n}\n\n/** A message that arrived where a provider that judges nothing stores mail. */\nexport interface ArrivedMessage {\n\t/** Its key in that store — Mailpit's message id locally. */\n\tkey: string;\n\t/** Where the store is, as a notification names it: `mailpit`. */\n\tstore: string;\n\t/** The envelope sender. */\n\tfrom: string;\n\t/** The envelope recipients — never `To:`. */\n\trecipients: readonly string[];\n\t/** What a test says the provider judged; `'unavailable'` otherwise. */\n\tverdicts?: Partial<Verdicts>;\n}\n\n/**\n * Receive a message the way a receipt rule does: for each inbox one of its\n * envelope recipients is addressed to, publish the receipt notification for\n * those recipients on the inbox's topic. What no inbox receives at goes\n * nowhere — mail the app sent to anyone else included.\n *\n * The one receiver for every local path: Mailpit's webhook under `gkm dev`\n * and a local compose stack, and `mailbox.receive` in a feature test. SES is\n * the receiver deployed. Returns the ids of the inboxes it announced to.\n */\nexport async function receiveMail(\n\tmessage: ArrivedMessage,\n\tinboxes: readonly ReceivingInbox[],\n): Promise<string[]> {\n\tconst received: string[] = [];\n\tfor (const inbox of inboxes) {\n\t\tconst recipients = message.recipients.filter((address) =>\n\t\t\tinboxRecipient(address, inbox.addressing, inbox.domain),\n\t\t);\n\t\tif (recipients.length === 0) continue;\n\t\tawait inbox.publish(\n\t\t\tunjudgedReceipt({\n\t\t\t\tmessageId: message.key,\n\t\t\t\tsource: message.from,\n\t\t\t\trecipients,\n\t\t\t\tbucketName: message.store,\n\t\t\t\tobjectKey: message.key,\n\t\t\t\t...(message.verdicts ? { verdicts: message.verdicts } : {}),\n\t\t\t}),\n\t\t);\n\t\treceived.push(inbox.id);\n\t}\n\treturn received;\n}\n\n/** Whether `value` is an {@link Inbox}. */\nexport function isInbox(value: unknown): value is Inbox {\n\treturn value instanceof Inbox;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,sBAAb,cAAyC,MAAM;CACzB;CAArB,YAAY,OAAwB;EACnC,MACC,cAAc,MAAM,+GAEr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ACA,SAAS,KAAK,MAAM,EAAE;CACvB;CACA,OAAO;AACR;;AAGA,SAAgB,QAAQ,OAAgC;CACvD,OAAO,iBAAiB;AACzB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
1
2
|
let _geekmidas_services = require("@geekmidas/services");
|
|
2
3
|
//#region src/subscribers/runSubscriber.ts
|
|
3
4
|
/** The subscriber's output did not match its `.output()` schema. */
|
|
@@ -19,7 +20,11 @@ async function subscribedEvents(subscriber, rawEvent, logger) {
|
|
|
19
20
|
const toObjectEvents = subscriber.bucketName ? (await import("@geekmidas/storage/events")).toObjectEvents : void 0;
|
|
20
21
|
for (const record of records) try {
|
|
21
22
|
const event = parse(record);
|
|
22
|
-
const
|
|
23
|
+
const untyped = !(typeof event === "object" && event?.type);
|
|
24
|
+
const parsed = subscriber.inboxName && untyped ? [{
|
|
25
|
+
type: _geekmidas_manifest.INBOX_EVENT,
|
|
26
|
+
payload: event
|
|
27
|
+
}] : toObjectEvents && untyped ? toObjectEvents(event) : [event];
|
|
23
28
|
for (const one of parsed) if (isSubscribed(subscriber, one)) events.push(one);
|
|
24
29
|
} catch (error) {
|
|
25
30
|
logger.error({
|
|
@@ -125,4 +130,4 @@ Object.defineProperty(exports, "subscriberContext", {
|
|
|
125
130
|
}
|
|
126
131
|
});
|
|
127
132
|
|
|
128
|
-
//# sourceMappingURL=runSubscriber-
|
|
133
|
+
//# sourceMappingURL=runSubscriber-CC_2C9F2.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runSubscriber-CC_2C9F2.cjs","names":["INBOX_EVENT","ServiceDiscovery"],"sources":["../src/subscribers/runSubscriber.ts"],"sourcesContent":["/**\n * What a subscriber does with a batch of records, however they arrived: parse\n * them into events, keep the ones it subscribed to, and run its handler with\n * its services and database.\n *\n * Shared by the Lambda adaptor, which wraps it in middy, and the SNS push\n * adaptor, which a server runs and which must not need middy to load.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { INBOX_EVENT } from '@geekmidas/manifest';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { SNSEvent, SNSEventRecord, SQSEvent, SQSRecord } from 'aws-lambda';\nimport type { Subscriber } from './Subscriber';\n\ntype AnySubscriber = Subscriber<any, any, any, any, any, any, any>;\n\n/** The subscriber's output did not match its `.output()` schema. */\nexport class SubscriberOutputInvalid extends Error {\n\tconstructor(readonly issues: ReadonlyArray<unknown>) {\n\t\tsuper(\n\t\t\t\"Subscriber output validation failed: the handler's result does not match its .output() schema.\",\n\t\t);\n\t\tthis.name = 'SubscriberOutputInvalid';\n\t}\n}\n\n/** The events in an SQS or SNS batch (a Lambda event's `Records`) that `subscriber` subscribed to. */\nexport async function subscribedEvents(\n\tsubscriber: AnySubscriber,\n\trawEvent: { Records?: readonly unknown[] },\n\tlogger: Logger,\n): Promise<any[]> {\n\tconst events: any[] = [];\n\tconst records = rawEvent.Records ?? [];\n\tconst first = records[0] as any;\n\tconst parse =\n\t\tfirst?.eventSource === 'aws:sqs'\n\t\t\t? (record: any) => parseSQSRecord(record)\n\t\t\t: first?.EventSource === 'aws:sns'\n\t\t\t\t? (record: any) => parseSNSRecord(record)\n\t\t\t\t: undefined;\n\tif (!parse) return events;\n\n\t// A bucket's subscriber is sent what the storage sends — a notification\n\t// of records — and reads it as object events. Loaded only then: an app\n\t// with no bucket never installs the storage package.\n\tconst toObjectEvents = subscriber.bucketName\n\t\t? (await import('@geekmidas/storage/events')).toObjectEvents\n\t\t: undefined;\n\n\tfor (const record of records) {\n\t\ttry {\n\t\t\tconst event = parse(record);\n\t\t\tconst untyped = !(typeof event === 'object' && event?.type);\n\t\t\t// An inbox's subscriber is sent SES's receipt notification as SES\n\t\t\t// wrote it, with no type of ours on it.\n\t\t\tconst parsed =\n\t\t\t\tsubscriber.inboxName && untyped\n\t\t\t\t\t? [{ type: INBOX_EVENT, payload: event }]\n\t\t\t\t\t: toObjectEvents && untyped\n\t\t\t\t\t\t? toObjectEvents(event)\n\t\t\t\t\t\t: [event];\n\t\t\tfor (const one of parsed) {\n\t\t\t\tif (isSubscribed(subscriber, one)) events.push(one);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error({ err: error, record }, 'Failed to parse record');\n\t\t}\n\t}\n\treturn events;\n}\n\n/** The subscriber's services and database, registered as functions do. */\nexport async function subscriberContext(\n\tsubscriber: AnySubscriber,\n\tenvParser: EnvironmentParser<{}>,\n): Promise<{ services: Record<string, unknown>; db: unknown }> {\n\tconst discovery = ServiceDiscovery.getInstance(envParser);\n\tconst services =\n\t\tsubscriber.services.length > 0\n\t\t\t? await discovery.register(subscriber.services)\n\t\t\t: {};\n\tconst service = subscriber.databaseService;\n\tconst db = service\n\t\t? (await discovery.register([service]))[service.serviceName]\n\t\t: undefined;\n\treturn { services, db };\n}\n\n/** Runs the handler on `events`, and checks its output against its schema. */\nexport async function runSubscriber(\n\tsubscriber: AnySubscriber,\n\tcontext: {\n\t\tevents: any[];\n\t\tservices: Record<string, unknown>;\n\t\tdb: unknown;\n\t\tlogger: Logger;\n\t},\n): Promise<unknown> {\n\tif (context.events.length === 0) {\n\t\tcontext.logger.info('No subscribed events to process');\n\t\treturn { batchItemFailures: [] };\n\t}\n\n\tconst { events, services, db, logger } = context;\n\tconst result = await subscriber.handler({\n\t\tevents,\n\t\tservices,\n\t\tlogger,\n\t\tdb,\n\t} as any);\n\n\tif (subscriber.outputSchema && result) {\n\t\tconst validation =\n\t\t\tawait subscriber.outputSchema['~standard'].validate(result);\n\t\tif (validation.issues) {\n\t\t\tcontext.logger.error(\n\t\t\t\t{ issues: validation.issues },\n\t\t\t\t'Subscriber output validation failed',\n\t\t\t);\n\t\t\tthrow new SubscriberOutputInvalid(validation.issues);\n\t\t}\n\t\treturn validation.value;\n\t}\n\n\treturn result;\n}\n\nfunction isSubscribed(subscriber: AnySubscriber, event: any): boolean {\n\t// No event type (raw string/non-object) — always include\n\tif (typeof event !== 'object' || !event?.type) return true;\n\t// No filter configured — accept all\n\tif (!subscriber.subscribedEvents) return true;\n\treturn subscriber.subscribedEvents.includes(event.type);\n}\n\nfunction parseSNSRecord(record: SNSEventRecord): any {\n\tconst message = safeJsonParse(record.Sns.Message);\n\tconst messageType = record.Sns.MessageAttributes?.type?.Value;\n\n\t// Not JSON — wrap raw string with type from MessageAttributes if available\n\tif (message === null) {\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: record.Sns.Message }\n\t\t\t: record.Sns.Message;\n\t}\n\n\tif (message.type) {\n\t\treturn message; // Full event format: { type, payload }\n\t}\n\n\t// Payload-only format: type is in MessageAttributes\n\treturn messageType ? { type: messageType, payload: message } : message;\n}\n\nfunction parseSQSRecord(record: SQSRecord): any {\n\tconst body = safeJsonParse(record.body);\n\n\t// Not JSON — return raw body as-is\n\tif (body === null) {\n\t\treturn record.body;\n\t}\n\n\t// Check if this is an SNS message wrapped in SQS\n\tif (body.Type === 'Notification' && body.Message) {\n\t\tconst snsMessage = safeJsonParse(body.Message);\n\t\tconst messageType = body.MessageAttributes?.type?.Value;\n\n\t\t// SNS Message not JSON — wrap with type from MessageAttributes if available\n\t\tif (snsMessage === null) {\n\t\t\treturn messageType\n\t\t\t\t? { type: messageType, payload: body.Message }\n\t\t\t\t: body.Message;\n\t\t}\n\n\t\tif (snsMessage.type) {\n\t\t\treturn snsMessage; // Full event format: { type, payload }\n\t\t}\n\n\t\t// Payload-only format: type is in MessageAttributes\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: snsMessage }\n\t\t\t: snsMessage;\n\t}\n\n\t// Direct SQS message\n\treturn body;\n}\n\nfunction safeJsonParse(value: string): any | null {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;AAmBA,IAAa,0BAAb,cAA6C,MAAM;CAC7B;CAArB,YAAY,QAAyC;EACpD,MACC,gGACD;EAHoB,KAAA,SAAA;EAI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GAAE,MAAM;GAAa,SAAS;EAAW,IACzC;CACJ;CAGA,OAAO;AACR;AAEA,SAAS,cAAc,OAA2B;CACjD,IAAI;EACH,OAAO,KAAK,MAAM,KAAK;CACxB,QAAQ;EACP,OAAO;CACR;AACD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { INBOX_EVENT } from "@geekmidas/manifest";
|
|
1
2
|
import { ServiceDiscovery } from "@geekmidas/services";
|
|
2
3
|
//#region src/subscribers/runSubscriber.ts
|
|
3
4
|
/** The subscriber's output did not match its `.output()` schema. */
|
|
@@ -19,7 +20,11 @@ async function subscribedEvents(subscriber, rawEvent, logger) {
|
|
|
19
20
|
const toObjectEvents = subscriber.bucketName ? (await import("@geekmidas/storage/events")).toObjectEvents : void 0;
|
|
20
21
|
for (const record of records) try {
|
|
21
22
|
const event = parse(record);
|
|
22
|
-
const
|
|
23
|
+
const untyped = !(typeof event === "object" && event?.type);
|
|
24
|
+
const parsed = subscriber.inboxName && untyped ? [{
|
|
25
|
+
type: INBOX_EVENT,
|
|
26
|
+
payload: event
|
|
27
|
+
}] : toObjectEvents && untyped ? toObjectEvents(event) : [event];
|
|
23
28
|
for (const one of parsed) if (isSubscribed(subscriber, one)) events.push(one);
|
|
24
29
|
} catch (error) {
|
|
25
30
|
logger.error({
|
|
@@ -108,4 +113,4 @@ function safeJsonParse(value) {
|
|
|
108
113
|
//#endregion
|
|
109
114
|
export { subscribedEvents as n, subscriberContext as r, runSubscriber as t };
|
|
110
115
|
|
|
111
|
-
//# sourceMappingURL=runSubscriber-
|
|
116
|
+
//# sourceMappingURL=runSubscriber-DyHWp_Lf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runSubscriber-DyHWp_Lf.mjs","names":[],"sources":["../src/subscribers/runSubscriber.ts"],"sourcesContent":["/**\n * What a subscriber does with a batch of records, however they arrived: parse\n * them into events, keep the ones it subscribed to, and run its handler with\n * its services and database.\n *\n * Shared by the Lambda adaptor, which wraps it in middy, and the SNS push\n * adaptor, which a server runs and which must not need middy to load.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { INBOX_EVENT } from '@geekmidas/manifest';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { SNSEvent, SNSEventRecord, SQSEvent, SQSRecord } from 'aws-lambda';\nimport type { Subscriber } from './Subscriber';\n\ntype AnySubscriber = Subscriber<any, any, any, any, any, any, any>;\n\n/** The subscriber's output did not match its `.output()` schema. */\nexport class SubscriberOutputInvalid extends Error {\n\tconstructor(readonly issues: ReadonlyArray<unknown>) {\n\t\tsuper(\n\t\t\t\"Subscriber output validation failed: the handler's result does not match its .output() schema.\",\n\t\t);\n\t\tthis.name = 'SubscriberOutputInvalid';\n\t}\n}\n\n/** The events in an SQS or SNS batch (a Lambda event's `Records`) that `subscriber` subscribed to. */\nexport async function subscribedEvents(\n\tsubscriber: AnySubscriber,\n\trawEvent: { Records?: readonly unknown[] },\n\tlogger: Logger,\n): Promise<any[]> {\n\tconst events: any[] = [];\n\tconst records = rawEvent.Records ?? [];\n\tconst first = records[0] as any;\n\tconst parse =\n\t\tfirst?.eventSource === 'aws:sqs'\n\t\t\t? (record: any) => parseSQSRecord(record)\n\t\t\t: first?.EventSource === 'aws:sns'\n\t\t\t\t? (record: any) => parseSNSRecord(record)\n\t\t\t\t: undefined;\n\tif (!parse) return events;\n\n\t// A bucket's subscriber is sent what the storage sends — a notification\n\t// of records — and reads it as object events. Loaded only then: an app\n\t// with no bucket never installs the storage package.\n\tconst toObjectEvents = subscriber.bucketName\n\t\t? (await import('@geekmidas/storage/events')).toObjectEvents\n\t\t: undefined;\n\n\tfor (const record of records) {\n\t\ttry {\n\t\t\tconst event = parse(record);\n\t\t\tconst untyped = !(typeof event === 'object' && event?.type);\n\t\t\t// An inbox's subscriber is sent SES's receipt notification as SES\n\t\t\t// wrote it, with no type of ours on it.\n\t\t\tconst parsed =\n\t\t\t\tsubscriber.inboxName && untyped\n\t\t\t\t\t? [{ type: INBOX_EVENT, payload: event }]\n\t\t\t\t\t: toObjectEvents && untyped\n\t\t\t\t\t\t? toObjectEvents(event)\n\t\t\t\t\t\t: [event];\n\t\t\tfor (const one of parsed) {\n\t\t\t\tif (isSubscribed(subscriber, one)) events.push(one);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error({ err: error, record }, 'Failed to parse record');\n\t\t}\n\t}\n\treturn events;\n}\n\n/** The subscriber's services and database, registered as functions do. */\nexport async function subscriberContext(\n\tsubscriber: AnySubscriber,\n\tenvParser: EnvironmentParser<{}>,\n): Promise<{ services: Record<string, unknown>; db: unknown }> {\n\tconst discovery = ServiceDiscovery.getInstance(envParser);\n\tconst services =\n\t\tsubscriber.services.length > 0\n\t\t\t? await discovery.register(subscriber.services)\n\t\t\t: {};\n\tconst service = subscriber.databaseService;\n\tconst db = service\n\t\t? (await discovery.register([service]))[service.serviceName]\n\t\t: undefined;\n\treturn { services, db };\n}\n\n/** Runs the handler on `events`, and checks its output against its schema. */\nexport async function runSubscriber(\n\tsubscriber: AnySubscriber,\n\tcontext: {\n\t\tevents: any[];\n\t\tservices: Record<string, unknown>;\n\t\tdb: unknown;\n\t\tlogger: Logger;\n\t},\n): Promise<unknown> {\n\tif (context.events.length === 0) {\n\t\tcontext.logger.info('No subscribed events to process');\n\t\treturn { batchItemFailures: [] };\n\t}\n\n\tconst { events, services, db, logger } = context;\n\tconst result = await subscriber.handler({\n\t\tevents,\n\t\tservices,\n\t\tlogger,\n\t\tdb,\n\t} as any);\n\n\tif (subscriber.outputSchema && result) {\n\t\tconst validation =\n\t\t\tawait subscriber.outputSchema['~standard'].validate(result);\n\t\tif (validation.issues) {\n\t\t\tcontext.logger.error(\n\t\t\t\t{ issues: validation.issues },\n\t\t\t\t'Subscriber output validation failed',\n\t\t\t);\n\t\t\tthrow new SubscriberOutputInvalid(validation.issues);\n\t\t}\n\t\treturn validation.value;\n\t}\n\n\treturn result;\n}\n\nfunction isSubscribed(subscriber: AnySubscriber, event: any): boolean {\n\t// No event type (raw string/non-object) — always include\n\tif (typeof event !== 'object' || !event?.type) return true;\n\t// No filter configured — accept all\n\tif (!subscriber.subscribedEvents) return true;\n\treturn subscriber.subscribedEvents.includes(event.type);\n}\n\nfunction parseSNSRecord(record: SNSEventRecord): any {\n\tconst message = safeJsonParse(record.Sns.Message);\n\tconst messageType = record.Sns.MessageAttributes?.type?.Value;\n\n\t// Not JSON — wrap raw string with type from MessageAttributes if available\n\tif (message === null) {\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: record.Sns.Message }\n\t\t\t: record.Sns.Message;\n\t}\n\n\tif (message.type) {\n\t\treturn message; // Full event format: { type, payload }\n\t}\n\n\t// Payload-only format: type is in MessageAttributes\n\treturn messageType ? { type: messageType, payload: message } : message;\n}\n\nfunction parseSQSRecord(record: SQSRecord): any {\n\tconst body = safeJsonParse(record.body);\n\n\t// Not JSON — return raw body as-is\n\tif (body === null) {\n\t\treturn record.body;\n\t}\n\n\t// Check if this is an SNS message wrapped in SQS\n\tif (body.Type === 'Notification' && body.Message) {\n\t\tconst snsMessage = safeJsonParse(body.Message);\n\t\tconst messageType = body.MessageAttributes?.type?.Value;\n\n\t\t// SNS Message not JSON — wrap with type from MessageAttributes if available\n\t\tif (snsMessage === null) {\n\t\t\treturn messageType\n\t\t\t\t? { type: messageType, payload: body.Message }\n\t\t\t\t: body.Message;\n\t\t}\n\n\t\tif (snsMessage.type) {\n\t\t\treturn snsMessage; // Full event format: { type, payload }\n\t\t}\n\n\t\t// Payload-only format: type is in MessageAttributes\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: snsMessage }\n\t\t\t: snsMessage;\n\t}\n\n\t// Direct SQS message\n\treturn body;\n}\n\nfunction safeJsonParse(value: string): any | null {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;AAmBA,IAAa,0BAAb,cAA6C,MAAM;CAC7B;CAArB,YA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W,MACd,OAAO;EAIR,OAAO,cACJ;GAAE,MAAM;GAAa,SAAS;EAAW,IACzC;CACJ;CAGA,OAAO;AACR;AAEA,SAAS,cAAc,OAA2B;CACjD,IAAI;EACH,OAAO,KAAK,MAAM,KAAK;CACxB,QAAQ;EACP,OAAO;CACR;AACD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_SubscriberBuilder = require("../SubscriberBuilder-
|
|
3
|
-
const require_runSubscriber = require("../runSubscriber-
|
|
2
|
+
const require_SubscriberBuilder = require("../SubscriberBuilder-CWzKwX1p.cjs");
|
|
3
|
+
const require_runSubscriber = require("../runSubscriber-CC_2C9F2.cjs");
|
|
4
4
|
let _geekmidas_events = require("@geekmidas/events");
|
|
5
5
|
let _geekmidas_services = require("@geekmidas/services");
|
|
6
6
|
let _geekmidas_errors = require("@geekmidas/errors");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Subscriber } from "../Subscriber-
|
|
2
|
-
import { a as ObjectSubscriberHasNoEvents, i as ObjectSubscriberHandler, n as ObjectSubscriberBuilder, o as SubscriberBuilder, r as ObjectSubscriberContext, t as ObjectSubscriber } from "../ObjectSubscriberBuilder-
|
|
1
|
+
import { t as Subscriber } from "../Subscriber-5rCX1Nph.cjs";
|
|
2
|
+
import { a as ObjectSubscriberHasNoEvents, i as ObjectSubscriberHandler, n as ObjectSubscriberBuilder, o as SubscriberBuilder, r as ObjectSubscriberContext, t as ObjectSubscriber } from "../ObjectSubscriberBuilder-BuuaYcrm.cjs";
|
|
3
3
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
4
4
|
import { SnsHttpMessage } from "@geekmidas/events/sns";
|
|
5
5
|
//#region src/subscribers/SnsPushSubscriberAdaptor.d.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Subscriber } from "../Subscriber-
|
|
2
|
-
import { a as ObjectSubscriberHasNoEvents, i as ObjectSubscriberHandler, n as ObjectSubscriberBuilder, o as SubscriberBuilder, r as ObjectSubscriberContext, t as ObjectSubscriber } from "../ObjectSubscriberBuilder-
|
|
1
|
+
import { t as Subscriber } from "../Subscriber-CW_Dl-YR.mjs";
|
|
2
|
+
import { a as ObjectSubscriberHasNoEvents, i as ObjectSubscriberHandler, n as ObjectSubscriberBuilder, o as SubscriberBuilder, r as ObjectSubscriberContext, t as ObjectSubscriber } from "../ObjectSubscriberBuilder-CzgYmOUH.mjs";
|
|
3
3
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
4
4
|
import { SnsHttpMessage } from "@geekmidas/events/sns";
|
|
5
5
|
//#region src/subscribers/SnsPushSubscriberAdaptor.d.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as ObjectSubscriberHasNoEvents, n as Subscriber, r as ObjectSubscriberBuilder, t as SubscriberBuilder } from "../SubscriberBuilder-
|
|
2
|
-
import { n as subscribedEvents, r as subscriberContext, t as runSubscriber } from "../runSubscriber-
|
|
1
|
+
import { i as ObjectSubscriberHasNoEvents, n as Subscriber, r as ObjectSubscriberBuilder, t as SubscriberBuilder } from "../SubscriberBuilder-BL_GTcwh.mjs";
|
|
2
|
+
import { n as subscribedEvents, r as subscriberContext, t as runSubscriber } from "../runSubscriber-DyHWp_Lf.mjs";
|
|
3
3
|
import { carrierFromAttributes, consumeTraced } from "@geekmidas/events";
|
|
4
4
|
import { runWithRequestContext } from "@geekmidas/services";
|
|
5
5
|
import { wrapError } from "@geekmidas/errors";
|
package/dist/worker.cjs
CHANGED
|
@@ -4,9 +4,59 @@ const require_functions = require("./functions-DLF6-IK8.cjs");
|
|
|
4
4
|
const require_surfaceEnv = require("./surfaceEnv-CNimK76p.cjs");
|
|
5
5
|
const require_CronBuilder = require("./CronBuilder-B_NSP-Y5.cjs");
|
|
6
6
|
const require_QueueBuilder = require("./QueueBuilder-BxsZ9o5z.cjs");
|
|
7
|
-
const require_SubscriberBuilder = require("./SubscriberBuilder-
|
|
7
|
+
const require_SubscriberBuilder = require("./SubscriberBuilder-CWzKwX1p.cjs");
|
|
8
8
|
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
9
9
|
let _geekmidas_logger_console = require("@geekmidas/logger/console");
|
|
10
|
+
//#region src/subscribers/InboxSubscriberBuilder.ts
|
|
11
|
+
var InboxSubscriberBuilder = class InboxSubscriberBuilder {
|
|
12
|
+
inner;
|
|
13
|
+
inbox;
|
|
14
|
+
constructor(inner, inbox) {
|
|
15
|
+
this.inner = inner;
|
|
16
|
+
this.inbox = inbox;
|
|
17
|
+
}
|
|
18
|
+
dependsOn(constructs) {
|
|
19
|
+
return this.with(this.inner.dependsOn(constructs));
|
|
20
|
+
}
|
|
21
|
+
services(services) {
|
|
22
|
+
return this.with(this.inner.services(services));
|
|
23
|
+
}
|
|
24
|
+
database(source) {
|
|
25
|
+
return this.with(this.inner.database(source));
|
|
26
|
+
}
|
|
27
|
+
timeout(timeout) {
|
|
28
|
+
return this.with(this.inner.timeout(timeout));
|
|
29
|
+
}
|
|
30
|
+
output(schema) {
|
|
31
|
+
return this.with(this.inner.output(schema));
|
|
32
|
+
}
|
|
33
|
+
logger(logger) {
|
|
34
|
+
return this.with(this.inner.logger(logger));
|
|
35
|
+
}
|
|
36
|
+
handle(fn) {
|
|
37
|
+
const key = (0, _geekmidas_manifest.serviceKey)(this.inbox.id);
|
|
38
|
+
const handler = async (ctx) => {
|
|
39
|
+
const inbox = ctx.services[key];
|
|
40
|
+
const notifications = ctx.events.filter((event) => event?.type === _geekmidas_manifest.INBOX_EVENT);
|
|
41
|
+
const messages = [];
|
|
42
|
+
for (const { payload } of notifications) messages.push(...await inbox.messages(payload));
|
|
43
|
+
if (messages.length === 0) return void 0;
|
|
44
|
+
return fn({
|
|
45
|
+
...ctx,
|
|
46
|
+
messages,
|
|
47
|
+
inbox
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
const subscriber = this.inner.subscribe([_geekmidas_manifest.INBOX_EVENT]).handle(handler);
|
|
51
|
+
subscriber.inboxName = this.inbox.id;
|
|
52
|
+
subscriber.inboxAddressing = this.inbox.addressing;
|
|
53
|
+
return subscriber;
|
|
54
|
+
}
|
|
55
|
+
with(inner) {
|
|
56
|
+
return new InboxSubscriberBuilder(inner, this.inbox);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
//#endregion
|
|
10
60
|
//#region src/worker.ts
|
|
11
61
|
var Worker = class Worker {
|
|
12
62
|
config;
|
|
@@ -113,6 +163,26 @@ var Worker = class Worker {
|
|
|
113
163
|
return new require_SubscriberBuilder.ObjectSubscriberBuilder(inner, bucket.id);
|
|
114
164
|
}
|
|
115
165
|
/**
|
|
166
|
+
* A runnable handed the mail an {@link Inbox} receives.
|
|
167
|
+
*
|
|
168
|
+
* Bound, as a topic subscriber is: the inbox's topic is what it consumes,
|
|
169
|
+
* and what it is handed is the messages on it, parsed — one per envelope
|
|
170
|
+
* recipient the inbox receives at. It reads its inbox's raw messages
|
|
171
|
+
* without depending on it; anything else it uses it names, as ever.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```ts
|
|
175
|
+
* export const onRequest = worker
|
|
176
|
+
* .inbox(requests)
|
|
177
|
+
* .handle(async ({ messages, db }) => {
|
|
178
|
+
* for (const message of messages) message.recipient.subdomain;
|
|
179
|
+
* });
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
inbox(inbox) {
|
|
183
|
+
return new InboxSubscriberBuilder(this.own(new require_SubscriberBuilder.SubscriberBuilder().logger(this.logger)).topic(inbox.topic).dependsOn([inbox]), inbox);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
116
186
|
* A runnable that consumes a topic.
|
|
117
187
|
*
|
|
118
188
|
* Binding is not publishing: a consumer is handed the topic's event types
|