mirror of
https://github.com/kennethnym/aris.git
synced 2026-03-20 17:11:17 +00:00
Compare commits
24 Commits
feat/repla
...
fix/remove
| Author | SHA1 | Date | |
|---|---|---|---|
|
5988fd5b81
|
|||
| 28d26b3c87 | |||
| 78b0ed94bd | |||
| ee957ea7b1 | |||
| 6ae0ad1d40 | |||
|
941acb826c
|
|||
| 3d492a5d56 | |||
|
08dd437952
|
|||
| 2fc20759dd | |||
|
963bf073d1
|
|||
| c0b3db0e11 | |||
|
ca4a337dcd
|
|||
| 769e2d4eb0 | |||
|
5e9094710d
|
|||
|
5556f3fbf9
|
|||
|
0176979925
|
|||
|
971aba0932
|
|||
|
68e319e4b8
|
|||
| c042af88f3 | |||
|
0608f2ac61
|
|||
| 1ade63dd8c | |||
|
8df340d9af
|
|||
|
727280e8b1
|
|||
| d30f70494b |
@@ -13,8 +13,6 @@
|
||||
"@aris/source-location": "workspace:*",
|
||||
"@aris/source-tfl": "workspace:*",
|
||||
"@aris/source-weatherkit": "workspace:*",
|
||||
"@hono/trpc-server": "^0.3",
|
||||
"@trpc/server": "^11",
|
||||
"arktype": "^2.1.29",
|
||||
"better-auth": "^1",
|
||||
"hono": "^4",
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import type { Context, Next } from "hono"
|
||||
import type { Context, MiddlewareHandler, Next } from "hono"
|
||||
|
||||
import type { AuthSession, AuthUser } from "./session.ts"
|
||||
|
||||
import { auth } from "./index.ts"
|
||||
|
||||
type SessionUser = typeof auth.$Infer.Session.user
|
||||
type Session = typeof auth.$Infer.Session.session
|
||||
|
||||
export interface SessionVariables {
|
||||
user: SessionUser | null
|
||||
session: Session | null
|
||||
user: AuthUser | null
|
||||
session: AuthSession | null
|
||||
}
|
||||
|
||||
export type AuthSessionEnv = { Variables: SessionVariables }
|
||||
|
||||
export type AuthSessionMiddleware = MiddlewareHandler<AuthSessionEnv>
|
||||
|
||||
declare module "hono" {
|
||||
interface ContextVariableMap extends SessionVariables {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,7 +55,22 @@ export async function requireSession(c: Context, next: Next): Promise<Response |
|
||||
*/
|
||||
export async function getSessionFromHeaders(
|
||||
headers: Headers,
|
||||
): Promise<{ user: SessionUser; session: Session } | null> {
|
||||
): Promise<{ user: AuthUser; session: AuthSession } | null> {
|
||||
const session = await auth.api.getSession({ headers })
|
||||
return session
|
||||
}
|
||||
|
||||
/**
|
||||
* Test-only middleware that injects a fake user and session.
|
||||
* Pass userId to simulate an authenticated request, or omit to get 401.
|
||||
*/
|
||||
export function mockAuthSessionMiddleware(userId?: string): AuthSessionMiddleware {
|
||||
return async (c: Context, next: Next): Promise<Response | void> => {
|
||||
if (!userId) {
|
||||
return c.json({ error: "Unauthorized" }, 401)
|
||||
}
|
||||
c.set("user", { id: userId } as AuthUser)
|
||||
c.set("session", { id: "mock-session" } as AuthSession)
|
||||
await next()
|
||||
}
|
||||
}
|
||||
|
||||
4
apps/aris-backend/src/auth/session.ts
Normal file
4
apps/aris-backend/src/auth/session.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import type { auth } from "./index.ts"
|
||||
|
||||
export type AuthUser = typeof auth.$Infer.Session.user
|
||||
export type AuthSession = typeof auth.$Infer.Session.session
|
||||
140
apps/aris-backend/src/feed/http.test.ts
Normal file
140
apps/aris-backend/src/feed/http.test.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import type { ActionDefinition, Context, FeedItem, FeedSource } from "@aris/core"
|
||||
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Hono } from "hono"
|
||||
|
||||
import { mockAuthSessionMiddleware } from "../auth/session-middleware.ts"
|
||||
import { UserSessionManager } from "../session/index.ts"
|
||||
import { registerFeedHttpHandlers } from "./http.ts"
|
||||
|
||||
interface FeedResponse {
|
||||
items: Array<{
|
||||
id: string
|
||||
type: string
|
||||
priority: number
|
||||
timestamp: string
|
||||
data: Record<string, unknown>
|
||||
}>
|
||||
errors: Array<{ sourceId: string; error: string }>
|
||||
}
|
||||
|
||||
function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
|
||||
return {
|
||||
id,
|
||||
async listActions(): Promise<Record<string, ActionDefinition>> {
|
||||
return {}
|
||||
},
|
||||
async executeAction(): Promise<unknown> {
|
||||
return undefined
|
||||
},
|
||||
async fetchContext(): Promise<Partial<Context> | null> {
|
||||
return null
|
||||
},
|
||||
async fetchItems() {
|
||||
return items
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function buildTestApp(sessionManager: UserSessionManager, userId?: string) {
|
||||
const app = new Hono()
|
||||
registerFeedHttpHandlers(app, {
|
||||
sessionManager,
|
||||
authSessionMiddleware: mockAuthSessionMiddleware(userId),
|
||||
})
|
||||
return app
|
||||
}
|
||||
|
||||
describe("GET /api/feed", () => {
|
||||
test("returns 401 without auth", async () => {
|
||||
const manager = new UserSessionManager([])
|
||||
const app = buildTestApp(manager)
|
||||
|
||||
const res = await app.request("/api/feed")
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test("returns cached feed when available", async () => {
|
||||
const items: FeedItem[] = [
|
||||
{
|
||||
id: "item-1",
|
||||
type: "test",
|
||||
priority: 0.8,
|
||||
timestamp: new Date("2025-01-01T00:00:00.000Z"),
|
||||
data: { value: 42 },
|
||||
},
|
||||
]
|
||||
const manager = new UserSessionManager([() => createStubSource("test", items)])
|
||||
const app = buildTestApp(manager, "user-1")
|
||||
|
||||
// Prime the cache
|
||||
const session = manager.getOrCreate("user-1")
|
||||
await session.engine.refresh()
|
||||
expect(session.engine.lastFeed()).not.toBeNull()
|
||||
|
||||
const res = await app.request("/api/feed")
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as FeedResponse
|
||||
expect(body.items).toHaveLength(1)
|
||||
expect(body.items[0]!.id).toBe("item-1")
|
||||
expect(body.items[0]!.type).toBe("test")
|
||||
expect(body.items[0]!.priority).toBe(0.8)
|
||||
expect(body.items[0]!.timestamp).toBe("2025-01-01T00:00:00.000Z")
|
||||
expect(body.errors).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("forces refresh when no cached feed", async () => {
|
||||
const items: FeedItem[] = [
|
||||
{
|
||||
id: "fresh-1",
|
||||
type: "test",
|
||||
priority: 0.5,
|
||||
timestamp: new Date("2025-06-01T12:00:00.000Z"),
|
||||
data: { fresh: true },
|
||||
},
|
||||
]
|
||||
const manager = new UserSessionManager([() => createStubSource("test", items)])
|
||||
const app = buildTestApp(manager, "user-1")
|
||||
|
||||
// No prior refresh — lastFeed() returns null, handler should call refresh()
|
||||
const res = await app.request("/api/feed")
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as FeedResponse
|
||||
expect(body.items).toHaveLength(1)
|
||||
expect(body.items[0]!.id).toBe("fresh-1")
|
||||
expect(body.items[0]!.data.fresh).toBe(true)
|
||||
expect(body.errors).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("serializes source errors as message strings", async () => {
|
||||
const failingSource: FeedSource = {
|
||||
id: "failing",
|
||||
async listActions() {
|
||||
return {}
|
||||
},
|
||||
async executeAction() {
|
||||
return undefined
|
||||
},
|
||||
async fetchContext() {
|
||||
return null
|
||||
},
|
||||
async fetchItems() {
|
||||
throw new Error("connection timeout")
|
||||
},
|
||||
}
|
||||
const manager = new UserSessionManager([() => failingSource])
|
||||
const app = buildTestApp(manager, "user-1")
|
||||
|
||||
const res = await app.request("/api/feed")
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as FeedResponse
|
||||
expect(body.items).toHaveLength(0)
|
||||
expect(body.errors).toHaveLength(1)
|
||||
expect(body.errors[0]!.sourceId).toBe("failing")
|
||||
expect(body.errors[0]!.error).toBe("connection timeout")
|
||||
})
|
||||
})
|
||||
41
apps/aris-backend/src/feed/http.ts
Normal file
41
apps/aris-backend/src/feed/http.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { Context, Hono } from "hono"
|
||||
|
||||
import { createMiddleware } from "hono/factory"
|
||||
|
||||
import type { AuthSessionMiddleware } from "../auth/session-middleware.ts"
|
||||
import type { UserSessionManager } from "../session/index.ts"
|
||||
|
||||
type Env = { Variables: { sessionManager: UserSessionManager } }
|
||||
|
||||
interface FeedHttpHandlersDeps {
|
||||
sessionManager: UserSessionManager
|
||||
authSessionMiddleware: AuthSessionMiddleware
|
||||
}
|
||||
|
||||
export function registerFeedHttpHandlers(
|
||||
app: Hono,
|
||||
{ sessionManager, authSessionMiddleware }: FeedHttpHandlersDeps,
|
||||
) {
|
||||
const inject = createMiddleware<Env>(async (c, next) => {
|
||||
c.set("sessionManager", sessionManager)
|
||||
await next()
|
||||
})
|
||||
|
||||
app.get("/api/feed", inject, authSessionMiddleware, handleGetFeed)
|
||||
}
|
||||
|
||||
async function handleGetFeed(c: Context<Env>) {
|
||||
const user = c.get("user")!
|
||||
const sessionManager = c.get("sessionManager")
|
||||
const session = sessionManager.getOrCreate(user.id)
|
||||
|
||||
const feed = session.engine.lastFeed() ?? (await session.engine.refresh())
|
||||
|
||||
return c.json({
|
||||
items: feed.items,
|
||||
errors: feed.errors.map((e) => ({
|
||||
sourceId: e.sourceId,
|
||||
error: e.error.message,
|
||||
})),
|
||||
})
|
||||
}
|
||||
56
apps/aris-backend/src/location/http.ts
Normal file
56
apps/aris-backend/src/location/http.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import type { Context, Hono } from "hono"
|
||||
|
||||
import { type } from "arktype"
|
||||
import { createMiddleware } from "hono/factory"
|
||||
|
||||
import type { UserSessionManager } from "../session/index.ts"
|
||||
|
||||
import { requireSession } from "../auth/session-middleware.ts"
|
||||
|
||||
type Env = { Variables: { sessionManager: UserSessionManager } }
|
||||
|
||||
const locationInput = type({
|
||||
lat: "number",
|
||||
lng: "number",
|
||||
accuracy: "number",
|
||||
timestamp: "string.date.iso",
|
||||
})
|
||||
|
||||
export function registerLocationHttpHandlers(
|
||||
app: Hono,
|
||||
{ sessionManager }: { sessionManager: UserSessionManager },
|
||||
) {
|
||||
const inject = createMiddleware<Env>(async (c, next) => {
|
||||
c.set("sessionManager", sessionManager)
|
||||
await next()
|
||||
})
|
||||
|
||||
app.post("/api/location", inject, requireSession, handleUpdateLocation)
|
||||
}
|
||||
|
||||
async function handleUpdateLocation(c: Context<Env>) {
|
||||
let body: unknown
|
||||
try {
|
||||
body = await c.req.json()
|
||||
} catch {
|
||||
return c.json({ error: "Invalid JSON" }, 400)
|
||||
}
|
||||
|
||||
const result = locationInput(body)
|
||||
|
||||
if (result instanceof type.errors) {
|
||||
return c.json({ error: result.summary }, 400)
|
||||
}
|
||||
|
||||
const user = c.get("user")!
|
||||
const sessionManager = c.get("sessionManager")
|
||||
const session = sessionManager.getOrCreate(user.id)
|
||||
await session.engine.executeAction("aris.location", "update-location", {
|
||||
lat: result.lat,
|
||||
lng: result.lng,
|
||||
accuracy: result.accuracy,
|
||||
timestamp: new Date(result.timestamp),
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { type } from "arktype"
|
||||
|
||||
import type { UserSessionManager } from "../session/index.ts"
|
||||
import type { TRPC } from "../trpc/router.ts"
|
||||
|
||||
const locationInput = type({
|
||||
lat: "number",
|
||||
lng: "number",
|
||||
accuracy: "number",
|
||||
timestamp: "Date",
|
||||
})
|
||||
|
||||
export function createLocationRouter(
|
||||
t: TRPC,
|
||||
{ sessionManager }: { sessionManager: UserSessionManager },
|
||||
) {
|
||||
return t.router({
|
||||
update: t.procedure.input(locationInput).mutation(async ({ input, ctx }) => {
|
||||
const session = sessionManager.getOrCreate(ctx.user.id)
|
||||
await session.engine.executeAction("aris.location", "update-location", {
|
||||
lat: input.lat,
|
||||
lng: input.lng,
|
||||
accuracy: input.accuracy,
|
||||
timestamp: input.timestamp,
|
||||
})
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { LocationSource } from "@aris/source-location"
|
||||
import { trpcServer } from "@hono/trpc-server"
|
||||
import { Hono } from "hono"
|
||||
|
||||
import { registerAuthHandlers } from "./auth/http.ts"
|
||||
import { requireSession } from "./auth/session-middleware.ts"
|
||||
import { registerFeedHttpHandlers } from "./feed/http.ts"
|
||||
import { registerLocationHttpHandlers } from "./location/http.ts"
|
||||
import { UserSessionManager } from "./session/index.ts"
|
||||
import { WeatherSourceProvider } from "./weather/provider.ts"
|
||||
import { createContext } from "./trpc/context.ts"
|
||||
import { createTRPCRouter } from "./trpc/router.ts"
|
||||
|
||||
function main() {
|
||||
const sessionManager = new UserSessionManager([
|
||||
@@ -21,21 +21,13 @@ function main() {
|
||||
}),
|
||||
])
|
||||
|
||||
const trpcRouter = createTRPCRouter({ sessionManager })
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
app.get("/health", (c) => c.json({ status: "ok" }))
|
||||
|
||||
registerAuthHandlers(app)
|
||||
|
||||
app.use(
|
||||
"/trpc/*",
|
||||
trpcServer({
|
||||
router: trpcRouter,
|
||||
createContext,
|
||||
}),
|
||||
)
|
||||
registerFeedHttpHandlers(app, { sessionManager, authSessionMiddleware: requireSession })
|
||||
registerLocationHttpHandlers(app, { sessionManager })
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { WeatherKitClient, WeatherKitResponse } from "@aris/source-weatherkit"
|
||||
|
||||
import { LocationSource } from "@aris/source-location"
|
||||
import { describe, expect, mock, test } from "bun:test"
|
||||
|
||||
import { WeatherSourceProvider } from "../weather/provider.ts"
|
||||
import { UserSessionManager } from "./user-session-manager.ts"
|
||||
|
||||
import type { WeatherKitClient, WeatherKitResponse } from "@aris/source-weatherkit"
|
||||
|
||||
const mockWeatherClient: WeatherKitClient = {
|
||||
fetch: async () => ({}) as WeatherKitResponse,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { FeedSourceProviderInput } from "./feed-source-provider.ts"
|
||||
|
||||
import { UserSession } from "./user-session.ts"
|
||||
|
||||
export class UserSessionManager {
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import type { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch"
|
||||
|
||||
import { auth } from "../auth/index.ts"
|
||||
|
||||
export async function createContext(opts: FetchCreateContextFnOptions) {
|
||||
const session = await auth.api.getSession({ headers: opts.req.headers })
|
||||
|
||||
return {
|
||||
user: session?.user ?? null,
|
||||
session: session?.session ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export type Context = Awaited<ReturnType<typeof createContext>>
|
||||
@@ -1,44 +0,0 @@
|
||||
import { initTRPC, TRPCError } from "@trpc/server"
|
||||
|
||||
import type { UserSessionManager } from "../session/index.ts"
|
||||
import type { Context } from "./context.ts"
|
||||
|
||||
import { createLocationRouter } from "../location/router.ts"
|
||||
|
||||
export type TRPC = ReturnType<typeof createTRPC>
|
||||
|
||||
export interface TRPCRouterDeps {
|
||||
sessionManager: UserSessionManager
|
||||
}
|
||||
|
||||
export function createTRPCRouter({ sessionManager }: TRPCRouterDeps) {
|
||||
const t = createTRPC()
|
||||
|
||||
return t.router({
|
||||
location: createLocationRouter(t, { sessionManager }),
|
||||
})
|
||||
}
|
||||
|
||||
export type TRPCRouter = ReturnType<typeof createTRPCRouter>
|
||||
|
||||
function createTRPC() {
|
||||
const t = initTRPC.context<Context>().create()
|
||||
|
||||
const isAuthed = t.middleware(({ ctx, next }) => {
|
||||
if (!ctx.user || !ctx.session) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" })
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
user: ctx.user,
|
||||
session: ctx.session,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
router: t.router,
|
||||
procedure: t.procedure.use(isAuthed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,97 @@
|
||||
}
|
||||
}
|
||||
],
|
||||
"expo-font"
|
||||
[
|
||||
"expo-font",
|
||||
{
|
||||
"android": {
|
||||
"fonts": [
|
||||
{
|
||||
"fontFamily": "Inter",
|
||||
"fontDefinitions": [
|
||||
{ "path": "./assets/fonts/Inter_100Thin.ttf", "weight": 100 },
|
||||
{ "path": "./assets/fonts/Inter_100Thin_Italic.ttf", "weight": 100, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_200ExtraLight.ttf", "weight": 200 },
|
||||
{ "path": "./assets/fonts/Inter_200ExtraLight_Italic.ttf", "weight": 200, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_300Light.ttf", "weight": 300 },
|
||||
{ "path": "./assets/fonts/Inter_300Light_Italic.ttf", "weight": 300, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_400Regular.ttf", "weight": 400 },
|
||||
{ "path": "./assets/fonts/Inter_400Regular_Italic.ttf", "weight": 400, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_500Medium.ttf", "weight": 500 },
|
||||
{ "path": "./assets/fonts/Inter_500Medium_Italic.ttf", "weight": 500, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_600SemiBold.ttf", "weight": 600 },
|
||||
{ "path": "./assets/fonts/Inter_600SemiBold_Italic.ttf", "weight": 600, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_700Bold.ttf", "weight": 700 },
|
||||
{ "path": "./assets/fonts/Inter_700Bold_Italic.ttf", "weight": 700, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_800ExtraBold.ttf", "weight": 800 },
|
||||
{ "path": "./assets/fonts/Inter_800ExtraBold_Italic.ttf", "weight": 800, "style": "italic" },
|
||||
{ "path": "./assets/fonts/Inter_900Black.ttf", "weight": 900 },
|
||||
{ "path": "./assets/fonts/Inter_900Black_Italic.ttf", "weight": 900, "style": "italic" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"fontFamily": "Source Serif 4",
|
||||
"fontDefinitions": [
|
||||
{ "path": "./assets/fonts/SourceSerif4_200ExtraLight.ttf", "weight": 200 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_200ExtraLight_Italic.ttf", "weight": 200, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_300Light.ttf", "weight": 300 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_300Light_Italic.ttf", "weight": 300, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_400Regular.ttf", "weight": 400 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_400Regular_Italic.ttf", "weight": 400, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_500Medium.ttf", "weight": 500 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_500Medium_Italic.ttf", "weight": 500, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_600SemiBold.ttf", "weight": 600 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_600SemiBold_Italic.ttf", "weight": 600, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_700Bold.ttf", "weight": 700 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_700Bold_Italic.ttf", "weight": 700, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_800ExtraBold.ttf", "weight": 800 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_800ExtraBold_Italic.ttf", "weight": 800, "style": "italic" },
|
||||
{ "path": "./assets/fonts/SourceSerif4_900Black.ttf", "weight": 900 },
|
||||
{ "path": "./assets/fonts/SourceSerif4_900Black_Italic.ttf", "weight": 900, "style": "italic" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"ios": {
|
||||
"fonts": [
|
||||
"./assets/fonts/Inter_100Thin.ttf",
|
||||
"./assets/fonts/Inter_100Thin_Italic.ttf",
|
||||
"./assets/fonts/Inter_200ExtraLight.ttf",
|
||||
"./assets/fonts/Inter_200ExtraLight_Italic.ttf",
|
||||
"./assets/fonts/Inter_300Light.ttf",
|
||||
"./assets/fonts/Inter_300Light_Italic.ttf",
|
||||
"./assets/fonts/Inter_400Regular.ttf",
|
||||
"./assets/fonts/Inter_400Regular_Italic.ttf",
|
||||
"./assets/fonts/Inter_500Medium.ttf",
|
||||
"./assets/fonts/Inter_500Medium_Italic.ttf",
|
||||
"./assets/fonts/Inter_600SemiBold.ttf",
|
||||
"./assets/fonts/Inter_600SemiBold_Italic.ttf",
|
||||
"./assets/fonts/Inter_700Bold.ttf",
|
||||
"./assets/fonts/Inter_700Bold_Italic.ttf",
|
||||
"./assets/fonts/Inter_800ExtraBold.ttf",
|
||||
"./assets/fonts/Inter_800ExtraBold_Italic.ttf",
|
||||
"./assets/fonts/Inter_900Black.ttf",
|
||||
"./assets/fonts/Inter_900Black_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_200ExtraLight.ttf",
|
||||
"./assets/fonts/SourceSerif4_200ExtraLight_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_300Light.ttf",
|
||||
"./assets/fonts/SourceSerif4_300Light_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_400Regular.ttf",
|
||||
"./assets/fonts/SourceSerif4_400Regular_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_500Medium.ttf",
|
||||
"./assets/fonts/SourceSerif4_500Medium_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_600SemiBold.ttf",
|
||||
"./assets/fonts/SourceSerif4_600SemiBold_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_700Bold.ttf",
|
||||
"./assets/fonts/SourceSerif4_700Bold_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_800ExtraBold.ttf",
|
||||
"./assets/fonts/SourceSerif4_800ExtraBold_Italic.ttf",
|
||||
"./assets/fonts/SourceSerif4_900Black.ttf",
|
||||
"./assets/fonts/SourceSerif4_900Black_Italic.ttf"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true,
|
||||
|
||||
BIN
apps/aris-client/assets/fonts/Inter_100Thin.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_100Thin.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_100Thin_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_100Thin_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_200ExtraLight.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_200ExtraLight.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_200ExtraLight_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_200ExtraLight_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_300Light.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_300Light.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_300Light_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_300Light_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_400Regular.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_400Regular.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_400Regular_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_400Regular_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_500Medium.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_500Medium.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_500Medium_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_500Medium_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_600SemiBold.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_600SemiBold.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_600SemiBold_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_600SemiBold_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_700Bold.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_700Bold.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_700Bold_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_700Bold_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_800ExtraBold.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_800ExtraBold.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_800ExtraBold_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_800ExtraBold_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_900Black.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_900Black.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/Inter_900Black_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/Inter_900Black_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_200ExtraLight.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_200ExtraLight.ttf
Normal file
Binary file not shown.
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_300Light.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_300Light.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_300Light_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_300Light_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_400Regular.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_400Regular.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_400Regular_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_400Regular_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_500Medium.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_500Medium.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_500Medium_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_500Medium_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_600SemiBold.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_600SemiBold.ttf
Normal file
Binary file not shown.
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_700Bold.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_700Bold.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_700Bold_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_700Bold_Italic.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_800ExtraBold.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_800ExtraBold.ttf
Normal file
Binary file not shown.
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_900Black.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_900Black.ttf
Normal file
Binary file not shown.
BIN
apps/aris-client/assets/fonts/SourceSerif4_900Black_Italic.ttf
Normal file
BIN
apps/aris-client/assets/fonts/SourceSerif4_900Black_Italic.ttf
Normal file
Binary file not shown.
@@ -8,6 +8,12 @@
|
||||
"developmentClient": true,
|
||||
"distribution": "internal"
|
||||
},
|
||||
"development-simulator": {
|
||||
"extends": "development",
|
||||
"ios": {
|
||||
"simulator": "true"
|
||||
}
|
||||
},
|
||||
"preview": {
|
||||
"distribution": "internal"
|
||||
},
|
||||
|
||||
@@ -11,10 +11,12 @@
|
||||
"web": "expo start --web",
|
||||
"lint": "expo lint",
|
||||
"build:ios": "eas build --profile development --platform ios --non-interactive",
|
||||
"build:ios-simulator": "eas build --profile development-simulator --platform ios --non-interactive",
|
||||
"debugger": "bun run scripts/open-debugger.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo-google-fonts/inter": "^0.4.2",
|
||||
"@expo-google-fonts/source-serif-4": "^0.4.1",
|
||||
"@expo/vector-icons": "^15.0.3",
|
||||
"@react-navigation/bottom-tabs": "^7.4.0",
|
||||
"@react-navigation/elements": "^2.6.3",
|
||||
@@ -40,6 +42,7 @@
|
||||
"react-native-reanimated": "~4.1.1",
|
||||
"react-native-safe-area-context": "~5.6.0",
|
||||
"react-native-screens": "~4.16.0",
|
||||
"react-native-svg": "15.12.1",
|
||||
"react-native-web": "~0.21.0",
|
||||
"react-native-worklets": "0.5.1",
|
||||
"twrnc": "^4.16.0"
|
||||
|
||||
61
bun.lock
61
bun.lock
@@ -21,8 +21,6 @@
|
||||
"@aris/source-location": "workspace:*",
|
||||
"@aris/source-tfl": "workspace:*",
|
||||
"@aris/source-weatherkit": "workspace:*",
|
||||
"@hono/trpc-server": "^0.3",
|
||||
"@trpc/server": "^11",
|
||||
"arktype": "^2.1.29",
|
||||
"better-auth": "^1",
|
||||
"hono": "^4",
|
||||
@@ -37,6 +35,7 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@expo-google-fonts/inter": "^0.4.2",
|
||||
"@expo-google-fonts/source-serif-4": "^0.4.1",
|
||||
"@expo/vector-icons": "^15.0.3",
|
||||
"@react-navigation/bottom-tabs": "^7.4.0",
|
||||
"@react-navigation/elements": "^2.6.3",
|
||||
@@ -62,6 +61,7 @@
|
||||
"react-native-reanimated": "~4.1.1",
|
||||
"react-native-safe-area-context": "~5.6.0",
|
||||
"react-native-screens": "~4.16.0",
|
||||
"react-native-svg": "15.12.1",
|
||||
"react-native-web": "~0.21.0",
|
||||
"react-native-worklets": "0.5.1",
|
||||
"twrnc": "^4.16.0",
|
||||
@@ -89,15 +89,6 @@
|
||||
"arktype": "^2.1.0",
|
||||
},
|
||||
},
|
||||
"packages/aris-source-apple-calendar": {
|
||||
"name": "@aris/source-apple-calendar",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@aris/core": "workspace:*",
|
||||
"ical.js": "^2.1.0",
|
||||
"tsdav": "^2.1.7",
|
||||
},
|
||||
},
|
||||
"packages/aris-source-google-calendar": {
|
||||
"name": "@aris/source-google-calendar",
|
||||
"version": "0.0.0",
|
||||
@@ -144,8 +135,6 @@
|
||||
|
||||
"@aris/data-source-weatherkit": ["@aris/data-source-weatherkit@workspace:packages/aris-data-source-weatherkit"],
|
||||
|
||||
"@aris/source-apple-calendar": ["@aris/source-apple-calendar@workspace:packages/aris-source-apple-calendar"],
|
||||
|
||||
"@aris/source-google-calendar": ["@aris/source-google-calendar@workspace:packages/aris-source-google-calendar"],
|
||||
|
||||
"@aris/source-location": ["@aris/source-location@workspace:packages/aris-source-location"],
|
||||
@@ -384,6 +373,8 @@
|
||||
|
||||
"@expo-google-fonts/inter": ["@expo-google-fonts/inter@0.4.2", "", {}, "sha512-syfiImMaDmq7cFi0of+waE2M4uSCyd16zgyWxdPOY7fN2VBmSLKEzkfbZgeOjJq61kSqPBNNtXjggiQiSD6gMQ=="],
|
||||
|
||||
"@expo-google-fonts/source-serif-4": ["@expo-google-fonts/source-serif-4@0.4.1", "", {}, "sha512-Ej4UXDjW1kwYPHG8YLq6fK1bqnJGb3K35J3S5atSL0ScKFAFLKvndxoTWeCls7mybtlS9x99hzwDeXCBkiI3rA=="],
|
||||
|
||||
"@expo/apple-utils": ["@expo/apple-utils@2.1.13", "", { "bin": { "apple-utils": "bin.js" } }, "sha512-nt3efiJhAWTHl9ikKYrHEuv3dhqCdicsHFRE9LmvtcVsPhXl9bAsm0gbACoLPr7ClP8664H/S6SdVJOD/tw0jg=="],
|
||||
|
||||
"@expo/bunyan": ["@expo/bunyan@4.0.1", "", { "dependencies": { "uuid": "^8.0.0" } }, "sha512-+Lla7nYSiHZirgK+U/uYzsLv/X+HaJienbD5AKX1UQZHYfWaP+9uuQluRB4GrEVWF0GZ7vEVp/jzaOT9k/SQlg=="],
|
||||
@@ -464,8 +455,6 @@
|
||||
|
||||
"@hapi/topo": ["@hapi/topo@5.1.0", "", { "dependencies": { "@hapi/hoek": "^9.0.0" } }, "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg=="],
|
||||
|
||||
"@hono/trpc-server": ["@hono/trpc-server@0.3.4", "", { "peerDependencies": { "@trpc/server": "^10.10.0 || >11.0.0-rc", "hono": ">=4.*" } }, "sha512-xFOPjUPnII70FgicDzOJy1ufIoBTu8eF578zGiDOrYOrYN8CJe140s9buzuPkX+SwJRYK8LjEBHywqZtxdm8aA=="],
|
||||
|
||||
"@humanfs/core": ["@humanfs/core@0.19.1", "", {}, "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA=="],
|
||||
|
||||
"@humanfs/node": ["@humanfs/node@0.16.7", "", { "dependencies": { "@humanfs/core": "^0.19.1", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ=="],
|
||||
@@ -682,8 +671,6 @@
|
||||
|
||||
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
||||
|
||||
"@trpc/server": ["@trpc/server@11.10.0", "", { "peerDependencies": { "typescript": ">=5.7.2" } }, "sha512-zZjTrR6He61e5TiT7e/bQqab/jRcXBZM8Fg78Yoo8uh5pz60dzzbYuONNUCOkafv5ppXVMms4NHYfNZgzw50vg=="],
|
||||
|
||||
"@tsconfig/node10": ["@tsconfig/node10@1.0.12", "", {}, "sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ=="],
|
||||
|
||||
"@tsconfig/node12": ["@tsconfig/node12@1.0.11", "", {}, "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag=="],
|
||||
@@ -912,8 +899,6 @@
|
||||
|
||||
"bare-events": ["bare-events@2.8.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ=="],
|
||||
|
||||
"base-64": ["base-64@1.0.0", "", {}, "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg=="],
|
||||
|
||||
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
|
||||
|
||||
"baseline-browser-mapping": ["baseline-browser-mapping@2.9.19", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
|
||||
@@ -928,6 +913,8 @@
|
||||
|
||||
"binary-extensions": ["binary-extensions@2.3.0", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
|
||||
|
||||
"boolbase": ["boolbase@1.0.0", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],
|
||||
|
||||
"bplist-creator": ["bplist-creator@0.1.0", "", { "dependencies": { "stream-buffers": "2.2.x" } }, "sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg=="],
|
||||
|
||||
"bplist-parser": ["bplist-parser@0.3.2", "", { "dependencies": { "big-integer": "1.6.x" } }, "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ=="],
|
||||
@@ -1024,7 +1011,7 @@
|
||||
|
||||
"create-require": ["create-require@1.1.1", "", {}, "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ=="],
|
||||
|
||||
"cross-fetch": ["cross-fetch@4.1.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw=="],
|
||||
"cross-fetch": ["cross-fetch@3.2.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
@@ -1034,6 +1021,12 @@
|
||||
|
||||
"css-in-js-utils": ["css-in-js-utils@3.1.0", "", { "dependencies": { "hyphenate-style-name": "^1.0.3" } }, "sha512-fJAcud6B3rRu+KHYk+Bwf+WFL2MDCJJ1XG9x137tJQ0xYxor7XziQtuGFbWNdqrvF4Tk26O3H73nfVqXt/fW1A=="],
|
||||
|
||||
"css-select": ["css-select@5.2.2", "", { "dependencies": { "boolbase": "^1.0.0", "css-what": "^6.1.0", "domhandler": "^5.0.2", "domutils": "^3.0.1", "nth-check": "^2.0.1" } }, "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw=="],
|
||||
|
||||
"css-tree": ["css-tree@1.1.3", "", { "dependencies": { "mdn-data": "2.0.14", "source-map": "^0.6.1" } }, "sha512-tRpdppF7TRazZrjJ6v3stzv93qxRcSsFmW6cX0Zm2NVKpxE1WV1HblnghVv9TreireHkqI/VDEsfolRF1p6y7Q=="],
|
||||
|
||||
"css-what": ["css-what@6.2.2", "", {}, "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA=="],
|
||||
|
||||
"cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
|
||||
|
||||
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
@@ -1086,8 +1079,16 @@
|
||||
|
||||
"doctrine": ["doctrine@2.1.0", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw=="],
|
||||
|
||||
"dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
|
||||
|
||||
"domelementtype": ["domelementtype@2.3.0", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],
|
||||
|
||||
"domhandler": ["domhandler@5.0.3", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],
|
||||
|
||||
"domino": ["domino@2.1.6", "", {}, "sha512-3VdM/SXBZX2omc9JF9nOPCtDaYQ67BGp5CoLpIQlO2KCAPETs8TcDHacF26jXadGbvUteZzRTeos2fhID5+ucQ=="],
|
||||
|
||||
"domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],
|
||||
|
||||
"dotenv": ["dotenv@16.3.1", "", {}, "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ=="],
|
||||
|
||||
"dotenv-expand": ["dotenv-expand@11.0.7", "", { "dependencies": { "dotenv": "^16.4.5" } }, "sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA=="],
|
||||
@@ -1110,6 +1111,8 @@
|
||||
|
||||
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
|
||||
|
||||
"entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
|
||||
|
||||
"env-editor": ["env-editor@0.4.2", "", {}, "sha512-ObFo8v4rQJAE59M69QzwloxPZtd33TpYEIjtKD1rrFDcM1Gd7IkDxEBU+HriziN6HSHQnBJi8Dmy+JWkav5HKA=="],
|
||||
|
||||
"env-paths": ["env-paths@2.2.0", "", {}, "sha512-6u0VYSCo/OW6IoD5WCLLy9JUGARbamfSavcNXry/eu8aHVFei6CD3Sw+VGX5alea1i9pgPHW0mbu6Xj0uBh7gA=="],
|
||||
@@ -1386,8 +1389,6 @@
|
||||
|
||||
"hyphenate-style-name": ["hyphenate-style-name@1.1.0", "", {}, "sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw=="],
|
||||
|
||||
"ical.js": ["ical.js@2.2.1", "", {}, "sha512-yK/UlPbEs316igb/tjRgbFA8ZV75rCsBJp/hWOatpyaPNlgw0dGDmU+FoicOcwX4xXkeXOkYiOmCqNPFpNPkQg=="],
|
||||
|
||||
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"ignore": ["ignore@5.3.0", "", {}, "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg=="],
|
||||
@@ -1624,6 +1625,8 @@
|
||||
|
||||
"md5": ["md5@2.3.0", "", { "dependencies": { "charenc": "0.0.2", "crypt": "0.0.2", "is-buffer": "~1.1.6" } }, "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g=="],
|
||||
|
||||
"mdn-data": ["mdn-data@2.0.14", "", {}, "sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow=="],
|
||||
|
||||
"memoize-one": ["memoize-one@5.2.1", "", {}, "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q=="],
|
||||
|
||||
"merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
|
||||
@@ -1724,6 +1727,8 @@
|
||||
|
||||
"npm-package-arg": ["npm-package-arg@11.0.3", "", { "dependencies": { "hosted-git-info": "^7.0.0", "proc-log": "^4.0.0", "semver": "^7.3.5", "validate-npm-package-name": "^5.0.0" } }, "sha512-sHGJy8sOC1YraBywpzQlIKBE4pBbGbiF95U6Auspzyem956E0+FtDtsx1ZxlOJkQCZ1AFXAY/yuvtFYrOxF+Bw=="],
|
||||
|
||||
"nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="],
|
||||
|
||||
"nullthrows": ["nullthrows@1.1.1", "", {}, "sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw=="],
|
||||
|
||||
"ob1": ["ob1@0.83.3", "", { "dependencies": { "flow-enums-runtime": "^0.0.6" } }, "sha512-egUxXCDwoWG06NGCS5s5AdcpnumHKJlfd3HH06P3m9TEMwwScfcY35wpQxbm9oHof+dM/lVH9Rfyu1elTVelSA=="],
|
||||
@@ -1910,6 +1915,8 @@
|
||||
|
||||
"react-native-screens": ["react-native-screens@4.16.0", "", { "dependencies": { "react-freeze": "^1.0.0", "react-native-is-edge-to-edge": "^1.2.1", "warn-once": "^0.1.0" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-yIAyh7F/9uWkOzCi1/2FqvNvK6Wb9Y1+Kzn16SuGfN9YFJDTbwlzGRvePCNTOX0recpLQF3kc2FmvMUhyTCH1Q=="],
|
||||
|
||||
"react-native-svg": ["react-native-svg@15.12.1", "", { "dependencies": { "css-select": "^5.1.0", "css-tree": "^1.1.3", "warn-once": "0.1.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-vCuZJDf8a5aNC2dlMovEv4Z0jjEUET53lm/iILFnFewa15b4atjVxU6Wirm6O9y6dEsdjDZVD7Q3QM4T1wlI8g=="],
|
||||
|
||||
"react-native-web": ["react-native-web@0.21.2", "", { "dependencies": { "@babel/runtime": "^7.18.6", "@react-native/normalize-colors": "^0.74.1", "fbjs": "^3.0.4", "inline-style-prefixer": "^7.0.1", "memoize-one": "^6.0.0", "nullthrows": "^1.1.1", "postcss-value-parser": "^4.2.0", "styleq": "^0.1.3" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, "sha512-SO2t9/17zM4iEnFvlu2DA9jqNbzNhoUP+AItkoCOyFmDMOhUnBBznBDCYN92fGdfAkfQlWzPoez6+zLxFNsZEg=="],
|
||||
|
||||
"react-native-worklets": ["react-native-worklets@0.5.1", "", { "dependencies": { "@babel/plugin-transform-arrow-functions": "^7.0.0-0", "@babel/plugin-transform-class-properties": "^7.0.0-0", "@babel/plugin-transform-classes": "^7.0.0-0", "@babel/plugin-transform-nullish-coalescing-operator": "^7.0.0-0", "@babel/plugin-transform-optional-chaining": "^7.0.0-0", "@babel/plugin-transform-shorthand-properties": "^7.0.0-0", "@babel/plugin-transform-template-literals": "^7.0.0-0", "@babel/plugin-transform-unicode-regex": "^7.0.0-0", "@babel/preset-typescript": "^7.16.7", "convert-source-map": "^2.0.0", "semver": "7.7.2" }, "peerDependencies": { "@babel/core": "^7.0.0-0", "react": "*", "react-native": "*" } }, "sha512-lJG6Uk9YuojjEX/tQrCbcbmpdLCSFxDK1rJlkDhgqkVi1KZzG7cdcBFQRqyNOOzR9Y0CXNuldmtWTGOyM0k0+w=="],
|
||||
@@ -2156,8 +2163,6 @@
|
||||
|
||||
"tsconfig-paths": ["tsconfig-paths@3.15.0", "", { "dependencies": { "@types/json5": "^0.0.29", "json5": "^1.0.2", "minimist": "^1.2.6", "strip-bom": "^3.0.0" } }, "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg=="],
|
||||
|
||||
"tsdav": ["tsdav@2.1.8", "", { "dependencies": { "base-64": "1.0.0", "cross-fetch": "4.1.0", "debug": "4.4.3", "xml-js": "1.6.11" } }, "sha512-zvQvhZLzTaEmNNgJbBlUYT/JOq9Xpw/xkxCqs7IT2d2/7o7pss0iZOlZXuHJ5VcvSvTny42Vc6+6GyzZcrCJ1g=="],
|
||||
|
||||
"tslib": ["tslib@2.6.2", "", {}, "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="],
|
||||
|
||||
"tunnel-agent": ["tunnel-agent@0.6.0", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
|
||||
@@ -2280,8 +2285,6 @@
|
||||
|
||||
"xcode": ["xcode@3.0.1", "", { "dependencies": { "simple-plist": "^1.1.0", "uuid": "^7.0.3" } }, "sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA=="],
|
||||
|
||||
"xml-js": ["xml-js@1.6.11", "", { "dependencies": { "sax": "^1.2.4" }, "bin": { "xml-js": "./bin/cli.js" } }, "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g=="],
|
||||
|
||||
"xml2js": ["xml2js@0.6.0", "", { "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" } }, "sha512-eLTh0kA8uHceqesPqSE+VvO1CDDJWMwlQfB6LuN6T8w6MaDJ8Txm8P7s5cHD0miF0V+GGTZrDQfxPZQVsur33w=="],
|
||||
|
||||
"xmlbuilder": ["xmlbuilder@14.0.0", "", {}, "sha512-ts+B2rSe4fIckR6iquDjsKbQFK2NlUk6iG5nf14mDEyldgoc2nEKZ3jZWMPTxGQwVgToSjt6VGIho1H8/fNFTg=="],
|
||||
@@ -2560,6 +2563,8 @@
|
||||
|
||||
"cross-fetch/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
|
||||
|
||||
"css-tree/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
|
||||
|
||||
"dotenv-expand/dotenv": ["dotenv@16.4.7", "", {}, "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ=="],
|
||||
|
||||
"error-ex/is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="],
|
||||
@@ -2608,8 +2613,6 @@
|
||||
|
||||
"fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"fbjs/cross-fetch": ["cross-fetch@3.2.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q=="],
|
||||
|
||||
"fbjs/promise": ["promise@7.3.1", "", { "dependencies": { "asap": "~2.0.3" } }, "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg=="],
|
||||
|
||||
"figures/escape-string-regexp": ["escape-string-regexp@1.0.5", "", {}, "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg=="],
|
||||
@@ -2936,8 +2939,6 @@
|
||||
|
||||
"expo/@expo/config-plugins/semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="],
|
||||
|
||||
"fbjs/cross-fetch/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
|
||||
|
||||
"finalhandler/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="],
|
||||
|
||||
"glob/minimatch/brace-expansion": ["brace-expansion@1.1.12", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg=="],
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,8 +16,8 @@ Examples of feed items:
|
||||
## Design Principles
|
||||
|
||||
1. **Extensibility**: The core must support different data sources, including third-party sources.
|
||||
2. **Separation of concerns**: Core handles data only. UI rendering is a separate system.
|
||||
3. **Parallel execution**: Sources run in parallel; no inter-source dependencies.
|
||||
2. **Separation of concerns**: Core handles data and UI description. The client is a thin renderer.
|
||||
3. **Dependency graph**: Sources declare dependencies on other sources. The engine resolves the graph and runs independent sources in parallel.
|
||||
4. **Graceful degradation**: Failed sources are skipped; partial results are returned.
|
||||
|
||||
## Architecture
|
||||
@@ -25,26 +25,28 @@ Examples of feed items:
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Backend │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │
|
||||
│ │ aris-core │ │ Sources │ │ UI Registry │ │
|
||||
│ │ │ │ (plugins) │ │ (schemas from │ │
|
||||
│ │ - Reconciler│◄───│ - Calendar │ │ third parties)│ │
|
||||
│ │ - Context │ │ - Weather │ │ │ │
|
||||
│ │ - FeedItem │ │ - Spotify │ │ │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────────┘ │
|
||||
│ │ │ │
|
||||
│ ▼ ▼ │
|
||||
│ Feed (data only) UI Schemas (JSON) │
|
||||
│ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ aris-core │ │ Sources │ │
|
||||
│ │ │ │ (plugins) │ │
|
||||
│ │ - FeedEngine│◄───│ - Calendar │ │
|
||||
│ │ - Context │ │ - Weather │ │
|
||||
│ │ - FeedItem │ │ - TfL │ │
|
||||
│ │ - Actions │ │ - Spotify │ │
|
||||
│ └─────────────┘ └─────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ Feed items (data + ui trees + slots) │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
│
|
||||
▼ (WebSocket / JSON-RPC)
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Frontend │
|
||||
│ Client (React Native) │
|
||||
│ ┌──────────────────────────────────────────────────────┐ │
|
||||
│ │ Renderer │ │
|
||||
│ │ - Receives feed items │ │
|
||||
│ │ - Fetches UI schema by item type │ │
|
||||
│ │ - Renders using json-render or similar │ │
|
||||
│ │ json-render + twrnc component map │ │
|
||||
│ │ - Receives feed items with ui trees │ │
|
||||
│ │ - Renders using registered RN components + twrnc │ │
|
||||
│ │ - User interactions trigger source actions │ │
|
||||
│ │ - Bespoke native components for rich interactions │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
@@ -54,15 +56,16 @@ Examples of feed items:
|
||||
The core is responsible for:
|
||||
|
||||
- Defining the context and feed item interfaces
|
||||
- Providing a reconciler that orchestrates data sources
|
||||
- Providing a `FeedEngine` that orchestrates sources via a dependency graph
|
||||
- Returning a flat list of prioritized feed items
|
||||
- Routing action execution to the correct source
|
||||
|
||||
### Key Concepts
|
||||
|
||||
- **Context**: Time and location (with accuracy) passed to all sources
|
||||
- **FeedItem**: Has an ID (source-generated, stable), type, priority, timestamp, and JSON-serializable data
|
||||
- **DataSource**: Interface that third parties implement to provide feed items
|
||||
- **Reconciler**: Orchestrates sources, runs them in parallel, returns items and any errors
|
||||
- **Context**: Time and location (with accuracy) passed to all sources. Sources can contribute to context (e.g., location source provides coordinates, weather source provides conditions).
|
||||
- **FeedItem**: Has an ID (source-generated, stable), type, timestamp, JSON-serializable data, optional actions, an optional `ui` tree, and optional `slots` for LLM-fillable content.
|
||||
- **FeedSource**: Interface that first and third parties implement to provide context, feed items, and actions. Uses reverse-domain IDs (e.g., `aris.weather`, `com.spotify`).
|
||||
- **FeedEngine**: Orchestrates sources respecting their dependency graph, runs independent sources in parallel, returns items and any errors. Routes action execution to the correct source.
|
||||
|
||||
## Data Sources
|
||||
|
||||
@@ -71,10 +74,13 @@ Key decisions:
|
||||
- Sources receive the full context and decide internally what to use
|
||||
- Each source returns a single item type (e.g., separate "Calendar Source" and "Location Suggestion Source" rather than a combined "Google Source")
|
||||
- Sources live in separate packages, not in the core
|
||||
- Sources declare dependencies on other sources (e.g., weather depends on location)
|
||||
- Sources are responsible for:
|
||||
- Transforming their domain data into feed items
|
||||
- Assigning priority based on domain logic (e.g., "event starting in 10 minutes" = high priority)
|
||||
- Returning empty arrays when nothing is relevant
|
||||
- Providing a `ui` tree for each feed item
|
||||
- Declaring and handling actions (e.g., RSVP, complete task, play/pause)
|
||||
|
||||
### Configuration
|
||||
|
||||
@@ -83,28 +89,323 @@ Configuration is passed at source registration time, not per reconcile call. Sou
|
||||
## Feed Output
|
||||
|
||||
- Flat list of `FeedItem` objects
|
||||
- No UI information (no icons, card types, etc.)
|
||||
- Items carry data, an optional `ui` field describing their layout, and optional `slots` for LLM enhancement
|
||||
- Items are a discriminated union by `type` field
|
||||
- Reconciler sorts by priority; can act as tiebreaker
|
||||
|
||||
## UI Rendering (Separate from Core)
|
||||
## UI Rendering: Server-Driven UI
|
||||
|
||||
The core does not handle UI. For extensible third-party UI:
|
||||
The UI for feed items is **server-driven**. Sources describe how their items look using a JSON tree (the `ui` field on `FeedItem`). The client renders these trees using [json-render](https://json-render.dev/) with a registered set of React Native components styled via [twrnc](https://github.com/jaredh159/tailwind-react-native-classnames).
|
||||
|
||||
1. Third-party apps register their UI schemas through the backend (UI Registry)
|
||||
2. Frontend fetches UI schemas from the backend
|
||||
3. Frontend matches feed items to schemas by `type` and renders accordingly
|
||||
### How it works
|
||||
|
||||
This approach:
|
||||
1. Sources return feed items with a `ui` field — a JSON tree describing the card layout using Tailwind class strings.
|
||||
2. The client passes a component map to json-render. Each component wraps a React Native primitive and resolves `className` via twrnc.
|
||||
3. json-render walks the tree and renders native components. twrnc parses Tailwind classes at runtime — no build step, arbitrary values work.
|
||||
4. User interactions (tap, etc.) map to source actions via the `actions` field on `FeedItem`. The client sends action requests to the backend, which routes them to the correct source via `FeedEngine.executeAction()`.
|
||||
|
||||
- Keeps the core focused on data
|
||||
- Works across platforms (web, React Native)
|
||||
- Avoids the need for third parties to inject code into the app
|
||||
- Uses a json-render style approach for declarative UI from JSON schemas
|
||||
### Styling
|
||||
|
||||
Reference: https://github.com/vercel-labs/json-render
|
||||
- Sources use Tailwind CSS class strings via the `className` prop (e.g., `"p-4 bg-white dark:bg-black rounded-xl"`).
|
||||
- twrnc resolves classes to React Native style objects at runtime. Supports arbitrary values (`mt-[31px]`, `bg-[#eaeaea]`), dark mode (`dark:bg-black`), and platform prefixes (`ios:pt-4 android:pt-2`).
|
||||
- Custom colors and spacing are configured via `tailwind.config.js` on the client.
|
||||
- No compile-time constraint — all styles resolve at runtime.
|
||||
|
||||
### Two tiers of UI
|
||||
|
||||
- **Server-driven (default):** Any source can return a `ui` tree. Covers most cards — weather, tasks, alerts, package tracking, news, etc. Simple interactions go through source actions. This is the default path for both first-party and third-party sources.
|
||||
- **Bespoke native:** For cards that need rich client interaction (gestures, animations, real-time updates), a native React Native component is registered in the json-render component map and referenced by type. Third parties that need this level of richness work with the ARIS team to get it integrated.
|
||||
|
||||
### Why server-driven
|
||||
|
||||
- Feed items are inherently server-driven — the data comes from sources on the backend. Attaching the layout alongside the data is a natural extension.
|
||||
- Card designs can be updated without shipping an app update.
|
||||
- Third-party sources can ship their own UI without bundling anything new into the app.
|
||||
|
||||
Reference: https://json-render.dev/
|
||||
|
||||
## Feed Items with UI and Slots
|
||||
|
||||
> Note: the codebase has evolved since the sections above. The engine now uses a dependency graph with topological ordering (`FeedEngine`, `FeedSource`), not the parallel reconciler described above. The `priority` field is being replaced by post-processing (see the ideas doc). This section describes the UI and enhancement architecture going forward.
|
||||
|
||||
Feed items carry an optional `ui` field containing a json-render tree, and an optional `slots` field for LLM-fillable content.
|
||||
|
||||
```typescript
|
||||
interface FeedItem<TType, TData> {
|
||||
id: string
|
||||
type: TType
|
||||
timestamp: Date
|
||||
data: TData
|
||||
ui?: JsonRenderNode
|
||||
slots?: Record<string, Slot>
|
||||
}
|
||||
|
||||
interface Slot {
|
||||
/** Tells the LLM what this slot wants — the source writes this */
|
||||
description: string
|
||||
/** LLM-filled text content, null until enhanced */
|
||||
content: string | null
|
||||
}
|
||||
```
|
||||
|
||||
### How it works
|
||||
|
||||
The source produces the item with a UI tree and empty slots:
|
||||
|
||||
```typescript
|
||||
// Weather source produces:
|
||||
{
|
||||
id: "weather-current-123",
|
||||
type: "weather-current",
|
||||
data: { temperature: 18, condition: "cloudy" },
|
||||
ui: {
|
||||
component: "VStack",
|
||||
children: [
|
||||
{ component: "WeatherHeader", props: { temp: 18, condition: "cloudy" } },
|
||||
{ component: "Slot", props: { name: "insight" } },
|
||||
{ component: "HourlyChart", props: { hours: [...] } },
|
||||
{ component: "Slot", props: { name: "cross-source" } },
|
||||
]
|
||||
},
|
||||
slots: {
|
||||
"insight": {
|
||||
description: "A short contextual insight about the current weather and how it affects the user's day",
|
||||
content: null
|
||||
},
|
||||
"cross-source": {
|
||||
description: "Connection between weather and the user's calendar events or plans",
|
||||
content: null
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The LLM enhancement harness fills `content`:
|
||||
|
||||
```typescript
|
||||
slots: {
|
||||
"insight": {
|
||||
description: "...",
|
||||
content: "Rain after 3pm — grab a jacket before your walk"
|
||||
},
|
||||
"cross-source": {
|
||||
description: "...",
|
||||
content: "Should be dry by 7pm for your dinner at The Ivy"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The client renders the `ui` tree. When it hits a `Slot` node, it looks up `slots[name].content`. If non-null, render the text. If null, render nothing.
|
||||
|
||||
### Separation of concerns
|
||||
|
||||
- **Sources** own the UI layout and declare what slots exist with descriptions.
|
||||
- **The LLM** fills slot content. It doesn't know about layout or positioning.
|
||||
- **The client** renders the UI tree and resolves slots to their content.
|
||||
|
||||
Sources define the prompt for each slot via the `description` field. The harness doesn't need to know what slots any source type has — it reads them dynamically from the items.
|
||||
|
||||
Each source defines its own slots. The harness handles them automatically — no central registry needed.
|
||||
|
||||
## Enhancement Harness
|
||||
|
||||
The LLM enhancement harness fills slots and produces synthetic feed items. It runs reactively — triggered by context changes, not by a timer.
|
||||
|
||||
### Execution model
|
||||
|
||||
```
|
||||
FeedEngine.refresh()
|
||||
→ sources produce items with ui + empty slots
|
||||
↓
|
||||
Fast path (rule-based post-processors, <10ms)
|
||||
→ group, dedup, affinity, time-adjust
|
||||
→ merge LAST cached slot fills + synthetic items
|
||||
→ return feed to UI immediately
|
||||
↓
|
||||
Background: has context changed since last LLM run?
|
||||
(hash of: item IDs + data + slot descriptions + user memory)
|
||||
↓
|
||||
No → done, cache is still valid
|
||||
Yes → run LLM harness async
|
||||
→ fill slots + generate synthetic items
|
||||
→ cache result
|
||||
→ push updated feed to UI via WebSocket
|
||||
```
|
||||
|
||||
The user never waits for the LLM. They see the feed instantly with the previous enhancement applied. If the LLM produces new slot content or synthetic items, the feed updates in place.
|
||||
|
||||
### LLM input
|
||||
|
||||
The harness serializes items with their unfilled slots into a single prompt. Items without slots are excluded. The LLM sees everything at once and fills whatever slots are relevant.
|
||||
|
||||
```typescript
|
||||
function buildHarnessInput(
|
||||
items: FeedItem[],
|
||||
context: AgentContext,
|
||||
): HarnessInput {
|
||||
const itemsWithSlots = items
|
||||
.filter(item => item.slots && Object.keys(item.slots).length > 0)
|
||||
.map(item => ({
|
||||
id: item.id,
|
||||
type: item.type,
|
||||
data: item.data,
|
||||
slots: Object.fromEntries(
|
||||
Object.entries(item.slots!).map(
|
||||
([name, slot]) => [name, slot.description]
|
||||
)
|
||||
),
|
||||
}))
|
||||
|
||||
return {
|
||||
items: itemsWithSlots,
|
||||
userMemory: context.preferences,
|
||||
currentTime: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The LLM sees:
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "weather-current-123",
|
||||
"type": "weather-current",
|
||||
"data": { "temperature": 18, "condition": "cloudy" },
|
||||
"slots": {
|
||||
"insight": "A short contextual insight about the current weather and how it affects the user's day",
|
||||
"cross-source": "Connection between weather and the user's calendar events or plans"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "calendar-event-456",
|
||||
"type": "calendar-event",
|
||||
"data": { "title": "Dinner at The Ivy", "startTime": "19:00", "location": "The Ivy, West St" },
|
||||
"slots": {
|
||||
"context": "Background on this event, attendees, or previous meetings with these people",
|
||||
"logistics": "Travel time, parking, directions to the venue",
|
||||
"weather": "Weather conditions relevant to this event's time and location"
|
||||
}
|
||||
}
|
||||
],
|
||||
"userMemory": { "commute": "victoria-line", "preference.walking_distance": "1 mile" },
|
||||
"currentTime": "2025-02-26T14:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### LLM output
|
||||
|
||||
A flat map of item ID → slot name → text content. Slots left null are unfilled.
|
||||
|
||||
```json
|
||||
{
|
||||
"slotFills": {
|
||||
"weather-current-123": {
|
||||
"insight": "Rain after 3pm — grab a jacket before your walk",
|
||||
"cross-source": "Should be dry by 7pm for your dinner at The Ivy"
|
||||
},
|
||||
"calendar-event-456": {
|
||||
"context": null,
|
||||
"logistics": "20-minute walk from home — leave by 18:40",
|
||||
"weather": "Rain clears by evening, you'll be fine"
|
||||
}
|
||||
},
|
||||
"syntheticItems": [
|
||||
{
|
||||
"id": "briefing-morning",
|
||||
"type": "briefing",
|
||||
"data": {},
|
||||
"ui": { "component": "Text", "props": { "text": "Light afternoon — just your dinner at 7. Rain clears by then." } }
|
||||
}
|
||||
],
|
||||
"suppress": [],
|
||||
"rankingHints": {}
|
||||
}
|
||||
```
|
||||
|
||||
### Enhancement manager
|
||||
|
||||
One per user, living in the `FeedEngineManager` on the backend:
|
||||
|
||||
```typescript
|
||||
class EnhancementManager {
|
||||
private cache: EnhancementResult | null = null
|
||||
private lastInputHash: string | null = null
|
||||
private running = false
|
||||
|
||||
async enhance(
|
||||
items: FeedItem[],
|
||||
context: AgentContext,
|
||||
): Promise<EnhancementResult> {
|
||||
const hash = computeHash(items, context)
|
||||
|
||||
if (hash === this.lastInputHash && this.cache) {
|
||||
return this.cache
|
||||
}
|
||||
|
||||
if (this.running) {
|
||||
return this.cache ?? emptyResult()
|
||||
}
|
||||
|
||||
this.running = true
|
||||
this.runHarness(items, context)
|
||||
.then(result => {
|
||||
this.cache = result
|
||||
this.lastInputHash = hash
|
||||
this.notifySubscribers(result)
|
||||
})
|
||||
.finally(() => { this.running = false })
|
||||
|
||||
return this.cache ?? emptyResult()
|
||||
}
|
||||
}
|
||||
|
||||
interface EnhancementResult {
|
||||
slotFills: Record<string, Record<string, string | null>>
|
||||
syntheticItems: FeedItem[]
|
||||
suppress: string[]
|
||||
rankingHints: Record<string, number>
|
||||
}
|
||||
```
|
||||
|
||||
### Merging
|
||||
|
||||
After the harness runs, the engine merges slot fills into items:
|
||||
|
||||
```typescript
|
||||
function mergeEnhancement(
|
||||
items: FeedItem[],
|
||||
result: EnhancementResult,
|
||||
): FeedItem[] {
|
||||
return items.map(item => {
|
||||
const fills = result.slotFills[item.id]
|
||||
if (!fills || !item.slots) return item
|
||||
|
||||
const mergedSlots = { ...item.slots }
|
||||
for (const [name, content] of Object.entries(fills)) {
|
||||
if (name in mergedSlots && content !== null) {
|
||||
mergedSlots[name] = { ...mergedSlots[name], content }
|
||||
}
|
||||
}
|
||||
|
||||
return { ...item, slots: mergedSlots }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Cost control
|
||||
|
||||
- **Hash-based cache gate.** Most refreshes reuse the cached result.
|
||||
- **Debounce.** Rapid context changes (location updates) settle before triggering a run.
|
||||
- **Skip inactive users.** Don't run if the user hasn't opened the app in 2+ hours.
|
||||
- **Exclude slotless items.** Only items with slots are sent to the LLM.
|
||||
- **Text-only output.** Slots produce strings, not UI trees — fewer output tokens, less variance.
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Exact schema format for UI registry
|
||||
- How third parties authenticate/register their sources and UI schemas
|
||||
- How third parties authenticate/register their sources
|
||||
- Exact set of React Native components exposed in the json-render component map
|
||||
- Validation/sandboxing of third-party ui trees
|
||||
- How synthetic items define their UI (full json-render tree vs. registered component)
|
||||
- Should slots support rich content (json-render nodes) in the future, or stay text-only?
|
||||
- How to handle slot content that references other items (e.g., "your dinner at The Ivy" linking to the calendar card)
|
||||
|
||||
@@ -125,7 +125,7 @@ interface FeedSource<TItem extends FeedItem = FeedItem> {
|
||||
|
||||
### Changes to FeedItem
|
||||
|
||||
One optional field added.
|
||||
Optional fields added for actions, server-driven UI, and LLM slots.
|
||||
|
||||
```typescript
|
||||
interface FeedItem<
|
||||
@@ -140,6 +140,12 @@ interface FeedItem<
|
||||
|
||||
/** Actions the user can take on this item. */
|
||||
actions?: readonly ItemAction[]
|
||||
|
||||
/** Server-driven UI tree rendered by json-render on the client. */
|
||||
ui?: JsonRenderNode
|
||||
|
||||
/** Named slots for LLM-fillable content. See architecture-draft.md. */
|
||||
slots?: Record<string, Slot>
|
||||
}
|
||||
```
|
||||
|
||||
@@ -222,6 +228,25 @@ class SpotifySource implements FeedSource<SpotifyFeedItem> {
|
||||
{ actionId: "skip-track" },
|
||||
{ actionId: "like-track", params: { trackId: track.id } },
|
||||
],
|
||||
ui: {
|
||||
type: "View",
|
||||
className: "flex-row items-center p-3 gap-3 bg-white dark:bg-black rounded-xl",
|
||||
children: [
|
||||
{
|
||||
type: "Image",
|
||||
source: { uri: track.albumArt },
|
||||
className: "w-12 h-12 rounded-lg",
|
||||
},
|
||||
{
|
||||
type: "View",
|
||||
className: "flex-1",
|
||||
children: [
|
||||
{ type: "Text", className: "font-semibold text-black dark:text-white", text: track.name },
|
||||
{ type: "Text", className: "text-sm text-gray-500 dark:text-gray-400", text: track.artist },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -236,6 +261,8 @@ class SpotifySource implements FeedSource<SpotifyFeedItem> {
|
||||
4. `FeedSource.listActions()` is a required method returning `Record<string, ActionDefinition>` (empty record if no actions)
|
||||
5. `FeedSource.executeAction()` is a required method (no-op for sources without actions)
|
||||
6. `FeedItem.actions` is an optional readonly array of `ItemAction`
|
||||
6b. `FeedItem.ui` is an optional json-render tree describing server-driven UI
|
||||
6c. `FeedItem.slots` is an optional record of named LLM-fillable slots
|
||||
7. `FeedEngine.executeAction()` routes to correct source, returns `ActionResult`
|
||||
8. `FeedEngine.listActions()` aggregates actions from all sources
|
||||
9. Existing tests pass unchanged (all changes are additive)
|
||||
|
||||
@@ -18,9 +18,9 @@ import type { FeedItem } from "./feed"
|
||||
* return [{
|
||||
* id: `weather-${Date.now()}`,
|
||||
* type: this.type,
|
||||
* priority: 0.5,
|
||||
* timestamp: context.time,
|
||||
* data: { temp: data.temperature },
|
||||
* signals: { urgency: 0.5, timeRelevance: "ambient" },
|
||||
* }]
|
||||
* }
|
||||
* }
|
||||
|
||||
@@ -3,7 +3,7 @@ import { describe, expect, test } from "bun:test"
|
||||
import type { ActionDefinition, Context, ContextKey, FeedItem, FeedSource } from "./index"
|
||||
|
||||
import { FeedEngine } from "./feed-engine"
|
||||
import { UnknownActionError, contextKey, contextValue } from "./index"
|
||||
import { TimeRelevance, UnknownActionError, contextKey, contextValue } from "./index"
|
||||
|
||||
// No-op action methods for test sources
|
||||
const noActions = {
|
||||
@@ -100,12 +100,12 @@ function createWeatherSource(
|
||||
{
|
||||
id: `weather-${Date.now()}`,
|
||||
type: "weather",
|
||||
priority: 0.5,
|
||||
timestamp: new Date(),
|
||||
data: {
|
||||
temperature: weather.temperature,
|
||||
condition: weather.condition,
|
||||
},
|
||||
signals: { urgency: 0.5, timeRelevance: TimeRelevance.Ambient },
|
||||
},
|
||||
]
|
||||
},
|
||||
@@ -131,9 +131,9 @@ function createAlertSource(): FeedSource<AlertFeedItem> {
|
||||
{
|
||||
id: "alert-storm",
|
||||
type: "alert",
|
||||
priority: 1.0,
|
||||
timestamp: new Date(),
|
||||
data: { message: "Storm warning!" },
|
||||
signals: { urgency: 1.0, timeRelevance: TimeRelevance.Imminent },
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -322,7 +322,7 @@ describe("FeedEngine", () => {
|
||||
expect(items[0]!.type).toBe("weather")
|
||||
})
|
||||
|
||||
test("sorts items by priority descending", async () => {
|
||||
test("returns items in source graph order (no engine-level sorting)", async () => {
|
||||
const location = createLocationSource()
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
|
||||
@@ -338,8 +338,12 @@ describe("FeedEngine", () => {
|
||||
const { items } = await engine.refresh()
|
||||
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0]!.type).toBe("alert") // priority 1.0
|
||||
expect(items[1]!.type).toBe("weather") // priority 0.5
|
||||
// Items returned in topological order (weather before alert)
|
||||
expect(items[0]!.type).toBe("weather")
|
||||
expect(items[1]!.type).toBe("alert")
|
||||
// Signals are preserved for post-processors to consume
|
||||
expect(items[0]!.signals?.urgency).toBe(0.5)
|
||||
expect(items[1]!.signals?.urgency).toBe(1.0)
|
||||
})
|
||||
|
||||
test("handles missing upstream context gracefully", async () => {
|
||||
@@ -638,4 +642,290 @@ describe("FeedEngine", () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("lastFeed", () => {
|
||||
test("returns null before any refresh", () => {
|
||||
const engine = new FeedEngine()
|
||||
|
||||
expect(engine.lastFeed()).toBeNull()
|
||||
})
|
||||
|
||||
test("returns cached result after refresh", async () => {
|
||||
const location = createLocationSource()
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
|
||||
const weather = createWeatherSource()
|
||||
const engine = new FeedEngine().register(location).register(weather)
|
||||
|
||||
const refreshResult = await engine.refresh()
|
||||
|
||||
const cached = engine.lastFeed()
|
||||
expect(cached).not.toBeNull()
|
||||
expect(cached!.items).toEqual(refreshResult.items)
|
||||
expect(cached!.context).toEqual(refreshResult.context)
|
||||
})
|
||||
|
||||
test("returns null after TTL expires", async () => {
|
||||
const engine = new FeedEngine({ cacheTtlMs: 50 })
|
||||
const location = createLocationSource()
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
|
||||
engine.register(location)
|
||||
await engine.refresh()
|
||||
|
||||
expect(engine.lastFeed()).not.toBeNull()
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 60))
|
||||
|
||||
expect(engine.lastFeed()).toBeNull()
|
||||
})
|
||||
|
||||
test("defaults to 5 minute TTL", async () => {
|
||||
const engine = new FeedEngine()
|
||||
const location = createLocationSource()
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
|
||||
engine.register(location)
|
||||
await engine.refresh()
|
||||
|
||||
// Should still be cached immediately
|
||||
expect(engine.lastFeed()).not.toBeNull()
|
||||
})
|
||||
|
||||
test("refresh always fetches from sources", async () => {
|
||||
let fetchCount = 0
|
||||
const source: FeedSource = {
|
||||
id: "counter",
|
||||
...noActions,
|
||||
async fetchContext() {
|
||||
fetchCount++
|
||||
return null
|
||||
},
|
||||
}
|
||||
|
||||
const engine = new FeedEngine().register(source)
|
||||
|
||||
await engine.refresh()
|
||||
await engine.refresh()
|
||||
await engine.refresh()
|
||||
|
||||
expect(fetchCount).toBe(3)
|
||||
})
|
||||
|
||||
test("reactive context update refreshes cache", async () => {
|
||||
const location = createLocationSource()
|
||||
const weather = createWeatherSource()
|
||||
|
||||
const engine = new FeedEngine({ cacheTtlMs: 5000 }).register(location).register(weather)
|
||||
|
||||
engine.start()
|
||||
|
||||
// Simulate location update which triggers reactive refresh
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
|
||||
// Wait for async reactive refresh to complete
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
const cached = engine.lastFeed()
|
||||
expect(cached).not.toBeNull()
|
||||
expect(cached!.items.length).toBeGreaterThan(0)
|
||||
|
||||
engine.stop()
|
||||
})
|
||||
|
||||
test("reactive item update refreshes cache", async () => {
|
||||
let itemUpdateCallback: (() => void) | null = null
|
||||
|
||||
const source: FeedSource = {
|
||||
id: "reactive-items",
|
||||
...noActions,
|
||||
async fetchContext() {
|
||||
return null
|
||||
},
|
||||
async fetchItems() {
|
||||
return [
|
||||
{
|
||||
id: "item-1",
|
||||
type: "test",
|
||||
priority: 0.5,
|
||||
timestamp: new Date(),
|
||||
data: {},
|
||||
},
|
||||
]
|
||||
},
|
||||
onItemsUpdate(callback) {
|
||||
itemUpdateCallback = callback
|
||||
return () => {
|
||||
itemUpdateCallback = null
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const engine = new FeedEngine().register(source)
|
||||
engine.start()
|
||||
|
||||
// Trigger item update
|
||||
itemUpdateCallback!()
|
||||
|
||||
// Wait for async refresh
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
const cached = engine.lastFeed()
|
||||
expect(cached).not.toBeNull()
|
||||
expect(cached!.items).toHaveLength(1)
|
||||
|
||||
engine.stop()
|
||||
})
|
||||
|
||||
test("TTL resets after reactive update", async () => {
|
||||
const location = createLocationSource()
|
||||
const weather = createWeatherSource()
|
||||
|
||||
const engine = new FeedEngine({ cacheTtlMs: 100 }).register(location).register(weather)
|
||||
|
||||
engine.start()
|
||||
|
||||
// Initial reactive update
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
expect(engine.lastFeed()).not.toBeNull()
|
||||
|
||||
// Wait 70ms (total 120ms from first update, past original TTL)
|
||||
// but trigger another update at 50ms to reset TTL
|
||||
location.simulateUpdate({ lat: 52.0, lng: -0.2 })
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
|
||||
// Should still be cached because TTL was reset by second update
|
||||
expect(engine.lastFeed()).not.toBeNull()
|
||||
|
||||
engine.stop()
|
||||
})
|
||||
|
||||
test("cacheTtlMs is configurable", async () => {
|
||||
const engine = new FeedEngine({ cacheTtlMs: 30 })
|
||||
const location = createLocationSource()
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
|
||||
engine.register(location)
|
||||
await engine.refresh()
|
||||
|
||||
expect(engine.lastFeed()).not.toBeNull()
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 40))
|
||||
|
||||
expect(engine.lastFeed()).toBeNull()
|
||||
})
|
||||
|
||||
test("auto-refreshes on TTL interval after start", async () => {
|
||||
let fetchCount = 0
|
||||
const source: FeedSource = {
|
||||
id: "counter",
|
||||
...noActions,
|
||||
async fetchContext() {
|
||||
fetchCount++
|
||||
return null
|
||||
},
|
||||
async fetchItems() {
|
||||
return [
|
||||
{
|
||||
id: `item-${fetchCount}`,
|
||||
type: "test",
|
||||
priority: 0.5,
|
||||
timestamp: new Date(),
|
||||
data: {},
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
const engine = new FeedEngine({ cacheTtlMs: 50 }).register(source)
|
||||
engine.start()
|
||||
|
||||
// Wait for two TTL intervals to elapse
|
||||
await new Promise((resolve) => setTimeout(resolve, 120))
|
||||
|
||||
// Should have auto-refreshed at least twice
|
||||
expect(fetchCount).toBeGreaterThanOrEqual(2)
|
||||
expect(engine.lastFeed()).not.toBeNull()
|
||||
|
||||
engine.stop()
|
||||
})
|
||||
|
||||
test("stop cancels periodic refresh", async () => {
|
||||
let fetchCount = 0
|
||||
const source: FeedSource = {
|
||||
id: "counter",
|
||||
...noActions,
|
||||
async fetchContext() {
|
||||
fetchCount++
|
||||
return null
|
||||
},
|
||||
}
|
||||
|
||||
const engine = new FeedEngine({ cacheTtlMs: 50 }).register(source)
|
||||
engine.start()
|
||||
engine.stop()
|
||||
|
||||
const countAfterStop = fetchCount
|
||||
|
||||
// Wait past TTL
|
||||
await new Promise((resolve) => setTimeout(resolve, 80))
|
||||
|
||||
// No additional fetches after stop
|
||||
expect(fetchCount).toBe(countAfterStop)
|
||||
})
|
||||
|
||||
test("reactive update resets periodic refresh timer", async () => {
|
||||
let fetchCount = 0
|
||||
const location = createLocationSource()
|
||||
const countingWeather: FeedSource<WeatherFeedItem> = {
|
||||
id: "weather",
|
||||
dependencies: ["location"],
|
||||
...noActions,
|
||||
async fetchContext(ctx) {
|
||||
fetchCount++
|
||||
const loc = contextValue(ctx, LocationKey)
|
||||
if (!loc) return null
|
||||
return { [WeatherKey]: { temperature: 20, condition: "sunny" } }
|
||||
},
|
||||
async fetchItems(ctx) {
|
||||
const weather = contextValue(ctx, WeatherKey)
|
||||
if (!weather) return []
|
||||
return [
|
||||
{
|
||||
id: `weather-${Date.now()}`,
|
||||
type: "weather",
|
||||
priority: 0.5,
|
||||
timestamp: new Date(),
|
||||
data: { temperature: weather.temperature, condition: weather.condition },
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
const engine = new FeedEngine({ cacheTtlMs: 100 })
|
||||
.register(location)
|
||||
.register(countingWeather)
|
||||
|
||||
engine.start()
|
||||
|
||||
// At 40ms, push a reactive update — this resets the timer
|
||||
await new Promise((resolve) => setTimeout(resolve, 40))
|
||||
const countBeforeUpdate = fetchCount
|
||||
location.simulateUpdate({ lat: 51.5, lng: -0.1 })
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
|
||||
// Reactive update triggered a fetch
|
||||
expect(fetchCount).toBeGreaterThan(countBeforeUpdate)
|
||||
const countAfterUpdate = fetchCount
|
||||
|
||||
// At 100ms from start (60ms after reactive update), the original
|
||||
// timer would have fired, but it was reset. No extra fetch yet.
|
||||
await new Promise((resolve) => setTimeout(resolve, 40))
|
||||
expect(fetchCount).toBe(countAfterUpdate)
|
||||
|
||||
engine.stop()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,14 @@ export interface FeedResult<TItem extends FeedItem = FeedItem> {
|
||||
|
||||
export type FeedSubscriber<TItem extends FeedItem = FeedItem> = (result: FeedResult<TItem>) => void
|
||||
|
||||
const DEFAULT_CACHE_TTL_MS = 300_000 // 5 minutes
|
||||
const MIN_CACHE_TTL_MS = 10 // prevent spin from zero/negative values
|
||||
|
||||
export interface FeedEngineConfig {
|
||||
/** Cache TTL in milliseconds. Default: 300_000 (5 minutes). Minimum: 10. */
|
||||
cacheTtlMs?: number
|
||||
}
|
||||
|
||||
interface SourceGraph {
|
||||
sources: Map<string, FeedSource>
|
||||
sorted: FeedSource[]
|
||||
@@ -59,6 +67,29 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
||||
private cleanups: Array<() => void> = []
|
||||
private started = false
|
||||
|
||||
private readonly cacheTtlMs: number
|
||||
private cachedResult: FeedResult<TItems> | null = null
|
||||
private cachedAt: number | null = null
|
||||
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
constructor(config?: FeedEngineConfig) {
|
||||
this.cacheTtlMs = Math.max(config?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS, MIN_CACHE_TTL_MS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the cached FeedResult if available and not expired.
|
||||
* Returns null if no refresh has completed or the cache TTL has elapsed.
|
||||
*/
|
||||
lastFeed(): FeedResult<TItems> | null {
|
||||
if (this.cachedResult === null || this.cachedAt === null) {
|
||||
return null
|
||||
}
|
||||
if (Date.now() - this.cachedAt > this.cacheTtlMs) {
|
||||
return null
|
||||
}
|
||||
return this.cachedResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a FeedSource. Invalidates the cached graph.
|
||||
*/
|
||||
@@ -119,12 +150,12 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by priority descending
|
||||
items.sort((a, b) => b.priority - a.priority)
|
||||
|
||||
this.context = context
|
||||
|
||||
return { context, items: items as TItems[], errors }
|
||||
const result: FeedResult<TItems> = { context, items: items as TItems[], errors }
|
||||
this.updateCache(result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -138,7 +169,7 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts reactive subscriptions on all sources.
|
||||
* Starts reactive subscriptions on all sources and begins periodic refresh.
|
||||
* Sources with onContextUpdate will trigger re-computation of dependents.
|
||||
*/
|
||||
start(): void {
|
||||
@@ -168,13 +199,16 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
||||
this.cleanups.push(cleanup)
|
||||
}
|
||||
}
|
||||
|
||||
this.scheduleNextRefresh()
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops all reactive subscriptions.
|
||||
* Stops all reactive subscriptions and the periodic refresh timer.
|
||||
*/
|
||||
stop(): void {
|
||||
this.started = false
|
||||
this.cancelScheduledRefresh()
|
||||
for (const cleanup of this.cleanups) {
|
||||
cleanup()
|
||||
}
|
||||
@@ -277,13 +311,14 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
||||
}
|
||||
}
|
||||
|
||||
items.sort((a, b) => b.priority - a.priority)
|
||||
|
||||
this.notifySubscribers({
|
||||
const result: FeedResult<TItems> = {
|
||||
context: this.context,
|
||||
items: items as TItems[],
|
||||
errors,
|
||||
})
|
||||
}
|
||||
this.updateCache(result)
|
||||
|
||||
this.notifySubscribers(result)
|
||||
}
|
||||
|
||||
private collectDependents(sourceId: string, graph: SourceGraph): string[] {
|
||||
@@ -307,11 +342,46 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
||||
return graph.sorted.filter((s) => result.includes(s.id)).map((s) => s.id)
|
||||
}
|
||||
|
||||
private updateCache(result: FeedResult<TItems>): void {
|
||||
this.cachedResult = result
|
||||
this.cachedAt = Date.now()
|
||||
if (this.started) {
|
||||
this.scheduleNextRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleNextRefresh(): void {
|
||||
this.cancelScheduledRefresh()
|
||||
this.refreshTimer = setTimeout(() => {
|
||||
this.refresh()
|
||||
.then((result) => {
|
||||
this.notifySubscribers(result)
|
||||
})
|
||||
.catch(() => {
|
||||
// Periodic refresh errors are non-fatal; schedule next attempt
|
||||
if (this.started) {
|
||||
this.scheduleNextRefresh()
|
||||
}
|
||||
})
|
||||
}, this.cacheTtlMs)
|
||||
}
|
||||
|
||||
private cancelScheduledRefresh(): void {
|
||||
if (this.refreshTimer !== null) {
|
||||
clearTimeout(this.refreshTimer)
|
||||
this.refreshTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleRefresh(): void {
|
||||
// Simple immediate refresh for now - could add debouncing later
|
||||
this.refresh().then((result) => {
|
||||
this.refresh()
|
||||
.then((result) => {
|
||||
this.notifySubscribers(result)
|
||||
})
|
||||
.catch(() => {
|
||||
// Reactive refresh errors are non-fatal
|
||||
})
|
||||
}
|
||||
|
||||
private notifySubscribers(result: FeedResult<TItems>): void {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
|
||||
|
||||
import type { ActionDefinition, Context, ContextKey, FeedItem, FeedSource } from "./index"
|
||||
|
||||
import { UnknownActionError, contextKey, contextValue } from "./index"
|
||||
import { TimeRelevance, UnknownActionError, contextKey, contextValue } from "./index"
|
||||
|
||||
// No-op action methods for test sources
|
||||
const noActions = {
|
||||
@@ -99,12 +99,12 @@ function createWeatherSource(
|
||||
{
|
||||
id: `weather-${Date.now()}`,
|
||||
type: "weather",
|
||||
priority: 0.5,
|
||||
timestamp: new Date(),
|
||||
data: {
|
||||
temperature: weather.temperature,
|
||||
condition: weather.condition,
|
||||
},
|
||||
signals: { urgency: 0.5, timeRelevance: TimeRelevance.Ambient },
|
||||
},
|
||||
]
|
||||
},
|
||||
@@ -130,9 +130,9 @@ function createAlertSource(): FeedSource<AlertFeedItem> {
|
||||
{
|
||||
id: "alert-storm",
|
||||
type: "alert",
|
||||
priority: 1.0,
|
||||
timestamp: new Date(),
|
||||
data: { message: "Storm warning!" },
|
||||
signals: { urgency: 1.0, timeRelevance: TimeRelevance.Imminent },
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -226,9 +226,6 @@ async function refreshGraph(graph: SourceGraph): Promise<{ context: Context; ite
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by priority descending
|
||||
items.sort((a, b) => b.priority - a.priority)
|
||||
|
||||
return { context, items }
|
||||
}
|
||||
|
||||
@@ -441,8 +438,12 @@ describe("FeedSource", () => {
|
||||
const { items } = await refreshGraph(graph)
|
||||
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0]!.type).toBe("alert") // priority 1.0
|
||||
expect(items[1]!.type).toBe("weather") // priority 0.5
|
||||
// Items returned in topological order (weather before alert)
|
||||
expect(items[0]!.type).toBe("weather")
|
||||
expect(items[1]!.type).toBe("alert")
|
||||
// Signals preserved for post-processors
|
||||
expect(items[0]!.signals?.urgency).toBe(0.5)
|
||||
expect(items[1]!.signals?.urgency).toBe(1.0)
|
||||
})
|
||||
|
||||
test("source without location context returns empty items", async () => {
|
||||
|
||||
@@ -1,3 +1,28 @@
|
||||
/**
|
||||
* Source-provided hints for post-processors.
|
||||
*
|
||||
* Sources express domain-specific relevance without determining final ranking.
|
||||
* Post-processors consume these signals alongside other inputs (user affinity,
|
||||
* time of day, interaction history) to produce the final feed order.
|
||||
*/
|
||||
export const TimeRelevance = {
|
||||
/** Needs attention now (e.g., event starting in minutes, severe alert) */
|
||||
Imminent: "imminent",
|
||||
/** Relevant soon (e.g., event in the next hour, approaching deadline) */
|
||||
Upcoming: "upcoming",
|
||||
/** Background information (e.g., daily forecast, low-priority status) */
|
||||
Ambient: "ambient",
|
||||
} as const
|
||||
|
||||
export type TimeRelevance = (typeof TimeRelevance)[keyof typeof TimeRelevance]
|
||||
|
||||
export interface FeedItemSignals {
|
||||
/** Source-assessed urgency (0-1). Post-processors use this as one ranking input. */
|
||||
urgency?: number
|
||||
/** How time-sensitive this item is relative to now. */
|
||||
timeRelevance?: TimeRelevance
|
||||
}
|
||||
|
||||
/**
|
||||
* A single item in the feed.
|
||||
*
|
||||
@@ -8,9 +33,9 @@
|
||||
* const item: WeatherItem = {
|
||||
* id: "weather-123",
|
||||
* type: "weather",
|
||||
* priority: 0.5,
|
||||
* timestamp: new Date(),
|
||||
* data: { temp: 18, condition: "cloudy" },
|
||||
* signals: { urgency: 0.5, timeRelevance: "ambient" },
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
@@ -22,10 +47,10 @@ export interface FeedItem<
|
||||
id: string
|
||||
/** Item type, matches the data source type */
|
||||
type: TType
|
||||
/** Sort priority (higher = more important, shown first) */
|
||||
priority: number
|
||||
/** When this item was generated */
|
||||
timestamp: Date
|
||||
/** Type-specific payload */
|
||||
data: TData
|
||||
/** Source-provided hints for post-processors. Optional — omit if no signals apply. */
|
||||
signals?: FeedItemSignals
|
||||
}
|
||||
|
||||
@@ -7,13 +7,14 @@ export type { ActionDefinition } from "./action"
|
||||
export { UnknownActionError } from "./action"
|
||||
|
||||
// Feed
|
||||
export type { FeedItem } from "./feed"
|
||||
export type { FeedItem, FeedItemSignals } from "./feed"
|
||||
export { TimeRelevance } from "./feed"
|
||||
|
||||
// Feed Source
|
||||
export type { FeedSource } from "./feed-source"
|
||||
|
||||
// Feed Engine
|
||||
export type { FeedResult, FeedSubscriber, SourceError } from "./feed-engine"
|
||||
export type { FeedEngineConfig, FeedResult, FeedSubscriber, SourceError } from "./feed-engine"
|
||||
export { FeedEngine } from "./feed-engine"
|
||||
|
||||
// =============================================================================
|
||||
|
||||
@@ -72,8 +72,6 @@ export class Reconciler<TItems extends FeedItem = never> {
|
||||
}
|
||||
})
|
||||
|
||||
items.sort((a, b) => b.priority - a.priority)
|
||||
|
||||
return { items, errors } as ReconcileResult<TItems>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,21 +190,22 @@ describe("query() with mocked client", () => {
|
||||
expect(imperialTemp).toBeCloseTo(expectedImperial, 2)
|
||||
})
|
||||
|
||||
test("assigns priority based on weather conditions", async () => {
|
||||
test("assigns signals based on weather conditions", async () => {
|
||||
const dataSource = new WeatherKitDataSource({ client: mockClient })
|
||||
const context = createMockContext({ lat: 37.7749, lng: -122.4194 })
|
||||
|
||||
const items = await dataSource.query(context)
|
||||
|
||||
for (const item of items) {
|
||||
expect(item.priority).toBeGreaterThanOrEqual(0)
|
||||
expect(item.priority).toBeLessThanOrEqual(1)
|
||||
expect(item.signals).toBeDefined()
|
||||
expect(item.signals!.urgency).toBeGreaterThanOrEqual(0)
|
||||
expect(item.signals!.urgency).toBeLessThanOrEqual(1)
|
||||
expect(item.signals!.timeRelevance).toBeDefined()
|
||||
}
|
||||
|
||||
const currentItem = items.find((i) => i.type === WeatherFeedItemType.current)
|
||||
expect(currentItem).toBeDefined()
|
||||
// Base priority for current is 0.5, may be adjusted for conditions
|
||||
expect(currentItem!.priority).toBeGreaterThanOrEqual(0.5)
|
||||
expect(currentItem!.signals!.urgency).toBeGreaterThanOrEqual(0.5)
|
||||
})
|
||||
|
||||
test("generates unique IDs for each item", async () => {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { Context, DataSource } from "@aris/core"
|
||||
import type { Context, DataSource, FeedItemSignals } from "@aris/core"
|
||||
|
||||
import { TimeRelevance } from "@aris/core"
|
||||
|
||||
import {
|
||||
WeatherFeedItemType,
|
||||
@@ -105,7 +107,7 @@ export class WeatherKitDataSource implements DataSource<WeatherFeedItem, Weather
|
||||
}
|
||||
}
|
||||
|
||||
const BASE_PRIORITY = {
|
||||
const BASE_URGENCY = {
|
||||
current: 0.5,
|
||||
hourly: 0.3,
|
||||
daily: 0.2,
|
||||
@@ -134,17 +136,17 @@ const MODERATE_CONDITIONS = new Set<ConditionCode>([
|
||||
ConditionCode.BlowingSnow,
|
||||
])
|
||||
|
||||
function adjustPriorityForCondition(basePriority: number, conditionCode: ConditionCode): number {
|
||||
function adjustUrgencyForCondition(baseUrgency: number, conditionCode: ConditionCode): number {
|
||||
if (SEVERE_CONDITIONS.has(conditionCode)) {
|
||||
return Math.min(1, basePriority + 0.3)
|
||||
return Math.min(1, baseUrgency + 0.3)
|
||||
}
|
||||
if (MODERATE_CONDITIONS.has(conditionCode)) {
|
||||
return Math.min(1, basePriority + 0.15)
|
||||
return Math.min(1, baseUrgency + 0.15)
|
||||
}
|
||||
return basePriority
|
||||
return baseUrgency
|
||||
}
|
||||
|
||||
function adjustPriorityForAlertSeverity(severity: Severity): number {
|
||||
function adjustUrgencyForAlertSeverity(severity: Severity): number {
|
||||
switch (severity) {
|
||||
case Severity.Extreme:
|
||||
return 1
|
||||
@@ -153,7 +155,29 @@ function adjustPriorityForAlertSeverity(severity: Severity): number {
|
||||
case Severity.Moderate:
|
||||
return 0.75
|
||||
case Severity.Minor:
|
||||
return BASE_PRIORITY.alert
|
||||
return BASE_URGENCY.alert
|
||||
}
|
||||
}
|
||||
|
||||
function timeRelevanceForCondition(conditionCode: ConditionCode): TimeRelevance {
|
||||
if (SEVERE_CONDITIONS.has(conditionCode)) {
|
||||
return TimeRelevance.Imminent
|
||||
}
|
||||
if (MODERATE_CONDITIONS.has(conditionCode)) {
|
||||
return TimeRelevance.Upcoming
|
||||
}
|
||||
return TimeRelevance.Ambient
|
||||
}
|
||||
|
||||
function timeRelevanceForAlertSeverity(severity: Severity): TimeRelevance {
|
||||
switch (severity) {
|
||||
case Severity.Extreme:
|
||||
case Severity.Severe:
|
||||
return TimeRelevance.Imminent
|
||||
case Severity.Moderate:
|
||||
return TimeRelevance.Upcoming
|
||||
case Severity.Minor:
|
||||
return TimeRelevance.Ambient
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,12 +221,14 @@ function createCurrentWeatherFeedItem(
|
||||
timestamp: Date,
|
||||
units: Units,
|
||||
): CurrentWeatherFeedItem {
|
||||
const priority = adjustPriorityForCondition(BASE_PRIORITY.current, current.conditionCode)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForCondition(BASE_URGENCY.current, current.conditionCode),
|
||||
timeRelevance: timeRelevanceForCondition(current.conditionCode),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-current-${timestamp.getTime()}`,
|
||||
type: WeatherFeedItemType.current,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
conditionCode: current.conditionCode,
|
||||
@@ -219,6 +245,7 @@ function createCurrentWeatherFeedItem(
|
||||
windGust: convertSpeed(current.windGust, units),
|
||||
windSpeed: convertSpeed(current.windSpeed, units),
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,12 +255,14 @@ function createHourlyWeatherFeedItem(
|
||||
timestamp: Date,
|
||||
units: Units,
|
||||
): HourlyWeatherFeedItem {
|
||||
const priority = adjustPriorityForCondition(BASE_PRIORITY.hourly, hourly.conditionCode)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForCondition(BASE_URGENCY.hourly, hourly.conditionCode),
|
||||
timeRelevance: timeRelevanceForCondition(hourly.conditionCode),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-hourly-${timestamp.getTime()}-${index}`,
|
||||
type: WeatherFeedItemType.hourly,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
forecastTime: new Date(hourly.forecastStart),
|
||||
@@ -250,6 +279,7 @@ function createHourlyWeatherFeedItem(
|
||||
windGust: convertSpeed(hourly.windGust, units),
|
||||
windSpeed: convertSpeed(hourly.windSpeed, units),
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,12 +289,14 @@ function createDailyWeatherFeedItem(
|
||||
timestamp: Date,
|
||||
units: Units,
|
||||
): DailyWeatherFeedItem {
|
||||
const priority = adjustPriorityForCondition(BASE_PRIORITY.daily, daily.conditionCode)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForCondition(BASE_URGENCY.daily, daily.conditionCode),
|
||||
timeRelevance: timeRelevanceForCondition(daily.conditionCode),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-daily-${timestamp.getTime()}-${index}`,
|
||||
type: WeatherFeedItemType.daily,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
forecastDate: new Date(daily.forecastStart),
|
||||
@@ -279,16 +311,19 @@ function createDailyWeatherFeedItem(
|
||||
temperatureMax: convertTemperature(daily.temperatureMax, units),
|
||||
temperatureMin: convertTemperature(daily.temperatureMin, units),
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
function createWeatherAlertFeedItem(alert: WeatherAlert, timestamp: Date): WeatherAlertFeedItem {
|
||||
const priority = adjustPriorityForAlertSeverity(alert.severity)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForAlertSeverity(alert.severity),
|
||||
timeRelevance: timeRelevanceForAlertSeverity(alert.severity),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-alert-${alert.id}`,
|
||||
type: WeatherFeedItemType.alert,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
alertId: alert.id,
|
||||
@@ -302,5 +337,6 @@ function createWeatherAlertFeedItem(alert: WeatherAlert, timestamp: Date): Weath
|
||||
source: alert.source,
|
||||
urgency: alert.urgency,
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Test//Test//EN
|
||||
BEGIN:VEVENT
|
||||
UID:all-day-001@test
|
||||
DTSTART;VALUE=DATE:20260115
|
||||
DTEND;VALUE=DATE:20260116
|
||||
SUMMARY:Company Holiday
|
||||
STATUS:CONFIRMED
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
@@ -1,11 +0,0 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Test//Test//EN
|
||||
BEGIN:VEVENT
|
||||
UID:cancelled-001@test
|
||||
DTSTART:20260115T120000Z
|
||||
DTEND:20260115T130000Z
|
||||
SUMMARY:Cancelled Meeting
|
||||
STATUS:CANCELLED
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
@@ -1,10 +0,0 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Test//Test//EN
|
||||
BEGIN:VEVENT
|
||||
UID:minimal-001@test
|
||||
DTSTART:20260115T180000Z
|
||||
DTEND:20260115T190000Z
|
||||
SUMMARY:Quick Chat
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
@@ -1,20 +0,0 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Test//Test//EN
|
||||
BEGIN:VEVENT
|
||||
UID:recurring-001@test
|
||||
DTSTART:20260115T090000Z
|
||||
DTEND:20260115T093000Z
|
||||
SUMMARY:Weekly Sync
|
||||
RRULE:FREQ=WEEKLY;COUNT=4
|
||||
STATUS:CONFIRMED
|
||||
END:VEVENT
|
||||
BEGIN:VEVENT
|
||||
UID:recurring-001@test
|
||||
RECURRENCE-ID:20260122T090000Z
|
||||
DTSTART:20260122T100000Z
|
||||
DTEND:20260122T103000Z
|
||||
SUMMARY:Weekly Sync (moved)
|
||||
STATUS:CONFIRMED
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
@@ -1,26 +0,0 @@
|
||||
BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Test//Test//EN
|
||||
BEGIN:VEVENT
|
||||
UID:single-event-001@test
|
||||
DTSTART:20260115T140000Z
|
||||
DTEND:20260115T150000Z
|
||||
SUMMARY:Team Standup
|
||||
LOCATION:Conference Room A
|
||||
DESCRIPTION:Daily standup meeting
|
||||
STATUS:CONFIRMED
|
||||
URL:https://example.com/meeting/123
|
||||
ORGANIZER;CN=Alice Smith:mailto:alice@example.com
|
||||
ATTENDEE;CN=Bob Jones;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED:mailto:bob@example.com
|
||||
ATTENDEE;CN=Carol White;ROLE=OPT-PARTICIPANT;PARTSTAT=TENTATIVE:mailto:carol@example.com
|
||||
BEGIN:VALARM
|
||||
TRIGGER:-PT15M
|
||||
ACTION:DISPLAY
|
||||
DESCRIPTION:Reminder
|
||||
END:VALARM
|
||||
BEGIN:VALARM
|
||||
TRIGGER:-PT5M
|
||||
ACTION:AUDIO
|
||||
END:VALARM
|
||||
END:VEVENT
|
||||
END:VCALENDAR
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "@aris/source-apple-calendar",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"scripts": {
|
||||
"test": "bun test ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@aris/core": "workspace:*",
|
||||
"ical.js": "^2.1.0",
|
||||
"tsdav": "^2.1.7"
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { ContextKey } from "@aris/core"
|
||||
|
||||
import { contextKey } from "@aris/core"
|
||||
|
||||
import type { CalendarEventData } from "./types.ts"
|
||||
|
||||
/**
|
||||
* Calendar context for downstream sources.
|
||||
*
|
||||
* Provides a snapshot of the user's upcoming events so other sources
|
||||
* can adapt (e.g. a commute source checking if there's a meeting soon).
|
||||
*/
|
||||
export interface CalendarContext {
|
||||
/** Events happening right now */
|
||||
inProgress: CalendarEventData[]
|
||||
/** Next upcoming event, if any */
|
||||
nextEvent: CalendarEventData | null
|
||||
/** Whether the user has any events today */
|
||||
hasTodayEvents: boolean
|
||||
/** Total number of events today */
|
||||
todayEventCount: number
|
||||
}
|
||||
|
||||
export const CalendarKey: ContextKey<CalendarContext> = contextKey("calendar")
|
||||
@@ -1,473 +0,0 @@
|
||||
import type { Context } from "@aris/core"
|
||||
|
||||
import { contextValue } from "@aris/core"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
import type {
|
||||
CalendarCredentialProvider,
|
||||
CalendarCredentials,
|
||||
CalendarDAVCalendar,
|
||||
CalendarDAVClient,
|
||||
CalendarDAVObject,
|
||||
CalendarEventData,
|
||||
} from "./types.ts"
|
||||
|
||||
import { CalendarKey } from "./calendar-context.ts"
|
||||
import { CalendarSource, computePriority } from "./calendar-source.ts"
|
||||
|
||||
function loadFixture(name: string): string {
|
||||
return readFileSync(join(import.meta.dir, "..", "fixtures", name), "utf-8")
|
||||
}
|
||||
|
||||
function createContext(time: Date): Context {
|
||||
return { time }
|
||||
}
|
||||
|
||||
const mockCredentials: CalendarCredentials = {
|
||||
accessToken: "mock-access-token",
|
||||
refreshToken: "mock-refresh-token",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
tokenUrl: "https://appleid.apple.com/auth/token",
|
||||
clientId: "com.example.aris",
|
||||
clientSecret: "mock-secret",
|
||||
}
|
||||
|
||||
class NullCredentialProvider implements CalendarCredentialProvider {
|
||||
async fetchCredentials(_userId: string): Promise<CalendarCredentials | null> {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
class MockCredentialProvider implements CalendarCredentialProvider {
|
||||
async fetchCredentials(_userId: string): Promise<CalendarCredentials | null> {
|
||||
return mockCredentials
|
||||
}
|
||||
}
|
||||
|
||||
class MockDAVClient implements CalendarDAVClient {
|
||||
credentials: Record<string, unknown> = {}
|
||||
fetchCalendarsCallCount = 0
|
||||
private calendars: CalendarDAVCalendar[]
|
||||
private objectsByCalendarUrl: Record<string, CalendarDAVObject[]>
|
||||
|
||||
constructor(
|
||||
calendars: CalendarDAVCalendar[],
|
||||
objectsByCalendarUrl: Record<string, CalendarDAVObject[]>,
|
||||
) {
|
||||
this.calendars = calendars
|
||||
this.objectsByCalendarUrl = objectsByCalendarUrl
|
||||
}
|
||||
|
||||
async login(): Promise<void> {}
|
||||
|
||||
async fetchCalendars(): Promise<CalendarDAVCalendar[]> {
|
||||
this.fetchCalendarsCallCount++
|
||||
return this.calendars
|
||||
}
|
||||
|
||||
async fetchCalendarObjects(params: {
|
||||
calendar: CalendarDAVCalendar
|
||||
timeRange: { start: string; end: string }
|
||||
}): Promise<CalendarDAVObject[]> {
|
||||
return this.objectsByCalendarUrl[params.calendar.url] ?? []
|
||||
}
|
||||
}
|
||||
|
||||
describe("CalendarSource", () => {
|
||||
test("has correct id", () => {
|
||||
const source = new CalendarSource(new NullCredentialProvider(), "user-1")
|
||||
expect(source.id).toBe("aris.apple-calendar")
|
||||
})
|
||||
|
||||
test("returns empty array when credentials are null", async () => {
|
||||
const source = new CalendarSource(new NullCredentialProvider(), "user-1")
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
expect(items).toEqual([])
|
||||
})
|
||||
|
||||
test("returns empty array when no calendars exist", async () => {
|
||||
const client = new MockDAVClient([], {})
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
expect(items).toEqual([])
|
||||
})
|
||||
|
||||
test("returns feed items from a single calendar", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]!.type).toBe("calendar-event")
|
||||
expect(items[0]!.id).toBe("calendar-event-single-event-001@test")
|
||||
expect(items[0]!.data.title).toBe("Team Standup")
|
||||
expect(items[0]!.data.location).toBe("Conference Room A")
|
||||
expect(items[0]!.data.calendarName).toBe("Work")
|
||||
expect(items[0]!.data.attendees).toHaveLength(2)
|
||||
expect(items[0]!.data.alarms).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("returns feed items from multiple calendars", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
"/cal/personal": [
|
||||
{
|
||||
url: "/cal/personal/event2.ics",
|
||||
data: loadFixture("all-day-event.ics"),
|
||||
},
|
||||
],
|
||||
}
|
||||
const client = new MockDAVClient(
|
||||
[
|
||||
{ url: "/cal/work", displayName: "Work" },
|
||||
{ url: "/cal/personal", displayName: "Personal" },
|
||||
],
|
||||
objects,
|
||||
)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
|
||||
expect(items).toHaveLength(2)
|
||||
|
||||
const standup = items.find((i) => i.data.title === "Team Standup")
|
||||
const holiday = items.find((i) => i.data.title === "Company Holiday")
|
||||
|
||||
expect(standup).toBeDefined()
|
||||
expect(standup!.data.calendarName).toBe("Work")
|
||||
|
||||
expect(holiday).toBeDefined()
|
||||
expect(holiday!.data.calendarName).toBe("Personal")
|
||||
expect(holiday!.data.isAllDay).toBe(true)
|
||||
})
|
||||
|
||||
test("skips objects with non-string data", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [
|
||||
{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") },
|
||||
{ url: "/cal/work/bad.ics", data: 12345 },
|
||||
{ url: "/cal/work/empty.ics" },
|
||||
],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]!.data.title).toBe("Team Standup")
|
||||
})
|
||||
|
||||
test("uses context time as feed item timestamp", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const now = new Date("2026-01-15T12:00:00Z")
|
||||
const items = await source.fetchItems(createContext(now))
|
||||
expect(items[0]!.timestamp).toEqual(now)
|
||||
})
|
||||
|
||||
test("assigns priority based on event proximity", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [
|
||||
{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") },
|
||||
{ url: "/cal/work/allday.ics", data: loadFixture("all-day-event.ics") },
|
||||
],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
// 2 hours before the event at 14:00
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
|
||||
const standup = items.find((i) => i.data.title === "Team Standup")
|
||||
const holiday = items.find((i) => i.data.title === "Company Holiday")
|
||||
|
||||
expect(standup!.priority).toBe(0.7) // within 2 hours
|
||||
expect(holiday!.priority).toBe(0.3) // all-day
|
||||
})
|
||||
|
||||
test("handles calendar with non-string displayName", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/weird": [
|
||||
{
|
||||
url: "/cal/weird/event1.ics",
|
||||
data: loadFixture("minimal-event.ics"),
|
||||
},
|
||||
],
|
||||
}
|
||||
const client = new MockDAVClient(
|
||||
[{ url: "/cal/weird", displayName: { _cdata: "Weird Calendar" } }],
|
||||
objects,
|
||||
)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
expect(items[0]!.data.calendarName).toBeNull()
|
||||
})
|
||||
|
||||
test("handles recurring events with exceptions", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [
|
||||
{
|
||||
url: "/cal/work/recurring.ics",
|
||||
data: loadFixture("recurring-event.ics"),
|
||||
},
|
||||
],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const items = await source.fetchItems(createContext(new Date("2026-01-15T08:00:00Z")))
|
||||
|
||||
expect(items).toHaveLength(2)
|
||||
|
||||
const base = items.find((i) => i.data.title === "Weekly Sync")
|
||||
const exception = items.find((i) => i.data.title === "Weekly Sync (moved)")
|
||||
|
||||
expect(base).toBeDefined()
|
||||
expect(base!.data.recurrenceId).toBeNull()
|
||||
|
||||
expect(exception).toBeDefined()
|
||||
expect(exception!.data.recurrenceId).not.toBeNull()
|
||||
expect(exception!.id).toContain("-")
|
||||
})
|
||||
|
||||
test("caches events within the same refresh cycle", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const context = createContext(new Date("2026-01-15T12:00:00Z"))
|
||||
|
||||
await source.fetchContext(context)
|
||||
await source.fetchItems(context)
|
||||
|
||||
// Same context.time reference — fetchEvents should only hit the client once
|
||||
expect(client.fetchCalendarsCallCount).toBe(1)
|
||||
})
|
||||
|
||||
test("refetches events for a different context time", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
await source.fetchItems(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
await source.fetchItems(createContext(new Date("2026-01-15T13:00:00Z")))
|
||||
|
||||
// Different context.time references — should fetch twice
|
||||
expect(client.fetchCalendarsCallCount).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe("CalendarSource.fetchContext", () => {
|
||||
test("returns empty context when credentials are null", async () => {
|
||||
const source = new CalendarSource(new NullCredentialProvider(), "user-1")
|
||||
const ctx = await source.fetchContext(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
const calendar = contextValue(ctx as Context, CalendarKey)
|
||||
|
||||
expect(calendar).toBeDefined()
|
||||
expect(calendar!.inProgress).toEqual([])
|
||||
expect(calendar!.nextEvent).toBeNull()
|
||||
expect(calendar!.hasTodayEvents).toBe(false)
|
||||
expect(calendar!.todayEventCount).toBe(0)
|
||||
})
|
||||
|
||||
test("identifies in-progress events", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
// 14:30 is during the 14:00-15:00 event
|
||||
const ctx = await source.fetchContext(createContext(new Date("2026-01-15T14:30:00Z")))
|
||||
const calendar = contextValue(ctx as Context, CalendarKey)
|
||||
|
||||
expect(calendar!.inProgress).toHaveLength(1)
|
||||
expect(calendar!.inProgress[0]!.title).toBe("Team Standup")
|
||||
})
|
||||
|
||||
test("identifies next upcoming event", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
// 12:00 is before the 14:00 event
|
||||
const ctx = await source.fetchContext(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
const calendar = contextValue(ctx as Context, CalendarKey)
|
||||
|
||||
expect(calendar!.inProgress).toHaveLength(0)
|
||||
expect(calendar!.nextEvent).not.toBeNull()
|
||||
expect(calendar!.nextEvent!.title).toBe("Team Standup")
|
||||
})
|
||||
|
||||
test("excludes all-day events from inProgress and nextEvent", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [{ url: "/cal/work/allday.ics", data: loadFixture("all-day-event.ics") }],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const ctx = await source.fetchContext(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
const calendar = contextValue(ctx as Context, CalendarKey)
|
||||
|
||||
expect(calendar!.inProgress).toHaveLength(0)
|
||||
expect(calendar!.nextEvent).toBeNull()
|
||||
expect(calendar!.hasTodayEvents).toBe(true)
|
||||
expect(calendar!.todayEventCount).toBe(1)
|
||||
})
|
||||
|
||||
test("counts all events including all-day in todayEventCount", async () => {
|
||||
const objects: Record<string, CalendarDAVObject[]> = {
|
||||
"/cal/work": [
|
||||
{ url: "/cal/work/event1.ics", data: loadFixture("single-event.ics") },
|
||||
{ url: "/cal/work/allday.ics", data: loadFixture("all-day-event.ics") },
|
||||
],
|
||||
}
|
||||
const client = new MockDAVClient([{ url: "/cal/work", displayName: "Work" }], objects)
|
||||
const source = new CalendarSource(new MockCredentialProvider(), "user-1", {
|
||||
davClient: client,
|
||||
})
|
||||
|
||||
const ctx = await source.fetchContext(createContext(new Date("2026-01-15T12:00:00Z")))
|
||||
const calendar = contextValue(ctx as Context, CalendarKey)
|
||||
|
||||
expect(calendar!.todayEventCount).toBe(2)
|
||||
expect(calendar!.hasTodayEvents).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("computePriority", () => {
|
||||
const now = new Date("2026-01-15T12:00:00Z")
|
||||
|
||||
function makeEvent(overrides: Partial<CalendarEventData>): CalendarEventData {
|
||||
return {
|
||||
uid: "test-uid",
|
||||
title: "Test",
|
||||
startDate: new Date("2026-01-15T14:00:00Z"),
|
||||
endDate: new Date("2026-01-15T15:00:00Z"),
|
||||
isAllDay: false,
|
||||
location: null,
|
||||
description: null,
|
||||
calendarName: null,
|
||||
status: null,
|
||||
url: null,
|
||||
organizer: null,
|
||||
attendees: [],
|
||||
alarms: [],
|
||||
recurrenceId: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test("all-day events get priority 0.3", () => {
|
||||
const event = makeEvent({ isAllDay: true })
|
||||
expect(computePriority(event, now)).toBe(0.3)
|
||||
})
|
||||
|
||||
test("events starting within 30 minutes get priority 0.9", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-15T12:20:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.9)
|
||||
})
|
||||
|
||||
test("events starting exactly at 30 minutes get priority 0.9", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-15T12:30:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.9)
|
||||
})
|
||||
|
||||
test("events starting within 2 hours get priority 0.7", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-15T13:00:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.7)
|
||||
})
|
||||
|
||||
test("events later today get priority 0.5", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-15T20:00:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.5)
|
||||
})
|
||||
|
||||
test("in-progress events get priority 0.8", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-15T11:00:00Z"),
|
||||
endDate: new Date("2026-01-15T13:00:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.8)
|
||||
})
|
||||
|
||||
test("fully past events get priority 0.2", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-15T09:00:00Z"),
|
||||
endDate: new Date("2026-01-15T10:00:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.2)
|
||||
})
|
||||
|
||||
test("events on future days get priority 0.2", () => {
|
||||
const event = makeEvent({
|
||||
startDate: new Date("2026-01-16T10:00:00Z"),
|
||||
})
|
||||
expect(computePriority(event, now)).toBe(0.2)
|
||||
})
|
||||
|
||||
test("priority boundaries are correct", () => {
|
||||
// 31 minutes from now should be 0.7 (within 2 hours, not within 30 min)
|
||||
const event31min = makeEvent({
|
||||
startDate: new Date("2026-01-15T12:31:00Z"),
|
||||
})
|
||||
expect(computePriority(event31min, now)).toBe(0.7)
|
||||
|
||||
// 2 hours 1 minute from now should be 0.5 (later today, not within 2 hours)
|
||||
const event2h1m = makeEvent({
|
||||
startDate: new Date("2026-01-15T14:01:00Z"),
|
||||
})
|
||||
expect(computePriority(event2h1m, now)).toBe(0.5)
|
||||
})
|
||||
})
|
||||
@@ -1,251 +0,0 @@
|
||||
import type { ActionDefinition, Context, FeedSource } from "@aris/core"
|
||||
import { UnknownActionError } from "@aris/core"
|
||||
|
||||
import { DAVClient } from "tsdav"
|
||||
|
||||
import type {
|
||||
CalendarCredentialProvider,
|
||||
CalendarCredentials,
|
||||
CalendarDAVClient,
|
||||
CalendarEventData,
|
||||
CalendarFeedItem,
|
||||
} from "./types.ts"
|
||||
|
||||
export interface CalendarSourceOptions {
|
||||
/** Number of additional days beyond today to fetch. Default: 0 (today only). */
|
||||
lookAheadDays?: number
|
||||
/** Optional DAVClient instance for testing. Uses tsdav DAVClient by default. */
|
||||
davClient?: CalendarDAVClient
|
||||
}
|
||||
|
||||
import { CalendarKey, type CalendarContext } from "./calendar-context.ts"
|
||||
import { parseICalEvents } from "./ical-parser.ts"
|
||||
|
||||
const ICLOUD_CALDAV_URL = "https://caldav.icloud.com"
|
||||
const DEFAULT_LOOK_AHEAD_DAYS = 0
|
||||
|
||||
/**
|
||||
* A FeedSource that fetches Apple Calendar events via CalDAV.
|
||||
*
|
||||
* Credentials are provided by an injected CalendarCredentialProvider.
|
||||
* The server is responsible for managing OAuth tokens and storage.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const source = new CalendarSource(credentialProvider, "user-123")
|
||||
* const engine = new FeedEngine()
|
||||
* engine.register(source)
|
||||
* ```
|
||||
*/
|
||||
export class CalendarSource implements FeedSource<CalendarFeedItem> {
|
||||
readonly id = "aris.apple-calendar"
|
||||
|
||||
private readonly credentialProvider: CalendarCredentialProvider
|
||||
private readonly userId: string
|
||||
private readonly lookAheadDays: number
|
||||
private readonly injectedClient: CalendarDAVClient | null
|
||||
private davClient: CalendarDAVClient | null = null
|
||||
private lastAccessToken: string | null = null
|
||||
private cachedEvents: { time: Date; events: CalendarEventData[] } | null = null
|
||||
|
||||
constructor(
|
||||
credentialProvider: CalendarCredentialProvider,
|
||||
userId: string,
|
||||
options?: CalendarSourceOptions,
|
||||
) {
|
||||
this.credentialProvider = credentialProvider
|
||||
this.userId = userId
|
||||
this.lookAheadDays = options?.lookAheadDays ?? DEFAULT_LOOK_AHEAD_DAYS
|
||||
this.injectedClient = options?.davClient ?? null
|
||||
}
|
||||
|
||||
async listActions(): Promise<Record<string, ActionDefinition>> {
|
||||
return {}
|
||||
}
|
||||
|
||||
async executeAction(actionId: string): Promise<void> {
|
||||
throw new UnknownActionError(actionId)
|
||||
}
|
||||
|
||||
async fetchContext(context: Context): Promise<Partial<Context> | null> {
|
||||
const events = await this.fetchEvents(context)
|
||||
if (events.length === 0) {
|
||||
return {
|
||||
[CalendarKey]: {
|
||||
inProgress: [],
|
||||
nextEvent: null,
|
||||
hasTodayEvents: false,
|
||||
todayEventCount: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const now = context.time
|
||||
const inProgress = events.filter((e) => !e.isAllDay && e.startDate <= now && e.endDate > now)
|
||||
|
||||
const upcoming = events
|
||||
.filter((e) => !e.isAllDay && e.startDate > now)
|
||||
.sort((a, b) => a.startDate.getTime() - b.startDate.getTime())
|
||||
|
||||
const calendarContext: CalendarContext = {
|
||||
inProgress,
|
||||
nextEvent: upcoming[0] ?? null,
|
||||
hasTodayEvents: events.length > 0,
|
||||
todayEventCount: events.length,
|
||||
}
|
||||
|
||||
return { [CalendarKey]: calendarContext }
|
||||
}
|
||||
|
||||
async fetchItems(context: Context): Promise<CalendarFeedItem[]> {
|
||||
const now = context.time
|
||||
const events = await this.fetchEvents(context)
|
||||
return events.map((event) => createFeedItem(event, now))
|
||||
}
|
||||
|
||||
private async fetchEvents(context: Context): Promise<CalendarEventData[]> {
|
||||
if (this.cachedEvents && this.cachedEvents.time === context.time) {
|
||||
return this.cachedEvents.events
|
||||
}
|
||||
|
||||
const credentials = await this.credentialProvider.fetchCredentials(this.userId)
|
||||
if (!credentials) {
|
||||
return []
|
||||
}
|
||||
|
||||
const client = await this.connectClient(credentials)
|
||||
const calendars = await client.fetchCalendars()
|
||||
|
||||
const { start, end } = computeTimeRange(context.time, this.lookAheadDays)
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
calendars.map(async (calendar) => {
|
||||
const objects = await client.fetchCalendarObjects({
|
||||
calendar,
|
||||
timeRange: {
|
||||
start: start.toISOString(),
|
||||
end: end.toISOString(),
|
||||
},
|
||||
})
|
||||
// tsdav types displayName as string | Record<string, unknown> | undefined
|
||||
// because the XML parser can return an object for some responses
|
||||
const calendarName = typeof calendar.displayName === "string" ? calendar.displayName : null
|
||||
return { objects, calendarName }
|
||||
}),
|
||||
)
|
||||
|
||||
const allEvents: CalendarEventData[] = []
|
||||
for (const result of results) {
|
||||
if (result.status !== "fulfilled") continue
|
||||
const { objects, calendarName } = result.value
|
||||
for (const obj of objects) {
|
||||
if (typeof obj.data !== "string") continue
|
||||
|
||||
const events = parseICalEvents(obj.data, calendarName)
|
||||
for (const event of events) {
|
||||
allEvents.push(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.cachedEvents = { time: context.time, events: allEvents }
|
||||
return allEvents
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a ready-to-use DAVClient. Creates and logs in a new client
|
||||
* on first call; reuses the existing one on subsequent calls, updating
|
||||
* credentials if the access token has changed.
|
||||
*/
|
||||
private async connectClient(credentials: CalendarCredentials): Promise<CalendarDAVClient> {
|
||||
if (this.injectedClient) {
|
||||
return this.injectedClient
|
||||
}
|
||||
|
||||
const davCredentials = {
|
||||
tokenUrl: credentials.tokenUrl,
|
||||
refreshToken: credentials.refreshToken,
|
||||
accessToken: credentials.accessToken,
|
||||
expiration: credentials.expiresAt,
|
||||
clientId: credentials.clientId,
|
||||
clientSecret: credentials.clientSecret,
|
||||
}
|
||||
|
||||
if (!this.davClient) {
|
||||
this.davClient = new DAVClient({
|
||||
serverUrl: ICLOUD_CALDAV_URL,
|
||||
credentials: davCredentials,
|
||||
authMethod: "Oauth",
|
||||
defaultAccountType: "caldav",
|
||||
})
|
||||
await this.davClient.login()
|
||||
this.lastAccessToken = credentials.accessToken
|
||||
return this.davClient
|
||||
}
|
||||
|
||||
if (credentials.accessToken !== this.lastAccessToken) {
|
||||
this.davClient.credentials = davCredentials
|
||||
this.lastAccessToken = credentials.accessToken
|
||||
}
|
||||
|
||||
return this.davClient
|
||||
}
|
||||
}
|
||||
|
||||
function computeTimeRange(now: Date, lookAheadDays: number): { start: Date; end: Date } {
|
||||
const start = new Date(now)
|
||||
start.setUTCHours(0, 0, 0, 0)
|
||||
|
||||
const end = new Date(start)
|
||||
end.setUTCDate(end.getUTCDate() + 1 + lookAheadDays)
|
||||
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
export function computePriority(event: CalendarEventData, now: Date): number {
|
||||
if (event.isAllDay) {
|
||||
return 0.3
|
||||
}
|
||||
|
||||
const msUntilStart = event.startDate.getTime() - now.getTime()
|
||||
|
||||
// Event already started
|
||||
if (msUntilStart < 0) {
|
||||
const isInProgress = now.getTime() < event.endDate.getTime()
|
||||
// Currently happening events are high priority; fully past events are low
|
||||
return isInProgress ? 0.8 : 0.2
|
||||
}
|
||||
|
||||
// Starting within 30 minutes
|
||||
if (msUntilStart <= 30 * 60 * 1000) {
|
||||
return 0.9
|
||||
}
|
||||
|
||||
// Starting within 2 hours
|
||||
if (msUntilStart <= 2 * 60 * 60 * 1000) {
|
||||
return 0.7
|
||||
}
|
||||
|
||||
// Later today (within 24 hours from start of day)
|
||||
const startOfDay = new Date(now)
|
||||
startOfDay.setUTCHours(0, 0, 0, 0)
|
||||
const endOfDay = new Date(startOfDay)
|
||||
endOfDay.setUTCDate(endOfDay.getUTCDate() + 1)
|
||||
|
||||
if (event.startDate.getTime() < endOfDay.getTime()) {
|
||||
return 0.5
|
||||
}
|
||||
|
||||
// Future days
|
||||
return 0.2
|
||||
}
|
||||
|
||||
function createFeedItem(event: CalendarEventData, now: Date): CalendarFeedItem {
|
||||
return {
|
||||
id: `calendar-event-${event.uid}${event.recurrenceId ? `-${event.recurrenceId}` : ""}`,
|
||||
type: "calendar-event",
|
||||
priority: computePriority(event, now),
|
||||
timestamp: now,
|
||||
data: event,
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
import { parseICalEvents } from "./ical-parser.ts"
|
||||
|
||||
function loadFixture(name: string): string {
|
||||
return readFileSync(join(import.meta.dir, "..", "fixtures", name), "utf-8")
|
||||
}
|
||||
|
||||
describe("parseICalEvents", () => {
|
||||
test("parses a full event with all fields", () => {
|
||||
const events = parseICalEvents(loadFixture("single-event.ics"), "Work")
|
||||
|
||||
expect(events).toHaveLength(1)
|
||||
const event = events[0]!
|
||||
|
||||
expect(event.uid).toBe("single-event-001@test")
|
||||
expect(event.title).toBe("Team Standup")
|
||||
expect(event.startDate).toEqual(new Date("2026-01-15T14:00:00Z"))
|
||||
expect(event.endDate).toEqual(new Date("2026-01-15T15:00:00Z"))
|
||||
expect(event.isAllDay).toBe(false)
|
||||
expect(event.location).toBe("Conference Room A")
|
||||
expect(event.description).toBe("Daily standup meeting")
|
||||
expect(event.calendarName).toBe("Work")
|
||||
expect(event.status).toBe("confirmed")
|
||||
expect(event.url).toBe("https://example.com/meeting/123")
|
||||
expect(event.organizer).toBe("Alice Smith")
|
||||
expect(event.recurrenceId).toBeNull()
|
||||
|
||||
expect(event.attendees).toHaveLength(2)
|
||||
expect(event.attendees[0]).toEqual({
|
||||
name: "Bob Jones",
|
||||
email: "bob@example.com",
|
||||
role: "required",
|
||||
status: "accepted",
|
||||
})
|
||||
expect(event.attendees[1]).toEqual({
|
||||
name: "Carol White",
|
||||
email: "carol@example.com",
|
||||
role: "optional",
|
||||
status: "tentative",
|
||||
})
|
||||
|
||||
expect(event.alarms).toHaveLength(2)
|
||||
expect(event.alarms[0]).toEqual({ trigger: "-PT15M", action: "DISPLAY" })
|
||||
expect(event.alarms[1]).toEqual({ trigger: "-PT5M", action: "AUDIO" })
|
||||
})
|
||||
|
||||
test("parses an all-day event with optional fields as null", () => {
|
||||
const events = parseICalEvents(loadFixture("all-day-event.ics"), null)
|
||||
|
||||
expect(events).toHaveLength(1)
|
||||
const event = events[0]!
|
||||
|
||||
expect(event.isAllDay).toBe(true)
|
||||
expect(event.title).toBe("Company Holiday")
|
||||
expect(event.calendarName).toBeNull()
|
||||
expect(event.location).toBeNull()
|
||||
expect(event.description).toBeNull()
|
||||
expect(event.url).toBeNull()
|
||||
expect(event.organizer).toBeNull()
|
||||
expect(event.attendees).toEqual([])
|
||||
expect(event.alarms).toEqual([])
|
||||
})
|
||||
|
||||
test("parses recurring event with exception", () => {
|
||||
const events = parseICalEvents(loadFixture("recurring-event.ics"), "Team")
|
||||
|
||||
expect(events).toHaveLength(2)
|
||||
expect(events[0]!.uid).toBe("recurring-001@test")
|
||||
expect(events[1]!.uid).toBe("recurring-001@test")
|
||||
|
||||
const base = events.find((e) => e.title === "Weekly Sync")
|
||||
expect(base).toBeDefined()
|
||||
expect(base!.recurrenceId).toBeNull()
|
||||
|
||||
const exception = events.find((e) => e.title === "Weekly Sync (moved)")
|
||||
expect(exception).toBeDefined()
|
||||
expect(exception!.recurrenceId).not.toBeNull()
|
||||
})
|
||||
|
||||
test("parses minimal event with defaults", () => {
|
||||
const events = parseICalEvents(loadFixture("minimal-event.ics"), null)
|
||||
|
||||
expect(events).toHaveLength(1)
|
||||
const event = events[0]!
|
||||
|
||||
expect(event.uid).toBe("minimal-001@test")
|
||||
expect(event.title).toBe("Quick Chat")
|
||||
expect(event.startDate).toEqual(new Date("2026-01-15T18:00:00Z"))
|
||||
expect(event.endDate).toEqual(new Date("2026-01-15T19:00:00Z"))
|
||||
expect(event.location).toBeNull()
|
||||
expect(event.description).toBeNull()
|
||||
expect(event.status).toBeNull()
|
||||
expect(event.url).toBeNull()
|
||||
expect(event.organizer).toBeNull()
|
||||
expect(event.attendees).toEqual([])
|
||||
expect(event.alarms).toEqual([])
|
||||
expect(event.recurrenceId).toBeNull()
|
||||
})
|
||||
|
||||
test("parses cancelled status", () => {
|
||||
const events = parseICalEvents(loadFixture("cancelled-event.ics"), null)
|
||||
expect(events[0]!.status).toBe("cancelled")
|
||||
})
|
||||
})
|
||||
@@ -1,150 +0,0 @@
|
||||
import ICAL from "ical.js"
|
||||
|
||||
import {
|
||||
AttendeeRole,
|
||||
AttendeeStatus,
|
||||
CalendarEventStatus,
|
||||
type CalendarAlarm,
|
||||
type CalendarAttendee,
|
||||
type CalendarEventData,
|
||||
} from "./types.ts"
|
||||
|
||||
/**
|
||||
* Parses a raw iCalendar string and extracts all VEVENT components
|
||||
* into CalendarEventData objects.
|
||||
*
|
||||
* @param icsData - Raw iCalendar string from a CalDAV response
|
||||
* @param calendarName - Display name of the calendar this event belongs to
|
||||
*/
|
||||
export function parseICalEvents(icsData: string, calendarName: string | null): CalendarEventData[] {
|
||||
const jcal = ICAL.parse(icsData)
|
||||
const comp = new ICAL.Component(jcal)
|
||||
const vevents = comp.getAllSubcomponents("vevent")
|
||||
|
||||
return vevents.map((vevent: InstanceType<typeof ICAL.Component>) =>
|
||||
parseVEvent(vevent, calendarName),
|
||||
)
|
||||
}
|
||||
|
||||
function parseVEvent(
|
||||
vevent: InstanceType<typeof ICAL.Component>,
|
||||
calendarName: string | null,
|
||||
): CalendarEventData {
|
||||
const event = new ICAL.Event(vevent)
|
||||
|
||||
return {
|
||||
uid: event.uid ?? "",
|
||||
title: event.summary ?? "",
|
||||
startDate: event.startDate?.toJSDate() ?? new Date(0),
|
||||
endDate: event.endDate?.toJSDate() ?? new Date(0),
|
||||
isAllDay: event.startDate?.isDate ?? false,
|
||||
location: event.location ?? null,
|
||||
description: event.description ?? null,
|
||||
calendarName,
|
||||
status: parseStatus(asStringOrNull(vevent.getFirstPropertyValue("status"))),
|
||||
url: asStringOrNull(vevent.getFirstPropertyValue("url")),
|
||||
organizer: parseOrganizer(asStringOrNull(event.organizer), vevent),
|
||||
attendees: parseAttendees(Array.isArray(event.attendees) ? event.attendees : []),
|
||||
alarms: parseAlarms(vevent),
|
||||
recurrenceId: event.recurrenceId ? event.recurrenceId.toString() : null,
|
||||
}
|
||||
}
|
||||
|
||||
function parseStatus(raw: string | null): CalendarEventStatus | null {
|
||||
if (!raw) return null
|
||||
switch (raw.toLowerCase()) {
|
||||
case "confirmed":
|
||||
return CalendarEventStatus.Confirmed
|
||||
case "tentative":
|
||||
return CalendarEventStatus.Tentative
|
||||
case "cancelled":
|
||||
return CalendarEventStatus.Cancelled
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function parseOrganizer(
|
||||
value: string | null,
|
||||
vevent: InstanceType<typeof ICAL.Component>,
|
||||
): string | null {
|
||||
if (!value) return null
|
||||
|
||||
// Try CN parameter first
|
||||
const prop = vevent.getFirstProperty("organizer")
|
||||
if (prop) {
|
||||
const cn = prop.getParameter("cn") as string | undefined
|
||||
if (cn) return cn
|
||||
}
|
||||
|
||||
// Fall back to mailto: value
|
||||
return value.replace(/^mailto:/i, "")
|
||||
}
|
||||
|
||||
function parseAttendees(properties: unknown[]): CalendarAttendee[] {
|
||||
if (properties.length === 0) return []
|
||||
|
||||
return properties.map((prop) => {
|
||||
const p = prop as InstanceType<typeof ICAL.Property>
|
||||
const value = asStringOrNull(p.getFirstValue())
|
||||
const cn = asStringOrNull(p.getParameter("cn"))
|
||||
const role = asStringOrNull(p.getParameter("role"))
|
||||
const partstat = asStringOrNull(p.getParameter("partstat"))
|
||||
|
||||
return {
|
||||
name: cn,
|
||||
email: value ? value.replace(/^mailto:/i, "") : null,
|
||||
role: parseAttendeeRole(role),
|
||||
status: parseAttendeeStatus(partstat),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function parseAttendeeRole(raw: string | null): AttendeeRole | null {
|
||||
if (!raw) return null
|
||||
switch (raw.toUpperCase()) {
|
||||
case "CHAIR":
|
||||
return AttendeeRole.Chair
|
||||
case "REQ-PARTICIPANT":
|
||||
return AttendeeRole.Required
|
||||
case "OPT-PARTICIPANT":
|
||||
return AttendeeRole.Optional
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function parseAttendeeStatus(raw: string | null): AttendeeStatus | null {
|
||||
if (!raw) return null
|
||||
switch (raw.toUpperCase()) {
|
||||
case "ACCEPTED":
|
||||
return AttendeeStatus.Accepted
|
||||
case "DECLINED":
|
||||
return AttendeeStatus.Declined
|
||||
case "TENTATIVE":
|
||||
return AttendeeStatus.Tentative
|
||||
case "NEEDS-ACTION":
|
||||
return AttendeeStatus.NeedsAction
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function parseAlarms(vevent: InstanceType<typeof ICAL.Component>): CalendarAlarm[] {
|
||||
const valarms = vevent.getAllSubcomponents("valarm")
|
||||
if (!valarms || valarms.length === 0) return []
|
||||
|
||||
return valarms.map((valarm: InstanceType<typeof ICAL.Component>) => {
|
||||
const trigger = valarm.getFirstPropertyValue("trigger")
|
||||
const action = asStringOrNull(valarm.getFirstPropertyValue("action"))
|
||||
|
||||
return {
|
||||
trigger: trigger ? trigger.toString() : "",
|
||||
action: action ?? "DISPLAY",
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function asStringOrNull(value: unknown): string | null {
|
||||
return typeof value === "string" ? value : null
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
export { CalendarKey, type CalendarContext } from "./calendar-context.ts"
|
||||
export { CalendarSource, type CalendarSourceOptions } from "./calendar-source.ts"
|
||||
export {
|
||||
CalendarEventStatus,
|
||||
AttendeeRole,
|
||||
AttendeeStatus,
|
||||
type CalendarCredentials,
|
||||
type CalendarCredentialProvider,
|
||||
type CalendarDAVClient,
|
||||
type CalendarDAVCalendar,
|
||||
type CalendarDAVObject,
|
||||
type CalendarAttendee,
|
||||
type CalendarAlarm,
|
||||
type CalendarEventData,
|
||||
type CalendarFeedItem,
|
||||
} from "./types.ts"
|
||||
@@ -1,101 +0,0 @@
|
||||
import type { FeedItem } from "@aris/core"
|
||||
|
||||
// -- Credential provider --
|
||||
|
||||
export interface CalendarCredentials {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
/** Unix timestamp in milliseconds when the access token expires */
|
||||
expiresAt: number
|
||||
tokenUrl: string
|
||||
clientId: string
|
||||
clientSecret: string
|
||||
}
|
||||
|
||||
export interface CalendarCredentialProvider {
|
||||
fetchCredentials(userId: string): Promise<CalendarCredentials | null>
|
||||
}
|
||||
|
||||
// -- Feed item types --
|
||||
|
||||
export const CalendarEventStatus = {
|
||||
Confirmed: "confirmed",
|
||||
Tentative: "tentative",
|
||||
Cancelled: "cancelled",
|
||||
} as const
|
||||
|
||||
export type CalendarEventStatus = (typeof CalendarEventStatus)[keyof typeof CalendarEventStatus]
|
||||
|
||||
export const AttendeeRole = {
|
||||
Chair: "chair",
|
||||
Required: "required",
|
||||
Optional: "optional",
|
||||
} as const
|
||||
|
||||
export type AttendeeRole = (typeof AttendeeRole)[keyof typeof AttendeeRole]
|
||||
|
||||
export const AttendeeStatus = {
|
||||
Accepted: "accepted",
|
||||
Declined: "declined",
|
||||
Tentative: "tentative",
|
||||
NeedsAction: "needs-action",
|
||||
} as const
|
||||
|
||||
export type AttendeeStatus = (typeof AttendeeStatus)[keyof typeof AttendeeStatus]
|
||||
|
||||
export interface CalendarAttendee {
|
||||
name: string | null
|
||||
email: string | null
|
||||
role: AttendeeRole | null
|
||||
status: AttendeeStatus | null
|
||||
}
|
||||
|
||||
export interface CalendarAlarm {
|
||||
/** ISO 8601 duration relative to event start, e.g. "-PT15M" */
|
||||
trigger: string
|
||||
/** e.g. "DISPLAY", "AUDIO" */
|
||||
action: string
|
||||
}
|
||||
|
||||
export interface CalendarEventData extends Record<string, unknown> {
|
||||
uid: string
|
||||
title: string
|
||||
startDate: Date
|
||||
endDate: Date
|
||||
isAllDay: boolean
|
||||
location: string | null
|
||||
description: string | null
|
||||
calendarName: string | null
|
||||
status: CalendarEventStatus | null
|
||||
url: string | null
|
||||
organizer: string | null
|
||||
attendees: CalendarAttendee[]
|
||||
alarms: CalendarAlarm[]
|
||||
recurrenceId: string | null
|
||||
}
|
||||
|
||||
export type CalendarFeedItem = FeedItem<"calendar-event", CalendarEventData>
|
||||
|
||||
// -- DAV client interface --
|
||||
|
||||
export interface CalendarDAVObject {
|
||||
data?: unknown
|
||||
etag?: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface CalendarDAVCalendar {
|
||||
displayName?: string | Record<string, unknown>
|
||||
url: string
|
||||
}
|
||||
|
||||
/** Subset of DAVClient used by CalendarSource. */
|
||||
export interface CalendarDAVClient {
|
||||
login(): Promise<void>
|
||||
fetchCalendars(): Promise<CalendarDAVCalendar[]>
|
||||
fetchCalendarObjects(params: {
|
||||
calendar: CalendarDAVCalendar
|
||||
timeRange: { start: string; end: string }
|
||||
}): Promise<CalendarDAVObject[]>
|
||||
credentials: Record<string, unknown>
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { contextValue, type Context } from "@aris/core"
|
||||
import { TimeRelevance, contextValue, type Context } from "@aris/core"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import type { ApiCalendarEvent, GoogleCalendarClient, ListEventsOptions } from "./types"
|
||||
@@ -81,16 +81,17 @@ describe("GoogleCalendarSource", () => {
|
||||
expect(allDayItems.length).toBe(1)
|
||||
})
|
||||
|
||||
test("ongoing events get highest priority (1.0)", async () => {
|
||||
test("ongoing events get highest urgency (1.0)", async () => {
|
||||
const source = new GoogleCalendarSource({ client: defaultMockClient() })
|
||||
const items = await source.fetchItems(createContext())
|
||||
|
||||
const ongoing = items.find((i) => i.data.eventId === "evt-ongoing")
|
||||
expect(ongoing).toBeDefined()
|
||||
expect(ongoing!.priority).toBe(1.0)
|
||||
expect(ongoing!.signals!.urgency).toBe(1.0)
|
||||
expect(ongoing!.signals!.timeRelevance).toBe(TimeRelevance.Imminent)
|
||||
})
|
||||
|
||||
test("upcoming events get higher priority when sooner", async () => {
|
||||
test("upcoming events get higher urgency when sooner", async () => {
|
||||
const source = new GoogleCalendarSource({ client: defaultMockClient() })
|
||||
const items = await source.fetchItems(createContext())
|
||||
|
||||
@@ -99,16 +100,17 @@ describe("GoogleCalendarSource", () => {
|
||||
|
||||
expect(soon).toBeDefined()
|
||||
expect(later).toBeDefined()
|
||||
expect(soon!.priority).toBeGreaterThan(later!.priority)
|
||||
expect(soon!.signals!.urgency).toBeGreaterThan(later!.signals!.urgency!)
|
||||
})
|
||||
|
||||
test("all-day events get flat priority (0.4)", async () => {
|
||||
test("all-day events get flat urgency (0.4)", async () => {
|
||||
const source = new GoogleCalendarSource({ client: defaultMockClient() })
|
||||
const items = await source.fetchItems(createContext())
|
||||
|
||||
const allDay = items.find((i) => i.data.eventId === "evt-allday")
|
||||
expect(allDay).toBeDefined()
|
||||
expect(allDay!.priority).toBe(0.4)
|
||||
expect(allDay!.signals!.urgency).toBe(0.4)
|
||||
expect(allDay!.signals!.timeRelevance).toBe(TimeRelevance.Ambient)
|
||||
})
|
||||
|
||||
test("generates unique IDs for each item", async () => {
|
||||
@@ -280,7 +282,7 @@ describe("GoogleCalendarSource", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("priority ordering", () => {
|
||||
describe("urgency ordering", () => {
|
||||
test("ongoing > upcoming > all-day", async () => {
|
||||
const source = new GoogleCalendarSource({ client: defaultMockClient() })
|
||||
const items = await source.fetchItems(createContext())
|
||||
@@ -289,8 +291,8 @@ describe("GoogleCalendarSource", () => {
|
||||
const upcoming = items.find((i) => i.data.eventId === "evt-soon")!
|
||||
const allDay = items.find((i) => i.data.eventId === "evt-allday")!
|
||||
|
||||
expect(ongoing.priority).toBeGreaterThan(upcoming.priority)
|
||||
expect(upcoming.priority).toBeGreaterThan(allDay.priority)
|
||||
expect(ongoing.signals!.urgency).toBeGreaterThan(upcoming.signals!.urgency!)
|
||||
expect(upcoming.signals!.urgency).toBeGreaterThan(allDay.signals!.urgency!)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ActionDefinition, Context, FeedSource } from "@aris/core"
|
||||
import type { ActionDefinition, Context, FeedItemSignals, FeedSource } from "@aris/core"
|
||||
|
||||
import { UnknownActionError } from "@aris/core"
|
||||
import { TimeRelevance, UnknownActionError } from "@aris/core"
|
||||
|
||||
import type {
|
||||
ApiCalendarEvent,
|
||||
@@ -35,10 +35,10 @@ import { DefaultGoogleCalendarClient } from "./google-calendar-api"
|
||||
|
||||
const DEFAULT_LOOKAHEAD_HOURS = 24
|
||||
|
||||
const PRIORITY_ONGOING = 1.0
|
||||
const PRIORITY_UPCOMING_MAX = 0.9
|
||||
const PRIORITY_UPCOMING_MIN = 0.3
|
||||
const PRIORITY_ALL_DAY = 0.4
|
||||
const URGENCY_ONGOING = 1.0
|
||||
const URGENCY_UPCOMING_MAX = 0.9
|
||||
const URGENCY_UPCOMING_MIN = 0.3
|
||||
const URGENCY_ALL_DAY = 0.4
|
||||
|
||||
/**
|
||||
* A FeedSource that provides Google Calendar events and next-event context.
|
||||
@@ -171,9 +171,13 @@ function parseEvent(event: ApiCalendarEvent, calendarId: string): CalendarEventD
|
||||
}
|
||||
}
|
||||
|
||||
function computePriority(event: CalendarEventData, nowMs: number, lookaheadMs: number): number {
|
||||
function computeSignals(
|
||||
event: CalendarEventData,
|
||||
nowMs: number,
|
||||
lookaheadMs: number,
|
||||
): FeedItemSignals {
|
||||
if (event.isAllDay) {
|
||||
return PRIORITY_ALL_DAY
|
||||
return { urgency: URGENCY_ALL_DAY, timeRelevance: TimeRelevance.Ambient }
|
||||
}
|
||||
|
||||
const startMs = event.startTime.getTime()
|
||||
@@ -181,17 +185,23 @@ function computePriority(event: CalendarEventData, nowMs: number, lookaheadMs: n
|
||||
|
||||
// Ongoing: start <= now < end
|
||||
if (startMs <= nowMs && nowMs < endMs) {
|
||||
return PRIORITY_ONGOING
|
||||
return { urgency: URGENCY_ONGOING, timeRelevance: TimeRelevance.Imminent }
|
||||
}
|
||||
|
||||
// Upcoming: linear decay from PRIORITY_UPCOMING_MAX to PRIORITY_UPCOMING_MIN
|
||||
// Upcoming: linear decay from URGENCY_UPCOMING_MAX to URGENCY_UPCOMING_MIN
|
||||
const msUntilStart = startMs - nowMs
|
||||
if (msUntilStart <= 0) {
|
||||
return PRIORITY_UPCOMING_MIN
|
||||
return { urgency: URGENCY_UPCOMING_MIN, timeRelevance: TimeRelevance.Ambient }
|
||||
}
|
||||
|
||||
const ratio = Math.min(msUntilStart / lookaheadMs, 1)
|
||||
return PRIORITY_UPCOMING_MAX - ratio * (PRIORITY_UPCOMING_MAX - PRIORITY_UPCOMING_MIN)
|
||||
const urgency = URGENCY_UPCOMING_MAX - ratio * (URGENCY_UPCOMING_MAX - URGENCY_UPCOMING_MIN)
|
||||
|
||||
// Within 30 minutes = imminent, otherwise upcoming
|
||||
const timeRelevance =
|
||||
msUntilStart <= 30 * 60 * 1000 ? TimeRelevance.Imminent : TimeRelevance.Upcoming
|
||||
|
||||
return { urgency, timeRelevance }
|
||||
}
|
||||
|
||||
function createFeedItem(
|
||||
@@ -199,14 +209,13 @@ function createFeedItem(
|
||||
nowMs: number,
|
||||
lookaheadMs: number,
|
||||
): CalendarFeedItem {
|
||||
const priority = computePriority(event, nowMs, lookaheadMs)
|
||||
const itemType = event.isAllDay ? CalendarFeedItemType.allDay : CalendarFeedItemType.event
|
||||
|
||||
return {
|
||||
id: `calendar-${event.calendarId}-${event.eventId}`,
|
||||
type: itemType,
|
||||
priority,
|
||||
timestamp: new Date(nowMs),
|
||||
data: event,
|
||||
signals: computeSignals(event, nowMs, lookaheadMs),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +184,8 @@ describe("TflSource", () => {
|
||||
expect(typeof item.id).toBe("string")
|
||||
expect(item.id).toMatch(/^tfl-alert-/)
|
||||
expect(item.type).toBe("tfl-alert")
|
||||
expect(typeof item.priority).toBe("number")
|
||||
expect(item.signals).toBeDefined()
|
||||
expect(typeof item.signals!.urgency).toBe("number")
|
||||
expect(item.timestamp).toBeInstanceOf(Date)
|
||||
}
|
||||
})
|
||||
@@ -220,29 +221,29 @@ describe("TflSource", () => {
|
||||
expect(uniqueIds.size).toBe(ids.length)
|
||||
})
|
||||
|
||||
test("feed items are sorted by priority descending", async () => {
|
||||
test("feed items are sorted by urgency descending", async () => {
|
||||
const source = new TflSource({ client: api })
|
||||
const items = await source.fetchItems(createContext())
|
||||
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
const prev = items[i - 1]!
|
||||
const curr = items[i]!
|
||||
expect(prev.priority).toBeGreaterThanOrEqual(curr.priority)
|
||||
expect(prev.signals!.urgency).toBeGreaterThanOrEqual(curr.signals!.urgency!)
|
||||
}
|
||||
})
|
||||
|
||||
test("priority values match severity levels", async () => {
|
||||
test("urgency values match severity levels", async () => {
|
||||
const source = new TflSource({ client: api })
|
||||
const items = await source.fetchItems(createContext())
|
||||
|
||||
const severityPriority: Record<string, number> = {
|
||||
const severityUrgency: Record<string, number> = {
|
||||
closure: 1.0,
|
||||
"major-delays": 0.8,
|
||||
"minor-delays": 0.6,
|
||||
}
|
||||
|
||||
for (const item of items) {
|
||||
expect(item.priority).toBe(severityPriority[item.data.severity]!)
|
||||
expect(item.signals!.urgency).toBe(severityUrgency[item.data.severity]!)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -316,9 +317,7 @@ describe("TflSource", () => {
|
||||
test("executeAction throws on invalid input", async () => {
|
||||
const source = new TflSource({ client: api })
|
||||
|
||||
await expect(
|
||||
source.executeAction("set-lines-of-interest", "not-an-array"),
|
||||
).rejects.toThrow()
|
||||
await expect(source.executeAction("set-lines-of-interest", "not-an-array")).rejects.toThrow()
|
||||
})
|
||||
|
||||
test("executeAction throws for unknown action", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ActionDefinition, Context, FeedSource } from "@aris/core"
|
||||
import type { ActionDefinition, Context, FeedItemSignals, FeedSource } from "@aris/core"
|
||||
|
||||
import { UnknownActionError, contextValue } from "@aris/core"
|
||||
import { TimeRelevance, UnknownActionError, contextValue } from "@aris/core"
|
||||
import { LocationKey } from "@aris/source-location"
|
||||
import { type } from "arktype"
|
||||
|
||||
@@ -18,12 +18,18 @@ import { TflApi, lineId } from "./tfl-api.ts"
|
||||
|
||||
const setLinesInput = lineId.array()
|
||||
|
||||
const SEVERITY_PRIORITY: Record<TflAlertSeverity, number> = {
|
||||
const SEVERITY_URGENCY: Record<TflAlertSeverity, number> = {
|
||||
closure: 1.0,
|
||||
"major-delays": 0.8,
|
||||
"minor-delays": 0.6,
|
||||
}
|
||||
|
||||
const SEVERITY_TIME_RELEVANCE: Record<TflAlertSeverity, TimeRelevance> = {
|
||||
closure: TimeRelevance.Imminent,
|
||||
"major-delays": TimeRelevance.Imminent,
|
||||
"minor-delays": TimeRelevance.Upcoming,
|
||||
}
|
||||
|
||||
/**
|
||||
* A FeedSource that provides TfL (Transport for London) service alerts.
|
||||
*
|
||||
@@ -137,19 +143,26 @@ export class TflSource implements FeedSource<TflAlertFeedItem> {
|
||||
closestStationDistance,
|
||||
}
|
||||
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: SEVERITY_URGENCY[status.severity],
|
||||
timeRelevance: SEVERITY_TIME_RELEVANCE[status.severity],
|
||||
}
|
||||
|
||||
return {
|
||||
id: `tfl-alert-${status.lineId}-${status.severity}`,
|
||||
type: "tfl-alert",
|
||||
priority: SEVERITY_PRIORITY[status.severity],
|
||||
timestamp: context.time,
|
||||
data,
|
||||
signals,
|
||||
}
|
||||
})
|
||||
|
||||
// Sort by severity (desc), then by proximity (asc) if location available
|
||||
// Sort by urgency (desc), then by proximity (asc) if location available
|
||||
items.sort((a, b) => {
|
||||
if (b.priority !== a.priority) {
|
||||
return b.priority - a.priority
|
||||
const aUrgency = a.signals?.urgency ?? 0
|
||||
const bUrgency = b.signals?.urgency ?? 0
|
||||
if (bUrgency !== aUrgency) {
|
||||
return bUrgency - aUrgency
|
||||
}
|
||||
if (a.data.closestStationDistance !== null && b.data.closestStationDistance !== null) {
|
||||
return a.data.closestStationDistance - b.data.closestStationDistance
|
||||
|
||||
@@ -145,20 +145,22 @@ describe("WeatherSource", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("assigns priority based on weather conditions", async () => {
|
||||
test("assigns signals based on weather conditions", async () => {
|
||||
const source = new WeatherSource({ client: mockClient })
|
||||
const context = createMockContext({ lat: 37.7749, lng: -122.4194 })
|
||||
|
||||
const items = await source.fetchItems(context)
|
||||
|
||||
for (const item of items) {
|
||||
expect(item.priority).toBeGreaterThanOrEqual(0)
|
||||
expect(item.priority).toBeLessThanOrEqual(1)
|
||||
expect(item.signals).toBeDefined()
|
||||
expect(item.signals!.urgency).toBeGreaterThanOrEqual(0)
|
||||
expect(item.signals!.urgency).toBeLessThanOrEqual(1)
|
||||
expect(item.signals!.timeRelevance).toBeDefined()
|
||||
}
|
||||
|
||||
const currentItem = items.find((i) => i.type === WeatherFeedItemType.current)
|
||||
expect(currentItem).toBeDefined()
|
||||
expect(currentItem!.priority).toBeGreaterThanOrEqual(0.5)
|
||||
expect(currentItem!.signals!.urgency).toBeGreaterThanOrEqual(0.5)
|
||||
})
|
||||
|
||||
test("generates unique IDs for each item", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ActionDefinition, Context, FeedSource } from "@aris/core"
|
||||
import type { ActionDefinition, Context, FeedItemSignals, FeedSource } from "@aris/core"
|
||||
|
||||
import { UnknownActionError, contextValue } from "@aris/core"
|
||||
import { TimeRelevance, UnknownActionError, contextValue } from "@aris/core"
|
||||
import { LocationKey } from "@aris/source-location"
|
||||
|
||||
import { WeatherFeedItemType, type WeatherFeedItem } from "./feed-items"
|
||||
@@ -38,7 +38,7 @@ export interface WeatherSourceOptions {
|
||||
const DEFAULT_HOURLY_LIMIT = 12
|
||||
const DEFAULT_DAILY_LIMIT = 7
|
||||
|
||||
const BASE_PRIORITY = {
|
||||
const BASE_URGENCY = {
|
||||
current: 0.5,
|
||||
hourly: 0.3,
|
||||
daily: 0.2,
|
||||
@@ -199,17 +199,17 @@ export class WeatherSource implements FeedSource<WeatherFeedItem> {
|
||||
}
|
||||
}
|
||||
|
||||
function adjustPriorityForCondition(basePriority: number, conditionCode: ConditionCode): number {
|
||||
function adjustUrgencyForCondition(baseUrgency: number, conditionCode: ConditionCode): number {
|
||||
if (SEVERE_CONDITIONS.has(conditionCode)) {
|
||||
return Math.min(1, basePriority + 0.3)
|
||||
return Math.min(1, baseUrgency + 0.3)
|
||||
}
|
||||
if (MODERATE_CONDITIONS.has(conditionCode)) {
|
||||
return Math.min(1, basePriority + 0.15)
|
||||
return Math.min(1, baseUrgency + 0.15)
|
||||
}
|
||||
return basePriority
|
||||
return baseUrgency
|
||||
}
|
||||
|
||||
function adjustPriorityForAlertSeverity(severity: Severity): number {
|
||||
function adjustUrgencyForAlertSeverity(severity: Severity): number {
|
||||
switch (severity) {
|
||||
case "extreme":
|
||||
return 1
|
||||
@@ -218,7 +218,29 @@ function adjustPriorityForAlertSeverity(severity: Severity): number {
|
||||
case "moderate":
|
||||
return 0.75
|
||||
case "minor":
|
||||
return BASE_PRIORITY.alert
|
||||
return BASE_URGENCY.alert
|
||||
}
|
||||
}
|
||||
|
||||
function timeRelevanceForCondition(conditionCode: ConditionCode): TimeRelevance {
|
||||
if (SEVERE_CONDITIONS.has(conditionCode)) {
|
||||
return TimeRelevance.Imminent
|
||||
}
|
||||
if (MODERATE_CONDITIONS.has(conditionCode)) {
|
||||
return TimeRelevance.Upcoming
|
||||
}
|
||||
return TimeRelevance.Ambient
|
||||
}
|
||||
|
||||
function timeRelevanceForAlertSeverity(severity: Severity): TimeRelevance {
|
||||
switch (severity) {
|
||||
case "extreme":
|
||||
case "severe":
|
||||
return TimeRelevance.Imminent
|
||||
case "moderate":
|
||||
return TimeRelevance.Upcoming
|
||||
case "minor":
|
||||
return TimeRelevance.Ambient
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,12 +284,14 @@ function createCurrentWeatherFeedItem(
|
||||
timestamp: Date,
|
||||
units: Units,
|
||||
): WeatherFeedItem {
|
||||
const priority = adjustPriorityForCondition(BASE_PRIORITY.current, current.conditionCode)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForCondition(BASE_URGENCY.current, current.conditionCode),
|
||||
timeRelevance: timeRelevanceForCondition(current.conditionCode),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-current-${timestamp.getTime()}`,
|
||||
type: WeatherFeedItemType.current,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
conditionCode: current.conditionCode,
|
||||
@@ -284,6 +308,7 @@ function createCurrentWeatherFeedItem(
|
||||
windGust: convertSpeed(current.windGust, units),
|
||||
windSpeed: convertSpeed(current.windSpeed, units),
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,12 +318,14 @@ function createHourlyWeatherFeedItem(
|
||||
timestamp: Date,
|
||||
units: Units,
|
||||
): WeatherFeedItem {
|
||||
const priority = adjustPriorityForCondition(BASE_PRIORITY.hourly, hourly.conditionCode)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForCondition(BASE_URGENCY.hourly, hourly.conditionCode),
|
||||
timeRelevance: timeRelevanceForCondition(hourly.conditionCode),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-hourly-${timestamp.getTime()}-${index}`,
|
||||
type: WeatherFeedItemType.hourly,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
forecastTime: new Date(hourly.forecastStart),
|
||||
@@ -315,6 +342,7 @@ function createHourlyWeatherFeedItem(
|
||||
windGust: convertSpeed(hourly.windGust, units),
|
||||
windSpeed: convertSpeed(hourly.windSpeed, units),
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,12 +352,14 @@ function createDailyWeatherFeedItem(
|
||||
timestamp: Date,
|
||||
units: Units,
|
||||
): WeatherFeedItem {
|
||||
const priority = adjustPriorityForCondition(BASE_PRIORITY.daily, daily.conditionCode)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForCondition(BASE_URGENCY.daily, daily.conditionCode),
|
||||
timeRelevance: timeRelevanceForCondition(daily.conditionCode),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-daily-${timestamp.getTime()}-${index}`,
|
||||
type: WeatherFeedItemType.daily,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
forecastDate: new Date(daily.forecastStart),
|
||||
@@ -344,16 +374,19 @@ function createDailyWeatherFeedItem(
|
||||
temperatureMax: convertTemperature(daily.temperatureMax, units),
|
||||
temperatureMin: convertTemperature(daily.temperatureMin, units),
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
function createWeatherAlertFeedItem(alert: WeatherAlert, timestamp: Date): WeatherFeedItem {
|
||||
const priority = adjustPriorityForAlertSeverity(alert.severity)
|
||||
const signals: FeedItemSignals = {
|
||||
urgency: adjustUrgencyForAlertSeverity(alert.severity),
|
||||
timeRelevance: timeRelevanceForAlertSeverity(alert.severity),
|
||||
}
|
||||
|
||||
return {
|
||||
id: `weather-alert-${alert.id}`,
|
||||
type: WeatherFeedItemType.alert,
|
||||
priority,
|
||||
timestamp,
|
||||
data: {
|
||||
alertId: alert.id,
|
||||
@@ -367,5 +400,6 @@ function createWeatherAlertFeedItem(alert: WeatherAlert, timestamp: Date): Weath
|
||||
source: alert.source,
|
||||
urgency: alert.urgency,
|
||||
},
|
||||
signals,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user