@behindthemusictree/app-kit 32.0.3 → 33.0.0

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.
@@ -48,6 +48,7 @@ var assertWellFormedRequest = (url, options) => {
48
48
  throw Object.assign(createAppErrorFromErrorCode("CLI5000" /* CLIENT_INTERNAL_ERROR */), { cause: error });
49
49
  }
50
50
  };
51
+ var isCallerAbort = (error, signal) => !!signal?.aborted && error?.name !== "TimeoutError";
51
52
  var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryParams, handleMissingRequiredSession, handleError, expectBinary = false, backendBaseUrl) => {
52
53
  const urlWithParams = queryParams ? `${url}${url.includes("?") ? "&" : "?"}${new URLSearchParams(
53
54
  Object.entries(queryParams).map(([key, value]) => [key, String(value)])
@@ -82,6 +83,7 @@ var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryPar
82
83
  return result.json();
83
84
  }
84
85
  } catch (caughtError) {
86
+ if (isCallerAbort(caughtError, finalOptions.signal)) throw caughtError;
85
87
  let appError = null;
86
88
  if (caughtError instanceof AppError) {
87
89
  appError = caughtError;
@@ -264,4 +266,4 @@ export {
264
266
  useQueryWithParse,
265
267
  useValidatedMutation
266
268
  };
267
- //# sourceMappingURL=chunk-BVWRP6IK.js.map
269
+ //# sourceMappingURL=chunk-A6GKSUJA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport/app-errors/app-error-types.ts","../src/transport/fetch-wrapper.ts","../src/transport/useFetchWrapper.ts","../src/transport/lib/parse-with-log.ts","../src/transport/lib/paginated-response.ts","../src/transport/lib/use-query-with-parse.ts","../src/transport/lib/use-validated-mutation.ts"],"sourcesContent":["export enum ConnectivityErrorType {\n NETWORK = \"NETWORK\",\n INTERNAL = \"INTERNAL\",\n AUTH_REQUIRED = \"AUTH_REQUIRED\",\n BAD_REQUEST = \"BAD_REQUEST\",\n}\n","import {\n createAppErrorFromErrorCode,\n createAppErrorFromResult,\n createNetworkOrBackendError,\n} from \"./app-errors/app-error-factory\";\nimport { AppError } from \"./app-errors/app-error\";\nimport { ErrorCode } from \"./app-errors/app-error-codes\";\n\n// Stale keep-alive connections (e.g. browser↔Cloudflare) can drop a request before it reaches the server.\nconst NETWORK_RETRY_DELAYS_MS = [300, 900];\n\nconst fetchWithNetworkRetry = async (url: string, options: RequestInit): Promise<Response> => {\n const method = (options.method ?? \"GET\").toUpperCase();\n const retryable = method === \"GET\" || method === \"HEAD\";\n for (let attempt = 0; ; attempt++) {\n try {\n return await fetch(url, options);\n } catch (error) {\n if (!retryable || options.signal?.aborted || attempt >= NETWORK_RETRY_DELAYS_MS.length) throw error;\n await new Promise((resolve) => setTimeout(resolve, NETWORK_RETRY_DELAYS_MS[attempt]));\n }\n }\n};\n\n// fetch rejects a malformed request (bad URL, header value, method) with the same TypeError as a\n// dropped connection; building the Request first tells our bug apart. The body is left out so it\n// isn't encoded twice, hence the manual body-on-GET/HEAD check.\n// ponytail: only catches what the Request constructor validates, not errors raised mid-fetch.\n// React Native's URL polyfill doesn't reject bad URLs, so the check is weaker there.\nconst assertWellFormedRequest = (url: string, options: RequestInit) => {\n if (typeof Request !== \"function\" || typeof URL !== \"function\") return;\n try {\n const base = globalThis.document?.baseURI ?? globalThis.location?.href;\n const { method } = new Request(new URL(url, base), { ...options, body: undefined });\n if (options.body != null && (method === \"GET\" || method === \"HEAD\")) {\n throw new TypeError(`${method} request cannot have a body`);\n }\n } catch (error) {\n if (!(error instanceof TypeError)) throw error;\n throw Object.assign(createAppErrorFromErrorCode(ErrorCode.CLIENT_INTERNAL_ERROR), { cause: error });\n }\n};\n\n// fetch rejects with the signal's reason, so a custom reason is still the caller's abort;\n// AbortSignal.timeout() is the exception: it is a real failure to report.\nconst isCallerAbort = (error: unknown, signal: RequestInit[\"signal\"]) =>\n !!signal?.aborted && (error as { name?: unknown } | null)?.name !== \"TimeoutError\";\n\nexport const fetchWrapper = async <T>(\n url: string,\n requiresAuth: boolean,\n options: RequestInit = {},\n accessToken?: string,\n queryParams?: Record<string, string | number | boolean>,\n handleMissingRequiredSession?: () => void,\n handleError?: (error: Error) => void,\n expectBinary: boolean = false,\n backendBaseUrl?: string,\n): Promise<T | null> => {\n const urlWithParams = queryParams\n ? `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${new URLSearchParams(\n Object.entries(queryParams).map(([key, value]) => [key, String(value)]),\n ).toString()}`\n : url;\n\n const finalUrl = urlWithParams;\n\n // Don't set Content-Type for FormData - let browser set it with boundary\n const isFormData = options.body instanceof FormData;\n const finalOptions: RequestInit = {\n ...options,\n headers: {\n ...(isFormData ? {} : { \"Content-Type\": \"application/json\" }),\n ...(accessToken && { Authorization: `Bearer ${accessToken}` }),\n ...(options.headers || {}),\n },\n };\n\n if (requiresAuth && !accessToken) {\n handleMissingRequiredSession?.();\n return null;\n }\n\n try {\n assertWellFormedRequest(finalUrl, finalOptions);\n const result = await fetchWithNetworkRetry(finalUrl, finalOptions);\n\n if (!result.ok) {\n const appError = await createAppErrorFromResult(result, backendBaseUrl);\n throw appError;\n }\n\n if (result.status === 204) {\n return null;\n }\n\n if (expectBinary) {\n return (await result.arrayBuffer()) as T;\n } else {\n return result.json();\n }\n } catch (caughtError: unknown) {\n // A caller that aborts its own request (React Query cancelling a superseded query) is not a\n // connectivity failure; reporting it would raise the global offline popup.\n if (isCallerAbort(caughtError, finalOptions.signal)) throw caughtError;\n let appError: AppError | null = null;\n if (caughtError instanceof AppError) {\n appError = caughtError;\n } else {\n appError = createNetworkOrBackendError(caughtError, finalUrl, backendBaseUrl);\n }\n\n if (!handleError) throw appError;\n handleError(appError);\n // A mutation resolving to null reads as a schema mismatch downstream and hides the failure from onError.\n const method = (finalOptions.method ?? \"GET\").toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") throw appError;\n return null;\n }\n};\n","\"use client\";\n\nimport { useCallback } from \"react\";\nimport { useConnectivityError } from \"./connectivity-error-context\";\nimport { useSession } from \"../auth/SessionContext\";\nimport { BackendError, AuthRequired, ConnectivityError } from \"./app-errors/app-error\";\nimport { fetchWrapper as rawFetch } from \"./fetch-wrapper\";\nimport { createAppErrorFromErrorCode } from \"./app-errors/app-error-factory\";\nimport { ErrorCode } from \"./app-errors/app-error-codes\";\n\n/**\n * `getBackendBaseUrl` is supplied by the consuming app (e.g. a `site-urls.ts` built on top of\n * this package's `buildBackendBaseUrl`) rather than imported here, so this hook stays app-agnostic.\n */\nexport const useFetchWrapper = (getBackendBaseUrl: () => string) => {\n const { setConnectivityError } = useConnectivityError();\n const { clearSession, session, sessionRestored } = useSession();\n\n const handleError = useCallback((error: Error) => {\n if (error instanceof ConnectivityError) {\n const authDetailErrors = [\n ErrorCode.BACKEND_GOOGLE_OAUTH_CODE_INVALID_OR_EXPIRED,\n ErrorCode.BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST,\n ErrorCode.BACKEND_SPOTIFY_AUTHENTICATION_ERROR,\n ErrorCode.BACKEND_GOOGLE_AUTHENTICATION_ERROR,\n ErrorCode.BACKEND_GOOGLE_OAUTH_MISCONFIGURED,\n ];\n if (error instanceof BackendError && authDetailErrors.includes(error.code)) {\n throw error;\n }\n if (error instanceof AuthRequired) {\n clearSession();\n }\n setConnectivityError(error);\n if (error instanceof BackendError && error.code === ErrorCode.BACKEND_SPOTIFY_AUTHORIZATION_REQUIRED) {\n throw error;\n }\n } else {\n throw error;\n }\n }, [clearSession, setConnectivityError]);\n\n const handleMissingRequiredSession = () => {\n if (!sessionRestored) return;\n setConnectivityError(createAppErrorFromErrorCode(ErrorCode.SESSION_REQUIRED));\n };\n\n const fetch = useCallback(<T>(\n backendEndpointOrUrl: string,\n fromBackend: boolean = true,\n requiresAuth: boolean = true,\n options: RequestInit = {},\n queryParams?: Record<string, string | number | boolean>,\n expectBinary: boolean = false,\n skipGlobalError: boolean = false,\n ) => {\n const baseUrl = getBackendBaseUrl().replace(/\\/+$/, \"\");\n const endpointPath = String(backendEndpointOrUrl);\n if (fromBackend && endpointPath.startsWith(\"/\")) {\n throw new Error(`Endpoint path must be relative (no leading slash). Got: \"${endpointPath}\".`);\n }\n const url = fromBackend ? (endpointPath ? `${baseUrl}/${endpointPath}` : baseUrl) : backendEndpointOrUrl;\n return rawFetch<T>(\n url,\n requiresAuth,\n options,\n session?.accessToken || undefined,\n queryParams,\n handleMissingRequiredSession,\n skipGlobalError ? undefined : handleError,\n expectBinary,\n baseUrl,\n );\n }, [session?.accessToken, handleError, getBackendBaseUrl, sessionRestored, setConnectivityError]);\n\n return { fetch };\n};\n","import { z } from \"zod\";\n\nexport function parseWithLog<T>(schema: z.ZodType<T, unknown>, data: unknown, context?: string): T {\n const result = schema.safeParse(data);\n if (!result.success) {\n const prefix = context ? `[${context}]` : \"\";\n if (data == null) {\n throw new Error(`${prefix} received null response before schema validation`);\n }\n console.error(`${prefix} schema validation failed`, z.flattenError(result.error));\n throw result.error;\n }\n return result.data;\n}\n","import { z } from \"zod\";\n\nexport const PaginatedResponseSchema = <T extends z.ZodTypeAny>(itemSchema: T) =>\n z.object({\n overallTotal: z.number(),\n next: z.string().url().nullable(),\n previous: z.string().url().nullable(),\n results: z.array(itemSchema),\n page: z.number(),\n pageSize: z.number(),\n totalPages: z.number(),\n });\n\nexport type PaginatedResponse<T> = {\n overallTotal: number;\n next: string | null;\n previous: string | null;\n results: T[];\n page: number;\n pageSize: number;\n totalPages: number;\n};\n","import { useQuery, UseQueryOptions, QueryFunctionContext } from \"@tanstack/react-query\";\nimport { z } from \"zod\";\nimport { parseWithLog } from \"./parse-with-log\";\n\ntype UseQueryWithParseOptions<T> = Omit<UseQueryOptions<T, Error, T>, \"queryFn\"> & {\n // Receives React Query's context so callers can forward `signal` and let it cancel stale requests.\n queryFn: (context: QueryFunctionContext) => Promise<unknown>;\n schema: z.ZodType<T, unknown>;\n context?: string;\n};\n\nexport function useQueryWithParse<T>({\n queryFn,\n schema,\n context,\n ...options\n}: UseQueryWithParseOptions<T>) {\n return useQuery({\n ...options,\n queryFn: async (queryContext) => {\n const response = await queryFn(queryContext);\n return parseWithLog(schema, response, context);\n },\n });\n}\n","/**\n * React Query mutation hook with Zod validation for input and output, and form error handling.\n *\n * - Validates `variables` with `inputSchema` before calling `mutationFn`; on failure sets\n * `formErrors` and throws so the mutation is not sent.\n * - Validates the API response with `outputSchema`; on failure sets `formErrors` and throws.\n * - If the API returns an error with a `.json` body shaped like\n * `{ details: { fieldErrors: Record<string, { message: string }[]> } }`, those are mapped\n * into `formErrors` for display.\n *\n * @returns The same object as `useMutation` plus `formErrors: { field: string; message: string }[]`.\n */\nimport { useMutation, UseMutationOptions } from \"@tanstack/react-query\";\nimport { useState } from \"react\";\nimport { z } from \"zod\";\n\ntype FieldError = {\n field: string;\n message: string;\n};\n\ntype ValidatedMutationOptions<TData, TError, TVariables, TContext> = Omit<\n UseMutationOptions<TData, TError, TVariables, TContext>,\n \"mutationFn\"\n> & {\n inputSchema: z.ZodType<TVariables, unknown>;\n outputSchema: z.ZodType<TData, unknown>;\n mutationFn: (data: TVariables) => Promise<unknown>;\n};\n\nexport function useValidatedMutation<TData, TError = Error, TVariables = unknown, TContext = unknown>({\n inputSchema,\n outputSchema,\n mutationFn,\n ...options\n}: ValidatedMutationOptions<TData, TError, TVariables, TContext>) {\n const [formErrors, setFormErrors] = useState<FieldError[]>([]);\n\n const validatedMutation = useMutation<TData, TError, TVariables, TContext>({\n ...options,\n mutationFn: async (data) => {\n setFormErrors([]);\n const parsedInput = inputSchema.safeParse(data);\n if (!parsedInput.success) {\n const fieldErrors = parsedInput.error.issues.map((error) => ({\n field: error.path.map(String).join(\".\"),\n message: error.message,\n }));\n setFormErrors(fieldErrors);\n throw new Error(\"Invalid input data\");\n }\n\n try {\n const response = await mutationFn(parsedInput.data);\n const parsedOutput = outputSchema.safeParse(response);\n if (!parsedOutput.success) {\n console.error(\"Output validation failed:\", parsedOutput.error);\n setFormErrors([{ field: \"form\", message: \"Invalid response from server\" }]);\n throw new Error(\"Invalid response from server\");\n }\n return parsedOutput.data;\n } catch (error) {\n if (error instanceof Error && \"json\" in error) {\n try {\n const errorResponse = z\n .object({\n details: z.object({\n fieldErrors: z.record(z.string(), z.array(z.object({ message: z.string() }))),\n }),\n })\n .parse((error as unknown as { json: unknown }).json);\n\n setFormErrors(\n Object.entries(errorResponse.details.fieldErrors || {}).flatMap(([field, errors]) =>\n errors.map((err) => ({\n field,\n message: err.message,\n })),\n ),\n );\n } catch (parseError) {\n console.error(\"Failed to parse error response:\", parseError);\n setFormErrors([{ field: \"form\", message: \"An error occurred\" }]);\n }\n }\n throw error;\n }\n },\n });\n\n return { ...validatedMutation, formErrors };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAO,IAAK,wBAAL,kBAAKA,2BAAL;AACL,EAAAA,uBAAA,aAAU;AACV,EAAAA,uBAAA,cAAW;AACX,EAAAA,uBAAA,mBAAgB;AAChB,EAAAA,uBAAA,iBAAc;AAJJ,SAAAA;AAAA,GAAA;;;ACSZ,IAAM,0BAA0B,CAAC,KAAK,GAAG;AAEzC,IAAM,wBAAwB,OAAO,KAAa,YAA4C;AAC5F,QAAM,UAAU,QAAQ,UAAU,OAAO,YAAY;AACrD,QAAM,YAAY,WAAW,SAAS,WAAW;AACjD,WAAS,UAAU,KAAK,WAAW;AACjC,QAAI;AACF,aAAO,MAAM,MAAM,KAAK,OAAO;AAAA,IACjC,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,QAAQ,QAAQ,WAAW,WAAW,wBAAwB,OAAQ,OAAM;AAC9F,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,wBAAwB,OAAO,CAAC,CAAC;AAAA,IACtF;AAAA,EACF;AACF;AAOA,IAAM,0BAA0B,CAAC,KAAa,YAAyB;AACrE,MAAI,OAAO,YAAY,cAAc,OAAO,QAAQ,WAAY;AAChE,MAAI;AACF,UAAM,OAAO,WAAW,UAAU,WAAW,WAAW,UAAU;AAClE,UAAM,EAAE,OAAO,IAAI,IAAI,QAAQ,IAAI,IAAI,KAAK,IAAI,GAAG,EAA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,IAAI,MAAM,8BAA8B;AAAA,QAChD;AACA,eAAO,aAAa;AAAA,MACtB,SAAS,OAAO;AACd,YAAI,iBAAiB,SAAS,UAAU,OAAO;AAC7C,cAAI;AACF,kBAAM,gBAAgBA,GACnB,OAAO;AAAA,cACN,SAASA,GAAE,OAAO;AAAA,gBAChB,aAAaA,GAAE,OAAOA,GAAE,OAAO,GAAGA,GAAE,MAAMA,GAAE,OAAO,EAAE,SAASA,GAAE,OAAO,EAAE,CAAC,CAAC,CAAC;AAAA,cAC9E,CAAC;AAAA,YACH,CAAC,EACA,MAAO,MAAuC,IAAI;AAErD;AAAA,cACE,OAAO,QAAQ,cAAc,QAAQ,eAAe,CAAC,CAAC,EAAE;AAAA,gBAAQ,CAAC,CAAC,OAAO,MAAM,MAC7E,OAAO,IAAI,CAAC,SAAS;AAAA,kBACnB;AAAA,kBACA,SAAS,IAAI;AAAA,gBACf,EAAE;AAAA,cACJ;AAAA,YACF;AAAA,UACF,SAAS,YAAY;AACnB,oBAAQ,MAAM,mCAAmC,UAAU;AAC3D,0BAAc,CAAC,EAAE,OAAO,QAAQ,SAAS,oBAAoB,CAAC,CAAC;AAAA,UACjE;AAAA,QACF;AACA,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO,EAAE,GAAG,mBAAmB,WAAW;AAC5C;","names":["ConnectivityErrorType","fetch","z","z"]}
@@ -100,7 +100,7 @@ function useConnectivityErrorPopup({
100
100
  } else if (error instanceof BadRequestError || error instanceof BackendError || error instanceof ServiceError || error instanceof AuthRequired) {
101
101
  popup = renderer.renderInternalErrorPopup(error.code);
102
102
  } else if (error instanceof NetworkError) {
103
- popup = renderer.renderNetworkErrorPopup();
103
+ popup = renderer.renderNetworkErrorPopup(error.code);
104
104
  }
105
105
  if (popup) {
106
106
  showPopup(popup, popupType);
@@ -241,4 +241,4 @@ export {
241
241
  useConnectivityErrorPopup,
242
242
  useTrackUpload
243
243
  };
244
- //# sourceMappingURL=chunk-OGTDTTHJ.js.map
244
+ //# sourceMappingURL=chunk-I7NXFXV3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/popup/PopupContext.tsx","../src/popup/useConnectivityErrorPopup.ts","../src/popup/useTrackUpload.ts"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext, useState, useCallback, useMemo, ReactNode } from \"react\";\n\nexport const AUTH_POPUP_TYPE = \"auth\";\n\ninterface PopupState {\n content: ReactNode;\n type: string | null;\n}\n\ninterface HidePopupOptions {\n onlyIfType?: string;\n}\n\ninterface PopupContextType {\n showPopup: (popup: ReactNode, type?: string | null) => void;\n hidePopup: (options?: HidePopupOptions) => void;\n activePopup: ReactNode | null;\n}\n\nconst PopupContext = createContext<PopupContextType | undefined>(undefined);\n\ninterface PopupProviderProps {\n children: ReactNode;\n}\n\nexport function PopupProvider({ children }: PopupProviderProps) {\n const [state, setState] = useState<PopupState>({ content: null, type: null });\n const activePopup = state.content;\n\n const showPopup = useCallback((popup: ReactNode, type?: string | null) => {\n setState({ content: popup, type: type ?? null });\n }, []);\n\n const hidePopup = useCallback((options?: HidePopupOptions) => {\n if (options?.onlyIfType !== undefined) {\n setState((prev) => (prev.type === options.onlyIfType ? { content: null, type: null } : prev));\n } else {\n setState({ content: null, type: null });\n }\n }, []);\n\n const value = useMemo(() => ({ showPopup, hidePopup, activePopup }), [showPopup, hidePopup, activePopup]);\n\n return <PopupContext.Provider value={value}>{children}</PopupContext.Provider>;\n}\n\nexport function usePopup() {\n const context = useContext(PopupContext);\n if (context === undefined) {\n throw new Error(\"usePopup must be used within a PopupProvider\");\n }\n return context;\n}\n","\"use client\";\n\nimport { ReactNode, useEffect, useRef } from \"react\";\nimport {\n AuthRequired,\n BackendError,\n BadRequestError,\n ClientError,\n ConnectivityError,\n InvalidInputError,\n NetworkError,\n ServiceError,\n} from \"../transport/app-errors/app-error\";\nimport { ErrorCode } from \"../transport/app-errors/app-error-codes\";\nimport { useConnectivityError } from \"../transport/connectivity-error-context\";\nimport { AUTH_POPUP_TYPE, usePopup } from \"./PopupContext\";\n\nexport interface ConnectivityErrorPopupRenderers {\n renderAuthPopup: () => ReactNode;\n renderSpotifyOnlyAuthPopup: () => ReactNode;\n renderInternalErrorPopup: (errorCode: ErrorCode) => ReactNode;\n renderSpotifyAuthErrorPopup: (params: { message: string; errorCode: ErrorCode; onClose: () => void }) => ReactNode;\n renderGoogleAuthErrorPopup: (params: { message: string; onClose: () => void }) => ReactNode;\n renderNetworkErrorPopup: (errorCode: ErrorCode) => ReactNode;\n}\n\nexport interface UseConnectivityErrorPopupOptions {\n isAccountPage: boolean;\n routeRequiresAuth: boolean;\n routeRequiresSpotify: boolean;\n renderers: ConnectivityErrorPopupRenderers;\n}\n\nconst ALWAYS_REDISPLAY_ON_REPEAT = [NetworkError, BackendError, ClientError, ServiceError, InvalidInputError];\n\n/**\n * Classifies the shared connectivity-error state into the right popup and shows it. Consuming apps\n * supply the actual popup components via `renderers` since those are app-branded; this hook owns\n * only the error -> popup-kind decision, so a fix here (e.g. a route not requiring auth still\n * surfacing an unexpected AuthRequired) applies to every app instead of needing a per-app patch.\n */\nexport function useConnectivityErrorPopup({\n isAccountPage,\n routeRequiresAuth,\n routeRequiresSpotify,\n renderers,\n}: UseConnectivityErrorPopupOptions): void {\n const { showPopup, hidePopup } = usePopup();\n const { connectivityError, clearConnectivityError } = useConnectivityError();\n const currentConnectivityErrorRef = useRef<typeof ConnectivityError | null>(null);\n const renderersRef = useRef(renderers);\n renderersRef.current = renderers;\n\n useEffect(() => {\n if (connectivityError === null) {\n if (currentConnectivityErrorRef.current !== null) {\n currentConnectivityErrorRef.current = null;\n hidePopup();\n }\n return;\n }\n\n const error = connectivityError;\n const isSpotifyAllowlistOrAuthError =\n error instanceof BackendError &&\n [ErrorCode.BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST, ErrorCode.BACKEND_SPOTIFY_AUTHENTICATION_ERROR].includes(\n error.code,\n );\n\n if (isSpotifyAllowlistOrAuthError && !routeRequiresSpotify) {\n hidePopup();\n clearConnectivityError();\n currentConnectivityErrorRef.current = null;\n return;\n }\n\n if (\n currentConnectivityErrorRef.current == null ||\n (!ALWAYS_REDISPLAY_ON_REPEAT.includes(currentConnectivityErrorRef.current) &&\n !(connectivityError instanceof currentConnectivityErrorRef.current))\n ) {\n const renderer = renderersRef.current;\n let popup: ReactNode | null = null;\n let popupType: string | null = null;\n\n if (!isAccountPage && routeRequiresAuth && error instanceof AuthRequired) {\n popup = renderer.renderAuthPopup();\n popupType = AUTH_POPUP_TYPE;\n } else if (\n !isAccountPage &&\n routeRequiresSpotify &&\n error instanceof BackendError &&\n error.code === ErrorCode.BACKEND_SPOTIFY_AUTHORIZATION_REQUIRED\n ) {\n popup = renderer.renderSpotifyOnlyAuthPopup();\n popupType = AUTH_POPUP_TYPE;\n } else if (error instanceof InvalidInputError) {\n console.error(\"[InvalidInputError]\", error.code, error.json);\n popup = renderer.renderInternalErrorPopup(error.code);\n } else if (\n routeRequiresSpotify &&\n error instanceof BackendError &&\n [ErrorCode.BACKEND_SPOTIFY_USER_NOT_IN_ALLOWLIST, ErrorCode.BACKEND_SPOTIFY_AUTHENTICATION_ERROR].includes(\n error.code,\n )\n ) {\n popup = renderer.renderSpotifyAuthErrorPopup({\n message: error.message,\n errorCode: error.code,\n onClose: () => hidePopup(),\n });\n } else if (\n error instanceof BackendError &&\n [\n ErrorCode.BACKEND_GOOGLE_AUTHENTICATION_ERROR,\n ErrorCode.BACKEND_GOOGLE_OAUTH_MISCONFIGURED,\n ErrorCode.BACKEND_GOOGLE_OAUTH_CODE_INVALID_OR_EXPIRED,\n ].includes(error.code)\n ) {\n popup = renderer.renderGoogleAuthErrorPopup({ message: error.message, onClose: () => hidePopup() });\n } else if (\n error instanceof BadRequestError ||\n error instanceof BackendError ||\n error instanceof ServiceError ||\n error instanceof AuthRequired\n ) {\n // AuthRequired reaches here when the route doesn't require a session (e.g. a public\n // reference page) or is the account page, so the AuthPopup branch above didn't fire —\n // an unexpected 401 on those routes still needs to surface, not be dropped silently.\n popup = renderer.renderInternalErrorPopup(error.code);\n } else if (error instanceof NetworkError) {\n popup = renderer.renderNetworkErrorPopup(error.code);\n }\n\n if (popup) {\n showPopup(popup, popupType);\n }\n\n currentConnectivityErrorRef.current = error.constructor as typeof ConnectivityError;\n }\n }, [\n connectivityError,\n showPopup,\n hidePopup,\n clearConnectivityError,\n isAccountPage,\n routeRequiresAuth,\n routeRequiresSpotify,\n ]);\n}\n","\"use client\";\n\nimport { useState, useEffect, useCallback, useRef } from \"react\";\n\nexport type UploadStatus = \"pending\" | \"uploading\" | \"success\" | \"error\";\n\nexport type TrackUploadItem = {\n id: string;\n file: File;\n genre: string | null;\n status: UploadStatus;\n progress: number;\n error?: Error | null;\n uploadedTrack?: unknown;\n};\n\nexport interface UseTrackUploadOptions {\n files: File[];\n genre?: string | null;\n onProcessFile: (file: File, genre?: string | null) => Promise<unknown>;\n onComplete?: (uploadedTracks: unknown[]) => void;\n /**\n * Timeout (ms) before an in-flight upload is treated as failed. Passed by the consuming app\n * (from whatever env var / config it uses) so this package doesn't assume a specific env var name.\n */\n uploadTimeoutMs: number;\n}\n\nexport interface UseTrackUploadResult {\n items: TrackUploadItem[];\n isUploading: boolean;\n allComplete: boolean;\n successfulCount: number;\n errorCount: number;\n}\n\n/** Uploads `files` one after the other through `onProcessFile`, restarting whenever the file list or genre changes. */\nexport function useTrackUpload({\n files,\n genre,\n onProcessFile,\n onComplete,\n uploadTimeoutMs,\n}: UseTrackUploadOptions): UseTrackUploadResult {\n const [items, setItems] = useState<TrackUploadItem[]>([]);\n const [currentUploadIndex, setCurrentUploadIndex] = useState(0);\n const [isUploading, setIsUploading] = useState(false);\n const [allComplete, setAllComplete] = useState(false);\n\n const lastFilesKeyRef = useRef<string | null>(null);\n const progressIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const runRef = useRef(0);\n const completedRunRef = useRef<number | null>(null);\n\n useEffect(() => {\n const filesKey = `${files.length}-${files.map((f) => `${f.name}:${f.size}`).join(\"|\")}-${genre ?? \"\"}`;\n if (lastFilesKeyRef.current === filesKey) return;\n lastFilesKeyRef.current = filesKey;\n runRef.current += 1;\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n\n setItems(\n files.map((file, index) => ({\n id: `upload-${index}-${file.name}`,\n file,\n genre: genre ?? null,\n status: \"pending\" as UploadStatus,\n progress: 0,\n })),\n );\n setCurrentUploadIndex(0);\n setIsUploading(false);\n setAllComplete(false);\n }, [files, genre]);\n\n const startNextUpload = useCallback(() => {\n const currentItem = items[currentUploadIndex];\n setIsUploading(true);\n\n setItems((prev) =>\n prev.map((item, index) => (index === currentUploadIndex ? { ...item, status: \"uploading\", progress: 0 } : item)),\n );\n\n if (progressIntervalRef.current) clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = setInterval(() => {\n setItems((prev) =>\n prev.map((item, index) =>\n index === currentUploadIndex && item.status === \"uploading\"\n ? { ...item, progress: Math.min(item.progress + Math.random() * 8, 99) }\n : item,\n ),\n );\n }, 800);\n\n const uploadingIndex = currentUploadIndex;\n const run = runRef.current;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => reject(new Error(\"Upload timed out. The server took too long to respond.\")), uploadTimeoutMs);\n });\n\n Promise.race([onProcessFile(currentItem.file, currentItem.genre), timeoutPromise])\n .then((data) => {\n if (run !== runRef.current) return;\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n setItems((prev) =>\n prev.map((item, index) =>\n index === uploadingIndex ? { ...item, status: \"success\", progress: 100, uploadedTrack: data } : item,\n ),\n );\n setIsUploading(false);\n setCurrentUploadIndex((prev) => prev + 1);\n })\n .catch((error) => {\n if (run !== runRef.current) return;\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n setItems((prev) =>\n prev.map((item, index) => (index === uploadingIndex ? { ...item, status: \"error\", error } : item)),\n );\n setIsUploading(false);\n setCurrentUploadIndex((prev) => prev + 1);\n });\n }, [items, currentUploadIndex, onProcessFile, uploadTimeoutMs]);\n\n useEffect(() => {\n return () => {\n if (progressIntervalRef.current) {\n clearInterval(progressIntervalRef.current);\n progressIntervalRef.current = null;\n }\n };\n }, []);\n\n useEffect(() => {\n const shouldStart = items.length > 0 && !isUploading && currentUploadIndex < items.length;\n if (shouldStart) {\n startNextUpload();\n }\n }, [items, currentUploadIndex, isUploading, startNextUpload]);\n\n useEffect(() => {\n if (items.length > 0 && currentUploadIndex >= items.length && !isUploading) {\n // React may re-run queued updaters, handing back an equal-but-new items after completion\n if (completedRunRef.current === runRef.current) return;\n completedRunRef.current = runRef.current;\n setAllComplete(true);\n const successfulTracks = items\n .filter((item) => item.status === \"success\" && item.uploadedTrack)\n .map((item) => item.uploadedTrack);\n onComplete?.(successfulTracks);\n }\n }, [items, currentUploadIndex, isUploading, onComplete]);\n\n return {\n items,\n isUploading,\n allComplete,\n successfulCount: items.filter((item) => item.status === \"success\").length,\n errorCount: items.filter((item) => item.status === \"error\").length,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAEA,SAAS,eAAe,YAAY,UAAU,aAAa,eAA0B;AA2C5E;AAzCF,IAAM,kBAAkB;AAiB/B,IAAM,eAAe,cAA4C,MAAS;AAMnE,SAAS,cAAc,EAAE,SAAS,GAAuB;AAC9D,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAqB,EAAE,SAAS,MAAM,MAAM,KAAK,CAAC;AAC5E,QAAM,cAAc,MAAM;AAE1B,QAAM,YAAY,YAAY,CAAC,OAAkB,SAAyB;AACxE,aAAS,EAAE,SAAS,OAAO,MAAM,QAAQ,KAAK,CAAC;AAAA,EACjD,GAAG,CAAC,CAAC;AAEL,QAAM,YAAY,YAAY,CAAC,YAA+B;AAC5D,QAAI,SAAS,eAAe,QAAW;AACrC,eAAS,CAAC,SAAU,KAAK,SAAS,QAAQ,aAAa,EAAE,SAAS,MAAM,MAAM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QAAQ,SAAS,MAAM,IAAI,IAAK;AAAA,MACnG;AACA,qBAAe,KAAK;AACpB,4BAAsB,CAAC,SAAS,OAAO,CAAC;AAAA,IAC1C,CAAC;AAAA,EACL,GAAG,CAAC,OAAO,oBAAoB,eAAe,eAAe,CAAC;AAE9D,EAAAD,WAAU,MAAM;AACd,WAAO,MAAM;AACX,UAAI,oBAAoB,SAAS;AAC/B,sBAAc,oBAAoB,OAAO;AACzC,4BAAoB,UAAU;AAAA,MAChC;AAAA,IACF;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,EAAAA,WAAU,MAAM;AACd,UAAM,cAAc,MAAM,SAAS,KAAK,CAAC,eAAe,qBAAqB,MAAM;AACnF,QAAI,aAAa;AACf,sBAAgB;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,OAAO,oBAAoB,aAAa,eAAe,CAAC;AAE5D,EAAAA,WAAU,MAAM;AACd,QAAI,MAAM,SAAS,KAAK,sBAAsB,MAAM,UAAU,CAAC,aAAa;AAE1E,UAAI,gBAAgB,YAAY,OAAO,QAAS;AAChD,sBAAgB,UAAU,OAAO;AACjC,qBAAe,IAAI;AACnB,YAAM,mBAAmB,MACtB,OAAO,CAAC,SAAS,KAAK,WAAW,aAAa,KAAK,aAAa,EAChE,IAAI,CAAC,SAAS,KAAK,aAAa;AACnC,mBAAa,gBAAgB;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,OAAO,oBAAoB,aAAa,UAAU,CAAC;AAEvD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,SAAS,EAAE;AAAA,IACnE,YAAY,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,OAAO,EAAE;AAAA,EAC9D;AACF;","names":["useState","useEffect","useCallback","useRef"]}
@@ -4,7 +4,7 @@ import {
4
4
  useFetchWrapper,
5
5
  useQueryWithParse,
6
6
  useValidatedMutation
7
- } from "./chunk-BVWRP6IK.js";
7
+ } from "./chunk-A6GKSUJA.js";
8
8
  import {
9
9
  useSession
10
10
  } from "./chunk-T5D5T52J.js";
@@ -1776,4 +1776,4 @@ export {
1776
1776
  getReparentCandidates,
1777
1777
  editGenreSongPages
1778
1778
  };
1779
- //# sourceMappingURL=chunk-4EBHHVZI.js.map
1779
+ //# sourceMappingURL=chunk-JRUPUUYV.js.map
@@ -479,6 +479,7 @@ var assertWellFormedRequest = (url, options) => {
479
479
  throw Object.assign(createAppErrorFromErrorCode("CLI5000" /* CLIENT_INTERNAL_ERROR */), { cause: error });
480
480
  }
481
481
  };
482
+ var isCallerAbort = (error, signal) => !!signal?.aborted && error?.name !== "TimeoutError";
482
483
  var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryParams, handleMissingRequiredSession, handleError, expectBinary = false, backendBaseUrl) => {
483
484
  const urlWithParams = queryParams ? `${url}${url.includes("?") ? "&" : "?"}${new URLSearchParams(
484
485
  Object.entries(queryParams).map(([key, value]) => [key, String(value)])
@@ -513,6 +514,7 @@ var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryPar
513
514
  return result.json();
514
515
  }
515
516
  } catch (caughtError) {
517
+ if (isCallerAbort(caughtError, finalOptions.signal)) throw caughtError;
516
518
  let appError = null;
517
519
  if (caughtError instanceof AppError) {
518
520
  appError = caughtError;