1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import fs from 'fs';
17import { createFilter } from '@rollup/pluginutils';
18import { 
19  findVisualFile, 
20  visualTransform as processVisual 
21} from '../../process_visual';
22import MagicString from 'magic-string';
23import { PluginContext } from 'rollup';
24import { projectConfig } from '../../../main';
25
26const filter: any = createFilter(/(?<!\.d)\.ets$/);
27
28export function visualTransform() {
29  return {
30    name: 'visualTransform',
31    transform(code: string, id: string) {
32if (!filter(id)) {
33        return null;
34      }
35      if (process.env.watchMode !== 'true' && 'esmodule' === projectConfig.compileMode) {
36        return null;
37      }
38      const logger = this.share.getLogger('visualTransform');
39      code = processVisual(code, id, logger);
40      const magicString = new MagicString(code);
41      return {
42        code,
43        map: magicString.generateMap({ hires: true })
44      };
45    },
46    shouldInvalidCache(this: PluginContext, options: any): boolean {
47      const moduleId: string = options.id;
48      if (!filter(moduleId) || !moduleId) {
49        return false;
50      }
51      const visualId: string = findVisualFile(moduleId);
52      if (!visualId || !fs.existsSync(visualId)) {
53        if (this.cache.has(visualId)) {
54          this.cache.delete(visualId);
55        }
56        return false;
57      }
58      const stat: fs.Stats = fs.statSync(visualId);
59      const currentTimestamp: number = stat.mtime.getTime();
60      if (!this.cache.has(visualId)) {
61        this.cache.set(visualId, currentTimestamp);
62        return true;
63      }
64      const lastTimestamp: number = this.cache.get(visualId);
65      this.cache.set(visualId, currentTimestamp);
66      if (currentTimestamp === lastTimestamp) {
67        return false;
68      }
69      return true;
70    }
71  }
72}