import MagicString, { Bundle } from 'magic-string'; import { walk, childKeys } from 'estree-walker'; import { getLocator } from 'locate-character'; import Stats from '../Stats'; import reservedNames from '../utils/reservedNames'; import { namespaces, validNamespaces } from '../utils/namespaces'; import { removeNode } from '../utils/removeNode'; import wrapModule from './wrapModule'; import { createScopes, extractNames, Scope } from '../utils/annotateWithScopes'; import Stylesheet from './css/Stylesheet'; import { test } from '../config'; import Fragment from './nodes/Fragment'; import internal_exports from './internal-exports'; import { Node, Ast, CompileOptions, Var, Warning } from '../interfaces'; import error from '../utils/error'; import getCodeFrame from '../utils/getCodeFrame'; import flattenReference from '../utils/flattenReference'; import isReference from 'is-reference'; import TemplateScope from './nodes/shared/TemplateScope'; import fuzzymatch from '../utils/fuzzymatch'; import { remove_indentation, add_indentation } from '../utils/indentation'; import getObject from '../utils/getObject'; import globalWhitelist from '../utils/globalWhitelist'; type ComponentOptions = { namespace?: string; tag?: string; immutable?: boolean; props?: string; props_object?: string; props_node?: Node; }; // We need to tell estree-walker that it should always // look for an `else` block, otherwise it might get // the wrong idea about the shape of each/if blocks childKeys.EachBlock = childKeys.IfBlock = ['children', 'else']; childKeys.Attribute = ['value']; childKeys.ExportNamedDeclaration = ['declaration', 'specifiers']; export default class Component { stats: Stats; warnings: Warning[]; ast: Ast; source: string; code: MagicString; name: string; compileOptions: CompileOptions; fragment: Fragment; module_scope: Scope; instance_scope: Scope; instance_scope_map: WeakMap; componentOptions: ComponentOptions; namespace: string; tag: string; vars: Var[] = []; var_lookup: Map = new Map(); imports: Node[] = []; module_javascript: string; javascript: string; hoistable_nodes: Set = new Set(); node_for_declaration: Map = new Map(); partly_hoisted: string[] = []; fully_hoisted: string[] = []; reactive_declarations: Array<{ assignees: Set, dependencies: Set, node: Node, injected: boolean }> = []; reactive_declaration_nodes: Set = new Set(); has_reactive_assignments = false; injected_reactive_declaration_vars: Set = new Set(); helpers: Set = new Set(); indirectDependencies: Map> = new Map(); file: string; locate: (c: number) => { line: number, column: number }; // TODO this does the same as component.locate! remove one or the other locator: (search: number, startIndex?: number) => { line: number, column: number }; stylesheet: Stylesheet; aliases: Map = new Map(); usedNames: Set = new Set(); constructor( ast: Ast, source: string, name: string, compileOptions: CompileOptions, stats: Stats, warnings: Warning[] ) { this.name = name; this.stats = stats; this.warnings = warnings; this.ast = ast; this.source = source; this.compileOptions = compileOptions; this.file = compileOptions.filename && ( typeof process !== 'undefined' ? compileOptions.filename.replace(process.cwd(), '').replace(/^[\/\\]/, '') : compileOptions.filename ); this.locate = getLocator(this.source); this.code = new MagicString(source); // styles this.stylesheet = new Stylesheet(source, ast, compileOptions.filename, compileOptions.dev); this.stylesheet.validate(this); this.componentOptions = process_component_options(this, this.ast.html.children); this.namespace = namespaces[this.componentOptions.namespace] || this.componentOptions.namespace; if (compileOptions.customElement === true && !this.componentOptions.tag) { throw new Error(`No tag name specified`); // TODO better error } this.tag = compileOptions.customElement ? compileOptions.customElement === true ? this.componentOptions.tag : compileOptions.customElement as string : this.name; this.walk_module_js(); this.walk_instance_js_pre_template(); if (this.componentOptions.props) { this.has_reactive_assignments = true; const name = this.componentOptions.props_object; if (!this.ast.module && !this.ast.instance) { this.add_var({ name, export_name: name, implicit: true }); } const variable = this.var_lookup.get(name); if (!variable) { this.error(this.componentOptions.props_node, { code: 'missing-declaration', message: `'${name}' is not defined` }); } variable.reassigned = true; } this.name = this.getUniqueName(name); this.fragment = new Fragment(this, ast.html); this.walk_instance_js_post_template(); if (!compileOptions.customElement) this.stylesheet.reify(); this.stylesheet.warnOnUnusedSelectors(this); } add_var(variable: Var) { this.vars.push(variable); this.var_lookup.set(variable.name, variable); } add_reference(name: string) { const variable = this.var_lookup.get(name); if (variable) { variable.referenced = true; } else if (name[0] === '$') { this.add_var({ name, injected: true, referenced: true, mutated: true, writable: true }); const subscribable_name = name.slice(1); this.add_reference(subscribable_name); const variable = this.var_lookup.get(subscribable_name); variable.subscribable = true; } else if (!this.ast.instance) { this.add_var({ name, export_name: name, implicit: true, mutated: false, referenced: true, writable: true }); } } addSourcemapLocations(node: Node) { walk(node, { enter: (node: Node) => { this.code.addSourcemapLocation(node.start); this.code.addSourcemapLocation(node.end); }, }); } alias(name: string) { if (!this.aliases.has(name)) { this.aliases.set(name, this.getUniqueName(name)); } return this.aliases.get(name); } helper(name: string) { this.helpers.add(name); return this.alias(name); } generate(result: string) { let js = null; let css = null; if (result) { const { compileOptions, name } = this; const { format = 'esm' } = compileOptions; const banner = `/* ${this.file ? `${this.file} ` : ``}generated by Svelte v${"__VERSION__"} */`; // TODO use same regex for both result = result.replace(compileOptions.generate === 'ssr' ? /(@+|#+)(\w*(?:-\w*)?)/g : /(@+)(\w*(?:-\w*)?)/g, (match: string, sigil: string, name: string) => { if (sigil === '@') { if (internal_exports.has(name)) { if (compileOptions.dev && internal_exports.has(`${name}Dev`)) name = `${name}Dev`; this.helpers.add(name); } return this.alias(name); } return sigil.slice(1) + name; }); const importedHelpers = Array.from(this.helpers) .sort() .map(name => { const alias = this.alias(name); return { name, alias }; }); const module = wrapModule( result, format, name, compileOptions, banner, compileOptions.sveltePath, importedHelpers, this.imports, this.vars.filter(variable => variable.module && variable.export_name).map(variable => ({ name: variable.name, as: variable.export_name })), this.source ); const parts = module.split('✂]'); const finalChunk = parts.pop(); const compiled = new Bundle({ separator: '' }); function addString(str: string) { compiled.addSource({ content: new MagicString(str), }); } const { filename } = compileOptions; // special case — the source file doesn't actually get used anywhere. we need // to add an empty file to populate map.sources and map.sourcesContent if (!parts.length) { compiled.addSource({ filename, content: new MagicString(this.source).remove(0, this.source.length), }); } const pattern = /\[✂(\d+)-(\d+)$/; parts.forEach((str: string) => { const chunk = str.replace(pattern, ''); if (chunk) addString(chunk); const match = pattern.exec(str); const snippet = this.code.snip(+match[1], +match[2]); compiled.addSource({ filename, content: snippet, }); }); addString(finalChunk); css = compileOptions.customElement ? { code: null, map: null } : this.stylesheet.render(compileOptions.cssOutputFilename, true); js = { code: compiled.toString(), map: compiled.generateMap({ includeContent: true, file: compileOptions.outputFilename, }) }; } return { js, css, ast: this.ast, warnings: this.warnings, vars: this.vars.filter(v => !v.global && !v.implicit && !v.internal).map(v => ({ name: v.name, export_name: v.export_name || null, injected: v.injected || false, module: v.module || false, mutated: v.mutated || false, reassigned: v.reassigned || false, referenced: v.referenced || false, writable: v.writable || false })), stats: this.stats.render() }; } getUniqueName(name: string) { if (test) name = `${name}$`; let alias = name; for ( let i = 1; reservedNames.has(alias) || this.var_lookup.has(alias) || this.usedNames.has(alias); alias = `${name}_${i++}` ); this.usedNames.add(alias); return alias; } getUniqueNameMaker() { const localUsedNames = new Set(); function add(name: string) { localUsedNames.add(name); } reservedNames.forEach(add); this.var_lookup.forEach((value, key) => add(key)); return (name: string) => { if (test) name = `${name}$`; let alias = name; for ( let i = 1; this.usedNames.has(alias) || localUsedNames.has(alias); alias = `${name}_${i++}` ); localUsedNames.add(alias); return alias; }; } error( pos: { start: number, end: number }, e : { code: string, message: string } ) { error(e.message, { name: 'ValidationError', code: e.code, source: this.source, start: pos.start, end: pos.end, filename: this.compileOptions.filename }); } warn( pos: { start: number, end: number }, warning: { code: string, message: string } ) { if (!this.locator) { this.locator = getLocator(this.source, { offsetLine: 1 }); } const start = this.locator(pos.start); const end = this.locator(pos.end); const frame = getCodeFrame(this.source, start.line - 1, start.column); this.warnings.push({ code: warning.code, message: warning.message, frame, start, end, pos: pos.start, filename: this.compileOptions.filename, toString: () => `${warning.message} (${start.line + 1}:${start.column})\n${frame}`, }); } extract_imports(content) { const { code } = this; content.body.forEach(node => { if (node.type === 'ImportDeclaration') { // imports need to be hoisted out of the IIFE removeNode(code, content.start, content.end, content.body, node); this.imports.push(node); } }); } extract_exports(content) { const { code } = this; content.body.forEach(node => { if (node.type === 'ExportDefaultDeclaration') { this.error(node, { code: `default-export`, message: `A component cannot have a default export` }); } if (node.type === 'ExportNamedDeclaration') { if (node.declaration) { if (node.declaration.type === 'VariableDeclaration') { node.declaration.declarations.forEach(declarator => { extractNames(declarator.id).forEach(name => { const variable = this.var_lookup.get(name); variable.export_name = name; }); }); } else { const { name } = node.declaration.id; const variable = this.var_lookup.get(name); variable.export_name = name; } code.remove(node.start, node.declaration.start); } else { removeNode(code, content.start, content.end, content.body, node); node.specifiers.forEach(specifier => { const variable = this.var_lookup.get(specifier.local.name); if (variable) { variable.export_name = specifier.exported.name; } else { // TODO what happens with `export { Math }` or some other global? } }); } } }); } extract_javascript(script) { const nodes_to_include = script.content.body.filter(node => { if (this.hoistable_nodes.has(node)) return false; if (this.reactive_declaration_nodes.has(node)) return false; if (node.type === 'ImportDeclaration') return false; if (node.type === 'ExportDeclaration' && node.specifiers.length > 0) return false; return true; }); if (nodes_to_include.length === 0) return null; let a = script.content.start; while (/\s/.test(this.source[a])) a += 1; let b = a; let result = ''; script.content.body.forEach((node, i) => { if (this.hoistable_nodes.has(node) || this.reactive_declaration_nodes.has(node)) { if (a !== b) result += `[✂${a}-${b}✂]`; a = node.end; } b = node.end; }); // while (/\s/.test(this.source[a - 1])) a -= 1; b = script.content.end; while (/\s/.test(this.source[b - 1])) b -= 1; if (a < b) result += `[✂${a}-${b}✂]`; return result || null; } walk_module_js() { const script = this.ast.module; if (!script) return; this.addSourcemapLocations(script.content); let { scope, globals } = createScopes(script.content); this.module_scope = scope; scope.declarations.forEach((node, name) => { if (name[0] === '$') { this.error(node, { code: 'illegal-declaration', message: `The $ prefix is reserved, and cannot be used for variable and import names` }); } this.add_var({ name, module: true, hoistable: true, writable: node.kind === 'var' || node.kind === 'let' }); }); globals.forEach((node, name) => { if (name[0] === '$') { this.error(node, { code: 'illegal-subscription', message: `Cannot reference store value inside