@pithyjs/core 0.1.0-beta.0 → 0.1.0-beta.2

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 (114) hide show
  1. package/README.md +25 -0
  2. package/dist/compile/bindSwitchCases.js +5 -2
  3. package/dist/compile/bindSwitchCases.js.map +1 -1
  4. package/dist/compile/binds/bindClassDirectives.d.ts +2 -0
  5. package/dist/compile/binds/bindClassDirectives.d.ts.map +1 -1
  6. package/dist/compile/binds/bindClassDirectives.js +18 -15
  7. package/dist/compile/binds/bindClassDirectives.js.map +1 -1
  8. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  9. package/dist/compile/binds/bindComponentsTags.js +90 -33
  10. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  11. package/dist/compile/binds/bindDefaultTwoWay.d.ts.map +1 -1
  12. package/dist/compile/binds/bindDefaultTwoWay.js +2 -1
  13. package/dist/compile/binds/bindDefaultTwoWay.js.map +1 -1
  14. package/dist/compile/binds/bindDeferDirectives.d.ts.map +1 -1
  15. package/dist/compile/binds/bindDeferDirectives.js +41 -11
  16. package/dist/compile/binds/bindDeferDirectives.js.map +1 -1
  17. package/dist/compile/binds/bindErrorBoundary.d.ts +13 -2
  18. package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
  19. package/dist/compile/binds/bindErrorBoundary.js +20 -10
  20. package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
  21. package/dist/compile/binds/bindTextInterpolations.js +1 -1
  22. package/dist/compile/binds/bindTextInterpolations.js.map +1 -1
  23. package/dist/compile/binds/forwardedAttrs.d.ts +22 -0
  24. package/dist/compile/binds/forwardedAttrs.d.ts.map +1 -0
  25. package/dist/compile/binds/forwardedAttrs.js +66 -0
  26. package/dist/compile/binds/forwardedAttrs.js.map +1 -0
  27. package/dist/compile/componentResult.d.ts +100 -0
  28. package/dist/compile/componentResult.d.ts.map +1 -0
  29. package/dist/compile/componentResult.js +138 -0
  30. package/dist/compile/componentResult.js.map +1 -0
  31. package/dist/compile/contentProjection.d.ts.map +1 -1
  32. package/dist/compile/contentProjection.js +4 -10
  33. package/dist/compile/contentProjection.js.map +1 -1
  34. package/dist/compile/forLoops/bindForLoops.d.ts.map +1 -1
  35. package/dist/compile/forLoops/bindForLoops.js +2 -13
  36. package/dist/compile/forLoops/bindForLoops.js.map +1 -1
  37. package/dist/compile/forLoops/createLoopManager.d.ts +4 -1
  38. package/dist/compile/forLoops/createLoopManager.d.ts.map +1 -1
  39. package/dist/compile/forLoops/createLoopManager.js +143 -104
  40. package/dist/compile/forLoops/createLoopManager.js.map +1 -1
  41. package/dist/compile/forLoops/loopHelpers.d.ts +6 -0
  42. package/dist/compile/forLoops/loopHelpers.d.ts.map +1 -1
  43. package/dist/compile/forLoops/loopHelpers.js +17 -0
  44. package/dist/compile/forLoops/loopHelpers.js.map +1 -1
  45. package/dist/compile/forLoops/loopSignals.js +2 -2
  46. package/dist/compile/forLoops/loopSignals.js.map +1 -1
  47. package/dist/compile/handleConditionalChain.d.ts.map +1 -1
  48. package/dist/compile/handleConditionalChain.js +21 -18
  49. package/dist/compile/handleConditionalChain.js.map +1 -1
  50. package/dist/compile/index.d.ts +6 -3
  51. package/dist/compile/index.d.ts.map +1 -1
  52. package/dist/compile/index.js +19 -3
  53. package/dist/compile/index.js.map +1 -1
  54. package/dist/compile/renderChildren.d.ts +17 -0
  55. package/dist/compile/renderChildren.d.ts.map +1 -1
  56. package/dist/compile/renderChildren.js +20 -1
  57. package/dist/compile/renderChildren.js.map +1 -1
  58. package/dist/compile/ssrCrashes.d.ts +116 -0
  59. package/dist/compile/ssrCrashes.d.ts.map +1 -0
  60. package/dist/compile/ssrCrashes.js +173 -0
  61. package/dist/compile/ssrCrashes.js.map +1 -0
  62. package/dist/runtime/applyBindings.d.ts +3 -3
  63. package/dist/runtime/applyBindings.d.ts.map +1 -1
  64. package/dist/runtime/applyBindings.js +28 -4
  65. package/dist/runtime/applyBindings.js.map +1 -1
  66. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  67. package/dist/runtime/bindings/applyComponent.js +102 -13
  68. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  69. package/dist/runtime/bindings/applyDefer.d.ts.map +1 -1
  70. package/dist/runtime/bindings/applyDefer.js +40 -12
  71. package/dist/runtime/bindings/applyDefer.js.map +1 -1
  72. package/dist/runtime/bindings/applySimple.d.ts +2 -1
  73. package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
  74. package/dist/runtime/bindings/applySimple.js +27 -3
  75. package/dist/runtime/bindings/applySimple.js.map +1 -1
  76. package/dist/runtime/bindings/applyStructural.d.ts.map +1 -1
  77. package/dist/runtime/bindings/applyStructural.js +44 -62
  78. package/dist/runtime/bindings/applyStructural.js.map +1 -1
  79. package/dist/runtime/bindings/index.d.ts +2 -2
  80. package/dist/runtime/bindings/index.d.ts.map +1 -1
  81. package/dist/runtime/bindings/index.js +1 -1
  82. package/dist/runtime/bindings/index.js.map +1 -1
  83. package/dist/runtime/bindings/types.d.ts +12 -1
  84. package/dist/runtime/bindings/types.d.ts.map +1 -1
  85. package/dist/runtime/index.d.ts +1 -0
  86. package/dist/runtime/index.d.ts.map +1 -1
  87. package/dist/runtime/index.js +2 -0
  88. package/dist/runtime/index.js.map +1 -1
  89. package/dist/runtime/resource/createAction.d.ts +44 -0
  90. package/dist/runtime/resource/createAction.d.ts.map +1 -0
  91. package/dist/runtime/resource/createAction.js +102 -0
  92. package/dist/runtime/resource/createAction.js.map +1 -0
  93. package/dist/runtime/resource/createResource.d.ts +56 -0
  94. package/dist/runtime/resource/createResource.d.ts.map +1 -0
  95. package/dist/runtime/resource/createResource.js +103 -0
  96. package/dist/runtime/resource/createResource.js.map +1 -0
  97. package/dist/runtime/resource/engine.d.ts +136 -0
  98. package/dist/runtime/resource/engine.d.ts.map +1 -0
  99. package/dist/runtime/resource/engine.js +363 -0
  100. package/dist/runtime/resource/engine.js.map +1 -0
  101. package/dist/runtime/resource/index.d.ts +19 -0
  102. package/dist/runtime/resource/index.d.ts.map +1 -0
  103. package/dist/runtime/resource/index.js +18 -0
  104. package/dist/runtime/resource/index.js.map +1 -0
  105. package/dist/runtime/resource/types.d.ts +240 -0
  106. package/dist/runtime/resource/types.d.ts.map +1 -0
  107. package/dist/runtime/resource/types.js +9 -0
  108. package/dist/runtime/resource/types.js.map +1 -0
  109. package/dist/types/globals.d.ts +9 -0
  110. package/dist/types/globals.d.ts.map +1 -1
  111. package/dist/types/globals.js.map +1 -1
  112. package/dist/types/index.d.ts +15 -1
  113. package/dist/types/index.d.ts.map +1 -1
  114. package/package.json +5 -5
@@ -0,0 +1,363 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource.engine",
4
+ "title": "Async State Engine",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ /**
10
+ * Shared async-state engine behind `createResource` and `createAction`.
11
+ *
12
+ * The two public primitives are thin policy layers over this engine: they
13
+ * differ only in defaults (auto-run, overlap policy, previous-data retention)
14
+ * and in the shape of their call signature. All state transitions, cancellation
15
+ * and teardown live here so both primitives cannot drift apart.
16
+ *
17
+ * ## Why not reuse the router's loader system?
18
+ *
19
+ * `packages/router/src/router/features/loaders/` solves a superficially similar
20
+ * problem, but it is not reusable here:
21
+ *
22
+ * - It contains ZERO signals — `executeLoader()` returns a bare promise, so
23
+ * there is no observable `status`/`data`/`error` for a template to bind to.
24
+ * - It is route-keyed (`executeLoader(routeId, ...)`). A form submit has no
25
+ * `routeId` and is not a navigation.
26
+ * - Its `ResourceCache` is `get`/`set`/`clear` only — there is no per-key
27
+ * invalidation, which is a supporting reason this primitive ships without a
28
+ * cache in v1 (there would be no correct way to invalidate one entry).
29
+ * - Importing it would add a `core -> router` dependency and recreate a known
30
+ * build cycle. The prior art is referenced here in comments only.
31
+ *
32
+ * ## Why a generation counter and not an in-flight AbortController registry?
33
+ *
34
+ * `LoaderManager` keeps `private activeLoaders = new Map<string, AbortController>()`
35
+ * and relies on `abort()` to make a superseded request lose. That is not
36
+ * sufficient on its own: aborting cannot stop a fetcher that ignores its signal
37
+ * (a `setTimeout`-based mock, a third-party SDK, `indexedDB`, or any promise not
38
+ * wired to `AbortSignal`). Such a fetcher still settles and would happily write
39
+ * stale data into the signals.
40
+ *
41
+ * So correctness comes from the monotonic `generation` counter — a settled
42
+ * result may only write state if its generation is still the current one — and
43
+ * the `AbortController` is kept purely as a courtesy so well-behaved fetchers
44
+ * can stop early. (If a caller-supplied signal is ever needed, the router's
45
+ * `combineAbortSignals()` in `router/core/utils.ts` shows the shape. Not in v1.)
46
+ *
47
+ * ## Why the explicit `destroyed` flag?
48
+ *
49
+ * Disposing an effect does NOT stop an already in-flight promise from writing
50
+ * signals afterwards — the disposer only runs cleanups. And `onCleanup()`
51
+ * outside every effect is a silent no-op, so a primitive constructed in a plain
52
+ * component body with no owner gets no automatic teardown at all. `destroy()`
53
+ * is therefore load-bearing, not a nicety.
54
+ *
55
+ * Async continuations are automatically untracked (the signals runtime clears
56
+ * `currentEffect` synchronously in `runEffect`'s `finally`), so writing signals
57
+ * from a `.then`/`await` continuation can never subscribe the caller's effect to
58
+ * them. That is what makes this engine safe to use inside a component body.
59
+ *
60
+ * CAVEAT this does NOT cover: `execute()`'s synchronous prologue (everything
61
+ * up to the first `await task(...)`) runs inside whatever tracking context the
62
+ * *caller* was in — `currentEffect` is only cleared once execution actually
63
+ * suspends. So a fetcher's signal READS (e.g. `id()` referenced in its body
64
+ * before the first `await`) are tracked by an enclosing effect if one is
65
+ * running. Concretely: `effect(() => createResource(() => fetch(`/api/u/${id()}`)))`
66
+ * re-runs on every `id` change, constructing a brand-new resource and firing a
67
+ * brand-new fetch each time. The prior resource is now destroyed on that re-run
68
+ * rather than leaked, but the re-fetching itself remains a caller footgun, not
69
+ * an engine bug; it is documented for callers in the README's Async State
70
+ * section.
71
+ *
72
+ * @module runtime/resource/engine
73
+ */
74
+ import { batch, signal } from '@pithyjs/signals';
75
+ /**
76
+ * The single "nothing happened" result value.
77
+ *
78
+ * Structurally assignable to `ActionResult<T, E>` for any `T`/`E`, so it can be
79
+ * returned from every generic entry point without an allocation per call.
80
+ */
81
+ /** @codexApi {"parent":"pithy.core.resource.engine","name":"DROPPED","stability":"experimental","signature":"const DROPPED: { readonly ok: false; readonly dropped: true }"} */
82
+ // `readonly` is compile-time only — freeze it too, so a consumer mutating the
83
+ // object (accidentally or otherwise) cannot corrupt this shared sentinel for
84
+ // every resource and action in the process.
85
+ export const DROPPED = Object.freeze({
86
+ ok: false,
87
+ dropped: true,
88
+ });
89
+ /**
90
+ * Create the shared async-state engine.
91
+ *
92
+ * @typeParam T - Type of the resolved data.
93
+ * @typeParam E - Type of the carried error.
94
+ * @param options - Engine behaviour flags.
95
+ * @returns An {@link AsyncEngine} owning three signals and the run lifecycle.
96
+ */
97
+ /** @codexApi {"parent":"pithy.core.resource.engine","name":"createAsyncEngine","stability":"experimental","signature":"<T, E = unknown>(options: AsyncEngineOptions) => AsyncEngine<T, E>"} */
98
+ export function createAsyncEngine(options) {
99
+ const { keepPreviousData } = options;
100
+ const data = signal(undefined);
101
+ const error = signal(undefined);
102
+ const status = signal('idle');
103
+ /**
104
+ * Monotonic run id. Only a task whose id still equals `generation` may write
105
+ * state — this is what makes a stale response lose even when its fetcher
106
+ * ignored the abort signal entirely.
107
+ */
108
+ let generation = 0;
109
+ let inFlight = false;
110
+ let controller = null;
111
+ let destroyed = false;
112
+ /**
113
+ * How many attempts are still executing USER CODE — deliberately distinct
114
+ * from `inFlight`, which tracks whether we still WANT the result.
115
+ *
116
+ * `reset()` clears `inFlight` because it abandons the result, but it cannot
117
+ * recall a performer that is already running. An action drops its
118
+ * `AbortSignal` by design, so abort is inert there and nothing stops the
119
+ * request. The double-submit guard therefore has to consult this counter:
120
+ * otherwise Save -> dismiss (reset) -> Save fires two concurrent POSTs, the
121
+ * exact case `overlap: 'drop'` exists to prevent.
122
+ */
123
+ let outstanding = 0;
124
+ /**
125
+ * Release callbacks for attempts parked on `await`.
126
+ *
127
+ * The generation gate sits after the await, so without these a superseded
128
+ * attempt cannot report `DROPPED` until its own task settles — and a task
129
+ * that ignores its abort signal (or an action, which never receives one) may
130
+ * never settle at all, leaving a promise documented to resolve pending
131
+ * forever. Invalidation releases them so they resolve on their own.
132
+ */
133
+ const parked = new Set();
134
+ /**
135
+ * Invalidate anything currently running: bump the generation (so a late
136
+ * settle can never win), abort the controller as a courtesy, and release
137
+ * every parked attempt so it stops waiting on a task it no longer needs.
138
+ */
139
+ function invalidateInFlight() {
140
+ generation++;
141
+ inFlight = false;
142
+ controller?.abort();
143
+ controller = null;
144
+ const releasing = [...parked];
145
+ parked.clear();
146
+ for (const release of releasing)
147
+ release();
148
+ }
149
+ /**
150
+ * Perform a signal write with consumer re-entry isolated.
151
+ *
152
+ * Every write below re-enters application code: `set()` invokes `.subscribe()`
153
+ * listeners synchronously — even inside `batch()`, which only defers effects —
154
+ * and the outermost `batch()` flushes those effects on its way out. That pass
155
+ * runs every subscriber before rethrowing the first failure, so a throw
156
+ * propagates back into the engine — unless the caller wrapped the call in its
157
+ * own `batch()`. Then the effects run at the caller's flush, and a failure
158
+ * there is thrown by the caller's `batch()`, outside anything the engine can
159
+ * contain.
160
+ *
161
+ * Unisolated that was live in two ways: a throwing subscriber on the success
162
+ * write landed in the `catch` below, turning a SUCCESSFUL fetch into a
163
+ * failure carrying the consumer's own error; and the failure write then
164
+ * re-entered the same subscriber, whose second throw escaped `execute()`
165
+ * entirely — rejecting a promise the contract says never rejects.
166
+ *
167
+ * The throw is REPORTED rather than re-raised. Re-raising from a microtask
168
+ * would reach `window.onerror`, but it also becomes an uncaught exception —
169
+ * which crashes a Node process and fails a test run over a fault in consumer
170
+ * code that the engine has already contained. Reporting keeps it visible
171
+ * without letting one bad subscriber take down the host. The tradeoff is
172
+ * that error-reporting tools hooked only to `window.onerror` will not see
173
+ * it; those that capture `console.error` (most do) still will.
174
+ */
175
+ function report(err) {
176
+ console.error('[PithyJS] A subscriber threw while a resource/action was writing its ' +
177
+ 'state. The transition completed and the engine is unaffected — fix ' +
178
+ 'the subscriber.', err);
179
+ }
180
+ /**
181
+ * Apply a state transition one setter at a time.
182
+ *
183
+ * Wrapping the three setters in a single `batch()` is NOT enough to make the
184
+ * transition atomic, because `set()` invokes `.subscribe()` listeners
185
+ * synchronously — batching defers effects, not listeners. Two consequences,
186
+ * both of which this guards:
187
+ *
188
+ * - **A throw must not truncate the transition.** With one `try` around the
189
+ * whole batch, a listener throwing on the first setter skipped the rest —
190
+ * leaving `data` written while `status` stayed `'loading'` even though
191
+ * `execute()` went on to resolve success. Each setter is isolated instead,
192
+ * so one bad listener costs its own write and nothing else.
193
+ *
194
+ * - **A re-entrant supersede must win.** A listener can synchronously call
195
+ * `reset()` or start a newer run between two setters. That newer state is
196
+ * already committed by the time this loop resumes, so continuing would
197
+ * overwrite it with the remainder of a transition that is now stale.
198
+ * `superseded()` is therefore re-checked before every setter, not once up
199
+ * front.
200
+ *
201
+ * Setter order matters and is deliberate: `status` is written LAST, so a
202
+ * consumer keyed on `status` never observes the new status beside the old
203
+ * data.
204
+ */
205
+ function commit(writes, superseded) {
206
+ try {
207
+ batch(() => {
208
+ for (const write of writes) {
209
+ if (superseded())
210
+ return;
211
+ try {
212
+ write();
213
+ }
214
+ catch (err) {
215
+ report(err);
216
+ }
217
+ }
218
+ });
219
+ }
220
+ catch (err) {
221
+ // The outermost `batch()` flushes queued effects on its way out and rethrows
222
+ // the first failure; that flush happens after the loop above, so it needs its
223
+ // own guard. Nested in a caller's `batch()`, nothing flushes or throws here.
224
+ report(err);
225
+ }
226
+ }
227
+ /**
228
+ * `.set(() => value)` rather than `.set(value)`: the signals `set()` treats a
229
+ * function argument as an updater, so the updater form is the only spelling
230
+ * that stays correct when `T` is itself a function type.
231
+ */
232
+ function writeSuccess(value, superseded) {
233
+ commit([
234
+ () => data.set(() => value),
235
+ () => error.set(() => undefined),
236
+ () => status.set('success'),
237
+ ], superseded);
238
+ }
239
+ function writeFailure(carried, superseded) {
240
+ commit([() => error.set(() => carried), () => status.set('error')], superseded);
241
+ }
242
+ async function execute(task) {
243
+ if (destroyed)
244
+ return DROPPED;
245
+ // Supersede everything prior: bumps the generation so a late settle can
246
+ // never win, aborts the old controller, and releases any parked attempt so
247
+ // it reports DROPPED without waiting on a task that may never settle.
248
+ invalidateInFlight();
249
+ const runGeneration = generation;
250
+ const runController = new AbortController();
251
+ controller = runController;
252
+ inFlight = true;
253
+ /** Superseded by a newer run, or torn down. Either way: write nothing. */
254
+ const stale = () => destroyed || runGeneration !== generation;
255
+ let release;
256
+ const parkedUntilInvalidated = new Promise(resolve => {
257
+ release = resolve;
258
+ });
259
+ parked.add(release);
260
+ try {
261
+ commit([
262
+ () => status.set('loading'),
263
+ () => error.set(() => undefined),
264
+ ...(keepPreviousData ? [] : [() => data.set(() => undefined)]),
265
+ ], stale);
266
+ // The prologue above re-enters consumer code, which can synchronously
267
+ // `destroy()` or `reset()` this handle before any await. Invoking `task`
268
+ // afterwards would fire a side effect — for an action, a POST — on
269
+ // behalf of a handle that no longer exists.
270
+ if (stale())
271
+ return DROPPED;
272
+ outstanding++;
273
+ // Wrapped in an async IIFE so a SYNCHRONOUS throw from `task` becomes a
274
+ // rejection of `running` rather than escaping before the race is armed.
275
+ const running = (async () => task(runController.signal))();
276
+ // Settles `outstanding` against the task itself, not against our
277
+ // interest in it — see the counter's declaration. Doubles as the
278
+ // consumer of a rejection we may stop awaiting, so abandoning a
279
+ // superseded task never surfaces as an unhandled rejection.
280
+ running.then(() => {
281
+ outstanding--;
282
+ }, () => {
283
+ outstanding--;
284
+ });
285
+ const outcome = await Promise.race([
286
+ running.then(value => ({ settled: true, value })),
287
+ parkedUntilInvalidated.then(() => ({ settled: false })),
288
+ ]);
289
+ // `!outcome.settled` means invalidation released us first; `stale()`
290
+ // covers a supersession that raced the task's own settle.
291
+ if (!outcome.settled || stale())
292
+ return DROPPED;
293
+ inFlight = false;
294
+ controller = null;
295
+ writeSuccess(outcome.value, stale);
296
+ return { ok: true, data: outcome.value };
297
+ }
298
+ catch (thrown) {
299
+ if (stale())
300
+ return DROPPED;
301
+ inFlight = false;
302
+ controller = null;
303
+ // Errors are carried by reference with `E = unknown` — never wrapped in
304
+ // an `Error`, so a thrown string, a `Response`, or a typed API failure
305
+ // envelope survives intact.
306
+ const carried = thrown;
307
+ writeFailure(carried, stale);
308
+ return { ok: false, dropped: false, error: carried };
309
+ }
310
+ finally {
311
+ parked.delete(release);
312
+ }
313
+ }
314
+ function reset() {
315
+ if (destroyed)
316
+ return;
317
+ invalidateInFlight();
318
+ // Note this abandons the RESULT but cannot recall a running performer —
319
+ // `outstanding` deliberately survives, so the drop guard still holds.
320
+ // A listener could start a newer run mid-transition; that run's state must
321
+ // stand rather than be clobbered by the rest of this reset.
322
+ const at = generation;
323
+ commit([
324
+ () => data.set(() => undefined),
325
+ () => error.set(() => undefined),
326
+ () => status.set('idle'),
327
+ ], () => generation !== at);
328
+ }
329
+ function destroy() {
330
+ if (destroyed)
331
+ return;
332
+ destroyed = true;
333
+ // Captured BEFORE invalidateInFlight() clears it, and used in place of
334
+ // reading status(). The two are equivalent — `inFlight` and
335
+ // `status === 'loading'` are set together in execute() and cleared
336
+ // together on settle — but `inFlight` is a plain boolean, whereas
337
+ // status() is a signal read. destroy() runs outside any effect, so
338
+ // reading a signal here trips the dev-mode "read outside of a reactive
339
+ // context" warning on every teardown. The test env suppresses that
340
+ // warning, which is why the suite never saw it.
341
+ const wasInFlight = inFlight;
342
+ invalidateInFlight();
343
+ // `data`/`error` freeze exactly as they were, so a subscriber that
344
+ // outlives the primitive sees no phantom value change. `status` is the
345
+ // one exception: a destroy mid-flight must not leave it permanently
346
+ // stuck at 'loading' (a surviving subscriber would show a spinner
347
+ // forever, and reset() can no longer clear it — reset() early-returns
348
+ // once `destroyed` is true). Settle it to 'idle' instead.
349
+ if (wasInFlight)
350
+ commit([() => status.set('idle')], () => false);
351
+ }
352
+ return {
353
+ data,
354
+ error,
355
+ status,
356
+ isInFlight: () => inFlight,
357
+ hasRunningTask: () => outstanding > 0,
358
+ execute,
359
+ reset,
360
+ destroy,
361
+ };
362
+ }
363
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../../src/runtime/resource/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,EAAe,MAAM,kBAAkB,CAAC;AAG9D;;;;;GAKG;AACH,gLAAgL;AAChL,8EAA8E;AAC9E,6EAA6E;AAC7E,4CAA4C;AAC5C,MAAM,CAAC,MAAM,OAAO,GAClB,MAAM,CAAC,MAAM,CAAC;IACZ,EAAE,EAAE,KAAK;IACT,OAAO,EAAE,IAAI;CACd,CAAmD,CAAC;AA6CvD;;;;;;;GAOG;AACH,+LAA+L;AAC/L,MAAM,UAAU,iBAAiB,CAC/B,OAA2B;IAE3B,MAAM,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC;IAErC,MAAM,IAAI,GAAG,MAAM,CAAgB,SAAS,CAAC,CAAC;IAC9C,MAAM,KAAK,GAAG,MAAM,CAAgB,SAAS,CAAC,CAAC;IAC/C,MAAM,MAAM,GAAG,MAAM,CAAiB,MAAM,CAAC,CAAC;IAE9C;;;;OAIG;IACH,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,UAAU,GAA2B,IAAI,CAAC;IAC9C,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB;;;;;;;;;;OAUG;IACH,IAAI,WAAW,GAAG,CAAC,CAAC;IAEpB;;;;;;;;OAQG;IACH,MAAM,MAAM,GAAG,IAAI,GAAG,EAAc,CAAC;IAErC;;;;OAIG;IACH,SAAS,kBAAkB;QACzB,UAAU,EAAE,CAAC;QACb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AAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;IACnE,CAAC;IAED,OAAO;QACL,IAAI;QACJ,KAAK;QACL,MAAM;QACN,UAAU,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC1B,cAAc,EAAE,GAAG,EAAE,CAAC,WAAW,GAAG,CAAC;QACrC,OAAO;QACP,KAAK;QACL,OAAO;KACR,CAAC;AACJ,CAAC"}
@@ -0,0 +1,19 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource.barrel",
4
+ "title": "Async State Primitive Barrel",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * Public surface of the async-state primitives.
10
+ *
11
+ * `engine.ts` is intentionally NOT re-exported — it is an internal seam shared
12
+ * by the two primitives, not API.
13
+ *
14
+ * @module runtime/resource
15
+ */
16
+ export { createResource } from './createResource';
17
+ export { createAction } from './createAction';
18
+ export type { ResourceStatus, ResourceFetcher, ResourceOptions, ResourceHandle, ActionPerformer, ActionOverlap, ActionOptions, ActionHandle, ActionResult, } from './types';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/runtime/resource/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,YAAY,EACV,cAAc,EACd,eAAe,EACf,eAAe,EACf,cAAc,EACd,eAAe,EACf,aAAa,EACb,aAAa,EACb,YAAY,EACZ,YAAY,GACb,MAAM,SAAS,CAAC"}
@@ -0,0 +1,18 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource.barrel",
4
+ "title": "Async State Primitive Barrel",
5
+ "category": "runtime"
6
+ }
7
+ */
8
+ /**
9
+ * Public surface of the async-state primitives.
10
+ *
11
+ * `engine.ts` is intentionally NOT re-exported — it is an internal seam shared
12
+ * by the two primitives, not API.
13
+ *
14
+ * @module runtime/resource
15
+ */
16
+ export { createResource } from './createResource';
17
+ export { createAction } from './createAction';
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/runtime/resource/index.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,240 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource.types",
4
+ "title": "Async State Primitive Types",
5
+ "category": "types"
6
+ }
7
+ */
8
+ /**
9
+ * Public types for the async-state primitives (`createResource`, `createAction`).
10
+ *
11
+ * @module runtime/resource/types
12
+ */
13
+ /**
14
+ * Read access to a signal: call it to read (tracked normally inside an
15
+ * effect), `subscribe` to observe. Deliberately omits `.set()`.
16
+ *
17
+ * `@pithyjs/signals` exports `ReadonlySignal<T> = () => T`, which drops
18
+ * `.subscribe` as well. Observing without an effect is legitimate read access,
19
+ * so the handles use this instead — the write path is what has to be closed
20
+ * off, not the read path. If this proves generally useful it belongs in
21
+ * `@pithyjs/signals` beside `Signal` and `ReadonlySignal`.
22
+ */
23
+ export type ReadableSignal<T> = (() => T) & {
24
+ subscribe: (fn: (value: T) => void) => () => void;
25
+ };
26
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ResourceStatus","stability":"stable","signature":"type ResourceStatus = 'idle' | 'loading' | 'success' | 'error'"} */
27
+ /**
28
+ * Lifecycle status of a resource or action.
29
+ *
30
+ * NAMING NOTE: this is deliberately NOT called `ResourceState`. `@pithyjs/router`
31
+ * already exports an interface named `ResourceState` (route loader state), and
32
+ * `@pithyjs/core` re-exports its whole runtime barrel — an app importing both
33
+ * packages would otherwise face an ambiguous name.
34
+ */
35
+ export type ResourceStatus = 'idle' | 'loading' | 'success' | 'error';
36
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ResourceFetcher","stability":"stable","signature":"type ResourceFetcher<T> = (signal: AbortSignal) => T | Promise<T>"} */
37
+ /**
38
+ * The function a resource calls to produce its data.
39
+ *
40
+ * Receives an `AbortSignal` that is aborted when the resource is refetched,
41
+ * reset or destroyed. Forwarding it to `fetch()` is a courtesy optimisation
42
+ * only — correctness never depends on the fetcher honouring it (see
43
+ * `engine.ts` for the generation counter that guarantees it).
44
+ *
45
+ * @typeParam T - Type of the resolved data.
46
+ */
47
+ export type ResourceFetcher<T> = (signal: AbortSignal) => T | Promise<T>;
48
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ActionPerformer","stability":"stable","signature":"type ActionPerformer<T, A extends unknown[]> = (...args: A) => T | Promise<T>"} */
49
+ /**
50
+ * The function an action calls to perform its side effect.
51
+ *
52
+ * @typeParam T - Type of the resolved data.
53
+ * @typeParam A - Tuple of arguments forwarded from `run()`.
54
+ */
55
+ export type ActionPerformer<T, A extends unknown[]> = (...args: A) => T | Promise<T>;
56
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ActionResult","stability":"stable","signature":"type ActionResult<T, E = unknown> = { ok: true; data: T } | { ok: false; dropped: false; error: E } | { ok: false; dropped: true }"} */
57
+ /**
58
+ * Discriminated union resolved by `run()` and `refetch()`.
59
+ *
60
+ * These methods RESOLVE this union — they never reject. This deliberately
61
+ * diverges from the router's `executeLoader`, which rejects on failure; see the
62
+ * comment above `run()` in `createAction.ts` for the rationale.
63
+ *
64
+ * Narrowing:
65
+ * ```ts
66
+ * if (result.ok) result.data; // success
67
+ * else if (result.dropped) { } // superseded / destroyed / SSR — no run happened
68
+ * else result.error; // failure, error carried by reference
69
+ * ```
70
+ *
71
+ * @typeParam T - Type of the resolved data.
72
+ * @typeParam E - Type of the carried error (defaults to `unknown` — thrown values
73
+ * are carried by reference and never wrapped in an `Error`).
74
+ */
75
+ export type ActionResult<T, E = unknown> = {
76
+ readonly ok: true;
77
+ readonly data: T;
78
+ } | {
79
+ readonly ok: false;
80
+ readonly dropped: false;
81
+ readonly error: E;
82
+ } | {
83
+ readonly ok: false;
84
+ readonly dropped: true;
85
+ };
86
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ResourceOptions","stability":"stable","signature":"interface ResourceOptions"} */
87
+ /** Options for {@link createResource}. */
88
+ export interface ResourceOptions {
89
+ /**
90
+ * Fetch as soon as the resource is created.
91
+ *
92
+ * Ignored under server rendering (SSG *and* dynamic SSR), where the
93
+ * resource always stays `'idle'`.
94
+ *
95
+ * @default true
96
+ */
97
+ immediate?: boolean;
98
+ /**
99
+ * Keep the last successful `data` readable while a refetch is in flight,
100
+ * **and after that refetch fails**. When `false`, `data` is cleared the
101
+ * moment a refetch starts.
102
+ *
103
+ * The post-failure half matters: on failure `status` becomes `'error'` and
104
+ * `error` is populated, but `data` still holds the last success. A view that
105
+ * renders `data` whenever it is defined will therefore show stale content
106
+ * beside a fresh error unless it checks `status` too. That is the intended
107
+ * behaviour — it is what makes a transient refetch failure non-destructive —
108
+ * but it has to be handled deliberately.
109
+ *
110
+ * @default false
111
+ */
112
+ keepPreviousData?: boolean;
113
+ }
114
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ActionOverlap","stability":"stable","signature":"type ActionOverlap = 'drop' | 'restart'"} */
115
+ /**
116
+ * What happens when `run()` is called while a previous run is still in flight.
117
+ *
118
+ * - `'drop'` — the new call is ignored and resolves `{ ok: false, dropped: true }`.
119
+ * The default for actions: double-submitting a form should not fire twice.
120
+ * - `'restart'` — the new call supersedes the old one, which resolves
121
+ * `{ ok: false, dropped: true }` and can never write state again.
122
+ */
123
+ export type ActionOverlap = 'drop' | 'restart';
124
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ActionOptions","stability":"stable","signature":"interface ActionOptions"} */
125
+ /** Options for {@link createAction}. */
126
+ export interface ActionOptions {
127
+ /**
128
+ * Overlap policy for concurrent `run()` calls.
129
+ *
130
+ * @default 'drop'
131
+ */
132
+ overlap?: ActionOverlap;
133
+ /**
134
+ * Keep the last successful `data` readable while the next run is in flight
135
+ * — AND after that run fails. `writeFailure()` never clears `data`, so with
136
+ * this on (the default), a failed run leaves the previous success value
137
+ * readable in `data()` alongside the new `error()`/`status() === 'error'`.
138
+ * Only a subsequent success or an explicit `reset()` clears it.
139
+ *
140
+ * Defaults to `true` — the inverse of {@link ResourceOptions.keepPreviousData} —
141
+ * because an action's result is usually a receipt the UI keeps showing.
142
+ *
143
+ * @default true
144
+ */
145
+ keepPreviousData?: boolean;
146
+ }
147
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ResourceHandle","stability":"stable","signature":"interface ResourceHandle<T, E = unknown>"} */
148
+ /**
149
+ * Handle returned by {@link createResource}.
150
+ *
151
+ * `data`, `error` and `status` are exposed as {@link ReadableSignal} — read and
152
+ * subscribe, but no `.set()` — rather than `Signal`. `readonly` on the property alone
153
+ * would only stop the field being reassigned; the `Signal` behind it still
154
+ * carries `.set()`, so `resource.status.set('success')` would type-check and
155
+ * desync `status` from the engine's untracked bookkeeping, after which
156
+ * `destroy()` cannot clear a stuck spinner and `loading()` reports a state the
157
+ * engine never produced. The accessor type makes the intent enforceable
158
+ * instead of conventional.
159
+ *
160
+ * @typeParam T - Type of the resolved data.
161
+ * @typeParam E - Type of the carried error.
162
+ */
163
+ export interface ResourceHandle<T, E = unknown> {
164
+ /** Latest successful value, or `undefined` before the first success. */
165
+ readonly data: ReadableSignal<T | undefined>;
166
+ /**
167
+ * Latest error, carried by reference and never wrapped.
168
+ *
169
+ * `status() === 'error'` is the authoritative failure check, NOT
170
+ * `error() !== undefined`. A rejection can legitimately carry `undefined`
171
+ * (e.g. `Promise.reject()` / `throw undefined`), in which case `status()`
172
+ * is `'error'` while `error()` reads `undefined` — a consumer checking only
173
+ * `error()` would silently miss that failure.
174
+ */
175
+ readonly error: ReadableSignal<E | undefined>;
176
+ /** Current lifecycle status. */
177
+ readonly status: ReadableSignal<ResourceStatus>;
178
+ /**
179
+ * `true` while a fetch is in flight.
180
+ *
181
+ * A plain accessor rather than `computed()` — it still tracks reactively
182
+ * because it reads `status()` inside the caller's effect, and it avoids
183
+ * `computed()`'s leaked internal subscription.
184
+ */
185
+ readonly loading: () => boolean;
186
+ /**
187
+ * Re-run the fetcher. The newest call always wins; superseded calls resolve
188
+ * `{ ok: false, dropped: true }`. Inert under any server render.
189
+ */
190
+ refetch: () => Promise<ActionResult<T, E>>;
191
+ /** Return to `'idle'`, clearing data and error, and abandon any in-flight fetch. */
192
+ reset: () => void;
193
+ /**
194
+ * Permanently stop the resource: aborts the in-flight request and guarantees
195
+ * no signal is ever written again.
196
+ *
197
+ * MUST be called from the owning component's cleanup. `onCleanup()` is a
198
+ * silent no-op outside an effect, so this is not optional.
199
+ */
200
+ destroy: () => void;
201
+ }
202
+ /** @codexApi {"parent":"pithy.core.resource.types","name":"ActionHandle","stability":"stable","signature":"interface ActionHandle<T, A extends unknown[], E = unknown>"} */
203
+ /**
204
+ * Handle returned by {@link createAction}.
205
+ *
206
+ * @typeParam T - Type of the resolved data.
207
+ * @typeParam A - Tuple of arguments accepted by `run()`.
208
+ * @typeParam E - Type of the carried error.
209
+ */
210
+ export interface ActionHandle<T, A extends unknown[], E = unknown> {
211
+ /** Result of the latest successful run. */
212
+ readonly data: ReadableSignal<T | undefined>;
213
+ /**
214
+ * Error of the latest failed run, carried by reference and never wrapped.
215
+ *
216
+ * `status() === 'error'` is the authoritative failure check, NOT
217
+ * `error() !== undefined`. A rejection can legitimately carry `undefined`
218
+ * (e.g. `Promise.reject()` / `throw undefined`), in which case `status()`
219
+ * is `'error'` while `error()` reads `undefined` — a consumer checking only
220
+ * `error()` would silently miss that failure.
221
+ */
222
+ readonly error: ReadableSignal<E | undefined>;
223
+ /** Current lifecycle status. */
224
+ readonly status: ReadableSignal<ResourceStatus>;
225
+ /** `true` while a run is in flight (plain accessor, see `ResourceHandle.loading`). */
226
+ readonly pending: () => boolean;
227
+ /**
228
+ * Perform the action. Always resolves — never rejects — with an
229
+ * {@link ActionResult}.
230
+ */
231
+ run: (...args: A) => Promise<ActionResult<T, E>>;
232
+ /** Return to `'idle'`, clearing data and error, and abandon any in-flight run. */
233
+ reset: () => void;
234
+ /**
235
+ * Permanently stop the action: aborts the in-flight run and guarantees no
236
+ * signal is ever written again. See {@link ResourceHandle.destroy}.
237
+ */
238
+ destroy: () => void;
239
+ }
240
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/runtime/resource/types.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;GAIG;AAEH;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG;IAC1C,SAAS,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,KAAK,MAAM,IAAI,CAAC;CACnD,CAAC;AAEF,iLAAiL;AACjL;;;;;;;GAOG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,OAAO,CAAC;AAEtE,qLAAqL;AACrL;;;;;;;;;GASG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,KAAK,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEzE,iMAAiM;AACjM;;;;;GAKG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,EAAE,CAAC,SAAS,OAAO,EAAE,IAAI,CACpD,GAAG,IAAI,EAAE,CAAC,KACP,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEpB,mPAAmP;AACnP;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,IACnC;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,C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