@avelonjs/core 0.8.3 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -64,6 +64,10 @@ export const updatePost: QueryIR = {
64
64
 
65
65
  Adapters translate native requests and responses at three seams: mount, request conversion, and response conversion. Every mounted route delegates middleware, binding, validation mapping, controller dispatch, and exception mapping to `Kernel`. `HttpRequest.rawBody()` preserves signature-verification bytes, and streaming adapters accept `StreamResult`. A POST route exists whether the adapter uses a server action or an ordinary HTTP POST, and the adapter alone interprets an opaque view reference.
66
66
 
67
+ `createKernel({ resolveActor })` resolves the actor once per dispatch. The built-in `auth` middleware
68
+ requires that actor, and `can:*` uses the same actor as the controller. Register other middleware
69
+ aliases through `middleware`; an unknown alias returns a validation failure.
70
+
67
71
  ```ts
68
72
  import type { Adapter, Kernel, RouteManifest } from '@avelonjs/core'
69
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avelonjs/core",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "private": false,
5
5
  "description": "Frozen TypeScript contracts, errors, and capability types shared by Avelon packages.",
6
6
  "license": "MIT",
@@ -15,6 +15,7 @@ import { backoffSeconds, jobBoard } from './jobs'
15
15
  import { holdUntilCommit, isInTransaction } from './transaction'
16
16
 
17
17
  interface StoredRegistration {
18
+ id: string
18
19
  event?: EventConstructor
19
20
  pattern?: string
20
21
  listener: ListenerDefinition<Event>
@@ -37,7 +38,7 @@ class JsonEventSerializer implements EventSerializer {
37
38
 
38
39
  async deserialize(serialized: SerializedEvent): Promise<Event> {
39
40
  const ctor = this.#constructors.get(serialized.name)
40
- const event = ctor === undefined ? new Event() : Object.assign(new Event(), serialized.payload)
41
+ const event = Object.assign(new Event(), serialized.payload)
41
42
  if (ctor !== undefined) Object.setPrototypeOf(event, ctor.prototype)
42
43
  return event
43
44
  }
@@ -56,12 +57,12 @@ function isFalse(result: ListenerResult): result is false {
56
57
  export class InProcessEventDispatcher implements EventDispatcher {
57
58
  readonly #registrations: StoredRegistration[] = []
58
59
  readonly #after: Array<() => Promise<void>> = []
59
- readonly #serializer: JsonEventSerializer
60
+ readonly #serializer: EventSerializer
60
61
  #queue: QueueDriver | undefined
61
62
 
62
63
  constructor(options: { queue?: QueueDriver; serializer?: EventSerializer } = {}) {
63
64
  this.#queue = options.queue
64
- this.#serializer = new JsonEventSerializer()
65
+ this.#serializer = options.serializer ?? new JsonEventSerializer()
65
66
  }
66
67
 
67
68
  /** Wires a queue driver for `delivery: 'queued'` listeners. Omitting `queue` uses the memory board. */
@@ -78,15 +79,17 @@ export class InProcessEventDispatcher implements EventDispatcher {
78
79
  ): void {
79
80
  if (typeof event === 'string') {
80
81
  this.#registrations.push({
82
+ id: `${event}:${this.#registrations.length}`,
81
83
  pattern: event,
82
84
  listener: listeners as ListenerDefinition<Event>,
83
85
  })
84
86
  return
85
87
  }
86
- this.#serializer.register(event)
88
+ if (this.#serializer instanceof JsonEventSerializer) this.#serializer.register(event)
87
89
  const list = Array.isArray(listeners) ? listeners : [listeners]
88
90
  for (const listener of list) {
89
91
  this.#registrations.push({
92
+ id: `${event.name}:${this.#registrations.length}`,
90
93
  event,
91
94
  listener: listener as ListenerDefinition<Event>,
92
95
  })
@@ -243,10 +246,9 @@ export class InProcessEventDispatcher implements EventDispatcher {
243
246
  const event = await this.#serializer.deserialize(envelope.event)
244
247
  const registration = this.#registrations.find(
245
248
  (entry) =>
249
+ entry.id === envelope.listener &&
246
250
  entry.listener.delivery === 'queued' &&
247
- entry.listener.queue === envelope.queue &&
248
- (entry.event?.name === envelope.eventName ||
249
- (entry.pattern !== undefined && matchesPattern(entry.pattern, envelope.eventName))),
251
+ entry.listener.queue === envelope.queue,
250
252
  )
251
253
  if (registration === undefined || registration.listener.delivery !== 'queued') return
252
254
  await registration.listener.handle(event, {
@@ -270,7 +272,7 @@ export class InProcessEventDispatcher implements EventDispatcher {
270
272
  eventName: string
271
273
  } = {
272
274
  event: serialized,
273
- listener: entry.event?.name ?? entry.pattern ?? event.constructor.name,
275
+ listener: entry.id,
274
276
  queue,
275
277
  attempt: 0,
276
278
  availableAt: Date.now(),
@@ -47,13 +47,6 @@ export interface CreateKernelOptions {
47
47
  mapException?: (error: unknown) => KernelResult | undefined
48
48
  }
49
49
 
50
- function hasHeader(headers: Readonly<Record<string, string>>, name: string): boolean {
51
- const target = name.toLowerCase()
52
- return Object.entries(headers).some(
53
- ([key, value]) => key.toLowerCase() === target && value.length > 0,
54
- )
55
- }
56
-
57
50
  /**
58
51
  * Maps framework errors onto transport-neutral kernel results.
59
52
  *
@@ -161,28 +154,28 @@ async function runMiddleware(
161
154
  options: CreateKernelOptions,
162
155
  ): Promise<void> {
163
156
  for (const name of route.middleware) {
164
- const custom = options.middleware?.[name]
157
+ const custom =
158
+ options.middleware !== undefined && Object.hasOwn(options.middleware, name)
159
+ ? options.middleware[name]
160
+ : undefined
165
161
  if (custom !== undefined) {
166
162
  await custom(request, route)
167
163
  continue
168
164
  }
169
165
  if (name === 'auth') {
170
- const actor = options.resolveActor ? await options.resolveActor(request) : Gate.actor()
171
- const signedIn =
172
- actor !== null ||
173
- hasHeader(request.headers, 'authorization') ||
174
- hasHeader(request.headers, 'cookie')
175
- if (!signedIn) {
166
+ if (Gate.actor() === null) {
176
167
  throw new Unauthenticated('Authentication is required.', { metadata: { guard: 'auth' } })
177
168
  }
178
169
  continue
179
170
  }
180
171
  if (name.startsWith('can:')) {
181
172
  const ability = name.slice(4)
182
- const actor = options.resolveActor ? await options.resolveActor(request) : Gate.actor()
183
- await Gate.authorize(ability, 'Gate', actor)
173
+ await Gate.authorize(ability, 'Gate')
184
174
  continue
185
175
  }
176
+ throw new Invalid(`Unknown middleware '${name}'.`, {
177
+ metadata: { fields: { middleware: [`${name} is not registered.`] } },
178
+ })
186
179
  }
187
180
  }
188
181
 
@@ -24,7 +24,7 @@ function extractFields(error: unknown): Record<string, readonly string[]> {
24
24
  'issues' in error &&
25
25
  Array.isArray((error as { issues: unknown }).issues)
26
26
  ) {
27
- const fields: Record<string, string[]> = {}
27
+ const fields: Record<string, string[]> = Object.create(null)
28
28
  for (const issue of (error as { issues: Array<{ path?: unknown[]; message?: string }> })
29
29
  .issues) {
30
30
  const key = Array.isArray(issue.path) ? issue.path.map(String).join('.') || '_form' : '_form'
@@ -23,19 +23,20 @@ export async function runInTransaction<TResult>(
23
23
  callback: () => Promise<TResult>,
24
24
  ): Promise<TResult> {
25
25
  depth += 1
26
+ let result: TResult
26
27
  try {
27
- const result = await callback()
28
- depth -= 1
29
- if (depth === 0) {
30
- const tasks = held.splice(0, held.length)
31
- for (const task of tasks) await task()
32
- }
33
- return result
28
+ result = await callback()
34
29
  } catch (error) {
35
30
  depth -= 1
36
31
  if (depth === 0) held.length = 0
37
32
  throw error
38
33
  }
34
+ depth -= 1
35
+ if (depth === 0) {
36
+ const tasks = held.splice(0, held.length)
37
+ for (const task of tasks) await task()
38
+ }
39
+ return result
39
40
  }
40
41
 
41
42
  /** Clears transaction state. Intended for tests. */