Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/client/lib/ScriptInstance.ts
1028 views
1
import { v1 as uuidv1 } from 'uuid';
2
import IScriptInstanceMeta from '@secret-agent/interfaces/IScriptInstanceMeta';
3
import Log from '@secret-agent/commons/Logger';
4
import CoreSession from './CoreSession';
5
6
const { log } = Log(module);
7
8
export default class ScriptInstance {
9
public readonly id: string = uuidv1();
10
public readonly entrypoint = require.main?.filename ?? process.argv[1];
11
public readonly startDate = new Date().getTime();
12
private sessionNameCountByName: { [name: string]: number } = {};
13
14
public get meta(): IScriptInstanceMeta {
15
return {
16
id: this.id,
17
entrypoint: this.entrypoint,
18
startDate: this.startDate,
19
};
20
}
21
22
public async launchReplay(session: CoreSession): Promise<void> {
23
// eslint-disable-next-line global-require
24
const { replay } = require('@secret-agent/replay/index');
25
try {
26
await replay({
27
scriptInstanceId: this.id,
28
scriptStartDate: this.startDate,
29
sessionsDataLocation: session.sessionsDataLocation,
30
replayApiUrl: await session.replayApiUrl,
31
sessionId: session.sessionId,
32
sessionName: session.sessionName,
33
});
34
} catch (error) {
35
log.warn('Error launching Replay application', { sessionId: session.sessionId, error });
36
}
37
}
38
39
public generateSessionName(name: string, shouldCleanName = true): string {
40
if (name && shouldCleanName) {
41
name = cleanupSessionName(name);
42
}
43
name = name || 'default-session';
44
45
this.sessionNameCountByName[name] = this.sessionNameCountByName[name] || 0;
46
const countPlusOne = this.sessionNameCountByName[name] + 1;
47
if (countPlusOne > 1) {
48
const newName = `${name}-${countPlusOne}`;
49
if (this.sessionNameCountByName[newName]) {
50
return this.generateSessionName(newName, false);
51
}
52
this.sessionNameCountByName[name] += 1;
53
return newName;
54
}
55
this.sessionNameCountByName[name] += 1;
56
return name;
57
}
58
}
59
60
function cleanupSessionName(name: string): string {
61
return name
62
.toLowerCase()
63
.replace(/[^a-z0-9-]+/gi, '-')
64
.replace(/--/g, '')
65
.replace(/^-|-$/g, '');
66
}
67
68