@avelonjs/core 0.8.4 → 0.8.6

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
 
@@ -469,7 +473,7 @@ The table lists every public export. Capability surface interfaces describe meth
469
473
  | `InProcessEventDispatcher` | `class InProcessEventDispatcher` | Default `EventDispatcher` implementation. |
470
474
  | `KernelMiddleware` | `type KernelMiddleware` | Named middleware callback. |
471
475
  | `MaybeNamed` | `type MaybeNamed<TDriver>` | Single driver or named registry. |
472
- | `MemoryJobBoard` | `class MemoryJobBoard` | Process-local queue and failed table. |
476
+ | `MemoryJobBoard` | `class MemoryJobBoard` | Process-local queue and failed table. `take` is FIFO. |
473
477
  | `NamedDrivers` | `interface NamedDrivers<TDriver>` | `{ default, instances/mailers/disks/connections }` registry. |
474
478
  | `PolicyAbilities` | `type PolicyAbilities` | Ability name to handler map. |
475
479
  | `PolicyHandler` | `type PolicyHandler` | Policy callback receiving actor and resource. |
@@ -498,7 +502,7 @@ The table lists every public export. Capability surface interfaces describe meth
498
502
  | `detectWardDrift` | `(predicate, fixtures) => WardDrift[]` | Client-side evaluation mismatches. |
499
503
  | `disks` | `const disks` | Storage facade with named `disk()` resolution. |
500
504
  | `eventDispatcher` | `() => InProcessEventDispatcher` | Process-wide dispatcher instance. |
501
- | `evaluatePredicate` | `(predicate, row) => boolean \| null` | SQL three-valued client evaluation. |
505
+ | `evaluatePredicate` | `(predicate, row) => boolean \| null` | SQL three-valued client evaluation. LIKE honors backslash escapes. |
502
506
  | `finishResponse` | `() => Promise<void>` | Flushes `after` listeners and errands. |
503
507
  | `flushAfterErrands` | `() => Promise<void>` | Runs errands scheduled with `delivery: 'after'`. |
504
508
  | `getConfig` | `() => AvelonConfig` | Active configuration, or `Unavailable`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avelonjs/core",
3
- "version": "0.8.4",
3
+ "version": "0.8.6",
4
4
  "private": false,
5
5
  "description": "Frozen TypeScript contracts, errors, and capability types shared by Avelon packages.",
6
6
  "license": "MIT",
@@ -45,7 +45,7 @@ class JsonEventSerializer implements EventSerializer {
45
45
  }
46
46
 
47
47
  function matchesPattern(pattern: string, name: string): boolean {
48
- const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*')
48
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*')
49
49
  return new RegExp(`^${escaped}$`).test(name)
50
50
  }
51
51
 
@@ -42,12 +42,16 @@ export class MemoryJobBoard {
42
42
  take(
43
43
  options: { queue?: string; limit?: number; now?: number; name?: string } = {},
44
44
  ): QueueReceipt[] {
45
+ if (options.limit !== undefined && (!Number.isInteger(options.limit) || options.limit < 0)) {
46
+ throw new Invalid('Queue take limit must be a non-negative integer.', {
47
+ metadata: { fields: { limit: ['Expected a non-negative integer.'] } },
48
+ })
49
+ }
45
50
  const now = options.now ?? Date.now()
46
51
  const selected = [...this.#pending.values()]
47
52
  .filter((entry) => entry.availableAt <= now)
48
53
  .filter((entry) => options.queue === undefined || entry.job.queue === options.queue)
49
54
  .filter((entry) => options.name === undefined || entry.job.name === options.name)
50
- .sort((left, right) => left.id.localeCompare(right.id))
51
55
  .slice(0, options.limit ?? Number.POSITIVE_INFINITY)
52
56
 
53
57
  return selected.map((entry) => {
@@ -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'
@@ -160,10 +160,26 @@ function or(values: readonly TruthValue[]): TruthValue {
160
160
  return false
161
161
  }
162
162
 
163
+ function escapeRegex(char: string): string {
164
+ return char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
165
+ }
166
+
167
+ /** SQL LIKE: `%` and `_` are wildcards, and `\` escapes the next character. */
163
168
  function like(left: unknown, right: unknown, insensitive: boolean): boolean {
164
169
  if (typeof left !== 'string' || typeof right !== 'string') return false
165
- const escaped = right.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
166
- const pattern = `^${escaped.replaceAll('%', '.*').replaceAll('_', '.')}$`
170
+ let pattern = '^'
171
+ for (let index = 0; index < right.length; index += 1) {
172
+ const char = right[index] ?? ''
173
+ if (char === '\\' && index + 1 < right.length) {
174
+ pattern += escapeRegex(right[index + 1] ?? '')
175
+ index += 1
176
+ continue
177
+ }
178
+ if (char === '%') pattern += '[\\s\\S]*'
179
+ else if (char === '_') pattern += '[\\s\\S]'
180
+ else pattern += escapeRegex(char)
181
+ }
182
+ pattern += '$'
167
183
  return new RegExp(pattern, insensitive ? 'i' : undefined).test(left)
168
184
  }
169
185