import EventEmitter from 'node:events' import type polka from 'polka' /** Represents a browser session. Sessions are automatically persisted (and expired) in Kitten’s internal database. Used by Kitten to provide automatic authentication for Small Web places. You can also add/update arbitrary session data by adding/updating properties on this object in your routes (this object maps a session object in the `kitten._db.sessions` table in the internal database). You can emit events on a session in order to communicate with other browser tabs and windows that share the same session. @example export default function ({ request }) { request.session.kittens ??= { count: 1 } return kitten.html`

Kitten count

${'🐱️'.repeat(request.session.kittens.count++)}

` } @see https://kitten.small-web.org/tutorials/sessions/ @remarks Do not save custom classes on request.session or JSDB will throw an error when it tries to open the internal `_db` database and cannot find your custom class to instantiate. If you want persisted session-level custom objects, store them in your own database table in `kitten.db` keyed by `session.id`. */ import type { Session } from '../Sessions.ts' export type { Session } export type { default as WebSocket, BufferLike } from '../../third-party-libraries-with-missing-type-information/ws/index.d.ts' export type { default as slugify } from '@sindresorhus/slugify' export type Polka = ReturnType export { default as MarkdownIt } from 'markdown-it' export namespace yaml { export function parse(str:string, ...args:any[]): any export function stringify(value:any, ...args:any[]): string } /** Represents an uploaded file. @see https://kitten.small-web.org/tutorials/multipart-forms-and-file-uploads/ */ export type { Upload } from '../routes/PostRoute.ts' /** Abstract base class for lazily-loaded routes. */ export type { default as LazilyLoadedRoute } from '../routes/LazilyLoadedRoute.ts' import type {default as WebSocket, BufferLike } from '../../third-party-libraries-with-missing-type-information/ws/index.d.ts' type WebSocketWithIsAlive = WebSocket & {isAlive:boolean} /** MessageSender class. Provides a namespaced send() method for use in PageSocket. */ export type { MessageSender } from '../lib/KittenPage.ts' /** Kitten component class. */ /** This type definition required due to following shenanigans: https://github.com/Microsoft/TypeScript/issues/20007#issuecomment-2255964704 */ type JavaScriptFunction = (...args: any[]) => any /** A class constructor. */ type Constructor = new (...args: any[]) => T /** Represents the render function of a component that is bound to component (as its `this`). */ type BoundComponentRenderFunction = ((...args: Parameters) => Promise>>) & { boundObject: T } /** An EventEmitter listener with a `remove()` method for cleanup. */ export type { Listener } from '../lib/KittenComponent.ts' /** Kitten Component. A class that makes it easier to author hierarchies of connected components. Handles wiring up and disposal of event listeners for you and gives you an ergonomic, class-based way of writing maintainable applications that take advantage of Kitten’s Streaming HTML workflow while working with well-encapsulated, self-contained components in a clear hierarchy. Extend and instantiate this class to create your own components (components, fragments, layout components, and pages) and provide at least an override for the `html()` method, which is just a function that returns `kitten.html`. The example, below, updates a persisted counter via the + and - buttons (index.page.ts). @example // Initialise the database with a persisted counter object. kitten.db.counter ??= { count: 0 } export default class CounterPage extends kitten.Page { counter constructor () { super() this.counter = this.addChild(new Counter()) } override html () { return kitten.html`

Counter

<${this.counter} /> ` } } class Counter extends kitten.Component { override html () { return kitten.html`
${kitten.db.counter.count}
` } onUpdate (data: { value: number } ) { kitten.db.counter.count += data.value this.update() } } */ import type { default as KittenComponent } from '../lib/KittenComponent.ts' export type { default as KittenComponent } from '../lib/KittenComponent.ts' /** KittenPage class. A KittenPage is a specialised KittenComponent that represents a live page in memory (a live page is one that has an automatic WebSocket connection to the page rendered by the PageRoute). A KittenPage constitutes the root of the server-side component hierarchy. Instance data in a `KittenPage` instance sticks around for the lifetime of the page (e.g., until a reload or a navigation event away from it in the browser). If you need greater persistence, use session storage (`request.session`) or the built-in JSDB database (`kitten.db`). */ import type { default as KittenPage } from '../lib/KittenPage.ts' export type { default as KittenPage } from '../lib/KittenPage.ts' /** Request and response types. These vary per route type but are all built on the base of Polka’s request and response objects which are, themselves, based on the incoming message and server response types of Node’s own http module. */ import type { IncomingMessage, ServerResponse } from 'http' export interface ParsedURL { pathname: string search: string query: Record | void raw: string } export type PolkaResponse = ServerResponse export interface PolkaRequest extends IncomingMessage { url: string method: string originalUrl: string params: Record path: string search: string query: Record body?: any _decoded?: true _parsedUrl: ParsedURL } /** The request objects received by Kitten routes. Based on Polka’s request object with extra Kitten-specific properties and methods. */ export interface KittenRequest extends PolkaRequest { /** The raw body of non-multipart requests. Used, for example, for validation webhook signatures. */ rawBody: Buffer /** Check if the incoming request contains the `"Content-Type"` header field, and, if so, if it contains the specified mime `type`. Examples: // With Content-Type: text/html; charset=utf-8 req.is('html'); req.is('text/html'); req.is('text/*'); // => true // When Content-Type is application/json req.is('json'); req.is('application/json'); req.is('application/*'); // => true req.is('html'); // => false @link https://github.com/expressjs/express/blob/master/lib/request.js#L231 */ is (types:Array|string):string|false|null /** Represents a browser session. Sessions are automatically persisted (and expired) in Kitten’s internal database. Used by Kitten to provide automatic authentication for Small Web places. You can also add/update arbitrary session data by adding/updating properties on this object in your routes (this object maps a session object in the `kitten._db.sessions` table in the internal database). You can emit events on a session in order to communicate with other browser tabs and windows that share the same session. @example export default function ({ request }) { request.session.kittens ??= { count: 1 } return kitten.html`

Kitten count

${'🐱️'.repeat(request.session.kittens.count++)}

` } @see https://kitten.small-web.org/tutorials/sessions/ @remarks Do not save custom classes on request.session or JSDB will throw an error when it tries to open the internal `_db` database and cannot find your custom class to instantiate. If you want persisted session-level custom objects, store them in your own database table in `kitten.db` keyed by `session.id`. */ session: Session & { [key: string]: any } } type TypedArray = Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array /** The response objects received by Kitten routes. Based on Polka’s response object with extra Kitten-specific properties and methods. */ export interface KittenResponse extends PolkaResponse { /** JSON.stringifies passed data and ends response with inline JSON using proper headers. */ json (data:any):void /** JSON.stringifies passed data and ends response with JSON attachment using proper headers and requested file name (or data.json as fallback if no file name is provided). */ jsonFile (data:any, fileName?:string):void /** Ends response with a file. Optionally, uses passed file name (or `'download'` as fallback) and passed mime type (or `'application/octet-stream'` as fallback). */ file (data:string|Buffer|TypedArray|DataView, fileName?:string, mimeType?:string):void /** Ends response with 200 OK response code, and the response body, if any (and `''` if not). @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 */ ok (body?:string):void /** Ends response with 201 Created response code, and the response body, if any (and `''` if not). @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 */ created (body?:string):void /** Ends response with redirect via a GET request (303 See Other) to given location. Alias: seeOther */ get (location:string):void /** Alias for {@link get}. */ seeOther (location:string):void /** Redirect (temporary; 307) to requested location without changing the request method. */ redirect (location:string):void /** Alias for {@link redirect}. */ temporaryRedirect (location:string):void /** Redirect (permanentl 308) to requested location without changing the request method. */ permanentRedirect (location:string):void /** 400 Bad Request Indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). @link https://httpwg.org/specs/rfc9110.html#rfc.section.15.5.1 */ badRequest (body?:string):void /** “401 Unauthorized” (actually, unauthenticated) response. Aliases: unauthorised, unauthorized. */ unauthenticated (body?:string):void /** Alias for {@link unauthenticated}. */ unauthorised (body?:string):void /** Alias for {@link unauthenticated}. */ unauthorized (body?:string):void /** 403 Forbidden response. This should be returned if the request is authenticated but lacks the authorisation (i.e., sufficient rights) to access the resource. If the request requires authentication but has not been authenticated, you should return a “401 Unauthorized” (actually: unauthenticated) response. @see unauthenticated */ forbidden (body?:string):void /** 404 Not Found response. */ notFound (body?:string):void /** 500 Internal Server Error response. Alias: internalServerError. */ error (body?:string):void /** Alias for {@link error}. */ internalServerError (body?:string):void /** General shorthand helper for setting the status code and ending the response with an optional body. */ withCode (statusCode:number, body?:string):void } /** The signature of Kitten route handlers and middleware. Like polka’s own `Middleware` type but with Kitten’s request and response objects (Kitten’s middleware mixes the helper methods into every request and response before any route handler runs). */ export type KittenHandler = ( request: KittenRequest, response: KittenResponse, next: polka.NextHandler ) => void | Promise type RoutePattern = RegExp | string /** The Kitten server’s polka app. A polka instance whose handlers receive Kitten’s request and response objects. */ export interface KittenPolka extends Omit< Polka, 'find' | 'add' | 'use' | 'all' | 'get' | 'head' | 'patch' | 'options' | 'connect' | 'delete' | 'trace' | 'post' | 'put' | 'wares' | 'onError' | 'onNoMatch' | 'handler' > { handler: KittenHandler find(method: string, url: string): { params: Record handlers: KittenHandler[] } add(method: string, pattern: RoutePattern, ...handlers: KittenHandler[]): this use(pattern: RoutePattern, ...handlers: (KittenPolka | KittenHandler)[]): this use(...handlers: (KittenPolka | KittenHandler)[]): this all(pattern: RoutePattern, ...handlers: KittenHandler[]): this get(pattern: RoutePattern, ...handlers: KittenHandler[]): this head(pattern: RoutePattern, ...handlers: KittenHandler[]): this patch(pattern: RoutePattern, ...handlers: KittenHandler[]): this options(pattern: RoutePattern, ...handlers: KittenHandler[]): this connect(pattern: RoutePattern, ...handlers: KittenHandler[]): this delete(pattern: RoutePattern, ...handlers: KittenHandler[]): this trace(pattern: RoutePattern, ...handlers: KittenHandler[]): this post(pattern: RoutePattern, ...handlers: KittenHandler[]): this put(pattern: RoutePattern, ...handlers: KittenHandler[]): this } /** Kitten’s POST request object. If the POST route had a multi-part form with file uploads, they will be handled automatically by Kitten and you can find them in the `uploads` property. @see https://kitten.small-web.org/tutorials/multipart-forms-and-file-uploads/ */ export interface KittenPostRequest extends KittenRequest { uploads: Upload[] } /* Crypto */ type Hex = Uint8Array | string; type PrivKey = Hex | bigint | number; export class Point { readonly x: bigint; readonly y: bigint; static BASE: Point; static ZERO: Point; _WINDOW_SIZE?: number; constructor(x: bigint, y: bigint); _setWindowSize(windowSize: number): void; static fromHex(hex: Hex, strict?: boolean): Point; static fromPrivateKey(privateKey: PrivKey): Promise; toRawBytes(): Uint8Array; toHex(): string; toX25519(): Uint8Array; isTorsionFree(): boolean; equals(other: Point): boolean; negate(): Point; add(other: Point): Point; subtract(other: Point): Point; multiply(scalar: number | bigint): Point; } export class Signature { readonly r: Point; readonly s: bigint; constructor(r: Point, s: bigint); static fromHex(hex: Hex): Signature; assertValidity(): this; toRawBytes(): Uint8Array; toHex(): string; }