From d3307204411441a4e4f13b35de66fd287f9160df Mon Sep 17 00:00:00 2001 From: Suhail Kakar Date: Mon, 15 Jul 2024 19:36:08 +0530 Subject: [PATCH] api: rephrase error message (#2264) * api: rephrase error message * ci: run prettier on whole codebase * ci: run prettier * fix styling issue * prettier --- packages/api/src/app-router.ts | 14 +- packages/api/src/app/stream-info/parse-cli.ts | 2 +- .../src/app/stream-info/stream-info-app.ts | 6 +- packages/api/src/compile-schemas.js | 4 +- .../src/controllers/access-control.test.ts | 4 +- .../api/src/controllers/access-control.ts | 46 +-- packages/api/src/controllers/admin.js | 2 +- packages/api/src/controllers/api-token.js | 2 +- .../api/src/controllers/api-token.test.js | 2 +- packages/api/src/controllers/asset.test.ts | 42 +-- packages/api/src/controllers/asset.ts | 128 ++++----- packages/api/src/controllers/auth.test.ts | 50 ++-- packages/api/src/controllers/auth.ts | 6 +- packages/api/src/controllers/broadcaster.js | 2 +- packages/api/src/controllers/clip.ts | 30 +- packages/api/src/controllers/compose-m3u8.js | 4 +- .../src/controllers/compose-m3u8.test-data.js | 4 +- .../api/src/controllers/compose-m3u8.test.js | 8 +- .../api/src/controllers/experiment.test.ts | 12 +- packages/api/src/controllers/experiment.ts | 12 +- .../experiment/attestation.test.ts | 4 +- .../src/controllers/experiment/attestation.ts | 12 +- .../experiment/lit-signing-condition.ts | 6 +- .../api/src/controllers/generate-keys.test.ts | 4 +- packages/api/src/controllers/generate-keys.ts | 4 +- packages/api/src/controllers/helpers.test.ts | 52 ++-- packages/api/src/controllers/helpers.ts | 48 ++-- packages/api/src/controllers/ingest.js | 2 +- packages/api/src/controllers/live-proxy.js | 2 +- .../api/src/controllers/multistream.test.ts | 16 +- packages/api/src/controllers/multistream.ts | 16 +- .../api/src/controllers/object-store.test.js | 10 +- packages/api/src/controllers/object-store.ts | 10 +- packages/api/src/controllers/orchestrator.ts | 2 +- packages/api/src/controllers/playback.test.ts | 8 +- packages/api/src/controllers/playback.ts | 28 +- packages/api/src/controllers/project.ts | 4 +- packages/api/src/controllers/region.js | 8 +- packages/api/src/controllers/region.test.js | 2 +- packages/api/src/controllers/room.test.ts | 14 +- packages/api/src/controllers/room.ts | 38 +-- packages/api/src/controllers/session.ts | 24 +- .../api/src/controllers/signing-key.test.ts | 10 +- packages/api/src/controllers/signing-key.ts | 20 +- packages/api/src/controllers/stream-proxy.js | 2 +- packages/api/src/controllers/stream.test.ts | 104 +++---- packages/api/src/controllers/stream.ts | 262 +++++++++--------- packages/api/src/controllers/stripe.test.ts | 20 +- packages/api/src/controllers/stripe.ts | 58 ++-- packages/api/src/controllers/task.ts | 30 +- packages/api/src/controllers/transcode.ts | 4 +- packages/api/src/controllers/usage.ts | 48 ++-- packages/api/src/controllers/user.test.ts | 26 +- packages/api/src/controllers/user.ts | 126 ++++----- .../api/src/controllers/utils/notification.ts | 12 +- packages/api/src/controllers/webhook-log.ts | 4 +- packages/api/src/controllers/webhook.test.ts | 10 +- packages/api/src/controllers/webhook.ts | 10 +- packages/api/src/controllers/wowza-hydrate.js | 4 +- packages/api/src/hash.js | 4 +- packages/api/src/index.ts | 6 +- packages/api/src/jobs/active-cleanup.test.ts | 14 +- packages/api/src/jobs/active-cleanup.ts | 6 +- .../api/src/jobs/create-db-tables.test.ts | 2 +- packages/api/src/jobs/create-db-tables.ts | 2 +- packages/api/src/jobs/index.ts | 6 +- packages/api/src/jobs/update-usage.ts | 8 +- packages/api/src/logger.js | 2 +- packages/api/src/middleware/auth.test.ts | 44 +-- packages/api/src/middleware/auth.ts | 20 +- packages/api/src/middleware/geolocate.js | 2 +- .../api/src/middleware/hardcoded-nodes.ts | 2 +- packages/api/src/middleware/subgraph.ts | 2 +- packages/api/src/middleware/tracking.ts | 6 +- packages/api/src/parse-cli.ts | 10 +- packages/api/src/schema/api-schema.yaml | 2 +- packages/api/src/store/asset-table.test.ts | 2 +- packages/api/src/store/asset-table.ts | 18 +- packages/api/src/store/cache.ts | 2 +- .../api/src/store/cloudflare-cluster-store.js | 2 +- packages/api/src/store/cloudflare-store.js | 4 +- packages/api/src/store/db.ts | 20 +- .../api/src/store/experiment-table.test.ts | 6 +- packages/api/src/store/experiment-table.ts | 8 +- packages/api/src/store/firestore-store.js | 2 +- .../api/src/store/firestore-store.test.js | 6 +- packages/api/src/store/index.ts | 2 +- packages/api/src/store/model.ts | 2 +- packages/api/src/store/multistream-table.ts | 2 +- packages/api/src/store/queue.test.ts | 12 +- packages/api/src/store/queue.ts | 58 ++-- packages/api/src/store/session-table.ts | 4 +- packages/api/src/store/stream-table.ts | 38 +-- packages/api/src/store/table.ts | 26 +- packages/api/src/store/task-table.ts | 4 +- packages/api/src/store/webhook-table.ts | 8 +- packages/api/src/task/scheduler.ts | 42 +-- packages/api/src/test-helpers.ts | 12 +- packages/api/src/types/common.d.ts | 14 +- packages/api/src/util.ts | 17 +- packages/api/src/webhooks/cannon.test.ts | 20 +- packages/api/src/webhooks/cannon.ts | 94 +++---- packages/api/src/worker.js | 10 +- .../Admin/AdminObjectStoreTable/index.tsx | 6 +- .../Admin/AdminStreamsTable/index.tsx | 6 +- .../Admin/AdminTokenTable/index.tsx | 4 +- .../Admin/AdminWebhooksTable/index.tsx | 6 +- .../Admin/CommonAdminTable/index.tsx | 4 +- .../Admin/StreamSessionsTable/index.tsx | 10 +- .../components/Admin/StreamsTable/index.tsx | 6 +- .../Admin/Table-v2/filters/index.tsx | 4 +- .../www/components/Admin/Table-v2/index.tsx | 6 +- .../www/components/Admin/Table-v2/types.ts | 6 +- .../www/components/Admin/UserTable/index.tsx | 6 +- packages/www/components/ApiKeys/CorsCell.tsx | 2 +- .../www/components/ApiKeys/CreateDialog.tsx | 2 +- packages/www/components/ApiKeys/helpers.tsx | 4 +- packages/www/components/ApiKeys/index.tsx | 2 +- .../AssetDetails/AssetDetailsBox.tsx | 4 +- .../AssetDetails/AssetEventLogTab.tsx | 26 +- .../CreateAssetDialog/AssetsUploadError.tsx | 2 +- .../AssetsTable/CreateAssetDialog/index.tsx | 6 +- .../www/components/AssetsTable/helpers.tsx | 8 +- packages/www/components/AssetsTable/index.tsx | 4 +- packages/www/components/Breadcrumbs/index.tsx | 4 +- .../www/components/ContactDialog/index.tsx | 2 +- .../www/components/FeaturesModel/index.tsx | 2 +- packages/www/components/FileUpload/helpers.ts | 8 +- packages/www/components/FileUpload/index.tsx | 4 +- packages/www/components/Logger/index.tsx | 14 +- .../components/PastInvoicesTable/index.tsx | 2 +- packages/www/components/Plans/index.tsx | 4 +- packages/www/components/Sidebar/index.tsx | 4 +- .../SigningKeysTable/DeleteKeysDialog.tsx | 4 +- .../components/SigningKeysTable/helpers.tsx | 4 +- .../www/components/SigningKeysTable/index.tsx | 4 +- .../HealthChecksTable/helpers.tsx | 2 +- .../StreamDetails/HealthChecksTable/index.tsx | 17 +- .../SaveTargetDialog.tsx | 16 +- .../TargetStatusBadge.tsx | 6 +- .../MultistreamTargetsTable/Toolbox.tsx | 8 +- .../MultistreamTargetsTable/helpers.tsx | 4 +- .../MultistreamTargetsTable/index.tsx | 10 +- .../StreamDetails/SessionsTable/ClipsCell.tsx | 2 +- .../StreamDetails/SessionsTable/helpers.tsx | 8 +- .../StreamDetails/SessionsTable/index.tsx | 4 +- .../StreamDetails/StreamHealthTab.tsx | 8 +- .../StreamDetails/StreamOverviewBox.tsx | 2 +- .../StreamDetails/StreamPlayerBox/index.tsx | 4 +- .../StreamSessionsTable/DeleteDialog.tsx | 2 +- .../StreamSessionsTable/helpers.tsx | 6 +- .../components/StreamSessionsTable/index.tsx | 4 +- .../components/StreamsTable/StreamFilter.tsx | 2 +- .../www/components/StreamsTable/helpers.tsx | 2 +- .../www/components/StreamsTable/index.tsx | 10 +- .../components/TableStateDeleteDialog.tsx | 2 +- .../www/components/Table/filters/index.tsx | 18 +- packages/www/components/Table/index.tsx | 12 +- packages/www/components/Table/types.ts | 6 +- .../components/UpcomingInvoiceTable/index.tsx | 2 +- .../www/components/UsageSummary/index.tsx | 18 +- .../WebhookDetails/LogsContainer.tsx | 6 +- .../www/components/WebhookDetails/index.tsx | 4 +- .../www/components/WebhooksTable/helpers.tsx | 4 +- .../www/components/WebhooksTable/index.tsx | 4 +- packages/www/css/markdown.css | 30 +- packages/www/hooks/use-analyzer.tsx | 4 +- .../hooks/use-api/endpoints/accessControl.ts | 6 +- .../www/hooks/use-api/endpoints/apiToken.ts | 8 +- packages/www/hooks/use-api/endpoints/asset.ts | 18 +- .../hooks/use-api/endpoints/broadcaster.ts | 2 +- packages/www/hooks/use-api/endpoints/clip.ts | 4 +- packages/www/hooks/use-api/endpoints/data.ts | 2 +- .../www/hooks/use-api/endpoints/ingest.ts | 2 +- .../hooks/use-api/endpoints/multistream.ts | 8 +- .../hooks/use-api/endpoints/objectStore.ts | 8 +- .../www/hooks/use-api/endpoints/project.ts | 2 +- .../www/hooks/use-api/endpoints/session.ts | 8 +- .../www/hooks/use-api/endpoints/stream.ts | 20 +- packages/www/hooks/use-api/endpoints/task.ts | 6 +- packages/www/hooks/use-api/endpoints/user.ts | 34 +-- .../www/hooks/use-api/endpoints/version.ts | 2 +- .../www/hooks/use-api/endpoints/webhook.ts | 10 +- packages/www/hooks/use-api/index.tsx | 2 +- packages/www/hooks/use-debounce.tsx | 2 +- packages/www/hooks/use-drag.tsx | 2 +- packages/www/hooks/use-hubspot.tsx | 2 +- packages/www/hooks/use-logged-in.tsx | 2 +- packages/www/layouts/assetDetail.tsx | 2 +- packages/www/layouts/streamDetail.tsx | 6 +- packages/www/lib/utils/index.tsx | 13 +- packages/www/lib/utils/router.ts | 4 +- packages/www/next.config.js | 4 +- packages/www/pages/_app.tsx | 2 +- packages/www/pages/app/stream/[id].tsx | 8 +- .../[projectId]/assets/[id]/index.tsx | 6 +- .../[projectId]/developers/webhooks/[id].tsx | 4 +- .../www/pages/projects/[projectId]/index.tsx | 2 +- .../projects/[projectId]/stream-health.tsx | 4 +- .../[projectId]/streams/[id]/index.tsx | 4 +- packages/www/pages/settings/billing/index.tsx | 18 +- packages/www/pages/settings/usage/index.tsx | 12 +- packages/www/pages/verify-new-email.tsx | 2 +- packages/www/pages/verify.tsx | 2 +- 204 files changed, 1315 insertions(+), 1352 deletions(-) diff --git a/packages/api/src/app-router.ts b/packages/api/src/app-router.ts index f7c15c0ba8..1b17f8401e 100644 --- a/packages/api/src/app-router.ts +++ b/packages/api/src/app-router.ts @@ -80,7 +80,7 @@ export async function initDb(params: CliArgs, serviceName = "api") { ...pgBaseParams, poolMaxSize: pgJobsPoolSize, appName: `${appName}-jobs`, - }, + } ); return { db, jobsDb, store }; } @@ -111,7 +111,7 @@ export async function initClients(params: CliArgs, serviceName = "api") { if (!stripeSecretKey) { console.warn( - "Warning: Missing Stripe API key. In development, make sure to configure one in .env.local file.", + "Warning: Missing Stripe API key. In development, make sure to configure one in .env.local file." ); } const stripe = stripeSecretKey @@ -155,7 +155,7 @@ export default async function appRouter(params: CliArgs) { if (supportAddr || sendgridTemplateId || sendgridApiKey) { if (!(supportAddr && sendgridTemplateId && sendgridApiKey)) { throw new Error( - `Sending emails requires supportAddr, sendgridTemplateId, and sendgridApiKey`, + `Sending emails requires supportAddr, sendgridTemplateId, and sendgridApiKey` ); } } @@ -220,7 +220,7 @@ export default async function appRouter(params: CliArgs) { exposedHeaders: ["*"], }, }, - }), + }) ); // stripe webhook requires raw body @@ -241,7 +241,7 @@ export default async function appRouter(params: CliArgs) { if (returnRegionInOrchestrator) { app.use((req, res, next) => { req.orchestratorsGetters.push(() => - regionsGetter(halfRegionOrchestratorsUntrusted), + regionsGetter(halfRegionOrchestratorsUntrusted) ); return next(); }); @@ -251,7 +251,7 @@ export default async function appRouter(params: CliArgs) { app.use( subgraph({ subgraphUrl, - }), + }) ); } @@ -261,7 +261,7 @@ export default async function appRouter(params: CliArgs) { prefixRouter.get( "/stream/:streamId/broadcaster", geolocateMiddleware({}), - getBroadcasterHandler, + getBroadcasterHandler ); for (const [name, controller] of Object.entries(controllers)) { // if we're operating in api-region mode, only handle geolocation traffic, forward the rest on diff --git a/packages/api/src/app/stream-info/parse-cli.ts b/packages/api/src/app/stream-info/parse-cli.ts index 22f2c5f1da..e17da9a281 100644 --- a/packages/api/src/app/stream-info/parse-cli.ts +++ b/packages/api/src/app/stream-info/parse-cli.ts @@ -12,7 +12,7 @@ export function parseCli() { Options my also be provided as LP_API_ prefixed environment variables, e.g. LP_API_PORT=5000 is the same as --port=5000. - `, + ` ) .env("LP_API_") //.strict(true) diff --git a/packages/api/src/app/stream-info/stream-info-app.ts b/packages/api/src/app/stream-info/stream-info-app.ts index 5f6240ecb2..64bf743bd6 100644 --- a/packages/api/src/app/stream-info/stream-info-app.ts +++ b/packages/api/src/app/stream-info/stream-info-app.ts @@ -200,7 +200,7 @@ class statusPoller { if (si.stream?.id !== getStreamId(mid)) { console.log( - `stream id changed from ${si.stream?.id} to ${getStreamId(mid)}`, + `stream id changed from ${si.stream?.id} to ${getStreamId(mid)}` ); // save the old stream info so it's properly housekept later this.seenStreams.set(`old_${mid}_${si.stream?.id}`, si); @@ -266,7 +266,7 @@ class statusPoller { private async housekeepSeenStreams( activeStreams?: MasterPlaylistDictionary, - force?: boolean, + force?: boolean ) { for (const [mid, si] of this.seenStreams) { if (activeStreams && mid in activeStreams) { @@ -395,7 +395,7 @@ export default async function makeApp(params: CliArgs) { .listen(port, () => { listenPort = listener.address().port; logger.info( - `Stream info server listening on http://0.0.0.0:${listenPort}`, + `Stream info server listening on http://0.0.0.0:${listenPort}` ); resolve(); }) diff --git a/packages/api/src/compile-schemas.js b/packages/api/src/compile-schemas.js index bd02d1078d..74425a271e 100644 --- a/packages/api/src/compile-schemas.js +++ b/packages/api/src/compile-schemas.js @@ -31,11 +31,11 @@ fs.ensureDirSync(schemaDistDir); const apiSchemaStr = fs.readFileSync( path.resolve(schemaDir, "api-schema.yaml"), - "utf8", + "utf8" ); const dbSchemaStr = fs.readFileSync( path.resolve(schemaDir, "db-schema.yaml"), - "utf8", + "utf8" ); const apiData = parseYaml(apiSchemaStr); const dbData = parseYaml(dbSchemaStr); diff --git a/packages/api/src/controllers/access-control.test.ts b/packages/api/src/controllers/access-control.test.ts index 3030f09321..440025540f 100644 --- a/packages/api/src/controllers/access-control.test.ts +++ b/packages/api/src/controllers/access-control.test.ts @@ -323,7 +323,7 @@ describe("controllers/access-control", () => { expect(res3.status).toBe(403); let resJson = await res3.json(); expect(resJson.errors[0]).toBe( - `Content is gated and origin not in allowed origins`, + `Content is gated and origin not in allowed origins` ); const res4 = await client.post("/access-control/gate", { stream: `video+${gatedAsset.playbackId}`, @@ -338,7 +338,7 @@ describe("controllers/access-control", () => { expect(res4.status).toBe(403); let resJson2 = await res4.json(); expect(resJson2.errors[0]).toBe( - "Content is gated and corresponding public key not found", + "Content is gated and corresponding public key not found" ); }); diff --git a/packages/api/src/controllers/access-control.ts b/packages/api/src/controllers/access-control.ts index fc27537bde..e544c668ba 100644 --- a/packages/api/src/controllers/access-control.ts +++ b/packages/api/src/controllers/access-control.ts @@ -42,7 +42,7 @@ type GateConfig = { async function fireGateWebhook( webhook: DBWebhook, content: DBStream | WithID, - payload: AccessControlGatePayload, + payload: AccessControlGatePayload ) { let timestamp = Date.now(); let jsonPayload = { @@ -75,7 +75,7 @@ async function fireGateWebhook( const sigHeaders = signatureHeaders( params.body, webhook.sharedSecret, - timestamp, + timestamp ); params.headers = { ...params.headers, ...sigHeaders }; @@ -113,7 +113,7 @@ async function fireGateWebhook( timestamp, statusCode, errorMessage, - undefined, + undefined ); } if ("pull" in content && content.pull) { @@ -129,26 +129,26 @@ async function fireGateWebhook( `access-control: gate: webhook=${ webhook.id } statusCode=${statusCode} respSpanId=${resp?.headers.get( - "X-Tlive-Spanid", + "X-Tlive-Spanid" )} respBody=${Buffer.from(respBody).toString("base64")} duration=${ process.hrtime(startTime)[1] / 1e6 }ms accessKey=${payload.accessKey} playbackId=${ content.playbackId } webhook=${ webhook.id - } referer=${referer} origin=${origin} playURL=${playURL} playDomain=${playDomain}`, + } referer=${referer} origin=${origin} playURL=${playURL} playDomain=${playDomain}` ); } catch (e) { console.log( `access-control: gate: webhook=${ webhook.id } statusCode=${statusCode} respSpanId=${resp?.headers.get( - "X-Tlive-Spanid", + "X-Tlive-Spanid" )} respBody=${Buffer.from(respBody).toString("base64")} duration=${ process.hrtime(startTime)[1] / 1e6 }ms accessKey=${payload.accessKey} playbackId=${ content.playbackId - } webhook=${webhook.id}`, + } webhook=${webhook.id}` ); } } else { @@ -157,7 +157,7 @@ async function fireGateWebhook( webhook.id } statusCode=${statusCode} duration=${ process.hrtime(startTime)[1] / 1e6 - }ms`, + }ms` ); } return statusCode; @@ -172,7 +172,7 @@ function checkRespBody(resp: string): number | null { return body.ret; } catch (e) { console.log( - `access-control: error checking response body for status code: ${e}`, + `access-control: error checking response body for status code: ${e}` ); } } @@ -192,7 +192,7 @@ app.post( (await db.stream.getByPlaybackId(playbackId)) || (await db.asset.getByPlaybackId(playbackId)) ); - }, + } ); res.set("Cache-Control", "max-age=120,stale-while-revalidate=600"); @@ -261,7 +261,7 @@ app.post( if (origin === "null" || origin === "") { origin = referer; console.log( - `access-control: gate: origin is null, using referer=${origin} for playbackId=${playbackId}`, + `access-control: gate: origin is null, using referer=${origin} for playbackId=${playbackId}` ); } @@ -279,7 +279,7 @@ app.post( access-control: gate: content with playbackId=${playbackId} is gated but origin=${origin} not in allowed origins=${allowedOrigins}, disallowing playback `); throw new ForbiddenError( - `Content is gated and origin not in allowed origins`, + `Content is gated and origin not in allowed origins` ); } } @@ -296,7 +296,7 @@ app.post( access-control: gate: no pub provided for playbackId=${playbackId}, disallowing playback `); throw new ForbiddenError( - "Content is gated and requires a public key", + "Content is gated and requires a public key" ); } @@ -307,7 +307,7 @@ app.post( sql`signing_key.data->>'publicKey' = ${req.body.pub}`, ]; return db.signingKey.find(query, { limit: 2 }); - }, + } ); if (signingKeyOutput.length == 0) { @@ -315,7 +315,7 @@ app.post( access-control: gate: content with playbackId=${playbackId} is gated but corresponding public key not found for key=${req.body.pub}, disallowing playback `); throw new ForbiddenError( - "Content is gated and corresponding public key not found", + "Content is gated and corresponding public key not found" ); } @@ -325,7 +325,7 @@ app.post( access-control: gate: content contentId=${content.id} with playbackId=${playbackId} is gated but multiple (${signingKeyOutput.length}) public keys found for key=${req.body.pub}, disallowing playback, colliding keys=${collisionKeys} `); throw new BadRequestError( - "Multiple signing keys found for the same public key.", + "Multiple signing keys found for the same public key." ); } @@ -352,7 +352,7 @@ app.post( case "webhook": if (!req.body.accessKey || req.body.type !== "accessKey") { throw new ForbiddenError( - "Content is gated and requires an access key", + "Content is gated and requires an access key" ); } const webhook = await db.webhook.get(content.playbackPolicy.webhookId, { @@ -363,7 +363,7 @@ app.post( access-control: gate: content with playbackId=${playbackId} is gated but corresponding webhook not found for webhookId=${content.playbackPolicy.webhookId}, disallowing playback `); throw new InternalServerError( - "Content is gated and corresponding webhook not found", + "Content is gated and corresponding webhook not found" ); } @@ -379,22 +379,22 @@ app.post( access-control: gate: content with playbackId=${playbackId} is gated but webhook=${webhook.id} failed, disallowing playback `); throw new BadGatewayError( - "Content is gated and corresponding webhook failed", + "Content is gated and corresponding webhook failed" ); } else { console.log(` access-control: gate: content with playbackId=${playbackId} is gated but webhook=${webhook.id} returned status code ${statusCode}, disallowing playback `); throw new ForbiddenError( - "Content is gated and corresponding webhook failed", + "Content is gated and corresponding webhook failed" ); } default: throw new BadRequestError( - `unknown playbackPolicy type: ${playbackPolicyType}`, + `unknown playbackPolicy type: ${playbackPolicyType}` ); } - }, + } ); app.get("/public-key", async (req, res) => { @@ -414,7 +414,7 @@ app.get("/public-key", async (req, res) => { return response.json(); } else { throw new Error( - `access-control: error retrieving public key from catalyst statusCode=${response.status} catalystUrl=${url}`, + `access-control: error retrieving public key from catalyst statusCode=${response.status} catalystUrl=${url}` ); } }) diff --git a/packages/api/src/controllers/admin.js b/packages/api/src/controllers/admin.js index 7fad454a04..5a61c542e4 100644 --- a/packages/api/src/controllers/admin.js +++ b/packages/api/src/controllers/admin.js @@ -117,7 +117,7 @@ app.post( i++; } res.end(`cleaned routes for ${cleaned}/${toClean.length} streams\n`); - }, + } ); app.post("/active-clean", authorizer({ anyAdmin: true }), async (req, res) => { diff --git a/packages/api/src/controllers/api-token.js b/packages/api/src/controllers/api-token.js index 277188c603..a48ecca4f7 100644 --- a/packages/api/src/controllers/api-token.js +++ b/packages/api/src/controllers/api-token.js @@ -116,7 +116,7 @@ app.get("/", async (req, res) => { query.push( sql`coalesce(api_token.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); } diff --git a/packages/api/src/controllers/api-token.test.js b/packages/api/src/controllers/api-token.test.js index 753c6281fc..f70e4c5ad5 100644 --- a/packages/api/src/controllers/api-token.test.js +++ b/packages/api/src/controllers/api-token.test.js @@ -63,7 +63,7 @@ describe("controllers/api-token", () => { const nonAdminUserRes = await server.store.get( `user/${nonAdminUser.id}`, - false, + false ); nonAdminUser = { ...nonAdminUserRes, emailValid: true }; await server.store.replace(nonAdminUser); diff --git a/packages/api/src/controllers/asset.test.ts b/packages/api/src/controllers/asset.test.ts index 8b20658d58..19c80389d6 100644 --- a/packages/api/src/controllers/asset.test.ts +++ b/packages/api/src/controllers/asset.test.ts @@ -100,7 +100,7 @@ describe("controllers/asset", () => { const createApiToken = async ( cors: ApiToken["access"]["cors"], - projectId: string, + projectId: string ) => { client.jwtAuth = nonAdminToken; let res = await client.post(`/api-token/?projectId=${projectId}`, { @@ -200,7 +200,7 @@ describe("controllers/asset", () => { let res = await client.post( `/asset/upload/url/?projectId=${projectId}`, - spec, + spec ); expect(res.status).toBe(201); const { asset, task } = await res.json(); @@ -223,7 +223,7 @@ describe("controllers/asset", () => { expect(await res.json()).toBeDefined(); //api-key be retrieve if adminApiKey is used.. res = await client.get( - `/asset?limit=10&allUsers=true&filters=[{"id":"playbackId","value":"${asset.playbackId}"}]`, + `/asset?limit=10&allUsers=true&filters=[{"id":"playbackId","value":"${asset.playbackId}"}]` ); expect(res.status).toBe(200); let assets = await res.json(); @@ -296,7 +296,7 @@ describe("controllers/asset", () => { // BadRequest is expected if projectId is passed in as query-param let res = await client.post( `/asset/upload/url/?projectId=${projectId}`, - spec, + spec ); expect(res.status).toBe(400); @@ -405,7 +405,7 @@ describe("controllers/asset", () => { const prefix = url.substring(0, url.lastIndexOf("/") + 1); let res = await client.post( - `/asset/migrate/dstorage-urls?urlPrefix=${prefix}`, + `/asset/migrate/dstorage-urls?urlPrefix=${prefix}` ); expect(res.status).toBe(200); @@ -674,7 +674,7 @@ describe("controllers/asset", () => { const testStoragePatch = async ( patchedStorage: AssetPatchPayload["storage"], expectedStorage?: Asset["storage"], - expectedErrors?: any[], + expectedErrors?: any[] ) => { let res = await client.patch(`/asset/${asset.id}`, { storage: patchedStorage, @@ -707,7 +707,7 @@ describe("controllers/asset", () => { spec: {}, }, status: expect.any(Object), - }, + } ); await testStoragePatch({ ipfs: false }, undefined, [ "Cannot remove asset from IPFS", @@ -718,7 +718,7 @@ describe("controllers/asset", () => { await testStoragePatch( { ipfs: { nftMetadata: { a: "b" } } } as any, null, - [expect.stringContaining("should NOT have additional properties")], + [expect.stringContaining("should NOT have additional properties")] ); await testStoragePatch( { ipfs: {} }, @@ -727,7 +727,7 @@ describe("controllers/asset", () => { spec: {}, }, status: expect.any(Object), - }, + } ); await testStoragePatch({ ipfs: null }, undefined, [ "Cannot remove asset from IPFS", @@ -765,7 +765,7 @@ describe("controllers/asset", () => { await testStoragePatch( { ipfs: { spec: { nftMetadata: { b: "c", a: "b" } } } }, - expectedStorage, + expectedStorage ); patch.ipfs.spec.nftMetadata = { d: "e" }; @@ -781,7 +781,7 @@ describe("controllers/asset", () => { let assetFromIpfs: WithID; const createAsset = async ( - payload: Omit, + payload: Omit ) => { const id = uuid(); const playbackId = await generateUniquePlaybackId(id); @@ -791,7 +791,7 @@ describe("controllers/asset", () => { playbackId, userId: nonAdminUser.id, ...payload, - }), + }) ); }; @@ -864,11 +864,11 @@ describe("controllers/asset", () => { it("should find asset by NFT metadata CID", async () => { await expectFindAsset( `filters=[{"id":"nftMetadataCid","value":"somethingelse"}]`, - false, + false ); await expectFindAsset( `filters=[{"id":"nftMetadataCid","value":"${asset.storage.ipfs.nftMetadata.cid}"}]`, - true, + true ); }); @@ -876,7 +876,7 @@ describe("controllers/asset", () => { await expectFindAsset(`cid=${asset.storage.ipfs.nftMetadata.cid}`, false); await expectFindAsset( `filter=[{"id":"nftMetadataCid","value":"${asset.storage.ipfs.cid}"}]`, - false, + false ); }); @@ -884,7 +884,7 @@ describe("controllers/asset", () => { await expectFindAsset(`name=${asset.name}`, false); await expectFindAsset( `filters=[{"id":"name","value":"${asset.name}"}]`, - true, + true ); }); }); @@ -902,7 +902,7 @@ describe("controllers/asset", () => { filePath: string, tusEndpoint: string, shouldAbort: boolean, - resumeFrom?: number, + resumeFrom?: number ) => { const file = await fs.readFile(filePath); const { size } = await fs.stat(filePath); @@ -913,7 +913,7 @@ describe("controllers/asset", () => { const upload = new tus.Upload(file, { endpoint: tusEndpoint, urlStorage: new (tus as any).FileUrlStorage( - `${os.tmpdir()}/metadata`, + `${os.tmpdir()}/metadata` ), chunkSize: 1024 * 1024 * 1, metadata: { @@ -926,7 +926,7 @@ describe("controllers/asset", () => { }, onProgress(bytesUploaded, bytesTotal) { const percentage = parseFloat( - ((bytesUploaded / bytesTotal) * 100).toFixed(2), + ((bytesUploaded / bytesTotal) * 100).toFixed(2) ); if (resumeFrom) { expect(percentage).toBeGreaterThanOrEqual(resumeFrom); @@ -947,7 +947,7 @@ describe("controllers/asset", () => { upload.resumeFromPreviousUpload(previousUploads[0]); } upload.start(); - }, + } ); if (shouldAbort) { expect(uploadPercentage).toBeGreaterThan(0); @@ -971,7 +971,7 @@ describe("controllers/asset", () => { task: { id: taskId }, } = await res.json(); expect( - tusEndpoint?.startsWith(`http://test/api/asset/upload/tus?token=`), + tusEndpoint?.startsWith(`http://test/api/asset/upload/tus?token=`) ).toBe(true); tusEndpoint = tusEndpoint.replace("http://test", client.server.host); diff --git a/packages/api/src/controllers/asset.ts b/packages/api/src/controllers/asset.ts index cef6306a78..a8ee83f59b 100644 --- a/packages/api/src/controllers/asset.ts +++ b/packages/api/src/controllers/asset.ts @@ -86,7 +86,7 @@ export const primaryStorageExperiment = "primary-vod-storage"; export async function defaultObjectStoreId( { config, body, user }: Pick, - isOldPipeline?: boolean, + isOldPipeline?: boolean ): Promise { if (isOldPipeline) { return config.vodObjectStoreId; @@ -94,7 +94,7 @@ export async function defaultObjectStoreId( const secondaryStorageEnabled = !(await isExperimentSubject( primaryStorageExperiment, - user?.id, + user?.id )); if (isPrivatePlaybackPolicy(body.playbackPolicy)) { @@ -113,7 +113,7 @@ export async function defaultObjectStoreId( } export function assetEncryptionWithoutKey( - encryption: NewAssetPayload["encryption"], + encryption: NewAssetPayload["encryption"] ) { if (!encryption) { return encryption; @@ -138,7 +138,7 @@ function cleanAssetTracks(asset: WithID) { function anyMatchesRegexOrPrefix( arr: (string | RegExp)[], - value: string, + value: string ): boolean { for (const item of arr) { if (item instanceof RegExp && item.test(value)) { @@ -153,7 +153,7 @@ function anyMatchesRegexOrPrefix( function parseUrlToDStorageUrl( url: string, - { trustedIpfsGateways, trustedArweaveGateways }: CliArgs, + { trustedIpfsGateways, trustedArweaveGateways }: CliArgs ): string { const urlObj = new URL(url); const path = urlObj.pathname; @@ -190,7 +190,7 @@ export async function validateAssetPayload( id: string, playbackId: string, createdAt: number, - source: Asset["source"], + source: Asset["source"] ): Promise> { const userId = req.user.id; const payload = req.body as NewAssetPayload; @@ -202,7 +202,7 @@ export async function validateAssetPayload( const os = await getActiveObjectStore(objectStoreId); if (os.userId !== userId) { throw new ForbiddenError( - `the provided object store is not owned by user`, + `the provided object store is not owned by user` ); } } @@ -216,7 +216,7 @@ export async function validateAssetPayload( payload, playbackId, userId, - createdAt, + createdAt ); // Transform IPFS and Arweave gateway URLs into native protocol URLs @@ -258,7 +258,7 @@ async function validateAssetPlaybackPolicy( { playbackPolicy, objectStoreId, encryption }: Partial, playbackId: string, userId: string, - createdAt: number, + createdAt: number ) { if (isPrivatePlaybackPolicy(playbackPolicy) && objectStoreId) { throw new ForbiddenError(`private assets cannot use custom object store`); @@ -269,7 +269,7 @@ async function validateAssetPlaybackPolicy( if (!playbackPolicy.unifiedAccessControlConditions) { throw new UnprocessableEntityError( - `playbackPolicy.unifiedAccessControlConditions is required when using lit_signing_condition`, + `playbackPolicy.unifiedAccessControlConditions is required when using lit_signing_condition` ); } if (!playbackPolicy?.resourceId) { @@ -286,12 +286,12 @@ async function validateAssetPlaybackPolicy( let webhook = await db.webhook.get(playbackPolicy.webhookId); if (!webhook || webhook.deleted) { throw new BadRequestError( - `webhook ${playbackPolicy.webhookId} not found`, + `webhook ${playbackPolicy.webhookId} not found` ); } if (webhook.userId !== userId) { throw new BadRequestError( - `webhook ${playbackPolicy.webhookId} not found`, + `webhook ${playbackPolicy.webhookId} not found` ); } const allowedOrigins = playbackPolicy?.allowedOrigins; @@ -314,7 +314,7 @@ async function validateAssetPlaybackPolicy( const allowedOriginsValid = allowedOrigins.every(isValidOrigin); if (!allowedOriginsValid) { throw new BadRequestError( - "allowedOrigins must be a list of valid origins ://:", + "allowedOrigins must be a list of valid origins ://:" ); } } @@ -327,7 +327,7 @@ async function validateAssetPlaybackPolicy( if (encryption?.encryptedKey) { if (!playbackPolicy) { throw new BadRequestError( - `a playbackPolicy is required when using encryption`, + `a playbackPolicy is required when using encryption` ); } } @@ -352,7 +352,7 @@ export type StaticPlaybackInfo = { export function getStaticPlaybackInfo( asset: WithID, - os: ObjectStore, + os: ObjectStore ): StaticPlaybackInfo[] { return (asset.files ?? []) .filter((f) => f.type === "static_transcoded_mp4") @@ -369,18 +369,18 @@ export function getStaticPlaybackInfo( export function getPlaybackUrl( ingest: string, asset: WithID, - os: ObjectStore, + os: ObjectStore ): string { if (asset.playbackRecordingId) { return pathJoin( ingest, "recordings", asset.playbackRecordingId, - "index.m3u8", + "index.m3u8" ); } const catalystManifest = asset.files?.find( - (f) => f.type === "catalyst_hls_manifest", + (f) => f.type === "catalyst_hls_manifest" ); if (catalystManifest) { return pathJoin(os.publicUrl, asset.playbackId, catalystManifest.path); @@ -400,7 +400,7 @@ function getDownloadUrl( { vodObjectStoreId }: Request["config"], ingest: string, asset: WithID, - os: ObjectStore, + os: ObjectStore ): string { if ( (asset.source?.type === "recording" || asset.source?.type === "clip") && @@ -426,7 +426,7 @@ export async function withPlaybackUrls( config: CliArgs, ingest: string, asset: WithID, - os?: ObjectStore, + os?: ObjectStore ): Promise> { if (asset.files?.length < 1) { // files is only set when playback is available @@ -449,7 +449,7 @@ export async function withPlaybackUrls( export function withIpfsUrls>( gatewayUrl: string, - ipfs: T, + ipfs: T ): T { if (!ipfs?.cid) { return ipfs; @@ -463,7 +463,7 @@ export function withIpfsUrls>( function assetWithIpfsUrls( gatewayUrl: string, - asset: WithID, + asset: WithID ): WithID { if (!asset?.storage?.ipfs?.cid) { return asset; @@ -479,7 +479,7 @@ function assetWithIpfsUrls( } function storageInputToState( - input: NewAssetPayload["storage"], + input: NewAssetPayload["storage"] ): Asset["storage"] { if (typeof input?.ipfs === "undefined") { return undefined; @@ -517,12 +517,12 @@ async function reconcileAssetStorage( { taskScheduler, config }: Request, asset: WithID, newStorage: Asset["storage"], - task?: WithID, + task?: WithID ): Promise { let { storage } = asset; const ipfsParamsEq = _.isEqual( newStorage.ipfs?.spec, - storage?.ipfs?.spec ?? null, + storage?.ipfs?.spec ?? null ); if ("ipfs" in newStorage && !ipfsParamsEq) { let newSpec = newStorage.ipfs?.spec; @@ -535,7 +535,7 @@ async function reconcileAssetStorage( task = await taskScheduler.createAndScheduleTask( "export", { export: { ipfs: newSpec } }, - asset, + asset ); } storage = { @@ -560,7 +560,7 @@ async function genUploadUrl( playbackId: string, objectStoreId: string, jwtSecret: string, - aud: string, + aud: string ) { const uploadedObjectKey = `directUpload/${playbackId}`; const os = await getActiveObjectStore(objectStoreId); @@ -580,7 +580,7 @@ async function genUploadUrl( function parseUploadUrl( signedUploadUrl: string, jwtSecret: string, - audience: string, + audience: string ) { let urlJwt: JwtPayload; let uploadUrl: string; @@ -600,7 +600,7 @@ export async function toExternalAsset( a: WithID, config: CliArgs, details = false, - isAdmin = false, + isAdmin = false ) { const { ipfsGatewayUrl, ingest: ingestsConfig } = config; // Not sure why the ingests config was originally made an array and not a @@ -626,7 +626,7 @@ app.use(mung.jsonAsync(addDefaultProjectId)); app.use( mung.jsonAsync(async function cleanWriteOnlyResponses( data: WithID[] | WithID | { asset: WithID }, - req, + req ) { const { details } = toStringValues(req.query); const toExternalAssetFunc = async (a: Asset) => { @@ -634,7 +634,7 @@ app.use( a, req.config, !!details, - req.user.admin, + req.user.admin ); return modifiedAsset; @@ -653,7 +653,7 @@ app.use( }; } return data; - }), + }) ); const fieldsMap = { @@ -710,7 +710,7 @@ app.get("/", authorizer({}), async (req, res) => { if (cid) { const ipfsUrl = `ipfs://${cid}`; query.push( - sql`(asset.data->'storage'->'ipfs'->>'cid' = ${cid} OR asset.data->'source'->>'url' = ${ipfsUrl})`, + sql`(asset.data->'storage'->'ipfs'->>'cid' = ${cid} OR asset.data->'source'->>'url' = ${ipfsUrl})` ); } @@ -720,12 +720,12 @@ app.get("/", authorizer({}), async (req, res) => { if (req.user.admin && deleting === "true") { const deletionThreshold = new Date( - Date.now() - DELETE_ASSET_DELAY, + Date.now() - DELETE_ASSET_DELAY ).toISOString(); query.push(sql`asset.data->'status'->>'phase' = 'deleting'`); query.push( - sql`asset.data->>'deletedAt' IS NOT NULL AND asset.data->>'deletedAt' < ${deletionThreshold}`, + sql`asset.data->>'deletedAt' IS NOT NULL AND asset.data->>'deletedAt' < ${deletionThreshold}` ); } @@ -759,7 +759,7 @@ app.get("/", authorizer({}), async (req, res) => { query.push( sql`coalesce(asset.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); let fields = " asset.id as id, asset.data as data"; @@ -824,27 +824,27 @@ app.post( const task = await req.taskScheduler.createAndScheduleTask( "export", { export: params }, - asset, + asset ); if ("ipfs" in params && !params.ipfs?.pinata) { // TODO: Make this unsupported. PATCH should be the only way to change asset storage. console.warn( - `Deprecated export to IPFS API used. userId=${req.user.id} assetId=${assetId}`, + `Deprecated export to IPFS API used. userId=${req.user.id} assetId=${assetId}` ); const storage = await reconcileAssetStorage( req, asset, { ipfs: { spec: params.ipfs } }, - task, + task ); await req.taskScheduler.updateAsset(asset, { storage }); } res.status(201); res.json({ task }); - }, + } ); app.post( @@ -880,12 +880,12 @@ app.post( type: "url", url, encryption: assetEncryptionWithoutKey(encryption), - }, + } ); const dupAsset = await db.asset.findDuplicateUrlUpload( url, req.user, - req.project?.id, + req.project?.id ); if (dupAsset) { const [task] = await db.task.find({ outputAssetId: dupAsset.id }); @@ -913,19 +913,19 @@ app.post( encryption, thumbnails: !(await isExperimentSubject( "vod-thumbs-off", - req.user?.id, + req.user?.id )), ...(profiles ? { profiles } : null), // avoid serializing null profiles on the task, targetSegmentSizeSecs, }, }, undefined, - asset, + asset ); res.status(201); res.json({ asset, task: { id: task.id } }); - }, + } ); app.post( @@ -957,7 +957,7 @@ app.post( playbackId, vodObjectStoreId, jwtSecret, - jwtAudience, + jwtAudience ); const ingests = await req.getIngest(); @@ -985,18 +985,18 @@ app.post( encryption, thumbnails: !(await isExperimentSubject( "vod-thumbs-off", - req.user?.id, + req.user?.id )), c2pa, ...(profiles ? { profiles } : null), // avoid serializing null profiles on the task }, }, null, - asset, + asset ); res.json({ url, tusEndpoint, asset, task: { id: task.id } }); - }, + } ); let tusServer: TusServer; @@ -1069,7 +1069,7 @@ const onUploadComplete = async (playbackId: string) => { } catch (err) { console.error( `error processing upload complete playbackId=${playbackId} err=`, - err, + err ); } }; @@ -1086,7 +1086,7 @@ const getPendingAssetAndTask = async (playbackId: string) => { const tasks = await db.task.find( { outputAssetId: asset.id }, - { useReplica: false }, + { useReplica: false } ); if (!tasks?.length || !tasks[0]?.length) { throw new NotFoundError(`task not found`); @@ -1109,7 +1109,7 @@ app.post("/upload/tus", async (req, res) => { const uploadToken = req.query.token?.toString(); if (!uploadToken) { throw new UnauthorizedError( - "Missing uploadToken metadata from /request-upload API", + "Missing uploadToken metadata from /request-upload API" ); } @@ -1133,7 +1133,7 @@ app.put("/upload/direct", async (req, res) => { const { uploadUrl, playbackId } = parseUploadUrl( token?.toString(), jwtSecret, - jwtAudience, + jwtAudience ); // ensure upload exists and is pending @@ -1146,7 +1146,7 @@ app.put("/upload/direct", async (req, res) => { await onUploadComplete(playbackId); } else { console.log( - `assetUpload: Proxy upload to s3 on url ${uploadUrl} failed with status code: ${res.statusCode}`, + `assetUpload: Proxy upload to s3 on url ${uploadUrl} failed with status code: ${res.statusCode}` ); } }); @@ -1240,7 +1240,7 @@ app.delete("/", authorizer({ anyAdmin: true }), async (req, res) => { const user = await db.user.get(userId); if (!user) { - throw new NotFoundError(`user not found`); + throw new NotFoundError(`Account not found`); } const limit = parseInt(req.query.limit?.toString() || "100"); @@ -1249,7 +1249,7 @@ app.delete("/", authorizer({ anyAdmin: true }), async (req, res) => { [sql`data->>'userId' = ${userId}`, sql`data->>'deleted' IS NULL`], { limit, - }, + } ); let deletedCount = 0; @@ -1301,11 +1301,11 @@ app.patch( ) { const sameResourceId = _.isEqual( playbackPolicy.resourceId, - asset.playbackPolicy.resourceId, + asset.playbackPolicy.resourceId ); if (playbackPolicy.type !== "lit_signing_condition" || !sameResourceId) { throw new UnprocessableEntityError( - `cannot update playback policy from lit_signing_condition nor change the resource ID`, + `cannot update playback policy from lit_signing_condition nor change the resource ID` ); } } @@ -1316,7 +1316,7 @@ app.patch( isPrivatePlaybackPolicy(asset.playbackPolicy) ) { throw new UnprocessableEntityError( - `cannot update playback policy from private to public or vice versa`, + `cannot update playback policy from private to public or vice versa` ); } @@ -1324,7 +1324,7 @@ app.patch( { playbackPolicy }, asset.playbackId, asset.userId, - asset.createdAt, + asset.createdAt ); } @@ -1336,7 +1336,7 @@ app.patch( }); const updated = await db.asset.get(id, { useReplica: false }); res.status(200).json(updated); - }, + } ); app.post("/:id/retry", authorizer({}), async (req, res) => { @@ -1409,7 +1409,7 @@ app.post( sql`data->'source'->>'url' LIKE ${urlLike}`, ...(!from ? [] : [sql`data->'source'->>'url' > ${from}`]), ], - { limit, order: parseOrder(fieldsMap, "sourceUrl-false") }, + { limit, order: parseOrder(fieldsMap, "sourceUrl-false") } ); let tasks: Promise>[] = []; @@ -1434,7 +1434,7 @@ app.post( tasks.push( db.asset .update(asset.id, { source }) - .then(() => db.asset.get(asset.id)), + .then(() => db.asset.get(asset.id)) ); } @@ -1457,7 +1457,7 @@ app.post( source, })), }); - }, + } ); export default app; diff --git a/packages/api/src/controllers/auth.test.ts b/packages/api/src/controllers/auth.test.ts index 4c93530e9b..d77ad6a7ad 100644 --- a/packages/api/src/controllers/auth.test.ts +++ b/packages/api/src/controllers/auth.test.ts @@ -101,7 +101,7 @@ describe("controller/auth", () => { { resources: ["foo"], methods: ["options"] }, { resources: ["foo/bar"], methods: ["get", "patch"] }, { resources: ["foo/bar/zaz"], methods: ["head", "post"] }, - ]), + ]) ); it("should disallow other methods", async () => { @@ -132,7 +132,7 @@ describe("controller/auth", () => { setAccess(nonAdminApiKey, [ { resources: ["gus/:id"] }, { resources: ["gus/fra/*"] }, - ]), + ]) ); it("should disallow other paths", async () => { @@ -263,11 +263,11 @@ describe("controller/auth", () => { if (method === "OPTIONS") { expect(res.status).toEqual(204); expect(res.headers.get("access-control-allow-methods")).toEqual( - "GET,HEAD,PUT,PATCH,POST,DELETE", + "GET,HEAD,PUT,PATCH,POST,DELETE" ); } expect(res.headers.get("access-control-allow-credentials")).toEqual( - "true", + "true" ); const corsAllowed = res.headers.get("access-control-allow-origin") === origin; @@ -291,7 +291,7 @@ describe("controller/auth", () => { for (const origin of testOrigins) { await expectAllowed(method, "/asset/upload", origin).toBe(false); await expectAllowed(method, "/asset/request-upload", origin).toBe( - false, + false ); await expectAllowed(method, "/playback", origin).toBe(false); await expectAllowed(method, "/stream", origin).toBe(false); @@ -305,15 +305,15 @@ describe("controller/auth", () => { client.jwtAuth = nonAdminToken; for (const method of testMethods) { await expectAllowed(method, "/stream", "https://livepeer.studio").toBe( - true, + true ); await expectAllowed(method, "/asset", "https://livepeer.studio").toBe( - true, + true ); await expectAllowed( method, "/api-token/1234", - "https://livepeer.studio", + "https://livepeer.studio" ).toBe(true); } }); @@ -341,7 +341,7 @@ describe("controller/auth", () => { const expected = allowedOrigins.includes(origin); await expectAllowed(method, "/asset/request-upload", origin).toBe( - expected, + expected ); await expectAllowed(method, "/asset", origin).toBe(expected); await expectAllowed(method, "/asset/abcd", origin).toBe(expected); @@ -365,13 +365,13 @@ describe("controller/auth", () => { client.apiKey = await createApiToken({ allowedOrigins }); // control case await expect( - fetchCors("GET", "/stream/1234", allowedOrigins[0]), + fetchCors("GET", "/stream/1234", allowedOrigins[0]) ).resolves.toMatchObject({ corsAllowed: true, status: 204, }); await expect( - fetchCors("GET", "/data/views/1234/total", allowedOrigins[0]), + fetchCors("GET", "/data/views/1234/total", allowedOrigins[0]) ).resolves.toMatchObject({ corsAllowed: true, status: 204, @@ -379,7 +379,7 @@ describe("controller/auth", () => { for (const [method, path] of forbiddenApis) { await expect( - fetchCors(method, path, allowedOrigins[0]), + fetchCors(method, path, allowedOrigins[0]) ).resolves.toMatchObject({ corsAllowed: true, status: 403, @@ -401,7 +401,7 @@ describe("controller/auth", () => { const { corsAllowed, status, body } = await fetchCors( method, path, - allowedOrigins[0], + allowedOrigins[0] ); expect(corsAllowed).toBe(true); expect(status).toBe(204); @@ -424,14 +424,14 @@ describe("controller/auth", () => { ]; for (const [method, path] of apis) { await expect( - fetchCors(method, path, "https://not.allowed.com"), + fetchCors(method, path, "https://not.allowed.com") ).resolves.toMatchObject({ corsAllowed: false, status: 403, body: { errors: [ expect.stringMatching( - /credential disallows CORS access from origin .+/, + /credential disallows CORS access from origin .+/ ), ], }, @@ -516,15 +516,15 @@ describe("controller/auth", () => { await db.asset.markDeleted(nonAdminAsset.id); await expect(fetchAuth({ streamId: nonAdminStream.id })).resolves.toBe( - 404, + 404 ); await expect(fetchAuth({ pid: nonAdminStream.playbackId })).resolves.toBe( - 404, + 404 ); await expect(fetchAuth({ assetId: nonAdminAsset.id })).resolves.toBe(404); await expect(fetchAuth({ pid: nonAdminAsset.playbackId })).resolves.toBe( - 404, + 404 ); }); @@ -532,36 +532,36 @@ describe("controller/auth", () => { await expect(fetchAuth({ streamId: adminStream.id })).resolves.toBe(403); await expect(fetchAuth({ assetId: adminAsset.id })).resolves.toBe(403); await expect(fetchAuth({ pid: adminAsset.playbackId })).resolves.toBe( - 403, + 403 ); }); it("should allow access to own resources", async () => { await expect(fetchAuth({ streamId: nonAdminStream.id })).resolves.toBe( - 204, + 204 ); await expect(fetchAuth({ pid: nonAdminStream.playbackId })).resolves.toBe( - 204, + 204 ); await expect(fetchAuth({ assetId: nonAdminAsset.id })).resolves.toBe(204); await expect(fetchAuth({ pid: nonAdminAsset.playbackId })).resolves.toBe( - 204, + 204 ); }); it("should allow admins to access to other users resources", async () => { client.apiKey = adminApiKey; await expect(fetchAuth({ streamId: nonAdminStream.id })).resolves.toBe( - 204, + 204 ); await expect(fetchAuth({ pid: nonAdminStream.playbackId })).resolves.toBe( - 204, + 204 ); await expect(fetchAuth({ assetId: nonAdminAsset.id })).resolves.toBe(204); await expect(fetchAuth({ pid: nonAdminAsset.playbackId })).resolves.toBe( - 204, + 204 ); }); }); diff --git a/packages/api/src/controllers/auth.ts b/packages/api/src/controllers/auth.ts index 97566c6d67..ac8e9fac07 100644 --- a/packages/api/src/controllers/auth.ts +++ b/packages/api/src/controllers/auth.ts @@ -17,7 +17,7 @@ type UserOwnedObj = { id: string; deleted?: boolean; userId?: string }; async function checkUserOwned( req: Request, headerName: string, - getter: (id: string) => Promise, + getter: (id: string) => Promise ) { if (!(headerName in req.headers)) { return; @@ -41,7 +41,7 @@ function playbackIdGetter(req: Request) { return async (id: string): Promise => { const { asset, stream, session } = await getResourceByPlaybackId( id, - req.user, + req.user ); return asset || stream || session; }; @@ -72,7 +72,7 @@ app.all( res.header("x-livepeer-project-id", req.project?.id || ""); res.status(204).end(); - }, + } ); export default app; diff --git a/packages/api/src/controllers/broadcaster.js b/packages/api/src/controllers/broadcaster.js index f1ed79c5ef..9dce0af34b 100644 --- a/packages/api/src/controllers/broadcaster.js +++ b/packages/api/src/controllers/broadcaster.js @@ -26,7 +26,7 @@ export const amalgamate = async (req, endpoint) => { }); const data = await serverRes.json(); return data; - }), + }) ); let output; if (responses.length === 0) { diff --git a/packages/api/src/controllers/clip.ts b/packages/api/src/controllers/clip.ts index 3cc4de19e7..a47be3f271 100644 --- a/packages/api/src/controllers/clip.ts +++ b/packages/api/src/controllers/clip.ts @@ -41,7 +41,7 @@ const MAX_PROCESSING_CLIPS = 5; app.use( mung.jsonAsync(async function cleanWriteOnlyResponses( data: WithID[] | WithID | { asset: WithID }, - req, + req ) { const { details } = toStringValues(req.query); const toExternalAssetFunc = (a: Asset) => @@ -60,7 +60,7 @@ app.use( }; } return data; - }), + }) ); app.post( @@ -92,7 +92,7 @@ app.post( if (!owner) { throw new NotFoundError( - "Content not found - unable to find owner of content", + "Content not found - unable to find owner of content" ); } @@ -106,7 +106,7 @@ app.post( clip: user=${clippingUser.email} does not have permission to clip stream=${content.id} - owner=${owner?.id} `); throw new ForbiddenError( - "You do not have permission to clip this stream", + "You do not have permission to clip this stream" ); } @@ -118,7 +118,7 @@ app.post( requesterId, req.user.id, "clip", - 5, + 5 ); if (processingClips.length >= MAX_PROCESSING_CLIPS && !clippingUser.admin) { @@ -137,18 +137,18 @@ app.post( } if (session.parentId !== content.id) { throw new NotFoundError( - "The provided session id does not belong to this stream", + "The provided session id does not belong to this stream" ); } ({ url, objectStoreId } = await buildRecordingUrl( session, req.config.recordCatalystObjectStoreId, - req.config.secondaryRecordObjectStoreId, + req.config.secondaryRecordObjectStoreId )); } else { ({ url, session, objectStoreId } = await getRunningRecording( content, - req, + req )); } } else { @@ -186,7 +186,7 @@ app.post( type: "clip", playbackId, ...(isStream ? { sessionId: session.id } : { assetId: content.id }), - }, + } ); asset = await createAsset(asset, req.queue); @@ -210,14 +210,14 @@ app.post( null, asset, owner.id, - requesterId, + requesterId ); res.json({ task: { id: task.id }, asset, }); - }, + } ); const fieldsMap = { @@ -253,7 +253,7 @@ app.get("/:id", authorizer({}), async (req, res) => { export const getClips = async ( content: DBSession | DBStream | WithID, req: Request, - res: Response, + res: Response ) => { let { limit, cursor, all, allUsers, order, filters, count, cid, ...otherQs } = toStringValues(req.query); @@ -275,7 +275,7 @@ export const getClips = async ( query.push( sql`coalesce(asset.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); if (!content) { @@ -315,8 +315,8 @@ export const getClips = async ( query.push( sql`asset.data->'source'->>'sessionId' IN `.append( - sqlQueryGroup(sessionIds), - ), + sqlQueryGroup(sessionIds) + ) ); break; diff --git a/packages/api/src/controllers/compose-m3u8.js b/packages/api/src/controllers/compose-m3u8.js index f39f882654..61ae0f2352 100644 --- a/packages/api/src/controllers/compose-m3u8.js +++ b/packages/api/src/controllers/compose-m3u8.js @@ -24,7 +24,7 @@ export default async (urls, { limit, rewrite } = {}) => { } catch (err) { // No problem, we expect sometimes they don't exist } - }), + }) ); if (broadcasters.length === 0) { @@ -183,7 +183,7 @@ export const handleMasterPlaylist = (broadcasters) => { const { width, height } = playlist.attributes.RESOLUTION; // Todo: kinda hardcoded to what go-livepeer provides right now output.push( - `#EXT-X-STREAM-INF:PROGRAM-ID=${programId},BANDWIDTH=${bandwidth},RESOLUTION=${width}x${height}`, + `#EXT-X-STREAM-INF:PROGRAM-ID=${programId},BANDWIDTH=${bandwidth},RESOLUTION=${width}x${height}` ); output.push(playlist.uri); } diff --git a/packages/api/src/controllers/compose-m3u8.test-data.js b/packages/api/src/controllers/compose-m3u8.test-data.js index e2d6331cda..138102f720 100644 --- a/packages/api/src/controllers/compose-m3u8.test-data.js +++ b/packages/api/src/controllers/compose-m3u8.test-data.js @@ -265,9 +265,9 @@ test://longPlaylistBroadcaster/stream/6e028727-bb4d-4cf4-8bc0-cad57de4cd89/sourc export const longPlaylistStoreRewritten = longPlaylistStore.replace( /test:\/\/longPlaylistBroadcaster\/stream/g, - "https://example.com/store", + "https://example.com/store" ); export const longPlaylistCombinedRewritten = longPlaylistCombined.replace( /test:\/\/longPlaylistBroadcaster\/stream/g, - "https://example.com/store", + "https://example.com/store" ); diff --git a/packages/api/src/controllers/compose-m3u8.test.js b/packages/api/src/controllers/compose-m3u8.test.js index 07f166495e..4bf0345ce2 100644 --- a/packages/api/src/controllers/compose-m3u8.test.js +++ b/packages/api/src/controllers/compose-m3u8.test.js @@ -9,7 +9,7 @@ describe("compose-m3u8", () => { } setMock( "test://404.m3u8", - () => new Response("not found", { status: 404 }), + () => new Response("not found", { status: 404 }) ); }); @@ -91,7 +91,7 @@ describe("compose-m3u8", () => { "test://longPlaylistStore/stream/playlist.m3u8", "test://longPlaylistBroadcaster/stream/playlist.m3u8", ], - { limit: 10 }, + { limit: 10 } ); expect(combined).toEqual(testData.longPlaylistCombinedTen); const allCombined = await composeM3U8( @@ -99,7 +99,7 @@ describe("compose-m3u8", () => { "test://longPlaylistStore/stream/playlist.m3u8", "test://longPlaylistBroadcaster/stream/playlist.m3u8", ], - { limit: 99999999 }, + { limit: 99999999 } ); expect(allCombined).toEqual(testData.longPlaylistCombined); }); @@ -115,7 +115,7 @@ describe("compose-m3u8", () => { from: "test://longPlaylistBroadcaster/stream", to: "https://example.com/store", }, - }, + } ); expect(combined).toEqual(testData.longPlaylistCombinedRewritten); }); diff --git a/packages/api/src/controllers/experiment.test.ts b/packages/api/src/controllers/experiment.test.ts index 897201408c..270d8f1938 100644 --- a/packages/api/src/controllers/experiment.test.ts +++ b/packages/api/src/controllers/experiment.test.ts @@ -36,7 +36,7 @@ describe("controllers/experiment", () => { ({ client, adminApiKey, nonAdminUser, nonAdminApiKey } = await setupUsers( server, mockAdminUserInput, - mockNonAdminUserInput, + mockNonAdminUserInput )); client.apiKey = adminApiKey; @@ -54,7 +54,7 @@ describe("controllers/experiment", () => { expect(res.status).toBe(404); res = await client.post( - `/experiment/-/lit-signing-condition/verify-lit-jwt`, + `/experiment/-/lit-signing-condition/verify-lit-jwt` ); expect(res.status).toBe(403); const { errors } = await res.json(); @@ -82,7 +82,7 @@ describe("controllers/experiment", () => { `/experiment/lit-signing-condition/audience`, { allowAll: true, - }, + } ); expect(resAudience.status).toBe(204); @@ -92,7 +92,7 @@ describe("controllers/experiment", () => { it("allows admins to check for other users", async () => { const res = await client.get( - `/experiment/check/lit-signing-condition?userId=${nonAdminUser.id}`, + `/experiment/check/lit-signing-condition?userId=${nonAdminUser.id}` ); expect(res.status).toBe(204); }); @@ -111,11 +111,11 @@ describe("controllers/experiment", () => { } as any); let res = await client.get( - `/experiment/check/lit-signing-condition?playbackId=${assetId}`, + `/experiment/check/lit-signing-condition?playbackId=${assetId}` ); expect(res.status).toBe(204); res = await client.get( - `/experiment/check/lit-signing-condition?playbackId=${streamId}`, + `/experiment/check/lit-signing-condition?playbackId=${streamId}` ); expect(res.status).toBe(204); }); diff --git a/packages/api/src/controllers/experiment.ts b/packages/api/src/controllers/experiment.ts index 8242fe30db..cc4b8c77c5 100644 --- a/packages/api/src/controllers/experiment.ts +++ b/packages/api/src/controllers/experiment.ts @@ -26,7 +26,7 @@ async function toUserId(emailOrId: string) { user = users?.[0]; } if (!user) { - throw new NotFoundError(`user not found: ${emailOrId}`); + throw new NotFoundError(`Account not found: ${emailOrId}`); } return user.id; } @@ -62,7 +62,7 @@ app.get("/check/:experiment", authorizer({}), async (req, res) => { if (userId) { user = await db.user.get(userId); if (!user) { - throw new NotFoundError("user not found"); + throw new NotFoundError("Account not found"); } } } @@ -99,7 +99,7 @@ app.post( }); res.status(204).end(); - }, + } ); // Experiment CRUD @@ -121,7 +121,7 @@ app.post( audienceUserIds, }); res.status(201).json(experiment); - }, + } ); app.patch("/:experiment", authorizer({ anyAdmin: true }), async (req, res) => { @@ -154,7 +154,7 @@ app.get("/:experiment", authorizer({ anyAdmin: true }), async (req, res) => { experiment.audienceUserIds?.map(async (userId) => { const user = await db.user.get(userId); return db.user.cleanWriteOnlyResponse(user); - }) ?? [], + }) ?? [] ), }; @@ -171,7 +171,7 @@ const fieldsMap = { app.get("/", authorizer({ anyAdmin: true }), async (req, res) => { let { limit, cursor, order, filters, count, subject } = toStringValues( - req.query, + req.query ); if (isNaN(parseInt(limit))) { limit = undefined; diff --git a/packages/api/src/controllers/experiment/attestation.test.ts b/packages/api/src/controllers/experiment/attestation.test.ts index e0b588cf0b..552a835efc 100644 --- a/packages/api/src/controllers/experiment/attestation.test.ts +++ b/packages/api/src/controllers/experiment/attestation.test.ts @@ -70,7 +70,7 @@ beforeEach(async () => { { email: "user_non_admin@gmail.com", password: "y".repeat(64), - }, + } )); client.apiKey = adminApiKey; @@ -292,7 +292,7 @@ describe("Attestation API", () => { it("should return a list of attestation metadata entries from the given creator", async () => { const res = await client.get( - `/experiment/-/attestation?creator=${CREATOR_PUBLIC_KEY}`, + `/experiment/-/attestation?creator=${CREATOR_PUBLIC_KEY}` ); expect(res.status).toEqual(200); diff --git a/packages/api/src/controllers/experiment/attestation.ts b/packages/api/src/controllers/experiment/attestation.ts index cb417c0781..ebb72f7fcf 100644 --- a/packages/api/src/controllers/experiment/attestation.ts +++ b/packages/api/src/controllers/experiment/attestation.ts @@ -41,7 +41,7 @@ app.post("/", validatePost("attestation"), async (req, res) => { const verfiedSignatureType = await verifySignature( message, signature, - signatureType, + signatureType ); if (!verfiedSignatureType) { return res.status(400).json({ errors: ["invalid signature"] }); @@ -104,7 +104,7 @@ function toContent(attestation: Attestation) { async function verifySignature( message: any, signature: string, - signatureType?: Attestation["signatureType"], + signatureType?: Attestation["signatureType"] ): Promise { const verifiedEIP712 = (signatureType === "eip712" || !signatureType) && @@ -122,7 +122,7 @@ function verifyEIP712Signature(message: any, signature: string): boolean { DOMAIN, TYPES, message, - signature, + signature ); return verifiedSigner === message.signer; @@ -133,7 +133,7 @@ function verifyEIP712Signature(message: any, signature: string): boolean { async function verifyFlowSignature( message: any, - signature: string, + signature: string ): Promise { try { const compSig = [ @@ -148,7 +148,7 @@ async function verifyFlowSignature( return await fcl.AppUtils.verifyUserSignatures( Buffer.from(stringify(message)).toString("hex"), - compSig, + compSig ); } catch (e) { return false; @@ -176,7 +176,7 @@ app.get("/", async (req, res) => { const query = []; if (creator) { query.push( - `attestation.data->'message'->'attestations' @> '[{"role":"creator","address":"${creator}"}]'`, + `attestation.data->'message'->'attestations' @> '[{"role":"creator","address":"${creator}"}]'` ); } const [output, newCursor] = await db.attestation.find(query, { diff --git a/packages/api/src/controllers/experiment/lit-signing-condition.ts b/packages/api/src/controllers/experiment/lit-signing-condition.ts index 3bac7a25c8..1dbd992eaa 100644 --- a/packages/api/src/controllers/experiment/lit-signing-condition.ts +++ b/packages/api/src/controllers/experiment/lit-signing-condition.ts @@ -18,7 +18,7 @@ import { CliArgs } from "../../parse-cli"; export function signGoogleCDNCookie( config: CliArgs, urlPrefix: string, - expirationMs: number, + expirationMs: number ): [string, string] { const { googleCloudUrlSigningKeyName: keyName, @@ -49,13 +49,13 @@ function setGoogleCloudCookie(res: Response, asset: WithID) { const urlPrefix = getPlaybackFolderPrefix(asset.playbackUrl); const ttl = Math.max( 60 * 60 * 1000, - 2 * Math.round(asset.videoSpec.duration * 1000), + 2 * Math.round(asset.videoSpec.duration * 1000) ); const expiration = Date.now() + ttl; const [name, value] = signGoogleCDNCookie( res.req.config, urlPrefix.toString(), - expiration, + expiration ); res.cookie(name, value, { httpOnly: true, diff --git a/packages/api/src/controllers/generate-keys.test.ts b/packages/api/src/controllers/generate-keys.test.ts index 73e04d547e..15f2375627 100644 --- a/packages/api/src/controllers/generate-keys.test.ts +++ b/packages/api/src/controllers/generate-keys.test.ts @@ -105,7 +105,7 @@ describe("controllers/generate-keys", () => { keysMock.__addResult( stream1.playbackId, stream2.playbackId, - mockPlaybackId, + mockPlaybackId ); const pid = await generateUniquePlaybackId(""); expect(pid).not.toEqual(stream1.playbackId); @@ -129,7 +129,7 @@ describe("controllers/generate-keys", () => { stream2.playbackId, stream1.playbackId, stream2.streamKey, - mockPlaybackId, + mockPlaybackId ); await expect(generateUniquePlaybackId("")).resolves.toEqual(mockPlaybackId); }); diff --git a/packages/api/src/controllers/generate-keys.ts b/packages/api/src/controllers/generate-keys.ts index 96fcb1dc02..f2b35360d2 100644 --- a/packages/api/src/controllers/generate-keys.ts +++ b/packages/api/src/controllers/generate-keys.ts @@ -76,7 +76,7 @@ async function generateUniqueKey(shardBase: string, otherKeys: string[] = []) { return shardedKey; } console.warn( - `Generated conflicting database key. key=${shardedKey} otherKeys="${otherKeys}"`, + `Generated conflicting database key. key=${shardedKey} otherKeys="${otherKeys}"` ); } } @@ -85,5 +85,5 @@ export const generateUniqueStreamKey = generateUniqueKey; export const generateUniquePlaybackId = async ( shardBase: string, - otherKeys: string[] = [], + otherKeys: string[] = [] ) => formatPlaybackId(await generateUniqueKey(shardBase, otherKeys)); diff --git a/packages/api/src/controllers/helpers.test.ts b/packages/api/src/controllers/helpers.test.ts index 7adc816627..bda8d850f5 100644 --- a/packages/api/src/controllers/helpers.test.ts +++ b/packages/api/src/controllers/helpers.test.ts @@ -37,41 +37,41 @@ describe("controllers/helpers", () => { it("should support old object store URLs with region", async () => { const presignedUrl = await makePresignedUrl( - "s3+http://localhost:8000/test-region/test-bucket", + "s3+http://localhost:8000/test-region/test-bucket" ); expect(presignedUrl).toMatch( - /^http:\/\/localhost:8000\/test-bucket\/test\.txt.+test-region.+$/, + /^http:\/\/localhost:8000\/test-bucket\/test\.txt.+test-region.+$/ ); }); it("should support new object store URLs without region", async () => { const presignedUrl = await makePresignedUrl( - "s3+https://localhost:8000/test-bucket", + "s3+https://localhost:8000/test-bucket" ); expect(presignedUrl).toMatch( - /^https:\/\/localhost:8000\/test-bucket\/test\.txt.+ignored.+$/, + /^https:\/\/localhost:8000\/test-bucket\/test\.txt.+ignored.+$/ ); }); it("should support access credentials", async () => { const presignedUrl = await makePresignedUrl( - "s3+https://poweruser:secretpwd@localhost:8000/test-bucket", + "s3+https://poweruser:secretpwd@localhost:8000/test-bucket" ); expect(presignedUrl).toMatch( - /^https:\/\/localhost:8000\/test-bucket\/test\.txt.+poweruser.+$/, + /^https:\/\/localhost:8000\/test-bucket\/test\.txt.+poweruser.+$/ ); expect(presignedUrl).not.toContain("secretpwd"); }); it("should NOT support invalid object store URLs", async () => { await expect( - makePresignedUrl("not-s3://localhost:8000/test-bucket"), + makePresignedUrl("not-s3://localhost:8000/test-bucket") ).rejects.toThrow(/not-s3:/); await expect( - makePresignedUrl("s3+https://localhost:8000/"), + makePresignedUrl("s3+https://localhost:8000/") ).rejects.toThrow(/"\/"/); await expect( - makePresignedUrl("s3+https://localhost:8000/region/bucket/path"), + makePresignedUrl("s3+https://localhost:8000/region/bucket/path") ).rejects.toThrow(/"\/region\/bucket\/path"/); }); }); @@ -87,7 +87,7 @@ describe("controllers/helpers", () => { }, }; expect(toObjectStoreUrl(storageObj)).toBe( - "s3+https://AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI%2FK7MDENG%2FbPxRfiCYEXAMPLEKEY@gateway.storjshare.io/testbucket", + "s3+https://AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI%2FK7MDENG%2FbPxRfiCYEXAMPLEKEY@gateway.storjshare.io/testbucket" ); }); @@ -100,7 +100,7 @@ describe("controllers/helpers", () => { }, }; expect(() => toObjectStoreUrl(storageObj)).toThrow( - "undefined property 'endpoint'", + "undefined property 'endpoint'" ); }); @@ -114,7 +114,7 @@ describe("controllers/helpers", () => { }, }; expect(() => toObjectStoreUrl(storageObj)).toThrow( - "undefined property 'endpoint'", + "undefined property 'endpoint'" ); }); @@ -127,7 +127,7 @@ describe("controllers/helpers", () => { }, }; expect(() => toObjectStoreUrl(storageObj)).toThrow( - "undefined property 'bucket'", + "undefined property 'bucket'" ); }); @@ -137,7 +137,7 @@ describe("controllers/helpers", () => { bucket: "testbucket", }; expect(() => toObjectStoreUrl(storageObj)).toThrow( - "undefined property 'credentials'", + "undefined property 'credentials'" ); }); @@ -152,7 +152,7 @@ describe("controllers/helpers", () => { additionalProperty: "someAdditionalProperty", }; expect(() => toObjectStoreUrl(storageObj)).toThrow( - "undefined property 'credentials'", + "undefined property 'credentials'" ); }); }); @@ -161,26 +161,26 @@ describe("controllers/helpers", () => { it("should delete credentials form object store URL", () => { expect( deleteCredentials( - "s3+https://AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY@gateway.storjshare.io/testbucket", - ), + "s3+https://AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY@gateway.storjshare.io/testbucket" + ) ).toBe("s3+https://***:***@gateway.storjshare.io/testbucket"); }); it("should not modify a standard URL", () => { expect( deleteCredentials( - "https://s3.amazonaws.com/my-bucket/path/filename.mp4", - ), + "https://s3.amazonaws.com/my-bucket/path/filename.mp4" + ) ).toBe("https://s3.amazonaws.com/my-bucket/path/filename.mp4"); }); it("should not modify incorrect object store URL", () => { expect( deleteCredentials( - "s3+https://USERNAME_NO_PASSWORD:@gateway.storjshare.io/testbucket", - ), + "s3+https://USERNAME_NO_PASSWORD:@gateway.storjshare.io/testbucket" + ) ).toBe( - "s3+https://USERNAME_NO_PASSWORD:@gateway.storjshare.io/testbucket", + "s3+https://USERNAME_NO_PASSWORD:@gateway.storjshare.io/testbucket" ); }); }); @@ -196,7 +196,7 @@ describe("convert w3 storage to object store URL", () => { }, }; expect(toWeb3StorageUrl(storageObj)).toBe( - "w3s://EaJlcm9vdHOAZ3ZlcnNpb24BmgIBcRIg2uxHpcPYSWNtifMKFkPC7IEDvFDCxCd3ADViv0coV7SnYXNYRO2hA0AnblHEW38s3lSlcwaDjPn-_@/", + "w3s://EaJlcm9vdHOAZ3ZlcnNpb24BmgIBcRIg2uxHpcPYSWNtifMKFkPC7IEDvFDCxCd3ADViv0coV7SnYXNYRO2hA0AnblHEW38s3lSlcwaDjPn-_@/" ); }); @@ -209,7 +209,7 @@ describe("convert w3 storage to object store URL", () => { }, }; expect(toWeb3StorageUrl(storageObj)).toBe( - "w3s://EaJlcm9vdHOAZ3ZlcnNpb24BmgIBcRIg2uxHpcPYSWNtifMKFkPC7IEDvFDCxCd3ADViv0coV7SnYXNYRO2hA0AnblHEW38s3lSlcwaDjPn-_@/", + "w3s://EaJlcm9vdHOAZ3ZlcnNpb24BmgIBcRIg2uxHpcPYSWNtifMKFkPC7IEDvFDCxCd3ADViv0coV7SnYXNYRO2hA0AnblHEW38s3lSlcwaDjPn-_@/" ); }); @@ -219,7 +219,7 @@ describe("convert w3 storage to object store URL", () => { }; // @ts-expect-error expect(() => toWeb3StorageUrl(storageObj)).toThrow( - "undefined property 'credentials.proof'", + "undefined property 'credentials.proof'" ); }); @@ -230,7 +230,7 @@ describe("convert w3 storage to object store URL", () => { }; // @ts-expect-error expect(() => toWeb3StorageUrl(storageObj)).toThrow( - "undefined property 'credentials.proof'", + "undefined property 'credentials.proof'" ); }); diff --git a/packages/api/src/controllers/helpers.ts b/packages/api/src/controllers/helpers.ts index 20a481753b..ae0e626a7f 100644 --- a/packages/api/src/controllers/helpers.ts +++ b/packages/api/src/controllers/helpers.ts @@ -48,7 +48,7 @@ export async function hash(password: string, salt: string) { passphraseKey, { name: "PBKDF2" }, false, - ["deriveBits", "deriveKey"], + ["deriveBits", "deriveKey"] ); const webKey = await crypto.subtle.deriveKey( { @@ -71,7 +71,7 @@ export async function hash(password: string, salt: string) { true, // this web crypto object will only be allowed for these functions - ["encrypt", "decrypt"], + ["encrypt", "decrypt"] ); const buffer = await crypto.subtle.exportKey("raw", webKey); @@ -137,7 +137,7 @@ function bytesToHexString(bytes: Uint8Array, separate = false) { export function makeNextHREF(req: express.Request, nextCursor: string) { let baseUrl = new URL( - `${req.protocol}://${req.get("host")}${req.originalUrl}`, + `${req.protocol}://${req.get("host")}${req.originalUrl}` ); let next = baseUrl; next.searchParams.set("cursor", nextCursor); @@ -210,7 +210,7 @@ export type OSS3Config = S3ClientConfig & { }; export async function getObjectStoreS3Config( - os: ObjectStore, + os: ObjectStore ): Promise { const url = new URL(os.url); let protocol = url.protocol; @@ -398,8 +398,8 @@ export async function sendgridEmailPaymentFailed({ console.log(` sending payment failed email to=${email} for user=${ - user.id - } message=${JSON.stringify(msg)} + user.id + } message=${JSON.stringify(msg)} `); SendgridMail.setApiKey(sendgridApiKey); @@ -415,14 +415,14 @@ export function sendgridValidateEmail(email: string, validationApiKey: string) { sendgridValidateEmailAsync(email, validationApiKey).catch((error) => { console.error( `Email address validation error email="${email}" error=`, - error, + error ); }); } export async function sendgridValidateEmailAsync( email: string, - validationApiKey: string, + validationApiKey: string ) { SendgridClient.setApiKey(validationApiKey); const [response, body] = await SendgridClient.request({ @@ -437,7 +437,7 @@ export async function sendgridValidateEmailAsync( const rawBody = JSON.stringify(JSON.stringify(body)); console.log( `Email address validation result ` + - `email="${email}" status=${statusCode} verdict=${verdict} body=${rawBody}`, + `email="${email}" status=${statusCode} verdict=${verdict} body=${rawBody}` ); return verdict; } @@ -488,7 +488,7 @@ export function parseOrder(fieldsMap: FieldsMap, val: string) { export function parseFilters( fieldsMap: FieldsMap, - val: string, + val: string ): SQLStatement[] { try { return parseFiltersRaw(fieldsMap, val); @@ -530,21 +530,19 @@ function parseFiltersRaw(fieldsMap: FieldsMap, val: string): SQLStatement[] { throw new Error( `expected boolean value for field "${ filter.id - }", got: ${JSON.stringify(filter.value)}`, + }", got: ${JSON.stringify(filter.value)}` ); } q.push( sql``.append( `coalesce((${fv.val})::boolean, FALSE) IS ${ filter.value ? "TRUE" : "FALSE" - } `, - ), + } ` + ) ); } else if (fv.type === "full-text") { q.push( - sql`` - .append(fv.val) - .append(sql` ILIKE ${"%" + filter.value + "%"}`), + sql``.append(fv.val).append(sql` ILIKE ${"%" + filter.value + "%"}`) ); } else if (isObject(filter.value)) { // if value is a dictionary @@ -572,7 +570,7 @@ function parseFiltersRaw(fieldsMap: FieldsMap, val: string): SQLStatement[] { sql`` .append(fv.val) .append(comparison) - .append(sql` ${filter.value[key]}`), + .append(sql` ${filter.value[key]}`) ); }); } else { @@ -665,7 +663,7 @@ export const triggerCatalystPullStart = url.searchParams.set("lon", lon.toString()); playbackUrl = url.toString(); console.log( - `triggering catalyst pull start for streamId=${stream.id} playbackId=${stream.playbackId} lat=${lat} lon=${lon} pullRegion=${stream.pullRegion}, playbackUrl=${playbackUrl}`, + `triggering catalyst pull start for streamId=${stream.id} playbackId=${stream.playbackId} lat=${lat} lon=${lon} pullRegion=${stream.pullRegion}, playbackUrl=${playbackUrl}` ); } @@ -691,7 +689,7 @@ export const triggerCatalystPullStart = stream.id } playbackUrl=${playbackUrl} status=${ res.status - } error=${JSON.stringify(body)}`, + } error=${JSON.stringify(body)}` ); await sleep(250); } @@ -701,12 +699,12 @@ export const triggerCatalystPullStart = export const triggerCatalystStreamStopSessions = ( req: Request, - playback_id: string, + playback_id: string ) => triggerCatalystEvent(req, { resource: "stopSessions", playback_id }); export const triggerCatalystStreamUpdated = ( req: Request, - playback_id: string, + playback_id: string ) => triggerCatalystEvent(req, { resource: "stream", playback_id }); async function triggerCatalystEvent( @@ -714,7 +712,7 @@ async function triggerCatalystEvent( payload: { resource: "stream" | "nuke" | "stopSessions"; playback_id: string; - }, + } ) { const { catalystBaseUrl } = req.config; @@ -732,7 +730,7 @@ async function triggerCatalystEvent( throw new Error( `error dispatching event to catalyst url=${url} payload=${payload} status=${ res.status - } error=${await res.text()}`, + } error=${await res.text()}` ); } } @@ -754,7 +752,7 @@ export function getProjectId(req: Request): string { export async function addDefaultProjectId( body: any, req: Request, - res: Response, + res: Response ) { const deepClone = (obj) => { return JSON.parse(JSON.stringify(obj)); @@ -808,7 +806,7 @@ export async function addDefaultProjectId( enrichResponse(subItem); } } - }), + }) ); } }; diff --git a/packages/api/src/controllers/ingest.js b/packages/api/src/controllers/ingest.js index ea9a4ef03d..dcde31f506 100644 --- a/packages/api/src/controllers/ingest.js +++ b/packages/api/src/controllers/ingest.js @@ -16,7 +16,7 @@ app.get( ingestPoints = await req.getIngest(req); } res.json(shuffle(ingestPoints)); - }, + } ); export default app; diff --git a/packages/api/src/controllers/live-proxy.js b/packages/api/src/controllers/live-proxy.js index b7ac6d4007..0d80eee984 100644 --- a/packages/api/src/controllers/live-proxy.js +++ b/packages/api/src/controllers/live-proxy.js @@ -49,7 +49,7 @@ export default ({ client.put(`${id}.m3u8/part/${hostname}`, manifestText), ...parser.manifest.playlists.map(async (playlist) => { const manifestRes = await fetch( - `${upstreamBroadcaster}/stream/${playlist.uri}`, + `${upstreamBroadcaster}/stream/${playlist.uri}` ); const mediaManifest = await manifestRes.text(); await client.put(`${playlist.uri}/part/${hostname}`, mediaManifest); diff --git a/packages/api/src/controllers/multistream.test.ts b/packages/api/src/controllers/multistream.test.ts index c44206d2af..0312d8eb2e 100644 --- a/packages/api/src/controllers/multistream.test.ts +++ b/packages/api/src/controllers/multistream.test.ts @@ -67,7 +67,7 @@ describe("controllers/multistream-target", () => { expect(res.status).toBe(404); } const res = await client.get( - `/multistream/target?userId=${nonAdminUser.id}`, + `/multistream/target?userId=${nonAdminUser.id}` ); expect(res.status).toBe(200); expect(await res.json()).toEqual([{ ...userMsTarget, url: undefined }]); @@ -135,13 +135,13 @@ describe("controllers/multistream-target", () => { let cursor = ""; for (let page = 1; page <= 3; page++) { const res = await client.get( - `/multistream/target?userId=${nonAdminUser.id}&limit=5&cursor=${cursor}`, + `/multistream/target?userId=${nonAdminUser.id}&limit=5&cursor=${cursor}` ); expect(res.status).toBe(200); const link = res.headers.get("link"); expect(link).toEqual( - page < 3 ? expect.stringContaining("cursor=") : null, + page < 3 ? expect.stringContaining("cursor=") : null ); cursor = getNextCursor(link); @@ -191,7 +191,7 @@ describe("controllers/multistream-target", () => { }); expect(res.status).toBe(204); const patched = db.multistreamTarget.cleanWriteOnlyResponse( - await db.multistreamTarget.get(created.id), + await db.multistreamTarget.get(created.id) ); expect(patched).not.toEqual(created); expect(patched).toEqual({ ...created, disabled: true }); @@ -335,7 +335,7 @@ describe("controllers/multistream-target", () => { it("should get all multistream targets for another user with admin API key", async () => { client.apiKey = adminApiKey; let res = await client.get( - `/multistream/target?userId=${nonAdminUser.id}`, + `/multistream/target?userId=${nonAdminUser.id}` ); expect(res.status).toBe(200); @@ -346,7 +346,7 @@ describe("controllers/multistream-target", () => { it("should throw unauthorized error when using invalid API key", async () => { client.apiKey = "random_key"; const res = await client.get( - `/multistream/target?userId=${nonAdminUser.id}`, + `/multistream/target?userId=${nonAdminUser.id}` ); expect(res.status).toBe(401); }); @@ -362,12 +362,12 @@ describe("controllers/multistream-target", () => { client.apiKey = tokenId; const res = await client.get( - `/multistream/target?userId=${nonAdminUser.id}`, + `/multistream/target?userId=${nonAdminUser.id}` ); expect(res.status).toBe(401); const errJson = await res.json(); expect(errJson.errors[0]).toEqual( - `no user found from authorization header: Bearer ${tokenId}`, + `no user found from authorization header: Bearer ${tokenId}` ); }); }); diff --git a/packages/api/src/controllers/multistream.ts b/packages/api/src/controllers/multistream.ts index f4f885553b..4816b786b2 100644 --- a/packages/api/src/controllers/multistream.ts +++ b/packages/api/src/controllers/multistream.ts @@ -36,7 +36,7 @@ function adminListQuery( limit: number, cursor: string, orderStr: string, - filters: string, + filters: string ): [SQLStatement[], FindOptions] { type ResultRow = { id: string; @@ -83,11 +83,11 @@ target.use( } if ("id" in data) { return db.multistreamTarget.cleanWriteOnlyResponse( - data as DBMultistreamTarget, + data as DBMultistreamTarget ); } return data; - }), + }) ); target.get("/", authorizer({}), async (req, res) => { @@ -126,7 +126,7 @@ target.get("/:id", authorizer({}), async (req, res) => { const data = await db.multistreamTarget.getAuthed( req.params.id, req.user.id, - isAdmin, + isAdmin ); if (!data) { return notFound(res); @@ -148,7 +148,7 @@ target.post( }); res.status(201); res.json(data); - }, + } ); target.delete("/:id", authorizer({}), async (req, res) => { @@ -191,18 +191,18 @@ target.patch( await triggerCatalystMultistreamUpdated(req, id); res.status(204); res.end(); - }, + } ); async function triggerCatalystMultistreamUpdated(req: Request, id: string) { const query = []; query.push( - `stream.data->>'userId' = '${req.user.id}' AND stream.data->'multistream'->'targets' @> '[{"id":"${id}"}]'`, + `stream.data->>'userId' = '${req.user.id}' AND stream.data->'multistream'->'targets' @> '[{"id":"${id}"}]'` ); const [streams] = await db.stream.find(query, {}); await Promise.all( - streams.map((s) => triggerCatalystStreamUpdated(req, s.playbackId)), + streams.map((s) => triggerCatalystStreamUpdated(req, s.playbackId)) ); } diff --git a/packages/api/src/controllers/object-store.test.js b/packages/api/src/controllers/object-store.test.js index 81cfb137d0..d834c20071 100644 --- a/packages/api/src/controllers/object-store.test.js +++ b/packages/api/src/controllers/object-store.test.js @@ -78,7 +78,7 @@ describe("controllers/object-stores", () => { const nonAdminUserRes = await server.store.get( `user/${nonAdminUser.id}`, - false, + false ); nonAdminUser = { ...nonAdminUserRes, emailValid: true }; await server.store.replace(nonAdminUser); @@ -142,7 +142,7 @@ describe("controllers/object-stores", () => { } const res = await client.get( - `/object-store?userId=${store.userId}&limit=11`, + `/object-store?userId=${store.userId}&limit=11` ); const objStores = await res.json(); expect(res.headers.raw().link).toBeDefined(); @@ -187,7 +187,7 @@ describe("controllers/object-stores", () => { it("should not accept missing property for creating an object store", async () => { const postMockStoreMissingProp = JSON.parse( - JSON.stringify(postMockStore), + JSON.stringify(postMockStore) ); delete postMockStoreMissingProp["url"]; const res = await client.post("/object-store", { @@ -271,7 +271,7 @@ describe("controllers/object-stores", () => { const nonAdminUserRes = await server.store.get( `user/${nonAdminUser.id}`, - false, + false ); nonAdminUser = { ...nonAdminUserRes, emailValid: true }; await server.store.replace(nonAdminUser); @@ -324,7 +324,7 @@ describe("controllers/object-stores", () => { const objStore = await res.json(); expect(res.status).toBe(401); expect(objStore.errors[0]).toBe( - `no user found from authorization header: Bearer ${tokenId}`, + `no user found from authorization header: Bearer ${tokenId}` ); }); }); diff --git a/packages/api/src/controllers/object-store.ts b/packages/api/src/controllers/object-store.ts index 69e6242d72..7cb375eeb0 100644 --- a/packages/api/src/controllers/object-store.ts +++ b/packages/api/src/controllers/object-store.ts @@ -28,7 +28,7 @@ const fieldsMap: FieldsMap = { app.get("/", authorizer({}), async (req, res) => { let { limit, all, cursor, userId, order, filters } = toStringValues( - req.query, + req.query ); if (isNaN(parseInt(limit))) { limit = undefined; @@ -126,7 +126,7 @@ app.post( res.status(403); res.json({ errors: ["store not created"] }); } - }, + } ); app.delete("/:id", authorizer({}), async (req, res) => { @@ -162,12 +162,12 @@ app.patch( const payload = req.body as ObjectStorePatchPayload; console.log( `patch object store id=${id} payload=${JSON.stringify( - JSON.stringify(payload), - )}`, + JSON.stringify(payload) + )}` ); await db.objectStore.update(id, payload); res.status(204).end(); - }, + } ); export default app; diff --git a/packages/api/src/controllers/orchestrator.ts b/packages/api/src/controllers/orchestrator.ts index f64b1bf9ba..a8df473bc1 100644 --- a/packages/api/src/controllers/orchestrator.ts +++ b/packages/api/src/controllers/orchestrator.ts @@ -16,7 +16,7 @@ const getOrchestrators = async (req: Request, res, next) => { orchestrators.map(({ address, score = defaultScore }) => ({ address, score, - })), + })) ); }; diff --git a/packages/api/src/controllers/playback.test.ts b/packages/api/src/controllers/playback.test.ts index d96a59dab6..3b814ae2b4 100644 --- a/packages/api/src/controllers/playback.test.ts +++ b/packages/api/src/controllers/playback.test.ts @@ -8,7 +8,7 @@ import { DBSession } from "../store/session-table"; import { cache } from "../store/cache"; const EXPECTED_CROSS_USER_ASSETS_CUTOFF_DATE = Date.parse( - "2023-06-06T00:00:00.000Z", + "2023-06-06T00:00:00.000Z" ); let server: TestServer; @@ -79,7 +79,7 @@ describe("controllers/playback", () => { ({ client, adminToken, nonAdminToken } = await setupUsers( server, mockAdminUserInput, - mockNonAdminUserInput, + mockNonAdminUserInput )); client.jwtAuth = nonAdminToken; @@ -87,7 +87,7 @@ describe("controllers/playback", () => { ({ client: client2, nonAdminToken: otherUserToken } = await setupUsers( server, mockAdminUserInput2, - mockNonAdminUserInput2, + mockNonAdminUserInput2 )); client2.jwtAuth = otherUserToken; @@ -115,7 +115,7 @@ describe("controllers/playback", () => { `/stream/${stream.id}/stream?sessionId=${sessionId}`, { name: "test-recording", - }, + } ); expect(res.status).toBe(201); childStream = await res.json(); diff --git a/packages/api/src/controllers/playback.ts b/packages/api/src/controllers/playback.ts index ccac50bd4a..161a1dc3c2 100644 --- a/packages/api/src/controllers/playback.ts +++ b/packages/api/src/controllers/playback.ts @@ -50,7 +50,7 @@ function newPlaybackInfo( live?: PlaybackInfo["meta"]["live"], recordingUrl?: string, withRecordings?: boolean, - thumbUrl?: string, + thumbUrl?: string ): PlaybackInfo { let playbackInfo: PlaybackInfo = { type, @@ -127,7 +127,7 @@ function newPlaybackInfo( const getAssetPlaybackInfo = async ( config: CliArgs, ingest: string, - asset: WithID, + asset: WithID ) => { const os = await db.objectStore.get(asset.objectStoreId, { useCache: true }); if (!os || os.deleted || os.disabled) { @@ -147,7 +147,7 @@ const getAssetPlaybackInfo = async ( null, asset.playbackPolicy || null, getStaticPlaybackInfo(asset, os), - getThumbsVTTUrl(asset, os), + getThumbsVTTUrl(asset, os) ); }; @@ -160,7 +160,7 @@ type PlaybackResource = { export async function getResourceByPlaybackId( id: string, user?: User, - cutoffDate?: number, + cutoffDate?: number ): Promise { let stream = await db.stream.getByPlaybackId(id); if (!stream) { @@ -197,7 +197,7 @@ async function getAttestationPlaybackInfo( ingest: string, id: string, user?: User, - cutoffDate?: number, + cutoffDate?: number ): Promise { try { if (!isExperimentSubject("attestation", user?.id)) { @@ -232,7 +232,7 @@ async function getPlaybackInfo( id: string, isCrossUserQuery: boolean, origin: string, - withRecordings?: boolean, + withRecordings?: boolean ): Promise { const cutoffDate = isCrossUserQuery ? null : CROSS_USER_ASSETS_CUTOFF_DATE; const cacheKey = `playbackInfo-${id}-user-${req.user?.id}-cutoff-${cutoffDate}`; @@ -255,7 +255,7 @@ async function getPlaybackInfo( console.log( `Returning cross-user asset for playback. ` + `userId=${req.user?.id} userEmail=${req.user?.email} origin=${origin} ` + - `assetId=${asset.id} assetUserId=${asset.userId} playbackId=${asset.playbackId}`, + `assetId=${asset.id} assetUserId=${asset.userId} playbackId=${asset.playbackId}` ); } @@ -275,13 +275,13 @@ async function getPlaybackInfo( const { user } = req; if (!user) { throw new UnauthorizedError( - `authentication is required to access recordings`, + `authentication is required to access recordings` ); } if (stream.userId !== user.id) { throw new UnauthorizedError( - `user does not have access to recordings for this content`, + `user does not have access to recordings for this content` ); } } @@ -296,7 +296,7 @@ async function getPlaybackInfo( const flvOut = await isExperimentSubject( "stream-pull-source", - req.user?.id, + req.user?.id ); return newPlaybackInfo( "live", @@ -309,7 +309,7 @@ async function getPlaybackInfo( stream.isActive ? 1 : 0, url, withRecordings, - thumbUrl, + thumbUrl ); } @@ -318,7 +318,7 @@ async function getPlaybackInfo( req.config, ingest, session, - false, + false ); if (recordingUrl) { return newPlaybackInfo("recording", recordingUrl); @@ -330,7 +330,7 @@ async function getPlaybackInfo( ingest, id, req.user, - cutoffDate, + cutoffDate ); } @@ -360,7 +360,7 @@ app.get("/:id", async (req, res) => { id, isEmbeddablePlayer, origin, - withRecordings, + withRecordings ); if (!info) { throw new NotFoundError(`No playback URL found for ${id}`); diff --git a/packages/api/src/controllers/project.ts b/packages/api/src/controllers/project.ts index 720f85c036..2c0530f810 100644 --- a/packages/api/src/controllers/project.ts +++ b/packages/api/src/controllers/project.ts @@ -24,7 +24,7 @@ const fieldsMap = { app.get("/", authorizer({}), async (req, res) => { let { limit, cursor, order, all, filters, count, allUsers } = toStringValues( - req.query, + req.query ); if (isNaN(parseInt(limit))) { @@ -106,7 +106,7 @@ app.get("/:id", authorizer({}), async (req, res) => { if (req.user.admin !== true && req.user.id !== project.userId) { throw new ForbiddenError( - "user can only request information on their own projects", + "user can only request information on their own projects" ); } diff --git a/packages/api/src/controllers/region.js b/packages/api/src/controllers/region.js index be2ad83407..9117e16a6a 100644 --- a/packages/api/src/controllers/region.js +++ b/packages/api/src/controllers/region.js @@ -14,7 +14,7 @@ function flatRegions(regions = [], halfRegionOrchestratorsUntrusted = false) { halfRegionOrchestratorsUntrusted && count++ % 2 == 0 ? 0 : defaultScore, region: reg.region, ...orch, - })), + })) ); } @@ -31,7 +31,7 @@ app.get("/", async (req, res, next) => { } return res.json( - flatRegions(regions, req.config.halfRegionOrchestratorsUntrusted), + flatRegions(regions, req.config.halfRegionOrchestratorsUntrusted) ); }); @@ -69,7 +69,7 @@ app.put( } return res.json(region); - }, + } ); app.delete( @@ -78,7 +78,7 @@ app.delete( async (req, res, next) => { await db.region.delete(req.params.region); return res.status(204); - }, + } ); export default app; diff --git a/packages/api/src/controllers/region.test.js b/packages/api/src/controllers/region.test.js index 625c8e42db..dd793de0a6 100644 --- a/packages/api/src/controllers/region.test.js +++ b/packages/api/src/controllers/region.test.js @@ -54,7 +54,7 @@ describe("controllers/region", () => { const user = await server.store.get(`user/${adminUser.id}`, false); if (!user) { - throw new Error("user not found"); + throw new Error("Account not found"); } adminUser = { ...user, admin: true, emailValid: true }; await server.store.replace(adminUser); diff --git a/packages/api/src/controllers/room.test.ts b/packages/api/src/controllers/room.test.ts index 37b74a5fa0..c337fe9f8d 100644 --- a/packages/api/src/controllers/room.test.ts +++ b/packages/api/src/controllers/room.test.ts @@ -112,7 +112,7 @@ describe("controllers/room", () => { const mockGetParticipant = jest.spyOn( roomServiceClient, - "getParticipant", + "getParticipant" ); mockGetParticipant.mockReturnValueOnce( Promise.resolve({ @@ -121,7 +121,7 @@ describe("controllers/room", () => { someOtherProp: "foo", permission: {}, joinedAt: 1, - }), + }) ); res = await client.get(`/room/${roomId}/user/${resp.id}`); expect(res.status).toBe(200); @@ -140,7 +140,7 @@ describe("controllers/room", () => { const mockRemoveParticipant = jest.spyOn( roomServiceClient, - "removeParticipant", + "removeParticipant" ); res = await client.delete(`/room/${roomId}/user/${resp.id}`); expect(res.status).toBe(204); @@ -153,12 +153,12 @@ describe("controllers/room", () => { let mockStartEgress = jest.spyOn( egressClient, - "startRoomCompositeEgress", + "startRoomCompositeEgress" ); mockStartEgress.mockReturnValueOnce( Promise.resolve({ egressId: "egress-id", - }), + }) ); let mockStopEgress = jest.spyOn(egressClient, "stopEgress"); mockStopEgress.mockReturnValueOnce(Promise.resolve(undefined)); @@ -185,7 +185,7 @@ describe("controllers/room", () => { mockListEgress.mockReturnValueOnce( Promise.resolve([ { egressId: "egress-id", status: EgressStatus.EGRESS_ACTIVE }, - ]), + ]) ); // already started so should 400 res = await client.post(`/room/${roomId}/egress`, { @@ -196,7 +196,7 @@ describe("controllers/room", () => { mockListEgress.mockReturnValueOnce( Promise.resolve([ { egressId: "egress-id", status: EgressStatus.EGRESS_ACTIVE }, - ]), + ]) ); res = await client.delete(`/room/${roomId}/egress`); expect(res.status).toBe(204); diff --git a/packages/api/src/controllers/room.ts b/packages/api/src/controllers/room.ts index 13c6df7875..f3fecb6365 100644 --- a/packages/api/src/controllers/room.ts +++ b/packages/api/src/controllers/room.ts @@ -33,7 +33,7 @@ app.post("/", authorizer({}), async (req, res) => { const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); await svc.createRoom({ name: id, @@ -99,7 +99,7 @@ app.delete("/:roomId", authorizer({}), async (req, res) => { const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); try { await svc.deleteRoom(req.params.roomId); @@ -126,7 +126,7 @@ app.post( const egressClient = new EgressClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); const currentEgress = await egressClient.listEgress({ roomName: req.params.roomId, @@ -140,7 +140,7 @@ app.post( const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); const rooms = await svc.listRooms([req.params.roomId]); if (rooms.length < 1) { @@ -170,10 +170,10 @@ app.post( }, }); console.log( - `egress started. userId=${req.user.id} roomId=${req.params.roomId} streamId=${req.body.streamId}`, + `egress started. userId=${req.user.id} roomId=${req.params.roomId} streamId=${req.body.streamId}` ); res.status(204).end(); - }, + } ); app.delete("/:roomId/egress", authorizer({}), async (req, res) => { @@ -183,7 +183,7 @@ app.delete("/:roomId/egress", authorizer({}), async (req, res) => { const egressClient = new EgressClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); const currentEgress = await egressClient.listEgress({ roomName: req.params.roomId, @@ -195,7 +195,7 @@ app.delete("/:roomId/egress", authorizer({}), async (req, res) => { found = true; await egressClient.stopEgress(egress.egressId); console.log( - `egress stopped. userId=${req.user.id} roomId=${req.params.roomId}`, + `egress stopped. userId=${req.user.id} roomId=${req.params.roomId}` ); } } @@ -230,7 +230,7 @@ app.post( identity: id, ttl: 5 * 60, metadata: req.body.metadata, - }, + } ); at.addGrant({ roomJoin: true, @@ -251,7 +251,7 @@ app.post( token, token: token, }); - }, + } ); app.delete("/:roomId/user/:participantId", authorizer({}), async (req, res) => { @@ -260,7 +260,7 @@ app.delete("/:roomId/user/:participantId", authorizer({}), async (req, res) => { const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); try { await svc.removeParticipant(req.params.roomId, req.params.participantId); @@ -280,11 +280,11 @@ app.get("/:roomId/user/:participantId", authorizer({}), async (req, res) => { const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); const participant = await svc.getParticipant( req.params.roomId, - req.params.participantId, + req.params.participantId ); res.status(200); @@ -312,7 +312,7 @@ app.put( const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); const permissions: Partial = { @@ -324,17 +324,17 @@ app.put( req.params.roomId, req.params.participantId, req.body.metadata, - permissions as ParticipantPermission, + permissions as ParticipantPermission ); res.status(204).end(); - }, + } ); // Implement a webhook handler to receive webhooks from Livekit to update our state with room and participant details. app.post("/webhook", express.raw({ type: "*/*" }), async (req, res) => { const receiver = new WebhookReceiver( req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); // event is a WebhookEvent object @@ -343,7 +343,7 @@ app.post("/webhook", express.raw({ type: "*/*" }), async (req, res) => { event = receiver.receive(req.body, req.get("Authorization")); } catch (e) { console.log( - `failed to receive room webhook. auth=${req.get("Authorization")}`, + `failed to receive room webhook. auth=${req.get("Authorization")}` ); throw e; } @@ -368,7 +368,7 @@ app.post("/webhook", express.raw({ type: "*/*" }), async (req, res) => { const svc = new RoomServiceClient( req.config.livekitHost, req.config.livekitApiKey, - req.config.livekitSecret, + req.config.livekitSecret ); const participants = await svc.listParticipants(roomId); diff --git a/packages/api/src/controllers/session.ts b/packages/api/src/controllers/session.ts index e394a93912..a26b2db78a 100644 --- a/packages/api/src/controllers/session.ts +++ b/packages/api/src/controllers/session.ts @@ -83,7 +83,7 @@ app.get("/", authorizer({}), async (req, res, next) => { query.push( sql`coalesce(session.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); } } @@ -148,14 +148,8 @@ app.get("/", authorizer({}), async (req, res, next) => { } let sessions = await Promise.all( output.map(async (session) => - toExternalSession( - req.config, - session, - ingest, - !!forceUrl, - req.user.admin, - ), - ), + toExternalSession(req.config, session, ingest, !!forceUrl, req.user.admin) + ) ); res.json(sessions); }); @@ -179,7 +173,7 @@ app.get("/:id", authorizer({}), async (req, res) => { const { url } = await buildRecordingUrl( session, req.config.recordCatalystObjectStoreId, - req.config.secondaryRecordObjectStoreId, + req.config.secondaryRecordObjectStoreId ); originalRecordingUrl = url; session.sourceRecordingUrl = originalRecordingUrl; @@ -192,7 +186,7 @@ app.get("/:id", authorizer({}), async (req, res) => { session, ingest, false, - req.user.admin, + req.user.admin ); res.json(session); @@ -216,7 +210,7 @@ export async function toExternalSession( obj: DBSession, ingest: string, forceUrl = false, - isAdmin = false, + isAdmin = false ): Promise { obj = await withRecordingFields(config, ingest, obj, forceUrl); if (!isAdmin) { @@ -256,14 +250,14 @@ export async function getRunningRecording(content: DBStream, req: Request) { return await buildRecordingUrl( session, req.config.recordCatalystObjectStoreId, - req.config.secondaryRecordObjectStoreId, + req.config.secondaryRecordObjectStoreId ); } export async function buildRecordingUrl( session: DBSession, recordCatalystObjectStoreId: string, - secondaryRecordObjectStoreId: string, + secondaryRecordObjectStoreId: string ) { return ( (await buildSingleRecordingUrl(session, recordCatalystObjectStoreId)) ?? @@ -278,7 +272,7 @@ export async function buildRecordingUrl( async function buildSingleRecordingUrl( session: DBSession, - objectStoreId: string, + objectStoreId: string ) { const os = await db.objectStore.get(objectStoreId, { useCache: true }); diff --git a/packages/api/src/controllers/signing-key.test.ts b/packages/api/src/controllers/signing-key.test.ts index 7557d260ca..7f07f8d96d 100644 --- a/packages/api/src/controllers/signing-key.test.ts +++ b/packages/api/src/controllers/signing-key.test.ts @@ -76,7 +76,7 @@ describe("controllers/signing-key", () => { let otherSigningKey = await res.json(); otherPublicKey = Buffer.from( otherSigningKey.publicKey, - "base64", + "base64" ).toString(); // create a new project client.jwtAuth = nonAdminToken; @@ -121,7 +121,7 @@ describe("controllers/signing-key", () => { client.jwtAuth = nonAdminToken; client.apiKey = null; let sigKeyWithoutProject = await client.post( - "/access-control/signing-key", + "/access-control/signing-key" ); expect(sigKeyWithoutProject.status).toBe(201); client.jwtAuth = ""; @@ -157,7 +157,7 @@ describe("controllers/signing-key", () => { expect(() => jwt.verify(token, decodedPublicKey)).not.toThrow(); expect(() => jwt.verify(token, otherPublicKey)).toThrow( - JsonWebTokenError, + JsonWebTokenError ); }); @@ -172,7 +172,7 @@ describe("controllers/signing-key", () => { { disabled: true, name: "My test signing key 1", - }, + } ); expect(res.status).toBe(204); res = await client.get(`/access-control/signing-key/${signingKey.id}`); @@ -197,7 +197,7 @@ describe("controllers/signing-key", () => { expect(sigkey.status).toBe(201); let signingKey = await sigkey.json(); let res = await client.delete( - `/access-control/signing-key/${signingKey.id}`, + `/access-control/signing-key/${signingKey.id}` ); expect(res.status).toBe(204); res = await client.get(`/access-control/signing-key/${signingKey.id}`); diff --git a/packages/api/src/controllers/signing-key.ts b/packages/api/src/controllers/signing-key.ts index ab1c5c5f51..e1e05768e5 100644 --- a/packages/api/src/controllers/signing-key.ts +++ b/packages/api/src/controllers/signing-key.ts @@ -49,9 +49,9 @@ async function generateSigningKeys() { }, }, (err, publicKey, privateKey) => - err ? reject(err) : resolve({ publicKey, privateKey }), + err ? reject(err) : resolve({ publicKey, privateKey }) ); - }, + } ); return keypair; } @@ -62,7 +62,7 @@ signingKeyApp.use(mung.jsonAsync(addDefaultProjectId)); signingKeyApp.get("/", authorizer({}), async (req, res) => { let { limit, cursor, all, allUsers, order, filters, count } = toStringValues( - req.query, + req.query ); if (isNaN(parseInt(limit))) { limit = undefined; @@ -115,7 +115,7 @@ signingKeyApp.get("/", authorizer({}), async (req, res) => { query.push( sql`coalesce(signing_key.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); let fields = " signing_key.id as id, signing_key.data as data"; @@ -204,7 +204,7 @@ signingKeyApp.post( res.status(201); res.json(createdSigningKey); - }, + } ); signingKeyApp.delete("/:id", authorizer({}), async (req, res) => { @@ -235,12 +235,12 @@ signingKeyApp.patch( const payload = req.body as SigningKeyPatchPayload; console.log( `patch signing key id=${id} payload=${JSON.stringify( - JSON.stringify(payload), - )}`, + JSON.stringify(payload) + )}` ); await db.signingKey.update(id, payload); res.status(204).end(); - }, + } ); signingKeyApp.get( @@ -251,7 +251,7 @@ signingKeyApp.get( const adminKey = Buffer.from( req.config.accessControlAdminPrivkey, - "base64", + "base64" ); const pubkey = req.config.accessControlAdminPubkey; @@ -284,7 +284,7 @@ signingKeyApp.get( const token = sign(payload, adminKey, options); return res.send({ token }); - }, + } ); export default signingKeyApp; diff --git a/packages/api/src/controllers/stream-proxy.js b/packages/api/src/controllers/stream-proxy.js index d9fb1d4e0a..1b431f66e1 100644 --- a/packages/api/src/controllers/stream-proxy.js +++ b/packages/api/src/controllers/stream-proxy.js @@ -18,7 +18,7 @@ app.get("/:streamId.m3u8", async (req, res) => { await req.store.get(`stream/${streamId}`); const broadcasters = await req.getBroadcasters(); const urls = broadcasters.map( - ({ address }) => `${address}/stream/${streamId}.m3u8`, + ({ address }) => `${address}/stream/${streamId}.m3u8` ); const mergedM3U8 = await composeM3U8(urls); if (mergedM3U8 === null) { diff --git a/packages/api/src/controllers/stream.test.ts b/packages/api/src/controllers/stream.test.ts index a2897bb354..07395cae8a 100644 --- a/packages/api/src/controllers/stream.test.ts +++ b/packages/api/src/controllers/stream.test.ts @@ -277,7 +277,7 @@ describe("controllers/stream", () => { expect(res.status).toBe(400); const json = await res.json(); expect(json.errors[0]).toContain( - "multistream target profile not found", + "multistream target profile not found" ); }); @@ -304,7 +304,7 @@ describe("controllers/stream", () => { expect(res.status).toBe(400); const json = await res.json(); expect(json.errors[0]).toContain( - `must have either an "id" or a "spec"`, + `must have either an "id" or a "spec"` ); }); @@ -324,7 +324,7 @@ describe("controllers/stream", () => { expect(res.status).toBe(400); const json = await res.json(); expect(json.errors[0]).toContain( - `must have either an "id" or a "spec"`, + `must have either an "id" or a "spec"` ); }); @@ -347,7 +347,7 @@ describe("controllers/stream", () => { expect(res.status).toBe(400); const json = await res.json(); expect(json.errors[0]).toContain( - `multistream target {id,profile} must be unique`, + `multistream target {id,profile} must be unique` ); // Should allow same ID if using different profiles @@ -627,7 +627,7 @@ describe("controllers/stream", () => { promises.push( client.post(`/stream/${stream.id}/lockPull`, { host: `host-${i}`, - }), + }) ); } const resPulls = await Promise.all(promises); @@ -653,7 +653,7 @@ describe("controllers/stream", () => { // Request pull lock should succeed, because the lock lease has expired (so we assume the stream is not being pulled at the moment) const resLockPull2 = await client.post( `/stream/${stream.id}/lockPull`, - { leaseTimeout: 1 }, + { leaseTimeout: 1 } ); expect(resLockPull2.status).toBe(204); }); @@ -675,7 +675,7 @@ describe("controllers/stream", () => { // Request pull lock should succeed, because the lock lease has expired (so we assume the stream is not being pulled at the moment) const resLockPull2 = await client.post( `/stream/${stream.id}/lockPull`, - { host }, + { host } ); expect(resLockPull2.status).toBe(204); }); @@ -698,7 +698,7 @@ describe("controllers/stream", () => { // Request pull lock should succeed, because the lock lease has expired (so we assume the stream is not being pulled at the moment) const resLockPull2 = await client.post( `/stream/${stream.id}/lockPull`, - { host: "host-2" }, + { host: "host-2" } ); expect(resLockPull2.status).toBe(204); }); @@ -727,7 +727,7 @@ describe("controllers/stream", () => { it("should fail to dedup streams by a random key", async () => { let res = await client.put( "/stream/pull?key=invalid", - postMockPullStream, + postMockPullStream ); expect(res.status).toBe(400); const errors = await res.json(); @@ -739,7 +739,7 @@ describe("controllers/stream", () => { it("should fail to dedup streams by creatorId if not provided", async () => { let res = await client.put( "/stream/pull?key=creatorId", - postMockPullStream, + postMockPullStream ); expect(res.status).toBe(400); const errors = await res.json(); @@ -839,7 +839,7 @@ describe("controllers/stream", () => { it("should resolve pull url and region from existing stream", async () => { expect(resolvePullUrlFromExistingStreams([])).toStrictEqual(null); expect( - resolvePullUrlFromExistingStreams([{ id: "id-1", name: "stream-1" }]), + resolvePullUrlFromExistingStreams([{ id: "id-1", name: "stream-1" }]) ).toStrictEqual(null); expect( resolvePullUrlFromExistingStreams([ @@ -850,7 +850,7 @@ describe("controllers/stream", () => { pullLockedBy: "fra-prod-catalyst-1.lp-playback.studio", pullLockedAt: 1714997385837, }, - ]), + ]) ).toStrictEqual(null); expect( resolvePullUrlFromExistingStreams([ @@ -861,7 +861,7 @@ describe("controllers/stream", () => { pullLockedBy: "fra-prod-catalyst-1.lp-playback.studio", pullLockedAt: Date.now() - 2 * 60 * 1000, }, - ]), + ]) ).toStrictEqual(null); expect( resolvePullUrlFromExistingStreams([ @@ -872,7 +872,7 @@ describe("controllers/stream", () => { pullLockedBy: "fra-prod-catalyst-1.lp-playback.studio", pullLockedAt: Date.now(), }, - ]), + ]) ).toStrictEqual(null); expect( resolvePullUrlFromExistingStreams([ @@ -883,7 +883,7 @@ describe("controllers/stream", () => { pullLockedBy: "", pullLockedAt: Date.now(), }, - ]), + ]) ).toStrictEqual(null); expect( resolvePullUrlFromExistingStreams([ @@ -894,7 +894,7 @@ describe("controllers/stream", () => { pullLockedBy: "fra-prod-catalyst-1.lp-playback.studio", pullLockedAt: Date.now(), }, - ]), + ]) ).toStrictEqual({ pullUrl: "https://fra-prod-catalyst-1.lp-playback.studio:443/hls/video+", @@ -910,7 +910,7 @@ describe("controllers/stream", () => { pullLockedAt: Date.now() - 2 * 60 * 1000, lastSeen: Date.now(), }, - ]), + ]) ).toStrictEqual({ pullUrl: "https://fra-prod-catalyst-1.lp-playback.studio:443/hls/video+", @@ -922,56 +922,56 @@ describe("controllers/stream", () => { expect( extractUrlFrom( "https://sto-prod-catalyst-0.lp-playback.studio:443/hls/video+ingest-12345-67890/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe("https://sto-prod-catalyst-0.lp-playback.studio:443/hls/video+"); expect( extractUrlFrom( "https://mos2-prod-catalyst-0.lp-playback.studio:443/hls/video+ingest-12345-67890/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe( - "https://mos2-prod-catalyst-0.lp-playback.studio:443/hls/video+", + "https://mos2-prod-catalyst-0.lp-playback.studio:443/hls/video+" ); expect( extractUrlFrom( "https://fra-staging-staging-catalyst-0.livepeer.monster:443/hls/video+ingest-12345-67890/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe( - "https://fra-staging-staging-catalyst-0.livepeer.monster:443/hls/video+", + "https://fra-staging-staging-catalyst-0.livepeer.monster:443/hls/video+" ); expect( extractUrlFrom( "https://fra-staging-staging-catalyst-0.livepeer.monster:443/hls/video+other-playback/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe(null); }); it("should extract region from redirected playback url", async () => { expect( extractRegionFrom( "https://sto-prod-catalyst-0.lp-playback.studio:443/hls/video+ingest-12345-67890/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe("sto"); expect( extractRegionFrom( "https://mos2-prod-catalyst-0.lp-playback.studio:443/hls/video+ingest-12345-67890/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe("mos2"); expect( extractRegionFrom( "https://fra-staging-staging-catalyst-0.livepeer.monster:443/hls/video+ingest-12345-67890/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe("fra-staging"); expect( extractRegionFrom( "https://fra-staging-staging-catalyst-0.livepeer.monster:443/hls/video+other-playback/index.m3u8", - "12345-67890", - ), + "12345-67890" + ) ).toBe(null); }); }); @@ -1019,7 +1019,7 @@ describe("controllers/stream", () => { profile: "source", videoOnly: false, spec: { name: "target-name", url: "rtmp://test/test" }, - }, + } ); expect(res2.status).toBe(200); const body = await res2.json(); @@ -1029,7 +1029,7 @@ describe("controllers/stream", () => { describe("set active and heartbeat", () => { const callSetActive = async ( streamId: string, - payload: StreamSetActivePayload, + payload: StreamSetActivePayload ) => { const res = await client.put(`/stream/${streamId}/setactive`, payload); expect(res.status).toBe(204); @@ -1273,7 +1273,7 @@ describe("controllers/stream", () => { expect(res.status).toBe(400); const json = await res.json(); expect(json.errors[0]).toContain( - "recordingSpec is only supported with record=true", + "recordingSpec is only supported with record=true" ); }); @@ -1471,7 +1471,7 @@ describe("controllers/stream", () => { expect(res.status).toBe(400); const json = await res.json(); expect(json.errors[0]).toContain( - "recordingSpec is only supported with record=true", + "recordingSpec is only supported with record=true" ); }); @@ -1671,7 +1671,7 @@ describe("controllers/stream", () => { const testBasic = async ( userPassword: string, statusCode: number, - error?: string, + error?: string ) => { client.jwtAuth = undefined; client.basicAuth = userPassword; @@ -1695,7 +1695,7 @@ describe("controllers/stream", () => { await testBasic( `${nonAdminUser.id}:${adminApiKey}`, 401, - expect.stringMatching(/no token .+ found/), + expect.stringMatching(/no token .+ found/) ); }); @@ -1703,7 +1703,7 @@ describe("controllers/stream", () => { await testBasic( `${nonAdminUser.id}:${nonAdminApiKey}`, 403, - expect.stringContaining("admin"), + expect.stringContaining("admin") ); }); }); @@ -1736,7 +1736,7 @@ describe("controllers/stream", () => { const res = await client.post("/stream/hook/health", payload); expect(res.status).toBe(204); const stream = await server.db.stream.getByPlaybackId( - payload.stream_name.split("+", 2)[1], + payload.stream_name.split("+", 2)[1] ); return stream; }; @@ -1893,7 +1893,7 @@ describe("controllers/stream", () => { hookPayload = req.body; hookSem.release(); res.status(204).end(); - }, + } ); genMockWebhook = () => ({ id: uuid(), @@ -2066,7 +2066,7 @@ describe("controllers/stream", () => { `/stream/${stream.id}/stream?sessionId=${sessionId}`, { name: `video+${stream.playbackId}`, - }, + } ); expect(res.status).toBe(201); const child: Stream = await res.json(); @@ -2096,7 +2096,7 @@ describe("controllers/stream", () => { `/stream/${stream.id}/stream?sessionId=${sessionId}`, { name: `video+${stream.playbackId}`, - }, + } ); expect(res.status).toBe(201); const child: Stream = await res.json(); @@ -2227,7 +2227,7 @@ describe("controllers/stream", () => { profile: "H264ConstrainedHigh", ...profile, }; - }), + }) ); } }); @@ -2276,7 +2276,7 @@ describe("controllers/stream", () => { { ...smallStream, name: "stream1", - }, + } ); expect(res.status).toBe(201); let stream1 = await res.json(); @@ -2336,7 +2336,7 @@ describe("controllers/stream", () => { { ...smallStream, name: "stream2", - }, + } ); expect(res.status).toBe(201); let stream2 = await res.json(); @@ -2403,10 +2403,10 @@ describe("controllers/stream", () => { expect(sessions).toHaveLength(1); expect(sessions[0].id).toEqual(sessionId); expect(sessions[0].recordingUrl).toEqual( - "http://example-public/playback_id/output.m3u8", + "http://example-public/playback_id/output.m3u8" ); expect(sessions[0].mp4Url).toEqual( - "http://example-public/playback_id/output.mp4", + "http://example-public/playback_id/output.mp4" ); }); @@ -2440,7 +2440,7 @@ describe("controllers/stream", () => { `/stream/${parent.id}/stream?sessionId=${sessionId}`, { name: "session1", - }, + } ); expect(res.status).toBe(201); const childStream = await res.json(); diff --git a/packages/api/src/controllers/stream.ts b/packages/api/src/controllers/stream.ts index 814b7ccf4e..4cbef19c58 100644 --- a/packages/api/src/controllers/stream.ts +++ b/packages/api/src/controllers/stream.ts @@ -126,18 +126,18 @@ app.use(mung.jsonAsync(addDefaultProjectId)); async function validateMultistreamTarget( userId: string, profileNames: Set, - target: MultistreamTargetRef, + target: MultistreamTargetRef ): Promise> { const { profile, id, spec } = target; if (!profileNames.has(profile)) { const available = JSON.stringify([...profileNames]); throw new BadRequestError( - `multistream target profile not found: "${profile}". available: ${available}`, + `multistream target profile not found: "${profile}". available: ${available}` ); } if (!!spec === !!id) { throw new BadRequestError( - `multistream target must have either an "id" or a "spec"`, + `multistream target must have either an "id" or a "spec"` ); } if (id) { @@ -174,7 +174,7 @@ function toProfileNames(profiles: Profile[]): Set { async function validateMultistreamOpts( userId: string, profiles: Profile[], - multistream: MultistreamOptions, + multistream: MultistreamOptions ): Promise { const profileNames = toProfileNames(profiles); if (!multistream?.targets) { @@ -182,8 +182,8 @@ async function validateMultistreamOpts( } const targets = await Promise.all( multistream.targets.map((t) => - validateMultistreamTarget(userId, profileNames, t), - ), + validateMultistreamTarget(userId, profileNames, t) + ) ); const uniqueIds = new Set(targets.map((t) => `${t.profile} -> ${t.id}`)); if (uniqueIds.size !== targets.length) { @@ -194,7 +194,7 @@ async function validateMultistreamOpts( async function validateStreamPlaybackPolicy( playbackPolicy: DBStream["playbackPolicy"], - req: Request, + req: Request ) { if ( playbackPolicy?.type === "lit_signing_condition" || @@ -202,19 +202,19 @@ async function validateStreamPlaybackPolicy( playbackPolicy?.unifiedAccessControlConditions ) { throw new BadRequestError( - `playbackPolicy type "lit_signing_condition" with a resourceId or unifiedAccessControlConditions is not supported for streams`, + `playbackPolicy type "lit_signing_condition" with a resourceId or unifiedAccessControlConditions is not supported for streams` ); } if (playbackPolicy?.type == "webhook") { let webhook = await db.webhook.get(playbackPolicy.webhookId); if (!webhook || webhook.deleted) { throw new BadRequestError( - `webhook ${playbackPolicy.webhookId} not found`, + `webhook ${playbackPolicy.webhookId} not found` ); } if (!hasAccessToResource(req, webhook)) { throw new BadRequestError( - `webhook ${playbackPolicy.webhookId} not found`, + `webhook ${playbackPolicy.webhookId} not found` ); } const allowedOrigins = playbackPolicy?.allowedOrigins; @@ -237,7 +237,7 @@ async function validateStreamPlaybackPolicy( const allowedOriginsValid = allowedOrigins.every(isValidOrigin); if (!allowedOriginsValid) { throw new BadRequestError( - "allowedOrigins must be a list of valid origins ://:", + "allowedOrigins must be a list of valid origins ://:" ); } } @@ -253,7 +253,7 @@ async function validateTags(userTags: object) { let stringifiedTags = JSON.stringify(userTags); if (stringifiedTags.length > 2048) { throw new BadRequestError( - `userTags object is too large. Max size is 2048 characters`, + `userTags object is too large. Max size is 2048 characters` ); } } @@ -272,7 +272,7 @@ async function triggerManyIdleStreamsWebhook(ids: string[], queue: Queue) { projectId: stream.projectId, userId: user.id, }); - }), + }) ); } @@ -280,7 +280,7 @@ async function triggerManyIdleStreamsWebhook(ids: string[], queue: Queue) { // 1. if the same pull request is created within 1 min (this prevents race condition between different nodes executing /lockPull) // 2. if the same stream was stopped within 10 min (this prevents Mist delays in stopping/starting the stream) export function resolvePullUrlFromExistingStreams( - existingStreams: DBStream[], + existingStreams: DBStream[] ): { pullUrl: string; pullRegion: string } { if (existingStreams.length !== 1) { return null; @@ -295,7 +295,7 @@ export function resolvePullUrlFromExistingStreams( stream.lastSeen > Date.now() - PULL_REUSE_SAME_NODE_TIMEOUT; if (hasPullInfo && (pullLockedRecently || stoppedRecently)) { logger.info( - `pull request created with the same request within 10 min, reusing existing ingest node ${stream.pullLockedBy}`, + `pull request created with the same request within 10 min, reusing existing ingest node ${stream.pullLockedBy}` ); return { pullUrl: "https://" + stream.pullLockedBy + ":443/hls/video+", @@ -308,13 +308,13 @@ export function resolvePullUrlFromExistingStreams( async function resolvePullUrlAndRegion( stream: NewStreamPayload, ingest: string, - playbackId: string, + playbackId: string ): Promise<{ pullUrl: string; pullRegion: string }> { if (process.env.NODE_ENV === "test") { return { pullUrl: null, pullRegion: null }; } const url = new URL( - pathJoin(ingest, `hls`, `ingest-${playbackId}`, `index.m3u8`), + pathJoin(ingest, `hls`, `ingest-${playbackId}`, `index.m3u8`) ); const { lat, lon } = stream.pull?.location ?? {}; if (lat && lon) { @@ -337,10 +337,10 @@ async function resolvePullUrlAndRegion( // Extracts Mist URL from redirected node URL, e.g. "https://sto-prod-catalyst-0.lp-playback.studio:443/hls/video+" from "https://sto-prod-catalyst-0.lp-playback.studio:443/hls/video+foo/index.m3u8" export function extractUrlFrom( playbackUrl: string, - playbackId: string, + playbackId: string ): string { const hostRegex = new RegExp( - `(https?:\/\/.+-\\w+-catalyst.+\/hls\/.+)ingest-${playbackId}\/index.m3u8`, + `(https?:\/\/.+-\\w+-catalyst.+\/hls\/.+)ingest-${playbackId}\/index.m3u8` ); const matches = playbackUrl.match(hostRegex); return matches ? matches[1] : null; @@ -349,10 +349,10 @@ export function extractUrlFrom( // Extracts region from redirected node URL, e.g. "sto" from "https://sto-prod-catalyst-0.lp-playback.studio:443/hls/video+foo/index.m3u8" export function extractRegionFrom( playbackUrl: string, - playbackId: string, + playbackId: string ): string { const regionRegex = new RegExp( - `https?:\/\/(.+)-\\w+-catalyst.+ingest-${playbackId}\/index.m3u8`, + `https?:\/\/(.+)-\\w+-catalyst.+ingest-${playbackId}\/index.m3u8` ); const matches = playbackUrl.match(regionRegex); return matches ? matches[1] : null; @@ -384,7 +384,7 @@ export function triggerCleanUpIsActiveJob( config: CliArgs, streams: DBStream[], queue: Queue, - ingest: string, + ingest: string ): [DBStream[], Promise] { streams = streams.filter(shouldCleanUpIsActive); if (!streams.length) { @@ -409,15 +409,15 @@ export function triggerCleanUpIsActiveJob( { isActive: false }, queue, ingest, - true, - ), - ), + true + ) + ) ); } catch (err) { const ids = parentStreams.map((s) => s.id); logger.error( `Error sending /setactive hooks for streamIds=${ids} err=`, - err, + err ); } @@ -428,13 +428,13 @@ export function triggerCleanUpIsActiveJob( childStreams, queue, ingest, - true, + true ); } catch (err) { const ids = childStreams.map((s) => s.id); logger.error( `Error sending recording.waiting hooks for streamIds=${ids} err=`, - err, + err ); } }); @@ -525,7 +525,7 @@ app.get("/", authorizer({}), async (req, res) => { query.push( sql`coalesce(stream.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); } } @@ -569,14 +569,14 @@ app.get("/", authorizer({}), async (req, res) => { } output = db.stream.addDefaultFieldsMany( - db.stream.removePrivateFieldsMany(output, req.user.admin), + db.stream.removePrivateFieldsMany(output, req.user.admin) ); res.status(200).json(output); }); export async function getRecordingPlaybackUrl( stream: DBStream, - objectStoreId: string, + objectStoreId: string ) { let url: string; @@ -603,7 +603,7 @@ export async function getRecordingFields( config: CliArgs, ingest: string, session: DBSession, - forceUrl: boolean, + forceUrl: boolean ): Promise> { if (!session.record) { return {}; @@ -622,8 +622,8 @@ export async function getRecordingFields( assetPhase == "ready" ? "ready" : assetPhase == "failed" - ? "failed" - : "waiting", + ? "failed" + : "waiting", recordingUrl: assetWithPlayback.playbackUrl, mp4Url: assetWithPlayback.downloadUrl, }; @@ -638,7 +638,7 @@ export async function getRecordingFields( const base = pathJoin( ingest, `recordings`, - session.lastSessionId ?? session.id, + session.lastSessionId ?? session.id ); return { recordingStatus: recordingStatus, @@ -655,7 +655,7 @@ export async function withRecordingFields( config: CliArgs, ingest: string, session: DBSession, - forceUrl: boolean, + forceUrl: boolean ) { return { ...session, @@ -710,7 +710,7 @@ app.get("/:parentId/sessions", authorizer({}), async (req, res) => { req.config, ingest, session, - !!forceUrl, + !!forceUrl ); if (!raw) { if (session.previousSessions && session.previousSessions.length) { @@ -719,7 +719,7 @@ app.get("/:parentId/sessions", authorizer({}), async (req, res) => { } const combinedStats = getCombinedStats( session, - session.previousStats || {}, + session.previousStats || {} ); return { ...session, @@ -728,7 +728,7 @@ app.get("/:parentId/sessions", authorizer({}), async (req, res) => { }; } return session; - }), + }) ); if (filterOut) { @@ -762,8 +762,8 @@ app.get("/sessions/:parentId", authorizer({}), async (req, res) => { } res.json( db.stream.addDefaultFieldsMany( - db.stream.removePrivateFieldsMany(data, req.user.admin), - ), + db.stream.removePrivateFieldsMany(data, req.user.admin) + ) ); }); @@ -785,7 +785,7 @@ app.get("/user/:userId", authorizer({}), async (req, res) => { query.push( sql`coalesce(data->>'projectId', ${req.user.defaultProjectId || ""}) = ${ req.project?.id || "" - }`, + }` ); } if (streamsonly) { @@ -808,8 +808,8 @@ app.get("/user/:userId", authorizer({}), async (req, res) => { } res.json( db.stream.addDefaultFieldsMany( - db.stream.removePrivateFieldsMany(streams, req.user.admin), - ), + db.stream.removePrivateFieldsMany(streams, req.user.admin) + ) ); }); @@ -830,7 +830,7 @@ app.get("/:id", authorizer({}), async (req, res) => { // is a sum of all sessions const combinedStats = getCombinedStats( lastSession, - lastSession.previousStats || {}, + lastSession.previousStats || {} ); stream = { ...lastSession, @@ -858,15 +858,15 @@ app.get("/playback/:playbackId", authorizer({}), async (req, res) => { return stream; }, - 5, + 5 ); req.checkResourceAccess(stream); res.status(200); res.json( db.stream.addDefaultFields( - db.stream.removePrivateFields(stream, req.user.admin), - ), + db.stream.removePrivateFields(stream, req.user.admin) + ) ); }); @@ -875,14 +875,14 @@ app.get("/key/:streamKey", authorizer({}), async (req, res) => { const useReplica = req.query.main !== "true"; const [docs] = await db.stream.find( { streamKey: req.params.streamKey }, - { useReplica }, + { useReplica } ); req.checkResourceAccess(docs[0]); res.status(200); res.json( db.stream.addDefaultFields( - db.stream.removePrivateFields(docs[0], req.user.admin), - ), + db.stream.removePrivateFields(docs[0], req.user.admin) + ) ); }); @@ -890,7 +890,7 @@ app.get("/key/:streamKey", authorizer({}), async (req, res) => { app.get( "/:streamId/broadcaster", geolocateMiddleware({}), - getBroadcasterHandler, + getBroadcasterHandler ); app.post( @@ -917,7 +917,7 @@ app.post( const playbackId = req.body.name.split("+")[1]; const [docs] = await db.stream.find( { playbackId }, - { useReplica: false }, + { useReplica: false } ); if (docs.length) { stream = docs[0]; @@ -948,7 +948,7 @@ app.post( } = stream; const profiles = hackMistSettings( req, - useParentProfiles ? stream.profiles : req.body.profiles, + useParentProfiles ? stream.profiles : req.body.profiles ); const childStream: DBStream = wowzaHydrate({ ...req.body, @@ -973,7 +973,7 @@ app.post( const existingSession = await db.session.get(sessionId); if (existingSession) { logger.info( - `user session re-used for session.id=${sessionId} session.parentId=${existingSession.parentId} session.name=${existingSession.name} session.playbackId=${existingSession.playbackId} session.userId=${existingSession.userId} stream.id=${stream.id} stream.name='${stream.name}' stream.playbackId=${stream.playbackId} stream.userId=${stream.userId} stream.projectId=${stream.projectId}`, + `user session re-used for session.id=${sessionId} session.parentId=${existingSession.parentId} session.name=${existingSession.name} session.playbackId=${existingSession.playbackId} session.userId=${existingSession.userId} stream.id=${stream.id} stream.name='${stream.name}' stream.playbackId=${stream.playbackId} stream.userId=${stream.userId} stream.projectId=${stream.projectId}` ); } else { const session: DBSession = { @@ -1009,7 +1009,7 @@ app.post( req.config, session, req.queue, - ingest, + ingest ).catch((err) => { logger.error("Error sending recording.started hook err=", err); }); @@ -1025,9 +1025,9 @@ app.post( stream.name }' playbackid=${stream.playbackId} session_id=${id} projectid=${ stream.projectId - } elapsed=${Date.now() - start}ms`, + } elapsed=${Date.now() - start}ms` ); - }, + } ); app.post( @@ -1076,7 +1076,7 @@ app.post( await db.session.replace({ ...session, ...patch }); } else { logger.warn( - `stream-health-payload: session not found for stream_id=${stream.id} session_id=${payload.session_id}`, + `stream-health-payload: session not found for stream_id=${stream.id} session_id=${payload.session_id}` ); } } @@ -1090,11 +1090,11 @@ app.post( `is_active=${payload.is_active} is_healthy=${payload.is_healthy} ` + `issues=${payload.issues} human_issues=${payload.human_issues} ` + `extra=${JSON.stringify(payload.extra)} ` + - `tracks=${JSON.stringify(payload.tracks)}`, + `tracks=${JSON.stringify(payload.tracks)}` ); res.status(204).end(); - }, + } ); const pullStreamKeyAccessors: Record = { @@ -1155,7 +1155,7 @@ app.put( }; logger.info( `pull request received userId=${req.user.id} ` + - `payload=${JSON.stringify(JSON.stringify(payloadLog))}`, // double stringify to escape string for logfmt + `payload=${JSON.stringify(JSON.stringify(payloadLog))}` // double stringify to escape string for logfmt ); const keyValue = _.get(payload, pullStreamKeyAccessors[key]); @@ -1163,13 +1163,13 @@ app.put( return res.status(400).json({ errors: [ `key must be one of ${Object.keys( - pullStreamKeyAccessors, + pullStreamKeyAccessors )} and must be present in the payload`, ], }); } const filtersStr = encodeURIComponent( - JSON.stringify([{ id: key, value: keyValue }]), + JSON.stringify([{ id: key, value: keyValue }]) ); const filters = parseFilters(fieldsMap, filtersStr); @@ -1182,7 +1182,7 @@ app.put( }) = ${req.project?.id || ""}`, ...filters, ], - { useReplica: false }, + { useReplica: false } ); if (streams.length > 1) { return res.status(400).json({ @@ -1199,13 +1199,13 @@ app.put( let stream: DBStream; if (!streamExisted) { logger.info( - `pull request creating a new stream with name=${rawPayload.name}`, + `pull request creating a new stream with name=${rawPayload.name}` ); stream = await handleCreateStream(req, payload); const { pullUrl, pullRegion } = await resolvePullUrlAndRegion( rawPayload, ingest, - stream.playbackId, + stream.playbackId ); streamPullUrl = pullUrl; stream.pullRegion = pullRegion; @@ -1217,16 +1217,16 @@ app.put( (await resolvePullUrlAndRegion( rawPayload, ingest, - oldStream.playbackId, + oldStream.playbackId )); streamPullUrl = pullUrl; logger.info( - `pull reusing existing old stream with id=${oldStream.id} name=${oldStream.name}`, + `pull reusing existing old stream with id=${oldStream.id} name=${oldStream.name}` ); const sleepFor = terminateDelay(oldStream); if (sleepFor > 0) { console.log( - `stream pull delaying because of recent terminate streamId=${oldStream.id} lastTerminatedAt=${oldStream.lastTerminatedAt} sleepFor=${sleepFor}`, + `stream pull delaying because of recent terminate streamId=${oldStream.id} lastTerminatedAt=${oldStream.lastTerminatedAt} sleepFor=${sleepFor}` ); await sleep(sleepFor); } @@ -1261,10 +1261,10 @@ app.put( res.status(streamExisted ? 200 : 201); res.json( db.stream.addDefaultFields( - db.stream.removePrivateFields(stream, req.user.admin), - ), + db.stream.removePrivateFields(stream, req.user.admin) + ) ); - }, + } ); app.post("/:id/lockPull", authorizer({ anyAdmin: true }), async (req, res) => { @@ -1290,7 +1290,7 @@ app.post("/:id/lockPull", authorizer({ anyAdmin: true }), async (req, res) => { req.config, [stream], req.queue, - await getIngestBase(req), + await getIngestBase(req) ); const doingActiveCleanup = cleanedUpStreams.length > 0; @@ -1305,7 +1305,7 @@ app.post("/:id/lockPull", authorizer({ anyAdmin: true }), async (req, res) => { : sql`(data->>'pullLockedBy' = ${host} OR (COALESCE((data->>'pullLockedAt')::bigint,0) < ${leaseDeadline} AND COALESCE((data->>'isActive')::boolean,FALSE) = FALSE))`, ], { pullLockedAt: Date.now(), pullLockedBy: host }, - { throwIfEmpty: false }, + { throwIfEmpty: false } ); if (updateRes.rowCount > 0) { @@ -1313,7 +1313,7 @@ app.post("/:id/lockPull", authorizer({ anyAdmin: true }), async (req, res) => { return; } logger.info( - `/lockPull failed for stream=${id}, isActive=${stream.isActive}, lastSeen=${stream.lastSeen}, pullLockedBy=${stream.pullLockedBy}, pullLockedAt=${stream.pullLockedAt}`, + `/lockPull failed for stream=${id}, isActive=${stream.isActive}, lastSeen=${stream.lastSeen}, pullLockedBy=${stream.pullLockedBy}, pullLockedAt=${stream.pullLockedAt}` ); res.status(423).end(); }); @@ -1355,7 +1355,7 @@ app.post( req.user.defaultProjectId || "" }) = ${req.project?.id || ""}`, ], - { useReplica: false }, + { useReplica: false } ); if (streams.length === 1) { @@ -1363,15 +1363,15 @@ app.post( const ingest = await getIngestBase(req); await triggerCatalystPullStart( stream, - getHLSPlaybackUrl(ingest, stream), + getHLSPlaybackUrl(ingest, stream) ); return res .status(200) .json( db.stream.addDefaultFields( - db.stream.removePrivateFields(stream, req.user.admin), - ), + db.stream.removePrivateFields(stream, req.user.admin) + ) ); } else if (streams.length > 1) { return res.status(400).json({ @@ -1392,10 +1392,10 @@ app.post( res.status(201); res.json( db.stream.addDefaultFields( - db.stream.removePrivateFields(stream, req.user.admin), - ), + db.stream.removePrivateFields(stream, req.user.admin) + ) ); - }, + } ); async function handleCreateStream(req: Request, payload: NewStreamPayload) { @@ -1413,7 +1413,7 @@ async function handleCreateStream(req: Request, payload: NewStreamPayload) { const store = await db.objectStore.get(objectStoreId); if (!store || store.deleted || store.disabled) { throw new BadRequestError( - `object store ${objectStoreId} not found or disabled`, + `object store ${objectStoreId} not found or disabled` ); } } @@ -1421,7 +1421,7 @@ async function handleCreateStream(req: Request, payload: NewStreamPayload) { if (recordingSpec) { if (!payload.record) { throw new BadRequestError( - `recordingSpec is only supported with record=true`, + `recordingSpec is only supported with record=true` ); } if (!recordingSpec.profiles) { @@ -1458,7 +1458,7 @@ async function handleCreateStream(req: Request, payload: NewStreamPayload) { doc.multistream = await validateMultistreamOpts( req.user.id, doc.profiles, - doc.multistream, + doc.multistream ); if (doc.userTags) { @@ -1490,7 +1490,7 @@ app.put( const { id } = req.params; const { active, startedAt, hostName } = req.body as StreamSetActivePayload; logger.info( - `got /setactive for stream=${id} active=${active} hostName=${hostName} startedAt=${startedAt}`, + `got /setactive for stream=${id} active=${active} hostName=${hostName} startedAt=${startedAt}` ); const stream = await db.stream.get(id, { useReplica: false }); @@ -1523,7 +1523,7 @@ app.put( // key. We only support 1 conc. session so keep the last to have started. logger.info( `Ignoring /setactive false since another session had already started. ` + - `stream=${id} currMist="${stream.region}-${stream.mistHost}" oldMist="${req.config.ownRegion}-${hostName}"`, + `stream=${id} currMist="${stream.region}-${stream.mistHost}" oldMist="${req.config.ownRegion}-${hostName}"` ); return res.status(204).end(); } @@ -1543,7 +1543,7 @@ app.put( stream, patch, req.queue, - ingest, + ingest ); // update the other auxiliary info in the database in background. @@ -1564,13 +1564,13 @@ app.put( } catch (err) { logger.error( "Error updating aux info from /setactive in database err=", - err, + err ); } }); res.status(204).end(); - }, + } ); /** @@ -1588,11 +1588,11 @@ async function setStreamActiveWithHooks( patch: Partial & { isActive: boolean }, queue: Queue, ingest: string, - isCleanup?: boolean, + isCleanup?: boolean ) { if (stream.parentId) { throw new Error( - "must only set stream active synchronously for parent streams", + "must only set stream active synchronously for parent streams" ); } @@ -1619,7 +1619,7 @@ async function setStreamActiveWithHooks( .catch((err) => { logger.error( `Error sending /setactive hooks stream_id=${stream.id} event=${event} err=`, - err, + err ); }); } @@ -1633,13 +1633,13 @@ async function setStreamActiveWithHooks( childStreams, queue, ingest, - isCleanup, + isCleanup ).catch((err) => { logger.error( `Error triggering session recording hooks stream_id=${stream.id} err=`, - err, + err ); - }), + }) ); } } @@ -1655,14 +1655,14 @@ async function triggerSessionRecordingProcessing( childStreams: DBStream[], queue: Queue, ingest: string, - isCleanup?: boolean, + isCleanup?: boolean ) { const streamsBySessionId: Record = {}; for (const stream of childStreams) { if (!stream.parentId) { logger.error( `triggerSessionRecordingProcessing: ignoring parent streamId=${stream.id} stream=`, - stream, + stream ); continue; } else if (isCleanup && !shouldCleanUpIsActive(stream)) { @@ -1684,7 +1684,7 @@ async function triggerSessionRecordingProcessing( if (!sessionId) { // child streams didn't have a sessionId before recordings v2 upgrade. they're all stale now so just clear on DB. logger.info( - `triggerSessionRecordingProcessing: Clearing isActive for recording v1 child streams sessionId=${sessionId} childStreamsIds=${streamsIds}`, + `triggerSessionRecordingProcessing: Clearing isActive for recording v1 child streams sessionId=${sessionId} childStreamsIds=${streamsIds}` ); await clearIsActiveMany(db, streamsFromSession); return; @@ -1695,7 +1695,7 @@ async function triggerSessionRecordingProcessing( // if we have an asset, then the recording has already been processed and we don't need to send a // recording.waiting hook. also clear the isActive field from child streams. logger.info( - `triggerSessionRecordingProcessing: Clearing isActive for already processed session sessionId=${sessionId} assetId=${asset.id}`, + `triggerSessionRecordingProcessing: Clearing isActive for already processed session sessionId=${sessionId} assetId=${asset.id}` ); await clearIsActiveMany(db, streamsFromSession); return; @@ -1711,11 +1711,11 @@ async function triggerSessionRecordingProcessing( if (!session.record || isStale) { if (isStale) { logger.info( - `triggerSessionRecordingProcessing: Skipping recording for stale session sessionId=${session.id} lastSeen=${session.lastSeen} childStreamsIds=${streamsIds}`, + `triggerSessionRecordingProcessing: Skipping recording for stale session sessionId=${session.id} lastSeen=${session.lastSeen} childStreamsIds=${streamsIds}` ); } else { logger.info( - `triggerSessionRecordingProcessing: Clearing isActive for session without recording enabled sessionId=${session.id} childStreamsIds=${streamsIds}`, + `triggerSessionRecordingProcessing: Clearing isActive for session without recording enabled sessionId=${session.id} childStreamsIds=${streamsIds}` ); } // clean-up isActive field synchronously on child streams from stale sessions. no isActive left behind! @@ -1724,28 +1724,28 @@ async function triggerSessionRecordingProcessing( } logger.info( - `triggerSessionRecordingProcessing: Triggering recording.waiting hook sessionId=${sessionId} childStreamsIds=${streamsIds}`, + `triggerSessionRecordingProcessing: Triggering recording.waiting hook sessionId=${sessionId} childStreamsIds=${streamsIds}` ); await publishDelayedRecordingWaitingHook( config, session, queue, - ingest, + ingest ); } catch (err) { const ids = streamsFromSession?.map((s) => s?.id); logger.error( `Error handling session recording hooks sessionId=${sessionId} childStreamsIds=${ids} err=`, - err, + err ); } - }), + }) ); } async function clearIsActiveMany(db: DB, streams: DBStream[]) { await Promise.all( - streams.map((s) => db.stream.update(s.id, { isActive: false })), + streams.map((s) => db.stream.update(s.id, { isActive: false })) ); } @@ -1753,7 +1753,7 @@ async function publishRecordingStartedHook( config: CliArgs, session: DBSession, queue: Queue, - ingest: string, + ingest: string ) { return queue.publishWebhook("events.recording.started", { type: "webhook_event", @@ -1774,7 +1774,7 @@ async function publishDelayedRecordingWaitingHook( config: CliArgs, session: DBSession, queue: Queue, - ingest: string, + ingest: string ) { return await queue.delayedPublishWebhook( "events.recording.waiting", @@ -1796,7 +1796,7 @@ async function publishDelayedRecordingWaitingHook( }, }, USER_SESSION_TIMEOUT + 10_000, - "recording_waiting_delayed_events", + "recording_waiting_delayed_events" ); } @@ -1831,19 +1831,19 @@ app.patch( if (upRes.rowCount) { console.log( - `set isActive=false for ids=${req.body.ids} rowCount=${upRes.rowCount}`, + `set isActive=false for ids=${req.body.ids} rowCount=${upRes.rowCount}` ); } } catch (e) { console.error( - `error setting stream active to false ids=${req.body.ids} err=${e}`, + `error setting stream active to false ids=${req.body.ids} err=${e}` ); upRes = { rowCount: 0 } as QueryResult; } res.status(200); return res.json({ rowCount: upRes?.rowCount ?? 0 }); - }, + } ); app.post( @@ -1865,7 +1865,7 @@ app.post( const newTarget = await validateMultistreamTarget( req.user.id, toProfileNames(stream.profiles), - payload, + payload ); let multistream: DBStream["multistream"] = { @@ -1875,7 +1875,7 @@ app.post( multistream = await validateMultistreamOpts( req.user.id, stream.profiles, - multistream, + multistream ); let patch: StreamPatchPayload & Partial = { @@ -1888,7 +1888,7 @@ app.post( res.status(200); res.json(db.multistreamTarget.cleanWriteOnlyResponse(updatedTarget)); - }, + } ); app.delete("/:id/multistream/:targetId", authorizer({}), async (req, res) => { @@ -1906,7 +1906,7 @@ app.delete("/:id/multistream/:targetId", authorizer({}), async (req, res) => { multistream = await validateMultistreamOpts( req.user.id, stream.profiles, - multistream, + multistream ); let patch: StreamPatchPayload & Partial = { @@ -1976,7 +1976,7 @@ app.patch( const { record } = typeof payload.record === "boolean" ? payload : stream; if (!record) { throw new BadRequestError( - `recordingSpec is only supported with record=true`, + `recordingSpec is only supported with record=true` ); } if (!recordingSpec.profiles) { @@ -1992,7 +1992,7 @@ app.patch( multistream = await validateMultistreamOpts( req.user.id, stream.profiles, - multistream, + multistream ); patch = { ...patch, multistream }; } @@ -2023,7 +2023,7 @@ app.patch( res.status(204); res.end(); - }, + } ); app.patch("/:id/record", authorizer({}), async (req, res) => { @@ -2124,7 +2124,7 @@ app.get("/:id/info", authorizer({}), async (req, res) => { const user = await db.user.get(stream.userId); const resp = { stream: db.stream.addDefaultFields( - db.stream.removePrivateFields(stream, req.user.admin), + db.stream.removePrivateFields(stream, req.user.admin) ), session, isPlaybackid, @@ -2202,7 +2202,7 @@ app.post( await triggerCatalystPullStart(stream, getHLSPlaybackUrl(ingest, stream)); res.status(204).end(); - }, + } ); app.delete("/:id/terminate", authorizer({}), async (req, res) => { @@ -2254,12 +2254,12 @@ app.post( ...req.config, activeCleanupLimit: limit, }, - { jobsDb, queue: req.queue }, + { jobsDb, queue: req.queue } ); res.status(200); res.json({ cleanedUp }); - }, + } ); // Hooks @@ -2406,14 +2406,14 @@ app.post("/hook", authorizer({ anyAdmin: true }), async (req, res) => { const { data: webhooks } = await db.webhook.listSubscribed( user.id, - "stream.detection", + "stream.detection" ); let detection = undefined; if (webhooks.length > 0 || stream.detection) { console.warn( `Ignoring configured detection webhooks="${webhooks.map( - (w) => w.id, - )}" for manifestId=${manifestID}`, + (w) => w.id + )}" for manifestId=${manifestID}` ); // TODO: Validate if these are the best default configs // detection = { @@ -2429,8 +2429,8 @@ app.post("/hook", authorizer({ anyAdmin: true }), async (req, res) => { console.log( `StreamHookResponse id=${manifestID} profiles=${JSON.stringify( - stream.profiles, - )}`, + stream.profiles + )}` ); // Inject H264ConstrainedHigh profile for no B-Frames in livestreams unless the user has set it manually @@ -2485,7 +2485,7 @@ app.post( await req.queue.publishWebhook("events.stream.detection", msg); return res.status(204).end(); - }, + } ); const statsFields: (keyof StreamStats)[] = [ diff --git a/packages/api/src/controllers/stripe.test.ts b/packages/api/src/controllers/stripe.test.ts index 2046175967..646f1ec30d 100644 --- a/packages/api/src/controllers/stripe.test.ts +++ b/packages/api/src/controllers/stripe.test.ts @@ -84,18 +84,18 @@ describe("controllers/stripe", () => { }; overage = await calculateOverageOnMinimumSpend(product, billingUsage); expect(overage.StorageUsageMins * product.usage[2].price).toBeGreaterThan( - 0, + 0 ); expect( - overage.DeliveryUsageMins * product.usage[1].price, + overage.DeliveryUsageMins * product.usage[1].price ).toBeGreaterThan(0); expect(overage.TotalUsageMins * product.usage[0].price).toBeGreaterThan( - 0, + 0 ); expect( overage.TotalUsageMins * product.usage[0].price + overage.DeliveryUsageMins * product.usage[1].price + - overage.StorageUsageMins * product.usage[2].price, + overage.StorageUsageMins * product.usage[2].price ).toEqual(31); // Test 30$ spend with overage reported as 0, corresponding to 100$ invoice @@ -128,16 +128,16 @@ describe("controllers/stripe", () => { }; overage = await calculateOverageOnMinimumSpend(product, billingUsage); expect(overage.StorageUsageMins * product.usage[2].price).toBeGreaterThan( - 0, + 0 ); expect( - overage.DeliveryUsageMins * product.usage[1].price, + overage.DeliveryUsageMins * product.usage[1].price ).toBeGreaterThan(0); expect(overage.TotalUsageMins * product.usage[0].price).toBe(0); expect( overage.TotalUsageMins * product.usage[0].price + overage.DeliveryUsageMins * product.usage[1].price + - overage.StorageUsageMins * product.usage[2].price, + overage.StorageUsageMins * product.usage[2].price ).toEqual(47.5); // Test 550$ spend with overage reported as 450, corresponding to 550$ invoice @@ -196,13 +196,13 @@ describe("controllers/stripe", () => { }; overusage = await calculateOverUsage(product, billingUsage); expect(overusage.TotalUsageMins * product.usage[0].price).toEqual( - product.usage[0].price, + product.usage[0].price ); expect(overusage.DeliveryUsageMins * product.usage[1].price).toEqual( - product.usage[1].price, + product.usage[1].price ); expect(overusage.StorageUsageMins * product.usage[2].price).toEqual( - product.usage[2].price, + product.usage[2].price ); }); }); diff --git a/packages/api/src/controllers/stripe.ts b/packages/api/src/controllers/stripe.ts index d97f1b451c..e35a937745 100644 --- a/packages/api/src/controllers/stripe.ts +++ b/packages/api/src/controllers/stripe.ts @@ -24,7 +24,7 @@ const HELP_EMAIL = "help@livepeer.org"; export const reportUsage = async ( stripe: Stripe, config: CliArgs, - adminToken: string, + adminToken: string ) => { const payAsYouGoUsers = await getPayAsYouGoUsers(config.ingest, adminToken); @@ -43,12 +43,12 @@ export const reportUsage = async ( stripe, config, user, - adminToken, + adminToken ); updatedUsers.push(userUpdated); } catch (e) { logger.error( - `Failed to create usage record for user=${user.id} with error=${e.message}`, + `Failed to create usage record for user=${user.id} with error=${e.message}` ); updatedUsers.push({ id: user.id, @@ -76,7 +76,7 @@ async function getPayAsYouGoUsers(ingests: Ingest[], adminToken: string) { { limit: 9999999999, useReplica: true, - }, + } ); const hackerUsers = await getRecentlyActiveHackers(ingests, adminToken); @@ -93,7 +93,7 @@ async function reportUsageForUser( actuallyReport: boolean = true, forceReport: boolean = false, from?: number, - to?: number, + to?: number ) { // make sure this func takes at least 100ms to avoid incurring into stripe rate limits const sleepProm = sleep(100); @@ -109,7 +109,7 @@ async function reportUsageForUser( } const userSubscription = await stripe.subscriptions.retrieve( - user.stripeCustomerSubscriptionId, + user.stripeCustomerSubscriptionId ); let billingCycleStart = userSubscription.current_period_start * 1000; // 1685311200000 // Test date @@ -125,7 +125,7 @@ async function reportUsageForUser( billingCycleStart, billingCycleEnd, config.ingest, - adminToken, + adminToken ); const subscriptionItems = await stripe.subscriptionItems.list({ @@ -138,7 +138,7 @@ async function reportUsageForUser( if (!product.minumumSpend) { const usageNotifications = await getUsageNotifications( usageData.usagePercentages, - user, + user ); if (usageNotifications.length > 0) { @@ -147,7 +147,7 @@ async function reportUsageForUser( } else { const overage = await calculateOverageOnMinimumSpend( product, - usageData.billingUsage, + usageData.billingUsage ); usageToReport = overage; } @@ -159,7 +159,7 @@ async function reportUsageForUser( acc[item.price.lookup_key] = item.id; return acc; }, - {} as Record, + {} as Record ); logger.info(` usage: reporting usage to stripe for user=${user.id} email=${user.email} from=${billingCycleStart} to=${billingCycleEnd} @@ -168,7 +168,7 @@ async function reportUsageForUser( stripe, user, subscriptionItemsByLookupKey, - usageData.overUsage, + usageData.overUsage ); } @@ -188,7 +188,7 @@ const sendUsageRecordToStripe = async ( stripe: Stripe, user: WithID, subscriptionItemsByLookupKey, - overUsage, + overUsage ) => { // Invoice items based on overusage await Promise.all( @@ -200,7 +200,7 @@ const sendUsageRecordToStripe = async ( quantity: parseInt(overUsage.TotalUsageMins.toFixed(0)), timestamp: Math.floor(new Date().getTime() / 1000), action: "set", - }, + } ); } else if (product.name === "Delivery") { await stripe.subscriptionItems.createUsageRecord( @@ -209,7 +209,7 @@ const sendUsageRecordToStripe = async ( quantity: parseInt(overUsage.DeliveryUsageMins.toFixed(0)), timestamp: Math.floor(new Date().getTime() / 1000), action: "set", - }, + } ); } else if (product.name === "Storage") { await stripe.subscriptionItems.createUsageRecord( @@ -218,10 +218,10 @@ const sendUsageRecordToStripe = async ( quantity: parseInt(overUsage.StorageUsageMins.toFixed(0)), timestamp: Math.floor(new Date().getTime() / 1000), action: "set", - }, + } ); } - }), + }) ); }; @@ -332,12 +332,12 @@ app.post("/webhook", async (req, res) => { const [users] = await db.user.find( { stripeCustomerId: invoice.customer }, - { useReplica: false }, + { useReplica: false } ); if (users.length < 1) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } const user = users[0]; @@ -350,7 +350,7 @@ app.post("/webhook", async (req, res) => { invoice.period_end, { useReplica: false, - }, + } ); // Invoice items based on usage @@ -369,7 +369,7 @@ app.post("/webhook", async (req, res) => { subscription: user.stripeCustomerSubscriptionId, }); } - }), + }) ); } } else if (event.type === "invoice.payment_failed") { @@ -379,12 +379,12 @@ app.post("/webhook", async (req, res) => { const [users] = await db.user.find( { stripeCustomerId: invoice.customer }, - { useReplica: false }, + { useReplica: false } ); if (users.length < 1) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } const user = users[0]; @@ -439,7 +439,7 @@ app.post("/webhook", async (req, res) => { }); let paidInvoices = allCustomerInvoices.data.filter( - (invoice) => invoice.status === "paid" && invoice.amount_due > 0, + (invoice) => invoice.status === "paid" && invoice.amount_due > 0 ); if (paidInvoices.length === 0) { @@ -505,12 +505,12 @@ app.patch( if (!user) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } if (stripeCustomerSubscriptionId) { const subscription = await req.stripe.subscriptions.retrieve( - stripeCustomerSubscriptionId, + stripeCustomerSubscriptionId ); if (!subscription) { @@ -541,7 +541,7 @@ app.patch( res.status(200); return res.json({ result: "user subscription updated" }); - }, + } ); app.post( @@ -583,7 +583,7 @@ app.post( try { subscription = await req.stripe.subscriptions.retrieve( - user.stripeCustomerSubscriptionId, + user.stripeCustomerSubscriptionId ); } catch (e) { logger.error(` @@ -638,7 +638,7 @@ app.post( price: item.id, })), ], - }, + } ); await db.user.update(user.id, { @@ -661,7 +661,7 @@ app.post( res.json({ result: "Migrated user with email " + user.email + " to enterprise plan", }); - }, + } ); export default app; diff --git a/packages/api/src/controllers/task.ts b/packages/api/src/controllers/task.ts index 3c609bec2b..01e554771b 100644 --- a/packages/api/src/controllers/task.ts +++ b/packages/api/src/controllers/task.ts @@ -28,7 +28,7 @@ function validateTaskPayload( id: string, userId: string, createdAt: number, - payload, + payload ) { return { id, @@ -40,7 +40,7 @@ function validateTaskPayload( } const ipfsStorageToTaskOutput = ( - ipfs: Omit, + ipfs: Omit ): Task["output"]["export"]["ipfs"] => ({ videoFileCid: ipfs.cid, videoFileUrl: ipfs.url, @@ -52,7 +52,7 @@ const ipfsStorageToTaskOutput = ( function taskWithIpfsUrls( gatewayUrl: string, - task: WithID, + task: WithID ): WithID { if (task?.type !== "export" || !task?.output?.export?.ipfs) { return task; @@ -72,16 +72,16 @@ function taskWithIpfsUrls( export function taskParamsWithoutCredentials( type: Task["type"], - params: Task["params"], + params: Task["params"] ): Task["params"] { const result = _.cloneDeep(params); switch (type) { case "transcode-file": result["transcode-file"].input.url = deleteCredentials( - params["transcode-file"].input.url, + params["transcode-file"].input.url ); result["transcode-file"].storage.url = deleteCredentials( - params["transcode-file"].storage.url, + params["transcode-file"].storage.url ); break; case "upload": @@ -98,7 +98,7 @@ export async function getProcessingTasksByRequesterId( requesterId: string, ownerId: string, taskType?: string, - timeFrame?: number, // in minutes + timeFrame?: number // in minutes ): Promise[]> { if (!timeFrame) { timeFrame = 60; @@ -132,7 +132,7 @@ const fieldsMap: FieldsMap = { export function toExternalTask( t: WithID, config: CliArgs, - isAdmin = false, + isAdmin = false ) { t = taskWithIpfsUrls(config.ipfsGatewayUrl, t); if (isAdmin) { @@ -275,7 +275,7 @@ app.post( res.status(201); res.json(doc); - }, + } ); app.post("/:id/retry", authorizer({}), async (req, res) => { @@ -291,7 +291,7 @@ app.post("/:id/retry", authorizer({}), async (req, res) => { const user = await db.user.get(task.userId); if (!user) { - return res.status(500).json({ errors: ["user not found"] }); + return res.status(500).json({ errors: ["Account not found"] }); } if (!req.user.admin && req.user.id !== task.userId) { @@ -320,7 +320,7 @@ app.post("/:id/status", authorizer({ anyAdmin: true }), async (req, res) => { const user = await db.user.get(task.userId); if (!user) { - return res.status(500).json({ errors: ["task user not found"] }); + return res.status(500).json({ errors: ["task Account not found"] }); } else if (user.suspended || user.disabled) { return res.status(403).json({ errors: [`task user is ${user.suspended ? "suspended" : "disabled"}`], @@ -334,7 +334,7 @@ app.post("/:id/status", authorizer({ anyAdmin: true }), async (req, res) => { const numRunning = await db.task.countRunningTasks(req.user.id); if (numRunning >= req.config.vodMaxConcurrentTasksPerUser) { throw new TooManyRequestsError( - `too many tasks running for user ${user.id} (${numRunning})`, + `too many tasks running for user ${user.id} (${numRunning})` ); } } @@ -357,7 +357,7 @@ app.post("/:id/status", authorizer({ anyAdmin: true }), async (req, res) => { await req.taskScheduler.updateTask( task, { status }, - { allowedPhases: ["waiting", "running"] }, + { allowedPhases: ["waiting", "running"] } ); if (task.outputAssetId) { const asset = await db.asset.get(task.outputAssetId); @@ -370,7 +370,7 @@ app.post("/:id/status", authorizer({ anyAdmin: true }), async (req, res) => { progress: Math.max(doc.progress, asset.status.progress ?? 0), }, }, - { allowedPhases: ["waiting", "processing"] }, + { allowedPhases: ["waiting", "processing"] } ); } if (task.inputAssetId) { @@ -378,7 +378,7 @@ app.post("/:id/status", authorizer({ anyAdmin: true }), async (req, res) => { if (task.id === asset?.storage?.status?.tasks.pending) { const progress = Math.max( doc.progress, - asset.storage.status.progress ?? 0, + asset.storage.status.progress ?? 0 ); await req.taskScheduler.updateAsset(asset, { storage: { diff --git a/packages/api/src/controllers/transcode.ts b/packages/api/src/controllers/transcode.ts index 4f1d44cf9f..f0de33f210 100644 --- a/packages/api/src/controllers/transcode.ts +++ b/packages/api/src/controllers/transcode.ts @@ -69,10 +69,10 @@ app.post( }, null, null, - req.user.id, + req.user.id ); res.json(task); - }, + } ); export default app; diff --git a/packages/api/src/controllers/usage.ts b/packages/api/src/controllers/usage.ts index 5453f52e00..800acd36db 100644 --- a/packages/api/src/controllers/usage.ts +++ b/packages/api/src/controllers/usage.ts @@ -17,7 +17,7 @@ export const getBillingUsage = async ( fromTime: number, toTime: number, baseUrl: string, - adminToken: string, + adminToken: string ) => { // Fetch usage data from /data/usage endpoint const usage = await fetch( @@ -30,7 +30,7 @@ export const getBillingUsage = async ( headers: { Authorization: `Bearer ${adminToken}`, }, - }, + } ).then((res) => res.json()); return usage; @@ -40,7 +40,7 @@ export const getRecentlyActiveUsers = async ( fromTime: number, toTime: number, baseUrl: string, - adminToken: string, + adminToken: string ) => { // Fetch usage data from /data/usage endpoint const users = await fetch( @@ -52,7 +52,7 @@ export const getRecentlyActiveUsers = async ( headers: { Authorization: `Bearer ${adminToken}`, }, - }, + } ).then((res) => res.json()); return users; @@ -63,7 +63,7 @@ export const getViewers = async ( fromTime: number, toTime: number, baseUrl: string, - adminToken: string, + adminToken: string ) => { try { // Fetch viewership data from /data/views endpoint @@ -77,7 +77,7 @@ export const getViewers = async ( headers: { Authorization: `Bearer ${adminToken}`, }, - }, + } ).then((res) => res.json()); let viewers = 0; @@ -112,15 +112,15 @@ export const calculateOverUsage = async (product, usage) => { const overUsage = { TotalUsageMins: Math.max( usage?.TotalUsageMins - (limits.transcoding || 0), - 0, + 0 ), DeliveryUsageMins: Math.max( usage?.DeliveryUsageMins - (limits.streaming || 0), - 0, + 0 ), StorageUsageMins: Math.max( usage?.StorageUsageMins - (limits.storage || 0), - 0, + 0 ), }; @@ -161,7 +161,7 @@ export const getUsagePercentageOfLimit = async (product, usage) => { export async function getRecentlyActiveHackers( ingests: Ingest[], - adminToken: string, + adminToken: string ) { // Current date in milliseconds const currentDateMillis = new Date().getTime(); @@ -174,7 +174,7 @@ export async function getRecentlyActiveHackers( cutOffDate, currentDateMillis, ingests[0].origin, - adminToken, + adminToken ); let activeHackers = []; @@ -199,24 +199,24 @@ export async function getUsageData( billingCycleStart: number, billingCycleEnd: number, ingests: Ingest[], - adminToken: string, + adminToken: string ) { const billingUsage = await getBillingUsage( user.id, billingCycleStart, billingCycleEnd, ingests[0].origin, - adminToken, + adminToken ); const overUsage = await calculateOverUsage( products[user.stripeProductId], - billingUsage, + billingUsage ); const usagePercentages = await getUsagePercentageOfLimit( products[user.stripeProductId], - billingUsage, + billingUsage ); return { @@ -240,7 +240,7 @@ app.get("/", authorizer({ anyAdmin: true }), async (req, res) => { toTime, { useReplica: true, - }, + } ); res.status(200); @@ -254,12 +254,12 @@ app.get( const ingests = await req.getIngest(); const recentlyActiveHackers = await getRecentlyActiveHackers( ingests, - req.token.id, + req.token.id ); res.status(200); res.json(recentlyActiveHackers); - }, + } ); app.get("/user", authorizer({ anyAdmin: true }), async (req, res) => { @@ -284,7 +284,7 @@ app.get("/user", authorizer({ anyAdmin: true }), async (req, res) => { fromTime, toTime, ingests[0].origin, - req.token.id, + req.token.id ); res.status(200); @@ -309,7 +309,7 @@ app.get("/user/overage", authorizer({ anyAdmin: true }), async (req, res) => { const user = await db.user.get(req.query.userId); if (!user) { - throw new NotFoundError(`user not found: ${req.query.userId}`); + throw new NotFoundError(`Account not found: ${req.query.userId}`); } const ingests = await req.getIngest(); @@ -319,17 +319,17 @@ app.get("/user/overage", authorizer({ anyAdmin: true }), async (req, res) => { fromTime, toTime, ingests[0].origin, - req.token.id, + req.token.id ); const overage = await calculateOverUsage( products[user.stripeProductId], - usage, + usage ); const usagePercentages = await getUsagePercentageOfLimit( products[user.stripeProductId], - usage, + usage ); res.status(200); @@ -350,7 +350,7 @@ app.post("/update", authorizer({ anyAdmin: true }), async (req, res) => { updateUsageTo: toTime, updateUsageApiToken: req.token.id, }, - { jobsDb, stripe: req.stripe }, + { jobsDb, stripe: req.stripe } ); res.status(200); diff --git a/packages/api/src/controllers/user.test.ts b/packages/api/src/controllers/user.test.ts index 041ed0c39c..6350ffa689 100644 --- a/packages/api/src/controllers/user.test.ts +++ b/packages/api/src/controllers/user.test.ts @@ -134,7 +134,7 @@ describe("controllers/user", () => { let resTwoJson = await resTwo.json(); expect(resTwo.status).toBe(409); expect(resTwoJson.errors[0]).toBe( - "email already registered - please sign in instead or check your verification email", + "email already registered - please sign in instead or check your verification email" ); // Registering a user with the same uppercased email should fail @@ -145,7 +145,7 @@ describe("controllers/user", () => { let resThreeJson = await resThree.json(); expect(resThree.status).toBe(409); expect(resThreeJson.errors[0]).toBe( - "email already registered - please sign in instead or check your verification email", + "email already registered - please sign in instead or check your verification email" ); }); @@ -263,7 +263,7 @@ describe("controllers/user", () => { let adminChange = await resAdminChange.json(); expect(adminChange.errors[0]).toBe( - `user does not have admin priviledges`, + `user does not have admin priviledges` ); }); @@ -276,7 +276,7 @@ describe("controllers/user", () => { }); expect(res.status).toBe(404); let tokenRes = await res.json(); - expect(tokenRes.errors[0]).toBe(`user not found`); + expect(tokenRes.errors[0]).toBe(`Account not found`); // create user res = await client.post("/user", { @@ -378,7 +378,7 @@ describe("controllers/user", () => { }); expect(req.status).toBe(404); let resp = await req.json(); - expect(resp.errors[0]).toBe("user not found"); + expect(resp.errors[0]).toBe("Account not found"); // should return 422 when extra property added to request req = await client.post(`/user/password/reset-token`, { @@ -453,7 +453,7 @@ describe("controllers/user", () => { expect(refreshToken.revoked).toBeFalsy(); expect(refreshToken.createdAt).toBeLessThanOrEqual(Date.now()); expect(refreshToken.expiresAt).toBeGreaterThan( - Date.now() + REFRESH_TOKEN_TTL - 60000, + Date.now() + REFRESH_TOKEN_TTL - 60000 ); }; @@ -514,14 +514,14 @@ describe("controllers/user", () => { expect(res.status).toBe(201); mockTimeDelay( - ACCESS_TOKEN_TTL * REFRESH_TOKEN_MIN_REUSE_DELAY_RATIO - 60 * 1000, + ACCESS_TOKEN_TTL * REFRESH_TOKEN_MIN_REUSE_DELAY_RATIO - 60 * 1000 ); res = await client.post("/user/token/refresh", { refreshToken }); expect(res.status).toBe(401); const { errors } = await res.json(); expect(errors[0]).toBe( - "refresh token has already been used too recently", + "refresh token has already been used too recently" ); const refreshTokenObj = await db.jwtRefreshToken.get(refreshToken); @@ -553,7 +553,7 @@ describe("controllers/user", () => { it("should generate a new refresh token when close to expiration", async () => { mockTimeDelay( - REFRESH_TOKEN_TTL * (1 - REFRESH_TOKEN_REFRESH_THRESHOLD) + 60 * 1000, + REFRESH_TOKEN_TTL * (1 - REFRESH_TOKEN_REFRESH_THRESHOLD) + 60 * 1000 ); const res = await client.post("/user/token/refresh", { @@ -596,7 +596,7 @@ describe("controllers/user", () => { { algorithm: "HS256", jwtid: uuid(), - }, + } ); mockTime(NEVER_EXPIRING_JWT_CUTOFF_DATE - 24 * 60 * 60 * 1000); @@ -614,7 +614,7 @@ describe("controllers/user", () => { expect(res.status).toBe(401); const { errors } = await res.json(); expect(errors[0]).toBe( - "legacy access token detected. please log in again", + "legacy access token detected. please log in again" ); }); @@ -671,7 +671,7 @@ describe("controllers/user", () => { let resJson = await res.json(); expect(res.status).toBe(403); expect(resJson.errors[0]).toBe( - `user ${nonAdminUser.email} has not been verified. please check your inbox for verification email.`, + `user ${nonAdminUser.email} has not been verified. please check your inbox for verification email.` ); client.apiKey = adminApiKey; @@ -679,7 +679,7 @@ describe("controllers/user", () => { resJson = await res.json(); expect(res.status).toBe(403); expect(resJson.errors[0]).toBe( - `user ${adminUser.email} has not been verified. please check your inbox for verification email.`, + `user ${adminUser.email} has not been verified. please check your inbox for verification email.` ); // adding emailValid true to user diff --git a/packages/api/src/controllers/user.ts b/packages/api/src/controllers/user.ts index 510bdfe59a..a3aa7c6277 100644 --- a/packages/api/src/controllers/user.ts +++ b/packages/api/src/controllers/user.ts @@ -80,7 +80,7 @@ async function findUserByEmail(email: string, useReplica = true) { // Look for user by lowercase email const [lowercaseUsers] = await db.user.find( { email: email.toLowerCase() }, - { useReplica }, + { useReplica } ); if (lowercaseUsers?.length === 1) { return lowercaseUsers[0]; @@ -91,7 +91,7 @@ async function findUserByEmail(email: string, useReplica = true) { // Look for user by original email const [users] = await db.user.find({ email }, { useReplica }); if (!users?.length) { - throw new NotFoundError("user not found"); + throw new NotFoundError("Account not found"); } else if (users.length > 1) { throw new InternalServerError("multiple users found with same email"); } @@ -100,12 +100,12 @@ async function findUserByEmail(email: string, useReplica = true) { async function isEmailRegistered( email: string, - useReplica = true, + useReplica = true ): Promise { // Check if lowercase email is already registered const [lowercaseUsers] = await db.user.find( { email: email.toLowerCase() }, - { useReplica }, + { useReplica } ); if (lowercaseUsers?.length > 0) return true; @@ -119,7 +119,7 @@ export const frontendUrl = ( headers: { "x-forwarded-proto": proto }, config: { frontendDomain }, }: Pick, - path: string, + path: string ) => `${proto || "https"}://${frontendDomain}${path}`; export const unsubscribeUrl = (req: Pick) => @@ -127,7 +127,7 @@ export const unsubscribeUrl = (req: Pick) => export async function terminateUserStreams( req: Request, - userId: string, + userId: string ): Promise { const [streams] = await db.stream.find([ sql`stream.data->>'parentId' IS NULL`, @@ -139,7 +139,7 @@ export async function terminateUserStreams( await triggerCatalystStreamStopSessions(req, stream.playbackId); } catch (err) { logger.error( - `error suspending stream id=${stream.id} userId=${userId} err=${err}`, + `error suspending stream id=${stream.id} userId=${userId} err=${err}` ); } } @@ -161,7 +161,7 @@ async function createSubscription( stripe: Stripe, stripeProductId: StripeProductIDs, stripeCustomerId: string, - withPayAsYouGo: boolean, + withPayAsYouGo: boolean ) { const existing = await stripe.subscriptions.list({ customer: stripeCustomerId, @@ -207,7 +207,7 @@ async function createDefaultProject(userId: string): Promise> { function signUserJwt( userId: string, - { jwtAudience, jwtSecret, jwtAccessTokenTtl }: CliArgs, + { jwtAudience, jwtSecret, jwtAccessTokenTtl }: CliArgs ) { return jwt.sign({ sub: userId, aud: jwtAudience }, jwtSecret, { algorithm: "HS256", @@ -294,7 +294,7 @@ app.delete("/:id", authorizer({ anyAdmin: true }), async (req, res) => { const user = await db.user.get(id); if (!user) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } await db.user.delete(id); @@ -330,7 +330,7 @@ app.post("/", validatePost("user"), async (req, res) => { try { const recaptchaScore = await recaptchaVerify( recaptchaToken, - req.config.recaptchaSecretKey, + req.config.recaptchaSecretKey ); if (recaptchaScore < 0.5) { res.status(400); @@ -381,7 +381,7 @@ app.post("/", validatePost("user"), async (req, res) => { if (!oneUser) { logger.warn("!!!!!!!!!!!!!!!!!!!"); logger.warn( - `first user detected, promoting new admin userId=${id} email=${email}`, + `first user detected, promoting new admin userId=${id} email=${email}` ); logger.warn("!!!!!!!!!!!!!!!!!!!"); admin = true; @@ -396,7 +396,7 @@ app.post("/", validatePost("user"), async (req, res) => { req.stripe, defaultProductId, customer.id, - true, + true ); if (!subscription) { res.status(400); @@ -456,7 +456,7 @@ app.post("/", validatePost("user"), async (req, res) => { email: lowercaseEmail, emailValidToken, selectedPlan, - })}`, + })}` ), unsubscribe: unsubscribeUrl(req), text: [ @@ -542,7 +542,7 @@ app.patch("/:id/email", authorizer({}), async (req, res) => { } if (!user) { - return res.status(404).json({ errors: ["User not found"] }); + return res.status(404).json({ errors: ["Account not found"] }); } await db.user.update(req.params.id, { @@ -573,7 +573,7 @@ app.patch("/:id/email", authorizer({}), async (req, res) => { `/dashboard/verify-new-email?${qs.stringify({ emailValidToken, email: lowerCaseEmail, - })}`, + })}` ), unsubscribe: unsubscribeUrl(req), text: ["Please verify your new email address."].join("\n\n"), @@ -609,7 +609,7 @@ app.get("/verify/new-email", async (req, res) => { }); const suspensionEmailText = ( - emailTemplate: SuspendUserPayload["emailTemplate"], + emailTemplate: SuspendUserPayload["emailTemplate"] ) => { switch (emailTemplate) { case "copyright": @@ -646,7 +646,7 @@ app.patch( if (suspended) { terminateUserStreams(req, id).catch((err) => { logger.error( - `error terminating user streams id=${id} email=${email} err=${err}`, + `error terminating user streams id=${id} email=${email} err=${err}` ); }); } @@ -674,14 +674,14 @@ app.patch( }); } catch (err) { logger.error( - `error sending suspension email to user=${email} err=${err}`, + `error sending suspension email to user=${email} err=${err}` ); } } res.status(204); res.end(); - }, + } ); app.patch( @@ -706,7 +706,7 @@ app.patch( if (disabled) { terminateUserStreams(req, id).catch((err) => { logger.error( - `error terminating user streams id=${id} email=${email} err=${err}`, + `error terminating user streams id=${id} email=${email} err=${err}` ); }); } @@ -737,14 +737,14 @@ app.patch( }); } catch (err) { logger.error( - `error sending disabled email to user=${email} err=${err}`, + `error sending disabled email to user=${email} err=${err}` ); } } res.status(204); res.end(); - }, + } ); app.patch("/:id", authorizer({ anyAdmin: true }), async (req, res) => { @@ -771,7 +771,7 @@ app.post("/token", validatePost("user"), async (req, res) => { const [hashedPassword] = await hash(req.body.password, user.salt); if (hashedPassword !== user.password) { res.status(403); - res.json({ errors: ["incorrect password"] }); + res.json({ errors: ["Password incorrect"] }); return; } @@ -835,7 +835,7 @@ app.post( refreshTokenObj.revoked ) { console.log( - `Refresh attempt with invalid refresh token=${refreshToken} expiresAt=${refreshTokenObj?.expiresAt} revoked=${refreshTokenObj?.revoked}`, + `Refresh attempt with invalid refresh token=${refreshToken} expiresAt=${refreshTokenObj?.expiresAt} revoked=${refreshTokenObj?.revoked}` ); return res.status(401).json({ errors: ["invalid refresh token"] }); } @@ -845,7 +845,7 @@ app.post( req.config.jwtAccessTokenTtl * 1000 * REFRESH_TOKEN_MIN_REUSE_DELAY_RATIO; if (timeSinceLastRefresh < minReuseDelay) { console.log( - `Revoking token due to potential malicious use of refreshToken=${refreshToken}`, + `Revoking token due to potential malicious use of refreshToken=${refreshToken}` ); await db.jwtRefreshToken.update(refreshToken, { revoked: true, @@ -890,7 +890,7 @@ app.post( res.status(201); res.json({ token, refreshToken: newRefreshToken }); - }, + } ); // Utility to migrate from the never-expiring JWTs from the dashboard to @@ -918,7 +918,7 @@ app.post( res.status(201); res.json({ token, refreshToken: newRefreshToken }); - }, + } ); app.post("/verify", validatePost("user-verification"), async (req, res) => { @@ -977,7 +977,7 @@ app.post("/verify-email", validatePost("verify-email"), async (req, res) => { if (!user) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } const emailSent = await sendVerificationEmail(req, user, selectedPlan); @@ -1016,7 +1016,7 @@ async function sendVerificationEmail(req: Request, user: User, selectedPlan) { email, emailValidToken, selectedPlan, - })}`, + })}` ), unsubscribe: unsubscribeUrl(req), text: [ @@ -1069,7 +1069,7 @@ app.post( const userResp = await db.user.get(user.id); res.status(200).json(cleanUserFields(userResp)); - }, + } ); app.post( @@ -1105,7 +1105,7 @@ app.post( buttonText: "Reset Password", buttonUrl: frontendUrl( req, - `/dashboard/reset-password?${qs.stringify({ email, resetToken })}`, + `/dashboard/reset-password?${qs.stringify({ email, resetToken })}` ), unsubscribe: unsubscribeUrl(req), text: [ @@ -1121,7 +1121,7 @@ app.post( } const newToken = db.passwordResetToken.cleanWriteOnlyResponse( - await db.passwordResetToken.get(id), + await db.passwordResetToken.get(id) ); if (newToken) { res.status(201); @@ -1130,7 +1130,7 @@ app.post( res.status(403); res.json({ errors: ["error creating password reset token"] }); } - }, + } ); app.post( @@ -1142,7 +1142,7 @@ app.post( await db.user.update(user.id, { admin: req.body.admin }); user = await db.user.get(user.id); res.status(200).json(cleanUserFields(user, req.user.admin)); - }, + } ); app.post( @@ -1162,7 +1162,7 @@ app.post( if (!customer) { logger.warn( - `deprecated /create-customer API used. userEmail=${user.email} createdAt=${user.createdAt}`, + `deprecated /create-customer API used. userEmail=${user.email} createdAt=${user.createdAt}` ); customer = await getOrCreateCustomer(req.stripe, email); await db.user.update(user.id, { @@ -1174,7 +1174,7 @@ app.post( res.status(400); res.json({ errors: ["error creating customer"] }); } - }, + } ); app.post( @@ -1185,11 +1185,11 @@ app.post( async (req, res) => { const [users] = await db.user.find( { stripeCustomerId: req.body.stripeCustomerId }, - { useReplica: false }, + { useReplica: false } ); if (users.length < 1 || users[0].id !== req.user.id) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } let user = users[0]; @@ -1197,7 +1197,7 @@ app.post( req.body.stripeCustomerPaymentMethodId, { customer: req.body.stripeCustomerId, - }, + } ); const customer = await req.stripe.customers.update( @@ -1206,7 +1206,7 @@ app.post( invoice_settings: { default_payment_method: req.body.stripeCustomerPaymentMethodId, }, - }, + } ); // Update user's payment method @@ -1216,7 +1216,7 @@ app.post( ccBrand: paymentMethod.card.brand, }); res.json(customer); - }, + } ); app.post( @@ -1228,34 +1228,34 @@ app.post( req.body as CreateSubscription; const [users] = await db.user.find( { stripeCustomerId: stripeCustomerId }, - { useReplica: false }, + { useReplica: false } ); if (users.length < 1) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } let user = users[0]; if (user.stripeCustomerSubscriptionId) { const subscription = await req.stripe.subscriptions.retrieve( - user.stripeCustomerSubscriptionId, + user.stripeCustomerSubscriptionId ); return res.send(subscription); } logger.warn( - `deprecated /create-subscription API used. userEmail=${user.email} createdAt=${user.createdAt}`, + `deprecated /create-subscription API used. userEmail=${user.email} createdAt=${user.createdAt}` ); // Attach the payment method to the customer if it exists (free plan doesn't require payment) if (stripeCustomerPaymentMethodId) { logger.warn( - `attaching payment method through /create-subscription. userEmail=${user.email} createdAt=${user.createdAt}`, + `attaching payment method through /create-subscription. userEmail=${user.email} createdAt=${user.createdAt}` ); try { const paymentMethod = await req.stripe.paymentMethods.attach( stripeCustomerPaymentMethodId, { customer: stripeCustomerId, - }, + } ); // Update user's payment method await db.user.update(user.id, { @@ -1280,7 +1280,7 @@ app.post( req.stripe, stripeProductId, stripeCustomerId, - false, + false ); if (!subscription) { return res @@ -1294,7 +1294,7 @@ app.post( stripeCustomerSubscriptionId: subscription.id, }); res.send(subscription); - }, + } ); app.post( @@ -1306,14 +1306,14 @@ app.post( const payload = req.body as UpdateSubscription; const [users] = await db.user.find( { stripeCustomerId: payload.stripeCustomerId }, - { useReplica: false }, + { useReplica: false } ); if ( users.length < 1 || users[0].stripeCustomerId !== payload.stripeCustomerId ) { res.status(404); - return res.json({ errors: ["user not found"] }); + return res.json({ errors: ["Account not found"] }); } let user = users[0]; @@ -1324,7 +1324,7 @@ app.post( payload.stripeCustomerPaymentMethodId, { customer: payload.stripeCustomerId, - }, + } ); // Update user's payment method in our db await db.user.update(user.id, { @@ -1351,7 +1351,7 @@ app.post( // Get the subscription const subscription = await req.stripe.subscriptions.retrieve( - payload.stripeCustomerSubscriptionId, + payload.stripeCustomerSubscriptionId ); // Get the prices associated with the subscription @@ -1378,7 +1378,7 @@ app.post( price: item.id, })), ], - }, + } ); } else { let payAsYouGoItems = []; @@ -1413,7 +1413,7 @@ app.post( })), ...payAsYouGoItems, ], - }, + } ); } @@ -1432,7 +1432,7 @@ app.post( planChangedAt: Date.now(), }); res.send(updatedSubscription); - }, + } ); app.post( @@ -1447,10 +1447,10 @@ app.post( return res.status(403).json({ errors: ["access forbidden"] }); } const subscription = await req.stripe.subscriptions.retrieve( - stripeCustomerSubscriptionId, + stripeCustomerSubscriptionId ); res.status(200).json(subscription); - }, + } ); app.post( @@ -1466,7 +1466,7 @@ app.post( customer: stripeCustomerId, }); res.status(200).json(invoices); - }, + } ); app.post( @@ -1491,7 +1491,7 @@ app.post( invoices, subscriptionItems, }); - }, + } ); app.post( @@ -1504,10 +1504,10 @@ app.post( return res.status(403).json({ errors: ["access forbidden"] }); } const paymentMethod = await req.stripe.paymentMethods.retrieve( - stripePaymentMethodId, + stripePaymentMethodId ); res.status(200).json(paymentMethod); - }, + } ); export default app; diff --git a/packages/api/src/controllers/utils/notification.ts b/packages/api/src/controllers/utils/notification.ts index 414ba215db..379158a6ad 100644 --- a/packages/api/src/controllers/utils/notification.ts +++ b/packages/api/src/controllers/utils/notification.ts @@ -13,7 +13,7 @@ export const getUsageNotifications = async ( DeliveryUsageMins: number; StorageUsageMins: number; }, - user: WithID, + user: WithID ) => { let notifications = []; const { TotalUsageMins, DeliveryUsageMins, StorageUsageMins } = @@ -21,7 +21,7 @@ export const getUsageNotifications = async ( if ( [TotalUsageMins, DeliveryUsageMins, StorageUsageMins].some( - (min) => min > 90, + (min) => min > 90 ) ) { notifications.push({ @@ -43,7 +43,7 @@ export const getUsageNotifications = async ( } } else if ( [TotalUsageMins, DeliveryUsageMins, StorageUsageMins].some( - (min) => min > 90, + (min) => min > 90 ) ) { notifications.push({ @@ -53,7 +53,7 @@ export const getUsageNotifications = async ( }); } else if ( [TotalUsageMins, DeliveryUsageMins, StorageUsageMins].some( - (min) => min > 75, + (min) => min > 75 ) ) { notifications.push({ @@ -91,7 +91,7 @@ type Notification = { export const notifyUser = async ( notifications: Notification[], user: User, - req: Pick, + req: Pick ) => { for (let notification of notifications) { if (user.notifications?.usage?.[notification.type]) { @@ -124,7 +124,7 @@ export const notifyUser = async ( export const notifyMissingPaymentMethod = async ( user: WithID, - req: Request, + req: Request ) => { console.log(` usage: user=${user.id} is in overusage but doesn't have a payment method, notifying support team diff --git a/packages/api/src/controllers/webhook-log.ts b/packages/api/src/controllers/webhook-log.ts index 9d79b0b132..a080139b09 100644 --- a/packages/api/src/controllers/webhook-log.ts +++ b/packages/api/src/controllers/webhook-log.ts @@ -55,7 +55,7 @@ app.get("/:requestId", authorizer({}), async (req, res) => { async function checkRequest( req: Request, webhook: DBWebhook, - webhookLog: WebhookLog, + webhookLog: WebhookLog ) { if (!webhook || webhook.deleted) { throw new NotFoundError(`webhook not found`); @@ -76,7 +76,7 @@ async function checkRequest( app.get("/", authorizer({}), async (req, res) => { let { limit, cursor, all, allUsers, order, filters, count } = toStringValues( - req.query, + req.query ); if (isNaN(parseInt(limit))) { limit = undefined; diff --git a/packages/api/src/controllers/webhook.test.ts b/packages/api/src/controllers/webhook.test.ts index ace43a56a6..7cb0235abb 100644 --- a/packages/api/src/controllers/webhook.test.ts +++ b/packages/api/src/controllers/webhook.test.ts @@ -79,7 +79,7 @@ async function setupUsers(server) { const nonAdminUserRes = await server.store.get( `user/${nonAdminUser.id}`, - false, + false ); nonAdminUser = { ...nonAdminUserRes, emailValid: true }; await server.store.replace(nonAdminUser); @@ -166,7 +166,7 @@ describe("controllers/webhook", () => { const resJson = await res.json(); expect(res.status).toBe(200); expect(res.headers.get("link")).toEqual( - expect.stringContaining("cursor="), + expect.stringContaining("cursor=") ); expect(resJson).toHaveLength(1); expect(resJson[0].userId).toEqual(generatedWebhook.userId); @@ -353,13 +353,13 @@ describe("controllers/webhook", () => { expect(webhookRequest.response.body).toBeDefined(); const getRes = await client.get( - `/webhook/${generatedWebhook.id}/log/${webhookRequest.id}`, + `/webhook/${generatedWebhook.id}/log/${webhookRequest.id}` ); expect(getRes.status).toBe(200); const getJson = await getRes.json(); expect(getJson.id).toEqual(webhookRequest.id); const resendRes = await client.post( - `/webhook/${generatedWebhook.id}/log/${webhookRequest.id}/resend`, + `/webhook/${generatedWebhook.id}/log/${webhookRequest.id}/resend` ); expect(resendRes.status).toBe(200); const resent = await resendRes.json(); @@ -374,7 +374,7 @@ describe("controllers/webhook", () => { // try query filters logRes = await client.get( - `/webhook/${generatedWebhook.id}/log?filters=[{"id":"success","value":"false"}]`, + `/webhook/${generatedWebhook.id}/log?filters=[{"id":"success","value":"false"}]` ); expect(logRes.status).toBe(200); logJson = await logRes.json(); diff --git a/packages/api/src/controllers/webhook.ts b/packages/api/src/controllers/webhook.ts index 87498e18e3..4d15231185 100644 --- a/packages/api/src/controllers/webhook.ts +++ b/packages/api/src/controllers/webhook.ts @@ -28,7 +28,7 @@ function validateWebhookPayload(id, userId, projectId, createdAt, payload) { if (!payload.events && !payload.event) { throw new UnprocessableEntityError( - `must provide "events" field with subscriptions`, + `must provide "events" field with subscriptions` ); } @@ -111,7 +111,7 @@ app.get("/", authorizer({}), async (req, res) => { query.push( sql`coalesce(webhook.data->>'projectId', ${ req.user.defaultProjectId || "" - }) = ${req.project?.id || ""}`, + }) = ${req.project?.id || ""}` ); if (!all || all === "false" || !req.user.admin) { @@ -167,7 +167,7 @@ app.post("/", authorizer({}), validatePost("webhook"), async (req, res) => { req.user.id, req.project?.id, Date.now(), - req.body, + req.body ); try { await req.store.create(doc); @@ -201,7 +201,7 @@ app.put("/:id", authorizer({}), validatePost("webhook"), async (req, res) => { userId, projectId, createdAt, - req.body, + req.body ); try { await req.store.replace(doc); @@ -245,7 +245,7 @@ app.patch( }); res.status(204).end(); - }, + } ); app.delete("/:id", authorizer({}), async (req, res) => { diff --git a/packages/api/src/controllers/wowza-hydrate.js b/packages/api/src/controllers/wowza-hydrate.js index 19423fda9e..5de5e573ac 100644 --- a/packages/api/src/controllers/wowza-hydrate.js +++ b/packages/api/src/controllers/wowza-hydrate.js @@ -80,7 +80,7 @@ export default (stream) => { // Dedupe profiles profiles = [...new Set(profiles)]; const enabledEncodeNames = new Set( - enabledEncodes.map((encode) => encode.name), + enabledEncodes.map((encode) => encode.name) ); const streamNameGroups = transcoderConfig.streamNameGroups.map( (streamNameGroup) => { @@ -89,7 +89,7 @@ export default (stream) => { .filter((name) => enabledEncodeNames.has(name)) .map((encodeName) => encodeNameToRenditionName[encodeName]); return { name, renditions }; - }, + } ); const presets = []; return { diff --git a/packages/api/src/hash.js b/packages/api/src/hash.js index 297f2e7cdf..9595e808dd 100644 --- a/packages/api/src/hash.js +++ b/packages/api/src/hash.js @@ -29,7 +29,7 @@ export default async function hash(password, salt) { passphraseKey, { name: "PBKDF2" }, false, - ["deriveBits", "deriveKey"], + ["deriveBits", "deriveKey"] ); const webKey = await crypto.subtle.deriveKey( { @@ -52,7 +52,7 @@ export default async function hash(password, salt) { true, // this web crypto object will only be allowed for these functions - ["encrypt", "decrypt"], + ["encrypt", "decrypt"] ); const buffer = await crypto.subtle.exportKey("raw", webKey); diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 74f4f80ed7..42d291a16f 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -121,7 +121,7 @@ export default async function makeApp(params: CliArgs) { } return false; }, - }), + }) ); app.use(router); @@ -139,14 +139,14 @@ export default async function makeApp(params: CliArgs) { version: getGitHash(), app: "studio-api", }, - 1, + 1 ); await new Promise((resolve, reject) => { listener = app.listen(port, () => { const address = listener.address() as AddressInfo; listenPort = address.port; logger.info( - `API server listening on http://0.0.0.0:${listenPort}${httpPrefix}`, + `API server listening on http://0.0.0.0:${listenPort}${httpPrefix}` ); resolve(); }); diff --git a/packages/api/src/jobs/active-cleanup.test.ts b/packages/api/src/jobs/active-cleanup.test.ts index 1990104459..7c53d6f5db 100644 --- a/packages/api/src/jobs/active-cleanup.test.ts +++ b/packages/api/src/jobs/active-cleanup.test.ts @@ -70,7 +70,7 @@ describe("active-cleanup", () => { expect(initClientsSpy).toHaveBeenCalledTimes(1); expect(initClientsSpy).toHaveBeenLastCalledWith( params, - "active-cleanup-job", + "active-cleanup-job" ); expect(queue.consume).not.toHaveBeenCalled(); @@ -85,20 +85,20 @@ describe("active-cleanup", () => { // 3 active streams for (let i = 0; i < 3; i++) { await db.stream.create( - mockStream(true, now - streamController.ACTIVE_TIMEOUT / 2), + mockStream(true, now - streamController.ACTIVE_TIMEOUT / 2) ); } // 3 inactive streams for (let i = 0; i < 3; i++) { await db.stream.create( - mockStream(false, now - streamController.ACTIVE_TIMEOUT - 5000), + mockStream(false, now - streamController.ACTIVE_TIMEOUT - 5000) ); } // 3 active lost streams, only these should be cleaned up let expectedCleanedUp = []; for (let i = 0; i <= 3; i++) { const stream = await db.stream.create( - mockStream(true, now - streamController.ACTIVE_TIMEOUT - i), + mockStream(true, now - streamController.ACTIVE_TIMEOUT - i) ); expectedCleanedUp.push(stream); } @@ -110,7 +110,7 @@ describe("active-cleanup", () => { params, expectedCleanedUp, expect.any(RabbitQueue), - params.ingest[0].base, + params.ingest[0].base ); }); @@ -141,7 +141,7 @@ describe("active-cleanup", () => { "events.recording.waiting", expect.anything(), expect.any(Number), - "recording_waiting_delayed_events", + "recording_waiting_delayed_events" ); expect((queue.delayedPublishWebhook as any).mock.calls[0][1]).toMatchObject( { @@ -155,7 +155,7 @@ describe("active-cleanup", () => { id: session.id, }, }, - }, + } ); }); }); diff --git a/packages/api/src/jobs/active-cleanup.ts b/packages/api/src/jobs/active-cleanup.ts index a0f2033f08..a06477ae10 100644 --- a/packages/api/src/jobs/active-cleanup.ts +++ b/packages/api/src/jobs/active-cleanup.ts @@ -12,7 +12,7 @@ import Queue from "../store/queue"; // clean up logic for them. export default async function activeCleanup( config: CliArgs, - clients?: { jobsDb: DB; queue: Queue }, + clients?: { jobsDb: DB; queue: Queue } ) { if (!config.ingest?.length) { throw new Error("ingest not configured"); @@ -30,14 +30,14 @@ export default async function activeCleanup( { limit, order: "data->>'lastSeen' DESC", - }, + } ); const [cleanedUp, jobPromise] = triggerCleanUpIsActiveJob( config, streams, queue, - ingest[0].base, + ingest[0].base ); await jobPromise; diff --git a/packages/api/src/jobs/create-db-tables.test.ts b/packages/api/src/jobs/create-db-tables.test.ts index 9bb735a431..564ef5030f 100644 --- a/packages/api/src/jobs/create-db-tables.test.ts +++ b/packages/api/src/jobs/create-db-tables.test.ts @@ -8,7 +8,7 @@ describe("create-db-tables", () => { await createDbTables({ ...params, postgresCreateTables: false }); const res = await db.query( - "SELECT indexname FROM pg_indexes WHERE indexname NOT LIKE '%_pkey'", + "SELECT indexname FROM pg_indexes WHERE indexname NOT LIKE '%_pkey'" ); const indexes = res.rows?.map((r: any) => r.indexname).sort(); diff --git a/packages/api/src/jobs/create-db-tables.ts b/packages/api/src/jobs/create-db-tables.ts index 80e5b4b17a..fd601d2b6a 100644 --- a/packages/api/src/jobs/create-db-tables.ts +++ b/packages/api/src/jobs/create-db-tables.ts @@ -4,6 +4,6 @@ import { CliArgs } from "../parse-cli"; export default async function createDbTables(config: CliArgs) { await initDb( { ...config, postgresCreateTables: true }, - "create-db-tables-job", + "create-db-tables-job" ); } diff --git a/packages/api/src/jobs/index.ts b/packages/api/src/jobs/index.ts index 4fb9c091de..4e1b43a510 100644 --- a/packages/api/src/jobs/index.ts +++ b/packages/api/src/jobs/index.ts @@ -35,14 +35,14 @@ export async function runJob(jobName: JobType, config: CliArgs): Promise { const logCtx = result && result.logContext; logger.info( - `Ran job successfully. job=${jobName} time=${elapsedTimeSec}s ${logCtx}`, + `Ran job successfully. job=${jobName} time=${elapsedTimeSec}s ${logCtx}` ); process.exit(0); } catch (error) { logger.error( `Job failed. job=${jobName} error=${JSON.stringify( - error.message || error, - )} stack=${JSON.stringify(error.stack)}`, + error.message || error + )} stack=${JSON.stringify(error.stack)}` ); process.exit(1); } diff --git a/packages/api/src/jobs/update-usage.ts b/packages/api/src/jobs/update-usage.ts index d4ebef7b01..f7c1e96f21 100644 --- a/packages/api/src/jobs/update-usage.ts +++ b/packages/api/src/jobs/update-usage.ts @@ -7,7 +7,7 @@ import { DB } from "../store/db"; export default async function updateUsage( config: CliArgs, - clients?: { jobsDb: DB; stripe: Stripe }, + clients?: { jobsDb: DB; stripe: Stripe } ) { const { jobsDb, stripe } = clients ?? (await initClients(config, "update-usage-job")); @@ -23,7 +23,7 @@ export default async function updateUsage( let rows = ( await jobsDb.usage.find( {}, - { limit: 1, order: "data->>'date' DESC", useReplica: true }, + { limit: 1, order: "data->>'date' DESC", useReplica: true } ) )[0]; @@ -43,8 +43,8 @@ export default async function updateUsage( }); logger.info( `Updating usage from=${fromTime} to=${toTime} usageHistory=${JSON.stringify( - usageHistory, - )}`, + usageHistory + )}` ); // store each day of usage diff --git a/packages/api/src/logger.js b/packages/api/src/logger.js index 0330f7cedb..ed64379ae8 100644 --- a/packages/api/src/logger.js +++ b/packages/api/src/logger.js @@ -19,7 +19,7 @@ export default winston.createLogger({ return `${timestamp} [${level}]: ${message} ${ Object.keys(extra).length ? JSON.stringify(extra, null, 2) : "" }`; - }), + }) ), transports: [new winston.transports.Console()], }); diff --git a/packages/api/src/middleware/auth.test.ts b/packages/api/src/middleware/auth.test.ts index bae792a063..23db58bccb 100644 --- a/packages/api/src/middleware/auth.test.ts +++ b/packages/api/src/middleware/auth.test.ts @@ -48,13 +48,13 @@ beforeAll(async () => { app.use(authenticator()); app.all("/admin/*", authorizer({ anyAdmin: true }), (_req, res) => - res.status(202).end(), + res.status(202).end() ); const router = Router(); router.use( "/nested", - Router().all("/*", authorizer({}), (_req, res) => res.status(203).end()), + Router().all("/*", authorizer({}), (_req, res) => res.status(203).end()) ); router.all("/*", authorizer({}), (_req, res) => res.status(203).end()); app.use("/router", router); @@ -93,7 +93,7 @@ describe("auth middleware", () => { ({ nonAdminUser, nonAdminApiKey, nonAdminToken } = await setupUsers( server, mockAdminUserInput, - mockNonAdminUserInput, + mockNonAdminUserInput )); basicAuth = `${nonAdminUser.id}:${nonAdminApiKey}`; basicAuth64 = Buffer.from(basicAuth).toString("base64"); @@ -138,7 +138,7 @@ describe("auth middleware", () => { const setAccess = async ( token: string, - rules?: ApiToken["access"]["rules"], + rules?: ApiToken["access"]["rules"] ) => db.apiToken.update(token, { access: { rules } }); const fetchStatus = async (method: string, path: string) => { @@ -191,7 +191,7 @@ describe("auth middleware", () => { { resources: ["foo"], methods: ["options"] }, { resources: ["foo/bar"], methods: ["get", "patch"] }, { resources: ["foo/bar/zaz"], methods: ["head", "post"] }, - ]), + ]) ); it("should disallow other methods", async () => { @@ -222,7 +222,7 @@ describe("auth middleware", () => { setAccess(nonAdminApiKey, [ { resources: ["gus/:id"] }, { resources: ["gus/fra/*"] }, - ]), + ]) ); it("should disallow other paths", async () => { @@ -445,11 +445,11 @@ describe("auth middleware", () => { if (method === "OPTIONS") { expect(res.status).toEqual(204); expect(res.headers.get("access-control-allow-methods")).toEqual( - "GET,HEAD,PUT,PATCH,POST,DELETE", + "GET,HEAD,PUT,PATCH,POST,DELETE" ); } expect(res.headers.get("access-control-allow-credentials")).toEqual( - "true", + "true" ); const corsAllowed = res.headers.get("access-control-allow-origin") === origin; @@ -474,7 +474,7 @@ describe("auth middleware", () => { await expectAllowed( "OPTIONS", "/asset/upload/direct?token=eyJhbG.eyJzdWI.SflKx", - origin, + origin ).toBe(true); await expectAllowed("OPTIONS", "/playback/1234", origin).toBe(true); await expectAllowed("OPTIONS", "/user", origin).toBe(true); @@ -487,7 +487,7 @@ describe("auth middleware", () => { await expectAllowed( method, "/asset/upload/direct?token=eyJhbG.eyJzdWI.SflKx", - origin, + origin ).toBe(true); await expectAllowed(method, "/playback/1234", origin).toBe(true); } @@ -500,7 +500,7 @@ describe("auth middleware", () => { await expectAllowed(method, "/asset/upload/url", origin).toBe(false); await expectAllowed(method, "/asset/upload", origin).toBe(false); await expectAllowed(method, "/asset/request-upload", origin).toBe( - false, + false ); await expectAllowed(method, "/playback", origin).toBe(false); await expectAllowed(method, "/stream", origin).toBe(false); @@ -514,15 +514,15 @@ describe("auth middleware", () => { client.jwtAuth = nonAdminToken; for (const method of testMethods) { await expectAllowed(method, "/stream", "https://livepeer.studio").toBe( - true, + true ); await expectAllowed(method, "/asset", "https://livepeer.studio").toBe( - true, + true ); await expectAllowed( method, "/api-token/1234", - "https://livepeer.studio", + "https://livepeer.studio" ).toBe(true); } }); @@ -550,10 +550,10 @@ describe("auth middleware", () => { const expected = allowedOrigins.includes(origin); await expectAllowed(method, "/asset/upload/url", origin).toBe( - expected, + expected ); await expectAllowed(method, "/asset/request-upload", origin).toBe( - expected, + expected ); await expectAllowed(method, "/asset", origin).toBe(expected); await expectAllowed(method, "/asset/abcd", origin).toBe(expected); @@ -577,13 +577,13 @@ describe("auth middleware", () => { client.apiKey = await createApiToken({ allowedOrigins }); // control case await expect( - fetchCors("GET", "/stream/1234", allowedOrigins[0]), + fetchCors("GET", "/stream/1234", allowedOrigins[0]) ).resolves.toMatchObject({ corsAllowed: true, status: 404, }); await expect( - fetchCors("GET", "/data/views/1234/total", allowedOrigins[0]), + fetchCors("GET", "/data/views/1234/total", allowedOrigins[0]) ).resolves.toMatchObject({ corsAllowed: true, status: 404, @@ -591,7 +591,7 @@ describe("auth middleware", () => { for (const [method, path] of forbiddenApis) { await expect( - fetchCors(method, path, allowedOrigins[0]), + fetchCors(method, path, allowedOrigins[0]) ).resolves.toMatchObject({ corsAllowed: true, status: 403, @@ -613,7 +613,7 @@ describe("auth middleware", () => { const { corsAllowed, status, body } = await fetchCors( method, path, - allowedOrigins[0], + allowedOrigins[0] ); expect(corsAllowed).toBe(true); expect([200, 403, 404, 422]).toContain(status); @@ -636,14 +636,14 @@ describe("auth middleware", () => { ]; for (const [method, path] of apis) { await expect( - fetchCors(method, path, "https://not.allowed.com"), + fetchCors(method, path, "https://not.allowed.com") ).resolves.toMatchObject({ corsAllowed: false, status: 403, body: { errors: [ expect.stringMatching( - /credential disallows CORS access from origin .+/, + /credential disallows CORS access from origin .+/ ), ], }, diff --git a/packages/api/src/middleware/auth.ts b/packages/api/src/middleware/auth.ts index 6c64262c31..fccb218bcb 100644 --- a/packages/api/src/middleware/auth.ts +++ b/packages/api/src/middleware/auth.ts @@ -46,7 +46,7 @@ function isAuthorized( method: string, path: string, rules: AuthRule[], - httpPrefix?: string, + httpPrefix?: string ) { try { const policy = new AuthPolicy(rules); @@ -74,7 +74,7 @@ export async function getProject(req: Request, projectId: string) { export function hasAccessToResource( { isUIAdmin, user, project }: Pick, resource?: DBOwnedResource, - uiAdminOnly = false, + uiAdminOnly = false ) { if (!resource || !user) { return false; @@ -160,7 +160,7 @@ function authenticator(): RequestHandler { Date.now() > NEVER_EXPIRING_JWT_CUTOFF_DATE ) { throw new UnauthorizedError( - "legacy access token detected. please log in again", + "legacy access token detected. please log in again" ); } tracking.recordUser(userId); @@ -172,7 +172,7 @@ function authenticator(): RequestHandler { } } else { throw new UnauthorizedError( - `unsupported authorization header scheme: ${rawAuthScheme}`, + `unsupported authorization header scheme: ${rawAuthScheme}` ); } @@ -180,7 +180,7 @@ function authenticator(): RequestHandler { if (!user) { throw new UnauthorizedError( - `no user found from authorization header: ${authHeader}`, + `no user found from authorization header: ${authHeader}` ); } if (user.suspended) { @@ -204,7 +204,7 @@ function authenticator(): RequestHandler { req.checkResourceAccess = ( resource?: DBOwnedResource, - uiAdminOnly = false, + uiAdminOnly = false ) => { if (!hasAccessToResource(req, resource, uiAdminOnly)) { throw new NotFoundError("not found"); @@ -375,7 +375,7 @@ function authorizer(params: AuthzParams): RequestHandler { const resOrigin = res.getHeader("access-control-allow-origin")?.toString(); if (reqOrigin && reqOrigin !== resOrigin) { throw new ForbiddenError( - `credential disallows CORS access from origin ${reqOrigin}`, + `credential disallows CORS access from origin ${reqOrigin}` ); } @@ -385,7 +385,7 @@ function authorizer(params: AuthzParams): RequestHandler { user.createdAt > EMAIL_VERIFICATION_CUTOFF_DATE; if (verifyEmail && !user.emailValid) { throw new ForbiddenError( - `user ${user.email} has not been verified. please check your inbox for verification email.`, + `user ${user.email} has not been verified. please check your inbox for verification email.` ); } @@ -394,7 +394,7 @@ function authorizer(params: AuthzParams): RequestHandler { } if (token?.access?.cors && req.user.admin) { throw new ForbiddenError( - `cors access is not available to admins (how did you get this API key?)`, + `cors access is not available to admins (how did you get this API key?)` ); } const accessRules = tokenAccessRules(token); @@ -410,7 +410,7 @@ function authorizer(params: AuthzParams): RequestHandler { throw new ForbiddenError( isRestrictedCors(token) ? "access forbidden for CORS-enabled API key with restricted access" - : "credential has insufficent privileges", + : "credential has insufficent privileges" ); } } diff --git a/packages/api/src/middleware/geolocate.js b/packages/api/src/middleware/geolocate.js index e6bb8e08d2..a8d8789667 100644 --- a/packages/api/src/middleware/geolocate.js +++ b/packages/api/src/middleware/geolocate.js @@ -38,7 +38,7 @@ function geoLocateFactory({ first = true, region = "region" }) { const res = await fetch(upstreamUrl); if (res.status !== 200) { const err = new Error( - `${upstreamUrl} HTTP ${res.status}: ${await res.text()}`, + `${upstreamUrl} HTTP ${res.status}: ${await res.text()}` ); errors.push(err); throw err; diff --git a/packages/api/src/middleware/hardcoded-nodes.ts b/packages/api/src/middleware/hardcoded-nodes.ts index 2635eeb42c..f44c207a7c 100644 --- a/packages/api/src/middleware/hardcoded-nodes.ts +++ b/packages/api/src/middleware/hardcoded-nodes.ts @@ -31,7 +31,7 @@ export default function hardcodedNodes({ } if (orchestrators?.length) { req.orchestratorsGetters.push( - async () => orchestrators as OrchestratorNodeAddress[], + async () => orchestrators as OrchestratorNodeAddress[] ); } if (!req.getIngest) { diff --git a/packages/api/src/middleware/subgraph.ts b/packages/api/src/middleware/subgraph.ts index 9157f29f26..b04eb3cc44 100644 --- a/packages/api/src/middleware/subgraph.ts +++ b/packages/api/src/middleware/subgraph.ts @@ -50,7 +50,7 @@ export default function subgraphMiddleware({ const transcoders = (await res.json()).data.transcoders; cachedResp = transcoders .filter( - (tr) => !(tr.id.toLowerCase() in blockList) && !!tr.serviceURI, + (tr) => !(tr.id.toLowerCase() in blockList) && !!tr.serviceURI ) .map((tr) => ({ address: tr.serviceURI, score: defaultScore })); diff --git a/packages/api/src/middleware/tracking.ts b/packages/api/src/middleware/tracking.ts index 4a1ff7786c..7b192ceb49 100644 --- a/packages/api/src/middleware/tracking.ts +++ b/packages/api/src/middleware/tracking.ts @@ -28,7 +28,7 @@ class Tracker { private recordLastSeen( table: Table<{ id: string; lastSeen?: number }>, - id: string, + id: string ) { const key = `${table.name}-${id}`; const alreadyScheduled = this.pendingUpdates.has(key); @@ -50,12 +50,12 @@ class Tracker { sql`id = ${id}`, sql`coalesce((data->'lastSeen')::bigint, 0) < ${lastSeen}`, ], - { lastSeen }, + { lastSeen } ); } catch (err) { console.log( `error saving last seen: table=${table?.name} id=${id} err=`, - err, + err ); } } diff --git a/packages/api/src/parse-cli.ts b/packages/api/src/parse-cli.ts index c3699a6535..74ad788a15 100755 --- a/packages/api/src/parse-cli.ts +++ b/packages/api/src/parse-cli.ts @@ -105,7 +105,7 @@ function coerceJsonProfileArr(flagName: string) { } if (errors.length > 0) { throw new Error( - `--${flagName} validation error: ${JSON.stringify(errors)}`, + `--${flagName} validation error: ${JSON.stringify(errors)}` ); } return profiles; @@ -321,7 +321,7 @@ export default function parseCli(argv?: string | readonly string[]) { const split = supportAddr.split("/"); if (split.length !== 2) { throw new Error( - `supportAddr should be of the form name / email, got ${supportAddr} `, + `supportAddr should be of the form name / email, got ${supportAddr} ` ); } return split as [string, string]; @@ -624,14 +624,14 @@ export default function parseCli(argv?: string | readonly string[]) { --broadcaster and --orchestrator options should be of the form [{"address":"https://127.0.0.1:3086","cliAddress":"http://127.0.0.1:3076"}] - `, + ` ) .strict( - process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "development", + process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "development" ) .env("LP_API_") .strict( - process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "development", + process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "development" ) .help() .parse(argv); diff --git a/packages/api/src/schema/api-schema.yaml b/packages/api/src/schema/api-schema.yaml index da9f9c4335..6b2ee80cac 100644 --- a/packages/api/src/schema/api-schema.yaml +++ b/packages/api/src/schema/api-schema.yaml @@ -971,7 +971,7 @@ components: type: string example: - id not provided - - user not found + - Account not found multistream-target: type: object required: diff --git a/packages/api/src/store/asset-table.test.ts b/packages/api/src/store/asset-table.test.ts index 3b27f87b82..f4a316d6c0 100644 --- a/packages/api/src/store/asset-table.test.ts +++ b/packages/api/src/store/asset-table.test.ts @@ -8,7 +8,7 @@ beforeAll(async () => { describe("assets table", () => { it("should create all indexes defined in the schema", async () => { const res = await db.query( - "SELECT indexname FROM pg_indexes WHERE tablename = 'asset' AND indexname != 'asset_pkey'", + "SELECT indexname FROM pg_indexes WHERE tablename = 'asset' AND indexname != 'asset_pkey'" ); const indexes = res.rows?.map((r: any) => r.indexname).sort(); expect(indexes).toEqual([ diff --git a/packages/api/src/store/asset-table.ts b/packages/api/src/store/asset-table.ts index 4d599b8e8f..8e795be8b8 100644 --- a/packages/api/src/store/asset-table.ts +++ b/packages/api/src/store/asset-table.ts @@ -6,7 +6,7 @@ import { QueryOptions, WithID } from "./types"; const DUPLICATE_ASSETS_THRESHOLD = 15 * 60 * 1000; // 15 mins export const taskOutputToIpfsStorage = ( - out: Task["output"]["export"]["ipfs"], + out: Task["output"]["export"]["ipfs"] ): Omit => !out ? null @@ -26,7 +26,7 @@ export const taskOutputToIpfsStorage = ( export default class AssetTable extends Table> { async getByPlaybackId( playbackId: string, - opts?: QueryOptions, + opts?: QueryOptions ): Promise> { const query = [ sql`asset.data->>'playbackId' = ${playbackId}`, @@ -45,19 +45,19 @@ export default class AssetTable extends Table> { async getByIpfsCid( cid: string, user?: User, - crossUserCutoffDate?: number, + crossUserCutoffDate?: number ): Promise> { return this.findFirstReady( [sql`asset.data->'storage'->'ipfs'->>'cid' = ${cid}`], user, - crossUserCutoffDate, + crossUserCutoffDate ); } async getBySourceURL( url: string, user?: User, - crossUserCutoffDate?: number, + crossUserCutoffDate?: number ): Promise> { return this.findFirstReady( [ @@ -66,14 +66,14 @@ export default class AssetTable extends Table> { sql`asset.data->'source'->>'encryption' IS NULL`, ], user, - crossUserCutoffDate, + crossUserCutoffDate ); } private async findFirstReady( query: SQLStatement[], user?: User, - crossUserCutoffDate?: number, + crossUserCutoffDate?: number ): Promise> { const findOnce = async (userQuery: SQLStatement[]) => { const [assets] = await this.find( @@ -86,7 +86,7 @@ export default class AssetTable extends Table> { { limit: 1, order: "coalesce((asset.data->'createdAt')::bigint, 0) ASC", - }, + } ); return assets.length > 0 ? assets[0] : null; }; @@ -122,7 +122,7 @@ export default class AssetTable extends Table> { async findDuplicateUrlUpload( url: string, user: User, - projectId: string, + projectId: string ): Promise> { const createdAfter = Date.now() - DUPLICATE_ASSETS_THRESHOLD; const query = [ diff --git a/packages/api/src/store/cache.ts b/packages/api/src/store/cache.ts index af10e20e8b..bb1cde807e 100644 --- a/packages/api/src/store/cache.ts +++ b/packages/api/src/store/cache.ts @@ -39,7 +39,7 @@ class Cache { async getOrSet( cacheKey: string, getter: () => Promise, - ttl?: string | number, + ttl?: string | number ) { let content = this.get(cacheKey); if (!content) { diff --git a/packages/api/src/store/cloudflare-cluster-store.js b/packages/api/src/store/cloudflare-cluster-store.js index 751f3c561c..cb92de39be 100644 --- a/packages/api/src/store/cloudflare-cluster-store.js +++ b/packages/api/src/store/cloudflare-cluster-store.js @@ -6,7 +6,7 @@ export default class CloudflareStore { this.KV = global[cloudflareNamespace]; if (!this.KV) { throw new Error( - `couldn't find cloudflare kv namespace at global.${cloudflareNamespace}`, + `couldn't find cloudflare kv namespace at global.${cloudflareNamespace}` ); } } diff --git a/packages/api/src/store/cloudflare-store.js b/packages/api/src/store/cloudflare-store.js index 6534135b22..76d0fcb121 100644 --- a/packages/api/src/store/cloudflare-store.js +++ b/packages/api/src/store/cloudflare-store.js @@ -13,7 +13,7 @@ export default class CloudflareStore { constructor({ cloudflareNamespace, cloudflareAccount, cloudflareAuth }) { if (!cloudflareNamespace || !cloudflareAccount || !cloudflareAuth) { throw new Error( - "no cloudflare namespace, account id, or authorization key provided", + "no cloudflare namespace, account id, or authorization key provided" ); } namespace = cloudflareNamespace; @@ -94,7 +94,7 @@ export default class CloudflareStore { async function cloudflareFetch( reqUrl, - { method = "GET", retries = 0, data = null } = {}, + { method = "GET", retries = 0, data = null } = {} ) { const req = { method: method, diff --git a/packages/api/src/store/db.ts b/packages/api/src/store/db.ts index d7e7d701dd..e02009e0a4 100644 --- a/packages/api/src/store/db.ts +++ b/packages/api/src/store/db.ts @@ -185,20 +185,20 @@ export class DB { if (createTablesOnDb) { const tables = Object.entries(schema.components.schemas).filter( - ([name, schema]) => "table" in schema && schema.table, + ([name, schema]) => "table" in schema && schema.table ); await Promise.all( tables.map(([name, schema]) => { const camelName = kebabToCamel(name); return this[camelName].ensureTable(); - }), + }) ); } } queryWithOpts( query: QueryConfig, - opts: QueryOptions = { useReplica: true }, + opts: QueryOptions = { useReplica: true } ): Promise> { const { useReplica = true } = opts; if (useReplica && this.replicaPool) { @@ -209,14 +209,14 @@ export class DB { query( query: string | QueryConfig, - values?: I, + values?: I ): Promise> { return this.runQuery(this.pool, query, values); } replicaQuery( query: string | QueryConfig, - values?: I, + values?: I ): Promise> { let pool = this.replicaPool ?? this.pool; return this.runQuery(pool, query, values); @@ -226,7 +226,7 @@ export class DB { async runQuery( pool: Pool, query: string | QueryConfig, - values?: I, + values?: I ): Promise> { let queryLog: string; if (typeof query === "string") { @@ -243,14 +243,14 @@ export class DB { logger.error( `runQuery phase=error elapsed=${Date.now() - start}ms error=${ e.message - } query=${queryLog}`, + } query=${queryLog}` ); throw e; } logger.debug( - `runQuery phase=success elapsed=${ - Date.now() - start - }ms rows=${result?.rowCount} query=${queryLog}`, + `runQuery phase=success elapsed=${Date.now() - start}ms rows=${ + result?.rowCount + } query=${queryLog}` ); return result; } diff --git a/packages/api/src/store/experiment-table.test.ts b/packages/api/src/store/experiment-table.test.ts index 417f7e0a7d..4a305e8b72 100644 --- a/packages/api/src/store/experiment-table.test.ts +++ b/packages/api/src/store/experiment-table.test.ts @@ -8,7 +8,7 @@ beforeAll(async () => { describe("experiment table", () => { it("should create all indexes defined in the schema", async () => { const res = await db.query( - "SELECT indexname FROM pg_indexes WHERE tablename = 'experiment' AND indexname != 'experiment_pkey'", + "SELECT indexname FROM pg_indexes WHERE tablename = 'experiment' AND indexname != 'experiment_pkey'" ); const indexes = res.rows?.map((r: any) => r.indexname).sort(); expect(indexes).toEqual([ @@ -20,12 +20,12 @@ describe("experiment table", () => { it("should use index to search for experiment audience", async () => { const res = await db.query( - "EXPLAIN SELECT * FROM experiment WHERE data->'audienceUserIds' @> '123456'", + "EXPLAIN SELECT * FROM experiment WHERE data->'audienceUserIds' @> '123456'" ); const result = JSON.stringify(res.rows); expect(result).toContain(`Index Scan on \\"experiment_audienceUserIds\\"`); expect(result).toContain( - `Index Cond: ((data -> 'audienceUserIds'::text) @> '123456'::jsonb)`, + `Index Cond: ((data -> 'audienceUserIds'::text) @> '123456'::jsonb)` ); }); }); diff --git a/packages/api/src/store/experiment-table.ts b/packages/api/src/store/experiment-table.ts index ab99b8b376..47289225f6 100644 --- a/packages/api/src/store/experiment-table.ts +++ b/packages/api/src/store/experiment-table.ts @@ -18,11 +18,11 @@ export async function isExperimentSubject(experiment: string, userId?: string) { export async function ensureExperimentSubject( experiment: string, - userId: string, + userId: string ) { if (!(await isExperimentSubject(experiment, userId))) { throw new ForbiddenError( - `user is not a subject of experiment: ${experiment}`, + `user is not a subject of experiment: ${experiment}` ); } } @@ -32,7 +32,7 @@ export default class ExperimentTable extends Table> { userId: string, limit = 1000, cursor?: string, - includeDeleted = false, + includeDeleted = false ) { const query = [sql`data->'audienceUserIds' @> ${userId}`]; if (!includeDeleted) { @@ -49,7 +49,7 @@ export default class ExperimentTable extends Table> { async getByNameOrId(nameOrId: string) { const [experiments] = await this.find( [sql`(data->>'name' = ${nameOrId} OR id = ${nameOrId})`], - { limit: 1 }, + { limit: 1 } ); if (!experiments?.length) { throw new NotFoundError("experiment not found"); diff --git a/packages/api/src/store/firestore-store.js b/packages/api/src/store/firestore-store.js index 288bf39dd4..ae7f9e8c82 100644 --- a/packages/api/src/store/firestore-store.js +++ b/packages/api/src/store/firestore-store.js @@ -36,7 +36,7 @@ export default class FirestoreStore { if (parts[0] && parts[0].includes("+")) { if (!parts[1]) { throw new Error( - `I'm confused, what do I convert this key into for firestore? ${key}`, + `I'm confused, what do I convert this key into for firestore? ${key}` ); } parts[1] = `${parts[0]}_${parts[1]}`; diff --git a/packages/api/src/store/firestore-store.test.js b/packages/api/src/store/firestore-store.test.js index 2ce7e07b09..39b2b258d9 100644 --- a/packages/api/src/store/firestore-store.test.js +++ b/packages/api/src/store/firestore-store.test.js @@ -27,13 +27,13 @@ describe("firestoreStore", () => { it("should change urls correctly", () => { expect(store.getPath("user/ABC123")).toBe("staging/docs/user/ABC123"); expect(store.getPath("user+email/example@livepeer.org/ABC123")).toBe( - "staging/docs/user%2Bemail_example%40livepeer.org/ABC123", + "staging/docs/user%2Bemail_example%40livepeer.org/ABC123" ); expect(store.getPath("user+email/example@livepeer.org/")).toBe( - "staging/docs/user%2Bemail_example%40livepeer.org", + "staging/docs/user%2Bemail_example%40livepeer.org" ); expect(store.getPath("user+email/example@livepeer.org")).toBe( - "staging/docs/user%2Bemail_example%40livepeer.org", + "staging/docs/user%2Bemail_example%40livepeer.org" ); }); }); diff --git a/packages/api/src/store/index.ts b/packages/api/src/store/index.ts index e4256c4c98..afa6d57c57 100644 --- a/packages/api/src/store/index.ts +++ b/packages/api/src/store/index.ts @@ -6,7 +6,7 @@ export { db, jobsDb }; // Helper function to start database and boot up legacy store export default async function makeStore( dbParams: PostgresParams, - jobsDbParams: PostgresParams, + jobsDbParams: PostgresParams ): Promise<[DB, DB, Model]> { await db.start(dbParams); await jobsDb.start({ ...jobsDbParams, createTablesOnDb: false }); diff --git a/packages/api/src/store/model.ts b/packages/api/src/store/model.ts index f127c9b36a..c76b38a2cf 100644 --- a/packages/api/src/store/model.ts +++ b/packages/api/src/store/model.ts @@ -78,7 +78,7 @@ export default class Model implements IStore { const [table] = this.getTable(prefix); const [response, nextCursor] = await this.db[table].find( {}, - { limit, cursor }, + { limit, cursor } ); const keys = response.map((x) => x.id); return [keys, nextCursor]; diff --git a/packages/api/src/store/multistream-table.ts b/packages/api/src/store/multistream-table.ts index 4d19565b6b..324221049a 100644 --- a/packages/api/src/store/multistream-table.ts +++ b/packages/api/src/store/multistream-table.ts @@ -52,7 +52,7 @@ export default class MultistreamTargetTable extends Table { id: string, userId: string, isAdmin: boolean, - opts?: GetOptions, + opts?: GetOptions ) { const target = await super.get(id, opts); return isAdmin || userId === target?.userId ? target : null; diff --git a/packages/api/src/store/queue.test.ts b/packages/api/src/store/queue.test.ts index a77b9db1e1..541c376bc2 100644 --- a/packages/api/src/store/queue.test.ts +++ b/packages/api/src/store/queue.test.ts @@ -86,7 +86,7 @@ describe("Queue", () => { event: "recording.ready", userId: "fdsa", }, - 2000, + 2000 ); await sem.wait(4000); let duration = consumedAt - emittedAt; @@ -120,7 +120,7 @@ describe("Queue", () => { event: "recording.ready", userId: "fdsa", }, - 1000, + 1000 ); await sem.wait(3000); let duration = consumedAt - emittedAt; @@ -164,7 +164,7 @@ describe("Queue", () => { event: "recording.ready", userId: "fdsa", }, - 1000, + 1000 ); await queue.delayedPublishWebhook( "events.recording.ready", @@ -176,7 +176,7 @@ describe("Queue", () => { event: "recording.ready", userId: "fdsa", }, - 200, + 200 ); await sem2.wait(3000); let duration = consumedAt2 - emittedAt; @@ -217,7 +217,7 @@ describe("Queue", () => { event: "recording.ready", userId: "fdsa", }, - 200, + 200 ); await queue.delayedPublishWebhook( "webhooks.recording.ready", @@ -229,7 +229,7 @@ describe("Queue", () => { event: "recording.ready", userId: "fdsa", }, - 200, + 200 ); await sem1.wait(3000); await sem2.wait(3000); diff --git a/packages/api/src/store/queue.ts b/packages/api/src/store/queue.ts index 8fcff4d7d6..75001e438f 100644 --- a/packages/api/src/store/queue.ts +++ b/packages/api/src/store/queue.ts @@ -10,13 +10,13 @@ const getExchanges = (tasksExchange = defaultTaskExchange) => ({ webhooks: "webhook_default_exchange", task: tasksExchange, - }) as const; + } as const); const getQueues = (tasksExchange = defaultTaskExchange) => ({ events: "webhook_events_queue_v1", webhooks: "webhook_cannon_single_url_v1", task: `${tasksExchange}_results`, - }) as const; + } as const); const delayedWebhookQueue = (delayMs: number) => `delayed_webhook_${delayMs}ms`; type Queues = ReturnType; @@ -32,14 +32,14 @@ export default interface Queue { publish( exchange: ExchangeName, key: RoutingKey, - msg: messages.Any, + msg: messages.Any ): Promise; publishWebhook(key: RoutingKey, msg: messages.Webhooks): Promise; delayedPublishWebhook( key: RoutingKey, msg: messages.Any, delay: number, - delayedQueueName?: string, + delayedQueueName?: string ): Promise; consume(name: QueueName, func: (msg: ConsumeMessage) => void): Promise; @@ -53,11 +53,11 @@ export class NoopQueue implements Queue { async publish( exchange: ExchangeName, key: RoutingKey, - msg: messages.Webhooks, + msg: messages.Webhooks ) { console.warn( `WARN: Publish to exchange=${exchange} on noop queue. key=${key} message=`, - msg, + msg ); } @@ -68,11 +68,11 @@ export class NoopQueue implements Queue { async delayedPublishWebhook( key: RoutingKey, msg: messages.Any, - delay: number, + delay: number ) { console.warn( `WARN: Delayed publish event to noop queue. key=${key} delay=${delay} message=`, - msg, + msg ); } @@ -93,7 +93,7 @@ export class RabbitQueue implements Queue { public static async connect( url: string, appName: string = "api", - tasksExchange = defaultTaskExchange, + tasksExchange = defaultTaskExchange ): Promise { const queue = new RabbitQueue(tasksExchange); await queue.init(url, appName); @@ -137,22 +137,22 @@ export class RabbitQueue implements Queue { channel.bindQueue( this.queues.events, this.exchanges.webhooks, - "events.#", + "events.#" ), channel.bindQueue( this.queues.webhooks, this.exchanges.webhooks, - "webhooks.#", + "webhooks.#" ), channel.bindQueue( this.queues.task, this.exchanges.task, - "task.result.#", + "task.result.#" ), channel.bindQueue( this.queues.task, this.exchanges.task, - "task.resultPartial.#", + "task.resultPartial.#" ), ]); await channel.prefetch(10); @@ -171,15 +171,13 @@ export class RabbitQueue implements Queue { this.connection.on("connectFailed", (err: Error) => { console.log("AMQP Connect Failed.", err); resolveOnce( - new Error( - `Error connecting to RabbitMQ. ${err.name}: ${err.message}`, - ), + new Error(`Error connecting to RabbitMQ. ${err.name}: ${err.message}`) ); }); this.connection.on("disconnect", ({ err }: { err: Error }) => { console.log("AMQP Disconnected.", err); resolveOnce( - new Error(`RabbitMQ disconnected. ${err.name}: ${err.message}`), + new Error(`RabbitMQ disconnected. ${err.name}: ${err.message}`) ); }); }); @@ -201,7 +199,7 @@ export class RabbitQueue implements Queue { public async consume( queueName: QueueName, - func: (msg: ConsumeMessage) => void, + func: (msg: ConsumeMessage) => void ): Promise { if (!func) { throw new Error("RabbitMQ | consume | func is undefined"); @@ -220,7 +218,7 @@ export class RabbitQueue implements Queue { public async publishWebhook( route: RoutingKey, - msg: messages.Any, + msg: messages.Any ): Promise { await this.publish("webhooks", route, msg); } @@ -228,12 +226,12 @@ export class RabbitQueue implements Queue { public async publish( exchangeName: ExchangeName, route: RoutingKey, - msg: messages.Any, + msg: messages.Any ): Promise { console.log( `publishing message route=${route} exchange=${exchangeName} msg=${JSON.stringify( - msg, - )}`, + msg + )}` ); await this._channelPublish(this.exchanges[exchangeName], route, msg, { persistent: true, @@ -250,7 +248,7 @@ export class RabbitQueue implements Queue { routingKey: RoutingKey, msg: messages.Any, delay: number, - delayedQueueName?: string, + delayedQueueName?: string ): Promise { delay = Math.round(delay); if (!delayedQueueName) { @@ -278,18 +276,18 @@ export class RabbitQueue implements Queue { console.log( `emitting delayed message: delay=${ delay / 1000 - }s queue=${delayedQueueName} msg=${JSON.stringify(msg)}`, + }s queue=${delayedQueueName} msg=${JSON.stringify(msg)}` ); return this._channelPublish(delayedQueueName, routingKey, msg, { persistent: true, }); - }, + } ); } private async _withSetup( setup: amqp.SetupFunc, - action: () => Promise, + action: () => Promise ): Promise { await this.channel.addSetup(setup); try { @@ -304,24 +302,24 @@ export class RabbitQueue implements Queue { exchange: string, routingKey: string, msg: any, - opts: amqp.Options.Publish, + opts: amqp.Options.Publish ) { try { const success = await this.channel.publish( exchange, routingKey, msg, - opts, + opts ); if (!success) { throw new Error( - `Failed to publish message ${routingKey}: publish buffer full`, + `Failed to publish message ${routingKey}: publish buffer full` ); } } catch (err) { console.error( `Error publishing message: exchange="${exchange}" routingKey="${routingKey}" err=`, - err, + err ); if (err?.message?.includes("timeout")) { throw new Error(`Timeout publishing message ${routingKey} to queue`); diff --git a/packages/api/src/store/session-table.ts b/packages/api/src/store/session-table.ts index 5a1a0ea74d..65571d21ad 100644 --- a/packages/api/src/store/session-table.ts +++ b/packages/api/src/store/session-table.ts @@ -11,9 +11,9 @@ export default class SessionTable extends Table { async getLastSession(parentId: string, opts?: QueryOptions) { const res: QueryResult = await this.db.queryWithOpts( sql`SELECT * FROM session WHERE data->>'parentId'=${parentId} ORDER BY data->>'createdAt' DESC LIMIT 1`.setName( - `${this.name}_last_by_parentid`, + `${this.name}_last_by_parentid` ), - opts, + opts ); return res.rowCount < 1 ? null : (res.rows[0].data as DBSession); } diff --git a/packages/api/src/store/stream-table.ts b/packages/api/src/store/stream-table.ts index eb3de818cb..e08958ebf9 100644 --- a/packages/api/src/store/stream-table.ts +++ b/packages/api/src/store/stream-table.ts @@ -76,7 +76,7 @@ export default class StreamTable extends Table { async cachedUsageHistory( fromTime: number, toTime: number, - opts?: QueryOptions, + opts?: QueryOptions ): Promise { let usage = []; const q1 = sql`SELECT @@ -206,7 +206,7 @@ export default class StreamTable extends Table { userId: string, fromTime: number | string, toTime: number | string, - opts?: QueryOptions, + opts?: QueryOptions ): Promise { const q1 = sql`SELECT sum((data->>'sourceSegmentsDuration')::float) as sourceSegmentsDuration, @@ -276,26 +276,26 @@ export default class StreamTable extends Table { async getByStreamKey( streamKey: string, - opts?: QueryOptions, + opts?: QueryOptions ): Promise { const res: QueryResult = await this.db.queryWithOpts( sql`SELECT data FROM stream WHERE data->>'streamKey'=${streamKey}`.setName( - `${this.name}_by_streamKey`, + `${this.name}_by_streamKey` ), - opts, + opts ); return res.rowCount < 1 ? null : (res.rows[0].data as DBStream); } async getByPlaybackId( playbackId: string, - opts?: QueryOptions, + opts?: QueryOptions ): Promise { const res: QueryResult = await this.db.queryWithOpts( sql`SELECT data FROM stream WHERE data->>'playbackId'=${playbackId}`.setName( - `${this.name}_by_playbackid`, + `${this.name}_by_playbackid` ), - opts, + opts ); return res.rowCount < 1 ? null : (res.rows[0].data as DBStream); } @@ -303,22 +303,22 @@ export default class StreamTable extends Table { async getLastSession(id: string, opts?: QueryOptions): Promise { const res: QueryResult = await this.db.queryWithOpts( sql`SELECT data FROM stream WHERE data->>'parentId'=${id} ORDER BY data->>'createdAt' DESC LIMIT 1`.setName( - `${this.name}_by_parentid_last_session`, + `${this.name}_by_parentid_last_session` ), - opts, + opts ); return res.rowCount < 1 ? null : (res.rows[0].data as DBStream); } async getActiveSessions( id: string, - opts?: QueryOptions, + opts?: QueryOptions ): Promise { const res: QueryResult = await this.db.queryWithOpts( sql`SELECT data FROM stream WHERE data->>'parentId'=${id} AND (data->>'isActive')::boolean = TRUE`.setName( - `${this.name}_by_parentid_active_sessions`, + `${this.name}_by_parentid_active_sessions` ), - opts, + opts ); return res.rowCount < 1 ? [] : res.rows.map((row) => row.data as DBStream); } @@ -336,18 +336,18 @@ export default class StreamTable extends Table { sql`(data->>'lastSeen')::bigint = ${stream.lastSeen}`, ], { isActive: false }, - { throwIfEmpty: false }, + { throwIfEmpty: false } ); if (upRes.rowCount) { console.log( `cleaned timed out stream id=${stream.id} lastSeen=${new Date( - stream.lastSeen, - )} name=${stream.name}`, + stream.lastSeen + )} name=${stream.name}` ); } } catch (e) { console.error( - `error setting stream active to false id=${stream.id} name=${stream.name} err=${e}`, + `error setting stream active to false id=${stream.id} name=${stream.name} err=${e}` ); upRes = { rowCount: 0 }; } @@ -361,7 +361,7 @@ export default class StreamTable extends Table { } SET data = jsonb_set(data, '{isActive}', 'false'::jsonb) WHERE id IN (${ids .map((_, i) => "$" + (i + 1)) .join(",")})`, - ids, + ids ); return res; } @@ -402,7 +402,7 @@ export default class StreamTable extends Table { removePrivateFieldsMany( objs: Array, - isAdmin: boolean = false, + isAdmin: boolean = false ): Array { return objs.map((o) => this.removePrivateFields(o, isAdmin)); } diff --git a/packages/api/src/store/table.ts b/packages/api/src/store/table.ts index cfefe52772..a8403c62aa 100644 --- a/packages/api/src/store/table.ts +++ b/packages/api/src/store/table.ts @@ -47,7 +47,7 @@ export default class Table { // get a single document by id async get( id: string, - { useReplica = true, useCache }: GetOptions = {}, + { useReplica = true, useCache }: GetOptions = {} ): Promise { if (!id) { throw new Error("missing id"); @@ -68,13 +68,13 @@ export default class Table { res = await this.db.query( sql`SELECT data FROM ` .append(this.name) - .append(sql` WHERE id=${id}`.setName(`${this.name}_by_id`)), + .append(sql` WHERE id=${id}`.setName(`${this.name}_by_id`)) ); } else { res = await this.db.replicaQuery( sql`SELECT data FROM ` .append(this.name) - .append(sql` WHERE id=${id}`.setName(`${this.name}_by_id`)), + .append(sql` WHERE id=${id}`.setName(`${this.name}_by_id`)) ); } @@ -91,7 +91,7 @@ export default class Table { async getMany( ids: Array, - opts: GetOptions = { useReplica: true }, + opts: GetOptions = { useReplica: true } ): Promise> { if (!ids || !ids.length) { throw new Error("missing ids"); @@ -104,7 +104,7 @@ export default class Table { .join(",")})`, values: ids, }, - opts, + opts ); if (res.rowCount < 1) { @@ -116,7 +116,7 @@ export default class Table { // returns [docs, cursor] async find( query: FindQuery | Array = {}, - opts: FindOptions = {}, + opts: FindOptions = {} ): Promise<[Array, string]> { const { cursor = "", @@ -143,7 +143,7 @@ export default class Table { } if (cursor && !cursor.includes("skip")) { filters.push( - sql``.append(this.name + ".").append(sql`data->>'id' > ${cursor}`), + sql``.append(this.name + ".").append(sql`data->>'id' > ${cursor}`) ); } let first = true; @@ -196,7 +196,7 @@ export default class Table { try { await this.db.query( `INSERT INTO ${this.name} VALUES ($1, $2)`, //p - [doc.id, JSON.stringify(doc)], //p + [doc.id, JSON.stringify(doc)] //p ); } catch (e) { if (e.message.includes("duplicate key value")) { @@ -210,7 +210,7 @@ export default class Table { async replace(doc: T) { const res = await this.db.query( `UPDATE ${this.name} SET data = $1 WHERE id = $2`, - [JSON.stringify(doc), doc.id], + [JSON.stringify(doc), doc.id] ); if (res.rowCount < 1) { @@ -223,7 +223,7 @@ export default class Table { async update( query: string | Array, doc: Partial, - opts: UpdateOptions = {}, + opts: UpdateOptions = {} ) { const { throwIfEmpty = true } = opts; const q = sql`UPDATE `.append(this.name).append(sql` @@ -292,7 +292,7 @@ export default class Table { async markDeleted(id: string) { const res = await this.db.query( `UPDATE ${this.name} SET data = jsonb_set(data, '{deleted}', 'true'::jsonb) WHERE id = $1`, - [id], + [id] ); if (res.rowCount < 1) { @@ -307,7 +307,7 @@ export default class Table { } SET data = jsonb_set(data, '{deleted}', 'true'::jsonb) WHERE id IN (${ids .map((_, i) => "$" + (i + 1)) .join(",")})`, - ids, + ids ); if (res.rowCount < 1) { @@ -333,7 +333,7 @@ export default class Table { } else if (fieldSpec.properties && res[fieldName]) { res[fieldName] = this.cleanWriteOnlyResponse( res[fieldName] as any, - fieldSpec, + fieldSpec ); } } diff --git a/packages/api/src/store/task-table.ts b/packages/api/src/store/task-table.ts index 3bdbbc0840..fb9c096b7a 100644 --- a/packages/api/src/store/task-table.ts +++ b/packages/api/src/store/task-table.ts @@ -30,7 +30,7 @@ export default class TaskTable extends Table> { private async countPendingTasks( userId: string, - startedTasksOnly: boolean, + startedTasksOnly: boolean ): Promise { const activeTaskThreshold = Date.now() - ACTIVE_TASK_TIMEOUT; // tasks that are on a retry backoff will be in the `waiting` phase with a `retries` field @@ -49,7 +49,7 @@ export default class TaskTable extends Table> { sql` task.data->'status'->>'phase' = 'waiting' AND task.data->'status'->>'retries' IS NULL - AND coalesce( (task.data->'status'->>'updatedAt')::bigint, 0) > ${enqueuedTaskThreshold}`, + AND coalesce( (task.data->'status'->>'updatedAt')::bigint, 0) > ${enqueuedTaskThreshold}` ); } diff --git a/packages/api/src/store/webhook-table.ts b/packages/api/src/store/webhook-table.ts index 23d13cf832..0060f7a572 100644 --- a/packages/api/src/store/webhook-table.ts +++ b/packages/api/src/store/webhook-table.ts @@ -24,12 +24,12 @@ export default class WebhookTable extends Table { streamId?: string, limit = 100, cursor?: string, - includeDeleted = false, + includeDeleted = false ) { const query = [sql`data->>'userId' = ${userId}`]; if (streamId) { query.push( - sql`(data->>'streamId' = ${streamId} OR data->>'streamId' IS NULL)`, + sql`(data->>'streamId' = ${streamId} OR data->>'streamId' IS NULL)` ); } if (event) { @@ -54,9 +54,9 @@ export default class WebhookTable extends Table { sql`` .append(`UPDATE ${this.name} `) // table name can't be parameterized, append a raw string .append( - sql`SET data = jsonb_set(data, '{status}', case when data->'status' is null then '{}' else data->'status' end || ${statusStr}) `, + sql`SET data = jsonb_set(data, '{status}', case when data->'status' is null then '{}' else data->'status' end || ${statusStr}) ` ) - .append(sql`WHERE id = ${id}`), + .append(sql`WHERE id = ${id}`) ); if (res.rowCount < 1) { diff --git a/packages/api/src/task/scheduler.ts b/packages/api/src/task/scheduler.ts index 859cfcc9ee..d3cee61a9b 100644 --- a/packages/api/src/task/scheduler.ts +++ b/packages/api/src/task/scheduler.ts @@ -70,7 +70,7 @@ export class TaskScheduler { event = JSON.parse(data.content.toString()); console.log( "events: got task result message", - JSON.stringify(event, null, 2), + JSON.stringify(event, null, 2) ); } catch (err) { console.log("events: error parsing task message", err); @@ -117,13 +117,13 @@ export class TaskScheduler { } else { if (task.status.retries) { console.log( - `task retry process error: err=max retries reached taskId=${task.id}`, + `task retry process error: err=max retries reached taskId=${task.id}` ); } await this.failTask(task, event.error.message); } console.log( - `task event process error: err="${event.error.message}" unretriable=${event.error.unretriable}`, + `task event process error: err="${event.error.message}" unretriable=${event.error.unretriable}` ); return true; } @@ -136,7 +136,7 @@ export class TaskScheduler { if (!assetSpec) { const error = "bad task output: missing assetSpec"; console.error( - `task event process error: err=${error} taskId=${event.task.id}`, + `task event process error: err=${error} taskId=${event.task.id}` ); await this.failTask(task, error, event.output); return true; @@ -210,7 +210,7 @@ export class TaskScheduler { } async processTaskResultPartial( - event: messages.TaskResultPartial, + event: messages.TaskResultPartial ): Promise { const tasks = await db.task.find({ id: event.task.id }); if (!tasks?.length || !tasks[0].length) { @@ -249,7 +249,7 @@ export class TaskScheduler { this.config, session, null, - true, + true ); await this.queue.publishWebhook("events.recording.ready", { type: "webhook_event", @@ -278,7 +278,7 @@ export class TaskScheduler { public async failTask( task: WithID, error: string, - output?: Task["output"], + output?: Task["output"] ) { const baseStatus: Task["status"] & Asset["status"] = { phase: "failed", @@ -345,7 +345,7 @@ export class TaskScheduler { inputAsset?: Asset, outputAsset?: Asset, userId?: string, - requesterId?: string, + requesterId?: string ) { const task = await this.createTask( type, @@ -353,7 +353,7 @@ export class TaskScheduler { inputAsset, outputAsset, userId, - requesterId, + requesterId ); let uId = inputAsset?.userId || outputAsset?.userId || userId; @@ -376,7 +376,7 @@ export class TaskScheduler { inputAsset?: Asset, outputAsset?: Asset, userId?: string, - requesterId?: string, + requesterId?: string ) { const task = await db.task.create({ id: uuid(), @@ -429,8 +429,8 @@ export class TaskScheduler { this.failTask(task, "Failed to enqueue task").catch((err) => console.error( `Error failing task after enqueue error: taskId=${task.id} err=`, - err, - ), + err + ) ); throw new Error(`Failed to enqueue task: ${err}`); } @@ -439,7 +439,7 @@ export class TaskScheduler { async retryTask( task: WithID, errorMessage: string, - forceRetry?: boolean, + forceRetry?: boolean ) { let retries = (task.status.retries ?? 0) + 1; if (forceRetry) { @@ -469,15 +469,15 @@ export class TaskScheduler { async updateTask( task: WithID, updates: Pick, - filters?: { allowedPhases: Array }, + filters?: { allowedPhases: Array } ) { updates = this.deleteCredentials(task, updates); let query = [sql`id = ${task.id}`]; if (filters?.allowedPhases) { query.push( sql`data->'status'->>'phase' IN `.append( - sqlQueryGroup(filters.allowedPhases), - ), + sqlQueryGroup(filters.allowedPhases) + ) ); } const res = await db.task.update(query, updates); @@ -519,7 +519,7 @@ export class TaskScheduler { private deleteCredentials( task: WithID, - updates: Pick, + updates: Pick ): Pick { // We should remove this at some point and do not store credentials at all const isTerminal = @@ -588,7 +588,7 @@ export class TaskScheduler { async updateAsset( asset: string | Asset, updates: Partial, - filters?: { allowedPhases: Array }, + filters?: { allowedPhases: Array } ) { if (typeof asset === "string") { asset = await db.asset.get(asset); @@ -605,8 +605,8 @@ export class TaskScheduler { if (filters?.allowedPhases) { query.push( sql`data->'status'->>'phase' IN `.append( - sqlQueryGroup(filters.allowedPhases), - ), + sqlQueryGroup(filters.allowedPhases) + ) ); } const res = await db.asset.update(query, updates); @@ -657,7 +657,7 @@ export async function ensureQueueCapacity(config: CliArgs, userId: string) { const numScheduled = await db.task.countScheduledTasks(userId); if (numScheduled >= config.vodMaxScheduledTasksPerUser) { throw new TooManyRequestsError( - `user ${userId} has reached the maximum number of pending tasks`, + `user ${userId} has reached the maximum number of pending tasks` ); } } diff --git a/packages/api/src/test-helpers.ts b/packages/api/src/test-helpers.ts index 33c3c24789..6ef9b70c03 100644 --- a/packages/api/src/test-helpers.ts +++ b/packages/api/src/test-helpers.ts @@ -25,14 +25,14 @@ export async function clearDatabase(server: TestServer) { .map((s) => ("table" in s ? s.table : null)) .filter((t) => !!t); await Promise.all( - tables.map((t) => server?.db?.query(`TRUNCATE TABLE ${t}`)), + tables.map((t) => server?.db?.query(`TRUNCATE TABLE ${t}`)) ); } export function verifyJwt( token: string, publicKey: string, - verifyOptions?: VerifyOptions, + verifyOptions?: VerifyOptions ) { try { return jwt.verify(token, publicKey, verifyOptions); @@ -138,7 +138,7 @@ export class TestClient { { ...args, headers, - }, + } ); return res; } @@ -208,7 +208,7 @@ export async function createProject(client: TestClient) { export async function useApiTokenWithProject( client: TestClient, - token: string, + token: string ) { client.jwtAuth = token; const project = await createProject(client); @@ -246,7 +246,7 @@ export async function createUser( client: TestClient, userData: User, admin: boolean, - emailValid: boolean, + emailValid: boolean ) { const userRes = await client.post(`/user`, userData); let user = await userRes.json(); @@ -272,7 +272,7 @@ export async function setupUsers( server: TestServer, admin: User, nonAdmin: User, - emailValid = true, + emailValid = true ) { const client = new TestClient({ server }); const { diff --git a/packages/api/src/types/common.d.ts b/packages/api/src/types/common.d.ts index f1a80a6748..718f89527a 100644 --- a/packages/api/src/types/common.d.ts +++ b/packages/api/src/types/common.d.ts @@ -51,7 +51,7 @@ declare global { checkResourceAccess: ( resource?: DBOwnedResource, - uiAdminOnly?: boolean, + uiAdminOnly?: boolean ) => void; getBroadcasters?: () => Promise; orchestratorsGetters?: Array<() => Promise>; @@ -94,18 +94,18 @@ export interface IStore { get(id: string, cleanWriteOnly?: boolean): Promise; replace(data: StoredObject): Promise; list( - args: IStoreListArgs, + args: IStoreListArgs ): Promise<{ data: Array; cursor: string }>; listKeys( prefix: string, cursor?: string, - limit?: number, + limit?: number ): Promise<[Array, string]>; query( - args: IStoreQueryArgs, + args: IStoreQueryArgs ): Promise<{ data: Array; cursor: string }>; queryObjects( - args: IStoreQueryObjectsArgs, + args: IStoreQueryObjectsArgs ): Promise<{ data: Array; cursor: string }>; deleteKey(key: string): Promise; delete(id: string): Promise; @@ -117,12 +117,12 @@ export interface IStoreBackend { listKeys( prefix: string, cursor: any, - limit: number, + limit: number ): Promise<[Array, any]>; list( prefix: string, cursor: any, - limit: number, + limit: number ): Promise<{ data: Array; cursor: any }>; get(id: string): Promise; create(key: string, data: StoredObject): Promise; diff --git a/packages/api/src/util.ts b/packages/api/src/util.ts index 4a59208d4d..77592dce95 100644 --- a/packages/api/src/util.ts +++ b/packages/api/src/util.ts @@ -62,16 +62,13 @@ export const shuffle = (arr: T[]) => { export const fetchWithTimeout = ( url: string, - options: RequestInitWithTimeout, + options: RequestInitWithTimeout ) => new Promise((resolve, reject) => { - let timeout = setTimeout( - () => { - timeout = null; - reject("timeout"); - }, - options.timeout || 10 * 1000, - ); + let timeout = setTimeout(() => { + timeout = null; + reject("timeout"); + }, options.timeout || 10 * 1000); return fetch(url, options).then( (response) => { if (timeout === null) { @@ -88,13 +85,13 @@ export const fetchWithTimeout = ( } clearTimeout(timeout); return reject(rejectReason); - }, + } ); }); export const fetchWithTimeoutAndRedirects = async ( url: string, - options: RequestInitWithRedirects, + options: RequestInitWithRedirects ): Promise => { const { maxRedirects = 5 } = options; diff --git a/packages/api/src/webhooks/cannon.test.ts b/packages/api/src/webhooks/cannon.test.ts index 55381bcf19..fc5cfd5895 100644 --- a/packages/api/src/webhooks/cannon.test.ts +++ b/packages/api/src/webhooks/cannon.test.ts @@ -56,7 +56,7 @@ describe("webhook cannon", () => { const nonAdminUserRes = await server.store.get( `user/${nonAdminUser.id}`, - false, + false ); nonAdminUser = { ...nonAdminUserRes, emailValid: true }; await server.store.replace(nonAdminUser); @@ -181,7 +181,7 @@ describe("webhook cannon", () => { const signatureHeader = String(req.headers["livepeer-signature"]); const signature: string = signatureHeader.split(",")[1].split("=")[1]; expect(signature).toEqual( - sign(JSON.stringify(req.body), mockWebhook.sharedSecret), + sign(JSON.stringify(req.body), mockWebhook.sharedSecret) ); } next(); @@ -446,7 +446,7 @@ describe("webhook cannon", () => { `/stream/${parentStream.id}/stream?sessionId=${sessionId}`, { name: "session1", - }, + } ); expect(res.status).toBe(201); childStream = await res.json(); @@ -567,7 +567,7 @@ describe("webhook cannon", () => { const expectIsLocal = async ( url: string, isLocal: boolean, - ips?: string[], + ips?: string[] ) => { expect(await server.webhook.checkIsLocalIp(url, false)).toMatchObject({ isLocal, @@ -623,10 +623,10 @@ describe("webhook cannon", () => { it("should not flag domains that resolve to public IPs", async () => { resolverMock.resolve4.mockReturnValueOnce( - Promise.resolve(["172.67.149.35"]), + Promise.resolve(["172.67.149.35"]) ); resolverMock.resolve6.mockReturnValueOnce( - Promise.resolve(["2606:4700:3037::ac43:9523"]), + Promise.resolve(["2606:4700:3037::ac43:9523"]) ); await expectIsLocal("http://livepeer.studio/mock", false, [ @@ -635,11 +635,11 @@ describe("webhook cannon", () => { ]); expect(resolverMock.resolve4.mock.calls).toHaveLength(1); expect(resolverMock.resolve4.mock.calls[0][0]).toEqual( - "livepeer.studio", + "livepeer.studio" ); expect(resolverMock.resolve6.mock.calls).toHaveLength(1); expect(resolverMock.resolve6.mock.calls[0][0]).toEqual( - "livepeer.studio", + "livepeer.studio" ); }); @@ -665,11 +665,11 @@ describe("webhook cannon", () => { ]); expect(resolverMock.resolve4.mock.calls).toHaveLength(1); expect(resolverMock.resolve4.mock.calls[0][0]).toEqual( - "local.mydomain.com", + "local.mydomain.com" ); expect(resolverMock.resolve6.mock.calls).toHaveLength(1); expect(resolverMock.resolve6.mock.calls[0][0]).toEqual( - "local.mydomain.com", + "local.mydomain.com" ); }); } diff --git a/packages/api/src/webhooks/cannon.ts b/packages/api/src/webhooks/cannon.ts index 7a0e4c230f..30b40ecd86 100644 --- a/packages/api/src/webhooks/cannon.ts +++ b/packages/api/src/webhooks/cannon.ts @@ -129,7 +129,7 @@ export default class WebhookCannon { } catch (e) { console.log( `Error handling recording.waiting event sessionId=${sessionId} err=`, - e, + e ); throw e; } @@ -139,7 +139,7 @@ export default class WebhookCannon { console.log( `fetched webhooks. userId=${userId} event=${event} webhooks=`, - webhooks, + webhooks ); if (webhooks.length === 0) { return true; @@ -153,12 +153,12 @@ export default class WebhookCannon { if (!stream) { // if stream isn't found. don't fire the webhook, log an error throw new UnprocessableEntityError( - `webhook Cannon: onTrigger: Stream Not found , streamId: ${streamId}`, + `webhook Cannon: onTrigger: Stream Not found , streamId: ${streamId}` ); } // basic sanitization. stream = db.stream.addDefaultFields( - db.stream.removePrivateFields({ ...stream }), + db.stream.removePrivateFields({ ...stream }) ); delete stream.streamKey; } @@ -166,11 +166,11 @@ export default class WebhookCannon { let user = await db.user.get(userId); if (!user) { throw new UnprocessableEntityError( - `webhook Cannon: onTrigger: User not found userId=${userId}`, + `webhook Cannon: onTrigger: Account not found userId=${userId}` ); } else if (user.suspended) { throw new UnprocessableEntityError( - `webhook Cannon: onTrigger: User suspended userId=${userId}`, + `webhook Cannon: onTrigger: User suspended userId=${userId}` ); } @@ -189,8 +189,8 @@ export default class WebhookCannon { ...baseTrigger, id: uuid(), webhook, - }), - ), + }) + ) ); } catch (error) { console.log("Error publish webhook trigger message: ", error); @@ -239,17 +239,17 @@ export default class WebhookCannon { retry( trigger: messages.WebhookTrigger, webhookPayload?: RequestInitWithTimeout, - err?: Error, + err?: Error ) { if (trigger?.retries >= MAX_RETRIES) { console.log( - `Webhook Cannon| Max Retries Reached, id: ${trigger.id}, streamId: ${trigger.stream?.id}`, + `Webhook Cannon| Max Retries Reached, id: ${trigger.id}, streamId: ${trigger.stream?.id}` ); try { trigger = webhookFailNotification(trigger, webhookPayload, err); } catch (err) { console.error( - `Webhook Cannon| Error sending notification email to user, id: ${trigger.id}, streamId: ${trigger.stream?.id}`, + `Webhook Cannon| Error sending notification email to user, id: ${trigger.id}, streamId: ${trigger.stream?.id}` ); } return; @@ -265,27 +265,27 @@ export default class WebhookCannon { return this.queue.delayedPublishWebhook( "webhooks.delayedEmits", trigger, - trigger.lastInterval, + trigger.lastInterval ); } async notifyFailedWebhook( trigger: messages.WebhookTrigger, params?: RequestInitWithTimeout, - err?: any, + err?: any ) { if (!trigger.user.emailValid) { console.error( - `Webhook Cannon| User email is not valid, id: ${trigger.id}, streamId: ${trigger.stream?.id}`, + `Webhook Cannon| User email is not valid, id: ${trigger.id}, streamId: ${trigger.stream?.id}` ); return; } if (!(this.supportAddr && this.sendgridTemplateId && this.sendgridApiKey)) { console.error( - `Webhook Cannon| Unable to send notification email to user, id: ${trigger.id}, streamId: ${trigger.stream?.id}`, + `Webhook Cannon| Unable to send notification email to user, id: ${trigger.id}, streamId: ${trigger.stream?.id}` ); console.error( - `Sending emails requires supportAddr, sendgridTemplateId, and sendgridApiKey`, + `Sending emails requires supportAddr, sendgridTemplateId, and sendgridApiKey` ); return; } @@ -321,7 +321,7 @@ export default class WebhookCannon { }); console.log( - `Webhook Cannon| Email sent to user="${trigger.user.email}" id=${trigger.id} streamId=${trigger.stream?.id}`, + `Webhook Cannon| Email sent to user="${trigger.user.email}" id=${trigger.id} streamId=${trigger.stream?.id}` ); } @@ -330,7 +330,7 @@ export default class WebhookCannon { if (!event || !webhook || !user) { console.error( `invalid webhook trigger message received. type=${trigger.type} message=`, - trigger, + trigger ); return; } @@ -338,7 +338,7 @@ export default class WebhookCannon { const { ips, isLocal } = await this.checkIsLocalIp( webhook.url, - user.admin, + user.admin ).catch((e) => { console.error("error checking if is local IP: ", e); return { ips: [], isLocal: false }; @@ -347,7 +347,7 @@ export default class WebhookCannon { if (isLocal) { // don't fire this webhook. console.log( - `webhook ${webhook.id} resolved to a localIP, url: ${webhook.url}, resolved IP: ${ips}`, + `webhook ${webhook.id} resolved to a localIP, url: ${webhook.url}, resolved IP: ${ips}` ); } else { console.log("preparing to fire webhook ", webhook.url); @@ -374,7 +374,7 @@ export default class WebhookCannon { const sigHeaders = signatureHeaders( params.body, webhook.sharedSecret, - timestamp, + timestamp ); params.headers = { ...params.headers, ...sigHeaders }; @@ -400,12 +400,12 @@ export default class WebhookCannon { await this.retry( trigger, params, - new Error("Status code: " + resp.status), + new Error("Status code: " + resp.status) ); } console.error( - `webhook ${webhook.id} didn't get 200 back! response status: ${resp.status}`, + `webhook ${webhook.id} didn't get 200 back! response status: ${resp.status}` ); // we don't retry on non 400 responses. only on timeouts // this.retry(event); @@ -423,11 +423,11 @@ export default class WebhookCannon { startTime, responseBody, webhook.sharedSecret, - params, + params ); } catch (e) { console.log( - `Unable to store response of webhook ${webhook.id} url: ${webhook.url} error: ${e}`, + `Unable to store response of webhook ${webhook.id} url: ${webhook.url} error: ${e}` ); } await this.storeTriggerStatus( @@ -435,7 +435,7 @@ export default class WebhookCannon { triggerTime, statusCode, errorMessage, - responseBody, + responseBody ); return; } @@ -478,20 +478,20 @@ export default class WebhookCannon { triggerTime: number, statusCode: number, errorMessage: string, - responseBody: string, + responseBody: string ) { await storeTriggerStatus( webhook, triggerTime, statusCode, errorMessage, - responseBody, + responseBody ); } async handleRecordingWaitingChecks( sessionId: string, - attempt = 1, + attempt = 1 ): Promise { const session = await db.session.get(sessionId, { useReplica: false, @@ -525,12 +525,12 @@ export default class WebhookCannon { await Promise.all( childStreams.map((child) => { return db.stream.update(child.id, { isActive: false }); - }), + }) ); if (!lastSeen && !hasSourceSegments) { logger.info( - `Skipping unused session sessionId=${session.id} childStreamCount=${childStreams.length}`, + `Skipping unused session sessionId=${session.id} childStreamCount=${childStreams.length}` ); return; } @@ -549,7 +549,7 @@ export default class WebhookCannon { const secondaryStorageEnabled = !(await isExperimentSubject( primaryStorageExperiment, - session.userId, + session.userId )); const secondaryObjectStoreId = secondaryStorageEnabled && this.secondaryVodObjectStoreId; @@ -573,13 +573,13 @@ export default class WebhookCannon { objectStoreId: secondaryObjectStoreId || this.vodCatalystObjectStoreId, }, - this.queue, + this.queue ); const { url } = await buildRecordingUrl( session, this.recordCatalystObjectStoreId, - this.secondaryRecordObjectStoreId, + this.secondaryRecordObjectStoreId ); await taskScheduler.createAndScheduleTask( @@ -590,17 +590,17 @@ export default class WebhookCannon { profiles: session.recordingSpec?.profiles, thumbnails: !(await isExperimentSubject( "vod-thumbs-off", - session.userId, + session.userId )), }, }, undefined, - asset, + asset ); } catch (e) { if (e instanceof BadRequestError) { throw new UnprocessableEntityError( - "Asset for the recording session already added", + "Asset for the recording session already added" ); } else { throw e; @@ -621,13 +621,13 @@ async function storeResponse( startTime: [number, number], responseBody: string, sharedSecret: string, - params, + params ): Promise { const hrDuration = process.hrtime(startTime); let encodedResponseBody = ""; if (responseBody) { encodedResponseBody = Buffer.from(responseBody.substring(0, 1024)).toString( - "base64", + "base64" ); } @@ -660,7 +660,7 @@ async function storeResponse( export async function resendWebhook( webhook: DBWebhook, - webhookLog: WebhookLog, + webhookLog: WebhookLog ): Promise { const triggerTime = Date.now(); const startTime = process.hrtime(); @@ -678,7 +678,7 @@ export async function resendWebhook( const sigHeaders = signatureHeaders( webhookLog.request.body, webhookLog.sharedSecret, - timestamp, + timestamp ); webhookLog.request.headers = { ...webhookLog.request.headers, @@ -702,7 +702,7 @@ export async function resendWebhook( triggerTime, statusCode, errorMessage, - responseBody, + responseBody ); return await storeResponse( webhook, @@ -712,7 +712,7 @@ export async function resendWebhook( startTime, responseBody, webhookLog.sharedSecret, - webhookLog.request, + webhookLog.request ); } } @@ -722,7 +722,7 @@ export async function storeTriggerStatus( triggerTime: number, statusCode?: number, errorMessage?: string, - responseBody?: string, + responseBody?: string ): Promise { try { let status: DBWebhook["status"] = { lastTriggeredAt: triggerTime }; @@ -743,7 +743,7 @@ export async function storeTriggerStatus( await db.webhook.updateStatus(webhook.id, status); } catch (e) { console.log( - `Unable to store status of webhook ${webhook.id} url: ${webhook.url}`, + `Unable to store status of webhook ${webhook.id} url: ${webhook.url}` ); } } @@ -751,7 +751,7 @@ export async function storeTriggerStatus( export function webhookFailNotification( trigger: messages.WebhookTrigger, webhookPayload: RequestInitWithTimeout, - err: Error, + err: Error ): messages.WebhookTrigger { const lastFailureNotification = trigger?.lastFailureNotification; const currentTime = Date.now(); @@ -773,7 +773,7 @@ export function webhookFailNotification( export function signatureHeaders( payload: string, sharedSecret: string, - timestamp: number, + timestamp: number ): { [key: string]: string } | {} { if (!sharedSecret) return {}; let signature = sign(payload, sharedSecret); diff --git a/packages/api/src/worker.js b/packages/api/src/worker.js index ded3a0161e..af29b1eb84 100644 --- a/packages/api/src/worker.js +++ b/packages/api/src/worker.js @@ -130,7 +130,7 @@ const amalgamate = async (req) => { const serverRes = await fetch(newReq); const data = await serverRes.json(); return data; - }), + }) ); let output; if (responses.length === 0) { @@ -167,7 +167,7 @@ const amalgamateM3U8 = async (req) => { newUrl.hostname = server; newUrl.port = newUrl.protocol === "https:" ? 443 : 80; return newUrl.toString(); - }), + }) ); if (composed === null) { return new Response("not found", { status: 404 }); @@ -248,7 +248,7 @@ class ExpressResponse { .map(function (rel) { return "<" + links[rel] + '>; rel="' + rel + '"'; }) - .join(", "), + .join(", ") ); } @@ -294,7 +294,7 @@ async function expressRequest(cfReq, router) { new Response(text, { status: status, headers: res.headers, - }), + }) ); }, json: (jsonObj) => { @@ -369,7 +369,7 @@ async function handleEvent(event) { if (url.pathname === "/test.mp4") { return Response.redirect( "https://storage.googleapis.com/lp_testharness_assets/official_test_source_2s_keys_24pfs.mp4", - 302, + 302 ); } if (url.pathname.startsWith("/api/broadcaster/status")) { diff --git a/packages/www/components/Admin/AdminObjectStoreTable/index.tsx b/packages/www/components/Admin/AdminObjectStoreTable/index.tsx index f5acdb35ec..5e7e0e52c1 100644 --- a/packages/www/components/Admin/AdminObjectStoreTable/index.tsx +++ b/packages/www/components/Admin/AdminObjectStoreTable/index.tsx @@ -73,7 +73,7 @@ const AdminObjectStoreTable = ({ id }: { id: string }) => { accessor: "createdAt", }, ], - [nextCursor, lastFilters], + [nextCursor, lastFilters] ); const filtersDesc = useMemo( @@ -83,7 +83,7 @@ const AdminObjectStoreTable = ({ id }: { id: string }) => { { id: "url", placeholder: "url" }, { id: "publicUrl", placeholder: "public url" }, ], - [], + [] ); const fetchData = ({ order, cursor, filters }, refetch: boolean = false) => { @@ -116,7 +116,7 @@ const AdminObjectStoreTable = ({ id }: { id: string }) => { const refetch = () => { fetchData( { order: lastOrder, cursor: lastCursor, filters: lastFilters }, - true, + true ); }; diff --git a/packages/www/components/Admin/AdminStreamsTable/index.tsx b/packages/www/components/Admin/AdminStreamsTable/index.tsx index 1916e30e9b..6b0f5daccc 100644 --- a/packages/www/components/Admin/AdminStreamsTable/index.tsx +++ b/packages/www/components/Admin/AdminStreamsTable/index.tsx @@ -69,7 +69,7 @@ const AdminStreamsTable = ({ id }: { id: string }) => { }, }, ], - [nextCursor, lastFilters], + [nextCursor, lastFilters] ); const filtersDesc = useMemo( @@ -77,7 +77,7 @@ const AdminStreamsTable = ({ id }: { id: string }) => { { id: "id", placeholder: "Filter by ID" }, { id: "user.email", placeholder: "Filter by email" }, ], - [], + [] ); const fetchData = ({ order, cursor, filters }, refetch: boolean = false) => { @@ -117,7 +117,7 @@ const AdminStreamsTable = ({ id }: { id: string }) => { const refecth = () => { fetchData( { order: lastOrder, cursor: lastCursor, filters: lastFilters }, - true, + true ); }; diff --git a/packages/www/components/Admin/AdminTokenTable/index.tsx b/packages/www/components/Admin/AdminTokenTable/index.tsx index 8398a529a8..823e564cb2 100644 --- a/packages/www/components/Admin/AdminTokenTable/index.tsx +++ b/packages/www/components/Admin/AdminTokenTable/index.tsx @@ -81,7 +81,7 @@ const AdminTokenTable = ({ id }: TokenTableProps) => { accessor: "lastSeen", }, ], - [nextCursor, lastFilters], + [nextCursor, lastFilters] ); const filtersDesc = [ @@ -124,7 +124,7 @@ const AdminTokenTable = ({ id }: TokenTableProps) => { const refecth = () => { fetchData( { order: lastOrder, cursor: lastCursor, filters: lastFilters }, - true, + true ); }; diff --git a/packages/www/components/Admin/AdminWebhooksTable/index.tsx b/packages/www/components/Admin/AdminWebhooksTable/index.tsx index 66c805f64c..a80e78a070 100644 --- a/packages/www/components/Admin/AdminWebhooksTable/index.tsx +++ b/packages/www/components/Admin/AdminWebhooksTable/index.tsx @@ -99,7 +99,7 @@ const AdminWebhookTable = ({ id }: { id: string }) => { }, }, ], - [nextCursor, lastFilters], + [nextCursor, lastFilters] ); const filtersDesc = useMemo( @@ -108,7 +108,7 @@ const AdminWebhookTable = ({ id }: { id: string }) => { { id: "name", placeholder: "name" }, { id: "url", placeholder: "url" }, ], - [], + [] ); const fetchData = ({ order, cursor, filters }, refetch: boolean = false) => { @@ -141,7 +141,7 @@ const AdminWebhookTable = ({ id }: { id: string }) => { const refecth = () => { fetchData( { order: lastOrder, cursor: lastCursor, filters: lastFilters }, - true, + true ); }; diff --git a/packages/www/components/Admin/CommonAdminTable/index.tsx b/packages/www/components/Admin/CommonAdminTable/index.tsx index a561bfae2d..e9140f593b 100644 --- a/packages/www/components/Admin/CommonAdminTable/index.tsx +++ b/packages/www/components/Admin/CommonAdminTable/index.tsx @@ -325,7 +325,7 @@ const CommonAdminTable = ({ }, ...columns, ]); - }, + } ); useEffect(() => { @@ -424,7 +424,7 @@ const CommonAdminTable = ({ }} align="left" {...column.getHeaderProps( - column.getSortByToggleProps({ title: "" }), + column.getSortByToggleProps({ title: "" }) )} key={`header-column-${columnIndex}`}> diff --git a/packages/www/components/Admin/StreamSessionsTable/index.tsx b/packages/www/components/Admin/StreamSessionsTable/index.tsx index db0212a7bc..4ae9fe9a17 100644 --- a/packages/www/components/Admin/StreamSessionsTable/index.tsx +++ b/packages/www/components/Admin/StreamSessionsTable/index.tsx @@ -21,7 +21,7 @@ function makeMP4Url( hlsUrl: string, profileName: string, streamName: string, - createdAt: number, + createdAt: number ): string { const sanitizedName = filenamify .default(streamName, { replacement: "_" }) @@ -32,7 +32,7 @@ function makeMP4Url( const pp = hlsUrl.split("/"); pp.pop(); return `${pp.join( - "/", + "/" )}/${profileName}/${sanitizedName}-${timestamp}-${profileName}.mp4`; } @@ -56,7 +56,7 @@ function getHighestMP4Url(hlsUrl: string, profiles: Array): string { } return pv; }, - ["", 0], + ["", 0] ); return makeMP4Url(hlsUrl, profileName, "", 0); } @@ -80,7 +80,7 @@ const RecordingUrlCell = ({ cell.value.href, "source", cell.value.streamName, - cell.value.createdAt, + cell.value.createdAt )} sx={{ p: 1 }}> Download mp4 beta @@ -163,7 +163,7 @@ const StreamSessionsTable = ({ disableSortBy: true, }, ], - [], + [] ); const data: SessionsTableData[] = useMemo(() => { diff --git a/packages/www/components/Admin/StreamsTable/index.tsx b/packages/www/components/Admin/StreamsTable/index.tsx index 4c4276ba1e..2080db0599 100644 --- a/packages/www/components/Admin/StreamsTable/index.tsx +++ b/packages/www/components/Admin/StreamsTable/index.tsx @@ -187,7 +187,7 @@ const StreamsTable = ({ userId, id }: { userId: string; id: string }) => { disableSortBy: true, }, ], - [], + [] ); const data: StreamsTableData[] = useMemo(() => { @@ -213,10 +213,10 @@ const StreamsTable = ({ userId, id }: { userId: string; id: string }) => { const handleRowSelectionChange = useCallback( (rows: Row[]) => { setSelectedStreams( - rows.map((r) => streams.find((s) => s.id === r.original.id)), + rows.map((r) => streams.find((s) => s.id === r.original.id)) ); }, - [streams], + [streams] ); return ( diff --git a/packages/www/components/Admin/Table-v2/filters/index.tsx b/packages/www/components/Admin/Table-v2/filters/index.tsx index 4ba47759b9..4c4619e367 100644 --- a/packages/www/components/Admin/Table-v2/filters/index.tsx +++ b/packages/www/components/Admin/Table-v2/filters/index.tsx @@ -8,7 +8,7 @@ type AnyFilterValue = string; type BaseFilterProps< Table extends Record, - Value extends AnyFilterValue = string, + Value extends AnyFilterValue = string > = { currentFilters: { id: keyof Table; value: Value }[] | undefined; setFilter: (columnId: keyof Table, newValue: Value) => void; @@ -31,7 +31,7 @@ const TextFilter = >({ (e: React.ChangeEvent) => { setFilter(columnId, e.target.value); }, - [setFilter], + [setFilter] ); return ( diff --git a/packages/www/components/Admin/Table-v2/index.tsx b/packages/www/components/Admin/Table-v2/index.tsx index 486391a109..fe8212b35c 100644 --- a/packages/www/components/Admin/Table-v2/index.tsx +++ b/packages/www/components/Admin/Table-v2/index.tsx @@ -31,7 +31,7 @@ type Filter> = { id: keyof T; value: any }; export type FetchDataF> = ( filters: Filter[], sortBy: Sort[], - lastRow: Row | null, + lastRow: Row | null ) => void; type Props> = { @@ -147,7 +147,7 @@ const Table = >({ ...columns, ]); } - }, + } ); useEffect(() => { @@ -234,7 +234,7 @@ const Table = >({ scope="col" {...column.getHeaderProps( // @ts-ignore - column.getSortByToggleProps(), + column.getSortByToggleProps() )} sx={{ textTransform: "uppercase", diff --git a/packages/www/components/Admin/Table-v2/types.ts b/packages/www/components/Admin/Table-v2/types.ts index 2155569822..df009758bd 100644 --- a/packages/www/components/Admin/Table-v2/types.ts +++ b/packages/www/components/Admin/Table-v2/types.ts @@ -3,19 +3,19 @@ export type TableData = Record; export type CellComponentProps< D extends TableData, - T, + T > = React.PropsWithChildren>; export type SortTypeArgs = [ rowA: Row>, rowB: Row>, columnId: string, - desc: boolean, + desc: boolean ]; export type SortFn = ( path: string, rowA: Row>, rowB: Row>, columnId: string, - desc: boolean, + desc: boolean ) => number; diff --git a/packages/www/components/Admin/UserTable/index.tsx b/packages/www/components/Admin/UserTable/index.tsx index a293cc6e06..3660f11546 100644 --- a/packages/www/components/Admin/UserTable/index.tsx +++ b/packages/www/components/Admin/UserTable/index.tsx @@ -79,7 +79,7 @@ const UserTable = ({ userId, id }: UserTableProps) => { }, }, ], - [nextCursor, lastFilters], + [nextCursor, lastFilters] ); const filtersDesc = useMemo( @@ -104,7 +104,7 @@ const UserTable = ({ userId, id }: UserTableProps) => { ), }, ], - [], + [] ); const fetchData = ({ order, cursor, filters }, refetch: boolean = false) => { @@ -137,7 +137,7 @@ const UserTable = ({ userId, id }: UserTableProps) => { const refetch = () => { fetchData( { order: lastOrder, cursor: lastCursor, filters: lastFilters }, - true, + true ); }; diff --git a/packages/www/components/ApiKeys/CorsCell.tsx b/packages/www/components/ApiKeys/CorsCell.tsx index 6b75a73ef1..8a74c23a06 100644 --- a/packages/www/components/ApiKeys/CorsCell.tsx +++ b/packages/www/components/ApiKeys/CorsCell.tsx @@ -19,7 +19,7 @@ const CorsCell = (params: { cors: ApiToken["access"]["cors"] }) => { cors.allowedOrigins.includes("*") ? `${accessLevel} access allowed from any origin` : `${accessLevel} access allowed from: ${cors.allowedOrigins.join( - ", ", + ", " )}` } multiline> diff --git a/packages/www/components/ApiKeys/CreateDialog.tsx b/packages/www/components/ApiKeys/CreateDialog.tsx index 949da2f91c..77a19d6e2a 100644 --- a/packages/www/components/ApiKeys/CreateDialog.tsx +++ b/packages/www/components/ApiKeys/CreateDialog.tsx @@ -87,7 +87,7 @@ const CreateDialog = ({ }; }); }, - [setCors], + [setCors] ); const isNewOriginValid = useMemo(() => { diff --git a/packages/www/components/ApiKeys/helpers.tsx b/packages/www/components/ApiKeys/helpers.tsx index d0590c2311..67fd871c6d 100644 --- a/packages/www/components/ApiKeys/helpers.tsx +++ b/packages/www/components/ApiKeys/helpers.tsx @@ -56,7 +56,7 @@ export const makeColumns = () => [ export const rowsPageFromState = async ( userId: string, - getApiTokens: Function, + getApiTokens: Function ): Promise> => { const [tokens, nextCursor, resp, count] = await getApiTokens(userId, { count: true, @@ -86,7 +86,7 @@ export const rowsPageFromState = async ( cors: { children: , }, - }), + }) ); return { diff --git a/packages/www/components/ApiKeys/index.tsx b/packages/www/components/ApiKeys/index.tsx index 2a0e377b78..e554e4f041 100644 --- a/packages/www/components/ApiKeys/index.tsx +++ b/packages/www/components/ApiKeys/index.tsx @@ -39,7 +39,7 @@ const ApiKeysTable = ({ const fetcher: Fetcher = useCallback( async () => rowsPageFromState(userId, getApiTokens), - [userId], + [userId] ); const trackEvent = useCallback(() => { diff --git a/packages/www/components/AssetDetails/AssetDetailsBox.tsx b/packages/www/components/AssetDetails/AssetDetailsBox.tsx index 04185a3fb4..8249c92d27 100644 --- a/packages/www/components/AssetDetails/AssetDetailsBox.tsx +++ b/packages/www/components/AssetDetails/AssetDetailsBox.tsx @@ -21,7 +21,7 @@ export type AssetDetailsBoxProps = { const AssetDetailsBox = ({ asset }: AssetDetailsBoxProps) => { const videoTrack = useMemo( () => asset?.videoSpec?.tracks?.find((t) => t?.type === "video"), - [asset?.videoSpec], + [asset?.videoSpec] ); const isClip = asset?.source?.type ? asset?.source.type === "clip" : false; @@ -79,7 +79,7 @@ const AssetDetailsBox = ({ asset }: AssetDetailsBoxProps) => { url={asset.playbackUrl} shortendUrl={asset.playbackUrl.replace( asset.playbackUrl.slice(29, 70), - "…", + "…" )} anchor={false} /> diff --git a/packages/www/components/AssetDetails/AssetEventLogTab.tsx b/packages/www/components/AssetDetails/AssetEventLogTab.tsx index 0431ee4c3f..f648d57a51 100644 --- a/packages/www/components/AssetDetails/AssetEventLogTab.tsx +++ b/packages/www/components/AssetDetails/AssetEventLogTab.tsx @@ -27,20 +27,20 @@ const AssetEventLogTab = ({ asset }: { asset: Asset }) => { const events: AssetEvent[] = tasks ?.filter( (task) => - task.outputAssetId === asset.id || task.inputAssetId === asset.id, + task.outputAssetId === asset.id || task.inputAssetId === asset.id ) ?.map((task) => ({ type: ["upload", "import"].includes(task?.type) ? asset.source?.type == "url" ? "url-import" : asset.source?.type == "directUpload" - ? "file-import" - : asset.source?.type == "recording" - ? "recorded-session" - : "other" + ? "file-import" + : asset.source?.type == "recording" + ? "recorded-session" + : "other" : task?.params?.export?.["ipfs"] - ? "ipfs-upload" - : "other", + ? "ipfs-upload" + : "other", timestamp: task?.createdAt ?? Date.now(), })); @@ -79,12 +79,12 @@ const AssetEventLogTab = ({ asset }: { asset: Asset }) => { {event.type === "file-import" ? "Asset created from file upload" : event.type === "url-import" - ? "Asset created from URL import" - : event.type === "recorded-session" - ? "Asset created from recorded stream" - : event.type === "ipfs-upload" - ? "Uploaded to IPFS" - : "N/A"} + ? "Asset created from URL import" + : event.type === "recorded-session" + ? "Asset created from recorded stream" + : event.type === "ipfs-upload" + ? "Uploaded to IPFS" + : "N/A"} {moment.unix(event.timestamp / 1000).format("lll")} diff --git a/packages/www/components/AssetsTable/CreateAssetDialog/AssetsUploadError.tsx b/packages/www/components/AssetsTable/CreateAssetDialog/AssetsUploadError.tsx index ca6e232dc5..21f5b87e98 100644 --- a/packages/www/components/AssetsTable/CreateAssetDialog/AssetsUploadError.tsx +++ b/packages/www/components/AssetsTable/CreateAssetDialog/AssetsUploadError.tsx @@ -53,7 +53,7 @@ const AssetsUploadError = ({ errorMessage={e.message} /> ); - }), + }) )} diff --git a/packages/www/components/AssetsTable/CreateAssetDialog/index.tsx b/packages/www/components/AssetsTable/CreateAssetDialog/index.tsx index c47cc1f547..b6f753e8a0 100644 --- a/packages/www/components/AssetsTable/CreateAssetDialog/index.tsx +++ b/packages/www/components/AssetsTable/CreateAssetDialog/index.tsx @@ -74,7 +74,7 @@ const CreateAssetDialog = ({ ...prev, ...acceptedFiles.reduce( (prev, curr) => ({ ...prev, [curr.name]: curr }), - {}, + {} ), }; // Make sure there are never more than the max allowed files selected @@ -103,7 +103,7 @@ const CreateAssetDialog = ({ ...(isDragReject ? rejectStyle : {}), ...(isDragActive ? activeStyle : {}), }), - [isDragActive, isDragReject, isDragAccept], + [isDragActive, isDragReject, isDragAccept] ); return ( @@ -126,7 +126,7 @@ const CreateAssetDialog = ({ try { await onCreate({ videoFiles: Object.keys(videoFiles).map( - (key) => videoFiles[key], + (key) => videoFiles[key] ), }); setVideoFiles({}); diff --git a/packages/www/components/AssetsTable/helpers.tsx b/packages/www/components/AssetsTable/helpers.tsx index 8f1ce90a22..238aa842df 100644 --- a/packages/www/components/AssetsTable/helpers.tsx +++ b/packages/www/components/AssetsTable/helpers.tsx @@ -101,7 +101,7 @@ export const rowsPageFromState = async ( getAssets: ApiClient["getAssets"], getTasks: ApiClient["getTasks"], onDeleteAsset: Function, - appendProjectId: Function, + appendProjectId: Function ): Promise> => { const assetsPromise = getAssets(userId, { filters: formatFiltersForApiRequest(state.filters), @@ -178,17 +178,17 @@ export const rowsPageFromState = async ( onDelete: () => onDeleteAsset(asset.id), }, }; - }, + } ); return { rows, nextCursor, count }; }; export const fileUploadProgressForAsset = ( asset: Asset, - fileUploads: FileUpload[], + fileUploads: FileUpload[] ): number | undefined => { const fileUpload = fileUploads.find( - (upload) => upload.file.name === asset.name, + (upload) => upload.file.name === asset.name ); return fileUpload && asset.status?.phase === "waiting" ? (fileUpload.completed ? 1 : 0.99) * fileUpload.progress diff --git a/packages/www/components/AssetsTable/index.tsx b/packages/www/components/AssetsTable/index.tsx index ed8b3657bc..bcbbec7fc5 100644 --- a/packages/www/components/AssetsTable/index.tsx +++ b/packages/www/components/AssetsTable/index.tsx @@ -79,9 +79,9 @@ const AssetsTable = ({ getAssets, getTasks, onDeleteAsset, - appendProjectId, + appendProjectId ), - [userId, appendProjectId], + [userId, appendProjectId] ); useEffect(() => { diff --git a/packages/www/components/Breadcrumbs/index.tsx b/packages/www/components/Breadcrumbs/index.tsx index 2681007fa7..b6454a8122 100644 --- a/packages/www/components/Breadcrumbs/index.tsx +++ b/packages/www/components/Breadcrumbs/index.tsx @@ -31,7 +31,7 @@ function insertSeparators(items) { current, / - , + ); } else { acc.push(current); @@ -79,7 +79,7 @@ const Breadcrumbs = ({ children }) => { }} key="project"> {project?.name} - , + ); } } diff --git a/packages/www/components/ContactDialog/index.tsx b/packages/www/components/ContactDialog/index.tsx index 7cacfb3f2b..0ce7ea322f 100644 --- a/packages/www/components/ContactDialog/index.tsx +++ b/packages/www/components/ContactDialog/index.tsx @@ -29,7 +29,7 @@ export const ContactDialog = ({ open, setOpen }) => { if (data) { formEl.current.reset(); openSnackbar( - "Thank you for getting in touch. Our team will get back to you soon.", + "Thank you for getting in touch. Our team will get back to you soon." ); setOpen(false); } diff --git a/packages/www/components/FeaturesModel/index.tsx b/packages/www/components/FeaturesModel/index.tsx index 16d9d01a60..30c80f05ad 100644 --- a/packages/www/components/FeaturesModel/index.tsx +++ b/packages/www/components/FeaturesModel/index.tsx @@ -34,7 +34,7 @@ export default function FeaturesModel() { useEffect(() => { if (typeof window !== "undefined") { const hasShownFeature = localStorage.getItem( - `hasShownFeature-${feature.id}`, + `hasShownFeature-${feature.id}` ); if (!hasShownFeature) { setShouldShowFeature(true); diff --git a/packages/www/components/FileUpload/helpers.ts b/packages/www/components/FileUpload/helpers.ts index 8ef56b41b2..97efeda8a5 100644 --- a/packages/www/components/FileUpload/helpers.ts +++ b/packages/www/components/FileUpload/helpers.ts @@ -9,7 +9,7 @@ export type FileUploadFilteredItem = { export const filteredItemsToShow = ( fileUploads: FileUpload[], - assets: Asset[], + assets: Asset[] ): FileUploadFilteredItem[] => { const assetNamesUninque = new Set(); const assetsFiltered = assets @@ -17,7 +17,7 @@ export const filteredItemsToShow = ( .filter((asset) => { // Filter outfailed assets that are currently not file uploads const fileUpload = fileUploads.find( - (fileUpload) => fileUpload.file.name === asset.name, + (fileUpload) => fileUpload.file.name === asset.name ); const doesAssetNameMatchesFile = fileUpload !== undefined; if (!doesAssetNameMatchesFile) return false; @@ -35,10 +35,10 @@ export const filteredItemsToShow = ( const items = [ ...assetsFiltered.map( - (asset): FileUploadFilteredItem => ({ type: "asset", asset }), + (asset): FileUploadFilteredItem => ({ type: "asset", asset }) ), ...fileUploads.map( - (file): FileUploadFilteredItem => ({ type: "file", file }), + (file): FileUploadFilteredItem => ({ type: "file", file }) ), ]; return items; diff --git a/packages/www/components/FileUpload/index.tsx b/packages/www/components/FileUpload/index.tsx index 609fc6aac7..80ba13332f 100644 --- a/packages/www/components/FileUpload/index.tsx +++ b/packages/www/components/FileUpload/index.tsx @@ -14,12 +14,12 @@ const FileUpload = () => { const hasPendingFileUploads = useMemo( () => fileUploads.some((file) => !file.completed), - [fileUploads], + [fileUploads] ); const items = useMemo( () => filteredItemsToShow(fileUploads, latestGetAssetsResult ?? []), - [fileUploads, latestGetAssetsResult], + [fileUploads, latestGetAssetsResult] ); useEffect(() => { diff --git a/packages/www/components/Logger/index.tsx b/packages/www/components/Logger/index.tsx index 000fc4f930..ae9edeb3fc 100644 --- a/packages/www/components/Logger/index.tsx +++ b/packages/www/components/Logger/index.tsx @@ -19,7 +19,7 @@ const newLog = ( evt: events.Any, level: "info" | "error", text: string, - keySuffix?: string, + keySuffix?: string ): LogData => ({ key: keySuffix ? `${evt.id}-${keySuffix}` : evt.id, timestamp: evt.timestamp, @@ -102,8 +102,8 @@ function createEventHandler() { infoLog( evt, `Stream is being transcoded on orchestrator ${orchestrator}`, - "transcoding-orchestrator", - ), + "transcoding-orchestrator" + ) ); } @@ -112,8 +112,8 @@ function createEventHandler() { infoLog( evt, `Segment ${seqNo} successfully transcoded on ${orchestrator}`, - "segment-success", - ), + "segment-success" + ) ); failedSegments.current.delete(seqNo); } @@ -131,13 +131,13 @@ function createEventHandler() { newLog( evt, level, - `Multistream of "${payload.target.profile}" to target "${payload.target.name}" ${action}!`, + `Multistream of "${payload.target.profile}" to target "${payload.target.name}" ${action}!` ), ]; } return []; }, - [lastOrchestrator, failedSegments], + [lastOrchestrator, failedSegments] ); } diff --git a/packages/www/components/PastInvoicesTable/index.tsx b/packages/www/components/PastInvoicesTable/index.tsx index 659530db38..16da7ef92b 100644 --- a/packages/www/components/PastInvoicesTable/index.tsx +++ b/packages/www/components/PastInvoicesTable/index.tsx @@ -42,7 +42,7 @@ const PastInvoicesTable = ({ invoices }) => { { products[ invoice.lines.data.filter( - (item) => item.type === "subscription", + (item) => item.type === "subscription" )[0]?.plan.product ]?.name }{" "} diff --git a/packages/www/components/Plans/index.tsx b/packages/www/components/Plans/index.tsx index 1f7a5bf62e..809592d4c6 100644 --- a/packages/www/components/Plans/index.tsx +++ b/packages/www/components/Plans/index.tsx @@ -394,8 +394,8 @@ const Plans = ({ dashboard = false, stripeProductId }: PlanProps) => { ? stripeProductId === "prod_O9XtHhI6rbTT1B" ? "Current plan" : stripeProductId === "prod_O9XtcfOSMjSD5L" - ? "Select" - : "Select" + ? "Select" + : "Select" : "Sign up" } disabled={ diff --git a/packages/www/components/Sidebar/index.tsx b/packages/www/components/Sidebar/index.tsx index 79f6eddeb1..38c4ec50ea 100644 --- a/packages/www/components/Sidebar/index.tsx +++ b/packages/www/components/Sidebar/index.tsx @@ -232,7 +232,7 @@ const Sidebar = ({ id }: { id: SidebarId }) => { const response = canSendEmail("resetPassword"); if (!response.canSend) { openSnackbar( - `Please wait ${response.waitTime} seconds before sending another email.`, + `Please wait ${response.waitTime} seconds before sending another email.` ); return; } @@ -598,7 +598,7 @@ const Sidebar = ({ id }: { id: SidebarId }) => { )} - ), + ) )} { setIsDeleting(true); await Promise.all( - state.selectedRows.map((row) => deleteSigningKey(row.id)), + state.selectedRows.map((row) => deleteSigningKey(row.id)) ); openSnackbar( `${state.selectedRows.length} signing key${ state.selectedRows.length > 1 ? "s" : "" - } deleted.`, + } deleted.` ); setIsDeleting(false); await state.invalidate(); diff --git a/packages/www/components/SigningKeysTable/helpers.tsx b/packages/www/components/SigningKeysTable/helpers.tsx index 24ea47bca2..02bbc6090e 100644 --- a/packages/www/components/SigningKeysTable/helpers.tsx +++ b/packages/www/components/SigningKeysTable/helpers.tsx @@ -43,7 +43,7 @@ export const makeColumns = () => [ export const rowsPageFromState = async ( state: State, - getSigningKeys: Function, + getSigningKeys: Function ): Promise> => { const [signingKeys, nextCursor, _, count] = await getSigningKeys({ filters: formatFiltersForApiRequest(state.filters), @@ -70,7 +70,7 @@ export const rowsPageFromState = async ( date: new Date(signingKey.createdAt), fallback: , }, - }), + }) ); return { rows, nextCursor, count }; }; diff --git a/packages/www/components/SigningKeysTable/index.tsx b/packages/www/components/SigningKeysTable/index.tsx index 37a672446e..a7651c66a0 100644 --- a/packages/www/components/SigningKeysTable/index.tsx +++ b/packages/www/components/SigningKeysTable/index.tsx @@ -41,7 +41,7 @@ const SigningKeysTable = ({ const fetcher: Fetcher = useCallback( async (state) => rowsPageFromState(state, getSigningKeys), - [], + [] ); useEffect(() => { @@ -62,7 +62,7 @@ const SigningKeysTable = ({ selectAction={makeSelectAction("Delete", deleteDialogState.onOn)} createAction={makeCreateAction( "Create signing key", - createDialogState.onOn, + createDialogState.onOn )} /> diff --git a/packages/www/components/StreamDetails/HealthChecksTable/helpers.tsx b/packages/www/components/StreamDetails/HealthChecksTable/helpers.tsx index 9dc44983d1..aa30b4ce26 100644 --- a/packages/www/components/StreamDetails/HealthChecksTable/helpers.tsx +++ b/packages/www/components/StreamDetails/HealthChecksTable/helpers.tsx @@ -35,7 +35,7 @@ export const makeColumns = () => [ export const makeTableData = ( conditionsMap: Record, stream: Stream, - streamActiveSince: number, + streamActiveSince: number ): TableData => ({ isLoading: false, data: { diff --git a/packages/www/components/StreamDetails/HealthChecksTable/index.tsx b/packages/www/components/StreamDetails/HealthChecksTable/index.tsx index 2df3558bcb..e99f2f49bb 100644 --- a/packages/www/components/StreamDetails/HealthChecksTable/index.tsx +++ b/packages/www/components/StreamDetails/HealthChecksTable/index.tsx @@ -35,26 +35,23 @@ const HealthChecksTable = ({ const conditionsMap = useMemo( () => - (streamHealth?.conditions ?? []).reduce( - function (map, condition) { - map[condition.type] = condition; - return map; - }, - {} as Record, - ), - [streamHealth?.conditions], + (streamHealth?.conditions ?? []).reduce(function (map, condition) { + map[condition.type] = condition; + return map; + }, {} as Record), + [streamHealth?.conditions] ); const streamActiveSince = useMemo( () => conditionsMap.Active?.status ? conditionsMap.Active.lastTransitionTime : null, - [conditionsMap.Active], + [conditionsMap.Active] ); const tableData: TableData = useMemo( () => makeTableData(conditionsMap, stream, streamActiveSince), - [state.tableId, stream, streamActiveSince, conditionsMap], + [state.tableId, stream, streamActiveSince, conditionsMap] ); return ( diff --git a/packages/www/components/StreamDetails/MultistreamTargetsTable/SaveTargetDialog.tsx b/packages/www/components/StreamDetails/MultistreamTargetsTable/SaveTargetDialog.tsx index 248a2e376f..a1ad06cdcf 100644 --- a/packages/www/components/StreamDetails/MultistreamTargetsTable/SaveTargetDialog.tsx +++ b/packages/www/components/StreamDetails/MultistreamTargetsTable/SaveTargetDialog.tsx @@ -61,7 +61,7 @@ const parseUrlSafe = (str: string) => { const addQuery = ( url: url.UrlWithParsedQuery, - query: querystring.ParsedUrlQuery, + query: querystring.ParsedUrlQuery ) => { url.query = { ...url.query, ...query }; url.search = `?${querystring.stringify(url.query)}`; @@ -95,7 +95,7 @@ const createTarget = ( api: Api, stream: Stream, state: State, - parsedUrl: url.Url, + parsedUrl: url.Url ) => { const targets: MultistreamTargetRef[] = [ ...(stream.multistream?.targets ?? []), @@ -117,7 +117,7 @@ const updateTarget = async ( targetId: string, state: State, parsedUrl: url.Url, - initState: State, + initState: State ) => { const patch = { name: state.name !== initState.name ? state.name : undefined, @@ -138,7 +138,7 @@ const updateTarget = async ( ...t, profile: state.profile, videoOnly: state.videoOnly, - }, + } ); await api.patchStream(stream.id, { multistream: { targets } }); } @@ -173,7 +173,7 @@ const SaveTargetDialog = ({ profile: action === Action.Create ? "source" : targetRef?.profile, videoOnly: targetRef?.videoOnly ?? false, }), - [action, target?.name, targetRef?.profile, targetRef?.videoOnly], + [action, target?.name, targetRef?.profile, targetRef?.videoOnly] ); const [state, setState] = useState(initState); useEffect(() => setState(initState), [isOpen]); @@ -184,7 +184,7 @@ const SaveTargetDialog = ({ const parsedUrl = useMemo( () => composeIngestUrl(state.ingestUrl, state.streamKey), - [state.ingestUrl, state.streamKey], + [state.ingestUrl, state.streamKey] ); const saveMultistreamTarget = async () => { @@ -202,7 +202,7 @@ const SaveTargetDialog = ({ openSnackbar( `Successfully ${ action === Action.Create ? "created" : "updated" - } multistream target ${name}`, + } multistream target ${name}` ); } catch (error) { console.error(error); @@ -219,7 +219,7 @@ const SaveTargetDialog = ({ }; const fromStream = stream.profiles ?.sort( - (p1, p2) => p1.height - p2.height || p1.name.localeCompare(p2.name), + (p1, p2) => p1.height - p2.height || p1.name.localeCompare(p2.name) ) .reverse() .map(({ name, width, height, fps }) => ({ diff --git a/packages/www/components/StreamDetails/MultistreamTargetsTable/TargetStatusBadge.tsx b/packages/www/components/StreamDetails/MultistreamTargetsTable/TargetStatusBadge.tsx index 39a69af3e9..3d42a8396b 100644 --- a/packages/www/components/StreamDetails/MultistreamTargetsTable/TargetStatusBadge.tsx +++ b/packages/www/components/StreamDetails/MultistreamTargetsTable/TargetStatusBadge.tsx @@ -10,7 +10,7 @@ const computeStatus = ( target: MultistreamTarget, status: MultistreamStatus, streamActiveSince: number | undefined, - metrics: Metrics, + metrics: Metrics ): Status => { if ( status?.connected.lastProbeTime < streamActiveSince || @@ -22,7 +22,7 @@ const computeStatus = ( const currentTimestamp = moment().unix() * 1000; const lastActive = metrics?.MultistreamActiveSec?.find( - (m) => m?.dimensions?.targetId === target?.id, + (m) => m?.dimensions?.targetId === target?.id )?.last[0]; const difference = (currentTimestamp - lastActive) / 1000; @@ -58,7 +58,7 @@ const TargetStatusBadge = ({ }) => { const status = useMemo( () => computeStatus(stream, target, msStatus, streamActiveSince, metrics), - [stream, target, msStatus, streamActiveSince], + [stream, target, msStatus, streamActiveSince] ); const timestamp = msStatus?.connected.lastProbeTime; return ; diff --git a/packages/www/components/StreamDetails/MultistreamTargetsTable/Toolbox.tsx b/packages/www/components/StreamDetails/MultistreamTargetsTable/Toolbox.tsx index 1159d37256..eba905dbd4 100644 --- a/packages/www/components/StreamDetails/MultistreamTargetsTable/Toolbox.tsx +++ b/packages/www/components/StreamDetails/MultistreamTargetsTable/Toolbox.tsx @@ -132,7 +132,7 @@ const DeleteDialog = ({ setSaving(true); try { const targets = stream.multistream.targets.filter( - (t) => t.id !== targetId, + (t) => t.id !== targetId ); const patch = { multistream: { targets } }; await patchStream(stream.id, patch); @@ -187,7 +187,7 @@ const Toolbox = ({ await patchMultistreamTarget(target.id, { disabled }); await invalidateTargetId(target?.id); openSnackbar( - `Target ${target.name} has been turned ${disabled ? "off" : "on"}.`, + `Target ${target.name} has been turned ${disabled ? "off" : "on"}.` ); }, [ @@ -197,7 +197,7 @@ const Toolbox = ({ target?.id, target?.name, target?.disabled, - ], + ] ); const invalidateAll = useCallback(async () => { await Promise.all([invalidateStream(), invalidateTargetId(target?.id)]); @@ -254,7 +254,7 @@ const Toolbox = ({ setTargetDisabled(true), - [setTargetDisabled], + [setTargetDisabled] )} open={disableDialogOpen} setOpen={setDisableDialogOpen} diff --git a/packages/www/components/StreamDetails/MultistreamTargetsTable/helpers.tsx b/packages/www/components/StreamDetails/MultistreamTargetsTable/helpers.tsx index 852514ce3c..e27cc327e3 100644 --- a/packages/www/components/StreamDetails/MultistreamTargetsTable/helpers.tsx +++ b/packages/www/components/StreamDetails/MultistreamTargetsTable/helpers.tsx @@ -52,7 +52,7 @@ export const makeTableData = ( targets, targetRefs, invalidateStream: (optm?: Stream) => Promise, - invalidateTargetId, + invalidateTargetId ): TableData => { return { isLoading: false, @@ -62,7 +62,7 @@ export const makeTableData = ( rows: targets.map((target, idx) => { const ref = targetRefs[idx]; const status = streamHealth?.multistream?.find( - (m) => m.target.id === ref.id && m.target.profile === ref.profile, + (m) => m.target.id === ref.id && m.target.profile === ref.profile ); return { id: ref.id, diff --git a/packages/www/components/StreamDetails/MultistreamTargetsTable/index.tsx b/packages/www/components/StreamDetails/MultistreamTargetsTable/index.tsx index 9ca4b0b499..91056652fe 100644 --- a/packages/www/components/StreamDetails/MultistreamTargetsTable/index.tsx +++ b/packages/www/components/StreamDetails/MultistreamTargetsTable/index.tsx @@ -47,18 +47,18 @@ const MultistreamTargetsTable = ({ const targetQueryKey = (id: string) => ["multistreamTarget", id]; const invalidateTargetId = useCallback( (id: string) => queryClient.invalidateQueries(targetQueryKey(id)), - [queryClient], + [queryClient] ); const targetRefs = stream.multistream?.targets ?? []; const targets = useQueries( targetRefs.map((ref) => ({ queryKey: targetQueryKey(ref.id), queryFn: () => getMultistreamTarget(ref.id), - })), + })) ).map((res) => res.data as MultistreamTarget); const streamActiveSince = useMemo(() => { const activeCondition = streamHealth?.conditions.find( - (c) => c.type === "Active", + (c) => c.type === "Active" ); return activeCondition?.status ? activeCondition.lastTransitionTime : null; }, [streamHealth?.conditions]); @@ -72,9 +72,9 @@ const MultistreamTargetsTable = ({ targets, targetRefs, invalidateStream, - invalidateTargetId, + invalidateTargetId ), - [state.tableId, stream, streamHealth, invalidateTargetId, targetRefs], + [state.tableId, stream, streamHealth, invalidateTargetId, targetRefs] ); const trackEvent = useCallback(() => { diff --git a/packages/www/components/StreamDetails/SessionsTable/ClipsCell.tsx b/packages/www/components/StreamDetails/SessionsTable/ClipsCell.tsx index 4a251cb821..6495dd2548 100644 --- a/packages/www/components/StreamDetails/SessionsTable/ClipsCell.tsx +++ b/packages/www/components/StreamDetails/SessionsTable/ClipsCell.tsx @@ -35,7 +35,7 @@ const ClipsCell = ({ {cell.value.clipsCounts} diff --git a/packages/www/components/StreamDetails/SessionsTable/helpers.tsx b/packages/www/components/StreamDetails/SessionsTable/helpers.tsx index a69523c505..71828c71b2 100644 --- a/packages/www/components/StreamDetails/SessionsTable/helpers.tsx +++ b/packages/www/components/StreamDetails/SessionsTable/helpers.tsx @@ -55,7 +55,7 @@ export const makeColumns = () => [ sortType: (...params: SortTypeArgs) => numberSort( "original.sourceSegmentsDuration.sourceSegmentsDuration", - ...params, + ...params ), }, { @@ -78,7 +78,7 @@ export const rowsPageFromState = async ( streamId: string, getStreamSessions: Function, getClipsBySessionId: Function, - openSnackbar: Function, + openSnackbar: Function ): Promise> => { const [streams, nextCursor, count] = await getStreamSessions( streamId, @@ -87,11 +87,11 @@ export const rowsPageFromState = async ( formatFiltersForApiRequest(state.filters, { parseNumber: (n) => n * 60, }), - true, + true ); const clipsPromises = streams.map((stream: any) => - getClipsBySessionId(stream.id, null, 100, null, null, 1), + getClipsBySessionId(stream.id, null, 100, null, null, 1) ); const clipsCounts = await Promise.all(clipsPromises); diff --git a/packages/www/components/StreamDetails/SessionsTable/index.tsx b/packages/www/components/StreamDetails/SessionsTable/index.tsx index 89bd498307..fe63f421cd 100644 --- a/packages/www/components/StreamDetails/SessionsTable/index.tsx +++ b/packages/www/components/StreamDetails/SessionsTable/index.tsx @@ -42,9 +42,9 @@ const SessionsTable = ({ streamId, getStreamSessions, getClipsBySessionId, - openSnackbar, + openSnackbar ), - [getStreamSessions, user.id], + [getStreamSessions, user.id] ); return ( diff --git a/packages/www/components/StreamDetails/StreamHealthTab.tsx b/packages/www/components/StreamDetails/StreamHealthTab.tsx index ec0fc1e1cc..b0e46ac16a 100644 --- a/packages/www/components/StreamDetails/StreamHealthTab.tsx +++ b/packages/www/components/StreamDetails/StreamHealthTab.tsx @@ -28,7 +28,7 @@ const StreamHealthTab = ({ stream, streamHealth, invalidateStream }) => { const June = useJune(); const [multiDataChart, setMultiDataChart] = useState( - [], + [] ); const startTime = useMemo(() => Date.now(), []); @@ -53,7 +53,7 @@ const StreamHealthTab = ({ stream, streamHealth, invalidateStream }) => { setInfo(info); } }, - [getStreamInfo], + [getStreamInfo] ); const getIngestRate = useCallback( @@ -70,13 +70,13 @@ const StreamHealthTab = ({ stream, streamHealth, invalidateStream }) => { { name: lastItem ? lastItem.name + ingestInterval / 1000 : 0, "Session bitrate": Math.round( - (newInfo.session.ingestRate / 1000) * 8, + (newInfo.session.ingestRate / 1000) * 8 ), // kilobits rather than bytes here }, ].slice(Math.max(prev.length - maxItems, 0)); }); }, - [getStreamInfo], + [getStreamInfo] ); useEffect(() => { diff --git a/packages/www/components/StreamDetails/StreamOverviewBox.tsx b/packages/www/components/StreamDetails/StreamOverviewBox.tsx index d53919eb18..02c7a7858a 100644 --- a/packages/www/components/StreamDetails/StreamOverviewBox.tsx +++ b/packages/www/components/StreamDetails/StreamOverviewBox.tsx @@ -68,7 +68,7 @@ const StreamOverviewBox = ({ url={globalPlaybackUrl} shortendUrl={globalPlaybackUrl.replace( globalPlaybackUrl.slice(29, 45), - "…", + "…" )} anchor={false} /> diff --git a/packages/www/components/StreamDetails/StreamPlayerBox/index.tsx b/packages/www/components/StreamDetails/StreamPlayerBox/index.tsx index c6cf41a45a..3bb859f39e 100644 --- a/packages/www/components/StreamDetails/StreamPlayerBox/index.tsx +++ b/packages/www/components/StreamDetails/StreamPlayerBox/index.tsx @@ -48,13 +48,13 @@ const StreamPlayerBox = ({ setIsBroadcastLive, }: StreamPlayerBoxProps) => { const [activeTab, setSwitchTab] = useState<"Browser" | "Streaming Software">( - "Browser", + "Browser" ); const June = useJune(); const isStreamActiveFromExternal = useMemo( () => !isBroadcastLive && stream.isActive, - [isBroadcastLive, stream.isActive], + [isBroadcastLive, stream.isActive] ); useEffect(() => { diff --git a/packages/www/components/StreamSessionsTable/DeleteDialog.tsx b/packages/www/components/StreamSessionsTable/DeleteDialog.tsx index d6fab664eb..9376eb3541 100644 --- a/packages/www/components/StreamSessionsTable/DeleteDialog.tsx +++ b/packages/www/components/StreamSessionsTable/DeleteDialog.tsx @@ -77,7 +77,7 @@ const DeleteDialog = ({ total, onUnselect, onDelete }) => { setSaving(true); await onDelete(); openSnackbar( - `${total} session${total > 1 ? "s" : ""} deleted.`, + `${total} session${total > 1 ? "s" : ""} deleted.` ); setSaving(false); setOpen(false); diff --git a/packages/www/components/StreamSessionsTable/helpers.tsx b/packages/www/components/StreamSessionsTable/helpers.tsx index f6cf703c22..29c698f50a 100644 --- a/packages/www/components/StreamSessionsTable/helpers.tsx +++ b/packages/www/components/StreamSessionsTable/helpers.tsx @@ -59,7 +59,7 @@ export const makeColumns = () => [ sortType: (...params: SortTypeArgs) => numberSort( "original.sourceSegmentsDuration.sourceSegmentsDuration", - ...params, + ...params ), }, { @@ -75,7 +75,7 @@ export const rowsPageFromState = async ( userId: string, getStreamSessionsByUserId: Function, openSnackbar: Function, - appendProjectId: Function, + appendProjectId: Function ): Promise> => { const [streams, nextCursor, count] = await getStreamSessionsByUserId( userId, @@ -85,7 +85,7 @@ export const rowsPageFromState = async ( formatFiltersForApiRequest(state.filters, { parseNumber: (n) => n * 60, }), - true, + true ); return { diff --git a/packages/www/components/StreamSessionsTable/index.tsx b/packages/www/components/StreamSessionsTable/index.tsx index 1cc398bffa..a5193abf98 100644 --- a/packages/www/components/StreamSessionsTable/index.tsx +++ b/packages/www/components/StreamSessionsTable/index.tsx @@ -33,9 +33,9 @@ const StreamSessionsTable = ({ title = "Sessions" }: { title?: string }) => { user.id, getStreamSessionsByUserId, openSnackbar, - appendProjectId, + appendProjectId ), - [getStreamSessionsByUserId, user.id], + [getStreamSessionsByUserId, user.id] ); useEffect(() => { diff --git a/packages/www/components/StreamsTable/StreamFilter.tsx b/packages/www/components/StreamsTable/StreamFilter.tsx index e7ae58ac11..13ad17f92e 100644 --- a/packages/www/components/StreamsTable/StreamFilter.tsx +++ b/packages/www/components/StreamsTable/StreamFilter.tsx @@ -253,7 +253,7 @@ const StreamFilter = ({ onDone, activeFilters }) => { onClick={(e) => { e.stopPropagation(); const newFilters = outputFilters.filter( - (f) => f.id !== filter.id, + (f) => f.id !== filter.id ); setOutputFilters(newFilters); onDone(newFilters); diff --git a/packages/www/components/StreamsTable/helpers.tsx b/packages/www/components/StreamsTable/helpers.tsx index de0a91d5ff..f3d6f9bc35 100644 --- a/packages/www/components/StreamsTable/helpers.tsx +++ b/packages/www/components/StreamsTable/helpers.tsx @@ -65,7 +65,7 @@ export const rowsPageFromState = async ( state: State, userId: string, getStreams: Function, - appendProjectId: Function, + appendProjectId: Function ): Promise> => { let active: boolean; let isHealthy: boolean; diff --git a/packages/www/components/StreamsTable/index.tsx b/packages/www/components/StreamsTable/index.tsx index e4f2dfcd10..1c3c97b802 100644 --- a/packages/www/components/StreamsTable/index.tsx +++ b/packages/www/components/StreamsTable/index.tsx @@ -63,7 +63,7 @@ const StreamsTable = ({ const fetcher: Fetcher = useCallback( async (state) => rowsPageFromState(state, userId, getStreams, appendProjectId), - [userId], + [userId] ); const onCreateClick = useCallback( @@ -79,7 +79,7 @@ const StreamsTable = ({ query, }); }, - [createStream, state.invalidate], + [createStream, state.invalidate] ); const onSetFilters = (e) => { @@ -101,7 +101,7 @@ const StreamsTable = ({ if (type === "All") { console.log("All", currentFilters); const newFilters = currentFilters.filter( - (filter) => filter.id !== "isActive" && filter.id !== "isHealthy", + (filter) => filter.id !== "isActive" && filter.id !== "isHealthy" ); stateSetter.setFilters([]); } else { @@ -129,7 +129,7 @@ const StreamsTable = ({ if (type !== "All") { searchParams.set( type === "Active" ? "isActive" : "isHealthy", - type === "Active" ? "true" : "false", + type === "Active" ? "true" : "false" ); } @@ -184,7 +184,7 @@ const StreamsTable = ({ selectAction={makeSelectAction("Delete", deleteDialogState.onOn)} createAction={makeCreateAction( "Create livestream", - createDialogState.onOn, + createDialogState.onOn )} header={ <> diff --git a/packages/www/components/Table/components/TableStateDeleteDialog.tsx b/packages/www/components/Table/components/TableStateDeleteDialog.tsx index 26ee0ff235..10c5c8c801 100644 --- a/packages/www/components/Table/components/TableStateDeleteDialog.tsx +++ b/packages/www/components/Table/components/TableStateDeleteDialog.tsx @@ -46,7 +46,7 @@ const TableStateDeleteDialog = ({ await deleteMultipleFunction(ids); } else if (ids.length > 1) { const promises = state.selectedRows.map(async (row) => - deleteFunction(row.original.id), + deleteFunction(row.original.id) ); await Promise.all(promises); } else if (ids.length === 1) { diff --git a/packages/www/components/Table/filters/index.tsx b/packages/www/components/Table/filters/index.tsx index 8e76c45450..98b9729008 100644 --- a/packages/www/components/Table/filters/index.tsx +++ b/packages/www/components/Table/filters/index.tsx @@ -55,14 +55,14 @@ const TableFilter = ({ items, onDone }: TableFilterProps) => { const router = useRouter(); const [isOpen, setIsOpen] = useState(false); const [filters, setFilters] = useState( - items.map((i) => ({ ...i, isOpen: false })), + items.map((i) => ({ ...i, isOpen: false })) ); const [activeFiltersCount, setActiveFiltersCount] = useState(0); const [previousFilters, setPreviousFilters] = useState([]); const handleClear = useCallback(() => { setFilters((p) => - p.map((f) => ({ ...f, isOpen: false, condition: undefined })), + p.map((f) => ({ ...f, isOpen: false, condition: undefined })) ); }, []); @@ -102,7 +102,7 @@ const TableFilter = ({ items, onDone }: TableFilterProps) => { setFilters(previousFilters); } }, - [filters, previousFilters], + [filters, previousFilters] ); return ( @@ -266,7 +266,7 @@ type Parsers = { export const formatFiltersForApiRequest = ( filters: Filter[], - parsers?: Partial, + parsers?: Partial ) => { const normalized: { id: string; value: any }[] = []; const typedParsers: Parsers = { @@ -357,7 +357,7 @@ export const formatFiltersForQueryParam = (filters: Filter[]) => { normalized.push({ id: filter.id, value: `${new Date(filter.condition.value[0]).getTime()},${new Date( - filter.condition.value[1], + filter.condition.value[1] ).getTime()}`, }); case "numberEqual": @@ -381,7 +381,7 @@ export const formatFiltersForQueryParam = (filters: Filter[]) => { export const formatFilterItemFromQueryParam = ( filter: FilterItem, - queryParamValue: string, + queryParamValue: string ): Filter => { const decodedValue = decodeURIComponent(queryParamValue); switch (filter.type) { @@ -414,12 +414,12 @@ export const formatFilterItemFromQueryParam = ( ? (splitted.map((s) => format( addMinutes(new Date(parseInt(s)), timezoneOffset), - "yyyy-MM-dd", - ), + "yyyy-MM-dd" + ) ) as [string, string]) : format( addMinutes(new Date(parseInt(splitted[0])), timezoneOffset), - "yyyy-MM-dd", + "yyyy-MM-dd" ), }, }; diff --git a/packages/www/components/Table/index.tsx b/packages/www/components/Table/index.tsx index a1174b5490..618ea3f9b4 100644 --- a/packages/www/components/Table/index.tsx +++ b/packages/www/components/Table/index.tsx @@ -90,7 +90,7 @@ export type FetchResult> = { }; export type Fetcher> = ( - state: State, + state: State ) => Promise>; export type TableData> = { @@ -241,7 +241,7 @@ export const DataTableComponent = >({ ...columns, ]); } - }, + } ); useEffect(() => { stateSetter.setSelectedRows(selectedFlatRows); @@ -434,7 +434,7 @@ export const DataTableComponent = >({ }} {...column.getHeaderProps( // @ts-ignore - column.getSortByToggleProps(), + column.getSortByToggleProps() )}> >({ setDataCount, setProjectId, }), - [], + [] ); const state: State = useMemo( @@ -620,7 +620,7 @@ export const useTableState = >({ queryClient, tableId, projectId, - ], + ] ); return { state, stateSetter }; @@ -638,7 +638,7 @@ const TableComponent = >(props: Props) => { const tableData: UseQueryResult> = useQuery( queryKey, () => fetcher(state), - fetcherOptions, + fetcherOptions ); return DataTableComponent({ ...props, tableData }); diff --git a/packages/www/components/Table/types.ts b/packages/www/components/Table/types.ts index 156b1fb07c..8ecc001c26 100644 --- a/packages/www/components/Table/types.ts +++ b/packages/www/components/Table/types.ts @@ -3,14 +3,14 @@ export type TableData = Record; export type CellComponentProps< D extends TableData, - T, + T > = React.PropsWithChildren>; export type SortTypeArgs = [ rowA: Row>, rowB: Row>, columnId: string, - desc: boolean, + desc: boolean ]; export type SortFn = ( @@ -18,7 +18,7 @@ export type SortFn = ( rowA: Row>, rowB: Row>, columnId: string, - desc: boolean, + desc: boolean ) => number; export type RowsPageFromStateResult = { diff --git a/packages/www/components/UpcomingInvoiceTable/index.tsx b/packages/www/components/UpcomingInvoiceTable/index.tsx index 4ad1dfc485..21103261d3 100644 --- a/packages/www/components/UpcomingInvoiceTable/index.tsx +++ b/packages/www/components/UpcomingInvoiceTable/index.tsx @@ -107,7 +107,7 @@ const UpcomingInvoiceTable = ({
Due on{" "} {new Date( - subscription.current_period_end * 1000, + subscription.current_period_end * 1000 ).toLocaleDateString("en-US", { year: "numeric", month: "long", diff --git a/packages/www/components/UsageSummary/index.tsx b/packages/www/components/UsageSummary/index.tsx index df81d43b05..1e1c7cdaff 100644 --- a/packages/www/components/UsageSummary/index.tsx +++ b/packages/www/components/UsageSummary/index.tsx @@ -87,7 +87,7 @@ const UsageSummary = () => { const [subscription, setSubscription] = useState(null); const [invoices, setInvoices] = useState(null); const [overUsageBill, setOverUsageBill] = useState( - null, + null ); const [upcomingInvoiceTotal, setUpcomingInvoiceTotal] = useState(0); const [upcomingInvoice, setUpcomingInvoice] = useState(null); @@ -134,7 +134,7 @@ const UsageSummary = () => { doGetUsage( subscription?.current_period_start, subscription?.current_period_end, - subscription?.status, + subscription?.status ); }; @@ -160,7 +160,7 @@ const UsageSummary = () => { TotalUsageMins: Math.max(usage?.TotalUsageMins - limits.transcoding, 0), DeliveryUsageMins: Math.max( usage?.DeliveryUsageMins - limits.streaming, - 0, + 0 ), StorageUsageMins: Math.max(usage?.StorageUsageMins - limits.storage, 0), }; @@ -176,8 +176,8 @@ const UsageSummary = () => { units: overusage.TotalUsageMins, total: Number( (overusage.TotalUsageMins * payAsYouGoData.usage[0].price).toFixed( - 2, - ), + 2 + ) ), }, deliveryBill: { @@ -185,7 +185,7 @@ const UsageSummary = () => { total: Number( ( overusage.DeliveryUsageMins * payAsYouGoData.usage[1].price - ).toFixed(2), + ).toFixed(2) ), }, storageBill: { @@ -193,7 +193,7 @@ const UsageSummary = () => { total: Number( ( overusage.StorageUsageMins * payAsYouGoData.usage[2].price - ).toFixed(2), + ).toFixed(2) ), }, }; @@ -263,14 +263,14 @@ const UsageSummary = () => { {subscription && ( {new Date( - subscription.current_period_start * 1000, + subscription.current_period_start * 1000 ).toLocaleDateString("en-US", { month: "short", day: "numeric", })}{" "} to{" "} {new Date( - subscription.current_period_end * 1000, + subscription.current_period_end * 1000 ).toLocaleDateString("en-US", { month: "short", day: "numeric", diff --git a/packages/www/components/WebhookDetails/LogsContainer.tsx b/packages/www/components/WebhookDetails/LogsContainer.tsx index cb86c68fdd..d453656ce4 100644 --- a/packages/www/components/WebhookDetails/LogsContainer.tsx +++ b/packages/www/components/WebhookDetails/LogsContainer.tsx @@ -48,8 +48,8 @@ const LogsContainer = ({ filter === "all" ? logs : filter === "succeeded" - ? succeededLogs - : failedLogs; + ? succeededLogs + : failedLogs; const customTheme = { key: "color:#606060;line-height:1.8;font-size:14px;", @@ -224,7 +224,7 @@ const LogsContainer = ({ JSON.parse(selected?.request?.body)?.payload || JSON.parse(selected?.request?.body)?.stream || JSON.parse(selected?.request?.body)?.asset || - JSON.parse(selected?.request?.body)?.task, + JSON.parse(selected?.request?.body)?.task )} /> )} diff --git a/packages/www/components/WebhookDetails/index.tsx b/packages/www/components/WebhookDetails/index.tsx index 7d6e535520..3fd24619b1 100644 --- a/packages/www/components/WebhookDetails/index.tsx +++ b/packages/www/components/WebhookDetails/index.tsx @@ -359,8 +359,8 @@ const Filters = ({ filters, activeFilter, handleFilterClick, logs }) => { {filter === "all" ? totalWebhookLogs : filter === "succeeded" - ? totalSucceededWebhookLogs - : totalFailedWebhookLogs} + ? totalSucceededWebhookLogs + : totalFailedWebhookLogs} ))} diff --git a/packages/www/components/WebhooksTable/helpers.tsx b/packages/www/components/WebhooksTable/helpers.tsx index 77c2e80623..6d5da7a62a 100644 --- a/packages/www/components/WebhooksTable/helpers.tsx +++ b/packages/www/components/WebhooksTable/helpers.tsx @@ -47,7 +47,7 @@ export const makeColumns = () => [ export const rowsPageFromState = async ( state, getWebhooks: Function, - appendProjectId: Function, + appendProjectId: Function ): Promise> => { const [webhooks, nextCursor, _res, count] = await getWebhooks( false, @@ -56,7 +56,7 @@ export const rowsPageFromState = async ( null, state.pageSize, state.cursor, - true, + true ); return { diff --git a/packages/www/components/WebhooksTable/index.tsx b/packages/www/components/WebhooksTable/index.tsx index c9452d5046..28693a7d76 100644 --- a/packages/www/components/WebhooksTable/index.tsx +++ b/packages/www/components/WebhooksTable/index.tsx @@ -39,7 +39,7 @@ const WebhooksTable = ({ title = "Endpoints" }: { title?: string }) => { const fetcher: Fetcher = useCallback( async (state) => rowsPageFromState(state, getWebhooks, appendProjectId), - [getWebhooks, user.id], + [getWebhooks, user.id] ); const onCreateSubmit = async ({ events, name, url, sharedSecret }) => { @@ -75,7 +75,7 @@ const WebhooksTable = ({ title = "Endpoints" }: { title?: string }) => { selectAction={makeSelectAction("Delete", deleteDialogState.onOn)} createAction={makeCreateAction( "Create webhook", - createDialogState.onOn, + createDialogState.onOn )} /> diff --git a/packages/www/css/markdown.css b/packages/www/css/markdown.css index 58ffbefec9..a38066daa2 100644 --- a/packages/www/css/markdown.css +++ b/packages/www/css/markdown.css @@ -242,14 +242,8 @@ .markdown-body kbd { display: inline-block; padding: 3px 5px; - font: - 11px ui-monospace, - SFMono-Regular, - SF Mono, - Menlo, - Consolas, - Liberation Mono, - monospace; + font: 11px ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, + Liberation Mono, monospace; line-height: 10px; color: #24292f; vertical-align: middle; @@ -339,28 +333,16 @@ .markdown-body tt, .markdown-body code { - font-family: - ui-monospace, - SFMono-Regular, - SF Mono, - Menlo, - Consolas, - Liberation Mono, - monospace; + font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, + Liberation Mono, monospace; font-size: 12px; } .markdown-body pre { margin-top: 0; margin-bottom: 0; - font-family: - ui-monospace, - SFMono-Regular, - SF Mono, - Menlo, - Consolas, - Liberation Mono, - monospace; + font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, + Liberation Mono, monospace; font-size: 12px; word-wrap: normal; } diff --git a/packages/www/hooks/use-analyzer.tsx b/packages/www/hooks/use-analyzer.tsx index 09facb87ec..6cab82b841 100644 --- a/packages/www/hooks/use-analyzer.tsx +++ b/packages/www/hooks/use-analyzer.tsx @@ -237,7 +237,7 @@ class AnalyzerClient { fetchJson = async ( region: string, path: string, - opts: RequestInit = {}, + opts: RequestInit = {} ) => { const url = makeUrl(region, path); const headers = new Headers(opts.headers || {}); @@ -269,7 +269,7 @@ class AnalyzerClient { region: string, streamId: string, handler: (data: events.Any) => void, - from?: number, + from?: number ) => { const path = `/stream/${streamId}/events`; const qs = !from ? "" : "?from=" + from; diff --git a/packages/www/hooks/use-api/endpoints/accessControl.ts b/packages/www/hooks/use-api/endpoints/accessControl.ts index 8a92e552cf..6a64136826 100644 --- a/packages/www/hooks/use-api/endpoints/accessControl.ts +++ b/packages/www/hooks/use-api/endpoints/accessControl.ts @@ -15,7 +15,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -37,7 +37,7 @@ export const getSigningKeys = async (opts?: { cursor: opts?.cursor, count: opts?.count, projectId, - })}`, + })}` ); const nextCursor = getCursor(res.headers.get("link")); const count = res.headers.get("X-Total-Count"); @@ -45,7 +45,7 @@ export const getSigningKeys = async (opts?: { }; export const createSigningKey = async ( - params, + params ): Promise => { trackPageView(params.email, "/create-signing-key"); const url = `/access-control/signing-key?projectId=${projectId}`; diff --git a/packages/www/hooks/use-api/endpoints/apiToken.ts b/packages/www/hooks/use-api/endpoints/apiToken.ts index 8ee96c2430..9c2bf405d3 100644 --- a/packages/www/hooks/use-api/endpoints/apiToken.ts +++ b/packages/www/hooks/use-api/endpoints/apiToken.ts @@ -11,7 +11,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -25,7 +25,7 @@ export const getApiTokens = async ( cursor?: string; order?: string; count?: boolean; - }, + } ): Promise<[Array | ApiError, string, Response, number]> => { const filters = opts?.filters ? JSON.stringify(opts?.filters) : undefined; const [res, tokens] = await context.fetch( @@ -37,7 +37,7 @@ export const getApiTokens = async ( cursor: opts?.cursor, count: opts?.count, projectId, - })}`, + })}` ); const nextCursor = getCursor(res.headers.get("link")); const count = res.headers.get("X-Total-Count"); @@ -54,7 +54,7 @@ export const createApiToken = async (params): Promise => { headers: { "content-type": "application/json", }, - }, + } ); if (res.status !== 201) { throw new Error(JSON.stringify(res.errors)); diff --git a/packages/www/hooks/use-api/endpoints/asset.ts b/packages/www/hooks/use-api/endpoints/asset.ts index fa5b25af9c..6b074660ac 100644 --- a/packages/www/hooks/use-api/endpoints/asset.ts +++ b/packages/www/hooks/use-api/endpoints/asset.ts @@ -12,7 +12,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -38,12 +38,12 @@ export const uploadAssets = async ( files: File[], onSuccess?: (file: File) => void, onError?: (file: File, error: Error) => void, - onProgress?: (file: File, progress: number) => void, + onProgress?: (file: File, progress: number) => void ): Promise => { const url = `/asset/request-upload?projectId=${projectId}`; const requestAssetUpload = async ( - params, + params ): Promise<{ tusEndpoint: string }> => { const [res, assetUpload] = await context.fetch(url, { method: "POST", @@ -64,7 +64,7 @@ export const uploadAssets = async ( progress: number, completed: boolean, updatedAt: number, - error?: Error, + error?: Error ) => { setState((state) => ({ ...state, @@ -127,13 +127,13 @@ export const uploadAssets = async ( export const getFileUploads = (): FileUpload[] => { return Object.keys(context.currentFileUploads ?? {}).map( - (key) => context.currentFileUploads?.[key], + (key) => context.currentFileUploads?.[key] ); }; export const getFilteredFileUploads = (): FileUpload[] => { return getFileUploads().filter( - (file) => file && !file.error && file.file.name, + (file) => file && !file.error && file.file.name ); }; @@ -149,7 +149,7 @@ export const getAssets = async ( cursor?: string; order?: string; count?: boolean; - }, + } ): Promise<[Asset[], string, number]> => { const filters = opts?.filters ? JSON.stringify(opts?.filters) : undefined; const [res, assets] = await context.fetch( @@ -162,7 +162,7 @@ export const getAssets = async ( count: opts?.count, details: 1, projectId, - })}`, + })}` ); if (res.status !== 200) { throw new Error(assets); @@ -187,7 +187,7 @@ export const getAsset = async (assetId): Promise => { export const patchAsset = async ( assetId: string, - patch: AssetPatchPayload, + patch: AssetPatchPayload ): Promise => { const url = `/asset/${assetId}?projectId=${projectId}`; diff --git a/packages/www/hooks/use-api/endpoints/broadcaster.ts b/packages/www/hooks/use-api/endpoints/broadcaster.ts index 19a51b080e..34eec63c2e 100644 --- a/packages/www/hooks/use-api/endpoints/broadcaster.ts +++ b/packages/www/hooks/use-api/endpoints/broadcaster.ts @@ -6,7 +6,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; diff --git a/packages/www/hooks/use-api/endpoints/clip.ts b/packages/www/hooks/use-api/endpoints/clip.ts index 055993ab83..0e17f96ea5 100644 --- a/packages/www/hooks/use-api/endpoints/clip.ts +++ b/packages/www/hooks/use-api/endpoints/clip.ts @@ -9,7 +9,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -21,7 +21,7 @@ export const getClipsBySessionId = async ( limit: number = 20, order?: string, filters?: Array<{ id: string; value: string | object }>, - count?: boolean, + count?: boolean ): Promise<[Array, string, number]> => { const stringifiedFilters = filters ? JSON.stringify(filters) : undefined; const uri = `/clip/${sessionId}?${qs.stringify({ diff --git a/packages/www/hooks/use-api/endpoints/data.ts b/packages/www/hooks/use-api/endpoints/data.ts index 0ea605f4b2..1023469cb9 100644 --- a/packages/www/hooks/use-api/endpoints/data.ts +++ b/packages/www/hooks/use-api/endpoints/data.ts @@ -6,7 +6,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; diff --git a/packages/www/hooks/use-api/endpoints/ingest.ts b/packages/www/hooks/use-api/endpoints/ingest.ts index 3ba05815ce..53b67ec29d 100644 --- a/packages/www/hooks/use-api/endpoints/ingest.ts +++ b/packages/www/hooks/use-api/endpoints/ingest.ts @@ -6,7 +6,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; diff --git a/packages/www/hooks/use-api/endpoints/multistream.ts b/packages/www/hooks/use-api/endpoints/multistream.ts index 9d9a24aca0..d9c4fb9fbd 100644 --- a/packages/www/hooks/use-api/endpoints/multistream.ts +++ b/packages/www/hooks/use-api/endpoints/multistream.ts @@ -11,7 +11,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -19,7 +19,7 @@ export const setSharedScope = ( export const createMultistreamTarget = async ( id: string, - input: Omit, + input: Omit ): Promise => { const [res, target] = await context.fetch("/multistream/target", { method: "POST", @@ -35,7 +35,7 @@ export const createMultistreamTarget = async ( }; export const getMultistreamTarget = async ( - id: string, + id: string ): Promise => { const uri = `/multistream/target/${id}`; const [res, target] = await context.fetch(uri); @@ -47,7 +47,7 @@ export const getMultistreamTarget = async ( export const patchMultistreamTarget = async ( id: string, - patch: MultistreamTargetPatchPayload, + patch: MultistreamTargetPatchPayload ): Promise => { const [res, body] = await context.fetch(`/multistream/target/${id}`, { method: "PATCH", diff --git a/packages/www/hooks/use-api/endpoints/objectStore.ts b/packages/www/hooks/use-api/endpoints/objectStore.ts index 9c1cdcfdbf..efbbb7087f 100644 --- a/packages/www/hooks/use-api/endpoints/objectStore.ts +++ b/packages/www/hooks/use-api/endpoints/objectStore.ts @@ -9,7 +9,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -20,7 +20,7 @@ export const getObjectStore = async ( order?: string, filters?: Array<{ id: string; value: string }>, limit?: number, - cursor?: string, + cursor?: string ): Promise<[Array | ApiError, string, Response]> => { const f = filters ? JSON.stringify(filters) : undefined; const [res, streams] = await context.fetch( @@ -30,7 +30,7 @@ export const getObjectStore = async ( limit, cursor, filters: f, - })}`, + })}` ); const nextCursor = getCursor(res.headers.get("link")); return [streams, nextCursor, res]; @@ -53,7 +53,7 @@ export const createObjectStore = async (params): Promise => { export const disableObjectStore = async ( id: string, - disabled: boolean, + disabled: boolean ): Promise<[Response, boolean | ApiError]> => { const [res, body] = await context.fetch(`/object-store/${id}`, { method: "PATCH", diff --git a/packages/www/hooks/use-api/endpoints/project.ts b/packages/www/hooks/use-api/endpoints/project.ts index 5cd6187a75..11410a3b22 100644 --- a/packages/www/hooks/use-api/endpoints/project.ts +++ b/packages/www/hooks/use-api/endpoints/project.ts @@ -9,7 +9,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; diff --git a/packages/www/hooks/use-api/endpoints/session.ts b/packages/www/hooks/use-api/endpoints/session.ts index e854670267..9d57eb7a05 100644 --- a/packages/www/hooks/use-api/endpoints/session.ts +++ b/packages/www/hooks/use-api/endpoints/session.ts @@ -10,7 +10,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -21,7 +21,7 @@ export const getStreamSessions = async ( cursor?: string, limit: number = 20, filters?: Array<{ id: string; value: string | object }>, - count?: boolean, + count?: boolean ): Promise<[Array, string, number]> => { const stringifiedFilters = filters ? JSON.stringify(filters) : undefined; const uri = `/session?${qs.stringify({ @@ -46,7 +46,7 @@ export const getSession = async ( cursor?: string, limit: number = 20, filters?: Array<{ id: string; value: string | object }>, - count?: boolean, + count?: boolean ): Promise<[Session, string, number]> => { const stringifiedFilters = filters ? JSON.stringify(filters) : undefined; const uri = `/session/${id}?${qs.stringify({ @@ -71,7 +71,7 @@ export const getStreamSessionsByUserId = async ( limit: number = 20, order?: string, filters?: Array<{ id: string; value: string | object }>, - count?: boolean, + count?: boolean ): Promise<[Array, string, number]> => { const stringifiedFilters = filters ? JSON.stringify(filters) : undefined; const uri = `/session?${qs.stringify({ diff --git a/packages/www/hooks/use-api/endpoints/stream.ts b/packages/www/hooks/use-api/endpoints/stream.ts index 4bff17e660..b661ec7adf 100644 --- a/packages/www/hooks/use-api/endpoints/stream.ts +++ b/packages/www/hooks/use-api/endpoints/stream.ts @@ -15,14 +15,14 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; }; export const getStreamInfo = async ( - id: string, + id: string ): Promise<[Response, StreamInfo | ApiError]> => { let [res, info] = await context.fetch(`/stream/${id}/info`); return [res, info as StreamInfo | ApiError]; @@ -49,7 +49,7 @@ export const getStreams = async ( order?: string; active?: boolean; count?: boolean; - }, + } ): Promise<[Stream[], string, number, number, number, number]> => { const filters = opts?.filters ? JSON.stringify(opts?.filters) : undefined; @@ -64,7 +64,7 @@ export const getStreams = async ( count: opts?.count, streamsonly: 1, projectId, - })}`, + })}` ); const [allStreamRes] = await context.fetch( @@ -76,7 +76,7 @@ export const getStreams = async ( count: true, streamsonly: 1, projectId, - })}`, + })}` ); const [activeStreamRes] = await context.fetch( `/stream?${qs.stringify({ @@ -87,7 +87,7 @@ export const getStreams = async ( count: true, streamsonly: 1, projectId, - })}`, + })}` ); const [unHealtyStreamRes] = await context.fetch( @@ -100,7 +100,7 @@ export const getStreams = async ( count: true, streamsonly: 1, projectId, - })}`, + })}` ); if (res.status !== 200) { @@ -153,7 +153,7 @@ export const getAdminStreams = async ({ nonLivepeerOnly, userId, sessionsonly, - })}`, + })}` ); const nextCursor = getCursor(res.headers.get("link")); return [streams, nextCursor, res]; @@ -161,7 +161,7 @@ export const getAdminStreams = async ({ export const generateJwt = async (playbackId: string): Promise => { const [res] = await context.fetch( - `/access-control/signing-key/jwt/${playbackId}`, + `/access-control/signing-key/jwt/${playbackId}` ); if (res.status !== 200) { throw new Error(JSON.stringify(res.body)); @@ -229,7 +229,7 @@ export const deleteStreams = async (ids: Array): Promise => { export const patchStream = async ( streamId: string, - patch: StreamPatchPayload, + patch: StreamPatchPayload ): Promise => { const url = `/stream/${streamId}?projectId=${projectId}`; const [res, body] = await context.fetch(url, { diff --git a/packages/www/hooks/use-api/endpoints/task.ts b/packages/www/hooks/use-api/endpoints/task.ts index 8b065304d1..3be0938255 100644 --- a/packages/www/hooks/use-api/endpoints/task.ts +++ b/packages/www/hooks/use-api/endpoints/task.ts @@ -9,7 +9,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -24,7 +24,7 @@ export const getTasks = async ( order?: string; active?: boolean; count?: boolean; - }, + } ): Promise<[Array, string, number]> => { const filters = opts?.filters ? JSON.stringify(opts?.filters) : undefined; @@ -36,7 +36,7 @@ export const getTasks = async ( limit: opts?.limit, cursor: opts?.cursor, count: opts?.count, - })}`, + })}` ); if (res.status !== 200) { diff --git a/packages/www/hooks/use-api/endpoints/user.ts b/packages/www/hooks/use-api/endpoints/user.ts index d8f7a1c15d..dc014d8f1e 100644 --- a/packages/www/hooks/use-api/endpoints/user.ts +++ b/packages/www/hooks/use-api/endpoints/user.ts @@ -25,7 +25,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -151,7 +151,7 @@ export const register = async ({ headers: { "content-type": "application/json", }, - }, + } ); if (res.status !== 201) { return body; @@ -249,7 +249,7 @@ export const resetPassword = async (email, resetToken, password) => { export const getUser = async ( userId, - opts = {}, + opts = {} ): Promise<[Response, User | ApiError]> => { let [res, user] = await context.fetch(`/user/${userId}`, opts); if (isDevelopment() && hasStripe && !user.stripeProductId && user.email) { @@ -275,7 +275,7 @@ export const getUsers = async ( limit = 100, cursor?: string, order?: string, - filters?: Array<{ id: string; value: string }>, + filters?: Array<{ id: string; value: string }> ): Promise<[Array | ApiError, string, Response]> => { const f = filters ? JSON.stringify(filters) : undefined; const uri = `/user?${qs.stringify({ limit, cursor, filters: f, order })}`; @@ -288,11 +288,11 @@ export const getUsers = async ( export const getUsage = async ( fromTime: number, toTime: number, - userId?: number, + userId?: number ): Promise<[Response, UsageData | ApiError]> => { let [res, usage] = await context.fetch( `/user/usage?${qs.stringify({ fromTime, toTime, userId })}`, - {}, + {} ); return [res, usage as UsageData | ApiError]; @@ -302,7 +302,7 @@ export const getBillingUsage = async ( fromTime: number, toTime: number, creatorId?: number, - timeStep?: string, + timeStep?: string ): Promise<[Response, BillingUsageData | ApiError]> => { let [res, usage] = await context.fetch( `/data/usage/query?${qs.stringify({ @@ -311,7 +311,7 @@ export const getBillingUsage = async ( creatorId, timeStep, })}`, - {}, + {} ); if (!usage) { @@ -329,7 +329,7 @@ export const getBillingUsage = async ( }; export const getUpcomingInvoice = async ( - stripeCustomerId: string, + stripeCustomerId: string ): Promise<[Response, any | ApiError]> => { let [res, invoice] = await context.fetch(`/user/retrieve-upcoming-invoice`, { method: "POST", @@ -344,7 +344,7 @@ export const getUpcomingInvoice = async ( export const makeUserAdmin = async ( email, - admin, + admin ): Promise<[Response, User | ApiError]> => { const [res, body] = await context.fetch("/user/make-admin", { method: "POST", @@ -365,7 +365,7 @@ export const makeUserAdmin = async ( export const setUserSuspended = async ( userId: string, - payload: SuspendUserPayload, + payload: SuspendUserPayload ): Promise<[Response, ApiError]> => { const [res, body] = await context.fetch(`/user/${userId}/suspended`, { method: "PATCH", @@ -388,7 +388,7 @@ export const setUserSuspended = async ( }; export const createCustomer = async ( - email, + email ): Promise<{ id: string } | ApiError> => { if (!hasStripe) { return; @@ -460,7 +460,7 @@ export const updateSubscription = async ({ }; export const getSubscription = async ( - stripeCustomerSubscriptionId: string, + stripeCustomerSubscriptionId: string ): Promise<[Response, ApiError]> => { let [res, subscription] = await context.fetch(`/user/retrieve-subscription`, { method: "POST", @@ -476,7 +476,7 @@ export const getSubscription = async ( }; export const getInvoices = async ( - stripeCustomerId: string, + stripeCustomerId: string ): Promise<[Response, ApiError]> => { let [res, invoice] = await context.fetch(`/user/retrieve-invoices`, { method: "POST", @@ -492,7 +492,7 @@ export const getInvoices = async ( }; export const getPaymentMethod = async ( - stripePaymentMethodId: string, + stripePaymentMethodId: string ): Promise<[Response, PaymentMethodData | ApiError]> => { let [res, paymentMethod] = await context.fetch( `/user/retrieve-payment-method`, @@ -504,7 +504,7 @@ export const getPaymentMethod = async ( headers: { "content-type": "application/json", }, - }, + } ); return [res, paymentMethod]; }; @@ -524,7 +524,7 @@ export const updateCustomerPaymentMethod = async ({ headers: { "content-type": "application/json", }, - }, + } ); setState((state) => ({ ...state, userRefresh: Date.now() })); diff --git a/packages/www/hooks/use-api/endpoints/version.ts b/packages/www/hooks/use-api/endpoints/version.ts index f620bbb856..610f9a67af 100644 --- a/packages/www/hooks/use-api/endpoints/version.ts +++ b/packages/www/hooks/use-api/endpoints/version.ts @@ -6,7 +6,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; diff --git a/packages/www/hooks/use-api/endpoints/webhook.ts b/packages/www/hooks/use-api/endpoints/webhook.ts index 7cce7ef916..0db3f5a6ba 100644 --- a/packages/www/hooks/use-api/endpoints/webhook.ts +++ b/packages/www/hooks/use-api/endpoints/webhook.ts @@ -10,7 +10,7 @@ let setState: (value: SetStateAction) => void; export const setSharedScope = ( _context: any, - _setState: (value: SetStateAction) => void, + _setState: (value: SetStateAction) => void ) => { context = _context; setState = _setState; @@ -23,7 +23,7 @@ export const getWebhooks = async ( filters?: Array<{ id: string; value: string | object }>, limit?: number, cursor?: string, - count?: boolean, + count?: boolean ): Promise<[Webhook[], string, Response, number]> => { const f = filters ? JSON.stringify(filters) : undefined; const [res, streams] = await context.fetch( @@ -36,7 +36,7 @@ export const getWebhooks = async ( filters: f, count, projectId, - })}`, + })}` ); const nextCursor = getCursor(res.headers.get("link")); const c = res.headers.get("X-Total-Count"); @@ -112,12 +112,12 @@ export const deleteWebhooks = async (ids: Array): Promise => { export const getWebhookLogs = async ( webhookId, - filters = null, + filters = null ): Promise => { const f = filters ? JSON.stringify(filters) : undefined; const [res, logs] = await context.fetch( - `/webhook/${webhookId}/log?${qs.stringify({ filters: f, projectId })}`, + `/webhook/${webhookId}/log?${qs.stringify({ filters: f, projectId })}` ); if (res.status !== 200) { throw logs && typeof logs === "object" diff --git a/packages/www/hooks/use-api/index.tsx b/packages/www/hooks/use-api/index.tsx index 70389837de..8b6823e7a4 100644 --- a/packages/www/hooks/use-api/index.tsx +++ b/packages/www/hooks/use-api/index.tsx @@ -47,7 +47,7 @@ const endpoint = getEndpoint(); const makeContext = ( state: ApiState, - setState: React.Dispatch>, + setState: React.Dispatch> ) => { const context = { ...state, diff --git a/packages/www/hooks/use-debounce.tsx b/packages/www/hooks/use-debounce.tsx index 011f0dadc3..51ac3f9b68 100644 --- a/packages/www/hooks/use-debounce.tsx +++ b/packages/www/hooks/use-debounce.tsx @@ -3,7 +3,7 @@ import { useState, useEffect } from "react"; export default function useDebounce( value: T, delay: number, - onChange?: (v: T) => void, + onChange?: (v: T) => void ) { const [debouncedValue, setDebouncedValue] = useState(value); diff --git a/packages/www/hooks/use-drag.tsx b/packages/www/hooks/use-drag.tsx index 8772bd7fa5..6673caa877 100644 --- a/packages/www/hooks/use-drag.tsx +++ b/packages/www/hooks/use-drag.tsx @@ -17,7 +17,7 @@ function useDrag() { setDragging(false); setClicked(false); }), - [], + [] ); const dragMove = (ev: MouseEvent, cb: (posDif: number) => void) => { diff --git a/packages/www/hooks/use-hubspot.tsx b/packages/www/hooks/use-hubspot.tsx index 59eafdd545..10ac90bb20 100644 --- a/packages/www/hooks/use-hubspot.tsx +++ b/packages/www/hooks/use-hubspot.tsx @@ -9,7 +9,7 @@ const useHubspotForm = ({ portalId, formId }) => { const url = useMemo( () => `https://api.hsforms.com/submissions/v3/integration/submit/${portalId}/${formId}`, - [portalId, formId], + [portalId, formId] ); const fetchData = async () => { diff --git a/packages/www/hooks/use-logged-in.tsx b/packages/www/hooks/use-logged-in.tsx index e46bc80cca..c0f10bf299 100644 --- a/packages/www/hooks/use-logged-in.tsx +++ b/packages/www/hooks/use-logged-in.tsx @@ -23,7 +23,7 @@ export default function useLoggedIn(shouldBeLoggedIn = true) { email: user.email, }); }, - [June], + [June] ); useEffect(() => { diff --git a/packages/www/layouts/assetDetail.tsx b/packages/www/layouts/assetDetail.tsx index b5151983d5..00e4624627 100644 --- a/packages/www/layouts/assetDetail.tsx +++ b/packages/www/layouts/assetDetail.tsx @@ -62,7 +62,7 @@ const AssetDetail = ({ await refetchAsset(); } }, - [asset, patchAsset, refetchAsset], + [asset, patchAsset, refetchAsset] ); useEffect(() => { diff --git a/packages/www/layouts/streamDetail.tsx b/packages/www/layouts/streamDetail.tsx index 929cc8a65c..c003769ff7 100644 --- a/packages/www/layouts/streamDetail.tsx +++ b/packages/www/layouts/streamDetail.tsx @@ -82,7 +82,7 @@ const StreamDetail = ({ if (!stream?.isActive) return null; const activeCond = streamHealth?.conditions.find( - (c) => c.type === "Active", + (c) => c.type === "Active" ); const healthyCond = streamHealth?.healthy; const healthValid = @@ -92,8 +92,8 @@ const StreamDetail = ({ return !healthValid ? StatusVariant.Pending : healthyCond.status - ? StatusVariant.Healthy - : StatusVariant.Unhealthy; + ? StatusVariant.Healthy + : StatusVariant.Unhealthy; }, [stream?.isActive, streamHealth]); if (!user) { diff --git a/packages/www/lib/utils/index.tsx b/packages/www/lib/utils/index.tsx index e055a96fb8..7ecda11942 100644 --- a/packages/www/lib/utils/index.tsx +++ b/packages/www/lib/utils/index.tsx @@ -45,7 +45,7 @@ function getLineHeight(el: HTMLElement) { "style", `margin:0; padding:0;font-family:${ el.style.fontFamily || "inherit" - };font-size:${el.style.fontSize || "inherit"};`, + };font-size:${el.style.fontSize || "inherit"};` ); temp.innerHTML = "A"; @@ -118,7 +118,7 @@ export const shouldStripe = () => { export function formatAmountForDisplay( amount: number, - currency: string, + currency: string ): string { let numberFormat = new Intl.NumberFormat(["en-US"], { style: "currency", @@ -130,7 +130,7 @@ export function formatAmountForDisplay( export function formatAmountForStripe( amount: number, - currency: string, + currency: string ): number { let numberFormat = new Intl.NumberFormat(["en-US"], { style: "currency", @@ -149,7 +149,7 @@ export function formatAmountForStripe( export function formatNumber( val: number, - maximumFractionDigits: number, + maximumFractionDigits: number ): string { let numberFormat = new Intl.NumberFormat(["en-US"], { maximumFractionDigits, @@ -158,10 +158,7 @@ export function formatNumber( } export class HttpError extends Error { - constructor( - public status: number, - public body: any, - ) { + constructor(public status: number, public body: any) { super(HttpError.makeMessage(status, body)); } diff --git a/packages/www/lib/utils/router.ts b/packages/www/lib/utils/router.ts index de8413ce6d..aed3239977 100644 --- a/packages/www/lib/utils/router.ts +++ b/packages/www/lib/utils/router.ts @@ -32,7 +32,7 @@ export const checkIsExternal = (href: string) => { const getHrefWithQuery = ( asPath: string, newQueryParams?: QueryParams, - override = true, + override = true ) => { const uri = new URL(asPath, originURL); @@ -61,7 +61,7 @@ export type TransitionOptions = Parameters["2"]; const makeQuery = ( router: NextRouter, queryParams: QueryParams, - opts?: { replace?: boolean } & TransitionOptions, + opts?: { replace?: boolean } & TransitionOptions ) => { const url = getHrefWithQuery(router.asPath, queryParams); const replace = opts?.replace; diff --git a/packages/www/next.config.js b/packages/www/next.config.js index 1fe6aa8844..f2afdff6e6 100644 --- a/packages/www/next.config.js +++ b/packages/www/next.config.js @@ -91,13 +91,13 @@ let configWithPlugins = withPlugins( ? [require("@next/bundle-analyzer")({ enabled: isAnalyzeEnabled })] : []), ], - config, + config ); if (!isStaticBuild) { configWithPlugins = withSentryConfig( configWithPlugins, - SentryWebpackPluginOptions, + SentryWebpackPluginOptions ); } diff --git a/packages/www/pages/_app.tsx b/packages/www/pages/_app.tsx index c3188474fa..5e3a8b9438 100644 --- a/packages/www/pages/_app.tsx +++ b/packages/www/pages/_app.tsx @@ -63,7 +63,7 @@ const globalStyles = globalCss({ const themes: any = getThemes(); const themeMap = {}; Object.keys(themes).map( - (key, _index) => (themeMap[themes[key].className] = themes[key].className), + (key, _index) => (themeMap[themes[key].className] = themes[key].className) ); const livepeerClient = createReactClient({ diff --git a/packages/www/pages/app/stream/[id].tsx b/packages/www/pages/app/stream/[id].tsx index 169149b1e6..3a018dbb3d 100644 --- a/packages/www/pages/app/stream/[id].tsx +++ b/packages/www/pages/app/stream/[id].tsx @@ -331,7 +331,7 @@ const ID = () => { const getIngestURL = ( stream: Stream, showKey: boolean, - i: number, + i: number ): string => { const key = showKey ? stream.streamKey : ""; return i < ingest.length ? pathJoin(ingest[i].ingest, key) : key || ""; @@ -848,7 +848,7 @@ const ID = () => { sec ( {formatNumber( (stream.sourceSegmentsDuration || 0) / 60, - 2, + 2 )}{" "} min) @@ -856,12 +856,12 @@ const ID = () => { {formatNumber( stream.transcodedSegmentsDuration || 0, - 0, + 0 )}{" "} sec ( {formatNumber( (stream.transcodedSegmentsDuration || 0) / 60, - 2, + 2 )}{" "} min) diff --git a/packages/www/pages/projects/[projectId]/assets/[id]/index.tsx b/packages/www/pages/projects/[projectId]/assets/[id]/index.tsx index b4069b7009..0e7eb533da 100644 --- a/packages/www/pages/projects/[projectId]/assets/[id]/index.tsx +++ b/packages/www/pages/projects/[projectId]/assets/[id]/index.tsx @@ -14,7 +14,7 @@ const AssetDetails = () => { const router = useRouter(); const { getAsset, getTotalViews } = useApi(); const [currentTab, setCurrentTab] = useState<"Overview" | "Event Logs">( - "Overview", + "Overview" ); const [editAssetDialogOpen, setEditAssetDialogOpen] = useState(false); const [embedVideoDialogOpen, setEmbedVideoDialogOpen] = useState(false); @@ -29,7 +29,7 @@ const AssetDetails = () => { { refetchInterval, enabled: Boolean(id), - }, + } ); const { data: totalViews } = useQuery( @@ -38,7 +38,7 @@ const AssetDetails = () => { { refetchInterval, enabled: Boolean(id), - }, + } ); return ( diff --git a/packages/www/pages/projects/[projectId]/developers/webhooks/[id].tsx b/packages/www/pages/projects/[projectId]/developers/webhooks/[id].tsx index 2a4434b8ef..f15385bf47 100644 --- a/packages/www/pages/projects/[projectId]/developers/webhooks/[id].tsx +++ b/packages/www/pages/projects/[projectId]/developers/webhooks/[id].tsx @@ -23,7 +23,7 @@ const WebhookDetail = () => { () => getWebhook(id), { enabled: !!id, - }, + } ); const { data: logs, refetch: refetchLogs } = useQuery( @@ -32,7 +32,7 @@ const WebhookDetail = () => { { enabled: !!id, initialData: [], - }, + } ); const handleLogFilters = async (filters) => { diff --git a/packages/www/pages/projects/[projectId]/index.tsx b/packages/www/pages/projects/[projectId]/index.tsx index ffc662162a..6d0284cf07 100644 --- a/packages/www/pages/projects/[projectId]/index.tsx +++ b/packages/www/pages/projects/[projectId]/index.tsx @@ -31,7 +31,7 @@ const Dashboard = () => { openSnackbar(`Errors: ${res.errors.join(", ")}`); } else { openSnackbar( - `We've sent you a link to verify your email. Please check your inbox at ${user.email}`, + `We've sent you a link to verify your email. Please check your inbox at ${user.email}` ); } }; diff --git a/packages/www/pages/projects/[projectId]/stream-health.tsx b/packages/www/pages/projects/[projectId]/stream-health.tsx index 9845e7bea5..ec1d6a436e 100644 --- a/packages/www/pages/projects/[projectId]/stream-health.tsx +++ b/packages/www/pages/projects/[projectId]/stream-health.tsx @@ -81,7 +81,7 @@ const Health = () => { setInfo(info); } }, - [getStreamInfo], + [getStreamInfo] ); const getIngestRate = useCallback( @@ -104,7 +104,7 @@ const Health = () => { }); } }, - [getStreamInfo], + [getStreamInfo] ); useEffect(() => { diff --git a/packages/www/pages/projects/[projectId]/streams/[id]/index.tsx b/packages/www/pages/projects/[projectId]/streams/[id]/index.tsx index b1a55989ff..bb3e76d265 100644 --- a/packages/www/pages/projects/[projectId]/streams/[id]/index.tsx +++ b/packages/www/pages/projects/[projectId]/streams/[id]/index.tsx @@ -17,7 +17,7 @@ const StreamDetails = () => { const { getHealth } = useAnalyzer(); const { appendProjectId } = useProjectContext(); const [currentTab, setCurrentTab] = useState<"Overview" | "Health">( - "Overview", + "Overview" ); const [embedVideoDialogOpen, setEmbedVideoDialogOpen] = useState(false); @@ -35,7 +35,7 @@ const StreamDetails = () => { } return queryClient.invalidateQueries([id]); }, - [queryClient, id], + [queryClient, id] ); const { data: streamHealth } = useQuery({ diff --git a/packages/www/pages/settings/billing/index.tsx b/packages/www/pages/settings/billing/index.tsx index 0334c6cd55..2a58ca39d6 100644 --- a/packages/www/pages/settings/billing/index.tsx +++ b/packages/www/pages/settings/billing/index.tsx @@ -49,7 +49,7 @@ const Billing = () => { const [upcomingInvoiceTotal, setUpcomingInvoiceTotal] = useState(0); const [upcomingInvoice, setUpcomingInvoice] = useState(null); const [overUsageBill, setOverUsageBill] = useState( - null, + null ); const June = useJune(); @@ -58,7 +58,7 @@ const Billing = () => { const fetcher = useCallback(async () => { if (user?.stripeCustomerPaymentMethodId) { const [_res, paymentMethod] = await getPaymentMethod( - user.stripeCustomerPaymentMethodId, + user.stripeCustomerPaymentMethodId ); return paymentMethod; } @@ -138,8 +138,8 @@ const Billing = () => { units: overusage.TotalUsageMins, total: Number( (overusage.TotalUsageMins * payAsYouGoData.usage[0].price).toFixed( - 2, - ), + 2 + ) ), }, deliveryBill: { @@ -147,7 +147,7 @@ const Billing = () => { total: Number( ( overusage.DeliveryUsageMins * payAsYouGoData.usage[1].price - ).toFixed(2), + ).toFixed(2) ), }, storageBill: { @@ -155,7 +155,7 @@ const Billing = () => { total: Number( ( overusage.StorageUsageMins * payAsYouGoData.usage[2].price - ).toFixed(2), + ).toFixed(2) ), }, }; @@ -171,7 +171,7 @@ const Billing = () => { doGetUsage( subscription?.current_period_start, subscription?.current_period_end, - subscription?.status, + subscription?.status ); }; @@ -222,14 +222,14 @@ const Billing = () => { {subscription && ( {new Date( - subscription.current_period_start * 1000, + subscription.current_period_start * 1000 ).toLocaleDateString("en-US", { month: "short", day: "numeric", })}{" "} to{" "} {new Date( - subscription.current_period_end * 1000, + subscription.current_period_end * 1000 ).toLocaleDateString("en-US", { month: "short", day: "numeric", diff --git a/packages/www/pages/settings/usage/index.tsx b/packages/www/pages/settings/usage/index.tsx index df592e019a..6069951180 100644 --- a/packages/www/pages/settings/usage/index.tsx +++ b/packages/www/pages/settings/usage/index.tsx @@ -98,7 +98,7 @@ const Usage = () => { const doGetBillingUsage = async ( fromTime: any, toTime: any, - status: any, + status: any ) => { fromTime = fromTime * 1000; toTime = toTime * 1000; @@ -127,7 +127,7 @@ const Usage = () => { fromTime, toTime, null, - timestep, + timestep ); if (res2.status == 200 && Array.isArray(usageByDay)) { setUsageData(usageByDay); @@ -142,12 +142,12 @@ const Usage = () => { doGetUsage( subscription?.current_period_start, subscription?.current_period_end, - user.id, + user.id ); doGetBillingUsage( subscription?.current_period_start, subscription?.current_period_end, - subscription?.status, + subscription?.status ); }; @@ -193,14 +193,14 @@ const Usage = () => { {subscription && ( {new Date( - subscription.current_period_start * 1000, + subscription.current_period_start * 1000 ).toLocaleDateString("en-US", { month: "short", day: "numeric", })}{" "} to{" "} {new Date( - subscription.current_period_end * 1000, + subscription.current_period_end * 1000 ).toLocaleDateString("en-US", { month: "short", day: "numeric", diff --git a/packages/www/pages/verify-new-email.tsx b/packages/www/pages/verify-new-email.tsx index 80092ae7d9..181f819033 100644 --- a/packages/www/pages/verify-new-email.tsx +++ b/packages/www/pages/verify-new-email.tsx @@ -77,7 +77,7 @@ const Verify = ({ openSnackbar(`Errors: ${res.errors.join(", ")}`); } else { openSnackbar( - `We've sent you a link to verify your email. Please check your inbox at ${email}`, + `We've sent you a link to verify your email. Please check your inbox at ${email}` ); } }; diff --git a/packages/www/pages/verify.tsx b/packages/www/pages/verify.tsx index 8b8e771ac5..969b5e85b8 100644 --- a/packages/www/pages/verify.tsx +++ b/packages/www/pages/verify.tsx @@ -77,7 +77,7 @@ const Verify = ({ openSnackbar(`Errors: ${res.errors.join(", ")}`); } else { openSnackbar( - `We've sent you a link to verify your email. Please check your inbox at ${email}`, + `We've sent you a link to verify your email. Please check your inbox at ${email}` ); } };