|
| 1 | +import { Identifier } from "@/id/id" |
| 2 | +import { withStatics } from "@/util/schema" |
| 3 | +import { DateTime, Effect, Schema } from "effect" |
| 4 | + |
| 5 | +export namespace Message { |
| 6 | + export const ID = Schema.String.pipe(Schema.brand("Message.ID")).pipe( |
| 7 | + withStatics((s) => ({ |
| 8 | + create: () => s.make(Identifier.ascending("message")), |
| 9 | + prefix: "msg", |
| 10 | + })), |
| 11 | + ) |
| 12 | + |
| 13 | + export class File extends Schema.Class<File>("Message.File")({ |
| 14 | + url: Schema.String, |
| 15 | + mime: Schema.String, |
| 16 | + }) { |
| 17 | + static create(url: string) { |
| 18 | + return new File({ |
| 19 | + url, |
| 20 | + mime: "text/plain", |
| 21 | + }) |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + export class UserContent extends Schema.Class<UserContent>("Message.User.Content")({ |
| 26 | + text: Schema.String, |
| 27 | + synthetic: Schema.Boolean.pipe(Schema.optional), |
| 28 | + agent: Schema.String.pipe(Schema.optional), |
| 29 | + files: Schema.Array(File).pipe(Schema.optional), |
| 30 | + }) {} |
| 31 | + |
| 32 | + export class User extends Schema.Class<User>("Message.User")({ |
| 33 | + id: ID, |
| 34 | + type: Schema.Literal("user"), |
| 35 | + time: Schema.Struct({ |
| 36 | + created: Schema.DateTimeUtc, |
| 37 | + }), |
| 38 | + content: UserContent, |
| 39 | + }) { |
| 40 | + static create(content: Schema.Schema.Type<typeof UserContent>) { |
| 41 | + const msg = new User({ |
| 42 | + id: ID.create(), |
| 43 | + type: "user", |
| 44 | + time: { |
| 45 | + created: Effect.runSync(DateTime.now), |
| 46 | + }, |
| 47 | + content, |
| 48 | + }) |
| 49 | + return msg |
| 50 | + } |
| 51 | + |
| 52 | + static file(url: string) { |
| 53 | + return new File({ |
| 54 | + url, |
| 55 | + mime: "text/plain", |
| 56 | + }) |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + export namespace User {} |
| 61 | +} |
| 62 | + |
| 63 | +const msg = Message.User.create({ |
| 64 | + text: "Hello world", |
| 65 | + files: [Message.File.create("file://example.com/file.txt")], |
| 66 | +}) |
| 67 | + |
| 68 | +console.log(JSON.stringify(msg, null, 2)) |
0 commit comments