@fougere/core 0.3.0-alpha.0 → 0.4.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +1 -1
  2. package/dist/boot/HandlerFacade.js +2 -2
  3. package/dist/boot/HandlerFacade.js.map +1 -1
  4. package/dist/boot/apply.d.ts.map +1 -1
  5. package/dist/boot/apply.js +2 -12
  6. package/dist/boot/apply.js.map +1 -1
  7. package/dist/boot/binding.js +4 -4
  8. package/dist/boot/binding.js.map +1 -1
  9. package/dist/boot/boot.d.ts +1 -1
  10. package/dist/boot/boot.d.ts.map +1 -1
  11. package/dist/boot/bootstrap.d.ts.map +1 -1
  12. package/dist/boot/bootstrap.js +14 -13
  13. package/dist/boot/bootstrap.js.map +1 -1
  14. package/dist/boot/frame.d.ts +1 -1
  15. package/dist/boot/frame.d.ts.map +1 -1
  16. package/dist/boot/frame.js +5 -14
  17. package/dist/boot/frame.js.map +1 -1
  18. package/dist/boot/ownership.d.ts.map +1 -1
  19. package/dist/boot/ownership.js +5 -5
  20. package/dist/boot/ownership.js.map +1 -1
  21. package/dist/boot/remote.d.ts.map +1 -1
  22. package/dist/boot/remote.js +2 -2
  23. package/dist/boot/remote.js.map +1 -1
  24. package/dist/boot/together.d.ts.map +1 -1
  25. package/dist/boot/together.js +6 -6
  26. package/dist/boot/together.js.map +1 -1
  27. package/dist/boot/types.d.ts +2 -2
  28. package/dist/boot/types.d.ts.map +1 -1
  29. package/dist/contract.d.ts +1 -1
  30. package/dist/contract.d.ts.map +1 -1
  31. package/dist/contract.js +3 -3
  32. package/dist/contract.js.map +1 -1
  33. package/dist/dispatch/InFlight.d.ts.map +1 -1
  34. package/dist/dispatch/InFlight.js.map +1 -1
  35. package/dist/dispatch/InputValidator.d.ts.map +1 -1
  36. package/dist/dispatch/InputValidator.js +3 -2
  37. package/dist/dispatch/InputValidator.js.map +1 -1
  38. package/dist/dispatch/OutputProjector.js +2 -2
  39. package/dist/dispatch/OutputProjector.js.map +1 -1
  40. package/dist/dispatch/StorageGuard.d.ts.map +1 -1
  41. package/dist/dispatch/StorageGuard.js +2 -2
  42. package/dist/dispatch/StorageGuard.js.map +1 -1
  43. package/dist/effective-operation.js +4 -5
  44. package/dist/effective-operation.js.map +1 -1
  45. package/dist/emit.d.ts +2 -2
  46. package/dist/emit.d.ts.map +1 -1
  47. package/dist/emit.js +2 -2
  48. package/dist/emit.js.map +1 -1
  49. package/dist/identity.js +1 -1
  50. package/dist/identity.js.map +1 -1
  51. package/dist/imports.d.ts +1 -1
  52. package/dist/imports.d.ts.map +1 -1
  53. package/dist/imports.js.map +1 -1
  54. package/dist/orm.d.ts.map +1 -1
  55. package/dist/orm.js +4 -4
  56. package/dist/orm.js.map +1 -1
  57. package/dist/prefab/collector.js +2 -2
  58. package/dist/prefab/collector.js.map +1 -1
  59. package/dist/prefab/mirror.d.ts.map +1 -1
  60. package/dist/prefab/mirror.js +2 -2
  61. package/dist/prefab/mirror.js.map +1 -1
  62. package/dist/prefab/presenter.d.ts.map +1 -1
  63. package/dist/prefab/presenter.js +2 -2
  64. package/dist/prefab/presenter.js.map +1 -1
  65. package/dist/prefab/repository.d.ts.map +1 -1
  66. package/dist/prefab/repository.js +2 -2
  67. package/dist/prefab/repository.js.map +1 -1
  68. package/dist/scan/emit.d.ts.map +1 -1
  69. package/dist/scan/emit.js +3 -2
  70. package/dist/scan/emit.js.map +1 -1
  71. package/dist/scan/handler-parser.d.ts +2 -0
  72. package/dist/scan/handler-parser.d.ts.map +1 -1
  73. package/dist/scan/handler-parser.js +52 -12
  74. package/dist/scan/handler-parser.js.map +1 -1
  75. package/dist/scan/scanner.d.ts.map +1 -1
  76. package/dist/scan/scanner.js +37 -10
  77. package/dist/scan/scanner.js.map +1 -1
  78. package/dist/verify.js +2 -2
  79. package/dist/verify.js.map +1 -1
  80. package/dist/wire/call.d.ts +7 -7
  81. package/dist/wire/call.d.ts.map +1 -1
  82. package/dist/wire/call.js +6 -6
  83. package/dist/wire/call.js.map +1 -1
  84. package/package.json +6 -4
  85. package/src/boot/AppLifecycle.ts +50 -0
  86. package/src/boot/Emissions.ts +263 -0
  87. package/src/boot/HandlerFacade.ts +242 -0
  88. package/src/boot/Lifecycle.ts +3 -0
  89. package/src/boot/ambient-port.ts +41 -0
  90. package/src/boot/ambient.als.ts +43 -0
  91. package/src/boot/ambient.queue.ts +75 -0
  92. package/src/boot/apply.ts +47 -0
  93. package/src/boot/auth.ts +55 -0
  94. package/src/boot/binding.ts +182 -0
  95. package/src/boot/boot.ts +125 -0
  96. package/src/boot/bootstrap.ts +839 -0
  97. package/src/boot/frame.ts +210 -0
  98. package/src/boot/ownership.ts +140 -0
  99. package/src/boot/ports.ts +66 -0
  100. package/src/boot/remote.ts +179 -0
  101. package/src/boot/seed.ts +158 -0
  102. package/src/boot/together.ts +215 -0
  103. package/src/boot/types.ts +261 -0
  104. package/src/builtins/config.ts +19 -0
  105. package/src/builtins/logger.ts +175 -0
  106. package/src/config-loader.ts +146 -0
  107. package/src/contract/Call.ts +18 -0
  108. package/src/contract/Invocation.ts +72 -0
  109. package/src/contract/RouteAddress.ts +49 -0
  110. package/src/contract.ts +74 -0
  111. package/src/crypto/encoding.ts +59 -0
  112. package/src/crypto/node.ts +30 -0
  113. package/src/crypto/port.ts +45 -0
  114. package/src/crypto/webcrypto.ts +55 -0
  115. package/src/define.ts +10 -0
  116. package/src/dispatch/ArgumentResolver.ts +17 -0
  117. package/src/dispatch/ArrayResult.ts +10 -0
  118. package/src/dispatch/DispatchEvent.ts +38 -0
  119. package/src/dispatch/DispatchLifecycle.ts +23 -0
  120. package/src/dispatch/DispatchPort.ts +6 -0
  121. package/src/dispatch/Dispatcher.ts +48 -0
  122. package/src/dispatch/InFlight.ts +49 -0
  123. package/src/dispatch/InputValidator.ts +28 -0
  124. package/src/dispatch/LocalRoutePolicy.ts +34 -0
  125. package/src/dispatch/OperationExecutor.ts +60 -0
  126. package/src/dispatch/OperationRoute.ts +18 -0
  127. package/src/dispatch/OutputProjector.ts +32 -0
  128. package/src/dispatch/OutputView.ts +9 -0
  129. package/src/dispatch/PresenterArgumentResolver.ts +25 -0
  130. package/src/dispatch/PresenterExecutor.ts +55 -0
  131. package/src/dispatch/RemoteRouteResolver.ts +21 -0
  132. package/src/dispatch/Route.ts +11 -0
  133. package/src/dispatch/RouteNotFoundError.ts +29 -0
  134. package/src/dispatch/RoutePolicy.ts +8 -0
  135. package/src/dispatch/RouteRegistry.ts +73 -0
  136. package/src/dispatch/RouteResolver.ts +7 -0
  137. package/src/dispatch/StorageGuard.ts +71 -0
  138. package/src/effective-operation.ts +597 -0
  139. package/src/emit.ts +90 -0
  140. package/src/entry/DynamicFacade.ts +28 -0
  141. package/src/entry/FacadeEntry.ts +32 -0
  142. package/src/entry/TransportEntry.ts +30 -0
  143. package/src/frond-config.ts +138 -0
  144. package/src/graph.ts +180 -0
  145. package/src/identity-keys.ts +43 -0
  146. package/src/identity.ts +235 -0
  147. package/src/imports.ts +123 -0
  148. package/src/index.ts +106 -0
  149. package/src/loader.ts +41 -0
  150. package/src/node.ts +28 -0
  151. package/src/orm.ts +252 -0
  152. package/src/prefab/collector.ts +36 -0
  153. package/src/prefab/crud.ts +188 -0
  154. package/src/prefab/mirror.ts +122 -0
  155. package/src/prefab/prefab.ts +46 -0
  156. package/src/prefab/presenter.ts +63 -0
  157. package/src/prefab/repository.ts +170 -0
  158. package/src/scan/Fronds.ts +73 -0
  159. package/src/scan/conventions.ts +122 -0
  160. package/src/scan/emit.ts +231 -0
  161. package/src/scan/frond.ts +235 -0
  162. package/src/scan/handler-parser.ts +818 -0
  163. package/src/scan/scan-cache.ts +115 -0
  164. package/src/scan/scanner.ts +758 -0
  165. package/src/verify.ts +193 -0
  166. package/src/wire/call.ts +369 -0
  167. package/src/wire/errors.ts +124 -0
  168. package/src/wire/http-error.ts +77 -0
  169. package/src/wire/invocation.ts +10 -0
  170. package/src/wire/loggerMiddleware.ts +29 -0
  171. package/src/wire/middleware.ts +47 -0
  172. package/src/wire/operation.ts +258 -0
  173. package/dist/boot/egress.d.ts +0 -8
  174. package/dist/boot/egress.d.ts.map +0 -1
  175. package/dist/boot/egress.js +0 -11
  176. package/dist/boot/egress.js.map +0 -1
@@ -0,0 +1,242 @@
1
+ import { lowerFirst, type Fields } from '@fougere/schema';
2
+ import type { Container } from '@fougere/container';
3
+ import type { AppMiddleware } from '../wire/middleware.js';
4
+ import type { CollectorResolver } from './binding.js';
5
+ import { collectorKeyOf } from '../prefab/collector.js';
6
+ import { presenterKeyOf } from '../prefab/presenter.js';
7
+ import { repositoryKeyOf } from '../prefab/repository.js';
8
+ import { targetOf } from '../prefab/prefab.js';
9
+ import type { OperationContract, OperationsMap } from '../wire/operation.js';
10
+ import type { EffectiveOperation, EffectiveOperationsMap } from '../effective-operation.js';
11
+ import type { InvocationContext } from '../wire/invocation.js';
12
+ import type { Emissions } from './Emissions.js';
13
+ import type { Logger } from '../builtins/logger.js';
14
+ import type { EntityEntry, HandlerEntry, PresenterEntry } from '../scan/frond.js';
15
+ import { InputValidator } from '../dispatch/InputValidator.js';
16
+ import { ArgumentResolver } from '../dispatch/ArgumentResolver.js';
17
+ import { OperationExecutor } from '../dispatch/OperationExecutor.js';
18
+ import { OutputProjector } from '../dispatch/OutputProjector.js';
19
+ import { OutputView } from '../dispatch/OutputView.js';
20
+ import { PresenterExecutor } from '../dispatch/PresenterExecutor.js';
21
+ import { PresenterArgumentResolver } from '../dispatch/PresenterArgumentResolver.js';
22
+
23
+ /** What this door is about: a handler, the entity behind it when there is one, and where it resolves. */
24
+ export interface Doorway {
25
+ handler: HandlerEntry;
26
+ /** Handlers in the owning frond, used to realize a resolved implementation override. */
27
+ handlers: readonly HandlerEntry[];
28
+ /** The canonical operation table resolved before boot performs any side effect. */
29
+ operations: EffectiveOperationsMap;
30
+ /** The subject — absent is ordinary: a health check owns no row. */
31
+ entity: EntityEntry | undefined;
32
+ /** The scope the handler and its collectors resolve in — a surface gets its own. */
33
+ scope: Container;
34
+ /** The container key this door answers under. */
35
+ key: string;
36
+ }
37
+
38
+ /** What the frond and the boot supply to every door alike. */
39
+ export interface Wiring {
40
+ /** The frond this door belongs to — travels on every OperationContext. */
41
+ frond: string;
42
+ /** The frond's own scope — where presenters live, whatever sub-scope the door uses. */
43
+ frondScope: Container;
44
+ log: Logger;
45
+ /** Entity names this frond has a collector for. */
46
+ collectors: Set<string>;
47
+ presenters: Map<string, PresenterEntry>;
48
+ /** The middlewares that apply to an address, read at call time and never at boot. */
49
+ middlewaresFor: (address: string) => AppMiddleware[];
50
+ emissions: Emissions;
51
+ }
52
+
53
+ /** Adapts one handler door to executable operations. */
54
+ export class HandlerFacade {
55
+ /** Rich operation facts shared with check, explain and adapters. */
56
+ readonly effectiveOperations: EffectiveOperationsMap;
57
+ /** Contracts served by this door. */
58
+ readonly contracts: OperationsMap;
59
+
60
+ /** The callable surface: op name → the function a caller reaches. */
61
+ readonly ops: Record<string, Function> = {};
62
+
63
+ private readonly cachedViews = new Map<string, OutputView>();
64
+ private instance: any;
65
+ private readonly implementationKeys = new Map<string, string>();
66
+ private readonly implementationInstances = new Map<string, any>();
67
+ private readonly inputValidator = new InputValidator();
68
+ private readonly argumentResolver = new ArgumentResolver(
69
+ (typeName) => this.collectorResolver(typeName),
70
+ );
71
+ private readonly presenterArguments: PresenterArgumentResolver;
72
+
73
+ constructor(private readonly door: Doorway, private readonly wiring: Wiring) {
74
+ const { handler, entity } = door;
75
+ this.presenterArguments = new PresenterArgumentResolver(
76
+ this.argumentResolver,
77
+ wiring.collectors,
78
+ );
79
+ this.refuseCrudWithoutRepository(handler);
80
+
81
+ door.scope.register(this.handlerKey, handler.ctor, { deps: this.depsOf(handler) });
82
+
83
+ this.effectiveOperations = door.operations;
84
+ this.contracts = new Map(
85
+ [...door.operations].map(([name, operation]) => [name, operation as OperationContract] as const),
86
+ );
87
+ handler.operations = this.contracts;
88
+
89
+ // Register model-selected implementations in the same execution scope.
90
+ for (const [name, operation] of door.operations) {
91
+ if (this.isBaseImplementation(operation)) continue;
92
+ const implementation = this.implementationHandler(name);
93
+ this.refuseCrudWithoutRepository(implementation);
94
+ const key = `${this.handlerKey}:implementation:${operation.implementation.className}`;
95
+ if (!this.implementationKeys.has(operation.implementation.className)) {
96
+ door.scope.register(key, implementation.ctor, { deps: this.depsOf(implementation) });
97
+ this.implementationKeys.set(operation.implementation.className, key);
98
+ }
99
+ }
100
+
101
+ // Emissions use the same contracts and execution path as direct calls.
102
+ wiring.emissions.note(this.contracts, door.key);
103
+ // Only declared operations become callable façade members.
104
+ for (const op of this.contracts.keys()) this.ops[op] = this.wrap(op);
105
+
106
+ if (this.inheritsCrud(handler) && !entity) {
107
+ // An installed Crud subject may be absent from the local scan.
108
+ wiring.log.debug(`${handler.ctor.name} extends Crud() and no scanned entity is named `
109
+ + `'${this.subjectOf(handler)}' — installed entity, or a missing one: no ORM will be injected`);
110
+ }
111
+ }
112
+
113
+ /** Storage follows the Crud subject, which may differ from the door address. */
114
+ private subjectOf(handler: HandlerEntry): string {
115
+ const target = targetOf(handler.ctor);
116
+ return target?.name ? lowerFirst(target.name) : handler.address;
117
+ }
118
+
119
+ private inheritsCrud(handler: HandlerEntry): boolean {
120
+ const proto = handler.ctor.prototype;
121
+ return typeof proto?.list === 'function' && typeof proto?.findById === 'function';
122
+ }
123
+
124
+ private get handlerKey(): string {
125
+ return `_handler:${this.door.key}`;
126
+ }
127
+
128
+ private depsOf(handler: HandlerEntry): string[] {
129
+ const { deps } = handler;
130
+ if (deps.length > 0) return deps;
131
+ return this.inheritsCrud(handler) ? [repositoryKeyOf(this.subjectOf(handler))] : [];
132
+ }
133
+
134
+ /** A custom Crud constructor must explicitly receive its repository. */
135
+ private refuseCrudWithoutRepository(handler: HandlerEntry): void {
136
+ const repoTypeName = repositoryKeyOf(this.subjectOf(handler));
137
+ if (!this.inheritsCrud(handler) || handler.deps.length === 0 || handler.deps.includes(repoTypeName)) return;
138
+ throw new Error(
139
+ `${handler.ctor.name} extends Crud() and declares a constructor, so its storage is no ` +
140
+ `longer injected for it — but it does not take any.\n` +
141
+ ` Add it and hand it to super():\n` +
142
+ ` constructor(repo: ${repoTypeName}, …) { super(repo); }`,
143
+ );
144
+ }
145
+
146
+ /** Resolve and cache the output view declared for one operation. */
147
+ private viewOf(op: string): OutputView {
148
+ const known = this.cachedViews.get(op);
149
+ if (known) return known;
150
+
151
+ const operation = this.effectiveOperations.get(op);
152
+ const schema = operation?.output as { getFields?: () => Fields } | undefined;
153
+ const resolved = new OutputView(
154
+ typeof schema?.getFields === 'function' ? schema.getFields() : {},
155
+ operation?.outputClosed ?? false,
156
+ );
157
+ this.cachedViews.set(op, resolved);
158
+ return resolved;
159
+ }
160
+
161
+ private collectorResolver = (typeName: string): CollectorResolver | undefined => {
162
+ try { return this.door.scope.resolve(collectorKeyOf(typeName)) as CollectorResolver; }
163
+ catch { return undefined; }
164
+ };
165
+
166
+ /** The handler itself, resolved on first call — never at boot. */
167
+ private resolvedHandler(): any {
168
+ if (!this.instance) this.instance = this.door.scope.resolve(this.handlerKey);
169
+ return this.instance;
170
+ }
171
+
172
+ private isBaseImplementation(operation: EffectiveOperation): boolean {
173
+ return operation.implementation.className === this.door.handler.ctor.name
174
+ && operation.implementation.address === this.door.handler.address
175
+ && operation.implementation.filePath === this.door.handler.filePath;
176
+ }
177
+
178
+ /** The exact handler entry the pure model selected; no name-only retry or fallback. */
179
+ private implementationHandler(operationName: string): HandlerEntry {
180
+ const operation = this.effectiveOperations.get(operationName)!;
181
+ const matches = this.door.handlers.filter((handler) =>
182
+ handler.ctor.name === operation.implementation.className
183
+ && handler.address === operation.implementation.address
184
+ && handler.filePath === operation.implementation.filePath);
185
+ if (matches.length !== 1) {
186
+ throw new Error(
187
+ `EffectiveOperation '${operation.id}' names ${operation.implementation.className}.`
188
+ + `${operation.implementation.method}, but boot found ${matches.length} matching handlers.`,
189
+ );
190
+ }
191
+ return matches[0]!;
192
+ }
193
+
194
+ private resolvedImplementation(operationName: string): { instance: any; method: string } {
195
+ const operation = this.effectiveOperations.get(operationName)!;
196
+ if (this.isBaseImplementation(operation)) {
197
+ return { instance: this.resolvedHandler(), method: operation.implementation.method };
198
+ }
199
+
200
+ const className = operation.implementation.className;
201
+ const key = this.implementationKeys.get(className);
202
+ if (!key) throw new Error(`No registered implementation for EffectiveOperation '${operation.id}'.`);
203
+ let instance = this.implementationInstances.get(key);
204
+ if (!instance) {
205
+ instance = this.door.scope.resolve(key);
206
+ this.implementationInstances.set(key, instance);
207
+ }
208
+ return { instance, method: operation.implementation.method };
209
+ }
210
+
211
+ private wrap(op: string): (invocation?: InvocationContext) => Promise<unknown> {
212
+ const address = this.door.handler.address;
213
+ const contract = this.contracts.get(op);
214
+ const view = this.viewOf(op);
215
+ const presenter = this.wiring.presenters.get(address);
216
+ const executor = new OperationExecutor({
217
+ entity: address,
218
+ frond: this.wiring.frond,
219
+ operation: op,
220
+ contract,
221
+ middlewares: () => this.wiring.middlewaresFor(address),
222
+ validator: this.inputValidator,
223
+ arguments: this.argumentResolver,
224
+ invoke: async (args) => {
225
+ const implementation = this.resolvedImplementation(op);
226
+ return implementation.instance[implementation.method](...args);
227
+ },
228
+ projector: new OutputProjector(view),
229
+ ...(view.closed || !presenter ? {} : {
230
+ present: async (result: unknown, effective: InvocationContext) =>
231
+ new PresenterExecutor(
232
+ this.wiring.frondScope.resolve(presenterKeyOf(address)),
233
+ presenter.fields,
234
+ address,
235
+ op,
236
+ ).present(result, await this.presenterArguments.resolve(presenter, effective)),
237
+ }),
238
+ });
239
+
240
+ return (invocation) => executor.execute(invocation);
241
+ }
242
+ }
@@ -0,0 +1,3 @@
1
+ /** Compatibility module. Prefer AppLifecycle for the process-level lifecycle. */
2
+ export { AppLifecycle, AppLifecycle as Lifecycle, migrating } from './AppLifecycle.js';
3
+ export type { Extension } from './AppLifecycle.js';
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What a call needs to know about the call it is inside, and the two ways to answer it.
3
+ *
4
+ * One realization reads an async context (`ambient.als.ts`), the other cannot and waits
5
+ * its turn instead (`ambient.queue.ts`). `#ambient` in package.json picks one per runtime,
6
+ * so a bundle for a host without async context never names `node:async_hooks`.
7
+ */
8
+ export interface Ambient {
9
+ /** True when this runtime has no async context, and the boot says so. */
10
+ readonly degraded: boolean;
11
+
12
+ /**
13
+ * Run `fn` as the frame `key`. A frame opened inside another must not proceed.
14
+ *
15
+ * Measured on SQLite: a second transaction on the same connection WAITS for the first,
16
+ * so a nested frame hangs on one engine and returns when split across two.
17
+ */
18
+ enterFrame<R>(key: string, fn: () => Promise<R>): Promise<R>;
19
+
20
+ /**
21
+ * Settle before `fact` is dispatched: a fact announced inside a frame that then rolls
22
+ * back is a lie. Refuses when the caller's own frame can be told, waits when it cannot.
23
+ */
24
+ beforeAnnounce(fact: string): Promise<void>;
25
+
26
+ /**
27
+ * The facts already being announced up the stack, so a fact cannot cause itself.
28
+ *
29
+ * A CHAIN and not a depth: `A → B → D` and `A → C → D` is a diamond, perfectly legal,
30
+ * while `A → … → A` never ends. Empty where it cannot be followed.
31
+ *
32
+ * Detecting this at boot was the first idea and it was wrong: `Emit<G>` is a CONSTRUCTOR
33
+ * dependency, so it belongs to the handler and not to one of its methods. A handler that
34
+ * subscribes to `A` in one method and emits `G` from another would have been refused for
35
+ * a cycle it never walks.
36
+ */
37
+ currentChain(): readonly string[];
38
+
39
+ /** Run `fn` with `fact` appended to the emission chain. */
40
+ enterChain<R>(fact: string, fn: () => Promise<R>): Promise<R>;
41
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The realization that can tell whose frame is open: an async context.
3
+ *
4
+ * Chosen by `#ambient` wherever `node:async_hooks` exists — Node, Deno, Bun, and workerd
5
+ * with `nodejs_als`. Every refusal here is immediate and names its cause.
6
+ */
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import type { Ambient } from './ambient-port.js';
9
+
10
+ const frame = new AsyncLocalStorage<string>();
11
+ const chain = new AsyncLocalStorage<readonly string[]>();
12
+
13
+ export const ambient: Ambient = {
14
+ degraded: false,
15
+
16
+ enterFrame<R>(key: string, fn: () => Promise<R>): Promise<R> {
17
+ const held = frame.getStore();
18
+ if (held !== undefined) {
19
+ return Promise.reject(new Error(
20
+ `Together<[…]> (${key}) cannot be opened inside ${held}: on one engine the second `
21
+ + `transaction waits for the first and the call hangs. Two frames that must both hold `
22
+ + `are ONE frame — declare a single Together naming every member.`,
23
+ ));
24
+ }
25
+ return frame.run(key, fn);
26
+ },
27
+
28
+ beforeAnnounce(fact: string): Promise<void> {
29
+ const held = frame.getStore();
30
+ if (held === undefined) return Promise.resolve();
31
+ return Promise.reject(new Error(
32
+ `${fact} cannot be announced inside Together<[…]> (${held}): announcing is dispatch, `
33
+ + `so subscribers and the carrier would have it while these writes can still be taken `
34
+ + `back. Announce after run() returns, when it is true.`,
35
+ ));
36
+ },
37
+
38
+ currentChain: () => chain.getStore() ?? [],
39
+
40
+ enterChain<R>(fact: string, fn: () => Promise<R>): Promise<R> {
41
+ return chain.run([...(chain.getStore() ?? []), fact], fn);
42
+ },
43
+ };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The realization for a runtime with no async context: it cannot tell whose frame is
3
+ * open, so it never guesses — it waits its turn.
4
+ *
5
+ * Two consequences the boot reports rather than hides: frames run one at a time, and a
6
+ * frame opened inside another is not refused, it waits for itself and times out.
7
+ */
8
+ import type { Ambient } from './ambient-port.js';
9
+
10
+ /** What a nested frame waits before it is told what it did — the hang, measured, plus a name. */
11
+ const NESTED_TIMEOUT_MS = 5_000;
12
+
13
+ let busy: Promise<void> | undefined;
14
+ let holder: string | undefined;
15
+
16
+ const settled = () => undefined;
17
+
18
+ /** Resolves when `p` settles or `ms` elapses, whichever comes first, holding no timer after. */
19
+ function raceWith(p: Promise<void>, ms: number): Promise<void> {
20
+ return new Promise((resolve) => {
21
+ const timer = setTimeout(resolve, ms);
22
+ const clear = () => { clearTimeout(timer); resolve(); };
23
+ void p.then(clear, clear);
24
+ });
25
+ }
26
+
27
+ export const ambient: Ambient = {
28
+ degraded: true,
29
+
30
+ async enterFrame<R>(key: string, fn: () => Promise<R>): Promise<R> {
31
+ const deadline = Date.now() + NESTED_TIMEOUT_MS;
32
+ for (;;) {
33
+ // Nothing may await between this test and the reservation below, or two waiters
34
+ // woken in the same tick would both take the frame.
35
+ if (busy === undefined) break;
36
+ const left = deadline - Date.now();
37
+ if (left <= 0) {
38
+ throw new Error(
39
+ `Together<[…]> (${key}) waited ${NESTED_TIMEOUT_MS}ms for ${holder} and gave up. `
40
+ + `This runtime has no async context, so a frame opened inside another waits for `
41
+ + `itself instead of being refused. Two frames that must both hold are ONE frame — `
42
+ + `declare a single Together naming every member.`,
43
+ );
44
+ }
45
+ await raceWith(busy, left);
46
+ }
47
+ // Held BEFORE `fn` runs: the first thing a frame's body does may be to open another,
48
+ // and reserving on the returned promise would be one tick too late to see it.
49
+ let release = settled as () => void;
50
+ busy = new Promise<void>((resolve) => { release = resolve; });
51
+ holder = key;
52
+ try {
53
+ return await fn();
54
+ } finally {
55
+ busy = undefined;
56
+ holder = undefined;
57
+ release();
58
+ }
59
+ },
60
+
61
+ /**
62
+ * Waits rather than refuses: whose frame is open cannot be told here, and refusing on
63
+ * that would refuse an announcement made by an unrelated call.
64
+ */
65
+ async beforeAnnounce(_fact: string): Promise<void> {
66
+ while (busy) await raceWith(busy, NESTED_TIMEOUT_MS);
67
+ },
68
+
69
+ /** No chain can be followed here — an emission ring is not detected. Said at boot. */
70
+ currentChain: () => [],
71
+
72
+ enterChain<R>(_fact: string, fn: () => Promise<R>): Promise<R> {
73
+ return fn();
74
+ },
75
+ };
@@ -0,0 +1,47 @@
1
+ import type { FougereConfig } from '../config-loader.js';
2
+ import { setLogLevel, logLevel, envLevel } from '../builtins/logger.js';
3
+ import { dequal } from 'dequal';
4
+
5
+ export interface ConfigApplication {
6
+ /** What this call changed in the running process. */
7
+ applied: string[];
8
+ /** What differs from the config in force and did NOT take effect. */
9
+ pending: string[];
10
+ }
11
+
12
+ /**
13
+ * What a (re-)read config changes in a process that is already running.
14
+ *
15
+ * The rule it realizes, and the only one worth remembering: **a value that is
16
+ * CONSULTED can change under a running app; a value that was CONSUMED to build
17
+ * something cannot, without rebuilding what it built.** `logLevel` is consulted at
18
+ * every emission, so it moves. `db` opened a connection, `ports:` registered a class,
19
+ * the entities built façades — those are consumed, and this function reports them
20
+ * rather than pretending.
21
+ *
22
+ * The list of consulted keys is not declared anywhere: a key is consulted when this
23
+ * function does something with it, which is the only definition that cannot go stale.
24
+ */
25
+ export function applyConfig(next: FougereConfig, inForce?: FougereConfig): ConfigApplication {
26
+ const applied: string[] = [];
27
+ const pending: string[] = [];
28
+
29
+ // The CLI speaks through the environment, so it keeps winning over the file — read
30
+ // through `envLevel`, which is where the environment is already judged. Casting it
31
+ // here was a second reader that validated nothing: `FOUGERE_LOG_LEVEL=verbose` set
32
+ // the threshold to `undefined` and every log passed.
33
+ const wanted = envLevel() ?? next.logLevel ?? 'debug';
34
+ const before = logLevel();
35
+ if (wanted !== before) {
36
+ setLogLevel(wanted);
37
+ applied.push(`logLevel: ${before} → ${wanted}`);
38
+ }
39
+
40
+ for (const key of new Set([...Object.keys(next), ...Object.keys(inForce ?? {})])) {
41
+ if (key === 'logLevel' || !inForce) continue;
42
+ if (!dequal((next as Record<string, unknown>)[key], (inForce as Record<string, unknown>)[key])) {
43
+ pending.push(key);
44
+ }
45
+ }
46
+ return { applied, pending };
47
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * What an auth provider promises the boot, and what the boot hands it — the whole of
3
+ * the contract between core and an `@fougere/auth-*` package.
4
+ */
5
+ import type { SchemaView } from '@fougere/schema';
6
+ import type { EntityOrm, OrmFactory } from '../orm.js';
7
+
8
+ /**
9
+ * Lazy auth declaration written in fougere.config.ts.
10
+ *
11
+ * Each @fougere/auth-* package exports a factory (e.g. `betterAuth(opts)`) that
12
+ * returns this shape. The `create()` method is called once at boot with the
13
+ * resolved db + ormFactory, so the provider can wire its engine through Fougere.
14
+ */
15
+ export interface AuthConfig {
16
+ /** Build the runtime — invoked by createApp at boot with the resolved storage handles. */
17
+ create(ctx: AuthContext): AuthRuntime | Promise<AuthRuntime>;
18
+ /**
19
+ * Entities the provider will use. Optional metadata — useful for the core's
20
+ * future migration registry to know which tables auth needs.
21
+ */
22
+ entities?: Record<string, SchemaView>;
23
+ }
24
+
25
+ /**
26
+ * Context passed by the core to an auth provider's create() function.
27
+ * Provides the resources the provider needs to integrate with the app.
28
+ */
29
+ export interface AuthContext {
30
+ /** Storage handle (Kysely DB instance, Prisma client, etc.) — opaque to core. */
31
+ db: unknown;
32
+ /** Per-entity ORM factory — auth provider uses this to back its adapter. */
33
+ ormFactory: OrmFactory;
34
+ }
35
+
36
+ /**
37
+ * Runtime returned by an auth provider's create(config, ctx) function.
38
+ * The core mounts this on the App and the HTTP layer (Nuxt module / router) uses it.
39
+ */
40
+ export interface AuthRuntime {
41
+ /** Entities used by the provider, including any defaults it filled in. */
42
+ entities: Record<string, SchemaView>;
43
+ /**
44
+ * Per-entity ORMs the provider built for itself. Exposed so app code can
45
+ * query auth tables (e.g. list active sessions for a user) without rebuilding
46
+ * the same EntityOrm.
47
+ */
48
+ orms: Record<string, EntityOrm>;
49
+ /** Web Standard handler that processes /auth/* requests. */
50
+ handler: (request: Request) => Promise<Response>;
51
+ /** Programmatic API exposed by the provider (getSession, signOut, ...). */
52
+ api: Record<string, unknown>;
53
+ /** Effective mount path (echoes config.basePath or the provider's default). */
54
+ basePath: string;
55
+ }