Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { describe, expect, it, vi } from "vitest";

import {
parseIntegerSearchParam,
setParamsBlobValue,
} from "../searchParamsUtils";

describe("setParamsBlobValue", () => {
it("returns a function that updates the blob with the new value", () => {
const setter = vi.fn();
const oldBlob = { foo: "bar", baz: 1 };
const key = "foo";

const updateFoo = setParamsBlobValue(setter, oldBlob, key);
updateFoo("qux");

expect(setter).toHaveBeenCalledWith({ foo: "qux", baz: 1 });
});

it("adds a new key if it did not exist", () => {
const setter = vi.fn();
const oldBlob: { foo: string; baz?: number } = { foo: "bar" };
const key = "baz";

const updateBaz = setParamsBlobValue(setter, oldBlob, key);
updateBaz(2);

expect(setter).toHaveBeenCalledWith({ foo: "bar", baz: 2 });
});
});

describe("parseIntegerSearchParam", () => {
it("returns undefined for null", () => {
expect(parseIntegerSearchParam(null)).toBeUndefined();
});

it("returns undefined for empty string", () => {
expect(parseIntegerSearchParam("")).toBeUndefined();
});

it("returns undefined for whitespace string", () => {
expect(parseIntegerSearchParam(" ")).toBeUndefined();
});

it("returns undefined for non-numeric string", () => {
expect(parseIntegerSearchParam("abc")).toBeUndefined();
expect(parseIntegerSearchParam("123a")).toBeUndefined();
expect(parseIntegerSearchParam("a123")).toBeUndefined();
});

it("returns undefined for float string", () => {
expect(parseIntegerSearchParam("12.34")).toBeUndefined();
});

it("returns integer for valid integer string", () => {
expect(parseIntegerSearchParam("123")).toBe(123);
expect(parseIntegerSearchParam("0")).toBe(0);
expect(parseIntegerSearchParam(" 456 ")).toBe(456);
});

it("returns undefined for unsafe integers", () => {
// Number.MAX_SAFE_INTEGER is 9007199254740991
const unsafe = "9007199254740992";
expect(parseIntegerSearchParam(unsafe)).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
@layer nimbus-components {
.nimbus-error-boundary {
display: flex;
flex-direction: column;
gap: var(--gap-sm);
align-items: flex-start;
padding: var(--space-20);
border: 1px solid rgb(61 78 159 / 0.35);
border-radius: var(--radius-lg);
background: linear-gradient(
135deg,
rgb(29 41 95 / 0.35),
rgb(19 26 68 / 0.5)
);
transition:
background 180ms ease,
border-color 180ms ease,
box-shadow 180ms ease;
}

.nimbus-error-boundary:hover {
border-color: rgb(103 140 255 / 0.55);
background: linear-gradient(
135deg,
rgb(40 58 132 / 0.45),
rgb(24 32 86 / 0.65)
);
box-shadow: 0 0.5rem 1.25rem rgb(29 36 82 / 0.45);
}

.nimbus-error-boundary__actions {
display: flex;
gap: var(--gap-xs);
align-self: stretch;
}

.nimbus-error-boundary__button {
flex-grow: 1;
}

.nimbus-error-boundary__description {
color: var(--color-text-secondary);
line-height: var(--line-height-md);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import { Component, type ErrorInfo, type ReactNode, useCallback } from "react";
import { useAsyncError, useLocation, useRouteError } from "react-router";

import { NewButton } from "@thunderstore/cyberstorm";
import { classnames } from "@thunderstore/cyberstorm";

import {
resolveRouteErrorPayload,
safeResolveRouteErrorPayload,
} from "../resolveRouteErrorPayload";
import "./NimbusErrorBoundary.css";

interface NimbusErrorBoundaryState {
error: Error | null;
}

export interface NimbusErrorRetryHandlerArgs {
error: unknown;
reset: () => void;
}

export interface NimbusErrorBoundaryProps {
children: ReactNode;
title?: string;
description?: string;
retryLabel?: string;
onError?: (error: Error, info: ErrorInfo) => void;
onReset?: () => void;
fallback?: React.ComponentType<NimbusErrorBoundaryFallbackProps>;
onRetry?: (args: NimbusErrorRetryHandlerArgs) => void;
fallbackClassName?: string;
}

export interface NimbusErrorBoundaryFallbackProps {
error: unknown;
reset?: () => void;
title?: string;
description?: string;
retryLabel?: string;
onRetry?: (args: NimbusErrorRetryHandlerArgs) => void;
className?: string;
}

export type NimbusAwaitErrorElementProps = Pick<
NimbusErrorBoundaryFallbackProps,
"title" | "description" | "retryLabel" | "className" | "onRetry"
>;

/**
* NimbusErrorBoundary isolates rendering failures within a subtree and surfaces
* a consistent recovery UI with an optional "Retry" affordance.
*/
export class NimbusErrorBoundary extends Component<
NimbusErrorBoundaryProps,
NimbusErrorBoundaryState
> {
public state: NimbusErrorBoundaryState = {
error: null,
};

public static getDerivedStateFromError(
error: Error
): NimbusErrorBoundaryState {
return { error };
}

public componentDidCatch(error: Error, info: ErrorInfo) {
this.props.onError?.(error, info);
}

private readonly resetBoundary = () => {
this.setState({ error: null }, () => {
this.props.onReset?.();
});
};

public override render() {
const { error } = this.state;

if (error) {
const FallbackComponent =
this.props.fallback ?? NimbusErrorBoundaryFallback;

return (
<FallbackComponent
error={error}
reset={this.resetBoundary}
title={this.props.title}
description={this.props.description}
retryLabel={this.props.retryLabel}
className={this.props.fallbackClassName}
onRetry={this.props.onRetry}
/>
);
}

return this.props.children;
}
}

/**
* Default fallback surface displayed by {@link NimbusErrorBoundary}. It derives
* user-facing messaging from the captured error when possible and offers a
* retry button that either resets the boundary or runs a custom handler.
*/
export function NimbusErrorBoundaryFallback(
props: NimbusErrorBoundaryFallbackProps
) {
const { error, reset, onRetry, className } = props;
const { pathname, search, hash } = useLocation();

const payload = safeResolveRouteErrorPayload(error);
const title = props.title ?? payload?.headline ?? "Something went wrong";
const description =
props.description ?? payload?.description ?? "Please try again.";
const retryLabel = props.retryLabel ?? "Retry";
const currentLocation = `${pathname}${search}${hash}`;
const rootClassName = classnames(
"container container--y container--full nimbus-error-boundary",
className
);

const noopReset = useCallback(() => {}, []);
const safeReset = reset ?? noopReset;

const handleRetry = useCallback(() => {
if (onRetry) {
onRetry({ error, reset: safeReset });
return;
}

window.location.assign(currentLocation);
}, [currentLocation, error, onRetry, safeReset]);

return (
<div className={rootClassName}>
<p>{title}</p>
{description ? (
<p className="nimbus-error-boundary__description">{description}</p>
) : null}
<div className="nimbus-error-boundary__actions">
<NewButton
csVariant="accent"
onClick={handleRetry}
csSize="medium"
rootClasses="nimbus-error-boundary__button"
>
{retryLabel}
</NewButton>
</div>
</div>
);
}

/**
* Generic Await error element that mirrors {@link NimbusErrorBoundaryFallback}
* behaviour by surfacing the async error alongside Nimbus styling.
*/
export function NimbusAwaitErrorElement(props: NimbusAwaitErrorElementProps) {
const error = useAsyncError();

return <NimbusErrorBoundaryFallback {...props} error={error} />;
}

export function NimbusDefaultRouteErrorBoundary() {
const error = useRouteError();
const payload = resolveRouteErrorPayload(error);

return (
<NimbusErrorBoundaryFallback
error={error}
title={payload.headline}
description={payload.description}
/>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./NimbusErrorBoundary";
80 changes: 80 additions & 0 deletions apps/cyberstorm-remix/cyberstorm/utils/errors/handleLoaderError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import {
ApiError,
type UserFacingErrorCategory,
mapApiErrorToUserFacingError,
} from "@thunderstore/thunderstore-api";

import { defaultErrorMappings } from "./loaderMappings";
import {
type CreateUserFacingErrorResponseOptions,
type UserFacingErrorPayload,
throwUserFacingErrorResponse,
throwUserFacingPayloadResponse,
} from "./userFacingErrorResponse";

export interface LoaderErrorMapping {
status: number;
headline: string;
description?: string;
category?: UserFacingErrorCategory;
includeContext?: boolean;
statusOverride?: number;
}

export interface HandleLoaderErrorOptions
extends CreateUserFacingErrorResponseOptions {
mappings?: LoaderErrorMapping[];
}

/**
* Normalises unknown loader errors, promoting mapped API errors to user-facing payloads
* and rethrowing everything else via `throwUserFacingErrorResponse`.
*/
export function handleLoaderError(
error: unknown,
options?: HandleLoaderErrorOptions
): never {
if (error instanceof Response) {
throw error;
}

const resolvedOptions: HandleLoaderErrorOptions = options ?? {};
const allOptions = defaultErrorMappings.concat(
resolvedOptions.mappings ?? []
);

if (error instanceof ApiError && allOptions.length) {
const mapping = allOptions.findLast((candidate) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that status is just number and not an array, I think this cleans up to:

    const mapping = allOptions.findLast(
      (mapping) => mapping.status === error.response.status
    );

const statuses = Array.isArray(candidate.status)
? candidate.status
: [candidate.status];
return statuses.includes(error.response.status);
});

if (mapping) {
const base = mapApiErrorToUserFacingError(
error,
resolvedOptions.mapOptions
);
const payload: UserFacingErrorPayload = {
headline: mapping.headline,
description: mapping.description ?? base.description,
category: mapping.category ?? base.category,
status: mapping.statusOverride ?? base.status,
};

payload.context =
base.context &&
(mapping.includeContext ?? resolvedOptions.includeContext ?? false)
? base.context
: undefined;

throwUserFacingPayloadResponse(payload, {
statusOverride:
mapping.statusOverride ?? resolvedOptions.statusOverride,
});
}
}

throwUserFacingErrorResponse(error, resolvedOptions);
}
Loading
Loading