@telorun/assert 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ # SUSTAINABLE USE LICENSE (Fair-code)
2
+
3
+ Copyright (c) 2026 CodeNet Sp. z o.o.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to use, copy, modify, and distribute the Software for any purpose—including commercial purposes—subject to the following conditions:
6
+
7
+ 1. ANTI-COMPETITION RESTRICTION: The Software may not be provided to third parties as a managed service, commercial SaaS (Software-as-a-Service), PaaS (Platform-as-a-Service), BaaS (Backend-as-a-Service), or similar offering where the primary value provided to the user is the functionality of the Software itself, without a separate commercial license from the copyright holder.
8
+
9
+ 2. PERMITTED COMMERCIAL USE: You are free to use the Software to build, host, and monetize your own commercial applications, products, and services, provided such use does not violate Clause 1.
10
+
11
+ 3. ATTRIBUTION: This copyright notice and license must be included in all copies or substantial portions of the Software.
12
+
13
+ 4. CONTRIBUTIONS: Contributions to the Software are welcome and encouraged. By contributing, you agree that your contributions may be incorporated into the Software and distributed under this license.
14
+
15
+ 5. DISCLAIMER: The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.
16
+
17
+ For commercial licensing, managed hosting exemptions, or enterprise inquiries, please contact <contact@codenet.pl>.
package/README.md ADDED
@@ -0,0 +1,246 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/telorun/telo/main/assets/telo.png" alt="Telo" width="200" />
3
+ </p>
4
+
5
+ <h1 align="center">Telo</h1>
6
+
7
+ <p align="center">Runtime for declarative backends.</p>
8
+
9
+ <p align="center">
10
+ <a href="https://github.com/telorun/telo/actions/workflows/test.yml"><img alt="Tests" src="https://github.com/telorun/telo/actions/workflows/test.yml/badge.svg" /></a>
11
+ <a href="https://www.npmjs.com/package/@telorun/cli"><img alt="node" src="https://img.shields.io/node/v/@telorun/cli" /></a>
12
+ <br />
13
+ <a href="https://github.com/telorun/telo/commits/main"><img alt="Last commit" src="https://img.shields.io/github/last-commit/telorun/telo" /></a>
14
+ <a href="https://github.com/telorun/telo/issues"><img alt="Issues" src="https://img.shields.io/github/issues/telorun/telo" /></a>
15
+ <a href="https://github.com/telorun/telo/pulls"><img alt="Pull requests" src="https://img.shields.io/github/issues-pr/telorun/telo" /></a>
16
+ <br />
17
+ <img alt="Changesets" src="https://img.shields.io/badge/maintained%20with-changesets-176de3" />
18
+ </p>
19
+
20
+ Telo is an execution engine (Micro-Kernel) that runs logic defined entirely in YAML manifests. Instead of writing imperative backend code, you define your routes, databases, schemas, and AI workflows as atomic, interconnected YAML documents. Telo takes those manifests and runs them.
21
+
22
+ Built to be language-agnostic and infinitely extensible.
23
+
24
+ ```bash
25
+ # Reconcile your manifest into a running backend
26
+ $ telo ./examples/hello-api.yaml
27
+
28
+ {"level":30,"time":1771610393008,"pid":1310178,"hostname":"dev","msg":"Server listening at http://127.0.0.1:8844"}
29
+ ```
30
+
31
+ ## Why use Telo?
32
+
33
+ - **Open Standards:** Built on YAML, JSON Schema, and CEL — no proprietary DSL.
34
+ - **Static Analysis:** CEL type checking, reference validation, and IDE diagnostics catch errors before runtime.
35
+ - **Micro-Kernel Architecture:** Telo itself knows nothing about HTTP or SQL. Everything is a module you import, scope, and compose with typed variable and secret contracts.
36
+ - **Language Agnostic:** Available as a Node.js runtime today, with a shared YAML runtime contract that allows for future Rust or Go implementations without changing your manifests.
37
+
38
+ ## What It Does
39
+
40
+ - **Loads** YAML resources and compiles CEL expressions (`${{ }}`) into an in-memory registry.
41
+ - **Resolves** resource dependencies via a multi-pass init loop, handling ordering automatically.
42
+ - **Indexes** resources by Kind and Name for constant-time lookup.
43
+ - **Dispatches** execution to the controller that owns each Kind.
44
+
45
+ ## Example manifest
46
+
47
+ Here is an example Telo application that defines a simple HTTP API:
48
+
49
+ ```yaml
50
+ kind: Telo.Application
51
+ metadata:
52
+ name: feedback
53
+ version: 1.0.0
54
+ description: |
55
+ A complete feedback collection REST API — no code, pure YAML.
56
+ Persists entries to SQLite and serves them over HTTP.
57
+ targets:
58
+ - Migrations
59
+ - Server
60
+ ---
61
+ kind: Telo.Import
62
+ metadata:
63
+ name: Http
64
+ source: std/http-server@0.4.0
65
+ ---
66
+ kind: Telo.Import
67
+ metadata:
68
+ name: Sql
69
+ source: std/sql@0.2.3
70
+ ---
71
+ # SQLite database — swap driver/host/database for PostgreSQL with zero YAML changes
72
+ kind: Sql.Connection
73
+ metadata:
74
+ name: Db
75
+ driver: sqlite
76
+ file: ./tmp/feedback.db
77
+ ---
78
+ # Migrations: applied automatically before the server starts
79
+ kind: Sql.Migrations
80
+ metadata:
81
+ name: Migrations
82
+ connection:
83
+ kind: Sql.Connection
84
+ name: Db
85
+ ---
86
+ kind: Sql.Migration
87
+ metadata:
88
+ name: Migration_20260413_182154_CreateFeedback
89
+ version: 20260413_182154_CreateFeedback
90
+ sql: |
91
+ CREATE TABLE IF NOT EXISTS feedback (
92
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
93
+ text TEXT NOT NULL,
94
+ source TEXT,
95
+ score INTEGER NOT NULL DEFAULT 0,
96
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
97
+ )
98
+ ---
99
+ kind: Http.Server
100
+ metadata:
101
+ name: Server
102
+ baseUrl: http://localhost:8844
103
+ port: 8844
104
+ logger: true
105
+ openapi:
106
+ info:
107
+ title: Feedback API
108
+ version: 1.0.0
109
+ mounts:
110
+ - path: /v1
111
+ type: Http.Api.FeedbackRoutes
112
+ ---
113
+ kind: Http.Api
114
+ metadata:
115
+ name: FeedbackRoutes
116
+ routes:
117
+ # POST /v1/feedback — insert a new entry, score derived from body length heuristic
118
+ - request:
119
+ path: /feedback
120
+ method: POST
121
+ schema:
122
+ body:
123
+ type: object
124
+ properties:
125
+ text:
126
+ type: string
127
+ minLength: 1
128
+ source:
129
+ type: string
130
+ required: [text]
131
+ handler:
132
+ kind: Sql.Exec
133
+ connection:
134
+ kind: Sql.Connection
135
+ name: Db
136
+ inputs:
137
+ sql: "INSERT INTO feedback (text, source, score) VALUES (?, ?, ?)"
138
+ bindings:
139
+ - "${{ request.body.text }}"
140
+ - "${{ request.body.source }}"
141
+ - "${{ size(request.body.text) }}"
142
+ response:
143
+ - status: 201
144
+ headers:
145
+ Content-Type: application/json
146
+ body:
147
+ ok: true
148
+ message: Feedback received
149
+
150
+ # GET /v1/feedback — list all entries, newest first
151
+ - request:
152
+ path: /feedback
153
+ method: GET
154
+ handler:
155
+ kind: Sql.Select
156
+ connection:
157
+ kind: Sql.Connection
158
+ name: Db
159
+ from: feedback
160
+ columns: [id, text, source, score, created_at]
161
+ orderBy:
162
+ - { column: created_at, direction: desc }
163
+ response:
164
+ - status: 200
165
+ headers:
166
+ Content-Type: application/json
167
+ body: "${{ result.rows }}"
168
+
169
+ # GET /v1/feedback/{id} — fetch a single entry
170
+ - request:
171
+ path: /feedback/{id}
172
+ method: GET
173
+ schema:
174
+ params:
175
+ type: object
176
+ properties:
177
+ id:
178
+ type: integer
179
+ required: [id]
180
+ handler:
181
+ kind: Sql.Select
182
+ connection:
183
+ kind: Sql.Connection
184
+ name: Db
185
+ from: feedback
186
+ columns: [id, text, source, score, created_at]
187
+ where:
188
+ - { column: id, op: "=", value: "${{ request.params.id }}" }
189
+ response:
190
+ - status: 200
191
+ when: "size(result.rows) > 0"
192
+ headers:
193
+ Content-Type: application/json
194
+ body: "${{ result.rows[0] }}"
195
+ - status: 404
196
+ headers:
197
+ Content-Type: application/json
198
+ body:
199
+ ok: false
200
+ message: Not found
201
+ ```
202
+
203
+ ## Status
204
+
205
+ Telo is under **active development**. The core runtime, module system, and standard library are functional, but the API surface — including YAML shapes — may change without notice. Not yet recommended for production use.
206
+
207
+ ## The Meaning of Telo
208
+
209
+ The name Telo is derived from the Greek root Telos - meaning the "end goal", "purpose", or "final state". That is exactly the philosophy behind this runtime. In standard imperative programming, you have to write thousands of lines of code to tell a server exactly how to start. With Telo, you simply declare your desired final state.
210
+
211
+ You define the end state. Telo makes it real.
212
+
213
+ ## Philosophy
214
+
215
+ Modern platforms often spend disproportionate effort on technical mechanics-wiring frameworks, managing infrastructure, and negotiating toolchains-while the original business problem gets delayed or diluted. Telo pushes in the opposite direction: it treats kernel execution as a stable, predictable host so teams can concentrate on the **business logic and outcomes** instead of the plumbing.
216
+
217
+ By separating "what the system should do" from "how it is hosted", the runtime reduces friction for domain‑level changes. Teams can move faster on product requirements, experiment more safely, and keep conversations centered on value delivered rather than implementation trivia.
218
+
219
+ Telo also aims to **join forces across all programming language communities**, so the best ideas, patterns, and implementations can converge into a shared kernel truth without forcing everyone into a single stack.
220
+
221
+ YAML also makes the system more **AI‑friendly** than traditional programming languages: it is explicit, structured, and easier for tools to generate, review, and transform without losing intent.
222
+
223
+ ## Modularity
224
+
225
+ Telo is built around **modules** that own specific resource kinds. A module is loaded from a manifest, declares which kinds it implements, and then receives only the resources of those kinds. This keeps concerns isolated and lets teams compose systems from focused building blocks rather than monolithic services.
226
+
227
+ At kernel execution time, execution is always routed by **Kind.Name**. The kernel resolves the Kind to its owning module and hands off execution. Modules can call back into the kernel to execute other resources, enabling composition without tight coupling.
228
+
229
+ ## Architecture
230
+
231
+ The architecture is inspired by Kubernetes-style manifests: declarative resources, explicit kinds, and a control plane that routes work based on those definitions.
232
+ Those manifests were taken to the next level by allowing them to run inside a standalone runtime host.
233
+
234
+ ## See more at
235
+
236
+ - [Telo Kernel](./kernel/README.md)
237
+ - [Telo SDK for module authors](sdk/README.md)
238
+ - [Modules](modules/README.md)
239
+
240
+ ## License
241
+
242
+ See [LICENSE](https://github.com/telorun/telo/blob/main/LICENSE).
243
+
244
+ ## Contribution Note
245
+
246
+ By contributing, you agree that code and examples in this repository may be translated or re‑implemented in other programming languages (including by AI systems) to support the project’s polyglot goals.
@@ -0,0 +1,12 @@
1
+ import type { ResourceContext } from "@telorun/sdk";
2
+ /**
3
+ * Build the small ANSI color helpers used by every assert kind. Returns
4
+ * pass-through (uncolored) helpers when stderr isn't a TTY so piped /
5
+ * redirected output stays clean.
6
+ */
7
+ export declare function createColors(ctx: ResourceContext): {
8
+ bold: (t: string) => string;
9
+ red: (t: string) => string;
10
+ green: (t: string) => string;
11
+ dim: (t: string) => string;
12
+ };
package/dist/colors.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Build the small ANSI color helpers used by every assert kind. Returns
3
+ * pass-through (uncolored) helpers when stderr isn't a TTY so piped /
4
+ * redirected output stays clean.
5
+ */
6
+ export function createColors(ctx) {
7
+ const useColor = ctx.stderr.isTTY ?? false;
8
+ const c = (code, text) => useColor ? `\x1b[${code}m${text}\x1b[0m` : text;
9
+ return {
10
+ bold: (t) => c("1", t),
11
+ red: (t) => c("31", t),
12
+ green: (t) => c("32", t),
13
+ dim: (t) => c("2", t),
14
+ };
15
+ }
@@ -0,0 +1,16 @@
1
+ import { ResourceContext } from "@telorun/sdk";
2
+ import { Static } from "@sinclair/typebox";
3
+ export declare const schema: import("@sinclair/typebox").TObject<{
4
+ metadata: import("@sinclair/typebox").TObject<{
5
+ name: import("@sinclair/typebox").TString;
6
+ }>;
7
+ }>;
8
+ type AssertManifest = Static<typeof schema>;
9
+ interface ContainsInput {
10
+ actual: unknown;
11
+ value: unknown;
12
+ }
13
+ export declare function create(manifest: AssertManifest, ctx: ResourceContext): Promise<{
14
+ invoke: (input: ContainsInput) => boolean;
15
+ }>;
16
+ export {};
@@ -0,0 +1,53 @@
1
+ import { InvokeError } from "@telorun/sdk";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { createColors } from "./colors.js";
4
+ import { deepEquals } from "./deep-equals.js";
5
+ export const schema = Type.Object({
6
+ metadata: Type.Object({
7
+ name: Type.String(),
8
+ }),
9
+ });
10
+ export async function create(manifest, ctx) {
11
+ const { bold, red, green, dim } = createColors(ctx);
12
+ const name = manifest.metadata.name;
13
+ return {
14
+ invoke: (input) => {
15
+ const { actual, value } = input ?? {};
16
+ let ok = false;
17
+ let kind = "";
18
+ if (typeof actual === "string") {
19
+ if (typeof value !== "string") {
20
+ const message = `actual is a string but value is ${typeof value}; expected substring`;
21
+ ctx.stderr.write(bold(red(`Assert.Contains.${name}: assertion failed`)) +
22
+ "\n" +
23
+ ` ${red("✗")} ${message}\n`);
24
+ throw new InvokeError("ERR_ASSERTION_FAILED", `Assert.Contains "${name}": ${message}`);
25
+ }
26
+ kind = "substring";
27
+ ok = actual.includes(value);
28
+ }
29
+ else if (Array.isArray(actual)) {
30
+ kind = "element";
31
+ ok = actual.some((item) => deepEquals(item, value));
32
+ }
33
+ else {
34
+ const message = `actual must be string or array; got ${typeof actual}`;
35
+ ctx.stderr.write(bold(red(`Assert.Contains.${name}: assertion failed`)) +
36
+ "\n" +
37
+ ` ${red("✗")} ${message}\n`);
38
+ throw new InvokeError("ERR_ASSERTION_FAILED", `Assert.Contains "${name}": ${message}`);
39
+ }
40
+ if (ok) {
41
+ ctx.stdout.write(bold(green(`Assert.Contains.${name}: assertion passed`)) +
42
+ "\n" +
43
+ ` ${green("✓")} ${dim(JSON.stringify(actual))} ${dim("⊇")} ${dim(JSON.stringify(value))}\n`);
44
+ return true;
45
+ }
46
+ const message = `${JSON.stringify(actual)} does not contain ${kind} ${JSON.stringify(value)}`;
47
+ ctx.stderr.write(bold(red(`Assert.Contains.${name}: assertion failed`)) +
48
+ "\n" +
49
+ ` ${red("✗")} ${message}\n`);
50
+ throw new InvokeError("ERR_ASSERTION_FAILED", `Assert.Contains "${name}": ${message}`);
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Deep equality for the JSON-shaped values Telo stages typically pass
3
+ * around: primitives, plain objects (proto === Object.prototype or null),
4
+ * and arrays. Non-plain objects (Date, Map, Set, RegExp, class instances)
5
+ * are NOT structurally compared — only `Object.is`-equal instances pass.
6
+ *
7
+ * This is intentional: structurally comparing the empty `Object.keys()`
8
+ * of two distinct `new Date(…)` instances would silently return true,
9
+ * letting `Assert.Equals` pass for values that are clearly different.
10
+ * If a consumer genuinely needs Date / Map / Set equality, they should
11
+ * serialize first (e.g. `date.toISOString()`) and compare the strings.
12
+ */
13
+ export declare function deepEquals(a: unknown, b: unknown): boolean;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Deep equality for the JSON-shaped values Telo stages typically pass
3
+ * around: primitives, plain objects (proto === Object.prototype or null),
4
+ * and arrays. Non-plain objects (Date, Map, Set, RegExp, class instances)
5
+ * are NOT structurally compared — only `Object.is`-equal instances pass.
6
+ *
7
+ * This is intentional: structurally comparing the empty `Object.keys()`
8
+ * of two distinct `new Date(…)` instances would silently return true,
9
+ * letting `Assert.Equals` pass for values that are clearly different.
10
+ * If a consumer genuinely needs Date / Map / Set equality, they should
11
+ * serialize first (e.g. `date.toISOString()`) and compare the strings.
12
+ */
13
+ export function deepEquals(a, b) {
14
+ if (Object.is(a, b))
15
+ return true;
16
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
17
+ return false;
18
+ if (Array.isArray(a) || Array.isArray(b)) {
19
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
20
+ return false;
21
+ for (let i = 0; i < a.length; i++) {
22
+ if (!deepEquals(a[i], b[i]))
23
+ return false;
24
+ }
25
+ return true;
26
+ }
27
+ // Refuse structural compare for non-plain objects. Identity was already
28
+ // checked at the top; reaching here with a non-plain object means a !== b
29
+ // and we cannot meaningfully recurse into "fields" — empty keys would
30
+ // produce false positives.
31
+ if (!isPlainObject(a) || !isPlainObject(b))
32
+ return false;
33
+ const ao = a;
34
+ const bo = b;
35
+ const aKeys = Object.keys(ao);
36
+ const bKeys = Object.keys(bo);
37
+ if (aKeys.length !== bKeys.length)
38
+ return false;
39
+ for (const k of aKeys) {
40
+ if (!Object.prototype.hasOwnProperty.call(bo, k) || !deepEquals(ao[k], bo[k]))
41
+ return false;
42
+ }
43
+ return true;
44
+ }
45
+ function isPlainObject(v) {
46
+ const proto = Object.getPrototypeOf(v);
47
+ return proto === Object.prototype || proto === null;
48
+ }
@@ -0,0 +1,16 @@
1
+ import { ResourceContext } from "@telorun/sdk";
2
+ import { Static } from "@sinclair/typebox";
3
+ export declare const schema: import("@sinclair/typebox").TObject<{
4
+ metadata: import("@sinclair/typebox").TObject<{
5
+ name: import("@sinclair/typebox").TString;
6
+ }>;
7
+ }>;
8
+ type AssertManifest = Static<typeof schema>;
9
+ interface EqualsInput {
10
+ actual: unknown;
11
+ expected: unknown;
12
+ }
13
+ export declare function create(manifest: AssertManifest, ctx: ResourceContext): Promise<{
14
+ invoke: (input: EqualsInput) => boolean;
15
+ }>;
16
+ export {};
package/dist/equals.js ADDED
@@ -0,0 +1,29 @@
1
+ import { InvokeError } from "@telorun/sdk";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { createColors } from "./colors.js";
4
+ import { deepEquals } from "./deep-equals.js";
5
+ export const schema = Type.Object({
6
+ metadata: Type.Object({
7
+ name: Type.String(),
8
+ }),
9
+ });
10
+ export async function create(manifest, ctx) {
11
+ const { bold, red, green, dim } = createColors(ctx);
12
+ const name = manifest.metadata.name;
13
+ return {
14
+ invoke: (input) => {
15
+ const { actual, expected } = input ?? {};
16
+ if (deepEquals(actual, expected)) {
17
+ ctx.stdout.write(bold(green(`Assert.Equals.${name}: assertion passed`)) +
18
+ "\n" +
19
+ ` ${green("✓")} ${dim(JSON.stringify(actual))}\n`);
20
+ return true;
21
+ }
22
+ const message = `expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`;
23
+ ctx.stderr.write(bold(red(`Assert.Equals.${name}: assertion failed`)) +
24
+ "\n" +
25
+ ` ${red("✗")} ${message}\n`);
26
+ throw new InvokeError("ERR_ASSERTION_FAILED", `Assert.Equals "${name}": ${message}`);
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,19 @@
1
+ import { Static } from "@sinclair/typebox";
2
+ import { ResourceContext } from "@telorun/sdk";
3
+ export declare const schema: import("@sinclair/typebox").TObject<{
4
+ metadata: import("@sinclair/typebox").TObject<{
5
+ name: import("@sinclair/typebox").TString;
6
+ }>;
7
+ filter: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<{
8
+ type: import("@sinclair/typebox").TString;
9
+ }>>>;
10
+ expect: import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<{
11
+ event: import("@sinclair/typebox").TString;
12
+ payload: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TRecord<import("@sinclair/typebox").TString, import("@sinclair/typebox").TAny>>;
13
+ }>>;
14
+ }>;
15
+ type AssertManifest = Static<typeof schema>;
16
+ export declare function create(manifest: AssertManifest, ctx: ResourceContext): Promise<{
17
+ run: () => Promise<void>;
18
+ }>;
19
+ export {};
package/dist/events.js ADDED
@@ -0,0 +1,121 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ const FilterEntry = Type.Object({
3
+ type: Type.String(),
4
+ });
5
+ const ExpectEntry = Type.Object({
6
+ event: Type.String(),
7
+ payload: Type.Optional(Type.Record(Type.String(), Type.Any())),
8
+ });
9
+ export const schema = Type.Object({
10
+ metadata: Type.Object({
11
+ name: Type.String(),
12
+ }),
13
+ filter: Type.Optional(Type.Array(FilterEntry)),
14
+ expect: Type.Array(ExpectEntry),
15
+ });
16
+ function matchesPattern(pattern, eventName) {
17
+ if (pattern === "*")
18
+ return true;
19
+ if (pattern === eventName)
20
+ return true;
21
+ if (!pattern.includes("*"))
22
+ return false;
23
+ const patternParts = pattern.split(".");
24
+ const eventParts = eventName.split(".");
25
+ if (patternParts.length !== eventParts.length)
26
+ return false;
27
+ for (let i = 0; i < patternParts.length; i++) {
28
+ if (patternParts[i] !== "*" && patternParts[i] !== eventParts[i])
29
+ return false;
30
+ }
31
+ return true;
32
+ }
33
+ function matchesPayload(actual, expected) {
34
+ for (const [key, value] of Object.entries(expected)) {
35
+ if (actual == null)
36
+ return false;
37
+ if (typeof value === "object" && value !== null) {
38
+ if (!matchesPayload(actual[key], value))
39
+ return false;
40
+ }
41
+ else {
42
+ if (actual[key] !== value)
43
+ return false;
44
+ }
45
+ }
46
+ return true;
47
+ }
48
+ export async function create(manifest, ctx) {
49
+ const useColor = ctx.stderr.isTTY ?? false;
50
+ const c = (code, text) => (useColor ? `\x1b[${code}m${text}\x1b[0m` : text);
51
+ const bold = (t) => c("1", t);
52
+ const red = (t) => c("31", t);
53
+ const green = (t) => c("32", t);
54
+ const yellow = (t) => c("33", t);
55
+ const dim = (t) => c("2", t);
56
+ function buildReport(name, captured, expect) {
57
+ const results = [];
58
+ let pos = 0;
59
+ for (const entry of expect) {
60
+ let found = false;
61
+ while (pos < captured.length) {
62
+ const ev = captured[pos++];
63
+ if (matchesPattern(entry.event, ev.name)) {
64
+ if (!entry.payload || matchesPayload(ev.payload, entry.payload)) {
65
+ results.push({ status: "matched", entry, actual: ev });
66
+ }
67
+ else {
68
+ results.push({ status: "payload-mismatch", entry, actual: ev });
69
+ }
70
+ found = true;
71
+ break;
72
+ }
73
+ }
74
+ if (!found) {
75
+ results.push({ status: "not-found", entry });
76
+ }
77
+ }
78
+ const failures = results.filter((r) => r.status !== "matched");
79
+ let report = bold(failures.length > 0
80
+ ? red(`Assert.Events.${name}: assertion failed`)
81
+ : green(`Assert.Events.${name}: assertion passed`)) + "\n";
82
+ for (const result of results) {
83
+ if (result.status === "matched") {
84
+ report += ` ${green("✓")} ${dim(result.actual.name)}\n`;
85
+ }
86
+ else if (result.status === "not-found") {
87
+ report += ` ${red("✗")} ${result.entry.event} ${dim("← not found in stream")}\n`;
88
+ if (result.entry.payload) {
89
+ report += ` ${dim("expected payload:")} ${yellow(JSON.stringify(result.entry.payload))}\n`;
90
+ }
91
+ }
92
+ else if (result.status === "payload-mismatch") {
93
+ report += ` ${red("✗")} ${result.actual.name}\n`;
94
+ report += ` ${dim("expected payload:")} ${yellow(JSON.stringify(result.entry.payload))}\n`;
95
+ report += ` ${dim("actual payload: ")} ${red(JSON.stringify(result.actual.payload))}\n`;
96
+ }
97
+ }
98
+ return { report, passed: failures.length === 0 };
99
+ }
100
+ const captured = [];
101
+ const filters = manifest.filter ?? [{ type: "*" }];
102
+ ctx.on("*", (event) => {
103
+ if (filters.some((f) => matchesPattern(f.type, event.name))) {
104
+ captured.push({ name: event.name, payload: event.payload });
105
+ }
106
+ });
107
+ return {
108
+ run: async () => {
109
+ const report = buildReport(manifest.metadata.name, captured, manifest.expect);
110
+ if (report) {
111
+ if (report.passed) {
112
+ ctx.stdout.write(report.report);
113
+ }
114
+ else {
115
+ ctx.stderr.write(report.report);
116
+ ctx.requestExit(1);
117
+ }
118
+ }
119
+ },
120
+ };
121
+ }
@@ -0,0 +1,19 @@
1
+ import type { ResourceContext, Runnable } from "@telorun/sdk";
2
+ interface ExpectError {
3
+ code?: string;
4
+ message?: string;
5
+ }
6
+ interface ManifestAssertManifest {
7
+ metadata: {
8
+ name: string;
9
+ module?: string;
10
+ };
11
+ source: string;
12
+ expect: {
13
+ errors?: ExpectError[];
14
+ warnings?: ExpectError[];
15
+ loadError?: string;
16
+ };
17
+ }
18
+ export declare function create(manifest: ManifestAssertManifest, ctx: ResourceContext): Promise<Runnable>;
19
+ export {};