@graphql-tools/graphql-tag-pluck 6.4.1 → 6.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es5/index.cjs.js CHANGED
@@ -4,8 +4,27 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
6
 
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) { return e; } else {
9
+ var n = {};
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () {
16
+ return e[k];
17
+ }
18
+ });
19
+ });
20
+ }
21
+ n['default'] = e;
22
+ return n;
23
+ }
24
+ }
25
+
7
26
  const tslib = require('tslib');
8
- const parser$1 = require('@babel/parser');
27
+ const parser = require('@babel/parser');
9
28
  const types = require('@babel/types');
10
29
  const utils = require('@graphql-tools/utils/es5');
11
30
  const traverse = _interopDefault(require('@babel/traverse'));
@@ -157,6 +176,18 @@ var defaults = {
157
176
  name: 'react-relay',
158
177
  identifier: 'graphql',
159
178
  },
179
+ {
180
+ name: 'react-relay/hooks',
181
+ identifier: 'graphql',
182
+ },
183
+ {
184
+ name: 'relay-runtime',
185
+ identifier: 'graphql',
186
+ },
187
+ {
188
+ name: 'babel-plugin-relay/macro',
189
+ identifier: 'graphql',
190
+ },
160
191
  {
161
192
  name: 'apollo-boost',
162
193
  identifier: 'gql',
@@ -197,6 +228,26 @@ var defaults = {
197
228
  name: 'graphql.macro',
198
229
  identifier: 'gql',
199
230
  },
231
+ {
232
+ name: '@urql/core',
233
+ identifier: 'gql',
234
+ },
235
+ {
236
+ name: 'urql',
237
+ identifier: 'gql',
238
+ },
239
+ {
240
+ name: '@urql/preact',
241
+ identifier: 'gql',
242
+ },
243
+ {
244
+ name: '@urql/svelte',
245
+ identifier: 'gql',
246
+ },
247
+ {
248
+ name: '@urql/vue',
249
+ identifier: 'gql',
250
+ },
200
251
  ],
201
252
  gqlMagicComment: 'graphql',
202
253
  globalGqlIdentifierName: ['gql', 'graphql'],
@@ -236,7 +287,7 @@ const createVisitor = (function (code, out, options) {
236
287
  // Slice quotes
237
288
  .slice(start + 1, end - 1)
238
289
  // Erase string interpolations as we gonna export everything as a single
239
- // string anyways
290
+ // string anyway
240
291
  .replace(/\$\{[^}]*\}/g, '')
241
292
  .split('\\`')
242
293
  .join('`'), options.skipIndent);
@@ -428,7 +479,7 @@ var gqlPluckFromCodeStringSync = function (filePath, code, options) {
428
479
  function parseCode(_a) {
429
480
  var code = _a.code, filePath = _a.filePath, options = _a.options;
430
481
  var out = { returnValue: null };
431
- var ast = parser$1.parse(code, generateConfig(filePath, code));
482
+ var ast = parser.parse(code, generateConfig(filePath, code));
432
483
  var visitor = createVisitor(code, out, options);
433
484
  traverse(ast, visitor);
434
485
  return out.returnValue || [];
@@ -459,7 +510,7 @@ function pluckVueFileScript(fileData) {
459
510
  switch (_a.label) {
460
511
  case 0:
461
512
  _a.trys.push([0, 2, , 3]);
462
- return [4 /*yield*/, Promise.resolve().then(function () { return compilerSfc_cjs; })];
513
+ return [4 /*yield*/, new Promise(function (resolve) { resolve(_interopNamespace(require('@vue/compiler-sfc'))); })];
463
514
  case 1:
464
515
  // tslint:disable-next-line: no-implicit-dependencies
465
516
  vueTemplateCompiler = _a.sent();
@@ -485,2511 +536,6 @@ function pluckVueFileScriptSync(fileData) {
485
536
  return parseWithVue(vueTemplateCompiler, fileData);
486
537
  }
487
538
 
488
- Object.defineProperty(exports, '__esModule', { value: true });
489
-
490
- var CompilerDOM = require('@vue/compiler-dom');
491
- var sourceMap = require('source-map');
492
- var postcss = require('postcss');
493
- var hash = require('hash-sum');
494
- var path = require('path');
495
- var compilerCore = require('@vue/compiler-core');
496
- var url = require('url');
497
- var shared = require('@vue/shared');
498
- var CompilerSSR = require('@vue/compiler-ssr');
499
- var selectorParser = require('postcss-selector-parser');
500
- var merge = require('merge-source-map');
501
- var MagicString = require('magic-string');
502
- var parser = require('@babel/parser');
503
- var estreeWalker = require('estree-walker');
504
-
505
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
506
-
507
- function _interopNamespace(e) {
508
- if (e && e.__esModule) return e;
509
- var n = Object.create(null);
510
- if (e) {
511
- Object.keys(e).forEach(function (k) {
512
- n[k] = e[k];
513
- });
514
- }
515
- n['default'] = e;
516
- return Object.freeze(n);
517
- }
518
-
519
- var CompilerDOM__namespace = /*#__PURE__*/_interopNamespace(CompilerDOM);
520
- var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
521
- var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
522
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
523
- var CompilerSSR__namespace = /*#__PURE__*/_interopNamespace(CompilerSSR);
524
- var selectorParser__default = /*#__PURE__*/_interopDefaultLegacy(selectorParser);
525
- var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge);
526
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
527
-
528
- const CSS_VARS_HELPER = `useCssVars`;
529
- const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
530
- function genCssVarsFromList(vars, id, isProd) {
531
- return `{\n ${vars
532
- .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
533
- .join(',\n ')}\n}`;
534
- }
535
- function genVarName(id, raw, isProd) {
536
- if (isProd) {
537
- return hash__default(id + raw);
538
- }
539
- else {
540
- return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
541
- }
542
- }
543
- function parseCssVars(sfc) {
544
- const vars = [];
545
- sfc.styles.forEach(style => {
546
- let match;
547
- while ((match = cssVarRE.exec(style.content))) {
548
- vars.push(match[1] || match[2] || match[3]);
549
- }
550
- });
551
- return vars;
552
- }
553
- const cssVarsPlugin = postcss__default.plugin('vue-scoped', opts => (root) => {
554
- const { id, isProd } = opts;
555
- root.walkDecls(decl => {
556
- // rewrite CSS variables
557
- if (cssVarRE.test(decl.value)) {
558
- decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
559
- return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`;
560
- });
561
- }
562
- });
563
- });
564
- function genCssVarsCode(vars, bindings, id, isProd) {
565
- const varsExp = genCssVarsFromList(vars, id, isProd);
566
- const exp = CompilerDOM.createSimpleExpression(varsExp, false);
567
- const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
568
- prefixIdentifiers: true,
569
- inline: true,
570
- bindingMetadata: bindings
571
- });
572
- const transformed = CompilerDOM.processExpression(exp, context);
573
- const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
574
- ? transformed.content
575
- : transformed.children
576
- .map(c => {
577
- return typeof c === 'string'
578
- ? c
579
- : c.content;
580
- })
581
- .join('');
582
- return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
583
- }
584
- // <script setup> already gets the calls injected as part of the transform
585
- // this is only for single normal <script>
586
- function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
587
- return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
588
- `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
589
- `const __setup__ = __default__.setup\n` +
590
- `__default__.setup = __setup__\n` +
591
- ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
592
- ` : __injectCSSVars__\n`);
593
- }
594
-
595
- const hasWarned = {};
596
- function warnOnce(msg) {
597
- const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
598
- if (!isNodeProd && !false && !hasWarned[msg]) {
599
- hasWarned[msg] = true;
600
- warn(msg);
601
- }
602
- }
603
- function warn(msg) {
604
- console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
605
- }
606
- function warnExperimental(feature, rfcId) {
607
- warnOnce(`${feature} is still an experimental proposal.\n` +
608
- `Follow its status at https://github.com/vuejs/rfcs/pull/${rfcId}.`);
609
- warnOnce(`When using experimental features,\n` +
610
- `it is recommended to pin your vue dependencies to exact versions to avoid breakage.`);
611
- }
612
-
613
- const SFC_CACHE_MAX_SIZE = 500;
614
- const sourceToSFC = new (require('lru-cache'))(SFC_CACHE_MAX_SIZE);
615
- function parse(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, compiler = CompilerDOM__namespace } = {}) {
616
- const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
617
- const cache = sourceToSFC.get(sourceKey);
618
- if (cache) {
619
- return cache;
620
- }
621
- const descriptor = {
622
- filename,
623
- source,
624
- template: null,
625
- script: null,
626
- scriptSetup: null,
627
- styles: [],
628
- customBlocks: [],
629
- cssVars: []
630
- };
631
- const errors = [];
632
- const ast = compiler.parse(source, {
633
- // there are no components at SFC parsing level
634
- isNativeTag: () => true,
635
- // preserve all whitespaces
636
- isPreTag: () => true,
637
- getTextMode: ({ tag, props }, parent) => {
638
- // all top level elements except <template> are parsed as raw text
639
- // containers
640
- if ((!parent && tag !== 'template') ||
641
- // <template lang="xxx"> should also be treated as raw text
642
- (tag === 'template' &&
643
- props.some(p => p.type === 6 /* ATTRIBUTE */ &&
644
- p.name === 'lang' &&
645
- p.value &&
646
- p.value.content !== 'html'))) {
647
- return 2 /* RAWTEXT */;
648
- }
649
- else {
650
- return 0 /* DATA */;
651
- }
652
- },
653
- onError: e => {
654
- errors.push(e);
655
- }
656
- });
657
- ast.children.forEach(node => {
658
- if (node.type !== 1 /* ELEMENT */) {
659
- return;
660
- }
661
- if (!node.children.length && !hasSrc(node) && node.tag !== 'template') {
662
- return;
663
- }
664
- switch (node.tag) {
665
- case 'template':
666
- if (!descriptor.template) {
667
- const templateBlock = (descriptor.template = createBlock(node, source, false));
668
- templateBlock.ast = node;
669
- }
670
- else {
671
- errors.push(createDuplicateBlockError(node));
672
- }
673
- break;
674
- case 'script':
675
- const scriptBlock = createBlock(node, source, pad);
676
- const isSetup = !!scriptBlock.attrs.setup;
677
- if (isSetup && !descriptor.scriptSetup) {
678
- descriptor.scriptSetup = scriptBlock;
679
- break;
680
- }
681
- if (!isSetup && !descriptor.script) {
682
- descriptor.script = scriptBlock;
683
- break;
684
- }
685
- errors.push(createDuplicateBlockError(node, isSetup));
686
- break;
687
- case 'style':
688
- const styleBlock = createBlock(node, source, pad);
689
- if (styleBlock.attrs.vars) {
690
- errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
691
- `https://github.com/vuejs/rfcs/pull/231`));
692
- }
693
- descriptor.styles.push(styleBlock);
694
- break;
695
- default:
696
- descriptor.customBlocks.push(createBlock(node, source, pad));
697
- break;
698
- }
699
- });
700
- if (descriptor.scriptSetup) {
701
- if (descriptor.scriptSetup.src) {
702
- errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
703
- `its syntax will be ambiguous outside of the component.`));
704
- descriptor.scriptSetup = null;
705
- }
706
- if (descriptor.script && descriptor.script.src) {
707
- errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
708
- `also present because they must be processed together.`));
709
- descriptor.script = null;
710
- }
711
- }
712
- if (sourceMap) {
713
- const genMap = (block) => {
714
- if (block && !block.src) {
715
- block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
716
- }
717
- };
718
- genMap(descriptor.template);
719
- genMap(descriptor.script);
720
- descriptor.styles.forEach(genMap);
721
- descriptor.customBlocks.forEach(genMap);
722
- }
723
- // parse CSS vars
724
- descriptor.cssVars = parseCssVars(descriptor);
725
- if (descriptor.cssVars.length) {
726
- warnExperimental(`v-bind() CSS variable injection`, 231);
727
- }
728
- const result = {
729
- descriptor,
730
- errors
731
- };
732
- sourceToSFC.set(sourceKey, result);
733
- return result;
734
- }
735
- function createDuplicateBlockError(node, isScriptSetup = false) {
736
- const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
737
- err.loc = node.loc;
738
- return err;
739
- }
740
- function createBlock(node, source, pad) {
741
- const type = node.tag;
742
- let { start, end } = node.loc;
743
- let content = '';
744
- if (node.children.length) {
745
- start = node.children[0].loc.start;
746
- end = node.children[node.children.length - 1].loc.end;
747
- content = source.slice(start.offset, end.offset);
748
- }
749
- const loc = {
750
- source: content,
751
- start,
752
- end
753
- };
754
- const attrs = {};
755
- const block = {
756
- type,
757
- content,
758
- loc,
759
- attrs
760
- };
761
- if (pad) {
762
- block.content = padContent(source, block, pad) + block.content;
763
- }
764
- node.props.forEach(p => {
765
- if (p.type === 6 /* ATTRIBUTE */) {
766
- attrs[p.name] = p.value ? p.value.content || true : true;
767
- if (p.name === 'lang') {
768
- block.lang = p.value && p.value.content;
769
- }
770
- else if (p.name === 'src') {
771
- block.src = p.value && p.value.content;
772
- }
773
- else if (type === 'style') {
774
- if (p.name === 'scoped') {
775
- block.scoped = true;
776
- }
777
- else if (p.name === 'module') {
778
- block.module = attrs[p.name];
779
- }
780
- }
781
- else if (type === 'script' && p.name === 'setup') {
782
- block.setup = attrs.setup;
783
- }
784
- }
785
- });
786
- return block;
787
- }
788
- const splitRE = /\r?\n/g;
789
- const emptyRE = /^(?:\/\/)?\s*$/;
790
- const replaceRE = /./g;
791
- function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
792
- const map = new sourceMap.SourceMapGenerator({
793
- file: filename.replace(/\\/g, '/'),
794
- sourceRoot: sourceRoot.replace(/\\/g, '/')
795
- });
796
- map.setSourceContent(filename, source);
797
- generated.split(splitRE).forEach((line, index) => {
798
- if (!emptyRE.test(line)) {
799
- const originalLine = index + 1 + lineOffset;
800
- const generatedLine = index + 1;
801
- for (let i = 0; i < line.length; i++) {
802
- if (!/\s/.test(line[i])) {
803
- map.addMapping({
804
- source: filename,
805
- original: {
806
- line: originalLine,
807
- column: i
808
- },
809
- generated: {
810
- line: generatedLine,
811
- column: i
812
- }
813
- });
814
- }
815
- }
816
- }
817
- });
818
- return JSON.parse(map.toString());
819
- }
820
- function padContent(content, block, pad) {
821
- content = content.slice(0, block.loc.start.offset);
822
- if (pad === 'space') {
823
- return content.replace(replaceRE, ' ');
824
- }
825
- else {
826
- const offset = content.split(splitRE).length;
827
- const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
828
- return Array(offset).join(padChar);
829
- }
830
- }
831
- function hasSrc(node) {
832
- return node.props.some(p => {
833
- if (p.type !== 6 /* ATTRIBUTE */) {
834
- return false;
835
- }
836
- return p.name === 'src';
837
- });
838
- }
839
-
840
- function isRelativeUrl(url) {
841
- const firstChar = url.charAt(0);
842
- return firstChar === '.' || firstChar === '~' || firstChar === '@';
843
- }
844
- const externalRE = /^https?:\/\//;
845
- function isExternalUrl(url) {
846
- return externalRE.test(url);
847
- }
848
- const dataUrlRE = /^\s*data:/i;
849
- function isDataUrl(url) {
850
- return dataUrlRE.test(url);
851
- }
852
- /**
853
- * Parses string url into URL object.
854
- */
855
- function parseUrl(url) {
856
- const firstChar = url.charAt(0);
857
- if (firstChar === '~') {
858
- const secondChar = url.charAt(1);
859
- url = url.slice(secondChar === '/' ? 2 : 1);
860
- }
861
- return parseUriParts(url);
862
- }
863
- /**
864
- * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
865
- * @param urlString an url as a string
866
- */
867
- function parseUriParts(urlString) {
868
- // A TypeError is thrown if urlString is not a string
869
- // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
870
- return url.parse(shared.isString(urlString) ? urlString : '', false, true);
871
- }
872
-
873
- const defaultAssetUrlOptions = {
874
- base: null,
875
- includeAbsolute: false,
876
- tags: {
877
- video: ['src', 'poster'],
878
- source: ['src'],
879
- img: ['src'],
880
- image: ['xlink:href', 'href'],
881
- use: ['xlink:href', 'href']
882
- }
883
- };
884
- const normalizeOptions = (options) => {
885
- if (Object.keys(options).some(key => shared.isArray(options[key]))) {
886
- // legacy option format which directly passes in tags config
887
- return {
888
- ...defaultAssetUrlOptions,
889
- tags: options
890
- };
891
- }
892
- return {
893
- ...defaultAssetUrlOptions,
894
- ...options
895
- };
896
- };
897
- const createAssetUrlTransformWithOptions = (options) => {
898
- return (node, context) => transformAssetUrl(node, context, options);
899
- };
900
- /**
901
- * A `@vue/compiler-core` plugin that transforms relative asset urls into
902
- * either imports or absolute urls.
903
- *
904
- * ``` js
905
- * // Before
906
- * createVNode('img', { src: './logo.png' })
907
- *
908
- * // After
909
- * import _imports_0 from './logo.png'
910
- * createVNode('img', { src: _imports_0 })
911
- * ```
912
- */
913
- const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
914
- if (node.type === 1 /* ELEMENT */) {
915
- if (!node.props.length) {
916
- return;
917
- }
918
- const tags = options.tags || defaultAssetUrlOptions.tags;
919
- const attrs = tags[node.tag];
920
- const wildCardAttrs = tags['*'];
921
- if (!attrs && !wildCardAttrs) {
922
- return;
923
- }
924
- const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
925
- node.props.forEach((attr, index) => {
926
- if (attr.type !== 6 /* ATTRIBUTE */ ||
927
- !assetAttrs.includes(attr.name) ||
928
- !attr.value ||
929
- isExternalUrl(attr.value.content) ||
930
- isDataUrl(attr.value.content) ||
931
- attr.value.content[0] === '#' ||
932
- (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
933
- return;
934
- }
935
- const url = parseUrl(attr.value.content);
936
- if (options.base) {
937
- // explicit base - directly rewrite the url into absolute url
938
- // does not apply to absolute urls or urls that start with `@`
939
- // since they are aliases
940
- if (attr.value.content[0] !== '@' &&
941
- isRelativeUrl(attr.value.content)) {
942
- // Allow for full hostnames provided in options.base
943
- const base = parseUrl(options.base);
944
- const protocol = base.protocol || '';
945
- const host = base.host ? protocol + '//' + base.host : '';
946
- const basePath = base.path || '/';
947
- // when packaged in the browser, path will be using the posix-
948
- // only version provided by rollup-plugin-node-builtins.
949
- attr.value.content =
950
- host +
951
- (path__default.posix || path__default).join(basePath, url.path + (url.hash || ''));
952
- }
953
- return;
954
- }
955
- // otherwise, transform the url into an import.
956
- // this assumes a bundler will resolve the import into the correct
957
- // absolute url (e.g. webpack file-loader)
958
- const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
959
- node.props[index] = {
960
- type: 7 /* DIRECTIVE */,
961
- name: 'bind',
962
- arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
963
- exp,
964
- modifiers: [],
965
- loc: attr.loc
966
- };
967
- });
968
- }
969
- };
970
- function getImportsExpressionExp(path, hash, loc, context) {
971
- if (path) {
972
- const importsArray = Array.from(context.imports);
973
- const existing = importsArray.find(i => i.path === path);
974
- if (existing) {
975
- return existing.exp;
976
- }
977
- const name = `_imports_${importsArray.length}`;
978
- const exp = compilerCore.createSimpleExpression(name, false, loc, 2 /* CAN_HOIST */);
979
- context.imports.add({ exp, path });
980
- if (hash && path) {
981
- return context.hoist(compilerCore.createSimpleExpression(`${name} + '${hash}'`, false, loc, 2 /* CAN_HOIST */));
982
- }
983
- else {
984
- return exp;
985
- }
986
- }
987
- else {
988
- return compilerCore.createSimpleExpression(`''`, false, loc, 2 /* CAN_HOIST */);
989
- }
990
- }
991
-
992
- const srcsetTags = ['img', 'source'];
993
- // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
994
- const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
995
- const createSrcsetTransformWithOptions = (options) => {
996
- return (node, context) => transformSrcset(node, context, options);
997
- };
998
- const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
999
- if (node.type === 1 /* ELEMENT */) {
1000
- if (srcsetTags.includes(node.tag) && node.props.length) {
1001
- node.props.forEach((attr, index) => {
1002
- if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
1003
- if (!attr.value)
1004
- return;
1005
- const value = attr.value.content;
1006
- const imageCandidates = value.split(',').map(s => {
1007
- // The attribute value arrives here with all whitespace, except
1008
- // normal spaces, represented by escape sequences
1009
- const [url, descriptor] = s
1010
- .replace(escapedSpaceCharacters, ' ')
1011
- .trim()
1012
- .split(' ', 2);
1013
- return { url, descriptor };
1014
- });
1015
- // for data url need recheck url
1016
- for (let i = 0; i < imageCandidates.length; i++) {
1017
- if (imageCandidates[i].url.trim().startsWith('data:')) {
1018
- imageCandidates[i + 1].url =
1019
- imageCandidates[i].url + ',' + imageCandidates[i + 1].url;
1020
- imageCandidates.splice(i, 1);
1021
- }
1022
- }
1023
- // When srcset does not contain any relative URLs, skip transforming
1024
- if (!options.includeAbsolute &&
1025
- !imageCandidates.some(({ url }) => isRelativeUrl(url))) {
1026
- return;
1027
- }
1028
- if (options.base) {
1029
- const base = options.base;
1030
- const set = [];
1031
- imageCandidates.forEach(({ url, descriptor }) => {
1032
- descriptor = descriptor ? ` ${descriptor}` : ``;
1033
- if (isRelativeUrl(url)) {
1034
- set.push((path__default.posix || path__default).join(base, url) + descriptor);
1035
- }
1036
- else {
1037
- set.push(url + descriptor);
1038
- }
1039
- });
1040
- attr.value.content = set.join(', ');
1041
- return;
1042
- }
1043
- const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
1044
- imageCandidates.forEach(({ url, descriptor }, index) => {
1045
- if (!isExternalUrl(url) &&
1046
- !isDataUrl(url) &&
1047
- (options.includeAbsolute || isRelativeUrl(url))) {
1048
- const { path } = parseUrl(url);
1049
- let exp;
1050
- if (path) {
1051
- const importsArray = Array.from(context.imports);
1052
- const existingImportsIndex = importsArray.findIndex(i => i.path === path);
1053
- if (existingImportsIndex > -1) {
1054
- exp = compilerCore.createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 2 /* CAN_HOIST */);
1055
- }
1056
- else {
1057
- exp = compilerCore.createSimpleExpression(`_imports_${importsArray.length}`, false, attr.loc, 2 /* CAN_HOIST */);
1058
- context.imports.add({ exp, path });
1059
- }
1060
- compoundExpression.children.push(exp);
1061
- }
1062
- }
1063
- else {
1064
- const exp = compilerCore.createSimpleExpression(`"${url}"`, false, attr.loc, 2 /* CAN_HOIST */);
1065
- compoundExpression.children.push(exp);
1066
- }
1067
- const isNotLast = imageCandidates.length - 1 > index;
1068
- if (descriptor && isNotLast) {
1069
- compoundExpression.children.push(` + '${descriptor}, ' + `);
1070
- }
1071
- else if (descriptor) {
1072
- compoundExpression.children.push(` + '${descriptor}'`);
1073
- }
1074
- else if (isNotLast) {
1075
- compoundExpression.children.push(` + ', ' + `);
1076
- }
1077
- });
1078
- const hoisted = context.hoist(compoundExpression);
1079
- hoisted.constType = 2 /* CAN_HOIST */;
1080
- node.props[index] = {
1081
- type: 7 /* DIRECTIVE */,
1082
- name: 'bind',
1083
- arg: compilerCore.createSimpleExpression('srcset', true, attr.loc),
1084
- exp: hoisted,
1085
- modifiers: [],
1086
- loc: attr.loc
1087
- };
1088
- }
1089
- });
1090
- }
1091
- }
1092
- };
1093
-
1094
- function preprocess({ source, filename, preprocessOptions }, preprocessor) {
1095
- // Consolidate exposes a callback based API, but the callback is in fact
1096
- // called synchronously for most templating engines. In our case, we have to
1097
- // expose a synchronous API so that it is usable in Jest transforms (which
1098
- // have to be sync because they are applied via Node.js require hooks)
1099
- let res = '';
1100
- let err = null;
1101
- preprocessor.render(source, { filename, ...preprocessOptions }, (_err, _res) => {
1102
- if (_err)
1103
- err = _err;
1104
- res = _res;
1105
- });
1106
- if (err)
1107
- throw err;
1108
- return res;
1109
- }
1110
- function compileTemplate(options) {
1111
- const { preprocessLang, preprocessCustomRequire } = options;
1112
- const preprocessor = preprocessLang
1113
- ? preprocessCustomRequire
1114
- ? preprocessCustomRequire(preprocessLang)
1115
- : require('consolidate')[preprocessLang]
1116
- : false;
1117
- if (preprocessor) {
1118
- try {
1119
- return doCompileTemplate({
1120
- ...options,
1121
- source: preprocess(options, preprocessor)
1122
- });
1123
- }
1124
- catch (e) {
1125
- return {
1126
- code: `export default function render() {}`,
1127
- source: options.source,
1128
- tips: [],
1129
- errors: [e]
1130
- };
1131
- }
1132
- }
1133
- else if (preprocessLang) {
1134
- return {
1135
- code: `export default function render() {}`,
1136
- source: options.source,
1137
- tips: [
1138
- `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
1139
- ],
1140
- errors: [
1141
- `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
1142
- ]
1143
- };
1144
- }
1145
- else {
1146
- return doCompileTemplate(options);
1147
- }
1148
- }
1149
- function doCompileTemplate({ filename, id, scoped, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace, compilerOptions = {}, transformAssetUrls }) {
1150
- const errors = [];
1151
- let nodeTransforms = [];
1152
- if (shared.isObject(transformAssetUrls)) {
1153
- const assetOptions = normalizeOptions(transformAssetUrls);
1154
- nodeTransforms = [
1155
- createAssetUrlTransformWithOptions(assetOptions),
1156
- createSrcsetTransformWithOptions(assetOptions)
1157
- ];
1158
- }
1159
- else if (transformAssetUrls !== false) {
1160
- nodeTransforms = [transformAssetUrl, transformSrcset];
1161
- }
1162
- if (ssr && !ssrCssVars) {
1163
- warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
1164
- `corresponding \`cssVars\` option.\`.`);
1165
- }
1166
- if (!id) {
1167
- warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
1168
- id = '';
1169
- }
1170
- const shortId = id.replace(/^data-v-/, '');
1171
- const longId = `data-v-${shortId}`;
1172
- let { code, ast, preamble, map } = compiler.compile(source, {
1173
- mode: 'module',
1174
- prefixIdentifiers: true,
1175
- hoistStatic: true,
1176
- cacheHandlers: true,
1177
- ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
1178
- ? genCssVarsFromList(ssrCssVars, shortId, isProd)
1179
- : '',
1180
- scopeId: scoped ? longId : undefined,
1181
- ...compilerOptions,
1182
- nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
1183
- filename,
1184
- sourceMap: true,
1185
- onError: e => errors.push(e)
1186
- });
1187
- // inMap should be the map produced by ./parse.ts which is a simple line-only
1188
- // mapping. If it is present, we need to adjust the final map and errors to
1189
- // reflect the original line numbers.
1190
- if (inMap) {
1191
- if (map) {
1192
- map = mapLines(inMap, map);
1193
- }
1194
- if (errors.length) {
1195
- patchErrors(errors, source, inMap);
1196
- }
1197
- }
1198
- return { code, ast, preamble, source, errors, tips: [], map };
1199
- }
1200
- function mapLines(oldMap, newMap) {
1201
- if (!oldMap)
1202
- return newMap;
1203
- if (!newMap)
1204
- return oldMap;
1205
- const oldMapConsumer = new sourceMap.SourceMapConsumer(oldMap);
1206
- const newMapConsumer = new sourceMap.SourceMapConsumer(newMap);
1207
- const mergedMapGenerator = new sourceMap.SourceMapGenerator();
1208
- newMapConsumer.eachMapping(m => {
1209
- if (m.originalLine == null) {
1210
- return;
1211
- }
1212
- const origPosInOldMap = oldMapConsumer.originalPositionFor({
1213
- line: m.originalLine,
1214
- column: m.originalColumn
1215
- });
1216
- if (origPosInOldMap.source == null) {
1217
- return;
1218
- }
1219
- mergedMapGenerator.addMapping({
1220
- generated: {
1221
- line: m.generatedLine,
1222
- column: m.generatedColumn
1223
- },
1224
- original: {
1225
- line: origPosInOldMap.line,
1226
- // use current column, since the oldMap produced by @vue/compiler-sfc
1227
- // does not
1228
- column: m.originalColumn
1229
- },
1230
- source: origPosInOldMap.source,
1231
- name: origPosInOldMap.name
1232
- });
1233
- });
1234
- // source-map's type definition is incomplete
1235
- const generator = mergedMapGenerator;
1236
- oldMapConsumer.sources.forEach((sourceFile) => {
1237
- generator._sources.add(sourceFile);
1238
- const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
1239
- if (sourceContent != null) {
1240
- mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
1241
- }
1242
- });
1243
- generator._sourceRoot = oldMap.sourceRoot;
1244
- generator._file = oldMap.file;
1245
- return generator.toJSON();
1246
- }
1247
- function patchErrors(errors, source, inMap) {
1248
- const originalSource = inMap.sourcesContent[0];
1249
- const offset = originalSource.indexOf(source);
1250
- const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
1251
- errors.forEach(err => {
1252
- if (err.loc) {
1253
- err.loc.start.line += lineOffset;
1254
- err.loc.start.offset += offset;
1255
- if (err.loc.end !== err.loc.start) {
1256
- err.loc.end.line += lineOffset;
1257
- err.loc.end.offset += offset;
1258
- }
1259
- }
1260
- });
1261
- }
1262
-
1263
- var trimPlugin = postcss__default.plugin('trim', () => (css) => {
1264
- css.walk(({ type, raws }) => {
1265
- if (type === 'rule' || type === 'atrule') {
1266
- if (raws.before)
1267
- raws.before = '\n';
1268
- if (raws.after)
1269
- raws.after = '\n';
1270
- }
1271
- });
1272
- });
1273
-
1274
- const animationNameRE = /^(-\w+-)?animation-name$/;
1275
- const animationRE = /^(-\w+-)?animation$/;
1276
- var scopedPlugin = postcss__default.plugin('vue-scoped', (id) => (root) => {
1277
- const keyframes = Object.create(null);
1278
- const shortId = id.replace(/^data-v-/, '');
1279
- root.each(function rewriteSelectors(node) {
1280
- if (node.type !== 'rule') {
1281
- // handle media queries
1282
- if (node.type === 'atrule') {
1283
- if (node.name === 'media' || node.name === 'supports') {
1284
- node.each(rewriteSelectors);
1285
- }
1286
- else if (/-?keyframes$/.test(node.name)) {
1287
- // register keyframes
1288
- keyframes[node.params] = node.params = node.params + '-' + shortId;
1289
- }
1290
- }
1291
- return;
1292
- }
1293
- node.selector = selectorParser__default(selectors => {
1294
- function rewriteSelector(selector, slotted) {
1295
- let node = null;
1296
- let shouldInject = true;
1297
- // find the last child node to insert attribute selector
1298
- selector.each(n => {
1299
- // DEPRECATED ">>>" and "/deep/" combinator
1300
- if (n.type === 'combinator' &&
1301
- (n.value === '>>>' || n.value === '/deep/')) {
1302
- n.value = ' ';
1303
- n.spaces.before = n.spaces.after = '';
1304
- warn(`the >>> and /deep/ combinators have been deprecated. ` +
1305
- `Use :deep() instead.`);
1306
- return false;
1307
- }
1308
- if (n.type === 'pseudo') {
1309
- const { value } = n;
1310
- // deep: inject [id] attribute at the node before the ::v-deep
1311
- // combinator.
1312
- if (value === ':deep' || value === '::v-deep') {
1313
- if (n.nodes.length) {
1314
- // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
1315
- // replace the current node with ::v-deep's inner selector
1316
- let last = n;
1317
- n.nodes[0].each(ss => {
1318
- selector.insertAfter(last, ss);
1319
- last = ss;
1320
- });
1321
- // insert a space combinator before if it doesn't already have one
1322
- const prev = selector.at(selector.index(n) - 1);
1323
- if (!prev || !isSpaceCombinator(prev)) {
1324
- selector.insertAfter(n, selectorParser__default.combinator({
1325
- value: ' '
1326
- }));
1327
- }
1328
- selector.removeChild(n);
1329
- }
1330
- else {
1331
- // DEPRECATED usage
1332
- // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
1333
- warn(`::v-deep usage as a combinator has ` +
1334
- `been deprecated. Use :deep(<inner-selector>) instead.`);
1335
- const prev = selector.at(selector.index(n) - 1);
1336
- if (prev && isSpaceCombinator(prev)) {
1337
- selector.removeChild(prev);
1338
- }
1339
- selector.removeChild(n);
1340
- }
1341
- return false;
1342
- }
1343
- // slot: use selector inside `::v-slotted` and inject [id + '-s']
1344
- // instead.
1345
- // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
1346
- if (value === ':slotted' || value === '::v-slotted') {
1347
- rewriteSelector(n.nodes[0], true /* slotted */);
1348
- let last = n;
1349
- n.nodes[0].each(ss => {
1350
- selector.insertAfter(last, ss);
1351
- last = ss;
1352
- });
1353
- // selector.insertAfter(n, n.nodes[0])
1354
- selector.removeChild(n);
1355
- // since slotted attribute already scopes the selector there's no
1356
- // need for the non-slot attribute.
1357
- shouldInject = false;
1358
- return false;
1359
- }
1360
- // global: replace with inner selector and do not inject [id].
1361
- // ::v-global(.foo) -> .foo
1362
- if (value === ':global' || value === '::v-global') {
1363
- selectors.insertAfter(selector, n.nodes[0]);
1364
- selectors.removeChild(selector);
1365
- return false;
1366
- }
1367
- }
1368
- if (n.type !== 'pseudo' && n.type !== 'combinator') {
1369
- node = n;
1370
- }
1371
- });
1372
- if (node) {
1373
- node.spaces.after = '';
1374
- }
1375
- else {
1376
- // For deep selectors & standalone pseudo selectors,
1377
- // the attribute selectors are prepended rather than appended.
1378
- // So all leading spaces must be eliminated to avoid problems.
1379
- selector.first.spaces.before = '';
1380
- }
1381
- if (shouldInject) {
1382
- const idToAdd = slotted ? id + '-s' : id;
1383
- selector.insertAfter(
1384
- // If node is null it means we need to inject [id] at the start
1385
- // insertAfter can handle `null` here
1386
- node, selectorParser__default.attribute({
1387
- attribute: idToAdd,
1388
- value: idToAdd,
1389
- raws: {},
1390
- quoteMark: `"`
1391
- }));
1392
- }
1393
- }
1394
- selectors.each(selector => rewriteSelector(selector));
1395
- }).processSync(node.selector);
1396
- });
1397
- if (Object.keys(keyframes).length) {
1398
- // If keyframes are found in this <style>, find and rewrite animation names
1399
- // in declarations.
1400
- // Caveat: this only works for keyframes and animation rules in the same
1401
- // <style> element.
1402
- // individual animation-name declaration
1403
- root.walkDecls(decl => {
1404
- if (animationNameRE.test(decl.prop)) {
1405
- decl.value = decl.value
1406
- .split(',')
1407
- .map(v => keyframes[v.trim()] || v.trim())
1408
- .join(',');
1409
- }
1410
- // shorthand
1411
- if (animationRE.test(decl.prop)) {
1412
- decl.value = decl.value
1413
- .split(',')
1414
- .map(v => {
1415
- const vals = v.trim().split(/\s+/);
1416
- const i = vals.findIndex(val => keyframes[val]);
1417
- if (i !== -1) {
1418
- vals.splice(i, 1, keyframes[vals[i]]);
1419
- return vals.join(' ');
1420
- }
1421
- else {
1422
- return v;
1423
- }
1424
- })
1425
- .join(',');
1426
- }
1427
- });
1428
- }
1429
- });
1430
- function isSpaceCombinator(node) {
1431
- return node.type === 'combinator' && /^\s+$/.test(node.value);
1432
- }
1433
-
1434
- // .scss/.sass processor
1435
- const scss = (source, map, options, load = require) => {
1436
- const nodeSass = load('sass');
1437
- const finalOptions = {
1438
- ...options,
1439
- data: getSource(source, options.filename, options.additionalData),
1440
- file: options.filename,
1441
- outFile: options.filename,
1442
- sourceMap: !!map
1443
- };
1444
- try {
1445
- const result = nodeSass.renderSync(finalOptions);
1446
- const dependencies = result.stats.includedFiles;
1447
- if (map) {
1448
- return {
1449
- code: result.css.toString(),
1450
- map: merge__default(map, JSON.parse(result.map.toString())),
1451
- errors: [],
1452
- dependencies
1453
- };
1454
- }
1455
- return { code: result.css.toString(), errors: [], dependencies };
1456
- }
1457
- catch (e) {
1458
- return { code: '', errors: [e], dependencies: [] };
1459
- }
1460
- };
1461
- const sass = (source, map, options, load) => scss(source, map, {
1462
- ...options,
1463
- indentedSyntax: true
1464
- }, load);
1465
- // .less
1466
- const less = (source, map, options, load = require) => {
1467
- const nodeLess = load('less');
1468
- let result;
1469
- let error = null;
1470
- nodeLess.render(getSource(source, options.filename, options.additionalData), { ...options, syncImport: true }, (err, output) => {
1471
- error = err;
1472
- result = output;
1473
- });
1474
- if (error)
1475
- return { code: '', errors: [error], dependencies: [] };
1476
- const dependencies = result.imports;
1477
- if (map) {
1478
- return {
1479
- code: result.css.toString(),
1480
- map: merge__default(map, result.map),
1481
- errors: [],
1482
- dependencies: dependencies
1483
- };
1484
- }
1485
- return {
1486
- code: result.css.toString(),
1487
- errors: [],
1488
- dependencies: dependencies
1489
- };
1490
- };
1491
- // .styl
1492
- const styl = (source, map, options, load = require) => {
1493
- const nodeStylus = load('stylus');
1494
- try {
1495
- const ref = nodeStylus(source);
1496
- Object.keys(options).forEach(key => ref.set(key, options[key]));
1497
- if (map)
1498
- ref.set('sourcemap', { inline: false, comment: false });
1499
- const result = ref.render();
1500
- const dependencies = ref.deps();
1501
- if (map) {
1502
- return {
1503
- code: result,
1504
- map: merge__default(map, ref.sourcemap),
1505
- errors: [],
1506
- dependencies
1507
- };
1508
- }
1509
- return { code: result, errors: [], dependencies };
1510
- }
1511
- catch (e) {
1512
- return { code: '', errors: [e], dependencies: [] };
1513
- }
1514
- };
1515
- function getSource(source, filename, additionalData) {
1516
- if (!additionalData)
1517
- return source;
1518
- if (shared.isFunction(additionalData)) {
1519
- return additionalData(source, filename);
1520
- }
1521
- return additionalData + source;
1522
- }
1523
- const processors = {
1524
- less,
1525
- sass,
1526
- scss,
1527
- styl,
1528
- stylus: styl
1529
- };
1530
-
1531
- function compileStyle(options) {
1532
- return doCompileStyle({
1533
- ...options,
1534
- isAsync: false
1535
- });
1536
- }
1537
- function compileStyleAsync(options) {
1538
- return doCompileStyle({ ...options, isAsync: true });
1539
- }
1540
- function doCompileStyle(options) {
1541
- const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
1542
- const preprocessor = preprocessLang && processors[preprocessLang];
1543
- const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
1544
- const map = preProcessedSource
1545
- ? preProcessedSource.map
1546
- : options.inMap || options.map;
1547
- const source = preProcessedSource ? preProcessedSource.code : options.source;
1548
- const shortId = id.replace(/^data-v-/, '');
1549
- const longId = `data-v-${shortId}`;
1550
- const plugins = (postcssPlugins || []).slice();
1551
- plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
1552
- if (trim) {
1553
- plugins.push(trimPlugin());
1554
- }
1555
- if (scoped) {
1556
- plugins.push(scopedPlugin(longId));
1557
- }
1558
- let cssModules;
1559
- if (modules) {
1560
- if (!options.isAsync) {
1561
- throw new Error('[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync().');
1562
- }
1563
- plugins.push(require('postcss-modules')({
1564
- ...modulesOptions,
1565
- getJSON: (_cssFileName, json) => {
1566
- cssModules = json;
1567
- }
1568
- }));
1569
- }
1570
- const postCSSOptions = {
1571
- ...postcssOptions,
1572
- to: filename,
1573
- from: filename
1574
- };
1575
- if (map) {
1576
- postCSSOptions.map = {
1577
- inline: false,
1578
- annotation: false,
1579
- prev: map
1580
- };
1581
- }
1582
- let result;
1583
- let code;
1584
- let outMap;
1585
- // stylus output include plain css. so need remove the repeat item
1586
- const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
1587
- // sass has filename self when provided filename option
1588
- dependencies.delete(filename);
1589
- const errors = [];
1590
- if (preProcessedSource && preProcessedSource.errors.length) {
1591
- errors.push(...preProcessedSource.errors);
1592
- }
1593
- const recordPlainCssDependencies = (messages) => {
1594
- messages.forEach(msg => {
1595
- if (msg.type === 'dependency') {
1596
- // postcss output path is absolute position path
1597
- dependencies.add(msg.file);
1598
- }
1599
- });
1600
- return dependencies;
1601
- };
1602
- try {
1603
- result = postcss__default(plugins).process(source, postCSSOptions);
1604
- // In async mode, return a promise.
1605
- if (options.isAsync) {
1606
- return result
1607
- .then(result => ({
1608
- code: result.css || '',
1609
- map: result.map && result.map.toJSON(),
1610
- errors,
1611
- modules: cssModules,
1612
- rawResult: result,
1613
- dependencies: recordPlainCssDependencies(result.messages)
1614
- }))
1615
- .catch(error => ({
1616
- code: '',
1617
- map: undefined,
1618
- errors: [...errors, error],
1619
- rawResult: undefined,
1620
- dependencies
1621
- }));
1622
- }
1623
- recordPlainCssDependencies(result.messages);
1624
- // force synchronous transform (we know we only have sync plugins)
1625
- code = result.css;
1626
- outMap = result.map;
1627
- }
1628
- catch (e) {
1629
- errors.push(e);
1630
- }
1631
- return {
1632
- code: code || ``,
1633
- map: outMap && outMap.toJSON(),
1634
- errors,
1635
- rawResult: result,
1636
- dependencies
1637
- };
1638
- }
1639
- function preprocess$1(options, preprocessor) {
1640
- return preprocessor(options.source, options.map, {
1641
- filename: options.filename,
1642
- ...options.preprocessOptions
1643
- }, options.preprocessCustomRequire);
1644
- }
1645
-
1646
- const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
1647
- const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/;
1648
- /**
1649
- * Utility for rewriting `export default` in a script block into a variable
1650
- * declaration so that we can inject things into it
1651
- */
1652
- function rewriteDefault(input, as, parserPlugins) {
1653
- if (!hasDefaultExport(input)) {
1654
- return input + `\nconst ${as} = {}`;
1655
- }
1656
- const replaced = input.replace(defaultExportRE, `$1const ${as} =`);
1657
- if (!hasDefaultExport(replaced)) {
1658
- return replaced;
1659
- }
1660
- // if the script somehow still contains `default export`, it probably has
1661
- // multi-line comments or template strings. fallback to a full parse.
1662
- const s = new MagicString__default(input);
1663
- const ast = parser.parse(input, {
1664
- sourceType: 'module',
1665
- plugins: parserPlugins
1666
- }).program.body;
1667
- ast.forEach(node => {
1668
- if (node.type === 'ExportDefaultDeclaration') {
1669
- s.overwrite(node.start, node.declaration.start, `const ${as} = `);
1670
- }
1671
- if (node.type === 'ExportNamedDeclaration') {
1672
- node.specifiers.forEach(specifier => {
1673
- if (specifier.type === 'ExportSpecifier' &&
1674
- specifier.exported.type === 'Identifier' &&
1675
- specifier.exported.name === 'default') {
1676
- const end = specifier.end;
1677
- s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
1678
- s.append(`\nconst ${as} = ${specifier.local.name}`);
1679
- }
1680
- });
1681
- }
1682
- });
1683
- return s.toString();
1684
- }
1685
- function hasDefaultExport(input) {
1686
- return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
1687
- }
1688
-
1689
- const DEFINE_PROPS = 'defineProps';
1690
- const DEFINE_EMIT = 'defineEmit';
1691
- /**
1692
- * Compile `<script setup>`
1693
- * It requires the whole SFC descriptor because we need to handle and merge
1694
- * normal `<script>` + `<script setup>` if both are present.
1695
- */
1696
- function compileScript(sfc, options) {
1697
- const { script, scriptSetup, source, filename } = sfc;
1698
- if (scriptSetup) {
1699
- warnExperimental(`<script setup>`, 227);
1700
- }
1701
- // for backwards compat
1702
- if (!options) {
1703
- options = { id: '' };
1704
- }
1705
- if (!options.id) {
1706
- warnOnce(`compileScript now requires passing the \`id\` option.\n` +
1707
- `Upgrade your vite or vue-loader version for compatibility with ` +
1708
- `the latest experimental proposals.`);
1709
- }
1710
- const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
1711
- const cssVars = sfc.cssVars;
1712
- const hasInheritAttrsFlag = sfc.template && sfc.template.attrs['inherit-attrs'] === 'false';
1713
- const scriptLang = script && script.lang;
1714
- const scriptSetupLang = scriptSetup && scriptSetup.lang;
1715
- const isTS = scriptLang === 'ts' || scriptSetupLang === 'ts';
1716
- const plugins = [...shared.babelParserDefaultPlugins, 'jsx'];
1717
- if (options.babelParserPlugins)
1718
- plugins.push(...options.babelParserPlugins);
1719
- if (isTS)
1720
- plugins.push('typescript', 'decorators-legacy');
1721
- if (!scriptSetup) {
1722
- if (!script) {
1723
- throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
1724
- }
1725
- if (scriptLang && scriptLang !== 'ts') {
1726
- // do not process non js/ts script blocks
1727
- return script;
1728
- }
1729
- try {
1730
- const scriptAst = parser.parse(script.content, {
1731
- plugins,
1732
- sourceType: 'module'
1733
- }).program.body;
1734
- const bindings = analyzeScriptBindings(scriptAst);
1735
- const needRewrite = cssVars.length || hasInheritAttrsFlag;
1736
- let content = script.content;
1737
- if (needRewrite) {
1738
- content = rewriteDefault(content, `__default__`, plugins);
1739
- if (cssVars.length) {
1740
- content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
1741
- }
1742
- if (hasInheritAttrsFlag) {
1743
- content += `__default__.inheritAttrs = false`;
1744
- }
1745
- content += `\nexport default __default__`;
1746
- }
1747
- return {
1748
- ...script,
1749
- content,
1750
- bindings,
1751
- scriptAst
1752
- };
1753
- }
1754
- catch (e) {
1755
- // silently fallback if parse fails since user may be using custom
1756
- // babel syntax
1757
- return script;
1758
- }
1759
- }
1760
- if (script && scriptLang !== scriptSetupLang) {
1761
- throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`);
1762
- }
1763
- if (scriptSetupLang && scriptSetupLang !== 'ts') {
1764
- // do not process non js/ts script blocks
1765
- return scriptSetup;
1766
- }
1767
- const defaultTempVar = `__default__`;
1768
- const bindingMetadata = {};
1769
- const helperImports = new Set();
1770
- const userImports = Object.create(null);
1771
- const userImportAlias = Object.create(null);
1772
- const setupBindings = Object.create(null);
1773
- const refBindings = Object.create(null);
1774
- const refIdentifiers = new Set();
1775
- const enableRefSugar = options.refSugar !== false;
1776
- let defaultExport;
1777
- let hasDefinePropsCall = false;
1778
- let hasDefineEmitCall = false;
1779
- let propsRuntimeDecl;
1780
- let propsTypeDecl;
1781
- let propsIdentifier;
1782
- let emitRuntimeDecl;
1783
- let emitTypeDecl;
1784
- let emitIdentifier;
1785
- let hasAwait = false;
1786
- let hasInlinedSsrRenderFn = false;
1787
- // props/emits declared via types
1788
- const typeDeclaredProps = {};
1789
- const typeDeclaredEmits = new Set();
1790
- // record declared types for runtime props type generation
1791
- const declaredTypes = {};
1792
- // magic-string state
1793
- const s = new MagicString__default(source);
1794
- const startOffset = scriptSetup.loc.start.offset;
1795
- const endOffset = scriptSetup.loc.end.offset;
1796
- const scriptStartOffset = script && script.loc.start.offset;
1797
- const scriptEndOffset = script && script.loc.end.offset;
1798
- function helper(key) {
1799
- helperImports.add(key);
1800
- return `_${key}`;
1801
- }
1802
- function parse(input, options, offset) {
1803
- try {
1804
- return parser.parse(input, options).program.body;
1805
- }
1806
- catch (e) {
1807
- e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${shared.generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
1808
- throw e;
1809
- }
1810
- }
1811
- function error(msg, node, end = node.end + startOffset) {
1812
- throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${shared.generateCodeFrame(source, node.start + startOffset, end)}`);
1813
- }
1814
- function registerUserImport(source, local, imported, isType) {
1815
- if (source === 'vue' && imported) {
1816
- userImportAlias[imported] = local;
1817
- }
1818
- userImports[local] = {
1819
- isType,
1820
- imported: imported || 'default',
1821
- source
1822
- };
1823
- }
1824
- function processDefineProps(node) {
1825
- if (isCallOf(node, DEFINE_PROPS)) {
1826
- if (hasDefinePropsCall) {
1827
- error(`duplicate ${DEFINE_PROPS}() call`, node);
1828
- }
1829
- hasDefinePropsCall = true;
1830
- propsRuntimeDecl = node.arguments[0];
1831
- // context call has type parameters - infer runtime types from it
1832
- if (node.typeParameters) {
1833
- if (propsRuntimeDecl) {
1834
- error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
1835
- `at the same time. Use one or the other.`, node);
1836
- }
1837
- const typeArg = node.typeParameters.params[0];
1838
- if (typeArg.type === 'TSTypeLiteral') {
1839
- propsTypeDecl = typeArg;
1840
- }
1841
- else {
1842
- error(`type argument passed to ${DEFINE_PROPS}() must be a literal type.`, typeArg);
1843
- }
1844
- }
1845
- return true;
1846
- }
1847
- return false;
1848
- }
1849
- function processDefineEmit(node) {
1850
- if (isCallOf(node, DEFINE_EMIT)) {
1851
- if (hasDefineEmitCall) {
1852
- error(`duplicate ${DEFINE_EMIT}() call`, node);
1853
- }
1854
- hasDefineEmitCall = true;
1855
- emitRuntimeDecl = node.arguments[0];
1856
- if (node.typeParameters) {
1857
- if (emitRuntimeDecl) {
1858
- error(`${DEFINE_EMIT}() cannot accept both type and non-type arguments ` +
1859
- `at the same time. Use one or the other.`, node);
1860
- }
1861
- const typeArg = node.typeParameters.params[0];
1862
- if (typeArg.type === 'TSFunctionType' ||
1863
- typeArg.type === 'TSUnionType') {
1864
- emitTypeDecl = typeArg;
1865
- }
1866
- else {
1867
- error(`type argument passed to ${DEFINE_EMIT}() must be a function type ` +
1868
- `or a union of function types.`, typeArg);
1869
- }
1870
- }
1871
- return true;
1872
- }
1873
- return false;
1874
- }
1875
- function checkInvalidScopeReference(node, method) {
1876
- if (!node)
1877
- return;
1878
- walkIdentifiers(node, id => {
1879
- if (setupBindings[id.name]) {
1880
- error(`\`${method}()\` in <script setup> cannot reference locally ` +
1881
- `declared variables because it will be hoisted outside of the ` +
1882
- `setup() function. If your component options requires initialization ` +
1883
- `in the module scope, use a separate normal <script> to export ` +
1884
- `the options instead.`, id);
1885
- }
1886
- });
1887
- }
1888
- function processRefExpression(exp, statement) {
1889
- if (exp.type === 'AssignmentExpression') {
1890
- const { left, right } = exp;
1891
- if (left.type === 'Identifier') {
1892
- registerRefBinding(left);
1893
- s.prependRight(right.start + startOffset, `${helper('ref')}(`);
1894
- s.appendLeft(right.end + startOffset, ')');
1895
- }
1896
- else if (left.type === 'ObjectPattern') {
1897
- // remove wrapping parens
1898
- for (let i = left.start; i > 0; i--) {
1899
- const char = source[i + startOffset];
1900
- if (char === '(') {
1901
- s.remove(i + startOffset, i + startOffset + 1);
1902
- break;
1903
- }
1904
- }
1905
- for (let i = left.end; i > 0; i++) {
1906
- const char = source[i + startOffset];
1907
- if (char === ')') {
1908
- s.remove(i + startOffset, i + startOffset + 1);
1909
- break;
1910
- }
1911
- }
1912
- processRefObjectPattern(left, statement);
1913
- }
1914
- else if (left.type === 'ArrayPattern') {
1915
- processRefArrayPattern(left, statement);
1916
- }
1917
- }
1918
- else if (exp.type === 'SequenceExpression') {
1919
- // possible multiple declarations
1920
- // ref: x = 1, y = 2
1921
- exp.expressions.forEach(e => processRefExpression(e, statement));
1922
- }
1923
- else if (exp.type === 'Identifier') {
1924
- registerRefBinding(exp);
1925
- s.appendLeft(exp.end + startOffset, ` = ${helper('ref')}()`);
1926
- }
1927
- else {
1928
- error(`ref: statements can only contain assignment expressions.`, exp);
1929
- }
1930
- }
1931
- function registerRefBinding(id) {
1932
- if (id.name[0] === '$') {
1933
- error(`ref variable identifiers cannot start with $.`, id);
1934
- }
1935
- refBindings[id.name] = setupBindings[id.name] = "setup-ref" /* SETUP_REF */;
1936
- refIdentifiers.add(id);
1937
- }
1938
- function processRefObjectPattern(pattern, statement) {
1939
- for (const p of pattern.properties) {
1940
- let nameId;
1941
- if (p.type === 'ObjectProperty') {
1942
- if (p.key.start === p.value.start) {
1943
- // shorthand { foo } --> { foo: __foo }
1944
- nameId = p.key;
1945
- s.appendLeft(nameId.end + startOffset, `: __${nameId.name}`);
1946
- if (p.value.type === 'AssignmentPattern') {
1947
- // { foo = 1 }
1948
- refIdentifiers.add(p.value.left);
1949
- }
1950
- }
1951
- else {
1952
- if (p.value.type === 'Identifier') {
1953
- // { foo: bar } --> { foo: __bar }
1954
- nameId = p.value;
1955
- s.prependRight(nameId.start + startOffset, `__`);
1956
- }
1957
- else if (p.value.type === 'ObjectPattern') {
1958
- processRefObjectPattern(p.value, statement);
1959
- }
1960
- else if (p.value.type === 'ArrayPattern') {
1961
- processRefArrayPattern(p.value, statement);
1962
- }
1963
- else if (p.value.type === 'AssignmentPattern') {
1964
- // { foo: bar = 1 } --> { foo: __bar = 1 }
1965
- nameId = p.value.left;
1966
- s.prependRight(nameId.start + startOffset, `__`);
1967
- }
1968
- }
1969
- }
1970
- else {
1971
- // rest element { ...foo } --> { ...__foo }
1972
- nameId = p.argument;
1973
- s.prependRight(nameId.start + startOffset, `__`);
1974
- }
1975
- if (nameId) {
1976
- registerRefBinding(nameId);
1977
- // append binding declarations after the parent statement
1978
- s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
1979
- }
1980
- }
1981
- }
1982
- function processRefArrayPattern(pattern, statement) {
1983
- for (const e of pattern.elements) {
1984
- if (!e)
1985
- continue;
1986
- let nameId;
1987
- if (e.type === 'Identifier') {
1988
- // [a] --> [__a]
1989
- nameId = e;
1990
- }
1991
- else if (e.type === 'AssignmentPattern') {
1992
- // [a = 1] --> [__a = 1]
1993
- nameId = e.left;
1994
- }
1995
- else if (e.type === 'RestElement') {
1996
- // [...a] --> [...__a]
1997
- nameId = e.argument;
1998
- }
1999
- else if (e.type === 'ObjectPattern') {
2000
- processRefObjectPattern(e, statement);
2001
- }
2002
- else if (e.type === 'ArrayPattern') {
2003
- processRefArrayPattern(e, statement);
2004
- }
2005
- if (nameId) {
2006
- registerRefBinding(nameId);
2007
- // prefix original
2008
- s.prependRight(nameId.start + startOffset, `__`);
2009
- // append binding declarations after the parent statement
2010
- s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
2011
- }
2012
- }
2013
- }
2014
- // 1. process normal <script> first if it exists
2015
- let scriptAst;
2016
- if (script) {
2017
- // import dedupe between <script> and <script setup>
2018
- scriptAst = parse(script.content, {
2019
- plugins,
2020
- sourceType: 'module'
2021
- }, scriptStartOffset);
2022
- for (const node of scriptAst) {
2023
- if (node.type === 'ImportDeclaration') {
2024
- // record imports for dedupe
2025
- for (const specifier of node.specifiers) {
2026
- const imported = specifier.type === 'ImportSpecifier' &&
2027
- specifier.imported.type === 'Identifier' &&
2028
- specifier.imported.name;
2029
- registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type');
2030
- }
2031
- }
2032
- else if (node.type === 'ExportDefaultDeclaration') {
2033
- // export default
2034
- defaultExport = node;
2035
- const start = node.start + scriptStartOffset;
2036
- s.overwrite(start, start + `export default`.length, `const ${defaultTempVar} =`);
2037
- }
2038
- else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
2039
- const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
2040
- if (defaultSpecifier) {
2041
- defaultExport = node;
2042
- // 1. remove specifier
2043
- if (node.specifiers.length > 1) {
2044
- s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
2045
- }
2046
- else {
2047
- s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
2048
- }
2049
- if (node.source) {
2050
- // export { x as default } from './x'
2051
- // rewrite to `import { x as __default__ } from './x'` and
2052
- // add to top
2053
- s.prepend(`import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`);
2054
- }
2055
- else {
2056
- // export { x as default }
2057
- // rewrite to `const __default__ = x` and move to end
2058
- s.append(`\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`);
2059
- }
2060
- }
2061
- }
2062
- }
2063
- }
2064
- // 2. parse <script setup> and walk over top level statements
2065
- const scriptSetupAst = parse(scriptSetup.content, {
2066
- plugins: [
2067
- ...plugins,
2068
- // allow top level await but only inside <script setup>
2069
- 'topLevelAwait'
2070
- ],
2071
- sourceType: 'module'
2072
- }, startOffset);
2073
- for (const node of scriptSetupAst) {
2074
- const start = node.start + startOffset;
2075
- let end = node.end + startOffset;
2076
- // import or type declarations: move to top
2077
- // locate comment
2078
- if (node.trailingComments && node.trailingComments.length > 0) {
2079
- const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
2080
- end = lastCommentNode.end + startOffset;
2081
- }
2082
- // locate the end of whitespace between this statement and the next
2083
- while (end <= source.length) {
2084
- if (!/\s/.test(source.charAt(end))) {
2085
- break;
2086
- }
2087
- end++;
2088
- }
2089
- // process `ref: x` bindings (convert to refs)
2090
- if (node.type === 'LabeledStatement' &&
2091
- node.label.name === 'ref' &&
2092
- node.body.type === 'ExpressionStatement') {
2093
- if (enableRefSugar) {
2094
- warnExperimental(`ref: sugar`, 228);
2095
- s.overwrite(node.label.start + startOffset, node.body.start + startOffset, 'const ');
2096
- processRefExpression(node.body.expression, node);
2097
- }
2098
- else {
2099
- // TODO if we end up shipping ref: sugar as an opt-in feature,
2100
- // need to proxy the option in vite, vue-loader and rollup-plugin-vue.
2101
- error(`ref: sugar needs to be explicitly enabled via vite or vue-loader options.`, node);
2102
- }
2103
- }
2104
- if (node.type === 'ImportDeclaration') {
2105
- // import declarations are moved to top
2106
- s.move(start, end, 0);
2107
- // dedupe imports
2108
- let removed = 0;
2109
- let prev, next;
2110
- const removeSpecifier = (node) => {
2111
- removed++;
2112
- s.remove(prev ? prev.end + startOffset : node.start + startOffset, next && !prev ? next.start + startOffset : node.end + startOffset);
2113
- };
2114
- for (let i = 0; i < node.specifiers.length; i++) {
2115
- const specifier = node.specifiers[i];
2116
- prev = node.specifiers[i - 1];
2117
- next = node.specifiers[i + 1];
2118
- const local = specifier.local.name;
2119
- const imported = specifier.type === 'ImportSpecifier' &&
2120
- specifier.imported.type === 'Identifier' &&
2121
- specifier.imported.name;
2122
- const source = node.source.value;
2123
- const existing = userImports[local];
2124
- if (source === 'vue' &&
2125
- (imported === DEFINE_PROPS || imported === DEFINE_EMIT)) {
2126
- removeSpecifier(specifier);
2127
- }
2128
- else if (existing) {
2129
- if (existing.source === source && existing.imported === imported) {
2130
- // already imported in <script setup>, dedupe
2131
- removeSpecifier(specifier);
2132
- }
2133
- else {
2134
- error(`different imports aliased to same local name.`, specifier);
2135
- }
2136
- }
2137
- else {
2138
- registerUserImport(source, local, imported, node.importKind === 'type');
2139
- }
2140
- }
2141
- if (node.specifiers.length && removed === node.specifiers.length) {
2142
- s.remove(node.start + startOffset, node.end + startOffset);
2143
- }
2144
- }
2145
- // process `defineProps` and `defineEmit` calls
2146
- if (node.type === 'ExpressionStatement' &&
2147
- (processDefineProps(node.expression) ||
2148
- processDefineEmit(node.expression))) {
2149
- s.remove(node.start + startOffset, node.end + startOffset);
2150
- }
2151
- if (node.type === 'VariableDeclaration' && !node.declare) {
2152
- for (const decl of node.declarations) {
2153
- if (decl.init) {
2154
- const isDefineProps = processDefineProps(decl.init);
2155
- if (isDefineProps) {
2156
- propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
2157
- }
2158
- const isDefineEmit = processDefineEmit(decl.init);
2159
- if (isDefineEmit) {
2160
- emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
2161
- }
2162
- if (isDefineProps || isDefineEmit)
2163
- if (node.declarations.length === 1) {
2164
- s.remove(node.start + startOffset, node.end + startOffset);
2165
- }
2166
- else {
2167
- s.remove(decl.start + startOffset, decl.end + startOffset);
2168
- }
2169
- }
2170
- }
2171
- }
2172
- // walk decalrations to record declared bindings
2173
- if ((node.type === 'VariableDeclaration' ||
2174
- node.type === 'FunctionDeclaration' ||
2175
- node.type === 'ClassDeclaration') &&
2176
- !node.declare) {
2177
- walkDeclaration(node, setupBindings, userImportAlias);
2178
- }
2179
- // Type declarations
2180
- if (node.type === 'VariableDeclaration' && node.declare) {
2181
- s.remove(start, end);
2182
- }
2183
- // move all type declarations to outer scope
2184
- if (node.type.startsWith('TS') ||
2185
- (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type')) {
2186
- recordType(node, declaredTypes);
2187
- s.move(start, end, 0);
2188
- }
2189
- // walk statements & named exports / variable declarations for top level
2190
- // await
2191
- if ((node.type === 'VariableDeclaration' && !node.declare) ||
2192
- node.type.endsWith('Statement')) {
2193
- estreeWalker.walk(node, {
2194
- enter(node) {
2195
- if (isFunction(node)) {
2196
- this.skip();
2197
- }
2198
- if (node.type === 'AwaitExpression') {
2199
- hasAwait = true;
2200
- }
2201
- }
2202
- });
2203
- }
2204
- if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
2205
- node.type === 'ExportAllDeclaration' ||
2206
- node.type === 'ExportDefaultDeclaration') {
2207
- error(`<script setup> cannot contain ES module exports. ` +
2208
- `If you are using a previous version of <script setup>, please ` +
2209
- `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
2210
- }
2211
- }
2212
- // 3. Do a full walk to rewrite identifiers referencing let exports with ref
2213
- // value access
2214
- if (enableRefSugar && Object.keys(refBindings).length) {
2215
- for (const node of scriptSetupAst) {
2216
- if (node.type !== 'ImportDeclaration') {
2217
- walkIdentifiers(node, (id, parent) => {
2218
- if (refBindings[id.name] && !refIdentifiers.has(id)) {
2219
- if (isStaticProperty(parent) && parent.shorthand) {
2220
- // let binding used in a property shorthand
2221
- // { foo } -> { foo: foo.value }
2222
- // skip for destructure patterns
2223
- if (!parent.inPattern ||
2224
- isInDestructureAssignment(parent, parentStack)) {
2225
- s.appendLeft(id.end + startOffset, `: ${id.name}.value`);
2226
- }
2227
- }
2228
- else {
2229
- s.appendLeft(id.end + startOffset, '.value');
2230
- }
2231
- }
2232
- else if (id.name[0] === '$' && refBindings[id.name.slice(1)]) {
2233
- // $xxx raw ref access variables, remove the $ prefix
2234
- s.remove(id.start + startOffset, id.start + startOffset + 1);
2235
- }
2236
- });
2237
- }
2238
- }
2239
- }
2240
- // 4. extract runtime props/emits code from setup context type
2241
- if (propsTypeDecl) {
2242
- extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
2243
- }
2244
- if (emitTypeDecl) {
2245
- extractRuntimeEmits(emitTypeDecl, typeDeclaredEmits);
2246
- }
2247
- // 5. check useOptions args to make sure it doesn't reference setup scope
2248
- // variables
2249
- checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
2250
- checkInvalidScopeReference(emitRuntimeDecl, DEFINE_PROPS);
2251
- // 6. remove non-script content
2252
- if (script) {
2253
- if (startOffset < scriptStartOffset) {
2254
- // <script setup> before <script>
2255
- s.remove(0, startOffset);
2256
- s.remove(endOffset, scriptStartOffset);
2257
- s.remove(scriptEndOffset, source.length);
2258
- }
2259
- else {
2260
- // <script> before <script setup>
2261
- s.remove(0, scriptStartOffset);
2262
- s.remove(scriptEndOffset, startOffset);
2263
- s.remove(endOffset, source.length);
2264
- }
2265
- }
2266
- else {
2267
- // only <script setup>
2268
- s.remove(0, startOffset);
2269
- s.remove(endOffset, source.length);
2270
- }
2271
- // 7. analyze binding metadata
2272
- if (scriptAst) {
2273
- Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst));
2274
- }
2275
- if (propsRuntimeDecl) {
2276
- for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
2277
- bindingMetadata[key] = "props" /* PROPS */;
2278
- }
2279
- }
2280
- for (const key in typeDeclaredProps) {
2281
- bindingMetadata[key] = "props" /* PROPS */;
2282
- }
2283
- for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
2284
- if (isType)
2285
- continue;
2286
- bindingMetadata[key] =
2287
- (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
2288
- ? "setup-const" /* SETUP_CONST */
2289
- : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
2290
- }
2291
- for (const key in setupBindings) {
2292
- bindingMetadata[key] = setupBindings[key];
2293
- }
2294
- // 8. inject `useCssVars` calls
2295
- if (cssVars.length) {
2296
- helperImports.add(CSS_VARS_HELPER);
2297
- helperImports.add('unref');
2298
- s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, !!options.isProd)}\n`);
2299
- }
2300
- // 9. finalize setup() argument signature
2301
- let args = `__props`;
2302
- if (propsTypeDecl) {
2303
- args += `: ${scriptSetup.content.slice(propsTypeDecl.start, propsTypeDecl.end)}`;
2304
- }
2305
- // inject user assignment of props
2306
- // we use a default __props so that template expressions referencing props
2307
- // can use it directly
2308
- if (propsIdentifier) {
2309
- s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props`);
2310
- }
2311
- if (emitIdentifier) {
2312
- args +=
2313
- emitIdentifier === `emit` ? `, { emit }` : `, { emit: ${emitIdentifier} }`;
2314
- if (emitTypeDecl) {
2315
- args += `: {
2316
- emit: (${scriptSetup.content.slice(emitTypeDecl.start, emitTypeDecl.end)}),
2317
- slots: any,
2318
- attrs: any
2319
- }`;
2320
- }
2321
- }
2322
- // 10. generate return statement
2323
- let returned;
2324
- if (options.inlineTemplate) {
2325
- if (sfc.template && !sfc.template.src) {
2326
- if (options.templateOptions && options.templateOptions.ssr) {
2327
- hasInlinedSsrRenderFn = true;
2328
- }
2329
- // inline render function mode - we are going to compile the template and
2330
- // inline it right here
2331
- const { code, ast, preamble, tips, errors } = compileTemplate({
2332
- filename,
2333
- source: sfc.template.content,
2334
- inMap: sfc.template.map,
2335
- ...options.templateOptions,
2336
- id: scopeId,
2337
- scoped: sfc.styles.some(s => s.scoped),
2338
- isProd: options.isProd,
2339
- ssrCssVars: sfc.cssVars,
2340
- compilerOptions: {
2341
- ...(options.templateOptions &&
2342
- options.templateOptions.compilerOptions),
2343
- inline: true,
2344
- isTS,
2345
- bindingMetadata
2346
- }
2347
- });
2348
- if (tips.length) {
2349
- tips.forEach(warnOnce);
2350
- }
2351
- const err = errors[0];
2352
- if (typeof err === 'string') {
2353
- throw new Error(err);
2354
- }
2355
- else if (err) {
2356
- if (err.loc) {
2357
- err.message +=
2358
- `\n\n` +
2359
- sfc.filename +
2360
- '\n' +
2361
- shared.generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
2362
- `\n`;
2363
- }
2364
- throw err;
2365
- }
2366
- if (preamble) {
2367
- s.prepend(preamble);
2368
- }
2369
- // avoid duplicated unref import
2370
- // as this may get injected by the render function preamble OR the
2371
- // css vars codegen
2372
- if (ast && ast.helpers.includes(compilerCore.UNREF)) {
2373
- helperImports.delete('unref');
2374
- }
2375
- returned = code;
2376
- }
2377
- else {
2378
- returned = `() => {}`;
2379
- }
2380
- }
2381
- else {
2382
- // return bindings from setup
2383
- const allBindings = { ...setupBindings };
2384
- for (const key in userImports) {
2385
- if (!userImports[key].isType) {
2386
- allBindings[key] = true;
2387
- }
2388
- }
2389
- returned = `{ ${Object.keys(allBindings).join(', ')} }`;
2390
- }
2391
- s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
2392
- // 11. finalize default export
2393
- // expose: [] makes <script setup> components "closed" by default.
2394
- let runtimeOptions = `\n expose: [],`;
2395
- if (hasInheritAttrsFlag) {
2396
- runtimeOptions += `\n inheritAttrs: false,`;
2397
- }
2398
- if (hasInlinedSsrRenderFn) {
2399
- runtimeOptions += `\n __ssrInlineRender: true,`;
2400
- }
2401
- if (propsRuntimeDecl) {
2402
- runtimeOptions += `\n props: ${scriptSetup.content
2403
- .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
2404
- .trim()},`;
2405
- }
2406
- else if (propsTypeDecl) {
2407
- runtimeOptions += genRuntimeProps(typeDeclaredProps);
2408
- }
2409
- if (emitRuntimeDecl) {
2410
- runtimeOptions += `\n emits: ${scriptSetup.content
2411
- .slice(emitRuntimeDecl.start, emitRuntimeDecl.end)
2412
- .trim()},`;
2413
- }
2414
- else if (emitTypeDecl) {
2415
- runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
2416
- }
2417
- if (isTS) {
2418
- // for TS, make sure the exported type is still valid type with
2419
- // correct props information
2420
- // we have to use object spread for types to be merged properly
2421
- // user's TS setting should compile it down to proper targets
2422
- const def = defaultExport ? `\n ...${defaultTempVar},` : ``;
2423
- // wrap setup code with function.
2424
- // export the content of <script setup> as a named export, `setup`.
2425
- // this allows `import { setup } from '*.vue'` for testing purposes.
2426
- s.prependLeft(startOffset, `\nexport default ${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n`);
2427
- s.appendRight(endOffset, `})`);
2428
- }
2429
- else {
2430
- if (defaultExport) {
2431
- // can't rely on spread operator in non ts mode
2432
- s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
2433
- s.append(`\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`);
2434
- }
2435
- else {
2436
- s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
2437
- `${hasAwait ? `async ` : ``}setup(${args}) {\n`);
2438
- s.appendRight(endOffset, `}`);
2439
- }
2440
- }
2441
- // 12. finalize Vue helper imports
2442
- if (helperImports.size > 0) {
2443
- s.prepend(`import { ${[...helperImports]
2444
- .map(h => `${h} as _${h}`)
2445
- .join(', ')} } from 'vue'\n`);
2446
- }
2447
- s.trim();
2448
- return {
2449
- ...scriptSetup,
2450
- bindings: bindingMetadata,
2451
- content: s.toString(),
2452
- map: s.generateMap({
2453
- source: filename,
2454
- hires: true,
2455
- includeContent: true
2456
- }),
2457
- scriptAst,
2458
- scriptSetupAst
2459
- };
2460
- }
2461
- function walkDeclaration(node, bindings, userImportAlias) {
2462
- if (node.type === 'VariableDeclaration') {
2463
- const isConst = node.kind === 'const';
2464
- // export const foo = ...
2465
- for (const { id, init } of node.declarations) {
2466
- const isDefineCall = !!(isConst &&
2467
- (isCallOf(init, DEFINE_PROPS) || isCallOf(init, DEFINE_EMIT)));
2468
- if (id.type === 'Identifier') {
2469
- let bindingType;
2470
- if (
2471
- // if a declaration is a const literal, we can mark it so that
2472
- // the generated render fn code doesn't need to unref() it
2473
- isDefineCall ||
2474
- (isConst &&
2475
- canNeverBeRef(init, userImportAlias['reactive'] || 'reactive'))) {
2476
- bindingType = "setup-const" /* SETUP_CONST */;
2477
- }
2478
- else if (isConst) {
2479
- if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
2480
- bindingType = "setup-ref" /* SETUP_REF */;
2481
- }
2482
- else {
2483
- bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
2484
- }
2485
- }
2486
- else {
2487
- bindingType = "setup-let" /* SETUP_LET */;
2488
- }
2489
- bindings[id.name] = bindingType;
2490
- }
2491
- else if (id.type === 'ObjectPattern') {
2492
- walkObjectPattern(id, bindings, isConst, isDefineCall);
2493
- }
2494
- else if (id.type === 'ArrayPattern') {
2495
- walkArrayPattern(id, bindings, isConst, isDefineCall);
2496
- }
2497
- }
2498
- }
2499
- else if (node.type === 'FunctionDeclaration' ||
2500
- node.type === 'ClassDeclaration') {
2501
- // export function foo() {} / export class Foo {}
2502
- // export declarations must be named.
2503
- bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
2504
- }
2505
- }
2506
- function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
2507
- for (const p of node.properties) {
2508
- if (p.type === 'ObjectProperty') {
2509
- // key can only be Identifier in ObjectPattern
2510
- if (p.key.type === 'Identifier') {
2511
- if (p.key === p.value) {
2512
- // const { x } = ...
2513
- bindings[p.key.name] = isDefineCall
2514
- ? "setup-const" /* SETUP_CONST */
2515
- : isConst
2516
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2517
- : "setup-let" /* SETUP_LET */;
2518
- }
2519
- else {
2520
- walkPattern(p.value, bindings, isConst, isDefineCall);
2521
- }
2522
- }
2523
- }
2524
- else {
2525
- // ...rest
2526
- // argument can only be identifer when destructuring
2527
- bindings[p.argument.name] = isConst
2528
- ? "setup-const" /* SETUP_CONST */
2529
- : "setup-let" /* SETUP_LET */;
2530
- }
2531
- }
2532
- }
2533
- function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
2534
- for (const e of node.elements) {
2535
- e && walkPattern(e, bindings, isConst, isDefineCall);
2536
- }
2537
- }
2538
- function walkPattern(node, bindings, isConst, isDefineCall = false) {
2539
- if (node.type === 'Identifier') {
2540
- bindings[node.name] = isDefineCall
2541
- ? "setup-const" /* SETUP_CONST */
2542
- : isConst
2543
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2544
- : "setup-let" /* SETUP_LET */;
2545
- }
2546
- else if (node.type === 'RestElement') {
2547
- // argument can only be identifer when destructuring
2548
- bindings[node.argument.name] = isConst
2549
- ? "setup-const" /* SETUP_CONST */
2550
- : "setup-let" /* SETUP_LET */;
2551
- }
2552
- else if (node.type === 'ObjectPattern') {
2553
- walkObjectPattern(node, bindings, isConst);
2554
- }
2555
- else if (node.type === 'ArrayPattern') {
2556
- walkArrayPattern(node, bindings, isConst);
2557
- }
2558
- else if (node.type === 'AssignmentPattern') {
2559
- if (node.left.type === 'Identifier') {
2560
- bindings[node.left.name] = isDefineCall
2561
- ? "setup-const" /* SETUP_CONST */
2562
- : isConst
2563
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2564
- : "setup-let" /* SETUP_LET */;
2565
- }
2566
- else {
2567
- walkPattern(node.left, bindings, isConst);
2568
- }
2569
- }
2570
- }
2571
- function recordType(node, declaredTypes) {
2572
- if (node.type === 'TSInterfaceDeclaration') {
2573
- declaredTypes[node.id.name] = [`Object`];
2574
- }
2575
- else if (node.type === 'TSTypeAliasDeclaration') {
2576
- declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
2577
- }
2578
- else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
2579
- recordType(node.declaration, declaredTypes);
2580
- }
2581
- }
2582
- function extractRuntimeProps(node, props, declaredTypes) {
2583
- for (const m of node.members) {
2584
- if (m.type === 'TSPropertySignature' && m.key.type === 'Identifier') {
2585
- props[m.key.name] = {
2586
- key: m.key.name,
2587
- required: !m.optional,
2588
- type: m.typeAnnotation
2589
- ? inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
2590
- : [`null`]
2591
- };
2592
- }
2593
- }
2594
- }
2595
- function inferRuntimeType(node, declaredTypes) {
2596
- switch (node.type) {
2597
- case 'TSStringKeyword':
2598
- return ['String'];
2599
- case 'TSNumberKeyword':
2600
- return ['Number'];
2601
- case 'TSBooleanKeyword':
2602
- return ['Boolean'];
2603
- case 'TSObjectKeyword':
2604
- return ['Object'];
2605
- case 'TSTypeLiteral':
2606
- // TODO (nice to have) generate runtime property validation
2607
- return ['Object'];
2608
- case 'TSFunctionType':
2609
- return ['Function'];
2610
- case 'TSArrayType':
2611
- case 'TSTupleType':
2612
- // TODO (nice to have) generate runtime element type/length checks
2613
- return ['Array'];
2614
- case 'TSLiteralType':
2615
- switch (node.literal.type) {
2616
- case 'StringLiteral':
2617
- return ['String'];
2618
- case 'BooleanLiteral':
2619
- return ['Boolean'];
2620
- case 'NumericLiteral':
2621
- case 'BigIntLiteral':
2622
- return ['Number'];
2623
- default:
2624
- return [`null`];
2625
- }
2626
- case 'TSTypeReference':
2627
- if (node.typeName.type === 'Identifier') {
2628
- if (declaredTypes[node.typeName.name]) {
2629
- return declaredTypes[node.typeName.name];
2630
- }
2631
- switch (node.typeName.name) {
2632
- case 'Array':
2633
- case 'Function':
2634
- case 'Object':
2635
- case 'Set':
2636
- case 'Map':
2637
- case 'WeakSet':
2638
- case 'WeakMap':
2639
- return [node.typeName.name];
2640
- case 'Record':
2641
- case 'Partial':
2642
- case 'Readonly':
2643
- case 'Pick':
2644
- case 'Omit':
2645
- case 'Exclude':
2646
- case 'Extract':
2647
- case 'Required':
2648
- case 'InstanceType':
2649
- return ['Object'];
2650
- }
2651
- }
2652
- return [`null`];
2653
- case 'TSUnionType':
2654
- return [
2655
- ...new Set([].concat(node.types.map(t => inferRuntimeType(t, declaredTypes))))
2656
- ];
2657
- case 'TSIntersectionType':
2658
- return ['Object'];
2659
- default:
2660
- return [`null`]; // no runtime check
2661
- }
2662
- }
2663
- function genRuntimeProps(props) {
2664
- const keys = Object.keys(props);
2665
- if (!keys.length) {
2666
- return ``;
2667
- }
2668
- return `\n props: {\n ${keys
2669
- .map(key => {
2670
- const { type, required } = props[key];
2671
- return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required} }`;
2672
- })
2673
- .join(',\n ')}\n } as unknown as undefined,`;
2674
- }
2675
- function toRuntimeTypeString(types) {
2676
- return types.some(t => t === 'null')
2677
- ? `null`
2678
- : types.length > 1
2679
- ? `[${types.join(', ')}]`
2680
- : types[0];
2681
- }
2682
- function extractRuntimeEmits(node, emits) {
2683
- if (node.type === 'TSUnionType') {
2684
- for (let t of node.types) {
2685
- if (t.type === 'TSParenthesizedType')
2686
- t = t.typeAnnotation;
2687
- if (t.type === 'TSFunctionType') {
2688
- extractRuntimeEmits(t, emits);
2689
- }
2690
- }
2691
- return;
2692
- }
2693
- const eventName = node.parameters[0];
2694
- if (eventName.type === 'Identifier' &&
2695
- eventName.typeAnnotation &&
2696
- eventName.typeAnnotation.type === 'TSTypeAnnotation') {
2697
- const typeNode = eventName.typeAnnotation.typeAnnotation;
2698
- if (typeNode.type === 'TSLiteralType') {
2699
- emits.add(String(typeNode.literal.value));
2700
- }
2701
- else if (typeNode.type === 'TSUnionType') {
2702
- for (const t of typeNode.types) {
2703
- if (t.type === 'TSLiteralType') {
2704
- emits.add(String(t.literal.value));
2705
- }
2706
- }
2707
- }
2708
- }
2709
- }
2710
- function genRuntimeEmits(emits) {
2711
- return emits.size
2712
- ? `\n emits: [${Array.from(emits)
2713
- .map(p => JSON.stringify(p))
2714
- .join(', ')}] as unknown as undefined,`
2715
- : ``;
2716
- }
2717
- const parentStack = [];
2718
- /**
2719
- * Walk an AST and find identifiers that are variable references.
2720
- * This is largely the same logic with `transformExpressions` in compiler-core
2721
- * but with some subtle differences as this needs to handle a wider range of
2722
- * possible syntax.
2723
- */
2724
- function walkIdentifiers(root, onIdentifier) {
2725
- const knownIds = Object.create(null);
2726
- estreeWalker.walk(root, {
2727
- enter(node, parent) {
2728
- parent && parentStack.push(parent);
2729
- if (node.type === 'Identifier') {
2730
- if (!knownIds[node.name] && isRefIdentifier(node, parent)) {
2731
- onIdentifier(node, parent);
2732
- }
2733
- }
2734
- else if (isFunction(node)) {
2735
- // walk function expressions and add its arguments to known identifiers
2736
- // so that we don't prefix them
2737
- node.params.forEach(p => estreeWalker.walk(p, {
2738
- enter(child, parent) {
2739
- if (child.type === 'Identifier' &&
2740
- // do not record as scope variable if is a destructured key
2741
- !isStaticPropertyKey(child, parent) &&
2742
- // do not record if this is a default value
2743
- // assignment of a destructured variable
2744
- !(parent &&
2745
- parent.type === 'AssignmentPattern' &&
2746
- parent.right === child)) {
2747
- const { name } = child;
2748
- if (node.scopeIds && node.scopeIds.has(name)) {
2749
- return;
2750
- }
2751
- if (name in knownIds) {
2752
- knownIds[name]++;
2753
- }
2754
- else {
2755
- knownIds[name] = 1;
2756
- }
2757
- (node.scopeIds || (node.scopeIds = new Set())).add(name);
2758
- }
2759
- }
2760
- }));
2761
- }
2762
- else if (node.type === 'ObjectProperty' &&
2763
- parent.type === 'ObjectPattern') {
2764
- node.inPattern = true;
2765
- }
2766
- },
2767
- leave(node, parent) {
2768
- parent && parentStack.pop();
2769
- if (node.scopeIds) {
2770
- node.scopeIds.forEach((id) => {
2771
- knownIds[id]--;
2772
- if (knownIds[id] === 0) {
2773
- delete knownIds[id];
2774
- }
2775
- });
2776
- }
2777
- }
2778
- });
2779
- }
2780
- function isRefIdentifier(id, parent) {
2781
- // declaration id
2782
- if ((parent.type === 'VariableDeclarator' ||
2783
- parent.type === 'ClassDeclaration') &&
2784
- parent.id === id) {
2785
- return false;
2786
- }
2787
- if (isFunction(parent)) {
2788
- // function decalration/expression id
2789
- if (parent.id === id) {
2790
- return false;
2791
- }
2792
- // params list
2793
- if (parent.params.includes(id)) {
2794
- return false;
2795
- }
2796
- }
2797
- // property key
2798
- // this also covers object destructure pattern
2799
- if (isStaticPropertyKey(id, parent)) {
2800
- return false;
2801
- }
2802
- // non-assignment array destructure pattern
2803
- if (parent.type === 'ArrayPattern' &&
2804
- !isInDestructureAssignment(parent, parentStack)) {
2805
- return false;
2806
- }
2807
- // member expression property
2808
- if ((parent.type === 'MemberExpression' ||
2809
- parent.type === 'OptionalMemberExpression') &&
2810
- parent.property === id &&
2811
- !parent.computed) {
2812
- return false;
2813
- }
2814
- // is a special keyword but parsed as identifier
2815
- if (id.name === 'arguments') {
2816
- return false;
2817
- }
2818
- return true;
2819
- }
2820
- const isStaticProperty = (node) => node &&
2821
- (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
2822
- !node.computed;
2823
- const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
2824
- function isFunction(node) {
2825
- return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
2826
- }
2827
- function isCallOf(node, name) {
2828
- return !!(node &&
2829
- node.type === 'CallExpression' &&
2830
- node.callee.type === 'Identifier' &&
2831
- node.callee.name === name);
2832
- }
2833
- function canNeverBeRef(node, userReactiveImport) {
2834
- if (isCallOf(node, userReactiveImport)) {
2835
- return true;
2836
- }
2837
- switch (node.type) {
2838
- case 'UnaryExpression':
2839
- case 'BinaryExpression':
2840
- case 'ArrayExpression':
2841
- case 'ObjectExpression':
2842
- case 'FunctionExpression':
2843
- case 'ArrowFunctionExpression':
2844
- case 'UpdateExpression':
2845
- case 'ClassExpression':
2846
- case 'TaggedTemplateExpression':
2847
- return true;
2848
- case 'SequenceExpression':
2849
- return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
2850
- default:
2851
- if (node.type.endsWith('Literal')) {
2852
- return true;
2853
- }
2854
- return false;
2855
- }
2856
- }
2857
- function isInDestructureAssignment(parent, parentStack) {
2858
- if (parent &&
2859
- (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
2860
- let i = parentStack.length;
2861
- while (i--) {
2862
- const p = parentStack[i];
2863
- if (p.type === 'AssignmentExpression') {
2864
- const root = parentStack[0];
2865
- // if this is a ref: destructure, it should be treated like a
2866
- // variable decalration!
2867
- return !(root.type === 'LabeledStatement' && root.label.name === 'ref');
2868
- }
2869
- else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
2870
- break;
2871
- }
2872
- }
2873
- }
2874
- return false;
2875
- }
2876
- /**
2877
- * Analyze bindings in normal `<script>`
2878
- * Note that `compileScriptSetup` already analyzes bindings as part of its
2879
- * compilation process so this should only be used on single `<script>` SFCs.
2880
- */
2881
- function analyzeScriptBindings(ast) {
2882
- for (const node of ast) {
2883
- if (node.type === 'ExportDefaultDeclaration' &&
2884
- node.declaration.type === 'ObjectExpression') {
2885
- return analyzeBindingsFromOptions(node.declaration);
2886
- }
2887
- }
2888
- return {};
2889
- }
2890
- function analyzeBindingsFromOptions(node) {
2891
- const bindings = {};
2892
- for (const property of node.properties) {
2893
- if (property.type === 'ObjectProperty' &&
2894
- !property.computed &&
2895
- property.key.type === 'Identifier') {
2896
- // props
2897
- if (property.key.name === 'props') {
2898
- // props: ['foo']
2899
- // props: { foo: ... }
2900
- for (const key of getObjectOrArrayExpressionKeys(property.value)) {
2901
- bindings[key] = "props" /* PROPS */;
2902
- }
2903
- }
2904
- // inject
2905
- else if (property.key.name === 'inject') {
2906
- // inject: ['foo']
2907
- // inject: { foo: {} }
2908
- for (const key of getObjectOrArrayExpressionKeys(property.value)) {
2909
- bindings[key] = "options" /* OPTIONS */;
2910
- }
2911
- }
2912
- // computed & methods
2913
- else if (property.value.type === 'ObjectExpression' &&
2914
- (property.key.name === 'computed' || property.key.name === 'methods')) {
2915
- // methods: { foo() {} }
2916
- // computed: { foo() {} }
2917
- for (const key of getObjectExpressionKeys(property.value)) {
2918
- bindings[key] = "options" /* OPTIONS */;
2919
- }
2920
- }
2921
- }
2922
- // setup & data
2923
- else if (property.type === 'ObjectMethod' &&
2924
- property.key.type === 'Identifier' &&
2925
- (property.key.name === 'setup' || property.key.name === 'data')) {
2926
- for (const bodyItem of property.body.body) {
2927
- // setup() {
2928
- // return {
2929
- // foo: null
2930
- // }
2931
- // }
2932
- if (bodyItem.type === 'ReturnStatement' &&
2933
- bodyItem.argument &&
2934
- bodyItem.argument.type === 'ObjectExpression') {
2935
- for (const key of getObjectExpressionKeys(bodyItem.argument)) {
2936
- bindings[key] =
2937
- property.key.name === 'setup'
2938
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2939
- : "data" /* DATA */;
2940
- }
2941
- }
2942
- }
2943
- }
2944
- }
2945
- return bindings;
2946
- }
2947
- function getObjectExpressionKeys(node) {
2948
- const keys = [];
2949
- for (const prop of node.properties) {
2950
- if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
2951
- !prop.computed) {
2952
- if (prop.key.type === 'Identifier') {
2953
- keys.push(prop.key.name);
2954
- }
2955
- else if (prop.key.type === 'StringLiteral') {
2956
- keys.push(prop.key.value);
2957
- }
2958
- }
2959
- }
2960
- return keys;
2961
- }
2962
- function getArrayExpressionKeys(node) {
2963
- const keys = [];
2964
- for (const element of node.elements) {
2965
- if (element && element.type === 'StringLiteral') {
2966
- keys.push(element.value);
2967
- }
2968
- }
2969
- return keys;
2970
- }
2971
- function getObjectOrArrayExpressionKeys(value) {
2972
- if (value.type === 'ArrayExpression') {
2973
- return getArrayExpressionKeys(value);
2974
- }
2975
- if (value.type === 'ObjectExpression') {
2976
- return getObjectExpressionKeys(value);
2977
- }
2978
- return [];
2979
- }
2980
-
2981
- exports.generateCodeFrame = compilerCore.generateCodeFrame;
2982
- exports.compileScript = compileScript;
2983
- exports.compileStyle = compileStyle;
2984
- exports.compileStyleAsync = compileStyleAsync;
2985
- exports.compileTemplate = compileTemplate;
2986
- exports.parse = parse;
2987
- exports.rewriteDefault = rewriteDefault;
2988
-
2989
- const compilerSfc_cjs = /*#__PURE__*/Object.freeze({
2990
- __proto__: null
2991
- });
2992
-
2993
539
  exports.gqlPluckFromCodeString = gqlPluckFromCodeString;
2994
540
  exports.gqlPluckFromCodeStringSync = gqlPluckFromCodeStringSync;
2995
541
  exports.parseCode = parseCode;