svelte-effect-runtime 1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-client.js","names":[],"sources":["../../../modules/svelte-effect-runtime/internal/remote-client.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport { tick } from \"svelte\";\nimport { create_remote_effect_from_promise } from \"../client.ts\";\nimport {\n create_remote_domain_error,\n create_remote_http_error,\n create_remote_transport_error,\n create_remote_validation_error,\n type FormIssue,\n is_remote_validation_issue,\n is_serialized_remote_failure_envelope,\n REMOTE_ERROR_DECODER,\n type RemoteFailure,\n} from \"./remote-shared.ts\";\n\ntype AnyCallable = (...args: Array<unknown>) => unknown;\n\ntype Decode_remote_payload = <ErrorType = unknown>(\n encoded: string,\n) => ErrorType;\n\ninterface HttpErrorLike {\n readonly body?: unknown;\n readonly status?: number;\n}\n\ninterface RedirectLike {\n readonly location: string;\n readonly status: number;\n}\n\ninterface Remote_request_dependencies {\n readonly app?: {\n readonly decoders?: Record<string, unknown>;\n readonly hooks?: {\n readonly transport?: Record<string, unknown>;\n };\n };\n readonly app_dir: string;\n readonly apply_refreshes?: (value: string) => void;\n readonly base: string;\n readonly get_remote_request_headers: () => HeadersInit;\n readonly remote_request: (url: string, headers: HeadersInit) => Promise<string>;\n readonly stringify_remote_arg: (\n value: unknown,\n transport: unknown,\n sort?: boolean,\n ) => string;\n}\n\ntype Query_adapter_mode = \"query\" | \"query_batch\" | \"prerender\";\n\ntype Form_request_dependencies = Remote_request_dependencies & {\n readonly app: {\n readonly decoders?: Record<string, unknown>;\n readonly encoders?: Record<string, unknown>;\n };\n readonly app_dir: string;\n readonly apply_refreshes: (value: string) => void;\n readonly base: string;\n readonly binary_form_content_type: string;\n readonly goto: (url: string, options?: unknown, code?: number) => void;\n readonly invalidate_all: () => Promise<void> | void;\n readonly serialize_binary_form: (\n data: unknown,\n meta: Record<string, unknown>,\n ) => {\n readonly blob: Blob;\n };\n};\n\ninterface Attached_form_tracker {\n current: HTMLFormElement | null;\n}\n\nfunction log_remote_client_step(\n step: string,\n details?: Record<string, unknown>,\n): void {\n console.log(\"[svelte-effect-runtime][remote-client]\", step, details ?? {});\n}\n\nfunction define_hidden_property<Value extends object, Property>(\n value: Value,\n key: string | symbol,\n property: Property,\n): Value {\n Object.defineProperty(value, key, {\n value: property,\n enumerable: false,\n });\n\n return value;\n}\n\nfunction define_remote_error_decoder<Value extends object>(\n value: Value,\n decode_payload: Decode_remote_payload,\n): Value {\n return define_hidden_property(value, REMOTE_ERROR_DECODER, decode_payload);\n}\n\nfunction is_http_error_like(value: unknown): value is HttpErrorLike {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as { status?: unknown }).status === \"number\",\n );\n}\n\nfunction is_redirect_like(value: unknown): value is RedirectLike {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as { location?: unknown }).location === \"string\" &&\n typeof (value as { status?: unknown }).status === \"number\",\n );\n}\n\nfunction get_error_status(value: unknown): number {\n return is_http_error_like(value) ? value.status ?? 500 : 500;\n}\n\nfunction decode_remote_error<ErrorType>(\n error: unknown,\n decode_payload: Decode_remote_payload,\n): RemoteFailure<ErrorType> {\n log_remote_client_step(\"decode_remote_error:start\", {\n error,\n });\n\n if (is_http_error_like(error)) {\n const body = error.body;\n\n if (is_serialized_remote_failure_envelope(body)) {\n try {\n return create_remote_domain_error<ErrorType>(\n decode_payload<ErrorType>(body.encoded),\n get_error_status(error),\n );\n } catch (cause) {\n return create_remote_transport_error(cause, body);\n }\n }\n\n if (get_error_status(error) === 400) {\n return create_remote_validation_error([], {\n body,\n status: 400,\n });\n }\n\n return create_remote_http_error(error, {\n body,\n status: get_error_status(error),\n });\n }\n\n const decoded = create_remote_http_error(error);\n log_remote_client_step(\"decode_remote_error:http_error\", {\n decoded,\n });\n return decoded;\n}\n\nfunction create_effect_call<Success, ErrorType>(\n create_promise: () => PromiseLike<Success>,\n decode_payload: Decode_remote_payload,\n): Effect.Effect<Success, RemoteFailure<ErrorType>, never> {\n return create_remote_effect_from_promise<Success, ErrorType>(\n () => {\n log_remote_client_step(\"create_effect_call:start\");\n return create_promise();\n },\n (error) => decode_remote_error<ErrorType>(error, decode_payload),\n );\n}\n\nfunction create_decoded_native_callable(\n native: AnyCallable,\n decode_payload: Decode_remote_payload,\n): AnyCallable {\n const wrapped = ((...args: Array<unknown>) => {\n const result = native(...args);\n\n if (\n result && (typeof result === \"object\" || typeof result === \"function\")\n ) {\n define_remote_error_decoder(result as object, decode_payload);\n }\n\n return result;\n }) as AnyCallable;\n\n define_hidden_property(wrapped, \"native\", native);\n define_remote_error_decoder(wrapped as object, decode_payload);\n\n return wrapped;\n}\n\nfunction get_transport(\n dependencies?: Remote_request_dependencies,\n): Record<string, unknown> {\n return dependencies?.app?.hooks?.transport ?? {};\n}\n\nfunction stringify_remote_payload(\n arg: unknown,\n dependencies: Remote_request_dependencies,\n sort = true,\n): string {\n if (arg === undefined) {\n return \"\";\n }\n\n return dependencies.stringify_remote_arg(arg, get_transport(dependencies), sort);\n}\n\nasync function execute_query_request<Success>(\n id: string,\n arg: unknown,\n decode_payload: Decode_remote_payload,\n dependencies: Remote_request_dependencies,\n): Promise<Success> {\n const payload = stringify_remote_payload(arg, dependencies);\n const url =\n `${dependencies.base}/${dependencies.app_dir}/remote/${id}${\n payload ? `?payload=${payload}` : \"\"\n }`;\n const encoded = await dependencies.remote_request(\n url,\n dependencies.get_remote_request_headers(),\n );\n\n return decode_payload<Success>(encoded);\n}\n\nasync function execute_query_batch_request<Success>(\n id: string,\n arg: unknown,\n decode_payload: Decode_remote_payload,\n dependencies: Remote_request_dependencies,\n): Promise<Success> {\n const payload = stringify_remote_payload(arg, dependencies);\n const response = await fetch(`${dependencies.base}/${dependencies.app_dir}/remote/${id}`, {\n method: \"POST\",\n body: JSON.stringify({\n payloads: [payload],\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n ...dependencies.get_remote_request_headers(),\n },\n });\n\n if (!response.ok) {\n throw new Error(\"Failed to execute batch query\");\n }\n\n const result = await response.json() as {\n readonly type: string;\n readonly result?: string;\n readonly status?: number;\n readonly error?: unknown;\n readonly location?: string;\n };\n\n if (result.type === \"error\") {\n throw {\n body: result.error,\n status: result.status ?? 500,\n };\n }\n\n if (result.type === \"redirect\") {\n throw {\n location: result.location,\n status: 307,\n };\n }\n\n const entries = decode_payload<Array<{\n readonly data?: Success;\n readonly error?: unknown;\n readonly status?: number;\n readonly type: string;\n }>>(result.result ?? \"\");\n const first = entries[0];\n\n if (!first) {\n throw new Error(\"Batch query returned no entries.\");\n }\n\n if (first.type === \"error\") {\n throw {\n body: first.error,\n status: first.status ?? 500,\n };\n }\n\n return first.data as Success;\n}\n\nasync function execute_prerender_request<Success>(\n id: string,\n arg: unknown,\n decode_payload: Decode_remote_payload,\n dependencies: Remote_request_dependencies,\n): Promise<Success> {\n const payload = stringify_remote_payload(arg, dependencies);\n const url =\n `${dependencies.base}/${dependencies.app_dir}/remote/${id}${\n payload ? `/${payload}` : \"\"\n }`;\n const encoded = await dependencies.remote_request(\n url,\n dependencies.get_remote_request_headers(),\n );\n\n return decode_payload<Success>(encoded);\n}\n\nfunction create_query_request<Success>(\n mode: Query_adapter_mode,\n id: string,\n arg: unknown,\n decode_payload: Decode_remote_payload,\n dependencies?: Remote_request_dependencies,\n native_with_decoder?: AnyCallable,\n): Promise<Success> {\n if (!dependencies || !native_with_decoder) {\n return Promise.resolve(native_with_decoder?.(arg) as Success);\n }\n\n switch (mode) {\n case \"query\":\n return execute_query_request<Success>(id, arg, decode_payload, dependencies);\n case \"query_batch\":\n return execute_query_batch_request<Success>(id, arg, decode_payload, dependencies);\n case \"prerender\":\n return execute_prerender_request<Success>(id, arg, decode_payload, dependencies);\n }\n}\n\nasync function execute_command_request<Success>(\n id: string,\n arg: unknown,\n decode_payload: Decode_remote_payload,\n dependencies: Remote_request_dependencies,\n): Promise<Success> {\n const response = await fetch(`${dependencies.base}/${dependencies.app_dir}/remote/${id}`, {\n method: \"POST\",\n body: JSON.stringify({\n payload: stringify_remote_payload(arg, dependencies, false),\n refreshes: [],\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n ...dependencies.get_remote_request_headers(),\n },\n });\n\n if (!response.ok) {\n throw new Error(\"Failed to execute remote command\");\n }\n\n const result = await response.json() as {\n readonly type: string;\n readonly result?: string;\n readonly status?: number;\n readonly error?: unknown;\n readonly refreshes?: string;\n };\n\n if (result.type === \"error\") {\n throw {\n body: result.error,\n status: result.status ?? 500,\n };\n }\n\n if (result.type === \"redirect\") {\n throw new Error(\n \"Redirects are not allowed in commands. Return a result instead and use goto on the client.\",\n );\n }\n\n if (result.refreshes) {\n dependencies.apply_refreshes?.(result.refreshes);\n }\n\n return decode_payload<Success>(result.result ?? \"\");\n}\n\nexport function create_remote_query_adapter(\n native_query_factory: (id: string) => AnyCallable,\n decode_payload: Decode_remote_payload,\n dependencies?: Remote_request_dependencies,\n mode: Query_adapter_mode = \"query\",\n) {\n return (id: string) => {\n const native = native_query_factory(id);\n const native_with_decoder = create_decoded_native_callable(\n native,\n decode_payload,\n );\n const wrapped = ((arg?: unknown) =>\n create_effect_call(\n () =>\n create_query_request(\n mode,\n id,\n arg,\n decode_payload,\n dependencies,\n native_with_decoder,\n ),\n decode_payload,\n )) as AnyCallable;\n\n define_hidden_property(wrapped, \"native\", native_with_decoder);\n\n return wrapped;\n };\n}\n\nexport function create_remote_command_adapter(\n native_command_factory: (id: string) => AnyCallable,\n decode_payload: Decode_remote_payload,\n dependencies?: Remote_request_dependencies,\n) {\n return (id: string) => {\n const native = native_command_factory(id);\n const native_with_decoder = create_decoded_native_callable(\n native,\n decode_payload,\n );\n let local_pending = 0;\n const wrapped = ((arg?: unknown) =>\n create_effect_call(\n async () => {\n local_pending += 1;\n\n try {\n if (!dependencies) {\n return await Promise.resolve(native_with_decoder(arg));\n }\n\n return await execute_command_request(\n id,\n arg,\n decode_payload,\n dependencies,\n );\n } finally {\n local_pending -= 1;\n }\n },\n decode_payload,\n )) as AnyCallable;\n\n define_hidden_property(wrapped, \"native\", native_with_decoder);\n Object.defineProperty(wrapped, \"pending\", {\n get: () => ((native as { pending?: number }).pending ?? 0) + local_pending,\n });\n\n return wrapped;\n };\n}\n\nfunction normalize_form_issues(issues: unknown): ReadonlyArray<FormIssue> {\n if (!Array.isArray(issues)) {\n return [];\n }\n\n return issues.flatMap((issue) =>\n is_remote_validation_issue(issue)\n ? [{\n message: issue.message,\n path: [...issue.path],\n }]\n : []\n );\n}\n\nfunction get_root_form_issues(\n native: {\n readonly fields?: {\n readonly allIssues?: unknown;\n };\n },\n): ReadonlyArray<FormIssue> {\n return normalize_form_issues(native.fields?.allIssues);\n}\n\nfunction get_attachment(\n value: Record<string | symbol, unknown>,\n): (form: HTMLFormElement) => void | (() => void) {\n for (const symbol of Object.getOwnPropertySymbols(value)) {\n const candidate = value[symbol];\n\n if (typeof candidate === \"function\") {\n return candidate as (form: HTMLFormElement) => void | (() => void);\n }\n }\n\n throw new Error(\n \"Failed to find the Svelte attachment for the remote form enhancement.\",\n );\n}\n\nfunction build_form_field_name(path: ReadonlyArray<string | number>): string {\n let name = \"\";\n\n for (const segment of path) {\n if (typeof segment === \"number\") {\n name += `[${segment}]`;\n continue;\n }\n\n name += name === \"\" ? segment : `.${segment}`;\n }\n\n return name;\n}\n\nfunction append_hidden_input(\n form: HTMLFormElement,\n name: string,\n value: string,\n): void {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = name;\n input.value = value;\n form.append(input);\n}\n\nfunction append_file_input(\n form: HTMLFormElement,\n name: string,\n value: File,\n): void {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.name = name;\n\n if (typeof DataTransfer === \"function\") {\n const transfer = new DataTransfer();\n transfer.items.add(value);\n\n try {\n input.files = transfer.files;\n } catch {\n // ignore and fall back below\n }\n }\n\n if (input.files?.length) {\n form.append(input);\n return;\n }\n\n append_hidden_input(form, name, value.name);\n}\n\nfunction append_form_value(\n form: HTMLFormElement,\n value: unknown,\n path: ReadonlyArray<string | number>,\n): void {\n if (value === undefined) {\n return;\n }\n\n if (value instanceof File) {\n append_file_input(form, build_form_field_name(path), value);\n return;\n }\n\n if (Array.isArray(value)) {\n value.forEach((entry, index) => {\n append_form_value(form, entry, [...path, index]);\n });\n return;\n }\n\n if (value && typeof value === \"object\") {\n for (\n const [key, entry] of Object.entries(value as Record<string, unknown>)\n ) {\n append_form_value(form, entry, [...path, key]);\n }\n return;\n }\n\n const base_name = build_form_field_name(path);\n\n if (typeof value === \"number\") {\n append_hidden_input(form, `n:${base_name}`, String(value));\n return;\n }\n\n if (typeof value === \"boolean\") {\n append_hidden_input(form, `b:${base_name}`, value ? \"on\" : \"\");\n return;\n }\n\n append_hidden_input(\n form,\n base_name,\n value === null ? \"\" : String(value),\n );\n}\n\nfunction apply_input_to_fields(fields: unknown, input: unknown): void {\n if (!fields || typeof fields !== \"object\") {\n return;\n }\n\n const maybe_field = fields as {\n readonly set?: (value: unknown) => void;\n };\n\n if (typeof maybe_field.set === \"function\") {\n maybe_field.set(input);\n return;\n }\n\n if (!input || typeof input !== \"object\") {\n return;\n }\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n apply_input_to_fields(\n (fields as Record<string, unknown>)[key],\n value,\n );\n }\n}\n\ntype Submitter_like = {\n click(): void;\n} & Record<string, unknown>;\n\nfunction is_submitter_like(value: unknown): value is Submitter_like {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as { click?: unknown }).click === \"function\",\n );\n}\n\nfunction get_submitter(\n form: HTMLFormElement,\n): Submitter_like | undefined {\n const submitter = form.querySelector(\"button:not([type]), [type='submit']\");\n return is_submitter_like(submitter) ? submitter : undefined;\n}\n\nfunction request_form_submit(form: HTMLFormElement): void {\n const submitter = get_submitter(form);\n log_remote_client_step(\"request_form_submit\", {\n action: form.action,\n has_submitter: Boolean(submitter),\n submitter,\n });\n\n if (typeof SubmitEvent === \"function\") {\n form.dispatchEvent(\n new SubmitEvent(\"submit\", {\n bubbles: true,\n cancelable: true,\n submitter: submitter as HTMLElement | null | undefined,\n }),\n );\n return;\n }\n\n const event = new Event(\"submit\", {\n bubbles: true,\n cancelable: true,\n }) as Event & {\n readonly submitter?: Submitter_like;\n };\n Object.defineProperty(event, \"submitter\", {\n configurable: true,\n value: submitter,\n });\n form.dispatchEvent(event);\n}\n\nasync function wait_for_pending_settle(\n native: {\n readonly pending?: number;\n },\n): Promise<void> {\n await tick();\n\n while ((native.pending ?? 0) > 0) {\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n await tick();\n}\n\nasync function submit_attached_form<Success, ErrorType>(\n form: {\n readonly native: {\n readonly fields?: {\n readonly allIssues?: unknown;\n } & Record<string, unknown>;\n readonly pending?: number;\n readonly result?: Success;\n };\n },\n element: HTMLFormElement,\n input: unknown,\n): Promise<Effect.Effect<Success, RemoteFailure<ErrorType>, never>> {\n log_remote_client_step(\"submit_attached_form:start\", {\n action: element.action,\n input,\n });\n\n if (input !== undefined) {\n apply_input_to_fields(form.native.fields, input);\n }\n\n await tick();\n request_form_submit(element);\n await wait_for_pending_settle(form.native);\n\n const issues = get_root_form_issues(form.native);\n log_remote_client_step(\"submit_attached_form:after_submit\", {\n issues,\n pending: form.native.pending ?? 0,\n result: form.native.result,\n });\n\n if (issues.length > 0) {\n return Effect.fail(\n create_remote_validation_error(issues, {\n body: issues,\n status: 400,\n }),\n );\n }\n\n return Effect.succeed(form.native.result as Success);\n}\n\nfunction create_form_submit_effect<Success, ErrorType>(\n form: {\n readonly native: {\n readonly action: string;\n readonly result?: Success;\n readonly fields?: {\n readonly allIssues?: unknown;\n };\n enhance(\n callback: (args: {\n readonly form: HTMLFormElement;\n readonly data: unknown;\n readonly submit: () => Promise<unknown>;\n }) => Promise<void> | void,\n ): Record<string | symbol, unknown>;\n };\n },\n input: unknown,\n decode_payload: Decode_remote_payload,\n attached_form_tracker: Attached_form_tracker,\n _dependencies: Form_request_dependencies,\n): Effect.Effect<Success, RemoteFailure<ErrorType>, never> {\n return Effect.async<Success, RemoteFailure<ErrorType>>((resume) => {\n log_remote_client_step(\"create_form_submit_effect:start\", {\n action: form.native.action,\n input,\n attached: Boolean(attached_form_tracker.current),\n });\n\n if (typeof document === \"undefined\") {\n resume(\n Effect.fail(\n create_remote_http_error(\n new Error(\"Programmatic remote form submission requires a DOM.\"),\n ),\n ),\n );\n return;\n }\n\n let settled = false;\n let dispose_attachment: void | (() => void);\n const temp_form = document.createElement(\"form\");\n temp_form.method = \"POST\";\n temp_form.action = form.native.action;\n temp_form.hidden = true;\n document.body.append(temp_form);\n\n const cleanup = () => {\n if (typeof dispose_attachment === \"function\") {\n dispose_attachment();\n }\n\n temp_form.remove();\n };\n\n const finish = (\n effect: Effect.Effect<Success, RemoteFailure<ErrorType>, never>,\n ) => {\n if (settled) {\n return;\n }\n\n settled = true;\n cleanup();\n resume(effect);\n };\n\n try {\n const attached_form = attached_form_tracker.current;\n\n if (attached_form) {\n log_remote_client_step(\"create_form_submit_effect:attached_form_branch\", {\n action: attached_form.action,\n });\n void submit_attached_form<Success, ErrorType>(\n form,\n attached_form,\n input,\n ).then(finish, (error) => {\n finish(\n Effect.fail(decode_remote_error<ErrorType>(error, decode_payload)),\n );\n });\n return;\n }\n\n log_remote_client_step(\"create_form_submit_effect:detached_fallback_branch\", {\n action: form.native.action,\n });\n const enhanced = form.native.enhance(async ({ submit }) => {\n try {\n log_remote_client_step(\"create_form_submit_effect:fallback_submit:start\", {\n action: form.native.action,\n });\n await submit();\n const issues = get_root_form_issues(form.native);\n log_remote_client_step(\"create_form_submit_effect:fallback_submit:after\", {\n issues,\n result: form.native.result,\n });\n\n if (issues.length > 0) {\n finish(\n Effect.fail(\n create_remote_validation_error(issues, {\n body: issues,\n status: 400,\n }),\n ),\n );\n return;\n }\n\n finish(Effect.succeed(form.native.result as Success));\n } catch (error) {\n if (is_redirect_like(error)) {\n finish(Effect.die(error));\n return;\n }\n\n finish(\n Effect.fail(decode_remote_error<ErrorType>(error, decode_payload)),\n );\n }\n });\n\n dispose_attachment = get_attachment(enhanced)(temp_form);\n\n if (input && typeof input === \"object\") {\n append_form_value(temp_form, input, []);\n }\n\n const submitter = document.createElement(\"button\");\n submitter.type = \"submit\";\n temp_form.append(submitter);\n if (typeof temp_form.requestSubmit === \"function\") {\n temp_form.requestSubmit(submitter);\n } else {\n submitter.click();\n }\n } catch (error) {\n log_remote_client_step(\"create_form_submit_effect:error\", {\n error,\n });\n finish(\n Effect.fail(decode_remote_error<ErrorType>(error, decode_payload)),\n );\n }\n });\n}\n\nfunction wrap_native_form(\n native: Record<string, unknown>,\n decode_payload: Decode_remote_payload,\n dependencies: Form_request_dependencies,\n) {\n const attached_form_tracker: Attached_form_tracker = {\n current: null,\n };\n const wrapped_symbol_properties = new Map<symbol, unknown>();\n const wrapped = new Proxy({} as Record<string, unknown>, {\n get(_target, property, receiver) {\n if (property === \"native\") {\n return native;\n }\n\n if (property === \"submit\") {\n return (input: unknown) =>\n create_form_submit_effect(\n receiver as {\n readonly native: {\n readonly action: string;\n readonly result?: unknown;\n readonly fields?: {\n readonly allIssues?: unknown;\n };\n enhance(\n callback: (args: {\n readonly form: HTMLFormElement;\n readonly data: unknown;\n readonly submit: () => Promise<unknown>;\n }) => Promise<void> | void,\n ): Record<string | symbol, unknown>;\n };\n },\n input,\n decode_payload,\n attached_form_tracker,\n dependencies,\n );\n }\n\n if (typeof property === \"symbol\") {\n if (wrapped_symbol_properties.has(property)) {\n return wrapped_symbol_properties.get(property);\n }\n\n const native_value = Reflect.get(native, property, native);\n\n if (typeof native_value === \"function\") {\n const wrapped_attachment = (element: HTMLFormElement) => {\n log_remote_client_step(\"wrap_native_form:attach\", {\n action: element.action,\n native_action: (native as { action?: unknown }).action,\n });\n attached_form_tracker.current = element;\n const cleanup = native_value.call(native, element);\n\n return () => {\n log_remote_client_step(\"wrap_native_form:detach\", {\n action: element.action,\n });\n if (attached_form_tracker.current === element) {\n attached_form_tracker.current = null;\n }\n\n if (typeof cleanup === \"function\") {\n cleanup();\n }\n };\n };\n\n wrapped_symbol_properties.set(property, wrapped_attachment);\n return wrapped_attachment;\n }\n }\n\n if (property === \"for\") {\n const native_for = Reflect.get(native, property, native);\n\n if (typeof native_for === \"function\") {\n return (key: string | number) =>\n wrap_native_form(\n native_for.call(native, key) as Record<string, unknown>,\n decode_payload,\n dependencies,\n );\n }\n }\n\n return Reflect.get(native, property, native);\n },\n has(_target, property) {\n if (\n property === \"native\" ||\n property === \"submit\" ||\n property === \"for\"\n ) {\n return true;\n }\n\n return Reflect.has(native, property);\n },\n ownKeys() {\n return Reflect.ownKeys(native);\n },\n getOwnPropertyDescriptor(_target, property) {\n if (\n property === \"native\" ||\n property === \"submit\" ||\n property === \"for\"\n ) {\n return {\n configurable: true,\n enumerable: false,\n writable: false,\n };\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(native, property);\n\n if (!descriptor) {\n return descriptor;\n }\n\n return {\n ...descriptor,\n configurable: true,\n };\n },\n });\n\n return wrapped as Record<string, unknown>;\n}\n\nexport function create_remote_form_adapter(\n native_form_factory: (id: string) => Record<string, unknown>,\n decode_payload: Decode_remote_payload,\n dependencies: Form_request_dependencies,\n) {\n return (id: string) => {\n const native = native_form_factory(id);\n return wrap_native_form(native, decode_payload, dependencies);\n };\n}\n"],"mappings":";;;;;AA2EA,SAAS,uBACP,MACA,SACM;AACN,SAAQ,IAAI,0CAA0C,MAAM,WAAW,EAAE,CAAC;;AAG5E,SAAS,uBACP,OACA,KACA,UACO;AACP,QAAO,eAAe,OAAO,KAAK;EAChC,OAAO;EACP,YAAY;EACb,CAAC;AAEF,QAAO;;AAGT,SAAS,4BACP,OACA,gBACO;AACP,QAAO,uBAAuB,OAAO,sBAAsB,eAAe;;AAG5E,SAAS,mBAAmB,OAAwC;AAClE,QAAO,QACL,SACE,OAAO,UAAU,YACjB,OAAQ,MAA+B,WAAW,SACrD;;AAGH,SAAS,iBAAiB,OAAuC;AAC/D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ER = "__svelte_effect_remote__";
2
+ export declare const REMOTE_ERROR_DECODER: unique symbol;
3
+ export interface FormIssue {
4
+ readonly message: string;
5
+ readonly path: ReadonlyArray<string | number>;
6
+ }
7
+ export interface FormError<SchemaType = unknown> {
8
+ readonly _tag: "FormError";
9
+ readonly issues: ReadonlyArray<FormIssue>;
10
+ readonly _schema?: SchemaType | undefined;
11
+ }
12
+ export interface RemoteDomainError<ErrorType = unknown> {
13
+ readonly _tag: "RemoteDomainError";
14
+ readonly cause: ErrorType;
15
+ readonly status: number;
16
+ }
17
+ export interface RemoteValidationError {
18
+ readonly _tag: "RemoteValidationError";
19
+ readonly body?: unknown;
20
+ readonly issues: ReadonlyArray<FormIssue>;
21
+ readonly status: number;
22
+ }
23
+ export interface RemoteHttpError {
24
+ readonly _tag: "RemoteHttpError";
25
+ readonly body?: unknown;
26
+ readonly cause: unknown;
27
+ readonly status: number;
28
+ }
29
+ export interface RemoteTransportError {
30
+ readonly _tag: "RemoteTransportError";
31
+ readonly body?: unknown;
32
+ readonly cause: unknown;
33
+ }
34
+ export type RemoteFailure<ErrorType = unknown> = RemoteDomainError<ErrorType> | RemoteValidationError | RemoteHttpError | RemoteTransportError;
35
+ export interface SerializedRemoteFailureEnvelope {
36
+ readonly [EFFECT_REMOTE_ERROR_MARKER]: true;
37
+ readonly encoded: string;
38
+ }
39
+ export declare function create_form_error<SchemaType = unknown>(...issues: Array<FormIssue>): FormError<SchemaType>;
40
+ export declare function create_remote_domain_error<ErrorType = unknown>(cause: ErrorType, status: number): RemoteDomainError<ErrorType>;
41
+ export declare function create_remote_validation_error(issues: ReadonlyArray<FormIssue>, options?: {
42
+ body?: unknown;
43
+ status?: number;
44
+ }): RemoteValidationError;
45
+ export declare function create_remote_http_error(cause: unknown, options?: {
46
+ body?: unknown;
47
+ status?: number;
48
+ }): RemoteHttpError;
49
+ export declare function create_remote_transport_error(cause: unknown, body?: unknown): RemoteTransportError;
50
+ export declare function create_serialized_remote_failure_envelope(encoded: string): SerializedRemoteFailureEnvelope;
51
+ export declare function is_form_error(value: unknown): value is FormError;
52
+ export declare function is_serialized_remote_failure_envelope(value: unknown): value is SerializedRemoteFailureEnvelope;
53
+ export declare function is_remote_validation_issue(value: unknown): value is FormIssue;
@@ -0,0 +1,58 @@
1
+ //#region internal/remote-shared.ts
2
+ const EFFECT_REMOTE_ERROR_MARKER = "__svelte_effect_remote__";
3
+ const REMOTE_ERROR_DECODER = Symbol.for("svelte-effect-runtime/remote-error-decoder");
4
+ function create_form_error(...issues) {
5
+ return {
6
+ _tag: "FormError",
7
+ issues
8
+ };
9
+ }
10
+ function create_remote_domain_error(cause, status) {
11
+ return {
12
+ _tag: "RemoteDomainError",
13
+ cause,
14
+ status
15
+ };
16
+ }
17
+ function create_remote_validation_error(issues, options = {}) {
18
+ return {
19
+ _tag: "RemoteValidationError",
20
+ body: options.body,
21
+ issues,
22
+ status: options.status ?? 400
23
+ };
24
+ }
25
+ function create_remote_http_error(cause, options = {}) {
26
+ return {
27
+ _tag: "RemoteHttpError",
28
+ body: options.body,
29
+ cause,
30
+ status: options.status ?? 500
31
+ };
32
+ }
33
+ function create_remote_transport_error(cause, body) {
34
+ return {
35
+ _tag: "RemoteTransportError",
36
+ body,
37
+ cause
38
+ };
39
+ }
40
+ function create_serialized_remote_failure_envelope(encoded) {
41
+ return {
42
+ [EFFECT_REMOTE_ERROR_MARKER]: true,
43
+ encoded
44
+ };
45
+ }
46
+ function is_form_error(value) {
47
+ return Boolean(value && typeof value === "object" && value._tag === "FormError" && Array.isArray(value.issues));
48
+ }
49
+ function is_serialized_remote_failure_envelope(value) {
50
+ return Boolean(value && typeof value === "object" && "__svelte_effect_remote__" in value && value["__svelte_effect_remote__"] === true && typeof value.encoded === "string");
51
+ }
52
+ function is_remote_validation_issue(value) {
53
+ return Boolean(value && typeof value === "object" && typeof value.message === "string" && Array.isArray(value.path));
54
+ }
55
+ //#endregion
56
+ export { EFFECT_REMOTE_ERROR_MARKER, REMOTE_ERROR_DECODER, create_form_error, create_remote_domain_error, create_remote_http_error, create_remote_transport_error, create_remote_validation_error, create_serialized_remote_failure_envelope, is_form_error, is_remote_validation_issue, is_serialized_remote_failure_envelope };
57
+
58
+ //# sourceMappingURL=remote-shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-shared.js","names":[],"sources":["../../../modules/svelte-effect-runtime/internal/remote-shared.ts"],"sourcesContent":["export const EFFECT_REMOTE_ERROR_MARKER = \"__svelte_effect_remote__\";\nexport const REMOTE_ERROR_DECODER = Symbol.for(\n \"svelte-effect-runtime/remote-error-decoder\",\n);\n\nexport interface FormIssue {\n readonly message: string;\n readonly path: ReadonlyArray<string | number>;\n}\n\nexport interface FormError<SchemaType = unknown> {\n readonly _tag: \"FormError\";\n readonly issues: ReadonlyArray<FormIssue>;\n readonly _schema?: SchemaType | undefined;\n}\n\nexport interface RemoteDomainError<ErrorType = unknown> {\n readonly _tag: \"RemoteDomainError\";\n readonly cause: ErrorType;\n readonly status: number;\n}\n\nexport interface RemoteValidationError {\n readonly _tag: \"RemoteValidationError\";\n readonly body?: unknown;\n readonly issues: ReadonlyArray<FormIssue>;\n readonly status: number;\n}\n\nexport interface RemoteHttpError {\n readonly _tag: \"RemoteHttpError\";\n readonly body?: unknown;\n readonly cause: unknown;\n readonly status: number;\n}\n\nexport interface RemoteTransportError {\n readonly _tag: \"RemoteTransportError\";\n readonly body?: unknown;\n readonly cause: unknown;\n}\n\nexport type RemoteFailure<ErrorType = unknown> =\n | RemoteDomainError<ErrorType>\n | RemoteValidationError\n | RemoteHttpError\n | RemoteTransportError;\n\nexport interface SerializedRemoteFailureEnvelope {\n readonly [EFFECT_REMOTE_ERROR_MARKER]: true;\n readonly encoded: string;\n}\n\nexport function create_form_error<SchemaType = unknown>(\n ...issues: Array<FormIssue>\n): FormError<SchemaType> {\n return {\n _tag: \"FormError\",\n issues,\n };\n}\n\nexport function create_remote_domain_error<ErrorType = unknown>(\n cause: ErrorType,\n status: number,\n): RemoteDomainError<ErrorType> {\n return {\n _tag: \"RemoteDomainError\",\n cause,\n status,\n };\n}\n\nexport function create_remote_validation_error(\n issues: ReadonlyArray<FormIssue>,\n options: {\n body?: unknown;\n status?: number;\n } = {},\n): RemoteValidationError {\n return {\n _tag: \"RemoteValidationError\",\n body: options.body,\n issues,\n status: options.status ?? 400,\n };\n}\n\nexport function create_remote_http_error(\n cause: unknown,\n options: {\n body?: unknown;\n status?: number;\n } = {},\n): RemoteHttpError {\n return {\n _tag: \"RemoteHttpError\",\n body: options.body,\n cause,\n status: options.status ?? 500,\n };\n}\n\nexport function create_remote_transport_error(\n cause: unknown,\n body?: unknown,\n): RemoteTransportError {\n return {\n _tag: \"RemoteTransportError\",\n body,\n cause,\n };\n}\n\nexport function create_serialized_remote_failure_envelope(\n encoded: string,\n): SerializedRemoteFailureEnvelope {\n return {\n [EFFECT_REMOTE_ERROR_MARKER]: true,\n encoded,\n };\n}\n\nexport function is_form_error(value: unknown): value is FormError {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as { _tag?: unknown })._tag === \"FormError\" &&\n Array.isArray((value as { issues?: unknown }).issues),\n );\n}\n\nexport function is_serialized_remote_failure_envelope(\n value: unknown,\n): value is SerializedRemoteFailureEnvelope {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n EFFECT_REMOTE_ERROR_MARKER in value &&\n (value as Record<string, unknown>)[EFFECT_REMOTE_ERROR_MARKER] === true &&\n typeof (value as { encoded?: unknown }).encoded === \"string\",\n );\n}\n\nexport function is_remote_validation_issue(\n value: unknown,\n): value is FormIssue {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as { message?: unknown }).message === \"string\" &&\n Array.isArray((value as { path?: unknown }).path),\n );\n}\n"],"mappings":";AAAA,MAAa,6BAA6B;AAC1C,MAAa,uBAAuB,OAAO,IACzC,6CACD;AAkDD,SAAgB,kBACd,GAAG,QACoB;AACvB,QAAO;EACL,MAAM;EACN;EACD;;AAGH,SAAgB,2BACd,OACA,QAC8B;AAC9B,QAAO;EACL,MAAM;EACN;EACA;EACD;;AAGH,SAAgB,+BACd,QACA,UAGI,EAAE,EACiB;AACvB,QAAO;EACL,MAAM;EACN,MAAM,QAAQ;EACd;EACA,QAAQ,QAAQ,UAAU;EAC3B;;AAGH,SAAgB,yBACd,OACA,UAGI,EAAE,EACW;AACjB,QAAO;EACL,MAAM;EACN,MAAM,QAAQ;EACd;EACA,QAAQ,QAAQ,UAAU;EAC3B;;AAGH,SAAgB,8BACd,OACA,MACsB;AACtB,QAAO;EACL,MAAM;EACN;EACA;EACD;;AAGH,SAAgB,0CACd,SACiC;AACjC,QAAO;GACJ,6BAA6B;EAC9B;EACD;;AAGH,SAAgB,cAAc,OAAoC;AAChE,QAAO,QACL,SACE,OAAO,UAAU,YAChB,MAA6B,SAAS,eACvC,MAAM,QAAS,MAA+B,OAAO,CACxD;;AAGH,SAAgB,sCACd,OAC0C;AAC1C,QAAO,QACL,SACE,OAAO,UAAU,YAAA,8BACa,SAC7B,MAAA,gCAAkE,QACnE,OAAQ,MAAgC,YAAY,SACvD;;AAGH,SAAgB,2BACd,OACoB;AACpB,QAAO,QACL,SACE,OAAO,UAAU,YACjB,OAAQ,MAAgC,YAAY,YACpD,MAAM,QAAS,MAA6B,KAAK,CACpD"}
@@ -0,0 +1,11 @@
1
+ import { type SourceMap } from "magic-string";
2
+ import type { EffectPreprocessOptions } from "../preprocess.ts";
3
+ interface TransformEffectScriptOptions extends EffectPreprocessOptions {
4
+ filename: string;
5
+ }
6
+ interface TransformEffectScriptResult {
7
+ code: string;
8
+ map: SourceMap;
9
+ }
10
+ export declare function transformEffectScript(content: string, options: TransformEffectScriptOptions): TransformEffectScriptResult;
11
+ export {};
@@ -0,0 +1,262 @@
1
+ import { t as MagicString } from "../chunks/magic-string.es-CHYFped_.js";
2
+ import ts from "typescript";
3
+ //#region internal/transform.ts
4
+ const DEFAULT_RUNTIME_MODULE_ID = "svelte-effect-runtime";
5
+ const DEFAULT_EFFECT_MODULE_ID = "effect";
6
+ const DEFAULT_SVELTE_MODULE_ID = "svelte";
7
+ const RUNE_IDENTIFIERS = new Set([
8
+ "$bindable",
9
+ "$derived",
10
+ "$effect",
11
+ "$host",
12
+ "$inspect",
13
+ "$props",
14
+ "$state"
15
+ ]);
16
+ const HOISTED_KINDS = new Set([
17
+ ts.SyntaxKind.ClassDeclaration,
18
+ ts.SyntaxKind.EmptyStatement,
19
+ ts.SyntaxKind.EnumDeclaration,
20
+ ts.SyntaxKind.ExportAssignment,
21
+ ts.SyntaxKind.ExportDeclaration,
22
+ ts.SyntaxKind.FunctionDeclaration,
23
+ ts.SyntaxKind.ImportDeclaration,
24
+ ts.SyntaxKind.ImportEqualsDeclaration,
25
+ ts.SyntaxKind.InterfaceDeclaration,
26
+ ts.SyntaxKind.ModuleDeclaration,
27
+ ts.SyntaxKind.TypeAliasDeclaration
28
+ ]);
29
+ const HOISTED_CALL_IDENTIFIERS = new Set([
30
+ "$effect",
31
+ "__svelteEffectRuntimeMarkupOnDestroy",
32
+ "__svelteEffectRuntimeMarkupRegisterHotDispose",
33
+ "onDestroy"
34
+ ]);
35
+ function transformEffectScript(content, options) {
36
+ const sourceFile = ts.createSourceFile(options.filename, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
37
+ const effectStatements = [];
38
+ const runtimeStatements = [];
39
+ const magicString = new MagicString(content);
40
+ const effectBoundBindings = /* @__PURE__ */ new Set();
41
+ for (const statement of sourceFile.statements) {
42
+ if (ts.isVariableStatement(statement)) {
43
+ if (isGeneratedMarkupHelperStatement(statement, content)) continue;
44
+ const transformed = transformVariableStatement(statement, content, options.filename, effectBoundBindings);
45
+ if (transformed.hoistedText.length === 0) magicString.remove(statement.getFullStart(), statement.end);
46
+ else magicString.overwrite(statement.getStart(sourceFile), statement.end, transformed.hoistedText);
47
+ runtimeStatements.push(...transformed.effectTexts);
48
+ for (const bindingName of transformed.loweredBindings) effectBoundBindings.add(bindingName);
49
+ continue;
50
+ }
51
+ if (isHoistedExpressionStatement(statement)) continue;
52
+ if (isHoistedStatement(statement)) continue;
53
+ if (containsTopLevelAwait(statement)) throw new Error(`${options.filename}: top-level await is not supported in <script effect>. Use yield* Effect.promise(...) or yield* Effect.tryPromise(...) instead.`);
54
+ effectStatements.push({
55
+ node: statement,
56
+ text: normalizeStatementText(sliceNode(content, statement))
57
+ });
58
+ }
59
+ for (const statement of [...effectStatements].reverse()) magicString.remove(statement.node.getFullStart(), statement.node.end);
60
+ const allRuntimeStatements = [...runtimeStatements, ...effectStatements.map((statement) => statement.text)];
61
+ if (allRuntimeStatements.length > 0) {
62
+ magicString.prepend(makeInjectedImports(options));
63
+ magicString.append(makeRuntimeBlock(allRuntimeStatements));
64
+ }
65
+ return {
66
+ code: magicString.toString(),
67
+ map: magicString.generateMap({
68
+ hires: true,
69
+ includeContent: true,
70
+ source: options.filename
71
+ })
72
+ };
73
+ }
74
+ function isHoistedStatement(statement) {
75
+ return HOISTED_KINDS.has(statement.kind);
76
+ }
77
+ function isHoistedExpressionStatement(statement) {
78
+ if (!ts.isExpressionStatement(statement)) return false;
79
+ if (!ts.isCallExpression(statement.expression)) return false;
80
+ return getCalledIdentifierText(statement.expression.expression) !== void 0 && HOISTED_CALL_IDENTIFIERS.has(getCalledIdentifierText(statement.expression.expression));
81
+ }
82
+ function getCalledIdentifierText(expression) {
83
+ if (ts.isIdentifier(expression)) return expression.text;
84
+ if (ts.isPropertyAccessExpression(expression)) {
85
+ const base = getCalledIdentifierText(expression.expression);
86
+ return base ? `${base}.${expression.name.text}` : expression.name.text;
87
+ }
88
+ }
89
+ function transformVariableStatement(statement, content, filename, effectBoundBindings) {
90
+ if ((statement.modifiers?.length ?? 0) > 0) {
91
+ validateModifiedVariableStatement(statement, content, filename);
92
+ return {
93
+ effectTexts: [],
94
+ hoistedText: normalizeStatementText(sliceNode(content, statement)),
95
+ loweredBindings: []
96
+ };
97
+ }
98
+ const effectTexts = [];
99
+ const hoistedDeclarations = [];
100
+ const loweredBindings = [];
101
+ for (const declaration of statement.declarationList.declarations) {
102
+ if (declaration.initializer && containsTopLevelAwait(declaration.initializer)) {
103
+ const statementText = normalizeStatementText(sliceNode(content, statement));
104
+ throw new Error(`${filename}: declarations in <script effect> cannot depend on await.\nUse yield* Effect.promise(...) or yield* Effect.tryPromise(...) instead.\n\nProblematic statement:\n${statementText}`);
105
+ }
106
+ if (declaration.initializer && isRuneInitializer(declaration.initializer)) {
107
+ hoistedDeclarations.push(`${getDeclarationKind(statement.declarationList.flags)} ${normalizeStatementText(sliceNode(content, declaration))};`);
108
+ continue;
109
+ }
110
+ if (shouldHoistDeclaration(statement.declarationList.flags, declaration, effectBoundBindings)) {
111
+ hoistedDeclarations.push(`${getDeclarationKind(statement.declarationList.flags)} ${normalizeStatementText(sliceNode(content, declaration))};`);
112
+ continue;
113
+ }
114
+ const bindingNames = extractBindingNames(declaration.name);
115
+ for (const bindingName of bindingNames) hoistedDeclarations.push(makeStateDeclaration(bindingName, declaration, content));
116
+ loweredBindings.push(...bindingNames);
117
+ if (declaration.initializer) effectTexts.push(makeEffectAssignment(declaration.name, declaration.initializer, content));
118
+ }
119
+ return {
120
+ effectTexts,
121
+ hoistedText: hoistedDeclarations.join("\n"),
122
+ loweredBindings
123
+ };
124
+ }
125
+ function shouldHoistDeclaration(flags, declaration, effectBoundBindings) {
126
+ if ((flags & ts.NodeFlags.Const) === 0) return false;
127
+ if (!declaration.initializer) return false;
128
+ if (containsYieldStar(declaration.initializer) || containsTopLevelAwait(declaration.initializer)) return false;
129
+ return !referencesEffectBoundBindings(declaration.initializer, effectBoundBindings);
130
+ }
131
+ function referencesEffectBoundBindings(node, effectBoundBindings) {
132
+ const localScopes = [/* @__PURE__ */ new Set()];
133
+ let found = false;
134
+ const visit = (current) => {
135
+ if (found) return;
136
+ if (ts.isArrowFunction(current) || ts.isFunctionDeclaration(current) || ts.isFunctionExpression(current)) {
137
+ const scope = /* @__PURE__ */ new Set();
138
+ if (current.name) scope.add(current.name.text);
139
+ for (const parameter of current.parameters) declareBindingInto(scope, parameter.name);
140
+ localScopes.unshift(scope);
141
+ current.forEachChild(visit);
142
+ localScopes.shift();
143
+ return;
144
+ }
145
+ if (ts.isIdentifier(current)) {
146
+ if (!isSkippedReference(current) && effectBoundBindings.has(current.text) && !localScopes.some((scope) => scope.has(current.text))) found = true;
147
+ return;
148
+ }
149
+ current.forEachChild(visit);
150
+ };
151
+ const declareBindingInto = (scope, name) => {
152
+ if (ts.isIdentifier(name)) {
153
+ scope.add(name.text);
154
+ return;
155
+ }
156
+ for (const element of name.elements) {
157
+ if (ts.isOmittedExpression(element)) continue;
158
+ declareBindingInto(scope, element.name);
159
+ }
160
+ };
161
+ visit(node);
162
+ return found;
163
+ }
164
+ function isSkippedReference(identifier) {
165
+ const parent = identifier.parent;
166
+ return ts.isPropertyAccessExpression(parent) && parent.name === identifier || ts.isPropertyAssignment(parent) && parent.name === identifier || ts.isShorthandPropertyAssignment(parent) && parent.objectAssignmentInitializer === identifier || ts.isBindingElement(parent) && parent.propertyName === identifier || ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent) || ts.isLabeledStatement(parent) && parent.label === identifier;
167
+ }
168
+ function isGeneratedMarkupHelperStatement(statement, content) {
169
+ return statement.declarationList.declarations.every((declaration) => extractBindingNames(declaration.name).every((name) => name.startsWith("__svelteEffectRuntimeMarkup")) || normalizeStatementText(sliceNode(content, declaration)).startsWith("__svelteEffectRuntimeMarkup"));
170
+ }
171
+ function validateModifiedVariableStatement(statement, content, filename) {
172
+ for (const declaration of statement.declarationList.declarations) if (declaration.initializer && (containsYieldStar(declaration.initializer) || containsTopLevelAwait(declaration.initializer))) {
173
+ const statementText = normalizeStatementText(sliceNode(content, statement));
174
+ throw new Error(`${filename}: declarations with modifiers cannot depend on yield* or await in <script effect> right now.\nSplit the declaration into a plain top-level binding and assign inside the effect body instead.\n\nProblematic statement:\n${statementText}`);
175
+ }
176
+ }
177
+ function getDeclarationKind(flags) {
178
+ if ((flags & ts.NodeFlags.Const) !== 0) return "const";
179
+ if ((flags & ts.NodeFlags.Let) !== 0) return "let";
180
+ return "var";
181
+ }
182
+ function makeStateDeclaration(name, declaration, content) {
183
+ if (ts.isIdentifier(declaration.name) && declaration.type) return `let ${name} = $state<${normalizeStatementText(sliceNode(content, declaration.type))} | undefined>(undefined);`;
184
+ return `let ${name} = $state<any>(undefined);`;
185
+ }
186
+ function makeEffectAssignment(name, initializer, content) {
187
+ const target = normalizeStatementText(sliceNode(content, name));
188
+ const expression = normalizeStatementText(sliceNode(content, initializer));
189
+ if (ts.isIdentifier(name)) return `${target} = ${expression};`;
190
+ return `(${target} = ${expression});`;
191
+ }
192
+ function extractBindingNames(name) {
193
+ if (ts.isIdentifier(name)) return [name.text];
194
+ const names = [];
195
+ for (const element of name.elements) {
196
+ if (ts.isOmittedExpression(element)) continue;
197
+ names.push(...extractBindingNames(element.name));
198
+ }
199
+ return names;
200
+ }
201
+ function isRuneInitializer(expression) {
202
+ if (!ts.isCallExpression(expression)) return false;
203
+ return isRuneCallee(expression.expression);
204
+ }
205
+ function isRuneCallee(expression) {
206
+ if (ts.isIdentifier(expression)) return RUNE_IDENTIFIERS.has(expression.text);
207
+ if (ts.isPropertyAccessExpression(expression)) return isRuneCallee(expression.expression);
208
+ return false;
209
+ }
210
+ function containsYieldStar(node) {
211
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AsteriskToken && ts.isIdentifier(node.left) && node.left.text === "yield") return true;
212
+ return node.getChildren().some((child) => isFunctionBoundary(child) ? false : containsYieldStar(child));
213
+ }
214
+ function containsTopLevelAwait(node) {
215
+ if (ts.isAwaitExpression(node)) return true;
216
+ return node.getChildren().some((child) => isFunctionBoundary(child) ? false : containsTopLevelAwait(child));
217
+ }
218
+ function isFunctionBoundary(node) {
219
+ return ts.isArrowFunction(node) || ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node);
220
+ }
221
+ function sliceNode(content, node) {
222
+ return content.slice(node.getFullStart(), node.end);
223
+ }
224
+ function normalizeStatementText(text) {
225
+ return text.trim();
226
+ }
227
+ function indentBlock(text, indent) {
228
+ return text.split("\n").map((line) => line.length > 0 ? `${indent}${line}` : line).join("\n");
229
+ }
230
+ function makeInjectedImports(options) {
231
+ const runtimeModuleId = options.runtimeModuleId ?? DEFAULT_RUNTIME_MODULE_ID;
232
+ const effectModuleId = options.effectModuleId ?? DEFAULT_EFFECT_MODULE_ID;
233
+ return [
234
+ `import { onMount as __svelteEffectRuntimeOnMount } from "${options.svelteModuleId ?? DEFAULT_SVELTE_MODULE_ID}";`,
235
+ `import { Effect as __svelteEffectRuntimeEffect } from "${effectModuleId}";`,
236
+ `import { getEffectRuntimeOrThrow as __svelteEffectRuntimeGetRuntime, registerHotDispose as __svelteEffectRuntimeRegisterHotDispose, runComponentEffect as __svelteEffectRuntimeRunComponentEffect } from "${runtimeModuleId}";`,
237
+ ""
238
+ ].join("\n");
239
+ }
240
+ function makeRuntimeBlock(statements) {
241
+ return [
242
+ "",
243
+ "const __svelteEffectRuntimeProgram = __svelteEffectRuntimeEffect.gen(function* () {",
244
+ statements.map((statement) => indentBlock(statement, " ")).join("\n\n"),
245
+ "});",
246
+ "",
247
+ "__svelteEffectRuntimeOnMount(() => {",
248
+ " const __svelteEffectRuntimeCleanup = __svelteEffectRuntimeRunComponentEffect(",
249
+ " __svelteEffectRuntimeGetRuntime(),",
250
+ " __svelteEffectRuntimeProgram,",
251
+ " );",
252
+ "",
253
+ " __svelteEffectRuntimeRegisterHotDispose(import.meta, __svelteEffectRuntimeCleanup);",
254
+ " return __svelteEffectRuntimeCleanup;",
255
+ "});",
256
+ ""
257
+ ].join("\n");
258
+ }
259
+ //#endregion
260
+ export { transformEffectScript };
261
+
262
+ //# sourceMappingURL=transform.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform.js","names":[],"sources":["../../../modules/svelte-effect-runtime/internal/transform.ts"],"sourcesContent":["import MagicString, { type SourceMap } from \"magic-string\";\nimport ts from \"typescript\";\nimport type { EffectPreprocessOptions } from \"../preprocess.ts\";\n\nconst DEFAULT_RUNTIME_MODULE_ID = \"svelte-effect-runtime\";\nconst DEFAULT_EFFECT_MODULE_ID = \"effect\";\nconst DEFAULT_SVELTE_MODULE_ID = \"svelte\";\n\nconst RUNE_IDENTIFIERS = new Set([\n \"$bindable\",\n \"$derived\",\n \"$effect\",\n \"$host\",\n \"$inspect\",\n \"$props\",\n \"$state\",\n]);\n\ninterface TransformEffectScriptOptions extends EffectPreprocessOptions {\n filename: string;\n}\n\ninterface TransformEffectScriptResult {\n code: string;\n map: SourceMap;\n}\n\ninterface VariableStatementTransform {\n effectTexts: string[];\n hoistedText: string;\n loweredBindings: string[];\n}\n\nconst HOISTED_KINDS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.ClassDeclaration,\n ts.SyntaxKind.EmptyStatement,\n ts.SyntaxKind.EnumDeclaration,\n ts.SyntaxKind.ExportAssignment,\n ts.SyntaxKind.ExportDeclaration,\n ts.SyntaxKind.FunctionDeclaration,\n ts.SyntaxKind.ImportDeclaration,\n ts.SyntaxKind.ImportEqualsDeclaration,\n ts.SyntaxKind.InterfaceDeclaration,\n ts.SyntaxKind.ModuleDeclaration,\n ts.SyntaxKind.TypeAliasDeclaration,\n]);\n\nconst HOISTED_CALL_IDENTIFIERS = new Set([\n \"$effect\",\n \"__svelteEffectRuntimeMarkupOnDestroy\",\n \"__svelteEffectRuntimeMarkupRegisterHotDispose\",\n \"onDestroy\",\n]);\n\nexport function transformEffectScript(\n content: string,\n options: TransformEffectScriptOptions,\n): TransformEffectScriptResult {\n const sourceFile = ts.createSourceFile(\n options.filename,\n content,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n );\n\n const effectStatements: Array<{ node: ts.Statement; text: string }> = [];\n const runtimeStatements: string[] = [];\n const magicString = new MagicString(content);\n const effectBoundBindings = new Set<string>();\n\n for (const statement of sourceFile.statements) {\n if (ts.isVariableStatement(statement)) {\n if (isGeneratedMarkupHelperStatement(statement, content)) {\n continue;\n }\n\n const transformed = transformVariableStatement(\n statement,\n content,\n options.filename,\n effectBoundBindings,\n );\n\n if (transformed.hoistedText.length === 0) {\n magicString.remove(statement.getFullStart(), statement.end);\n } else {\n magicString.overwrite(\n statement.getStart(sourceFile),\n statement.end,\n transformed.hoistedText,\n );\n }\n\n runtimeStatements.push(...transformed.effectTexts);\n for (const bindingName of transformed.loweredBindings) {\n effectBoundBindings.add(bindingName);\n }\n continue;\n }\n\n if (isHoistedExpressionStatement(statement)) {\n continue;\n }\n\n if (isHoistedStatement(statement)) {\n continue;\n }\n\n if (containsTopLevelAwait(statement)) {\n throw new Error(\n `${options.filename}: top-level await is not supported in <script effect>. Use yield* Effect.promise(...) or yield* Effect.tryPromise(...) instead.`,\n );\n }\n\n effectStatements.push({\n node: statement,\n text: normalizeStatementText(sliceNode(content, statement)),\n });\n }\n\n for (const statement of [...effectStatements].reverse()) {\n magicString.remove(statement.node.getFullStart(), statement.node.end);\n }\n\n const allRuntimeStatements = [\n ...runtimeStatements,\n ...effectStatements.map((statement) => statement.text),\n ];\n\n if (allRuntimeStatements.length > 0) {\n magicString.prepend(makeInjectedImports(options));\n magicString.append(makeRuntimeBlock(allRuntimeStatements));\n }\n\n return {\n code: magicString.toString(),\n map: magicString.generateMap({\n hires: true,\n includeContent: true,\n source: options.filename,\n }),\n };\n}\n\nfunction isHoistedStatement(statement: ts.Statement): boolean {\n return HOISTED_KINDS.has(statement.kind);\n}\n\nfunction isHoistedExpressionStatement(statement: ts.Statement): boolean {\n if (!ts.isExpressionStatement(statement)) {\n return false;\n }\n\n if (!ts.isCallExpression(statement.expression)) {\n return false;\n }\n\n return getCalledIdentifierText(statement.expression.expression) !==\n undefined &&\n HOISTED_CALL_IDENTIFIERS.has(\n getCalledIdentifierText(statement.expression.expression)!,\n );\n}\n\nfunction getCalledIdentifierText(\n expression: ts.Expression,\n): string | undefined {\n if (ts.isIdentifier(expression)) {\n return expression.text;\n }\n\n if (ts.isPropertyAccessExpression(expression)) {\n const base = getCalledIdentifierText(expression.expression);\n return base ? `${base}.${expression.name.text}` : expression.name.text;\n }\n\n return undefined;\n}\n\nfunction transformVariableStatement(\n statement: ts.VariableStatement,\n content: string,\n filename: string,\n effectBoundBindings: ReadonlySet<string>,\n): VariableStatementTransform {\n if ((statement.modifiers?.length ?? 0) > 0) {\n validateModifiedVariableStatement(statement, content, filename);\n return {\n effectTexts: [],\n hoistedText: normalizeStatementText(sliceNode(content, statement)),\n loweredBindings: [],\n };\n }\n\n const effectTexts: string[] = [];\n const hoistedDeclarations: string[] = [];\n const loweredBindings: string[] = [];\n\n for (const declaration of statement.declarationList.declarations) {\n if (\n declaration.initializer && containsTopLevelAwait(declaration.initializer)\n ) {\n const statementText = normalizeStatementText(\n sliceNode(content, statement),\n );\n\n throw new Error(\n `${filename}: declarations in <script effect> cannot depend on await.\\nUse yield* Effect.promise(...) or yield* Effect.tryPromise(...) instead.\\n\\nProblematic statement:\\n${statementText}`,\n );\n }\n\n if (declaration.initializer && isRuneInitializer(declaration.initializer)) {\n hoistedDeclarations.push(\n `${getDeclarationKind(statement.declarationList.flags)} ${\n normalizeStatementText(sliceNode(content, declaration))\n };`,\n );\n continue;\n }\n\n if (\n shouldHoistDeclaration(\n statement.declarationList.flags,\n declaration,\n effectBoundBindings,\n )\n ) {\n hoistedDeclarations.push(\n `${getDeclarationKind(statement.declarationList.flags)} ${\n normalizeStatementText(sliceNode(content, declaration))\n };`,\n );\n continue;\n }\n\n const bindingNames = extractBindingNames(declaration.name);\n\n for (const bindingName of bindingNames) {\n hoistedDeclarations.push(\n makeStateDeclaration(bindingName, declaration, content),\n );\n }\n loweredBindings.push(...bindingNames);\n\n if (declaration.initializer) {\n effectTexts.push(\n makeEffectAssignment(\n declaration.name,\n declaration.initializer,\n content,\n ),\n );\n }\n }\n\n return {\n effectTexts,\n hoistedText: hoistedDeclarations.join(\"\\n\"),\n loweredBindings,\n };\n}\n\nfunction shouldHoistDeclaration(\n flags: ts.NodeFlags,\n declaration: ts.VariableDeclaration,\n effectBoundBindings: ReadonlySet<string>,\n): boolean {\n if ((flags & ts.NodeFlags.Const) === 0) {\n return false;\n }\n\n if (!declaration.initializer) {\n return false;\n }\n\n if (\n containsYieldStar(declaration.initializer) ||\n containsTopLevelAwait(declaration.initializer)\n ) {\n return false;\n }\n\n return !referencesEffectBoundBindings(\n declaration.initializer,\n effectBoundBindings,\n );\n}\n\nfunction referencesEffectBoundBindings(\n node: ts.Node,\n effectBoundBindings: ReadonlySet<string>,\n): boolean {\n const localScopes: Array<Set<string>> = [new Set()];\n let found = false;\n\n const visit = (current: ts.Node): void => {\n if (found) {\n return;\n }\n\n if (\n ts.isArrowFunction(current) || ts.isFunctionDeclaration(current) ||\n ts.isFunctionExpression(current)\n ) {\n const scope = new Set<string>();\n\n if (current.name) {\n scope.add(current.name.text);\n }\n\n for (const parameter of current.parameters) {\n declareBindingInto(scope, parameter.name);\n }\n\n localScopes.unshift(scope);\n current.forEachChild(visit);\n localScopes.shift();\n return;\n }\n\n if (ts.isIdentifier(current)) {\n if (\n !isSkippedReference(current) &&\n effectBoundBindings.has(current.text) &&\n !localScopes.some((scope) => scope.has(current.text))\n ) {\n found = true;\n }\n\n return;\n }\n\n current.forEachChild(visit);\n };\n\n const declareBindingInto = (\n scope: Set<string>,\n name: ts.BindingName,\n ): void => {\n if (ts.isIdentifier(name)) {\n scope.add(name.text);\n return;\n }\n\n for (const element of name.elements) {\n if (ts.isOmittedExpression(element)) {\n continue;\n }\n\n declareBindingInto(scope, element.name);\n }\n };\n\n visit(node);\n return found;\n}\n\nfunction isSkippedReference(identifier: ts.Identifier): boolean {\n const parent = identifier.parent;\n\n return ts.isPropertyAccessExpression(parent) && parent.name === identifier ||\n ts.isPropertyAssignment(parent) && parent.name === identifier ||\n ts.isShorthandPropertyAssignment(parent) &&\n parent.objectAssignmentInitializer === identifier ||\n ts.isBindingElement(parent) && parent.propertyName === identifier ||\n ts.isImportSpecifier(parent) ||\n ts.isExportSpecifier(parent) ||\n ts.isLabeledStatement(parent) && parent.label === identifier;\n}\n\nfunction isGeneratedMarkupHelperStatement(\n statement: ts.VariableStatement,\n content: string,\n): boolean {\n return statement.declarationList.declarations.every((declaration) =>\n extractBindingNames(declaration.name).every((name) =>\n name.startsWith(\"__svelteEffectRuntimeMarkup\")\n ) ||\n normalizeStatementText(sliceNode(content, declaration)).startsWith(\n \"__svelteEffectRuntimeMarkup\",\n )\n );\n}\n\nfunction validateModifiedVariableStatement(\n statement: ts.VariableStatement,\n content: string,\n filename: string,\n): void {\n for (const declaration of statement.declarationList.declarations) {\n if (\n declaration.initializer &&\n (containsYieldStar(declaration.initializer) ||\n containsTopLevelAwait(declaration.initializer))\n ) {\n const statementText = normalizeStatementText(\n sliceNode(content, statement),\n );\n\n throw new Error(\n `${filename}: declarations with modifiers cannot depend on yield* or await in <script effect> right now.\\nSplit the declaration into a plain top-level binding and assign inside the effect body instead.\\n\\nProblematic statement:\\n${statementText}`,\n );\n }\n }\n}\n\nfunction getDeclarationKind(flags: ts.NodeFlags): \"const\" | \"let\" | \"var\" {\n if ((flags & ts.NodeFlags.Const) !== 0) {\n return \"const\";\n }\n\n if ((flags & ts.NodeFlags.Let) !== 0) {\n return \"let\";\n }\n\n return \"var\";\n}\n\nfunction makeStateDeclaration(\n name: string,\n declaration: ts.VariableDeclaration,\n content: string,\n): string {\n if (ts.isIdentifier(declaration.name) && declaration.type) {\n const typeText = normalizeStatementText(\n sliceNode(content, declaration.type),\n );\n return `let ${name} = $state<${typeText} | undefined>(undefined);`;\n }\n\n return `let ${name} = $state<any>(undefined);`;\n}\n\nfunction makeEffectAssignment(\n name: ts.BindingName,\n initializer: ts.Expression,\n content: string,\n): string {\n const target = normalizeStatementText(sliceNode(content, name));\n const expression = normalizeStatementText(sliceNode(content, initializer));\n\n if (ts.isIdentifier(name)) {\n return `${target} = ${expression};`;\n }\n\n return `(${target} = ${expression});`;\n}\n\nfunction extractBindingNames(name: ts.BindingName): string[] {\n if (ts.isIdentifier(name)) {\n return [name.text];\n }\n\n const names: string[] = [];\n\n for (const element of name.elements) {\n if (ts.isOmittedExpression(element)) {\n continue;\n }\n\n names.push(...extractBindingNames(element.name));\n }\n\n return names;\n}\n\nfunction isRuneInitializer(expression: ts.Expression): boolean {\n if (!ts.isCallExpression(expression)) {\n return false;\n }\n\n return isRuneCallee(expression.expression);\n}\n\nfunction isRuneCallee(expression: ts.Expression): boolean {\n if (ts.isIdentifier(expression)) {\n return RUNE_IDENTIFIERS.has(expression.text);\n }\n\n if (ts.isPropertyAccessExpression(expression)) {\n return isRuneCallee(expression.expression);\n }\n\n return false;\n}\n\nfunction containsYieldStar(node: ts.Node): boolean {\n if (\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind === ts.SyntaxKind.AsteriskToken &&\n ts.isIdentifier(node.left) &&\n node.left.text === \"yield\"\n ) {\n return true;\n }\n\n return node.getChildren().some((child) =>\n isFunctionBoundary(child) ? false : containsYieldStar(child)\n );\n}\n\nfunction containsTopLevelAwait(node: ts.Node): boolean {\n if (ts.isAwaitExpression(node)) {\n return true;\n }\n\n return node.getChildren().some((child) =>\n isFunctionBoundary(child) ? false : containsTopLevelAwait(child)\n );\n}\n\nfunction isFunctionBoundary(node: ts.Node): boolean {\n return ts.isArrowFunction(node) ||\n ts.isFunctionDeclaration(node) ||\n ts.isFunctionExpression(node) ||\n ts.isMethodDeclaration(node) ||\n ts.isGetAccessorDeclaration(node) ||\n ts.isSetAccessorDeclaration(node);\n}\n\nfunction sliceNode(content: string, node: ts.Node): string {\n return content.slice(node.getFullStart(), node.end);\n}\n\nfunction normalizeStatementText(text: string): string {\n return text.trim();\n}\n\nfunction indentBlock(text: string, indent: string): string {\n return text.split(\"\\n\").map((line) =>\n line.length > 0 ? `${indent}${line}` : line\n ).join(\"\\n\");\n}\n\nfunction makeInjectedImports(options: TransformEffectScriptOptions): string {\n const runtimeModuleId = options.runtimeModuleId ?? DEFAULT_RUNTIME_MODULE_ID;\n const effectModuleId = options.effectModuleId ?? DEFAULT_EFFECT_MODULE_ID;\n const svelteModuleId = options.svelteModuleId ?? DEFAULT_SVELTE_MODULE_ID;\n\n return [\n `import { onMount as __svelteEffectRuntimeOnMount } from \"${svelteModuleId}\";`,\n `import { Effect as __svelteEffectRuntimeEffect } from \"${effectModuleId}\";`,\n `import { getEffectRuntimeOrThrow as __svelteEffectRuntimeGetRuntime, registerHotDispose as __svelteEffectRuntimeRegisterHotDispose, runComponentEffect as __svelteEffectRuntimeRunComponentEffect } from \"${runtimeModuleId}\";`,\n \"\",\n ].join(\"\\n\");\n}\n\nfunction makeRuntimeBlock(statements: string[]): string {\n const body = statements.map((statement) => indentBlock(statement, \" \"))\n .join(\"\\n\\n\");\n\n return [\n \"\",\n \"const __svelteEffectRuntimeProgram = __svelteEffectRuntimeEffect.gen(function* () {\",\n body,\n \"});\",\n \"\",\n \"__svelteEffectRuntimeOnMount(() => {\",\n \" const __svelteEffectRuntimeCleanup = __svelteEffectRuntimeRunComponentEffect(\",\n \" __svelteEffectRuntimeGetRuntime(),\",\n \" __svelteEffectRuntimeProgram,\",\n \" );\",\n \"\",\n \" __svelteEffectRuntimeRegisterHotDispose(import.meta, __svelteEffectRuntimeCleanup);\",\n \" return __svelteEffectRuntimeCleanup;\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n"],"mappings":";;;AAIA,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AAEjC,MAAM,mBAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAiBF,MAAM,gBAAgB,IAAI,IAAmB;CAC3C,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,GAAG,WAAW;CACd,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EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK"}
@@ -0,0 +1,3 @@
1
+ export { effectPreprocess } from "./preprocess.ts";
2
+ export { transformEffectMarkup } from "./internal/markup.ts";
3
+ export { transformEffectScript } from "./internal/transform.ts";
@@ -0,0 +1,4 @@
1
+ import { transformEffectMarkup } from "./internal/markup.js";
2
+ import { transformEffectScript } from "./internal/transform.js";
3
+ import { effectPreprocess } from "./preprocess.js";
4
+ export { effectPreprocess, transformEffectMarkup, transformEffectScript };
package/dist/mod.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type { EffectPreprocessOptions } from "./preprocess.ts";
2
+ export type { ClientRuntimeService, EffectRuntime, FormError, FormIssue, ProvideEffectRuntimeOptions, RemoteDomainError, RemoteFailure, RemoteHttpError, RemoteTransportError, RemoteValidationError, } from "./client.ts";
3
+ export { effectPreprocess } from "./preprocess.ts";
4
+ export { transformEffectMarkup } from "./internal/markup.ts";
5
+ export { transformEffectScript } from "./internal/transform.ts";
6
+ export { ClientRuntime, ClientRuntimeTag, getEffectRuntimeOrThrow, provideEffectRuntime, registerHotDispose, runComponentEffect, runInlineEffect, to_effect, to_native, } from "./client.ts";
package/dist/mod.js ADDED
@@ -0,0 +1,5 @@
1
+ import { transformEffectMarkup } from "./internal/markup.js";
2
+ import { transformEffectScript } from "./internal/transform.js";
3
+ import { effectPreprocess } from "./preprocess.js";
4
+ import { ClientRuntime, ClientRuntimeTag, getEffectRuntimeOrThrow, provideEffectRuntime, registerHotDispose, runComponentEffect, runInlineEffect, to_effect, to_native } from "./client.js";
5
+ export { ClientRuntime, ClientRuntimeTag, effectPreprocess, getEffectRuntimeOrThrow, provideEffectRuntime, registerHotDispose, runComponentEffect, runInlineEffect, to_effect, to_native, transformEffectMarkup, transformEffectScript };
@@ -0,0 +1,7 @@
1
+ import type { PreprocessorGroup } from "svelte/compiler";
2
+ export interface EffectPreprocessOptions {
3
+ runtimeModuleId?: string;
4
+ effectModuleId?: string;
5
+ svelteModuleId?: string;
6
+ }
7
+ export declare function effectPreprocess(options?: EffectPreprocessOptions): PreprocessorGroup;
@@ -0,0 +1,36 @@
1
+ import { transformEffectMarkup } from "./internal/markup.js";
2
+ import { transformEffectScript } from "./internal/transform.js";
3
+ //#region preprocess.ts
4
+ function effectPreprocess(options = {}) {
5
+ return {
6
+ name: "svelte-effect-runtime",
7
+ markup({ content, filename }) {
8
+ const transformed = transformEffectMarkup(content, {
9
+ ...options,
10
+ filename: filename ?? "Component.svelte"
11
+ });
12
+ if (transformed.code === content) return;
13
+ return {
14
+ code: transformed.code,
15
+ map: transformed.map
16
+ };
17
+ },
18
+ script({ content, attributes, filename }) {
19
+ if (attributes.context === "module" || !Object.hasOwn(attributes, "effect")) return;
20
+ const { effect: _effect, ...nextAttributes } = attributes;
21
+ const transformed = transformEffectScript(content, {
22
+ ...options,
23
+ filename: filename ?? "Component.svelte"
24
+ });
25
+ return {
26
+ code: transformed.code,
27
+ map: transformed.map,
28
+ attributes: nextAttributes
29
+ };
30
+ }
31
+ };
32
+ }
33
+ //#endregion
34
+ export { effectPreprocess };
35
+
36
+ //# sourceMappingURL=preprocess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preprocess.js","names":[],"sources":["../../modules/svelte-effect-runtime/preprocess.ts"],"sourcesContent":["import type { PreprocessorGroup } from \"svelte/compiler\";\nimport { transformEffectMarkup } from \"./internal/markup.ts\";\nimport { transformEffectScript } from \"./internal/transform.ts\";\n\nexport interface EffectPreprocessOptions {\n runtimeModuleId?: string;\n effectModuleId?: string;\n svelteModuleId?: string;\n}\n\nexport function effectPreprocess(\n options: EffectPreprocessOptions = {},\n): PreprocessorGroup {\n return {\n name: \"svelte-effect-runtime\",\n markup({ content, filename }) {\n const transformed = transformEffectMarkup(content, {\n ...options,\n filename: filename ?? \"Component.svelte\",\n });\n\n if (transformed.code === content) {\n return;\n }\n\n return {\n code: transformed.code,\n map: transformed.map,\n };\n },\n script({ content, attributes, filename }) {\n if (\n attributes.context === \"module\" || !Object.hasOwn(attributes, \"effect\")\n ) {\n return;\n }\n\n const { effect: _effect, ...nextAttributes } = attributes;\n const transformed = transformEffectScript(content, {\n ...options,\n filename: filename ?? \"Component.svelte\",\n });\n\n return {\n code: transformed.code,\n map: transformed.map,\n attributes: nextAttributes,\n };\n },\n };\n}\n"],"mappings":";;;AAUA,SAAgB,iBACd,UAAmC,EAAE,EAClB;AACnB,QAAO;EACL,MAAM;EACN,OAAO,EAAE,SAAS,YAAY;GAC5B,MAAM,cAAc,sBAAsB,SAAS;IACjD,GAAG;IACH,UAAU,YAAY;IACvB,CAAC;AAEF,OAAI,YAAY,SAAS,QACvB;AAGF,UAAO;IACL,MAAM,YAAY;IAClB,KAAK,YAAY;IAClB;;EAEH,OAAO,EAAE,SAAS,YAAY,YAAY;AACxC,OACE,WAAW,YAAY,YAAY,CAAC,OAAO,OAAO,YAAY,SAAS,CAEvE;GAGF,MAAM,EAAE,QAAQ,SAAS,GAAG,mBAAmB;GAC/C,MAAM,cAAc,sBAAsB,SAAS;IACjD,GAAG;IACH,UAAU,YAAY;IACvB,CAAC;AAEF,UAAO;IACL,MAAM,YAAY;IAClB,KAAK,YAAY;IACjB,YAAY;IACb;;EAEJ"}