libs/common/src/lib/services/flight.service.ts:40:51 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

          40    worker = new Worker(new URL('./flight.worker', import.meta.url), { type: 'module' }



service 
import { HttpClient, HttpParams } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { filter, map, Observable, Subject, tap } from 'rxjs';
import { Flight, FLIGHT_STATUS_DICT, IFlight, IFlightLeg } from '../models/flight.model';
import { DateTime } from 'luxon';
import {  flatten, intersection, sortBy } from 'lodash';;
import * as FileSaver from 'file-saver';
import * as ExcelJS from 'exceljs';
import { ConfigService } from './config.service';
import { GraphqlService } from './graphql.service';
import { AuthService } from '../core/auth/auth.service';
import { generateClient, GraphQLResult } from 'aws-amplify/api';
import { flightLegSubscription } from './queries/flightleg.subscription';
import { FlightTag } from '../models/tag.model';

type GetFlightOptions = {
  startTs: string;
  endTs: string;
  flightNumber?: string;
};

@Injectable({
  providedIn: 'root',
})
export class FlightService {
  public workerProcessedFlights$ = new Subject<Flight[]>();
  private readonly httpClient = inject(HttpClient);
  // private readonly thresholdStore = inject(ThresholdStore);
  private configService = inject(ConfigService);
  private graphql = inject(GraphqlService);
  private authService = inject(AuthService);
  private readonly flightListRealTimeHost =
    this.configService.config?.flightListRealTimeHost || '';
  private client = generateClient({
    endpoint: this.flightListRealTimeHost,
    authMode: 'lambda',
    authToken: `Bearer ${this.authService.accessToken}`
  });

   worker = new Worker(new URL('./flight.worker', import.meta.url), { type: 'module' });


   constructor() {
    this.graphql.initializeClient(this.flightListRealTimeHost);
  }

  public getFlights(opts: GetFlightOptions): Observable<Flight[]> {
    const url = this.configService.config?.oneuiDOPBaseUrl + "/api/v1/flights";

    const params = new HttpParams()
      .set('startTs', opts.startTs)
      .set('endTs', opts.endTs);
    return this.httpClient.get<Flight[]>(url, {params});
  }

  public onFlightListUpdateEvent(): Observable<GraphQLResult<{ observeFlightLeg: Flight }>> {
    return this.client.graphql({
      query: flightLegSubscription
    }) as Observable<GraphQLResult<{ observeFlightLeg: Flight }>>;
  }
  public processFlight(flight: Flight): Flight {
    flight = {
      ...flight,
      notes: flight.notes || [],
      tags: flight.tags || [],
      cxScore: +flight.cxScore,
      communicatorMessages: flight.communicatorMessages || [],
      lastUpdatedTs: DateTime.fromISO(flight.lastUpdated + 'Z').toISO() || '',
      diversionLegs: this.generateDiversionLegs(flight),
    };

    flight.painCategory = this.assignPainCategory(flight);

    return flight;
  }

  public webWorkerFlightProcess(flights: Flight[]) {
    const data = {
      originalFlights: flights,
      // thresholdData: this.thresholdStore.thresholdEntities(),
      thresholdData: []
    };

    this.worker.postMessage(data);

    this.worker.onmessage = ({ data }) => {
      this.workerProcessedFlights$.next(data);
    };
  }

  public getFlightUpdates(timestamp: string): Observable<Flight[]> {
    const url = this.configService.config?.oneuiDOPBaseUrl + `flightupdates/${timestamp}`;

    return this.httpClient.get<Flight[]>(url);
  }

   public filterFlights(flights: Flight[], filters: any): Flight[] {
    const keepActiveStatus = ['MONITOR', 'ACTION'];

    const timeOffset = DateTime.utc().minus({ hours: 12 });

    // Filter only painful flights
    flights = flights.filter((flight) => flight.cxScore >= 0);

    // Remove Completed +12 Hours
    flights = flights.filter((flight) => {
      if (flight.flightLegStatus !== 'COMPLETE') {
        return true;
      }

      if (flight.flightLegStatus === 'COMPLETE') {
        // If for some reason a complete flight doesnt have in IN time show it list
        if (!flight.actualArrivalTimeUtc) {
          return true;
        }

        if (
          DateTime.fromISO(flight.actualArrivalTimeUtc) > timeOffset ||
          keepActiveStatus.includes(flight.docStatus)
        ) {
          return true;
        } else {
          return false;
        }
      }

      return false;
    });

    // Remove Cancelled +12 Hours
    flights = flights.filter((flight) => {
      if (flight.flightLegStatus !== 'CANCELED') {
        return true;
      }

      if (flight.flightLegStatus === 'CANCELED') {
        // If no cancel time available include in filter for user to manually hide
        if (flight.cnclDteTmeUtc === null) {
          return true;
        }

        if (
          DateTime.fromISO(flight.cnclDteTmeUtc) > timeOffset ||
          keepActiveStatus.includes(flight.docStatus)
        ) {
          return true;
        }
      }

      return false;
    });

    if (filters.flightNumber) {
      flights = flights.filter((f) => f.flightNumber === filters.flightNumber);
    }

    if (filters.originCode) {
      flights = flights.filter(
        (f) => f.originCode.toLowerCase() === filters.originCode.toLowerCase(),
      );
    }

    if (filters.destinationCode) {
      flights = flights.filter(
        (f) =>
          f.destinationCode.toLowerCase() ===
          filters.destinationCode.toLowerCase(),
      );
    }

    if (filters.originDate && filters.originDate !== 'ALL') {
      flights = flights.filter(
        (flight) =>
          DateTime.fromISO(flight.flightOriginDateLcl).toFormat('dd') ===
          filters.originDate,
      );
    }

    if (filters.flightStatus) {
      let activeStatusList = filters.flightStatus.map((statusGroup: keyof typeof FLIGHT_STATUS_DICT) => {
        return FLIGHT_STATUS_DICT[statusGroup];
      });

      activeStatusList = flatten(activeStatusList);

      flights = flights.filter((flight) => {
        return activeStatusList.map((s: string) => s.toUpperCase()).includes(flight.flightLegStatus);
      });
    }

    if (filters.teamStatus && filters.teamStatus.length) {
      flights = flights.filter((f) => {
        const filterArray: string[] = [];

        filterArray.push(`DOC:${f.docStatus ? f.docStatus : 'NONE'}`);
        filterArray.push(`ROC:${f.rocStatus ? f.rocStatus : 'NONE'}`);
        filterArray.push(`GAC:${f.gacStatus ? f.gacStatus : 'NONE'}`);
        filterArray.push(`RMO:${f.rmoStatus ? f.rmoStatus : 'NONE'}`);
        filterArray.push(`RES:${f.resOccStatus ? f.resOccStatus : 'NONE'}`);
        filterArray.push(
          `CATERING:${f.occCateringStatus ? f.occCateringStatus : 'NONE'}`,
        );
        filterArray.push(`ACS:${f.acsOccStatus ? f.acsOccStatus : 'NONE'}`);

        return intersection(filters.teamStatus, filterArray).length;
      });
    }

    if (filters.piLBound) {
      flights = flights.filter((flight) => flight.cxScore >= filters.piLBound);
    }

    if (filters.piUBound) {
      flights = flights.filter((flight) => flight.cxScore <= filters.piUBound);
    }

    if (filters.painVelocity === 'HIGH') {
      flights = flights.filter((flight) => flight.lastHighPainVelocityCheckTs);
    }

    if (filters.carriers && filters.carriers.length > 0) {
      flights = flights.filter((flight) =>
        filters.carriers.includes(flight.operatingCarrierCode),
      );
    }

    if (filters.tags && filters.tags.length) {
      flights = (flights || []).filter((flight) => {
        if (flight.tags) {
          const flightTags = flight.tags.map((t: FlightTag) => t.tag);

          return intersection(filters.tags, flightTags).length;
        }
        return ['']
      });
    }

    if (filters.docCommunicationType && filters.docCommunicationType.length) {
      flights = flights.filter((flight) => {
        if (flight.communicatorMessages) {
          const commTypes = flight.communicatorMessages.map(
            (comm) => comm.type,
          );

          return (
            intersection(commTypes, filters.docCommunicationType).length > 0
          );
        }

        return false;
      });
    }

    return flights;
  }

  public addFlightTask(flight: Flight, task: any): Observable<any> {
    const url = this.configService.config?.oneuiDOPBaseUrl + `/api/v1/flights/${flight.flightId}/tasks`;

    return this.httpClient.post(url, task);
  }

  public createTeamStatus(status: any) {
    const url = this.configService.config?.oneuiDOPBaseUrl + 'flights/status';

    return this.httpClient.post(url, status);
  }

  public updatesTeamStatus(status: { ID: any; }) {
    const url = this.configService.config?.oneuiDOPBaseUrl + `flights/status/${status.ID}`;

    return this.httpClient.put(url, status);
  }

  public getFlightBySK(opts: { sk: string }): Observable<Flight> {
    const url = this.configService.config?.oneuiDOPBaseUrl + `/api/v1/flights/${opts.sk}`;

    return this.httpClient.get<Flight>(url).pipe(
      map((flight: Flight) => this.processFlight(flight)),
    );
  }

  public lookupFlights(params: GetFlightOptions): Observable<Flight[]> {
    const url = this.configService.config?.oneuiDOPBaseUrl + `/api/v1/flightlookup`;

    return this.httpClient.get<Flight[]>(url, { params });
  }

  public getScoreBreakdown(flight: Flight): Observable<any> {
    const url = this.configService.config?.oneuiDOPBaseUrl + `flights/${flight.flightId}/scoredetail`;

    return this.httpClient.get(url);
  }

  public assignPainCategory(flight: Flight): string {
    const cxScore = flight.cxScore;
    // const threshold = this.thresholdStore
    //   .thresholdEntities()
    //   .filter((t) => cxScore >= t['lowerBound'] && cxScore < t['upperBound']);

    // if (threshold.length > 0) {
    //   return threshold[0]['name'];
    // } else {
    //   return '--';
    // }
    return '--'
  }

  public generateDiversionLegs(flight: Flight) {
    if (flight.linkedLegs) {
      return flight.linkedLegs.filter(
        (leg) => leg.arvl_iop_action_cde === 'DVRT',
      );
    }
    return [];
  }

  public downloadStatusChanges(startTs: string, endTs: string) {
    const url = this.configService.config?.oneuiDOPBaseUrl + `statuschange`;

    const params = {
      startTs,
      endTs,
    };

    this.httpClient.get(url, { params }).subscribe(async (res: any) => {
      if (res) {
        const sheetName = 'OCC DOC Flight Tracker';
        const workbook = new ExcelJS.Workbook();
        const sheet = workbook.addWorksheet(sheetName);

        sheet.addRow([
          'Carrier',
          'Flt Num',
          'Orig',
          'Dest',
          'SKD Dep Date',
          'Final PI',
          'Action',
          'Value',
          'Link',
        ]);

        const font = { name: 'Arial', size: 12, bold: true };

        sheet.getCell('A1').font = font;
        sheet.getCell('B1').font = font;
        sheet.getCell('C1').font = font;
        sheet.getCell('D1').font = font;
        sheet.getCell('E1').font = font;
        sheet.getCell('F1').font = font;
        sheet.getCell('G1').font = font;
        sheet.getCell('H1').font = font;
        sheet.getCell('I1').font = font;

        const filteredArray = res.filter((rec: { content: { status: string; }; }) => {
          return (
            rec.content.status === 'ACTION|COMPLETE' ||
            rec.content.status === 'ACTION'
          );
        });

        // Massage leg
        filteredArray.forEach((c: { [x: string]: any; content: { status: any; }; }) => {
          const data = c['flightid'].split('::');

          c['carrier'] = data[0];
          c['flightNumber'] = data[2];
          c['Orig'] = data[3];
          c['dest'] = data[4];
          c['skd_date'] = DateTime.fromISO(data[1]).toFormat('LL/dd/yy');
          c['content'] = c.content.status;
        });

        // Sort By Date
        const sorted_array = sortBy(filteredArray, ['skd_date', 'flightNumber']);

        let recsMap: any;

        // Keep ACTION / COMPLETE over ACTION
        sorted_array.forEach((item) => {
          if (recsMap[item.flightid]) {
            if (item.content === 'ACTION | COMPLETE') {
              recsMap[item.flightid] = item;
            }
          } else {
            recsMap[item.flightid] = item;
          }
        });

        const records: any = Object.values(recsMap);

        records.forEach((c: { [x: string]: any; }) => {
          const newRow = sheet.addRow([
            c['carrier'],
            c['flightNumber'],
            c['Orig'],
            c['dest'],
            c['skd_date'],
            c['cxScore'],
            c['action'],
            c['content'],
            {
              text: 'Link',
              hyperlink: `${window.location.origin}/?flight=${c['flightid']}`,
            },
          ]);

          newRow.font = { name: 'Arial', size: 10 };
        });

        const buffer = await workbook.xlsx.writeBuffer();
        const fileType =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const fileExtension = '.xlsx';
        const blob = new Blob([buffer], { type: fileType });

        FileSaver.saveAs(
          blob,
          `${sheetName}-${DateTime.fromISO(startTs).toFormat('ddLLL')}-${DateTime.fromISO(
            endTs,
          ).toFormat(
            'ddLLL',
          )}-${DateTime.local().toFormat('yyyy-LL-dd HHmm')}.${fileExtension}`,
        );
      }
    });
  }
}

worker.json
{
    "extends": "./tsconfig.json",
    "compilerOptions": {
      "lib": ["es20222", "webworker"],
      "target":"es2022",
      "module": "es2022",
      "types": []
    },
    "include": [
      "**/*.worker.ts"
    ]
  }

{
  "name": "@oneui/common",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/common/src",
  "prefix": "lib",
  "projectType": "library", 
  "tags": [],
  "targets": {
    "test": {
      "executor": "@nx/jest:jest",
      "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
      "options": {
        "jestConfig": "libs/common/jest.config.ts",
        "webWorkerTsConfig":"tsconfig.worker.json"
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint"
    },
    "build" :{
       "options": {
        "webWorkerTsConfig":"tsconfig.worker.json"
      }
    }
  }
}