@entifix/react-integration 0.18.2 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +7 -7
  2. package/dist/hooks/use-data-loading/use-data-loading.d.ts +2 -0
  3. package/dist/hooks/use-data-loading/use-data-loading.d.ts.map +1 -1
  4. package/dist/hooks/use-data-loading/use-data-loading.js +8 -1
  5. package/dist/hooks/use-data-loading/use-data-loading.js.map +1 -1
  6. package/dist/hooks/use-entity-form/use-entity-form.d.ts +1 -1
  7. package/dist/hooks/use-entity-form/use-entity-form.d.ts.map +1 -1
  8. package/dist/hooks/use-entity-form/use-entity-form.helpers.d.ts +9 -8
  9. package/dist/hooks/use-entity-form/use-entity-form.helpers.d.ts.map +1 -1
  10. package/dist/hooks/use-entity-form/use-entity-form.helpers.js +33 -17
  11. package/dist/hooks/use-entity-form/use-entity-form.helpers.js.map +1 -1
  12. package/dist/hooks/use-entity-form/use-entity-form.js +9 -16
  13. package/dist/hooks/use-entity-form/use-entity-form.js.map +1 -1
  14. package/dist/hooks/use-entity-form/use-entity-form.types.d.ts +8 -11
  15. package/dist/hooks/use-entity-form/use-entity-form.types.d.ts.map +1 -1
  16. package/dist/hooks/use-entity-form/use-entity-form.types.js.map +1 -1
  17. package/dist/hooks/use-facet-counts/index.d.ts +2 -0
  18. package/dist/hooks/use-facet-counts/index.d.ts.map +1 -0
  19. package/dist/hooks/use-facet-counts/index.js +3 -0
  20. package/dist/hooks/use-facet-counts/index.js.map +1 -0
  21. package/dist/hooks/use-facet-counts/use-facet-counts.d.ts +29 -0
  22. package/dist/hooks/use-facet-counts/use-facet-counts.d.ts.map +1 -0
  23. package/dist/hooks/use-facet-counts/use-facet-counts.js +41 -0
  24. package/dist/hooks/use-facet-counts/use-facet-counts.js.map +1 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/reactive/event-source-push-channel.d.ts.map +1 -1
  30. package/dist/reactive/event-source-push-channel.js +12 -0
  31. package/dist/reactive/event-source-push-channel.js.map +1 -1
  32. package/dist/reactive/push-channel.d.ts +14 -0
  33. package/dist/reactive/push-channel.d.ts.map +1 -1
  34. package/dist/reactive/push-channel.js +10 -2
  35. package/dist/reactive/push-channel.js.map +1 -1
  36. package/dist/reactive/push-router.d.ts +12 -3
  37. package/dist/reactive/push-router.d.ts.map +1 -1
  38. package/dist/reactive/push-router.js +18 -1
  39. package/dist/reactive/push-router.js.map +1 -1
  40. package/dist/reactive/use-push-connection.d.ts +13 -0
  41. package/dist/reactive/use-push-connection.d.ts.map +1 -0
  42. package/dist/reactive/use-push-connection.js +18 -0
  43. package/dist/reactive/use-push-connection.js.map +1 -0
  44. package/package.json +5 -5
@@ -1,5 +1,5 @@
1
1
  import type { Entity, EntityConstructor, EntityDraft, EntityDraftValue, EntityLinkSelection, StandardSchemaV1 } from '@entifix/core';
2
- import type { EntityDraftMessages } from './use-entity-form.helpers.js';
2
+ import type { TranslateKey } from './use-entity-form.helpers.js';
3
3
  /**
4
4
  * Where an autosaved draft is persisted, as the form sees it.
5
5
  *
@@ -53,17 +53,14 @@ export interface UseEntityFormOptions<TEntity extends Entity> {
53
53
  /** Metadata source; fields and their validation rules derive from it. */
54
54
  entityConstructor: EntityConstructor<TEntity>;
55
55
  /**
56
- * Copy for the four field-level validation failures. Omit and the keys
57
- * render, which is what an adopter with no i18n library sees.
56
+ * Resolves a catalog key in the reader's language: the form's validation
57
+ * sentences, a field's `labelKey`, and a schema issue's message, which is
58
+ * authored as a key (`validation.minLength`) so a rule written in one
59
+ * language never reaches a user untranslated. Required, because a form that
60
+ * cannot resolve its copy shows keys. `useTranslateKey` from the controls
61
+ * package is what a host passes.
58
62
  */
59
- validationMessages?: EntityDraftMessages;
60
- /**
61
- * Resolves a schema issue's message, which is authored as a catalog key
62
- * (`validation.minLength`) so a rule written in one language never reaches a
63
- * user untranslated. `useTranslateKey` from the controls package is what a
64
- * host passes; omit it and the message renders as authored.
65
- */
66
- translateKey?: (key: string, params?: Record<string, unknown>) => string;
63
+ translateKey: TranslateKey;
67
64
  /** The record being edited; seeds the initial draft. Omit to create. */
68
65
  entity?: TEntity;
69
66
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"use-entity-form.types.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-entity-form/use-entity-form.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,iBAAiB,EACjB,WAAW,EACX,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAExE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;;;;OAQG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,CAAC;IAC7B;;;;;OAKG;IACH,IAAI,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IAC/B;;;;;;;OAOG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AAED,MAAM,WAAW,oBAAoB,CAAC,OAAO,SAAS,MAAM;IAC1D,yEAAyE;IACzE,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAC9C;;;OAGG;IACH,kBAAkB,CAAC,EAAE,mBAAmB,CAAC;IACzC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC;IACzE,wEAAwE;IACxE,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;OAIG;IACH,KAAK,CAAC,EAAE,gBAAgB,CAAC;IACzB;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B;;;;;;;;;;;;;OAaG;IACH,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3D,uDAAuD;IACvD,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACzD;AAED,MAAM,WAAW,mBAAmB;IAClC,qEAAqE;IACrE,MAAM,EAAE,WAAW,CAAC;IACpB,kEAAkE;IAClE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC1D;;;;;;;;;OASG;IACH,KAAK,EAAE,mBAAmB,CAAC;IAC3B;;;OAGG;IACH,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAC;IAC5D;;;;;;;;OAQG;IACH,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IACtD;;;;;;;;OAQG;IACH,MAAM,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAC/B,8DAA8D;IAC9D,OAAO,EAAE,OAAO,CAAC;CAClB"}
1
+ {"version":3,"file":"use-entity-form.types.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-entity-form/use-entity-form.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,iBAAiB,EACjB,WAAW,EACX,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,YAAY,E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;;;;;OASG;IACH,KAAK,EAAE,mBAAmB,CAAC;IAC3B;;;OAGG;IACH,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAC;IAC5D;;;;;;;;OAQG;IACH,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IACtD;;;;;;;;OAQG;IACH,MAAM,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAC/B,8DAA8D;IAC9D,OAAO,EAAE,OAAO,CAAC;CAClB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/use-entity-form/use-entity-form.types.ts"],"sourcesContent":["import type {\n Entity,\n EntityConstructor,\n EntityDraft,\n EntityDraftValue,\n EntityLinkSelection,\n StandardSchemaV1,\n} from '@entifix/core';\n\nimport type { EntityDraftMessages } from './use-entity-form.helpers.js';\n\n/**\n * Where an autosaved draft is persisted, as the form sees it.\n *\n * A **port**, because the store cannot be imported: `useDraft` and the zustand\n * store behind it are in `@entifix/next-shell` (T4), this package is T3, and\n * `@nx/enforce-module-boundaries` fails the build on the upward edge. Moving\n * the store down would put IndexedDB into the agnostic UI tier, so\n * the shell implements this instead — `useEntityDraft` in `@entifix/next-shell`\n * is the one adapter today.\n *\n * It lives here rather than in `@entifix/core`, and the asymmetry with\n * `EntityLinkSource` is deliberate: that port sits in core because\n * `@entifix/react-controls` and `@entifix/react-integration` are both\n * T3 with no declared edge between them, so they *had* to meet below\n * both. Nothing forces that here — `@entifix/next-shell` already imports this\n * hook — so the port stays beside the options it joins.\n *\n * Everything it carries is JSON round-trippable, because a draft is written\n * through `createJSONStorage`.\n * `EntityDraft` is that guarantee's compile-time half.\n */\nexport interface EntityDraftStore {\n /**\n * The persisted draft, layered over the record's seed — how a workspace\n * restores an autosaved, half-finished edit.\n *\n * It wins on *values*, never on *keys*: a member the entity no longer declares\n * is dropped and one the draft never held keeps its seeded value, so a draft\n * written under an older shape cannot leave a field uncontrolled. See\n * `restoreEntityDraft`.\n */\n readonly draft?: EntityDraft;\n /**\n * Persist the draft. Called on every edit away from the seed.\n *\n * Must be referentially stable across renders: the hook writes from an effect\n * keyed on it, so a new identity each render turns every render into a write.\n */\n save(draft: EntityDraft): void;\n /**\n * Discard the persisted draft.\n *\n * **The hook never calls this.** A draft is spent when the write *commits*,\n * and the hook does not know whether it did — it neither fetches nor saves.\n * The host that owns the mutation calls it on success. Naming it on the port\n * anyway is what stops each host re-deriving the address it would clear by.\n */\n clear(): void;\n}\n\nexport interface UseEntityFormOptions<TEntity extends Entity> {\n /** Metadata source; fields and their validation rules derive from it. */\n entityConstructor: EntityConstructor<TEntity>;\n /**\n * Copy for the four field-level validation failures. Omit and the keys\n * render, which is what an adopter with no i18n library sees.\n */\n validationMessages?: EntityDraftMessages;\n /**\n * Resolves a schema issue's message, which is authored as a catalog key\n * (`validation.minLength`) so a rule written in one language never reaches a\n * user untranslated. `useTranslateKey` from the controls package is what a\n * host passes; omit it and the message renders as authored.\n */\n translateKey?: (key: string, params?: Record<string, unknown>) => string;\n /** The record being edited; seeds the initial draft. Omit to create. */\n entity?: TEntity;\n /**\n * Where to persist this form's draft, so a half-finished edit survives a\n * refresh. Omit and the form is ephemeral — which is what a plain route wants,\n * and why autosave is opt-in rather than a flag a host can set wrong.\n */\n draft?: EntityDraftStore;\n /**\n * Edit only these members, by accessor name. Omit and the form owns them all.\n *\n * It narrows the **descriptors**, so it narrows seeding, coercion *and*\n * validation together — which is the whole point. A wizard splits one entity\n * across several steps, and without this every step would validate the whole\n * record: step one could not advance until members it does not show were\n * filled, and the required-ness of a field would depend on which step you\n * were standing on.\n *\n * The submit therefore receives a **partial** draft. Merging the steps and\n * rebuilding the entity is the host's job, exactly as it already is for one\n * form.\n *\n * A fresh array literal per render is fine: the memo behind it keys on the\n * names rather than the array's identity.\n */\n fields?: readonly string[];\n /**\n * A Standard Schema (Zod, Valibot, ArkType — anything exposing `~standard`)\n * for the rules metadata cannot express: regex, min/max, cross-field.\n *\n * Authored against the **string draft**, so it coerces (`z.coerce.number()`)\n * rather than expecting typed values. Each message is a catalog key\n * (`validation.minLength`), resolved against the `controls` namespace with the\n * literal as its fallback — a rule written in one language would otherwise\n * reach the user untranslated. An issue with no path becomes `formError`.\n *\n * Synchronous rules only: validation runs in a synchronous pass, so an async\n * schema throws rather than silently passing. Put asynchronous checks — a\n * uniqueness lookup, say — behind {@link UseEntityFormOptions.validate}.\n */\n schema?: StandardSchemaV1;\n /**\n * Extra validation beyond the metadata and schema rules, returning a\n * field-name → message map. Applied last, so it wins on conflict.\n */\n validate?: (values: EntityDraft) => Record<string, string>;\n /** Called with the draft once it passes validation. */\n onSubmit: (values: EntityDraft) => void | Promise<void>;\n}\n\nexport interface UseEntityFormResult {\n /** The current draft. Feed straight into `EntityForm`'s `values`. */\n values: EntityDraft;\n /** Field-name → message, surfaced only after a submit attempt. */\n errors: Record<string, string>;\n /**\n * The message that belongs to no single field — a cross-field schema rule.\n * Feed into `EntityForm`'s `formError`, which has nowhere else to show it.\n */\n formError?: string;\n /**\n * Feed into `EntityForm`'s `onFieldChange`.\n *\n * A scalar takes a string; a `composition` takes its list of rows, the one\n * member with no lossless string form.\n */\n setField: (name: string, value: EntityDraftValue) => void;\n /**\n * The instances behind the relation ids the draft holds — seeded from the\n * record's already-materialized links, extended by every pick, and refilled\n * from a resolved id by {@link UseEntityFormResult.hydrateLink}.\n *\n * Pass to `applyEntityLinks` at submit: the draft alone cannot express an\n * embedded relation, because an id is not an entity. It is not persisted — a\n * restored draft arrives with ids and no instances, which is what\n * `hydrateLink` exists to repair.\n */\n links: EntityLinkSelection;\n /**\n * Feed into `EntityForm`'s `onLinkChange`. Records the picked instance and\n * writes its id into the draft, which stays the serializable source of truth.\n */\n setLink: (name: string, entity: Entity | undefined) => void;\n /**\n * Record an instance resolved from an id the draft already held — the restore\n * path, not a pick.\n *\n * Unlike {@link UseEntityFormResult.setLink} it writes only the sidecar, so it\n * cannot dirty a form the user has not touched. It also never overwrites an\n * entry that is already there: a pick in flight is newer than a lookup that\n * started before it.\n */\n hydrateLink: (name: string, resolved: Entity) => void;\n /**\n * Validate, then submit when clean. Feed into `EntityForm`'s `onSubmit`.\n *\n * **Resolves `true` only when the submit actually ran**, so a caller that has\n * to gate on the outcome — a wizard, whose \"Siguiente\" *is* the step's submit\n * — can await it instead of awaiting a tick and re-reading `errors`. A caller\n * with nothing to gate ignores the promise and is unaffected, which is every\n * existing one.\n */\n submit: () => Promise<boolean>;\n /** True once any field has been edited away from its seed. */\n isDirty: boolean;\n}\n"],"names":[],"mappings":"AA8HA,WAuDC"}
1
+ {"version":3,"sources":["../../../src/hooks/use-entity-form/use-entity-form.types.ts"],"sourcesContent":["import type {\n Entity,\n EntityConstructor,\n EntityDraft,\n EntityDraftValue,\n EntityLinkSelection,\n StandardSchemaV1,\n} from '@entifix/core';\n\nimport type { TranslateKey } from './use-entity-form.helpers.js';\n\n/**\n * Where an autosaved draft is persisted, as the form sees it.\n *\n * A **port**, because the store cannot be imported: `useDraft` and the zustand\n * store behind it are in `@entifix/next-shell` (T4), this package is T3, and\n * `@nx/enforce-module-boundaries` fails the build on the upward edge. Moving\n * the store down would put IndexedDB into the agnostic UI tier, so\n * the shell implements this instead — `useEntityDraft` in `@entifix/next-shell`\n * is the one adapter today.\n *\n * It lives here rather than in `@entifix/core`, and the asymmetry with\n * `EntityLinkSource` is deliberate: that port sits in core because\n * `@entifix/react-controls` and `@entifix/react-integration` are both\n * T3 with no declared edge between them, so they *had* to meet below\n * both. Nothing forces that here — `@entifix/next-shell` already imports this\n * hook — so the port stays beside the options it joins.\n *\n * Everything it carries is JSON round-trippable, because a draft is written\n * through `createJSONStorage`.\n * `EntityDraft` is that guarantee's compile-time half.\n */\nexport interface EntityDraftStore {\n /**\n * The persisted draft, layered over the record's seed — how a workspace\n * restores an autosaved, half-finished edit.\n *\n * It wins on *values*, never on *keys*: a member the entity no longer declares\n * is dropped and one the draft never held keeps its seeded value, so a draft\n * written under an older shape cannot leave a field uncontrolled. See\n * `restoreEntityDraft`.\n */\n readonly draft?: EntityDraft;\n /**\n * Persist the draft. Called on every edit away from the seed.\n *\n * Must be referentially stable across renders: the hook writes from an effect\n * keyed on it, so a new identity each render turns every render into a write.\n */\n save(draft: EntityDraft): void;\n /**\n * Discard the persisted draft.\n *\n * **The hook never calls this.** A draft is spent when the write *commits*,\n * and the hook does not know whether it did — it neither fetches nor saves.\n * The host that owns the mutation calls it on success. Naming it on the port\n * anyway is what stops each host re-deriving the address it would clear by.\n */\n clear(): void;\n}\n\nexport interface UseEntityFormOptions<TEntity extends Entity> {\n /** Metadata source; fields and their validation rules derive from it. */\n entityConstructor: EntityConstructor<TEntity>;\n /**\n * Resolves a catalog key in the reader's language: the form's validation\n * sentences, a field's `labelKey`, and a schema issue's message, which is\n * authored as a key (`validation.minLength`) so a rule written in one\n * language never reaches a user untranslated. Required, because a form that\n * cannot resolve its copy shows keys. `useTranslateKey` from the controls\n * package is what a host passes.\n */\n translateKey: TranslateKey;\n /** The record being edited; seeds the initial draft. Omit to create. */\n entity?: TEntity;\n /**\n * Where to persist this form's draft, so a half-finished edit survives a\n * refresh. Omit and the form is ephemeral — which is what a plain route wants,\n * and why autosave is opt-in rather than a flag a host can set wrong.\n */\n draft?: EntityDraftStore;\n /**\n * Edit only these members, by accessor name. Omit and the form owns them all.\n *\n * It narrows the **descriptors**, so it narrows seeding, coercion *and*\n * validation together — which is the whole point. A wizard splits one entity\n * across several steps, and without this every step would validate the whole\n * record: step one could not advance until members it does not show were\n * filled, and the required-ness of a field would depend on which step you\n * were standing on.\n *\n * The submit therefore receives a **partial** draft. Merging the steps and\n * rebuilding the entity is the host's job, exactly as it already is for one\n * form.\n *\n * A fresh array literal per render is fine: the memo behind it keys on the\n * names rather than the array's identity.\n */\n fields?: readonly string[];\n /**\n * A Standard Schema (Zod, Valibot, ArkType — anything exposing `~standard`)\n * for the rules metadata cannot express: regex, min/max, cross-field.\n *\n * Authored against the **string draft**, so it coerces (`z.coerce.number()`)\n * rather than expecting typed values. Each message is a catalog key\n * (`validation.minLength`), resolved against the `controls` namespace with the\n * literal as its fallback — a rule written in one language would otherwise\n * reach the user untranslated. An issue with no path becomes `formError`.\n *\n * Synchronous rules only: validation runs in a synchronous pass, so an async\n * schema throws rather than silently passing. Put asynchronous checks — a\n * uniqueness lookup, say — behind {@link UseEntityFormOptions.validate}.\n */\n schema?: StandardSchemaV1;\n /**\n * Extra validation beyond the metadata and schema rules, returning a\n * field-name → message map. Applied last, so it wins on conflict.\n */\n validate?: (values: EntityDraft) => Record<string, string>;\n /** Called with the draft once it passes validation. */\n onSubmit: (values: EntityDraft) => void | Promise<void>;\n}\n\nexport interface UseEntityFormResult {\n /** The current draft. Feed straight into `EntityForm`'s `values`. */\n values: EntityDraft;\n /** Field-name → message, surfaced only after a submit attempt. */\n errors: Record<string, string>;\n /**\n * The message that belongs to no single field — a cross-field schema rule.\n * Feed into `EntityForm`'s `formError`, which has nowhere else to show it.\n */\n formError?: string;\n /**\n * Feed into `EntityForm`'s `onFieldChange`.\n *\n * A scalar takes a string; a `composition` takes its list of rows, the one\n * member with no lossless string form.\n */\n setField: (name: string, value: EntityDraftValue) => void;\n /**\n * The instances behind the relation ids the draft holds — seeded from the\n * record's already-materialized links, extended by every pick, and refilled\n * from a resolved id by {@link UseEntityFormResult.hydrateLink}.\n *\n * Pass to `applyEntityLinks` at submit: the draft alone cannot express an\n * embedded relation, because an id is not an entity. It is not persisted — a\n * restored draft arrives with ids and no instances, which is what\n * `hydrateLink` exists to repair.\n */\n links: EntityLinkSelection;\n /**\n * Feed into `EntityForm`'s `onLinkChange`. Records the picked instance and\n * writes its id into the draft, which stays the serializable source of truth.\n */\n setLink: (name: string, entity: Entity | undefined) => void;\n /**\n * Record an instance resolved from an id the draft already held — the restore\n * path, not a pick.\n *\n * Unlike {@link UseEntityFormResult.setLink} it writes only the sidecar, so it\n * cannot dirty a form the user has not touched. It also never overwrites an\n * entry that is already there: a pick in flight is newer than a lookup that\n * started before it.\n */\n hydrateLink: (name: string, resolved: Entity) => void;\n /**\n * Validate, then submit when clean. Feed into `EntityForm`'s `onSubmit`.\n *\n * **Resolves `true` only when the submit actually ran**, so a caller that has\n * to gate on the outcome — a wizard, whose \"Siguiente\" *is* the step's submit\n * — can await it instead of awaiting a tick and re-reading `errors`. A caller\n * with nothing to gate ignores the promise and is unaffected, which is every\n * existing one.\n */\n submit: () => Promise<boolean>;\n /** True once any field has been edited away from its seed. */\n isDirty: boolean;\n}\n"],"names":[],"mappings":"AA2HA,WAuDC"}
@@ -0,0 +1,2 @@
1
+ export * from './use-facet-counts.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-facet-counts/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './use-facet-counts.js';
2
+
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/hooks/use-facet-counts/index.ts"],"sourcesContent":["export * from './use-facet-counts.js';\n"],"names":[],"mappings":"AAAA,cAAc,wBAAwB"}
@@ -0,0 +1,29 @@
1
+ import { EntityFacetCounterTag } from '@entifix/business';
2
+ import type { Entity, EntityFacetCounts, FilterGroup } from '@entifix/core';
3
+ import { type Context } from 'effect';
4
+ /** A member to count, by its accessor name and its wire key. */
5
+ export interface FacetMember {
6
+ readonly name: string;
7
+ readonly key: string;
8
+ }
9
+ export interface UseFacetCountsOptions<TEntity extends Entity> {
10
+ /** Where a facet counter runs. Without one nothing is counted. */
11
+ readonly ctx: Context.Context<EntityFacetCounterTag> | undefined;
12
+ /** The members to count — an enum's or a boolean's, typically. */
13
+ readonly members: readonly FacetMember[];
14
+ /** The filtering the list is under. */
15
+ readonly filtering: FilterGroup<TEntity> | undefined;
16
+ /**
17
+ * The entity's query scope, so an invalidation that refreshes the list
18
+ * refreshes its counts with it.
19
+ */
20
+ readonly scope: readonly unknown[];
21
+ }
22
+ /**
23
+ * How many records hold each value of each member, under the list's filtering
24
+ * ([ADR 0012](../../../../../../docs/adr/0012-facet-counts-are-a-port-of-their-own.md)),
25
+ * for a filter panel to show beside its choices. `undefined` until counted, and
26
+ * always without a counter.
27
+ */
28
+ export declare function useFacetCounts<TEntity extends Entity>({ ctx, members, filtering, scope, }: UseFacetCountsOptions<TEntity>): EntityFacetCounts | undefined;
29
+ //# sourceMappingURL=use-facet-counts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-facet-counts.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-facet-counts/use-facet-counts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAwB,MAAM,mBAAmB,CAAC;AAChF,OAAO,KAAK,EACV,MAAM,EACN,iBAAiB,EAGjB,WAAW,EACZ,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,KAAK,OAAO,EAAU,MAAM,QAAQ,CAAC;AAE9C,gEAAgE;AAChE,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,qBAAqB,CAAC,OAAO,SAAS,MAAM;IAC3D,kEAAkE;IAClE,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,SAAS,CAAC;IACjE,kEAAkE;IAClE,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,uCAAuC;IACvC,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC;IACrD;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,SAAS,OAAO,EAAE,CAAC;CACpC;AAwBD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,EACrD,GAAG,EACH,OAAO,EACP,SAAS,EACT,KAAK,GACN,EAAE,qBAAqB,CAAC,OAAO,CAAC,GAAG,iBAAiB,GAAG,SAAS,CAwBhE"}
@@ -0,0 +1,41 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { facetCountsUCFactory } from '@entifix/business';
3
+ import { useQuery } from '@tanstack/react-query';
4
+ import { Effect } from 'effect';
5
+ /**
6
+ * The filtering a member is counted under: the list's own, less any filter on
7
+ * that member — so choosing one value does not drop every other value's count
8
+ * to zero. Only an `and` group can lose a clause and stay a narrowing of the
9
+ * same list; an `or` group is counted as it stands.
10
+ */ function withoutMember(filtering, member) {
11
+ if (filtering.operator !== 'and') return filtering;
12
+ return _extends({}, filtering, {
13
+ values: filtering.values.filter((node)=>!('property' in node) || String(node.property) !== member.name && String(node.property) !== member.key)
14
+ });
15
+ }
16
+ /**
17
+ * How many records hold each value of each member, under the list's filtering
18
+ * ([ADR 0012](../../../../../../docs/adr/0012-facet-counts-are-a-port-of-their-own.md)),
19
+ * for a filter panel to show beside its choices. `undefined` until counted, and
20
+ * always without a counter.
21
+ */ export function useFacetCounts({ ctx, members, filtering, scope }) {
22
+ const queries = members.map((member)=>_extends({
23
+ member: member.name
24
+ }, filtering === undefined ? {} : {
25
+ filtering: [
26
+ withoutMember(filtering, member)
27
+ ]
28
+ }));
29
+ const { data } = useQuery({
30
+ enabled: ctx !== undefined && members.length > 0,
31
+ queryKey: [
32
+ ...scope,
33
+ '$facets',
34
+ queries
35
+ ],
36
+ queryFn: ()=>Effect.runPromise(Effect.provide(facetCountsUCFactory(queries), ctx))
37
+ });
38
+ return data;
39
+ }
40
+
41
+ //# sourceMappingURL=use-facet-counts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/hooks/use-facet-counts/use-facet-counts.ts"],"sourcesContent":["import { EntityFacetCounterTag, facetCountsUCFactory } from '@entifix/business';\nimport type {\n Entity,\n EntityFacetCounts,\n EntityFacetQuery,\n EntityFiltering,\n FilterGroup,\n} from '@entifix/core';\nimport { useQuery } from '@tanstack/react-query';\nimport { type Context, Effect } from 'effect';\n\n/** A member to count, by its accessor name and its wire key. */\nexport interface FacetMember {\n readonly name: string;\n readonly key: string;\n}\n\nexport interface UseFacetCountsOptions<TEntity extends Entity> {\n /** Where a facet counter runs. Without one nothing is counted. */\n readonly ctx: Context.Context<EntityFacetCounterTag> | undefined;\n /** The members to count — an enum's or a boolean's, typically. */\n readonly members: readonly FacetMember[];\n /** The filtering the list is under. */\n readonly filtering: FilterGroup<TEntity> | undefined;\n /**\n * The entity's query scope, so an invalidation that refreshes the list\n * refreshes its counts with it.\n */\n readonly scope: readonly unknown[];\n}\n\n/**\n * The filtering a member is counted under: the list's own, less any filter on\n * that member — so choosing one value does not drop every other value's count\n * to zero. Only an `and` group can lose a clause and stay a narrowing of the\n * same list; an `or` group is counted as it stands.\n */\nfunction withoutMember<TEntity extends Entity>(\n filtering: FilterGroup<TEntity>,\n member: FacetMember,\n): FilterGroup<TEntity> {\n if (filtering.operator !== 'and') return filtering;\n return {\n ...filtering,\n values: filtering.values.filter(\n node =>\n !('property' in node) ||\n (String(node.property) !== member.name &&\n String(node.property) !== member.key),\n ),\n };\n}\n\n/**\n * How many records hold each value of each member, under the list's filtering\n * ([ADR 0012](../../../../../../docs/adr/0012-facet-counts-are-a-port-of-their-own.md)),\n * for a filter panel to show beside its choices. `undefined` until counted, and\n * always without a counter.\n */\nexport function useFacetCounts<TEntity extends Entity>({\n ctx,\n members,\n filtering,\n scope,\n}: UseFacetCountsOptions<TEntity>): EntityFacetCounts | undefined {\n const queries: EntityFacetQuery<TEntity>[] = members.map(member => ({\n member: member.name as keyof TEntity & string,\n ...(filtering === undefined\n ? {}\n : {\n filtering: [\n withoutMember(filtering, member) as EntityFiltering<TEntity>,\n ],\n }),\n }));\n\n const { data } = useQuery({\n enabled: ctx !== undefined && members.length > 0,\n queryKey: [...scope, '$facets', queries],\n queryFn: () =>\n Effect.runPromise(\n Effect.provide(\n facetCountsUCFactory(queries),\n ctx as Context.Context<EntityFacetCounterTag>,\n ),\n ),\n });\n return data;\n}\n"],"names":["facetCountsUCFactory","useQuery","Effect","withoutMember","filtering","member","operator","values","filter","node","String","property","name","key","useFacetCounts","ctx","members","scope","queries","map","undefined","data","enabled","length","queryKey","queryFn","runPromise","provide"],"mappings":";AAAA,SAAgCA,oBAAoB,QAAQ,oBAAoB;AAQhF,SAASC,QAAQ,QAAQ,wBAAwB;AACjD,SAAuBC,MAAM,QAAQ,SAAS;AAsB9C;;;;;CAKC,GACD,SAASC,cACPC,SAA+B,EAC/BC,MAAmB;IAEnB,IAAID,UAAUE,QAAQ,KAAK,OAAO,OAAOF;IACzC,OAAO,aACFA;QACHG,QAAQH,UAAUG,MAAM,CAACC,MAAM,CAC7BC,CAAAA,OACE,CAAE,CAAA,cAAcA,IAAG,KAClBC,OAAOD,KAAKE,QAAQ,MAAMN,OAAOO,IAAI,IACpCF,OAAOD,KAAKE,QAAQ,MAAMN,OAAOQ,GAAG;;AAG9C;AAEA;;;;;CAKC,GACD,OAAO,SAASC,eAAuC,EACrDC,GAAG,EACHC,OAAO,EACPZ,SAAS,EACTa,KAAK,EAC0B;IAC/B,MAAMC,UAAuCF,QAAQG,GAAG,CAACd,CAAAA,SAAW;YAClEA,QAAQA,OAAOO,IAAI;WACfR,cAAcgB,YACd,CAAC,IACD;YACEhB,WAAW;gBACTD,cAAcC,WAAWC;aAC1B;QACH;IAGN,MAAM,EAAEgB,IAAI,EAAE,GAAGpB,SAAS;QACxBqB,SAASP,QAAQK,aAAaJ,QAAQO,MAAM,GAAG;QAC/CC,UAAU;eAAIP;YAAO;YAAWC;SAAQ;QACxCO,SAAS,IACPvB,OAAOwB,UAAU,CACfxB,OAAOyB,OAAO,CACZ3B,qBAAqBkB,UACrBH;IAGR;IACA,OAAOM;AACT"}
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export * from './hooks/use-entity-link-source/index.js';
6
6
  export * from './hooks/use-entity-mutation/index.js';
7
7
  export * from './hooks/use-entity-record/index.js';
8
8
  export * from './hooks/use-entity-use-cases/index.js';
9
+ export * from './hooks/use-facet-counts/index.js';
9
10
  export * from './hooks/use-wizard/index.js';
10
11
  export * from './pending/pending-flow-store.js';
11
12
  export * from './pending/use-optimistic-mutation.js';
@@ -15,6 +16,7 @@ export * from './query/entity-query-key.js';
15
16
  export * from './query/query-provider.js';
16
17
  export * from './reactive/push-channel.js';
17
18
  export * from './reactive/reactive-channel.js';
19
+ export * from './reactive/use-push-connection.js';
18
20
  export * from './reactive/use-reactive-cache.js';
19
21
  export * from './reactive/use-reactive-invalidation.js';
20
22
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qCAAqC,CAAC;AACpD,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC;AACjD,cAAc,2CAA2C,CAAC;AAC1D,cAAc,yCAAyC,CAAC;AACxD,cAAc,sCAAsC,CAAC;AACrD,cAAc,oCAAoC,CAAC;AACnD,cAAc,uCAAuC,CAAC;AACtD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,sCAAsC,CAAC;AACrD,cAAc,0CAA0C,CAAC;AACzD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yCAAyC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qCAAqC,CAAC;AACpD,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC;AACjD,cAAc,2CAA2C,CAAC;AAC1D,cAAc,yCAAyC,CAAC;AACxD,cAAc,sCAAsC,CAAC;AACrD,cAAc,oCAAoC,CAAC;AACnD,cAAc,uCAAuC,CAAC;AACtD,cAAc,mCAAmC,CAAC;AAClD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,sCAAsC,CAAC;AACrD,cAAc,0CAA0C,CAAC;AACzD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC;AACjD,cAAc,yCAAyC,CAAC"}
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export * from './hooks/use-entity-link-source/index.js';
6
6
  export * from './hooks/use-entity-mutation/index.js';
7
7
  export * from './hooks/use-entity-record/index.js';
8
8
  export * from './hooks/use-entity-use-cases/index.js';
9
+ export * from './hooks/use-facet-counts/index.js';
9
10
  export * from './hooks/use-wizard/index.js';
10
11
  export * from './pending/pending-flow-store.js';
11
12
  export * from './pending/use-optimistic-mutation.js';
@@ -15,6 +16,7 @@ export * from './query/entity-query-key.js';
15
16
  export * from './query/query-provider.js';
16
17
  export * from './reactive/push-channel.js';
17
18
  export * from './reactive/reactive-channel.js';
19
+ export * from './reactive/use-push-connection.js';
18
20
  export * from './reactive/use-reactive-cache.js';
19
21
  export * from './reactive/use-reactive-invalidation.js';
20
22
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './context/adapters-context/index.js';\nexport * from './hooks/use-data-loading/index.js';\nexport * from './hooks/use-entity-form/index.js';\nexport * from './hooks/use-entity-link-resolver/index.js';\nexport * from './hooks/use-entity-link-source/index.js';\nexport * from './hooks/use-entity-mutation/index.js';\nexport * from './hooks/use-entity-record/index.js';\nexport * from './hooks/use-entity-use-cases/index.js';\nexport * from './hooks/use-wizard/index.js';\nexport * from './pending/pending-flow-store.js';\nexport * from './pending/use-optimistic-mutation.js';\nexport * from './pending/use-pending-flow-settlement.js';\nexport * from './query/combine-filtering.js';\nexport * from './query/entity-query-key.js';\nexport * from './query/query-provider.js';\nexport * from './reactive/push-channel.js';\nexport * from './reactive/reactive-channel.js';\nexport * from './reactive/use-reactive-cache.js';\nexport * from './reactive/use-reactive-invalidation.js';\n"],"names":[],"mappings":"AAAA,cAAc,sCAAsC;AACpD,cAAc,oCAAoC;AAClD,cAAc,mCAAmC;AACjD,cAAc,4CAA4C;AAC1D,cAAc,0CAA0C;AACxD,cAAc,uCAAuC;AACrD,cAAc,qCAAqC;AACnD,cAAc,wCAAwC;AACtD,cAAc,8BAA8B;AAC5C,cAAc,kCAAkC;AAChD,cAAc,uCAAuC;AACrD,cAAc,2CAA2C;AACzD,cAAc,+BAA+B;AAC7C,cAAc,8BAA8B;AAC5C,cAAc,4BAA4B;AAC1C,cAAc,6BAA6B;AAC3C,cAAc,iCAAiC;AAC/C,cAAc,mCAAmC;AACjD,cAAc,0CAA0C"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './context/adapters-context/index.js';\nexport * from './hooks/use-data-loading/index.js';\nexport * from './hooks/use-entity-form/index.js';\nexport * from './hooks/use-entity-link-resolver/index.js';\nexport * from './hooks/use-entity-link-source/index.js';\nexport * from './hooks/use-entity-mutation/index.js';\nexport * from './hooks/use-entity-record/index.js';\nexport * from './hooks/use-entity-use-cases/index.js';\nexport * from './hooks/use-facet-counts/index.js';\nexport * from './hooks/use-wizard/index.js';\nexport * from './pending/pending-flow-store.js';\nexport * from './pending/use-optimistic-mutation.js';\nexport * from './pending/use-pending-flow-settlement.js';\nexport * from './query/combine-filtering.js';\nexport * from './query/entity-query-key.js';\nexport * from './query/query-provider.js';\nexport * from './reactive/push-channel.js';\nexport * from './reactive/reactive-channel.js';\nexport * from './reactive/use-push-connection.js';\nexport * from './reactive/use-reactive-cache.js';\nexport * from './reactive/use-reactive-invalidation.js';\n"],"names":[],"mappings":"AAAA,cAAc,sCAAsC;AACpD,cAAc,oCAAoC;AAClD,cAAc,mCAAmC;AACjD,cAAc,4CAA4C;AAC1D,cAAc,0CAA0C;AACxD,cAAc,uCAAuC;AACrD,cAAc,qCAAqC;AACnD,cAAc,wCAAwC;AACtD,cAAc,oCAAoC;AAClD,cAAc,8BAA8B;AAC5C,cAAc,kCAAkC;AAChD,cAAc,uCAAuC;AACrD,cAAc,2CAA2C;AACzD,cAAc,+BAA+B;AAC7C,cAAc,8BAA8B;AAC5C,cAAc,4BAA4B;AAC1C,cAAc,6BAA6B;AAC3C,cAAc,iCAAiC;AAC/C,cAAc,oCAAoC;AAClD,cAAc,mCAAmC;AACjD,cAAc,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"event-source-push-channel.d.ts","sourceRoot":"","sources":["../../src/reactive/event-source-push-channel.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,uEAAuE;AACvE,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,wEAAwE;AACxE,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAClD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,MAAM,WAAW,6BAA6B;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAChD;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,sBAAuB,SAAQ,WAAW;IACzD;;;;OAIG;IACH,OAAO,IAAI,MAAM,CAAC;CACnB;AAmCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CAAC,EACzC,GAAG,EACH,OAAO,EACP,YAAuB,EACvB,aAAkB,GACnB,EAAE,6BAA6B,GAAG,sBAAsB,CA8FxD"}
1
+ {"version":3,"file":"event-source-push-channel.d.ts","sourceRoot":"","sources":["../../src/reactive/event-source-push-channel.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,uEAAuE;AACvE,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,wEAAwE;AACxE,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAClD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,MAAM,WAAW,6BAA6B;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAChD;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,sBAAuB,SAAQ,WAAW;IACzD;;;;OAIG;IACH,OAAO,IAAI,MAAM,CAAC;CACnB;AAmCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CAAC,EACzC,GAAG,EACH,OAAO,EACP,YAAuB,EACvB,aAAkB,GACnB,EAAE,6BAA6B,GAAG,sBAAsB,CA4GxD"}
@@ -65,6 +65,11 @@ const decodeEventFrame = (body)=>Effect.flatMap(Schema.decodeUnknownEffect(Event
65
65
  opened.onopen = ()=>{
66
66
  router.connected();
67
67
  };
68
+ // A dropped stream: the browser retries on its own while the source is
69
+ // `CONNECTING`, and has given up once it is `CLOSED`.
70
+ opened.onerror = ()=>{
71
+ router.disconnected(opened.readyState === EventSource.CLOSED ? 'closed' : 'reconnecting');
72
+ };
68
73
  opened.onmessage = (message)=>{
69
74
  if (message.lastEventId !== '') lastEventId = message.lastEventId;
70
75
  const frame = parse(message.data, decodeEventFrame);
@@ -111,6 +116,13 @@ const decodeEventFrame = (body)=>Effect.flatMap(Schema.decodeUnknownEffect(Event
111
116
  subscribe: router.subscribe,
112
117
  onConnect: router.onConnect,
113
118
  onResync: router.onResync,
119
+ connection: router.connection,
120
+ onConnectionChange: router.onConnectionChange,
121
+ reconnect: ()=>{
122
+ // Forgets the open stream, so the sync opens a fresh one at once.
123
+ close();
124
+ sync();
125
+ },
114
126
  dropped: ()=>dropped
115
127
  };
116
128
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/reactive/event-source-push-channel.ts"],"sourcesContent":["import { decodeEvent, type DomainEvent } from '@entifix/core';\nimport { Effect, Result, Schema } from 'effect';\n\nimport type { PushChannel } from './push-channel.js';\nimport { makePushRouter } from './push-router.js';\n\n/** The stream URL's repeated parameter naming one subscribed topic. */\nexport const PUSH_TOPIC_PARAM = 'topic';\n/** The stream URL's repeated parameter carrying one flow capability. */\nexport const PUSH_CAPABILITY_PARAM = 'capability';\n/**\n * The stream URL's parameter carrying the last event id seen, on a reopen. A\n * new `EventSource` cannot set the `Last-Event-ID` header itself.\n */\nexport const PUSH_CURSOR_PARAM = 'lastEventId';\n\nexport interface EventSourcePushChannelOptions {\n /** The stream's same-origin URL, without the topic parameters. */\n readonly url: string;\n /**\n * Refreshes the session when the server asks for a reauth. The stream stays\n * closed until it resolves; a rejection leaves it closed until the next\n * change of interest, because reopening on a credential known to be dead is\n * a `401`, which an `EventSource` never retries.\n */\n readonly refresh: () => Promise<void>;\n /**\n * The flow capabilities to present, read at every open. A host that hands\n * an anonymous holder a capability returns it here.\n */\n readonly capabilities?: () => readonly string[];\n /**\n * How long a change of interest waits before reopening, in milliseconds, so\n * a screen mounting five subscriptions reopens once. Defaults to 25.\n */\n readonly reopenDelayMs?: number;\n}\n\nexport interface EventSourcePushChannel extends PushChannel {\n /**\n * How many frames this channel dropped because they did not decode. A frame\n * is dropped rather than thrown, so the count is the only trace a drifted\n * server leaves in the browser.\n */\n dropped(): number;\n}\n\nconst EventFrame = Schema.Struct({\n topics: Schema.Array(Schema.String),\n envelope: Schema.Unknown,\n});\n\nconst ResyncFrame = Schema.Struct({ topics: Schema.Array(Schema.String) });\n\nconst parse = <A>(\n raw: string,\n decode: (body: unknown) => Effect.Effect<A, unknown>,\n): Result.Result<A, unknown> =>\n Effect.runSync(\n Effect.result(\n Effect.flatMap(\n Effect.try(() => JSON.parse(raw) as unknown),\n decode,\n ),\n ),\n );\n\nconst decodeEventFrame = (\n body: unknown,\n): Effect.Effect<\n { readonly topics: readonly string[]; readonly event: DomainEvent },\n unknown\n> =>\n Effect.flatMap(Schema.decodeUnknownEffect(EventFrame)(body), frame =>\n Effect.map(decodeEvent(frame.envelope), event => ({\n topics: frame.topics,\n event,\n })),\n );\n\n/**\n * The push channel's browser end: **one** `EventSource` per tab per base URL,\n * multiplexing every subscribed topic\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n *\n * The topic set is the stream's URL, so a change of interest closes the stream\n * and opens a new one, carrying the last event id so the server can resume.\n * The reopen is debounced; a stream nobody listens to is closed on the same\n * delay. Every frame is decoded through the message registry, and one that\n * does not decode is dropped and counted.\n *\n * On `event: reauth` the stream is closed at once — before the server's EOF\n * could make the browser reconnect on the expiring cookie — and reopened only\n * once `refresh` resolves.\n */\nexport function makeEventSourcePushChannel({\n url,\n refresh,\n capabilities = () => [],\n reopenDelayMs = 25,\n}: EventSourcePushChannelOptions): EventSourcePushChannel {\n const router = makePushRouter();\n let source: EventSource | undefined;\n let openedUrl: string | undefined;\n let lastEventId: string | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let refreshing = false;\n let dropped = 0;\n\n const streamUrl = (): string | undefined => {\n const topics = router.topics();\n if (topics.length === 0) return undefined;\n const params = new URLSearchParams();\n for (const topic of topics) params.append(PUSH_TOPIC_PARAM, topic);\n for (const capability of [...capabilities()].sort())\n params.append(PUSH_CAPABILITY_PARAM, capability);\n return `${url}${url.includes('?') ? '&' : '?'}${params.toString()}`;\n };\n\n const close = (): void => {\n source?.close();\n source = undefined;\n openedUrl = undefined;\n router.disconnected();\n };\n\n const open = (target: string): void => {\n const cursor =\n lastEventId === undefined\n ? ''\n : `&${PUSH_CURSOR_PARAM}=${encodeURIComponent(lastEventId)}`;\n const opened = new EventSource(`${target}${cursor}`);\n source = opened;\n openedUrl = target;\n opened.onopen = () => {\n router.connected();\n };\n opened.onmessage = message => {\n if (message.lastEventId !== '') lastEventId = message.lastEventId;\n const frame = parse(message.data as string, decodeEventFrame);\n if (Result.isFailure(frame)) {\n dropped += 1;\n return;\n }\n router.deliver(frame.success.topics, frame.success.event);\n };\n opened.addEventListener('resync', message => {\n const frame = parse(\n (message as MessageEvent).data as string,\n Schema.decodeUnknownEffect(ResyncFrame),\n );\n if (Result.isFailure(frame)) {\n dropped += 1;\n return;\n }\n router.resync(frame.success.topics);\n });\n opened.addEventListener('reauth', () => {\n close();\n refreshing = true;\n refresh().then(\n () => {\n refreshing = false;\n sync();\n },\n () => {\n refreshing = false;\n },\n );\n });\n };\n\n // Brings the stream in line with the subscribed topics: closes it when\n // nothing listens, reopens it when the topics or capabilities moved.\n const sync = (): void => {\n // Guarded because a server-rendered pass has no `EventSource` at all.\n if (refreshing || typeof EventSource === 'undefined') return;\n const target = streamUrl();\n if (target === openedUrl) return;\n close();\n if (target !== undefined) open(target);\n };\n\n router.onTopicsChange(() => {\n clearTimeout(timer);\n timer = setTimeout(sync, reopenDelayMs);\n });\n\n return {\n subscribe: router.subscribe,\n onConnect: router.onConnect,\n onResync: router.onResync,\n dropped: () => dropped,\n };\n}\n"],"names":["decodeEvent","Effect","Result","Schema","makePushRouter","PUSH_TOPIC_PARAM","PUSH_CAPABILITY_PARAM","PUSH_CURSOR_PARAM","EventFrame","Struct","topics","Array","String","envelope","Unknown","ResyncFrame","parse","raw","decode","runSync","result","flatMap","try","JSON","decodeEventFrame","body","decodeUnknownEffect","frame","map","event","makeEventSourcePushChannel","url","refresh","capabilities","reopenDelayMs","router","source","openedUrl","lastEventId","timer","refreshing","dropped","streamUrl","length","undefined","params","URLSearchParams","topic","append","capability","sort","includes","toString","close","disconnected","open","target","cursor","encodeURIComponent","opened","EventSource","onopen","connected","onmessage","message","data","isFailure","deliver","success","addEventListener","resync","then","sync","onTopicsChange","clearTimeout","setTimeout","subscribe","onConnect","onResync"],"mappings":"AAAA,SAASA,WAAW,QAA0B,gBAAgB;AAC9D,SAASC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAGhD,SAASC,cAAc,QAAQ,mBAAmB;AAElD,qEAAqE,GACrE,OAAO,MAAMC,mBAAmB,QAAQ;AACxC,sEAAsE,GACtE,OAAO,MAAMC,wBAAwB,aAAa;AAClD;;;CAGC,GACD,OAAO,MAAMC,oBAAoB,cAAc;AAiC/C,MAAMC,aAAaL,OAAOM,MAAM,CAAC;IAC/BC,QAAQP,OAAOQ,KAAK,CAACR,OAAOS,MAAM;IAClCC,UAAUV,OAAOW,OAAO;AAC1B;AAEA,MAAMC,cAAcZ,OAAOM,MAAM,CAAC;IAAEC,QAAQP,OAAOQ,KAAK,CAACR,OAAOS,MAAM;AAAE;AAExE,MAAMI,QAAQ,CACZC,KACAC,SAEAjB,OAAOkB,OAAO,CACZlB,OAAOmB,MAAM,CACXnB,OAAOoB,OAAO,CACZpB,OAAOqB,GAAG,CAAC,IAAMC,KAAKP,KAAK,CAACC,OAC5BC;AAKR,MAAMM,mBAAmB,CACvBC,OAKAxB,OAAOoB,OAAO,CAAClB,OAAOuB,mBAAmB,CAAClB,YAAYiB,OAAOE,CAAAA,QAC3D1B,OAAO2B,GAAG,CAAC5B,YAAY2B,MAAMd,QAAQ,GAAGgB,CAAAA,QAAU,CAAA;gBAChDnB,QAAQiB,MAAMjB,MAAM;gBACpBmB;YACF,CAAA;AAGJ;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O,CAACxC,MAAMyC,OAAO,CAAC1D,MAAM,EAAEiB,MAAMyC,OAAO,CAACvC,KAAK;QAC1D;QACA8B,OAAOU,gBAAgB,CAAC,UAAUL,CAAAA;YAChC,MAAMrC,QAAQX,MACZ,AAACgD,QAAyBC,IAAI,EAC9B9D,OAAOuB,mBAAmB,CAACX;YAE7B,IAAIb,OAAOgE,SAAS,CAACvC,QAAQ;gBAC3Bc,WAAW;gBACX;YACF;YACAN,OAAOmC,MAAM,CAAC3C,MAAMyC,OAAO,CAAC1D,MAAM;QACpC;QACAiD,OAAOU,gBAAgB,CAAC,UAAU;YAChChB;YACAb,aAAa;YACbR,UAAUuC,IAAI,CACZ;gBACE/B,aAAa;gBACbgC;YACF,GACA;gBACEhC,aAAa;YACf;QAEJ;IACF;IAEA,uEAAuE;IACvE,qEAAqE;IACrE,MAAMgC,OAAO;QACX,sEAAsE;QACtE,IAAIhC,cAAc,OAAOoB,gBAAgB,aAAa;QACtD,MAAMJ,SAASd;QACf,IAAIc,WAAWnB,WAAW;QAC1BgB;QACA,IAAIG,WAAWZ,WAAWW,KAAKC;IACjC;IAEArB,OAAOsC,cAAc,CAAC;QACpBC,aAAanC;QACbA,QAAQoC,WAAWH,MAAMtC;IAC3B;IAEA,OAAO;QACL0C,WAAWzC,OAAOyC,SAAS;QAC3BC,WAAW1C,OAAO0C,SAAS;QAC3BC,UAAU3C,OAAO2C,QAAQ;QACzBrC,SAAS,IAAMA;IACjB;AACF"}
1
+ {"version":3,"sources":["../../src/reactive/event-source-push-channel.ts"],"sourcesContent":["import { decodeEvent, type DomainEvent } from '@entifix/core';\nimport { Effect, Result, Schema } from 'effect';\n\nimport type { PushChannel } from './push-channel.js';\nimport { makePushRouter } from './push-router.js';\n\n/** The stream URL's repeated parameter naming one subscribed topic. */\nexport const PUSH_TOPIC_PARAM = 'topic';\n/** The stream URL's repeated parameter carrying one flow capability. */\nexport const PUSH_CAPABILITY_PARAM = 'capability';\n/**\n * The stream URL's parameter carrying the last event id seen, on a reopen. A\n * new `EventSource` cannot set the `Last-Event-ID` header itself.\n */\nexport const PUSH_CURSOR_PARAM = 'lastEventId';\n\nexport interface EventSourcePushChannelOptions {\n /** The stream's same-origin URL, without the topic parameters. */\n readonly url: string;\n /**\n * Refreshes the session when the server asks for a reauth. The stream stays\n * closed until it resolves; a rejection leaves it closed until the next\n * change of interest, because reopening on a credential known to be dead is\n * a `401`, which an `EventSource` never retries.\n */\n readonly refresh: () => Promise<void>;\n /**\n * The flow capabilities to present, read at every open. A host that hands\n * an anonymous holder a capability returns it here.\n */\n readonly capabilities?: () => readonly string[];\n /**\n * How long a change of interest waits before reopening, in milliseconds, so\n * a screen mounting five subscriptions reopens once. Defaults to 25.\n */\n readonly reopenDelayMs?: number;\n}\n\nexport interface EventSourcePushChannel extends PushChannel {\n /**\n * How many frames this channel dropped because they did not decode. A frame\n * is dropped rather than thrown, so the count is the only trace a drifted\n * server leaves in the browser.\n */\n dropped(): number;\n}\n\nconst EventFrame = Schema.Struct({\n topics: Schema.Array(Schema.String),\n envelope: Schema.Unknown,\n});\n\nconst ResyncFrame = Schema.Struct({ topics: Schema.Array(Schema.String) });\n\nconst parse = <A>(\n raw: string,\n decode: (body: unknown) => Effect.Effect<A, unknown>,\n): Result.Result<A, unknown> =>\n Effect.runSync(\n Effect.result(\n Effect.flatMap(\n Effect.try(() => JSON.parse(raw) as unknown),\n decode,\n ),\n ),\n );\n\nconst decodeEventFrame = (\n body: unknown,\n): Effect.Effect<\n { readonly topics: readonly string[]; readonly event: DomainEvent },\n unknown\n> =>\n Effect.flatMap(Schema.decodeUnknownEffect(EventFrame)(body), frame =>\n Effect.map(decodeEvent(frame.envelope), event => ({\n topics: frame.topics,\n event,\n })),\n );\n\n/**\n * The push channel's browser end: **one** `EventSource` per tab per base URL,\n * multiplexing every subscribed topic\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n *\n * The topic set is the stream's URL, so a change of interest closes the stream\n * and opens a new one, carrying the last event id so the server can resume.\n * The reopen is debounced; a stream nobody listens to is closed on the same\n * delay. Every frame is decoded through the message registry, and one that\n * does not decode is dropped and counted.\n *\n * On `event: reauth` the stream is closed at once — before the server's EOF\n * could make the browser reconnect on the expiring cookie — and reopened only\n * once `refresh` resolves.\n */\nexport function makeEventSourcePushChannel({\n url,\n refresh,\n capabilities = () => [],\n reopenDelayMs = 25,\n}: EventSourcePushChannelOptions): EventSourcePushChannel {\n const router = makePushRouter();\n let source: EventSource | undefined;\n let openedUrl: string | undefined;\n let lastEventId: string | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let refreshing = false;\n let dropped = 0;\n\n const streamUrl = (): string | undefined => {\n const topics = router.topics();\n if (topics.length === 0) return undefined;\n const params = new URLSearchParams();\n for (const topic of topics) params.append(PUSH_TOPIC_PARAM, topic);\n for (const capability of [...capabilities()].sort())\n params.append(PUSH_CAPABILITY_PARAM, capability);\n return `${url}${url.includes('?') ? '&' : '?'}${params.toString()}`;\n };\n\n const close = (): void => {\n source?.close();\n source = undefined;\n openedUrl = undefined;\n router.disconnected();\n };\n\n const open = (target: string): void => {\n const cursor =\n lastEventId === undefined\n ? ''\n : `&${PUSH_CURSOR_PARAM}=${encodeURIComponent(lastEventId)}`;\n const opened = new EventSource(`${target}${cursor}`);\n source = opened;\n openedUrl = target;\n opened.onopen = () => {\n router.connected();\n };\n // A dropped stream: the browser retries on its own while the source is\n // `CONNECTING`, and has given up once it is `CLOSED`.\n opened.onerror = () => {\n router.disconnected(\n opened.readyState === EventSource.CLOSED ? 'closed' : 'reconnecting',\n );\n };\n opened.onmessage = message => {\n if (message.lastEventId !== '') lastEventId = message.lastEventId;\n const frame = parse(message.data as string, decodeEventFrame);\n if (Result.isFailure(frame)) {\n dropped += 1;\n return;\n }\n router.deliver(frame.success.topics, frame.success.event);\n };\n opened.addEventListener('resync', message => {\n const frame = parse(\n (message as MessageEvent).data as string,\n Schema.decodeUnknownEffect(ResyncFrame),\n );\n if (Result.isFailure(frame)) {\n dropped += 1;\n return;\n }\n router.resync(frame.success.topics);\n });\n opened.addEventListener('reauth', () => {\n close();\n refreshing = true;\n refresh().then(\n () => {\n refreshing = false;\n sync();\n },\n () => {\n refreshing = false;\n },\n );\n });\n };\n\n // Brings the stream in line with the subscribed topics: closes it when\n // nothing listens, reopens it when the topics or capabilities moved.\n const sync = (): void => {\n // Guarded because a server-rendered pass has no `EventSource` at all.\n if (refreshing || typeof EventSource === 'undefined') return;\n const target = streamUrl();\n if (target === openedUrl) return;\n close();\n if (target !== undefined) open(target);\n };\n\n router.onTopicsChange(() => {\n clearTimeout(timer);\n timer = setTimeout(sync, reopenDelayMs);\n });\n\n return {\n subscribe: router.subscribe,\n onConnect: router.onConnect,\n onResync: router.onResync,\n connection: router.connection,\n onConnectionChange: router.onConnectionChange,\n reconnect: () => {\n // Forgets the open stream, so the sync opens a fresh one at once.\n close();\n sync();\n },\n dropped: () => dropped,\n };\n}\n"],"names":["decodeEvent","Effect","Result","Schema","makePushRouter","PUSH_TOPIC_PARAM","PUSH_CAPABILITY_PARAM","PUSH_CURSOR_PARAM","EventFrame","Struct","topics","Array","String","envelope","Unknown","ResyncFrame","parse","raw","decode","runSync","result","flatMap","try","JSON","decodeEventFrame","body","decodeUnknownEffect","frame","map","event","makeEventSourcePushChannel","url","refresh","capabilities","reopenDelayMs","router","source","openedUrl","lastEventId","timer","refreshing","dropped","streamUrl","length","undefined","params","URLSearchParams","topic","append","capability","sort","includes","toString","close","disconnected","open","target","cursor","encodeURIComponent","opened","EventSource","onopen","connected","onerror","readyState","CLOSED","onmessage","message","data","isFailure","deliver","success","addEventListener","resync","then","sync","onTopicsChange","clearTimeout","setTimeout","subscribe","onConnect","onResync","connection","onConnectionChange","reconnect"],"mappings":"AAAA,SAASA,WAAW,QAA0B,gBAAgB;AAC9D,SAASC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAGhD,SAASC,cAAc,QAAQ,mBAAmB;AAElD,qEAAqE,GACrE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M;QACpC;QACAiD,OAAOa,gBAAgB,CAAC,UAAU;YAChCnB;YACAb,aAAa;YACbR,UAAU0C,IAAI,CACZ;gBACElC,aAAa;gBACbmC;YACF,GACA;gBACEnC,aAAa;YACf;QAEJ;IACF;IAEA,uEAAuE;IACvE,qEAAqE;IACrE,MAAMmC,OAAO;QACX,sEAAsE;QACtE,IAAInC,cAAc,OAAOoB,gBAAgB,aAAa;QACtD,MAAMJ,SAASd;QACf,IAAIc,WAAWnB,WAAW;QAC1BgB;QACA,IAAIG,WAAWZ,WAAWW,KAAKC;IACjC;IAEArB,OAAOyC,cAAc,CAAC;QACpBC,aAAatC;QACbA,QAAQuC,WAAWH,MAAMzC;IAC3B;IAEA,OAAO;QACL6C,WAAW5C,OAAO4C,SAAS;QAC3BC,WAAW7C,OAAO6C,SAAS;QAC3BC,UAAU9C,OAAO8C,QAAQ;QACzBC,YAAY/C,OAAO+C,UAAU;QAC7BC,oBAAoBhD,OAAOgD,kBAAkB;QAC7CC,WAAW;YACT,kEAAkE;YAClE/B;YACAsB;QACF;QACAlC,SAAS,IAAMA;IACjB;AACF"}
@@ -40,7 +40,19 @@ export interface PushChannel {
40
40
  onConnect(listener: () => void): () => void;
41
41
  /** Runs when the server asks for subscribed topics to be read again. */
42
42
  onResync(listener: ResyncListener): () => void;
43
+ /**
44
+ * Where the stream stands, as a reader should be told: `open`, or a drop —
45
+ * `reconnecting` while the transport retries on its own, `closed` once it
46
+ * has given up. A stream still opening for the first time is `open`.
47
+ */
48
+ connection(): PushConnection;
49
+ /** Runs whenever {@link PushChannel.connection} changes. */
50
+ onConnectionChange(listener: () => void): () => void;
51
+ /** Opens the stream again now, rather than waiting on the transport. */
52
+ reconnect(): void;
43
53
  }
54
+ /** Where a push channel's stream stands (ADR 0028). */
55
+ export type PushConnection = 'open' | 'reconnecting' | 'closed';
44
56
  declare const PushChannelTag_base: Context.ServiceClass<PushChannelTag, "@entifix/react-integration/PushChannel", PushChannel>;
45
57
  export declare class PushChannelTag extends PushChannelTag_base {
46
58
  }
@@ -59,6 +71,8 @@ export interface InMemoryPushChannel extends PushChannel {
59
71
  resync(topics: readonly PushTopic[]): void;
60
72
  /** The topics something is subscribed to, sorted. */
61
73
  topics(): readonly PushTopic[];
74
+ /** Drops the stream, as a network does: retrying, or given up. */
75
+ drop(state: Exclude<PushConnection, 'open'>): void;
62
76
  }
63
77
  /**
64
78
  * A synchronous channel for specs and mocks. It routes exactly as the
@@ -1 +1 @@
1
- {"version":3,"file":"push-channel.d.ts","sourceRoot":"","sources":["../../src/reactive/push-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAIjC;;;;GAIG;AACH,MAAM,MAAM,SAAS,GACnB,UAAU,MAAM,EAAE,GAAG,UAAU,MAAM,IAAI,MAAM,EAAE,GAAG,QAAQ,MAAM,EAAE,CAAC;AAEvE,+DAA+D;AAC/D,eAAO,MAAM,WAAW,GAAI,KAAK,MAAM,KAAG,SAA4B,CAAC;AAEvE,+CAA+C;AAC/C,eAAO,MAAM,WAAW,GAAI,KAAK,MAAM,EAAE,IAAI,QAAQ,KAAG,SACzB,CAAC;AAEhC,oDAAoD;AACpD,eAAO,MAAM,SAAS,GAAI,QAAQ,MAAM,KAAG,SAA6B,CAAC;AAEzE,uEAAuE;AACvE,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI,CAAC;AAEpE;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,GAAG,MAAM,IAAI,CAAC;IAChE;;;;;OAKG;IACH,SAAS,CAAC,QAAQ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AAG,IAAI,CAAC;CACpD;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,mBAAmB,CAgB7D"}
@@ -12,7 +12,10 @@ export class PushChannelTag extends Context.Service()('@entifix/react-integratio
12
12
  */ export const NoopPushChannel = {
13
13
  subscribe: ()=>()=>undefined,
14
14
  onConnect: ()=>()=>undefined,
15
- onResync: ()=>()=>undefined
15
+ onResync: ()=>()=>undefined,
16
+ connection: ()=>'open',
17
+ onConnectionChange: ()=>()=>undefined,
18
+ reconnect: ()=>undefined
16
19
  };
17
20
  /**
18
21
  * A synchronous channel for specs and mocks. It routes exactly as the
@@ -26,7 +29,12 @@ export class PushChannelTag extends Context.Service()('@entifix/react-integratio
26
29
  emit: router.deliver,
27
30
  connect: router.connected,
28
31
  resync: router.resync,
29
- topics: router.topics
32
+ topics: router.topics,
33
+ connection: router.connection,
34
+ onConnectionChange: router.onConnectionChange,
35
+ // In memory there is nothing to reopen: reconnecting is connecting.
36
+ reconnect: router.connected,
37
+ drop: router.disconnected
30
38
  };
31
39
  }
32
40
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/reactive/push-channel.ts"],"sourcesContent":["import type { DomainEvent, EntityId } from '@entifix/core';\nimport { Context } from 'effect';\n\nimport { makePushRouter } from './push-router.js';\n\n/**\n * What a tab can listen to: every change to one entity, one record, or one\n * flow's outcome\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n */\nexport type PushTopic =\n `entity:${string}` | `record:${string}:${string}` | `flow:${string}`;\n\n/** Every change to the entity whose `key ?? name` is `key`. */\nexport const entityTopic = (key: string): PushTopic => `entity:${key}`;\n\n/** Every change to one record of an entity. */\nexport const recordTopic = (key: string, id: EntityId): PushTopic =>\n `record:${key}:${String(id)}`;\n\n/** The outcome of one flow: its `flow.*` events. */\nexport const flowTopic = (flowId: string): PushTopic => `flow:${flowId}`;\n\n/** Receives each event pushed on a topic it subscribed to, decoded. */\nexport type PushListener = (event: DomainEvent) => void;\n\n/**\n * Receives the subscribed topics the server could not replay after a\n * reconnect. Whatever the listener shows for them must be read again.\n */\nexport type ResyncListener = (topics: readonly PushTopic[]) => void;\n\n/**\n * The browser half of push: topics in, decoded events out.\n *\n * Commands never travel here; the stream is one-way and every write stays\n * HTTP. Each subscribe returns its own unsubscribe.\n */\nexport interface PushChannel {\n /**\n * Listens to one topic. A listener subscribed to several topics an event\n * names hears that event once.\n */\n subscribe(topic: PushTopic, listener: PushListener): () => void;\n /**\n * Runs whenever the stream is (re)connected, and **immediately if it is\n * already connected when the listener registers**. A consumer that may have\n * missed something while disconnected re-reads here; without the replay, one\n * mounting after the stream opened would wait for a drop that may never come.\n */\n onConnect(listener: () => void): () => void;\n /** Runs when the server asks for subscribed topics to be read again. */\n onResync(listener: ResyncListener): () => void;\n}\n\nexport class PushChannelTag extends Context.Service<\n PushChannelTag,\n PushChannel\n>()('@entifix/react-integration/PushChannel') {}\n\n/**\n * A channel that never connects and never emits: the default until a host\n * provides a transport. Its consumers reconcile never, which is the honest\n * behaviour for a transport that is not there.\n */\nexport const NoopPushChannel: PushChannel = {\n subscribe: () => () => undefined,\n onConnect: () => () => undefined,\n onResync: () => () => undefined,\n};\n\nexport interface InMemoryPushChannel extends PushChannel {\n /** Delivers `event` as a server would, naming the topics it matched. */\n emit(topics: readonly PushTopic[], event: DomainEvent): void;\n /** Announces a (re)connection and marks the channel connected. */\n connect(): void;\n /** Asks for `topics` to be read again, as a server's `resync` does. */\n resync(topics: readonly PushTopic[]): void;\n /** The topics something is subscribed to, sorted. */\n topics(): readonly PushTopic[];\n}\n\n/**\n * A synchronous channel for specs and mocks. It routes exactly as the\n * `EventSource` adapter does, because both run on the same router.\n */\nexport function makeInMemoryPushChannel(): InMemoryPushChannel {\n const router = makePushRouter();\n return {\n subscribe: router.subscribe,\n onConnect: router.onConnect,\n onResync: router.onResync,\n emit: router.deliver,\n connect: router.connected,\n resync: router.resync,\n topics: router.topics,\n };\n}\n"],"names":["Context","makePushRouter","entityTopic","key","recordTopic","id","String","flowTopic","flowId","PushChannelTag","Service","NoopPushChannel","subscribe","undefined","onConnect","onResync","makeInMemoryPushChannel","router","emit","deliver","connect","connected","resync","topics"],"mappings":"AACA,SAASA,OAAO,QAAQ,SAAS;AAEjC,SAASC,cAAc,QAAQ,mBAAmB;AAUlD,6DAA6D,GAC7D,OAAO,MAAMC,cAAc,CAACC,MAA2B,CAAC,OAAO,EAAEA,KAAK,CAAC;AAEvE,6CAA6C,GAC7C,OAAO,MAAMC,cAAc,CAACD,KAAaE,KACvC,CAAC,OAAO,EAAEF,IAAI,CAAC,EAAEG,OAAOD,KAAK,CAAC;AAEhC,kDAAkD,GAClD,OAAO,MAAME,YAAY,CAACC,SAA8B,CAAC,KAAK,EAAEA,QAAQ,CAAC;AAkCzE,OAAO,MAAMC,uBAAuBT,QAAQU,OAAO,GAG/C;AAA2C;AAE/C;;;;CAIC,GACD,OAAO,MAAMC,kBAA+B;IAC1CC,WAAW,IAAM,IAAMC;IACvBC,WAAW,IAAM,IAAMD;IACvBE,UAAU,IAAM,IAAMF;AACxB,EAAE;AAaF;;;CAGC,GACD,OAAO,SAASG;IACd,MAAMC,SAAShB;IACf,OAAO;QACLW,WAAWK,OAAOL,SAAS;QAC3BE,WAAWG,OAAOH,SAAS;QAC3BC,UAAUE,OAAOF,QAAQ;QACzBG,MAAMD,OAAOE,OAAO;QACpBC,SAASH,OAAOI,SAAS;QACzBC,QAAQL,OAAOK,MAAM;QACrBC,QAAQN,OAAOM,MAAM;IACvB;AACF"}
1
+ {"version":3,"sources":["../../src/reactive/push-channel.ts"],"sourcesContent":["import type { DomainEvent, EntityId } from '@entifix/core';\nimport { Context } from 'effect';\n\nimport { makePushRouter } from './push-router.js';\n\n/**\n * What a tab can listen to: every change to one entity, one record, or one\n * flow's outcome\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n */\nexport type PushTopic =\n `entity:${string}` | `record:${string}:${string}` | `flow:${string}`;\n\n/** Every change to the entity whose `key ?? name` is `key`. */\nexport const entityTopic = (key: string): PushTopic => `entity:${key}`;\n\n/** Every change to one record of an entity. */\nexport const recordTopic = (key: string, id: EntityId): PushTopic =>\n `record:${key}:${String(id)}`;\n\n/** The outcome of one flow: its `flow.*` events. */\nexport const flowTopic = (flowId: string): PushTopic => `flow:${flowId}`;\n\n/** Receives each event pushed on a topic it subscribed to, decoded. */\nexport type PushListener = (event: DomainEvent) => void;\n\n/**\n * Receives the subscribed topics the server could not replay after a\n * reconnect. Whatever the listener shows for them must be read again.\n */\nexport type ResyncListener = (topics: readonly PushTopic[]) => void;\n\n/**\n * The browser half of push: topics in, decoded events out.\n *\n * Commands never travel here; the stream is one-way and every write stays\n * HTTP. Each subscribe returns its own unsubscribe.\n */\nexport interface PushChannel {\n /**\n * Listens to one topic. A listener subscribed to several topics an event\n * names hears that event once.\n */\n subscribe(topic: PushTopic, listener: PushListener): () => void;\n /**\n * Runs whenever the stream is (re)connected, and **immediately if it is\n * already connected when the listener registers**. A consumer that may have\n * missed something while disconnected re-reads here; without the replay, one\n * mounting after the stream opened would wait for a drop that may never come.\n */\n onConnect(listener: () => void): () => void;\n /** Runs when the server asks for subscribed topics to be read again. */\n onResync(listener: ResyncListener): () => void;\n /**\n * Where the stream stands, as a reader should be told: `open`, or a drop —\n * `reconnecting` while the transport retries on its own, `closed` once it\n * has given up. A stream still opening for the first time is `open`.\n */\n connection(): PushConnection;\n /** Runs whenever {@link PushChannel.connection} changes. */\n onConnectionChange(listener: () => void): () => void;\n /** Opens the stream again now, rather than waiting on the transport. */\n reconnect(): void;\n}\n\n/** Where a push channel's stream stands (ADR 0028). */\nexport type PushConnection = 'open' | 'reconnecting' | 'closed';\n\nexport class PushChannelTag extends Context.Service<\n PushChannelTag,\n PushChannel\n>()('@entifix/react-integration/PushChannel') {}\n\n/**\n * A channel that never connects and never emits: the default until a host\n * provides a transport. Its consumers reconcile never, which is the honest\n * behaviour for a transport that is not there.\n */\nexport const NoopPushChannel: PushChannel = {\n subscribe: () => () => undefined,\n onConnect: () => () => undefined,\n onResync: () => () => undefined,\n connection: () => 'open',\n onConnectionChange: () => () => undefined,\n reconnect: () => undefined,\n};\n\nexport interface InMemoryPushChannel extends PushChannel {\n /** Delivers `event` as a server would, naming the topics it matched. */\n emit(topics: readonly PushTopic[], event: DomainEvent): void;\n /** Announces a (re)connection and marks the channel connected. */\n connect(): void;\n /** Asks for `topics` to be read again, as a server's `resync` does. */\n resync(topics: readonly PushTopic[]): void;\n /** The topics something is subscribed to, sorted. */\n topics(): readonly PushTopic[];\n /** Drops the stream, as a network does: retrying, or given up. */\n drop(state: Exclude<PushConnection, 'open'>): void;\n}\n\n/**\n * A synchronous channel for specs and mocks. It routes exactly as the\n * `EventSource` adapter does, because both run on the same router.\n */\nexport function makeInMemoryPushChannel(): InMemoryPushChannel {\n const router = makePushRouter();\n return {\n subscribe: router.subscribe,\n onConnect: router.onConnect,\n onResync: router.onResync,\n emit: router.deliver,\n connect: router.connected,\n resync: router.resync,\n topics: router.topics,\n connection: router.connection,\n onConnectionChange: router.onConnectionChange,\n // In memory there is nothing to reopen: reconnecting is connecting.\n reconnect: router.connected,\n drop: router.disconnected,\n };\n}\n"],"names":["Context","makePushRouter","entityTopic","key","recordTopic","id","String","flowTopic","flowId","PushChannelTag","Service","NoopPushChannel","subscribe","undefined","onConnect","onResync","connection","onConnectionChange","reconnect","makeInMemoryPushChannel","router","emit","deliver","connect","connected","resync","topics","drop","disconnected"],"mappings":"AACA,SAASA,OAAO,QAAQ,SAAS;AAEjC,SAASC,cAAc,QAAQ,mBAAmB;AAUlD,6DAA6D,GAC7D,OAAO,MAAMC,cAAc,CAACC,MAA2B,CAAC,OAAO,EAAEA,KAAK,CAAC;AAEvE,6CAA6C,GAC7C,OAAO,MAAMC,cAAc,CAACD,KAAaE,KACvC,CAAC,OAAO,EAAEF,IAAI,CAAC,EAAEG,OAAOD,KAAK,CAAC;AAEhC,kDAAkD,GAClD,OAAO,MAAME,YAAY,CAACC,SAA8B,CAAC,KAAK,EAAEA,QAAQ,CAAC;AA+CzE,OAAO,MAAMC,uBAAuBT,QAAQU,OAAO,GAG/C;AAA2C;AAE/C;;;;CAIC,GACD,OAAO,MAAMC,kBAA+B;IAC1CC,WAAW,IAAM,IAAMC;IACvBC,WAAW,IAAM,IAAMD;IACvBE,UAAU,IAAM,IAAMF;IACtBG,YAAY,IAAM;IAClBC,oBAAoB,IAAM,IAAMJ;IAChCK,WAAW,IAAML;AACnB,EAAE;AAeF;;;CAGC,GACD,OAAO,SAASM;IACd,MAAMC,SAASnB;IACf,OAAO;QACLW,WAAWQ,OAAOR,SAAS;QAC3BE,WAAWM,OAAON,SAAS;QAC3BC,UAAUK,OAAOL,QAAQ;QACzBM,MAAMD,OAAOE,OAAO;QACpBC,SAASH,OAAOI,SAAS;QACzBC,QAAQL,OAAOK,MAAM;QACrBC,QAAQN,OAAOM,MAAM;QACrBV,YAAYI,OAAOJ,UAAU;QAC7BC,oBAAoBG,OAAOH,kBAAkB;QAC7C,oEAAoE;QACpEC,WAAWE,OAAOI,SAAS;QAC3BG,MAAMP,OAAOQ,YAAY;IAC3B;AACF"}
@@ -1,5 +1,5 @@
1
1
  import type { DomainEvent } from '@entifix/core';
2
- import type { PushListener, PushTopic, ResyncListener } from './push-channel.js';
2
+ import type { PushConnection, PushListener, PushTopic, ResyncListener } from './push-channel.js';
3
3
  /**
4
4
  * The listener bookkeeping every `PushChannel` shares: who listens to which
5
5
  * topic, and who wants to hear about a connection or a resync. A transport
@@ -13,8 +13,17 @@ export interface PushRouter {
13
13
  deliver(topics: readonly string[], event: DomainEvent): void;
14
14
  /** Marks the channel connected and tells every connect listener. */
15
15
  connected(): void;
16
- /** Marks the channel disconnected; a late connect listener then waits. */
17
- disconnected(): void;
16
+ /**
17
+ * Marks the channel disconnected; a late connect listener then waits. With
18
+ * a state, the drop is also one a reader should hear about — `reconnecting`
19
+ * while the transport retries, `closed` when it gave up. Without one it is
20
+ * a reopen the channel chose, which says nothing.
21
+ */
22
+ disconnected(state?: Exclude<PushConnection, 'open'>): void;
23
+ /** Where the connection stands, as a reader would be told. */
24
+ connection(): PushConnection;
25
+ /** Runs whenever {@link connection} changes. */
26
+ onConnectionChange(listener: () => void): () => void;
18
27
  /** Tells every resync listener, about the named topics still subscribed. */
19
28
  resync(topics: readonly string[]): void;
20
29
  /** The topics something is subscribed to, sorted. */
@@ -1 +1 @@
1
- {"version":3,"file":"push-router.d.ts","sourceRoot":"","sources":["../../src/reactive/push-router.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,KAAK,EACV,YAAY,EACZ,SAAS,EACT,cAAc,EACf,MAAM,mBAAmB,CAAC;AAE3B;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,GAAG,MAAM,IAAI,CAAC;IAChE,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,QAAQ,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,IAAI,CAAC;IAC/C,qEAAqE;IACrE,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IAC7D,oEAAoE;IACpE,SAAS,IAAI,IAAI,CAAC;IAClB,0EAA0E;IAC1E,YAAY,IAAI,IAAI,CAAC;IACrB,4EAA4E;IAC5E,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;IACxC,qDAAqD;IACrD,MAAM,IAAI,SAAS,SAAS,EAAE,CAAC;IAC/B,0DAA0D;IAC1D,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAC5C;AAED,wBAAgB,cAAc,IAAI,UAAU,CAkE3C"}
1
+ {"version":3,"file":"push-router.d.ts","sourceRoot":"","sources":["../../src/reactive/push-router.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,SAAS,EACT,cAAc,EACf,MAAM,mBAAmB,CAAC;AAE3B;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,GAAG,MAAM,IAAI,CAAC;IAChE,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,QAAQ,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,IAAI,CAAC;IAC/C,qEAAqE;IACrE,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IAC7D,oEAAoE;IACpE,SAAS,IAAI,IAAI,CAAC;IAClB;;;;;OAKG;IACH,YAAY,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IAC5D,8DAA8D;IAC9D,UAAU,IAAI,cAAc,CAAC;IAC7B,gDAAgD;IAChD,kBAAkB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IACrD,4EAA4E;IAC5E,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;IACxC,qDAAqD;IACrD,MAAM,IAAI,SAAS,SAAS,EAAE,CAAC;IAC/B,0DAA0D;IAC1D,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAC5C;AAED,wBAAgB,cAAc,IAAI,UAAU,CAmF3C"}
@@ -4,6 +4,14 @@ export function makePushRouter() {
4
4
  const resyncListeners = new Set();
5
5
  let isConnected = false;
6
6
  let topicsChanged = ()=>undefined;
7
+ // Nothing to report until a drop is seen: a stream still opening is not news.
8
+ let connection = 'open';
9
+ const connectionListeners = new Set();
10
+ const setConnection = (next)=>{
11
+ if (next === connection) return;
12
+ connection = next;
13
+ for (const listener of connectionListeners)listener();
14
+ };
7
15
  const subscribed = (topics)=>topics.filter((topic)=>byTopic.has(topic));
8
16
  return {
9
17
  subscribe (topic, listener) {
@@ -42,10 +50,19 @@ export function makePushRouter() {
42
50
  },
43
51
  connected () {
44
52
  isConnected = true;
53
+ setConnection('open');
45
54
  for (const listener of connectListeners)listener();
46
55
  },
47
- disconnected () {
56
+ disconnected (state) {
48
57
  isConnected = false;
58
+ if (state !== undefined) setConnection(state);
59
+ },
60
+ connection: ()=>connection,
61
+ onConnectionChange (listener) {
62
+ connectionListeners.add(listener);
63
+ return ()=>{
64
+ connectionListeners.delete(listener);
65
+ };
49
66
  },
50
67
  resync (topics) {
51
68
  const still = subscribed(topics);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/reactive/push-router.ts"],"sourcesContent":["import type { DomainEvent } from '@entifix/core';\n\nimport type {\n PushListener,\n PushTopic,\n ResyncListener,\n} from './push-channel.js';\n\n/**\n * The listener bookkeeping every `PushChannel` shares: who listens to which\n * topic, and who wants to hear about a connection or a resync. A transport\n * decides when those happen; this decides who hears.\n */\nexport interface PushRouter {\n subscribe(topic: PushTopic, listener: PushListener): () => void;\n onConnect(listener: () => void): () => void;\n onResync(listener: ResyncListener): () => void;\n /** Hands `event` to each listener of the named topics, once each. */\n deliver(topics: readonly string[], event: DomainEvent): void;\n /** Marks the channel connected and tells every connect listener. */\n connected(): void;\n /** Marks the channel disconnected; a late connect listener then waits. */\n disconnected(): void;\n /** Tells every resync listener, about the named topics still subscribed. */\n resync(topics: readonly string[]): void;\n /** The topics something is subscribed to, sorted. */\n topics(): readonly PushTopic[];\n /** Runs whenever the set of subscribed topics changes. */\n onTopicsChange(listener: () => void): void;\n}\n\nexport function makePushRouter(): PushRouter {\n const byTopic = new Map<PushTopic, Set<PushListener>>();\n const connectListeners = new Set<() => void>();\n const resyncListeners = new Set<ResyncListener>();\n let isConnected = false;\n let topicsChanged = (): void => undefined;\n\n const subscribed = (topics: readonly string[]): PushTopic[] =>\n topics.filter((topic): topic is PushTopic =>\n byTopic.has(topic as PushTopic),\n );\n\n return {\n subscribe(topic, listener) {\n let listeners = byTopic.get(topic);\n if (listeners === undefined) {\n listeners = new Set();\n byTopic.set(topic, listeners);\n topicsChanged();\n }\n listeners.add(listener);\n return () => {\n const current = byTopic.get(topic);\n if (current?.delete(listener) !== true || current.size > 0) return;\n byTopic.delete(topic);\n topicsChanged();\n };\n },\n onConnect(listener) {\n connectListeners.add(listener);\n if (isConnected) listener();\n return () => {\n connectListeners.delete(listener);\n };\n },\n onResync(listener) {\n resyncListeners.add(listener);\n return () => {\n resyncListeners.delete(listener);\n };\n },\n deliver(topics, event) {\n const named = new Set(topics);\n const listeners = new Set<PushListener>();\n for (const [topic, topicListeners] of byTopic)\n if (named.has(topic))\n for (const listener of topicListeners) listeners.add(listener);\n for (const listener of listeners) listener(event);\n },\n connected() {\n isConnected = true;\n for (const listener of connectListeners) listener();\n },\n disconnected() {\n isConnected = false;\n },\n resync(topics) {\n const still = subscribed(topics);\n if (still.length === 0) return;\n for (const listener of resyncListeners) listener(still);\n },\n topics: () => [...byTopic.keys()].sort(),\n onTopicsChange(listener) {\n topicsChanged = listener;\n },\n };\n}\n"],"names":["makePushRouter","byTopic","Map","connectListeners","Set","resyncListeners","isConnected","topicsChanged","undefined","subscribed","topics","filter","topic","has","subscribe","listener","listeners","get","set","add","current","delete","size","onConnect","onResync","deliver","event","named","topicListeners","connected","disconnected","resync","still","length","keys","sort","onTopicsChange"],"mappings":"AA+BA,OAAO,SAASA;IACd,MAAMC,UAAU,IAAIC;IACpB,MAAMC,mBAAmB,IAAIC;IAC7B,MAAMC,kBAAkB,IAAID;IAC5B,IAAIE,cAAc;IAClB,IAAIC,gBAAgB,IAAYC;IAEhC,MAAMC,aAAa,CAACC,SAClBA,OAAOC,MAAM,CAAC,CAACC,QACbX,QAAQY,GAAG,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AQ;YACrBR,gBAAgBQ;QAClB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/reactive/push-router.ts"],"sourcesContent":["import type { DomainEvent } from '@entifix/core';\n\nimport type {\n PushConnection,\n PushListener,\n PushTopic,\n ResyncListener,\n} from './push-channel.js';\n\n/**\n * The listener bookkeeping every `PushChannel` shares: who listens to which\n * topic, and who wants to hear about a connection or a resync. A transport\n * decides when those happen; this decides who hears.\n */\nexport interface PushRouter {\n subscribe(topic: PushTopic, listener: PushListener): () => void;\n onConnect(listener: () => void): () => void;\n onResync(listener: ResyncListener): () => void;\n /** Hands `event` to each listener of the named topics, once each. */\n deliver(topics: readonly string[], event: DomainEvent): void;\n /** Marks the channel connected and tells every connect listener. */\n connected(): void;\n /**\n * Marks the channel disconnected; a late connect listener then waits. With\n * a state, the drop is also one a reader should hear about — `reconnecting`\n * while the transport retries, `closed` when it gave up. Without one it is\n * a reopen the channel chose, which says nothing.\n */\n disconnected(state?: Exclude<PushConnection, 'open'>): void;\n /** Where the connection stands, as a reader would be told. */\n connection(): PushConnection;\n /** Runs whenever {@link connection} changes. */\n onConnectionChange(listener: () => void): () => void;\n /** Tells every resync listener, about the named topics still subscribed. */\n resync(topics: readonly string[]): void;\n /** The topics something is subscribed to, sorted. */\n topics(): readonly PushTopic[];\n /** Runs whenever the set of subscribed topics changes. */\n onTopicsChange(listener: () => void): void;\n}\n\nexport function makePushRouter(): PushRouter {\n const byTopic = new Map<PushTopic, Set<PushListener>>();\n const connectListeners = new Set<() => void>();\n const resyncListeners = new Set<ResyncListener>();\n let isConnected = false;\n let topicsChanged = (): void => undefined;\n // Nothing to report until a drop is seen: a stream still opening is not news.\n let connection: PushConnection = 'open';\n const connectionListeners = new Set<() => void>();\n const setConnection = (next: PushConnection): void => {\n if (next === connection) return;\n connection = next;\n for (const listener of connectionListeners) listener();\n };\n\n const subscribed = (topics: readonly string[]): PushTopic[] =>\n topics.filter((topic): topic is PushTopic =>\n byTopic.has(topic as PushTopic),\n );\n\n return {\n subscribe(topic, listener) {\n let listeners = byTopic.get(topic);\n if (listeners === undefined) {\n listeners = new Set();\n byTopic.set(topic, listeners);\n topicsChanged();\n }\n listeners.add(listener);\n return () => {\n const current = byTopic.get(topic);\n if (current?.delete(listener) !== true || current.size > 0) return;\n byTopic.delete(topic);\n topicsChanged();\n };\n },\n onConnect(listener) {\n connectListeners.add(listener);\n if (isConnected) listener();\n return () => {\n connectListeners.delete(listener);\n };\n },\n onResync(listener) {\n resyncListeners.add(listener);\n return () => {\n resyncListeners.delete(listener);\n };\n },\n deliver(topics, event) {\n const named = new Set(topics);\n const listeners = new Set<PushListener>();\n for (const [topic, topicListeners] of byTopic)\n if (named.has(topic))\n for (const listener of topicListeners) listeners.add(listener);\n for (const listener of listeners) listener(event);\n },\n connected() {\n isConnected = true;\n setConnection('open');\n for (const listener of connectListeners) listener();\n },\n disconnected(state) {\n isConnected = false;\n if (state !== undefined) setConnection(state);\n },\n connection: () => connection,\n onConnectionChange(listener) {\n connectionListeners.add(listener);\n return () => {\n connectionListeners.delete(listener);\n };\n },\n resync(topics) {\n const still = subscribed(topics);\n if (still.length === 0) return;\n for (const listener of resyncListeners) listener(still);\n },\n topics: () => [...byTopic.keys()].sort(),\n onTopicsChange(listener) {\n topicsChanged = listener;\n },\n };\n}\n"],"names":["makePushRouter","byTopic","Map","connectListeners","Set","resyncListeners","isConnected","topicsChanged","undefined","connection","connectionListeners","setConnection","next","listener","subscribed","topics","filter","topic","has","subscribe","listeners","get","set","add","current","delete","size","onConnect","onResync","deliver","event","named","topicListeners","connected","disconnected","state","onConnectionChange","resync","still","length","keys","sort","onTopicsChange"],"mappings":"AAyCA,OAAO,SAASA;IACd,MAAMC,UAAU,IAAIC;IACpB,MAAMC,mBAAmB,IAAIC;IAC7B,MAAMC,kBAAkB,IAAID;IAC5B,IAAIE,cAAc;IAClB,IAAIC,gBAAgB,IAAYC;IAChC,8EAA8E;IAC9E,IAAIC,aAA6B;IACjC,MAAMC,sBAAsB,IAAI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IAAI6B,UAAU3B,WAAWG,cAAcwB;QACzC;QACA1B,YAAY,IAAMA;QAClB2B,oBAAmBvB,QAAQ;YACzBH,oBAAoBa,GAAG,CAACV;YACxB,OAAO;gBACLH,oBAAoBe,MAAM,CAACZ;YAC7B;QACF;QACAwB,QAAOtB,MAAM;YACX,MAAMuB,QAAQxB,WAAWC;YACzB,IAAIuB,MAAMC,MAAM,KAAK,GAAG;YACxB,KAAK,MAAM1B,YAAYR,gBAAiBQ,SAASyB;QACnD;QACAvB,QAAQ,IAAM;mBAAId,QAAQuC,IAAI;aAAG,CAACC,IAAI;QACtCC,gBAAe7B,QAAQ;YACrBN,gBAAgBM;QAClB;IACF;AACF"}
@@ -0,0 +1,13 @@
1
+ import type { PushChannel, PushConnection } from './push-channel.js';
2
+ /** A push channel's state, and the way to try again now. */
3
+ export interface PushConnectionState {
4
+ readonly connection: PushConnection;
5
+ readonly reconnect: () => void;
6
+ }
7
+ /**
8
+ * Where the tab's push stream stands — `open`, `reconnecting` or `closed` —
9
+ * re-rendering when it moves, so a screen can say live updates are paused
10
+ * rather than leaving a pending write waiting without a word (ADR 0028).
11
+ */
12
+ export declare function usePushConnection(channel: PushChannel): PushConnectionState;
13
+ //# sourceMappingURL=use-push-connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-push-connection.d.ts","sourceRoot":"","sources":["../../src/reactive/use-push-connection.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAErE,4DAA4D;AAC5D,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;IACpC,QAAQ,CAAC,SAAS,EAAE,MAAM,IAAI,CAAC;CAChC;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,mBAAmB,CAS3E"}
@@ -0,0 +1,18 @@
1
+ import { useCallback, useSyncExternalStore } from 'react';
2
+ /**
3
+ * Where the tab's push stream stands — `open`, `reconnecting` or `closed` —
4
+ * re-rendering when it moves, so a screen can say live updates are paused
5
+ * rather than leaving a pending write waiting without a word (ADR 0028).
6
+ */ export function usePushConnection(channel) {
7
+ const connection = useSyncExternalStore(channel.onConnectionChange, channel.connection, // A server render has no stream; it is not news there either.
8
+ ()=>'open');
9
+ const reconnect = useCallback(()=>channel.reconnect(), [
10
+ channel
11
+ ]);
12
+ return {
13
+ connection,
14
+ reconnect
15
+ };
16
+ }
17
+
18
+ //# sourceMappingURL=use-push-connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/reactive/use-push-connection.ts"],"sourcesContent":["import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { PushChannel, PushConnection } from './push-channel.js';\n\n/** A push channel's state, and the way to try again now. */\nexport interface PushConnectionState {\n readonly connection: PushConnection;\n readonly reconnect: () => void;\n}\n\n/**\n * Where the tab's push stream stands — `open`, `reconnecting` or `closed` —\n * re-rendering when it moves, so a screen can say live updates are paused\n * rather than leaving a pending write waiting without a word (ADR 0028).\n */\nexport function usePushConnection(channel: PushChannel): PushConnectionState {\n const connection = useSyncExternalStore(\n channel.onConnectionChange,\n channel.connection,\n // A server render has no stream; it is not news there either.\n () => 'open' as const,\n );\n const reconnect = useCallback(() => channel.reconnect(), [channel]);\n return { connection, reconnect };\n}\n"],"names":["useCallback","useSyncExternalStore","usePushConnection","channel","connection","onConnectionChange","reconnect"],"mappings":"AAAA,SAASA,WAAW,EAAEC,oBAAoB,QAAQ,QAAQ;AAU1D;;;;CAIC,GACD,OAAO,SAASC,kBAAkBC,OAAoB;IACpD,MAAMC,aAAaH,qBACjBE,QAAQE,kBAAkB,EAC1BF,QAAQC,UAAU,EAClB,8DAA8D;IAC9D,IAAM;IAER,MAAME,YAAYN,YAAY,IAAMG,QAAQG,SAAS,IAAI;QAACH;KAAQ;IAClE,OAAO;QAAEC;QAAYE;IAAU;AACjC"}