Function bodies 43 total
SidebarState class · typescript · L23-L58 (36 LOC)src/lib/components/ui/sidebar/context.svelte.ts
class SidebarState {
readonly props: SidebarStateProps;
open = $derived.by(() => this.props.open());
openMobile = $state(false);
setOpen: SidebarStateProps['setOpen'];
#isMobile: IsMobile;
state = $derived.by(() => (this.open ? 'expanded' : 'collapsed'));
constructor(props: SidebarStateProps) {
this.setOpen = props.setOpen;
this.#isMobile = new IsMobile();
this.props = props;
}
// Convenience getter for checking if the sidebar is mobile
// without this, we would need to use `sidebar.isMobile.current` everywhere
get isMobile() {
return this.#isMobile.current;
}
// Event handler to apply to the `<svelte:window>`
handleShortcutKeydown = (e: KeyboardEvent) => {
if (e.key === SIDEBAR_KEYBOARD_SHORTCUT && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
this.toggle();
}
};
setOpenMobile = (value: boolean) => {
this.openMobile = value;
};
toggle = () => {
return this.#isMobile.current ? (this.openMobile = !this.openMobile) : this.setOpen(!this.open)constructor method · typescript · L31-L35 (5 LOC)src/lib/components/ui/sidebar/context.svelte.ts
constructor(props: SidebarStateProps) {
this.setOpen = props.setOpen;
this.#isMobile = new IsMobile();
this.props = props;
}setSidebar function · typescript · L68-L70 (3 LOC)src/lib/components/ui/sidebar/context.svelte.ts
export function setSidebar(props: SidebarStateProps): SidebarState {
return setContext(Symbol.for(SYMBOL_KEY), new SidebarState(props));
}useSidebar function · typescript · L77-L79 (3 LOC)src/lib/components/ui/sidebar/context.svelte.ts
export function useSidebar(): SidebarState {
return getContext(Symbol.for(SYMBOL_KEY));
}IsMobile class · typescript · L5-L9 (5 LOC)src/lib/hooks/is-mobile.svelte.ts
export class IsMobile extends MediaQuery {
constructor(breakpoint: number = DEFAULT_MOBILE_BREAKPOINT) {
super(`max-width: ${breakpoint - 1}px`);
}
}constructor method · typescript · L6-L8 (3 LOC)src/lib/hooks/is-mobile.svelte.ts
constructor(breakpoint: number = DEFAULT_MOBILE_BREAKPOINT) {
super(`max-width: ${breakpoint - 1}px`);
}logActivity function · typescript · L5-L25 (21 LOC)src/lib/server/activity.ts
export async function logActivity(params: {
organizationId: string;
clientId?: string | null;
entityType: EntityType;
entityId: string;
action: ActivityAction;
description: string;
performedById: string;
metadata?: Record<string, unknown>;
}) {
await db.insert(activity).values({
organizationId: params.organizationId,
clientId: params.clientId ?? null,
entityType: params.entityType,
entityId: params.entityId,
action: params.action,
description: params.description,
performedById: params.performedById,
metadata: params.metadata ?? null
});
}Repobility (the analyzer behind this table) · https://repobility.com
createResendSender function · typescript · L21-L33 (13 LOC)src/lib/server/email.ts
function createResendSender(): SendFn {
return async (message) => {
const { Resend } = await import('resend');
const resend = new Resend(RESEND_API_KEY);
await resend.emails.send({
from: EMAIL_FROM,
to: message.to,
subject: message.subject,
html: message.html,
text: message.text
});
};
}createSendGridSender function · typescript · L35-L47 (13 LOC)src/lib/server/email.ts
function createSendGridSender(): SendFn {
return async (message) => {
const sgMail = await import('@sendgrid/mail');
sgMail.default.setApiKey(SENDGRID_API_KEY);
await sgMail.default.send({
from: EMAIL_FROM,
to: message.to,
subject: message.subject,
html: message.html,
text: message.text
});
};
}createSmtpSender function · typescript · L49-L65 (17 LOC)src/lib/server/email.ts
function createSmtpSender(): SendFn {
return async (message) => {
const nodemailer = await import('nodemailer');
const transport = nodemailer.default.createTransport({
host: SMTP_HOST,
port: Number(SMTP_PORT) || 587,
auth: { user: SMTP_USER, pass: SMTP_PASS }
});
await transport.sendMail({
from: EMAIL_FROM,
to: message.to,
subject: message.subject,
html: message.html,
text: message.text
});
};
}createConsoleSender function · typescript · L67-L73 (7 LOC)src/lib/server/email.ts
function createConsoleSender(): SendFn {
return async (message) => {
console.log(`[DEV EMAIL] To: ${message.to}`);
console.log(`[DEV EMAIL] Subject: ${message.subject}`);
console.log(`[DEV EMAIL] Body: ${message.text ?? message.html}`);
};
}getSender function · typescript · L75-L86 (12 LOC)src/lib/server/email.ts
function getSender(): SendFn {
switch (EMAIL_PROVIDER) {
case 'resend':
return createResendSender();
case 'sendgrid':
return createSendGridSender();
case 'smtp':
return createSmtpSender();
default:
return createConsoleSender();
}
}sendEmail function · typescript · L90-L96 (7 LOC)src/lib/server/email.ts
export async function sendEmail(message: EmailMessage): Promise<void> {
try {
await sender(message);
} catch (error) {
console.error('[EMAIL] Failed to send:', error);
}
}sanitizeFileName function · typescript · L7-L10 (4 LOC)src/lib/server/files.ts
function sanitizeFileName(fileName: string): string {
const baseName = basename(fileName).replace(/[^\w.-]/g, '_');
return baseName || 'upload';
}isWithinUploadDir function · typescript · L12-L15 (4 LOC)src/lib/server/files.ts
function isWithinUploadDir(filePath: string): boolean {
const relativePath = relative(UPLOAD_DIR, resolve(filePath));
return relativePath === '' || (!relativePath.startsWith('..') && !isAbsolute(relativePath));
}Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
saveUploadedFile function · typescript · L17-L20 (4 LOC)src/lib/server/files.ts
export async function saveUploadedFile(
orgId: string,
file: File
): Promise<{ storagePath: string; fileName: string; mimeType: string; size: number }> {deleteFile function · typescript · L40-L51 (12 LOC)src/lib/server/files.ts
export async function deleteFile(storagePath: string): Promise<void> {
if (!isWithinUploadDir(storagePath)) {
console.error('[FILES] Refusing to delete file outside upload directory:', storagePath);
return;
}
try {
await unlink(resolve(storagePath));
} catch {
// File may already be deleted
}
}normalizeOrganizationSlug function · typescript · L9-L16 (8 LOC)src/lib/server/organization.ts
export function normalizeOrganizationSlug(input: string): string {
return input
.trim()
.toLowerCase()
.replace(/['’]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}getOrganizationAccessContext function · typescript · L18-L24 (7 LOC)src/lib/server/organization.ts
export async function getOrganizationAccessContext(
requestHeaders: Headers,
session: Session['session'] | null
): Promise<{
activeOrganizationId: string | null;
organizations: ListedOrganization[];
}> {claimOrphanOrganizationForUser function · typescript · L60-L111 (52 LOC)src/lib/server/organization.ts
export async function claimOrphanOrganizationForUser(slug: string, userId: string) {
return db.transaction(async (tx) => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${`claim-org:${slug}`}))`);
const [existingOrganization] = await tx
.select({
id: organization.id,
name: organization.name,
slug: organization.slug,
logo: organization.logo,
createdAt: organization.createdAt,
metadata: organization.metadata
})
.from(organization)
.where(eq(organization.slug, slug))
.limit(1);
if (!existingOrganization) {
return null;
}
const [existingUserMembership] = await tx
.select({ id: member.id })
.from(member)
.where(and(eq(member.organizationId, existingOrganization.id), eq(member.userId, userId)))
.limit(1);
if (existingUserMembership) {
return existingOrganization;
}
const [existingMember] = await tx
.select({ id: member.id })
.from(member)
.where(eq(member.organizationId, existingOrganization.resolveOrgMemberUserId function · typescript · L113-L127 (15 LOC)src/lib/server/organization.ts
export async function resolveOrgMemberUserId(
orgId: string,
requestedUserId: string | null | undefined
): Promise<string | null> {
const userId = requestedUserId?.trim();
if (!userId) return null;
const [orgMember] = await db
.select({ userId: member.userId })
.from(member)
.where(and(eq(member.organizationId, orgId), eq(member.userId, userId)))
.limit(1);
return orgMember?.userId ?? null;
}filterVisibleTagIds function · typescript · L129-L142 (14 LOC)src/lib/server/organization.ts
export async function filterVisibleTagIds(
orgId: string,
requestedTagIds: string[]
): Promise<string[]> {
const tagIds = Array.from(new Set(requestedTagIds.map((id) => id.trim()).filter(Boolean)));
if (tagIds.length === 0) return [];
const visibleTags = await db
.select({ id: tag.id })
.from(tag)
.where(and(inArray(tag.id, tagIds), or(eq(tag.organizationId, orgId), eq(tag.isSystem, true))));
return visibleTags.map(({ id }) => id);
}seedSystemTags function · typescript · L9-L38 (30 LOC)src/lib/server/seed-tags.ts
export async function seedSystemTags() {
if (seeded) return;
if (seedingPromise) {
await seedingPromise;
return;
}
seedingPromise = (async () => {
const existing = await db.select({ name: tag.name }).from(tag).where(eq(tag.isSystem, true));
const existingNames = new Set(existing.map((t) => t.name));
const missing = SYSTEM_TAGS.filter((name) => !existingNames.has(name));
if (missing.length > 0) {
await db
.insert(tag)
.values(missing.map((name) => ({ name, isSystem: true, organizationId: null })));
}
seeded = true;
})();
try {
await seedingPromise;
} catch (error) {
seedingPromise = null;
throw error;
}
seedingPromise = null;
}All rows above produced by Repobility · https://repobility.com
formatDate function · typescript · L5-L9 (5 LOC)src/lib/utils/format.ts
export function formatDate(d: string | Date | null | undefined): string {
if (!d) return '\u2014';
const date = typeof d === 'string' ? new Date(d) : d;
return date.toLocaleDateString('en-ZA', { year: 'numeric', month: 'short', day: 'numeric' });
}currentGreeting function · typescript · L11-L16 (6 LOC)src/lib/utils/format.ts
export function currentGreeting(now: Date = new Date()): string {
const hour = now.getHours();
if (hour < 12) return 'Good morning';
if (hour < 17) return 'Good afternoon';
return 'Good evening';
}daysUntilDate function · typescript · L18-L30 (13 LOC)src/lib/utils/format.ts
export function daysUntilDate(d: string | Date | null | undefined): number {
if (!d) return Infinity;
const endDate = typeof d === 'string' ? new Date(d) : new Date(d.getTime());
if (isNaN(endDate.getTime())) return Infinity;
endDate.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(0, 0, 0, 0);
return Math.ceil((endDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
}isOverdueDate function · typescript · L32-L37 (6 LOC)src/lib/utils/format.ts
export function isOverdueDate(d: string | Date | null | undefined, status?: string): boolean {
if (!d || status === 'done') return false;
const dueTime = typeof d === 'string' ? Date.parse(d) : d.getTime();
return !Number.isNaN(dueTime) && dueTime < Date.now();
}formatCurrency function · typescript · L39-L44 (6 LOC)src/lib/utils/format.ts
export function formatCurrency(v: string | number | null | undefined): string {
if (v == null || v === '') return '\u2014';
const num = typeof v === 'string' ? parseFloat(v) : v;
if (isNaN(num)) return '\u2014';
return new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(num);
}timeAgo function · typescript · L46-L58 (13 LOC)src/lib/utils/format.ts
export function timeAgo(d: string | Date | null | undefined): string {
if (!d) return '';
const date = typeof d === 'string' ? new Date(d) : d;
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
if (seconds < 60) return 'just now';
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days < 30) return `${days}d ago`;
return formatDate(d);
}formatFileSize function · typescript · L60-L64 (5 LOC)src/lib/utils/format.ts
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1048576).toFixed(1)} MB`;
}policyTypeLabel function · typescript · L66-L76 (11 LOC)src/lib/utils/format.ts
export function policyTypeLabel(t: string): string {
const labels: Record<string, string> = {
motor: 'Motor',
property: 'Property',
liability: 'Liability',
commercial: 'Commercial',
life: 'Life',
other: 'Other'
};
return labels[t] ?? t;
}Same scanner, your repo: https://repobility.com — Repobility
claimStatusVariant function · typescript · L78-L87 (10 LOC)src/lib/utils/format.ts
export function claimStatusVariant(s: string): 'default' | 'secondary' | 'destructive' | 'outline' {
const map: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
open: 'default',
in_progress: 'default',
settled: 'secondary',
rejected: 'destructive',
closed: 'outline'
};
return map[s] ?? 'outline';
}claimStatusLabel function · typescript · L89-L98 (10 LOC)src/lib/utils/format.ts
export function claimStatusLabel(s: string): string {
const labels: Record<string, string> = {
open: 'Open',
in_progress: 'In Progress',
settled: 'Settled',
rejected: 'Rejected',
closed: 'Closed'
};
return labels[s] ?? s;
}policyStatusVariant function · typescript · L100-L110 (11 LOC)src/lib/utils/format.ts
export function policyStatusVariant(
s: string
): 'default' | 'secondary' | 'destructive' | 'outline' {
const map: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
active: 'default',
pending: 'outline',
lapsed: 'destructive',
cancelled: 'secondary'
};
return map[s] ?? 'outline';
}policyStatusLabel function · typescript · L112-L120 (9 LOC)src/lib/utils/format.ts
export function policyStatusLabel(s: string): string {
const labels: Record<string, string> = {
active: 'Active',
pending: 'Pending',
lapsed: 'Lapsed',
cancelled: 'Cancelled'
};
return labels[s] ?? s;
}buildRelativeUrl function · typescript · L1-L19 (19 LOC)src/lib/utils/query.ts
export function buildRelativeUrl(
pathname: string,
search: string,
updates: Record<string, string | null | undefined>
): string {
const params = new URLSearchParams(search);
for (const [key, value] of Object.entries(updates)) {
if (!value) {
params.delete(key);
continue;
}
params.set(key, value);
}
const query = params.toString();
return query ? `${pathname}?${query}` : pathname;
}cn function · typescript · L4-L6 (3 LOC)src/lib/utils.ts
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}isOneOf function · typescript · L8-L13 (6 LOC)src/lib/utils.ts
export function isOneOf<T extends readonly string[]>(
value: string,
allowed: T
): value is T[number] {
return allowed.includes(value as T[number]);
}findClientPolicy function · typescript · L26-L35 (10 LOC)src/routes/(app)/clients/[id]/+page.server.ts
async function findClientPolicy(orgId: string, clientId: string, policyId: string) {
const [existingPolicy] = await db
.select()
.from(policy)
.where(
and(eq(policy.id, policyId), eq(policy.clientId, clientId), eq(policy.organizationId, orgId))
);
return existingPolicy;
}Repobility (the analyzer behind this table) · https://repobility.com
findClientClaim function · typescript · L37-L46 (10 LOC)src/routes/(app)/clients/[id]/+page.server.ts
async function findClientClaim(orgId: string, clientId: string, claimId: string) {
const [existingClaim] = await db
.select()
.from(claim)
.where(
and(eq(claim.id, claimId), eq(claim.clientId, clientId), eq(claim.organizationId, orgId))
);
return existingClaim;
}findClientNote function · typescript · L48-L55 (8 LOC)src/routes/(app)/clients/[id]/+page.server.ts
async function findClientNote(orgId: string, clientId: string, noteId: string) {
const [existingNote] = await db
.select()
.from(note)
.where(and(eq(note.id, noteId), eq(note.clientId, clientId), eq(note.organizationId, orgId)));
return existingNote;
}findClientDocument function · typescript · L57-L70 (14 LOC)src/routes/(app)/clients/[id]/+page.server.ts
async function findClientDocument(orgId: string, clientId: string, documentId: string) {
const [existingDocument] = await db
.select()
.from(document)
.where(
and(
eq(document.id, documentId),
eq(document.clientId, clientId),
eq(document.organizationId, orgId)
)
);
return existingDocument;
}getAuthErrorMessage function · typescript · L12-L30 (19 LOC)src/routes/(app)/settings/organization/+page.server.ts
function getAuthErrorMessage(error: unknown): string {
if (
typeof error === 'object' &&
error &&
'body' in error &&
typeof error.body === 'object' &&
error.body &&
'message' in error.body &&
typeof error.body.message === 'string'
) {
return error.body.message;
}
if (error instanceof Error && error.message) {
return error.message;
}
return 'Something went wrong while updating the organization.';
}