wrangler 0.0.0-e61907d → 0.0.0-eebdb6c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +36 -2
  3. package/import_meta_url.js +3 -0
  4. package/package.json +59 -19
  5. package/pages/functions/buildWorker.ts +57 -0
  6. package/pages/functions/filepath-routing.test.ts +32 -0
  7. package/pages/functions/filepath-routing.ts +225 -0
  8. package/pages/functions/identifiers.ts +78 -0
  9. package/pages/functions/routes.ts +158 -0
  10. package/pages/functions/template-worker.ts +135 -0
  11. package/src/__tests__/clipboardy-mock.js +4 -0
  12. package/src/__tests__/index.test.ts +287 -0
  13. package/src/__tests__/jest.setup.ts +22 -0
  14. package/src/__tests__/kv.test.ts +1098 -0
  15. package/src/__tests__/mock-cfetch.ts +171 -0
  16. package/src/__tests__/mock-dialogs.ts +65 -0
  17. package/src/__tests__/run-in-tmp.ts +19 -0
  18. package/src/__tests__/run-wrangler.ts +32 -0
  19. package/src/api/form_data.ts +131 -0
  20. package/src/api/inspect.ts +430 -0
  21. package/src/api/preview.ts +128 -0
  22. package/src/api/worker.ts +155 -0
  23. package/src/cfetch/index.ts +103 -0
  24. package/src/cfetch/internal.ts +69 -0
  25. package/src/cli.ts +9 -0
  26. package/src/config.ts +131 -0
  27. package/src/dev.tsx +879 -0
  28. package/src/dialogs.tsx +77 -0
  29. package/src/index.tsx +1904 -0
  30. package/src/kv.tsx +267 -0
  31. package/src/module-collection.ts +64 -0
  32. package/src/pages.tsx +921 -0
  33. package/src/proxy.ts +103 -0
  34. package/src/publish.ts +350 -0
  35. package/src/sites.tsx +114 -0
  36. package/src/tail.tsx +73 -0
  37. package/src/user.tsx +1022 -0
  38. package/wrangler-dist/{index_node.js → cli.js} +49951 -28396
  39. package/wrangler-dist/cli.js.map +7 -0
  40. package/wrangler-dist/index_node.js.map +0 -7
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ ## 🤠 wrangler
2
+
3
+ `wrangler` is a command line tool for building [Cloudflare Workers](https://workers.cloudflare.com/).
4
+
5
+ [(Read the full stack week launch blog post.)](https://blog.cloudflare.com/wrangler-v2-beta/)
6
+
7
+ **DISCLAIMER**: This is a work in progress, and is NOT recommended for use in production. We are opening this preview for feedback from the community, and to openly share our [roadmap](https://github.com/cloudflare/wrangler2/issues/12) for the future. As such, expect APIs and documentation to change before the end of the preview.
8
+
9
+ Further, we will NOT do a general release until we are both feature complete, and have a full backward compatibility and incremental migration plan in place. For more details, follow the [parent roadmap issue](https://github.com/cloudflare/wrangler2/issues/12).
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ # Make a javascript file
15
+ $ echo "export default { fetch() { return new Response('hello world') } }" > index.js
16
+ # try it out
17
+ $ npx wrangler@beta dev index.js
18
+ # and then publish it
19
+ $ npx wrangler@beta publish index.js --name my-worker
20
+ # visit https://my-worker.<your workers subdomain>.workers.dev
21
+ ```
22
+
23
+ ## Installation:
24
+
25
+ ```bash
26
+ $ npm install wrangler@beta
27
+ ```
28
+
29
+ ## Commands
30
+
31
+ ### `wrangler init [name]`
32
+
33
+ Creates a `wrangler.toml` configuration file. For more details on the configuration keys and values, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration).
34
+
35
+ ### `wrangler dev [script]`
36
+
37
+ Start a local development server, with live reloading and devtools.
38
+
39
+ ### `wrangler publish [script] --name [name]`
40
+
41
+ Publish the given script to the worldwide Cloudflare network.
42
+
43
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/commands).
44
+
45
+ ### `wrangler pages dev [directory] [-- command]`
46
+
47
+ Either serves a static build asset directory, or proxies itself in front of a command.
48
+
49
+ Builds and runs functions from a `./functions` directory or uses a `_worker.js` file inside the static build asset directory.
50
+
51
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/pages/platform/functions#develop-and-preview-locally) or run `wrangler pages dev --help`.
package/bin/wrangler.js CHANGED
@@ -1,2 +1,36 @@
1
- #!/usr/bin/env node --no-warnings
2
- require("../wrangler-dist/index_node.js");
1
+ #!/usr/bin/env node
2
+ const { spawn } = require("child_process");
3
+ const { join } = require("path");
4
+ const semiver = require("semiver");
5
+
6
+ const MIN_NODE_VERSION = "16.7.0";
7
+
8
+ async function main() {
9
+ if (semiver(process.versions.node, MIN_NODE_VERSION) < 0) {
10
+ // Note Volta and nvm are also recommended in the official docs:
11
+ // https://developers.cloudflare.com/workers/get-started/guide#2-install-the-workers-cli
12
+ console.error(
13
+ `Wrangler requires at least Node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}.
14
+ You should use the latest Node.js version if possible, as Cloudflare Workers use a very up-to-date version of V8.
15
+ Consider using a Node.js version manager such as https://volta.sh/ or https://github.com/nvm-sh/nvm.`
16
+ );
17
+ process.exitCode = 1;
18
+ return;
19
+ }
20
+
21
+ spawn(
22
+ process.execPath,
23
+ [
24
+ "--no-warnings",
25
+ "--experimental-vm-modules",
26
+ ...process.execArgv,
27
+ join(__dirname, "../wrangler-dist/cli.js"),
28
+ ...process.argv.slice(2),
29
+ ],
30
+ { stdio: "inherit" }
31
+ ).on("exit", (code) =>
32
+ process.exit(code === undefined || code === null ? 0 : code)
33
+ );
34
+ }
35
+
36
+ void main();
@@ -0,0 +1,3 @@
1
+ // as per https://github.com/evanw/esbuild/issues/1492
2
+ // to make some libs work
3
+ export const import_meta_url = require("url").pathToFileURL(__filename);
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-e61907d",
3
+ "version": "0.0.0-eebdb6c",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
- "bin": "./bin/wrangler.js",
6
+ "bin": {
7
+ "wrangler": "./bin/wrangler.js",
8
+ "wrangler2": "./bin/wrangler.js"
9
+ },
7
10
  "license": "MIT OR Apache-2.0",
8
11
  "bugs": {
9
12
  "url": "https://github.com/cloudflare/wrangler/issues"
@@ -33,52 +36,89 @@
33
36
  "cli"
34
37
  ],
35
38
  "dependencies": {
36
- "esbuild": "^0.13.12",
37
- "miniflare": "^1.4.1",
38
- "yargs": "^17.2.1"
39
+ "esbuild": "0.14.1",
40
+ "miniflare": "2.0.0-rc.5",
41
+ "path-to-regexp": "^6.2.0",
42
+ "semiver": "^1.1.0"
39
43
  },
40
44
  "optionalDependencies": {
41
45
  "fsevents": "~2.3.2"
42
46
  },
43
47
  "devDependencies": {
48
+ "@babel/types": "^7.16.0",
44
49
  "@iarna/toml": "^2.2.5",
45
- "@types/cloudflare": "^2.7.6",
46
- "@types/react": "^17.0.34",
50
+ "@types/mime": "^2.0.3",
51
+ "@types/estree": "^0.0.50",
52
+ "@types/react": "^17.0.37",
53
+ "@types/serve-static": "^1.13.10",
47
54
  "@types/signal-exit": "^3.0.1",
48
- "@types/ws": "^8.2.0",
49
- "@types/yargs": "^17.0.5",
55
+ "@types/ws": "^8.2.1",
56
+ "@types/yargs": "^17.0.7",
57
+ "acorn": "^8.6.0",
58
+ "acorn-walk": "^8.2.0",
59
+ "chokidar": "^3.5.2",
50
60
  "clipboardy": "^3.0.0",
51
- "cloudflare": "^2.9.1",
52
61
  "command-exists": "^1.2.9",
62
+ "execa": "^6.0.0",
63
+ "faye-websocket": "^0.11.4",
53
64
  "finalhandler": "^1.1.2",
54
65
  "find-up": "^6.2.0",
55
66
  "formdata-node": "^4.3.1",
56
- "http-proxy": "^1.18.1",
57
67
  "ink": "^3.2.0",
68
+ "ink-select-input": "^4.2.1",
58
69
  "ink-table": "^3.0.0",
59
- "ink-text-input": "^4.0.1",
60
- "node-fetch": "github:tekwiz/node-fetch#fix/redirect-with-empty-chunked-transfer-encoding",
70
+ "ink-text-input": "^4.0.2",
71
+ "mime": "^3.0.0",
72
+ "node-fetch": "^3.1.0",
61
73
  "open": "^8.4.0",
62
74
  "react": "^17.0.2",
75
+ "react-error-boundary": "^3.1.4",
63
76
  "serve-static": "^1.14.1",
64
- "signal-exit": "^3.0.5",
77
+ "signal-exit": "^3.0.6",
65
78
  "tmp-promise": "^3.0.3",
66
- "ws": "^8.2.3"
79
+ "undici": "^4.11.1",
80
+ "ws": "^8.3.0",
81
+ "yargs": "^17.3.0"
67
82
  },
68
83
  "files": [
84
+ "src",
69
85
  "bin",
86
+ "pages",
70
87
  "miniflare-config-stubs",
71
88
  "wrangler-dist",
72
89
  "static-asset-facade.js",
73
- "vendor"
90
+ "vendor",
91
+ "import_meta_url.js"
74
92
  ],
75
93
  "scripts": {
76
94
  "clean": "rm -rf wrangler-dist",
77
95
  "bundle": "node -r esbuild-register scripts/bundle.ts",
78
96
  "build": "npm run clean && npm run bundle",
79
- "start": "npm run bundle && ./bin/wrangler.js"
97
+ "start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
98
+ "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
80
99
  },
81
100
  "engines": {
82
- "node": ">=16.0.0"
101
+ "node": ">=16.7.0"
102
+ },
103
+ "jest": {
104
+ "restoreMocks": true,
105
+ "testRegex": ".*.(test|spec)\\.[jt]sx?$",
106
+ "transformIgnorePatterns": [
107
+ "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
108
+ ],
109
+ "moduleNameMapper": {
110
+ "clipboardy": "<rootDir>/src/__tests__/clipboardy-mock.js"
111
+ },
112
+ "transform": {
113
+ "^.+\\.c?(t|j)sx?$": [
114
+ "esbuild-jest",
115
+ {
116
+ "sourcemap": true
117
+ }
118
+ ]
119
+ },
120
+ "setupFilesAfterEnv": [
121
+ "<rootDir>/src/__tests__/jest.setup.ts"
122
+ ]
83
123
  }
84
- }
124
+ }
@@ -0,0 +1,57 @@
1
+ import path from "path";
2
+ import { build } from "esbuild";
3
+
4
+ type Options = {
5
+ routesModule: string;
6
+ outfile: string;
7
+ minify?: boolean;
8
+ sourcemap?: boolean;
9
+ watch?: boolean;
10
+ onEnd?: () => void;
11
+ };
12
+
13
+ export function buildWorker({
14
+ routesModule,
15
+ outfile = "bundle.js",
16
+ minify = false,
17
+ sourcemap = false,
18
+ watch = false,
19
+ onEnd = () => {},
20
+ }: Options) {
21
+ return build({
22
+ entryPoints: [
23
+ path.resolve(__dirname, "../pages/functions/template-worker.ts"),
24
+ ],
25
+ inject: [routesModule],
26
+ bundle: true,
27
+ format: "esm",
28
+ target: "esnext",
29
+ outfile,
30
+ minify,
31
+ sourcemap,
32
+ watch,
33
+ allowOverwrite: true,
34
+ plugins: [
35
+ {
36
+ name: "wrangler notifier and monitor",
37
+ setup(pluginBuild) {
38
+ pluginBuild.onEnd((result) => {
39
+ if (result.errors.length > 0) {
40
+ console.error(
41
+ `${result.errors.length} error(s) and ${result.warnings.length} warning(s) when compiling Worker.`
42
+ );
43
+ } else if (result.warnings.length > 0) {
44
+ console.warn(
45
+ `${result.warnings.length} warning(s) when compiling Worker.`
46
+ );
47
+ onEnd();
48
+ } else {
49
+ console.log("Compiled Worker successfully.");
50
+ onEnd();
51
+ }
52
+ });
53
+ },
54
+ },
55
+ ],
56
+ });
57
+ }
@@ -0,0 +1,32 @@
1
+ import { compareRoutes } from "./filepath-routing";
2
+
3
+ describe("compareRoutes()", () => {
4
+ test("routes with fewer segments come after those with more segments", () => {
5
+ expect(compareRoutes("/foo", "/foo/bar")).toBe(1);
6
+ });
7
+
8
+ test("routes with wildcard segments come after those without", () => {
9
+ expect(compareRoutes("/:foo*", "/foo")).toBe(1);
10
+ expect(compareRoutes("/:foo*", "/:foo")).toBe(1);
11
+ });
12
+
13
+ test("routes with dynamic segments come after those without", () => {
14
+ expect(compareRoutes("/:foo", "/foo")).toBe(1);
15
+ });
16
+
17
+ test("routes with dynamic segments occuring earlier come after those with dynamic segments in later positions", () => {
18
+ expect(compareRoutes("/foo/:id/bar", "/foo/bar/:id")).toBe(1);
19
+ });
20
+
21
+ test("routes with no HTTP method come after those specifying a method", () => {
22
+ expect(compareRoutes("/foo", "GET /foo")).toBe(1);
23
+ });
24
+
25
+ test("two equal routes are sorted according to their original position in the list", () => {
26
+ expect(compareRoutes("GET /foo", "GET /foo")).toBe(0);
27
+ });
28
+
29
+ test("it returns -1 if the first argument should appear first in the list", () => {
30
+ expect(compareRoutes("GET /foo", "/foo")).toBe(-1);
31
+ });
32
+ });
@@ -0,0 +1,225 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+
3
+ import path from "path";
4
+ import fs from "fs/promises";
5
+ import { transform } from "esbuild";
6
+ import * as acorn from "acorn";
7
+ import * as acornWalk from "acorn-walk";
8
+ import type { Config } from "./routes";
9
+ import type { Identifier } from "estree";
10
+ import type { ExportNamedDeclaration } from "@babel/types";
11
+
12
+ type Arguments = {
13
+ baseDir: string;
14
+ baseURL: string;
15
+ };
16
+
17
+ export async function generateConfigFromFileTree({
18
+ baseDir,
19
+ baseURL,
20
+ }: Arguments) {
21
+ let routeEntries: [
22
+ string,
23
+ { [key in "module" | "middleware"]?: string[] }
24
+ ][] = [] as any;
25
+
26
+ if (!baseURL.startsWith("/")) {
27
+ baseURL = `/${baseURL}`;
28
+ }
29
+
30
+ if (baseURL.endsWith("/")) {
31
+ baseURL = baseURL.slice(0, -1);
32
+ }
33
+
34
+ await forEachFile(baseDir, async (filepath) => {
35
+ const ext = path.extname(filepath);
36
+ if (/\.(mjs|js|ts)/.test(ext)) {
37
+ // transform the code to ensure we're working with vanilla JS + ESM
38
+ const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
39
+ loader: ext === ".ts" ? "ts" : "js",
40
+ });
41
+
42
+ // parse each file into an AST and search for module exports that match "onRequest" and friends
43
+ const ast = acorn.parse(code, {
44
+ ecmaVersion: "latest",
45
+ sourceType: "module",
46
+ });
47
+ acornWalk.simple(ast, {
48
+ ExportNamedDeclaration(_node) {
49
+ const node: ExportNamedDeclaration = _node as any;
50
+
51
+ // this is an array because multiple things can be exported from a single statement
52
+ // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
53
+ const exportNames: string[] = [];
54
+
55
+ if (node.declaration) {
56
+ const declaration = node.declaration;
57
+
58
+ // `export async function onRequest() {...}`
59
+ if (declaration.type === "FunctionDeclaration") {
60
+ exportNames.push(declaration.id.name);
61
+ }
62
+
63
+ // `export const onRequestGet = () => {}, onRequestPost = () => {}`
64
+ if (declaration.type === "VariableDeclaration") {
65
+ exportNames.push(
66
+ ...declaration.declarations.map(
67
+ (variableDeclarator) =>
68
+ (variableDeclarator.id as unknown as Identifier).name
69
+ )
70
+ );
71
+ }
72
+ }
73
+
74
+ // `export {foo, bar}`
75
+ if (node.specifiers.length) {
76
+ exportNames.push(
77
+ ...node.specifiers.map(
78
+ (exportSpecifier) =>
79
+ (exportSpecifier.exported as unknown as Identifier).name
80
+ )
81
+ );
82
+ }
83
+
84
+ for (const exportName of exportNames) {
85
+ const [match, method] =
86
+ exportName.match(
87
+ /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
88
+ ) ?? [];
89
+
90
+ if (match) {
91
+ const basename = path.basename(filepath).slice(0, -ext.length);
92
+
93
+ const isIndexFile = basename === "index";
94
+ // TODO: deprecate _middleware_ in favor of _middleware
95
+ const isMiddlewareFile =
96
+ basename === "_middleware" || basename === "_middleware_";
97
+
98
+ let routePath = path
99
+ .relative(baseDir, filepath)
100
+ .slice(0, -ext.length);
101
+
102
+ if (isIndexFile || isMiddlewareFile) {
103
+ routePath = path.dirname(routePath);
104
+ }
105
+
106
+ if (routePath === ".") {
107
+ routePath = "";
108
+ }
109
+
110
+ routePath = `${baseURL}/${routePath}`;
111
+
112
+ routePath = routePath.replace(/\[\[(.+)]]/g, ":$1*"); // transform [[id]] => :id*
113
+ routePath = routePath.replace(/\[(.+)]/g, ":$1"); // transform [id] => :id
114
+
115
+ if (method) {
116
+ routePath = `${method.toUpperCase()} ${routePath}`;
117
+ }
118
+
119
+ routeEntries.push([
120
+ routePath,
121
+ {
122
+ [isMiddlewareFile ? "middleware" : "module"]: [
123
+ `${path.relative(baseDir, filepath)}:${exportName}`,
124
+ ],
125
+ },
126
+ ]);
127
+ }
128
+ }
129
+ },
130
+ });
131
+ }
132
+ });
133
+
134
+ // Combine together any routes (index routes) which contain both a module and a middleware
135
+ routeEntries = routeEntries.reduce(
136
+ (acc: typeof routeEntries, [routePath, routeHandler]) => {
137
+ const existingRouteEntry = acc.find(
138
+ (routeEntry) => routeEntry[0] === routePath
139
+ );
140
+ if (existingRouteEntry !== undefined) {
141
+ existingRouteEntry[1] = {
142
+ ...existingRouteEntry[1],
143
+ ...routeHandler,
144
+ };
145
+ } else {
146
+ acc.push([routePath, routeHandler]);
147
+ }
148
+ return acc;
149
+ },
150
+ []
151
+ );
152
+
153
+ routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB));
154
+
155
+ return { routes: Object.fromEntries(routeEntries) } as Config;
156
+ }
157
+
158
+ // Ensure routes are produced in order of precedence so that
159
+ // more specific routes aren't occluded from matching due to
160
+ // less specific routes appearing first in the route list.
161
+ export function compareRoutes(a: string, b: string) {
162
+ function parseRoutePath(routePath: string) {
163
+ let [method, segmentedPath] = routePath.split(" ");
164
+ if (!segmentedPath) {
165
+ segmentedPath = method;
166
+ method = null;
167
+ }
168
+
169
+ const segments = segmentedPath.slice(1).split("/");
170
+ return [method, segments];
171
+ }
172
+
173
+ const [methodA, segmentsA] = parseRoutePath(a);
174
+ const [methodB, segmentsB] = parseRoutePath(b);
175
+
176
+ // sort routes with fewer segments after those with more segments
177
+ if (segmentsA.length !== segmentsB.length) {
178
+ return segmentsB.length - segmentsA.length;
179
+ }
180
+
181
+ for (let i = 0; i < segmentsA.length; i++) {
182
+ const isWildcardA = segmentsA[i].includes("*");
183
+ const isWildcardB = segmentsB[i].includes("*");
184
+ const isParamA = segmentsA[i].includes(":");
185
+ const isParamB = segmentsB[i].includes(":");
186
+
187
+ // sort wildcard segments after non-wildcard segments
188
+ if (isWildcardA && !isWildcardB) return 1;
189
+ if (!isWildcardA && isWildcardB) return -1;
190
+
191
+ // sort dynamic param segments after non-param segments
192
+ if (isParamA && !isParamB) return 1;
193
+ if (!isParamA && isParamB) return -1;
194
+ }
195
+
196
+ // sort routes that specify an HTTP before those that don't
197
+ if (methodA && !methodB) return -1;
198
+ if (!methodA && methodB) return 1;
199
+
200
+ // all else equal, just sort them lexicographically
201
+ return a.localeCompare(b);
202
+ }
203
+
204
+ async function forEachFile<T>(
205
+ baseDir: string,
206
+ fn: (filepath: string) => T | Promise<T>
207
+ ) {
208
+ const searchPaths = [baseDir];
209
+ const returnValues: T[] = [];
210
+
211
+ while (searchPaths.length) {
212
+ const cwd = searchPaths.shift();
213
+ const dir = await fs.readdir(cwd, { withFileTypes: true });
214
+ for (const entry of dir) {
215
+ const pathname = path.join(cwd, entry.name);
216
+ if (entry.isDirectory()) {
217
+ searchPaths.push(pathname);
218
+ } else if (entry.isFile()) {
219
+ returnValues.push(await fn(pathname));
220
+ }
221
+ }
222
+ }
223
+
224
+ return returnValues;
225
+ }
@@ -0,0 +1,78 @@
1
+ export const RESERVED_KEYWORDS = [
2
+ "do",
3
+ "if",
4
+ "in",
5
+ "for",
6
+ "let",
7
+ "new",
8
+ "try",
9
+ "var",
10
+ "case",
11
+ "else",
12
+ "enum",
13
+ "eval",
14
+ "null",
15
+ "this",
16
+ "true",
17
+ "void",
18
+ "with",
19
+ "await",
20
+ "break",
21
+ "catch",
22
+ "class",
23
+ "const",
24
+ "false",
25
+ "super",
26
+ "throw",
27
+ "while",
28
+ "yield",
29
+ "delete",
30
+ "export",
31
+ "import",
32
+ "public",
33
+ "return",
34
+ "static",
35
+ "switch",
36
+ "typeof",
37
+ "default",
38
+ "extends",
39
+ "finally",
40
+ "package",
41
+ "private",
42
+ "continue",
43
+ "debugger",
44
+ "function",
45
+ "arguments",
46
+ "interface",
47
+ "protected",
48
+ "implements",
49
+ "instanceof",
50
+ "NaN",
51
+ "Infinity",
52
+ "undefined",
53
+ ];
54
+
55
+ export const reservedKeywordRegex = new RegExp(
56
+ `^${RESERVED_KEYWORDS.join("|")}$`
57
+ );
58
+
59
+ export const identifierStartRegex = /[$_\p{ID_Start}]/u;
60
+
61
+ export const identifierPartRegex = /[$_\u200C\u200D\p{ID_Continue}]/u;
62
+
63
+ export const identifierNameRegex =
64
+ /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
65
+
66
+ export const validIdentifierRegex = new RegExp(
67
+ `(?!(${reservedKeywordRegex.source})$)${identifierNameRegex.source}`,
68
+ "u"
69
+ );
70
+
71
+ export const isValidIdentifer = (identifier: string) =>
72
+ validIdentifierRegex.test(identifier);
73
+
74
+ export const normalizeIdentifier = (identifier: string) =>
75
+ identifier.replace(
76
+ /(?:^[^$_\p{ID_Start}])|[^$_\u200C\u200D\p{ID_Continue}]/gu,
77
+ "_"
78
+ );