svelte-effect-runtime 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/chunks/{client-DkW4e4dD.js → client-vV6UAwoP.js} +3 -3
  2. package/dist/chunks/client-vV6UAwoP.js.map +1 -0
  3. package/dist/chunks/{server-CQcF2W3T.js → server-7YVuxUNk.js} +53 -2
  4. package/dist/chunks/server-7YVuxUNk.js.map +1 -0
  5. package/dist/chunks/v3-D0c0MKPf.js +1 -0
  6. package/dist/chunks/v4-MMhHmzIG.js +1 -0
  7. package/dist/client.js +1 -1
  8. package/dist/internal/remote-client.js +3 -3
  9. package/dist/internal/remote-client.js.map +1 -1
  10. package/dist/internal/remote-shared.d.ts +134 -1
  11. package/dist/internal/remote-shared.js +64 -0
  12. package/dist/internal/remote-shared.js.map +1 -1
  13. package/dist/internal/transform.d.ts +7 -0
  14. package/dist/internal/transform.js +172 -15
  15. package/dist/internal/transform.js.map +1 -1
  16. package/dist/mod.d.ts +21 -0
  17. package/dist/mod.js +2 -2
  18. package/dist/preprocess.d.ts +5 -0
  19. package/dist/preprocess.js +6 -1
  20. package/dist/preprocess.js.map +1 -1
  21. package/dist/root-node.js +3 -3
  22. package/dist/server.d.ts +25 -0
  23. package/dist/server.js +26 -1
  24. package/dist/server.js.map +1 -1
  25. package/dist/v3/client.d.ts +24 -0
  26. package/dist/v3/mod.d.ts +24 -0
  27. package/dist/v3/server.d.ts +106 -0
  28. package/dist/v4/mod.d.ts +24 -0
  29. package/dist/v4/mod.js +2 -2
  30. package/dist/v4/preprocess.d.ts +4 -0
  31. package/dist/v4/preprocess.js +5 -1
  32. package/dist/v4/preprocess.js.map +1 -1
  33. package/dist/v4/root-node.js +2 -2
  34. package/dist/v4/server.d.ts +196 -0
  35. package/dist/v4/server.js +50 -1
  36. package/dist/v4/server.js.map +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunks/client-DkW4e4dD.js.map +0 -1
  39. package/dist/chunks/server-CQcF2W3T.js.map +0 -1
  40. package/dist/chunks/v3-p8V3Drpp.js +0 -1
  41. package/dist/chunks/v4-DIhYCbb_.js +0 -1
@@ -1 +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 \"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 { get_effect_runtime_or_throw as __svelteEffectRuntimeGetRuntime, run_component_effect 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 \" import.meta.hot?.dispose(__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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SAAS,iBAAiB,YAA8B;AAItD,QAAO;EACL;EACA;EALW,WAAW,KAAK,cAAc,YAAY,WAAW,OAAO,CAAC,CACvE,KAAK,OAAO;EAMb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK"}
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 relocations: Array<TransformRelocation>;\n}\n\ninterface VariableStatementTransform {\n effectTexts: string[];\n hoistedText: string;\n loweredBindings: string[];\n pendingRelocations: Array<PendingRelocation>;\n usesPendingYieldHelper: boolean;\n}\n\ninterface TransformRelocation {\n originalStart: number;\n originalEnd: number;\n generatedStart: number;\n generatedEnd: number;\n}\n\ninterface PendingRelocation {\n originalStart: number;\n originalEnd: number;\n generatedSnippet: string;\n generatedInnerStart: number;\n generatedInnerEnd: number;\n}\n\ninterface StateDeclarationTransform {\n code: string;\n pendingRelocations: Array<PendingRelocation>;\n}\n\ninterface LoweredDeclarationHelper {\n declarationText: string;\n stateTypeText: string;\n assignmentExpression: string;\n expressionRelocation: PendingRelocation;\n tempName?: 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 \"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 pendingRelocations: Array<PendingRelocation> = [];\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 pendingRelocations.push(...transformed.pendingRelocations);\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 pendingRelocations.push({\n originalStart: statement.getStart(sourceFile),\n originalEnd: statement.end,\n generatedSnippet: normalizeStatementText(sliceNode(content, statement)),\n generatedInnerStart: 0,\n generatedInnerEnd: normalizeStatementText(sliceNode(content, statement))\n .length,\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 const code = magicString.toString();\n\n return {\n code,\n map: magicString.generateMap({\n hires: true,\n includeContent: true,\n source: options.filename,\n }),\n relocations: resolvePendingRelocations(pendingRelocations, code),\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 pendingRelocations: [],\n usesPendingYieldHelper: false,\n };\n }\n\n const effectTexts: string[] = [];\n const hoistedDeclarations: string[] = [];\n const loweredBindings: string[] = [];\n const pendingRelocations: Array<PendingRelocation> = [];\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 const renderedDeclaration =\n `${getDeclarationKind(statement.declarationList.flags)} ${\n normalizeStatementText(sliceNode(content, declaration))\n };`;\n hoistedDeclarations.push(renderedDeclaration);\n pendingRelocations.push(\n ...make_declaration_relocations(declaration, renderedDeclaration, content),\n );\n continue;\n }\n\n if (\n shouldHoistDeclaration(\n statement.declarationList.flags,\n declaration,\n effectBoundBindings,\n )\n ) {\n const renderedDeclaration =\n `${getDeclarationKind(statement.declarationList.flags)} ${\n normalizeStatementText(sliceNode(content, declaration))\n };`;\n hoistedDeclarations.push(renderedDeclaration);\n pendingRelocations.push(\n ...make_declaration_relocations(declaration, renderedDeclaration, content),\n );\n continue;\n }\n\n const bindingNames = extractBindingNames(declaration.name);\n const helper = create_lowered_declaration_helper(declaration, content);\n\n if (helper) {\n hoistedDeclarations.push(helper.declarationText);\n pendingRelocations.push(helper.expressionRelocation);\n }\n\n if (helper?.tempName) {\n hoistedDeclarations.push(\n makeTypedStateBinding(helper.tempName, helper.stateTypeText),\n );\n }\n\n for (const bindingName of bindingNames) {\n const stateDeclaration = makeStateDeclaration(\n bindingName,\n declaration,\n content,\n helper?.tempName ? null : helper?.stateTypeText,\n );\n hoistedDeclarations.push(stateDeclaration.code);\n pendingRelocations.push(...stateDeclaration.pendingRelocations);\n }\n loweredBindings.push(...bindingNames);\n\n if (declaration.initializer) {\n if (helper?.tempName) {\n effectTexts.push(`${helper.tempName} = ${helper.assignmentExpression};`);\n effectTexts.push(\n makeEffectAssignment(\n declaration.name,\n helper.tempName,\n content,\n ),\n );\n } else {\n const effectAssignment = helper\n ? `${bindingNames[0]} = ${helper.assignmentExpression};`\n : makeEffectAssignment(\n declaration.name,\n declaration.initializer,\n content,\n );\n effectTexts.push(effectAssignment);\n if (!helper) {\n pendingRelocations.push(\n makeEffectAssignmentRelocation(\n declaration.initializer,\n effectAssignment,\n content,\n ),\n );\n }\n }\n }\n }\n\n return {\n effectTexts,\n hoistedText: hoistedDeclarations.join(\"\\n\"),\n loweredBindings,\n pendingRelocations,\n usesPendingYieldHelper: false,\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 inferredTypeText?: string | null,\n): StateDeclarationTransform {\n let stateTypeText: string | null = null;\n\n if (ts.isIdentifier(declaration.name) && declaration.type) {\n stateTypeText = normalizeStatementText(\n sliceNode(content, declaration.type),\n );\n } else if (inferredTypeText) {\n stateTypeText = inferredTypeText;\n }\n\n const code = stateTypeText\n ? makeTypedStateBinding(name, stateTypeText)\n : `let ${name} = $state<any>(undefined);`;\n\n const nameStart = code.indexOf(name);\n const pendingRelocations: Array<PendingRelocation> = [{\n originalStart: find_binding_name_start(declaration.name, name),\n originalEnd: find_binding_name_end(declaration.name, name),\n generatedSnippet: \"\",\n generatedInnerStart: nameStart,\n generatedInnerEnd: nameStart + name.length,\n }];\n\n pendingRelocations[0] = {\n ...pendingRelocations[0],\n generatedSnippet: code,\n };\n\n return {\n code,\n pendingRelocations,\n };\n}\n\nfunction makeEffectAssignment(\n name: ts.BindingName,\n initializer: ts.Expression | string,\n content: string,\n): string {\n const target = normalizeStatementText(sliceNode(content, name));\n const expression = typeof initializer === \"string\"\n ? initializer\n : normalizeStatementText(sliceNode(content, initializer));\n\n if (ts.isIdentifier(name)) {\n return `${target} = ${expression};`;\n }\n\n return `(${target} = ${expression});`;\n}\n\nfunction makeEffectAssignmentRelocation(\n initializer: ts.Expression,\n effectAssignment: string,\n content: string,\n): PendingRelocation {\n const expression = normalizeStatementText(sliceNode(content, initializer));\n const generatedInnerStart = effectAssignment.lastIndexOf(expression);\n\n return {\n originalStart: initializer.getStart(),\n originalEnd: initializer.end,\n generatedSnippet: effectAssignment,\n generatedInnerStart,\n generatedInnerEnd: generatedInnerStart + expression.length,\n };\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 getYieldOperand(node: ts.Node | undefined): ts.Expression | null {\n if (\n node &&\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind === ts.SyntaxKind.AsteriskToken &&\n ts.isIdentifier(node.left) &&\n node.left.text === \"yield\"\n ) {\n return node.right;\n }\n\n return null;\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(\n options: TransformEffectScriptOptions,\n): 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 const lines = [\n `import { onMount as __svelteEffectRuntimeOnMount } from \"${svelteModuleId}\";`,\n `import { Effect as __svelteEffectRuntimeEffect } from \"${effectModuleId}\";`,\n `import { get_effect_runtime_or_throw as __svelteEffectRuntimeGetRuntime, run_component_effect as __svelteEffectRuntimeRunComponentEffect } from \"${runtimeModuleId}\";`,\n `type __svelteEffectRuntimeYielded<T> = T extends __svelteEffectRuntimeEffect.Effect<infer A, any, any> ? A : T;`,\n ];\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nfunction makeTypedStateBinding(name: string, stateTypeText: string): string {\n return `let ${name}: ${stateTypeText} | undefined = $state(undefined as ${stateTypeText} | undefined);`;\n}\n\nfunction create_lowered_declaration_helper(\n declaration: ts.VariableDeclaration,\n content: string,\n): LoweredDeclarationHelper | null {\n if (declaration.type || !declaration.initializer) {\n return null;\n }\n\n const bindingNames = extractBindingNames(declaration.name);\n const suffix = declaration.getStart();\n const baseName = bindingNames[0] ?? \"binding\";\n const helperName = `__svelteEffectRuntime_${baseName}_${suffix}`;\n const expressionNode = getYieldOperand(declaration.initializer) ??\n declaration.initializer;\n const expressionText = normalizeStatementText(sliceNode(content, expressionNode));\n const declarationText = `const ${helperName} = () => ${expressionText};`;\n const yieldedExpression = getYieldOperand(declaration.initializer);\n const stateTypeText = yieldedExpression\n ? `__svelteEffectRuntimeYielded<ReturnType<typeof ${helperName}>>`\n : `ReturnType<typeof ${helperName}>`;\n const assignmentExpression = yieldedExpression\n ? `yield* ${helperName}()`\n : `${helperName}()`;\n\n return {\n declarationText,\n stateTypeText,\n assignmentExpression,\n tempName: ts.isIdentifier(declaration.name)\n ? undefined\n : `__svelteEffectRuntimeTemp_${suffix}`,\n expressionRelocation: {\n originalStart: expressionNode.getStart(),\n originalEnd: expressionNode.end,\n generatedSnippet: declarationText,\n generatedInnerStart: declarationText.lastIndexOf(expressionText),\n generatedInnerEnd: declarationText.lastIndexOf(expressionText) +\n expressionText.length,\n },\n };\n}\n\nfunction make_declaration_relocations(\n declaration: ts.VariableDeclaration,\n renderedDeclaration: string,\n content: string,\n): Array<PendingRelocation> {\n const relocations: Array<PendingRelocation> = [];\n\n if (ts.isIdentifier(declaration.name)) {\n const nameStart = renderedDeclaration.indexOf(declaration.name.text);\n relocations.push({\n originalStart: declaration.name.getStart(),\n originalEnd: declaration.name.end,\n generatedSnippet: renderedDeclaration,\n generatedInnerStart: nameStart,\n generatedInnerEnd: nameStart + declaration.name.text.length,\n });\n }\n\n if (declaration.initializer) {\n const initializerText = normalizeStatementText(\n sliceNode(content, declaration.initializer),\n );\n const initializerStart = renderedDeclaration.lastIndexOf(initializerText);\n if (initializerStart >= 0) {\n relocations.push({\n originalStart: declaration.initializer.getStart(),\n originalEnd: declaration.initializer.end,\n generatedSnippet: renderedDeclaration,\n generatedInnerStart: initializerStart,\n generatedInnerEnd: initializerStart + initializerText.length,\n });\n }\n }\n\n return relocations;\n}\n\nfunction find_binding_name_start(name: ts.BindingName, bindingName: string): number {\n if (ts.isIdentifier(name)) {\n return name.text === bindingName ? name.getStart() : -1;\n }\n\n for (const element of name.elements) {\n if (ts.isOmittedExpression(element)) {\n continue;\n }\n\n const start = find_binding_name_start(element.name, bindingName);\n if (start !== -1) {\n return start;\n }\n }\n\n return -1;\n}\n\nfunction find_binding_name_end(name: ts.BindingName, bindingName: string): number {\n if (ts.isIdentifier(name)) {\n return name.text === bindingName ? name.end : -1;\n }\n\n for (const element of name.elements) {\n if (ts.isOmittedExpression(element)) {\n continue;\n }\n\n const end = find_binding_name_end(element.name, bindingName);\n if (end !== -1) {\n return end;\n }\n }\n\n return -1;\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 \" import.meta.hot?.dispose(__svelteEffectRuntimeCleanup);\",\n \" return __svelteEffectRuntimeCleanup;\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction resolvePendingRelocations(\n pendingRelocations: Array<PendingRelocation>,\n code: string,\n): Array<TransformRelocation> {\n const relocations: Array<TransformRelocation> = [];\n let searchStart = 0;\n\n for (const relocation of pendingRelocations) {\n const generatedStart = code.indexOf(relocation.generatedSnippet, searchStart);\n\n if (generatedStart === -1) {\n continue;\n }\n\n searchStart = generatedStart + relocation.generatedSnippet.length;\n relocations.push({\n originalStart: relocation.originalStart,\n originalEnd: relocation.originalEnd,\n generatedStart: generatedStart + relocation.generatedInnerStart,\n generatedEnd: generatedStart + relocation.generatedInnerEnd,\n });\n }\n\n return relocations;\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;AAgDF,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,GAAG,WAAW;CACf,CAAC;AAEF,MAAM,2BAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACD,CAAC;AAEF,SAAgB,sBACd,SACA,SAC6B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AQ,CACjC;EAGF,MAAM,MAAM,sBAAsB,QAAQ,MAAM,YAAY;AAC5D,MAAI,QAAQ,GACV,QAAO;;AAIX,QAAO;;AAGT,SAAS,iBAAiB,YAA8B;AAItD,QAAO;EACL;EACA;EALW,WAAW,KAAK,cAAc,YAAY,WAAW,OAAO,CAAC,CACvE,KAAK,OAAO;EAMb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,SAAS,0BACP,oBACA,MAC4B;CAC5B,MAAM,cAA0C,EAAE;CAClD,IAAI,cAAc;AAElB,MAAK,MAAM,cAAc,oBAAoB;EAC3C,MAAM,iBAAiB,KAAK,QAAQ,WAAW,kBAAkB,YAAY;AAE7E,MAAI,mBAAmB,GACrB;AAGF,gBAAc,iBAAiB,WAAW,iBAAiB;AAC3D,cAAY,KAAK;GACf,eAAe,WAAW;GAC1B,aAAa,WAAW;GACxB,gBAAgB,iBAAiB,WAAW;GAC5C,cAAc,iBAAiB,WAAW;GAC3C,CAAC;;AAGJ,QAAO"}
package/dist/mod.d.ts CHANGED
@@ -1 +1,22 @@
1
+ /**
2
+ * Main entrypoint for `svelte-effect-runtime`.
3
+ *
4
+ * Re-exports the v3 public surface so that plain
5
+ * `import { ClientRuntime } from "svelte-effect-runtime"` resolves to the
6
+ * stable default runtime. For explicit version targeting see
7
+ * `svelte-effect-runtime/v3` and `svelte-effect-runtime/v4`.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { ClientRuntime, run_component_effect } from "svelte-effect-runtime";
12
+ * import { Effect } from "effect";
13
+ *
14
+ * const runtime = ClientRuntime.make();
15
+ * run_component_effect(runtime, Effect.log("hello from effect"));
16
+ * ```
17
+ *
18
+ * @see https://ser.barekey.dev/
19
+ *
20
+ * @module
21
+ */
1
22
  export * from "./v3/mod.js";
package/dist/mod.js CHANGED
@@ -1,3 +1,3 @@
1
- import { a as run_component_effect, c as to_native, o as run_inline_effect, r as get_effect_runtime_or_throw, s as to_effect, t as ClientRuntime } from "./chunks/client-DkW4e4dD.js";
2
- import "./chunks/v3-p8V3Drpp.js";
1
+ import { a as run_component_effect, c as to_native, o as run_inline_effect, r as get_effect_runtime_or_throw, s as to_effect, t as ClientRuntime } from "./chunks/client-vV6UAwoP.js";
2
+ import "./chunks/v3-D0c0MKPf.js";
3
3
  export { ClientRuntime, get_effect_runtime_or_throw, run_component_effect, run_inline_effect, to_effect, to_native };
@@ -22,3 +22,8 @@ export type { EffectPreprocessOptions } from "./v3/preprocess.js";
22
22
  * @see https://ser.barekey.dev/content/reference/preprocess
23
23
  */
24
24
  export declare function effect_preprocess(options?: EffectPreprocessOptions): PreprocessorGroup;
25
+ /**
26
+ * Backwards-compatible camelCase alias retained for older test fixtures and
27
+ * downstream code that imported the preprocessor before the snake_case rename.
28
+ */
29
+ export declare const effectPreprocess: typeof effect_preprocess;
@@ -9,7 +9,12 @@ import { t as effect_preprocess$1 } from "./chunks/preprocess-CtLrnJcK.js";
9
9
  function effect_preprocess(options) {
10
10
  return effect_preprocess$1(options);
11
11
  }
12
+ /**
13
+ * Backwards-compatible camelCase alias retained for older test fixtures and
14
+ * downstream code that imported the preprocessor before the snake_case rename.
15
+ */
16
+ const effectPreprocess = effect_preprocess;
12
17
  //#endregion
13
- export { effect_preprocess };
18
+ export { effectPreprocess, effect_preprocess };
14
19
 
15
20
  //# sourceMappingURL=preprocess.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"preprocess.js","names":["create_effect_preprocess"],"sources":["../../modules/svelte-effect-runtime/preprocess.ts"],"sourcesContent":["/**\n * Public preprocess entrypoint for `svelte-effect-runtime`.\n *\n * @example\n * ```ts\n * import { effect_preprocess } from \"svelte-effect-runtime/preprocess\";\n *\n * export default {\n * preprocess: [effect_preprocess()],\n * };\n * ```\n *\n * @module\n */\nimport type { PreprocessorGroup } from \"svelte/compiler\";\nimport {\n effect_preprocess as create_effect_preprocess,\n type EffectPreprocessOptions,\n} from \"$/v3/preprocess.ts\";\n\nexport type { EffectPreprocessOptions } from \"$/v3/preprocess.ts\";\n\n/**\n * Low-level `.svelte` preprocessor used by the higher-level `effect()`\n * plugin.\n *\n * @see https://ser.barekey.dev/content/reference/preprocess\n */\nexport function effect_preprocess(\n options?: EffectPreprocessOptions,\n): PreprocessorGroup {\n return create_effect_preprocess(options);\n}\n"],"mappings":";;;;;;;;AA4BA,SAAgB,kBACd,SACmB;AACnB,QAAOA,oBAAyB,QAAQ"}
1
+ {"version":3,"file":"preprocess.js","names":["create_effect_preprocess"],"sources":["../../modules/svelte-effect-runtime/preprocess.ts"],"sourcesContent":["/**\n * Public preprocess entrypoint for `svelte-effect-runtime`.\n *\n * @example\n * ```ts\n * import { effect_preprocess } from \"svelte-effect-runtime/preprocess\";\n *\n * export default {\n * preprocess: [effect_preprocess()],\n * };\n * ```\n *\n * @module\n */\nimport type { PreprocessorGroup } from \"svelte/compiler\";\nimport {\n effect_preprocess as create_effect_preprocess,\n type EffectPreprocessOptions,\n} from \"$/v3/preprocess.ts\";\n\nexport type { EffectPreprocessOptions } from \"$/v3/preprocess.ts\";\n\n/**\n * Low-level `.svelte` preprocessor used by the higher-level `effect()`\n * plugin.\n *\n * @see https://ser.barekey.dev/content/reference/preprocess\n */\nexport function effect_preprocess(\n options?: EffectPreprocessOptions,\n): PreprocessorGroup {\n return create_effect_preprocess(options);\n}\n\n/**\n * Backwards-compatible camelCase alias retained for older test fixtures and\n * downstream code that imported the preprocessor before the snake_case rename.\n */\nexport const effectPreprocess = effect_preprocess;\n"],"mappings":";;;;;;;;AA4BA,SAAgB,kBACd,SACmB;AACnB,QAAOA,oBAAyB,QAAQ;;;;;;AAO1C,MAAa,mBAAmB"}
package/dist/root-node.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as run_component_effect, c as to_native, o as run_inline_effect, r as get_effect_runtime_or_throw, s as to_effect, t as ClientRuntime } from "./chunks/client-DkW4e4dD.js";
2
- import "./chunks/v3-p8V3Drpp.js";
3
- import { a as RequestEvent$1, c as get_server_runtime_or_throw$1, i as Query$1, n as Form$1, o as ServerRuntime$1, r as Prerender$1, s as create_effect_transport$1, t as Command$1 } from "./chunks/server-CQcF2W3T.js";
1
+ import { a as run_component_effect, c as to_native, o as run_inline_effect, r as get_effect_runtime_or_throw, s as to_effect, t as ClientRuntime } from "./chunks/client-vV6UAwoP.js";
2
+ import "./chunks/v3-D0c0MKPf.js";
3
+ import { a as RequestEvent$1, c as get_server_runtime_or_throw$1, i as Query$1, n as Form$1, o as ServerRuntime$1, r as Prerender$1, s as create_effect_transport$1, t as Command$1 } from "./chunks/server-7YVuxUNk.js";
4
4
  import { t as effect } from "./chunks/effect-CL8GJs8A.js";
5
5
  //#region v3/root-node.ts
6
6
  /**
package/dist/server.d.ts CHANGED
@@ -1,3 +1,28 @@
1
+ /**
2
+ * Default server-side entrypoint for `svelte-effect-runtime`.
3
+ *
4
+ * Re-exports the v3 remote-function helpers (`Query`, `Command`, `Form`,
5
+ * `Prerender`), the `ServerRuntime` builder, and the `RequestEvent` service
6
+ * tag. Consumers normally import this module indirectly: the Vite plugin
7
+ * rewrites the public runtime specifier to this subpath inside `.remote.ts`
8
+ * files so the real implementation runs server-side.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { Query, ServerRuntime } from "svelte-effect-runtime/_server";
13
+ * import { Effect, Schema } from "effect";
14
+ *
15
+ * ServerRuntime.make();
16
+ *
17
+ * export const hello = Query(Schema.String, (name) =>
18
+ * Effect.succeed(`hello ${name}`)
19
+ * );
20
+ * ```
21
+ *
22
+ * @see https://ser.barekey.dev/content/reference/server-runtime
23
+ *
24
+ * @module
25
+ */
1
26
  import * as Server_module from "./v3/server.js";
2
27
  export type * from "./v3/server.js";
3
28
  /**
package/dist/server.js CHANGED
@@ -1,6 +1,31 @@
1
- import { a as RequestEvent$1, c as get_server_runtime_or_throw$1, i as Query$1, n as Form$1, o as ServerRuntime$1, r as Prerender$1, s as create_effect_transport$1, t as Command$1 } from "./chunks/server-CQcF2W3T.js";
1
+ import { a as RequestEvent$1, c as get_server_runtime_or_throw$1, i as Query$1, n as Form$1, o as ServerRuntime$1, r as Prerender$1, s as create_effect_transport$1, t as Command$1 } from "./chunks/server-7YVuxUNk.js";
2
2
  //#region server.ts
3
3
  /**
4
+ * Default server-side entrypoint for `svelte-effect-runtime`.
5
+ *
6
+ * Re-exports the v3 remote-function helpers (`Query`, `Command`, `Form`,
7
+ * `Prerender`), the `ServerRuntime` builder, and the `RequestEvent` service
8
+ * tag. Consumers normally import this module indirectly: the Vite plugin
9
+ * rewrites the public runtime specifier to this subpath inside `.remote.ts`
10
+ * files so the real implementation runs server-side.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { Query, ServerRuntime } from "svelte-effect-runtime/_server";
15
+ * import { Effect, Schema } from "effect";
16
+ *
17
+ * ServerRuntime.make();
18
+ *
19
+ * export const hello = Query(Schema.String, (name) =>
20
+ * Effect.succeed(`hello ${name}`)
21
+ * );
22
+ * ```
23
+ *
24
+ * @see https://ser.barekey.dev/content/reference/server-runtime
25
+ *
26
+ * @module
27
+ */
28
+ /**
4
29
  * Define a read-only remote function that returns an `Effect` on the client.
5
30
  *
6
31
  * @see https://ser.barekey.dev/content/remote-functions/query
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["Server_module.Query","Server_module.Command","Server_module.Form","Server_module.Prerender","Server_module.RequestEvent","Server_module.ServerRuntime","Server_module.create_effect_transport","Server_module\n .get_server_runtime_or_throw"],"sources":["../../modules/svelte-effect-runtime/server.ts"],"sourcesContent":["import * as Server_module from \"$/v3/server.ts\";\n\nexport type * from \"$/v3/server.ts\";\n\n/**\n * Define a read-only remote function that returns an `Effect` on the client.\n *\n * @see https://ser.barekey.dev/content/remote-functions/query\n */\nexport const Query: typeof Server_module.Query = Server_module.Query;\n/**\n * Define a write-oriented remote function that returns an `Effect` on the\n * client.\n *\n * @see https://ser.barekey.dev/content/remote-functions/command\n */\nexport const Command: typeof Server_module.Command = Server_module.Command;\n/**\n * Define a remote form handler that maps submitted data into an Effect\n * program.\n *\n * @see https://ser.barekey.dev/content/remote-functions/form\n */\nexport const Form: typeof Server_module.Form = Server_module.Form;\n/**\n * Define a prerenderable remote function backed by an Effect program.\n *\n * @see https://ser.barekey.dev/content/remote-functions/prerender\n */\nexport const Prerender: typeof Server_module.Prerender =\n Server_module.Prerender;\n/**\n * Effect `Context.Tag` for the current SvelteKit `RequestEvent`.\n *\n * @see https://ser.barekey.dev/content/runtimes/server\n */\nexport const RequestEvent: typeof Server_module.RequestEvent =\n Server_module.RequestEvent;\n/**\n * Server-side runtime builder used to provide long-lived Effect services to\n * remote functions.\n *\n * @see https://ser.barekey.dev/content/reference/server-runtime\n */\nexport const ServerRuntime: typeof Server_module.ServerRuntime =\n Server_module.ServerRuntime;\n/**\n * Build a devalue transport table from Effect schemas so remote payloads can\n * round-trip custom data across the client/server boundary.\n *\n * @see https://ser.barekey.dev/content/reference/transport\n */\nexport const create_effect_transport:\n typeof Server_module.create_effect_transport =\n Server_module.create_effect_transport;\n/**\n * Resolve the active server runtime, lazily creating a default empty runtime\n * when no explicit one has been registered.\n *\n * @internal Internal - do not use.\n * @see https://ser.barekey.dev/content/reference/server-runtime\n */\nexport const get_server_runtime_or_throw = Server_module\n .get_server_runtime_or_throw as typeof Server_module.get_server_runtime_or_throw;\n"],"mappings":";;;;;;;AASA,MAAa,QAAoCA;;;;;;;AAOjD,MAAa,UAAwCC;;;;;;;AAOrD,MAAa,OAAkCC;;;;;;AAM/C,MAAa,YACXC;;;;;;AAMF,MAAa,eACXC;;;;;;;AAOF,MAAa,gBACXC;;;;;;;AAOF,MAAa,0BAETC;;;;;;;;AAQJ,MAAa,8BAA8BC"}
1
+ {"version":3,"file":"server.js","names":["Server_module.Query","Server_module.Command","Server_module.Form","Server_module.Prerender","Server_module.RequestEvent","Server_module.ServerRuntime","Server_module.create_effect_transport","Server_module\n .get_server_runtime_or_throw"],"sources":["../../modules/svelte-effect-runtime/server.ts"],"sourcesContent":["/**\n * Default server-side entrypoint for `svelte-effect-runtime`.\n *\n * Re-exports the v3 remote-function helpers (`Query`, `Command`, `Form`,\n * `Prerender`), the `ServerRuntime` builder, and the `RequestEvent` service\n * tag. Consumers normally import this module indirectly: the Vite plugin\n * rewrites the public runtime specifier to this subpath inside `.remote.ts`\n * files so the real implementation runs server-side.\n *\n * @example\n * ```ts\n * import { Query, ServerRuntime } from \"svelte-effect-runtime/_server\";\n * import { Effect, Schema } from \"effect\";\n *\n * ServerRuntime.make();\n *\n * export const hello = Query(Schema.String, (name) =>\n * Effect.succeed(`hello ${name}`)\n * );\n * ```\n *\n * @see https://ser.barekey.dev/content/reference/server-runtime\n *\n * @module\n */\nimport * as Server_module from \"$/v3/server.ts\";\n\nexport type * from \"$/v3/server.ts\";\n\n/**\n * Define a read-only remote function that returns an `Effect` on the client.\n *\n * @see https://ser.barekey.dev/content/remote-functions/query\n */\nexport const Query: typeof Server_module.Query = Server_module.Query;\n/**\n * Define a write-oriented remote function that returns an `Effect` on the\n * client.\n *\n * @see https://ser.barekey.dev/content/remote-functions/command\n */\nexport const Command: typeof Server_module.Command = Server_module.Command;\n/**\n * Define a remote form handler that maps submitted data into an Effect\n * program.\n *\n * @see https://ser.barekey.dev/content/remote-functions/form\n */\nexport const Form: typeof Server_module.Form = Server_module.Form;\n/**\n * Define a prerenderable remote function backed by an Effect program.\n *\n * @see https://ser.barekey.dev/content/remote-functions/prerender\n */\nexport const Prerender: typeof Server_module.Prerender =\n Server_module.Prerender;\n/**\n * Effect `Context.Tag` for the current SvelteKit `RequestEvent`.\n *\n * @see https://ser.barekey.dev/content/runtimes/server\n */\nexport const RequestEvent: typeof Server_module.RequestEvent =\n Server_module.RequestEvent;\n/**\n * Server-side runtime builder used to provide long-lived Effect services to\n * remote functions.\n *\n * @see https://ser.barekey.dev/content/reference/server-runtime\n */\nexport const ServerRuntime: typeof Server_module.ServerRuntime =\n Server_module.ServerRuntime;\n/**\n * Build a devalue transport table from Effect schemas so remote payloads can\n * round-trip custom data across the client/server boundary.\n *\n * @see https://ser.barekey.dev/content/reference/transport\n */\nexport const create_effect_transport:\n typeof Server_module.create_effect_transport =\n Server_module.create_effect_transport;\n/**\n * Resolve the active server runtime, lazily creating a default empty runtime\n * when no explicit one has been registered.\n *\n * @internal Internal - do not use.\n * @see https://ser.barekey.dev/content/reference/server-runtime\n */\nexport const get_server_runtime_or_throw = Server_module\n .get_server_runtime_or_throw as typeof Server_module.get_server_runtime_or_throw;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,QAAoCA;;;;;;;AAOjD,MAAa,UAAwCC;;;;;;;AAOrD,MAAa,OAAkCC;;;;;;AAM/C,MAAa,YACXC;;;;;;AAMF,MAAa,eACXC;;;;;;;AAOF,MAAa,gBACXC;;;;;;;AAOF,MAAa,0BAETC;;;;;;;;AAQJ,MAAa,8BAA8BC"}
@@ -1,13 +1,37 @@
1
1
  import { Effect, Exit, Layer, ManagedRuntime } from "effect";
2
2
  import { type RemoteFailure } from "../internal/remote-shared.js";
3
+ /**
4
+ * Minimal runtime abstraction the client adapters rely on. Implemented by the
5
+ * Effect `ManagedRuntime` returned from {@link ClientRuntime.make}, but
6
+ * callers may substitute their own object conforming to this shape.
7
+ *
8
+ * @see https://ser.barekey.dev/content/reference/client-runtime
9
+ */
3
10
  export interface EffectRuntime<R = unknown> {
11
+ /**
12
+ * Execute an Effect and receive a cancellation token. The optional `onExit`
13
+ * callback fires with the final `Exit` value once the fiber completes.
14
+ */
4
15
  runCallback<A, E, R2>(effect: Effect.Effect<A, E, R2>, options?: {
5
16
  onExit?: (exit: Exit.Exit<A, E>) => void;
6
17
  }): () => void;
18
+ /**
19
+ * Execute an Effect and return a Promise that resolves with the success
20
+ * value or rejects with the propagated failure.
21
+ */
7
22
  runPromise<A, E, R2>(effect: Effect.Effect<A, E, R2>): Promise<A>;
23
+ /**
24
+ * Tear down the runtime and release any resources held by its root scope.
25
+ */
8
26
  dispose(): Promise<void>;
9
27
  }
10
28
  export type { FormError, FormIssue, RemoteDomainError, RemoteFailure, RemoteHttpError, RemoteTransportError, RemoteValidationError, } from "../internal/remote-shared.js";
29
+ /**
30
+ * Alias for {@link EffectRuntime} exposed as a stable service name used by
31
+ * generated code and documentation.
32
+ *
33
+ * @see https://ser.barekey.dev/content/reference/client-runtime
34
+ */
11
35
  export interface ClientRuntimeService extends EffectRuntime<unknown> {
12
36
  }
13
37
  type RuntimeSeedLayer<R> = Layer.Layer<R, never, R>;
package/dist/v3/mod.d.ts CHANGED
@@ -1,3 +1,27 @@
1
+ /**
2
+ * v3 public entrypoint for `svelte-effect-runtime`.
3
+ *
4
+ * Exposes the stable client runtime, lifecycle helpers, and shared remote
5
+ * error / result types. Import from `svelte-effect-runtime/v3` to pin against
6
+ * the v3 runtime explicitly; the package default entry (`mod.ts`) re-exports
7
+ * everything here.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import {
12
+ * ClientRuntime,
13
+ * run_component_effect,
14
+ * } from "svelte-effect-runtime/v3";
15
+ * import { Effect } from "effect";
16
+ *
17
+ * const runtime = ClientRuntime.make();
18
+ * run_component_effect(runtime, Effect.log("hi from v3"));
19
+ * ```
20
+ *
21
+ * @see https://ser.barekey.dev/
22
+ *
23
+ * @module
24
+ */
1
25
  export type { EffectPreprocessOptions } from "./preprocess.js";
2
26
  export type { ClientRuntimeService, EffectRuntime, FormError, FormIssue, RemoteDomainError, RemoteFailure, RemoteHttpError, RemoteTransportError, RemoteValidationError, } from "./client.js";
3
27
  export { ClientRuntime, get_effect_runtime_or_throw, run_component_effect, run_inline_effect, to_effect, to_native, } from "./client.js";
@@ -4,21 +4,43 @@ import { Effect, Layer, ManagedRuntime, Schema } from "effect";
4
4
  import type { Context } from "effect";
5
5
  import { type FormError } from "../internal/remote-shared.js";
6
6
  type EffectSchema = Schema.Schema.Any;
7
+ /**
8
+ * Single entry in a {@link Transport} table. Describes how to encode a value
9
+ * of type `T` to a wire payload and decode it back.
10
+ *
11
+ * @see https://ser.barekey.dev/content/reference/transport
12
+ */
7
13
  export interface Transporter<T = unknown, U = {
8
14
  value: unknown;
9
15
  }> {
16
+ /** Restore the original value from the wire payload. */
10
17
  decode: (data: U) => T;
18
+ /**
19
+ * Encode the value to a wire payload, or return `false` when this transporter
20
+ * does not apply to the supplied value.
21
+ */
11
22
  encode: (value: T) => false | U;
12
23
  }
24
+ /**
25
+ * Named collection of {@link Transporter}s, passed to devalue so custom types
26
+ * survive the client/server round-trip.
27
+ *
28
+ * @see https://ser.barekey.dev/content/reference/transport
29
+ */
13
30
  export type Transport = Record<string, Transporter>;
31
+ /** Alias for SvelteKit's native remote-form input shape. */
14
32
  export type RemoteFormInput = SvelteKitRemoteFormInput;
33
+ /** SvelteKit's native `query` function signature, re-exported for typing. */
15
34
  export type RemoteQueryFunction<Input, Output> = (arg: OptionalArgument<Input>) => Promise<Output>;
35
+ /** SvelteKit's native `command` shape, re-exported for typing. */
16
36
  export type RemoteCommand<Input, Output> = ((arg: OptionalArgument<Input>) => Promise<Output> & {
17
37
  updates(...updates: Array<unknown>): Promise<Output>;
18
38
  }) & {
19
39
  readonly pending: number;
20
40
  };
41
+ /** SvelteKit's native `prerender` function signature, re-exported for typing. */
21
42
  export type RemotePrerenderFunction<Input, Output> = (arg: OptionalArgument<Input>) => Promise<Output>;
43
+ /** SvelteKit's native `form` shape, re-exported for typing. */
22
44
  export type RemoteForm<Input extends RemoteFormInput | void, Output> = SvelteKitRemoteForm<Input, Output>;
23
45
  type RuntimeOperator = (self: Layer.Layer<unknown, unknown, unknown>) => Layer.Layer<unknown, unknown, unknown>;
24
46
  type RuntimeSeedLayer<Requirements> = Layer.Layer<Requirements, never, Requirements>;
@@ -33,24 +55,70 @@ type SchemaOutput<SchemaType extends EffectSchema> = Schema.Schema.Type<SchemaTy
33
55
  type FieldHelpers<FormShape, SchemaType> = FormShape extends Record<string, unknown> ? {
34
56
  [Key in keyof FormShape as Key extends string ? Key : never]: (message: string) => Effect.Effect<never, FormError<SchemaType>, never>;
35
57
  } : Record<PropertyKey, never>;
58
+ /**
59
+ * Proxy passed into `Form` handlers for reporting validation issues. Call
60
+ * `invalid.form(message)` for a top-level issue, or `invalid.<field>(message)`
61
+ * to attach the issue to a specific field declared in the schema.
62
+ *
63
+ * @see https://ser.barekey.dev/content/remote-functions/form
64
+ */
36
65
  export type Invalid<SchemaType = unknown> = {
66
+ /** Attach a top-level form issue with the supplied message. */
37
67
  form: (message: string) => Effect.Effect<never, FormError<SchemaType>, never>;
38
68
  } & FieldHelpers<SchemaType extends EffectSchema ? SchemaOutput<SchemaType> : unknown, SchemaType>;
69
+ /**
70
+ * Shape of an Effect-returning remote `query`. Callable with the validated
71
+ * input; exposes the underlying SvelteKit function via `native`.
72
+ *
73
+ * @see https://ser.barekey.dev/content/remote-functions/query
74
+ */
39
75
  export type EffectQueryFunction<Input, Output, Error = never> = ((arg: OptionalArgument<Input>) => Effect.Effect<Output, import("../internal/remote-shared.js").RemoteFailure<Error>, never>) & {
76
+ /** Underlying SvelteKit `query` function, for fallback direct usage. */
40
77
  native: RemoteQueryFunction<Input, Output>;
41
78
  };
79
+ /**
80
+ * Shape of an Effect-returning remote `command`. Callable with the validated
81
+ * input; exposes the underlying SvelteKit command via `native` and tracks
82
+ * in-flight submissions through `pending`.
83
+ *
84
+ * @see https://ser.barekey.dev/content/remote-functions/command
85
+ */
42
86
  export type EffectCommand<Input, Output, Error = never> = ((arg: OptionalArgument<Input>) => Effect.Effect<Output, import("../internal/remote-shared.js").RemoteFailure<Error>, never>) & {
87
+ /** Underlying SvelteKit `command` function, for fallback direct usage. */
43
88
  native: RemoteCommand<Input, Output>;
89
+ /** Count of currently in-flight invocations of this command. */
44
90
  readonly pending: number;
45
91
  };
92
+ /**
93
+ * Shape of an Effect-returning remote `prerender` function. Callable with the
94
+ * validated input; exposes the underlying SvelteKit function via `native`.
95
+ *
96
+ * @see https://ser.barekey.dev/content/remote-functions/prerender
97
+ */
46
98
  export type EffectPrerenderFunction<Input, Output, Error = never> = ((arg: OptionalArgument<Input>) => Effect.Effect<Output, import("../internal/remote-shared.js").RemoteFailure<Error>, never>) & {
99
+ /** Underlying SvelteKit `prerender` function, for fallback direct usage. */
47
100
  native: RemotePrerenderFunction<Input, Output>;
48
101
  };
102
+ /**
103
+ * Shape of an Effect-returning remote `form`. Usable anywhere the native
104
+ * SvelteKit form is; additionally exposes `submit(data)` to run the form
105
+ * program as an Effect, and `for(...)` to clone the binding for a given
106
+ * input.
107
+ *
108
+ * @see https://ser.barekey.dev/content/remote-functions/form
109
+ */
49
110
  export type EffectForm<Input extends RemoteFormInput | void, Output, Error = never> = RemoteForm<Input, Output> & {
111
+ /** Underlying SvelteKit `form` object, for fallback direct usage. */
50
112
  native: RemoteForm<Input, Output>;
113
+ /** Submit the form programmatically and receive the result as an Effect. */
51
114
  submit(data: OptionalArgument<Input>): Effect.Effect<Output, import("../internal/remote-shared.js").RemoteFailure<Error>, never>;
115
+ /** Clone the form binding for a specific value - mirrors `RemoteForm.for`. */
52
116
  for: RemoteForm<Input, Output>["for"] extends (...args: infer Args) => infer Result ? (...args: Args) => EffectForm<Input, Output, Error> : never;
53
117
  };
118
+ /**
119
+ * Type of the SvelteKit `RequestEvent` exposed through the {@link RequestEvent}
120
+ * Effect service.
121
+ */
54
122
  export type RequestEventService = ReturnType<typeof get_native_request_event>;
55
123
  /**
56
124
  * Effect `Context.Tag` for the current SvelteKit `RequestEvent`.
@@ -100,10 +168,20 @@ export declare function normalize_remote_helper_error(error: unknown): unknown;
100
168
  * @see https://ser.barekey.dev/content/reference/transport
101
169
  */
102
170
  export declare function create_effect_transport<const Schemas extends Record<string, EffectSchema>>(schemas: Schemas): Transport;
171
+ /**
172
+ * Overload set for the {@link Query} factory. Supports no-arg, `"unchecked"`,
173
+ * and Effect.Schema-validated definitions, plus `Query.batch(...)`.
174
+ *
175
+ * @see https://ser.barekey.dev/content/remote-functions/query
176
+ */
103
177
  export interface EffectQueryFactory {
178
+ /** Define a void-input query. */
104
179
  <Output, ErrorType, Requirements>(fn: () => Effect.Effect<Output, ErrorType, Requirements>): EffectQueryFunction<void, Output, ErrorType>;
180
+ /** Define a query that bypasses schema validation. */
105
181
  <Input, Output, ErrorType, Requirements>(validate: "unchecked", fn: (arg: Input) => Effect.Effect<Output, ErrorType, Requirements>): EffectQueryFunction<Input, Output, ErrorType>;
182
+ /** Define a query whose input is validated by an Effect.Schema. */
106
183
  <SchemaType extends EffectSchema, Output, ErrorType, Requirements>(validate: SchemaType, fn: (arg: SchemaOutput<SchemaType>) => Effect.Effect<Output, ErrorType, Requirements>): EffectQueryFunction<SchemaInput<SchemaType>, Output, ErrorType>;
184
+ /** Define a batched query - mirrors SvelteKit's `query.batch`. */
107
185
  batch: typeof query_batch_factory;
108
186
  }
109
187
  type RemotePrerenderInputsGenerator<Input> = (event: RequestEventService) => AsyncIterable<Input> | Iterable<Input>;
@@ -114,9 +192,18 @@ declare function query_batch_factory(validate_or_fn: unknown, maybe_fn?: unknown
114
192
  * @see https://ser.barekey.dev/content/remote-functions/query
115
193
  */
116
194
  export declare const Query: EffectQueryFactory;
195
+ /**
196
+ * Overload set for the {@link Command} factory. Supports no-arg,
197
+ * `"unchecked"`, and Effect.Schema-validated definitions.
198
+ *
199
+ * @see https://ser.barekey.dev/content/remote-functions/command
200
+ */
117
201
  export interface EffectCommandFactory {
202
+ /** Define a void-input command. */
118
203
  <Output, ErrorType, Requirements>(fn: () => Effect.Effect<Output, ErrorType, Requirements>): EffectCommand<void, Output, ErrorType>;
204
+ /** Define a command that bypasses schema validation. */
119
205
  <Input, Output, ErrorType, Requirements>(validate: "unchecked", fn: (arg: Input) => Effect.Effect<Output, ErrorType, Requirements>): EffectCommand<Input, Output, ErrorType>;
206
+ /** Define a command whose input is validated by an Effect.Schema. */
120
207
  <SchemaType extends EffectSchema, Output, ErrorType, Requirements>(validate: SchemaType, fn: (arg: SchemaOutput<SchemaType>) => Effect.Effect<Output, ErrorType, Requirements>): EffectCommand<SchemaInput<SchemaType>, Output, ErrorType>;
121
208
  }
122
209
  /**
@@ -126,12 +213,21 @@ export interface EffectCommandFactory {
126
213
  * @see https://ser.barekey.dev/content/remote-functions/command
127
214
  */
128
215
  export declare const Command: EffectCommandFactory;
216
+ /**
217
+ * Overload set for the {@link Form} factory. Supports no-arg, `"unchecked"`,
218
+ * and Effect.Schema-validated form handlers.
219
+ *
220
+ * @see https://ser.barekey.dev/content/remote-functions/form
221
+ */
129
222
  export interface EffectFormFactory {
223
+ /** Define a form handler with no input data. */
130
224
  <Output, ErrorType, Requirements>(fn: () => Effect.Effect<Output, ErrorType, Requirements>): EffectForm<void, Output, ErrorType>;
225
+ /** Define a form handler that bypasses schema validation. */
131
226
  <Input extends RemoteFormInput, Output, ErrorType, Requirements>(validate: "unchecked", fn: (args: {
132
227
  data: Input;
133
228
  invalid: Invalid;
134
229
  }) => Effect.Effect<Output, ErrorType | FormError, Requirements>): EffectForm<Input, Output, ErrorType>;
230
+ /** Define a form handler whose submitted data is validated by a schema. */
135
231
  <SchemaType extends EffectSchema, Output, ErrorType, Requirements>(validate: SchemaType, fn: (args: {
136
232
  data: SchemaOutput<SchemaType>;
137
233
  invalid: Invalid<SchemaType>;
@@ -144,15 +240,25 @@ export interface EffectFormFactory {
144
240
  * @see https://ser.barekey.dev/content/remote-functions/form
145
241
  */
146
242
  export declare const Form: EffectFormFactory;
243
+ /**
244
+ * Overload set for the {@link Prerender} factory. Accepts the same three
245
+ * validation flavours as the other factories, plus a SvelteKit `options` bag
246
+ * with `inputs` / `dynamic` flags.
247
+ *
248
+ * @see https://ser.barekey.dev/content/remote-functions/prerender
249
+ */
147
250
  export interface EffectPrerenderFactory {
251
+ /** Define a void-input prerender function. */
148
252
  <Output, ErrorType, Requirements>(fn: () => Effect.Effect<Output, ErrorType, Requirements>, options?: {
149
253
  inputs?: RemotePrerenderInputsGenerator<void>;
150
254
  dynamic?: boolean;
151
255
  }): EffectPrerenderFunction<void, Output, ErrorType>;
256
+ /** Define a prerender function that bypasses schema validation. */
152
257
  <Input, Output, ErrorType, Requirements>(validate: "unchecked", fn: (arg: Input) => Effect.Effect<Output, ErrorType, Requirements>, options?: {
153
258
  inputs?: RemotePrerenderInputsGenerator<Input>;
154
259
  dynamic?: boolean;
155
260
  }): EffectPrerenderFunction<Input, Output, ErrorType>;
261
+ /** Define a prerender function whose input is validated by a schema. */
156
262
  <SchemaType extends EffectSchema, Output, ErrorType, Requirements>(validate: SchemaType, fn: (arg: SchemaOutput<SchemaType>) => Effect.Effect<Output, ErrorType, Requirements>, options?: {
157
263
  inputs?: RemotePrerenderInputsGenerator<SchemaInput<SchemaType>>;
158
264
  dynamic?: boolean;
package/dist/v4/mod.d.ts CHANGED
@@ -1,3 +1,27 @@
1
+ /**
2
+ * v4 public entrypoint for `svelte-effect-runtime`.
3
+ *
4
+ * Targets Effect v4 (beta) while sharing the underlying client helpers with
5
+ * v3. Importing from `svelte-effect-runtime/v4` opts into the v4 preprocess /
6
+ * Vite pipeline and the v4-flavoured server helpers exposed through the
7
+ * `/v4/_server` subpath.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import {
12
+ * ClientRuntime,
13
+ * run_component_effect,
14
+ * } from "svelte-effect-runtime/v4";
15
+ * import { Effect } from "effect";
16
+ *
17
+ * const runtime = ClientRuntime.make();
18
+ * run_component_effect(runtime, Effect.log("hi from v4"));
19
+ * ```
20
+ *
21
+ * @see https://ser.barekey.dev/
22
+ *
23
+ * @module
24
+ */
1
25
  export type { EffectPreprocessOptions } from "./preprocess.js";
2
26
  export type { ClientRuntimeService, EffectRuntime, FormError, FormIssue, RemoteDomainError, RemoteFailure, RemoteHttpError, RemoteTransportError, RemoteValidationError, } from "./client.js";
3
27
  export { ClientRuntime, get_effect_runtime_or_throw, run_component_effect, run_inline_effect, to_effect, to_native, } from "./client.js";
package/dist/v4/mod.js CHANGED
@@ -1,3 +1,3 @@
1
- import { a as run_component_effect, c as to_native, o as run_inline_effect, r as get_effect_runtime_or_throw, s as to_effect, t as ClientRuntime } from "../chunks/client-DkW4e4dD.js";
2
- import "../chunks/v4-DIhYCbb_.js";
1
+ import { a as run_component_effect, c as to_native, o as run_inline_effect, r as get_effect_runtime_or_throw, s as to_effect, t as ClientRuntime } from "../chunks/client-vV6UAwoP.js";
2
+ import "../chunks/v4-MMhHmzIG.js";
3
3
  export { ClientRuntime, get_effect_runtime_or_throw, run_component_effect, run_inline_effect, to_effect, to_native };
@@ -28,3 +28,7 @@ export declare function with_v4_effect_preprocess_options(options?: EffectPrepro
28
28
  * @see https://ser.barekey.dev/content/reference/preprocess
29
29
  */
30
30
  export declare function effect_preprocess(options?: EffectPreprocessOptions): PreprocessorGroup;
31
+ /**
32
+ * Backwards-compatible camelCase alias retained for older downstream imports.
33
+ */
34
+ export declare const effectPreprocess: typeof effect_preprocess;
@@ -22,7 +22,11 @@ function with_v4_effect_preprocess_options(options = {}) {
22
22
  function effect_preprocess(options = {}) {
23
23
  return effect_preprocess$1(with_v4_effect_preprocess_options(options));
24
24
  }
25
+ /**
26
+ * Backwards-compatible camelCase alias retained for older downstream imports.
27
+ */
28
+ const effectPreprocess = effect_preprocess;
25
29
  //#endregion
26
- export { V4_RUNTIME_MODULE_ID, effect_preprocess, with_v4_effect_preprocess_options };
30
+ export { V4_RUNTIME_MODULE_ID, effectPreprocess, effect_preprocess, with_v4_effect_preprocess_options };
27
31
 
28
32
  //# sourceMappingURL=preprocess.js.map