Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=function&page=1124&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 17970 results for "function"(1683ms)

InvocationTracker_Testmain.tsx2 matches

@rozek•Updated 3 months ago
2import { InvocationTracker } from 'https://esm.town/v/rozek/InvocationTracker'
3
4export default async function () {
5 const TestCases = [
6 /**** test constructor with valid inputs ****/
154/**** removeTable ****/
155
156 async function removeTable (TableName:string):Promise<void> {
157 console.log('(cleaning up)')
158 await sqlite.execute(

mightyAmberTakinmain.tsx10 matches

@aashish•Updated 3 months ago
24);
25
26function Hero({
27 prompt,
28 setPrompt,
45
46 <p className="text-[#bababa] text-center max-w-[25ch] mx-auto my-4 font-dm-sans">
47 Turn your ideas into fully functional apps in{" "}
48 <span className="relative w-fit text-fuchsia-400 z-10 italic font-semibold rounded-full">
49 less than a second
116}
117
118function App() {
119 const previewRef = React.useRef<HTMLDivElement>(null);
120 const [prompt, setPrompt] = useState("");
170 });
171
172 function handleStarterPromptClick(promptItem: typeof prompts[number]) {
173 setLoading(true);
174 setTimeout(() => handleSubmit(promptItem.prompt), 0);
175 }
176
177 async function handleSubmit(e: React.FormEvent | string) {
178 if (typeof e !== "string") {
179 e.preventDefault();
226 }
227
228 function handleVersionChange(direction: "back" | "forward") {
229 const { currentVersionIndex, versions } = versionHistory;
230 if (direction === "back" && currentVersionIndex > 0) {
974);
975
976function client() {
977 const path = window.location.pathname;
978 const root = createRoot(document.getElementById("root")!);
1010}
1011
1012function extractCodeFromFence(text: string): string {
1013 const htmlMatch = text.match(/```html\n([\s\S]*?)\n```/);
1014 return htmlMatch ? htmlMatch[1].trim() : text;
1015}
1016
1017async function generateCode(prompt: string, currentCode: string) {
1018 const starterPrompt = STARTER_PROMPTS.find(p => p.prompt === prompt);
1019 if (starterPrompt) {
1059}
1060
1061export default async function server(req: Request): Promise<Response> {
1062 // Dynamic import for SQLite to avoid client-side import
1063 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");

moralCoffeeSkinkmain.tsx10 matches

@aashish•Updated 3 months ago
24);
25
26function Hero({
27 prompt,
28 setPrompt,
45
46 <p className="text-[#bababa] text-center max-w-[25ch] mx-auto my-4 font-dm-sans">
47 Turn your ideas into fully functional apps in{" "}
48 <span className="relative w-fit text-fuchsia-400 z-10 italic font-semibold rounded-full">
49 less than a second
116}
117
118function App() {
119 const previewRef = React.useRef<HTMLDivElement>(null);
120 const [prompt, setPrompt] = useState("");
170 });
171
172 function handleStarterPromptClick(promptItem: typeof prompts[number]) {
173 setLoading(true);
174 setTimeout(() => handleSubmit(promptItem.prompt), 0);
175 }
176
177 async function handleSubmit(e: React.FormEvent | string) {
178 if (typeof e !== "string") {
179 e.preventDefault();
226 }
227
228 function handleVersionChange(direction: "back" | "forward") {
229 const { currentVersionIndex, versions } = versionHistory;
230 if (direction === "back" && currentVersionIndex > 0) {
974);
975
976function client() {
977 const path = window.location.pathname;
978 const root = createRoot(document.getElementById("root")!);
1010}
1011
1012function extractCodeFromFence(text: string): string {
1013 const htmlMatch = text.match(/```html\n([\s\S]*?)\n```/);
1014 return htmlMatch ? htmlMatch[1].trim() : text;
1015}
1016
1017async function generateCode(prompt: string, currentCode: string) {
1018 const starterPrompt = STARTER_PROMPTS.find(p => p.prompt === prompt);
1019 if (starterPrompt) {
1059}
1060
1061export default async function server(req: Request): Promise<Response> {
1062 // Dynamic import for SQLite to avoid client-side import
1063 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");

OpenTowniesystem_prompt.txt17 matches

@pomdtr•Updated 3 months ago
10 1. `http`: http vals export a default server request handler.
11 2. `script`: script vals can be imported into other vals, similar to an npm package.
12 3. `cron`: cron vals export a function that can automatically run at user-set intervals, similar to a cron command.
13 4. `email`: email vals export a function that runs when its associated email address receives an email.
14
15Follow these requirements for Val Town when generating code.
49</requirements>
50
51If the user asks for specific functionality, the Val Town standard library includes the following:
52
53<libraries>
63 ```
64
65 Blob storage only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
66 `const { blob } = await import("https://esm.town/v/std/blob");`
67 </library>
78 If you are changing a SQLite table's schema, you should also change the table's name so it creates a fresh table, ie by adding _2 or _3 after it everywhere. Ensure that tables are created before they are used.
79
80 SQLite storage only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
81 `const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");`
82 </library>
99 ```
100
101 OpenAI only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
102 `const { OpenAI } = await import "https://esm.town/v/std/openai");`
103 </library>
113 ```
114
115 Email only works on the server. If the val includes client-side code, use dynamic imports to import this module in the server function, e.g.:
116 `const { email } = await import "https://esm.town/v/std/email");`
117 </library>
131 Write the code in ```val code fences.
132 Include the val type as metadata on the code fence, e.g.: ```val type=script
133 If this is a new val, decide what val type is appropriate based on the user's prompt. Default to choosing http type vals unless the user has requested specific functionality that requires a different type.
134
135 * If the user requests diff format in their prompt, follow these steps:
157 * Use fetch to communicate with the backend server portion.
158 */
159function App() {
160 return (
161 <div>
167/**
168 * Client-only code
169 * Any code that makes use of document or window should be scoped to the `client()` function.
170 * This val should not cause errors when imported as a module in a browser.
171 */
172function client() {
173 createRoot(document.getElementById("root")).render(<App />);
174}
177/**
178 * Server-only code
179 * Any code that is meant to run on the server should be included in the server function.
180 * This can include endpoints that the client side component can send fetch requests to.
181 */
182export default async function server(request: Request): Promise<Response> {
183 /** If needed, blob storage or sqlite can be imported as a dynamic import in this function.
184 * Blob storage should never be used in the browser directly.
185 * Other server-side specific modules can be imported in a similar way.
232 ```val type=script
233 /** Use this template for creating script vals only */
234 export default function () {
235 return "Hello, world";
236 }
243 ```val type=cron
244 /** Use this template for creating cron vals only */
245 export default async function (interval: Interval) {
246 // code will run at an interval set by the user
247 console.log(`Hello, world: ${Date.now()}`);
270 // The email address for this val will be `<username>.<valname>@valtown.email` which can be derived from:
271 // const emailAddress = new URL(import.meta.url).pathname.split("/").slice(-2).join(".") + "@valtown.email";
272 export default async function (e: Email) {
273 console.log("Email received!", email.from, email.subject, email.text);
274 }

linkInBioTemplatemain.tsx1 match

@awhitter•Updated 3 months ago
2import { renderToString } from "npm:react-dom/server";
3
4export default async function(req: Request) {
5 return new Response(
6 renderToString(

steel_puppeteer_startermain.tsx1 match

@charmaine•Updated 3 months ago
12});
13
14async function main() {
15 let session;
16 let browser;

trackESMContentmain.tsx5 matches

@maxm•Updated 3 months ago
10const TABLE_NAME = `${KEY}_versions_v1`;
11
12async function fetchContent(url: string) {
13 const response = await fetch(url);
14 return await response.text();
15}
16
17async function initializeDatabase() {
18 await sqlite.execute(`
19 CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (
26}
27
28export default async function(interval: Interval) {
29 await initializeDatabase();
30
56}
57
58async function sha256(message: string): Promise<string> {
59 const msgUint8 = new TextEncoder().encode(message);
60 const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);
64}
65
66export async function getAllVersions() {
67 await initializeDatabase();
68 const versions = await sqlite.execute(`SELECT * FROM ${TABLE_NAME} ORDER BY timestamp DESC`);

steel_puppeteer_startermain.tsx1 match

@stevekrouse•Updated 3 months ago
12});
13
14async function main() {
15 let session;
16 let browser;

badgemain.tsx1 match

@stevekrouse•Updated 3 months ago
1export default function server(req: Request): Response {
2 const svg = `<svg width="140" height="35" viewBox="0 0 140 35" fill="none" xmlns="http://www.w3.org/2000/svg">
3<g clip-path="url(#clip0_0_3)">

react_client_forkmain.tsx8 matches

@johndevor•Updated 3 months ago
1<think>
2Okay, so the user provided a React application written in TypeScript, and they mentioned that the requested changes are undefined. That probably means they just want the code to be formatted or cleaned up without any functional changes.
3
4Looking at the code, I notice that it's using a mix of JavaScript and some TypeScript features, but it's not strictly typed. The initialTodos prop is defined as an array of objects with a text property, which is good. However, the state for todos and newTodo could benefit from more specific types.
6I'll start by adding explicit types to the useState hooks. For the todos state, I'll define it as an array of { text: string }, and for newTodo, it should be a string. This helps with type checking and makes the code more robust.
7
8Next, I'll format the code for better readability. I'll adjust the indentation and spacing, especially in the JSX where inline styles are applied. This makes the code cleaner and easier to read without changing any functionality.
9
10I also notice that the server function handles different routes. I'll make sure the syntax is consistent and that all possible routes are handled correctly. Since there are no requested changes, I won't alter the functionality here.
11
12Finally, I'll ensure that all imports and function calls are correctly formatted and that there are no syntax errors. This includes checking that the createRoot function is properly used and that the client-side rendering is correctly set up.
13
14In summary, the main steps are adding explicit types, improving code formatting, and ensuring consistency without changing any functionality since the requested changes were undefined.
15</think>
16
23import { blob } from "https://esm.town/v/std/blob?v=10";
24
25function App({ initialTodos }: { initialTodos: { text: string; }[]; }) {
26 const [todos, setTodos] = useState<{ text: string; }[]>(Array.isArray(initialTodos) ? initialTodos : []);
27 const [newTodo, setNewTodo] = useState<string>("");
117}
118
119function client() {
120 const fetchTodos = async () => {
121 const response = await fetch('/todos');
131if (typeof document !== "undefined") { client(); }
132
133export default async function server(request: Request) {
134 if (request.method === 'POST' && request.url.endsWith('/add-todo')) {
135 const body = await request.json();

getFileEmail4 file matches

@shouser•Updated 1 week ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 1 week ago
Simple functional CSS library for Val Town
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",