@pollium/readable 0.0.0-stage → 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.
Files changed (72) hide show
  1. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorate.js +8 -0
  2. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorateMetadata.js +5 -0
  3. package/dist/app/Application.d.ts +33 -0
  4. package/dist/app/Application.js +133 -0
  5. package/dist/app/abort.d.ts +8 -0
  6. package/dist/app/abort.js +16 -0
  7. package/dist/app/compression.d.ts +2 -0
  8. package/dist/app/compression.js +35 -0
  9. package/dist/app/config.d.ts +44 -0
  10. package/dist/app/config.js +55 -0
  11. package/dist/app/discovery.d.ts +23 -0
  12. package/dist/app/discovery.js +74 -0
  13. package/dist/app/errors.d.ts +22 -0
  14. package/dist/app/errors.js +57 -0
  15. package/dist/app/logger.d.ts +20 -0
  16. package/dist/app/logger.js +40 -0
  17. package/dist/app/metadata.d.ts +5 -0
  18. package/dist/app/metadata.js +16 -0
  19. package/dist/app/redis.d.ts +4 -0
  20. package/dist/app/redis.js +24 -0
  21. package/dist/auth/credentials.d.ts +6 -0
  22. package/dist/auth/credentials.js +24 -0
  23. package/dist/auth/guards.d.ts +11 -0
  24. package/dist/auth/guards.js +44 -0
  25. package/dist/auth/params.d.ts +8 -0
  26. package/dist/auth/params.js +19 -0
  27. package/dist/auth/secrets.d.ts +6 -0
  28. package/dist/auth/secrets.js +38 -0
  29. package/dist/auth/sessions.d.ts +32 -0
  30. package/dist/auth/sessions.js +49 -0
  31. package/dist/database/data-source.d.ts +7 -0
  32. package/dist/database/data-source.js +15 -0
  33. package/dist/database/models.d.ts +16 -0
  34. package/dist/database/models.js +72 -0
  35. package/dist/database/queries.d.ts +26 -0
  36. package/dist/database/queries.js +56 -0
  37. package/dist/events/Broadcast.d.ts +8 -0
  38. package/dist/events/Broadcast.js +42 -0
  39. package/dist/events/EventBus.d.ts +23 -0
  40. package/dist/events/EventBus.js +115 -0
  41. package/dist/gateway/ConnectionRegistry.d.ts +25 -0
  42. package/dist/gateway/ConnectionRegistry.js +68 -0
  43. package/dist/gateway/Gateway.d.ts +15 -0
  44. package/dist/gateway/Gateway.js +135 -0
  45. package/dist/http/Controller.d.ts +24 -0
  46. package/dist/http/Controller.js +94 -0
  47. package/dist/http/auto-validate-body.d.ts +8 -0
  48. package/dist/http/auto-validate-body.js +16 -0
  49. package/dist/http/call.d.ts +24 -0
  50. package/dist/http/call.js +66 -0
  51. package/dist/http/middleware.d.ts +21 -0
  52. package/dist/http/middleware.js +39 -0
  53. package/dist/http/org-context.d.ts +6 -0
  54. package/dist/http/org-context.js +23 -0
  55. package/dist/http/params.d.ts +38 -0
  56. package/dist/http/params.js +93 -0
  57. package/dist/http/responses.d.ts +20 -0
  58. package/dist/http/responses.js +29 -0
  59. package/dist/queues/BaseQueue.d.ts +15 -0
  60. package/dist/queues/BaseQueue.js +69 -0
  61. package/dist/storage/ObjectStorage.d.ts +37 -0
  62. package/dist/storage/ObjectStorage.js +170 -0
  63. package/dist/testing/harness.d.ts +25 -0
  64. package/dist/testing/harness.js +46 -0
  65. package/dist/testing/rate-limit.d.ts +1 -0
  66. package/dist/testing/rate-limit.js +4 -0
  67. package/dist/testing/request.d.ts +21 -0
  68. package/dist/testing/request.js +41 -0
  69. package/dist/tools/ToolGroup.d.ts +33 -0
  70. package/dist/tools/ToolGroup.js +30 -0
  71. package/package.json +59 -3
  72. package/README.md +0 -3
@@ -0,0 +1,93 @@
1
+ import { ClassMetadata } from "../app/metadata.js";
2
+ import { RequestError, ValidationError } from "../app/errors.js";
3
+ // lib/http/params.ts
4
+ const bindingsByController = new ClassMetadata();
5
+ const createParamDecorator = (resolve) => {
6
+ return (target, handlerName, index) => {
7
+ if (handlerName === void 0) return;
8
+ bindingsByController.append(target.constructor, {
9
+ handlerName,
10
+ index,
11
+ resolve
12
+ });
13
+ };
14
+ };
15
+ const getParamResolvers = (ctor, handlerName) => {
16
+ const bindings = bindingsByController.get(ctor).filter((binding) => binding.handlerName === handlerName);
17
+ const resolvers = [];
18
+ for (const binding of bindings) resolvers[binding.index] = binding.resolve;
19
+ return resolvers;
20
+ };
21
+ const parseId = (raw) => {
22
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
23
+ if (typeof raw !== "string") throw RequestError.InvalidId();
24
+ const value = raw.toLowerCase();
25
+ if (!uuid.test(value)) throw RequestError.InvalidId();
26
+ return value;
27
+ };
28
+ const parseOrdinal = (raw) => {
29
+ const value = Number(raw);
30
+ if (!Number.isInteger(value) || value <= 0) throw RequestError.InvalidId();
31
+ return value;
32
+ };
33
+ const parseValue = (raw, defaultValue, minimum) => {
34
+ if (raw === void 0) return defaultValue;
35
+ const value = Number(raw);
36
+ if (!Number.isSafeInteger(value) || value < minimum) throw RequestError.InvalidPagination();
37
+ return value;
38
+ };
39
+ const parsePagination = (query, options) => {
40
+ const raw = query ?? {};
41
+ return {
42
+ limit: Math.min(parseValue(raw.limit, options?.defaultLimit ?? 50, 1), options?.maxLimit ?? 100),
43
+ offset: parseValue(raw.offset, 0, 0)
44
+ };
45
+ };
46
+ const messageFor = ({ expected, value }) => {
47
+ const length = typeof value === "string" ? value.length : null;
48
+ const min = expected.match(/MinLength<(\d+)>/);
49
+ if (min && length !== null && length < Number(min[1])) return min[1] === "1" ? "Required" : `At least ${min[1]} characters`;
50
+ const max = expected.match(/MaxLength<(\d+)>/);
51
+ if (max && length !== null && length > Number(max[1])) return `At most ${max[1]} characters`;
52
+ if (expected.includes("Format<\"email\">")) return "Invalid email";
53
+ if (expected.includes("Pattern<")) return "Invalid format";
54
+ if (value === void 0) return "Required";
55
+ return `Expected ${expected}`;
56
+ };
57
+ const fieldKeyOf = (path) => path === "$input" ? "body" : path.replace(/^\$input\./, "").split(/[.[]/)[0];
58
+ const parseBody = (validate, body) => {
59
+ const result = validate(body);
60
+ if (result.success) return result.data;
61
+ const errors = {};
62
+ for (const error of result.errors) {
63
+ const key = fieldKeyOf(error.path);
64
+ if (!(key in errors)) errors[key] = messageFor(error);
65
+ }
66
+ throw new ValidationError(errors);
67
+ };
68
+ const Body = (validate) => createParamDecorator((req) => validate ? parseBody(validate, req.body) : req.body);
69
+ const IdParam = (name) => createParamDecorator((req) => parseId(req.params[name]));
70
+ const OrdinalParam = (name) => createParamDecorator((req) => parseOrdinal(req.params[name]));
71
+ const Param = (name) => createParamDecorator((req) => req.params[name]);
72
+ const Query = (name) => createParamDecorator((req) => req.query[name]);
73
+ const IdQuery = (name) => createParamDecorator((req) => parseId(req.query[name]));
74
+ const OptionalIdQuery = (name) => createParamDecorator((req) => {
75
+ const raw = req.query[name];
76
+ return raw === void 0 ? void 0 : parseId(raw);
77
+ });
78
+ const Pagination = (options) => createParamDecorator((req) => parsePagination(req.query, options));
79
+ const UploadedFile = () => createParamDecorator(async (req) => {
80
+ const part = await req.file();
81
+ if (!part) throw RequestError.FileMissing();
82
+ try {
83
+ const buffer = await part.toBuffer();
84
+ return {
85
+ filename: part.filename,
86
+ buffer
87
+ };
88
+ } catch (error) {
89
+ if (error instanceof Error && error.code === "FST_REQ_FILE_TOO_LARGE") throw RequestError.FileTooLarge();
90
+ throw error;
91
+ }
92
+ });
93
+ export { Body, IdParam, IdQuery, OptionalIdQuery, OrdinalParam, Pagination, Param, Query, UploadedFile, bindingsByController, createParamDecorator, getParamResolvers, parseBody, parseId, parseOrdinal, parsePagination };
@@ -0,0 +1,20 @@
1
+ import { Page } from "./params.js";
2
+ import { PageMeta } from "@pollium/readable-contracts/http";
3
+ export declare class Paginated<T> {
4
+ readonly items: T[];
5
+ readonly page: Page;
6
+ readonly total: number;
7
+ constructor(items: T[], page: Page, total: number);
8
+ get meta(): PageMeta;
9
+ }
10
+ export declare class RawResponse {
11
+ readonly body: string | Buffer;
12
+ readonly contentType: string;
13
+ readonly status: number;
14
+ constructor(body: string | Buffer, contentType: string, status?: number);
15
+ }
16
+ export declare class RedirectResponse {
17
+ readonly url: string;
18
+ readonly status: number;
19
+ constructor(url: string, status?: number);
20
+ }
@@ -0,0 +1,29 @@
1
+ // lib/http/responses.ts
2
+ var Paginated = class {
3
+ constructor(items, page, total) {
4
+ this.items = items;
5
+ this.page = page;
6
+ this.total = total;
7
+ }
8
+ get meta() {
9
+ return {
10
+ total: this.total,
11
+ limit: this.page.limit,
12
+ offset: this.page.offset
13
+ };
14
+ }
15
+ };
16
+ var RawResponse = class {
17
+ constructor(body, contentType, status = 200) {
18
+ this.body = body;
19
+ this.contentType = contentType;
20
+ this.status = status;
21
+ }
22
+ };
23
+ var RedirectResponse = class {
24
+ constructor(url, status = 302) {
25
+ this.url = url;
26
+ this.status = status;
27
+ }
28
+ };
29
+ export { Paginated, RawResponse, RedirectResponse };
@@ -0,0 +1,15 @@
1
+ import { JobsOptions, RateLimiterOptions, RepeatOptions, Worker } from "bullmq";
2
+ export default abstract class BaseQueue<T> {
3
+ #private;
4
+ abstract readonly name: string;
5
+ protected readonly concurrency: number;
6
+ protected readonly limiter: RateLimiterOptions | undefined;
7
+ protected readonly lockDuration: number;
8
+ protected readonly everyMs: number | undefined;
9
+ protected readonly jobOptions: JobsOptions;
10
+ add(data: T, options?: JobsOptions): Promise<void>;
11
+ abstract process(data: T): Promise<void>;
12
+ protected schedule(repeat: Partial<RepeatOptions>, data?: T): Promise<void>;
13
+ startWorker(): Worker;
14
+ close(): Promise<void>;
15
+ }
@@ -0,0 +1,69 @@
1
+ import { redisOptions } from "../app/redis.js";
2
+ import { logger } from "../app/logger.js";
3
+ import { Queue, Worker } from "bullmq";
4
+ // lib/queues/BaseQueue.ts
5
+ var BaseQueue = class {
6
+ constructor() {
7
+ this.concurrency = 1;
8
+ this.limiter = void 0;
9
+ this.lockDuration = 3e4;
10
+ this.everyMs = void 0;
11
+ this.jobOptions = {
12
+ attempts: 3,
13
+ backoff: {
14
+ type: "exponential",
15
+ delay: 1e3
16
+ }
17
+ };
18
+ }
19
+ #queue;
20
+ #worker;
21
+ async add(data, options = {}) {
22
+ const job = await this.#connect().add(this.name, data, {
23
+ ...this.jobOptions,
24
+ ...options
25
+ });
26
+ this.#trace("enqueue", job);
27
+ }
28
+ async schedule(repeat, data) {
29
+ await this.#connect().upsertJobScheduler(this.name, repeat, {
30
+ name: this.name,
31
+ data
32
+ });
33
+ this.#trace("schedule");
34
+ }
35
+ startWorker() {
36
+ this.#worker ??= this.#traced(new Worker(this.name, (job) => this.process(job.data), {
37
+ connection: redisOptions(),
38
+ concurrency: this.concurrency,
39
+ limiter: this.limiter,
40
+ lockDuration: this.lockDuration
41
+ }));
42
+ if (this.everyMs !== void 0) this.schedule({ every: this.everyMs });
43
+ return this.#worker;
44
+ }
45
+ async close() {
46
+ await this.#worker?.close();
47
+ await this.#queue?.close();
48
+ }
49
+ #connect() {
50
+ this.#queue ??= new Queue(this.name, { connection: redisOptions() });
51
+ return this.#queue;
52
+ }
53
+ #traced(worker) {
54
+ for (const stage of [
55
+ "active",
56
+ "completed",
57
+ "failed"
58
+ ]) worker.on(stage, (job) => this.#trace(stage, job));
59
+ return worker;
60
+ }
61
+ #trace(stage, job) {
62
+ logger.debug(this.name, {
63
+ scope: `queue.${stage}`,
64
+ jobId: job?.id,
65
+ attempts: job?.attemptsMade
66
+ });
67
+ }
68
+ };
69
+ export { BaseQueue as default };
@@ -0,0 +1,37 @@
1
+ export interface StoredObject {
2
+ key: string;
3
+ size: number;
4
+ modifiedAt: Date;
5
+ }
6
+ export interface StoredPage {
7
+ objects: StoredObject[];
8
+ folders: string[];
9
+ cursor: string | null;
10
+ }
11
+ export interface StoredStat {
12
+ size: number;
13
+ modifiedAt: Date;
14
+ contentType: string | null;
15
+ cacheControl: string | null;
16
+ etag: string | null;
17
+ }
18
+ export interface ListOptions {
19
+ grouped: boolean;
20
+ limit: number;
21
+ cursor?: string;
22
+ }
23
+ declare class ObjectStorage {
24
+ #private;
25
+ put(key: string, body: string | Uint8Array, contentType: string): Promise<void>;
26
+ putImmutable(key: string, body: string | Uint8Array, contentType: string): Promise<void>;
27
+ putDownload(key: string, body: string | Uint8Array, contentType: string, filename: string): Promise<void>;
28
+ get(key: string): Promise<Buffer>;
29
+ list(prefix: string, options: ListOptions): Promise<StoredPage>;
30
+ stat(key: string): Promise<StoredStat | null>;
31
+ exists(key: string): Promise<boolean>;
32
+ delete(key: string): Promise<void>;
33
+ deletePrefix(prefix: string): Promise<void>;
34
+ publicUrl(key: string): string;
35
+ }
36
+ export declare const objectStorage: ObjectStorage;
37
+ export {};
@@ -0,0 +1,170 @@
1
+ import { storageConfig } from "../app/config.js";
2
+ import { CreateBucketCommand, DeleteObjectCommand, GetObjectCommand, HeadBucketCommand, HeadObjectCommand, ListObjectsV2Command, PutBucketCorsCommand, PutBucketPolicyCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
3
+ // lib/storage/ObjectStorage.ts
4
+ var ObjectStorage = class {
5
+ #ensured;
6
+ #client;
7
+ #immutableCacheControl = "public, max-age=31536000, immutable";
8
+ #s3() {
9
+ this.#client ??= new S3Client({
10
+ endpoint: storageConfig().endpoint,
11
+ region: storageConfig().region,
12
+ forcePathStyle: true,
13
+ credentials: {
14
+ accessKeyId: storageConfig().accessKey,
15
+ secretAccessKey: storageConfig().secretKey
16
+ }
17
+ });
18
+ return this.#client;
19
+ }
20
+ put(key, body, contentType) {
21
+ return this.#write(key, body, contentType);
22
+ }
23
+ putImmutable(key, body, contentType) {
24
+ return this.#write(key, body, contentType, this.#immutableCacheControl);
25
+ }
26
+ putDownload(key, body, contentType, filename) {
27
+ return this.#write(key, body, contentType, this.#immutableCacheControl, `attachment; filename="${filename.replace(/["\\]/g, "")}"`);
28
+ }
29
+ async get(key) {
30
+ await this.#ensureBucket();
31
+ const found = await this.#s3().send(new GetObjectCommand({
32
+ Bucket: storageConfig().bucket,
33
+ Key: key
34
+ }));
35
+ return Buffer.from(await found.Body.transformToByteArray());
36
+ }
37
+ async list(prefix, options) {
38
+ await this.#ensureBucket();
39
+ const page = await this.#s3().send(new ListObjectsV2Command({
40
+ Bucket: storageConfig().bucket,
41
+ Prefix: prefix === "" ? void 0 : prefix,
42
+ Delimiter: options.grouped ? "/" : void 0,
43
+ MaxKeys: options.limit,
44
+ ContinuationToken: options.cursor
45
+ }));
46
+ return {
47
+ objects: (page.Contents ?? []).map((object) => ({
48
+ key: object.Key,
49
+ size: object.Size,
50
+ modifiedAt: object.LastModified
51
+ })),
52
+ folders: (page.CommonPrefixes ?? []).map((common) => common.Prefix),
53
+ cursor: page.NextContinuationToken ?? null
54
+ };
55
+ }
56
+ async stat(key) {
57
+ await this.#ensureBucket();
58
+ try {
59
+ const head = await this.#s3().send(new HeadObjectCommand({
60
+ Bucket: storageConfig().bucket,
61
+ Key: key
62
+ }));
63
+ return {
64
+ size: head.ContentLength ?? 0,
65
+ modifiedAt: head.LastModified,
66
+ contentType: head.ContentType ?? null,
67
+ cacheControl: head.CacheControl ?? null,
68
+ etag: head.ETag ?? null
69
+ };
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+ async exists(key) {
75
+ await this.#ensureBucket();
76
+ try {
77
+ await this.#s3().send(new HeadObjectCommand({
78
+ Bucket: storageConfig().bucket,
79
+ Key: key
80
+ }));
81
+ return true;
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+ async delete(key) {
87
+ await this.#ensureBucket();
88
+ await this.#s3().send(new DeleteObjectCommand({
89
+ Bucket: storageConfig().bucket,
90
+ Key: key
91
+ }));
92
+ }
93
+ async deletePrefix(prefix) {
94
+ let cursor;
95
+ do {
96
+ const page = await this.list(prefix, {
97
+ grouped: false,
98
+ limit: 1e3,
99
+ cursor
100
+ });
101
+ for (const object of page.objects) await this.delete(object.key);
102
+ cursor = page.cursor ?? void 0;
103
+ } while (cursor !== void 0);
104
+ }
105
+ publicUrl(key) {
106
+ return `${storageConfig().publicUrl}/${storageConfig().bucket}/${key}`;
107
+ }
108
+ async #write(key, body, contentType, cacheControl, contentDisposition) {
109
+ const scriptableType = /^(text\/html|application\/xhtml\+xml|image\/svg\+xml|text\/xml|application\/xml)\b/i;
110
+ await this.#ensureBucket();
111
+ await this.#s3().send(new PutObjectCommand({
112
+ Bucket: storageConfig().bucket,
113
+ Key: key,
114
+ Body: body,
115
+ ContentType: contentType,
116
+ CacheControl: cacheControl,
117
+ ContentDisposition: contentDisposition ?? (scriptableType.test(contentType) ? "attachment" : void 0)
118
+ }));
119
+ }
120
+ #ensureBucket() {
121
+ this.#ensured ??= this.#headOrCreate().catch((error) => {
122
+ this.#ensured = void 0;
123
+ throw error;
124
+ });
125
+ return this.#ensured;
126
+ }
127
+ async #headOrCreate() {
128
+ try {
129
+ await this.#s3().send(new HeadBucketCommand({ Bucket: storageConfig().bucket }));
130
+ } catch {
131
+ await this.#s3().send(new CreateBucketCommand({ Bucket: storageConfig().bucket }));
132
+ await this.#setPublicReadPolicy();
133
+ }
134
+ await this.#allowBrowserReads();
135
+ }
136
+ async #allowBrowserReads() {
137
+ await this.#s3().send(new PutBucketCorsCommand({
138
+ Bucket: storageConfig().bucket,
139
+ CORSConfiguration: { CORSRules: [{
140
+ AllowedMethods: ["GET", "HEAD"],
141
+ AllowedOrigins: ["*"],
142
+ AllowedHeaders: ["*"],
143
+ ExposeHeaders: [
144
+ "Content-Length",
145
+ "Content-Range",
146
+ "Accept-Ranges"
147
+ ],
148
+ MaxAgeSeconds: 3600
149
+ }] }
150
+ }));
151
+ }
152
+ async #setPublicReadPolicy() {
153
+ const policy = {
154
+ Version: "2012-10-17",
155
+ Statement: [{
156
+ Sid: "PublicRead",
157
+ Effect: "Allow",
158
+ Principal: "*",
159
+ Action: ["s3:GetObject"],
160
+ Resource: [`arn:aws:s3:::${storageConfig().bucket}/*`]
161
+ }]
162
+ };
163
+ await this.#s3().send(new PutBucketPolicyCommand({
164
+ Bucket: storageConfig().bucket,
165
+ Policy: JSON.stringify(policy)
166
+ }));
167
+ }
168
+ };
169
+ const objectStorage = new ObjectStorage();
170
+ export { objectStorage };
@@ -0,0 +1,25 @@
1
+ import { FastifyInstance } from "fastify";
2
+ import { DataSource } from "typeorm";
3
+ export interface TestApp {
4
+ app: FastifyInstance;
5
+ dataSource: DataSource;
6
+ resetDb: () => Promise<void>;
7
+ close: () => Promise<void>;
8
+ }
9
+ export interface HarnessOptions {
10
+ createApp: () => {
11
+ build: (options?: {
12
+ queues?: boolean;
13
+ }) => Promise<FastifyInstance>;
14
+ dataSource?: DataSource;
15
+ stop: () => Promise<void>;
16
+ };
17
+ schema: string | undefined;
18
+ onReset?: (dataSource: DataSource) => Promise<void> | void;
19
+ onBeforeAll?: () => Promise<void> | void;
20
+ onBeforeEach?: () => Promise<void> | void;
21
+ }
22
+ export declare const requireTestSchema: (schema: string | undefined) => string;
23
+ export declare const truncateSchema: (dataSource: DataSource, schema: string) => Promise<void>;
24
+ export declare const createTestApp: (options: HarnessOptions) => Promise<TestApp>;
25
+ export declare const useApp: (options: HarnessOptions) => TestApp;
@@ -0,0 +1,46 @@
1
+ import BaseQueue from "../queues/BaseQueue.js";
2
+ import { ConfigError } from "../app/errors.js";
3
+ import { eventBus } from "../events/EventBus.js";
4
+ import { afterAll, afterEach, beforeAll, beforeEach, vi } from "vitest";
5
+ // lib/testing/harness.ts
6
+ const requireTestSchema = (schema) => {
7
+ if (!schema || schema === "public") throw ConfigError.MissingEnv("DATABASE_SCHEMA");
8
+ return schema;
9
+ };
10
+ const truncateSchema = async (dataSource, schema) => {
11
+ const rows = await dataSource.query("SELECT tablename FROM pg_tables WHERE schemaname = $1", [schema]);
12
+ if (rows.length === 0) return;
13
+ const tables = rows.map((row) => `"${schema}"."${row.tablename}"`).join(", ");
14
+ await dataSource.query(`TRUNCATE ${tables} RESTART IDENTITY CASCADE`);
15
+ };
16
+ const createTestApp = async (options) => {
17
+ const application = options.createApp();
18
+ const app = await application.build({ queues: false });
19
+ const dataSource = application.dataSource;
20
+ const schema = requireTestSchema(options.schema);
21
+ return {
22
+ app,
23
+ dataSource,
24
+ resetDb: async () => {
25
+ await truncateSchema(dataSource, schema);
26
+ await options.onReset?.(dataSource);
27
+ },
28
+ close: () => application.stop()
29
+ };
30
+ };
31
+ const useApp = (options) => {
32
+ const ctx = {};
33
+ beforeAll(async () => {
34
+ await options.onBeforeAll?.();
35
+ Object.assign(ctx, await createTestApp(options));
36
+ });
37
+ afterAll(() => ctx.close());
38
+ beforeEach(async () => {
39
+ vi.spyOn(BaseQueue.prototype, "add").mockResolvedValue();
40
+ await options.onBeforeEach?.();
41
+ await ctx.resetDb();
42
+ });
43
+ afterEach(() => eventBus.settled());
44
+ return ctx;
45
+ };
46
+ export { createTestApp, requireTestSchema, truncateSchema, useApp };
@@ -0,0 +1 @@
1
+ export declare const rateLimitStore: any;
@@ -0,0 +1,4 @@
1
+ import RedisStore from "@fastify/rate-limit/store/RedisStore.js";
2
+ // lib/testing/rate-limit.ts
3
+ const rateLimitStore = RedisStore.prototype;
4
+ export { rateLimitStore };
@@ -0,0 +1,21 @@
1
+ import { FastifyInstance } from "fastify";
2
+ import { Endpoint, HttpMethod } from "@pollium/readable-contracts/routing";
3
+ type QueryParams = Record<string, number | string>;
4
+ export interface RequestOptions<I> {
5
+ as?: string;
6
+ body?: I;
7
+ params?: QueryParams;
8
+ query?: QueryParams;
9
+ headers?: Record<string, string>;
10
+ }
11
+ export interface TestResponse<O> {
12
+ status: number;
13
+ body: string;
14
+ json: <T = Record<string, unknown>>() => T;
15
+ data: () => O;
16
+ }
17
+ export declare const authHeader: (userId: string) => Record<string, string>;
18
+ export declare const request: <I, O>(app: FastifyInstance, endpoint: Endpoint<I, O>, { as, body, params, query, headers }?: RequestOptions<I>) => Promise<TestResponse<O>>;
19
+ export declare const route: (method: HttpMethod, path: string) => Endpoint<unknown, unknown>;
20
+ export declare const expectError: (res: TestResponse<unknown>, status: number, code: string) => void;
21
+ export {};
@@ -0,0 +1,41 @@
1
+ import { JWTService } from "../auth/sessions.js";
2
+ import { expect } from "vitest";
3
+ // lib/testing/request.ts
4
+ const authHeader = (userId) => ({ authorization: `Bearer ${new JWTService().sign(userId)}` });
5
+ const withParams = (path, params) => {
6
+ let url = path;
7
+ for (const [name, value] of Object.entries(params)) url = url.replace(`:${name}`, String(value));
8
+ return url;
9
+ };
10
+ const withQuery = (url, query) => {
11
+ if (!query) return url;
12
+ const search = new URLSearchParams();
13
+ for (const [key, value] of Object.entries(query)) search.set(key, String(value));
14
+ return `${url}?${search}`;
15
+ };
16
+ const request = async (app, endpoint, { as, body, params = {}, query, headers } = {}) => {
17
+ const res = await app.inject({
18
+ method: endpoint.method,
19
+ url: withQuery(withParams(endpoint.path, params), query),
20
+ headers: {
21
+ ...headers,
22
+ ...as === void 0 ? {} : authHeader(as)
23
+ },
24
+ payload: body
25
+ });
26
+ return {
27
+ status: res.statusCode,
28
+ body: res.body,
29
+ json: () => res.json(),
30
+ data: () => res.json().data
31
+ };
32
+ };
33
+ const route = (method, path) => ({
34
+ method,
35
+ path
36
+ });
37
+ const expectError = (res, status, code) => {
38
+ expect(res.status).toBe(status);
39
+ expect(res.json()).toMatchObject({ error: code });
40
+ };
41
+ export { authHeader, expectError, request, route };
@@ -0,0 +1,33 @@
1
+ import { ILlmSchema, IValidation } from "typia";
2
+ export declare enum ToolAccess {
3
+ Read = "read",
4
+ Write = "write"
5
+ }
6
+ export interface ToolContext {
7
+ userId: string;
8
+ teamId: string;
9
+ sessionId: string;
10
+ }
11
+ export interface ToolDefinition<T> {
12
+ description: string;
13
+ access: ToolAccess;
14
+ parameters: ILlmSchema.IParameters;
15
+ validate: (input: unknown) => IValidation<T>;
16
+ decline?: string;
17
+ unattended?: boolean;
18
+ approval?: boolean;
19
+ }
20
+ export interface ToolApprovalOptions {
21
+ unattended?: boolean;
22
+ omit?: readonly string[];
23
+ }
24
+ export interface ToolBinding {
25
+ tool: string;
26
+ handlerName: string | symbol;
27
+ definition: ToolDefinition<unknown>;
28
+ }
29
+ export type ToolHandler = (context: ToolContext, input: never) => unknown;
30
+ export declare const DefineToolGroup: (group: string) => ClassDecorator;
31
+ export declare const getToolGroup: (ctor: object) => string | undefined;
32
+ export declare const Tool: <T>(definition: ToolDefinition<T>) => MethodDecorator;
33
+ export declare const getTools: (ctor: object) => ToolBinding[];
@@ -0,0 +1,30 @@
1
+ import { ClassMetadata } from "../app/metadata.js";
2
+ // lib/tools/ToolGroup.ts
3
+ let ToolAccess = /* @__PURE__ */ function(ToolAccess) {
4
+ ToolAccess["Read"] = "read";
5
+ ToolAccess["Write"] = "write";
6
+ return ToolAccess;
7
+ }({});
8
+ const groupByClass = /* @__PURE__ */ new WeakMap();
9
+ const toolsByClass = new ClassMetadata();
10
+ const DefineToolGroup = (group) => {
11
+ return (target) => {
12
+ groupByClass.set(target, group);
13
+ };
14
+ };
15
+ const getToolGroup = (ctor) => {
16
+ return groupByClass.get(ctor);
17
+ };
18
+ const Tool = (definition) => {
19
+ return (target, handlerName) => {
20
+ toolsByClass.append(target.constructor, {
21
+ tool: String(handlerName),
22
+ handlerName,
23
+ definition
24
+ });
25
+ };
26
+ };
27
+ const getTools = (ctor) => {
28
+ return toolsByClass.get(ctor);
29
+ };
30
+ export { DefineToolGroup, Tool, ToolAccess, getToolGroup, getTools };