Skip to content

Commit

Permalink
fix: prefer nullish coalescing (#391)
Browse files Browse the repository at this point in the history
  • Loading branch information
stefl authored Nov 27, 2024
1 parent 02cc4db commit b40def9
Show file tree
Hide file tree
Showing 44 changed files with 75 additions and 65 deletions.
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@
"cuid",
"dashify",
"datadoghq",
"datamodel",
"dialog",
"Dialogs",
"distractor",
"distractors",
"dmmf",
"Docgen",
"dockerized",
"dopplerhq",
Expand Down Expand Up @@ -86,6 +88,7 @@
"initialisation",
"initialise",
"inngest",
"ipcountry",
"Jayne",
"jsonparse",
"jsonrepair",
Expand All @@ -104,8 +107,10 @@
"moderations",
"multilogical",
"NDJSON",
"Neue",
"nextjs",
"nocheck",
"Noto",
"Nullability",
"oakai",
"oaknational",
Expand Down Expand Up @@ -146,6 +151,7 @@
"RSHE",
"rushstack",
"Sedar",
"Segoe",
"slidedeck",
"sonarcloud",
"sonarqube",
Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/src/app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export async function getChatById(
id,
sessionOutput: session.output,
userId: session.userId,
}) || null
}) ?? null
);
}

Expand Down
4 changes: 2 additions & 2 deletions apps/nextjs/src/app/api/chat/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export const defaultConfig: Config = {
const webActionsPlugin = createWebActionsPlugin(globalPrisma);
const createdAila = new Aila({
...options,
plugins: [...(options.plugins || []), webActionsPlugin],
plugins: [...(options.plugins ?? []), webActionsPlugin],
prisma: options.prisma ?? globalPrisma,
chat: options.chat || {
chat: options.chat ?? {
id: nanoid(),
userId: undefined,
},
Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/src/app/api/chat/webActionsPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export const createWebActionsPlugin: PluginCreator = (
data: {
chatId: aila.chatId || "Unknown",
categories: moderation.categories as string[],
justification: moderation.justification || "Unknown",
justification: moderation.justification ?? "Unknown",
},
});

Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/src/app/api/cron-jobs/expired-exports/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ async function fetchExpiredExports({
});

const files =
res.data.files?.filter((file) => file.ownedByMe === true) || [];
res.data.files?.filter((file) => file.ownedByMe === true) ?? [];

if (files.length === 0) {
log.info(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface ChatProps extends React.ComponentProps<"div"> {
export function Chat({ className }: Readonly<ChatProps>) {
const chatContext = useLessonChat();
const { id, lessonPlan, messages, chat } = chatContext;
const isShared = chat?.isShared || false;
const isShared = chat?.isShared ?? false;
return (
<ChatModeration>
<DialogRoot>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export function useProgressForDownloads({
*/
return true;
}
}) || [];
}) ?? [];
const sections = [
{
label: "Lesson details",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ export const LessonPlanDisplay = ({
const lessonPlan = {
...chat.lessonPlan,
starterQuiz:
chat.lessonPlan._experimental_starterQuizMathsV0 ||
chat.lessonPlan._experimental_starterQuizMathsV0 ??
chat.lessonPlan.starterQuiz,
exitQuiz:
chat.lessonPlan._experimental_exitQuizMathsV0 || chat.lessonPlan.exitQuiz,
chat.lessonPlan._experimental_exitQuizMathsV0 ?? chat.lessonPlan.exitQuiz,
};

const [userHasCancelledAutoScroll, setUserHasCancelledAutoScroll] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ const LessonPlanMapToMarkDown = ({
const lessonPlanWithExperiments = {
...lessonPlan,
starterQuiz:
lessonPlan._experimental_starterQuizMathsV0 || lessonPlan.starterQuiz,
exitQuiz: lessonPlan._experimental_exitQuizMathsV0 || lessonPlan.exitQuiz,
lessonPlan._experimental_starterQuizMathsV0 ?? lessonPlan.starterQuiz,
exitQuiz: lessonPlan._experimental_exitQuizMathsV0 ?? lessonPlan.exitQuiz,
};
return (
Object.entries(lessonPlanWithExperiments)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const QuickActionButtons = ({ isEmptyScreen }: QuickActionButtonsProps) => {
const handleRegenerate = useCallback(() => {
trackEvent("chat:regenerate", { id: id });
const lastUserMessage =
findLast(messages, (m) => m.role === "user")?.content || "";
findLast(messages, (m) => m.role === "user")?.content ?? "";
lessonPlanTracking.onClickRetry(lastUserMessage);
queueUserAction("regenerate");
}, [queueUserAction, lessonPlanTracking, messages, trackEvent, id]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const KeyStageAndSubjectPicker = ({
useEffect(() => {
const havePickedUnavailableSubject =
selectedSubject && !allowedSubjects.includes(selectedSubject);
if (havePickedUnavailableSubject || !selectedSubject) {
if (havePickedUnavailableSubject ?? !selectedSubject) {
const firstAvailableSubject = allowedSubjects[0];

if (selectedSubject !== firstAvailableSubject) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const DialogContents = ({
<OakModalAtTheFront isOpen={!!dialogWindow} onClose={closeDialog}>
<OakModalCenterBody
title={dialogTitlesAndIcons[dialogWindow].title}
iconName={dialogTitlesAndIcons[dialogWindow].iconName || "warning"}
iconName={dialogTitlesAndIcons[dialogWindow].iconName ?? "warning"}
hideIcon={dialogTitlesAndIcons[dialogWindow].iconName === null}
>
{children}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export function useExportAdditionalMaterials({
dialogOpen,
closeDialog,
status: query.status,
data: checkForSnapShotAndPreloadQuery.data || query.data,
data: checkForSnapShotAndPreloadQuery.data ?? query.data,
}),
[
checkForSnapShotAndPreloadQuery.data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export function useExportLessonPlanDoc({
dialogOpen,
closeDialog,
status: query.status,
data: checkForSnapShotAndPreloadQuery.data || query.data,
data: checkForSnapShotAndPreloadQuery.data ?? query.data,
}),
[
checkForSnapShotAndPreloadQuery.data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export function useExportLessonSlides({
dialogOpen,
closeDialog,
status: query.status,
data: checkForSnapShotAndPreloadQuery.data || query.data,
data: checkForSnapShotAndPreloadQuery.data ?? query.data,
}),
[
active,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export function useExportQuizDoc({
dialogOpen,
closeDialog,
status: query.status,
data: checkForSnapShotAndPreloadQuery.data || query.data,
data: checkForSnapShotAndPreloadQuery.data ?? query.data,
}),
[
checkForSnapShotAndPreloadQuery.data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export function useExportWorksheetSlides({
dialogOpen,
closeDialog,
status: query.status,
data: checkForSnapShotAndPreloadQuery.data || query.data,
data: checkForSnapShotAndPreloadQuery.data ?? query.data,
}),
[
checkForSnapShotAndPreloadQuery.data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const SubjectAndKeyStageSelect = ({
useEffect(() => {
const havePickedUnavailableSubject =
selectedSubject && !allowedSubjects.includes(selectedSubject);
if (havePickedUnavailableSubject || !selectedSubject) {
if (havePickedUnavailableSubject ?? !selectedSubject) {
const firstAvailableSubject = allowedSubjects[0];

if (selectedSubject !== firstAvailableSubject) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const useModerationFeedbackSurvey = ({

useEffect(() => {
if (moderationRecord.data) {
setComment(moderationRecord.data.userComment || "");
setComment(moderationRecord.data.userComment ?? "");
}
}, [moderationRecord.data]);
const [hasSubmitted, setHasSubmitted] = useState(false);
Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/src/hooks/useClerkDemoMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type UserWithDemoStatus = User & {
};

export function isDemoStatusSet(user: LabsUser): user is UserWithDemoStatus {
const labsMetadata = user.publicMetadata.labs || {};
const labsMetadata = user.publicMetadata.labs ?? {};
return "isDemoUser" in labsMetadata;
}

Expand Down
3 changes: 1 addition & 2 deletions apps/nextjs/src/lib/feature-flags/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ import { posthogAiBetaServerClient } from "@oakai/core/src/analytics/posthogAiBe
import { aiLogger } from "@oakai/logger";
import cookie from "cookie";
import type { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
import invariant from "tiny-invariant";

const log = aiLogger("feature-flags");

/**
* We use posthog feature flags to toggle functionality without deploying code changes.
* Fething feature flags on the frontend hasn't been reliable for us:
* Fetching feature flags on the front-end hasn't been reliable for us:
* - you have to wait for a round trip to the posthog API
* - we currently have a bug where denying cookie consent prevents feature flags from loading
*
Expand Down
8 changes: 4 additions & 4 deletions apps/nextjs/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ const environment = parseEnvironment(process.env.NEXT_PUBLIC_ENVIRONMENT);
const cspConfig: CspConfig = {
strictCsp: process.env.STRICT_CSP === "true",
environment,
sentryEnv: process.env.NEXT_PUBLIC_SENTRY_ENV || "",
sentryRelease: process.env.NEXT_PUBLIC_APP_VERSION || "",
sentryReportUri: process.env.SENTRY_REPORT_URI || "",
cspReportSampleRate: process.env.NEXT_PUBLIC_CSP_REPORT_SAMPLE_RATE || "1",
sentryEnv: process.env.NEXT_PUBLIC_SENTRY_ENV ?? "",
sentryRelease: process.env.NEXT_PUBLIC_APP_VERSION ?? "",
sentryReportUri: process.env.SENTRY_REPORT_URI ?? "",
cspReportSampleRate: process.env.NEXT_PUBLIC_CSP_REPORT_SAMPLE_RATE ?? "1",
vercelEnv: parseVercelEnv(process.env.VERCEL_ENV),
enabledPolicies: {
clerk: ["development", "preview"].includes(environment),
Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/src/middlewares/csp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function generatePoliciesForEnvironment(env: CspEnvironment): string {
};

const result = addCspHeaders(mockResponse, mockRequest, config);
const cspHeader = result.headers.get("Content-Security-Policy") || "";
const cspHeader = result.headers.get("Content-Security-Policy") ?? "";

const sanitizedCspHeader = cspHeader.replace(
/'nonce-[^']+'/g,
Expand Down
4 changes: 2 additions & 2 deletions apps/nextjs/src/middlewares/csp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,8 @@ export const addCspHeaders = (
if (
request.nextUrl.pathname.match(
/(_next\/static|_next\/image|favicon.ico)/,
) ||
request.headers.has("next-router-prefetch") ||
) ??
request.headers.has("next-router-prefetch") ??
request.headers.has("purpose")
) {
return response;
Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/src/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
@tailwind utilities;

:root {
--base-color: #22222;
--base-color: #222222;
}

.radix-themes {
Expand Down
2 changes: 1 addition & 1 deletion apps/nextjs/tests-e2e/config/common-persona.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const setTestChatIdCookie = async (page: Page, chatId: string | undefined) => {
{
url: TEST_BASE_URL,
name: "typicalChatId",
value: chatId || "",
value: chatId ?? "",
},
]);
};
Expand Down
2 changes: 1 addition & 1 deletion packages/aila/src/core/Aila.testHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export function expectPatch(
value: expect.objectContaining({
op: operation,
path: path,
value: value === undefined ? expect.any(String) : value,
value: value ?? expect.any(String),
}),
}),
);
Expand Down
2 changes: 1 addition & 1 deletion packages/aila/src/features/analytics/AilaAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class AilaAnalytics {
aila: AilaServices;
adapters?: AnalyticsAdapter[];
}) {
this._adapters = adapters || [];
this._adapters = adapters ?? [];
this._aila = aila;
}

Expand Down
6 changes: 2 additions & 4 deletions packages/api/src/router/generations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@ import {
serializeGeneration,
serializedGenerationSchema,
} from "@oakai/core/src/models/serializers";
import type {
GenerationPart} from "@oakai/core/src/types";
import type { GenerationPart } from "@oakai/core/src/types";
import {
generationPartSchema,
generationPartUserTweakedSchema,
} from "@oakai/core/src/types";
import { sendQuizFeedbackEmail } from "@oakai/core/src/utils/sendQuizFeedbackEmail";
import { requestGenerationWorker } from "@oakai/core/src/workers/generations/requestGeneration";
import { structuredLogger as logger } from "@oakai/logger";
import { aiLogger } from "@oakai/logger";
import { aiLogger, structuredLogger as logger } from "@oakai/logger";
import { TRPCError } from "@trpc/server";
import { Redis } from "@upstash/redis";
import { waitUntil } from "@vercel/functions";
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/router/lesson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export const lessonRouter = router({

return res.map(({ slug, title, content }) => {
content = content as Content;
const description = (content?.lessonDescription || "") as string;
const description = (content?.lessonDescription ?? "") as string;
return {
slug,
title,
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/router/testSupport/prepareUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const log = aiLogger("testing");
const branch = process.env.VERCEL_GIT_COMMIT_REF ?? os.hostname();

const GENERATIONS_PER_24H = parseInt(
process.env.RATELIMIT_GENERATIONS_PER_24H || "120",
process.env.RATELIMIT_GENERATIONS_PER_24H ?? "120",
10,
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from "./featureFlagEvaluation";

const host = process.env.NEXT_PUBLIC_POSTHOG_HOST as string;
const apiKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY || "*";
const apiKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY ?? "*";
const personalApiKey = process.env.POSTHOG_PERSONAL_KEY_FLAGS;
invariant(personalApiKey, "POSTHOG_PERSONAL_KEY_FLAGS is required");

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/models/demoUsers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { User } from "@clerk/nextjs/server";

const DEVELOPMENT_USER_REGION = process.env.DEVELOPMENT_USER_REGION || null;
const DEVELOPMENT_USER_REGION = process.env.DEVELOPMENT_USER_REGION ?? null;
if (process.env.NODE_ENV === "development" && !DEVELOPMENT_USER_REGION) {
throw new Error("DEVELOPMENT_USER_REGION is required for development");
}
Expand Down Expand Up @@ -62,7 +62,7 @@ class DemoUsers {
}

isDemoStatusSet(user: LabsUser): user is UserWithDemoStatus {
const labsMetadata = user.publicMetadata.labs || {};
const labsMetadata = user.publicMetadata.labs ?? {};
return "isDemoUser" in labsMetadata && labsMetadata.isDemoUser !== null;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/models/lessons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,11 @@ export class Lessons {
let transcript;
if (!lesson.isNewLesson) {
zLesson = ZLesson.parse(lesson.content);
description = zLesson.lessonDescription || lesson.title;
description = zLesson.lessonDescription ?? lesson.title;
transcript = zLesson.video?.captions?.transcript;
} else {
zLesson = ZNewLesson.parse(lesson.newLessonContent);
description = zLesson.pupilLessonOutcome || lesson.title;
description = zLesson.pupilLessonOutcome ?? lesson.title;
transcript = zLesson.transcriptSentences;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/models/safetyViolations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import { inngest } from "../inngest";
import { UserBannedError } from "./userBannedError";

const ALLOWED_VIOLATIONS = parseInt(
process.env.SAFETY_VIOLATIONS_MAX_ALLOWED || "5",
process.env.SAFETY_VIOLATIONS_MAX_ALLOWED ?? "5",
10,
);
const CHECK_WINDOW_DAYS = parseInt(
process.env.SAFETY_VIOLATION_WINDOW_DAYS || "30",
process.env.SAFETY_VIOLATION_WINDOW_DAYS ?? "30",
10,
);
const checkWindowMs = 1000 * 60 * 60 * 24 * CHECK_WINDOW_DAYS;
Expand Down
Loading

0 comments on commit b40def9

Please sign in to comment.