Search

Results include substring matches and semantically similar vals. Learn more
maxm avatar
greenBat
@maxm
An interactive, runnable TypeScript val by maxm
Script
const ret = await build({
dependencies: {
"@aws-sdk/client-dynamodb": "^3.587.0",
source: `
/* @jsx h */
export * as ddb from "@aws-sdk/client-dynamodb";
// for types checking and LSP completion
const ddb = await import(ret.url);
vlad avatar
serverlessMatrixEchoBot
@vlad
A example Serverless Bot for Matrix chat. See https://vlad.roam.garden/How-to-create-a-serverless-Matrix-Chat-bot for a more detailed write-up on how to set one up! To test this bot: invite serverless-echo@matrix.org to your unencrypted room Send a message starting with !echo and the bot will repeat content after. Use https://matrix-serverless.netlify.app/ to configure Matrix to call the endpoint on newly received messages
Express
text.slice(echoText.length),
// This is important - if you don't return this JSON -
// Matrix won't consider notification as processed and will keep sending you the same one
return res.json({ rejected: [] });
stevekrouse avatar
upgradeHTTPPreviewVals
@stevekrouse
Auto-Upgrade for HTTP Preview This val is experimentally testing if we can use an LLM to determine if an old-style HTTP val needs to be upgraded for the new HTTP runtime, currently in preview. You can read more about the breaking change and upgrade proccess here: https://blog.val.town/blog/http-preview/#breaking-changes In some light testing, it seems like ChatGPT 3.5 and 4o both are bad at this task, so I'm pausing experimenting with this for now. Example output from 4o: [ { "name": "harlequinChickadee", "probabilityUpgradeNeeded": true, "reason": "The current code structure has several functions and program logic outside the main handler, including word selection, game state management, and SVG generation. These parts would not re-run with the new runtime, potentially affecting functionality. They need to be moved inside the handler to ensure consistent behavior across requests." }, { "name": "redElephant", "probabilityUpgradeNeeded": "100%", "reason": "The initialization of `fs` and `vscode` objects should occur \n inside the handler in the new runtime in order to ensure that they are \n freshly created for each request. This is critical since the new runtime \n does not rerun code outside of the handler for each request.." }, { "name": "untitled_indigoNightingale", "probabilityUpgradeNeeded": false, "reason": "The code initializes and configures the Hono app outside of the handler, but it does not appear to have any stateful logic that would need to be re-calculated with each request. Each request will call the handler provided by Hono and should behave the same in the new runtime." }, { "name": "untitled_pinkRoundworm", "probabilityUpgradeNeeded": true, "reason": "The functions `addComment` and `getComments` as well as the initialization \nof the KEY variable perform actions that are intended to be run per request. These need to be moved \ninside the relevant HTTP handler to ensure the behavior remains consistent in the new runtime." }, { "name": "untitled_harlequinIguana", "probabilityUpgradeNeeded": false, "reason": "The provided code defines the handler directly without any side effects or additional code outside the handler. The behavior should remain the same in the new runtime." }, { "name": "untitled_moccasinHeron", "probabilityUpgradeNeeded": false, "reason": "The code outside the handler is just a constant string declaration, which does not change behavior between requests. The handler itself handles requests correctly and independently." }, { "name": "untitled_maroonSwallow", "probabilityUpgradeNeeded": false, "reason": "All the code, including the check for authentication,\n is inside the handler function. This means the behavior will stay \n the same with the new runtime." }, { "name": "wikiOG", "probabilityUpgradeNeeded": true, "reason": "The function `getWikipediaInfo` defined outside of the handler makes network requests and processes data for each request. In the new runtime, this function would only be executed once and cached. To ensure the same behavior in the new runtime, this function should be moved into the handler." }, { "name": "parsePostBodyExample", "probabilityUpgradeNeeded": false, "reason": "All the code is inside the handler, so the behavior will remain consistent in the new runtime." }, { "name": "discordEventReceiver", "probabilityUpgradeNeeded": false, "reason": "All the relevant code for handling requests and logging input is inside the handler.\n No code needs to be moved for the new runtime to function correctly." } ] Feel free to fork this and try it yourself! If you could get it working, it'd be a big help for us as we upgrade the thousands of HTTP vals. Future ideas: Better LLM (Claude 3.5) Better prompt More examples JSON mode having it reply with upgraded code send pull requests to users with public vals that probably need upgrading
Script
ason": "The current code structure has several functions and program logic outside the main handler, including word selection
eason": "The initialization of `fs` and `vscode` objects should occur \n inside the handler in the new runtime in order to
"reason": "The code initializes and configures the Hono app outside of the handler, but it does not appear to have any st
m actions that are intended to be run per request. These need to be moved \ninside the relevant HTTP handler to ensure the be
not any of the other code in val. This means that if any code outside of handler needs
inside the handler.
content: `import { BrowserWebSocketClientAdapter } from "npm:@automerge/automerge-repo-network-websocket";
const repo = new Repo({ network: [new BrowserWebSocketClientAdapter("wss://sync.automerge.org")] });
reason: `The only code outside of the handler is initializing a wasm module,
best practice to initialize wasm outside of the handler so it's cached between requests.`,
ifavo avatar
vechain_sdk_blocks_best_script
@ifavo
The ThorClient is responsible for communicating with the Vechain network, it is passed a HTTP Client that will handle the requests.
HTTP (deprecated)
The ThorClient is responsible for communicating with the Vechain network, it is passed a HTTP Client that will handle the req
import { HttpClient, ThorClient } from "npm:@vechain/sdk-network";
const thorClient = new ThorClient(new HttpClient("https://mainnet.vechain.org"));
const bestBlock = await thorClient.blocks.getBestBlockCompressed();
console.log("Best Block:", bestBlock.number);
const finalBlock = await thorClient.blocks.getFinalBlockCompressed();
console.log("Final Block:", finalBlock.number);
const genesisBlock = await thorClient.blocks.getBlockCompressed(0);
console.log("Genesis Block Id:", genesisBlock.id);
rlesser avatar
getNextSSR
@rlesser
getNextSSR - fetch data from Next.js SSR-based sites Many modern websites use Next.js and Server-side Rendering (SSR) to serve their website and the data to populate it. Instead of standard API calls, this manifests in the browser as calls routed through dynamic endpoints. This val handles the url construction and response parsing, giving you access to the endpoint and data. Input websiteUrl - The website's url, like google.com or val.town let getNextSSR: (websiteUrl: string) => Promise<(endpoint: string) => Promise<Record<string, any>>> Returns fetching function - A function that takes in an endpoint and returns the endpoint's response data: Input endpoint - The endpoint string, like results.json or trending.json?page=2 Returns data - The endpoint response data, without NextJS artifacts. Example const fetch = await @rlesser.getNextSSR("example.com"); const data = fetch("results.json"); return data;
Script
# getNextSSR - fetch data from Next.js SSR-based sites
Many modern websites use Next.js and Server-side Rendering (SSR) to serve their website and the data to populate it. Instead
This val handles the url construction and response parsing, giving you access to the endpoint and data.
janpaul123 avatar
blogPostEmbeddingsDimensionalityReduction
@janpaul123
An interactive, runnable TypeScript val by janpaul123
Script
import { decode as base64Decode, encode as base64Encode } from "https://deno.land/std@0.166.0/encoding/base64.ts";
import { createClient } from "https://esm.sh/@libsql/client@0.6.0/web";
import { sqlToJSON } from "https://esm.town/v/nbbaier/sqliteExportHelpers?v=22";
import { db as allValsDb } from "https://esm.town/v/sqlite/db?v=9";
zarutian avatar
rpc
@zarutian
RPC Turn any function into an API! This lets you call a function in Val Town without manually handling a Request or Response object. This val can be used as a replacement for the Run API, which implicitly did something similar. Create an API from your function: This is how you can expose a function as an API: Create an HTTP handler val Import this val Call rpc with your function as an argument Here's an example from @std/rpc_example: import { rpc } from "https://esm.town/v/std/rpc?v=6"; export const rpc_example = rpc(async (a: number, b: number) => { return a + b; }); And here is how you do it for one of your already existing private val, say floobie, import { rpc } from "https://esm.town/v/std/rpc?v=6"; import { floobie } from "https://esm.town/v/stevekrouse/floobie"; export const rpced_floobie = rpc(floobie, true); Send a request to your val You can invoke that function from your client or your local machine with an HTTP request. You can either use a GET or a POST request, passing arguments in the query parameters or the body respectively. Make sure your val's privacy is set to Unlisted or Public. GET request const res = await fetch("https://std-rpc_example.web.val.run/?args=[2,3]"); console.log(await res.json()); // 5 POST request const res = await fetch("https://std-rpc_example.web.val.run/", { method: "POST", body: JSON.stringify({ args: [2, 3] }) }); console.log(await res.json()); // 5
Script
## Send a request to your val
You can invoke that function from your client or your local machine with an HTTP request. You can either use a GET or a POST
**GET request**
robsimmons avatar
aoc_2023_13
@robsimmons
An interactive, runnable TypeScript val by robsimmons
Script
import { Dusa } from "https://unpkg.com/dusa@0.0.10/lib/client.js";
const INPUT = `
.trim()
stevekrouse avatar
sqlite
@stevekrouse
LLM-Safe Fork of @std/sqlite We found that LLMs have trouble with the inputs and outputs of our @std/sqlite method. It expects the input to be (sql: string, args: any[]) but it's { sql: string, args: any[] } It expects the output to be objects, but they are arrays Instead of struggling to teach it, we built this val to be a wrapper around @std/sqlite that adheres to what the LLMs expect. This val is also backwards-compatible with @std/sqlite, so we're considering merging it in.
Script
Instead of struggling to teach it, we built this val to be a wrapper around @std/sqlite that adheres to what the LLMs expect.
This val is also backwards-compatible with @std/sqlite, so we're considering merging it in.
import { API_URL } from "https://esm.town/v/std/API_URL";
import { LibsqlError, type ResultSet, type Row, type TransactionMode } from "npm:@libsql/client";
import { z } from "npm:zod";
// adapted from
// https://github.com/tursodatabase/libsql-client-ts/blob/17dd996b840c950dd22b871adfe4ba0eb4a5ead3/packages/libsql-client/src
function rowFromSql(
hurricanenate avatar
webscrapeBareBonesTiki
@hurricanenate
Check Bare Bones Tiki to see when their sea light swizzles become available.
Cron
const document = new DOMParser().parseFromString(html, "text/html");
// Grab every .grid-title, because the products listed on the page have
// identical classes, they're only differentiated by the text inside
const nodeList: NodeListOf<HTMLElement> = document.querySelectorAll(".grid-title");
// Find the title that matches the product we're interested in
tomas_padrieza avatar
reactEmailTemplate
@tomas_padrieza
Simple demo of a React Email rendering
Script
Simple demo of a React Email rendering
import { Button, Tailwind } from "npm:@react-email/components";
import { Html } from "npm:@react-email/html";
import { render } from "npm:@react-email/render";
import * as React from "npm:react";
import { sendMail } from "https://esm.town/v/tomas_padrieza/sendEmail";
petermillspaugh avatar
spacedRepetition
@petermillspaugh
@jsxImportSource https://esm.sh/react
Script
/** @jsxImportSource https://esm.sh/react */
import { generateLessonHtml } from "https://esm.town/v/petermillspaugh/lessonTemplate";
import { renderToString } from "npm:react-dom/server";
const TITLE = "Spaced repetition";
// TODO: better prompt?
canpolat avatar
getLemmyJwt
@canpolat
An interactive, runnable TypeScript val by canpolat
Script
password: string;
//const { LemmyHttp } = await import("npm:lemmy-js-client");
const { LemmyHttp } = await import("npm:lemmy-js-client@0.18.1");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
try {
const ret = await client.login({
username_or_email: username,
saolsen avatar
qstash
@saolsen
Upstash qstash client for vals. Lets you publish and receive qstash messages in vals. To use, set up qstash on Upstash and set the environment variables. QSTASH_TOKEN QSTASH_CURRENT_SIGNING_KEY QSTASH_NEXT_SIGNING_KEY Calls are also traced via https://www.val.town/v/saolsen/tracing so if you use that library you will see linked spans between the publish call and the receive call. For an example of how to use it see https://www.val.town/v/saolsen/try_qstash_publish and https://www.val.town/v/saolsen/try_qstash_receive.
Script
# Upstash qstash client for vals.
Lets you publish and receive qstash messages in vals.
} from "https://cdn.skypack.dev/@opentelemetry/api";
import { Client, Receiver } from "npm:@upstash/qstash";
import { get_tracer, traced } from "https://esm.town/v/saolsen/tracing?v=136";
const client = new Client({
token: Deno.env.get("QSTASH_TOKEN")!,
propagation.inject(context.active(), prop_output);
const result = await client.publishJSON({
body,
josephscott avatar
ulid
@josephscott
// From https://github.com/skeeto/ulid-js/blob/master/ulid.js
Script
if (now === last) {
/* 80-bit overflow is so incredibly unlikely that it's not
* considered as a possiblity here.
for (let i = 9; i >= 0; i--) if (rand[i]++ < 255) break;
} else {