npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sveltebase/utils

v0.4.6

Published

Utility helpers for Svelte 5 apps, with small primitives for cookies, async actions, timestamps, waiting, and toast-friendly error handling.

Readme

@sveltebase/utils

Utility helpers for Svelte 5 apps, with small primitives for cookies, async actions, timestamps, waiting, and toast-friendly error handling.

Install

With Bun:

bun add @sveltebase/utils

If you want toast notifications from createAsync or tryCatch, also install svelte-sonner:

bun add svelte-sonner

svelte is a peer dependency and should already exist in your app.

What’s included

  • Cookies — browser cookie helpers
  • createAsync — wraps async functions with loading and error state
  • tryCatch — run a task with built-in toast/error handling
  • timestamps — generate createdAt / updatedAt values
  • wait — simple promise-based delay helper
  • TryCatchReturn — shared return type for async helpers

Exports

import {
  Cookies,
  createAsync,
  timestamps,
  tryCatch,
  wait,
  type TryCatchReturn
} from "@sveltebase/utils";

Cookies

A small browser-only cookie helper with set, get, and remove.

Example

import { Cookies } from "@sveltebase/utils";

Cookies.set("theme", "dark", {
  path: "/",
  sameSite: "Lax",
  expires: 30
});

const theme = Cookies.get("theme");

Cookies.remove("theme");

API

Cookies.set(name, value, options?)

Sets a cookie.

Options:

  • expires?: number — number of days
  • path?: string
  • domain?: string
  • secure?: boolean
  • sameSite?: "Lax" | "Strict" | "None"
  • partitioned?: boolean

Cookies.get(name)

Returns the cookie value as string | null.

Cookies.remove(name, options?)

Removes a cookie by setting an expired value.


createAsync

Wraps an async function and gives you:

  • loading state
  • last thrown error
  • optional success/error toasts

Your async function can return:

  • { success: string }
  • { error: string }
  • null
  • void

Example

import { createAsync } from "@sveltebase/utils";

const saveProfile = createAsync(async (name: string) => {
  const response = await fetch("/api/profile", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ name })
  });

  if (!response.ok) {
    return { error: "Failed to save profile" };
  }

  return { success: "Profile saved" };
});

await saveProfile.run("Ahror");

console.log(saveProfile.isLoading());
console.log(saveProfile.error);

Keyed loading states

Use runWithKey when you want separate loading states for multiple actions.

import { createAsync } from "@sveltebase/utils";

const removeItem = createAsync(async (id: string) => {
  const response = await fetch(`/api/items/${id}`, {
    method: "DELETE"
  });

  if (!response.ok) {
    return { error: "Delete failed" };
  }

  return { success: "Item removed" };
});

await removeItem.runWithKey("item-42", "42");

const isDeleting = removeItem.isLoading("item-42");

API

const task = createAsync(asyncFn);

task.run(...args);
task.runWithKey(key, ...args);
task.isLoading(key?);
task.error;

Notes

  • Toasts are shown with svelte-sonner when available in the browser.
  • In development, thrown errors are also logged to the console.
  • On the server, toast behavior is skipped safely.

tryCatch

Runs a task and handles success/error messages in a consistent way.

Example

import { tryCatch } from "@sveltebase/utils";

await tryCatch(async () => {
  const response = await fetch("/api/invite", { method: "POST" });

  if (!response.ok) {
    return { error: "Could not send invite" };
  }

  return { success: "Invite sent" };
});

Throwing errors

import { tryCatch } from "@sveltebase/utils";

await tryCatch(async () => {
  const response = await fetch("/api/private");

  if (response.status === 401) {
    throw new Error("Unauthorized");
  }

  return { success: "Loaded" };
});

timestamps

Creates timestamp objects using Date.now().

Example

import { timestamps } from "@sveltebase/utils";

const created = timestamps(false);
// { createdAt: 1712345678901, updatedAt: 1712345678901 }

const updated = timestamps(true);
// { updatedAt: 1712345678901 }

Common usage

import { timestamps } from "@sveltebase/utils";

const post = {
  id: crypto.randomUUID(),
  title: "Hello",
  ...timestamps(false)
};

wait

Returns a promise that resolves after the given number of milliseconds.

Example

import { wait } from "@sveltebase/utils";

await wait(500);
console.log("Done");

Useful for:

  • delaying UI transitions
  • retry flows
  • testing async behavior

TryCatchReturn

A shared type for functions used with createAsync and tryCatch.

import type { TryCatchReturn } from "@sveltebase/utils";

async function submitForm(): Promise<TryCatchReturn> {
  return { success: "Submitted" };
}

Possible values:

type TryCatchReturn =
  | { success: string; error?: never }
  | { error: string; success?: never }
  | null
  | void;

Svelte example

<script lang="ts">
  import { createAsync } from "@sveltebase/utils";

  let name = $state("");

  const save = createAsync(async (value: string) => {
    const response = await fetch("/api/profile", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ name: value })
    });

    if (!response.ok) {
      return { error: "Could not save profile" };
    }

    return { success: "Profile saved" };
  });
</script>

<input bind:value={name} placeholder="Your name" />

<button onclick={() => save.run(name)} disabled={save.isLoading()}>
  {save.isLoading() ? "Saving..." : "Save"}
</button>

{#if save.error}
  <p>{save.error.message}</p>
{/if}

Notes

  • Cookies works only in the browser.
  • createAsync and tryCatch integrate with svelte-sonner if it is installed.
  • The package is designed for Svelte 5 projects.

License

ISC