EXPO SQLite, ReferenceError: Property ‘db’ doesn’t exist, js engine: hermes

I am trying to open a database called expenses.db but I am getting the error,

ReferenceError: Property ‘db’ doesn’t exist, js engine: hermes

This is the code I have written,

import { View, Text, Pressable, StyleSheet, StatusBar } from "react-native";
import Input from "../../src/components/input";
import { useState } from "react";
import { Picker } from "@react-native-picker/picker";
import * as SQLite from 'expo-sqlite';


const db = SQLite.openDatabase({
  name: 'expenses.db',
  location: 'default',
});

try {
  db.transaction((tx) => {
    tx.executeSql(
      'CREATE TABLE IF NOT EXISTS expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, amount REAL, category TEXT)',
      [],
      () => {
        console.log('Table created successfully.');
      },
      (error) => {
        console.log('Error creating table:', error);
      }
    );
  });
}
catch (error) {
  console.log('Error executing SQL statement:', error);
}

const AddExpense = () => {
  const [Category, setCategory] = useState("food");
  const [Name, setName] = useState("");
  const [Amount, setAmount] = useState("");

  // Function to be executed once we get input from the user about the expense/Inserting an expense record
  const Add = () => {
    console.log("Input 1:", Name);
    console.log("Input 2:", Amount);
    console.log("Input 3", Category);

    db.transaction(tx => {
      tx.executeSql(
        'INSERT INTO expenses (Name, Amount, Category) VALUES (?, ?, ?)',
        [Name, Amount, Category],
        (_, { rowsAffected, insertId }) => {
          if (rowsAffected > 0) {
            console.log("Expense record inserted with ID:", {insertId});
          }
        },
        (_, error) => {
          console.log("Error inserting expense record:", error);
        }
      );
    });
  };

  return (
    <View style={styles.container}>
      <Text>GastoCalc</Text>

      <Input
        text={"Name Of Expense"}
        placeholder={"What did you spend on?"}
        multiline={false}
        value={Name}
        onChangeText={(text) => setName(text)}
      />
      <Input
        text={"Expense Amount"}
        placeholder={"₹ ??"}
        inputMode={"numeric"}
        value={Amount}
        onChangeText={(text) => setAmount(text)}
      />

      <View style={styles.inputContainer}>
        <Text style={styles.inputText}>Category Of Expense</Text>

        <View style={styles.inputBorder}>
          <Picker
            // Updating category mutable variable everytime a new option is selected
            selectedValue={Category}
            onValueChange={(itemValue, itemIndex) => setCategory(itemValue)}
            style={styles.input}
          >
            <Picker.Item label="Food" value="food" />
            <Picker.Item label="Rent" value="rent" />
            <Picker.Item label="Fuel" value="fuel" />
            <Picker.Item label="Miscellaneous" value="mics" />
          </Picker>
        </View>
      </View>

      <View style={styles.buttonView}>
        <Pressable style={styles.addButton} onPress={Add}>
          <Text>ADD</Text>
        </Pressable>
      </View>
    </View>
  );
};

export default AddExpense;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight,
  },
  addButton: {
    backgroundColor: "lightgreen",
    alignItems: "center",
    justifyContent: "center",
    width: 75,
    height: 30,
  },
  buttonView: {
    flex: 1,
    justifyContent: "flex-end",
    alignItems: "center",
    marginBottom: 30,
  },

  // Styles for picker tag which will eventually be transferred to a different file.
  input: {
    marginTop: -9,
  },
  inputText: {
    fontSize: 15,
    alignItems: "baseline",
  },
  inputContainer: {
    flexDirection: "column",
    alignItems: "center",
    marginLeft: 15,
  },
  inputBorder: {
    borderWidth: 1,
    height: 40,
    width: 240,
    marginTop: 10,
  },
});

The error is particularly in the area below, I found this out using a try and catch block which I have removed since then,

const db = SQLite.openDatabase({
  name: 'expenses.db',
  location: 'default',
});

I am not sure where the problem is and there is no information about this on the internet as well. Any help is appreciated.

Need javascript with intents when working with the discord.js library

here is the code for a program that should play music from youtube in discord:

const { Client, Intents } = require('discord.js');
const ytdl = require('ytdl-core');
const ytSearch = require('youtube-search');

const token = 'xxxxxxxxxxxxxxxxxxxx'; // ds token

const client = new Client({
intents: [
GatewayIntentBits.GUILDS,
GatewayIntentBits.GUILD_MESSAGES,
GatewayIntentBits.GUILD_VOICE_STATES,
GatewayIntentBits.GUILD_MESSAGE_REACTIONS,
]
});

const opts = {
maxResults: 5,
key: 'xxxxxxxxxxxxxxxxxxxxxxxx',  // youtube api
type: 'video',
};

let dispatcher = null;
let repeat = false;

client.once('ready', () => {
console.log('Bot is online!');
});

client.on('messageCreate', async (message) => {
if (message.author.bot) return;

const voiceChannel = message.member.voice.channel;

if (message.content.startsWith('!play')) {
    if (!voiceChannel) {
        return message.channel.send('Вы должны находиться в голосовом канале, чтобы проиграть            музыку!');
    }

    const searchQuery = message.content.replace('!play', '').trim();

    try {
        const results = await ytSearch(searchQuery, opts);
        const videoURL = results[0].link;
        const connection = await voiceChannel.join();
        const stream = ytdl(videoURL, { filter: 'audioonly' });
        dispatcher = connection.play(stream, { seek: 0, volume: 1 });

        dispatcher.on('finish', () => {
            if (repeat) {
                dispatcher = connection.play(stream, { seek: 0, volume: 1 });
            } else {
                voiceChannel.leave();
                dispatcher = null;
            }
        });
    } catch (error) {
        console.error(error);
        message.channel.send('Произошла ошибка при воспроизведении музыки!');
    }
}

if (message.content === '!stop') {
    if (dispatcher) {
        dispatcher.end();
        dispatcher = null;
        voiceChannel.leave();
    }
}

if (message.content === '!skip') {
    if (dispatcher) {
        dispatcher.end();
        dispatcher = null;
    }
}

if (message.content === '!repeat') {
    repeat = !repeat;
    message.channel.send(`Режим повтора воспроизведения: ${repeat ? 'Включен' : 'Выключен'}`);
}

});

client.login(xxxxxxxxxxxxxxxx);

the error it’s giving:
Uncaught ReferenceError ReferenceError: GatewayIntentBits is not defined
at (file:///G:/All_Code/bots/bot_discord_music.js:9:9)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at executeUserEntryPoint (node:internal/modules/run_main:81:12)
at (node:internal/main/run_main_module:23:47)

help fix the problems to make the code work please!

How do I identify devices visiting my site?

Context

I am building a web app that is a survey-tool which allows users to create surveys, send them to others and have them filled out in the browser by them; much like Google Forms! A user does not have to log in before filling out one of these surveys.

Additional info:

  1. Building the web app with Nuxt
  2. Using Firebase as my backend

Problem

As users do not have to log in before filling out a survey, I need a way of identifying them to later be able to block survey resubmissions if the same user tries to send in another response.

I have read similar questions on StackOverflow covering this topic, however, in my case this doesn’t have to work all the time. I do not need something that is super secure that always works. It only has to work for the most part.

My plan is to grab some sort of device-based identifier once the user opens the survey, and I check if it exists in my database. If it does, then I block the submission. If it doesn’t exist, then I allow the submission and store the identifier in my database.

I would greatly appreciate any guidance towards solving this issue!

Populating Array Variable with Results of string.match method

I am having trouble with some Javascript code regarding populating an array with the results of the string.match method.

Essentially, I am trying to extract an array of strings from a piece of JSON coming from another application. I have verified that the match method does in fact return a valid array and that my regex expression is accurate. It is only when trying push these results to its own array that I seem to be running into problems.

The general structure of the code is as follows:

var orgSearchDomain = /*JSON STRING*/;
let orgSearchName = '';
let orgId = 0;
var orgAddresses = [];

if (orgSearchDomain.match(/"item":{"id"/g).length = 1) {

orgId = orgSearchDomain.match(/(?<="id":)d+/)[0];

}
else if (orgSearchDomain.match(/"item":{"id"/g).length > 1){

orgAddresses = new Array(orgSearchDomain.match(/(?<="address":).+?(? 
=,"visible_to)/g).slice(0));
}

I’ve tried declaring orgAddresses within the if-block using var and let without success. Moving the declaration outside of the if-block using var made some progress where the code no longer crashes but printing any of the properties of OrgAddresses will show that it is still an empty array of 0 length.

I really don’t know what I am missing here. Like I said, just printing properties of

orgSearchDomain.match(/(?<=”address”:).+?(? =,”visible_to)/g)

will yield correct results; something just seems to be going wrong the assignment to the new array of orgAddresses.

Any help will be much appreciated and please let me know if there is any additional information I may provide.

Interface shows data when output to the console, but getting undefined when accessing

I’ve been struggling with this problem for a while. I have an object that will be used to feed a vuetify data table. This object had nested objects full of data as well. I’ve been trying for a while to get the table to show my nested data objects, particularly on of type/interface IOrderDetails, to no avail.

I then figured I should just flatten the object. I made it so that my object took in the interface and mapped it to its members, and each member is responsible for mapping itself if it implements an interface. So I restructured it and now it I’m seeing this.
console output
using the interface

Seems like IOrderDetails is undefined when trying to access it, no matter what/when. But when I push it to the console, it shows the correct data. And I’m inspecting it before I try to access it. What am I not understanding about interfaces. Note that the other members are able to map themselves just fine. I cannot figure why this one is different. Some guidance would be greatly appreciated. Thanks in advance.

I tried mapping the data from interface land to object land. I keep running into the “undefined” interface.

Data is being dispatched using Omnibus.js. So I tried awaiting the dispatch call (in this case called “trigger”). I wasn’t doing that before, but I still get the same problem. Inspecting IOrderDetails before I dispatch it shows undefined. But inspecting the whole object shows IOrderDetails with data.

trouble pushing array into object (Javascript)

Using Javascript, I want to push some values into an array, then push that array into an object, but I’m getting the error message Cannot read properties of undefined (reading 'push').

I looked at JavaScript: Push into an Array inside an Object? and I appear to be using the same syntax. What am I doing wrong?

//global vars
var arrPlayer = [];
var objPicked;

$(document).ready(function() {
   arrPlayer = [{'PlayerID':3}, {'Num': '--'}, {'First': 'John'}, {'Last': 'Smith' }, {'Position': 'QB'}];

   objPicked.push(arrPlayer); //throws error

});

Download CSV using AJAX in Django – saved file contains the view content instead of the csv content

I’m dynamically generating a CSV from some content, and want to provide a message to the user and then download the file.

When using Javascript, the file that’s downloaded is the HTML of the view, and not the CSV. If I remove the javascript, the CSV is downloaded, but then there is no indication of this to the user.

How can I get the CSV when using javascript?

One thing I note is that I see a GET after the POST in my Django application log when using the javascript script.

I am following https://docs.djangoproject.com/en/4.2/howto/outputting-csv/ to generate the csv content, and got the javascript from the answer in Django cannot download docx file in ajax

This view content works when used without the javascript components – a csv file is downloaded.

def csv_report(request):
    if request.method == "POST":
        report_dates_form = AllMemberseventForm(request.POST)
        if report_dates_form.is_valid():
            start_date = report_dates_form.cleaned_data.get("start_date")
            end_date = report_dates_form.cleaned_data.get("end_date")
            events = Events.objects.filter(event_date__range=[start_date, end_date]).order_by("event_date")
            if events and len(events) > 0:
                response = HttpResponse(
                    content_type="text/csv",
                    headers={
                        "Content-Disposition": 'attachment; filename="%s"' % filename,
                        "filename": filename,
                        "event_count": len(events),
                    },
                )
                writer = csv.writer(response)
                for event in events:
                    writer.writerow(
                        [event.thing, event.otherthing, event.event_date]
                    )
                return response

My javascript in the template that the view uses is as follows. In my chrome developer tools console, the expected CSV content is shown when I log the data entry. The HTML is updated with the result content prepended below.

$('#post-form').on('submit', function(event){
    event.preventDefault();
    get_event_reports_csv();
});

function get_event_reports_csv() {
    let start_date = $('#id_start_date').val()
    let end_date = $('#id_end_date').val()
    console.log(`Getting all report for all events between ${start_date} and ${end_date}`)
    $.ajax({
        url : "/signin/event_reports/", // my view
        type : "POST", // http method
        data : { 
            start_date : $('#id_start_date').val(),
            end_date : $('#id_end_date').val(),
        }, // data sent with the post request

        // handle a successful response
        success : function(data, textStatus, request) {
            var filename = request.getResponseHeader('filename');
            var event_count = request.getResponseHeader('event_count');
            
            console.log("Request for all events report successful");
            if (event_count == 1) {
                $("#result").prepend(`There was ${event_count} events between ${start_date} and ${end_date}. The CSV file will be downloaded shortly. Please check your downloads folder.`);
            } else {
                $("#result").prepend(`There were ${event_count} events between ${start_date} and ${end_date}. The CSV file will be downloaded shortly. Please check your downloads folder.`);
            }
 
            console.log(`data: ${data}`)
            const downloadLink = document.createElement("a");
            downloadLink.href = data;
            downloadLink.download = filename;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

Convert complex excel if, else, or, and excel formulas to javascript or python, to create an app

I have a multiple complex excel formulas, like:

=SE(OU(AP15="";AP17="";AP19="";K12="";K13="";K14="";J34="";N20="");"";SE(E(AP15="Uréia";AP17="Superfosfato triplo";AP19="Cloreto de potássio");AK26+AK45+AK65;SE(E(AP15="Uréia";AP17="Superfosfato triplo";AP19="Potasil");AK26+AK45+AK66;SE(E(AP15="Uréia";AP17="Superfosfato simples";AP19="Cloreto de potássio");AK26+AK46+AK65;SE(E(AP15="Uréia";AP17="Superfosfato simples";AP19="Potasil");AK26+AK46+AK66;SE(E(AP15="Uréia";AP17="Yoorin Master";AP19="Cloreto de potássio");AK26+AK47+AK65;SE(E(AP15="Uréia";AP17="Yoorin Master";AP19="potasil");AK26+AK47+AK66;SE(E(AP15="Uréia";AP17="Yoorin Master S";AP19="Cloreto de potássio");AK26+AK48+AK65;SE(E(AP15="Uréia";AP17="Yoorin Master S";AP19="Potasil");AK26+AK48+AK66)))))))))

and

=SE(J34=0;"";SE(E(L10>400;L10<1000);SE(E(J34<3);"Muito baixo";SE(E(J34>=3;J34<7);"Baixo";SE(E(J34>=7;J34<10);"Médio";SE(E(J34>=10;J34<12);"Alto";SE(J34>=12;"Muito alto";SE(J34>60;"Condição a evitar"))))));SE(E(L10>=250;L10<400);SE(E(J34<4);"Muito baixo";SE(E(J34>=4;J34<9);"Baixo";SE(E(J34>=9;J34<13);"Médio";SE(E(J34>=13;J34<18);"Alto";SE(J34>=18;"Muito alto";SE(J34>90;"Condição a evitar"))))));SE(L10<250;SE(E(J34<6);"Muito baixo";SE(E(J34>=6;J34<13);"Baixo";SE(E(J34>=13;J34<19);"Médio";SE(E(J34>=19;J34<24);"Alto";SE(J34>=24;"Muito alto";SE(J34>120;"Condição a evitar"))))))))))

and many other. It’s a really complex file that automates soil quimical analisys.

Is possible to convert, even if 1 by 1, to a javascript or python code? Or have any other way that can i create a web app and mobile app with this excel expressions?

I search for cases like mine, don’t find a way. I expected that have a good way to convert this logical expressions into JS or even python, or a other language that turns possible create an web app and mobile app.

How to use sendEmailVerification() in firebase 9

I have been trying to use the sendEmailVerification() method in my firebase 9 app but all the tutorials/docs on the internet seem to use firebase 8 and thus have different syntax to the one used in firebase 9. Even the firebase docs seem to be outdated. Bellow is my best attempt at trying to use this method, and it does not work. To be clear the desired behavior is for a verification email to be sent and then wait for the email to be verified before proceeding to the homescreen. Currently no email is sent and when you create an account it logs you straight in. No errors are displayed either. I would be very grateful for any help provided.

  const handleCreateAccount = async () => {
    if (password == password2) {
      try {
        const { user } = await createUserWithEmailAndPassword(auth, email, password)
        await user.sendEmailVerification();
        setVerifyMessage("Verification mail sent")
      } catch (error) {
        setDisplayError(error.message)
      }
    } else {
      setDisplayError("The passwords don't match")
    }
  }

Error in passing array data to createChatCompletion ChatGPT

I am exploring chatGPT API Documentation. I created a following array and sending it to generate response from the ChatGPT API. It works fine.

But whenever I am pushing an object inside that array and then sending it to the ChatGPT API it is showing an error.

const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
  apiKey: 'Your OPENAI_API_KEY',
});

const chatGPTProvider = async () => {
  try {
    const url = 'https://api.openai.com/v1/chat/completions';

    let data = [
      { role: 'system', content: 'You are a helpful assistant.' },
      {
        role: 'user',
        content: 'Act as an intelligent AI.',
      },
    ];

    // data.push({ role: 'sytem', content: 'Hola GPT' });

    // console.log(data);

    const resp = await openai.createChatCompletion({
      model: 'gpt-3.5-turbo',
      messages: data,
    });

    return { status: 'SUCCESS', result: resp.data.choices[0].message };
  } catch (ex) {
    console.log(ex.message);

    return { status: 'ERROR', result: null };
  }
};

This code works fine. When you uncomment that push method it starts giving error.
Request failed with status code 400

Can you please tell why only pushing data into the array results in error?

Documentation: https://platform.openai.com/docs/api-reference/chat/create?lang=node.js

AngularJS – I have a different behavior when creating the carousel items with ng-repeat

I have a template that allows me to create items inside a panel with a background image and some text. Something super simple.

The initial code would be this:

<div class="container-fluid p-0 pb-5">
    <div class="owl-carousel header-carousel position-relative mb-5">


        <!-- <div class="owl-carousel-item position-relative">
            <img class="img-fluid" src="img/carousel-1.jpg" alt="">
            <div class="position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center"
                style="background: rgba(6, 3, 21, .5);">
                <div class="container">
                    <div class="row justify-content-start">
                        <div class="col-10 col-lg-8">
                            <h1 class="display-3 text-white animated slideInDown mb-4">hola</h1>
                            <p class="fs-5 fw-medium text-white mb-4 pb-2">paraffito</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="owl-carousel-item position-relative">
            <img class="img-fluid" src="img/carousel-2.jpg" alt="">
            <div class="position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center"
                style="background: rgba(6, 3, 21, .5);">
                <div class="container">
                    <div class="row justify-content-start">
                        <div class="col-10 col-lg-8">
                            <h1 class="display-3 text-white animated slideInDown mb-4">hola 2</h1>
                            <p class="fs-5 fw-medium text-white mb-4 pb-2">paraffito 2</p>
                        </div>
                    </div>
                </div>
            </div>
        </div> 
    </div>
</div>

This works perfectly, however when I transform this HTML so that the items are created based on an array that I have the behavior is different, and for some reason instead of being a single carousel, it is as if I were stacking multiple carousels with a single items in each.
This would be my HTML transformed with ng-repeat:

    <div class="container-fluid p-0 pb-5">
    <div class="owl-carousel header-carousel position-relative mb-5">

            <div ng-repeat="objetosConImagenes in objetosConImagenes" class="owl-carousel-item position-relative" >
            <img class="img-fluid" ng-src="{{objetosConImagenes.imagenUrl}}" alt="">
            <div class="position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center"
                style="background: rgba(6, 3, 21, .5);">
                <div class="container">
                    <div class="row justify-content-start">
                        <div class="col-10 col-lg-8">
                            <h1 class="display-3 text-white animated slideInDown mb-4">
                                {{objetosConImagenes.TituloPresentacion}}</h1>
                            <p class="fs-5 fw-medium text-white mb-4 pb-2">{{objetosConImagenes.DescCorta}}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>


    </div>
</div>

I don’t know if it has something to do with the problem, but I have these libraries in use.

    <!-- JavaScript Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="js/parametros.js"></script>
<script src="js/scriptv2.js"></script>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="lib/wow/wow.min.js"></script>
<!-- <script src="lib/easing/easing.min.js"></script>
<script src="lib/waypoints/waypoints.min.js"></script>-->
<script src="lib/counterup/counterup.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>

<!-- Template Javascript -->
<script src="js/main.js"></script>

What am I doing wrong? What can I do to achieve the same behavior as in the original HTML?
I know there is a Bootstrap UI for AngularJS, however I would love to keep this project simple and have it work this way.

How to stop javascript event listener from breaking a page [closed]

I have a webpage that loads elements (videos & images) through ajax that have alot of event listeners. Once too many elements are loaded through Ajax the page breaks. I am trying to find a way to keep the page from breaking.

One solution I had was to use .remove() on elements at the top of the page once a certain amount of elements were loaded. The problem with .remove() is it takes the page scroll back to the top which I can’t have. I couldn’t find a way to prevent the page going back to the top neither. Any solutions?

The page at hand is:
https://vidvast.com/pin/user_pins/

ReferenceError: SharedArrayBuffer is not defined while using ffmpeg.wasm

<!DOCTYPE html>
<html>
  <head>
    <title>TikTok Live Downloader</title>
  </head>
  <body>
    <h1>TikTok Live Downloader</h1>
      <label for="username">Username:</label>
      <input id="txt" type="text" name="username" id="username" required>
      <button type="submit">Download</button>
  </body>
<script src="ffmpeg.js"></script>
<script>
const downloadButton = document.querySelector('button[type="submit"]');
downloadButton.addEventListener('click', async () => {
const ffmpeg = FFmpeg.createFFmpeg({
     corePath: new URL('ffmpeg-core.js', document.location).href,
     workerPath: new URL('ffmpeg-core.worker.js', document.location).href,
     wasmPath: new URL('ffmpeg-core.wasm', document.location).href,
     log: true
   });
   await ffmpeg.load();
const liveUrl=document.getElementById("txt").value;
ffmpeg.run('-i', '${liveUrl}', 'c','copy','test.mp4');
const dwnLink = document.createElement('a');
dwnLink.download = `output${'test.mp4'}`;
dwnLink.href= encodedData;
dwnLink.click();
});
</script>
</html>

With the above code, I was trying to make a tiktok video downloader but I keep getting the SharedArrayBuffer error. I’m running this with node.js.

// middleware to enable SharedBuffer to be used
app.use(function(req, res, next) {
  res.header("Cross-Origin-Embedder-Policy", "require-corp");
  res.header("Cross-Origin-Opener-Policy", "same-origin");
  next();
});

I tried adding the above two lines in my app.js but still the issue persists.

How to make View Transtion for a span that will shrink and expand during one transition?

I was playing with View transition API (available in Google Chrome).

I was creating demos for my library jQuery Terminal. I make what I want with two transitions. I set the text to single space and when the transition ends I use destination transition.

JavaScript:

let id = 0;
async function animate(messages, time) {
    const messages_copy = [...messages];
    const empty = wrap(' ');
    const first = wrap(messages_copy.shift());
    if (can_animate) {
        term.echo(empty);
        index = term.last_index();
        const transition = document.startViewTransition(() => {
            term.update(index, first);
        });
        await transition.finished;
        await delay(time);
        for (const message of messages_copy) {
           term.update(index, empty);
           
            const transition = document.startViewTransition(() => {
                term.update(index, wrap(message));
            });
            await transition.finished;
            await delay(time);
        }   
    } else {
        term.echo(first);
        await delay(time);
        const index = term.last_index();
        for (const message of messages_copy) {
            term.update(index, wrap(message));
            await delay(time);
        }
    }
    ++id;
}

const wrap = message => {
    return `<text name="${id}">${message}</text>`;
};

const delay = time => new Promise(resolve => {
    setTimeout(resolve, time);
});

// formatting to diplay text with given view-transition-name name and given class
$.terminal.new_formatter([
    /<text name="([^"]+)">(.*?)</text>/g,
    '[[;;;terminal-inverted;;{"style": "view-transition-name: t_$1"}]$2]'
]);

CSS:

/* ref: https://codepen.io/argyleink/pen/ZEmLrze */
::view-transition-old(*),
::view-transition-new(*) {
    height: 100%;
    width: 100%;
}

I’ve tried this:

::view-transition-old(*) {
  animation: 0.5s transition-out 0s ease;
}

::view-transition-new(*) {
  animation: 0.5s transition-in 0s ease;
}

@keyframes transition-out {
    from {
        max-width: 100%;
    }
    to {
        max-width: 0;
    }
}

@keyframes transition-in {
    from {
        max-width: 0;
    }
    to {
        max-width: 100%;
    }
}

But this transition happens on the whole page. I want it applied only for my text like in the reference CodePen.

Here is my CodePen demo for View Transistions

The code uses jQuery Terminal but in fact, it’s not related to the library. Since I just update DOM with span and view-transition-name CSS property. But I can create simple Demo without the library, but note that the code will probably be the same only term.echo() and term.update() will change to directly update the DOM.