@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
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAaxC,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,EAChB,KAAK,YAAY,GAClB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EACL,IAAI,EACJ,YAAY,EACZ,WAAW,EACX,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,UAAU,GAChB,MAAM,QAAQ,CAAC;AAGhB,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,SAAS,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/D,OAAO,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAaxC,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,EAChB,KAAK,YAAY,GAClB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EACL,IAAI,EACJ,YAAY,EACZ,WAAW,EACX,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,UAAU,GAChB,MAAM,QAAQ,CAAC;AAGhB,OAAO,EACL,cAAc,EACd,YAAY,EACZ,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,YAAY,GAClB,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,SAAS,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/D,OAAO,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,iBAAiB,CAAC"}
@@ -12,6 +12,8 @@ export { onDestroy } from './onDestroy';
12
12
  export { loadModule, getModuleRecord, invalidateModule, getResolvedModuleKeys, clearModuleCache, } from './module-cache';
13
13
  // Lazy loading
14
14
  export { lazy, isLazyHandle, preloadLazy, } from './lazy';
15
+ // Async state primitives (reactive query + mutation)
16
+ export { createResource, createAction, } from './resource';
15
17
  // Visibility trigger (IntersectionObserver pool) - from @pithyjs/shared
16
18
  export { DEFAULT_VISIBILITY_MARGIN, observeVisibilityOnce, } from '@pithyjs/shared';
17
19
  // App bootstrap (fresh mount, no hydration)
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,sEAAsE;AACtE,yEAAyE;AACzE,oCAAoC;AACpC,sEAAsE;AAEtE,uEAAuE;AACvE,4DAA4D;AAC5D,0EAA0E;AAC1E,wEAAwE;AAExE,iEAAiE;AACjE,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,GAEjB,MAAM,gBAAgB,CAAC;AAExB,eAAe;AACf,OAAO,EACL,IAAI,EACJ,YAAY,EACZ,WAAW,GAIZ,MAAM,QAAQ,CAAC;AAEhB,wEAAwE;AACxE,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAEzB,4CAA4C;AAC5C,OAAO,EAAE,SAAS,EAAyB,MAAM,aAAa,CAAC;AAE/D,qEAAqE;AACrE,OAAO,EAAE,YAAY,EAAoB,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,sEAAsE;AACtE,yEAAyE;AACzE,oCAAoC;AACpC,sEAAsE;AAEtE,uEAAuE;AACvE,4DAA4D;AAC5D,0EAA0E;AAC1E,wEAAwE;AAExE,iEAAiE;AACjE,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,GAEjB,MAAM,gBAAgB,CAAC;AAExB,eAAe;AACf,OAAO,EACL,IAAI,EACJ,YAAY,EACZ,WAAW,GAIZ,MAAM,QAAQ,CAAC;AAEhB,qDAAqD;AACrD,OAAO,EACL,cAAc,EACd,YAAY,GAUb,MAAM,YAAY,CAAC;AAEpB,wEAAwE;AACxE,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAEzB,4CAA4C;AAC5C,OAAO,EAAE,SAAS,EAAyB,MAAM,aAAa,CAAC;AAE/D,qEAAqE;AACrE,OAAO,EAAE,YAAY,EAAoB,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,44 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource.action",
4
+ "title": "Async Action Primitive",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ import type { ActionHandle, ActionOptions, ActionPerformer } from './types';
10
+ /**
11
+ * Create a reactive async action.
12
+ *
13
+ * Unlike {@link createResource} an action never runs on its own — only an
14
+ * explicit `run()` triggers it — and by default a concurrent `run()` is dropped
15
+ * rather than restarted, so a double-clicked submit button fires once.
16
+ *
17
+ * There is no static-generation special case: an action only runs from an
18
+ * explicit call, and prerendering never calls one, so there is no auto-run to
19
+ * suppress.
20
+ *
21
+ * @typeParam T - Type of the resolved data.
22
+ * @typeParam A - Tuple of arguments forwarded from `run()` to the performer.
23
+ * @typeParam E - Type of the carried error (`unknown` by default).
24
+ * @param performer - Function performing the side effect.
25
+ * @param options - Behaviour options, see {@link ActionOptions}.
26
+ * @returns An {@link ActionHandle} whose `destroy()` MUST be called from the
27
+ * owning component's cleanup.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const save = createAction((draft: Draft) =>
32
+ * fetch('/api/posts', { method: 'POST', body: JSON.stringify(draft) })
33
+ * );
34
+ *
35
+ * const result = await save.run(draft);
36
+ * if (result.ok) toast('Saved');
37
+ * else if (!result.dropped) toast(String(result.error));
38
+ *
39
+ * onDestroy(() => save.destroy());
40
+ * ```
41
+ */
42
+ /** @codexApi {"parent":"pithy.core.resource.action","name":"createAction","stability":"stable","signature":"<T, A extends unknown[] = [], E = unknown>(performer: ActionPerformer<T, A>, options?: ActionOptions) => ActionHandle<T, A, E>"} */
43
+ export declare function createAction<T, A extends unknown[] = [], E = unknown>(performer: ActionPerformer<T, A>, options?: ActionOptions): ActionHandle<T, A, E>;
44
+ //# sourceMappingURL=createAction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createAction.d.ts","sourceRoot":"","sources":["../../../src/runtime/resource/createAction.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAeF,OAAO,KAAK,EACV,YAAY,EACZ,aAAa,EACb,eAAe,EAEhB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,gPAAgP;AAChP,wBAAgB,YAAY,CAAC,CAAC,EAAE,CAAC,SAAS,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,OAAO,EACnE,SAAS,EAAE,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,EAChC,OAAO,GAAE,aAAkB,GAC1B,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAoDvB"}
@@ -0,0 +1,102 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource.action",
4
+ "title": "Async Action Primitive",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ /**
10
+ * `createAction` — reactive async write (a mutation, triggered explicitly).
11
+ *
12
+ * Named `createAction` rather than `createMutation` on purpose: "mutation" is
13
+ * already taken by the site-builder vocabulary (`mutation-vocabulary.ts`,
14
+ * mutation envelopes, the mutation executor) and reusing it here would make
15
+ * two unrelated concepts share a word.
16
+ *
17
+ * @module runtime/resource/createAction
18
+ */
19
+ import { onCleanup } from '@pithyjs/signals';
20
+ import { createAsyncEngine, DROPPED } from './engine';
21
+ /**
22
+ * Create a reactive async action.
23
+ *
24
+ * Unlike {@link createResource} an action never runs on its own — only an
25
+ * explicit `run()` triggers it — and by default a concurrent `run()` is dropped
26
+ * rather than restarted, so a double-clicked submit button fires once.
27
+ *
28
+ * There is no static-generation special case: an action only runs from an
29
+ * explicit call, and prerendering never calls one, so there is no auto-run to
30
+ * suppress.
31
+ *
32
+ * @typeParam T - Type of the resolved data.
33
+ * @typeParam A - Tuple of arguments forwarded from `run()` to the performer.
34
+ * @typeParam E - Type of the carried error (`unknown` by default).
35
+ * @param performer - Function performing the side effect.
36
+ * @param options - Behaviour options, see {@link ActionOptions}.
37
+ * @returns An {@link ActionHandle} whose `destroy()` MUST be called from the
38
+ * owning component's cleanup.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const save = createAction((draft: Draft) =>
43
+ * fetch('/api/posts', { method: 'POST', body: JSON.stringify(draft) })
44
+ * );
45
+ *
46
+ * const result = await save.run(draft);
47
+ * if (result.ok) toast('Saved');
48
+ * else if (!result.dropped) toast(String(result.error));
49
+ *
50
+ * onDestroy(() => save.destroy());
51
+ * ```
52
+ */
53
+ /** @codexApi {"parent":"pithy.core.resource.action","name":"createAction","stability":"stable","signature":"<T, A extends unknown[] = [], E = unknown>(performer: ActionPerformer<T, A>, options?: ActionOptions) => ActionHandle<T, A, E>"} */
54
+ export function createAction(performer, options = {}) {
55
+ const { overlap = 'drop', keepPreviousData = true } = options;
56
+ const engine = createAsyncEngine({ keepPreviousData });
57
+ /**
58
+ * Perform the action.
59
+ *
60
+ * DIVERGENCE, ON PURPOSE: this RESOLVES a discriminated {@link ActionResult}
61
+ * instead of rejecting. The house convention for async elsewhere in this repo
62
+ * is to reject — the router's `executeLoader()` does. A failed mutation,
63
+ * though, is an ordinary UI state (show the message, keep the form filled),
64
+ * not an exception; making it reject forces a try/catch around every submit
65
+ * handler and loses the type of the error. Rejections stay reserved for bugs.
66
+ *
67
+ * The performer receives only the caller's arguments — no `AbortSignal`. A
68
+ * variadic argument tuple leaves no unambiguous slot for one, and adding it
69
+ * would wreck inference of `A` for the common signal-less case. Correctness
70
+ * does not depend on it: the engine's generation counter already guarantees a
71
+ * superseded or destroyed run can never write state.
72
+ */
73
+ function run(...args) {
74
+ // Guards on whether a PERFORMER is still running, not on whether we still
75
+ // want its result. `reset()` clears the latter — that is its job — but the
76
+ // POST it abandoned is still in flight, and an action's performer never
77
+ // receives the AbortSignal, so nothing stops it. Guarding on `isInFlight()`
78
+ // meant Save -> dismiss error (reset) -> Save sent two concurrent requests
79
+ // and could create a duplicate record: precisely what 'drop' prevents.
80
+ if (overlap === 'drop' && engine.hasRunningTask()) {
81
+ return Promise.resolve(DROPPED);
82
+ }
83
+ return engine.execute(() => performer(...args));
84
+ }
85
+ const handle = {
86
+ data: engine.data,
87
+ error: engine.error,
88
+ status: engine.status,
89
+ // Plain accessor rather than computed() — see createResource.ts.
90
+ pending: () => engine.status() === 'loading',
91
+ run,
92
+ reset: engine.reset,
93
+ destroy: engine.destroy,
94
+ };
95
+ // Best effort only — onCleanup() outside an effect is a silent no-op. Under
96
+ // an owner it fires on a re-run as well as on the disposer, so an action
97
+ // built inside an effect is destroyed when that effect re-runs. See
98
+ // createResource.ts and the README for detail.
99
+ onCleanup(() => engine.destroy());
100
+ return handle;
101
+ }
102
+ //# sourceMappingURL=createAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createAction.js","sourceRoot":"","sources":["../../../src/runtime/resource/createAction.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;GASG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAQtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,gPAAgP;AAChP,MAAM,UAAU,YAAY,CAC1B,SAAgC,EAChC,UAAyB,EAAE;IAE3B,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE,gBAAgB,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAE9D,MAAM,MAAM,GAAG,iBAAiB,CAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC;IAE7D;;;;;;;;;;;;;;;OAeG;IACH,SAAS,GAAG,CAAC,GAAG,IAAO;QACrB,0EAA0E;QAC1E,2EAA2E;QAC3E,wEAAwE;QACxE,4EAA4E;QAC5E,2EAA2E;QAC3E,uEAAuE;QACvE,IAAI,OAAO,KAAK,MAAM,IAAI,MAAM,CAAC,cAAc,EAAE,EAAE,CAAC;YAClD,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,MAAM,GAA0B;QACpC,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,iEAAiE;QACjE,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,SAAS;QAC5C,GAAG;QACH,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,OAAO,EAAE,MAAM,CAAC,OAAO;KACxB,CAAC;IAEF,4EAA4E;IAC5E,yEAAyE;IACzE,oEAAoE;IACpE,+CAA+C;IAC/C,SAAS,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,56 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource",
4
+ "title": "Async State Primitive",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ import type { ResourceFetcher, ResourceHandle, ResourceOptions } from './types';
10
+ /**
11
+ * Create a reactive async resource.
12
+ *
13
+ * The fetcher runs immediately by default and again on every `refetch()`. The
14
+ * newest run always wins: a superseded response can never write state, even if
15
+ * its fetcher ignored the abort signal (see `engine.ts`).
16
+ *
17
+ * ## Server rendering
18
+ *
19
+ * Under ANY server render the fetcher is NOT called and the resource resolves to
20
+ * `'idle'` — deliberately not `'loading'`, so a prerendered page ships its
21
+ * empty/idle markup rather than a spinner frozen into the HTML. `refetch()` is
22
+ * inert there too.
23
+ *
24
+ * SCOPE: this covers static generation *and* per-request dynamic SSR. The gate
25
+ * is `isSSRMode()`, and `@pithyjs/ssr` sets `__PITHY_SSR__` in `setupEnvironment()`,
26
+ * which every `renderToString()` call runs — not only the SSG build. Suppression
27
+ * is correct for both: the renderer awaits *route loaders*, which it discovers
28
+ * declaratively from the route tree, and has no way to discover a resource
29
+ * constructed inside a component body mid-render. Server-side data belongs in a
30
+ * loader; a resource that fired here could never contribute to the HTML anyway.
31
+ *
32
+ * The flag is read at call time on purpose: it toggles per render while modules
33
+ * stay cached across renders in one process, so capturing it in a module const
34
+ * would poison every later render.
35
+ *
36
+ * @typeParam T - Type of the resolved data.
37
+ * @typeParam E - Type of the carried error (`unknown` by default — thrown values
38
+ * are carried by reference and never wrapped).
39
+ * @param fetcher - Function producing the data. Receives an `AbortSignal` that is
40
+ * aborted on refetch, reset and destroy.
41
+ * @param options - Behaviour options, see {@link ResourceOptions}.
42
+ * @returns A {@link ResourceHandle} whose `destroy()` MUST be called from the
43
+ * owning component's cleanup.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const user = createResource(signal => fetch('/api/me', { signal }).then(r => r.json()));
48
+ *
49
+ * // in a template: {{ user.loading() ? 'Loading…' : user.data()?.name }}
50
+ *
51
+ * onDestroy(() => user.destroy());
52
+ * ```
53
+ */
54
+ /** @codexApi {"parent":"pithy.core.resource","name":"createResource","stability":"stable","signature":"<T, E = unknown>(fetcher: ResourceFetcher<T>, options?: ResourceOptions) => ResourceHandle<T, E>"} */
55
+ export declare function createResource<T, E = unknown>(fetcher: ResourceFetcher<T>, options?: ResourceOptions): ResourceHandle<T, E>;
56
+ //# sourceMappingURL=createResource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createResource.d.ts","sourceRoot":"","sources":["../../../src/runtime/resource/createResource.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAeF,OAAO,KAAK,EAEV,eAAe,EACf,cAAc,EACd,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,6MAA6M;AAC7M,wBAAgB,cAAc,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,EAC3C,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,EAC3B,OAAO,GAAE,eAAoB,GAC5B,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,CAyCtB"}
@@ -0,0 +1,103 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.core.resource",
4
+ "title": "Async State Primitive",
5
+ "category": "runtime",
6
+ "risk": "high"
7
+ }
8
+ */
9
+ /**
10
+ * `createResource` — reactive async read (a query).
11
+ *
12
+ * Wraps an async fetch in three signals (`data`, `error`, `status`) so a
13
+ * template can bind to loading and error states directly instead of the app
14
+ * hand-rolling `isLoading` booleans around every `await`.
15
+ *
16
+ * @module runtime/resource/createResource
17
+ */
18
+ import { onCleanup } from '@pithyjs/signals';
19
+ import { isSSRMode } from '../../compile/ssrMode';
20
+ import { createAsyncEngine, DROPPED } from './engine';
21
+ /**
22
+ * Create a reactive async resource.
23
+ *
24
+ * The fetcher runs immediately by default and again on every `refetch()`. The
25
+ * newest run always wins: a superseded response can never write state, even if
26
+ * its fetcher ignored the abort signal (see `engine.ts`).
27
+ *
28
+ * ## Server rendering
29
+ *
30
+ * Under ANY server render the fetcher is NOT called and the resource resolves to
31
+ * `'idle'` — deliberately not `'loading'`, so a prerendered page ships its
32
+ * empty/idle markup rather than a spinner frozen into the HTML. `refetch()` is
33
+ * inert there too.
34
+ *
35
+ * SCOPE: this covers static generation *and* per-request dynamic SSR. The gate
36
+ * is `isSSRMode()`, and `@pithyjs/ssr` sets `__PITHY_SSR__` in `setupEnvironment()`,
37
+ * which every `renderToString()` call runs — not only the SSG build. Suppression
38
+ * is correct for both: the renderer awaits *route loaders*, which it discovers
39
+ * declaratively from the route tree, and has no way to discover a resource
40
+ * constructed inside a component body mid-render. Server-side data belongs in a
41
+ * loader; a resource that fired here could never contribute to the HTML anyway.
42
+ *
43
+ * The flag is read at call time on purpose: it toggles per render while modules
44
+ * stay cached across renders in one process, so capturing it in a module const
45
+ * would poison every later render.
46
+ *
47
+ * @typeParam T - Type of the resolved data.
48
+ * @typeParam E - Type of the carried error (`unknown` by default — thrown values
49
+ * are carried by reference and never wrapped).
50
+ * @param fetcher - Function producing the data. Receives an `AbortSignal` that is
51
+ * aborted on refetch, reset and destroy.
52
+ * @param options - Behaviour options, see {@link ResourceOptions}.
53
+ * @returns A {@link ResourceHandle} whose `destroy()` MUST be called from the
54
+ * owning component's cleanup.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const user = createResource(signal => fetch('/api/me', { signal }).then(r => r.json()));
59
+ *
60
+ * // in a template: {{ user.loading() ? 'Loading…' : user.data()?.name }}
61
+ *
62
+ * onDestroy(() => user.destroy());
63
+ * ```
64
+ */
65
+ /** @codexApi {"parent":"pithy.core.resource","name":"createResource","stability":"stable","signature":"<T, E = unknown>(fetcher: ResourceFetcher<T>, options?: ResourceOptions) => ResourceHandle<T, E>"} */
66
+ export function createResource(fetcher, options = {}) {
67
+ const { immediate = true, keepPreviousData = false } = options;
68
+ const engine = createAsyncEngine({ keepPreviousData });
69
+ function refetch() {
70
+ // Read isSSRMode() at CALL time — never hoist it into a module const.
71
+ if (isSSRMode())
72
+ return Promise.resolve(DROPPED);
73
+ return engine.execute(signal => fetcher(signal));
74
+ }
75
+ const handle = {
76
+ data: engine.data,
77
+ error: engine.error,
78
+ status: engine.status,
79
+ // Plain accessor rather than computed(): it still tracks reactively because
80
+ // it reads status() inside the caller's effect, and computed() leaks its
81
+ // internal effect disposer.
82
+ loading: () => engine.status() === 'loading',
83
+ refetch,
84
+ reset: engine.reset,
85
+ destroy: engine.destroy,
86
+ };
87
+ if (immediate) {
88
+ void refetch();
89
+ }
90
+ // Best effort only: onCleanup() outside an effect is a SILENT no-op, so this
91
+ // helps when the resource happens to be created inside one and does nothing
92
+ // otherwise. The explicit destroy() remains the contract.
93
+ //
94
+ // "Best effort" means only that `onCleanup()` outside an effect is a silent
95
+ // no-op. Under an owner this now fires on a re-run as well as on the
96
+ // disposer, so `effect(() => createResource(() => fetch(`/api/u/${id()}`)))`
97
+ // destroys the previous resource on each `id` change instead of leaking one
98
+ // per run. The resource still must not outlive that run: hold it in a
99
+ // `createRoot` if it should. See the README's Async State section.
100
+ onCleanup(() => engine.destroy());
101
+ return handle;
102
+ }
103
+ //# sourceMappingURL=createResource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createResource.js","sourceRoot":"","sources":["../../../src/runtime/resource/createResource.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;GAQG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAQtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,6MAA6M;AAC7M,MAAM,UAAU,cAAc,CAC5B,OAA2B,EAC3B,UAA2B,EAAE;IAE7B,MAAM,EAAE,SAAS,GAAG,IAAI,EAAE,gBAAgB,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;IAE/D,MAAM,MAAM,GAAG,iBAAiB,CAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC;IAE7D,SAAS,OAAO;QACd,sEAAsE;QACtE,IAAI,SAAS,EAAE;YAAE,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACjD,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACnD,CAAC;IAED,MAAM,MAAM,GAAyB;QACnC,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,4EAA4E;QAC5E,yEAAyE;QACzE,4BAA4B;QAC5B,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,SAAS;QAC5C,OAAO;QACP,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,OAAO,EAAE,MAAM,CAAC,OAAO;KACxB,CAAC;IAEF,IAAI,SAAS,EAAE,CAAC;QACd,KAAK,OAAO,EAAE,CAAC;IACjB,CAAC;IAED,6EAA6E;IAC7E,4EAA4E;IAC5E,0DAA0D;IAC1D,EAAE;IACF,4EAA4E;IAC5E,qEAAqE;IACrE,6EAA6E;IAC7E,4EAA4E;IAC5E,sEAAsE;IACtE,mEAAmE;IACnE,SAAS,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,136 @@
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 { type Signal } from '@pithyjs/signals';
75
+ import type { ActionResult, ResourceStatus } from './types';
76
+ /**
77
+ * The single "nothing happened" result value.
78
+ *
79
+ * Structurally assignable to `ActionResult<T, E>` for any `T`/`E`, so it can be
80
+ * returned from every generic entry point without an allocation per call.
81
+ */
82
+ /** @codexApi {"parent":"pithy.core.resource.engine","name":"DROPPED","stability":"experimental","signature":"const DROPPED: { readonly ok: false; readonly dropped: true }"} */
83
+ export declare const DROPPED: {
84
+ readonly ok: false;
85
+ readonly dropped: true;
86
+ };
87
+ /** Construction options for {@link createAsyncEngine}. */
88
+ /** @codexApi {"parent":"pithy.core.resource.engine","name":"AsyncEngineOptions","stability":"experimental","signature":"interface AsyncEngineOptions"} */
89
+ export interface AsyncEngineOptions {
90
+ /** Keep the last successful `data` readable while the next task is in flight. */
91
+ keepPreviousData: boolean;
92
+ }
93
+ /** Internal engine surface consumed by `createResource` / `createAction`. */
94
+ /** @codexApi {"parent":"pithy.core.resource.engine","name":"AsyncEngine","stability":"experimental","signature":"interface AsyncEngine<T, E>"} */
95
+ export interface AsyncEngine<T, E> {
96
+ /** Latest successful value. */
97
+ readonly data: Signal<T | undefined>;
98
+ /** Latest error, carried by reference. */
99
+ readonly error: Signal<E | undefined>;
100
+ /** Current lifecycle status. */
101
+ readonly status: Signal<ResourceStatus>;
102
+ /**
103
+ * Non-reactive flag: is there a run whose result we still want?
104
+ *
105
+ * Cleared by `reset()` and `destroy()`. NOT the overlap guard — see
106
+ * {@link AsyncEngine.hasRunningTask}.
107
+ */
108
+ isInFlight: () => boolean;
109
+ /**
110
+ * Non-reactive flag: is user code (a fetcher or performer) still executing?
111
+ *
112
+ * This is what the `'drop'` overlap policy guards on. It deliberately
113
+ * survives `reset()`, which abandons the result but cannot recall a request
114
+ * already sent — an action's performer never receives the `AbortSignal`, so
115
+ * nothing stops it. Guarding on `isInFlight()` instead let
116
+ * Save -> dismiss -> Save issue two concurrent POSTs.
117
+ */
118
+ hasRunningTask: () => boolean;
119
+ /** Run `task`, transitioning state and resolving (never rejecting) a result. */
120
+ execute: (task: (signal: AbortSignal) => T | Promise<T>) => Promise<ActionResult<T, E>>;
121
+ /** Return to `'idle'` and abandon anything in flight. */
122
+ reset: () => void;
123
+ /** Permanently stop the engine. No signal is written after this returns. */
124
+ destroy: () => void;
125
+ }
126
+ /**
127
+ * Create the shared async-state engine.
128
+ *
129
+ * @typeParam T - Type of the resolved data.
130
+ * @typeParam E - Type of the carried error.
131
+ * @param options - Engine behaviour flags.
132
+ * @returns An {@link AsyncEngine} owning three signals and the run lifecycle.
133
+ */
134
+ /** @codexApi {"parent":"pithy.core.resource.engine","name":"createAsyncEngine","stability":"experimental","signature":"<T, E = unknown>(options: AsyncEngineOptions) => AsyncEngine<T, E>"} */
135
+ export declare function createAsyncEngine<T, E = unknown>(options: AsyncEngineOptions): AsyncEngine<T, E>;
136
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../src/runtime/resource/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAEH,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE5D;;;;;GAKG;AACH,gLAAgL;AAIhL,eAAO,MAAM,OAAO,EAAE;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAA;CAIZ,CAAC;AAEvD,0DAA0D;AAC1D,0JAA0J;AAC1J,MAAM,WAAW,kBAAkB;IACjC,iFAAiF;IACjF,gBAAgB,EAAE,OAAO,CAAC;CAC3B;AAED,6EAA6E;AAC7E,kJAAkJ;AAClJ,MAAM,WAAW,WAAW,CAAC,CAAC,EAAE,CAAC;IAC/B,+BAA+B;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IACrC,0CAA0C;IAC1C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IACtC,gCAAgC;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,cAAc,CAAC,CAAC;IACxC;;;;;OAKG;IACH,UAAU,EAAE,MAAM,OAAO,CAAC;IAC1B;;;;;;;;OAQG;IACH,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,gFAAgF;IAChF,OAAO,EAAE,CACP,IAAI,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,KAC1C,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACjC,yDAAyD;IACzD,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED;;;;;;;GAOG;AACH,+LAA+L;AAC/L,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,EAC9C,OAAO,EAAE,kBAAkB,GAC1B,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,CA0SnB"}