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/$%7BsvgDataUrl%7D?q=function&page=33&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 30865 results for "function"(2777ms)

api_ianmenethil_comreqInputFilter.ts8 matches

@ianmenethilโ€ขUpdated 1 day ago
16 * console.log(clean); // <script>alert("xss")</script>
17 */
18export function sanitizeInput(input: any): any {
19 if (typeof input === "string") {
20 // Check for blocked patterns
60 * }
61 */
62export function validateRequestSize(request: Request): boolean {
63 const contentLength = request.headers.get("content-length");
64 if (contentLength) {
92 * }
93 */
94export function validateJsonPayloadSize(jsonString: string): boolean {
95 const size = new TextEncoder().encode(jsonString).length;
96 const isValid = size <= InputValidationConfig.maxJsonPayload;
120 * }
121 */
122export function validateUrlLength(url: string): boolean {
123 const isValid = url.length <= InputValidationConfig.maxUrlLength;
124
147 * }
148 */
149export function validateFileType(mimeType: string): boolean {
150 const isValid = InputValidationConfig.allowedFileTypes.includes(mimeType);
151
169 * @returns True if input contains blocked patterns
170 */
171export function containsBlockedPatterns(input: string): boolean {
172 for (const pattern of InputValidationConfig.blockedPatterns) {
173 if (pattern.test(input)) {
190 *
191 * @param c - Hono context object containing request and response data
192 * @param next - Next middleware function in the Hono processing chain
193 * @returns Promise<void> - Continues to next middleware or throws HTTPException on security violation
194 * @throws HTTPException - 413 Request Entity Too Large, 414 URI Too Long, 400 Bad Request
255 *
256 * @param c - Hono context object
257 * @param next - Next middleware function
258 */
259export const sanitizeBodyMiddleware = async (

api_ianmenethil_comreqHeaders.ts1 match

@ianmenethilโ€ขUpdated 1 day ago
84 }
85
86 /* Header validation (original functionality) ---------------------- */
87 if (!cfg.enabled) {
88 await next();

api_ianmenethil_comreqBody.ts3 matches

@ianmenethilโ€ขUpdated 1 day ago
54
55/**
56 * Validation utility functions for common input patterns.
57 * Provides reusable validators for UUID, alphanumeric, length, and enum validation.
58 */
393 *
394 * @param c - Hono context object containing request and response data
395 * @param next - Next middleware function in the Hono processing chain
396 * @returns Promise<void> - Completes after validation check and next() execution
397 */
425/**
426 * @param schemaName - Name of the validation schema to retrieve from available schemas
427 * @returns Corresponding validator function for the specified schema type
428 */
429export const getBodyValidator = (schemaName: keyof typeof bodyValidationSchemas) => {

api_ianmenethil_comrateLimiter.ts12 matches

@ianmenethilโ€ขUpdated 1 day ago
28};
29
30async function initTables() {
31 await sqlService.createTable("rate_limit_violations", {
32 id: { type: "INTEGER", primaryKey: true, autoIncrement: true },
58}
59
60async function persistViolation(v: RateLimitViolation) {
61 await sqlService.insert("rate_limit_violations", {
62 ip: v.ip,
68}
69
70async function persistBlockStatus(b: IPBlockStatus) {
71 await sqlService.execute({
72 sql: `INSERT OR REPLACE INTO ip_block_status
86}
87
88async function persistBlacklist(ip: string, reason: string) {
89 const key = "rate-limiter/blacklist.json";
90 const json = (await blobService.getJSON<Record<string, unknown>>(key)) ?? {};
93}
94
95async function loadBlacklist() {
96 const key = "rate-limiter/blacklist.json";
97 const json = await blobService.getJSON<Record<string, unknown>>(key);
114];
115
116function getClientIP(c: Context): string {
117 for (const h of HEADER_CANDIDATES) {
118 const v = c.req.header(h);
122}
123
124async function currentViolationCount(ip: string): Promise<number> {
125 if (!AUTO_BLOCK_CONFIG.persistToStorage) {
126 return memoryCache.violationCounts.get(ip) ?? 0;
137}
138
139async function addViolation(ip: string, ep: string, ua?: string) {
140 const v: RateLimitViolation = {
141 ip,
153
154/* Threat detection & auto-blocking */
155async function inspectThreat(ip: string): Promise<ThreatDetectionResult> {
156 if (memoryCache.blacklistedIPs.has(ip)) {
157 return { action: "blacklist", reason: "already blacklisted", violationCount: 0 };
183}
184
185async function temporaryBlock(ip: string, reason: string, vCount: number) {
186 const until = new Date(getSydneyTimestamp() + AUTO_BLOCK_CONFIG.blockDuration * 60 * 1000);
187 const st: IPBlockStatus = {
201/* Middleware */
202/* โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
203export async function enhancedRateLimitMiddleware(c: Context, next: Next) {
204 if (!AUTO_BLOCK_CONFIG.enabled) return await next();
205
250
251/* Back-compat wrapper (same signature as old middleware) */
252export default function createBackendRateLimitMiddleware(): MiddlewareHandler<
253 { Variables: HonoVariables }
254> {

api_ianmenethil_comnetworkFilter.ts3 matches

@ianmenethilโ€ขUpdated 1 day ago
110 c.set("securityContext", newSecurityContextUpdate);
111 await next();
112 function safeMatch(ipToMatch: string, range: string, errTpl: string): boolean {
113 try {
114 return checkIpRange(ipToMatch, range);
118 }
119 }
120 function logIfBlocked(msg: string) {
121 if (cfg.logBlocked) console.warn(msg);
122 }
123 function throwForbidden(
124 config: NetworkFilterConfig,
125 codeKey: keyof NetworkFilterConfig["errorCodes"],

api_ianmenethil_comlogging.ts2 matches

@ianmenethilโ€ขUpdated 1 day ago
182 * Centralised security-event logger (โš ๏ธ do not remove).
183 */
184export function logSecurityEvent(
185 type: string,
186 details: unknown,
287
288/* --- alert stub ---------------------------------------------------- */
289function triggerSecurityAlert(event: SecurityEvent): void {
290 // TODO: integrate pager-duty / email / webhook
291 console.error(

api_ianmenethil_comgeoFilter.ts4 matches

@ianmenethilโ€ขUpdated 1 day ago
16}>("middleware.geofence").geofencing;
17
18function logGeoEvent(type: string, details: GeoEventDetails): void {
19 const logData = {
20 type,
29}
30
31export function checkGeoRestriction(request: Request): GeoFilterResult {
32 if (!GEO.enabled) {
33 return { allowed: true, country: "XX", reason: "Geofencing disabled" };
124/* Middleware */
125/* ------------------------------------------------------------------ */
126export function createGeoFilterMiddleware() {
127 return async (c: Context, next: Next) => {
128 if (!GEO.enabled) return await next();
152}
153
154export async function geoDataExtractionMiddleware(
155 c: Context,
156 next: Next,

api_ianmenethil_comexceptionHandler.ts5 matches

@ianmenethilโ€ขUpdated 1 day ago
61 * @returns HTTPException with formatted JSON response
62 */
63export function buildError(
64 cfg: HeaderInspectionConfig,
65 msg: string,
167
168/**
169 * Helper function to throw HTTP errors with consistent formatting and error codes.
170 *
171 * Creates HTTPException instances with standardized status codes and optional
176 * @param message - Error message to include in the HTTP response body
177 * @param code - Optional error code for categorization and debugging purposes
178 * @returns void - Function throws HTTPException instead of returning
179 * @throws HTTPException - Always throws with provided status and formatted message
180 *
192
193/**
194 * Configuration management functions for error handler settings.
195 */
196
219 *
220 * @param _c - Hono context object (unused but required by middleware signature)
221 * @param next - Next middleware function in the processing chain
222 * @returns Promise<void> - Completes after error handling or next() execution
223 * @throws HTTPException - Converts all errors to HTTPException format for global handler

api_ianmenethil_comcsrf.ts1 match

@ianmenethilโ€ขUpdated 1 day ago
110
111/* helper to throw HTTPException with consistent body */
112function throwCsrfError(message: string, code: string): never {
113 const payload = {
114 error: message,

api_ianmenethil_comcloudflareHelpers.ts10 matches

@ianmenethilโ€ขUpdated 1 day ago
9 * Extracts and parses CF-Visitor header which contains JSON data
10 */
11function parseVisitorHeader(visitorHeader: string | undefined): Record<string, unknown> | null {
12 if (!visitorHeader) return null;
13
23 * Validates and sanitizes coordinate values
24 */
25function parseCoordinate(coord: string | undefined): number | null {
26 if (!coord) return null;
27
33 * Extracts all Cloudflare headers from the request and structures them for use
34 */
35export function extractCloudflareHeaders(c: Context): CloudflareHeaderData {
36 const headers = c.req.raw.headers;
37
104 * Logs CF header data
105 */
106export function logCFData(cfData: CloudflareHeaderData, zid?: string): void {
107 console.log(
108 `[CF-Headers] ${zid ? `[${zid}] ` : ""}Headers processed: ${
113
114/**
115 * Helper function to get Cloudflare data from context
116 */
117export function getCFData(c: Context): CloudflareHeaderData | null {
118 return c.get("cfData") || null;
119}
120
121/**
122 * Helper function to check if request came through Cloudflare
123 */
124export function isCloudflareRequest(c: Context): boolean {
125 const cfData = getCFData(c);
126 return cfData?.hasCloudflareHeaders || false;
128
129/**
130 * Helper function to get geographic summary string
131 */
132export function getGeographicSummary(c: Context): string {
133 const cfData = getCFData(c);
134 if (!cfData) return "Unknown location";
tuna

tuna9 file matches

@jxnblkโ€ขUpdated 1 week ago
Simple functional CSS library for Val Town

getFileEmail4 file matches

@shouserโ€ขUpdated 1 month ago
A helper function to build a file's email
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": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.