@thomasfosterau/effect-forms-svelte 0.2.0 → 0.3.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 (39) hide show
  1. package/README.md +19 -19
  2. package/dist/ClientValidate.d.ts +1 -2
  3. package/dist/ClientValidate.js +1 -2
  4. package/dist/EnhanceCore.d.ts +34 -4
  5. package/dist/EnhanceCore.js +106 -39
  6. package/dist/EnhanceCore.js.map +1 -1
  7. package/dist/EntityForm.d.ts +0 -2
  8. package/dist/EntityForm.js +29 -30
  9. package/dist/EntityForm.js.map +1 -1
  10. package/dist/FormStore.svelte.d.ts +11 -5
  11. package/dist/FormStore.svelte.js +94 -61
  12. package/dist/FormStore.svelte.js.map +1 -1
  13. package/dist/Listeners.d.ts +1 -2
  14. package/dist/Listeners.js +4 -4
  15. package/dist/Listeners.js.map +1 -1
  16. package/dist/SvelteKit.d.ts +1 -2
  17. package/dist/SvelteKit.js +3 -3
  18. package/dist/SvelteKit.js.map +1 -1
  19. package/dist/Tainted.d.ts +1 -2
  20. package/dist/Tainted.js +28 -41
  21. package/dist/Tainted.js.map +1 -1
  22. package/dist/_virtual/_rolldown/runtime.js +1 -2
  23. package/dist/kit/ActionRedirect.d.ts +0 -2
  24. package/dist/kit/ActionRedirect.js +12 -15
  25. package/dist/kit/ActionRedirect.js.map +1 -1
  26. package/dist/kit/CommandFailure.d.ts +1 -2
  27. package/dist/kit/CommandFailure.js +18 -20
  28. package/dist/kit/CommandFailure.js.map +1 -1
  29. package/dist/kit/Enhance.d.ts +0 -2
  30. package/dist/kit/Enhance.js +1 -2
  31. package/dist/kit/FormAction.d.ts +0 -2
  32. package/dist/kit/FormAction.js +39 -33
  33. package/dist/kit/FormAction.js.map +1 -1
  34. package/dist/kit/FormStateReaders.d.ts +0 -2
  35. package/dist/kit/FormStateReaders.js +4 -4
  36. package/dist/kit/FormStateReaders.js.map +1 -1
  37. package/dist/kit/Pointer.d.ts +0 -2
  38. package/dist/kit/Pointer.js +1 -2
  39. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"FormAction.js","names":[],"sources":["../../src/kit/FormAction.ts"],"sourcesContent":["/**\n * Derive a SvelteKit page form action from an `@thomasfosterau/effect-forms`\n * form plus the command it submits to.\n *\n * {@link runFormAction} is the framework-neutral seam — validate the request\n * against the form's schema (every field error collected, posted values\n * retained), run the command on a valid submission, and describe the outcome\n * as a `Result.FormActionResult`. {@link formAction} maps that onto\n * SvelteKit's action protocol (`redirect()` / `fail()`), which the client\n * store applies back via `applyActionResult` / {@link enhanceForm}.\n *\n * A command is either a Promise-returning function (an API client call) or\n * an `Effect` with no requirements; a failure on either is classified by\n * {@link CommandFailure.jsonapiFailure} (or a caller's own classifier) and\n * routed onto the form's fields by each JSON:API error's `source.pointer`.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/FormAction\n */\n\nimport { fail, redirect, type RequestEvent } from \"@sveltejs/kit\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport type * as Schema from \"effect/Schema\";\nimport { type Form, Result, State } from \"@thomasfosterau/effect-forms\";\nimport {\n type Classify,\n type CommandFailure,\n DEFAULT_MESSAGE,\n detailOf,\n type ErrorObject,\n jsonapiFailure,\n} from \"./CommandFailure.ts\";\nimport { fieldFromPointer } from \"./Pointer.ts\";\n\ntype FormState<A, Message = unknown> = State.FormState<A, Message>;\ntype FormActionResult<A, Message = unknown> = Result.FormActionResult<A, Message>;\ntype FormActionData<A = unknown, Message = unknown> = Result.FormActionData<A, Message>;\n\n/**\n * A command: a Promise-returning function or one returning an `Effect` with\n * no requirements (provide them first, e.g. through a `ManagedRuntime`).\n */\nexport type Command<I, O> = (input: I) => Promise<O> | Effect.Effect<O, unknown>;\n\nconst toEffect = <O>(\n thunk: () => Promise<O> | Effect.Effect<O, unknown>,\n): Effect.Effect<O, unknown> =>\n Effect.suspend(() => {\n const out = thunk();\n return Effect.isEffect(out)\n ? out\n : Effect.tryPromise({ try: () => out, catch: (cause) => cause });\n });\n\n// ── Idempotent client-id create retry ──────────────────────────────────\n\nconst isConflict = (cause: unknown): boolean =>\n Predicate.isObjectOrArray(cause) &&\n (cause as { readonly status?: unknown }).status === 409 &&\n ((cause as { readonly _tag?: unknown })._tag === \"JsonapiError\" ||\n (cause as { readonly _tag?: unknown })._tag === \"ErrorResponse\");\n\nconst submittedId = (input: unknown): string | undefined => {\n const id = Predicate.isObjectOrArray(input) ? (input as { readonly id?: unknown }).id : undefined;\n return Predicate.isString(id) && id !== \"\" ? id : undefined;\n};\n\nconst retryOwnConflict = <I, O>(\n create: Command<I, O>,\n fetchExisting: (id: string) => Promise<O> | Effect.Effect<O, unknown>,\n input: I,\n): Effect.Effect<O, unknown> =>\n toEffect(() => create(input)).pipe(\n Effect.catch((cause) => {\n const id = submittedId(input);\n if (id === undefined || !isConflict(cause)) return Effect.fail(cause);\n // The re-fetch failing rethrows the ORIGINAL conflict, not its own error.\n return toEffect(() => fetchExisting(id)).pipe(Effect.mapError(() => cause));\n }),\n );\n\n/**\n * Wrap a client-id create command so a 409 conflict on the caller's OWN\n * submitted `id` resolves as success instead of a form error — the\n * double-submit of a create whose id the client generated.\n *\n * On any 409 (a `JsonapiError` / `ErrorResponse`-tagged cause), re-fetches\n * `input.id` via `fetchExisting` and returns that. This is deliberately\n * unconditional on *why* the 409 fired: the re-fetch is the proof, not the\n * status. A 409 from an unrelated precondition never left a row at\n * `input.id`, so the re-fetch fails and the original conflict rethrows\n * unchanged. An input with no `id`, or any other failure, rethrows as is.\n *\n * `input.id` is read structurally rather than through a constraint on\n * `Input`: a constraint here would be used only contravariantly (as\n * `create`'s parameter), which makes TypeScript infer `Input` from the\n * constraint instead of from the command's own input type.\n */\nexport function idempotentCreate<Input, Output>(\n create: (input: Input) => Promise<Output>,\n fetchExisting: (id: string) => Promise<Output>,\n): (input: Input) => Promise<Output> {\n return async (input) => {\n const exit = await Effect.runPromiseExit(retryOwnConflict(create, fetchExisting, input));\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n };\n}\n\n/**\n * Idempotent-retry wiring for a client-id create action: `clientId` gates the\n * wrap to commands whose input actually carries a client-generated `id` (an\n * entity form definition's own `clientId`, from `defineEntityForm`);\n * `fetchExisting` re-fetches the submitted id (see {@link idempotentCreate}).\n */\nexport interface IdempotentCreateOptions<O> {\n readonly clientId: boolean;\n readonly fetchExisting: (id: string) => Promise<O> | Effect.Effect<O, unknown>;\n}\n\n/** Options for {@link runFormAction} and {@link formAction}. */\nexport interface FormActionOptions<A, O> {\n /** Retry a client-id create's own 409 as success (see {@link IdempotentCreateOptions}). */\n readonly idempotent?: IdempotentCreateOptions<O> | undefined;\n /**\n * How a command failure is recognised. Defaults to\n * {@link CommandFailure.jsonapiFailure}; compose with it to add an\n * application's own failures.\n */\n readonly classify?: Classify | undefined;\n /**\n * Applied to every form state echoed back to the browser (an invalid\n * submission, a routed command failure) — e.g. blanking password fields\n * so a secret never rides a response body.\n */\n readonly redact?: ((state: FormState<A>) => FormState<A>) | undefined;\n /**\n * What happens to a command failure the classifier does not recognise:\n * `\"error\"` (the default) answers an `Error` result at 500 carrying the\n * cause's message; `\"throw\"` rethrows the cause, leaving it to SvelteKit's\n * `handleError`.\n */\n readonly unrecognised?: \"error\" | \"throw\" | undefined;\n}\n\n/** The field path an error object's pointer routes to, or `[]` (the root). */\nconst fieldPath = (error: ErrorObject): ReadonlyArray<string> =>\n Option.toArray(\n fieldFromPointer(\n error.source !== undefined && \"pointer\" in error.source ? error.source.pointer : undefined,\n ),\n );\n\n/**\n * Route a recognised command failure onto the form state. A root issue lands\n * at the empty path, which the nested error tree exposes as `_errors` — the\n * form-level message surface (`form.errors._errors`).\n */\nconst routeFailure = <A>(state: FormState<A>, failure: CommandFailure): FormState<A> =>\n failure._tag === \"Routed\"\n ? failure.errors.reduce(\n (acc, error) => State.withError(acc, fieldPath(error), detailOf(error)),\n state,\n )\n : State.withError(state, [], failure.message);\n\n/**\n * Validate `request` against `form`, then:\n *\n * - invalid → a `Failure` carrying the form state (nested errors + posted\n * values), status 400, and the command never runs;\n * - valid → run the command (wrapped in the idempotent retry when\n * `options.idempotent.clientId` is true); on success a `Redirect` (303) to\n * `locationFor(output, input)`;\n * - a recognised command failure → a `Failure` at the failure's own status,\n * each JSON:API error routed onto its field (or the root);\n * - an unrecognised one → an `Error` result at 500 (or a rethrow, per\n * `options.unrecognised`).\n *\n * Posted values survive every failure, so the form re-renders what was typed.\n *\n * `locationFor` returns the redirect target as-is: `runFormAction` does not\n * check it. {@link formAction} hands it to SvelteKit's `redirect`, which\n * accepts only a same-origin location (see there).\n */\nexport async function runFormAction<S extends Schema.Top, O, Message = unknown>(\n form: Form.Form<S, Message>,\n request: Request,\n run: Command<S[\"Type\"], O>,\n locationFor: (output: O, input: S[\"Type\"]) => string,\n options: FormActionOptions<S[\"Type\"], O> = {},\n): Promise<FormActionResult<S[\"Type\"]>> {\n const redact = options.redact ?? ((state: FormState<S[\"Type\"]>) => state);\n // A posted form needs no decoding services at runtime; schemas projected\n // from elsewhere can still carry an unreduced `DecodingServices` type, so\n // only the requirements channel is narrowed here.\n const state = (await Effect.runPromise(\n form.validate(request) as Effect.Effect<FormState<S[\"Type\"], Message>>,\n )) as FormState<S[\"Type\"]>;\n if (!state.valid) return Result.failure(redact(state), 400);\n\n const idempotent = options.idempotent;\n const command =\n idempotent?.clientId === true\n ? retryOwnConflict(run, idempotent.fetchExisting, state.data)\n : toEffect(() => run(state.data));\n const exit = await Effect.runPromiseExit(command);\n if (Exit.isSuccess(exit)) return Result.redirect(locationFor(exit.value, state.data), 303);\n\n const cause = Cause.squash(exit.cause);\n const failure = (options.classify ?? jsonapiFailure)(cause);\n if (Option.isSome(failure)) {\n return Result.failure(redact(routeFailure(state, failure.value)), failure.value.status);\n }\n if (options.unrecognised === \"throw\") throw cause;\n return Result.errorResult(Predicate.isError(cause) ? cause.message : DEFAULT_MESSAGE, 500);\n}\n\n/**\n * A command for {@link formAction}: like {@link Command}, and also handed the\n * `RequestEvent` (for `locals`, `cookies`, `fetch`).\n */\nexport type ActionCommand<I, O> = (\n input: I,\n event: RequestEvent,\n) => Promise<O> | Effect.Effect<O, unknown>;\n\n/**\n * Derive a SvelteKit page form **action** from `form` plus its command. The\n * handler validates the submission, runs the command on success, and maps\n * the outcome onto SvelteKit's action protocol:\n *\n * - success → `redirect(303, locationFor(output, input))`;\n * - an invalid submission or a recognised command failure →\n * `fail(status, { form })`, carrying the (redacted) state;\n * - an unrecognised failure → `fail(500, { message })` (or a rethrow).\n *\n * Wire it into `export const actions`; the client `createForm` store applies\n * the returned `form` via {@link enhanceForm} (or `applyActionResult`).\n *\n * `locationFor` must return a same-origin path, such as\n * `/organisations/${id}`. SvelteKit 3's `redirect` rejects an external\n * location unless it is passed `{ external }`, and `formAction` never passes\n * it, so a `locationFor` that returns an absolute URL on another origin (or a\n * protocol-relative `//host/...`) makes the action throw an `Error` instead of\n * redirecting, after the command has already run. To send the user off-site,\n * redirect to a same-origin route that performs the external redirect itself.\n *\n * @example\n * ```ts\n * // src/routes/organisations/create/+page.server.ts\n * import { formAction } from \"@thomasfosterau/effect-forms-svelte/kit\";\n * import { organisationForm } from \"#lib/forms\";\n * import { api } from \"#lib/server/api\";\n *\n * export const actions = {\n * default: formAction(\n * organisationForm,\n * (input, { locals }) => api(locals).organisations.create(input),\n * (id) => `/organisations/${id}`,\n * ),\n * };\n * ```\n */\nexport function formAction<S extends Schema.Top, O, Message = unknown>(\n form: Form.Form<S, Message>,\n run: ActionCommand<S[\"Type\"], O>,\n locationFor: (output: O, input: S[\"Type\"]) => string,\n options?: FormActionOptions<S[\"Type\"], O>,\n) {\n return async (event: RequestEvent) => {\n const result = await runFormAction(\n form,\n event.request,\n (input) => run(input, event),\n locationFor,\n options,\n );\n const data = (d: FormActionData<S[\"Type\"]>): FormActionData<S[\"Type\"]> => d;\n switch (result._tag) {\n case \"Redirect\":\n return redirect(result.status, result.location);\n case \"Failure\":\n return fail(result.status, data({ form: result.state }));\n case \"Error\":\n return fail(result.status, data({ message: result.message }));\n case \"Success\":\n // `runFormAction` answers success with a redirect; a success result\n // carrying state is echoed back as-is.\n return data({ form: result.state });\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAM,YACJ,UAEA,OAAO,cAAc;CACnB,MAAM,MAAM,MAAM;CAClB,OAAO,OAAO,SAAS,GAAG,IACtB,MACA,OAAO,WAAW;EAAE,WAAW;EAAK,QAAQ,UAAU;CAAM,CAAC;AACnE,CAAC;AAIH,MAAM,cAAc,UAClB,UAAU,gBAAgB,KAAK,KAC9B,MAAwC,WAAW,QAClD,MAAsC,SAAS,kBAC9C,MAAsC,SAAS;AAEpD,MAAM,eAAe,UAAuC;CAC1D,MAAM,KAAK,UAAU,gBAAgB,KAAK,IAAK,MAAoC,KAAK,KAAA;CACxF,OAAO,UAAU,SAAS,EAAE,KAAK,OAAO,KAAK,KAAK,KAAA;AACpD;AAEA,MAAM,oBACJ,QACA,eACA,UAEA,eAAe,OAAO,KAAK,CAAC,CAAC,CAAC,KAC5B,OAAO,OAAO,UAAU;CACtB,MAAM,KAAK,YAAY,KAAK;CAC5B,IAAI,OAAO,KAAA,KAAa,CAAC,WAAW,KAAK,GAAG,OAAO,OAAO,KAAK,KAAK;CAEpE,OAAO,eAAe,cAAc,EAAE,CAAC,CAAC,CAAC,KAAK,OAAO,eAAe,KAAK,CAAC;AAC5E,CAAC,CACH;;;;;;;;;;;;;;;;;;AAmBF,SAAgB,iBACd,QACA,eACmC;CACnC,OAAO,OAAO,UAAU;EACtB,MAAM,OAAO,MAAM,OAAO,eAAe,iBAAiB,QAAQ,eAAe,KAAK,CAAC;EACvF,IAAI,KAAK,UAAU,IAAI,GAAG,OAAO,KAAK;EACtC,MAAM,MAAM,OAAO,KAAK,KAAK;CAC/B;AACF;;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;;;;AAgDA,SAAgB,WACd,MACA,KACA,aACA,SACA;CACA,OAAO,OAAO,UAAwB;EACpC,MAAM,SAAS,MAAM,cACnB,MACA,MAAM,UACL,UAAU,IAAI,OAAO,KAAK,GAC3B,aACA,OACF;EACA,MAAM,QAAQ,MAA4D;EAC1E,QAAQ,OAAO,MAAf;GACE,KAAK,YACH,OAAO,SAAS,OAAO,QAAQ,OAAO,QAAQ;GAChD,KAAK,WACH,OAAO,KAAK,OAAO,QAAQ,KAAK,EAAE,MAAM,OAAO,MAAM,CAAC,CAAC;GACzD,KAAK,SACH,OAAO,KAAK,OAAO,QAAQ,KAAK,EAAE,SAAS,OAAO,QAAQ,CAAC,CAAC;GAC9D,KAAK,WAGH,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,CAAC;EACtC;CACF;AACF"}
1
+ {"version":3,"file":"FormAction.js","names":[],"sources":["../../src/kit/FormAction.ts"],"sourcesContent":["/**\n * Derive a SvelteKit page form action from an `@thomasfosterau/effect-forms`\n * form plus the command it submits to.\n *\n * {@link runFormAction} is the framework-neutral seam — validate the request\n * against the form's schema (every field error collected, posted values\n * retained), run the command on a valid submission, and describe the outcome\n * as a `Result.FormActionResult`. {@link formAction} maps that onto\n * SvelteKit's action protocol (`redirect()` / `fail()`), which the client\n * store applies back via `applyActionResult` / {@link enhanceForm}.\n *\n * A command is either a Promise-returning function (an API client call) or\n * an `Effect` with no requirements; a failure on either is classified by\n * {@link CommandFailure.jsonapiFailure} (or a caller's own classifier) and\n * routed onto the form's fields by each JSON:API error's `source.pointer`.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/FormAction\n */\n\nimport { fail, redirect, type RequestEvent } from \"@sveltejs/kit\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport type * as Schema from \"effect/Schema\";\nimport { type Form, Result, State } from \"@thomasfosterau/effect-forms\";\nimport {\n type Classify,\n type CommandFailure,\n DEFAULT_MESSAGE,\n detailOf,\n type ErrorObject,\n jsonapiFailure,\n} from \"./CommandFailure.ts\";\nimport { fieldFromPointer } from \"./Pointer.ts\";\n\ntype FormState<A, Message = unknown> = State.FormState<A, Message>;\ntype FormActionResult<A, Message = unknown> = Result.FormActionResult<A, Message>;\ntype FormActionData<A = unknown, Message = unknown> = Result.FormActionData<A, Message>;\n\n/**\n * A command: a Promise-returning function or one returning an `Effect` with\n * no requirements (provide them first, e.g. through a `ManagedRuntime`).\n */\nexport type Command<I, O> = (input: I) => Promise<O> | Effect.Effect<O, unknown>;\n\nconst toEffect = <O>(\n thunk: () => Promise<O> | Effect.Effect<O, unknown>,\n): Effect.Effect<O, unknown> =>\n Effect.suspend(() => {\n const out = thunk();\n return Effect.isEffect(out)\n ? out\n : Effect.tryPromise({ try: () => out, catch: (cause) => cause });\n });\n\n// ── Idempotent client-id create retry ──────────────────────────────────\n\nconst isConflict = (cause: unknown): boolean =>\n Predicate.isObjectOrArray(cause) &&\n Predicate.hasProperty(cause, \"status\") &&\n cause.status === 409 &&\n (Predicate.isTagged(cause, \"JsonapiError\") || Predicate.isTagged(cause, \"ErrorResponse\"));\n\nconst submittedId = (input: unknown): Option.Option<string> =>\n Predicate.isObjectOrArray(input) &&\n Predicate.hasProperty(input, \"id\") &&\n Predicate.isString(input.id) &&\n input.id !== \"\"\n ? Option.some(input.id)\n : Option.none();\n\nconst retryOwnConflict = <I, O>(\n create: Command<I, O>,\n fetchExisting: (id: string) => Promise<O> | Effect.Effect<O, unknown>,\n input: I,\n): Effect.Effect<O, unknown> =>\n toEffect(() => create(input)).pipe(\n Effect.catch((cause) =>\n Option.match(isConflict(cause) ? submittedId(input) : Option.none(), {\n onNone: () => Effect.fail(cause),\n // The re-fetch failing rethrows the ORIGINAL conflict, not its own error.\n onSome: (id) => toEffect(() => fetchExisting(id)).pipe(Effect.mapError(() => cause)),\n }),\n ),\n );\n\n/**\n * Wrap a client-id create command so a 409 conflict on the caller's OWN\n * submitted `id` resolves as success instead of a form error — the\n * double-submit of a create whose id the client generated.\n *\n * On any 409 (a `JsonapiError` / `ErrorResponse`-tagged cause), re-fetches\n * `input.id` via `fetchExisting` and returns that. This is deliberately\n * unconditional on *why* the 409 fired: the re-fetch is the proof, not the\n * status. A 409 from an unrelated precondition never left a row at\n * `input.id`, so the re-fetch fails and the original conflict rethrows\n * unchanged. An input with no `id`, or any other failure, rethrows as is.\n *\n * `input.id` is read structurally rather than through a constraint on\n * `Input`: a constraint here would be used only contravariantly (as\n * `create`'s parameter), which makes TypeScript infer `Input` from the\n * constraint instead of from the command's own input type.\n */\nexport function idempotentCreate<Input, Output>(\n create: (input: Input) => Promise<Output>,\n fetchExisting: (id: string) => Promise<Output>,\n): (input: Input) => Promise<Output> {\n return async (input) => {\n const exit = await Effect.runPromiseExit(retryOwnConflict(create, fetchExisting, input));\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n };\n}\n\n/**\n * Idempotent-retry wiring for a client-id create action: `clientId` gates the\n * wrap to commands whose input actually carries a client-generated `id` (an\n * entity form definition's own `clientId`, from `defineEntityForm`);\n * `fetchExisting` re-fetches the submitted id (see {@link idempotentCreate}).\n */\nexport interface IdempotentCreateOptions<O> {\n readonly clientId: boolean;\n readonly fetchExisting: (id: string) => Promise<O> | Effect.Effect<O, unknown>;\n}\n\n/** Options for {@link runFormAction} and {@link formAction}. */\nexport interface FormActionOptions<A, O> {\n /** Retry a client-id create's own 409 as success (see {@link IdempotentCreateOptions}). */\n readonly idempotent?: IdempotentCreateOptions<O> | undefined;\n /**\n * How a command failure is recognised. Defaults to\n * {@link CommandFailure.jsonapiFailure}; compose with it to add an\n * application's own failures.\n */\n readonly classify?: Classify | undefined;\n /**\n * Applied to every form state echoed back to the browser (an invalid\n * submission, a routed command failure) — e.g. blanking password fields\n * so a secret never rides a response body.\n */\n readonly redact?: ((state: FormState<A>) => FormState<A>) | undefined;\n /**\n * What happens to a command failure the classifier does not recognise:\n * `\"error\"` (the default) answers an `Error` result at 500 carrying the\n * cause's message; `\"throw\"` rethrows the cause, leaving it to SvelteKit's\n * `handleError`.\n */\n readonly unrecognised?: \"error\" | \"throw\" | undefined;\n}\n\n/** The field path an error object's pointer routes to, or `[]` (the root). */\nconst fieldPath = (error: ErrorObject): ReadonlyArray<string> =>\n Option.toArray(\n fieldFromPointer(\n error.source !== undefined && \"pointer\" in error.source ? error.source.pointer : undefined,\n ),\n );\n\n/**\n * Route a recognised command failure onto the form state. A root issue lands\n * at the empty path, which the nested error tree exposes as `_errors` — the\n * form-level message surface (`form.errors._errors`).\n */\nconst routeFailure = <A>(state: FormState<A>, failure: CommandFailure): FormState<A> =>\n Predicate.isTagged(failure, \"Routed\")\n ? failure.errors.reduce(\n (acc, error) => State.withError(acc, fieldPath(error), detailOf(error)),\n state,\n )\n : State.withError(state, [], failure.message);\n\n/**\n * Validate `request` against `form`, then:\n *\n * - invalid → a `Failure` carrying the form state (nested errors + posted\n * values), status 400, and the command never runs;\n * - valid → run the command (wrapped in the idempotent retry when\n * `options.idempotent.clientId` is true); on success a `Redirect` (303) to\n * `locationFor(output, input)`;\n * - a recognised command failure → a `Failure` at the failure's own status,\n * each JSON:API error routed onto its field (or the root);\n * - an unrecognised one → an `Error` result at 500 (or a rethrow, per\n * `options.unrecognised`).\n *\n * Posted values survive every failure, so the form re-renders what was typed.\n *\n * `locationFor` returns the redirect target as-is: `runFormAction` does not\n * check it. {@link formAction} hands it to SvelteKit's `redirect`, which\n * accepts only a same-origin location (see there).\n */\nexport async function runFormAction<S extends Schema.Top, O, Message = unknown>(\n form: Form.Form<S, Message>,\n request: Request,\n run: Command<S[\"Type\"], O>,\n locationFor: (output: O, input: S[\"Type\"]) => string,\n options: FormActionOptions<S[\"Type\"], O> = {},\n): Promise<FormActionResult<S[\"Type\"]>> {\n const redact = options.redact ?? ((state: FormState<S[\"Type\"]>) => state);\n const classify = options.classify ?? jsonapiFailure;\n // SAFETY: a posted form needs no decoding services at runtime; schemas\n // projected from elsewhere can still carry an unreduced `DecodingServices`\n // type, so only the requirements channel is narrowed here.\n const validate = form.validate(request) as Effect.Effect<FormState<S[\"Type\"], Message>>;\n const program = Effect.flatMap(\n validate,\n (state): Effect.Effect<FormActionResult<S[\"Type\"]>, unknown> => {\n if (!state.valid) return Effect.succeed(Result.failure(redact(state), 400));\n const idempotent = options.idempotent;\n const command =\n idempotent?.clientId === true\n ? retryOwnConflict(run, idempotent.fetchExisting, state.data)\n : toEffect(() => run(state.data));\n return Effect.matchCauseEffect(command, {\n onSuccess: (output) =>\n Effect.sync(() => Result.redirect(locationFor(output, state.data), 303)),\n onFailure: (commandCause) =>\n Effect.suspend(() => {\n const cause = Cause.squash(commandCause);\n return Option.match(classify(cause), {\n onSome: (failure) =>\n Effect.sync(() =>\n Result.failure(redact(routeFailure(state, failure)), failure.status),\n ),\n onNone: () =>\n options.unrecognised === \"throw\"\n ? Effect.fail(cause)\n : Effect.succeed(\n Result.errorResult(\n Predicate.isError(cause) ? cause.message : DEFAULT_MESSAGE,\n 500,\n ),\n ),\n });\n }),\n });\n },\n );\n // The Promise boundary: an unrecognised failure under `\"throw\"` (or a defect\n // anywhere above) rejects with the squashed cause, as a thrown value would.\n const exit = await Effect.runPromiseExit(program);\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n}\n\n/**\n * A command for {@link formAction}: like {@link Command}, and also handed the\n * `RequestEvent` (for `locals`, `cookies`, `fetch`).\n */\nexport type ActionCommand<I, O> = (\n input: I,\n event: RequestEvent,\n) => Promise<O> | Effect.Effect<O, unknown>;\n\n/** Pin an action's return to {@link FormActionData}, so every branch types alike. */\nconst actionData = <A>(data: FormActionData<A>): FormActionData<A> => data;\n\n/**\n * Derive a SvelteKit page form **action** from `form` plus its command. The\n * handler validates the submission, runs the command on success, and maps\n * the outcome onto SvelteKit's action protocol:\n *\n * - success → `redirect(303, locationFor(output, input))`;\n * - an invalid submission or a recognised command failure →\n * `fail(status, { form })`, carrying the (redacted) state;\n * - an unrecognised failure → `fail(500, { message })` (or a rethrow).\n *\n * Wire it into `export const actions`; the client `createForm` store applies\n * the returned `form` via {@link enhanceForm} (or `applyActionResult`).\n *\n * `locationFor` must return a same-origin path, such as\n * `/organisations/${id}`. SvelteKit 3's `redirect` rejects an external\n * location unless it is passed `{ external }`, and `formAction` never passes\n * it, so a `locationFor` that returns an absolute URL on another origin (or a\n * protocol-relative `//host/...`) makes the action throw an `Error` instead of\n * redirecting, after the command has already run. To send the user off-site,\n * redirect to a same-origin route that performs the external redirect itself.\n *\n * @example\n * ```ts\n * // src/routes/organisations/create/+page.server.ts\n * import { formAction } from \"@thomasfosterau/effect-forms-svelte/kit\";\n * import { organisationForm } from \"#lib/forms\";\n * import { api } from \"#lib/server/api\";\n *\n * export const actions = {\n * default: formAction(\n * organisationForm,\n * (input, { locals }) => api(locals).organisations.create(input),\n * (id) => `/organisations/${id}`,\n * ),\n * };\n * ```\n */\nexport function formAction<S extends Schema.Top, O, Message = unknown>(\n form: Form.Form<S, Message>,\n run: ActionCommand<S[\"Type\"], O>,\n locationFor: (output: O, input: S[\"Type\"]) => string,\n options?: FormActionOptions<S[\"Type\"], O>,\n) {\n return async (event: RequestEvent) => {\n const result = await runFormAction(\n form,\n event.request,\n (input) => run(input, event),\n locationFor,\n options,\n );\n return Match.valueTags(result, {\n Redirect: (redirectResult) => redirect(redirectResult.status, redirectResult.location),\n Failure: (failure) => fail(failure.status, actionData<S[\"Type\"]>({ form: failure.state })),\n Error: (error) => fail(error.status, actionData<S[\"Type\"]>({ message: error.message })),\n // `runFormAction` answers success with a redirect; a success result\n // carrying state is echoed back as-is.\n Success: (success) => actionData<S[\"Type\"]>({ form: success.state }),\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,YACJ,UAEA,OAAO,cAAc;CACnB,MAAM,MAAM,MAAM;CAClB,OA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;;;;;;;;AAuCtE,SAAgB,WACd,MACA,KACA,aACA,SACA;CACA,OAAO,OAAO,UAAwB;EACpC,MAAM,SAAS,MAAM,cACnB,MACA,MAAM,UACL,UAAU,IAAI,OAAO,KAAK,GAC3B,aACA,OACF;EACA,OAAO,MAAM,UAAU,QAAQ;GAC7B,WAAW,mBAAmB,SAAS,eAAe,QAAQ,eAAe,QAAQ;GACrF,UAAU,YAAY,KAAK,QAAQ,QAAQ,WAAsB,EAAE,MAAM,QAAQ,MAAM,CAAC,CAAC;GACzF,QAAQ,UAAU,KAAK,MAAM,QAAQ,WAAsB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC;GAGtF,UAAU,YAAY,WAAsB,EAAE,MAAM,QAAQ,MAAM,CAAC;EACrE,CAAC;CACH;AACF"}
@@ -1,4 +1,3 @@
1
- //#region src/kit/FormStateReaders.d.ts
2
1
  /**
3
2
  * Total readers over the form state a failed form action hands back on
4
3
  * `PageProps["form"]`.
@@ -54,5 +53,4 @@ export declare const rootIssuesOf: (state: ActionFormState | undefined) => Reado
54
53
  * the user sees what they sent.
55
54
  */
56
55
  export declare const valueOf: (state: ActionFormState | undefined, field: string, fallback?: string) => string;
57
- //#endregion
58
56
  //# sourceMappingURL=FormStateReaders.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import * as Predicate from "effect/Predicate";
2
- //#region src/kit/FormStateReaders.ts
2
+ // src/kit/FormStateReaders.ts
3
3
  /**
4
4
  * Total readers over the form state a failed form action hands back on
5
5
  * `PageProps["form"]`.
@@ -28,9 +28,10 @@ import * as Predicate from "effect/Predicate";
28
28
  * that carried a bare message instead.
29
29
  */
30
30
  const formStateOf = (form) => {
31
- if (!Predicate.isObjectOrArray(form)) return void 0;
31
+ if (!Predicate.isObjectOrArray(form) || !Predicate.hasProperty(form, "form")) return void 0;
32
32
  const state = form.form;
33
- return Predicate.isObjectOrArray(state) ? state : void 0;
33
+ if (!Predicate.isObjectOrArray(state)) return void 0;
34
+ return state;
34
35
  };
35
36
  /** Messages attached to a named field, or none. */
36
37
  const issuesFor = (state, field) => {
@@ -57,7 +58,6 @@ const valueOf = (state, field, fallback = "") => {
57
58
  if (value === void 0 || value === null) return fallback;
58
59
  return Predicate.isString(value) ? value : String(value);
59
60
  };
60
- //#endregion
61
61
  export { formStateOf, issuesFor, rootIssuesOf, valueOf };
62
62
 
63
63
  //# sourceMappingURL=FormStateReaders.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"FormStateReaders.js","names":[],"sources":["../../src/kit/FormStateReaders.ts"],"sourcesContent":["/**\n * Total readers over the form state a failed form action hands back on\n * `PageProps[\"form\"]`.\n *\n * {@link formAction} answers an invalid submission with\n * `fail(status, { form: state })`, where `state` carries the posted values\n * and a nested error tree. A server-rendered page (no client store) needs\n * three things per field off a value SvelteKit types as `ActionData | null`:\n * what the user typed, what was wrong with it, and what was wrong with the\n * form as a whole.\n *\n * Every reader is deliberately **total**: it answers sensibly for a first\n * render (`form` is `null`), for a successful submission, and for a shape\n * that is not a form state at all. A create page that threw on\n * `form === null` would fail on the one render it does most.\n *\n * `undefined` rather than `Option` for \"no submission\": these are called from\n * Svelte templates, where `Option` has no rendering.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/FormStateReaders\n */\n\nimport * as Predicate from \"effect/Predicate\";\n\n/**\n * The subset of `State.FormState` the readers touch: the posted values and\n * the nested error tree. Structural rather than imported so a page can hand\n * in its raw `ActionData` without a cast.\n */\nexport interface ActionFormState {\n readonly data?: Readonly<Record<string, unknown>>;\n readonly errors?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * The carried form state, or `undefined` when there is none — a first\n * render, a successful submission (which redirects), or an action result\n * that carried a bare message instead.\n */\nexport const formStateOf = (form: unknown): ActionFormState | undefined => {\n if (!Predicate.isObjectOrArray(form)) return undefined;\n const state = (form as { readonly form?: unknown }).form;\n return Predicate.isObjectOrArray(state) ? (state as ActionFormState) : undefined;\n};\n\n/** Messages attached to a named field, or none. */\nexport const issuesFor = (\n state: ActionFormState | undefined,\n field: string,\n): ReadonlyArray<string> => {\n const issues = state?.errors?.[field];\n return Array.isArray(issues) ? (issues as ReadonlyArray<string>) : [];\n};\n\n/**\n * Whole-form messages — the ones with no field to attach to (a 409, a\n * rejected command). {@link runFormAction} routes them to the error tree's\n * empty path, which the nested tree exposes as `_errors`.\n */\nexport const rootIssuesOf = (state: ActionFormState | undefined): ReadonlyArray<string> =>\n issuesFor(state, \"_errors\");\n\n/**\n * What to render in a field: the value the user posted if this is a failed\n * submission, else `fallback` (the row's stored value on an edit form, or\n * the empty string on a create form). A posted blank stays blank.\n *\n * Non-string posted values (a checkbox's boolean, a number) render through\n * `String(...)` rather than being dropped: the point of repopulation is that\n * the user sees what they sent.\n */\nexport const valueOf = (\n state: ActionFormState | undefined,\n field: string,\n fallback = \"\",\n): string => {\n const value = state?.data?.[field];\n if (value === undefined || value === null) return fallback;\n // oxlint-disable-next-line typescript/no-base-to-string -- posted values are form scalars (a checkbox's boolean, a number); rendering them is the point\n return Predicate.isString(value) ? value : String(value);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,eAAe,SAA+C;CACzE,IAAI,CAAC,UAAU,gBAAgB,IAAI,GAAG,OAAO,KAAA;CAC7C,MAAM,QAAS,KAAqC;CACpD,OAAO,UAAU,gBAAgB,KAAK,IAAK,QAA4B,KAAA;AACzE;;AAGA,MAAa,aACX,OACA,UAC0B;CAC1B,MAAM,SAAS,OAAO,SAAS;CAC/B,OAAO,MAAM,QAAQ,MAAM,IAAK,SAAmC,CAAC;AACtE;;;;;;AAOA,MAAa,gBAAgB,UAC3B,UAAU,OAAO,SAAS;;;;;;;;;;AAW5B,MAAa,WACX,OACA,OACA,WAAW,OACA;CACX,MAAM,QAAQ,OAAO,OAAO;CAC5B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAElD,OAAO,UAAU,SAAS,KAAK,IAAI,QAAQ,OAAO,KAAK;AACzD"}
1
+ {"version":3,"file":"FormStateReaders.js","names":[],"sources":["../../src/kit/FormStateReaders.ts"],"sourcesContent":["/**\n * Total readers over the form state a failed form action hands back on\n * `PageProps[\"form\"]`.\n *\n * {@link formAction} answers an invalid submission with\n * `fail(status, { form: state })`, where `state` carries the posted values\n * and a nested error tree. A server-rendered page (no client store) needs\n * three things per field off a value SvelteKit types as `ActionData | null`:\n * what the user typed, what was wrong with it, and what was wrong with the\n * form as a whole.\n *\n * Every reader is deliberately **total**: it answers sensibly for a first\n * render (`form` is `null`), for a successful submission, and for a shape\n * that is not a form state at all. A create page that threw on\n * `form === null` would fail on the one render it does most.\n *\n * `undefined` rather than `Option` for \"no submission\": these are called from\n * Svelte templates, where `Option` has no rendering.\n *\n * @copyright Thomas Foster\n * @module effect-forms-svelte/kit/FormStateReaders\n */\n\nimport * as Predicate from \"effect/Predicate\";\n\n/**\n * The subset of `State.FormState` the readers touch: the posted values and\n * the nested error tree. Structural rather than imported so a page can hand\n * in its raw `ActionData` without a cast.\n */\nexport interface ActionFormState {\n readonly data?: Readonly<Record<string, unknown>>;\n readonly errors?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * The carried form state, or `undefined` when there is none — a first\n * render, a successful submission (which redirects), or an action result\n * that carried a bare message instead.\n */\nexport const formStateOf = (form: unknown): ActionFormState | undefined => {\n if (!Predicate.isObjectOrArray(form) || !Predicate.hasProperty(form, \"form\")) return undefined;\n const state = form.form;\n if (!Predicate.isObjectOrArray(state)) return undefined;\n // SAFETY: `ActionFormState` is all-optional and every reader below reaches\n // `data` / `errors` only through optional chaining and re-checks the value it\n // finds (`Array.isArray`, `isString`), so any object answers totally.\n return state as ActionFormState;\n};\n\n/** Messages attached to a named field, or none. */\nexport const issuesFor = (\n state: ActionFormState | undefined,\n field: string,\n): ReadonlyArray<string> => {\n const issues = state?.errors?.[field];\n // SAFETY: the error tree `formAction` hands back holds the form's messages\n // at each field, and these readers serve pages whose messages are strings.\n return Array.isArray(issues) ? (issues as ReadonlyArray<string>) : [];\n};\n\n/**\n * Whole-form messages — the ones with no field to attach to (a 409, a\n * rejected command). {@link runFormAction} routes them to the error tree's\n * empty path, which the nested tree exposes as `_errors`.\n */\nexport const rootIssuesOf = (state: ActionFormState | undefined): ReadonlyArray<string> =>\n issuesFor(state, \"_errors\");\n\n/**\n * What to render in a field: the value the user posted if this is a failed\n * submission, else `fallback` (the row's stored value on an edit form, or\n * the empty string on a create form). A posted blank stays blank.\n *\n * Non-string posted values (a checkbox's boolean, a number) render through\n * `String(...)` rather than being dropped: the point of repopulation is that\n * the user sees what they sent.\n */\nexport const valueOf = (\n state: ActionFormState | undefined,\n field: string,\n fallback = \"\",\n): string => {\n const value = state?.data?.[field];\n if (value === undefined || value === null) return fallback;\n // oxlint-disable-next-line typescript/no-base-to-string -- posted values are form scalars (a checkbox's boolean, a number); rendering them is the point\n return Predicate.isString(value) ? value : String(value);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,eAAe,SAA+C;CACzE,IAAI,CAAC,UAAU,gBAAgB,IAAI,KAAK,CAAC,UAAU,YAAY,MAAM,MAAM,GAAG,OAAO,KAAA;CACrF,MAAM,QAAQ,KAAK;CACnB,IAAI,CAAC,UAAU,gBAAgB,KAAK,GAAG,OAAO,KAAA;CAI9C,OAAO;AACT;;AAGA,MAAa,aACX,OACA,UAC0B;CAC1B,MAAM,SAAS,OAAO,SAAS;CAG/B,OAAO,MAAM,QAAQ,MAAM,IAAK,SAAmC,CAAC;AACtE;;;;;;AAOA,MAAa,gBAAgB,UAC3B,UAAU,OAAO,SAAS;;;;;;;;;;AAW5B,MAAa,WACX,OACA,OACA,WAAW,OACA;CACX,MAAM,QAAQ,OAAO,OAAO;CAC5B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAElD,OAAO,UAAU,SAAS,KAAK,IAAI,QAAQ,OAAO,KAAK;AACzD"}
@@ -1,5 +1,4 @@
1
1
  import * as Option from "effect/Option";
2
- //#region src/kit/Pointer.d.ts
3
2
  /**
4
3
  * The field a JSON Pointer of the form `/data/attributes/<field>…` names.
5
4
  * Deeper segments are ignored: the form issue layer keys by the top-level
@@ -19,5 +18,4 @@ import * as Option from "effect/Option";
19
18
  * ```
20
19
  */
21
20
  export declare const fieldFromPointer: (pointer: string | undefined) => Option.Option<string>;
22
- //#endregion
23
21
  //# sourceMappingURL=Pointer.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import * as Option from "effect/Option";
2
- //#region src/kit/Pointer.ts
2
+ // src/kit/Pointer.ts
3
3
  /**
4
4
  * JSON Pointer → form field routing for a JSON:API error object's
5
5
  * `source.pointer`.
@@ -32,7 +32,6 @@ const fieldFromPointer = (pointer) => {
32
32
  if (data !== "data" || attributes !== "attributes") return Option.none();
33
33
  return field === void 0 || field === "" ? Option.none() : Option.some(field);
34
34
  };
35
- //#endregion
36
35
  export { fieldFromPointer };
37
36
 
38
37
  //# sourceMappingURL=Pointer.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thomasfosterau/effect-forms-svelte",
3
- "version": "0.2.0",
3
+ "version": "0.3.2",
4
4
  "description": "Svelte 5 (runes) bindings for @thomasfosterau/effect-forms — a reactive form store, an enhance action, tainted tracking, and client-side validation.",
5
5
  "keywords": [
6
6
  "effect",
@@ -12,7 +12,7 @@
12
12
  "sveltekit",
13
13
  "typescript"
14
14
  ],
15
- "homepage": "https://github.com/thomasfosterau/effect-forms/tree/main/packages/svelte#readme",
15
+ "homepage": "https://github.com/thomasfosterau/effect-forms/tree/trunk/packages/svelte#readme",
16
16
  "bugs": {
17
17
  "url": "https://github.com/thomasfosterau/effect-forms/issues"
18
18
  },
@@ -49,16 +49,16 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@thomasfosterau/effect-forms": "^0.2.0"
52
+ "@thomasfosterau/effect-forms": "^0.3.2"
53
53
  },
54
54
  "devDependencies": {
55
- "@sveltejs/kit": "3.0.0",
56
- "@thomasfosterau/effect-jsonapi": "^0.16.3"
55
+ "@sveltejs/kit": "3.1.1",
56
+ "@thomasfosterau/effect-jsonapi": "^0.20.0"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "@sveltejs/kit": "^3.0.0",
60
60
  "@thomasfosterau/effect-jsonapi": ">=0.16.0",
61
- "effect": ">=4.0.0-rc.118",
61
+ "effect": "^4.0.0",
62
62
  "svelte": "^5.40.0"
63
63
  },
64
64
  "peerDependenciesMeta": {