Newest

1
console.log("test")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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": "*",
"Access-Control-Allow-Headers": "*",
},
status: 204,
});
}
const openai = new OpenAI();
try {
var body = await req.json();
} catch (e) {
var search = (new URL(req.url)).searchParams;
body = {
"messages": [{
"role": "user",
"content": search.get("q") || "hello",
}],
"temperature": 0.5,
"presence_penalty": 0,
"frequency_penalty": 0,
"top_p": 1,
stream: true,
model: "gpt-4-turbo",
};
}
const stream = await openai.chat.completions.create(body);
if (!body.stream) {
return new Response(JSON.stringify(body), {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Content-Type": "application/json; charset=UTF-8",
},
});
}
/*
const { readable, writable } = new TransformStream();
const my_stream_writer = writable.getWriter();
var encoder = new TextEncoder();
(async () => {
for await (const chunk of stream) {
my_stream_writer.write(encoder.encode(chunk.choices[0]?.delta?.content || ""));
}
my_stream_writer.close();
})();*/
const { readable, writable } = new TransformStream();
const my_stream_writer = writable.getWriter();
var reader = stream.toReadableStream().getReader();
var totalText = "";
const decoder = new TextDecoder("utf-8", { stream: true });
var encoder = new TextEncoder();
(async () => {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalText += decoder.decode(value, { stream: true });
var msgs = totalText.split("\n");
totalText = msgs.pop();
for (let i in msgs) {
my_stream_writer.write(encoder.encode(`data: ${msgs[i]}\n\n`));
}
await new Promise((r) => {
setTimeout(r, 20);
});
}
my_stream_writer.close();
})();
return new Response(readable, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Content-Type": "text/event-stream; charset=UTF-8",
},
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { email } from "https://esm.town/v/std/email";
import {
CommandContext,
CommandData,
CommandDefinition,
} from "https://raw.githubusercontent.com/curtcox/CommandInterpreter/main/CommandDefinition.ts";
const meta = {
name: "email",
doc: "send an email",
source: import.meta.url,
input_formats: ["EmailOptions"],
output_formats: ["text"],
};
const func = async (context: CommandContext, options: CommandData) => {
const result = await email({
subject: options.content.subject,
text: options.content.text,
});
return {
commands: context.commands,
output: {
format: "JSON",
content: result,
},
};
};
export interface EmailOptions {
subject: string;
text: string;
}
export const email_cmd: CommandDefinition = {
meta,
func,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/preact */
import { activeGTrainAlerts } from "https://esm.town/v/pbt/gtrainalerts?v=36";
import { render } from "npm:preact-render-to-string";
import Uwuifier from "npm:uwuifier";
export default async function(req: Request) {
const uwuifier = new Uwuifier();
const query = new URL(req.url).searchParams;
const timestamp = query.get("at");
const uwu = query.get("uwu");
const parsedTimestamp = timestamp ? Number.parseInt(timestamp, 10) : Date.now();
const entities = await activeGTrainAlerts(parsedTimestamp);
const fucked = entities.length > 0;
const soFucked = entities.length > 1;
const howFucked = soFucked ? `s${entities.map(e => "o").join("")} fucked` : "fucked";
const title = `${uwu ? "UwU! " : " "}the g train ${fucked ? "is" : "isn’t"} ${howFucked}`;
return new Response(
render(
<html class="dark:bg-zinc-800 dark:text-white min-h-screen">
<head>
<title>{title}</title>
<meta
property="og:title"
content={`${title} as of ${
new Date(parsedTimestamp).toLocaleString("en-US", {
timeZone: "America/New_York",
})
}`}
/>
<meta
property="og:description"
content={`${entities.length} active alert${!fucked || soFucked ? "s" : ""}`}
/>
<meta
property="og:image"
content={fucked
? "https://pbt-gtrainog.web.val.run/?status=notOk"
: "https://pbt-gtrainog.web.val.run/?status=ok"}
/>
<meta property="og:url" content="www.isthegtrainfucked.com" />
<meta name="viewport" content="widthdevice-width, initial-scale=1.0" />
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="min-h-screen flex flex-col justify-center items-center gap-4">
<header class="italic text-4xl mb-6">
{uwu ? "UwU!" : ""} the g train {fucked
? (
<span>
is{" "}
<strong>
{soFucked ? (uwu ? "so fucky-wucky" : "so fucked") : (uwu ? "fucky-wucky" : "fucked")}{" "}
{uwu ? "(˶˃ᆺ˂˶)" : ""}
</strong>
</span>
)
: <span>isn’t {uwu ? "fucky-wucky" : "fucked"} {uwu ? "⸜(。 ˃ ᵕ ˂ )⸝♡" : ""}</span>}
</header>
<h1
style="background: #6CBE45"
class={`${
uwu ? "text-7xl" : "text-9xl"
} font-bold text-white rounded-full p-10 h-64 w-64 flex flex-col justify-center items-center`}
>
{fucked ? (uwu ? "• ᴖ •。" : "💩") : (uwu ? "👉👈" : ":)")}
</h1>
<main class="bg-slate-100 dark:bg-stone-900 p-10 m-10 rounded">
{fucked
? (
<div>
<h2 class="font-bold pb-2">
{uwu ? uwuifier.uwuifyWords("how it’s fucked as of") : "how it’s fucked as of"}{" "}
{new Date(parsedTimestamp).toLocaleString("en-US", {
timeZone: "America/New_York",
})}:
</h2>
<ul>
{entities.map(({ alert }) => {
const { text: active } = (alert["transit_realtime.mercury_alert"]["human_readable_active_period"]
?? { translation: [{ language: "en", text: "right now" }] }).translation.find((
{ language },
) => language === "en");
const { text } = alert.header_text.translation.find(({ language }) => language === "en-html");
return (
<li>
<div dangerouslySetInnerHTML={{ __html: uwu ? uwuifier.uwuifySentence(text) : text }} />
<p class="text-xs pt-1 pb-3">{uwu ? uwuifier.uwuifySentence(active) : active}</p>
</li>
);
})}
</ul>
<p>
<a target="__blank" class="underline" href="https://new.mta.info/">
{uwu ? uwuifier.uwuifySentence("alerts on mta.info") : "alerts on mta.info"}
</a>
</p>
</div>
)
: (
<span class="font-bold">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { assertEquals, assertExists } from "https://deno.land/std@0.224.0/assert/mod.ts";
import { css } from "https://esm.town/v/jxnblk/tuna";
const bodyStyles = css({
body: {
color: "red",
fontFamily: "sans-serif",
},
});
assertEquals(bodyStyles.css, "body{color:red;font-family:sans-serif}");
assertEquals(bodyStyles.tag.dangerouslySetInnerHTML.__html, bodyStyles.css);
const styles = css({
button: {
color: "blue",
padding: "8px",
},
box: {
color: "blue",
padding: "32px",
},
});
assertExists(styles.css, "x0");
assertExists(styles.css, "x1");
assertExists(styles.css, "x2");
assertExists(styles.css, ".x0{color:blue}");
assertExists(styles.css, ".x1{padding:8px}");
assertExists(styles.css, ".x2{padding:32px}");
assertEquals(styles.button, "x0 x1");
assertEquals(styles.box, "x0 x2");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { assertEquals } from "https://deno.land/std@0.224.0/assert/mod.ts";
import { caviar } from "https://esm.town/v/jxnblk/caviar";
const simple = caviar({
blue: "#0cf",
});
assertEquals(simple.blue, "var(--blue)");
assertEquals(simple.style, { "--blue": "#0cf" });
const modes = caviar({
light: {
text: "#000",
bg: "#fff",
},
dark: {
text: "#fff",
bg: "#000",
},
});
assertEquals(modes.text, "var(--text)");
assertEquals(modes.style.light, { "--text": "#000", "--bg": "#fff" });
assertEquals(modes.style.dark, { "--text": "#fff", "--bg": "#000" });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export default (component: Function, url: string) =>
function(req: Request) {
return new Response(
`<html>
<body></body>
<script type="module">
import { ${component.name} } from "${url}"
import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
import { jsx } from "https://esm.sh/react@18.2.0/jsx-runtime";
createRoot(document.body).render(jsx(App, {}));
</script>
</html>`,
{
headers: {
"content-type": "text/html",
},
},
);
};

Simple CSS Vars library

Create valimport { caviar } from "https://esm.town/v/jxnblk/caviar"; const vars = caviar({ dark: { text: "#000", bg: "#fff", }, light: { text: "#fff", bg: "#000", }, });
Create val// JSX example <div style={vars.style.light}> <h1 style={{ color: vars.text, backgroundColor: vars.bg, }}> Hello </h1> </div>

Can also be used for non-dynamic CSS vars

Create valimport { caviar } from "https://esm.town/v/jxnblk/caviar"; const vars = caviar({ blue: "#0cf", }); // <div style={vars.style} />

Tests: https://www.val.town/v/jxnblk/caviar_tests

TODO

  • Fallback for missing mode keys
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
export function caviar(obj: any) {
const result: any = {
style: {},
};
for (const [key, val] of Object.entries(obj)) {
if (key === "style") {
throw new Error(`Cannot use reserved key: '${key}'`);
}
if (typeof val === "object") {
createMode(result, key, val);
} else {
const varKey = `--${key}`;
const varVal = `var(${varKey})`;
result[key] = varVal;
result.style[varKey] = val;
}
}
return result;
}
function createMode(result: any, mode: string, obj: any) {
result.style[mode] = {};
for (const [key, val] of Object.entries(obj)) {
const varKey = `--${key}`;
const varVal = `var(${varKey})`;
result[key] = varVal;
result.style[mode][varKey] = val;
}
}

Simple CSS library for Val Town

Create valimport { css } from "https://esm.town/v/jxnblk/tuna"; const styles = css({ body: { // special keyword fontFamily: "system-ui, sans-serif", margin: 0, backgroundColor: "#f5f5f5", }, container: { padding: "32px", margin: "0 auto", maxWidth: "1024px", }, input: { fontFamily: "inherit", fontSize: "inherit", lineHeight: "1.5", padding: "2px 8px", border: "1px solid #ccc", borderRadius: "4px", }, });
Create val// JSX example const html = render( <div className={styles.container}> <style {...styles.tag} /> <h1>Tuna Example</h1> <input type="text" defaultValue="hi" className={styles.input} /> </div> );
Create val// get raw CSS string styles.css

Limitations

  • Does not currently support media queries
  • Does not support HTML element selectors (other than body)
  • Does not support pseudoselectors
  • Does not support nested selectors

Tests: https://www.val.town/v/jxnblk/tuna_tests

TODO

  • Convert number values to px
  • Companion CSS var library
  • Media queries
  • Nested selectors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// import { paramCase } from "https://deno.land/x/case@2.2.0/mod.ts";
// import hash from "https://esm.sh/string-hash@1.1.3";
import { kebabCase } from "https://esm.sh/change-case@5.4.4";
const reserved = ["css", "tag"];
const cache = new Map();
const createDeclaration = (key, val) => `${kebabCase(key)}:${val}`;
function createRule(obj) {
const rules = [];
const classNames = [];
for (const [key, val] of Object.entries(obj)) {
const dec = createDeclaration(key, val);
if (cache.has(dec)) {
classNames.push(cache.get(dec));
} else {
// const cn = "x" + hash(dec).toString(36);
const cn = "x" + cache.size.toString(36);
const rule = `.${cn}{${dec}}`;
rules.push(rule);
classNames.push(cn);
cache.set(dec, cn);
}
}
const css = rules.join("");
const className = classNames.join(" ");
return {
css,
className,
};
}
function createRawRule(selector, obj) {
const decs = [];
for (const [key, val] of Object.entries(obj)) {
const dec = createDeclaration(key, val);
decs.push(dec);
}
return `${selector}{${decs.join(";")}}`;
}
export function css(obj) {
const result = {};
const rules = [];
for (const key in obj) {
if (reserved.includes(key)) {
const msg = `Cannot use key: '${key}'`;
throw new Error(msg);
}
if (key === "body") {
rules.push(createRawRule("body", obj[key]));
continue;
}
const val = obj[key];
const { css, className } = createRule(val);
result[key] = className;
rules.push(css);
}
result.css = rules.join("");
result.tag = {
dangerouslySetInnerHTML: { __html: result.css },
};
return result;
}
export default css;
// TEST
/*
const styles = css({
body: {
margin: 0,
fontFamily: "system-ui, sans-serif",
},
container: {
padding: "32px",
maxWidth: "1024px",
},
button: {
backgroundColor: "tomato",
padding: "8px 16px",
},
box: {
backgroundColor: "tomato",
},
_css: {
should: "throw",
},
});
console.log(styles.container);
console.log(styles.button);
console.log(styles.box);
console.log(styles.css);
*/

AQI Alerts

Get email alerts when AQI is unhealthy near you.

Set up

  1. Click Fork
  2. Change location (Line 4) to describe your location. It accepts fairly flexible English descriptions which it turns into locations via nominatim's geocoder API.
  3. Click Run

Background

This val uses nominatim's geocoder to get your lat, lon, and air quality data from OpenAQ. It uses EPA's NowCast AQI Index calculation and severity levels. Learn more: https://www.val.town/v/stevekrouse.easyAQI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { email } from "https://esm.town/v/std/email?v=9";
import { easyAQI } from "https://esm.town/v/stevekrouse/easyAQI";
export async function aqi(interval: Interval) {
const location = "Dhaka, Bangladesh"; // <-- change to place, city, or zip code
const data = await easyAQI({ location });
if (!interval.lastRunAt) {
email({
text:
`You will now get Air Quality alerts for ${location} if it's unhealthy. It is now ${data.aqi} which is ${data.severity}.`,
subject: `AQI Alerts for ${location} setup!`,
});
}
if (data.severity.includes("Unhealthy")) {
email({
text: "Air Quality: " + data.severity,
subject: `AQI in ${location} is ${data.aqi}`,
});
}
}