@dloizides/content-upload 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -7,8 +7,8 @@ interface CsrfHeader {
7
7
  interface UploadedContent {
8
8
  /** Stable id of the persisted content row. */
9
9
  contentId: string;
10
- /** Server status (e.g. "Active"). */
11
- status: string;
10
+ /** Server status (e.g. "Active"); absent from the Dloizides.Content.Upload.AspNetCore proxy body. */
11
+ status?: string;
12
12
  /** Public download URL; present when the upload was public. */
13
13
  url?: string;
14
14
  }
@@ -63,7 +63,7 @@ declare const DEFAULT_CSRF_HEADER: CsrfHeader;
63
63
  declare function buildUploadRequest(file: Blob, options: UploadImageOptions): UploadRequest;
64
64
  /**
65
65
  * Upload one image as multipart/form-data (`File`, `Category`, `IsPublic`) to a
66
- * consumer-supplied endpoint and return the parsed `{ contentId, status, url }`.
66
+ * consumer-supplied endpoint and return the parsed `{ contentId, status?, url }`.
67
67
  *
68
68
  * Never sets Content-Type: the runtime adds the multipart boundary, and a JSON content type
69
69
  * on a FormData body is a 415 (see `@dloizides/bff-web-client` writeContentTypeGuard).
@@ -98,7 +98,7 @@ declare const enum UploadErrorKind {
98
98
  Http = "http",
99
99
  /** The caller aborted (AbortSignal / hook reset). */
100
100
  Aborted = "aborted",
101
- /** 2xx, but the body was not `{ contentId, status, url? }` (or lacked a required url). */
101
+ /** 2xx, but the body was not `{ contentId, status?, url? }` (or lacked a required url). */
102
102
  InvalidResponse = "invalid-response"
103
103
  }
104
104
 
package/dist/index.d.ts CHANGED
@@ -7,8 +7,8 @@ interface CsrfHeader {
7
7
  interface UploadedContent {
8
8
  /** Stable id of the persisted content row. */
9
9
  contentId: string;
10
- /** Server status (e.g. "Active"). */
11
- status: string;
10
+ /** Server status (e.g. "Active"); absent from the Dloizides.Content.Upload.AspNetCore proxy body. */
11
+ status?: string;
12
12
  /** Public download URL; present when the upload was public. */
13
13
  url?: string;
14
14
  }
@@ -63,7 +63,7 @@ declare const DEFAULT_CSRF_HEADER: CsrfHeader;
63
63
  declare function buildUploadRequest(file: Blob, options: UploadImageOptions): UploadRequest;
64
64
  /**
65
65
  * Upload one image as multipart/form-data (`File`, `Category`, `IsPublic`) to a
66
- * consumer-supplied endpoint and return the parsed `{ contentId, status, url }`.
66
+ * consumer-supplied endpoint and return the parsed `{ contentId, status?, url }`.
67
67
  *
68
68
  * Never sets Content-Type: the runtime adds the multipart boundary, and a JSON content type
69
69
  * on a FormData body is a 415 (see `@dloizides/bff-web-client` writeContentTypeGuard).
@@ -98,7 +98,7 @@ declare const enum UploadErrorKind {
98
98
  Http = "http",
99
99
  /** The caller aborted (AbortSignal / hook reset). */
100
100
  Aborted = "aborted",
101
- /** 2xx, but the body was not `{ contentId, status, url? }` (or lacked a required url). */
101
+ /** 2xx, but the body was not `{ contentId, status?, url? }` (or lacked a required url). */
102
102
  InvalidResponse = "invalid-response"
103
103
  }
104
104
 
package/dist/index.js CHANGED
@@ -43,14 +43,16 @@ function parseUploadedContent(text, requireUrl) {
43
43
  } catch {
44
44
  throw invalid("Upload response was not JSON.");
45
45
  }
46
- if (!isRecord(payload) || typeof payload.contentId !== "string" || typeof payload.status !== "string") {
46
+ const hasBadStatus = isRecord(payload) && payload.status !== void 0 && typeof payload.status !== "string";
47
+ if (!isRecord(payload) || typeof payload.contentId !== "string" || hasBadStatus) {
47
48
  throw invalid("Upload response shape was invalid.");
48
49
  }
50
+ const status = typeof payload.status === "string" ? payload.status : void 0;
49
51
  const url = typeof payload.url === "string" && payload.url !== "" ? payload.url : void 0;
50
52
  if (requireUrl && url === void 0) {
51
53
  throw invalid("Upload response did not include a public URL.");
52
54
  }
53
- return { contentId: payload.contentId, status: payload.status, url };
55
+ return { contentId: payload.contentId, status, url };
54
56
  }
55
57
 
56
58
  // src/transports.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/UploadErrorKind.ts","../src/UploadError.ts","../src/parseUploadedContent.ts","../src/transports.ts","../src/uploadImage.ts","../src/blobFromUri.ts","../src/UploadStatus.ts","../src/useImageUpload.ts"],"names":["UploadErrorKind","UploadStatus","useReducer","useRef","useCallback","useEffect"],"mappings":";;;;;AACO,IAAW,eAAA,qBAAAA,gBAAAA,KAAX;AAEL,EAAAA,iBAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,MAAA,CAAA,GAAO,MAAA;AAEP,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,iBAAA,CAAA,GAAkB,kBAAA;AAVF,EAAA,OAAAA,gBAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;;ACEX,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAKrC,WAAA,CAAY,IAAA,EAAuB,OAAA,EAAiB,MAAA,EAAiB;AACnE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAGO,SAAS,cAAc,KAAA,EAA6B;AACzD,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,OAAO,IAAI,qCAAqC,OAAO,CAAA;AACzD;;;AClBA,SAAS,SAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAEA,SAAS,QAAQ,OAAA,EAA8B;AAC7C,EAAA,OAAO,IAAI,sDAA6C,OAAO,CAA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,EAAU,YAAY,aAAA,CAAc,QAAA;AAAA,QACpC,QAAQ,UAAA,CAAW,MAAA;AAAA,QACnB,UAAA,EAAY,CAAC,OAAA,KAAY;AACvB,UAAA,IAAI,WAAU,EAAG;AACf,YAAA,QAAA,CAAS,EAAE,IAAA,EAAM,UAAA,EAAY,OAAA,EAAS,CAAA;AAAA,UACxC;AAAA,QACF;AAAA,OACD,CAAA;AACD,MAAA,IAAI,CAAC,WAAU,EAAG;AAChB,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,CAAA;AACjC,MAAA,SAAA,GAAY,MAAM,CAAA;AAClB,MAAA,OAAO,MAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,CAAC,WAAU,EAAG;AAChB,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,MAAM,KAAA,GAAQ,cAAc,KAAK,CAAA;AACjC,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,KAAA,EAAO,CAAA;AAChC,MAAA,OAAA,GAAU,KAAK,CAAA;AACf,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF,CAAA,EAAG,CAAC,aAAa,CAAC,CAAA;AAElB,EAAA,MAAM,KAAA,GAAQA,kBAAY,MAAY;AACpC,IAAA,aAAA,EAAc;AACd,IAAA,QAAA,CAAS,EAAE,IAAA,EAAM,OAAA,EAAS,CAAA;AAAA,EAC5B,CAAA,EAAG,CAAC,aAAa,CAAC,CAAA;AAElB,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAM;AACnC","file":"index.js","sourcesContent":["/** Why an upload failed. Consumers map this to translated copy; `message` is developer-facing only. */\nexport const enum UploadErrorKind {\n /** Rejected client-side before any request: empty file, too large, disallowed MIME type. */\n Validation = 'validation',\n /** The request never produced an HTTP response (offline, DNS, CORS). */\n Network = 'network',\n /** The server answered outside 2xx; `status` carries the code. */\n Http = 'http',\n /** The caller aborted (AbortSignal / hook reset). */\n Aborted = 'aborted',\n /** 2xx, but the body was not `{ contentId, status, url? }` (or lacked a required url). */\n InvalidResponse = 'invalid-response',\n}\n","import { UploadErrorKind } from './UploadErrorKind';\n\n/** The single error type thrown by `uploadImage` and surfaced by `useImageUpload`. */\nexport class UploadError extends Error {\n readonly kind: UploadErrorKind;\n /** HTTP status for `UploadErrorKind.Http`; undefined otherwise. */\n readonly status: number | undefined;\n\n constructor(kind: UploadErrorKind, message: string, status?: number) {\n super(message);\n this.name = 'UploadError';\n this.kind = kind;\n this.status = status;\n }\n}\n\n/** Normalise anything thrown into an `UploadError` (unknown throws become `Network`). */\nexport function toUploadError(cause: unknown): UploadError {\n if (cause instanceof UploadError) {\n return cause;\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new UploadError(UploadErrorKind.Network, message);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadedContent } from './types';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(message: string): UploadError {\n return new UploadError(UploadErrorKind.InvalidResponse, message);\n}\n\n/** Parse the upload endpoint's JSON body into `UploadedContent`, or throw `InvalidResponse`. */\nexport function parseUploadedContent(text: string, requireUrl: boolean): UploadedContent {\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch {\n throw invalid('Upload response was not JSON.');\n }\n if (!isRecord(payload) || typeof payload.contentId !== 'string' || typeof payload.status !== 'string') {\n throw invalid('Upload response shape was invalid.');\n }\n const url = typeof payload.url === 'string' && payload.url !== '' ? payload.url : undefined;\n if (requireUrl && url === undefined) {\n throw invalid('Upload response did not include a public URL.');\n }\n return { contentId: payload.contentId, status: payload.status, url };\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { ProgressListener } from './types';\n\nconst HTTP_OK_MIN = 200;\nconst HTTP_OK_MAX_EXCLUSIVE = 300;\nexport const PERCENT_COMPLETE = 100;\n\n/** A fully built multipart upload, independent of the transport that sends it. */\nexport interface UploadRequest {\n url: string;\n /** Never contains Content-Type: the runtime sets the multipart boundary for a FormData body. */\n headers: Record<string, string>;\n form: FormData;\n credentials: RequestCredentials;\n signal: AbortSignal | undefined;\n}\n\nfunction isOk(status: number): boolean {\n return status >= HTTP_OK_MIN && status < HTTP_OK_MAX_EXCLUSIVE;\n}\n\nfunction httpError(status: number): UploadError {\n return new UploadError(UploadErrorKind.Http, `Upload failed (${String(status)}).`, status);\n}\n\nfunction abortedError(): UploadError {\n return new UploadError(UploadErrorKind.Aborted, 'Upload was cancelled.');\n}\n\n/** POST with fetch; resolves to the raw response text of a 2xx. */\nexport async function sendWithFetch(request: UploadRequest, fetchImpl: typeof fetch): Promise<string> {\n let response: Response;\n try {\n response = await fetchImpl(request.url, {\n method: 'POST',\n credentials: request.credentials,\n headers: request.headers,\n body: request.form,\n signal: request.signal,\n });\n } catch (cause) {\n if (request.signal?.aborted === true) {\n throw abortedError();\n }\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Network, detail);\n }\n if (!isOk(response.status)) {\n throw httpError(response.status);\n }\n return response.text();\n}\n\nfunction reportProgress(event: ProgressEvent, onProgress: ProgressListener): void {\n if (event.lengthComputable && event.total > 0) {\n onProgress(Math.round((event.loaded / event.total) * PERCENT_COMPLETE));\n }\n}\n\n/** POST with XMLHttpRequest so upload progress can be observed. */\nexport function sendWithXhr(\n request: UploadRequest,\n createXhr: () => XMLHttpRequest,\n onProgress: ProgressListener,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const { signal } = request;\n if (signal?.aborted === true) {\n reject(abortedError());\n return;\n }\n const xhr = createXhr();\n xhr.upload.addEventListener('progress', (event) => reportProgress(event, onProgress));\n xhr.addEventListener('load', () => {\n if (isOk(xhr.status)) {\n resolve(xhr.responseText);\n } else {\n reject(httpError(xhr.status));\n }\n });\n xhr.addEventListener('error', () => reject(new UploadError(UploadErrorKind.Network, 'Upload failed (network error).')));\n xhr.addEventListener('abort', () => reject(abortedError()));\n signal?.addEventListener('abort', () => xhr.abort(), { once: true });\n xhr.open('POST', request.url);\n xhr.withCredentials = request.credentials === 'include';\n Object.entries(request.headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(request.form);\n });\n}\n","import { parseUploadedContent } from './parseUploadedContent';\nimport { sendWithFetch, sendWithXhr } from './transports';\nimport { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadRequest } from './transports';\nimport type { CsrfHeader, UploadedContent, UploadImageOptions } from './types';\n\n/** The Bff.AspNetCore anti-forgery convention: header presence, any value. */\nexport const DEFAULT_CSRF_HEADER: CsrfHeader = { name: 'X-BFF-Csrf', value: '1' };\n\nconst DEFAULT_CATEGORY = 'Image';\nconst DEFAULT_FILE_NAME = 'upload';\nconst FILE_FIELD = 'File';\nconst CATEGORY_FIELD = 'Category';\nconst IS_PUBLIC_FIELD = 'IsPublic';\n\nfunction validationError(message: string): UploadError {\n return new UploadError(UploadErrorKind.Validation, message);\n}\n\n/** Client-side checks that must fail before a byte leaves the device. */\nfunction validate(file: Blob, options: UploadImageOptions): void {\n if (file.size === 0) {\n throw validationError('File is empty.');\n }\n if (options.maxBytes !== undefined && file.size > options.maxBytes) {\n throw validationError(`File is ${String(file.size)} bytes; the limit is ${String(options.maxBytes)}.`);\n }\n if (options.allowedTypes !== undefined && !options.allowedTypes.includes(file.type)) {\n throw validationError(`File type \"${file.type}\" is not allowed.`);\n }\n}\n\nfunction resolveFileName(file: Blob, explicit: string | undefined): string {\n if (explicit !== undefined && explicit !== '') {\n return explicit;\n }\n if ('name' in file && typeof file.name === 'string' && file.name !== '') {\n return file.name;\n }\n return DEFAULT_FILE_NAME;\n}\n\nfunction buildHeaders(csrf: CsrfHeader | null | undefined): Record<string, string> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n const header = csrf === undefined ? DEFAULT_CSRF_HEADER : csrf;\n if (header !== null) {\n headers[header.name] = header.value;\n }\n return headers;\n}\n\n/** Build the transport-independent request. Exported so consumers can pin the write shape. */\nexport function buildUploadRequest(file: Blob, options: UploadImageOptions): UploadRequest {\n const form = new FormData();\n form.append(FILE_FIELD, file, resolveFileName(file, options.fileName));\n form.append(CATEGORY_FIELD, options.category ?? DEFAULT_CATEGORY);\n form.append(IS_PUBLIC_FIELD, String(options.isPublic ?? true));\n return {\n url: options.endpoint,\n headers: buildHeaders(options.csrf),\n form,\n credentials: options.credentials ?? 'include',\n signal: options.signal,\n };\n}\n\nfunction resolveXhrFactory(options: UploadImageOptions): (() => XMLHttpRequest) | undefined {\n if (options.fetchImpl !== undefined) {\n return undefined;\n }\n if (options.xhrFactory !== undefined) {\n return options.xhrFactory;\n }\n return typeof XMLHttpRequest === 'undefined' ? undefined : (): XMLHttpRequest => new XMLHttpRequest();\n}\n\nasync function send(request: UploadRequest, options: UploadImageOptions): Promise<string> {\n const { onProgress } = options;\n const createXhr = onProgress === undefined ? undefined : resolveXhrFactory(options);\n if (createXhr !== undefined && onProgress !== undefined) {\n return sendWithXhr(request, createXhr, onProgress);\n }\n const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n return sendWithFetch(request, fetchImpl);\n}\n\n/**\n * Upload one image as multipart/form-data (`File`, `Category`, `IsPublic`) to a\n * consumer-supplied endpoint and return the parsed `{ contentId, status, url }`.\n *\n * Never sets Content-Type: the runtime adds the multipart boundary, and a JSON content type\n * on a FormData body is a 415 (see `@dloizides/bff-web-client` writeContentTypeGuard).\n *\n * @throws {UploadError} for every failure; switch on `error.kind`.\n */\nexport async function uploadImage(file: Blob, options: UploadImageOptions): Promise<UploadedContent> {\n validate(file, options);\n const request = buildUploadRequest(file, options);\n const text = await send(request, options);\n return parseUploadedContent(text, options.requireUrl ?? options.isPublic ?? true);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\n/**\n * Read a local URI (`blob:`, `data:`, or an RN image-picker `file:` URI) into a Blob so it\n * can be passed to `uploadImage`.\n *\n * @throws {UploadError} `Validation` when the URI cannot be read.\n */\nexport async function blobFromUri(uri: string, fetchImpl?: typeof fetch): Promise<Blob> {\n const doFetch = fetchImpl ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n response = await doFetch(uri);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Validation, `Could not read file: ${detail}`);\n }\n if (!response.ok) {\n throw new UploadError(UploadErrorKind.Validation, `Could not read file (${String(response.status)}).`);\n }\n return response.blob();\n}\n","/** Lifecycle of a single `useImageUpload` slot. */\nexport const enum UploadStatus {\n Idle = 'idle',\n Uploading = 'uploading',\n Error = 'error',\n Done = 'done',\n}\n","import { useCallback, useEffect, useReducer, useRef } from 'react';\n\nimport { PERCENT_COMPLETE } from './transports';\nimport { toUploadError } from './UploadError';\nimport { uploadImage } from './uploadImage';\nimport { UploadStatus } from './UploadStatus';\n\nimport type { UploadedContent, UploadImageOptions } from './types';\nimport type { UploadError } from './UploadError';\n\n/** Options for `useImageUpload`: everything `uploadImage` takes except the per-call wiring. */\nexport interface UseImageUploadOptions extends Omit<UploadImageOptions, 'signal' | 'onProgress'> {\n onSuccess?: (content: UploadedContent) => void;\n onError?: (error: UploadError) => void;\n}\n\nexport interface ImageUploadState {\n status: UploadStatus;\n /** 0-100. Stays 0 while uploading when the transport cannot report progress (fetch). */\n progress: number;\n error: UploadError | null;\n result: UploadedContent | null;\n}\n\nexport interface UseImageUploadResult extends ImageUploadState {\n /** Start an upload (aborting any in-flight one). Resolves to the content, or null on error/abort. */\n upload: (file: Blob, fileName?: string) => Promise<UploadedContent | null>;\n /** Abort any in-flight upload and return to idle. */\n reset: () => void;\n}\n\nconst IDLE: ImageUploadState = { status: UploadStatus.Idle, progress: 0, error: null, result: null };\nconst UPLOADING: ImageUploadState = { status: UploadStatus.Uploading, progress: 0, error: null, result: null };\n\ntype Action =\n | { type: 'start' }\n | { type: 'progress'; percent: number }\n | { type: 'done'; result: UploadedContent }\n | { type: 'fail'; error: UploadError }\n | { type: 'reset' };\n\nfunction reducer(state: ImageUploadState, action: Action): ImageUploadState {\n switch (action.type) {\n case 'start':\n return UPLOADING;\n case 'progress':\n return { ...state, progress: action.percent };\n case 'done':\n return { status: UploadStatus.Done, progress: PERCENT_COMPLETE, error: null, result: action.result };\n case 'fail':\n return { ...state, status: UploadStatus.Error, error: action.error };\n default:\n return IDLE;\n }\n}\n\n/**\n * One image-upload slot: idle -> uploading -> done | error. Progress is reported when the\n * XMLHttpRequest transport is available (browser, React Native) and no `fetchImpl` is set.\n * A newer `upload()` or `reset()` supersedes the previous request; its late result is dropped.\n * Unmount aborts the in-flight request.\n */\nexport function useImageUpload(options: UseImageUploadOptions): UseImageUploadResult {\n const [state, dispatch] = useReducer(reducer, IDLE);\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const controllerRef = useRef<AbortController | null>(null);\n const requestIdRef = useRef(0);\n\n const abortInFlight = useCallback((): void => {\n controllerRef.current?.abort();\n controllerRef.current = null;\n requestIdRef.current += 1;\n }, []);\n\n useEffect(() => abortInFlight, [abortInFlight]);\n\n const upload = useCallback(async (file: Blob, fileName?: string): Promise<UploadedContent | null> => {\n abortInFlight();\n const controller = new AbortController();\n controllerRef.current = controller;\n const requestId = requestIdRef.current;\n const isCurrent = (): boolean => requestId === requestIdRef.current;\n const { onSuccess, onError, ...uploadOptions } = optionsRef.current;\n dispatch({ type: 'start' });\n try {\n const result = await uploadImage(file, {\n ...uploadOptions,\n fileName: fileName ?? uploadOptions.fileName,\n signal: controller.signal,\n onProgress: (percent) => {\n if (isCurrent()) {\n dispatch({ type: 'progress', percent });\n }\n },\n });\n if (!isCurrent()) {\n return null;\n }\n dispatch({ type: 'done', result });\n onSuccess?.(result);\n return result;\n } catch (cause) {\n if (!isCurrent()) {\n return null;\n }\n const error = toUploadError(cause);\n dispatch({ type: 'fail', error });\n onError?.(error);\n return null;\n }\n }, [abortInFlight]);\n\n const reset = useCallback((): void => {\n abortInFlight();\n dispatch({ type: 'reset' });\n }, [abortInFlight]);\n\n return { ...state, upload, reset };\n}\n"]}
1
+ {"version":3,"sources":["../src/UploadErrorKind.ts","../src/UploadError.ts","../src/parseUploadedContent.ts","../src/transports.ts","../src/uploadImage.ts","../src/blobFromUri.ts","../src/UploadStatus.ts","../src/useImageUpload.ts"],"names":["UploadErrorKind","UploadStatus","useReducer","useRef","useCallback","useEffect"],"mappings":";;;;;AACO,IAAW,eAAA,qBAAAA,gBAAAA,KAAX;AAEL,EAAAA,iBAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,MAAA,CAAA,GAAO,MAAA;AAEP,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,iBAAA,CAAA,GAAkB,kBAAA;AAVF,EAAA,OAAAA,gBAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;;ACEX,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAKrC,WAAA,CAAY,IAAA,EAAuB,OAAA,EAAiB,MAAA,EAAiB;AACnE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAGO,SAAS,cAAc,KAAA,EAA6B;AACzD,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,OAAO,IAAI,qCAAqC,OAAO,CAAA;AACzD;;;AClBA,SAAS,SAA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S,EAAE,IAAA,EAAM,OAAA,EAAS,CAAA;AAAA,EAC5B,CAAA,EAAG,CAAC,aAAa,CAAC,CAAA;AAElB,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAM;AACnC","file":"index.js","sourcesContent":["/** Why an upload failed. Consumers map this to translated copy; `message` is developer-facing only. */\nexport const enum UploadErrorKind {\n /** Rejected client-side before any request: empty file, too large, disallowed MIME type. */\n Validation = 'validation',\n /** The request never produced an HTTP response (offline, DNS, CORS). */\n Network = 'network',\n /** The server answered outside 2xx; `status` carries the code. */\n Http = 'http',\n /** The caller aborted (AbortSignal / hook reset). */\n Aborted = 'aborted',\n /** 2xx, but the body was not `{ contentId, status?, url? }` (or lacked a required url). */\n InvalidResponse = 'invalid-response',\n}\n","import { UploadErrorKind } from './UploadErrorKind';\n\n/** The single error type thrown by `uploadImage` and surfaced by `useImageUpload`. */\nexport class UploadError extends Error {\n readonly kind: UploadErrorKind;\n /** HTTP status for `UploadErrorKind.Http`; undefined otherwise. */\n readonly status: number | undefined;\n\n constructor(kind: UploadErrorKind, message: string, status?: number) {\n super(message);\n this.name = 'UploadError';\n this.kind = kind;\n this.status = status;\n }\n}\n\n/** Normalise anything thrown into an `UploadError` (unknown throws become `Network`). */\nexport function toUploadError(cause: unknown): UploadError {\n if (cause instanceof UploadError) {\n return cause;\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new UploadError(UploadErrorKind.Network, message);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadedContent } from './types';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(message: string): UploadError {\n return new UploadError(UploadErrorKind.InvalidResponse, message);\n}\n\n/** Parse the upload endpoint's JSON body into `UploadedContent`, or throw `InvalidResponse`. */\nexport function parseUploadedContent(text: string, requireUrl: boolean): UploadedContent {\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch {\n throw invalid('Upload response was not JSON.');\n }\n // `status` is optional: ContentService sends it, the Dloizides.Content.Upload.AspNetCore\n // proxy (`ContentUploadResponse(ContentId, Url)`) does not. Present-but-not-a-string is still malformed.\n const hasBadStatus = isRecord(payload) && payload.status !== undefined && typeof payload.status !== 'string';\n if (!isRecord(payload) || typeof payload.contentId !== 'string' || hasBadStatus) {\n throw invalid('Upload response shape was invalid.');\n }\n const status = typeof payload.status === 'string' ? payload.status : undefined;\n const url = typeof payload.url === 'string' && payload.url !== '' ? payload.url : undefined;\n if (requireUrl && url === undefined) {\n throw invalid('Upload response did not include a public URL.');\n }\n return { contentId: payload.contentId, status, url };\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { ProgressListener } from './types';\n\nconst HTTP_OK_MIN = 200;\nconst HTTP_OK_MAX_EXCLUSIVE = 300;\nexport const PERCENT_COMPLETE = 100;\n\n/** A fully built multipart upload, independent of the transport that sends it. */\nexport interface UploadRequest {\n url: string;\n /** Never contains Content-Type: the runtime sets the multipart boundary for a FormData body. */\n headers: Record<string, string>;\n form: FormData;\n credentials: RequestCredentials;\n signal: AbortSignal | undefined;\n}\n\nfunction isOk(status: number): boolean {\n return status >= HTTP_OK_MIN && status < HTTP_OK_MAX_EXCLUSIVE;\n}\n\nfunction httpError(status: number): UploadError {\n return new UploadError(UploadErrorKind.Http, `Upload failed (${String(status)}).`, status);\n}\n\nfunction abortedError(): UploadError {\n return new UploadError(UploadErrorKind.Aborted, 'Upload was cancelled.');\n}\n\n/** POST with fetch; resolves to the raw response text of a 2xx. */\nexport async function sendWithFetch(request: UploadRequest, fetchImpl: typeof fetch): Promise<string> {\n let response: Response;\n try {\n response = await fetchImpl(request.url, {\n method: 'POST',\n credentials: request.credentials,\n headers: request.headers,\n body: request.form,\n signal: request.signal,\n });\n } catch (cause) {\n if (request.signal?.aborted === true) {\n throw abortedError();\n }\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Network, detail);\n }\n if (!isOk(response.status)) {\n throw httpError(response.status);\n }\n return response.text();\n}\n\nfunction reportProgress(event: ProgressEvent, onProgress: ProgressListener): void {\n if (event.lengthComputable && event.total > 0) {\n onProgress(Math.round((event.loaded / event.total) * PERCENT_COMPLETE));\n }\n}\n\n/** POST with XMLHttpRequest so upload progress can be observed. */\nexport function sendWithXhr(\n request: UploadRequest,\n createXhr: () => XMLHttpRequest,\n onProgress: ProgressListener,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const { signal } = request;\n if (signal?.aborted === true) {\n reject(abortedError());\n return;\n }\n const xhr = createXhr();\n xhr.upload.addEventListener('progress', (event) => reportProgress(event, onProgress));\n xhr.addEventListener('load', () => {\n if (isOk(xhr.status)) {\n resolve(xhr.responseText);\n } else {\n reject(httpError(xhr.status));\n }\n });\n xhr.addEventListener('error', () => reject(new UploadError(UploadErrorKind.Network, 'Upload failed (network error).')));\n xhr.addEventListener('abort', () => reject(abortedError()));\n signal?.addEventListener('abort', () => xhr.abort(), { once: true });\n xhr.open('POST', request.url);\n xhr.withCredentials = request.credentials === 'include';\n Object.entries(request.headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(request.form);\n });\n}\n","import { parseUploadedContent } from './parseUploadedContent';\nimport { sendWithFetch, sendWithXhr } from './transports';\nimport { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadRequest } from './transports';\nimport type { CsrfHeader, UploadedContent, UploadImageOptions } from './types';\n\n/** The Bff.AspNetCore anti-forgery convention: header presence, any value. */\nexport const DEFAULT_CSRF_HEADER: CsrfHeader = { name: 'X-BFF-Csrf', value: '1' };\n\nconst DEFAULT_CATEGORY = 'Image';\nconst DEFAULT_FILE_NAME = 'upload';\nconst FILE_FIELD = 'File';\nconst CATEGORY_FIELD = 'Category';\nconst IS_PUBLIC_FIELD = 'IsPublic';\n\nfunction validationError(message: string): UploadError {\n return new UploadError(UploadErrorKind.Validation, message);\n}\n\n/** Client-side checks that must fail before a byte leaves the device. */\nfunction validate(file: Blob, options: UploadImageOptions): void {\n if (file.size === 0) {\n throw validationError('File is empty.');\n }\n if (options.maxBytes !== undefined && file.size > options.maxBytes) {\n throw validationError(`File is ${String(file.size)} bytes; the limit is ${String(options.maxBytes)}.`);\n }\n if (options.allowedTypes !== undefined && !options.allowedTypes.includes(file.type)) {\n throw validationError(`File type \"${file.type}\" is not allowed.`);\n }\n}\n\nfunction resolveFileName(file: Blob, explicit: string | undefined): string {\n if (explicit !== undefined && explicit !== '') {\n return explicit;\n }\n if ('name' in file && typeof file.name === 'string' && file.name !== '') {\n return file.name;\n }\n return DEFAULT_FILE_NAME;\n}\n\nfunction buildHeaders(csrf: CsrfHeader | null | undefined): Record<string, string> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n const header = csrf === undefined ? DEFAULT_CSRF_HEADER : csrf;\n if (header !== null) {\n headers[header.name] = header.value;\n }\n return headers;\n}\n\n/** Build the transport-independent request. Exported so consumers can pin the write shape. */\nexport function buildUploadRequest(file: Blob, options: UploadImageOptions): UploadRequest {\n const form = new FormData();\n form.append(FILE_FIELD, file, resolveFileName(file, options.fileName));\n form.append(CATEGORY_FIELD, options.category ?? DEFAULT_CATEGORY);\n form.append(IS_PUBLIC_FIELD, String(options.isPublic ?? true));\n return {\n url: options.endpoint,\n headers: buildHeaders(options.csrf),\n form,\n credentials: options.credentials ?? 'include',\n signal: options.signal,\n };\n}\n\nfunction resolveXhrFactory(options: UploadImageOptions): (() => XMLHttpRequest) | undefined {\n if (options.fetchImpl !== undefined) {\n return undefined;\n }\n if (options.xhrFactory !== undefined) {\n return options.xhrFactory;\n }\n return typeof XMLHttpRequest === 'undefined' ? undefined : (): XMLHttpRequest => new XMLHttpRequest();\n}\n\nasync function send(request: UploadRequest, options: UploadImageOptions): Promise<string> {\n const { onProgress } = options;\n const createXhr = onProgress === undefined ? undefined : resolveXhrFactory(options);\n if (createXhr !== undefined && onProgress !== undefined) {\n return sendWithXhr(request, createXhr, onProgress);\n }\n const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n return sendWithFetch(request, fetchImpl);\n}\n\n/**\n * Upload one image as multipart/form-data (`File`, `Category`, `IsPublic`) to a\n * consumer-supplied endpoint and return the parsed `{ contentId, status?, url }`.\n *\n * Never sets Content-Type: the runtime adds the multipart boundary, and a JSON content type\n * on a FormData body is a 415 (see `@dloizides/bff-web-client` writeContentTypeGuard).\n *\n * @throws {UploadError} for every failure; switch on `error.kind`.\n */\nexport async function uploadImage(file: Blob, options: UploadImageOptions): Promise<UploadedContent> {\n validate(file, options);\n const request = buildUploadRequest(file, options);\n const text = await send(request, options);\n return parseUploadedContent(text, options.requireUrl ?? options.isPublic ?? true);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\n/**\n * Read a local URI (`blob:`, `data:`, or an RN image-picker `file:` URI) into a Blob so it\n * can be passed to `uploadImage`.\n *\n * @throws {UploadError} `Validation` when the URI cannot be read.\n */\nexport async function blobFromUri(uri: string, fetchImpl?: typeof fetch): Promise<Blob> {\n const doFetch = fetchImpl ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n response = await doFetch(uri);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Validation, `Could not read file: ${detail}`);\n }\n if (!response.ok) {\n throw new UploadError(UploadErrorKind.Validation, `Could not read file (${String(response.status)}).`);\n }\n return response.blob();\n}\n","/** Lifecycle of a single `useImageUpload` slot. */\nexport const enum UploadStatus {\n Idle = 'idle',\n Uploading = 'uploading',\n Error = 'error',\n Done = 'done',\n}\n","import { useCallback, useEffect, useReducer, useRef } from 'react';\n\nimport { PERCENT_COMPLETE } from './transports';\nimport { toUploadError } from './UploadError';\nimport { uploadImage } from './uploadImage';\nimport { UploadStatus } from './UploadStatus';\n\nimport type { UploadedContent, UploadImageOptions } from './types';\nimport type { UploadError } from './UploadError';\n\n/** Options for `useImageUpload`: everything `uploadImage` takes except the per-call wiring. */\nexport interface UseImageUploadOptions extends Omit<UploadImageOptions, 'signal' | 'onProgress'> {\n onSuccess?: (content: UploadedContent) => void;\n onError?: (error: UploadError) => void;\n}\n\nexport interface ImageUploadState {\n status: UploadStatus;\n /** 0-100. Stays 0 while uploading when the transport cannot report progress (fetch). */\n progress: number;\n error: UploadError | null;\n result: UploadedContent | null;\n}\n\nexport interface UseImageUploadResult extends ImageUploadState {\n /** Start an upload (aborting any in-flight one). Resolves to the content, or null on error/abort. */\n upload: (file: Blob, fileName?: string) => Promise<UploadedContent | null>;\n /** Abort any in-flight upload and return to idle. */\n reset: () => void;\n}\n\nconst IDLE: ImageUploadState = { status: UploadStatus.Idle, progress: 0, error: null, result: null };\nconst UPLOADING: ImageUploadState = { status: UploadStatus.Uploading, progress: 0, error: null, result: null };\n\ntype Action =\n | { type: 'start' }\n | { type: 'progress'; percent: number }\n | { type: 'done'; result: UploadedContent }\n | { type: 'fail'; error: UploadError }\n | { type: 'reset' };\n\nfunction reducer(state: ImageUploadState, action: Action): ImageUploadState {\n switch (action.type) {\n case 'start':\n return UPLOADING;\n case 'progress':\n return { ...state, progress: action.percent };\n case 'done':\n return { status: UploadStatus.Done, progress: PERCENT_COMPLETE, error: null, result: action.result };\n case 'fail':\n return { ...state, status: UploadStatus.Error, error: action.error };\n default:\n return IDLE;\n }\n}\n\n/**\n * One image-upload slot: idle -> uploading -> done | error. Progress is reported when the\n * XMLHttpRequest transport is available (browser, React Native) and no `fetchImpl` is set.\n * A newer `upload()` or `reset()` supersedes the previous request; its late result is dropped.\n * Unmount aborts the in-flight request.\n */\nexport function useImageUpload(options: UseImageUploadOptions): UseImageUploadResult {\n const [state, dispatch] = useReducer(reducer, IDLE);\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const controllerRef = useRef<AbortController | null>(null);\n const requestIdRef = useRef(0);\n\n const abortInFlight = useCallback((): void => {\n controllerRef.current?.abort();\n controllerRef.current = null;\n requestIdRef.current += 1;\n }, []);\n\n useEffect(() => abortInFlight, [abortInFlight]);\n\n const upload = useCallback(async (file: Blob, fileName?: string): Promise<UploadedContent | null> => {\n abortInFlight();\n const controller = new AbortController();\n controllerRef.current = controller;\n const requestId = requestIdRef.current;\n const isCurrent = (): boolean => requestId === requestIdRef.current;\n const { onSuccess, onError, ...uploadOptions } = optionsRef.current;\n dispatch({ type: 'start' });\n try {\n const result = await uploadImage(file, {\n ...uploadOptions,\n fileName: fileName ?? uploadOptions.fileName,\n signal: controller.signal,\n onProgress: (percent) => {\n if (isCurrent()) {\n dispatch({ type: 'progress', percent });\n }\n },\n });\n if (!isCurrent()) {\n return null;\n }\n dispatch({ type: 'done', result });\n onSuccess?.(result);\n return result;\n } catch (cause) {\n if (!isCurrent()) {\n return null;\n }\n const error = toUploadError(cause);\n dispatch({ type: 'fail', error });\n onError?.(error);\n return null;\n }\n }, [abortInFlight]);\n\n const reset = useCallback((): void => {\n abortInFlight();\n dispatch({ type: 'reset' });\n }, [abortInFlight]);\n\n return { ...state, upload, reset };\n}\n"]}
package/dist/index.mjs CHANGED
@@ -41,14 +41,16 @@ function parseUploadedContent(text, requireUrl) {
41
41
  } catch {
42
42
  throw invalid("Upload response was not JSON.");
43
43
  }
44
- if (!isRecord(payload) || typeof payload.contentId !== "string" || typeof payload.status !== "string") {
44
+ const hasBadStatus = isRecord(payload) && payload.status !== void 0 && typeof payload.status !== "string";
45
+ if (!isRecord(payload) || typeof payload.contentId !== "string" || hasBadStatus) {
45
46
  throw invalid("Upload response shape was invalid.");
46
47
  }
48
+ const status = typeof payload.status === "string" ? payload.status : void 0;
47
49
  const url = typeof payload.url === "string" && payload.url !== "" ? payload.url : void 0;
48
50
  if (requireUrl && url === void 0) {
49
51
  throw invalid("Upload response did not include a public URL.");
50
52
  }
51
- return { contentId: payload.contentId, status: payload.status, url };
53
+ return { contentId: payload.contentId, status, url };
52
54
  }
53
55
 
54
56
  // src/transports.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/UploadErrorKind.ts","../src/UploadError.ts","../src/parseUploadedContent.ts","../src/transports.ts","../src/uploadImage.ts","../src/blobFromUri.ts","../src/UploadStatus.ts","../src/useImageUpload.ts"],"names":["UploadErrorKind","UploadStatus"],"mappings":";;;AACO,IAAW,eAAA,qBAAAA,gBAAAA,KAAX;AAEL,EAAAA,iBAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,MAAA,CAAA,GAAO,MAAA;AAEP,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,iBAAA,CAAA,GAAkB,kBAAA;AAVF,EAAA,OAAAA,gBAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;;ACEX,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAKrC,WAAA,CAAY,IAAA,EAAuB,OAAA,EAAiB,MAAA,EAAiB;AACnE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAGO,SAAS,cAAc,KAAA,EAA6B;AACzD,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,OAAO,IAAI,qCAAqC,OAAO,CAAA;AACzD;;;AClBA,SAAS,SAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAEA,SAAS,QAAQ,OAAA,EAA8B;AAC7C,EAAA,OAA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AAAA,QACH,QAAA,EAAU,YAAY,aAAA,CAAc,QAAA;AAAA,QACpC,QAAQ,UAAA,CAAW,MAAA;AAAA,QACnB,UAAA,EAAY,CAAC,OAAA,KAAY;AACvB,UAAA,IAAI,WAAU,EAAG;AACf,YAAA,QAAA,CAAS,EAAE,IAAA,EAAM,UAAA,EAAY,OAAA,EAAS,CAAA;AAAA,UACxC;AAAA,QACF;AAAA,OACD,CAAA;AACD,MAAA,IAAI,CAAC,WAAU,EAAG;AAChB,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,CAAA;AACjC,MAAA,SAAA,GAAY,MAAM,CAAA;AAClB,MAAA,OAAO,MAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,CAAC,WAAU,EAAG;AAChB,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,MAAM,KAAA,GAAQ,cAAc,KAAK,CAAA;AACjC,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,KAAA,EAAO,CAAA;AAChC,MAAA,OAAA,GAAU,KAAK,CAAA;AACf,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF,CAAA,EAAG,CAAC,aAAa,CAAC,CAAA;AAElB,EAAA,MAAM,KAAA,GAAQ,YAAY,MAAY;AACpC,IAAA,aAAA,EAAc;AACd,IAAA,QAAA,CAAS,EAAE,IAAA,EAAM,OAAA,EAAS,CAAA;AAAA,EAC5B,CAAA,EAAG,CAAC,aAAa,CAAC,CAAA;AAElB,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAM;AACnC","file":"index.mjs","sourcesContent":["/** Why an upload failed. Consumers map this to translated copy; `message` is developer-facing only. */\nexport const enum UploadErrorKind {\n /** Rejected client-side before any request: empty file, too large, disallowed MIME type. */\n Validation = 'validation',\n /** The request never produced an HTTP response (offline, DNS, CORS). */\n Network = 'network',\n /** The server answered outside 2xx; `status` carries the code. */\n Http = 'http',\n /** The caller aborted (AbortSignal / hook reset). */\n Aborted = 'aborted',\n /** 2xx, but the body was not `{ contentId, status, url? }` (or lacked a required url). */\n InvalidResponse = 'invalid-response',\n}\n","import { UploadErrorKind } from './UploadErrorKind';\n\n/** The single error type thrown by `uploadImage` and surfaced by `useImageUpload`. */\nexport class UploadError extends Error {\n readonly kind: UploadErrorKind;\n /** HTTP status for `UploadErrorKind.Http`; undefined otherwise. */\n readonly status: number | undefined;\n\n constructor(kind: UploadErrorKind, message: string, status?: number) {\n super(message);\n this.name = 'UploadError';\n this.kind = kind;\n this.status = status;\n }\n}\n\n/** Normalise anything thrown into an `UploadError` (unknown throws become `Network`). */\nexport function toUploadError(cause: unknown): UploadError {\n if (cause instanceof UploadError) {\n return cause;\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new UploadError(UploadErrorKind.Network, message);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadedContent } from './types';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(message: string): UploadError {\n return new UploadError(UploadErrorKind.InvalidResponse, message);\n}\n\n/** Parse the upload endpoint's JSON body into `UploadedContent`, or throw `InvalidResponse`. */\nexport function parseUploadedContent(text: string, requireUrl: boolean): UploadedContent {\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch {\n throw invalid('Upload response was not JSON.');\n }\n if (!isRecord(payload) || typeof payload.contentId !== 'string' || typeof payload.status !== 'string') {\n throw invalid('Upload response shape was invalid.');\n }\n const url = typeof payload.url === 'string' && payload.url !== '' ? payload.url : undefined;\n if (requireUrl && url === undefined) {\n throw invalid('Upload response did not include a public URL.');\n }\n return { contentId: payload.contentId, status: payload.status, url };\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { ProgressListener } from './types';\n\nconst HTTP_OK_MIN = 200;\nconst HTTP_OK_MAX_EXCLUSIVE = 300;\nexport const PERCENT_COMPLETE = 100;\n\n/** A fully built multipart upload, independent of the transport that sends it. */\nexport interface UploadRequest {\n url: string;\n /** Never contains Content-Type: the runtime sets the multipart boundary for a FormData body. */\n headers: Record<string, string>;\n form: FormData;\n credentials: RequestCredentials;\n signal: AbortSignal | undefined;\n}\n\nfunction isOk(status: number): boolean {\n return status >= HTTP_OK_MIN && status < HTTP_OK_MAX_EXCLUSIVE;\n}\n\nfunction httpError(status: number): UploadError {\n return new UploadError(UploadErrorKind.Http, `Upload failed (${String(status)}).`, status);\n}\n\nfunction abortedError(): UploadError {\n return new UploadError(UploadErrorKind.Aborted, 'Upload was cancelled.');\n}\n\n/** POST with fetch; resolves to the raw response text of a 2xx. */\nexport async function sendWithFetch(request: UploadRequest, fetchImpl: typeof fetch): Promise<string> {\n let response: Response;\n try {\n response = await fetchImpl(request.url, {\n method: 'POST',\n credentials: request.credentials,\n headers: request.headers,\n body: request.form,\n signal: request.signal,\n });\n } catch (cause) {\n if (request.signal?.aborted === true) {\n throw abortedError();\n }\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Network, detail);\n }\n if (!isOk(response.status)) {\n throw httpError(response.status);\n }\n return response.text();\n}\n\nfunction reportProgress(event: ProgressEvent, onProgress: ProgressListener): void {\n if (event.lengthComputable && event.total > 0) {\n onProgress(Math.round((event.loaded / event.total) * PERCENT_COMPLETE));\n }\n}\n\n/** POST with XMLHttpRequest so upload progress can be observed. */\nexport function sendWithXhr(\n request: UploadRequest,\n createXhr: () => XMLHttpRequest,\n onProgress: ProgressListener,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const { signal } = request;\n if (signal?.aborted === true) {\n reject(abortedError());\n return;\n }\n const xhr = createXhr();\n xhr.upload.addEventListener('progress', (event) => reportProgress(event, onProgress));\n xhr.addEventListener('load', () => {\n if (isOk(xhr.status)) {\n resolve(xhr.responseText);\n } else {\n reject(httpError(xhr.status));\n }\n });\n xhr.addEventListener('error', () => reject(new UploadError(UploadErrorKind.Network, 'Upload failed (network error).')));\n xhr.addEventListener('abort', () => reject(abortedError()));\n signal?.addEventListener('abort', () => xhr.abort(), { once: true });\n xhr.open('POST', request.url);\n xhr.withCredentials = request.credentials === 'include';\n Object.entries(request.headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(request.form);\n });\n}\n","import { parseUploadedContent } from './parseUploadedContent';\nimport { sendWithFetch, sendWithXhr } from './transports';\nimport { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadRequest } from './transports';\nimport type { CsrfHeader, UploadedContent, UploadImageOptions } from './types';\n\n/** The Bff.AspNetCore anti-forgery convention: header presence, any value. */\nexport const DEFAULT_CSRF_HEADER: CsrfHeader = { name: 'X-BFF-Csrf', value: '1' };\n\nconst DEFAULT_CATEGORY = 'Image';\nconst DEFAULT_FILE_NAME = 'upload';\nconst FILE_FIELD = 'File';\nconst CATEGORY_FIELD = 'Category';\nconst IS_PUBLIC_FIELD = 'IsPublic';\n\nfunction validationError(message: string): UploadError {\n return new UploadError(UploadErrorKind.Validation, message);\n}\n\n/** Client-side checks that must fail before a byte leaves the device. */\nfunction validate(file: Blob, options: UploadImageOptions): void {\n if (file.size === 0) {\n throw validationError('File is empty.');\n }\n if (options.maxBytes !== undefined && file.size > options.maxBytes) {\n throw validationError(`File is ${String(file.size)} bytes; the limit is ${String(options.maxBytes)}.`);\n }\n if (options.allowedTypes !== undefined && !options.allowedTypes.includes(file.type)) {\n throw validationError(`File type \"${file.type}\" is not allowed.`);\n }\n}\n\nfunction resolveFileName(file: Blob, explicit: string | undefined): string {\n if (explicit !== undefined && explicit !== '') {\n return explicit;\n }\n if ('name' in file && typeof file.name === 'string' && file.name !== '') {\n return file.name;\n }\n return DEFAULT_FILE_NAME;\n}\n\nfunction buildHeaders(csrf: CsrfHeader | null | undefined): Record<string, string> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n const header = csrf === undefined ? DEFAULT_CSRF_HEADER : csrf;\n if (header !== null) {\n headers[header.name] = header.value;\n }\n return headers;\n}\n\n/** Build the transport-independent request. Exported so consumers can pin the write shape. */\nexport function buildUploadRequest(file: Blob, options: UploadImageOptions): UploadRequest {\n const form = new FormData();\n form.append(FILE_FIELD, file, resolveFileName(file, options.fileName));\n form.append(CATEGORY_FIELD, options.category ?? DEFAULT_CATEGORY);\n form.append(IS_PUBLIC_FIELD, String(options.isPublic ?? true));\n return {\n url: options.endpoint,\n headers: buildHeaders(options.csrf),\n form,\n credentials: options.credentials ?? 'include',\n signal: options.signal,\n };\n}\n\nfunction resolveXhrFactory(options: UploadImageOptions): (() => XMLHttpRequest) | undefined {\n if (options.fetchImpl !== undefined) {\n return undefined;\n }\n if (options.xhrFactory !== undefined) {\n return options.xhrFactory;\n }\n return typeof XMLHttpRequest === 'undefined' ? undefined : (): XMLHttpRequest => new XMLHttpRequest();\n}\n\nasync function send(request: UploadRequest, options: UploadImageOptions): Promise<string> {\n const { onProgress } = options;\n const createXhr = onProgress === undefined ? undefined : resolveXhrFactory(options);\n if (createXhr !== undefined && onProgress !== undefined) {\n return sendWithXhr(request, createXhr, onProgress);\n }\n const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n return sendWithFetch(request, fetchImpl);\n}\n\n/**\n * Upload one image as multipart/form-data (`File`, `Category`, `IsPublic`) to a\n * consumer-supplied endpoint and return the parsed `{ contentId, status, url }`.\n *\n * Never sets Content-Type: the runtime adds the multipart boundary, and a JSON content type\n * on a FormData body is a 415 (see `@dloizides/bff-web-client` writeContentTypeGuard).\n *\n * @throws {UploadError} for every failure; switch on `error.kind`.\n */\nexport async function uploadImage(file: Blob, options: UploadImageOptions): Promise<UploadedContent> {\n validate(file, options);\n const request = buildUploadRequest(file, options);\n const text = await send(request, options);\n return parseUploadedContent(text, options.requireUrl ?? options.isPublic ?? true);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\n/**\n * Read a local URI (`blob:`, `data:`, or an RN image-picker `file:` URI) into a Blob so it\n * can be passed to `uploadImage`.\n *\n * @throws {UploadError} `Validation` when the URI cannot be read.\n */\nexport async function blobFromUri(uri: string, fetchImpl?: typeof fetch): Promise<Blob> {\n const doFetch = fetchImpl ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n response = await doFetch(uri);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Validation, `Could not read file: ${detail}`);\n }\n if (!response.ok) {\n throw new UploadError(UploadErrorKind.Validation, `Could not read file (${String(response.status)}).`);\n }\n return response.blob();\n}\n","/** Lifecycle of a single `useImageUpload` slot. */\nexport const enum UploadStatus {\n Idle = 'idle',\n Uploading = 'uploading',\n Error = 'error',\n Done = 'done',\n}\n","import { useCallback, useEffect, useReducer, useRef } from 'react';\n\nimport { PERCENT_COMPLETE } from './transports';\nimport { toUploadError } from './UploadError';\nimport { uploadImage } from './uploadImage';\nimport { UploadStatus } from './UploadStatus';\n\nimport type { UploadedContent, UploadImageOptions } from './types';\nimport type { UploadError } from './UploadError';\n\n/** Options for `useImageUpload`: everything `uploadImage` takes except the per-call wiring. */\nexport interface UseImageUploadOptions extends Omit<UploadImageOptions, 'signal' | 'onProgress'> {\n onSuccess?: (content: UploadedContent) => void;\n onError?: (error: UploadError) => void;\n}\n\nexport interface ImageUploadState {\n status: UploadStatus;\n /** 0-100. Stays 0 while uploading when the transport cannot report progress (fetch). */\n progress: number;\n error: UploadError | null;\n result: UploadedContent | null;\n}\n\nexport interface UseImageUploadResult extends ImageUploadState {\n /** Start an upload (aborting any in-flight one). Resolves to the content, or null on error/abort. */\n upload: (file: Blob, fileName?: string) => Promise<UploadedContent | null>;\n /** Abort any in-flight upload and return to idle. */\n reset: () => void;\n}\n\nconst IDLE: ImageUploadState = { status: UploadStatus.Idle, progress: 0, error: null, result: null };\nconst UPLOADING: ImageUploadState = { status: UploadStatus.Uploading, progress: 0, error: null, result: null };\n\ntype Action =\n | { type: 'start' }\n | { type: 'progress'; percent: number }\n | { type: 'done'; result: UploadedContent }\n | { type: 'fail'; error: UploadError }\n | { type: 'reset' };\n\nfunction reducer(state: ImageUploadState, action: Action): ImageUploadState {\n switch (action.type) {\n case 'start':\n return UPLOADING;\n case 'progress':\n return { ...state, progress: action.percent };\n case 'done':\n return { status: UploadStatus.Done, progress: PERCENT_COMPLETE, error: null, result: action.result };\n case 'fail':\n return { ...state, status: UploadStatus.Error, error: action.error };\n default:\n return IDLE;\n }\n}\n\n/**\n * One image-upload slot: idle -> uploading -> done | error. Progress is reported when the\n * XMLHttpRequest transport is available (browser, React Native) and no `fetchImpl` is set.\n * A newer `upload()` or `reset()` supersedes the previous request; its late result is dropped.\n * Unmount aborts the in-flight request.\n */\nexport function useImageUpload(options: UseImageUploadOptions): UseImageUploadResult {\n const [state, dispatch] = useReducer(reducer, IDLE);\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const controllerRef = useRef<AbortController | null>(null);\n const requestIdRef = useRef(0);\n\n const abortInFlight = useCallback((): void => {\n controllerRef.current?.abort();\n controllerRef.current = null;\n requestIdRef.current += 1;\n }, []);\n\n useEffect(() => abortInFlight, [abortInFlight]);\n\n const upload = useCallback(async (file: Blob, fileName?: string): Promise<UploadedContent | null> => {\n abortInFlight();\n const controller = new AbortController();\n controllerRef.current = controller;\n const requestId = requestIdRef.current;\n const isCurrent = (): boolean => requestId === requestIdRef.current;\n const { onSuccess, onError, ...uploadOptions } = optionsRef.current;\n dispatch({ type: 'start' });\n try {\n const result = await uploadImage(file, {\n ...uploadOptions,\n fileName: fileName ?? uploadOptions.fileName,\n signal: controller.signal,\n onProgress: (percent) => {\n if (isCurrent()) {\n dispatch({ type: 'progress', percent });\n }\n },\n });\n if (!isCurrent()) {\n return null;\n }\n dispatch({ type: 'done', result });\n onSuccess?.(result);\n return result;\n } catch (cause) {\n if (!isCurrent()) {\n return null;\n }\n const error = toUploadError(cause);\n dispatch({ type: 'fail', error });\n onError?.(error);\n return null;\n }\n }, [abortInFlight]);\n\n const reset = useCallback((): void => {\n abortInFlight();\n dispatch({ type: 'reset' });\n }, [abortInFlight]);\n\n return { ...state, upload, reset };\n}\n"]}
1
+ {"version":3,"sources":["../src/UploadErrorKind.ts","../src/UploadError.ts","../src/parseUploadedContent.ts","../src/transports.ts","../src/uploadImage.ts","../src/blobFromUri.ts","../src/UploadStatus.ts","../src/useImageUpload.ts"],"names":["UploadErrorKind","UploadStatus"],"mappings":";;;AACO,IAAW,eAAA,qBAAAA,gBAAAA,KAAX;AAEL,EAAAA,iBAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,MAAA,CAAA,GAAO,MAAA;AAEP,EAAAA,iBAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,iBAAA,iBAAA,CAAA,GAAkB,kBAAA;AAVF,EAAA,OAAAA,gBAAAA;AAAA,CAAA,EAAA,eAAA,IAAA,EAAA;;;ACEX,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAKrC,WAAA,CAAY,IAAA,EAAuB,OAAA,EAAiB,MAAA,EAAiB;AACnE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAGO,SAAS,cAAc,KAAA,EAA6B;AACzD,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,OAAO,IAAI,qCAAqC,OAAO,CAAA;AACzD;;;AClBA,SAAS,SAAS,KAAA,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OAAA,EAAS,CAAA;AAAA,EAC5B,CAAA,EAAG,CAAC,aAAa,CAAC,CAAA;AAElB,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAM;AACnC","file":"index.mjs","sourcesContent":["/** Why an upload failed. Consumers map this to translated copy; `message` is developer-facing only. */\nexport const enum UploadErrorKind {\n /** Rejected client-side before any request: empty file, too large, disallowed MIME type. */\n Validation = 'validation',\n /** The request never produced an HTTP response (offline, DNS, CORS). */\n Network = 'network',\n /** The server answered outside 2xx; `status` carries the code. */\n Http = 'http',\n /** The caller aborted (AbortSignal / hook reset). */\n Aborted = 'aborted',\n /** 2xx, but the body was not `{ contentId, status?, url? }` (or lacked a required url). */\n InvalidResponse = 'invalid-response',\n}\n","import { UploadErrorKind } from './UploadErrorKind';\n\n/** The single error type thrown by `uploadImage` and surfaced by `useImageUpload`. */\nexport class UploadError extends Error {\n readonly kind: UploadErrorKind;\n /** HTTP status for `UploadErrorKind.Http`; undefined otherwise. */\n readonly status: number | undefined;\n\n constructor(kind: UploadErrorKind, message: string, status?: number) {\n super(message);\n this.name = 'UploadError';\n this.kind = kind;\n this.status = status;\n }\n}\n\n/** Normalise anything thrown into an `UploadError` (unknown throws become `Network`). */\nexport function toUploadError(cause: unknown): UploadError {\n if (cause instanceof UploadError) {\n return cause;\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new UploadError(UploadErrorKind.Network, message);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadedContent } from './types';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(message: string): UploadError {\n return new UploadError(UploadErrorKind.InvalidResponse, message);\n}\n\n/** Parse the upload endpoint's JSON body into `UploadedContent`, or throw `InvalidResponse`. */\nexport function parseUploadedContent(text: string, requireUrl: boolean): UploadedContent {\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch {\n throw invalid('Upload response was not JSON.');\n }\n // `status` is optional: ContentService sends it, the Dloizides.Content.Upload.AspNetCore\n // proxy (`ContentUploadResponse(ContentId, Url)`) does not. Present-but-not-a-string is still malformed.\n const hasBadStatus = isRecord(payload) && payload.status !== undefined && typeof payload.status !== 'string';\n if (!isRecord(payload) || typeof payload.contentId !== 'string' || hasBadStatus) {\n throw invalid('Upload response shape was invalid.');\n }\n const status = typeof payload.status === 'string' ? payload.status : undefined;\n const url = typeof payload.url === 'string' && payload.url !== '' ? payload.url : undefined;\n if (requireUrl && url === undefined) {\n throw invalid('Upload response did not include a public URL.');\n }\n return { contentId: payload.contentId, status, url };\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { ProgressListener } from './types';\n\nconst HTTP_OK_MIN = 200;\nconst HTTP_OK_MAX_EXCLUSIVE = 300;\nexport const PERCENT_COMPLETE = 100;\n\n/** A fully built multipart upload, independent of the transport that sends it. */\nexport interface UploadRequest {\n url: string;\n /** Never contains Content-Type: the runtime sets the multipart boundary for a FormData body. */\n headers: Record<string, string>;\n form: FormData;\n credentials: RequestCredentials;\n signal: AbortSignal | undefined;\n}\n\nfunction isOk(status: number): boolean {\n return status >= HTTP_OK_MIN && status < HTTP_OK_MAX_EXCLUSIVE;\n}\n\nfunction httpError(status: number): UploadError {\n return new UploadError(UploadErrorKind.Http, `Upload failed (${String(status)}).`, status);\n}\n\nfunction abortedError(): UploadError {\n return new UploadError(UploadErrorKind.Aborted, 'Upload was cancelled.');\n}\n\n/** POST with fetch; resolves to the raw response text of a 2xx. */\nexport async function sendWithFetch(request: UploadRequest, fetchImpl: typeof fetch): Promise<string> {\n let response: Response;\n try {\n response = await fetchImpl(request.url, {\n method: 'POST',\n credentials: request.credentials,\n headers: request.headers,\n body: request.form,\n signal: request.signal,\n });\n } catch (cause) {\n if (request.signal?.aborted === true) {\n throw abortedError();\n }\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Network, detail);\n }\n if (!isOk(response.status)) {\n throw httpError(response.status);\n }\n return response.text();\n}\n\nfunction reportProgress(event: ProgressEvent, onProgress: ProgressListener): void {\n if (event.lengthComputable && event.total > 0) {\n onProgress(Math.round((event.loaded / event.total) * PERCENT_COMPLETE));\n }\n}\n\n/** POST with XMLHttpRequest so upload progress can be observed. */\nexport function sendWithXhr(\n request: UploadRequest,\n createXhr: () => XMLHttpRequest,\n onProgress: ProgressListener,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const { signal } = request;\n if (signal?.aborted === true) {\n reject(abortedError());\n return;\n }\n const xhr = createXhr();\n xhr.upload.addEventListener('progress', (event) => reportProgress(event, onProgress));\n xhr.addEventListener('load', () => {\n if (isOk(xhr.status)) {\n resolve(xhr.responseText);\n } else {\n reject(httpError(xhr.status));\n }\n });\n xhr.addEventListener('error', () => reject(new UploadError(UploadErrorKind.Network, 'Upload failed (network error).')));\n xhr.addEventListener('abort', () => reject(abortedError()));\n signal?.addEventListener('abort', () => xhr.abort(), { once: true });\n xhr.open('POST', request.url);\n xhr.withCredentials = request.credentials === 'include';\n Object.entries(request.headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(request.form);\n });\n}\n","import { parseUploadedContent } from './parseUploadedContent';\nimport { sendWithFetch, sendWithXhr } from './transports';\nimport { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\nimport type { UploadRequest } from './transports';\nimport type { CsrfHeader, UploadedContent, UploadImageOptions } from './types';\n\n/** The Bff.AspNetCore anti-forgery convention: header presence, any value. */\nexport const DEFAULT_CSRF_HEADER: CsrfHeader = { name: 'X-BFF-Csrf', value: '1' };\n\nconst DEFAULT_CATEGORY = 'Image';\nconst DEFAULT_FILE_NAME = 'upload';\nconst FILE_FIELD = 'File';\nconst CATEGORY_FIELD = 'Category';\nconst IS_PUBLIC_FIELD = 'IsPublic';\n\nfunction validationError(message: string): UploadError {\n return new UploadError(UploadErrorKind.Validation, message);\n}\n\n/** Client-side checks that must fail before a byte leaves the device. */\nfunction validate(file: Blob, options: UploadImageOptions): void {\n if (file.size === 0) {\n throw validationError('File is empty.');\n }\n if (options.maxBytes !== undefined && file.size > options.maxBytes) {\n throw validationError(`File is ${String(file.size)} bytes; the limit is ${String(options.maxBytes)}.`);\n }\n if (options.allowedTypes !== undefined && !options.allowedTypes.includes(file.type)) {\n throw validationError(`File type \"${file.type}\" is not allowed.`);\n }\n}\n\nfunction resolveFileName(file: Blob, explicit: string | undefined): string {\n if (explicit !== undefined && explicit !== '') {\n return explicit;\n }\n if ('name' in file && typeof file.name === 'string' && file.name !== '') {\n return file.name;\n }\n return DEFAULT_FILE_NAME;\n}\n\nfunction buildHeaders(csrf: CsrfHeader | null | undefined): Record<string, string> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n const header = csrf === undefined ? DEFAULT_CSRF_HEADER : csrf;\n if (header !== null) {\n headers[header.name] = header.value;\n }\n return headers;\n}\n\n/** Build the transport-independent request. Exported so consumers can pin the write shape. */\nexport function buildUploadRequest(file: Blob, options: UploadImageOptions): UploadRequest {\n const form = new FormData();\n form.append(FILE_FIELD, file, resolveFileName(file, options.fileName));\n form.append(CATEGORY_FIELD, options.category ?? DEFAULT_CATEGORY);\n form.append(IS_PUBLIC_FIELD, String(options.isPublic ?? true));\n return {\n url: options.endpoint,\n headers: buildHeaders(options.csrf),\n form,\n credentials: options.credentials ?? 'include',\n signal: options.signal,\n };\n}\n\nfunction resolveXhrFactory(options: UploadImageOptions): (() => XMLHttpRequest) | undefined {\n if (options.fetchImpl !== undefined) {\n return undefined;\n }\n if (options.xhrFactory !== undefined) {\n return options.xhrFactory;\n }\n return typeof XMLHttpRequest === 'undefined' ? undefined : (): XMLHttpRequest => new XMLHttpRequest();\n}\n\nasync function send(request: UploadRequest, options: UploadImageOptions): Promise<string> {\n const { onProgress } = options;\n const createXhr = onProgress === undefined ? undefined : resolveXhrFactory(options);\n if (createXhr !== undefined && onProgress !== undefined) {\n return sendWithXhr(request, createXhr, onProgress);\n }\n const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n return sendWithFetch(request, fetchImpl);\n}\n\n/**\n * Upload one image as multipart/form-data (`File`, `Category`, `IsPublic`) to a\n * consumer-supplied endpoint and return the parsed `{ contentId, status?, url }`.\n *\n * Never sets Content-Type: the runtime adds the multipart boundary, and a JSON content type\n * on a FormData body is a 415 (see `@dloizides/bff-web-client` writeContentTypeGuard).\n *\n * @throws {UploadError} for every failure; switch on `error.kind`.\n */\nexport async function uploadImage(file: Blob, options: UploadImageOptions): Promise<UploadedContent> {\n validate(file, options);\n const request = buildUploadRequest(file, options);\n const text = await send(request, options);\n return parseUploadedContent(text, options.requireUrl ?? options.isPublic ?? true);\n}\n","import { UploadError } from './UploadError';\nimport { UploadErrorKind } from './UploadErrorKind';\n\n/**\n * Read a local URI (`blob:`, `data:`, or an RN image-picker `file:` URI) into a Blob so it\n * can be passed to `uploadImage`.\n *\n * @throws {UploadError} `Validation` when the URI cannot be read.\n */\nexport async function blobFromUri(uri: string, fetchImpl?: typeof fetch): Promise<Blob> {\n const doFetch = fetchImpl ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n response = await doFetch(uri);\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new UploadError(UploadErrorKind.Validation, `Could not read file: ${detail}`);\n }\n if (!response.ok) {\n throw new UploadError(UploadErrorKind.Validation, `Could not read file (${String(response.status)}).`);\n }\n return response.blob();\n}\n","/** Lifecycle of a single `useImageUpload` slot. */\nexport const enum UploadStatus {\n Idle = 'idle',\n Uploading = 'uploading',\n Error = 'error',\n Done = 'done',\n}\n","import { useCallback, useEffect, useReducer, useRef } from 'react';\n\nimport { PERCENT_COMPLETE } from './transports';\nimport { toUploadError } from './UploadError';\nimport { uploadImage } from './uploadImage';\nimport { UploadStatus } from './UploadStatus';\n\nimport type { UploadedContent, UploadImageOptions } from './types';\nimport type { UploadError } from './UploadError';\n\n/** Options for `useImageUpload`: everything `uploadImage` takes except the per-call wiring. */\nexport interface UseImageUploadOptions extends Omit<UploadImageOptions, 'signal' | 'onProgress'> {\n onSuccess?: (content: UploadedContent) => void;\n onError?: (error: UploadError) => void;\n}\n\nexport interface ImageUploadState {\n status: UploadStatus;\n /** 0-100. Stays 0 while uploading when the transport cannot report progress (fetch). */\n progress: number;\n error: UploadError | null;\n result: UploadedContent | null;\n}\n\nexport interface UseImageUploadResult extends ImageUploadState {\n /** Start an upload (aborting any in-flight one). Resolves to the content, or null on error/abort. */\n upload: (file: Blob, fileName?: string) => Promise<UploadedContent | null>;\n /** Abort any in-flight upload and return to idle. */\n reset: () => void;\n}\n\nconst IDLE: ImageUploadState = { status: UploadStatus.Idle, progress: 0, error: null, result: null };\nconst UPLOADING: ImageUploadState = { status: UploadStatus.Uploading, progress: 0, error: null, result: null };\n\ntype Action =\n | { type: 'start' }\n | { type: 'progress'; percent: number }\n | { type: 'done'; result: UploadedContent }\n | { type: 'fail'; error: UploadError }\n | { type: 'reset' };\n\nfunction reducer(state: ImageUploadState, action: Action): ImageUploadState {\n switch (action.type) {\n case 'start':\n return UPLOADING;\n case 'progress':\n return { ...state, progress: action.percent };\n case 'done':\n return { status: UploadStatus.Done, progress: PERCENT_COMPLETE, error: null, result: action.result };\n case 'fail':\n return { ...state, status: UploadStatus.Error, error: action.error };\n default:\n return IDLE;\n }\n}\n\n/**\n * One image-upload slot: idle -> uploading -> done | error. Progress is reported when the\n * XMLHttpRequest transport is available (browser, React Native) and no `fetchImpl` is set.\n * A newer `upload()` or `reset()` supersedes the previous request; its late result is dropped.\n * Unmount aborts the in-flight request.\n */\nexport function useImageUpload(options: UseImageUploadOptions): UseImageUploadResult {\n const [state, dispatch] = useReducer(reducer, IDLE);\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const controllerRef = useRef<AbortController | null>(null);\n const requestIdRef = useRef(0);\n\n const abortInFlight = useCallback((): void => {\n controllerRef.current?.abort();\n controllerRef.current = null;\n requestIdRef.current += 1;\n }, []);\n\n useEffect(() => abortInFlight, [abortInFlight]);\n\n const upload = useCallback(async (file: Blob, fileName?: string): Promise<UploadedContent | null> => {\n abortInFlight();\n const controller = new AbortController();\n controllerRef.current = controller;\n const requestId = requestIdRef.current;\n const isCurrent = (): boolean => requestId === requestIdRef.current;\n const { onSuccess, onError, ...uploadOptions } = optionsRef.current;\n dispatch({ type: 'start' });\n try {\n const result = await uploadImage(file, {\n ...uploadOptions,\n fileName: fileName ?? uploadOptions.fileName,\n signal: controller.signal,\n onProgress: (percent) => {\n if (isCurrent()) {\n dispatch({ type: 'progress', percent });\n }\n },\n });\n if (!isCurrent()) {\n return null;\n }\n dispatch({ type: 'done', result });\n onSuccess?.(result);\n return result;\n } catch (cause) {\n if (!isCurrent()) {\n return null;\n }\n const error = toUploadError(cause);\n dispatch({ type: 'fail', error });\n onError?.(error);\n return null;\n }\n }, [abortInFlight]);\n\n const reset = useCallback((): void => {\n abortInFlight();\n dispatch({ type: 'reset' });\n }, [abortInFlight]);\n\n return { ...state, upload, reset };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dloizides/content-upload",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Framework-light image upload client for the dloizides.com ContentService (multipart POST through a same-origin BFF proxy, CSRF header, abort, optional progress) plus a useImageUpload React hook with idle/uploading/error/done states. The endpoint is supplied by the consumer.",
5
5
  "keywords": [
6
6
  "upload",