How to use _mergeDetails method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

project_static.js

Source: project_static.js Github

copy
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.createCiProject = exports.writeProjectId = exports.getId = exports.add = exports.remove = exports.getProjectStatus = exports.getProjectStatuses = exports._getProject = exports._mergeState = exports._mergeDetails = exports.getDashboardProjects = exports.getPathsAndIds = exports.paths = exports.getOrgs = void 0;
4const tslib_1 = require("tslib");
5const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
6const commit_info_1 = (0, tslib_1.__importDefault)(require("@cypress/commit-info"));
7const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
8const logger_1 = (0, tslib_1.__importDefault)(require("./logger"));
9const api_1 = (0, tslib_1.__importDefault)(require("./api"));
10const cache_1 = (0, tslib_1.__importDefault)(require("./cache"));
11const user_1 = (0, tslib_1.__importDefault)(require("./user"));
12const keys_1 = (0, tslib_1.__importDefault)(require("./util/keys"));
13const settings = (0, tslib_1.__importStar)(require("./util/settings"));
14const project_base_1 = require("./project-base");
15const project_utils_1 = require("./project_utils");
16const debug = (0, debug_1.default)('cypress:server:project_static');
17function getOrgs() {
18    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
19        const authToken = yield user_1.default.ensureAuthToken();
20        return api_1.default.getOrgs(authToken);
21    });
22}
23exports.getOrgs = getOrgs;
24function paths() {
25    return cache_1.default.getProjectRoots();
26}
27exports.paths = paths;
28function getPathsAndIds() {
29    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
30        const projectRoots = yield cache_1.default.getProjectRoots();
31        // this assumes that the configFile for a cached project is 'cypress.json'
32        // https://git.io/JeGyF
33        return Promise.all(projectRoots.map((projectRoot) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
34            return {
35                path: projectRoot,
36                id: yield settings.id(projectRoot),
37            };
38        })));
39    });
40}
41exports.getPathsAndIds = getPathsAndIds;
42function getDashboardProjects() {
43    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
44        const authToken = yield user_1.default.ensureAuthToken();
45        debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });
46        return api_1.default.getProjects(authToken);
47    });
48}
49exports.getDashboardProjects = getDashboardProjects;
50function _mergeDetails(clientProject, project) {
51    return lodash_1.default.extend({}, clientProject, project, { state: 'VALID' });
52}
53exports._mergeDetails = _mergeDetails;
54function _mergeState(clientProject, state) {
55    return lodash_1.default.extend({}, clientProject, { state });
56}
57exports._mergeState = _mergeState;
58function _getProject(clientProject, authToken) {
59    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
60        debug('get project from api', clientProject.id, clientProject.path);
61        try {
62            const project = yield api_1.default.getProject(clientProject.id, authToken);
63            debug('got project from api');
64            return _mergeDetails(clientProject, project);
65        }
66        catch (err) {
67            debug('failed to get project from api', err.statusCode);
68            switch (err.statusCode) {
69                case 404:
70                    // project doesn't exist
71                    return _mergeState(clientProject, 'INVALID');
72                case 403:
73                    // project exists, but user isn't authorized for it
74                    return _mergeState(clientProject, 'UNAUTHORIZED');
75                default:
76                    throw err;
77            }
78        }
79    });
80}
81exports._getProject = _getProject;
82function getProjectStatuses(clientProjects = []) {
83    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
84        debug(`get project statuses for ${clientProjects.length} projects`);
85        const authToken = yield user_1.default.ensureAuthToken();
86        debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });
87        const projects = ((yield api_1.default.getProjects(authToken)) || []);
88        debug(`got ${projects.length} projects`);
89        const projectsIndex = lodash_1.default.keyBy(projects, 'id');
90        return Promise.all(lodash_1.default.map(clientProjects, (clientProject) => {
91            debug('looking at', clientProject.path);
92            // not a CI project, just mark as valid and return
93            if (!clientProject.id) {
94                debug('no project id');
95                return _mergeState(clientProject, 'VALID');
96            }
97            const project = projectsIndex[clientProject.id];
98            if (project) {
99                debug('found matching:', project);
100                // merge in details for matching project
101                return _mergeDetails(clientProject, project);
102            }
103            debug('did not find matching:', project);
104            // project has id, but no matching project found
105            // check if it doesn't exist or if user isn't authorized
106            return _getProject(clientProject, authToken);
107        }));
108    });
109}
110exports.getProjectStatuses = getProjectStatuses;
111function getProjectStatus(clientProject) {
112    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
113        debug('get project status for client id %s at path %s', clientProject.id, clientProject.path);
114        if (!clientProject.id) {
115            debug('no project id');
116            return Promise.resolve(_mergeState(clientProject, 'VALID'));
117        }
118        const authToken = yield user_1.default.ensureAuthToken();
119        debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });
120        return _getProject(clientProject, authToken);
121    });
122}
123exports.getProjectStatus = getProjectStatus;
124function remove(path) {
125    return cache_1.default.removeProject(path);
126}
127exports.remove = remove;
128function add(path, options) {
129    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
130        // don't cache a project if a non-default configFile is set
131        // https://git.io/JeGyF
132        if (settings.configFile(options) !== 'cypress.json') {
133            return Promise.resolve({ path });
134        }
135        try {
136            yield cache_1.default.insertProject(path);
137            const id = yield getId(path);
138            return {
139                id,
140                path,
141            };
142        }
143        catch (e) {
144            return { path };
145        }
146    });
147}
148exports.add = add;
149function getId(path) {
150    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
151        const configFile = yield (0, project_utils_1.getDefaultConfigFilePath)(path);
152        return new project_base_1.ProjectBase({ projectRoot: path, testingType: 'e2e', options: { configFile } }).getProjectId();
153    });
154}
155exports.getId = getId;
156function writeProjectId({ id, projectRoot, configFile }) {
157    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
158        const attrs = { projectId: id };
159        logger_1.default.info('Writing Project ID', lodash_1.default.clone(attrs));
160        // TODO: We need to set this
161        // this.generatedProjectIdTimestamp = new Date()
162        yield settings.write(projectRoot, attrs, { configFile });
163        return id;
164    });
165}
166exports.writeProjectId = writeProjectId;
167function createCiProject(_a) {
168    var { projectRoot, configFile } = _a, projectDetails = (0, tslib_1.__rest)(_a, ["projectRoot", "configFile"]);
169    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
170        debug('create CI project with projectDetails %o projectRoot %s', projectDetails);
171        const authToken = yield user_1.default.ensureAuthToken();
172        const remoteOrigin = yield commit_info_1.default.getRemoteOrigin(projectRoot);
173        debug('found remote origin at projectRoot %o', {
174            remoteOrigin,
175            projectRoot,
176        });
177        const newProject = yield api_1.default.createProject(projectDetails, remoteOrigin, authToken);
178        yield writeProjectId({
179            configFile,
180            projectRoot,
181            id: newProject.id,
182        });
183        return newProject;
184    });
185}
186exports.createCiProject = createCiProject;
187
Full Screen

m3u8-live.js

Source: m3u8-live.js Github

copy
1import { F, Logger, Task, Maybe, Tick } from 'vod-fp-utility';
2import { ACTION, PROCESS } from '../store';
3import { loadResource } from './playlist';
4import { updateMediaDuration } from '../media/media';
5import { getBufferInfo } from '../buffer/buffer-helper';
6const { curry, prop } = F;
7let logger = new Logger('player');
8
9/**
10 *  [0,1,1] -> [0,1,0]
11    [0,1,1,2,2,2,3] -> [0,1,0,2,0,0,3]
12    [1,1,1,2,2] -> [1,0,0,2,0]
13 */
14function _convertCC(segments) {
15  if (!segments || !segments.length) return segments;
16  let newCC = segments[0].cc;
17  for (let i = 1; i < segments.length; i++) {
18    if (segments[i].cc !== newCC) {
19      newCC = segments[i].cc;
20    } else {
21      segments[i].cc = 0;
22    }
23  }
24  return segments;
25}
26
27/**
28 * live merge playlist conditions:
29 * 1. current details sn [3,5], new details sn [2,4]
30       current details sn [3,5], new details sn [3,5]
31       current details sn [3,5], new details sn [4,6]
32       current details sn [3,5], new details sn [7,9]
33 2. last level 2,details sn [10,13]     level changed to 3
34    level 3 detaisl sn [3,6],flushed new details [9,12]、[10,13]、[11,14]
35 *
36 * @param {*} param0
37 * @param {*} levelId the current used level
38 * @param {*} newDetails
39 */
40function mergePlaylist({ getState, dispatch, connect }, levelId, newDetails) {
41  let noNews = false;
42
43  getState(ACTION.PLAYLIST.FIND_LEVEL, levelId).map(level => {
44    let { detail } = level;
45    let oldStartSN = detail.startSN;
46    let oldEndSN = detail.endSN;
47    let oldSegments = detail.segments;
48    let newSegments = _convertCC(newDetails.segments);
49    let { startSN, endSN } = newDetails;
50    let delta = startSN - oldStartSN;
51    let lastSegment;
52    let lastCC = 0;
53
54    noNews = oldStartSN === startSN && oldEndSN === endSN;
55
56    logger.log(
57      `merge level ${newDetails.levelId} details with levelId ${levelId},[${oldStartSN},${oldEndSN}] -> [${startSN},${endSN}]`
58    );
59
60    let overlap =
61      (startSN >= oldStartSN && startSN <= oldEndSN) ||
62      (oldStartSN >= startSN && oldStartSN <= endSN);
63
64    if (!overlap) {
65      getState(ACTION.PLAYLIST.FIND_LAST_LEVEL)
66        .map(prop('detail'))
67        .map(prop('segments'))
68        .map(olds => {
69          oldSegments = olds;
70          logger.log(`use last level ${olds.levelId} to sync new details`);
71        });
72    }
73
74    let result = _mergeDetails(oldSegments, newSegments);
75    logger.warn(
76      `new levels index=${result.newIndex} match old levels index=${result.oldIndex}`
77    );
78
79    for (let i = 0; i < newSegments.length; i++) {
80      let newSeg = newSegments[i];
81      if (newSeg.cc) {
82        lastCC++;
83      }
84      newSeg.cc = lastCC;
85      newSeg.levelId = levelId;
86      newSeg.lowestLevel = levelId === 1;
87      if (i > result.newIndex) {
88        newSeg.start = newSeg.origStart = newSegments[i - 1].end;
89        newSeg.end = newSeg.origEnd = newSeg.start + newSeg.duration;
90      }
91      if (oldSegments.map(x => x.id).indexOf(newSeg.id) === -1) {
92        oldSegments.push(newSeg);
93      }
94    }
95
96    oldSegments = oldSegments.filter(x => x.id >= startSN);
97    if (!oldSegments.length) return;
98    let first = oldSegments[0];
99    let last = oldSegments[oldSegments.length - 1];
100    detail.segments = oldSegments;
101    detail.startSN = first.id;
102    detail.endSN = last.id;
103    detail.mediaSequence = detail.startSN;
104    detail.live = detail.live;
105    detail.duration = Math.max(
106      detail.duration,
107      last.end,
108      connect(getBufferInfo)(last.end).bufferEnd
109    );
110    dispatch(ACTION.PLAYLIST.UPDATE_LEVEL, { levelId, detail });
111    dispatch(ACTION.CONFIG.MAX_BUFFER_LENGTH, newDetails.duration);
112    dispatch(ACTION.CONFIG.MAX_FLY_BUFFER_LENGTH, newDetails.duration);
113    connect(updateMediaDuration);
114    logger.log(
115      `slide position:${first.start} , `,
116      `segments rangs: [${first.start},${last.end}]`
117    );
118  });
119  return noNews;
120}
121
122function _mergeDetails(oldSegments, newSegments) {
123  let s;
124  let oldIds = oldSegments.map(x => x.id);
125  let newIds = newSegments.map(x => x.id);
126  let deltas = newIds
127    .map((id, index) => {
128      return oldIds
129        .map((oldId, oldIndex) => {
130          return {
131            newIndex: index,
132            oldIndex,
133            delta: id - oldId
134          };
135        })
136        .filter(x => x.delta === 0);
137    })
138    .filter(x => x.length);
139
140  if (deltas.length && deltas[0].length) {
141    let matched = deltas[0][0];
142    s = newSegments[matched.newIndex];
143    s.start = oldSegments[matched.oldIndex].start;
144    s.end = s.start + s.duration;
145    return matched;
146  }
147
148  let oldNb = oldSegments.length - 1;
149  s = newSegments[0];
150  s.start = oldSegments[oldNb].start;
151  s.end = s.start + s.duration;
152  logger.warn(
153    `no overlap between two level,assume they are aligned,set segment.id = ${s.id} start`
154  );
155  return {
156    newIndex: 0,
157    oldIndex: oldNb
158  };
159}
160
161function bootStrapFlushPlaylist({ getState, dispatch, getConfig, connect }) {
162  let flushTask;
163  let factor = getConfig(ACTION.CONFIG.LIVE_FLUSH_INTERVAL_FACTOR);
164  let interval = getState(ACTION.PLAYLIST.AVG_SEG_DURATION)
165    .map(duration => duration * factor * 1000 || undefined)
166    .getOrElse(1000);
167
168  function _flushPlaylist(nextTick) {
169    Maybe.of(
170      curry((levelUrl, currentLevelId) => {
171        let tsStart = performance.now();
172        connect(loadResource)('LEVEL', levelUrl)
173          .map(details => {
174            let segsNb = details.segments.length;
175            let noNews = connect(mergePlaylist)(currentLevelId, details);
176            interval = details.targetduration * 1000 || interval;
177
178            if (!details.live) {
179              // end of live
180              flushTask.destroy();
181              return;
182            }
183
184            let time = interval - performance.now() + tsStart;
185            time = time / (noNews ? 2 : 1);
186
187            logger.log(`m3u8  flush after ${time} ms`);
188            nextTick(time);
189          })
190          .error(e => {
191            if (e.fatal()) {
192              flushTask.destroy();
193              dispatch(ACTION.ERROR, e);
194            }
195          });
196      })
197    )
198      .ap(getState(ACTION.PLAYLIST.GET_LEVEL_URL))
199      .ap(getState(ACTION.PLAYLIST.CURRENT_LEVEL_ID));
200  }
201
202  flushTask = Tick.of()
203    .addTask(_flushPlaylist)
204    .interval(interval)
205    .immediateRun();
206  dispatch(ACTION.PLAYLIST.FLUSH_TASK, flushTask);
207}
208
209function _caclLiveSyncPosition({ getState, getConfig }) {
210  return Maybe.of(
211    curry((segs, duration) => {
212      let segsTotalDuration = segs.map(prop('duration')).reduce((all, c) => {
213        all += c;
214        return all;
215      }, 0);
216      return (
217        duration -
218        segsTotalDuration * getConfig(ACTION.CONFIG.LIVE_LATENCY_FACTOR)
219      );
220    })
221  )
222    .ap(getState(ACTION.PLAYLIST.SEGMENTS))
223    .ap(getState(ACTION.PLAYLIST.DURATION));
224}
225
226// number -> number when break away,nothing when not
227function checkSyncLivePosition({ getState, connect, dispatch }, bufferEnd) {
228  return Maybe.of(
229    curry((_, slidePosition) => {
230      //check the current play time is break away from the live point
231      if (bufferEnd < slidePosition) {
232        logger.log('bufferEnd:', bufferEnd, 'slidePosition:', slidePosition);
233        return connect(_caclLiveSyncPosition).chain(liveSyncPostion => {
234          logger.log(
235            'break away from the live point,sync position',
236            liveSyncPostion,
237            'bufferEnd: ',
238            bufferEnd
239          );
240          dispatch(ACTION.BUFFER.LIVE_LOAD_POINT, liveSyncPostion);
241          return liveSyncPostion;
242        });
243      }
244    })
245  )
246    .ap(getState(ACTION.PLAYLIST.IS_LIVE))
247    .ap(getState(ACTION.PLAYLIST.SLIDE_POSITION))
248    .getOrElse(() => {
249      dispatch(ACTION.BUFFER.LIVE_LOAD_POINT, -1);
250    });
251}
252
253// in ts live,check the current time break away from live windows then need to
254// seek to the new buffer area
255function checkSeekAfterBufferAppend({ getState }, segBound) {
256  Maybe.of(
257    curry((_, bufferInfo, slidePosition, media) => {
258      if (bufferInfo.bufferEnd < slidePosition) {
259        logger.log('media seeking to', segBound.start);
260        media.currentTime = segBound.start;
261      }
262    })
263  )
264    .ap(getState(ACTION.PLAYLIST.IS_LIVE))
265    .ap(getState(ACTION.BUFFER.GET_BUFFER_INFO))
266    .ap(getState(ACTION.PLAYLIST.SLIDE_POSITION))
267    .ap(getState(ACTION.MEDIA.MEDIA_ELE));
268}
269
270mergePlaylist = curry(mergePlaylist);
271bootStrapFlushPlaylist = curry(bootStrapFlushPlaylist);
272checkSyncLivePosition = curry(checkSyncLivePosition);
273checkSeekAfterBufferAppend = curry(checkSeekAfterBufferAppend);
274
275export {
276  mergePlaylist,
277  bootStrapFlushPlaylist,
278  checkSyncLivePosition,
279  checkSeekAfterBufferAppend
280};
281
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)