@fougere/core 0.3.0-alpha.0 → 0.5.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 (243) hide show
  1. package/README.md +1 -1
  2. package/dist/boot/Emissions.js +1 -1
  3. package/dist/boot/Emissions.js.map +1 -1
  4. package/dist/boot/HandlerFacade.js +2 -2
  5. package/dist/boot/HandlerFacade.js.map +1 -1
  6. package/dist/boot/apply.d.ts.map +1 -1
  7. package/dist/boot/apply.js +2 -12
  8. package/dist/boot/apply.js.map +1 -1
  9. package/dist/boot/binding.d.ts +1 -1
  10. package/dist/boot/binding.d.ts.map +1 -1
  11. package/dist/boot/binding.js +4 -4
  12. package/dist/boot/binding.js.map +1 -1
  13. package/dist/boot/boot.d.ts +1 -1
  14. package/dist/boot/boot.d.ts.map +1 -1
  15. package/dist/boot/bootstrap.d.ts.map +1 -1
  16. package/dist/boot/bootstrap.js +26 -17
  17. package/dist/boot/bootstrap.js.map +1 -1
  18. package/dist/boot/frame.d.ts +1 -1
  19. package/dist/boot/frame.d.ts.map +1 -1
  20. package/dist/boot/frame.js +5 -14
  21. package/dist/boot/frame.js.map +1 -1
  22. package/dist/boot/hosted.d.ts +29 -0
  23. package/dist/boot/hosted.d.ts.map +1 -0
  24. package/dist/boot/hosted.js +38 -0
  25. package/dist/boot/hosted.js.map +1 -0
  26. package/dist/boot/ownership.d.ts +0 -3
  27. package/dist/boot/ownership.d.ts.map +1 -1
  28. package/dist/boot/ownership.js +5 -5
  29. package/dist/boot/ownership.js.map +1 -1
  30. package/dist/boot/remote.d.ts +1 -1
  31. package/dist/boot/remote.d.ts.map +1 -1
  32. package/dist/boot/remote.js +3 -3
  33. package/dist/boot/remote.js.map +1 -1
  34. package/dist/boot/statement-drift.d.ts +24 -0
  35. package/dist/boot/statement-drift.d.ts.map +1 -0
  36. package/dist/boot/statement-drift.js +38 -0
  37. package/dist/boot/statement-drift.js.map +1 -0
  38. package/dist/boot/together.d.ts.map +1 -1
  39. package/dist/boot/together.js +6 -6
  40. package/dist/boot/together.js.map +1 -1
  41. package/dist/boot/types.d.ts +17 -4
  42. package/dist/boot/types.d.ts.map +1 -1
  43. package/dist/contract/CallLog.d.ts +57 -0
  44. package/dist/contract/CallLog.d.ts.map +1 -0
  45. package/dist/contract/CallLog.js +2 -0
  46. package/dist/contract/CallLog.js.map +1 -0
  47. package/dist/contract.d.ts +9 -4
  48. package/dist/contract.d.ts.map +1 -1
  49. package/dist/contract.js +12 -5
  50. package/dist/contract.js.map +1 -1
  51. package/dist/dispatch/DispatchLifecycle.d.ts +9 -1
  52. package/dist/dispatch/DispatchLifecycle.d.ts.map +1 -1
  53. package/dist/dispatch/DispatchLifecycle.js +17 -2
  54. package/dist/dispatch/DispatchLifecycle.js.map +1 -1
  55. package/dist/dispatch/InFlight.d.ts +0 -1
  56. package/dist/dispatch/InFlight.d.ts.map +1 -1
  57. package/dist/dispatch/InFlight.js +0 -3
  58. package/dist/dispatch/InFlight.js.map +1 -1
  59. package/dist/dispatch/InputValidator.d.ts.map +1 -1
  60. package/dist/dispatch/InputValidator.js +3 -2
  61. package/dist/dispatch/InputValidator.js.map +1 -1
  62. package/dist/dispatch/OutputProjector.js +2 -2
  63. package/dist/dispatch/OutputProjector.js.map +1 -1
  64. package/dist/dispatch/StorageGuard.d.ts.map +1 -1
  65. package/dist/dispatch/StorageGuard.js +2 -2
  66. package/dist/dispatch/StorageGuard.js.map +1 -1
  67. package/dist/effective-operation.d.ts.map +1 -1
  68. package/dist/effective-operation.js +8 -5
  69. package/dist/effective-operation.js.map +1 -1
  70. package/dist/emit.d.ts +2 -2
  71. package/dist/emit.d.ts.map +1 -1
  72. package/dist/emit.js +2 -2
  73. package/dist/emit.js.map +1 -1
  74. package/dist/identity.js +1 -1
  75. package/dist/identity.js.map +1 -1
  76. package/dist/imports.d.ts +1 -1
  77. package/dist/imports.d.ts.map +1 -1
  78. package/dist/imports.js.map +1 -1
  79. package/dist/index.d.ts +8 -2
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +12 -1
  82. package/dist/index.js.map +1 -1
  83. package/dist/node.d.ts +2 -0
  84. package/dist/node.d.ts.map +1 -1
  85. package/dist/node.js +2 -0
  86. package/dist/node.js.map +1 -1
  87. package/dist/orm.d.ts.map +1 -1
  88. package/dist/orm.js +4 -4
  89. package/dist/orm.js.map +1 -1
  90. package/dist/prefab/collector.js +2 -2
  91. package/dist/prefab/collector.js.map +1 -1
  92. package/dist/prefab/mirror.d.ts.map +1 -1
  93. package/dist/prefab/mirror.js +2 -2
  94. package/dist/prefab/mirror.js.map +1 -1
  95. package/dist/prefab/presenter.d.ts.map +1 -1
  96. package/dist/prefab/presenter.js +2 -2
  97. package/dist/prefab/presenter.js.map +1 -1
  98. package/dist/prefab/repository.d.ts.map +1 -1
  99. package/dist/prefab/repository.js +2 -2
  100. package/dist/prefab/repository.js.map +1 -1
  101. package/dist/scan/bundling.d.ts +14 -0
  102. package/dist/scan/bundling.d.ts.map +1 -0
  103. package/dist/scan/bundling.js +26 -0
  104. package/dist/scan/bundling.js.map +1 -0
  105. package/dist/scan/declare.d.ts +71 -0
  106. package/dist/scan/declare.d.ts.map +1 -0
  107. package/dist/scan/declare.js +125 -0
  108. package/dist/scan/declare.js.map +1 -0
  109. package/dist/scan/emit.d.ts.map +1 -1
  110. package/dist/scan/emit.js +3 -2
  111. package/dist/scan/emit.js.map +1 -1
  112. package/dist/scan/handler-parser.d.ts +2 -0
  113. package/dist/scan/handler-parser.d.ts.map +1 -1
  114. package/dist/scan/handler-parser.js +52 -13
  115. package/dist/scan/handler-parser.js.map +1 -1
  116. package/dist/scan/scanner.d.ts.map +1 -1
  117. package/dist/scan/scanner.js +37 -11
  118. package/dist/scan/scanner.js.map +1 -1
  119. package/dist/scan/statement.d.ts +4 -0
  120. package/dist/scan/statement.d.ts.map +1 -0
  121. package/dist/scan/statement.js +112 -0
  122. package/dist/scan/statement.js.map +1 -0
  123. package/dist/verify.js +2 -2
  124. package/dist/verify.js.map +1 -1
  125. package/dist/wire/call.d.ts +19 -8
  126. package/dist/wire/call.d.ts.map +1 -1
  127. package/dist/wire/call.js +17 -6
  128. package/dist/wire/call.js.map +1 -1
  129. package/dist/wire/drift.d.ts +55 -0
  130. package/dist/wire/drift.d.ts.map +1 -0
  131. package/dist/wire/drift.js +121 -0
  132. package/dist/wire/drift.js.map +1 -0
  133. package/dist/wire/middleware.d.ts +1 -1
  134. package/dist/wire/middleware.d.ts.map +1 -1
  135. package/package.json +6 -4
  136. package/src/boot/AppLifecycle.ts +50 -0
  137. package/src/boot/Emissions.ts +263 -0
  138. package/src/boot/HandlerFacade.ts +242 -0
  139. package/src/boot/ambient-port.ts +41 -0
  140. package/src/boot/ambient.als.ts +43 -0
  141. package/src/boot/ambient.queue.ts +75 -0
  142. package/src/boot/apply.ts +47 -0
  143. package/src/boot/auth.ts +55 -0
  144. package/src/boot/binding.ts +182 -0
  145. package/src/boot/boot.ts +125 -0
  146. package/src/boot/bootstrap.ts +847 -0
  147. package/src/boot/frame.ts +210 -0
  148. package/src/boot/hosted.ts +77 -0
  149. package/src/boot/ownership.ts +137 -0
  150. package/src/boot/ports.ts +66 -0
  151. package/src/boot/remote.ts +179 -0
  152. package/src/boot/seed.ts +158 -0
  153. package/src/boot/statement-drift.ts +60 -0
  154. package/src/boot/together.ts +215 -0
  155. package/src/boot/types.ts +274 -0
  156. package/src/builtins/config.ts +19 -0
  157. package/src/builtins/logger.ts +175 -0
  158. package/src/config-loader.ts +146 -0
  159. package/src/contract/Call.ts +18 -0
  160. package/src/contract/CallLog.ts +55 -0
  161. package/src/contract/Invocation.ts +72 -0
  162. package/src/contract/RouteAddress.ts +49 -0
  163. package/src/contract.ts +83 -0
  164. package/src/crypto/encoding.ts +59 -0
  165. package/src/crypto/node.ts +30 -0
  166. package/src/crypto/port.ts +45 -0
  167. package/src/crypto/webcrypto.ts +55 -0
  168. package/src/define.ts +10 -0
  169. package/src/dispatch/ArgumentResolver.ts +17 -0
  170. package/src/dispatch/ArrayResult.ts +10 -0
  171. package/src/dispatch/DispatchEvent.ts +38 -0
  172. package/src/dispatch/DispatchLifecycle.ts +43 -0
  173. package/src/dispatch/DispatchPort.ts +6 -0
  174. package/src/dispatch/Dispatcher.ts +48 -0
  175. package/src/dispatch/InFlight.ts +45 -0
  176. package/src/dispatch/InputValidator.ts +28 -0
  177. package/src/dispatch/LocalRoutePolicy.ts +34 -0
  178. package/src/dispatch/OperationExecutor.ts +60 -0
  179. package/src/dispatch/OperationRoute.ts +18 -0
  180. package/src/dispatch/OutputProjector.ts +32 -0
  181. package/src/dispatch/OutputView.ts +9 -0
  182. package/src/dispatch/PresenterArgumentResolver.ts +25 -0
  183. package/src/dispatch/PresenterExecutor.ts +55 -0
  184. package/src/dispatch/RemoteRouteResolver.ts +21 -0
  185. package/src/dispatch/Route.ts +11 -0
  186. package/src/dispatch/RouteNotFoundError.ts +29 -0
  187. package/src/dispatch/RoutePolicy.ts +8 -0
  188. package/src/dispatch/RouteRegistry.ts +73 -0
  189. package/src/dispatch/RouteResolver.ts +7 -0
  190. package/src/dispatch/StorageGuard.ts +71 -0
  191. package/src/effective-operation.ts +601 -0
  192. package/src/emit.ts +90 -0
  193. package/src/entry/DynamicFacade.ts +28 -0
  194. package/src/entry/FacadeEntry.ts +32 -0
  195. package/src/entry/TransportEntry.ts +30 -0
  196. package/src/frond-config.ts +138 -0
  197. package/src/graph.ts +180 -0
  198. package/src/identity-keys.ts +43 -0
  199. package/src/identity.ts +235 -0
  200. package/src/imports.ts +123 -0
  201. package/src/index.ts +120 -0
  202. package/src/loader.ts +41 -0
  203. package/src/node.ts +30 -0
  204. package/src/orm.ts +252 -0
  205. package/src/prefab/collector.ts +36 -0
  206. package/src/prefab/crud.ts +188 -0
  207. package/src/prefab/mirror.ts +122 -0
  208. package/src/prefab/prefab.ts +46 -0
  209. package/src/prefab/presenter.ts +63 -0
  210. package/src/prefab/repository.ts +170 -0
  211. package/src/scan/Fronds.ts +73 -0
  212. package/src/scan/bundling.ts +25 -0
  213. package/src/scan/conventions.ts +122 -0
  214. package/src/scan/declare.ts +188 -0
  215. package/src/scan/emit.ts +231 -0
  216. package/src/scan/frond.ts +235 -0
  217. package/src/scan/handler-parser.ts +817 -0
  218. package/src/scan/scanner.ts +757 -0
  219. package/src/scan/statement.ts +126 -0
  220. package/src/verify.ts +193 -0
  221. package/src/wire/call.ts +381 -0
  222. package/src/wire/drift.ts +131 -0
  223. package/src/wire/errors.ts +124 -0
  224. package/src/wire/http-error.ts +77 -0
  225. package/src/wire/loggerMiddleware.ts +29 -0
  226. package/src/wire/middleware.ts +47 -0
  227. package/src/wire/operation.ts +258 -0
  228. package/dist/boot/Lifecycle.d.ts +0 -4
  229. package/dist/boot/Lifecycle.d.ts.map +0 -1
  230. package/dist/boot/Lifecycle.js +0 -3
  231. package/dist/boot/Lifecycle.js.map +0 -1
  232. package/dist/boot/egress.d.ts +0 -8
  233. package/dist/boot/egress.d.ts.map +0 -1
  234. package/dist/boot/egress.js +0 -11
  235. package/dist/boot/egress.js.map +0 -1
  236. package/dist/scan/scan-cache.d.ts +0 -16
  237. package/dist/scan/scan-cache.d.ts.map +0 -1
  238. package/dist/scan/scan-cache.js +0 -99
  239. package/dist/scan/scan-cache.js.map +0 -1
  240. package/dist/wire/invocation.d.ts +0 -4
  241. package/dist/wire/invocation.d.ts.map +0 -1
  242. package/dist/wire/invocation.js +0 -3
  243. package/dist/wire/invocation.js.map +0 -1
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The boot's two ends: what `createApp` takes, and what it hands back.
3
+ *
4
+ * The scan's descriptors moved to `frond.ts` and the auth contract to `auth.ts` — this
5
+ * file was named after a role ("the types"), so everything with nowhere else to be
6
+ * landed in it, seventeen notions deep.
7
+ */
8
+ import type { Container } from '@fougere/container';
9
+ import type { Fronds } from '../scan/Fronds.js';
10
+ import type { FrondDescriptor, ScanResult } from '../scan/frond.js';
11
+ import type { SchemaView } from '@fougere/schema';
12
+ import type { OrmFactory } from '../orm.js';
13
+ import type { AppMiddleware } from '../wire/middleware.js';
14
+ import type { RpcAnswer, Transport } from '../wire/call.js';
15
+ import type { Extension } from './AppLifecycle.js';
16
+ import type { AuthConfig, AuthRuntime } from './auth.js';
17
+ import type { EffectiveOperationsMap } from '../effective-operation.js';
18
+ import type { DispatchObserver } from '../dispatch/DispatchEvent.js';
19
+ import type { DispatchPort } from '../dispatch/DispatchPort.js';
20
+
21
+ /** Options for createApp(). */
22
+ export interface CreateAppOptions {
23
+ /** Factory function to create the container. Required. */
24
+ createContainer: () => Container;
25
+ /** Factory to auto-generate EntityOrm for each scanned entity. */
26
+ ormFactory?: OrmFactory;
27
+ /**
28
+ * Which source an entity's rows live in, and how to open a transaction on one — the two
29
+ * questions that decide whether `Together<[…]>` gets the engine's own unwind or replays
30
+ * inverses itself.
31
+ *
32
+ * Optional together, because a host may hand in a bare `ormFactory` and know neither. A
33
+ * frame then compensates: not knowing where the rows are and promising atomicity over
34
+ * them are two different things, and only one of them is honest.
35
+ */
36
+ sourceOf?: (entityName: string) => string;
37
+ transacted?: <R>(source: string, fn: (ormFactory: OrmFactory) => Promise<R>) => Promise<R>;
38
+ /**
39
+ * Builds the cross-source reader a frond gets when it declares `reads:`.
40
+ *
41
+ * A factory rather than a value, for the same reason `ormFactory` is one: core must
42
+ * not name a storage package, and this one costs 71 MB of downloaded extensions and a
43
+ * native module — nothing a first run that only wanted sqlite should carry. The host
44
+ * decides what backs it; `@fougere/adapter-duckdb` is one answer, not the contract.
45
+ *
46
+ * Called once per frond that asks, with the entity CLASSES its `reads:` named — a
47
+ * name would make the reader resolve the schema a second time.
48
+ */
49
+ sourcesFactory?: (reads: unknown[], frond: string) => Promise<unknown> | unknown;
50
+ /**
51
+ * What this app is built from — required, because producing it is what reads a disk.
52
+ *
53
+ * `scanProject` (`@fougere/core/node`) reads the fronds off the filesystem; a module a
54
+ * build wrote holds the same value with no disk at all. `createApp` cannot tell them
55
+ * apart, and that is the point: it names no builtin, so a runtime without `node:fs`
56
+ * runs it. `root` and `fronds` used to live here — both were arguments to the scan.
57
+ */
58
+ scan?: ScanResult | (() => Promise<ScanResult> | ScanResult);
59
+ /**
60
+ * What this app STATES it hosts — `frond('blog', { entities: [Post] })`.
61
+ *
62
+ * Passing this and not `scan:` is how an app says "do not scan": nothing reads a disk,
63
+ * nothing loads `typescript`, and what was not named does not exist. Passing both fills
64
+ * the members left unnamed from what the scan found — the app's word wins, the way
65
+ * `frond.config.ts` wins over the scan one level down.
66
+ */
67
+ fronds?: readonly FrondDescriptor[];
68
+ /**
69
+ * Remote fronds — label → address. What each remote hosts is discovered
70
+ * at the first miss (rpc.discover), never declared here.
71
+ */
72
+ remotes?: Record<string, string>;
73
+ /**
74
+ * Builds the transport used to reach `remotes` addresses. Wired by
75
+ * layer-2 packages (e.g. @fougere/transport-http); required when
76
+ * `remotes` is non-empty.
77
+ */
78
+ remoteTransport?: (url: string) => Transport;
79
+ /**
80
+ * Which realization answers which port — see `FougereConfig.ports`. Needed only
81
+ * when two classes extend the same port; one is resolved by convention.
82
+ */
83
+ ports?: Record<string, string>;
84
+ /**
85
+ * What this app takes on beyond its fronds, each stating what it does and what it undoes.
86
+ *
87
+ * `up` runs before `createApp` returns, in this order; `down` runs inside `dispose()`,
88
+ * in reverse. Three levels release in reverse of construction, which is the container's
89
+ * own rule read one level out: extensions first (built last), then the container, then
90
+ * `onDispose` — a resource opened before any of this existed.
91
+ *
92
+ * A member may be `undefined`, so a host writes a conditional one inline rather than a
93
+ * spread over a ternary. The framework's own two are always declared, `migrate` as an
94
+ * empty slot when nothing migrates: a host filling it later REPLACES that member in
95
+ * place instead of adding one after the seeds.
96
+ */
97
+ extensions?: readonly (Extension | undefined)[];
98
+ /**
99
+ * Released by `app.dispose()` AFTER the container, for a resource handed in rather
100
+ * than built here — a storage connection is the one case today.
101
+ *
102
+ * NOT an extension, and the difference is a time: this was opened BEFORE the container,
103
+ * so it closes after it, while an extension's `up` runs after the container and its
104
+ * `down` therefore runs before. A storage's migration is an extension; its connection
105
+ * is not, and `ResolvedStorage` declares the two beside each other.
106
+ */
107
+ onDispose?: () => Promise<void> | void;
108
+ /**
109
+ * Which protocol adapters this app serves — see `FougereConfig.adapters`.
110
+ * Carried onto the App so every door reads one answer instead of each host
111
+ * deciding for itself.
112
+ */
113
+ adapters?: Record<string, boolean | undefined>;
114
+ /**
115
+ * Carries an announced fact out of this process — a broker, a queue, a log.
116
+ *
117
+ * Called for every emission, ALONGSIDE the local dispatch and never instead of it: a
118
+ * listener in this process is reached directly, and this is how the others hear.
119
+ *
120
+ * It exists because the local dispatch finds its listeners by having READ their code,
121
+ * which stops at the repository boundary. A carrier hands the fact to a NAME; the far
122
+ * side subscribes to that same name from its own code, and neither ever reads the other.
123
+ *
124
+ * Its failure never reaches the emitter — same rule as a subscriber's.
125
+ */
126
+ onEmit?: (fact: string, payload: unknown) => void | Promise<void>;
127
+ /** Passive observers of every dispatch transition. */
128
+ dispatchObservers?: readonly DispatchObserver[];
129
+ /**
130
+ * Storage handle to expose to the auth provider via AuthContext.db.
131
+ * Required when `auth` is set.
132
+ */
133
+ db?: unknown;
134
+ /** Auth declaration to wire into the app at boot. */
135
+ auth?: AuthConfig;
136
+ }
137
+
138
+ /** The App object returned by createApp(). */
139
+ export interface App extends DispatchPort {
140
+ /** Process-only dispatch capability used by incoming transports. */
141
+ local: DispatchPort;
142
+ /** Root container with builtins + frond scopes. */
143
+ container: Container;
144
+ /**
145
+ * Which protocol adapters this app declared, from `fougere.config.ts`.
146
+ *
147
+ * Read by the doors themselves, so an undeclared adapter serves nothing whatever
148
+ * the host mounted — the route file may exist, the middleware may be installed, and
149
+ * the answer is still "not here".
150
+ */
151
+ adapters: Record<string, boolean | undefined>;
152
+ /** Where a call goes, as the config declared it — frond name to address. */
153
+ remotes: Readonly<Record<string, string>>;
154
+ /** Discovered fronds metadata. */
155
+ fronds: Fronds;
156
+ /** Resolve from root container (shortcut). */
157
+ resolve<T>(name: string): T;
158
+ /**
159
+ * Resolve an entity's schema — the local `entityClass` when it's hosted or
160
+ * scanned here, else reconstructed from the remote's identity card
161
+ * (`rpc.discover` to `Card.toSchema`). The one way to get a live schema for an
162
+ * entity whose class may not be importable at all (another repo, another
163
+ * language) — a card travelled, but until now its `schema` was thrown away.
164
+ */
165
+ schemaFor(entity: string): Promise<SchemaView>;
166
+ /**
167
+ * The door a name exposes to one audience, or `undefined` when it exposes
168
+ * none. A named surface is CLOSED: a name with no door of its own under that
169
+ * surface is not in it — it never falls back to the full one.
170
+ *
171
+ * **Not always a façade**, despite the name: when the owning frond is declared
172
+ * remote, nothing is registered locally (`bootstrap.ts`, `declaredRemotes`) and
173
+ * this resolves to a doublure — a façade-shaped stand-in (`remote.ts`). The
174
+ * caller cannot tell, which is the point; the word here was simply wrong.
175
+ *
176
+ * The one way an adapter reaches that door. It exists so the key format stays
177
+ * inside core (see `facadeKeyOf`), which is what lets a projection package
178
+ * stay structurally typed and depend on nothing.
179
+ */
180
+ facadeFor(entity: string, surface?: string): Record<string, Function> | undefined;
181
+ /**
182
+ * The canonical contracts served beside a facade, after prefab + scan + config,
183
+ * binding, kind, topology and surface resolution. Check, explain and adapters read
184
+ * this table instead of replaying those decisions.
185
+ */
186
+ operationsFor(entity: string, surface?: string): EffectiveOperationsMap | undefined;
187
+ /**
188
+ * The facts this app has a listener for — what a carrier must subscribe to on its behalf.
189
+ *
190
+ * Derived from the signatures it scanned (`Fact<T>` in an op's parameters), so a process
191
+ * states what it listens to without anyone declaring it twice. The dual of `onEmit`: one
192
+ * says what leaves, this says what should be brought in.
193
+ */
194
+ listensTo(): string[];
195
+ /**
196
+ * Hand a fact that came from OUTSIDE to the listeners in this process — and stop there.
197
+ *
198
+ * The dual of `onEmit`, and deliberately not the same thing as announcing: resolving the
199
+ * emission value to deliver an inbound fact would carry it straight back out through
200
+ * `onEmit`, so a hub echoed every reading it received to the whole fleet. Receiving and
201
+ * announcing are two operations; only one of them leaves.
202
+ *
203
+ * The local dispatch is identical either way — same judge, same binding, same
204
+ * middlewares — so a fact off a wire is no less checked than one raised next door.
205
+ *
206
+ * **It waits, and it tells** — the opposite of announcing, on purpose. It resolves once
207
+ * every listener here is done, and REJECTS with an `AggregateError` if any refused. A
208
+ * carrier's whole job is to know whether the fact landed: at-least-once is retrying what
209
+ * failed, so a delivery that cannot report makes durability impossible to build above it.
210
+ * "Dispatch is not delivery" protects the EMITTER from a slow subscriber; a carrier is
211
+ * not the emitter, it is the party whose business this is.
212
+ *
213
+ * It still holds nothing. A refused fact is refused, and whether it comes back is the
214
+ * carrier's decision — Fougere puts the channel underneath rather than reimplementing it.
215
+ */
216
+ deliver(fact: string, payload: unknown): Promise<void>;
217
+ /**
218
+ * The storage an entity is backed by, resolved through its owning frond's scope —
219
+ * the dual of {@link facadeFor}. `undefined` when no loaded frond hosts the entity,
220
+ * or when the app booted with no storage at all.
221
+ *
222
+ * `unknown` because the port belongs to whoever wired it: narrowing it to `EntityOrm`
223
+ * is the caller saying which implementation they are standing on.
224
+ */
225
+ ormFor(entity: string): unknown | undefined;
226
+ /**
227
+ * The presenter of an entity, resolved through its owning frond's scope.
228
+ *
229
+ * Same shape as {@link ormFor}, and it exists so an adapter never spells the container
230
+ * key itself: `schema-graphql` wrote out `${Name}Presenter` by hand, and a key respelled
231
+ * in a second place finds nothing and reports nothing the day the convention moves.
232
+ */
233
+ presenterFor(entity: string): unknown | undefined;
234
+ /** Dispose the root container. */
235
+ dispose(): Promise<void>;
236
+ /**
237
+ * Stop taking calls, and resolve once the running ones are done.
238
+ *
239
+ * The step before releasing, when there is work on the app: `dispose()` closes a
240
+ * storage connection the running calls are standing on. Rejects on `timeoutMs`
241
+ * naming how many are left, rather than resolving as if it had succeeded.
242
+ */
243
+ drain(timeoutMs?: number): Promise<void>;
244
+ /** How many calls are running right now — one count for all three doors and the wire. */
245
+ inFlight(): number;
246
+ /**
247
+ * The same disposal, spelled so the language does it: `await using app = await
248
+ * createApp(…)`. Twelve of the twenty-six mounts in this repo's own tests never
249
+ * called `dispose()` — a scope that closes itself is the only version of that
250
+ * rule nobody forgets.
251
+ */
252
+ [Symbol.asyncDispose](): Promise<void>;
253
+ /**
254
+ * What this app took on, in the order it will release them. The reading of
255
+ * `CreateAppOptions.extensions` after the boot resolved it.
256
+ */
257
+ extensions(): string[];
258
+ /**
259
+ * Declare one `rpc` op — what the app says about ITSELF, beside the card.
260
+ *
261
+ * The gesture a package uses to add a reading core does not hold: an app that never
262
+ * installed it never registers it, so the runner's refusal is the whole degradation.
263
+ * A name already declared is refused rather than replaced — `discover` included.
264
+ */
265
+ serveRpc(op: string, answer: RpcAnswer): void;
266
+ /** Register a global app middleware (runs on every operation). */
267
+ /** Watch every dispatch transition; the returned function unsubscribes. */
268
+ observe(observer: DispatchObserver): () => void;
269
+ use(middleware: AppMiddleware): void;
270
+ /** Register an app middleware scoped to a specific entity. */
271
+ use(entity: string, middleware: AppMiddleware): void;
272
+ /** Auth runtime, present when fougere.config.ts declares `auth`. */
273
+ auth?: AuthRuntime;
274
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The process environment, as a service — so a handler asks for it rather than reading it.
3
+ *
4
+ * `process` is absent on a Worker, where the environment arrives as a binding. Read through
5
+ * `globalThis` and treated as empty when there is none: a missing variable and a missing
6
+ * `process` are the same answer to a caller, and the fallback already says what to do.
7
+ */
8
+ export class Config {
9
+ constructor(private readonly env: Record<string, string | undefined> = envOfProcess()) {}
10
+
11
+ get<T = string>(key: string, fallback?: T): T {
12
+ return (this.env[key] as T) ?? (fallback as T);
13
+ }
14
+ }
15
+
16
+ function envOfProcess(): Record<string, string | undefined> {
17
+ const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;
18
+ return proc?.env ?? {};
19
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Fougere Logger — structured, colored, multi-runtime.
3
+ *
4
+ * Works on Node, Bun, Deno, Cloudflare Workers (console-based, no native bindings).
5
+ */
6
+
7
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
8
+
9
+ /**
10
+ * One line, before it was formatted for a terminal.
11
+ *
12
+ * The console form is already cooked — ANSI codes, a badge, a timestamp — so anything
13
+ * that wants to FORWARD a log needs it before that. What travels is the structure, and
14
+ * nothing here knows where it goes.
15
+ */
16
+ export interface LogRecord {
17
+ level: Exclude<LogLevel, 'silent'>;
18
+ /** The logger's own name — 'boot:app', 'boot:app:catalog'. */
19
+ name: string;
20
+ message: string;
21
+ args: unknown[];
22
+ /** Epoch milliseconds. */
23
+ at: number;
24
+ }
25
+
26
+ export type LogSink = (record: LogRecord) => void;
27
+
28
+ /**
29
+ * Who else takes this process's log lines, beside the console. A list, like the span
30
+ * sinks: a line is one fact, and forwarding it twice is the caller's business.
31
+ *
32
+ * Nothing is built when nobody listens — the record is only shaped if a sink exists.
33
+ */
34
+ const sinks: LogSink[] = [];
35
+
36
+ /** Take every line this process logs. Returns the way to withdraw. */
37
+ export function onLog(next: LogSink): () => void {
38
+ sinks.push(next);
39
+ return () => {
40
+ const at = sinks.indexOf(next);
41
+ if (at >= 0) sinks.splice(at, 1);
42
+ };
43
+ }
44
+
45
+ const LEVELS: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
46
+
47
+ /**
48
+ * The level, held ONCE for the process and CONSULTED at every emission.
49
+ *
50
+ * It used to be copied into each Logger by the constructor, and copied again by
51
+ * `child()` — so there was no place where "the level" was, and changing it meant
52
+ * rebuilding every logger AND everything that had been handed one. A value read at
53
+ * the moment it is used costs the same and can move.
54
+ */
55
+ let threshold: number = LEVELS[envLevel() ?? 'info'];
56
+
57
+ /**
58
+ * The level the PROCESS was started with. Read here rather than only at `applyConfig`,
59
+ * which runs after the boot has already said where its root is — an operator asking for
60
+ * `warn` got that line anyway. Guarded: this module runs on Workers, where there is no
61
+ * `process`.
62
+ */
63
+ export function envLevel(): LogLevel | undefined {
64
+ const raw = typeof process === 'undefined' ? undefined : process.env.FOUGERE_LOG_LEVEL;
65
+ return raw !== undefined && raw in LEVELS ? (raw as LogLevel) : undefined;
66
+ }
67
+
68
+ /**
69
+ * Set the level for every logger in this process, at once.
70
+ *
71
+ * Refuses a level it does not know rather than storing `undefined` as the threshold:
72
+ * every comparison against it is then `NaN`, so nothing is filtered and `logLevel()`
73
+ * reports its own fallback instead of what is in force.
74
+ */
75
+ export function setLogLevel(level: LogLevel): void {
76
+ if (!(level in LEVELS)) {
77
+ throw new Error(`Unknown log level: '${level}'. One of ${Object.keys(LEVELS).join(', ')}.`);
78
+ }
79
+ threshold = LEVELS[level];
80
+ }
81
+
82
+ /** What the level is now — the dual, so a reload can report what it changed. */
83
+ export function logLevel(): LogLevel {
84
+ return (Object.keys(LEVELS) as LogLevel[]).find((l) => LEVELS[l] === threshold) ?? 'info';
85
+ }
86
+
87
+ const COLORS: Record<string, string> = {
88
+ reset: '\x1b[0m',
89
+ dim: '\x1b[2m',
90
+ bold: '\x1b[1m',
91
+ green: '\x1b[32m',
92
+ yellow: '\x1b[33m',
93
+ red: '\x1b[31m',
94
+ cyan: '\x1b[36m',
95
+ magenta: '\x1b[35m',
96
+ gray: '\x1b[90m',
97
+ };
98
+
99
+ const LEVEL_STYLE: Record<string, { badge: string; color: string }> = {
100
+ debug: { badge: 'DBG', color: 'gray' },
101
+ info: { badge: 'INF', color: 'green' },
102
+ warn: { badge: 'WRN', color: 'yellow' },
103
+ error: { badge: 'ERR', color: 'red' },
104
+ };
105
+
106
+ function supportsColor(): boolean {
107
+ if (typeof process !== 'undefined') {
108
+ if (process.env.NO_COLOR) return false;
109
+ if (process.env.FORCE_COLOR === '1') return true;
110
+ return process.stdout?.isTTY === true;
111
+ }
112
+ return false;
113
+ }
114
+
115
+ function formatTime(): string {
116
+ const d = new Date();
117
+ const h = String(d.getHours()).padStart(2, '0');
118
+ const m = String(d.getMinutes()).padStart(2, '0');
119
+ const s = String(d.getSeconds()).padStart(2, '0');
120
+ const ms = String(d.getMilliseconds()).padStart(3, '0');
121
+ return `${h}:${m}:${s}.${ms}`;
122
+ }
123
+
124
+ export interface LoggerOptions {
125
+ /** Logger name / prefix. */
126
+ name?: string;
127
+ /** Force color on/off. Auto-detected by default. */
128
+ color?: boolean;
129
+ }
130
+
131
+ export class Logger {
132
+ private name: string;
133
+ private color: boolean;
134
+
135
+ constructor(prefix?: string, options?: Omit<LoggerOptions, 'name'>) {
136
+ this.name = prefix ?? 'app';
137
+ this.color = options?.color ?? supportsColor();
138
+ }
139
+
140
+ /** Create a child logger with a sub-name. It carries no level of its own either. */
141
+ child(name: string): Logger {
142
+ return new Logger(`${this.name}:${name}`, { color: this.color });
143
+ }
144
+
145
+ debug(msg: string, ...args: unknown[]) { this.log('debug', msg, args); }
146
+ info(msg: string, ...args: unknown[]) { this.log('info', msg, args); }
147
+ warn(msg: string, ...args: unknown[]) { this.log('warn', msg, args); }
148
+ error(msg: string, ...args: unknown[]) { this.log('error', msg, args); }
149
+
150
+ private log(level: string, msg: string, args: unknown[]) {
151
+ if (LEVELS[level as LogLevel] < threshold) return;
152
+
153
+ // Beside the console, never instead of it: a forwarded line is an addition, and a
154
+ // sink that throws must not cost the operator the line they were reading.
155
+ for (const take of sinks) {
156
+ try {
157
+ take({ level: level as LogRecord['level'], name: this.name, message: msg, args, at: Date.now() });
158
+ } catch { /* forwarding never breaks logging */ }
159
+ }
160
+
161
+ const style = LEVEL_STYLE[level];
162
+ const time = formatTime();
163
+ // One console method per level. `debug` and `info` both went to `console.log`, so
164
+ // nothing downstream — a terminal filter, a collector — could tell them apart.
165
+ const method = level as 'debug' | 'info' | 'warn' | 'error';
166
+
167
+ if (this.color) {
168
+ const c = COLORS[style.color];
169
+ const prefix = `${COLORS.dim}${time}${COLORS.reset} ${c}${COLORS.bold}${style.badge}${COLORS.reset} ${COLORS.magenta}${this.name}${COLORS.reset}`;
170
+ console[method](prefix, msg, ...args);
171
+ } else {
172
+ console[method](`${time} ${style.badge} [${this.name}]`, msg, ...args);
173
+ }
174
+ }
175
+ }
@@ -0,0 +1,146 @@
1
+ import { resolve } from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import type { AuthConfig } from './boot/auth.js';
4
+ import type { LogLevel } from './builtins/logger.js';
5
+ import type { ConventionsInput } from './scan/conventions.js';
6
+ import { getModuleLoader } from './loader.js';
7
+
8
+ // ── Types ────────────────────────────────────────
9
+
10
+ export interface FougereConfig {
11
+ /** Database configuration — the DEFAULT source, the one an entity lands in unnamed. */
12
+ db?: 'sqlite' | { dialect: 'sqlite'; path?: string } | false;
13
+ /**
14
+ * The other places rows live — a name, an engine, and the entities it holds.
15
+ *
16
+ * A fact about the APP, stated beside `remotes:` because it is the same kind of
17
+ * statement: `remotes:` says where a CALL goes, this says where a ROW is. Neither
18
+ * belongs on the entity, which describes itself and not its deployment.
19
+ *
20
+ * Only the exception is declared: everything unnamed stays in `db`. Membership is
21
+ * per ENTITY rather than per frond — two fronds may share a database, and one frond
22
+ * may hold entities in two — so the entity is the truth and a frond-wide shorthand
23
+ * waits for a case that needs it.
24
+ *
25
+ * A `ref()` across two sources gets no foreign key: two databases share no
26
+ * constraint. The DDL stops pretending rather than the `ref` being refused.
27
+ */
28
+ sources?: Record<string, { dialect?: 'sqlite'; path?: string; entities: string[] }>;
29
+ /**
30
+ * The names the scan reads instead of deriving them — the import scope, the fronds
31
+ * directory, the seven convention directories.
32
+ *
33
+ * Only what differs is stated. Read BEFORE the fronds are discovered, which is what
34
+ * lets it name the prefix they are found under: nothing in this file may import
35
+ * `@fronds/*`, or the name would be needed to read the file that declares it.
36
+ */
37
+ conventions?: ConventionsInput;
38
+ /**
39
+ * How much every logger says. The one key a running app CONSULTS rather than
40
+ * consumes, so re-reading this file changes it without rebuilding anything.
41
+ *
42
+ * `FOUGERE_LOG_LEVEL` still wins — it is how the CLI speaks, and the precedence is
43
+ * the usual one (CLI over config file).
44
+ */
45
+ logLevel?: LogLevel;
46
+ /** Remote fronds — frondName → base URL. */
47
+ remotes?: Record<string, string>;
48
+ /**
49
+ * Which realization answers which port — port class name → implementation class name.
50
+ *
51
+ * A fact about the APP, stated beside `remotes:` for the same reason `sources:` is:
52
+ * `remotes:` says where a CALL goes, `sources:` says where a ROW is, this says who
53
+ * performs an ACTION. None of the three belongs inside the frond, which describes
54
+ * itself and not its deployment — a `billing` frond naming Stripe would be the one
55
+ * thing the framework refuses.
56
+ *
57
+ * Only the exception is declared. One class extending a port answers it by
58
+ * convention and this key stays absent; two make the boot refuse until one is named.
59
+ */
60
+ ports?: Record<string, string>;
61
+ /** Auth declaration — picks a provider package and forwards options to it. */
62
+ auth?: AuthConfig;
63
+ /**
64
+ * Which protocol adapters this app serves.
65
+ *
66
+ * A fact about the APP, declared once beside `db`, `remotes` and `auth` — not a
67
+ * property of whichever host runs it. Before this existed the same decision was
68
+ * spelled five different ways: Nuxt mounted REST unconditionally, the Web hosts
69
+ * served it if you happened to create a route file, and Express if you happened to
70
+ * call a middleware. One decision, five dialects, no canonical place.
71
+ *
72
+ * Absent means not served. The call envelope is not listed here: it is the wire the
73
+ * client primitives use, not a projection an app chooses to publish.
74
+ */
75
+ adapters?: AdapterConfig;
76
+ }
77
+
78
+ /** Protocol adapters, by the name of the package that provides them. */
79
+ export interface AdapterConfig {
80
+ /** `@fougere/adapter-rest` — REST under `/api/{frond}/{plural}`. */
81
+ rest?: boolean;
82
+ /** `@fougere/adapter-graphql` — a GraphQL schema over the same operations. */
83
+ graphql?: boolean;
84
+ /** A surface of your own; the framework only records that you declared it. */
85
+ [adapter: string]: boolean | undefined;
86
+ }
87
+
88
+ // ── Loading ──────────────────────────────────────
89
+
90
+ const CONFIG_FILES = ['fougere.config.ts', 'fougere.config.js', 'fougere.config.mjs'];
91
+
92
+ async function loadConfigFrom(dir: string, fresh?: boolean): Promise<FougereConfig> {
93
+ const loader = getModuleLoader();
94
+ for (const file of CONFIG_FILES) {
95
+ const path = resolve(dir, file);
96
+ if (existsSync(path)) {
97
+ // A module is cached by its specifier, so a second load of an EDITED file hands
98
+ // back what was read the first time — measured, and it made re-reading a config
99
+ // return the config already in force. The loader owns its own cache, so it is the
100
+ // one told; the old module stays in memory, re-reading being for a change.
101
+ const mod = await loader(path, fresh ? { fresh } : undefined);
102
+ return ((mod as { default?: FougereConfig }).default ?? mod) as FougereConfig;
103
+ }
104
+ }
105
+ return {};
106
+ }
107
+
108
+ /**
109
+ * Load the root fougere.config.{ts,js,mjs} from the given directory.
110
+ *
111
+ * `fresh` re-reads a file that may have changed since the last load — what a host
112
+ * calls when it decides to reconsider its config, and the only way `applyConfig` has
113
+ * anything new to apply.
114
+ */
115
+ export async function loadConfig(root: string, options?: { fresh?: boolean }): Promise<FougereConfig> {
116
+ return loadConfigFrom(root, options?.fresh);
117
+ }
118
+
119
+ // ── Merging ──────────────────────────────────────
120
+
121
+ /**
122
+ * Override a config with another, the invariant of every cascade level:
123
+ * scalar keys replace, but `remotes` (the topology) MERGES — an override adds
124
+ * or redirects a frond without erasing the others. Used for workspace→app and
125
+ * for global→CLI alike.
126
+ */
127
+ function mergeGlobal(base: FougereConfig, override: Partial<FougereConfig>): FougereConfig {
128
+ const merged: FougereConfig = { ...base, ...override };
129
+ if (base.remotes || override.remotes) {
130
+ merged.remotes = { ...base.remotes, ...override.remotes };
131
+ }
132
+ return merged;
133
+ }
134
+
135
+ /**
136
+ * Load config along the workspace→app frontier. The workspace-root config is
137
+ * the base (canonical topology: `remotes`, shared `db`); the app-root config
138
+ * overrides. Same `root` boundary the fronds already cascade along. When both
139
+ * roots resolve to the same dir (single app, no workspace), this is the plain
140
+ * root config — idempotent, no behavior change.
141
+ */
142
+ export async function loadCascadedConfig(workspaceRoot: string, appRoot: string): Promise<FougereConfig> {
143
+ const base = await loadConfig(workspaceRoot);
144
+ if (resolve(workspaceRoot) === resolve(appRoot)) return base;
145
+ return mergeGlobal(base, await loadConfig(appRoot));
146
+ }
@@ -0,0 +1,18 @@
1
+ import { Invocation, type InvocationInput } from './Invocation.js';
2
+ import type { RouteAddress } from './RouteAddress.js';
3
+
4
+ /** One normalized request: where it goes and what the caller supplied. */
5
+ export class Call {
6
+ readonly address: RouteAddress;
7
+ readonly invocation: Invocation;
8
+
9
+ constructor(address: RouteAddress, invocation?: InvocationInput) {
10
+ this.address = address;
11
+ this.invocation = Invocation.from(invocation);
12
+ Object.freeze(this);
13
+ }
14
+
15
+ withInvocation(invocation: Invocation): Call {
16
+ return new Call(this.address, invocation);
17
+ }
18
+ }