// Serves HTML from a template for every landing route on aesthetic.computer. import https from "https"; import path from "path"; import { promises as fs } from "fs"; import { URLSearchParams, fileURLToPath } from "url"; import he from "he"; const { encode } = he; import * as num from "../../public/aesthetic.computer/lib/num.mjs"; import { parse, metadata, inferTitleDesc, updateCode, } from "../../public/aesthetic.computer/lib/parse.mjs"; import { respond } from "../../backend/http.mjs"; import { handleFromPermahandle } from "../../backend/authorization.mjs"; import { connect } from "../../backend/database.mjs"; import { recordPieceHit, looksAutomated } from "../../backend/piece-hits.mjs"; import { bootPreloads, workerBundleFilename, builtinPieceUrl } from "../../backend/boot-preloads.mjs"; import { defaultTemplateStringProcessor as html } from "../../public/aesthetic.computer/lib/helpers.mjs"; import { networkInterfaces } from "os"; const dev = process.env.CONTEXT === "dev" || process.env.NETLIFY_DEV === "true"; const BARE_KIDLISP_CODE = /^[0-9A-Za-z]{3,64}$/; const POSTHOG_CLOUD_HOSTS = new Set([ "https://us.i.posthog.com", "https://eu.i.posthog.com", ]); function postHogBrowserConfig() { const projectToken = process.env.POSTHOG_PROJECT_TOKEN?.trim(); const apiHost = process.env.POSTHOG_API_HOST?.trim() || "https://us.i.posthog.com"; if (!projectToken?.startsWith("phc_") || !POSTHOG_CLOUD_HOSTS.has(apiHost)) { return null; } return { projectToken, apiHost, uiHost: apiHost.startsWith("https://eu.") ? "https://eu.posthog.com" : "https://us.posthog.com", }; } function serializeBrowserConfig(config) { return JSON.stringify(config).replaceAll("<", "\\u003c"); } // Record a piece hit against the database we are already connected to. This // used to POST to our own public API โ€” out through the CDN and back into a // second function invocation โ€” which is why half the landing page's latency // was spent telling ourselves something we already knew. async function trackPieceHit(piece, type) { try { const database = await connect(); await recordPieceHit(database.db, { piece, type }); await database.disconnect(); } catch (e) { // Silent fail โ€” counting a read must never cost the reader the page. if (dev) console.log("๐Ÿ“Š Hit tracking failed:", e.message); } } async function findBareKidlispCode(slug) { if (!BARE_KIDLISP_CODE.test(slug)) return false; try { const database = await connect(); const record = await database.db.collection("kidlisp").findOne( { code: slug }, { projection: { _id: 1 } }, ); await database.disconnect(); return !!record; } catch (err) { console.log(`[kidlisp] Bare /${slug} lookup failed:`, err?.message || err); return false; } } function redirectToKidlispCode(event, code) { const query = new URLSearchParams(event.queryStringParameters || {}); const suffix = query.toString() ? `?${query.toString()}` : ""; const location = `/$${code}${suffix}`; return respond( 302, `Redirecting to ${location}`, { "Content-Type": "text/html", Location: location, }, ); } async function fun(event, context) { const _startTime = Date.now(); // ๐Ÿ› DEBUG: Log the actual path resolution for troubleshooting console.log(`๐Ÿ” DEBUG index.mjs: path=${event.path}, dev=${dev}, __dirname=${typeof __dirname !== 'undefined' ? __dirname : 'N/A'}`); try { // TODO: Return a 500 or 404 for everything that does not exist... // - [] Like for example if the below import fails... // ๐Ÿ”Œ A WebSocket handshake is not a page. Stale clients โ€” cached service // workers and old installed builds from before the loader moved to // session-server.aesthetic.computer โ€” still try to upgrade against the // root host, and every failed attempt was being answered with the full // ~120KB landing page and counted as a piece hit. Refuse cheaply instead; // they retry forever either way, but now it costs a header, not a page. if ((event.headers["upgrade"] || "").toLowerCase() === "websocket") { return { statusCode: 426, headers: { "Content-Type": "text/plain; charset=utf-8", Connection: "close", }, body: "Upgrade Required โ€” the module loader lives at wss://session-server.aesthetic.computer", }; } if (event.path === "/favicon.ico") { return { statusCode: 302, headers: { "Cache-Control": "public, max-age=86400", "Content-Type": "text/plain; charset=utf-8", Location: "/purple-pals.svg", }, body: "", }; } if (event.path === "/requestProvider.js.map") { return { statusCode: 404, headers: { "Content-Type": "text/plain; charset=utf-8" }, body: "Not found", }; } // Serve system .mjs files directly as static assets // These get caught by the catch-all redirect but shouldn't go through piece loading if (event.path.endsWith(".mjs") && !event.path.startsWith("/disks/")) { try { // On Netlify, with base="system", files are at /var/task/ (not /var/task/system/) const baseDir = dev ? process.cwd() : "/var/task"; const filePath = path.join(baseDir, "public/aesthetic.computer", event.path.slice(1)); const content = await fs.readFile(filePath, "utf8"); return { statusCode: 200, headers: { "Content-Type": "application/javascript", "Cache-Control": "public, max-age=60" }, body: content, }; } catch (err) { console.log(`โšก System .mjs file not found: ${event.path}, tried: ${path.join(dev ? process.cwd() : "/var/task", "public/aesthetic.computer", event.path.slice(1))}`); return { statusCode: 404, body: `File not found: ${event.path}` }; } } if (event.headers["host"] === "sotce.local:8888") { return respond( 302, 'https://localhost:8888/sotce-net', { "Content-Type": "text/html", Location: "https://localhost:8888/sotce-net", }, ); } // Serve top.kidlisp.com with dynamic meta tags for social previews / iMessage // event.path check handles local dev (localhost:8888/top.kidlisp.com via catch-all) // host header check handles production (top.kidlisp.com domain โ†’ function proxy) if (event.path.startsWith("/top.kidlisp.com") || event.headers["host"] === "top.kidlisp.com") { try { const pathParts = event.path.split("/").filter((p) => p); // In local dev: pathParts[0] = "top.kidlisp.com", pathParts[1] = "@handle" // In production: pathParts[0] = "@handle" (event.path is the original request path) const startsWithDomain = event.path.startsWith("/top.kidlisp.com"); const handleIdx = startsWithDomain ? 1 : 0; const handle = pathParts[handleIdx]?.startsWith("@") ? pathParts[handleIdx] : null; const title = handle ? `KidLisp Top 100 ยท ${handle}` : "KidLisp Top 100"; const desc = handle ? `Top KidLisp pieces by ${handle}` : "The top 100 KidLisp pieces"; const ogImage = "https://oven.aesthetic.computer/kidlisp-og.png"; const baseUrl = dev ? "http://localhost:8888" : "https://aesthetic.computer"; const res = await fetch(`${baseUrl}/kidlisp.com/device.html`); if (!res.ok) throw new Error(`fetch device.html: ${res.status}`); let htmlContent = await res.text(); // Replace title and static OG/Twitter tags with dynamic versions htmlContent = htmlContent.replace( /KidLisp\.com ยท Device<\/title>[\s\S]*?<meta name="twitter:image"[^>]*\/>/, `<title>${encode(title)} `, ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving top.kidlisp.com:", err); return respond(500, "Error loading top.kidlisp.com"); } } // Serve calm.kidlisp.com with dynamic meta tags for social previews if (event.path.startsWith("/calm.kidlisp.com") || event.headers["host"] === "calm.kidlisp.com") { try { const title = "KidLisp Calm"; const desc = "A hand-curated selection of calming KidLisp pieces"; const ogImage = "https://oven.aesthetic.computer/kidlisp-og.png"; const baseUrl = dev ? "http://localhost:8888" : "https://aesthetic.computer"; const res = await fetch(`${baseUrl}/kidlisp.com/device.html`); if (!res.ok) throw new Error(`fetch device.html: ${res.status}`); let htmlContent = await res.text(); htmlContent = htmlContent.replace( /KidLisp\.com ยท Device<\/title>[\s\S]*?<meta name="twitter:image"[^>]*\/>/, `<title>${encode(title)} `, ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving calm.kidlisp.com:", err); return respond(500, "Error loading calm.kidlisp.com"); } } // Serve keep.kidlisp.com locally if (event.path.startsWith("/keep.kidlisp.com")) { try { let htmlContent = await fs.readFile( path.join(process.cwd(), "public/kidlisp.com/keeps.html"), "utf8" ); if (dev) { htmlContent = htmlContent.replace("", ``); } return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving kidlisp.com/keeps:", err); return respond(500, "Error loading kidlisp.com keeps"); } } // Serve specific kidlisp.com pages before the catch-all // /kidlisp.com/device* โ†’ device.html (FF1 optimized display) // /device.kidlisp.com/* โ†’ device.html (local dev path for device.kidlisp.com) // /kidlisp.com/pj* โ†’ pj.html (PJ mode) if (event.path.startsWith("/kidlisp.com/device") || event.path.startsWith("/device.kidlisp.com")) { try { const htmlContent = await fs.readFile( path.join(process.cwd(), "public/kidlisp.com/device.html"), "utf8" ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving kidlisp.com/device:", err); return respond(500, "Error loading kidlisp.com device mode"); } } if (event.path.startsWith("/kidlisp.com/pj")) { try { const htmlContent = await fs.readFile( path.join(process.cwd(), "public/kidlisp.com/pj.html"), "utf8" ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving kidlisp.com/pj:", err); return respond(500, "Error loading kidlisp.com PJ mode"); } } // Serve kidlisp.com/index.html for all /kidlisp.com/* paths (SPA routing) // This handles paths like /kidlisp.com, /kidlisp.com/, /kidlisp.com/$abc if (event.path.startsWith("/kidlisp.com")) { try { const htmlContent = await fs.readFile( path.join(process.cwd(), "public/kidlisp.com/index.html"), "utf8" ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving kidlisp.com:", err); return respond(500, "Error loading kidlisp.com"); } } // Serve jas.life/index.html for /jas.life path if (event.path === "/jas.life" || event.path.startsWith("/jas.life/")) { try { const htmlContent = await fs.readFile( path.join(process.cwd(), "public/jas.life/index.html"), "utf8" ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: htmlContent, }; } catch (err) { console.error("โŒ Error serving jas.life:", err); return respond(500, "Error loading jas.life"); } } // Serve GIF files directly as static assets (for mockup previews, etc.) if (event.path.endsWith(".gif")) { try { const baseDir = dev ? process.cwd() : "/var/task"; const gifPath = path.join(baseDir, "public/aesthetic.computer", event.path.slice(1)); const gifBuffer = await fs.readFile(gifPath); return { statusCode: 200, headers: { "Content-Type": "image/gif", "Cache-Control": "public, max-age=60" }, body: gifBuffer.toString("base64"), isBase64Encoded: true, }; } catch (err) { console.error("โŒ Error serving GIF:", event.path, err.message); return respond(404, "GIF not found"); } } // Serve WebP files directly as static assets (for animated mockup previews with transparency) if (event.path.endsWith(".webp")) { try { const baseDir = dev ? process.cwd() : "/var/task"; const webpPath = path.join(baseDir, "public/aesthetic.computer", event.path.slice(1)); const webpBuffer = await fs.readFile(webpPath); return { statusCode: 200, headers: { "Content-Type": "image/webp", "Cache-Control": "public, max-age=60" }, body: webpBuffer.toString("base64"), isBase64Encoded: true, }; } catch (err) { console.error("โŒ Error serving WebP:", event.path, err.message); return respond(404, "WebP not found"); } } // console.log("๐Ÿ˜ƒ", __dirname, __filename); let slug = event.path.slice(1) || "prompt"; // Solo mode: trailing `|` is syntactic sugar for ?solo // e.g., /notepat| โ†’ /notepat?solo (302 redirect) if (slug.endsWith("|")) { const cleanSlug = slug.slice(0, -1); const existingParams = event.queryStringParameters || {}; const paramStr = Object.entries({ ...existingParams, solo: "true" }) .map(([k, v]) => v === "true" ? k : `${k}=${v}`) .join("&"); return { statusCode: 302, headers: { Location: `/${cleanSlug}?${paramStr}` }, }; } // Handle direct requests to /disks/ paths (static asset requests) if (slug.startsWith("disks/")) { // For direct disk file requests, strip the "disks/" prefix // so "/disks/prompt.mjs" becomes "prompt.mjs" slug = slug.substring(6); // Remove "disks/" // Also strip the file extension if present, since the netlify function expects // the piece name without extension if (slug.endsWith(".mjs")) { slug = slug.slice(0, -4); // Remove ".mjs" } else if (slug.endsWith(".lisp")) { slug = slug.slice(0, -5); // Remove ".lisp" } } // Prevent loading of .json, font, or other non-code files as Lisp/JS pieces // Note: .gif is allowed for mockup previews served from /aesthetic.computer/ const forbiddenExtensions = [".json", ".ttf", ".otf", ".woff", ".woff2", ".eot", ".svg", ".png", ".jpg", ".jpeg", ".bmp", ".ico"]; for (const ext of forbiddenExtensions) { if (slug.endsWith(ext)) { console.log(`โ›” Blocked attempt to load forbidden file type: ${slug}`); return respond(404, `File type not allowed: ${ext}`); } } // Safely decode URL-encoded characters in the slug try { slug = decodeURIComponent(slug); } catch (error) { console.log("โš ๏ธ Failed to decode URL slug (likely contains literal % or # symbols):", slug); // If decoding fails, leave slug as-is for legacy % symbols (e.g., old tape %code links) // But still handle common escape sequences manually slug = slug .replace(/%C2%A7/g, "\n") // UTF-8 encoded ยง to newline .replace(/%C2%A4/g, "%") // UTF-8 encoded ยค to percent .replace(/%C2%A8/g, ";") // UTF-8 encoded ยจ to semicolon .replace(/%23/g, "#") // URL-encoded hash to # .replace(/ยง/g, "\n") // Direct ยง to newline (in case not URL-encoded) .replace(/ยค/g, "%") // Direct ยค to percent (in case not URL-encoded) .replace(/ยจ/g, ";") // Direct ยจ to semicolon (in case not URL-encoded) // Standard URL decoding (safe ones only) .replace(/%28/g, "(") .replace(/%29/g, ")") .replace(/%20/g, " "); // Note: Legacy % symbols (like in "tape %JyK") are left as-is } // console.log("Path:", event.path, "Host:", event.headers["host"]); // Some domains will rewrite the initial slug. if (event.headers["host"] === "botce.ac") { slug = "botce"; } else if (event.headers["host"] === "wipppps.world" || event.headers["host"] === "www.wipppps.world") { slug = "wipppps"; } else if (event.headers["host"] === "sundarakarma.com" || event.headers["host"] === "www.sundarakarma.com") { slug = "sundarakarma.com"; } else if ( event.headers["host"] === "m2w2.whistlegraph.com" && event.path.length <= 1 ) { slug = "wg~m2w2"; } else if ( (event.headers["host"] === "notepat.com" || event.headers["host"] === "www.notepat.com") && event.path.length <= 1 ) { slug = "notepat"; } else if ( (event.headers["host"] === "oskiewar.com" || event.headers["host"] === "www.oskiewar.com") && event.path.length <= 1 ) { slug = "oskiewar"; } // Handle kidlisp:code URL pattern and convert to $code format const originalPath = event.path.slice(1) || "prompt"; // Store original for redirect check if (slug.startsWith("kidlisp:") && slug.length > 8) { const code = slug.slice(8); // Remove "kidlisp:" prefix const newSlug = `$${code}`; // Convert to $code format console.log(`[kidlisp] Converting kidlisp:${code} to $${code} and redirecting`); // Redirect to the $code format to update the URL bar return respond( 302, `Redirecting to /${newSlug}`, { "Content-Type": "text/html", Location: `/${newSlug}`, }, ); } // Handle clock:code URL pattern and convert to *code format if (slug.startsWith("clock:") && slug.length > 6) { const code = slug.slice(6); // Remove "clock:" prefix const newSlug = `*${code}`; // Convert to *code format console.log(`[clock] Converting clock:${code} to *${code} and redirecting`); return respond( 302, `Redirecting to /${newSlug}`, { "Content-Type": "text/html", Location: `/${newSlug}`, }, ); } // ๐ŸŽ„ Handle mo.XX and merryo.XX uniform timing shorthand URLs // e.g., /mo.1:a:b:c โ†’ /mo~.1:a:b:c (piece=mo, timing=.1, pieces=a,b,c) // e.g., /merryo.05:tone:clock โ†’ /merryo~.05:tone:clock const moMatch = slug.match(/^(mo|merryo)\.(\d+(?:\.\d+)?)([:~].+)?$/); if (moMatch) { const [, prefix, timing, rest] = moMatch; // Route to the mo piece with timing as first colon param const newSlug = `mo~.${timing}${rest || ""}`; console.log(`[merry] Converting ${slug} to ${newSlug}`); return respond( 302, `Redirecting to /${newSlug}`, { "Content-Type": "text/html", Location: `/${encodeURIComponent(newSlug)}`, }, ); } // Handle *xxx clock shortcode - serve page directly, let client fetch melody // The client-side disk.mjs normalizes *code to clock piece and preserves the URL if (slug.startsWith("*") && slug.length > 1 && !slug.includes("~")) { const code = slug.slice(1); // Remove * prefix console.log(`[clock] Serving clock shortcode: *${code} (client will fetch melody)`); // Fall through to normal page rendering - client handles the rest } // Handle permahandle URLs (e.g., /ac25namuc โ†’ /@jeffrey) // Permahandles are 9 chars starting with "ac" if (slug.length === 9 && slug.startsWith("ac") && /^ac[0-9]{2}[a-z]{5}$/.test(slug)) { console.log(`[permahandle] Checking if ${slug} is a valid permahandle...`); try { const result = await handleFromPermahandle(slug); if (result?.handle) { console.log(`[permahandle] Found: ${slug} โ†’ @${result.handle}`); // Redirect to the user's profile return respond( 302, `Redirecting to /@${result.handle}`, { "Content-Type": "text/html", Location: `/@${result.handle}`, }, ); } } catch (err) { console.log(`[permahandle] Lookup failed for ${slug}:`, err.message); } } const parsed = parse(slug, { hostname: event.headers["host"] }); // Get local IP. let lanHost; if (dev) { const ifaces = networkInterfaces(); let ipAddress; // Iterate over network interfaces to find the 1st non-internal IPv4 address Object.keys(ifaces).forEach((ifname) => { ifaces[ifname].forEach((iface) => { if (iface.family === "IPv4" && !iface.internal) { ipAddress = iface.address; return; } }); }); lanHost = `"https://${ipAddress}:8888"`; // Quoted for use in `body`. } let meta; const redirect = { statusCode: 302, headers: { "Content-Type": "text/html", Location: "/" + new URLSearchParams(event.queryStringParameters), }, body: 'https://aesthetic.computer', }; // Load and pre-process a piece's source code, then run it's `meta` function. let statusCode = 200, sourceCode, language = "javascript", // Might switch to 'lisp' if necessary. module, fromHandle = false; try { // Externally hosted pieces always start with @. if (slug.startsWith("@") && slug.indexOf("/") !== -1) { const baseUrl = `https://${event.headers["host"]}/${parsed.path}`; console.log("๐Ÿง”๐Ÿงฉ Loading handled piece:", `${baseUrl}.mjs`); try { let handledPiece = await getPage(`${baseUrl}.mjs`); // Try to load the Lisp source if the .mjs file is not found if (handledPiece?.code !== 200) { console.log("๐Ÿง”๐Ÿงฉ .mjs not found, trying .lisp:", `${baseUrl}.lisp`); handledPiece = await getPage(`${baseUrl}.lisp`); language = "lisp"; } if (handledPiece?.code !== 200) { statusCode = 404; // return respond(statusCode, `Content not found: ${path}`); } else { sourceCode = handledPiece.data; fromHandle = true; } } catch (err) { console.log("Failed to load handled piece:", err); } // const url = `https://${event.headers["host"]}/${parsed.path}.mjs`; // console.log("๐Ÿง”๐Ÿงฉ Loading handled piece:", url); // try { // const handledPiece = await getPage(url); // // TODO: This should also be able to handle lisp source. // if (handledPiece?.code !== 200) { // statusCode = 404; // respond(statusCode, `Content not found: ${path}`); // } // sourceCode = handledPiece.data; // fromHandle = true; // } catch (err) { // console.log("Failed to load handled piece:", err); // } } else { // Locally hosted piece. try { // Strip the "aesthetic.computer/disks/" prefix from parsed.path // Handle cases where it might be duplicated let path = parsed.path; // Remove all occurrences of "aesthetic.computer/disks/" while (path.startsWith("aesthetic.computer/disks/")) { path = path.substring("aesthetic.computer/disks/".length); } if (path.startsWith("@")) path = "profile"; // Skip API paths - these are handled by separate functions if (path.startsWith("api/")) { console.log("[index] Skipping API path:", path); sourceCode = null; // Handle special kidlisp path case } else if (path === "(...)" || path === "(...)") { // This is inline kidlisp code, not a file to load console.log("[kidlisp] Detected inline kidlisp, skipping file load"); sourceCode = null; // No source code to load // Handle $code nanoid pieces - these load source from MongoDB client-side } else if (path.startsWith("$") && path.length >= 4 && /^\$[a-zA-Z0-9]+$/.test(path)) { console.log("[kidlisp] Detected $code piece, skipping file load:", path); sourceCode = null; // Source loaded client-side from MongoDB statusCode = 200; // Ensure we return 200 for valid $code pieces // Handle *code clock pieces - these load source from MongoDB client-side and route to clock.mjs } else if (path.startsWith("*") && path.length >= 4 && /^\*[a-zA-Z0-9]+$/.test(path)) { console.log("[clock] Detected *code piece, skipping file load:", path); sourceCode = null; // Source loaded client-side from MongoDB statusCode = 200; // Ensure we return 200 for valid *code pieces } else { try { const basePath = `${dev ? "./" : "/var/task/"}public/aesthetic.computer/disks/${path}`; console.log(`๐Ÿ” DEBUG: Trying to load disk from basePath=${basePath}`); try { sourceCode = await fs.readFile(`${basePath}.mjs`, "utf8"); console.log(`๐Ÿ” DEBUG: Successfully loaded ${basePath}.mjs`); } catch (errJavaScript) { console.log(`๐Ÿ” DEBUG: Failed to load .mjs: ${errJavaScript.message}`); try { sourceCode = await fs.readFile(`${basePath}.lisp`, "utf8"); console.log(`๐Ÿ” DEBUG: Successfully loaded ${basePath}.lisp`); language = "lisp"; } catch (errLisp) { console.error( "๐Ÿ“ƒ Error reading or importing source code (both .mjs and .lisp failed):", errJavaScript, errLisp, ); console.log(`๐Ÿ” DEBUG: Both .mjs and .lisp failed for ${basePath}`); statusCode = 404; // return respond(statusCode, `Content not found: ${path}`); } } } catch (err) { console.error("๐Ÿ“ƒ Error:", err); statusCode = 404; // return respond(statusCode, `Content not found: ${path}`); // throw err; } } } catch (e) { console.log("๐Ÿ”ด Piece load failure..."); const anonUrl = `https://art.aesthetic.computer/${ parsed.path.split("/").pop() + ".mjs" }`; console.log("๐Ÿ“ฅ Attempting to load piece from anon:", anonUrl); const externalPiece = await getPage(anonUrl); sourceCode = externalPiece.data; if (externalPiece?.code !== 200) statusCode = 404; } } // TODO: โค๏ธโ€๐Ÿ”ฅ How will this work for handled pieces? if (sourceCode) { const originalCode = sourceCode; const currentDirectory = fileURLToPath(new URL("../../", import.meta.url)).replace(/\/$/, ""); sourceCode = updateCode( sourceCode, dev ? "localhost:8888" : event.headers["host"], dev, (event.headers["x-forwarded-proto"] || "https") + ":", //, fromHandle ? false : true, fromHandle ? undefined : currentDirectory, ); // const tempPath = path.join("/tmp", `${slug.replaceAll("/", "-")}.mjs`); // try { // await fs.writeFile(tempPath, sourceCode); // if (language === "javascript") // module = await import(`file://${tempPath}`); // } catch (err) { // console.log("โš ๏ธ Import error:", err, tempPath); // } finally { // await fs.unlink(tempPath); // } const tempPath = path.join("/tmp", `${slug.replaceAll("/", "-")}.mjs`); try { await fs.writeFile(tempPath, sourceCode); if (language === "javascript") module = await import(`file://${tempPath}`); // TODO: This fails in development sometimes, still not sure why... } catch (err) { console.error("โš ๏ธ Import error:", err); try { await fs.access(tempPath); const contents = await fs.readFile(tempPath, "utf8"); // console.error("๐Ÿชต Temp file contents:\n", contents); } catch (accessErr) { console.error("โŒ Temp file does not exist:", tempPath); } } finally { try { await fs.unlink(tempPath); // console.log("๐Ÿงน Cleaned up temp file."); } catch (e) { // console.warn("โš ๏ธ Failed to delete temp file:", e); } } // Get initial metadata from module or infer it meta = module?.meta?.({ ...parsed, num }) || inferTitleDesc(originalCode); // Override title with first line comment if it's a Lisp file and no meta.title exists if (language === "lisp" && originalCode && (!meta?.title || meta.title === parsed.text)) { const firstLine = originalCode.split('\n')[0]?.trim(); if (firstLine && firstLine.startsWith(';')) { const title = firstLine.substring(1).trim(); // Remove semicolon and trim whitespace if (title) { meta = { ...meta, title, standaloneTitle: true }; } } } } else if (parsed.source) { // Handle inline kidlisp code that doesn't need file loading console.log("[kidlisp] Using inline kidlisp source for metadata"); // Reset status to 200 for inline kidlisp pieces statusCode = 200; // Get initial metadata from inference meta = inferTitleDesc(parsed.source); // Override title with first line comment if it exists and current title is default const firstLine = parsed.source.split('\n')[0]?.trim(); if (firstLine && firstLine.startsWith(';') && (!meta?.title || meta.title === parsed.text)) { const title = firstLine.substring(1).trim(); // Remove semicolon and trim whitespace if (title) { meta = { ...meta, title, standaloneTitle: true }; } } } if (statusCode === 404 && !sourceCode && !fromHandle && await findBareKidlispCode(slug)) { console.log(`[kidlisp] Converting bare /${slug} to /$${slug} and redirecting`); return redirectToKidlispCode(event, slug); } } catch (err) { // If either module doesn't load, then we can fallback to the main route. console.log("๐Ÿ”ด Error loading module:", err, sourceCode); return redirect; } const { title, desc, ogImage, icon, iconWebp, twitterImage, manifest } = metadata( event.headers["host"], slug, meta, "https:", // Server-side defaults to HTTPS ); // TODO: Not sure if 'location' is correct here, but I wan tto skip rendering the link rel icon and og:image if the icon or preview parameter is present // in the request url qury params... const qsp = event.queryStringParameters || {}; const previewOrIcon = "icon" in qsp || "preview" in qsp; const posthogConfig = previewOrIcon ? null : postHogBrowserConfig(); // Boot screen. 'empty' (the default) ships no canvas and no animation code // at all โ€” the 97 KB block below is only rendered for ?boot=serious or // ?boot=aesthetic. ?noboot is the legacy spelling of empty. const bootTheme = "noboot" in qsp ? "empty" : qsp.boot || "empty"; const bootCanvasWanted = bootTheme !== "empty"; // What the browser should fetch before boot.mjs runs: the static import // graph of the entry modules (derived, see backend/boot-preloads.mjs) and // the worker bundle, which bios would otherwise ask for only after it has // evaluated and read the manifest. bios appends the page's query string to // the worker URL, so the warm-up fetch carries it too: same URL, same // cache entry, one download. const preloadTags = dev ? `` : (await bootPreloads()) .map((p) => ``) .join("\n "); const workerFilename = dev ? null : await workerBundleFilename(); const workerHintTag = workerFilename ? `` : ""; // The piece itself, for built-in .mjs pieces: fetched at parse time so the // worker finds it in its piece-code cache instead of fetching it only after // its bundle has evaluated and the preamble frames have run. cache:"no-cache" // keeps the freshness the worker's ?v= bust gave, as an ETag 304 when the // file is unchanged rather than a full download every load. const pieceUrl = dev ? null : await builtinPieceUrl(parsed?.text); const pieceHintTag = pieceUrl ? `` : ""; const body = html` ${title} ${!previewOrIcon && iconWebp ? html`` : ""} ${!previewOrIcon ? html`` : ""} ${!previewOrIcon ? html`` : ""} ${!previewOrIcon ? html`` : ""} ${dev ? "" : ``} ${workerHintTag} ${pieceHintTag} ${preloadTags}

${encode(title)}

${encode(desc)}

Aesthetic Computer is an open creative computing platform for making art, games, and tools in the browser using JavaScript and KidLisp. Navigate by typing a piece name (e.g. "painting", "line", "wand", "prompt") into the command prompt and pressing Enter. See llms.txt for full documentation: https://aesthetic.computer/llms.txt

Source code: https://tangled.org/aesthetic.computer/core | Pieces (programs): https://tangled.org/aesthetic.computer/core/tree/main/system/public/aesthetic.computer/disks | Runtime: https://tangled.org/aesthetic.computer/core/tree/main/system/public/aesthetic.computer/lib

${bootCanvasWanted ? ` ` : ``} `; // ๐ŸŒธ Cute compact log const _ms = Date.now() - _startTime; const _path = event.path === "/" ? "๐Ÿ " : event.path.slice(0, 20); console.log(`โœจ ${_path} ${meta?.title || "~"} ${_ms}ms`); // ๐Ÿ“Š Track piece hit โ€” a local write now, so it no longer needs a race // against a two second timeout. Machines are not readers: crawlers, // link previewers and scripted clients reach this same line, and // counting them made the collection describe traffic instead of people. if ( !dev && statusCode === 200 && parsed?.text && !previewOrIcon && !looksAutomated(event.headers) ) { const pieceType = parsed.path?.startsWith("@") ? "user" : "system"; // Not awaited: the reader gets the page first, the count lands after. trackPieceHit(parsed.text, pieceType).catch(() => {}); } return { statusCode, headers: { "Content-Type": "text/html", // "Cross-Origin-Embedder-Policy": "require-corp", "Cross-Origin-Opener-Policy": "same-origin-allow-popups", "Cross-Origin-Resource-Policy": "cross-origin", }, body, ttl: 60, }; } catch (error) { console.error("โŒ Error in index.mjs handler:", error); console.error(" Path:", event.path); console.error(" Stack:", error.stack); return { statusCode: 500, headers: { "Content-Type": "text/plain" }, body: `Server Error: ${error.message}\n\nPath: ${event.path}\n\nPlease check the server logs.`, }; } } async function getPage(url) { return new Promise((resolve, reject) => { let data = ""; const options = dev ? { agent: new https.Agent({ rejectUnauthorized: false }) } : {}; https .get(url, options, (res) => { res.on("data", (chunk) => { data += chunk; }); res.on("end", () => { resolve({ data, code: res.statusCode }); }); }) .on("error", (e) => { console.log("Error:", e); reject(e); }); }); } export const handler = fun;