tina4-nodejs 3.13.157 → 3.13.158

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -222,6 +222,44 @@ export class QueryBuilder {
222
222
  return this;
223
223
  }
224
224
 
225
+ /**
226
+ * Set OFFSET (rows to skip) as its own chainable verb.
227
+ *
228
+ * `limit(n, offset)` buries the offset as a second positional arg; this
229
+ * exposes it on its own, so `.offset(20).limit(10)` reads naturally and
230
+ * matches the SQL keyword.
231
+ *
232
+ * @param count - Number of rows to skip.
233
+ * @returns this for chaining.
234
+ */
235
+ offset(count: number): QueryBuilder {
236
+ this.offsetVal = count;
237
+ return this;
238
+ }
239
+
240
+ /**
241
+ * Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
242
+ *
243
+ * Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
244
+ * already emits, so a query reads the same whether it targets SQL or MongoDB.
245
+ *
246
+ * @param count - Number of rows to skip.
247
+ * @returns this for chaining.
248
+ */
249
+ skip(count: number): QueryBuilder {
250
+ return this.offset(count);
251
+ }
252
+
253
+ /**
254
+ * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
255
+ *
256
+ * @param count - Maximum rows to return.
257
+ * @returns this for chaining.
258
+ */
259
+ take(count: number): QueryBuilder {
260
+ return this.limit(count);
261
+ }
262
+
225
263
  /**
226
264
  * Build and return the SQL string without executing.
227
265
  *
@@ -1,6 +1,8 @@
1
1
  export type { Tina4Request, Tina4Response, RouteHandler, RouteDefinition, RouteMeta, Tina4Config, Middleware, MiddlewareClass, MiddlewareSpec, UploadedFile, CookieOptions, WebSocketRouteHandler, WebSocketRouteDefinition, } from "./types.js";
2
2
  export { startServer, resolvePortAndHost, loopbackBindHosts, handle, start, stop, httpReason, resolveTemplate, resetTemplateCache, templateAutoRoutingEnabled, isBannerSuppressed } from "./server.js";
3
3
  export { background, stopAllBackgroundTasks, backgroundTaskCount } from "./background.js";
4
+ export { tcpService, tcp, TcpService, TcpConnection, registeredTcpServices, clearTcpRegistry, startAllTcpServices, stopAcceptingAllTcpServices, drainAllTcpServices, } from "./tcp.js";
5
+ export type { TcpServiceOptions, TcpConnectHandler, TcpDataHandler, TcpCloseHandler, TcpLineHandler, } from "./tcp.js";
4
6
  export { Router, RouteGroup, RouteRef, WsRouteRef, defaultRouter, runRouteMiddlewares, resolveStringMiddleware, isTrailingSlashRedirectEnabled } from "./router.js";
5
7
  export { get, post, put, patch, del, any, websocket, del as delete } from "./router.js";
6
8
  export type { RouteInfo } from "./router.js";
@@ -104,7 +104,7 @@ export declare class Queue {
104
104
  * - new Queue("mongodb", { path: "data/queue" }) // legacy
105
105
  * - new Queue() // file backend, default topic
106
106
  *
107
- * Throws on backend "rabbitmq" or "kafka" (ADR-0022).
107
+ * Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
108
108
  */
109
109
  constructor(backendOrConfig?: string | QueueConfig, config?: QueueConfig);
110
110
  /**
@@ -53,8 +53,6 @@ export declare function kafkaSecurityConfig(env?: NodeJS.ProcessEnv): KafkaSecur
53
53
  * convention name (`KAFKA_AUTO_OFFSET_RESET`) — the same precedence the TLS/SASL
54
54
  * keys use. A blank value falls through to the default (tina4-nodejs#263).
55
55
  *
56
- * Surfaced on the declared consumer config for parity/introspection; this
57
- * backend reads records over the raw protocol from the earliest retained offset.
58
56
  * Mirrors Python's `KafkaConnector._offset_reset`.
59
57
  */
60
58
  export declare function kafkaOffsetReset(env?: NodeJS.ProcessEnv): string;
@@ -65,76 +63,72 @@ export interface QueueBackend {
65
63
  clear(queue: string): void;
66
64
  }
67
65
  /**
68
- * Kafka queue backend using raw Kafka protocol over TCP.
69
- *
70
- * Uses synchronous-style communication by spawning a child process
71
- * for each operation, similar to the Redis session handler pattern.
66
+ * Kafka queue backend — a persistent worker-thread connection (see the file
67
+ * header). The public API stays synchronous; each call blocks the main thread on
68
+ * Atomics.wait while the worker runs the async socket I/O.
72
69
  */
73
70
  export declare class KafkaBackend implements QueueBackend {
74
71
  private brokers;
75
72
  private groupId;
73
+ private worker;
74
+ private sab;
75
+ private header;
76
+ private outBytes;
77
+ private static readonly SAB_SIZE;
78
+ private static readonly CALL_TIMEOUT_MS;
76
79
  constructor(config?: KafkaConfig);
77
- /**
78
- * Resolved connection config — exposed for testing/introspection.
79
- */
80
+ /** Resolved connection config — exposed for testing/introspection. */
80
81
  getConfig(): Required<Omit<KafkaConfig, "visibilityTimeout">>;
81
- /**
82
- * Resolved SSL/SASL client config from the environment (PLAINTEXT default).
83
- * Mirrors Python's `KafkaConnector._security_config`.
84
- */
85
82
  securityConfig(): KafkaSecurityConfig;
86
- /**
87
- * Full producer config — brokers + client id + the resolved security block.
88
- * The security keys are applied to BOTH producer and consumer (matching
89
- * Python's `_connect_confluent`).
90
- */
91
83
  producerConfig(): KafkaClientConfig;
92
- /**
93
- * Full consumer config — brokers + client id + group id + the SAME resolved
94
- * security block applied to the producer.
95
- */
96
84
  consumerConfig(): KafkaClientConfig;
85
+ /** Lazily start the persistent worker + its shared buffer. */
86
+ private ensureWorker;
87
+ /** One synchronous request to the worker: post, block on Atomics.wait, read. */
88
+ private request;
97
89
  /**
98
- * Parse broker string into host:port.
99
- */
100
- private parseBroker;
101
- /**
102
- * Execute a Kafka operation synchronously via a child process.
103
- *
104
- * The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
105
- * library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
106
- * (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
107
- * **v4** and parses the v2 RecordBatch out of the response. Both formats are
108
- * what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
109
- * Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
90
+ * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
91
+ * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
92
+ * consumer reading the topic gets the schema it expects; otherwise the Tina4
93
+ * job envelope. pop() unwraps both shapes (payload ?? the whole record).
110
94
  */
111
- private execSync;
95
+ private static encodeJob;
96
+ push(queue: string, payload: unknown, _delay?: number, _priority?: number, raw?: boolean): string;
97
+ pop(queue: string): QueueJob | null;
112
98
  /**
113
- * Sleep synchronously between produce retries.
114
- *
115
- * `push()` is synchronous (the whole backend drives its socket through a child
116
- * process), so there is no event loop to await on. `Atomics.wait` on a
117
- * SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
118
- * no dependency, no busy-wait burning CPU.
99
+ * Read the next record's value exactly as it sits on the wire — a Tina4
100
+ * envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
101
+ * with no id/offset tracking. For a foreign consumer's view of the schema;
102
+ * the queue facade consumes through pop(), which also normalises and tracks
103
+ * the offset so complete()/fail() can commit it.
119
104
  */
120
- private static sleepSync;
105
+ dequeue(queue: string): unknown;
106
+ /** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
107
+ complete(queue: string, id: string): void;
121
108
  /**
122
- * Turn a sentinel from the protocol child into a thrown error, or return.
123
- *
124
- * The wording matches the Python and PHP backends exactly -- the parity rule
125
- * covers user-visible error messages, not just behaviour.
109
+ * Record a failed attempt: re-produce the job with an incremented attempts
110
+ * count while it has retries left, else produce it to the dead-letter topic;
111
+ * commit the original offset either way (ADR-0022 decision 2).
126
112
  */
127
- private static assertNoError;
113
+ fail(queue: string, id: string, error: string, maxRetries: number, _retryBackoff?: number): void;
114
+ /** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
115
+ reject(queue: string, id: string, reason: string, maxRetries: number): void;
116
+ /** Re-produce the job (manual retry) and commit the original offset. */
117
+ retry(queue: string, id: string, delaySeconds?: number): boolean;
118
+ /** Read the dead-letter topic for this queue (every record on it is a dead letter). */
119
+ deadLetters(queue: string, _maxRetries?: number): QueueJob[];
128
120
  /**
129
- * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
130
- * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
131
- * consumer reading the topic gets the schema it expects; otherwise the Tina4 job
132
- * envelope. pop() unwraps both shapes (payload ?? the whole record).
121
+ * Refuse rather than silently answer from the local file store. Kafka keeps no
122
+ * queryable registry of failed jobs: a failed record is re-produced to a
123
+ * dead-letter TOPIC and the original offset committed past, and a log cannot be
124
+ * queried by job state. Returning [] would claim nothing has failed.
133
125
  */
134
- private static encodeJob;
135
- push(queue: string, payload: unknown, _delay?: number, _priority?: number, raw?: boolean): string;
136
- pop(queue: string): QueueJob | null;
126
+ failed(_queue: string, _maxRetries?: number): QueueJob[];
127
+ /** Refuse for the same reason failed() does (no queryable failed registry). */
128
+ retryFailed(_queue: string, _maxRetries?: number): number;
137
129
  size(_queue: string): number;
138
130
  clear(_queue: string): void;
139
131
  purge(_queue: string, _status?: string): number;
132
+ /** Stop the worker and release the connection. Idempotent. */
133
+ close(): void;
140
134
  }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Raw TCP service — a user-facing, non-HTTP, long-lived binary TCP listener.
3
+ *
4
+ * Governed by ADR-0102 (feature 142), and the Python reference tina4_python/tcp.
5
+ * A Tina4 app exposes its own protocol — a GPS/GPRS car-tracker gateway
6
+ * (GT06/TK103/Concox/Teltonika) is the driving case — in the SAME process as its
7
+ * HTTP dashboard, reusing config, logging, ORM and queue.
8
+ *
9
+ * const svc = tcpService(5023, {
10
+ * onData(conn, data) {
11
+ * const frame = parse(data); // the APP frames the stream
12
+ * if (frame.isLogin) conn.identify(frame.imei);
13
+ * conn.send(ackFor(frame)); // ACK on the same socket
14
+ * },
15
+ * });
16
+ *
17
+ * // server -> device push from an HTTP route:
18
+ * tcp("trackers").sendTo(imei, buildCommand("set_interval", 30));
19
+ *
20
+ * The listener runs on the SAME event loop as the HTTP server (D1 in-process),
21
+ * via `net.createServer`. The framework owns the socket hard-parts: lifecycle,
22
+ * max_connections refusal, an idle reaper (default OFF for long-lived device
23
+ * sockets), graceful-shutdown drain, bounded write backpressure, and
24
+ * single-owner bind under N workers.
25
+ *
26
+ * Non-goals in v1 (ADR-0102): no CRC/length framing helper beyond on_line, no
27
+ * TLS termination, no UDP, no replacement for the WebSocket surface.
28
+ */
29
+ import { type Socket } from "node:net";
30
+ export type TcpConnectHandler = (conn: TcpConnection) => void | Promise<void>;
31
+ export type TcpDataHandler = (conn: TcpConnection, data: Buffer) => void | Promise<void>;
32
+ export type TcpCloseHandler = (conn: TcpConnection) => void | Promise<void>;
33
+ export type TcpLineHandler = (conn: TcpConnection, line: Buffer) => void | Promise<void>;
34
+ export interface TcpServiceOptions {
35
+ name?: string;
36
+ onConnect?: TcpConnectHandler;
37
+ onData?: TcpDataHandler;
38
+ onClose?: TcpCloseHandler;
39
+ onLine?: TcpLineHandler;
40
+ /** Seconds; 0 (default) disables the idle reaper (device sockets are long-lived). */
41
+ idleTimeout?: number;
42
+ /** The (N+1)th connection past this is refused; unset = unbounded. */
43
+ maxConnections?: number;
44
+ /** Per-connection outstanding-write ceiling in bytes (default TINA4_TCP_MAX_BACKLOG or 1 MiB). */
45
+ maxBacklog?: number;
46
+ }
47
+ /**
48
+ * One live TCP connection — the uniform connection object (ADR-0102 D5). The
49
+ * SAME surface exists in all four frameworks so the primitive ports.
50
+ */
51
+ export declare class TcpConnection {
52
+ readonly socket: Socket;
53
+ private readonly service;
54
+ /** The registry id (the IMEI), or null until identify() is called. */
55
+ id: string | null;
56
+ /** Per-connection mutable state bag — the app's parse buffer, auth flag. */
57
+ context: Record<string, unknown>;
58
+ /** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
59
+ readonly remoteAddr: string;
60
+ lastActivity: number;
61
+ lineBuffer: Buffer;
62
+ private closed;
63
+ private closeFired;
64
+ constructor(socket: Socket, service: TcpService);
65
+ get isClosed(): boolean;
66
+ /**
67
+ * Register this live connection under an app-chosen id (the IMEI). A second
68
+ * connection identifying with the same id SUPERSEDES the first in the
69
+ * registry — exactly a device that dropped and reconnected.
70
+ */
71
+ identify(appId: string | number): this;
72
+ /**
73
+ * Write raw bytes to THIS socket. Returns true when queued/sent, false when
74
+ * the connection is closed or dropped for backpressure. A stalled reader
75
+ * (never draining) is bounded: once more than the service's maxBacklog bytes
76
+ * are outstanding, the connection is dropped rather than buffered without end
77
+ * (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
78
+ */
79
+ send(data: Buffer | string): boolean;
80
+ /**
81
+ * Close this connection. on_close fires exactly once (from the socket's close
82
+ * event) and the registry entry is removed.
83
+ */
84
+ close(): void;
85
+ /** @internal mark activity for the idle reaper. */
86
+ _touch(): void;
87
+ /** @internal fire on_close exactly once (called from the service removal path). */
88
+ _fireClose(): void;
89
+ }
90
+ /** A named raw TCP listener and its connection registry (ADR-0102). */
91
+ export declare class TcpService {
92
+ readonly name: string;
93
+ readonly port: number;
94
+ readonly maxBacklog: number;
95
+ /** @internal the callback bag, read by TcpConnection. */
96
+ readonly _callbacks: Required<Pick<TcpServiceOptions, never>> & {
97
+ onConnect?: TcpConnectHandler;
98
+ onData?: TcpDataHandler;
99
+ onClose?: TcpCloseHandler;
100
+ onLine?: TcpLineHandler;
101
+ };
102
+ private readonly idleTimeout;
103
+ private readonly maxConnections;
104
+ private readonly connections;
105
+ private readonly byId;
106
+ private server;
107
+ private owner;
108
+ private boundPortValue;
109
+ private reaper;
110
+ constructor(port: number, options?: TcpServiceOptions);
111
+ get isOwner(): boolean;
112
+ /** The port actually bound (resolves an ephemeral port=0 to the real one). */
113
+ get boundPort(): number;
114
+ count(): number;
115
+ /** @internal */
116
+ _registerId(appId: string, conn: TcpConnection): void;
117
+ /** The live connection for an app id, or null if unknown or closed. */
118
+ connection(appId: string | number): TcpConnection | null;
119
+ /**
120
+ * Write bytes to exactly the connection identified by appId. A send to an
121
+ * unknown or closed id is a NO-OP that returns false — never a throw.
122
+ */
123
+ sendTo(appId: string | number, data: Buffer | string): boolean;
124
+ /** Write bytes to every live connection. Returns how many received it. */
125
+ broadcast(data: Buffer | string): number;
126
+ /**
127
+ * Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
128
+ * under a multi-worker deployment exactly ONE worker wins the bind; a worker
129
+ * that finds the port already bound skips silently (single-owner, D1).
130
+ * Resolves true when THIS call bound the port.
131
+ */
132
+ start(host?: string): Promise<boolean>;
133
+ private handleConnection;
134
+ private dispatch;
135
+ /** @internal remove a connection and fire on_close exactly once. */
136
+ remove(conn: TcpConnection): void;
137
+ private startReaper;
138
+ private reapIdle;
139
+ /** Stop accepting new connections (close the listener). Live conns stay. */
140
+ stopAccepting(): void;
141
+ /** Close every live connection (firing on_close) and release the listener. */
142
+ drain(): Promise<void>;
143
+ /** Stop accepting and drain in one call (used by direct callers/tests). */
144
+ stop(): Promise<void>;
145
+ }
146
+ /**
147
+ * Register a named raw TCP service; the server binds it on boot (D1). Options
148
+ * are read once here. Reachable anywhere via `tcp(name)`.
149
+ */
150
+ export declare function tcpService(port: number, options?: TcpServiceOptions): TcpService;
151
+ /**
152
+ * The registry for a named service, for server -> device push. Throws for an
153
+ * unknown service name — a programming error, unlike a send to an unknown
154
+ * device id, which is a runtime no-op.
155
+ */
156
+ export declare function tcp(name?: string): TcpService;
157
+ export declare function registeredTcpServices(): TcpService[];
158
+ /** Drop every registered service (test isolation; not used in production). */
159
+ export declare function clearTcpRegistry(): void;
160
+ /** Start every registered service on boot (called by startServer). */
161
+ export declare function startAllTcpServices(host?: string): Promise<void>;
162
+ /** Stop every service accepting (shutdown step 1). */
163
+ export declare function stopAcceptingAllTcpServices(): void;
164
+ /** Drain and release every service's connections (shutdown drain step). */
165
+ export declare function drainAllTcpServices(): Promise<void>;
@@ -61,6 +61,15 @@ export declare const expressionFormCache: Map<string, number>;
61
61
  * Crud.toCrud never carries its own copy of the escape table (ADR-0094).
62
62
  */
63
63
  export declare function escapeHtml(value: unknown): string;
64
+ /**
65
+ * Thrown when a Frond template is malformed and cannot be rendered safely
66
+ * (ADR-0104) — an unclosed `{% block %}` or a cut-short `{% endblock %` whose
67
+ * closing `%}` is missing. Failing loud surfaces the real cause to a developer
68
+ * (or an AI agent) instead of a page served 200 with its body quietly dropped.
69
+ */
70
+ export declare class FrondSyntaxError extends Error {
71
+ constructor(message: string);
72
+ }
64
73
  /**
65
74
  * Set the session ID used by formToken() / form_token() for CSRF session binding.
66
75
  */
@@ -1,2 +1,2 @@
1
- export { Frond, escapeHtml, setCspNonceProvider, setFormTokenSessionProvider } from "./engine.js";
1
+ export { Frond, FrondSyntaxError, escapeHtml, setCspNonceProvider, setFormTokenSessionProvider } from "./engine.js";
2
2
  export type { FilterFn, TestFn, LiveProvider, LiveRequest, LiveResponse, LiveBroadcaster } from "./engine.js";
@@ -120,6 +120,34 @@ export declare class QueryBuilder {
120
120
  * @returns this for chaining.
121
121
  */
122
122
  limit(count: number, offset?: number): QueryBuilder;
123
+ /**
124
+ * Set OFFSET (rows to skip) as its own chainable verb.
125
+ *
126
+ * `limit(n, offset)` buries the offset as a second positional arg; this
127
+ * exposes it on its own, so `.offset(20).limit(10)` reads naturally and
128
+ * matches the SQL keyword.
129
+ *
130
+ * @param count - Number of rows to skip.
131
+ * @returns this for chaining.
132
+ */
133
+ offset(count: number): QueryBuilder;
134
+ /**
135
+ * Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
136
+ *
137
+ * Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
138
+ * already emits, so a query reads the same whether it targets SQL or MongoDB.
139
+ *
140
+ * @param count - Number of rows to skip.
141
+ * @returns this for chaining.
142
+ */
143
+ skip(count: number): QueryBuilder;
144
+ /**
145
+ * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
146
+ *
147
+ * @param count - Maximum rows to return.
148
+ * @returns this for chaining.
149
+ */
150
+ take(count: number): QueryBuilder;
123
151
  /**
124
152
  * Build and return the SQL string without executing.
125
153
  *