foldkit-surface 0.10.2 → 0.12.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.
package/README.md CHANGED
@@ -40,7 +40,7 @@ pnpm add foldkit-surface
40
40
  ```ts
41
41
  import { Option, Schema } from 'effect'
42
42
  import { defineMessageUnion } from 'foldkit/message'
43
- import { Projection, Surface } from 'foldkit-surface'
43
+ import { ModelRef, Projection, Surface } from 'foldkit-surface'
44
44
 
45
45
  const Todo = Schema.Struct({ id: Schema.String, title: Schema.String, done: Schema.Boolean })
46
46
  const Model = Schema.Struct({
@@ -83,22 +83,26 @@ in a real application.
83
83
  ## Field references
84
84
 
85
85
  `Surface.application` generates a reference tree from the Model Schema, one node
86
- per field. Each `FieldRef` carries its optic, codec, `get`, and `set`, plus the
87
- field name as a literal type, so a selection can infer its own output keys
88
- without a parallel field registry.
86
+ per field. A ref's string keys are the fields below it, and nothing else, so a
87
+ Model field may have any name (`index`, `at`, `get`, `select`). The ref's own
88
+ members are its *focus*, kept under a symbol and read with `ModelRef.focus`:
89
+ its optic, codec, path, `get`, `set`, and the field name as a literal type, so a
90
+ selection can infer its own output keys without a parallel field registry.
89
91
 
90
92
  ```ts
91
- App.model.todos // FieldRef<Model, Todo[], 'todos'>
92
- App.model.selectedTodoId // FieldRef<Model, Option<string>, 'selectedTodoId'>
93
- App.model.todosById.at('t1') // OptionalRef<Model, Option<Todo>> (dynamic key)
94
- App.model.todos.index(0) // OptionalRef<Model, Option<Todo>> (dynamic index)
93
+ App.model.todos // FieldRef<Model, Todo[], 'todos'>
94
+ App.model.selectedTodoId // FieldRef<Model, Option<string>, 'selectedTodoId'>
95
+ ModelRef.focus(App.model.todos).dependency // ['todos']
96
+ ModelRef.focus(App.model.todosById).at('t1') // OptionalRef<Model, Option<Todo>> (dynamic key)
97
+ ModelRef.focus(App.model.todos).index(0) // OptionalRef<Model, Option<Todo>> (dynamic index)
95
98
  ```
96
99
 
97
100
  A Model field that is itself a `Schema.Struct` recurses, so each of its fields is
98
- a `FieldRef` too. Array and record access is `.index(i)` / `.at(key)`, which
99
- returns an `OptionalRef` — a `ModelRef` with an `Option` value. Those are dynamic
100
- selections, so `Projection.pick` (which needs a static field name) rejects them;
101
- they are useful inside a `Projection`.
101
+ a `FieldRef` too. A focus reaches into an array with `index(i)` and into a record
102
+ with `at(key)`, each only where the value is one; both return an `OptionalRef` —
103
+ a `ModelRef` with an `Option` value. Those are dynamic selections, so
104
+ `Projection.pick` (which needs a static field name) rejects them; they are
105
+ useful inside a `Projection`.
102
106
 
103
107
  `App.fields` is the same tree under a second name, kept only so older code
104
108
  compiles. It is deprecated; use `App.model`.
@@ -144,6 +148,33 @@ Projection.fromReader(codec, read) // escape hatch for a non-ModelRef value
144
148
  mix local fields with remote or replicated values. A nested projection
145
149
  contributes its dependencies and metadata to the parent.
146
150
 
151
+ ### Derivations
152
+
153
+ A view often works out a value from the Model on every render: a filtered
154
+ list, a count, a summary of many server reads. `Projection.derive(on, derive)`
155
+ works it out again only when a value at one of the paths `on` names is a new
156
+ object:
157
+
158
+ ```ts
159
+ const Open = Projection.derive([App.model.todos], model =>
160
+ model.todos.filter(todo => !todo.done),
161
+ )
162
+ Open.read(model) // the same array while `model.todos` is
163
+ ```
164
+
165
+ `on` takes field references and Projections, whose `dependencies` it reads;
166
+ `derive` must read nothing else, or it shows what it read last. A Remote read
167
+ declares no path (its data is named by its metadata), and a `struct` holding
168
+ one declares only its other entries' paths, so while `on` holds such a read
169
+ the value is worked out on every read. Name the store's field,
170
+ `App.model.remote`, in `on` in its place, reading the Remote read inside
171
+ `derive`, and the value is kept while the store holds. A new result
172
+ with the same fields as the last (shallowly) gives the last back, so a memo
173
+ keyed on it downstream holds. It keeps one result, the one for the Model it
174
+ was last given, and an empty `on` throws, since nothing could tell it to work
175
+ the value out again. What it returns is `{ dependencies, read }`, which
176
+ `foldkit-mixins`' `SlotView.region` takes, and a region uses the same rule.
177
+
147
178
  ### Metadata
148
179
 
149
180
  `Metadata` is [`foldkit-metadata`](../metadata/README.md), re-exported so an
@@ -253,7 +284,7 @@ const TodoDetail = App.surface('TodoDetail', {
253
284
  // A parameterized Surface may read `params`; dynamic lookups are OptionalRefs.
254
285
  const ById = App.surface('ById', {
255
286
  params: { id: Schema.String },
256
- model: ({ model, params }) => ({ todo: model.todosById.at(params.id) }),
287
+ model: ({ model, params }) => ({ todo: ModelRef.focus(model.todosById).at(params.id) }),
257
288
  })
258
289
 
259
290
  Surface.read(TodoDetail, root) // project purely
@@ -265,7 +296,9 @@ Surface.rootView(TodoDetail, undefined, render) // bound to the app root
265
296
  The Surface's Model is the projected value (`{ todos; selectedTodoId }`), its
266
297
  Params the fields, and its Message the union of the constructors listed; a
267
298
  constructor from another application is a compile error at the constructor.
268
- A parameterized Surface's projection is not evaluated until it has params.
299
+ A parameterized Surface's projection is not evaluated until it has params:
300
+ `Surface.read(ById, root)` without them is a type error, and a caller the types
301
+ do not reach is refused with an error naming the Surface.
269
302
 
270
303
  `Surface.at(surface, params)` is the Surface as the Model activates it: `params`
271
304
  is the value, or a function of the Model returning it as an `Option` (none while
@@ -321,6 +354,62 @@ recorded by two replication contracts, and a path or Message the application
321
354
  does not declare. `Module.add(module, ...more)` returns a new Module, so feature
322
355
  modules can contribute their contracts independently.
323
356
 
357
+ ## Diagnostics
358
+
359
+ `Diagnostics` is the one channel every Foldkit Plus package reports into what
360
+ it met and kept going past: a fallback, a refusal it answered generically, a
361
+ failure it swallowed, a check run in development. This package owns the
362
+ channel, not the reports: each package declares its own variants on the base
363
+ `Diagnostic` (`_tag`, `source`, `level`, `message`) and lists them in its
364
+ README.
365
+
366
+ A report goes to the `Diagnostics.Reporter` in the Effect context, which by
367
+ default is Effect's log at the diagnostic's level (an `error` reaches
368
+ `console.error`, or stderr on a server). Replace it to send reports elsewhere,
369
+ and collect them in a test:
370
+
371
+ ```ts
372
+ import { Effect, Layer } from 'effect'
373
+ import { Diagnostics, type Diagnostic } from 'foldkit-surface'
374
+
375
+ declare const send: (diagnostic: Diagnostic) => Effect.Effect<void>
376
+
377
+ // In a browser runtime's `resources`: log as before, and send.
378
+ const reporting = Diagnostics.layer(diagnostic =>
379
+ Effect.andThen(Diagnostics.log(diagnostic), send(diagnostic)),
380
+ )
381
+
382
+ // On a server, where no Mount runs, the reporter alone is enough.
383
+ const onServer = Layer.succeed(Diagnostics.Reporter, Diagnostics.log)
384
+
385
+ // In a test: provide `report`, then assert on `reported`.
386
+ const { report, reported } = Diagnostics.collect()
387
+ const inTest = Layer.succeed(Diagnostics.Reporter, report)
388
+ ```
389
+
390
+ `Diagnostics.report(diagnostic)` reports one and never fails: a reporter that
391
+ breaks is logged with what it was given.
392
+
393
+ **Mounts.** Foldkit runs a Mount in the runtime's own context, not its
394
+ `resources`, so a reporter there reaches Commands and Subscriptions but no
395
+ Mount. A Mount reports with `Diagnostics.dispatch(element, diagnostic)`
396
+ instead: a `DiagnosticEvent` at its element, which `Diagnostics.layer(reporter)`
397
+ claims for `reporter` while the runtime holds its resources. Nothing claims it
398
+ on a page without that layer, and it goes to the reporter in context, the log.
399
+ Two limits: Foldkit builds `resources` at the first Command or Subscription
400
+ (before `init` with Flags), so a Mount that fails earlier is logged; and with
401
+ two runtimes in one document, the first to build its resources claims both
402
+ runtimes' events. Only events `foldkit-surface` built are claimed, so a script
403
+ dispatching a `foldkit-diagnostic` event cannot reach your reporter.
404
+
405
+ **Production.** The default is the same in every build: this package cannot
406
+ tell a production build from a development one in every bundler. A page that
407
+ should not show warnings (which ask a developer to change something) chooses
408
+ `Diagnostics.quiet`, which logs errors and drops warnings, where it knows its
409
+ mode: `Diagnostics.layer(import.meta.env.DEV ? Diagnostics.log : Diagnostics.quiet)`.
410
+ In development, `foldkit-mixins`' `DevOverlay` lists what was reported on the
411
+ page.
412
+
324
413
  ## Advanced: how this relates to Optics and Submodels
325
414
 
326
415
  Surface sits near two existing ideas in Effect and Foldkit, so the overlap is
@@ -351,10 +440,10 @@ application with a `filter` field and an already-decoded `restoredFilter`:
351
440
  modifyFields(model, { filter: () => 'active' })
352
441
 
353
442
  // structural addressing
354
- App.model.filter.get(model)
443
+ ModelRef.focus(App.model.filter).get(model)
355
444
 
356
445
  // infrastructure installation
357
- App.model.filter.set(model, restoredFilter)
446
+ ModelRef.focus(App.model.filter).set(model, restoredFilter)
358
447
  ```
359
448
 
360
449
  ### Surface builds on Optics rather than replacing them
@@ -516,6 +605,8 @@ that may observe across those runtime boundaries without creating another one.
516
605
  - Typed Message subsets (`MessageSet.make`, `MessageSet.union`).
517
606
  - Actions (`Action.define`, `Action.run`): a named capability ending in a Message.
518
607
  - Named Surfaces and their renderer binding.
608
+ - The `Diagnostics` channel and its default reporter; each package owns its own
609
+ variants.
519
610
 
520
611
  ## Limits
521
612
 
@@ -0,0 +1,63 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ /**
3
+ * A fallback, refusal or swallowed failure, as the package that met it
4
+ * reports it. A package's own variants extend this with a literal `_tag` and
5
+ * the typed facts behind `message`.
6
+ */
7
+ export interface Diagnostic {
8
+ readonly _tag: string;
9
+ /** The package that met it, as published: `foldkit-remote`. */
10
+ readonly source: string;
11
+ /** `error` when something broke on this side; `warning` when the application should change something. */
12
+ readonly level: 'warning' | 'error';
13
+ /** What happened and what to do about it, for a log. */
14
+ readonly message: string;
15
+ }
16
+ /** Where diagnostics go. It should not fail; when it does, `Diagnostics.report` logs that it did. */
17
+ export type ReportDiagnostic = (diagnostic: Diagnostic) => Effect.Effect<void>;
18
+ /** Reports one diagnostic. Never fails: a reporter that breaks is logged, with what it was given. */
19
+ declare const report: (diagnostic: Diagnostic) => Effect.Effect<void>;
20
+ /**
21
+ * A diagnostic handed to the document by code the application's context does
22
+ * not reach, for `Diagnostics.layer` to claim. Only events of this class are
23
+ * claimed: any script can dispatch an event named `foldkit-diagnostic`.
24
+ */
25
+ declare class DiagnosticEvent extends Event {
26
+ readonly diagnostic: Diagnostic;
27
+ constructor(diagnostic: Diagnostic);
28
+ }
29
+ /**
30
+ * Reports `diagnostic` from code the application's context does not reach (a
31
+ * Mount, which Foldkit runs outside `resources`): a `DiagnosticEvent` at
32
+ * `element`, or at its document once the element has left it, where nothing
33
+ * would hear it. Unclaimed, it goes to the reporter in context.
34
+ */
35
+ declare const dispatch: (element: Element, diagnostic: Diagnostic) => Effect.Effect<void>;
36
+ export declare const Diagnostics: {
37
+ Reporter: Context.Reference<ReportDiagnostic>;
38
+ report: typeof report;
39
+ /**
40
+ * `reporter` as the reporter, hearing what Mounts report too: in a document,
41
+ * it claims each `DiagnosticEvent` while the layer is built. Give it in a
42
+ * runtime's resources. Foldkit builds those at the first Command or
43
+ * Subscription (before `init` with Flags); a Mount failing earlier goes to
44
+ * the default log.
45
+ */
46
+ layer: (reporter: ReportDiagnostic) => Layer.Layer<never>;
47
+ dispatch: typeof dispatch;
48
+ DiagnosticEvent: typeof DiagnosticEvent;
49
+ /** For a production page: errors as `log` writes them, warnings dropped. */
50
+ quiet: ReportDiagnostic;
51
+ /** The default reporter, to compose with another: `d => Effect.andThen(Diagnostics.log(d), send(d))`. */
52
+ log: ReportDiagnostic;
53
+ /**
54
+ * A reporter that keeps what it is given, for a test: provide `report`, then
55
+ * assert on `reported`, `[]` included.
56
+ */
57
+ collect: () => {
58
+ readonly report: ReportDiagnostic;
59
+ readonly reported: ReadonlyArray<Diagnostic>;
60
+ };
61
+ };
62
+ export {};
63
+ //# sourceMappingURL=diagnostics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../src/diagnostics.ts"],"mappings":";;;;;;iBAciB;WACN;;WAEA;;WAEA;;WAEA;;;YAIC,oBAAoB,YAAY,eAAe,OAAO;;cA8B5D,SAAM,YAAgB,eAAa,OAAO;;;;;;cAoB1C,wBAAwB;WACnB,YAAY;EACrB,YAAY,YAAY;;;;;;;;cAYpB,WAAQ,SAAa,SAAO,YAAc,eAAa,OAAO;qBAyBvD;;;;;;;;;;EAUO,QAAA,UAAA,qBAAmB,MAAM;;;;;;;;;;;EAY9B;aACF,QAAQ;aACR,UAAU,cAAc"}
@@ -0,0 +1,104 @@
1
+ import { Cause, Context, Effect, Layer, Logger } from "effect";
2
+ // src/diagnostics.ts
3
+ /**
4
+ * The one channel for what a package met and did not fail on: a fallback, a
5
+ * refusal it answered generically, a failure it swallowed, a check run in
6
+ * development. Each package names its own variants; every one is reported
7
+ * through the `Diagnostics.Reporter` in the Effect context, which logs by
8
+ * default.
9
+ */
10
+ /**
11
+ * Effect's default logger writes every level with `console.log` unless
12
+ * `LogToStderr` is set, so an error would never reach `console.error`, where a
13
+ * browser, an end-to-end check and a Worker's tail look for one (#272). A
14
+ * replaced logger gets the entry at its level and decides for itself.
15
+ */
16
+ const logError = (text) => Effect.provideService(Effect.logError(text), Logger.LogToStderr, true);
17
+ /**
18
+ * Effect's log at the diagnostic's level. With Effect's default logger an
19
+ * error goes to `console.error` (stderr on a server) and a warning to
20
+ * `console.log`.
21
+ */
22
+ const log = (diagnostic) => {
23
+ const text = `[${diagnostic.source}] ${diagnostic.message}`;
24
+ return diagnostic.level === "error" ? logError(text) : Effect.logWarning(text);
25
+ };
26
+ /**
27
+ * The reporter in effect. Provide another with `Layer.succeed(Diagnostics.Reporter, report)`
28
+ * (a Foldkit runtime's resources, a server's layer) or `Effect.provideService`.
29
+ */
30
+ const Reporter = Context.Reference("foldkit-surface/Diagnostics", { defaultValue: () => log });
31
+ /** Reports one diagnostic. Never fails: a reporter that breaks is logged, with what it was given. */
32
+ const report = (diagnostic) => Effect.flatMap(Effect.service(Reporter), (reporter) => reporter(diagnostic)).pipe(Effect.catchCause((cause) => logError(`[foldkit-surface] the diagnostics reporter broke on: [${diagnostic.source}] ${diagnostic.message}\n${Cause.pretty(cause)}`)));
33
+ /** Errors as `log` writes them; warnings, which ask a developer to change something, dropped. */
34
+ const quiet = (diagnostic) => diagnostic.level === "error" ? log(diagnostic) : Effect.void;
35
+ const eventType = "foldkit-diagnostic";
36
+ /**
37
+ * A diagnostic handed to the document by code the application's context does
38
+ * not reach, for `Diagnostics.layer` to claim. Only events of this class are
39
+ * claimed: any script can dispatch an event named `foldkit-diagnostic`.
40
+ */
41
+ var DiagnosticEvent = class extends Event {
42
+ diagnostic;
43
+ constructor(diagnostic) {
44
+ super(eventType, {
45
+ bubbles: true,
46
+ composed: true,
47
+ cancelable: true
48
+ });
49
+ this.diagnostic = diagnostic;
50
+ }
51
+ };
52
+ /**
53
+ * Reports `diagnostic` from code the application's context does not reach (a
54
+ * Mount, which Foldkit runs outside `resources`): a `DiagnosticEvent` at
55
+ * `element`, or at its document once the element has left it, where nothing
56
+ * would hear it. Unclaimed, it goes to the reporter in context.
57
+ */
58
+ const dispatch = (element, diagnostic) => Effect.suspend(() => {
59
+ return (element.isConnected ? element : element.ownerDocument).dispatchEvent(new DiagnosticEvent(diagnostic)) ? report(diagnostic) : Effect.void;
60
+ });
61
+ /** While its scope is open, claims each unclaimed `DiagnosticEvent` in the document for `reporter`. */
62
+ const claim = (reporter) => typeof document === "undefined" ? Effect.void : Effect.asVoid(Effect.acquireRelease(Effect.sync(() => {
63
+ const listener = (event) => {
64
+ if (!(event instanceof DiagnosticEvent) || event.defaultPrevented) return;
65
+ event.preventDefault();
66
+ Effect.runFork(Effect.provideService(report(event.diagnostic), Reporter, reporter));
67
+ };
68
+ document.addEventListener(eventType, listener);
69
+ return listener;
70
+ }), (listener) => Effect.sync(() => document.removeEventListener(eventType, listener))));
71
+ const Diagnostics = {
72
+ Reporter,
73
+ report,
74
+ /**
75
+ * `reporter` as the reporter, hearing what Mounts report too: in a document,
76
+ * it claims each `DiagnosticEvent` while the layer is built. Give it in a
77
+ * runtime's resources. Foldkit builds those at the first Command or
78
+ * Subscription (before `init` with Flags); a Mount failing earlier goes to
79
+ * the default log.
80
+ */
81
+ layer: (reporter) => Layer.merge(Layer.succeed(Reporter, reporter), Layer.effectDiscard(claim(reporter))),
82
+ dispatch,
83
+ DiagnosticEvent,
84
+ /** For a production page: errors as `log` writes them, warnings dropped. */
85
+ quiet,
86
+ /** The default reporter, to compose with another: `d => Effect.andThen(Diagnostics.log(d), send(d))`. */
87
+ log,
88
+ /**
89
+ * A reporter that keeps what it is given, for a test: provide `report`, then
90
+ * assert on `reported`, `[]` included.
91
+ */
92
+ collect: () => {
93
+ const reported = [];
94
+ return {
95
+ reported,
96
+ report: (diagnostic) => Effect.sync(() => {
97
+ reported.push(diagnostic);
98
+ })
99
+ };
100
+ }
101
+ };
102
+ export { Diagnostics };
103
+
104
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * The one channel for what a package met and did not fail on: a fallback, a\n * refusal it answered generically, a failure it swallowed, a check run in\n * development. Each package names its own variants; every one is reported\n * through the `Diagnostics.Reporter` in the Effect context, which logs by\n * default.\n */\nimport { Cause, Context, Effect, Layer, Logger, type Scope } from 'effect'\n\n/**\n * A fallback, refusal or swallowed failure, as the package that met it\n * reports it. A package's own variants extend this with a literal `_tag` and\n * the typed facts behind `message`.\n */\nexport interface Diagnostic {\n readonly _tag: string\n /** The package that met it, as published: `foldkit-remote`. */\n readonly source: string\n /** `error` when something broke on this side; `warning` when the application should change something. */\n readonly level: 'warning' | 'error'\n /** What happened and what to do about it, for a log. */\n readonly message: string\n}\n\n/** Where diagnostics go. It should not fail; when it does, `Diagnostics.report` logs that it did. */\nexport type ReportDiagnostic = (diagnostic: Diagnostic) => Effect.Effect<void>\n\n/**\n * Effect's default logger writes every level with `console.log` unless\n * `LogToStderr` is set, so an error would never reach `console.error`, where a\n * browser, an end-to-end check and a Worker's tail look for one (#272). A\n * replaced logger gets the entry at its level and decides for itself.\n */\nconst logError = (text: string): Effect.Effect<void> =>\n Effect.provideService(Effect.logError(text), Logger.LogToStderr, true)\n\n/**\n * Effect's log at the diagnostic's level. With Effect's default logger an\n * error goes to `console.error` (stderr on a server) and a warning to\n * `console.log`.\n */\nconst log: ReportDiagnostic = diagnostic => {\n const text = `[${diagnostic.source}] ${diagnostic.message}`\n return diagnostic.level === 'error' ? logError(text) : Effect.logWarning(text)\n}\n\n/**\n * The reporter in effect. Provide another with `Layer.succeed(Diagnostics.Reporter, report)`\n * (a Foldkit runtime's resources, a server's layer) or `Effect.provideService`.\n */\nconst Reporter = Context.Reference<ReportDiagnostic>('foldkit-surface/Diagnostics', {\n defaultValue: () => log,\n})\n\n/** Reports one diagnostic. Never fails: a reporter that breaks is logged, with what it was given. */\nconst report = (diagnostic: Diagnostic): Effect.Effect<void> =>\n Effect.flatMap(Effect.service(Reporter), reporter => reporter(diagnostic)).pipe(\n Effect.catchCause(cause =>\n logError(\n `[foldkit-surface] the diagnostics reporter broke on: [${diagnostic.source}] ${diagnostic.message}\\n${Cause.pretty(cause)}`,\n ),\n ),\n )\n\n/** Errors as `log` writes them; warnings, which ask a developer to change something, dropped. */\nconst quiet: ReportDiagnostic = diagnostic =>\n diagnostic.level === 'error' ? log(diagnostic) : Effect.void\n\nconst eventType = 'foldkit-diagnostic'\n\n/**\n * A diagnostic handed to the document by code the application's context does\n * not reach, for `Diagnostics.layer` to claim. Only events of this class are\n * claimed: any script can dispatch an event named `foldkit-diagnostic`.\n */\nclass DiagnosticEvent extends Event {\n readonly diagnostic: Diagnostic\n constructor(diagnostic: Diagnostic) {\n super(eventType, { bubbles: true, composed: true, cancelable: true })\n this.diagnostic = diagnostic\n }\n}\n\n/**\n * Reports `diagnostic` from code the application's context does not reach (a\n * Mount, which Foldkit runs outside `resources`): a `DiagnosticEvent` at\n * `element`, or at its document once the element has left it, where nothing\n * would hear it. Unclaimed, it goes to the reporter in context.\n */\nconst dispatch = (element: Element, diagnostic: Diagnostic): Effect.Effect<void> =>\n Effect.suspend(() => {\n const target = element.isConnected ? element : element.ownerDocument\n return target.dispatchEvent(new DiagnosticEvent(diagnostic)) ? report(diagnostic) : Effect.void\n })\n\n/** While its scope is open, claims each unclaimed `DiagnosticEvent` in the document for `reporter`. */\nconst claim = (reporter: ReportDiagnostic): Effect.Effect<void, never, Scope.Scope> =>\n typeof document === 'undefined'\n ? Effect.void\n : Effect.asVoid(\n Effect.acquireRelease(\n Effect.sync(() => {\n const listener = (event: Event) => {\n if (!(event instanceof DiagnosticEvent) || event.defaultPrevented) return\n event.preventDefault()\n Effect.runFork(Effect.provideService(report(event.diagnostic), Reporter, reporter))\n }\n document.addEventListener(eventType, listener)\n return listener\n }),\n listener => Effect.sync(() => document.removeEventListener(eventType, listener)),\n ),\n )\n\nexport const Diagnostics = {\n Reporter,\n report,\n /**\n * `reporter` as the reporter, hearing what Mounts report too: in a document,\n * it claims each `DiagnosticEvent` while the layer is built. Give it in a\n * runtime's resources. Foldkit builds those at the first Command or\n * Subscription (before `init` with Flags); a Mount failing earlier goes to\n * the default log.\n */\n layer: (reporter: ReportDiagnostic): Layer.Layer<never> =>\n Layer.merge(Layer.succeed(Reporter, reporter), Layer.effectDiscard(claim(reporter))),\n dispatch,\n DiagnosticEvent,\n /** For a production page: errors as `log` writes them, warnings dropped. */\n quiet,\n /** The default reporter, to compose with another: `d => Effect.andThen(Diagnostics.log(d), send(d))`. */\n log,\n /**\n * A reporter that keeps what it is given, for a test: provide `report`, then\n * assert on `reported`, `[]` included.\n */\n collect: (): {\n readonly report: ReportDiagnostic\n readonly reported: ReadonlyArray<Diagnostic>\n } => {\n const reported: Array<Diagnostic> = []\n return {\n reported,\n report: diagnostic =>\n Effect.sync(() => {\n reported.push(diagnostic)\n }),\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiCA,MAAM,YAAY,SAChB,OAAO,eAAe,OAAO,SAAS,IAAI,GAAG,OAAO,aAAa,IAAI;;;;;;AAOvE,MAAM,OAAwB,eAAc;CAC1C,MAAM,OAAO,IAAI,WAAW,OAAO,IAAI,WAAW;CAClD,OAAO,WAAW,UAAU,UAAU,SAAS,IAAI,IAAI,OAAO,WAAW,IAAI;AAC/E;;;;;AAMA,MAAM,WAAW,QAAQ,UAA4B,+BAA+B,EAClF,oBAAoB,IACtB,CAAC;;AAGD,MAAM,UAAU,eACd,OAAO,QAAQ,OAAO,QAAQ,QAAQ,IAAG,aAAY,SAAS,UAAU,CAAC,CAAC,CAAC,KACzE,OAAO,YAAW,UAChB,SACE,yDAAyD,WAAW,OAAO,IAAI,WAAW,QAAQ,IAAI,MAAM,OAAO,KAAK,GAC1H,CACF,CACF;;AAGF,MAAM,SAA0B,eAC9B,WAAW,UAAU,UAAU,IAAI,UAAU,IAAI,OAAO;AAE1D,MAAM,YAAY;;;;;;AAOlB,IAAM,kBAAN,cAA8B,MAAM;CAClC;CACA,YAAY,YAAwB;EAClC,MAAM,WAAW;GAAE,SAAS;GAAM,UAAU;GAAM,YAAY;EAAK,CAAC;EACpE,KAAK,aAAa;CACpB;AACF;;;;;;;AAQA,MAAM,YAAY,SAAkB,eAClC,OAAO,cAAc;CAEnB,QADe,QAAQ,cAAc,UAAU,QAAQ,cAAA,CACzC,cAAc,IAAI,gBAAgB,UAAU,CAAC,IAAI,OAAO,UAAU,IAAI,OAAO;AAC7F,CAAC;;AAGH,MAAM,SAAS,aACb,OAAO,aAAa,cAChB,OAAO,OACP,OAAO,OACL,OAAO,eACL,OAAO,WAAW;CAChB,MAAM,YAAY,UAAiB;EACjC,IAAI,EAAE,iBAAiB,oBAAoB,MAAM,kBAAkB;EACnE,MAAM,eAAe;EACrB,OAAO,QAAQ,OAAO,eAAe,OAAO,MAAM,UAAU,GAAG,UAAU,QAAQ,CAAC;CACpF;CACA,SAAS,iBAAiB,WAAW,QAAQ;CAC7C,OAAO;AACT,CAAC,IACD,aAAY,OAAO,WAAW,SAAS,oBAAoB,WAAW,QAAQ,CAAC,CACjF,CACF;AAEN,MAAa,cAAc;CACzB;CACA;;;;;;;;CAQA,QAAQ,aACN,MAAM,MAAM,MAAM,QAAQ,UAAU,QAAQ,GAAG,MAAM,cAAc,MAAM,QAAQ,CAAC,CAAC;CACrF;CACA;;CAEA;;CAEA;;;;;CAKA,eAGK;EACH,MAAM,WAA8B,CAAC;EACrC,OAAO;GACL;GACA,SAAQ,eACN,OAAO,WAAW;IAChB,SAAS,KAAK,UAAU;GAC1B,CAAC;EACL;CACF;AACF"}
@@ -1,65 +1,106 @@
1
1
  import { Optic, Option, Result, Schema } from "effect";
2
2
  import { Metadata, Metadata as Metadata$1, MetadataKey, MetadataSummary, MetadataSummary as MetadataSummary$1, MetadataTypeId } from "foldkit-metadata";
3
+ import { Diagnostic, Diagnostics, ReportDiagnostic } from "./diagnostics.js";
3
4
  import { Html, HtmlBuilder } from "foldkit/html";
4
5
  import { MessageUnion } from "foldkit/message";
5
6
  import { Entry } from "foldkit/managedResource";
6
7
  import { Subscriptions } from "foldkit/subscription";
7
8
  import * as Update from "foldkit/update";
8
9
  import { Url } from "foldkit/url";
9
- //#region src/index.d.ts
10
- export interface ModelRef<Root, Value, Encoded = unknown> {
10
+ /**
11
+ * The key a ref keeps its own members under; read them with `ModelRef.focus`.
12
+ * A ref's string keys are the Model's fields, whatever their names (#331),
13
+ * and no Schema field reaches a symbol. `Symbol.for`, so two copies of this
14
+ * package read each other's refs.
15
+ */
16
+ export declare const RefTypeId: unique symbol;
17
+ /** What a ref points at and how to read and write it: `ModelRef.focus(ref)`. */
18
+ export interface Focus<Root, Value, Encoded = unknown> {
11
19
  /** A pure codec: Foldkit Model fields carry no decoding or encoding services. */
12
20
  readonly Schema: Schema.Codec<Value, Encoded, never, never>;
13
21
  readonly optic: Optic.Optional<Root, Value>;
22
+ /** The Model path the ref points at. */
14
23
  readonly dependency: readonly string[];
15
24
  readonly get: (root: Root) => Value;
16
25
  readonly set: (root: Root, value: Value) => Root;
17
26
  /**
18
27
  * Focused structural replacement: `set` of `fn` applied to `get`. This
19
- * delegates through the ref's own `set`, so container-aware setters
20
- * (`.at`/`.index` insertion and removal) keep working — never `optic`
28
+ * delegates through the focus's own `set`, so container-aware setters
29
+ * (`at`/`index` insertion and removal) keep working — never `optic`
21
30
  * calls directly. Infrastructure seam, not an application transition.
22
31
  */
23
32
  readonly modify: (root: Root, fn: (value: Value) => Value) => Root;
24
33
  }
34
+ /**
35
+ * A reference to a place in the Model. Its string keys are the fields below
36
+ * it; its own members are its `Focus`, read with `ModelRef.focus`.
37
+ */
38
+ export interface ModelRef<Root, Value, Encoded = unknown> {
39
+ readonly [RefTypeId]: Focus<Root, Value, Encoded>;
40
+ }
25
41
  /**
26
42
  * A `ModelRef` generated for a named Model field. `key` is the literal field
27
43
  * name, so a reference-based selection can infer its output keys without a
28
44
  * parallel field registry or string paths.
29
45
  */
30
46
  export interface FieldRef<Root, Value, Key extends string = string, Encoded = unknown> extends ModelRef<Root, Value, Encoded> {
31
- readonly key: Key;
32
- /** The application definition this field was generated from. */
33
- readonly owner: object;
47
+ readonly [RefTypeId]: Focus<Root, Value, Encoded> & {
48
+ readonly key: Key;
49
+ /** The application definition this field was generated from. */
50
+ readonly owner: object;
51
+ };
34
52
  }
35
- /**
36
- * Low-level escape hatch for a focus with no Model path of its own. Prefer the
37
- * `App.model` tree; use this for an optic that is not part of the Model.
38
- */
39
53
  export declare const ModelRef: {
54
+ /**
55
+ * Low-level escape hatch for a focus with no Model path of its own. Prefer
56
+ * the `App.model` tree; use this for an optic that is not part of the Model.
57
+ */
40
58
  fromOptic: <Root, Value>(Schema: Schema.Schema<Value>, optic: Optic.Optional<Root, Value>, dependency?: readonly string[]) => ModelRef<Root, Value>;
59
+ /**
60
+ * A ref's own members: where it points, how to read and write it, and, as
61
+ * its value allows, `at` (a record), `index` (an array) and `select`. They
62
+ * are kept apart from the ref's string keys, which are the Model's fields.
63
+ */
64
+ focus: <R extends {
65
+ readonly [RefTypeId]: object;
66
+ }>(ref: R) => R[typeof RefTypeId];
67
+ /** Whether a value is a ref, as opposed to a Projection or a plain object. */
68
+ is: (value: unknown) => value is ModelRef<unknown, unknown>;
41
69
  };
42
70
  export type RefTree<Root, F extends Schema.Struct.Fields> = { readonly [K in keyof F & string]: RefNode<Root, F[K], K>; };
43
- type Selectable<Root, Value, Key extends string, Encoded = unknown> = [Value] extends [Option.Option<infer Inner>] ? FieldRef<Root, Value, Key, Encoded> & {
44
- readonly select: <P>(projection: Projection<Inner, P>) => Projection<Root, Option.Option<P>>;
45
- } : FieldRef<Root, Value, Key, Encoded> & {
46
- readonly select: <P>(projection: Projection<Value, P>) => Projection<Root, P>;
47
- };
71
+ /** A ref whose focus can `select` a Projection of its value. */
72
+ export interface Selects<Root, Value> {
73
+ readonly [RefTypeId]: {
74
+ readonly select: <P>(projection: Projection<Value, P>) => Projection<Root, P>;
75
+ };
76
+ }
77
+ /** A ref to an optional value, whose focus selects inside the Option. */
78
+ export interface SelectsSome<Root, Inner> {
79
+ readonly [RefTypeId]: {
80
+ readonly select: <P>(projection: Projection<Inner, P>) => Projection<Root, Option.Option<P>>;
81
+ };
82
+ }
83
+ /** A ref to an array, whose focus reaches an item: `ModelRef.focus(ref).index(0)`. */
84
+ export interface Indexes<Root, Item> {
85
+ readonly [RefTypeId]: {
86
+ readonly index: (index: number) => OptionalRef<Root, Option.Option<Item>>;
87
+ };
88
+ }
89
+ /** A ref to a record, whose focus reaches an entry: `ModelRef.focus(ref).at(key)`. */
90
+ export interface Entries<Root, Key extends string, Value> {
91
+ readonly [RefTypeId]: {
92
+ readonly at: (key: Key) => OptionalRef<Root, Option.Option<Value>>;
93
+ };
94
+ }
95
+ type Select<Root, Value> = [Value] extends [Option.Option<infer Inner>] ? SelectsSome<Root, Inner> : Selects<Root, Value>;
96
+ type Selectable<Root, Value, Key extends string, Encoded = unknown> = FieldRef<Root, Value, Key, Encoded> & Select<Root, Value>;
48
97
  /**
49
- * A dynamic focus from `.at`/`.index`. Deliberately not a `FieldRef`: its key is
50
- * a record key or index, not a Model field, so a static `Projection.pick` cannot
51
- * infer a field name from it.
98
+ * A dynamic focus from `at`/`index`. Deliberately not a `FieldRef`: its key is
99
+ * a record key or index, not a Model field, so a static `Projection.pick`
100
+ * cannot infer a field name from it.
52
101
  */
53
- type OptionalRef<Root, Value> = [Value] extends [Option.Option<infer Inner>] ? ModelRef<Root, Value> & {
54
- readonly select: <P>(projection: Projection<Inner, P>) => Projection<Root, Option.Option<P>>;
55
- } : ModelRef<Root, Value> & {
56
- readonly select: <P>(projection: Projection<Value, P>) => Projection<Root, P>;
57
- };
58
- type RefNode<Root, S, Key extends string> = S extends Schema.Codec<infer A, infer Encoded, any, any> ? S extends Schema.Struct<infer F> ? Selectable<Root, A, Key, Encoded> & RefTree<Root, F> : A extends ReadonlyArray<infer E> ? Selectable<Root, A, Key, Encoded> & {
59
- readonly index: (index: number) => OptionalRef<Root, Option.Option<E>>;
60
- } : A extends Readonly<Record<infer K extends string, infer V>> ? Selectable<Root, A, Key, Encoded> & {
61
- readonly at: (key: K) => OptionalRef<Root, Option.Option<V>>;
62
- } : Selectable<Root, A, Key, Encoded> : never;
102
+ export type OptionalRef<Root, Value> = ModelRef<Root, Value> & Select<Root, Value>;
103
+ type RefNode<Root, S, Key extends string> = S extends Schema.Codec<infer A, infer Encoded, any, any> ? S extends Schema.Struct<infer F> ? Selectable<Root, A, Key, Encoded> & RefTree<Root, F> : A extends ReadonlyArray<infer E> ? Selectable<Root, A, Key, Encoded> & Indexes<Root, E> : A extends Readonly<Record<infer K extends string, infer V>> ? Selectable<Root, A, Key, Encoded> & Entries<Root, K, V> : Selectable<Root, A, Key, Encoded> : never;
63
104
  export type DependencyTree = readonly (readonly string[])[];
64
105
  export interface Projection<Root, Value> {
65
106
  readonly Model: Schema.Codec<Value, unknown>;
@@ -88,6 +129,11 @@ type EntryRoots<Entries> = { readonly [K in keyof Entries]: EntryRoot<Entries[K]
88
129
  /** `true` when the union has more than one member. Used to reject mixed roots. */
89
130
  type IsUnion<T, U = T> = [T] extends [never] ? false : T extends unknown ? [U] extends [T] ? false : true : never;
90
131
  type StructValue<Entries> = { readonly [K in keyof Entries]: EntryValue<Entries[K]>; } extends (infer Value) ? { readonly [K in keyof Value]: Value[K]; } : never;
132
+ /** A value derived from the Model and the paths it reads: what `Projection.derive` makes. */
133
+ export interface Derived<Root, Value> {
134
+ readonly dependencies: DependencyTree;
135
+ readonly read: (root: Root) => Value;
136
+ }
91
137
  export declare const Projection: {
92
138
  of: <F extends Schema.Struct.Fields>(schema: Schema.Struct<F>) => <const Sel extends OfSelection<F>>(selection: Sel) => Projection<Schema.Struct.Type<F>, OfValue<F, Sel>>;
93
139
  struct: <const Entries extends Record<string, Projection<any, any> | ModelRef<any, any>>>(entries: Entries & (IsUnion<EntryRoots<Entries>[keyof Entries]> extends true ? never : unknown)) => Projection<EntryRoot<Entries[keyof Entries]>, StructValue<Entries>>;
@@ -109,6 +155,29 @@ export declare const Projection: {
109
155
  readonly dependencies?: DependencyTree;
110
156
  readonly metadata?: Metadata$1;
111
157
  }) => Projection<Root, Value>;
158
+ /**
159
+ * A value worked out from the Model, and worked out again only when a value
160
+ * at a path it reads is a new object: the value counterpart of
161
+ * `foldkit-mixins`' `SlotView.region`, and what a region can be drawn from.
162
+ * `on` names what `derive` reads, as field references or Projections;
163
+ * `derive` must read nothing else, or it shows what it read last. While
164
+ * something in `on` reads what no path of its names (a Remote read, alone or
165
+ * inside a `struct`), the value is worked out on every read. A result with
166
+ * the same fields as the last, shallowly, gives the last back, so a memo
167
+ * keyed on it holds. It keeps one result: the one for the last Model it was
168
+ * given.
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * const shown = Projection.derive([App.model.todos, App.model.filter], (model: Model) =>
173
+ * model.todos.filter(todo => model.filter === 'all' || todo.done === (model.filter === 'done')),
174
+ * )
175
+ * // In the view: shown.read(model)
176
+ * ```
177
+ */
178
+ derive: <Root, Value>(on: ReadonlyArray<ModelRef<Root, any> | {
179
+ readonly dependencies: DependencyTree;
180
+ }>, derive: (root: Root) => Value) => Derived<Root, Value>;
112
181
  /**
113
182
  * Derives a writable projection from generated Model field references:
114
183
  * `Projection.pick(App.model.todos, App.model.selectedTodoId)` infers
@@ -146,6 +215,11 @@ export interface SurfaceInspection {
146
215
  export type ParamsSchema<Params> = unknown extends Params ? Schema.Codec<Params, unknown> | undefined : [Params] extends [void] ? [void] extends [Params] ? undefined // `undefined` also extends `void`, but a Surface may still declare its schema.
147
216
  : Schema.Codec<Params, unknown> | undefined : [void] extends [Params] // `void | X`: the schema is optional.
148
217
  ? Schema.Codec<Params, unknown> | undefined : Schema.Codec<Params, unknown>;
218
+ /**
219
+ * The params argument of `Surface.read`, `contract` and `inspect`: required
220
+ * unless `undefined` is a params value, as it is for a Surface without params.
221
+ */
222
+ type ParamsArgument<Params> = undefined extends Params ? [params?: Params] : [params: Params];
149
223
  export interface Surface<Root, Model, Message, Params> {
150
224
  readonly name: string;
151
225
  /** Identity token of the application this Surface belongs to. */
@@ -174,21 +248,23 @@ export interface Surface<Root, Model, Message, Params> {
174
248
  * What `Surface.when` needs of a place in the Model: where it is, and how to
175
249
  * read it.
176
250
  *
177
- * The read half of a `ModelRef`, and deliberately not the whole thing.
251
+ * A ref whose focus can be read, and deliberately not a whole `ModelRef`.
178
252
  * Activation **observes** — it never installs a value — so asking for a
179
253
  * writable reference would claim an authority it does not use. It also makes
180
254
  * the common case work: a field holding a tagged union is a *union of*
181
255
  * `FieldRef`s, one per case, which no single `ModelRef<Root, Value>` accepts.
182
256
  */
183
257
  export interface ModelPlace<Root> {
184
- /** Where the value lives, as `ModelRef.dependency` gives it. */
185
- readonly dependency: readonly string[];
186
- readonly get: (root: Root) => unknown;
258
+ readonly [RefTypeId]: {
259
+ /** Where the value lives, as `ModelRef.focus(place).dependency` gives it. */
260
+ readonly dependency: readonly string[];
261
+ readonly get: (root: Root) => unknown;
262
+ };
187
263
  }
188
264
  export interface Activation {
189
- /** The Model path the tagged value lives at, as `ModelRef.dependency` gives it. */
265
+ /** The Model path the tagged value lives at, as a focus's `dependency` gives it. */
190
266
  readonly path: readonly string[];
191
- /** The tag that makes the Surface active. */
267
+ /** The tag the Surface is active under; a Site node reading the viewer waits for one too. */
192
268
  readonly tag: string;
193
269
  }
194
270
  export interface ActiveSurface<Root, Model = unknown> {
@@ -199,7 +275,10 @@ export interface ActiveSurface<Root, Model = unknown> {
199
275
  readonly projectionOf: (model: Root) => Option.Option<Projection<Root, Model>>;
200
276
  /** The tags of the Messages the Surface lists in `messages`: what it may send. */
201
277
  readonly messages: ReadonlyArray<string>;
202
- /** Present when the Surface was placed with `Surface.when`; absent for `Surface.at`. */
278
+ /**
279
+ * Present when a tagged value at a known place activates the Surface
280
+ * (`Surface.when`, or a Site node); absent for a bare `Surface.at`.
281
+ */
203
282
  readonly activation?: Activation | undefined;
204
283
  }
205
284
  /**
@@ -281,7 +360,7 @@ type Subset<Sub, Super> = [Sub] extends [Super] ? unknown : never;
281
360
  type RefRoot<R> = R extends ModelRef<infer Root, any> ? Root : never;
282
361
  type RefRoots<Refs extends readonly unknown[]> = { readonly [K in keyof Refs]: RefRoot<Refs[K]>; };
283
362
  /** The struct fields a reference selection produces, keyed by each ref's field. */
284
- type PickFields<Refs extends readonly FieldRef<any, any, string>[]> = { readonly [R in Refs[number] as R['key']]: R['Schema']; };
363
+ type PickFields<Refs extends readonly FieldRef<any, any, string>[]> = { readonly [R in Refs[number] as R[typeof RefTypeId]['key']]: R[typeof RefTypeId]['Schema']; };
285
364
  type ProjectionModel<P> = P extends WritableProjection<infer M, any> ? M : never;
286
365
  type ProjectionFields<P> = P extends WritableProjection<any, infer F> ? F : never;
287
366
  type Merge2<A, B> = { readonly [K in keyof A | keyof B]: K extends keyof A ? A[K] : K extends keyof B ? B[K] : never; };
@@ -499,7 +578,7 @@ export declare const Surface: {
499
578
  }) => Projection<Root, Model>;
500
579
  readonly messages?: Ms;
501
580
  }) => Surface<Root, Model, MsgOf<Ms>, Params>;
502
- read: <Root, Model, Message, Params>(surface: Surface<Root, Model, Message, Params>, root: Root, params?: Params) => Model;
581
+ read: <Root, Model, Message, Params>(surface: Surface<Root, Model, Message, Params>, root: Root, ...params: ParamsArgument<Params>) => Model;
503
582
  /**
504
583
  * Binds a renderer to a Surface's projected Model and Message set. A
505
584
  * type-level binder: the renderer already has this shape, but `Model` and
@@ -522,12 +601,12 @@ export declare const Surface: {
522
601
  * A Surface as a `Contract` for `Module`: what it observes, requires, and may
523
602
  * emit. A parameterized Surface needs its `params` to build the projection.
524
603
  */
525
- contract: <Root, Model, Message, Params>(surface: Surface<Root, Model, Message, Params>, params: Params) => Contract;
604
+ contract: <Root, Model, Message, Params>(surface: Surface<Root, Model, Message, Params>, ...params: ParamsArgument<Params>) => Contract;
526
605
  /**
527
606
  * Pure introspection for DevTools: what a Surface observes (dependencies,
528
607
  * requirements) and what it may emit. No behavior change, no I/O.
529
608
  */
530
- inspect: <Root, Model, Message, Params>(surface: Surface<Root, Model, Message, Params>, params: Params) => SurfaceInspection;
609
+ inspect: <Root, Model, Message, Params>(surface: Surface<Root, Model, Message, Params>, ...params: ParamsArgument<Params>) => SurfaceInspection;
531
610
  };
532
611
  /**
533
612
  * What one contract claims about an application, as data. Sync, Remote, and
@@ -648,6 +727,5 @@ export declare const Module: {
648
727
  */
649
728
  toMermaid: (module: Module<any, any, any>) => string;
650
729
  };
651
- //#endregion
652
- export { Metadata, type MetadataKey, type MetadataSummary, MetadataTypeId };
653
- //# sourceMappingURL=index.d.mts.map
730
+ export { type Diagnostic, Diagnostics, Metadata, type MetadataKey, type MetadataSummary, MetadataTypeId, type ReportDiagnostic };
731
+ //# sourceMappingURL=index.d.ts.map