@autofleet/cli 2.30.1 → 2.31.0
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.
- package/dist/claude-marketplace/plugins/autofleet/.claude-plugin/plugin.json +1 -1
- package/dist/claude-marketplace/plugins/autofleet/skills/code-review/SKILL.md +2 -1
- package/dist/claude-marketplace/plugins/autofleet/skills/logging-standard/SKILL.md +127 -0
- package/dist/claude-marketplace/plugins/autofleet/skills/logging-standard/examples.md +94 -0
- package/dist/e2e.js +1 -1
- package/dist/git-autofleet.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{utils-COC28l4j.js → utils-BOPv1fAz.js} +2 -2
- package/dist/{utils-COC28l4j.js.map → utils-BOPv1fAz.js.map} +1 -1
- package/package.json +1 -1
|
@@ -62,7 +62,7 @@ Use this skill when performing automated code reviews on pull requests. This ski
|
|
|
62
62
|
|
|
63
63
|
- **Entity hierarchy**: Proper use of Fleet → Business Model → Demand Source
|
|
64
64
|
- **Microservice communication**: Appropriate service boundaries
|
|
65
|
-
- **Logging**: Consistent logging patterns
|
|
65
|
+
- **Logging**: Consistent logging patterns — apply `logging-standard` skill for level, schema, and PII rules
|
|
66
66
|
- **Error tracking**: Proper error propagation and tracking
|
|
67
67
|
- **Configuration**: Environment-specific config properly managed
|
|
68
68
|
- **Route validation (new HTTP routes)**: New endpoints validate body/query/params with Joi via `@autofleet/shin-gimel` — see **examples.md → Route Validation** and `add-endpoint`.
|
|
@@ -206,6 +206,7 @@ When reviewing code, reference these related skills for detailed standards:
|
|
|
206
206
|
- **python-standards** - For Python code review
|
|
207
207
|
- **db-modeling** - For database schema and query review
|
|
208
208
|
- **pr-standards** - For PR structure and description quality
|
|
209
|
+
- **logging-standard** - For logging patterns, log levels, and log schema compliance
|
|
209
210
|
- **add-endpoint** - For new HTTP routes: validation layers (shin-gimel/Joi), `@autofleet/errors` (`handleError` / `handleErrorFastify`), response shape, status codes, gateway registration
|
|
210
211
|
|
|
211
212
|
## Example Review Comments
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: logging-standard
|
|
3
|
+
description: Use this skill when writing, reviewing, or discussing logging in any Autofleet service. Enforces the unified Autofleet logging standard.
|
|
4
|
+
version: 1.0.0
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Autofleet Logging Standard
|
|
8
|
+
|
|
9
|
+
Apply these standards when writing or reviewing logging code in any Autofleet service.
|
|
10
|
+
|
|
11
|
+
## Standard Library
|
|
12
|
+
|
|
13
|
+
Always use `@autofleet/logger`. **Never** use `console.log`/`console.error` in production service code (migrations and dev scripts are acceptable exceptions). Never implement custom logging logic.
|
|
14
|
+
|
|
15
|
+
### Logger Initialization
|
|
16
|
+
|
|
17
|
+
Every microservice initializes `@autofleet/logger` once in `src/logger.ts` and exports it as default. Always pass `ServiceContext` so GCP Error Reporting can attribute errors to the correct service.
|
|
18
|
+
|
|
19
|
+
Also export a `getChildLogger` helper for scoped module-level logging. Modules use `getChildLogger` to create a scoped logger that automatically includes the `module` field on every log entry — no need to repeat it manually.
|
|
20
|
+
|
|
21
|
+
If `ServiceContext` is omitted, GCP Error Reporting cannot attribute errors to a specific service and `serviceContext` will be absent from all log entries.
|
|
22
|
+
|
|
23
|
+
**examples.md → Logger Initialization**
|
|
24
|
+
|
|
25
|
+
## What the Logger Handles Automatically
|
|
26
|
+
|
|
27
|
+
These fields are injected automatically — reviewers do **not** need to check for them:
|
|
28
|
+
- `timestamp` — Pino injects this
|
|
29
|
+
- `level` — set by Pino
|
|
30
|
+
- `traceId` — injected by `@autofleet/zehut`'s `enableTracing` (see [Tracing](#tracing) below)
|
|
31
|
+
|
|
32
|
+
### GCP Log Fields (production only)
|
|
33
|
+
|
|
34
|
+
In production, `@autofleet/logger` wraps Pino with `gcpLogOptions`, which adds GCP-specific fields automatically:
|
|
35
|
+
|
|
36
|
+
| Field | Description |
|
|
37
|
+
|-------|-------------|
|
|
38
|
+
| `severity` | Mapped from Pino level (`INFO`, `WARNING`, `ERROR`, `CRITICAL`) for Cloud Logging |
|
|
39
|
+
| `@type` | Set on `error`/`fatal` logs so GCP Error Reporting tracks them even without a stack trace |
|
|
40
|
+
| `message` | Pino's `msg` is remapped to `message` (GCP's expected key) |
|
|
41
|
+
| `stack_trace` | Extracted from `err.stack`, `error.stack`, or `e.stack` for Cloud Error Reporting |
|
|
42
|
+
| `serviceContext` | `{ service, version }` — only present when `ServiceContext` is passed to `Logger()` |
|
|
43
|
+
|
|
44
|
+
These are injected by the logger infrastructure — do **not** add them manually in application code.
|
|
45
|
+
|
|
46
|
+
## Tracing
|
|
47
|
+
|
|
48
|
+
`traceId` is automatically injected into every log entry via `@autofleet/zehut`'s `enableTracing({ logger })`, which registers a context middleware through `logger.addContextMiddleware`. **Do not** call `enableTracing` or `addContextMiddleware` manually unless you are setting up a Fastify service entrypoint.
|
|
49
|
+
|
|
50
|
+
- **Express (SuperExpress)**: Handled automatically. `superExpress` calls `enableTracing({ logger })` when `tracing: true` (the default). No action needed.
|
|
51
|
+
- **Fastify**: The service entrypoint must call `enableTracing({ logger })` **before** creating the Fastify instance, because `outbreak` monkey-patches `http.createServer`.
|
|
52
|
+
|
|
53
|
+
**examples.md → Tracing Setup (Fastify)**
|
|
54
|
+
|
|
55
|
+
## Log Levels
|
|
56
|
+
|
|
57
|
+
| Level | When to Use |
|
|
58
|
+
|-------|-------------|
|
|
59
|
+
| FATAL | System unusable — unrecoverable crash or critical component failure |
|
|
60
|
+
| ERROR | Operation failed (API call, DB write), but app remains running |
|
|
61
|
+
| WARN | Unexpected/sub-optimal event that didn't stop the flow (slow response, successful retry) |
|
|
62
|
+
| INFO | High-level operational milestones ("Sync completed", "File upload received", "Role assigned") |
|
|
63
|
+
| DEBUG | Granular internal state for developer diagnostics |
|
|
64
|
+
|
|
65
|
+
**Production default: WARN.** Services run at WARN in production (`LOG_LEVEL` env var can override). INFO and DEBUG logs are not written unless the level is explicitly raised. Use INFO only for high-value operational milestones that justify the cost; use WARN for unexpected-but-handled conditions; use DEBUG for granular diagnostics.
|
|
66
|
+
|
|
67
|
+
## What Code Reviewers Must Check
|
|
68
|
+
|
|
69
|
+
### 1. No console.log
|
|
70
|
+
|
|
71
|
+
**examples.md → No console.log**
|
|
72
|
+
|
|
73
|
+
### 2. No PII in Log Metadata
|
|
74
|
+
|
|
75
|
+
Never log email addresses, passwords, tokens, or phone numbers in the metadata object.
|
|
76
|
+
|
|
77
|
+
**examples.md → No PII in Log Metadata**
|
|
78
|
+
|
|
79
|
+
### 3. Latency on External Calls
|
|
80
|
+
|
|
81
|
+
Latency tracking is an infrastructure concern, not a per-call responsibility:
|
|
82
|
+
|
|
83
|
+
- **HTTP calls**: Use `Network` from `@autofleet/network` — it logs request/response automatically. Flag raw `fetch`/`axios` calls.
|
|
84
|
+
- **HTTP request logging**: `SExpress` logs HTTP request latency automatically via Morgan — it is enabled by default (`morgan: true`) and wired to the service's logger instance. No per-call logging is needed; the only option consumers have is `morgan: false` to disable it.
|
|
85
|
+
- **DB queries**: Latency should be instrumented via a Sequelize hook at service setup, not per-query.
|
|
86
|
+
|
|
87
|
+
### 4. Correct Log Level
|
|
88
|
+
|
|
89
|
+
**examples.md → Correct Log Level**
|
|
90
|
+
|
|
91
|
+
### 4a. INFO Overuse — Flag These Patterns
|
|
92
|
+
|
|
93
|
+
Because production runs at WARN, INFO logs are never written unless the level is raised. Reviewers should flag INFO calls that are not genuine high-value milestones:
|
|
94
|
+
|
|
95
|
+
- **Flow steps** — e.g. `logger.info('Fetching user')`, `logger.info('Processing request')` → downgrade to DEBUG
|
|
96
|
+
- **Per-item loop logs** — any `info` inside a loop or batch → downgrade to DEBUG
|
|
97
|
+
- **Unexpected-but-handled events** — retry succeeded, fallback used, value missing but defaulted → upgrade to WARN
|
|
98
|
+
|
|
99
|
+
If removing the INFO log would make debugging noticeably harder, it's a sign the service needs structured trace persistence (log on error only) rather than always-on INFO.
|
|
100
|
+
|
|
101
|
+
### 5. No Large Objects in Metadata
|
|
102
|
+
|
|
103
|
+
Never pass large objects, arrays, or deeply nested structures directly as log metadata — this inflates log size and increases GCP logging costs. Log only the IDs or scalar values needed to identify the entity.
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
// ❌ Bad — entire object serialized on every log
|
|
107
|
+
logger.info('Processing ride', { ride, vehicle, driver })
|
|
108
|
+
|
|
109
|
+
// ✓ Good — only identifiers
|
|
110
|
+
logger.info('Processing ride', { context: { rideId, vehicleId, driverId } })
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### 6. Log Informativeness
|
|
114
|
+
|
|
115
|
+
Each log should be self-contained enough for someone reading it in GCP to understand what happened without additional context. Reviewers should check:
|
|
116
|
+
|
|
117
|
+
1. **Flow context in the message** — does the message name the operation? `'Update user flow — user not found'` is actionable; `'User not found'` is not.
|
|
118
|
+
2. **Enough params to reconstruct context** — include the filter or key used for lookups (but not PII values). If a search failed, log which field was searched, not its value.
|
|
119
|
+
3. **Not spammy** — if another log in the same flow already provides equivalent context, this one can be removed or downgraded.
|
|
120
|
+
|
|
121
|
+
### 7. Lazy Logging for Unavoidable Expensive Payloads
|
|
122
|
+
|
|
123
|
+
Prefer not computing expensive metadata in log calls at all (see latency guidance above). When it is genuinely unavoidable — e.g. `Object.keys`, array `.map`, or Set-to-array conversions needed for a debug payload — use the lazy variant so the computation is skipped entirely when the level is disabled.
|
|
124
|
+
|
|
125
|
+
All levels have a lazy variant: `traceLazy`, `debugLazy`, `infoLazy`, `warnLazy`, `errorLazy`, `fatalLazy`. The callback must return `[message]` or `[message, metadata]`.
|
|
126
|
+
|
|
127
|
+
**examples.md → Lazy Logging for Expensive Payloads**
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Logging Standard — Examples
|
|
2
|
+
|
|
3
|
+
## Logger Initialization
|
|
4
|
+
|
|
5
|
+
### Basic setup with ServiceContext
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
// src/logger.ts
|
|
9
|
+
import Logger from '@autofleet/logger';
|
|
10
|
+
import pkgJson from '../package.json';
|
|
11
|
+
|
|
12
|
+
export default Logger(undefined, { serviceName: pkgJson.name, version: pkgJson.version });
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
### With child logger helper
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
// src/logger.ts
|
|
19
|
+
import Logger from '@autofleet/logger';
|
|
20
|
+
import pkgJson from '../package.json';
|
|
21
|
+
|
|
22
|
+
export const logger = Logger(undefined, { serviceName: pkgJson.name, version: pkgJson.version });
|
|
23
|
+
export const getChildLogger = (moduleName: string, metadata?: Record<string, unknown>) =>
|
|
24
|
+
logger.child(moduleName, { module: moduleName, ...metadata });
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Using a child logger in a module
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
// src/api/v1/approval/approvers.ts
|
|
31
|
+
import { getChildLogger } from '../../../logger';
|
|
32
|
+
|
|
33
|
+
const logger = getChildLogger('approvers-router');
|
|
34
|
+
|
|
35
|
+
logger.info('Context created', { contextId, entityId });
|
|
36
|
+
// → { module: 'approvers-router', contextId, entityId, ... }
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Tracing Setup (Fastify)
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
import { enableTracing } from '@autofleet/zehut';
|
|
43
|
+
import { logger } from './logger.ts';
|
|
44
|
+
|
|
45
|
+
enableTracing({ logger });
|
|
46
|
+
// Must come before Fastify initialization
|
|
47
|
+
const app = await buildApp({ loggerInstance: logger.child('fastify', {}) });
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Code Review — Bad vs Good Patterns
|
|
51
|
+
|
|
52
|
+
### No console.log
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// ❌ Bad
|
|
56
|
+
console.log('User created', userId)
|
|
57
|
+
console.error('Failed', error)
|
|
58
|
+
|
|
59
|
+
// ✓ Good — descriptive message, IDs grouped under context
|
|
60
|
+
logger.info('User created', { context: { userId, fleetId } })
|
|
61
|
+
logger.error('Ride assignment failed', { context: { rideId, fleetId }, error })
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### No PII in Log Metadata
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
// ❌ Bad
|
|
68
|
+
logger.info('Auth check', { email, userId })
|
|
69
|
+
logger.error('Fetch failed', { email, contextId, error })
|
|
70
|
+
|
|
71
|
+
// ✓ Good — use IDs only
|
|
72
|
+
logger.info('Auth check', { userId, contextId })
|
|
73
|
+
logger.error('Fetch failed', { userId, contextId, error })
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Correct Log Level
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
// ❌ Bad — ERROR for a handled/expected case
|
|
80
|
+
logger.error('User not found', { userId })
|
|
81
|
+
|
|
82
|
+
// ✓ Good
|
|
83
|
+
logger.warn('User not found', { userId })
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Lazy Logging for Expensive Payloads
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
// ❌ Bad — computation runs even when debug is off in production
|
|
90
|
+
logger.debug('Sync payload', { ids: items.map(i => i.id) })
|
|
91
|
+
|
|
92
|
+
// ✓ Good — function never called if debug is disabled
|
|
93
|
+
logger.debugLazy(() => ['Sync payload', { ids: items.map(i => i.id) }])
|
|
94
|
+
```
|
package/dist/e2e.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{S as e,c as t,i as n,l as r,n as i,w as a}from"./utils-
|
|
2
|
+
import{S as e,c as t,i as n,l as r,n as i,w as a}from"./utils-BOPv1fAz.js";import o from"node:path";import s from"p-retry";const c=[`identity-ms`,`vehicle-ms`,`ride-ms`,`vehicle-live-data-ms`,`pricing-ms`,`payment-ms`,`route-plan-ms`,`task-ms`,`audit-ms`,`pgweb`,`placement-ms`,`demand-prediction-ms`,`control-center-ms`,`setting-ms`,`api-gateway-ms`],l={start:`--e2eBranch=<branchName> --branches="{\\"ride-ms\\": \\"AUT-7070\\"}"`,getIpsForEnv:`--variationId=<yourVariationUuid> --cluster=<dev1/e2eManager>`},u=e=>Object.keys(l).includes(e),{positionals:d,values:f,help:p}=a({strict:!0,binName:`autofleet-e2e`,allowPositionals:!0,options:{e2eBranch:{type:`string`,default:`master`,description:`Name of e2e branch`},branches:{type:`string`,default:``,description:`"ride-ms": "AUT-7070"`},cluster:{type:`string`,short:`c`,description:`The cluster name. One of dev1, e2eManager, expManager`},variationId:{type:`string`,short:`i`,description:`The variation id`}},commands:l});d.length||(console.log(p),process.exit(0));const[m]=d;if(u(m)||n(Error(`Command ${m} does not exist`),p),m===`start`){let t=(f.branches?.replace(`{`,` `)||``).replace(/[^a-z0-9]/gi,``),n=`${o.resolve()}/bin/utils/e2e.sh`,i=`${o.resolve()}/e2e.sh`;r({newFilePath:i,filePath:n,linesToReplace:[{find:`$E2E_BRANCH_PLACE_HOLDER$`,replace:f.e2eBranch},{find:`$BRANCHES_PLACE_HOLDER$`,replace:f.branches},{find:`$NAME_PLACE_HOLDER$`,replace:t}]}),await e(`chmod`,[`+x ${i} && ${i}`]),console.log(`finished e2e`)}const{cluster:h,variationId:g}=f;h||n(Error(`cluster required`),p),g||n(Error(`variationId required`),p);let _;try{_=await i({clusterName:h,variationId:g})}catch(e){n(e)}m===`getIpsForEnv`&&(await Promise.all(c.map(t=>e(`kubectl`,[`annotate`,_,`service`,t,`cloud.google.com/load-balancer-type-`],{print:!1}))),await Promise.all(c.map(t=>e(`kubectl`,[`patch`,`svc`,_,t,`-p`,`{"spec": {"type": "LoadBalancer"}}`],{print:!1}))),console.log(`exposed services successfully. the services are now creating public ips.`),await s(async()=>{let{stdout:n}=await e(`kubectl`,[_,`get`,`services`],{print:!1}),r=t(n);if(r.some(e=>e.includes(`<pending>`)))throw Error(`Some services are still pending`);r.forEach(e=>console.log(e))},{retries:10,factor:1,maxTimeout:5e3,randomize:!0}),process.exit(0));export{};
|
|
3
3
|
//# sourceMappingURL=e2e.js.map
|
package/dist/git-autofleet.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{S as e,_ as t,g as n,h as r,i,m as a,v as o,w as s,y as c}from"./utils-
|
|
2
|
+
import{S as e,_ as t,g as n,h as r,i,m as a,v as o,w as s,y as c}from"./utils-BOPv1fAz.js";import{basename as l,sep as u}from"node:path";import{readdir as d}from"node:fs/promises";import{randomUUID as f}from"node:crypto";const p=[`premajor`,`preminor`,`prepatch`,`prerelease`],m=[`major`,`minor`,`patch`,...p],h={bumpVersion:`[${m.join(`|`)}]`,openPR:`Opens github UI for creating a PR from the current branch.`,releaseBeta:`Bumps version if needed, and publishes a beta release to NPM registry.`},g=e=>Object.keys(h).includes(e),_=async({versionType:t,packageName:n,preReleaseId:r=``})=>{let{stdout:i}=await e(`npm`,[`version`,t,`--no-git-tag-version`,`--preid`,r],{print:!1,cwd:n?`.${u}packages${u}${n}`:void 0});return await e(`git`,[`add`,`package*`],{print:!1}),await e(`git`,[`commit`,`-m`,`${t} version: ${i}`],{print:!1}),console.log(`Created commit for version bump: ${t}. Version is now ${i}`),i},v=async e=>{let t=await c(),{default:{version:n}}=await import(`${e?`${t}${u}packages${u}${e}`:t}${u}package.json`,{with:{type:`json`}});return n.replace(/\d+\.\d+\.\d+(?:-beta-([\w]+)?\.\d+)?/,`$1`)},{positionals:y,help:b}=s({strict:!0,binName:`git autofleet`,allowPositionals:!0,options:{},commands:h});y.length||(console.log(b),process.exit(0));const[x,S,C]=y;if(g(x)||i(Error(`Command ${x} does not exist`),b),x===`openPR`){let[t,n]=await Promise.all([c(),o()]);await e(`open`,[`https://github.com/Autofleet/${l(t)}/compare/${n}?expand=1`],{print:!1}),process.exit(0)}async function w(){let e=await c();return e.split(u).pop()===`autorepo`?e:!1}async function T({message:e,pathIfAutorepo:t}){t??=await w();let r=C;if(t){let a=(await d(`${t}${u}packages`)).filter(e=>!e.startsWith(`.`));r?a.includes(r)||i(Error(`Package name ${r} does not exist in autorepo packages`),b):r=await n({message:e,choices:a.map(e=>({name:e,value:e}))}),r||i(Error(`No package name provided, exiting...`),b)}return r}if(x===`bumpVersion`){let e=await T({message:`Which package do you want to bump?`}),t=S||await n({message:`Which version type do you want to bump?`,choices:(x===`bumpVersion`?m:p).map(e=>({name:e,value:e}))});t||i(Error(`Must explicitly define version type.\n\tVersion type can be one of: ${m.join(`, `)}`),b);let r=await o();[`main`,`master`].includes(r)&&(await a(`Are you sure you want to bump version on main branch?`)||process.exit(0)),await _({versionType:t,packageName:e}),process.exit(0)}if(x===`releaseBeta`){let n=await w(),s=await T({message:`Which package do you want to release?`,pathIfAutorepo:n});S&&!p.includes(S)&&i(Error(`Invalid version type: ${S}\n\tVersion must be a prerelease type. (${p.join(`, `)})`),b);let c=await o();[`main`,`master`].includes(c)&&i(Error(`Cannot release beta from main branch`),b);let l=s?`.${u}packages${u}${s}`:void 0,d=!(await t(s?`.${u}packages${u}${s}${u}package.json`:`package.json`)).split(`
|
|
3
3
|
`).some(e=>/^\+\s*"version":\s*"\d+\.\d+\.\d+(?:-(?:[\w-]+\.)?\d+)?",/.test(e))||await a(`Version already bumped on branch. Should version be re-bumped?`),m=d&&await v(s),h=d&&await _({versionType:S||`prerelease`,preReleaseId:`beta-${m||f().split(`-`)[0]}`,packageName:s}),g=n?`pnpm`:`npm`;await e(g,[`run`,`build`],{cwd:l});let y=await r({message:`In case your token requires an OTP, please enter it:`});try{await e(g,[`publish`,`--tag`,`beta`,`--@autofleet:registry=https://registry.npmjs.org`,...y?[`--otp`,y]:[],...n?[`--no-git-checks`]:[]],{cwd:l})}catch(e){console.error(e),i(`Failed to publish beta version`)}if(h)console.log(`Published beta version with new version: ${h}`);else{let{stdout:t}=await e(g,[`info`,`.`,`version`],{print:!1,cwd:l});console.log(`Published beta version with existing version: ${t}`)}process.exit(0)}export{};
|
|
4
4
|
//# sourceMappingURL=git-autofleet.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{C as e,S as t,T as n,a as r,b as i,c as a,d as o,f as s,g as c,i as l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v as ee,w as v,x as y,y as b}from"./utils-
|
|
2
|
+
import{C as e,S as t,T as n,a as r,b as i,c as a,d as o,f as s,g as c,i as l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v as ee,w as v,x as y,y as b}from"./utils-BOPv1fAz.js";import{styleText as x}from"node:util";import*as te from"node:fs";import S from"node:fs";import{execFile as ne,execSync as C,spawn as re}from"node:child_process";import{confirm as w}from"@inquirer/prompts";import*as T from"node:path";import E,{basename as D,join as O,resolve as k,sep as ie}from"node:path";import{mkdir as ae,readFile as A,writeFile as j}from"node:fs/promises";import*as oe from"node:os";import se,{EOL as M,homedir as ce}from"node:os";import{randomUUID as le}from"node:crypto";import{setTimeout as ue}from"node:timers/promises";import{cwd as de}from"node:process";function N(e){return e.replace(/^[\^~]/,``)}function P(e){let t=N(e),n=/^(\d+)/.exec(t);return n?parseInt(n[1],10):0}function fe(e,t){return P(t)>P(e)}function pe(e,t){if(e.includes(`-`)||t.includes(`-`))return!1;let n=e=>e.split(`.`).map(Number),[r,i,a]=n(e),[o,s,c]=n(t);return r===o?i===s?a>c:i>s:r>o}const F=E.join(se.homedir(),`.autofleet`,`update-check.json`);function me(){try{return JSON.parse(S.readFileSync(F,`utf-8`))}catch{return null}}function he(e){try{S.mkdirSync(E.dirname(F),{recursive:!0}),S.writeFileSync(F,JSON.stringify(e))}catch{}}function ge(e,t){try{return C(`${e} ${t.join(` `)}`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||null}catch{return null}}function _e(){let e=process.argv[1]??``;for(let{pm:t,args:n}of[{pm:`pnpm`,args:[`root`,`-g`]},{pm:`yarn`,args:[`global`,`dir`]},{pm:`npm`,args:[`root`,`-g`]}]){let r=ge(t,n);if(r&&e.startsWith(r))return t}return`npm`}function ve(e){return e===`pnpm`?`pnpm add -g @autofleet/cli@latest`:e===`yarn`?`yarn global add @autofleet/cli@latest`:`${E.join(E.dirname(process.execPath),`npm`)} install -g @autofleet/cli@latest`}function ye(){ne(`npm`,[`view`,`@autofleet/cli@latest`,`version`],{encoding:`utf-8`,timeout:15e3},(e,t)=>{if(e||!t.trim())return;let n=t.trim();n&&he({latestVersion:n,checkedAt:Date.now()})}).unref()}async function be(e=!1){if(e)return;let t=me();if(t&&pe(t.latestVersion,n)&&await u(`New @autofleet/cli version available (${n} → ${t.latestVersion}). Update now?`)){let e=ve(_e());console.log(`Updating @autofleet/cli...`),C(e,{stdio:`inherit`}),console.log(`✓ Updated! Please re-run your command.`),process.exit(0)}(t?Date.now()-t.checkedAt:1/0)>864e5&&ye()}const I=`.mirrord`;async function L({makeDir:e=!1}={}){let t=O(await b(),I);return e&&await ae(t,{recursive:!0}),O(t,`mirrord.json`)}async function xe(e=le()){let t=await L({makeDir:!0}),n={feature:{network:{incoming:{mode:`steal`,http_filter:{ports:[8080],path_filter:`^(?!/alive|/ready)`}},outgoing:!0},fs:`read`,env:!0},target:{namespace:e},agent:{ephemeral:!0,startup_timeout:600,communication_timeout:120,namespace:e}};return await j(t,JSON.stringify(n,null,2)),{mirrordConfigData:n,mirrordPath:t}}async function Se(){try{let e=await A(await L(),{encoding:`utf-8`});return JSON.parse(e||`{}`)?.target?.namespace??``}catch{return``}}function Ce(e){process.once(`exit`,e),process.once(`SIGTERM`,e),process.once(`SIGINT`,e)}function R(e){return e&&=e.trim(),e&&(e.startsWith(`'`)&&e.endsWith(`'`)&&(e=e.slice(1,-1)),e)}const z=`livenessProbe`,B=`readinessProbe`,V=e=>`jsonpath='{.spec.template.spec.containers[?(@.name=="worker")].${e}}'`,H=(...e)=>`{"spec": {"template": {"spec": {"containers": [{"name": "worker",${e.map(([e,t])=>`"${e}": ${t}`).join(`,`)}}]}}}}`;var we=async(e,n,r)=>{console.log(`Will now disable health check to allow debugging.`);let[{stdout:i},{stdout:a}]=await Promise.all([t(`kubectl`,[`get`,`deployment/${r}`,e,`-o`,V(z)],{print:!1}),t(`kubectl`,[`get`,`deployment/${r}`,e,`-o`,V(B)],{print:!1})]);i&&=R(i),a&&=R(a),(i||a)&&(await t(`kubectl`,[`patch`,`deployment/${r}`,e,`--patch`,H([z,`null`],[B,`null`])],{print:!1}),console.log(`Health check disabled, will now start mirrord and run "npm run dev". Make sure to attach a debugger!`));let o=new AbortController;Ce(async()=>{globalThis.executedExitHooks||(globalThis.executedExitHooks=!0,o.abort(),(i||a)&&(console.log(`Re-enabling health check.`),await t(`kubectl`,[`patch`,`deployment/${r}`,e,`--patch`,`'${H([z,i],[B,a])}'`],{print:!1,shell:!0}),console.log(`health check enabled.`)),process.exit(0))});try{let e=await L();await t(`mirrord`,[`exec`,`-t`,`deployment/${r}`,`-n`,n,`-f`,e,`--steal`,`npm`,`run`,`dev`],{signal:o.signal})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ABORT_ERR`)return;l(e)}},Te=async(e,n)=>{if(await m(e),e===`expManager`||e===`dev1`){let{variationId:e}=await _({variationId:n},[`variationId`]);e!==``&&(await r()===e&&(console.log(`Already connected to simulation with uuid: ${e}, skipping namespace switch...`),process.exit(0)),await t(`kubectl`,[`config`,`set-context`,`--current`,`--namespace=${e}`],{print:!1}),console.log(`Switched to simulation with uuid: ${e} successfully`))}process.exit(0)};async function Ee(){try{await t(`telepresence`,[`version`],{print:!1})}catch{l(`Telepresence is not installed. Please install it from:
|
|
3
3
|
https://www.telepresence.io/docs/latest/quick-start/`)}}function De(){return c({message:`Do you want to leave the connection or create a new one?`,choices:[{name:`Leave the current connection`,value:`leave`},{name:`Create a new connection`,value:`connect`}],default:`connect`})}async function Oe(e){await Ee();let{cluster:n=``,service:r=``}=e;await m(n);let i=await De();if([`leave`,`connect`].includes(i)||l(`Invalid action, how did you get here? 🤔`),i===`leave`){await t(`telepresence`,[`leave`,r]),console.log(`Disconnected! 👋`);return}let a=e.variationId||await p(),o=e[`local-port`]&&Number.parseInt(e[`local-port`],10)||Number.parseInt(await s()||``,10);await t(`telepresence`,[`connect`,`--namespace=${a}`]),await t(`telepresence`,[`intercept`,r,`--port`,o.toString(),`--env-file=./.env`]),console.log(`Everything is set up! 🚀`),console.log(`You can now access the service at localhost:${o}`),console.log(`You can only have one connection at a time. If you want to connect to a different service, you need to leave the current connection first.`),process.exit(0)}var ke=async(e,n,r)=>{r||l(Error(`service is required for exposeService`),n),await t(`kubectl`,[`patch`,`svc`,e,r,`-p`,`{"spec": {"type": "LoadBalancer"}}`]),console.log(`exposed ${r} successfully. the service is now creating an internal load balancer ip to use with vpn`),process.exit(0)},Ae=async(e,n,r,i,a)=>{let o=Number.parseInt(e[`local-port`]??`5432`,10);Number.isNaN(o)&&l(Error(`if defined, local-port must be a number`),i);let s=`afpass_${r}`,c=`postgres`,u=r.replaceAll(`-`,`_`),d=a?`${a.replaceAll(`-`,`_`)||``}_${u}`:`postgres`,f=`postgres://${c}:${s}@localhost:${o}/${d}?&nickname=var_${r}`;console.log(`Forwarding db to local port ${o}.\naccess the DB at ${f}\nPress ctrl+c to stop.`);let p=` DB_USERNAME=${c}
|
|
4
4
|
DB_PASSWORD=${s}
|
|
5
5
|
DB_NAME=${a?d:`<service_name>_${u}`}`;console.log(`Generated database environment for local development:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{parseArgs as e}from"node:util";import t from"node:fs";import{spawn as n}from"node:child_process";import{confirm as r,input as i,select as a}from"@inquirer/prompts";import{sep as o}from"node:path";import{readdir as s}from"node:fs/promises";var c=`2.
|
|
1
|
+
import{parseArgs as e}from"node:util";import t from"node:fs";import{spawn as n}from"node:child_process";import{confirm as r,input as i,select as a}from"@inquirer/prompts";import{sep as o}from"node:path";import{readdir as s}from"node:fs/promises";var c=`2.31.0`;const l={help:{type:`boolean`,short:`h`,default:!1,description:`Show help (prints this message)`},version:{type:`boolean`,short:`v`,default:!1,description:`Show version number`},quiet:{type:`boolean`,short:`q`,default:!1,description:`Skip interactive prompts (e.g. version update check)`}};function u(t){t.options={...l,...t.options};let n=e(t),{values:r}=n;r.version&&(console.log(c),process.exit(0));let i=t.commands?`
|
|
2
2
|
|
|
3
3
|
Commands:
|
|
4
4
|
${Object.entries(t.commands).map(([e,t])=>`${e.padEnd(30,` `)} ${t}`).join(`
|
|
@@ -10,4 +10,4 @@ Options:
|
|
|
10
10
|
`)}
|
|
11
11
|
`;return r.help&&(console.log(o),process.exit(0)),{...n,help:o}}const d=()=>{if(Promise.withResolvers)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=r,t=n}),reject:e,resolve:t}};var f=async(e,t,{print:r=!0,env:i={},signal:a,shell:o,cwd:s}={})=>{typeof t==`boolean`&&(r=t,t=void 0);let c=Error(),l=c.stack?c.stack.replace(/^.*/,` ...`):null,{promise:u,reject:f,resolve:p}=d(),m=n(e,t,{env:Object.assign(i,process.env),signal:a,shell:o,cwd:s});r&&(m.stdout.pipe(process.stdout),m.stderr.pipe(process.stderr));let h=``,g=``;m.stdout?.on(`data`,e=>{h+=e}),m.stderr?.on(`data`,e=>{g+=e});let _=r?`exit`:`close`;function v(e){m.removeListener(_,y),Object.assign(e,{pid:m.pid,stdout:h,stderr:g,status:null,signal:null}),f(e)}function y(n,r){m.removeListener(`error`,v);let i={pid:m.pid,stdout:h,stderr:g,status:n,signal:r};if(n!==0){let a=typeof t!=`boolean`&&` ${t?.join(` `)}`||``,o=r?Error(`${e}${a} exited with signal: ${r}`):Error(`${e}${a} exited with non-zero code: ${n}`);o.stack&&l&&(o.stack+=`\n${l}`),Object.assign(o,i),f(o)}else p(i)}return m.once(_,y),m.once(`error`,v),u};const p=async()=>{let{stdout:e}=await f(`git`,[`branch`,`--show-current`],{print:!1});return e.trim()},m=async()=>{let{stdout:e}=await f(`git`,[`rev-parse`,`--show-toplevel`],{print:!1});return e.trim()},h=async(e=`origin`)=>{try{let{stdout:t}=await f(`git`,[`config`,`--get`,`remote.${e}.url`],{print:!1});return t.trim()}catch{return``}},g=async e=>{let{stdout:t}=await f(`git`,[`diff`,`origin/master..`,e],{print:!1});return t},_=async e=>{try{return await f(`git`,[`check-ignore`,e],{print:!1}),!0}catch{return!1}};function v(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}Symbol.dispose??=Symbol.for(`nodejs.dispose`),Symbol.asyncDispose??=Symbol.for(`nodejs.asyncDispose`);let y;const b=()=>y?.();function x(){return process.once(`beforeExit`,b),{[Symbol.dispose](){process.off(`beforeExit`,b),y=void 0}}}async function S(e,...t){try{try{var n=v();n.u(x());let r=e(...t);return y=r.cancel,await r}catch(e){n.e=e}finally{n.d()}}catch(e){e instanceof Error&&[`CancelPromptError`,`ExitPromptError`].includes(e.constructor.name)&&Y(`Cancelled! 👋`),Y(e);return}}function C(...e){return S(a,...e)}function w(...e){return S(i,...e)}const T=e=>e.charAt(0).toUpperCase()+e.slice(1).split(/(?=[A-Z])/).join(` `);function E(){return C({message:`Which environment do you want to use?`,choices:V.map(e=>({name:T(e),value:e})),default:`expManager`})}async function D(e){return C({message:`Using from autorepo, Which app do you want to use?`,choices:(await s(`${e}${o}apps`)).filter(e=>!e.startsWith(`.`)&&!e.endsWith(`-e2e`)).map(e=>({name:e,value:e}))})}async function O(){let e=await m(),t=e.split(o).pop();return t===`autorepo`?D(e):w({message:`Enter the service name:`,default:t})}function k(e=`default`){return w({message:`Enter your simulator id (Press enter to pass):`,default:e})}async function A(e=`8080`,t=!1){return w({message:`Enter the ${t?`local `:``}port:`,default:e,validate(e){return/^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/.test(e)?!0:`Please enter a valid port number`}})}async function j(e=`5432`){return A(e,!0)}const M={cluster:E,variationId:k,service:O,port:(e=`8080`)=>A(e),"local-port":j};async function N(e,t){for(let n of t){let t=typeof n==`object`?n.option:n,r=typeof n==`object`?n.defaultVal:void 0;if(typeof t!=`string`)throw Error(`Invalid option ${String(t)}`);let i=M[t];if(!i)throw Error(`No value getter for ${String(t)}`);e[t]??=await i(r)}return e}async function P(e,t=!0){return S(r,{message:e,default:t})}const F={prodUs:[`us-prod-autofleet`,`us-central1`,`autofleet-production`],prodEu:[`eu-prod-autofleet`,`europe-west1`,`autofleetprod`],prodJp:[`jp-autofleet`,`asia-northeast1`,`autofleet-japan`]},I={dev1:[`dev-cluster-2`,`europe-west1`,`dev1-experiment-manager`],e2eManager:[`e2e-cluster-2`,`europe-west1`,`e2e-project-1`],expManager:[`af-experiment-manager`,`europe-west1`]},L={staging:[`stg-autofleet`,`europe-west1`,`autofleet-staging`],loadTest:[`lt-autofleet-production`,`asia-northeast1`,`load-testing-428806`]},R={osrmProd:[`maps-prod`,`europe-west1`,`af-mapping`]},z={...F,...I,...L,...R},B={staging:`europe-west1`},V=Object.keys(z),H=async e=>{let t=z[e];if(!t)throw Error(`Cluster name ${e} does not exist!`);let[n,r,i]=t;return F[e]&&!await P(`❌❌ Are you sure you want to run this command on ${e}? ❌❌`,!1)?(console.log(`Aborting...`),process.exit(1)):{name:n,region:r,project:i}},U=({newFilePath:e,filePath:n,linesToReplace:r})=>{let i=t.readFileSync(n,`utf8`);for(let{find:e,replace:t}of r)i=i.replace(e,t);t.writeFileSync(e,i)};async function W(){try{let{stdout:e}=await f(`kubectl`,[`config`,`current-context`],{print:!1});return e.trim()}catch{return null}}const G=async e=>{let{name:t,region:n,project:r}=await H(e),i=`gke_${r||t}_${n}_${t}`;return await W()===i?(console.log(`Already connected to ${e}, skipping connection to cluster...`),{name:t,region:n,project:r}):(await f(`gcloud`,[`container`,`clusters`,`get-credentials`,t,`--region`,n,`--project`,r||t],{print:!1}),console.log(`Switched to ${e} successfully`),{name:t,region:n,project:r})};async function K(){try{let{stdout:e}=await f(`kubectl`,[`config`,`view`,`--minify`,`--output`,`jsonpath={..namespace}`],{print:!1});return e.trim()}catch{return`default`}}const q=async({clusterName:e,variationId:t})=>(await G(e),`--namespace=${t}`),J=e=>{let t=e.split(`
|
|
12
12
|
`).filter(Boolean);t.shift();let n=t.map(e=>{let[t,n,r,i,a,o]=e.split(/(\s+)/).map(e=>e.trim()).filter(Boolean);return`${t.replace(/-/g,`_`).toUpperCase()}_SERVICE_HOST=${i}`});return n=n.filter(e=>!e.includes(`none`)&&!e.includes(`undefined`)),n};function Y(e,t){return e instanceof Error||(e=Error(e)),console.error(e),t&&console.log(t),process.exit(1)}const X=e=>Object.keys(I).includes(e),Z=e=>B[e]||z[e][1];export{d as C,f as S,c as T,g as _,K as a,h as b,J as c,D as d,j as f,C as g,w as h,Y as i,U as l,P as m,q as n,Z as o,k as p,G as r,X as s,V as t,N as u,p as v,u as w,_ as x,m as y};
|
|
13
|
-
//# sourceMappingURL=utils-
|
|
13
|
+
//# sourceMappingURL=utils-BOPv1fAz.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils-COC28l4j.js","names":["parseArgs","nativeParseArgs","packageJson.version","reject!: PromiseWithResolvers<T>['reject']","resolve!: PromiseWithResolvers<T>['resolve']","result: SpawnResult","signal","asyncSpawn","path","cancelFn: (() => void) | undefined","asyncSpawn"],"sources":["../package.json","../bin/utils/parser.ts","../bin/utils/promise.ts","../bin/utils/asyncSpawn.ts","../bin/utils/git.ts","../bin/utils/inquirer.ts","../bin/utils/index.ts"],"sourcesContent":["","import { parseArgs as nativeParseArgs, type ParseArgsConfig } from 'node:util';\nimport packageJson from '../../package.json' with { type: 'json' };\n\ntype ParseArgsOptionConfig = NonNullable<ParseArgsConfig['options']>[string] & { description: string; };\ntype ParseArgsParams = Omit<ParseArgsConfig, 'options'> & { binName: string; options: Record<string, ParseArgsOptionConfig>; commands?: Record<string, string>; };\n\nconst GLOBAL_OPTIONS = {\n help: {\n type: 'boolean',\n short: 'h',\n default: false,\n description: 'Show help (prints this message)',\n },\n version: {\n type: 'boolean',\n short: 'v',\n default: false,\n description: 'Show version number',\n },\n quiet: {\n type: 'boolean',\n short: 'q',\n default: false,\n description: 'Skip interactive prompts (e.g. version update check)',\n },\n} satisfies ParseArgsParams['options'];\n\ntype Expanded<T extends ParseArgsParams> = T & { options: T['options'] & typeof GLOBAL_OPTIONS; };\ntype Parsed<T extends ParseArgsParams> = ReturnType<typeof nativeParseArgs<Expanded<T>>> & { help: string; };\n\nexport default function parseArgs<T extends ParseArgsParams = ParseArgsParams>(params: T): Parsed<T> {\n params.options = { ...GLOBAL_OPTIONS, ...params.options };\n const data = nativeParseArgs(params as Expanded<T>);\n const { values } = data;\n if ((values as { version: boolean; }).version) {\n console.log(packageJson.version);\n process.exit(0);\n }\n\n const commands = !params.commands ? '' : `\n\nCommands:\n ${Object.entries(params.commands).map(([command, example]) => `${command.padEnd(30, ' ')} ${example}`).join('\\n ')}\n`;\n\n const longestDescriptionLength = Math.max.apply(null, Object.values(params.options).map(({ description }) => description.length));\n\n const help = `\n${params.binName} ${commands ? '[command] ' : ''}<options>${commands}\nOptions:\n ${Object.entries(params.options).map(([option, { description, type, short }]) => {\n const key = short ? `--${option}, -${short}` : `--${option}`;\n return `${key.padEnd(30, ' ')} ${description.padEnd(longestDescriptionLength + 10, ' ')} [${type}]`;\n }).join('\\n ')}\n`;\n\n if ((values as { help: boolean; }).help) {\n console.log(help);\n process.exit(0);\n }\n\n return { ...data, help };\n}\n","declare global {\n interface PromiseWithResolvers<T> {\n promise: Promise<T>;\n resolve: (value: T | PromiseLike<T>) => void;\n reject: (reason?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n interface PromiseConstructor {\n /**\n * Creates a new Promise and returns it in an object, along with its resolve and reject functions.\n * @returns An object with the properties `promise`, `resolve`, and `reject`.\n *\n * ```ts\n * const { promise, resolve, reject } = Promise.withResolvers<T>();\n * ```\n */\n withResolvers<T>(): PromiseWithResolvers<T>;\n }\n}\n\nexport const createDeferredPromise = <T>() => {\n if (Promise.withResolvers) {\n return Promise.withResolvers<T>();\n }\n let reject!: PromiseWithResolvers<T>['reject'];\n let resolve!: PromiseWithResolvers<T>['resolve'];\n const promise = new Promise<T>((res, rej) => {\n reject = rej;\n resolve = res;\n });\n return { promise, reject, resolve };\n};\n","import { spawn } from 'node:child_process';\nimport { createDeferredPromise } from './promise.js';\n\ninterface SpawnResult {\n pid?: number;\n stdout: string;\n stderr: string;\n status: number | null;\n signal: string | null;\n}\n\nexport default async (\n command: string,\n args?: boolean | readonly string[],\n {\n print = true,\n env = {},\n signal,\n shell,\n cwd,\n }: { print?: boolean; env?: NodeJS.ProcessEnv; signal?: AbortSignal; shell?: string | boolean; cwd?: string; } = {},\n) => {\n if (typeof args === 'boolean') {\n print = args;\n args = undefined;\n }\n const stubError = new Error();\n const callerStack = stubError.stack ? stubError.stack.replace(/^.*/, ' ...') : null;\n const { promise, reject, resolve } = createDeferredPromise<SpawnResult>();\n const child = spawn(command, args, { env: Object.assign(env, process.env), signal, shell, cwd });\n if (print) {\n child.stdout.pipe(process.stdout);\n child.stderr.pipe(process.stderr);\n }\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (data) => {\n stdout += data;\n });\n child.stderr?.on('data', (data) => {\n stderr += data;\n });\n const completionEventName = print ? 'exit' : 'close';\n function errorListener(error: Error) {\n child.removeListener(completionEventName, completionListener);\n Object.assign(error, {\n pid: child.pid,\n stdout,\n stderr,\n status: null,\n signal: null,\n });\n reject(error);\n }\n function completionListener(code: number | null, signal: string | null) {\n child.removeListener('error', errorListener);\n const result: SpawnResult = {\n pid: child.pid,\n stdout,\n stderr,\n status: code,\n signal,\n };\n if (code !== 0) {\n const argumentString = (typeof args !== 'boolean' && ` ${args?.join(' ')}`) || '';\n const error = signal\n ? new Error(`${command}${argumentString} exited with signal: ${signal}`)\n : new Error(`${command}${argumentString} exited with non-zero code: ${code}`);\n if (error.stack && callerStack) {\n error.stack += `\\n${callerStack}`;\n }\n Object.assign(error, result);\n reject(error);\n } else {\n resolve(result);\n }\n }\n\n child.once(completionEventName, completionListener);\n child.once('error', errorListener);\n return promise;\n};\n","import asyncSpawn from './asyncSpawn.js';\n\nexport const getCurrentBranch = async () => {\n const { stdout: currentBranch } = await asyncSpawn('git', ['branch', '--show-current'], { print: false });\n return currentBranch.trim();\n};\n\nexport const getGitPath = async () => {\n const { stdout: gitPath } = await asyncSpawn('git', ['rev-parse', '--show-toplevel'], { print: false });\n return gitPath.trim();\n};\n\nexport const getRemoteUrl = async (remote = 'origin') => {\n try {\n const { stdout } = await asyncSpawn('git', ['config', '--get', `remote.${remote}.url`], { print: false });\n return stdout.trim();\n } catch {\n return '';\n }\n};\n\nexport const getChangesOfFile = async (filePath: string) => {\n const { stdout: changes } = await asyncSpawn('git', ['diff', 'origin/master..', filePath], { print: false });\n return changes;\n};\n\nexport const isPathIgnored = async (path: string) => {\n try {\n await asyncSpawn('git', ['check-ignore', path], { print: false });\n return true;\n } catch {\n return false;\n }\n};\n","import { confirm, input, select } from '@inquirer/prompts';\nimport type { Prompt } from '@inquirer/type';\nimport { getGitPath } from './git.js';\nimport { SUPPORTED_CLUSTERS, endWithError } from './index.js';\nimport { sep } from 'node:path';\nimport { readdir } from 'node:fs/promises';\n\ndeclare global {\n interface SymbolConstructor {\n /** A method that is used to release resources held by an object. Called by the semantics of the `using` statement. */\n readonly dispose: unique symbol;\n /** A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. */\n readonly asyncDispose: unique symbol;\n }\n}\n// @ts-expect-error polyfill for node < 18.18\nSymbol.dispose ??= Symbol.for('nodejs.dispose');\n// @ts-expect-error polyfill for node < 18.18\nSymbol.asyncDispose ??= Symbol.for('nodejs.asyncDispose');\nlet cancelFn: (() => void) | undefined;\nconst handler = () => cancelFn?.();\nfunction addExitListener() {\n process.once('beforeExit', handler);\n return {\n [Symbol.dispose]() {\n process.off('beforeExit', handler);\n cancelFn = undefined;\n },\n };\n}\n\nasync function inquirerWrapper<Value, Config>(fn: Prompt<Value, Config>, ...params: Parameters<Prompt<Value, Config>>) {\n try {\n using _ = addExitListener();\n const result = fn(...params);\n cancelFn = result.cancel;\n return await result;\n } catch (error) {\n if (error instanceof Error && ['CancelPromptError', 'ExitPromptError'].includes(error.constructor.name)) {\n endWithError('Cancelled! 👋');\n }\n endWithError(error as Error);\n return undefined;\n }\n}\n\nexport function safeSelect<Value = string>(...params: Parameters<typeof select<Value>>) {\n return inquirerWrapper(select, ...params);\n}\n\nexport function safeInput(...params: Parameters<typeof input>) {\n return inquirerWrapper(input, ...params);\n}\n\nconst splitWordAtCapital = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).split(/(?=[A-Z])/).join(' ');\n\nfunction getEnvironment() {\n return safeSelect({\n message: 'Which environment do you want to use?',\n choices: SUPPORTED_CLUSTERS.map(cluster => ({ name: splitWordAtCapital(cluster), value: cluster })),\n default: 'expManager',\n });\n}\n\nexport async function getAutorepoAppName(currentServicePath: string) {\n const appNames = (await readdir(`${currentServicePath}${sep}apps`)).filter(name => !name.startsWith('.') && !name.endsWith('-e2e'));\n return safeSelect({\n message: 'Using from autorepo, Which app do you want to use?',\n choices: appNames.map(app => ({ name: app, value: app })),\n });\n}\n\nasync function getServiceName() {\n const gitPath = await getGitPath();\n const defaultValue = gitPath.split(sep).pop();\n if (defaultValue === 'autorepo') {\n return getAutorepoAppName(gitPath);\n }\n return safeInput({ message: 'Enter the service name:', default: defaultValue });\n}\n\nexport function getVariationId(defaultVal = 'default') {\n return safeInput({ message: 'Enter your simulator id (Press enter to pass):', default: defaultVal });\n}\n\nasync function getPort(defaultVal = '8080', isLocal = false) {\n return safeInput({\n message: `Enter the ${isLocal ? 'local ' : ''}port:`,\n default: defaultVal,\n validate(value) {\n // Regex source: https://stackoverflow.com/a/12968117\n if (!/^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/.test(value)) {\n return 'Please enter a valid port number';\n }\n return true;\n },\n });\n}\n\nexport async function getLocalPort(defaultVal = '5432') {\n return getPort(defaultVal, true);\n}\n\nconst VALUE_GETTER_MAP = {\n cluster: getEnvironment,\n variationId: getVariationId,\n service: getServiceName,\n port: (defaultVal = '8080') => getPort(defaultVal),\n 'local-port': getLocalPort,\n} as const;\n\nexport async function fillMissingRequiredValues<T extends { [key in keyof typeof VALUE_GETTER_MAP]?: string }>(values: T, requiredValues: (keyof T | { option: keyof T; defaultVal: string; })[]) {\n for (const value of requiredValues) {\n const option = typeof value === 'object' ? value.option : value;\n const defaultVal = typeof value === 'object' ? value.defaultVal : undefined;\n if (typeof option !== 'string') {\n throw new Error(`Invalid option ${String(option)}`);\n }\n const getter = VALUE_GETTER_MAP[option as keyof typeof VALUE_GETTER_MAP];\n if (!getter) {\n throw new Error(`No value getter for ${String(option)}`);\n }\n\n values[option] ??= await getter(defaultVal) as T[keyof T & string];\n }\n return values;\n}\n\nexport async function promptForConfirmation(message: string, defaultVal = true) {\n return inquirerWrapper(confirm, { message, default: defaultVal });\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport asyncSpawn from './asyncSpawn.js';\nimport { promptForConfirmation } from './inquirer.js';\n\nconst IP_LINE_SUFFIX = 'SERVICE_HOST';\nconst PROD_CLUSTER_TO_CMD_MAP = {\n prodUs: ['us-prod-autofleet', 'us-central1', 'autofleet-production'],\n prodEu: ['eu-prod-autofleet', 'europe-west1', 'autofleetprod'],\n prodJp: ['jp-autofleet', 'asia-northeast1', 'autofleet-japan'],\n};\nconst SIMULATION_CLUSTER_TO_CMD_MAP = {\n dev1: ['dev-cluster-2', 'europe-west1', 'dev1-experiment-manager'],\n e2eManager: ['e2e-cluster-2', 'europe-west1', 'e2e-project-1'],\n expManager: ['af-experiment-manager', 'europe-west1'],\n};\nconst STAGING_CLUSTER_TO_CMD_MAP = {\n staging: ['stg-autofleet', 'europe-west1', 'autofleet-staging'],\n loadTest: ['lt-autofleet-production', 'asia-northeast1', 'load-testing-428806'],\n};\nconst MAPPING_CLUSTER_TO_CMD_MAP = {\n osrmProd: ['maps-prod', 'europe-west1', 'af-mapping'],\n};\nconst CLUSTER_TO_CMD_MAP = {\n ...PROD_CLUSTER_TO_CMD_MAP,\n ...SIMULATION_CLUSTER_TO_CMD_MAP,\n ...STAGING_CLUSTER_TO_CMD_MAP,\n ...MAPPING_CLUSTER_TO_CMD_MAP,\n};\n\nconst CLUSTER_TO_REDIS_REGION = {\n staging: 'europe-west1',\n};\n\nexport const SUPPORTED_CLUSTERS = Object.keys(CLUSTER_TO_CMD_MAP) as (keyof typeof CLUSTER_TO_CMD_MAP)[];\n\nconst getClusterDetails = async (clusterName: string) => {\n const command = CLUSTER_TO_CMD_MAP[clusterName as keyof typeof CLUSTER_TO_CMD_MAP];\n if (!command) {\n throw new Error(`Cluster name ${clusterName} does not exist!`);\n }\n const [name, region, project] = command;\n\n if (\n PROD_CLUSTER_TO_CMD_MAP[clusterName as keyof typeof PROD_CLUSTER_TO_CMD_MAP]\n && !(await promptForConfirmation(`❌❌ Are you sure you want to run this command on ${clusterName}? ❌❌`, false))) {\n console.log('Aborting...');\n return process.exit(1);\n }\n\n return { name, region, project };\n};\n\nexport const replaceInFile = ({ newFilePath, filePath, linesToReplace }: { newFilePath: string; filePath: string; linesToReplace: { find: string; replace: string; }[]; }) => {\n let fileAsString = fs.readFileSync(filePath, 'utf8');\n for (const { find, replace } of linesToReplace) {\n fileAsString = fileAsString.replace(find, replace);\n }\n fs.writeFileSync(newFilePath, fileAsString);\n};\n\nexport async function getCurrentCluster() {\n try {\n const { stdout } = await asyncSpawn('kubectl', ['config', 'current-context'], { print: false });\n return stdout.trim();\n } catch {\n return null;\n }\n}\n\nexport const connectToCluster = async (clusterName: string) => {\n const { name, region, project } = await getClusterDetails(clusterName);\n\n const expectedContext = `gke_${project || name}_${region}_${name}`;\n const currentContext = await getCurrentCluster();\n if (currentContext === expectedContext) {\n console.log(`Already connected to ${clusterName}, skipping connection to cluster...`);\n return { name, region, project };\n }\n\n await asyncSpawn('gcloud', ['container', 'clusters', 'get-credentials', name, '--region', region, '--project', project || name], { print: false });\n\n console.log(`Switched to ${clusterName} successfully`);\n\n return { name, region, project };\n};\n\nexport async function getCurrentNamespace() {\n try {\n const { stdout } = await asyncSpawn('kubectl', ['config', 'view', '--minify', '--output', 'jsonpath={..namespace}'], { print: false });\n return stdout.trim();\n } catch {\n return 'default'; // If no namespace is set, it defaults to 'default'\n }\n}\n\nexport const connectAndGetPrefix = async ({ clusterName, variationId }: { clusterName: string; variationId: string; }) => {\n await connectToCluster(clusterName);\n return `--namespace=${variationId}`;\n};\n\nexport const parseIps = (ips: string) => {\n const ipLines = ips.split('\\n').filter(Boolean);\n ipLines.shift();\n\n let formattedIps = ipLines.map((ipLine) => {\n const [name, _type, _clusterIp, externalIp, _port, _age] = ipLine.split(/(\\s+)/).map(s => s.trim()).filter(Boolean);\n const serviceName = name.replace(/-/g, '_').toUpperCase();\n const formattedLine = `${serviceName}_${IP_LINE_SUFFIX}=${externalIp}`;\n return formattedLine;\n });\n formattedIps = formattedIps.filter(formattedIp => !formattedIp.includes('none') && !formattedIp.includes('undefined'));\n return formattedIps;\n};\n\nexport function endWithError(error: string | Error, helpText?: string): never {\n if (!(error instanceof Error)) {\n error = new Error(error);\n }\n console.error(error);\n if (helpText) {\n console.log(helpText);\n }\n return process.exit(1);\n}\n\nexport const isSimulationCluster = (clusterName: string) => Object.keys(SIMULATION_CLUSTER_TO_CMD_MAP).includes(clusterName);\n\nexport const getRedisRegion = (clusterName: string) => CLUSTER_TO_REDIS_REGION[clusterName as keyof typeof CLUSTER_TO_REDIS_REGION]\n || CLUSTER_TO_CMD_MAP[clusterName as keyof typeof CLUSTER_TO_CMD_MAP][1];\n"],"mappings":"qQCMA,MAAM,EAAiB,CACrB,KAAM,CACJ,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,kCACd,CACD,QAAS,CACP,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,sBACd,CACD,MAAO,CACL,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,uDACd,CACF,CAKD,SAAwBA,EAAuD,EAAsB,CACnG,EAAO,QAAU,CAAE,GAAG,EAAgB,GAAG,EAAO,QAAS,CACzD,IAAM,EAAOC,EAAgB,EAAsB,CAC7C,CAAE,UAAW,EACd,EAAiC,UACpC,QAAQ,IAAIC,EAAoB,CAChC,QAAQ,KAAK,EAAE,EAGjB,IAAM,EAAY,EAAO,SAAgB;;;IAGvC,OAAO,QAAQ,EAAO,SAAS,CAAC,KAAK,CAAC,EAAS,KAAa,GAAG,EAAQ,OAAO,GAAI,IAAI,CAAC,GAAG,IAAU,CAAC,KAAK;IAAO,CAAC;EAHhF,GAM9B,EAA2B,KAAK,IAAI,MAAM,KAAM,OAAO,OAAO,EAAO,QAAQ,CAAC,KAAK,CAAE,iBAAkB,EAAY,OAAO,CAAC,CAE3H,EAAO;EACb,EAAO,QAAQ,GAAG,EAAW,aAAe,GAAG,WAAW,EAAS;;IAEjE,OAAO,QAAQ,EAAO,QAAQ,C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,EAE1B,QAAQ,MAAM,EAAM,CAChB,GACF,QAAQ,IAAI,EAAS,CAEhB,QAAQ,KAAK,EAAE,CAGxB,MAAa,EAAuB,GAAwB,OAAO,KAAK,EAA8B,CAAC,SAAS,EAAY,CAE/G,EAAkB,GAAwB,EAAwB,IAC1E,EAAmB,GAAgD"}
|
|
1
|
+
{"version":3,"file":"utils-BOPv1fAz.js","names":["parseArgs","nativeParseArgs","packageJson.version","reject!: PromiseWithResolvers<T>['reject']","resolve!: PromiseWithResolvers<T>['resolve']","result: SpawnResult","signal","asyncSpawn","path","cancelFn: (() => void) | undefined","asyncSpawn"],"sources":["../package.json","../bin/utils/parser.ts","../bin/utils/promise.ts","../bin/utils/asyncSpawn.ts","../bin/utils/git.ts","../bin/utils/inquirer.ts","../bin/utils/index.ts"],"sourcesContent":["","import { parseArgs as nativeParseArgs, type ParseArgsConfig } from 'node:util';\nimport packageJson from '../../package.json' with { type: 'json' };\n\ntype ParseArgsOptionConfig = NonNullable<ParseArgsConfig['options']>[string] & { description: string; };\ntype ParseArgsParams = Omit<ParseArgsConfig, 'options'> & { binName: string; options: Record<string, ParseArgsOptionConfig>; commands?: Record<string, string>; };\n\nconst GLOBAL_OPTIONS = {\n help: {\n type: 'boolean',\n short: 'h',\n default: false,\n description: 'Show help (prints this message)',\n },\n version: {\n type: 'boolean',\n short: 'v',\n default: false,\n description: 'Show version number',\n },\n quiet: {\n type: 'boolean',\n short: 'q',\n default: false,\n description: 'Skip interactive prompts (e.g. version update check)',\n },\n} satisfies ParseArgsParams['options'];\n\ntype Expanded<T extends ParseArgsParams> = T & { options: T['options'] & typeof GLOBAL_OPTIONS; };\ntype Parsed<T extends ParseArgsParams> = ReturnType<typeof nativeParseArgs<Expanded<T>>> & { help: string; };\n\nexport default function parseArgs<T extends ParseArgsParams = ParseArgsParams>(params: T): Parsed<T> {\n params.options = { ...GLOBAL_OPTIONS, ...params.options };\n const data = nativeParseArgs(params as Expanded<T>);\n const { values } = data;\n if ((values as { version: boolean; }).version) {\n console.log(packageJson.version);\n process.exit(0);\n }\n\n const commands = !params.commands ? '' : `\n\nCommands:\n ${Object.entries(params.commands).map(([command, example]) => `${command.padEnd(30, ' ')} ${example}`).join('\\n ')}\n`;\n\n const longestDescriptionLength = Math.max.apply(null, Object.values(params.options).map(({ description }) => description.length));\n\n const help = `\n${params.binName} ${commands ? '[command] ' : ''}<options>${commands}\nOptions:\n ${Object.entries(params.options).map(([option, { description, type, short }]) => {\n const key = short ? `--${option}, -${short}` : `--${option}`;\n return `${key.padEnd(30, ' ')} ${description.padEnd(longestDescriptionLength + 10, ' ')} [${type}]`;\n }).join('\\n ')}\n`;\n\n if ((values as { help: boolean; }).help) {\n console.log(help);\n process.exit(0);\n }\n\n return { ...data, help };\n}\n","declare global {\n interface PromiseWithResolvers<T> {\n promise: Promise<T>;\n resolve: (value: T | PromiseLike<T>) => void;\n reject: (reason?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n interface PromiseConstructor {\n /**\n * Creates a new Promise and returns it in an object, along with its resolve and reject functions.\n * @returns An object with the properties `promise`, `resolve`, and `reject`.\n *\n * ```ts\n * const { promise, resolve, reject } = Promise.withResolvers<T>();\n * ```\n */\n withResolvers<T>(): PromiseWithResolvers<T>;\n }\n}\n\nexport const createDeferredPromise = <T>() => {\n if (Promise.withResolvers) {\n return Promise.withResolvers<T>();\n }\n let reject!: PromiseWithResolvers<T>['reject'];\n let resolve!: PromiseWithResolvers<T>['resolve'];\n const promise = new Promise<T>((res, rej) => {\n reject = rej;\n resolve = res;\n });\n return { promise, reject, resolve };\n};\n","import { spawn } from 'node:child_process';\nimport { createDeferredPromise } from './promise.js';\n\ninterface SpawnResult {\n pid?: number;\n stdout: string;\n stderr: string;\n status: number | null;\n signal: string | null;\n}\n\nexport default async (\n command: string,\n args?: boolean | readonly string[],\n {\n print = true,\n env = {},\n signal,\n shell,\n cwd,\n }: { print?: boolean; env?: NodeJS.ProcessEnv; signal?: AbortSignal; shell?: string | boolean; cwd?: string; } = {},\n) => {\n if (typeof args === 'boolean') {\n print = args;\n args = undefined;\n }\n const stubError = new Error();\n const callerStack = stubError.stack ? stubError.stack.replace(/^.*/, ' ...') : null;\n const { promise, reject, resolve } = createDeferredPromise<SpawnResult>();\n const child = spawn(command, args, { env: Object.assign(env, process.env), signal, shell, cwd });\n if (print) {\n child.stdout.pipe(process.stdout);\n child.stderr.pipe(process.stderr);\n }\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (data) => {\n stdout += data;\n });\n child.stderr?.on('data', (data) => {\n stderr += data;\n });\n const completionEventName = print ? 'exit' : 'close';\n function errorListener(error: Error) {\n child.removeListener(completionEventName, completionListener);\n Object.assign(error, {\n pid: child.pid,\n stdout,\n stderr,\n status: null,\n signal: null,\n });\n reject(error);\n }\n function completionListener(code: number | null, signal: string | null) {\n child.removeListener('error', errorListener);\n const result: SpawnResult = {\n pid: child.pid,\n stdout,\n stderr,\n status: code,\n signal,\n };\n if (code !== 0) {\n const argumentString = (typeof args !== 'boolean' && ` ${args?.join(' ')}`) || '';\n const error = signal\n ? new Error(`${command}${argumentString} exited with signal: ${signal}`)\n : new Error(`${command}${argumentString} exited with non-zero code: ${code}`);\n if (error.stack && callerStack) {\n error.stack += `\\n${callerStack}`;\n }\n Object.assign(error, result);\n reject(error);\n } else {\n resolve(result);\n }\n }\n\n child.once(completionEventName, completionListener);\n child.once('error', errorListener);\n return promise;\n};\n","import asyncSpawn from './asyncSpawn.js';\n\nexport const getCurrentBranch = async () => {\n const { stdout: currentBranch } = await asyncSpawn('git', ['branch', '--show-current'], { print: false });\n return currentBranch.trim();\n};\n\nexport const getGitPath = async () => {\n const { stdout: gitPath } = await asyncSpawn('git', ['rev-parse', '--show-toplevel'], { print: false });\n return gitPath.trim();\n};\n\nexport const getRemoteUrl = async (remote = 'origin') => {\n try {\n const { stdout } = await asyncSpawn('git', ['config', '--get', `remote.${remote}.url`], { print: false });\n return stdout.trim();\n } catch {\n return '';\n }\n};\n\nexport const getChangesOfFile = async (filePath: string) => {\n const { stdout: changes } = await asyncSpawn('git', ['diff', 'origin/master..', filePath], { print: false });\n return changes;\n};\n\nexport const isPathIgnored = async (path: string) => {\n try {\n await asyncSpawn('git', ['check-ignore', path], { print: false });\n return true;\n } catch {\n return false;\n }\n};\n","import { confirm, input, select } from '@inquirer/prompts';\nimport type { Prompt } from '@inquirer/type';\nimport { getGitPath } from './git.js';\nimport { SUPPORTED_CLUSTERS, endWithError } from './index.js';\nimport { sep } from 'node:path';\nimport { readdir } from 'node:fs/promises';\n\ndeclare global {\n interface SymbolConstructor {\n /** A method that is used to release resources held by an object. Called by the semantics of the `using` statement. */\n readonly dispose: unique symbol;\n /** A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. */\n readonly asyncDispose: unique symbol;\n }\n}\n// @ts-expect-error polyfill for node < 18.18\nSymbol.dispose ??= Symbol.for('nodejs.dispose');\n// @ts-expect-error polyfill for node < 18.18\nSymbol.asyncDispose ??= Symbol.for('nodejs.asyncDispose');\nlet cancelFn: (() => void) | undefined;\nconst handler = () => cancelFn?.();\nfunction addExitListener() {\n process.once('beforeExit', handler);\n return {\n [Symbol.dispose]() {\n process.off('beforeExit', handler);\n cancelFn = undefined;\n },\n };\n}\n\nasync function inquirerWrapper<Value, Config>(fn: Prompt<Value, Config>, ...params: Parameters<Prompt<Value, Config>>) {\n try {\n using _ = addExitListener();\n const result = fn(...params);\n cancelFn = result.cancel;\n return await result;\n } catch (error) {\n if (error instanceof Error && ['CancelPromptError', 'ExitPromptError'].includes(error.constructor.name)) {\n endWithError('Cancelled! 👋');\n }\n endWithError(error as Error);\n return undefined;\n }\n}\n\nexport function safeSelect<Value = string>(...params: Parameters<typeof select<Value>>) {\n return inquirerWrapper(select, ...params);\n}\n\nexport function safeInput(...params: Parameters<typeof input>) {\n return inquirerWrapper(input, ...params);\n}\n\nconst splitWordAtCapital = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).split(/(?=[A-Z])/).join(' ');\n\nfunction getEnvironment() {\n return safeSelect({\n message: 'Which environment do you want to use?',\n choices: SUPPORTED_CLUSTERS.map(cluster => ({ name: splitWordAtCapital(cluster), value: cluster })),\n default: 'expManager',\n });\n}\n\nexport async function getAutorepoAppName(currentServicePath: string) {\n const appNames = (await readdir(`${currentServicePath}${sep}apps`)).filter(name => !name.startsWith('.') && !name.endsWith('-e2e'));\n return safeSelect({\n message: 'Using from autorepo, Which app do you want to use?',\n choices: appNames.map(app => ({ name: app, value: app })),\n });\n}\n\nasync function getServiceName() {\n const gitPath = await getGitPath();\n const defaultValue = gitPath.split(sep).pop();\n if (defaultValue === 'autorepo') {\n return getAutorepoAppName(gitPath);\n }\n return safeInput({ message: 'Enter the service name:', default: defaultValue });\n}\n\nexport function getVariationId(defaultVal = 'default') {\n return safeInput({ message: 'Enter your simulator id (Press enter to pass):', default: defaultVal });\n}\n\nasync function getPort(defaultVal = '8080', isLocal = false) {\n return safeInput({\n message: `Enter the ${isLocal ? 'local ' : ''}port:`,\n default: defaultVal,\n validate(value) {\n // Regex source: https://stackoverflow.com/a/12968117\n if (!/^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/.test(value)) {\n return 'Please enter a valid port number';\n }\n return true;\n },\n });\n}\n\nexport async function getLocalPort(defaultVal = '5432') {\n return getPort(defaultVal, true);\n}\n\nconst VALUE_GETTER_MAP = {\n cluster: getEnvironment,\n variationId: getVariationId,\n service: getServiceName,\n port: (defaultVal = '8080') => getPort(defaultVal),\n 'local-port': getLocalPort,\n} as const;\n\nexport async function fillMissingRequiredValues<T extends { [key in keyof typeof VALUE_GETTER_MAP]?: string }>(values: T, requiredValues: (keyof T | { option: keyof T; defaultVal: string; })[]) {\n for (const value of requiredValues) {\n const option = typeof value === 'object' ? value.option : value;\n const defaultVal = typeof value === 'object' ? value.defaultVal : undefined;\n if (typeof option !== 'string') {\n throw new Error(`Invalid option ${String(option)}`);\n }\n const getter = VALUE_GETTER_MAP[option as keyof typeof VALUE_GETTER_MAP];\n if (!getter) {\n throw new Error(`No value getter for ${String(option)}`);\n }\n\n values[option] ??= await getter(defaultVal) as T[keyof T & string];\n }\n return values;\n}\n\nexport async function promptForConfirmation(message: string, defaultVal = true) {\n return inquirerWrapper(confirm, { message, default: defaultVal });\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport asyncSpawn from './asyncSpawn.js';\nimport { promptForConfirmation } from './inquirer.js';\n\nconst IP_LINE_SUFFIX = 'SERVICE_HOST';\nconst PROD_CLUSTER_TO_CMD_MAP = {\n prodUs: ['us-prod-autofleet', 'us-central1', 'autofleet-production'],\n prodEu: ['eu-prod-autofleet', 'europe-west1', 'autofleetprod'],\n prodJp: ['jp-autofleet', 'asia-northeast1', 'autofleet-japan'],\n};\nconst SIMULATION_CLUSTER_TO_CMD_MAP = {\n dev1: ['dev-cluster-2', 'europe-west1', 'dev1-experiment-manager'],\n e2eManager: ['e2e-cluster-2', 'europe-west1', 'e2e-project-1'],\n expManager: ['af-experiment-manager', 'europe-west1'],\n};\nconst STAGING_CLUSTER_TO_CMD_MAP = {\n staging: ['stg-autofleet', 'europe-west1', 'autofleet-staging'],\n loadTest: ['lt-autofleet-production', 'asia-northeast1', 'load-testing-428806'],\n};\nconst MAPPING_CLUSTER_TO_CMD_MAP = {\n osrmProd: ['maps-prod', 'europe-west1', 'af-mapping'],\n};\nconst CLUSTER_TO_CMD_MAP = {\n ...PROD_CLUSTER_TO_CMD_MAP,\n ...SIMULATION_CLUSTER_TO_CMD_MAP,\n ...STAGING_CLUSTER_TO_CMD_MAP,\n ...MAPPING_CLUSTER_TO_CMD_MAP,\n};\n\nconst CLUSTER_TO_REDIS_REGION = {\n staging: 'europe-west1',\n};\n\nexport const SUPPORTED_CLUSTERS = Object.keys(CLUSTER_TO_CMD_MAP) as (keyof typeof CLUSTER_TO_CMD_MAP)[];\n\nconst getClusterDetails = async (clusterName: string) => {\n const command = CLUSTER_TO_CMD_MAP[clusterName as keyof typeof CLUSTER_TO_CMD_MAP];\n if (!command) {\n throw new Error(`Cluster name ${clusterName} does not exist!`);\n }\n const [name, region, project] = command;\n\n if (\n PROD_CLUSTER_TO_CMD_MAP[clusterName as keyof typeof PROD_CLUSTER_TO_CMD_MAP]\n && !(await promptForConfirmation(`❌❌ Are you sure you want to run this command on ${clusterName}? ❌❌`, false))) {\n console.log('Aborting...');\n return process.exit(1);\n }\n\n return { name, region, project };\n};\n\nexport const replaceInFile = ({ newFilePath, filePath, linesToReplace }: { newFilePath: string; filePath: string; linesToReplace: { find: string; replace: string; }[]; }) => {\n let fileAsString = fs.readFileSync(filePath, 'utf8');\n for (const { find, replace } of linesToReplace) {\n fileAsString = fileAsString.replace(find, replace);\n }\n fs.writeFileSync(newFilePath, fileAsString);\n};\n\nexport async function getCurrentCluster() {\n try {\n const { stdout } = await asyncSpawn('kubectl', ['config', 'current-context'], { print: false });\n return stdout.trim();\n } catch {\n return null;\n }\n}\n\nexport const connectToCluster = async (clusterName: string) => {\n const { name, region, project } = await getClusterDetails(clusterName);\n\n const expectedContext = `gke_${project || name}_${region}_${name}`;\n const currentContext = await getCurrentCluster();\n if (currentContext === expectedContext) {\n console.log(`Already connected to ${clusterName}, skipping connection to cluster...`);\n return { name, region, project };\n }\n\n await asyncSpawn('gcloud', ['container', 'clusters', 'get-credentials', name, '--region', region, '--project', project || name], { print: false });\n\n console.log(`Switched to ${clusterName} successfully`);\n\n return { name, region, project };\n};\n\nexport async function getCurrentNamespace() {\n try {\n const { stdout } = await asyncSpawn('kubectl', ['config', 'view', '--minify', '--output', 'jsonpath={..namespace}'], { print: false });\n return stdout.trim();\n } catch {\n return 'default'; // If no namespace is set, it defaults to 'default'\n }\n}\n\nexport const connectAndGetPrefix = async ({ clusterName, variationId }: { clusterName: string; variationId: string; }) => {\n await connectToCluster(clusterName);\n return `--namespace=${variationId}`;\n};\n\nexport const parseIps = (ips: string) => {\n const ipLines = ips.split('\\n').filter(Boolean);\n ipLines.shift();\n\n let formattedIps = ipLines.map((ipLine) => {\n const [name, _type, _clusterIp, externalIp, _port, _age] = ipLine.split(/(\\s+)/).map(s => s.trim()).filter(Boolean);\n const serviceName = name.replace(/-/g, '_').toUpperCase();\n const formattedLine = `${serviceName}_${IP_LINE_SUFFIX}=${externalIp}`;\n return formattedLine;\n });\n formattedIps = formattedIps.filter(formattedIp => !formattedIp.includes('none') && !formattedIp.includes('undefined'));\n return formattedIps;\n};\n\nexport function endWithError(error: string | Error, helpText?: string): never {\n if (!(error instanceof Error)) {\n error = new Error(error);\n }\n console.error(error);\n if (helpText) {\n console.log(helpText);\n }\n return process.exit(1);\n}\n\nexport const isSimulationCluster = (clusterName: string) => Object.keys(SIMULATION_CLUSTER_TO_CMD_MAP).includes(clusterName);\n\nexport const getRedisRegion = (clusterName: string) => CLUSTER_TO_REDIS_REGION[clusterName as keyof typeof CLUSTER_TO_REDIS_REGION]\n || CLUSTER_TO_CMD_MAP[clusterName as keyof typeof CLUSTER_TO_CMD_MAP][1];\n"],"mappings":"qQCMA,MAAM,EAAiB,CACrB,KAAM,CACJ,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,kCACd,CACD,QAAS,CACP,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,sBACd,CACD,MAAO,CACL,KAAM,UACN,MAAO,IACP,QAAS,GACT,YAAa,uDACd,CACF,CAKD,SAAwBA,EAAuD,EAAsB,CACnG,EAAO,QAAU,CAAE,GAAG,EAAgB,GAAG,EAAO,QAAS,CACzD,IAAM,EAAOC,EAAgB,EAAsB,CAC7C,CAAE,UAAW,EACd,EAAiC,UACpC,QAAQ,IAAIC,EAAoB,CAChC,QAAQ,KAAK,EAAE,EAGjB,IAAM,EAAY,EAAO,SAAgB;;;IAGvC,OAAO,QAAQ,EAAO,SAAS,CAAC,KAAK,CAAC,EAAS,KAAa,GAAG,EAAQ,OAAO,GAAI,IAAI,CAAC,GAAG,IAAU,CAAC,KAAK;IAAO,CAAC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