@dimah-s3/server 2.0.0-beta.1 → 2.0.0-beta.11

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.
@@ -1,7 +1,7 @@
1
1
  import { type MultipartAbortResponse } from "@dimah-s3/core";
2
2
  import type { S3ServerCallOptions } from "../../types/config.js";
3
3
  import type { ResolvedConfig } from "../../types/resolved.js";
4
- import { type MultipartTicketBody } from "./open-multipart";
4
+ import { type MultipartTicketBody } from "./open-multipart.js";
5
5
  /**
6
6
  * Aborts a multipart upload (`POST /presign/multipart/abort`,
7
7
  * `s3.api.multipart.abort`).
@@ -1,7 +1,7 @@
1
1
  import { type MultipartCompleteResponse } from "@dimah-s3/core";
2
2
  import type { S3ServerCallOptions } from "../../types/config.js";
3
3
  import type { ResolvedConfig } from "../../types/resolved.js";
4
- import { type MultipartTicketBody } from "./open-multipart";
4
+ import { type MultipartTicketBody } from "./open-multipart.js";
5
5
  /**
6
6
  * Completes a multipart upload (`POST /presign/multipart/complete`,
7
7
  * `s3.api.multipart.complete`).
@@ -1,7 +1,7 @@
1
1
  import type { MultipartListPartsResponse } from "@dimah-s3/core";
2
2
  import type { S3ServerCallOptions } from "../../types/config.js";
3
3
  import type { ResolvedConfig } from "../../types/resolved.js";
4
- import { type MultipartTicketBody } from "./open-multipart";
4
+ import { type MultipartTicketBody } from "./open-multipart.js";
5
5
  /**
6
6
  * Lists the uploaded parts (`POST /presign/multipart/parts`,
7
7
  * `s3.api.multipart.listParts`), so a client can resume an upload. It reads
@@ -1,5 +1,5 @@
1
1
  import type { DimahS3Config, DimahS3Logger } from "../types/config.js";
2
- import type { AppliedPlugins, DimahS3Plugin, PluginContextMap } from "./types";
2
+ import type { AppliedPlugins, DimahS3Plugin, PluginContextMap } from "./types.js";
3
3
  /**
4
4
  * Checks the plugins, builds the context map, collects the endpoints, and
5
5
  * runs each `init` in plugin order. Throws on a config error, so
@@ -1,4 +1,4 @@
1
- import type { DimahS3Plugin } from "./types";
1
+ import type { DimahS3Plugin } from "./types.js";
2
2
  /**
3
3
  * Identity helper that keeps the literal `id` and the `context` type, so
4
4
  * `s3.context[id]` and `s3[id]` are typed.
@@ -1,5 +1,5 @@
1
- export { applyPlugins } from "./apply-plugins";
2
- export { chainHooks } from "./chain-hooks";
3
- export { definePlugin } from "./define-plugin";
4
- export type { AppliedPlugins, DimahS3Plugin, DimahS3PluginHooks, PluginContextMap, PluginInitEnv, } from "./types";
1
+ export { applyPlugins } from "./apply-plugins.js";
2
+ export { chainHooks } from "./chain-hooks.js";
3
+ export { definePlugin } from "./define-plugin.js";
4
+ export type { AppliedPlugins, DimahS3Plugin, DimahS3PluginHooks, PluginContextMap, PluginInitEnv, } from "./types.js";
5
5
  //# sourceMappingURL=index.d.ts.map
package/dist/plugins.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- export { createS3Endpoint } from "./api/create-s3-endpoint";
2
- export type { S3Endpoint, S3EndpointMethod, S3EndpointOptions, } from "./api/create-s3-endpoint";
3
- export { createS3Middleware } from "./api/create-s3-middleware";
4
- export type { S3EndpointContext } from "./api/context";
5
- export { isFeatureOn } from "./config/feature-toggle";
6
- export { definePlugin } from "./plugin";
7
- export type { DimahS3Plugin, DimahS3PluginHooks, PluginContextMap, PluginInitEnv, } from "./plugin";
8
- export { isAwsNotFound } from "./helpers/aws-errors";
9
- export { deleteObjectIfMatch, type ConditionalDeleteInput, } from "./helpers/best-effort";
10
- export { readUploadMarker } from "./helpers/object-meta";
1
+ export { createS3Endpoint } from "./api/create-s3-endpoint.js";
2
+ export type { S3Endpoint, S3EndpointMethod, S3EndpointOptions, } from "./api/create-s3-endpoint.js";
3
+ export { createS3Middleware } from "./api/create-s3-middleware.js";
4
+ export type { S3EndpointContext } from "./api/context.js";
5
+ export { isFeatureOn } from "./config/feature-toggle.js";
6
+ export { definePlugin } from "./plugin/index.js";
7
+ export type { DimahS3Plugin, DimahS3PluginHooks, PluginContextMap, PluginInitEnv, } from "./plugin/index.js";
8
+ export { isAwsNotFound } from "./helpers/aws-errors.js";
9
+ export { assertFileConstraints, type FileConstraints, } from "./helpers/constraints.js";
10
+ export { deleteObjectIfMatch, type ConditionalDeleteInput, } from "./helpers/best-effort.js";
11
+ export { readObjectMetadata, readUploadMarker } from "./helpers/object-meta.js";
11
12
  //# sourceMappingURL=plugins.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,YAAY,EACV,UAAU,EACV,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,YAAY,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,GACd,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EACL,mBAAmB,EACnB,KAAK,sBAAsB,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,YAAY,EACV,UAAU,EACV,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,YAAY,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,GACd,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EACL,qBAAqB,EACrB,KAAK,eAAe,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,mBAAmB,EACnB,KAAK,sBAAsB,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/plugins.js CHANGED
@@ -1,4 +1,4 @@
1
- import { S3_API_ROUTES, s3Error, APIError, base64UrlDecode } from '@dimah-s3/core';
1
+ import { S3_API_ROUTES, s3Error, APIError, matchesFileTypes, describeFileType, base64UrlDecode } from '@dimah-s3/core';
2
2
  import { createMiddleware, createEndpoint } from 'better-call';
3
3
  import * as z from 'zod';
4
4
  import { statusCodes, APIError as APIError$1 } from 'better-call/error';
@@ -307,6 +307,23 @@ function isAwsPreconditionFailed(error) {
307
307
  function isAwsNotImplemented(error) {
308
308
  return matches(error, ["NotImplemented"], 501);
309
309
  }
310
+ function assertWithinMaxFileSize(maxFileSize, size) {
311
+ if (maxFileSize !== void 0 && size > maxFileSize) {
312
+ throw s3Error("FILE_TOO_LARGE", { size, maxFileSize });
313
+ }
314
+ }
315
+ function assertFileConstraints(constraints, file) {
316
+ const { fileTypes, maxFileSize } = constraints;
317
+ const name = file.name ?? "";
318
+ if (fileTypes?.length && !matchesFileTypes(name, file.type, fileTypes)) {
319
+ throw s3Error("FILE_TYPE_NOT_ALLOWED", {
320
+ type: describeFileType(name, file.type),
321
+ allowed: fileTypes.join(", ")
322
+ });
323
+ }
324
+ if (file.size === 0) throw s3Error("FILE_EMPTY");
325
+ assertWithinMaxFileSize(maxFileSize, file.size);
326
+ }
310
327
  async function deleteObjectIfMatch(client, input) {
311
328
  const target = { Bucket: input.bucket, Key: input.key };
312
329
  if (input.eTag === void 0) {
@@ -403,6 +420,6 @@ function readUploadMarker(metadata) {
403
420
  return readObjectMetadata(metadata).uploadToken;
404
421
  }
405
422
 
406
- export { createS3Endpoint, createS3Middleware, definePlugin, deleteObjectIfMatch, isAwsNotFound, isFeatureOn, readUploadMarker };
423
+ export { assertFileConstraints, createS3Endpoint, createS3Middleware, definePlugin, deleteObjectIfMatch, isAwsNotFound, isFeatureOn, readObjectMetadata, readUploadMarker };
407
424
  //# sourceMappingURL=plugins.js.map
408
425
  //# sourceMappingURL=plugins.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/helpers/error-boundary.ts","../src/helpers/hooks.ts","../src/helpers/request.ts","../src/api/router-context.ts","../src/api/create-s3-middleware.ts","../src/api/create-s3-endpoint.ts","../src/config/feature-toggle.ts","../src/plugin/define-plugin.ts","../src/helpers/aws-errors.ts","../src/helpers/best-effort.ts","../src/helpers/metadata-encoding.ts","../src/helpers/object-meta.ts"],"names":["BetterCallAPIError","s3Error"],"mappings":";;;;;;;AAMA,IAAM,aAAA,uBAAoB,GAAA,CAAI;AAAA,EAC5B,WAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,aAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGD,IAAM,eAAe,IAAI,GAAA;AAAA,EACvB,MAAA,CAAO,OAAA,CAAQ,WAAW,CAAA,CAAE,GAAA,CAAI,CAAC,CAAC,IAAA,EAAM,MAAM,CAAA,KAAM,CAAC,MAAA,EAAQ,IAAI,CAAC;AACpE,CAAA;AAOO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CA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KAAA,CAAM,MAAA,EAAQ,CAAC,CAAC,CAAA;AAC3E,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,GAAA,CAAI,GAAA,CAAI,OAAO,MAAM,CAAA;AACrB,IAAA,MAAA,IAAU,KAAA,CAAM,MAAA;AAAA,EAClB;AACA,EAAA,OAAO,GAAA;AACT;;;AC1FO,IAAM,kBAAA,GAAqB,cAAA;AAG3B,IAAM,iBAAA,GAAoB,oBAAA;AAwE1B,SAAS,mBACd,GAAA,EACsB;AACtB,EAAA,MAAM,WAAmC,EAAC;AAC1C,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,WAAA;AACJ,EAAA,KAAA,MAAW,CAAC,MAAM,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,GAAA,IAAO,EAAE,CAAA,EAAG;AACrD,IAAA,MAAM,GAAA,GAAM,KAAK,WAAA,EAAY;AAC7B,IAAA,MAAM,OAAA,GAAU,oBAAoB,KAAK,CAAA;AACzC,IAAA,IAAI,GAAA,KAAQ,oBAAoB,WAAA,GAAc,OAAA;AAAA,SAAA,IACrC,GAAA,KAAQ,iBAAA,EAAmB,WAAA,GAAc,OAAA,IAAW,MAAA;AAAA,SACxD,QAAA,CAAS,GAAG,CAAA,GAAI,OAAA;AAAA,EACvB;AACA,EAAA,OAAO,EAAE,QAAA,EAAU,WAAA,EAAa,WAAA,EAAY;AAC9C;AAQO,SAAS,iBACd,QAAA,EACoB;AACpB,EAAA,OAAO,kBAAA,CAAmB,QAAQ,CAAA,CAAE,WAAA;AACtC","file":"plugins.js","sourcesContent":["import { APIError, s3Error } from \"@dimah-s3/core\";\nimport { APIError as BetterCallAPIError, statusCodes } from \"better-call/error\";\nimport type { S3Operation } from \"@/types/hook-contexts\";\nimport type { ResolvedConfig } from \"@/types/resolved\";\n\n/** Socket error codes that mean the S3 endpoint could not be reached. */\nconst NETWORK_CODES = new Set([\n \"EAI_AGAIN\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EHOSTUNREACH\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n]);\n\n/** better-call status names by number (`403` → `\"FORBIDDEN\"`). */\nconst STATUS_NAMES = new Map<number, string>(\n Object.entries(statusCodes).map(([name, status]) => [status, name]),\n);\n\n/**\n * A server misconfiguration found while handling a call, such as a guard\n * that returned a boolean. The error boundary logs it and returns\n * `500 INTERNAL_ERROR`.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nexport type ErrorBoundaryEnv = Pick<ResolvedConfig, \"logger\" | \"onError\">;\n\n/**\n * Maps anything a call throws to the {@link APIError} the client receives.\n *\n * - An `APIError` passes through. A raw better-call error gets a code:\n * `UNSUPPORTED_MEDIA_TYPE`, `VALIDATION_ERROR` for a bad request, or the\n * code and message it carries.\n * - A socket error from S3 becomes `S3_NETWORK_ERROR`.\n * - Anything else becomes `INTERNAL_ERROR`.\n *\n * Failures that are not an `APIError` are logged and passed to `onError`,\n * unless the client already went away. Only a real better-call error passes\n * through: another library's error that is merely named `APIError` is an\n * unexpected failure like any other.\n */\nexport function toAPIError(\n error: unknown,\n env: ErrorBoundaryEnv,\n request: Request,\n operation?: S3Operation,\n): APIError {\n if (isHttpError(error)) return normalizeAPIError(error);\n\n const networkCode = socketErrorCode(error);\n const result = networkCode\n ? s3Error(\"S3_NETWORK_ERROR\", { code: networkCode }, { cause: error })\n : s3Error(\"INTERNAL_ERROR\", undefined, { cause: error });\n\n // An aborted request is a client disconnect, not a server failure.\n if (!request.signal.aborted) {\n report(error, result, env, { request, operation });\n }\n return result;\n}\n\nfunction report(\n error: unknown,\n result: APIError,\n env: ErrorBoundaryEnv,\n context: { request: Request; operation?: S3Operation },\n): void {\n env.logger.error?.(logMessage(error, result), error);\n const failed = (hookError: unknown) => {\n env.logger.error?.(\"onError threw\", hookError);\n };\n try {\n // An async onError must not become an unhandled rejection.\n void Promise.resolve(env.onError?.(error, context)).catch(failed);\n } catch (hookError) {\n failed(hookError);\n }\n}\n\n/**\n * A better-call `APIError` (core's extends it), or a copy from another\n * better-call instance: named `APIError`, with a numeric `statusCode` and\n * a string `body.code`.\n */\nfunction isHttpError(error: unknown): error is RawAPIError {\n if (error instanceof APIError || error instanceof BetterCallAPIError) {\n return true;\n }\n const candidate = error as Partial<RawAPIError> | null;\n return (\n candidate?.name === \"APIError\" &&\n typeof candidate.statusCode === \"number\" &&\n typeof candidate.body?.code === \"string\"\n );\n}\n\nfunction logMessage(error: unknown, result: APIError): string {\n if (error instanceof ConfigError) return `Config error: ${error.message}`;\n if (result.code === \"S3_NETWORK_ERROR\") return result.message;\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction socketErrorCode(error: unknown): string | undefined {\n const candidates = [error, (error as { cause?: unknown } | null)?.cause];\n for (const candidate of candidates) {\n const code = (candidate as { code?: unknown } | null)?.code;\n if (typeof code === \"string\" && NETWORK_CODES.has(code)) return code;\n }\n return undefined;\n}\n\n/** A better-call error from another copy of the library, or a duck-typed one. */\ntype RawAPIError = {\n name: string;\n message: string;\n body?: {\n code?: unknown;\n message?: unknown;\n params?: Record<string, string | number>;\n };\n statusCode?: unknown;\n headers?: HeadersInit;\n};\n\n/** Gives a raw better-call (or duck-typed) error a stable catalog-style code. */\nfunction normalizeAPIError(error: RawAPIError): APIError {\n if (error instanceof APIError) return error;\n\n const body = error.body ?? {};\n const status = typeof error.statusCode === \"number\" ? error.statusCode : 500;\n const message =\n typeof body.message === \"string\" ? body.message : error.message;\n const code =\n typeof body.code === \"string\"\n ? body.code\n : (STATUS_NAMES.get(status) ?? \"INTERNAL_ERROR\");\n\n switch (code) {\n case \"UNSUPPORTED_MEDIA_TYPE\":\n return s3Error(\"UNSUPPORTED_MEDIA_TYPE\", undefined, { cause: error });\n case \"BAD_REQUEST\":\n case \"VALIDATION_ERROR\":\n return s3Error(\"VALIDATION_ERROR\", { issue: message }, { cause: error });\n case \"INTERNAL_SERVER_ERROR\":\n return s3Error(\"INTERNAL_ERROR\", undefined, { cause: error });\n }\n\n return new APIError(\n status,\n {\n code,\n message,\n ...(body.params !== undefined ? { params: body.params } : {}),\n cause: error,\n },\n error.headers,\n );\n}\n","import { ConfigError } from \"@/helpers/error-boundary\";\nimport type { GuardContext } from \"@/types/hook-contexts\";\nimport type { DimahS3Locals, Guard, LifecycleHook } from \"@/types/locals\";\nimport type { HookList } from \"@/types/resolved\";\n\n/**\n * A new null-prototype `locals` object for one call, seeded with trusted\n * in-process values.\n */\nexport function createLocals(seed?: Partial<DimahS3Locals>): DimahS3Locals {\n const locals: DimahS3Locals = Object.create(null);\n if (seed) mergeLocals(locals, seed);\n return locals;\n}\n\n/**\n * Runs guards in order. Each `{ locals }` result is copied into\n * `context.locals`, so later hooks in the call see it. A throw rejects the\n * call. Any other return value is a {@link ConfigError} and never allows.\n */\nexport async function runGuards<C extends GuardContext>(\n guards: HookList<Guard<C>>,\n context: C,\n): Promise<void> {\n for (const { plugin, hook } of guards) {\n const result: unknown = await hook(context);\n if (result === undefined) continue;\n if (!isGuardResult(result)) {\n throw new ConfigError(\n `${guardName(plugin)} for \"${context.operation}\" returned ${describeValue(result)}. ` +\n \"Return nothing or { locals } to allow, and throw to reject.\",\n );\n }\n mergeLocals(context.locals, result.locals);\n }\n}\n\nexport type RunLifecycleOptions = {\n /**\n * Runs when a plugin hook throws, before the error is rethrown. Use it to\n * undo the operation, for example to delete an object whose bookkeeping\n * failed.\n */\n onPluginError?: (error: unknown) => Promise<void> | void;\n};\n\n/**\n * Runs lifecycle hooks in order: plugins first, then the user hook. The\n * first throw stops the rest and is rethrown. A user hook failure leaves the\n * operation's effects in place.\n */\nexport async function runLifecycle<C>(\n hooks: HookList<LifecycleHook<C>>,\n context: C,\n options: RunLifecycleOptions = {},\n): Promise<void> {\n for (const { plugin, hook } of hooks) {\n try {\n await hook(context);\n } catch (error) {\n if (plugin !== undefined) await options.onPluginError?.(error);\n throw error;\n }\n }\n}\n\nfunction mergeLocals(target: DimahS3Locals, source: object): void {\n for (const [key, value] of Object.entries(source)) {\n (target as Record<string, unknown>)[key] = value;\n }\n}\n\n/**\n * Exactly `{ locals: object }`: a plain object whose only key is `locals`,\n * holding an object that is not an array.\n */\nexport function isGuardResult(\n value: unknown,\n): value is { locals: Partial<DimahS3Locals> } {\n if (!isPlainObject(value)) return false;\n const keys = Object.keys(value);\n return (\n keys.length === 1 &&\n keys[0] === \"locals\" &&\n typeof value.locals === \"object\" &&\n value.locals !== null &&\n !Array.isArray(value.locals)\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction guardName(plugin: string | undefined): string {\n return plugin === undefined ? \"A guard\" : `The \"${plugin}\" plugin guard`;\n}\n\nfunction describeValue(value: unknown): string {\n switch (typeof value) {\n case \"string\":\n return \"a string\";\n case \"function\":\n return \"a function\";\n case \"object\":\n if (value === null) return \"null\";\n return Array.isArray(value)\n ? \"an array\"\n : \"an object other than { locals }\";\n default:\n return String(value);\n }\n}\n","import type { ResolvedConfig } from \"@/types/resolved\";\n\n/**\n * Request for an in-process call that did not pass one: a GET to the API\n * base URL (`baseURL`, else `http://localhost` plus `basePath`) carrying the\n * call headers and signal.\n */\nexport function syntheticRequest(\n config: Pick<ResolvedConfig, \"basePath\" | \"baseURL\">,\n init: { headers?: HeadersInit; signal?: AbortSignal } = {},\n): Request {\n return new Request(config.baseURL ?? `http://localhost${config.basePath}`, {\n headers: init.headers,\n signal: init.signal,\n });\n}\n","import type { DimahS3Config } from \"@/types/config\";\nimport type { ResolvedConfig } from \"@/types/resolved\";\n\n/**\n * Router context key of the resolved config. Plugin endpoints see only the\n * user `config`; the core endpoints and the error boundary read this one.\n * `Symbol.for` keeps one key across the entry points, which are bundled\n * separately.\n */\nconst RESOLVED_CONFIG: unique symbol = Symbol.for(\"dimah-s3.resolved-config\");\n\n/** What the dimahS3 router injects into every endpoint's `ctx.context`. */\nexport type RouterContext = {\n config: Readonly<DimahS3Config>;\n [RESOLVED_CONFIG]: ResolvedConfig;\n};\n\n/** The router context for the user config and its resolved form. */\nexport function createRouterContext(\n config: Readonly<DimahS3Config>,\n resolved: ResolvedConfig,\n): RouterContext {\n return { config, [RESOLVED_CONFIG]: resolved };\n}\n\n/**\n * The resolved config in an endpoint's `ctx.context`. Throws when the\n * endpoint is called outside a dimahS3 router.\n */\nexport function resolvedConfig(context: object): ResolvedConfig {\n const resolved = (context as Partial<RouterContext>)[RESOLVED_CONFIG];\n if (!resolved) {\n throw new Error(\n \"createS3Endpoint needs the dimahS3 router context. Mount the endpoint as a plugin endpoint and call it through the HTTP handler.\",\n );\n }\n return resolved;\n}\n","import { createMiddleware } from \"better-call\";\nimport { toAPIError } from \"@/helpers/error-boundary\";\nimport { createLocals, runGuards } from \"@/helpers/hooks\";\nimport { syntheticRequest } from \"@/helpers/request\";\nimport type { S3EndpointContext } from \"./context\";\nimport { resolvedConfig, type RouterContext } from \"./router-context\";\n\n/**\n * Adds `config`, `request` and `locals` to the endpoint context. With\n * `runGuards`, it also runs the instance guards (operation `\"plugin\"`) and\n * keeps the `locals` they return. It runs them once per call: when an\n * earlier middleware already did, it reuses that `locals`.\n */\nfunction contextMiddleware(options: { runGuards: boolean }) {\n return createMiddleware(async (ctx): Promise<S3EndpointContext> => {\n const resolved = resolvedConfig(ctx.context);\n const injected = ctx.context as RouterContext & Partial<S3EndpointContext>;\n const { config } = injected;\n const request =\n ctx.request ?? syntheticRequest(resolved, { headers: ctx.headers });\n if (injected.locals) return { config, request, locals: injected.locals };\n\n const locals = createLocals();\n if (options.runGuards) {\n try {\n await runGuards(resolved.guard, {\n request,\n operation: \"plugin\",\n locals,\n });\n } catch (error) {\n throw toAPIError(error, resolved, request, \"plugin\");\n }\n }\n return { config, request, locals };\n });\n}\n\n/**\n * Context middleware of every plugin endpoint. Plugin endpoints are guarded\n * here; core endpoints run their guards inside the operation.\n */\nexport const s3ContextMiddleware = contextMiddleware({ runGuards: true });\n\n/** Context middleware of the core endpoints, whose operations run the guards. */\nexport const coreContextMiddleware = contextMiddleware({ runGuards: false });\n\n/**\n * Creates a middleware for plugin endpoints. Its handler sees the same\n * `ctx.context` as the endpoint (`config`, `request`, `locals`), and the\n * instance guards have already run.\n *\n * ```ts\n * const requireUser = createS3Middleware(async (ctx) => {\n * if (!ctx.context.locals.userId) throw s3Error(\"UNAUTHORIZED\");\n * });\n *\n * createS3Endpoint(\"/audit/recent\", { method: \"GET\", use: [requireUser] }, handler);\n * ```\n */\nexport const createS3Middleware = createMiddleware.create({\n use: [s3ContextMiddleware],\n});\n","import { S3_API_ROUTES, s3Error } from \"@dimah-s3/core\";\nimport {\n createEndpoint,\n type Endpoint,\n type EndpointBaseOptions,\n type EndpointHandler,\n type StandardSchemaV1,\n} from \"better-call\";\nimport * as z from \"zod\";\nimport { toAPIError } from \"@/helpers/error-boundary\";\nimport type { S3Operation } from \"@/types/hook-contexts\";\nimport type { S3EndpointContext } from \"./context\";\nimport {\n coreContextMiddleware,\n s3ContextMiddleware,\n} from \"./create-s3-middleware\";\nimport { resolvedConfig } from \"./router-context\";\n\n/** HTTP methods a dimah-s3 endpoint can use. */\nexport type S3EndpointMethod = \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\";\n\n/**\n * Options of {@link createS3Endpoint}. `GET` and `DELETE` read the `query`.\n * `POST` and `PATCH` read a JSON `body`.\n */\nexport type S3EndpointOptions = Omit<EndpointBaseOptions, \"disableBody\"> &\n (\n | { method: \"GET\"; body?: never }\n | { method: \"DELETE\"; body?: never }\n | { method: \"POST\" | \"PATCH\"; body?: StandardSchemaV1 }\n );\n\nconst pluginEndpoint = createEndpoint.create({\n use: [s3ContextMiddleware],\n});\n\n// Core operations run the guards themselves, with their own operation name.\nconst coreEndpoint = createEndpoint.create({\n use: [coreContextMiddleware],\n});\n\n/** The endpoint {@link createS3Endpoint} returns for a path, options and result. */\nexport type S3Endpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n> = ReturnType<typeof pluginEndpoint<Path, Options, R>>;\n\n/** Body endpoints accept only JSON, so a cross-site form post is refused. */\nexport const BODY_MEDIA_TYPES: string[] = [\"application/json\"];\n\nconst CORE_PATHS: ReadonlySet<string> = new Set(Object.values(S3_API_ROUTES));\n\n/**\n * Creates an endpoint for a plugin's `endpoints`. The path is under\n * `basePath`, such as `/audit/recent`.\n *\n * - `GET` and `DELETE` read the `query`. `POST` and `PATCH` read a JSON\n * `body`; any other content type returns `415 UNSUPPORTED_MEDIA_TYPE`.\n * - The instance guards run first (operation `\"plugin\"`), and the `locals`\n * they return are on `ctx.context.locals`, next to `config` and `request`.\n * - A schema failure returns `400 VALIDATION_ERROR`. An `APIError` passes\n * through; anything else is logged, passed to `onError`, and returns\n * `500 INTERNAL_ERROR`.\n *\n * ```ts\n * endpoints: {\n * recent: createS3Endpoint(\n * \"/audit/recent\",\n * { method: \"GET\", query: z.object({ limit: z.coerce.number().optional() }) },\n * async (ctx) => ({ events: await audit.recent(ctx.context.locals, ctx.query) }),\n * ),\n * }\n * ```\n */\nexport function createS3Endpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n>(\n path: Path,\n options: Options,\n handler: EndpointHandler<Path, Options, R, S3EndpointContext>,\n): S3Endpoint<Path, Options, R> {\n if (CORE_PATHS.has(path)) {\n throw new Error(\n `createS3Endpoint(\"${path}\"): the path belongs to a core endpoint.`,\n );\n }\n return buildEndpoint(pluginEndpoint, path, options, handler, \"plugin\");\n}\n\n/**\n * A core endpoint. Internal: its operation runs the guards and names the\n * call, so the context middleware only adds `config`, `request` and an\n * empty `locals`.\n */\nexport function createCoreEndpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n>(\n path: Path,\n options: Options,\n handler: EndpointHandler<Path, Options, R, S3EndpointContext>,\n): S3Endpoint<Path, Options, R> {\n return buildEndpoint(coreEndpoint, path, options, handler);\n}\n\nfunction buildEndpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n>(\n create: typeof pluginEndpoint,\n path: Path,\n options: Options,\n handler: EndpointHandler<Path, Options, R, S3EndpointContext>,\n operation?: S3Operation,\n): S3Endpoint<Path, Options, R> {\n const endpoint = create(path, endpointOptions(path, options), async (ctx) => {\n try {\n return await handler(ctx);\n } catch (error) {\n const apiError = toAPIError(\n error,\n resolvedConfig(ctx.context),\n ctx.context.request,\n operation,\n );\n // better-call answers a thrown error with the endpoint's response\n // headers and drops the error's own, such as `Content-Range` on a 416.\n new Headers(apiError.headers).forEach((value, name) => {\n ctx.setHeader(name, value);\n });\n throw apiError;\n }\n });\n return withCallContext(endpoint);\n}\n\nfunction endpointOptions<Options extends S3EndpointOptions>(\n path: string,\n options: Options,\n): Options {\n const { method } = options;\n if (![\"GET\", \"POST\", \"PATCH\", \"DELETE\"].includes(method)) {\n throw new Error(\n `createS3Endpoint(\"${path}\"): method must be GET, POST, PATCH or DELETE.`,\n );\n }\n const readsBody = method === \"POST\" || method === \"PATCH\";\n if (!readsBody && options.body !== undefined) {\n throw new Error(\n `createS3Endpoint(\"${path}\"): ${method} reads the query, so it cannot have a body schema.`,\n );\n }\n return {\n ...options,\n ...(options.body !== undefined ? { body: compileIfZod(options.body) } : {}),\n ...(options.query !== undefined\n ? { query: compileIfZod(options.query) }\n : {}),\n metadata: readsBody\n ? { ...options.metadata, allowedMediaTypes: BODY_MEDIA_TYPES }\n : options.metadata,\n // A DELETE is never parsed for a body, so a form post cannot reach it.\n ...(method === \"DELETE\" ? { disableBody: true } : {}),\n // The router reads the body before the hooks run. Reading a clone keeps\n // the original request readable for guards.\n ...(readsBody && options.cloneRequest === undefined\n ? { cloneRequest: true }\n : {}),\n onValidationError:\n options.onValidationError ??\n (({ message }) => {\n throw s3Error(\"VALIDATION_ERROR\", { issue: message });\n }),\n };\n}\n\n/**\n * Compiles a Zod schema with `z.compile()`, so valid input skips the\n * interpreter. A schema it cannot compile, or a runtime without\n * `new Function`, keeps the regular parser.\n */\nfunction compileIfZod<T extends StandardSchemaV1>(schema: T): T {\n if (\"_zod\" in schema) {\n return z.compile(schema as unknown as z.ZodType) as unknown as T;\n }\n return schema;\n}\n\n/**\n * Gives every call its own copy of the router context. better-call merges\n * middleware results into `ctx.context`, and the router passes the same\n * object to every request, so without the copy concurrent calls would see\n * each other's `request` and `locals`.\n */\nfunction withCallContext<E extends Endpoint>(endpoint: E): E {\n const call = (input: { context?: object } = {}) =>\n endpoint({ ...input, context: { ...input.context } });\n return Object.assign(call, {\n path: endpoint.path,\n options: endpoint.options,\n }) as E;\n}\n","import type { FeatureToggle } from \"@/types/config\";\n\n/** Whether a resolved feature is on. Narrows to the enabled shape. */\nexport function isEnabled<T extends { enabled: boolean }>(\n feature: T,\n): feature is T & { enabled: true } {\n return feature.enabled;\n}\n\n/**\n * Whether a feature toggle is on: `true` or an options object is on, and\n * `false` is off. `undefined` uses `defaultOn`. A resolved `{ enabled }`\n * object uses its flag.\n */\nexport function isFeatureOn<T extends object>(\n value: FeatureToggle<T> | { enabled: boolean } | undefined,\n defaultOn = false,\n): boolean {\n if (value === undefined) return defaultOn;\n if (typeof value === \"boolean\") return value;\n if (\"enabled\" in value && typeof value.enabled === \"boolean\") {\n return value.enabled;\n }\n return true;\n}\n","import type { DimahS3Plugin } from \"./types\";\n\n/**\n * Identity helper that keeps the literal `id` and the `context` type, so\n * `s3.context[id]` and `s3[id]` are typed.\n *\n * ```ts\n * export const audit = definePlugin({\n * id: \"audit\",\n * hooks: { upload: { onConfirmed: ({ key }) => log(key) } },\n * context: { log },\n * });\n * ```\n */\nexport function definePlugin<\n Id extends string,\n TContext extends Record<string, unknown> = Record<string, unknown>,\n>(plugin: DimahS3Plugin<Id, TContext>): DimahS3Plugin<Id, TContext> {\n return plugin;\n}\n","import { s3Error } from \"@dimah-s3/core\";\n\n/*\n * Reads a failed S3 call. The AWS SDK names its errors (`NoSuchKey`), some\n * S3-compatible providers only set `Code`, and every response carries the\n * HTTP status in `$metadata`, so each check accepts any of the three.\n */\n\ntype AwsErrorFields = {\n name?: unknown;\n Code?: unknown;\n $metadata?: { httpStatusCode?: unknown };\n};\n\nfunction fields(error: unknown): AwsErrorFields {\n return typeof error === \"object\" && error !== null\n ? (error as AwsErrorFields)\n : {};\n}\n\n/** The error `name` or `Code` is one of `names`. */\nfunction named(error: unknown, names: readonly string[]): boolean {\n const { name, Code } = fields(error);\n return (\n (typeof name === \"string\" && names.includes(name)) ||\n (typeof Code === \"string\" && names.includes(Code))\n );\n}\n\nfunction matches(\n error: unknown,\n names: readonly string[],\n status: number,\n): boolean {\n return named(error, names) || awsStatus(error) === status;\n}\n\n/** The HTTP status S3 answered a failed call with, when there was one. */\nexport function awsStatus(error: unknown): number | undefined {\n const status = fields(error).$metadata?.httpStatusCode;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * The object, or the multipart upload, does not exist. A missing bucket is\n * a 404 too, but it is a config error, so it does not count.\n */\nexport function isAwsNotFound(error: unknown): boolean {\n if (named(error, [\"NoSuchBucket\"])) return false;\n return matches(error, [\"NoSuchKey\", \"NotFound\", \"NoSuchUpload\"], 404);\n}\n\n/** An `If-Match` or `If-Unmodified-Since` condition failed. */\nexport function isAwsPreconditionFailed(error: unknown): boolean {\n return matches(error, [\"PreconditionFailed\"], 412);\n}\n\n/** The provider does not implement the request, such as a conditional delete. */\nexport function isAwsNotImplemented(error: unknown): boolean {\n return matches(error, [\"NotImplemented\"], 501);\n}\n\n/** The requested byte range is outside the object. */\nexport function isAwsRangeNotSatisfiable(error: unknown): boolean {\n return matches(error, [\"InvalidRange\"], 416);\n}\n\n/** Runs an S3 call and turns a not-found error into `OBJECT_NOT_FOUND`. */\nexport async function sendOrObjectNotFound<T>(\n send: () => Promise<T>,\n): Promise<T> {\n try {\n return await send();\n } catch (error) {\n if (isAwsNotFound(error)) {\n throw s3Error(\"OBJECT_NOT_FOUND\", undefined, { cause: error });\n }\n throw error;\n }\n}\n","import {\n AbortMultipartUploadCommand,\n DeleteObjectCommand,\n type S3Client,\n} from \"@aws-sdk/client-s3\";\nimport { isAwsNotImplemented, isAwsPreconditionFailed } from \"./aws-errors\";\n\n/** The object to delete, and the ETag it must still have. */\nexport type ConditionalDeleteInput = {\n bucket: string;\n key: string;\n /** ETag from the HeadObject that identified the object. */\n eTag?: string;\n};\n\n/**\n * DeleteObject that keeps a newer object at the same key. With an `eTag`,\n * the delete is conditional (`If-Match`): when the key now holds another\n * object (`412`), nothing is deleted and it returns `false`. A provider\n * without conditional DeleteObject (`501`) gets a plain delete. Any other\n * failure is thrown.\n */\nexport async function deleteObjectIfMatch(\n client: S3Client,\n input: ConditionalDeleteInput,\n): Promise<boolean> {\n const target = { Bucket: input.bucket, Key: input.key };\n if (input.eTag === undefined) {\n await client.send(new DeleteObjectCommand(target));\n return true;\n }\n try {\n await client.send(\n new DeleteObjectCommand({ ...target, IfMatch: input.eTag }),\n );\n } catch (error) {\n if (isAwsPreconditionFailed(error)) return false;\n if (!isAwsNotImplemented(error)) throw error;\n await client.send(new DeleteObjectCommand(target));\n }\n return true;\n}\n\n/**\n * {@link deleteObjectIfMatch} after a failed check, ignoring every failure:\n * the caller is already returning an error, and an object left behind is\n * caught by purge or a bucket lifecycle rule.\n */\nexport async function deleteObjectBestEffort(\n client: S3Client,\n bucket: string,\n key: string,\n eTag?: string,\n): Promise<void> {\n try {\n await deleteObjectIfMatch(client, { bucket, key, eTag });\n } catch {\n // Best-effort cleanup.\n }\n}\n\n/** Best-effort AbortMultipartUpload, when init fails after CreateMultipartUpload. */\nexport async function abortMultipartBestEffort(\n client: S3Client,\n bucket: string,\n key: string,\n uploadId: string,\n): Promise<void> {\n try {\n await client.send(\n new AbortMultipartUploadCommand({\n Bucket: bucket,\n Key: key,\n UploadId: uploadId,\n }),\n );\n } catch {\n // Best-effort cleanup.\n }\n}\n","import { base64UrlDecode, base64UrlEncode } from \"@dimah-s3/core\";\n\n/** Values S3 and HTTP clients carry unchanged in an `x-amz-meta-*` header. */\nconst PLAIN_VALUE = /^(?:[\\x21-\\x7e](?:[\\x20-\\x7e]*[\\x21-\\x7e])?)?$/;\n\n/** A value that reads as an RFC 2047 encoded word, so it must be encoded to survive a round trip. */\nconst ENCODED_WORD_LIKE = /^=\\?.*\\?=$/s;\n\n/** One RFC 2047 encoded word: `=?charset?B|Q?text?=`, with an optional RFC 2231 language. */\nconst ENCODED_WORD = /^=\\?([^?*]+)(?:\\*[^?]*)?\\?([bq])\\?([^?]*)\\?=$/i;\n\nconst UTF8_CHARSETS = new Set([\"utf-8\", \"utf8\", \"us-ascii\"]);\n\n/**\n * Makes a metadata value safe to send as an `x-amz-meta-*` header. Printable\n * ASCII without surrounding spaces is kept as is. Anything else becomes one\n * RFC 2047 encoded word (`=?UTF-8?B?…?=`), the form S3 itself returns for\n * non-ASCII metadata.\n */\nexport function encodeMetadataValue(value: string): string {\n if (PLAIN_VALUE.test(value) && !ENCODED_WORD_LIKE.test(value)) return value;\n return `=?UTF-8?B?${toBase64(new TextEncoder().encode(value))}?=`;\n}\n\n/**\n * Reverses {@link encodeMetadataValue}, and decodes any RFC 2047 value S3\n * returns: one or more `B` or `Q` encoded words in UTF-8 or US-ASCII,\n * separated by whitespace. A value that is not a well-formed encoded word\n * is returned unchanged.\n */\nexport function decodeMetadataValue(value: string): string {\n const words = value.trim().split(/\\s+/);\n const chunks: Uint8Array[] = [];\n for (const word of words) {\n const match = ENCODED_WORD.exec(word);\n if (!match || !UTF8_CHARSETS.has(match[1].toLowerCase())) return value;\n const bytes =\n match[2].toLowerCase() === \"b\"\n ? fromBase64(match[3])\n : fromQuotedPrintable(match[3]);\n if (!bytes) return value;\n chunks.push(bytes);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(concat(chunks));\n } catch {\n return value;\n }\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n const url = base64UrlEncode(bytes).replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n return url.padEnd(Math.ceil(url.length / 4) * 4, \"=\");\n}\n\nfunction fromBase64(text: string): Uint8Array | undefined {\n if (!/^[a-z0-9+/]*={0,2}$/i.test(text) || text.length % 4 !== 0) {\n return undefined;\n }\n try {\n return base64UrlDecode(\n text.replace(/=+$/, \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\"),\n );\n } catch {\n return undefined;\n }\n}\n\n/** RFC 2047 `Q` encoding: `_` is a space and `=XX` is a hex byte. */\nfunction fromQuotedPrintable(text: string): Uint8Array | undefined {\n const bytes: number[] = [];\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"_\") {\n bytes.push(0x20);\n } else if (char === \"=\") {\n const hex = text.slice(i + 1, i + 3);\n if (!/^[0-9a-f]{2}$/i.test(hex)) return undefined;\n bytes.push(Number.parseInt(hex, 16));\n i += 2;\n } else {\n const code = char.charCodeAt(0);\n if (code < 0x21 || code > 0x7e) return undefined;\n bytes.push(code);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction concat(chunks: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n","import { ConfigError } from \"@/helpers/error-boundary\";\nimport {\n decodeMetadataValue,\n encodeMetadataValue,\n} from \"@/helpers/metadata-encoding\";\n\n/** S3 user-metadata key for the upload marker. Its value is the upload token. */\nexport const UPLOAD_MARKER_META = \"dimah-upload\";\n\n/** S3 user-metadata key for `upload.object().previousKey`. */\nexport const PREVIOUS_KEY_META = \"dimah-previous-key\";\n\n/** S3 limit on user metadata: UTF-8 bytes of every key and value, summed. */\nexport const MAX_METADATA_BYTES = 2048;\n\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set([\n UPLOAD_MARKER_META,\n PREVIOUS_KEY_META,\n]);\n\n/** An HTTP header-name token, so `x-amz-meta-{key}` is a valid header. */\nconst METADATA_KEY = /^[!#$%&'*+.^`|~\\w-]+$/;\n\nexport type ObjectMetadataInput = {\n /** User metadata from `upload.object()` or `s3.put`. */\n metadata?: Record<string, string>;\n uploadToken: string;\n /** Key to delete after a successful confirm. */\n previousKey?: string;\n};\n\n/**\n * S3 user metadata for a new object: the user metadata plus the upload\n * marker and the previous key. Keys are lowercased, as S3 stores them, and\n * values are RFC 2047-encoded where needed.\n *\n * Throws a {@link ConfigError} when a key is invalid, repeats, or uses an\n * internal name, or when the total exceeds {@link MAX_METADATA_BYTES}.\n */\nexport function buildObjectMetadata(\n input: ObjectMetadataInput,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [name, value] of Object.entries(input.metadata ?? {})) {\n const key = name.toLowerCase();\n if (!METADATA_KEY.test(key)) {\n throw new ConfigError(`S3 metadata key \"${name}\" is not a valid name.`);\n }\n if (INTERNAL_KEYS.has(key)) {\n throw new ConfigError(`S3 metadata key \"${name}\" is reserved.`);\n }\n if (Object.hasOwn(result, key)) {\n throw new ConfigError(`S3 metadata key \"${name}\" is set twice.`);\n }\n result[key] = encodeMetadataValue(value);\n }\n const userBytes = metadataByteSize(result);\n\n result[UPLOAD_MARKER_META] = input.uploadToken;\n if (input.previousKey !== undefined) {\n result[PREVIOUS_KEY_META] = encodeMetadataValue(input.previousKey);\n }\n const totalBytes = metadataByteSize(result);\n if (totalBytes > MAX_METADATA_BYTES) {\n throw new ConfigError(\n `S3 metadata is ${totalBytes} bytes (${userBytes} from upload.object() ` +\n `and ${totalBytes - userBytes} added by dimah-s3); S3 allows ` +\n `${MAX_METADATA_BYTES}. Keys and values count once encoded.`,\n );\n }\n return result;\n}\n\n/** User metadata as HeadObject returns it, split from the internal keys. */\nexport type StoredObjectMetadata = {\n /** Decoded user metadata, without internal keys. */\n metadata: Record<string, string>;\n uploadToken?: string;\n previousKey?: string;\n};\n\n/** Splits and decodes HeadObject `Metadata`. */\nexport function readObjectMetadata(\n raw: Record<string, string> | undefined,\n): StoredObjectMetadata {\n const metadata: Record<string, string> = {};\n let uploadToken: string | undefined;\n let previousKey: string | undefined;\n for (const [name, value] of Object.entries(raw ?? {})) {\n const key = name.toLowerCase();\n const decoded = decodeMetadataValue(value);\n if (key === UPLOAD_MARKER_META) uploadToken = decoded;\n else if (key === PREVIOUS_KEY_META) previousKey = decoded || undefined;\n else metadata[key] = decoded;\n }\n return { metadata, uploadToken, previousKey };\n}\n\n/**\n * The upload token an object was written with: its upload marker, read\n * from HeadObject `Metadata`. `undefined` for an object dimah-s3 did not\n * write. A plugin that cleans up an upload deletes the object only while\n * this still equals the token of the upload it tracks.\n */\nexport function readUploadMarker(\n metadata: Record<string, string> | undefined,\n): string | undefined {\n return readObjectMetadata(metadata).uploadToken;\n}\n\nfunction metadataByteSize(metadata: Record<string, string>): number {\n const encoder = new TextEncoder();\n let bytes = 0;\n for (const [key, value] of Object.entries(metadata)) {\n bytes += encoder.encode(key).length + encoder.encode(value).length;\n }\n return bytes;\n}\n"]}
1
+ {"version":3,"sources":["../src/helpers/error-boundary.ts","../src/helpers/hooks.ts","../src/helpers/request.ts","../src/api/router-context.ts","../src/api/create-s3-middleware.ts","../src/api/create-s3-endpoint.ts","../src/config/feature-toggle.ts","../src/plugin/define-plugin.ts","../src/helpers/aws-errors.ts","../src/helpers/constraints.ts","../src/helpers/best-effort.ts","../src/helpers/metadata-encoding.ts","../src/helpers/object-meta.ts"],"names":["BetterCallAPIError","s3Error"],"mappings":";;;;;;;AAMA,IAAM,aAAA,uBAAoB,GAAA,CAAI;AAAA,EAC5B,WAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,aAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGD,IAAM,eAAe,IAAI,GAAA;AAAA,EACvB,MAAA,CAAO,OAAA,CAAQ,WAAW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AAA,MAAA,IAAU,KAAA,CAAM,MAAA;AAAA,EAClB;AACA,EAAA,OAAO,GAAA;AACT;;;AC1FO,IAAM,kBAAA,GAAqB,cAAA;AAG3B,IAAM,iBAAA,GAAoB,oBAAA;AAwE1B,SAAS,mBACd,GAAA,EACsB;AACtB,EAAA,MAAM,WAAmC,EAAC;AAC1C,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,WAAA;AACJ,EAAA,KAAA,MAAW,CAAC,MAAM,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,GAAA,IAAO,EAAE,CAAA,EAAG;AACrD,IAAA,MAAM,GAAA,GAAM,KAAK,WAAA,EAAY;AAC7B,IAAA,MAAM,OAAA,GAAU,oBAAoB,KAAK,CAAA;AACzC,IAAA,IAAI,GAAA,KAAQ,oBAAoB,WAAA,GAAc,OAAA;AAAA,SAAA,IACrC,GAAA,KAAQ,iBAAA,EAAmB,WAAA,GAAc,OAAA,IAAW,MAAA;AAAA,SACxD,QAAA,CAAS,GAAG,CAAA,GAAI,OAAA;AAAA,EACvB;AACA,EAAA,OAAO,EAAE,QAAA,EAAU,WAAA,EAAa,WAAA,EAAY;AAC9C;AAQO,SAAS,iBACd,QAAA,EACoB;AACpB,EAAA,OAAO,kBAAA,CAAmB,QAAQ,CAAA,CAAE,WAAA;AACtC","file":"plugins.js","sourcesContent":["import { APIError, s3Error } from \"@dimah-s3/core\";\nimport { APIError as BetterCallAPIError, statusCodes } from \"better-call/error\";\nimport type { S3Operation } from \"@/types/hook-contexts\";\nimport type { ResolvedConfig } from \"@/types/resolved\";\n\n/** Socket error codes that mean the S3 endpoint could not be reached. */\nconst NETWORK_CODES = new Set([\n \"EAI_AGAIN\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EHOSTUNREACH\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n]);\n\n/** better-call status names by number (`403` → `\"FORBIDDEN\"`). */\nconst STATUS_NAMES = new Map<number, string>(\n Object.entries(statusCodes).map(([name, status]) => [status, name]),\n);\n\n/**\n * A server misconfiguration found while handling a call, such as a guard\n * that returned a boolean. The error boundary logs it and returns\n * `500 INTERNAL_ERROR`.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nexport type ErrorBoundaryEnv = Pick<ResolvedConfig, \"logger\" | \"onError\">;\n\n/**\n * Maps anything a call throws to the {@link APIError} the client receives.\n *\n * - An `APIError` passes through. A raw better-call error gets a code:\n * `UNSUPPORTED_MEDIA_TYPE`, `VALIDATION_ERROR` for a bad request, or the\n * code and message it carries.\n * - A socket error from S3 becomes `S3_NETWORK_ERROR`.\n * - Anything else becomes `INTERNAL_ERROR`.\n *\n * Failures that are not an `APIError` are logged and passed to `onError`,\n * unless the client already went away. Only a real better-call error passes\n * through: another library's error that is merely named `APIError` is an\n * unexpected failure like any other.\n */\nexport function toAPIError(\n error: unknown,\n env: ErrorBoundaryEnv,\n request: Request,\n operation?: S3Operation,\n): APIError {\n if (isHttpError(error)) return normalizeAPIError(error);\n\n const networkCode = socketErrorCode(error);\n const result = networkCode\n ? s3Error(\"S3_NETWORK_ERROR\", { code: networkCode }, { cause: error })\n : s3Error(\"INTERNAL_ERROR\", undefined, { cause: error });\n\n // An aborted request is a client disconnect, not a server failure.\n if (!request.signal.aborted) {\n report(error, result, env, { request, operation });\n }\n return result;\n}\n\nfunction report(\n error: unknown,\n result: APIError,\n env: ErrorBoundaryEnv,\n context: { request: Request; operation?: S3Operation },\n): void {\n env.logger.error?.(logMessage(error, result), error);\n const failed = (hookError: unknown) => {\n env.logger.error?.(\"onError threw\", hookError);\n };\n try {\n // An async onError must not become an unhandled rejection.\n void Promise.resolve(env.onError?.(error, context)).catch(failed);\n } catch (hookError) {\n failed(hookError);\n }\n}\n\n/**\n * A better-call `APIError` (core's extends it), or a copy from another\n * better-call instance: named `APIError`, with a numeric `statusCode` and\n * a string `body.code`.\n */\nfunction isHttpError(error: unknown): error is RawAPIError {\n if (error instanceof APIError || error instanceof BetterCallAPIError) {\n return true;\n }\n const candidate = error as Partial<RawAPIError> | null;\n return (\n candidate?.name === \"APIError\" &&\n typeof candidate.statusCode === \"number\" &&\n typeof candidate.body?.code === \"string\"\n );\n}\n\nfunction logMessage(error: unknown, result: APIError): string {\n if (error instanceof ConfigError) return `Config error: ${error.message}`;\n if (result.code === \"S3_NETWORK_ERROR\") return result.message;\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction socketErrorCode(error: unknown): string | undefined {\n const candidates = [error, (error as { cause?: unknown } | null)?.cause];\n for (const candidate of candidates) {\n const code = (candidate as { code?: unknown } | null)?.code;\n if (typeof code === \"string\" && NETWORK_CODES.has(code)) return code;\n }\n return undefined;\n}\n\n/** A better-call error from another copy of the library, or a duck-typed one. */\ntype RawAPIError = {\n name: string;\n message: string;\n body?: {\n code?: unknown;\n message?: unknown;\n params?: Record<string, string | number>;\n };\n statusCode?: unknown;\n headers?: HeadersInit;\n};\n\n/** Gives a raw better-call (or duck-typed) error a stable catalog-style code. */\nfunction normalizeAPIError(error: RawAPIError): APIError {\n if (error instanceof APIError) return error;\n\n const body = error.body ?? {};\n const status = typeof error.statusCode === \"number\" ? error.statusCode : 500;\n const message =\n typeof body.message === \"string\" ? body.message : error.message;\n const code =\n typeof body.code === \"string\"\n ? body.code\n : (STATUS_NAMES.get(status) ?? \"INTERNAL_ERROR\");\n\n switch (code) {\n case \"UNSUPPORTED_MEDIA_TYPE\":\n return s3Error(\"UNSUPPORTED_MEDIA_TYPE\", undefined, { cause: error });\n case \"BAD_REQUEST\":\n case \"VALIDATION_ERROR\":\n return s3Error(\"VALIDATION_ERROR\", { issue: message }, { cause: error });\n case \"INTERNAL_SERVER_ERROR\":\n return s3Error(\"INTERNAL_ERROR\", undefined, { cause: error });\n }\n\n return new APIError(\n status,\n {\n code,\n message,\n ...(body.params !== undefined ? { params: body.params } : {}),\n cause: error,\n },\n error.headers,\n );\n}\n","import { ConfigError } from \"@/helpers/error-boundary\";\nimport type { GuardContext } from \"@/types/hook-contexts\";\nimport type { DimahS3Locals, Guard, LifecycleHook } from \"@/types/locals\";\nimport type { HookList } from \"@/types/resolved\";\n\n/**\n * A new null-prototype `locals` object for one call, seeded with trusted\n * in-process values.\n */\nexport function createLocals(seed?: Partial<DimahS3Locals>): DimahS3Locals {\n const locals: DimahS3Locals = Object.create(null);\n if (seed) mergeLocals(locals, seed);\n return locals;\n}\n\n/**\n * Runs guards in order. Each `{ locals }` result is copied into\n * `context.locals`, so later hooks in the call see it. A throw rejects the\n * call. Any other return value is a {@link ConfigError} and never allows.\n */\nexport async function runGuards<C extends GuardContext>(\n guards: HookList<Guard<C>>,\n context: C,\n): Promise<void> {\n for (const { plugin, hook } of guards) {\n const result: unknown = await hook(context);\n if (result === undefined) continue;\n if (!isGuardResult(result)) {\n throw new ConfigError(\n `${guardName(plugin)} for \"${context.operation}\" returned ${describeValue(result)}. ` +\n \"Return nothing or { locals } to allow, and throw to reject.\",\n );\n }\n mergeLocals(context.locals, result.locals);\n }\n}\n\nexport type RunLifecycleOptions = {\n /**\n * Runs when a plugin hook throws, before the error is rethrown. Use it to\n * undo the operation, for example to delete an object whose bookkeeping\n * failed.\n */\n onPluginError?: (error: unknown) => Promise<void> | void;\n};\n\n/**\n * Runs lifecycle hooks in order: plugins first, then the user hook. The\n * first throw stops the rest and is rethrown. A user hook failure leaves the\n * operation's effects in place.\n */\nexport async function runLifecycle<C>(\n hooks: HookList<LifecycleHook<C>>,\n context: C,\n options: RunLifecycleOptions = {},\n): Promise<void> {\n for (const { plugin, hook } of hooks) {\n try {\n await hook(context);\n } catch (error) {\n if (plugin !== undefined) await options.onPluginError?.(error);\n throw error;\n }\n }\n}\n\nfunction mergeLocals(target: DimahS3Locals, source: object): void {\n for (const [key, value] of Object.entries(source)) {\n (target as Record<string, unknown>)[key] = value;\n }\n}\n\n/**\n * Exactly `{ locals: object }`: a plain object whose only key is `locals`,\n * holding an object that is not an array.\n */\nexport function isGuardResult(\n value: unknown,\n): value is { locals: Partial<DimahS3Locals> } {\n if (!isPlainObject(value)) return false;\n const keys = Object.keys(value);\n return (\n keys.length === 1 &&\n keys[0] === \"locals\" &&\n typeof value.locals === \"object\" &&\n value.locals !== null &&\n !Array.isArray(value.locals)\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction guardName(plugin: string | undefined): string {\n return plugin === undefined ? \"A guard\" : `The \"${plugin}\" plugin guard`;\n}\n\nfunction describeValue(value: unknown): string {\n switch (typeof value) {\n case \"string\":\n return \"a string\";\n case \"function\":\n return \"a function\";\n case \"object\":\n if (value === null) return \"null\";\n return Array.isArray(value)\n ? \"an array\"\n : \"an object other than { locals }\";\n default:\n return String(value);\n }\n}\n","import type { ResolvedConfig } from \"@/types/resolved\";\n\n/**\n * Request for an in-process call that did not pass one: a GET to the API\n * base URL (`baseURL`, else `http://localhost` plus `basePath`) carrying the\n * call headers and signal.\n */\nexport function syntheticRequest(\n config: Pick<ResolvedConfig, \"basePath\" | \"baseURL\">,\n init: { headers?: HeadersInit; signal?: AbortSignal } = {},\n): Request {\n return new Request(config.baseURL ?? `http://localhost${config.basePath}`, {\n headers: init.headers,\n signal: init.signal,\n });\n}\n","import type { DimahS3Config } from \"@/types/config\";\nimport type { ResolvedConfig } from \"@/types/resolved\";\n\n/**\n * Router context key of the resolved config. Plugin endpoints see only the\n * user `config`; the core endpoints and the error boundary read this one.\n * `Symbol.for` keeps one key across the entry points, which are bundled\n * separately.\n */\nconst RESOLVED_CONFIG: unique symbol = Symbol.for(\"dimah-s3.resolved-config\");\n\n/** What the dimahS3 router injects into every endpoint's `ctx.context`. */\nexport type RouterContext = {\n config: Readonly<DimahS3Config>;\n [RESOLVED_CONFIG]: ResolvedConfig;\n};\n\n/** The router context for the user config and its resolved form. */\nexport function createRouterContext(\n config: Readonly<DimahS3Config>,\n resolved: ResolvedConfig,\n): RouterContext {\n return { config, [RESOLVED_CONFIG]: resolved };\n}\n\n/**\n * The resolved config in an endpoint's `ctx.context`. Throws when the\n * endpoint is called outside a dimahS3 router.\n */\nexport function resolvedConfig(context: object): ResolvedConfig {\n const resolved = (context as Partial<RouterContext>)[RESOLVED_CONFIG];\n if (!resolved) {\n throw new Error(\n \"createS3Endpoint needs the dimahS3 router context. Mount the endpoint as a plugin endpoint and call it through the HTTP handler.\",\n );\n }\n return resolved;\n}\n","import { createMiddleware } from \"better-call\";\nimport { toAPIError } from \"@/helpers/error-boundary\";\nimport { createLocals, runGuards } from \"@/helpers/hooks\";\nimport { syntheticRequest } from \"@/helpers/request\";\nimport type { S3EndpointContext } from \"./context\";\nimport { resolvedConfig, type RouterContext } from \"./router-context\";\n\n/**\n * Adds `config`, `request` and `locals` to the endpoint context. With\n * `runGuards`, it also runs the instance guards (operation `\"plugin\"`) and\n * keeps the `locals` they return. It runs them once per call: when an\n * earlier middleware already did, it reuses that `locals`.\n */\nfunction contextMiddleware(options: { runGuards: boolean }) {\n return createMiddleware(async (ctx): Promise<S3EndpointContext> => {\n const resolved = resolvedConfig(ctx.context);\n const injected = ctx.context as RouterContext & Partial<S3EndpointContext>;\n const { config } = injected;\n const request =\n ctx.request ?? syntheticRequest(resolved, { headers: ctx.headers });\n if (injected.locals) return { config, request, locals: injected.locals };\n\n const locals = createLocals();\n if (options.runGuards) {\n try {\n await runGuards(resolved.guard, {\n request,\n operation: \"plugin\",\n locals,\n });\n } catch (error) {\n throw toAPIError(error, resolved, request, \"plugin\");\n }\n }\n return { config, request, locals };\n });\n}\n\n/**\n * Context middleware of every plugin endpoint. Plugin endpoints are guarded\n * here; core endpoints run their guards inside the operation.\n */\nexport const s3ContextMiddleware = contextMiddleware({ runGuards: true });\n\n/** Context middleware of the core endpoints, whose operations run the guards. */\nexport const coreContextMiddleware = contextMiddleware({ runGuards: false });\n\n/**\n * Creates a middleware for plugin endpoints. Its handler sees the same\n * `ctx.context` as the endpoint (`config`, `request`, `locals`), and the\n * instance guards have already run.\n *\n * ```ts\n * const requireUser = createS3Middleware(async (ctx) => {\n * if (!ctx.context.locals.userId) throw s3Error(\"UNAUTHORIZED\");\n * });\n *\n * createS3Endpoint(\"/audit/recent\", { method: \"GET\", use: [requireUser] }, handler);\n * ```\n */\nexport const createS3Middleware = createMiddleware.create({\n use: [s3ContextMiddleware],\n});\n","import { S3_API_ROUTES, s3Error } from \"@dimah-s3/core\";\nimport {\n createEndpoint,\n type Endpoint,\n type EndpointBaseOptions,\n type EndpointHandler,\n type StandardSchemaV1,\n} from \"better-call\";\nimport * as z from \"zod\";\nimport { toAPIError } from \"@/helpers/error-boundary\";\nimport type { S3Operation } from \"@/types/hook-contexts\";\nimport type { S3EndpointContext } from \"./context\";\nimport {\n coreContextMiddleware,\n s3ContextMiddleware,\n} from \"./create-s3-middleware\";\nimport { resolvedConfig } from \"./router-context\";\n\n/** HTTP methods a dimah-s3 endpoint can use. */\nexport type S3EndpointMethod = \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\";\n\n/**\n * Options of {@link createS3Endpoint}. `GET` and `DELETE` read the `query`.\n * `POST` and `PATCH` read a JSON `body`.\n */\nexport type S3EndpointOptions = Omit<EndpointBaseOptions, \"disableBody\"> &\n (\n | { method: \"GET\"; body?: never }\n | { method: \"DELETE\"; body?: never }\n | { method: \"POST\" | \"PATCH\"; body?: StandardSchemaV1 }\n );\n\nconst pluginEndpoint = createEndpoint.create({\n use: [s3ContextMiddleware],\n});\n\n// Core operations run the guards themselves, with their own operation name.\nconst coreEndpoint = createEndpoint.create({\n use: [coreContextMiddleware],\n});\n\n/** The endpoint {@link createS3Endpoint} returns for a path, options and result. */\nexport type S3Endpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n> = ReturnType<typeof pluginEndpoint<Path, Options, R>>;\n\n/** Body endpoints accept only JSON, so a cross-site form post is refused. */\nexport const BODY_MEDIA_TYPES: string[] = [\"application/json\"];\n\nconst CORE_PATHS: ReadonlySet<string> = new Set(Object.values(S3_API_ROUTES));\n\n/**\n * Creates an endpoint for a plugin's `endpoints`. The path is under\n * `basePath`, such as `/audit/recent`.\n *\n * - `GET` and `DELETE` read the `query`. `POST` and `PATCH` read a JSON\n * `body`; any other content type returns `415 UNSUPPORTED_MEDIA_TYPE`.\n * - The instance guards run first (operation `\"plugin\"`), and the `locals`\n * they return are on `ctx.context.locals`, next to `config` and `request`.\n * - A schema failure returns `400 VALIDATION_ERROR`. An `APIError` passes\n * through; anything else is logged, passed to `onError`, and returns\n * `500 INTERNAL_ERROR`.\n *\n * ```ts\n * endpoints: {\n * recent: createS3Endpoint(\n * \"/audit/recent\",\n * { method: \"GET\", query: z.object({ limit: z.coerce.number().optional() }) },\n * async (ctx) => ({ events: await audit.recent(ctx.context.locals, ctx.query) }),\n * ),\n * }\n * ```\n */\nexport function createS3Endpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n>(\n path: Path,\n options: Options,\n handler: EndpointHandler<Path, Options, R, S3EndpointContext>,\n): S3Endpoint<Path, Options, R> {\n if (CORE_PATHS.has(path)) {\n throw new Error(\n `createS3Endpoint(\"${path}\"): the path belongs to a core endpoint.`,\n );\n }\n return buildEndpoint(pluginEndpoint, path, options, handler, \"plugin\");\n}\n\n/**\n * A core endpoint. Internal: its operation runs the guards and names the\n * call, so the context middleware only adds `config`, `request` and an\n * empty `locals`.\n */\nexport function createCoreEndpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n>(\n path: Path,\n options: Options,\n handler: EndpointHandler<Path, Options, R, S3EndpointContext>,\n): S3Endpoint<Path, Options, R> {\n return buildEndpoint(coreEndpoint, path, options, handler);\n}\n\nfunction buildEndpoint<\n Path extends string,\n Options extends S3EndpointOptions,\n R,\n>(\n create: typeof pluginEndpoint,\n path: Path,\n options: Options,\n handler: EndpointHandler<Path, Options, R, S3EndpointContext>,\n operation?: S3Operation,\n): S3Endpoint<Path, Options, R> {\n const endpoint = create(path, endpointOptions(path, options), async (ctx) => {\n try {\n return await handler(ctx);\n } catch (error) {\n const apiError = toAPIError(\n error,\n resolvedConfig(ctx.context),\n ctx.context.request,\n operation,\n );\n // better-call answers a thrown error with the endpoint's response\n // headers and drops the error's own, such as `Content-Range` on a 416.\n new Headers(apiError.headers).forEach((value, name) => {\n ctx.setHeader(name, value);\n });\n throw apiError;\n }\n });\n return withCallContext(endpoint);\n}\n\nfunction endpointOptions<Options extends S3EndpointOptions>(\n path: string,\n options: Options,\n): Options {\n const { method } = options;\n if (![\"GET\", \"POST\", \"PATCH\", \"DELETE\"].includes(method)) {\n throw new Error(\n `createS3Endpoint(\"${path}\"): method must be GET, POST, PATCH or DELETE.`,\n );\n }\n const readsBody = method === \"POST\" || method === \"PATCH\";\n if (!readsBody && options.body !== undefined) {\n throw new Error(\n `createS3Endpoint(\"${path}\"): ${method} reads the query, so it cannot have a body schema.`,\n );\n }\n return {\n ...options,\n ...(options.body !== undefined ? { body: compileIfZod(options.body) } : {}),\n ...(options.query !== undefined\n ? { query: compileIfZod(options.query) }\n : {}),\n metadata: readsBody\n ? { ...options.metadata, allowedMediaTypes: BODY_MEDIA_TYPES }\n : options.metadata,\n // A DELETE is never parsed for a body, so a form post cannot reach it.\n ...(method === \"DELETE\" ? { disableBody: true } : {}),\n // The router reads the body before the hooks run. Reading a clone keeps\n // the original request readable for guards.\n ...(readsBody && options.cloneRequest === undefined\n ? { cloneRequest: true }\n : {}),\n onValidationError:\n options.onValidationError ??\n (({ message }) => {\n throw s3Error(\"VALIDATION_ERROR\", { issue: message });\n }),\n };\n}\n\n/**\n * Compiles a Zod schema with `z.compile()`, so valid input skips the\n * interpreter. A schema it cannot compile, or a runtime without\n * `new Function`, keeps the regular parser.\n */\nfunction compileIfZod<T extends StandardSchemaV1>(schema: T): T {\n if (\"_zod\" in schema) {\n return z.compile(schema as unknown as z.ZodType) as unknown as T;\n }\n return schema;\n}\n\n/**\n * Gives every call its own copy of the router context. better-call merges\n * middleware results into `ctx.context`, and the router passes the same\n * object to every request, so without the copy concurrent calls would see\n * each other's `request` and `locals`.\n */\nfunction withCallContext<E extends Endpoint>(endpoint: E): E {\n const call = (input: { context?: object } = {}) =>\n endpoint({ ...input, context: { ...input.context } });\n return Object.assign(call, {\n path: endpoint.path,\n options: endpoint.options,\n }) as E;\n}\n","import type { FeatureToggle } from \"@/types/config\";\n\n/** Whether a resolved feature is on. Narrows to the enabled shape. */\nexport function isEnabled<T extends { enabled: boolean }>(\n feature: T,\n): feature is T & { enabled: true } {\n return feature.enabled;\n}\n\n/**\n * Whether a feature toggle is on: `true` or an options object is on, and\n * `false` is off. `undefined` uses `defaultOn`. A resolved `{ enabled }`\n * object uses its flag.\n */\nexport function isFeatureOn<T extends object>(\n value: FeatureToggle<T> | { enabled: boolean } | undefined,\n defaultOn = false,\n): boolean {\n if (value === undefined) return defaultOn;\n if (typeof value === \"boolean\") return value;\n if (\"enabled\" in value && typeof value.enabled === \"boolean\") {\n return value.enabled;\n }\n return true;\n}\n","import type { DimahS3Plugin } from \"./types\";\n\n/**\n * Identity helper that keeps the literal `id` and the `context` type, so\n * `s3.context[id]` and `s3[id]` are typed.\n *\n * ```ts\n * export const audit = definePlugin({\n * id: \"audit\",\n * hooks: { upload: { onConfirmed: ({ key }) => log(key) } },\n * context: { log },\n * });\n * ```\n */\nexport function definePlugin<\n Id extends string,\n TContext extends Record<string, unknown> = Record<string, unknown>,\n>(plugin: DimahS3Plugin<Id, TContext>): DimahS3Plugin<Id, TContext> {\n return plugin;\n}\n","import { s3Error } from \"@dimah-s3/core\";\n\n/*\n * Reads a failed S3 call. The AWS SDK names its errors (`NoSuchKey`), some\n * S3-compatible providers only set `Code`, and every response carries the\n * HTTP status in `$metadata`, so each check accepts any of the three.\n */\n\ntype AwsErrorFields = {\n name?: unknown;\n Code?: unknown;\n $metadata?: { httpStatusCode?: unknown };\n};\n\nfunction fields(error: unknown): AwsErrorFields {\n return typeof error === \"object\" && error !== null\n ? (error as AwsErrorFields)\n : {};\n}\n\n/** The error `name` or `Code` is one of `names`. */\nfunction named(error: unknown, names: readonly string[]): boolean {\n const { name, Code } = fields(error);\n return (\n (typeof name === \"string\" && names.includes(name)) ||\n (typeof Code === \"string\" && names.includes(Code))\n );\n}\n\nfunction matches(\n error: unknown,\n names: readonly string[],\n status: number,\n): boolean {\n return named(error, names) || awsStatus(error) === status;\n}\n\n/** The HTTP status S3 answered a failed call with, when there was one. */\nexport function awsStatus(error: unknown): number | undefined {\n const status = fields(error).$metadata?.httpStatusCode;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * The object, or the multipart upload, does not exist. A missing bucket is\n * a 404 too, but it is a config error, so it does not count.\n */\nexport function isAwsNotFound(error: unknown): boolean {\n if (named(error, [\"NoSuchBucket\"])) return false;\n return matches(error, [\"NoSuchKey\", \"NotFound\", \"NoSuchUpload\"], 404);\n}\n\n/** An `If-Match` or `If-Unmodified-Since` condition failed. */\nexport function isAwsPreconditionFailed(error: unknown): boolean {\n return matches(error, [\"PreconditionFailed\"], 412);\n}\n\n/** The provider does not implement the request, such as a conditional delete. */\nexport function isAwsNotImplemented(error: unknown): boolean {\n return matches(error, [\"NotImplemented\"], 501);\n}\n\n/** The requested byte range is outside the object. */\nexport function isAwsRangeNotSatisfiable(error: unknown): boolean {\n return matches(error, [\"InvalidRange\"], 416);\n}\n\n/** Runs an S3 call and turns a not-found error into `OBJECT_NOT_FOUND`. */\nexport async function sendOrObjectNotFound<T>(\n send: () => Promise<T>,\n): Promise<T> {\n try {\n return await send();\n } catch (error) {\n if (isAwsNotFound(error)) {\n throw s3Error(\"OBJECT_NOT_FOUND\", undefined, { cause: error });\n }\n throw error;\n }\n}\n","import {\n describeFileType,\n matchesFileTypes,\n s3Error,\n S3_MAX_POST_OBJECT_BYTES,\n} from \"@dimah-s3/core\";\nimport type { UploadFile } from \"@/types/hook-contexts\";\nimport type { ResolvedUpload } from \"@/types/resolved\";\n\n/** File limits from `upload` (`fileTypes` / `maxFileSize`). */\nexport type FileConstraints = Pick<ResolvedUpload, \"fileTypes\" | \"maxFileSize\">;\n\n/** Fails with `FILE_TOO_LARGE` when `size` is over `maxFileSize`, if one is set. */\nexport function assertWithinMaxFileSize(\n maxFileSize: number | undefined,\n size: number,\n): void {\n if (maxFileSize !== undefined && size > maxFileSize) {\n throw s3Error(\"FILE_TOO_LARGE\", { size, maxFileSize });\n }\n}\n\n/**\n * Checks a file against the route limits: `FILE_TYPE_NOT_ALLOWED` when it\n * matches none of `fileTypes`, `FILE_EMPTY` when it has no bytes, and\n * `FILE_TOO_LARGE` when it is over `maxFileSize`. Runs on the declared file\n * at presign, and again on the HeadObject values at confirm.\n */\nexport function assertFileConstraints(\n constraints: FileConstraints,\n file: Pick<UploadFile, \"size\" | \"type\"> & { name?: string },\n): void {\n const { fileTypes, maxFileSize } = constraints;\n const name = file.name ?? \"\";\n if (fileTypes?.length && !matchesFileTypes(name, file.type, fileTypes)) {\n throw s3Error(\"FILE_TYPE_NOT_ALLOWED\", {\n type: describeFileType(name, file.type),\n allowed: fileTypes.join(\", \"),\n });\n }\n if (file.size === 0) throw s3Error(\"FILE_EMPTY\");\n assertWithinMaxFileSize(maxFileSize, file.size);\n}\n\n/**\n * Fails with `FILE_TOO_LARGE` above 5 GiB, the most S3 takes in one POST or\n * PutObject. Larger files need multipart.\n */\nexport function assertSingleUploadSize(size: number): void {\n if (size > S3_MAX_POST_OBJECT_BYTES) {\n throw s3Error(\"FILE_TOO_LARGE\", {\n size,\n maxFileSize: S3_MAX_POST_OBJECT_BYTES,\n });\n }\n}\n","import {\n AbortMultipartUploadCommand,\n DeleteObjectCommand,\n type S3Client,\n} from \"@aws-sdk/client-s3\";\nimport { isAwsNotImplemented, isAwsPreconditionFailed } from \"./aws-errors\";\n\n/** The object to delete, and the ETag it must still have. */\nexport type ConditionalDeleteInput = {\n bucket: string;\n key: string;\n /** ETag from the HeadObject that identified the object. */\n eTag?: string;\n};\n\n/**\n * DeleteObject that keeps a newer object at the same key. With an `eTag`,\n * the delete is conditional (`If-Match`): when the key now holds another\n * object (`412`), nothing is deleted and it returns `false`. A provider\n * without conditional DeleteObject (`501`) gets a plain delete. Any other\n * failure is thrown.\n */\nexport async function deleteObjectIfMatch(\n client: S3Client,\n input: ConditionalDeleteInput,\n): Promise<boolean> {\n const target = { Bucket: input.bucket, Key: input.key };\n if (input.eTag === undefined) {\n await client.send(new DeleteObjectCommand(target));\n return true;\n }\n try {\n await client.send(\n new DeleteObjectCommand({ ...target, IfMatch: input.eTag }),\n );\n } catch (error) {\n if (isAwsPreconditionFailed(error)) return false;\n if (!isAwsNotImplemented(error)) throw error;\n await client.send(new DeleteObjectCommand(target));\n }\n return true;\n}\n\n/**\n * {@link deleteObjectIfMatch} after a failed check, ignoring every failure:\n * the caller is already returning an error, and an object left behind is\n * caught by purge or a bucket lifecycle rule.\n */\nexport async function deleteObjectBestEffort(\n client: S3Client,\n bucket: string,\n key: string,\n eTag?: string,\n): Promise<void> {\n try {\n await deleteObjectIfMatch(client, { bucket, key, eTag });\n } catch {\n // Best-effort cleanup.\n }\n}\n\n/** Best-effort AbortMultipartUpload, when init fails after CreateMultipartUpload. */\nexport async function abortMultipartBestEffort(\n client: S3Client,\n bucket: string,\n key: string,\n uploadId: string,\n): Promise<void> {\n try {\n await client.send(\n new AbortMultipartUploadCommand({\n Bucket: bucket,\n Key: key,\n UploadId: uploadId,\n }),\n );\n } catch {\n // Best-effort cleanup.\n }\n}\n","import { base64UrlDecode, base64UrlEncode } from \"@dimah-s3/core\";\n\n/** Values S3 and HTTP clients carry unchanged in an `x-amz-meta-*` header. */\nconst PLAIN_VALUE = /^(?:[\\x21-\\x7e](?:[\\x20-\\x7e]*[\\x21-\\x7e])?)?$/;\n\n/** A value that reads as an RFC 2047 encoded word, so it must be encoded to survive a round trip. */\nconst ENCODED_WORD_LIKE = /^=\\?.*\\?=$/s;\n\n/** One RFC 2047 encoded word: `=?charset?B|Q?text?=`, with an optional RFC 2231 language. */\nconst ENCODED_WORD = /^=\\?([^?*]+)(?:\\*[^?]*)?\\?([bq])\\?([^?]*)\\?=$/i;\n\nconst UTF8_CHARSETS = new Set([\"utf-8\", \"utf8\", \"us-ascii\"]);\n\n/**\n * Makes a metadata value safe to send as an `x-amz-meta-*` header. Printable\n * ASCII without surrounding spaces is kept as is. Anything else becomes one\n * RFC 2047 encoded word (`=?UTF-8?B?…?=`), the form S3 itself returns for\n * non-ASCII metadata.\n */\nexport function encodeMetadataValue(value: string): string {\n if (PLAIN_VALUE.test(value) && !ENCODED_WORD_LIKE.test(value)) return value;\n return `=?UTF-8?B?${toBase64(new TextEncoder().encode(value))}?=`;\n}\n\n/**\n * Reverses {@link encodeMetadataValue}, and decodes any RFC 2047 value S3\n * returns: one or more `B` or `Q` encoded words in UTF-8 or US-ASCII,\n * separated by whitespace. A value that is not a well-formed encoded word\n * is returned unchanged.\n */\nexport function decodeMetadataValue(value: string): string {\n const words = value.trim().split(/\\s+/);\n const chunks: Uint8Array[] = [];\n for (const word of words) {\n const match = ENCODED_WORD.exec(word);\n if (!match || !UTF8_CHARSETS.has(match[1].toLowerCase())) return value;\n const bytes =\n match[2].toLowerCase() === \"b\"\n ? fromBase64(match[3])\n : fromQuotedPrintable(match[3]);\n if (!bytes) return value;\n chunks.push(bytes);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(concat(chunks));\n } catch {\n return value;\n }\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n const url = base64UrlEncode(bytes).replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n return url.padEnd(Math.ceil(url.length / 4) * 4, \"=\");\n}\n\nfunction fromBase64(text: string): Uint8Array | undefined {\n if (!/^[a-z0-9+/]*={0,2}$/i.test(text) || text.length % 4 !== 0) {\n return undefined;\n }\n try {\n return base64UrlDecode(\n text.replace(/=+$/, \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\"),\n );\n } catch {\n return undefined;\n }\n}\n\n/** RFC 2047 `Q` encoding: `_` is a space and `=XX` is a hex byte. */\nfunction fromQuotedPrintable(text: string): Uint8Array | undefined {\n const bytes: number[] = [];\n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"_\") {\n bytes.push(0x20);\n } else if (char === \"=\") {\n const hex = text.slice(i + 1, i + 3);\n if (!/^[0-9a-f]{2}$/i.test(hex)) return undefined;\n bytes.push(Number.parseInt(hex, 16));\n i += 2;\n } else {\n const code = char.charCodeAt(0);\n if (code < 0x21 || code > 0x7e) return undefined;\n bytes.push(code);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction concat(chunks: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n","import { ConfigError } from \"@/helpers/error-boundary\";\nimport {\n decodeMetadataValue,\n encodeMetadataValue,\n} from \"@/helpers/metadata-encoding\";\n\n/** S3 user-metadata key for the upload marker. Its value is the upload token. */\nexport const UPLOAD_MARKER_META = \"dimah-upload\";\n\n/** S3 user-metadata key for `upload.object().previousKey`. */\nexport const PREVIOUS_KEY_META = \"dimah-previous-key\";\n\n/** S3 limit on user metadata: UTF-8 bytes of every key and value, summed. */\nexport const MAX_METADATA_BYTES = 2048;\n\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set([\n UPLOAD_MARKER_META,\n PREVIOUS_KEY_META,\n]);\n\n/** An HTTP header-name token, so `x-amz-meta-{key}` is a valid header. */\nconst METADATA_KEY = /^[!#$%&'*+.^`|~\\w-]+$/;\n\nexport type ObjectMetadataInput = {\n /** User metadata from `upload.object()` or `s3.put`. */\n metadata?: Record<string, string>;\n uploadToken: string;\n /** Key to delete after a successful confirm. */\n previousKey?: string;\n};\n\n/**\n * S3 user metadata for a new object: the user metadata plus the upload\n * marker and the previous key. Keys are lowercased, as S3 stores them, and\n * values are RFC 2047-encoded where needed.\n *\n * Throws a {@link ConfigError} when a key is invalid, repeats, or uses an\n * internal name, or when the total exceeds {@link MAX_METADATA_BYTES}.\n */\nexport function buildObjectMetadata(\n input: ObjectMetadataInput,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [name, value] of Object.entries(input.metadata ?? {})) {\n const key = name.toLowerCase();\n if (!METADATA_KEY.test(key)) {\n throw new ConfigError(`S3 metadata key \"${name}\" is not a valid name.`);\n }\n if (INTERNAL_KEYS.has(key)) {\n throw new ConfigError(`S3 metadata key \"${name}\" is reserved.`);\n }\n if (Object.hasOwn(result, key)) {\n throw new ConfigError(`S3 metadata key \"${name}\" is set twice.`);\n }\n result[key] = encodeMetadataValue(value);\n }\n const userBytes = metadataByteSize(result);\n\n result[UPLOAD_MARKER_META] = input.uploadToken;\n if (input.previousKey !== undefined) {\n result[PREVIOUS_KEY_META] = encodeMetadataValue(input.previousKey);\n }\n const totalBytes = metadataByteSize(result);\n if (totalBytes > MAX_METADATA_BYTES) {\n throw new ConfigError(\n `S3 metadata is ${totalBytes} bytes (${userBytes} from upload.object() ` +\n `and ${totalBytes - userBytes} added by dimah-s3); S3 allows ` +\n `${MAX_METADATA_BYTES}. Keys and values count once encoded.`,\n );\n }\n return result;\n}\n\n/** User metadata as HeadObject returns it, split from the internal keys. */\nexport type StoredObjectMetadata = {\n /** Decoded user metadata, without internal keys. */\n metadata: Record<string, string>;\n uploadToken?: string;\n previousKey?: string;\n};\n\n/** Splits and decodes HeadObject `Metadata`. */\nexport function readObjectMetadata(\n raw: Record<string, string> | undefined,\n): StoredObjectMetadata {\n const metadata: Record<string, string> = {};\n let uploadToken: string | undefined;\n let previousKey: string | undefined;\n for (const [name, value] of Object.entries(raw ?? {})) {\n const key = name.toLowerCase();\n const decoded = decodeMetadataValue(value);\n if (key === UPLOAD_MARKER_META) uploadToken = decoded;\n else if (key === PREVIOUS_KEY_META) previousKey = decoded || undefined;\n else metadata[key] = decoded;\n }\n return { metadata, uploadToken, previousKey };\n}\n\n/**\n * The upload token an object was written with: its upload marker, read\n * from HeadObject `Metadata`. `undefined` for an object dimah-s3 did not\n * write. A plugin that cleans up an upload deletes the object only while\n * this still equals the token of the upload it tracks.\n */\nexport function readUploadMarker(\n metadata: Record<string, string> | undefined,\n): string | undefined {\n return readObjectMetadata(metadata).uploadToken;\n}\n\nfunction metadataByteSize(metadata: Record<string, string>): number {\n const encoder = new TextEncoder();\n let bytes = 0;\n for (const [key, value] of Object.entries(metadata)) {\n bytes += encoder.encode(key).length + encoder.encode(value).length;\n }\n return bytes;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { S3Client } from "@aws-sdk/client-s3";
2
2
  import type { ContentDispositionType, S3Api, S3ObjectAcl, S3RouteName, UploadPresignMethod } from "@dimah-s3/core";
3
- import type { DeleteGuardContext, DeleteOnDeletedContext, DownloadGuardContext, DownloadOnPresignedContext, DownloadResolveContext, DownloadResolveInfo, GuardContext, MultipartGuardContext, MultipartOnAbortContext, RouteGuardContext, S3Operation, UploadConfirmGuardContext, UploadGuardContext, UploadObjectContext, UploadObjectInfo, UploadOnConfirmedContext, UploadOnStartContext } from "./hook-contexts";
4
- import type { DimahS3Locals, DimahS3RoutePluginOptions, Guard, LifecycleHook } from "./locals";
3
+ import type { DeleteGuardContext, DeleteOnDeletedContext, DownloadGuardContext, DownloadOnPresignedContext, DownloadResolveContext, DownloadResolveInfo, GuardContext, MultipartGuardContext, MultipartOnAbortContext, RouteGuardContext, S3Operation, UploadConfirmGuardContext, UploadGuardContext, UploadObjectContext, UploadObjectInfo, UploadOnConfirmedContext, UploadOnStartContext } from "./hook-contexts.js";
4
+ import type { DimahS3Locals, DimahS3RoutePluginOptions, Guard, LifecycleHook } from "./locals.js";
5
5
  import type { DimahS3Plugin } from "../plugin/types.js";
6
6
  /** `true` or an options object turns the feature on; omit it or pass `false` to keep it off. */
7
7
  export type FeatureToggle<T> = boolean | T;
@@ -1,7 +1,10 @@
1
1
  import type { ContentDispositionType, S3ObjectAcl } from "@dimah-s3/core";
2
- import type { DimahS3Locals } from "./locals";
3
- /** The call a hook runs in. Plugin endpoints use `"plugin"`. */
4
- export type S3Operation = "upload" | "confirm" | "download" | "file" | "delete" | "deleteMany" | "catalog" | "put" | "multipart.init" | "multipart.signPart" | "multipart.listParts" | "multipart.complete" | "multipart.abort" | "plugin";
2
+ import type { DimahS3Locals } from "./locals.js";
3
+ /**
4
+ * The call a hook runs in. Plugin endpoints use `"plugin"`. `"record"` is
5
+ * `s3.db.record`, which is not an HTTP route.
6
+ */
7
+ export type S3Operation = "upload" | "confirm" | "download" | "file" | "delete" | "deleteMany" | "catalog" | "put" | "multipart.init" | "multipart.signPart" | "multipart.listParts" | "multipart.complete" | "multipart.abort" | "plugin" | "record";
5
8
  /**
6
9
  * How the bytes reach S3: a presigned POST or PUT, a multipart upload, or
7
10
  * `s3.put` on the server.
@@ -1 +1 @@
1
- {"version":3,"file":"hook-contexts.d.ts","sourceRoot":"","sources":["../../src/types/hook-contexts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE9C,gEAAgE;AAChE,MAAM,MAAM,WAAW,GACnB,QAAQ,GACR,SAAS,GACT,UAAU,GACV,MAAM,GACN,QAAQ,GACR,YAAY,GACZ,SAAS,GACT,KAAK,GACL,gBAAgB,GAChB,oBAAoB,GACpB,qBAAqB,GACrB,oBAAoB,GACpB,iBAAiB,GACjB,QAAQ,CAAC;AAEb;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,KAAK,GAAG,WAAW,GAAG,QAAQ,CAAC;AAEjE,wEAAwE;AACxE,MAAM,MAAM,YAAY,GAAG;IACzB,qEAAqE;IACrE,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,WAAW,CAAC;IACvB,0EAA0E;IA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CAAC;CACpB,CAAC;AAEF,0CAA0C;AAC1C,MAAM,MAAM,0BAA0B,GAAG,oBAAoB,GAAG;IAC9D,2DAA2D;IAC3D,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,kCAAkC;AAClC,MAAM,MAAM,kBAAkB,GAAG,aAAa,CAAC;AAE/C;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,aAAa,CAAC;AAEnD,8DAA8D;AAC9D,MAAM,MAAM,sBAAsB,GAAG,aAAa,GAAG;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,6BAA6B;IAC7B,IAAI,EAAE,UAAU,CAAC;CAClB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAC7B,CAAC,sBAAsB,GAAG;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,2BAA2B;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAC;CACd,CAAC,GACF,CAAC,sBAAsB,GAAG;IAAE,MAAM,EAAE,MAAM,GAAG,OAAO,GAAG,UAAU,CAAA;CAAE,CAAC,CAAC;AAEzE,8CAA8C;AAC9C,MAAM,MAAM,uBAAuB,GAAG,sBAAsB,CAAC"}
@@ -1,4 +1,4 @@
1
- export type { DeleteGuardContext, DeleteOnDeletedContext, DownloadGuardContext, DownloadOnPresignedContext, DownloadResolveContext, DownloadResolveInfo, GuardContext, MultipartGuardContext, MultipartOnAbortContext, MultipartUploadContext, ObjectContext, ObjectS3Headers, RouteGuardContext, S3Operation, UploadConfirmGuardContext, UploadFile, UploadGuardContext, UploadKind, UploadObjectContext, UploadObjectInfo, UploadOnConfirmedContext, UploadOnStartContext, VerifiedObject, } from "./hook-contexts";
2
- export type { DeleteConfig, DimahS3Api, DimahS3Config, DimahS3Logger, DimahS3RouteConfig, DownloadConfig, FeatureToggle, MultipartConfig, PutInput, S3ServerCallOptions, TicketSubject, UploadConfig, } from "./config";
3
- export type { DimahS3Locals, DimahS3RoutePluginOptions, Guard, GuardResult, LifecycleHook, } from "./locals";
1
+ export type { DeleteGuardContext, DeleteOnDeletedContext, DownloadGuardContext, DownloadOnPresignedContext, DownloadResolveContext, DownloadResolveInfo, GuardContext, MultipartGuardContext, MultipartOnAbortContext, MultipartUploadContext, ObjectContext, ObjectS3Headers, RouteGuardContext, S3Operation, UploadConfirmGuardContext, UploadFile, UploadGuardContext, UploadKind, UploadObjectContext, UploadObjectInfo, UploadOnConfirmedContext, UploadOnStartContext, VerifiedObject, } from "./hook-contexts.js";
2
+ export type { DeleteConfig, DimahS3Api, DimahS3Config, DimahS3Logger, DimahS3RouteConfig, DownloadConfig, FeatureToggle, MultipartConfig, PutInput, S3ServerCallOptions, TicketSubject, UploadConfig, } from "./config.js";
3
+ export type { DimahS3Locals, DimahS3RoutePluginOptions, Guard, GuardResult, LifecycleHook, } from "./locals.js";
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,8 +1,8 @@
1
1
  import type { S3Client } from "@aws-sdk/client-s3";
2
2
  import type { ContentDispositionType, S3ObjectAcl, UploadPresignMethod } from "@dimah-s3/core";
3
- import type { DimahS3Config, DimahS3Logger, DownloadConfig, TicketSubject, UploadConfig } from "./config";
4
- import type { DeleteGuardContext, DeleteOnDeletedContext, DownloadGuardContext, DownloadOnPresignedContext, GuardContext, MultipartGuardContext, MultipartOnAbortContext, RouteGuardContext, UploadConfirmGuardContext, UploadGuardContext, UploadOnConfirmedContext, UploadOnStartContext } from "./hook-contexts";
5
- import type { DimahS3RoutePluginOptions, Guard, LifecycleHook } from "./locals";
3
+ import type { DimahS3Config, DimahS3Logger, DownloadConfig, TicketSubject, UploadConfig } from "./config.js";
4
+ import type { DeleteGuardContext, DeleteOnDeletedContext, DownloadGuardContext, DownloadOnPresignedContext, GuardContext, MultipartGuardContext, MultipartOnAbortContext, RouteGuardContext, UploadConfirmGuardContext, UploadGuardContext, UploadOnConfirmedContext, UploadOnStartContext } from "./hook-contexts.js";
5
+ import type { DimahS3RoutePluginOptions, Guard, LifecycleHook } from "./locals.js";
6
6
  /**
7
7
  * A route feature a call can hit. `multipart` is nested under upload, and
8
8
  * `proxy` is a download in `mode: "proxy"`, the only one `/file` serves.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimah-s3/server",
3
- "version": "2.0.0-beta.1",
3
+ "version": "2.0.0-beta.11",
4
4
  "description": "Presigned S3 server — dimahS3() with HTTP handler and direct api for upload, download, delete, and multipart",
5
5
  "keywords": [
6
6
  "s3",
@@ -25,7 +25,7 @@
25
25
  "sveltekit",
26
26
  "typescript"
27
27
  ],
28
- "homepage": "https://v2.s3.dimah.dev/docs/server",
28
+ "homepage": "https://s3.dimah.dev/docs/server",
29
29
  "bugs": {
30
30
  "url": "https://github.com/dimah-kz/dimah-s3/issues"
31
31
  },
@@ -80,24 +80,24 @@
80
80
  "dist"
81
81
  ],
82
82
  "dependencies": {
83
- "@aws-sdk/s3-presigned-post": "^3.1161.0",
84
- "@aws-sdk/s3-request-presigner": "^3.1161.0",
85
- "@dimah-s3/core": "2.0.0-beta.1",
86
- "better-call": "1.4.4",
83
+ "@aws-sdk/s3-presigned-post": "^3.1172.0",
84
+ "@aws-sdk/s3-request-presigner": "^3.1172.0",
85
+ "@dimah-s3/core": "2.0.0-beta.11",
86
+ "better-call": "1.4.6",
87
87
  "zod": "^4.6.7"
88
88
  },
89
89
  "devDependencies": {
90
- "@aws-sdk/client-s3": "^3.1161.0",
90
+ "@aws-sdk/client-s3": "^3.1172.0",
91
91
  "@types/node": "^26.6.6",
92
92
  "@workspace/eslint-config": "0.0.1",
93
93
  "@workspace/tsup-config": "0.0.0",
94
94
  "@workspace/typescript-config": "0.0.1",
95
95
  "@workspace/vitest-config": "0.0.7",
96
- "eslint": "^10.14.0",
96
+ "eslint": "^10.15.0",
97
97
  "tsc-alias": "^1.9.10",
98
98
  "tsup": "^9.0.0",
99
99
  "typescript": "7.0.2",
100
- "vitest": "^5.0.5"
100
+ "vitest": "^5.1.1"
101
101
  },
102
102
  "peerDependencies": {
103
103
  "@aws-sdk/client-s3": ">=3"
@@ -106,7 +106,7 @@
106
106
  "access": "public"
107
107
  },
108
108
  "scripts": {
109
- "build": "tsup --config tsup.config.ts && tsc --emitDeclarationOnly -p tsconfig.build.json && tsc-alias",
109
+ "build": "tsup --config tsup.config.ts && tsc --emitDeclarationOnly -p tsconfig.build.json && tsc-alias && node ../../tooling/tsup-config/dts-extensions.mjs",
110
110
  "check-types": "tsc --noEmit",
111
111
  "lint": "eslint --cache --cache-strategy content --max-warnings 0",
112
112
  "test": "vitest run"