@playfast/reform-proof 1.1.1 → 1.2.1

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.
@@ -1,21 +0,0 @@
1
- import { Array as Arr, Order } from 'effect'
2
- import type { TreeFeatureMount } from './runtimeTreeTypes'
3
-
4
- interface DisposeTreeMountsOptions {
5
- readonly status: { disposed: boolean }
6
- readonly mounts: Map<string, TreeFeatureMount>
7
- }
8
-
9
- export const disposeTreeMounts = ({ status, mounts }: DisposeTreeMountsOptions): void => {
10
- if (status.disposed) {
11
- return
12
- }
13
- status.disposed = true
14
- Arr.sortWith(Array.from(mounts.values()), (record) => -record.depth, Order.number).forEach(
15
- (record) => {
16
- record.attempt += 1
17
- record.dispose()
18
- },
19
- )
20
- mounts.clear()
21
- }
@@ -1,285 +0,0 @@
1
- import { Array as Arr, Effect, Match, Option, Order, Record as Rec, Schema as S } from 'effect'
2
- import {
3
- Composition,
4
- type CompositionClass,
5
- isFeatureBinding,
6
- isStructure,
7
- type RenderEnv,
8
- type RuntimeHandle,
9
- } from '@playfast/reform'
10
- import { eventsOf, type Sink, uiNameOf } from './sink'
11
- import { slotsOf, structureFills } from './treeBindings'
12
- import { disposeTreeMounts } from './runtimeTreeDispose'
13
- import { makeTreeSettle } from './runtimeTreeSettle'
14
- import {
15
- encodeIdentityPart,
16
- type FeatureRecordInput,
17
- fillEntries,
18
- type MountIdentityInput,
19
- type RenderCompositionInput,
20
- type TreeDriver,
21
- type TreeFeatureMount,
22
- type TreeNode,
23
- type TreeRenderState,
24
- treeFingerprint,
25
- } from './runtimeTreeTypes'
26
-
27
- const encodeUnknown = S.encodeSync(S.parseJson(S.Unknown))
28
-
29
- export const makeTreeDriver = (
30
- runtime: RuntimeHandle,
31
- root: CompositionClass<unknown>,
32
- sink: Sink,
33
- ): TreeDriver => {
34
- const mounts = new Map<string, TreeFeatureMount>()
35
- const runtimeIds = new WeakMap<RuntimeHandle, number>()
36
- const bindingIds = new WeakMap<object, number>()
37
- const sequence = { runtime: 0, binding: 0 }
38
- const status = { disposed: false }
39
-
40
- const identity = (
41
- identities: WeakMap<object, number>,
42
- subject: object,
43
- next: () => number,
44
- ): number => {
45
- const current = identities.get(subject)
46
- if (current !== undefined) {
47
- return current
48
- }
49
- const created = next()
50
- identities.set(subject, created)
51
- return created
52
- }
53
-
54
- const mountId = ({ parent, parentPath, slotName, key, binding }: MountIdentityInput): string => {
55
- const runtimeId = identity(runtimeIds, parent, () => ++sequence.runtime)
56
- const bindingId = identity(bindingIds, binding, () => ++sequence.binding)
57
- return [String(runtimeId), parentPath, slotName, String(bindingId), key]
58
- .map(encodeIdentityPart)
59
- .join('')
60
- }
61
-
62
- const startMount = (record: TreeFeatureMount): void => {
63
- record.attempt += 1
64
- const attempt = record.attempt
65
- if (record.binding.strategy === 'default') {
66
- record.state = { _tag: 'Live', runtime: record.parent }
67
- record.binding.boot.forEach((event) => record.parent.dispatch('High', event))
68
- record.dispose = () => {}
69
- return
70
- }
71
- record.state = { _tag: 'Loading' }
72
- record.dispose = record.parent.mountFeature(record.binding, {
73
- props: record.props,
74
- onLive: (childRuntime) => {
75
- if (status.disposed || record.attempt !== attempt || mounts.get(record.id) !== record) {
76
- return
77
- }
78
- record.state = { _tag: 'Live', runtime: childRuntime }
79
- },
80
- onFailed: (error) => {
81
- if (status.disposed || record.attempt !== attempt || mounts.get(record.id) !== record) {
82
- return
83
- }
84
- record.state = { _tag: 'Failed', error }
85
- },
86
- })
87
- }
88
-
89
- const retryMount = (record: TreeFeatureMount): void => {
90
- if (status.disposed || mounts.get(record.id) !== record || record.state._tag !== 'Failed') {
91
- return
92
- }
93
- record.dispose()
94
- startMount(record)
95
- }
96
-
97
- const featureRecord = ({
98
- id,
99
- parent,
100
- binding,
101
- depth,
102
- props,
103
- }: FeatureRecordInput): TreeFeatureMount => {
104
- const current = mounts.get(id)
105
- if (current !== undefined && current.binding === binding && current.parent === parent) {
106
- return current
107
- }
108
- if (current !== undefined) {
109
- current.attempt += 1
110
- current.dispose()
111
- }
112
- const created: TreeFeatureMount = {
113
- id,
114
- binding,
115
- parent,
116
- depth,
117
- props,
118
- attempt: 0,
119
- state: { _tag: 'Loading' },
120
- dispose: () => {},
121
- }
122
- mounts.set(id, created)
123
- startMount(created)
124
- return created
125
- }
126
-
127
- const renderComposition = ({
128
- runtime: currentRuntime,
129
- comp,
130
- props,
131
- key,
132
- path,
133
- depth,
134
- seen,
135
- }: RenderCompositionInput): TreeNode => {
136
- const service = currentRuntime.read(comp.tag)
137
- const env: RenderEnv = { props, tracker: { add: () => {} } }
138
- const endRenderSpan = sink.instrumentation.uiRendered(uiNameOf(comp))
139
- const frame = Effect.runSync(Composition.render(service, env))
140
- endRenderSpan()
141
- if (!isStructure(frame)) {
142
- return Effect.runSync(
143
- Effect.dieMessage(`reform-proof: composition ${uiNameOf(comp)} did not return a Structure`),
144
- )
145
- }
146
- sink.api.record({
147
- name: uiNameOf(comp),
148
- props: frame.props,
149
- events: eventsOf(frame),
150
- ...(Option.isSome(key) ? { key: key.value } : {}),
151
- })
152
-
153
- const fills = structureFills(frame)
154
- const renderedSlots = Rec.map(slotsOf(comp), (slotClass, slotName) => {
155
- const fill = fills[slotName]
156
- if (fill === undefined) {
157
- return []
158
- }
159
- const child = currentRuntime.read(slotClass.tag)
160
- return fillEntries(slotName, fill).flatMap((entry) => {
161
- const childPath = `${path}${encodeIdentityPart(slotName)}${encodeIdentityPart(entry.key)}`
162
- if (!isFeatureBinding(child)) {
163
- return [
164
- renderComposition({
165
- runtime: currentRuntime,
166
- comp: child,
167
- props: entry.props,
168
- key: Option.some(entry.key),
169
- path: childPath,
170
- depth: depth + 1,
171
- seen,
172
- }),
173
- ]
174
- }
175
- const id = mountId({
176
- parent: currentRuntime,
177
- parentPath: path,
178
- slotName,
179
- key: entry.key,
180
- binding: child,
181
- })
182
- seen.add(id)
183
- const record = featureRecord({
184
- id,
185
- parent: currentRuntime,
186
- binding: child,
187
- depth: depth + 1,
188
- props: entry.props,
189
- })
190
- return Match.value(record.state).pipe(
191
- Match.when({ _tag: 'Live' }, (live) => [
192
- renderComposition({
193
- runtime: live.runtime,
194
- comp: child.composition,
195
- props: entry.props,
196
- key: Option.some(entry.key),
197
- path: childPath,
198
- depth: depth + 1,
199
- seen,
200
- }),
201
- ]),
202
- Match.when({ _tag: 'Failed' }, (failed) => {
203
- if (child.placeholder === undefined) {
204
- return []
205
- }
206
- return [
207
- renderComposition({
208
- runtime: currentRuntime,
209
- comp: child.placeholder.failed,
210
- props: { error: failed.error, retry: () => retryMount(record) },
211
- key: Option.some(entry.key),
212
- path: `${childPath}/failed`,
213
- depth: depth + 1,
214
- seen,
215
- }),
216
- ]
217
- }),
218
- Match.when({ _tag: 'Loading' }, () => {
219
- if (child.placeholder === undefined) {
220
- return []
221
- }
222
- return [
223
- renderComposition({
224
- runtime: currentRuntime,
225
- comp: child.placeholder.loading,
226
- props: entry.props,
227
- key: Option.some(entry.key),
228
- path: `${childPath}/loading`,
229
- depth: depth + 1,
230
- seen,
231
- }),
232
- ]
233
- }),
234
- Match.exhaustive,
235
- )
236
- })
237
- })
238
-
239
- return {
240
- path,
241
- depth,
242
- key,
243
- comp,
244
- props: frame.props,
245
- events: eventsOf(frame),
246
- slots: renderedSlots,
247
- }
248
- }
249
-
250
- const disposeStale = (seen: ReadonlySet<string>): void => {
251
- Arr.sortWith(
252
- Array.from(mounts.values()).filter((record) => !seen.has(record.id)),
253
- (record) => -record.depth,
254
- Order.number,
255
- ).forEach((record) => {
256
- mounts.delete(record.id)
257
- record.attempt += 1
258
- record.dispose()
259
- })
260
- }
261
-
262
- const render = (): TreeRenderState => {
263
- sink.reset()
264
- const seen = new Set<string>()
265
- const rootNode = renderComposition({
266
- runtime,
267
- comp: root,
268
- props: {},
269
- key: Option.none(),
270
- path: 'root',
271
- depth: 0,
272
- seen,
273
- })
274
- disposeStale(seen)
275
- return {
276
- root: rootNode,
277
- fingerprint: encodeUnknown(treeFingerprint(rootNode)),
278
- }
279
- }
280
-
281
- const settle = makeTreeSettle(render)
282
- const dispose = (): void => disposeTreeMounts({ status, mounts })
283
-
284
- return { render, settle, dispose }
285
- }
@@ -1,134 +0,0 @@
1
- import { Array as Arr, Effect, Option } from 'effect'
2
- import type { CompositionClass, RuntimeHandle } from '@playfast/reform'
3
- import { AssertionFailed, UnknownAction, UnknownSlot } from './errors'
4
- import { matchProps } from './assertions'
5
- import { makeTreeDriver } from './runtimeTreeDriver'
6
- import type { RuntimeTreeFacade, TreeNode } from './runtimeTreeTypes'
7
- import { keyed, type Sink, uiNameOf } from './sink'
8
- import type { MountedFacade, MountedSlotFacade } from './runtimeFacade'
9
-
10
- export type { RuntimeTreeFacade } from './runtimeTreeTypes'
11
-
12
- export const makeRuntimeTreeFacade = (
13
- runtime: RuntimeHandle,
14
- root: CompositionClass<unknown>,
15
- sink: Sink,
16
- dispatched: Set<string>,
17
- ): RuntimeTreeFacade => {
18
- const driver = makeTreeDriver(runtime, root, sink)
19
- const currentRoot = (): TreeNode => driver.render().root
20
-
21
- const nodeFacade = (resolve: () => TreeNode): MountedFacade => ({
22
- props: Effect.sync(() => resolve().props),
23
- expectProps: (partial) =>
24
- Effect.sync(() => {
25
- const mismatch = matchProps({
26
- actual: resolve().props,
27
- expected: partial,
28
- })
29
- if (mismatch !== undefined) {
30
- return Effect.runSync(
31
- Effect.dieMessage(new AssertionFailed({ detail: mismatch }).message),
32
- )
33
- }
34
- }),
35
- actions: keyed(
36
- (event) => (payload: unknown) =>
37
- Effect.gen(function* () {
38
- const node = resolve()
39
- const trigger = node.events[event]
40
- if (trigger === undefined) {
41
- return yield* Effect.dieMessage(
42
- new UnknownAction({
43
- composition: uiNameOf(node.comp),
44
- action: event,
45
- rendered: 1,
46
- }).message,
47
- )
48
- }
49
- dispatched.add(event)
50
- trigger(payload)
51
- yield* driver.settle
52
- return resolve().props
53
- }),
54
- ),
55
- slots: keyed((slotName) => slotFacade(resolve, slotName)),
56
- frame: driver.settle,
57
- })
58
-
59
- const slotFacade = (resolveParent: () => TreeNode, slotName: string): MountedSlotFacade => {
60
- const children = (): ReadonlyArray<TreeNode> => {
61
- const parent = resolveParent()
62
- const resolved = parent.slots[slotName]
63
- if (resolved === undefined) {
64
- return Effect.runSync(
65
- Effect.dieMessage(
66
- new UnknownSlot({ parent: uiNameOf(parent.comp), slot: slotName }).message,
67
- ),
68
- )
69
- }
70
- return resolved
71
- }
72
- const childAt = (index: number): MountedFacade =>
73
- nodeFacade(() => children()[index] ?? missingChild(index))
74
- const childByKey = (key: string): MountedFacade =>
75
- nodeFacade(() => {
76
- return Option.getOrElse(
77
- Arr.findFirst(children(), (candidate) => Option.contains(candidate.key, key)),
78
- () => missingKey(key),
79
- )
80
- })
81
- const missingChild = (index: number): never => {
82
- const parent = resolveParent()
83
- return Effect.runSync(
84
- Effect.dieMessage(
85
- new UnknownSlot({
86
- parent: uiNameOf(parent.comp),
87
- slot: `${slotName}[${index}]`,
88
- }).message,
89
- ),
90
- )
91
- }
92
- const missingKey = (key: string): never => {
93
- const parent = resolveParent()
94
- return Effect.runSync(
95
- Effect.dieMessage(
96
- new UnknownSlot({
97
- parent: uiNameOf(parent.comp),
98
- slot: `${slotName}[key=${key}]`,
99
- }).message,
100
- ),
101
- )
102
- }
103
- const first = childAt(0)
104
- return {
105
- first: Effect.sync(() => childAt(0)),
106
- at: (index) => Effect.sync(() => childAt(index)),
107
- all: Effect.sync(() => children().map((_child, index) => childAt(index))),
108
- byKey: (key) =>
109
- Effect.sync(() => {
110
- const child = Arr.findFirst(children(), (candidate) =>
111
- Option.contains(candidate.key, key),
112
- )
113
- return Option.isNone(child) ? missingKey(key) : childByKey(key)
114
- }),
115
- where: (predicate) =>
116
- Effect.sync(() =>
117
- children().flatMap((child, index) => (predicate(child.props) ? [childAt(index)] : [])),
118
- ),
119
- count: Effect.sync(() => children().length),
120
- props: first.props,
121
- expectProps: first.expectProps,
122
- actions: first.actions,
123
- slots: first.slots,
124
- frame: driver.settle,
125
- }
126
- }
127
-
128
- return {
129
- facade: nodeFacade(currentRoot),
130
- settle: driver.settle,
131
- dispose: driver.dispose,
132
- }
133
- }
134
-
@@ -1,34 +0,0 @@
1
- import { Effect } from 'effect'
2
- import { SETTLE_MAX_RENDERS, SETTLE_STEP, settleDrain } from './sink'
3
- import type { SettleProgress } from './treeBindings'
4
- import type { TreeRenderState } from './runtimeTreeTypes'
5
-
6
- export const makeTreeSettle: (
7
- render: () => TreeRenderState,
8
- ) => Effect.Effect<void, never, never> = Effect.fn('makeTreeSettle')(function* (
9
- render: () => TreeRenderState,
10
- ): Effect.fn.Return<void, never, never> {
11
- yield* settleDrain
12
- const first = render()
13
- yield* Effect.iterate(
14
- {
15
- previous: first.fingerprint,
16
- remaining: SETTLE_MAX_RENDERS,
17
- stable: false,
18
- },
19
- {
20
- while: (progress: SettleProgress) => !progress.stable && progress.remaining > 0,
21
- body: (progress) =>
22
- Effect.gen(function* () {
23
- yield* settleDrain
24
- yield* Effect.sleep(SETTLE_STEP)
25
- const current = render()
26
- return {
27
- previous: current.fingerprint,
28
- remaining: progress.remaining - 1,
29
- stable: current.fingerprint === progress.previous,
30
- }
31
- }),
32
- },
33
- )
34
- })
package/src/sink.ts DELETED
@@ -1,73 +0,0 @@
1
- import { Effect, Layer, MutableRef } from 'effect'
2
- import {
3
- Bus,
4
- CaptureSink,
5
- type CaptureSinkApi,
6
- type CompositionClass,
7
- type CompositionService,
8
- type Instrumentation,
9
- noopInstrumentation,
10
- type Scene,
11
- type SlotChild,
12
- type Structure,
13
- type Trigger,
14
- type UiCapture,
15
- type UiContract,
16
- } from '@playfast/reform'
17
-
18
- const SETTLE_DRAIN = 30
19
- export const SETTLE_STEP = '1 milli'
20
- export const SETTLE_MAX_RENDERS = 100
21
-
22
- export const settleDrain: Effect.Effect<void> = Effect.yieldNow().pipe(Effect.repeatN(SETTLE_DRAIN))
23
-
24
- export const keyed = <V>(get: (key: string) => V): Record<string, V> => {
25
- const target: Record<string, V> = Object.create(null)
26
- return new Proxy(target, { get: (_target, key) => get(String(key)) })
27
- }
28
-
29
- export const messageOf = (error: unknown): string =>
30
- error instanceof Error ? error.message : String(error)
31
-
32
- export const uiNameOf = (comp: CompositionClass<unknown>): string => comp.manifest.ui.manifest.name
33
-
34
- export const eventsOf = (structure: Structure<UiContract>): Record<string, Trigger<unknown>> => ({
35
- ...structure.events,
36
- })
37
-
38
- export interface Sink {
39
- readonly api: CaptureSinkApi
40
- readonly captures: ReadonlyArray<UiCapture>
41
- readonly instrumentation: Instrumentation
42
- reset(): void
43
- }
44
-
45
- export const makeSink = (instrumentation: Instrumentation = noopInstrumentation): Sink => {
46
- const captures = MutableRef.make<UiCapture[]>([])
47
- return {
48
- api: {
49
- record: (capture) => {
50
- MutableRef.update(captures, (current) => [...current, capture])
51
- },
52
- },
53
- get captures() {
54
- return MutableRef.get(captures)
55
- },
56
- instrumentation,
57
- reset: () => {
58
- MutableRef.set(captures, [])
59
- },
60
- }
61
- }
62
-
63
- export type RuntimeServices = CompositionService | SlotChild | Bus
64
-
65
- export const proofLayer = (scene: Scene, sink: Sink): Layer.Layer<RuntimeServices, never, never> => {
66
- // oxlint-disable-next-line reform-rules/no-type-assertion -- the one erasure boundary: the scene's host-read `MountedServices` layer widens to the broader `RuntimeServices` a proof resolves
67
- const sceneLayer = scene.provide.reduce((merged, layer) => Layer.merge(merged, layer)) as unknown as Layer.Layer<
68
- RuntimeServices,
69
- never,
70
- never
71
- >
72
- return Layer.provideMerge(sceneLayer, Layer.succeed(CaptureSink, sink.api))
73
- }
@@ -1,121 +0,0 @@
1
- import { Effect, Match, Option, Record as Rec } from 'effect'
2
- import {
3
- type CompositionClass,
4
- isFeatureBinding,
5
- type SlotChild,
6
- type SlotClass,
7
- type SlotFill,
8
- type Structure,
9
- type UiContract,
10
- } from '@playfast/reform'
11
- import { eventsOf, type Sink, uiNameOf } from './sink'
12
-
13
- export interface Mounted {
14
- readonly comp: CompositionClass<unknown>
15
- readonly props: unknown
16
- readonly key: Option.Option<string>
17
- }
18
-
19
- export interface NodeRef {
20
- readonly name: string
21
- readonly index: number
22
- }
23
-
24
- export interface SettleProgress {
25
- readonly previous: string
26
- readonly remaining: number
27
- readonly stable: boolean
28
- }
29
-
30
- export interface PumpStep {
31
- readonly input: unknown
32
- readonly index: number
33
- }
34
-
35
- export const childComposition = (child: SlotChild): CompositionClass<unknown> =>
36
- isFeatureBinding(child) ? child.composition : child
37
-
38
- export const slotsOf = (comp: CompositionClass<unknown>): Record<string, SlotClass> =>
39
- Option.getOrElse(Option.fromNullable(comp.manifest.slots), () => ({}))
40
-
41
- const isSlotFill = (candidate: unknown): candidate is SlotFill<unknown> =>
42
- typeof candidate === 'object' &&
43
- candidate !== null &&
44
- '_tag' in candidate &&
45
- (candidate._tag === 'Each' || candidate._tag === 'One' || candidate._tag === 'Absent')
46
-
47
- export const structureFills = (
48
- structure: Structure<UiContract>,
49
- ): Record<string, SlotFill<unknown>> =>
50
- Rec.fromEntries(
51
- Rec.toEntries(structure.slots).flatMap(([slotName, fillValue]) =>
52
- isSlotFill(fillValue) ? [[slotName, fillValue] as const] : [],
53
- ),
54
- )
55
-
56
- export const collectBindings: (
57
- root: CompositionClass<unknown>,
58
- ) => Effect.Effect<Map<SlotClass, CompositionClass<unknown>>, never, SlotChild> = Effect.fn(
59
- 'collectBindings',
60
- )(function* (
61
- root: CompositionClass<unknown>,
62
- ): Effect.fn.Return<Map<SlotClass, CompositionClass<unknown>>, never, SlotChild> {
63
- const bindings = new Map<SlotClass, CompositionClass<unknown>>()
64
- const walk: (comp: CompositionClass<unknown>) => Effect.Effect<void, never, SlotChild> = Effect.fn(
65
- 'collectBindings.walk',
66
- )(function* (comp: CompositionClass<unknown>): Effect.fn.Return<void, never, SlotChild> {
67
- yield* Effect.forEach(Rec.values(slotsOf(comp)), (slotClass) =>
68
- Effect.gen(function* () {
69
- if (bindings.has(slotClass)) {
70
- return
71
- }
72
- const child = childComposition(yield* slotClass.tag)
73
- bindings.set(slotClass, child)
74
- yield* walk(child)
75
- }),
76
- )
77
- })
78
- yield* walk(root)
79
- return bindings
80
- })
81
-
82
- const enqueueFill = (
83
- slotName: string,
84
- fill: SlotFill<unknown>,
85
- child: CompositionClass<unknown>,
86
- ): ReadonlyArray<Mounted> =>
87
- Match.value(fill).pipe(
88
- Match.when({ _tag: 'Each' }, (each) =>
89
- each.items.map((entry) => ({
90
- comp: child,
91
- props: entry.props,
92
- key: Option.some(entry.key),
93
- })),
94
- ),
95
- Match.when({ _tag: 'One' }, (oneFill) => [
96
- { comp: child, props: oneFill.props, key: Option.some(`${slotName}.0`) },
97
- ]),
98
- Match.when({ _tag: 'Absent' }, () => []),
99
- Match.exhaustive,
100
- )
101
-
102
- export const driveStructure = (
103
- comp: CompositionClass<unknown>,
104
- structure: Structure<UiContract>,
105
- key: Option.Option<string>,
106
- sink: Sink,
107
- bindings: ReadonlyMap<SlotClass, CompositionClass<unknown>>,
108
- ): ReadonlyArray<Mounted> => {
109
- sink.api.record({
110
- name: uiNameOf(comp),
111
- props: structure.props,
112
- events: eventsOf(structure),
113
- ...(Option.isSome(key) ? { key: key.value } : {}),
114
- })
115
- const fills = structureFills(structure)
116
- return Rec.toEntries(slotsOf(comp)).flatMap(([slotName, slotClass]) => {
117
- const child = bindings.get(slotClass)
118
- const fill = fills[slotName]
119
- return child === undefined || fill === undefined ? [] : enqueueFill(slotName, fill, child)
120
- })
121
- }