The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as FileSystem from "effect/FileSystem"; |
| 3 | import * as Option from "effect/Option"; |
| 4 | import * as Path from "effect/Path"; |
| 5 | import * as Schema from "effect/Schema"; |
| 6 | |
| 7 | const CONFIG_FILES = [ |
| 8 | "app.config.ts", |
| 9 | "app.config.mts", |
| 10 | "app.config.js", |
| 11 | "app.config.mjs", |
| 12 | "app.config.cjs", |
| 13 | ]; |
| 14 | const JSON_CONFIG_FILES = ["app.config.json", "app.json"]; |
| 15 | const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; |
| 16 | // Only accept a quoted UUID as the whole value, followed by a separator or EOF. |
| 17 | // Consume comments whole so separators inside them cannot end the entry; |
| 18 | // an operator can follow a line break or comment. |
| 19 | const QUOTED_PROJECT_ID = |
| 20 | /\bprojectId["']?\s*:\s*["'`]([^"'`\n]*)["'`](?=(?:\s|\/\/[^\n\r\u2028\u2029]*(?:[\n\r\u2028\u2029]|$)|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:[,;})\]]|$))/gi; |
| 21 | const PROJECT_ID_MENTION = /\bprojectId\b/gi; |
| 22 | // Reading a config is linear in its size per entry; one this large is not an |
| 23 | // app config but a file made to keep the server busy. |
| 24 | const MAX_CONFIG_LENGTH = 256 * 1024; |
| 25 | // Each entry is read against the rest of the file, so a file with many is |
| 26 | // quadratic; an app config mentions its project a few times at most. |
| 27 | const MAX_MENTIONS = 32; |
| 28 | |
| 29 | // A later spread at any depth can replace an entry through an enclosing object. |
| 30 | // Assignments can replace the config from anywhere; Object.assign names its call |
| 31 | // before either argument. |
| 32 | const SPREAD_LATER = /\.\.\./; |
| 33 | // Space, a comment, or an opening parenthesis: what may sit between `...` |
| 34 | // and the thing spread. Sticky, so the scan moves through the file once. |
| 35 | const SPREAD_FILLER = /(?:\s+|\/\/[^\n\r\u2028\u2029]*|\/\*(?:[^*]|\*(?!\/))*\*\/|\()/y; |
| 36 | // `config`'s `extra` and `extra.eas` entries, the holders of the Expo project id |
| 37 | // (dotted, optional-chained or in brackets). |
| 38 | const EXTRA_OF_CONFIG = String.raw`config(?:\s*\??\.\s*extra|\s*(?:\?\.)?\s*\[\s*["'\x60]extra["'\x60]\s*\])`; |
| 39 | const EAS_OF_CONFIG = |
| 40 | EXTRA_OF_CONFIG + String.raw`(?:\s*\??\.\s*eas|\s*(?:\?\.)?\s*\[\s*["'\x60]eas["'\x60]\s*\])`; |
| 41 | // The holder, and nothing more of it: no further property, call or operator |
| 42 | // (`?? {}` keeps it, so it may follow). |
| 43 | const HOLDER_END = String.raw`(?![\p{ID_Continue}$\u200c\u200d\\]|\s*(?:[.\[(]|\?(?!\?)))`; |
| 44 | const HOLDER_AT = { |
| 45 | extra: new RegExp(EXTRA_OF_CONFIG + HOLDER_END, "uy"), |
| 46 | eas: new RegExp(EAS_OF_CONFIG + HOLDER_END, "uy"), |
| 47 | }; |
| 48 | // `config` and no more of it: not an identifier continuing (`$`, Unicode |
| 49 | // letters and a `\u` escape do, where `\b` would not), nor a property. |
| 50 | const CONFIG_AT = new RegExp("config" + HOLDER_END, "uy"); |
| 51 | // A part of `config` other than `extra`, such as `config.ios`; the last name is |
| 52 | // captured. Spread at the top it could bring its own `extra` (`...config.preview`). |
| 53 | const CONFIG_PART_AT = new RegExp( |
| 54 | String.raw`config(?:\s*\??\.\s*(?!extra(?![\p{ID_Continue}$]))([\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*))+` + |
| 55 | HOLDER_END, |
| 56 | "uy", |
| 57 | ); |
| 58 | // So a part keeps the id only as the first item of the object or array entry it |
| 59 | // names (`ios: { ...config.ios`, `plugins: [...config.plugins`); the key is captured. |
| 60 | const PART_OPENER = |
| 61 | /(?<=[{,]\s*["']?([\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*)["']?\s*:\s*[[{]\s*)/uy; |
| 62 | |
| 63 | /** |
| 64 | * Only Expo's `config`, its own `extra`/`extra.eas`, and parts kept in their own entry can |
| 65 | * preserve app.json's id. Other spreads may replace it; no spreads leaves inheritance unclear. |
| 66 | * Skip comments whole after spreads to keep scanning linear. |
| 67 | */ |
| 68 | const staticConfigUse = (source: string): "spreads" | "replaces" | "unclear" => { |
| 69 | let spreads = 0; |
| 70 | let at = 0; |
| 71 | for (;;) { |
| 72 | const next = source.indexOf("...", at); |
| 73 | if (next === -1) return spreads > 0 ? "spreads" : "unclear"; |
| 74 | at = next + 3; |
| 75 | for (;;) { |
| 76 | SPREAD_FILLER.lastIndex = at; |
| 77 | const filler = SPREAD_FILLER.exec(source); |
| 78 | if (!filler) break; |
| 79 | at += filler[0].length; |
| 80 | } |
| 81 | CONFIG_AT.lastIndex = at; |
| 82 | if (CONFIG_AT.test(source)) { |
| 83 | spreads++; |
| 84 | continue; |
| 85 | } |
| 86 | CONFIG_PART_AT.lastIndex = at; |
| 87 | const part = CONFIG_PART_AT.exec(source); |
| 88 | PART_OPENER.lastIndex = next; |
| 89 | const opener = part && PART_OPENER.exec(source); |
| 90 | // Expo reads a returned `expo` entry as the whole config. |
| 91 | if (opener && opener[1] === part[1] && opener[1] !== "expo") continue; |
| 92 | HOLDER_AT.extra.lastIndex = at; |
| 93 | HOLDER_AT.eas.lastIndex = at; |
| 94 | if (!HOLDER_AT.extra.test(source) && !HOLDER_AT.eas.test(source)) return "replaces"; |
| 95 | } |
| 96 | }; |
| 97 | const ASSIGNS_OVER = /\bObject\s*\.\s*assign\b|\bassign\s*\(/; |
| 98 | // A config may replace its entry or itself from where this scan cannot read: |
| 99 | // assigning `.extra` or `.eas` (dotted or bracketed), a `delete`, or a file it |
| 100 | // requires or imports. Typing it as `import('expo/config').ConfigContext`, in a |
| 101 | // comment or not, loads only Expo's own module. |
| 102 | const REPLACES_HOLDER = |
| 103 | /(?:\.\s*(?:extra|eas)|\[\s*["'`](?:extra|eas)["'`]\s*\])\s*=(?!=)|\bdelete\b|\brequire\s*\(|\bimport\s*\((?!\s*(["'])expo\/config\1\s*\)\s*\.\s*[A-Z])/; |
| 104 | // An `extra`/`eas` object must start by spreading the matching `config` entry to keep app.json's id. |
| 105 | // Spreading the whole config there puts the id elsewhere; shorthand entries replace it too. |
| 106 | // Stop reading once entries exceed MAX_MENTIONS. |
| 107 | const EXTRA_OR_EAS = /(?:\b(extra|eas)|["'`](extra|eas)["'`]\s*\]?)\s*:\s*/g; |
| 108 | const SHORTHAND_EXTRA_OR_EAS = /(?<![.\p{ID_Continue}$])(?:extra|eas)\s*(?=[,}])/u; |
| 109 | const keepsStaticExtra = (source: string): boolean => { |
| 110 | if (SHORTHAND_EXTRA_OR_EAS.test(source)) return false; |
| 111 | let entries = 0; |
| 112 | for (const entry of source.matchAll(EXTRA_OR_EAS)) { |
| 113 | if (++entries > MAX_MENTIONS) return false; |
| 114 | const holder = HOLDER_AT[(entry[1] ?? entry[2]) as "extra" | "eas"]; |
| 115 | let at = entry.index + entry[0].length; |
| 116 | if (source[at] !== "{") return false; |
| 117 | at++; |
| 118 | for (;;) { |
| 119 | SPREAD_FILLER.lastIndex = at; |
| 120 | const filler = SPREAD_FILLER.exec(source); |
| 121 | if (!filler) break; |
| 122 | at += filler[0].length; |
| 123 | } |
| 124 | if (!source.startsWith("...", at)) return false; |
| 125 | at += 3; |
| 126 | for (;;) { |
| 127 | SPREAD_FILLER.lastIndex = at; |
| 128 | const filler = SPREAD_FILLER.exec(source); |
| 129 | if (!filler) break; |
| 130 | at += filler[0].length; |
| 131 | } |
| 132 | holder.lastIndex = at; |
| 133 | if (!holder.test(source)) return false; |
| 134 | } |
| 135 | return true; |
| 136 | }; |
| 137 | |
| 138 | const Extra = Schema.optional( |
| 139 | Schema.Struct({ |
| 140 | eas: Schema.optional(Schema.Struct({ projectId: Schema.optional(Schema.String) })), |
| 141 | }), |
| 142 | ); |
| 143 | // Expo reads a static config wrapped in `expo` or not, and as JSON5; one |
| 144 | // this cannot decode (comments, say) still names a project, unknown here. |
| 145 | const decodeAppJson = Schema.decodeUnknownOption( |
| 146 | Schema.fromJsonString( |
| 147 | Schema.Struct({ expo: Schema.optional(Schema.Struct({ extra: Extra })), extra: Extra }), |
| 148 | ), |
| 149 | ); |
| 150 | |
| 151 | /** |
| 152 | * Never execute dynamic configs. Keep ids in comments so stale ids make the answer ambiguous. |
| 153 | * Include JSON configs because dynamic configs may replace them only for some builds. |
| 154 | * Return null for unreadable configs or ids set or changed without a literal. |
| 155 | */ |
| 156 | const projectIdsOf = Effect.fn("easProjectId.projectIdsOf")(function* (dir: string) { |
| 157 | const fs = yield* FileSystem.FileSystem; |
| 158 | const path = yield* Path.Path; |
| 159 | const ids: Array<string> = []; |
| 160 | const configFile = yield* Effect.findFirst(CONFIG_FILES, (file) => |
| 161 | fs.exists(path.join(dir, file)).pipe(Effect.orElseSucceed(() => false)), |
| 162 | ); |
| 163 | if (Option.isSome(configFile)) { |
| 164 | const source = yield* fs |
| 165 | .readFileString(path.join(dir, configFile.value)) |
| 166 | .pipe(Effect.orElseSucceed(() => "projectId")); |
| 167 | // Every mention of `projectId` must be a quoted entry: one set from a |
| 168 | // variable, or assigned later, could be any project, and makes the |
| 169 | // answer unknown. |
| 170 | if (source.length > MAX_CONFIG_LENGTH) return null; |
| 171 | const mentions = source.match(PROJECT_ID_MENTION)?.length ?? 0; |
| 172 | if (mentions > MAX_MENTIONS) return null; |
| 173 | const entries = [...source.matchAll(QUOTED_PROJECT_ID)]; |
| 174 | const quoted = entries.map((match) => match[1]!); |
| 175 | // A template that interpolates could be any project too, and so could |
| 176 | // one a spread after the entry, or an assignment anywhere, replaces; |
| 177 | if ( |
| 178 | quoted.length !== mentions || |
| 179 | quoted.some((id) => id.includes("${")) || |
| 180 | ASSIGNS_OVER.test(source) || |
| 181 | REPLACES_HOLDER.test(source) || |
| 182 | entries.some((match) => SPREAD_LATER.test(source.slice(match.index + match[0].length))) |
| 183 | ) { |
| 184 | return null; |
| 185 | } |
| 186 | // Only a config shown to spread `config` and nothing else carries app.json's |
| 187 | // entry through unchanged; any other shape could use or replace it. |
| 188 | if ( |
| 189 | !quoted.some((id) => UUID.test(id)) && |
| 190 | (staticConfigUse(source) !== "spreads" || !keepsStaticExtra(source)) |
| 191 | ) { |
| 192 | return null; |
| 193 | } |
| 194 | ids.push(...quoted.filter((id) => UUID.test(id)).map((id) => id.toLowerCase())); |
| 195 | } |
| 196 | for (const file of JSON_CONFIG_FILES) { |
| 197 | const json = yield* fs.readFileString(path.join(dir, file)).pipe( |
| 198 | Effect.asSome, |
| 199 | Effect.catch((error) => |
| 200 | Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : null), |
| 201 | ), |
| 202 | ); |
| 203 | // A config that is there but cannot be read could name any project. |
| 204 | if (json === null) return null; |
| 205 | if (Option.isNone(json)) continue; |
| 206 | const decoded = decodeAppJson(json.value); |
| 207 | if (Option.isNone(decoded)) return null; |
| 208 | const id = (decoded.value.expo ?? decoded.value).extra?.eas?.projectId; |
| 209 | if (id !== undefined && UUID.test(id)) ids.push(id.toLowerCase()); |
| 210 | // Expo reads only the first static config it finds. |
| 211 | break; |
| 212 | } |
| 213 | return ids; |
| 214 | }); |
| 215 | |
| 216 | /** |
| 217 | * The Expo project of a workspace's Expo app: its root, or one app below |
| 218 | * `apps/` or `packages/`. None when there is none, a config is ambiguous, or |
| 219 | * the apps disagree, so the caller asks for an explicit choice instead of |
| 220 | * billing the wrong project. |
| 221 | */ |
| 222 | export const findEasProjectId = Effect.fn("easProjectId.findEasProjectId")(function* ( |
| 223 | workspaceRoot: string, |
| 224 | ) { |
| 225 | const fs = yield* FileSystem.FileSystem; |
| 226 | const path = yield* Path.Path; |
| 227 | const isDirectory = (child: string) => |
| 228 | fs.stat(child).pipe( |
| 229 | Effect.map((info) => info.type === "Directory"), |
| 230 | Effect.orElseSucceed(() => false), |
| 231 | ); |
| 232 | // Only a directory can be an app; a README or .DS_Store beside them is not one. |
| 233 | const children = (parent: string) => |
| 234 | fs.readDirectory(path.join(workspaceRoot, parent)).pipe( |
| 235 | Effect.map((names) => names.map((name) => path.join(workspaceRoot, parent, name))), |
| 236 | Effect.flatMap((paths) => |
| 237 | Effect.forEach(paths, (child) => |
| 238 | Effect.map(isDirectory(child), (directory) => (directory ? [child] : [])), |
| 239 | ), |
| 240 | ), |
| 241 | Effect.map((kept) => kept.flat()), |
| 242 | Effect.orElseSucceed(() => []), |
| 243 | ); |
| 244 | const directories = [ |
| 245 | workspaceRoot, |
| 246 | ...(yield* children("apps")), |
| 247 | ...(yield* children("packages")), |
| 248 | ]; |
| 249 | const ids = yield* Effect.forEach(directories, projectIdsOf, { concurrency: 4 }); |
| 250 | // An app whose project is unknown could be the one the thread works on. |
| 251 | if (ids.some((found) => found === null)) return Option.none<string>(); |
| 252 | const distinct = new Set(ids.flatMap((found) => found ?? [])); |
| 253 | return distinct.size === 1 ? Option.some([...distinct][0]!) : Option.none<string>(); |
| 254 | }); |