From 7d8d7bac15f056f23ef6ecfb93798095acd2fb46 Mon Sep 17 00:00:00 2001 From: Yuichiro Yamashita Date: Sun, 22 May 2022 15:16:49 +0900 Subject: [PATCH] improve validation --- .../wrappers/InlineComponent/index.ts | 6 ++---- src/runtime/internal/dev.ts | 18 +++++++++++++++--- src/runtime/internal/dom.ts | 4 ++++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/compiler/compile/render_dom/wrappers/InlineComponent/index.ts b/src/compiler/compile/render_dom/wrappers/InlineComponent/index.ts index 7523d79e41..3395baefc4 100644 --- a/src/compiler/compile/render_dom/wrappers/InlineComponent/index.ts +++ b/src/compiler/compile/render_dom/wrappers/InlineComponent/index.ts @@ -416,8 +416,7 @@ export default class InlineComponentWrapper extends Wrapper { } if (${switch_value}) { - ${component.compile_options.dev && b`@validate_svelte_component(${switch_value});`} - ${name} = new ${switch_value}(${switch_props}(#ctx)); + ${name} = @construct_svelte_component(${switch_value}, ${switch_props}(#ctx)); ${munged_bindings} ${munged_handlers} @@ -461,8 +460,7 @@ export default class InlineComponentWrapper extends Wrapper { } if (${switch_value}) { - ${component.compile_options.dev && b`@validate_svelte_component(${switch_value});`} - ${name} = new ${switch_value}(${switch_props}(#ctx)); + ${name} = @construct_svelte_component(${switch_value}, ${switch_props}(#ctx)); ${munged_bindings} ${munged_handlers} diff --git a/src/runtime/internal/dev.ts b/src/runtime/internal/dev.ts index 502afd88d6..3907b91372 100644 --- a/src/runtime/internal/dev.ts +++ b/src/runtime/internal/dev.ts @@ -121,9 +121,21 @@ export function validate_void_dynamic_element(tag: undefined | string) { } } -export function validate_svelte_component(component: any) { - if (!(component.prototype instanceof SvelteComponent)) { - throw new Error('this={...} of should specify a Svelte component.'); +export function construct_svelte_component_dev(component, props) { + const error_message = 'this={...} of should specify a Svelte component.'; + try { + const instance = new component(props); + if (!instance.$$ || !instance.$set || !instance.$on || !instance.$destroy) { + throw new Error(error_message); + } + return instance; + } catch (err) { + const { message } = err; + if (typeof message === 'string' && message.indexOf('is not a constructor') !== -1) { + throw new Error(error_message); + } else { + throw err; + } } } diff --git a/src/runtime/internal/dom.ts b/src/runtime/internal/dom.ts index cadc1abbaa..77c2b67aa2 100644 --- a/src/runtime/internal/dom.ts +++ b/src/runtime/internal/dom.ts @@ -740,3 +740,7 @@ export function get_custom_elements_slots(element: HTMLElement) { }); return result; } + +export function construct_svelte_component(component, props) { + return new component(props); +}