svelte-effect-runtime 2.5.1 → 3.0.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.
- package/.dist/chunks/{client-Cj2X9lY-.js → client-Cruhk6Oo.js} +12 -5
- package/.dist/chunks/client-Cruhk6Oo.js.map +1 -0
- package/.dist/chunks/{dispatcher-BVkm8qbG.js → dispatcher-CgCdn6bj.js} +12 -2
- package/.dist/chunks/{dispatcher-BVkm8qbG.js.map → dispatcher-CgCdn6bj.js.map} +1 -1
- package/.dist/chunks/{preprocess-DseI9Doo.js → preprocess-BhoCga82.js} +49 -6
- package/.dist/chunks/preprocess-BhoCga82.js.map +1 -0
- package/.dist/chunks/{transform-Cx5bjmP6.js → transform-CMvL4SBp.js} +19 -9
- package/.dist/chunks/transform-CMvL4SBp.js.map +1 -0
- package/.dist/dispatcher.js +1 -1
- package/.dist/internal/generators.js +1 -1
- package/.dist/internal/remote-client.js +1 -1
- package/.dist/markup/promise.js +1 -1
- package/.dist/markup/run.js +1 -1
- package/.dist/markup/transform.js +1 -1
- package/.dist/markup/value.js +1 -1
- package/.dist/mod.d.ts +1 -40
- package/.dist/mod.js +2 -27
- package/.dist/mod.js.map +1 -1
- package/.dist/preprocess/imports.d.ts +10 -2
- package/.dist/preprocess/types.d.ts +8 -1
- package/.dist/preprocess.js +2 -2
- package/.dist/remote/client.js +1 -1
- package/.dist/remote/server.js +5 -1
- package/.dist/remote/server.js.map +1 -1
- package/.dist/runtime/transform.d.ts +2 -0
- package/.dist/{chunks/transform-BotzDlj3.js → runtime/transform.js} +4 -17
- package/.dist/runtime/transform.js.map +1 -0
- package/.dist/server/factories.d.ts +5 -1
- package/.dist/server/index.d.ts +1 -1
- package/.dist/server/types.d.ts +44 -1
- package/.dist/server.d.ts +1 -1
- package/.dist/server.js.map +1 -1
- package/.dist/vite.js +9 -13
- package/.dist/vite.js.map +1 -1
- package/package.json +4 -4
- package/.dist/chunks/client-Cj2X9lY-.js.map +0 -1
- package/.dist/chunks/preprocess-DseI9Doo.js.map +0 -1
- package/.dist/chunks/transform-BotzDlj3.js.map +0 -1
- package/.dist/chunks/transform-Cx5bjmP6.js.map +0 -1
- package/.dist/runtime/preprocess.d.ts +0 -39
- package/.dist/runtime/preprocess.js +0 -31
- package/.dist/runtime/preprocess.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as get_dispatcher } from "./dispatcher-
|
|
1
|
+
import { n as get_dispatcher } from "./dispatcher-CgCdn6bj.js";
|
|
2
2
|
import { create_remote_http_error, create_remote_transport_error, create_remote_validation_error, is_serialized_remote_failure_envelope } from "../remote/shared.js";
|
|
3
3
|
import { t as copy_property_descriptors } from "./descriptors-OS4VfJuW.js";
|
|
4
4
|
import { Effect } from "effect";
|
|
@@ -141,10 +141,16 @@ async function decode_response_failure(response) {
|
|
|
141
141
|
async function decode_response_or_value(value, decode_payload) {
|
|
142
142
|
if (value instanceof Response) {
|
|
143
143
|
if (!value.ok) throw await decode_response_failure(value);
|
|
144
|
-
return decode_payload(await value
|
|
144
|
+
return decode_payload(await decode_success_response_body(value));
|
|
145
145
|
}
|
|
146
146
|
return decode_payload(value);
|
|
147
147
|
}
|
|
148
|
+
async function decode_success_response_body(response) {
|
|
149
|
+
if (response.status === 204 || response.status === 205) return;
|
|
150
|
+
const text = await response.text();
|
|
151
|
+
if (text.length === 0) return;
|
|
152
|
+
return JSON.parse(text);
|
|
153
|
+
}
|
|
148
154
|
//#endregion
|
|
149
155
|
//#region src/remote/client/effect.ts
|
|
150
156
|
/**
|
|
@@ -302,8 +308,9 @@ function decode_form_response(envelope, decode_payload) {
|
|
|
302
308
|
if (is_decoded_remote_failure(decoded)) throw decoded;
|
|
303
309
|
throw create_remote_http_error(response.status ?? 500, response.error);
|
|
304
310
|
}
|
|
305
|
-
|
|
306
|
-
|
|
311
|
+
const result_text = typeof response.result === "string" ? response.result : typeof response.data === "string" ? response.data : void 0;
|
|
312
|
+
if (response.type !== "result" || result_text === void 0) throw create_remote_transport_error(/* @__PURE__ */ new Error("[REMOTE_FORM_RESPONSE_UNSUPPORTED]: Unsupported remote form response"), envelope);
|
|
313
|
+
const decoded = decode_payload(parse(result_text));
|
|
307
314
|
if (decoded.issues && decoded.issues.length > 0) throw create_remote_validation_error(decoded.issues, decoded, 400);
|
|
308
315
|
return decoded.result;
|
|
309
316
|
}
|
|
@@ -568,4 +575,4 @@ function make_live_query_resource(resource) {
|
|
|
568
575
|
//#endregion
|
|
569
576
|
export { create_remote_command_adapter as i, create_remote_query_adapter as n, create_remote_form_adapter as r, create_remote_live_query_adapter as t };
|
|
570
577
|
|
|
571
|
-
//# sourceMappingURL=client-
|
|
578
|
+
//# sourceMappingURL=client-Cruhk6Oo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-Cruhk6Oo.js","names":[],"sources":["../../../modules/svelte-effect-runtime/src/remote/client/failures.ts","../../../modules/svelte-effect-runtime/src/remote/client/responses.ts","../../../modules/svelte-effect-runtime/src/remote/client/effect.ts","../../../modules/svelte-effect-runtime/src/remote/client/utils.ts","../../../modules/svelte-effect-runtime/src/remote/client/command.ts","../../../modules/svelte-effect-runtime/src/remote/client/form-data.ts","../../../modules/svelte-effect-runtime/src/remote/client/form-transport.ts","../../../modules/svelte-effect-runtime/src/remote/client/form-enhance.ts","../../../modules/svelte-effect-runtime/src/remote/client/form.ts","../../../modules/svelte-effect-runtime/src/remote/client/query-result.ts","../../../modules/svelte-effect-runtime/src/remote/client/query.ts"],"sourcesContent":["import {\n create_remote_http_error,\n create_remote_transport_error,\n create_remote_validation_error,\n is_serialized_remote_failure_envelope,\n} from \"$/remote/shared.ts\";\nimport type { FormIssue, RemoteFailure } from \"$/remote/shared.ts\";\nimport { parse } from \"devalue\";\n\n/**\n * Decodes a raw wire value into a remote failure when it uses the runtime\n * failure envelope.\n *\n * @example\n * ```ts\n * const failure = decode_remote_error(body);\n * ```\n *\n * @since 2.0.0\n * @param raw - Raw value received from the network or SvelteKit error body.\n * @param decode - Optional devalue decoder for custom error payloads.\n * @returns The decoded failure/value, or a transport error when decoding fails.\n */\nexport function decode_remote_error<ErrorType = never>(\n raw: unknown,\n decode?: (encoded: string) => unknown,\n): RemoteFailure<ErrorType> | unknown {\n const embedded = parse_embedded_remote_failure(raw);\n\n if (embedded !== raw) {\n return decode_remote_error<ErrorType>(embedded, decode);\n }\n\n if (is_serialized_remote_failure_envelope(raw)) {\n try {\n const decoded = decode ? decode(raw.encoded) : parse(raw.encoded);\n\n return decoded as RemoteFailure<ErrorType>;\n } catch {\n return create_remote_transport_error(\n new Error(\n \"[REMOTE_ERROR_DECODE_FAILED]: Failed to decode remote error payload\",\n ),\n raw,\n );\n }\n }\n\n return raw;\n}\n\nfunction parse_embedded_remote_failure(raw: unknown): unknown {\n if (typeof raw === \"string\") {\n return parse_json_or_original(raw);\n }\n\n if (typeof raw !== \"object\" || raw === null || !(\"message\" in raw)) {\n return raw;\n }\n\n const message = (raw as { message?: unknown }).message;\n\n if (typeof message !== \"string\") {\n return raw;\n }\n\n const parsed = parse_json_or_original(message);\n\n return parsed === message ? raw : parsed;\n}\n\nfunction parse_json_or_original(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Checks whether a decoded value is a tagged remote failure.\n *\n * @example\n * ```ts\n * if (is_decoded_remote_failure(value)) throw value;\n * ```\n *\n * @since 2.0.0\n * @param value - Value to inspect.\n * @returns Whether the value carries a `_tag` discriminator.\n */\nexport function is_decoded_remote_failure(\n value: unknown,\n): value is RemoteFailure<never> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_tag\" in value\n );\n}\n\n/**\n * Checks whether a response body represents SvelteKit validation issues.\n *\n * @example\n * ```ts\n * if (is_validation_body(body)) return body.issues;\n * ```\n *\n * @since 2.0.0\n * @param value - Value to inspect.\n * @returns Whether the value contains a form issue list.\n */\nexport function is_validation_body(\n value: unknown,\n): value is { issues: readonly FormIssue[] } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as { issues?: unknown }).issues)\n );\n}\n\n/**\n * Normalizes native thrown values into the runtime's remote failure model.\n *\n * @example\n * ```ts\n * const failure = normalize_native_error(error);\n * ```\n *\n * @since 2.0.0\n * @param error - Unknown value thrown by a native remote helper.\n * @returns A typed remote failure.\n */\nexport function normalize_native_error<ErrorType = never>(\n error: unknown,\n): RemoteFailure<ErrorType> {\n const body = get_error_body(error);\n const decoded = decode_remote_error<ErrorType>(body);\n const status = get_error_status(error);\n\n if (is_decoded_remote_failure(decoded)) {\n return decoded;\n }\n\n if (status === 400 && is_validation_body(body)) {\n return create_remote_validation_error(body.issues, body, status);\n }\n\n if (status !== undefined) {\n return create_remote_http_error(status, body, error);\n }\n\n return create_remote_transport_error(error);\n}\n\nfunction get_error_status(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null) {\n return undefined;\n }\n\n const status = (error as { status?: unknown }).status;\n\n return typeof status === \"number\" ? status : undefined;\n}\n\nfunction get_error_body(error: unknown): unknown {\n if (typeof error !== \"object\" || error === null) {\n return undefined;\n }\n\n if (\"body\" in error) {\n return (error as { body?: unknown }).body;\n }\n\n if (\"data\" in error) {\n return (error as { data?: unknown }).data;\n }\n\n return undefined;\n}\n","import {\n create_remote_http_error,\n create_remote_validation_error,\n} from \"$/remote/shared.ts\";\nimport type { RemoteFailure } from \"$/remote/shared.ts\";\n\nimport {\n decode_remote_error,\n is_decoded_remote_failure,\n is_validation_body,\n} from \"./failures.ts\";\n\n/**\n * Decodes a failed fetch response into the runtime failure model.\n *\n * @example\n * ```ts\n * const failure = await decode_response_failure(response);\n * ```\n *\n * @since 2.0.0\n * @param response - Failed fetch response returned by the remote endpoint.\n * @returns Remote failure represented by the response.\n */\nexport async function decode_response_failure<ErrorType = never>(\n response: Response,\n): Promise<RemoteFailure<ErrorType>> {\n const body = await response.json().catch(() => undefined);\n const decoded = decode_remote_error<ErrorType>(body);\n\n if (is_decoded_remote_failure(decoded)) {\n return decoded;\n }\n\n if (response.status === 400 && is_validation_body(body)) {\n return create_remote_validation_error(body.issues, body, response.status);\n }\n\n return create_remote_http_error(response.status, body);\n}\n\n/**\n * Decodes either a raw value or `Response` returned by a native remote helper.\n *\n * @example\n * ```ts\n * const output = await decode_response_or_value(result, decode_payload);\n * ```\n *\n * @since 2.0.0\n * @param value - Native result value or fetch response.\n * @param decode_payload - Function used to decode successful payloads.\n * @returns Decoded successful output.\n */\nexport async function decode_response_or_value<Output, ErrorType = never>(\n value: unknown,\n decode_payload: (value: unknown) => unknown,\n): Promise<Output> {\n if (value instanceof Response) {\n if (!value.ok) {\n throw await decode_response_failure<ErrorType>(value);\n }\n\n const data = await decode_success_response_body(value);\n\n return decode_payload(data) as Output;\n }\n\n return decode_payload(value) as Output;\n}\n\nasync function decode_success_response_body(\n response: Response,\n): Promise<unknown> {\n if (response.status === 204 || response.status === 205) {\n return undefined;\n }\n\n const text = await response.text();\n\n if (text.length === 0) {\n return undefined;\n }\n\n return JSON.parse(text);\n}\n","import type { RemoteFailure } from \"$/remote/shared.ts\";\nimport { Effect } from \"effect\";\n\nimport {\n is_decoded_remote_failure,\n normalize_native_error,\n} from \"./failures.ts\";\n\n/**\n * Wraps a promise-producing remote operation in an Effect with failure mapping.\n *\n * @example\n * ```ts\n * const program = make_effect_from_promise(() => native_remote(input));\n * ```\n *\n * @since 2.0.0\n * @param run - Promise-producing operation that invokes a native remote helper.\n * @returns Effect that maps thrown values into remote failures.\n */\nexport function make_effect_from_promise<Output, ErrorType = never>(\n run: () => Promise<Output>,\n): Effect.Effect<Output, RemoteFailure<ErrorType>> {\n return Effect.tryPromise({\n try: run,\n catch: (error: unknown) => {\n if (is_decoded_remote_failure(error)) {\n return error;\n }\n\n return normalize_native_error<ErrorType>(error);\n },\n }) as Effect.Effect<Output, RemoteFailure<ErrorType>>;\n}\n","export { copy_property_descriptors } from \"$/internal/descriptors.ts\";\nimport type { NativeMethod } from \"./types.ts\";\n\n/**\n * Checks whether a value has a callable method property.\n *\n * @since 2.0.0\n * @param value - Value to inspect.\n * @param key - Method key to look up.\n * @returns Whether the value has a function at `key`.\n */\nexport function has_method<K extends PropertyKey>(\n value: unknown,\n key: K,\n): value is Record<K, NativeMethod> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<PropertyKey, unknown>)[key] === \"function\"\n );\n}\n","import type { RemoteFailure } from \"$/remote/shared.ts\";\nimport type { Effect } from \"effect\";\n\nimport { decode_response_or_value } from \"./responses.ts\";\nimport { make_effect_from_promise } from \"./effect.ts\";\nimport { copy_property_descriptors, has_method } from \"./utils.ts\";\nimport type { NativeMethod, Pending } from \"./types.ts\";\n\ntype EffectRemoteCommandAdapter<Input, Output, ErrorType = never> =\n & ((\n input: undefined extends Input ? Input | void : Input,\n ) => Effect.Effect<Output, RemoteFailure<ErrorType>>)\n & {\n readonly pending: number;\n };\n\n/**\n * Creates a remote command adapter. The adapter preserves the native\n * pending getter and turns each invocation into an Effect.\n *\n * @since 2.0.0\n * @param native_factory - SvelteKit's native command function or a legacy\n * response factory used by tests.\n * @param decode_payload - Function to decode the response payload.\n * @param _base - Deprecated transport base retained for compatibility.\n * @param pending - Optional pending counter for legacy response factories.\n * @returns A function returning an Effect of the response.\n * @internal\n */\nexport function create_remote_command_adapter<\n Input,\n Output,\n ErrorType = never,\n>(\n native_factory: unknown,\n decode_payload: (value: unknown) => unknown,\n _base = \"\",\n pending?: Pending,\n): EffectRemoteCommandAdapter<Input, Output, ErrorType> {\n const invoke = has_method(native_factory, \"invoke\")\n ? native_factory.invoke\n : undefined;\n\n if (typeof native_factory !== \"function\" && !invoke) {\n throw new Error(\n \"[INVALID_COMMAND_FACTORY]: Invalid command factory: expected a function\",\n );\n }\n\n const count = pending ?? { value: 0 };\n\n const adapter = (input: undefined extends Input ? Input | void : Input) =>\n make_effect_from_promise<Output, ErrorType>(async () => {\n count.value += 1;\n\n try {\n const result = invoke\n ? await invoke(input)\n : await (native_factory as NativeMethod)(input);\n\n return await decode_response_or_value<Output, ErrorType>(\n result,\n decode_payload,\n );\n } finally {\n count.value -= 1;\n }\n });\n\n copy_property_descriptors(native_factory, adapter);\n\n if (!Object.prototype.hasOwnProperty.call(adapter, \"pending\")) {\n Object.defineProperty(adapter, \"pending\", {\n get: () => count.value,\n });\n }\n\n return adapter as EffectRemoteCommandAdapter<Input, Output, ErrorType>;\n}\n","/**\n * Encodes remote form input into SvelteKit-compatible form data.\n *\n * @since 2.0.0\n * @param input - Input value supplied to the remote form.\n * @returns FormData payload for the remote endpoint.\n */\nexport function to_form_data(input: unknown): FormData {\n const form_data = new FormData();\n\n append_form_value(form_data, \"\", input);\n\n return form_data;\n}\n\nfunction append_form_value(\n form_data: FormData,\n path: string,\n value: unknown,\n): void {\n if (value === undefined) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n append_form_value(form_data, `${path}[]`, item);\n }\n\n return;\n }\n\n if (value instanceof Blob) {\n form_data.append(path, value);\n\n return;\n }\n\n if (typeof value === \"object\" && value !== null) {\n for (const [key, child] of Object.entries(value)) {\n const child_path = path.length === 0 ? key : `${path}.${key}`;\n\n append_form_value(form_data, child_path, child);\n }\n\n return;\n }\n\n if (typeof value === \"number\") {\n form_data.append(`n:${path}`, String(value));\n\n return;\n }\n\n if (typeof value === \"boolean\") {\n if (value) {\n form_data.append(`b:${path}`, \"on\");\n }\n\n return;\n }\n\n form_data.append(path, value === null ? \"\" : String(value));\n}\n","import {\n create_remote_http_error,\n create_remote_transport_error,\n create_remote_validation_error,\n} from \"$/remote/shared.ts\";\nimport type { FormIssue } from \"$/remote/shared.ts\";\nimport { parse } from \"devalue\";\n\nimport { decode_remote_error, is_decoded_remote_failure } from \"./failures.ts\";\nimport { decode_response_failure } from \"./responses.ts\";\nimport { to_form_data } from \"./form-data.ts\";\nimport type { NativeFormRecord } from \"./types.ts\";\n\n/**\n * Submits a native remote form through the SvelteKit remote endpoint.\n *\n * @since 2.0.0\n * @param form_obj - Native form object being adapted.\n * @param input - Form input value.\n * @param decode_payload - Function to decode successful payloads.\n * @param remote_base - Base URL for the remote endpoint.\n * @returns Decoded form output.\n */\nexport async function submit_remote_form<Output>(\n form_obj: NativeFormRecord,\n input: unknown,\n decode_payload: (value: unknown) => unknown,\n remote_base: string,\n): Promise<Output> {\n const action_id = get_remote_action_id(form_obj);\n\n if (!action_id || remote_base.length === 0) {\n throw create_remote_transport_error(\n new Error(\n \"[REMOTE_FORM_ENDPOINT_MISSING]: Form has no submit method or remote endpoint\",\n ),\n );\n }\n\n const response = await fetch(to_remote_form_url(remote_base, action_id), {\n method: \"POST\",\n body: to_form_data(input),\n });\n\n if (!response.ok) {\n throw await decode_response_failure(response);\n }\n\n const envelope = await response.json();\n\n return decode_form_response<Output>(envelope, decode_payload);\n}\n\n/**\n * Extracts SvelteKit's remote action id from a native form action URL.\n *\n * @since 2.0.0\n * @param form_obj - Native form object being adapted.\n * @returns Remote action id when present.\n */\nexport function get_remote_action_id(\n form_obj: NativeFormRecord,\n): string | undefined {\n const action = form_obj.action;\n\n if (typeof action !== \"string\") {\n return undefined;\n }\n\n const fallback = \"http://localhost/\";\n const href = typeof location === \"undefined\" ? fallback : location.href;\n const url = new URL(action, href);\n\n return url.searchParams.get(\"/remote\") ??\n url.searchParams.get(\"remote\") ??\n undefined;\n}\n\nfunction to_remote_form_url(remote_base: string, action_id: string): string {\n const parts = action_id.split(\"/\");\n const head = parts.slice(0, 2).join(\"/\");\n const tail = parts.slice(2).join(\"/\");\n const normalized_base = remote_base.replace(/\\/$/, \"\");\n\n if (tail.length === 0) {\n return `${normalized_base}/${head}`;\n }\n\n return `${normalized_base}/${head}/${encodeURIComponent(tail)}`;\n}\n\nfunction decode_form_response<Output>(\n envelope: unknown,\n decode_payload: (value: unknown) => unknown,\n): Output {\n if (\n typeof envelope !== \"object\" ||\n envelope === null ||\n !(\"type\" in envelope)\n ) {\n throw create_remote_transport_error(\n new Error(\n \"[REMOTE_FORM_RESPONSE_INVALID]: Invalid remote form response\",\n ),\n envelope,\n );\n }\n\n const response = envelope as {\n data?: unknown;\n type: string;\n result?: unknown;\n error?: unknown;\n status?: number;\n };\n\n if (response.type === \"error\") {\n const decoded = decode_remote_error(response.error);\n\n if (is_decoded_remote_failure(decoded)) {\n throw decoded;\n }\n\n throw create_remote_http_error(\n response.status ?? 500,\n response.error,\n );\n }\n\n const result_text = typeof response.result === \"string\"\n ? response.result\n : typeof response.data === \"string\"\n ? response.data\n : undefined;\n\n if (response.type !== \"result\" || result_text === undefined) {\n throw create_remote_transport_error(\n new Error(\n \"[REMOTE_FORM_RESPONSE_UNSUPPORTED]: Unsupported remote form response\",\n ),\n envelope,\n );\n }\n\n const parsed = parse(result_text);\n const decoded = decode_payload(parsed) as {\n issues?: readonly FormIssue[];\n result?: Output;\n };\n\n if (decoded.issues && decoded.issues.length > 0) {\n throw create_remote_validation_error(decoded.issues, decoded, 400);\n }\n\n return decoded.result as Output;\n}\n","import { get_dispatcher } from \"$/dispatcher.ts\";\nimport { Effect } from \"effect\";\n\nimport { make_effect_from_promise } from \"./effect.ts\";\nimport { has_method } from \"./utils.ts\";\nimport type { EffectRemoteFormSubmit, NativeMethod } from \"./types.ts\";\n\n/**\n * Wraps a remote form enhance callback so Effect return values are run.\n *\n * @since 2.0.0\n * @param callback - Native enhance callback to wrap.\n * @returns Wrapped callback or undefined.\n */\nexport function wrap_enhance_callback<Output, ErrorType = never>(\n callback: NativeMethod | undefined,\n): NativeMethod | undefined {\n if (!callback) {\n return undefined;\n }\n\n return (event: unknown) => {\n const wrapped_event = wrap_submit_callback<Output, ErrorType>(event);\n const result = callback(wrapped_event);\n\n if (Effect.isEffect(result)) {\n return get_dispatcher().run(result);\n }\n\n return result;\n };\n}\n\nfunction wrap_submit_callback<Output, ErrorType>(event: unknown): unknown {\n if (\n typeof event !== \"object\" || event === null || !has_method(event, \"submit\")\n ) {\n return event;\n }\n\n const original_submit = event.submit;\n const { submit: _submit, ...descriptors } = Object.getOwnPropertyDescriptors(\n event,\n );\n\n void _submit;\n\n return Object.defineProperties({}, {\n ...descriptors,\n submit: {\n configurable: true,\n enumerable: false,\n value: () =>\n make_submit_effect<Output, ErrorType>(original_submit, event),\n },\n });\n}\n\nfunction make_submit_effect<Output, ErrorType>(\n original_submit: NativeMethod,\n event: unknown,\n): EffectRemoteFormSubmit<Output, ErrorType> {\n let updates_args: unknown[] | undefined;\n\n const effect = make_effect_from_promise<Output | undefined, ErrorType>(\n async (): Promise<Output | undefined> => {\n const result = original_submit();\n const value = updates_args && has_method(result, \"updates\")\n ? await Promise.resolve(result.updates(...updates_args))\n : await Promise.resolve(result);\n\n if (typeof value === \"boolean\") {\n return read_submit_result<Output>(event);\n }\n\n return value as Output;\n },\n ) as EffectRemoteFormSubmit<Output, ErrorType>;\n\n Object.defineProperty(effect, \"updates\", {\n configurable: true,\n enumerable: false,\n value: (...args: unknown[]) => {\n updates_args ??= args;\n\n return effect;\n },\n });\n\n return effect;\n}\n\nfunction read_submit_result<Output>(event: unknown): Output | undefined {\n if (typeof event !== \"object\" || event === null || !(\"result\" in event)) {\n return undefined;\n }\n\n return Reflect.get(event, \"result\") as Output | undefined;\n}\n","import type { RemoteFormInput } from \"@sveltejs/kit\";\n\nimport { decode_response_or_value } from \"./responses.ts\";\nimport { make_effect_from_promise } from \"./effect.ts\";\nimport { get_remote_action_id, submit_remote_form } from \"./form-transport.ts\";\nimport { copy_property_descriptors, has_method } from \"./utils.ts\";\nimport { wrap_enhance_callback } from \"./form-enhance.ts\";\nimport type {\n EffectRemoteForm,\n NativeFormRecord,\n NativeMethod,\n} from \"./types.ts\";\n\ntype RemoteInput<Input> = undefined extends Input ? Input | void : Input;\n\n/**\n * Creates a remote form adapter. The callable preserves SvelteKit's native\n * form descriptors while wrapping `validate`, `enhance`, and programmatic\n * submission in Effect-returning APIs.\n *\n * @example\n * ```ts\n * const createPost = create_remote_form_adapter(nativeForm, (value) => value);\n * yield* createPost.validate({ includeUntouched: true });\n * ```\n *\n * @since 2.0.0\n * @param native_factory - SvelteKit's native form object.\n * @param decode_payload - Function to decode the response payload.\n * @param remote_base - Base URL for SvelteKit's remote endpoint.\n * @returns A callable form function whose properties mirror the native form.\n * @internal\n */\nexport function create_remote_form_adapter<\n Input extends RemoteFormInput | void,\n Output,\n ErrorType = never,\n>(\n native_factory: unknown,\n decode_payload: (value: unknown) => unknown,\n remote_base = \"\",\n): EffectRemoteForm<Input, Output, ErrorType> {\n const form_obj = native_factory as NativeFormRecord;\n\n const submit_effect = (input?: RemoteInput<Input>) =>\n make_effect_from_promise<Output, ErrorType>(async () => {\n const can_use_remote_endpoint = remote_base.length > 0 &&\n get_remote_action_id(form_obj) !== undefined;\n\n if (has_method(form_obj, \"submit\") && !can_use_remote_endpoint) {\n const result = await form_obj.submit(input);\n\n return await decode_response_or_value<Output>(result, decode_payload);\n }\n\n return await submit_remote_form<Output>(\n form_obj,\n input,\n decode_payload,\n remote_base,\n );\n });\n\n const callable =\n ((input?: RemoteInput<Input>) => submit_effect(input)) as EffectRemoteForm<\n Input,\n Output,\n ErrorType\n >;\n\n copy_property_descriptors(\n form_obj,\n callable,\n new Set([\"submit\", \"validate\", \"enhance\", \"for\", \"preflight\"]),\n );\n\n Object.defineProperty(callable, \"submit\", {\n configurable: true,\n enumerable: false,\n value: submit_effect,\n });\n\n if (has_method(form_obj, \"validate\")) {\n Object.defineProperty(callable, \"validate\", {\n configurable: true,\n enumerable: false,\n value: (options?: Record<string, unknown>) =>\n make_effect_from_promise<void, ErrorType>(async () => {\n await form_obj.validate(options);\n }),\n });\n }\n\n if (has_method(form_obj, \"enhance\")) {\n Object.defineProperty(callable, \"enhance\", {\n configurable: true,\n enumerable: false,\n value: (callback?: NativeMethod) =>\n form_obj.enhance(\n wrap_enhance_callback<Output, ErrorType>(callback),\n ),\n });\n }\n\n if (has_method(form_obj, \"for\")) {\n Object.defineProperty(callable, \"for\", {\n configurable: true,\n enumerable: false,\n value: (key: string | number | boolean) =>\n create_remote_form_adapter<Input, Output, ErrorType>(\n form_obj.for(key),\n decode_payload,\n remote_base,\n ),\n });\n }\n\n if (has_method(form_obj, \"preflight\")) {\n Object.defineProperty(callable, \"preflight\", {\n configurable: true,\n enumerable: false,\n value: (schema: unknown) => {\n form_obj.preflight(schema);\n\n return callable;\n },\n });\n }\n\n return callable;\n}\n","import { decode_response_or_value } from \"./responses.ts\";\nimport { has_method } from \"./utils.ts\";\n\n/**\n * Resolves native query results, including SvelteKit run handles.\n *\n * @example\n * ```ts\n * const output = await resolve_query_result(result, decode_payload);\n * ```\n *\n * @since 2.0.0\n * @param value - Native query result or query run handle.\n * @param decode_payload - Function used to decode successful payloads.\n * @returns Decoded query output.\n */\nexport async function resolve_query_result<Output>(\n value: unknown,\n decode_payload: (value: unknown) => unknown,\n): Promise<Output> {\n if (has_method(value, \"then\")) {\n const result = await Promise.resolve(value);\n\n return decode_response_or_value(result, decode_payload);\n }\n\n if (has_method(value, \"run\")) {\n const result = await value.run();\n\n return decode_response_or_value(result, decode_payload);\n }\n\n const result = await Promise.resolve(value);\n\n return decode_response_or_value(result, decode_payload);\n}\n","import { copy_property_descriptors, has_method } from \"./utils.ts\";\nimport { normalize_native_error } from \"./failures.ts\";\nimport { resolve_query_result } from \"./query-result.ts\";\nimport { make_effect_from_promise } from \"./effect.ts\";\nimport type { EffectRemoteQueryUpdateBrand, NativeMethod } from \"./types.ts\";\nimport type { RemoteFailure } from \"$/remote/shared.ts\";\nimport { Effect } from \"effect\";\n\ntype RemoteInput<Input> = undefined extends Input ? Input | void : Input;\n\ntype DecodePayload<Output> = (value: unknown) => Output;\n\ntype NativeQueryFactory<Input> =\n | ((input: RemoteInput<Input>) => unknown)\n | {\n readonly load: (input: RemoteInput<Input>) => unknown;\n };\n\ntype RemoteResourceEffect<Output, ErrorType = never> =\n & Effect.Effect<Output, RemoteFailure<ErrorType>>\n & {\n readonly current: Output | undefined;\n readonly error: unknown;\n readonly loading: boolean;\n readonly ready: boolean;\n };\n\ntype RemoteResourceLike<Output, ErrorType = never> =\n | RemoteResourceEffect<Output, ErrorType>\n | RemoteLiveQueryResource<Output>;\n\ntype RemoteQueryEffect<Output, ErrorType = never> =\n & RemoteResourceEffect<Output, ErrorType>\n & {\n readonly refresh: () => Effect.Effect<void, unknown, never>;\n readonly set: (value: Output) => void;\n readonly withOverride: (\n update: (current: Output) => Output,\n ) => unknown;\n };\n\ntype RemoteLiveQueryEffect<Output, ErrorType = never> = Effect.Effect<\n RemoteLiveQueryResource<Output>,\n RemoteFailure<ErrorType>\n>;\n\ntype RemoteLiveQueryResource<Output> =\n & {\n readonly connected: boolean;\n readonly current: Output | undefined;\n readonly done: boolean;\n readonly error: unknown;\n readonly loading: boolean;\n readonly ready: boolean;\n readonly reconnect: () => Effect.Effect<void, unknown, never>;\n }\n & AsyncIterable<Output>;\n\ntype NativeRemoteResource<Output> = {\n readonly connected?: boolean;\n readonly current?: Output;\n readonly done?: boolean;\n readonly error?: unknown;\n readonly loading?: boolean;\n readonly ready?: boolean;\n readonly reconnect?: () => Promise<void>;\n readonly refresh?: () => Promise<void>;\n readonly set?: (value: Output) => void;\n readonly withOverride?: (update: (current: Output) => Output) => unknown;\n readonly [Symbol.asyncIterator]?: () => AsyncIterator<Output>;\n};\n\n/**\n * Creates a remote query adapter. The returned function takes input and\n * returns an `Effect` that executes SvelteKit's native query function.\n *\n * @example\n * ```ts\n * const getUser = create_remote_query_adapter(nativeQuery, (value) => value);\n * const user = yield* getUser({ id: 1 });\n * ```\n *\n * @since 2.0.0\n * @param native_factory - SvelteKit's native query function or a legacy\n * response factory used by tests.\n * @param decode_payload - Function to decode the response payload.\n * @param _base - Deprecated transport base retained for compatibility.\n * @returns A function returning an Effect of the response.\n * @internal\n */\nexport function create_remote_query_adapter<\n Input,\n Output,\n ErrorType = never,\n>(\n native_factory: NativeQueryFactory<Input>,\n decode_payload: DecodePayload<Output>,\n _base?: string,\n):\n & EffectRemoteQueryUpdateBrand\n & ((input: RemoteInput<Input>) => RemoteQueryEffect<Output, ErrorType>);\nexport function create_remote_query_adapter<\n Input,\n Output,\n ErrorType = never,\n>(\n native_factory: NativeQueryFactory<Input>,\n decode_payload: (value: unknown) => unknown,\n _base?: string,\n):\n & EffectRemoteQueryUpdateBrand\n & ((input: RemoteInput<Input>) => RemoteQueryEffect<Output, ErrorType>);\nexport function create_remote_query_adapter<\n Input,\n Output,\n ErrorType = never,\n>(\n native_factory: unknown,\n decode_payload: DecodePayload<Output>,\n _base = \"\",\n):\n & EffectRemoteQueryUpdateBrand\n & ((input: RemoteInput<Input>) => RemoteQueryEffect<Output, ErrorType>) {\n const load = has_method(native_factory, \"load\")\n ? native_factory.load\n : undefined;\n const query = typeof native_factory === \"function\"\n ? native_factory as NativeMethod\n : undefined;\n\n if (!query && !load) {\n throw new Error(\n \"[INVALID_QUERY_FACTORY]: Invalid query factory: expected a function\",\n );\n }\n\n const wrapped = ((input: RemoteInput<Input>) => {\n if (!query) {\n return make_effect_from_promise<Output, ErrorType>(async () => {\n const result = await load?.(input);\n\n return await resolve_query_result<Output>(result, decode_payload);\n }) as RemoteQueryEffect<Output, ErrorType>;\n }\n\n const resource = query(input);\n const effect = make_effect_from_promise<Output, ErrorType>(async () =>\n await resolve_query_result<Output>(resource, decode_payload)\n ) as RemoteQueryEffect<Output, ErrorType>;\n\n attach_query_resource(resource, effect);\n\n return effect;\n }) as\n & EffectRemoteQueryUpdateBrand\n & ((input: RemoteInput<Input>) => RemoteQueryEffect<Output, ErrorType>);\n\n copy_property_descriptors(native_factory, wrapped);\n\n return wrapped;\n}\n\n/**\n * Creates a remote live query adapter. The returned function takes input and\n * returns an `Effect` that resolves to a live query resource with stream state\n * and reconnect controls.\n *\n * @example\n * ```ts\n * const getTime = create_remote_live_query_adapter(nativeLive, (value) => value);\n * const time = yield* getTime();\n * const current = time.current;\n * ```\n *\n * @since 2.0.0\n * @param native_factory - SvelteKit's native live query function.\n * @param _decode_payload - Deprecated payload decoder retained for parity with\n * other remote adapters.\n * @param _base - Deprecated transport base retained for compatibility.\n * @returns A function returning an Effect-backed live query resource.\n * @internal\n */\nexport function create_remote_live_query_adapter<\n Input,\n Output,\n ErrorType = never,\n>(\n native_factory: unknown,\n _decode_payload: (value: unknown) => unknown,\n _base = \"\",\n):\n & EffectRemoteQueryUpdateBrand\n & ((input: RemoteInput<Input>) => RemoteLiveQueryEffect<Output, ErrorType>) {\n const query = typeof native_factory === \"function\"\n ? native_factory as NativeMethod\n : undefined;\n\n if (!query) {\n throw new Error(\n \"[INVALID_LIVE_QUERY_FACTORY]: Invalid live query factory: expected a function\",\n );\n }\n\n const wrapped = ((input: Input) =>\n Effect.try({\n try: () => {\n const resource = query(input);\n\n return make_live_query_resource<Output>(resource);\n },\n catch: normalize_native_error,\n }) as RemoteLiveQueryEffect<Output>) as\n & EffectRemoteQueryUpdateBrand\n & ((\n input: RemoteInput<Input>,\n ) => RemoteLiveQueryEffect<Output, ErrorType>);\n\n copy_property_descriptors(native_factory, wrapped);\n\n return wrapped;\n}\n\nfunction is_resource<Output>(\n resource: unknown,\n): resource is NativeRemoteResource<Output> {\n const resource_type = typeof resource;\n\n return (\n (resource_type === \"object\" && resource !== null) ||\n resource_type === \"function\"\n );\n}\n\nfunction attach_resource_getters<Output, ErrorType = never>(\n resource: unknown,\n effect: RemoteResourceLike<Output, ErrorType>,\n): void {\n const methods = is_resource<Output>(resource) ? resource : undefined;\n const keys = [\"current\", \"error\", \"loading\", \"ready\"] as const;\n\n if (!methods) {\n return;\n }\n\n for (const key of keys) {\n if (!(key in methods)) {\n continue;\n }\n\n Object.defineProperty(effect, key, {\n configurable: true,\n get: () => methods[key],\n });\n }\n}\n\nfunction attach_query_resource<Output, ErrorType = never>(\n resource: unknown,\n effect: RemoteQueryEffect<Output, ErrorType>,\n): void {\n const methods = is_resource<Output>(resource) ? resource : undefined;\n const refresh = methods?.refresh;\n const set = methods?.set;\n const with_override = methods?.withOverride;\n\n attach_resource_getters(resource, effect);\n\n if (!methods) {\n return;\n }\n\n if (typeof refresh === \"function\") {\n Object.defineProperty(effect, \"refresh\", {\n configurable: true,\n value: () =>\n make_effect_from_promise(() => Promise.resolve(refresh.call(resource))),\n });\n }\n\n if (typeof set === \"function\") {\n Object.defineProperty(effect, \"set\", {\n configurable: true,\n value: (value: Output) => set.call(resource, value),\n });\n }\n\n if (typeof with_override === \"function\") {\n Object.defineProperty(effect, \"withOverride\", {\n configurable: true,\n value: (update: (current: Output) => Output) =>\n with_override.call(resource, update),\n });\n }\n}\n\nfunction attach_live_query_resource<Output>(\n resource: unknown,\n effect: RemoteLiveQueryResource<Output>,\n): void {\n const methods = is_resource<Output>(resource) ? resource : undefined;\n const async_iterator = methods?.[Symbol.asyncIterator];\n const reconnect = methods?.reconnect;\n const keys = [\"connected\", \"done\"] as const;\n\n attach_resource_getters(resource, effect);\n\n if (!methods) {\n return;\n }\n\n for (const key of keys) {\n if (!(key in methods)) {\n continue;\n }\n\n Object.defineProperty(effect, key, {\n configurable: true,\n get: () => methods[key],\n });\n }\n\n if (typeof reconnect === \"function\") {\n Object.defineProperty(effect, \"reconnect\", {\n configurable: true,\n value: () =>\n make_effect_from_promise(() =>\n Promise.resolve(reconnect.call(resource))\n ),\n });\n }\n\n if (typeof async_iterator === \"function\") {\n Object.defineProperty(effect, Symbol.asyncIterator, {\n configurable: true,\n value: () => async_iterator.call(resource),\n });\n }\n}\n\nfunction make_live_query_resource<Output>(\n resource: unknown,\n): RemoteLiveQueryResource<Output> {\n const live_resource = {} as RemoteLiveQueryResource<Output>;\n\n attach_live_query_resource(resource, live_resource);\n\n return live_resource;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,oBACd,KACA,QACoC;CACpC,MAAM,WAAW,8BAA8B,GAAG;CAElD,IAAI,aAAa,KACf,OAAO,oBAA+B,UAAU,MAAM;CAGxD,IAAI,sCAAsC,GAAG,GAC3C,IAAI;EAGF,OAFgB,SAAS,OAAO,IAAI,OAAO,IAAI,MAAM,IAAI,OAAO;CAGlE,QAAQ;EACN,OAAO,8CACL,IAAI,MACF,qE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EACd,QAAQ,WACN,cAAc,KAAK,UAAU,MAAM;CACvC,CAAC;AAEL;AAEA,SAAS,2BACP,UACA,QACM;CACN,MAAM,UAAU,YAAoB,QAAQ,IAAI,WAAW,KAAA;CAC3D,MAAM,iBAAiB,UAAU,OAAO;CACxC,MAAM,YAAY,SAAS;CAC3B,MAAM,OAAO,CAAC,aAAa,MAAM;CAEjC,wBAAwB,UAAU,MAAM;CAExC,IAAI,CAAC,SACH;CAGF,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,EAAE,OAAO,UACX;EAGF,OAAO,eAAe,QAAQ,KAAK;GACjC,cAAc;GACd,WAAW,QAAQ;EACrB,CAAC;CACH;CAEA,IAAI,OAAO,cAAc,YACvB,OAAO,eAAe,QAAQ,aAAa;EACzC,cAAc;EACd,aACE,+BACE,QAAQ,QAAQ,UAAU,KAAK,QAAQ,CAAC,CAC1C;CACJ,CAAC;CAGH,IAAI,OAAO,mBAAmB,YAC5B,OAAO,eAAe,QAAQ,OAAO,eAAe;EAClD,cAAc;EACd,aAAa,eAAe,KAAK,QAAQ;CAC3C,CAAC;AAEL;AAEA,SAAS,yBACP,UACiC;CACjC,MAAM,gBAAgB,CAAC;CAEvB,2BAA2B,UAAU,aAAa;CAElD,OAAO;AACT"}
|
|
@@ -251,7 +251,12 @@ var Dispatcher = class Dispatcher {
|
|
|
251
251
|
*/
|
|
252
252
|
run(effect) {
|
|
253
253
|
if (this.#disposed) return Promise.reject(/* @__PURE__ */ new Error("[DISPATCHER_DISPOSED]: Dispatcher has been disposed"));
|
|
254
|
-
|
|
254
|
+
const exit_effect = Effect.exit(effect);
|
|
255
|
+
return this.#runtime.runPromise(exit_effect).then((exit) => {
|
|
256
|
+
const result = exit;
|
|
257
|
+
if (Exit.isSuccess(result)) return result.value;
|
|
258
|
+
if (Cause.hasInterruptsOnly(result.cause)) return;
|
|
259
|
+
const error = Cause.squash(result.cause);
|
|
255
260
|
queueMicrotask(() => {
|
|
256
261
|
throw error;
|
|
257
262
|
});
|
|
@@ -276,6 +281,11 @@ var Dispatcher = class Dispatcher {
|
|
|
276
281
|
this.#values.clear();
|
|
277
282
|
this.#value_ids.clear();
|
|
278
283
|
this.#promise_ids.clear();
|
|
284
|
+
this.#runtime.dispose().catch((error) => {
|
|
285
|
+
queueMicrotask(() => {
|
|
286
|
+
throw error;
|
|
287
|
+
});
|
|
288
|
+
});
|
|
279
289
|
}
|
|
280
290
|
#make_value_cache_key(id, deps) {
|
|
281
291
|
return `value:${id}::${hash_deps(deps)}`;
|
|
@@ -356,4 +366,4 @@ function reset_dispatcher() {
|
|
|
356
366
|
//#endregion
|
|
357
367
|
export { get_dispatcher as n, reset_dispatcher as r, Dispatcher as t };
|
|
358
368
|
|
|
359
|
-
//# sourceMappingURL=dispatcher-
|
|
369
|
+
//# sourceMappingURL=dispatcher-CgCdn6bj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatcher-BVkm8qbG.js","names":["#runtime","#disposed","#next_fiber_id","#fibers","#make_value_cache_key","#value_ids","#interrupt_cached_fiber","#should_start_value_fiber","#start_value_fiber","#values","#make_promise_cache_key","#promise_ids","#start_promise_fiber"],"sources":["../../../modules/svelte-effect-runtime/src/dispatcher/fibers.ts","../../../modules/svelte-effect-runtime/src/dispatcher/deps.ts","../../../modules/svelte-effect-runtime/src/dispatcher/index.ts"],"sourcesContent":["import { Cause, Effect, Exit, Fiber } from \"effect\";\nimport type { Fiber as FiberType } from \"effect/Fiber\";\nimport type { ManagedRuntime as ManagedRuntimeType } from \"effect/ManagedRuntime\";\n\n/**\n * Callbacks fired when a watched dispatcher fiber completes.\n *\n * @example\n * ```ts\n * const callbacks: FiberWatchCallbacks<number> = {\n * on_success: (value) => cache.set(key, value),\n * };\n * ```\n *\n * @since 2.0.0\n * @internal\n */\nexport interface FiberWatchCallbacks<A> {\n on_complete?: () => void;\n on_success?: (value: A) => void;\n}\n\n/**\n * Interrupts a dispatcher fiber through its managed runtime.\n *\n * @example\n * ```ts\n * interrupt_fiber(runtime, fiber);\n * ```\n *\n * @since 2.0.0\n * @param runtime - Managed runtime that owns the fiber.\n * @param fiber - Fiber to interrupt.\n * @returns Nothing.\n * @internal\n */\nexport function interrupt_fiber(\n runtime: ManagedRuntimeType<unknown, unknown>,\n fiber: FiberType<unknown, unknown>,\n): void {\n runtime.runFork(\n Fiber.interrupt(fiber) as Effect.Effect<unknown, unknown, unknown>,\n );\n}\n\n/**\n * Watches a dispatcher fiber, runs completion callbacks, and surfaces\n * non-interrupt failures on the microtask queue.\n *\n * @example\n * ```ts\n * watch_fiber_exit({ runtime, fiber, on_complete: cleanup });\n * ```\n *\n * @since 2.0.0\n * @param options - Runtime, fiber, and callbacks used for the watcher.\n * @returns Nothing.\n * @internal\n */\nexport function watch_fiber_exit<A>(\n options: {\n runtime: ManagedRuntimeType<unknown, unknown>;\n fiber: FiberType<unknown, unknown>;\n } & FiberWatchCallbacks<A>,\n): void {\n const { runtime, fiber, on_complete, on_success } = options;\n\n runtime.runFork(\n Effect.flatMap(Fiber.await(fiber), (exit) =>\n Effect.sync(() => {\n on_complete?.();\n\n if (Exit.isSuccess(exit)) {\n on_success?.(exit.value as A);\n\n return;\n }\n\n if (!Cause.hasInterruptsOnly(exit.cause)) {\n queueMicrotask(() => {\n throw Cause.squash(exit.cause);\n });\n }\n })),\n );\n}\n","const object_dep_ids = new WeakMap<object, number>();\nconst symbol_dep_ids = new Map<symbol, number>();\n\nlet next_object_dep_id = 0;\nlet next_symbol_dep_id = 0;\n\n/**\n * Builds a deterministic cache key from a dependency array.\n *\n * @example\n * ```ts\n * const key = hash_deps([user_id, filters]);\n * ```\n *\n * @since 2.0.0\n * @param deps - Dependency array to encode for cache lookup.\n * @returns A structured string key suitable for Map lookups.\n * @internal\n */\nexport function hash_deps(deps: readonly unknown[]): string {\n const parts = deps.map((dep) => {\n if (dep === null) {\n return \"l:null\";\n }\n\n if (dep === undefined) {\n return \"u:undefined\";\n }\n\n const type = typeof dep;\n\n if (type === \"string\") {\n return [\"s\", dep];\n }\n\n if (type === \"number\") {\n return `n:${Object.is(dep, -0) ? \"-0\" : String(dep)}`;\n }\n\n if (type === \"bigint\") {\n return `b:${dep}`;\n }\n\n if (type === \"boolean\") {\n return dep ? \"t:true\" : \"f:false\";\n }\n\n if (type === \"symbol\") {\n return hash_symbol_dep(dep as symbol);\n }\n\n return hash_object_dep(dep as object);\n });\n\n return JSON.stringify(parts);\n}\n\nfunction hash_symbol_dep(dep: symbol): string {\n let id = symbol_dep_ids.get(dep);\n\n if (id === undefined) {\n next_symbol_dep_id += 1;\n id = next_symbol_dep_id;\n symbol_dep_ids.set(dep, id);\n }\n\n return `y:${id}`;\n}\n\nfunction hash_object_dep(dep: object): string {\n let id = object_dep_ids.get(dep);\n\n if (id === undefined) {\n next_object_dep_id += 1;\n id = next_object_dep_id;\n object_dep_ids.set(dep, id);\n }\n\n return `o:${id}`;\n}\n","import { Cause, Effect, Exit, Fiber, Layer, ManagedRuntime } from \"effect\";\nimport type { Fiber as FiberType } from \"effect/Fiber\";\nimport type { ManagedRuntime as ManagedRuntimeType } from \"effect/ManagedRuntime\";\n\nimport { interrupt_fiber, watch_fiber_exit } from \"./fibers.ts\";\nimport { hash_deps } from \"./deps.ts\";\nimport type { Dispose, PromiseOptions, ValueOptions } from \"./types.ts\";\n\nexport type { Dispose, PromiseOptions, ValueOptions } from \"./types.ts\";\n\n/**\n * Unified effect block dispatcher. Manages the fiber lifecycle of every\n * effect block and wires results into reactive channels.\n *\n * @example\n * ```ts\n * const dispatcher = new Dispatcher();\n * const cancel = dispatcher.fork(Effect.log(\"running\"));\n * cancel();\n * ```\n *\n * @since 2.0.0\n * @internal\n */\nexport class Dispatcher {\n /** The underlying Effect runtime that executes forked programs. */\n #runtime: ManagedRuntimeType<unknown, unknown>;\n /** Active fibers keyed by cache id or generated fork id. */\n #fibers = new Map<string, FiberType<unknown, unknown>>();\n /** Resolved values and pending promises keyed by cache id. */\n #values = new Map<string, unknown>();\n /** Current cache key per value block id. */\n #value_ids = new Map<string, string>();\n /** Current cache key per promise block id. */\n #promise_ids = new Map<string, string>();\n /** Whether dispose has been called, blocking new work. */\n #disposed = false;\n /** Monotonically increasing counter for unnamed fiber keys. */\n #next_fiber_id = 0;\n\n /**\n * Creates a dispatcher with an optional layer and installs it as the global\n * singleton returned by {@link get_dispatcher}.\n *\n * @example\n * ```ts\n * const dispatcher = Dispatcher.make(Db.Live);\n * ```\n *\n * @since 2.0.0\n * @param layer - Optional Effect layer to provide to the runtime.\n * @returns The newly created dispatcher.\n */\n static make<R = never>(\n layer?: Layer.Layer<R>,\n ): Dispatcher {\n const runtime = ManagedRuntime.make(\n layer ?? (Layer.empty as unknown as Layer.Layer<R>),\n );\n\n const dispatcher = new Dispatcher(\n runtime as ManagedRuntimeType<unknown, unknown>,\n );\n current_dispatcher = dispatcher;\n\n return dispatcher;\n }\n\n /**\n * Creates a dispatcher backed by the provided managed runtime.\n *\n * @example\n * ```ts\n * const dispatcher = new Dispatcher(runtime);\n * ```\n *\n * @since 2.0.0\n * @param runtime - Managed runtime to use, or an empty-layer runtime when\n * omitted.\n */\n constructor(runtime?: ManagedRuntimeType<unknown, unknown>) {\n this.#runtime = runtime ??\n ManagedRuntime.make(Layer.empty) as unknown as ManagedRuntimeType<\n unknown,\n unknown\n >;\n }\n\n /**\n * Forks an effect as a managed fiber and returns a cleanup function.\n *\n * @example\n * ```ts\n * const dispose = dispatcher.fork(Effect.log(\"clicked\"));\n * ```\n *\n * @since 2.0.0\n * @param effect - Effect to fork.\n * @returns A function that interrupts the fiber.\n */\n fork<A, E, R>(effect: Effect.Effect<A, E, R>): Dispose {\n if (this.#disposed) {\n return () => {};\n }\n\n const fiber = this.#runtime.runFork(\n effect as Effect.Effect<unknown, unknown, unknown>,\n );\n const key = `fork:${this.#next_fiber_id}`;\n\n this.#next_fiber_id += 1;\n this.#fibers.set(key, fiber);\n watch_fiber_exit({\n runtime: this.#runtime,\n fiber,\n on_complete: () => this.#fibers.delete(key),\n });\n\n let disposed = false;\n\n return (): void => {\n if (disposed) {\n return;\n }\n\n disposed = true;\n interrupt_fiber(this.#runtime, fiber);\n };\n }\n\n /**\n * Forks an effect and exposes its result as a cached reactive value.\n *\n * @example\n * ```ts\n * const user = dispatcher.value({ id, deps, fallback, factory });\n * ```\n *\n * @since 2.0.0\n * @param options - Value id, dependency array, fallback, and effect factory.\n * @returns The cached value if resolved, otherwise the fallback.\n */\n value<A>(options: ValueOptions<A>): A {\n const cache_key = this.#make_value_cache_key(options.id, options.deps);\n const old_key = this.#value_ids.get(options.id);\n\n if (old_key !== undefined && old_key !== cache_key) {\n this.#interrupt_cached_fiber(old_key);\n }\n\n this.#value_ids.set(options.id, cache_key);\n\n if (this.#should_start_value_fiber(cache_key)) {\n this.#start_value_fiber(cache_key, options);\n }\n\n if (this.#values.has(cache_key)) {\n return this.#values.get(cache_key) as A;\n }\n\n return options.fallback;\n }\n\n /**\n * Forks an effect and exposes its completion as a cached promise.\n *\n * @example\n * ```ts\n * const promise = dispatcher.promise({ id, deps, factory });\n * ```\n *\n * @since 2.0.0\n * @param options - Promise id, dependency array, and effect factory.\n * @returns A promise that resolves with the effect result.\n */\n promise<A>(options: PromiseOptions<A>): Promise<A> {\n if (this.#disposed) {\n return Promise.reject(\n new Error(\"[DISPATCHER_DISPOSED]: Dispatcher has been disposed\"),\n );\n }\n\n const cache_key = this.#make_promise_cache_key(options.id, options.deps);\n const old_key = this.#promise_ids.get(options.id);\n\n if (old_key !== undefined && old_key !== cache_key) {\n this.#interrupt_cached_fiber(old_key);\n this.#values.delete(old_key);\n }\n\n this.#promise_ids.set(options.id, cache_key);\n\n const existing = this.#values.get(cache_key);\n\n if (existing instanceof Promise) {\n return existing as Promise<A>;\n }\n\n const promise = this.#start_promise_fiber(cache_key, options);\n\n this.#values.set(cache_key, promise);\n\n return promise;\n }\n\n /**\n * Runs an event-handler effect and surfaces failures to Svelte.\n *\n * @example\n * ```ts\n * await dispatcher.run(Effect.log(\"submit\"));\n * ```\n *\n * @since 2.0.0\n * @param effect - Effect to execute.\n * @returns A promise that resolves or rejects when the effect completes.\n */\n run<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A> {\n if (this.#disposed) {\n return Promise.reject(\n new Error(\"[DISPATCHER_DISPOSED]: Dispatcher has been disposed\"),\n );\n }\n\n return this.#runtime\n .runPromise(effect as Effect.Effect<unknown, unknown, unknown>)\n .catch((error: unknown) => {\n queueMicrotask(() => {\n throw error;\n });\n\n throw error;\n }) as Promise<A>;\n }\n\n /**\n * Cancels all running fibers and releases cached values.\n *\n * @example\n * ```ts\n * dispatcher.dispose();\n * ```\n *\n * @since 2.0.0\n * @returns Nothing.\n */\n dispose(): void {\n this.#disposed = true;\n\n for (const fiber of this.#fibers.values()) {\n interrupt_fiber(this.#runtime, fiber);\n }\n\n this.#fibers.clear();\n this.#values.clear();\n this.#value_ids.clear();\n this.#promise_ids.clear();\n }\n\n #make_value_cache_key(id: string, deps: readonly unknown[]): string {\n return `value:${id}::${hash_deps(deps)}`;\n }\n\n #make_promise_cache_key(id: string, deps: readonly unknown[]): string {\n return `promise:${id}::${hash_deps(deps)}`;\n }\n\n #interrupt_cached_fiber(cache_key: string): void {\n const old_fiber = this.#fibers.get(cache_key);\n\n if (!old_fiber) {\n return;\n }\n\n interrupt_fiber(this.#runtime, old_fiber);\n this.#fibers.delete(cache_key);\n }\n\n #should_start_value_fiber(cache_key: string): boolean {\n return (\n !this.#disposed &&\n !this.#fibers.has(cache_key) &&\n !this.#values.has(cache_key)\n );\n }\n\n #start_value_fiber<A>(cache_key: string, options: ValueOptions<A>): void {\n const program = Effect.gen(function* () {\n const result = yield* Effect.gen(options.factory);\n\n return result;\n });\n const fiber = this.#runtime.runFork(\n program as Effect.Effect<unknown, unknown, unknown>,\n );\n\n this.#fibers.set(cache_key, fiber);\n watch_fiber_exit({\n runtime: this.#runtime,\n fiber,\n on_complete: () => this.#fibers.delete(cache_key),\n on_success: (value) => this.#values.set(cache_key, value),\n });\n }\n\n #start_promise_fiber<A>(\n cache_key: string,\n options: PromiseOptions<A>,\n ): Promise<A> {\n const program = Effect.gen(function* () {\n const result = yield* Effect.gen(options.factory);\n\n return result;\n });\n const fiber = this.#runtime.runFork(\n program as Effect.Effect<unknown, unknown, unknown>,\n );\n\n this.#fibers.set(cache_key, fiber);\n\n return this.#runtime.runPromise(\n Effect.flatMap(Fiber.await(fiber), (exit) =>\n Effect.sync(() => {\n this.#fibers.delete(cache_key);\n this.#values.delete(cache_key);\n\n if (this.#promise_ids.get(options.id) === cache_key) {\n this.#promise_ids.delete(options.id);\n }\n\n if (Exit.isSuccess(exit)) {\n return exit.value as A;\n }\n\n throw Cause.squash(exit.cause);\n })),\n );\n }\n}\n\nlet current_dispatcher: Dispatcher | null = null;\n\n/**\n * Resolves the active dispatcher, creating a default one if necessary.\n *\n * @example\n * ```ts\n * const dispatcher = get_dispatcher();\n * ```\n *\n * @since 2.0.0\n * @returns The active dispatcher singleton.\n * @internal\n */\nexport function get_dispatcher(): Dispatcher {\n current_dispatcher ??= new Dispatcher();\n\n return current_dispatcher;\n}\n\n/**\n * Resets the internal singleton dispatcher used by source-level tests.\n *\n * @example\n * ```ts\n * reset_dispatcher();\n * ```\n *\n * @since 2.0.0\n * @returns Nothing.\n * @internal\n */\nexport function reset_dispatcher(): void {\n current_dispatcher?.dispose();\n current_dispatcher = null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,SAAgB,gBACd,SACA,OACM;CACN,QAAQ,QACN,MAAM,UAAU,KAAK,CACvB;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,iBACd,SAIM;CACN,MAAM,EAAE,SAAS,OAAO,aAAa,eAAe;CAEpD,QAAQ,QACN,OAAO,QAAQ,MAAM,MAAM,KAAK,IAAI,SAClC,OAAO,WAAW;EAChB,cAAc;EAEd,IAAI,KAAK,UAAU,IAAI,GAAG;GACxB,aAAa,KAAK,KAAU;GAE5B;EACF;EAEA,IAAI,CAAC,MAAM,kBAAkB,KAAK,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dn6bj.js","names":["#runtime","#disposed","#next_fiber_id","#fibers","#make_value_cache_key","#value_ids","#interrupt_cached_fiber","#should_start_value_fiber","#start_value_fiber","#values","#make_promise_cache_key","#promise_ids","#start_promise_fiber"],"sources":["../../../modules/svelte-effect-runtime/src/dispatcher/fibers.ts","../../../modules/svelte-effect-runtime/src/dispatcher/deps.ts","../../../modules/svelte-effect-runtime/src/dispatcher/index.ts"],"sourcesContent":["import { Cause, Effect, Exit, Fiber } from \"effect\";\nimport type { Fiber as FiberType } from \"effect/Fiber\";\nimport type { ManagedRuntime as ManagedRuntimeType } from \"effect/ManagedRuntime\";\n\n/**\n * Callbacks fired when a watched dispatcher fiber completes.\n *\n * @example\n * ```ts\n * const callbacks: FiberWatchCallbacks<number> = {\n * on_success: (value) => cache.set(key, value),\n * };\n * ```\n *\n * @since 2.0.0\n * @internal\n */\nexport interface FiberWatchCallbacks<A> {\n on_complete?: () => void;\n on_success?: (value: A) => void;\n}\n\n/**\n * Interrupts a dispatcher fiber through its managed runtime.\n *\n * @example\n * ```ts\n * interrupt_fiber(runtime, fiber);\n * ```\n *\n * @since 2.0.0\n * @param runtime - Managed runtime that owns the fiber.\n * @param fiber - Fiber to interrupt.\n * @returns Nothing.\n * @internal\n */\nexport function interrupt_fiber(\n runtime: ManagedRuntimeType<unknown, unknown>,\n fiber: FiberType<unknown, unknown>,\n): void {\n runtime.runFork(\n Fiber.interrupt(fiber) as Effect.Effect<unknown, unknown, unknown>,\n );\n}\n\n/**\n * Watches a dispatcher fiber, runs completion callbacks, and surfaces\n * non-interrupt failures on the microtask queue.\n *\n * @example\n * ```ts\n * watch_fiber_exit({ runtime, fiber, on_complete: cleanup });\n * ```\n *\n * @since 2.0.0\n * @param options - Runtime, fiber, and callbacks used for the watcher.\n * @returns Nothing.\n * @internal\n */\nexport function watch_fiber_exit<A>(\n options: {\n runtime: ManagedRuntimeType<unknown, unknown>;\n fiber: FiberType<unknown, unknown>;\n } & FiberWatchCallbacks<A>,\n): void {\n const { runtime, fiber, on_complete, on_success } = options;\n\n runtime.runFork(\n Effect.flatMap(Fiber.await(fiber), (exit) =>\n Effect.sync(() => {\n on_complete?.();\n\n if (Exit.isSuccess(exit)) {\n on_success?.(exit.value as A);\n\n return;\n }\n\n if (!Cause.hasInterruptsOnly(exit.cause)) {\n queueMicrotask(() => {\n throw Cause.squash(exit.cause);\n });\n }\n })),\n );\n}\n","const object_dep_ids = new WeakMap<object, number>();\nconst symbol_dep_ids = new Map<symbol, number>();\n\nlet next_object_dep_id = 0;\nlet next_symbol_dep_id = 0;\n\n/**\n * Builds a deterministic cache key from a dependency array.\n *\n * @example\n * ```ts\n * const key = hash_deps([user_id, filters]);\n * ```\n *\n * @since 2.0.0\n * @param deps - Dependency array to encode for cache lookup.\n * @returns A structured string key suitable for Map lookups.\n * @internal\n */\nexport function hash_deps(deps: readonly unknown[]): string {\n const parts = deps.map((dep) => {\n if (dep === null) {\n return \"l:null\";\n }\n\n if (dep === undefined) {\n return \"u:undefined\";\n }\n\n const type = typeof dep;\n\n if (type === \"string\") {\n return [\"s\", dep];\n }\n\n if (type === \"number\") {\n return `n:${Object.is(dep, -0) ? \"-0\" : String(dep)}`;\n }\n\n if (type === \"bigint\") {\n return `b:${dep}`;\n }\n\n if (type === \"boolean\") {\n return dep ? \"t:true\" : \"f:false\";\n }\n\n if (type === \"symbol\") {\n return hash_symbol_dep(dep as symbol);\n }\n\n return hash_object_dep(dep as object);\n });\n\n return JSON.stringify(parts);\n}\n\nfunction hash_symbol_dep(dep: symbol): string {\n let id = symbol_dep_ids.get(dep);\n\n if (id === undefined) {\n next_symbol_dep_id += 1;\n id = next_symbol_dep_id;\n symbol_dep_ids.set(dep, id);\n }\n\n return `y:${id}`;\n}\n\nfunction hash_object_dep(dep: object): string {\n let id = object_dep_ids.get(dep);\n\n if (id === undefined) {\n next_object_dep_id += 1;\n id = next_object_dep_id;\n object_dep_ids.set(dep, id);\n }\n\n return `o:${id}`;\n}\n","import { Cause, Effect, Exit, Fiber, Layer, ManagedRuntime } from \"effect\";\nimport type { Fiber as FiberType } from \"effect/Fiber\";\nimport type { ManagedRuntime as ManagedRuntimeType } from \"effect/ManagedRuntime\";\n\nimport { interrupt_fiber, watch_fiber_exit } from \"./fibers.ts\";\nimport { hash_deps } from \"./deps.ts\";\nimport type { Dispose, PromiseOptions, ValueOptions } from \"./types.ts\";\n\nexport type { Dispose, PromiseOptions, ValueOptions } from \"./types.ts\";\n\n/**\n * Unified effect block dispatcher. Manages the fiber lifecycle of every\n * effect block and wires results into reactive channels.\n *\n * @example\n * ```ts\n * const dispatcher = new Dispatcher();\n * const cancel = dispatcher.fork(Effect.log(\"running\"));\n * cancel();\n * ```\n *\n * @since 2.0.0\n * @internal\n */\nexport class Dispatcher {\n /** The underlying Effect runtime that executes forked programs. */\n #runtime: ManagedRuntimeType<unknown, unknown>;\n /** Active fibers keyed by cache id or generated fork id. */\n #fibers = new Map<string, FiberType<unknown, unknown>>();\n /** Resolved values and pending promises keyed by cache id. */\n #values = new Map<string, unknown>();\n /** Current cache key per value block id. */\n #value_ids = new Map<string, string>();\n /** Current cache key per promise block id. */\n #promise_ids = new Map<string, string>();\n /** Whether dispose has been called, blocking new work. */\n #disposed = false;\n /** Monotonically increasing counter for unnamed fiber keys. */\n #next_fiber_id = 0;\n\n /**\n * Creates a dispatcher with an optional layer and installs it as the global\n * singleton returned by {@link get_dispatcher}.\n *\n * @example\n * ```ts\n * const dispatcher = Dispatcher.make(Db.Live);\n * ```\n *\n * @since 2.0.0\n * @param layer - Optional Effect layer to provide to the runtime.\n * @returns The newly created dispatcher.\n */\n static make<R = never>(\n layer?: Layer.Layer<R>,\n ): Dispatcher {\n const runtime = ManagedRuntime.make(\n layer ?? (Layer.empty as unknown as Layer.Layer<R>),\n );\n\n const dispatcher = new Dispatcher(\n runtime as ManagedRuntimeType<unknown, unknown>,\n );\n current_dispatcher = dispatcher;\n\n return dispatcher;\n }\n\n /**\n * Creates a dispatcher backed by the provided managed runtime.\n *\n * @example\n * ```ts\n * const dispatcher = new Dispatcher(runtime);\n * ```\n *\n * @since 2.0.0\n * @param runtime - Managed runtime to use, or an empty-layer runtime when\n * omitted.\n */\n constructor(runtime?: ManagedRuntimeType<unknown, unknown>) {\n this.#runtime = runtime ??\n ManagedRuntime.make(Layer.empty) as unknown as ManagedRuntimeType<\n unknown,\n unknown\n >;\n }\n\n /**\n * Forks an effect as a managed fiber and returns a cleanup function.\n *\n * @example\n * ```ts\n * const dispose = dispatcher.fork(Effect.log(\"clicked\"));\n * ```\n *\n * @since 2.0.0\n * @param effect - Effect to fork.\n * @returns A function that interrupts the fiber.\n */\n fork<A, E, R>(effect: Effect.Effect<A, E, R>): Dispose {\n if (this.#disposed) {\n return () => {};\n }\n\n const fiber = this.#runtime.runFork(\n effect as Effect.Effect<unknown, unknown, unknown>,\n );\n const key = `fork:${this.#next_fiber_id}`;\n\n this.#next_fiber_id += 1;\n this.#fibers.set(key, fiber);\n watch_fiber_exit({\n runtime: this.#runtime,\n fiber,\n on_complete: () => this.#fibers.delete(key),\n });\n\n let disposed = false;\n\n return (): void => {\n if (disposed) {\n return;\n }\n\n disposed = true;\n interrupt_fiber(this.#runtime, fiber);\n };\n }\n\n /**\n * Forks an effect and exposes its result as a cached reactive value.\n *\n * @example\n * ```ts\n * const user = dispatcher.value({ id, deps, fallback, factory });\n * ```\n *\n * @since 2.0.0\n * @param options - Value id, dependency array, fallback, and effect factory.\n * @returns The cached value if resolved, otherwise the fallback.\n */\n value<A>(options: ValueOptions<A>): A {\n const cache_key = this.#make_value_cache_key(options.id, options.deps);\n const old_key = this.#value_ids.get(options.id);\n\n if (old_key !== undefined && old_key !== cache_key) {\n this.#interrupt_cached_fiber(old_key);\n }\n\n this.#value_ids.set(options.id, cache_key);\n\n if (this.#should_start_value_fiber(cache_key)) {\n this.#start_value_fiber(cache_key, options);\n }\n\n if (this.#values.has(cache_key)) {\n return this.#values.get(cache_key) as A;\n }\n\n return options.fallback;\n }\n\n /**\n * Forks an effect and exposes its completion as a cached promise.\n *\n * @example\n * ```ts\n * const promise = dispatcher.promise({ id, deps, factory });\n * ```\n *\n * @since 2.0.0\n * @param options - Promise id, dependency array, and effect factory.\n * @returns A promise that resolves with the effect result.\n */\n promise<A>(options: PromiseOptions<A>): Promise<A> {\n if (this.#disposed) {\n return Promise.reject(\n new Error(\"[DISPATCHER_DISPOSED]: Dispatcher has been disposed\"),\n );\n }\n\n const cache_key = this.#make_promise_cache_key(options.id, options.deps);\n const old_key = this.#promise_ids.get(options.id);\n\n if (old_key !== undefined && old_key !== cache_key) {\n this.#interrupt_cached_fiber(old_key);\n this.#values.delete(old_key);\n }\n\n this.#promise_ids.set(options.id, cache_key);\n\n const existing = this.#values.get(cache_key);\n\n if (existing instanceof Promise) {\n return existing as Promise<A>;\n }\n\n const promise = this.#start_promise_fiber(cache_key, options);\n\n this.#values.set(cache_key, promise);\n\n return promise;\n }\n\n /**\n * Runs an event-handler effect and surfaces failures to Svelte.\n *\n * @example\n * ```ts\n * await dispatcher.run(Effect.log(\"submit\"));\n * ```\n *\n * @since 2.0.0\n * @param effect - Effect to execute.\n * @returns A promise that resolves or rejects when the effect completes.\n */\n run<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A> {\n if (this.#disposed) {\n return Promise.reject(\n new Error(\"[DISPATCHER_DISPOSED]: Dispatcher has been disposed\"),\n );\n }\n\n const exit_effect = Effect.exit(effect) as Effect.Effect<\n unknown,\n unknown,\n unknown\n >;\n\n return this.#runtime\n .runPromise(exit_effect)\n .then((exit: unknown) => {\n const result = exit as Exit.Exit<A, E>;\n\n if (Exit.isSuccess(result)) {\n return result.value;\n }\n\n if (Cause.hasInterruptsOnly(result.cause)) {\n return undefined as A;\n }\n\n const error = Cause.squash(result.cause);\n\n queueMicrotask(() => {\n throw error;\n });\n\n throw error;\n });\n }\n\n /**\n * Cancels all running fibers and releases cached values.\n *\n * @example\n * ```ts\n * dispatcher.dispose();\n * ```\n *\n * @since 2.0.0\n * @returns Nothing.\n */\n dispose(): void {\n this.#disposed = true;\n\n for (const fiber of this.#fibers.values()) {\n interrupt_fiber(this.#runtime, fiber);\n }\n\n this.#fibers.clear();\n this.#values.clear();\n this.#value_ids.clear();\n this.#promise_ids.clear();\n\n void this.#runtime.dispose().catch((error: unknown) => {\n queueMicrotask(() => {\n throw error;\n });\n });\n }\n\n #make_value_cache_key(id: string, deps: readonly unknown[]): string {\n return `value:${id}::${hash_deps(deps)}`;\n }\n\n #make_promise_cache_key(id: string, deps: readonly unknown[]): string {\n return `promise:${id}::${hash_deps(deps)}`;\n }\n\n #interrupt_cached_fiber(cache_key: string): void {\n const old_fiber = this.#fibers.get(cache_key);\n\n if (!old_fiber) {\n return;\n }\n\n interrupt_fiber(this.#runtime, old_fiber);\n this.#fibers.delete(cache_key);\n }\n\n #should_start_value_fiber(cache_key: string): boolean {\n return (\n !this.#disposed &&\n !this.#fibers.has(cache_key) &&\n !this.#values.has(cache_key)\n );\n }\n\n #start_value_fiber<A>(cache_key: string, options: ValueOptions<A>): void {\n const program = Effect.gen(function* () {\n const result = yield* Effect.gen(options.factory);\n\n return result;\n });\n const fiber = this.#runtime.runFork(\n program as Effect.Effect<unknown, unknown, unknown>,\n );\n\n this.#fibers.set(cache_key, fiber);\n watch_fiber_exit({\n runtime: this.#runtime,\n fiber,\n on_complete: () => this.#fibers.delete(cache_key),\n on_success: (value) => this.#values.set(cache_key, value),\n });\n }\n\n #start_promise_fiber<A>(\n cache_key: string,\n options: PromiseOptions<A>,\n ): Promise<A> {\n const program = Effect.gen(function* () {\n const result = yield* Effect.gen(options.factory);\n\n return result;\n });\n const fiber = this.#runtime.runFork(\n program as Effect.Effect<unknown, unknown, unknown>,\n );\n\n this.#fibers.set(cache_key, fiber);\n\n return this.#runtime.runPromise(\n Effect.flatMap(Fiber.await(fiber), (exit) =>\n Effect.sync(() => {\n this.#fibers.delete(cache_key);\n this.#values.delete(cache_key);\n\n if (this.#promise_ids.get(options.id) === cache_key) {\n this.#promise_ids.delete(options.id);\n }\n\n if (Exit.isSuccess(exit)) {\n return exit.value as A;\n }\n\n throw Cause.squash(exit.cause);\n })),\n );\n }\n}\n\nlet current_dispatcher: Dispatcher | null = null;\n\n/**\n * Resolves the active dispatcher, creating a default one if necessary.\n *\n * @example\n * ```ts\n * const dispatcher = get_dispatcher();\n * ```\n *\n * @since 2.0.0\n * @returns The active dispatcher singleton.\n * @internal\n */\nexport function get_dispatcher(): Dispatcher {\n current_dispatcher ??= new Dispatcher();\n\n return current_dispatcher;\n}\n\n/**\n * Resets the internal singleton dispatcher used by source-level tests.\n *\n * @example\n * ```ts\n * reset_dispatcher();\n * ```\n *\n * @since 2.0.0\n * @returns Nothing.\n * @internal\n */\nexport function reset_dispatcher(): void {\n current_dispatcher?.dispose();\n current_dispatcher = null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,SAAgB,gBACd,SACA,OACM;CACN,QAAQ,QACN,MAAM,UAAU,KAAK,CACvB;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,iBACd,SAIM;CACN,MAAM,EAAE,SAAS,OAAO,aAAa,eAAe;CAEpD,QAAQ,QACN,OAAO,QAAQ,MAAM,MAAM,KAAK,IAAI,SAClC,OAAO,WAAW;EAChB,cAAc;EAEd,IAAI,KAAK,UAAU,IAAI,GAAG;GACxB,aAAa,KAAK,KAAU;GAE5B;EACF;EAEA,IAAI,CAAC,MAAM,kBAAkB,KAAK,KAAK,GACrC,qBAAqB;GACnB,MAAM,MAAM,OAAO,KAAK,KAAK;EAC/B,CAAC;CAEL,CAAC,CAAC,CACN;AACF;;;ACrFA,MAAM,iCAAiB,IAAI,QAAwB;AACnD,MAAM,iCAAiB,IAAI,IAAoB;AAE/C,IAAI,qBAAqB;AACzB,IAAI,qBAAqB;;;;;;;;;;;;;;AAezB,SAAgB,UAAU,MAAkC;CAC1D,MAAM,QAAQ,KAAK,KAAK,QAAQ;EAC9B,IAAI,QAAQ,MACV,OAAO;EAGT,IAAI,QAAQ,KAAA,GACV,OAAO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_binding_names, l as AwaitInEffectWorkError, n as collect_yield_star_nodes, o as is_yield_star_expression, p as make_imports, r as contains_top_level_await, s as collect_free_identifiers, u as PreprocessError } from "./transform-
|
|
1
|
+
import { a as find_yield_star_node, c as AsyncEffectInSyncRuneError, d as collect_top_level_binding_names, f as has_local_import_binding, i as extract_binding_names, l as AwaitInEffectWorkError, n as collect_yield_star_nodes, o as is_yield_star_expression, p as make_imports, r as contains_top_level_await, s as collect_free_identifiers, u as PreprocessError } from "./transform-CMvL4SBp.js";
|
|
2
2
|
import { contains_top_level_yield_star } from "../detect.js";
|
|
3
3
|
import MagicString from "magic-string";
|
|
4
4
|
import ts from "typescript";
|
|
@@ -187,6 +187,7 @@ function lower_variable_statement(stmt, content, context) {
|
|
|
187
187
|
const decl_list = stmt.declarationList;
|
|
188
188
|
const kind = (decl_list.flags & ts.NodeFlags.Let) !== 0 ? "let" : "const";
|
|
189
189
|
let has_bare_yield = false;
|
|
190
|
+
let uses_dispatcher_promise = false;
|
|
190
191
|
for (const decl of decl_list.declarations) {
|
|
191
192
|
if (!decl.initializer || !contains_top_level_yield_star(decl.initializer)) {
|
|
192
193
|
if (contains_top_level_yield_star(decl.name)) {
|
|
@@ -207,6 +208,13 @@ function lower_variable_statement(stmt, content, context) {
|
|
|
207
208
|
if (ts.isIdentifier(decl.name)) {
|
|
208
209
|
const original_name = binding_text;
|
|
209
210
|
if (is_yield_star_expression(decl.initializer)) {
|
|
211
|
+
if (kind === "const") {
|
|
212
|
+
const awaited = make_awaited_yield_initializer(decl.initializer, content, original_name, context);
|
|
213
|
+
type_helpers.push(awaited.declaration);
|
|
214
|
+
rewritten_decls.push(`${original_name} = ${awaited.expression}`);
|
|
215
|
+
uses_dispatcher_promise = true;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
210
218
|
const temp_name = context.next_temp_name(original_name);
|
|
211
219
|
const yield_text = extract_yield_star_full_text(decl.initializer, content);
|
|
212
220
|
const type_helper = make_yield_type_helper(yield_text, original_name, context);
|
|
@@ -268,6 +276,7 @@ function lower_variable_statement(stmt, content, context) {
|
|
|
268
276
|
type_helpers,
|
|
269
277
|
rewritten_text: rewritten_decls.length === 0 ? "" : `${has_bare_yield ? "let" : kind} ${rewritten_decls.join(", ")};`,
|
|
270
278
|
effect_blocks: statements.length === 0 ? [] : [make_effect_block(statements, deps)],
|
|
279
|
+
uses_dispatcher_promise,
|
|
271
280
|
range: {
|
|
272
281
|
start: stmt.getStart(),
|
|
273
282
|
end: stmt.end
|
|
@@ -391,6 +400,22 @@ function lower_expression_yields(expr, content, hint, context) {
|
|
|
391
400
|
effect_blocks: [make_effect_block(statements, deps)]
|
|
392
401
|
};
|
|
393
402
|
}
|
|
403
|
+
function make_awaited_yield_initializer(expr, content, hint, context) {
|
|
404
|
+
const yield_text = extract_yield_star_full_text(expr, content);
|
|
405
|
+
const helper_name = context.next_helper_name(`effect_${hint}`);
|
|
406
|
+
const helper_id = make_script_effect_id(expr, context);
|
|
407
|
+
const deps_text = `[${collect_deps(yield_text).join(", ")}]`;
|
|
408
|
+
return {
|
|
409
|
+
declaration: `function* ${helper_name}() { return (${yield_text}); }`,
|
|
410
|
+
expression: [
|
|
411
|
+
`await ${context.dispatcher_name}().promise({`,
|
|
412
|
+
`id: ${JSON.stringify(helper_id)}, `,
|
|
413
|
+
`deps: ${deps_text}, `,
|
|
414
|
+
`factory: () => ${helper_name}()`,
|
|
415
|
+
`})`
|
|
416
|
+
].join("")
|
|
417
|
+
};
|
|
418
|
+
}
|
|
394
419
|
function make_yield_type_helper(yield_text, hint, context) {
|
|
395
420
|
if (!context.emit_types) return;
|
|
396
421
|
const helper_name = context.next_type_helper_name(hint);
|
|
@@ -413,6 +438,9 @@ function make_state_placeholder(rune_name, type, context) {
|
|
|
413
438
|
function strip_yield_star(yield_text) {
|
|
414
439
|
return yield_text.replace(/^yield\*\s*/, "");
|
|
415
440
|
}
|
|
441
|
+
function make_script_effect_id(expr, context) {
|
|
442
|
+
return `${context.filename}:${expr.getStart()}:${expr.end}`;
|
|
443
|
+
}
|
|
416
444
|
function rewrite_state_rune_as_derived(expression) {
|
|
417
445
|
const state_call = expression.match(/^\$state(?:\.raw)?\(([\s\S]*)\)$/);
|
|
418
446
|
if (!state_call) return expression;
|
|
@@ -496,6 +524,8 @@ function transform_script_effect(content, filename, options = {}) {
|
|
|
496
524
|
const name_allocator = make_name_allocator(top_level_binding_names);
|
|
497
525
|
const emit_types = options.emit_types ?? true;
|
|
498
526
|
let has_effect = false;
|
|
527
|
+
let uses_dispatcher_promise = false;
|
|
528
|
+
let uses_effect_types = false;
|
|
499
529
|
/** Phase 1: detect imports already provided by the user. */
|
|
500
530
|
const has_effect_import = has_local_import_binding(source_file, "effect", "Effect");
|
|
501
531
|
const has_dispatcher_import = has_local_import_binding(source_file, "svelte-effect-runtime/internal/generators", "get_dispatcher");
|
|
@@ -510,8 +540,13 @@ function transform_script_effect(content, filename, options = {}) {
|
|
|
510
540
|
untrack: has_untrack_import ? "untrack" : reserve_runtime_import("untrack")
|
|
511
541
|
};
|
|
512
542
|
const context = {
|
|
543
|
+
filename,
|
|
544
|
+
dispatcher_name: runtime_bindings.dispatcher,
|
|
513
545
|
effect_name: runtime_bindings.effect,
|
|
514
546
|
emit_types,
|
|
547
|
+
next_helper_name(hint) {
|
|
548
|
+
return name_allocator.reserve(make_generated_name(hint ?? "helper", ""));
|
|
549
|
+
},
|
|
515
550
|
next_temp_name(hint) {
|
|
516
551
|
const suffix = temp_counter === 0 ? "" : `_${temp_counter}`;
|
|
517
552
|
const name = make_generated_name(hint ?? String(temp_counter), suffix);
|
|
@@ -537,6 +572,8 @@ function transform_script_effect(content, filename, options = {}) {
|
|
|
537
572
|
magic.appendLeft(lowered.range.start, prefix + "\n");
|
|
538
573
|
}
|
|
539
574
|
effect_blocks.push(...lowered.effect_blocks);
|
|
575
|
+
uses_dispatcher_promise ||= lowered.uses_dispatcher_promise ?? false;
|
|
576
|
+
uses_effect_types ||= lowered.temps.some((temp) => temp.type?.includes(`${runtime_bindings.effect}.Success`) ?? false);
|
|
540
577
|
}
|
|
541
578
|
if (!has_effect) {
|
|
542
579
|
block_refs.push({
|
|
@@ -549,13 +586,19 @@ function transform_script_effect(content, filename, options = {}) {
|
|
|
549
586
|
};
|
|
550
587
|
}
|
|
551
588
|
/** Phase 3: inject runtime imports after the last user import. */
|
|
552
|
-
const imports = make_imports(has_effect_import, has_dispatcher_import, has_untrack_import, runtime_bindings
|
|
589
|
+
const imports = make_imports(has_effect_import, has_dispatcher_import, has_untrack_import, runtime_bindings, {
|
|
590
|
+
needs_dispatcher: effect_blocks.length > 0 || uses_dispatcher_promise,
|
|
591
|
+
needs_effect: effect_blocks.length > 0 || uses_effect_types,
|
|
592
|
+
needs_untrack: effect_blocks.length > 0
|
|
593
|
+
});
|
|
553
594
|
const last_import = [...source_file.statements].reverse().find(ts.isImportDeclaration);
|
|
554
|
-
if (last_import) magic.appendRight(last_import.end, "\n" + imports);
|
|
595
|
+
if (imports) if (last_import) magic.appendRight(last_import.end, "\n" + imports);
|
|
555
596
|
else magic.prepend(imports + "\n");
|
|
556
597
|
/** Phase 4: append the runtime program and lifecycle wiring. */
|
|
557
|
-
|
|
558
|
-
|
|
598
|
+
if (effect_blocks.length > 0) {
|
|
599
|
+
const runtime_block = make_runtime_block_with_bindings(effect_blocks, runtime_bindings);
|
|
600
|
+
magic.append("\n" + runtime_block);
|
|
601
|
+
}
|
|
559
602
|
block_refs.push({
|
|
560
603
|
id: filename,
|
|
561
604
|
kind: "script"
|
|
@@ -610,4 +653,4 @@ function make_generated_name(hint, suffix) {
|
|
|
610
653
|
//#endregion
|
|
611
654
|
export { transform_script_effect as t };
|
|
612
655
|
|
|
613
|
-
//# sourceMappingURL=preprocess-
|
|
656
|
+
//# sourceMappingURL=preprocess-BhoCga82.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"preprocess-BhoCga82.js","names":[],"sources":["../../../modules/svelte-effect-runtime/src/preprocess/source.ts","../../../modules/svelte-effect-runtime/src/preprocess/runtime-block.ts","../../../modules/svelte-effect-runtime/src/preprocess/runes.ts","../../../modules/svelte-effect-runtime/src/preprocess/lower.ts","../../../modules/svelte-effect-runtime/src/preprocess/index.ts"],"sourcesContent":["import type MagicString from \"magic-string\";\nimport type ts from \"typescript\";\n\n/**\n * Creates a source map from transformed script back to the original block.\n *\n * @since 2.0.0\n * @param magic - MagicString instance holding the transformed source.\n * @param filename - Source filename used for the source map entry.\n * @returns A plain source map object.\n */\nexport function create_source_map(\n magic: MagicString,\n filename: string,\n): Record<string, unknown> {\n const map = magic.generateMap({\n hires: true,\n includeContent: true,\n source: filename,\n });\n\n return map as unknown as Record<string, unknown>;\n}\n\n/**\n * Slices a substring matching a node's full source range.\n *\n * @since 2.0.0\n * @param content - Original source text.\n * @param node - AST node whose full range should be extracted.\n * @returns Source text including leading trivia.\n */\nexport function slice(content: string, node: ts.Node): string {\n return content.slice(node.getFullStart(), node.end);\n}\n\n/**\n * Slices a substring matching a node's source range without leading trivia.\n *\n * @since 2.0.0\n * @param content - Original source text.\n * @param node - AST node whose non-trivia range should be extracted.\n * @returns Source text excluding leading trivia.\n */\nexport function slice_start(content: string, node: ts.Node): string {\n return content.slice(node.getStart(), node.end);\n}\n","import type { EffectBlock, RuntimeImportBindings } from \"./types.ts\";\n\n/**\n * Builds the runtime blocks appended to lowered script effect code.\n *\n * @since 2.0.0\n * @param blocks - Effect bodies and dependency reads to emit.\n * @returns Full `$effect` blocks that fork generated `Effect.gen` programs.\n */\nexport function make_runtime_block(blocks: EffectBlock[]): string {\n const bindings: RuntimeImportBindings = {\n cancel: \"__SER___cancel\",\n dispatcher: \"get_dispatcher\",\n dispatcher_value: \"__SER___dispatcher\",\n effect: \"Effect\",\n program: \"__SER___program\",\n untrack: \"untrack\",\n };\n\n return make_runtime_block_with_bindings(blocks, bindings);\n}\n\n/**\n * Builds the runtime blocks appended to lowered script effect code with\n * explicit runtime import bindings.\n *\n * @since 2.4.2\n * @param blocks - Effect bodies and dependency reads to emit.\n * @param bindings - Runtime binding names available in the generated code.\n * @returns Full `$effect` blocks that fork generated `Effect.gen` programs.\n */\nexport function make_runtime_block_with_bindings(\n blocks: EffectBlock[],\n bindings: RuntimeImportBindings,\n): string {\n const merged_block = merge_effect_blocks(blocks);\n const dep_reads = merged_block.deps.map((dep) => ` ${dep};`);\n\n const body = merged_block.statements\n .map((statement) => ` ${statement}`)\n .join(\"\\n\");\n\n return [\n \"\",\n \"$effect(() => {\",\n ...dep_reads,\n ` const ${bindings.dispatcher_value} = ${bindings.dispatcher}();`,\n ` const ${bindings.program} = ${bindings.effect}.gen(function* () {`,\n body,\n \" });\",\n ` const ${bindings.cancel} = ${bindings.untrack}(() => ${bindings.dispatcher_value}.fork(${bindings.program}));`,\n ` import.meta.hot?.dispose(${bindings.cancel});`,\n ` return ${bindings.cancel};`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction merge_effect_blocks(blocks: EffectBlock[]): EffectBlock {\n const statements = blocks.flatMap((block) => block.statements);\n const deps = blocks.flatMap((block) => block.deps);\n\n return {\n statements,\n deps: [...new Set(deps)],\n };\n}\n","import { contains_top_level_yield_star } from \"$/detect.ts\";\nimport { AsyncEffectInSyncRuneError } from \"$/error.ts\";\nimport { slice } from \"./source.ts\";\n\nimport ts from \"typescript\";\n\nconst ASYNC_EXPRESSION_RUNES = new Set([\n \"$derived\",\n \"$inspect\",\n \"$state\",\n \"$state.raw\",\n]);\n\nconst CALLBACK_RUNES = new Set([\n \"$derived.by\",\n \"$effect\",\n \"$effect.pre\",\n \"$effect.root\",\n]);\n\n/**\n * Validates that `yield*` only appears in rune positions the script-effect\n * transform can lower without changing the rune's normal Svelte contract.\n *\n * @since 2.0.0\n * @param node - AST node to scan.\n * @param content - Original script source used for diagnostics.\n * @param filename - Source filename used for diagnostics.\n * @returns Nothing.\n */\nexport function validate_rune_yield_usage(\n node: ts.Node,\n content: string,\n filename: string,\n): void {\n visit_rune_yield_usage(node, content, filename);\n}\n\n/**\n * Identifies `$state(...)` and `$state.raw(...)` initializer calls.\n *\n * @since 2.0.0\n * @param expr - Expression to classify.\n * @param content - Original script source used to preserve argument text.\n * @returns State rune details when the expression is a state initializer.\n */\nexport function get_state_rune_initializer(\n expr: ts.Expression,\n content: string,\n): { rune_name: \"$state\" | \"$state.raw\"; value_text: string } | undefined {\n if (!ts.isCallExpression(expr)) {\n return undefined;\n }\n\n const rune_name = get_rune_name(expr.expression);\n\n if (rune_name !== \"$state\" && rune_name !== \"$state.raw\") {\n return undefined;\n }\n\n const first_arg = expr.arguments[0];\n\n if (!first_arg) {\n return undefined;\n }\n\n return {\n rune_name,\n value_text: slice(content, first_arg).trim(),\n };\n}\n\nfunction visit_rune_yield_usage(\n node: ts.Node,\n content: string,\n filename: string,\n): void {\n if (ts.isCallExpression(node)) {\n validate_call_expression(node, content, filename);\n }\n\n node.forEachChild((child) => {\n visit_rune_yield_usage(child, content, filename);\n });\n}\n\nfunction validate_call_expression(\n call: ts.CallExpression,\n content: string,\n filename: string,\n): void {\n const rune_name = get_rune_name(call.expression);\n\n if (!rune_name) {\n return;\n }\n\n if (\n !ASYNC_EXPRESSION_RUNES.has(rune_name) &&\n contains_top_level_yield_star(call)\n ) {\n throw new AsyncEffectInSyncRuneError(\n rune_name,\n slice(content, call),\n filename,\n );\n }\n\n if (!CALLBACK_RUNES.has(rune_name)) {\n return;\n }\n\n const callback = call.arguments[0];\n\n if (!callback || !callback_has_top_level_yield_star(callback)) {\n return;\n }\n\n throw new AsyncEffectInSyncRuneError(\n rune_name,\n slice(content, call),\n filename,\n );\n}\n\nfunction callback_has_top_level_yield_star(node: ts.Expression): boolean {\n if (\n (ts.isArrowFunction(node) ||\n ts.isFunctionExpression(node)) &&\n node.body !== undefined\n ) {\n return contains_top_level_yield_star(node.body);\n }\n\n return contains_top_level_yield_star(node);\n}\n\nfunction get_rune_name(expr: ts.Expression): string | undefined {\n if (ts.isIdentifier(expr) && is_rune_root(expr.text)) {\n return expr.text;\n }\n\n if (!ts.isPropertyAccessExpression(expr)) {\n return undefined;\n }\n\n const root_name = get_rune_name(expr.expression);\n\n if (!root_name) {\n return undefined;\n }\n\n return `${root_name}.${expr.name.text}`;\n}\n\nfunction is_rune_root(name: string): boolean {\n return (\n name === \"$bindable\" ||\n name === \"$derived\" ||\n name === \"$effect\" ||\n name === \"$host\" ||\n name === \"$inspect\" ||\n name === \"$props\" ||\n name === \"$state\"\n );\n}\n","import { collect_free_identifiers } from \"$/markup/transform/expressions.ts\";\nimport { contains_top_level_yield_star } from \"$/detect.ts\";\nimport {\n collect_yield_star_nodes,\n extract_binding_names,\n find_yield_star_node,\n is_yield_star_expression,\n} from \"./ast.ts\";\nimport { get_state_rune_initializer } from \"./runes.ts\";\nimport { slice, slice_start } from \"./source.ts\";\nimport type {\n EffectBlock,\n LoweredExpression,\n LoweredStatement,\n ScriptLoweringContext,\n TempBinding,\n} from \"./types.ts\";\n\nimport ts from \"typescript\";\n\n/**\n * Delegates a statement to the correct lowerer based on syntax kind.\n *\n * @since 2.0.0\n * @param stmt - Statement to lower.\n * @param content - Original source text.\n * @param context - Lowering services for this transform pass.\n * @returns Lowered statement descriptor.\n */\nexport function lower_statement(\n stmt: ts.Statement,\n content: string,\n context: ScriptLoweringContext,\n): LoweredStatement {\n if (ts.isExpressionStatement(stmt)) {\n return lower_expression_statement(stmt, content, context);\n }\n\n if (ts.isVariableStatement(stmt)) {\n return lower_variable_statement(stmt, content, context);\n }\n\n const text = slice(content, stmt);\n\n return {\n temps: [],\n rewritten_text: \"\",\n effect_blocks: [make_effect_block([text], collect_deps(text))],\n range: { start: stmt.getFullStart(), end: stmt.end },\n };\n}\n\nfunction lower_variable_statement(\n stmt: ts.VariableStatement,\n content: string,\n context: ScriptLoweringContext,\n): LoweredStatement {\n const temps: TempBinding[] = [];\n const type_helpers: string[] = [];\n const rewritten_decls: string[] = [];\n const statements: string[] = [];\n const deps: string[] = [];\n\n const decl_list = stmt.declarationList;\n const kind = (decl_list.flags & ts.NodeFlags.Let) !== 0 ? \"let\" : \"const\";\n let has_bare_yield = false;\n let uses_dispatcher_promise = false;\n\n for (const decl of decl_list.declarations) {\n if (!decl.initializer || !contains_top_level_yield_star(decl.initializer)) {\n if (contains_top_level_yield_star(decl.name)) {\n has_bare_yield = true;\n\n const binding_text = slice(content, decl.name).trim();\n const initializer_text = decl.initializer\n ? slice(content, decl.initializer).trim()\n : \"undefined\";\n const names = extract_binding_names(decl.name);\n const statement = `(${binding_text} = ${initializer_text});`;\n\n temps.push(...names.map((name) => make_unknown_temp(name, context)));\n statements.push(statement);\n deps.push(...collect_deps(statement, names));\n\n continue;\n }\n\n rewritten_decls.push(slice(content, decl).trim());\n continue;\n }\n\n const binding_text = slice(content, decl.name).trim();\n\n if (ts.isIdentifier(decl.name)) {\n const original_name = binding_text;\n\n if (is_yield_star_expression(decl.initializer)) {\n if (kind === \"const\") {\n const awaited = make_awaited_yield_initializer(\n decl.initializer,\n content,\n original_name,\n context,\n );\n\n type_helpers.push(awaited.declaration);\n rewritten_decls.push(`${original_name} = ${awaited.expression}`);\n uses_dispatcher_promise = true;\n continue;\n }\n\n const temp_name = context.next_temp_name(original_name);\n const yield_text = extract_yield_star_full_text(\n decl.initializer,\n content,\n );\n const type_helper = make_yield_type_helper(\n yield_text,\n original_name,\n context,\n );\n\n if (type_helper) {\n type_helpers.push(type_helper.declaration);\n temps.push({ name: temp_name, type: type_helper.type });\n } else {\n temps.push({ name: temp_name });\n }\n\n has_bare_yield = true;\n rewritten_decls.push(`${original_name} = $derived(${temp_name})`);\n\n statements.push(`${temp_name} = ${yield_text};`);\n deps.push(...collect_deps(yield_text));\n } else {\n const state_rune = get_state_rune_initializer(\n decl.initializer,\n content,\n );\n\n if (state_rune) {\n const direct_yield_text = extract_yield_star_full_text(\n decl.initializer,\n content,\n );\n const state_type = direct_yield_text === state_rune.value_text\n ? make_yield_type_helper(\n state_rune.value_text,\n original_name,\n context,\n )\n : undefined;\n\n if (state_type) {\n type_helpers.push(state_type.declaration);\n }\n\n has_bare_yield = true;\n rewritten_decls.push(\n `${original_name} = ${\n make_state_placeholder(\n state_rune.rune_name,\n state_type?.type,\n context,\n )\n }`,\n );\n statements.push(`${original_name} = ${state_rune.value_text};`);\n deps.push(...collect_deps(state_rune.value_text));\n continue;\n }\n\n const lowered = lower_expression_yields(\n decl.initializer,\n content,\n original_name,\n context,\n );\n\n temps.push(...lowered.temps);\n type_helpers.push(...(lowered.type_helpers ?? []));\n for (const block of lowered.effect_blocks) {\n statements.push(...block.statements);\n deps.push(...block.deps);\n }\n\n const rewritten_expr = rewrite_state_rune_as_derived(\n lowered.rewritten_expr,\n );\n const final_expr = should_wrap_complex_initializer_as_derived(\n decl.initializer,\n content,\n )\n ? `$derived(${rewritten_expr})`\n : rewritten_expr;\n\n if (final_expr !== rewritten_expr) {\n has_bare_yield = true;\n }\n\n rewritten_decls.push(`${original_name} = ${final_expr}`);\n }\n } else {\n has_bare_yield = true;\n\n const temp_name = context.next_temp_name(\"destructure\");\n const names = extract_binding_names(decl.name);\n const yield_text = extract_yield_star_full_text(\n decl.initializer,\n content,\n );\n const type_helper = make_yield_type_helper(\n yield_text,\n \"destructure\",\n context,\n );\n\n if (type_helper) {\n type_helpers.push(type_helper.declaration);\n temps.push({ name: temp_name, type: type_helper.type });\n } else {\n temps.push({ name: temp_name });\n }\n\n temps.push(...names.map((name) => make_unknown_temp(name, context)));\n\n statements.push(`${temp_name} = ${yield_text};`);\n statements.push(`(${binding_text} = ${temp_name});`);\n deps.push(...collect_deps(yield_text));\n }\n }\n\n const rewritten_text = rewritten_decls.length === 0\n ? \"\"\n : `${has_bare_yield ? \"let\" : kind} ${rewritten_decls.join(\", \")};`;\n\n return {\n temps,\n type_helpers,\n rewritten_text,\n effect_blocks: statements.length === 0\n ? []\n : [make_effect_block(statements, deps)],\n uses_dispatcher_promise,\n range: { start: stmt.getStart(), end: stmt.end },\n };\n}\n\nfunction lower_expression_statement(\n stmt: ts.ExpressionStatement,\n content: string,\n context: ScriptLoweringContext,\n): LoweredStatement {\n const expr = stmt.expression;\n\n if (!contains_top_level_yield_star(expr)) {\n return {\n temps: [],\n rewritten_text: slice(content, stmt).trim(),\n effect_blocks: [],\n range: { start: stmt.getStart(), end: stmt.end },\n };\n }\n\n if (is_yield_star_expression(expr)) {\n const text = slice(content, expr).trim();\n\n return {\n temps: [],\n rewritten_text: \"\",\n effect_blocks: [make_effect_block([text + \";\"], collect_deps(text))],\n range: { start: stmt.getFullStart(), end: stmt.end },\n };\n }\n\n if (ts.isBinaryExpression(expr) && is_assignment_operator(expr)) {\n const target = slice(content, expr.left).trim();\n const target_names = collect_assignment_target_names(expr.left);\n\n if (\n expr.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n is_yield_star_expression(expr.right)\n ) {\n const yield_text = extract_yield_star_full_text(expr.right, content);\n\n return {\n temps: [],\n rewritten_text: \"\",\n effect_blocks: [\n make_effect_block(\n [`${target} = ${yield_text};`],\n collect_deps(yield_text, target_names),\n ),\n ],\n range: { start: stmt.getStart(), end: stmt.end },\n };\n }\n\n const lowered = lower_expression_yields(\n expr.right,\n content,\n make_temp_hint(target),\n context,\n );\n const temp_names = lowered.temps.map((temp) => temp.name);\n const statement = `${target} ${\n slice(content, expr.operatorToken).trim()\n } ${lowered.rewritten_expr};`;\n\n return {\n temps: lowered.temps,\n type_helpers: lowered.type_helpers,\n rewritten_text: \"\",\n effect_blocks: [\n make_effect_block(\n [\n ...lowered.effect_blocks.flatMap((block) => block.statements),\n statement,\n ],\n [\n ...lowered.effect_blocks.flatMap((block) => block.deps),\n ...collect_deps(lowered.rewritten_expr, [\n ...target_names,\n ...temp_names,\n ]),\n ],\n ),\n ],\n range: { start: stmt.getStart(), end: stmt.end },\n };\n }\n\n const lowered = lower_expression_yields(\n expr,\n content,\n \"call\",\n context,\n );\n\n if (is_top_level_rune_call(expr)) {\n return {\n temps: lowered.temps,\n type_helpers: lowered.type_helpers,\n rewritten_text: lowered.rewritten_expr + \";\",\n effect_blocks: lowered.effect_blocks,\n range: { start: stmt.getStart(), end: stmt.end },\n };\n }\n\n const temp_names = lowered.temps.map((temp) => temp.name);\n\n return {\n temps: lowered.temps,\n type_helpers: lowered.type_helpers,\n rewritten_text: \"\",\n effect_blocks: [\n make_effect_block(\n [\n ...lowered.effect_blocks.flatMap((block) => block.statements),\n lowered.rewritten_expr + \";\",\n ],\n [\n ...lowered.effect_blocks.flatMap((block) => block.deps),\n ...collect_deps(lowered.rewritten_expr, temp_names),\n ],\n ),\n ],\n range: { start: stmt.getStart(), end: stmt.end },\n };\n}\n\nfunction lower_expression_yields(\n expr: ts.Expression,\n content: string,\n hint: string,\n context: ScriptLoweringContext,\n): LoweredExpression {\n const replacements: Array<{\n start: number;\n end: number;\n text: string;\n }> = [];\n\n const temps: TempBinding[] = [];\n const type_helpers: string[] = [];\n const statements: string[] = [];\n const deps: string[] = [];\n\n collect_yield_star_nodes(expr, (node) => {\n const temp_name = context.next_temp_name(hint);\n const yield_text = slice_start(content, node).trim();\n const type_helper = make_yield_type_helper(yield_text, hint, context);\n\n if (type_helper) {\n type_helpers.push(type_helper.declaration);\n temps.push({ name: temp_name, type: type_helper.type });\n } else {\n temps.push({ name: temp_name });\n }\n\n statements.push(`${temp_name} = ${yield_text};`);\n deps.push(...collect_deps(yield_text));\n replacements.push({\n start: node.getStart(),\n end: node.end,\n text: temp_name,\n });\n });\n\n if (replacements.length === 0) {\n return {\n temps,\n type_helpers,\n rewritten_expr: slice(content, expr).trim(),\n effect_blocks: [],\n };\n }\n\n replacements.sort((a, b) => b.start - a.start);\n\n let text = slice(content, expr);\n\n const offset_in_expr = expr.getFullStart();\n\n for (const replacement of replacements) {\n text = text.slice(0, replacement.start - offset_in_expr) +\n replacement.text +\n text.slice(replacement.end - offset_in_expr);\n }\n\n return {\n temps,\n type_helpers,\n rewritten_expr: text.trim(),\n effect_blocks: [make_effect_block(statements, deps)],\n };\n}\n\nfunction make_awaited_yield_initializer(\n expr: ts.Expression,\n content: string,\n hint: string,\n context: ScriptLoweringContext,\n): { declaration: string; expression: string } {\n const yield_text = extract_yield_star_full_text(expr, content);\n const helper_name = context.next_helper_name(`effect_${hint}`);\n const helper_id = make_script_effect_id(expr, context);\n const deps = collect_deps(yield_text);\n const deps_text = `[${deps.join(\", \")}]`;\n\n return {\n declaration: `function* ${helper_name}() { return (${yield_text}); }`,\n expression: [\n `await ${context.dispatcher_name}().promise({`,\n `id: ${JSON.stringify(helper_id)}, `,\n `deps: ${deps_text}, `,\n `factory: () => ${helper_name}()`,\n `})`,\n ].join(\"\"),\n };\n}\n\nfunction make_yield_type_helper(\n yield_text: string,\n hint: string,\n context: ScriptLoweringContext,\n): { declaration: string; type: string } | undefined {\n if (!context.emit_types) {\n return undefined;\n }\n\n const helper_name = context.next_type_helper_name(hint);\n const effect_text = strip_yield_star(yield_text);\n\n return {\n declaration: `function ${helper_name}() { return (${effect_text}); }`,\n type:\n `${context.effect_name}.Success<ReturnType<typeof ${helper_name}>> | undefined`,\n };\n}\n\nfunction make_unknown_temp(\n name: string,\n context: ScriptLoweringContext,\n): TempBinding {\n return {\n name,\n type: context.emit_types ? \"unknown\" : undefined,\n };\n}\n\nfunction make_state_placeholder(\n rune_name: string,\n type: string | undefined,\n context: ScriptLoweringContext,\n): string {\n if (type) {\n return `${rune_name}<${type}>(undefined)`;\n }\n\n if (context.emit_types) {\n return `${rune_name}<unknown>(undefined)`;\n }\n\n return `${rune_name}(undefined)`;\n}\n\nfunction strip_yield_star(yield_text: string): string {\n return yield_text.replace(/^yield\\*\\s*/, \"\");\n}\n\nfunction make_script_effect_id(\n expr: ts.Expression,\n context: ScriptLoweringContext,\n): string {\n return `${context.filename}:${expr.getStart()}:${expr.end}`;\n}\n\nfunction rewrite_state_rune_as_derived(expression: string): string {\n const state_call = expression.match(/^\\$state(?:\\.raw)?\\(([\\s\\S]*)\\)$/);\n\n if (!state_call) {\n return expression;\n }\n\n return `$derived(${state_call[1]})`;\n}\n\nfunction should_wrap_complex_initializer_as_derived(\n expr: ts.Expression,\n content: string,\n): boolean {\n const text = slice(content, expr).trim();\n\n return !/^\\$derived(?:\\.by)?\\(/.test(text) &&\n !/^\\$inspect(?:\\.trace)?\\(/.test(text);\n}\n\nfunction is_assignment_operator(expr: ts.BinaryExpression): boolean {\n return expr.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&\n expr.operatorToken.kind <= ts.SyntaxKind.LastAssignment;\n}\n\nfunction is_top_level_rune_call(expr: ts.Expression): boolean {\n if (!ts.isCallExpression(expr)) {\n return false;\n }\n\n const callee = expr.expression;\n\n if (ts.isIdentifier(callee)) {\n return callee.text.startsWith(\"$\");\n }\n\n return ts.isPropertyAccessExpression(callee) &&\n ts.isIdentifier(callee.expression) &&\n callee.expression.text.startsWith(\"$\");\n}\n\nfunction make_temp_hint(target: string): string {\n const match = target.match(/[A-Za-z_$][\\w$]*$/);\n\n return match?.[0] ?? \"assignment\";\n}\n\nfunction extract_yield_star_full_text(\n expr: ts.Expression,\n content: string,\n): string {\n let found: string | undefined;\n\n find_yield_star_node(expr, (node) => {\n found = slice_start(content, node).trim();\n });\n\n return found ?? \"undefined\";\n}\n\nfunction make_effect_block(\n statements: string[],\n deps: string[],\n): EffectBlock {\n return {\n statements,\n deps: [...new Set(deps)],\n };\n}\n\nfunction collect_deps(\n expr_text: string,\n excluded_names: readonly string[] = [],\n): string[] {\n const excluded = new Set(excluded_names);\n\n return collect_free_identifiers(expr_text).filter(\n (identifier) =>\n !identifier.startsWith(\"__SER___\") && !excluded.has(identifier),\n );\n}\n\nfunction collect_assignment_target_names(node: ts.Node): string[] {\n if (ts.isIdentifier(node)) {\n return [node.text];\n }\n\n if (ts.isParenthesizedExpression(node)) {\n return collect_assignment_target_names(node.expression);\n }\n\n if (\n ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)\n ) {\n return collect_assignment_target_names(node.expression);\n }\n\n if (ts.isObjectLiteralExpression(node)) {\n return node.properties.flatMap((property) => {\n if (ts.isShorthandPropertyAssignment(property)) {\n return [property.name.text];\n }\n\n if (ts.isPropertyAssignment(property)) {\n return collect_assignment_target_names(property.initializer);\n }\n\n if (ts.isSpreadAssignment(property)) {\n return collect_assignment_target_names(property.expression);\n }\n\n return [];\n });\n }\n\n if (ts.isArrayLiteralExpression(node)) {\n return node.elements.flatMap((element) =>\n ts.isSpreadElement(element)\n ? collect_assignment_target_names(element.expression)\n : collect_assignment_target_names(element)\n );\n }\n\n return [];\n}\n","import { contains_top_level_yield_star } from \"$/detect.ts\";\nimport {\n collect_top_level_binding_names,\n has_local_import_binding,\n make_imports,\n} from \"./imports.ts\";\nimport { create_source_map, slice } from \"./source.ts\";\nimport { AwaitInEffectWorkError, PreprocessError } from \"$/error.ts\";\nimport { make_runtime_block_with_bindings } from \"./runtime-block.ts\";\nimport { contains_top_level_await } from \"./ast.ts\";\nimport { lower_statement } from \"./lower.ts\";\nimport { validate_rune_yield_usage } from \"./runes.ts\";\nimport type {\n BlockRef,\n EffectBlock,\n RuntimeImportBindings,\n ScriptLoweringContext,\n ScriptTransformResult,\n} from \"./types.ts\";\n\nimport MagicString from \"magic-string\";\nimport ts from \"typescript\";\n\nexport type { BlockRef, ScriptTransformResult } from \"./types.ts\";\n\ninterface ScriptTransformOptions {\n emit_types?: boolean;\n}\n\n/**\n * Transforms a `<script effect>` body by extracting top-level `yield*`\n * expressions into `$state` temp bindings and wrapping the lowered\n * assignments in a dependency-tracked `$effect` block.\n *\n * @example\n * ```ts\n * const result = transform_script_effect(\n * `let user = $state(yield* getUser(id));`,\n * \"App.svelte\",\n * );\n * ```\n *\n * @since 2.0.0\n * @param content - The raw `<script effect>` body content.\n * @param filename - The source filename, used in error messages.\n * @param options - Optional transform settings for generated script code.\n * @returns The transformed code and any block references.\n */\nexport function transform_script_effect(\n content: string,\n filename: string,\n options: ScriptTransformOptions = {},\n): ScriptTransformResult {\n let temp_counter = 0;\n\n const source_file = ts.createSourceFile(\n filename,\n content,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n );\n\n const magic = new MagicString(content);\n const effect_blocks: EffectBlock[] = [];\n const block_refs: BlockRef[] = [];\n const top_level_binding_names = collect_top_level_binding_names(source_file);\n const top_level_binding_names_set = new Set(top_level_binding_names);\n const name_allocator = make_name_allocator(top_level_binding_names);\n const emit_types = options.emit_types ?? true;\n\n let has_effect = false;\n let uses_dispatcher_promise = false;\n let uses_effect_types = false;\n\n /** Phase 1: detect imports already provided by the user. */\n const has_effect_import = has_local_import_binding(\n source_file,\n \"effect\",\n \"Effect\",\n );\n\n const has_dispatcher_import = has_local_import_binding(\n source_file,\n \"svelte-effect-runtime/internal/generators\",\n \"get_dispatcher\",\n );\n\n const has_untrack_import = has_local_import_binding(\n source_file,\n \"svelte\",\n \"untrack\",\n );\n\n const reserve_runtime_import = (name: string) =>\n top_level_binding_names_set.has(name)\n ? name_allocator.reserve(make_generated_name(name, \"\"))\n : name_allocator.reserve(name);\n\n const runtime_bindings: RuntimeImportBindings = {\n cancel: name_allocator.reserve(\"__SER___cancel\"),\n dispatcher: has_dispatcher_import\n ? \"get_dispatcher\"\n : reserve_runtime_import(\"get_dispatcher\"),\n dispatcher_value: name_allocator.reserve(\"__SER___dispatcher\"),\n effect: has_effect_import ? \"Effect\" : reserve_runtime_import(\"Effect\"),\n program: name_allocator.reserve(\"__SER___program\"),\n untrack: has_untrack_import ? \"untrack\" : reserve_runtime_import(\"untrack\"),\n };\n\n const context: ScriptLoweringContext = {\n filename,\n dispatcher_name: runtime_bindings.dispatcher,\n effect_name: runtime_bindings.effect,\n emit_types,\n next_helper_name(hint?: string) {\n return name_allocator.reserve(make_generated_name(hint ?? \"helper\", \"\"));\n },\n next_temp_name(hint?: string) {\n const suffix = temp_counter === 0 ? \"\" : `_${temp_counter}`;\n const name = make_generated_name(hint ?? String(temp_counter), suffix);\n\n temp_counter += 1;\n\n return name_allocator.reserve(name);\n },\n next_type_helper_name(hint?: string) {\n return name_allocator.reserve(\n make_generated_name(`type_${hint ?? \"effect\"}`, \"\"),\n );\n },\n };\n\n /** Phase 2: lower every top-level statement that contains `yield*`. */\n for (const stmt of source_file.statements) {\n validate_rune_yield_usage(stmt, content, filename);\n validate_script_yield_boundaries(stmt, content, filename);\n\n const has_top_level_yield_star = contains_top_level_yield_star(stmt);\n\n if (!has_top_level_yield_star) {\n continue;\n }\n\n if (contains_top_level_await(stmt)) {\n const text = slice(content, stmt);\n throw new AwaitInEffectWorkError(filename, text);\n }\n\n has_effect = true;\n const lowered = lower_statement(stmt, content, context);\n\n magic.overwrite(\n lowered.range.start,\n lowered.range.end,\n lowered.rewritten_text,\n );\n\n if (lowered.temps.length > 0 || lowered.type_helpers?.length) {\n const temp_declarations = lowered.temps.map((temp) =>\n temp.type\n ? `let ${temp.name} = $state<${temp.type}>(undefined);`\n : `let ${temp.name} = $state(undefined);`\n );\n\n const prefix = [\n ...(lowered.type_helpers ?? []),\n ...temp_declarations,\n ].join(\"\\n\");\n\n magic.appendLeft(lowered.range.start, prefix + \"\\n\");\n }\n\n effect_blocks.push(...lowered.effect_blocks);\n uses_dispatcher_promise ||= lowered.uses_dispatcher_promise ?? false;\n uses_effect_types ||= lowered.temps.some((temp) =>\n temp.type?.includes(`${runtime_bindings.effect}.Success`) ?? false\n );\n }\n\n if (!has_effect) {\n block_refs.push({ id: filename, kind: \"script\" });\n\n return { code: content, blocks: block_refs };\n }\n\n /** Phase 3: inject runtime imports after the last user import. */\n const imports = make_imports(\n has_effect_import,\n has_dispatcher_import,\n has_untrack_import,\n runtime_bindings,\n {\n needs_dispatcher: effect_blocks.length > 0 || uses_dispatcher_promise,\n needs_effect: effect_blocks.length > 0 || uses_effect_types,\n needs_untrack: effect_blocks.length > 0,\n },\n );\n\n const last_import = [...source_file.statements]\n .reverse()\n .find(ts.isImportDeclaration);\n\n if (imports) {\n if (last_import) {\n magic.appendRight(last_import.end, \"\\n\" + imports);\n } else {\n magic.prepend(imports + \"\\n\");\n }\n }\n\n /** Phase 4: append the runtime program and lifecycle wiring. */\n if (effect_blocks.length > 0) {\n const runtime_block = make_runtime_block_with_bindings(\n effect_blocks,\n runtime_bindings,\n );\n\n magic.append(\"\\n\" + runtime_block);\n }\n\n block_refs.push({ id: filename, kind: \"script\" });\n\n return {\n code: magic.toString(),\n blocks: block_refs,\n map: create_source_map(magic, filename),\n };\n}\n\nfunction validate_script_yield_boundaries(\n stmt: ts.Statement,\n content: string,\n filename: string,\n): void {\n const bad_member = find_class_member_with_yield_star(stmt);\n\n if (!bad_member) {\n return;\n }\n\n throw new PreprocessError(\n [\n `[ASYNC_EFFECT_IN_CLASS_MEMBER]: ${filename}: yield* cannot be used inside class members.`,\n `Class fields and methods are not component top-level reactive work. Move the Effect work into a script effect statement before assigning it to the class instance.`,\n \"\",\n \"Problematic member:\",\n slice(content, bad_member),\n ].join(\"\\n\"),\n filename,\n );\n}\n\nfunction find_class_member_with_yield_star(\n stmt: ts.Statement,\n): ts.Node | undefined {\n let found: ts.Node | undefined;\n\n function visit(node: ts.Node): void {\n if (found) {\n return;\n }\n\n if (\n ts.isPropertyDeclaration(node) &&\n node.initializer &&\n contains_top_level_yield_star(node.initializer)\n ) {\n found = node;\n return;\n }\n\n node.forEachChild(visit);\n }\n\n visit(stmt);\n\n return found;\n}\n\nfunction make_name_allocator(initial_names: readonly string[]): {\n reserve(name: string): string;\n} {\n const used_names = new Set(initial_names);\n\n return {\n reserve(name: string): string {\n let candidate = name;\n let suffix = 1;\n\n while (used_names.has(candidate)) {\n candidate = `${name}_${suffix}`;\n suffix += 1;\n }\n\n used_names.add(candidate);\n\n return candidate;\n },\n };\n}\n\nfunction make_generated_name(hint: string, suffix: string): string {\n const normalized_hint = hint.replace(/[^A-Za-z0-9_$]/g, \"_\");\n const safe_hint = /^[A-Za-z_$]/.test(normalized_hint)\n ? normalized_hint\n : `temp_${normalized_hint}`;\n\n return `__SER___${safe_hint}${suffix}`;\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAgB,kBACd,OACA,UACyB;CAOzB,OANY,MAAM,YAAY;EAC5B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K,WAAW,GAC9C;GACA,QAAQ;GACR;EACF;EAEA,KAAK,aAAa,KAAK;CACzB;CAEA,MAAM,IAAI;CAEV,OAAO;AACT;AAEA,SAAS,oBAAoB,eAE3B;CACA,MAAM,aAAa,IAAI,IAAI,aAAa;CAExC,OAAO,EACL,QAAQ,MAAsB;EAC5B,IAAI,YAAY;EAChB,IAAI,SAAS;EAEb,OAAO,WAAW,IAAI,SAAS,GAAG;GAChC,YAAY,GAAG,KAAK,GAAG;GACvB,UAAU;EACZ;EAEA,WAAW,IAAI,SAAS;EAExB,OAAO;CACT,EACF;AACF;AAEA,SAAS,oBAAoB,MAAc,QAAwB;CACjE,MAAM,kBAAkB,KAAK,QAAQ,mBAAmB,GAAG;CAK3D,OAAO,WAJW,cAAc,KAAK,eAAe,IAChD,kBACA,QAAQ,oBAEkB;AAChC"}
|
|
@@ -11,6 +11,8 @@ import ts from "typescript";
|
|
|
11
11
|
* @param has_dispatcher_import - Whether the user already imports
|
|
12
12
|
* `get_dispatcher`.
|
|
13
13
|
* @param has_untrack_import - Whether the user already imports `untrack`.
|
|
14
|
+
* @param bindings - Local names reserved for generated runtime helpers.
|
|
15
|
+
* @param options - Runtime helper imports required by this transformed script.
|
|
14
16
|
* @returns Newline-separated import statements to inject.
|
|
15
17
|
*/
|
|
16
18
|
function make_imports(has_effect_import, has_dispatcher_import, has_untrack_import, bindings = {
|
|
@@ -20,14 +22,17 @@ function make_imports(has_effect_import, has_dispatcher_import, has_untrack_impo
|
|
|
20
22
|
effect: "Effect",
|
|
21
23
|
program: "__SER___program",
|
|
22
24
|
untrack: "untrack"
|
|
23
|
-
}) {
|
|
25
|
+
}, options = {}) {
|
|
26
|
+
const needs_dispatcher = options.needs_dispatcher ?? true;
|
|
27
|
+
const needs_effect = options.needs_effect ?? true;
|
|
28
|
+
const needs_untrack = options.needs_untrack ?? true;
|
|
24
29
|
const dispatcher_import = bindings.dispatcher === "get_dispatcher" ? `import { get_dispatcher } from "svelte-effect-runtime/internal/generators";` : `import { get_dispatcher as ${bindings.dispatcher} } from "svelte-effect-runtime/internal/generators";`;
|
|
25
30
|
const untrack_import = bindings.untrack === "untrack" ? `import { untrack } from "svelte";` : `import { untrack as ${bindings.untrack} } from "svelte";`;
|
|
26
31
|
const effect_import = has_effect_import ? false : bindings.effect === "Effect" ? `import { Effect } from "effect";` : `import { Effect as ${bindings.effect} } from "effect";`;
|
|
27
32
|
return [
|
|
28
|
-
!has_dispatcher_import && dispatcher_import,
|
|
29
|
-
!has_untrack_import && untrack_import,
|
|
30
|
-
effect_import
|
|
33
|
+
needs_dispatcher && !has_dispatcher_import && dispatcher_import,
|
|
34
|
+
needs_untrack && !has_untrack_import && untrack_import,
|
|
35
|
+
needs_effect && effect_import
|
|
31
36
|
].filter(Boolean).join("\n");
|
|
32
37
|
}
|
|
33
38
|
/**
|
|
@@ -108,12 +113,13 @@ function inject_helpers(magic, content, helpers = [], bindings = HELPERS) {
|
|
|
108
113
|
const import_helpers = unique_import_helpers(helpers);
|
|
109
114
|
const local_helpers = helpers.filter((helper) => !is_import_helper(helper));
|
|
110
115
|
const helper_segments = [
|
|
111
|
-
`import { value as ${bindings.value} } from "svelte-effect-runtime/internal/generators"
|
|
112
|
-
`import { promise as ${bindings.promise} } from "svelte-effect-runtime/internal/generators"
|
|
113
|
-
`import { run as ${bindings.run} } from "svelte-effect-runtime/internal/generators"
|
|
116
|
+
make_import_helper(content, `import { value as ${bindings.value} } from "svelte-effect-runtime/internal/generators";`),
|
|
117
|
+
make_import_helper(content, `import { promise as ${bindings.promise} } from "svelte-effect-runtime/internal/generators";`),
|
|
118
|
+
make_import_helper(content, `import { run as ${bindings.run} } from "svelte-effect-runtime/internal/generators";`),
|
|
114
119
|
...import_helpers,
|
|
115
120
|
...local_helpers
|
|
116
|
-
].map((helper) => typeof helper === "string" ? { text: helper } : helper);
|
|
121
|
+
].filter((helper) => helper !== void 0).map((helper) => typeof helper === "string" ? { text: helper } : helper);
|
|
122
|
+
if (helper_segments.length === 0) return;
|
|
117
123
|
const helper_block = helper_segments.map((segment) => segment.text).join("\n");
|
|
118
124
|
const script_tag = find_instance_script_tag(content);
|
|
119
125
|
if (script_tag) {
|
|
@@ -175,6 +181,10 @@ function create_relocations(replacements, helper_insertion) {
|
|
|
175
181
|
})) ?? [];
|
|
176
182
|
return [...replacement_relocations, ...helper_relocations];
|
|
177
183
|
}
|
|
184
|
+
function make_import_helper(content, import_text) {
|
|
185
|
+
if (content.includes(import_text)) return;
|
|
186
|
+
return import_text;
|
|
187
|
+
}
|
|
178
188
|
function make_insertion_relocations(segments, prefix) {
|
|
179
189
|
const relocations = [];
|
|
180
190
|
let offset = prefix.length;
|
|
@@ -1671,4 +1681,4 @@ function transform_markup_effect(content, filename) {
|
|
|
1671
1681
|
//#endregion
|
|
1672
1682
|
export { find_yield_star_node as a, AsyncEffectInSyncRuneError as c, collect_top_level_binding_names as d, has_local_import_binding as f, extract_binding_names as i, AwaitInEffectWorkError as l, collect_yield_star_nodes as n, is_yield_star_expression as o, make_imports as p, contains_top_level_await as r, collect_free_identifiers as s, transform_markup_effect as t, PreprocessError as u };
|
|
1673
1683
|
|
|
1674
|
-
//# sourceMappingURL=transform-
|
|
1684
|
+
//# sourceMappingURL=transform-CMvL4SBp.js.map
|