### HTM Component Syntax Example Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows correct usage of HTM syntax for component mounting to maintain component identity. ```javascript // ✅ Correct - proper component identity <${MyComponent} prop=${value} /> ``` -------------------------------- ### Sentry.init with skipOpenTelemetrySetup Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/sentry-tracing-options.md Initializes Sentry for error reporting while skipping OpenTelemetry setup, keeping OTel ownership in packages/web/otel.js. ```javascript Sentry.init({ dsn: sentryDsn, environment: sentryEnvironment, release: sentryRelease, skipOpenTelemetrySetup: true, }) ``` -------------------------------- ### Component Naming Convention Examples Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows correct capitalized component names and incorrect lowercase names for function components. ```javascript // ✅ Good - capitalized component names export const ArticleHeader = ({ title, publishDate }) => { ... } export const Breadcrumb = ({ pathSegments }) => { ... } // ❌ Avoid - lowercase function names export const articleHeader = ({ title, publishDate }) => { ... } export const breadcrumb = ({ pathSegments }) => { ... } ``` -------------------------------- ### Wire Sentry into existing OTel setup with @sentry/opentelemetry Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/sentry-tracing-options.md Configure Sentry to export spans through an existing OpenTelemetry setup by setting skipOpenTelemetrySetup: true and wiring Sentry's propagator, sampler, span processor, and context manager into the NodeSDK. Requires @sentry/opentelemetry and preserves Prometheus metrics and custom Fastify instrumentation. ```javascript import { SentryAsyncLocalStorageContextManager, SentryPropagator, SentrySampler, SentrySpanProcessor, setupEventContextTrace, setOpenTelemetryContextAsyncContextStrategy, } from '@sentry/opentelemetry' Sentry.init({ dsn: sentryDsn, environment: sentryEnvironment, release: sentryRelease, skipOpenTelemetrySetup: true, tracesSampleRate: Number(process.env['SENTRY_TRACES_SAMPLE_RATE'] ?? '0.05'), }) const sentryClient = Sentry.getClient() setupEventContextTrace(sentryClient) export const sdk = new NodeSDK({ sampler: new SentrySampler(sentryClient), spanProcessors: [ new SentrySpanProcessor(), ], textMapPropagator: new SentryPropagator(), contextManager: new SentryAsyncLocalStorageContextManager(), metricReader: new PrometheusExporter({ port: 9091 }), instrumentations: [ new HttpInstrumentation(), new RuntimeNodeInstrumentation({ monitoringPrecision: 5000 }), new FastifyOtelInstrumentation({ registerOnInitialization: true, ignorePaths: routeOptions => routeOptions.url in ignoredRoutes, }), ], }) sdk.start() setOpenTelemetryContextAsyncContextStrategy() ``` -------------------------------- ### Typed Component Helper (tc) Example Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Provides a typed component helper for better type checking with HTM, including usage example. ```javascript /** * Typed component helper for better type checking with HTM * @template T * @param {FunctionComponent} component * @param {T} props */ export const tc = (component, props) => html`<${component} ...${props} />` // Usage with full type checking: ${tc(MyComponent, { prop: value, onSave: handler })} ``` -------------------------------- ### Sentry tracing with Breadcrum metrics setup Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/sentry-tracing-options.md Configures Sentry to own tracing via Sentry.init with fastifyIntegration, while Breadcrum sets up its own metrics with a NodeSDK using PrometheusExporter, RuntimeNodeInstrumentation, and HostMetrics. This sketch intentionally removes FastifyOtelInstrumentation and HttpInstrumentation to avoid overlapping with Sentry tracing ownership. ```javascript Sentry.init({ dsn: sentryDsn, environment: sentryEnvironment, release: sentryRelease, tracesSampleRate: Number(process.env['SENTRY_TRACES_SAMPLE_RATE'] ?? '0.05'), integrations: [ Sentry.fastifyIntegration(), ], }) export const sdk = new NodeSDK({ metricReader: new PrometheusExporter({ port: 9091 }), instrumentations: [ new RuntimeNodeInstrumentation({ monitoringPrecision: 5000 }), ], }) sdk.start() new HostMetrics({ meterProvider: metrics.getMeterProvider() }).start() ``` -------------------------------- ### Regular imports use standard syntax - type vs regular import distinction Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows that `@import` is for types only, while regular imports use standard ES module syntax. This example demonstrates the correct usage for a type import and a regular import. ```javascript /** @import {QueryResult} from 'pg' */ // Type import import { Pool } from 'pg' // Regular import for the actual Pool class ``` -------------------------------- ### HTM single interpolation per attribute (guideline example) Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Repeats the HTM constraint with a wrong and correct example for single interpolation per attribute. ```js // ❌ Wrong - multiple interpolations class="${someClass} ${anotherClass}" // ✅ Correct - single interpolation class="${`${someClass} ${anotherClass}`}" ``` -------------------------------- ### GET /discover route request Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md HTTP request format for the new /discover route. The route mirrors routes/unified/routes.js but calls runTask({ url, format, metadataOnly: true }) for YouTube URLs and the Python yt-dlp server's /discover endpoint for non-YouTube URLs. The response schema has no url field. ```http GET /discover?url=&format= ``` -------------------------------- ### HTM single interpolation per attribute (invalid and valid examples) Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows the HTM constraint: only one tagged template interpolation per HTML attribute. The invalid example uses two interpolations; the valid examples use template literals or string concatenation to combine values. ```javascript // ❌ Won't work - multiple interpolations class="${someClass} ${anotherClass}" // ✅ Works - single interpolation class="${`${someClass} ${anotherClass}`}" class="${someClass + ' ' + anotherClass}" ``` -------------------------------- ### tc Usage for Complex Props Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows usage of the tc helper for complex props to get better type checking. ```javascript ${tc(ArticleHeader, { title: vars.title, authorImgUrl: null, authorImgAlt: null, publishDate: vars.publishDate, updatedDate: vars.updatedDate })} ``` -------------------------------- ### Use classnames for conditional classes Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Import classnames as cn and use it for conditional class toggling in HTM templates. The example shows how to conditionally apply classes based on boolean flags. ```javascript import cn from 'classnames' // Use cn for conditional classes class="${cn({ 'bc-item': true, 'bc-item-active': isActive, 'bc-item-disabled': isDisabled })}" ``` -------------------------------- ### Sentry.init with fastifyIntegration and tracesSampleRate Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/sentry-tracing-options.md Configures Sentry to own tracing and Fastify instrumentation, with a traces sample rate from SENTRY_TRACES_SAMPLE_RATE (default 0.05) and a custom error handler. ```javascript Sentry.init({ dsn: sentryDsn, environment: sentryEnvironment, release: sentryRelease, tracesSampleRate: Number(process.env['SENTRY_TRACES_SAMPLE_RATE'] ?? '0.05'), integrations: [ Sentry.fastifyIntegration({ shouldHandleError (error, _request, reply) { return shouldHandleSentryError(error, reply.statusCode) }, }), ], }) ``` -------------------------------- ### Create users table with pgcrypto Source: https://github.com/hifiwi-fi/breadcrum.net/wiki/Notes Enables the pgcrypto extension and creates a users table with an id, unique email, and password column for storing hashed passwords. ```sql CREATE EXTENSION pgcrypto; CREATE TABLE users ( id SERIAL PRIMARY KEY, email TEXT NOT NULL UNIQUE, password TEXT NOT NULL ); ``` -------------------------------- ### Update episodes/index.js to use getYTDLPDiscoveryMetadata Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md Replace the getYTDLPMetadata call with getYTDLPDiscoveryMetadata in packages/worker/workers/episodes/index.js. The before version checks media.url and throws an error; the after version omits that check because discovery doesn't return a url. ```javascript // Before: const media = await getYTDLPMetadata({ url, medium, ytDLPEndpoint, attempt: 0, cache, maxRetries: 0, }) // ... if (!media?.url) { throw new Error('No video URL was found in discovery step') } // After: const media = await getYTDLPDiscoveryMetadata({ url, medium, ytDLPEndpoint, attempt: 0, cache, maxRetries: 0, }) // No url check — discovery doesn't return a url ``` -------------------------------- ### Sentry.setupFastifyErrorHandler Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/sentry-tracing-options.md Sets up Sentry's Fastify error handler with a custom shouldHandleError callback that delegates to shouldHandleSentryError. ```javascript Sentry.setupFastifyErrorHandler(fastify, { shouldHandleError (error, _request, reply) { return shouldHandleSentryError(error, reply.statusCode) }, }) ``` -------------------------------- ### Add /discover endpoint to yt_dlp_api.py Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md Flask endpoint for /discover in ytdlp-server/yt_dlp_api.py. Uses yt-dlp's extract_info with download=False and process=False to return the raw info dictionary without resolving format URLs. Requires a url query parameter; aborts with 400 if missing and 500 on any exception. ```python @app.route('/discover', methods=['GET']) def video_discover(): url = request.args.get('url') if url is None: abort(400, 'url querystring required') ydl_opts = { 'noplaylist': True, } with yt_dlp.YoutubeDL(ydl_opts) as ydl: try: info = ydl.extract_info(url, download=False, process=False) return jsonify(ydl.sanitize_info(info)) except Exception as e: abort(500, str(e)) ``` -------------------------------- ### HTM Syntax for Simple Props Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows HTM component syntax for simple props, recommended for better performance. ```javascript <${Header} /> <${Breadcrumb} pathSegments=${pathSegments} /> ``` -------------------------------- ### Response schema for /discover Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md Response schema for the /discover route. It is a subset of the unified response schema, notably without the url field. Fields include filesize_approx, duration, channel, title, ext, _type, description, uploader_url, channel_url, thumbnail, live_status, and release_timestamp. ```json { "filesize_approx": number | null, "duration": number | null, "channel": string | null, "title": string | null, "ext": string | null, "_type": string | null, "description": string | null, "uploader_url": string | null, "channel_url": string | null, "thumbnail": string | null, "live_status": string | null, "release_timestamp": number | null } ``` -------------------------------- ### Avoid any types - discouraged and recommended patterns Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows discouraged usage of `any` types and the recommended specific type annotations. Use specific object types instead of `any` to describe data structures. ```javascript // ❌ Avoid const data: any = {...} // ❌ Avoid function process(item: any) {...} ``` ```javascript // ✅ Good const data: { id: number, name: string } = {...} // ✅ Good function process(item: { id: number, name: string }) {...} ``` -------------------------------- ### Verify password with crypt and show results Source: https://github.com/hifiwi-fi/breadcrum.net/wiki/Notes Verifies a user's password by comparing the stored hash with the provided password. The first query returns the user id for a correct password, while the second returns no rows for an incorrect one. ```sql SELECT id FROM users WHERE email = 'johndoe@mail.com' AND password = crypt('johnspassword', password); id ---- 1 (1 row) SELECT id FROM users WHERE email = 'johndoe@mail.com' AND password = crypt('wrongpassword', password); id ---- (0 rows) ``` -------------------------------- ### Backfill migration 030.do SQL Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/worker-resolution-audit.md One-time backfill migration (030.do) that clears existing stuck records using the same logic as the cleanup job. Bookmarks and archives are updated without a time filter, while episodes are limited to those older than 7 days to preserve legitimately upcoming ones. ```sql UPDATE bookmarks SET done = true, error = 'Timed out: marked done by backfill migration' WHERE done = false; ``` ```sql UPDATE archives SET done = true, error = 'Timed out: marked done by backfill migration' WHERE done = false; ``` ```sql UPDATE episodes SET done = true, error = 'Timed out: marked done by backfill migration' WHERE done = false AND created_at < NOW() - INTERVAL '7 days'; ``` -------------------------------- ### Add getYTDLPDiscoveryMetadata() to yt-dlp-api-client.js Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md New exported function in packages/resources/episodes/yt-dlp-api-client.js that calls /discover instead of /unified. Returns YTDLPDiscoveryMetadata (no url field) and initially has no internal retry wrapper; YouTube keeps the same 3-retry default. ```javascript /** * @typedef {Omit} YTDLPDiscoveryMetadata */ export async function getYTDLPDiscoveryMetadata({ url, medium, ytDLPEndpoint, attempt = 0, cache, maxRetries, retryDelayMs = 5000, }) { // same retry wrapper logic as getYTDLPMetadata // calls internal getYTDLPDiscoveryMetadataAttempt // which sets requestURL.pathname = 'discover' } ``` -------------------------------- ### Regular imports consolidated normally - standard ES module syntax Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows the recommended way to consolidate regular imports using standard ES module syntax. This is separate from type imports which use `@import`. ```javascript // ✅ Regular imports consolidated normally import { render, hydrate } from 'preact' import { Pool, Client } from 'pg' ``` -------------------------------- ### Consolidate type imports from same module - discouraged and recommended patterns Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows the discouraged separate type imports from the same module and the recommended consolidated `@import` statement. Combine multiple type imports from the same module into a single statement. ```javascript // ❌ Avoid separate type imports from same module /** @import { FunctionComponent } from 'preact' */ /** @import { ComponentChild } from 'preact' */ /** @import { QueryResult } from 'pg' */ /** @import { Pool } from 'pg' */ ``` ```javascript // ✅ Consolidate type imports from same module /** @import { FunctionComponent, ComponentChild } from 'preact' */ /** @import { QueryResult, Pool } from 'pg' */ ``` -------------------------------- ### getBasicInfoMetadata() in lib/onesie/index.js Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md Adds a new export to lib/onesie/index.js that resolves a YouTube URL to a videoId and fetches metadata via innertube.getBasicInfo() without URL decipher. Returns a discovery-only object with fields like title, duration, channel, thumbnail, live_status, and release_timestamp; url is intentionally absent. Requires an existing innertube instance and formatSelector. ```javascript /** * Resolve a YouTube URL to a videoId and fetch metadata without URL decipher. * Uses innertube.getBasicInfo() — one request, no encryption, no decipher. * * @param {string} youtubeUrl * @param {OnesieFormat} format * @param {InnerTube} innertube */ export async function getBasicInfoMetadata(youtubeUrl, format, innertube) { // resolveURL already used in onesieRequest — reuse same pattern const resolved = await innertube.resolveURL(youtubeUrl) const videoId = resolved.payload.videoId if (!videoId) throw new Error('No videoId resolved') const info = await innertube.getBasicInfo(videoId) const is_upcoming = info.basic_info.is_upcoming return { title: info.basic_info.title, duration: info.basic_info.duration, filesize_approx: null, // not available without format processing channel: info.basic_info.channel?.name ?? null, description: info.basic_info.short_description ?? null, channel_url: info.basic_info.channel?.url ?? null, uploader_url: info.basic_info.channel?.url ?? null, ext: formatSelector[format].format, _type: format, thumbnail: info.basic_info.thumbnail?.[0]?.url ?? null, // url intentionally absent — this is discovery only live_status: is_upcoming ? 'is_upcoming' : (info.basic_info.is_live ? 'is_live' : null), release_timestamp: info.basic_info.start_timestamp ? Math.floor(info.basic_info.start_timestamp.getTime() / 1000) : null, } } ``` -------------------------------- ### Schema-Based Route Definitions in Fastify Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Always import and use predefined schemas instead of inline definitions. Use the `FastifyPluginAsyncJsonSchemaToTs` type with `SerializerSchemaOptions` to handle deserialization of date-time strings to `Date` objects. The route handler is typed with the schema's response. ```javascript // ✅ Good - use imported schemas import { schemaUserRead } from './schemas/schema-user-read.js' /** * @type {FastifyPluginAsyncJsonSchemaToTs<{ * SerializerSchemaOptions: { * deserialize: [{ pattern: { type: 'string'; format: 'date-time'; }; output: Date; }] * } * }>} */ export async function getUser (fastify, _opts) { fastify.get('/', { schema: { response: { 200: schemaUserRead } } }, async function getUserHandler (request, reply) { // handler implementation }) } ``` -------------------------------- ### Preact Component Type Import Syntax Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Always use the `@import` syntax for Preact component types at the top of the file. Avoid inline type imports like `import('preact').ComponentChild`. Use regular imports for actual Preact functions and components. ```javascript /** * @import { FunctionComponent, ComponentChild, JSX } from 'preact' */ ``` ```javascript // ❌ Avoid inline type imports legend?: string | import('preact').ComponentChild // ✅ Use @import syntax for types /** @import { ComponentChild } from 'preact' */ legend?: string | ComponentChild ``` ```javascript /** @import { FunctionComponent } from 'preact' */ // Type import import { render } from 'preact' // Regular import import { html } from 'htm/preact' // Regular import ``` -------------------------------- ### Insert user with hashed password Source: https://github.com/hifiwi-fi/breadcrum.net/wiki/Notes Inserts a new user with a bcrypt-hashed password using the crypt and gen_salt functions from pgcrypto. ```sql INSERT INTO users (email, password) VALUES ( 'johndoe@mail.com', crypt('johnspassword', gen_salt('bf')) ); ``` -------------------------------- ### Use @ts-expect-error over @ts-ignore - recommended and discouraged patterns Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows the recommended `@ts-expect-error` and the discouraged `@ts-ignore` for error suppression. `@ts-expect-error` fails if the error is fixed, alerting to remove the comment. ```javascript // ✅ Good - will fail if error is fixed, alerting us to remove the comment // @ts-expect-error - No type definitions available for @breadcrum/bookmarklet import getBookmarklet from '@breadcrum/bookmarklet' ``` ```javascript // ❌ Avoid - continues to suppress even when unnecessary // @ts-ignore - No type definitions available for @breadcrum/bookmarklet import getBookmarklet from '@breadcrum/bookmarklet' ``` -------------------------------- ### handleOnesieRequest with metadataOnly flag in lib/onesie-worker.js Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/media-discovery-extraction-split.md Updates lib/onesie-worker.js to handle a new optional metadataOnly flag in the OnesieRequest task data. When metadataOnly is true, it calls getBasicInfoMetadata without tvConfig; otherwise it falls back to the existing onesieFormatRequest path. ```javascript /** * @typedef {Object} OnesieRequest * @property {string} url * @property {OnesieFormat} format * @property {boolean} [returnRedirectUrl] // used by unified (existing) * @property {boolean} [metadataOnly] // used by discover (new) */ const handleOnesieRequest = async (taskData) => { const { url, format, returnRedirectUrl = true, metadataOnly = false } = taskData if (metadataOnly) { return getBasicInfoMetadata(url, format, innertube) // no tvConfig needed } else { return onesieFormatRequest(url, format, innertube, tvConfig, returnRedirectUrl) } } ``` -------------------------------- ### Return Value Pattern: Explicit Status Code vs Implicit Return Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Always use reply.code().send() for explicit status codes and proper type narrowing. The good pattern ensures explicit HTTP status codes, proper type extraction with ExtractResponseType, type safety for response bodies, and consistent error handling. ```javascript // ✅ Good - explicit status code with send return reply.code(201).send({ token, auth_token: authToken, }) // ❌ Avoid - implicit return without status code return { token, auth_token: authToken, } ``` -------------------------------- ### Prefer Schema-Based Types Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Always import types from schema files instead of redefining them manually. This ensures a single source of truth for types, automatic updates when schemas change, and consistency across components. ```javascript // ✅ Good - import from schema /** @import { TypeArchiveReadClient } from '../../../routes/api/archives/schemas/schema-archive-read.js' */ archive: TypeArchiveReadClient // ❌ Avoid - manual type definition archive: { id: string, title: string, url: string, // ... many more fields } ``` -------------------------------- ### TypeScript DOM reference pragma for client code Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Place at the top of client-side files in packages/web/client to enable DOM type checking in editors. Required for all browser-running code. ```js /// ``` -------------------------------- ### Direct Function Call Anti-Patterns Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Demonstrates dangerous direct calls to Preact components that break reconciliation and hooks. ```javascript // ❌ DANGEROUS - breaks React/Preact reconciliation and hooks ${MyComponent({ prop: value })} // ❌ DANGEROUS - direct function calls break everything MyComponent() // ❌ DANGEROUS - even in tests and page wrappers export default () => { return Page() // This breaks hooks! } ``` -------------------------------- ### Use newer @import syntax in jsdoc/ts-in-js for types only - discouraged and recommended patterns Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows the discouraged inline type import and the recommended placement of `@import` near top-level imports. `@import` is for type imports only; regular imports use standard ES module syntax. ```javascript /** @import {QueryResult} from 'pg' */ /** @type {QueryResult} */ const results = await client.query(query) ``` ```javascript /** @import {QueryResult} from 'pg' */ // Other imports/code... /** @type {QueryResult} */ const results = await client.query(query) ``` -------------------------------- ### Undo migration 030.undo SQL Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/worker-resolution-audit.md Undo migration for the backfill, which is a no-op because the lost state cannot be restored after setting stuck records to done=true. ```sql -- 030.undo.mark-stale-resolutions-done.sql -- No-op: cannot restore stuck records to done=false after backfill ``` -------------------------------- ### Import classnames for conditional classes Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Always import classnames as cn for conditional class toggles in HTM templates. ```js import cn from 'classnames' ``` -------------------------------- ### Prefer type updates over conditional object spreads - discouraged and recommended patterns Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Contrasts conditional object spreads with a more accurate parameter declaration. Use conditional spreads only when runtime behavior intentionally distinguishes absent from undefined properties. ```javascript // ❌ Avoid type-driven object construction noise await createBookmark({ url, ...(note !== undefined ? { note } : {}), ...(summary !== undefined ? { summary } : {}), }) ``` ```javascript // ✅ Prefer an accurate parameter declaration /** * @param {Object} params * @param {string} params.url * @param {string | undefined} [params.note] * @param {string | undefined} [params.summary] */ async function createBookmark ({ url, note, summary }) { // ... } await createBookmark({ url, note, summary }) ``` -------------------------------- ### Schema Type Exports with FromSchema Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Where you define schemas, always export a FromSchema type without deserialization options for use in other parts of the application. This provides a base type that can be imported and used throughout the application without route-specific deserialization transformations. ```javascript /** * @import { JSONSchema, FromSchema } from 'json-schema-to-ts' * @typedef {typeof schemaUserRead} SchemaUserRead * @typedef {FromSchema} TypeUserRead */ export const schemaUserRead = /** @type {const} @satisfies {JSONSchema} */ ({ type: 'object', // ... schema definition }) ``` -------------------------------- ### String concatenation with preact-render-to-string for multi-child fragments Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Use preact-render-to-string to render components to strings and concatenate with string HTML content. Necessary because the html tagged template expects proper template syntax, not arbitrary string interpolation. ```js import { render } from 'preact-render-to-string' // Render components to strings and concatenate const headerContent = html`

${args.vars.title}

` const wrappedChildren = typeof children === 'string' ? render(headerContent) + children // String concatenation : html` ${headerContent} ${children} ` ``` -------------------------------- ### Package Import Aliases for Cross-Area Imports Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Use package `imports` aliases (e.g., `#test/helper.js`) for cross-area imports to avoid deep relative paths. Keep relative imports for nearby sibling files in the same feature folder. When a package import maps to a TypeScript source file, use the runtime `.js` specifier and let `package.json#imports` map it to the `.ts` source for type checking. ```javascript // ✅ Cross-area imports use package aliases import { build } from '#test/helper.js' import { defaultFrontendFlags } from '#plugins/flags/frontend-flags.js' /** @import { TypeUserRead } from '#routes/api/user/schemas/schema-user-read.js' */ // ✅ Local sibling imports stay relative import { getSearchBookmarksQuery } from './get-search-bookmarks-query.js' ``` ```javascript /** @import { ExtractKnownResponseType } from '#types/fastify-utils.js' */ ``` -------------------------------- ### HTML comment for TODO in HTM Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Use HTML-style comments for TODO items or disabled functionality in HTM templates. ```js ``` -------------------------------- ### Typing Database Query Results with pg Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md When working with PostgreSQL queries using `pg`, declare the type on the variable to avoid casting. Use `/** @type {QueryResult} */` to type the results, providing proper typing for `results.rows`, `results.rows[0]`, and other properties like `rowCount` and `fields`. This is preferable to casting the return value. ```javascript /** @import {QueryResult} from 'pg' */ /** @type {QueryResult} */ const results = await client.query(query) return results.rows[0] // Automatically typed as TypeUserRead | undefined ``` ```javascript // Avoid this pattern when possible const results = await client.query(query) return /** @type {TypeUserRead | undefined} */ (results.rows[0]) ``` -------------------------------- ### Required Nullable Fields vs Optional Fields Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Prefer required nullable fields over optional fields in schemas for consistency and clarity. This pattern ensures consistent handling of null vs undefined, better alignment with database query results, and clearer API contracts. ```javascript // ✅ Good - required nullable field { type: 'object', required: ['id', 'name', 'updated_at'], properties: { id: { type: 'string' }, name: { type: 'string' }, updated_at: { type: 'string', nullable: true, format: 'date-time' } } } // ❌ Avoid - optional field { type: 'object', required: ['id', 'name'], properties: { id: { type: 'string' }, name: { type: 'string' }, updated_at: { type: 'string', format: 'date-time' } } } ``` -------------------------------- ### Date Deserialization with SerializerSchemaOptions Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Use the SerializerSchemaOptions.deserialize option to automatically convert date-time strings to Date objects on the server side. This ensures date-time fields in responses are properly typed as Date | null for nullable fields, or Date for non-nullable fields. ```javascript /** * @type {FastifyPluginAsyncJsonSchemaToTs<{ * SerializerSchemaOptions: { * deserialize: [{ pattern: { type: 'string'; format: 'date-time'; }; output: Date | null; }] * } * }>} */ ``` -------------------------------- ### Database Query Types with JSDoc and SQL Tag Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Define query result types next to your queries, separate from schemas, to ensure query types align with schema types. This pattern ensures query types are maintained alongside query definitions, easy verification that database types match schema expectations, and clear documentation of what the database returns. ```javascript /** * @typedef {Object} UserRow * @property {string} id - User UUID * @property {string} name - User name * @property {Date|null} updated_at - Last update time * @property {string} email - User email */ const getUserQuery = SQL` SELECT id, name, updated_at, email FROM users WHERE id = ${userId} ` /** @type {QueryResult} */ const result = await fastify.pg.query(getUserQuery) ``` -------------------------------- ### Conditional spread for optional header - Undici request headers exception Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Shows the concrete exception where conditional spread is used to omit an optional header because header values cannot be undefined. Use this pattern for request headers. ```javascript const response = await request(url, { headers: { Accept: 'application/json', ...(parentRequestId ? { 'X-Breadcrum-Request-Id': parentRequestId } : {}), }, }) ``` -------------------------------- ### Nightly stale record cleanup SQL Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/plans/worker-resolution-audit.md Nightly cleanup job SQL statements that mark records stuck pending for over 24 hours as done with a generic error message. The episodes statement may incorrectly mark upcoming episodes (which legitimately have done=false) as failed; the recommendation is to use a 7-day window for episodes instead. ```sql UPDATE bookmarks SET done = true, error = 'Timed out: marked done by cleanup job' WHERE done = false AND created_at < NOW() - INTERVAL '24 hours' ``` ```sql UPDATE episodes SET done = true, error = 'Timed out: marked done by cleanup job' WHERE done = false AND created_at < NOW() - INTERVAL '24 hours' ``` ```sql UPDATE archives SET done = true, error = 'Timed out: marked done by cleanup job' WHERE done = false AND created_at < NOW() - INTERVAL '24 hours' ``` -------------------------------- ### Nullable Fields in Schemas: nullable Property vs Type Arrays Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md For nullable fields in JSON schemas, use the nullable: true property instead of type arrays. This ensures proper JSON Schema validation and TypeScript type generation. ```javascript // ✅ Good - use nullable property { type: 'string', nullable: true, format: 'date-time', description: 'Optional date field' } // ❌ Avoid - type arrays for nullable { type: ['string', 'null'], format: 'date-time', description: 'Optional date field' } ``` -------------------------------- ### Form Element Access Pattern with Type Casting Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md When accessing form elements through refs, use proper type casting with null checks. Cast `formRef.current` to `HTMLFormElement | null` and then cast the result of `form.elements.namedItem('title')` to `HTMLInputElement | null`. Always check for null before using the element. ```javascript const form = /** @type {HTMLFormElement | null} */ (/** @type {unknown} */ (formRef.current)) if (!form) return const titleElement = /** @type {HTMLInputElement | null} */ (form.elements.namedItem('title')) if (!titleElement) return const title = titleElement.value ``` -------------------------------- ### dangerouslySetInnerHTML for single element string content Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Use this pattern in layouts when rendering string HTML content into a single element. It conditionally uses dangerouslySetInnerHTML for strings or normal children otherwise. ```js ${typeof children === 'string' ? html`
` : html`
${children}
` } ``` -------------------------------- ### Response Type Extraction with ExtractResponseType Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Extract response types using ExtractResponseType with the specific status code. This pattern ensures explicit HTTP status codes and proper type narrowing for response bodies. ```javascript /** * @import { ExtractResponseType } from '../../../../types/fastify-utils.js' */ async function handler (request, reply) { /** @typedef {ExtractResponseType>} ReturnBody */ /** @type {ReturnBody} */ const returnBody = { // properly typed response data } return reply.code(200).send(returnBody) } ``` -------------------------------- ### Error Handling in Components with Type Casting Source: https://github.com/hifiwi-fi/breadcrum.net/blob/master/AGENTS.md Always type-cast errors and check for optional callbacks. In the catch block, cast `err` to `Error` using JSDoc type assertion. This ensures proper error handling and type safety. ```javascript try { if (onSave) await onSave(formState) } catch (err) { setError(/** @type {Error} */(err)) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.