@geekmidas/constructs 10.0.0-alpha.167 → 10.0.0-alpha.168
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/Construct-127M7yrl.d.cts.map +1 -1
- package/dist/Construct-BMk_CRSD.d.mts.map +1 -1
- package/dist/{Queue-u8w8_HpE.mjs → Queue-9Hh20ZCk.mjs} +3 -3
- package/dist/Queue-9Hh20ZCk.mjs.map +1 -0
- package/dist/Queue-B8HGg439.d.mts.map +1 -1
- package/dist/Queue-C4rijiM7.d.cts.map +1 -1
- package/dist/{Queue-D4Iaidrs.cjs → Queue-W1wueijP.cjs} +2 -2
- package/dist/Queue-W1wueijP.cjs.map +1 -0
- package/dist/{QueueBuilder-BxsZ9o5z.cjs → QueueBuilder-BDcv9B71.cjs} +2 -2
- package/dist/{QueueBuilder-BxsZ9o5z.cjs.map → QueueBuilder-BDcv9B71.cjs.map} +1 -1
- package/dist/{QueueBuilder-2wP5lEC8.mjs → QueueBuilder-CrZL8HHs.mjs} +2 -2
- package/dist/{QueueBuilder-2wP5lEC8.mjs.map → QueueBuilder-CrZL8HHs.mjs.map} +1 -1
- package/dist/{Topic-DN2gYJ-p.mjs → Topic-BGoOeCT6.mjs} +3 -3
- package/dist/Topic-BGoOeCT6.mjs.map +1 -0
- package/dist/{Topic-Dp9Q7Lj2.cjs → Topic-DLCZBNwK.cjs} +2 -2
- package/dist/Topic-DLCZBNwK.cjs.map +1 -0
- package/dist/adaptors/testing.cjs +15 -15
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +16 -16
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/auth-1yI2wR-4.d.cts.map +1 -1
- package/dist/auth-D4NMXgLt.d.mts.map +1 -1
- package/dist/auth.cjs +5 -5
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.mjs +6 -6
- package/dist/auth.mjs.map +1 -1
- package/dist/cache.cjs +1 -1
- package/dist/cache.cjs.map +1 -1
- package/dist/cache.mjs +2 -2
- package/dist/cache.mjs.map +1 -1
- package/dist/{credential-DfSAOOdY.mjs → credential-B80mOxwT.mjs} +3 -3
- package/dist/credential-B80mOxwT.mjs.map +1 -0
- package/dist/{credential-DYymbp_7.cjs → credential-RlgbzZAc.cjs} +2 -2
- package/dist/credential-RlgbzZAc.cjs.map +1 -0
- package/dist/credential.cjs +1 -1
- package/dist/credential.mjs +1 -1
- package/dist/database/kysely.cjs +1 -1
- package/dist/database/kysely.mjs +1 -1
- package/dist/email.cjs +2 -2
- package/dist/email.cjs.map +1 -1
- package/dist/email.mjs +3 -3
- package/dist/email.mjs.map +1 -1
- package/dist/encryption.cjs +1 -1
- package/dist/encryption.cjs.map +1 -1
- package/dist/encryption.mjs +2 -2
- package/dist/encryption.mjs.map +1 -1
- package/dist/external-api.cjs +3 -3
- package/dist/external-api.cjs.map +1 -1
- package/dist/external-api.mjs +4 -4
- package/dist/external-api.mjs.map +1 -1
- package/dist/fake-BvOXkZmj.d.mts.map +1 -1
- package/dist/fake-Djx8E0o1.d.cts.map +1 -1
- package/dist/file-server.cjs +1 -1
- package/dist/file-server.cjs.map +1 -1
- package/dist/file-server.d.cts.map +1 -1
- package/dist/file-server.d.mts.map +1 -1
- package/dist/file-server.mjs +2 -2
- package/dist/file-server.mjs.map +1 -1
- package/dist/inbox.cjs +3 -3
- package/dist/inbox.cjs.map +1 -1
- package/dist/inbox.mjs +4 -4
- package/dist/inbox.mjs.map +1 -1
- package/dist/{kysely-Cs4uPO8k.mjs → kysely-Bc9xzaik.mjs} +4 -4
- package/dist/kysely-Bc9xzaik.mjs.map +1 -0
- package/dist/{kysely-CukArHJ0.cjs → kysely-D7f6J2lh.cjs} +3 -3
- package/dist/kysely-D7f6J2lh.cjs.map +1 -0
- package/dist/mobile-app.cjs +1 -1
- package/dist/mobile-app.cjs.map +1 -1
- package/dist/mobile-app.mjs +2 -2
- package/dist/mobile-app.mjs.map +1 -1
- package/dist/object-storage.cjs +1 -1
- package/dist/object-storage.cjs.map +1 -1
- package/dist/object-storage.d.cts.map +1 -1
- package/dist/object-storage.d.mts.map +1 -1
- package/dist/object-storage.mjs +2 -2
- package/dist/object-storage.mjs.map +1 -1
- package/dist/queue/index.cjs +2 -2
- package/dist/queue/index.mjs +2 -2
- package/dist/rest-api.cjs +3 -3
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.mjs +4 -4
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.cjs +2 -2
- package/dist/site.cjs.map +1 -1
- package/dist/site.mjs +3 -3
- package/dist/site.mjs.map +1 -1
- package/dist/topic/index.cjs +1 -1
- package/dist/topic/index.mjs +1 -1
- package/dist/websocket-api-B1Wl3tg4.d.cts.map +1 -1
- package/dist/websocket-api-CvnPDSZB.d.mts.map +1 -1
- package/dist/{websocket-api-czxhekGG.cjs → websocket-api-Zy2U-Qyh.cjs} +4 -4
- package/dist/websocket-api-Zy2U-Qyh.cjs.map +1 -0
- package/dist/{websocket-api-Bg9SowJ5.mjs → websocket-api-svBCnOAE.mjs} +5 -5
- package/dist/{websocket-api-Bg9SowJ5.mjs.map → websocket-api-svBCnOAE.mjs.map} +1 -1
- package/dist/websocket-api.cjs +1 -1
- package/dist/websocket-api.mjs +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.mjs +1 -1
- package/package.json +31 -31
- package/dist/Queue-D4Iaidrs.cjs.map +0 -1
- package/dist/Queue-u8w8_HpE.mjs.map +0 -1
- package/dist/Topic-DN2gYJ-p.mjs.map +0 -1
- package/dist/Topic-Dp9Q7Lj2.cjs.map +0 -1
- package/dist/credential-DYymbp_7.cjs.map +0 -1
- package/dist/credential-DfSAOOdY.mjs.map +0 -1
- package/dist/kysely-Cs4uPO8k.mjs.map +0 -1
- package/dist/kysely-CukArHJ0.cjs.map +0 -1
- package/dist/websocket-api-czxhekGG.cjs.map +0 -1
package/dist/file-server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-server.cjs","names":["canonicalId","expiryDays","DERIVED_PREFIX","fileServerSurfaceId","provideKey","providedKeyFor","serviceKey","createStorageClient","ProcessorBuilder","parsePattern","DEFAULT_LOGGER","fillPattern"],"sources":["../src/file-server.ts"],"sourcesContent":["/**\n * `FileServer` — a domain that serves a bucket's objects.\n *\n * `ObjectStorage` is the bucket: it writes, it presigns, and its URL is never\n * public. Serving those objects on a domain is a different thing, and it is a\n * construct of its own rather than a flag on the bucket — see\n * `docs/design/constructs-paradigm.md`, \"Why a separate construct, and what it\n * costs\", for the comparison that rules the other two shapes out.\n *\n * ```ts\n * export const uploads = new FileServer('Uploads', { open: ['brand/**'] });\n *\n * uploads.getUploadURL({ path, contentType }) // an S3 presign at the bucket\n * uploads.url('brand/logo.png') // open path — no signature\n * uploads.signedUrl('invoices/7.pdf') // one object, one recipient\n * ```\n *\n * **One construct, one client, both halves.** How a file lands in the bucket is\n * the same whether or not it is served, so splitting the upload half from the\n * serving half would be ceremony rather than safety. The client is a *superset*\n * of `StorageClient`, made literal in the type, so anything taking\n * `services.uploads` keeps compiling when the construct behind it grows a\n * serving half.\n *\n * **The id names the bucket, not the surface.** This is the detail that has to\n * be right before anything ships, because getting it backwards is destructive:\n * the migration people actually perform is serving a bucket they already have,\n * and naming the bucket after the construct makes that edit *add* a node rather\n * than rename the one holding the data.\n */\n\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDERIVED_PREFIX,\n\ttype Declaration,\n\tfileServerSurfaceId,\n\tprovidedKeyFor,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient, type StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type {\n\tConstruct,\n\tDeclarable,\n\tHasPublicFace,\n} from './construct-interface';\nimport { expiryDays, type ObjectExpiry } from './expire';\nimport type { Processor } from './processors/Processor';\nimport { ProcessorBuilder } from './processors/ProcessorBuilder';\nimport {\n\tfillPattern,\n\ttype PatternParams,\n\tparsePattern,\n} from './processors/pattern';\nimport type { Telemetry } from './telemetry';\n\n/**\n * A key an open pattern admits.\n *\n * The same template-literal trick `ConstructName` uses, so `open` is checked at\n * the call site rather than only at the edge:\n *\n * ```ts\n * files.url('brand/logo.png') // ok\n * files.url(`avatars/${id}.png`) // ok — a template literal still matches\n * files.url('invoices/7.pdf') // not assignable — never served unsigned\n * ```\n *\n * A single star and a double star resolve to the same type, stated rather than\n * discovered: a template literal cannot exclude `/`, so this is a prefix-and-\n * suffix guard while the *exact* pattern is enforced by the bucket policy, by\n * the cache behaviour, and by this construct's own runtime check. The type says\n * plausibly open; the infrastructure says definitely.\n */\nexport type Served<P extends string> = P extends `${infer Head}**`\n\t? `${Head}${string}`\n\t: P extends `${infer Head}*${infer Tail}`\n\t\t? `${Head}${string}${Tail}`\n\t\t: P;\n\n/** What consuming a file server hands you: a bucket client that also serves. */\nexport interface FileServerClient<TOpen extends string = never>\n\textends StorageClient {\n\t/**\n\t * The unsigned address of an open object.\n\t *\n\t * Compile-checked against the declared patterns, *and* checked again at\n\t * runtime — a JavaScript caller gets no compiler, and minting an unsigned\n\t * URL for a private object is a leak rather than a mistake.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\turl(key: Served<TOpen>): string;\n\n\t/**\n\t * The same thing for a key the compiler cannot see.\n\t *\n\t * A fully dynamic key does not type, which is correct and is also the case\n\t * people will hit — so the escape hatch is a named method rather than a\n\t * cast, and it runs the *same* runtime check rather than being a way around\n\t * it.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\topenUrl(key: string): string;\n\n\t/**\n\t * A signed address for one object and one recipient.\n\t *\n\t * Today this is an **S3 presign at the bucket**, which is what works\n\t * unchanged against MinIO locally and against S3 deployed. It is deliberately\n\t * not described as a CDN URL: CloudFront signing is a different mechanism,\n\t * with different keys, against a different host, and it needs key material\n\t * this construct does not yet declare.\n\t *\n\t * @param expiresIn - minutes, matching `getUploadURL`.\n\t */\n\tsignedUrl(key: string, expiresIn?: number): Promise<string>;\n\n\t/**\n\t * The address of a processor's derivative of an open object — the\n\t * thumbnail, not the original.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t * @throws {ProcessorNotOnThisServer} for another file server's processor.\n\t */\n\tprocessedUrl<\n\t\tTPattern extends string,\n\t\tTSchema extends StandardSchemaV1 | undefined,\n\t>(\n\t\tprocessor: Processor<TPattern, TSchema, any, any>,\n\t\tparams: ProcessorUrlParams<TPattern, TSchema>,\n\t\tkey: string,\n\t): string;\n}\n\n/**\n * What addresses a derivative: the values the processor's schema accepts —\n * its input, since these go into a path — or, without one, the raw strings.\n */\nexport type ProcessorUrlParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferInput<TSchema>\n\t: PatternParams<TPattern>;\n\n/** A processed URL was asked of a file server the processor is not on. */\nexport class ProcessorNotOnThisServer extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly server: string,\n\t\treadonly expected: string,\n\t) {\n\t\tsuper(\n\t\t\t`The processor at '${pattern}' belongs to '${server}', not '${expected}'. ` +\n\t\t\t\t`Ask its own file server for the URL: services.<its id>.processedUrl(…).`,\n\t\t);\n\t\tthis.name = 'ProcessorNotOnThisServer';\n\t}\n}\n\nexport interface FileServerOptions<TOpen extends string = never> {\n\t/**\n\t * Paths served without a signature. Everything else needs one.\n\t *\n\t * Private by default: a bucket where forgetting a flag publishes user\n\t * uploads is the wrong default, so this is an exception list, and listing it\n\t * in code means exactly one set of paths is unauthenticated and it is\n\t * reviewable in a diff.\n\t *\n\t * Uploading is deliberately *not* restricted to these. Writing to a path\n\t * that happens to be open is ordinary; the only asymmetry worth enforcing is\n\t * that you cannot hand out an unsigned URL for something the server would\n\t * refuse to serve unsigned.\n\t */\n\topen?: readonly TOpen[];\n\t/**\n\t * Open paths whose objects never change once written — keyed by a content\n\t * hash or a file id — so every client may keep them forever: the edge\n\t * sends `Cache-Control: public, max-age=31536000, immutable`, over\n\t * whatever the object was stored with.\n\t *\n\t * A subset of `open`, because a signed object is never served by the edge.\n\t * Only say it of paths whose keys are written once: a client holding an\n\t * immutable copy never asks again.\n\t */\n\timmutable?: readonly string[];\n\t/** Keep previous versions of an object. */\n\tversioned?: boolean;\n\t/**\n\t * Delete the objects under each prefix this many days after they were\n\t * written — `{ 'previews/': { days: 7 } }`. A setting of the bucket this\n\t * server vends, so it cannot be given with `origin`.\n\t */\n\texpire?: ObjectExpiry;\n\t/**\n\t * How long its processors' derivatives are kept in the bucket before it\n\t * deletes them — 30 days unless said. They are remade on the next request,\n\t * so this trades storage for the work of making one again.\n\t */\n\tderived?: { readonly days: number };\n\t/**\n\t * What its processor unit emits — the `Telemetry` construct, as a worker\n\t * takes it: each request is a span, and the deploy hands the unit the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * A bucket declared elsewhere, instead of one of this server's own.\n\t *\n\t * `new FileServer('Uploads')` declares both nodes; this fronts a bucket that\n\t * already exists, which is also how the two edges come back when you want\n\t * them separately — a handler depending on the bucket writes, a handler\n\t * depending on the server mints URLs.\n\t */\n\torigin?: Declarable;\n}\n\n/** An immutable pattern that no open pattern admits. */\nexport class ImmutableNotOpen extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly pattern: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' says '${pattern}' is immutable, and no open path admits it` +\n\t\t\t\t(open.length ? ` (open: ${open.join(', ')})` : ' — it opens none') +\n\t\t\t\t'. Only an open path is served by the edge, so only one can be ' +\n\t\t\t\t'cached there: add it to `open`, or narrow it to one that is.',\n\t\t);\n\t\tthis.name = 'ImmutableNotOpen';\n\t}\n}\n\n/**\n * A bucket setting given to a file server that fronts a bucket declared\n * elsewhere — where the bucket's own construct is the one that says it.\n */\nexport class BucketOptionOnOrigin extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\treadonly origin: string,\n\t\treadonly option: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' fronts '${origin}', which declares itself, so '${option}' ` +\n\t\t\t\t`belongs on the construct that declares '${origin}', not on the file server.`,\n\t\t);\n\t\tthis.name = 'BucketOptionOnOrigin';\n\t}\n}\n\n/**\n * A bucket method called on a file server's client that was handed only its\n * public address — a frontend's plain edge.\n */\nexport class FileServerReadOnly extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly method: string,\n\t\treadonly key: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' was reached through its public address only, so it serves ` +\n\t\t\t\t`and cannot ${method}(): ${key} is not in this process's environment. ` +\n\t\t\t\t`A site or app whose server half writes or presigns depends on ` +\n\t\t\t\t`'${id}'.server instead — .dependsOn([${id.charAt(0).toLowerCase()}${id.slice(1)}.server]).`,\n\t\t);\n\t\tthis.name = 'FileServerReadOnly';\n\t}\n}\n\n/** Names asked of any object, which a read-only client must not answer. */\nconst INTROSPECTED = new Set([\n\t'then',\n\t'toJSON',\n\t'constructor',\n\t'asymmetricMatch',\n\t'$$typeof',\n\t'nodeType',\n\t'inspect',\n]);\n\n/**\n * The bucket half of a client that has no bucket: every method throws\n * {@link FileServerReadOnly}, naming itself.\n *\n * A proxy rather than a list of stubs, so a method the storage client grows\n * later refuses the same way. What a runtime asks of any object is left\n * alone: `then`, because a client is resolved from a promise, and the names a\n * serialiser or a test's printer looks for.\n */\nfunction readOnlyStorage(id: string, key: string): StorageClient {\n\treturn new Proxy({} as StorageClient, {\n\t\tget(_target, property) {\n\t\t\tif (typeof property !== 'string' || INTROSPECTED.has(property)) return;\n\t\t\treturn () => {\n\t\t\t\tthrow new FileServerReadOnly(id, property, key);\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** A key was asked to be served unsigned, and no open pattern admits it. */\nexport class NotOpen extends Error {\n\tconstructor(\n\t\treadonly key: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${key}' is not served without a signature. ` +\n\t\t\t\t(open.length\n\t\t\t\t\t? `Open paths: ${open.join(', ')}. Use signedUrl() for anything else.`\n\t\t\t\t\t: 'This file server declares no open paths, so every object needs signedUrl().'),\n\t\t);\n\t\tthis.name = 'NotOpen';\n\t}\n}\n\nexport class FileServer<\n\tTName extends string = string,\n\tTOpen extends string = never,\n> implements Construct<TName, FileServerClient<TOpen>>, HasPublicFace\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, FileServerClient<TOpen>>;\n\n\t/** The id of the surface node, as opposed to the bucket's. */\n\treadonly surfaceId: string;\n\n\tprivate readonly open: readonly string[];\n\tprivate readonly immutable: readonly string[];\n\n\t/** The vended bucket's expiry, checked once: prefix → days. */\n\tprivate readonly expire: Record<string, number> | undefined;\n\n\t/** Days its processors' derivatives are kept, when it says. */\n\tprivate readonly derivedDays: number | undefined;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the client reads cannot drift.\n\t */\n\tprivate readonly keys: { origin: string; server: string };\n\n\t/**\n\t * How a processor reaches the bucket: the bucket's own URL and nothing of\n\t * the serving half, which a processor never needs. A field, not a getter:\n\t * services are cached by object identity.\n\t */\n\tprivate readonly origin: Service<string, StorageClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: FileServerOptions<TOpen> = {},\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.open = options.open ?? [];\n\t\tthis.immutable = options.immutable ?? [];\n\t\tfor (const pattern of this.immutable) {\n\t\t\tif (!this.covers(pattern)) {\n\t\t\t\tthrow new ImmutableNotOpen(canonical, pattern, this.open);\n\t\t\t}\n\t\t}\n\n\t\t// The surface takes the suffix and the bucket keeps the plain id, which\n\t\t// is what makes \"serve a bucket I already have\" an edit that adds a node\n\t\t// instead of renaming the one holding the data.\n\t\tconst originId = options.origin?.id ?? canonical;\n\t\tif (options.origin && options.expire) {\n\t\t\tthrow new BucketOptionOnOrigin(canonical, originId, 'expire');\n\t\t}\n\t\tthis.expire = expiryDays(canonical, options.expire);\n\t\tthis.derivedDays = options.derived\n\t\t\t? expiryDays(canonical, { [DERIVED_PREFIX]: options.derived })?.[\n\t\t\t\t\tDERIVED_PREFIX\n\t\t\t\t]\n\t\t\t: undefined;\n\t\tthis.surfaceId = fileServerSurfaceId(canonical);\n\n\t\tthis.keys = {\n\t\t\torigin: provideKey(originId, 'connectionString'),\n\t\t\tserver: providedKeyFor(this.surfaceId, 'file-server', 'url'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\n\t\tconst originKey = this.keys.origin;\n\t\tthis.origin = {\n\t\t\tserviceName: `${serviceKey(originId)}ProcessorOrigin`,\n\t\t\tregister: ({ envParser }) => {\n\t\t\t\tconst { url } = envParser\n\t\t\t\t\t.create((get) => ({ url: get(originKey).string() }))\n\t\t\t\t\t.parse();\n\t\t\t\treturn createStorageClient(url);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * A processor behind one path pattern of this server: a handler that makes\n\t * a derivative of an open object on read.\n\t *\n\t * ```ts\n\t * export const thumbnails = assets\n\t * .process('/i/:width/*')\n\t * .params(z.object({ width: z.enum(['64', '256', '1024']) }))\n\t * .native(['sharp'])\n\t * .handle(async ({ params, object }) => ({\n\t * body: await sharp(await object.bytes()).resize(Number(params.width)).webp().toBuffer(),\n\t * contentType: 'image/webp',\n\t * cache: 'immutable',\n\t * }));\n\t * ```\n\t *\n\t * Open paths only: a key no `open` pattern admits is answered 404, as an\n\t * unsigned read of it would be.\n\t *\n\t * @throws {ProcessorPatternInvalid} for a pattern the edge cannot route.\n\t */\n\tprocess<TPattern extends `/${string}/*`>(\n\t\tpattern: TPattern,\n\t\toptions: { logger?: Logger } = {},\n\t): ProcessorBuilder<TPattern> {\n\t\treturn new ProcessorBuilder<TPattern>({\n\t\t\tparsed: parsePattern(pattern),\n\t\t\tsurfaceId: this.surfaceId,\n\t\t\tbucketId: this.options.origin?.id ?? this.id,\n\t\t\torigin: this.origin,\n\t\t\tserves: (key) => this.serves(key),\n\t\t\tlogger: (options.logger ?? DEFAULT_LOGGER) as Logger,\n\t\t\tnative: [],\n\t\t\tservices: [],\n\t\t\tconstructs: [],\n\t\t});\n\t}\n\n\t/**\n\t * The served surface: what a site's or a mobile app's plain\n\t * `.dependsOn([uploads])` points at.\n\t *\n\t * Its address is public, so the frontend is built with it\n\t * (`VITE_UPLOADS_URL`) — and it is all the frontend gets: no bucket, no\n\t * key. A backend's plain edge is to the bucket, as it presigns and writes.\n\t */\n\tget publicFace(): Declarable {\n\t\tconst surface = this.declare().find(\n\t\t\t(declaration) => declaration.id === this.surfaceId,\n\t\t);\n\n\t\treturn {\n\t\t\tid: this.surfaceId,\n\t\t\tdeclare: () => (surface ? [surface] : []),\n\t\t};\n\t}\n\n\t/**\n\t * Everything: the bucket, its credentials, and the address it is served\n\t * on.\n\t *\n\t * What a backend's plain edge already is. A frontend asks for it by name —\n\t * `.dependsOn([uploads.server])` — when its server half uploads or\n\t * presigns: a full-stack site's, never a bundle's. The bucket's connection\n\t * is never inlined into a bundle either way; only the served address is.\n\t */\n\tget server(): Declarable {\n\t\tconst originId = this.options.origin?.id ?? this.id;\n\t\tconst declarations = this.options.origin\n\t\t\t? this.options.origin.declare()\n\t\t\t: this.declare();\n\n\t\treturn { id: originId, declare: () => declarations };\n\t}\n\n\t/**\n\t * The bucket and the surface over it — or just the surface, when the bucket\n\t * was declared elsewhere.\n\t *\n\t * The surface names its origin through `of`, which is what makes the\n\t * reference check work: an origin resolving to nothing is a build failure,\n\t * the same guarantee `assertDerivations` already gives a reader and a schema\n\t * tenant.\n\t */\n\tdeclare(): Declaration[] {\n\t\tconst origin = this.options.origin;\n\n\t\tconst surface: Declaration = {\n\t\t\tkind: 'file-server',\n\t\t\tid: this.surfaceId,\n\t\t\tof: origin?.id ?? this.id,\n\t\t\t...(this.open.length ? { open: this.open } : {}),\n\t\t\t...(this.immutable.length ? { immutable: this.immutable } : {}),\n\t\t\t...(this.derivedDays !== undefined\n\t\t\t\t? { derivedDays: this.derivedDays }\n\t\t\t\t: {}),\n\t\t\t...(this.options.telemetry\n\t\t\t\t? { telemetry: this.options.telemetry.id }\n\t\t\t\t: {}),\n\t\t\tprovides: [this.keys.server],\n\t\t};\n\n\t\t// A vended bucket is declared here; a given one already declares itself,\n\t\t// and declaring it twice is the duplication the whole model removes.\n\t\tif (origin) return [surface];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'objects',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.origin],\n\t\t\t\t...(this.options.versioned ? { versioned: true } : {}),\n\t\t\t\t...(this.expire ? { expire: this.expire } : {}),\n\t\t\t},\n\t\t\tsurface,\n\t\t];\n\t}\n\n\t/**\n\t * The bucket's client, with the serving half added.\n\t *\n\t * Both keys are read here, which is also how the environment reaches a\n\t * handler: the sniffer records what this reads, so `.dependsOn([uploads])`\n\t * carries the bucket's connection and the server's address without either\n\t * being written down beside the handler.\n\t *\n\t * Without the connection — a site's or an app's plain edge, which is to\n\t * the public face — the client serves and does nothing else: its bucket\n\t * methods throw {@link FileServerReadOnly}.\n\t */\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<FileServerClient<TOpen>> {\n\t\tconst { origin, server } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigin: get(this.keys.origin).string().optional(),\n\t\t\t\tserver: get(this.keys.server).string(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tconst storage = origin\n\t\t\t? createStorageClient(origin)\n\t\t\t: readOnlyStorage(this.id, this.keys.origin);\n\t\tconst base = server.replace(/\\/+$/, '');\n\n\t\tconst serve = (key: string): string => {\n\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\n\t\t\treturn `${base}/${key.replace(/^\\/+/, '')}`;\n\t\t};\n\n\t\t// Delegating rather than copying: the bucket half is whatever the driver\n\t\t// produced, including anything it grows later, and only the serving half\n\t\t// is added on top.\n\t\treturn Object.assign(Object.create(storage) as StorageClient, {\n\t\t\turl: serve as (key: Served<TOpen>) => string,\n\t\t\topenUrl: serve,\n\t\t\tsignedUrl: (key: string, expiresIn?: number) =>\n\t\t\t\tstorage.getDownloadURL({ path: key } as never, expiresIn),\n\t\t\tprocessedUrl: (\n\t\t\t\tprocessor: Processor<string, any, any, any>,\n\t\t\t\tparams: Record<string, string | number>,\n\t\t\t\tkey: string,\n\t\t\t) => {\n\t\t\t\tif (processor.surfaceId !== this.surfaceId) {\n\t\t\t\t\tthrow new ProcessorNotOnThisServer(\n\t\t\t\t\t\tprocessor.pattern,\n\t\t\t\t\t\tprocessor.surfaceId,\n\t\t\t\t\t\tthis.surfaceId,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\t\t\t\treturn `${base}${fillPattern(processor.parsed, params, key)}`;\n\t\t\t},\n\t\t}) as FileServerClient<TOpen>;\n\t}\n\n\t/**\n\t * Whether an open pattern admits a key.\n\t *\n\t * The runtime half of {@link Served}, and stricter than it: here a single\n\t * star stops at a segment boundary and a double star does not, which is the\n\t * distinction a template-literal type cannot draw and the infrastructure\n\t * does.\n\t */\n\tprivate serves(key: string): boolean {\n\t\treturn this.open.some((pattern) => globToRegExp(pattern).test(key));\n\t}\n\n\t/**\n\t * Whether every key a pattern admits is open: the pattern itself, each of\n\t * its wildcards taken as a segment of its own, is a key an open pattern\n\t * serves — `brand/logos/*` under `brand/**`, but not `**` under `brand/**`.\n\t */\n\tprivate covers(pattern: string): boolean {\n\t\treturn this.serves(pattern.replace(/\\*\\*/g, 'x/x').replace(/\\*/g, 'x'));\n\t}\n}\n\n/**\n * One open pattern as an anchored expression.\n *\n * A double star crosses `/`; a single star does not. Both are consumed in one\n * left-to-right pass rather than by substitution, so a pattern cannot be\n * rewritten into a placeholder that a later pass mistakes for literal text.\n */\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = '';\n\n\tfor (let index = 0; index < pattern.length; index++) {\n\t\tconst character = pattern[index];\n\n\t\tif (character !== '*') {\n\t\t\tsource += character?.replace(/[.+^${}()|[\\]\\\\?]/, '\\\\$&') ?? '';\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (pattern[index + 1] === '*') {\n\t\t\tsource += '.*';\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tsource += '[^/]*';\n\t}\n\n\treturn new RegExp(`^${source}$`);\n}\n"],"mappings":";;;;;;;;AAyJA,IAAa,2BAAb,cAA8C,MAAM;CAEzC;CACA;CACA;CAHV,YACC,SACA,QACA,UACC;EACD,MACC,qBAAqB,QAAQ,gBAAgB,OAAO,UAAU,SAAS,2EAExE;EAPS,KAAA,UAAA;EACA,KAAA,SAAA;EACA,KAAA,WAAA;EAMT,KAAK,OAAO;CACb;AACD;;AA4DA,IAAa,mBAAb,cAAsC,MAAM;CAEjC;CACA;CACA;CAHV,YACC,IACA,SACA,MACC;EACD,MACC,IAAI,GAAG,UAAU,QAAQ,+CACvB,KAAK,SAAS,WAAW,KAAK,KAAK,IAAI,EAAE,KAAK,sBAC/C,4HAEF;EATS,KAAA,KAAA;EACA,KAAA,UAAA;EACA,KAAA,OAAA;EAQT,KAAK,OAAO;CACb;AACD;;;;;AAMA,IAAa,uBAAb,cAA0C,MAAM;CAErC;CACA;CACA;CAHV,YACC,QACA,QACA,QACC;EACD,MACC,IAAI,OAAO,YAAY,OAAO,gCAAgC,OAAO,4CACzB,OAAO,2BACpD;EAPS,KAAA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AAK,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC;CACvE;AACD;;;;;;;;AASA,SAAS,aAAa,SAAyB;CAC9C,IAAI,SAAS;CAEb,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS;EACpD,MAAM,YAAY,QAAQ;EAE1B,IAAI,cAAc,KAAK;GACtB,UAAU,WAAW,QAAQ,qBAAqB,MAAM,KAAK;GAC7D;EACD;EAEA,IAAI,QAAQ,QAAQ,OAAO,KAAK;GAC/B,UAAU;GACV;GACA;EACD;EAEA,UAAU;CACX;CAEA,OAAO,IAAI,OAAO,IAAI,OAAO,EAAE;AAChC"}
|
|
1
|
+
{"version":3,"file":"file-server.cjs","names":["canonicalId","expiryDays","DERIVED_PREFIX","fileServerSurfaceId","providedKeyFor","serviceKey","createStorageClient","ProcessorBuilder","parsePattern","DEFAULT_LOGGER","fillPattern"],"sources":["../src/file-server.ts"],"sourcesContent":["/**\n * `FileServer` — a domain that serves a bucket's objects.\n *\n * `ObjectStorage` is the bucket: it writes, it presigns, and its URL is never\n * public. Serving those objects on a domain is a different thing, and it is a\n * construct of its own rather than a flag on the bucket — see\n * `docs/design/constructs-paradigm.md`, \"Why a separate construct, and what it\n * costs\", for the comparison that rules the other two shapes out.\n *\n * ```ts\n * export const uploads = new FileServer('Uploads', { open: ['brand/**'] });\n *\n * uploads.getUploadURL({ path, contentType }) // an S3 presign at the bucket\n * uploads.url('brand/logo.png') // open path — no signature\n * uploads.signedUrl('invoices/7.pdf') // one object, one recipient\n * ```\n *\n * **One construct, one client, both halves.** How a file lands in the bucket is\n * the same whether or not it is served, so splitting the upload half from the\n * serving half would be ceremony rather than safety. The client is a *superset*\n * of `StorageClient`, made literal in the type, so anything taking\n * `services.uploads` keeps compiling when the construct behind it grows a\n * serving half.\n *\n * **The id names the bucket, not the surface.** This is the detail that has to\n * be right before anything ships, because getting it backwards is destructive:\n * the migration people actually perform is serving a bucket they already have,\n * and naming the bucket after the construct makes that edit *add* a node rather\n * than rename the one holding the data.\n */\n\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDERIVED_PREFIX,\n\ttype Declaration,\n\tfileServerSurfaceId,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient, type StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type {\n\tConstruct,\n\tDeclarable,\n\tHasPublicFace,\n} from './construct-interface';\nimport { expiryDays, type ObjectExpiry } from './expire';\nimport type { Processor } from './processors/Processor';\nimport { ProcessorBuilder } from './processors/ProcessorBuilder';\nimport {\n\tfillPattern,\n\ttype PatternParams,\n\tparsePattern,\n} from './processors/pattern';\nimport type { Telemetry } from './telemetry';\n\n/**\n * A key an open pattern admits.\n *\n * The same template-literal trick `ConstructName` uses, so `open` is checked at\n * the call site rather than only at the edge:\n *\n * ```ts\n * files.url('brand/logo.png') // ok\n * files.url(`avatars/${id}.png`) // ok — a template literal still matches\n * files.url('invoices/7.pdf') // not assignable — never served unsigned\n * ```\n *\n * A single star and a double star resolve to the same type, stated rather than\n * discovered: a template literal cannot exclude `/`, so this is a prefix-and-\n * suffix guard while the *exact* pattern is enforced by the bucket policy, by\n * the cache behaviour, and by this construct's own runtime check. The type says\n * plausibly open; the infrastructure says definitely.\n */\nexport type Served<P extends string> = P extends `${infer Head}**`\n\t? `${Head}${string}`\n\t: P extends `${infer Head}*${infer Tail}`\n\t\t? `${Head}${string}${Tail}`\n\t\t: P;\n\n/** What consuming a file server hands you: a bucket client that also serves. */\nexport interface FileServerClient<TOpen extends string = never>\n\textends StorageClient {\n\t/**\n\t * The unsigned address of an open object.\n\t *\n\t * Compile-checked against the declared patterns, *and* checked again at\n\t * runtime — a JavaScript caller gets no compiler, and minting an unsigned\n\t * URL for a private object is a leak rather than a mistake.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\turl(key: Served<TOpen>): string;\n\n\t/**\n\t * The same thing for a key the compiler cannot see.\n\t *\n\t * A fully dynamic key does not type, which is correct and is also the case\n\t * people will hit — so the escape hatch is a named method rather than a\n\t * cast, and it runs the *same* runtime check rather than being a way around\n\t * it.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\topenUrl(key: string): string;\n\n\t/**\n\t * A signed address for one object and one recipient.\n\t *\n\t * Today this is an **S3 presign at the bucket**, which is what works\n\t * unchanged against MinIO locally and against S3 deployed. It is deliberately\n\t * not described as a CDN URL: CloudFront signing is a different mechanism,\n\t * with different keys, against a different host, and it needs key material\n\t * this construct does not yet declare.\n\t *\n\t * @param expiresIn - minutes, matching `getUploadURL`.\n\t */\n\tsignedUrl(key: string, expiresIn?: number): Promise<string>;\n\n\t/**\n\t * The address of a processor's derivative of an open object — the\n\t * thumbnail, not the original.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t * @throws {ProcessorNotOnThisServer} for another file server's processor.\n\t */\n\tprocessedUrl<\n\t\tTPattern extends string,\n\t\tTSchema extends StandardSchemaV1 | undefined,\n\t>(\n\t\tprocessor: Processor<TPattern, TSchema, any, any>,\n\t\tparams: ProcessorUrlParams<TPattern, TSchema>,\n\t\tkey: string,\n\t): string;\n}\n\n/**\n * What addresses a derivative: the values the processor's schema accepts —\n * its input, since these go into a path — or, without one, the raw strings.\n */\nexport type ProcessorUrlParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferInput<TSchema>\n\t: PatternParams<TPattern>;\n\n/** A processed URL was asked of a file server the processor is not on. */\nexport class ProcessorNotOnThisServer extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly server: string,\n\t\treadonly expected: string,\n\t) {\n\t\tsuper(\n\t\t\t`The processor at '${pattern}' belongs to '${server}', not '${expected}'. ` +\n\t\t\t\t`Ask its own file server for the URL: services.<its id>.processedUrl(…).`,\n\t\t);\n\t\tthis.name = 'ProcessorNotOnThisServer';\n\t}\n}\n\nexport interface FileServerOptions<TOpen extends string = never> {\n\t/**\n\t * Paths served without a signature. Everything else needs one.\n\t *\n\t * Private by default: a bucket where forgetting a flag publishes user\n\t * uploads is the wrong default, so this is an exception list, and listing it\n\t * in code means exactly one set of paths is unauthenticated and it is\n\t * reviewable in a diff.\n\t *\n\t * Uploading is deliberately *not* restricted to these. Writing to a path\n\t * that happens to be open is ordinary; the only asymmetry worth enforcing is\n\t * that you cannot hand out an unsigned URL for something the server would\n\t * refuse to serve unsigned.\n\t */\n\topen?: readonly TOpen[];\n\t/**\n\t * Open paths whose objects never change once written — keyed by a content\n\t * hash or a file id — so every client may keep them forever: the edge\n\t * sends `Cache-Control: public, max-age=31536000, immutable`, over\n\t * whatever the object was stored with.\n\t *\n\t * A subset of `open`, because a signed object is never served by the edge.\n\t * Only say it of paths whose keys are written once: a client holding an\n\t * immutable copy never asks again.\n\t */\n\timmutable?: readonly string[];\n\t/** Keep previous versions of an object. */\n\tversioned?: boolean;\n\t/**\n\t * Delete the objects under each prefix this many days after they were\n\t * written — `{ 'previews/': { days: 7 } }`. A setting of the bucket this\n\t * server vends, so it cannot be given with `origin`.\n\t */\n\texpire?: ObjectExpiry;\n\t/**\n\t * How long its processors' derivatives are kept in the bucket before it\n\t * deletes them — 30 days unless said. They are remade on the next request,\n\t * so this trades storage for the work of making one again.\n\t */\n\tderived?: { readonly days: number };\n\t/**\n\t * What its processor unit emits — the `Telemetry` construct, as a worker\n\t * takes it: each request is a span, and the deploy hands the unit the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * A bucket declared elsewhere, instead of one of this server's own.\n\t *\n\t * `new FileServer('Uploads')` declares both nodes; this fronts a bucket that\n\t * already exists, which is also how the two edges come back when you want\n\t * them separately — a handler depending on the bucket writes, a handler\n\t * depending on the server mints URLs.\n\t */\n\torigin?: Declarable;\n}\n\n/** An immutable pattern that no open pattern admits. */\nexport class ImmutableNotOpen extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly pattern: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' says '${pattern}' is immutable, and no open path admits it` +\n\t\t\t\t(open.length ? ` (open: ${open.join(', ')})` : ' — it opens none') +\n\t\t\t\t'. Only an open path is served by the edge, so only one can be ' +\n\t\t\t\t'cached there: add it to `open`, or narrow it to one that is.',\n\t\t);\n\t\tthis.name = 'ImmutableNotOpen';\n\t}\n}\n\n/**\n * A bucket setting given to a file server that fronts a bucket declared\n * elsewhere — where the bucket's own construct is the one that says it.\n */\nexport class BucketOptionOnOrigin extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\treadonly origin: string,\n\t\treadonly option: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' fronts '${origin}', which declares itself, so '${option}' ` +\n\t\t\t\t`belongs on the construct that declares '${origin}', not on the file server.`,\n\t\t);\n\t\tthis.name = 'BucketOptionOnOrigin';\n\t}\n}\n\n/**\n * A bucket method called on a file server's client that was handed only its\n * public address — a frontend's plain edge.\n */\nexport class FileServerReadOnly extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly method: string,\n\t\treadonly key: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' was reached through its public address only, so it serves ` +\n\t\t\t\t`and cannot ${method}(): ${key} is not in this process's environment. ` +\n\t\t\t\t`A site or app whose server half writes or presigns depends on ` +\n\t\t\t\t`'${id}'.server instead — .dependsOn([${id.charAt(0).toLowerCase()}${id.slice(1)}.server]).`,\n\t\t);\n\t\tthis.name = 'FileServerReadOnly';\n\t}\n}\n\n/** Names asked of any object, which a read-only client must not answer. */\nconst INTROSPECTED = new Set([\n\t'then',\n\t'toJSON',\n\t'constructor',\n\t'asymmetricMatch',\n\t'$$typeof',\n\t'nodeType',\n\t'inspect',\n]);\n\n/**\n * The bucket half of a client that has no bucket: every method throws\n * {@link FileServerReadOnly}, naming itself.\n *\n * A proxy rather than a list of stubs, so a method the storage client grows\n * later refuses the same way. What a runtime asks of any object is left\n * alone: `then`, because a client is resolved from a promise, and the names a\n * serialiser or a test's printer looks for.\n */\nfunction readOnlyStorage(id: string, key: string): StorageClient {\n\treturn new Proxy({} as StorageClient, {\n\t\tget(_target, property) {\n\t\t\tif (typeof property !== 'string' || INTROSPECTED.has(property)) return;\n\t\t\treturn () => {\n\t\t\t\tthrow new FileServerReadOnly(id, property, key);\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** A key was asked to be served unsigned, and no open pattern admits it. */\nexport class NotOpen extends Error {\n\tconstructor(\n\t\treadonly key: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${key}' is not served without a signature. ` +\n\t\t\t\t(open.length\n\t\t\t\t\t? `Open paths: ${open.join(', ')}. Use signedUrl() for anything else.`\n\t\t\t\t\t: 'This file server declares no open paths, so every object needs signedUrl().'),\n\t\t);\n\t\tthis.name = 'NotOpen';\n\t}\n}\n\nexport class FileServer<\n\tTName extends string = string,\n\tTOpen extends string = never,\n> implements Construct<TName, FileServerClient<TOpen>>, HasPublicFace\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, FileServerClient<TOpen>>;\n\n\t/** The id of the surface node, as opposed to the bucket's. */\n\treadonly surfaceId: string;\n\n\tprivate readonly open: readonly string[];\n\tprivate readonly immutable: readonly string[];\n\n\t/** The vended bucket's expiry, checked once: prefix → days. */\n\tprivate readonly expire: Record<string, number> | undefined;\n\n\t/** Days its processors' derivatives are kept, when it says. */\n\tprivate readonly derivedDays: number | undefined;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the client reads cannot drift.\n\t */\n\tprivate readonly keys: { origin: string; server: string };\n\n\t/**\n\t * How a processor reaches the bucket: the bucket's own URL and nothing of\n\t * the serving half, which a processor never needs. A field, not a getter:\n\t * services are cached by object identity.\n\t */\n\tprivate readonly origin: Service<string, StorageClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: FileServerOptions<TOpen> = {},\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.open = options.open ?? [];\n\t\tthis.immutable = options.immutable ?? [];\n\t\tfor (const pattern of this.immutable) {\n\t\t\tif (!this.covers(pattern)) {\n\t\t\t\tthrow new ImmutableNotOpen(canonical, pattern, this.open);\n\t\t\t}\n\t\t}\n\n\t\t// The surface takes the suffix and the bucket keeps the plain id, which\n\t\t// is what makes \"serve a bucket I already have\" an edit that adds a node\n\t\t// instead of renaming the one holding the data.\n\t\tconst originId = options.origin?.id ?? canonical;\n\t\tif (options.origin && options.expire) {\n\t\t\tthrow new BucketOptionOnOrigin(canonical, originId, 'expire');\n\t\t}\n\t\tthis.expire = expiryDays(canonical, options.expire);\n\t\tthis.derivedDays = options.derived\n\t\t\t? expiryDays(canonical, { [DERIVED_PREFIX]: options.derived })?.[\n\t\t\t\t\tDERIVED_PREFIX\n\t\t\t\t]\n\t\t\t: undefined;\n\t\tthis.surfaceId = fileServerSurfaceId(canonical);\n\n\t\tthis.keys = {\n\t\t\torigin: providedKeyFor(originId, 'objects', 'connectionString'),\n\t\t\tserver: providedKeyFor(this.surfaceId, 'file-server', 'url'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\n\t\tconst originKey = this.keys.origin;\n\t\tthis.origin = {\n\t\t\tserviceName: `${serviceKey(originId)}ProcessorOrigin`,\n\t\t\tregister: ({ envParser }) => {\n\t\t\t\tconst { url } = envParser\n\t\t\t\t\t.create((get) => ({ url: get(originKey).string() }))\n\t\t\t\t\t.parse();\n\t\t\t\treturn createStorageClient(url);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * A processor behind one path pattern of this server: a handler that makes\n\t * a derivative of an open object on read.\n\t *\n\t * ```ts\n\t * export const thumbnails = assets\n\t * .process('/i/:width/*')\n\t * .params(z.object({ width: z.enum(['64', '256', '1024']) }))\n\t * .native(['sharp'])\n\t * .handle(async ({ params, object }) => ({\n\t * body: await sharp(await object.bytes()).resize(Number(params.width)).webp().toBuffer(),\n\t * contentType: 'image/webp',\n\t * cache: 'immutable',\n\t * }));\n\t * ```\n\t *\n\t * Open paths only: a key no `open` pattern admits is answered 404, as an\n\t * unsigned read of it would be.\n\t *\n\t * @throws {ProcessorPatternInvalid} for a pattern the edge cannot route.\n\t */\n\tprocess<TPattern extends `/${string}/*`>(\n\t\tpattern: TPattern,\n\t\toptions: { logger?: Logger } = {},\n\t): ProcessorBuilder<TPattern> {\n\t\treturn new ProcessorBuilder<TPattern>({\n\t\t\tparsed: parsePattern(pattern),\n\t\t\tsurfaceId: this.surfaceId,\n\t\t\tbucketId: this.options.origin?.id ?? this.id,\n\t\t\torigin: this.origin,\n\t\t\tserves: (key) => this.serves(key),\n\t\t\tlogger: (options.logger ?? DEFAULT_LOGGER) as Logger,\n\t\t\tnative: [],\n\t\t\tservices: [],\n\t\t\tconstructs: [],\n\t\t});\n\t}\n\n\t/**\n\t * The served surface: what a site's or a mobile app's plain\n\t * `.dependsOn([uploads])` points at.\n\t *\n\t * Its address is public, so the frontend is built with it\n\t * (`VITE_UPLOADS_URL`) — and it is all the frontend gets: no bucket, no\n\t * key. A backend's plain edge is to the bucket, as it presigns and writes.\n\t */\n\tget publicFace(): Declarable {\n\t\tconst surface = this.declare().find(\n\t\t\t(declaration) => declaration.id === this.surfaceId,\n\t\t);\n\n\t\treturn {\n\t\t\tid: this.surfaceId,\n\t\t\tdeclare: () => (surface ? [surface] : []),\n\t\t};\n\t}\n\n\t/**\n\t * Everything: the bucket, its credentials, and the address it is served\n\t * on.\n\t *\n\t * What a backend's plain edge already is. A frontend asks for it by name —\n\t * `.dependsOn([uploads.server])` — when its server half uploads or\n\t * presigns: a full-stack site's, never a bundle's. The bucket's connection\n\t * is never inlined into a bundle either way; only the served address is.\n\t */\n\tget server(): Declarable {\n\t\tconst originId = this.options.origin?.id ?? this.id;\n\t\tconst declarations = this.options.origin\n\t\t\t? this.options.origin.declare()\n\t\t\t: this.declare();\n\n\t\treturn { id: originId, declare: () => declarations };\n\t}\n\n\t/**\n\t * The bucket and the surface over it — or just the surface, when the bucket\n\t * was declared elsewhere.\n\t *\n\t * The surface names its origin through `of`, which is what makes the\n\t * reference check work: an origin resolving to nothing is a build failure,\n\t * the same guarantee `assertDerivations` already gives a reader and a schema\n\t * tenant.\n\t */\n\tdeclare(): Declaration[] {\n\t\tconst origin = this.options.origin;\n\n\t\tconst surface: Declaration = {\n\t\t\tkind: 'file-server',\n\t\t\tid: this.surfaceId,\n\t\t\tof: origin?.id ?? this.id,\n\t\t\t...(this.open.length ? { open: this.open } : {}),\n\t\t\t...(this.immutable.length ? { immutable: this.immutable } : {}),\n\t\t\t...(this.derivedDays !== undefined\n\t\t\t\t? { derivedDays: this.derivedDays }\n\t\t\t\t: {}),\n\t\t\t...(this.options.telemetry\n\t\t\t\t? { telemetry: this.options.telemetry.id }\n\t\t\t\t: {}),\n\t\t\tprovides: [this.keys.server],\n\t\t};\n\n\t\t// A vended bucket is declared here; a given one already declares itself,\n\t\t// and declaring it twice is the duplication the whole model removes.\n\t\tif (origin) return [surface];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'objects',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.origin],\n\t\t\t\t...(this.options.versioned ? { versioned: true } : {}),\n\t\t\t\t...(this.expire ? { expire: this.expire } : {}),\n\t\t\t},\n\t\t\tsurface,\n\t\t];\n\t}\n\n\t/**\n\t * The bucket's client, with the serving half added.\n\t *\n\t * Both keys are read here, which is also how the environment reaches a\n\t * handler: the sniffer records what this reads, so `.dependsOn([uploads])`\n\t * carries the bucket's connection and the server's address without either\n\t * being written down beside the handler.\n\t *\n\t * Without the connection — a site's or an app's plain edge, which is to\n\t * the public face — the client serves and does nothing else: its bucket\n\t * methods throw {@link FileServerReadOnly}.\n\t */\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<FileServerClient<TOpen>> {\n\t\tconst { origin, server } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigin: get(this.keys.origin).string().optional(),\n\t\t\t\tserver: get(this.keys.server).string(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tconst storage = origin\n\t\t\t? createStorageClient(origin)\n\t\t\t: readOnlyStorage(this.id, this.keys.origin);\n\t\tconst base = server.replace(/\\/+$/, '');\n\n\t\tconst serve = (key: string): string => {\n\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\n\t\t\treturn `${base}/${key.replace(/^\\/+/, '')}`;\n\t\t};\n\n\t\t// Delegating rather than copying: the bucket half is whatever the driver\n\t\t// produced, including anything it grows later, and only the serving half\n\t\t// is added on top.\n\t\treturn Object.assign(Object.create(storage) as StorageClient, {\n\t\t\turl: serve as (key: Served<TOpen>) => string,\n\t\t\topenUrl: serve,\n\t\t\tsignedUrl: (key: string, expiresIn?: number) =>\n\t\t\t\tstorage.getDownloadURL({ path: key } as never, expiresIn),\n\t\t\tprocessedUrl: (\n\t\t\t\tprocessor: Processor<string, any, any, any>,\n\t\t\t\tparams: Record<string, string | number>,\n\t\t\t\tkey: string,\n\t\t\t) => {\n\t\t\t\tif (processor.surfaceId !== this.surfaceId) {\n\t\t\t\t\tthrow new ProcessorNotOnThisServer(\n\t\t\t\t\t\tprocessor.pattern,\n\t\t\t\t\t\tprocessor.surfaceId,\n\t\t\t\t\t\tthis.surfaceId,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\t\t\t\treturn `${base}${fillPattern(processor.parsed, params, key)}`;\n\t\t\t},\n\t\t}) as FileServerClient<TOpen>;\n\t}\n\n\t/**\n\t * Whether an open pattern admits a key.\n\t *\n\t * The runtime half of {@link Served}, and stricter than it: here a single\n\t * star stops at a segment boundary and a double star does not, which is the\n\t * distinction a template-literal type cannot draw and the infrastructure\n\t * does.\n\t */\n\tprivate serves(key: string): boolean {\n\t\treturn this.open.some((pattern) => globToRegExp(pattern).test(key));\n\t}\n\n\t/**\n\t * Whether every key a pattern admits is open: the pattern itself, each of\n\t * its wildcards taken as a segment of its own, is a key an open pattern\n\t * serves — `brand/logos/*` under `brand/**`, but not `**` under `brand/**`.\n\t */\n\tprivate covers(pattern: string): boolean {\n\t\treturn this.serves(pattern.replace(/\\*\\*/g, 'x/x').replace(/\\*/g, 'x'));\n\t}\n}\n\n/**\n * One open pattern as an anchored expression.\n *\n * A double star crosses `/`; a single star does not. Both are consumed in one\n * left-to-right pass rather than by substitution, so a pattern cannot be\n * rewritten into a placeholder that a later pass mistakes for literal text.\n */\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = '';\n\n\tfor (let index = 0; index < pattern.length; index++) {\n\t\tconst character = pattern[index];\n\n\t\tif (character !== '*') {\n\t\t\tsource += character?.replace(/[.+^${}()|[\\]\\\\?]/, '\\\\$&') ?? '';\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (pattern[index + 1] === '*') {\n\t\t\tsource += '.*';\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tsource += '[^/]*';\n\t}\n\n\treturn new RegExp(`^${source}$`);\n}\n"],"mappings":";;;;;;;;AAwJA,IAAa,2BAAb,cAA8C,MAAM;CAEzC;CACA;CACA;CAHV,YACC,SACA,QACA,UACC;EACD,MACC,qBAAqB,QAAQ,gBAAgB,OAAO,UAAU,SAAS,2EAExE;EAPS,KAAA,UAAA;EACA,KAAA,SAAA;EACA,KAAA,WAAA;EAMT,KAAK,OAAO;CACb;AACD;;AA4DA,IAAa,mBAAb,cAAsC,MAAM;CAEjC;CACA;CACA;CAHV,YACC,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KAAK,SACN;IAED,IAAI,CAAC,KAAK,OAAO,GAAG,GAAG,MAAM,IAAI,QAAQ,KAAK,KAAK,IAAI;IACvD,OAAO,GAAG,OAAOI,gBAAAA,YAAY,UAAU,QAAQ,QAAQ,GAAG;GAC3D;EACD,CAAC;CACF;;;;;;;;;CAUA,OAAe,KAAsB;EACpC,OAAO,KAAK,KAAK,MAAM,YAAY,aAAa,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC;CACnE;;;;;;CAOA,OAAe,SAA0B;EACxC,OAAO,KAAK,OAAO,QAAQ,QAAQ,SAAS,KAAK,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC;CACvE;AACD;;;;;;;;AASA,SAAS,aAAa,SAAyB;CAC9C,IAAI,SAAS;CAEb,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS;EACpD,MAAM,YAAY,QAAQ;EAE1B,IAAI,cAAc,KAAK;GACtB,UAAU,WAAW,QAAQ,qBAAqB,MAAM,KAAK;GAC7D;EACD;EAEA,IAAI,QAAQ,QAAQ,OAAO,KAAK;GAC/B,UAAU;GACV;GACA;EACD;EAEA,UAAU;CACX;CAEA,OAAO,IAAI,OAAO,IAAI,OAAO,EAAE;AAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-server.d.cts","names":[],"sources":["../src/file-server.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"file-server.d.cts","names":[],"sources":["../src/file-server.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;YA8EY,OAAO,oBAAoB,mBAAmB,cACpD,kBACH,mBAAmB,cAAc,YAC7B,gBAAgB,SACnB;;iBAGa,iBAAiB,sCACzB;;;;;;;;;;EAUR,IAAI,KAAK,OAAO;;;;;;;;;;;EAYhB,QAAQ;;;;;;;;;;;;EAaR,UAAU,aAAa,qBAAqB;;;;;;;;EAS5C,aACC,yBACA,gBAAgB,8BAEhB,WAAW,UAAU,UAAU,oBAC/B,QAAQ,mBAAmB,UAAU,UACrC;;;;;;YAQU,mBACX,yBACA,gBAAgB,gCACb,gBAAgB,mBACjB,iBAAiB,WAAW,WAC5B,cAAc;;qBAGJ,iCAAiC;WAEnC;WACA;WACA;EAHV,YACU,iBACA,gBACA;;iBAUM,kBAAkB;;;;;;;;;;;;;;EAclC,gBAAgB;;;;;;;;;;;EAWhB;;EAEA;;;;;;EAMA,SAAS;;;;;;EAMT;aAAqB;;;;;;;EAMrB,YAAY;;;;;;;;;EASZ,SAAS;;;qBAIG,yBAAyB;WAE3B;WACA;WACA;EAHV,YACU,YACA,iBACA;;;;;;qBAgBE,6BAA6B;WAE/B;WACA;WACA;EAHV,YACU,gBACA,gBACA;;;;;;qBAcE,2BAA2B;WAE7B;WACA;WACA;EAHV,YACU,YACA,gBACA;;;qBA4CE,gBAAgB;WAElB;WACA;EAFV,YACU,aACA;;qBAYE,WACZ,+BACA,yCACY,UAAU,OAAO,iBAAiB,SAAS;mBAgCrC;WA9BT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ,iBAAiB;;WAGvD;mBAEQ;mBACA;;mBAGA;;mBAGA;;;;;mBAMA;;;;;;mBAOA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS,kBAAkB;;;;;;;;;;;;;;;;;;;;;;EAwE7C,QAAQ,iCACP,SAAS,UACT;IAAW,SAAS;MAClB,iBAAiB;;;;;;;;;MAsBhB,cAAc;;;;;;;;;;MAoBd,UAAU;;;;;;;;;;EAkBd,WAAW;;;;;;;;;;;;;UA8CG;;;;;;;;;UAuDN;;;;;;UASA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-server.d.mts","names":[],"sources":["../src/file-server.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"file-server.d.mts","names":[],"sources":["../src/file-server.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;YA8E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;;;;;;UASA"}
|
package/dist/file-server.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as expiryDays } from "./expire-CpzUAfr9.mjs";
|
|
2
2
|
import { a as parsePattern, o as ProcessorBuilder, r as fillPattern } from "./pattern-C1CEcglD.mjs";
|
|
3
|
-
import { DERIVED_PREFIX, canonicalId, fileServerSurfaceId,
|
|
3
|
+
import { DERIVED_PREFIX, canonicalId, fileServerSurfaceId, providedKeyFor, serviceKey } from "@geekmidas/manifest";
|
|
4
4
|
import { createStorageClient } from "@geekmidas/storage";
|
|
5
5
|
import { DEFAULT_LOGGER } from "@geekmidas/logger/console";
|
|
6
6
|
//#region src/file-server.ts
|
|
@@ -136,7 +136,7 @@ var FileServer = class {
|
|
|
136
136
|
this.derivedDays = options.derived ? expiryDays(canonical, { [DERIVED_PREFIX]: options.derived })?.[DERIVED_PREFIX] : void 0;
|
|
137
137
|
this.surfaceId = fileServerSurfaceId(canonical);
|
|
138
138
|
this.keys = {
|
|
139
|
-
origin:
|
|
139
|
+
origin: providedKeyFor(originId, "objects", "connectionString"),
|
|
140
140
|
server: providedKeyFor(this.surfaceId, "file-server", "url")
|
|
141
141
|
};
|
|
142
142
|
this.service = {
|
package/dist/file-server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-server.mjs","names":[],"sources":["../src/file-server.ts"],"sourcesContent":["/**\n * `FileServer` — a domain that serves a bucket's objects.\n *\n * `ObjectStorage` is the bucket: it writes, it presigns, and its URL is never\n * public. Serving those objects on a domain is a different thing, and it is a\n * construct of its own rather than a flag on the bucket — see\n * `docs/design/constructs-paradigm.md`, \"Why a separate construct, and what it\n * costs\", for the comparison that rules the other two shapes out.\n *\n * ```ts\n * export const uploads = new FileServer('Uploads', { open: ['brand/**'] });\n *\n * uploads.getUploadURL({ path, contentType }) // an S3 presign at the bucket\n * uploads.url('brand/logo.png') // open path — no signature\n * uploads.signedUrl('invoices/7.pdf') // one object, one recipient\n * ```\n *\n * **One construct, one client, both halves.** How a file lands in the bucket is\n * the same whether or not it is served, so splitting the upload half from the\n * serving half would be ceremony rather than safety. The client is a *superset*\n * of `StorageClient`, made literal in the type, so anything taking\n * `services.uploads` keeps compiling when the construct behind it grows a\n * serving half.\n *\n * **The id names the bucket, not the surface.** This is the detail that has to\n * be right before anything ships, because getting it backwards is destructive:\n * the migration people actually perform is serving a bucket they already have,\n * and naming the bucket after the construct makes that edit *add* a node rather\n * than rename the one holding the data.\n */\n\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDERIVED_PREFIX,\n\ttype Declaration,\n\tfileServerSurfaceId,\n\tprovidedKeyFor,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient, type StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type {\n\tConstruct,\n\tDeclarable,\n\tHasPublicFace,\n} from './construct-interface';\nimport { expiryDays, type ObjectExpiry } from './expire';\nimport type { Processor } from './processors/Processor';\nimport { ProcessorBuilder } from './processors/ProcessorBuilder';\nimport {\n\tfillPattern,\n\ttype PatternParams,\n\tparsePattern,\n} from './processors/pattern';\nimport type { Telemetry } from './telemetry';\n\n/**\n * A key an open pattern admits.\n *\n * The same template-literal trick `ConstructName` uses, so `open` is checked at\n * the call site rather than only at the edge:\n *\n * ```ts\n * files.url('brand/logo.png') // ok\n * files.url(`avatars/${id}.png`) // ok — a template literal still matches\n * files.url('invoices/7.pdf') // not assignable — never served unsigned\n * ```\n *\n * A single star and a double star resolve to the same type, stated rather than\n * discovered: a template literal cannot exclude `/`, so this is a prefix-and-\n * suffix guard while the *exact* pattern is enforced by the bucket policy, by\n * the cache behaviour, and by this construct's own runtime check. The type says\n * plausibly open; the infrastructure says definitely.\n */\nexport type Served<P extends string> = P extends `${infer Head}**`\n\t? `${Head}${string}`\n\t: P extends `${infer Head}*${infer Tail}`\n\t\t? `${Head}${string}${Tail}`\n\t\t: P;\n\n/** What consuming a file server hands you: a bucket client that also serves. */\nexport interface FileServerClient<TOpen extends string = never>\n\textends StorageClient {\n\t/**\n\t * The unsigned address of an open object.\n\t *\n\t * Compile-checked against the declared patterns, *and* checked again at\n\t * runtime — a JavaScript caller gets no compiler, and minting an unsigned\n\t * URL for a private object is a leak rather than a mistake.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\turl(key: Served<TOpen>): string;\n\n\t/**\n\t * The same thing for a key the compiler cannot see.\n\t *\n\t * A fully dynamic key does not type, which is correct and is also the case\n\t * people will hit — so the escape hatch is a named method rather than a\n\t * cast, and it runs the *same* runtime check rather than being a way around\n\t * it.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\topenUrl(key: string): string;\n\n\t/**\n\t * A signed address for one object and one recipient.\n\t *\n\t * Today this is an **S3 presign at the bucket**, which is what works\n\t * unchanged against MinIO locally and against S3 deployed. It is deliberately\n\t * not described as a CDN URL: CloudFront signing is a different mechanism,\n\t * with different keys, against a different host, and it needs key material\n\t * this construct does not yet declare.\n\t *\n\t * @param expiresIn - minutes, matching `getUploadURL`.\n\t */\n\tsignedUrl(key: string, expiresIn?: number): Promise<string>;\n\n\t/**\n\t * The address of a processor's derivative of an open object — the\n\t * thumbnail, not the original.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t * @throws {ProcessorNotOnThisServer} for another file server's processor.\n\t */\n\tprocessedUrl<\n\t\tTPattern extends string,\n\t\tTSchema extends StandardSchemaV1 | undefined,\n\t>(\n\t\tprocessor: Processor<TPattern, TSchema, any, any>,\n\t\tparams: ProcessorUrlParams<TPattern, TSchema>,\n\t\tkey: string,\n\t): string;\n}\n\n/**\n * What addresses a derivative: the values the processor's schema accepts —\n * its input, since these go into a path — or, without one, the raw strings.\n */\nexport type ProcessorUrlParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferInput<TSchema>\n\t: PatternParams<TPattern>;\n\n/** A processed URL was asked of a file server the processor is not on. */\nexport class ProcessorNotOnThisServer extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly server: string,\n\t\treadonly expected: string,\n\t) {\n\t\tsuper(\n\t\t\t`The processor at '${pattern}' belongs to '${server}', not '${expected}'. ` +\n\t\t\t\t`Ask its own file server for the URL: services.<its id>.processedUrl(…).`,\n\t\t);\n\t\tthis.name = 'ProcessorNotOnThisServer';\n\t}\n}\n\nexport interface FileServerOptions<TOpen extends string = never> {\n\t/**\n\t * Paths served without a signature. Everything else needs one.\n\t *\n\t * Private by default: a bucket where forgetting a flag publishes user\n\t * uploads is the wrong default, so this is an exception list, and listing it\n\t * in code means exactly one set of paths is unauthenticated and it is\n\t * reviewable in a diff.\n\t *\n\t * Uploading is deliberately *not* restricted to these. Writing to a path\n\t * that happens to be open is ordinary; the only asymmetry worth enforcing is\n\t * that you cannot hand out an unsigned URL for something the server would\n\t * refuse to serve unsigned.\n\t */\n\topen?: readonly TOpen[];\n\t/**\n\t * Open paths whose objects never change once written — keyed by a content\n\t * hash or a file id — so every client may keep them forever: the edge\n\t * sends `Cache-Control: public, max-age=31536000, immutable`, over\n\t * whatever the object was stored with.\n\t *\n\t * A subset of `open`, because a signed object is never served by the edge.\n\t * Only say it of paths whose keys are written once: a client holding an\n\t * immutable copy never asks again.\n\t */\n\timmutable?: readonly string[];\n\t/** Keep previous versions of an object. */\n\tversioned?: boolean;\n\t/**\n\t * Delete the objects under each prefix this many days after they were\n\t * written — `{ 'previews/': { days: 7 } }`. A setting of the bucket this\n\t * server vends, so it cannot be given with `origin`.\n\t */\n\texpire?: ObjectExpiry;\n\t/**\n\t * How long its processors' derivatives are kept in the bucket before it\n\t * deletes them — 30 days unless said. They are remade on the next request,\n\t * so this trades storage for the work of making one again.\n\t */\n\tderived?: { readonly days: number };\n\t/**\n\t * What its processor unit emits — the `Telemetry` construct, as a worker\n\t * takes it: each request is a span, and the deploy hands the unit the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * A bucket declared elsewhere, instead of one of this server's own.\n\t *\n\t * `new FileServer('Uploads')` declares both nodes; this fronts a bucket that\n\t * already exists, which is also how the two edges come back when you want\n\t * them separately — a handler depending on the bucket writes, a handler\n\t * depending on the server mints URLs.\n\t */\n\torigin?: Declarable;\n}\n\n/** An immutable pattern that no open pattern admits. */\nexport class ImmutableNotOpen extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly pattern: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' says '${pattern}' is immutable, and no open path admits it` +\n\t\t\t\t(open.length ? ` (open: ${open.join(', ')})` : ' — it opens none') +\n\t\t\t\t'. Only an open path is served by the edge, so only one can be ' +\n\t\t\t\t'cached there: add it to `open`, or narrow it to one that is.',\n\t\t);\n\t\tthis.name = 'ImmutableNotOpen';\n\t}\n}\n\n/**\n * A bucket setting given to a file server that fronts a bucket declared\n * elsewhere — where the bucket's own construct is the one that says it.\n */\nexport class BucketOptionOnOrigin extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\treadonly origin: string,\n\t\treadonly option: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' fronts '${origin}', which declares itself, so '${option}' ` +\n\t\t\t\t`belongs on the construct that declares '${origin}', not on the file server.`,\n\t\t);\n\t\tthis.name = 'BucketOptionOnOrigin';\n\t}\n}\n\n/**\n * A bucket method called on a file server's client that was handed only its\n * public address — a frontend's plain edge.\n */\nexport class FileServerReadOnly extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly method: string,\n\t\treadonly key: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' was reached through its public address only, so it serves ` +\n\t\t\t\t`and cannot ${method}(): ${key} is not in this process's environment. ` +\n\t\t\t\t`A site or app whose server half writes or presigns depends on ` +\n\t\t\t\t`'${id}'.server instead — .dependsOn([${id.charAt(0).toLowerCase()}${id.slice(1)}.server]).`,\n\t\t);\n\t\tthis.name = 'FileServerReadOnly';\n\t}\n}\n\n/** Names asked of any object, which a read-only client must not answer. */\nconst INTROSPECTED = new Set([\n\t'then',\n\t'toJSON',\n\t'constructor',\n\t'asymmetricMatch',\n\t'$$typeof',\n\t'nodeType',\n\t'inspect',\n]);\n\n/**\n * The bucket half of a client that has no bucket: every method throws\n * {@link FileServerReadOnly}, naming itself.\n *\n * A proxy rather than a list of stubs, so a method the storage client grows\n * later refuses the same way. What a runtime asks of any object is left\n * alone: `then`, because a client is resolved from a promise, and the names a\n * serialiser or a test's printer looks for.\n */\nfunction readOnlyStorage(id: string, key: string): StorageClient {\n\treturn new Proxy({} as StorageClient, {\n\t\tget(_target, property) {\n\t\t\tif (typeof property !== 'string' || INTROSPECTED.has(property)) return;\n\t\t\treturn () => {\n\t\t\t\tthrow new FileServerReadOnly(id, property, key);\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** A key was asked to be served unsigned, and no open pattern admits it. */\nexport class NotOpen extends Error {\n\tconstructor(\n\t\treadonly key: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${key}' is not served without a signature. ` +\n\t\t\t\t(open.length\n\t\t\t\t\t? `Open paths: ${open.join(', ')}. Use signedUrl() for anything else.`\n\t\t\t\t\t: 'This file server declares no open paths, so every object needs signedUrl().'),\n\t\t);\n\t\tthis.name = 'NotOpen';\n\t}\n}\n\nexport class FileServer<\n\tTName extends string = string,\n\tTOpen extends string = never,\n> implements Construct<TName, FileServerClient<TOpen>>, HasPublicFace\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, FileServerClient<TOpen>>;\n\n\t/** The id of the surface node, as opposed to the bucket's. */\n\treadonly surfaceId: string;\n\n\tprivate readonly open: readonly string[];\n\tprivate readonly immutable: readonly string[];\n\n\t/** The vended bucket's expiry, checked once: prefix → days. */\n\tprivate readonly expire: Record<string, number> | undefined;\n\n\t/** Days its processors' derivatives are kept, when it says. */\n\tprivate readonly derivedDays: number | undefined;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the client reads cannot drift.\n\t */\n\tprivate readonly keys: { origin: string; server: string };\n\n\t/**\n\t * How a processor reaches the bucket: the bucket's own URL and nothing of\n\t * the serving half, which a processor never needs. A field, not a getter:\n\t * services are cached by object identity.\n\t */\n\tprivate readonly origin: Service<string, StorageClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: FileServerOptions<TOpen> = {},\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.open = options.open ?? [];\n\t\tthis.immutable = options.immutable ?? [];\n\t\tfor (const pattern of this.immutable) {\n\t\t\tif (!this.covers(pattern)) {\n\t\t\t\tthrow new ImmutableNotOpen(canonical, pattern, this.open);\n\t\t\t}\n\t\t}\n\n\t\t// The surface takes the suffix and the bucket keeps the plain id, which\n\t\t// is what makes \"serve a bucket I already have\" an edit that adds a node\n\t\t// instead of renaming the one holding the data.\n\t\tconst originId = options.origin?.id ?? canonical;\n\t\tif (options.origin && options.expire) {\n\t\t\tthrow new BucketOptionOnOrigin(canonical, originId, 'expire');\n\t\t}\n\t\tthis.expire = expiryDays(canonical, options.expire);\n\t\tthis.derivedDays = options.derived\n\t\t\t? expiryDays(canonical, { [DERIVED_PREFIX]: options.derived })?.[\n\t\t\t\t\tDERIVED_PREFIX\n\t\t\t\t]\n\t\t\t: undefined;\n\t\tthis.surfaceId = fileServerSurfaceId(canonical);\n\n\t\tthis.keys = {\n\t\t\torigin: provideKey(originId, 'connectionString'),\n\t\t\tserver: providedKeyFor(this.surfaceId, 'file-server', 'url'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\n\t\tconst originKey = this.keys.origin;\n\t\tthis.origin = {\n\t\t\tserviceName: `${serviceKey(originId)}ProcessorOrigin`,\n\t\t\tregister: ({ envParser }) => {\n\t\t\t\tconst { url } = envParser\n\t\t\t\t\t.create((get) => ({ url: get(originKey).string() }))\n\t\t\t\t\t.parse();\n\t\t\t\treturn createStorageClient(url);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * A processor behind one path pattern of this server: a handler that makes\n\t * a derivative of an open object on read.\n\t *\n\t * ```ts\n\t * export const thumbnails = assets\n\t * .process('/i/:width/*')\n\t * .params(z.object({ width: z.enum(['64', '256', '1024']) }))\n\t * .native(['sharp'])\n\t * .handle(async ({ params, object }) => ({\n\t * body: await sharp(await object.bytes()).resize(Number(params.width)).webp().toBuffer(),\n\t * contentType: 'image/webp',\n\t * cache: 'immutable',\n\t * }));\n\t * ```\n\t *\n\t * Open paths only: a key no `open` pattern admits is answered 404, as an\n\t * unsigned read of it would be.\n\t *\n\t * @throws {ProcessorPatternInvalid} for a pattern the edge cannot route.\n\t */\n\tprocess<TPattern extends `/${string}/*`>(\n\t\tpattern: TPattern,\n\t\toptions: { logger?: Logger } = {},\n\t): ProcessorBuilder<TPattern> {\n\t\treturn new ProcessorBuilder<TPattern>({\n\t\t\tparsed: parsePattern(pattern),\n\t\t\tsurfaceId: this.surfaceId,\n\t\t\tbucketId: this.options.origin?.id ?? this.id,\n\t\t\torigin: this.origin,\n\t\t\tserves: (key) => this.serves(key),\n\t\t\tlogger: (options.logger ?? DEFAULT_LOGGER) as Logger,\n\t\t\tnative: [],\n\t\t\tservices: [],\n\t\t\tconstructs: [],\n\t\t});\n\t}\n\n\t/**\n\t * The served surface: what a site's or a mobile app's plain\n\t * `.dependsOn([uploads])` points at.\n\t *\n\t * Its address is public, so the frontend is built with it\n\t * (`VITE_UPLOADS_URL`) — and it is all the frontend gets: no bucket, no\n\t * key. A backend's plain edge is to the bucket, as it presigns and writes.\n\t */\n\tget publicFace(): Declarable {\n\t\tconst surface = this.declare().find(\n\t\t\t(declaration) => declaration.id === this.surfaceId,\n\t\t);\n\n\t\treturn {\n\t\t\tid: this.surfaceId,\n\t\t\tdeclare: () => (surface ? [surface] : []),\n\t\t};\n\t}\n\n\t/**\n\t * Everything: the bucket, its credentials, and the address it is served\n\t * on.\n\t *\n\t * What a backend's plain edge already is. A frontend asks for it by name —\n\t * `.dependsOn([uploads.server])` — when its server half uploads or\n\t * presigns: a full-stack site's, never a bundle's. The bucket's connection\n\t * is never inlined into a bundle either way; only the served address is.\n\t */\n\tget server(): Declarable {\n\t\tconst originId = this.options.origin?.id ?? this.id;\n\t\tconst declarations = this.options.origin\n\t\t\t? this.options.origin.declare()\n\t\t\t: this.declare();\n\n\t\treturn { id: originId, declare: () => declarations };\n\t}\n\n\t/**\n\t * The bucket and the surface over it — or just the surface, when the bucket\n\t * was declared elsewhere.\n\t *\n\t * The surface names its origin through `of`, which is what makes the\n\t * reference check work: an origin resolving to nothing is a build failure,\n\t * the same guarantee `assertDerivations` already gives a reader and a schema\n\t * tenant.\n\t */\n\tdeclare(): Declaration[] {\n\t\tconst origin = this.options.origin;\n\n\t\tconst surface: Declaration = {\n\t\t\tkind: 'file-server',\n\t\t\tid: this.surfaceId,\n\t\t\tof: origin?.id ?? this.id,\n\t\t\t...(this.open.length ? { open: this.open } : {}),\n\t\t\t...(this.immutable.length ? { immutable: this.immutable } : {}),\n\t\t\t...(this.derivedDays !== undefined\n\t\t\t\t? { derivedDays: this.derivedDays }\n\t\t\t\t: {}),\n\t\t\t...(this.options.telemetry\n\t\t\t\t? { telemetry: this.options.telemetry.id }\n\t\t\t\t: {}),\n\t\t\tprovides: [this.keys.server],\n\t\t};\n\n\t\t// A vended bucket is declared here; a given one already declares itself,\n\t\t// and declaring it twice is the duplication the whole model removes.\n\t\tif (origin) return [surface];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'objects',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.origin],\n\t\t\t\t...(this.options.versioned ? { versioned: true } : {}),\n\t\t\t\t...(this.expire ? { expire: this.expire } : {}),\n\t\t\t},\n\t\t\tsurface,\n\t\t];\n\t}\n\n\t/**\n\t * The bucket's client, with the serving half added.\n\t *\n\t * Both keys are read here, which is also how the environment reaches a\n\t * handler: the sniffer records what this reads, so `.dependsOn([uploads])`\n\t * carries the bucket's connection and the server's address without either\n\t * being written down beside the handler.\n\t *\n\t * Without the connection — a site's or an app's plain edge, which is to\n\t * the public face — the client serves and does nothing else: its bucket\n\t * methods throw {@link FileServerReadOnly}.\n\t */\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<FileServerClient<TOpen>> {\n\t\tconst { origin, server } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigin: get(this.keys.origin).string().optional(),\n\t\t\t\tserver: get(this.keys.server).string(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tconst storage = origin\n\t\t\t? createStorageClient(origin)\n\t\t\t: readOnlyStorage(this.id, this.keys.origin);\n\t\tconst base = server.replace(/\\/+$/, '');\n\n\t\tconst serve = (key: string): string => {\n\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\n\t\t\treturn `${base}/${key.replace(/^\\/+/, '')}`;\n\t\t};\n\n\t\t// Delegating rather than copying: the bucket half is whatever the driver\n\t\t// produced, including anything it grows later, and only the serving half\n\t\t// is added on top.\n\t\treturn Object.assign(Object.create(storage) as StorageClient, {\n\t\t\turl: serve as (key: Served<TOpen>) => string,\n\t\t\topenUrl: serve,\n\t\t\tsignedUrl: (key: string, expiresIn?: number) =>\n\t\t\t\tstorage.getDownloadURL({ path: key } as never, expiresIn),\n\t\t\tprocessedUrl: (\n\t\t\t\tprocessor: Processor<string, any, any, any>,\n\t\t\t\tparams: Record<string, string | number>,\n\t\t\t\tkey: string,\n\t\t\t) => {\n\t\t\t\tif (processor.surfaceId !== this.surfaceId) {\n\t\t\t\t\tthrow new ProcessorNotOnThisServer(\n\t\t\t\t\t\tprocessor.pattern,\n\t\t\t\t\t\tprocessor.surfaceId,\n\t\t\t\t\t\tthis.surfaceId,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\t\t\t\treturn `${base}${fillPattern(processor.parsed, params, key)}`;\n\t\t\t},\n\t\t}) as FileServerClient<TOpen>;\n\t}\n\n\t/**\n\t * Whether an open pattern admits a key.\n\t *\n\t * The runtime half of {@link Served}, and stricter than it: here a single\n\t * star stops at a segment boundary and a double star does not, which is the\n\t * distinction a template-literal type cannot draw and the infrastructure\n\t * does.\n\t */\n\tprivate serves(key: string): boolean {\n\t\treturn this.open.some((pattern) => globToRegExp(pattern).test(key));\n\t}\n\n\t/**\n\t * Whether every key a pattern admits is open: the pattern itself, each of\n\t * its wildcards taken as a segment of its own, is a key an open pattern\n\t * serves — `brand/logos/*` under `brand/**`, but not `**` under `brand/**`.\n\t */\n\tprivate covers(pattern: string): boolean {\n\t\treturn this.serves(pattern.replace(/\\*\\*/g, 'x/x').replace(/\\*/g, 'x'));\n\t}\n}\n\n/**\n * One open pattern as an anchored expression.\n *\n * A double star crosses `/`; a single star does not. Both are consumed in one\n * left-to-right pass rather than by substitution, so a pattern cannot be\n * rewritten into a placeholder that a later pass mistakes for literal text.\n */\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = '';\n\n\tfor (let index = 0; index < pattern.length; index++) {\n\t\tconst character = pattern[index];\n\n\t\tif (character !== '*') {\n\t\t\tsource += character?.replace(/[.+^${}()|[\\]\\\\?]/, '\\\\$&') ?? '';\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (pattern[index + 1] === '*') {\n\t\t\tsource += '.*';\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tsource += '[^/]*';\n\t}\n\n\treturn new RegExp(`^${source}$`);\n}\n"],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C,MAAM,IAAI,yBACT,UAAU,SACV,UAAU,WACV,KAAK,SACN;IAED,IAAI,CAAC,KAAK,OAAO,GAAG,GAAG,MAAM,IAAI,QAAQ,KAAK,KAAK,IAAI;IACvD,OAAO,GAAG,OAAO,YAAY,UAAU,QAAQ,QAAQ,GAAG;GAC3D;EACD,CAAC;CACF;;;;;;;;;CAUA,OAAe,KAAsB;EACpC,OAAO,KAAK,KAAK,MAAM,YAAY,aAAa,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC;CACnE;;;;;;CAOA,OAAe,SAA0B;EACxC,OAAO,KAAK,OAAO,QAAQ,QAAQ,SAAS,KAAK,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC;CACvE;AACD;;;;;;;;AASA,SAAS,aAAa,SAAyB;CAC9C,IAAI,SAAS;CAEb,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS;EACpD,MAAM,YAAY,QAAQ;EAE1B,IAAI,cAAc,KAAK;GACtB,UAAU,WAAW,QAAQ,qBAAqB,MAAM,KAAK;GAC7D;EACD;EAEA,IAAI,QAAQ,QAAQ,OAAO,KAAK;GAC/B,UAAU;GACV;GACA;EACD;EAEA,UAAU;CACX;CAEA,OAAO,IAAI,OAAO,IAAI,OAAO,EAAE;AAChC"}
|
|
1
|
+
{"version":3,"file":"file-server.mjs","names":[],"sources":["../src/file-server.ts"],"sourcesContent":["/**\n * `FileServer` — a domain that serves a bucket's objects.\n *\n * `ObjectStorage` is the bucket: it writes, it presigns, and its URL is never\n * public. Serving those objects on a domain is a different thing, and it is a\n * construct of its own rather than a flag on the bucket — see\n * `docs/design/constructs-paradigm.md`, \"Why a separate construct, and what it\n * costs\", for the comparison that rules the other two shapes out.\n *\n * ```ts\n * export const uploads = new FileServer('Uploads', { open: ['brand/**'] });\n *\n * uploads.getUploadURL({ path, contentType }) // an S3 presign at the bucket\n * uploads.url('brand/logo.png') // open path — no signature\n * uploads.signedUrl('invoices/7.pdf') // one object, one recipient\n * ```\n *\n * **One construct, one client, both halves.** How a file lands in the bucket is\n * the same whether or not it is served, so splitting the upload half from the\n * serving half would be ceremony rather than safety. The client is a *superset*\n * of `StorageClient`, made literal in the type, so anything taking\n * `services.uploads` keeps compiling when the construct behind it grows a\n * serving half.\n *\n * **The id names the bucket, not the surface.** This is the detail that has to\n * be right before anything ships, because getting it backwards is destructive:\n * the migration people actually perform is serving a bucket they already have,\n * and naming the bucket after the construct makes that edit *add* a node rather\n * than rename the one holding the data.\n */\n\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDERIVED_PREFIX,\n\ttype Declaration,\n\tfileServerSurfaceId,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient, type StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type {\n\tConstruct,\n\tDeclarable,\n\tHasPublicFace,\n} from './construct-interface';\nimport { expiryDays, type ObjectExpiry } from './expire';\nimport type { Processor } from './processors/Processor';\nimport { ProcessorBuilder } from './processors/ProcessorBuilder';\nimport {\n\tfillPattern,\n\ttype PatternParams,\n\tparsePattern,\n} from './processors/pattern';\nimport type { Telemetry } from './telemetry';\n\n/**\n * A key an open pattern admits.\n *\n * The same template-literal trick `ConstructName` uses, so `open` is checked at\n * the call site rather than only at the edge:\n *\n * ```ts\n * files.url('brand/logo.png') // ok\n * files.url(`avatars/${id}.png`) // ok — a template literal still matches\n * files.url('invoices/7.pdf') // not assignable — never served unsigned\n * ```\n *\n * A single star and a double star resolve to the same type, stated rather than\n * discovered: a template literal cannot exclude `/`, so this is a prefix-and-\n * suffix guard while the *exact* pattern is enforced by the bucket policy, by\n * the cache behaviour, and by this construct's own runtime check. The type says\n * plausibly open; the infrastructure says definitely.\n */\nexport type Served<P extends string> = P extends `${infer Head}**`\n\t? `${Head}${string}`\n\t: P extends `${infer Head}*${infer Tail}`\n\t\t? `${Head}${string}${Tail}`\n\t\t: P;\n\n/** What consuming a file server hands you: a bucket client that also serves. */\nexport interface FileServerClient<TOpen extends string = never>\n\textends StorageClient {\n\t/**\n\t * The unsigned address of an open object.\n\t *\n\t * Compile-checked against the declared patterns, *and* checked again at\n\t * runtime — a JavaScript caller gets no compiler, and minting an unsigned\n\t * URL for a private object is a leak rather than a mistake.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\turl(key: Served<TOpen>): string;\n\n\t/**\n\t * The same thing for a key the compiler cannot see.\n\t *\n\t * A fully dynamic key does not type, which is correct and is also the case\n\t * people will hit — so the escape hatch is a named method rather than a\n\t * cast, and it runs the *same* runtime check rather than being a way around\n\t * it.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t */\n\topenUrl(key: string): string;\n\n\t/**\n\t * A signed address for one object and one recipient.\n\t *\n\t * Today this is an **S3 presign at the bucket**, which is what works\n\t * unchanged against MinIO locally and against S3 deployed. It is deliberately\n\t * not described as a CDN URL: CloudFront signing is a different mechanism,\n\t * with different keys, against a different host, and it needs key material\n\t * this construct does not yet declare.\n\t *\n\t * @param expiresIn - minutes, matching `getUploadURL`.\n\t */\n\tsignedUrl(key: string, expiresIn?: number): Promise<string>;\n\n\t/**\n\t * The address of a processor's derivative of an open object — the\n\t * thumbnail, not the original.\n\t *\n\t * @throws {NotOpen} when the key matches no declared pattern.\n\t * @throws {ProcessorNotOnThisServer} for another file server's processor.\n\t */\n\tprocessedUrl<\n\t\tTPattern extends string,\n\t\tTSchema extends StandardSchemaV1 | undefined,\n\t>(\n\t\tprocessor: Processor<TPattern, TSchema, any, any>,\n\t\tparams: ProcessorUrlParams<TPattern, TSchema>,\n\t\tkey: string,\n\t): string;\n}\n\n/**\n * What addresses a derivative: the values the processor's schema accepts —\n * its input, since these go into a path — or, without one, the raw strings.\n */\nexport type ProcessorUrlParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferInput<TSchema>\n\t: PatternParams<TPattern>;\n\n/** A processed URL was asked of a file server the processor is not on. */\nexport class ProcessorNotOnThisServer extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly server: string,\n\t\treadonly expected: string,\n\t) {\n\t\tsuper(\n\t\t\t`The processor at '${pattern}' belongs to '${server}', not '${expected}'. ` +\n\t\t\t\t`Ask its own file server for the URL: services.<its id>.processedUrl(…).`,\n\t\t);\n\t\tthis.name = 'ProcessorNotOnThisServer';\n\t}\n}\n\nexport interface FileServerOptions<TOpen extends string = never> {\n\t/**\n\t * Paths served without a signature. Everything else needs one.\n\t *\n\t * Private by default: a bucket where forgetting a flag publishes user\n\t * uploads is the wrong default, so this is an exception list, and listing it\n\t * in code means exactly one set of paths is unauthenticated and it is\n\t * reviewable in a diff.\n\t *\n\t * Uploading is deliberately *not* restricted to these. Writing to a path\n\t * that happens to be open is ordinary; the only asymmetry worth enforcing is\n\t * that you cannot hand out an unsigned URL for something the server would\n\t * refuse to serve unsigned.\n\t */\n\topen?: readonly TOpen[];\n\t/**\n\t * Open paths whose objects never change once written — keyed by a content\n\t * hash or a file id — so every client may keep them forever: the edge\n\t * sends `Cache-Control: public, max-age=31536000, immutable`, over\n\t * whatever the object was stored with.\n\t *\n\t * A subset of `open`, because a signed object is never served by the edge.\n\t * Only say it of paths whose keys are written once: a client holding an\n\t * immutable copy never asks again.\n\t */\n\timmutable?: readonly string[];\n\t/** Keep previous versions of an object. */\n\tversioned?: boolean;\n\t/**\n\t * Delete the objects under each prefix this many days after they were\n\t * written — `{ 'previews/': { days: 7 } }`. A setting of the bucket this\n\t * server vends, so it cannot be given with `origin`.\n\t */\n\texpire?: ObjectExpiry;\n\t/**\n\t * How long its processors' derivatives are kept in the bucket before it\n\t * deletes them — 30 days unless said. They are remade on the next request,\n\t * so this trades storage for the work of making one again.\n\t */\n\tderived?: { readonly days: number };\n\t/**\n\t * What its processor unit emits — the `Telemetry` construct, as a worker\n\t * takes it: each request is a span, and the deploy hands the unit the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * A bucket declared elsewhere, instead of one of this server's own.\n\t *\n\t * `new FileServer('Uploads')` declares both nodes; this fronts a bucket that\n\t * already exists, which is also how the two edges come back when you want\n\t * them separately — a handler depending on the bucket writes, a handler\n\t * depending on the server mints URLs.\n\t */\n\torigin?: Declarable;\n}\n\n/** An immutable pattern that no open pattern admits. */\nexport class ImmutableNotOpen extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly pattern: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' says '${pattern}' is immutable, and no open path admits it` +\n\t\t\t\t(open.length ? ` (open: ${open.join(', ')})` : ' — it opens none') +\n\t\t\t\t'. Only an open path is served by the edge, so only one can be ' +\n\t\t\t\t'cached there: add it to `open`, or narrow it to one that is.',\n\t\t);\n\t\tthis.name = 'ImmutableNotOpen';\n\t}\n}\n\n/**\n * A bucket setting given to a file server that fronts a bucket declared\n * elsewhere — where the bucket's own construct is the one that says it.\n */\nexport class BucketOptionOnOrigin extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\treadonly origin: string,\n\t\treadonly option: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' fronts '${origin}', which declares itself, so '${option}' ` +\n\t\t\t\t`belongs on the construct that declares '${origin}', not on the file server.`,\n\t\t);\n\t\tthis.name = 'BucketOptionOnOrigin';\n\t}\n}\n\n/**\n * A bucket method called on a file server's client that was handed only its\n * public address — a frontend's plain edge.\n */\nexport class FileServerReadOnly extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly method: string,\n\t\treadonly key: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' was reached through its public address only, so it serves ` +\n\t\t\t\t`and cannot ${method}(): ${key} is not in this process's environment. ` +\n\t\t\t\t`A site or app whose server half writes or presigns depends on ` +\n\t\t\t\t`'${id}'.server instead — .dependsOn([${id.charAt(0).toLowerCase()}${id.slice(1)}.server]).`,\n\t\t);\n\t\tthis.name = 'FileServerReadOnly';\n\t}\n}\n\n/** Names asked of any object, which a read-only client must not answer. */\nconst INTROSPECTED = new Set([\n\t'then',\n\t'toJSON',\n\t'constructor',\n\t'asymmetricMatch',\n\t'$$typeof',\n\t'nodeType',\n\t'inspect',\n]);\n\n/**\n * The bucket half of a client that has no bucket: every method throws\n * {@link FileServerReadOnly}, naming itself.\n *\n * A proxy rather than a list of stubs, so a method the storage client grows\n * later refuses the same way. What a runtime asks of any object is left\n * alone: `then`, because a client is resolved from a promise, and the names a\n * serialiser or a test's printer looks for.\n */\nfunction readOnlyStorage(id: string, key: string): StorageClient {\n\treturn new Proxy({} as StorageClient, {\n\t\tget(_target, property) {\n\t\t\tif (typeof property !== 'string' || INTROSPECTED.has(property)) return;\n\t\t\treturn () => {\n\t\t\t\tthrow new FileServerReadOnly(id, property, key);\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** A key was asked to be served unsigned, and no open pattern admits it. */\nexport class NotOpen extends Error {\n\tconstructor(\n\t\treadonly key: string,\n\t\treadonly open: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${key}' is not served without a signature. ` +\n\t\t\t\t(open.length\n\t\t\t\t\t? `Open paths: ${open.join(', ')}. Use signedUrl() for anything else.`\n\t\t\t\t\t: 'This file server declares no open paths, so every object needs signedUrl().'),\n\t\t);\n\t\tthis.name = 'NotOpen';\n\t}\n}\n\nexport class FileServer<\n\tTName extends string = string,\n\tTOpen extends string = never,\n> implements Construct<TName, FileServerClient<TOpen>>, HasPublicFace\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, FileServerClient<TOpen>>;\n\n\t/** The id of the surface node, as opposed to the bucket's. */\n\treadonly surfaceId: string;\n\n\tprivate readonly open: readonly string[];\n\tprivate readonly immutable: readonly string[];\n\n\t/** The vended bucket's expiry, checked once: prefix → days. */\n\tprivate readonly expire: Record<string, number> | undefined;\n\n\t/** Days its processors' derivatives are kept, when it says. */\n\tprivate readonly derivedDays: number | undefined;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the client reads cannot drift.\n\t */\n\tprivate readonly keys: { origin: string; server: string };\n\n\t/**\n\t * How a processor reaches the bucket: the bucket's own URL and nothing of\n\t * the serving half, which a processor never needs. A field, not a getter:\n\t * services are cached by object identity.\n\t */\n\tprivate readonly origin: Service<string, StorageClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: FileServerOptions<TOpen> = {},\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.open = options.open ?? [];\n\t\tthis.immutable = options.immutable ?? [];\n\t\tfor (const pattern of this.immutable) {\n\t\t\tif (!this.covers(pattern)) {\n\t\t\t\tthrow new ImmutableNotOpen(canonical, pattern, this.open);\n\t\t\t}\n\t\t}\n\n\t\t// The surface takes the suffix and the bucket keeps the plain id, which\n\t\t// is what makes \"serve a bucket I already have\" an edit that adds a node\n\t\t// instead of renaming the one holding the data.\n\t\tconst originId = options.origin?.id ?? canonical;\n\t\tif (options.origin && options.expire) {\n\t\t\tthrow new BucketOptionOnOrigin(canonical, originId, 'expire');\n\t\t}\n\t\tthis.expire = expiryDays(canonical, options.expire);\n\t\tthis.derivedDays = options.derived\n\t\t\t? expiryDays(canonical, { [DERIVED_PREFIX]: options.derived })?.[\n\t\t\t\t\tDERIVED_PREFIX\n\t\t\t\t]\n\t\t\t: undefined;\n\t\tthis.surfaceId = fileServerSurfaceId(canonical);\n\n\t\tthis.keys = {\n\t\t\torigin: providedKeyFor(originId, 'objects', 'connectionString'),\n\t\t\tserver: providedKeyFor(this.surfaceId, 'file-server', 'url'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\n\t\tconst originKey = this.keys.origin;\n\t\tthis.origin = {\n\t\t\tserviceName: `${serviceKey(originId)}ProcessorOrigin`,\n\t\t\tregister: ({ envParser }) => {\n\t\t\t\tconst { url } = envParser\n\t\t\t\t\t.create((get) => ({ url: get(originKey).string() }))\n\t\t\t\t\t.parse();\n\t\t\t\treturn createStorageClient(url);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * A processor behind one path pattern of this server: a handler that makes\n\t * a derivative of an open object on read.\n\t *\n\t * ```ts\n\t * export const thumbnails = assets\n\t * .process('/i/:width/*')\n\t * .params(z.object({ width: z.enum(['64', '256', '1024']) }))\n\t * .native(['sharp'])\n\t * .handle(async ({ params, object }) => ({\n\t * body: await sharp(await object.bytes()).resize(Number(params.width)).webp().toBuffer(),\n\t * contentType: 'image/webp',\n\t * cache: 'immutable',\n\t * }));\n\t * ```\n\t *\n\t * Open paths only: a key no `open` pattern admits is answered 404, as an\n\t * unsigned read of it would be.\n\t *\n\t * @throws {ProcessorPatternInvalid} for a pattern the edge cannot route.\n\t */\n\tprocess<TPattern extends `/${string}/*`>(\n\t\tpattern: TPattern,\n\t\toptions: { logger?: Logger } = {},\n\t): ProcessorBuilder<TPattern> {\n\t\treturn new ProcessorBuilder<TPattern>({\n\t\t\tparsed: parsePattern(pattern),\n\t\t\tsurfaceId: this.surfaceId,\n\t\t\tbucketId: this.options.origin?.id ?? this.id,\n\t\t\torigin: this.origin,\n\t\t\tserves: (key) => this.serves(key),\n\t\t\tlogger: (options.logger ?? DEFAULT_LOGGER) as Logger,\n\t\t\tnative: [],\n\t\t\tservices: [],\n\t\t\tconstructs: [],\n\t\t});\n\t}\n\n\t/**\n\t * The served surface: what a site's or a mobile app's plain\n\t * `.dependsOn([uploads])` points at.\n\t *\n\t * Its address is public, so the frontend is built with it\n\t * (`VITE_UPLOADS_URL`) — and it is all the frontend gets: no bucket, no\n\t * key. A backend's plain edge is to the bucket, as it presigns and writes.\n\t */\n\tget publicFace(): Declarable {\n\t\tconst surface = this.declare().find(\n\t\t\t(declaration) => declaration.id === this.surfaceId,\n\t\t);\n\n\t\treturn {\n\t\t\tid: this.surfaceId,\n\t\t\tdeclare: () => (surface ? [surface] : []),\n\t\t};\n\t}\n\n\t/**\n\t * Everything: the bucket, its credentials, and the address it is served\n\t * on.\n\t *\n\t * What a backend's plain edge already is. A frontend asks for it by name —\n\t * `.dependsOn([uploads.server])` — when its server half uploads or\n\t * presigns: a full-stack site's, never a bundle's. The bucket's connection\n\t * is never inlined into a bundle either way; only the served address is.\n\t */\n\tget server(): Declarable {\n\t\tconst originId = this.options.origin?.id ?? this.id;\n\t\tconst declarations = this.options.origin\n\t\t\t? this.options.origin.declare()\n\t\t\t: this.declare();\n\n\t\treturn { id: originId, declare: () => declarations };\n\t}\n\n\t/**\n\t * The bucket and the surface over it — or just the surface, when the bucket\n\t * was declared elsewhere.\n\t *\n\t * The surface names its origin through `of`, which is what makes the\n\t * reference check work: an origin resolving to nothing is a build failure,\n\t * the same guarantee `assertDerivations` already gives a reader and a schema\n\t * tenant.\n\t */\n\tdeclare(): Declaration[] {\n\t\tconst origin = this.options.origin;\n\n\t\tconst surface: Declaration = {\n\t\t\tkind: 'file-server',\n\t\t\tid: this.surfaceId,\n\t\t\tof: origin?.id ?? this.id,\n\t\t\t...(this.open.length ? { open: this.open } : {}),\n\t\t\t...(this.immutable.length ? { immutable: this.immutable } : {}),\n\t\t\t...(this.derivedDays !== undefined\n\t\t\t\t? { derivedDays: this.derivedDays }\n\t\t\t\t: {}),\n\t\t\t...(this.options.telemetry\n\t\t\t\t? { telemetry: this.options.telemetry.id }\n\t\t\t\t: {}),\n\t\t\tprovides: [this.keys.server],\n\t\t};\n\n\t\t// A vended bucket is declared here; a given one already declares itself,\n\t\t// and declaring it twice is the duplication the whole model removes.\n\t\tif (origin) return [surface];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'objects',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.origin],\n\t\t\t\t...(this.options.versioned ? { versioned: true } : {}),\n\t\t\t\t...(this.expire ? { expire: this.expire } : {}),\n\t\t\t},\n\t\t\tsurface,\n\t\t];\n\t}\n\n\t/**\n\t * The bucket's client, with the serving half added.\n\t *\n\t * Both keys are read here, which is also how the environment reaches a\n\t * handler: the sniffer records what this reads, so `.dependsOn([uploads])`\n\t * carries the bucket's connection and the server's address without either\n\t * being written down beside the handler.\n\t *\n\t * Without the connection — a site's or an app's plain edge, which is to\n\t * the public face — the client serves and does nothing else: its bucket\n\t * methods throw {@link FileServerReadOnly}.\n\t */\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<FileServerClient<TOpen>> {\n\t\tconst { origin, server } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigin: get(this.keys.origin).string().optional(),\n\t\t\t\tserver: get(this.keys.server).string(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tconst storage = origin\n\t\t\t? createStorageClient(origin)\n\t\t\t: readOnlyStorage(this.id, this.keys.origin);\n\t\tconst base = server.replace(/\\/+$/, '');\n\n\t\tconst serve = (key: string): string => {\n\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\n\t\t\treturn `${base}/${key.replace(/^\\/+/, '')}`;\n\t\t};\n\n\t\t// Delegating rather than copying: the bucket half is whatever the driver\n\t\t// produced, including anything it grows later, and only the serving half\n\t\t// is added on top.\n\t\treturn Object.assign(Object.create(storage) as StorageClient, {\n\t\t\turl: serve as (key: Served<TOpen>) => string,\n\t\t\topenUrl: serve,\n\t\t\tsignedUrl: (key: string, expiresIn?: number) =>\n\t\t\t\tstorage.getDownloadURL({ path: key } as never, expiresIn),\n\t\t\tprocessedUrl: (\n\t\t\t\tprocessor: Processor<string, any, any, any>,\n\t\t\t\tparams: Record<string, string | number>,\n\t\t\t\tkey: string,\n\t\t\t) => {\n\t\t\t\tif (processor.surfaceId !== this.surfaceId) {\n\t\t\t\t\tthrow new ProcessorNotOnThisServer(\n\t\t\t\t\t\tprocessor.pattern,\n\t\t\t\t\t\tprocessor.surfaceId,\n\t\t\t\t\t\tthis.surfaceId,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!this.serves(key)) throw new NotOpen(key, this.open);\n\t\t\t\treturn `${base}${fillPattern(processor.parsed, params, key)}`;\n\t\t\t},\n\t\t}) as FileServerClient<TOpen>;\n\t}\n\n\t/**\n\t * Whether an open pattern admits a key.\n\t *\n\t * The runtime half of {@link Served}, and stricter than it: here a single\n\t * star stops at a segment boundary and a double star does not, which is the\n\t * distinction a template-literal type cannot draw and the infrastructure\n\t * does.\n\t */\n\tprivate serves(key: string): boolean {\n\t\treturn this.open.some((pattern) => globToRegExp(pattern).test(key));\n\t}\n\n\t/**\n\t * Whether every key a pattern admits is open: the pattern itself, each of\n\t * its wildcards taken as a segment of its own, is a key an open pattern\n\t * serves — `brand/logos/*` under `brand/**`, but not `**` under `brand/**`.\n\t */\n\tprivate covers(pattern: string): boolean {\n\t\treturn this.serves(pattern.replace(/\\*\\*/g, 'x/x').replace(/\\*/g, 'x'));\n\t}\n}\n\n/**\n * One open pattern as an anchored expression.\n *\n * A double star crosses `/`; a single star does not. Both are consumed in one\n * left-to-right pass rather than by substitution, so a pattern cannot be\n * rewritten into a placeholder that a later pass mistakes for literal text.\n */\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = '';\n\n\tfor (let index = 0; index < pattern.length; index++) {\n\t\tconst character = pattern[index];\n\n\t\tif (character !== '*') {\n\t\t\tsource += character?.replace(/[.+^${}()|[\\]\\\\?]/, '\\\\$&') ?? '';\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (pattern[index + 1] === '*') {\n\t\t\tsource += '.*';\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tsource += '[^/]*';\n\t}\n\n\treturn new RegExp(`^${source}$`);\n}\n"],"mappings":";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,MAAM,IAAI,yBACT,UAAU,SACV,UAAU,WACV,KAAK,SACN;IAED,IAAI,CAAC,KAAK,OAAO,GAAG,GAAG,MAAM,IAAI,QAAQ,KAAK,KAAK,IAAI;IACvD,OAAO,GAAG,OAAO,YAAY,UAAU,QAAQ,QAAQ,GAAG;GAC3D;EACD,CAAC;CACF;;;;;;;;;CAUA,OAAe,KAAsB;EACpC,OAAO,KAAK,KAAK,MAAM,YAAY,aAAa,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC;CACnE;;;;;;CAOA,OAAe,SAA0B;EACxC,OAAO,KAAK,OAAO,QAAQ,QAAQ,SAAS,KAAK,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC;CACvE;AACD;;;;;;;;AASA,SAAS,aAAa,SAAyB;CAC9C,IAAI,SAAS;CAEb,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS;EACpD,MAAM,YAAY,QAAQ;EAE1B,IAAI,cAAc,KAAK;GACtB,UAAU,WAAW,QAAQ,qBAAqB,MAAM,KAAK;GAC7D;EACD;EAEA,IAAI,QAAQ,QAAQ,OAAO,KAAK;GAC/B,UAAU;GACV;GACA;EACD;EAEA,UAAU;CACX;CAEA,OAAO,IAAI,OAAO,IAAI,OAAO,EAAE;AAChC"}
|
package/dist/inbox.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_Topic = require("./Topic-
|
|
2
|
+
const require_Topic = require("./Topic-DLCZBNwK.cjs");
|
|
3
3
|
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
4
4
|
let _geekmidas_storage = require("@geekmidas/storage");
|
|
5
5
|
let _geekmidas_emailkit_inbound = require("@geekmidas/emailkit/inbound");
|
|
@@ -101,8 +101,8 @@ var Inbox = class {
|
|
|
101
101
|
...this.subdomains ? { subdomains: true } : {}
|
|
102
102
|
};
|
|
103
103
|
this.keys = {
|
|
104
|
-
url: (0, _geekmidas_manifest.
|
|
105
|
-
domain: (0, _geekmidas_manifest.
|
|
104
|
+
url: (0, _geekmidas_manifest.providedKeyFor)(canonical, "inbox", "url"),
|
|
105
|
+
domain: (0, _geekmidas_manifest.providedKeyFor)(canonical, "inbox", "domain")
|
|
106
106
|
};
|
|
107
107
|
this.topic = new require_Topic.Topic(`${canonical}Mail`, { events: { [_geekmidas_manifest.INBOX_EVENT]: RECEIPT_NOTIFICATION } });
|
|
108
108
|
this.service = {
|
package/dist/inbox.cjs.map
CHANGED
|
@@ -1 +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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,sBAAb,cAAyC,MAAM;CACzB;CAArB,YAAY,OAAwB;EACnC,MACC,cAAc,MAAM,+GAErB;EAJoB,KAAA,QAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,sBAAb,cAAyC,MAAM;CAEpC;CACA;CAFV,YACC,OACA,SACC;EACD,MACC,cAAc,MAAM,WAAW,QAAQ,6IAGxC;EAPS,KAAA,QAAA;EACA,KAAA,UAAA;EAOT,KAAK,OAAO;CACb;AACD;;;;;AAMA,IAAa,+BAAb,cAAkD,MAAM;CAE7C;CACA;CAFV,YACC,OACA,QACC;EACD,MACC,cAAc,MAAM,8CAA8C,OAAO,4EAE1E;EANS,KAAA,QAAA;EACA,KAAA,SAAA;EAMT,KAAK,OAAO;CACb;AACD;;AA4FA,MAAM,uBAA8D,EACnE,aAAa;CACZ,SAAS;CACT,QAAQ;CACR,WAAW,WAAW,EAAS,MAA6B;AAC7D,EACD;AAIA,IAAa,QAAb,MAEA;CACC;CACA;;CAEA;;CAGA;CACA;CACA;CACA;CAEA,YAAY,MAA4B,SAAuB;EAC9D,MAAM,aAAA,GAAYA,oBAAA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AChB,aAAa,CAAC,GAAG,QAAQ,UAAU;EACpC;EACA,SAAS;GACR,WAAW;GACX,YAAY,CAAC,GAAG,QAAQ,UAAU;GAClC,YAAY,OAAO,QAAQ,UAAU,GAAG;GACxC,aAAa,OAAO,QAAQ,UAAU,IAAI;GAC1C,cAAc,OAAO,QAAQ,UAAU,KAAK;GAC5C,aAAa,OAAO,QAAQ,UAAU,IAAI;GAC1C,cAAc,OAAO,QAAQ,UAAU,KAAK;GAC5C,QAAQ;IACP,MAAM;IACN,YAAY,QAAQ;IACpB,WAAW,QAAQ;GACpB;EACD;CACD;AACD;;;;;;;;;;;AAoCA,eAAsB,YACrB,SACA,SACoB;CACpB,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,SAAS,SAAS;EAC5B,MAAM,aAAa,QAAQ,WAAW,QAAQ,aAAA,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"}
|
|
1
|
+
{"version":3,"file":"inbox.cjs","names":["canonicalId","providedKeyFor","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\tprovidedKeyFor,\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: providedKeyFor(canonical, 'inbox', 'url'),\n\t\t\tdomain: providedKeyFor(canonical, 'inbox', '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,+GAErB;EAJoB,KAAA,QAAA;EAKpB,K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AAM,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.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Topic } from "./Topic-
|
|
2
|
-
import { INBOX_EVENT, canonicalId, inboxRecipient,
|
|
1
|
+
import { t as Topic } from "./Topic-BGoOeCT6.mjs";
|
|
2
|
+
import { INBOX_EVENT, canonicalId, inboxRecipient, providedKeyFor, serviceKey } from "@geekmidas/manifest";
|
|
3
3
|
import { createStorageClient } from "@geekmidas/storage";
|
|
4
4
|
import { parseEmail } from "@geekmidas/emailkit/inbound";
|
|
5
5
|
//#region src/inbox.ts
|
|
@@ -100,8 +100,8 @@ var Inbox = class {
|
|
|
100
100
|
...this.subdomains ? { subdomains: true } : {}
|
|
101
101
|
};
|
|
102
102
|
this.keys = {
|
|
103
|
-
url:
|
|
104
|
-
domain:
|
|
103
|
+
url: providedKeyFor(canonical, "inbox", "url"),
|
|
104
|
+
domain: providedKeyFor(canonical, "inbox", "domain")
|
|
105
105
|
};
|
|
106
106
|
this.topic = new Topic(`${canonical}Mail`, { events: { [INBOX_EVENT]: RECEIPT_NOTIFICATION } });
|
|
107
107
|
this.service = {
|
package/dist/inbox.mjs.map
CHANGED
|
@@ -1 +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,+GAErB;EAJoB,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KAAK,MAAM,EAAE;CACvB;CACA,OAAO;AACR;;AAGA,SAAgB,QAAQ,OAAgC;CACvD,OAAO,iBAAiB;AACzB"}
|
|
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\tprovidedKeyFor,\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: providedKeyFor(canonical, 'inbox', 'url'),\n\t\t\tdomain: providedKeyFor(canonical, 'inbox', '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,+GAErB;EAJoB,KAAA,QAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,sBAAb,cAAyC,MAAM;CAEpC;CACA;CAFV,YACC,OACA,SACC;EACD,MACC,cAAc,MAAM,WAAW,QAAQ,6IAGxC;EAPS,KAAA,QAAA;EACA,KAAA,UAAA;EAOT,KAAK,OAAO;CACb;AACD;;;;;AAMA,IAAa,+BAAb,cAAkD,MAAM;CAE7C;CACA;CAFV,YACC,OACA,QACC;EACD,MACC,cAAc,MAAM,8CAA8C,OAAO,4EAE1E;EANS,KAAA,QAAA;EACA,KAAA,SAAA;EAMT,KAAK,OAAO;CACb;AACD;;AA4FA,MAAM,uBAA8D,EACnE,aAAa;CACZ,SAAS;CACT,QAAQ;CACR,WAAW,WAAW,EAAS,MAA6B;AAC7D,EACD;AAIA,IAAa,QAAb,MAEA;CACC;CACA;;CAEA;;CAGA;CACA;CACA;CACA;CAEA,YAAY,MAA4B,SAAuB;EAC9D,MAAM,YAAY,YAAY,IAAc;EAC5C,IAAI,QAAQ,UAAU,WAAW,GAChC,MAAM,IAAI,oBAAoB,SAAS;EAExC,KAAK,MAAM,WAAW,QAAQ,WAC7B,IAAI,CAAC,0BAA0B,KAAK,OAAO,GAC1C,MAAM,IAAI,oBAAoB,WAAW,OAAO;EAIlD,KAAK,KAAK;EACV,KAAK,YAAY,QAAQ,UAAU,KAAK,MAAM,EAAE,YAAY,CAAC;EAC7D,KAAK,aAAa,QAAQ,eAAe;EACzC,KAA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