Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore: remove maybeResult (#3293)

teo5fc08db639fb
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsx
index 5874f65861..f0c441d1e9 100644
--- a/js/app/packages/app/component/Launcher.tsx
+++ b/js/app/packages/app/component/Launcher.tsx
@@ -22,7 +22,6 @@ import {
createMarkdownFile,
} from '@core/util/create';
import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';
-import { isErr, ok } from '@core/util/maybeResult';
import { AnimatedChatIcon } from '@icon/wide-chat';
import WideChat from '@icon/wide-chat.svg';
import { AnimatedDiagramIcon } from '@icon/wide-diagram';
@@ -168,8 +167,7 @@ export function runCreateAction(
title: 'New Canvas',
});
if ('error' in result) return;
- const [_, id] = ok(result.documentId);
- return id;
+ return result.documentId ?? undefined;
},
shouldInsert,
});
@@ -222,9 +220,8 @@ export function runCreateAction(
extension: 'py',
title: 'New Code File',
});
- if (isErr(result)) return;
- const [, id] = ok(result[1]?.documentId);
- return id;
+ if (result.isErr()) return;
+ return result.value.documentId ?? undefined;
},
shouldInsert,
});
diff --git a/js/app/packages/app/component/PropertyDisplayControl.tsx b/js/app/packages/app/component/PropertyDisplayControl.tsx
index abaa584cae..ce4c32e1d4 100644
--- a/js/app/packages/app/component/PropertyDisplayControl.tsx
+++ b/js/app/packages/app/component/PropertyDisplayControl.tsx
@@ -5,7 +5,6 @@ import {
} from '@core/component/Properties/utils';
import { ERROR_MESSAGES } from '@core/component/Properties/utils/errorHandling';
import { toast } from '@core/component/Toast/Toast';
-import { isErr } from '@core/util/maybeResult';
import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
import XIcon from '@phosphor/x.svg';
import { propertiesServiceClient } from '@service-properties/client';
@@ -178,16 +177,13 @@ export const PropertyDisplayControl: Component<PropertyDisplayControlProps> = (
include_options: false,
});
- if (isErr(result)) {
+ if (result.isErr()) {
setError(ERROR_MESSAGES.PROPERTY_FETCH);
setIsLoading(false);
return;
}
- const [, data] = result;
- const properties = Array.isArray(data) ? data : [];
-
- const normalizedProperties = properties.map((item) => {
+ const normalizedProperties = result.value.map((item) => {
const definition = 'definition' in item ? item.definition : item;
return toPropertyDefinitionDomain(definition);
});
diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueSelect.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueSelect.tsx
index c45824700b..e3976f030e 100644
--- a/js/app/packages/app/component/PropertyFilter/FilterValueSelect.tsx
+++ b/js/app/packages/app/component/PropertyFilter/FilterValueSelect.tsx
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { propertiesServiceClient } from '@service-properties/client';
import type { PropertyOption } from '@service-properties/generated/schemas/propertyOption';
import type { Component } from 'solid-js';
@@ -36,12 +35,12 @@ export const FilterValueSelect: Component<FilterValueSelectProps> = (props) => {
definition_id: props.propertyId,
});
- if (isErr(result)) {
+ if (result.isErr()) {
setOptions([]);
return;
}
- const [, data] = result;
+ const data = result.value;
setOptions(Array.isArray(data) ? data : []);
} catch (_error) {
setOptions([]);
diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueSelectMulti.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueSelectMulti.tsx
index 35234b57d5..95d9edc7df 100644
--- a/js/app/packages/app/component/PropertyFilter/FilterValueSelectMulti.tsx
+++ b/js/app/packages/app/component/PropertyFilter/FilterValueSelectMulti.tsx
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import XIcon from '@phosphor/x.svg';
import { propertiesServiceClient } from '@service-properties/client';
import type { PropertyOption } from '@service-properties/generated/schemas/propertyOption';
@@ -39,12 +38,12 @@ export const FilterValueSelectMulti: Component<FilterValueSelectMultiProps> = (
definition_id: props.propertyId,
});
- if (isErr(result)) {
+ if (result.isErr()) {
setOptions([]);
return;
}
- const [, data] = result;
+ const data = result.value;
setOptions(Array.isArray(data) ? data : []);
} catch (_error) {
setOptions([]);
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsx
index d62c494a0a..6f6c71f7db 100644
--- a/js/app/packages/app/component/SoupChatInput.tsx
+++ b/js/app/packages/app/component/SoupChatInput.tsx
@@ -13,7 +13,7 @@ import { deriveChatName } from '@core/component/AI/util/deriveName';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { TOKENS } from '@core/hotkey/tokens';
import { isPaymentError } from '@core/util/handlePaymentError';
-import { isErr } from '@core/util/maybeResult';
+
import { createRenameDssEntityMutation } from '@macro-entity';
import { invalidateAllSoup } from '@queries/soup/cache';
import { cognitionApiServiceClient } from '@service-cognition/client';
@@ -74,14 +74,14 @@ function SoupChatInputInner() {
// Create a new persistent chat
const response = await cognitionApiServiceClient.createChat({});
- if (isErr(response)) {
+ if (response.isErr()) {
if (isPaymentError(response)) {
const { showPaywall } = usePaywallState();
showPaywall(PaywallKey.CHAT_LIMIT);
}
return;
}
- const [, { id: chatId }] = response;
+ const { id: chatId } = response.value;
// Rename via mutation for optimistic cache updates (history, preview, soup)
const name = deriveChatName(request.content);
diff --git a/js/app/packages/app/component/app-sidebar/invite-modal.tsx b/js/app/packages/app/component/app-sidebar/invite-modal.tsx
index 2d735bbf19..3ebaf65fd2 100644
--- a/js/app/packages/app/component/app-sidebar/invite-modal.tsx
+++ b/js/app/packages/app/component/app-sidebar/invite-modal.tsx
@@ -1,6 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import { useReferralCode } from '@core/context/user';
-import { isOk } from '@core/util/maybeResult';
+
import { getWebOrigin } from '@core/util/webOrigin';
import ClipboardIcon from '@phosphor/clipboard.svg';
import CloseIcon from '@phosphor/x.svg';
@@ -46,7 +46,7 @@ export const InviteModal = () => {
setSending(true);
for (const email of emails) {
const result = await authServiceClient.sendReferralInvite(email);
- if (isOk(result)) {
+ if (result.isOk()) {
contactsClient.addContact(`macro|${email.toLowerCase()}`);
}
}
diff --git a/js/app/packages/app/component/auth/EmailForm.tsx b/js/app/packages/app/component/auth/EmailForm.tsx
index 52a9dfaaf6..e0e3fe5e82 100644
--- a/js/app/packages/app/component/auth/EmailForm.tsx
+++ b/js/app/packages/app/component/auth/EmailForm.tsx
@@ -1,7 +1,6 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
-import { isErr } from '@core/util/maybeResult';
import ArrowLeft from '@phosphor/arrow-left.svg';
import ArrowRight from '@phosphor/arrow-right.svg';
import { authServiceClient } from '@service-auth/client';
@@ -46,7 +45,7 @@ export const sendEmailCode = action(async (formData: FormData) => {
password,
email,
});
- if (isErr(maybeTokens))
+ if (maybeTokens.isErr())
throw new Error(
'Failed to login. Check your email and password then try again.'
);
diff --git a/js/app/packages/app/component/auth/Login.tsx b/js/app/packages/app/component/auth/Login.tsx
index 80d81a769e..c9226ee97c 100644
--- a/js/app/packages/app/component/auth/Login.tsx
+++ b/js/app/packages/app/component/auth/Login.tsx
@@ -4,7 +4,6 @@ import { PcNoiseGrid } from '@core/component/PcNoiseGrid';
import { useEmailLinks } from '@core/email-link';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
-import { isOk } from '@core/util/maybeResult';
import LogoIcon from '@icon/macro-logo.svg';
import { useUserInfo } from '@queries/auth';
import {
@@ -91,7 +90,7 @@ export function Login() {
unsetTokenPromise();
authServiceClient.sessionLogin({ session_code }).then(async (res) => {
console.log({ res });
- if (isOk(res)) {
+ if (res.isOk()) {
await invalidateAllAfterLogin();
await initEmailLink().match(
() => {},
diff --git a/js/app/packages/app/component/auth/LoginOptions.tsx b/js/app/packages/app/component/auth/LoginOptions.tsx
index bb4fec8e71..d3466044f4 100644
--- a/js/app/packages/app/component/auth/LoginOptions.tsx
+++ b/js/app/packages/app/component/auth/LoginOptions.tsx
@@ -8,7 +8,7 @@ import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import type { RedirectLocation } from '@core/util/authRedirect';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
-import { isOk } from '@core/util/maybeResult';
+
import { getNativeMobilePlatform } from '@core/util/platform';
import IconApple from '@icon/macro-apple.svg';
import IconGoogle from '@icon/macro-google.svg';
@@ -105,7 +105,7 @@ export function LoginOptions(props: {
session_code: result.token,
});
- if (isOk(res)) {
+ if (res.isOk()) {
await invalidateAllAfterLogin();
await initEmailLink().match(
() => {},
diff --git a/js/app/packages/app/component/auth/VerifyForm.tsx b/js/app/packages/app/component/auth/VerifyForm.tsx
index 3a19dad097..28a12ec9ab 100644
--- a/js/app/packages/app/component/auth/VerifyForm.tsx
+++ b/js/app/packages/app/component/auth/VerifyForm.tsx
@@ -1,5 +1,4 @@
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
-import { isErr } from '@core/util/maybeResult';
import ArrowLeft from '@phosphor/arrow-left.svg';
import ArrowRight from '@phosphor/arrow-right.svg';
import { authServiceClient } from '@service-auth/client';
@@ -16,13 +15,15 @@ const verifyCode = action(async (formData: FormData) => {
const email = formData.get('email');
if (typeof email !== 'string') throw new Error('Invalid email');
- const maybeResult = await authServiceClient.passwordlessCallback({
+ const result = await authServiceClient.passwordlessCallback({
code,
email,
});
- const [err] = maybeResult;
- if (err) {
- if (isErr([err], 'UNAUTHORIZED')) {
+ if (result.isErr()) {
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'UNAUTHORIZED')
+ ) {
throw new Error('Invalid code.');
}
throw new Error('Unable to perform verification.');
diff --git a/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx b/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx
index fca16fd1b0..3455982bfd 100644
--- a/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx
@@ -14,7 +14,6 @@ import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { fetchToken } from '@core/util/fetchWithToken';
-import { isOk } from '@core/util/maybeResult';
import LogoIcon from '@icon/macro-logo.svg';
import ArrowLeftIcon from '@phosphor/arrow-left.svg';
import InfoIcon from '@phosphor/info.svg';
@@ -66,15 +65,15 @@ export default function InteractiveOnboarding() {
const result = await sendMobileWelcomeEmail.mutateAsync(email);
- if (isOk(result)) {
- if (result[1].sent) {
+ if (result.isOk()) {
+ if (result.value.sent) {
setSubmittedEmail(email);
setMobileWebStep('signup-sent');
} else {
toast.alert('Email already sent.');
}
} else {
- const code = result[0]?.[0]?.code;
+ const code = result.error?.[0]?.code;
if (code === 'RATE_LIMITED') {
toast.failure('Rate limit exceeded.');
} else if (code === 'INVALID_EMAIL') {
diff --git a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
index 36de8a3a36..1523344e74 100644
--- a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
@@ -7,7 +7,7 @@ import {
import { analytics } from '@app/lib/analytics/analytics';
import { useIsAuthenticated } from '@core/auth';
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import ArrowRightIcon from '@phosphor/arrow-right.svg';
import InfoIcon from '@phosphor/info.svg';
import LockIcon from '@phosphor/lock.svg';
diff --git a/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx b/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx
index 208efcc628..a497a26289 100644
--- a/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx
+++ b/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx
@@ -27,7 +27,7 @@ import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
import type { WithCustomUserInput } from '@core/user';
import { invalidateContacts } from '@core/user/contactService';
import { getDestinationFromOptions } from '@core/util/destination';
-import { isErr, throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import {
chatRuleset,
handleFileFolderDrop,
@@ -269,12 +269,12 @@ function IosShareSheetComposer(props: {
recipients: destination.users,
});
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure('Failed to open channel');
throw new Error('Failed to resolve share destination channel');
}
- return result[1].channel_id;
+ return result.value.channel_id;
};
const handleSend = async (snapshot: InputSnapshot) => {
@@ -292,7 +292,7 @@ function IosShareSheetComposer(props: {
message,
});
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure('Failed to send message');
throw new Error('Failed to post shared message');
}
diff --git a/js/app/packages/app/component/next-soup/soup-view/NewCallButton.tsx b/js/app/packages/app/component/next-soup/soup-view/NewCallButton.tsx
index e7f26f5597..30b1e2bb49 100644
--- a/js/app/packages/app/component/next-soup/soup-view/NewCallButton.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/NewCallButton.tsx
@@ -4,7 +4,6 @@ import { toast } from '@core/component/Toast/Toast';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
import type { WithCustomUserInput } from '@core/user';
import { getDestinationFromOptions } from '@core/util/destination';
-import { isErr } from '@core/util/maybeResult';
import PhoneCallIcon from '@icon/wide-call.svg';
import XIcon from '@phosphor/x.svg';
import { commsServiceClient } from '@service-comms/client';
@@ -52,13 +51,13 @@ export function NewCallButton() {
recipients: destination.users,
});
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure('Failed to create channel for call');
setIsSubmitting(false);
return;
}
- channelId = result[1].channel_id;
+ channelId = result.value.channel_id;
}
setIsOpen(false);
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
index 02997a10d0..14f8734aab 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
@@ -17,7 +17,7 @@ import { createSearchState } from '@app/component/next-soup/soup-view/create-sea
import { deduplicateEntities } from '@app/component/next-soup/utils';
import { ENABLE_FEATURED_SEARCH_RESULTS } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import {
type EntityData,
getPropertyOptionLabel,
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index 7b170b38e7..d101d26e85 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -9,7 +9,7 @@ import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import type { BlockOrchestrator } from '@core/orchestrator';
import type { DateValue } from '@core/util/date';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { waitForFrames } from '@core/util/sleep';
import {
type EntityData,
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index bc578a02fe..1dce167bcb 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -89,12 +89,8 @@ function formatBundleUpdateStatus(status: BundleUpdateStatus): string {
function useUserName() {
const fetchUserName = async () => {
- const [_, response] = await authServiceClient.getUserName();
- if (response) {
- return response;
- }
-
- return null;
+ const response = await authServiceClient.getUserName();
+ return response.isOk() ? response.value : null;
};
const [userNameResource] = createResource(fetchUserName);
@@ -135,14 +131,14 @@ export function Account() {
const emailActive = useEmailLinksStatus();
const [githubLinkExists, { refetch: refetchGithubLink }] = createResource(async () => {
- const [_, response] = await authServiceClient.checkLinkExists({ idp_name: 'github' });
- return response?.link_exists ?? false;
+ const response = await authServiceClient.checkLinkExists({ idp_name: 'github' });
+ return response.isOk() ? response.value.link_exists : false;
});
const handleGithubEnable = async () => {
- const [_, url] = await authServiceClient.initGithubLink(window.location.href);
- if (url) {
- window.location.href = url;
+ const url = await authServiceClient.initGithubLink(window.location.href);
+ if (url.isOk()) {
+ window.location.href = url.value;
}
};
diff --git a/js/app/packages/app/component/settings/Agent.tsx b/js/app/packages/app/component/settings/Agent.tsx
index a8c1a5a88d..5a6a520138 100644
--- a/js/app/packages/app/component/settings/Agent.tsx
+++ b/js/app/packages/app/component/settings/Agent.tsx
@@ -3,7 +3,10 @@ import { Tabs } from '@core/component/Tabs';
import { Button, Layer, Panel } from '@ui';
import { McpSetupCards } from '@core/component/AI/component/McpSetupCards';
import { toast } from '@core/component/Toast/Toast';
-import type { ServerResponse } from '@service-cognition/generated/schemas';
+import type {
+ ServerResponse,
+ StartAuthResponse,
+} from '@service-cognition/generated/schemas';
import { ScopedPortal } from '@core/component/ScopedPortal';
import {
useMcpServersQuery,
@@ -44,7 +47,7 @@ function AddServerForm(props: {
authMutation.mutate(
{ server_name: serverName, server_url: serverUrl },
{
- onSuccess: (result) => {
+ onSuccess: (result: StartAuthResponse) => {
window.open(result.authorization_url, '_blank');
},
onError: () => {
@@ -232,7 +235,7 @@ function ServerRow(props: { server: ServerResponse }) {
server_name: props.server.server_name,
},
{
- onSuccess: (result) => {
+ onSuccess: (result: StartAuthResponse) => {
window.open(result.authorization_url, '_blank');
},
onError: () => {
diff --git a/js/app/packages/block-automation/component/automationUtils.ts b/js/app/packages/block-automation/component/automationUtils.ts
index 4c3f01961a..4bc8a61848 100644
--- a/js/app/packages/block-automation/component/automationUtils.ts
+++ b/js/app/packages/block-automation/component/automationUtils.ts
@@ -1,7 +1,7 @@
import { DEFAULT_MODEL } from '@core/component/AI/constant';
import type { Model } from '@core/component/AI/types';
import { blockNameToDefaultFile } from '@core/constant/allBlocks';
-import { MaybeResultError } from '@core/util/maybeResult';
+import { ThrownResultError } from '@core/util/result';
import type {
AgentTask,
CreateScheduledAction,
@@ -324,7 +324,7 @@ export function formatDateTime(value: string | null | undefined) {
}
export function getErrorMessage(error: unknown) {
- if (error instanceof MaybeResultError) {
+ if (error instanceof ThrownResultError) {
return error.errors.map((item) => item.message).join(', ');
}
diff --git a/js/app/packages/block-automation/definition.ts b/js/app/packages/block-automation/definition.ts
index 4bc069cf8b..e02a8a40bd 100644
--- a/js/app/packages/block-automation/definition.ts
+++ b/js/app/packages/block-automation/definition.ts
@@ -1,5 +1,6 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
-import { ok } from '@core/util/maybeResult';
+import { ok } from 'neverthrow';
+
import { Automation } from './component/Automation';
export const definition = defineBlock({
diff --git a/js/app/packages/block-call/component/CallBlockAdapter.tsx b/js/app/packages/block-call/component/CallBlockAdapter.tsx
index 68eece8c52..05a326ac86 100644
--- a/js/app/packages/block-call/component/CallBlockAdapter.tsx
+++ b/js/app/packages/block-call/component/CallBlockAdapter.tsx
@@ -4,7 +4,7 @@ import { useBlockId } from '@core/block';
import Unauthorized from '@core/component/AccessErrorViews/Unauthorized';
import { createMethodRegistration } from '@core/orchestrator';
import { blockHandleSignal } from '@core/signal/load';
-import { MaybeResultError } from '@core/util/maybeResult';
+import { ThrownResultError } from '@core/util/result';
import { useCallRecordQuery } from '@queries/call/call';
import { useSearchParams } from '@solidjs/router';
import { createSignal, Match, Switch } from 'solid-js';
@@ -13,7 +13,7 @@ import { CallRecordingSplitHeaderLoading } from './CallRecording/CallRecordingSp
import { ModalsProvider } from './ModalsProvider';
function isUnauthorized(error: Error | null): boolean {
- if (error instanceof MaybeResultError) {
+ if (error instanceof ThrownResultError) {
return error.errors[0]?.code === 'UNAUTHORIZED';
}
return false;
diff --git a/js/app/packages/block-call/component/CallRecording/CallRecordingParticipants.tsx b/js/app/packages/block-call/component/CallRecording/CallRecordingParticipants.tsx
index c6455c3364..854c462c41 100644
--- a/js/app/packages/block-call/component/CallRecording/CallRecordingParticipants.tsx
+++ b/js/app/packages/block-call/component/CallRecording/CallRecordingParticipants.tsx
@@ -1,7 +1,7 @@
import { useSplitLayout } from '@app/component/split-layout/layout';
import { UserIcon } from '@core/component/UserIcon';
import { idToEmail } from '@core/user';
-import { isOk } from '@core/util/maybeResult';
+
import { commsServiceClient } from '@service-comms/client';
import type { CallRecord } from '@service-storage/generated/schemas/callRecord';
import type { Accessor } from 'solid-js';
@@ -23,7 +23,7 @@ export function CallRecordingParticipantsSection(props: {
const result = await commsServiceClient.getOrCreateDirectMessage({
recipient_id: participantId,
});
- const channelId = isOk(result) && result[1]?.channel_id;
+ const channelId = result.isOk() && result.value?.channel_id;
if (!channelId) return;
replaceOrInsertSplit({
type: 'channel',
diff --git a/js/app/packages/block-call/definition.ts b/js/app/packages/block-call/definition.ts
index 5e85b04bb8..37269a7631 100644
--- a/js/app/packages/block-call/definition.ts
+++ b/js/app/packages/block-call/definition.ts
@@ -1,6 +1,7 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
-import { ok } from '@core/util/maybeResult';
+import { ok } from 'neverthrow';
+
import { CallBlockAdapter } from './component/CallBlockAdapter';
export const definition = defineBlock({
diff --git a/js/app/packages/block-canvas/component/Block.tsx b/js/app/packages/block-canvas/component/Block.tsx
index 9432eb56bb..1c55e78ca6 100644
--- a/js/app/packages/block-canvas/component/Block.tsx
+++ b/js/app/packages/block-canvas/component/Block.tsx
@@ -7,7 +7,7 @@ import {
} from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { blockFileSignal, blockHandleSignal } from '@core/signal/load';
-import { isErr } from '@core/util/maybeResult';
+
import type { IDocumentStorageServiceFile } from '@filesystem/file';
import { storageServiceClient } from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
@@ -154,8 +154,8 @@ export default function BlockCanvas(props: BlockCanvasProps) {
},
});
- if (isErr(res)) return null;
- const [, { viewLocation }] = res;
+ if (res.isErr()) return null;
+ const { viewLocation } = res.value;
if (!viewLocation) return null;
const initialParams = new URLSearchParams(viewLocation.replace('#', ''));
diff --git a/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx b/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx
index 93902301f1..cb21e6593f 100644
--- a/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx
+++ b/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx
@@ -2,7 +2,6 @@ import { clamp } from '@block-canvas/util/math';
import { LoadErrors } from '@core/block';
import { CircleSpinner } from '@core/component/CircleSpinner';
import { staticFileIdEndpoint } from '@core/constant/servers';
-import { isErr } from '@core/util/maybeResult';
import PauseIcon from '@phosphor/pause.svg';
import PlayIcon from '@phosphor/play.svg';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
@@ -172,28 +171,32 @@ export function DSSMedia(props: { node: MediaNode; mode: RenderMode }) {
if (props.node.status === 'dss' || !props.node.status) {
const res = await fetchBinaryDocumentData(props.node.uuid);
- if (isErr(res, 'UNAUTHORIZED') || isErr(res, 'HTTP_ERROR')) {
+ if (
+ (res.isErr() &&
+ res.error.some((error) => error.code === 'UNAUTHORIZED')) ||
+ (res.isErr() && res.error.some((error) => error.code === 'HTTP_ERROR'))
+ ) {
setError();
setError('UNAUTHORIZED');
return LoadErrors.UNAUTHORIZED;
}
- if (isErr(res)) {
+ if (res.isErr()) {
setError();
setError('MISSING');
return LoadErrors.MISSING;
}
- const [, documentResult] = res;
+ const documentResult = res.value;
const { blobUrl } = documentResult;
const blobResult = await fetchBinary(blobUrl, 'blob');
- if (isErr(blobResult)) {
+ if (blobResult.isErr()) {
return LoadErrors.MISSING;
}
- const url = URL.createObjectURL(blobResult[1]);
+ const url = URL.createObjectURL(blobResult.value);
setUrl(url);
setError();
diff --git a/js/app/packages/block-canvas/definition.ts b/js/app/packages/block-canvas/definition.ts
index 40d98c3bc4..279c28dec0 100644
--- a/js/app/packages/block-canvas/definition.ts
+++ b/js/app/packages/block-canvas/definition.ts
@@ -5,10 +5,10 @@ import {
loadResult,
} from '@core/block';
import { blockAcceptedFileExtensionToMimeType } from '@core/constant/allBlocks';
-import { isErr, ok } from '@core/util/maybeResult';
import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
+import { err, ok } from 'neverthrow';
import CanvasBlock from './component/Block';
import type { Canvas } from './model/CanvasModel';
@@ -33,15 +33,15 @@ export const definition = defineBlock({
});
}
- if (isErr(maybeDocument)) return maybeDocument;
- const [, documentResult] = maybeDocument;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
+ const documentResult = maybeDocument.value;
const { documentMetadata, blobUrl, userAccessLevel } = documentResult;
const blobResult = await loadResult(fetchBinary(blobUrl, 'blob'));
- if (isErr(blobResult)) return blobResult;
+ if (blobResult.isErr()) return err(blobResult.error);
- const [, blob] = blobResult;
+ const blob = blobResult.value;
const dssFile = await makeFileFromBlob({
blob,
diff --git a/js/app/packages/block-canvas/store/canvasData.ts b/js/app/packages/block-canvas/store/canvasData.ts
index 5bb03a3ea3..cdde2919de 100644
--- a/js/app/packages/block-canvas/store/canvasData.ts
+++ b/js/app/packages/block-canvas/store/canvasData.ts
@@ -4,7 +4,7 @@ import {
} from '@block-canvas/util/connectors';
import { createBlockSignal, useBlockId } from '@core/block';
import { filterMapAsync } from '@core/util/list';
-import { isErr } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
import { debounce } from '@solid-primitives/scheduled';
@@ -829,7 +829,7 @@ export const useSaveCanvasDataImmediate = sharedInstance(() => {
file,
});
- if (isErr(saveRes)) {
+ if (saveRes.isErr()) {
console.error('error on canvas save');
}
diff --git a/js/app/packages/block-channel/component/Compose.tsx b/js/app/packages/block-channel/component/Compose.tsx
index 739f64291b..9f83237ec3 100644
--- a/js/app/packages/block-channel/component/Compose.tsx
+++ b/js/app/packages/block-channel/component/Compose.tsx
@@ -29,7 +29,7 @@ import {
} from '@core/user';
import { useSendMessageToPeople } from '@core/util/channels';
import { getDestinationFromOptions } from '@core/util/destination';
-import { isErr } from '@core/util/maybeResult';
+
import {
chatRuleset,
handleFileFolderDrop,
@@ -130,10 +130,10 @@ export function ChannelCompose() {
name: channelName() ?? null,
participants: destination.users,
});
- if (isErr(res)) {
+ if (res.isErr()) {
throw new Error('Could not create channel');
}
- const [, { id }] = res;
+ const { id } = res.value;
await sendToChannel({
channelId: id,
content,
diff --git a/js/app/packages/block-channel/definition.ts b/js/app/packages/block-channel/definition.ts
index bbda9cbad5..5ac015e3f3 100644
--- a/js/app/packages/block-channel/definition.ts
+++ b/js/app/packages/block-channel/definition.ts
@@ -1,5 +1,6 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
-import { ok } from '@core/util/maybeResult';
+import { ok } from 'neverthrow';
+
import { NewChannelBlockAdapter } from './component/NewChannelBlockAdapter';
export const definition = defineBlock({
diff --git a/js/app/packages/block-chat/client.ts b/js/app/packages/block-chat/client.ts
index f91377c8dd..6cac294647 100644
--- a/js/app/packages/block-chat/client.ts
+++ b/js/app/packages/block-chat/client.ts
@@ -1,7 +1,7 @@
import type { BlockName } from '@core/block';
import { usePaywallState } from '@core/constant/PaywallState';
import { isPaymentError } from '@core/util/handlePaymentError';
-import { isErr } from '@core/util/maybeResult';
+
import { cognitionApiServiceClient } from '@service-cognition/client';
export function useOpenChatForAttachment() {
@@ -18,8 +18,8 @@ export function useOpenChatForAttachment() {
const res = await cognitionApiServiceClient.getChatsForAttachment({
attachment_id: attachmentId,
});
- if (isErr(res)) return;
- const [, data] = res;
+ if (res.isErr()) return;
+ const data = res.value;
let recent_id = data?.recent_chat?.id;
@@ -33,10 +33,10 @@ export function useOpenChatForAttachment() {
showPaywall();
return;
}
- if (isErr(res)) {
+ if (res.isErr()) {
return;
}
- const [, data] = res;
+ const data = res.value;
recent_id = data?.id;
} else if (!recent_id || !data?.recent_chat?.isPersistent) {
const res = await cognitionApiServiceClient.createChat({});
@@ -45,10 +45,10 @@ export function useOpenChatForAttachment() {
showPaywall();
return;
}
- if (isErr(res)) {
+ if (res.isErr()) {
return;
}
- const [, data] = res;
+ const data = res.value;
recent_id = data?.id;
}
};
diff --git a/js/app/packages/block-chat/definition.ts b/js/app/packages/block-chat/definition.ts
index e7ab4bd08f..9848ee9ca5 100644
--- a/js/app/packages/block-chat/definition.ts
+++ b/js/app/packages/block-chat/definition.ts
@@ -1,9 +1,9 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { AllModels } from '@service-cognition/generated/schemas';
import type { Entity } from '@service-cognition/generated/schemas/entity';
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
+import { ok } from 'neverthrow';
import BlockChat from './component/Block';
export const DEFAULT_CHAT_NAME = 'New Chat';
@@ -21,9 +21,13 @@ export const definition = defineBlock({
// Fetch the chat from dcs
const chatId = source.id;
const res = await cognitionApiServiceClient.getChat({ chat_id: chatId });
- if (isErr(res, 'UNAUTHORIZED')) return LoadErrors.INVALID;
- if (isErr(res)) return LoadErrors.MISSING;
- const [, chat] = res;
+ if (
+ res.isErr() &&
+ res.error.some((error) => error.code === 'UNAUTHORIZED')
+ )
+ return LoadErrors.INVALID;
+ if (res.isErr()) return LoadErrors.MISSING;
+ const chat = res.value;
if (intent === 'preload') {
return ok({
diff --git a/js/app/packages/block-code/definition.ts b/js/app/packages/block-code/definition.ts
index eca9df8931..ab591d8b31 100644
--- a/js/app/packages/block-code/definition.ts
+++ b/js/app/packages/block-code/definition.ts
@@ -4,8 +4,8 @@ import {
LoadErrors,
loadResult,
} from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
+import { err, ok } from 'neverthrow';
import BlockCode from './component/Block';
import { supportedExtensions } from './util/languageSupport';
@@ -32,8 +32,8 @@ export const definition = defineBlock({
documentId: source.id,
})
);
- if (isErr(document)) return document;
- const [, result] = document;
+ if (document.isErr()) return err(document.error);
+ const result = document.value;
return ok(result);
},
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index 216ec76856..17d227cd7c 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -11,7 +11,7 @@ import { Message } from '@core/component/Message';
import { toast } from '@core/component/Toast/Toast';
import { VideoPreview } from '@core/component/VideoPreview';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import { isErr } from '@core/util/maybeResult';
+
import { logger } from '@observability';
import { refetchSoupEntity } from '@queries/soup/cache';
import { emailClient } from '@service-email/client';
@@ -142,28 +142,28 @@ export function MessageContainer(props: MessageContainerProps) {
const response = await emailClient.getOrCreateAttachmentDocumentId({
id: dbId,
});
- if (isErr(response)) {
+ if (response.isErr()) {
toast.failure('Failed to get attachment. Please try again.');
return logger.error('Failed to get or create attachment document id', {
error: new Error(
- 'Failed to get or create attachment document id: ' + response[0]
+ 'Failed to get or create attachment document id: ' + response.error
),
});
}
- const { document_id } = response[1];
+ const { document_id } = response.value;
const maybeDocumentMetadata =
await storageServiceClient.getDocumentMetadata({
documentId: document_id,
});
- if (isErr(maybeDocumentMetadata)) {
+ if (maybeDocumentMetadata.isErr()) {
toast.failure('Failed to get attachment. Please try again.');
return logger.error(
'Failed to get or create attachment document metadata',
{
error: new Error(
'Failed to get or create attachment document metadata: ' +
- maybeDocumentMetadata[0]
+ maybeDocumentMetadata.error
),
}
);
diff --git a/js/app/packages/block-email/definition.ts b/js/app/packages/block-email/definition.ts
index d2c1521e09..09555de1c1 100644
--- a/js/app/packages/block-email/definition.ts
+++ b/js/app/packages/block-email/definition.ts
@@ -1,6 +1,6 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { fetchAndCacheThread } from '@queries/email/thread';
+import { ok } from 'neverthrow';
import EmailBlock from './component/Block';
export const definition = defineBlock({
@@ -19,19 +19,25 @@ export const definition = defineBlock({
return LoadErrors.MISSING;
}
- if (isErr(email)) {
- if (isErr(email, 'MISSING')) {
+ if (email.isErr()) {
+ if (email.error.some((error) => error.code === 'NOT_FOUND')) {
return LoadErrors.MISSING;
- } else if (isErr(email, 'UNAUTHORIZED')) {
+ } else if (
+ email.isErr() &&
+ email.error.some((error) => error.code === 'UNAUTHORIZED')
+ ) {
return LoadErrors.UNAUTHORIZED;
- } else if (isErr(email, 'GONE')) {
+ } else if (
+ email.isErr() &&
+ email.error.some((error) => error.code === 'GONE')
+ ) {
return LoadErrors.GONE;
} else {
return LoadErrors.INVALID;
}
}
- const [, emailData] = email;
+ const emailData = email.value;
return ok({
...emailData,
diff --git a/js/app/packages/block-email/signal/emailDraft.ts b/js/app/packages/block-email/signal/emailDraft.ts
index 8acc628c6f..3adca2271c 100644
--- a/js/app/packages/block-email/signal/emailDraft.ts
+++ b/js/app/packages/block-email/signal/emailDraft.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { logger } from '@observability/logger';
import { emailClient } from '@service-email/client';
import type {
@@ -14,23 +13,23 @@ export async function saveEmailDraft(
draft,
send_time: sendTime?.toISOString() ?? null,
});
- if (isErr(createRes)) {
- logger.error(new Error('Failed to save draft', { cause: createRes[0] }));
+ if (createRes.isErr()) {
+ logger.error(new Error('Failed to save draft', { cause: createRes.error }));
return false;
}
- if (!createRes[1].draft.db_id) {
+ if (!createRes.value.draft.db_id) {
logger.error(new Error('Draft save success but no draft id returned'));
return false;
}
- return createRes[1].draft.db_id;
+ return createRes.value.draft.db_id;
}
export async function deleteEmailDraft(draftId: string): Promise<boolean> {
const deleteRes = await emailClient.deleteDraft({ id: draftId });
- if (isErr(deleteRes)) {
+ if (deleteRes.isErr()) {
logger.error(
new Error('Failed to delete draft', {
- cause: new Error(`Failed to delete draft: ${deleteRes[0]}`),
+ cause: new Error(`Failed to delete draft: ${deleteRes.error}`),
})
);
return false;
diff --git a/js/app/packages/block-email/util/makeAttachmentPublic.ts b/js/app/packages/block-email/util/makeAttachmentPublic.ts
index a8381ebe63..95db67b7fb 100644
--- a/js/app/packages/block-email/util/makeAttachmentPublic.ts
+++ b/js/app/packages/block-email/util/makeAttachmentPublic.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { isErr } from '@core/util/maybeResult';
+
import { logger } from '@observability';
import { storageServiceClient } from '@service-storage/client';
@@ -7,8 +7,8 @@ export const makeAttachmentPublic = async (attachmentId: string) => {
const permissions = await storageServiceClient.getDocumentPermissions({
document_id: attachmentId,
});
- if (!isErr(permissions)) {
- if (permissions[1].isPublic) {
+ if (!permissions.isErr()) {
+ if (permissions.value.isPublic) {
return;
}
}
@@ -20,7 +20,7 @@ export const makeAttachmentPublic = async (attachmentId: string) => {
publicAccessLevel: 'view',
},
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
toast.success('Recipients can now view this file', {
subtext: 'File share permissions have been updated to public view-only',
});
@@ -28,6 +28,6 @@ export const makeAttachmentPublic = async (attachmentId: string) => {
toast.alert('Recipients may not be able to view this file', {
subtext: 'Please consult the document owner to change share permissions',
});
- logger.error('Failed to make attachment public', result);
+ logger.error('Failed to make attachment public', { errors: result.error });
}
};
diff --git a/js/app/packages/block-image/definition.ts b/js/app/packages/block-image/definition.ts
index 66d7d94bb5..570708fbe6 100644
--- a/js/app/packages/block-image/definition.ts
+++ b/js/app/packages/block-image/definition.ts
@@ -4,10 +4,10 @@ import {
LoadErrors,
loadResult,
} from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
+import { err, ok } from 'neverthrow';
import { lazy } from 'solid-js';
export const definition = defineBlock({
@@ -34,16 +34,16 @@ export const definition = defineBlock({
origin: source,
});
- if (isErr(maybeDocument)) return maybeDocument;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
- const [, documentResult] = maybeDocument;
+ const documentResult = maybeDocument.value;
const { documentMetadata, blobUrl, userAccessLevel } = documentResult;
const blobResult = await loadResult(fetchBinary(blobUrl, 'blob'));
- if (isErr(blobResult)) return blobResult;
- const [, blob] = blobResult;
+ if (blobResult.isErr()) return err(blobResult.error);
+ const blob = blobResult.value;
const dssFile = await makeFileFromBlob({
blob,
diff --git a/js/app/packages/block-md/comments/commentsResource.ts b/js/app/packages/block-md/comments/commentsResource.ts
index 7400ad0907..a84ed47845 100644
--- a/js/app/packages/block-md/comments/commentsResource.ts
+++ b/js/app/packages/block-md/comments/commentsResource.ts
@@ -5,7 +5,7 @@ import {
useBlockName,
} from '@core/block';
import { compareDateAsc } from '@core/util/date';
-import { isErr } from '@core/util/maybeResult';
+
import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
import { storageServiceClient } from '@service-storage/client';
import type { AnnotationIncrementalUpdate } from '@service-storage/generated/schemas/annotationIncrementalUpdate';
@@ -43,7 +43,7 @@ async function fetchComments() {
const commentThreads = await storageServiceClient.annotations.getComments({
documentId,
});
- return commentThreads[1]?.data ?? [];
+ return commentThreads.isOk() ? commentThreads.value.data : [];
}
function useHandleCreateComment() {
@@ -80,17 +80,17 @@ function useCreateComment() {
const handleCreateComment = useHandleCreateComment();
return async (body: CreateCommentRequest) => {
- const maybeResult = await storageServiceClient.annotations.createComment({
+ const result = await storageServiceClient.annotations.createComment({
documentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to create comment');
return null;
}
- const response = maybeResult[1];
+ const response = result.value;
handleCreateComment(response);
@@ -130,17 +130,17 @@ export function useEditCommentResource() {
const handleEditComment = useHandleEditComment();
return async (commentId: number, body: EditCommentRequest) => {
- const maybeResult = await storageServiceClient.annotations.editComment({
+ const result = await storageServiceClient.annotations.editComment({
commentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to edit comment');
return false;
}
- const [, response] = maybeResult;
+ const response = result.value;
handleEditComment(response);
@@ -188,17 +188,17 @@ export function useDeleteCommentResource() {
const handleDeleteComment = useHandleDeleteComment();
return async (commentId: number, body: DeleteCommentRequest) => {
- const maybeResult = await storageServiceClient.annotations.deleteComment({
+ const result = await storageServiceClient.annotations.deleteComment({
commentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to delete comment');
return;
}
- const [, response] = maybeResult;
+ const response = result.value;
return handleDeleteComment(response);
};
diff --git a/js/app/packages/block-md/component/ComposeTask.tsx b/js/app/packages/block-md/component/ComposeTask.tsx
index 72dc841e29..e330e0d71c 100644
--- a/js/app/packages/block-md/component/ComposeTask.tsx
+++ b/js/app/packages/block-md/component/ComposeTask.tsx
@@ -29,7 +29,7 @@ import { useUserId } from '@core/context/user';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { createTask } from '@core/util/create';
import { filterMap } from '@core/util/list';
-import { isErr } from '@core/util/maybeResult';
+
import { buildSimpleEntityUrl } from '@core/util/url';
import ArrowSquareOutIcon from '@phosphor/arrow-square-out.svg';
import SplitIcon from '@phosphor/square-half.svg';
@@ -284,10 +284,10 @@ export function ComposeTask(props: ComposeTaskProps) {
scope: 'system',
include_options: true,
});
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to fetch system properties');
}
- const [, data] = result;
+ const data = result.value;
return data;
},
staleTime: 1000 * 60 * 10, // TODO (seamus) Ask daniel what might make us wanna refetch this
diff --git a/js/app/packages/block-md/component/DispatchAgentMenu.tsx b/js/app/packages/block-md/component/DispatchAgentMenu.tsx
index 036e2dddc4..5c385cc0e7 100644
--- a/js/app/packages/block-md/component/DispatchAgentMenu.tsx
+++ b/js/app/packages/block-md/component/DispatchAgentMenu.tsx
@@ -6,7 +6,6 @@ import { toast } from '@core/component/Toast/Toast';
import { macroIdToEmail, tryMacroId } from '@core/user';
import { copyBranchNameToClipboard } from '@core/util/branchName';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import { isOk } from '@core/util/maybeResult';
import ClaudeIcon from '@icon/wide-claude.svg';
import CodexIcon from '@icon/wide-codex-ide.svg';
import CursorIcon from '@icon/wide-cursor-ide.svg';
@@ -41,10 +40,10 @@ async function generateTaskPrompt(
const result = await storageServiceClient.getDocumentBranchName({
documentId,
});
- if (!isOk(result)) {
+ if (!result.isOk()) {
throw new Error('Failed to fetch branch name');
}
- const { shortId, branchName } = result[1];
+ const { shortId, branchName } = result.value;
const lines: string[] = [];
diff --git a/js/app/packages/block-md/component/History.tsx b/js/app/packages/block-md/component/History.tsx
index 0f01575e4c..2a306a6aff 100644
--- a/js/app/packages/block-md/component/History.tsx
+++ b/js/app/packages/block-md/component/History.tsx
@@ -23,7 +23,7 @@ import { toast } from '@core/component/Toast/Toast';
import { UserIcon } from '@core/component/UserIcon';
import { TOKENS } from '@core/hotkey/tokens';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import { isErr } from '@core/util/maybeResult';
+
import { CommentNode, InlineSearchNode, peerIdPlugin } from '@lexical-core';
import ClockIcon from '@phosphor/clock-counter-clockwise.svg';
import { storageServiceClient } from '@service-storage/client';
@@ -59,9 +59,9 @@ async function forkDocumentAtVersion(
syncServiceVersion: version,
});
- if (isErr(response)) return;
+ if (response.isErr()) return;
- const [, data] = response;
+ const data = response.value;
return data.documentId;
}
@@ -73,12 +73,12 @@ async function getLoroDocFromId(documentId: string) {
const doc = new LoroDoc();
- if (isErr(maybeSnapshot)) {
+ if (maybeSnapshot.isErr()) {
console.error("Couldn't get snapshot", maybeSnapshot);
return doc;
}
- const [, snapshot] = maybeSnapshot;
+ const snapshot = maybeSnapshot.value;
doc.import(snapshot);
return doc;
diff --git a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
index f7a12644c1..4f7bca861f 100644
--- a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
+++ b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
@@ -28,7 +28,7 @@ import { UserIcon } from '@core/component/UserIcon';
import type { Entity, EntityType } from '@core/types';
import { tryMacroId, useDisplayName } from '@core/user';
import { type DateValue, formatDate } from '@core/util/date';
-import { isErr } from '@core/util/maybeResult';
+
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
import { useNotificationsForEntity } from '@notifications';
import Plus from '@phosphor/plus.svg';
@@ -517,12 +517,12 @@ function ReferencesSectionConditional(props: { documentId: string }) {
entity_id: id,
});
- if (isErr(response)) {
+ if (response.isErr()) {
console.error(response);
return [];
}
- return response[1].references;
+ return response.value.references;
}
);
diff --git a/js/app/packages/block-md/definition.ts b/js/app/packages/block-md/definition.ts
index 0c83455da5..88775c8a64 100644
--- a/js/app/packages/block-md/definition.ts
+++ b/js/app/packages/block-md/definition.ts
@@ -6,12 +6,12 @@ import {
} from '@core/block';
import { createLoroManager } from '@core/collab/manager';
import { ENABLE_MARKDOWN_LIVE_COLLABORATION } from '@core/constant/featureFlags';
-import { isErr, ok } from '@core/util/maybeResult';
import { MARKDOWN_LORO_SCHEMA } from '@lexical-core/markdown-loro-schema';
import { waitForDocumentSyncServiceReady } from '@queries/storage/document-location';
import { storageServiceClient } from '@service-storage/client';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
import { createSyncServiceSource } from '@service-sync/source';
+import { err, ok } from 'neverthrow';
import MarkdownBlock from './component/Block';
import type { MarkdownRewriteOutput } from './signal/rewriteSignal';
@@ -42,18 +42,18 @@ export const definition = defineBlock({
}),
]);
- if (isErr(maybeToken)) {
+ if (maybeToken.isErr()) {
return LoadErrors.UNAUTHORIZED;
}
- const [, { token }] = maybeToken;
+ const { token } = maybeToken.value;
- if (isErr(maybeDocument)) return maybeDocument;
- if (isErr(maybeLocation)) return maybeLocation;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
+ if (maybeLocation.isErr()) return err(maybeLocation.error);
- const [, documentResult] = maybeDocument;
+ const documentResult = maybeDocument.value;
const { documentMetadata, userAccessLevel } = documentResult;
- let [, { data: location }] = maybeLocation;
+ let { data: location } = maybeLocation.value;
if (
location.type === 'presignedUrl' &&
@@ -98,7 +98,7 @@ export const definition = defineBlock({
initialSync.snapshot
);
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to initialize doc state', result);
return LoadErrors.INVALID;
}
diff --git a/js/app/packages/block-md/signal/save.ts b/js/app/packages/block-md/signal/save.ts
index ebb16671f0..2a0af31ad2 100644
--- a/js/app/packages/block-md/signal/save.ts
+++ b/js/app/packages/block-md/signal/save.ts
@@ -5,7 +5,7 @@ import {
getSaveState,
} from '@core/component/LexicalMarkdown/utils';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import { isErr } from '@core/util/maybeResult';
+
import { utf8Encode } from '@core/util/string';
import { createRenameDssEntityMutation } from '@macro-entity';
import { refetchHistory } from '@queries/history/history';
@@ -34,7 +34,7 @@ export function useSaveMarkdownDocument() {
file: new Blob([buffer], { type: 'text/markdown' }),
});
- if (isErr(saveRes)) {
+ if (saveRes.isErr()) {
console.error('error on markdown save');
return;
}
diff --git a/js/app/packages/block-pdf/component/TopBar.tsx b/js/app/packages/block-pdf/component/TopBar.tsx
index ca595dcf28..d0d088c9f7 100644
--- a/js/app/packages/block-pdf/component/TopBar.tsx
+++ b/js/app/packages/block-pdf/component/TopBar.tsx
@@ -139,8 +139,8 @@ export function TopBar() {
const downloadDocx = createCallback(async () => {
if (!isAuth()) return openLoginModal();
- const [_, data] = await storageServiceClient.exportDocument({ documentId });
- if (!data) {
+ const data = await storageServiceClient.exportDocument({ documentId });
+ if (data.isErr()) {
return toast.failure('Unable to download file');
}
@@ -148,7 +148,7 @@ export function TopBar() {
try {
// Fetch the file from the presigned URL
- const response = await platformFetch(data.presigned_url);
+ const response = await platformFetch(data.value.presigned_url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
diff --git a/js/app/packages/block-pdf/definition.ts b/js/app/packages/block-pdf/definition.ts
index 90fa665f6b..cdc10f96d9 100644
--- a/js/app/packages/block-pdf/definition.ts
+++ b/js/app/packages/block-pdf/definition.ts
@@ -4,9 +4,11 @@ import {
LoadErrors,
loadResult,
} from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
+import type { GetDocumentResponseDataViewLocation } from '@service-storage/generated/schemas/getDocumentResponseDataViewLocation';
import { fetchBinary } from '@service-storage/util/fetchBinary';
+import { err, ok } from 'neverthrow';
+import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
import BlockPdf from './component/Block';
import PdfJsWorker from './PdfViewer/pdfjs-worker?worker';
@@ -35,13 +37,13 @@ export const definition = defineBlock({
origin: source,
});
- if (isErr(maybeDocument)) return maybeDocument;
- const [, { blobUrl, ...documentFile }] = maybeDocument;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
+ const { blobUrl, ...documentFile } = maybeDocument.value;
const maybeBlob = await loadResult(fetchBinary(blobUrl, 'blob'));
- if (isErr(maybeBlob)) return maybeBlob;
+ if (maybeBlob.isErr()) return err(maybeBlob.error);
- const [, blob] = maybeBlob;
+ const blob = maybeBlob.value;
const buffer = await blob.arrayBuffer();
const data = new Uint8Array(buffer);
@@ -58,4 +60,7 @@ export const definition = defineBlock({
},
});
-export type PdfBlockData = ExtractLoadType<(typeof definition)['load']>;
+export type PdfBlockData = ExtractLoadType<(typeof definition)['load']> & {
+ documentProxy: PDFDocumentProxy;
+ viewLocation?: GetDocumentResponseDataViewLocation;
+};
diff --git a/js/app/packages/block-pdf/store/commentsResource.ts b/js/app/packages/block-pdf/store/commentsResource.ts
index ea89d4150c..ea6e2593d1 100644
--- a/js/app/packages/block-pdf/store/commentsResource.ts
+++ b/js/app/packages/block-pdf/store/commentsResource.ts
@@ -8,7 +8,7 @@ import {
} from '@core/block';
import { useUserId } from '@core/context/user';
import { compareDateAsc } from '@core/util/date';
-import { isErr } from '@core/util/maybeResult';
+
import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
import { storageServiceClient } from '@service-storage/client';
import type { AnnotationIncrementalUpdate } from '@service-storage/generated/schemas/annotationIncrementalUpdate';
@@ -53,7 +53,7 @@ async function fetchComments() {
const commentThreads = await storageServiceClient.annotations.getComments({
documentId,
});
- return commentThreads[1]?.data ?? [];
+ return commentThreads.isOk() ? commentThreads.value.data : [];
}
async function fetchAnchors() {
@@ -61,7 +61,7 @@ async function fetchAnchors() {
const anchors = await storageServiceClient.annotations.getAnchors({
documentId,
});
- return anchors[1]?.data ?? [];
+ return anchors.isOk() ? anchors.value.data : [];
}
function useHandleCreateUnthreadedAnchor() {
@@ -77,17 +77,17 @@ function useCreateUnthreadedAnchor() {
const handleCreateUnthreadedAnchor = useHandleCreateUnthreadedAnchor();
return async (body: CreateUnthreadedAnchorRequest) => {
- const maybeResult = await storageServiceClient.annotations.createAnchor({
+ const result = await storageServiceClient.annotations.createAnchor({
documentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to create anchor');
return false;
}
- const [, response] = maybeResult;
+ const response = result.value;
handleCreateUnthreadedAnchor(response);
@@ -113,16 +113,16 @@ function useDeleteUnthreadedAnchor() {
const handleDeleteUnthreadedAnchor = useHandleDeleteUnthreadedAnchor();
return async (body: DeleteUnthreadedAnchorRequest) => {
- const maybeResult = await storageServiceClient.annotations.deleteAnchor({
+ const result = await storageServiceClient.annotations.deleteAnchor({
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to delete anchor');
return false;
}
- const [, response] = maybeResult;
+ const response = result.value;
handleDeleteUnthreadedAnchor(response);
@@ -145,16 +145,16 @@ function useEditAnchor() {
const handleEditAnchor = useHandleEditAnchor();
return async (body: EditAnchorRequest) => {
- const maybeResult = await storageServiceClient.annotations.editAnchor({
+ const result = await storageServiceClient.annotations.editAnchor({
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to edit anchor');
return false;
}
- const [, response] = maybeResult;
+ const response = result.value;
handleEditAnchor(response);
@@ -207,17 +207,17 @@ function useCreateComment() {
return null;
}
- const maybeResult = await storageServiceClient.annotations.createComment({
+ const result = await storageServiceClient.annotations.createComment({
documentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to create comment');
return null;
}
- const response = maybeResult[1];
+ const response = result.value;
handleCreateComment(response);
@@ -257,17 +257,17 @@ export function useEditCommentResource() {
const handleEditComment = useHandleEditComment();
return async (commentId: number, body: EditCommentRequest) => {
- const maybeResult = await storageServiceClient.annotations.editComment({
+ const result = await storageServiceClient.annotations.editComment({
commentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to edit comment');
return false;
}
- const [, response] = maybeResult;
+ const response = result.value;
handleEditComment(response);
@@ -319,17 +319,17 @@ export function useDeleteCommentResource() {
const handleDeleteComment = useHandleDeleteComment();
return async (commentId: number, body: DeleteCommentRequest) => {
- const maybeResult = await storageServiceClient.annotations.deleteComment({
+ const result = await storageServiceClient.annotations.deleteComment({
commentId,
body,
});
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
console.error('Unable to delete comment');
return false;
}
- const [, response] = maybeResult;
+ const response = result.value;
handleDeleteComment(response);
diff --git a/js/app/packages/block-pdf/websocket/export.ts b/js/app/packages/block-pdf/websocket/export.ts
index 107fcbfe71..709a827d8d 100644
--- a/js/app/packages/block-pdf/websocket/export.ts
+++ b/js/app/packages/block-pdf/websocket/export.ts
@@ -20,12 +20,12 @@ export function exportPdf({
},
action: 'pdf_export',
processResult: async (data) => {
- const [, blob] = await fetchBinary(data.resultUrl, 'blob');
- if (!blob) {
- console.error('unable to retrieve blob');
+ const blob = await fetchBinary(data.resultUrl, 'blob');
+ if (blob.isErr()) {
+ console.error('unable to retrieve blob', blob.error);
return undefined;
}
- return blob;
+ return blob.value;
},
handleSuccess: async (blob) => {
return makeFile({
diff --git a/js/app/packages/block-pdf/websocket/preprocess.ts b/js/app/packages/block-pdf/websocket/preprocess.ts
index 0480d71d41..04b6ed6a5f 100644
--- a/js/app/packages/block-pdf/websocket/preprocess.ts
+++ b/js/app/packages/block-pdf/websocket/preprocess.ts
@@ -2,7 +2,7 @@ import type {
PreprocessInvoke,
PreprocessResponseData,
} from '@coparse/document-processing-types';
-import { isErr } from '@core/util/maybeResult';
+
import {
type ProcessingResultResponseType,
storageServiceClient,
@@ -17,12 +17,11 @@ export async function preprocess({
documentVersionId: number;
}) {
try {
- const [, parseResult] =
- await storageServiceClient.getDocumentProcessingResult({
- documentId,
- type: 'PREPROCESS',
- });
- if (parseResult) return parseResult.preprocess;
+ const parseResult = await storageServiceClient.getDocumentProcessingResult({
+ documentId,
+ type: 'PREPROCESS',
+ });
+ if (parseResult.isOk()) return parseResult.value.preprocess;
} catch (e) {
console.error('preprocess fetch error', e);
}
@@ -48,10 +47,10 @@ export async function preprocess({
jobId,
type: 'PREPROCESS',
});
- if (isErr(result)) {
+ if (result.isErr()) {
throw result;
}
- return result[1].preprocess;
+ return result.value.preprocess;
},
});
}
diff --git a/js/app/packages/block-project/definition.ts b/js/app/packages/block-project/definition.ts
index 5754bf9438..a7ba000bc6 100644
--- a/js/app/packages/block-project/definition.ts
+++ b/js/app/packages/block-project/definition.ts
@@ -4,10 +4,10 @@ import {
LoadErrors,
loadResult,
} from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
import type { GetProjectResponseData } from '@service-storage/generated/schemas/getProjectResponseData';
import { ProjectType } from '@service-storage/generated/schemas/projectType';
+import { ok } from 'neverthrow';
import { lazy } from 'solid-js';
export const definition = defineBlock({
@@ -48,10 +48,10 @@ export const definition = defineBlock({
const maybeProject = await loadResult(
storageServiceClient.projects.getProject({ id: source.id })
);
- if (isErr(maybeProject)) {
+ if (maybeProject.isErr()) {
return maybeProject;
}
- const [, project] = maybeProject;
+ const project = maybeProject.value;
return ok(project);
}
diff --git a/js/app/packages/block-unknown/definition.ts b/js/app/packages/block-unknown/definition.ts
index 9894851eb7..9cef4a04f4 100644
--- a/js/app/packages/block-unknown/definition.ts
+++ b/js/app/packages/block-unknown/definition.ts
@@ -4,8 +4,8 @@ import {
LoadErrors,
loadResult,
} from '@core/block';
-import { isErr, ok } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
+import { err, ok } from 'neverthrow';
import BlockUnknown from './component/Block';
export const definition = defineBlock({
@@ -25,9 +25,9 @@ export const definition = defineBlock({
});
}
- if (isErr(maybeDocument)) return maybeDocument;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
- const [, documentResult] = maybeDocument;
+ const documentResult = maybeDocument.value;
const { documentMetadata, userAccessLevel } = documentResult;
diff --git a/js/app/packages/block-unknown/signal/blockData.ts b/js/app/packages/block-unknown/signal/blockData.ts
index 8304e86cec..1232ea459f 100644
--- a/js/app/packages/block-unknown/signal/blockData.ts
+++ b/js/app/packages/block-unknown/signal/blockData.ts
@@ -1,5 +1,5 @@
import { blockDataSignalAs, useBlockId } from '@core/block';
-import { isErr } from '@core/util/maybeResult';
+
import { fetchPresigned } from '@service-storage/util/fetchPresigned';
import { getPresignedUrl } from '@service-storage/util/presignedUrl';
import { createMemo } from 'solid-js';
@@ -26,12 +26,12 @@ export const useGetFileBlob = () => {
const getPresignedUrl = useGetFileUrl();
const fetchFromPresignedUrl = async (url: string) => {
- const maybeResult = await fetchPresigned(url, 'blob');
- if (isErr(maybeResult)) {
+ const result = await fetchPresigned(url, 'blob');
+ if (result.isErr()) {
throw new Error('unable to fetch from presigned url');
}
- const [, blob] = maybeResult;
+ const blob = result.value;
if (!blob) {
throw new Error('no blob data');
}
diff --git a/js/app/packages/block-video/definition.ts b/js/app/packages/block-video/definition.ts
index 93ec23130b..578c64ecdb 100644
--- a/js/app/packages/block-video/definition.ts
+++ b/js/app/packages/block-video/definition.ts
@@ -6,11 +6,11 @@ import {
type MimeType,
} from '@core/block';
import { ENABLE_VIDEO_BLOCK } from '@core/constant/featureFlags';
-import { isErr, ok } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
import type { DocumentMetadataFileType } from '@service-storage/generated/schemas/documentMetadataFileType';
import { getPresignedUrl } from '@service-storage/util/presignedUrl';
import { toast } from 'core/component/Toast/Toast';
+import { err, ok } from 'neverthrow';
import BlockVideo from './component/Block';
export const VIDEO_MIMES: Record<
@@ -68,9 +68,9 @@ export const definition = defineBlock({
});
}
- if (isErr(maybeDocument)) return maybeDocument;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
- const [, documentResult] = maybeDocument;
+ const documentResult = maybeDocument.value;
const { documentMetadata, userAccessLevel } = documentResult;
@@ -97,4 +97,6 @@ export const definition = defineBlock({
},
});
-export type VideoFileData = ExtractLoadType<(typeof definition)['load']>;
+export type VideoFileData = ExtractLoadType<(typeof definition)['load']> & {
+ videoUrl?: string;
+};
diff --git a/js/app/packages/block-video/signal/blockData.ts b/js/app/packages/block-video/signal/blockData.ts
index 9e62e8d788..5f09707dcf 100644
--- a/js/app/packages/block-video/signal/blockData.ts
+++ b/js/app/packages/block-video/signal/blockData.ts
@@ -1,5 +1,5 @@
import { blockDataSignalAs, useBlockId } from '@core/block';
-import { isErr } from '@core/util/maybeResult';
+
import {
type FetchProgress,
fetchPresigned,
@@ -37,14 +37,14 @@ export const useGetFileBlob = () => {
url: string,
options?: GetBlobOptions
) => {
- const maybeResult = options?.onProgress
+ const result = options?.onProgress
? await fetchPresignedBlobWithProgress(url, options.onProgress)
: await fetchPresigned(url, 'blob');
- if (isErr(maybeResult)) {
+ if (result.isErr()) {
throw new Error('unable to fetch from presigned url');
}
- const [, blob] = maybeResult;
+ const blob = result.value;
if (!blob) {
throw new Error('no blob data');
}
diff --git a/js/app/packages/channel/Call/use-call.ts b/js/app/packages/channel/Call/use-call.ts
index 992df86f75..8f1b71b4d9 100644
--- a/js/app/packages/channel/Call/use-call.ts
+++ b/js/app/packages/channel/Call/use-call.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { useLeaveCallMutation } from '@queries/call/call';
import { queryClient } from '@queries/client';
import { callServiceClient } from '@service-call/client';
diff --git a/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx b/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx
index 47c208d2a5..ddbd16df0a 100644
--- a/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx
+++ b/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx
@@ -2,7 +2,7 @@ import { useSplitLayout } from '@app/component/split-layout/layout';
import { useChannelType } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import { idToEmail } from '@core/user';
-import { isOk } from '@core/util/maybeResult';
+
import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';
import {
useAddParticipantsMutation,
@@ -65,7 +65,7 @@ export function ChannelParticipantsTab(props: { channelId: string }) {
const result = await commsServiceClient.getOrCreateDirectMessage({
recipient_id: participantId,
});
- const channelId = isOk(result) && result[1]?.channel_id;
+ const channelId = result.isOk() && result.value?.channel_id;
if (channelId) {
replaceOrInsertSplit({
diff --git a/js/app/packages/core/auth/sso.ts b/js/app/packages/core/auth/sso.ts
index b570f7a434..f0ea481fe8 100644
--- a/js/app/packages/core/auth/sso.ts
+++ b/js/app/packages/core/auth/sso.ts
@@ -1,7 +1,7 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
-import { isOk } from '@core/util/maybeResult';
+
import { getNativeMobilePlatform } from '@core/util/platform';
import { invalidateAllAfterLogin } from '@queries/auth/user-info';
import { authServiceClient } from '@service-auth/client';
@@ -60,7 +60,7 @@ export async function startSsoLogin(
session_code: result.token,
});
- if (isOk(res)) {
+ if (res.isOk()) {
await invalidateAllAfterLogin();
return true;
}
diff --git a/js/app/packages/core/block.ts b/js/app/packages/core/block.ts
index 227187395d..dbe6d1062b 100644
--- a/js/app/packages/core/block.ts
+++ b/js/app/packages/core/block.ts
@@ -5,6 +5,7 @@ import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
import type { GetDocumentResponseData } from '@service-storage/generated/schemas/getDocumentResponseData';
import type { Project } from '@service-storage/generated/schemas/project';
+import { err, ok, type Result } from 'neverthrow';
import type {
Accessor,
Component,
@@ -34,12 +35,7 @@ import { createStore, type SetStoreFunction, type Store } from 'solid-js/store';
import { ENABLE_PDF_MULTISPLIT } from './constant/featureFlags';
import { blockDataSignal } from './internal/BlockLoader';
import type { Source, SourcePreload } from './source';
-import {
- err,
- isErr,
- type MaybeResult,
- type ObjectLike,
-} from './util/maybeResult';
+import type { ObjectLike, ResultError } from './util/result';
/**
* List of valid block types that can be used in the application.
@@ -170,42 +166,62 @@ export const ValidNestingCombinations: BlockCombinationRules = {
};
export const LoadErrors = {
- UNAUTHORIZED: err('UNAUTHORIZED', 'Unauthorized access'),
- MISSING: err('MISSING', 'Not found'),
- INVALID: err('INVALID', 'Unable to load invalid document'),
- GONE: err('GONE', 'Document no longer exists'),
+ UNAUTHORIZED: err<never, ResultError<'UNAUTHORIZED'>[]>([
+ { code: 'UNAUTHORIZED', message: 'Unauthorized access' },
+ ]),
+ MISSING: err<never, ResultError<'MISSING'>[]>([
+ { code: 'MISSING', message: 'Not found' },
+ ]),
+ INVALID: err<never, ResultError<'INVALID'>[]>([
+ { code: 'INVALID', message: 'Unable to load invalid document' },
+ ]),
+ GONE: err<never, ResultError<'GONE'>[]>([
+ { code: 'GONE', message: 'Document no longer exists' },
+ ]),
} as const;
type LoadErrorCodes = keyof typeof LoadErrors;
/**
- * Converts a MaybeResult to a MaybeResult with a load error code.
+ * Converts a Result to a Result with a load error code.
* @template T - The type of the input result value.
- * @param {MaybeResult<string, T>} maybeResult - The result to convert.
- * @returns {MaybeResult<keyof typeof LoadErrors, T>} A new MaybeResult with a load error code.
+ * @param {Result<T, ResultError<string>[]>} result - The result to convert.
+ * @returns {Result<T, ResultError<keyof typeof LoadErrors>[]>} A new Result with a load error code.
*/
export function toLoadResult<E extends string, T extends ObjectLike>(
- maybeResult: MaybeResult<E, T>
-): MaybeResult<keyof typeof LoadErrors, T> {
- if (isErr(maybeResult, 'GONE')) return LoadErrors.GONE;
- if (isErr(maybeResult, 'UNAUTHORIZED')) return LoadErrors.UNAUTHORIZED;
- if (isErr(maybeResult, 'NOT_FOUND')) return LoadErrors.MISSING;
- if (isErr(maybeResult)) return LoadErrors.INVALID;
- return maybeResult;
+ result: Result<T, ResultError<E>[]>
+): Result<T, ResultError<keyof typeof LoadErrors>[]> {
+ if (result.isErr() && result.error.some((error) => error.code === 'GONE')) {
+ return err(LoadErrors.GONE.error);
+ }
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'UNAUTHORIZED')
+ ) {
+ return err(LoadErrors.UNAUTHORIZED.error);
+ }
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'NOT_FOUND')
+ ) {
+ return err(LoadErrors.MISSING.error);
+ }
+ if (result.isErr()) return err(LoadErrors.INVALID.error);
+ return ok(result.value);
}
/**
* Awaits a load result and returns a new load result with the same value or a load error.
* @template T - The type of the input result value.
- * @param {Promise<MaybeResult<string, T>>} result - The result to await.
- * @returns {Promise<MaybeResult<keyof typeof LoadErrors, T>>} A new MaybeResult with the same value or a load error.
+ * @param {Promise<Result<T, ResultError<string>[]>>} result - The result to await.
+ * @returns {Promise<Result<T, ResultError<keyof typeof LoadErrors>[]>>} A new Result with the same value or a load error.
*/
export async function loadResult<
- T extends Promise<MaybeResult<string, ObjectLike>>,
+ T extends Promise<Result<ObjectLike, ResultError<string>[]>>,
>(
result: T
): Promise<
- MaybeResult<keyof typeof LoadErrors, ExtractSuccessType<Awaited<T>>>
+ Result<ExtractSuccessType<Awaited<T>>, ResultError<keyof typeof LoadErrors>[]>
> {
return toLoadResult(await result) as any; // any because TypeScript gets confused and loses the ObjectLike's specific type
}
@@ -214,17 +230,17 @@ export async function loadResult<
* Maps over an ok result, or passes through a load error.
* @template T - The type of the input result value.
* @template U - The type of the output result value.
- * @param {MaybeResult<string, T>} result - The result to map.
+ * @param {Result<T, ResultError<string>[]>} result - The result to map.
* @param {(value: T) => U} fn - The function to apply to the ok value.
- * @returns {MaybeResult<LoadErrorCodes, U>} A new MaybeResult with the mapped value or a load error.
+ * @returns {Result<U, ResultError<LoadErrorCodes>[]>} A new Result with the mapped value or a load error.
*/
export function mapLoadResult<T extends ObjectLike, U extends ObjectLike>(
- result: MaybeResult<string, T>,
+ result: Result<T, ResultError<string>[]>,
fn: (value: T) => U
-): MaybeResult<LoadErrorCodes, U> {
- const [error, data] = toLoadResult(result);
- if (error) return [error, null];
- return [null, fn(data)];
+): Result<U, ResultError<LoadErrorCodes>[]> {
+ const loadResult = toLoadResult(result);
+ if (loadResult.isErr()) return err(loadResult.error);
+ return ok(fn(loadResult.value));
}
// Magic type that when used at sites where generic types are inferred from, will prevent those sites from being involved in the inference.
@@ -253,17 +269,18 @@ export type LoadFunction<
source: NoInfer<S>,
intent: Intent
) => Promise<
- MaybeResult<keyof typeof LoadErrors, S extends Source ? T | P : T>
+ Result<S extends Source ? T | P : T, ResultError<keyof typeof LoadErrors>[]>
>;
-type ExtractSuccessType<T> = T extends [null, infer S]
- ? Exclude<S, SourcePreload<{}>>
- : never;
+type ExtractSuccessType<T> =
+ T extends Result<infer S, ResultError<any>[]>
+ ? Exclude<S, { type: 'preload' }>
+ : never;
/**
* Extracts the non-error, non-preload return type of a load function.
*
- * This utility type unwraps the Promise, extracts the success type from MaybeResult,
+ * This utility type unwraps the Promise, extracts the success type from Result,
* and excludes the SourcePreload type. It's useful for getting the actual data type
* returned by a load function in the successful, non-preload case.
*
@@ -274,7 +291,7 @@ type ExtractSuccessType<T> = T extends [null, infer S]
* const definition = defineBlock({
* // ... other properties ...
* async load(source, intent) {
- * // Implementation that returns Promise<MaybeResult<Error, Data | Preload>>
+ * // Implementation that returns Promise<Result<Data | Preload, ResultError<Error>[]>>
* },
* });
*
diff --git a/js/app/packages/core/collab/engine.ts b/js/app/packages/core/collab/engine.ts
index eddfa7c792..bae829f8cd 100644
--- a/js/app/packages/core/collab/engine.ts
+++ b/js/app/packages/core/collab/engine.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { type InferType, SyncDirection } from '@loro-mirror/packages/core/src';
import { logger } from '@observability/logger';
import { Mutex } from 'async-mutex';
@@ -91,7 +90,7 @@ export function createSyncEngine<
await syncLock.runExclusive(async () => {
let importResult = loroManager.importUpdate(update);
await Promise.resolve();
- if (isErr(importResult)) {
+ if (importResult.isErr()) {
logger.error('failed to import remote update', {
resolution: 'reset engine',
scope: 'sync_engine',
@@ -140,7 +139,7 @@ export function createSyncEngine<
const syncResult = await loroManager.syncToLoro(state);
// Failed to sync, try to reset the engine
- if (isErr(syncResult)) {
+ if (syncResult.isErr()) {
let error = syncResult;
logger.error('failed to sync state to remote', {
resolution: 'reset engine',
@@ -176,7 +175,7 @@ export function createSyncEngine<
}
let resetResult = await loroManager.reset(snapshot.value);
- if (isErr(resetResult)) {
+ if (resetResult.isErr()) {
logger.error('failed to reset engine or loro manager', {
resolution: 'fail',
scope: 'sync_engine',
diff --git a/js/app/packages/core/collab/manager.ts b/js/app/packages/core/collab/manager.ts
index d278c1ae82..0399e5de32 100644
--- a/js/app/packages/core/collab/manager.ts
+++ b/js/app/packages/core/collab/manager.ts
@@ -1,11 +1,5 @@
-import {
- err,
- isErr,
- type MaybeError,
- type MaybeResult,
- ok,
- onlyErr,
-} from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
+
import {
type InferType,
Mirror,
@@ -21,6 +15,7 @@ import {
type Side,
type VersionVector,
} from 'loro-crdt';
+import { err, ok, type Result } from 'neverthrow';
import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
import type { GenericRootSchema, LoroRawUpdate } from './shared';
@@ -139,56 +134,62 @@ export type LoroManager<S extends GenericRootSchema = GenericRootSchema> = {
* └───────────┘
*
* @param state - The state to sync to loro
- * @returns maybeError - The error if syncing to loro failed
+ * @returns result - The error if syncing to loro failed
*
* */
- syncToLoro(state: InferType<S>): Promise<MaybeError<LoroManagerError>>;
+ syncToLoro(
+ state: InferType<S>
+ ): Promise<Result<void, ResultError<LoroManagerError>[]>>;
/** Retrieve all loro container ids */
- getAllContainerIds(): MaybeResult<LoroManagerError, ContainerID[]>;
+ getAllContainerIds(): Result<ContainerID[], ResultError<LoroManagerError>[]>;
/** Retrieve a LoroUpdate with all relavent events/data since the given version vector
*
* @param lastVersionVector - The last version vector to sync from
- * @returns maybeResult - The update if it exists, or an error if it doesn't
+ * @returns result - The update if it exists, or an error if it doesn't
* */
getUpdateSince(
lastVersionVector: VersionVector
- ): MaybeResult<LoroManagerError, Uint8Array | undefined>;
+ ): Result<Uint8Array | undefined, ResultError<LoroManagerError>[]>;
/** Initializes the manager from a snapshot
*
* If this is successful, it will set isInitialized to true
*
* @param snapshot - The snapshot to initialize from
- * @returns maybeError - The error if initializing from the snapshot failed
+ * @returns result - The error if initializing from the snapshot failed
* */
initializeFromSnapshot(
snapshot: LoroRawUpdate
- ): Promise<MaybeError<LoroManagerError>>;
+ ): Promise<Result<void, ResultError<LoroManagerError>[]>>;
/** Imports a single loro update
*
* @param update - The update to import
- * @returns maybeError - The error if importing the update failed
+ * @returns result - The error if importing the update failed
* */
- importUpdate(update: LoroRawUpdate): MaybeResult<LoroManagerError, boolean>;
+ importUpdate(
+ update: LoroRawUpdate
+ ): Result<boolean, ResultError<LoroManagerError>[]>;
/** Imports multiple loro updates at once
*
* @param updates - The updates to import
- * @returns maybeError - The error if importing the updates failed
+ * @returns result - The error if importing the updates failed
* */
importBatchUpdates(
updates: LoroRawUpdate[]
- ): MaybeResult<LoroManagerError, boolean>;
+ ): Result<boolean, ResultError<LoroManagerError>[]>;
/** Resets the manager to a new state
*
* @param snapshot - The snapshot to reset to
- * @returns maybeError - The error if resetting the manager failed
+ * @returns result - The error if resetting the manager failed
* */
- reset(snapshot: LoroRawUpdate): Promise<MaybeError<LoroManagerError>>;
+ reset(
+ snapshot: LoroRawUpdate
+ ): Promise<Result<void, ResultError<LoroManagerError>[]>>;
/** Returns the current version of the manager */
getVersion(): VersionVector;
@@ -201,16 +202,16 @@ export type LoroManager<S extends GenericRootSchema = GenericRootSchema> = {
/** Returns the container with the given id if it exists */
getContainerById(
id: ContainerID
- ): MaybeResult<LoroManagerError, Container | undefined>;
+ ): Result<Container | undefined, ResultError<LoroManagerError>[]>;
/** Returns the current cursor position for the given LoroCursor within its container */
- getCursorPos(cursor: Cursor): MaybeResult<
- LoroManagerError,
+ getCursorPos(cursor: Cursor): Result<
{
update?: Cursor;
offset: number;
side: Side;
- }
+ },
+ ResultError<LoroManagerError>[]
>;
};
@@ -246,7 +247,7 @@ export function createLoroManager<S extends GenericRootSchema>(
const importUpdate = (
update: LoroRawUpdate
- ): MaybeResult<LoroManagerError, boolean> => {
+ ): Result<boolean, ResultError<LoroManagerError>[]> => {
let importStatus;
try {
@@ -254,17 +255,21 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to import update', e);
pushError(LoroManagerError.ImportFailed);
- return err(
- LoroManagerError.ImportFailed,
- `Failed to import update: ${e}`
- );
+ return err([
+ {
+ code: LoroManagerError.ImportFailed,
+ message: `Failed to import update: ${e}`,
+ },
+ ]);
}
const didChange = Object.keys(importStatus.success).length > 0;
if (Object.keys(importStatus.pending ?? {}).length > 0) {
pushError(LoroManagerError.ImportFailed);
- return err(LoroManagerError.ImportFailed, 'Import failed');
+ return err([
+ { code: LoroManagerError.ImportFailed, message: 'Import failed' },
+ ]);
}
return ok(didChange);
@@ -272,7 +277,7 @@ export function createLoroManager<S extends GenericRootSchema>(
const importBatchUpdates = (
updates: LoroRawUpdate[]
- ): MaybeResult<LoroManagerError, boolean> => {
+ ): Result<boolean, ResultError<LoroManagerError>[]> => {
let importStatus;
try {
@@ -280,17 +285,21 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to import update', e);
pushError(LoroManagerError.ImportFailed);
- return err(
- LoroManagerError.ImportFailed,
- `Failed to import update: ${e}`
- );
+ return err([
+ {
+ code: LoroManagerError.ImportFailed,
+ message: `Failed to import update: ${e}`,
+ },
+ ]);
}
const didChange = Object.keys(importStatus.success).length > 0;
if (Object.keys(importStatus.pending ?? {}).length > 0) {
pushError(LoroManagerError.ImportFailed);
- return err(LoroManagerError.ImportFailed, 'Import failed');
+ return err([
+ { code: LoroManagerError.ImportFailed, message: 'Import failed' },
+ ]);
}
return ok(didChange);
@@ -298,12 +307,12 @@ export function createLoroManager<S extends GenericRootSchema>(
const initializeFromSnapshot = async (
snapshot: LoroRawUpdate
- ): Promise<MaybeError<LoroManagerError>> => {
+ ): Promise<Result<void, ResultError<LoroManagerError>[]>> => {
const importResult = importUpdate(snapshot);
- if (isErr(importResult)) {
- let error = importResult[0];
- return onlyErr(error[0].code, error[0].message);
+ if (importResult.isErr()) {
+ const [error] = importResult.error;
+ return err([{ code: error.code, message: error.message }]);
}
const mirror_ = createMirror(loroDoc(), schema);
@@ -321,25 +330,29 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to sync mirror', e);
pushError(LoroManagerError.InitializeFailed);
- return onlyErr(
- LoroManagerError.InitializeFailed,
- `Failed to sync mirror: ${e}`
- );
+ return err([
+ {
+ code: LoroManagerError.InitializeFailed,
+ message: `Failed to sync mirror: ${e}`,
+ },
+ ]);
}
setInitialized(true);
setMirror(mirror_);
- return [null];
+ return ok(undefined);
};
const getUpdateSince = (
lastVersionVector: VersionVector
- ): MaybeResult<LoroManagerError, Uint8Array | undefined> => {
+ ): Result<Uint8Array | undefined, ResultError<LoroManagerError>[]> => {
const mirror_ = mirror();
if (!initialized() || !mirror_) {
- return err(LoroManagerError.NotInitialized, 'Not initialized');
+ return err([
+ { code: LoroManagerError.NotInitialized, message: 'Not initialized' },
+ ]);
}
const currentVersionVector = loroDoc().version();
/** Comparison between the current state, and the last synced state */
@@ -371,21 +384,25 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to export update', e);
pushError(LoroManagerError.ExportFailed);
- return err(
- LoroManagerError.ExportFailed,
- `Failed to export update: ${e}`
- );
+ return err([
+ {
+ code: LoroManagerError.ExportFailed,
+ message: `Failed to export update: ${e}`,
+ },
+ ]);
}
return ok(update);
};
- const getAllContainerIds = (): MaybeResult<
- LoroManagerError,
- ContainerID[]
+ const getAllContainerIds = (): Result<
+ ContainerID[],
+ ResultError<LoroManagerError>[]
> => {
if (!initialized() || !mirror()) {
- return err(LoroManagerError.NotInitialized, 'Not initialized');
+ return err([
+ { code: LoroManagerError.NotInitialized, message: 'Not initialized' },
+ ]);
}
return ok(mirror()!.getContainerIds());
@@ -393,10 +410,12 @@ export function createLoroManager<S extends GenericRootSchema>(
const syncToLoro = async (
state: InferType<S>
- ): Promise<MaybeError<LoroManagerError>> => {
+ ): Promise<Result<void, ResultError<LoroManagerError>[]>> => {
const mirror_ = mirror();
if (!initialized() || !mirror_) {
- return onlyErr(LoroManagerError.NotInitialized, 'Not initialized');
+ return err([
+ { code: LoroManagerError.NotInitialized, message: 'Not initialized' },
+ ]);
}
try {
@@ -407,18 +426,20 @@ export function createLoroManager<S extends GenericRootSchema>(
await awaitMirrorSync();
} catch (e) {
console.error('Failed to sync to loro', e);
- return onlyErr(
- LoroManagerError.SyncFailed,
- `Failed to sync to loro: ${e}`
- );
+ return err([
+ {
+ code: LoroManagerError.SyncFailed,
+ message: `Failed to sync to loro: ${e}`,
+ },
+ ]);
}
- return [null];
+ return ok(undefined);
};
const reset = async (
snapshot: LoroRawUpdate
- ): Promise<MaybeError<LoroManagerError>> => {
+ ): Promise<Result<void, ResultError<LoroManagerError>[]>> => {
mirror()?.dispose();
loroDoc().free();
@@ -431,18 +452,22 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to import snapshot', e);
pushError(LoroManagerError.ImportFailed);
- return onlyErr(
- LoroManagerError.ImportFailed,
- `Failed to import snapshot: ${e}`
- );
+ return err([
+ {
+ code: LoroManagerError.ImportFailed,
+ message: `Failed to import snapshot: ${e}`,
+ },
+ ]);
}
if (Object.keys(importStatus.pending ?? {}).length > 0) {
pushError(LoroManagerError.ImportFailed);
- return onlyErr(
- LoroManagerError.ImportFailed,
- 'Snapshot import has pending updates'
- );
+ return err([
+ {
+ code: LoroManagerError.ImportFailed,
+ message: 'Snapshot import has pending updates',
+ },
+ ]);
}
const newMirror = createMirror(newDoc, schema);
@@ -461,12 +486,12 @@ export function createLoroManager<S extends GenericRootSchema>(
setInitialized(true);
- return [null];
+ return ok(undefined);
};
const getContainerById = (
id: ContainerID
- ): MaybeResult<LoroManagerError, Container | undefined> => {
+ ): Result<Container | undefined, ResultError<LoroManagerError>[]> => {
let container: Container | undefined;
try {
@@ -474,7 +499,9 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to get container', e);
pushError(LoroManagerError.GetContainerByIdFailed);
- return err(LoroManagerError.GetContainerByIdFailed, e);
+ return err([
+ { code: LoroManagerError.GetContainerByIdFailed, message: e },
+ ]);
}
return ok(container);
@@ -482,13 +509,13 @@ export function createLoroManager<S extends GenericRootSchema>(
const getCursorPos = (
cursor: Cursor
- ): MaybeResult<
- LoroManagerError,
+ ): Result<
{
update?: Cursor;
offset: number;
side: Side;
- }
+ },
+ ResultError<LoroManagerError>[]
> => {
let pos: { update?: Cursor; offset: number; side: Side } | undefined;
try {
@@ -496,7 +523,7 @@ export function createLoroManager<S extends GenericRootSchema>(
} catch (e) {
console.error('Failed to get cursor pos', e);
pushError(LoroManagerError.GetCursorPosFailed);
- return err(LoroManagerError.GetCursorPosFailed, e);
+ return err([{ code: LoroManagerError.GetCursorPosFailed, message: e }]);
}
return ok(pos);
diff --git a/js/app/packages/core/collab/time-travel.ts b/js/app/packages/core/collab/time-travel.ts
index ba40318855..b637308e39 100644
--- a/js/app/packages/core/collab/time-travel.ts
+++ b/js/app/packages/core/collab/time-travel.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { syncServiceClient } from '@service-sync/client';
import {
type Change,
@@ -150,24 +149,24 @@ function createGroup(
async function fetchRawHistory(documentId: string): Promise<BaseHistory[]> {
const maybeSnapshot = await syncServiceClient.getSnapshot({ documentId });
- if (isErr(maybeSnapshot)) {
+ if (maybeSnapshot.isErr()) {
console.error('Failed to get snapshot', maybeSnapshot);
return [];
}
const doc = new LoroDoc();
- doc.import(maybeSnapshot[1]);
+ doc.import(maybeSnapshot.value);
const maybeMetadata = await syncServiceClient.getDocumentMetadata({
documentId,
});
- if (isErr(maybeMetadata)) {
+ if (maybeMetadata.isErr()) {
console.error('Failed to get document metadata', maybeMetadata);
return [];
}
- const metadata = maybeMetadata[1];
+ const metadata = maybeMetadata.value;
const peerToUserId = new Map(
metadata.peers.map((p) => [String(p.peer_id), p.user_id])
);
diff --git a/js/app/packages/core/component/AI/component/debug/Attachment.tsx b/js/app/packages/core/component/AI/component/debug/Attachment.tsx
index ee5d9bfa0e..0377d06a8b 100644
--- a/js/app/packages/core/component/AI/component/debug/Attachment.tsx
+++ b/js/app/packages/core/component/AI/component/debug/Attachment.tsx
@@ -1,5 +1,5 @@
import type { Attachment, Model } from '@core/component/AI/types';
-import { isErr } from '@core/util/maybeResult';
+
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { ChatMessageStream } from '@service-connection/stream';
import { subscribe } from '@service-connection/stream';
@@ -139,10 +139,10 @@ async function sendRequest(simple: SimpleRequest): Promise<SendResult> {
model: simple.model,
attachments: simple.attachments.length > 0 ? simple.attachments : undefined,
});
- if (isErr(response)) {
+ if (response.isErr()) {
return { type: 'error' };
}
- const [, { stream_id, chat_id }] = response;
+ const { stream_id, chat_id } = response.value;
const connectionStream = subscribe('chat', chat_id, stream_id);
if (!connectionStream) {
return { type: 'error' };
diff --git a/js/app/packages/core/component/AI/component/debug/Component.tsx b/js/app/packages/core/component/AI/component/debug/Component.tsx
index 7350fd16f6..2396cdb759 100644
--- a/js/app/packages/core/component/AI/component/debug/Component.tsx
+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx
@@ -2,7 +2,7 @@ import { buildChatEditor } from '@core/component/AI/component/input/buildChatEdi
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
import type { Model } from '@core/component/AI/types';
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
-import { isErr } from '@core/util/maybeResult';
+
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { ChatMessageStream } from '@service-connection/stream';
import { subscribe } from '@service-connection/stream';
@@ -132,11 +132,11 @@ function ChatInputBoxConnectedInner() {
attachments: input.attachments.length > 0 ? input.attachments : undefined,
toolset: input.toolset,
});
- if (isErr(response)) {
+ if (response.isErr()) {
console.log('error sending message', response);
return;
}
- const [, { stream_id, chat_id }] = response;
+ const { stream_id, chat_id } = response.value;
const connectionStream = subscribe('chat', chat_id, stream_id);
if (!connectionStream) {
console.log('no connection stream');
@@ -244,11 +244,11 @@ function FullChatInner() {
attachments: input.attachments.length > 0 ? input.attachments : undefined,
toolset: input.toolset,
});
- if (isErr(response)) {
+ if (response.isErr()) {
console.log('error sending message', response);
return;
}
- const [, { stream_id, chat_id }] = response;
+ const { stream_id, chat_id } = response.value;
const connectionStream = subscribe('chat', chat_id, stream_id);
if (!connectionStream) {
console.log('no connection stream');
diff --git a/js/app/packages/core/component/AI/component/input/buildRequest.ts b/js/app/packages/core/component/AI/component/input/buildRequest.ts
index 021029c3b2..3fb0b0a07d 100644
--- a/js/app/packages/core/component/AI/component/input/buildRequest.ts
+++ b/js/app/packages/core/component/AI/component/input/buildRequest.ts
@@ -3,7 +3,7 @@ import { DEFAULT_MODEL } from '@core/component/AI/constant';
import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';
import type { Attachment, Model, ToolSet } from '@core/component/AI/types';
import { isPaymentError } from '@core/util/handlePaymentError';
-import { isErr } from '@core/util/maybeResult';
+
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { ChatMessageStream } from '@service-connection/stream';
import { subscribe } from '@service-connection/stream';
@@ -45,11 +45,11 @@ export function useSendChatMessage() {
if (isPaymentError(response)) {
return { error: true, paymentError: true };
}
- if (isErr(response)) {
+ if (response.isErr()) {
return { error: true };
}
- const [, { stream_id, chat_id }] = response;
+ const { stream_id, chat_id } = response.value;
const connectionStream = subscribe('chat', chat_id, stream_id);
if (!connectionStream) {
diff --git a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
index 99ce599e94..18fe7864a3 100644
--- a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
+++ b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
@@ -8,7 +8,7 @@ import {
allSupportedExtensionSet,
isCodeEditorExtensionSupported,
} from '@core/util/languageQuery';
-import { isOk } from '@core/util/maybeResult';
+
import Terminal from '@phosphor-icons/core/regular/terminal.svg';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type {
@@ -68,9 +68,9 @@ function CreateResult(props: {
source_id: props.toolId,
});
- if (isOk(result) && result[1]) {
+ if (result.isOk() && result.value) {
try {
- const fileInfo = JSON.parse(result[1]) as CreatedFileInfo;
+ const fileInfo = JSON.parse(result.value) as CreatedFileInfo;
createdFilesMap[props.toolId] = fileInfo;
setCreatedFile(fileInfo);
} catch {
@@ -193,8 +193,8 @@ const handler = createToolRenderer({
title: fileName,
});
- if (isOk(result)) {
- const documentId = result[1].documentId;
+ if (result.isOk()) {
+ const documentId = result.value.documentId;
createdFilesMap[ctx.tool.id] = {
documentId,
fileName,
diff --git a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
index 0113ca771c..d3dda7631f 100644
--- a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
+++ b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
@@ -14,7 +14,7 @@ import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientC
import { useChatContext } from '@core/component/AI/context';
import type { AssistantMessagePart } from '@core/component/AI/types';
import { toast } from '@core/component/Toast/Toast';
-import { isErr } from '@core/util/maybeResult';
+
import { useChatQuery } from '@queries/chat';
import { useEmailLinksQuery } from '@queries/email/link';
import { cognitionApiServiceClient } from '@service-cognition/client';
@@ -240,7 +240,7 @@ export function ComposeTool(props: ComposeToolProps) {
args,
});
- if (isErr(updateCallResult)) {
+ if (updateCallResult.isErr()) {
toast.failure('Failed to save changes');
return;
}
@@ -253,7 +253,7 @@ export function ComposeTool(props: ComposeToolProps) {
response: { UserAction: 'userEdited' },
});
- if (isErr(updateResponseResult)) {
+ if (updateResponseResult.isErr()) {
toast.failure('Failed to save changes');
return;
}
@@ -278,12 +278,12 @@ export function ComposeTool(props: ComposeToolProps) {
setIsSending(false);
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure('Failed to send email');
return;
}
- const sentResponse = getSentToolResponse(result[1]);
+ const sentResponse = getSentToolResponse(result.value);
if (sentResponse) {
toolFinalized = true;
chat.setMessages((messages) =>
diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsx
index d885632127..b9459bc8d1 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import {
deserializeToolCall,
deserializeToolResponse,
@@ -101,9 +100,9 @@ export function RenderTool(props: ToolProps) {
json: props.json,
name: props.name as ToolName,
});
- if (isErr(maybeTool)) return null;
+ if (maybeTool.isErr()) return null;
- const tool = maybeTool[1];
+ const tool = maybeTool.value;
const handler = toolHandlers[tool.name] as ToolHandler<
ToolName,
RenderContext
@@ -125,8 +124,8 @@ export function RenderTool(props: ToolProps) {
name: props.response.name as ToolName,
});
- if (isErr(maybeResponse)) return undefined;
- return maybeResponse[1];
+ if (maybeResponse.isErr()) return undefined;
+ return maybeResponse.value;
};
return (
@@ -165,9 +164,9 @@ export async function triggerToolCall(args: TriggerToolArgs) {
name: name as ToolName,
});
- if (isErr(maybeTool)) return;
+ if (maybeTool.isErr()) return;
- const tool = maybeTool[1];
+ const tool = maybeTool.value;
const handler = toolHandlers[tool.name] as ToolHandler<
ToolName,
RenderContext
diff --git a/js/app/packages/core/component/AI/constant/prompts.ts b/js/app/packages/core/component/AI/constant/prompts.ts
index fc5f414657..587a2d7bc8 100644
--- a/js/app/packages/core/component/AI/constant/prompts.ts
+++ b/js/app/packages/core/component/AI/constant/prompts.ts
@@ -31,8 +31,8 @@ export function useAdditionalInstructions() {
const userInstructionsQuery = useInstructionsMdTextQuery();
const { email } = useUserContext();
const [userName] = createResource(async () => {
- const [, response] = await authServiceClient.getUserName();
- return response ?? null;
+ const response = await authServiceClient.getUserName();
+ return response.isOk() ? response.value : null;
});
return () => {
let prompt = ABOUT_MACRO;
diff --git a/js/app/packages/core/component/DocumentPreview.tsx b/js/app/packages/core/component/DocumentPreview.tsx
index 37fc75b980..363cdfba92 100644
--- a/js/app/packages/core/component/DocumentPreview.tsx
+++ b/js/app/packages/core/component/DocumentPreview.tsx
@@ -22,7 +22,6 @@ import { itemToBlockName, resolveBlockAlias } from '@core/constant/allBlocks';
import { tryMacroId, useDisplayName } from '@core/user';
import { copyBranchNameToClipboard } from '@core/util/branchName';
import { matches } from '@core/util/match';
-import { isErr } from '@core/util/maybeResult';
import MacroEmbed from '@icon/macro-embed.svg';
import CollapseInlinePreview from '@phosphor/arrows-in-line-horizontal.svg';
import OpenIcon from '@phosphor/arrows-out.svg';
@@ -314,8 +313,8 @@ function ImageCoverStrip(props: {
let objectUrl: string | undefined;
fetchBinary(presignedUrl, 'blob', { signal: controller.signal }).then(
(result) => {
- if (controller.signal.aborted || isErr(result)) return;
- const [, blob] = result;
+ if (controller.signal.aborted || result.isErr()) return;
+ const blob = result.value;
objectUrl = URL.createObjectURL(
new Blob([blob], { type: 'image/svg+xml' })
);
diff --git a/js/app/packages/core/component/EntityPermissionsGate.tsx b/js/app/packages/core/component/EntityPermissionsGate.tsx
index 95720063c2..f68cacef02 100644
--- a/js/app/packages/core/component/EntityPermissionsGate.tsx
+++ b/js/app/packages/core/component/EntityPermissionsGate.tsx
@@ -1,4 +1,4 @@
-import { MaybeResultError } from '@core/util/maybeResult';
+import { ThrownResultError } from '@core/util/result';
import { useEntityPermissions } from '@queries/entity/permissions';
import { hasEntityAccess } from '@queries/entity/permissionUtils';
import { type FlowProps, Match, Show, Suspense, Switch } from 'solid-js';
@@ -8,7 +8,7 @@ import Unauthorized from './AccessErrorViews/Unauthorized';
import { LoadingBlock } from './LoadingBlock';
function getErrorCode(error: Error | null): string | null {
- if (error instanceof MaybeResultError) {
+ if (error instanceof ThrownResultError) {
return error.errors[0]?.code ?? null;
}
return null;
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index 7857009301..9d64295da4 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -1,7 +1,7 @@
import { analytics } from '@app/lib/analytics';
import { usePaywallState } from '@core/constant/PaywallState';
import { isPaymentError } from '@core/util/handlePaymentError';
-import { isErr, isOk } from '@core/util/maybeResult';
+
import { removeHistoryItem } from '@queries/history/history';
import {
getDeletedTree,
@@ -36,8 +36,8 @@ export async function getItemAccessLevel({
await storageServiceClient.projects.getProject({
id,
});
- if (isOk(maybeProjectMetadata)) {
- return maybeProjectMetadata[1].userAccessLevel;
+ if (maybeProjectMetadata.isOk()) {
+ return maybeProjectMetadata.value.userAccessLevel;
}
break;
@@ -46,8 +46,8 @@ export async function getItemAccessLevel({
await storageServiceClient.getDocumentMetadata({
documentId: id,
});
- if (isOk(maybeDocumentMetadata)) {
- return maybeDocumentMetadata[1].userAccessLevel;
+ if (maybeDocumentMetadata.isOk()) {
+ return maybeDocumentMetadata.value.userAccessLevel;
}
break;
@@ -55,8 +55,8 @@ export async function getItemAccessLevel({
const maybeChatMetadata = await cognitionApiServiceClient.getChat({
chat_id: id,
});
- if (isOk(maybeChatMetadata)) {
- return maybeChatMetadata[1].userAccessLevel;
+ if (maybeChatMetadata.isOk()) {
+ return maybeChatMetadata.value.userAccessLevel;
}
break;
case 'email':
@@ -64,8 +64,8 @@ export async function getItemAccessLevel({
thread_id: id,
limit: 1,
});
- if (isOk(maybeThread)) {
- return maybeThread[1].thread.access_level;
+ if (maybeThread.isOk()) {
+ return maybeThread.value.thread.access_level;
}
break;
default:
@@ -124,7 +124,7 @@ export async function renameItem(args: {
}
}
- if (isErr(result)) {
+ if (result.isErr()) {
return false;
}
@@ -143,7 +143,7 @@ export async function setFileType(args: {
fileType: { set: fileType },
});
- if (isErr(result)) {
+ if (result.isErr()) {
return false;
}
@@ -183,7 +183,7 @@ export async function deleteItem(args: {
return false;
}
}
- if (isErr(result)) {
+ if (result.isErr()) {
return false;
}
} else {
@@ -284,7 +284,7 @@ export async function moveToFolder(args: {
}
}
- if (isErr(result)) {
+ if (result.isErr()) {
return false;
}
refetchResources();
@@ -348,8 +348,8 @@ export async function copyItem(args: {
documentId: id,
documentName: createCopyName(name),
});
- if (isErr(result)) return null;
- newId = result[1].documentId;
+ if (result.isErr()) return null;
+ newId = result.value.documentId;
break;
}
case 'chat': {
@@ -360,10 +360,10 @@ export async function copyItem(args: {
if (isPaymentError(result)) {
showPaywall();
}
- if (isErr(result)) {
+ if (result.isErr()) {
return null;
}
- newId = result[1].id;
+ newId = result.value.id;
break;
}
default:
@@ -443,7 +443,7 @@ export async function revertDelete(args: {
}
}
- if (isErr(result)) {
+ if (result.isErr()) {
return false;
}
@@ -503,7 +503,7 @@ export async function permanentlyDelete(args: {
}
}
- if (isErr(result)) {
+ if (result.isErr()) {
return false;
}
diff --git a/js/app/packages/core/component/ImagePreview.tsx b/js/app/packages/core/component/ImagePreview.tsx
index 235e5a48e8..f3221a4304 100644
--- a/js/app/packages/core/component/ImagePreview.tsx
+++ b/js/app/packages/core/component/ImagePreview.tsx
@@ -4,7 +4,7 @@ false && internalDrag;
import { SERVER_HOSTS } from '@core/constant/servers';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { maybeThrow } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { Dialog } from '@kobalte/core/dialog';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import { constrainImageDimensions } from '@lexical-core/utils/media';
@@ -55,13 +55,12 @@ const THEMES = {
// NOTE: copied logic from block-image
const getDssImageBlob = async (documentId: string) => {
- const maybeDocument = await fetchBinaryDocumentData(documentId);
- const documentResult = maybeThrow(maybeDocument);
+ const documentResult = await throwOnErr(() =>
+ fetchBinaryDocumentData(documentId)
+ );
// presigned url with expiry
const { blobUrl } = documentResult;
- const blobResult = await fetchBinary(blobUrl, 'blob');
- const blob = maybeThrow(blobResult);
- return blob;
+ return throwOnErr(() => fetchBinary(blobUrl, 'blob'));
};
/** Max width for single image preview containers (matches MediaPreview max-w-[400px]) */
diff --git a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
index 7c146a5e14..8dec6acef7 100644
--- a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
@@ -2,7 +2,7 @@ import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/signal/location';
import { itemToBlockName } from '@core/constant/allBlocks';
import { useChannelsContext } from '@core/context/channels';
-import { isOk } from '@core/util/maybeResult';
+
import { getHistoryItems } from '@queries/history/history';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { validate as uuidValidate } from 'uuid';
@@ -117,8 +117,8 @@ const getPdfCitationInfo = async (citationId: string) => {
const response = await cognitionApiServiceClient.getCitation({
id: citationId,
});
- if (isOk(response)) {
- const [, textPart] = response;
+ if (response.isOk()) {
+ const textPart = response.value;
const documentId = textPart.document_id;
const blockName = textPart.reference.kind;
if (blockName === 'pdf') {
diff --git a/js/app/packages/core/component/LexicalMarkdown/collaboration/cursor.ts b/js/app/packages/core/component/LexicalMarkdown/collaboration/cursor.ts
index adcb7b16f7..3f9853a9da 100644
--- a/js/app/packages/core/component/LexicalMarkdown/collaboration/cursor.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/collaboration/cursor.ts
@@ -1,6 +1,6 @@
import type { LoroManager } from '@core/collab/manager';
import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { isErr } from '@core/util/maybeResult';
+
import { $getNodeById, type NodeIdMappings } from '@lexical-core';
import {
$createPoint,
@@ -159,12 +159,12 @@ export function $convertLexicalSelectionToCursors(
// Create cursor at the start of the first node
const firstContainerResult = loroManager.getContainerById(firstContainerId);
- if (isErr(firstContainerResult)) {
+ if (firstContainerResult.isErr()) {
warn('Failed to get first container', firstContainerResult);
return undefined;
}
- const firstContainer = firstContainerResult[1];
+ const firstContainer = firstContainerResult.value;
if (firstContainer instanceof LoroText) {
anchorCursor = firstContainer.getCursor(0);
} else if (firstContainer instanceof LoroMovableList) {
@@ -174,12 +174,12 @@ export function $convertLexicalSelectionToCursors(
// Create cursor at the end of the last node
const lastContainerResult = loroManager.getContainerById(lastContainerId);
- if (isErr(lastContainerResult)) {
+ if (lastContainerResult.isErr()) {
warn('Failed to get last container', lastContainerResult);
return undefined;
}
- const lastContainer = lastContainerResult[1];
+ const lastContainer = lastContainerResult.value;
if (lastContainer instanceof LoroText) {
focusCursor = lastContainer.getCursor(lastContainer.length);
@@ -236,12 +236,12 @@ function lexicalPointToCursor(
// Get the container and create the cursor
const maybeContainer = loroManager.getContainerById(containerId);
- if (isErr(maybeContainer)) {
+ if (maybeContainer.isErr()) {
warn('Failed to get container', maybeContainer);
return undefined;
}
- let container = maybeContainer[1];
+ let container = maybeContainer.value;
let cursor: Cursor | undefined;
if (container instanceof LoroText) {
@@ -312,12 +312,12 @@ export function $cursorToLexicalPoint(
let maybeContainer = loroManager.getContainerById(cursorContainerID);
- if (isErr(maybeContainer)) {
+ if (maybeContainer.isErr()) {
warn('Failed to get container', maybeContainer);
return null;
}
- if (!maybeContainer[1]) {
+ if (!maybeContainer.value) {
warn("no container for cursor's containe id");
return null;
}
@@ -327,12 +327,12 @@ export function $cursorToLexicalPoint(
// Get position info from the cursor
const posResult = loroManager.getCursorPos(cursor.cursor);
- if (isErr(posResult)) {
+ if (posResult.isErr()) {
warn('Failed to get cursor position', posResult);
return null;
}
- let pos = posResult[1];
+ let pos = posResult.value;
// Create a Point for the Lexical node
return $createPointFromKeyAndOffset(nodeKey, pos.offset);
diff --git a/js/app/packages/core/component/LexicalMarkdown/collaboration/mapping.ts b/js/app/packages/core/component/LexicalMarkdown/collaboration/mapping.ts
index 01bc4cdb5a..a2e8e24066 100644
--- a/js/app/packages/core/component/LexicalMarkdown/collaboration/mapping.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/collaboration/mapping.ts
@@ -1,6 +1,6 @@
import type { LoroManager } from '@core/collab/manager';
import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { isErr } from '@core/util/maybeResult';
+
import type { NodeIdMappings } from '@lexical-core';
import { $getNodeByKey, type LexicalNode } from 'lexical';
import { type ContainerID, LoroMap } from 'loro-crdt';
@@ -22,12 +22,12 @@ export function $findLexicalNodeForLoroContainer(
): LexicalNode | null {
let maybeContainer = loroManager.getContainerById(containerId);
- if (isErr(maybeContainer)) {
+ if (maybeContainer.isErr()) {
warn('Failed to get container', maybeContainer);
return null;
}
- let container = maybeContainer[1];
+ let container = maybeContainer.value;
container = container?.getAttached();
@@ -108,22 +108,22 @@ function smartSearchContainersForNode(
): ContainerID | undefined {
const res = loroManager.getAllContainerIds();
- if (isErr(res)) {
+ if (res.isErr()) {
warn('Failed to get all container ids', res);
return undefined;
}
- const containerIds: ContainerID[] = res[1].reverse();
+ const containerIds: ContainerID[] = res.value.reverse();
for (const containerId of containerIds) {
const maybeContainer = loroManager.getContainerById(containerId);
- if (isErr(maybeContainer)) {
+ if (maybeContainer.isErr()) {
warn('Failed to get container', maybeContainer);
return undefined;
}
- let container = maybeContainer[1];
+ let container = maybeContainer.value;
container = container?.getAttached();
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
index 78484167fa..210b3bf406 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
@@ -4,7 +4,7 @@ false && internalDrag;
import { toast } from '@core/component/Toast/Toast';
import { debouncedDependent } from '@core/util/debounce';
-import { isErr } from '@core/util/maybeResult';
+
import { Dialog } from '@kobalte/core/dialog';
import { mergeRegister } from '@lexical/utils';
import { $isImageNode, type ImageDecoratorProps } from '@lexical-core';
@@ -109,15 +109,24 @@ export function MarkdownImage(props: ImageDecoratorProps) {
id: props.id,
url: props.url,
}).then((maybeUrl) => {
- if (isErr(maybeUrl)) {
+ if (maybeUrl.isErr()) {
setState('error');
- if (isErr(maybeUrl, 'UNAUTHORIZED')) setImageError('UNAUTHORIZED');
- else if (isErr(maybeUrl, 'MISSING')) setImageError('MISSING');
- else if (isErr(maybeUrl, 'GONE')) setImageError('GONE');
+ if (
+ maybeUrl.isErr() &&
+ maybeUrl.error.some((error) => error.code === 'UNAUTHORIZED')
+ )
+ setImageError('UNAUTHORIZED');
+ else if (maybeUrl.error.some((error) => error.code === 'NOT_FOUND'))
+ setImageError('MISSING');
+ else if (
+ maybeUrl.isErr() &&
+ maybeUrl.error.some((error) => error.code === 'GONE')
+ )
+ setImageError('GONE');
else setImageError('FALLBACK');
return;
}
- const url = maybeUrl[1];
+ const url = maybeUrl.value;
setImageUrl(url);
if (props.srcType === 'dss') {
editor()?.update(
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx
index d5ac03433b..1c5c89d89e 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx
@@ -1,6 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import { debouncedDependent } from '@core/util/debounce';
-import { isErr } from '@core/util/maybeResult';
+
import { Dialog } from '@kobalte/core/dialog';
import { mergeRegister } from '@lexical/utils';
import { $isVideoNode, type VideoDecoratorProps } from '@lexical-core';
@@ -92,15 +92,24 @@ export function MarkdownVideo(props: VideoDecoratorProps) {
id: props.id,
url: props.url,
}).then((maybeUrl) => {
- if (isErr(maybeUrl)) {
+ if (maybeUrl.isErr()) {
setState('error');
- if (isErr(maybeUrl, 'UNAUTHORIZED')) setVideoError('UNAUTHORIZED');
- else if (isErr(maybeUrl, 'MISSING')) setVideoError('MISSING');
- else if (isErr(maybeUrl, 'GONE')) setVideoError('GONE');
+ if (
+ maybeUrl.isErr() &&
+ maybeUrl.error.some((error) => error.code === 'UNAUTHORIZED')
+ )
+ setVideoError('UNAUTHORIZED');
+ else if (maybeUrl.error.some((error) => error.code === 'NOT_FOUND'))
+ setVideoError('MISSING');
+ else if (
+ maybeUrl.isErr() &&
+ maybeUrl.error.some((error) => error.code === 'GONE')
+ )
+ setVideoError('GONE');
else setVideoError('FALLBACK');
return;
}
- const url = maybeUrl[1];
+ const url = maybeUrl.value;
setVideoUrl(url);
if (props.srcType === 'dss') {
editor()?.update(
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
index 908dd490c8..8ad515bf0d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
@@ -4,7 +4,8 @@ import { heicConversionService } from '@core/heic/service';
import type { FetchError } from '@core/service';
import { createStaticFile } from '@core/util/create';
import { contentHash } from '@core/util/hash';
-import { type MaybeResult, mapOk } from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
+
import { mergeRegister } from '@lexical/utils';
import {
$createImageNode,
@@ -34,6 +35,7 @@ import {
type LexicalEditor,
type NodeKey,
} from 'lexical';
+import { ok, type Result } from 'neverthrow';
import { $insertNodesAndSplitList } from '../../utils';
import { mapRegisterDelete } from '../shared';
@@ -122,17 +124,17 @@ export async function getMediaUrl(src: {
type: string;
id: string;
url: string;
-}): Promise<MaybeResult<FetchError | 'INVALID_DOCUMENT', string>> {
- if (src.type === 'local' || src.type === 'url') return [null, src.url];
+}): Promise<Result<string, ResultError<FetchError | 'INVALID_DOCUMENT'>[]>> {
+ if (src.type === 'local' || src.type === 'url') return ok(src.url);
if (src.type === 'sfs') {
const url = staticFileIdEndpoint(src.id);
- return [null, url];
+ return ok(url);
}
if (src.type === 'dss') {
- return mapOk(await fetchBinaryDocumentData(src.id), (res) => res.blobUrl);
+ return (await fetchBinaryDocumentData(src.id)).map((res) => res.blobUrl);
}
console.warn('Get media url failed for src:', src);
- return [null, ''];
+ return ok('');
}
/**
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts b/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts
index f2df37c138..f5fcdc6441 100644
--- a/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts
@@ -2,7 +2,7 @@ import type { BlockAlias, BlockName } from '@core/block';
import { entityPropertyFromApi } from '@core/component/Properties/api/converters';
import type { Property } from '@core/component/Properties/types';
import { trackMention } from '@core/signal/mention';
-import { isErr, isOk } from '@core/util/maybeResult';
+
import type { HistoryItem as Item } from '@queries/history/history';
import { fetchDocumentAsMarkdown } from '@queries/sync/markdownText';
import { propertiesServiceClient } from '@service-properties/client';
@@ -179,8 +179,10 @@ export async function handleSnapshotMention(
}
text = contentResult;
- if (propsResult && isOk(propsResult)) {
- const properties = propsResult[1].properties.map(entityPropertyFromApi);
+ if (propsResult && propsResult.isOk()) {
+ const properties = propsResult.value.properties.map(
+ entityPropertyFromApi
+ );
propertiesFrontMatter = formatPropertiesAsYamlFrontMatter(properties);
}
} else {
@@ -189,7 +191,7 @@ export async function handleSnapshotMention(
documentId: item.id,
});
- if (isErr(result)) {
+ if (result.isErr()) {
// Fall back to regular mention on error
console.error(
'Failed to fetch document content for SnapshotNode:',
@@ -197,7 +199,7 @@ export async function handleSnapshotMention(
);
return;
}
- text = result[1].text;
+ text = result.value.text;
}
let mentionId: string | undefined;
diff --git a/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx b/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx
index 9cb5439bed..eb9c249487 100644
--- a/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx
+++ b/js/app/packages/core/component/Properties/debug/PropertiesDebug.tsx
@@ -1,7 +1,7 @@
import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
import { StaticSplitLabel } from '@app/component/split-layout/components/SplitLabel';
import { filterMap } from '@core/util/list';
-import { isErr } from '@core/util/maybeResult';
+
import { propertiesServiceClient } from '@service-properties/client';
import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
import { useQuery } from '@tanstack/solid-query';
@@ -64,10 +64,10 @@ const PropertiesDebug: Component = () => {
scope: 'system',
include_options: true,
});
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to fetch system properties');
}
- const [, data] = result;
+ const data = result.value;
return data;
},
staleTime: 1000 * 60 * 10,
diff --git a/js/app/packages/core/component/References.tsx b/js/app/packages/core/component/References.tsx
index ff894cdb6d..a94dd6c6e3 100644
--- a/js/app/packages/core/component/References.tsx
+++ b/js/app/packages/core/component/References.tsx
@@ -6,7 +6,7 @@ import { toast } from '@core/component/Toast/Toast';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { tryMacroId, useDisplayNameParts } from '@core/user';
import { compareDateDesc, type DateValue } from '@core/util/date';
-import { isErr } from '@core/util/maybeResult';
+
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
import { formatRelativeTimestamp } from '@entity';
import {
@@ -225,12 +225,12 @@ export function References(props: ReferenceProps) {
entity_id: props.documentId,
});
- if (isErr(response)) {
+ if (response.isErr()) {
console.error(response);
return [];
}
- return response[1].references;
+ return response.value.references;
});
const { openWithSplit } = useSplitLayout();
const blockOrchestrator = useGlobalBlockOrchestrator();
diff --git a/js/app/packages/core/component/ReferencesModal.tsx b/js/app/packages/core/component/ReferencesModal.tsx
index 7b66cabcbb..12f9e8d20d 100644
--- a/js/app/packages/core/component/ReferencesModal.tsx
+++ b/js/app/packages/core/component/ReferencesModal.tsx
@@ -1,7 +1,6 @@
import { SplitDrawer } from '@app/component/split-layout/components/SplitDrawer';
import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';
import clickOutside from '@core/directive/clickOutside';
-import { isErr } from '@core/util/maybeResult';
import Quotes from '@phosphor/quotes.svg';
import { commsServiceClient } from '@service-comms/client';
import type { ItemType } from '@service-storage/client';
@@ -92,12 +91,12 @@ export function ReferencesModal(props: ReferencesModalProps) {
entity_id: id,
});
- if (isErr(response)) {
+ if (response.isErr()) {
console.error(response);
return 0;
}
- return response[1].references.length;
+ return response.value.references.length;
}
);
diff --git a/js/app/packages/core/component/TopBar/ShareButton.tsx b/js/app/packages/core/component/TopBar/ShareButton.tsx
index 2db331d40d..f98e220de5 100644
--- a/js/app/packages/core/component/TopBar/ShareButton.tsx
+++ b/js/app/packages/core/component/TopBar/ShareButton.tsx
@@ -33,12 +33,7 @@ import {
} from '@core/signal/permissions';
import { idToEmail } from '@core/user';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
-import {
- isErr,
- isOk,
- type MaybeError,
- type MaybeResult,
-} from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
import { buildSimpleEntityUrl } from '@core/util/url';
import IconComment from '@icon/wide-comment.svg';
import WideCopy from '@icon/wide-copy.svg';
@@ -65,6 +60,7 @@ import type { SharePermissionV2ChannelSharePermissions } from '@service-storage/
import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
import { Button, ButtonGroup, cn, Panel, ToggleSwitch, Tooltip } from '@ui';
+import type { Result } from 'neverthrow';
import {
type Accessor,
createContext,
@@ -592,10 +588,10 @@ export function ShareModal(props: ShareModalProps) {
const [channelNamesResource] = createResource(
() => {
const result = permissionsResource.latest;
- if (!result || isErr(result)) {
+ if (!result || result.isErr()) {
return;
}
- const [, sharePermission] = result;
+ const sharePermission = result.value;
if (!sharePermission?.channelSharePermissions?.length) {
return;
}
@@ -611,11 +607,11 @@ export function ShareModal(props: ShareModalProps) {
// Create a map of channel IDs to channel names
const channelNameMap = createMemo(() => {
const result = channelNamesResource.latest;
- if (!result || isErr(result)) {
+ if (!result || result.isErr()) {
return new Map();
}
- const [, data] = result;
+ const data = result.value;
const map = new Map();
data.previews.forEach((preview) => {
@@ -631,10 +627,10 @@ export function ShareModal(props: ShareModalProps) {
});
const recipients = createMemo(() => {
- const maybeResult = permissionsResource.latest;
- if (!maybeResult || isErr(maybeResult)) return;
+ const result = permissionsResource.latest;
+ if (!result || result.isErr()) return;
- const [, sharePermission] = maybeResult;
+ const sharePermission = result.value;
return sharePermission.channelSharePermissions;
});
@@ -657,7 +653,7 @@ export function ShareModal(props: ShareModalProps) {
],
},
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
refetch();
toast.success('Removed channel access', {
subtext: 'Channel no longer has access to this chat',
@@ -680,7 +676,7 @@ export function ShareModal(props: ShareModalProps) {
],
},
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
refetch();
toast.success('Removed channel access', {
subtext: 'Channel no longer has access to this document',
@@ -703,7 +699,7 @@ export function ShareModal(props: ShareModalProps) {
],
},
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
refetch();
toast.success('Removed folder access');
} else {
@@ -723,7 +719,10 @@ export function ShareModal(props: ShareModalProps) {
) => {
if (props.userPermissions !== Permissions.OWNER) return;
- let result: MaybeResult<any, any> | MaybeError<any> | null = null;
+ let result:
+ | Result<any, ResultError<any>[]>
+ | Result<void, ResultError<any>[]>
+ | null = null;
if (props.itemType === 'chat') {
result = await cognitionApiServiceClient.updateChatPermissions({
sharePermission: {
@@ -778,7 +777,7 @@ export function ShareModal(props: ShareModalProps) {
});
}
- if (result && isOk(result)) {
+ if (result && result.isOk()) {
refetch();
if (!hideSuccessToast) {
toast.success('Changed channel access level', {
@@ -796,11 +795,11 @@ export function ShareModal(props: ShareModalProps) {
const publicAccessLevel = createMemo(() => {
const currentPermissions = permissionsResource.latest;
- if (!currentPermissions || isErr(currentPermissions)) {
+ if (!currentPermissions || currentPermissions.isErr()) {
return;
}
- const [, sharePermission] = currentPermissions;
+ const sharePermission = currentPermissions.value;
return sharePermission.publicAccessLevel;
});
@@ -814,7 +813,7 @@ export function ShareModal(props: ShareModalProps) {
},
chat_id: props.id,
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
refetch();
if (accessLevel === null) {
@@ -846,7 +845,7 @@ export function ShareModal(props: ShareModalProps) {
},
documentId: props.id,
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
refetch();
if (accessLevel === null) {
toast.success('Made document private', {
@@ -877,7 +876,7 @@ export function ShareModal(props: ShareModalProps) {
},
id: props.id,
});
- if (!isErr(result)) {
+ if (!result.isErr()) {
refetch();
if (accessLevel === null) {
toast.success('Made folder private', {
@@ -1246,9 +1245,9 @@ export function ShareTrigger(props: { copyLink?: () => void }) {
}));
const shareAccessLevelText = createMemo(() => {
- const maybeResult = permissionsBlockResource[0].latest;
- if (!maybeResult || isErr(maybeResult)) return '';
- const [, sharePermission] = maybeResult;
+ const result = permissionsBlockResource[0].latest;
+ if (!result || result.isErr()) return '';
+ const sharePermission = result.value;
if (sharePermission.isPublic) return 'Public';
if (sharePermission.channelSharePermissions?.length) return 'Shared';
return 'Just me';
diff --git a/js/app/packages/core/component/UserIcon.tsx b/js/app/packages/core/component/UserIcon.tsx
index 2e66e98725..a6850bd9e9 100644
--- a/js/app/packages/core/component/UserIcon.tsx
+++ b/js/app/packages/core/component/UserIcon.tsx
@@ -8,7 +8,7 @@ import {
useDisplayName,
useDisplayNameParts,
} from '@core/user';
-import { isOk } from '@core/util/maybeResult';
+
import Trash from '@phosphor-icons/core/regular/trash.svg?component-solid';
import { commsServiceClient } from '@service-comms/client';
import { Avatar, type AvatarSize } from '@ui';
@@ -156,7 +156,7 @@ export function UserIcon(props: UserIconProps) {
recipient_id: props.id,
});
- const channelId = isOk(result) && result[1]?.channel_id;
+ const channelId = result.isOk() && result.value?.channel_id;
if (!channelId) return;
replaceOrInsertSplit({ type: 'channel', id: channelId });
diff --git a/js/app/packages/core/component/UserTooltip.tsx b/js/app/packages/core/component/UserTooltip.tsx
index 533cf4e202..6f8e7bbc4f 100644
--- a/js/app/packages/core/component/UserTooltip.tsx
+++ b/js/app/packages/core/component/UserTooltip.tsx
@@ -1,7 +1,6 @@
import { useSplitLayout } from '@app/component/split-layout/layout';
import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
-import { isOk } from '@core/util/maybeResult';
import WideChat from '@icon/wide-chat.svg';
import WideCopy from '@icon/wide-copy.svg';
import WideTask from '@icon/wide-task.svg';
@@ -46,7 +45,7 @@ export function UserTooltip(props: UserTooltipProps) {
const result = await commsServiceClient.getOrCreateDirectMessage({
recipient_id: props.id,
});
- const channelId = isOk(result) && result[1]?.channel_id;
+ const channelId = result.isOk() && result.value?.channel_id;
if (channelId) {
openWithSplit(
{ type: 'channel', id: channelId },
diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.ts
index 7ee35523ef..5dd7e5be13 100644
--- a/js/app/packages/core/email-link/index.ts
+++ b/js/app/packages/core/email-link/index.ts
@@ -5,7 +5,7 @@ import {
type TimeoutError,
} from '@core/auth/channel';
import { openEmailAuthPopup } from '@core/auth/email';
-import { isErr } from '@core/util/maybeResult';
+
import { invalidateUserInfo } from '@queries/auth/user-info';
import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';
import { emailClient } from '@service-email/client';
@@ -45,11 +45,10 @@ type EmailInitError =
function initEmailLink(): ResultAsync<void, EmailInitError> {
return ResultAsync.fromSafePromise(emailClient.init()).andThen(
(initResult) => {
- if (isErr(initResult)) {
- const [errors] = initResult;
- const badRequestError = errors.find(
+ if (initResult.isErr()) {
+ const badRequestError = initResult.error.find(
// TODO: this is cope but seems like error.code not being set correctly
- (e) => e.code === '400' || e.message.includes('400')
+ (e) => e.message.includes('400')
);
return err(
badRequestError
@@ -104,7 +103,7 @@ function stopEmailPolling() {
function disconnectEmail(): ResultAsync<void, 'failed-to-disconnect'> {
return ResultAsync.fromSafePromise(emailClient.stopSync()).andThen(
(response) =>
- isErr(response) ? err('failed-to-disconnect') : okAsync(void 0)
+ response.isErr() ? err('failed-to-disconnect') : okAsync(void 0)
);
}
diff --git a/js/app/packages/core/internal/BlockLoader.tsx b/js/app/packages/core/internal/BlockLoader.tsx
index f0b7bfedf9..c2b1cef5ab 100644
--- a/js/app/packages/core/internal/BlockLoader.tsx
+++ b/js/app/packages/core/internal/BlockLoader.tsx
@@ -4,6 +4,7 @@ import type { OwnedBlockHandle } from '@core/orchestrator';
import { useQueryClient } from '@queries/client';
import type { AccessLevel as UserAccessLevel } from '@service-storage/generated/schemas/accessLevel';
import { createAsync } from '@solidjs/router';
+import { err, ok } from 'neverthrow';
import { createEffect, type JSX, onCleanup, useContext } from 'solid-js';
import {
type BlockDefinition,
@@ -26,7 +27,7 @@ import {
blockUserAccessSignal,
} from '../signal/load';
import type { Source, SourcePreload } from '../source';
-import { err, isErr, type ObjectLike, ok } from '../util/maybeResult';
+import type { ObjectLike } from '../util/result';
export const blockDataSignal = createBlockSignal<unknown>();
export const blockLiveTrackingEnabledSignal = createBlockSignal<boolean>();
@@ -72,16 +73,21 @@ export function BlockLoader<
const getResult = createAsync(async () => {
const result = await props.definition.load(props.source, 'initial');
- if (isErr(result)) {
- return result;
+ if (result.isErr()) {
+ return err(result.error);
}
- const [, data] = result;
+ const data = result.value;
if ('type' in data && data.type === 'preload') {
console.error(
`BlockLoader received a nested preload.
Check that the load function does not return a preload source when the intent is not preload`
);
- return err('INVALID', 'BlockLoader received a nested preload');
+ return err([
+ {
+ code: 'INVALID' as const,
+ message: 'BlockLoader received a nested preload',
+ },
+ ]);
}
return ok({
...data,
@@ -111,19 +117,22 @@ Check that the load function does not return a preload source when the intent is
return;
}
- const [, data] = result;
- setError(() => {
- if (isErr(result, 'UNAUTHORIZED')) {
- return 'UNAUTHORIZED';
- } else if (isErr(result, 'MISSING')) {
- return 'MISSING';
- } else if (isErr(result, 'GONE')) {
- return 'GONE';
- } else if (isErr(result)) {
+ if (result.isErr()) {
+ setError(() => {
+ if (result.error.some((error) => error.code === 'UNAUTHORIZED')) {
+ return 'UNAUTHORIZED';
+ } else if (result.error.some((error) => error.code === 'MISSING')) {
+ return 'MISSING';
+ } else if (result.error.some((error) => error.code === 'GONE')) {
+ return 'GONE';
+ }
return 'INVALID';
- }
- return null;
- });
+ });
+ return;
+ }
+
+ const data = result.value;
+ setError(null);
if (!isNested && !isPreview && data) {
// we need to pass in a client accessor since the mutation is dynamically imported outside a query context provider
diff --git a/js/app/packages/core/service.ts b/js/app/packages/core/service.ts
index b0c563425d..b987afb0be 100644
--- a/js/app/packages/core/service.ts
+++ b/js/app/packages/core/service.ts
@@ -1,6 +1,7 @@
+import type { ResultError } from '@core/util/result';
+import type { Result } from 'neverthrow';
import { z } from 'zod';
import type { FlattenObject } from './util/flatten';
-import type { MaybeError, MaybeResult } from './util/maybeResult';
type ErrorDef = {
code: string;
@@ -262,13 +263,13 @@ type ClientFunctionArgs<T> =
: never;
type ClientFunctionResult<T> =
- T extends FunctionDefinition<any, any, infer Result, infer Throws>
- ? Result extends z.ZodRawShape | AnyZodType
+ T extends FunctionDefinition<any, any, infer Output, infer Throws>
+ ? Output extends z.ZodRawShape | AnyZodType
? Throws extends string[]
- ? MaybeResult<Throws[number], ZodResultToType<Result>>
- : ZodResultToType<Result>
+ ? Result<ZodResultToType<Output>, ResultError<Throws[number]>[]>
+ : ZodResultToType<Output>
: Throws extends string[]
- ? MaybeError<Throws[number]>
+ ? Result<void, ResultError<Throws[number]>[]>
: void
: never;
diff --git a/js/app/packages/core/signal/mention.ts b/js/app/packages/core/signal/mention.ts
index f192782fa9..688de6337e 100644
--- a/js/app/packages/core/signal/mention.ts
+++ b/js/app/packages/core/signal/mention.ts
@@ -1,5 +1,5 @@
import { ENABLE_MENTION_TRACKING } from '@core/constant/featureFlags';
-import { isErr } from '@core/util/maybeResult';
+
import { commsServiceClient } from '@service-comms/client';
import type { ItemType } from '@service-storage/client';
import { getPermissionToken } from './token';
@@ -25,12 +25,12 @@ export async function trackMention(
token
);
- if (isErr(response)) {
+ if (response.isErr()) {
console.error('Failed to track document mention', response);
return;
}
- return response[1]?.id;
+ return response.value?.id;
}
export async function untrackMention(
@@ -48,7 +48,7 @@ export async function untrackMention(
token
);
- if (isErr(response)) {
+ if (response.isErr()) {
console.error('Failed to untrack document mention', response);
}
}
diff --git a/js/app/packages/core/signal/profilePicture.ts b/js/app/packages/core/signal/profilePicture.ts
index 8da45533ad..174efb3045 100644
--- a/js/app/packages/core/signal/profilePicture.ts
+++ b/js/app/packages/core/signal/profilePicture.ts
@@ -1,5 +1,5 @@
import { debounce } from '@core/util/debounce';
-import { isErr } from '@core/util/maybeResult';
+
import { authServiceClient } from '@service-auth/client';
import {
type Accessor,
@@ -51,12 +51,12 @@ async function fetchProfilePictures(
const result = await authServiceClient.postProfilePictures({
user_id_list: ids,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch user profile pictures');
return [];
}
- const [, { pictures }] = result;
+ const { pictures } = result.value;
return pictures.map(({ id, url }) => ({
_createdAt: new Date(),
id,
diff --git a/js/app/packages/core/signal/token.ts b/js/app/packages/core/signal/token.ts
index c020123352..a41a9482b5 100644
--- a/js/app/packages/core/signal/token.ts
+++ b/js/app/packages/core/signal/token.ts
@@ -1,5 +1,5 @@
import { useBlockId } from '@core/block';
-import { isErr } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
import { createStore, type SetStoreFunction, type Store } from 'solid-js/store';
@@ -20,12 +20,12 @@ async function fetchNewToken(blockId: string) {
document_id: blockId,
});
- if (isErr(token)) {
- console.error('Failed to create permission token:', token);
+ if (token.isErr()) {
+ console.error('Failed to create permission token:', token.error);
return;
}
- return token[1].token;
+ return token.value.token;
}
function isTokenExpired(token: string) {
diff --git a/js/app/packages/core/signal/unfurl.ts b/js/app/packages/core/signal/unfurl.ts
index 2f1663a781..3a59796866 100644
--- a/js/app/packages/core/signal/unfurl.ts
+++ b/js/app/packages/core/signal/unfurl.ts
@@ -1,5 +1,5 @@
import { debounce } from '@core/util/debounce';
-import { isErr } from '@core/util/maybeResult';
+
import { UnfurlServiceClient } from '@service-unfurl/client';
import type { GetUnfurlResponse } from '@service-unfurl/generated/schemas/getUnfurlResponse';
import {
@@ -75,7 +75,7 @@ async function batchFetchUnfurls(urls: string[]) {
const result = await UnfurlServiceClient.unfurlBulk({ url_list: urls });
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch unfurl bulk data');
const errorUpdates: UnfurlStore = {};
urls.forEach((url) => {
@@ -85,7 +85,7 @@ async function batchFetchUnfurls(urls: string[]) {
return;
}
- const [, data] = result;
+ const data = result.value;
const successUpdates: UnfurlStore = {};
data.responses.forEach((unfurl) => {
diff --git a/js/app/packages/core/tests/token.test.ts b/js/app/packages/core/tests/token.test.ts
index 0fab189d02..1f9578acf5 100644
--- a/js/app/packages/core/tests/token.test.ts
+++ b/js/app/packages/core/tests/token.test.ts
@@ -1,3 +1,4 @@
+import { err, ok } from 'neverthrow';
import { createRoot } from 'solid-js';
import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -36,7 +37,7 @@ describe('getPermissionToken', () => {
const mockToken = 'new-token';
vi.mocked(
storageServiceClient.permissionsTokens.createPermissionToken
- ).mockResolvedValue([null, { token: mockToken }]);
+ ).mockResolvedValue(ok({ token: mockToken }));
const token = await createRoot(async () => {
return await getPermissionToken('document', 'block-123');
@@ -80,7 +81,7 @@ describe('getPermissionToken', () => {
vi.mocked(
storageServiceClient.permissionsTokens.createPermissionToken
- ).mockResolvedValue([null, { token: newToken }]);
+ ).mockResolvedValue(ok({ token: newToken }));
const token = await createRoot(async () => {
return await getPermissionToken('document', 'block-123', [
@@ -100,10 +101,9 @@ describe('getPermissionToken', () => {
it('should return undefined when token fetch fails', async () => {
vi.mocked(
storageServiceClient.permissionsTokens.createPermissionToken
- ).mockResolvedValue([
- [{ code: 'NETWORK_ERROR', message: 'Failed to create token' }],
- null,
- ]);
+ ).mockResolvedValue(
+ err([{ code: 'NETWORK_ERROR', message: 'Failed to create token' }])
+ );
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -114,7 +114,7 @@ describe('getPermissionToken', () => {
expect(token).toBeUndefined();
expect(consoleSpy).toHaveBeenCalledWith(
'Failed to create permission token:',
- [[{ code: 'NETWORK_ERROR', message: 'Failed to create token' }], null]
+ [{ code: 'NETWORK_ERROR', message: 'Failed to create token' }]
);
expect(consoleSpy).toHaveBeenCalledWith('Failed to fetch permission token');
});
diff --git a/js/app/packages/core/user/displayName.ts b/js/app/packages/core/user/displayName.ts
index b019d22680..4ab337c33f 100644
--- a/js/app/packages/core/user/displayName.ts
+++ b/js/app/packages/core/user/displayName.ts
@@ -1,5 +1,5 @@
import { debounce } from '@core/util/debounce';
-import { isErr } from '@core/util/maybeResult';
+
import { authServiceClient } from '@service-auth/client';
import { createEffect, createSignal } from 'solid-js';
import { createStore, unwrap } from 'solid-js/store';
@@ -55,12 +55,12 @@ async function fetchDisplayNames(ids: string[]): Promise<UserNameItem[]> {
const result = await authServiceClient.getUserNamesWithEmail({
user_ids: ids,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch user display names');
return [];
}
- const [, data] = result;
+ const data = result.value;
return data.names.map((name) => {
return {
_createdAt: new Date(),
diff --git a/js/app/packages/core/util/branchName.ts b/js/app/packages/core/util/branchName.ts
index 8983fafaac..1bf2cb9c36 100644
--- a/js/app/packages/core/util/branchName.ts
+++ b/js/app/packages/core/util/branchName.ts
@@ -1,18 +1,18 @@
import { analytics } from '@app/lib/analytics';
import { toast } from '@core/component/Toast/Toast';
-import { isOk } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
export const copyBranchNameToClipboard = async (documentId: string) => {
const result = await storageServiceClient.getDocumentBranchName({
documentId,
});
- if (!isOk(result)) {
+ if (!result.isOk()) {
toast.failure('Failed to copy branch name');
return;
}
try {
- await navigator.clipboard.writeText(result[1].branchName);
+ await navigator.clipboard.writeText(result.value.branchName);
analytics.track('task_copy_branch_name');
toast.success('Branch name copied to clipboard');
} catch {
diff --git a/js/app/packages/core/util/cache.spec.ts b/js/app/packages/core/util/cache.spec.ts
index 000f2bae89..2d3896d2e7 100644
--- a/js/app/packages/core/util/cache.spec.ts
+++ b/js/app/packages/core/util/cache.spec.ts
@@ -1,6 +1,7 @@
+import { err, ok, type Result } from 'neverthrow';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { cache } from './cache';
-import { err, type MaybeResult, ok } from './maybeResult';
+import type { ResultError } from './result';
describe('cache', () => {
let mockFn: ReturnType<typeof vi.fn>;
@@ -36,7 +37,9 @@ describe('cache', () => {
});
test('not cache error results', async () => {
- mockFn = vi.fn(() => Promise.resolve(err('ERROR', 'Test error')));
+ mockFn = vi.fn(() =>
+ Promise.resolve(err([{ code: 'ERROR', message: 'Test error' }]))
+ );
const cachedFn = cache(mockFn, { minutes: 5 });
await cachedFn('arg1', 'arg2');
@@ -78,9 +81,11 @@ describe('cache', () => {
test('handle promises that resolve after expiration time', async () => {
const slowMockFn = vi.fn(
(_arg: string) =>
- new Promise<MaybeResult<string, { data: string }>>((resolve) => {
- setTimeout(() => resolve(ok({ data: 'slow test' })), 100);
- })
+ new Promise<Result<{ data: string }, ResultError<string>[]>>(
+ (resolve) => {
+ setTimeout(() => resolve(ok({ data: 'slow test' })), 100);
+ }
+ )
);
const cachedFn = cache(slowMockFn, { minutes: 1 });
diff --git a/js/app/packages/core/util/cache.ts b/js/app/packages/core/util/cache.ts
index 1e64ac8ef3..a0fa433a2f 100644
--- a/js/app/packages/core/util/cache.ts
+++ b/js/app/packages/core/util/cache.ts
@@ -1,7 +1,8 @@
-import { isErr, type MaybeResult, type ObjectLike } from './maybeResult';
+import type { Result } from 'neverthrow';
+import type { ObjectLike, ResultError } from './result';
interface CacheEntry<E extends string, R extends ObjectLike> {
- result: Promise<MaybeResult<E, R>>;
+ result: Promise<Result<R, ResultError<E>[]>>;
expiresAt: number;
}
@@ -26,7 +27,7 @@ type CachedFunction<Fn extends (...args: any[]) => Promise<any> | (() => any)> =
};
/**
- * Wraps a function that returns a Promise of MaybeResult with caching functionality.
+ * Wraps a function that returns a Promise of Result with caching functionality.
* The arguments of the function are used as the key for the cache tied to this function.
*
* @param fn - The function to be cached
@@ -40,7 +41,7 @@ type CachedFunction<Fn extends (...args: any[]) => Promise<any> | (() => any)> =
* }
*
* const cachedGetUser = cache(
- * async (): Promise<MaybeResult<string, UserInfo>> => {
+ * async (): Promise<Result<UserInfo, ResultError<string>[]>> => {
* const response = await fetchUser();
* if (!response.ok) {
* return err('FETCH_ERROR', 'Failed to fetch');
@@ -80,7 +81,7 @@ export function cache<Fn extends (...args: any[]) => Promise<any>>(
};
result.then((value) => {
- if (isErr(value)) {
+ if (value.isErr()) {
cache.delete(key);
}
});
diff --git a/js/app/packages/core/util/channels.ts b/js/app/packages/core/util/channels.ts
index acf4475f37..922d84a975 100644
--- a/js/app/packages/core/util/channels.ts
+++ b/js/app/packages/core/util/channels.ts
@@ -3,7 +3,7 @@ import { useSplitLayout } from '@app/component/split-layout/layout';
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import { toast } from '@core/component/Toast/Toast';
import { invalidateContacts } from '@core/user/contactService';
-import { isErr } from '@core/util/maybeResult';
+
import { invalidateListChannels } from '@queries/channel/channels';
import { commsServiceClient, type IdResponse } from '@service-comms/client';
import type {
@@ -53,13 +53,13 @@ export function useSendMessageToPeople() {
},
});
- if (isErr(message) || !message.at(1)) {
+ if (message.isErr()) {
toast.failure('Failed to send message to people');
- console.error('failed to post message to channel', message);
+ console.error('failed to post message to channel', message.error);
return;
}
- const messageResponse = message.at(1) as IdResponse;
+ const messageResponse = message.value as IdResponse;
invalidateListChannels();
invalidateContacts();
@@ -95,14 +95,14 @@ export function useSendMessageToPeople() {
recipients: args.users,
});
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure('Failed to send message to people');
console.error('failed to create new channel to forward', result);
return;
}
return sendAndNavigateToChannel(
- result[1].channel_id,
+ result.value.channel_id,
args.content,
args.mentions,
args.attachments ?? [],
diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.ts
index 0d4f9c400d..518a2c9388 100644
--- a/js/app/packages/core/util/create.ts
+++ b/js/app/packages/core/util/create.ts
@@ -21,6 +21,7 @@ import { staticFileClient } from '@service-static-files/client';
import { storageServiceClient } from '@service-storage/client';
import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
+import { err, ok } from 'neverthrow';
import { isPaymentError } from './handlePaymentError';
import { contentHash } from './hash';
import {
@@ -28,7 +29,6 @@ import {
isCodeEditorExtensionSupported,
isCodeEditorLanguageSupported,
} from './languageQuery';
-import { err, isErr, ok } from './maybeResult';
type CreateMarkdownFileArgs = {
title?: string;
@@ -51,9 +51,9 @@ export async function createMarkdownFile(
invalidateUserQuota();
- if (isErr(result)) return;
+ if (result.isErr()) return;
- const { documentId } = result[1];
+ const { documentId } = result.value;
setPreviewOnCreate({
itemId: documentId,
@@ -107,9 +107,9 @@ export async function createTask(
invalidateUserQuota();
- if (isErr(result)) return;
+ if (result.isErr()) return;
- const { documentId } = result[1];
+ const { documentId } = result.value;
setPreviewOnCreate({
itemId: documentId,
@@ -141,25 +141,31 @@ export async function createCodeFileFromText({
if (language && !extension) {
if (!isCodeEditorLanguageSupported(language))
- return err(
- 'UNSUPPORTED_LANGUAGE',
- `${language} is not supported by the code block`
- );
+ return err([
+ {
+ code: 'UNSUPPORTED_LANGUAGE',
+ message: `${language} is not supported by the code block`,
+ },
+ ]);
finalExtension = getExtensionForLanguage(language) ?? undefined;
if (!finalExtension) {
- return err(
- 'UNSUPPORTED_LANGUAGE',
- `Could not find file extension for language: ${language}`
- );
+ return err([
+ {
+ code: 'UNSUPPORTED_LANGUAGE',
+ message: `Could not find file extension for language: ${language}`,
+ },
+ ]);
}
}
if (!finalExtension || !isCodeEditorExtensionSupported(finalExtension))
- return err(
- 'UNSUPPORTED_EXTENSION',
- `${finalExtension ?? 'undefined'} is not supported by the code block`
- );
+ return err([
+ {
+ code: 'UNSUPPORTED_EXTENSION',
+ message: `${finalExtension ?? 'undefined'} is not supported by the code block`,
+ },
+ ]);
const mimeType = 'text/plain';
@@ -172,18 +178,20 @@ export async function createCodeFileFromText({
invalidateUserQuota();
// TODO: this is kind of odd, since there's an actual code we could use for the paywall, 402 Payment Required
- if (isErr(maybeCode) && maybeCode[0][0].message.includes('403')) {
- return err('UNAUTHORIZED', maybeCode[0][0].message);
+ if (maybeCode.isErr() && maybeCode.error[0].message.includes('403')) {
+ return err([{ code: 'UNAUTHORIZED', message: maybeCode.error[0].message }]);
}
- if (isErr(maybeCode)) return err('SERVER_ERROR', maybeCode[0][0].message);
- const [, document] = maybeCode;
+ if (maybeCode.isErr())
+ return err([{ code: 'SERVER_ERROR', message: maybeCode.error[0].message }]);
+ const document = maybeCode.value;
const uploadResult = await uploadToPresignedUrl({
presignedUrl: document.presignedUrl,
buffer,
sha,
type: mimeType,
});
- if (isErr(uploadResult)) return err('SERVER_ERROR', 'Failed to upload file');
+ if (uploadResult.isErr())
+ return err([{ code: 'SERVER_ERROR', message: 'Failed to upload file' }]);
postNewHistoryItem('document', document.metadata.documentId);
setPreviewOnCreate({
itemId: document.metadata.documentId,
@@ -212,8 +220,8 @@ export async function createCanvasFileFromJsonString(args: {
projectId,
});
invalidateUserQuota();
- if (isErr(maybeCanvas)) return { error: 'Document creation failed.' };
- const [, canvas] = maybeCanvas;
+ if (maybeCanvas.isErr()) return { error: 'Document creation failed.' };
+ const canvas = maybeCanvas.value;
const uploadResult = await uploadToPresignedUrl({
presignedUrl: canvas.presignedUrl,
@@ -222,7 +230,7 @@ export async function createCanvasFileFromJsonString(args: {
type: 'application/x-macro-canvas',
});
- if (isErr(uploadResult)) return { error: 'Failed to upload file.' };
+ if (uploadResult.isErr()) return { error: 'Failed to upload file.' };
postNewHistoryItem('document', canvas.metadata.documentId);
setPreviewOnCreate({
@@ -252,13 +260,13 @@ export async function createChat(args?: CreateChatRequest) {
const maybeChat = await cognitionApiServiceClient.createChat(args ?? {});
invalidateUserQuota();
- if (isErr(maybeChat)) {
+ if (maybeChat.isErr()) {
if (isPaymentError(maybeChat)) {
showPaywall(PaywallKey.CHAT_LIMIT);
}
return { error: 'Failed to create chat.' };
}
- const [, chat] = maybeChat;
+ const chat = maybeChat.value;
postNewHistoryItem('chat', chat.id);
setPreviewOnCreate({
itemId: chat.id,
@@ -276,9 +284,9 @@ export async function createStaticFile(file: File): Promise<string> {
content_type: file.type,
});
invalidateUserQuota();
- if (isErr(result)) throw new Error('Failed to upload file');
+ if (result.isErr()) throw new Error('Failed to upload file');
- const { upload_url, id } = result[1];
+ const { upload_url, id } = result.value;
const uploadResult = await staticFileClient.uploadToPresignedUrl({
url: upload_url,
blob: file,
diff --git a/js/app/packages/core/util/estimateTextHeight.ts b/js/app/packages/core/util/estimateTextHeight.ts
index b87cb13b0f..26e2b95e3a 100644
--- a/js/app/packages/core/util/estimateTextHeight.ts
+++ b/js/app/packages/core/util/estimateTextHeight.ts
@@ -32,9 +32,9 @@ function estimateTextHeight_(
fontStyle?: TwStyle,
fontCss?: string
) {
- const maybeResult = globalThis.maxDimPx.get(fontStyleName);
- if (maybeResult)
- return calculatePxHeight(text.length, maybeResult, containerWidthPx);
+ const cachedDims = globalThis.maxDimPx.get(fontStyleName);
+ if (cachedDims)
+ return calculatePxHeight(text.length, cachedDims, containerWidthPx);
const el = document.createElement('div');
if (fontCss) el.className = fontCss;
@@ -75,9 +75,9 @@ function estimateTextHeight_(
: el.clientHeight - heightPadding;
document.body.removeChild(el);
- const result: Dims = { glyph: [maxWidth, maxHeight], heightPadding };
- globalThis.maxDimPx.set(fontStyleName, result);
- return calculatePxHeight(text.length, result, containerWidthPx);
+ const measuredDims: Dims = { glyph: [maxWidth, maxHeight], heightPadding };
+ globalThis.maxDimPx.set(fontStyleName, measuredDims);
+ return calculatePxHeight(text.length, measuredDims, containerWidthPx);
}
/**
diff --git a/js/app/packages/core/util/fetchWithToken.ts b/js/app/packages/core/util/fetchWithToken.ts
index bc0967edb1..61bbfac8a9 100644
--- a/js/app/packages/core/util/fetchWithToken.ts
+++ b/js/app/packages/core/util/fetchWithToken.ts
@@ -2,13 +2,8 @@ import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';
import { SERVER_HOSTS } from '@core/constant/servers';
import { logger } from '@observability';
import { fetchWithAuth } from '@service-auth/fetch';
-import {
- err,
- isErr,
- type MaybeError,
- type MaybeResult,
- type ObjectLike,
-} from './maybeResult';
+import { err, ok, type Result } from 'neverthrow';
+import type { ObjectLike, ResultError } from './result';
import {
type BaseFetchErrorCode,
type SafeFetchInit,
@@ -20,17 +15,19 @@ export type FetchWithTokenErrorCode = BaseFetchErrorCode;
function fetchWithCredentials<T extends ObjectLike>(
input: RequestInfo,
init?: SafeFetchInit
-): Promise<MaybeResult<BaseFetchErrorCode, T>> {
+): Promise<Result<T, ResultError<BaseFetchErrorCode>[]>> {
return safeFetch<T>(input, {
...init,
credentials: 'include',
});
}
-let tokenPromise: Promise<MaybeError<FetchWithTokenErrorCode>> | null = null;
+let tokenPromise: Promise<
+ Result<void, ResultError<FetchWithTokenErrorCode>[]>
+> | null = null;
export async function fetchToken(): Promise<
- MaybeError<FetchWithTokenErrorCode>
+ Result<void, ResultError<FetchWithTokenErrorCode>[]>
> {
if (tokenPromise == null) {
tokenPromise = (async () => {
@@ -47,12 +44,11 @@ export async function fetchToken(): Promise<
}
);
- if (isErr(result)) {
- return [result[0]!];
- // return [null, result[0]];
+ if (result.isErr()) {
+ return err(result.error);
}
- return [null];
+ return ok(undefined);
} finally {
tokenPromise = null;
}
@@ -67,7 +63,7 @@ export async function fetchToken(): Promise<
* @template T - The expected response data type.
* @param {RequestInfo} input - The resource that you wish to fetch.
* @param {SafeFetchInit} [init] - An options object containing any custom settings you want to apply to the request, including retry configuration.
- * @returns {Promise<MaybeResult<FetchWithTokenErrorCode, T>>} A promise that resolves to a MaybeResult containing either the response data or an error.
+ * @returns {Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>} A promise that resolves to a Result containing either the response data or an error.
*
* @example
* const result = await fetchWithToken<UserData>(
@@ -78,26 +74,23 @@ export async function fetchToken(): Promise<
* }
* );
*
- * if (isErr(result)) {
- * console.error('Error:', result[0]);
+ * if ((result).isErr()) {
+ * console.error('Error:', result.error);
* } else {
- * console.log('User data:', result[1]);
+ * console.log('User data:', result.value);
* }
*/
export async function fetchWithToken<T extends ObjectLike>(
input: RequestInfo,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>> {
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>> {
if (ENABLE_BEARER_TOKEN_AUTH) {
const result = await fetchWithAuth<T>(input, init);
- if (isErr(result)) {
+ if (result.isErr()) {
logger.error('fetchWithToken: fetchWithAuth failed', {
input,
init,
- cause: {
- name: 'fetchWithAuthError',
- ...result[0],
- },
+ errors: result.error,
});
}
@@ -106,15 +99,20 @@ export async function fetchWithToken<T extends ObjectLike>(
let result = await fetchWithCredentials<T>(input, init);
- if (isErr(result, 'UNAUTHORIZED')) {
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'UNAUTHORIZED')
+ ) {
const tokenResult = await fetchToken();
- if (isErr(tokenResult, 'HTTP_ERROR')) {
+ if (
+ tokenResult.isErr() &&
+ tokenResult.error.some((error) => error.code === 'HTTP_ERROR')
+ ) {
// converting this most likely a bad request to unauthorized error
- return err('UNAUTHORIZED', '');
+ return err([{ code: 'UNAUTHORIZED', message: '' }]);
}
- if (isErr(tokenResult)) {
- // Convert MaybeError to MaybeResult
- return [tokenResult[0], null];
+ if (tokenResult.isErr()) {
+ return err(tokenResult.error);
}
// Retry the original request
diff --git a/js/app/packages/core/util/handlePaymentError.ts b/js/app/packages/core/util/handlePaymentError.ts
index aca0468700..ade0928d0c 100644
--- a/js/app/packages/core/util/handlePaymentError.ts
+++ b/js/app/packages/core/util/handlePaymentError.ts
@@ -1,14 +1,18 @@
-import { isErr, type MaybeError, type MaybeResult } from './maybeResult';
+import type { Result } from 'neverthrow';
+import type { ResultError } from './result';
export function isPaymentError<T>(
- result: MaybeResult<string, T> | MaybeError<string>
+ result: Result<T, ResultError<string>[]> | Result<void, ResultError<string>[]>
): boolean {
- if (!isErr(result)) {
+ if (!result.isErr()) {
return false;
}
- if (isErr(result, 'HTTP_ERROR')) {
- const errorMessage = result[0][0].message;
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'HTTP_ERROR')
+ ) {
+ const errorMessage = result.error[0].message;
if (
errorMessage.includes('402') ||
errorMessage.includes('payment_required') ||
diff --git a/js/app/packages/core/util/maybeResult.spec.ts b/js/app/packages/core/util/maybeResult.spec.ts
deleted file mode 100644
index 4128077d76..0000000000
--- a/js/app/packages/core/util/maybeResult.spec.ts
+++ /dev/null
@@ -1,329 +0,0 @@
-import { describe, expect, test, vi } from 'vitest';
-import {
- chain,
- combine,
- err,
- isErr,
- isOk,
- type MaybeResult,
- mapOk,
- maybeLog,
- maybeThrow,
- type ObjectLike,
- ok,
- onErr,
- tryCatch,
-} from './maybeResult';
-
-describe('isErr', () => {
- test('returns false for null result', () => {
- expect(isErr([null])).toBe(false);
- });
-
- test('returns false for successful result', () => {
- expect(isErr([null, {}])).toBe(false);
- });
-
- test('returns true for empty error array', () => {
- expect(isErr([[], null])).toBe(true);
- });
-
- test('returns true for non-empty error array', () => {
- expect(isErr([[{ code: 'ERROR', message: 'Test error' }], null])).toBe(
- true
- );
- });
-
- test('returns true for error result without specifying error code', () => {
- expect(isErr([[{ code: 'ERROR', message: 'Test error' }], null])).toBe(
- true
- );
- });
-
- test('returns true when error code matches', () => {
- const result: MaybeResult<'ERROR' | 'OTHER_ERROR', {}> = [
- [{ code: 'ERROR', message: 'Test error' }],
- null,
- ];
- expect(isErr(result, 'ERROR')).toBe(true);
- });
-
- test('returns false when error code does not match', () => {
- const result: MaybeResult<'ERROR' | 'OTHER_ERROR', {}> = [
- [{ code: 'ERROR', message: 'Test error' }],
- null,
- ];
- expect(isErr(result, 'OTHER_ERROR')).toBe(false);
- });
-
- test('returns true when at least one error code matches in multiple errors', () => {
- const result: MaybeResult<'ERROR' | 'OTHER_ERROR', {}> = [
- [
- { code: 'ERROR', message: 'Test error' },
- { code: 'OTHER_ERROR', message: 'Another error' },
- ],
- null,
- ];
- expect(isErr(result, 'OTHER_ERROR')).toBe(true);
- });
-});
-
-describe('isOk', () => {
- test('returns true for null result', () => {
- expect(isOk([null])).toBe(true);
- });
-
- test('returns true for successful result', () => {
- expect(isOk([null, {}])).toBe(true);
- });
-
- test('returns false for empty error array', () => {
- expect(isOk([[], null])).toBe(false);
- });
-
- test('returns false for non-empty error array', () => {
- expect(isOk([[{ code: 'ERROR', message: 'Test error' }], null])).toBe(
- false
- );
- });
-});
-
-describe('maybeThrow', () => {
- test('returns value for successful result', () => {
- expect(maybeThrow([null, { value: 42 }])).toEqual({ value: 42 });
- });
-
- test('throws error for error result', () => {
- expect(() =>
- maybeThrow([[{ code: 'ERROR', message: 'Test error' }], null])
- ).toThrow('Test error');
- });
-});
-
-describe('maybeLog', () => {
- test('returns value for successful result', () => {
- const consoleSpy = vi.spyOn(console, 'error');
- expect(maybeLog([null, { value: 42 }])).toEqual({ value: 42 });
- expect(consoleSpy).not.toHaveBeenCalled();
- consoleSpy.mockRestore();
- });
-
- test('logs error and returns undefined for error result', () => {
- const consoleSpy = vi.spyOn(console, 'error');
- expect(
- maybeLog([[{ code: 'ERROR', message: 'Test error' }], null])
- ).toBeUndefined();
- expect(consoleSpy).toHaveBeenCalledWith('Error:', 'Test error');
- consoleSpy.mockRestore();
- });
-});
-
-describe('tryCatch', () => {
- test('returns value for successful function', async () => {
- const successFn = async () =>
- [null, { value: 42 }] as MaybeResult<string, { value: number }>;
- const errorHandler = vi.fn();
- expect(await tryCatch(successFn, errorHandler)).toEqual({ value: 42 });
- expect(errorHandler).not.toHaveBeenCalled();
- });
-
- test('calls error handler and returns undefined for error function', async () => {
- const errorFn = async () =>
- [[{ code: 'ERROR', message: 'Test error' }], null] as MaybeResult<
- string,
- {}
- >;
- const errorHandler = vi.fn();
- expect(await tryCatch(errorFn, errorHandler)).toBeUndefined();
- expect(errorHandler).toHaveBeenCalledWith([
- { code: 'ERROR', message: 'Test error' },
- ]);
- });
-});
-
-describe('mapOk', () => {
- test('applies function to successful result', () => {
- expect(
- mapOk([null, { value: 42 }], (v) => ({ doubled: v.value * 2 }))
- ).toEqual([null, { doubled: 84 }]);
- });
-
- test('passes through error result', () => {
- expect(
- mapOk([[{ code: 'ERROR', message: 'Test error' }], null], () => ({
- doubled: 0,
- }))
- ).toEqual([[{ code: 'ERROR', message: 'Test error' }], null]);
- });
-});
-
-describe('chain', () => {
- const double = (v: {
- value: number;
- }): MaybeResult<string, { doubled: number }> => ok({ doubled: v.value * 2 });
-
- const square = (v: {
- doubled: number;
- }): MaybeResult<string, { squared: number }> =>
- ok({ squared: v.doubled ** 2 });
-
- const errorFn = (): MaybeResult<string, never> => err('ERROR', 'Test error');
-
- test('chains multiple successful functions', () => {
- const result = chain(ok({ value: 5 }), double, square);
- expect(result).toEqual([null, { squared: 100 }]);
- });
-
- test('short-circuits on first error', () => {
- const result = chain(ok({ value: 5 }), double, errorFn, square);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- expect(result[0]).toEqual([{ code: 'ERROR', message: 'Test error' }]);
- }
- });
-
- test('works with single function', () => {
- const result = chain(ok({ value: 5 }), double);
- expect(result).toEqual([null, { doubled: 10 }]);
- });
-
- test('works with no functions', () => {
- const initial: MaybeResult<string, { value: number }> = ok({ value: 5 });
- const result = chain(initial);
- expect(result).toEqual(initial);
- });
-
- test('handles initial error', () => {
- const initial: MaybeResult<string, never> = err(
- 'INITIAL_ERROR',
- 'Initial error'
- );
- const result = chain(initial, double, square);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- expect(result[0]).toEqual([
- { code: 'INITIAL_ERROR', message: 'Initial error' },
- ]);
- }
- });
-});
-describe('combine', () => {
- const result1: MaybeResult<string, ObjectLike> = [null, { value: 42 }];
- const result2: MaybeResult<string, ObjectLike> = [null, { text: 'hello' }];
- const result3: MaybeResult<string, ObjectLike> = [
- [{ code: 'ERROR', message: 'Test error' }],
- null,
- ];
-
- test('combines multiple successful results', () => {
- expect(combine(result1, result2)).toEqual([
- null,
- [{ value: 42 }, { text: 'hello' }],
- ]);
- });
-
- test('returns error when one result is an error', () => {
- const errorResult = combine(result1, result3);
- expect(errorResult[0]).toEqual([{ code: 'ERROR', message: 'Test error' }]);
- expect(errorResult[1]).toEqual(null);
- });
-
- test('returns all errors when multiple results are errors', () => {
- const result4: MaybeResult<string, ObjectLike> = [
- [{ code: 'ANOTHER_ERROR', message: 'Another error' }],
- null,
- ];
- const errorResult = combine(result1, result3, result4);
- expect(errorResult[0]).toEqual([
- { code: 'ERROR', message: 'Test error' },
- { code: 'ANOTHER_ERROR', message: 'Another error' },
- ]);
- expect(errorResult[1]).toEqual(null);
- });
-});
-
-describe('onErr', () => {
- test('returns false for successful result', () => {
- const handlers = {
- ERROR: vi.fn(),
- };
- expect(onErr([null, { value: 42 }], handlers)).toBe(false);
- expect(handlers.ERROR).not.toHaveBeenCalled();
- });
-
- test('calls handler and returns false for non-fatal error', () => {
- const handlers = {
- NON_FATAL: vi.fn(),
- };
- const result: MaybeResult<'NON_FATAL', {}> = [
- [{ code: 'NON_FATAL', message: 'Non-fatal error' }],
- null,
- ];
- expect(onErr(result, handlers)).toBe(false);
- expect(handlers.NON_FATAL).toHaveBeenCalledWith({
- code: 'NON_FATAL',
- message: 'Non-fatal error',
- });
- });
-
- test('calls handler and returns true for fatal error', () => {
- const handlers = {
- FATAL: vi.fn(),
- };
- const result: MaybeResult<'FATAL', {}> = [
- [{ code: 'FATAL', message: 'Fatal error', fatal: true }],
- null,
- ];
- expect(onErr(result, handlers)).toBe(true);
- expect(handlers.FATAL).toHaveBeenCalledWith({
- code: 'FATAL',
- message: 'Fatal error',
- fatal: true,
- });
- });
-
- test('calls multiple handlers for multiple non-fatal errors', () => {
- const handlers = {
- ERROR1: vi.fn(),
- ERROR2: vi.fn(),
- };
- const result: MaybeResult<'ERROR1' | 'ERROR2', {}> = [
- [
- { code: 'ERROR1', message: 'First error' },
- { code: 'ERROR2', message: 'Second error' },
- ],
- null,
- ];
- expect(onErr(result, handlers)).toBe(false);
- expect(handlers.ERROR1).toHaveBeenCalledWith({
- code: 'ERROR1',
- message: 'First error',
- });
- expect(handlers.ERROR2).toHaveBeenCalledWith({
- code: 'ERROR2',
- message: 'Second error',
- });
- });
-
- test('stops after encountering a fatal error', () => {
- const handlers = {
- NON_FATAL: vi.fn(),
- FATAL: vi.fn(),
- AFTER_FATAL: vi.fn(),
- };
- const result: MaybeResult<'NON_FATAL' | 'FATAL' | 'AFTER_FATAL', {}> = [
- [
- { code: 'NON_FATAL', message: 'Non-fatal error' },
- { code: 'FATAL', message: 'Fatal error', fatal: true },
- { code: 'AFTER_FATAL', message: 'This should not be processed' },
- ],
- null,
- ];
- expect(onErr(result, handlers)).toBe(true);
- expect(handlers.NON_FATAL).toHaveBeenCalled();
- expect(handlers.FATAL).toHaveBeenCalled();
- expect(handlers.AFTER_FATAL).not.toHaveBeenCalled();
- });
-});
-
-// ... (rest of the file remains unchanged)
diff --git a/js/app/packages/core/util/maybeResult.ts b/js/app/packages/core/util/maybeResult.ts
deleted file mode 100644
index 52abe9a700..0000000000
--- a/js/app/packages/core/util/maybeResult.ts
+++ /dev/null
@@ -1,435 +0,0 @@
-export interface Error {
- description?: string;
- fatal?: true;
- arg?: string;
-}
-
-export interface ResultError<Code extends string = string> extends Error {
- code: Code;
- message: string;
-}
-
-export type MaybeError<ErrorCode extends string> =
- | [null]
- | [ResultError<ErrorCode>[]];
-
-export type ObjectLike = Record<string, any>;
-// switched from Record<string, unknown> to unknown to avoid type inference issues
-// when using the result in a function signature, the type can use NonNullable<T>
-// to ensure that the result is not null and thus a result type
-type UnknownObjectLike = unknown;
-
-export type MaybeResult<ErrorCode extends string, T> =
- | [null, T]
- | [ResultError<ErrorCode>[], null];
-
-/**
- * Checks if the result is an error, optionally checking for a specific error code.
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The type of the successful result value.
- * @param {MaybeError<ErrorCode> | MaybeResult<ErrorCode, UnknownObjectLike>} result - The result to check.
- * @param {ErrorCode} [errorCode] - Optional specific error code to check for.
- * @returns {boolean} True if the result is an error (and matches the specified error code if provided), false otherwise.
- */
-export function isErr<ErrorCode extends string>(
- result: MaybeError<string> | MaybeResult<string, any>,
- errorCode: ErrorCode
-): result is [ResultError<ErrorCode>[], null];
-export function isErr<ErrorCode extends string>(
- result: MaybeError<ErrorCode> | MaybeResult<ErrorCode, any>
-): result is [ResultError<ErrorCode>[], null];
-export function isErr<ErrorCode extends string = string>(
- result: MaybeError<ErrorCode> | MaybeResult<ErrorCode, any>,
- errorCode?: ErrorCode
-): result is [ResultError<ErrorCode>[], null] {
- if (result[0] == null) {
- return false;
- }
- return (
- errorCode == null || result[0].some((error) => error.code === errorCode)
- );
-}
-
-/**
- * Checks if the result is ok (not an error).
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The type of the successful result value.
- * @param {MaybeError<ErrorCode> | MaybeResult<ErrorCode, T>} result - The result to check.
- * @returns {boolean} True if the result is ok, false otherwise.
- */
-export function isOk<ErrorCode extends string, T extends UnknownObjectLike>(
- result: MaybeError<ErrorCode> | MaybeResult<ErrorCode, T>
-): result is [null] | [null, T] {
- return result[0] === null;
-}
-
-/**
- * Unwraps a MaybeResult, throwing an error if it's an error result.
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The type of the successful result value.
- * @param {MaybeResult<ErrorCode, T>} result - The result to unwrap.
- * @returns {T} The unwrapped value if the result is ok.
- * @throws {Error} If the result is an error, with all error messages joined.
- */
-export function maybeThrow<
- ErrorCode extends string,
- T extends UnknownObjectLike,
->(result: MaybeResult<ErrorCode, T>): T {
- if (isErr(result)) {
- throw new Error(result[0].map((e) => e.message).join(', '));
- }
- return result[1];
-}
-
-/**
- * Unwraps a MaybeResult, logging an error to the console if it's an error result.
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The type of the successful result value.
- * @param {MaybeResult<ErrorCode, T>} result - The result to unwrap.
- * @returns {T | undefined} The unwrapped value if the result is ok, undefined if it's an error.
- */
-export function maybeLog<const T extends UnknownObjectLike>(
- result: MaybeResult<any, T>
-): T | undefined {
- if (isErr(result)) {
- console.error('Error:', result[0].map((e) => e.message).join(', '));
- return undefined;
- }
- return result[1];
-}
-
-/**
- * Safely executes a function that returns a MaybeResult and handles errors.
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The type of the successful result value.
- * @param {() => Promise<MaybeResult<ErrorCode, T>>} fn - The function to execute.
- * @param {(errors: ResultError<ErrorCode>[]) => void} errorHandler - The function to handle errors.
- * @returns {Promise<T | undefined>} The result value if successful, undefined if an error occurred.
- */
-export async function tryCatch<
- ErrorCode extends string,
- T extends UnknownObjectLike,
->(
- fn: () => Promise<MaybeResult<ErrorCode, T>> | MaybeResult<ErrorCode, T>,
- errorHandler: (errors: ResultError<ErrorCode>[]) => void
-): Promise<T | undefined> {
- const result = await fn();
- if (isErr(result)) {
- errorHandler(result[0]);
- return undefined;
- }
- return result[1];
-}
-
-/**
- * Maps over an ok result, or passes through an error.
- * @template ErrorCode - The type of error codes used in the result.
- * @template MR - The type of the input resul.
- * @template U - The type of the output result
- * @param {MaybeResult<ErrorCode, MR>} result - The result to map
- * @param {(value: ResultType<MR>) => U} fn - The function to apply to the ok value.
- * @returns {MaybeResult<ErrorCode, U>} A new MaybeResult with the mapped value or the original error.
- */
-export function mapOk<
- ErrorCode extends string,
- MR extends MaybeResult<ErrorCode, NonNullable<any>>,
- U,
->(result: MR, fn: (value: ResultType<MR>) => U): MaybeResult<ErrorCode, U> {
- if (isErr(result)) {
- return result;
- }
- return [null, fn(result[1])];
-}
-
-/**
- * Chains multiple MaybeResult-returning functions, short-circuiting on errors.
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The tuple type representing the types of the input and intermediate results.
- * @param {MaybeResult<ErrorCode, T[0]>} initial - The initial result.
- * @param {...Array<(value: any) => MaybeResult<ErrorCode, any>>} fns - The functions to chain.
- * @returns {MaybeResult<ErrorCode, T[number]>} The result of the last chained function or the first encountered error.
- *
- * @example
- * const result = chain(
- * ok({ value: 5 }),
- * (v) => ok({ doubled: v.value * 2 }),
- * (v) => ok({ squared: v.doubled ** 2 })
- * );
- * // result will be [null, { squared: 100 }]
- *
- * @example
- * const result = chain(
- * ok({ value: 5 }),
- * (v) => ok({ doubled: v.value * 2 }),
- * (v) => err('NOT_OKAY', 'Value is NOT okay'),
- * (v) => ok({ final: v }) // This function won't be called due to the previous error
- * );
- * // result will be [[{ code: 'NOT_OKAY', message: 'Value is NOT okay' }], null]
- */
-export function chain<ErrorCode extends string, T extends any[]>(
- initial: MaybeResult<ErrorCode, T[0]>,
- ...fns: Array<(value: any) => MaybeResult<ErrorCode, any>>
-): MaybeResult<ErrorCode, T[number]> {
- let result = initial;
- for (const fn of fns) {
- if (isErr(result)) {
- return result;
- }
- result = fn(result[1]);
- }
- return result;
-}
-
-/**
- * Combines multiple MaybeResults into a single MaybeResult.
- * @template ErrorCode - The type of error codes used in the results.
- * @template T - The tuple type representing the types of the input results.
- * @param {...MaybeResult<ErrorCode, T[number]>} results - The results to combine.
- * @returns {MaybeResult<ErrorCode, T>} A combined MaybeResult with all values or all errors.
- */
-export function combine<ErrorCode extends string, T extends any[]>(
- ...results: { [K in keyof T]: MaybeResult<ErrorCode, T[K]> }
-): MaybeResult<ErrorCode, T> | MaybeResult<ErrorCode, {}> {
- const errors: ResultError<ErrorCode>[] = [];
- const values: any[] = [];
-
- for (const result of results) {
- if (isErr(result)) {
- errors.push(...result[0]);
- } else {
- values.push(result[1]);
- }
- }
-
- if (errors.length > 0) {
- return [errors, null];
- }
-
- return [null, values as T];
-}
-
-export function ok<T>(result: T): [null, T] {
- return [null, result];
-}
-
-export function err<ErrorCode extends string>(
- code: ErrorCode,
- message: string
-): [ResultError<ErrorCode>[], null] {
- return [
- [
- {
- code,
- message,
- },
- ],
- null,
- ];
-}
-
-export function onlyErr<ErrorCode extends string>(
- code: ErrorCode,
- message: string
-): [[ResultError<ErrorCode>]] {
- return [
- [
- {
- code,
- message,
- },
- ],
- ];
-}
-
-/**
- * Handles different error codes with specific functions, stopping on the first fatal error.
- * @template ErrorCode - The type of error codes used in the result.
- * @template T - The type of the successful result value.
- * @template Handlers - The type of the handlers object, with a handler for each error code.
- * @param {MaybeResult<ErrorCode, T>} result - The result to handle.
- * @param {Handlers} handlers - An object with error handling functions for each error code.
- * @returns {boolean} True if a fatal error was encountered, false otherwise.
- *
- * @example
- * type MyErrorCode = 'NEGATIVE' | 'TOO_LARGE';
- *
- * interface SuccessResult {
- * value: number;
- * }
- *
- * function someOperation(input: number): MaybeResult<MyErrorCode, SuccessResult> {
- * if (input < 0) return err('NEGATIVE', 'Input is negative', { fatal: true });
- * if (input > 100) return err('TOO_LARGE', 'Input is too large');
- * return ok({ value: input });
- * }
- *
- * function processInput(input: number) {
- * const result = someOperation(input);
- *
- * if (onErr(result, {
- * NEGATIVE(error) {
- * console.log('Fatal error:', error.message);
- * // This is a fatal error, so processing will stop here
- * },
- * TOO_LARGE(error) {
- * console.log('Non-fatal error:', error.message);
- * // This error is non-fatal, so processing will continue
- * },
- * })) {
- * console.log('A fatal error occurred. Stopping process.');
- * return;
- * }
- *
- * if (isOk(result)) {
- * console.log('Operation successful, result:', result[1].value);
- * }
- * }
- *
- * processInput(-5); // Will log: "Fatal error: Input is negative" and "A fatal error occurred. Stopping process."
- * processInput(150); // Will log: "Non-fatal error: Input is too large" and "Operation completed with non-fatal errors."
- * processInput(25); // Will log: "Another non-fatal error: Input is not even" and "Operation completed with non-fatal errors."
- * processInput(50); // Will log: "Operation successful, result: 50"
- */
-export function onErr<
- ErrorCode extends string,
- T extends UnknownObjectLike,
- Handlers extends Record<ErrorCode, (error: ResultError<ErrorCode>) => void>,
->(result: MaybeResult<ErrorCode, T>, handlers: Handlers): boolean {
- if (isErr(result)) {
- for (const error of result[0]) {
- handlers[error.code](error);
- if (error.fatal) {
- return true;
- }
- }
- }
- return false;
-}
-
-export type ResultType<T extends MaybeResult<any, any>> =
- T extends MaybeResult<any, infer R> ? NonNullable<R> : never;
-
-/**
- * Error class that preserves MaybeResult errors when thrown.
- * Enables round-trip conversion between MaybeResult and throwable functions.
- */
-export class MaybeResultError<E extends string = string> extends Error {
- constructor(public readonly errors: ResultError<E>[]) {
- super(errors.map((e) => e.message).join(', '));
- this.name = 'MaybeResultError';
- }
-}
-
-/**
- * Wraps a MaybeResult-returning async function to throw on error.
- * Useful for tanstack-query and other APIs that expect thrown errors.
- */
-export async function throwOnErr<E extends string>(
- fn: () => Promise<MaybeError<E>>
-): Promise<void>;
-export async function throwOnErr<E extends string, T>(
- fn: () => Promise<MaybeResult<E, T>>
-): Promise<T>;
-export async function throwOnErr<E extends string, T>(
- fn: () => Promise<MaybeError<E> | MaybeResult<E, T>>
-): Promise<T | void> {
- const result = await fn();
- if (isErr(result)) {
- throw new MaybeResultError(result[0]);
- }
- if (result.length > 1) return (result as [null, T])[1];
-}
-
-/**
- * Wraps an async throwable function to return MaybeResult instead.
- * Preserves MaybeResultError errors; wraps other errors as UNKNOWN.
- */
-export async function catchToResult<T>(
- throwable: () => Promise<T>
-): Promise<MaybeResult<string, T>> {
- try {
- return ok(await throwable());
- } catch (error) {
- if (error instanceof MaybeResultError) {
- return [error.errors, null];
- }
- return err(
- 'UNKNOWN',
- error instanceof Error ? error.message : String(error)
- );
- }
-}
-
-/**
- * A hybrid type that acts as both a single ResultError and an array containing that error.
- * Provides backward compatibility by allowing access to error properties directly
- * while maintaining array functionality.
- */
-export type HybridResultError<ErrorCode extends string> =
- ResultError<ErrorCode> &
- [ResultError<ErrorCode>] & {
- readonly length: 1;
- };
-
-export function resultError<ErrorCode extends string>(
- error: ResultError<ErrorCode>
-): HybridResultError<ErrorCode> {
- return toHybridError([error]);
-}
-
-/**
- * Converts an array of ResultError to a hybrid object that acts as both
- * a single error and an array containing that error.
- *
- * @template ErrorCode - The type of error codes used in the result.
- * @param {ResultError<ErrorCode>[]} errors - The array of errors to convert.
- * @returns {HybridResultError<ErrorCode>} A hybrid object with both error properties and array methods.
- *
- * @example
- * const errors: ResultError<'NOT_FOUND'>[] = [{ code: 'NOT_FOUND', message: 'Item not found' }];
- * const hybrid = toHybridError(errors);
- *
- * // Access as single error
- * console.log(hybrid.code); // 'NOT_FOUND'
- * console.log(hybrid.message); // 'Item not found'
- *
- * // Access as array
- * console.log(hybrid.length); // 1
- * console.log(hybrid[0].code); // 'NOT_FOUND'
- * console.log(hybrid.map(e => e.code)); // ['NOT_FOUND']
- *
- * // Maintains backward compatibility
- * console.log(hybrid.code === hybrid[0].code); // true
- */
-export function toHybridError<ErrorCode extends string>(
- errors: ResultError<ErrorCode>[]
-): HybridResultError<ErrorCode> {
- if (errors.length === 0) {
- throw new Error('Cannot create hybrid error from empty array');
- }
-
- // Take the first error as the primary error
- const primaryError = errors[0];
-
- // Create an array with just the primary error
- const errorArray = [primaryError] as [ResultError<ErrorCode>];
-
- // Create the hybrid object by copying error properties to the array
- const hybrid = Object.assign(errorArray, {
- code: primaryError.code,
- message: primaryError.message,
- description: primaryError.description,
- fatal: primaryError.fatal,
- arg: primaryError.arg,
- }) as HybridResultError<ErrorCode>;
-
- // Ensure length is readonly and always 1
- Object.defineProperty(hybrid, 'length', {
- value: 1,
- writable: false,
- enumerable: false,
- configurable: false,
- });
-
- return hybrid;
-}
diff --git a/js/app/packages/core/util/result.spec.ts b/js/app/packages/core/util/result.spec.ts
new file mode 100644
index 0000000000..4223adb878
--- /dev/null
+++ b/js/app/packages/core/util/result.spec.ts
@@ -0,0 +1,50 @@
+import { err, ok } from 'neverthrow';
+import { describe, expect, it } from 'vitest';
+import { catchToResult, ThrownResultError, throwOnErr } from './result';
+
+describe('throwOnErr', () => {
+ it('returns ok values', async () => {
+ await expect(throwOnErr(async () => ok({ value: 42 }))).resolves.toEqual({
+ value: 42,
+ });
+ });
+
+ it('throws a ThrownResultError for err values', async () => {
+ const error = [{ code: 'ERROR', message: 'Test error' }];
+
+ await expect(throwOnErr(async () => err(error))).rejects.toMatchObject({
+ errors: error,
+ message: 'Test error',
+ });
+ });
+});
+
+describe('catchToResult', () => {
+ it('returns ok values', async () => {
+ const result = await catchToResult(async () => ({ value: 42 }));
+
+ expect(result.isOk()).toBe(true);
+ if (result.isOk()) expect(result.value).toEqual({ value: 42 });
+ });
+
+ it('preserves thrown result errors', async () => {
+ const errors = [{ code: 'ERROR', message: 'Test error' }];
+ const result = await catchToResult(async () => {
+ throw new ThrownResultError(errors);
+ });
+
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) expect(result.error).toEqual(errors);
+ });
+
+ it('converts regular thrown errors', async () => {
+ const result = await catchToResult(async () => {
+ throw new Error('Boom');
+ });
+
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ expect(result.error).toEqual([{ code: 'UNKNOWN', message: 'Boom' }]);
+ }
+ });
+});
diff --git a/js/app/packages/core/util/result.ts b/js/app/packages/core/util/result.ts
new file mode 100644
index 0000000000..38380ef640
--- /dev/null
+++ b/js/app/packages/core/util/result.ts
@@ -0,0 +1,55 @@
+import { err, ok, type Result } from 'neverthrow';
+
+export interface Error {
+ description?: string;
+ fatal?: true;
+ arg?: string;
+}
+
+export interface ResultError<Code extends string = string> extends Error {
+ code: Code;
+ message: string;
+}
+
+export type ObjectLike = Record<string, any>;
+
+export type ResultType<T extends Result<any, any>> =
+ T extends Result<infer Value, any> ? Value : never;
+
+/** Error class that preserves result errors when thrown at query/UI boundaries. */
+export class ThrownResultError<E extends string = string> extends Error {
+ constructor(public readonly errors: ResultError<E>[]) {
+ super(errors.map((e) => e.message).join(', '));
+ this.name = 'ThrownResultError';
+ }
+}
+
+/** Wraps a result-returning async function to throw on error. */
+export async function throwOnErr<E extends string, T>(
+ fn: () => Promise<Result<T, ResultError<E>[]>>
+): Promise<T> {
+ const result = await fn();
+ if (result.isErr()) {
+ throw new ThrownResultError(result.error);
+ }
+ return result.value;
+}
+
+/** Wraps an async throwable function to return a result instead. */
+export async function catchToResult<T>(
+ throwable: () => Promise<T>
+): Promise<Result<T, ResultError<string>[]>> {
+ try {
+ return ok(await throwable());
+ } catch (error) {
+ if (error instanceof ThrownResultError) {
+ return err(error.errors);
+ }
+ return err([
+ {
+ code: 'UNKNOWN',
+ message: error instanceof Error ? error.message : String(error),
+ },
+ ]);
+ }
+}
diff --git a/js/app/packages/core/util/safeFetch.spec.ts b/js/app/packages/core/util/safeFetch.spec.ts
index 4d6fd16c1d..3a2b6ef648 100644
--- a/js/app/packages/core/util/safeFetch.spec.ts
+++ b/js/app/packages/core/util/safeFetch.spec.ts
@@ -3,7 +3,7 @@
*/
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import { isErr, isOk } from './maybeResult';
+
import { type BaseFetchErrorCode, safeFetch } from './safeFetch';
let originalFetch = global.fetch;
@@ -43,9 +43,9 @@ describe('safeFetch', () => {
const result = await safeFetch<{ data: string }>('https://localhost/data');
- expect(isOk(result)).toBe(true);
- if (isOk(result)) {
- const [, data] = result;
+ expect(result.isOk()).toBe(true);
+ if (result.isOk()) {
+ const data = result.value;
expect(data).toEqual({ data: 'test' });
}
});
@@ -57,9 +57,9 @@ describe('safeFetch', () => {
const result = await safeFetch<{ data: string }>('https://localhost/data');
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code }] = result.error;
expect(code).toBe('NETWORK_ERROR');
}
});
@@ -81,9 +81,9 @@ describe('safeFetch', () => {
retry: { maxTries: 2, delay: 0 },
});
- expect(isOk(result)).toBe(true);
- if (isOk(result)) {
- const [, data] = result;
+ expect(result.isOk()).toBe(true);
+ if (result.isOk()) {
+ const data = result.value;
expect(data).toEqual({ data: 'retry success' });
}
expect(mockFetch).toHaveBeenCalledTimes(2);
@@ -102,9 +102,9 @@ describe('safeFetch', () => {
const result = await safeFetch<{ data: string }>('https://localhost/data');
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code }] = result.error;
expect(code).toBe('INVALID_JSON');
}
});
@@ -122,9 +122,9 @@ describe('safeFetch', () => {
'https://localhost/data'
);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code }] = result.error;
expect(code).toBe('NOT_FOUND');
}
});
@@ -141,9 +141,9 @@ describe('safeFetch', () => {
'https://localhost/data'
);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code }] = result.error;
expect(code).toBe('UNAUTHORIZED');
}
});
@@ -160,9 +160,9 @@ describe('safeFetch', () => {
'https://localhost/data'
);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code }] = result.error;
expect(code).toBe('SERVER_ERROR');
}
});
@@ -179,9 +179,9 @@ describe('safeFetch', () => {
'https://localhost/data'
);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code }] = result.error;
expect(code).toBe('HTTP_ERROR');
}
});
@@ -218,9 +218,9 @@ describe('safeFetch', () => {
customErrorHandler
);
- expect(isErr(result)).toBe(true);
- if (isErr(result)) {
- const [[{ code, message }]] = result;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr()) {
+ const [{ code, message }] = result.error;
expect(code).toBe('RATE_LIMITED');
expect(message).toBe('Too many requests');
}
@@ -240,7 +240,7 @@ describe('safeFetch', () => {
}
);
- expect(isErr(result)).toBe(true);
+ expect(result.isErr()).toBe(true);
expect(mockFetch).toHaveBeenCalledTimes(3);
});
@@ -273,9 +273,9 @@ describe('safeFetch', () => {
}
);
- expect(isOk(result)).toBe(true);
- if (isOk(result)) {
- const [, data] = result;
+ expect(result.isOk()).toBe(true);
+ if (result.isOk()) {
+ const data = result.value;
expect(data).toEqual({ data: 'success after retries' });
}
expect(mockFetch).toHaveBeenCalledTimes(3);
diff --git a/js/app/packages/core/util/safeFetch.ts b/js/app/packages/core/util/safeFetch.ts
index 31981c59a2..477ee8ddd8 100644
--- a/js/app/packages/core/util/safeFetch.ts
+++ b/js/app/packages/core/util/safeFetch.ts
@@ -1,11 +1,6 @@
-import {
- err,
- type MaybeResult,
- type ObjectLike,
- ok,
- type ResultError,
-} from './maybeResult';
+import { err, ok, type Result } from 'neverthrow';
import { platformFetch } from './platformFetch';
+import type { ObjectLike, ResultError } from './result';
import { sleep } from './sleep';
/**
@@ -83,7 +78,7 @@ export type TextResponse = { contentType: 'text/plain'; body: string };
* @param {RequestInfo} input - The resource to fetch.
* @param {SafeFetchInit} [init] - Custom settings to apply to the request, including retry configuration.
* @param {ErrorResponseHandler<CustomErrorCode>} [errorResponseHandler] - Custom error response handler.
- * @returns {Promise<MaybeResult<BaseFetchErrorCode | CustomErrorCode, T>>} A promise that resolves to a MaybeResult.
+ * @returns {Promise<Result<T, ResultError<BaseFetchErrorCode | CustomErrorCode>[]>>} A promise that resolves to a Result.
*
* @example
* // Basic usage
@@ -92,12 +87,12 @@ export type TextResponse = { contentType: 'text/plain'; body: string };
* `https://localhost/users/${userId}`
* );
*
- * if (isErr(result)) {
- * console.error('Error fetching user:', result[0]);
+ * if ((result).isErr()) {
+ * console.error('Error fetching user:', result.error);
* return;
* }
*
- * const user = result[1];
+ * const user = result.value;
* console.log('User data:', user);
* }
*
@@ -116,8 +111,8 @@ export type TextResponse = { contentType: 'text/plain'; body: string };
* myErrorHandler
* );
*
- * if (isErr(result)) {
- * const [errors] = result;
+ * if ((result).isErr()) {
+ * const errors = result.error;
* switch (errors[0].code) {
* case 'RATE_LIMITED':
* console.error('Rate limit reached:', errors[0].message);
@@ -133,7 +128,7 @@ export type TextResponse = { contentType: 'text/plain'; body: string };
* return;
* }
*
- * const user = result[1];
+ * const user = result.value;
* console.log('User data:', user);
* }
*
@@ -148,12 +143,12 @@ export type TextResponse = { contentType: 'text/plain'; body: string };
* }
* );
*
- * if (isErr(result)) {
- * console.error('Error fetching user:', result[0]);
+ * if ((result).isErr()) {
+ * console.error('Error fetching user:', result.error);
* return;
* }
*
- * const user = result[1];
+ * const user = result.value;
* console.log('User data:', user);
* }
*/
@@ -164,11 +159,14 @@ export async function safeFetch<
input: RequestInfo,
init?: SafeFetchInit,
errorResponseHandler?: ErrorResponseHandler<CustomErrorCode>
-): Promise<MaybeResult<BaseFetchErrorCode | CustomErrorCode, T>> {
+): Promise<Result<T, ResultError<BaseFetchErrorCode | CustomErrorCode>[]>> {
const { retry, ...fetchInit } = init || {};
const maxTries = retry?.maxTries ?? 1;
const delay = retry?.delay ?? 0;
- let lastError;
+ type ErrorCode = BaseFetchErrorCode | CustomErrorCode;
+ const fetchErr = (errors: ResultError<ErrorCode>[]) =>
+ err<T, ResultError<ErrorCode>[]>(errors);
+ let lastError: Result<T, ResultError<ErrorCode>[]> | undefined;
for (let attempt = 1; attempt <= maxTries; attempt++) {
try {
@@ -190,25 +188,38 @@ export async function safeFetch<
if (!response.ok) {
if (errorResponseHandler) {
const customError = await errorResponseHandler(response);
- return [customError ? [customError] : [], null];
+ return fetchErr(customError ? [customError] : []);
}
switch (response.status) {
case 404:
- return err('NOT_FOUND', 'Resource not found');
+ return fetchErr([
+ { code: 'NOT_FOUND', message: 'Resource not found' },
+ ]);
case 401:
- return err('UNAUTHORIZED', 'Unauthorized access');
+ return fetchErr([
+ { code: 'UNAUTHORIZED', message: 'Unauthorized access' },
+ ]);
case 403:
- return err('FORBIDDEN', 'Forbidden');
+ return fetchErr([{ code: 'FORBIDDEN', message: 'Forbidden' }]);
case 409:
- return err('CONFLICT', 'Resource conflict');
+ return fetchErr([
+ { code: 'CONFLICT', message: 'Resource conflict' },
+ ]);
case 410:
- return err('GONE', 'Resource deleted');
+ return fetchErr([{ code: 'GONE', message: 'Resource deleted' }]);
case 500:
- lastError = err('SERVER_ERROR', 'Internal server error');
+ lastError = fetchErr([
+ { code: 'SERVER_ERROR', message: 'Internal server error' },
+ ]);
break;
default:
- return err('HTTP_ERROR', `HTTP error! status: ${response.status}`);
+ return fetchErr([
+ {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ },
+ ]);
}
} else {
if (fetchInit.method === 'HEAD') return ok({} as T);
@@ -226,11 +237,20 @@ export async function safeFetch<
}
} catch (error) {
if (error instanceof TypeError && error.message === 'Failed to fetch') {
- lastError = err('NETWORK_ERROR', 'Network error occurred');
+ lastError = fetchErr([
+ { code: 'NETWORK_ERROR', message: 'Network error occurred' },
+ ]);
} else if (error instanceof SyntaxError) {
- return err('INVALID_JSON', 'Invalid JSON in response');
+ return fetchErr([
+ { code: 'INVALID_JSON', message: 'Invalid JSON in response' },
+ ]);
} else {
- return err('UNKNOWN_ERROR', `An unknown error occurred: ${error}`);
+ return fetchErr([
+ {
+ code: 'UNKNOWN_ERROR',
+ message: `An unknown error occurred: ${error}`,
+ },
+ ]);
}
}
@@ -240,7 +260,13 @@ export async function safeFetch<
}
return (
- lastError ?? err('UNKNOWN_ERROR', 'Retry failed for an unknown reason')
+ lastError ??
+ fetchErr([
+ {
+ code: 'UNKNOWN_ERROR',
+ message: 'Retry failed for an unknown reason',
+ },
+ ])
);
}
function calculateDelay(
diff --git a/js/app/packages/macro-entity/src/queries/auth.ts b/js/app/packages/macro-entity/src/queries/auth.ts
index c2690a176f..c4c7f51d97 100644
--- a/js/app/packages/macro-entity/src/queries/auth.ts
+++ b/js/app/packages/macro-entity/src/queries/auth.ts
@@ -6,7 +6,7 @@ import {
} from '@tanstack/solid-query';
import { SERVER_HOSTS } from 'core/constant/servers';
import { fetchWithToken } from 'core/util/fetchWithToken';
-import { isOk } from 'core/util/maybeResult';
+
import { queryKeys } from './key';
const authHost = SERVER_HOSTS['auth-service'];
@@ -50,11 +50,11 @@ export const fetchApiToken = async () => {
`${authHost}/jwt/macro_api_token`
);
- if (!isOk(result)) {
- throw new Error('Failed to fetch API token', { cause: result[0] });
+ if (!result.isOk()) {
+ throw new Error('Failed to fetch API token', { cause: result.error });
}
- return result[1].macro_api_token;
+ return result.value.macro_api_token;
};
type ApiTokenQueryOptions = SolidQueryOptions<
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 63514f3e51..30ae29df71 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -4,7 +4,7 @@ import {
moveToFolder,
} from '@core/component/FileList/itemOperations';
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
import { scheduledActionKeys } from '@queries/agent-schedule/keys';
import { queryClient } from '@queries/client';
diff --git a/js/app/packages/macro-entity/src/queries/email.ts b/js/app/packages/macro-entity/src/queries/email.ts
index b2546ea207..46f3a4d9af 100644
--- a/js/app/packages/macro-entity/src/queries/email.ts
+++ b/js/app/packages/macro-entity/src/queries/email.ts
@@ -4,7 +4,7 @@ import { emailClient } from '@service-email/client';
import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';
import type { PreviewsInboxCursorParams } from '@service-email/generated/schemas/previewsInboxCursorParams';
import { useInfiniteQuery } from '@tanstack/solid-query';
-import { isErr } from 'core/util/maybeResult';
+
import { type Accessor, createMemo } from 'solid-js';
import { createApiTokenQuery, withApiTokenRetry } from './auth';
import { queryKeys } from './key';
@@ -34,11 +34,11 @@ const fetchPaginatedEmails = async ({
init
);
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to fetch email');
}
- return result[1];
+ return result.value;
};
export function createEmailsInfiniteQuery(
diff --git a/js/app/packages/notifications/queries/entities-notifications-query.ts b/js/app/packages/notifications/queries/entities-notifications-query.ts
index e14a7a7545..29341a3f8e 100644
--- a/js/app/packages/notifications/queries/entities-notifications-query.ts
+++ b/js/app/packages/notifications/queries/entities-notifications-query.ts
@@ -1,5 +1,5 @@
import type { Entity } from '@core/types';
-import { isErr } from '@core/util/maybeResult';
+
import { notificationServiceClient } from '@service-notification/client';
import type { ApiUserNotification } from '@service-notification/generated/schemas';
@@ -15,13 +15,13 @@ export const fetchNotificationsForEntities = async (
eventItemIds,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error(
'failed to fetch notifications for specific event item ids',
- result[0]
+ result.error
);
return [];
}
- return result[1].items;
+ return result.value.items;
};
diff --git a/js/app/packages/notifications/queries/muted-entities-query.ts b/js/app/packages/notifications/queries/muted-entities-query.ts
index 85ef2c8306..4f8c740b03 100644
--- a/js/app/packages/notifications/queries/muted-entities-query.ts
+++ b/js/app/packages/notifications/queries/muted-entities-query.ts
@@ -1,14 +1,13 @@
-import { isErr } from '@core/util/maybeResult';
import { notificationServiceClient } from '@service-notification/client';
import { useQuery } from '@tanstack/solid-query';
const fetchUnsubscriptions = async () => {
const response = await notificationServiceClient.getUnsubscribes();
- if (isErr(response))
+ if (response.isErr())
throw new Error('Failed to fetch unsubscribers', { cause: response });
- const result = response[1].data;
+ const result = response.value.data;
return result;
};
diff --git a/js/app/packages/queries/agent-schedule/schedules.ts b/js/app/packages/queries/agent-schedule/schedules.ts
index 0ff08112f4..169da7feb7 100644
--- a/js/app/packages/queries/agent-schedule/schedules.ts
+++ b/js/app/packages/queries/agent-schedule/schedules.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { scheduledActionClient } from '@service-scheduled-action/client';
diff --git a/js/app/packages/queries/ai/createAIObject.ts b/js/app/packages/queries/ai/createAIObject.ts
index f6315d61b8..6918401552 100644
--- a/js/app/packages/queries/ai/createAIObject.ts
+++ b/js/app/packages/queries/ai/createAIObject.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { dcsCompletion } from '@service-cognition/client';
import {
type SolidMutationOptions,
@@ -263,11 +262,11 @@ async function generateAIObject<Schema extends z.ZodType, Variables>(
},
});
- if (isErr(response)) {
- throw new Error(response[0].map((error) => error.message).join(', '));
+ if (response.isErr()) {
+ throw new Error(response.error.map((error) => error.message).join(', '));
}
- const content = response[1].choices[0]?.message?.content;
+ const content = response.value.choices[0]?.message?.content;
if (!content) {
throw new Error('AI object completion returned no content');
}
diff --git a/js/app/packages/queries/auth/mobile-welcome-email.ts b/js/app/packages/queries/auth/mobile-welcome-email.ts
index 05122e2585..e10ff1e902 100644
--- a/js/app/packages/queries/auth/mobile-welcome-email.ts
+++ b/js/app/packages/queries/auth/mobile-welcome-email.ts
@@ -3,7 +3,7 @@ import { useMutation } from '@tanstack/solid-query';
/**
* Mutation for sending a mobile welcome email.
- * Returns the raw `MaybeResult` from the client so callers can distinguish
+ * Returns the raw `Result` from the client so callers can distinguish
* between "sent" / "already sent" / rate-limited / invalid-email cases.
*/
export function useSendMobileWelcomeEmail() {
diff --git a/js/app/packages/queries/auth/mutations.ts b/js/app/packages/queries/auth/mutations.ts
index 7efd32aded..39f8857d89 100644
--- a/js/app/packages/queries/auth/mutations.ts
+++ b/js/app/packages/queries/auth/mutations.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import type { PatchUserOnboardingRequest } from '@service-auth/generated/schemas/patchUserOnboardingRequest';
import { useMutation } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/auth/tutorial.ts b/js/app/packages/queries/auth/tutorial.ts
index f2cb9fed43..9ded27d8f4 100644
--- a/js/app/packages/queries/auth/tutorial.ts
+++ b/js/app/packages/queries/auth/tutorial.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
diff --git a/js/app/packages/queries/auth/user-info.ts b/js/app/packages/queries/auth/user-info.ts
index d7099a3d75..67f53b6419 100644
--- a/js/app/packages/queries/auth/user-info.ts
+++ b/js/app/packages/queries/auth/user-info.ts
@@ -1,6 +1,6 @@
import { enableUserInfoQuery } from '@core/context/user-info-gate';
import { hasLoginCookie } from '@core/util/cookies';
-import { catchToResult, throwOnErr } from '@core/util/maybeResult';
+import { catchToResult, type ResultType, throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import { useQuery } from '@tanstack/solid-query';
import { queryClient } from '../client';
@@ -10,9 +10,9 @@ export { authKeys } from './keys';
const USER_INFO_STALE_TIME = 15_000; // 15 seconds
-export type UserInfoData = Awaited<
- ReturnType<typeof authServiceClient.getLegacyUserPermissions>
->[1];
+export type UserInfoData = ResultType<
+ Awaited<ReturnType<typeof authServiceClient.getLegacyUserPermissions>>
+>;
type UseUserInfoQueryOptions = {
/** Whether the query should be enabled. Can be a boolean or accessor for reactivity. */
diff --git a/js/app/packages/queries/auth/user-quota.ts b/js/app/packages/queries/auth/user-quota.ts
index 028ead7f4d..76618092ef 100644
--- a/js/app/packages/queries/auth/user-quota.ts
+++ b/js/app/packages/queries/auth/user-quota.ts
@@ -1,4 +1,3 @@
-import { isOk } from '@core/util/maybeResult';
import { authServiceClient } from '@service-auth/client';
import type { UserQuota } from '@service-auth/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
@@ -14,12 +13,12 @@ const USER_QUOTA_STALE_TIME = 1000 * 60 * 5; // 5 minutes
const getUserQuota = async (): Promise<UserQuota> => {
const result = await authServiceClient.userQuota();
- if (isOk(result)) {
- const [, quota] = result;
+ if (result.isOk()) {
+ const quota = result.value;
return quota;
}
- const [error] = result;
+ const error = result.error;
const [{ code, message }] = error;
console.error('Error getting user quota', error);
throw new Error(`Failed to get user quota: ${code} - ${message}`);
diff --git a/js/app/packages/queries/call/call.ts b/js/app/packages/queries/call/call.ts
index 8cc4834630..e8de04659b 100644
--- a/js/app/packages/queries/call/call.ts
+++ b/js/app/packages/queries/call/call.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { MaybeResultError, throwOnErr } from '@core/util/maybeResult';
+import { ThrownResultError, throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { callServiceClient } from '@service-call/client';
import { useMutation, useQuery } from '@tanstack/solid-query';
@@ -24,7 +24,7 @@ export function useJoinCallMutation() {
},
onError(error: Error) {
if (
- error instanceof MaybeResultError &&
+ error instanceof ThrownResultError &&
error.errors[0]?.code === 'CONFLICT'
) {
toast.alert("You're already in another call", {
diff --git a/js/app/packages/queries/channel/activity.ts b/js/app/packages/queries/channel/activity.ts
index e299112199..0157e98917 100644
--- a/js/app/packages/queries/channel/activity.ts
+++ b/js/app/packages/queries/channel/activity.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { commsServiceClient } from '@service-comms/client';
diff --git a/js/app/packages/queries/channel/channel-attachments.ts b/js/app/packages/queries/channel/channel-attachments.ts
index 89ff0b9834..97e3733369 100644
--- a/js/app/packages/queries/channel/channel-attachments.ts
+++ b/js/app/packages/queries/channel/channel-attachments.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import {
type ApiChannelAttachment,
type ChannelAttachmentsPage,
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index de23935c53..25541ba84c 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -1,4 +1,4 @@
-import { MaybeResultError, throwOnErr } from '@core/util/maybeResult';
+import { ThrownResultError, throwOnErr } from '@core/util/result';
import {
type ApiChannelMessage,
type ApiThreadReply,
@@ -58,7 +58,7 @@ type ChannelMessagesPageParam = {
export function isMissingChannelMessageError(error: unknown): boolean {
return (
- error instanceof MaybeResultError &&
+ error instanceof ThrownResultError &&
error.errors.some(({ code }) => code === 'NOT_FOUND' || code === 'GONE')
);
}
diff --git a/js/app/packages/queries/channel/channel-participants.ts b/js/app/packages/queries/channel/channel-participants.ts
index 7f83ccf5e1..8b86729164 100644
--- a/js/app/packages/queries/channel/channel-participants.ts
+++ b/js/app/packages/queries/channel/channel-participants.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import {
type ApiChannelParticipant,
commsServiceClient,
diff --git a/js/app/packages/queries/channel/channels.ts b/js/app/packages/queries/channel/channels.ts
index 8c116249f0..f8f5a7771f 100644
--- a/js/app/packages/queries/channel/channels.ts
+++ b/js/app/packages/queries/channel/channels.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { commsServiceClient } from '@service-comms/client';
import { useQuery } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/channel/get-or-create-dm.ts b/js/app/packages/queries/channel/get-or-create-dm.ts
index 13dec3f2e0..211458c3c4 100644
--- a/js/app/packages/queries/channel/get-or-create-dm.ts
+++ b/js/app/packages/queries/channel/get-or-create-dm.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { commsServiceClient } from '@service-comms/client';
import type { GetOrCreateDmResponse } from '@service-comms/generated/models';
diff --git a/js/app/packages/queries/channel/mentions.ts b/js/app/packages/queries/channel/mentions.ts
index 30a90e0fc3..737a1178f0 100644
--- a/js/app/packages/queries/channel/mentions.ts
+++ b/js/app/packages/queries/channel/mentions.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { commsServiceClient } from '@service-comms/client';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index d87293cb0f..669c8d986c 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -1,7 +1,7 @@
import { useAnalytics } from '@app/component/analytics-context';
import { toast } from '@core/component/Toast/Toast';
import type { DateValue } from '@core/util/date';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
type ApiChannelMessage,
diff --git a/js/app/packages/queries/channel/participants.ts b/js/app/packages/queries/channel/participants.ts
index ccf0d296eb..41aeee6860 100644
--- a/js/app/packages/queries/channel/participants.ts
+++ b/js/app/packages/queries/channel/participants.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
commsServiceClient,
diff --git a/js/app/packages/queries/channel/reaction.ts b/js/app/packages/queries/channel/reaction.ts
index d8f70161ae..ab9c3cbc48 100644
--- a/js/app/packages/queries/channel/reaction.ts
+++ b/js/app/packages/queries/channel/reaction.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
commsServiceClient,
diff --git a/js/app/packages/queries/channel/tests/channel-attachments.test.ts b/js/app/packages/queries/channel/tests/channel-attachments.test.ts
index 14d4593841..e9a58e15b3 100644
--- a/js/app/packages/queries/channel/tests/channel-attachments.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-attachments.test.ts
@@ -1,4 +1,5 @@
import { commsServiceClient } from '@service-comms/client';
+import { ok } from 'neverthrow';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
channelAttachmentsQueryOptions,
@@ -33,10 +34,9 @@ describe('channel attachment queries', () => {
it('passes attachment type, cursor, and abort signal to the service client', async () => {
const page = { items: [], next_cursor: null };
- vi.mocked(commsServiceClient.getChannelAttachments).mockResolvedValue([
- null,
- page,
- ]);
+ vi.mocked(commsServiceClient.getChannelAttachments).mockResolvedValue(
+ ok(page)
+ );
const signal = new AbortController().signal;
await expect(
diff --git a/js/app/packages/queries/channel/tests/channel-messages.test.ts b/js/app/packages/queries/channel/tests/channel-messages.test.ts
index 7c905e557f..e5424c554b 100644
--- a/js/app/packages/queries/channel/tests/channel-messages.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-messages.test.ts
@@ -1,8 +1,9 @@
+import { err as resultErr } from 'neverthrow';
/**
* @vitest-environment jsdom
*/
-import { MaybeResultError } from '@core/util/maybeResult';
+import { ThrownResultError } from '@core/util/result';
import { QueryClient } from '@tanstack/solid-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -43,10 +44,9 @@ describe('channelMessagesQueryOptions', () => {
'NOT_FOUND',
'GONE',
] as const)('throws missing load-around messages without retrying them for %s', async (code) => {
- mocks.getChannelMessages.mockResolvedValueOnce([
- [{ code, message: 'Message unavailable' }],
- null,
- ]);
+ mocks.getChannelMessages.mockResolvedValueOnce(
+ resultErr([{ code, message: 'Message unavailable' }])
+ );
const options = channelMessagesQueryOptions('channel-1', 'message-missing');
@@ -61,7 +61,7 @@ describe('channelMessagesQueryOptions', () => {
throw new Error('Expected queryFn to throw an Error');
}
- expect(error).toBeInstanceOf(MaybeResultError);
+ expect(error).toBeInstanceOf(ThrownResultError);
expect(isMissingChannelMessageError(error)).toBe(true);
expect(options.retry(0, error)).toBe(false);
expect(mocks.getChannelMessages).toHaveBeenCalledTimes(1);
diff --git a/js/app/packages/queries/channel/thread-replies.ts b/js/app/packages/queries/channel/thread-replies.ts
index 94b252dfe9..41d3e03b8d 100644
--- a/js/app/packages/queries/channel/thread-replies.ts
+++ b/js/app/packages/queries/channel/thread-replies.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { type ApiThreadReply, commsServiceClient } from '@service-comms/client';
import type { ApiCountedReaction } from '@service-storage/generated/schemas';
import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
diff --git a/js/app/packages/queries/chat.ts b/js/app/packages/queries/chat.ts
index fb8af135b3..912e7163ca 100644
--- a/js/app/packages/queries/chat.ts
+++ b/js/app/packages/queries/chat.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { useQuery } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/cognition/chat-data.ts b/js/app/packages/queries/cognition/chat-data.ts
index 1d3fc2f041..f38c360df4 100644
--- a/js/app/packages/queries/cognition/chat-data.ts
+++ b/js/app/packages/queries/cognition/chat-data.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { ChatResponse } from '@service-cognition/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
@@ -10,10 +9,10 @@ const GC_TIME = 10 * 60 * 1000;
async function fetchChatData(chatId: string): Promise<ChatResponse> {
const result = await cognitionApiServiceClient.getChat({ chat_id: chatId });
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to fetch chat');
}
- return result[1].chat;
+ return result.value.chat;
}
export function useChatDataQuery(chatId: Accessor<string>) {
diff --git a/js/app/packages/queries/contacts/contacts.ts b/js/app/packages/queries/contacts/contacts.ts
index fb0c6c83ea..dced84c171 100644
--- a/js/app/packages/queries/contacts/contacts.ts
+++ b/js/app/packages/queries/contacts/contacts.ts
@@ -1,6 +1,6 @@
import type { IUser } from '@core/user/types';
import { idToDisplayName, idToEmail } from '@core/user/util';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { contactsClient } from '@service-contacts/client';
import { useQuery } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/email/attachment.ts b/js/app/packages/queries/email/attachment.ts
index b81836f47d..fc3208ceb6 100644
--- a/js/app/packages/queries/email/attachment.ts
+++ b/js/app/packages/queries/email/attachment.ts
@@ -1,6 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import { contentHash } from '@core/util/hash';
-import { isErr, throwOnErr, toHybridError } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { emailClient } from '@service-email/client';
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
@@ -64,11 +64,14 @@ export const useUploadDraftAttachmentsMutation = (
type: result.content_type,
});
- if (isErr(uploadedResponse)) {
- const err = toHybridError(uploadedResponse);
+ if (uploadedResponse.isErr()) {
+ const uploadError = uploadedResponse.error[0] ?? {
+ code: 'SERVER_ERROR',
+ message: 'Upload failed',
+ };
throw new UploadDraftAttachmentError(
- err.message,
- { cause: err.code },
+ uploadError.message,
+ { cause: uploadError.code },
{
attachmentID: result.attachment_id,
file: attachment,
diff --git a/js/app/packages/queries/email/draft.ts b/js/app/packages/queries/email/draft.ts
index ffecbe2b28..2cc295eeff 100644
--- a/js/app/packages/queries/email/draft.ts
+++ b/js/app/packages/queries/email/draft.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { invalidateSoupEntity, refetchSoupEntity } from '@queries/soup/cache';
import { emailClient } from '@service-email/client';
import type {
diff --git a/js/app/packages/queries/email/label.ts b/js/app/packages/queries/email/label.ts
index 90ac96a487..62a5f73a50 100644
--- a/js/app/packages/queries/email/label.ts
+++ b/js/app/packages/queries/email/label.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { emailClient } from '@service-email/client';
import { useQuery } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/email/link.ts b/js/app/packages/queries/email/link.ts
index 5d8cad5dc1..6813dd88a7 100644
--- a/js/app/packages/queries/email/link.ts
+++ b/js/app/packages/queries/email/link.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { emailClient } from '@service-email/client';
import { useQuery } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index 04ca22ac25..fbd738721e 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -1,7 +1,7 @@
import { useAnalytics } from '@app/component/analytics-context';
import { toast } from '@core/component/Toast/Toast';
import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';
-import { catchToResult, isErr, ok, throwOnErr } from '@core/util/maybeResult';
+import { catchToResult, throwOnErr } from '@core/util/result';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
import { emailClient } from '@service-email/client';
import type {
@@ -17,6 +17,7 @@ import {
useInfiniteQuery,
useMutation,
} from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { optimisticUpdateSoupEntity } from '../soup/cache';
@@ -103,11 +104,11 @@ export async function fetchAndCacheThread(
await queryClient.fetchInfiniteQuery(threadQueryOptions(threadId))
);
- if (isErr(result)) {
- return result;
+ if (result.isErr()) {
+ return err(result.error as any);
}
- data = result[1];
+ data = result.value;
const thread = flattenThreadPages(data);
return ok({ thread: thread! });
@@ -382,7 +383,7 @@ export async function blockSenderWithToast(senderEmail: string) {
email_address: senderEmail,
});
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure('Failed to block sender', { subtext: senderEmail });
return;
}
@@ -397,7 +398,7 @@ export async function blockSenderWithToast(senderEmail: string) {
const undoResult = await emailClient.unblockSender({
email_address: senderEmail,
});
- if (isErr(undoResult)) {
+ if (undoResult.isErr()) {
toast.failure('Failed to unblock sender', { subtext: senderEmail });
} else {
toast.success('Sender unblocked');
@@ -419,14 +420,14 @@ async function upsertSenderFilterWithToast(
is_important: isImportant,
});
- if (isErr(result)) {
+ if (result.isErr()) {
toast.failure(`Failed to mark sender as ${label}`, {
subtext: senderEmail,
});
return;
}
- const filterId = result[1].filter.id;
+ const filterId = result.value.filter.id;
invalidateAllSoup();
toast.success(`Sender marked as ${label}`, {
@@ -439,7 +440,7 @@ async function upsertSenderFilterWithToast(
const undoResult = await emailClient.deleteEmailFilter({
id: filterId,
});
- if (isErr(undoResult)) {
+ if (undoResult.isErr()) {
toast.failure('Failed to undo', { subtext: senderEmail });
} else {
invalidateAllSoup();
diff --git a/js/app/packages/queries/entity/permissions.ts b/js/app/packages/queries/entity/permissions.ts
index 30264de448..aad8e22ad8 100644
--- a/js/app/packages/queries/entity/permissions.ts
+++ b/js/app/packages/queries/entity/permissions.ts
@@ -1,11 +1,8 @@
-import {
- catchToResult,
- type MaybeResult,
- throwOnErr,
-} from '@core/util/maybeResult';
+import { catchToResult, type ResultError, throwOnErr } from '@core/util/result';
import { dssFetch } from '@service-storage/client';
import type { EntityPermissionResponse } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
+import type { Result } from 'neverthrow';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { entityKeys } from './keys';
@@ -35,7 +32,7 @@ export function useEntityPermissions(
export async function fetchEntityPermissions(
entityType: string,
entityId: string
-): Promise<MaybeResult<string, EntityPermissionResponse>> {
+): Promise<Result<EntityPermissionResponse, ResultError<string>[]>> {
return await catchToResult(
async () =>
await queryClient.ensureQueryData(
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index aaadd91693..cbeca27b08 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -1,4 +1,4 @@
-import { catchToResult, isOk, throwOnErr } from '@core/util/maybeResult';
+import { catchToResult, throwOnErr } from '@core/util/result';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { storageServiceClient } from '@service-storage/client';
import type { CloudStorageItemType } from '@service-storage/generated/schemas/cloudStorageItemType';
@@ -174,7 +174,7 @@ export async function postNewHistoryItem(
await refetchHistory();
- return isOk(maybeAdded) && !!maybeAdded[1].success;
+ return maybeAdded.isOk() && !!maybeAdded.value.success;
}
/** Standalone function to remove an item from history. */
@@ -193,7 +193,7 @@ export async function removeHistoryItem(
await refetchHistory();
- return isOk(maybeRemoved) && !!maybeRemoved[1].success;
+ return maybeRemoved.isOk() && !!maybeRemoved.value.success;
}
/** Hook to get the updated raw name (no transform) of a HistoryItem */
@@ -242,9 +242,9 @@ export async function insertProjectIntoHistory(projectId: string) {
const projectContent = await storageServiceClient.projects.getContent({
id,
});
- if (isOk(projectContent)) {
+ if (projectContent.isOk()) {
ids.push(
- ...projectContent[1].data.reduce<string[]>((acc, { item }) => {
+ ...projectContent.value.data.reduce<string[]>((acc, { item }) => {
if (
item.type === 'project' &&
!prevData.some(({ id }) => id === item.id)
@@ -255,7 +255,9 @@ export async function insertProjectIntoHistory(projectId: string) {
}, [])
);
newData.push(
- ...projectContent[1].data.map(({ item }) => transformHistoryItem(item))
+ ...projectContent.value.data.map(({ item }) =>
+ transformHistoryItem(item)
+ )
);
}
}
diff --git a/js/app/packages/queries/mcp-servers.ts b/js/app/packages/queries/mcp-servers.ts
index b7878b5c75..8d2c309ca0 100644
--- a/js/app/packages/queries/mcp-servers.ts
+++ b/js/app/packages/queries/mcp-servers.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type {
diff --git a/js/app/packages/queries/notification/tests/user-notifications.test.tsx b/js/app/packages/queries/notification/tests/user-notifications.test.tsx
index cf2b12858a..478fa0e523 100644
--- a/js/app/packages/queries/notification/tests/user-notifications.test.tsx
+++ b/js/app/packages/queries/notification/tests/user-notifications.test.tsx
@@ -1,8 +1,8 @@
+import { err, ok } from 'neverthrow';
/**
* @vitest-environment jsdom
*/
-import { err, ok } from '@core/util/maybeResult';
import type { UnifiedNotification } from '@notifications/types';
import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';
import type { GetAllUserNotificationsResponse } from '@service-notification/generated/schemas/getAllUserNotificationsResponse';
@@ -186,7 +186,7 @@ describe('notification mutations', () => {
seedQueryCache([createMockNotificationPage([n1])]);
mockBulkMarkNotificationAsSeen.mockResolvedValue(
- err('SERVER_ERROR', 'Failed to mark as seen')
+ err([{ code: 'SERVER_ERROR', message: 'Failed to mark as seen' }])
);
let mutatePromise: Promise<unknown> | undefined;
@@ -275,7 +275,7 @@ describe('notification mutations', () => {
seedQueryCache([createMockNotificationPage([n1, n2])]);
mockBulkMarkNotificationAsDone.mockResolvedValue(
- err('NETWORK_ERROR', 'Connection failed')
+ err([{ code: 'NETWORK_ERROR', message: 'Connection failed' }])
);
let mutatePromise: Promise<unknown> | undefined;
diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.ts
index 3cd5739e4c..9d12cfb114 100644
--- a/js/app/packages/queries/notification/user-notifications.ts
+++ b/js/app/packages/queries/notification/user-notifications.ts
@@ -1,5 +1,5 @@
import type { Maybe } from '@core/types';
-import { type MaybeResult, throwOnErr } from '@core/util/maybeResult';
+import { type ResultError, throwOnErr } from '@core/util/result';
import type { UnifiedNotification } from '@notifications/types';
import {
optimisticUpdateSoupItemUpdatedAt,
@@ -15,6 +15,7 @@ import {
useInfiniteQuery,
useMutation,
} from '@tanstack/solid-query';
+import type { Result } from 'neverthrow';
import { match, P } from 'ts-pattern';
import { queryClient } from '../client';
import { notificationKeys } from './keys';
@@ -259,7 +260,7 @@ type NotificationsMutationCallbacks<T> = MutationCallbacks<
>;
type NotificationsMutationFn<T> = MutationFunction<
- MaybeResult<string, T>,
+ Result<T, ResultError<string>[]>,
NotificationsMutationParams
>;
diff --git a/js/app/packages/queries/preview/fetchers.ts b/js/app/packages/queries/preview/fetchers.ts
index 2908d76568..e0188cef8a 100644
--- a/js/app/packages/queries/preview/fetchers.ts
+++ b/js/app/packages/queries/preview/fetchers.ts
@@ -1,5 +1,5 @@
import { itemToSafeName } from '@core/constant/allBlocks';
-import { isErr } from '@core/util/maybeResult';
+
import { cognitionApiServiceClient } from '@service-cognition/client';
import { commsServiceClient } from '@service-comms/client';
import { emailClient } from '@service-email/client';
@@ -15,12 +15,12 @@ async function fetchChannelPreviews(
channel_ids: channelIds,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch channel previews');
return [];
}
- const [, data] = result;
+ const data = result.value;
return data.previews.map((channel) => {
const base = {
id: channel.channel_id,
@@ -55,11 +55,11 @@ export async function fetchMessageContext(
message_id: messageId,
});
- if (isErr(msgResult)) {
+ if (msgResult.isErr()) {
return null;
}
- const [, msgData] = msgResult;
+ const msgData = msgResult.value;
const message = msgData.messages[0];
if (!message) {
@@ -74,12 +74,12 @@ async function fetchDocumentPreviews(ids: string[]): Promise<PreviewItem[]> {
document_ids: ids,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch document previews');
return [];
}
- const [, data] = result;
+ const data = result.value;
return data.previews.map((doc) => {
const base = {
id: doc.document_id,
@@ -121,12 +121,12 @@ async function fetchCallPreviews(ids: string[]): Promise<PreviewItem[]> {
call_ids: ids,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch call previews');
return [];
}
- const [, data] = result;
+ const data = result.value;
return data.previews.map((call) => {
const base = {
id: call.callId,
@@ -163,12 +163,12 @@ async function fetchChatPreviews(ids: string[]): Promise<PreviewItem[]> {
chat_ids: ids,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch chat previews');
return [];
}
- const [, data] = result;
+ const data = result.value;
return data.previews.map((chat) => {
const base = {
id: chat.chat_id,
@@ -204,12 +204,12 @@ async function fetchProjectPreviews(
projectIds,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Failed to fetch projects previews');
return [];
}
- return result[1].previews.map((preview) => {
+ return result.value.previews.map((preview) => {
const { updatedAt, ...rest } = preview as Extract<
typeof preview,
{ updatedAt?: unknown }
@@ -238,7 +238,7 @@ async function fetchEmailPreviews(threadIds: string[]): Promise<PreviewItem[]> {
type: 'email',
} as const;
- if (isErr(result)) {
+ if (result.isErr()) {
return {
...base,
access: 'no_access' as const,
@@ -246,7 +246,7 @@ async function fetchEmailPreviews(threadIds: string[]): Promise<PreviewItem[]> {
};
}
- const [, data] = result;
+ const data = result.value;
const firstMessage = data.thread.messages[0];
const subject = firstMessage?.subject ?? 'No Subject';
const sender =
diff --git a/js/app/packages/queries/preview/wakeup.ts b/js/app/packages/queries/preview/wakeup.ts
index e23d219873..5d8e03a8e5 100644
--- a/js/app/packages/queries/preview/wakeup.ts
+++ b/js/app/packages/queries/preview/wakeup.ts
@@ -1,5 +1,5 @@
import type { ItemLike } from '@core/constant/allBlocks';
-import { isErr } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
import { AsyncBatcher } from '@tanstack/pacer';
import type { PreviewItem } from './types';
@@ -29,7 +29,7 @@ const documentWakeupBatcher = new AsyncBatcher<string>(
document_ids: uniqueDocumentIds,
});
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to bulk wakeup sync service documents');
}
},
diff --git a/js/app/packages/queries/properties/definitions.ts b/js/app/packages/queries/properties/definitions.ts
index b21145d428..74586c9190 100644
--- a/js/app/packages/queries/properties/definitions.ts
+++ b/js/app/packages/queries/properties/definitions.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 0815a9114c..1bd96cd923 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { useMutation, useQuery } from '@tanstack/solid-query';
import { type Accessor, batch } from 'solid-js';
import {
diff --git a/js/app/packages/queries/properties/options.ts b/js/app/packages/queries/properties/options.ts
index 8b2467b256..079eea4cd6 100644
--- a/js/app/packages/queries/properties/options.ts
+++ b/js/app/packages/queries/properties/options.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.ts
index 3e717ec3c6..f666930171 100644
--- a/js/app/packages/queries/soup/items.ts
+++ b/js/app/packages/queries/soup/items.ts
@@ -1,6 +1,6 @@
import { filterSoupItemByRequestBody } from '@app/component/next-soup/filters/query-filters';
import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
import {
parseGroupMeta,
diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.ts
index 701c08f221..ccd89fd72d 100644
--- a/js/app/packages/queries/soup/normalized-cache/operations.ts
+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts
@@ -1,5 +1,5 @@
import { QUERY_FILTERS_BASE } from '@app/component/next-soup/filters/query-filters';
-import { isErr } from '@core/util/maybeResult';
+
import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
import type {
PostSoupRequest,
@@ -239,7 +239,7 @@ export async function refetchSoupEntity(
body: filter,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error(
'[normalized-cache] operations: failed to fetch individual soup item',
result
@@ -247,7 +247,7 @@ export async function refetchSoupEntity(
return;
}
- const [, page] = result;
+ const page = result.value;
if (!page.items.length) return;
for (const item of page.items) {
diff --git a/js/app/packages/queries/soup/recently-viewed.ts b/js/app/packages/queries/soup/recently-viewed.ts
index d6b2651749..c58b16e7d7 100644
--- a/js/app/packages/queries/soup/recently-viewed.ts
+++ b/js/app/packages/queries/soup/recently-viewed.ts
@@ -1,4 +1,4 @@
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { storageServiceClient } from '@service-storage/client';
import { useQuery } from '@tanstack/solid-query';
import { queryClient } from '../client';
diff --git a/js/app/packages/queries/soup/search.ts b/js/app/packages/queries/soup/search.ts
index cb0073ef51..7c7ebb3253 100644
--- a/js/app/packages/queries/soup/search.ts
+++ b/js/app/packages/queries/soup/search.ts
@@ -1,6 +1,6 @@
import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import type { ChannelMessageEntity, EntityData, WithSearch } from '@entity';
import { soupKeys } from '@queries/soup/keys';
import {
diff --git a/js/app/packages/queries/storage/binary-document.ts b/js/app/packages/queries/storage/binary-document.ts
index 9f26ef9fa4..ee0f6d7d5b 100644
--- a/js/app/packages/queries/storage/binary-document.ts
+++ b/js/app/packages/queries/storage/binary-document.ts
@@ -1,13 +1,9 @@
import type { FetchError } from '@core/service';
-import {
- isErr,
- type MaybeResult,
- maybeThrow,
- ok,
-} from '@core/util/maybeResult';
+import { type ResultError, throwOnErr } from '@core/util/result';
import { storageServiceClient } from '@service-storage/client';
import type { GetDocumentResponseData } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
+import { err, ok, type Result } from 'neverthrow';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { waitForDocumentPresignedUrlReady } from './document-location';
@@ -21,13 +17,13 @@ type BinaryDocumentError = FetchError | 'INVALID_DOCUMENT';
export async function fetchBinaryDocumentData(
documentId: string
-): Promise<MaybeResult<BinaryDocumentError, BinaryDocumentData>> {
+): Promise<Result<BinaryDocumentData, ResultError<BinaryDocumentError>[]>> {
const maybeDocument = await storageServiceClient.getDocumentMetadata({
documentId,
});
- if (isErr(maybeDocument)) return maybeDocument;
+ if (maybeDocument.isErr()) return err(maybeDocument.error);
- const [, documentData] = maybeDocument;
+ const documentData = maybeDocument.value;
const versionId = documentData.documentMetadata.documentVersionId;
const location = await waitForDocumentPresignedUrlReady({
@@ -44,15 +40,12 @@ export async function fetchBinaryDocumentData(
location.type !== 'presignedUrl' ||
!location.presignedUrl
) {
- return [
- [
- {
- code: 'INVALID_DOCUMENT',
- message: 'Document location is not ready as a presigned URL',
- },
- ],
- null,
- ];
+ return err([
+ {
+ code: 'INVALID_DOCUMENT',
+ message: 'Document location is not ready as a presigned URL',
+ },
+ ]);
}
return ok({
@@ -62,8 +55,7 @@ export async function fetchBinaryDocumentData(
}
async function fetchBinaryDocument(documentId: string): Promise<string> {
- const result = await fetchBinaryDocumentData(documentId);
- const data = maybeThrow(result);
+ const data = await throwOnErr(() => fetchBinaryDocumentData(documentId));
return data.blobUrl;
}
diff --git a/js/app/packages/queries/storage/deleted.ts b/js/app/packages/queries/storage/deleted.ts
index 800813246d..07de1cfc40 100644
--- a/js/app/packages/queries/storage/deleted.ts
+++ b/js/app/packages/queries/storage/deleted.ts
@@ -1,6 +1,6 @@
import { buildFileTree } from '@core/component/FileList/buildFileTree';
import { itemToSafeName } from '@core/constant/allBlocks';
-import { isOk } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
import type { Item } from '@service-storage/generated/schemas/item';
import { useQuery } from '@tanstack/solid-query';
@@ -16,8 +16,8 @@ type DeletedItemsQueryResponse = {
async function fetchDeletedItems(): Promise<DeletedItemsQueryResponse> {
const result = await storageServiceClient.getDeletedItems();
- if (isOk(result)) {
- return result[1];
+ if (result.isOk()) {
+ return result.value;
}
return { items: [] };
}
diff --git a/js/app/packages/queries/storage/document-location.ts b/js/app/packages/queries/storage/document-location.ts
index 6b9bbee0c6..82a82020e1 100644
--- a/js/app/packages/queries/storage/document-location.ts
+++ b/js/app/packages/queries/storage/document-location.ts
@@ -1,11 +1,11 @@
import {
- isErr,
- type MaybeResult,
+ type ResultError,
type ResultType,
throwOnErr,
-} from '@core/util/maybeResult';
+} from '@core/util/result';
import { storageServiceClient } from '@service-storage/client';
import { DocumentContentState } from '@service-storage/generated/schemas/documentContentState';
+import { ok, type Result } from 'neverthrow';
import { queryClient } from '../client';
import { documentLocationKeys } from './keys';
@@ -186,10 +186,10 @@ export function waitForDocumentPresignedUrlReady(
});
}
-export function locationToMaybeResult(
+export function locationToAppResult(
location: DocumentLocation
-): MaybeResult<string, { data: DocumentLocation }> {
- return [null, { data: location }];
+): Result<{ data: DocumentLocation }, ResultError<string>[]> {
+ return ok({ data: location });
}
export function isDocumentLocationReady(location: DocumentLocation) {
@@ -197,7 +197,7 @@ export function isDocumentLocationReady(location: DocumentLocation) {
}
export function isDocumentLocationResultReady(
- result: MaybeResult<string, { data: DocumentLocation }>
+ result: Result<{ data: DocumentLocation }, ResultError<string>[]>
) {
- return !isErr(result) && isDocumentLocationReady(result[1].data);
+ return !result.isErr() && isDocumentLocationReady(result.value.data);
}
diff --git a/js/app/packages/queries/storage/document-metadata.ts b/js/app/packages/queries/storage/document-metadata.ts
index a2a303734f..a2dff6be30 100644
--- a/js/app/packages/queries/storage/document-metadata.ts
+++ b/js/app/packages/queries/storage/document-metadata.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
import type { DocumentMetadata } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
@@ -12,10 +11,10 @@ async function fetchDocumentMetadata(
documentId: string
): Promise<DocumentMetadata> {
const result = await storageServiceClient.getDocumentMetadata({ documentId });
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to fetch document metadata');
}
- return result[1].documentMetadata;
+ return result.value.documentMetadata;
}
export function useDocumentMetadataQuery(documentId: Accessor<string>) {
diff --git a/js/app/packages/queries/storage/instructions-md.ts b/js/app/packages/queries/storage/instructions-md.ts
index 8125596082..767545df9b 100644
--- a/js/app/packages/queries/storage/instructions-md.ts
+++ b/js/app/packages/queries/storage/instructions-md.ts
@@ -3,7 +3,7 @@ import {
getTextContent,
initializeEditorWithState,
} from '@core/component/LexicalMarkdown/utils';
-import { isOk } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
import { syncServiceClient } from '@service-sync/client';
import { useQuery } from '@tanstack/solid-query';
@@ -19,12 +19,12 @@ export { default as AiInstructionsIcon } from '@phosphor/notepad.svg';
const getInstructionsMdId = async (): Promise<string | null | undefined> => {
const getResult = await storageServiceClient.instructions.get();
- if (isOk(getResult)) {
- const [, { documentId }] = getResult;
+ if (getResult.isOk()) {
+ const { documentId } = getResult.value;
return documentId;
}
- const [error] = getResult;
+ const error = getResult.error;
const [{ code }] = error;
if (code === 'NOT_FOUND') {
return null;
@@ -100,8 +100,8 @@ export function useInstructionsMdTextQuery() {
export function useCreateInstructionsMd() {
return async () => {
const createResult = await storageServiceClient.instructions.create();
- if (isOk(createResult)) {
- const [, { documentId }] = createResult;
+ if (createResult.isOk()) {
+ const { documentId } = createResult.value;
queryClient.setQueryData(instructionsMdKeys.id.queryKey, documentId);
return documentId;
}
diff --git a/js/app/packages/queries/storage/project-data.ts b/js/app/packages/queries/storage/project-data.ts
index 28298f7468..698eb14468 100644
--- a/js/app/packages/queries/storage/project-data.ts
+++ b/js/app/packages/queries/storage/project-data.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
import type { Project } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
@@ -12,10 +11,10 @@ async function fetchProjectData(projectId: string): Promise<Project> {
const result = await storageServiceClient.projects.getProject({
id: projectId,
});
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error('Failed to fetch project');
}
- return result[1].projectMetadata;
+ return result.value.projectMetadata;
}
export function useProjectDataQuery(
diff --git a/js/app/packages/queries/storage/project-preview.ts b/js/app/packages/queries/storage/project-preview.ts
index b6793fb880..05da2d0cd1 100644
--- a/js/app/packages/queries/storage/project-preview.ts
+++ b/js/app/packages/queries/storage/project-preview.ts
@@ -1,12 +1,8 @@
-import {
- catchToResult,
- isErr,
- type MaybeResult,
- ok,
-} from '@core/util/maybeResult';
+import { catchToResult, type ResultError } from '@core/util/result';
import { storageServiceClient } from '@service-storage/client';
import type { ProjectPreviewData } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
+import { err, ok, type Result } from 'neverthrow';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { projectsKeys } from './keys';
@@ -24,11 +20,11 @@ async function fetchProjectPreview(
projectIds: [projectId],
});
- if (isErr(result)) {
+ if (result.isErr()) {
throw new Error(`Failed to fetch project preview`);
}
- const projectPreview = result[1].previews.find(
+ const projectPreview = result.value.previews.find(
(preview) => preview.id === projectId
);
@@ -73,16 +69,16 @@ export function useProjectPreviewQuery(projectId: Accessor<string>) {
*/
export async function fetchAndCacheProjectPreview(
projectId: string
-): Promise<MaybeResult<string, { project: ProjectPreviewData }>> {
+): Promise<Result<{ project: ProjectPreviewData }, ResultError<string>[]>> {
const result = await catchToResult(async () =>
queryClient.ensureQueryData(projectPreviewQueryOptions(projectId))
);
- if (isErr(result)) {
- return result;
+ if (result.isErr()) {
+ return err(result.error);
}
- return ok({ project: result[1] });
+ return ok({ project: result.value });
}
/**
diff --git a/js/app/packages/queries/storage/projects.ts b/js/app/packages/queries/storage/projects.ts
index f5e82f4c23..46cf82a99f 100644
--- a/js/app/packages/queries/storage/projects.ts
+++ b/js/app/packages/queries/storage/projects.ts
@@ -1,7 +1,7 @@
import { ENABLE_PROJECT_SHARING } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { compareDateDesc } from '@core/util/date';
-import { isOk } from '@core/util/maybeResult';
+
import {
refetchHistory,
useUpsertToHistoryMutation,
@@ -29,8 +29,8 @@ async function fetchProjects(): Promise<ProjectsQueryResponse> {
storageServiceClient.projects.getPending(),
]);
- const projects = isOk(projectsResult) ? projectsResult[1].data : [];
- const pending = isOk(pendingResult) ? pendingResult[1].data : [];
+ const projects = projectsResult.isOk() ? projectsResult.value.data : [];
+ const pending = pendingResult.isOk() ? pendingResult.value.data : [];
return { projects, pending };
}
@@ -92,14 +92,14 @@ export async function createProject(params: {
parentId?: string;
sharePermission?: null;
}): Promise<string | undefined> {
- const maybeResult = await storageServiceClient.projects.create({
+ const result = await storageServiceClient.projects.create({
name: params.name,
projectParentId: params.parentId,
sharePermission: params.sharePermission,
});
- if (isOk(maybeResult)) {
- const projectId = maybeResult[1].id;
+ if (result.isOk()) {
+ const projectId = result.value.id;
setPreviewOnCreate({
itemId: projectId,
itemType: 'project',
@@ -141,14 +141,14 @@ export function useCreateProjectMutation(
mutationFn: async (
params: CreateProjectParams
): Promise<string | undefined> => {
- const maybeResult = await storageServiceClient.projects.create({
+ const result = await storageServiceClient.projects.create({
name: params.name,
projectParentId: params.parentId,
sharePermission: params.sharePermission,
});
- if (isOk(maybeResult)) {
- return maybeResult[1].id;
+ if (result.isOk()) {
+ return result.value.id;
}
return undefined;
},
diff --git a/js/app/packages/queries/team/invitations.ts b/js/app/packages/queries/team/invitations.ts
index 39787682ed..d0d87d2b12 100644
--- a/js/app/packages/queries/team/invitations.ts
+++ b/js/app/packages/queries/team/invitations.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import type { TeamInvitesResponse } from '@service-auth/generated/schemas/teamInvitesResponse';
import { useMutation, useQuery } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/team/invites.ts b/js/app/packages/queries/team/invites.ts
index fff09bf01e..5446f3580d 100644
--- a/js/app/packages/queries/team/invites.ts
+++ b/js/app/packages/queries/team/invites.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import type { InviteToTeamRequest } from '@service-auth/generated/schemas/inviteToTeamRequest';
import type { TeamInvitesResponse } from '@service-auth/generated/schemas/teamInvitesResponse';
diff --git a/js/app/packages/queries/team/members.ts b/js/app/packages/queries/team/members.ts
index b739721702..3438889477 100644
--- a/js/app/packages/queries/team/members.ts
+++ b/js/app/packages/queries/team/members.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import type { TeamWithMembers } from '@service-auth/generated/schemas/teamWithMembers';
import { useMutation } from '@tanstack/solid-query';
diff --git a/js/app/packages/queries/team/teams.ts b/js/app/packages/queries/team/teams.ts
index 963daa930e..a3e4c170ad 100644
--- a/js/app/packages/queries/team/teams.ts
+++ b/js/app/packages/queries/team/teams.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { throwOnErr } from '@core/util/maybeResult';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import type { CreateTeamRequest } from '@service-auth/generated/schemas/createTeamRequest';
import type { PatchTeamRequest } from '@service-auth/generated/schemas/patchTeamRequest';
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index ae2b4011f2..073be73b8b 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -1,17 +1,12 @@
import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
-import {
- isOk,
- mapOk,
- type ObjectLike,
- ok,
- resultError,
-} from '@core/util/maybeResult';
import { registerClient } from '@core/util/mockClient';
+import type { ObjectLike } from '@core/util/result';
import { type SafeFetchInit, safeFetch } from '@core/util/safeFetch';
import { logger } from '@observability';
import { makePersisted } from '@solid-primitives/storage';
+import { ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import { fetchWithAuth as _fetchWithAuth } from './fetch';
import type {
@@ -106,14 +101,14 @@ export async function getAccessToken(): Promise<string | null> {
refreshToken,
});
- if (isOk(result)) {
+ if (result.isOk()) {
// After successful refresh, get the updated access token from storage
setAccessTokenData({
- accessToken: result[1].access_token,
- refreshToken: result[1].refresh_token,
- expiresAt: getExpiresAt(result[1].access_token),
+ accessToken: result.value.access_token,
+ refreshToken: result.value.refresh_token,
+ expiresAt: getExpiresAt(result.value.access_token),
});
- return result[1].access_token;
+ return result.value.access_token;
} else {
// Refresh failed
return null;
@@ -144,36 +139,34 @@ export type PatchSubscriptionTierErrorCode =
export const authServiceClient = {
async logout() {
setAccessTokenData(null);
- return mapOk(
- await authApiFetch<EmptyResponse>(`/logout`, { method: 'POST' }),
- (result) => result
- );
+ return (
+ await authApiFetch<EmptyResponse>(`/logout`, { method: 'POST' })
+ ).map((result) => result);
},
async getUserInfo() {
- return mapOk(
+ return (
await fetchWithAuth<Partial<GetUserInfo>>(`${authHost}/user/me`, {
method: 'GET',
- }),
- (data) => ({
- authenticated: !!data.user_id,
- permissions: data.permissions || [],
- userId: data.user_id,
- organizationId: data.organization_id ?? undefined,
})
- );
+ ).map((data) => ({
+ authenticated: !!data.user_id,
+ permissions: data.permissions || [],
+ userId: data.user_id,
+ organizationId: data.organization_id ?? undefined,
+ }));
},
async sessionLogin(args: { session_code: string }) {
- const maybeResult = await authApiFetch<UserTokensResponse>(
+ const result = await authApiFetch<UserTokensResponse>(
`/session/login/${args.session_code}`
);
- if (isOk(maybeResult)) {
+ if (result.isOk()) {
setAccessTokenData({
- accessToken: maybeResult[1].access_token,
- refreshToken: maybeResult[1].refresh_token,
- expiresAt: getExpiresAt(maybeResult[1].access_token),
+ accessToken: result.value.access_token,
+ refreshToken: result.value.refresh_token,
+ expiresAt: getExpiresAt(result.value.access_token),
});
}
- return maybeResult;
+ return result;
},
async deleteUser() {
setAccessTokenData(null);
@@ -194,22 +187,22 @@ export const authServiceClient = {
});
},
async passwordlessCallback({ code, email }: { code: string; email: string }) {
- const maybeResult = await safeFetch<UserTokensResponse>(
+ const result = await safeFetch<UserTokensResponse>(
`${authHost}/oauth/passwordless/${code}?email=${encodeURIComponent(email)}&disable_redirect=true`,
{ cache: 'no-store', credentials: 'include' },
async (response) => {
const message = await response.text();
- return resultError({ code: 'UNAUTHORIZED', message });
+ return { code: 'UNAUTHORIZED' as const, message };
}
);
- if (isOk(maybeResult)) {
+ if (result.isOk()) {
setAccessTokenData({
- accessToken: maybeResult[1].access_token,
- refreshToken: maybeResult[1].refresh_token,
- expiresAt: getExpiresAt(maybeResult[1].access_token),
+ accessToken: result.value.access_token,
+ refreshToken: result.value.refresh_token,
+ expiresAt: getExpiresAt(result.value.access_token),
});
}
- return maybeResult;
+ return result;
},
async refreshToken(args: { accessToken: string; refreshToken: string }) {
return authApiFetch<UserTokensResponse>('/jwt/refresh', {
@@ -224,7 +217,7 @@ export const authServiceClient = {
args: GetProfilePicturesRequestBody,
init?: SafeFetchInit
) {
- return mapOk(
+ return (
await fetchWithAuth<ProfilePictures>(
`${authHost}/user/profile_pictures`,
{
@@ -232,28 +225,25 @@ export const authServiceClient = {
method: 'POST',
body: JSON.stringify(args),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async putProfilePicture(args: PutProfilePictureParams) {
- return mapOk(
+ return (
await fetchWithAuth<ProfilePictures>(
`${authHost}/user/profile_picture?url=${args.url}`,
{
method: 'PUT',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getUserName() {
- return mapOk(
+ return (
await fetchWithAuth<UserName>(`${authHost}/user/name`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async putUserName(args: PutUserNameQueryParams) {
const queryParams: string[] = [];
@@ -266,30 +256,27 @@ export const authServiceClient = {
queryParams.push(`last_name=${encodeURIComponent(args.last_name)}`);
}
const queryString = queryParams.join('&');
- return mapOk(
+ return (
await fetchWithAuth<UserName>(`${authHost}/user/name?${queryString}`, {
method: 'PUT',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getUserNames(args: PostGetNamesRequestBody) {
- return mapOk(
+ return (
await fetchWithAuth<UserNames>(`${authHost}/user/get_names`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getUserNamesWithEmail(args: PostGetNamesRequestBody) {
- return mapOk(
+ return (
await fetchWithAuth<UserNames>(`${authHost}/user/get_names_with_email`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async checkLinkExists(args: { idp_name?: string; idp_id?: string }) {
const queryParams: string[] = [];
@@ -301,15 +288,14 @@ export const authServiceClient = {
queryParams.push(`idp_id=${args.idp_id}`);
}
const queryString = queryParams.join('&');
- return mapOk(
+ return (
await fetchWithAuth<UserLinkResponse>(
`${authHost}/user/link_exists?${queryString}`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async macroApiToken() {
const accessToken = await getAccessToken();
@@ -325,33 +311,30 @@ export const authServiceClient = {
});
},
async userQuota() {
- const result = await mapOk(
+ const result = await (
await fetchWithAuth<UserQuota>(`${authHost}/user/quota`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
return result;
},
async patchUserTutorial(args: PatchUserTutorialRequest) {
- return mapOk(
+ return (
await fetchWithAuth<EmptyResponse>(`${authHost}/user/tutorial`, {
method: 'PATCH',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async patchAiConsent(args: { aiDataConsent: boolean }) {
- return mapOk(
+ return (
await fetchWithAuth<EmptyResponse>(`${authHost}/user/ai_consent`, {
method: 'PATCH',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
// HTTP methods (migrated from RPC)
@@ -361,7 +344,7 @@ export const authServiceClient = {
{ method: 'GET' }
);
- return mapOk(result, (data) => ({
+ return result.map((data) => ({
id: data.userId,
permissions: data.permissions,
email: data.email,
@@ -385,7 +368,7 @@ export const authServiceClient = {
);
// If the response is an error, treat as no organization (204 No Content or other errors)
- if (!isOk(response)) {
+ if (!response.isOk()) {
return ok({
organizationId: undefined as string | undefined,
organizationName: undefined as string | undefined,
@@ -393,41 +376,38 @@ export const authServiceClient = {
}
return ok({
- organizationId: response[1].organizationId
- ? String(response[1].organizationId)
+ organizationId: response.value.organizationId
+ ? String(response.value.organizationId)
: undefined,
- organizationName: response[1].organizationName as string | undefined,
+ organizationName: response.value.organizationName as string | undefined,
});
},
async completeOnboarding(args: PatchUserOnboardingRequest) {
- return mapOk(
+ return (
await fetchWithAuth<EmptyResponse>(`${authHost}/user/onboarding`, {
method: 'PATCH',
body: JSON.stringify(args),
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async setGroup(args: PatchUserGroupRequest) {
- return mapOk(
+ return (
await fetchWithAuth<EmptyResponse>(`${authHost}/user/group`, {
method: 'PATCH',
body: JSON.stringify(args),
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async sendReferralInvite(recipient: string) {
- return mapOk(
+ return (
await fetchWithAuth<EmptyResponse>(`${authHost}/referral/send`, {
method: 'POST',
body: JSON.stringify({ recipient }),
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
// Stripe HTTP methods (replacing RPC calls)
@@ -442,7 +422,7 @@ export const authServiceClient = {
};
tier?: string;
}) {
- return mapOk(
+ return (
await fetchWithAuth<{ url: string }>(`${authHost}/user/stripe/checkout`, {
method: 'POST',
body: JSON.stringify({
@@ -452,21 +432,19 @@ export const authServiceClient = {
metadata: args.metadata,
tier: args.tier ?? undefined,
}),
- }),
- (result) => result.url
- );
+ })
+ ).map((result) => result.url);
},
async createPortalSession(args: { returnUrl: string }) {
- return mapOk(
+ return (
await fetchWithAuth<{ url: string }>(`${authHost}/user/stripe/portal`, {
method: 'POST',
body: JSON.stringify({
returnUrl: args.returnUrl,
}),
- }),
- (result) => result.url
- );
+ })
+ ).map((result) => result.url);
},
/**
@@ -536,12 +514,11 @@ export const authServiceClient = {
const url = originalUrl
? `${authHost}/link/github?original_url=${encodeURIComponent(originalUrl)}`
: `${authHost}/link/github`;
- return mapOk(
+ return (
await fetchWithAuth<InitGithubLinkResponse>(url, {
method: 'POST',
- }),
- (result) => result.authorization_url
- );
+ })
+ ).map((result) => result.authorization_url);
},
/**
@@ -549,12 +526,11 @@ export const authServiceClient = {
* NOTE: this does not delete the github application from being installed on a teams repository
*/
async deleteGithubLink() {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/link/github`, {
method: 'DELETE',
- }),
- (_result) => {}
- );
+ })
+ ).map((_result) => {});
},
async sendMobileWelcomeEmail(email: string) {
@@ -584,115 +560,103 @@ export const authServiceClient = {
},
async getUserTeams() {
- return mapOk(
- await fetchWithAuth<Team[]>(`${authHost}/team/user`, { method: 'GET' }),
- (result) => result
- );
+ return (
+ await fetchWithAuth<Team[]>(`${authHost}/team/user`, { method: 'GET' })
+ ).map((result) => result);
},
async getUserInvites() {
- return mapOk(
+ return (
await fetchWithAuth<TeamInvitesResponse>(
`${authHost}/team/user/invites`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getTeam() {
- return mapOk(
+ return (
await fetchWithAuth<TeamWithMembers>(`${authHost}/team`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getTeamInvites() {
- return mapOk(
+ return (
await fetchWithAuth<TeamInvitesResponse>(`${authHost}/team/invites`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async createTeam(args: CreateTeamRequest) {
- return mapOk(
+ return (
await fetchWithAuth<Team>(`${authHost}/team`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async joinTeam(teamInviteId: string) {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team/join/${teamInviteId}`, {
method: 'GET',
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async rejectInvitation(teamInviteId: string) {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team/join/${teamInviteId}`, {
method: 'DELETE',
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async patchTeam(args: PatchTeamRequest) {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team`, {
method: 'PATCH',
body: JSON.stringify(args),
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async inviteToTeam(args: InviteToTeamRequest) {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team/invite`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async deleteTeamInvite(teamInviteId: string) {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team/invite/${teamInviteId}`, {
method: 'DELETE',
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async removeUserFromTeam(userId: string) {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team/remove/${userId}`, {
method: 'DELETE',
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
async deleteTeam() {
- return mapOk(
+ return (
await fetchWithAuth<{}>(`${authHost}/team`, {
method: 'DELETE',
- }),
- () => undefined
- );
+ })
+ ).map(() => undefined);
},
};
diff --git a/js/app/packages/service-clients/service-auth/fetch.ts b/js/app/packages/service-clients/service-auth/fetch.ts
index ac10014d61..0d11e85cf7 100644
--- a/js/app/packages/service-clients/service-auth/fetch.ts
+++ b/js/app/packages/service-clients/service-auth/fetch.ts
@@ -1,12 +1,5 @@
import { LOCAL_ONLY } from '@core/constant/featureFlags';
-import {
- err,
- type HybridResultError,
- type ObjectLike,
- ok,
- type ResultError,
- toHybridError,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import {
type BaseFetchErrorCode,
type ErrorResponseHandler,
@@ -14,6 +7,7 @@ import {
safeFetch,
type TextResponse,
} from '@core/util/safeFetch';
+import { err, ok, type Result } from 'neverthrow';
import { authServiceClient } from './client';
function isExpired(token: string) {
@@ -40,13 +34,11 @@ export async function getMacroApiToken() {
}
macroApiTokenPromise = new Promise((resolve, reject) =>
- authServiceClient.macroApiToken().then(([err, result]) => {
- if (err) {
- reject(err);
- } else if (result) {
- resolve(result.macro_api_token);
+ authServiceClient.macroApiToken().then((result) => {
+ if (result.isErr()) {
+ reject(result.error);
} else {
- reject(new Error('No result from macroApiToken'));
+ resolve(result.value.macro_api_token);
}
})
);
@@ -74,24 +66,18 @@ type fetchWithAuthOptions<
) => Promise<ResultError<BaseFetchErrorCode | CustomErrorCode>>;
headers?: AcceptHeader<T>;
};
-type HybridMaybeResult<ErrorCode extends string, T> =
- | [null, T]
- | [HybridResultError<ErrorCode>, null];
-
export async function fetchWithAuth<
T extends ObjectLike | TextContentType = {},
CustomErrorCode extends string = never,
>(
input: RequestInfo,
init?: fetchWithAuthOptions<T, CustomErrorCode>
-): Promise<HybridMaybeResult<BaseFetchErrorCode | CustomErrorCode, T>> {
+): Promise<Result<T, ResultError<BaseFetchErrorCode | CustomErrorCode>[]>> {
const apiToken = await getMacroApiToken();
if (!apiToken) {
- const [noTokenError] = err(
- 'UNAUTHORIZED',
- 'No access and/or refresh token found'
- );
- return [toHybridError(noTokenError), null];
+ return err([
+ { code: 'UNAUTHORIZED', message: 'No access and/or refresh token found' },
+ ]);
}
const safeFetchInit = {
@@ -144,16 +130,15 @@ export async function fetchWithAuth<
};
// TODO: move safeFetch code to here
- const [errors, result] = await safeFetch<SafeFetchT<T>, CustomErrorCode>(
+ const result = await safeFetch<SafeFetchT<T>, CustomErrorCode>(
input,
safeFetchInit,
safeFetchErrorHandler
);
- // TODO: Refactor when backward compatibility is no longer needed
- if (!!errors && errors.length > 0) {
- return [toHybridError(errors), null];
+ if (result.isErr()) {
+ return err(result.error);
}
- return ok(result as T);
+ return ok(result.value as T);
}
diff --git a/js/app/packages/service-clients/service-call/client.ts b/js/app/packages/service-clients/service-call/client.ts
index d771fb71f4..e9a148a08e 100644
--- a/js/app/packages/service-clients/service-call/client.ts
+++ b/js/app/packages/service-clients/service-call/client.ts
@@ -1,6 +1,6 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
-import { mapOk } from '@core/util/maybeResult';
+
import type { CallActiveResponse } from '@service-storage/generated/schemas/callActiveResponse';
import type { CallRecord } from '@service-storage/generated/schemas/callRecord';
import type { CallTokenResponse } from '@service-storage/generated/schemas/callTokenResponse';
@@ -17,51 +17,48 @@ const host: string = SERVER_HOSTS['document-storage-service'];
export const callServiceClient = {
async getOrCreateCall(channelId: string) {
- return mapOk(
+ return (
await fetchWithToken<CallTokenResponse>(`${host}/call/${channelId}`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async leaveCall(channelId: string) {
- return mapOk(
+ return (
await fetchWithToken<LeaveCallResponse>(`${host}/call/${channelId}`, {
method: 'DELETE',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async checkActiveCall(channelId: string) {
- return mapOk(
+ return (
await fetchWithToken<CallActiveResponse>(
`${host}/call/${channelId}/active`,
{ method: 'GET' }
- ),
+ )
+ ).map(
// safeFetch returns {} for 204 (no Content-Type header)
(data) => ('callId' in data ? (data as CallActiveResponse) : null)
);
},
async getCallRecord(callId: string) {
- return mapOk(
+ return (
await fetchWithToken<CallRecord>(`${host}/call/record/${callId}`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteCallRecord(callId: string) {
- return mapOk(
+ return (
await fetchWithToken<Record<string, never>>(
`${host}/call/record/${callId}`,
{ method: 'DELETE' }
- ),
- () => undefined
- );
+ )
+ ).map(() => undefined);
},
async toggleShareWithTeam(callId: string) {
@@ -72,19 +69,18 @@ export const callServiceClient = {
`${host}/call/record/${callId}/share-with-team/toggle`,
{ method: 'POST' }
);
- return mapOk(result, (r) => r as unknown as boolean);
+ return result.map((r) => r as unknown as boolean);
},
async editCallRecord(params: { callId: string; customName: string }) {
- return mapOk(
+ return (
await fetchWithToken<Record<string, never>>(
`${host}/call/record/${params.callId}`,
{
method: 'PATCH',
body: JSON.stringify({ customName: params.customName }),
}
- ),
- () => undefined
- );
+ )
+ ).map(() => undefined);
},
};
diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.ts
index 2cbafc0ddf..92f7f3e006 100644
--- a/js/app/packages/service-clients/service-cognition/client.ts
+++ b/js/app/packages/service-clients/service-cognition/client.ts
@@ -5,18 +5,11 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- err,
- isErr,
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
- ok,
-} from '@core/util/maybeResult';
import { platformFetch } from '@core/util/platformFetch';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { DocumentTextPart } from '@service-cognition/generated/schemas/documentTextPart';
+import { err, ok, type Result } from 'neverthrow';
import type OpenAI from 'openai';
import type { AddServerRequest } from './generated/schemas/addServerRequest';
import type { CreateChatRequest } from './generated/schemas/createChatRequest';
@@ -53,17 +46,17 @@ type WithProjectId = { project_id: string };
export function dcsFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function dcsFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function dcsFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${dcsHost}${url}`, init);
}
export type Success = { success: boolean };
@@ -74,35 +67,32 @@ export const cognitionApiServiceClient = {
/** Creates a mapping from source_id to target_id */
async createIdMapping(args: { source_id: string; target_id: string }) {
const { source_id, target_id } = args;
- return mapOk(
+ return (
await dcsFetch<{ success: boolean }>(`/id_mapping/${source_id}`, {
method: 'POST',
body: JSON.stringify({ target_id }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
/** Gets the target_id for a given source_id */
async getIdMapping(args: { source_id: string }) {
const { source_id } = args;
- return mapOk(
+ return (
await dcsFetch<IdMappingResponse>(`/id_mapping/${source_id}`, {
method: 'GET',
- }),
- (result) => result.target_id
- );
+ })
+ ).map((result) => result.target_id);
},
getChat: cache(
async function getChat(args: WithChatId) {
const { chat_id } = args;
- return mapOk(
+ return (
await dcsFetch<GetChatResponse>(`/chats/${chat_id}`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
{
seconds: 5,
@@ -111,15 +101,14 @@ export const cognitionApiServiceClient = {
async editChatProject(args: WithChatId & WithProjectId) {
const { chat_id, project_id } = args;
- return mapOk(
+ return (
await dcsFetch<{ success: boolean }>(`/chats/${chat_id}`, {
method: 'PATCH',
body: JSON.stringify({
projectId: project_id,
}),
- }),
- () => ({ success: true })
- );
+ })
+ ).map(() => ({ success: true }));
},
async updateChatPermissions(args: PatchChatRequest & WithChatId) {
@@ -133,43 +122,40 @@ export const cognitionApiServiceClient = {
},
async renameChat(args: WithChatId & { new_name: string }) {
const { chat_id, new_name } = args;
- return mapOk(
+ return (
await dcsFetch<{ success: boolean }>(`/chats/${chat_id}`, {
method: 'PATCH',
body: JSON.stringify({
name: new_name,
}),
- }),
- () => ({ success: true })
- );
+ })
+ ).map(() => ({ success: true }));
},
async copyChat(args: WithChatId & WithName) {
const { chat_id, name } = args;
- return mapOk(
+ return (
await dcsFetch<StringIDResponse>(`/chats/${chat_id}/copy`, {
method: 'POST',
body: JSON.stringify({
name,
}),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async createChat(args: CreateChatRequest) {
- return mapOk(
+ return (
await dcsFetch<StringIDResponse>(`/chats`, {
method: 'POST',
body: JSON.stringify({
name: args.name,
projectId: args.projectId,
}),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteChat(args: WithChatId) {
const { chat_id } = args;
- const maybeResult = await dcsFetch(`/chats/${chat_id}`, {
+ const result = await dcsFetch(`/chats/${chat_id}`, {
method: 'DELETE',
});
@@ -178,18 +164,21 @@ export const cognitionApiServiceClient = {
// delete chat returns a 200 with an empty body on success
// which return INVALID_JSON error on response.json()
// so we return no error instead to signal success
- if (isErr(maybeResult, 'INVALID_JSON')) maybeResult;
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'INVALID_JSON')
+ )
+ result;
- return maybeResult;
+ return result;
},
async getChatPermissions(args: { id: string }) {
const { id } = args;
- return mapOk(
+ return (
await dcsFetch<GetChatPermissionsResponse>(`/chats/${id}/permissions`, {
method: 'GET',
- }),
- (result) => result.permissions
- );
+ })
+ ).map((result) => result.permissions);
},
async permanentlyDeleteChat(args: WithChatId) {
const { chat_id } = args;
@@ -202,30 +191,27 @@ export const cognitionApiServiceClient = {
},
async revertDeleteChat(args: WithChatId) {
const { chat_id } = args;
- return mapOk(
+ return (
await dcsFetch<Success>(`/chats/${chat_id}/revert_delete`, {
method: 'PUT',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getChatsForAttachment(args: { attachment_id: string }) {
const { attachment_id } = args;
- return mapOk(
+ return (
await dcsFetch<GetChatsForAttachmentResponse>(
`/attachments/${attachment_id}/chats`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
getCitation: cache(
async function getCitation(args) {
- return mapOk(
- await dcsFetch<DocumentTextPart>(`/citations/${args.id}`),
+ return (await dcsFetch<DocumentTextPart>(`/citations/${args.id}`)).map(
(result) => result
);
},
@@ -234,13 +220,12 @@ export const cognitionApiServiceClient = {
}
),
async getBatchChatPreviews(args: GetBatchPreviewRequest) {
- return mapOk(
+ return (
await dcsFetch<GetBatchPreviewResponse>(`/preview`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
/** Update a tool call's arguments (validates against tool schema server-side). */
async updateToolCall<T extends keyof ToolCallArgs>(args: {
@@ -283,7 +268,7 @@ export const cognitionApiServiceClient = {
toolCallId: string;
args?: ToolCallArgs[T];
}) {
- return mapOk(
+ return (
await dcsFetch<{ result: unknown }>(`/chats/${args.chat_id}/tool/call`, {
method: 'POST',
body: JSON.stringify({
@@ -291,9 +276,8 @@ export const cognitionApiServiceClient = {
toolCallId: args.toolCallId,
args: args.args,
}),
- }),
- (result) => result.result
- );
+ })
+ ).map((result) => result.result);
},
/** Reject a pending tool call. */
@@ -313,52 +297,47 @@ export const cognitionApiServiceClient = {
/** Send a chat message via HTTP stream API. Response chunks arrive via connection_gateway. */
async sendStreamChatMessage(args: HttpSendChatMessageRequest) {
- return mapOk(
+ return (
await dcsFetch<SendChatMessageResponse>(`/stream/chat/message`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
/** Stops an in-flight AI chat stream. The streaming task persists whatever
* the user has already seen and emits StreamEnd. */
async stopChatStream(args: StopChatStreamRequest) {
- return mapOk(
+ return (
await dcsFetch<StopChatStreamResponse>(`/stream/chat/message/stop`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async listMcpServers() {
- return mapOk(
- await dcsFetch<ServerResponse[]>(`/mcp/servers`, { method: 'GET' }),
- (result) => result
- );
+ return (
+ await dcsFetch<ServerResponse[]>(`/mcp/servers`, { method: 'GET' })
+ ).map((result) => result);
},
async addMcpServer(args: AddServerRequest) {
- return mapOk(
+ return (
await dcsFetch<ServerResponse>(`/mcp/servers`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async updateMcpServer(args: UpdateServerRequest) {
- return mapOk(
+ return (
await dcsFetch<ServerResponse>(`/mcp/servers`, {
method: 'PUT',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteMcpServer(args: { url: string }) {
@@ -368,13 +347,12 @@ export const cognitionApiServiceClient = {
},
async startMcpAuth(args: StartAuthRequest) {
- return mapOk(
+ return (
await dcsFetch<StartAuthResponse>(`/mcp/servers/auth/start`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
};
@@ -390,12 +368,12 @@ export async function generateTitle(text: string): Promise<string | undefined> {
max_tokens: 100,
});
- if (isErr(result)) {
+ if (result.isErr()) {
console.error('Error generating title');
return undefined;
}
- return result[1].choices[0]?.message?.content?.trim() || undefined;
+ return result.value.choices[0]?.message?.content?.trim() || undefined;
}
type DcsCompletionErrorCode = 'NETWORK_ERROR' | 'OPENAI_ERROR';
@@ -403,9 +381,9 @@ type DcsCompletionErrorCode = 'NETWORK_ERROR' | 'OPENAI_ERROR';
export async function dcsCompletion(
body: Omit<OpenAI.ChatCompletionCreateParamsNonStreaming, 'stream'>
): Promise<
- MaybeResult<
- FetchWithTokenErrorCode | DcsCompletionErrorCode,
- OpenAI.ChatCompletion
+ Result<
+ OpenAI.ChatCompletion,
+ ResultError<FetchWithTokenErrorCode | DcsCompletionErrorCode>[]
>
> {
let response: Response;
@@ -417,7 +395,9 @@ export async function dcsCompletion(
body: JSON.stringify({ ...body, stream: false }),
});
} catch {
- return err('NETWORK_ERROR', 'Failed to reach completions proxy');
+ return err([
+ { code: 'NETWORK_ERROR', message: 'Failed to reach completions proxy' },
+ ]);
}
const data = await response.json();
@@ -426,7 +406,7 @@ export async function dcsCompletion(
const message =
data?.error?.message ??
`Completion failed with status ${response.status}`;
- return err('OPENAI_ERROR', message);
+ return err([{ code: 'OPENAI_ERROR', message: message }]);
}
return ok(data as OpenAI.ChatCompletion);
}
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
index a1d348a15c..94aec019bf 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
@@ -2,7 +2,8 @@
* *DO NOT EDIT MANUALLY*
*/
-import { err, type MaybeResult, ok } from 'core/util/maybeResult';
+import type { ResultError } from 'core/util/result';
+import { err, ok, type Result } from 'neverthrow';
import * as schemas from './schemas';
import type * as types from './types';
@@ -284,9 +285,11 @@ export type NamedTool<
function deserializeTool<T extends NamedTool>(
tool: NamedRawTool,
direction: 'call' | 'response'
-): MaybeResult<'parse_error' | 'not_found', T> {
+): Result<T, ResultError<'parse_error' | 'not_found'>[]> {
if (!(tool.name in toolParserMap)) {
- return err('not_found', `tool name not found ${tool.name}`);
+ return err([
+ { code: 'not_found', message: `tool name not found ${tool.name}` },
+ ]);
}
const parser = toolParserMap[tool.name as ToolName];
const maybeToolCall = parser[direction].safeParse(tool.json);
@@ -297,17 +300,23 @@ function deserializeTool<T extends NamedTool>(
data: maybeToolCall.data,
} as T);
}
- return err('parse_error', 'tool parsing failed');
+ return err([{ code: 'parse_error', message: 'tool parsing failed' }]);
}
export function deserializeToolCall(
tool: NamedRawTool
-): MaybeResult<'parse_error' | 'not_found', NamedTool<ToolName, 'call'>> {
+): Result<
+ NamedTool<ToolName, 'call'>,
+ ResultError<'parse_error' | 'not_found'>[]
+> {
return deserializeTool(tool, 'call');
}
export function deserializeToolResponse(
tool: NamedRawTool
-): MaybeResult<'parse_error' | 'not_found', NamedTool<ToolName, 'response'>> {
+): Result<
+ NamedTool<ToolName, 'response'>,
+ ResultError<'parse_error' | 'not_found'>[]
+> {
return deserializeTool(tool, 'response');
}
diff --git a/js/app/packages/service-clients/service-comms/client.ts b/js/app/packages/service-clients/service-comms/client.ts
index 87cdd5e17f..a0a3128484 100644
--- a/js/app/packages/service-clients/service-comms/client.ts
+++ b/js/app/packages/service-clients/service-comms/client.ts
@@ -3,18 +3,14 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { ApiThreadReply } from '@service-storage/generated/schemas';
import type { ApiChannelAttachmentsPage } from '@service-storage/generated/schemas/apiChannelAttachmentsPage';
import type { ApiChannelMessagesPage } from '@service-storage/generated/schemas/apiChannelMessagesPage';
import type { ApiChannelParticipant } from '@service-storage/generated/schemas/apiChannelParticipant';
import type { ChannelMessageFilters } from '@service-storage/generated/schemas/channelMessageFilters';
+import type { Result } from 'neverthrow';
import type {
ApiActivity,
ApiChannelWithLatest,
@@ -57,17 +53,17 @@ const commsHost: string = SERVER_HOSTS['document-storage-service'];
export function commsFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function commsFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function commsFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${commsHost}${url}`, init);
}
@@ -92,20 +88,18 @@ export const ChannelTypeEnum = {
export const commsServiceClient = {
async getChannel(args: WithChannelId) {
const { channel_id } = args;
- return mapOk(
+ return (
await commsFetch<GetChannelResponse>(`/comms/channels/${channel_id}`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getChannels() {
- return mapOk(
+ return (
await commsFetch<ApiChannelWithLatest[]>(`/comms/channels`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getMessageWithContext(args: GetMessageWithContextParams) {
const { message_id, before, after } = args;
@@ -123,55 +117,51 @@ export const commsServiceClient = {
const { channel_id, message, nonce } = args;
const uniqueMentions = Array.from(new Set(message.mentions));
const sendMessage = { ...message, mentions: uniqueMentions, nonce };
- return mapOk(
+ return (
await commsFetch<IdResponse & { nonce?: string }>(
`/comms/channels/${channel_id}/message`,
{
method: 'POST',
body: JSON.stringify(sendMessage),
}
- ),
- (result) => result ?? {}
- );
+ )
+ ).map((result) => result ?? {});
},
async createChannel(args: CreateChannelRequest) {
- return mapOk(
+ return (
await commsFetch<CreateChannelResponse>(`/comms/channels`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async postTypingUpdate(
args: PostTypingRequest & WithChannelId & { nonce?: string }
) {
const { channel_id, action, thread_id, nonce } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(
`/comms/channels/${channel_id}/typing`,
{
method: 'POST',
body: JSON.stringify({ action, thread_id, nonce }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async postReaction(
args: PostReactionRequest & WithChannelId & { nonce?: string }
) {
const { channel_id, action, emoji, message_id, nonce } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(
`/comms/channels/${channel_id}/reaction`,
{
method: 'POST',
body: JSON.stringify({ action, emoji, message_id, nonce }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async patchMessage(
args: PatchMessageRequest &
@@ -186,7 +176,7 @@ export const commsServiceClient = {
attachments_to_add,
nonce,
} = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(
`/comms/channels/${channel_id}/message/${message_id}`,
{
@@ -198,9 +188,8 @@ export const commsServiceClient = {
nonce,
}),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async deleteMessage(
args: WithChannelId & WithMessageId & { nonce?: string }
@@ -209,146 +198,133 @@ export const commsServiceClient = {
const url = nonce
? `/comms/channels/${channel_id}/message/${message_id}?nonce=${encodeURIComponent(nonce)}`
: `/comms/channels/${channel_id}/message/${message_id}`;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(url, {
method: 'DELETE',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async postActivity(args: PostActivityRequest) {
const { activity_type, channel_id } = args;
- return mapOk(
+ return (
await commsFetch<Activity>(`/comms/activity`, {
method: 'POST',
body: JSON.stringify({ activity_type, channel_id }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getActivity() {
- return mapOk(
+ return (
await commsFetch<ApiActivity[]>(`/comms/activity`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async joinChannel(args: WithChannelId) {
const { channel_id } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(`/comms/channels/${channel_id}/join`, {
method: 'POST',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async leaveChannel(args: WithChannelId) {
const { channel_id } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(`/comms/channels/${channel_id}/leave`, {
method: 'POST',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getBatchChannelPreviews(args: GetBatchChannelPreviewRequest) {
const { channel_ids } = args;
- return mapOk(
+ return (
await commsFetch<GetBatchChannelPreviewResponse>(`/comms/preview`, {
body: JSON.stringify({ channel_ids }),
method: 'POST',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async addParticipantsToChanenl(args: AddParticipantsRequest & WithChannelId) {
const { channel_id, participants } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(
`/comms/channels/${channel_id}/participants`,
{
method: 'POST',
body: JSON.stringify({ participants }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getOrCreateDirectMessage(args: GetOrCreateDmRequest) {
const { recipient_id } = args;
- return mapOk(
+ return (
await commsFetch<GetOrCreateDmResponse>(
`/comms/channels/get_or_create_dm`,
{
method: 'POST',
body: JSON.stringify({ recipient_id }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getOrCreatePrivateChannel(args: GetOrCreatePrivateRequest) {
const { recipients } = args;
- return mapOk(
+ return (
await commsFetch<GetOrCreatePrivateResponse>(
`/comms/channels/get_or_create_private`,
{
method: 'POST',
body: JSON.stringify({ recipients }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async removeParticipantsFromChannel(
args: RemoveParticipantsRequest & WithChannelId
) {
const { channel_id, participants } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(
`/comms/channels/${channel_id}/participants`,
{
method: 'DELETE',
body: JSON.stringify({ participants }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async deleteChannel(args: WithChannelId) {
const { channel_id } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(`/comms/channels/${channel_id}`, {
method: 'DELETE',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async patchChannel(args: WithChannelId & { channel_name: string }) {
const { channel_id, channel_name } = args;
- return mapOk(
+ return (
await commsFetch<MessageResponse>(`/comms/channels/${channel_id}`, {
method: 'PATCH',
body: JSON.stringify({ channel_name }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async attachmentReferences(args: WithEntity) {
const { entity_type, entity_id } = args;
- return mapOk(
+ return (
await commsFetch<GetAttachmentReferencesResponse>(
`/comms/attachments/${entity_type}/${entity_id}/references`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async createEntityMention(args: CreateEntityMentionRequest, token?: string) {
- return mapOk(
+ return (
await commsFetch<CreateEntityMentionResponse>('/comms/mentions', {
method: 'POST',
body: JSON.stringify(args),
@@ -357,32 +333,29 @@ export const commsServiceClient = {
'x-permissions-token': `${token}`,
}
: undefined,
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteEntityMention(args: WithMentionId, token?: string) {
- return mapOk(
+ return (
await commsFetch<DeleteEntityMentionResponse>(
`/comms/mentions/${args.mention_id}`,
{
method: 'DELETE',
headers: token ? { 'x-permissions-token': `${token}` } : undefined,
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getMentions(args: WithChannelId) {
- return mapOk(
+ return (
await commsFetch<GetMentionsResponse>(
`/comms/channels/${args.channel_id}/mentions`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getChannelMessages(
args: WithChannelId & {
@@ -408,13 +381,12 @@ export const commsServiceClient = {
} else if (previous_cursor) {
params.append('previous_cursor', previous_cursor);
}
- return mapOk(
+ return (
await commsFetch<ApiChannelMessagesPage>(
`/channels/${channel_id}/messages?${params.toString()}`,
{ method: 'GET' }
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async postChannelMessages(
args: WithChannelId & { filters: ChannelMessageFilters; limit?: number }
@@ -423,16 +395,15 @@ export const commsServiceClient = {
const params = new URLSearchParams();
if (limit !== undefined) params.append('limit', limit.toString());
const query = params.toString();
- return mapOk(
+ return (
await commsFetch<ApiChannelMessagesPage>(
`/channels/${channel_id}/messages${query ? `?${query}` : ''}`,
{
method: 'POST',
body: JSON.stringify(filters),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getChannelAttachments(
args: WithChannelId & {
@@ -447,32 +418,29 @@ export const commsServiceClient = {
params.append('limit', limit.toString());
if (cursor) params.append('cursor', cursor);
if (attachment_type) params.append('attachment_type', attachment_type);
- return mapOk(
+ return (
await commsFetch<ApiChannelAttachmentsPage>(
`/channels/${channel_id}/attachments?${params.toString()}`,
{ method: 'GET', signal }
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getThreadReplies(args: WithChannelId & WithMessageId) {
const { channel_id, message_id } = args;
- return mapOk(
+ return (
await commsFetch<Array<ApiThreadReply>>(
`/channels/${channel_id}/messages/${message_id}/replies`,
{ method: 'GET' }
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getChannelParticipants(args: WithChannelId) {
const { channel_id } = args;
- return mapOk(
+ return (
await commsFetch<ApiChannelParticipant[]>(
`/channels/${channel_id}/participants`,
{ method: 'GET' }
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
};
diff --git a/js/app/packages/service-clients/service-connection/client.ts b/js/app/packages/service-clients/service-connection/client.ts
index 7a964c318e..78a54fa951 100644
--- a/js/app/packages/service-clients/service-connection/client.ts
+++ b/js/app/packages/service-clients/service-connection/client.ts
@@ -1,5 +1,6 @@
import type { EntityId } from '@core/types';
-import { ok } from '@core/util/maybeResult';
+import { ok } from 'neverthrow';
+
import type { TrackEntityMessage } from './generated/schemas/trackEntityMessage';
import { clearStream } from './stream';
import { ws } from './websocket';
diff --git a/js/app/packages/service-clients/service-contacts/client.ts b/js/app/packages/service-clients/service-contacts/client.ts
index fd56cd4c92..b1be0ecabe 100644
--- a/js/app/packages/service-clients/service-contacts/client.ts
+++ b/js/app/packages/service-clients/service-contacts/client.ts
@@ -3,14 +3,9 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
-
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import type { Result } from 'neverthrow';
const contactsHost = `${SERVER_HOSTS['contacts']}`;
@@ -19,28 +14,27 @@ import type { GetContactsResponse } from './generated/schemas/getContactsRespons
export function contactsFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function contactsFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function contactsFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${contactsHost}${url}`, init);
}
export const contactsClient = {
async getContacts() {
- return mapOk(
+ return (
await contactsFetch<GetContactsResponse>(`/contacts`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async addContact(userId: string) {
return contactsFetch(`/contacts`, {
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index d21c30ebd4..7fc1df7b2d 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -3,13 +3,9 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import type { Result } from 'neverthrow';
import type {
AddDraftAttachmentRequest,
AddDraftAttachmentResponse,
@@ -41,28 +37,27 @@ const emailHost: string = SERVER_HOSTS['email-service'];
export function emailFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function emailFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function emailFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${emailHost}${url}`, init);
}
export const emailClient = {
async init() {
- return mapOk(
+ return (
await emailFetch<EmptyResponse>('/email/init', {
method: 'POST',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getThread(args: {
offset?: number;
@@ -70,23 +65,21 @@ export const emailClient = {
thread_id: string;
}) {
const { offset, limit, thread_id } = args;
- return mapOk(
+ return (
await emailFetch<GetThreadResponse>(
`/email/threads/${thread_id}?offset=${offset ?? 0}&limit=${limit ?? 5}`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getUserLabels() {
- return mapOk(
+ return (
await emailFetch<ListLabelsResponse>(`/email/labels`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getPreviews(
args: {
@@ -104,41 +97,38 @@ export const emailClient = {
.join('&');
const qp = p.length > 0 ? '?' + p : '';
- return mapOk(
+ return (
await emailFetch<ApiPaginatedThreadCursor>(
`/email/threads/previews/cursor/${view}${qp}`,
{
method: 'GET',
...init,
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async updateMessageLabelBatch(args: UpdateLabelBatchRequest) {
const { message_ids, label_id, value } = args;
- return mapOk(
+ return (
await emailFetch<UpdateLabelBatchResponse>(`/email/messages/labels`, {
method: 'PATCH',
body: JSON.stringify({ value, label_id, message_ids }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async updateThreadLabel(
args: { thread_id: string } & UpdateThreadLabelRequest
) {
const { thread_id, label_id, value } = args;
- return mapOk(
+ return (
await emailFetch<UpdateThreadLabelsResponse>(
`/email/threads/${thread_id}/labels`,
{
method: 'PATCH',
body: JSON.stringify({ label_id, value }),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async updateThreadProject(args: {
thread_id: string;
@@ -155,154 +145,140 @@ export const emailClient = {
},
async flagArchived(args: { value: boolean; id: string }) {
const { value, id } = args;
- return mapOk(
+ return (
await emailFetch<EmptyResponse>(`/email/threads/${id}/archived`, {
method: 'PATCH',
body: JSON.stringify({ value }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async startSync() {
- return mapOk(
+ return (
await emailFetch<EmptyResponse>('/email/sync', {
method: 'POST',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async stopSync() {
- return mapOk(
+ return (
await emailFetch<EmptyResponse>('/email/sync', {
method: 'DELETE',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async sendMessage(args: SendMessageRequest) {
- return mapOk(
+ return (
await emailFetch<SendMessageResponse>('/email/messages', {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async scheduleMessage(args: { draftID: string } & UpsertScheduledRequest) {
const { draftID, ...rest } = args;
- return mapOk(
+ return (
await emailFetch<UpsertScheduledResponse>(
`/email/drafts/scheduled/${draftID}`,
{
method: 'PUT',
body: JSON.stringify(rest),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async unscheduleMessage(args: { draftID: string }) {
- return mapOk(
+ return (
await emailFetch<EmptyResponse>(
`/email/drafts/scheduled/${args.draftID}`,
{
method: 'DELETE',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async getLinks() {
- return mapOk(
+ return (
await emailFetch<ListLinksResponse>('/email/links', {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async listContacts() {
- return mapOk(
+ return (
await emailFetch<ListContactsResponse>('/email/contacts', {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getAttachmentUrl(args: { id: string }) {
const { id } = args;
- return mapOk(
+ return (
await emailFetch<GetAttachmentResponse>(`/email/attachments/${id}`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getOrCreateAttachmentDocumentId(args: { id: string }) {
const { id } = args;
- return mapOk(
+ return (
await emailFetch<GetAttachmentDocumentIDResponse>(
`/email/attachments/${id}/document_id`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async createDraft(args: CreateDraftRequest) {
- return mapOk(
+ return (
await emailFetch<CreateDraftResponse>('/email/drafts', {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteDraft(args: { id: string }) {
const { id } = args;
- return mapOk(
+ return (
await emailFetch<EmptyResponse>(`/email/drafts/${id}`, {
method: 'DELETE',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async addDraftAttachment(args: {
draftID: string;
attachment: AddDraftAttachmentRequest;
}) {
- return mapOk(
+ return (
await emailFetch<AddDraftAttachmentResponse>(
`/email/drafts/${args.draftID}/attachments`,
{
method: 'POST',
body: JSON.stringify(args.attachment),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async removeDraftAttachment(args: { draftID: string; attachmentID: string }) {
- return mapOk(
+ return (
await emailFetch<EmptyResponse>(
`/email/drafts/${args.draftID}/attachments/${args.attachmentID}`,
{
method: 'DELETE',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async addForwardedAttachment(args: {
draftID: string;
attachmentID: string;
}) {
- return mapOk(
+ return (
await emailFetch<{
attachment_id: string;
filename: string | null;
@@ -311,32 +287,29 @@ export const emailClient = {
}>(`/email/drafts/${args.draftID}/forwarded-attachments`, {
method: 'POST',
body: JSON.stringify({ attachment_id: args.attachmentID }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async removeForwardedAttachment(args: {
draftID: string;
attachmentID: string;
}) {
- return mapOk(
+ return (
await emailFetch<EmptyResponse>(
`/email/drafts/${args.draftID}/forwarded-attachments/${args.attachmentID}`,
{
method: 'DELETE',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async markThreadAsSeen(args: { thread_id: string }) {
const { thread_id } = args;
- return mapOk(
+ return (
await emailFetch<EmptyResponse>(`/email/threads/${thread_id}/seen`, {
method: 'POST',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async blockSender(args: { email_address: string }) {
return emailFetch('/email/contacts/block', {
@@ -351,21 +324,19 @@ export const emailClient = {
});
},
async listEmailFilters() {
- return mapOk(
+ return (
await emailFetch<ListEmailFiltersResponse>('/email/filters', {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async upsertEmailFilter(args: UpsertEmailFilterRequest) {
- return mapOk(
+ return (
await emailFetch<UpsertEmailFilterResponse>('/email/filters', {
method: 'PUT',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteEmailFilter(args: { id: string }) {
return emailFetch(`/email/filters/${args.id}`, {
diff --git a/js/app/packages/service-clients/service-notification/client.ts b/js/app/packages/service-clients/service-notification/client.ts
index 2cf64b8ac3..2443b17598 100644
--- a/js/app/packages/service-clients/service-notification/client.ts
+++ b/js/app/packages/service-clients/service-notification/client.ts
@@ -3,13 +3,9 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import type { Result } from 'neverthrow';
import { z } from 'zod';
import type {
BulkGetByEventItemIdsRequest,
@@ -43,17 +39,17 @@ export type UnifiedNotification = Omit<ApiUserNotification, 'ownerId'> & {
export function notificationFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function notificationFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function notificationFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${notificationHost}${url}`, init);
}
export type Success = { success: boolean };
@@ -94,32 +90,30 @@ type NotificationParams = { cursor?: string; limit?: number };
export const notificationServiceClient = {
async userNotifications(args: NotificationParams) {
const { limit, cursor } = args;
- return mapOk(
+ return (
await notificationFetch<GetAllUserNotificationsResponse>(
`/user_notifications?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}`,
{
method: 'GET',
}
- ),
- (result) => {
- return result;
- }
- );
+ )
+ ).map((result) => {
+ return result;
+ });
},
async getUserNotificationById(notificationId: string) {
- return mapOk(
+ return (
await notificationFetch<ApiUserNotification>(
`/user_notifications/${notificationId}`,
{ method: 'GET' }
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async bulkGetUserNotificationsByEventItemId(
args: NotificationParams & BulkGetByEventItemIdsRequest
) {
const { limit, cursor } = args;
- return mapOk(
+ return (
await notificationFetch<GetAllUserNotificationsResponse>(
`/user_notifications/item/bulk?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}`,
{
@@ -127,85 +121,77 @@ export const notificationServiceClient = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ eventItemIds: args.eventItemIds }),
}
- ),
- (result) => {
- return result;
- }
- );
+ )
+ ).map((result) => {
+ return result;
+ });
},
async markNotificationAsSeen(args: NotificationBulkRequest) {
const { notificationIds } = args;
- return mapOk(
+ return (
await notificationFetch<any>(`/user_notifications/bulk/seen`, {
method: 'PATCH',
body: JSON.stringify({ notificationIds }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async markNotificationAsDone(args: NotificationBulkRequest) {
const { notificationIds } = args;
- return mapOk(
+ return (
await notificationFetch<any>(`/user_notifications/bulk/done`, {
method: 'PATCH',
body: JSON.stringify({ notificationIds }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async bulkMarkNotificationAsSeen(args: NotificationBulkRequest) {
const { notificationIds } = args;
- return mapOk(
+ return (
await notificationFetch<any>(`/user_notifications/bulk/seen`, {
method: 'PATCH',
body: JSON.stringify({ notificationIds }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async bulkMarkNotificationAsDone(args: NotificationBulkRequest) {
const { notificationIds } = args;
- return mapOk(
+ return (
await notificationFetch<any>(`/user_notifications/bulk/done`, {
method: 'PATCH',
body: JSON.stringify({ notificationIds }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async bulkMarkNotificationAsUndone(args: NotificationBulkRequest) {
const { notificationIds } = args;
- return mapOk(
+ return (
await notificationFetch<any>(`/user_notifications/bulk/undone`, {
method: 'PATCH',
body: JSON.stringify({ notificationIds }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async markNotificationEntityAsSeen(args: WithEventItemId) {
const { event_item_id } = args;
- return mapOk(
+ return (
await notificationFetch<{}>(
`/user_notifications/item/${event_item_id}/seen`,
{
method: 'PATCH',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async markNotificationEntityAsDone(args: WithEventItemId) {
const { event_item_id } = args;
- return mapOk(
+ return (
await notificationFetch<{}>(
`/user_notifications/item/${event_item_id}/done`,
{
method: 'PATCH',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async registerDevice(args: DeviceRequest) {
return notificationFetch<{}>('/device/register', {
@@ -220,12 +206,11 @@ export const notificationServiceClient = {
});
},
async getUnsubscribes() {
- return mapOk(
+ return (
await notificationFetch<UserUnsubscribe[]>('/unsubscribe', {
method: 'GET',
- }),
- (result) => ({ data: result })
- );
+ })
+ ).map((result) => ({ data: result }));
},
async unsubscribeItem(args: WithItem) {
return notificationFetch<{}>(
diff --git a/js/app/packages/service-clients/service-properties/client.ts b/js/app/packages/service-clients/service-properties/client.ts
index 7714523306..1dfbfd3cec 100644
--- a/js/app/packages/service-clients/service-properties/client.ts
+++ b/js/app/packages/service-clients/service-properties/client.ts
@@ -3,14 +3,10 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
import { registerClient } from '@core/util/mockClient';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import type { Result } from 'neverthrow';
import type { AddPropertyOptionRequest } from './generated/schemas/addPropertyOptionRequest';
import type { BulkEntityPropertiesRequest } from './generated/schemas/bulkEntityPropertiesRequest';
import type { CreatePropertyDefinitionRequest } from './generated/schemas/createPropertyDefinitionRequest';
@@ -71,17 +67,17 @@ const propertiesHost: string = SERVER_HOSTS['document-storage-service'];
export function propertiesFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function propertiesFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function propertiesFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${propertiesHost}${url}`, init);
}
@@ -122,7 +118,7 @@ export const propertiesServiceClient = {
}
);
- return mapOk(result, () => ({ success: true }));
+ return result.map(() => ({ success: true }));
},
getEntityProperties: async (args: GetEntityPropertiesArgs) => {
@@ -148,7 +144,7 @@ export const propertiesServiceClient = {
body: JSON.stringify(args.body),
});
- return mapOk(result, () => ({ success: true }));
+ return result.map(() => ({ success: true }));
},
deleteEntityProperty: async (args: DeleteEntityPropertyArgs) => {
@@ -159,7 +155,7 @@ export const propertiesServiceClient = {
}
);
- return mapOk(result, () => ({ success: true }));
+ return result.map(() => ({ success: true }));
},
getPropertyOptions: async (args: GetPropertyOptionsArgs) => {
@@ -189,7 +185,7 @@ export const propertiesServiceClient = {
}
);
- return mapOk(result, () => ({ success: true }));
+ return result.map(() => ({ success: true }));
},
setPropertyStatusComplete: async (args: SetPropertyStatusCompleteArgs) => {
@@ -197,7 +193,7 @@ export const propertiesServiceClient = {
const result = await propertiesFetch<{}>(url, {
method: 'PATCH',
});
- return mapOk(result, () => ({ success: true }));
+ return result.map(() => ({ success: true }));
},
getBulkEntityProperties: async (args: GetBulkEntityPropertiesArgs) => {
diff --git a/js/app/packages/service-clients/service-scheduled-action/client.ts b/js/app/packages/service-clients/service-scheduled-action/client.ts
index e7d870e080..cb53e2fb84 100644
--- a/js/app/packages/service-clients/service-scheduled-action/client.ts
+++ b/js/app/packages/service-clients/service-scheduled-action/client.ts
@@ -3,13 +3,9 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import type { Result } from 'neverthrow';
import type {
ActionExecutionRecord,
CreateScheduledAction,
@@ -23,17 +19,17 @@ const scheduledActionHost: string = SERVER_HOSTS['scheduled-action'];
export function scheduledActionFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function scheduledActionFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function scheduledActionFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${scheduledActionHost}${url}`, init);
}
@@ -66,7 +62,7 @@ export const scheduledActionClient = {
`/scheduled-actions/${args.scheduleId}`,
{ method: 'DELETE' }
);
- return mapOk(result, () => ({ success: true }));
+ return result.map(() => ({ success: true }));
},
runNow: async (args: { scheduleId: string }) =>
diff --git a/js/app/packages/service-clients/service-search/client.ts b/js/app/packages/service-clients/service-search/client.ts
index 461afd77ca..b0fa7c9c86 100644
--- a/js/app/packages/service-clients/service-search/client.ts
+++ b/js/app/packages/service-clients/service-search/client.ts
@@ -3,14 +3,9 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
-
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import type { Result } from 'neverthrow';
const searchServiceHost = `${SERVER_HOSTS['document-storage-service']}`;
@@ -24,17 +19,17 @@ export type { ChannelSearchRequest, ChannelSearchResponse };
export function searchServiceFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function searchServiceFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function searchServiceFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${searchServiceHost}${url}`, init);
}
@@ -68,25 +63,23 @@ const buildSearchQuery = (params: SearchParams) => {
export const searchClient = {
async search(args: SearchArgs, init?: SafeFetchInit) {
const url = `/search${buildSearchQuery(args.params)}`;
- return mapOk(
+ return (
await searchServiceFetch<UnifiedSearchResponse>(url, {
method: 'POST',
body: JSON.stringify(args.request),
...init,
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async searchChannel(args: ChannelSearchArgs, init?: SafeFetchInit) {
const url = `/search/channel${buildSearchQuery(args.params)}`;
- return mapOk(
+ return (
await searchServiceFetch<ChannelSearchResponse>(url, {
method: 'POST',
body: JSON.stringify(args.request),
...init,
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
};
diff --git a/js/app/packages/service-clients/service-static-files/client.ts b/js/app/packages/service-clients/service-static-files/client.ts
index e34d93e9e9..d70366b7d3 100644
--- a/js/app/packages/service-clients/service-static-files/client.ts
+++ b/js/app/packages/service-clients/service-static-files/client.ts
@@ -3,14 +3,10 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- type MaybeError,
- type MaybeResult,
- mapOk,
- type ObjectLike,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import { platformFetch } from 'core/util/platformFetch';
+import type { Result } from 'neverthrow';
import type { FileMetadata } from './generated/schemas/fileMetadata';
import type { PutFileRequest } from './generated/schemas/putFileRequest';
import type { PutFileResponse } from './generated/schemas/putFileResponse';
@@ -20,17 +16,17 @@ const staticFileHost = `${SERVER_HOSTS['static-file']}`;
export function staticFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function staticFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function staticFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${staticFileHost}${url}`, init);
}
@@ -38,21 +34,19 @@ type WithFileId = { file_id: string };
export const staticFileClient = {
async makePresignedUrl(args: PutFileRequest) {
- return mapOk(
+ return (
await staticFetch<PutFileResponse>('/api/file', {
method: 'PUT',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getMetadata(args: WithFileId) {
- return mapOk(
+ return (
await staticFetch<FileMetadata>(`/api/file/metadata/${args.file_id}`, {
method: 'GET',
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async deleteFile(args: WithFileId) {
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index 79baa0a912..97e70c1764 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -19,19 +19,13 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- err,
- isErr,
- isOk,
- type MaybeError,
- type MaybeResult,
- mapOk,
- ok,
-} from '@core/util/maybeResult';
import { registerClient } from '@core/util/mockClient';
+import type { ResultError } from '@core/util/result';
+
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
import { platformFetch } from 'core/util/platformFetch';
+import { err, ok, type Result } from 'neverthrow';
import type {
AccessLevel,
CallRecordPreview,
@@ -111,17 +105,17 @@ const dssHost = SERVER_HOSTS['document-storage-service'];
export function dssFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function dssFetch<T extends Record<string, any>>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function dssFetch<T extends Record<string, any> = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${dssHost}${url}`, init);
}
@@ -223,20 +217,18 @@ const { showPaywall } = usePaywallState();
export const storageServiceClient = {
async ping() {
- return mapOk(
- await dssFetch<SuccessResponse>(`/ping`),
+ return (await dssFetch<SuccessResponse>(`/ping`)).map(
(result) => result.data
);
},
async bulkWakeupSyncServiceDocuments(args: { document_ids: string[] }) {
- return mapOk(
+ return (
await dssFetch<{ dispatched: number }>(`/sync_service/wakeup`, {
method: 'POST',
body: JSON.stringify({ document_ids: args.document_ids }),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async getSoupItems(args: {
@@ -324,123 +316,113 @@ export const storageServiceClient = {
},
},
async getUsersHistory() {
- return mapOk(await dssFetch<{ data: Item[] }>(`/history`), (result) => ({
+ return (await dssFetch<{ data: Item[] }>(`/history`)).map((result) => ({
data: result.data,
}));
},
async upsertItemToUserHistory({ itemType, itemId }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/history/${itemType}/${itemId}`, {
method: 'POST',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async removeItemFromUserHistory(params: {
itemId: string;
itemType: ItemType;
}) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(
`/history/${params.itemType}/${params.itemId}`,
{
method: 'DELETE',
}
- ),
- (result) => result.data
- );
+ )
+ ).map((result) => result.data);
},
async editDocument(params) {
const { documentId, ...body } = params;
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/documents/${documentId}`, {
method: 'PATCH',
body: JSON.stringify(body),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async getUserDocuments(params: { limit: number; offset: number }) {
- return mapOk(
+ return (
await dssFetch<{
data: {
documents: DocumentMetadata[];
total: number;
next_offset: number;
};
- }>(`/documents?limit=${params.limit}&offset=${params.offset}`),
- (result) => ({
- documents: result.data.documents,
- total: result.data.total,
- nextOffset: result.data.next_offset,
- })
- );
+ }>(`/documents?limit=${params.limit}&offset=${params.offset}`)
+ ).map((result) => ({
+ documents: result.data.documents,
+ total: result.data.total,
+ nextOffset: result.data.next_offset,
+ }));
},
async initializeUserDocuments() {
- return mapOk(
+ return (
await dssFetch<{ success: boolean }>(
'/documents/initialize_user_documents',
{
method: 'POST',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async deleteDocument(params: { documentId: string }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/documents/${params.documentId}`, {
method: 'DELETE',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async getPins(params?: { limit?: number; offset?: number }) {
- return mapOk(
+ return (
await dssFetch<{ data: UserPins }>(
`/pins?limit=${params?.limit ?? 10}&offset=${params?.offset ?? 0}`
- ),
- (result) => result.data
- );
+ )
+ ).map((result) => result.data);
},
async pinItem(params: { id: string } & AddPinRequest) {
const { id, ...body } = params;
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/pins/${id}`, {
method: 'POST',
body: JSON.stringify(body),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async removePin(params: { id: string } & PinRequest) {
const { id, ...body } = params;
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/pins/${id}`, {
method: 'DELETE',
body: JSON.stringify(body),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async reorderPins(params: { pins: Array<ReorderPinRequest> }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/pins`, {
method: 'PATCH',
body: JSON.stringify(params.pins),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async getDocumentMetadata(params: {
@@ -458,18 +440,17 @@ export const storageServiceClient = {
maxTries: 5,
},
};
- return mapOk(
+ return (
await dssFetch<{
data: GetDocumentResponseData;
- }>(`/documents/${params.documentId}${versionSuffix}`, fetchOptions),
- (result) => {
- const data = result.data;
- return {
- ...data,
- documentMetadata: data.documentMetadata,
- };
- }
- );
+ }>(`/documents/${params.documentId}${versionSuffix}`, fetchOptions)
+ ).map((result) => {
+ const data = result.data;
+ return {
+ ...data,
+ documentMetadata: data.documentMetadata,
+ };
+ });
},
async createDocument(request: CreateDocumentRequest) {
@@ -478,20 +459,20 @@ export const storageServiceClient = {
body: JSON.stringify(request),
});
- if (!isOk(result)) {
- const err = result[0];
+ if (!result.isOk()) {
+ const errors = result.error;
- if (err[0].message.includes('403')) {
+ if (errors[0].message.includes('403')) {
showPaywall(PaywallKey.FILE_LIMIT);
}
- return result;
+ return err(result.error);
}
- const [, { data }] = result;
+ const { data } = result.value;
if (!data.presignedUrl) {
console.error('no presigned url found for upload');
- return err('SERVER_ERROR', 'Failed to upload file');
+ return err([{ code: 'SERVER_ERROR', message: 'Failed to upload file' }]);
}
return ok({
@@ -514,15 +495,15 @@ export const storageServiceClient = {
}
);
- if (!isOk(result)) {
- const err = result[0];
- if (err[0].message.includes('403')) {
+ if (!result.isOk()) {
+ const errors = result.error;
+ if (errors[0].message.includes('403')) {
showPaywall(PaywallKey.FILE_LIMIT);
}
- return result;
+ return err(result.error);
}
- const [, response] = result;
+ const response = result.value;
return ok({ documentId: response.documentId });
},
@@ -538,15 +519,15 @@ export const storageServiceClient = {
}
);
- if (!isOk(result)) {
- const err = result[0];
- if (err[0].message.includes('403')) {
+ if (!result.isOk()) {
+ const errors = result.error;
+ if (errors[0].message.includes('403')) {
showPaywall(PaywallKey.FILE_LIMIT);
}
- return result;
+ return err(result.error);
}
- const [, response] = result;
+ const response = result.value;
return ok(response);
},
@@ -571,54 +552,51 @@ export const storageServiceClient = {
}
);
- const result: MaybeResult<
- FetchWithTokenErrorCode,
- DocumentResponseMetadataWithContent
- > = mapOk(copyResult, (result) => result.data.documentMetadata);
+ const result: Result<
+ DocumentResponseMetadataWithContent,
+ ResultError<FetchWithTokenErrorCode>[]
+ > = copyResult.map((result) => result.data.documentMetadata);
- if (isErr(result)) {
- const err = result[0];
+ if (result.isErr()) {
+ const errors = result.error;
- if (err[0].message.includes('403')) {
+ if (errors[0].message.includes('403')) {
showPaywall(PaywallKey.FILE_LIMIT);
}
- return result;
+ return err(result.error);
}
return result;
},
async permanentlyDeleteDocument({ documentId }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/documents/${documentId}/permanent`, {
method: 'DELETE',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async revertDocumentDelete({ documentId }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(
`/documents/${documentId}/revert_delete`,
{
method: 'PUT',
}
- ),
- (result) => result.data
- );
+ )
+ ).map((result) => result.data);
},
async getDocumentShortId({
documentId,
}: {
documentId: string;
- }): Promise<MaybeResult<FetchWithTokenErrorCode, string>> {
- return mapOk(
+ }): Promise<Result<string, ResultError<FetchWithTokenErrorCode>[]>> {
+ return (
await dssFetch<{ shortId: string }>(`/documents/${documentId}/short_id`, {
method: 'GET',
- }),
- (result) => result.shortId
- );
+ })
+ ).map((result) => result.shortId);
},
async getDocumentBranchName({
@@ -626,70 +604,65 @@ export const storageServiceClient = {
}: {
documentId: string;
}): Promise<
- MaybeResult<
- FetchWithTokenErrorCode,
- { shortId: string; branchName: string }
+ Result<
+ { shortId: string; branchName: string },
+ ResultError<FetchWithTokenErrorCode>[]
>
> {
- return mapOk(
+ return (
await dssFetch<{ shortId: string; branchName: string }>(
`/documents/${documentId}/branch_name`,
{ method: 'GET' }
- ),
- (result) => ({
- shortId: result.shortId,
- branchName: result.branchName,
- })
- );
+ )
+ ).map((result) => ({
+ shortId: result.shortId,
+ branchName: result.branchName,
+ }));
},
async exportDocument({ documentId }) {
- return mapOk(
+ return (
await dssFetch<ExportDocumentResponse>(
`/documents/${documentId}/export`,
{
method: 'GET',
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async uploadModificationData(uploadData: unknown) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/documents/metadata/modification-data`, {
method: 'PATCH',
body: JSON.stringify(uploadData, modificationDataReplacer),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async getBatchDocumentPreviews(args: { document_ids: string[] }) {
- return mapOk(
+ return (
await dssFetch<{ previews: DocumentPreview[] }>(`/documents/preview`, {
method: 'POST',
body: JSON.stringify({ document_ids: args.document_ids }),
- }),
- (result) => ({
- previews: result.previews,
})
- );
+ ).map((result) => ({
+ previews: result.previews,
+ }));
},
async getBatchCallPreviews(args: { call_ids: string[] }) {
- return mapOk(
+ return (
await dssFetch<{ previews: CallRecordPreview[] }>(
`/call/record/preview`,
{
method: 'POST',
body: JSON.stringify({ callIds: args.call_ids }),
}
- ),
- (result) => ({
- previews: result.previews,
- })
- );
+ )
+ ).map((result) => ({
+ previews: result.previews,
+ }));
},
async getDocumentProcessingResult<T extends ProcessingResultType>(params: {
@@ -699,12 +672,14 @@ export const storageServiceClient = {
const result = await dssFetch<GetDocumentProcessingResultResponse>(
`/documents/${params.documentId}/processing`
);
- if (!isOk(result)) return result;
+ if (!result.isOk()) return err(result.error);
- const [, { data }] = result;
+ const { data } = result.value;
if (!data?.result) {
- return err('INVALID_RESPONSE', 'Processing result is missing');
+ return err([
+ { code: 'INVALID_RESPONSE', message: 'Processing result is missing' },
+ ]);
}
switch (params.type) {
case 'PREPROCESS': {
@@ -713,10 +688,17 @@ export const storageServiceClient = {
? ok({
preprocess: parseResult.data,
})
- : err('INVALID_RESPONSE', 'Invalid PREPROCESS result');
+ : err([
+ {
+ code: 'INVALID_RESPONSE',
+ message: 'Invalid PREPROCESS result',
+ },
+ ]);
}
default:
- return err('INVALID_RESPONSE', `Invalid type ${params.type}`);
+ return err([
+ { code: 'INVALID_RESPONSE', message: `Invalid type ${params.type}` },
+ ]);
}
},
async getJobProcessingResult<T extends ProcessingResultType>(params: {
@@ -727,12 +709,14 @@ export const storageServiceClient = {
const result = await dssFetch<GetDocumentProcessingResultResponse>(
`/documents/${params.documentId}/processing/${params.jobId}`
);
- if (!isOk(result)) return result;
+ if (!result.isOk()) return err(result.error);
- const [, { data }] = result;
+ const { data } = result.value;
if (!data?.result) {
- return err('INVALID_RESPONSE', 'Processing result is missing');
+ return err([
+ { code: 'INVALID_RESPONSE', message: 'Processing result is missing' },
+ ]);
}
switch (params.type) {
case 'PREPROCESS': {
@@ -741,16 +725,22 @@ export const storageServiceClient = {
? ok({
preprocess: parseResult.data,
})
- : err('INVALID_RESPONSE', 'Invalid PREPROCESS result');
+ : err([
+ {
+ code: 'INVALID_RESPONSE',
+ message: 'Invalid PREPROCESS result',
+ },
+ ]);
}
default:
- return err('INVALID_RESPONSE', `Invalid type ${params.type}`);
+ return err([
+ { code: 'INVALID_RESPONSE', message: `Invalid type ${params.type}` },
+ ]);
}
},
async listDocuments() {
- return mapOk(
- await dssFetch<GetDocumentSearchResponse>(`/documents/list`),
+ return (await dssFetch<GetDocumentSearchResponse>(`/documents/list`)).map(
(result) => ({ documents: result.data })
);
},
@@ -769,7 +759,9 @@ export const storageServiceClient = {
JSON.parse(modificationDataString)
);
if (!attemptParse.success) {
- return err('INVALID_DATA', 'Invalid modification data to save');
+ return err([
+ { code: 'INVALID_DATA', message: 'Invalid modification data to save' },
+ ]);
}
const body = `{ "sha": "${sha}", "modificationData": ${modificationDataString} }`;
@@ -780,19 +772,21 @@ export const storageServiceClient = {
body,
}
);
- if (!isOk(result)) return result;
+ if (!result.isOk()) return err(result.error);
- const [, { data }] = result;
+ const { data } = result.value;
const metadata =
saveDocumentHandlerResponse.shape.data.shape.documentMetadata.safeParse(
data.documentMetadata
);
if (!metadata.success) {
- return err(
- 'INVALID_RESPONSE',
- 'Invalid document metadata in server response'
- );
+ return err([
+ {
+ code: 'INVALID_RESPONSE',
+ message: 'Invalid document metadata in server response',
+ },
+ ]);
}
return ok(metadata.data);
},
@@ -808,90 +802,86 @@ export const storageServiceClient = {
body: formData,
}
);
- if (!isOk(result)) return result;
+ if (!result.isOk()) return err(result.error);
- const [, { data }] = result;
+ const { data } = result.value;
const metadata =
saveDocumentHandlerResponse.shape.data.shape.documentMetadata.safeParse(
data.documentMetadata
);
if (!metadata.success) {
- return err(
- 'INVALID_RESPONSE',
- 'Invalid document metatdata in server response'
- );
+ return err([
+ {
+ code: 'INVALID_RESPONSE',
+ message: 'Invalid document metatdata in server response',
+ },
+ ]);
}
return ok(metadata.data);
},
annotations: {
async getComments({ documentId }) {
- return mapOk(
+ return (
await dssFetch<ThreadResponse>(
`/annotations/comments/document/${documentId}`,
{
method: 'GET',
}
- ),
- (result) => ({ data: result.data })
- );
+ )
+ ).map((result) => ({ data: result.data }));
},
async getAnchors({ documentId }) {
- return mapOk(
+ return (
await dssFetch<AnchorResponse>(
`/annotations/anchors/document/${documentId}`,
{
method: 'GET',
}
- ),
- (result) => ({ data: result.data })
- );
+ )
+ ).map((result) => ({ data: result.data }));
},
async createComment({ documentId, body }) {
- return mapOk(
+ return (
await dssFetch<CreateCommentResponse>(
`/annotations/comments/document/${documentId}`,
{
method: 'POST',
body: JSON.stringify(body),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async createAnchor({ documentId, body }) {
- return mapOk(
+ return (
await dssFetch<CreateUnthreadedAnchorResponse>(
`/annotations/anchors/document/${documentId}`,
{
method: 'POST',
body: JSON.stringify(body),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async deleteComment({ commentId, body }) {
- return mapOk(
+ return (
await dssFetch<DeleteCommentResponse>(
`/annotations/comments/comment/${commentId}`,
{
method: 'DELETE',
body: JSON.stringify(body),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async deleteAnchor({ body }) {
- return mapOk(
+ return (
await dssFetch<DeleteUnthreadedAnchorResponse>(`/annotations/anchors`, {
method: 'DELETE',
body: JSON.stringify(body),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async editComment({ commentId, body }) {
return await dssFetch<EditCommentResponse>(
@@ -903,13 +893,12 @@ export const storageServiceClient = {
);
},
async editAnchor({ body }) {
- return mapOk(
+ return (
await dssFetch<EditAnchorResponse>(`/annotations/anchors`, {
method: 'PATCH',
body: JSON.stringify(body),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
},
@@ -917,9 +906,9 @@ export const storageServiceClient = {
async function getDocxFile(
args
): Promise<
- MaybeResult<
- FetchError | 'INVALID_FILETYPE' | 'INVALID_DOCUMENT',
- GetDocxFileResponse
+ Result<
+ GetDocxFileResponse,
+ ResultError<FetchError | 'INVALID_FILETYPE' | 'INVALID_DOCUMENT'>[]
>
> {
const { documentId, documentVersionId } = args;
@@ -933,7 +922,7 @@ export const storageServiceClient = {
documentVersionId,
}),
args.withoutParts
- ? (Promise.resolve([null, { presignedUrls: [] }]) as ReturnType<
+ ? (Promise.resolve(ok({ presignedUrls: [] })) as ReturnType<
typeof storageServiceClient.getWriterPartUrls
>)
: storageServiceClient.getWriterPartUrls({
@@ -943,11 +932,11 @@ export const storageServiceClient = {
]);
} else {
metadataResult = await storageServiceClient.getDocumentMetadata(args);
- if (isErr(metadataResult)) return metadataResult;
- const [, { documentMetadata: metadata }] = metadataResult;
+ if (metadataResult.isErr()) return err(metadataResult.error);
+ const { documentMetadata: metadata } = metadataResult.value;
const versionId = metadata.documentVersionId.toString();
locationResult = args.withoutParts
- ? await (Promise.resolve([null, { presignedUrls: [] }]) as ReturnType<
+ ? await (Promise.resolve(ok({ presignedUrls: [] })) as ReturnType<
typeof storageServiceClient.getWriterPartUrls
>)
: await storageServiceClient.getWriterPartUrls({
@@ -956,27 +945,31 @@ export const storageServiceClient = {
});
}
- if (isErr(locationResult)) {
- return locationResult;
+ if (locationResult.isErr()) {
+ return err(locationResult.error);
}
- if (isErr(metadataResult)) {
- return metadataResult;
+ if (metadataResult.isErr()) {
+ return err(metadataResult.error);
}
- const [, info] = locationResult;
- const [, { documentMetadata: metadata, userAccessLevel }] =
- metadataResult;
+ const info = locationResult.value;
+ const { documentMetadata: metadata, userAccessLevel } =
+ metadataResult.value;
if (metadata.fileType !== 'docx') {
- return err('INVALID_FILETYPE', metadata.fileType ?? 'unknown');
+ return err([
+ { code: 'INVALID_FILETYPE', message: metadata.fileType ?? 'unknown' },
+ ]);
}
if (
!args.withoutParts &&
(info.presignedUrls == null || metadata.documentBom == null)
) {
- return err('INVALID_DOCUMENT', 'Document has no parts');
+ return err([
+ { code: 'INVALID_DOCUMENT', message: 'Document has no parts' },
+ ]);
}
return ok<GetDocxFileResponse>({
@@ -995,26 +988,36 @@ export const storageServiceClient = {
async function getTextDocument(args) {
const metadataResult =
await storageServiceClient.getDocumentMetadata(args);
- if (isErr(metadataResult)) return metadataResult;
- const [, { documentMetadata, userAccessLevel }] = metadataResult;
+ if (metadataResult.isErr()) return err(metadataResult.error);
+ const { documentMetadata, userAccessLevel } = metadataResult.value;
const locationResult = await storageServiceClient.getDocumentLocation({
documentId: documentMetadata.documentId,
versionId: documentMetadata.documentVersionId,
});
- if (isErr(locationResult, 'GONE'))
- return err('NOT_FOUND', 'The document resource is no longer available');
- else if (isErr(locationResult)) return locationResult;
- const [, { data }] = locationResult;
+ if (
+ locationResult.isErr() &&
+ locationResult.error.some((error) => error.code === 'GONE')
+ )
+ return err([
+ {
+ code: 'NOT_FOUND',
+ message: 'The document resource is no longer available',
+ },
+ ]);
+ else if (locationResult.isErr()) return err(locationResult.error);
+ const { data } = locationResult.value;
if (data.type !== 'presignedUrl') {
- return err(
- 'INVALID_DOCUMENT',
- 'Document location is missing presignedUrl'
- );
+ return err([
+ {
+ code: 'INVALID_DOCUMENT',
+ message: 'Document location is missing presignedUrl',
+ },
+ ]);
}
const result = await fetchPresigned(data.presignedUrl, 'text');
- if (isErr(result)) return result;
- const [, text] = result;
+ if (result.isErr()) return err(result.error);
+ const text = result.value;
return ok({
text,
documentMetadata,
@@ -1029,18 +1032,18 @@ export const storageServiceClient = {
async getBinaryDocument(
args
): Promise<
- MaybeResult<
- FetchError | 'INVALID_DOCUMENT',
- GetDocumentResponseData & { blobUrl: string }
+ Result<
+ GetDocumentResponseData & { blobUrl: string },
+ ResultError<FetchError | 'INVALID_DOCUMENT'>[]
>
> {
const maybeDocument = await storageServiceClient.getDocumentMetadata(args);
- if (isErr(maybeDocument)) {
+ if (maybeDocument.isErr()) {
console.error('error in getDocument', maybeDocument);
- return maybeDocument;
+ return err(maybeDocument.error);
}
- const [, documentData] = maybeDocument;
+ const documentData = maybeDocument.value;
const {
documentMetadata: { documentId, documentVersionId: versionId },
} = documentData;
@@ -1049,17 +1052,19 @@ export const storageServiceClient = {
documentId,
versionId,
});
- if (isErr(maybeLocation)) {
+ if (maybeLocation.isErr()) {
console.error('error in getLocation', maybeLocation);
- return maybeLocation;
+ return err(maybeLocation.error);
}
- const [, { data }] = maybeLocation;
+ const { data } = maybeLocation.value;
if (data.type !== 'presignedUrl') {
- return err(
- 'INVALID_DOCUMENT',
- 'Document location is missing presignedUrl'
- );
+ return err([
+ {
+ code: 'INVALID_DOCUMENT',
+ message: 'Document location is missing presignedUrl',
+ },
+ ]);
}
return ok({
@@ -1079,19 +1084,21 @@ export const storageServiceClient = {
body: formData,
}
);
- if (!isOk(result)) return result;
+ if (!result.isOk()) return err(result.error);
- const [, { data }] = result;
+ const { data } = result.value;
const metadata =
saveDocumentHandlerResponse.shape.data.shape.documentMetadata.safeParse(
data.documentMetadata
);
if (!metadata.success) {
- return err(
- 'INVALID_RESPONSE',
- 'Invalid document metatdata in server response'
- );
+ return err([
+ {
+ code: 'INVALID_RESPONSE',
+ message: 'Invalid document metatdata in server response',
+ },
+ ]);
}
return ok(metadata.data);
},
@@ -1100,17 +1107,16 @@ export const storageServiceClient = {
// this can be cached because it requires the version ID
async function getWriterPartUrls(args) {
const { uuid, versionId } = args;
- return mapOk(
+ return (
await dssFetch<{
presignedUrls: Array<{ sha: string; presignedUrl: string }>;
- }>(`/documents/${uuid}/location${withVersionId(versionId)}`),
- (result) => ({
- presignedUrls: result.presignedUrls.map((x) => ({
- url: x.presignedUrl,
- sha: x.sha,
- })),
- })
- );
+ }>(`/documents/${uuid}/location${withVersionId(versionId)}`)
+ ).map((result) => ({
+ presignedUrls: result.presignedUrls.map((x) => ({
+ url: x.presignedUrl,
+ sha: x.sha,
+ })),
+ }));
},
{
minutes: MINUTES_BEFORE_PRESIGNED_EXPIRES,
@@ -1127,11 +1133,11 @@ export const storageServiceClient = {
if (versionId != null)
params.set('document_version_id', String(versionId));
- const maybeResult = await dssFetch<LocationResponseV3>(
+ const result = await dssFetch<LocationResponseV3>(
`/documents/${documentId}/location_v3?${params.toString()}`
);
- return mapOk(maybeResult, (result) => ({
+ return result.map((result) => ({
data: normalizeLocationResponseV3(result),
}));
},
@@ -1154,12 +1160,11 @@ export const storageServiceClient = {
async getDocumentPermissions(args) {
const { document_id } = args;
- return mapOk(
+ return (
await dssFetch<GetDocumentPermissionsResponseDataV2>(
`/documents/${document_id}/permissions`
- ),
- (result) => result.documentPermissions
- );
+ )
+ ).map((result) => result.documentPermissions);
},
getDocxExpandedParts,
@@ -1179,24 +1184,21 @@ export const storageServiceClient = {
projects: {
async getAll() {
- return mapOk(
- await dssFetch<{ data: Project[] }>('/projects'),
+ return (await dssFetch<{ data: Project[] }>('/projects')).map(
(result) => ({ data: result.data })
);
},
async getProject({ id }) {
- return mapOk(
- await dssFetch<GetProjectResponse>(`/projects/${id}`),
+ return (await dssFetch<GetProjectResponse>(`/projects/${id}`)).map(
(result) => result.data
);
},
async getPending() {
- return mapOk(
- await dssFetch<GetPendingProjectsHandler200>('/projects/pending'),
- (result) => ({ data: result.data })
- );
+ return (
+ await dssFetch<GetPendingProjectsHandler200>('/projects/pending')
+ ).map((result) => ({ data: result.data }));
},
async create(params: {
@@ -1204,102 +1206,92 @@ export const storageServiceClient = {
projectParentId?: string;
sharePermission?: null;
}) {
- return mapOk(
+ return (
await dssFetch<CreateProjectResponse>('/projects', {
method: 'POST',
body: JSON.stringify(params),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async delete({ id }: { id: string }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/projects/${id}`, {
method: 'DELETE',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async edit(args) {
const { id, ...body } = args;
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/projects/${id}`, {
method: 'PATCH',
body: JSON.stringify(body),
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async getContent({ id }: { id: string }) {
- return mapOk(
- await dssFetch<GetProjectContentResponse>(`/projects/${id}/content`),
- (result) => result
- );
+ return (
+ await dssFetch<GetProjectContentResponse>(`/projects/${id}/content`)
+ ).map((result) => result);
},
async getPermissions({ id }) {
- return mapOk(
- await dssFetch<SharePermissionV2>(`/projects/${id}/permissions`),
- (result) => result
- );
+ return (
+ await dssFetch<SharePermissionV2>(`/projects/${id}/permissions`)
+ ).map((result) => result);
},
async getUserAccessLevel({
id,
- }): Promise<MaybeResult<FetchWithTokenErrorCode, AccessLevel>> {
+ }): Promise<Result<AccessLevel, ResultError<FetchWithTokenErrorCode>[]>> {
return await dssFetch<any>(`/projects/${id}/access_level`);
},
async getPreview(args) {
- return mapOk(
+ return (
await dssFetch<GetBatchProjectPreviewResponse>(`/projects/preview`, {
method: 'POST',
body: JSON.stringify(args),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async createUploadZipRequest(args) {
- return mapOk(
+ return (
await dssFetch<UploadExtractFolderHandler200>(
`/projects/upload_extract`,
{
method: 'POST',
body: JSON.stringify(args),
}
- ),
- (result) => result.data
- );
+ )
+ ).map((result) => result.data);
},
async permanentlyDelete({ id }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/projects/${id}/permanent`, {
method: 'DELETE',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
async revertDelete({ id }) {
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/projects/${id}/revert_delete`, {
method: 'PUT',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
},
async getDeletedItems() {
- return mapOk(
+ return (
await dssFetch<TypedSuccessResponse>('/recents/deleted', {
method: 'GET',
- }),
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
instructions: {
@@ -1318,19 +1310,17 @@ export const storageServiceClient = {
views: {
async getSavedViews() {
- return mapOk(
- await dssFetch<ViewsResponse>('/saved_views'),
+ return (await dssFetch<ViewsResponse>('/saved_views')).map(
(result) => result
);
},
async createSavedView(params) {
- return mapOk(
+ return (
await dssFetch<View>('/saved_views', {
method: 'POST',
body: JSON.stringify(params),
- }),
- (result) => result
- );
+ })
+ ).map((result) => result);
},
async excludeDefaultView(params) {
return await dssFetch('/saved_views/exclude_default', {
@@ -1354,14 +1344,12 @@ export const storageServiceClient = {
async editThread(params) {
const { threadId, ...body } = params;
- return mapOk(
+ return (
await dssFetch<SuccessResponse>(`/threads/${threadId}`, {
method: 'PATCH',
body: JSON.stringify(body),
- }),
-
- (result) => result.data
- );
+ })
+ ).map((result) => result.data);
},
} satisfies StorageServiceClient &
typeof enhancements &
diff --git a/js/app/packages/service-clients/service-storage/util/fetchBinary.ts b/js/app/packages/service-clients/service-storage/util/fetchBinary.ts
index 817c058d44..4750434b4b 100644
--- a/js/app/packages/service-clients/service-storage/util/fetchBinary.ts
+++ b/js/app/packages/service-clients/service-storage/util/fetchBinary.ts
@@ -1,5 +1,7 @@
-import { err, type MaybeResult, ok } from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
+
import { platformFetch } from 'core/util/platformFetch';
+import { err, ok, type Result } from 'neverthrow';
import type { DocumentMetadata } from '../generated/schemas/documentMetadata';
import type { StorageError } from './storageError';
@@ -7,30 +9,39 @@ export async function fetchBinary(
url: string,
responseType: 'arraybuffer',
init?: RequestInit
-): Promise<MaybeResult<StorageError, ArrayBuffer>>;
+): Promise<Result<ArrayBuffer, ResultError<StorageError>[]>>;
export async function fetchBinary(
url: string,
responseType: 'blob',
init?: RequestInit
-): Promise<MaybeResult<StorageError, Blob>>;
+): Promise<Result<Blob, ResultError<StorageError>[]>>;
export async function fetchBinary<T extends ArrayBuffer | Blob>(
url: string,
responseType: 'arraybuffer' | 'blob',
init?: RequestInit
-): Promise<MaybeResult<StorageError, T>> {
+): Promise<Result<T, ResultError<StorageError>[]>> {
try {
const response = await platformFetch(url, init);
if (!response.ok) {
switch (response.status) {
case 404:
- return err('NOT_FOUND', 'Resource not found');
+ return err([{ code: 'NOT_FOUND', message: 'Resource not found' }]);
case 401:
- return err('UNAUTHORIZED', 'Unauthorized access');
+ return err([
+ { code: 'UNAUTHORIZED', message: 'Unauthorized access' },
+ ]);
case 500:
- return err('SERVER_ERROR', 'Internal server error');
+ return err([
+ { code: 'SERVER_ERROR', message: 'Internal server error' },
+ ]);
default:
- return err('HTTP_ERROR', `HTTP error! status: ${response.status}`);
+ return err([
+ {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ },
+ ]);
}
}
@@ -40,9 +51,16 @@ export async function fetchBinary<T extends ArrayBuffer | Blob>(
return ok(data as T);
} catch (error) {
if (error instanceof TypeError && error.message === 'Failed to fetch') {
- return err('NETWORK_ERROR', 'Network error occurred');
+ return err([
+ { code: 'NETWORK_ERROR', message: 'Network error occurred' },
+ ]);
} else {
- return err('UNKNOWN_ERROR', `An unknown error occurred: ${error}`);
+ return err([
+ {
+ code: 'UNKNOWN_ERROR',
+ message: `An unknown error occurred: ${error}`,
+ },
+ ]);
}
}
}
diff --git a/js/app/packages/service-clients/service-storage/util/fetchPresigned.ts b/js/app/packages/service-clients/service-storage/util/fetchPresigned.ts
index f0485225e4..f22e9f1fa2 100644
--- a/js/app/packages/service-clients/service-storage/util/fetchPresigned.ts
+++ b/js/app/packages/service-clients/service-storage/util/fetchPresigned.ts
@@ -1,11 +1,7 @@
import type { FetchError } from '@core/service';
-import {
- err,
- type MaybeResult,
- type ObjectLike,
- ok,
-} from '@core/util/maybeResult';
+import type { ObjectLike, ResultError } from '@core/util/result';
import { platformFetch } from 'core/util/platformFetch';
+import { err, ok, type Result } from 'neverthrow';
type ResultMap = {
arraybuffer: ArrayBuffer;
@@ -14,31 +10,47 @@ type ResultMap = {
json: ObjectLike;
};
-function httpStatusToError(status: number) {
+function httpStatusToError(
+ status: number
+): Result<never, ResultError<FetchError>[]> {
switch (status) {
case 404:
- return err('NOT_FOUND', 'Resource not found');
+ return err<never, ResultError<FetchError>[]>([
+ { code: 'NOT_FOUND', message: 'Resource not found' },
+ ]);
case 401:
- return err('UNAUTHORIZED', 'Unauthorized access');
+ return err<never, ResultError<FetchError>[]>([
+ { code: 'UNAUTHORIZED', message: 'Unauthorized access' },
+ ]);
case 500:
- return err('SERVER_ERROR', 'Internal server error');
+ return err<never, ResultError<FetchError>[]>([
+ { code: 'SERVER_ERROR', message: 'Internal server error' },
+ ]);
default:
- return err('HTTP_ERROR', `HTTP error! status: ${status}`);
+ return err<never, ResultError<FetchError>[]>([
+ { code: 'HTTP_ERROR', message: `HTTP error! status: ${status}` },
+ ]);
}
}
-function fetchExceptionToError(error: unknown) {
+function fetchExceptionToError(
+ error: unknown
+): Result<never, ResultError<FetchError>[]> {
if (error instanceof TypeError && error.message === 'Failed to fetch') {
- return err('NETWORK_ERROR', 'Network error occurred');
+ return err<never, ResultError<FetchError>[]>([
+ { code: 'NETWORK_ERROR', message: 'Network error occurred' },
+ ]);
}
- return err('UNKNOWN_ERROR', `An unknown error occurred: ${error}`);
+ return err<never, ResultError<FetchError>[]>([
+ { code: 'UNKNOWN_ERROR', message: `An unknown error occurred: ${error}` },
+ ]);
}
export async function fetchPresigned<K extends keyof ResultMap>(
url: string,
responseType: K,
init?: RequestInit
-): Promise<MaybeResult<FetchError, ResultMap[K]>> {
+): Promise<Result<ResultMap[K], ResultError<FetchError>[]>> {
try {
const response = await platformFetch(url, init);
@@ -64,7 +76,7 @@ export async function fetchPresignedBlobWithProgress(
url: string,
onProgress: (progress: FetchProgress) => void,
init?: RequestInit
-): Promise<MaybeResult<FetchError, Blob>> {
+): Promise<Result<Blob, ResultError<FetchError>[]>> {
try {
const response = await platformFetch(url, init);
diff --git a/js/app/packages/service-clients/service-storage/util/getDocxFile.ts b/js/app/packages/service-clients/service-storage/util/getDocxFile.ts
index a83d63d6a6..70e8f930af 100644
--- a/js/app/packages/service-clients/service-storage/util/getDocxFile.ts
+++ b/js/app/packages/service-clients/service-storage/util/getDocxFile.ts
@@ -1,14 +1,9 @@
import type { FlattenObject } from '@core/util/flatten';
-import {
- err,
- isErr,
- type MaybeResult,
- ok,
- type ResultError,
-} from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
import type { WithRequired } from '@core/util/withRequired';
import type { AccessLevel as UserAccessLevel } from '@service-storage/generated/schemas/accessLevel';
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
+import { err, ok, type Result } from 'neverthrow';
import { fetchBinary } from './fetchBinary';
import { getOPFSDocumentStore } from './opfs';
import type { StorageError } from './storageError';
@@ -40,16 +35,18 @@ export type GetDocxFileResponse = FlattenObject<{
export async function getDocxExpandedParts(
docxFile: GetDocxFileResponse
-): Promise<MaybeResult<StorageError, DocxExpandedPart[]>> {
+): Promise<Result<DocxExpandedPart[], ResultError<StorageError>[]>> {
const { documentId, documentBom } = docxFile.metadata;
let opfsDocumentStore;
try {
opfsDocumentStore = await getOPFSDocumentStore();
} catch (error) {
- return err(
- 'OPFS_ERROR',
- `Failed to get OPFS document store: ${error.message}`
- );
+ return err([
+ {
+ code: 'OPFS_ERROR',
+ message: `Failed to get OPFS document store: ${error.message}`,
+ },
+ ]);
}
let opfsDocHandle;
@@ -57,27 +54,33 @@ export async function getDocxExpandedParts(
const result = await opfsDocumentStore.get(documentId, { create: true });
opfsDocHandle = result.document;
} catch (error) {
- return err(
- 'OPFS_ERROR',
- `Failed to get OPFS document handle for ${documentId}: ${error.message}`
- );
+ return err([
+ {
+ code: 'OPFS_ERROR',
+ message: `Failed to get OPFS document handle for ${documentId}: ${error.message}`,
+ },
+ ]);
}
if (!opfsDocHandle) {
- return err(
- 'OPFS_ERROR',
- `Failed to get OPFS document handle for ${documentId}`
- );
+ return err([
+ {
+ code: 'OPFS_ERROR',
+ message: `Failed to get OPFS document handle for ${documentId}`,
+ },
+ ]);
}
let opfsParts: DocxExpandedPartList;
try {
opfsParts = await opfsDocHandle.list();
} catch (error) {
- return err(
- 'OPFS_ERROR',
- `Failed to list OPFS parts for ${documentId}: ${error.message}`
- );
+ return err([
+ {
+ code: 'OPFS_ERROR',
+ message: `Failed to list OPFS parts for ${documentId}: ${error.message}`,
+ },
+ ]);
}
const partPromises = docxFile.parts.map(async (location) => {
@@ -119,18 +122,20 @@ export async function getDocxExpandedParts(
headers: { 'Content-Type': 'application/octet-stream' },
});
- if (isErr(fetchResult)) {
- return fetchResult;
+ if (fetchResult.isErr()) {
+ return err(fetchResult.error);
}
- const [, arrayBuffer] = fetchResult;
+ const arrayBuffer = fetchResult.value;
const shaMatches = documentBom.filter((bom) => bom.sha === sha);
if (shaMatches.length === 0) {
- return err(
- 'INVALID_DOCUMENT',
- `Failed to find path for ${url}, sha: ${sha}`
- );
+ return err([
+ {
+ code: 'INVALID_DOCUMENT' as const,
+ message: `Failed to find path for ${url}, sha: ${sha}`,
+ },
+ ]);
}
return ok(
@@ -149,22 +154,21 @@ export async function getDocxExpandedParts(
settledResults.forEach((result) => {
if (result.status === 'fulfilled') {
- const [err, part] = result.value;
- if (err) {
- errors.push(...err);
+ if (result.value.isErr()) {
+ errors.push(...result.value.error);
} else {
- parts.push(...part);
+ parts.push(...result.value.value);
}
} else {
errors.push({
- code: 'UNKNOWN_ERROR',
+ code: 'UNKNOWN_ERROR' as const,
message: `Failed to process part: ${result.reason}`,
});
}
});
if (errors.length > 0) {
- return [errors, null];
+ return err(errors);
}
return ok(parts);
diff --git a/js/app/packages/service-clients/service-storage/util/presignedUrl.ts b/js/app/packages/service-clients/service-storage/util/presignedUrl.ts
index 6c29257670..3552b3b1dd 100644
--- a/js/app/packages/service-clients/service-storage/util/presignedUrl.ts
+++ b/js/app/packages/service-clients/service-storage/util/presignedUrl.ts
@@ -1,4 +1,3 @@
-import { isErr } from '@core/util/maybeResult';
import { storageServiceClient } from '../client';
// we expire slightly before the actual expiry to avoid race condition
@@ -39,11 +38,11 @@ export const getPresignedUrl = async ({
documentId,
versionId,
});
- if (isErr(maybeLocation)) {
+ if (maybeLocation.isErr()) {
throw new Error('unable to retrieve location data');
}
- const [, { data }] = maybeLocation;
+ const { data } = maybeLocation.value;
if (data.type !== 'presignedUrl') {
throw new Error('presignedUrl not found in location data');
}
diff --git a/js/app/packages/service-clients/service-storage/util/upload.ts b/js/app/packages/service-clients/service-storage/util/upload.ts
index e7c995b951..2f8623b92c 100644
--- a/js/app/packages/service-clients/service-storage/util/upload.ts
+++ b/js/app/packages/service-clients/service-storage/util/upload.ts
@@ -3,7 +3,7 @@ import type { FileTypeString, MimeType } from '@core/block';
import { blockAcceptedMimetypeToFileExtension } from '@core/constant/allBlocks';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { contentHash } from '@core/util/hash';
-import { isErr, type ResultError } from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
import { toaster } from '@kobalte/core/toast';
import { waitForDocumentContentReady } from '@queries/storage/document-location';
import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
@@ -26,7 +26,7 @@ const uploadWithPresignedUrl = async (params: {
type: MimeType;
}) => {
const uploadResult = await uploadToPresignedUrl(params);
- return !isErr(uploadResult);
+ return !uploadResult.isErr();
};
type DocumentUploadResult = {
@@ -130,11 +130,11 @@ export async function upload(
name,
parentId: options?.projectId,
});
- if (isErr(res)) {
- return handleUploadError(res[0], toastId);
+ if (res.isErr()) {
+ return handleUploadError(res.error, toastId);
}
- const { presignedUrl, requestId } = res[1];
+ const { presignedUrl, requestId } = res.value;
if (
!presignedUrl ||
@@ -195,11 +195,11 @@ export async function upload(
fileType: options?.fileType,
});
- if (isErr(newfile)) {
- return handleUploadError(newfile[0], toastId);
+ if (newfile.isErr()) {
+ return handleUploadError(newfile.error, toastId);
}
- const [, { metadata, presignedUrl, contentType, fileType }] = newfile;
+ const { metadata, presignedUrl, contentType, fileType } = newfile.value;
const { documentId, documentVersionId } = metadata;
const fallbackMime = fileType
diff --git a/js/app/packages/service-clients/service-storage/util/uploadToPresignedUrl.ts b/js/app/packages/service-clients/service-storage/util/uploadToPresignedUrl.ts
index 83be8ded05..c5150919f0 100644
--- a/js/app/packages/service-clients/service-storage/util/uploadToPresignedUrl.ts
+++ b/js/app/packages/service-clients/service-storage/util/uploadToPresignedUrl.ts
@@ -1,5 +1,7 @@
-import type { MaybeError } from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
+
import { platformFetch } from 'core/util/platformFetch';
+import { err, ok, type Result } from 'neverthrow';
export async function uploadToPresignedUrl({
presignedUrl,
@@ -13,7 +15,7 @@ export async function uploadToPresignedUrl({
sha: string;
type: string;
signal?: AbortSignal;
-}): Promise<MaybeError<'SERVER_ERROR'>> {
+}): Promise<Result<void, ResultError<'SERVER_ERROR'>[]>> {
const blob = new Blob([buffer], { type });
const base64Sha = btoa(
@@ -35,15 +37,8 @@ export async function uploadToPresignedUrl({
if (!response.ok) {
const message = await response.text();
- return [
- [
- {
- code: 'SERVER_ERROR',
- message,
- },
- ],
- ];
+ return err([{ code: 'SERVER_ERROR', message: message }]);
}
- return [null];
+ return ok(undefined);
}
diff --git a/js/app/packages/service-clients/service-storage/util/websocketPromiseChain.ts b/js/app/packages/service-clients/service-storage/util/websocketPromiseChain.ts
index bde7232a30..e7ee11f760 100644
--- a/js/app/packages/service-clients/service-storage/util/websocketPromiseChain.ts
+++ b/js/app/packages/service-clients/service-storage/util/websocketPromiseChain.ts
@@ -1,4 +1,6 @@
-import { isErr, type MaybeError, onlyErr } from '@core/util/maybeResult';
+import type { ResultError } from '@core/util/result';
+
+import { err, ok, type Result } from 'neverthrow';
import { v7 as uuid7 } from 'uuid';
type PromiseHandler = Promise<any> & {
@@ -36,23 +38,25 @@ export function createWebsocketPromiseChain<
const websocketErrorFilter = (
response: any
- ): MaybeError<'INVALID_RESPONSE' | 'SERVICE_ERROR'> => {
+ ): Result<void, ResultError<'INVALID_RESPONSE' | 'SERVICE_ERROR'>[]> => {
if (isJobSubmissionErrorResponse(response)) {
- return onlyErr('SERVICE_ERROR', response.error);
+ return err([{ code: 'SERVICE_ERROR', message: response.error }]);
}
if (!isJobSubmissionSuccessResponse(response)) {
- return onlyErr('INVALID_RESPONSE', 'Invalid response format');
+ return err([
+ { code: 'INVALID_RESPONSE', message: 'Invalid response format' },
+ ]);
}
if (
isDocumentProcessResponse(response.data) &&
isDocumentProcessResponseError(response.data)
) {
- return onlyErr('SERVICE_ERROR', response.data.message);
+ return err([{ code: 'SERVICE_ERROR', message: response.data.message }]);
}
- return [null];
+ return ok(undefined);
};
const createResultPromise = (): PromiseHandler => {
@@ -87,9 +91,9 @@ export function createWebsocketPromiseChain<
if (response?.macroRequestId !== requestId) return;
const errorCheck = websocketErrorFilter(response);
- if (isErr(errorCheck)) {
+ if (errorCheck.isErr()) {
for (const [promise] of promiseHandlerListeners) {
- console.error(errorCheck[1]);
+ console.error(errorCheck.error);
if (!promise.resolved) promise.resolve(undefined);
}
return;
diff --git a/js/app/packages/service-clients/service-stripe/client.ts b/js/app/packages/service-clients/service-stripe/client.ts
index 49f66213d6..ff47ff2768 100644
--- a/js/app/packages/service-clients/service-stripe/client.ts
+++ b/js/app/packages/service-clients/service-stripe/client.ts
@@ -1,4 +1,3 @@
-import { isOk } from '@core/util/maybeResult';
import { registerClient } from '@core/util/mockClient';
import {
authServiceClient,
@@ -70,13 +69,13 @@ export const stripeServiceClient = {
tier,
});
- if (!isOk(result)) {
+ if (!result.isOk()) {
throw new Error(
- result[0]?.[0]?.message ?? 'Failed to create checkout session'
+ result.error?.[0]?.message ?? 'Failed to create checkout session'
);
}
- return result[1];
+ return result.value;
},
/**
* Creates a portal session
@@ -87,18 +86,18 @@ export const stripeServiceClient = {
returnUrl: `${window.location.origin}/app`,
});
- if (!isOk(result)) {
+ if (!result.isOk()) {
throw new Error(
- result[0]?.[0]?.message ?? 'Failed to create portal session'
+ result.error?.[0]?.message ?? 'Failed to create portal session'
);
}
- return result[1];
+ return result.value;
},
/**
* Changes the current user's subscription tier. Returns a narrow discriminated union so
- * callers get a type-checked error `code` without drilling into the MaybeResult tuple
- * shape (`result[0]?.[0]?.code`), which would silently fall through to the default case
+ * callers get a type-checked error `code` without drilling into the Result
+ * error array (`result.error?.[0]?.code`), which would silently fall through to the default case
* if the shape ever changes. Callers should invalidate the user info query on success.
*/
updateSubscriptionTier: async (
@@ -107,12 +106,12 @@ export const stripeServiceClient = {
const result = await authServiceClient.patchSubscriptionTier({
newTier: tier,
});
- if (isOk(result)) return { ok: true };
+ if (result.isOk()) return { ok: true };
// Narrow the first error's code to our known union; anything else (NETWORK_ERROR,
// UNAUTHORIZED, SERVER_ERROR, etc.) collapses to 'UNKNOWN'. `match` + the explicit
// P.union of `PatchSubscriptionTierErrorCode` members means adding a new backend
// code without widening this union is a compile error.
- const code = match(result[0]?.code)
+ const code = match(result.error[0]?.code)
.with(
P.union(
'TIER_UNCHANGED',
diff --git a/js/app/packages/service-clients/service-sync/client.ts b/js/app/packages/service-clients/service-sync/client.ts
index 77514e5947..b0d30b6fa5 100644
--- a/js/app/packages/service-clients/service-sync/client.ts
+++ b/js/app/packages/service-clients/service-sync/client.ts
@@ -4,17 +4,12 @@ import {
type FetchWithTokenErrorCode,
fetchWithToken,
} from '@core/util/fetchWithToken';
-import {
- isErr,
- type MaybeError,
- type MaybeResult,
- type ObjectLike,
- ok,
-} from '@core/util/maybeResult';
import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
+import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { SerializedEditorState } from 'lexical';
+import { err, ok, type Result } from 'neverthrow';
import { InitializeFromSnapshotRequest } from './generated/schema';
const SYNC_SERVICE_WORKER_URL = `${SYNC_SERVICE_HOSTS['worker']}`;
@@ -47,17 +42,17 @@ const cancelIdleTask =
export function syncFetch(
url: string,
init?: SafeFetchInit
-): Promise<MaybeError<FetchWithTokenErrorCode>>;
+): Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>>;
export function syncFetch<T extends ObjectLike>(
url: string,
init?: SafeFetchInit
-): Promise<MaybeResult<FetchWithTokenErrorCode, T>>;
+): Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>;
export function syncFetch<T extends ObjectLike = never>(
url: string,
init?: SafeFetchInit
):
- | Promise<MaybeResult<FetchWithTokenErrorCode, T>>
- | Promise<MaybeError<FetchWithTokenErrorCode>> {
+ | Promise<Result<T, ResultError<FetchWithTokenErrorCode>[]>>
+ | Promise<Result<void, ResultError<FetchWithTokenErrorCode>[]>> {
return fetchWithToken<T>(`${SYNC_SERVICE_WORKER_URL}${url}`, {
...init,
headers: {
@@ -135,8 +130,11 @@ export const syncServiceClient = {
method: 'HEAD',
});
- if (isErr(res)) {
- if (isErr(res, 'NOT_FOUND')) {
+ if (res.isErr()) {
+ if (
+ res.isErr() &&
+ res.error.some((error) => error.code === 'NOT_FOUND')
+ ) {
return ok({ exists: false });
}
return res;
@@ -175,13 +173,11 @@ export const syncServiceClient = {
method: 'GET',
}
);
- if (isErr(response)) {
- if (isErr(response, 'NOT_FOUND')) {
- return response;
- }
+ if (response.isErr()) {
+ return err(response.error);
}
- return ok(response[1] as MetadataResponse);
+ return ok(response.value as MetadataResponse);
},
async getSnapshot(args: { documentId: string }) {
const token = await getPermissionToken('document', args.documentId);
diff --git a/js/app/packages/service-clients/service-sync/source.ts b/js/app/packages/service-clients/service-sync/source.ts
index 24c2a00443..366cd76709 100644
--- a/js/app/packages/service-clients/service-sync/source.ts
+++ b/js/app/packages/service-clients/service-sync/source.ts
@@ -11,7 +11,7 @@ import {
} from '@core/collab/source';
import { SYNC_SERVICE_HOSTS } from '@core/constant/servers';
import { arrayEquals } from '@core/util/compareUtils';
-import { isErr as isChaseError } from '@core/util/maybeResult';
+
import { storageServiceClient } from '@service-storage/client';
import { createEventBus } from '@solid-primitives/event-bus';
import { raceTimeout, until } from '@solid-primitives/promise';
@@ -74,12 +74,12 @@ function createSyncServiceSocket(documentId: string, initialToken: string) {
document_id: documentId,
});
- if (isChaseError(response)) {
+ if (response.isErr()) {
console.error('failed to fetch permission token', response);
return fallbackUrl;
}
- const refreshedUrl = connectUrl(response[1].token);
+ const refreshedUrl = connectUrl(response.value.token);
fallbackUrl = refreshedUrl;
return refreshedUrl;
};
@@ -89,8 +89,8 @@ function createSyncServiceSocket(documentId: string, initialToken: string) {
.withBackoff(new ConstantBackoff(500))
.withMaxRetries(20)
.withHeartbeat({
- interval: 3_000,
- timeout: 2_000,
+ interval: 10_000,
+ timeout: 5_000,
pingMessage: 'ping',
pongMessage: 'pong',
maxMissedHeartbeats: 2,
diff --git a/js/app/packages/service-clients/service-unfurl/client.ts b/js/app/packages/service-clients/service-unfurl/client.ts
index 5467715064..a13fa916b5 100644
--- a/js/app/packages/service-clients/service-unfurl/client.ts
+++ b/js/app/packages/service-clients/service-unfurl/client.ts
@@ -1,6 +1,6 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
-import { mapOk } from '@core/util/maybeResult';
+
import type { GetUnfurlBulkBody } from './generated/schemas/getUnfurlBulkBody';
import type { GetUnfurlBulkResponse } from './generated/schemas/getUnfurlBulkResponse';
import type { GetUnfurlParams } from './generated/schemas/getUnfurlParams';
@@ -12,23 +12,21 @@ export function proxyResource(url: string) {
export const UnfurlServiceClient = {
async unfurl(args: GetUnfurlParams) {
- return mapOk(
+ return (
await fetchWithToken<GetUnfurlResponse>(
`${SERVER_HOSTS['unfurl-service']}/unfurl?url=${args.url}`
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
async unfurlBulk(args: GetUnfurlBulkBody) {
- return mapOk(
+ return (
await fetchWithToken<GetUnfurlBulkResponse>(
`${SERVER_HOSTS['unfurl-service']}/unfurl/bulk`,
{
method: 'POST',
body: JSON.stringify(args),
}
- ),
- (result) => result
- );
+ )
+ ).map((result) => result);
},
};
diff --git a/js/app/packages/tauri/src/PushNotification.tsx b/js/app/packages/tauri/src/PushNotification.tsx
index a74ce23d19..d3082bfbb8 100644
--- a/js/app/packages/tauri/src/PushNotification.tsx
+++ b/js/app/packages/tauri/src/PushNotification.tsx
@@ -1,4 +1,3 @@
-import { isOk } from '@core/util/maybeResult';
import { whenSettled } from '@core/util/whenSettled';
import {
checkPermissions,
@@ -47,7 +46,7 @@ function usePushNotifications(
deviceType,
token,
});
- const result = isOk(res) ? ('granted' as const) : ('denied' as const);
+ const result = res.isOk() ? ('granted' as const) : ('denied' as const);
setPermission(result);
return result;
}
diff --git a/js/app/packages/websocket/solid/socket-effect.ts b/js/app/packages/websocket/solid/socket-effect.ts
index caa4ff2f61..5ab35799c0 100644
--- a/js/app/packages/websocket/solid/socket-effect.ts
+++ b/js/app/packages/websocket/solid/socket-effect.ts
@@ -1,4 +1,4 @@
-import type { ObjectLike } from '@core/util/maybeResult';
+import type { ObjectLike } from '@core/util/result';
import { getOwner, onCleanup } from 'solid-js';
import type { Websocket } from '../core/websocket';
import { WebsocketEvent } from '../core/websocket-event';
diff --git a/js/app/scripts/generate-dcs-tools.ts b/js/app/scripts/generate-dcs-tools.ts
index 65b673d974..2a6feffdc2 100644
--- a/js/app/scripts/generate-dcs-tools.ts
+++ b/js/app/scripts/generate-dcs-tools.ts
@@ -1,3 +1,4 @@
+import { err, ok } from 'neverthrow';
// Usage:
// bun run scripts/generate-dcs-tools.ts
//
@@ -157,7 +158,9 @@ async function generateToolsFile(schema: CombinedSchema) {
const contents = `${warning}
-import { err, type MaybeResult, ok } from 'core/util/maybeResult';
+
+import type { ResultError } from 'core/util/result';
+import { err, ok, type Result } from 'neverthrow';
import * as schemas from './schemas';
import type * as types from './types';
@@ -208,9 +211,9 @@ export type NamedTool<
function deserializeTool<T extends NamedTool>(
tool: NamedRawTool,
direction: 'call' | 'response'
-): MaybeResult<'parse_error' | 'not_found', T> {
+): Result<T, ResultError<'parse_error' | 'not_found'>[]> {
if (!(tool.name in toolParserMap)) {
- return err('not_found', \`tool name not found \${tool.name}\`);
+ return err([{ code: 'not_found', message: \`tool name not found \${tool.name}\` }]);
}
const parser = toolParserMap[tool.name as ToolName];
const maybeToolCall = parser[direction].safeParse(tool.json);
@@ -221,18 +224,18 @@ function deserializeTool<T extends NamedTool>(
data: maybeToolCall.data,
} as T);
}
- return err('parse_error', 'tool parsing failed');
+ return err([{ code: 'parse_error', message: 'tool parsing failed' }]);
}
export function deserializeToolCall(
tool: NamedRawTool
-): MaybeResult<'parse_error' | 'not_found', NamedTool<ToolName, 'call'>> {
+): Result<NamedTool<ToolName, 'call'>, ResultError<'parse_error' | 'not_found'>[]> {
return deserializeTool(tool, 'call');
}
export function deserializeToolResponse(
tool: NamedRawTool
-): MaybeResult<'parse_error' | 'not_found', NamedTool<ToolName, 'response'>> {
+): Result<NamedTool<ToolName, 'response'>, ResultError<'parse_error' | 'not_found'>[]> {
return deserializeTool(tool, 'response');
}
`;