Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: replace deprecated String.prototype.substr() #35421

Merged
merged 5 commits into from Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/next-stats-action/src/add-comment.js
Expand Up @@ -20,7 +20,7 @@ const round = (num, places) => {

const shortenLabel = (itemKey) =>
itemKey.length > 24
? `${itemKey.substr(0, 12)}..${itemKey.substr(itemKey.length - 12, 12)}`
? `${itemKey.slice(0, 12)}..${itemKey.slice(-12)}`
: itemKey

const twoMB = 2 * 1024 * 1024
Expand Down
Expand Up @@ -74,8 +74,7 @@ module.exports = async function collectStats(
const responseText = (await res.text()).trim()

let fileName = pathname === '/' ? '/index' : pathname
if (fileName.endsWith('/'))
fileName = fileName.substr(0, fileName.length - 1)
if (fileName.endsWith('/')) fileName = fileName.slice(0, -1)
logger(
`Writing file to ${path.join(fetchedPagesDir, `${fileName}.html`)}`
)
Expand Down
2 changes: 1 addition & 1 deletion examples/with-magic/pages/api/login.js
Expand Up @@ -3,7 +3,7 @@ import { setLoginSession } from '../../lib/auth'

export default async function login(req, res) {
try {
const didToken = req.headers.authorization.substr(7)
const didToken = req.headers.authorization.slice(7)
const metadata = await magic.users.getMetadataByToken(didToken)
const session = { ...metadata }

Expand Down
4 changes: 2 additions & 2 deletions packages/next-codemod/transforms/cra-to-next.ts
Expand Up @@ -218,7 +218,7 @@ class CraTransform {
return `${reactName}={\`${value.replace(
/%([a-zA-Z0-9_]{0,})%/g,
(subStr) => {
return `\${process.env.${subStr.substr(1, subStr.length - 2)}}`
return `\${process.env.${subStr.slice(1, -1)}}`
}
)}\`}`
}
Expand Down Expand Up @@ -293,7 +293,7 @@ class CraTransform {
: [...globalCssContext.cssImports]
.map((file) => {
if (!this.isCra) {
file = file.startsWith('/') ? file.substr(1) : file
file = file.startsWith('/') ? file.slice(1) : file
}

return `import '${
Expand Down
Expand Up @@ -13,7 +13,7 @@ const camelCase = (value: string): string => {
const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) =>
chr ? chr.toUpperCase() : ''
)
return val.substr(0, 1).toUpperCase() + val.substr(1)
return val.slice(0, 1).toUpperCase() + val.slice(1)
}

const isValidIdentifier = (value: string): boolean =>
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/index.ts
Expand Up @@ -1659,7 +1659,7 @@ export default async function build(
// strip leading / and then recurse number of nested dirs
// to place from base folder
originPage
.substr(1)
.slice(1)
.split('/')
.map(() => '..')
.join('/')
Expand Down Expand Up @@ -1709,7 +1709,7 @@ export default async function build(
for (const locale of i18n.locales) {
const curPath = `/${locale}${page === '/' ? '' : page}`
const localeExt = page === '/' ? path.extname(file) : ''
const relativeDestNoPages = relativeDest.substr(
const relativeDestNoPages = relativeDest.slice(
'pages/'.length
)

Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/output/store.ts
Expand Up @@ -81,7 +81,7 @@ store.subscribe((state) => {
const matches = cleanError.match(/\[.*\]=/)
if (matches) {
for (const match of matches) {
const prop = (match.split(']').shift() || '').substr(1)
const prop = (match.split(']').shift() || '').slice(1)
console.log(
`AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt`
)
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/utils.ts
Expand Up @@ -723,7 +723,7 @@ export async function buildStaticPaths(
let cleanedEntry = entry

if (localePathResult.detectedLocale) {
cleanedEntry = entry.substr(localePathResult.detectedLocale.length + 1)
cleanedEntry = entry.slice(localePathResult.detectedLocale.length + 1)
} else if (defaultLocale) {
entry = `/${defaultLocale}${entry}`
}
Expand Down
Expand Up @@ -55,7 +55,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
i18n,
reactRoot,
}: ServerlessLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
typeof this.query === 'string' ? parse(this.query.slice(1)) : this.query

const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
Expand Down
Expand Up @@ -274,9 +274,9 @@ export function getUtils({
}

pathname =
pathname.substr(0, paramIdx) +
pathname.slice(0, paramIdx) +
(paramValue || '') +
pathname.substr(paramIdx + builtParam.length)
pathname.slice(paramIdx + builtParam.length)
}
}

Expand Down
Expand Up @@ -44,8 +44,8 @@ export function tryParsePattern(pattern: string): Pattern | undefined {
return indexOfStar === -1
? undefined
: {
prefix: pattern.substr(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1),
prefix: pattern.slice(0, indexOfStar),
suffix: pattern.slice(indexOfStar + 1),
}
}

Expand Down
Expand Up @@ -532,7 +532,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance {
) {
requestPath = (
resContext.descriptionFileRoot +
request.substr(getPkgName(request)?.length || 0) +
request.slice(getPkgName(request)?.length || 0) +
nodePath.sep +
'package.json'
)
Expand All @@ -546,7 +546,7 @@ export class TraceEntryPointsPlugin implements webpack5.WebpackPluginInstance {
(separatorIndex = requestPath.lastIndexOf('/')) >
rootSeparatorIndex
) {
requestPath = requestPath.substr(0, separatorIndex)
requestPath = requestPath.slice(0, separatorIndex)
const curPackageJsonPath = `${requestPath}/package.json`
if (await job.isFile(curPackageJsonPath)) {
await job.emitFile(
Expand Down
9 changes: 5 additions & 4 deletions packages/next/client/dev/amp-dev.js
Expand Up @@ -48,12 +48,13 @@ async function tryApplyUpdates() {
).some((mod) => {
return (
mod.indexOf(
`pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}`
`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`
) !== -1 ||
mod.indexOf(
`pages${
curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`
}`.replace(/\//g, '\\')
`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`.replace(
/\//g,
'\\'
)
) !== -1
)
})
Expand Down
2 changes: 1 addition & 1 deletion packages/next/export/index.ts
Expand Up @@ -646,7 +646,7 @@ export default async function exportApp(
// strip leading / and then recurse number of nested dirs
// to place from base folder
pageName
.substr(1)
.slice(1)
.split('/')
.map(() => '..')
.join('/')
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/base-server.ts
Expand Up @@ -1143,7 +1143,7 @@ export default abstract class Server {
// ensure correct status is set when visiting a status page
// directly e.g. /500
if (STATIC_STATUS_PAGES.includes(pathname)) {
res.statusCode = parseInt(pathname.substr(1), 10)
res.statusCode = parseInt(pathname.slice(1), 10)
}

// static pages can only respond to GET/HEAD
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/dev/hot-reloader.ts
Expand Up @@ -733,7 +733,7 @@ export default class HotReloader {
this.send({
event: 'serverOnlyChanges',
pages: serverOnlyChanges.map((pg) =>
denormalizePagePath(pg.substr('pages'.length))
denormalizePagePath(pg.slice('pages'.length))
),
})
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next/server/router.ts
Expand Up @@ -56,7 +56,7 @@ export function replaceBasePath(pathname: string, basePath: string): string {
// and doesn't contain extra chars e.g. basePath /docs
// should replace for /docs, /docs/, /docs/a but not /docsss
if (hasBasePath(pathname, basePath)) {
pathname = pathname.substr(basePath.length)
pathname = pathname.slice(basePath.length)
if (!pathname.startsWith('/')) pathname = `/${pathname}`
}
return pathname
Expand Down
8 changes: 4 additions & 4 deletions packages/next/shared/lib/router/router.ts
Expand Up @@ -121,7 +121,7 @@ function addPathPrefix(path: string, prefix?: string) {

return (
normalizePathTrailingSlash(`${prefix}${pathname}`) +
path.substr(pathname.length)
path.slice(pathname.length)
)
}

Expand Down Expand Up @@ -177,7 +177,7 @@ export function delLocale(path: string, locale?: string) {
(pathLower.startsWith('/' + localeLower + '/') ||
pathLower === '/' + localeLower)
? (pathname.length === locale.length + 1 ? '/' : '') +
path.substr(locale.length + 1)
path.slice(locale.length + 1)
: path
}
return path
Expand Down Expand Up @@ -320,7 +320,7 @@ export function resolveHref(
// invalid and will never match a Next.js page/file
const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//)
const urlAsStringNoProto = urlProtoMatch
? urlAsString.substr(urlProtoMatch[0].length)
? urlAsString.slice(urlProtoMatch[0].length)
: urlAsString

const urlParts = urlAsStringNoProto.split('?')
Expand Down Expand Up @@ -751,7 +751,7 @@ export default class Router implements BaseRouter {
if (typeof window !== 'undefined') {
// make sure "as" doesn't start with double slashes or else it can
// throw an error as it's considered invalid
if (as.substr(0, 2) !== '//') {
if (!as.startsWith('//')) {
// in order for `e.state` to work on the `onpopstate` event
// we have to register the initial route upon initialization
const options: TransitionOptions = { locale }
Expand Down
2 changes: 1 addition & 1 deletion packages/next/shared/lib/router/utils/format-url.ts
Expand Up @@ -51,7 +51,7 @@ export function formatUrl(urlObj: UrlObject) {

let search = urlObj.search || (query && `?${query}`) || ''

if (protocol && protocol.substr(-1) !== ':') protocol += ':'
if (protocol && !protocol.endsWith(':')) protocol += ':'

if (
urlObj.slashes ||
Expand Down
Expand Up @@ -109,7 +109,7 @@ export function compileNonPath(value: string, params: Params): string {

// the value needs to start with a forward-slash to be compiled
// correctly
return compile(`/${value}`, { validate: false })(params).substr(1)
return compile(`/${value}`, { validate: false })(params).slice(1)
}

export function prepareDestination(args: {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/shared/lib/router/utils/route-regex.ts
Expand Up @@ -73,7 +73,7 @@ export function getParametrizedRoute(route: string) {
if (cleanedKey.length === 0 || cleanedKey.length > 30) {
invalidKey = true
}
if (!isNaN(parseInt(cleanedKey.substr(0, 1)))) {
if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) {
invalidKey = true
}

Expand Down
6 changes: 3 additions & 3 deletions test/integration/api-support/test/index.test.js
Expand Up @@ -50,7 +50,7 @@ function runTests(dev = false) {
expect(res2.headers.get('transfer-encoding')).toBe(null)

if (dev) {
expect(stderr.substr(stderrIdx)).toContain(
expect(stderr.slice(stderrIdx)).toContain(
'A body was attempted to be set with a 204 statusCode'
)
}
Expand Down Expand Up @@ -509,7 +509,7 @@ function runTests(dev = false) {
it('should not show warning when the API resolves and the response is piped', async () => {
const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length
await fetchViaHTTP(appPort, `/api/test-res-pipe`, { port: appPort })
expect(stderr.substr(startIdx)).not.toContain(
expect(stderr.slice(startIdx)).not.toContain(
`API resolved without sending a response for /api/test-res-pipe`
)
})
Expand All @@ -527,7 +527,7 @@ function runTests(dev = false) {
const startIdx = stderr.length > 0 ? stderr.length - 1 : stderr.length
const apiURL = '/api/external-resolver'
const req = await fetchViaHTTP(appPort, apiURL)
expect(stderr.substr(startIdx)).not.toContain(
expect(stderr.slice(startIdx)).not.toContain(
`API resolved without sending a response for ${apiURL}`
)
expect(await req.text()).toBe('hello world')
Expand Down
4 changes: 2 additions & 2 deletions test/integration/export-serverless/test/browser.js
Expand Up @@ -18,7 +18,7 @@ export default function (context) {
.elementByCss('#about-via-link')
.getAttribute('href')

expect(link.substr(link.length - 1)).toBe('/')
expect(link.slice(-1)).toBe('/')
})

it('should not add trailing slash on Link when disabled', async () => {
Expand All @@ -27,7 +27,7 @@ export default function (context) {
.elementByCss('#about-via-link')
.getAttribute('href')

expect(link.substr(link.length - 1)).not.toBe('/')
expect(link.slice(-1)).not.toBe('/')
})

it('should do navigations via Link', async () => {
Expand Down
4 changes: 2 additions & 2 deletions test/integration/export/test/browser.js
Expand Up @@ -18,7 +18,7 @@ export default function (context) {
.elementByCss('#about-via-link')
.getAttribute('href')

expect(link.substr(link.length - 1)).toBe('/')
expect(link.slice(-1)).toBe('/')
})

it('should not add any slash on hash Link', async () => {
Expand Down Expand Up @@ -52,7 +52,7 @@ export default function (context) {
.elementByCss('#about-via-link')
.getAttribute('href')

expect(link.substr(link.length - 1)).not.toBe('/')
expect(link.slice(-1)).not.toBe('/')
})

it('should do navigations via Link', async () => {
Expand Down
14 changes: 7 additions & 7 deletions test/integration/server-side-dev-errors/test/index.test.js
Expand Up @@ -49,7 +49,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/gsp')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/gsp.js') &&
err.includes('6:2') &&
Expand Down Expand Up @@ -81,7 +81,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/gssp')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/gssp.js') &&
err.includes('6:2') &&
Expand Down Expand Up @@ -113,7 +113,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/blog/first')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/blog/[slug].js') &&
err.includes('6:2') &&
Expand Down Expand Up @@ -145,7 +145,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/api/hello')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/api/hello.js') &&
err.includes('2:2') &&
Expand Down Expand Up @@ -177,7 +177,7 @@ describe('server-side dev errors', () => {
const browser = await webdriver(appPort, '/api/blog/first')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/api/blog/[slug].js') &&
err.includes('2:2') &&
Expand All @@ -202,7 +202,7 @@ describe('server-side dev errors', () => {
await webdriver(appPort, '/uncaught-rejection')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/uncaught-rejection.js') &&
err.includes('7:19') &&
Expand All @@ -218,7 +218,7 @@ describe('server-side dev errors', () => {
await webdriver(appPort, '/uncaught-exception')

await check(async () => {
const err = stderr.substr(stderrIdx)
const err = stderr.slice(stderrIdx)

return err.includes('pages/uncaught-exception.js') &&
err.includes('7:10') &&
Expand Down
2 changes: 1 addition & 1 deletion test/lib/next-modes/next-start.ts
Expand Up @@ -142,7 +142,7 @@ export class NextStartInstance extends NextInstance {
this.childProcess = undefined
resolve({
exitCode: signal || code,
cliOutput: this.cliOutput.substr(curOutput),
cliOutput: this.cliOutput.slice(curOutput),
})
})
})
Expand Down