@better-update/cli 0.9.0 → 0.10.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["idParam","projectIdParam","idParam","idParam","idParam","idParam","idParam","idParam","idParam","projectIdParam","idParam","idParam","idParam","idParam","idParam","idParam","projectIdParam","idParam","process","process","channelsCommand","channelsCommand","listCommand","listCommand","listCommand","createCommand","renameCommand","deleteCommand","process","asString","deleteCommand","getCommand","listCommand","uploadCommand","listCommand","getCommand","deleteCommand","uploadCommand","resolveNamedResourceId","resolveNamedResourceId","resolveNamedResourceIdBase","createCommand","resolveNamedResourceId","deleteCommand","listCommand","completeCommand","createCommand","resolveNamedResourceId","revertCommand","updateCommand","rolloutCommand","createCommand","updateCommand","completeCommand","revertCommand","updateCommand","resolveNamedResourceId","listCommand","createCommand","updateCommand","deleteCommand","rolloutCommand","CREDENTIAL_TYPES","deleteCommand","listCommand","listCommand","deleteCommand","deleteCommand","getCommand","listCommand","setCommand","listCommand","getCommand","setCommand","deleteCommand","listCommand","deleteCommand","resolveNamedResourceIdBase","pkg.version"],"sources":["../package.json","../../../packages/api/src/auth/context.ts","../../../packages/api/src/auth/errors.ts","../../../packages/api/src/auth/middleware.ts","../../../packages/api/src/auth/ownership.ts","../../../packages/api/src/domain/common.ts","../../../packages/api/src/domain/analytics.ts","../../../packages/api/src/groups/analytics.ts","../../../packages/api/src/domain/android-application-identifier.ts","../../../packages/api/src/domain/errors.ts","../../../packages/api/src/groups/android-application-identifiers.ts","../../../packages/api/src/domain/android-build-credentials.ts","../../../packages/api/src/groups/android-build-credentials.ts","../../../packages/api/src/domain/android-upload-keystore.ts","../../../packages/api/src/groups/android-upload-keystores.ts","../../../packages/api/src/domain/apple-team.ts","../../../packages/api/src/domain/apple-distribution-certificate.ts","../../../packages/api/src/groups/apple-distribution-certificates.ts","../../../packages/api/src/domain/apple-provisioning-profile.ts","../../../packages/api/src/groups/apple-provisioning-profiles.ts","../../../packages/api/src/domain/apple-push-key.ts","../../../packages/api/src/groups/apple-push-keys.ts","../../../packages/api/src/groups/apple-teams.ts","../../../packages/api/src/domain/asc-api-key.ts","../../../packages/api/src/groups/asc-api-keys.ts","../../../packages/api/src/domain/asset.ts","../../../packages/api/src/groups/assets.ts","../../../packages/api/src/domain/audit-log.ts","../../../packages/api/src/groups/audit-logs.ts","../../../packages/api/src/domain/branch.ts","../../../packages/api/src/groups/branches.ts","../../../packages/api/src/domain/build-credentials.ts","../../../packages/api/src/groups/build-credentials.ts","../../../packages/api/src/domain/build.ts","../../../packages/api/src/domain/build-compatibility.ts","../../../packages/api/src/groups/builds.ts","../../../packages/api/src/domain/channel.ts","../../../packages/api/src/groups/channels.ts","../../../packages/api/src/domain/device.ts","../../../packages/api/src/groups/devices.ts","../../../packages/api/src/domain/env-var.ts","../../../packages/api/src/groups/env-vars.ts","../../../packages/api/src/domain/google-service-account-key.ts","../../../packages/api/src/groups/google-service-account-keys.ts","../../../packages/api/src/domain/ios-bundle-configuration.ts","../../../packages/api/src/groups/ios-bundle-configurations.ts","../../../packages/api/src/domain/project.ts","../../../packages/api/src/groups/projects.ts","../../../packages/api/src/domain/update.ts","../../../packages/api/src/groups/updates.ts","../../../packages/api/src/api.ts","../../../packages/api/src/groups/manifest.ts","../../../packages/api/src/protocol-api.ts","../../../packages/type-guards/src/index.ts","../src/lib/exit-codes.ts","../src/lib/format-error.ts","../src/services/cli-runtime.ts","../src/services/auth-store.ts","../src/services/config-store.ts","../src/services/api-client.ts","../../../packages/safe-json/src/index.ts","../src/services/apple-session-store.ts","../src/services/presigned-upload.ts","../src/services/update-asset-uploader.ts","../src/services/version-check.ts","../src/app-layer.ts","../src/application/command-exit.ts","../src/lib/command-errors.ts","../src/lib/citty-effect.ts","../src/lib/expo-config.ts","../src/lib/output.ts","../src/commands/analytics/adoption.ts","../src/commands/analytics/channels.ts","../src/commands/analytics/platforms.ts","../src/commands/analytics/updates.ts","../src/commands/analytics/index.ts","../src/lib/cli-schemas.ts","../src/commands/audit-logs/list.ts","../src/commands/audit-logs/index.ts","../src/lib/drain-cursor.ts","../src/commands/branches.ts","../src/lib/android-signing-gradle.ts","../src/lib/string-utils.ts","../src/lib/artifact-finder.ts","../../../packages/encoding/src/index.ts","../src/lib/credentials-downloader.ts","../src/lib/sha256.ts","../src/commands/build/run-step.ts","../src/commands/build/android.ts","../src/lib/ios-export-options.ts","../src/lib/ios-keychain.ts","../src/lib/plist.ts","../src/lib/ios-provisioning.ts","../src/lib/post-build-validation.ts","../src/lib/xcpretty-formatter.ts","../src/commands/build/ios.ts","../src/commands/build/reserve-and-upload.ts","../src/lib/build-profile.ts","../src/lib/env-exporter.ts","../src/lib/git-context.ts","../src/lib/gradle-config.ts","../src/lib/fingerprint.ts","../src/lib/runtime-version.ts","../src/lib/temp-dir.ts","../src/application/build-workflow.ts","../src/commands/build/index.ts","../src/commands/builds/compatibility-matrix.ts","../src/commands/builds/delete.ts","../src/commands/builds/get.ts","../src/commands/builds/install-link.ts","../src/commands/builds/list.ts","../src/application/upload-workflow.ts","../src/commands/builds/upload.ts","../src/commands/builds/index.ts","../src/lib/resolve-named-resource.ts","../src/commands/channels/helpers.ts","../src/commands/channels/create.ts","../src/commands/channels/delete.ts","../src/commands/channels/list.ts","../src/commands/channels/pause.ts","../src/commands/channels/resume.ts","../src/commands/channels/rollout/complete.ts","../src/commands/channels/rollout/create.ts","../src/commands/channels/rollout/revert.ts","../src/commands/channels/rollout/update.ts","../src/commands/channels/rollout/index.ts","../src/commands/channels/update.ts","../src/commands/channels/index.ts","../src/lib/pkcs12.ts","../src/lib/credentials-manager.ts","../src/commands/credentials/delete.ts","../src/commands/credentials/list.ts","../src/commands/credentials/upload.ts","../src/commands/credentials/index.ts","../src/commands/env/helpers.ts","../src/commands/env/delete.ts","../src/commands/env/export.ts","../src/commands/env/get.ts","../src/commands/env/import.ts","../src/commands/env/list.ts","../src/commands/env/pull.ts","../src/commands/env/set.ts","../src/commands/env/index.ts","../src/commands/fingerprint/compare.ts","../src/commands/fingerprint/generate.ts","../src/commands/fingerprint/index.ts","../src/commands/init.ts","../src/lib/browser-login.ts","../src/lib/prompts.ts","../src/application/login.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/projects.ts","../src/commands/status.ts","../src/commands/update/helpers.ts","../src/commands/update/delete.ts","../src/commands/update/list.ts","../src/lib/signed-payloads.ts","../src/application/update-promote.ts","../src/commands/update/promote.ts","../src/lib/expo-export.ts","../src/lib/update-platforms.ts","../src/application/update-publish.ts","../src/commands/update/publish.ts","../../../packages/expo-protocol/src/index.ts","../src/application/update-rollback.ts","../src/commands/update/rollback.ts","../src/commands/update/rollout/complete.ts","../src/commands/update/rollout/revert.ts","../src/commands/update/rollout/set.ts","../src/commands/update/rollout/index.ts","../src/commands/update/index.ts","../src/lib/detect-installer.ts","../src/lib/semver-compare.ts","../src/lib/version-notifier.ts","../src/index.ts"],"sourcesContent":["","import { Context } from \"effect\";\n\nexport type Role = \"owner\" | \"admin\" | \"developer\" | \"viewer\";\n\nexport type Resource =\n | \"organization\"\n | \"member\"\n | \"invitation\"\n | \"project\"\n | \"channel\"\n | \"branch\"\n | \"update\"\n | \"rollout\"\n | \"billing\"\n | \"apiKey\"\n | \"build\"\n | \"appleCredential\"\n | \"androidCredential\"\n | \"iosBundleConfiguration\"\n | \"envVar\"\n | \"auditLog\"\n | \"device\";\n\nexport type Action = \"read\" | \"create\" | \"update\" | \"delete\" | \"cancel\" | \"download\";\n\nexport type EffectivePermissions = Partial<Record<Resource, readonly Action[]>>;\n\nexport interface AuthContextShape {\n readonly userId: string | null;\n readonly organizationId: string;\n readonly role: Role | null;\n readonly effectivePermissions: EffectivePermissions;\n readonly source: \"session\" | \"api-key\";\n readonly actorEmail: string;\n}\n\nexport class AuthContext extends Context.Tag(\"api/AuthContext\")<AuthContext, AuthContextShape>() {}\n","import { HttpApiSchema } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nexport class Unauthorized extends Schema.TaggedError<Unauthorized>()(\n \"Unauthorized\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 401 }),\n) {}\n\nexport class Forbidden extends Schema.TaggedError<Forbidden>()(\n \"Forbidden\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 403 }),\n) {}\n\nexport class OrgRequired extends Schema.TaggedError<OrgRequired>()(\n \"OrgRequired\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 400 }),\n) {}\n","import { HttpApiMiddleware, HttpApiSecurity } from \"@effect/platform\";\n\nimport { AuthContext } from \"./context\";\nimport { Unauthorized } from \"./errors\";\n\nconst bearerSecurity = HttpApiSecurity.bearer;\nconst cookieSecurity = HttpApiSecurity.apiKey({\n key: \"__Secure-better-auth.session_token\",\n in: \"cookie\",\n});\n\nexport class Authentication extends HttpApiMiddleware.Tag<Authentication>()(\"api/Authentication\", {\n failure: Unauthorized,\n provides: AuthContext,\n security: { bearer: bearerSecurity, cookie: cookieSecurity },\n}) {}\n","import { HttpApiSchema } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\n \"NotFound\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 404 }),\n) {}\n","import { Schema } from \"effect\";\n\nexport const Id = Schema.String.annotations({\n description: \"UUIDv7 identifier\",\n});\n\nexport const DateTimeString = Schema.String.annotations({\n description: \"ISO 8601 datetime\",\n});\n\nexport const Platform = Schema.Literal(\"ios\", \"android\");\n\nexport const PaginationParams = Schema.Struct({\n page: Schema.optional(Schema.NumberFromString),\n limit: Schema.optional(Schema.NumberFromString),\n});\n\nexport const CursorPaginationParams = Schema.Struct({\n cursor: Schema.optional(Schema.String),\n limit: Schema.optional(Schema.NumberFromString),\n});\n\nexport const cursorPageResult = <T, Encoded, R>(itemSchema: Schema.Schema<T, Encoded, R>) =>\n Schema.Struct({\n items: Schema.Array(itemSchema),\n nextCursor: Schema.NullOr(Schema.String),\n });\n\nexport const UpdateRolloutBody = Schema.Struct({\n percentage: Schema.Number.pipe(Schema.int(), Schema.between(1, 100)),\n});\n\nexport const UploadHeaders = Schema.Record({ key: Schema.String, value: Schema.String });\n","import { Schema } from \"effect\";\n\nimport { Id } from \"./common\";\n\n// -- Shared --\n\nexport const PeriodLiteral = Schema.Literal(\"1d\", \"7d\", \"30d\", \"90d\");\nexport const Period = Schema.optional(PeriodLiteral);\n\n// -- Adoption --\n\nexport const AdoptionParams = Schema.Struct({\n projectId: Id,\n period: Period,\n});\n\nconst AdoptionEntry = Schema.Struct({\n updateId: Schema.String,\n devices: Schema.Number,\n firstSeen: Schema.String,\n lastSeen: Schema.String,\n});\n\nexport const AdoptionResult = Schema.Struct({\n updates: Schema.Array(AdoptionEntry),\n});\n\n// -- Update Analytics --\n\nexport const UpdateAnalyticsParams = Schema.Struct({\n projectId: Id,\n updateId: Schema.String,\n period: Period,\n});\n\nconst ResponseTypeBreakdown = Schema.Struct({\n manifest: Schema.Number,\n directive: Schema.Number,\n no_update: Schema.Number,\n});\n\nconst TimeSeriesEntry = Schema.Struct({\n timestamp: Schema.String,\n requests: Schema.Number,\n});\n\nexport const UpdateAnalyticsResult = Schema.Struct({\n updateId: Schema.String,\n totalRequests: Schema.Number,\n uniqueDevices: Schema.Number,\n byResponseType: ResponseTypeBreakdown,\n timeSeries: Schema.Array(TimeSeriesEntry),\n});\n\n// -- Channel Analytics --\n\nexport const ChannelAnalyticsParams = Schema.Struct({\n projectId: Id,\n channel: Schema.String,\n period: Period,\n});\n\nexport const ChannelAnalyticsResult = Schema.Struct({\n channel: Schema.String,\n totalRequests: Schema.Number,\n uniqueDevices: Schema.Number,\n responseTypeDistribution: ResponseTypeBreakdown,\n});\n\n// -- Platform Analytics --\n\nexport const PlatformParams = Schema.Struct({\n projectId: Id,\n period: Period,\n});\n\nconst PlatformEntry = Schema.Struct({\n platform: Schema.String,\n requests: Schema.Number,\n devices: Schema.Number,\n});\n\nexport const PlatformResult = Schema.Struct({\n platforms: Schema.Array(PlatformEntry),\n});\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AdoptionParams,\n AdoptionResult,\n ChannelAnalyticsParams,\n ChannelAnalyticsResult,\n PlatformParams,\n PlatformResult,\n UpdateAnalyticsParams,\n UpdateAnalyticsResult,\n} from \"../domain/analytics\";\n\nexport class AnalyticsGroup extends HttpApiGroup.make(\"analytics\")\n .add(\n HttpApiEndpoint.get(\"adoption\", \"/api/analytics/adoption\")\n .setUrlParams(AdoptionParams)\n .addSuccess(AdoptionResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Adoption analytics\",\n description: \"Adoption rate per update for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"updates\", \"/api/analytics/updates\")\n .setUrlParams(UpdateAnalyticsParams)\n .addSuccess(UpdateAnalyticsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update analytics\",\n description: \"Request metrics for a specific update\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"channels\", \"/api/analytics/channels\")\n .setUrlParams(ChannelAnalyticsParams)\n .addSuccess(ChannelAnalyticsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Channel analytics\",\n description: \"Channel-level health metrics\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"platforms\", \"/api/analytics/platforms\")\n .setUrlParams(PlatformParams)\n .addSuccess(PlatformResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Platform analytics\",\n description: \"Device count breakdown by platform\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Analytics\",\n description: \"Deployment analytics endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AndroidPackageName = Schema.String.pipe(\n Schema.pattern(/^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$/u, {\n message: () => \"Package name must be reverse-domain style (e.g., com.acme.app)\",\n }),\n);\n\nexport class AndroidApplicationIdentifier extends Schema.Class<AndroidApplicationIdentifier>(\n \"AndroidApplicationIdentifier\",\n)({\n id: Id,\n organizationId: Id,\n projectId: Id,\n packageName: Schema.String,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateAndroidApplicationIdentifierBody = Schema.Struct({\n packageName: AndroidPackageName,\n});\n\nexport const DeleteAndroidApplicationIdentifierResult = Schema.Struct({\n deleted: Schema.Number,\n});\n","import { HttpApiSchema } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nexport class BadRequest extends Schema.TaggedError<BadRequest>()(\n \"BadRequest\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 400 }),\n) {}\n\nexport class Conflict extends Schema.TaggedError<Conflict>()(\n \"Conflict\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 409 }),\n) {}\n\nexport class NotAcceptable extends Schema.TaggedError<NotAcceptable>()(\n \"NotAcceptable\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 406 }),\n) {}\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AndroidApplicationIdentifier,\n CreateAndroidApplicationIdentifierBody,\n DeleteAndroidApplicationIdentifierResult,\n} from \"../domain/android-application-identifier\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class AndroidApplicationIdentifiersGroup extends HttpApiGroup.make(\n \"androidApplicationIdentifiers\",\n)\n .add(\n HttpApiEndpoint.get(\"list\")`/api/projects/${projectIdParam}/android-application-identifiers`\n .addSuccess(Schema.Struct({ items: Schema.Array(AndroidApplicationIdentifier) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Android application identifiers\",\n description: \"List all Android package identifiers for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"create\")`/api/projects/${projectIdParam}/android-application-identifiers`\n .setPayload(CreateAndroidApplicationIdentifierBody)\n .addSuccess(AndroidApplicationIdentifier, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create Android application identifier\",\n description: \"Register an Android package name for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/android-application-identifiers/${idParam}`\n .addSuccess(DeleteAndroidApplicationIdentifierResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete Android application identifier\",\n description: \"Remove an Android application identifier\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Android Application Identifiers\",\n description: \"Manage Android package name registrations per project\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport class AndroidBuildCredentials extends Schema.Class<AndroidBuildCredentials>(\n \"AndroidBuildCredentials\",\n)({\n id: Id,\n organizationId: Id,\n androidApplicationIdentifierId: Id,\n androidUploadKeystoreId: Schema.NullOr(Id),\n googleServiceAccountKeyForSubmissionsId: Schema.NullOr(Id),\n googleServiceAccountKeyForFcmV1Id: Schema.NullOr(Id),\n name: Schema.String,\n isDefault: Schema.Boolean,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateAndroidBuildCredentialsBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n androidUploadKeystoreId: Schema.optional(Id),\n googleServiceAccountKeyForSubmissionsId: Schema.optional(Id),\n googleServiceAccountKeyForFcmV1Id: Schema.optional(Id),\n isDefault: Schema.optional(Schema.Boolean),\n});\n\nexport const UpdateAndroidBuildCredentialsBody = Schema.Struct({\n name: Schema.optional(Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120))),\n androidUploadKeystoreId: Schema.optional(Schema.NullOr(Id)),\n googleServiceAccountKeyForSubmissionsId: Schema.optional(Schema.NullOr(Id)),\n googleServiceAccountKeyForFcmV1Id: Schema.optional(Schema.NullOr(Id)),\n isDefault: Schema.optional(Schema.Boolean),\n});\n\nexport const DeleteAndroidBuildCredentialsResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AndroidBuildCredentials,\n CreateAndroidBuildCredentialsBody,\n DeleteAndroidBuildCredentialsResult,\n UpdateAndroidBuildCredentialsBody,\n} from \"../domain/android-build-credentials\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst applicationIdentifierIdParam = HttpApiSchema.param(\"applicationIdentifierId\", Schema.String);\n\nexport class AndroidBuildCredentialsGroup extends HttpApiGroup.make(\"androidBuildCredentials\")\n .add(\n HttpApiEndpoint.get(\n \"list\",\n )`/api/android-application-identifiers/${applicationIdentifierIdParam}/build-credentials`\n .addSuccess(Schema.Struct({ items: Schema.Array(AndroidBuildCredentials) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Android build credentials\",\n description: \"List named build credential groups for an Android app identifier\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\n \"create\",\n )`/api/android-application-identifiers/${applicationIdentifierIdParam}/build-credentials`\n .setPayload(CreateAndroidBuildCredentialsBody)\n .addSuccess(AndroidBuildCredentials, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create Android build credentials group\",\n description: \"Create a named build credentials group (Default or custom)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.put(\"update\")`/api/android-build-credentials/${idParam}`\n .setPayload(UpdateAndroidBuildCredentialsBody)\n .addSuccess(AndroidBuildCredentials)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update Android build credentials\",\n description: \"Rename group, change default flag, or swap bound keystore/keys\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/android-build-credentials/${idParam}`\n .addSuccess(DeleteAndroidBuildCredentialsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete Android build credentials\",\n description: \"Remove a build credentials group\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Android Build Credentials\",\n description: \"Named groups of build credentials per Android application identifier\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport class AndroidUploadKeystore extends Schema.Class<AndroidUploadKeystore>(\n \"AndroidUploadKeystore\",\n)({\n id: Id,\n organizationId: Id,\n keyAlias: Schema.String,\n md5Fingerprint: Schema.NullOr(Schema.String),\n sha1Fingerprint: Schema.NullOr(Schema.String),\n sha256Fingerprint: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAndroidUploadKeystoreBody = Schema.Struct({\n keystoreBase64: Schema.String.pipe(Schema.minLength(1)),\n keyAlias: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(200)),\n keystorePassword: Schema.String.pipe(Schema.minLength(1)),\n keyPassword: Schema.String.pipe(Schema.minLength(1)),\n md5Fingerprint: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n sha1Fingerprint: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n sha256Fingerprint: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n});\n\nexport const DeleteAndroidUploadKeystoreResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AndroidUploadKeystore,\n DeleteAndroidUploadKeystoreResult,\n UploadAndroidUploadKeystoreBody,\n} from \"../domain/android-upload-keystore\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AndroidUploadKeystoresGroup extends HttpApiGroup.make(\"androidUploadKeystores\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/android/upload-keystores\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AndroidUploadKeystore) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Android upload keystores\",\n description: \"List uploaded Android keystores\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/android/upload-keystores\")\n .setPayload(UploadAndroidUploadKeystoreBody)\n .addSuccess(AndroidUploadKeystore, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload Android keystore\",\n description: \"Upload a JKS/PKCS12 keystore with key alias + passwords\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/android/upload-keystores/${idParam}`\n .addSuccess(DeleteAndroidUploadKeystoreResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete Android keystore\",\n description: \"Remove a stored Android keystore\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Android Upload Keystores\",\n description: \"Manage Android signing keystores\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AppleTeamType = Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\");\nexport type AppleTeamTypeValue = typeof AppleTeamType.Type;\n\nexport const AppleTeamIdentifier = Schema.String.pipe(\n Schema.pattern(/^[A-Z0-9]{10}$/u, {\n message: () => \"Apple Team identifier must be 10 uppercase alphanumeric characters\",\n }),\n);\n\nexport class AppleTeam extends Schema.Class<AppleTeam>(\"AppleTeam\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.String,\n appleTeamType: AppleTeamType,\n name: Schema.NullOr(Schema.String),\n distributionCertificateCount: Schema.Number,\n pushKeyCount: Schema.Number,\n ascApiKeyCount: Schema.Number,\n provisioningProfileCount: Schema.Number,\n deviceCount: Schema.Number,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n","import { Schema } from \"effect\";\n\nimport { AppleTeamIdentifier } from \"./apple-team\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport class AppleDistributionCertificate extends Schema.Class<AppleDistributionCertificate>(\n \"AppleDistributionCertificate\",\n)({\n id: Id,\n organizationId: Id,\n appleTeamId: Id,\n serialNumber: Schema.String,\n developerIdIdentifier: Schema.NullOr(Schema.String),\n validFrom: DateTimeString,\n validUntil: DateTimeString,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAppleDistributionCertificateBody = Schema.Struct({\n p12Base64: Schema.String.pipe(Schema.minLength(1)),\n p12Password: Schema.String.pipe(Schema.minLength(1)),\n serialNumber: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(200)),\n appleTeamIdentifier: AppleTeamIdentifier,\n appleTeamName: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n appleTeamType: Schema.optional(Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\")),\n developerIdIdentifier: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n validFrom: DateTimeString,\n validUntil: DateTimeString,\n});\n\nexport const DeleteAppleDistributionCertificateResult = Schema.Struct({\n deleted: Schema.Number,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AppleDistributionCertificate,\n DeleteAppleDistributionCertificateResult,\n UploadAppleDistributionCertificateBody,\n} from \"../domain/apple-distribution-certificate\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AppleDistributionCertificatesGroup extends HttpApiGroup.make(\n \"appleDistributionCertificates\",\n)\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/distribution-certificates\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AppleDistributionCertificate) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Apple distribution certificates\",\n description: \"List uploaded Apple distribution certificates for the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/distribution-certificates\")\n .setPayload(UploadAppleDistributionCertificateBody)\n .addSuccess(AppleDistributionCertificate, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload distribution certificate\",\n description:\n \"Upload a .p12 distribution certificate; auto-derives the Apple team from the provided identifier\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/distribution-certificates/${idParam}`\n .addSuccess(DeleteAppleDistributionCertificateResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete distribution certificate\",\n description: \"Remove a distribution certificate from storage\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Distribution Certificates\",\n description: \"Manage .p12 distribution certificates\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const DistributionType = Schema.Literal(\"APP_STORE\", \"AD_HOC\", \"ENTERPRISE\", \"DEVELOPMENT\");\nexport type DistributionTypeValue = typeof DistributionType.Type;\n\nexport const BundleIdentifier = Schema.String.pipe(\n Schema.pattern(/^[A-Za-z0-9.\\-_]{1,200}$/u, {\n message: () => \"Bundle identifier must be reverse-domain style (letters, digits, dot, dash)\",\n }),\n);\n\nexport class AppleProvisioningProfile extends Schema.Class<AppleProvisioningProfile>(\n \"AppleProvisioningProfile\",\n)({\n id: Id,\n organizationId: Id,\n appleTeamId: Id,\n appleDistributionCertificateId: Schema.NullOr(Id),\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n developerPortalIdentifier: Schema.NullOr(Schema.String),\n profileName: Schema.NullOr(Schema.String),\n validUntil: Schema.NullOr(DateTimeString),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAppleProvisioningProfileBody = Schema.Struct({\n profileBase64: Schema.String.pipe(Schema.minLength(1)),\n appleDistributionCertificateId: Schema.optional(Id),\n});\n\nexport const GenerateAppleProvisioningProfileBody = Schema.Struct({\n ascApiKeyId: Id,\n appleDistributionCertificateId: Id,\n bundleIdentifier: BundleIdentifier,\n distributionType: DistributionType,\n deviceIds: Schema.optional(Schema.Array(Id)),\n});\n\nexport const DeleteAppleProvisioningProfileResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const ListAppleProvisioningProfilesParams = Schema.Struct({\n bundleIdentifier: Schema.optional(BundleIdentifier),\n distributionType: Schema.optional(DistributionType),\n appleTeamId: Schema.optional(Id),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AppleProvisioningProfile,\n DeleteAppleProvisioningProfileResult,\n GenerateAppleProvisioningProfileBody,\n ListAppleProvisioningProfilesParams,\n UploadAppleProvisioningProfileBody,\n} from \"../domain/apple-provisioning-profile\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AppleProvisioningProfilesGroup extends HttpApiGroup.make(\"appleProvisioningProfiles\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/provisioning-profiles\")\n .setUrlParams(ListAppleProvisioningProfilesParams)\n .addSuccess(Schema.Struct({ items: Schema.Array(AppleProvisioningProfile) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List provisioning profiles\",\n description: \"List stored provisioning profiles, optionally filtered by bundle + team\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/provisioning-profiles\")\n .setPayload(UploadAppleProvisioningProfileBody)\n .addSuccess(AppleProvisioningProfile, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload provisioning profile\",\n description: \"Upload an existing .mobileprovision; auto-parses the embedded plist\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"generate\", \"/api/apple/provisioning-profiles/generate\")\n .setPayload(GenerateAppleProvisioningProfileBody)\n .addSuccess(AppleProvisioningProfile, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Generate provisioning profile\",\n description: \"Generate + download a new provisioning profile via App Store Connect API\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/provisioning-profiles/${idParam}`\n .addSuccess(DeleteAppleProvisioningProfileResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete provisioning profile\",\n description: \"Remove a stored provisioning profile\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Provisioning Profiles\",\n description: \"Manage .mobileprovision profiles (upload or generate)\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { AppleTeamIdentifier } from \"./apple-team\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport const ApplePushKeyId = Schema.String.pipe(\n Schema.pattern(/^[A-Z0-9]{10}$/u, {\n message: () => \"Push Key ID must be 10 uppercase alphanumeric characters\",\n }),\n);\n\nexport class ApplePushKey extends Schema.Class<ApplePushKey>(\"ApplePushKey\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Id,\n keyId: Schema.String,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadApplePushKeyBody = Schema.Struct({\n keyId: ApplePushKeyId,\n p8Pem: Schema.String.pipe(Schema.minLength(1)),\n appleTeamIdentifier: AppleTeamIdentifier,\n appleTeamName: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n appleTeamType: Schema.optional(Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\")),\n});\n\nexport const DeleteApplePushKeyResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n ApplePushKey,\n DeleteApplePushKeyResult,\n UploadApplePushKeyBody,\n} from \"../domain/apple-push-key\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class ApplePushKeysGroup extends HttpApiGroup.make(\"applePushKeys\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/push-keys\")\n .addSuccess(Schema.Struct({ items: Schema.Array(ApplePushKey) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Apple push keys\",\n description: \"List APNs push keys for the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/push-keys\")\n .setPayload(UploadApplePushKeyBody)\n .addSuccess(ApplePushKey, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload push key\",\n description: \"Upload an APNs .p8 push notification key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/push-keys/${idParam}`\n .addSuccess(DeleteApplePushKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete push key\",\n description: \"Remove a stored APNs push key\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Push Keys\",\n description: \"Manage APNs push notification keys\",\n }),\n ) {}\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { AppleTeam } from \"../domain/apple-team\";\n\nexport class AppleTeamsGroup extends HttpApiGroup.make(\"appleTeams\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple-teams\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AppleTeam) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Apple teams\",\n description:\n \"List Apple developer teams derived from uploaded artifacts (certs, push keys, ASC keys)\",\n }),\n ),\n )\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Teams\",\n description: \"Read-only view of Apple teams auto-created from uploaded credentials\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { AppleTeamIdentifier } from \"./apple-team\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AscApiKeyId = Schema.String.pipe(\n Schema.pattern(/^[A-Z0-9]{10}$/u, {\n message: () => \"ASC API Key ID must be 10 uppercase alphanumeric characters\",\n }),\n);\n\nexport const IssuerId = Schema.String.pipe(\n Schema.pattern(/^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$/u, {\n message: () => \"Issuer ID must be a UUID (8-4-4-4-12 hex)\",\n }),\n);\n\nexport class AscApiKey extends Schema.Class<AscApiKey>(\"AscApiKey\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.NullOr(Id),\n keyId: Schema.String,\n name: Schema.String,\n roles: Schema.Array(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAscApiKeyBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n keyId: AscApiKeyId,\n issuerId: IssuerId,\n p8Pem: Schema.String.pipe(Schema.minLength(1)),\n appleTeamIdentifier: Schema.optional(AppleTeamIdentifier),\n appleTeamName: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n appleTeamType: Schema.optional(Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\")),\n roles: Schema.optional(Schema.Array(Schema.String)),\n});\n\nexport const DeleteAscApiKeyResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const SyncedDeviceSummary = Schema.Struct({\n id: Id,\n identifier: Schema.String,\n name: Schema.String,\n deviceClass: Schema.Literal(\"IPHONE\", \"IPAD\", \"MAC\", \"UNKNOWN\"),\n});\n\nexport const SyncDevicesResult = Schema.Struct({\n pulled: Schema.Number,\n pushed: Schema.Number,\n skipped: Schema.Number,\n devices: Schema.Array(SyncedDeviceSummary),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AscApiKey,\n DeleteAscApiKeyResult,\n SyncDevicesResult,\n UploadAscApiKeyBody,\n} from \"../domain/asc-api-key\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AscApiKeysGroup extends HttpApiGroup.make(\"ascApiKeys\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/asc-api-keys\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AscApiKey) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List App Store Connect API keys\",\n description: \"List stored ASC API keys for the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/asc-api-keys\")\n .setPayload(UploadAscApiKeyBody)\n .addSuccess(AscApiKey, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload ASC API key\",\n description: \"Upload an App Store Connect API key (.p8 + issuer)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/asc-api-keys/${idParam}`\n .addSuccess(DeleteAscApiKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete ASC API key\",\n description: \"Remove a stored ASC API key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"syncDevices\")`/api/apple/asc-api-keys/${idParam}/sync-devices`\n .addSuccess(SyncDevicesResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Sync devices via ASC API key\",\n description:\n \"Pull registered devices from Apple Developer Portal for this key's team; push local devices that aren't yet registered\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"App Store Connect API Keys\",\n description: \"Manage ASC API keys used for device + profile sync\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, UploadHeaders } from \"./common\";\n\nexport class Asset extends Schema.Class<Asset>(\"Asset\")({\n hash: Schema.String,\n contentType: Schema.String,\n fileExt: Schema.String,\n byteSize: Schema.Number,\n r2Key: Schema.String,\n createdAt: DateTimeString,\n}) {}\n\nexport const AssetUploadBody = Schema.Struct({\n projectId: Id,\n assets: Schema.Array(\n Schema.Struct({\n hash: Schema.String,\n contentType: Schema.String,\n fileExt: Schema.String,\n contentChecksum: Schema.optional(Schema.String),\n }),\n ),\n});\n\nexport const AssetUploadResult = Schema.Struct({\n uploaded: Schema.Array(\n Schema.Struct({\n hash: Schema.String,\n uploadMode: Schema.Literal(\"single\"),\n uploadUrl: Schema.String,\n uploadExpiresAt: DateTimeString,\n uploadHeaders: UploadHeaders,\n }),\n ),\n deduplicated: Schema.Array(Schema.String),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { Asset, AssetUploadBody, AssetUploadResult } from \"../domain/asset\";\nimport { BadRequest } from \"../domain/errors\";\n\nconst hashParam = HttpApiSchema.param(\"hash\", Schema.String);\n\nexport class AssetsGroup extends HttpApiGroup.make(\"assets\")\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/assets/upload\")\n .setPayload(AssetUploadBody)\n .addSuccess(AssetUploadResult, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload assets\",\n description: \"Upload asset files to R2 storage (deduplicated by content hash)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"finalize\")`/api/assets/${hashParam}/finalize`\n .addSuccess(Asset)\n .annotateContext(\n OpenApi.annotations({\n title: \"Finalize asset upload\",\n description: \"Verify a directly uploaded asset in R2 and mark it available for updates\",\n }),\n ),\n )\n .addError(BadRequest)\n .addError(NotFound)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Assets\",\n description: \"Asset upload endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AuditLogResourceType = Schema.Literal(\n \"project\",\n \"branch\",\n \"channel\",\n \"update\",\n \"build\",\n \"appleCredential\",\n \"androidCredential\",\n \"iosBundleConfiguration\",\n \"envVar\",\n \"device\",\n);\n\nexport const AuditLogSource = Schema.Literal(\"session\", \"api-key\");\n\nexport class AuditLog extends Schema.Class<AuditLog>(\"AuditLog\")({\n id: Id,\n organizationId: Id,\n actorId: Schema.NullOr(Schema.String),\n actorEmail: Schema.String,\n action: Schema.String,\n resourceType: AuditLogResourceType,\n resourceId: Schema.NullOr(Schema.String),\n metadata: Schema.NullOr(Schema.String),\n source: AuditLogSource,\n createdAt: DateTimeString,\n}) {}\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { AuditLog } from \"../domain/audit-log\";\nimport { CursorPaginationParams, cursorPageResult } from \"../domain/common\";\n\nexport class AuditLogsGroup extends HttpApiGroup.make(\"audit-logs\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/audit-logs\")\n .setUrlParams(\n Schema.Struct({\n projectId: Schema.optional(Schema.String),\n resourceType: Schema.optional(Schema.String),\n from: Schema.optional(Schema.String),\n to: Schema.optional(Schema.String),\n ...CursorPaginationParams.fields,\n }),\n )\n .addSuccess(cursorPageResult(AuditLog))\n .annotateContext(\n OpenApi.annotations({\n title: \"List audit logs\",\n description: \"List audit log entries with optional filters\",\n }),\n ),\n )\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Audit Logs\",\n description: \"View audit trail for organization actions\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams } from \"./common\";\n\nexport class Branch extends Schema.Class<Branch>(\"Branch\")({\n id: Id,\n projectId: Id,\n name: Schema.String,\n createdAt: DateTimeString,\n updateCount: Schema.Number,\n}) {}\n\nexport const BranchSortColumn = Schema.Literal(\"name\", \"createdAt\", \"updateCount\");\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-createdAt` (desc).\n */\nexport const BranchSort = Schema.Union(\n BranchSortColumn,\n Schema.TemplateLiteral(\"-\", BranchSortColumn),\n);\n\nexport const ListBranchesParams = Schema.Struct({\n projectId: Id,\n ...PaginationParams.fields,\n sort: Schema.optional(BranchSort),\n});\n\nexport const CreateBranchBody = Schema.Struct({\n projectId: Id,\n name: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const UpdateBranchBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const DeleteBranchResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n Branch,\n CreateBranchBody,\n DeleteBranchResult,\n ListBranchesParams,\n UpdateBranchBody,\n} from \"../domain/branch\";\nimport { Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class BranchesGroup extends HttpApiGroup.make(\"branches\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/branches\")\n .setPayload(CreateBranchBody)\n .addSuccess(Branch, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create branch\",\n description: \"Create a new branch within a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/branches\")\n .setUrlParams(ListBranchesParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Branch),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List branches\",\n description: \"List all branches for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"rename\")`/api/branches/${idParam}`\n .setPayload(UpdateBranchBody)\n .addSuccess(Branch)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Rename branch\",\n description: \"Rename a branch (channels and updates are unaffected)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/branches/${idParam}`\n .addSuccess(DeleteBranchResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete branch\",\n description: \"Delete a branch and all its updates\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Branches\",\n description: \"Branch management endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { AndroidPackageName } from \"./android-application-identifier\";\nimport { BundleIdentifier, DistributionType } from \"./apple-provisioning-profile\";\n\nexport const ResolveBuildCredentialsIosBody = Schema.Struct({\n platform: Schema.Literal(\"ios\"),\n bundleIdentifier: BundleIdentifier,\n distributionType: DistributionType,\n});\n\nexport const ResolveBuildCredentialsAndroidBody = Schema.Struct({\n platform: Schema.Literal(\"android\"),\n applicationIdentifier: AndroidPackageName,\n});\n\nexport const ResolveBuildCredentialsBody = Schema.Union(\n ResolveBuildCredentialsIosBody,\n ResolveBuildCredentialsAndroidBody,\n);\n\nexport const IosBuildDistributionCertificate = Schema.Struct({\n p12Base64: Schema.String,\n p12Password: Schema.String,\n});\n\nexport const IosBuildProvisioningProfile = Schema.Struct({\n mobileprovisionBase64: Schema.String,\n uuid: Schema.NullOr(Schema.String),\n name: Schema.NullOr(Schema.String),\n teamId: Schema.String,\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n});\n\nexport const IosBuildPushKey = Schema.Struct({\n p8Base64: Schema.String,\n keyId: Schema.String,\n teamId: Schema.String,\n});\n\nexport const ResolveBuildCredentialsIosResult = Schema.Struct({\n platform: Schema.Literal(\"ios\"),\n distributionCertificate: IosBuildDistributionCertificate,\n provisioningProfile: IosBuildProvisioningProfile,\n pushKey: Schema.NullOr(IosBuildPushKey),\n});\n\nexport const AndroidBuildKeystore = Schema.Struct({\n keystoreBase64: Schema.String,\n storePassword: Schema.String,\n keyAlias: Schema.String,\n keyPassword: Schema.String,\n});\n\nexport const ResolveBuildCredentialsAndroidResult = Schema.Struct({\n platform: Schema.Literal(\"android\"),\n keystore: AndroidBuildKeystore,\n});\n\nexport const ResolveBuildCredentialsResult = Schema.Union(\n ResolveBuildCredentialsIosResult,\n ResolveBuildCredentialsAndroidResult,\n);\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n ResolveBuildCredentialsBody,\n ResolveBuildCredentialsResult,\n} from \"../domain/build-credentials\";\nimport { BadRequest } from \"../domain/errors\";\n\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class BuildCredentialsGroup extends HttpApiGroup.make(\"buildCredentials\")\n .add(\n HttpApiEndpoint.post(\"resolve\")`/api/projects/${projectIdParam}/build-credentials/resolve`\n .setPayload(ResolveBuildCredentialsBody)\n .addSuccess(ResolveBuildCredentialsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Resolve build credentials\",\n description:\n \"Return decrypted signing assets for a project build. Regenerates the iOS provisioning profile via Apple ASC when the registered device roster has changed since the profile was last generated.\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Build Credentials\",\n description: \"Materialize signing assets needed by a CLI build run\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams, Platform, UploadHeaders } from \"./common\";\n\nexport const Distribution = Schema.Literal(\n \"app-store\",\n \"ad-hoc\",\n \"development\",\n \"enterprise\",\n \"simulator\",\n \"play-store\",\n \"direct\",\n);\n\nexport const ArtifactFormat = Schema.Literal(\"ipa\", \"apk\", \"aab\", \"tar.gz\");\nconst Sha256Hex = Schema.String.pipe(Schema.pattern(/^[a-fA-F0-9]{64}$/u), Schema.maxLength(64));\n\nconst CreateBuildCommonFields = {\n projectId: Id,\n profile: Schema.optional(Schema.String),\n runtimeVersion: Schema.optional(Schema.String),\n appVersion: Schema.optional(Schema.String),\n buildNumber: Schema.optional(Schema.String),\n bundleId: Schema.optional(Schema.String),\n gitRef: Schema.optional(Schema.String),\n gitCommit: Schema.optional(Schema.String),\n message: Schema.optional(Schema.String),\n metadata: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n sha256: Sha256Hex,\n byteSize: Schema.Number.pipe(Schema.nonNegative()),\n} as const;\n\nexport class Build extends Schema.Class<Build>(\"Build\")({\n id: Id,\n projectId: Id,\n platform: Platform,\n profile: Schema.String,\n distribution: Distribution,\n runtimeVersion: Schema.NullOr(Schema.String),\n appVersion: Schema.NullOr(Schema.String),\n buildNumber: Schema.NullOr(Schema.String),\n bundleId: Schema.NullOr(Schema.String),\n gitRef: Schema.NullOr(Schema.String),\n gitCommit: Schema.NullOr(Schema.String),\n message: Schema.NullOr(Schema.String),\n metadataJson: Schema.String,\n createdAt: DateTimeString,\n}) {}\n\nexport class BuildArtifact extends Schema.Class<BuildArtifact>(\"BuildArtifact\")({\n buildId: Id,\n r2Key: Schema.String,\n format: ArtifactFormat,\n contentType: Schema.String,\n byteSize: Schema.Number,\n sha256: Schema.String,\n createdAt: DateTimeString,\n}) {}\n\nexport class BuildWithArtifact extends Build.extend<BuildWithArtifact>(\"BuildWithArtifact\")({\n artifact: Schema.NullOr(\n Schema.Struct({\n r2Key: Schema.String,\n format: ArtifactFormat,\n contentType: Schema.String,\n byteSize: Schema.Number,\n sha256: Schema.String,\n }),\n ),\n}) {}\n\nexport const CreateBuildBody = Schema.Union(\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"ios\"),\n distribution: Schema.Literal(\"app-store\", \"ad-hoc\", \"development\", \"enterprise\"),\n artifactFormat: Schema.Literal(\"ipa\"),\n }),\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"ios\"),\n distribution: Schema.Literal(\"simulator\"),\n artifactFormat: Schema.Literal(\"tar.gz\"),\n }),\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"android\"),\n distribution: Schema.Literal(\"play-store\"),\n artifactFormat: Schema.Literal(\"aab\"),\n }),\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"android\"),\n distribution: Schema.Literal(\"direct\"),\n artifactFormat: Schema.Literal(\"apk\"),\n }),\n);\n\nexport const BuildSortColumn = Schema.Literal(\n \"createdAt\",\n \"platform\",\n \"distribution\",\n \"runtimeVersion\",\n \"appVersion\",\n);\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `runtimeVersion` (asc), `-createdAt` (desc).\n */\nexport const BuildSort = Schema.Union(\n BuildSortColumn,\n Schema.TemplateLiteral(\"-\", BuildSortColumn),\n);\n\nexport const ListBuildsParams = Schema.Struct({\n projectId: Id,\n platform: Schema.optional(Platform),\n profile: Schema.optional(Schema.String),\n runtimeVersion: Schema.optional(Schema.String),\n distribution: Schema.optional(Distribution),\n ...PaginationParams.fields,\n sort: Schema.optional(BuildSort),\n});\n\nexport const CompleteBuildBody = Schema.Struct({\n sha256: Sha256Hex,\n byteSize: Schema.Number.pipe(Schema.nonNegative()),\n});\n\nexport const ReserveBuildResult = Schema.Struct({\n id: Id,\n uploadMode: Schema.Literal(\"single\"),\n uploadUrl: Schema.String,\n uploadExpiresAt: DateTimeString,\n uploadHeaders: UploadHeaders,\n});\n\nexport const DeleteBuildResult = Schema.Struct({\n deleted: Schema.Number,\n});\n\nexport const InstallLinkResult = Schema.Struct({\n token: Schema.String,\n expires: Schema.Number,\n artifactUrl: Schema.String,\n installUrl: Schema.NullOr(Schema.String),\n});\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, Platform } from \"./common\";\n\n// Per-runtime channel status — varies per (platform, runtimeVersion).\nexport class BuildCompatibilityChannel extends Schema.Class<BuildCompatibilityChannel>(\n \"BuildCompatibilityChannel\",\n)({\n channelId: Id,\n updateCount: Schema.Number,\n latestUpdateId: Schema.NullOr(Id),\n latestUpdateMessage: Schema.NullOr(Schema.String),\n latestUpdateCreatedAt: Schema.NullOr(DateTimeString),\n}) {}\n\n// Channel-level metadata that does not depend on a specific build's runtime.\nexport class CompatibilityChannelInfo extends Schema.Class<CompatibilityChannelInfo>(\n \"CompatibilityChannelInfo\",\n)({\n channelId: Id,\n channelName: Schema.String,\n isPaused: Schema.Boolean,\n rolloutActive: Schema.Boolean,\n}) {}\n\nexport class MissingRuntimeVersionBuild extends Schema.Class<MissingRuntimeVersionBuild>(\n \"MissingRuntimeVersionBuild\",\n)({\n channelId: Id,\n channelName: Schema.String,\n platform: Platform,\n runtimeVersion: Schema.String,\n updateCount: Schema.Number,\n latestUpdateId: Id,\n latestUpdateMessage: Schema.String,\n latestUpdateCreatedAt: DateTimeString,\n rolloutActive: Schema.Boolean,\n}) {}\n\nexport const BuildCompatibilityMatrixResult = Schema.Struct({\n channels: Schema.Array(CompatibilityChannelInfo),\n channelStatusByKey: Schema.Record({\n key: Schema.String,\n value: Schema.Array(BuildCompatibilityChannel),\n }),\n missingRuntimeVersions: Schema.Array(MissingRuntimeVersionBuild),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n BuildWithArtifact,\n CompleteBuildBody,\n CreateBuildBody,\n DeleteBuildResult,\n InstallLinkResult,\n ListBuildsParams,\n ReserveBuildResult,\n} from \"../domain/build\";\nimport { BuildCompatibilityMatrixResult } from \"../domain/build-compatibility\";\nimport { Id } from \"../domain/common\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class BuildsGroup extends HttpApiGroup.make(\"builds\")\n .add(\n HttpApiEndpoint.post(\"reserve\", \"/api/builds\")\n .setPayload(CreateBuildBody)\n .addSuccess(ReserveBuildResult, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Reserve build\",\n description: \"Reserve a build ID and get a presigned upload URL\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"complete\")`/api/builds/${idParam}/complete`\n .setPayload(CompleteBuildBody)\n .addSuccess(BuildWithArtifact)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Complete build\",\n description: \"Finalize a build after artifact upload\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/builds\")\n .setUrlParams(ListBuildsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(BuildWithArtifact),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List builds\",\n description: \"List builds for a project with optional filters\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"compatibilityMatrix\", \"/api/builds/compatibility-matrix\")\n .setUrlParams(\n Schema.Struct({\n projectId: Id,\n }),\n )\n .addSuccess(BuildCompatibilityMatrixResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Build compatibility matrix\",\n description: \"List build-to-channel OTA compatibility for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/builds/${idParam}`\n .addSuccess(BuildWithArtifact)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get build\",\n description: \"Get a build by ID with artifact details\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/builds/${idParam}`\n .addSuccess(DeleteBuildResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete build\",\n description: \"Delete a build and its artifact from storage\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"getInstallLink\")`/api/builds/${idParam}/install-link`\n .addSuccess(InstallLinkResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get install link\",\n description: \"Generate a signed install link for a build artifact\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Forbidden)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Builds\",\n description: \"Build artifact upload, tracking, and download endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams } from \"./common\";\n\nexport class Channel extends Schema.Class<Channel>(\"Channel\")({\n id: Id,\n projectId: Id,\n name: Schema.String,\n branchId: Id,\n branchMappingJson: Schema.NullOr(Schema.String),\n cacheVersion: Schema.Number,\n isPaused: Schema.Boolean,\n createdAt: DateTimeString,\n}) {}\n\nexport const ChannelSortColumn = Schema.Literal(\"name\", \"createdAt\");\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-createdAt` (desc).\n */\nexport const ChannelSort = Schema.Union(\n ChannelSortColumn,\n Schema.TemplateLiteral(\"-\", ChannelSortColumn),\n);\n\nexport const ListChannelsParams = Schema.Struct({\n projectId: Id,\n ...PaginationParams.fields,\n sort: Schema.optional(ChannelSort),\n});\n\nexport const CreateChannelBody = Schema.Struct({\n projectId: Id,\n name: Schema.String.pipe(Schema.minLength(1)),\n branchId: Id,\n});\n\nexport const UpdateChannelBody = Schema.Struct({\n branchId: Id,\n});\n\nexport const CreateBranchRolloutBody = Schema.Struct({\n newBranchId: Id,\n percentage: Schema.Number.pipe(Schema.int(), Schema.between(1, 100)),\n});\n\nexport const DeleteChannelResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n Channel,\n CreateBranchRolloutBody,\n CreateChannelBody,\n DeleteChannelResult,\n ListChannelsParams,\n UpdateChannelBody,\n} from \"../domain/channel\";\nimport { UpdateRolloutBody } from \"../domain/common\";\nimport { Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class ChannelsGroup extends HttpApiGroup.make(\"channels\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/channels\")\n .setPayload(CreateChannelBody)\n .addSuccess(Channel, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create channel\",\n description: \"Create a new channel linked to a branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/channels/${idParam}`\n .setPayload(UpdateChannelBody)\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update channel\",\n description: \"Relink channel to a different branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/channels\")\n .setUrlParams(ListChannelsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Channel),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List channels\",\n description: \"List all channels for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"pause\")`/api/channels/${idParam}/pause`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Pause channel\",\n description: \"Pause a channel — manifest requests return 204 No Content\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"resume\")`/api/channels/${idParam}/resume`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Resume channel\",\n description: \"Resume a paused channel\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"createBranchRollout\")`/api/channels/${idParam}/rollout`\n .setPayload(CreateBranchRolloutBody)\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Create branch rollout\",\n description: \"Start a gradual rollout to a new branch on this channel\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"updateBranchRollout\")`/api/channels/${idParam}/rollout`\n .setPayload(UpdateRolloutBody)\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update branch rollout\",\n description: \"Change the rollout percentage for a branch rollout\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"completeBranchRollout\")`/api/channels/${idParam}/rollout/complete`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Complete branch rollout\",\n description: \"Finalize the rollout — promote the new branch to 100%\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"revertBranchRollout\")`/api/channels/${idParam}/rollout/revert`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Revert branch rollout\",\n description: \"Revert the rollout — restore the original branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/channels/${idParam}`\n .addSuccess(DeleteChannelResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete channel\",\n description: \"Delete a channel\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Channels\",\n description: \"Channel management endpoints including pause/resume and branch rollouts\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams } from \"./common\";\n\nexport const DeviceClass = Schema.Literal(\"IPHONE\", \"IPAD\", \"MAC\", \"UNKNOWN\");\nexport type DeviceClassValue = typeof DeviceClass.Type;\n\nconst IDENTIFIER_PATTERN =\n /^(?:[A-Fa-f0-9]{40}|[A-Fa-f0-9]{8}-[A-Fa-f0-9]{16}|[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12})$/u;\n\nexport const DeviceIdentifier = Schema.String.pipe(\n Schema.pattern(IDENTIFIER_PATTERN, {\n message: () =>\n \"Identifier must be an Apple UDID: 40 hex chars, 8-16 hex, or UUID (8-4-4-4-12 hex)\",\n }),\n);\n\nexport class Device extends Schema.Class<Device>(\"Device\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.NullOr(Id),\n identifier: Schema.String,\n name: Schema.String,\n model: Schema.NullOr(Schema.String),\n deviceClass: DeviceClass,\n enabled: Schema.Boolean,\n appleDevicePortalId: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const RegisterDeviceBody = Schema.Struct({\n identifier: DeviceIdentifier,\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n deviceClass: DeviceClass,\n model: Schema.optional(Schema.String.pipe(Schema.maxLength(120))),\n appleTeamId: Schema.optional(Id),\n});\n\nexport const UpdateDeviceBody = Schema.Struct({\n name: Schema.optional(Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120))),\n enabled: Schema.optional(Schema.Boolean),\n appleTeamId: Schema.optional(Schema.NullOr(Id)),\n});\n\nexport const DeleteDeviceResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DeviceSortColumn = Schema.Literal(\"name\", \"createdAt\", \"deviceClass\");\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-createdAt` (desc).\n */\nexport const DeviceSort = Schema.Union(\n DeviceSortColumn,\n Schema.TemplateLiteral(\"-\", DeviceSortColumn),\n);\n\nexport const ListDevicesParams = Schema.Struct({\n ...PaginationParams.fields,\n deviceClass: Schema.optional(DeviceClass),\n appleTeamId: Schema.optional(Id),\n query: Schema.optional(Schema.String),\n sort: Schema.optional(DeviceSort),\n});\n\nexport class DeviceRegistrationRequest extends Schema.Class<DeviceRegistrationRequest>(\n \"DeviceRegistrationRequest\",\n)({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.NullOr(Id),\n deviceNameHint: Schema.NullOr(Schema.String),\n deviceClassHint: Schema.NullOr(DeviceClass),\n url: Schema.String,\n expiresAt: DateTimeString,\n consumedAt: Schema.NullOr(DateTimeString),\n consumedDeviceId: Schema.NullOr(Id),\n createdAt: DateTimeString,\n}) {}\n\nexport const CreateRegistrationRequestBody = Schema.Struct({\n deviceNameHint: Schema.optional(Schema.String.pipe(Schema.maxLength(120))),\n deviceClassHint: Schema.optional(DeviceClass),\n ttlHours: Schema.optional(Schema.Number.pipe(Schema.int(), Schema.between(1, 168))),\n appleTeamId: Schema.optional(Id),\n});\n\nexport const ListRegistrationRequestsParams = Schema.Struct({\n active: Schema.optional(Schema.Literal(\"true\", \"false\")),\n appleTeamId: Schema.optional(Id),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n CreateRegistrationRequestBody,\n DeleteDeviceResult,\n Device,\n DeviceRegistrationRequest,\n ListDevicesParams,\n ListRegistrationRequestsParams,\n RegisterDeviceBody,\n UpdateDeviceBody,\n} from \"../domain/device\";\nimport { Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class DevicesGroup extends HttpApiGroup.make(\"devices\")\n .add(\n HttpApiEndpoint.post(\"register\", \"/api/devices\")\n .setPayload(RegisterDeviceBody)\n .addSuccess(Device, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Register device\",\n description: \"Register an Apple device UDID in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/devices\")\n .setUrlParams(ListDevicesParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Device),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List devices\",\n description: \"List registered Apple devices in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/devices/${idParam}`.addSuccess(Device).annotateContext(\n OpenApi.annotations({\n title: \"Get device\",\n description: \"Get a single device by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/devices/${idParam}`\n .setPayload(UpdateDeviceBody)\n .addSuccess(Device)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update device\",\n description: \"Rename a device or toggle its enabled state\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/devices/${idParam}`\n .addSuccess(DeleteDeviceResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete device\",\n description: \"Remove a registered device from the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"createRegistrationRequest\", \"/api/devices/registration-requests\")\n .setPayload(CreateRegistrationRequestBody)\n .addSuccess(DeviceRegistrationRequest, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create device registration request\",\n description:\n \"Generate a URL + QR code for self-service device enrollment via Safari on iOS\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"listRegistrationRequests\", \"/api/devices/registration-requests\")\n .setUrlParams(ListRegistrationRequestsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(DeviceRegistrationRequest),\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List device registration requests\",\n description: \"List outstanding device registration invites\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Devices\",\n description: \"Apple device management for ad-hoc builds\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const EnvVarVisibility = Schema.Literal(\"plaintext\", \"sensitive\", \"secret\");\n\nexport class EnvVar extends Schema.Class<EnvVar>(\"EnvVar\")({\n id: Id,\n organizationId: Id,\n projectId: Id,\n environment: Schema.String,\n key: Schema.String,\n visibility: EnvVarVisibility,\n value: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\n// Key validation: uppercase letters, digits, underscores. Must start with letter.\nconst EnvVarKey = Schema.String.pipe(Schema.pattern(/^[A-Z][A-Z0-9_]*$/u), Schema.maxLength(256));\n\nconst EnvVarValue = Schema.String.pipe(Schema.maxLength(32_768));\n\nconst EnvVarEnvironment = Schema.String.pipe(Schema.minLength(1), Schema.maxLength(64));\n\nexport const CreateEnvVarBody = Schema.Struct({\n projectId: Id,\n environment: EnvVarEnvironment,\n key: EnvVarKey,\n value: EnvVarValue,\n visibility: EnvVarVisibility,\n});\n\nexport const UpdateEnvVarBody = Schema.Struct({\n value: Schema.optional(EnvVarValue),\n visibility: Schema.optional(EnvVarVisibility),\n});\n\nexport const BulkImportEnvVarsBody = Schema.Struct({\n projectId: Id,\n environment: EnvVarEnvironment,\n content: Schema.String.pipe(Schema.maxLength(4_000_000)),\n visibility: EnvVarVisibility,\n});\n\nexport const BulkImportResult = Schema.Struct({\n created: Schema.Number,\n updated: Schema.Number,\n skipped: Schema.Number,\n});\n\nexport const DeleteEnvVarResult = Schema.Struct({\n id: Id,\n});\n\nexport const EnvVarExportItem = Schema.Struct({\n key: Schema.String,\n value: Schema.String,\n visibility: EnvVarVisibility,\n});\n\nexport const EnvVarExportResult = Schema.Struct({\n items: Schema.Array(EnvVarExportItem),\n environment: Schema.String,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { Id, PaginationParams } from \"../domain/common\";\nimport {\n BulkImportEnvVarsBody,\n BulkImportResult,\n CreateEnvVarBody,\n DeleteEnvVarResult,\n EnvVar,\n EnvVarExportResult,\n UpdateEnvVarBody,\n} from \"../domain/env-var\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class EnvVarsGroup extends HttpApiGroup.make(\"env-vars\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/env-vars\")\n .setPayload(CreateEnvVarBody)\n .addSuccess(EnvVar, { status: 201 })\n .addError(BadRequest)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Create environment variable\",\n description: \"Create a new environment variable for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/env-vars\")\n .setUrlParams(\n Schema.Struct({\n projectId: Id,\n environment: Schema.optional(Schema.String),\n ...PaginationParams.fields,\n }),\n )\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(EnvVar),\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List environment variables\",\n description: \"List environment variables with optional filters\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/env-vars/${idParam}`.addSuccess(EnvVar).annotateContext(\n OpenApi.annotations({\n title: \"Get environment variable\",\n description: \"Get an environment variable by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/env-vars/${idParam}`\n .setPayload(UpdateEnvVarBody)\n .addSuccess(EnvVar)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update environment variable\",\n description: \"Update an environment variable's value or visibility\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/env-vars/${idParam}`\n .addSuccess(DeleteEnvVarResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete environment variable\",\n description: \"Delete an environment variable\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"bulkImport\", \"/api/env-vars/bulk-import\")\n .setPayload(BulkImportEnvVarsBody)\n .addSuccess(BulkImportResult)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Bulk import environment variables\",\n description:\n \"Import environment variables from a dotenv-formatted string. Supports KEY=VALUE format with # comments. Quoted values (single/double) are unquoted. Multiline values are not supported.\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"export\", \"/api/env-vars/export\")\n .setUrlParams(\n Schema.Struct({\n projectId: Id,\n environment: Schema.String,\n }),\n )\n .addSuccess(EnvVarExportResult)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Export environment variables\",\n description: \"Export environment variables for a project environment\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Forbidden)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Environment Variables\",\n description: \"Manage environment variables for project builds and deployments\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport class GoogleServiceAccountKey extends Schema.Class<GoogleServiceAccountKey>(\n \"GoogleServiceAccountKey\",\n)({\n id: Id,\n organizationId: Id,\n clientEmail: Schema.String,\n privateKeyId: Schema.String,\n googleProjectId: Schema.String,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadGoogleServiceAccountKeyBody = Schema.Struct({\n json: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const DeleteGoogleServiceAccountKeyResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n DeleteGoogleServiceAccountKeyResult,\n GoogleServiceAccountKey,\n UploadGoogleServiceAccountKeyBody,\n} from \"../domain/google-service-account-key\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class GoogleServiceAccountKeysGroup extends HttpApiGroup.make(\"googleServiceAccountKeys\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/google/service-account-keys\")\n .addSuccess(Schema.Struct({ items: Schema.Array(GoogleServiceAccountKey) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Google service account keys\",\n description: \"List uploaded Google service account JSON keys\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/google/service-account-keys\")\n .setPayload(UploadGoogleServiceAccountKeyBody)\n .addSuccess(GoogleServiceAccountKey, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload service account key\",\n description: \"Upload a Google service account JSON key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/google/service-account-keys/${idParam}`\n .addSuccess(DeleteGoogleServiceAccountKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete service account key\",\n description: \"Remove a stored Google service account key\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Google Service Account Keys\",\n description: \"Manage Google Play + FCM service account JSON keys\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { BundleIdentifier, DistributionType } from \"./apple-provisioning-profile\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport class IosBundleConfiguration extends Schema.Class<IosBundleConfiguration>(\n \"IosBundleConfiguration\",\n)({\n id: Id,\n organizationId: Id,\n projectId: Id,\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n appleTeamId: Id,\n appleDistributionCertificateId: Schema.NullOr(Id),\n appleProvisioningProfileId: Schema.NullOr(Id),\n applePushKeyId: Schema.NullOr(Id),\n ascApiKeyId: Schema.NullOr(Id),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateIosBundleConfigurationBody = Schema.Struct({\n bundleIdentifier: BundleIdentifier,\n distributionType: DistributionType,\n appleTeamId: Id,\n appleDistributionCertificateId: Schema.optional(Id),\n appleProvisioningProfileId: Schema.optional(Id),\n applePushKeyId: Schema.optional(Id),\n ascApiKeyId: Schema.optional(Id),\n});\n\nexport const UpdateIosBundleConfigurationBody = Schema.Struct({\n appleDistributionCertificateId: Schema.optional(Schema.NullOr(Id)),\n appleProvisioningProfileId: Schema.optional(Schema.NullOr(Id)),\n applePushKeyId: Schema.optional(Schema.NullOr(Id)),\n ascApiKeyId: Schema.optional(Schema.NullOr(Id)),\n});\n\nexport const DeleteIosBundleConfigurationResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n CreateIosBundleConfigurationBody,\n DeleteIosBundleConfigurationResult,\n IosBundleConfiguration,\n UpdateIosBundleConfigurationBody,\n} from \"../domain/ios-bundle-configuration\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class IosBundleConfigurationsGroup extends HttpApiGroup.make(\"iosBundleConfigurations\")\n .add(\n HttpApiEndpoint.get(\"list\")`/api/projects/${projectIdParam}/ios-bundle-configurations`\n .addSuccess(Schema.Struct({ items: Schema.Array(IosBundleConfiguration) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List iOS bundle configurations\",\n description: \"List all iOS bundle configurations for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"create\")`/api/projects/${projectIdParam}/ios-bundle-configurations`\n .setPayload(CreateIosBundleConfigurationBody)\n .addSuccess(IosBundleConfiguration, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create iOS bundle configuration\",\n description: \"Bind certificate + profile + push + ASC to a bundle identifier\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.put(\"update\")`/api/ios-bundle-configurations/${idParam}`\n .setPayload(UpdateIosBundleConfigurationBody)\n .addSuccess(IosBundleConfiguration)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update iOS bundle configuration\",\n description: \"Change the credentials bound to an iOS bundle configuration\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/ios-bundle-configurations/${idParam}`\n .addSuccess(DeleteIosBundleConfigurationResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete iOS bundle configuration\",\n description: \"Remove an iOS bundle configuration binding\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"iOS Bundle Configurations\",\n description: \"Per-project per-bundle credential bindings\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { PaginationParams, DateTimeString, Id } from \"./common\";\n\nexport class Project extends Schema.Class<Project>(\"Project\")({\n id: Id,\n organizationId: Id,\n name: Schema.String,\n slug: Schema.String,\n createdAt: DateTimeString,\n lastActivityAt: DateTimeString,\n branchCount: Schema.Number,\n channelCount: Schema.Number,\n updateCount: Schema.Number,\n}) {}\n\nexport const ProjectSortColumn = Schema.Literal(\n \"lastActivityAt\",\n \"name\",\n \"createdAt\",\n \"branchCount\",\n \"channelCount\",\n \"updateCount\",\n);\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-lastActivityAt` (desc).\n */\nexport const ProjectSort = Schema.Union(\n ProjectSortColumn,\n Schema.TemplateLiteral(\"-\", ProjectSortColumn),\n);\n\nexport const ListProjectsParams = Schema.Struct({\n ...PaginationParams.fields,\n query: Schema.optional(Schema.String),\n sort: Schema.optional(ProjectSort),\n});\n\nexport const CreateProjectBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1)),\n slug: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const UpdateProjectBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const DeleteProjectResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { Conflict } from \"../domain/errors\";\nimport {\n CreateProjectBody,\n DeleteProjectResult,\n ListProjectsParams,\n Project,\n UpdateProjectBody,\n} from \"../domain/project\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst slugParam = HttpApiSchema.param(\"slug\", Schema.String);\n\nexport class ProjectsGroup extends HttpApiGroup.make(\"projects\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/projects\")\n .setPayload(CreateProjectBody)\n .addSuccess(Project, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create project\",\n description: \"Create a new project in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/projects\")\n .setUrlParams(ListProjectsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Project),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List projects\",\n description: \"List all projects in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/projects/${idParam}`.addSuccess(Project).annotateContext(\n OpenApi.annotations({\n title: \"Get project\",\n description: \"Get a single project by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"getBySlug\")`/api/projects/by-slug/${slugParam}`\n .addSuccess(Project)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get project by slug\",\n description: \"Get a single project by slug within the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"rename\")`/api/projects/${idParam}`\n .setPayload(UpdateProjectBody)\n .addSuccess(Project)\n .annotateContext(\n OpenApi.annotations({\n title: \"Rename project\",\n description: \"Rename a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/projects/${idParam}`\n .addSuccess(DeleteProjectResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete project\",\n description: \"Delete a project and all its branches, channels, and updates\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Projects\",\n description: \"Project management endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams, Platform } from \"./common\";\n\nexport class Update extends Schema.Class<Update>(\"Update\")({\n id: Id,\n branchId: Id,\n runtimeVersion: Schema.String,\n platform: Platform,\n message: Schema.String,\n metadataJson: Schema.String,\n extraJson: Schema.NullOr(Schema.String),\n groupId: Schema.String,\n rolloutPercentage: Schema.Number,\n isRollback: Schema.Boolean,\n signature: Schema.NullOr(Schema.String),\n certificateChain: Schema.NullOr(Schema.String),\n manifestBody: Schema.NullOr(Schema.String),\n directiveBody: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n}) {}\n\nexport const UpdateSortColumn = Schema.Literal(\n \"createdAt\",\n \"runtimeVersion\",\n \"platform\",\n \"rolloutPercentage\",\n);\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `runtimeVersion` (asc), `-createdAt` (desc).\n */\nexport const UpdateSort = Schema.Union(\n UpdateSortColumn,\n Schema.TemplateLiteral(\"-\", UpdateSortColumn),\n);\n\nexport const ListUpdatesParams = Schema.Struct({\n projectId: Id,\n branchId: Schema.optional(Id),\n platform: Schema.optional(Platform),\n ...PaginationParams.fields,\n sort: Schema.optional(UpdateSort),\n});\n\nexport const AssetRef = Schema.Struct({\n hash: Schema.String,\n key: Schema.String,\n isLaunch: Schema.Boolean,\n contentChecksum: Schema.optional(Schema.String),\n});\n\nexport const CreateUpdateBody = Schema.Struct({\n branch: Schema.String.pipe(Schema.minLength(1)),\n slug: Schema.String.pipe(Schema.minLength(1)),\n runtimeVersion: Schema.String.pipe(Schema.minLength(1)),\n platform: Platform,\n message: Schema.String,\n groupId: Schema.String.pipe(Schema.minLength(1)),\n metadata: Schema.Record({ key: Schema.String, value: Schema.Unknown }),\n extra: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n assets: Schema.Array(AssetRef),\n manifestBody: Schema.optional(Schema.String),\n directiveBody: Schema.optional(Schema.String),\n isRollback: Schema.optional(Schema.Boolean),\n signature: Schema.optional(Schema.String),\n certificateChain: Schema.optional(Schema.String),\n rolloutPercentage: Schema.optional(Schema.Number.pipe(Schema.int(), Schema.between(1, 100))),\n});\n\nexport const RepublishBody = Schema.Struct({\n sourceUpdateId: Schema.optional(Id),\n sourceGroupId: Schema.optional(Schema.String.pipe(Schema.minLength(1))),\n destinationBranchId: Schema.optional(Id),\n destinationChannel: Schema.optional(Schema.String.pipe(Schema.minLength(1))),\n message: Schema.optional(Schema.String),\n signedUpdates: Schema.optional(\n Schema.Array(\n Schema.Struct({\n sourceUpdateId: Id,\n manifestBody: Schema.String.pipe(Schema.minLength(1)),\n signature: Schema.String.pipe(Schema.minLength(1)),\n certificateChain: Schema.String.pipe(Schema.minLength(1)),\n }),\n ),\n ),\n});\n\nexport const RepublishResult = Schema.Struct({\n updates: Schema.Array(Update),\n});\n\nexport const DeleteUpdateResult = Schema.Struct({\n deleted: Schema.Number,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { UpdateRolloutBody } from \"../domain/common\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n CreateUpdateBody,\n DeleteUpdateResult,\n ListUpdatesParams,\n RepublishBody,\n RepublishResult,\n Update,\n} from \"../domain/update\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst groupIdParam = HttpApiSchema.param(\"groupId\", Schema.String);\n\nexport class UpdatesGroup extends HttpApiGroup.make(\"updates\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/updates\")\n .setPayload(CreateUpdateBody)\n .addSuccess(Update, { status: 201 })\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Create update\",\n description: \"Publish a new update (manifest + directive) to a branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/updates\")\n .setUrlParams(ListUpdatesParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Update),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List updates\",\n description: \"List updates for a project, optionally filtered by branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"deleteGroup\")`/api/updates/${groupIdParam}`\n .addSuccess(DeleteUpdateResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete update group\",\n description: \"Delete all updates in a group (paired iOS + Android updates)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"republish\", \"/api/updates/republish\")\n .setPayload(RepublishBody)\n .addSuccess(RepublishResult)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Republish update\",\n description: \"Cross-channel republish (promote) an update\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"editRollout\")`/api/updates/${idParam}/rollout`\n .setPayload(UpdateRolloutBody)\n .addSuccess(Update)\n .annotateContext(\n OpenApi.annotations({\n title: \"Edit per-update rollout\",\n description: \"Change the rollout percentage for a specific update\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"completeRollout\")`/api/updates/${idParam}/rollout/complete`\n .addSuccess(Update)\n .annotateContext(\n OpenApi.annotations({\n title: \"Complete per-update rollout\",\n description: \"End rollout — make update available to all devices\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"revertRollout\")`/api/updates/${idParam}/rollout/revert`\n .addSuccess(Update)\n .annotateContext(\n OpenApi.annotations({\n title: \"Revert per-update rollout\",\n description: \"End rollout — revert to previous update\",\n }),\n ),\n )\n .addError(BadRequest)\n .addError(NotFound)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Updates\",\n description: \"Update publishing, deletion, republish, and per-update rollout endpoints\",\n }),\n ) {}\n","import { HttpApi, OpenApi } from \"@effect/platform\";\n\nimport { Authentication } from \"./auth/middleware\";\nimport { AnalyticsGroup } from \"./groups/analytics\";\nimport { AndroidApplicationIdentifiersGroup } from \"./groups/android-application-identifiers\";\nimport { AndroidBuildCredentialsGroup } from \"./groups/android-build-credentials\";\nimport { AndroidUploadKeystoresGroup } from \"./groups/android-upload-keystores\";\nimport { AppleDistributionCertificatesGroup } from \"./groups/apple-distribution-certificates\";\nimport { AppleProvisioningProfilesGroup } from \"./groups/apple-provisioning-profiles\";\nimport { ApplePushKeysGroup } from \"./groups/apple-push-keys\";\nimport { AppleTeamsGroup } from \"./groups/apple-teams\";\nimport { AscApiKeysGroup } from \"./groups/asc-api-keys\";\nimport { AssetsGroup } from \"./groups/assets\";\nimport { AuditLogsGroup } from \"./groups/audit-logs\";\nimport { BranchesGroup } from \"./groups/branches\";\nimport { BuildCredentialsGroup } from \"./groups/build-credentials\";\nimport { BuildsGroup } from \"./groups/builds\";\nimport { ChannelsGroup } from \"./groups/channels\";\nimport { DevicesGroup } from \"./groups/devices\";\nimport { EnvVarsGroup } from \"./groups/env-vars\";\nimport { GoogleServiceAccountKeysGroup } from \"./groups/google-service-account-keys\";\nimport { IosBundleConfigurationsGroup } from \"./groups/ios-bundle-configurations\";\nimport { ProjectsGroup } from \"./groups/projects\";\nimport { UpdatesGroup } from \"./groups/updates\";\n\nexport class ManagementApi extends HttpApi.make(\"management-api\")\n .add(ProjectsGroup)\n .add(BranchesGroup)\n .add(ChannelsGroup)\n .add(UpdatesGroup)\n .add(AssetsGroup)\n .add(AnalyticsGroup)\n .add(BuildsGroup)\n .add(EnvVarsGroup)\n .add(AuditLogsGroup)\n .add(DevicesGroup)\n .add(AppleTeamsGroup)\n .add(AppleDistributionCertificatesGroup)\n .add(ApplePushKeysGroup)\n .add(AscApiKeysGroup)\n .add(AppleProvisioningProfilesGroup)\n .add(GoogleServiceAccountKeysGroup)\n .add(IosBundleConfigurationsGroup)\n .add(AndroidApplicationIdentifiersGroup)\n .add(AndroidUploadKeystoresGroup)\n .add(AndroidBuildCredentialsGroup)\n .add(BuildCredentialsGroup)\n .middleware(Authentication)\n .annotateContext(\n OpenApi.annotations({\n title: \"Better Update Management API\",\n version: \"1.0.0\",\n description: \"Management API for OTA update publishing, deployment, and analytics\",\n }),\n ) {}\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, NotAcceptable } from \"../domain/errors\";\n\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class ManifestGroup extends HttpApiGroup.make(\"manifest\")\n .add(\n HttpApiEndpoint.get(\"serve\")`/manifest/${projectIdParam}`\n .addError(BadRequest)\n .addError(NotFound)\n .addError(NotAcceptable)\n .annotateContext(\n OpenApi.annotations({\n title: \"Serve manifest\",\n description: \"Expo Updates protocol v1 manifest endpoint\",\n }),\n ),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"Protocol\",\n description: \"Expo Updates protocol endpoints\",\n }),\n ) {}\n","import { HttpApi, OpenApi } from \"@effect/platform\";\n\nimport { ManifestGroup } from \"./groups/manifest\";\n\n/**\n * Documentation-only contract for OpenAPI/Scalar generation.\n * The manifest endpoint bypasses HttpApiBuilder at runtime because the Expo Updates\n * protocol requires multipart/mixed responses that do not fit the standard pipeline.\n */\nexport class ProtocolApi extends HttpApi.make(\"protocol-api\")\n .add(ManifestGroup)\n .annotateContext(\n OpenApi.annotations({\n title: \"Better Update Protocol API\",\n version: \"1.0.0\",\n description: \"Expo Updates protocol endpoints (unauthenticated)\",\n }),\n ) {}\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const asRecord = (value: unknown): Record<string, unknown> | undefined =>\n isRecord(value) ? value : undefined;\n","/* eslint-disable eslint/max-classes-per-file -- dedicated error-taxonomy module: each error class is a small, purpose-built tag used across the CLI for Effect.catchTag */\n\nimport { Data } from \"effect\";\n\nexport class AuthRequiredError extends Data.TaggedError(\"AuthRequiredError\")<{\n readonly message: string;\n}> {}\n\nexport class ProjectNotLinkedError extends Data.TaggedError(\"ProjectNotLinkedError\")<{\n readonly message: string;\n}> {}\n\nexport class UploadFailedError extends Data.TaggedError(\"UploadFailedError\")<{\n readonly message: string;\n}> {}\n\nexport class BuildProfileError extends Data.TaggedError(\"BuildProfileError\")<{\n readonly message: string;\n}> {}\n\nexport class RuntimeVersionError extends Data.TaggedError(\"RuntimeVersionError\")<{\n readonly message: string;\n}> {}\n\nexport class MissingCredentialsError extends Data.TaggedError(\"MissingCredentialsError\")<{\n readonly message: string;\n readonly hint: string;\n}> {}\n\nexport class BuildFailedError extends Data.TaggedError(\"BuildFailedError\")<{\n readonly step: string;\n readonly exitCode: number;\n readonly message: string;\n}> {}\n\nexport class ReserveError extends Data.TaggedError(\"ReserveError\")<{\n readonly message: string;\n}> {}\n\nexport class CompleteError extends Data.TaggedError(\"CompleteError\")<{\n readonly message: string;\n}> {}\n\nexport class PresignedUrlExpiredError extends Data.TaggedError(\"PresignedUrlExpiredError\")<{\n readonly message: string;\n}> {}\n\nexport class ArtifactNotFoundError extends Data.TaggedError(\"ArtifactNotFoundError\")<{\n readonly message: string;\n}> {}\n\nexport class KeychainError extends Data.TaggedError(\"KeychainError\")<{\n readonly message: string;\n}> {}\n\nexport class ProvisioningError extends Data.TaggedError(\"ProvisioningError\")<{\n readonly message: string;\n}> {}\n\nexport class EnvExportError extends Data.TaggedError(\"EnvExportError\")<{\n readonly message: string;\n}> {}\n\nexport class UpdatePublishError extends Data.TaggedError(\"UpdatePublishError\")<{\n readonly message: string;\n}> {}\n\nexport class UpdateRollbackError extends Data.TaggedError(\"UpdateRollbackError\")<{\n readonly message: string;\n}> {}\n\nexport class UpdatePromoteError extends Data.TaggedError(\"UpdatePromoteError\")<{\n readonly message: string;\n}> {}\n\nexport class CredentialValidationError extends Data.TaggedError(\"CredentialValidationError\")<{\n readonly message: string;\n}> {}\n\nexport class AppleAuthError extends Data.TaggedError(\"AppleAuthError\")<{\n readonly message: string;\n}> {}\n\nexport class InvalidArgumentError extends Data.TaggedError(\"InvalidArgumentError\")<{\n readonly message: string;\n}> {}\n","export const formatCause = (cause: unknown): string => {\n if (cause instanceof Error) {\n return cause.message;\n }\n\n if (typeof cause === \"object\" && cause !== null) {\n const tagged = cause as { readonly _tag?: unknown; readonly message?: unknown };\n const tag = typeof tagged._tag === \"string\" ? tagged._tag : undefined;\n const message = typeof tagged.message === \"string\" ? tagged.message : undefined;\n if (tag && message) {\n return `${tag}: ${message}`;\n }\n if (message) {\n return message;\n }\n if (tag) {\n return tag;\n }\n }\n\n return String(cause);\n};\n","import process from \"node:process\";\n\nimport { Context, Effect, Layer } from \"effect\";\n\nconst definedEnvironment = (): Readonly<Record<string, string>> =>\n Object.fromEntries(\n Object.entries(process.env).flatMap(([key, value]) =>\n typeof value === \"string\" ? [[key, value] as const] : [],\n ),\n );\n\nexport class CliRuntime extends Context.Tag(\"cli/CliRuntime\")<\n CliRuntime,\n {\n readonly argv: readonly string[];\n readonly platform: NodeJS.Platform;\n readonly cwd: Effect.Effect<string>;\n readonly getEnv: (name: string) => Effect.Effect<string | undefined>;\n readonly homeDirectory: Effect.Effect<string>;\n readonly userName: Effect.Effect<string>;\n readonly commandEnvironment: (\n overrides?: Readonly<Record<string, string>>,\n ) => Effect.Effect<Readonly<Record<string, string>>>;\n readonly setExitCode: (code: number) => Effect.Effect<void>;\n }\n>() {}\n\nexport const CliRuntimeLive = Layer.succeed(CliRuntime, {\n argv: [...process.argv],\n platform: process.platform,\n cwd: Effect.sync(() => process.cwd()),\n getEnv: (name: string) => Effect.sync(() => process.env[name]),\n homeDirectory: Effect.sync(\n () => process.env[\"HOME\"] ?? process.env[\"USERPROFILE\"] ?? process.cwd(),\n ),\n userName: Effect.sync(() => process.env[\"USER\"] ?? process.env[\"USERNAME\"] ?? \"better-update\"),\n commandEnvironment: (overrides = {}) =>\n Effect.sync(() => ({\n ...definedEnvironment(),\n ...overrides,\n })),\n setExitCode: (code: number) =>\n Effect.sync(() => {\n process.exitCode = code;\n }),\n});\n","import path from \"node:path\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { AuthRequiredError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { CliRuntime } from \"./cli-runtime\";\n\nexport class AuthStore extends Context.Tag(\"cli/AuthStore\")<\n AuthStore,\n {\n readonly getToken: Effect.Effect<string, AuthRequiredError>;\n readonly saveToken: (token: string) => Effect.Effect<void, AuthRequiredError>;\n readonly clearToken: Effect.Effect<void>;\n }\n>() {}\n\nexport const AuthStoreLive = Layer.effect(\n AuthStore,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const authDir = path.join(homeDirectory, \".better-update\");\n const authFile = path.join(authDir, \"auth.json\");\n\n return {\n getToken: Effect.gen(function* () {\n const envToken = yield* runtime.getEnv(\"BETTER_UPDATE_TOKEN\");\n if (envToken) {\n return envToken;\n }\n\n const content = yield* fs.readFileString(authFile).pipe(\n Effect.mapError(\n () =>\n new AuthRequiredError({\n message: \"Not logged in. Run `better-update login` to authenticate.\",\n }),\n ),\n );\n\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(content),\n catch: () =>\n new AuthRequiredError({\n message: \"Corrupted auth file. Run `better-update login` to re-authenticate.\",\n }),\n });\n if (!isRecord(parsed)) {\n return yield* new AuthRequiredError({\n message: \"Invalid auth file. Run `better-update login` to re-authenticate.\",\n });\n }\n const { token } = parsed;\n if (typeof token !== \"string\") {\n return yield* new AuthRequiredError({\n message: \"Invalid auth file. Run `better-update login` to re-authenticate.\",\n });\n }\n\n return token;\n }),\n\n saveToken: (token: string) =>\n Effect.gen(function* () {\n yield* fs.makeDirectory(authDir, { recursive: true });\n yield* fs.chmod(authDir, 0o700);\n yield* fs.writeFileString(authFile, `${JSON.stringify({ token }, null, 2)}\\n`);\n yield* fs.chmod(authFile, 0o600);\n }).pipe(\n Effect.mapError(\n (cause) =>\n new AuthRequiredError({\n message: `Failed to save auth token: ${formatCause(cause)}`,\n }),\n ),\n ),\n\n clearToken: fs.remove(authFile).pipe(Effect.catchAll(() => Effect.void)),\n };\n }),\n);\n","import path from \"node:path\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Context, Data, Effect, Layer } from \"effect\";\n\nimport { CliRuntime } from \"./cli-runtime\";\n\nconst DEFAULT_BASE_URL = \"https://better-update.dev\";\nconst DEFAULT_WEB_URL = \"https://better-update.dev\";\n\nclass ConfigStoreParseError extends Data.TaggedError(\"ConfigStoreParseError\")<{\n readonly message: string;\n readonly cause: unknown;\n}> {}\n\nconst normalizeUrl = (value: string): string => value.replace(/\\/$/u, \"\");\n\nexport class ConfigStore extends Context.Tag(\"cli/ConfigStore\")<\n ConfigStore,\n {\n readonly getBaseUrl: Effect.Effect<string>;\n readonly getWebUrl: Effect.Effect<string>;\n }\n>() {}\n\nexport const ConfigStoreLive = Layer.effect(\n ConfigStore,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const configFile = path.join(homeDirectory, \".better-update\", \"config.json\");\n const readConfig = fs.readFileString(configFile).pipe(\n Effect.catchAll(() => Effect.succeed(\"\")),\n Effect.flatMap((content) =>\n content.length === 0\n ? Effect.succeed(undefined)\n : Effect.try({\n try: (): unknown => JSON.parse(content),\n catch: (cause) =>\n new ConfigStoreParseError({\n message: \"Config file contains invalid JSON\",\n cause,\n }),\n }).pipe(\n Effect.map((parsed) => (isRecord(parsed) ? parsed : undefined)),\n Effect.catchAll(() => Effect.succeed(undefined)),\n ),\n ),\n );\n const resolveBaseUrl = Effect.gen(function* () {\n const envUrl = yield* runtime.getEnv(\"BETTER_UPDATE_URL\");\n if (envUrl) {\n return normalizeUrl(envUrl);\n }\n\n const parsed = yield* readConfig;\n const baseUrl = parsed?.[\"baseUrl\"];\n if (typeof baseUrl === \"string\") {\n return normalizeUrl(baseUrl);\n }\n\n return DEFAULT_BASE_URL;\n });\n\n return {\n getBaseUrl: resolveBaseUrl,\n\n getWebUrl: Effect.gen(function* () {\n const envUrl = yield* runtime.getEnv(\"BETTER_UPDATE_WEB_URL\");\n if (envUrl) {\n return normalizeUrl(envUrl);\n }\n\n const parsed = yield* readConfig;\n const webUrl = parsed?.[\"webUrl\"];\n if (typeof webUrl === \"string\") {\n return normalizeUrl(webUrl);\n }\n\n return DEFAULT_WEB_URL;\n }),\n };\n }),\n);\n","import { ManagementApi } from \"@better-update/api\";\nimport { HttpApiClient, HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { AuthStore } from \"./auth-store\";\nimport { ConfigStore } from \"./config-store\";\n\nimport type { AuthRequiredError } from \"../lib/exit-codes\";\n\nconst client = HttpApiClient.make(ManagementApi);\nexport type ApiClient = Effect.Effect.Success<typeof client>;\n\nexport class ApiClientService extends Context.Tag(\"cli/ApiClient\")<\n ApiClientService,\n {\n readonly get: Effect.Effect<ApiClient, AuthRequiredError>;\n }\n>() {}\n\nexport const apiClient: Effect.Effect<ApiClient, AuthRequiredError, ApiClientService> =\n // eslint-disable-next-line unicorn/no-array-method-this-argument -- Effect.flatMap, not Array.prototype.flatMap; the second arg is a continuation, not a thisArg\n Effect.flatMap(ApiClientService, ({ get }) => get);\n\nexport const ApiClientLive = Layer.effect(\n ApiClientService,\n Effect.gen(function* () {\n const clientService = yield* HttpClient.HttpClient;\n const authStore = yield* AuthStore;\n const configStore = yield* ConfigStore;\n\n return {\n get: Effect.gen(function* () {\n const token = yield* authStore.getToken;\n const baseUrl = yield* configStore.getBaseUrl;\n return yield* HttpApiClient.make(ManagementApi, {\n transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),\n baseUrl,\n }).pipe(Effect.provideService(HttpClient.HttpClient, clientService));\n }),\n };\n }),\n);\n","export type JsonParseResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false };\n\nexport const parseJsonResult = (text: string): JsonParseResult => {\n // eslint-disable-next-line functional/no-try-statements -- JSON.parse exposes syntax errors via throw; this helper converts them to an explicit result value\n try {\n return { ok: true, value: JSON.parse(text) as unknown };\n } catch {\n return { ok: false };\n }\n};\n\nexport const safeJsonParse = (text: string): unknown => {\n const result = parseJsonResult(text);\n return result.ok ? result.value : null;\n};\n","import path from \"node:path\";\n\nimport { safeJsonParse } from \"@better-update/safe-json\";\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport type { Auth } from \"@expo/apple-utils\";\n\nimport { AppleAuthError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { CliRuntime } from \"./cli-runtime\";\n\n// The cookies payload accepted by @expo/apple-utils Auth.loginWithCookiesAsync.\n// Derived structurally so we don't depend on the un-exported `CookiesJSON` alias.\nexport type AppleSessionCookies = Parameters<typeof Auth.loginWithCookiesAsync>[0][\"cookies\"];\n\nexport interface SerializedAppleSession {\n readonly cookies: AppleSessionCookies;\n readonly teamId: string;\n readonly username: string;\n readonly providerId?: number;\n}\n\nexport class AppleSessionStore extends Context.Tag(\"cli/AppleSessionStore\")<\n AppleSessionStore,\n {\n readonly loadSession: Effect.Effect<SerializedAppleSession | null>;\n readonly saveSession: (session: SerializedAppleSession) => Effect.Effect<void, AppleAuthError>;\n readonly clearSession: Effect.Effect<void>;\n }\n>() {}\n\nexport const AppleSessionStoreLive = Layer.effect(\n AppleSessionStore,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const sessionDir = path.join(homeDirectory, \".better-update\");\n const sessionFile = path.join(sessionDir, \"apple-session.json\");\n\n return {\n loadSession: Effect.gen(function* () {\n const content = yield* fs\n .readFileString(sessionFile)\n .pipe(Effect.catchAll(() => Effect.succeed(null)));\n\n if (!content) {\n return null;\n }\n\n const parsed = safeJsonParse(content);\n if (!isRecord(parsed)) {\n return null;\n }\n\n if (\n typeof parsed[\"teamId\"] !== \"string\" ||\n typeof parsed[\"username\"] !== \"string\" ||\n !parsed[\"cookies\"]\n ) {\n return null;\n }\n\n const providerIdRaw = parsed[\"providerId\"];\n const hasProviderId = typeof providerIdRaw === \"number\" && Number.isInteger(providerIdRaw);\n\n // eslint-disable-next-line typescript/no-unsafe-type-assertion, typescript/no-unsafe-assignment -- AppleSessionCookies is an opaque cookies payload from @expo/apple-utils; round-tripped verbatim from disk\n const cookies = parsed[\"cookies\"] as AppleSessionCookies;\n\n const session: SerializedAppleSession = {\n // eslint-disable-next-line typescript/no-unsafe-assignment -- see disable on the `cookies` declaration above; same opaque value\n cookies,\n teamId: parsed[\"teamId\"],\n username: parsed[\"username\"],\n ...(hasProviderId ? { providerId: providerIdRaw } : {}),\n };\n return session;\n }),\n\n saveSession: (session: SerializedAppleSession) =>\n Effect.gen(function* () {\n yield* fs.makeDirectory(sessionDir, { recursive: true });\n yield* fs.chmod(sessionDir, 0o700);\n yield* fs.writeFileString(sessionFile, `${JSON.stringify(session, null, 2)}\\n`);\n yield* fs.chmod(sessionFile, 0o600);\n }).pipe(\n Effect.mapError(\n (cause) =>\n new AppleAuthError({\n message: `Failed to save Apple session: ${formatCause(cause)}`,\n }),\n ),\n ),\n\n clearSession: fs.remove(sessionFile).pipe(Effect.catchAll(() => Effect.void)),\n };\n }),\n);\n","import { FileSystem, HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { PresignedUrlExpiredError, UploadFailedError } from \"../lib/exit-codes\";\n\nconst EXPIRY_SAFETY_MARGIN_MS = 30_000;\n\nexport interface PutToPresignedUrlInput {\n readonly url: string;\n readonly filePath: string;\n readonly byteSize: number;\n readonly expiresAt: string;\n readonly headers?: Record<string, string>;\n}\n\nexport class PresignedUploadClient extends Context.Tag(\"cli/PresignedUploadClient\")<\n PresignedUploadClient,\n {\n readonly putToPresignedUrl: (\n input: PutToPresignedUrlInput,\n ) => Effect.Effect<void, PresignedUrlExpiredError | UploadFailedError>;\n }\n>() {}\n\nexport const PresignedUploadClientLive = Layer.effect(\n PresignedUploadClient,\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const fileSystem = yield* FileSystem.FileSystem;\n\n return {\n putToPresignedUrl: ({\n url,\n filePath,\n byteSize,\n expiresAt,\n headers,\n }: PutToPresignedUrlInput) =>\n Effect.gen(function* () {\n const now = Date.now();\n const expiryMs = new Date(expiresAt).getTime();\n if (Number.isNaN(expiryMs) || now > expiryMs - EXPIRY_SAFETY_MARGIN_MS) {\n return yield* new PresignedUrlExpiredError({\n message: `Presigned upload URL expired or too close to expiry (expiresAt=${expiresAt}).`,\n });\n }\n\n const request = yield* HttpClientRequest.put(url).pipe(\n HttpClientRequest.bodyFile(filePath),\n Effect.provideService(FileSystem.FileSystem, fileSystem),\n Effect.map(\n HttpClientRequest.setHeaders({\n \"content-length\": String(byteSize),\n ...headers,\n }),\n ),\n Effect.mapError(\n (cause) =>\n new UploadFailedError({\n message: `Failed to open artifact for upload: ${String(cause)}`,\n }),\n ),\n );\n\n const response = yield* client.execute(request).pipe(\n Effect.mapError(\n (cause) =>\n new UploadFailedError({\n message: `HTTP request to presigned URL failed: ${String(cause)}`,\n }),\n ),\n );\n\n if (response.status < 200 || response.status >= 300) {\n const body = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"));\n return yield* new UploadFailedError({\n message: `Presigned URL upload failed with status ${response.status}: ${body}`,\n });\n }\n return undefined;\n }),\n };\n }),\n);\n","import { Context, Effect, Layer } from \"effect\";\n\nimport { UpdatePublishError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { ApiClientService } from \"./api-client\";\nimport { PresignedUploadClient } from \"./presigned-upload\";\n\nexport interface UploadUpdateAssetInput {\n readonly path: string;\n readonly hash: string;\n readonly byteSize: number;\n readonly uploadUrl: string;\n readonly uploadExpiresAt: string;\n readonly uploadHeaders: Record<string, string>;\n}\n\nexport class UpdateAssetUploader extends Context.Tag(\"cli/UpdateAssetUploader\")<\n UpdateAssetUploader,\n {\n readonly uploadAssetBinary: (\n input: UploadUpdateAssetInput,\n ) => Effect.Effect<void, UpdatePublishError>;\n }\n>() {}\n\nexport const UpdateAssetUploaderLive = Layer.effect(\n UpdateAssetUploader,\n Effect.gen(function* () {\n const presignedUploadClient = yield* PresignedUploadClient;\n const apiService = yield* ApiClientService;\n\n return {\n uploadAssetBinary: (asset: UploadUpdateAssetInput) =>\n Effect.gen(function* () {\n const api = yield* apiService.get.pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Asset upload requires authentication: ${formatCause(cause)}`,\n }),\n ),\n );\n\n yield* presignedUploadClient\n .putToPresignedUrl({\n url: asset.uploadUrl,\n filePath: asset.path,\n byteSize: asset.byteSize,\n expiresAt: asset.uploadExpiresAt,\n headers: asset.uploadHeaders,\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Asset upload failed for ${asset.hash}: ${formatCause(cause)}`,\n }),\n ),\n );\n\n yield* api.assets.finalize({ path: { hash: asset.hash } }).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Asset finalize failed for ${asset.hash}: ${formatCause(cause)}`,\n }),\n ),\n );\n }),\n };\n }),\n);\n","import path from \"node:path\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem, HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { CliRuntime } from \"./cli-runtime\";\n\nconst NPM_REGISTRY_URL = \"https://registry.npmjs.org/@better-update/cli/latest\";\nconst CACHE_TTL_MS = 24 * 60 * 60 * 1000;\nconst REFRESH_TIMEOUT_MS = 3000;\n\ninterface VersionCacheEntry {\n readonly latest: string;\n readonly checkedAt: number;\n}\n\nexport class VersionCheck extends Context.Tag(\"cli/VersionCheck\")<\n VersionCheck,\n {\n readonly cachedLatest: Effect.Effect<string | undefined>;\n readonly cacheStale: Effect.Effect<boolean>;\n readonly refreshCache: Effect.Effect<void>;\n }\n>() {}\n\nexport const VersionCheckLive = Layer.effect(\n VersionCheck,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const httpClient = yield* HttpClient.HttpClient;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const cacheDir = path.join(homeDirectory, \".better-update\");\n const cacheFile = path.join(cacheDir, \"version-check.json\");\n\n const readCache: Effect.Effect<VersionCacheEntry | undefined> = Effect.gen(function* () {\n const content = yield* fs\n .readFileString(cacheFile)\n .pipe(Effect.catchAll(() => Effect.succeed(\"\")));\n if (content.length === 0) {\n return undefined;\n }\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(content),\n catch: () => \"parse-error\" as const,\n }).pipe(Effect.catchAll(() => Effect.succeed(undefined)));\n if (\n isRecord(parsed) &&\n typeof parsed[\"latest\"] === \"string\" &&\n typeof parsed[\"checkedAt\"] === \"number\"\n ) {\n return {\n latest: parsed[\"latest\"],\n checkedAt: parsed[\"checkedAt\"],\n } satisfies VersionCacheEntry;\n }\n return undefined;\n });\n\n return {\n cachedLatest: readCache.pipe(Effect.map((entry) => entry?.latest)),\n cacheStale: readCache.pipe(\n Effect.map((entry) => {\n if (!entry) {\n return true;\n }\n const elapsed = Date.now() - entry.checkedAt;\n return elapsed < 0 || elapsed > CACHE_TTL_MS;\n }),\n ),\n refreshCache: Effect.gen(function* () {\n const request = HttpClientRequest.get(NPM_REGISTRY_URL).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n );\n const response = yield* httpClient.execute(request);\n if (response.status < 200 || response.status >= 300) {\n return;\n }\n const body = yield* response.json;\n if (!isRecord(body) || typeof body[\"version\"] !== \"string\") {\n return;\n }\n const latest = body[\"version\"];\n yield* fs.makeDirectory(cacheDir, { recursive: true });\n yield* fs.writeFileString(\n cacheFile,\n `${JSON.stringify({ latest, checkedAt: Date.now() }, null, 2)}\\n`,\n );\n }).pipe(\n Effect.timeout(REFRESH_TIMEOUT_MS),\n Effect.catchAll(() => Effect.void),\n ),\n };\n }),\n);\n","import { FetchHttpClient } from \"@effect/platform\";\nimport { NodeContext } from \"@effect/platform-node\";\nimport { Layer } from \"effect\";\n\nimport { ApiClientLive } from \"./services/api-client\";\nimport { AppleSessionStoreLive } from \"./services/apple-session-store\";\nimport { AuthStoreLive } from \"./services/auth-store\";\nimport { CliRuntimeLive } from \"./services/cli-runtime\";\nimport { ConfigStoreLive } from \"./services/config-store\";\nimport { PresignedUploadClientLive } from \"./services/presigned-upload\";\nimport { UpdateAssetUploaderLive } from \"./services/update-asset-uploader\";\nimport { VersionCheckLive } from \"./services/version-check\";\n\nconst CliPlatformLayer = Layer.mergeAll(CliRuntimeLive, NodeContext.layer, FetchHttpClient.layer);\nconst CliStoreLayer = Layer.mergeAll(AuthStoreLive, ConfigStoreLive, AppleSessionStoreLive).pipe(\n Layer.provide(CliPlatformLayer),\n);\nconst CliAdapterDependencies = Layer.mergeAll(CliPlatformLayer, CliStoreLayer);\nconst ApiClientLayer = ApiClientLive.pipe(Layer.provide(CliAdapterDependencies));\nconst PresignedUploadLayer = PresignedUploadClientLive.pipe(Layer.provide(CliPlatformLayer));\nconst UpdateAssetUploaderLayer = UpdateAssetUploaderLive.pipe(\n Layer.provide(Layer.mergeAll(ApiClientLayer, PresignedUploadLayer)),\n);\nconst VersionCheckLayer = VersionCheckLive.pipe(Layer.provide(CliPlatformLayer));\n\nexport const CliLive = Layer.mergeAll(\n CliAdapterDependencies,\n ApiClientLayer,\n PresignedUploadLayer,\n UpdateAssetUploaderLayer,\n VersionCheckLayer,\n);\n","import { Console, Effect } from \"effect\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nexport const exitWith = (code: number, message: string): Effect.Effect<void, never, CliRuntime> =>\n Console.error(message).pipe(\n Effect.zipRight(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n yield* runtime.setExitCode(code);\n }),\n ),\n );\n","import { Effect } from \"effect\";\n\nimport { exitWith } from \"../application/command-exit\";\nimport { formatCause } from \"./format-error\";\n\nimport type { CliRuntime } from \"../services/cli-runtime\";\n\ntype ExitCode = 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\ninterface TaggedError {\n readonly message: string;\n}\n\ntype Handler = (error: TaggedError) => Effect.Effect<void, never, CliRuntime>;\n\nconst BASE_TAG_MAP: Record<string, ExitCode> = {\n AuthRequiredError: 3,\n ProjectNotLinkedError: 4,\n NotFound: 1,\n Conflict: 1,\n Forbidden: 1,\n BadRequest: 2,\n InvalidArgumentError: 2,\n};\n\nconst SYSTEM_TAG_MESSAGE: Record<string, (error: TaggedError) => string> = {\n SystemError: (error) => `Filesystem error: ${error.message}`,\n BadArgument: (error) => `Invalid argument: ${error.message}`,\n};\n\nconst SYSTEM_TAG_CODE: Record<string, ExitCode> = {\n SystemError: 6,\n BadArgument: 6,\n};\n\nexport const makeCommandErrorHandler = (\n extras: Record<string, ExitCode> = {},\n): (<Success, Requirements>(\n effect: Effect.Effect<Success, unknown, Requirements>,\n) => Effect.Effect<Success, never, Requirements | CliRuntime>) => {\n const combined = { ...BASE_TAG_MAP, ...extras };\n const handlers: Record<string, Handler> = {};\n for (const [tag, code] of Object.entries(combined)) {\n const systemFormat = SYSTEM_TAG_MESSAGE[tag];\n const resolvedCode = SYSTEM_TAG_CODE[tag] ?? code;\n handlers[tag] = (error) =>\n exitWith(resolvedCode, systemFormat ? systemFormat(error) : error.message);\n }\n\n return <Success, Requirements>(\n effect: Effect.Effect<Success, unknown, Requirements>,\n ): Effect.Effect<Success, never, Requirements | CliRuntime> => {\n const piped = effect.pipe(\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- Effect.catchTags tag-inference requires a literal object; we accept a dynamic handler map so tags are chosen at runtime\n Effect.catchTags(handlers as never),\n Effect.catchAll((cause) => exitWith(1, formatCause(cause))),\n );\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- catchTags narrowing lost when handlers is dynamic; re-narrow at the boundary\n return piped as Effect.Effect<Success, never, Requirements | CliRuntime>;\n };\n};\n","import { Effect } from \"effect\";\n\nimport { CliLive } from \"../app-layer\";\nimport { makeCommandErrorHandler } from \"./command-errors\";\n\ntype ExtraExitMap = Parameters<typeof makeCommandErrorHandler>[0];\n\nexport const runEffect = async <Value, Err, Req>(\n effect: Effect.Effect<Value, Err, Req>,\n extras: ExtraExitMap = {},\n): Promise<void> => {\n const handled = makeCommandErrorHandler(extras)(effect);\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CliLive provides every service the CLI handlers require; after makeCommandErrorHandler's catch-all the failure channel is `never`\n const provided = handled.pipe(Effect.provide(CliLive)) as Effect.Effect<Value>;\n return Effect.runPromise(provided.pipe(Effect.asVoid));\n};\n","import process from \"node:process\";\n\nimport { Effect } from \"effect\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { BuildProfileError, ProjectNotLinkedError } from \"./exit-codes\";\nimport { formatCause } from \"./format-error\";\n\nimport type { AppMeta, Platform, RawRuntimeVersion } from \"./build-profile\";\n\nexport interface ExpoConfig {\n readonly name?: string;\n readonly slug?: string;\n readonly version?: string;\n readonly runtimeVersion?: string | { readonly policy: string };\n readonly ios?: {\n readonly bundleIdentifier?: string;\n readonly buildNumber?: string;\n };\n readonly android?: {\n readonly package?: string;\n readonly versionCode?: number;\n };\n readonly extra?: {\n readonly betterUpdate?: {\n readonly projectId?: unknown;\n readonly profiles?: unknown;\n } & Record<string, unknown>;\n } & Record<string, unknown>;\n readonly [key: string]: unknown;\n}\n\nexport interface ConfigFilePaths {\n readonly staticConfigPath: string | null;\n readonly dynamicConfigPath: string | null;\n}\n\ninterface ExpoConfigModule {\n readonly getConfig: (\n projectRoot: string,\n options?: { readonly skipSDKVersionRequirement?: boolean },\n ) => { readonly exp: ExpoConfig };\n readonly modifyConfigAsync: (\n projectRoot: string,\n modifications: Record<string, unknown>,\n readOptions?: { readonly skipSDKVersionRequirement?: boolean },\n ) => Promise<{\n readonly type: \"success\" | \"warn\" | \"fail\";\n readonly message?: string;\n readonly config: ExpoConfig | null;\n }>;\n readonly getConfigFilePaths: (projectRoot: string) => ConfigFilePaths;\n}\n\nconst loadExpoConfigModule = (): ExpoConfigModule =>\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CJS require returns `any`; narrow at the @expo/config boundary\n require(\"@expo/config\") as ExpoConfigModule;\n\n// `@expo/config` resolves dynamic configs via Node's `require`, which caches the\n// Evaluated module by absolute path. For static-form `module.exports = {...}`\n// Files, top-level `process.env` reads are captured at first load and frozen,\n// So a subsequent `readExpoConfig` call with a different env overlay would\n// Silently return the stale cached object. Evicting the cached entry forces\n// Re-evaluation on every call so env overlays always take effect.\nconst clearDynamicConfigCache = (projectRoot: string): void => {\n const { dynamicConfigPath } = loadExpoConfigModule().getConfigFilePaths(projectRoot);\n if (dynamicConfigPath) {\n // eslint-disable-next-line typescript/no-dynamic-delete -- evict @expo/config-cached module so each readExpoConfig sees fresh process.env\n delete require.cache[dynamicConfigPath];\n }\n};\n\nconst applyEnvOverlay = (envVars: Record<string, string>): Record<string, string | undefined> => {\n const previous: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(envVars)) {\n previous[key] = process.env[key];\n process.env[key] = value;\n }\n return previous;\n};\n\nconst restoreEnv = (previous: Record<string, string | undefined>): void => {\n for (const [key, value] of Object.entries(previous)) {\n if (value === undefined) {\n // eslint-disable-next-line typescript/no-dynamic-delete -- restoring snapshot of arbitrary process.env keys captured at overlay time\n delete process.env[key];\n } else {\n process.env[key] = value;\n }\n }\n};\n\n/**\n * Resolve the Expo config via `@expo/config`, supporting `app.json`,\n * `app.config.json`, `app.config.js`, and `app.config.ts`.\n *\n * `envVars` are applied as a scoped overlay on `process.env` for the duration\n * of the call so dynamic configs (`app.config.js`/`.ts`) can read them without\n * leaking server-side secrets to child processes.\n */\nexport const readExpoConfig = (\n projectRoot: string,\n envVars: Record<string, string> = {},\n): Effect.Effect<ExpoConfig, ProjectNotLinkedError> =>\n Effect.acquireUseRelease(\n Effect.sync(() => {\n clearDynamicConfigCache(projectRoot);\n return applyEnvOverlay(envVars);\n }),\n () =>\n Effect.try({\n try: () =>\n loadExpoConfigModule().getConfig(projectRoot, { skipSDKVersionRequirement: true }).exp,\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to load Expo config from ${projectRoot}: ${formatCause(cause)}`,\n }),\n }),\n (previous) =>\n Effect.sync(() => {\n restoreEnv(previous);\n }),\n );\n\nexport const getConfigFilePaths = (\n projectRoot: string,\n): Effect.Effect<ConfigFilePaths, ProjectNotLinkedError> =>\n Effect.try({\n try: () => loadExpoConfigModule().getConfigFilePaths(projectRoot),\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to inspect Expo config paths in ${projectRoot}: ${formatCause(cause)}`,\n }),\n });\n\nexport const extractProjectId = (\n config: ExpoConfig,\n): Effect.Effect<string, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n const projectId = config.extra?.betterUpdate?.projectId;\n if (typeof projectId !== \"string\") {\n return yield* new ProjectNotLinkedError({\n message:\n \"Project not linked. Run `better-update link` to connect this project, or set extra.betterUpdate.projectId in your Expo config.\",\n });\n }\n return projectId;\n });\n\nexport const extractSlug = (config: ExpoConfig): Effect.Effect<string, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n if (typeof config.slug !== \"string\") {\n return yield* new ProjectNotLinkedError({\n message: \"Missing slug in your Expo config. Required to identify the project.\",\n });\n }\n return config.slug;\n });\n\n/** Convenience reader for command code: resolves projectRoot from CliRuntime. */\nexport const readProjectId: Effect.Effect<string, ProjectNotLinkedError, CliRuntime> = Effect.gen(\n function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const config = yield* readExpoConfig(projectRoot);\n return yield* extractProjectId(config);\n },\n);\n\nexport interface WriteProjectIdResult {\n readonly type: \"success\" | \"warn\";\n readonly configPath: string | null;\n readonly message?: string;\n}\n\nconst buildManualPasteHint = (id: string, message?: string): string => {\n const reason = message ? ` (${message})` : \"\";\n return [\n `Cannot write projectId to a dynamic Expo config${reason}.`,\n \"Add this to your config manually:\",\n \"\",\n ` extra: { betterUpdate: { projectId: \"${id}\" } }`,\n ].join(\"\\n\");\n};\n\nexport const writeProjectId = (\n projectRoot: string,\n id: string,\n): Effect.Effect<WriteProjectIdResult, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n const result = yield* Effect.tryPromise({\n try: async () =>\n loadExpoConfigModule().modifyConfigAsync(\n projectRoot,\n { extra: { betterUpdate: { projectId: id } } },\n { skipSDKVersionRequirement: true },\n ),\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to write projectId to Expo config: ${formatCause(cause)}`,\n }),\n });\n\n // `modifyConfigAsync` returns 'warn' with config: null when only a dynamic\n // Config exists (it can't write to .js/.ts) and 'fail' for hard errors.\n // Both indicate the projectId did NOT get persisted — surface a manual-paste hint.\n if (result.type === \"fail\" || (result.type === \"warn\" && result.config === null)) {\n return yield* new ProjectNotLinkedError({\n message: buildManualPasteHint(id, result.message),\n });\n }\n\n const paths = yield* getConfigFilePaths(projectRoot);\n return {\n type: result.type,\n configPath: paths.staticConfigPath,\n ...(result.message === undefined ? {} : { message: result.message }),\n } satisfies WriteProjectIdResult;\n });\n\nconst extractBuildNumber = (config: ExpoConfig, platform: Platform): string | undefined => {\n if (platform === \"ios\") {\n return config.ios?.buildNumber;\n }\n if (config.android?.versionCode === undefined) {\n return undefined;\n }\n return String(config.android.versionCode);\n};\n\nconst extractRawRuntimeVersion = (config: ExpoConfig): RawRuntimeVersion | undefined => {\n const raw = config.runtimeVersion;\n if (typeof raw === \"string\") {\n return raw;\n }\n // typeof null === \"object\" — guard before reading `policy` so configs that\n // explicitly clear runtimeVersion (e.g. `runtimeVersion: null` from a dynamic\n // config) fall through to undefined instead of crashing resolveRuntimeVersion.\n // eslint-disable-next-line typescript/no-unnecessary-condition -- runtime guard against `runtimeVersion: null` even though the static type excludes null\n if (typeof raw === \"object\" && raw !== null && typeof raw.policy === \"string\") {\n return { policy: raw.policy };\n }\n return undefined;\n};\n\n/**\n * Extract AppMeta from a resolved ExpoConfig (from `@expo/config`).\n */\nexport const readAppMeta = (\n config: ExpoConfig,\n platform: Platform,\n): Effect.Effect<AppMeta, BuildProfileError> =>\n Effect.gen(function* () {\n if (platform === \"ios\" && !config.ios) {\n return yield* new BuildProfileError({\n message:\n \"Missing ios section in your Expo config. Required for iOS builds (bundleIdentifier).\",\n });\n }\n if (platform === \"android\" && !config.android) {\n return yield* new BuildProfileError({\n message:\n \"Missing android section in your Expo config. Required for Android builds (package).\",\n });\n }\n\n return {\n bundleId: config.ios?.bundleIdentifier,\n androidPackage: config.android?.package,\n appVersion: config.version,\n buildNumber: extractBuildNumber(config, platform),\n rawRuntimeVersion: extractRawRuntimeVersion(config),\n };\n });\n","import { Console, Effect } from \"effect\";\n\nexport const printTable = (\n headers: readonly string[],\n rows: readonly (readonly string[])[],\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const allRows = [headers, ...rows];\n const colWidths = headers.map((_, colIndex) =>\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- table padding for ragged rows; missing cell treated as empty-width\n Math.max(...allRows.map((row) => (row[colIndex] ?? \"\").length)),\n );\n\n const formatRow = (row: readonly string[]): string =>\n row.map((cell, idx) => cell.padEnd(colWidths[idx] ?? 0)).join(\" \");\n\n yield* Console.log(formatRow(headers));\n yield* Console.log(colWidths.map((width) => \"-\".repeat(width)).join(\" \"));\n\n for (const row of rows) {\n yield* Console.log(formatRow(row));\n }\n });\n\nexport const printKeyValue = (pairs: readonly (readonly [string, string])[]): Effect.Effect<void> =>\n Effect.gen(function* () {\n const maxKeyLen = Math.max(...pairs.map(([key]) => key.length));\n\n for (const [key, value] of pairs) {\n yield* Console.log(`${key.padEnd(maxKeyLen)} ${value}`);\n }\n });\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const adoptionCommand = defineCommand({\n meta: { name: \"adoption\", description: \"Show update adoption across devices\" },\n args: {\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.adoption({\n urlParams: { projectId, ...periodFilter },\n });\n\n if (result.updates.length === 0) {\n yield* Console.log(\"No adoption data found.\");\n return;\n }\n\n yield* printTable(\n [\"Update ID\", \"Devices\", \"First Seen\", \"Last Seen\"],\n result.updates.map((update) => [\n update.updateId,\n String(update.devices),\n update.firstSeen,\n update.lastSeen,\n ]),\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const channelsCommand = defineCommand({\n meta: { name: \"channels\", description: \"Stats for a specific channel\" },\n args: {\n channel: { type: \"string\", required: true, description: \"Channel name\" },\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.channels({\n urlParams: { projectId, channel: args.channel, ...periodFilter },\n });\n\n yield* printKeyValue([\n [\"Channel\", result.channel],\n [\"Total Requests\", String(result.totalRequests)],\n [\"Unique Devices\", String(result.uniqueDevices)],\n [\"Manifest\", String(result.responseTypeDistribution.manifest)],\n [\"Directive\", String(result.responseTypeDistribution.directive)],\n [\"No Update\", String(result.responseTypeDistribution.no_update)],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const platformsCommand = defineCommand({\n meta: { name: \"platforms\", description: \"Stats by platform\" },\n args: {\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.platforms({\n urlParams: { projectId, ...periodFilter },\n });\n\n if (result.platforms.length === 0) {\n yield* Console.log(\"No platform data found.\");\n return;\n }\n\n yield* printTable(\n [\"Platform\", \"Requests\", \"Devices\"],\n result.platforms.map((platform) => [\n platform.platform,\n String(platform.requests),\n String(platform.devices),\n ]),\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const updatesCommand = defineCommand({\n meta: { name: \"updates\", description: \"Stats for a specific update\" },\n args: {\n \"update-id\": { type: \"string\", required: true, description: \"Update ID\" },\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.updates({\n urlParams: { projectId, updateId: args[\"update-id\"], ...periodFilter },\n });\n\n yield* printKeyValue([\n [\"Update ID\", result.updateId],\n [\"Total Requests\", String(result.totalRequests)],\n [\"Unique Devices\", String(result.uniqueDevices)],\n [\"Manifest\", String(result.byResponseType.manifest)],\n [\"Directive\", String(result.byResponseType.directive)],\n [\"No Update\", String(result.byResponseType.no_update)],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { adoptionCommand } from \"./adoption\";\nimport { channelsCommand } from \"./channels\";\nimport { platformsCommand } from \"./platforms\";\nimport { updatesCommand } from \"./updates\";\n\nexport const analyticsCommand = defineCommand({\n meta: { name: \"analytics\", description: \"View deployment analytics\" },\n subCommands: {\n adoption: adoptionCommand,\n updates: updatesCommand,\n channels: channelsCommand,\n platforms: platformsCommand,\n },\n});\n","import { Effect, ParseResult, Schema } from \"effect\";\n\nimport { InvalidArgumentError } from \"./exit-codes\";\n\nexport const RolloutPercentage = Schema.Number.pipe(\n Schema.int(),\n Schema.between(1, 100),\n).annotations({\n message: () => \"Rollout percentage must be between 1 and 100.\",\n identifier: \"RolloutPercentage\",\n});\n\nexport const KeyValuePair = Schema.Struct({\n key: Schema.String,\n value: Schema.String,\n});\nexport type KeyValuePair = Schema.Schema.Type<typeof KeyValuePair>;\n\nexport const KeyValueFromString = Schema.transformOrFail(Schema.String, KeyValuePair, {\n strict: true,\n decode: (input, _options, ast) => {\n const eqIndex = input.indexOf(\"=\");\n if (eqIndex <= 0) {\n return ParseResult.fail(\n new ParseResult.Type(ast, input, \"Invalid format. Use KEY=VALUE (e.g. API_KEY=abc123)\"),\n );\n }\n return ParseResult.succeed({\n key: input.slice(0, eqIndex),\n value: input.slice(eqIndex + 1),\n });\n },\n encode: ({ key, value }) => ParseResult.succeed(`${key}=${value}`),\n});\n\nexport const parseRolloutPercentage = (\n raw: string,\n flag: string,\n): Effect.Effect<number, InvalidArgumentError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(RolloutPercentage)(Number(raw)),\n catch: () =>\n new InvalidArgumentError({\n message: `--${flag} must be an integer between 1 and 100, got \"${raw}\".`,\n }),\n });\n\nexport const parseKeyValue = (raw: string): Effect.Effect<KeyValuePair, InvalidArgumentError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(KeyValueFromString)(raw),\n catch: () =>\n new InvalidArgumentError({\n message: \"Invalid format. Use KEY=VALUE (e.g. API_KEY=abc123)\",\n }),\n });\n\nexport const parseLimit = (\n raw: string | undefined,\n defaultValue: number,\n): Effect.Effect<number, InvalidArgumentError> => {\n if (raw === undefined) {\n return Effect.succeed(defaultValue);\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 1) {\n return Effect.fail(\n new InvalidArgumentError({ message: `--limit must be a positive integer, got \"${raw}\".` }),\n );\n }\n return Effect.succeed(parsed);\n};\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseLimit } from \"../../lib/cli-schemas\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List audit log entries\" },\n args: {\n \"resource-type\": { type: \"string\", description: \"Filter by resource type\" },\n from: { type: \"string\", description: \"ISO timestamp lower bound\" },\n to: { type: \"string\", description: \"ISO timestamp upper bound\" },\n limit: { type: \"string\", default: \"100\", description: \"Max rows (default 100)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const limit = yield* parseLimit(args.limit, 100);\n const api = yield* apiClient;\n\n const filters: Record<string, string> = {};\n if (args[\"resource-type\"]) {\n filters[\"resourceType\"] = args[\"resource-type\"];\n }\n if (args.from) {\n filters[\"from\"] = args.from;\n }\n if (args.to) {\n filters[\"to\"] = args.to;\n }\n\n const { items } = yield* api[\"audit-logs\"].list({\n urlParams: { ...filters, limit },\n });\n\n if (items.length === 0) {\n yield* Console.log(\"No audit log entries found.\");\n return;\n }\n\n yield* printTable(\n [\"ID\", \"Action\", \"Resource Type\", \"Resource ID\", \"Actor\", \"Source\", \"Created\"],\n items.map((log) => [\n log.id,\n log.action,\n log.resourceType,\n log.resourceId ?? \"-\",\n log.actorEmail,\n log.source,\n log.createdAt,\n ]),\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { listCommand } from \"./list\";\n\nexport const auditLogsCommand = defineCommand({\n meta: { name: \"audit-logs\", description: \"View audit logs\" },\n subCommands: {\n list: listCommand,\n },\n});\n","import { Effect } from \"effect\";\n\ninterface NumberedPage<Item> {\n readonly items: readonly Item[];\n readonly total: number;\n readonly page: number;\n readonly limit: number;\n}\n\nconst MAX_PAGES = 100;\n\n/**\n * Drain a page-numbered list endpoint into a single array. Used by CLI\n * commands that need the full set, not a page slice.\n */\nexport const drainPages = <Item, Err, Req>(\n fetchPage: (page: number) => Effect.Effect<NumberedPage<Item>, Err, Req>,\n): Effect.Effect<readonly Item[], Err, Req> => {\n const loop = (\n accumulator: readonly Item[],\n page: number,\n ): Effect.Effect<readonly Item[], Err, Req> =>\n fetchPage(page).pipe(\n Effect.flatMap((response) => {\n const next = [...accumulator, ...response.items];\n const fetched = page * response.limit;\n const reachedLimit = page >= MAX_PAGES || next.length >= response.total;\n return reachedLimit || fetched >= response.total\n ? Effect.succeed(next)\n : loop(next, page + 1);\n }),\n );\n return loop([], 1);\n};\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { drainPages } from \"../lib/drain-cursor\";\nimport { readProjectId } from \"../lib/expo-config\";\nimport { printKeyValue, printTable } from \"../lib/output\";\nimport { apiClient } from \"../services/api-client\";\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List branches for the linked project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const items = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n\n if (items.length === 0) {\n yield* Console.log(\"No branches found.\");\n return;\n }\n\n yield* printTable(\n [\"ID\", \"Name\", \"Created\"],\n items.map((branch) => [branch.id, branch.name, branch.createdAt]),\n );\n }),\n ),\n});\n\nconst createCommand = defineCommand({\n meta: { name: \"create\", description: \"Create a branch\" },\n args: {\n name: { type: \"string\", required: true, description: \"Branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const branch = yield* api.branches.create({\n payload: { projectId, name: args.name },\n });\n yield* printKeyValue([\n [\"ID\", branch.id],\n [\"Name\", branch.name],\n [\"Created\", branch.createdAt],\n ]);\n }),\n ),\n});\n\nconst renameCommand = defineCommand({\n meta: { name: \"rename\", description: \"Rename a branch\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Branch ID\" },\n name: { type: \"string\", required: true, description: \"New branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const branch = yield* api.branches.rename({\n path: { id: args.id },\n payload: { name: args.name },\n });\n yield* Console.log(`Branch renamed to \"${branch.name}\".`);\n }),\n ),\n});\n\nconst deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a branch\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Branch ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.branches.delete({ path: { id: args.id } });\n yield* Console.log(`Branch ${args.id} deleted.`);\n }),\n ),\n});\n\nexport const branchesCommand = defineCommand({\n meta: { name: \"branches\", description: \"Manage branches\" },\n subCommands: {\n list: listCommand,\n create: createCommand,\n rename: renameCommand,\n delete: deleteCommand,\n },\n});\n","export interface RenderSigningGradleInput {\n readonly keystorePath: string;\n readonly storePassword: string;\n readonly keyAlias: string;\n readonly keyPassword: string;\n}\n\n/**\n * Escape a Groovy single-quoted string literal: backslashes, single quotes,\n * and `$` (to prevent string interpolation on Groovy double-quoted strings,\n * though we use single quotes everywhere for safety).\n */\nconst escapeGroovySingleQuoted = (value: string): string =>\n value\n .replaceAll(\"\\\\\", String.raw`\\\\`)\n .replaceAll(\"'\", String.raw`\\'`)\n .replaceAll(\"$\", String.raw`\\$`);\n\n/**\n * Render a Gradle init script that injects a `release` signing config into\n * every Android application module after evaluation. This is passed to\n * `./gradlew --init-script <path>` so the keystore never has to live in the\n * project tree.\n */\nexport const renderSigningGradle = ({\n keystorePath,\n storePassword,\n keyAlias,\n keyPassword,\n}: RenderSigningGradleInput): string =>\n `allprojects {\n afterEvaluate { project ->\n if (project.plugins.hasPlugin('com.android.application')) {\n project.android {\n signingConfigs {\n release {\n storeFile file('${escapeGroovySingleQuoted(keystorePath)}')\n storePassword '${escapeGroovySingleQuoted(storePassword)}'\n keyAlias '${escapeGroovySingleQuoted(keyAlias)}'\n keyPassword '${escapeGroovySingleQuoted(keyPassword)}'\n }\n }\n buildTypes {\n release {\n signingConfig signingConfigs.release\n }\n }\n }\n }\n }\n}\n`;\n","export const capitalize = (value: string): string => {\n const [first] = value;\n return first === undefined ? value : `${first.toUpperCase()}${value.slice(1)}`;\n};\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Option } from \"effect\";\nimport { maxBy } from \"es-toolkit\";\n\nimport type { PlatformError } from \"@effect/platform/Error\";\n\nimport { ArtifactNotFoundError } from \"./exit-codes\";\nimport { capitalize } from \"./string-utils\";\n\nexport interface FindIosArtifactOptions {\n readonly exportPath: string;\n}\n\nexport interface FindAndroidArtifactOptions {\n readonly projectRoot: string;\n readonly format: \"apk\" | \"aab\";\n readonly flavor?: string;\n readonly buildType: \"debug\" | \"release\";\n /**\n * If provided, only artifacts with mtimeMs >= this value are considered.\n * Used to exclude stale artifacts from previous builds when the current\n * build failed to write an expected output.\n */\n readonly minMtimeMs?: number;\n}\n\ninterface FoundFile {\n readonly path: string;\n readonly mtimeMs: number;\n}\n\nconst walkAndFind = (\n root: string,\n extension: string,\n): Effect.Effect<readonly FoundFile[], PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n // No fs.exists pre-check: readDirectory on a missing/non-dir path fails\n // With a PlatformError that we catch into an empty list below.\n const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));\n\n const results: FoundFile[] = [];\n for (const entry of entries) {\n const fullPath = path.join(root, entry);\n const stat = yield* fs.stat(fullPath).pipe(Effect.option);\n if (Option.isSome(stat)) {\n const info = stat.value;\n if (info.type === \"Directory\") {\n const nested = yield* walkAndFind(fullPath, extension);\n results.push(...nested);\n } else if (info.type === \"File\" && entry.toLowerCase().endsWith(extension)) {\n results.push({\n path: fullPath,\n mtimeMs: Option.match(info.mtime, {\n onNone: () => 0,\n onSome: (date) => date.getTime(),\n }),\n });\n }\n }\n }\n return results;\n });\n\nconst newest = (files: readonly FoundFile[], minMtimeMs?: number): FoundFile | undefined => {\n const eligible =\n minMtimeMs === undefined ? files : files.filter((file) => file.mtimeMs >= minMtimeMs);\n return maxBy(eligible, (file) => file.mtimeMs);\n};\n\nexport const findIosArtifact = ({\n exportPath,\n}: FindIosArtifactOptions): Effect.Effect<\n string,\n ArtifactNotFoundError | PlatformError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const files = yield* walkAndFind(exportPath, \".ipa\");\n const picked = newest(files);\n if (!picked) {\n return yield* new ArtifactNotFoundError({\n message: `No .ipa file found under \"${exportPath}\".`,\n });\n }\n return picked.path;\n });\n\nexport const findAndroidArtifact = ({\n projectRoot,\n format,\n flavor,\n buildType,\n minMtimeMs,\n}: FindAndroidArtifactOptions): Effect.Effect<\n string,\n ArtifactNotFoundError | PlatformError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const outputsRoot = path.join(projectRoot, \"android\", \"app\", \"build\", \"outputs\");\n const subdir = format === \"aab\" ? \"bundle\" : \"apk\";\n const variantDir = flavor ? `${flavor}${capitalize(buildType)}` : buildType;\n const expectedDir = path.join(outputsRoot, subdir, variantDir);\n\n const direct = yield* walkAndFind(expectedDir, `.${format}`);\n const pickedDirect = newest(direct, minMtimeMs);\n if (pickedDirect) {\n return pickedDirect.path;\n }\n\n const fallback = yield* walkAndFind(outputsRoot, `.${format}`);\n const pickedFallback = newest(fallback, minMtimeMs);\n if (!pickedFallback) {\n return yield* new ArtifactNotFoundError({\n message: `No .${format} artifact found under \"${outputsRoot}\"${minMtimeMs === undefined ? \"\" : \" (newer than build start)\"}.`,\n });\n }\n return pickedFallback.path;\n });\n","const asUint8Array = (data: Uint8Array | ArrayBuffer): Uint8Array =>\n data instanceof Uint8Array ? data : new Uint8Array(data);\n\nconst toBinaryString = (data: Uint8Array | ArrayBuffer): string =>\n Array.from(asUint8Array(data), (byte) => String.fromCodePoint(byte)).join(\"\");\n\nconst padBase64 = (value: string): string =>\n value.padEnd(value.length + ((4 - (value.length % 4)) % 4), \"=\");\n\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/u;\nconst BASE64_URL_PATTERN = /^[A-Za-z0-9_-]*={0,2}$/u;\nconst HEX_PATTERN = /^(?:[0-9A-Fa-f]{2})*$/u;\n\nconst normalizeBase64 = (value: string): string => {\n const compact = value.replaceAll(/\\s+/gu, \"\");\n if (!BASE64_PATTERN.test(compact) || compact.length % 4 === 1) {\n throw new RangeError(\"Invalid base64 string\");\n }\n return padBase64(compact);\n};\n\nconst normalizeBase64Url = (value: string): string => {\n const compact = value.replaceAll(/\\s+/gu, \"\");\n if (!BASE64_URL_PATTERN.test(compact) || compact.length % 4 === 1) {\n throw new RangeError(\"Invalid base64url string\");\n }\n return compact.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n};\n\nexport const toBase64 = (data: Uint8Array | ArrayBuffer): string => btoa(toBinaryString(data));\n\nexport const fromBase64 = (str: string): Uint8Array<ArrayBuffer> => {\n const binary = atob(normalizeBase64(str));\n return Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);\n};\n\nexport const toBase64Url = (data: Uint8Array | ArrayBuffer): string =>\n toBase64(data).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/u, \"\");\n\nexport const fromBase64Url = (str: string): Uint8Array<ArrayBuffer> =>\n fromBase64(padBase64(normalizeBase64Url(str)));\n\nexport const toHex = (bytes: Uint8Array | ArrayBuffer): string =>\n Array.from(asUint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\nexport const fromHex = (hex: string): Uint8Array<ArrayBuffer> => {\n if (!HEX_PATTERN.test(hex)) {\n throw new RangeError(\"Invalid hex string\");\n }\n return Uint8Array.from(hex.match(/.{2}/gu) ?? [], (byte) => Number.parseInt(byte, 16));\n};\n","import path from \"node:path\";\n\nimport { fromBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { PlatformError } from \"@effect/platform/Error\";\n\nimport { MissingCredentialsError } from \"./exit-codes\";\n\nimport type { ApiClient } from \"../services/api-client\";\nimport type { IosDistribution } from \"./build-profile\";\n\nexport interface DownloadIosCredentialsOptions {\n readonly projectId: string;\n readonly bundleIdentifier: string;\n readonly distribution: IosDistribution;\n readonly tempDir: string;\n}\n\nexport interface IosCredentials {\n readonly p12Path: string;\n readonly p12Password: string;\n readonly profilePath: string;\n readonly profileFilename: string;\n readonly teamId: string;\n}\n\nconst IOS_DISTRIBUTION_TO_TYPE = {\n \"app-store\": \"APP_STORE\",\n \"ad-hoc\": \"AD_HOC\",\n development: \"DEVELOPMENT\",\n enterprise: \"ENTERPRISE\",\n} as const satisfies Record<IosDistribution, \"APP_STORE\" | \"AD_HOC\" | \"DEVELOPMENT\" | \"ENTERPRISE\">;\n\nconst bindHint =\n \"Bind the bundle via the dashboard (Credentials → iOS Bundle Configurations) and make sure a distribution certificate, provisioning profile, and ASC API key are attached.\";\n\nconst permissionHint = \"Ask an org admin to grant the build-credentials download permission.\";\n\nconst androidBindHint =\n \"Register the package in the dashboard (Credentials → Android Build Credentials) and bind a keystore to the default group.\";\n\ninterface TaggedCause {\n readonly _tag: string;\n readonly message?: string;\n}\n\nconst hasTag = (cause: unknown): cause is TaggedCause =>\n typeof cause === \"object\" && cause !== null && \"_tag\" in cause;\n\nconst resolveErrorToMissingCredentials = (\n cause: unknown,\n platform: \"ios\" | \"android\",\n): MissingCredentialsError => {\n const tag = hasTag(cause) ? cause._tag : null;\n const message = hasTag(cause) && typeof cause.message === \"string\" ? cause.message : null;\n const platformLabel = platform === \"ios\" ? \"iOS\" : \"Android\";\n const bind = platform === \"ios\" ? bindHint : androidBindHint;\n\n if (tag === \"Forbidden\") {\n return new MissingCredentialsError({\n message: message ?? `Permission denied when resolving ${platformLabel} build credentials`,\n hint: permissionHint,\n });\n }\n if (tag === \"NotFound\") {\n return new MissingCredentialsError({\n message: message ?? `No ${platformLabel} build credentials configured`,\n hint: bind,\n });\n }\n if (tag === \"BadRequest\") {\n return new MissingCredentialsError({\n message: message ?? `${platformLabel} build credentials are misconfigured`,\n hint: bind,\n });\n }\n return new MissingCredentialsError({\n message: message ?? `Failed to resolve ${platformLabel} build credentials`,\n hint: bind,\n });\n};\n\nexport const downloadIosCredentials = (\n api: ApiClient,\n options: DownloadIosCredentialsOptions,\n): Effect.Effect<IosCredentials, MissingCredentialsError | PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n\n const resolved = yield* api.buildCredentials\n .resolve({\n path: { projectId: options.projectId },\n payload: {\n platform: \"ios\" as const,\n bundleIdentifier: options.bundleIdentifier,\n distributionType: IOS_DISTRIBUTION_TO_TYPE[options.distribution],\n },\n })\n .pipe(Effect.mapError((cause) => resolveErrorToMissingCredentials(cause, \"ios\")));\n\n if (resolved.platform !== \"ios\") {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"Server returned non-iOS credentials for an iOS build request\",\n hint: bindHint,\n }),\n );\n }\n\n const p12Path = path.join(options.tempDir, \"signing.p12\");\n const profileFilename = `${resolved.provisioningProfile.uuid ?? \"profile\"}.mobileprovision`;\n const profilePath = path.join(options.tempDir, profileFilename);\n\n yield* fs.writeFile(p12Path, fromBase64(resolved.distributionCertificate.p12Base64));\n yield* fs.writeFile(\n profilePath,\n fromBase64(resolved.provisioningProfile.mobileprovisionBase64),\n );\n\n return {\n p12Path,\n p12Password: resolved.distributionCertificate.p12Password,\n profilePath,\n profileFilename,\n teamId: resolved.provisioningProfile.teamId,\n };\n });\n\nexport interface DownloadAndroidCredentialsOptions {\n readonly projectId: string;\n readonly applicationIdentifier: string;\n readonly tempDir: string;\n}\n\nexport interface AndroidCredentials {\n readonly keystorePath: string;\n readonly storePassword: string;\n readonly keyAlias: string;\n readonly keyPassword: string;\n}\n\nexport const downloadAndroidCredentials = (\n api: ApiClient,\n options: DownloadAndroidCredentialsOptions,\n): Effect.Effect<\n AndroidCredentials,\n MissingCredentialsError | PlatformError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n\n const resolved = yield* api.buildCredentials\n .resolve({\n path: { projectId: options.projectId },\n payload: {\n platform: \"android\" as const,\n applicationIdentifier: options.applicationIdentifier,\n },\n })\n .pipe(Effect.mapError((cause) => resolveErrorToMissingCredentials(cause, \"android\")));\n\n if (resolved.platform !== \"android\") {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"Server returned non-Android credentials for an Android build request\",\n hint: androidBindHint,\n }),\n );\n }\n\n const keystorePath = path.join(options.tempDir, \"upload.keystore\");\n yield* fs.writeFile(keystorePath, fromBase64(resolved.keystore.keystoreBase64));\n\n return {\n keystorePath,\n storePassword: resolved.keystore.storePassword,\n keyAlias: resolved.keystore.keyAlias,\n keyPassword: resolved.keystore.keyPassword,\n };\n });\n","import { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\n\nimport { toBase64Url } from \"@better-update/encoding\";\nimport { Effect } from \"effect\";\n\nimport { BuildFailedError } from \"./exit-codes\";\n\nexport interface Sha256FileResult {\n readonly sha256: string;\n readonly byteSize: number;\n}\n\nexport interface Sha256FileBase64UrlResult {\n readonly sha256Base64Url: string;\n readonly byteSize: number;\n}\n\nconst hashReadError = (message: string) =>\n new BuildFailedError({\n step: \"sha256\",\n exitCode: 1,\n message,\n });\n\nconst hashFile = <TDigest>(\n path: string,\n formatDigest: (digest: Buffer) => TDigest,\n): Effect.Effect<{ digest: TDigest; byteSize: number }, BuildFailedError> =>\n Effect.async<{ digest: TDigest; byteSize: number }, BuildFailedError>((resume) => {\n const hash = createHash(\"sha256\");\n const stream = createReadStream(path);\n let byteSize = 0;\n\n stream.on(\"data\", (chunk) => {\n const buffer = typeof chunk === \"string\" ? Buffer.from(chunk) : chunk;\n byteSize += buffer.byteLength;\n hash.update(buffer);\n });\n stream.on(\"error\", (error) => {\n resume(Effect.fail(hashReadError(`Failed to read file for SHA-256: ${error.message}`)));\n });\n stream.on(\"end\", () => {\n resume(\n Effect.succeed({\n digest: formatDigest(hash.digest()),\n byteSize,\n }),\n );\n });\n });\n\n/**\n * Compute the SHA-256 digest and byte size of a file using Node's streaming\n * hash API. The file is never fully loaded into memory — chunks flow through\n * `createReadStream` into `crypto.createHash(\"sha256\")`.\n */\nexport const sha256File = (path: string): Effect.Effect<Sha256FileResult, BuildFailedError> =>\n hashFile(path, (digest) => digest.toString(\"hex\")).pipe(\n Effect.map(({ digest, byteSize }) => ({ sha256: digest, byteSize })),\n );\n\nexport const sha256FileBase64Url = (\n path: string,\n): Effect.Effect<Sha256FileBase64UrlResult, BuildFailedError> =>\n hashFile(path, toBase64Url).pipe(\n Effect.map(({ digest, byteSize }) => ({ sha256Base64Url: digest, byteSize })),\n );\n\n/**\n * Compute a content-type-namespaced hash: `SHA-256(contentType + '\\0' + SHA-256_hex(fileBytes))`.\n *\n * This prevents hash collisions when identical bytes are served with different\n * MIME types (e.g. same file used as both `application/javascript` and `text/plain`).\n * The raw content hash is still needed separately for R2 upload verification.\n */\nexport const sha256Namespaced = (contentType: string, contentSha256Hex: string): string => {\n const input = `${contentType}\\0${contentSha256Hex}`;\n return toBase64Url(createHash(\"sha256\").update(input).digest());\n};\n","import process from \"node:process\";\n\nimport { Command } from \"@effect/platform\";\nimport { Effect, Fiber, Stream } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { Scope } from \"effect\";\n\nimport { BuildFailedError } from \"../../lib/exit-codes\";\n\nimport type { XcodebuildFormatter } from \"../../lib/xcpretty-formatter\";\n\nexport const runStep = (\n cmd: Command.Command,\n step: string,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor> =>\n Command.exitCode(cmd.pipe(Command.stdout(\"inherit\"), Command.stderr(\"inherit\"))).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} failed to spawn: ${String(cause)}`,\n }),\n ),\n Effect.flatMap((code) =>\n code === 0\n ? Effect.void\n : Effect.fail(\n new BuildFailedError({\n step,\n exitCode: code,\n message: `${step} exited with code ${code}`,\n }),\n ),\n ),\n );\n\n/**\n * Run a build step with stdout piped through a formatter (e.g., xcpretty).\n * stderr passes through to the terminal directly.\n */\nexport const runStepFormatted = (\n cmd: Command.Command,\n step: string,\n formatter: XcodebuildFormatter,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor | Scope.Scope> =>\n Effect.gen(function* () {\n const proc = yield* Command.start(\n cmd.pipe(Command.stdout(\"pipe\"), Command.stderr(\"pipe\")),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} failed to spawn: ${String(cause)}`,\n }),\n ),\n );\n\n const stdoutFiber = yield* proc.stdout.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => {\n const formatted = formatter.pipe(line);\n return formatted.length > 0\n ? Effect.sync(() => {\n for (const output of formatted) {\n process.stdout.write(`${output}\\n`);\n }\n })\n : Effect.void;\n }),\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} stdout stream error: ${String(cause)}`,\n }),\n ),\n Effect.fork,\n );\n\n const stderrFiber = yield* proc.stderr.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => Effect.sync(() => process.stderr.write(`${line}\\n`))),\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} stderr stream error: ${String(cause)}`,\n }),\n ),\n Effect.fork,\n );\n\n // Join fibers concurrently — stream errors are non-fatal, exit code takes precedence.\n yield* Effect.all([Fiber.join(stdoutFiber), Fiber.join(stderrFiber)], {\n concurrency: 2,\n }).pipe(Effect.catchAll(() => Effect.void));\n\n const code = yield* proc.exitCode.pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} exit code error: ${String(cause)}`,\n }),\n ),\n );\n\n if (code !== 0) {\n // Print build summary on failure for xcpretty diagnostics\n const summary = formatter.getBuildSummary();\n if (summary) {\n process.stderr.write(`${summary}\\n`);\n }\n\n return yield* new BuildFailedError({\n step,\n exitCode: code,\n message: `${step} exited with code ${code}`,\n });\n }\n return undefined;\n });\n","import path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { PlatformError } from \"@effect/platform/Error\";\n\nimport { renderSigningGradle } from \"../../lib/android-signing-gradle\";\nimport { findAndroidArtifact } from \"../../lib/artifact-finder\";\nimport { downloadAndroidCredentials } from \"../../lib/credentials-downloader\";\nimport { sha256File } from \"../../lib/sha256\";\nimport { capitalize } from \"../../lib/string-utils\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\nimport { runStep } from \"./run-step\";\n\nimport type { AndroidProfile } from \"../../lib/build-profile\";\nimport type {\n ArtifactNotFoundError,\n BuildFailedError,\n MissingCredentialsError,\n} from \"../../lib/exit-codes\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nexport interface RunAndroidBuildInput {\n readonly api: ApiClient;\n readonly tempDir: string;\n readonly projectRoot: string;\n readonly androidProfile: AndroidProfile;\n readonly applicationIdentifier: string;\n readonly envVars: Record<string, string>;\n readonly projectId: string;\n}\n\nexport interface RunAndroidBuildResult {\n readonly artifactPath: string;\n readonly byteSize: number;\n readonly sha256: string;\n}\n\n/**\n * Compose the Gradle task name from flavor, format, and buildType.\n *\n * Gradle naming convention: `<verb><Flavor><Variant>`, e.g.\n * - no flavor + apk + release → `assembleRelease`\n * - no flavor + aab + release → `bundleRelease`\n * - flavor=prod + aab + release → `bundleProdRelease`\n * - flavor=prod + apk + debug → `assembleProdDebug`\n */\nconst gradleTaskName = (\n format: \"apk\" | \"aab\",\n flavor: string | undefined,\n buildType: \"debug\" | \"release\",\n): string => {\n const verb = format === \"aab\" ? \"bundle\" : \"assemble\";\n return flavor\n ? `${verb}${capitalize(flavor)}${capitalize(buildType)}`\n : `${verb}${capitalize(buildType)}`;\n};\n\nexport const runAndroidBuild = (\n input: RunAndroidBuildInput,\n): Effect.Effect<\n RunAndroidBuildResult,\n BuildFailedError | MissingCredentialsError | ArtifactNotFoundError | PlatformError,\n CliRuntime | CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const { api, tempDir, projectRoot, androidProfile, applicationIdentifier, envVars, projectId } =\n input;\n const runtime = yield* CliRuntime;\n\n // Record build start so artifact-finder can reject stale outputs from\n // Earlier builds that may still live in `android/app/build/outputs/`.\n const buildStartMs = Date.now();\n\n const { format } = androidProfile;\n const { flavor } = androidProfile;\n const buildType = androidProfile.buildType ?? \"release\";\n const androidDir = path.join(projectRoot, \"android\");\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n\n const credentials = yield* downloadAndroidCredentials(api, {\n projectId,\n applicationIdentifier,\n tempDir,\n });\n\n yield* runStep(\n Command.make(\"bunx\", \"expo\", \"prebuild\", \"--platform\", \"android\", \"--clean\").pipe(\n Command.workingDirectory(projectRoot),\n Command.env(commandEnv),\n ),\n \"expo prebuild android\",\n );\n\n const fs = yield* FileSystem.FileSystem;\n const signingGradlePath = path.join(tempDir, \"signing.gradle\");\n yield* fs.writeFileString(\n signingGradlePath,\n renderSigningGradle({\n keystorePath: credentials.keystorePath,\n storePassword: credentials.storePassword,\n keyAlias: credentials.keyAlias,\n keyPassword: credentials.keyPassword,\n }),\n );\n\n const taskName = gradleTaskName(format, flavor, buildType);\n yield* runStep(\n Command.make(\"./gradlew\", \"--init-script\", signingGradlePath, `:app:${taskName}`).pipe(\n Command.workingDirectory(androidDir),\n Command.env(commandEnv),\n ),\n \"gradlew\",\n );\n\n const artifactPath = yield* findAndroidArtifact({\n projectRoot,\n format,\n ...(flavor === undefined ? {} : { flavor }),\n buildType,\n minMtimeMs: buildStartMs,\n });\n\n const { sha256, byteSize } = yield* sha256File(artifactPath);\n\n return { artifactPath, byteSize, sha256 };\n });\n","export type ExportMethod = \"app-store\" | \"ad-hoc\" | \"enterprise\" | \"development\";\n\nexport interface RenderExportOptionsPlistInput {\n readonly method: ExportMethod;\n readonly teamId: string;\n readonly bundleId: string;\n readonly provisioningProfileName: string;\n readonly compileBitcode?: boolean;\n}\n\nconst escapeXml = (value: string): string =>\n value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n\nconst boolTag = (value: boolean): string => (value ? \"<true/>\" : \"<false/>\");\n\n/**\n * Render an Xcode `ExportOptions.plist` for `xcodebuild -exportArchive`.\n *\n * - `signingStyle` is always `manual` (ephemeral keychain + downloaded profile)\n * - `uploadSymbols` is emitted only for `app-store` exports\n * - `provisioningProfiles` dict maps bundleId → profile name\n * - `compileBitcode` defaults to `false`\n */\nexport const renderExportOptionsPlist = ({\n method,\n teamId,\n bundleId,\n provisioningProfileName,\n compileBitcode = false,\n}: RenderExportOptionsPlistInput): string => {\n const lines: string[] = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n \"<dict>\",\n \"\\t<key>method</key>\",\n `\\t<string>${escapeXml(method)}</string>`,\n \"\\t<key>teamID</key>\",\n `\\t<string>${escapeXml(teamId)}</string>`,\n \"\\t<key>signingStyle</key>\",\n \"\\t<string>manual</string>\",\n \"\\t<key>compileBitcode</key>\",\n `\\t${boolTag(compileBitcode)}`,\n \"\\t<key>provisioningProfiles</key>\",\n \"\\t<dict>\",\n `\\t\\t<key>${escapeXml(bundleId)}</key>`,\n `\\t\\t<string>${escapeXml(provisioningProfileName)}</string>`,\n \"\\t</dict>\",\n ];\n\n if (method === \"app-store\") {\n lines.push(\"\\t<key>uploadSymbols</key>\", \"\\t<true/>\");\n }\n\n lines.push(\"</dict>\", \"</plist>\", \"\");\n return lines.join(\"\\n\");\n};\n","import { randomBytes, randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { Command } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { Scope } from \"effect\";\n\nimport { KeychainError } from \"./exit-codes\";\n\nexport interface AcquireKeychainOptions {\n readonly tempDir: string;\n readonly p12Path: string;\n readonly p12Password: string;\n}\n\nexport interface KeychainHandle {\n readonly keychainName: string;\n readonly keychainPath: string;\n readonly signingIdentity: string;\n}\n\n// ── shell helpers ─────────────────────────────────────────────────\n\nconst runOrFail = (\n cmd: Command.Command,\n step: string,\n): Effect.Effect<string, KeychainError, CommandExecutor.CommandExecutor> =>\n Command.string(cmd).pipe(\n Effect.mapError(\n (cause) =>\n new KeychainError({\n message: `keychain ${step} failed: ${String(cause)}`,\n }),\n ),\n );\n\nconst listCurrentKeychains = Effect.gen(function* () {\n // `security list-keychains -d user` returns each keychain path on its own line,\n // Surrounded by double quotes and optionally preceded by whitespace.\n const output = yield* runOrFail(\n Command.make(\"security\", \"list-keychains\", \"-d\", \"user\"),\n \"list-keychains\",\n );\n return output\n .split(\"\\n\")\n .map((line) => line.trim().replace(/^\"/u, \"\").replace(/\"$/u, \"\"))\n .filter((line) => line.length > 0);\n});\n\n// Parse `security find-identity -v <keychain>` output to extract the first\n// Signing identity. Lines look like:\n// 1) 1A2B3C4D... \"Apple Distribution: Your Name (TEAMID)\"\nconst parseSigningIdentity = (output: string): string | undefined => {\n const lines = output.split(\"\\n\");\n for (const line of lines) {\n const match = /\"([^\"]+)\"/u.exec(line);\n if (match?.[1]) {\n return match[1];\n }\n }\n return undefined;\n};\n\n// ── acquireRelease ────────────────────────────────────────────────\n\n/**\n * Acquire an ephemeral macOS keychain, import a `.p12` into it, add it to the\n * user search list, and tear it all down on scope close. The keychain name is\n * namespaced as `better-update-<uuid>` and lives in `$tempDir`, so cleanup is\n * guaranteed under all termination paths.\n */\nexport const acquireKeychain = ({\n tempDir,\n p12Path,\n p12Password,\n}: AcquireKeychainOptions): Effect.Effect<\n KeychainHandle,\n KeychainError,\n CommandExecutor.CommandExecutor | Scope.Scope\n> => {\n const keychainName = `better-update-${randomUUID()}.keychain-db`;\n const keychainPath = path.join(tempDir, keychainName);\n const keychainPassword = randomBytes(32).toString(\"hex\");\n\n return Effect.acquireRelease(\n // ── acquire ─────────────────────────────────────────────────\n Effect.gen(function* () {\n const priorKeychains = yield* listCurrentKeychains;\n\n yield* runOrFail(\n Command.make(\"security\", \"create-keychain\", \"-p\", keychainPassword, keychainPath),\n \"create-keychain\",\n );\n\n yield* runOrFail(\n Command.make(\"security\", \"unlock-keychain\", \"-p\", keychainPassword, keychainPath),\n \"unlock-keychain\",\n );\n\n yield* runOrFail(\n Command.make(\"security\", \"set-keychain-settings\", \"-t\", \"3600\", \"-l\", keychainPath),\n \"set-keychain-settings\",\n );\n\n yield* runOrFail(\n Command.make(\n \"security\",\n \"import\",\n p12Path,\n \"-k\",\n keychainPath,\n \"-P\",\n p12Password,\n \"-T\",\n \"/usr/bin/codesign\",\n ),\n \"import\",\n );\n\n yield* runOrFail(\n Command.make(\n \"security\",\n \"set-key-partition-list\",\n \"-S\",\n \"apple-tool:,apple:,codesign:\",\n \"-s\",\n \"-k\",\n keychainPassword,\n keychainPath,\n ),\n \"set-key-partition-list\",\n );\n\n // Prepend our keychain to the search list while preserving the user's\n // Existing ones.\n yield* runOrFail(\n Command.make(\n \"security\",\n \"list-keychains\",\n \"-d\",\n \"user\",\n \"-s\",\n keychainPath,\n ...priorKeychains,\n ),\n \"list-keychains -s (add)\",\n );\n\n const identitiesOutput = yield* runOrFail(\n Command.make(\"security\", \"find-identity\", \"-v\", \"-p\", \"codesigning\", keychainPath),\n \"find-identity\",\n );\n const signingIdentity = parseSigningIdentity(identitiesOutput);\n if (!signingIdentity) {\n return yield* new KeychainError({\n message: \"No code signing identity found after importing .p12 into ephemeral keychain.\",\n });\n }\n\n return {\n handle: { keychainName, keychainPath, signingIdentity },\n priorKeychains,\n };\n }),\n\n // ── release ─────────────────────────────────────────────────\n ({ priorKeychains }) =>\n Effect.gen(function* () {\n // Restore the original search list first, then delete our keychain.\n yield* Command.string(\n Command.make(\"security\", \"list-keychains\", \"-d\", \"user\", \"-s\", ...priorKeychains),\n ).pipe(Effect.catchAll(() => Effect.void));\n\n yield* Command.string(Command.make(\"security\", \"delete-keychain\", keychainPath)).pipe(\n Effect.catchAll(() => Effect.void),\n );\n }),\n ).pipe(Effect.map(({ handle }) => handle));\n};\n","import plist from \"@expo/plist\";\n\nimport type { PlistObject } from \"@expo/plist\";\n// eslint-disable-next-line import-plugin/no-namespace -- bplist-parser typings have no named export; used only as `typeof BplistParser` for the CJS require result\nimport type * as BplistParser from \"bplist-parser\";\n\nexport type { PlistObject, PlistValue } from \"@expo/plist\";\n\n/**\n * Parse an XML plist string into a typed object.\n * Throws on malformed XML — callers should wrap in Effect.try.\n */\nexport const parsePlistXml = (xml: string): PlistObject =>\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- @expo/plist.parse returns `any`; PlistObject is the library's declared shape for XML plists\n plist.parse(xml) as PlistObject;\n\n/**\n * Parse a binary plist buffer into a typed object.\n * Uses bplist-parser for Apple's binary plist format.\n */\nexport const parsePlistBinary = (buffer: Buffer): PlistObject => {\n const bplistParser =\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CJS require returns `any`; narrow to the package's own typings at the boundary\n require(\"bplist-parser\") as typeof BplistParser;\n // eslint-disable-next-line typescript/no-unsafe-assignment -- bplist-parser typings declare parseBuffer<T>(): T[] with T=any in the shipped .d.ts\n const [result] = bplistParser.parseBuffer(buffer);\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- bplist-parser typings return `any[]`; PlistObject is the superset shape we consume\n return result as PlistObject;\n};\n\nconst BPLIST_MAGIC = Buffer.from(\"bplist00\");\n\n/**\n * Auto-detect plist format (binary vs XML) and parse accordingly.\n */\nexport const parsePlist = (data: Buffer): PlistObject =>\n data.subarray(0, 8).equals(BPLIST_MAGIC)\n ? parsePlistBinary(data)\n : parsePlistXml(data.toString(\"utf8\"));\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { Scope } from \"effect\";\n\nimport { ProvisioningError } from \"./exit-codes\";\nimport { parsePlistXml } from \"./plist\";\n\nimport type { PlistObject } from \"./plist\";\n\n// ── pure extraction ───────────────────────────────────────────────\n\nexport interface ProvisioningInfo {\n readonly uuid: string;\n readonly name: string;\n readonly teamId: string;\n}\n\nconst getString = (obj: PlistObject, key: string): string | undefined => {\n const value = obj[key];\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst getFirstArrayString = (obj: PlistObject, key: string): string | undefined => {\n const value = obj[key];\n if (Array.isArray(value) && typeof value[0] === \"string\") {\n return value[0];\n }\n return undefined;\n};\n\n/**\n * Extract `UUID`, `Name`, and the first `TeamIdentifier` from the XML plist\n * output of `security cms -D -i <path>`. Returns `ProvisioningError` when any\n * of the three fields are missing.\n */\nexport const extractProvisioningInfo = (\n plistXml: string,\n): Effect.Effect<ProvisioningInfo, ProvisioningError> =>\n Effect.gen(function* () {\n const parsed: PlistObject = yield* Effect.try({\n try: () => parsePlistXml(plistXml),\n catch: (error) =>\n new ProvisioningError({\n message: `Failed to parse provisioning profile plist: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n const uuid = getString(parsed, \"UUID\");\n const name = getString(parsed, \"Name\");\n const teamId = getFirstArrayString(parsed, \"TeamIdentifier\");\n\n if (!uuid || !name || !teamId) {\n return yield* new ProvisioningError({\n message:\n `Failed to parse provisioning profile: missing ${uuid ? \"\" : \"UUID \"}${name ? \"\" : \"Name \"}${teamId ? \"\" : \"TeamIdentifier \"}`.trim(),\n });\n }\n\n return { uuid, name, teamId };\n });\n\n// ── scoped installation ───────────────────────────────────────────\n\nexport interface InstallProvisioningProfileOptions {\n readonly profilePath: string;\n}\n\nexport interface InstalledProvisioning {\n readonly uuid: string;\n readonly name: string;\n readonly teamId: string;\n readonly installedPath: string;\n}\n\ninterface AcquiredProvisioning extends InstalledProvisioning {\n /**\n * True if we installed the profile (so release should delete it).\n * False if the profile was already present (e.g., installed by Xcode) —\n * in that case we leave it alone on release to avoid breaking the user's\n * other signing operations.\n */\n readonly ownsInstallation: boolean;\n}\n\nconst userProvisioningProfilesDir = (): string =>\n path.join(os.homedir(), \"Library\", \"MobileDevice\", \"Provisioning Profiles\");\n\n/**\n * Scoped installation of a provisioning profile: parses its metadata via\n * `security cms -D -i`, copies it into `~/Library/MobileDevice/Provisioning Profiles`\n * under `<uuid>.mobileprovision`, and removes the copy on scope close — but\n * only if we installed it. If the target file already existed when we arrived\n * (e.g., Xcode had it), we leave both the file and the contents untouched.\n */\nexport const installProvisioningProfile = ({\n profilePath,\n}: InstallProvisioningProfileOptions): Effect.Effect<\n InstalledProvisioning,\n ProvisioningError,\n CommandExecutor.CommandExecutor | FileSystem.FileSystem | Scope.Scope\n> =>\n Effect.acquireRelease(\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n\n const plistXml = yield* Command.string(\n Command.make(\"security\", \"cms\", \"-D\", \"-i\", profilePath),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new ProvisioningError({\n message: `security cms -D failed for ${profilePath}: ${String(cause)}`,\n }),\n ),\n );\n\n const info = yield* extractProvisioningInfo(plistXml);\n const targetDir = userProvisioningProfilesDir();\n const installedPath = path.join(targetDir, `${info.uuid}.mobileprovision`);\n\n yield* fs.makeDirectory(targetDir, { recursive: true }).pipe(\n Effect.catchAll(\n (cause) =>\n new ProvisioningError({\n message: `Failed to create provisioning profiles dir: ${String(cause)}`,\n }),\n ),\n );\n\n const alreadyInstalled = yield* fs\n .exists(installedPath)\n .pipe(Effect.orElseSucceed(() => false));\n\n if (alreadyInstalled) {\n return {\n ...info,\n installedPath,\n ownsInstallation: false,\n } satisfies AcquiredProvisioning;\n }\n\n yield* fs.copyFile(profilePath, installedPath).pipe(\n Effect.catchAll(\n (cause) =>\n new ProvisioningError({\n message: `Failed to copy provisioning profile into ${installedPath}: ${String(cause)}`,\n }),\n ),\n );\n\n return {\n ...info,\n installedPath,\n ownsInstallation: true,\n } satisfies AcquiredProvisioning;\n }),\n (acquired) =>\n Effect.gen(function* () {\n if (!acquired.ownsInstallation) {\n return;\n }\n const fs = yield* FileSystem.FileSystem;\n yield* fs.remove(acquired.installedPath).pipe(Effect.catchAll(() => Effect.void));\n }),\n ).pipe(\n Effect.map<AcquiredProvisioning, InstalledProvisioning>(\n ({ uuid, name, teamId, installedPath }) => ({\n uuid,\n name,\n teamId,\n installedPath,\n }),\n ),\n );\n","import path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { parsePlist, parsePlistXml } from \"./plist\";\n\nexport interface IosValidationParams {\n readonly archivePath: string;\n readonly expectedBundleId: string;\n readonly expectedTeamId: string;\n readonly expectedProfileUuid: string;\n}\n\nexport interface ValidationResult {\n readonly passed: boolean;\n readonly warnings: readonly string[];\n}\n\n/**\n * Validate an iOS build after xcodebuild completes. Checks:\n * 1. Bundle ID matches expected value\n * 2. Provisioning profile UUID matches\n * 3. Team ID matches\n *\n * All checks are non-blocking — returns warnings, never fails the build.\n */\nexport const validateIosBuild = (\n params: IosValidationParams,\n): Effect.Effect<\n ValidationResult,\n never,\n CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const appDir = yield* findAppDirectory(params.archivePath).pipe(\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n\n if (!appDir) {\n const warnings = [\"Could not locate .app bundle in archive — skipping post-build validation\"];\n return { passed: false, warnings };\n }\n\n const bundleWarning = yield* checkBundleId(appDir, params.expectedBundleId).pipe(\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n\n const profileWarnings = yield* checkEmbeddedProfile(\n appDir,\n params.expectedProfileUuid,\n params.expectedTeamId,\n ).pipe(Effect.catchAll(() => Effect.succeed([] as readonly string[])));\n\n const warnings: readonly string[] = [\n ...(bundleWarning ? [bundleWarning] : []),\n ...profileWarnings,\n ];\n\n if (warnings.length > 0) {\n yield* Console.warn(\"Post-build validation warnings:\");\n for (const warning of warnings) {\n yield* Console.warn(` - ${warning}`);\n }\n }\n\n return { passed: warnings.length === 0, warnings };\n });\n\n// ── helpers ──────────────────────────────────────────────────────\n\nconst findAppDirectory = (\n archivePath: string,\n): Effect.Effect<string, unknown, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const productsDir = path.join(archivePath, \"Products\", \"Applications\");\n const entries = yield* fs.readDirectory(productsDir);\n const appEntry = entries.find((entry) => entry.endsWith(\".app\"));\n if (!appEntry) {\n return yield* Effect.fail(\"No .app found\");\n }\n return path.join(productsDir, appEntry);\n });\n\nconst checkBundleId = (\n appDir: string,\n expectedBundleId: string,\n): Effect.Effect<string | undefined, unknown, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const plistPath = path.join(appDir, \"Info.plist\");\n const data = yield* fs.readFile(plistPath);\n const parsed = parsePlist(Buffer.from(data));\n const actualBundleId = parsed[\"CFBundleIdentifier\"];\n\n if (typeof actualBundleId === \"string\" && actualBundleId !== expectedBundleId) {\n return `Bundle ID mismatch: expected \"${expectedBundleId}\", got \"${actualBundleId}\"`;\n }\n return undefined;\n });\n\nconst checkEmbeddedProfile = (\n appDir: string,\n expectedUuid: string,\n expectedTeamId: string,\n): Effect.Effect<\n readonly string[],\n unknown,\n CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const warnings: string[] = [];\n const profilePath = path.join(appDir, \"embedded.mobileprovision\");\n\n // Use security cms to decrypt the profile (it's CMS-signed)\n const plistXml = yield* Command.string(\n Command.make(\"security\", \"cms\", \"-D\", \"-i\", profilePath),\n );\n\n const parsed = parsePlistXml(plistXml);\n\n const actualUuid = parsed[\"UUID\"];\n if (typeof actualUuid === \"string\" && actualUuid !== expectedUuid) {\n warnings.push(`Profile UUID mismatch: expected \"${expectedUuid}\", got \"${actualUuid}\"`);\n }\n\n const teamIdentifiers = parsed[\"TeamIdentifier\"];\n if (Array.isArray(teamIdentifiers)) {\n // eslint-disable-next-line typescript/no-unsafe-assignment -- @expo/plist types array entries as any; narrowed via typeof check below\n const [actualTeamId] = teamIdentifiers;\n if (typeof actualTeamId === \"string\" && actualTeamId !== expectedTeamId) {\n warnings.push(`Team ID mismatch: expected \"${expectedTeamId}\", got \"${actualTeamId}\"`);\n }\n }\n\n // Check expiration\n const expirationDate = parsed[\"ExpirationDate\"];\n if (expirationDate instanceof Date && expirationDate.getTime() < Date.now()) {\n warnings.push(`Embedded provisioning profile expired on ${expirationDate.toISOString()}`);\n }\n\n return warnings;\n });\n","import { ExpoRunFormatter } from \"@expo/xcpretty\";\n\nexport interface XcodebuildFormatter {\n /** Feed a line of raw xcodebuild output. Returns formatted lines (0 or more). */\n readonly pipe: (line: string) => readonly string[];\n /** Get a build summary after the process completes. */\n readonly getBuildSummary: () => string;\n}\n\n/**\n * Create a stateful xcodebuild output formatter backed by `@expo/xcpretty`.\n * Each `pipe(line)` call may return zero or more formatted lines — zero means\n * the line was suppressed (e.g., intermediate compiler invocations).\n */\nexport const createXcodebuildFormatter = (projectRoot: string): XcodebuildFormatter => {\n const formatter = ExpoRunFormatter.create(projectRoot);\n return {\n pipe: (line: string) => formatter.pipe(line),\n getBuildSummary: () => formatter.getBuildSummary(),\n };\n};\n","import path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { PlatformError } from \"@effect/platform/Error\";\nimport type { Scope } from \"effect\";\n\nimport { findIosArtifact } from \"../../lib/artifact-finder\";\nimport { downloadIosCredentials } from \"../../lib/credentials-downloader\";\nimport { BuildFailedError } from \"../../lib/exit-codes\";\nimport { renderExportOptionsPlist } from \"../../lib/ios-export-options\";\nimport { acquireKeychain } from \"../../lib/ios-keychain\";\nimport { installProvisioningProfile } from \"../../lib/ios-provisioning\";\nimport { validateIosBuild } from \"../../lib/post-build-validation\";\nimport { sha256File } from \"../../lib/sha256\";\nimport { createXcodebuildFormatter } from \"../../lib/xcpretty-formatter\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\nimport { runStep, runStepFormatted } from \"./run-step\";\n\nimport type { IosProfile } from \"../../lib/build-profile\";\nimport type {\n ArtifactNotFoundError,\n KeychainError,\n MissingCredentialsError,\n ProvisioningError,\n} from \"../../lib/exit-codes\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nexport interface RunIosBuildInput {\n readonly api: ApiClient;\n readonly tempDir: string;\n readonly projectRoot: string;\n readonly iosProfile: IosProfile;\n readonly bundleId: string;\n readonly envVars: Record<string, string>;\n readonly projectId: string;\n readonly rawOutput?: boolean | undefined;\n}\n\nexport interface RunIosBuildResult {\n readonly artifactPath: string;\n readonly byteSize: number;\n readonly sha256: string;\n}\n\nconst findXcworkspace = (\n iosDir: string,\n): Effect.Effect<string, BuildFailedError | PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const entries = yield* fs.readDirectory(iosDir);\n const workspace = entries.find((entry) => entry.endsWith(\".xcworkspace\"));\n if (!workspace) {\n return yield* new BuildFailedError({\n step: \"detect xcworkspace\",\n exitCode: 1,\n message: `No .xcworkspace found under ${iosDir}. Did \"pod install\" run?`,\n });\n }\n return workspace;\n });\n\nexport const runIosBuild = (\n input: RunIosBuildInput,\n): Effect.Effect<\n RunIosBuildResult,\n | BuildFailedError\n | MissingCredentialsError\n | KeychainError\n | ProvisioningError\n | ArtifactNotFoundError\n | PlatformError,\n CliRuntime | CommandExecutor.CommandExecutor | FileSystem.FileSystem | Scope.Scope\n> =>\n // eslint-disable-next-line eslint/max-statements -- ios build orchestration is inherently sequential (prebuild → pod → credentials → archive → exportArchive → find artifact → sha256); splitting further fragments the pipeline without clarifying it\n Effect.gen(function* () {\n const { api, tempDir, projectRoot, iosProfile, bundleId, envVars, projectId } = input;\n const runtime = yield* CliRuntime;\n\n const iosDir = path.join(projectRoot, \"ios\");\n const { distribution } = iosProfile;\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n\n // 1. Download credentials (p12 + mobileprovision) into tempDir.\n const credentials = yield* downloadIosCredentials(api, {\n projectId,\n bundleIdentifier: bundleId,\n distribution,\n tempDir,\n });\n\n // 2. Expo prebuild (ios).\n yield* runStep(\n Command.make(\"bunx\", \"expo\", \"prebuild\", \"--platform\", \"ios\", \"--clean\").pipe(\n Command.workingDirectory(projectRoot),\n Command.env(commandEnv),\n ),\n \"expo prebuild ios\",\n );\n\n // 3. pod install.\n yield* runStep(\n Command.make(\"pod\", \"install\").pipe(\n Command.workingDirectory(iosDir),\n Command.env(commandEnv),\n ),\n \"pod install\",\n );\n\n // 4. Scoped ephemeral keychain (auto-cleaned on scope close).\n const keychain = yield* acquireKeychain({\n tempDir,\n p12Path: credentials.p12Path,\n p12Password: credentials.p12Password,\n });\n\n // 5. Scoped provisioning profile install.\n const provisioning = yield* installProvisioningProfile({\n profilePath: credentials.profilePath,\n });\n\n // 6. Detect workspace + scheme.\n const workspaceFilename = yield* findXcworkspace(iosDir);\n const scheme = iosProfile.scheme ?? workspaceFilename.replace(/\\.xcworkspace$/u, \"\");\n const configuration = iosProfile.buildConfiguration ?? \"Release\";\n\n // 7. xcodebuild archive.\n const archivePath = path.join(tempDir, \"build.xcarchive\");\n const archiveCmd = Command.make(\n \"xcodebuild\",\n \"-workspace\",\n workspaceFilename,\n \"-scheme\",\n scheme,\n \"-configuration\",\n configuration,\n \"-archivePath\",\n archivePath,\n \"-allowProvisioningUpdates\",\n \"archive\",\n \"CODE_SIGN_STYLE=Manual\",\n `DEVELOPMENT_TEAM=${provisioning.teamId}`,\n `CODE_SIGN_IDENTITY=${keychain.signingIdentity}`,\n `PROVISIONING_PROFILE_SPECIFIER=${provisioning.name}`,\n ).pipe(Command.workingDirectory(iosDir), Command.env(commandEnv));\n\n const formatter = input.rawOutput ? undefined : createXcodebuildFormatter(projectRoot);\n yield* formatter\n ? runStepFormatted(archiveCmd, \"xcodebuild archive\", formatter)\n : runStep(archiveCmd, \"xcodebuild archive\");\n\n const fs = yield* FileSystem.FileSystem;\n const exportOptionsPath = path.join(tempDir, \"ExportOptions.plist\");\n yield* fs.writeFileString(\n exportOptionsPath,\n renderExportOptionsPlist({\n method: distribution,\n teamId: provisioning.teamId,\n bundleId,\n provisioningProfileName: provisioning.name,\n }),\n );\n\n // 9. xcodebuild exportArchive.\n const exportPath = path.join(tempDir, \"export\");\n const exportCmd = Command.make(\n \"xcodebuild\",\n \"-exportArchive\",\n \"-archivePath\",\n archivePath,\n \"-exportPath\",\n exportPath,\n \"-exportOptionsPlist\",\n exportOptionsPath,\n \"-allowProvisioningUpdates\",\n ).pipe(Command.workingDirectory(iosDir), Command.env(commandEnv));\n\n yield* formatter\n ? runStepFormatted(exportCmd, \"xcodebuild exportArchive\", formatter)\n : runStep(exportCmd, \"xcodebuild exportArchive\");\n\n // 10. Post-build validation (non-blocking).\n yield* validateIosBuild({\n archivePath,\n expectedBundleId: bundleId,\n expectedTeamId: provisioning.teamId,\n expectedProfileUuid: provisioning.uuid,\n });\n\n // 11. Locate artifact.\n const artifactPath = yield* findIosArtifact({ exportPath });\n\n // 12. SHA-256 + byte size.\n const { sha256, byteSize } = yield* sha256File(artifactPath);\n\n return { artifactPath, byteSize, sha256 };\n });\n","import { Effect } from \"effect\";\n\nimport { CompleteError, ReserveError } from \"../../lib/exit-codes\";\nimport { formatCause } from \"../../lib/format-error\";\nimport { PresignedUploadClient } from \"../../services/presigned-upload\";\n\nimport type { PresignedUrlExpiredError, UploadFailedError } from \"../../lib/exit-codes\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nexport type BuildTarget =\n | {\n readonly platform: \"ios\";\n readonly distribution: \"app-store\" | \"ad-hoc\" | \"development\" | \"enterprise\";\n readonly artifactFormat: \"ipa\";\n }\n | {\n readonly platform: \"ios\";\n readonly distribution: \"simulator\";\n readonly artifactFormat: \"tar.gz\";\n }\n | {\n readonly platform: \"android\";\n readonly distribution: \"play-store\";\n readonly artifactFormat: \"aab\";\n }\n | {\n readonly platform: \"android\";\n readonly distribution: \"direct\";\n readonly artifactFormat: \"apk\";\n };\n\nexport interface ReserveAndUploadInput {\n readonly target: BuildTarget;\n readonly projectId: string;\n readonly profileName: string;\n readonly runtimeVersion: string;\n readonly appVersion?: string;\n readonly buildNumber?: string;\n readonly bundleId: string;\n readonly gitContext: {\n readonly ref?: string;\n readonly commit?: string;\n readonly dirty: boolean;\n };\n readonly message?: string;\n readonly artifactPath: string;\n readonly sha256: string;\n readonly byteSize: number;\n}\n\nconst buildReserveCommon = (input: ReserveAndUploadInput) =>\n ({\n projectId: input.projectId,\n profile: input.profileName,\n runtimeVersion: input.runtimeVersion,\n bundleId: input.bundleId,\n sha256: input.sha256,\n byteSize: input.byteSize,\n ...(input.appVersion === undefined ? {} : { appVersion: input.appVersion }),\n ...(input.buildNumber === undefined ? {} : { buildNumber: input.buildNumber }),\n ...(input.gitContext.ref === undefined ? {} : { gitRef: input.gitContext.ref }),\n ...(input.gitContext.commit === undefined ? {} : { gitCommit: input.gitContext.commit }),\n ...(input.message === undefined ? {} : { message: input.message }),\n }) as const;\n\nconst callReserve = (api: ApiClient, input: ReserveAndUploadInput) => {\n const common = buildReserveCommon(input);\n const { target } = input;\n if (target.platform === \"ios\") {\n return target.distribution === \"simulator\"\n ? api.builds.reserve({\n payload: {\n ...common,\n platform: \"ios\",\n distribution: \"simulator\",\n artifactFormat: \"tar.gz\",\n },\n })\n : api.builds.reserve({\n payload: {\n ...common,\n platform: \"ios\",\n distribution: target.distribution,\n artifactFormat: \"ipa\",\n },\n });\n }\n return target.distribution === \"play-store\"\n ? api.builds.reserve({\n payload: {\n ...common,\n platform: \"android\",\n distribution: \"play-store\",\n artifactFormat: \"aab\",\n },\n })\n : api.builds.reserve({\n payload: { ...common, platform: \"android\", distribution: \"direct\", artifactFormat: \"apk\" },\n });\n};\n\nexport interface ReserveAndUploadResult {\n readonly id: string;\n readonly status: string;\n}\n\n/**\n * Reserve a build record on the server, upload the artifact to the returned\n * presigned URL, and finalize the build with its sha256 + byteSize.\n */\nexport const reserveAndUpload = (\n api: ApiClient,\n input: ReserveAndUploadInput,\n): Effect.Effect<\n ReserveAndUploadResult,\n ReserveError | UploadFailedError | PresignedUrlExpiredError | CompleteError,\n PresignedUploadClient\n> =>\n Effect.gen(function* () {\n const presignedUploadClient = yield* PresignedUploadClient;\n\n const reserveResult = yield* callReserve(api, input).pipe(\n Effect.mapError(\n (cause) =>\n new ReserveError({\n message: `Failed to reserve build: ${formatCause(cause)}`,\n }),\n ),\n );\n\n yield* presignedUploadClient.putToPresignedUrl({\n url: reserveResult.uploadUrl,\n filePath: input.artifactPath,\n byteSize: input.byteSize,\n expiresAt: reserveResult.uploadExpiresAt,\n headers: reserveResult.uploadHeaders,\n });\n\n const completed = yield* api.builds\n .complete({\n path: { id: reserveResult.id },\n payload: { sha256: input.sha256, byteSize: input.byteSize },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new CompleteError({\n message: `Failed to complete build ${reserveResult.id}: ${formatCause(cause)}`,\n }),\n ),\n );\n\n if (!completed.artifact) {\n return yield* new CompleteError({\n message: `Build ${completed.id} completed but server returned no artifact record.`,\n });\n }\n\n return { id: completed.id, status: \"uploaded\" };\n });\n","import { asRecord } from \"@better-update/type-guards\";\nimport { Effect } from \"effect\";\n\nimport { BuildProfileError } from \"./exit-codes\";\n\nimport type { ExpoConfig } from \"./expo-config\";\n\nexport type Platform = \"ios\" | \"android\";\n\nexport type IosDistribution = \"app-store\" | \"ad-hoc\" | \"development\" | \"enterprise\";\n\nexport interface IosProfile {\n readonly buildConfiguration?: string;\n readonly distribution: IosDistribution;\n readonly scheme?: string;\n}\n\nexport type AndroidDistribution = \"play-store\" | \"direct\";\n\nexport interface AndroidProfile {\n readonly buildType?: \"debug\" | \"release\";\n readonly format: \"apk\" | \"aab\";\n readonly flavor?: string;\n readonly distribution: AndroidDistribution;\n}\n\nexport interface BuildProfile {\n readonly name: string;\n readonly environment: string;\n readonly ios?: IosProfile;\n readonly android?: AndroidProfile;\n}\n\nexport type RawRuntimeVersion = string | { readonly policy: string };\n\nexport interface AppMeta {\n readonly bundleId: string | undefined;\n readonly androidPackage: string | undefined;\n readonly appVersion: string | undefined;\n readonly buildNumber: string | undefined;\n readonly rawRuntimeVersion: RawRuntimeVersion | undefined;\n}\n\nexport interface RuntimeVersionMeta {\n readonly appVersion: string | undefined;\n readonly rawRuntimeVersion: RawRuntimeVersion | undefined;\n}\n\nexport const asString = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined;\n\nconst VALID_IOS_DISTRIBUTIONS: readonly IosDistribution[] = [\n \"app-store\",\n \"ad-hoc\",\n \"development\",\n \"enterprise\",\n];\n\nconst isIosDistribution = (value: string): value is IosDistribution =>\n (VALID_IOS_DISTRIBUTIONS as readonly string[]).includes(value);\n\nconst readIosProfile = (raw: unknown): IosProfile | undefined => {\n const iosRaw = asRecord(raw);\n if (!iosRaw) {\n return undefined;\n }\n const distributionRaw = asString(iosRaw[\"distribution\"]);\n if (!distributionRaw) {\n return undefined;\n }\n if (!isIosDistribution(distributionRaw)) {\n return undefined;\n }\n const distribution: IosDistribution = distributionRaw;\n const buildConfiguration = asString(iosRaw[\"buildConfiguration\"]);\n const scheme = asString(iosRaw[\"scheme\"]);\n return {\n distribution,\n ...(buildConfiguration === undefined ? {} : { buildConfiguration }),\n ...(scheme === undefined ? {} : { scheme }),\n };\n};\n\nconst resolveAndroidDistribution = (\n raw: string | undefined,\n format: \"apk\" | \"aab\",\n): AndroidDistribution => {\n if (raw === \"play-store\" || raw === \"direct\") {\n return raw;\n }\n return format === \"aab\" ? \"play-store\" : \"direct\";\n};\n\nconst readAndroidProfile = (raw: unknown): AndroidProfile | undefined => {\n const androidRaw = asRecord(raw);\n if (!androidRaw) {\n return undefined;\n }\n const formatValue = asString(androidRaw[\"format\"]);\n const format = formatValue === \"apk\" || formatValue === \"aab\" ? formatValue : undefined;\n if (!format) {\n return undefined;\n }\n const buildTypeValue = asString(androidRaw[\"buildType\"]);\n const buildType =\n buildTypeValue === \"debug\" || buildTypeValue === \"release\" ? buildTypeValue : undefined;\n const flavor = asString(androidRaw[\"flavor\"]);\n const distribution = resolveAndroidDistribution(asString(androidRaw[\"distribution\"]), format);\n return {\n format,\n distribution,\n ...(buildType === undefined ? {} : { buildType }),\n ...(flavor === undefined ? {} : { flavor }),\n };\n};\n\nexport const readBuildProfile = (\n config: ExpoConfig,\n profileName: string,\n): Effect.Effect<BuildProfile, BuildProfileError> =>\n Effect.gen(function* () {\n const profiles = asRecord(config.extra?.betterUpdate?.profiles);\n if (!profiles) {\n return yield* new BuildProfileError({\n message: \"No build profiles defined. Add extra.betterUpdate.profiles to your Expo config.\",\n });\n }\n const profileRaw = asRecord(profiles[profileName]);\n if (!profileRaw) {\n return yield* new BuildProfileError({\n message: `Build profile \"${profileName}\" not found in your Expo config.`,\n });\n }\n const environment = asString(profileRaw[\"environment\"]) ?? \"production\";\n const ios = readIosProfile(profileRaw[\"ios\"]);\n const android = readAndroidProfile(profileRaw[\"android\"]);\n return {\n name: profileName,\n environment,\n ...(ios === undefined ? {} : { ios }),\n ...(android === undefined ? {} : { android }),\n };\n });\n\nexport const readRuntimeVersionMeta = (config: ExpoConfig): RuntimeVersionMeta => ({\n appVersion: config.version,\n rawRuntimeVersion: readRawRuntimeVersion(config.runtimeVersion),\n});\n\nconst readRawRuntimeVersion = (value: unknown): RawRuntimeVersion | undefined => {\n if (typeof value === \"string\") {\n return value;\n }\n const record = asRecord(value);\n const policy = asString(record?.[\"policy\"]);\n if (policy) {\n return { policy };\n }\n return undefined;\n};\n","import { Effect } from \"effect\";\n\nimport { EnvExportError } from \"./exit-codes\";\n\nimport type { ApiClient } from \"../services/api-client\";\n\nexport interface PullEnvVarsOptions {\n readonly projectId: string;\n readonly environment: string;\n}\n\n/**\n * Pull environment variables for a project + environment and flatten them into\n * a key/value map. Returns an empty map when the project has no variables.\n */\nexport const pullEnvVars = (\n api: ApiClient,\n { projectId, environment }: PullEnvVarsOptions,\n): Effect.Effect<Record<string, string>, EnvExportError> =>\n api[\"env-vars\"].export({ urlParams: { projectId, environment } }).pipe(\n Effect.map((result) => Object.fromEntries(result.items.map((item) => [item.key, item.value]))),\n Effect.mapError(\n (cause) =>\n new EnvExportError({\n message: `Failed to export environment variables for \"${environment}\": ${String(cause)}`,\n }),\n ),\n );\n","import { Command } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nexport interface GitContext {\n readonly ref: string | undefined;\n readonly commit: string | undefined;\n readonly commitMessage: string | undefined;\n readonly dirty: boolean;\n}\n\nconst runString = (\n cmd: Command.Command,\n cwd: string,\n): Effect.Effect<string, unknown, CommandExecutor.CommandExecutor> =>\n Command.string(Command.workingDirectory(cmd, cwd));\n\n/**\n * Best-effort git context extraction. If git is missing, the directory isn't\n * a repo, or any command fails, we silently return undefined fields so the\n * build can still proceed. This is intentional — git context is metadata,\n * not a requirement.\n */\nexport const readGitContext = (\n projectRoot: string,\n): Effect.Effect<GitContext, never, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const [commit, ref, commitMessage, status] = yield* Effect.all(\n [\n runString(Command.make(\"git\", \"rev-parse\", \"HEAD\"), projectRoot).pipe(\n Effect.map((output) => output.trim()),\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n runString(Command.make(\"git\", \"symbolic-ref\", \"--short\", \"HEAD\"), projectRoot).pipe(\n Effect.map((output) => output.trim()),\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n runString(Command.make(\"git\", \"log\", \"-1\", \"--format=%s\"), projectRoot).pipe(\n Effect.map((output) => output.trim()),\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n runString(Command.make(\"git\", \"status\", \"--porcelain\"), projectRoot).pipe(\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n ],\n { concurrency: \"unbounded\" },\n );\n\n return {\n ref: ref.length > 0 ? ref : undefined,\n commit: commit.length > 0 ? commit : undefined,\n commitMessage: commitMessage.length > 0 ? commitMessage : undefined,\n dirty: status.trim().length > 0,\n };\n });\n","import path from \"node:path\";\n\nimport { asRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nexport interface GradleConfig {\n readonly applicationId?: string;\n readonly versionCode?: number;\n readonly versionName?: string;\n}\n\n/**\n * Parse Groovy `build.gradle` to extract key Android config values.\n * Returns `undefined` if:\n * - Only `build.gradle.kts` exists (Kotlin DSL not supported by gradle-to-js)\n * - No build.gradle found at all\n * - Parse fails\n *\n * Informational only — never blocks the build.\n */\nexport const readGradleConfig = (\n androidDir: string,\n): Effect.Effect<GradleConfig | undefined, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const gradlePath = path.join(androidDir, \"app\", \"build.gradle\");\n const ktsPath = path.join(androidDir, \"app\", \"build.gradle.kts\");\n\n const hasGroovy = yield* fs.exists(gradlePath).pipe(Effect.orElseSucceed(() => false));\n const hasKts = yield* fs.exists(ktsPath).pipe(Effect.orElseSucceed(() => false));\n\n if (!hasGroovy && hasKts) {\n // Kotlin DSL — gradle-to-js cannot parse it\n return undefined;\n }\n\n if (!hasGroovy) {\n return undefined;\n }\n\n const content = yield* fs\n .readFileString(gradlePath)\n .pipe(Effect.catchAll(() => Effect.succeed(undefined)));\n if (!content) {\n return undefined;\n }\n\n return yield* Effect.tryPromise({\n try: async () => {\n const gradle =\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CJS require returns `any`; narrow to gradle-to-js declared shape\n require(\"gradle-to-js\") as {\n parseText: (text: string) => Promise<Record<string, unknown>>;\n };\n return gradle.parseText(stripGroovyComments(content));\n },\n catch: () => undefined,\n }).pipe(\n Effect.map(extractGradleConfig),\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n });\n\n/**\n * Log a warning if Gradle applicationId differs from app.json package name.\n */\nexport const warnOnGradleMismatch = (\n gradleConfig: GradleConfig | undefined,\n expectedPackage: string,\n): Effect.Effect<void> => {\n if (!gradleConfig?.applicationId) {\n return Effect.void;\n }\n if (gradleConfig.applicationId === expectedPackage) {\n return Effect.void;\n }\n return Console.warn(\n `Gradle applicationId \"${gradleConfig.applicationId}\" differs from app.json package \"${expectedPackage}\". ` +\n `The Gradle value will be used in the built APK/AAB.`,\n );\n};\n\n// ── helpers ──────────────────────────────────────────────────────\n\n/**\n * Strip Groovy single-line and block comments.\n * gradle-to-js chokes on comments — EAS CLI does this same pre-processing.\n */\nconst stripGroovyComments = (text: string): string =>\n text.replaceAll(/\\/\\/.*$/gmu, \"\").replaceAll(/\\/\\*[\\s\\S]*?\\*\\//gu, \"\");\n\nconst parseVersionCode = (raw: unknown): number | undefined => {\n if (typeof raw === \"number\") {\n return raw;\n }\n if (typeof raw === \"string\") {\n return Number.parseInt(raw, 10) || undefined;\n }\n return undefined;\n};\n\nconst extractGradleConfig = (parsed: Record<string, unknown>): GradleConfig => {\n const android = asRecord(parsed[\"android\"]);\n const defaultConfig = asRecord(android?.[\"defaultConfig\"]);\n\n const applicationId =\n typeof defaultConfig?.[\"applicationId\"] === \"string\"\n ? unquote(defaultConfig[\"applicationId\"])\n : undefined;\n const versionCode = parseVersionCode(defaultConfig?.[\"versionCode\"]);\n const versionName =\n typeof defaultConfig?.[\"versionName\"] === \"string\"\n ? unquote(defaultConfig[\"versionName\"])\n : undefined;\n\n return {\n ...(applicationId === undefined ? {} : { applicationId }),\n ...(versionCode === undefined ? {} : { versionCode }),\n ...(versionName === undefined ? {} : { versionName }),\n };\n};\n\nconst unquote = (input: string): string =>\n input.startsWith('\"') && input.endsWith('\"') ? input.slice(1, -1) : input;\n","import { isRecord } from \"@better-update/type-guards\";\nimport { Command } from \"@effect/platform\";\nimport { Data, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nexport class FingerprintError extends Data.TaggedError(\"FingerprintError\")<{\n readonly message: string;\n}> {}\n\nexport interface FingerprintSource {\n readonly type: string;\n readonly filePath?: string;\n readonly reasons: readonly string[];\n readonly hash: string | null;\n}\n\nexport interface FingerprintResult {\n readonly hash: string;\n readonly sources: readonly FingerprintSource[];\n}\n\nexport const runFingerprintFull = (\n projectRoot: string,\n): Effect.Effect<FingerprintResult, FingerprintError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const cmd = Command.make(\"bunx\", \"@expo/fingerprint\", projectRoot).pipe(\n Command.workingDirectory(projectRoot),\n );\n const stdout = yield* Command.string(cmd).pipe(\n Effect.mapError(\n (cause) =>\n new FingerprintError({\n message: `Failed to run \"@expo/fingerprint\": ${cause.message}`,\n }),\n ),\n );\n\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(stdout),\n catch: () =>\n new FingerprintError({\n message: \"Failed to parse @expo/fingerprint output as JSON.\",\n }),\n });\n\n if (!isRecord(parsed)) {\n return yield* new FingerprintError({\n message: \"@expo/fingerprint output was not a JSON object.\",\n });\n }\n\n const { hash } = parsed;\n if (typeof hash !== \"string\" || hash.length === 0) {\n return yield* new FingerprintError({\n message: '@expo/fingerprint output did not contain a \"hash\" string field.',\n });\n }\n\n const sourcesRaw = parsed[\"sources\"];\n const sources: readonly FingerprintSource[] = Array.isArray(sourcesRaw)\n ? (sourcesRaw as readonly FingerprintSource[])\n : [];\n\n return { hash, sources };\n });\n","import { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { RuntimeVersionError } from \"./exit-codes\";\nimport { runFingerprintFull } from \"./fingerprint\";\n\nimport type { RawRuntimeVersion } from \"./build-profile\";\n\nexport interface ResolveRuntimeVersionOptions {\n readonly raw: RawRuntimeVersion | undefined;\n readonly appVersion: string | undefined;\n readonly projectRoot: string;\n}\n\nexport const resolveRuntimeVersion = ({\n raw,\n appVersion,\n projectRoot,\n}: ResolveRuntimeVersionOptions): Effect.Effect<\n string,\n RuntimeVersionError,\n CommandExecutor.CommandExecutor\n> =>\n Effect.gen(function* () {\n if (typeof raw === \"string\") {\n return raw;\n }\n if (raw === undefined) {\n return yield* new RuntimeVersionError({\n message: \"No runtimeVersion configured in expo section of app.json.\",\n });\n }\n\n const { policy } = raw;\n if (policy === \"appVersion\") {\n if (appVersion === undefined) {\n return yield* new RuntimeVersionError({\n message: 'runtimeVersion policy is \"appVersion\" but expo.version is missing in app.json.',\n });\n }\n return appVersion;\n }\n\n if (policy === \"fingerprint\") {\n return yield* runFingerprintFull(projectRoot).pipe(\n Effect.map((result) => result.hash),\n Effect.mapError((cause) => new RuntimeVersionError({ message: cause.message })),\n );\n }\n\n if (policy === \"nativeVersion\") {\n return yield* new RuntimeVersionError({\n message:\n 'runtimeVersion policy \"nativeVersion\" is not supported. Set a static runtimeVersion string in your Expo config.',\n });\n }\n\n return yield* new RuntimeVersionError({\n message: `Unsupported runtimeVersion policy \"${policy}\". Use a static string, \"appVersion\", or \"fingerprint\".`,\n });\n });\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\n/**\n * Create a scoped temp directory prefixed with \"better-update-\" and `chmod 0o700`\n * it so only the current user can read its contents. The directory and all files\n * inside it are removed when the enclosing scope closes.\n */\nexport const acquireBuildTempDir = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const dir = yield* fs.makeTempDirectoryScoped({ prefix: \"better-update-\" });\n yield* fs.chmod(dir, 0o700);\n return dir;\n});\n","import { Console, Effect } from \"effect\";\n\nimport { runAndroidBuild } from \"../commands/build/android\";\nimport { runIosBuild } from \"../commands/build/ios\";\nimport { reserveAndUpload } from \"../commands/build/reserve-and-upload\";\nimport { readBuildProfile } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { BuildProfileError } from \"../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../lib/expo-config\";\nimport { readGitContext } from \"../lib/git-context\";\nimport { readGradleConfig, warnOnGradleMismatch } from \"../lib/gradle-config\";\nimport { printKeyValue } from \"../lib/output\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { acquireBuildTempDir } from \"../lib/temp-dir\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nimport type { BuildTarget } from \"../commands/build/reserve-and-upload\";\nimport type { Platform } from \"../lib/build-profile\";\n\nexport interface RunBuildWorkflowOptions {\n readonly platform: Platform;\n readonly profileName: string;\n readonly message: string | undefined;\n readonly noUpload: boolean;\n readonly rawOutput?: boolean;\n}\n\ntype AppMeta = Effect.Effect.Success<ReturnType<typeof readAppMeta>>;\ntype BuildProfile = Effect.Effect.Success<ReturnType<typeof readBuildProfile>>;\ntype ApiClient = Effect.Effect.Success<typeof apiClient>;\n\ninterface PlatformBuildInput {\n readonly api: ApiClient;\n readonly options: RunBuildWorkflowOptions;\n readonly profile: BuildProfile;\n readonly appMeta: AppMeta;\n readonly envVars: Record<string, string>;\n readonly projectId: string;\n readonly projectRoot: string;\n readonly tempDir: string;\n}\n\nconst runIosPlatformBuild = (input: PlatformBuildInput) =>\n Effect.gen(function* () {\n const { api, appMeta, envVars, options, profile, projectId, projectRoot, tempDir } = input;\n if (!profile.ios) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no ios section.`,\n });\n }\n const iosProfile = profile.ios;\n const iosBundleId = appMeta.bundleId;\n if (!iosBundleId) {\n return yield* new BuildProfileError({\n message: \"Missing ios.bundleIdentifier in your Expo config.\",\n });\n }\n const build = yield* runIosBuild({\n api,\n tempDir,\n projectRoot,\n iosProfile,\n bundleId: iosBundleId,\n envVars,\n projectId,\n rawOutput: options.rawOutput,\n });\n const target: BuildTarget = {\n platform: \"ios\",\n distribution: iosProfile.distribution,\n artifactFormat: \"ipa\",\n };\n return { build, target, bundleId: iosBundleId };\n });\n\nconst runAndroidPlatformBuild = (input: PlatformBuildInput) =>\n Effect.gen(function* () {\n const { api, appMeta, envVars, profile, projectId, projectRoot, tempDir } = input;\n if (!profile.android) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no android section.`,\n });\n }\n const androidProfile = profile.android;\n const androidBundleId = appMeta.androidPackage;\n if (!androidBundleId) {\n return yield* new BuildProfileError({\n message: \"Missing android.package in your Expo config.\",\n });\n }\n // Cross-validate Gradle config against the Expo config (Groovy only). When\n // Gradle resolves a different applicationId, the built APK/AAB is signed\n // Under that id — so the Credential resolver must key off the Gradle value.\n const androidDir = `${projectRoot}/android`;\n const gradleConfig = yield* readGradleConfig(androidDir);\n yield* warnOnGradleMismatch(gradleConfig, androidBundleId);\n const applicationIdentifier = gradleConfig?.applicationId ?? androidBundleId;\n const build = yield* runAndroidBuild({\n api,\n tempDir,\n projectRoot,\n androidProfile,\n applicationIdentifier,\n envVars,\n projectId,\n });\n const target: BuildTarget =\n androidProfile.format === \"aab\"\n ? { platform: \"android\", distribution: \"play-store\", artifactFormat: \"aab\" }\n : { platform: \"android\", distribution: \"direct\", artifactFormat: \"apk\" };\n return { build, target, bundleId: applicationIdentifier };\n });\n\nconst runPlatformBuild = (input: PlatformBuildInput) =>\n input.options.platform === \"ios\" ? runIosPlatformBuild(input) : runAndroidPlatformBuild(input);\n\nexport const runBuildWorkflow = (options: RunBuildWorkflowOptions) =>\n Effect.scoped(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n\n // Read config first without env vars to learn the profile's environment\n // (so we know which env scope to pull) + projectId. app.config.{js,ts}\n // that read process.env for these fields will see the caller's\n // environment only — server env vars are not available yet.\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n const baseProfile = yield* readBuildProfile(baseConfig, options.profileName);\n\n // Load env vars now that we know the profile's environment.\n const envVars = yield* pullEnvVars(api, {\n projectId,\n environment: baseProfile.environment,\n });\n\n // Re-resolve config with env-var overlay so dynamic configs see them.\n // envVars are applied as a scoped process.env overlay inside readExpoConfig\n // and restored after the call so secrets do not leak to child processes.\n // Re-read the profile from the env-resolved config so platform-specific\n // fields (format/distribution/buildConfiguration) that derive from env\n // vars resolve correctly downstream.\n const expoConfig = yield* readExpoConfig(projectRoot, envVars);\n const profile = yield* readBuildProfile(expoConfig, options.profileName);\n const appMeta = yield* readAppMeta(expoConfig, options.platform);\n\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: appMeta.rawRuntimeVersion,\n appVersion: appMeta.appVersion,\n projectRoot,\n });\n\n const tempDir = yield* acquireBuildTempDir;\n\n yield* Console.log(\n `Building ${options.platform} artifact for profile \"${profile.name}\" (runtimeVersion=${runtimeVersion})`,\n );\n\n const outcome = yield* runPlatformBuild({\n api,\n options,\n profile,\n appMeta,\n envVars,\n projectId,\n projectRoot,\n tempDir,\n });\n const { build, target, bundleId } = outcome;\n\n yield* Console.log(`Artifact produced: ${build.artifactPath}`);\n\n if (options.noUpload) {\n yield* printKeyValue([\n [\"Artifact\", build.artifactPath],\n [\"SHA-256\", build.sha256],\n [\"Bytes\", String(build.byteSize)],\n [\"Upload\", \"skipped (--no-upload)\"],\n ]);\n return;\n }\n\n const rawGitContext = yield* readGitContext(projectRoot);\n const gitContext: {\n readonly ref?: string;\n readonly commit?: string;\n readonly dirty: boolean;\n } = {\n ...(rawGitContext.ref === undefined ? {} : { ref: rawGitContext.ref }),\n ...(rawGitContext.commit === undefined ? {} : { commit: rawGitContext.commit }),\n dirty: rawGitContext.dirty,\n };\n\n const result = yield* reserveAndUpload(api, {\n target,\n projectId,\n profileName: profile.name,\n runtimeVersion,\n ...(appMeta.appVersion === undefined ? {} : { appVersion: appMeta.appVersion }),\n ...(appMeta.buildNumber === undefined ? {} : { buildNumber: appMeta.buildNumber }),\n bundleId,\n gitContext,\n ...(options.message === undefined ? {} : { message: options.message }),\n artifactPath: build.artifactPath,\n sha256: build.sha256,\n byteSize: build.byteSize,\n });\n\n yield* Console.log(\"\");\n yield* printKeyValue([\n [\"Build ID\", result.id],\n [\"Status\", result.status],\n [\"Platform\", options.platform],\n [\"Profile\", profile.name],\n [\"Runtime version\", runtimeVersion],\n [\"Artifact\", build.artifactPath],\n [\"SHA-256\", build.sha256],\n [\"Bytes\", String(build.byteSize)],\n ]);\n }),\n );\n","import { defineCommand } from \"citty\";\n\nimport { runBuildWorkflow } from \"../../application/build-workflow\";\nimport { runEffect } from \"../../lib/citty-effect\";\n\nconst BUILD_EXIT_EXTRAS = {\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n MissingCredentialsError: 5,\n BuildFailedError: 6,\n KeychainError: 6,\n ProvisioningError: 6,\n ArtifactNotFoundError: 6,\n ReserveError: 7,\n UploadFailedError: 7,\n PresignedUrlExpiredError: 7,\n CompleteError: 7,\n EnvExportError: 7,\n} as const;\n\nexport const buildCommand = defineCommand({\n meta: { name: \"build\", description: \"Build the app locally and optionally upload\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n profile: { type: \"string\", default: \"production\", description: \"Build profile name\" },\n message: { type: \"string\", description: \"Optional build message\" },\n upload: {\n type: \"boolean\",\n default: true,\n description: \"Upload the built artifact to better-update\",\n negativeDescription: \"Skip upload (use --no-upload)\",\n },\n \"raw-output\": { type: \"boolean\", description: \"Stream raw Gradle/Xcode output\" },\n },\n run: async ({ args }) =>\n runEffect(\n runBuildWorkflow({\n platform: args.platform,\n profileName: args.profile,\n message: args.message,\n noUpload: !args.upload,\n rawOutput: args[\"raw-output\"] ?? false,\n }),\n BUILD_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const compatibilityMatrixCommand = defineCommand({\n meta: {\n name: \"compatibility-matrix\",\n description: \"Show build-to-channel compatibility and missing runtime versions\",\n },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const result = yield* api.builds.compatibilityMatrix({ urlParams: { projectId } });\n\n const matrixKeys = Object.keys(result.channelStatusByKey);\n\n if (matrixKeys.length === 0 && result.missingRuntimeVersions.length === 0) {\n yield* Console.log(\"No compatibility data found.\");\n return;\n }\n\n const channelLookup: Record<string, string> = Object.fromEntries(\n result.channels.map((channel) => [channel.channelId, channel.channelName]),\n );\n\n if (matrixKeys.length > 0) {\n yield* Console.log(\"Channel Status by (Platform / Runtime Version):\");\n yield* printTable(\n [\"Platform / Runtime\", \"Channel\", \"Updates\"],\n matrixKeys.flatMap((key) =>\n (result.channelStatusByKey[key] ?? [])\n .filter((entry) => entry.updateCount > 0)\n .map((entry) => [\n key,\n channelLookup[entry.channelId] ?? entry.channelId,\n String(entry.updateCount),\n ]),\n ),\n );\n }\n\n if (result.missingRuntimeVersions.length > 0) {\n yield* Console.log(\"\\nMissing Runtime Versions:\");\n yield* printTable(\n [\"Channel\", \"Platform\", \"Runtime Version\", \"Updates\"],\n result.missingRuntimeVersions.map((missing) => [\n missing.channelName,\n missing.platform,\n missing.runtimeVersion,\n String(missing.updateCount),\n ]),\n );\n }\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a build\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.builds.delete({ path: { id: args.id } });\n yield* Console.log(`Build ${args.id} deleted.`);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const getCommand = defineCommand({\n meta: { name: \"get\", description: \"Show a build\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const build = yield* api.builds.get({ path: { id: args.id } });\n yield* printKeyValue([\n [\"ID\", build.id],\n [\"Platform\", build.platform],\n [\"Profile\", build.profile],\n [\"Distribution\", build.distribution],\n [\"Version\", build.appVersion ?? \"-\"],\n [\"Build Number\", build.buildNumber ?? \"-\"],\n [\"Runtime Version\", build.runtimeVersion ?? \"-\"],\n [\"Bundle ID\", build.bundleId ?? \"-\"],\n [\"Git Ref\", build.gitRef ?? \"-\"],\n [\"Message\", build.message ?? \"-\"],\n [\n \"Artifact\",\n build.artifact\n ? `${build.artifact.format} (${String(build.artifact.byteSize)} bytes)`\n : \"none\",\n ],\n [\"Created\", build.createdAt],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const installLinkCommand = defineCommand({\n meta: { name: \"install-link\", description: \"Get install/artifact URLs for a build\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.builds.getInstallLink({ path: { id: args.id } });\n yield* printKeyValue([\n [\"Artifact URL\", result.artifactUrl],\n [\"Install URL\", result.installUrl ?? \"-\"],\n [\"Expires\", String(result.expires)],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseLimit } from \"../../lib/cli-schemas\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List builds for the linked project\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], description: \"Filter by platform\" },\n limit: { type: \"string\", default: \"10\", description: \"Max rows (default 10)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const limit = yield* parseLimit(args.limit, 10);\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const platformFilter = args.platform ? { platform: args.platform } : {};\n\n const { items } = yield* api.builds.list({\n urlParams: { projectId, ...platformFilter, limit },\n });\n\n yield* printTable(\n [\"ID\", \"Platform\", \"Profile\", \"Distribution\", \"Version\", \"Created\"],\n items.map((build) => [\n build.id,\n build.platform,\n build.profile,\n build.distribution,\n build.appVersion ?? \"-\",\n build.createdAt,\n ]),\n );\n }),\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport { reserveAndUpload } from \"../commands/build/reserve-and-upload\";\nimport { readBuildProfile } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { ArtifactNotFoundError, BuildProfileError } from \"../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../lib/expo-config\";\nimport { readGitContext } from \"../lib/git-context\";\nimport { readGradleConfig, warnOnGradleMismatch } from \"../lib/gradle-config\";\nimport { printKeyValue } from \"../lib/output\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { sha256File } from \"../lib/sha256\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nimport type { BuildTarget } from \"../commands/build/reserve-and-upload\";\nimport type { Platform } from \"../lib/build-profile\";\n\nexport interface RunUploadWorkflowOptions {\n readonly platform: Platform;\n readonly profileName: string;\n readonly artifactPath: string;\n readonly message: string | undefined;\n}\n\ninterface ResolvedTarget {\n readonly target: BuildTarget;\n readonly bundleId: string;\n}\n\nconst resolveIosTarget = (\n profile: Effect.Effect.Success<ReturnType<typeof readBuildProfile>>,\n appMeta: Effect.Effect.Success<ReturnType<typeof readAppMeta>>,\n): Effect.Effect<ResolvedTarget, BuildProfileError> =>\n Effect.gen(function* () {\n if (!profile.ios) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no ios section.`,\n });\n }\n if (!appMeta.bundleId) {\n return yield* new BuildProfileError({\n message: \"Missing ios.bundleIdentifier in your Expo config.\",\n });\n }\n return {\n target: {\n platform: \"ios\",\n distribution: profile.ios.distribution,\n artifactFormat: \"ipa\",\n },\n bundleId: appMeta.bundleId,\n };\n });\n\nconst resolveAndroidTarget = (\n profile: Effect.Effect.Success<ReturnType<typeof readBuildProfile>>,\n appMeta: Effect.Effect.Success<ReturnType<typeof readAppMeta>>,\n projectRoot: string,\n) =>\n Effect.gen(function* () {\n if (!profile.android) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no android section.`,\n });\n }\n if (!appMeta.androidPackage) {\n return yield* new BuildProfileError({\n message: \"Missing android.package in your Expo config.\",\n });\n }\n const gradleConfig = yield* readGradleConfig(`${projectRoot}/android`);\n yield* warnOnGradleMismatch(gradleConfig, appMeta.androidPackage);\n const bundleId = gradleConfig?.applicationId ?? appMeta.androidPackage;\n const target: BuildTarget =\n profile.android.format === \"aab\"\n ? { platform: \"android\", distribution: \"play-store\", artifactFormat: \"aab\" }\n : { platform: \"android\", distribution: \"direct\", artifactFormat: \"apk\" };\n return { target, bundleId };\n });\n\nexport const runUploadWorkflow = (options: RunUploadWorkflowOptions) =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n\n const fs = yield* FileSystem.FileSystem;\n const artifactExists = yield* fs\n .exists(options.artifactPath)\n .pipe(Effect.orElseSucceed(() => false));\n if (!artifactExists) {\n yield* new ArtifactNotFoundError({\n message: `Artifact not found at ${options.artifactPath}.`,\n });\n }\n\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n const profile = yield* readBuildProfile(baseConfig, options.profileName);\n\n const envVars = yield* pullEnvVars(api, {\n projectId,\n environment: profile.environment,\n });\n\n const expoConfig = yield* readExpoConfig(projectRoot, envVars);\n const appMeta = yield* readAppMeta(expoConfig, options.platform);\n\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: appMeta.rawRuntimeVersion,\n appVersion: appMeta.appVersion,\n projectRoot,\n });\n\n const { target, bundleId } =\n options.platform === \"ios\"\n ? yield* resolveIosTarget(profile, appMeta)\n : yield* resolveAndroidTarget(profile, appMeta, projectRoot);\n\n yield* Console.log(`Hashing ${options.artifactPath}...`);\n const { sha256, byteSize } = yield* sha256File(options.artifactPath);\n\n const rawGitContext = yield* readGitContext(projectRoot);\n const gitContext: {\n readonly ref?: string;\n readonly commit?: string;\n readonly dirty: boolean;\n } = {\n ...(rawGitContext.ref === undefined ? {} : { ref: rawGitContext.ref }),\n ...(rawGitContext.commit === undefined ? {} : { commit: rawGitContext.commit }),\n dirty: rawGitContext.dirty,\n };\n\n const result = yield* reserveAndUpload(api, {\n target,\n projectId,\n profileName: profile.name,\n runtimeVersion,\n ...(appMeta.appVersion === undefined ? {} : { appVersion: appMeta.appVersion }),\n ...(appMeta.buildNumber === undefined ? {} : { buildNumber: appMeta.buildNumber }),\n bundleId,\n gitContext,\n ...(options.message === undefined ? {} : { message: options.message }),\n artifactPath: options.artifactPath,\n sha256,\n byteSize,\n });\n\n yield* Console.log(\"\");\n yield* printKeyValue([\n [\"Build ID\", result.id],\n [\"Status\", result.status],\n [\"Platform\", options.platform],\n [\"Profile\", profile.name],\n [\"Runtime version\", runtimeVersion],\n [\"Artifact\", options.artifactPath],\n [\"SHA-256\", sha256],\n [\"Bytes\", String(byteSize)],\n ]);\n });\n","import { defineCommand } from \"citty\";\n\nimport { runUploadWorkflow } from \"../../application/upload-workflow\";\nimport { runEffect } from \"../../lib/citty-effect\";\n\nconst UPLOAD_EXIT_EXTRAS = {\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n ArtifactNotFoundError: 6,\n BuildFailedError: 6,\n ReserveError: 7,\n UploadFailedError: 7,\n PresignedUrlExpiredError: 7,\n CompleteError: 7,\n EnvExportError: 7,\n} as const;\n\nexport const uploadCommand = defineCommand({\n meta: { name: \"upload\", description: \"Upload an existing artifact to better-update\" },\n args: {\n \"artifact-path\": { type: \"positional\", required: true, description: \"Path to artifact\" },\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n profile: { type: \"string\", default: \"production\", description: \"Build profile name\" },\n message: { type: \"string\", description: \"Optional build message\" },\n },\n run: async ({ args }) =>\n runEffect(\n runUploadWorkflow({\n artifactPath: args[\"artifact-path\"],\n platform: args.platform,\n profileName: args.profile,\n message: args.message,\n }),\n UPLOAD_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { compatibilityMatrixCommand } from \"./compatibility-matrix\";\nimport { deleteCommand } from \"./delete\";\nimport { getCommand } from \"./get\";\nimport { installLinkCommand } from \"./install-link\";\nimport { listCommand } from \"./list\";\nimport { uploadCommand } from \"./upload\";\n\nexport const buildsCommand = defineCommand({\n meta: { name: \"builds\", description: \"Manage builds\" },\n subCommands: {\n list: listCommand,\n get: getCommand,\n delete: deleteCommand,\n \"install-link\": installLinkCommand,\n \"compatibility-matrix\": compatibilityMatrixCommand,\n upload: uploadCommand,\n },\n});\n","import { Effect } from \"effect\";\n\ninterface NamedResource {\n readonly id: string;\n readonly name: string;\n}\n\nexport const resolveNamedResourceId = <Err>(\n params: {\n readonly items: readonly NamedResource[];\n readonly kind: string;\n readonly name: string;\n },\n makeError: (message: string) => Err,\n): Effect.Effect<string, Err> =>\n Effect.gen(function* () {\n const match = params.items.find((item) => item.name === params.name);\n if (match === undefined) {\n return yield* Effect.fail(\n makeError(`${params.kind} \"${params.name}\" not found in the linked project.`),\n );\n }\n return match.id;\n });\n","import { Data } from \"effect\";\n\nimport { resolveNamedResourceId as resolveNamedResourceIdBase } from \"../../lib/resolve-named-resource\";\n\nexport class ChannelCommandError extends Data.TaggedError(\"ChannelCommandError\")<{\n readonly message: string;\n}> {}\n\nexport const channelErrorExtras = { ChannelCommandError: 2 } as const;\n\nexport const resolveNamedResourceId = (params: {\n readonly items: readonly { readonly id: string; readonly name: string }[];\n readonly kind: string;\n readonly name: string;\n}) => resolveNamedResourceIdBase(params, (message) => new ChannelCommandError({ message }));\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras, resolveNamedResourceId } from \"./helpers\";\n\nexport const createCommand = defineCommand({\n meta: { name: \"create\", description: \"Create a channel\" },\n args: {\n name: { type: \"string\", required: true, description: \"Channel name\" },\n branch: { type: \"string\", required: true, description: \"Initial branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const branchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n });\n\n const channel = yield* api.channels.create({\n payload: { projectId, name: args.name, branchId },\n });\n\n yield* printKeyValue([\n [\"ID\", channel.id],\n [\"Name\", channel.name],\n [\"Branch\", args.branch],\n [\"Created\", channel.createdAt],\n ]);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a channel\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.channels.delete({ path: { id: args.id } });\n yield* Console.log(`Channel ${args.id} deleted.`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List channels for the linked project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const [items, branches] = yield* Effect.all([\n drainPages((page) =>\n api.channels.list({\n urlParams: { projectId, limit: 100, page },\n }),\n ),\n drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n ),\n ]);\n\n if (items.length === 0) {\n yield* Console.log(\"No channels found.\");\n return;\n }\n\n const branchNames = new Map(branches.map((branch) => [branch.id, branch.name]));\n\n yield* printTable(\n [\"ID\", \"Name\", \"Branch\", \"Paused\", \"Rollout\", \"Created\"],\n items.map((channel) => [\n channel.id,\n channel.name,\n branchNames.get(channel.branchId) ?? channel.branchId,\n channel.isPaused ? \"yes\" : \"no\",\n channel.branchMappingJson === null ? \"-\" : \"active\",\n channel.createdAt,\n ]),\n );\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const pauseCommand = defineCommand({\n meta: { name: \"pause\", description: \"Pause a channel\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.pause({ path: { id: args.id } });\n yield* Console.log(`Channel \"${channel.name}\" paused.`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const resumeCommand = defineCommand({\n meta: { name: \"resume\", description: \"Resume a paused channel\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.resume({ path: { id: args.id } });\n yield* Console.log(`Channel \"${channel.name}\" resumed.`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras } from \"../helpers\";\n\nexport const completeCommand = defineCommand({\n meta: { name: \"complete\", description: \"Complete the active branch rollout\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.completeBranchRollout({\n path: { id: args.channelId },\n });\n yield* Console.log(`Completed rollout on channel \"${channel.name}\".`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../../lib/cli-schemas\";\nimport { drainPages } from \"../../../lib/drain-cursor\";\nimport { readProjectId } from \"../../../lib/expo-config\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras, resolveNamedResourceId } from \"../helpers\";\n\nexport const createCommand = defineCommand({\n meta: { name: \"create\", description: \"Start a branch rollout on a channel\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n branch: { type: \"string\", required: true, description: \"Target branch name\" },\n percentage: {\n type: \"string\",\n required: true,\n description: \"Initial rollout percentage (1-100)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const percentage = yield* parseRolloutPercentage(args.percentage, \"percentage\");\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const newBranchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n });\n\n const channel = yield* api.channels.createBranchRollout({\n path: { id: args.channelId },\n payload: { newBranchId, percentage },\n });\n\n yield* Console.log(\n `Started rollout on channel \"${channel.name}\" to branch \"${args.branch}\" at ${String(percentage)}%.`,\n );\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras } from \"../helpers\";\n\nexport const revertCommand = defineCommand({\n meta: { name: \"revert\", description: \"Revert the active branch rollout\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.revertBranchRollout({\n path: { id: args.channelId },\n });\n yield* Console.log(`Reverted rollout on channel \"${channel.name}\".`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../../lib/cli-schemas\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras } from \"../helpers\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Update the rollout percentage on a channel\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n percentage: { type: \"string\", required: true, description: \"New rollout percentage (1-100)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const percentage = yield* parseRolloutPercentage(args.percentage, \"percentage\");\n const api = yield* apiClient;\n const channel = yield* api.channels.updateBranchRollout({\n path: { id: args.channelId },\n payload: { percentage },\n });\n\n yield* Console.log(\n `Updated rollout on channel \"${channel.name}\" to ${String(percentage)}%.`,\n );\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { completeCommand } from \"./complete\";\nimport { createCommand } from \"./create\";\nimport { revertCommand } from \"./revert\";\nimport { updateCommand } from \"./update\";\n\nexport const rolloutCommand = defineCommand({\n meta: { name: \"rollout\", description: \"Manage channel branch rollouts\" },\n subCommands: {\n create: createCommand,\n update: updateCommand,\n complete: completeCommand,\n revert: revertCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras, resolveNamedResourceId } from \"./helpers\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Relink a channel to a different branch\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n branch: { type: \"string\", required: true, description: \"Target branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const branchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n });\n\n const channel = yield* api.channels.update({\n path: { id: args.id },\n payload: { branchId },\n });\n\n yield* Console.log(`Channel \"${channel.name}\" relinked to branch \"${args.branch}\".`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { pauseCommand } from \"./pause\";\nimport { resumeCommand } from \"./resume\";\nimport { rolloutCommand } from \"./rollout\";\nimport { updateCommand } from \"./update\";\n\nexport const channelsCommand = defineCommand({\n meta: { name: \"channels\", description: \"Manage channels\" },\n subCommands: {\n list: listCommand,\n create: createCommand,\n update: updateCommand,\n pause: pauseCommand,\n resume: resumeCommand,\n delete: deleteCommand,\n rollout: rolloutCommand,\n },\n});\n","/* eslint-disable typescript/no-unsafe-assignment, typescript/no-unsafe-member-access, typescript/no-unsafe-call -- @expo/pkcs12 exports declare node-forge cert shapes as `any`; this file is the narrowing boundary that produces the typed P12Info for the rest of the CLI */\n\nimport { getFormattedSerialNumber, getX509Certificate, parsePKCS12 } from \"@expo/pkcs12\";\nimport { Effect } from \"effect\";\n\nimport { CredentialValidationError } from \"./exit-codes\";\n\nexport interface P12Info {\n readonly serialNumber: string;\n readonly validFrom: Date | undefined;\n readonly expiresAt: Date | undefined;\n readonly subject: string;\n readonly issuerCN: string | undefined;\n readonly signingIdentity: string;\n readonly teamId: string | undefined;\n}\n\nconst APPLE_TEAM_ID_RE = /^[A-Z0-9]{10}$/u;\n\nconst extractTeamId = (params: {\n readonly signingIdentity: string;\n readonly orgUnit: string | undefined;\n}): string | undefined => {\n if (params.orgUnit && APPLE_TEAM_ID_RE.test(params.orgUnit)) {\n return params.orgUnit;\n }\n const parenMatch = /\\(([A-Z0-9]{10})\\)\\s*$/u.exec(params.signingIdentity);\n return parenMatch?.[1];\n};\n\n/**\n * Parse a PKCS#12 (.p12) buffer and extract certificate metadata.\n */\nexport const inspectP12 = (params: {\n readonly data: Buffer;\n readonly password: string;\n}): Effect.Effect<P12Info, CredentialValidationError> =>\n Effect.try({\n try: () => {\n const p12 = parsePKCS12(params.data, params.password);\n const cert = getX509Certificate(p12);\n\n const serialNumber = getFormattedSerialNumber(cert) ?? \"unknown\";\n\n const validFrom =\n cert.validity.notBefore instanceof Date ? cert.validity.notBefore : undefined;\n const expiresAt = cert.validity.notAfter instanceof Date ? cert.validity.notAfter : undefined;\n\n const subjectParts = cert.subject.attributes.map(\n (attr: { shortName?: string; name: string; value: unknown }) =>\n `${attr.shortName ?? attr.name}=${String(attr.value)}`,\n );\n const subject = subjectParts.join(\", \");\n\n const issuerCNValue = cert.issuer.getField(\"CN\")?.value;\n const issuerCN = typeof issuerCNValue === \"string\" ? issuerCNValue : undefined;\n\n // Signing identity = Common Name from subject, e.g. \"Apple Distribution: Name (TEAMID)\"\n const cnValue = cert.subject.getField(\"CN\")?.value;\n const cn = typeof cnValue === \"string\" ? cnValue : undefined;\n const signingIdentity = cn ?? subject;\n const orgUnitValue = cert.subject.getField(\"OU\")?.value;\n const orgUnit = typeof orgUnitValue === \"string\" ? orgUnitValue : undefined;\n\n const teamId = extractTeamId({ signingIdentity, orgUnit });\n\n return { serialNumber, validFrom, expiresAt, subject, issuerCN, signingIdentity, teamId };\n },\n catch: (error) =>\n new CredentialValidationError({\n message: `Failed to parse P12 certificate: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n","import { toBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Match } from \"effect\";\n\nimport { CredentialValidationError } from \"./exit-codes\";\nimport { inspectP12 } from \"./pkcs12\";\n\nimport type { ApiClient } from \"../services/api-client\";\n\nexport type CliCredentialType =\n | \"distribution-certificate\"\n | \"push-key\"\n | \"asc-api-key\"\n | \"provisioning-profile\"\n | \"keystore\"\n | \"google-service-account-key\";\n\nexport type CliCredentialPlatform = \"ios\" | \"android\";\n\nexport interface CliCredentialRow {\n readonly id: string;\n readonly name: string;\n readonly platform: CliCredentialPlatform;\n readonly type: CliCredentialType;\n readonly distribution: string | null;\n}\n\nconst formatDistribution = (value: string): string => value.toLowerCase().replaceAll(\"_\", \"-\");\n\nexport const listAllCredentials = (api: ApiClient) =>\n Effect.gen(function* () {\n const [certs, pushKeys, ascKeys, profiles, keystores, googleKeys] = yield* Effect.all(\n [\n api.appleDistributionCertificates.list(),\n api.applePushKeys.list(),\n api.ascApiKeys.list(),\n api.appleProvisioningProfiles.list({ urlParams: {} }),\n api.androidUploadKeystores.list(),\n api.googleServiceAccountKeys.list(),\n ],\n { concurrency: \"unbounded\" },\n );\n\n const rows: CliCredentialRow[] = [\n ...certs.items.map(\n (cert): CliCredentialRow => ({\n id: cert.id,\n name: cert.serialNumber,\n platform: \"ios\",\n type: \"distribution-certificate\",\n distribution: null,\n }),\n ),\n ...pushKeys.items.map(\n (key): CliCredentialRow => ({\n id: key.id,\n name: key.keyId,\n platform: \"ios\",\n type: \"push-key\",\n distribution: null,\n }),\n ),\n ...ascKeys.items.map(\n (key): CliCredentialRow => ({\n id: key.id,\n name: key.name,\n platform: \"ios\",\n type: \"asc-api-key\",\n distribution: null,\n }),\n ),\n ...profiles.items.map(\n (profile): CliCredentialRow => ({\n id: profile.id,\n name: profile.profileName ?? profile.bundleIdentifier,\n platform: \"ios\",\n type: \"provisioning-profile\",\n distribution: formatDistribution(profile.distributionType),\n }),\n ),\n ...keystores.items.map(\n (ks): CliCredentialRow => ({\n id: ks.id,\n name: ks.keyAlias,\n platform: \"android\",\n type: \"keystore\",\n distribution: null,\n }),\n ),\n ...googleKeys.items.map(\n (key): CliCredentialRow => ({\n id: key.id,\n name: key.clientEmail,\n platform: \"android\",\n type: \"google-service-account-key\",\n distribution: null,\n }),\n ),\n ];\n\n return rows;\n });\n\nexport const filterCredentials = (\n rows: readonly CliCredentialRow[],\n filter: {\n readonly platform?: CliCredentialPlatform;\n readonly type?: CliCredentialType;\n readonly distribution?: string;\n },\n): CliCredentialRow[] =>\n rows.filter((row) => {\n if (filter.platform && row.platform !== filter.platform) {\n return false;\n }\n if (filter.type && row.type !== filter.type) {\n return false;\n }\n if (filter.distribution && row.distribution !== filter.distribution) {\n return false;\n }\n return true;\n });\n\nexport interface UploadCredentialInput {\n readonly platform: CliCredentialPlatform;\n readonly type: CliCredentialType;\n readonly name: string;\n readonly filePath: string;\n readonly password?: string;\n readonly distribution?: string;\n readonly keyAlias?: string;\n readonly keyPassword?: string;\n readonly keyId?: string;\n readonly issuerId?: string;\n readonly appleTeamIdentifier?: string;\n}\n\nconst toUtf8 = (bytes: Uint8Array): string => new TextDecoder().decode(bytes);\n\nconst missing = (label: string) =>\n new CredentialValidationError({\n message: `Missing --${label} required for the selected credential type.`,\n });\n\nconst uploadIosDistributionCertificate = (\n api: ApiClient,\n input: UploadCredentialInput,\n bytes: Uint8Array,\n) =>\n Effect.gen(function* () {\n if (input.password === undefined) {\n return yield* missing(\"password\");\n }\n const info = yield* inspectP12({ data: Buffer.from(bytes), password: input.password });\n if (!info.teamId) {\n return yield* new CredentialValidationError({\n message:\n \"Could not derive Apple Team ID from certificate subject (expected OU=TEAMID or CN with (TEAMID)).\",\n });\n }\n if (!info.validFrom || !info.expiresAt) {\n return yield* new CredentialValidationError({\n message: \"Certificate is missing notBefore/notAfter dates.\",\n });\n }\n const created = yield* api.appleDistributionCertificates.upload({\n payload: {\n p12Base64: toBase64(bytes),\n p12Password: input.password,\n serialNumber: info.serialNumber,\n appleTeamIdentifier: info.teamId,\n validFrom: info.validFrom.toISOString(),\n validUntil: info.expiresAt.toISOString(),\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"distribution-certificate\" as const,\n };\n });\n\nconst uploadIosPushKey = (api: ApiClient, input: UploadCredentialInput, bytes: Uint8Array) =>\n Effect.gen(function* () {\n if (!input.keyId) {\n return yield* missing(\"key-id\");\n }\n if (!input.appleTeamIdentifier) {\n return yield* missing(\"apple-team-identifier\");\n }\n const created = yield* api.applePushKeys.upload({\n payload: {\n keyId: input.keyId,\n p8Pem: toUtf8(bytes),\n appleTeamIdentifier: input.appleTeamIdentifier,\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"push-key\" as const,\n };\n });\n\nconst uploadIosAscApiKey = (api: ApiClient, input: UploadCredentialInput, bytes: Uint8Array) =>\n Effect.gen(function* () {\n if (!input.keyId) {\n return yield* missing(\"key-id\");\n }\n if (!input.issuerId) {\n return yield* missing(\"issuer-id\");\n }\n const created = yield* api.ascApiKeys.upload({\n payload: {\n name: input.name,\n keyId: input.keyId,\n issuerId: input.issuerId,\n p8Pem: toUtf8(bytes),\n ...(input.appleTeamIdentifier === undefined\n ? {}\n : { appleTeamIdentifier: input.appleTeamIdentifier }),\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"asc-api-key\" as const,\n };\n });\n\nconst uploadIosProvisioningProfile = (\n api: ApiClient,\n input: UploadCredentialInput,\n bytes: Uint8Array,\n) =>\n Effect.gen(function* () {\n const created = yield* api.appleProvisioningProfiles.upload({\n payload: { profileBase64: toBase64(bytes) },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"provisioning-profile\" as const,\n };\n });\n\nconst uploadAndroidKeystore = (api: ApiClient, input: UploadCredentialInput, bytes: Uint8Array) =>\n Effect.gen(function* () {\n if (input.password === undefined) {\n return yield* missing(\"password\");\n }\n if (!input.keyAlias) {\n return yield* missing(\"key-alias\");\n }\n if (!input.keyPassword) {\n return yield* missing(\"key-password\");\n }\n const created = yield* api.androidUploadKeystores.upload({\n payload: {\n keystoreBase64: toBase64(bytes),\n keyAlias: input.keyAlias,\n keystorePassword: input.password,\n keyPassword: input.keyPassword,\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"android\" as const,\n type: \"keystore\" as const,\n };\n });\n\nconst uploadAndroidGoogleServiceAccountKey = (\n api: ApiClient,\n input: UploadCredentialInput,\n bytes: Uint8Array,\n) =>\n Effect.gen(function* () {\n const created = yield* api.googleServiceAccountKeys.upload({\n payload: { json: toUtf8(bytes) },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"android\" as const,\n type: \"google-service-account-key\" as const,\n };\n });\n\nconst uploadHandlers = {\n \"ios:distribution-certificate\": uploadIosDistributionCertificate,\n \"ios:push-key\": uploadIosPushKey,\n \"ios:asc-api-key\": uploadIosAscApiKey,\n \"ios:provisioning-profile\": uploadIosProvisioningProfile,\n \"android:keystore\": uploadAndroidKeystore,\n \"android:google-service-account-key\": uploadAndroidGoogleServiceAccountKey,\n};\n\nexport const uploadCredential = (api: ApiClient, input: UploadCredentialInput) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const bytes = yield* fs.readFile(input.filePath);\n const key = `${input.platform}:${input.type}`;\n type HandlerKey = keyof typeof uploadHandlers;\n const hasKey = (candidate: string): candidate is HandlerKey =>\n Object.hasOwn(uploadHandlers, candidate);\n const handler = hasKey(key) ? uploadHandlers[key] : undefined;\n if (!handler) {\n return yield* new CredentialValidationError({\n message: `Unsupported credential combination: platform=${input.platform} type=${input.type}`,\n });\n }\n return yield* handler(api, input, bytes);\n });\n\nexport const deleteCredential = (\n api: ApiClient,\n input: {\n readonly id: string;\n readonly platform: CliCredentialPlatform;\n readonly type: CliCredentialType;\n },\n) => {\n const path = { id: input.id };\n return Match.value({ platform: input.platform, type: input.type }).pipe(\n Match.when({ platform: \"ios\", type: \"distribution-certificate\" }, () =>\n api.appleDistributionCertificates.delete({ path }),\n ),\n Match.when({ platform: \"ios\", type: \"push-key\" }, () => api.applePushKeys.delete({ path })),\n Match.when({ platform: \"ios\", type: \"asc-api-key\" }, () => api.ascApiKeys.delete({ path })),\n Match.when({ platform: \"ios\", type: \"provisioning-profile\" }, () =>\n api.appleProvisioningProfiles.delete({ path }),\n ),\n Match.when({ platform: \"android\", type: \"keystore\" }, () =>\n api.androidUploadKeystores.delete({ path }),\n ),\n Match.when({ platform: \"android\", type: \"google-service-account-key\" }, () =>\n api.googleServiceAccountKeys.delete({ path }),\n ),\n Match.orElse(() =>\n Effect.fail(\n new CredentialValidationError({\n message: `Unsupported credential combination: platform=${input.platform} type=${input.type}`,\n }),\n ),\n ),\n );\n};\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { deleteCredential } from \"../../lib/credentials-manager\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { CliCredentialType } from \"../../lib/credentials-manager\";\n\nconst CREDENTIAL_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a credential\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Credential ID\" },\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n type: { type: \"enum\", options: [...CREDENTIAL_TYPES], required: true },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* deleteCredential(api, {\n id: args.id,\n platform: args.platform,\n type: args.type as CliCredentialType,\n });\n yield* Console.log(`Credential ${args.id} deleted.`);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { filterCredentials, listAllCredentials } from \"../../lib/credentials-manager\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List credentials across platforms\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], description: \"Filter by platform\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const rows = yield* listAllCredentials(api);\n\n const filtered = filterCredentials(rows, args.platform ? { platform: args.platform } : {});\n\n if (filtered.length === 0) {\n yield* Console.log(\"No credentials found.\");\n return;\n }\n\n yield* printTable(\n [\"ID\", \"Name\", \"Platform\", \"Type\", \"Distribution\"],\n filtered.map((row) => [\n row.id,\n row.name,\n row.platform,\n row.type,\n row.distribution ?? \"-\",\n ]),\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { uploadCredential } from \"../../lib/credentials-manager\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { CliCredentialType } from \"../../lib/credentials-manager\";\n\nconst CREDENTIAL_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\nexport const uploadCommand = defineCommand({\n meta: { name: \"upload\", description: \"Upload a credential\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n type: { type: \"enum\", options: [...CREDENTIAL_TYPES], required: true },\n name: { type: \"string\", required: true, description: \"Display name\" },\n file: { type: \"string\", required: true, description: \"Path to credential file\" },\n password: { type: \"string\", description: \"File password (keystore/p12)\" },\n \"key-alias\": { type: \"string\", description: \"Keystore alias\" },\n \"key-password\": { type: \"string\", description: \"Keystore key password\" },\n \"key-id\": { type: \"string\", description: \"ASC API key ID\" },\n \"issuer-id\": { type: \"string\", description: \"ASC API issuer ID\" },\n \"apple-team-identifier\": { type: \"string\", description: \"Apple Team ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n\n const input: {\n readonly platform: \"ios\" | \"android\";\n readonly type: CliCredentialType;\n readonly name: string;\n readonly filePath: string;\n readonly password?: string;\n readonly keyAlias?: string;\n readonly keyPassword?: string;\n readonly keyId?: string;\n readonly issuerId?: string;\n readonly appleTeamIdentifier?: string;\n } = {\n platform: args.platform,\n type: args.type as CliCredentialType,\n name: args.name,\n filePath: args.file,\n ...(args.password === undefined ? {} : { password: args.password }),\n ...(args[\"key-alias\"] === undefined ? {} : { keyAlias: args[\"key-alias\"] }),\n ...(args[\"key-password\"] === undefined ? {} : { keyPassword: args[\"key-password\"] }),\n ...(args[\"key-id\"] === undefined ? {} : { keyId: args[\"key-id\"] }),\n ...(args[\"issuer-id\"] === undefined ? {} : { issuerId: args[\"issuer-id\"] }),\n ...(args[\"apple-team-identifier\"] === undefined\n ? {}\n : { appleTeamIdentifier: args[\"apple-team-identifier\"] }),\n };\n\n const credential = yield* uploadCredential(api, input);\n\n yield* Console.log(\"Credential uploaded successfully.\");\n yield* Console.log(\"\");\n yield* printKeyValue([\n [\"ID\", credential.id],\n [\"Name\", credential.name],\n [\"Platform\", credential.platform],\n [\"Type\", credential.type],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { uploadCommand } from \"./upload\";\n\nexport const credentialsCommand = defineCommand({\n meta: { name: \"credentials\", description: \"Manage credentials\" },\n subCommands: {\n list: listCommand,\n upload: uploadCommand,\n delete: deleteCommand,\n },\n});\n","import { Data } from \"effect\";\n\nexport class EnvResourceNotFoundError extends Data.TaggedError(\"EnvResourceNotFoundError\")<{\n readonly message: string;\n}> {}\n\nexport const envErrorExtras = {\n EnvResourceNotFoundError: 1,\n SystemError: 6,\n BadArgument: 6,\n} as const;\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { EnvResourceNotFoundError, envErrorExtras } from \"./helpers\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete an environment variable by key\" },\n args: {\n key: { type: \"positional\", required: true, description: \"Env var key\" },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const existing = yield* api[\"env-vars\"].list({\n urlParams: { projectId, environment: args.environment },\n });\n\n const match = existing.items.find((item) => item.key === args.key);\n\n if (!match) {\n return yield* new EnvResourceNotFoundError({\n message: `Environment variable ${args.key} not found in ${args.environment}`,\n });\n }\n\n yield* api[\"env-vars\"].delete({ path: { id: match.id } });\n yield* Console.log(`Deleted ${args.key} from ${args.environment}`);\n return undefined;\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const exportCommand = defineCommand({\n meta: { name: \"export\", description: \"Print env vars in KEY='value' format\" },\n args: {\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const result = yield* api[\"env-vars\"].export({\n urlParams: { projectId, environment: args.environment },\n });\n\n for (const item of result.items) {\n const escaped = item.value.replaceAll(\"'\", String.raw`'\\''`);\n yield* Console.log(`${item.key}='${escaped}'`);\n }\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const getCommand = defineCommand({\n meta: { name: \"get\", description: \"Show an environment variable\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Env var ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const envVar = yield* api[\"env-vars\"].get({ path: { id: args.id } });\n yield* printKeyValue([\n [\"ID\", envVar.id],\n [\"Key\", envVar.key],\n [\"Environment\", envVar.environment],\n [\"Visibility\", envVar.visibility],\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- EnvVar.value nullable at storage; display empty when absent\n [\"Value\", envVar.visibility === \"plaintext\" ? (envVar.value ?? \"\") : \"******\"],\n [\"Created\", envVar.createdAt],\n [\"Updated\", envVar.updatedAt],\n ]);\n }),\n envErrorExtras,\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const importCommand = defineCommand({\n meta: { name: \"import\", description: \"Bulk-import env vars from a dotenv file\" },\n args: {\n file: { type: \"positional\", required: true, description: \"Path to .env file\" },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const content = yield* fs.readFileString(args.file);\n\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const result = yield* api[\"env-vars\"].bulkImport({\n payload: { projectId, environment: args.environment, content, visibility: \"plaintext\" },\n });\n\n yield* Console.log(\n `Imported: ${String(result.created)} created, ${String(result.updated)} updated, ${String(result.skipped)} skipped`,\n );\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List environment variables\" },\n args: {\n environment: { type: \"string\", description: \"Filter by environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const envFilter = args.environment ? { environment: args.environment } : {};\n\n const result = yield* api[\"env-vars\"].list({\n urlParams: { projectId, ...envFilter },\n });\n\n if (result.items.length === 0) {\n yield* Console.log(\"No environment variables found.\");\n return;\n }\n\n yield* printTable(\n [\"Key\", \"Environment\", \"Visibility\", \"Value\"],\n result.items.map((item) => [\n item.key,\n item.environment,\n item.visibility,\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- EnvVar.value nullable at storage; display empty when absent\n item.visibility === \"plaintext\" ? (item.value ?? \"\") : \"••••••\",\n ]),\n );\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const pullCommand = defineCommand({\n meta: { name: \"pull\", description: \"Print env vars in `export KEY='value'` format\" },\n args: {\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const result = yield* api[\"env-vars\"].export({\n urlParams: { projectId, environment: args.environment },\n });\n\n for (const item of result.items) {\n const escaped = item.value.replaceAll(\"'\", String.raw`'\\''`);\n yield* Console.log(`export ${item.key}='${escaped}'`);\n }\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseKeyValue } from \"../../lib/cli-schemas\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const setCommand = defineCommand({\n meta: { name: \"set\", description: \"Create or update an environment variable\" },\n args: {\n keyValue: {\n type: \"positional\",\n required: true,\n description: \"KEY=VALUE pair (e.g. API_KEY=abc123)\",\n },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n visibility: {\n type: \"enum\",\n options: [\"plaintext\", \"sensitive\", \"secret\"],\n default: \"plaintext\",\n description: \"Value visibility\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const { key, value } = yield* parseKeyValue(args.keyValue);\n const { environment } = args;\n const { visibility } = args;\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const existing = yield* api[\"env-vars\"].list({\n urlParams: { projectId, environment },\n });\n\n const match = existing.items.find((item) => item.key === key);\n\n if (match) {\n yield* api[\"env-vars\"].update({\n path: { id: match.id },\n payload: { value, visibility },\n });\n yield* Console.log(`Updated ${key} in ${environment}`);\n } else {\n yield* api[\"env-vars\"].create({\n payload: { projectId, environment, key, value, visibility },\n });\n yield* Console.log(`Created ${key} in ${environment}`);\n }\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { deleteCommand } from \"./delete\";\nimport { exportCommand } from \"./export\";\nimport { getCommand } from \"./get\";\nimport { importCommand } from \"./import\";\nimport { listCommand } from \"./list\";\nimport { pullCommand } from \"./pull\";\nimport { setCommand } from \"./set\";\n\nexport const envCommand = defineCommand({\n meta: { name: \"env\", description: \"Manage environment variables\" },\n subCommands: {\n list: listCommand,\n get: getCommand,\n set: setCommand,\n delete: deleteCommand,\n import: importCommand,\n export: exportCommand,\n pull: pullCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { exitWith } from \"../../application/command-exit\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { runFingerprintFull } from \"../../lib/fingerprint\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nexport const compareCommand = defineCommand({\n meta: { name: \"compare\", description: \"Compare a fingerprint hash against the current project\" },\n args: {\n hash: { type: \"positional\", required: true, description: \"Fingerprint hash to compare\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const result = yield* runFingerprintFull(projectRoot);\n\n if (result.hash === args.hash) {\n yield* Console.log(\"Fingerprints match.\");\n return undefined;\n }\n yield* Console.log(\"Fingerprints differ.\");\n yield* Console.log(` Local: ${result.hash}`);\n yield* Console.log(` Provided: ${args.hash}`);\n return yield* exitWith(1, \"Fingerprint mismatch\");\n }),\n { FingerprintError: 2 },\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { runFingerprintFull } from \"../../lib/fingerprint\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nexport const generateCommand = defineCommand({\n meta: { name: \"generate\", description: \"Compute a fingerprint for the current project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const result = yield* runFingerprintFull(projectRoot);\n yield* Console.log(result.hash);\n if (result.sources.length > 0) {\n yield* Console.log(`${result.sources.length} sources`);\n }\n }),\n { FingerprintError: 2 },\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { compareCommand } from \"./compare\";\nimport { generateCommand } from \"./generate\";\n\nexport const fingerprintCommand = defineCommand({\n meta: { name: \"fingerprint\", description: \"Fingerprint utilities\" },\n subCommands: {\n generate: generateCommand,\n compare: compareCommand,\n },\n});\n","import path from \"node:path\";\n\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { extractSlug, readExpoConfig, writeProjectId } from \"../lib/expo-config\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nexport const initCommand = defineCommand({\n meta: { name: \"init\", description: \"Link the local Expo project to a better-update project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const config = yield* readExpoConfig(projectRoot);\n const name = config.name ?? config.slug ?? \"untitled\";\n const slug = yield* extractSlug(config);\n\n yield* Console.log(`Linking project: ${name} (${slug})`);\n\n const api = yield* apiClient;\n const { items } = yield* api.projects.list({ urlParams: { page: 1, limit: 100 } });\n\n const existing = items.find((project) => project.slug === slug);\n const resolveLinkedProjectId = Effect.gen(function* () {\n if (existing) {\n yield* Console.log(`Found existing project: ${existing.name} (${existing.id})`);\n return existing.id;\n }\n yield* Console.log(\"No existing project found. Creating new project...\");\n const created = yield* api.projects.create({ payload: { name, slug } });\n yield* Console.log(`Created project: ${created.name} (${created.id})`);\n return created.id;\n });\n const linkedProjectId = yield* resolveLinkedProjectId;\n\n const writeResult = yield* writeProjectId(projectRoot, linkedProjectId);\n const target = writeResult.configPath\n ? path.relative(projectRoot, writeResult.configPath)\n : \"your Expo config\";\n yield* Console.log(`Project linked successfully. ID saved to ${target}.`);\n if (writeResult.type === \"warn\" && writeResult.message) {\n yield* Console.log(`Note: ${writeResult.message}`);\n }\n }),\n ),\n});\n","import { once } from \"node:events\";\nimport { createServer } from \"node:http\";\nimport type { IncomingMessage, Server, ServerResponse } from \"node:http\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { Data, Deferred, Duration, Effect } from \"effect\";\n\nexport class BrowserLoginTimeoutError extends Data.TaggedError(\"BrowserLoginTimeoutError\")<{\n readonly message: string;\n}> {}\n\nexport class BrowserLoginSessionClosedError extends Data.TaggedError(\n \"BrowserLoginSessionClosedError\",\n)<{\n readonly message: string;\n}> {}\n\nexport type BrowserLoginError = BrowserLoginSessionClosedError | BrowserLoginTimeoutError;\n\nexport const CALLBACK_PAGE = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>better-update CLI Login</title>\n <style>\n :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }\n body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; }\n main { max-width: 32rem; line-height: 1.5; }\n code { font-family: ui-monospace, SFMono-Regular, monospace; }\n </style>\n </head>\n <body>\n <main>\n <h1>Completing CLI login...</h1>\n <p id=\"message\">Finalizing the local session. You can keep this tab open.</p>\n </main>\n <script>\n const message = document.getElementById(\"message\");\n const render = (text) => {\n if (message) message.textContent = text;\n };\n\n const params = new URLSearchParams(window.location.hash.slice(1));\n const token = params.get(\"token\");\n\n if (!token) {\n render(\"Missing token. Return to the CLI and run login again.\");\n } else {\n fetch(\"/callback/token\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ token }),\n })\n .then(async (response) => {\n if (!response.ok) {\n const body = await response.text();\n throw new Error(body || \"Callback failed\");\n }\n window.history.replaceState({}, document.title, window.location.pathname);\n render(\"CLI login complete. You can close this tab.\");\n setTimeout(() => window.close(), 300);\n })\n .catch((error) => {\n render(error instanceof Error ? error.message : \"Callback failed.\");\n });\n }\n </script>\n </body>\n</html>`;\n\nexport interface BrowserLoginServer {\n readonly callbackUrl: string;\n readonly waitForToken: Effect.Effect<string, BrowserLoginError>;\n readonly stop: () => void;\n}\n\nexport interface BrowserLoginSession {\n readonly callbackPath: string;\n readonly waitForToken: Effect.Effect<string, BrowserLoginError>;\n readonly handleRequest: (request: Request) => Promise<Response>;\n readonly dispose: () => void;\n}\n\nexport interface CreateBrowserLoginServerOptions {\n readonly timeoutMs?: number;\n}\n\nexport const createBrowserLoginSession = (\n options: CreateBrowserLoginServerOptions = {},\n): BrowserLoginSession => {\n const tokenDeferred = Effect.runSync(Deferred.make<string, BrowserLoginSessionClosedError>());\n const waitForToken = Deferred.await(tokenDeferred).pipe(\n Effect.timeoutFail({\n duration:\n options.timeoutMs === undefined ? Duration.minutes(5) : Duration.millis(options.timeoutMs),\n onTimeout: () =>\n new BrowserLoginTimeoutError({\n message: \"Timed out waiting for browser login to complete.\",\n }),\n }),\n );\n\n const dispose = () => {\n Effect.runSync(\n Deferred.fail(\n tokenDeferred,\n new BrowserLoginSessionClosedError({\n message: \"Browser login session closed.\",\n }),\n ),\n );\n };\n\n return {\n callbackPath: \"/callback\",\n waitForToken,\n handleRequest: async (request) => {\n const url = new URL(request.url);\n\n if (request.method === \"GET\" && url.pathname === \"/callback\") {\n return new Response(CALLBACK_PAGE, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n }\n\n if (request.method === \"POST\" && url.pathname === \"/callback/token\") {\n try {\n const body: unknown = await request.json();\n if (!isRecord(body)) {\n return new Response(\"Invalid callback payload\", { status: 400 });\n }\n const token = typeof body[\"token\"] === \"string\" ? body[\"token\"].trim() : \"\";\n if (token.length === 0) {\n return new Response(\"Missing token\", { status: 400 });\n }\n\n Effect.runSync(Deferred.succeed(tokenDeferred, token));\n return Response.json({ ok: true });\n } catch {\n return new Response(\"Invalid callback payload\", { status: 400 });\n }\n }\n\n return new Response(\"Not found\", { status: 404 });\n },\n dispose,\n };\n};\n\nconst readBody = async (req: IncomingMessage): Promise<Buffer> => {\n const chunks: Buffer[] = [];\n for await (const chunk of req as AsyncIterable<Buffer>) {\n chunks.push(chunk);\n }\n return Buffer.concat(chunks);\n};\n\nconst toFetchRequest = async (req: IncomingMessage, origin: string): Promise<Request> => {\n const url = new URL(req.url ?? \"/\", origin);\n const method = req.method ?? \"GET\";\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) {\n // eslint-disable-next-line no-continue -- forEach would require push-style state mutation; continue keeps the filter inline\n continue;\n }\n if (Array.isArray(value)) {\n for (const entry of value) {\n headers.append(key, entry);\n }\n } else {\n headers.append(key, value);\n }\n }\n const init: RequestInit = { method, headers };\n if (method !== \"GET\" && method !== \"HEAD\") {\n const body = await readBody(req);\n init.body = new Uint8Array(body);\n }\n return new Request(url, init);\n};\n\nconst writeFetchResponse = async (res: ServerResponse, response: Response): Promise<void> => {\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n const body = await response.arrayBuffer();\n res.end(Buffer.from(body));\n};\n\nconst handleIncoming = async (\n req: IncomingMessage,\n res: ServerResponse,\n session: BrowserLoginSession,\n): Promise<void> => {\n try {\n const request = await toFetchRequest(req, \"http://127.0.0.1\");\n const response = await session.handleRequest(request);\n await writeFetchResponse(res, response);\n } catch {\n res.statusCode = 500;\n res.end(\"Local callback failed\");\n }\n};\n\nexport const createBrowserLoginServer = async (\n options: CreateBrowserLoginServerOptions = {},\n): Promise<BrowserLoginServer> => {\n const session = createBrowserLoginSession(options);\n const server: Server = createServer((req, res) => {\n // eslint-disable-next-line promise/prefer-await-to-then -- node createServer callback is sync; rejections already swallowed inside handleIncoming, so .catch here is a safety net, not a control-flow then()\n handleIncoming(req, res, session).catch(() => undefined);\n });\n\n server.listen(0, \"127.0.0.1\");\n await once(server, \"listening\");\n const address = server.address();\n const port = address !== null && typeof address === \"object\" ? address.port : 0;\n\n return {\n callbackUrl: `http://127.0.0.1:${port}${session.callbackPath}`,\n waitForToken: session.waitForToken,\n stop: () => {\n session.dispose();\n server.close();\n },\n };\n};\n","import { cancel, isCancel, password, select } from \"@clack/prompts\";\n\nexport const promptPassword = async (message: string): Promise<string> => {\n const value = await password({ message });\n if (isCancel(value)) {\n cancel(\"Operation cancelled.\");\n // eslint-disable-next-line eslint-plugin-unicorn/no-process-exit -- SIGINT at a CLI prompt must terminate the process; throwing would leave Effect runtime stuck\n process.exit(130);\n }\n return value;\n};\n\ntype SelectOption<T> = Parameters<typeof select<T>>[0][\"options\"][number];\n\nexport const promptSelect = async <T>(\n message: string,\n options: readonly SelectOption<T>[],\n): Promise<T> => {\n const value = await select<T>({ message, options: [...options] });\n if (isCancel(value)) {\n cancel(\"Operation cancelled.\");\n // eslint-disable-next-line eslint-plugin-unicorn/no-process-exit -- SIGINT at a CLI prompt must terminate the process; throwing would leave Effect runtime stuck\n process.exit(130);\n }\n return value;\n};\n","import { Command } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { createBrowserLoginServer } from \"../lib/browser-login\";\nimport { promptPassword } from \"../lib/prompts\";\nimport { AuthStore } from \"../services/auth-store\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { ConfigStore } from \"../services/config-store\";\n\nconst buildOpenBrowserCommand = (platform: NodeJS.Platform, url: string) => {\n if (platform === \"darwin\") {\n return Command.make(\"open\", url);\n }\n if (platform === \"win32\") {\n return Command.make(\"cmd\", \"/c\", \"start\", \"\", url);\n }\n return Command.make(\"xdg-open\", url);\n};\n\nconst openBrowser = (\n url: string,\n): Effect.Effect<void, never, CliRuntime | CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const command = buildOpenBrowserCommand(runtime.platform, url);\n\n const opened = yield* Command.exitCode(command).pipe(\n Effect.map((code) => code === 0),\n Effect.catchAll(() => Effect.succeed(false)),\n );\n\n if (!opened) {\n yield* Console.log(`Open this URL manually:\\n${url}`);\n }\n });\n\nconst browserLogin = Effect.scoped(\n Effect.gen(function* () {\n const configStore = yield* ConfigStore;\n const authStore = yield* AuthStore;\n const webUrl = yield* configStore.getWebUrl;\n\n const loginServer = yield* Effect.acquireRelease(\n Effect.promise(async () => createBrowserLoginServer()),\n (server) => Effect.sync(server.stop),\n );\n\n const loginUrl = `${webUrl}/auth/cli-login?callbackUrl=${encodeURIComponent(loginServer.callbackUrl)}`;\n\n yield* Console.log(\"Opening browser for better-update login...\");\n yield* Console.log(\"\");\n yield* openBrowser(loginUrl);\n\n const token = yield* loginServer.waitForToken;\n yield* authStore.saveToken(token);\n yield* Console.log(\"\");\n yield* Console.log(\"Logged in successfully. Token saved to ~/.better-update/auth.json\");\n }),\n);\n\nconst manualLogin = Effect.gen(function* () {\n yield* Console.log(\"Log in to better-update with an existing API key\");\n yield* Console.log(\"Get your API key from the dashboard > API Keys page\");\n yield* Console.log(\"\");\n\n const token = yield* Effect.promise(async () =>\n promptPassword(\"Paste your API key (from dashboard > API Keys):\"),\n );\n const authStore = yield* AuthStore;\n yield* authStore.saveToken(token);\n yield* Console.log(\"\");\n yield* Console.log(\"Logged in successfully. Token saved to ~/.better-update/auth.json\");\n});\n\nexport const runLogin = (options: { readonly manualApiKey: boolean }) =>\n Effect.gen(function* () {\n if (options.manualApiKey) {\n yield* manualLogin;\n return;\n }\n\n yield* browserLogin;\n });\n","import { defineCommand } from \"citty\";\n\nimport { runLogin } from \"../application/login\";\nimport { runEffect } from \"../lib/citty-effect\";\n\nexport const loginCommand = defineCommand({\n meta: { name: \"login\", description: \"Log in to better-update\" },\n args: {\n \"api-key\": {\n type: \"boolean\",\n description: \"Paste an API key manually instead of opening the browser\",\n },\n },\n run: async ({ args }) => runEffect(runLogin({ manualApiKey: args[\"api-key\"] ?? false })),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { AuthStore } from \"../services/auth-store\";\n\nexport const logoutCommand = defineCommand({\n meta: { name: \"logout\", description: \"Remove the stored auth token\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const authStore = yield* AuthStore;\n yield* authStore.clearToken;\n yield* Console.log(\"Logged out. Auth token removed.\");\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { printKeyValue, printTable } from \"../lib/output\";\nimport { apiClient } from \"../services/api-client\";\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List projects (most recently active first)\" },\n args: {\n query: { type: \"string\", description: \"Substring search on name or slug\" },\n sort: {\n type: \"string\",\n description: \"Sort key: lastActivityAt (default) or name\",\n default: \"lastActivityAt\",\n },\n limit: { type: \"string\", description: \"Page size (default 50, max 100)\", default: \"50\" },\n page: { type: \"string\", description: \"1-based page number\", default: \"1\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const sort = args.sort === \"name\" ? \"name\" : \"lastActivityAt\";\n const { items, total, page } = yield* api.projects.list({\n urlParams: {\n page: Number(args.page),\n limit: Number(args.limit),\n sort,\n ...(args.query ? { query: args.query } : {}),\n },\n });\n\n if (items.length === 0) {\n yield* Console.log(\"No projects found.\");\n return;\n }\n\n yield* printTable(\n [\"ID\", \"Name\", \"Slug\", \"Last activity\"],\n items.map((project) => [project.id, project.name, project.slug, project.lastActivityAt]),\n );\n yield* Console.log(`Page ${page} · ${items.length} of ${total} project(s)`);\n }),\n ),\n});\n\nconst createCommand = defineCommand({\n meta: { name: \"create\", description: \"Create a new project\" },\n args: {\n name: { type: \"string\", required: true, description: \"Display name\" },\n slug: { type: \"string\", required: true, description: \"URL-safe slug\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const project = yield* api.projects.create({\n payload: { name: args.name, slug: args.slug },\n });\n yield* printKeyValue([\n [\"ID\", project.id],\n [\"Name\", project.name],\n [\"Slug\", project.slug],\n [\"Created\", project.createdAt],\n ]);\n }),\n ),\n});\n\nconst getCommand = defineCommand({\n meta: { name: \"get\", description: \"Show a project\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Project ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const project = yield* api.projects.get({ path: { id: args.id } });\n yield* printKeyValue([\n [\"ID\", project.id],\n [\"Name\", project.name],\n [\"Slug\", project.slug],\n [\"Created\", project.createdAt],\n ]);\n }),\n ),\n});\n\nconst renameCommand = defineCommand({\n meta: { name: \"rename\", description: \"Rename a project\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Project ID\" },\n name: { type: \"string\", required: true, description: \"New display name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const project = yield* api.projects.rename({\n path: { id: args.id },\n payload: { name: args.name },\n });\n yield* Console.log(`Project renamed to \"${project.name}\".`);\n }),\n ),\n});\n\nconst deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a project\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Project ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.projects.delete({ path: { id: args.id } });\n yield* Console.log(`Project ${args.id} deleted.`);\n }),\n ),\n});\n\nexport const projectsCommand = defineCommand({\n meta: { name: \"projects\", description: \"Manage projects\" },\n subCommands: {\n list: listCommand,\n create: createCommand,\n get: getCommand,\n rename: renameCommand,\n delete: deleteCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { listAllCredentials } from \"../lib/credentials-manager\";\nimport { readProjectId } from \"../lib/expo-config\";\nimport { printKeyValue } from \"../lib/output\";\nimport { apiClient } from \"../services/api-client\";\n\nexport const statusCommand = defineCommand({\n meta: { name: \"status\", description: \"Show project status (credentials, builds)\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const { project, credentials, builds } = yield* Effect.all(\n {\n project: api.projects.get({ path: { id: projectId } }),\n credentials: listAllCredentials(api),\n builds: api.builds.list({ urlParams: { projectId } }),\n },\n { concurrency: \"unbounded\" },\n );\n\n yield* Console.log(\"Project\");\n yield* Console.log(\"-------\");\n yield* printKeyValue([\n [\"Name\", project.name],\n [\"ID\", project.id],\n [\"Slug\", project.slug],\n [\"Created\", project.createdAt],\n ]);\n\n yield* Console.log(\"\");\n yield* Console.log(\"Credentials\");\n yield* Console.log(\"-----------\");\n const iosCreds = credentials.filter((cred) => cred.platform === \"ios\").length;\n const androidCreds = credentials.filter((cred) => cred.platform === \"android\").length;\n yield* printKeyValue([\n [\"iOS\", String(iosCreds)],\n [\"Android\", String(androidCreds)],\n [\"Total\", String(credentials.length)],\n ]);\n\n yield* Console.log(\"\");\n yield* Console.log(\"Builds\");\n yield* Console.log(\"------\");\n const moreSuffix = builds.items.length < builds.total ? \"+\" : \"\";\n yield* printKeyValue([\n [\"Recent\", `${String(builds.items.length)}${moreSuffix}`],\n [\"Total\", String(builds.total)],\n ]);\n }),\n ),\n});\n","import { Data } from \"effect\";\n\nimport { resolveNamedResourceId as resolveNamedResourceIdBase } from \"../../lib/resolve-named-resource\";\n\nexport class UpdateCommandError extends Data.TaggedError(\"UpdateCommandError\")<{\n readonly message: string;\n}> {}\n\nexport const updateErrorExtras = {\n UpdateCommandError: 2,\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n EnvExportError: 7,\n UpdateRollbackError: 2,\n UpdatePromoteError: 2,\n} as const;\n\nexport const resolveNamedResourceId = (params: {\n readonly items: readonly { readonly id: string; readonly name: string }[];\n readonly kind: string;\n readonly name: string;\n}) => resolveNamedResourceIdBase(params, (message) => new UpdateCommandError({ message }));\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { updateErrorExtras } from \"./helpers\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete an update group\" },\n args: {\n groupId: { type: \"positional\", required: true, description: \"Update group ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.updates.deleteGroup({ path: { groupId: args.groupId } });\n yield* Console.log(\n `Deleted ${String(result.deleted)} update(s) from group ${args.groupId}.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseLimit } from \"../../lib/cli-schemas\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { resolveNamedResourceId, updateErrorExtras } from \"./helpers\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List recent updates\" },\n args: {\n branch: { type: \"string\", description: \"Filter by branch name\" },\n limit: { type: \"string\", default: \"20\", description: \"Max rows (default 20)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const limit = yield* parseLimit(args.limit, 20);\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n\n const branchId = args.branch\n ? yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n })\n : undefined;\n\n const { items } = yield* api.updates.list({\n urlParams: {\n projectId,\n ...(branchId === undefined ? {} : { branchId }),\n limit,\n },\n });\n\n if (items.length === 0) {\n yield* Console.log(\"No updates found.\");\n return;\n }\n\n const branchNames = new Map(branches.map((item) => [item.id, item.name]));\n\n yield* printTable(\n [\"Update ID\", \"Group\", \"Branch\", \"Platform\", \"Runtime\", \"Rollout\", \"Rollback\", \"Created\"],\n items.map((item) => [\n item.id,\n item.groupId,\n branchNames.get(item.branchId) ?? item.branchId,\n item.platform,\n item.runtimeVersion,\n `${String(item.rolloutPercentage)}%`,\n item.isRollback ? \"yes\" : \"no\",\n item.createdAt,\n ]),\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport { formatCause } from \"./format-error\";\n\nimport type { Platform } from \"./build-profile\";\n\nexport interface SignedPayload {\n readonly manifestBody: string;\n readonly signature: string;\n readonly certificateChain: string;\n}\n\nexport interface SignedPayloadFileSet {\n readonly manifestBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n}\n\nconst emptySignedPayloadFileSet = {\n manifestBodyFile: undefined,\n signatureFile: undefined,\n certificateChainFile: undefined,\n} as const satisfies SignedPayloadFileSet;\n\nconst hasAnySignedPayloadFile = (files: SignedPayloadFileSet) =>\n files.manifestBodyFile !== undefined ||\n files.signatureFile !== undefined ||\n files.certificateChainFile !== undefined;\n\nconst loadSignedPayloadFromFiles = <Err>(params: {\n readonly files: SignedPayloadFileSet;\n readonly label: string;\n readonly makeError: (message: string) => Err;\n}): Effect.Effect<SignedPayload | null, Err, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n if (!hasAnySignedPayloadFile(params.files)) {\n return null;\n }\n\n if (\n !params.files.manifestBodyFile ||\n !params.files.signatureFile ||\n !params.files.certificateChainFile\n ) {\n return yield* Effect.fail(\n params.makeError(\n `${params.label} requires ${[\n params.files.manifestBodyFile ? null : \"manifest body\",\n params.files.signatureFile ? null : \"signature\",\n params.files.certificateChainFile ? null : \"certificate chain\",\n ]\n .filter(Boolean)\n .join(\", \")} file inputs to be provided as a complete triplet.`,\n ),\n );\n }\n\n const [manifestBody, signature, certificateChain] = yield* Effect.all(\n [\n fileSystem.readFileString(params.files.manifestBodyFile),\n fileSystem.readFileString(params.files.signatureFile),\n fileSystem.readFileString(params.files.certificateChainFile),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.mapError((cause) =>\n params.makeError(`${params.label} failed to read signed inputs: ${formatCause(cause)}`),\n ),\n );\n\n return {\n manifestBody,\n signature: signature.trim(),\n certificateChain: certificateChain.trimEnd(),\n } as const satisfies SignedPayload;\n });\n\nexport const loadOptionalSignedPayload = loadSignedPayloadFromFiles;\n\nexport const loadSignedPublishPayloads = <Err>(params: {\n readonly platforms: readonly Platform[];\n readonly globalFiles: SignedPayloadFileSet;\n readonly platformFiles: Partial<Record<Platform, SignedPayloadFileSet>>;\n readonly makeError: (message: string) => Err;\n}): Effect.Effect<Partial<Record<Platform, SignedPayload>>, Err, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const targetedPlatforms = new Set(params.platforms);\n const nonTargetedPlatforms = ([\"ios\", \"android\"] as const).filter(\n (platform) =>\n !targetedPlatforms.has(platform) &&\n hasAnySignedPayloadFile(params.platformFiles[platform] ?? emptySignedPayloadFileSet),\n );\n if (nonTargetedPlatforms.length > 0) {\n return yield* Effect.fail(\n params.makeError(\n `Signed publish inputs were provided for non-targeted platform(s): ${nonTargetedPlatforms.join(\", \")}.`,\n ),\n );\n }\n\n const hasGlobalFiles = hasAnySignedPayloadFile(params.globalFiles);\n if (\n !hasGlobalFiles &&\n Object.values(params.platformFiles).every((files) => !hasAnySignedPayloadFile(files))\n ) {\n return {};\n }\n\n if (params.platforms.length > 1 && hasGlobalFiles) {\n return yield* Effect.fail(\n params.makeError(\n \"Signed multi-platform publish requires per-platform file sets. Use the --*-ios and --*-android options.\",\n ),\n );\n }\n\n if (params.platforms.length === 1 && hasGlobalFiles) {\n const [platform] = params.platforms;\n if (!platform) {\n return {};\n }\n if (hasAnySignedPayloadFile(params.platformFiles[platform] ?? emptySignedPayloadFileSet)) {\n return yield* Effect.fail(\n params.makeError(\n `Signed publish for ${platform} is ambiguous. Use either the generic file options or the ${platform}-specific file options, not both.`,\n ),\n );\n }\n\n const globalPayload = yield* loadSignedPayloadFromFiles({\n files: params.globalFiles,\n label: \"Signed publish\",\n makeError: params.makeError,\n });\n return globalPayload === null ? {} : { [platform]: globalPayload };\n }\n\n const platformPayloadEntries = yield* Effect.forEach(\n params.platforms,\n (platform) =>\n Effect.gen(function* () {\n const payload = yield* loadSignedPayloadFromFiles({\n files: params.platformFiles[platform] ?? emptySignedPayloadFileSet,\n label: `Signed publish for ${platform}`,\n makeError: params.makeError,\n });\n\n if (payload === null) {\n return yield* Effect.fail(\n params.makeError(\n `Signed multi-platform publish requires a signed payload for ${platform}.`,\n ),\n );\n }\n\n return [platform, payload] as const;\n }),\n { concurrency: 1 },\n );\n\n return Object.fromEntries(platformPayloadEntries) as Partial<Record<Platform, SignedPayload>>;\n });\n","import { Effect } from \"effect\";\n\nimport type { FileSystem } from \"@effect/platform\";\n\nimport { UpdatePromoteError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { loadOptionalSignedPayload } from \"../lib/signed-payloads\";\nimport { apiClient } from \"../services/api-client\";\n\nimport type { AuthRequiredError } from \"../lib/exit-codes\";\nimport type { ApiClientService } from \"../services/api-client\";\n\nexport interface RunUpdatePromoteOptions {\n readonly updateId: string;\n readonly channel: string;\n readonly manifestBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n}\n\nexport interface UpdatePromoteResult {\n readonly sourceUpdateId: string;\n readonly channel: string;\n readonly updateId: string;\n}\n\nexport const runUpdatePromote = (\n options: RunUpdatePromoteOptions,\n): Effect.Effect<\n UpdatePromoteResult,\n AuthRequiredError | UpdatePromoteError,\n ApiClientService | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const signedPayload = yield* loadOptionalSignedPayload({\n files: {\n manifestBodyFile: options.manifestBodyFile,\n signatureFile: options.signatureFile,\n certificateChainFile: options.certificateChainFile,\n },\n label: \"Signed promote\",\n makeError: (message) => new UpdatePromoteError({ message }),\n });\n\n const result = yield* api.updates\n .republish({\n payload: {\n sourceUpdateId: options.updateId,\n destinationChannel: options.channel,\n ...(signedPayload\n ? {\n signedUpdates: [\n {\n sourceUpdateId: options.updateId,\n manifestBody: signedPayload.manifestBody,\n signature: signedPayload.signature,\n certificateChain: signedPayload.certificateChain,\n },\n ],\n }\n : {}),\n },\n })\n .pipe(\n Effect.catchIf(\n (cause): cause is Exclude<typeof cause, AuthRequiredError> =>\n (cause as { readonly _tag?: string })._tag !== \"AuthRequiredError\",\n (cause) =>\n new UpdatePromoteError({\n message: `Failed to promote update: ${formatCause(cause)}`,\n }),\n ),\n );\n\n const [promotedUpdate] = result.updates;\n if (!promotedUpdate) {\n return yield* new UpdatePromoteError({\n message: \"Promote completed without returning a promoted update.\",\n });\n }\n\n return {\n sourceUpdateId: options.updateId,\n channel: options.channel,\n updateId: promotedUpdate.id,\n } as const satisfies UpdatePromoteResult;\n });\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdatePromote } from \"../../application/update-promote\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { updateErrorExtras } from \"./helpers\";\n\nexport const promoteCommand = defineCommand({\n meta: { name: \"promote\", description: \"Promote an existing update to a channel\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Source update ID\" },\n channel: { type: \"string\", required: true, description: \"Target channel name\" },\n \"manifest-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const result = yield* runUpdatePromote({\n updateId: args.updateId,\n channel: args.channel,\n manifestBodyFile: args[\"manifest-body-file\"],\n signatureFile: args[\"signature-file\"],\n certificateChainFile: args[\"certificate-chain-file\"],\n });\n\n yield* Console.log(\n `Promoted update ${result.sourceUpdateId} to channel \"${result.channel}\" as update ${result.updateId}.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import path from \"node:path\";\n\nimport { asRecord } from \"@better-update/type-guards\";\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { BuildFailedError, UpdatePublishError } from \"./exit-codes\";\n\nimport type { Platform } from \"./build-profile\";\n\nexport interface ExportedUpdateAssetFile {\n readonly path: string;\n readonly key: string;\n readonly fileExt: string;\n readonly contentType: string;\n readonly isLaunch: boolean;\n}\n\ninterface ReadExpoPublicConfigOptions {\n readonly projectRoot: string;\n readonly envVars: Record<string, string>;\n}\n\ninterface RunExpoExportOptions extends ReadExpoPublicConfigOptions {\n readonly exportDir: string;\n readonly platform: Platform;\n readonly clear: boolean;\n}\n\ninterface ReadExpoExportAssetsOptions {\n readonly exportDir: string;\n readonly platform: Platform;\n}\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined;\n\nconst normalizeExtension = (value: string | undefined): string | undefined => {\n if (!value) {\n return undefined;\n }\n return value.startsWith(\".\") ? value.slice(1) : value;\n};\n\nconst inferContentType = (fileExt: string, isLaunch: boolean): string => {\n const normalized = fileExt.toLowerCase();\n if (isLaunch || normalized === \"js\" || normalized === \"hbc\" || normalized === \"bundle\") {\n return \"application/javascript\";\n }\n\n switch (normalized) {\n case \"png\": {\n return \"image/png\";\n }\n case \"jpg\":\n case \"jpeg\": {\n return \"image/jpeg\";\n }\n case \"webp\": {\n return \"image/webp\";\n }\n case \"gif\": {\n return \"image/gif\";\n }\n case \"svg\": {\n return \"image/svg+xml\";\n }\n case \"json\": {\n return \"application/json\";\n }\n case \"mp4\": {\n return \"video/mp4\";\n }\n case \"mp3\": {\n return \"audio/mpeg\";\n }\n case \"wav\": {\n return \"audio/wav\";\n }\n case \"ttf\": {\n return \"font/ttf\";\n }\n case \"otf\": {\n return \"font/otf\";\n }\n case \"woff\": {\n return \"font/woff\";\n }\n case \"woff2\": {\n return \"font/woff2\";\n }\n default: {\n return \"application/octet-stream\";\n }\n }\n};\n\nconst makeBunxCommand = (...args: readonly string[]): Command.Command =>\n Command.make(\"bunx\", ...args);\n\nconst runCommand = (\n cmd: Command.Command,\n step: string,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor> =>\n Command.exitCode(cmd.pipe(Command.stdout(\"inherit\"), Command.stderr(\"inherit\"))).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} failed to spawn: ${String(cause)}`,\n }),\n ),\n Effect.flatMap((code) =>\n code === 0\n ? Effect.void\n : Effect.fail(\n new BuildFailedError({\n step,\n exitCode: code,\n message: `${step} exited with code ${code}`,\n }),\n ),\n ),\n );\n\nexport const readExpoPublicConfig = ({\n projectRoot,\n envVars,\n}: ReadExpoPublicConfigOptions): Effect.Effect<\n Record<string, unknown>,\n UpdatePublishError,\n CliRuntime | CommandExecutor.CommandExecutor\n> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n const stdout = yield* Command.string(\n makeBunxCommand(\"expo\", \"config\", \"--type\", \"public\", \"--json\").pipe(\n Command.workingDirectory(projectRoot),\n Command.env(commandEnv),\n ),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to read Expo public config: ${String(cause)}`,\n }),\n ),\n );\n\n const parsed = yield* Effect.try({\n try: () => JSON.parse(stdout) as unknown,\n catch: () =>\n new UpdatePublishError({\n message: \"Expo public config output was not valid JSON.\",\n }),\n });\n\n const config = asRecord(parsed);\n if (!config) {\n return yield* new UpdatePublishError({\n message: \"Expo public config did not decode to a JSON object.\",\n });\n }\n\n return config;\n });\n\nexport const runExpoExport = ({\n projectRoot,\n exportDir,\n platform,\n envVars,\n clear,\n}: RunExpoExportOptions): Effect.Effect<\n void,\n BuildFailedError,\n CliRuntime | CommandExecutor.CommandExecutor\n> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n const args = [\n \"expo\",\n \"export\",\n \"--platform\",\n platform,\n \"--output-dir\",\n exportDir,\n \"--dump-assetmap\",\n ];\n if (clear) {\n args.push(\"--clear\");\n }\n\n return yield* runCommand(\n makeBunxCommand(...args).pipe(Command.workingDirectory(projectRoot), Command.env(commandEnv)),\n `expo export ${platform}`,\n );\n });\n\nexport const readExpoExportAssets = ({\n exportDir,\n platform,\n}: ReadExpoExportAssetsOptions): Effect.Effect<\n readonly ExportedUpdateAssetFile[],\n UpdatePublishError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const metadataPath = path.join(exportDir, \"metadata.json\");\n const metadataText = yield* fs.readFileString(metadataPath).pipe(\n Effect.mapError(\n () =>\n new UpdatePublishError({\n message: `Expected Expo export metadata at ${metadataPath}.`,\n }),\n ),\n );\n\n const metadata = yield* Effect.try({\n try: () => JSON.parse(metadataText) as unknown,\n catch: () =>\n new UpdatePublishError({\n message: `Failed to parse ${metadataPath} as JSON.`,\n }),\n });\n\n const platformMetadata = asRecord(asRecord(asRecord(metadata)?.[\"fileMetadata\"])?.[platform]);\n const bundlePath = asString(platformMetadata?.[\"bundle\"]);\n if (!bundlePath) {\n return yield* new UpdatePublishError({\n message: `Expo export did not contain a bundle path for platform \"${platform}\".`,\n });\n }\n\n const bundleExt = normalizeExtension(path.extname(bundlePath)) ?? \"js\";\n const rawAssets = Array.isArray(platformMetadata?.[\"assets\"]) ? platformMetadata[\"assets\"] : [];\n\n // eslint-disable-next-line unicorn/no-array-method-this-argument -- Effect.forEach, not Array.prototype.forEach; the second arg is a mapping effect, not a thisArg\n const assets = yield* Effect.forEach(rawAssets, (rawAsset, index) =>\n Effect.gen(function* () {\n const asset = asRecord(rawAsset);\n const assetPath = asString(asset?.[\"path\"]);\n if (!assetPath) {\n return yield* new UpdatePublishError({\n message: `Expo export asset #${String(index + 1)} is missing its \"path\" field.`,\n });\n }\n\n const fileExt =\n normalizeExtension(asString(asset?.[\"ext\"])) ??\n normalizeExtension(path.extname(assetPath)) ??\n \"bin\";\n\n return {\n path: path.join(exportDir, assetPath),\n key: path.posix.basename(assetPath),\n fileExt,\n contentType: inferContentType(fileExt, false),\n isLaunch: false,\n } as const satisfies ExportedUpdateAssetFile;\n }),\n );\n\n return [\n {\n path: path.join(exportDir, bundlePath),\n key: path.posix.basename(bundlePath),\n fileExt: bundleExt,\n contentType: inferContentType(bundleExt, true),\n isLaunch: true,\n } as const satisfies ExportedUpdateAssetFile,\n ...assets,\n ] as const;\n });\n","import type { Platform } from \"./build-profile\";\nimport type { ExpoConfig } from \"./expo-config\";\n\nexport type UpdatePlatformOption = Platform | \"all\";\n\nexport const resolveUpdatePlatforms = (\n config: ExpoConfig,\n requestedPlatform: UpdatePlatformOption,\n): readonly Platform[] => {\n if (requestedPlatform !== \"all\") {\n return [requestedPlatform] as const;\n }\n\n // Typeof null === \"object\" in JS, so an explicit null check is required to\n // Reject configs that opt a platform out via `ios: null` / `android: null`.\n return ([\"ios\", \"android\"] as const).filter(\n (platform) =>\n // eslint-disable-next-line typescript/no-unnecessary-condition -- runtime guards against `ios: null` / `android: null` even though the static type excludes null\n typeof config[platform] === \"object\" && config[platform] !== null,\n );\n};\n","import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { fromHex, toBase64Url } from \"@better-update/encoding\";\nimport { Effect } from \"effect\";\nimport { uniqBy } from \"es-toolkit\";\n\nimport type { CommandExecutor, FileSystem } from \"@effect/platform\";\n\nimport { readRuntimeVersionMeta } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { UpdatePublishError } from \"../lib/exit-codes\";\nimport { extractProjectId, extractSlug, readExpoConfig } from \"../lib/expo-config\";\nimport { readExpoExportAssets, readExpoPublicConfig, runExpoExport } from \"../lib/expo-export\";\nimport { formatCause } from \"../lib/format-error\";\nimport { readGitContext } from \"../lib/git-context\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { sha256File, sha256Namespaced } from \"../lib/sha256\";\nimport { loadSignedPublishPayloads } from \"../lib/signed-payloads\";\nimport { acquireBuildTempDir } from \"../lib/temp-dir\";\nimport { resolveUpdatePlatforms } from \"../lib/update-platforms\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { UpdateAssetUploader } from \"../services/update-asset-uploader\";\n\nimport type { Platform } from \"../lib/build-profile\";\nimport type {\n AuthRequiredError,\n BuildProfileError,\n BuildFailedError,\n ProjectNotLinkedError,\n EnvExportError,\n RuntimeVersionError,\n} from \"../lib/exit-codes\";\nimport type { ExpoConfig } from \"../lib/expo-config\";\nimport type { SignedPayload } from \"../lib/signed-payloads\";\nimport type { ApiClientService } from \"../services/api-client\";\n\nexport interface RunUpdatePublishOptions {\n readonly branch: string | undefined;\n readonly platform: Platform | \"all\";\n readonly message: string | undefined;\n readonly auto: boolean;\n readonly environment: string;\n readonly clear: boolean;\n readonly rolloutPercentage: number | undefined;\n readonly manifestBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n readonly manifestBodyFileIos: string | undefined;\n readonly signatureFileIos: string | undefined;\n readonly certificateChainFileIos: string | undefined;\n readonly manifestBodyFileAndroid: string | undefined;\n readonly signatureFileAndroid: string | undefined;\n readonly certificateChainFileAndroid: string | undefined;\n}\n\nexport interface PublishedPlatformResult {\n readonly platform: Platform;\n readonly updateId: string;\n readonly runtimeVersion: string;\n readonly uploadedAssets: number;\n readonly deduplicatedAssets: number;\n}\n\nexport interface PublishUpdatesResult {\n readonly groupId: string;\n readonly branch: string;\n readonly results: readonly PublishedPlatformResult[];\n}\n\ninterface PreparedAsset {\n readonly path: string;\n readonly key: string;\n readonly hash: string;\n readonly contentChecksum: string;\n readonly byteSize: number;\n readonly contentType: string;\n readonly fileExt: string;\n readonly isLaunch: boolean;\n}\n\nconst buildUpdateExtra = (\n expoClient: Record<string, unknown>,\n projectId: string,\n environment: string,\n) => ({\n expoClient,\n eas: { projectId },\n environment,\n});\n\nconst dedupeAssetsByHash = (assets: readonly PreparedAsset[]): readonly PreparedAsset[] =>\n uniqBy(assets, (asset) => asset.hash);\n\nconst preparePlatformAssets = ({\n exportDir,\n platform,\n}: {\n readonly exportDir: string;\n readonly platform: Platform;\n}): Effect.Effect<\n readonly PreparedAsset[],\n UpdatePublishError | BuildFailedError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const exportedAssets = yield* readExpoExportAssets({ exportDir, platform });\n return yield* Effect.forEach(\n exportedAssets,\n (asset) =>\n sha256File(asset.path).pipe(\n Effect.map(({ sha256: contentSha256Hex, byteSize }) => ({\n ...asset,\n hash: sha256Namespaced(asset.contentType, contentSha256Hex),\n contentChecksum: toBase64Url(fromHex(contentSha256Hex)),\n byteSize,\n })),\n ),\n { concurrency: 4 },\n );\n });\n\nconst publishPlatform = (params: {\n readonly projectRoot: string;\n readonly exportDir: string;\n readonly projectId: string;\n readonly slug: string;\n readonly branch: string;\n readonly groupId: string;\n readonly message: string;\n readonly environment: string;\n readonly environmentVars: Record<string, string>;\n readonly expoClientConfig: Record<string, unknown>;\n readonly clear: boolean;\n readonly expoConfig: ExpoConfig;\n readonly platform: Platform;\n readonly signedPayload: SignedPayload | null;\n readonly rolloutPercentage: number | undefined;\n}): Effect.Effect<\n PublishedPlatformResult,\n | AuthRequiredError\n | UpdatePublishError\n | BuildProfileError\n | BuildFailedError\n | RuntimeVersionError,\n | ApiClientService\n | CliRuntime\n | UpdateAssetUploader\n | CommandExecutor.CommandExecutor\n | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const assetUploader = yield* UpdateAssetUploader;\n\n const runtimeVersionMeta = readRuntimeVersionMeta(params.expoConfig);\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: runtimeVersionMeta.rawRuntimeVersion,\n appVersion: runtimeVersionMeta.appVersion,\n projectRoot: params.projectRoot,\n });\n\n yield* runExpoExport({\n projectRoot: params.projectRoot,\n exportDir: params.exportDir,\n platform: params.platform,\n envVars: params.environmentVars,\n clear: params.clear,\n });\n\n const preparedAssets = yield* preparePlatformAssets({\n exportDir: params.exportDir,\n platform: params.platform,\n });\n const uniqueAssets = dedupeAssetsByHash(preparedAssets);\n\n const assetRegistration = yield* api.assets\n .upload({\n payload: {\n projectId: params.projectId,\n assets: uniqueAssets.map((asset) => ({\n hash: asset.hash,\n contentType: asset.contentType,\n fileExt: asset.fileExt,\n contentChecksum: asset.contentChecksum,\n })),\n },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to register ${params.platform} assets: ${formatCause(cause)}`,\n }),\n ),\n );\n\n const uploadDetailsByHash = new Map(\n assetRegistration.uploaded.map((asset) => [asset.hash, asset] as const),\n );\n yield* Effect.forEach(\n uniqueAssets.filter((asset) => uploadDetailsByHash.has(asset.hash)),\n (asset) =>\n Effect.gen(function* () {\n const detail = uploadDetailsByHash.get(asset.hash);\n if (!detail) {\n return yield* Effect.fail(\n new UpdatePublishError({\n message: `Missing upload details for asset ${asset.hash}`,\n }),\n );\n }\n return yield* assetUploader.uploadAssetBinary({\n path: asset.path,\n hash: asset.hash,\n byteSize: asset.byteSize,\n uploadUrl: detail.uploadUrl,\n uploadExpiresAt: detail.uploadExpiresAt,\n uploadHeaders: detail.uploadHeaders,\n });\n }),\n { concurrency: 4 },\n );\n\n const update = yield* api.updates\n .create({\n payload: {\n branch: params.branch,\n slug: params.slug,\n runtimeVersion,\n platform: params.platform,\n message: params.message,\n groupId: params.groupId,\n metadata: {},\n extra: buildUpdateExtra(params.expoClientConfig, params.projectId, params.environment),\n assets: preparedAssets.map((asset) => ({\n hash: asset.hash,\n key: asset.key,\n isLaunch: asset.isLaunch,\n contentChecksum: asset.contentChecksum,\n })),\n ...(params.signedPayload\n ? {\n manifestBody: params.signedPayload.manifestBody,\n signature: params.signedPayload.signature,\n certificateChain: params.signedPayload.certificateChain,\n }\n : {}),\n ...(params.rolloutPercentage === undefined\n ? {}\n : { rolloutPercentage: params.rolloutPercentage }),\n },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to publish ${params.platform} update: ${formatCause(cause)}`,\n }),\n ),\n );\n\n return {\n platform: params.platform,\n updateId: update.id,\n runtimeVersion,\n uploadedAssets: assetRegistration.uploaded.length,\n deduplicatedAssets: assetRegistration.deduplicated.length,\n } as const satisfies PublishedPlatformResult;\n });\n\nexport const runUpdatePublish = (\n options: RunUpdatePublishOptions,\n): Effect.Effect<\n PublishUpdatesResult,\n | AuthRequiredError\n | UpdatePublishError\n | ProjectNotLinkedError\n | BuildProfileError\n | RuntimeVersionError\n | EnvExportError\n | BuildFailedError,\n | ApiClientService\n | CliRuntime\n | UpdateAssetUploader\n | CommandExecutor.CommandExecutor\n | FileSystem.FileSystem\n> =>\n Effect.scoped(\n // eslint-disable-next-line eslint/max-statements -- update publish orchestration is inherently sequential (read config → resolve runtime version → expo export → register assets → publish per platform); splitting further fragments the pipeline without improving readability\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const api = yield* apiClient;\n\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n\n const environmentVars = yield* pullEnvVars(api, {\n projectId,\n environment: options.environment,\n });\n\n // Read slug from the env-resolved config so dynamic configs that derive\n // slug from env vars publish under the same identity as `expo export`.\n const expoConfig = yield* readExpoConfig(projectRoot, environmentVars);\n const slug = yield* extractSlug(expoConfig);\n const platforms = resolveUpdatePlatforms(expoConfig, options.platform);\n if (platforms.length === 0) {\n return yield* new UpdatePublishError({\n message:\n 'No publishable platforms found in your Expo config. Add an \"ios\" or \"android\" section, or pass --platform explicitly.',\n });\n }\n const expoClientConfig = yield* readExpoPublicConfig({\n projectRoot,\n envVars: environmentVars,\n });\n const tempDir = yield* acquireBuildTempDir.pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to create a temporary export directory: ${formatCause(cause)}`,\n }),\n ),\n );\n let resolvedBranch = options.branch;\n let resolvedMessage = options.message;\n\n if (options.auto) {\n const gitContext = yield* readGitContext(projectRoot);\n if (!resolvedBranch) {\n if (!gitContext.ref) {\n return yield* new UpdatePublishError({\n message:\n \"Cannot infer branch from git. Ensure you are in a git repo with a checked-out branch, or provide --branch explicitly.\",\n });\n }\n resolvedBranch = gitContext.ref;\n }\n if (!resolvedMessage && gitContext.commitMessage) {\n resolvedMessage = gitContext.commitMessage;\n }\n }\n\n if (!resolvedBranch) {\n return yield* new UpdatePublishError({\n message: \"Missing --branch. Provide it explicitly or use --auto to infer from git.\",\n });\n }\n\n const branch = resolvedBranch;\n const groupId = randomUUID();\n const message = resolvedMessage ?? \"Publish via better-update CLI\";\n const signedPayloads = yield* loadSignedPublishPayloads({\n platforms,\n globalFiles: {\n manifestBodyFile: options.manifestBodyFile,\n signatureFile: options.signatureFile,\n certificateChainFile: options.certificateChainFile,\n },\n platformFiles: {\n ios: {\n manifestBodyFile: options.manifestBodyFileIos,\n signatureFile: options.signatureFileIos,\n certificateChainFile: options.certificateChainFileIos,\n },\n android: {\n manifestBodyFile: options.manifestBodyFileAndroid,\n signatureFile: options.signatureFileAndroid,\n certificateChainFile: options.certificateChainFileAndroid,\n },\n },\n makeError: (errorMessage) => new UpdatePublishError({ message: errorMessage }),\n });\n const results = yield* Effect.forEach(\n platforms,\n (platform) =>\n publishPlatform({\n projectRoot,\n exportDir: path.join(tempDir, `export-${platform}`),\n projectId,\n slug,\n branch,\n groupId,\n message,\n environment: options.environment,\n environmentVars,\n expoClientConfig,\n clear: options.clear,\n expoConfig,\n platform,\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- signedPayload absence means unsigned; null is correct downstream\n signedPayload: signedPayloads[platform] ?? null,\n rolloutPercentage: options.rolloutPercentage,\n }),\n { concurrency: 1 },\n );\n\n return {\n groupId,\n branch,\n results,\n } as const satisfies PublishUpdatesResult;\n }),\n );\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdatePublish } from \"../../application/update-publish\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../lib/cli-schemas\";\nimport { printTable } from \"../../lib/output\";\n\nconst PUBLISH_EXIT_EXTRAS = {\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n EnvExportError: 7,\n BuildFailedError: 6,\n UpdatePublishError: 7,\n} as const;\n\nexport const publishCommand = defineCommand({\n meta: { name: \"publish\", description: \"Publish a new OTA update group\" },\n args: {\n branch: { type: \"string\", description: \"Target branch name\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Platform(s) to publish\",\n },\n message: { type: \"string\", description: \"Optional update message\" },\n environment: { type: \"string\", default: \"production\", description: \"Env vars scope\" },\n auto: { type: \"boolean\", description: \"Skip prompts (for CI)\" },\n clear: { type: \"boolean\", description: \"Drop existing assets before upload\" },\n \"rollout-percentage\": { type: \"string\", description: \"Initial rollout percentage (1-100)\" },\n \"manifest-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n \"manifest-body-file-ios\": { type: \"string\" },\n \"signature-file-ios\": { type: \"string\" },\n \"certificate-chain-file-ios\": { type: \"string\" },\n \"manifest-body-file-android\": { type: \"string\" },\n \"signature-file-android\": { type: \"string\" },\n \"certificate-chain-file-android\": { type: \"string\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const rolloutPercentage = args[\"rollout-percentage\"]\n ? yield* parseRolloutPercentage(args[\"rollout-percentage\"], \"rollout-percentage\")\n : undefined;\n\n const result = yield* runUpdatePublish({\n branch: args.branch,\n platform: args.platform,\n message: args.message,\n auto: args.auto ?? false,\n environment: args.environment,\n clear: args.clear ?? false,\n rolloutPercentage,\n manifestBodyFile: args[\"manifest-body-file\"],\n signatureFile: args[\"signature-file\"],\n certificateChainFile: args[\"certificate-chain-file\"],\n manifestBodyFileIos: args[\"manifest-body-file-ios\"],\n signatureFileIos: args[\"signature-file-ios\"],\n certificateChainFileIos: args[\"certificate-chain-file-ios\"],\n manifestBodyFileAndroid: args[\"manifest-body-file-android\"],\n signatureFileAndroid: args[\"signature-file-android\"],\n certificateChainFileAndroid: args[\"certificate-chain-file-android\"],\n });\n\n yield* Console.log(\n `Published update group ${result.groupId} to branch \"${result.branch}\".`,\n );\n yield* Console.log(\"\");\n yield* printTable(\n [\"Platform\", \"Update ID\", \"Runtime Version\", \"Uploaded\", \"Reused\"],\n result.results.map((entry) => [\n entry.platform,\n entry.updateId,\n entry.runtimeVersion,\n String(entry.uploadedAssets),\n String(entry.deduplicatedAssets),\n ]),\n );\n }),\n PUBLISH_EXIT_EXTRAS,\n ),\n});\n","export const buildRollbackDirectiveBody = (commitTime: string): string =>\n JSON.stringify({\n type: \"rollBackToEmbedded\",\n parameters: {\n commitTime,\n },\n });\n","import { randomUUID } from \"node:crypto\";\n\nimport { buildRollbackDirectiveBody } from \"@better-update/expo-protocol\";\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { readRuntimeVersionMeta } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { UpdateRollbackError } from \"../lib/exit-codes\";\nimport { extractProjectId, extractSlug, readExpoConfig } from \"../lib/expo-config\";\nimport { formatCause } from \"../lib/format-error\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { resolveUpdatePlatforms } from \"../lib/update-platforms\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nimport type { Platform } from \"../lib/build-profile\";\nimport type {\n AuthRequiredError,\n BuildProfileError,\n EnvExportError,\n ProjectNotLinkedError,\n RuntimeVersionError,\n} from \"../lib/exit-codes\";\nimport type { UpdatePlatformOption } from \"../lib/update-platforms\";\nimport type { ApiClientService } from \"../services/api-client\";\n\ninterface CreateRollbackParams {\n readonly branch: string;\n readonly projectSlug: string;\n readonly runtimeVersion: string;\n readonly platform: Platform;\n readonly message: string;\n readonly groupId: string;\n readonly directiveBody: string;\n readonly signature: string | undefined;\n readonly certificateChain: string | undefined;\n}\n\nexport interface RollbackResultItem {\n readonly platform: Platform;\n readonly updateId: string;\n readonly runtimeVersion: string;\n}\n\nexport interface RunUpdateRollbackOptions {\n readonly branch: string;\n readonly platform: UpdatePlatformOption;\n readonly environment: string;\n readonly message: string | undefined;\n readonly commitTime: string | undefined;\n readonly directiveBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n}\n\nexport interface UpdateRollbackResult {\n readonly groupId: string;\n readonly branch: string;\n readonly commitTime: string;\n readonly results: readonly RollbackResultItem[];\n}\n\ninterface SignedRollbackPayload {\n readonly directiveBody: string;\n readonly signature: string;\n readonly certificateChain: string;\n}\n\nconst resolveCommitTime = (input: string | undefined): Effect.Effect<string, UpdateRollbackError> =>\n Effect.gen(function* () {\n const commitTime = input ?? new Date().toISOString();\n if (Number.isNaN(Date.parse(commitTime))) {\n return yield* new UpdateRollbackError({\n message: \"commitTime must be a valid ISO 8601 timestamp.\",\n });\n }\n return commitTime;\n });\n\nconst extractDirectiveCommitTime = (\n directiveBody: string,\n): Effect.Effect<string, UpdateRollbackError> =>\n Effect.gen(function* () {\n const directive = yield* Effect.try({\n try: (): unknown => JSON.parse(directiveBody),\n catch: () =>\n new UpdateRollbackError({\n message: \"directiveBody must be valid JSON.\",\n }),\n });\n\n if (!isRecord(directive)) {\n return yield* new UpdateRollbackError({\n message: \"directiveBody must decode to a JSON object.\",\n });\n }\n\n if (directive[\"type\"] !== \"rollBackToEmbedded\") {\n return yield* new UpdateRollbackError({\n message: 'directiveBody.type must be \"rollBackToEmbedded\".',\n });\n }\n\n const { parameters } = directive;\n if (!isRecord(parameters)) {\n return yield* new UpdateRollbackError({\n message: \"directiveBody.parameters must be an object.\",\n });\n }\n\n const { commitTime } = parameters;\n if (typeof commitTime !== \"string\" || Number.isNaN(Date.parse(commitTime))) {\n return yield* new UpdateRollbackError({\n message: \"directiveBody.parameters.commitTime must be a valid ISO 8601 timestamp.\",\n });\n }\n\n return commitTime;\n });\n\nconst loadOptionalSignedRollbackPayload = (\n options: RunUpdateRollbackOptions,\n): Effect.Effect<SignedRollbackPayload | null, UpdateRollbackError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const hasAnySigningInput =\n options.directiveBodyFile !== undefined ||\n options.signatureFile !== undefined ||\n options.certificateChainFile !== undefined;\n\n if (!hasAnySigningInput) {\n return null;\n }\n\n if (!options.directiveBodyFile || !options.signatureFile || !options.certificateChainFile) {\n return yield* new UpdateRollbackError({\n message:\n \"Signed rollback requires --directive-body-file, --signature-file, and --certificate-chain-file together.\",\n });\n }\n\n const [directiveBody, signature, certificateChain] = yield* Effect.all(\n [\n fileSystem.readFileString(options.directiveBodyFile),\n fileSystem.readFileString(options.signatureFile),\n fileSystem.readFileString(options.certificateChainFile),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.mapError(\n (cause) =>\n new UpdateRollbackError({\n message: `Failed to read signed rollback inputs: ${formatCause(cause)}`,\n }),\n ),\n );\n\n return {\n directiveBody,\n signature: signature.trim(),\n certificateChain: certificateChain.trimEnd(),\n } satisfies SignedRollbackPayload;\n });\n\nconst createRollbackForPlatform = (\n params: CreateRollbackParams,\n): Effect.Effect<RollbackResultItem, AuthRequiredError | UpdateRollbackError, ApiClientService> =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const update = yield* api.updates\n .create({\n payload: {\n branch: params.branch,\n slug: params.projectSlug,\n runtimeVersion: params.runtimeVersion,\n platform: params.platform,\n message: params.message,\n groupId: params.groupId,\n metadata: {},\n assets: [],\n isRollback: true,\n directiveBody: params.directiveBody,\n ...(params.signature ? { signature: params.signature } : {}),\n ...(params.certificateChain ? { certificateChain: params.certificateChain } : {}),\n },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdateRollbackError({\n message: `Failed to create ${params.platform} rollback: ${formatCause(cause)}`,\n }),\n ),\n );\n\n return {\n platform: params.platform,\n updateId: update.id,\n runtimeVersion: params.runtimeVersion,\n } as const satisfies RollbackResultItem;\n });\n\nexport const runUpdateRollback = (\n options: RunUpdateRollbackOptions,\n): Effect.Effect<\n UpdateRollbackResult,\n | AuthRequiredError\n | ProjectNotLinkedError\n | BuildProfileError\n | EnvExportError\n | RuntimeVersionError\n | UpdateRollbackError,\n ApiClientService | CliRuntime | CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const api = yield* apiClient;\n\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n\n const environmentVars = yield* pullEnvVars(api, {\n projectId,\n environment: options.environment,\n });\n\n // Re-resolve with the env-var overlay so runtimeVersion / ios / android\n // sections (and slug) derived from process.env match what the corresponding\n // publish would have computed — otherwise rollback can target the wrong\n // runtime or publish under a stale slug.\n const config = yield* readExpoConfig(projectRoot, environmentVars);\n const projectSlug = yield* extractSlug(config);\n const platforms = resolveUpdatePlatforms(config, options.platform);\n if (platforms.length === 0) {\n return yield* new UpdateRollbackError({\n message:\n 'No publishable platforms found in your Expo config. Add an \"ios\" or \"android\" section, or pass --platform explicitly.',\n });\n }\n\n const { appVersion, rawRuntimeVersion } = readRuntimeVersionMeta(config);\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: rawRuntimeVersion,\n appVersion,\n projectRoot,\n });\n const signedPayload = yield* loadOptionalSignedRollbackPayload(options);\n const commitTime = signedPayload\n ? yield* Effect.gen(function* () {\n const directiveCommitTime = yield* extractDirectiveCommitTime(\n signedPayload.directiveBody,\n );\n if (options.commitTime && options.commitTime !== directiveCommitTime) {\n return yield* new UpdateRollbackError({\n message: \"commitTime must match directiveBody.parameters.commitTime in signed mode.\",\n });\n }\n return directiveCommitTime;\n })\n : yield* resolveCommitTime(options.commitTime);\n const groupId = randomUUID();\n const message = options.message ?? \"Rollback to embedded via better-update CLI\";\n\n const results = yield* Effect.forEach(\n platforms,\n (platform) =>\n createRollbackForPlatform({\n branch: options.branch,\n projectSlug,\n runtimeVersion,\n platform,\n message,\n groupId,\n directiveBody: signedPayload?.directiveBody ?? buildRollbackDirectiveBody(commitTime),\n signature: signedPayload?.signature,\n certificateChain: signedPayload?.certificateChain,\n }),\n { concurrency: 1 },\n );\n\n return {\n groupId,\n branch: options.branch,\n commitTime,\n results,\n } as const satisfies UpdateRollbackResult;\n });\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdateRollback } from \"../../application/update-rollback\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printTable } from \"../../lib/output\";\nimport { updateErrorExtras } from \"./helpers\";\n\nexport const rollbackCommand = defineCommand({\n meta: { name: \"rollback\", description: \"Roll back updates on a branch\" },\n args: {\n branch: { type: \"string\", required: true, description: \"Branch to roll back\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Platform(s) to roll back\",\n },\n message: { type: \"string\" },\n environment: { type: \"string\", default: \"production\", description: \"Env vars scope\" },\n \"commit-time\": { type: \"string\" },\n \"directive-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const result = yield* runUpdateRollback({\n branch: args.branch,\n platform: args.platform,\n environment: args.environment,\n message: args.message,\n commitTime: args[\"commit-time\"],\n directiveBodyFile: args[\"directive-body-file\"],\n signatureFile: args[\"signature-file\"],\n certificateChainFile: args[\"certificate-chain-file\"],\n });\n\n yield* Console.log(\n `Created rollback group ${result.groupId} on branch \"${result.branch}\" at ${result.commitTime}.`,\n );\n yield* Console.log(\"\");\n yield* printTable(\n [\"Platform\", \"Update ID\", \"Runtime Version\"],\n result.results.map((entry) => [entry.platform, entry.updateId, entry.runtimeVersion]),\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { updateErrorExtras } from \"../helpers\";\n\nexport const completeCommand = defineCommand({\n meta: { name: \"complete\", description: \"Complete the rollout for an update\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Update ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.updates.completeRollout({ path: { id: args.updateId } });\n yield* Console.log(\n `Completed rollout for ${args.updateId}. Current rollout is ${String(result.rolloutPercentage)}%.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { updateErrorExtras } from \"../helpers\";\n\nexport const revertCommand = defineCommand({\n meta: { name: \"revert\", description: \"Revert the rollout for an update\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Update ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.updates.revertRollout({ path: { id: args.updateId } });\n yield* Console.log(\n `Reverted rollout for ${args.updateId}. Current rollout is ${String(result.rolloutPercentage)}%.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../../lib/cli-schemas\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { updateErrorExtras } from \"../helpers\";\n\nexport const setCommand = defineCommand({\n meta: { name: \"set\", description: \"Set the rollout percentage for an update\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Update ID\" },\n percentage: { type: \"string\", required: true, description: \"Rollout percentage (1-100)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const percentage = yield* parseRolloutPercentage(args.percentage, \"percentage\");\n const api = yield* apiClient;\n const result = yield* api.updates.editRollout({\n path: { id: args.updateId },\n payload: { percentage },\n });\n\n yield* Console.log(\n `Updated rollout for ${args.updateId} to ${String(result.rolloutPercentage)}%.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { completeCommand } from \"./complete\";\nimport { revertCommand } from \"./revert\";\nimport { setCommand } from \"./set\";\n\nexport const rolloutCommand = defineCommand({\n meta: { name: \"rollout\", description: \"Manage per-update rollouts\" },\n subCommands: {\n set: setCommand,\n complete: completeCommand,\n revert: revertCommand,\n },\n});\n","import { defineCommand } from \"citty\";\n\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { promoteCommand } from \"./promote\";\nimport { publishCommand } from \"./publish\";\nimport { rollbackCommand } from \"./rollback\";\nimport { rolloutCommand } from \"./rollout\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Manage OTA updates\" },\n subCommands: {\n publish: publishCommand,\n list: listCommand,\n delete: deleteCommand,\n promote: promoteCommand,\n rollback: rollbackCommand,\n rollout: rolloutCommand,\n },\n});\n","import { fileURLToPath } from \"node:url\";\n\nexport type Installer = \"bun\" | \"pnpm\" | \"yarn\" | \"npm\";\n\nexport const detectInstaller = (modulePath: string): Installer => {\n const normalized = modulePath.replaceAll(\"\\\\\", \"/\").toLowerCase();\n if (normalized.includes(\"/.bun/\")) {\n return \"bun\";\n }\n if (normalized.includes(\"/pnpm/\")) {\n return \"pnpm\";\n }\n if (normalized.includes(\"/.yarn/\") || normalized.includes(\"/yarn/\")) {\n return \"yarn\";\n }\n return \"npm\";\n};\n\nconst INSTALL_COMMANDS: Readonly<Record<Installer, string>> = {\n bun: \"bun add -g @better-update/cli@latest\",\n pnpm: \"pnpm add -g @better-update/cli@latest\",\n yarn: \"yarn global add @better-update/cli@latest\",\n npm: \"npm install -g @better-update/cli@latest\",\n};\n\nexport const installCommand = (installer: Installer): string => INSTALL_COMMANDS[installer];\n\nexport const detectInstallerFromImportMetaUrl = (importMetaUrl: string): Installer =>\n detectInstaller(fileURLToPath(importMetaUrl));\n","const stripPrerelease = (version: string): readonly number[] => {\n const main = version.replace(/-.*$/u, \"\");\n return main.split(\".\").map((part) => Number.parseInt(part, 10) || 0);\n};\n\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const [la = 0, lb = 0, lc = 0] = stripPrerelease(latest);\n const [ca = 0, cb = 0, cc = 0] = stripPrerelease(current);\n if (la !== ca) {\n return la > ca;\n }\n if (lb !== cb) {\n return lb > cb;\n }\n return lc > cc;\n};\n","import { Console, Effect } from \"effect\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { VersionCheck } from \"../services/version-check\";\nimport { detectInstallerFromImportMetaUrl, installCommand } from \"./detect-installer\";\nimport { isNewerVersion } from \"./semver-compare\";\n\nconst formatNotice = (current: string, latest: string, command: string): string =>\n [\n \"\",\n `╭─ Update available: @better-update/cli ${current} → ${latest}`,\n `│ Run: ${command}`,\n \"╰─\",\n \"\",\n ].join(\"\\n\");\n\nconst isOptedOut = Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const value = yield* runtime.getEnv(\"BETTER_UPDATE_DISABLE_UPDATE_NOTIFIER\");\n return value === \"1\" || value === \"true\";\n});\n\nexport const bootstrapVersionCheck = (\n currentVersion: string,\n installerHint: string,\n spawnRefresh: () => void,\n): Effect.Effect<void, never, VersionCheck | CliRuntime> =>\n Effect.gen(function* () {\n if (yield* isOptedOut) {\n return;\n }\n const versionCheck = yield* VersionCheck;\n const cached = yield* versionCheck.cachedLatest;\n if (cached && isNewerVersion(cached, currentVersion)) {\n const installer = detectInstallerFromImportMetaUrl(installerHint);\n yield* Console.error(formatNotice(currentVersion, cached, installCommand(installer)));\n }\n if (yield* versionCheck.cacheStale) {\n spawnRefresh();\n }\n });\n\nexport const refreshVersionCacheIfStale: Effect.Effect<void, never, VersionCheck | CliRuntime> =\n Effect.gen(function* () {\n if (yield* isOptedOut) {\n return;\n }\n const versionCheck = yield* VersionCheck;\n const stale = yield* versionCheck.cacheStale;\n if (stale) {\n yield* versionCheck.refreshCache;\n }\n });\n","#!/usr/bin/env node\n\nimport { spawn } from \"node:child_process\";\n\nimport { defineCommand, runMain } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport { CliLive } from \"./app-layer\";\nimport { analyticsCommand } from \"./commands/analytics\";\nimport { auditLogsCommand } from \"./commands/audit-logs\";\nimport { branchesCommand } from \"./commands/branches\";\nimport { buildCommand } from \"./commands/build\";\nimport { buildsCommand } from \"./commands/builds\";\nimport { channelsCommand } from \"./commands/channels\";\nimport { credentialsCommand } from \"./commands/credentials\";\nimport { envCommand } from \"./commands/env\";\nimport { fingerprintCommand } from \"./commands/fingerprint\";\nimport { initCommand } from \"./commands/init\";\nimport { loginCommand } from \"./commands/login\";\nimport { logoutCommand } from \"./commands/logout\";\nimport { projectsCommand } from \"./commands/projects\";\nimport { statusCommand } from \"./commands/status\";\nimport { updateCommand } from \"./commands/update\";\nimport { bootstrapVersionCheck, refreshVersionCacheIfStale } from \"./lib/version-notifier\";\n\nconst REFRESH_VERSION_CACHE_FLAG = \"__refresh-version-cache\";\n\nif (process.argv[2] === REFRESH_VERSION_CACHE_FLAG) {\n await Effect.runPromise(refreshVersionCacheIfStale.pipe(Effect.provide(CliLive)));\n process.exit(0);\n}\n\nconst spawnDetachedRefresh = (): void => {\n const child = spawn(process.execPath, [import.meta.filename, REFRESH_VERSION_CACHE_FLAG], {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n};\n\nconst main = defineCommand({\n meta: {\n name: \"better-update\",\n version: pkg.version,\n description: \"Publish OTA updates and builds for Expo apps\",\n },\n setup: async () => {\n await Effect.runPromise(\n bootstrapVersionCheck(pkg.version, import.meta.url, spawnDetachedRefresh).pipe(\n Effect.provide(CliLive),\n ),\n );\n },\n subCommands: {\n login: loginCommand,\n logout: logoutCommand,\n init: initCommand,\n status: statusCommand,\n projects: projectsCommand,\n branches: branchesCommand,\n channels: channelsCommand,\n build: buildCommand,\n builds: buildsCommand,\n credentials: credentialsCommand,\n env: envCommand,\n fingerprint: fingerprintCommand,\n update: updateCommand,\n analytics: analyticsCommand,\n \"audit-logs\": auditLogsCommand,\n },\n});\n\nawait runMain(main);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACoCA,IAAa,cAAb,cAAiC,QAAQ,IAAI,kBAAkB,EAAiC,CAAC;;;;ACjCjG,IAAa,eAAb,cAAkC,OAAO,aAA2B,CAClE,gBACA,EAAE,SAAS,OAAO,QAAQ,EAC1B,cAAc,YAAY,EAAE,QAAQ,KAAK,CAAC,CAC3C,CAAC;AAEF,IAAa,YAAb,cAA+B,OAAO,aAAwB,CAC5D,aACA,EAAE,SAAS,OAAO,QAAQ,EAC1B,cAAc,YAAY,EAAE,QAAQ,KAAK,CAAC,CAC3C,CAAC;AAEF,IAAa,cAAb,cAAiC,OAAO,aAA0B,CAChE,eACA,EAAE,SAAS,OAAO,QAAQ,EAC1B,cAAc,YAAY,EAAE,QAAQ,KAAK,CAAC,CAC3C,CAAC;;;;ACdF,MAAM,iBAAiB,gBAAgB;AACvC,MAAM,iBAAiB,gBAAgB,OAAO;CAC5C,KAAK;CACL,IAAI;CACL,CAAC;AAEF,IAAa,iBAAb,cAAoC,kBAAkB,KAAqB,CAAC,sBAAsB;CAChG,SAAS;CACT,UAAU;CACV,UAAU;EAAE,QAAQ;EAAgB,QAAQ;EAAgB;CAC7D,CAAC,CAAC;;;;ACZH,IAAa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AAO,WAAW,2BAA2B,KAAK,OAAO,QAAQ,QAAQ,CAAC,CAAC;AACjF,SAAQ,KAAK,EAAE;;AAGjB,MAAM,6BAAmC;AAKvC,CAJc,MAAM,QAAQ,UAAU,CAAC,OAAO,KAAK,UAAU,2BAA2B,EAAE;EACxF,UAAU;EACV,OAAO;EACR,CACI,CAAC,OAAO;;AAmCf,MAAM,QAhCO,cAAc;CACzB,MAAM;EACJ,MAAM;EACGC;EACT,aAAa;EACd;CACD,OAAO,YAAY;AACjB,QAAM,OAAO,WACX,sBAAsBA,SAAa,OAAO,KAAK,KAAK,qBAAqB,CAAC,KACxE,OAAO,QAAQ,QAAQ,CACxB,CACF;;CAEH,aAAa;EACX,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ;EACR,UAAU;EACV,UAAU;EACV,UAAU;EACV,OAAO;EACP,QAAQ;EACR,aAAa;EACb,KAAK;EACL,aAAa;EACb,QAAQ;EACR,WAAW;EACX,cAAc;EACf;CACF,CAEiB,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["idParam","projectIdParam","idParam","idParam","idParam","idParam","idParam","idParam","idParam","projectIdParam","idParam","idParam","idParam","idParam","idParam","idParam","projectIdParam","idParam","idParam","AppleAuthError","process","AppleAuthError","process","channelsCommand","channelsCommand","listCommand","listCommand","listCommand","createCommand","viewCommand","renameCommand","deleteCommand","hasTag","asString","process","findAppDirectory","asString","APPLE_TEAM_ID_RE","extractTeamId","writeEasJson","deleteCommand","fetchArtifact","Buffer","downloadCommand","getCommand","DISTRIBUTION_OPTIONS","listCommand","Buffer","Buffer","runCommand","uploadCommand","listCommand","getCommand","deleteCommand","downloadCommand","runCommand","uploadCommand","resolveNamedResourceId","resolveNamedResourceId","resolveNamedResourceIdBase","createCommand","resolveNamedResourceId","deleteCommand","insightsCommand","listCommand","completeCommand","createCommand","resolveNamedResourceId","revertCommand","updateCommand","rolloutCommand","createCommand","updateCommand","completeCommand","revertCommand","updateCommand","resolveNamedResourceId","viewCommand","listCommand","viewCommand","createCommand","updateCommand","deleteCommand","rolloutCommand","insightsCommand","APPLE_PUSH_KEY_PORTAL_URL","formatRowLabel","process","APPLE_PUSH_KEY_PORTAL_URL","configureCommand","CREDENTIAL_TYPES","deleteCommand","writeText","downloadProvisioningProfile","downloadAscApiKey","distributionCertificateCommand","generateCommand","listCommand","CREDENTIAL_TYPES","pullCommand","pushCommand","pushCommand","pullCommand","CREDENTIAL_TYPES","viewCommand","listCommand","viewCommand","generateCommand","deleteCommand","configureCommand","process","deleteCommand","trailing","getCommand","listCommand","setCommand","updateCommand","listCommand","getCommand","setCommand","updateCommand","deleteCommand","listCommand","deleteCommand","resolveNamedResourceIdBase","revertCommand","revertCommand","ALLOWED_EVENTS","isWebhookEvent","parseEvents","pkg.version"],"sources":["../package.json","../src/lib/interactive-mode.ts","../src/lib/output-mode.ts","../../../packages/api/src/auth/context.ts","../../../packages/api/src/auth/errors.ts","../../../packages/api/src/auth/middleware.ts","../../../packages/api/src/auth/ownership.ts","../../../packages/api/src/domain/common.ts","../../../packages/api/src/domain/analytics.ts","../../../packages/api/src/groups/analytics.ts","../../../packages/api/src/domain/android-application-identifier.ts","../../../packages/api/src/domain/errors.ts","../../../packages/api/src/groups/android-application-identifiers.ts","../../../packages/api/src/domain/android-build-credentials.ts","../../../packages/api/src/groups/android-build-credentials.ts","../../../packages/api/src/domain/android-upload-keystore.ts","../../../packages/api/src/groups/android-upload-keystores.ts","../../../packages/api/src/domain/apple-team.ts","../../../packages/api/src/domain/apple-distribution-certificate.ts","../../../packages/api/src/groups/apple-distribution-certificates.ts","../../../packages/api/src/domain/apple-provisioning-profile.ts","../../../packages/api/src/groups/apple-provisioning-profiles.ts","../../../packages/api/src/domain/apple-push-key.ts","../../../packages/api/src/groups/apple-push-keys.ts","../../../packages/api/src/groups/apple-teams.ts","../../../packages/api/src/domain/asc-api-key.ts","../../../packages/api/src/groups/asc-api-keys.ts","../../../packages/api/src/domain/asset.ts","../../../packages/api/src/groups/assets.ts","../../../packages/api/src/domain/audit-log.ts","../../../packages/api/src/groups/audit-logs.ts","../../../packages/api/src/domain/branch.ts","../../../packages/api/src/groups/branches.ts","../../../packages/api/src/domain/build-credentials.ts","../../../packages/api/src/groups/build-credentials.ts","../../../packages/api/src/domain/build.ts","../../../packages/api/src/domain/build-compatibility.ts","../../../packages/api/src/groups/builds.ts","../../../packages/api/src/domain/channel.ts","../../../packages/api/src/groups/channels.ts","../../../packages/api/src/domain/device.ts","../../../packages/api/src/groups/devices.ts","../../../packages/api/src/domain/env-var.ts","../../../packages/api/src/groups/env-vars.ts","../../../packages/api/src/domain/google-service-account-key.ts","../../../packages/api/src/groups/google-service-account-keys.ts","../../../packages/api/src/domain/ios-bundle-configuration.ts","../../../packages/api/src/groups/ios-bundle-configurations.ts","../../../packages/api/src/domain/me.ts","../../../packages/api/src/groups/me.ts","../../../packages/api/src/domain/project.ts","../../../packages/api/src/groups/projects.ts","../../../packages/api/src/domain/update.ts","../../../packages/api/src/groups/updates.ts","../../../packages/api/src/domain/webhook.ts","../../../packages/api/src/groups/webhooks.ts","../../../packages/api/src/api.ts","../../../packages/api/src/groups/manifest.ts","../../../packages/api/src/protocol-api.ts","../../../packages/type-guards/src/index.ts","../src/lib/exit-codes.ts","../src/lib/format-error.ts","../src/services/cli-runtime.ts","../src/services/auth-store.ts","../src/services/config-store.ts","../src/services/api-client.ts","../../../packages/safe-json/src/index.ts","../src/services/apple-session-store.ts","../src/services/presigned-upload.ts","../src/services/update-asset-uploader.ts","../src/services/version-check.ts","../src/app-layer.ts","../src/application/command-exit.ts","../src/lib/command-errors.ts","../src/lib/citty-effect.ts","../src/lib/expo-config.ts","../src/lib/output.ts","../src/commands/analytics/adoption.ts","../src/commands/analytics/channels.ts","../src/commands/analytics/platforms.ts","../src/commands/analytics/updates.ts","../src/commands/analytics/index.ts","../src/lib/cli-schemas.ts","../src/commands/audit-logs/list.ts","../src/commands/audit-logs/index.ts","../src/commands/autocomplete.ts","../src/lib/drain-cursor.ts","../src/commands/branches.ts","../src/lib/android-signing-gradle.ts","../src/lib/string-utils.ts","../src/lib/artifact-finder.ts","../../../packages/encoding/src/index.ts","../src/lib/credentials-downloader.ts","../src/lib/credentials-json.ts","../src/lib/local-credentials.ts","../src/lib/sha256.ts","../src/commands/build/run-step.ts","../src/commands/build/android.ts","../src/lib/ios-export-options.ts","../src/lib/ios-keychain.ts","../src/lib/plist.ts","../src/lib/ios-provisioning.ts","../src/lib/post-build-validation.ts","../src/lib/xcpretty-formatter.ts","../src/commands/build/ios.ts","../src/commands/build/reserve-and-upload.ts","../src/lib/eas-config.ts","../src/lib/build-profile.ts","../src/lib/clear-cache.ts","../src/lib/env-exporter.ts","../src/lib/git-context.ts","../src/lib/gradle-config.ts","../src/lib/prompts.ts","../src/lib/platform-detect.ts","../src/lib/repo-clean.ts","../src/lib/fingerprint.ts","../src/lib/runtime-version.ts","../src/lib/temp-dir.ts","../src/lib/android-keystore.ts","../src/lib/apple-pem.ts","../src/lib/apple-asc-jwt.ts","../src/lib/apple-asc-client.ts","../src/lib/apple-cert-to-p12.ts","../src/lib/apple-csr.ts","../src/lib/credentials-generator.ts","../src/application/credentials-interactive.ts","../src/application/build-workflow.ts","../src/commands/build/configure.ts","../src/commands/build/index.ts","../src/commands/builds/compatibility-matrix.ts","../src/commands/builds/delete.ts","../src/commands/builds/download.ts","../src/commands/builds/get.ts","../src/commands/builds/install-link.ts","../src/commands/builds/list.ts","../src/commands/builds/resign.ts","../src/lib/native-runner.ts","../src/commands/builds/run.ts","../src/application/upload-workflow.ts","../src/commands/builds/upload.ts","../src/commands/builds/index.ts","../src/lib/resolve-named-resource.ts","../src/commands/channels/helpers.ts","../src/commands/channels/create.ts","../src/commands/channels/delete.ts","../src/commands/channels/insights.ts","../src/commands/channels/list.ts","../src/commands/channels/pause.ts","../src/commands/channels/resume.ts","../src/commands/channels/rollout/complete.ts","../src/commands/channels/rollout/create.ts","../src/commands/channels/rollout/revert.ts","../src/commands/channels/rollout/update.ts","../src/commands/channels/rollout/index.ts","../src/commands/channels/update.ts","../src/commands/channels/view.ts","../src/commands/channels/index.ts","../src/lib/pkcs12.ts","../src/lib/credentials-manager.ts","../src/application/credentials-manager-shared.ts","../src/application/credentials-rebind.ts","../src/application/credentials-manager-android.ts","../src/application/credentials-manager-ios-asc.ts","../src/application/credentials-manager-ios-revoke.ts","../src/application/credentials-manager-ios.ts","../src/application/credentials-manager.ts","../src/commands/credentials/configure.ts","../src/commands/credentials/delete.ts","../src/commands/credentials/download.ts","../src/commands/credentials/generate.ts","../src/commands/credentials/list.ts","../src/commands/credentials/regenerate-profile.ts","../src/commands/credentials/remove.ts","../src/commands/credentials/revoke.ts","../src/commands/credentials/sync/helpers.ts","../src/commands/credentials/sync/pull.ts","../src/commands/credentials/sync/push.ts","../src/commands/credentials/sync/index.ts","../src/commands/credentials/upload.ts","../src/commands/credentials/upload-asc-key.ts","../src/commands/credentials/view.ts","../src/commands/credentials/index.ts","../src/commands/devices/add.ts","../src/commands/devices/delete.ts","../src/commands/devices/disable.ts","../src/commands/devices/enable.ts","../src/commands/devices/list.ts","../src/commands/devices/rename.ts","../src/commands/devices/sync.ts","../src/commands/devices/view.ts","../src/commands/devices/index.ts","../src/commands/doctor.ts","../src/commands/env/helpers.ts","../src/commands/env/delete.ts","../src/lib/exec-trailing-argv.ts","../src/commands/env/exec.ts","../src/commands/env/export.ts","../src/commands/env/get.ts","../src/commands/env/import.ts","../src/commands/env/list.ts","../src/commands/env/pull.ts","../src/commands/env/push.ts","../src/commands/env/set.ts","../src/commands/env/update.ts","../src/commands/env/index.ts","../src/commands/fingerprint/compare.ts","../src/commands/fingerprint/generate.ts","../src/commands/fingerprint/index.ts","../src/commands/init.ts","../src/lib/browser-login.ts","../src/application/login.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/migrate-config.ts","../src/commands/open.ts","../src/commands/projects.ts","../src/commands/status.ts","../src/commands/update/configure.ts","../src/commands/update/helpers.ts","../src/commands/update/delete.ts","../src/commands/update/edit.ts","../src/commands/update/insights.ts","../src/commands/update/list.ts","../src/lib/signed-payloads.ts","../src/application/update-promote.ts","../src/commands/update/promote.ts","../src/lib/expo-export.ts","../src/lib/update-platforms.ts","../src/application/update-publish-helpers.ts","../src/application/update-publish.ts","../src/commands/update/publish.ts","../src/commands/update/republish.ts","../../../packages/expo-protocol/src/index.ts","../src/application/update-rollback.ts","../src/commands/update/revert.ts","../src/commands/update/revert-rollout.ts","../src/commands/update/rollback.ts","../src/commands/update/rollout/complete.ts","../src/commands/update/rollout/revert.ts","../src/commands/update/rollout/set.ts","../src/commands/update/rollout/index.ts","../src/commands/update/view.ts","../src/commands/update/index.ts","../src/commands/webhooks/create.ts","../src/commands/webhooks/delete.ts","../src/commands/webhooks/list.ts","../src/commands/webhooks/update.ts","../src/commands/webhooks/view.ts","../src/commands/webhooks/index.ts","../src/commands/whoami.ts","../src/lib/global-flags.ts","../src/lib/detect-installer.ts","../src/lib/semver-compare.ts","../src/lib/version-notifier.ts","../src/index.ts"],"sourcesContent":["","import { Context, Layer } from \"effect\";\n\nexport class InteractiveMode extends Context.Tag(\"cli/InteractiveMode\")<\n InteractiveMode,\n {\n /** True when the CLI may show interactive prompts; false in CI / `--non-interactive` / `--json`. */\n readonly allow: boolean;\n }\n>() {}\n\nexport const makeInteractiveModeLayer = (allow: boolean): Layer.Layer<InteractiveMode> =>\n Layer.succeed(InteractiveMode, { allow });\n\n/** Default: prompts allowed. The CLI entrypoint overrides this via `--non-interactive`/CI detect. */\nexport const InteractiveModeLive = makeInteractiveModeLayer(true);\n","import { Context, Layer } from \"effect\";\n\nexport class OutputMode extends Context.Tag(\"cli/OutputMode\")<\n OutputMode,\n {\n /** Emit machine-readable JSON only. Suppress spinners, progress, and human prose. */\n readonly json: boolean;\n }\n>() {}\n\nexport const makeOutputModeLayer = (json: boolean): Layer.Layer<OutputMode> =>\n Layer.succeed(OutputMode, { json });\n\n/** Default output mode: human-readable (json=false). Used when no override layer is provided. */\nexport const OutputModeLive = makeOutputModeLayer(false);\n","import { Context } from \"effect\";\n\nexport type Role = \"owner\" | \"admin\" | \"developer\" | \"viewer\";\n\nexport type Resource =\n | \"organization\"\n | \"member\"\n | \"invitation\"\n | \"project\"\n | \"channel\"\n | \"branch\"\n | \"update\"\n | \"rollout\"\n | \"billing\"\n | \"apiKey\"\n | \"build\"\n | \"appleCredential\"\n | \"androidCredential\"\n | \"iosBundleConfiguration\"\n | \"envVar\"\n | \"auditLog\"\n | \"device\"\n | \"webhook\";\n\nexport type Action = \"read\" | \"create\" | \"update\" | \"delete\" | \"cancel\" | \"download\";\n\nexport type EffectivePermissions = Partial<Record<Resource, readonly Action[]>>;\n\nexport interface AuthContextShape {\n readonly userId: string | null;\n readonly organizationId: string;\n readonly role: Role | null;\n readonly effectivePermissions: EffectivePermissions;\n readonly source: \"session\" | \"api-key\";\n readonly actorEmail: string;\n}\n\nexport class AuthContext extends Context.Tag(\"api/AuthContext\")<AuthContext, AuthContextShape>() {}\n","import { HttpApiSchema } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nexport class Unauthorized extends Schema.TaggedError<Unauthorized>()(\n \"Unauthorized\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 401 }),\n) {}\n\nexport class Forbidden extends Schema.TaggedError<Forbidden>()(\n \"Forbidden\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 403 }),\n) {}\n\nexport class OrgRequired extends Schema.TaggedError<OrgRequired>()(\n \"OrgRequired\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 400 }),\n) {}\n","import { HttpApiMiddleware, HttpApiSecurity } from \"@effect/platform\";\n\nimport { AuthContext } from \"./context\";\nimport { Unauthorized } from \"./errors\";\n\nconst bearerSecurity = HttpApiSecurity.bearer;\nconst cookieSecurity = HttpApiSecurity.apiKey({\n key: \"__Secure-better-auth.session_token\",\n in: \"cookie\",\n});\n\nexport class Authentication extends HttpApiMiddleware.Tag<Authentication>()(\"api/Authentication\", {\n failure: Unauthorized,\n provides: AuthContext,\n security: { bearer: bearerSecurity, cookie: cookieSecurity },\n}) {}\n","import { HttpApiSchema } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nexport class NotFound extends Schema.TaggedError<NotFound>()(\n \"NotFound\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 404 }),\n) {}\n","import { Schema } from \"effect\";\n\nexport const Id = Schema.String.annotations({\n description: \"UUIDv7 identifier\",\n});\n\nexport const DateTimeString = Schema.String.annotations({\n description: \"ISO 8601 datetime\",\n});\n\nexport const Platform = Schema.Literal(\"ios\", \"android\");\n\nexport const PaginationParams = Schema.Struct({\n page: Schema.optional(Schema.NumberFromString),\n limit: Schema.optional(Schema.NumberFromString),\n});\n\nexport const CursorPaginationParams = Schema.Struct({\n cursor: Schema.optional(Schema.String),\n limit: Schema.optional(Schema.NumberFromString),\n});\n\nexport const cursorPageResult = <T, Encoded, R>(itemSchema: Schema.Schema<T, Encoded, R>) =>\n Schema.Struct({\n items: Schema.Array(itemSchema),\n nextCursor: Schema.NullOr(Schema.String),\n });\n\nexport const UpdateRolloutBody = Schema.Struct({\n percentage: Schema.Number.pipe(Schema.int(), Schema.between(1, 100)),\n});\n\nexport const UploadHeaders = Schema.Record({ key: Schema.String, value: Schema.String });\n","import { Schema } from \"effect\";\n\nimport { Id } from \"./common\";\n\n// -- Shared --\n\nexport const PeriodLiteral = Schema.Literal(\"1d\", \"7d\", \"30d\", \"90d\");\nexport const Period = Schema.optional(PeriodLiteral);\n\n// -- Adoption --\n\nexport const AdoptionParams = Schema.Struct({\n projectId: Id,\n period: Period,\n});\n\nconst AdoptionEntry = Schema.Struct({\n updateId: Schema.String,\n devices: Schema.Number,\n firstSeen: Schema.String,\n lastSeen: Schema.String,\n});\n\nexport const AdoptionResult = Schema.Struct({\n updates: Schema.Array(AdoptionEntry),\n});\n\n// -- Update Analytics --\n\nexport const UpdateAnalyticsParams = Schema.Struct({\n projectId: Id,\n updateId: Schema.String,\n period: Period,\n});\n\nconst ResponseTypeBreakdown = Schema.Struct({\n manifest: Schema.Number,\n directive: Schema.Number,\n no_update: Schema.Number,\n});\n\nconst TimeSeriesEntry = Schema.Struct({\n timestamp: Schema.String,\n requests: Schema.Number,\n});\n\nexport const UpdateAnalyticsResult = Schema.Struct({\n updateId: Schema.String,\n totalRequests: Schema.Number,\n uniqueDevices: Schema.Number,\n byResponseType: ResponseTypeBreakdown,\n timeSeries: Schema.Array(TimeSeriesEntry),\n});\n\n// -- Channel Analytics --\n\nexport const ChannelAnalyticsParams = Schema.Struct({\n projectId: Id,\n channel: Schema.String,\n period: Period,\n});\n\nexport const ChannelAnalyticsResult = Schema.Struct({\n channel: Schema.String,\n totalRequests: Schema.Number,\n uniqueDevices: Schema.Number,\n responseTypeDistribution: ResponseTypeBreakdown,\n});\n\n// -- Platform Analytics --\n\nexport const PlatformParams = Schema.Struct({\n projectId: Id,\n period: Period,\n});\n\nconst PlatformEntry = Schema.Struct({\n platform: Schema.String,\n requests: Schema.Number,\n devices: Schema.Number,\n});\n\nexport const PlatformResult = Schema.Struct({\n platforms: Schema.Array(PlatformEntry),\n});\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AdoptionParams,\n AdoptionResult,\n ChannelAnalyticsParams,\n ChannelAnalyticsResult,\n PlatformParams,\n PlatformResult,\n UpdateAnalyticsParams,\n UpdateAnalyticsResult,\n} from \"../domain/analytics\";\n\nexport class AnalyticsGroup extends HttpApiGroup.make(\"analytics\")\n .add(\n HttpApiEndpoint.get(\"adoption\", \"/api/analytics/adoption\")\n .setUrlParams(AdoptionParams)\n .addSuccess(AdoptionResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Adoption analytics\",\n description: \"Adoption rate per update for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"updates\", \"/api/analytics/updates\")\n .setUrlParams(UpdateAnalyticsParams)\n .addSuccess(UpdateAnalyticsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update analytics\",\n description: \"Request metrics for a specific update\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"channels\", \"/api/analytics/channels\")\n .setUrlParams(ChannelAnalyticsParams)\n .addSuccess(ChannelAnalyticsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Channel analytics\",\n description: \"Channel-level health metrics\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"platforms\", \"/api/analytics/platforms\")\n .setUrlParams(PlatformParams)\n .addSuccess(PlatformResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Platform analytics\",\n description: \"Device count breakdown by platform\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Analytics\",\n description: \"Deployment analytics endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AndroidPackageName = Schema.String.pipe(\n Schema.pattern(/^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$/u, {\n message: () => \"Package name must be reverse-domain style (e.g., com.acme.app)\",\n }),\n);\n\nexport class AndroidApplicationIdentifier extends Schema.Class<AndroidApplicationIdentifier>(\n \"AndroidApplicationIdentifier\",\n)({\n id: Id,\n organizationId: Id,\n projectId: Id,\n packageName: Schema.String,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateAndroidApplicationIdentifierBody = Schema.Struct({\n packageName: AndroidPackageName,\n});\n\nexport const DeleteAndroidApplicationIdentifierResult = Schema.Struct({\n deleted: Schema.Number,\n});\n","import { HttpApiSchema } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nexport class BadRequest extends Schema.TaggedError<BadRequest>()(\n \"BadRequest\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 400 }),\n) {}\n\nexport class Conflict extends Schema.TaggedError<Conflict>()(\n \"Conflict\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 409 }),\n) {}\n\nexport class NotAcceptable extends Schema.TaggedError<NotAcceptable>()(\n \"NotAcceptable\",\n { message: Schema.String },\n HttpApiSchema.annotations({ status: 406 }),\n) {}\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AndroidApplicationIdentifier,\n CreateAndroidApplicationIdentifierBody,\n DeleteAndroidApplicationIdentifierResult,\n} from \"../domain/android-application-identifier\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class AndroidApplicationIdentifiersGroup extends HttpApiGroup.make(\n \"androidApplicationIdentifiers\",\n)\n .add(\n HttpApiEndpoint.get(\"list\")`/api/projects/${projectIdParam}/android-application-identifiers`\n .addSuccess(Schema.Struct({ items: Schema.Array(AndroidApplicationIdentifier) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Android application identifiers\",\n description: \"List all Android package identifiers for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"create\")`/api/projects/${projectIdParam}/android-application-identifiers`\n .setPayload(CreateAndroidApplicationIdentifierBody)\n .addSuccess(AndroidApplicationIdentifier, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create Android application identifier\",\n description: \"Register an Android package name for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/android-application-identifiers/${idParam}`\n .addSuccess(DeleteAndroidApplicationIdentifierResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete Android application identifier\",\n description: \"Remove an Android application identifier\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Android Application Identifiers\",\n description: \"Manage Android package name registrations per project\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport class AndroidBuildCredentials extends Schema.Class<AndroidBuildCredentials>(\n \"AndroidBuildCredentials\",\n)({\n id: Id,\n organizationId: Id,\n androidApplicationIdentifierId: Id,\n androidUploadKeystoreId: Schema.NullOr(Id),\n googleServiceAccountKeyForSubmissionsId: Schema.NullOr(Id),\n googleServiceAccountKeyForFcmV1Id: Schema.NullOr(Id),\n name: Schema.String,\n isDefault: Schema.Boolean,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateAndroidBuildCredentialsBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n androidUploadKeystoreId: Schema.optional(Id),\n googleServiceAccountKeyForSubmissionsId: Schema.optional(Id),\n googleServiceAccountKeyForFcmV1Id: Schema.optional(Id),\n isDefault: Schema.optional(Schema.Boolean),\n});\n\nexport const UpdateAndroidBuildCredentialsBody = Schema.Struct({\n name: Schema.optional(Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120))),\n androidUploadKeystoreId: Schema.optional(Schema.NullOr(Id)),\n googleServiceAccountKeyForSubmissionsId: Schema.optional(Schema.NullOr(Id)),\n googleServiceAccountKeyForFcmV1Id: Schema.optional(Schema.NullOr(Id)),\n isDefault: Schema.optional(Schema.Boolean),\n});\n\nexport const DeleteAndroidBuildCredentialsResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AndroidBuildCredentials,\n CreateAndroidBuildCredentialsBody,\n DeleteAndroidBuildCredentialsResult,\n UpdateAndroidBuildCredentialsBody,\n} from \"../domain/android-build-credentials\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst applicationIdentifierIdParam = HttpApiSchema.param(\"applicationIdentifierId\", Schema.String);\n\nexport class AndroidBuildCredentialsGroup extends HttpApiGroup.make(\"androidBuildCredentials\")\n .add(\n HttpApiEndpoint.get(\n \"list\",\n )`/api/android-application-identifiers/${applicationIdentifierIdParam}/build-credentials`\n .addSuccess(Schema.Struct({ items: Schema.Array(AndroidBuildCredentials) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Android build credentials\",\n description: \"List named build credential groups for an Android app identifier\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\n \"create\",\n )`/api/android-application-identifiers/${applicationIdentifierIdParam}/build-credentials`\n .setPayload(CreateAndroidBuildCredentialsBody)\n .addSuccess(AndroidBuildCredentials, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create Android build credentials group\",\n description: \"Create a named build credentials group (Default or custom)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.put(\"update\")`/api/android-build-credentials/${idParam}`\n .setPayload(UpdateAndroidBuildCredentialsBody)\n .addSuccess(AndroidBuildCredentials)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update Android build credentials\",\n description: \"Rename group, change default flag, or swap bound keystore/keys\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/android-build-credentials/${idParam}`\n .addSuccess(DeleteAndroidBuildCredentialsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete Android build credentials\",\n description: \"Remove a build credentials group\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Android Build Credentials\",\n description: \"Named groups of build credentials per Android application identifier\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport class AndroidUploadKeystore extends Schema.Class<AndroidUploadKeystore>(\n \"AndroidUploadKeystore\",\n)({\n id: Id,\n organizationId: Id,\n keyAlias: Schema.String,\n md5Fingerprint: Schema.NullOr(Schema.String),\n sha1Fingerprint: Schema.NullOr(Schema.String),\n sha256Fingerprint: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAndroidUploadKeystoreBody = Schema.Struct({\n keystoreBase64: Schema.String.pipe(Schema.minLength(1)),\n keyAlias: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(200)),\n keystorePassword: Schema.String.pipe(Schema.minLength(1)),\n keyPassword: Schema.String.pipe(Schema.minLength(1)),\n md5Fingerprint: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n sha1Fingerprint: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n sha256Fingerprint: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n});\n\nexport const DeleteAndroidUploadKeystoreResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DownloadAndroidUploadKeystoreResult = Schema.Struct({\n id: Id,\n keystoreBase64: Schema.String,\n keyAlias: Schema.String,\n keystorePassword: Schema.String,\n keyPassword: Schema.String,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AndroidUploadKeystore,\n DeleteAndroidUploadKeystoreResult,\n DownloadAndroidUploadKeystoreResult,\n UploadAndroidUploadKeystoreBody,\n} from \"../domain/android-upload-keystore\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AndroidUploadKeystoresGroup extends HttpApiGroup.make(\"androidUploadKeystores\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/android/upload-keystores\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AndroidUploadKeystore) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Android upload keystores\",\n description: \"List uploaded Android keystores\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/android/upload-keystores\")\n .setPayload(UploadAndroidUploadKeystoreBody)\n .addSuccess(AndroidUploadKeystore, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload Android keystore\",\n description: \"Upload a JKS/PKCS12 keystore with key alias + passwords\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/android/upload-keystores/${idParam}`\n .addSuccess(DeleteAndroidUploadKeystoreResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete Android keystore\",\n description: \"Remove a stored Android keystore\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"download\")`/api/android/upload-keystores/${idParam}/download`\n .addSuccess(DownloadAndroidUploadKeystoreResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Download Android keystore\",\n description: \"Fetch the decrypted keystore + passwords for local use (audit-logged)\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Android Upload Keystores\",\n description: \"Manage Android signing keystores\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AppleTeamType = Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\");\nexport type AppleTeamTypeValue = typeof AppleTeamType.Type;\n\nexport const AppleTeamIdentifier = Schema.String.pipe(\n Schema.pattern(/^[A-Z0-9]{10}$/u, {\n message: () => \"Apple Team identifier must be 10 uppercase alphanumeric characters\",\n }),\n);\n\nexport class AppleTeam extends Schema.Class<AppleTeam>(\"AppleTeam\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.String,\n appleTeamType: AppleTeamType,\n name: Schema.NullOr(Schema.String),\n distributionCertificateCount: Schema.Number,\n pushKeyCount: Schema.Number,\n ascApiKeyCount: Schema.Number,\n provisioningProfileCount: Schema.Number,\n deviceCount: Schema.Number,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n","import { Schema } from \"effect\";\n\nimport { AppleTeamIdentifier } from \"./apple-team\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport class AppleDistributionCertificate extends Schema.Class<AppleDistributionCertificate>(\n \"AppleDistributionCertificate\",\n)({\n id: Id,\n organizationId: Id,\n appleTeamId: Id,\n serialNumber: Schema.String,\n developerIdIdentifier: Schema.NullOr(Schema.String),\n validFrom: DateTimeString,\n validUntil: DateTimeString,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAppleDistributionCertificateBody = Schema.Struct({\n p12Base64: Schema.String.pipe(Schema.minLength(1)),\n p12Password: Schema.String.pipe(Schema.minLength(1)),\n serialNumber: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(200)),\n appleTeamIdentifier: AppleTeamIdentifier,\n appleTeamName: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n appleTeamType: Schema.optional(Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\")),\n developerIdIdentifier: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n validFrom: DateTimeString,\n validUntil: DateTimeString,\n});\n\nexport const DeleteAppleDistributionCertificateResult = Schema.Struct({\n deleted: Schema.Number,\n});\n\nexport const DownloadAppleDistributionCertificateResult = Schema.Struct({\n id: Id,\n p12Base64: Schema.String,\n p12Password: Schema.String,\n serialNumber: Schema.String,\n appleTeamIdentifier: AppleTeamIdentifier,\n validFrom: DateTimeString,\n validUntil: DateTimeString,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AppleDistributionCertificate,\n DeleteAppleDistributionCertificateResult,\n DownloadAppleDistributionCertificateResult,\n UploadAppleDistributionCertificateBody,\n} from \"../domain/apple-distribution-certificate\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AppleDistributionCertificatesGroup extends HttpApiGroup.make(\n \"appleDistributionCertificates\",\n)\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/distribution-certificates\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AppleDistributionCertificate) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Apple distribution certificates\",\n description: \"List uploaded Apple distribution certificates for the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/distribution-certificates\")\n .setPayload(UploadAppleDistributionCertificateBody)\n .addSuccess(AppleDistributionCertificate, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload distribution certificate\",\n description:\n \"Upload a .p12 distribution certificate; auto-derives the Apple team from the provided identifier\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/distribution-certificates/${idParam}`\n .addSuccess(DeleteAppleDistributionCertificateResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete distribution certificate\",\n description: \"Remove a distribution certificate from storage\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"download\")`/api/apple/distribution-certificates/${idParam}/download`\n .addSuccess(DownloadAppleDistributionCertificateResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Download distribution certificate\",\n description: \"Fetch the decrypted .p12 + password for local use (audit-logged)\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Distribution Certificates\",\n description: \"Manage .p12 distribution certificates\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const DistributionType = Schema.Literal(\"APP_STORE\", \"AD_HOC\", \"ENTERPRISE\", \"DEVELOPMENT\");\nexport type DistributionTypeValue = typeof DistributionType.Type;\n\nexport const BundleIdentifier = Schema.String.pipe(\n Schema.pattern(/^[A-Za-z0-9.\\-_]{1,200}$/u, {\n message: () => \"Bundle identifier must be reverse-domain style (letters, digits, dot, dash)\",\n }),\n);\n\nexport class AppleProvisioningProfile extends Schema.Class<AppleProvisioningProfile>(\n \"AppleProvisioningProfile\",\n)({\n id: Id,\n organizationId: Id,\n appleTeamId: Id,\n appleDistributionCertificateId: Schema.NullOr(Id),\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n developerPortalIdentifier: Schema.NullOr(Schema.String),\n profileName: Schema.NullOr(Schema.String),\n validUntil: Schema.NullOr(DateTimeString),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAppleProvisioningProfileBody = Schema.Struct({\n profileBase64: Schema.String.pipe(Schema.minLength(1)),\n appleDistributionCertificateId: Schema.optional(Id),\n deviceRosterHash: Schema.optional(Schema.String),\n isManaged: Schema.optional(Schema.Boolean),\n});\n\nexport const DeleteAppleProvisioningProfileResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DownloadAppleProvisioningProfileResult = Schema.Struct({\n id: Id,\n profileBase64: Schema.String,\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n profileName: Schema.NullOr(Schema.String),\n developerPortalIdentifier: Schema.NullOr(Schema.String),\n});\n\nexport const ListAppleProvisioningProfilesParams = Schema.Struct({\n bundleIdentifier: Schema.optional(BundleIdentifier),\n distributionType: Schema.optional(DistributionType),\n appleTeamId: Schema.optional(Id),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AppleProvisioningProfile,\n DeleteAppleProvisioningProfileResult,\n DownloadAppleProvisioningProfileResult,\n ListAppleProvisioningProfilesParams,\n UploadAppleProvisioningProfileBody,\n} from \"../domain/apple-provisioning-profile\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AppleProvisioningProfilesGroup extends HttpApiGroup.make(\"appleProvisioningProfiles\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/provisioning-profiles\")\n .setUrlParams(ListAppleProvisioningProfilesParams)\n .addSuccess(Schema.Struct({ items: Schema.Array(AppleProvisioningProfile) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List provisioning profiles\",\n description: \"List stored provisioning profiles, optionally filtered by bundle + team\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/provisioning-profiles\")\n .setPayload(UploadAppleProvisioningProfileBody)\n .addSuccess(AppleProvisioningProfile, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload provisioning profile\",\n description:\n \"Upload an existing or freshly generated .mobileprovision; auto-parses the embedded plist\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/provisioning-profiles/${idParam}`\n .addSuccess(DeleteAppleProvisioningProfileResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete provisioning profile\",\n description: \"Remove a stored provisioning profile\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"download\")`/api/apple/provisioning-profiles/${idParam}/download`\n .addSuccess(DownloadAppleProvisioningProfileResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Download provisioning profile\",\n description: \"Fetch the decoded .mobileprovision for local use (audit-logged)\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Provisioning Profiles\",\n description: \"Manage .mobileprovision profiles (upload or generate)\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { AppleTeamIdentifier } from \"./apple-team\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport const ApplePushKeyId = Schema.String.pipe(\n Schema.pattern(/^[A-Z0-9]{10}$/u, {\n message: () => \"Push Key ID must be 10 uppercase alphanumeric characters\",\n }),\n);\n\nexport class ApplePushKey extends Schema.Class<ApplePushKey>(\"ApplePushKey\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Id,\n keyId: Schema.String,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadApplePushKeyBody = Schema.Struct({\n keyId: ApplePushKeyId,\n p8Pem: Schema.String.pipe(Schema.minLength(1)),\n appleTeamIdentifier: AppleTeamIdentifier,\n appleTeamName: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n appleTeamType: Schema.optional(Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\")),\n});\n\nexport const DeleteApplePushKeyResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DownloadApplePushKeyResult = Schema.Struct({\n id: Id,\n p8Pem: Schema.String,\n keyId: Schema.String,\n appleTeamIdentifier: AppleTeamIdentifier,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n ApplePushKey,\n DeleteApplePushKeyResult,\n DownloadApplePushKeyResult,\n UploadApplePushKeyBody,\n} from \"../domain/apple-push-key\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class ApplePushKeysGroup extends HttpApiGroup.make(\"applePushKeys\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/push-keys\")\n .addSuccess(Schema.Struct({ items: Schema.Array(ApplePushKey) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Apple push keys\",\n description: \"List APNs push keys for the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/push-keys\")\n .setPayload(UploadApplePushKeyBody)\n .addSuccess(ApplePushKey, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload push key\",\n description: \"Upload an APNs .p8 push notification key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/push-keys/${idParam}`\n .addSuccess(DeleteApplePushKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete push key\",\n description: \"Remove a stored APNs push key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"download\")`/api/apple/push-keys/${idParam}/download`\n .addSuccess(DownloadApplePushKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Download push key\",\n description: \"Fetch the decrypted .p8 push key for local use (audit-logged)\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Push Keys\",\n description: \"Manage APNs push notification keys\",\n }),\n ) {}\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { AppleTeam } from \"../domain/apple-team\";\n\nexport class AppleTeamsGroup extends HttpApiGroup.make(\"appleTeams\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple-teams\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AppleTeam) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Apple teams\",\n description:\n \"List Apple developer teams derived from uploaded artifacts (certs, push keys, ASC keys)\",\n }),\n ),\n )\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Apple Teams\",\n description: \"Read-only view of Apple teams auto-created from uploaded credentials\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { AppleTeamIdentifier } from \"./apple-team\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AscApiKeyId = Schema.String.pipe(\n Schema.pattern(/^[A-Z0-9]{10}$/u, {\n message: () => \"ASC API Key ID must be 10 uppercase alphanumeric characters\",\n }),\n);\n\nexport const IssuerId = Schema.String.pipe(\n Schema.pattern(/^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$/u, {\n message: () => \"Issuer ID must be a UUID (8-4-4-4-12 hex)\",\n }),\n);\n\nexport class AscApiKey extends Schema.Class<AscApiKey>(\"AscApiKey\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.NullOr(Id),\n keyId: Schema.String,\n name: Schema.String,\n roles: Schema.Array(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadAscApiKeyBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n keyId: AscApiKeyId,\n issuerId: IssuerId,\n p8Pem: Schema.String.pipe(Schema.minLength(1)),\n appleTeamIdentifier: Schema.optional(AppleTeamIdentifier),\n appleTeamName: Schema.optional(Schema.String.pipe(Schema.maxLength(200))),\n appleTeamType: Schema.optional(Schema.Literal(\"IN_HOUSE\", \"COMPANY_ORGANIZATION\", \"INDIVIDUAL\")),\n roles: Schema.optional(Schema.Array(Schema.String)),\n});\n\nexport const DeleteAscApiKeyResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DownloadAscApiKeyResult = Schema.Struct({\n id: Id,\n name: Schema.String,\n keyId: AscApiKeyId,\n issuerId: IssuerId,\n p8Pem: Schema.String,\n appleTeamIdentifier: Schema.NullOr(AppleTeamIdentifier),\n});\n\nexport class AscApiKeyCredentials extends Schema.Class<AscApiKeyCredentials>(\n \"AscApiKeyCredentials\",\n)({\n ascApiKeyId: Id,\n keyId: AscApiKeyId,\n issuerId: IssuerId,\n p8Pem: Schema.String,\n appleTeamIdentifier: Schema.NullOr(AppleTeamIdentifier),\n}) {}\n\nexport const SyncedDeviceSummary = Schema.Struct({\n id: Id,\n identifier: Schema.String,\n name: Schema.String,\n deviceClass: Schema.Literal(\"IPHONE\", \"IPAD\", \"MAC\", \"UNKNOWN\"),\n});\n\nexport const SyncDevicesResult = Schema.Struct({\n pulled: Schema.Number,\n pushed: Schema.Number,\n skipped: Schema.Number,\n devices: Schema.Array(SyncedDeviceSummary),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n AscApiKey,\n AscApiKeyCredentials,\n DeleteAscApiKeyResult,\n SyncDevicesResult,\n UploadAscApiKeyBody,\n} from \"../domain/asc-api-key\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class AscApiKeysGroup extends HttpApiGroup.make(\"ascApiKeys\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/apple/asc-api-keys\")\n .addSuccess(Schema.Struct({ items: Schema.Array(AscApiKey) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List App Store Connect API keys\",\n description: \"List stored ASC API keys for the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/apple/asc-api-keys\")\n .setPayload(UploadAscApiKeyBody)\n .addSuccess(AscApiKey, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload ASC API key\",\n description: \"Upload an App Store Connect API key (.p8 + issuer)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/apple/asc-api-keys/${idParam}`\n .addSuccess(DeleteAscApiKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete ASC API key\",\n description: \"Remove a stored ASC API key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"syncDevices\")`/api/apple/asc-api-keys/${idParam}/sync-devices`\n .addSuccess(SyncDevicesResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Sync devices via ASC API key\",\n description:\n \"Pull registered devices from Apple Developer Portal for this key's team; push local devices that aren't yet registered\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"getCredentials\")`/api/apple/asc-api-keys/${idParam}/credentials`\n .addSuccess(AscApiKeyCredentials)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get ASC API key credentials\",\n description:\n \"Return the decrypted .p8 PEM, keyId, issuerId, and Apple team for direct App Store Connect API calls from the CLI\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"App Store Connect API Keys\",\n description: \"Manage ASC API keys used for device + profile sync\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, UploadHeaders } from \"./common\";\n\nexport class Asset extends Schema.Class<Asset>(\"Asset\")({\n hash: Schema.String,\n contentType: Schema.String,\n fileExt: Schema.String,\n byteSize: Schema.Number,\n r2Key: Schema.String,\n createdAt: DateTimeString,\n}) {}\n\nexport const AssetUploadBody = Schema.Struct({\n projectId: Id,\n assets: Schema.Array(\n Schema.Struct({\n hash: Schema.String,\n contentType: Schema.String,\n fileExt: Schema.String,\n contentChecksum: Schema.optional(Schema.String),\n }),\n ),\n});\n\nexport const AssetUploadResult = Schema.Struct({\n uploaded: Schema.Array(\n Schema.Struct({\n hash: Schema.String,\n uploadMode: Schema.Literal(\"single\"),\n uploadUrl: Schema.String,\n uploadExpiresAt: DateTimeString,\n uploadHeaders: UploadHeaders,\n }),\n ),\n deduplicated: Schema.Array(Schema.String),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { Asset, AssetUploadBody, AssetUploadResult } from \"../domain/asset\";\nimport { BadRequest } from \"../domain/errors\";\n\nconst hashParam = HttpApiSchema.param(\"hash\", Schema.String);\n\nexport class AssetsGroup extends HttpApiGroup.make(\"assets\")\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/assets/upload\")\n .setPayload(AssetUploadBody)\n .addSuccess(AssetUploadResult, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload assets\",\n description: \"Upload asset files to R2 storage (deduplicated by content hash)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"finalize\")`/api/assets/${hashParam}/finalize`\n .addSuccess(Asset)\n .annotateContext(\n OpenApi.annotations({\n title: \"Finalize asset upload\",\n description: \"Verify a directly uploaded asset in R2 and mark it available for updates\",\n }),\n ),\n )\n .addError(BadRequest)\n .addError(NotFound)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Assets\",\n description: \"Asset upload endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const AuditLogResourceType = Schema.Literal(\n \"project\",\n \"branch\",\n \"channel\",\n \"update\",\n \"build\",\n \"appleCredential\",\n \"androidCredential\",\n \"iosBundleConfiguration\",\n \"envVar\",\n \"device\",\n \"webhook\",\n);\n\nexport const AuditLogSource = Schema.Literal(\"session\", \"api-key\");\n\nexport class AuditLog extends Schema.Class<AuditLog>(\"AuditLog\")({\n id: Id,\n organizationId: Id,\n actorId: Schema.NullOr(Schema.String),\n actorEmail: Schema.String,\n action: Schema.String,\n resourceType: AuditLogResourceType,\n resourceId: Schema.NullOr(Schema.String),\n metadata: Schema.NullOr(Schema.String),\n source: AuditLogSource,\n createdAt: DateTimeString,\n}) {}\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { AuditLog } from \"../domain/audit-log\";\nimport { CursorPaginationParams, cursorPageResult } from \"../domain/common\";\n\nexport class AuditLogsGroup extends HttpApiGroup.make(\"audit-logs\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/audit-logs\")\n .setUrlParams(\n Schema.Struct({\n projectId: Schema.optional(Schema.String),\n resourceType: Schema.optional(Schema.String),\n from: Schema.optional(Schema.String),\n to: Schema.optional(Schema.String),\n ...CursorPaginationParams.fields,\n }),\n )\n .addSuccess(cursorPageResult(AuditLog))\n .annotateContext(\n OpenApi.annotations({\n title: \"List audit logs\",\n description: \"List audit log entries with optional filters\",\n }),\n ),\n )\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Audit Logs\",\n description: \"View audit trail for organization actions\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams } from \"./common\";\n\nexport class Branch extends Schema.Class<Branch>(\"Branch\")({\n id: Id,\n projectId: Id,\n name: Schema.String,\n createdAt: DateTimeString,\n updateCount: Schema.Number,\n}) {}\n\nexport const BranchSortColumn = Schema.Literal(\"name\", \"createdAt\", \"updateCount\");\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-createdAt` (desc).\n */\nexport const BranchSort = Schema.Union(\n BranchSortColumn,\n Schema.TemplateLiteral(\"-\", BranchSortColumn),\n);\n\nexport const ListBranchesParams = Schema.Struct({\n projectId: Id,\n ...PaginationParams.fields,\n sort: Schema.optional(BranchSort),\n});\n\nexport const CreateBranchBody = Schema.Struct({\n projectId: Id,\n name: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const UpdateBranchBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const DeleteBranchResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n Branch,\n CreateBranchBody,\n DeleteBranchResult,\n ListBranchesParams,\n UpdateBranchBody,\n} from \"../domain/branch\";\nimport { Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class BranchesGroup extends HttpApiGroup.make(\"branches\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/branches\")\n .setPayload(CreateBranchBody)\n .addSuccess(Branch, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create branch\",\n description: \"Create a new branch within a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/branches\")\n .setUrlParams(ListBranchesParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Branch),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List branches\",\n description: \"List all branches for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/branches/${idParam}`.addSuccess(Branch).annotateContext(\n OpenApi.annotations({\n title: \"Get branch\",\n description: \"Fetch a single branch by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"rename\")`/api/branches/${idParam}`\n .setPayload(UpdateBranchBody)\n .addSuccess(Branch)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Rename branch\",\n description: \"Rename a branch (channels and updates are unaffected)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/branches/${idParam}`\n .addSuccess(DeleteBranchResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete branch\",\n description: \"Delete a branch and all its updates\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Branches\",\n description: \"Branch management endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { AndroidPackageName } from \"./android-application-identifier\";\nimport { BundleIdentifier, DistributionType } from \"./apple-provisioning-profile\";\n\nexport const ResolveBuildCredentialsIosBody = Schema.Struct({\n platform: Schema.Literal(\"ios\"),\n bundleIdentifier: BundleIdentifier,\n distributionType: DistributionType,\n});\n\nexport const ResolveBuildCredentialsAndroidBody = Schema.Struct({\n platform: Schema.Literal(\"android\"),\n applicationIdentifier: AndroidPackageName,\n});\n\nexport const ResolveBuildCredentialsBody = Schema.Union(\n ResolveBuildCredentialsIosBody,\n ResolveBuildCredentialsAndroidBody,\n);\n\nexport const IosBuildDistributionCertificate = Schema.Struct({\n p12Base64: Schema.String,\n p12Password: Schema.String,\n});\n\nexport const IosBuildProvisioningProfile = Schema.Struct({\n mobileprovisionBase64: Schema.String,\n uuid: Schema.NullOr(Schema.String),\n name: Schema.NullOr(Schema.String),\n teamId: Schema.String,\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n});\n\nexport const IosBuildPushKey = Schema.Struct({\n p8Base64: Schema.String,\n keyId: Schema.String,\n teamId: Schema.String,\n});\n\nexport const ResolveBuildCredentialsIosResult = Schema.Struct({\n platform: Schema.Literal(\"ios\"),\n distributionCertificate: IosBuildDistributionCertificate,\n provisioningProfile: IosBuildProvisioningProfile,\n pushKey: Schema.NullOr(IosBuildPushKey),\n profileStale: Schema.Boolean,\n currentDeviceRosterHash: Schema.NullOr(Schema.String),\n});\n\nexport const AndroidBuildKeystore = Schema.Struct({\n keystoreBase64: Schema.String,\n storePassword: Schema.String,\n keyAlias: Schema.String,\n keyPassword: Schema.String,\n});\n\nexport const ResolveBuildCredentialsAndroidResult = Schema.Struct({\n platform: Schema.Literal(\"android\"),\n keystore: AndroidBuildKeystore,\n});\n\nexport const ResolveBuildCredentialsResult = Schema.Union(\n ResolveBuildCredentialsIosResult,\n ResolveBuildCredentialsAndroidResult,\n);\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n ResolveBuildCredentialsBody,\n ResolveBuildCredentialsResult,\n} from \"../domain/build-credentials\";\nimport { BadRequest } from \"../domain/errors\";\n\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class BuildCredentialsGroup extends HttpApiGroup.make(\"buildCredentials\")\n .add(\n HttpApiEndpoint.post(\"resolve\")`/api/projects/${projectIdParam}/build-credentials/resolve`\n .setPayload(ResolveBuildCredentialsBody)\n .addSuccess(ResolveBuildCredentialsResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Resolve build credentials\",\n description:\n \"Return decrypted signing assets for a project build. Regenerates the iOS provisioning profile via Apple ASC when the registered device roster has changed since the profile was last generated.\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Build Credentials\",\n description: \"Materialize signing assets needed by a CLI build run\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams, Platform, UploadHeaders } from \"./common\";\n\nexport const Distribution = Schema.Literal(\n \"app-store\",\n \"ad-hoc\",\n \"development\",\n \"enterprise\",\n \"simulator\",\n \"play-store\",\n \"direct\",\n);\n\nexport const ArtifactFormat = Schema.Literal(\"ipa\", \"apk\", \"aab\", \"tar.gz\");\nconst Sha256Hex = Schema.String.pipe(Schema.pattern(/^[a-fA-F0-9]{64}$/u), Schema.maxLength(64));\n\nconst CreateBuildCommonFields = {\n projectId: Id,\n profile: Schema.optional(Schema.String),\n runtimeVersion: Schema.optional(Schema.String),\n appVersion: Schema.optional(Schema.String),\n buildNumber: Schema.optional(Schema.String),\n bundleId: Schema.optional(Schema.String),\n gitRef: Schema.optional(Schema.String),\n gitCommit: Schema.optional(Schema.String),\n message: Schema.optional(Schema.String),\n metadata: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n sha256: Sha256Hex,\n byteSize: Schema.Number.pipe(Schema.nonNegative()),\n} as const;\n\nexport class Build extends Schema.Class<Build>(\"Build\")({\n id: Id,\n projectId: Id,\n platform: Platform,\n profile: Schema.String,\n distribution: Distribution,\n runtimeVersion: Schema.NullOr(Schema.String),\n appVersion: Schema.NullOr(Schema.String),\n buildNumber: Schema.NullOr(Schema.String),\n bundleId: Schema.NullOr(Schema.String),\n gitRef: Schema.NullOr(Schema.String),\n gitCommit: Schema.NullOr(Schema.String),\n message: Schema.NullOr(Schema.String),\n metadataJson: Schema.String,\n createdAt: DateTimeString,\n}) {}\n\nexport class BuildArtifact extends Schema.Class<BuildArtifact>(\"BuildArtifact\")({\n buildId: Id,\n r2Key: Schema.String,\n format: ArtifactFormat,\n contentType: Schema.String,\n byteSize: Schema.Number,\n sha256: Schema.String,\n createdAt: DateTimeString,\n}) {}\n\nexport class BuildWithArtifact extends Build.extend<BuildWithArtifact>(\"BuildWithArtifact\")({\n artifact: Schema.NullOr(\n Schema.Struct({\n r2Key: Schema.String,\n format: ArtifactFormat,\n contentType: Schema.String,\n byteSize: Schema.Number,\n sha256: Schema.String,\n }),\n ),\n}) {}\n\nexport const CreateBuildBody = Schema.Union(\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"ios\"),\n distribution: Schema.Literal(\"app-store\", \"ad-hoc\", \"development\", \"enterprise\"),\n artifactFormat: Schema.Literal(\"ipa\"),\n }),\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"ios\"),\n distribution: Schema.Literal(\"simulator\"),\n artifactFormat: Schema.Literal(\"tar.gz\"),\n }),\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"android\"),\n distribution: Schema.Literal(\"play-store\"),\n artifactFormat: Schema.Literal(\"aab\"),\n }),\n Schema.Struct({\n ...CreateBuildCommonFields,\n platform: Schema.Literal(\"android\"),\n distribution: Schema.Literal(\"direct\"),\n artifactFormat: Schema.Literal(\"apk\"),\n }),\n);\n\nexport const BuildSortColumn = Schema.Literal(\n \"createdAt\",\n \"platform\",\n \"distribution\",\n \"runtimeVersion\",\n \"appVersion\",\n);\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `runtimeVersion` (asc), `-createdAt` (desc).\n */\nexport const BuildSort = Schema.Union(\n BuildSortColumn,\n Schema.TemplateLiteral(\"-\", BuildSortColumn),\n);\n\nexport const ListBuildsParams = Schema.Struct({\n projectId: Id,\n platform: Schema.optional(Platform),\n profile: Schema.optional(Schema.String),\n runtimeVersion: Schema.optional(Schema.String),\n distribution: Schema.optional(Distribution),\n ...PaginationParams.fields,\n sort: Schema.optional(BuildSort),\n});\n\nexport const CompleteBuildBody = Schema.Struct({\n sha256: Sha256Hex,\n byteSize: Schema.Number.pipe(Schema.nonNegative()),\n});\n\nexport const ReserveBuildResult = Schema.Struct({\n id: Id,\n uploadMode: Schema.Literal(\"single\"),\n uploadUrl: Schema.String,\n uploadExpiresAt: DateTimeString,\n uploadHeaders: UploadHeaders,\n});\n\nexport const DeleteBuildResult = Schema.Struct({\n deleted: Schema.Number,\n});\n\nexport const InstallLinkResult = Schema.Struct({\n token: Schema.String,\n expires: Schema.Number,\n artifactUrl: Schema.String,\n installUrl: Schema.NullOr(Schema.String),\n});\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, Platform } from \"./common\";\n\n// Per-runtime channel status — varies per (platform, runtimeVersion).\nexport class BuildCompatibilityChannel extends Schema.Class<BuildCompatibilityChannel>(\n \"BuildCompatibilityChannel\",\n)({\n channelId: Id,\n updateCount: Schema.Number,\n latestUpdateId: Schema.NullOr(Id),\n latestUpdateMessage: Schema.NullOr(Schema.String),\n latestUpdateCreatedAt: Schema.NullOr(DateTimeString),\n}) {}\n\n// Channel-level metadata that does not depend on a specific build's runtime.\nexport class CompatibilityChannelInfo extends Schema.Class<CompatibilityChannelInfo>(\n \"CompatibilityChannelInfo\",\n)({\n channelId: Id,\n channelName: Schema.String,\n isPaused: Schema.Boolean,\n rolloutActive: Schema.Boolean,\n}) {}\n\nexport class MissingRuntimeVersionBuild extends Schema.Class<MissingRuntimeVersionBuild>(\n \"MissingRuntimeVersionBuild\",\n)({\n channelId: Id,\n channelName: Schema.String,\n platform: Platform,\n runtimeVersion: Schema.String,\n updateCount: Schema.Number,\n latestUpdateId: Id,\n latestUpdateMessage: Schema.String,\n latestUpdateCreatedAt: DateTimeString,\n rolloutActive: Schema.Boolean,\n}) {}\n\nexport const BuildCompatibilityMatrixResult = Schema.Struct({\n channels: Schema.Array(CompatibilityChannelInfo),\n channelStatusByKey: Schema.Record({\n key: Schema.String,\n value: Schema.Array(BuildCompatibilityChannel),\n }),\n missingRuntimeVersions: Schema.Array(MissingRuntimeVersionBuild),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n BuildWithArtifact,\n CompleteBuildBody,\n CreateBuildBody,\n DeleteBuildResult,\n InstallLinkResult,\n ListBuildsParams,\n ReserveBuildResult,\n} from \"../domain/build\";\nimport { BuildCompatibilityMatrixResult } from \"../domain/build-compatibility\";\nimport { Id } from \"../domain/common\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class BuildsGroup extends HttpApiGroup.make(\"builds\")\n .add(\n HttpApiEndpoint.post(\"reserve\", \"/api/builds\")\n .setPayload(CreateBuildBody)\n .addSuccess(ReserveBuildResult, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Reserve build\",\n description: \"Reserve a build ID and get a presigned upload URL\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"complete\")`/api/builds/${idParam}/complete`\n .setPayload(CompleteBuildBody)\n .addSuccess(BuildWithArtifact)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Complete build\",\n description: \"Finalize a build after artifact upload\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/builds\")\n .setUrlParams(ListBuildsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(BuildWithArtifact),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List builds\",\n description: \"List builds for a project with optional filters\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"compatibilityMatrix\", \"/api/builds/compatibility-matrix\")\n .setUrlParams(\n Schema.Struct({\n projectId: Id,\n }),\n )\n .addSuccess(BuildCompatibilityMatrixResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Build compatibility matrix\",\n description: \"List build-to-channel OTA compatibility for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/builds/${idParam}`\n .addSuccess(BuildWithArtifact)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get build\",\n description: \"Get a build by ID with artifact details\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/builds/${idParam}`\n .addSuccess(DeleteBuildResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete build\",\n description: \"Delete a build and its artifact from storage\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"getInstallLink\")`/api/builds/${idParam}/install-link`\n .addSuccess(InstallLinkResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get install link\",\n description: \"Generate a signed install link for a build artifact\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Forbidden)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Builds\",\n description: \"Build artifact upload, tracking, and download endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams } from \"./common\";\n\nexport class Channel extends Schema.Class<Channel>(\"Channel\")({\n id: Id,\n projectId: Id,\n name: Schema.String,\n branchId: Id,\n branchMappingJson: Schema.NullOr(Schema.String),\n cacheVersion: Schema.Number,\n isPaused: Schema.Boolean,\n createdAt: DateTimeString,\n}) {}\n\nexport const ChannelSortColumn = Schema.Literal(\"name\", \"createdAt\");\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-createdAt` (desc).\n */\nexport const ChannelSort = Schema.Union(\n ChannelSortColumn,\n Schema.TemplateLiteral(\"-\", ChannelSortColumn),\n);\n\nexport const ListChannelsParams = Schema.Struct({\n projectId: Id,\n ...PaginationParams.fields,\n sort: Schema.optional(ChannelSort),\n});\n\nexport const CreateChannelBody = Schema.Struct({\n projectId: Id,\n name: Schema.String.pipe(Schema.minLength(1)),\n branchId: Id,\n});\n\nexport const UpdateChannelBody = Schema.Struct({\n branchId: Id,\n});\n\nexport const CreateBranchRolloutBody = Schema.Struct({\n newBranchId: Id,\n percentage: Schema.Number.pipe(Schema.int(), Schema.between(1, 100)),\n});\n\nexport const DeleteChannelResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n Channel,\n CreateBranchRolloutBody,\n CreateChannelBody,\n DeleteChannelResult,\n ListChannelsParams,\n UpdateChannelBody,\n} from \"../domain/channel\";\nimport { UpdateRolloutBody } from \"../domain/common\";\nimport { Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class ChannelsGroup extends HttpApiGroup.make(\"channels\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/channels\")\n .setPayload(CreateChannelBody)\n .addSuccess(Channel, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create channel\",\n description: \"Create a new channel linked to a branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/channels/${idParam}`\n .setPayload(UpdateChannelBody)\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update channel\",\n description: \"Relink channel to a different branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/channels\")\n .setUrlParams(ListChannelsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Channel),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List channels\",\n description: \"List all channels for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"pause\")`/api/channels/${idParam}/pause`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Pause channel\",\n description: \"Pause a channel — manifest requests return 204 No Content\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"resume\")`/api/channels/${idParam}/resume`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Resume channel\",\n description: \"Resume a paused channel\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"createBranchRollout\")`/api/channels/${idParam}/rollout`\n .setPayload(CreateBranchRolloutBody)\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Create branch rollout\",\n description: \"Start a gradual rollout to a new branch on this channel\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"updateBranchRollout\")`/api/channels/${idParam}/rollout`\n .setPayload(UpdateRolloutBody)\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update branch rollout\",\n description: \"Change the rollout percentage for a branch rollout\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"completeBranchRollout\")`/api/channels/${idParam}/rollout/complete`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Complete branch rollout\",\n description: \"Finalize the rollout — promote the new branch to 100%\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"revertBranchRollout\")`/api/channels/${idParam}/rollout/revert`\n .addSuccess(Channel)\n .annotateContext(\n OpenApi.annotations({\n title: \"Revert branch rollout\",\n description: \"Revert the rollout — restore the original branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/channels/${idParam}`\n .addSuccess(DeleteChannelResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete channel\",\n description: \"Delete a channel\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Channels\",\n description: \"Channel management endpoints including pause/resume and branch rollouts\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams } from \"./common\";\n\nexport const DeviceClass = Schema.Literal(\"IPHONE\", \"IPAD\", \"MAC\", \"UNKNOWN\");\nexport type DeviceClassValue = typeof DeviceClass.Type;\n\nconst IDENTIFIER_PATTERN =\n /^(?:[A-Fa-f0-9]{40}|[A-Fa-f0-9]{8}-[A-Fa-f0-9]{16}|[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12})$/u;\n\nexport const DeviceIdentifier = Schema.String.pipe(\n Schema.pattern(IDENTIFIER_PATTERN, {\n message: () =>\n \"Identifier must be an Apple UDID: 40 hex chars, 8-16 hex, or UUID (8-4-4-4-12 hex)\",\n }),\n);\n\nexport class Device extends Schema.Class<Device>(\"Device\")({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.NullOr(Id),\n identifier: Schema.String,\n name: Schema.String,\n model: Schema.NullOr(Schema.String),\n deviceClass: DeviceClass,\n enabled: Schema.Boolean,\n appleDevicePortalId: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const RegisterDeviceBody = Schema.Struct({\n identifier: DeviceIdentifier,\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n deviceClass: DeviceClass,\n model: Schema.optional(Schema.String.pipe(Schema.maxLength(120))),\n appleTeamId: Schema.optional(Id),\n});\n\nexport const UpdateDeviceBody = Schema.Struct({\n name: Schema.optional(Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120))),\n enabled: Schema.optional(Schema.Boolean),\n appleTeamId: Schema.optional(Schema.NullOr(Id)),\n});\n\nexport const DeleteDeviceResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DeviceSortColumn = Schema.Literal(\"name\", \"createdAt\", \"deviceClass\");\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-createdAt` (desc).\n */\nexport const DeviceSort = Schema.Union(\n DeviceSortColumn,\n Schema.TemplateLiteral(\"-\", DeviceSortColumn),\n);\n\nexport const ListDevicesParams = Schema.Struct({\n ...PaginationParams.fields,\n deviceClass: Schema.optional(DeviceClass),\n appleTeamId: Schema.optional(Id),\n query: Schema.optional(Schema.String),\n sort: Schema.optional(DeviceSort),\n});\n\nexport class DeviceRegistrationRequest extends Schema.Class<DeviceRegistrationRequest>(\n \"DeviceRegistrationRequest\",\n)({\n id: Id,\n organizationId: Id,\n appleTeamId: Schema.NullOr(Id),\n deviceNameHint: Schema.NullOr(Schema.String),\n deviceClassHint: Schema.NullOr(DeviceClass),\n url: Schema.String,\n expiresAt: DateTimeString,\n consumedAt: Schema.NullOr(DateTimeString),\n consumedDeviceId: Schema.NullOr(Id),\n createdAt: DateTimeString,\n}) {}\n\nexport const CreateRegistrationRequestBody = Schema.Struct({\n deviceNameHint: Schema.optional(Schema.String.pipe(Schema.maxLength(120))),\n deviceClassHint: Schema.optional(DeviceClass),\n ttlHours: Schema.optional(Schema.Number.pipe(Schema.int(), Schema.between(1, 168))),\n appleTeamId: Schema.optional(Id),\n});\n\nexport const ListRegistrationRequestsParams = Schema.Struct({\n active: Schema.optional(Schema.Literal(\"true\", \"false\")),\n appleTeamId: Schema.optional(Id),\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport {\n CreateRegistrationRequestBody,\n DeleteDeviceResult,\n Device,\n DeviceRegistrationRequest,\n ListDevicesParams,\n ListRegistrationRequestsParams,\n RegisterDeviceBody,\n UpdateDeviceBody,\n} from \"../domain/device\";\nimport { Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class DevicesGroup extends HttpApiGroup.make(\"devices\")\n .add(\n HttpApiEndpoint.post(\"register\", \"/api/devices\")\n .setPayload(RegisterDeviceBody)\n .addSuccess(Device, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Register device\",\n description: \"Register an Apple device UDID in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/devices\")\n .setUrlParams(ListDevicesParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Device),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List devices\",\n description: \"List registered Apple devices in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/devices/${idParam}`.addSuccess(Device).annotateContext(\n OpenApi.annotations({\n title: \"Get device\",\n description: \"Get a single device by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/devices/${idParam}`\n .setPayload(UpdateDeviceBody)\n .addSuccess(Device)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update device\",\n description: \"Rename a device or toggle its enabled state\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/devices/${idParam}`\n .addSuccess(DeleteDeviceResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete device\",\n description: \"Remove a registered device from the organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"createRegistrationRequest\", \"/api/devices/registration-requests\")\n .setPayload(CreateRegistrationRequestBody)\n .addSuccess(DeviceRegistrationRequest, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create device registration request\",\n description:\n \"Generate a URL + QR code for self-service device enrollment via Safari on iOS\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"listRegistrationRequests\", \"/api/devices/registration-requests\")\n .setUrlParams(ListRegistrationRequestsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(DeviceRegistrationRequest),\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List device registration requests\",\n description: \"List outstanding device registration invites\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Devices\",\n description: \"Apple device management for ad-hoc builds\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const EnvVarVisibility = Schema.Literal(\"plaintext\", \"sensitive\", \"secret\");\n\nexport class EnvVar extends Schema.Class<EnvVar>(\"EnvVar\")({\n id: Id,\n organizationId: Id,\n projectId: Id,\n environment: Schema.String,\n key: Schema.String,\n visibility: EnvVarVisibility,\n value: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\n// Key validation: uppercase letters, digits, underscores. Must start with letter.\nconst EnvVarKey = Schema.String.pipe(Schema.pattern(/^[A-Z][A-Z0-9_]*$/u), Schema.maxLength(256));\n\nconst EnvVarValue = Schema.String.pipe(Schema.maxLength(32_768));\n\nconst EnvVarEnvironment = Schema.String.pipe(Schema.minLength(1), Schema.maxLength(64));\n\nexport const CreateEnvVarBody = Schema.Struct({\n projectId: Id,\n environment: EnvVarEnvironment,\n key: EnvVarKey,\n value: EnvVarValue,\n visibility: EnvVarVisibility,\n});\n\nexport const UpdateEnvVarBody = Schema.Struct({\n value: Schema.optional(EnvVarValue),\n visibility: Schema.optional(EnvVarVisibility),\n});\n\nexport const BulkImportEnvVarsBody = Schema.Struct({\n projectId: Id,\n environment: EnvVarEnvironment,\n content: Schema.String.pipe(Schema.maxLength(4_000_000)),\n visibility: EnvVarVisibility,\n});\n\nexport const BulkImportResult = Schema.Struct({\n created: Schema.Number,\n updated: Schema.Number,\n skipped: Schema.Number,\n});\n\nexport const DeleteEnvVarResult = Schema.Struct({\n id: Id,\n});\n\nexport const EnvVarExportItem = Schema.Struct({\n key: Schema.String,\n value: Schema.String,\n visibility: EnvVarVisibility,\n});\n\nexport const EnvVarExportResult = Schema.Struct({\n items: Schema.Array(EnvVarExportItem),\n environment: Schema.String,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { Id, PaginationParams } from \"../domain/common\";\nimport {\n BulkImportEnvVarsBody,\n BulkImportResult,\n CreateEnvVarBody,\n DeleteEnvVarResult,\n EnvVar,\n EnvVarExportResult,\n UpdateEnvVarBody,\n} from \"../domain/env-var\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class EnvVarsGroup extends HttpApiGroup.make(\"env-vars\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/env-vars\")\n .setPayload(CreateEnvVarBody)\n .addSuccess(EnvVar, { status: 201 })\n .addError(BadRequest)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Create environment variable\",\n description: \"Create a new environment variable for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/env-vars\")\n .setUrlParams(\n Schema.Struct({\n projectId: Id,\n environment: Schema.optional(Schema.String),\n ...PaginationParams.fields,\n }),\n )\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(EnvVar),\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List environment variables\",\n description: \"List environment variables with optional filters\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/env-vars/${idParam}`.addSuccess(EnvVar).annotateContext(\n OpenApi.annotations({\n title: \"Get environment variable\",\n description: \"Get an environment variable by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/env-vars/${idParam}`\n .setPayload(UpdateEnvVarBody)\n .addSuccess(EnvVar)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update environment variable\",\n description: \"Update an environment variable's value or visibility\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/env-vars/${idParam}`\n .addSuccess(DeleteEnvVarResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete environment variable\",\n description: \"Delete an environment variable\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"bulkImport\", \"/api/env-vars/bulk-import\")\n .setPayload(BulkImportEnvVarsBody)\n .addSuccess(BulkImportResult)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Bulk import environment variables\",\n description:\n \"Import environment variables from a dotenv-formatted string. Supports KEY=VALUE format with # comments. Quoted values (single/double) are unquoted. Multiline values are not supported.\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"export\", \"/api/env-vars/export\")\n .setUrlParams(\n Schema.Struct({\n projectId: Id,\n environment: Schema.String,\n }),\n )\n .addSuccess(EnvVarExportResult)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Export environment variables\",\n description: \"Export environment variables for a project environment\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Forbidden)\n .addError(BadRequest)\n .annotateContext(\n OpenApi.annotations({\n title: \"Environment Variables\",\n description: \"Manage environment variables for project builds and deployments\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport class GoogleServiceAccountKey extends Schema.Class<GoogleServiceAccountKey>(\n \"GoogleServiceAccountKey\",\n)({\n id: Id,\n organizationId: Id,\n clientEmail: Schema.String,\n privateKeyId: Schema.String,\n googleProjectId: Schema.String,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const UploadGoogleServiceAccountKeyBody = Schema.Struct({\n json: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const DeleteGoogleServiceAccountKeyResult = Schema.Struct({ deleted: Schema.Number });\n\nexport const DownloadGoogleServiceAccountKeyResult = Schema.Struct({\n id: Id,\n json: Schema.String,\n clientEmail: Schema.String,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n DeleteGoogleServiceAccountKeyResult,\n DownloadGoogleServiceAccountKeyResult,\n GoogleServiceAccountKey,\n UploadGoogleServiceAccountKeyBody,\n} from \"../domain/google-service-account-key\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class GoogleServiceAccountKeysGroup extends HttpApiGroup.make(\"googleServiceAccountKeys\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/google/service-account-keys\")\n .addSuccess(Schema.Struct({ items: Schema.Array(GoogleServiceAccountKey) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List Google service account keys\",\n description: \"List uploaded Google service account JSON keys\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"upload\", \"/api/google/service-account-keys\")\n .setPayload(UploadGoogleServiceAccountKeyBody)\n .addSuccess(GoogleServiceAccountKey, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Upload service account key\",\n description: \"Upload a Google service account JSON key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/google/service-account-keys/${idParam}`\n .addSuccess(DeleteGoogleServiceAccountKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete service account key\",\n description: \"Remove a stored Google service account key\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"download\")`/api/google/service-account-keys/${idParam}/download`\n .addSuccess(DownloadGoogleServiceAccountKeyResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Download service account key\",\n description: \"Fetch the decrypted JSON for local use (audit-logged)\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Google Service Account Keys\",\n description: \"Manage Google Play + FCM service account JSON keys\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { BundleIdentifier, DistributionType } from \"./apple-provisioning-profile\";\nimport { DateTimeString, Id } from \"./common\";\n\nexport class IosBundleConfiguration extends Schema.Class<IosBundleConfiguration>(\n \"IosBundleConfiguration\",\n)({\n id: Id,\n organizationId: Id,\n projectId: Id,\n bundleIdentifier: Schema.String,\n distributionType: DistributionType,\n appleTeamId: Id,\n appleDistributionCertificateId: Schema.NullOr(Id),\n appleProvisioningProfileId: Schema.NullOr(Id),\n applePushKeyId: Schema.NullOr(Id),\n ascApiKeyId: Schema.NullOr(Id),\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateIosBundleConfigurationBody = Schema.Struct({\n bundleIdentifier: BundleIdentifier,\n distributionType: DistributionType,\n appleTeamId: Id,\n appleDistributionCertificateId: Schema.optional(Id),\n appleProvisioningProfileId: Schema.optional(Id),\n applePushKeyId: Schema.optional(Id),\n ascApiKeyId: Schema.optional(Id),\n});\n\nexport const UpdateIosBundleConfigurationBody = Schema.Struct({\n appleDistributionCertificateId: Schema.optional(Schema.NullOr(Id)),\n appleProvisioningProfileId: Schema.optional(Schema.NullOr(Id)),\n applePushKeyId: Schema.optional(Schema.NullOr(Id)),\n ascApiKeyId: Schema.optional(Schema.NullOr(Id)),\n});\n\nexport const DeleteIosBundleConfigurationResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n CreateIosBundleConfigurationBody,\n DeleteIosBundleConfigurationResult,\n IosBundleConfiguration,\n UpdateIosBundleConfigurationBody,\n} from \"../domain/ios-bundle-configuration\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class IosBundleConfigurationsGroup extends HttpApiGroup.make(\"iosBundleConfigurations\")\n .add(\n HttpApiEndpoint.get(\"list\")`/api/projects/${projectIdParam}/ios-bundle-configurations`\n .addSuccess(Schema.Struct({ items: Schema.Array(IosBundleConfiguration) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List iOS bundle configurations\",\n description: \"List all iOS bundle configurations for a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"create\")`/api/projects/${projectIdParam}/ios-bundle-configurations`\n .setPayload(CreateIosBundleConfigurationBody)\n .addSuccess(IosBundleConfiguration, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create iOS bundle configuration\",\n description: \"Bind certificate + profile + push + ASC to a bundle identifier\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.put(\"update\")`/api/ios-bundle-configurations/${idParam}`\n .setPayload(UpdateIosBundleConfigurationBody)\n .addSuccess(IosBundleConfiguration)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update iOS bundle configuration\",\n description: \"Change the credentials bound to an iOS bundle configuration\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/ios-bundle-configurations/${idParam}`\n .addSuccess(DeleteIosBundleConfigurationResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete iOS bundle configuration\",\n description: \"Remove an iOS bundle configuration binding\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"iOS Bundle Configurations\",\n description: \"Per-project per-bundle credential bindings\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nexport const MeUser = Schema.Struct({\n id: Schema.String,\n name: Schema.String,\n email: Schema.String,\n});\n\nexport const MeOrganization = Schema.Struct({\n id: Schema.String,\n name: Schema.String,\n slug: Schema.String,\n role: Schema.NullOr(Schema.String),\n});\n\nexport const Me = Schema.Struct({\n user: Schema.NullOr(MeUser),\n activeOrganization: Schema.NullOr(MeOrganization),\n /** Authentication source — \"session\" for browser cookie, \"api-key\" for CLI bearer tokens. */\n source: Schema.Literal(\"session\", \"api-key\"),\n /** Email or descriptor identifying the actor — useful when `user` is null (api-key auth). */\n actorEmail: Schema.String,\n});\n","import { HttpApiEndpoint, HttpApiGroup, OpenApi } from \"@effect/platform\";\n\nimport { Me } from \"../domain/me\";\n\nexport class MeGroup extends HttpApiGroup.make(\"me\")\n .add(\n HttpApiEndpoint.get(\"get\", \"/api/me\")\n .addSuccess(Me)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get current actor\",\n description:\n \"Return the authenticated user + active organization. Useful for `whoami` and to verify the CLI's auth state.\",\n }),\n ),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"Me\",\n description: \"Current authenticated actor information\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { PaginationParams, DateTimeString, Id } from \"./common\";\n\nexport class Project extends Schema.Class<Project>(\"Project\")({\n id: Id,\n organizationId: Id,\n name: Schema.String,\n slug: Schema.String,\n createdAt: DateTimeString,\n lastActivityAt: DateTimeString,\n branchCount: Schema.Number,\n channelCount: Schema.Number,\n updateCount: Schema.Number,\n}) {}\n\nexport const ProjectSortColumn = Schema.Literal(\n \"lastActivityAt\",\n \"name\",\n \"createdAt\",\n \"branchCount\",\n \"channelCount\",\n \"updateCount\",\n);\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `name` (asc), `-lastActivityAt` (desc).\n */\nexport const ProjectSort = Schema.Union(\n ProjectSortColumn,\n Schema.TemplateLiteral(\"-\", ProjectSortColumn),\n);\n\nexport const ListProjectsParams = Schema.Struct({\n ...PaginationParams.fields,\n query: Schema.optional(Schema.String),\n sort: Schema.optional(ProjectSort),\n});\n\nexport const CreateProjectBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1)),\n slug: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const UpdateProjectBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1)),\n});\n\nexport const DeleteProjectResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { Conflict } from \"../domain/errors\";\nimport {\n CreateProjectBody,\n DeleteProjectResult,\n ListProjectsParams,\n Project,\n UpdateProjectBody,\n} from \"../domain/project\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst slugParam = HttpApiSchema.param(\"slug\", Schema.String);\n\nexport class ProjectsGroup extends HttpApiGroup.make(\"projects\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/projects\")\n .setPayload(CreateProjectBody)\n .addSuccess(Project, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create project\",\n description: \"Create a new project in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/projects\")\n .setUrlParams(ListProjectsParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Project),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List projects\",\n description: \"List all projects in the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/projects/${idParam}`.addSuccess(Project).annotateContext(\n OpenApi.annotations({\n title: \"Get project\",\n description: \"Get a single project by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"getBySlug\")`/api/projects/by-slug/${slugParam}`\n .addSuccess(Project)\n .annotateContext(\n OpenApi.annotations({\n title: \"Get project by slug\",\n description: \"Get a single project by slug within the caller's active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"rename\")`/api/projects/${idParam}`\n .setPayload(UpdateProjectBody)\n .addSuccess(Project)\n .annotateContext(\n OpenApi.annotations({\n title: \"Rename project\",\n description: \"Rename a project\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/projects/${idParam}`\n .addSuccess(DeleteProjectResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete project\",\n description: \"Delete a project and all its branches, channels, and updates\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Projects\",\n description: \"Project management endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id, PaginationParams, Platform } from \"./common\";\n\nexport class Update extends Schema.Class<Update>(\"Update\")({\n id: Id,\n branchId: Id,\n runtimeVersion: Schema.String,\n platform: Platform,\n message: Schema.String,\n metadataJson: Schema.String,\n extraJson: Schema.NullOr(Schema.String),\n groupId: Schema.String,\n rolloutPercentage: Schema.Number,\n isRollback: Schema.Boolean,\n signature: Schema.NullOr(Schema.String),\n certificateChain: Schema.NullOr(Schema.String),\n manifestBody: Schema.NullOr(Schema.String),\n directiveBody: Schema.NullOr(Schema.String),\n createdAt: DateTimeString,\n}) {}\n\nexport const UpdateSortColumn = Schema.Literal(\n \"createdAt\",\n \"runtimeVersion\",\n \"platform\",\n \"rolloutPercentage\",\n);\n\n/**\n * Sort param: column name optionally prefixed with `-` for descending.\n * Example: `runtimeVersion` (asc), `-createdAt` (desc).\n */\nexport const UpdateSort = Schema.Union(\n UpdateSortColumn,\n Schema.TemplateLiteral(\"-\", UpdateSortColumn),\n);\n\nexport const ListUpdatesParams = Schema.Struct({\n projectId: Id,\n branchId: Schema.optional(Id),\n platform: Schema.optional(Platform),\n ...PaginationParams.fields,\n sort: Schema.optional(UpdateSort),\n});\n\nexport const AssetRef = Schema.Struct({\n hash: Schema.String,\n key: Schema.String,\n isLaunch: Schema.Boolean,\n contentChecksum: Schema.optional(Schema.String),\n});\n\nexport const CreateUpdateBody = Schema.Struct({\n branch: Schema.String.pipe(Schema.minLength(1)),\n slug: Schema.String.pipe(Schema.minLength(1)),\n runtimeVersion: Schema.String.pipe(Schema.minLength(1)),\n platform: Platform,\n message: Schema.String,\n groupId: Schema.String.pipe(Schema.minLength(1)),\n metadata: Schema.Record({ key: Schema.String, value: Schema.Unknown }),\n extra: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n assets: Schema.Array(AssetRef),\n manifestBody: Schema.optional(Schema.String),\n directiveBody: Schema.optional(Schema.String),\n isRollback: Schema.optional(Schema.Boolean),\n signature: Schema.optional(Schema.String),\n certificateChain: Schema.optional(Schema.String),\n rolloutPercentage: Schema.optional(Schema.Number.pipe(Schema.int(), Schema.between(1, 100))),\n});\n\nexport const RepublishBody = Schema.Struct({\n sourceUpdateId: Schema.optional(Id),\n sourceGroupId: Schema.optional(Schema.String.pipe(Schema.minLength(1))),\n destinationBranchId: Schema.optional(Id),\n destinationChannel: Schema.optional(Schema.String.pipe(Schema.minLength(1))),\n message: Schema.optional(Schema.String),\n signedUpdates: Schema.optional(\n Schema.Array(\n Schema.Struct({\n sourceUpdateId: Id,\n manifestBody: Schema.String.pipe(Schema.minLength(1)),\n signature: Schema.String.pipe(Schema.minLength(1)),\n certificateChain: Schema.String.pipe(Schema.minLength(1)),\n }),\n ),\n ),\n});\n\nexport const RepublishResult = Schema.Struct({\n updates: Schema.Array(Update),\n});\n\nexport const DeleteUpdateResult = Schema.Struct({\n deleted: Schema.Number,\n});\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { UpdateRolloutBody } from \"../domain/common\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n CreateUpdateBody,\n DeleteUpdateResult,\n ListUpdatesParams,\n RepublishBody,\n RepublishResult,\n Update,\n} from \"../domain/update\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\nconst groupIdParam = HttpApiSchema.param(\"groupId\", Schema.String);\n\nexport class UpdatesGroup extends HttpApiGroup.make(\"updates\")\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/updates\")\n .setPayload(CreateUpdateBody)\n .addSuccess(Update, { status: 201 })\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Create update\",\n description: \"Publish a new update (manifest + directive) to a branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/updates\")\n .setUrlParams(ListUpdatesParams)\n .addSuccess(\n Schema.Struct({\n items: Schema.Array(Update),\n total: Schema.Number,\n page: Schema.Number,\n limit: Schema.Number,\n }),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"List updates\",\n description: \"List updates for a project, optionally filtered by branch\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/updates/${idParam}`.addSuccess(Update).annotateContext(\n OpenApi.annotations({\n title: \"Get update\",\n description: \"Fetch a single update by ID\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"deleteGroup\")`/api/updates/${groupIdParam}`\n .addSuccess(DeleteUpdateResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete update group\",\n description: \"Delete all updates in a group (paired iOS + Android updates)\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"republish\", \"/api/updates/republish\")\n .setPayload(RepublishBody)\n .addSuccess(RepublishResult)\n .addError(Conflict)\n .annotateContext(\n OpenApi.annotations({\n title: \"Republish update\",\n description: \"Cross-channel republish (promote) an update\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"editRollout\")`/api/updates/${idParam}/rollout`\n .setPayload(UpdateRolloutBody)\n .addSuccess(Update)\n .annotateContext(\n OpenApi.annotations({\n title: \"Edit per-update rollout\",\n description: \"Change the rollout percentage for a specific update\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"completeRollout\")`/api/updates/${idParam}/rollout/complete`\n .addSuccess(Update)\n .annotateContext(\n OpenApi.annotations({\n title: \"Complete per-update rollout\",\n description: \"End rollout — make update available to all devices\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"revertRollout\")`/api/updates/${idParam}/rollout/revert`\n .addSuccess(Update)\n .annotateContext(\n OpenApi.annotations({\n title: \"Revert per-update rollout\",\n description: \"End rollout — revert to previous update\",\n }),\n ),\n )\n .addError(BadRequest)\n .addError(NotFound)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Updates\",\n description: \"Update publishing, deletion, republish, and per-update rollout endpoints\",\n }),\n ) {}\n","import { Schema } from \"effect\";\n\nimport { DateTimeString, Id } from \"./common\";\n\nexport const WebhookEventName = Schema.Literal(\"update.published\", \"build.completed\");\nexport type WebhookEventNameValue = typeof WebhookEventName.Type;\n\nexport class Webhook extends Schema.Class<Webhook>(\"Webhook\")({\n id: Id,\n organizationId: Id,\n projectId: Schema.NullOr(Id),\n name: Schema.String,\n url: Schema.String,\n events: Schema.Array(WebhookEventName),\n enabled: Schema.Boolean,\n createdAt: DateTimeString,\n updatedAt: DateTimeString,\n}) {}\n\nexport const CreateWebhookBody = Schema.Struct({\n name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120)),\n url: Schema.String.pipe(\n Schema.pattern(/^https?:\\/\\/.+/u, { message: () => \"URL must start with http:// or https://\" }),\n Schema.maxLength(2000),\n ),\n events: Schema.Array(WebhookEventName).pipe(Schema.minItems(1)),\n projectId: Schema.optional(Id),\n});\n\nexport const UpdateWebhookBody = Schema.Struct({\n name: Schema.optional(Schema.String.pipe(Schema.minLength(1), Schema.maxLength(120))),\n url: Schema.optional(\n Schema.String.pipe(\n Schema.pattern(/^https?:\\/\\/.+/u, {\n message: () => \"URL must start with http:// or https://\",\n }),\n Schema.maxLength(2000),\n ),\n ),\n events: Schema.optional(Schema.Array(WebhookEventName).pipe(Schema.minItems(1))),\n enabled: Schema.optional(Schema.Boolean),\n});\n\nexport class WebhookWithSecret extends Schema.Class<WebhookWithSecret>(\"WebhookWithSecret\")({\n ...Webhook.fields,\n secret: Schema.String,\n}) {}\n\nexport const DeleteWebhookResult = Schema.Struct({ deleted: Schema.Number });\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { Forbidden } from \"../auth/errors\";\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, Conflict } from \"../domain/errors\";\nimport {\n CreateWebhookBody,\n DeleteWebhookResult,\n UpdateWebhookBody,\n Webhook,\n WebhookWithSecret,\n} from \"../domain/webhook\";\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.String);\n\nexport class WebhooksGroup extends HttpApiGroup.make(\"webhooks\")\n .add(\n HttpApiEndpoint.get(\"list\", \"/api/webhooks\")\n .addSuccess(Schema.Struct({ items: Schema.Array(Webhook) }))\n .annotateContext(\n OpenApi.annotations({\n title: \"List webhooks\",\n description: \"List webhook subscriptions in the active organization\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.post(\"create\", \"/api/webhooks\")\n .setPayload(CreateWebhookBody)\n .addSuccess(WebhookWithSecret, { status: 201 })\n .annotateContext(\n OpenApi.annotations({\n title: \"Create webhook\",\n description:\n \"Create a webhook subscription. The `secret` is returned once on creation — store it client-side.\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.get(\"get\")`/api/webhooks/${idParam}`\n .addSuccess(Webhook)\n .annotateContext(\n OpenApi.annotations({ title: \"Get webhook\", description: \"Fetch a single webhook by ID\" }),\n ),\n )\n .add(\n HttpApiEndpoint.patch(\"update\")`/api/webhooks/${idParam}`\n .setPayload(UpdateWebhookBody)\n .addSuccess(Webhook)\n .annotateContext(\n OpenApi.annotations({\n title: \"Update webhook\",\n description: \"Update webhook url, events, enabled state, or name\",\n }),\n ),\n )\n .add(\n HttpApiEndpoint.del(\"delete\")`/api/webhooks/${idParam}`\n .addSuccess(DeleteWebhookResult)\n .annotateContext(\n OpenApi.annotations({\n title: \"Delete webhook\",\n description: \"Remove a webhook subscription\",\n }),\n ),\n )\n .addError(NotFound)\n .addError(Conflict)\n .addError(BadRequest)\n .addError(Forbidden)\n .annotateContext(\n OpenApi.annotations({\n title: \"Webhooks\",\n description: \"User-configured HTTPS event subscriptions\",\n }),\n ) {}\n","import { HttpApi, OpenApi } from \"@effect/platform\";\n\nimport { Authentication } from \"./auth/middleware\";\nimport { AnalyticsGroup } from \"./groups/analytics\";\nimport { AndroidApplicationIdentifiersGroup } from \"./groups/android-application-identifiers\";\nimport { AndroidBuildCredentialsGroup } from \"./groups/android-build-credentials\";\nimport { AndroidUploadKeystoresGroup } from \"./groups/android-upload-keystores\";\nimport { AppleDistributionCertificatesGroup } from \"./groups/apple-distribution-certificates\";\nimport { AppleProvisioningProfilesGroup } from \"./groups/apple-provisioning-profiles\";\nimport { ApplePushKeysGroup } from \"./groups/apple-push-keys\";\nimport { AppleTeamsGroup } from \"./groups/apple-teams\";\nimport { AscApiKeysGroup } from \"./groups/asc-api-keys\";\nimport { AssetsGroup } from \"./groups/assets\";\nimport { AuditLogsGroup } from \"./groups/audit-logs\";\nimport { BranchesGroup } from \"./groups/branches\";\nimport { BuildCredentialsGroup } from \"./groups/build-credentials\";\nimport { BuildsGroup } from \"./groups/builds\";\nimport { ChannelsGroup } from \"./groups/channels\";\nimport { DevicesGroup } from \"./groups/devices\";\nimport { EnvVarsGroup } from \"./groups/env-vars\";\nimport { GoogleServiceAccountKeysGroup } from \"./groups/google-service-account-keys\";\nimport { IosBundleConfigurationsGroup } from \"./groups/ios-bundle-configurations\";\nimport { MeGroup } from \"./groups/me\";\nimport { ProjectsGroup } from \"./groups/projects\";\nimport { UpdatesGroup } from \"./groups/updates\";\nimport { WebhooksGroup } from \"./groups/webhooks\";\n\nexport class ManagementApi extends HttpApi.make(\"management-api\")\n .add(ProjectsGroup)\n .add(BranchesGroup)\n .add(ChannelsGroup)\n .add(UpdatesGroup)\n .add(AssetsGroup)\n .add(AnalyticsGroup)\n .add(BuildsGroup)\n .add(EnvVarsGroup)\n .add(AuditLogsGroup)\n .add(DevicesGroup)\n .add(AppleTeamsGroup)\n .add(AppleDistributionCertificatesGroup)\n .add(ApplePushKeysGroup)\n .add(AscApiKeysGroup)\n .add(AppleProvisioningProfilesGroup)\n .add(GoogleServiceAccountKeysGroup)\n .add(IosBundleConfigurationsGroup)\n .add(AndroidApplicationIdentifiersGroup)\n .add(AndroidUploadKeystoresGroup)\n .add(AndroidBuildCredentialsGroup)\n .add(BuildCredentialsGroup)\n .add(MeGroup)\n .add(WebhooksGroup)\n .middleware(Authentication)\n .annotateContext(\n OpenApi.annotations({\n title: \"Better Update Management API\",\n version: \"1.0.0\",\n description: \"Management API for OTA update publishing, deployment, and analytics\",\n }),\n ) {}\n","import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\";\nimport { Schema } from \"effect\";\n\nimport { NotFound } from \"../auth/ownership\";\nimport { BadRequest, NotAcceptable } from \"../domain/errors\";\n\nconst projectIdParam = HttpApiSchema.param(\"projectId\", Schema.String);\n\nexport class ManifestGroup extends HttpApiGroup.make(\"manifest\")\n .add(\n HttpApiEndpoint.get(\"serve\")`/manifest/${projectIdParam}`\n .addError(BadRequest)\n .addError(NotFound)\n .addError(NotAcceptable)\n .annotateContext(\n OpenApi.annotations({\n title: \"Serve manifest\",\n description: \"Expo Updates protocol v1 manifest endpoint\",\n }),\n ),\n )\n .annotateContext(\n OpenApi.annotations({\n title: \"Protocol\",\n description: \"Expo Updates protocol endpoints\",\n }),\n ) {}\n","import { HttpApi, OpenApi } from \"@effect/platform\";\n\nimport { ManifestGroup } from \"./groups/manifest\";\n\n/**\n * Documentation-only contract for OpenAPI/Scalar generation.\n * The manifest endpoint bypasses HttpApiBuilder at runtime because the Expo Updates\n * protocol requires multipart/mixed responses that do not fit the standard pipeline.\n */\nexport class ProtocolApi extends HttpApi.make(\"protocol-api\")\n .add(ManifestGroup)\n .annotateContext(\n OpenApi.annotations({\n title: \"Better Update Protocol API\",\n version: \"1.0.0\",\n description: \"Expo Updates protocol endpoints (unauthenticated)\",\n }),\n ) {}\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const asRecord = (value: unknown): Record<string, unknown> | undefined =>\n isRecord(value) ? value : undefined;\n","/* eslint-disable eslint/max-classes-per-file -- dedicated error-taxonomy module: each error class is a small, purpose-built tag used across the CLI for Effect.catchTag */\n\nimport { Data } from \"effect\";\n\nexport class AuthRequiredError extends Data.TaggedError(\"AuthRequiredError\")<{\n readonly message: string;\n}> {}\n\nexport class ProjectNotLinkedError extends Data.TaggedError(\"ProjectNotLinkedError\")<{\n readonly message: string;\n}> {}\n\nexport class UploadFailedError extends Data.TaggedError(\"UploadFailedError\")<{\n readonly message: string;\n}> {}\n\nexport class BuildProfileError extends Data.TaggedError(\"BuildProfileError\")<{\n readonly message: string;\n}> {}\n\nexport class RuntimeVersionError extends Data.TaggedError(\"RuntimeVersionError\")<{\n readonly message: string;\n}> {}\n\nexport class MissingCredentialsError extends Data.TaggedError(\"MissingCredentialsError\")<{\n readonly message: string;\n readonly hint: string;\n}> {}\n\nexport class BuildFailedError extends Data.TaggedError(\"BuildFailedError\")<{\n readonly step: string;\n readonly exitCode: number;\n readonly message: string;\n}> {}\n\nexport class ReserveError extends Data.TaggedError(\"ReserveError\")<{\n readonly message: string;\n}> {}\n\nexport class CompleteError extends Data.TaggedError(\"CompleteError\")<{\n readonly message: string;\n}> {}\n\nexport class PresignedUrlExpiredError extends Data.TaggedError(\"PresignedUrlExpiredError\")<{\n readonly message: string;\n}> {}\n\nexport class ArtifactNotFoundError extends Data.TaggedError(\"ArtifactNotFoundError\")<{\n readonly message: string;\n}> {}\n\nexport class KeychainError extends Data.TaggedError(\"KeychainError\")<{\n readonly message: string;\n}> {}\n\nexport class ProvisioningError extends Data.TaggedError(\"ProvisioningError\")<{\n readonly message: string;\n}> {}\n\nexport class EnvExportError extends Data.TaggedError(\"EnvExportError\")<{\n readonly message: string;\n}> {}\n\nexport class UpdatePublishError extends Data.TaggedError(\"UpdatePublishError\")<{\n readonly message: string;\n}> {}\n\nexport class UpdateRollbackError extends Data.TaggedError(\"UpdateRollbackError\")<{\n readonly message: string;\n}> {}\n\nexport class UpdatePromoteError extends Data.TaggedError(\"UpdatePromoteError\")<{\n readonly message: string;\n}> {}\n\nexport class CredentialValidationError extends Data.TaggedError(\"CredentialValidationError\")<{\n readonly message: string;\n}> {}\n\nexport class AppleAuthError extends Data.TaggedError(\"AppleAuthError\")<{\n readonly message: string;\n}> {}\n\nexport class InvalidArgumentError extends Data.TaggedError(\"InvalidArgumentError\")<{\n readonly message: string;\n}> {}\n\nexport class InteractiveProhibitedError extends Data.TaggedError(\"InteractiveProhibitedError\")<{\n readonly message: string;\n}> {}\n\nexport class CredentialsJsonError extends Data.TaggedError(\"CredentialsJsonError\")<{\n readonly message: string;\n}> {}\n\nexport class DirtyRepoError extends Data.TaggedError(\"DirtyRepoError\")<{\n readonly message: string;\n}> {}\n","export const formatCause = (cause: unknown): string => {\n if (cause instanceof Error) {\n return cause.message;\n }\n\n if (typeof cause === \"object\" && cause !== null) {\n const tagged = cause as { readonly _tag?: unknown; readonly message?: unknown };\n const tag = typeof tagged._tag === \"string\" ? tagged._tag : undefined;\n const message = typeof tagged.message === \"string\" ? tagged.message : undefined;\n if (tag && message) {\n return `${tag}: ${message}`;\n }\n if (message) {\n return message;\n }\n if (tag) {\n return tag;\n }\n }\n\n return String(cause);\n};\n","import process from \"node:process\";\n\nimport { Context, Effect, Layer } from \"effect\";\n\nconst definedEnvironment = (): Readonly<Record<string, string>> =>\n Object.fromEntries(\n Object.entries(process.env).flatMap(([key, value]) =>\n typeof value === \"string\" ? [[key, value] as const] : [],\n ),\n );\n\nexport class CliRuntime extends Context.Tag(\"cli/CliRuntime\")<\n CliRuntime,\n {\n readonly argv: readonly string[];\n readonly platform: NodeJS.Platform;\n readonly cwd: Effect.Effect<string>;\n readonly getEnv: (name: string) => Effect.Effect<string | undefined>;\n readonly homeDirectory: Effect.Effect<string>;\n readonly userName: Effect.Effect<string>;\n readonly commandEnvironment: (\n overrides?: Readonly<Record<string, string>>,\n ) => Effect.Effect<Readonly<Record<string, string>>>;\n readonly setExitCode: (code: number) => Effect.Effect<void>;\n }\n>() {}\n\nexport const CliRuntimeLive = Layer.succeed(CliRuntime, {\n argv: [...process.argv],\n platform: process.platform,\n cwd: Effect.sync(() => process.cwd()),\n getEnv: (name: string) => Effect.sync(() => process.env[name]),\n homeDirectory: Effect.sync(\n () => process.env[\"HOME\"] ?? process.env[\"USERPROFILE\"] ?? process.cwd(),\n ),\n userName: Effect.sync(() => process.env[\"USER\"] ?? process.env[\"USERNAME\"] ?? \"better-update\"),\n commandEnvironment: (overrides = {}) =>\n Effect.sync(() => ({\n ...definedEnvironment(),\n ...overrides,\n })),\n setExitCode: (code: number) =>\n Effect.sync(() => {\n process.exitCode = code;\n }),\n});\n","import path from \"node:path\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { AuthRequiredError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { CliRuntime } from \"./cli-runtime\";\n\nexport class AuthStore extends Context.Tag(\"cli/AuthStore\")<\n AuthStore,\n {\n readonly getToken: Effect.Effect<string, AuthRequiredError>;\n readonly saveToken: (token: string) => Effect.Effect<void, AuthRequiredError>;\n readonly clearToken: Effect.Effect<void>;\n }\n>() {}\n\nexport const AuthStoreLive = Layer.effect(\n AuthStore,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const authDir = path.join(homeDirectory, \".better-update\");\n const authFile = path.join(authDir, \"auth.json\");\n\n return {\n getToken: Effect.gen(function* () {\n const envToken = yield* runtime.getEnv(\"BETTER_UPDATE_TOKEN\");\n if (envToken) {\n return envToken;\n }\n\n const content = yield* fs.readFileString(authFile).pipe(\n Effect.mapError(\n () =>\n new AuthRequiredError({\n message: \"Not logged in. Run `better-update login` to authenticate.\",\n }),\n ),\n );\n\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(content),\n catch: () =>\n new AuthRequiredError({\n message: \"Corrupted auth file. Run `better-update login` to re-authenticate.\",\n }),\n });\n if (!isRecord(parsed)) {\n return yield* new AuthRequiredError({\n message: \"Invalid auth file. Run `better-update login` to re-authenticate.\",\n });\n }\n const { token } = parsed;\n if (typeof token !== \"string\") {\n return yield* new AuthRequiredError({\n message: \"Invalid auth file. Run `better-update login` to re-authenticate.\",\n });\n }\n\n return token;\n }),\n\n saveToken: (token: string) =>\n Effect.gen(function* () {\n yield* fs.makeDirectory(authDir, { recursive: true });\n yield* fs.chmod(authDir, 0o700);\n yield* fs.writeFileString(authFile, `${JSON.stringify({ token }, null, 2)}\\n`);\n yield* fs.chmod(authFile, 0o600);\n }).pipe(\n Effect.mapError(\n (cause) =>\n new AuthRequiredError({\n message: `Failed to save auth token: ${formatCause(cause)}`,\n }),\n ),\n ),\n\n clearToken: fs.remove(authFile).pipe(Effect.catchAll(() => Effect.void)),\n };\n }),\n);\n","import path from \"node:path\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Context, Data, Effect, Layer } from \"effect\";\n\nimport { CliRuntime } from \"./cli-runtime\";\n\nconst DEFAULT_BASE_URL = \"https://better-update.dev\";\nconst DEFAULT_WEB_URL = \"https://better-update.dev\";\n\nclass ConfigStoreParseError extends Data.TaggedError(\"ConfigStoreParseError\")<{\n readonly message: string;\n readonly cause: unknown;\n}> {}\n\nconst normalizeUrl = (value: string): string => value.replace(/\\/$/u, \"\");\n\nexport class ConfigStore extends Context.Tag(\"cli/ConfigStore\")<\n ConfigStore,\n {\n readonly getBaseUrl: Effect.Effect<string>;\n readonly getWebUrl: Effect.Effect<string>;\n }\n>() {}\n\nexport const ConfigStoreLive = Layer.effect(\n ConfigStore,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const configFile = path.join(homeDirectory, \".better-update\", \"config.json\");\n const readConfig = fs.readFileString(configFile).pipe(\n Effect.catchAll(() => Effect.succeed(\"\")),\n Effect.flatMap((content) =>\n content.length === 0\n ? Effect.succeed(undefined)\n : Effect.try({\n try: (): unknown => JSON.parse(content),\n catch: (cause) =>\n new ConfigStoreParseError({\n message: \"Config file contains invalid JSON\",\n cause,\n }),\n }).pipe(\n Effect.map((parsed) => (isRecord(parsed) ? parsed : undefined)),\n Effect.catchAll(() => Effect.succeed(undefined)),\n ),\n ),\n );\n const resolveBaseUrl = Effect.gen(function* () {\n const envUrl = yield* runtime.getEnv(\"BETTER_UPDATE_URL\");\n if (envUrl) {\n return normalizeUrl(envUrl);\n }\n\n const parsed = yield* readConfig;\n const baseUrl = parsed?.[\"baseUrl\"];\n if (typeof baseUrl === \"string\") {\n return normalizeUrl(baseUrl);\n }\n\n return DEFAULT_BASE_URL;\n });\n\n return {\n getBaseUrl: resolveBaseUrl,\n\n getWebUrl: Effect.gen(function* () {\n const envUrl = yield* runtime.getEnv(\"BETTER_UPDATE_WEB_URL\");\n if (envUrl) {\n return normalizeUrl(envUrl);\n }\n\n const parsed = yield* readConfig;\n const webUrl = parsed?.[\"webUrl\"];\n if (typeof webUrl === \"string\") {\n return normalizeUrl(webUrl);\n }\n\n return DEFAULT_WEB_URL;\n }),\n };\n }),\n);\n","import { ManagementApi } from \"@better-update/api\";\nimport { HttpApiClient, HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { AuthStore } from \"./auth-store\";\nimport { ConfigStore } from \"./config-store\";\n\nimport type { AuthRequiredError } from \"../lib/exit-codes\";\n\nconst client = HttpApiClient.make(ManagementApi);\nexport type ApiClient = Effect.Effect.Success<typeof client>;\n\nexport class ApiClientService extends Context.Tag(\"cli/ApiClient\")<\n ApiClientService,\n {\n readonly get: Effect.Effect<ApiClient, AuthRequiredError>;\n }\n>() {}\n\nexport const apiClient: Effect.Effect<ApiClient, AuthRequiredError, ApiClientService> =\n // eslint-disable-next-line unicorn/no-array-method-this-argument -- Effect.flatMap, not Array.prototype.flatMap; the second arg is a continuation, not a thisArg\n Effect.flatMap(ApiClientService, ({ get }) => get);\n\nexport const ApiClientLive = Layer.effect(\n ApiClientService,\n Effect.gen(function* () {\n const clientService = yield* HttpClient.HttpClient;\n const authStore = yield* AuthStore;\n const configStore = yield* ConfigStore;\n\n return {\n get: Effect.gen(function* () {\n const token = yield* authStore.getToken;\n const baseUrl = yield* configStore.getBaseUrl;\n return yield* HttpApiClient.make(ManagementApi, {\n transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),\n baseUrl,\n }).pipe(Effect.provideService(HttpClient.HttpClient, clientService));\n }),\n };\n }),\n);\n","export type JsonParseResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false };\n\nexport const parseJsonResult = (text: string): JsonParseResult => {\n // eslint-disable-next-line functional/no-try-statements -- JSON.parse exposes syntax errors via throw; this helper converts them to an explicit result value\n try {\n return { ok: true, value: JSON.parse(text) as unknown };\n } catch {\n return { ok: false };\n }\n};\n\nexport const safeJsonParse = (text: string): unknown => {\n const result = parseJsonResult(text);\n return result.ok ? result.value : null;\n};\n","import path from \"node:path\";\n\nimport { safeJsonParse } from \"@better-update/safe-json\";\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport type { Auth } from \"@expo/apple-utils\";\n\nimport { AppleAuthError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { CliRuntime } from \"./cli-runtime\";\n\n// The cookies payload accepted by @expo/apple-utils Auth.loginWithCookiesAsync.\n// Derived structurally so we don't depend on the un-exported `CookiesJSON` alias.\nexport type AppleSessionCookies = Parameters<typeof Auth.loginWithCookiesAsync>[0][\"cookies\"];\n\nexport interface SerializedAppleSession {\n readonly cookies: AppleSessionCookies;\n readonly teamId: string;\n readonly username: string;\n readonly providerId?: number;\n}\n\nexport class AppleSessionStore extends Context.Tag(\"cli/AppleSessionStore\")<\n AppleSessionStore,\n {\n readonly loadSession: Effect.Effect<SerializedAppleSession | null>;\n readonly saveSession: (session: SerializedAppleSession) => Effect.Effect<void, AppleAuthError>;\n readonly clearSession: Effect.Effect<void>;\n }\n>() {}\n\nexport const AppleSessionStoreLive = Layer.effect(\n AppleSessionStore,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const sessionDir = path.join(homeDirectory, \".better-update\");\n const sessionFile = path.join(sessionDir, \"apple-session.json\");\n\n return {\n loadSession: Effect.gen(function* () {\n const content = yield* fs\n .readFileString(sessionFile)\n .pipe(Effect.catchAll(() => Effect.succeed(null)));\n\n if (!content) {\n return null;\n }\n\n const parsed = safeJsonParse(content);\n if (!isRecord(parsed)) {\n return null;\n }\n\n if (\n typeof parsed[\"teamId\"] !== \"string\" ||\n typeof parsed[\"username\"] !== \"string\" ||\n !parsed[\"cookies\"]\n ) {\n return null;\n }\n\n const providerIdRaw = parsed[\"providerId\"];\n const hasProviderId = typeof providerIdRaw === \"number\" && Number.isInteger(providerIdRaw);\n\n // eslint-disable-next-line typescript/no-unsafe-type-assertion, typescript/no-unsafe-assignment -- AppleSessionCookies is an opaque cookies payload from @expo/apple-utils; round-tripped verbatim from disk\n const cookies = parsed[\"cookies\"] as AppleSessionCookies;\n\n const session: SerializedAppleSession = {\n // eslint-disable-next-line typescript/no-unsafe-assignment -- see disable on the `cookies` declaration above; same opaque value\n cookies,\n teamId: parsed[\"teamId\"],\n username: parsed[\"username\"],\n ...(hasProviderId ? { providerId: providerIdRaw } : {}),\n };\n return session;\n }),\n\n saveSession: (session: SerializedAppleSession) =>\n Effect.gen(function* () {\n yield* fs.makeDirectory(sessionDir, { recursive: true });\n yield* fs.chmod(sessionDir, 0o700);\n yield* fs.writeFileString(sessionFile, `${JSON.stringify(session, null, 2)}\\n`);\n yield* fs.chmod(sessionFile, 0o600);\n }).pipe(\n Effect.mapError(\n (cause) =>\n new AppleAuthError({\n message: `Failed to save Apple session: ${formatCause(cause)}`,\n }),\n ),\n ),\n\n clearSession: fs.remove(sessionFile).pipe(Effect.catchAll(() => Effect.void)),\n };\n }),\n);\n","import { FileSystem, HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { PresignedUrlExpiredError, UploadFailedError } from \"../lib/exit-codes\";\n\nconst EXPIRY_SAFETY_MARGIN_MS = 30_000;\n\nexport interface PutToPresignedUrlInput {\n readonly url: string;\n readonly filePath: string;\n readonly byteSize: number;\n readonly expiresAt: string;\n readonly headers?: Record<string, string>;\n}\n\nexport class PresignedUploadClient extends Context.Tag(\"cli/PresignedUploadClient\")<\n PresignedUploadClient,\n {\n readonly putToPresignedUrl: (\n input: PutToPresignedUrlInput,\n ) => Effect.Effect<void, PresignedUrlExpiredError | UploadFailedError>;\n }\n>() {}\n\nexport const PresignedUploadClientLive = Layer.effect(\n PresignedUploadClient,\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const fileSystem = yield* FileSystem.FileSystem;\n\n return {\n putToPresignedUrl: ({\n url,\n filePath,\n byteSize,\n expiresAt,\n headers,\n }: PutToPresignedUrlInput) =>\n Effect.gen(function* () {\n const now = Date.now();\n const expiryMs = new Date(expiresAt).getTime();\n if (Number.isNaN(expiryMs) || now > expiryMs - EXPIRY_SAFETY_MARGIN_MS) {\n return yield* new PresignedUrlExpiredError({\n message: `Presigned upload URL expired or too close to expiry (expiresAt=${expiresAt}).`,\n });\n }\n\n const request = yield* HttpClientRequest.put(url).pipe(\n HttpClientRequest.bodyFile(filePath),\n Effect.provideService(FileSystem.FileSystem, fileSystem),\n Effect.map(\n HttpClientRequest.setHeaders({\n \"content-length\": String(byteSize),\n ...headers,\n }),\n ),\n Effect.mapError(\n (cause) =>\n new UploadFailedError({\n message: `Failed to open artifact for upload: ${String(cause)}`,\n }),\n ),\n );\n\n const response = yield* client.execute(request).pipe(\n Effect.mapError(\n (cause) =>\n new UploadFailedError({\n message: `HTTP request to presigned URL failed: ${String(cause)}`,\n }),\n ),\n );\n\n if (response.status < 200 || response.status >= 300) {\n const body = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"));\n return yield* new UploadFailedError({\n message: `Presigned URL upload failed with status ${response.status}: ${body}`,\n });\n }\n return undefined;\n }),\n };\n }),\n);\n","import { Context, Effect, Layer } from \"effect\";\n\nimport { UpdatePublishError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { ApiClientService } from \"./api-client\";\nimport { PresignedUploadClient } from \"./presigned-upload\";\n\nexport interface UploadUpdateAssetInput {\n readonly path: string;\n readonly hash: string;\n readonly byteSize: number;\n readonly uploadUrl: string;\n readonly uploadExpiresAt: string;\n readonly uploadHeaders: Record<string, string>;\n}\n\nexport class UpdateAssetUploader extends Context.Tag(\"cli/UpdateAssetUploader\")<\n UpdateAssetUploader,\n {\n readonly uploadAssetBinary: (\n input: UploadUpdateAssetInput,\n ) => Effect.Effect<void, UpdatePublishError>;\n }\n>() {}\n\nexport const UpdateAssetUploaderLive = Layer.effect(\n UpdateAssetUploader,\n Effect.gen(function* () {\n const presignedUploadClient = yield* PresignedUploadClient;\n const apiService = yield* ApiClientService;\n\n return {\n uploadAssetBinary: (asset: UploadUpdateAssetInput) =>\n Effect.gen(function* () {\n const api = yield* apiService.get.pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Asset upload requires authentication: ${formatCause(cause)}`,\n }),\n ),\n );\n\n yield* presignedUploadClient\n .putToPresignedUrl({\n url: asset.uploadUrl,\n filePath: asset.path,\n byteSize: asset.byteSize,\n expiresAt: asset.uploadExpiresAt,\n headers: asset.uploadHeaders,\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Asset upload failed for ${asset.hash}: ${formatCause(cause)}`,\n }),\n ),\n );\n\n yield* api.assets.finalize({ path: { hash: asset.hash } }).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Asset finalize failed for ${asset.hash}: ${formatCause(cause)}`,\n }),\n ),\n );\n }),\n };\n }),\n);\n","import path from \"node:path\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem, HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { CliRuntime } from \"./cli-runtime\";\n\nconst NPM_REGISTRY_URL = \"https://registry.npmjs.org/@better-update/cli/latest\";\nconst CACHE_TTL_MS = 24 * 60 * 60 * 1000;\nconst REFRESH_TIMEOUT_MS = 3000;\n\ninterface VersionCacheEntry {\n readonly latest: string;\n readonly checkedAt: number;\n}\n\nexport class VersionCheck extends Context.Tag(\"cli/VersionCheck\")<\n VersionCheck,\n {\n readonly cachedLatest: Effect.Effect<string | undefined>;\n readonly cacheStale: Effect.Effect<boolean>;\n readonly refreshCache: Effect.Effect<void>;\n }\n>() {}\n\nexport const VersionCheckLive = Layer.effect(\n VersionCheck,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const httpClient = yield* HttpClient.HttpClient;\n const runtime = yield* CliRuntime;\n const homeDirectory = yield* runtime.homeDirectory;\n const cacheDir = path.join(homeDirectory, \".better-update\");\n const cacheFile = path.join(cacheDir, \"version-check.json\");\n\n const readCache: Effect.Effect<VersionCacheEntry | undefined> = Effect.gen(function* () {\n const content = yield* fs\n .readFileString(cacheFile)\n .pipe(Effect.catchAll(() => Effect.succeed(\"\")));\n if (content.length === 0) {\n return undefined;\n }\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(content),\n catch: () => \"parse-error\" as const,\n }).pipe(Effect.catchAll(() => Effect.succeed(undefined)));\n if (\n isRecord(parsed) &&\n typeof parsed[\"latest\"] === \"string\" &&\n typeof parsed[\"checkedAt\"] === \"number\"\n ) {\n return {\n latest: parsed[\"latest\"],\n checkedAt: parsed[\"checkedAt\"],\n } satisfies VersionCacheEntry;\n }\n return undefined;\n });\n\n return {\n cachedLatest: readCache.pipe(Effect.map((entry) => entry?.latest)),\n cacheStale: readCache.pipe(\n Effect.map((entry) => {\n if (!entry) {\n return true;\n }\n const elapsed = Date.now() - entry.checkedAt;\n return elapsed < 0 || elapsed > CACHE_TTL_MS;\n }),\n ),\n refreshCache: Effect.gen(function* () {\n const request = HttpClientRequest.get(NPM_REGISTRY_URL).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n );\n const response = yield* httpClient.execute(request);\n if (response.status < 200 || response.status >= 300) {\n return;\n }\n const body = yield* response.json;\n if (!isRecord(body) || typeof body[\"version\"] !== \"string\") {\n return;\n }\n const latest = body[\"version\"];\n yield* fs.makeDirectory(cacheDir, { recursive: true });\n yield* fs.writeFileString(\n cacheFile,\n `${JSON.stringify({ latest, checkedAt: Date.now() }, null, 2)}\\n`,\n );\n }).pipe(\n Effect.timeout(REFRESH_TIMEOUT_MS),\n Effect.catchAll(() => Effect.void),\n ),\n };\n }),\n);\n","import { FetchHttpClient } from \"@effect/platform\";\nimport { NodeContext } from \"@effect/platform-node\";\nimport { Layer } from \"effect\";\n\nimport { makeInteractiveModeLayer } from \"./lib/interactive-mode\";\nimport { makeOutputModeLayer } from \"./lib/output-mode\";\nimport { ApiClientLive } from \"./services/api-client\";\nimport { AppleSessionStoreLive } from \"./services/apple-session-store\";\nimport { AuthStoreLive } from \"./services/auth-store\";\nimport { CliRuntimeLive } from \"./services/cli-runtime\";\nimport { ConfigStoreLive } from \"./services/config-store\";\nimport { PresignedUploadClientLive } from \"./services/presigned-upload\";\nimport { UpdateAssetUploaderLive } from \"./services/update-asset-uploader\";\nimport { VersionCheckLive } from \"./services/version-check\";\n\nconst CliPlatformLayer = Layer.mergeAll(CliRuntimeLive, NodeContext.layer, FetchHttpClient.layer);\nconst CliStoreLayer = Layer.mergeAll(AuthStoreLive, ConfigStoreLive, AppleSessionStoreLive).pipe(\n Layer.provide(CliPlatformLayer),\n);\nconst CliAdapterDependencies = Layer.mergeAll(CliPlatformLayer, CliStoreLayer);\nconst ApiClientLayer = ApiClientLive.pipe(Layer.provide(CliAdapterDependencies));\nconst PresignedUploadLayer = PresignedUploadClientLive.pipe(Layer.provide(CliPlatformLayer));\nconst UpdateAssetUploaderLayer = UpdateAssetUploaderLive.pipe(\n Layer.provide(Layer.mergeAll(ApiClientLayer, PresignedUploadLayer)),\n);\nconst VersionCheckLayer = VersionCheckLive.pipe(Layer.provide(CliPlatformLayer));\n\nexport const makeCliLive = (options: { readonly json: boolean; readonly interactive: boolean }) =>\n Layer.mergeAll(\n CliAdapterDependencies,\n ApiClientLayer,\n PresignedUploadLayer,\n UpdateAssetUploaderLayer,\n VersionCheckLayer,\n makeOutputModeLayer(options.json),\n makeInteractiveModeLayer(options.interactive),\n );\n\n/** Default CLI layer: human-readable, interactive. Override via flags at the entrypoint. */\nexport const CliLive = makeCliLive({ json: false, interactive: true });\n","import { Console, Effect } from \"effect\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nexport const exitWith = (code: number, message: string): Effect.Effect<void, never, CliRuntime> =>\n Console.error(message).pipe(\n Effect.zipRight(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n yield* runtime.setExitCode(code);\n }),\n ),\n );\n","import { Effect } from \"effect\";\n\nimport { exitWith } from \"../application/command-exit\";\nimport { formatCause } from \"./format-error\";\n\nimport type { CliRuntime } from \"../services/cli-runtime\";\n\ntype ExitCode = 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\ninterface TaggedError {\n readonly message: string;\n}\n\ntype Handler = (error: TaggedError) => Effect.Effect<void, never, CliRuntime>;\n\nconst BASE_TAG_MAP: Record<string, ExitCode> = {\n AuthRequiredError: 3,\n ProjectNotLinkedError: 4,\n NotFound: 1,\n Conflict: 1,\n Forbidden: 1,\n BadRequest: 2,\n InvalidArgumentError: 2,\n InteractiveProhibitedError: 2,\n};\n\nconst SYSTEM_TAG_MESSAGE: Record<string, (error: TaggedError) => string> = {\n SystemError: (error) => `Filesystem error: ${error.message}`,\n BadArgument: (error) => `Invalid argument: ${error.message}`,\n};\n\nconst SYSTEM_TAG_CODE: Record<string, ExitCode> = {\n SystemError: 6,\n BadArgument: 6,\n};\n\nexport const makeCommandErrorHandler = (\n extras: Record<string, ExitCode> = {},\n): (<Success, Requirements>(\n effect: Effect.Effect<Success, unknown, Requirements>,\n) => Effect.Effect<Success, never, Requirements | CliRuntime>) => {\n const combined = { ...BASE_TAG_MAP, ...extras };\n const handlers: Record<string, Handler> = {};\n for (const [tag, code] of Object.entries(combined)) {\n const systemFormat = SYSTEM_TAG_MESSAGE[tag];\n const resolvedCode = SYSTEM_TAG_CODE[tag] ?? code;\n handlers[tag] = (error) =>\n exitWith(resolvedCode, systemFormat ? systemFormat(error) : error.message);\n }\n\n return <Success, Requirements>(\n effect: Effect.Effect<Success, unknown, Requirements>,\n ): Effect.Effect<Success, never, Requirements | CliRuntime> => {\n const piped = effect.pipe(\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- Effect.catchTags tag-inference requires a literal object; we accept a dynamic handler map so tags are chosen at runtime\n Effect.catchTags(handlers as never),\n Effect.catchAll((cause) => exitWith(1, formatCause(cause))),\n );\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- catchTags narrowing lost when handlers is dynamic; re-narrow at the boundary\n return piped as Effect.Effect<Success, never, Requirements | CliRuntime>;\n };\n};\n","import { Effect } from \"effect\";\n\nimport { CliLive } from \"../app-layer\";\nimport { makeCommandErrorHandler } from \"./command-errors\";\n\ntype CliLayer = typeof CliLive;\ntype ExtraExitMap = Parameters<typeof makeCommandErrorHandler>[0];\n\n// Active CLI layer. Defaults to CliLive (human-readable, interactive); the\n// entry point overrides this with `setActiveCliLayer(makeCliLive({...}))`\n// after parsing global flags so subcommands inherit the correct OutputMode\n// and InteractiveMode services.\nlet activeCliLayer: CliLayer = CliLive;\n\nexport const setActiveCliLayer = (layer: CliLayer): void => {\n activeCliLayer = layer;\n};\n\nexport const runEffect = async <Value, Err, Req>(\n effect: Effect.Effect<Value, Err, Req>,\n extras: ExtraExitMap = {},\n): Promise<void> => {\n const handled = makeCommandErrorHandler(extras)(effect);\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- activeCliLayer provides every service handlers require; after makeCommandErrorHandler the failure channel is `never`\n const provided = handled.pipe(Effect.provide(activeCliLayer)) as Effect.Effect<Value>;\n return Effect.runPromise(provided.pipe(Effect.asVoid));\n};\n","import process from \"node:process\";\n\nimport { Effect } from \"effect\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { BuildProfileError, ProjectNotLinkedError } from \"./exit-codes\";\nimport { formatCause } from \"./format-error\";\n\nimport type { AppMeta, Platform, RawRuntimeVersion } from \"./build-profile\";\n\nexport interface ExpoConfig {\n readonly name?: string;\n readonly slug?: string;\n readonly version?: string;\n readonly runtimeVersion?: string | { readonly policy: string };\n readonly ios?: {\n readonly bundleIdentifier?: string;\n readonly buildNumber?: string;\n };\n readonly android?: {\n readonly package?: string;\n readonly versionCode?: number;\n };\n readonly extra?: {\n readonly betterUpdate?: {\n readonly projectId?: unknown;\n readonly profiles?: unknown;\n } & Record<string, unknown>;\n } & Record<string, unknown>;\n readonly [key: string]: unknown;\n}\n\nexport interface ConfigFilePaths {\n readonly staticConfigPath: string | null;\n readonly dynamicConfigPath: string | null;\n}\n\ninterface ExpoConfigModule {\n readonly getConfig: (\n projectRoot: string,\n options?: { readonly skipSDKVersionRequirement?: boolean },\n ) => { readonly exp: ExpoConfig };\n readonly modifyConfigAsync: (\n projectRoot: string,\n modifications: Record<string, unknown>,\n readOptions?: { readonly skipSDKVersionRequirement?: boolean },\n ) => Promise<{\n readonly type: \"success\" | \"warn\" | \"fail\";\n readonly message?: string;\n readonly config: ExpoConfig | null;\n }>;\n readonly getConfigFilePaths: (projectRoot: string) => ConfigFilePaths;\n}\n\nconst loadExpoConfigModule = (): ExpoConfigModule =>\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CJS require returns `any`; narrow at the @expo/config boundary\n require(\"@expo/config\") as ExpoConfigModule;\n\n// `@expo/config` resolves dynamic configs via Node's `require`, which caches the\n// Evaluated module by absolute path. For static-form `module.exports = {...}`\n// Files, top-level `process.env` reads are captured at first load and frozen,\n// So a subsequent `readExpoConfig` call with a different env overlay would\n// Silently return the stale cached object. Evicting the cached entry forces\n// Re-evaluation on every call so env overlays always take effect.\nconst clearDynamicConfigCache = (projectRoot: string): void => {\n const { dynamicConfigPath } = loadExpoConfigModule().getConfigFilePaths(projectRoot);\n if (dynamicConfigPath) {\n // eslint-disable-next-line typescript/no-dynamic-delete -- evict @expo/config-cached module so each readExpoConfig sees fresh process.env\n delete require.cache[dynamicConfigPath];\n }\n};\n\nconst applyEnvOverlay = (envVars: Record<string, string>): Record<string, string | undefined> => {\n const previous: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(envVars)) {\n previous[key] = process.env[key];\n process.env[key] = value;\n }\n return previous;\n};\n\nconst restoreEnv = (previous: Record<string, string | undefined>): void => {\n for (const [key, value] of Object.entries(previous)) {\n if (value === undefined) {\n // eslint-disable-next-line typescript/no-dynamic-delete -- restoring snapshot of arbitrary process.env keys captured at overlay time\n delete process.env[key];\n } else {\n process.env[key] = value;\n }\n }\n};\n\n/**\n * Resolve the Expo config via `@expo/config`, supporting `app.json`,\n * `app.config.json`, `app.config.js`, and `app.config.ts`.\n *\n * `envVars` are applied as a scoped overlay on `process.env` for the duration\n * of the call so dynamic configs (`app.config.js`/`.ts`) can read them without\n * leaking server-side secrets to child processes.\n */\nexport const readExpoConfig = (\n projectRoot: string,\n envVars: Record<string, string> = {},\n): Effect.Effect<ExpoConfig, ProjectNotLinkedError> =>\n Effect.acquireUseRelease(\n Effect.sync(() => {\n clearDynamicConfigCache(projectRoot);\n return applyEnvOverlay(envVars);\n }),\n () =>\n Effect.try({\n try: () =>\n loadExpoConfigModule().getConfig(projectRoot, { skipSDKVersionRequirement: true }).exp,\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to load Expo config from ${projectRoot}: ${formatCause(cause)}`,\n }),\n }),\n (previous) =>\n Effect.sync(() => {\n restoreEnv(previous);\n }),\n );\n\nexport const getConfigFilePaths = (\n projectRoot: string,\n): Effect.Effect<ConfigFilePaths, ProjectNotLinkedError> =>\n Effect.try({\n try: () => loadExpoConfigModule().getConfigFilePaths(projectRoot),\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to inspect Expo config paths in ${projectRoot}: ${formatCause(cause)}`,\n }),\n });\n\nexport const extractProjectId = (\n config: ExpoConfig,\n): Effect.Effect<string, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n const projectId = config.extra?.betterUpdate?.projectId;\n if (typeof projectId !== \"string\") {\n return yield* new ProjectNotLinkedError({\n message:\n \"Project not linked. Run `better-update link` to connect this project, or set extra.betterUpdate.projectId in your Expo config.\",\n });\n }\n return projectId;\n });\n\nexport const extractSlug = (config: ExpoConfig): Effect.Effect<string, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n if (typeof config.slug !== \"string\") {\n return yield* new ProjectNotLinkedError({\n message: \"Missing slug in your Expo config. Required to identify the project.\",\n });\n }\n return config.slug;\n });\n\n/** Convenience reader for command code: resolves projectRoot from CliRuntime. */\nexport const readProjectId: Effect.Effect<string, ProjectNotLinkedError, CliRuntime> = Effect.gen(\n function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const config = yield* readExpoConfig(projectRoot);\n return yield* extractProjectId(config);\n },\n);\n\nexport interface WriteProjectIdResult {\n readonly type: \"success\" | \"warn\";\n readonly configPath: string | null;\n readonly message?: string;\n}\n\nconst buildManualPasteHint = (id: string, message?: string): string => {\n const reason = message ? ` (${message})` : \"\";\n return [\n `Cannot write projectId to a dynamic Expo config${reason}.`,\n \"Add this to your config manually:\",\n \"\",\n ` extra: { betterUpdate: { projectId: \"${id}\" } }`,\n ].join(\"\\n\");\n};\n\nexport const writeProjectId = (\n projectRoot: string,\n id: string,\n): Effect.Effect<WriteProjectIdResult, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n const result = yield* Effect.tryPromise({\n try: async () =>\n loadExpoConfigModule().modifyConfigAsync(\n projectRoot,\n { extra: { betterUpdate: { projectId: id } } },\n { skipSDKVersionRequirement: true },\n ),\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to write projectId to Expo config: ${formatCause(cause)}`,\n }),\n });\n\n // `modifyConfigAsync` returns 'warn' with config: null when only a dynamic\n // Config exists (it can't write to .js/.ts) and 'fail' for hard errors.\n // Both indicate the projectId did NOT get persisted — surface a manual-paste hint.\n if (result.type === \"fail\" || (result.type === \"warn\" && result.config === null)) {\n return yield* new ProjectNotLinkedError({\n message: buildManualPasteHint(id, result.message),\n });\n }\n\n const paths = yield* getConfigFilePaths(projectRoot);\n return {\n type: result.type,\n configPath: paths.staticConfigPath,\n ...(result.message === undefined ? {} : { message: result.message }),\n } satisfies WriteProjectIdResult;\n });\n\nexport interface WriteExpoConfigPatchResult {\n readonly type: \"success\" | \"warn\";\n readonly configPath: string | null;\n readonly message?: string;\n}\n\nexport const writeExpoConfigPatch = (\n projectRoot: string,\n patch: Record<string, unknown>,\n): Effect.Effect<WriteExpoConfigPatchResult, ProjectNotLinkedError> =>\n Effect.gen(function* () {\n const result = yield* Effect.tryPromise({\n try: async () =>\n loadExpoConfigModule().modifyConfigAsync(projectRoot, patch, {\n skipSDKVersionRequirement: true,\n }),\n catch: (cause) =>\n new ProjectNotLinkedError({\n message: `Failed to write Expo config: ${formatCause(cause)}`,\n }),\n });\n\n if (result.type === \"fail\") {\n return yield* new ProjectNotLinkedError({\n message: result.message ?? \"Failed to write Expo config.\",\n });\n }\n\n const paths = yield* getConfigFilePaths(projectRoot);\n return {\n type: result.type,\n configPath: result.config === null ? null : paths.staticConfigPath,\n ...(result.message === undefined ? {} : { message: result.message }),\n } satisfies WriteExpoConfigPatchResult;\n });\n\nconst extractBuildNumber = (config: ExpoConfig, platform: Platform): string | undefined => {\n if (platform === \"ios\") {\n return config.ios?.buildNumber;\n }\n if (config.android?.versionCode === undefined) {\n return undefined;\n }\n return String(config.android.versionCode);\n};\n\nconst extractRawRuntimeVersion = (config: ExpoConfig): RawRuntimeVersion | undefined => {\n const raw = config.runtimeVersion;\n if (typeof raw === \"string\") {\n return raw;\n }\n // typeof null === \"object\" — guard before reading `policy` so configs that\n // explicitly clear runtimeVersion (e.g. `runtimeVersion: null` from a dynamic\n // config) fall through to undefined instead of crashing resolveRuntimeVersion.\n // eslint-disable-next-line typescript/no-unnecessary-condition -- runtime guard against `runtimeVersion: null` even though the static type excludes null\n if (typeof raw === \"object\" && raw !== null && typeof raw.policy === \"string\") {\n return { policy: raw.policy };\n }\n return undefined;\n};\n\n/**\n * Extract AppMeta from a resolved ExpoConfig (from `@expo/config`).\n */\nexport const readAppMeta = (\n config: ExpoConfig,\n platform: Platform,\n): Effect.Effect<AppMeta, BuildProfileError> =>\n Effect.gen(function* () {\n if (platform === \"ios\" && !config.ios) {\n return yield* new BuildProfileError({\n message:\n \"Missing ios section in your Expo config. Required for iOS builds (bundleIdentifier).\",\n });\n }\n if (platform === \"android\" && !config.android) {\n return yield* new BuildProfileError({\n message:\n \"Missing android section in your Expo config. Required for Android builds (package).\",\n });\n }\n\n return {\n bundleId: config.ios?.bundleIdentifier,\n androidPackage: config.android?.package,\n appVersion: config.version,\n buildNumber: extractBuildNumber(config, platform),\n rawRuntimeVersion: extractRawRuntimeVersion(config),\n };\n });\n","import { Console, Effect } from \"effect\";\n\nimport { OutputMode } from \"./output-mode\";\n\n/**\n * Emit a key/value table. Human mode prints aligned columns; JSON mode emits a\n * `{ items: [...] }` array where each row is keyed by header name.\n */\nexport const printTable = (\n headers: readonly string[],\n rows: readonly (readonly string[])[],\n): Effect.Effect<void, never, OutputMode> =>\n Effect.gen(function* () {\n const mode = yield* OutputMode;\n if (mode.json) {\n const items = rows.map((row) =>\n Object.fromEntries(\n headers.map((header, idx) => [\n header,\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- ragged-row JSON: missing cell renders as empty string, matching the human table layout\n row[idx] ?? \"\",\n ]),\n ),\n );\n yield* Console.log(JSON.stringify({ items }));\n return;\n }\n const allRows = [headers, ...rows];\n const colWidths = headers.map((_, colIndex) =>\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- table padding for ragged rows; missing cell treated as empty-width\n Math.max(...allRows.map((row) => (row[colIndex] ?? \"\").length)),\n );\n\n const formatRow = (row: readonly string[]): string =>\n row.map((cell, idx) => cell.padEnd(colWidths[idx] ?? 0)).join(\" \");\n\n yield* Console.log(formatRow(headers));\n yield* Console.log(colWidths.map((width) => \"-\".repeat(width)).join(\" \"));\n\n for (const row of rows) {\n yield* Console.log(formatRow(row));\n }\n });\n\n/**\n * Emit aligned key/value pairs. Human mode prints a two-column layout; JSON\n * mode emits a flat object keyed by the first column.\n */\nexport const printKeyValue = (\n pairs: readonly (readonly [string, string])[],\n): Effect.Effect<void, never, OutputMode> =>\n Effect.gen(function* () {\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* Console.log(JSON.stringify(Object.fromEntries(pairs)));\n return;\n }\n const maxKeyLen = Math.max(...pairs.map(([key]) => key.length));\n\n for (const [key, value] of pairs) {\n yield* Console.log(`${key.padEnd(maxKeyLen)} ${value}`);\n }\n });\n\n/**\n * Emit arbitrary JSON. In human mode emits pretty-printed JSON; in JSON mode\n * emits compact JSON. Use this for `view <id>`-style commands where the whole\n * payload should be machine-parseable.\n */\nexport const printJson = (data: unknown): Effect.Effect<void, never, OutputMode> =>\n Effect.gen(function* () {\n const mode = yield* OutputMode;\n yield* Console.log(JSON.stringify(data, null, mode.json ? 0 : 2));\n });\n\n/**\n * Emit a human-only message. Suppressed entirely in JSON mode so the output\n * stream stays machine-parseable.\n */\nexport const printHuman = (message: string): Effect.Effect<void, never, OutputMode> =>\n Effect.gen(function* () {\n const mode = yield* OutputMode;\n if (mode.json) {\n return;\n }\n yield* Console.log(message);\n });\n\n/**\n * Emit a list result. In JSON mode always emits `{items: [...]}`; in human mode\n * prints the table or, if empty, the `emptyMessage`. Use this for `list`-style\n * commands so empty results stay parseable as `{items: []}` instead of falling\n * back to a plain-text \"Nothing found\" message.\n */\nexport const printList = (\n headers: readonly string[],\n rows: readonly (readonly string[])[],\n emptyMessage: string,\n): Effect.Effect<void, never, OutputMode> =>\n Effect.gen(function* () {\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printTable(headers, rows);\n return;\n }\n if (rows.length === 0) {\n yield* Console.log(emptyMessage);\n return;\n }\n yield* printTable(headers, rows);\n });\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const adoptionCommand = defineCommand({\n meta: { name: \"adoption\", description: \"Show update adoption across devices\" },\n args: {\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.adoption({\n urlParams: { projectId, ...periodFilter },\n });\n\n yield* printList(\n [\"Update ID\", \"Devices\", \"First Seen\", \"Last Seen\"],\n result.updates.map((update) => [\n update.updateId,\n String(update.devices),\n update.firstSeen,\n update.lastSeen,\n ]),\n \"No adoption data found.\",\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const channelsCommand = defineCommand({\n meta: { name: \"channels\", description: \"Stats for a specific channel\" },\n args: {\n channel: { type: \"string\", required: true, description: \"Channel name\" },\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.channels({\n urlParams: { projectId, channel: args.channel, ...periodFilter },\n });\n\n yield* printKeyValue([\n [\"Channel\", result.channel],\n [\"Total Requests\", String(result.totalRequests)],\n [\"Unique Devices\", String(result.uniqueDevices)],\n [\"Manifest\", String(result.responseTypeDistribution.manifest)],\n [\"Directive\", String(result.responseTypeDistribution.directive)],\n [\"No Update\", String(result.responseTypeDistribution.no_update)],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const platformsCommand = defineCommand({\n meta: { name: \"platforms\", description: \"Stats by platform\" },\n args: {\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.platforms({\n urlParams: { projectId, ...periodFilter },\n });\n\n yield* printList(\n [\"Platform\", \"Requests\", \"Devices\"],\n result.platforms.map((platform) => [\n platform.platform,\n String(platform.requests),\n String(platform.devices),\n ]),\n \"No platform data found.\",\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const updatesCommand = defineCommand({\n meta: { name: \"updates\", description: \"Stats for a specific update\" },\n args: {\n \"update-id\": { type: \"string\", required: true, description: \"Update ID\" },\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n\n const result = yield* api.analytics.updates({\n urlParams: { projectId, updateId: args[\"update-id\"], ...periodFilter },\n });\n\n yield* printKeyValue([\n [\"Update ID\", result.updateId],\n [\"Total Requests\", String(result.totalRequests)],\n [\"Unique Devices\", String(result.uniqueDevices)],\n [\"Manifest\", String(result.byResponseType.manifest)],\n [\"Directive\", String(result.byResponseType.directive)],\n [\"No Update\", String(result.byResponseType.no_update)],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { adoptionCommand } from \"./adoption\";\nimport { channelsCommand } from \"./channels\";\nimport { platformsCommand } from \"./platforms\";\nimport { updatesCommand } from \"./updates\";\n\nexport const analyticsCommand = defineCommand({\n meta: { name: \"analytics\", description: \"View deployment analytics\" },\n subCommands: {\n adoption: adoptionCommand,\n updates: updatesCommand,\n channels: channelsCommand,\n platforms: platformsCommand,\n },\n});\n","import { Effect, ParseResult, Schema } from \"effect\";\n\nimport { InvalidArgumentError } from \"./exit-codes\";\n\nexport const RolloutPercentage = Schema.Number.pipe(\n Schema.int(),\n Schema.between(1, 100),\n).annotations({\n message: () => \"Rollout percentage must be between 1 and 100.\",\n identifier: \"RolloutPercentage\",\n});\n\nexport const KeyValuePair = Schema.Struct({\n key: Schema.String,\n value: Schema.String,\n});\nexport type KeyValuePair = Schema.Schema.Type<typeof KeyValuePair>;\n\nexport const KeyValueFromString = Schema.transformOrFail(Schema.String, KeyValuePair, {\n strict: true,\n decode: (input, _options, ast) => {\n const eqIndex = input.indexOf(\"=\");\n if (eqIndex <= 0) {\n return ParseResult.fail(\n new ParseResult.Type(ast, input, \"Invalid format. Use KEY=VALUE (e.g. API_KEY=abc123)\"),\n );\n }\n return ParseResult.succeed({\n key: input.slice(0, eqIndex),\n value: input.slice(eqIndex + 1),\n });\n },\n encode: ({ key, value }) => ParseResult.succeed(`${key}=${value}`),\n});\n\nexport const parseRolloutPercentage = (\n raw: string,\n flag: string,\n): Effect.Effect<number, InvalidArgumentError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(RolloutPercentage)(Number(raw)),\n catch: () =>\n new InvalidArgumentError({\n message: `--${flag} must be an integer between 1 and 100, got \"${raw}\".`,\n }),\n });\n\nexport const parseKeyValue = (raw: string): Effect.Effect<KeyValuePair, InvalidArgumentError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(KeyValueFromString)(raw),\n catch: () =>\n new InvalidArgumentError({\n message: \"Invalid format. Use KEY=VALUE (e.g. API_KEY=abc123)\",\n }),\n });\n\nexport const parseLimit = (\n raw: string | undefined,\n defaultValue: number,\n): Effect.Effect<number, InvalidArgumentError> => {\n if (raw === undefined) {\n return Effect.succeed(defaultValue);\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 1) {\n return Effect.fail(\n new InvalidArgumentError({ message: `--limit must be a positive integer, got \"${raw}\".` }),\n );\n }\n return Effect.succeed(parsed);\n};\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseLimit } from \"../../lib/cli-schemas\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List audit log entries\" },\n args: {\n \"resource-type\": { type: \"string\", description: \"Filter by resource type\" },\n from: { type: \"string\", description: \"ISO timestamp lower bound\" },\n to: { type: \"string\", description: \"ISO timestamp upper bound\" },\n limit: { type: \"string\", default: \"100\", description: \"Max rows (default 100)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const limit = yield* parseLimit(args.limit, 100);\n const api = yield* apiClient;\n\n const filters: Record<string, string> = {};\n if (args[\"resource-type\"]) {\n filters[\"resourceType\"] = args[\"resource-type\"];\n }\n if (args.from) {\n filters[\"from\"] = args.from;\n }\n if (args.to) {\n filters[\"to\"] = args.to;\n }\n\n const { items } = yield* api[\"audit-logs\"].list({\n urlParams: { ...filters, limit },\n });\n\n yield* printList(\n [\"ID\", \"Action\", \"Resource Type\", \"Resource ID\", \"Actor\", \"Source\", \"Created\"],\n items.map((log) => [\n log.id,\n log.action,\n log.resourceType,\n log.resourceId ?? \"-\",\n log.actorEmail,\n log.source,\n log.createdAt,\n ]),\n \"No audit log entries found.\",\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { listCommand } from \"./list\";\n\nexport const auditLogsCommand = defineCommand({\n meta: { name: \"audit-logs\", description: \"View audit logs\" },\n subCommands: {\n list: listCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../lib/exit-codes\";\n\nconst TOP_LEVEL_COMMANDS = [\n \"login\",\n \"logout\",\n \"init\",\n \"status\",\n \"projects\",\n \"branches\",\n \"channels\",\n \"build\",\n \"builds\",\n \"credentials\",\n \"env\",\n \"fingerprint\",\n \"update\",\n \"analytics\",\n \"audit-logs\",\n \"whoami\",\n \"open\",\n \"doctor\",\n \"devices\",\n \"webhooks\",\n \"autocomplete\",\n];\n\nconst bashScript = (): string => {\n const commands = TOP_LEVEL_COMMANDS.join(\" \");\n return `_better_update_complete() {\n local cur prev\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n if [ \"$COMP_CWORD\" -eq 1 ]; then\n COMPREPLY=( $(compgen -W \"${commands}\" -- \"$cur\") )\n fi\n return 0\n}\ncomplete -F _better_update_complete better-update\n`;\n};\n\nconst zshScript = (): string => {\n const commands = TOP_LEVEL_COMMANDS.map((cmd) => `\"${cmd}\"`).join(\" \");\n return `#compdef better-update\n_better_update() {\n local commands\n commands=(${commands})\n if (( CURRENT == 2 )); then\n _describe 'command' commands\n fi\n}\ncompdef _better_update better-update\n`;\n};\n\nconst fishScript = (): string => {\n const lines = TOP_LEVEL_COMMANDS.map(\n (cmd) =>\n `complete -c better-update -f -n '__fish_use_subcommand' -a '${cmd}' -d '${cmd} subcommand'`,\n );\n return `${lines.join(\"\\n\")}\\n`;\n};\n\nexport const autocompleteCommand = defineCommand({\n meta: {\n name: \"autocomplete\",\n description:\n \"Print a shell completion script. Source it (or pipe to your rc file) to enable Tab-completion.\",\n },\n args: {\n shell: {\n type: \"positional\",\n required: true,\n description: \"Target shell: bash, zsh, or fish\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n switch (args.shell) {\n case \"bash\": {\n yield* Console.log(bashScript());\n return undefined;\n }\n case \"zsh\": {\n yield* Console.log(zshScript());\n return undefined;\n }\n case \"fish\": {\n yield* Console.log(fishScript());\n return undefined;\n }\n default: {\n return yield* new InvalidArgumentError({\n message: `Unknown shell: ${args.shell}. Supported: bash, zsh, fish.`,\n });\n }\n }\n }),\n ),\n});\n","import { Effect } from \"effect\";\n\ninterface NumberedPage<Item> {\n readonly items: readonly Item[];\n readonly total: number;\n readonly page: number;\n readonly limit: number;\n}\n\nconst MAX_PAGES = 100;\n\n/**\n * Drain a page-numbered list endpoint into a single array. Used by CLI\n * commands that need the full set, not a page slice.\n */\nexport const drainPages = <Item, Err, Req>(\n fetchPage: (page: number) => Effect.Effect<NumberedPage<Item>, Err, Req>,\n): Effect.Effect<readonly Item[], Err, Req> => {\n const loop = (\n accumulator: readonly Item[],\n page: number,\n ): Effect.Effect<readonly Item[], Err, Req> =>\n fetchPage(page).pipe(\n Effect.flatMap((response) => {\n const next = [...accumulator, ...response.items];\n const fetched = page * response.limit;\n const reachedLimit = page >= MAX_PAGES || next.length >= response.total;\n return reachedLimit || fetched >= response.total\n ? Effect.succeed(next)\n : loop(next, page + 1);\n }),\n );\n return loop([], 1);\n};\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { drainPages } from \"../lib/drain-cursor\";\nimport { InvalidArgumentError } from \"../lib/exit-codes\";\nimport { readProjectId } from \"../lib/expo-config\";\nimport { printJson, printKeyValue, printList } from \"../lib/output\";\nimport { OutputMode } from \"../lib/output-mode\";\nimport { apiClient } from \"../services/api-client\";\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List branches for the linked project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const items = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n\n yield* printList(\n [\"ID\", \"Name\", \"Created\"],\n items.map((branch) => [branch.id, branch.name, branch.createdAt]),\n \"No branches found.\",\n );\n }),\n ),\n});\n\nconst createCommand = defineCommand({\n meta: { name: \"create\", description: \"Create a branch\" },\n args: {\n name: { type: \"string\", required: true, description: \"Branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const branch = yield* api.branches.create({\n payload: { projectId, name: args.name },\n });\n yield* printKeyValue([\n [\"ID\", branch.id],\n [\"Name\", branch.name],\n [\"Created\", branch.createdAt],\n ]);\n }),\n ),\n});\n\nconst viewCommand = defineCommand({\n meta: { name: \"view\", description: \"Show a branch by ID or name\" },\n args: {\n target: {\n type: \"positional\",\n required: true,\n description: \"Branch ID or branch name (name requires linked project)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const branch = yield* api.branches.get({ path: { id: args.target } }).pipe(\n Effect.catchTag(\"NotFound\", () =>\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const matches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const byName = matches.find((entry) => entry.name === args.target);\n if (!byName) {\n return yield* new InvalidArgumentError({\n message: `Branch \"${args.target}\" not found by ID or name.`,\n });\n }\n return byName;\n }),\n ),\n );\n\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(branch);\n return undefined;\n }\n yield* printKeyValue([\n [\"ID\", branch.id],\n [\"Name\", branch.name],\n [\"Project ID\", branch.projectId],\n [\"Updates\", String(branch.updateCount)],\n [\"Created\", branch.createdAt],\n ]);\n return undefined;\n }),\n ),\n});\n\nconst renameCommand = defineCommand({\n meta: { name: \"rename\", description: \"Rename a branch\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Branch ID\" },\n name: { type: \"string\", required: true, description: \"New branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const branch = yield* api.branches.rename({\n path: { id: args.id },\n payload: { name: args.name },\n });\n yield* Console.log(`Branch renamed to \"${branch.name}\".`);\n }),\n ),\n});\n\nconst deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a branch\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Branch ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.branches.delete({ path: { id: args.id } });\n yield* Console.log(`Branch ${args.id} deleted.`);\n }),\n ),\n});\n\nexport const branchesCommand = defineCommand({\n meta: { name: \"branches\", description: \"Manage branches\" },\n subCommands: {\n list: listCommand,\n view: viewCommand,\n create: createCommand,\n rename: renameCommand,\n delete: deleteCommand,\n },\n});\n","export interface RenderSigningGradleInput {\n readonly keystorePath: string;\n readonly storePassword: string;\n readonly keyAlias: string;\n readonly keyPassword: string;\n}\n\n/**\n * Escape a Groovy single-quoted string literal: backslashes, single quotes,\n * and `$` (to prevent string interpolation on Groovy double-quoted strings,\n * though we use single quotes everywhere for safety).\n */\nconst escapeGroovySingleQuoted = (value: string): string =>\n value\n .replaceAll(\"\\\\\", String.raw`\\\\`)\n .replaceAll(\"'\", String.raw`\\'`)\n .replaceAll(\"$\", String.raw`\\$`);\n\n/**\n * Render a Gradle init script that injects a `release` signing config into\n * every Android application module after evaluation. This is passed to\n * `./gradlew --init-script <path>` so the keystore never has to live in the\n * project tree.\n */\nexport const renderSigningGradle = ({\n keystorePath,\n storePassword,\n keyAlias,\n keyPassword,\n}: RenderSigningGradleInput): string =>\n `allprojects {\n afterEvaluate { project ->\n if (project.plugins.hasPlugin('com.android.application')) {\n project.android {\n signingConfigs {\n release {\n storeFile file('${escapeGroovySingleQuoted(keystorePath)}')\n storePassword '${escapeGroovySingleQuoted(storePassword)}'\n keyAlias '${escapeGroovySingleQuoted(keyAlias)}'\n keyPassword '${escapeGroovySingleQuoted(keyPassword)}'\n }\n }\n buildTypes {\n release {\n signingConfig signingConfigs.release\n }\n }\n }\n }\n }\n}\n`;\n","export const capitalize = (value: string): string => {\n const [first] = value;\n return first === undefined ? value : `${first.toUpperCase()}${value.slice(1)}`;\n};\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Option } from \"effect\";\nimport { maxBy } from \"es-toolkit\";\n\nimport type { PlatformError } from \"@effect/platform/Error\";\n\nimport { ArtifactNotFoundError } from \"./exit-codes\";\nimport { capitalize } from \"./string-utils\";\n\nexport interface FindIosArtifactOptions {\n readonly exportPath: string;\n}\n\nexport interface FindAndroidArtifactOptions {\n readonly projectRoot: string;\n readonly format: \"apk\" | \"aab\";\n readonly flavor?: string;\n readonly buildType: \"debug\" | \"release\";\n /**\n * If provided, only artifacts with mtimeMs >= this value are considered.\n * Used to exclude stale artifacts from previous builds when the current\n * build failed to write an expected output.\n */\n readonly minMtimeMs?: number;\n}\n\ninterface FoundFile {\n readonly path: string;\n readonly mtimeMs: number;\n}\n\nconst walkAndFind = (\n root: string,\n extension: string,\n): Effect.Effect<readonly FoundFile[], PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n // No fs.exists pre-check: readDirectory on a missing/non-dir path fails\n // With a PlatformError that we catch into an empty list below.\n const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));\n\n const results: FoundFile[] = [];\n for (const entry of entries) {\n const fullPath = path.join(root, entry);\n const stat = yield* fs.stat(fullPath).pipe(Effect.option);\n if (Option.isSome(stat)) {\n const info = stat.value;\n if (info.type === \"Directory\") {\n const nested = yield* walkAndFind(fullPath, extension);\n results.push(...nested);\n } else if (info.type === \"File\" && entry.toLowerCase().endsWith(extension)) {\n results.push({\n path: fullPath,\n mtimeMs: Option.match(info.mtime, {\n onNone: () => 0,\n onSome: (date) => date.getTime(),\n }),\n });\n }\n }\n }\n return results;\n });\n\nconst newest = (files: readonly FoundFile[], minMtimeMs?: number): FoundFile | undefined => {\n const eligible =\n minMtimeMs === undefined ? files : files.filter((file) => file.mtimeMs >= minMtimeMs);\n return maxBy(eligible, (file) => file.mtimeMs);\n};\n\nexport const findIosArtifact = ({\n exportPath,\n}: FindIosArtifactOptions): Effect.Effect<\n string,\n ArtifactNotFoundError | PlatformError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const files = yield* walkAndFind(exportPath, \".ipa\");\n const picked = newest(files);\n if (!picked) {\n return yield* new ArtifactNotFoundError({\n message: `No .ipa file found under \"${exportPath}\".`,\n });\n }\n return picked.path;\n });\n\nexport const findAndroidArtifact = ({\n projectRoot,\n format,\n flavor,\n buildType,\n minMtimeMs,\n}: FindAndroidArtifactOptions): Effect.Effect<\n string,\n ArtifactNotFoundError | PlatformError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const outputsRoot = path.join(projectRoot, \"android\", \"app\", \"build\", \"outputs\");\n const subdir = format === \"aab\" ? \"bundle\" : \"apk\";\n const variantDir = flavor ? `${flavor}${capitalize(buildType)}` : buildType;\n const expectedDir = path.join(outputsRoot, subdir, variantDir);\n\n const direct = yield* walkAndFind(expectedDir, `.${format}`);\n const pickedDirect = newest(direct, minMtimeMs);\n if (pickedDirect) {\n return pickedDirect.path;\n }\n\n const fallback = yield* walkAndFind(outputsRoot, `.${format}`);\n const pickedFallback = newest(fallback, minMtimeMs);\n if (!pickedFallback) {\n return yield* new ArtifactNotFoundError({\n message: `No .${format} artifact found under \"${outputsRoot}\"${minMtimeMs === undefined ? \"\" : \" (newer than build start)\"}.`,\n });\n }\n return pickedFallback.path;\n });\n","const asUint8Array = (data: Uint8Array | ArrayBuffer): Uint8Array =>\n data instanceof Uint8Array ? data : new Uint8Array(data);\n\nconst toBinaryString = (data: Uint8Array | ArrayBuffer): string =>\n Array.from(asUint8Array(data), (byte) => String.fromCodePoint(byte)).join(\"\");\n\nconst padBase64 = (value: string): string =>\n value.padEnd(value.length + ((4 - (value.length % 4)) % 4), \"=\");\n\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/u;\nconst BASE64_URL_PATTERN = /^[A-Za-z0-9_-]*={0,2}$/u;\nconst HEX_PATTERN = /^(?:[0-9A-Fa-f]{2})*$/u;\n\nconst normalizeBase64 = (value: string): string => {\n const compact = value.replaceAll(/\\s+/gu, \"\");\n if (!BASE64_PATTERN.test(compact) || compact.length % 4 === 1) {\n throw new RangeError(\"Invalid base64 string\");\n }\n return padBase64(compact);\n};\n\nconst normalizeBase64Url = (value: string): string => {\n const compact = value.replaceAll(/\\s+/gu, \"\");\n if (!BASE64_URL_PATTERN.test(compact) || compact.length % 4 === 1) {\n throw new RangeError(\"Invalid base64url string\");\n }\n return compact.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n};\n\nexport const toBase64 = (data: Uint8Array | ArrayBuffer): string => btoa(toBinaryString(data));\n\nexport const fromBase64 = (str: string): Uint8Array<ArrayBuffer> => {\n const binary = atob(normalizeBase64(str));\n return Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);\n};\n\nexport const toBase64Url = (data: Uint8Array | ArrayBuffer): string =>\n toBase64(data).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/u, \"\");\n\nexport const fromBase64Url = (str: string): Uint8Array<ArrayBuffer> =>\n fromBase64(padBase64(normalizeBase64Url(str)));\n\nexport const toHex = (bytes: Uint8Array | ArrayBuffer): string =>\n Array.from(asUint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\nexport const fromHex = (hex: string): Uint8Array<ArrayBuffer> => {\n if (!HEX_PATTERN.test(hex)) {\n throw new RangeError(\"Invalid hex string\");\n }\n return Uint8Array.from(hex.match(/.{2}/gu) ?? [], (byte) => Number.parseInt(byte, 16));\n};\n","import path from \"node:path\";\n\nimport { fromBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { PlatformError } from \"@effect/platform/Error\";\n\nimport { MissingCredentialsError } from \"./exit-codes\";\n\nimport type { ApiClient } from \"../services/api-client\";\nimport type { IosDistribution } from \"./build-profile\";\n\nexport interface DownloadIosCredentialsOptions {\n readonly projectId: string;\n readonly bundleIdentifier: string;\n readonly distribution: IosDistribution;\n readonly tempDir: string;\n}\n\nexport interface IosCredentials {\n readonly p12Path: string;\n readonly p12Password: string;\n readonly profilePath: string;\n readonly profileFilename: string;\n readonly teamId: string;\n}\n\nexport const IOS_DISTRIBUTION_TO_TYPE = {\n \"app-store\": \"APP_STORE\",\n \"ad-hoc\": \"AD_HOC\",\n development: \"DEVELOPMENT\",\n enterprise: \"ENTERPRISE\",\n} as const satisfies Record<IosDistribution, \"APP_STORE\" | \"AD_HOC\" | \"DEVELOPMENT\" | \"ENTERPRISE\">;\n\nconst bindHint =\n \"Bind the bundle via the dashboard (Credentials → iOS Bundle Configurations) and make sure a distribution certificate, provisioning profile, and ASC API key are attached.\";\n\nconst permissionHint = \"Ask an org admin to grant the build-credentials download permission.\";\n\nconst androidBindHint =\n \"Register the package in the dashboard (Credentials → Android Build Credentials) and bind a keystore to the default group.\";\n\ninterface TaggedCause {\n readonly _tag: string;\n readonly message?: string;\n}\n\nconst hasTag = (cause: unknown): cause is TaggedCause =>\n typeof cause === \"object\" && cause !== null && \"_tag\" in cause;\n\nconst resolveErrorToMissingCredentials = (\n cause: unknown,\n platform: \"ios\" | \"android\",\n): MissingCredentialsError => {\n const tag = hasTag(cause) ? cause._tag : null;\n const message = hasTag(cause) && typeof cause.message === \"string\" ? cause.message : null;\n const platformLabel = platform === \"ios\" ? \"iOS\" : \"Android\";\n const bind = platform === \"ios\" ? bindHint : androidBindHint;\n\n if (tag === \"Forbidden\") {\n return new MissingCredentialsError({\n message: message ?? `Permission denied when resolving ${platformLabel} build credentials`,\n hint: permissionHint,\n });\n }\n if (tag === \"NotFound\") {\n return new MissingCredentialsError({\n message: message ?? `No ${platformLabel} build credentials configured`,\n hint: bind,\n });\n }\n if (tag === \"BadRequest\") {\n return new MissingCredentialsError({\n message: message ?? `${platformLabel} build credentials are misconfigured`,\n hint: bind,\n });\n }\n return new MissingCredentialsError({\n message: message ?? `Failed to resolve ${platformLabel} build credentials`,\n hint: bind,\n });\n};\n\nexport const downloadIosCredentials = (\n api: ApiClient,\n options: DownloadIosCredentialsOptions,\n): Effect.Effect<IosCredentials, MissingCredentialsError | PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n\n const resolved = yield* api.buildCredentials\n .resolve({\n path: { projectId: options.projectId },\n payload: {\n platform: \"ios\" as const,\n bundleIdentifier: options.bundleIdentifier,\n distributionType: IOS_DISTRIBUTION_TO_TYPE[options.distribution],\n },\n })\n .pipe(Effect.mapError((cause) => resolveErrorToMissingCredentials(cause, \"ios\")));\n\n if (resolved.platform !== \"ios\") {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"Server returned non-iOS credentials for an iOS build request\",\n hint: bindHint,\n }),\n );\n }\n\n const p12Path = path.join(options.tempDir, \"signing.p12\");\n const profileFilename = `${resolved.provisioningProfile.uuid ?? \"profile\"}.mobileprovision`;\n const profilePath = path.join(options.tempDir, profileFilename);\n\n yield* fs.writeFile(p12Path, fromBase64(resolved.distributionCertificate.p12Base64));\n yield* fs.writeFile(\n profilePath,\n fromBase64(resolved.provisioningProfile.mobileprovisionBase64),\n );\n\n return {\n p12Path,\n p12Password: resolved.distributionCertificate.p12Password,\n profilePath,\n profileFilename,\n teamId: resolved.provisioningProfile.teamId,\n };\n });\n\nexport interface DownloadAndroidCredentialsOptions {\n readonly projectId: string;\n readonly applicationIdentifier: string;\n readonly tempDir: string;\n}\n\nexport interface AndroidCredentials {\n readonly keystorePath: string;\n readonly storePassword: string;\n readonly keyAlias: string;\n readonly keyPassword: string;\n}\n\nexport const downloadAndroidCredentials = (\n api: ApiClient,\n options: DownloadAndroidCredentialsOptions,\n): Effect.Effect<\n AndroidCredentials,\n MissingCredentialsError | PlatformError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n\n const resolved = yield* api.buildCredentials\n .resolve({\n path: { projectId: options.projectId },\n payload: {\n platform: \"android\" as const,\n applicationIdentifier: options.applicationIdentifier,\n },\n })\n .pipe(Effect.mapError((cause) => resolveErrorToMissingCredentials(cause, \"android\")));\n\n if (resolved.platform !== \"android\") {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"Server returned non-Android credentials for an Android build request\",\n hint: androidBindHint,\n }),\n );\n }\n\n const keystorePath = path.join(options.tempDir, \"upload.keystore\");\n yield* fs.writeFile(keystorePath, fromBase64(resolved.keystore.keystoreBase64));\n\n return {\n keystorePath,\n storePassword: resolved.keystore.storePassword,\n keyAlias: resolved.keystore.keyAlias,\n keyPassword: resolved.keystore.keyPassword,\n };\n });\n","import path from \"node:path\";\n\nimport { asRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport { CredentialsJsonError } from \"./exit-codes\";\n\nexport interface IosDistributionCertificateEntry {\n readonly path: string;\n readonly password: string;\n}\n\nexport interface IosPushKeyEntry {\n readonly path: string;\n readonly keyId: string;\n readonly teamId: string;\n}\n\nexport interface IosAscApiKeyEntry {\n readonly path: string;\n readonly keyId: string;\n readonly issuerId: string;\n}\n\nexport interface IosCredentialsEntry {\n readonly provisioningProfilePath: string;\n readonly distributionCertificate: IosDistributionCertificateEntry;\n readonly pushKey?: IosPushKeyEntry;\n readonly ascApiKey?: IosAscApiKeyEntry;\n}\n\nexport interface AndroidKeystoreEntry {\n readonly keystorePath: string;\n readonly keystorePassword: string;\n readonly keyAlias: string;\n readonly keyPassword: string;\n}\n\nexport interface AndroidGoogleServiceAccountEntry {\n readonly path: string;\n}\n\nexport interface AndroidCredentialsEntry {\n readonly keystore: AndroidKeystoreEntry;\n readonly googleServiceAccountKey?: AndroidGoogleServiceAccountEntry;\n}\n\nexport interface CredentialsJson {\n readonly ios?: IosCredentialsEntry;\n readonly android?: AndroidCredentialsEntry;\n}\n\nexport const CREDENTIALS_JSON_FILENAME = \"credentials.json\";\n\nconst asString = (value: unknown, field: string): Effect.Effect<string, CredentialsJsonError> =>\n typeof value === \"string\" && value.length > 0\n ? Effect.succeed(value)\n : Effect.fail(\n new CredentialsJsonError({\n message: `credentials.json: field \"${field}\" must be a non-empty string.`,\n }),\n );\n\nconst parseIosDistributionCertificate = (\n raw: unknown,\n): Effect.Effect<IosDistributionCertificateEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: \"credentials.json: ios.distributionCertificate must be an object.\",\n });\n }\n return {\n path: yield* asString(record[\"path\"], \"ios.distributionCertificate.path\"),\n password: yield* asString(record[\"password\"], \"ios.distributionCertificate.password\"),\n } satisfies IosDistributionCertificateEntry;\n });\n\nconst parseIosPushKey = (raw: unknown): Effect.Effect<IosPushKeyEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: \"credentials.json: ios.pushKey must be an object.\",\n });\n }\n return {\n path: yield* asString(record[\"path\"], \"ios.pushKey.path\"),\n keyId: yield* asString(record[\"keyId\"], \"ios.pushKey.keyId\"),\n teamId: yield* asString(record[\"teamId\"], \"ios.pushKey.teamId\"),\n } satisfies IosPushKeyEntry;\n });\n\nconst parseIosAscApiKey = (raw: unknown): Effect.Effect<IosAscApiKeyEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: \"credentials.json: ios.ascApiKey must be an object.\",\n });\n }\n return {\n path: yield* asString(record[\"path\"], \"ios.ascApiKey.path\"),\n keyId: yield* asString(record[\"keyId\"], \"ios.ascApiKey.keyId\"),\n issuerId: yield* asString(record[\"issuerId\"], \"ios.ascApiKey.issuerId\"),\n } satisfies IosAscApiKeyEntry;\n });\n\nconst parseIos = (raw: unknown): Effect.Effect<IosCredentialsEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: 'credentials.json: \"ios\" must be an object.',\n });\n }\n const provisioningProfilePath = yield* asString(\n record[\"provisioningProfilePath\"],\n \"ios.provisioningProfilePath\",\n );\n const distributionCertificate = yield* parseIosDistributionCertificate(\n record[\"distributionCertificate\"],\n );\n const pushKey =\n record[\"pushKey\"] === undefined ? undefined : yield* parseIosPushKey(record[\"pushKey\"]);\n const ascApiKey =\n record[\"ascApiKey\"] === undefined ? undefined : yield* parseIosAscApiKey(record[\"ascApiKey\"]);\n return {\n provisioningProfilePath,\n distributionCertificate,\n ...(pushKey === undefined ? {} : { pushKey }),\n ...(ascApiKey === undefined ? {} : { ascApiKey }),\n } satisfies IosCredentialsEntry;\n });\n\nconst parseAndroidKeystore = (\n raw: unknown,\n): Effect.Effect<AndroidKeystoreEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: \"credentials.json: android.keystore must be an object.\",\n });\n }\n return {\n keystorePath: yield* asString(record[\"keystorePath\"], \"android.keystore.keystorePath\"),\n keystorePassword: yield* asString(\n record[\"keystorePassword\"],\n \"android.keystore.keystorePassword\",\n ),\n keyAlias: yield* asString(record[\"keyAlias\"], \"android.keystore.keyAlias\"),\n keyPassword: yield* asString(record[\"keyPassword\"], \"android.keystore.keyPassword\"),\n } satisfies AndroidKeystoreEntry;\n });\n\nconst parseGoogleServiceAccountKey = (\n raw: unknown,\n): Effect.Effect<AndroidGoogleServiceAccountEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: \"credentials.json: android.googleServiceAccountKey must be an object.\",\n });\n }\n return {\n path: yield* asString(record[\"path\"], \"android.googleServiceAccountKey.path\"),\n } satisfies AndroidGoogleServiceAccountEntry;\n });\n\nconst parseAndroid = (raw: unknown): Effect.Effect<AndroidCredentialsEntry, CredentialsJsonError> =>\n Effect.gen(function* () {\n const record = asRecord(raw);\n if (!record) {\n return yield* new CredentialsJsonError({\n message: 'credentials.json: \"android\" must be an object.',\n });\n }\n const keystore = yield* parseAndroidKeystore(record[\"keystore\"]);\n const googleServiceAccountKey =\n record[\"googleServiceAccountKey\"] === undefined\n ? undefined\n : yield* parseGoogleServiceAccountKey(record[\"googleServiceAccountKey\"]);\n return {\n keystore,\n ...(googleServiceAccountKey === undefined ? {} : { googleServiceAccountKey }),\n } satisfies AndroidCredentialsEntry;\n });\n\nexport const parseCredentialsJson = (\n raw: string,\n): Effect.Effect<CredentialsJson, CredentialsJsonError> =>\n Effect.gen(function* () {\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(raw),\n catch: () => new CredentialsJsonError({ message: \"credentials.json is not valid JSON.\" }),\n });\n const root = asRecord(parsed);\n if (!root) {\n return yield* new CredentialsJsonError({\n message: \"credentials.json must be a JSON object at the top level.\",\n });\n }\n const ios = root[\"ios\"] === undefined ? undefined : yield* parseIos(root[\"ios\"]);\n const android =\n root[\"android\"] === undefined ? undefined : yield* parseAndroid(root[\"android\"]);\n if (!ios && !android) {\n return yield* new CredentialsJsonError({\n message: 'credentials.json must contain at least one of \"ios\" or \"android\".',\n });\n }\n return {\n ...(ios === undefined ? {} : { ios }),\n ...(android === undefined ? {} : { android }),\n } satisfies CredentialsJson;\n });\n\nexport const credentialsJsonPath = (projectRoot: string): string =>\n path.join(projectRoot, CREDENTIALS_JSON_FILENAME);\n\nexport const readCredentialsJson = (\n projectRoot: string,\n): Effect.Effect<CredentialsJson, CredentialsJsonError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const filePath = credentialsJsonPath(projectRoot);\n const exists = yield* fs.exists(filePath).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (!exists) {\n return yield* new CredentialsJsonError({\n message: `credentials.json not found at ${filePath}.`,\n });\n }\n const raw = yield* fs.readFileString(filePath).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to read credentials.json: ${String(cause)}`,\n }),\n ),\n );\n return yield* parseCredentialsJson(raw);\n });\n\nexport const writeCredentialsJson = (\n projectRoot: string,\n data: CredentialsJson,\n): Effect.Effect<string, CredentialsJsonError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const filePath = credentialsJsonPath(projectRoot);\n const body = `${JSON.stringify(data, null, 2)}\\n`;\n yield* fs.writeFileString(filePath, body).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to write credentials.json: ${String(cause)}`,\n }),\n ),\n );\n return filePath;\n });\n\n/**\n * Resolve a path that may be either absolute or relative to the project root.\n */\nexport const resolveCredentialPath = (projectRoot: string, candidate: string): string =>\n path.isAbsolute(candidate) ? candidate : path.join(projectRoot, candidate);\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport { readCredentialsJson, resolveCredentialPath } from \"./credentials-json\";\nimport { MissingCredentialsError } from \"./exit-codes\";\n\nimport type { AndroidCredentials, IosCredentials } from \"./credentials-downloader\";\n\nconst requirePath = (\n fs: FileSystem.FileSystem,\n absolutePath: string,\n label: string,\n): Effect.Effect<void, MissingCredentialsError> =>\n fs.exists(absolutePath).pipe(\n Effect.catchAll(() => Effect.succeed(false)),\n Effect.flatMap((exists) =>\n exists\n ? Effect.void\n : Effect.fail(\n new MissingCredentialsError({\n message: `Local credentials.json: ${label} not found at ${absolutePath}.`,\n hint: \"Run `better-update credentials sync pull` to materialize files, or fix the path in credentials.json.\",\n }),\n ),\n ),\n );\n\nexport interface LoadLocalIosCredentialsOptions {\n readonly projectRoot: string;\n}\n\nexport const loadLocalIosCredentials = (\n options: LoadLocalIosCredentialsOptions,\n): Effect.Effect<IosCredentials, MissingCredentialsError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const data = yield* readCredentialsJson(options.projectRoot).pipe(\n Effect.mapError(\n (cause) =>\n new MissingCredentialsError({\n message: `Local credentials.json: ${cause.message}`,\n hint: 'Create credentials.json or switch the build profile\\'s credentialsSource back to \"remote\".',\n }),\n ),\n );\n if (!data.ios) {\n return yield* new MissingCredentialsError({\n message: \"credentials.json has no `ios` section but the build is for iOS.\",\n hint: \"Add an `ios` block to credentials.json or switch credentialsSource to remote.\",\n });\n }\n const p12Path = resolveCredentialPath(\n options.projectRoot,\n data.ios.distributionCertificate.path,\n );\n const profilePath = resolveCredentialPath(\n options.projectRoot,\n data.ios.provisioningProfilePath,\n );\n yield* requirePath(fs, p12Path, \"distribution certificate (.p12)\");\n yield* requirePath(fs, profilePath, \"provisioning profile (.mobileprovision)\");\n return {\n p12Path,\n p12Password: data.ios.distributionCertificate.password,\n profilePath,\n profileFilename: path.basename(profilePath),\n teamId: \"\",\n };\n });\n\nexport interface LoadLocalAndroidCredentialsOptions {\n readonly projectRoot: string;\n}\n\nexport const loadLocalAndroidCredentials = (\n options: LoadLocalAndroidCredentialsOptions,\n): Effect.Effect<AndroidCredentials, MissingCredentialsError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const data = yield* readCredentialsJson(options.projectRoot).pipe(\n Effect.mapError(\n (cause) =>\n new MissingCredentialsError({\n message: `Local credentials.json: ${cause.message}`,\n hint: 'Create credentials.json or switch the build profile\\'s credentialsSource back to \"remote\".',\n }),\n ),\n );\n if (!data.android) {\n return yield* new MissingCredentialsError({\n message: \"credentials.json has no `android` section but the build is for Android.\",\n hint: \"Add an `android` block to credentials.json or switch credentialsSource to remote.\",\n });\n }\n const keystorePath = resolveCredentialPath(\n options.projectRoot,\n data.android.keystore.keystorePath,\n );\n yield* requirePath(fs, keystorePath, \"keystore\");\n return {\n keystorePath,\n storePassword: data.android.keystore.keystorePassword,\n keyAlias: data.android.keystore.keyAlias,\n keyPassword: data.android.keystore.keyPassword,\n };\n });\n","import { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\n\nimport { toBase64Url } from \"@better-update/encoding\";\nimport { Effect } from \"effect\";\n\nimport { BuildFailedError } from \"./exit-codes\";\n\nexport interface Sha256FileResult {\n readonly sha256: string;\n readonly byteSize: number;\n}\n\nexport interface Sha256FileBase64UrlResult {\n readonly sha256Base64Url: string;\n readonly byteSize: number;\n}\n\nconst hashReadError = (message: string) =>\n new BuildFailedError({\n step: \"sha256\",\n exitCode: 1,\n message,\n });\n\nconst hashFile = <TDigest>(\n path: string,\n formatDigest: (digest: Buffer) => TDigest,\n): Effect.Effect<{ digest: TDigest; byteSize: number }, BuildFailedError> =>\n Effect.async<{ digest: TDigest; byteSize: number }, BuildFailedError>((resume) => {\n const hash = createHash(\"sha256\");\n const stream = createReadStream(path);\n let byteSize = 0;\n\n stream.on(\"data\", (chunk) => {\n const buffer = typeof chunk === \"string\" ? Buffer.from(chunk) : chunk;\n byteSize += buffer.byteLength;\n hash.update(buffer);\n });\n stream.on(\"error\", (error) => {\n resume(Effect.fail(hashReadError(`Failed to read file for SHA-256: ${error.message}`)));\n });\n stream.on(\"end\", () => {\n resume(\n Effect.succeed({\n digest: formatDigest(hash.digest()),\n byteSize,\n }),\n );\n });\n });\n\n/**\n * Compute the SHA-256 digest and byte size of a file using Node's streaming\n * hash API. The file is never fully loaded into memory — chunks flow through\n * `createReadStream` into `crypto.createHash(\"sha256\")`.\n */\nexport const sha256File = (path: string): Effect.Effect<Sha256FileResult, BuildFailedError> =>\n hashFile(path, (digest) => digest.toString(\"hex\")).pipe(\n Effect.map(({ digest, byteSize }) => ({ sha256: digest, byteSize })),\n );\n\nexport const sha256FileBase64Url = (\n path: string,\n): Effect.Effect<Sha256FileBase64UrlResult, BuildFailedError> =>\n hashFile(path, toBase64Url).pipe(\n Effect.map(({ digest, byteSize }) => ({ sha256Base64Url: digest, byteSize })),\n );\n\n/**\n * Compute a content-type-namespaced hash: `SHA-256(contentType + '\\0' + SHA-256_hex(fileBytes))`.\n *\n * This prevents hash collisions when identical bytes are served with different\n * MIME types (e.g. same file used as both `application/javascript` and `text/plain`).\n * The raw content hash is still needed separately for R2 upload verification.\n */\nexport const sha256Namespaced = (contentType: string, contentSha256Hex: string): string => {\n const input = `${contentType}\\0${contentSha256Hex}`;\n return toBase64Url(createHash(\"sha256\").update(input).digest());\n};\n","import process from \"node:process\";\n\nimport { Command } from \"@effect/platform\";\nimport { Effect, Fiber, Stream } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { Scope } from \"effect\";\n\nimport { BuildFailedError } from \"../../lib/exit-codes\";\n\nimport type { XcodebuildFormatter } from \"../../lib/xcpretty-formatter\";\n\nexport const runStep = (\n cmd: Command.Command,\n step: string,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor> =>\n Command.exitCode(cmd.pipe(Command.stdout(\"inherit\"), Command.stderr(\"inherit\"))).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} failed to spawn: ${String(cause)}`,\n }),\n ),\n Effect.flatMap((code) =>\n code === 0\n ? Effect.void\n : Effect.fail(\n new BuildFailedError({\n step,\n exitCode: code,\n message: `${step} exited with code ${code}`,\n }),\n ),\n ),\n );\n\n/**\n * Run a build step with stdout piped through a formatter (e.g., xcpretty).\n * stderr passes through to the terminal directly.\n */\nexport const runStepFormatted = (\n cmd: Command.Command,\n step: string,\n formatter: XcodebuildFormatter,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor | Scope.Scope> =>\n Effect.gen(function* () {\n const proc = yield* Command.start(\n cmd.pipe(Command.stdout(\"pipe\"), Command.stderr(\"pipe\")),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} failed to spawn: ${String(cause)}`,\n }),\n ),\n );\n\n const stdoutFiber = yield* proc.stdout.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => {\n const formatted = formatter.pipe(line);\n return formatted.length > 0\n ? Effect.sync(() => {\n for (const output of formatted) {\n process.stdout.write(`${output}\\n`);\n }\n })\n : Effect.void;\n }),\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} stdout stream error: ${String(cause)}`,\n }),\n ),\n Effect.fork,\n );\n\n const stderrFiber = yield* proc.stderr.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => Effect.sync(() => process.stderr.write(`${line}\\n`))),\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} stderr stream error: ${String(cause)}`,\n }),\n ),\n Effect.fork,\n );\n\n // Join fibers concurrently — stream errors are non-fatal, exit code takes precedence.\n yield* Effect.all([Fiber.join(stdoutFiber), Fiber.join(stderrFiber)], {\n concurrency: 2,\n }).pipe(Effect.catchAll(() => Effect.void));\n\n const code = yield* proc.exitCode.pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} exit code error: ${String(cause)}`,\n }),\n ),\n );\n\n if (code !== 0) {\n // Print build summary on failure for xcpretty diagnostics\n const summary = formatter.getBuildSummary();\n if (summary) {\n process.stderr.write(`${summary}\\n`);\n }\n\n return yield* new BuildFailedError({\n step,\n exitCode: code,\n message: `${step} exited with code ${code}`,\n });\n }\n return undefined;\n });\n","import path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { PlatformError } from \"@effect/platform/Error\";\n\nimport { renderSigningGradle } from \"../../lib/android-signing-gradle\";\nimport { findAndroidArtifact } from \"../../lib/artifact-finder\";\nimport { downloadAndroidCredentials } from \"../../lib/credentials-downloader\";\nimport { loadLocalAndroidCredentials } from \"../../lib/local-credentials\";\nimport { sha256File } from \"../../lib/sha256\";\nimport { capitalize } from \"../../lib/string-utils\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\nimport { runStep } from \"./run-step\";\n\nimport type { AndroidProfile, CredentialsSource } from \"../../lib/build-profile\";\nimport type {\n ArtifactNotFoundError,\n BuildFailedError,\n MissingCredentialsError,\n} from \"../../lib/exit-codes\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nexport interface RunAndroidBuildInput {\n readonly api: ApiClient;\n readonly tempDir: string;\n readonly projectRoot: string;\n readonly androidProfile: AndroidProfile;\n readonly applicationIdentifier: string;\n readonly envVars: Record<string, string>;\n readonly projectId: string;\n readonly credentialsSource: CredentialsSource;\n}\n\nexport interface RunAndroidBuildResult {\n readonly artifactPath: string;\n readonly byteSize: number;\n readonly sha256: string;\n}\n\n/**\n * Compose the Gradle task name from flavor, format, and buildType.\n *\n * Gradle naming convention: `<verb><Flavor><Variant>`, e.g.\n * - no flavor + apk + release → `assembleRelease`\n * - no flavor + aab + release → `bundleRelease`\n * - flavor=prod + aab + release → `bundleProdRelease`\n * - flavor=prod + apk + debug → `assembleProdDebug`\n */\nconst gradleTaskName = (\n format: \"apk\" | \"aab\",\n flavor: string | undefined,\n buildType: \"debug\" | \"release\",\n): string => {\n const verb = format === \"aab\" ? \"bundle\" : \"assemble\";\n return flavor\n ? `${verb}${capitalize(flavor)}${capitalize(buildType)}`\n : `${verb}${capitalize(buildType)}`;\n};\n\nexport const runAndroidBuild = (\n input: RunAndroidBuildInput,\n): Effect.Effect<\n RunAndroidBuildResult,\n BuildFailedError | MissingCredentialsError | ArtifactNotFoundError | PlatformError,\n CliRuntime | CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const { api, tempDir, projectRoot, androidProfile, applicationIdentifier, envVars, projectId } =\n input;\n const runtime = yield* CliRuntime;\n\n // Record build start so artifact-finder can reject stale outputs from\n // Earlier builds that may still live in `android/app/build/outputs/`.\n const buildStartMs = Date.now();\n\n const { format } = androidProfile;\n const { flavor } = androidProfile;\n const buildType = androidProfile.buildType ?? \"release\";\n const androidDir = path.join(projectRoot, \"android\");\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n\n const credentials =\n input.credentialsSource === \"local\"\n ? yield* loadLocalAndroidCredentials({ projectRoot })\n : yield* downloadAndroidCredentials(api, {\n projectId,\n applicationIdentifier,\n tempDir,\n });\n\n yield* runStep(\n Command.make(\"bunx\", \"expo\", \"prebuild\", \"--platform\", \"android\", \"--clean\").pipe(\n Command.workingDirectory(projectRoot),\n Command.env(commandEnv),\n ),\n \"expo prebuild android\",\n );\n\n const fs = yield* FileSystem.FileSystem;\n const signingGradlePath = path.join(tempDir, \"signing.gradle\");\n yield* fs.writeFileString(\n signingGradlePath,\n renderSigningGradle({\n keystorePath: credentials.keystorePath,\n storePassword: credentials.storePassword,\n keyAlias: credentials.keyAlias,\n keyPassword: credentials.keyPassword,\n }),\n );\n\n const taskName = gradleTaskName(format, flavor, buildType);\n yield* runStep(\n Command.make(\"./gradlew\", \"--init-script\", signingGradlePath, `:app:${taskName}`).pipe(\n Command.workingDirectory(androidDir),\n Command.env(commandEnv),\n ),\n \"gradlew\",\n );\n\n const artifactPath = yield* findAndroidArtifact({\n projectRoot,\n format,\n ...(flavor === undefined ? {} : { flavor }),\n buildType,\n minMtimeMs: buildStartMs,\n });\n\n const { sha256, byteSize } = yield* sha256File(artifactPath);\n\n return { artifactPath, byteSize, sha256 };\n });\n","export type ExportMethod = \"app-store\" | \"ad-hoc\" | \"enterprise\" | \"development\";\n\nexport interface RenderExportOptionsPlistInput {\n readonly method: ExportMethod;\n readonly teamId: string;\n readonly bundleId: string;\n readonly provisioningProfileName: string;\n readonly compileBitcode?: boolean;\n}\n\nconst escapeXml = (value: string): string =>\n value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n\nconst boolTag = (value: boolean): string => (value ? \"<true/>\" : \"<false/>\");\n\n/**\n * Render an Xcode `ExportOptions.plist` for `xcodebuild -exportArchive`.\n *\n * - `signingStyle` is always `manual` (ephemeral keychain + downloaded profile)\n * - `uploadSymbols` is emitted only for `app-store` exports\n * - `provisioningProfiles` dict maps bundleId → profile name\n * - `compileBitcode` defaults to `false`\n */\nexport const renderExportOptionsPlist = ({\n method,\n teamId,\n bundleId,\n provisioningProfileName,\n compileBitcode = false,\n}: RenderExportOptionsPlistInput): string => {\n const lines: string[] = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n \"<dict>\",\n \"\\t<key>method</key>\",\n `\\t<string>${escapeXml(method)}</string>`,\n \"\\t<key>teamID</key>\",\n `\\t<string>${escapeXml(teamId)}</string>`,\n \"\\t<key>signingStyle</key>\",\n \"\\t<string>manual</string>\",\n \"\\t<key>compileBitcode</key>\",\n `\\t${boolTag(compileBitcode)}`,\n \"\\t<key>provisioningProfiles</key>\",\n \"\\t<dict>\",\n `\\t\\t<key>${escapeXml(bundleId)}</key>`,\n `\\t\\t<string>${escapeXml(provisioningProfileName)}</string>`,\n \"\\t</dict>\",\n ];\n\n if (method === \"app-store\") {\n lines.push(\"\\t<key>uploadSymbols</key>\", \"\\t<true/>\");\n }\n\n lines.push(\"</dict>\", \"</plist>\", \"\");\n return lines.join(\"\\n\");\n};\n","import { randomBytes, randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { Command } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { Scope } from \"effect\";\n\nimport { KeychainError } from \"./exit-codes\";\n\nexport interface AcquireKeychainOptions {\n readonly tempDir: string;\n readonly p12Path: string;\n readonly p12Password: string;\n}\n\nexport interface KeychainHandle {\n readonly keychainName: string;\n readonly keychainPath: string;\n readonly signingIdentity: string;\n}\n\n// ── shell helpers ─────────────────────────────────────────────────\n\nconst runOrFail = (\n cmd: Command.Command,\n step: string,\n): Effect.Effect<string, KeychainError, CommandExecutor.CommandExecutor> =>\n Command.string(cmd).pipe(\n Effect.mapError(\n (cause) =>\n new KeychainError({\n message: `keychain ${step} failed: ${String(cause)}`,\n }),\n ),\n );\n\nconst listCurrentKeychains = Effect.gen(function* () {\n // `security list-keychains -d user` returns each keychain path on its own line,\n // Surrounded by double quotes and optionally preceded by whitespace.\n const output = yield* runOrFail(\n Command.make(\"security\", \"list-keychains\", \"-d\", \"user\"),\n \"list-keychains\",\n );\n return output\n .split(\"\\n\")\n .map((line) => line.trim().replace(/^\"/u, \"\").replace(/\"$/u, \"\"))\n .filter((line) => line.length > 0);\n});\n\n// Parse `security find-identity -v <keychain>` output to extract the first\n// Signing identity. Lines look like:\n// 1) 1A2B3C4D... \"Apple Distribution: Your Name (TEAMID)\"\nconst parseSigningIdentity = (output: string): string | undefined => {\n const lines = output.split(\"\\n\");\n for (const line of lines) {\n const match = /\"([^\"]+)\"/u.exec(line);\n if (match?.[1]) {\n return match[1];\n }\n }\n return undefined;\n};\n\n// ── acquireRelease ────────────────────────────────────────────────\n\n/**\n * Acquire an ephemeral macOS keychain, import a `.p12` into it, add it to the\n * user search list, and tear it all down on scope close. The keychain name is\n * namespaced as `better-update-<uuid>` and lives in `$tempDir`, so cleanup is\n * guaranteed under all termination paths.\n */\nexport const acquireKeychain = ({\n tempDir,\n p12Path,\n p12Password,\n}: AcquireKeychainOptions): Effect.Effect<\n KeychainHandle,\n KeychainError,\n CommandExecutor.CommandExecutor | Scope.Scope\n> => {\n const keychainName = `better-update-${randomUUID()}.keychain-db`;\n const keychainPath = path.join(tempDir, keychainName);\n const keychainPassword = randomBytes(32).toString(\"hex\");\n\n return Effect.acquireRelease(\n // ── acquire ─────────────────────────────────────────────────\n Effect.gen(function* () {\n const priorKeychains = yield* listCurrentKeychains;\n\n yield* runOrFail(\n Command.make(\"security\", \"create-keychain\", \"-p\", keychainPassword, keychainPath),\n \"create-keychain\",\n );\n\n yield* runOrFail(\n Command.make(\"security\", \"unlock-keychain\", \"-p\", keychainPassword, keychainPath),\n \"unlock-keychain\",\n );\n\n yield* runOrFail(\n Command.make(\"security\", \"set-keychain-settings\", \"-t\", \"3600\", \"-l\", keychainPath),\n \"set-keychain-settings\",\n );\n\n yield* runOrFail(\n Command.make(\n \"security\",\n \"import\",\n p12Path,\n \"-k\",\n keychainPath,\n \"-P\",\n p12Password,\n \"-T\",\n \"/usr/bin/codesign\",\n ),\n \"import\",\n );\n\n yield* runOrFail(\n Command.make(\n \"security\",\n \"set-key-partition-list\",\n \"-S\",\n \"apple-tool:,apple:,codesign:\",\n \"-s\",\n \"-k\",\n keychainPassword,\n keychainPath,\n ),\n \"set-key-partition-list\",\n );\n\n // Prepend our keychain to the search list while preserving the user's\n // Existing ones.\n yield* runOrFail(\n Command.make(\n \"security\",\n \"list-keychains\",\n \"-d\",\n \"user\",\n \"-s\",\n keychainPath,\n ...priorKeychains,\n ),\n \"list-keychains -s (add)\",\n );\n\n const identitiesOutput = yield* runOrFail(\n Command.make(\"security\", \"find-identity\", \"-v\", \"-p\", \"codesigning\", keychainPath),\n \"find-identity\",\n );\n const signingIdentity = parseSigningIdentity(identitiesOutput);\n if (!signingIdentity) {\n return yield* new KeychainError({\n message: \"No code signing identity found after importing .p12 into ephemeral keychain.\",\n });\n }\n\n return {\n handle: { keychainName, keychainPath, signingIdentity },\n priorKeychains,\n };\n }),\n\n // ── release ─────────────────────────────────────────────────\n ({ priorKeychains }) =>\n Effect.gen(function* () {\n // Restore the original search list first, then delete our keychain.\n yield* Command.string(\n Command.make(\"security\", \"list-keychains\", \"-d\", \"user\", \"-s\", ...priorKeychains),\n ).pipe(Effect.catchAll(() => Effect.void));\n\n yield* Command.string(Command.make(\"security\", \"delete-keychain\", keychainPath)).pipe(\n Effect.catchAll(() => Effect.void),\n );\n }),\n ).pipe(Effect.map(({ handle }) => handle));\n};\n","import plist from \"@expo/plist\";\n\nimport type { PlistObject } from \"@expo/plist\";\n// eslint-disable-next-line import-plugin/no-namespace -- bplist-parser typings have no named export; used only as `typeof BplistParser` for the CJS require result\nimport type * as BplistParser from \"bplist-parser\";\n\nexport type { PlistObject, PlistValue } from \"@expo/plist\";\n\n/**\n * Parse an XML plist string into a typed object.\n * Throws on malformed XML — callers should wrap in Effect.try.\n */\nexport const parsePlistXml = (xml: string): PlistObject =>\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- @expo/plist.parse returns `any`; PlistObject is the library's declared shape for XML plists\n plist.parse(xml) as PlistObject;\n\n/**\n * Parse a binary plist buffer into a typed object.\n * Uses bplist-parser for Apple's binary plist format.\n */\nexport const parsePlistBinary = (buffer: Buffer): PlistObject => {\n const bplistParser =\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CJS require returns `any`; narrow to the package's own typings at the boundary\n require(\"bplist-parser\") as typeof BplistParser;\n // eslint-disable-next-line typescript/no-unsafe-assignment -- bplist-parser typings declare parseBuffer<T>(): T[] with T=any in the shipped .d.ts\n const [result] = bplistParser.parseBuffer(buffer);\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- bplist-parser typings return `any[]`; PlistObject is the superset shape we consume\n return result as PlistObject;\n};\n\nconst BPLIST_MAGIC = Buffer.from(\"bplist00\");\n\n/**\n * Auto-detect plist format (binary vs XML) and parse accordingly.\n */\nexport const parsePlist = (data: Buffer): PlistObject =>\n data.subarray(0, 8).equals(BPLIST_MAGIC)\n ? parsePlistBinary(data)\n : parsePlistXml(data.toString(\"utf8\"));\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { Scope } from \"effect\";\n\nimport { ProvisioningError } from \"./exit-codes\";\nimport { parsePlistXml } from \"./plist\";\n\nimport type { PlistObject } from \"./plist\";\n\n// ── pure extraction ───────────────────────────────────────────────\n\nexport interface ProvisioningInfo {\n readonly uuid: string;\n readonly name: string;\n readonly teamId: string;\n}\n\nconst getString = (obj: PlistObject, key: string): string | undefined => {\n const value = obj[key];\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst getFirstArrayString = (obj: PlistObject, key: string): string | undefined => {\n const value = obj[key];\n if (Array.isArray(value) && typeof value[0] === \"string\") {\n return value[0];\n }\n return undefined;\n};\n\n/**\n * Extract `UUID`, `Name`, and the first `TeamIdentifier` from the XML plist\n * output of `security cms -D -i <path>`. Returns `ProvisioningError` when any\n * of the three fields are missing.\n */\nexport const extractProvisioningInfo = (\n plistXml: string,\n): Effect.Effect<ProvisioningInfo, ProvisioningError> =>\n Effect.gen(function* () {\n const parsed: PlistObject = yield* Effect.try({\n try: () => parsePlistXml(plistXml),\n catch: (error) =>\n new ProvisioningError({\n message: `Failed to parse provisioning profile plist: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n const uuid = getString(parsed, \"UUID\");\n const name = getString(parsed, \"Name\");\n const teamId = getFirstArrayString(parsed, \"TeamIdentifier\");\n\n if (!uuid || !name || !teamId) {\n return yield* new ProvisioningError({\n message:\n `Failed to parse provisioning profile: missing ${uuid ? \"\" : \"UUID \"}${name ? \"\" : \"Name \"}${teamId ? \"\" : \"TeamIdentifier \"}`.trim(),\n });\n }\n\n return { uuid, name, teamId };\n });\n\n// ── scoped installation ───────────────────────────────────────────\n\nexport interface InstallProvisioningProfileOptions {\n readonly profilePath: string;\n}\n\nexport interface InstalledProvisioning {\n readonly uuid: string;\n readonly name: string;\n readonly teamId: string;\n readonly installedPath: string;\n}\n\ninterface AcquiredProvisioning extends InstalledProvisioning {\n /**\n * True if we installed the profile (so release should delete it).\n * False if the profile was already present (e.g., installed by Xcode) —\n * in that case we leave it alone on release to avoid breaking the user's\n * other signing operations.\n */\n readonly ownsInstallation: boolean;\n}\n\nconst userProvisioningProfilesDir = (): string =>\n path.join(os.homedir(), \"Library\", \"MobileDevice\", \"Provisioning Profiles\");\n\n/**\n * Scoped installation of a provisioning profile: parses its metadata via\n * `security cms -D -i`, copies it into `~/Library/MobileDevice/Provisioning Profiles`\n * under `<uuid>.mobileprovision`, and removes the copy on scope close — but\n * only if we installed it. If the target file already existed when we arrived\n * (e.g., Xcode had it), we leave both the file and the contents untouched.\n */\nexport const installProvisioningProfile = ({\n profilePath,\n}: InstallProvisioningProfileOptions): Effect.Effect<\n InstalledProvisioning,\n ProvisioningError,\n CommandExecutor.CommandExecutor | FileSystem.FileSystem | Scope.Scope\n> =>\n Effect.acquireRelease(\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n\n const plistXml = yield* Command.string(\n Command.make(\"security\", \"cms\", \"-D\", \"-i\", profilePath),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new ProvisioningError({\n message: `security cms -D failed for ${profilePath}: ${String(cause)}`,\n }),\n ),\n );\n\n const info = yield* extractProvisioningInfo(plistXml);\n const targetDir = userProvisioningProfilesDir();\n const installedPath = path.join(targetDir, `${info.uuid}.mobileprovision`);\n\n yield* fs.makeDirectory(targetDir, { recursive: true }).pipe(\n Effect.catchAll(\n (cause) =>\n new ProvisioningError({\n message: `Failed to create provisioning profiles dir: ${String(cause)}`,\n }),\n ),\n );\n\n const alreadyInstalled = yield* fs\n .exists(installedPath)\n .pipe(Effect.orElseSucceed(() => false));\n\n if (alreadyInstalled) {\n return {\n ...info,\n installedPath,\n ownsInstallation: false,\n } satisfies AcquiredProvisioning;\n }\n\n yield* fs.copyFile(profilePath, installedPath).pipe(\n Effect.catchAll(\n (cause) =>\n new ProvisioningError({\n message: `Failed to copy provisioning profile into ${installedPath}: ${String(cause)}`,\n }),\n ),\n );\n\n return {\n ...info,\n installedPath,\n ownsInstallation: true,\n } satisfies AcquiredProvisioning;\n }),\n (acquired) =>\n Effect.gen(function* () {\n if (!acquired.ownsInstallation) {\n return;\n }\n const fs = yield* FileSystem.FileSystem;\n yield* fs.remove(acquired.installedPath).pipe(Effect.catchAll(() => Effect.void));\n }),\n ).pipe(\n Effect.map<AcquiredProvisioning, InstalledProvisioning>(\n ({ uuid, name, teamId, installedPath }) => ({\n uuid,\n name,\n teamId,\n installedPath,\n }),\n ),\n );\n","import path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { parsePlist, parsePlistXml } from \"./plist\";\n\nexport interface IosValidationParams {\n readonly archivePath: string;\n readonly expectedBundleId: string;\n readonly expectedTeamId: string;\n readonly expectedProfileUuid: string;\n}\n\nexport interface ValidationResult {\n readonly passed: boolean;\n readonly warnings: readonly string[];\n}\n\n/**\n * Validate an iOS build after xcodebuild completes. Checks:\n * 1. Bundle ID matches expected value\n * 2. Provisioning profile UUID matches\n * 3. Team ID matches\n *\n * All checks are non-blocking — returns warnings, never fails the build.\n */\nexport const validateIosBuild = (\n params: IosValidationParams,\n): Effect.Effect<\n ValidationResult,\n never,\n CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const appDir = yield* findAppDirectory(params.archivePath).pipe(\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n\n if (!appDir) {\n const warnings = [\"Could not locate .app bundle in archive — skipping post-build validation\"];\n return { passed: false, warnings };\n }\n\n const bundleWarning = yield* checkBundleId(appDir, params.expectedBundleId).pipe(\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n\n const profileWarnings = yield* checkEmbeddedProfile(\n appDir,\n params.expectedProfileUuid,\n params.expectedTeamId,\n ).pipe(Effect.catchAll(() => Effect.succeed([] as readonly string[])));\n\n const warnings: readonly string[] = [\n ...(bundleWarning ? [bundleWarning] : []),\n ...profileWarnings,\n ];\n\n if (warnings.length > 0) {\n yield* Console.warn(\"Post-build validation warnings:\");\n for (const warning of warnings) {\n yield* Console.warn(` - ${warning}`);\n }\n }\n\n return { passed: warnings.length === 0, warnings };\n });\n\n// ── helpers ──────────────────────────────────────────────────────\n\nconst findAppDirectory = (\n archivePath: string,\n): Effect.Effect<string, unknown, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const productsDir = path.join(archivePath, \"Products\", \"Applications\");\n const entries = yield* fs.readDirectory(productsDir);\n const appEntry = entries.find((entry) => entry.endsWith(\".app\"));\n if (!appEntry) {\n return yield* Effect.fail(\"No .app found\");\n }\n return path.join(productsDir, appEntry);\n });\n\nconst checkBundleId = (\n appDir: string,\n expectedBundleId: string,\n): Effect.Effect<string | undefined, unknown, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const plistPath = path.join(appDir, \"Info.plist\");\n const data = yield* fs.readFile(plistPath);\n const parsed = parsePlist(Buffer.from(data));\n const actualBundleId = parsed[\"CFBundleIdentifier\"];\n\n if (typeof actualBundleId === \"string\" && actualBundleId !== expectedBundleId) {\n return `Bundle ID mismatch: expected \"${expectedBundleId}\", got \"${actualBundleId}\"`;\n }\n return undefined;\n });\n\nconst checkEmbeddedProfile = (\n appDir: string,\n expectedUuid: string,\n expectedTeamId: string,\n): Effect.Effect<\n readonly string[],\n unknown,\n CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const warnings: string[] = [];\n const profilePath = path.join(appDir, \"embedded.mobileprovision\");\n\n // Use security cms to decrypt the profile (it's CMS-signed)\n const plistXml = yield* Command.string(\n Command.make(\"security\", \"cms\", \"-D\", \"-i\", profilePath),\n );\n\n const parsed = parsePlistXml(plistXml);\n\n const actualUuid = parsed[\"UUID\"];\n if (typeof actualUuid === \"string\" && actualUuid !== expectedUuid) {\n warnings.push(`Profile UUID mismatch: expected \"${expectedUuid}\", got \"${actualUuid}\"`);\n }\n\n const teamIdentifiers = parsed[\"TeamIdentifier\"];\n if (Array.isArray(teamIdentifiers)) {\n // eslint-disable-next-line typescript/no-unsafe-assignment -- @expo/plist types array entries as any; narrowed via typeof check below\n const [actualTeamId] = teamIdentifiers;\n if (typeof actualTeamId === \"string\" && actualTeamId !== expectedTeamId) {\n warnings.push(`Team ID mismatch: expected \"${expectedTeamId}\", got \"${actualTeamId}\"`);\n }\n }\n\n // Check expiration\n const expirationDate = parsed[\"ExpirationDate\"];\n if (expirationDate instanceof Date && expirationDate.getTime() < Date.now()) {\n warnings.push(`Embedded provisioning profile expired on ${expirationDate.toISOString()}`);\n }\n\n return warnings;\n });\n","import { ExpoRunFormatter } from \"@expo/xcpretty\";\n\nexport interface XcodebuildFormatter {\n /** Feed a line of raw xcodebuild output. Returns formatted lines (0 or more). */\n readonly pipe: (line: string) => readonly string[];\n /** Get a build summary after the process completes. */\n readonly getBuildSummary: () => string;\n}\n\n/**\n * Create a stateful xcodebuild output formatter backed by `@expo/xcpretty`.\n * Each `pipe(line)` call may return zero or more formatted lines — zero means\n * the line was suppressed (e.g., intermediate compiler invocations).\n */\nexport const createXcodebuildFormatter = (projectRoot: string): XcodebuildFormatter => {\n const formatter = ExpoRunFormatter.create(projectRoot);\n return {\n pipe: (line: string) => formatter.pipe(line),\n getBuildSummary: () => formatter.getBuildSummary(),\n };\n};\n","import path from \"node:path\";\n\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\nimport type { PlatformError } from \"@effect/platform/Error\";\nimport type { Scope } from \"effect\";\n\nimport { findIosArtifact } from \"../../lib/artifact-finder\";\nimport { downloadIosCredentials } from \"../../lib/credentials-downloader\";\nimport { ArtifactNotFoundError, BuildFailedError } from \"../../lib/exit-codes\";\nimport { renderExportOptionsPlist } from \"../../lib/ios-export-options\";\nimport { acquireKeychain } from \"../../lib/ios-keychain\";\nimport { installProvisioningProfile } from \"../../lib/ios-provisioning\";\nimport { loadLocalIosCredentials } from \"../../lib/local-credentials\";\nimport { validateIosBuild } from \"../../lib/post-build-validation\";\nimport { sha256File } from \"../../lib/sha256\";\nimport { createXcodebuildFormatter } from \"../../lib/xcpretty-formatter\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\nimport { runStep, runStepFormatted } from \"./run-step\";\n\nimport type { CredentialsSource, IosProfile } from \"../../lib/build-profile\";\nimport type {\n KeychainError,\n MissingCredentialsError,\n ProvisioningError,\n} from \"../../lib/exit-codes\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nexport interface RunIosBuildInput {\n readonly api: ApiClient;\n readonly tempDir: string;\n readonly projectRoot: string;\n readonly iosProfile: IosProfile;\n readonly bundleId: string;\n readonly envVars: Record<string, string>;\n readonly projectId: string;\n readonly credentialsSource: CredentialsSource;\n readonly rawOutput?: boolean | undefined;\n}\n\nexport interface RunIosBuildResult {\n readonly artifactPath: string;\n readonly byteSize: number;\n readonly sha256: string;\n}\n\nconst findXcworkspace = (\n iosDir: string,\n): Effect.Effect<string, BuildFailedError | PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const entries = yield* fs.readDirectory(iosDir);\n const workspace = entries.find((entry) => entry.endsWith(\".xcworkspace\"));\n if (!workspace) {\n return yield* new BuildFailedError({\n step: \"detect xcworkspace\",\n exitCode: 1,\n message: `No .xcworkspace found under ${iosDir}. Did \"pod install\" run?`,\n });\n }\n return workspace;\n });\n\ntype IosBuildRequiredServices =\n | CliRuntime\n | CommandExecutor.CommandExecutor\n | FileSystem.FileSystem\n | Scope.Scope;\n\ntype IosBuildErrors =\n | BuildFailedError\n | MissingCredentialsError\n | KeychainError\n | ProvisioningError\n | ArtifactNotFoundError\n | PlatformError;\n\nconst prebuildAndPods = (params: {\n readonly projectRoot: string;\n readonly iosDir: string;\n readonly commandEnv: Record<string, string>;\n}) =>\n Effect.gen(function* () {\n yield* runStep(\n Command.make(\"bunx\", \"expo\", \"prebuild\", \"--platform\", \"ios\", \"--clean\").pipe(\n Command.workingDirectory(params.projectRoot),\n Command.env(params.commandEnv),\n ),\n \"expo prebuild ios\",\n );\n yield* runStep(\n Command.make(\"pod\", \"install\").pipe(\n Command.workingDirectory(params.iosDir),\n Command.env(params.commandEnv),\n ),\n \"pod install\",\n );\n });\n\nconst findAppDirectory = (\n root: string,\n): Effect.Effect<string, ArtifactNotFoundError | PlatformError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const stack = [root];\n let depth = 0;\n while (stack.length > 0 && depth < 6) {\n const layer = stack.splice(0);\n depth += 1;\n for (const dir of layer) {\n const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));\n for (const entry of entries) {\n const full = path.join(dir, entry);\n if (entry.endsWith(\".app\")) {\n return full;\n }\n const stat = yield* fs.stat(full).pipe(Effect.option);\n if (stat._tag === \"Some\" && stat.value.type === \"Directory\") {\n stack.push(full);\n }\n }\n }\n }\n return yield* new ArtifactNotFoundError({\n message: `No .app bundle found under \"${root}\".`,\n });\n });\n\nconst runIosSimulatorBuild = (\n input: RunIosBuildInput,\n): Effect.Effect<RunIosBuildResult, IosBuildErrors, IosBuildRequiredServices> =>\n Effect.gen(function* () {\n const { projectRoot, iosProfile, envVars, tempDir } = input;\n const runtime = yield* CliRuntime;\n const iosDir = path.join(projectRoot, \"ios\");\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n\n yield* prebuildAndPods({ projectRoot, iosDir, commandEnv });\n\n const workspaceFilename = yield* findXcworkspace(iosDir);\n const scheme = iosProfile.scheme ?? workspaceFilename.replace(/\\.xcworkspace$/u, \"\");\n const configuration = iosProfile.buildConfiguration ?? \"Release\";\n const derivedDataPath = path.join(tempDir, \"derived-data\");\n\n const buildCmd = Command.make(\n \"xcodebuild\",\n \"-workspace\",\n workspaceFilename,\n \"-scheme\",\n scheme,\n \"-configuration\",\n configuration,\n \"-sdk\",\n \"iphonesimulator\",\n \"-destination\",\n \"generic/platform=iOS Simulator\",\n \"-derivedDataPath\",\n derivedDataPath,\n \"build\",\n \"CODE_SIGNING_ALLOWED=NO\",\n \"CODE_SIGNING_REQUIRED=NO\",\n \"CODE_SIGN_IDENTITY=\",\n ).pipe(Command.workingDirectory(iosDir), Command.env(commandEnv));\n\n const formatter = input.rawOutput ? undefined : createXcodebuildFormatter(projectRoot);\n yield* formatter\n ? runStepFormatted(buildCmd, \"xcodebuild build (simulator)\", formatter)\n : runStep(buildCmd, \"xcodebuild build (simulator)\");\n\n const productsRoot = path.join(\n derivedDataPath,\n \"Build\",\n \"Products\",\n `${configuration}-iphonesimulator`,\n );\n const appDir = yield* findAppDirectory(productsRoot);\n const archiveName = `${path.basename(appDir, \".app\")}-simulator.tar.gz`;\n const archivePath = path.join(tempDir, archiveName);\n yield* runStep(\n Command.make(\n \"tar\",\n \"-czf\",\n archivePath,\n \"-C\",\n path.dirname(appDir),\n path.basename(appDir),\n ).pipe(Command.env(commandEnv)),\n \"tar simulator .app\",\n );\n\n const { sha256, byteSize } = yield* sha256File(archivePath);\n return { artifactPath: archivePath, byteSize, sha256 };\n });\n\nconst runIosDeviceBuild = (\n input: RunIosBuildInput,\n): Effect.Effect<RunIosBuildResult, IosBuildErrors, IosBuildRequiredServices> =>\n // eslint-disable-next-line eslint/max-statements -- ios device build orchestration is inherently sequential (prebuild → pod → credentials → archive → exportArchive → find artifact → sha256); splitting further fragments the pipeline without clarifying it\n Effect.gen(function* () {\n const { api, tempDir, projectRoot, iosProfile, bundleId, envVars, projectId } = input;\n const runtime = yield* CliRuntime;\n\n const iosDir = path.join(projectRoot, \"ios\");\n const { distribution } = iosProfile;\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n\n const credentials =\n input.credentialsSource === \"local\"\n ? yield* loadLocalIosCredentials({ projectRoot })\n : yield* downloadIosCredentials(api, {\n projectId,\n bundleIdentifier: bundleId,\n distribution,\n tempDir,\n });\n\n yield* prebuildAndPods({ projectRoot, iosDir, commandEnv });\n\n const keychain = yield* acquireKeychain({\n tempDir,\n p12Path: credentials.p12Path,\n p12Password: credentials.p12Password,\n });\n\n const provisioning = yield* installProvisioningProfile({\n profilePath: credentials.profilePath,\n });\n\n const workspaceFilename = yield* findXcworkspace(iosDir);\n const scheme = iosProfile.scheme ?? workspaceFilename.replace(/\\.xcworkspace$/u, \"\");\n const configuration = iosProfile.buildConfiguration ?? \"Release\";\n\n const archivePath = path.join(tempDir, \"build.xcarchive\");\n const archiveCmd = Command.make(\n \"xcodebuild\",\n \"-workspace\",\n workspaceFilename,\n \"-scheme\",\n scheme,\n \"-configuration\",\n configuration,\n \"-archivePath\",\n archivePath,\n \"-allowProvisioningUpdates\",\n \"archive\",\n \"CODE_SIGN_STYLE=Manual\",\n `DEVELOPMENT_TEAM=${provisioning.teamId}`,\n `CODE_SIGN_IDENTITY=${keychain.signingIdentity}`,\n `PROVISIONING_PROFILE_SPECIFIER=${provisioning.name}`,\n ).pipe(Command.workingDirectory(iosDir), Command.env(commandEnv));\n\n const formatter = input.rawOutput ? undefined : createXcodebuildFormatter(projectRoot);\n yield* formatter\n ? runStepFormatted(archiveCmd, \"xcodebuild archive\", formatter)\n : runStep(archiveCmd, \"xcodebuild archive\");\n\n const fs = yield* FileSystem.FileSystem;\n const exportOptionsPath = path.join(tempDir, \"ExportOptions.plist\");\n yield* fs.writeFileString(\n exportOptionsPath,\n renderExportOptionsPlist({\n method: distribution,\n teamId: provisioning.teamId,\n bundleId,\n provisioningProfileName: provisioning.name,\n }),\n );\n\n const exportPath = path.join(tempDir, \"export\");\n const exportCmd = Command.make(\n \"xcodebuild\",\n \"-exportArchive\",\n \"-archivePath\",\n archivePath,\n \"-exportPath\",\n exportPath,\n \"-exportOptionsPlist\",\n exportOptionsPath,\n \"-allowProvisioningUpdates\",\n ).pipe(Command.workingDirectory(iosDir), Command.env(commandEnv));\n\n yield* formatter\n ? runStepFormatted(exportCmd, \"xcodebuild exportArchive\", formatter)\n : runStep(exportCmd, \"xcodebuild exportArchive\");\n\n yield* validateIosBuild({\n archivePath,\n expectedBundleId: bundleId,\n expectedTeamId: provisioning.teamId,\n expectedProfileUuid: provisioning.uuid,\n });\n\n const artifactPath = yield* findIosArtifact({ exportPath });\n const { sha256, byteSize } = yield* sha256File(artifactPath);\n\n return { artifactPath, byteSize, sha256 };\n });\n\nexport const runIosBuild = (\n input: RunIosBuildInput,\n): Effect.Effect<RunIosBuildResult, IosBuildErrors, IosBuildRequiredServices> =>\n input.iosProfile.simulator === true ? runIosSimulatorBuild(input) : runIosDeviceBuild(input);\n","import { Effect } from \"effect\";\n\nimport { CompleteError, ReserveError } from \"../../lib/exit-codes\";\nimport { formatCause } from \"../../lib/format-error\";\nimport { PresignedUploadClient } from \"../../services/presigned-upload\";\n\nimport type { PresignedUrlExpiredError, UploadFailedError } from \"../../lib/exit-codes\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nexport type BuildTarget =\n | {\n readonly platform: \"ios\";\n readonly distribution: \"app-store\" | \"ad-hoc\" | \"development\" | \"enterprise\";\n readonly artifactFormat: \"ipa\";\n }\n | {\n readonly platform: \"ios\";\n readonly distribution: \"simulator\";\n readonly artifactFormat: \"tar.gz\";\n }\n | {\n readonly platform: \"android\";\n readonly distribution: \"play-store\";\n readonly artifactFormat: \"aab\";\n }\n | {\n readonly platform: \"android\";\n readonly distribution: \"direct\";\n readonly artifactFormat: \"apk\";\n };\n\nexport interface ReserveAndUploadInput {\n readonly target: BuildTarget;\n readonly projectId: string;\n readonly profileName: string;\n readonly runtimeVersion: string;\n readonly appVersion?: string;\n readonly buildNumber?: string;\n readonly bundleId: string;\n readonly gitContext: {\n readonly ref?: string;\n readonly commit?: string;\n readonly dirty: boolean;\n };\n readonly message?: string;\n readonly artifactPath: string;\n readonly sha256: string;\n readonly byteSize: number;\n}\n\nconst buildReserveCommon = (input: ReserveAndUploadInput) =>\n ({\n projectId: input.projectId,\n profile: input.profileName,\n runtimeVersion: input.runtimeVersion,\n bundleId: input.bundleId,\n sha256: input.sha256,\n byteSize: input.byteSize,\n ...(input.appVersion === undefined ? {} : { appVersion: input.appVersion }),\n ...(input.buildNumber === undefined ? {} : { buildNumber: input.buildNumber }),\n ...(input.gitContext.ref === undefined ? {} : { gitRef: input.gitContext.ref }),\n ...(input.gitContext.commit === undefined ? {} : { gitCommit: input.gitContext.commit }),\n ...(input.message === undefined ? {} : { message: input.message }),\n }) as const;\n\nconst callReserve = (api: ApiClient, input: ReserveAndUploadInput) => {\n const common = buildReserveCommon(input);\n const { target } = input;\n if (target.platform === \"ios\") {\n return target.distribution === \"simulator\"\n ? api.builds.reserve({\n payload: {\n ...common,\n platform: \"ios\",\n distribution: \"simulator\",\n artifactFormat: \"tar.gz\",\n },\n })\n : api.builds.reserve({\n payload: {\n ...common,\n platform: \"ios\",\n distribution: target.distribution,\n artifactFormat: \"ipa\",\n },\n });\n }\n return target.distribution === \"play-store\"\n ? api.builds.reserve({\n payload: {\n ...common,\n platform: \"android\",\n distribution: \"play-store\",\n artifactFormat: \"aab\",\n },\n })\n : api.builds.reserve({\n payload: { ...common, platform: \"android\", distribution: \"direct\", artifactFormat: \"apk\" },\n });\n};\n\nexport interface ReserveAndUploadResult {\n readonly id: string;\n readonly status: string;\n}\n\n/**\n * Reserve a build record on the server, upload the artifact to the returned\n * presigned URL, and finalize the build with its sha256 + byteSize.\n */\nexport const reserveAndUpload = (\n api: ApiClient,\n input: ReserveAndUploadInput,\n): Effect.Effect<\n ReserveAndUploadResult,\n ReserveError | UploadFailedError | PresignedUrlExpiredError | CompleteError,\n PresignedUploadClient\n> =>\n Effect.gen(function* () {\n const presignedUploadClient = yield* PresignedUploadClient;\n\n const reserveResult = yield* callReserve(api, input).pipe(\n Effect.mapError(\n (cause) =>\n new ReserveError({\n message: `Failed to reserve build: ${formatCause(cause)}`,\n }),\n ),\n );\n\n yield* presignedUploadClient.putToPresignedUrl({\n url: reserveResult.uploadUrl,\n filePath: input.artifactPath,\n byteSize: input.byteSize,\n expiresAt: reserveResult.uploadExpiresAt,\n headers: reserveResult.uploadHeaders,\n });\n\n const completed = yield* api.builds\n .complete({\n path: { id: reserveResult.id },\n payload: { sha256: input.sha256, byteSize: input.byteSize },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new CompleteError({\n message: `Failed to complete build ${reserveResult.id}: ${formatCause(cause)}`,\n }),\n ),\n );\n\n if (!completed.artifact) {\n return yield* new CompleteError({\n message: `Build ${completed.id} completed but server returned no artifact record.`,\n });\n }\n\n return { id: completed.id, status: \"uploaded\" };\n });\n","import { asRecord } from \"@better-update/type-guards\";\nimport { FileSystem, Path } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport { BuildProfileError } from \"./exit-codes\";\nimport { formatCause } from \"./format-error\";\n\nexport type EasDistribution = \"internal\" | \"store\";\n\nexport type EasIosDistributionOverride = \"app-store\" | \"ad-hoc\" | \"development\" | \"enterprise\";\n\nexport interface EasIosProfile {\n readonly distribution?: EasIosDistributionOverride;\n readonly buildConfiguration?: string;\n readonly scheme?: string;\n readonly simulator?: boolean;\n readonly enterpriseProvisioning?: \"adhoc\" | \"universal\";\n}\n\nexport interface EasAndroidProfile {\n readonly buildType?: \"debug\" | \"release\";\n readonly flavor?: string;\n readonly gradleCommand?: string;\n readonly format?: \"apk\" | \"aab\";\n readonly distribution?: \"play-store\" | \"direct\";\n}\n\nexport type EasCredentialsSource = \"remote\" | \"local\";\n\nexport interface EasBuildProfile {\n readonly extends?: string;\n readonly developmentClient?: boolean;\n readonly distribution?: EasDistribution;\n readonly channel?: string;\n readonly environment?: string;\n readonly env?: Record<string, string>;\n readonly ios?: EasIosProfile;\n readonly android?: EasAndroidProfile;\n readonly credentialsSource?: EasCredentialsSource;\n}\n\nexport interface EasConfig {\n readonly cli?: { readonly version?: string };\n readonly build?: Record<string, EasBuildProfile>;\n}\n\nconst MAX_EXTENDS_DEPTH = 10;\n\nconst asStringValue = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined;\n\nconst asBooleanValue = (value: unknown): boolean | undefined =>\n typeof value === \"boolean\" ? value : undefined;\n\nconst asEnv = (value: unknown): Record<string, string> | undefined => {\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n const env: Record<string, string> = {};\n for (const [key, raw] of Object.entries(record)) {\n if (typeof raw === \"string\") {\n env[key] = raw;\n }\n }\n return Object.keys(env).length === 0 ? undefined : env;\n};\n\nconst asIosDistribution = (raw: unknown): EasIosDistributionOverride | undefined => {\n const value = asStringValue(raw);\n if (\n value === \"app-store\" ||\n value === \"ad-hoc\" ||\n value === \"development\" ||\n value === \"enterprise\"\n ) {\n return value;\n }\n return undefined;\n};\n\nconst asEnterpriseProvisioning = (raw: unknown): \"adhoc\" | \"universal\" | undefined => {\n const value = asStringValue(raw);\n return value === \"adhoc\" || value === \"universal\" ? value : undefined;\n};\n\nconst asAndroidBuildType = (raw: unknown): \"debug\" | \"release\" | undefined => {\n const value = asStringValue(raw);\n return value === \"debug\" || value === \"release\" ? value : undefined;\n};\n\nconst asAndroidFormat = (raw: unknown): \"apk\" | \"aab\" | undefined => {\n const value = asStringValue(raw);\n return value === \"apk\" || value === \"aab\" ? value : undefined;\n};\n\nconst asAndroidDistribution = (raw: unknown): \"play-store\" | \"direct\" | undefined => {\n const value = asStringValue(raw);\n return value === \"play-store\" || value === \"direct\" ? value : undefined;\n};\n\nconst asEasDistribution = (raw: unknown): EasDistribution | undefined => {\n const value = asStringValue(raw);\n return value === \"internal\" || value === \"store\" ? value : undefined;\n};\n\nconst asCredentialsSource = (raw: unknown): EasCredentialsSource | undefined => {\n const value = asStringValue(raw);\n return value === \"remote\" || value === \"local\" ? value : undefined;\n};\n\nconst parseIosProfile = (raw: unknown): EasIosProfile | undefined => {\n const record = asRecord(raw);\n if (!record) {\n return undefined;\n }\n const distribution = asIosDistribution(record[\"distribution\"]);\n const buildConfiguration = asStringValue(record[\"buildConfiguration\"]);\n const scheme = asStringValue(record[\"scheme\"]);\n const simulator = asBooleanValue(record[\"simulator\"]);\n const enterpriseProvisioning = asEnterpriseProvisioning(record[\"enterpriseProvisioning\"]);\n return {\n ...(distribution === undefined ? {} : { distribution }),\n ...(buildConfiguration === undefined ? {} : { buildConfiguration }),\n ...(scheme === undefined ? {} : { scheme }),\n ...(simulator === undefined ? {} : { simulator }),\n ...(enterpriseProvisioning === undefined ? {} : { enterpriseProvisioning }),\n };\n};\n\nconst parseAndroidProfile = (raw: unknown): EasAndroidProfile | undefined => {\n const record = asRecord(raw);\n if (!record) {\n return undefined;\n }\n const buildType = asAndroidBuildType(record[\"buildType\"]);\n const flavor = asStringValue(record[\"flavor\"]);\n const gradleCommand = asStringValue(record[\"gradleCommand\"]);\n const format = asAndroidFormat(record[\"format\"]);\n const distribution = asAndroidDistribution(record[\"distribution\"]);\n return {\n ...(buildType === undefined ? {} : { buildType }),\n ...(flavor === undefined ? {} : { flavor }),\n ...(gradleCommand === undefined ? {} : { gradleCommand }),\n ...(format === undefined ? {} : { format }),\n ...(distribution === undefined ? {} : { distribution }),\n };\n};\n\nconst parseBuildProfile = (raw: unknown): EasBuildProfile | undefined => {\n const record = asRecord(raw);\n if (!record) {\n return undefined;\n }\n const extendsName = asStringValue(record[\"extends\"]);\n const developmentClient = asBooleanValue(record[\"developmentClient\"]);\n const distribution = asEasDistribution(record[\"distribution\"]);\n const channel = asStringValue(record[\"channel\"]);\n const environment = asStringValue(record[\"environment\"]);\n const env = asEnv(record[\"env\"]);\n const ios = parseIosProfile(record[\"ios\"]);\n const android = parseAndroidProfile(record[\"android\"]);\n const credentialsSource = asCredentialsSource(record[\"credentialsSource\"]);\n return {\n ...(extendsName === undefined ? {} : { extends: extendsName }),\n ...(developmentClient === undefined ? {} : { developmentClient }),\n ...(distribution === undefined ? {} : { distribution }),\n ...(channel === undefined ? {} : { channel }),\n ...(environment === undefined ? {} : { environment }),\n ...(env === undefined ? {} : { env }),\n ...(ios === undefined ? {} : { ios }),\n ...(android === undefined ? {} : { android }),\n ...(credentialsSource === undefined ? {} : { credentialsSource }),\n };\n};\n\nexport const parseEasConfig = (text: string): Effect.Effect<EasConfig, BuildProfileError> =>\n Effect.gen(function* () {\n const parsed = yield* Effect.try({\n try: () => JSON.parse(text) as unknown,\n catch: (cause) =>\n new BuildProfileError({\n message: `eas.json is not valid JSON: ${formatCause(cause)}`,\n }),\n });\n const root = asRecord(parsed);\n if (!root) {\n return yield* new BuildProfileError({\n message: \"eas.json must be a JSON object at the top level.\",\n });\n }\n const buildRecord = asRecord(root[\"build\"]);\n if (!buildRecord) {\n return asRecord(root[\"cli\"]) ? { cli: parseCli(root[\"cli\"]) } : {};\n }\n const profiles: Record<string, EasBuildProfile> = {};\n for (const [name, value] of Object.entries(buildRecord)) {\n const profile = parseBuildProfile(value);\n if (profile) {\n profiles[name] = profile;\n }\n }\n return {\n ...(asRecord(root[\"cli\"]) ? { cli: parseCli(root[\"cli\"]) } : {}),\n build: profiles,\n };\n });\n\nconst parseCli = (raw: unknown): { readonly version?: string } => {\n const record = asRecord(raw);\n if (!record) {\n return {};\n }\n const version = asStringValue(record[\"version\"]);\n return version === undefined ? {} : { version };\n};\n\nconst easJsonPath = (projectRoot: string): Effect.Effect<string, never, Path.Path> =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n return path.join(projectRoot, \"eas.json\");\n });\n\nexport const readEasJson = (\n projectRoot: string,\n): Effect.Effect<EasConfig, BuildProfileError, FileSystem.FileSystem | Path.Path> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const filePath = yield* easJsonPath(projectRoot);\n const text = yield* fs.readFileString(filePath).pipe(\n Effect.catchAll((cause) =>\n Effect.fail(\n new BuildProfileError({\n message:\n cause._tag === \"SystemError\" && cause.reason === \"NotFound\"\n ? `No eas.json found at ${filePath}. Create one with a \"build\" section.`\n : `Failed to read eas.json: ${cause.message}`,\n }),\n ),\n ),\n );\n return yield* parseEasConfig(text);\n });\n\nconst mergeIos = (\n base: EasIosProfile | undefined,\n overlay: EasIosProfile | undefined,\n): EasIosProfile | undefined => {\n if (!base) {\n return overlay;\n }\n if (!overlay) {\n return base;\n }\n return { ...base, ...overlay };\n};\n\nconst mergeAndroid = (\n base: EasAndroidProfile | undefined,\n overlay: EasAndroidProfile | undefined,\n): EasAndroidProfile | undefined => {\n if (!base) {\n return overlay;\n }\n if (!overlay) {\n return base;\n }\n return { ...base, ...overlay };\n};\n\nconst mergeEnv = (\n base: Record<string, string> | undefined,\n overlay: Record<string, string> | undefined,\n): Record<string, string> | undefined => {\n if (!base) {\n return overlay;\n }\n if (!overlay) {\n return base;\n }\n return { ...base, ...overlay };\n};\n\nconst mergeProfile = (base: EasBuildProfile, overlay: EasBuildProfile): EasBuildProfile => {\n const ios = mergeIos(base.ios, overlay.ios);\n const android = mergeAndroid(base.android, overlay.android);\n const env = mergeEnv(base.env, overlay.env);\n const developmentClient = overlay.developmentClient ?? base.developmentClient;\n const distribution = overlay.distribution ?? base.distribution;\n const channel = overlay.channel ?? base.channel;\n const environment = overlay.environment ?? base.environment;\n const credentialsSource = overlay.credentialsSource ?? base.credentialsSource;\n return {\n ...(overlay.extends === undefined ? {} : { extends: overlay.extends }),\n ...(developmentClient === undefined ? {} : { developmentClient }),\n ...(distribution === undefined ? {} : { distribution }),\n ...(channel === undefined ? {} : { channel }),\n ...(environment === undefined ? {} : { environment }),\n ...(env === undefined ? {} : { env }),\n ...(ios === undefined ? {} : { ios }),\n ...(android === undefined ? {} : { android }),\n ...(credentialsSource === undefined ? {} : { credentialsSource }),\n };\n};\n\nconst collectExtendsChain = (\n profiles: Record<string, EasBuildProfile>,\n profileName: string,\n): Effect.Effect<readonly EasBuildProfile[], BuildProfileError> =>\n Effect.gen(function* () {\n const chain: EasBuildProfile[] = [];\n const visited = new Set<string>();\n let current: string | undefined = profileName;\n let depth = 0;\n while (current !== undefined) {\n if (visited.has(current)) {\n return yield* new BuildProfileError({\n message: `Cycle detected in eas.json build.${profileName} extends chain at \"${current}\".`,\n });\n }\n visited.add(current);\n const profile: EasBuildProfile | undefined = profiles[current];\n if (!profile) {\n return yield* new BuildProfileError({\n message:\n current === profileName\n ? `Build profile \"${profileName}\" not found in eas.json.`\n : `Build profile \"${profileName}\" extends missing profile \"${current}\".`,\n });\n }\n chain.unshift(profile);\n current = profile.extends;\n depth += 1;\n if (depth > MAX_EXTENDS_DEPTH) {\n return yield* new BuildProfileError({\n message: `Too many \"extends\" levels (max ${String(MAX_EXTENDS_DEPTH)}) in eas.json build.${profileName}.`,\n });\n }\n }\n return chain;\n });\n\nconst stripExtends = (profile: EasBuildProfile): EasBuildProfile => {\n if (profile.extends === undefined) {\n return profile;\n }\n const { extends: _omit, ...rest } = profile;\n return rest;\n};\n\nexport const resolveEasBuildProfile = (\n config: EasConfig,\n profileName: string,\n): Effect.Effect<EasBuildProfile, BuildProfileError> =>\n Effect.gen(function* () {\n const profiles = config.build;\n if (!profiles) {\n return yield* new BuildProfileError({\n message: 'eas.json has no \"build\" section. Add at least one profile.',\n });\n }\n const chain = yield* collectExtendsChain(profiles, profileName);\n const merged = chain.reduce<EasBuildProfile>(\n (acc, next, index) => (index === 0 ? next : mergeProfile(acc, next)),\n {},\n );\n return stripExtends(merged);\n });\n","import { asRecord } from \"@better-update/type-guards\";\nimport { Effect } from \"effect\";\n\nimport type { FileSystem, Path } from \"@effect/platform\";\n\nimport { readEasJson, resolveEasBuildProfile } from \"./eas-config\";\n\nimport type { EasAndroidProfile, EasBuildProfile, EasIosProfile } from \"./eas-config\";\nimport type { BuildProfileError } from \"./exit-codes\";\nimport type { ExpoConfig } from \"./expo-config\";\n\nexport type Platform = \"ios\" | \"android\";\n\nexport type IosDistribution = \"app-store\" | \"ad-hoc\" | \"development\" | \"enterprise\";\n\nexport interface IosProfile {\n readonly buildConfiguration?: string;\n readonly distribution: IosDistribution;\n readonly scheme?: string;\n readonly simulator?: boolean;\n}\n\nexport type AndroidDistribution = \"play-store\" | \"direct\";\n\nexport interface AndroidProfile {\n readonly buildType?: \"debug\" | \"release\";\n readonly format: \"apk\" | \"aab\";\n readonly flavor?: string;\n readonly distribution: AndroidDistribution;\n readonly gradleCommand?: string;\n}\n\nexport type CredentialsSource = \"remote\" | \"local\";\n\nexport interface BuildProfile {\n readonly name: string;\n readonly environment: string;\n readonly channel?: string;\n readonly env?: Record<string, string>;\n readonly ios?: IosProfile;\n readonly android?: AndroidProfile;\n readonly credentialsSource?: CredentialsSource;\n}\n\nexport type RawRuntimeVersion = string | { readonly policy: string };\n\nexport interface AppMeta {\n readonly bundleId: string | undefined;\n readonly androidPackage: string | undefined;\n readonly appVersion: string | undefined;\n readonly buildNumber: string | undefined;\n readonly rawRuntimeVersion: RawRuntimeVersion | undefined;\n}\n\nexport interface RuntimeVersionMeta {\n readonly appVersion: string | undefined;\n readonly rawRuntimeVersion: RawRuntimeVersion | undefined;\n}\n\nexport const asString = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined;\n\nconst deriveIosDistribution = (eas: EasBuildProfile): IosDistribution | undefined => {\n const override = eas.ios?.distribution;\n if (override) {\n return override;\n }\n if (eas.developmentClient === true) {\n return \"development\";\n }\n if (eas.distribution === \"internal\") {\n return \"ad-hoc\";\n }\n if (eas.distribution === \"store\") {\n return \"app-store\";\n }\n return undefined;\n};\n\nconst deriveAndroidFormat = (eas: EasBuildProfile): \"apk\" | \"aab\" | undefined => {\n if (eas.android?.format) {\n return eas.android.format;\n }\n if (eas.distribution === \"store\") {\n return \"aab\";\n }\n if (eas.distribution === \"internal\") {\n return \"apk\";\n }\n if (eas.developmentClient === true) {\n return \"apk\";\n }\n return undefined;\n};\n\nconst deriveAndroidDistribution = (\n eas: EasBuildProfile,\n format: \"apk\" | \"aab\",\n): AndroidDistribution => {\n if (eas.android?.distribution) {\n return eas.android.distribution;\n }\n if (format === \"aab\") {\n return \"play-store\";\n }\n return \"direct\";\n};\n\nconst hasIosIntent = (eas: EasBuildProfile): boolean =>\n eas.ios !== undefined || eas.distribution !== undefined || eas.developmentClient === true;\n\nconst hasAndroidIntent = (eas: EasBuildProfile): boolean =>\n eas.android !== undefined || eas.distribution !== undefined || eas.developmentClient === true;\n\nconst toIosProfile = (eas: EasBuildProfile): IosProfile | undefined => {\n if (!hasIosIntent(eas)) {\n return undefined;\n }\n const distribution = deriveIosDistribution(eas);\n if (!distribution) {\n return undefined;\n }\n const ios: EasIosProfile = eas.ios ?? {};\n return {\n distribution,\n ...(ios.buildConfiguration === undefined ? {} : { buildConfiguration: ios.buildConfiguration }),\n ...(ios.scheme === undefined ? {} : { scheme: ios.scheme }),\n ...(ios.simulator === undefined ? {} : { simulator: ios.simulator }),\n };\n};\n\nconst toAndroidProfile = (eas: EasBuildProfile): AndroidProfile | undefined => {\n if (!hasAndroidIntent(eas)) {\n return undefined;\n }\n const format = deriveAndroidFormat(eas);\n if (!format) {\n return undefined;\n }\n const android: EasAndroidProfile = eas.android ?? {};\n const distribution = deriveAndroidDistribution(eas, format);\n return {\n format,\n distribution,\n ...(android.buildType === undefined ? {} : { buildType: android.buildType }),\n ...(android.flavor === undefined ? {} : { flavor: android.flavor }),\n ...(android.gradleCommand === undefined ? {} : { gradleCommand: android.gradleCommand }),\n };\n};\n\nexport const fromEasProfile = (eas: EasBuildProfile, profileName: string): BuildProfile => {\n const ios = toIosProfile(eas);\n const android = toAndroidProfile(eas);\n return {\n name: profileName,\n environment: eas.environment ?? \"production\",\n ...(eas.channel === undefined ? {} : { channel: eas.channel }),\n ...(eas.env === undefined ? {} : { env: eas.env }),\n ...(ios === undefined ? {} : { ios }),\n ...(android === undefined ? {} : { android }),\n ...(eas.credentialsSource === undefined ? {} : { credentialsSource: eas.credentialsSource }),\n };\n};\n\nexport const readBuildProfile = (\n projectRoot: string,\n profileName: string,\n): Effect.Effect<BuildProfile, BuildProfileError, FileSystem.FileSystem | Path.Path> =>\n Effect.gen(function* () {\n const config = yield* readEasJson(projectRoot);\n const easProfile = yield* resolveEasBuildProfile(config, profileName);\n return fromEasProfile(easProfile, profileName);\n });\n\nexport const readRuntimeVersionMeta = (config: ExpoConfig): RuntimeVersionMeta => ({\n appVersion: config.version,\n rawRuntimeVersion: readRawRuntimeVersion(config.runtimeVersion),\n});\n\nconst readRawRuntimeVersion = (value: unknown): RawRuntimeVersion | undefined => {\n if (typeof value === \"string\") {\n return value;\n }\n const record = asRecord(value);\n const policy = asString(record?.[\"policy\"]);\n if (policy) {\n return { policy };\n }\n return undefined;\n};\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\n/**\n * Project-scoped build cache directories to remove when --clear-cache is passed.\n * Intentionally avoids `~/.gradle/caches` (global) and `ios/Pods/` (requires\n * pod install rebuild — leave to the user).\n */\nconst CACHE_DIRS = [\n \"android/.gradle\",\n \"android/app/build\",\n \"android/build\",\n \"ios/build\",\n \".expo\",\n \"node_modules/.cache\",\n] as const;\n\nexport const clearBuildCaches = (\n projectRoot: string,\n): Effect.Effect<void, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const removed: string[] = [];\n yield* Effect.forEach(\n CACHE_DIRS,\n (rel) =>\n Effect.gen(function* () {\n const target = path.join(projectRoot, rel);\n const exists = yield* fs\n .exists(target)\n .pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (!exists) {\n return;\n }\n yield* fs\n .remove(target, { recursive: true })\n .pipe(Effect.catchAll(() => Effect.succeed(undefined)));\n removed.push(rel);\n }),\n { concurrency: 4 },\n );\n if (removed.length > 0) {\n yield* Console.error(`Cleared caches: ${removed.join(\", \")}`);\n }\n });\n","import { Effect } from \"effect\";\n\nimport { EnvExportError } from \"./exit-codes\";\n\nimport type { ApiClient } from \"../services/api-client\";\n\nexport interface PullEnvVarsOptions {\n readonly projectId: string;\n readonly environment: string;\n}\n\n/**\n * Pull environment variables for a project + environment and flatten them into\n * a key/value map. Returns an empty map when the project has no variables.\n */\nexport const pullEnvVars = (\n api: ApiClient,\n { projectId, environment }: PullEnvVarsOptions,\n): Effect.Effect<Record<string, string>, EnvExportError> =>\n api[\"env-vars\"].export({ urlParams: { projectId, environment } }).pipe(\n Effect.map((result) => Object.fromEntries(result.items.map((item) => [item.key, item.value]))),\n Effect.mapError(\n (cause) =>\n new EnvExportError({\n message: `Failed to export environment variables for \"${environment}\": ${String(cause)}`,\n }),\n ),\n );\n","import { Command } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nexport interface GitContext {\n readonly ref: string | undefined;\n readonly commit: string | undefined;\n readonly commitMessage: string | undefined;\n readonly dirty: boolean;\n}\n\nconst runString = (\n cmd: Command.Command,\n cwd: string,\n): Effect.Effect<string, unknown, CommandExecutor.CommandExecutor> =>\n Command.string(Command.workingDirectory(cmd, cwd));\n\n/**\n * Best-effort git context extraction. If git is missing, the directory isn't\n * a repo, or any command fails, we silently return undefined fields so the\n * build can still proceed. This is intentional — git context is metadata,\n * not a requirement.\n */\nexport const readGitContext = (\n projectRoot: string,\n): Effect.Effect<GitContext, never, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const [commit, ref, commitMessage, status] = yield* Effect.all(\n [\n runString(Command.make(\"git\", \"rev-parse\", \"HEAD\"), projectRoot).pipe(\n Effect.map((output) => output.trim()),\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n runString(Command.make(\"git\", \"symbolic-ref\", \"--short\", \"HEAD\"), projectRoot).pipe(\n Effect.map((output) => output.trim()),\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n runString(Command.make(\"git\", \"log\", \"-1\", \"--format=%s\"), projectRoot).pipe(\n Effect.map((output) => output.trim()),\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n runString(Command.make(\"git\", \"status\", \"--porcelain\"), projectRoot).pipe(\n Effect.catchAll(() => Effect.succeed(\"\")),\n ),\n ],\n { concurrency: \"unbounded\" },\n );\n\n return {\n ref: ref.length > 0 ? ref : undefined,\n commit: commit.length > 0 ? commit : undefined,\n commitMessage: commitMessage.length > 0 ? commitMessage : undefined,\n dirty: status.trim().length > 0,\n };\n });\n","import path from \"node:path\";\n\nimport { asRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nexport interface GradleConfig {\n readonly applicationId?: string;\n readonly versionCode?: number;\n readonly versionName?: string;\n}\n\n/**\n * Parse Groovy `build.gradle` to extract key Android config values.\n * Returns `undefined` if:\n * - Only `build.gradle.kts` exists (Kotlin DSL not supported by gradle-to-js)\n * - No build.gradle found at all\n * - Parse fails\n *\n * Informational only — never blocks the build.\n */\nexport const readGradleConfig = (\n androidDir: string,\n): Effect.Effect<GradleConfig | undefined, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const gradlePath = path.join(androidDir, \"app\", \"build.gradle\");\n const ktsPath = path.join(androidDir, \"app\", \"build.gradle.kts\");\n\n const hasGroovy = yield* fs.exists(gradlePath).pipe(Effect.orElseSucceed(() => false));\n const hasKts = yield* fs.exists(ktsPath).pipe(Effect.orElseSucceed(() => false));\n\n if (!hasGroovy && hasKts) {\n // Kotlin DSL — gradle-to-js cannot parse it\n return undefined;\n }\n\n if (!hasGroovy) {\n return undefined;\n }\n\n const content = yield* fs\n .readFileString(gradlePath)\n .pipe(Effect.catchAll(() => Effect.succeed(undefined)));\n if (!content) {\n return undefined;\n }\n\n return yield* Effect.tryPromise({\n try: async () => {\n const gradle =\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- CJS require returns `any`; narrow to gradle-to-js declared shape\n require(\"gradle-to-js\") as {\n parseText: (text: string) => Promise<Record<string, unknown>>;\n };\n return gradle.parseText(stripGroovyComments(content));\n },\n catch: () => undefined,\n }).pipe(\n Effect.map(extractGradleConfig),\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n });\n\n/**\n * Log a warning if Gradle applicationId differs from app.json package name.\n */\nexport const warnOnGradleMismatch = (\n gradleConfig: GradleConfig | undefined,\n expectedPackage: string,\n): Effect.Effect<void> => {\n if (!gradleConfig?.applicationId) {\n return Effect.void;\n }\n if (gradleConfig.applicationId === expectedPackage) {\n return Effect.void;\n }\n return Console.warn(\n `Gradle applicationId \"${gradleConfig.applicationId}\" differs from app.json package \"${expectedPackage}\". ` +\n `The Gradle value will be used in the built APK/AAB.`,\n );\n};\n\n// ── helpers ──────────────────────────────────────────────────────\n\n/**\n * Strip Groovy single-line and block comments.\n * gradle-to-js chokes on comments — EAS CLI does this same pre-processing.\n */\nconst stripGroovyComments = (text: string): string =>\n text.replaceAll(/\\/\\/.*$/gmu, \"\").replaceAll(/\\/\\*[\\s\\S]*?\\*\\//gu, \"\");\n\nconst parseVersionCode = (raw: unknown): number | undefined => {\n if (typeof raw === \"number\") {\n return raw;\n }\n if (typeof raw === \"string\") {\n return Number.parseInt(raw, 10) || undefined;\n }\n return undefined;\n};\n\nconst extractGradleConfig = (parsed: Record<string, unknown>): GradleConfig => {\n const android = asRecord(parsed[\"android\"]);\n const defaultConfig = asRecord(android?.[\"defaultConfig\"]);\n\n const applicationId =\n typeof defaultConfig?.[\"applicationId\"] === \"string\"\n ? unquote(defaultConfig[\"applicationId\"])\n : undefined;\n const versionCode = parseVersionCode(defaultConfig?.[\"versionCode\"]);\n const versionName =\n typeof defaultConfig?.[\"versionName\"] === \"string\"\n ? unquote(defaultConfig[\"versionName\"])\n : undefined;\n\n return {\n ...(applicationId === undefined ? {} : { applicationId }),\n ...(versionCode === undefined ? {} : { versionCode }),\n ...(versionName === undefined ? {} : { versionName }),\n };\n};\n\nconst unquote = (input: string): string =>\n input.startsWith('\"') && input.endsWith('\"') ? input.slice(1, -1) : input;\n","import { cancel, confirm, isCancel, multiselect, password, select, text } from \"@clack/prompts\";\nimport { Effect } from \"effect\";\n\nimport { InteractiveProhibitedError } from \"./exit-codes\";\nimport { InteractiveMode } from \"./interactive-mode\";\n\nconst ensureInteractive = (\n promptName: string,\n): Effect.Effect<void, InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n const mode = yield* InteractiveMode;\n if (!mode.allow) {\n return yield* new InteractiveProhibitedError({\n message: `Interactive prompt \"${promptName}\" requested while running non-interactively. Provide the value via a flag, run with --interactive, or unset CI.`,\n });\n }\n return undefined;\n });\n\nconst handleCancel = <T>(value: T | symbol): T => {\n if (isCancel(value)) {\n cancel(\"Operation cancelled.\");\n // eslint-disable-next-line eslint-plugin-unicorn/no-process-exit -- SIGINT at a CLI prompt must terminate the process; throwing would leave Effect runtime stuck\n process.exit(130);\n }\n return value;\n};\n\nexport const promptPassword = (\n message: string,\n): Effect.Effect<string, InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n yield* ensureInteractive(message);\n const value = yield* Effect.promise(async () => password({ message }));\n return handleCancel(value);\n });\n\ntype SelectOption<T> = Parameters<typeof select<T>>[0][\"options\"][number];\n\nexport const promptSelect = <T>(\n message: string,\n options: readonly SelectOption<T>[],\n): Effect.Effect<T, InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n yield* ensureInteractive(message);\n const value = yield* Effect.promise(async () => select<T>({ message, options: [...options] }));\n return handleCancel(value);\n });\n\ntype MultiSelectOption<T> = Parameters<typeof multiselect<T>>[0][\"options\"][number];\n\nexport const promptMultiSelect = <T>(\n message: string,\n options: readonly MultiSelectOption<T>[],\n config?: { readonly required?: boolean },\n): Effect.Effect<readonly T[], InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n yield* ensureInteractive(message);\n const value = yield* Effect.promise(async () =>\n multiselect<T>({\n message,\n options: [...options],\n required: config?.required ?? false,\n }),\n );\n return handleCancel(value);\n });\n\nexport const promptText = (\n message: string,\n options?: { readonly placeholder?: string; readonly defaultValue?: string },\n): Effect.Effect<string, InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n yield* ensureInteractive(message);\n const value = yield* Effect.promise(async () =>\n text({\n message,\n ...(options?.placeholder === undefined ? {} : { placeholder: options.placeholder }),\n ...(options?.defaultValue === undefined ? {} : { defaultValue: options.defaultValue }),\n }),\n );\n return handleCancel(value);\n });\n\nexport const promptConfirm = (\n message: string,\n options?: { readonly initialValue?: boolean },\n): Effect.Effect<boolean, InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n yield* ensureInteractive(message);\n const value = yield* Effect.promise(async () =>\n confirm({\n message,\n ...(options?.initialValue === undefined ? {} : { initialValue: options.initialValue }),\n }),\n );\n return handleCancel(value);\n });\n","import { Effect } from \"effect\";\n\nimport { BuildProfileError } from \"./exit-codes\";\nimport { InteractiveMode } from \"./interactive-mode\";\nimport { promptSelect } from \"./prompts\";\n\nimport type { Platform } from \"./build-profile\";\nimport type { InteractiveProhibitedError } from \"./exit-codes\";\nimport type { ExpoConfig } from \"./expo-config\";\n\nconst PLATFORMS = [\"ios\", \"android\"] as const;\n\nconst inferPlatforms = (config: ExpoConfig): readonly Platform[] => {\n const fromConfig: unknown = config[\"platforms\"];\n if (Array.isArray(fromConfig)) {\n return fromConfig.filter((entry): entry is Platform => entry === \"ios\" || entry === \"android\");\n }\n const present: Platform[] = [];\n if (config.ios !== undefined) {\n present.push(\"ios\");\n }\n if (config.android !== undefined) {\n present.push(\"android\");\n }\n return present;\n};\n\n/**\n * Resolve a build platform from an explicit flag, or fall back to the Expo\n * config (`expo.platforms` or the presence of `ios`/`android` sections). Prompts\n * when the config declares both platforms; fails when ambiguous and prompts are\n * disallowed.\n */\nexport const detectPlatform = (\n explicit: Platform | undefined,\n config: ExpoConfig,\n): Effect.Effect<Platform, BuildProfileError | InteractiveProhibitedError, InteractiveMode> =>\n Effect.gen(function* () {\n if (explicit !== undefined) {\n return explicit;\n }\n const candidates = inferPlatforms(config);\n if (candidates.length === 0) {\n return yield* new BuildProfileError({\n message:\n \"Cannot infer build platform. Add an `ios` or `android` section to your Expo config, or pass --platform.\",\n });\n }\n if (candidates.length === 1) {\n const [only] = candidates;\n if (only === undefined) {\n return yield* new BuildProfileError({\n message: \"Internal: empty platform candidate list.\",\n });\n }\n return only;\n }\n const mode = yield* InteractiveMode;\n if (!mode.allow) {\n return yield* new BuildProfileError({\n message: `Multiple platforms detected (${candidates.join(\", \")}). Pass --platform explicitly when running non-interactively.`,\n });\n }\n return yield* promptSelect<Platform>(\n \"Which platform to build?\",\n PLATFORMS.filter((entry) => candidates.includes(entry)).map((entry) => ({\n value: entry,\n label: entry,\n })),\n );\n });\n","import { Command } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { DirtyRepoError } from \"./exit-codes\";\nimport { InteractiveMode } from \"./interactive-mode\";\nimport { promptConfirm } from \"./prompts\";\n\nimport type { InteractiveProhibitedError } from \"./exit-codes\";\n\nconst MAX_FILES_SHOWN = 10;\n\nconst readPorcelain = (\n projectRoot: string,\n): Effect.Effect<readonly string[], never, CommandExecutor.CommandExecutor> =>\n Command.make(\"git\", \"status\", \"--porcelain\").pipe(\n Command.workingDirectory(projectRoot),\n Command.string,\n Effect.map((output) =>\n output\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter((line) => line.length > 0),\n ),\n Effect.catchAll(() => Effect.succeed<readonly string[]>([])),\n );\n\nexport interface EnsureRepoCleanOptions {\n readonly projectRoot: string;\n readonly allowDirty: boolean;\n /** Label inserted into messages (e.g. \"build\", \"update publish\"). */\n readonly label: string;\n}\n\n/**\n * Refuse to proceed when the working tree has uncommitted changes. Skipped when\n * `allowDirty` is true. In interactive mode, prompts the user to confirm; in\n * non-interactive mode, fails with `DirtyRepoError`.\n */\nexport const ensureRepoClean = ({\n projectRoot,\n allowDirty,\n label,\n}: EnsureRepoCleanOptions): Effect.Effect<\n void,\n DirtyRepoError | InteractiveProhibitedError,\n CommandExecutor.CommandExecutor | InteractiveMode\n> =>\n Effect.gen(function* () {\n if (allowDirty) {\n return;\n }\n const dirty = yield* readPorcelain(projectRoot);\n if (dirty.length === 0) {\n return;\n }\n\n const preview = dirty.slice(0, MAX_FILES_SHOWN).join(\"\\n \");\n const overflow =\n dirty.length > MAX_FILES_SHOWN\n ? `\\n ... and ${String(dirty.length - MAX_FILES_SHOWN)} more`\n : \"\";\n yield* Console.error(\n `Uncommitted changes (${String(dirty.length)} file(s)):\\n ${preview}${overflow}`,\n );\n\n const mode = yield* InteractiveMode;\n if (!mode.allow) {\n yield* new DirtyRepoError({\n message: `Refusing to ${label} with a dirty working tree. Commit your changes or pass --allow-dirty.`,\n });\n return;\n }\n const ok = yield* promptConfirm(`Continue ${label} with uncommitted changes?`, {\n initialValue: false,\n });\n if (!ok) {\n yield* new DirtyRepoError({\n message: `${label} cancelled by user.`,\n });\n }\n });\n","import { isRecord } from \"@better-update/type-guards\";\nimport { Command } from \"@effect/platform\";\nimport { Data, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nexport class FingerprintError extends Data.TaggedError(\"FingerprintError\")<{\n readonly message: string;\n}> {}\n\nexport interface FingerprintSource {\n readonly type: string;\n readonly filePath?: string;\n readonly reasons: readonly string[];\n readonly hash: string | null;\n}\n\nexport interface FingerprintResult {\n readonly hash: string;\n readonly sources: readonly FingerprintSource[];\n}\n\nexport const runFingerprintFull = (\n projectRoot: string,\n): Effect.Effect<FingerprintResult, FingerprintError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const cmd = Command.make(\"bunx\", \"@expo/fingerprint\", projectRoot).pipe(\n Command.workingDirectory(projectRoot),\n );\n const stdout = yield* Command.string(cmd).pipe(\n Effect.mapError(\n (cause) =>\n new FingerprintError({\n message: `Failed to run \"@expo/fingerprint\": ${cause.message}`,\n }),\n ),\n );\n\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(stdout),\n catch: () =>\n new FingerprintError({\n message: \"Failed to parse @expo/fingerprint output as JSON.\",\n }),\n });\n\n if (!isRecord(parsed)) {\n return yield* new FingerprintError({\n message: \"@expo/fingerprint output was not a JSON object.\",\n });\n }\n\n const { hash } = parsed;\n if (typeof hash !== \"string\" || hash.length === 0) {\n return yield* new FingerprintError({\n message: '@expo/fingerprint output did not contain a \"hash\" string field.',\n });\n }\n\n const sourcesRaw = parsed[\"sources\"];\n const sources: readonly FingerprintSource[] = Array.isArray(sourcesRaw)\n ? (sourcesRaw as readonly FingerprintSource[])\n : [];\n\n return { hash, sources };\n });\n","import { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { RuntimeVersionError } from \"./exit-codes\";\nimport { runFingerprintFull } from \"./fingerprint\";\n\nimport type { RawRuntimeVersion } from \"./build-profile\";\n\nexport interface ResolveRuntimeVersionOptions {\n readonly raw: RawRuntimeVersion | undefined;\n readonly appVersion: string | undefined;\n readonly projectRoot: string;\n}\n\nexport const resolveRuntimeVersion = ({\n raw,\n appVersion,\n projectRoot,\n}: ResolveRuntimeVersionOptions): Effect.Effect<\n string,\n RuntimeVersionError,\n CommandExecutor.CommandExecutor\n> =>\n Effect.gen(function* () {\n if (typeof raw === \"string\") {\n return raw;\n }\n if (raw === undefined) {\n return yield* new RuntimeVersionError({\n message: \"No runtimeVersion configured in expo section of app.json.\",\n });\n }\n\n const { policy } = raw;\n if (policy === \"appVersion\") {\n if (appVersion === undefined) {\n return yield* new RuntimeVersionError({\n message: 'runtimeVersion policy is \"appVersion\" but expo.version is missing in app.json.',\n });\n }\n return appVersion;\n }\n\n if (policy === \"fingerprint\") {\n return yield* runFingerprintFull(projectRoot).pipe(\n Effect.map((result) => result.hash),\n Effect.mapError((cause) => new RuntimeVersionError({ message: cause.message })),\n );\n }\n\n if (policy === \"nativeVersion\") {\n return yield* new RuntimeVersionError({\n message:\n 'runtimeVersion policy \"nativeVersion\" is not supported. Set a static runtimeVersion string in your Expo config.',\n });\n }\n\n return yield* new RuntimeVersionError({\n message: `Unsupported runtimeVersion policy \"${policy}\". Use a static string, \"appVersion\", or \"fingerprint\".`,\n });\n });\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\n/**\n * Create a scoped temp directory prefixed with \"better-update-\" and `chmod 0o700`\n * it so only the current user can read its contents. The directory and all files\n * inside it are removed when the enclosing scope closes.\n */\nexport const acquireBuildTempDir = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const dir = yield* fs.makeTempDirectoryScoped({ prefix: \"better-update-\" });\n yield* fs.chmod(dir, 0o700);\n return dir;\n});\n","import { Command } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { BuildFailedError } from \"./exit-codes\";\n\nconst DEFAULT_KEYSTORE_VALIDITY_DAYS = 10_000;\n\nexport interface GenerateAndroidKeystoreInput {\n readonly outputPath: string;\n readonly keyAlias: string;\n readonly storePassword: string;\n readonly keyPassword: string;\n readonly commonName: string;\n readonly organization: string;\n readonly validityDays?: number;\n}\n\nexport const renderDistinguishedName = (params: {\n readonly commonName: string;\n readonly organization: string;\n}): string => `CN=${params.commonName}, O=${params.organization}`;\n\nexport const generateAndroidKeystore = (\n input: GenerateAndroidKeystoreInput,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor> =>\n Command.exitCode(\n Command.make(\n \"keytool\",\n \"-genkeypair\",\n \"-v\",\n \"-storetype\",\n \"JKS\",\n \"-keystore\",\n input.outputPath,\n \"-alias\",\n input.keyAlias,\n \"-keyalg\",\n \"RSA\",\n \"-keysize\",\n \"2048\",\n \"-validity\",\n String(input.validityDays ?? DEFAULT_KEYSTORE_VALIDITY_DAYS),\n \"-storepass\",\n input.storePassword,\n \"-keypass\",\n input.keyPassword,\n \"-dname\",\n renderDistinguishedName({\n commonName: input.commonName,\n organization: input.organization,\n }),\n \"-noprompt\",\n ).pipe(Command.stdout(\"inherit\"), Command.stderr(\"inherit\")),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step: \"generate android keystore\",\n exitCode: 1,\n message: `generate android keystore failed to spawn: ${String(cause)}`,\n }),\n ),\n Effect.flatMap((code) =>\n code === 0\n ? Effect.void\n : Effect.fail(\n new BuildFailedError({\n step: \"generate android keystore\",\n exitCode: code,\n message: `generate android keystore exited with code ${code}`,\n }),\n ),\n ),\n );\n","import { fromBase64 } from \"@better-update/encoding\";\n\nconst PEM_HEADER = \"-----BEGIN PRIVATE KEY-----\";\nconst PEM_FOOTER = \"-----END PRIVATE KEY-----\";\n\nexport const pemToPkcs8Der = (pem: string): Uint8Array | null => {\n const normalized = pem.replaceAll(\"\\r\\n\", \"\\n\").trim();\n const start = normalized.indexOf(PEM_HEADER);\n const end = normalized.indexOf(PEM_FOOTER);\n if (start === -1 || end === -1 || end <= start) {\n return null;\n }\n const body = normalized\n .slice(start + PEM_HEADER.length, end)\n .replaceAll(/\\s+/gu, \"\")\n .trim();\n if (body.length === 0) {\n return null;\n }\n try {\n return fromBase64(body);\n } catch {\n return null;\n }\n};\n","import { toBase64Url } from \"@better-update/encoding\";\nimport { Data, Effect } from \"effect\";\n\nimport { pemToPkcs8Der } from \"./apple-pem\";\n\nexport class AppleAuthError extends Data.TaggedError(\"AppleAuthError\")<{\n readonly cause: unknown;\n}> {}\n\nexport interface AscCredentials {\n readonly keyId: string;\n readonly issuerId: string;\n readonly p8Pem: string;\n}\n\nconst MAX_JWT_LIFETIME_SECONDS = 1200;\n\nconst asArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {\n const buffer = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(buffer).set(bytes);\n return buffer;\n};\n\nexport const signAscJwt = (credentials: AscCredentials) =>\n Effect.gen(function* () {\n const der = pemToPkcs8Der(credentials.p8Pem);\n if (der === null) {\n return yield* Effect.fail(new AppleAuthError({ cause: new Error(\"Invalid .p8 PEM\") }));\n }\n\n const header = { alg: \"ES256\", kid: credentials.keyId, typ: \"JWT\" };\n const now = Math.floor(Date.now() / 1000);\n const payload = {\n iss: credentials.issuerId,\n iat: now,\n exp: now + MAX_JWT_LIFETIME_SECONDS,\n aud: \"appstoreconnect-v1\",\n };\n\n const headerB64 = toBase64Url(new TextEncoder().encode(JSON.stringify(header)));\n const payloadB64 = toBase64Url(new TextEncoder().encode(JSON.stringify(payload)));\n const signingInput = `${headerB64}.${payloadB64}`;\n\n const key = yield* Effect.tryPromise({\n try: async () =>\n crypto.subtle.importKey(\n \"pkcs8\",\n asArrayBuffer(der),\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false,\n [\"sign\"],\n ),\n catch: (cause) => new AppleAuthError({ cause }),\n });\n\n const signature = yield* Effect.tryPromise({\n try: async () =>\n crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n key,\n new TextEncoder().encode(signingInput),\n ),\n catch: (cause) => new AppleAuthError({ cause }),\n });\n\n return `${signingInput}.${toBase64Url(new Uint8Array(signature))}`;\n });\n","import { isRecord } from \"@better-update/type-guards\";\nimport { Data, Effect } from \"effect\";\n\nimport { signAscJwt } from \"./apple-asc-jwt\";\n\nimport type { AppleAuthError, AscCredentials } from \"./apple-asc-jwt\";\n\nexport type { AppleAuthError, AscCredentials } from \"./apple-asc-jwt\";\n\nexport type AscCertificateType =\n | \"DEVELOPMENT\"\n | \"DISTRIBUTION\"\n | \"IOS_DEVELOPMENT\"\n | \"IOS_DISTRIBUTION\";\n\nexport type AscProfileType =\n | \"IOS_APP_ADHOC\"\n | \"IOS_APP_DEVELOPMENT\"\n | \"IOS_APP_STORE\"\n | \"IOS_APP_INHOUSE\";\n\nexport interface AscCertificate {\n readonly id: string;\n readonly serialNumber: string;\n readonly certificateType: string;\n readonly displayName: string | null;\n readonly certificateContent: string | null;\n readonly expirationDate: string;\n}\n\nexport interface AscBundleId {\n readonly id: string;\n readonly identifier: string;\n readonly name: string;\n}\n\nexport interface AscProfile {\n readonly id: string;\n readonly name: string;\n readonly uuid: string;\n readonly profileType: AscProfileType;\n readonly expirationDate: string;\n readonly profileContent: string;\n}\n\nexport interface AscDevice {\n readonly id: string;\n readonly udid: string;\n readonly name: string;\n}\n\nexport class AscApiError extends Data.TaggedError(\"AscApiError\")<{\n readonly status: number;\n readonly message: string;\n readonly code: string | undefined;\n readonly raw: string;\n}> {}\n\nexport class AscNetworkError extends Data.TaggedError(\"AscNetworkError\")<{\n readonly cause: unknown;\n}> {}\n\nexport type AscError = AppleAuthError | AscApiError | AscNetworkError;\n\nconst API_BASE = \"https://api.appstoreconnect.apple.com\";\n\ninterface ErrorBody {\n readonly status?: string;\n readonly code?: string;\n readonly title?: string;\n readonly detail?: string;\n}\n\nconst extractErrors = (body: unknown): readonly ErrorBody[] => {\n if (!isRecord(body) || !Array.isArray(body[\"errors\"])) {\n return [];\n }\n return body[\"errors\"].filter((value): value is ErrorBody => isRecord(value));\n};\n\nconst parseApiError = (response: Response, body: unknown, raw: string): AscApiError => {\n const [first] = extractErrors(body);\n return new AscApiError({\n status: response.status,\n message: first?.detail ?? first?.title ?? response.statusText,\n code: first?.code,\n raw,\n });\n};\n\nconst fetchRaw = (jwt: string, path: string, init?: { method?: string; body?: string }) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: async () =>\n fetch(`${API_BASE}${path}`, {\n method: init?.method ?? \"GET\",\n ...(init?.body === undefined ? {} : { body: init.body }),\n headers: {\n authorization: `Bearer ${jwt}`,\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n },\n }),\n catch: (cause) => new AscNetworkError({ cause }),\n });\n const text = yield* Effect.tryPromise({\n try: async () => response.text(),\n catch: (cause) => new AscNetworkError({ cause }),\n });\n const body: unknown = text.length === 0 ? {} : JSON.parse(text);\n if (!response.ok) {\n return yield* Effect.fail(parseApiError(response, body, text));\n }\n return body;\n });\n\nconst toAscCertificate = (value: unknown): AscCertificate | null => {\n if (!isRecord(value)) {\n return null;\n }\n const { id, attributes } = value;\n if (typeof id !== \"string\" || !isRecord(attributes)) {\n return null;\n }\n const { serialNumber, certificateType, expirationDate, certificateContent, displayName } =\n attributes;\n if (\n typeof serialNumber !== \"string\" ||\n typeof certificateType !== \"string\" ||\n typeof expirationDate !== \"string\"\n ) {\n return null;\n }\n return {\n id,\n serialNumber,\n certificateType,\n expirationDate,\n certificateContent: typeof certificateContent === \"string\" ? certificateContent : null,\n displayName: typeof displayName === \"string\" ? displayName : null,\n };\n};\n\nconst toAscBundleId = (value: unknown): AscBundleId | null => {\n if (!isRecord(value)) {\n return null;\n }\n const { id, attributes } = value;\n if (typeof id !== \"string\" || !isRecord(attributes)) {\n return null;\n }\n const { identifier, name } = attributes;\n if (typeof identifier !== \"string\" || typeof name !== \"string\") {\n return null;\n }\n return { id, identifier, name };\n};\n\nconst PROFILE_TYPES: readonly AscProfileType[] = [\n \"IOS_APP_ADHOC\",\n \"IOS_APP_DEVELOPMENT\",\n \"IOS_APP_STORE\",\n \"IOS_APP_INHOUSE\",\n];\n\nconst asProfileType = (value: unknown): AscProfileType | null => {\n const match = PROFILE_TYPES.find((entry) => entry === value);\n return match === undefined ? null : match;\n};\n\nconst toAscProfile = (value: unknown): AscProfile | null => {\n if (!isRecord(value)) {\n return null;\n }\n const { id, attributes } = value;\n if (typeof id !== \"string\" || !isRecord(attributes)) {\n return null;\n }\n const { name, uuid, expirationDate, profileContent } = attributes;\n const profileType = asProfileType(attributes[\"profileType\"]);\n if (\n typeof name !== \"string\" ||\n typeof uuid !== \"string\" ||\n typeof expirationDate !== \"string\" ||\n typeof profileContent !== \"string\" ||\n profileType === null\n ) {\n return null;\n }\n return { id, name, uuid, expirationDate, profileContent, profileType };\n};\n\nconst toAscDevice = (value: unknown): AscDevice | null => {\n if (!isRecord(value)) {\n return null;\n }\n const { id, attributes } = value;\n if (typeof id !== \"string\" || !isRecord(attributes)) {\n return null;\n }\n const { udid, name } = attributes;\n if (typeof udid !== \"string\" || typeof name !== \"string\") {\n return null;\n }\n return { id, udid, name };\n};\n\nconst extractList = <T>(body: unknown, map: (value: unknown) => T | null): readonly T[] => {\n if (!isRecord(body) || !Array.isArray(body[\"data\"])) {\n return [];\n }\n return body[\"data\"].map(map).filter((value): value is T => value !== null);\n};\n\nconst extractSingle = <T>(body: unknown, map: (value: unknown) => T | null): T | null => {\n if (!isRecord(body)) {\n return null;\n }\n return map(body[\"data\"]);\n};\n\nconst malformed = (resource: string): AscApiError =>\n new AscApiError({\n status: 500,\n message: `Malformed ${resource} response`,\n code: undefined,\n raw: \"\",\n });\n\nconst withJwt = <Value, Err, Req>(\n credentials: AscCredentials,\n fn: (jwt: string) => Effect.Effect<Value, Err, Req>,\n) =>\n Effect.gen(function* () {\n const jwt = yield* signAscJwt(credentials);\n return yield* fn(jwt);\n });\n\nexport const listCertificates = (\n credentials: AscCredentials,\n params?: { readonly certificateType?: AscCertificateType },\n) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n const filter = params?.certificateType\n ? `?filter[certificateType]=${params.certificateType}&limit=200`\n : \"?limit=200\";\n const body = yield* fetchRaw(jwt, `/v1/certificates${filter}`);\n return extractList(body, toAscCertificate);\n }),\n );\n\nexport const createCertificate = (\n credentials: AscCredentials,\n params: { readonly csrPem: string; readonly certificateType: AscCertificateType },\n) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n const csrContent = params.csrPem\n .replaceAll(\"-----BEGIN CERTIFICATE REQUEST-----\", \"\")\n .replaceAll(\"-----END CERTIFICATE REQUEST-----\", \"\")\n .replaceAll(/\\s+/gu, \"\");\n const body = yield* fetchRaw(jwt, \"/v1/certificates\", {\n method: \"POST\",\n body: JSON.stringify({\n data: {\n type: \"certificates\",\n attributes: { csrContent, certificateType: params.certificateType },\n },\n }),\n });\n const resource = extractSingle(body, toAscCertificate);\n if (resource === null) {\n return yield* Effect.fail(malformed(\"certificate\"));\n }\n return resource;\n }),\n );\n\nexport const deleteCertificate = (credentials: AscCredentials, id: string) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n yield* fetchRaw(jwt, `/v1/certificates/${encodeURIComponent(id)}`, { method: \"DELETE\" });\n }),\n );\n\nexport const listBundleIds = (credentials: AscCredentials) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n const body = yield* fetchRaw(jwt, \"/v1/bundleIds?limit=200\");\n return extractList(body, toAscBundleId);\n }),\n );\n\nexport const createBundleId = (\n credentials: AscCredentials,\n params: { readonly identifier: string; readonly name: string },\n) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n const body = yield* fetchRaw(jwt, \"/v1/bundleIds\", {\n method: \"POST\",\n body: JSON.stringify({\n data: {\n type: \"bundleIds\",\n attributes: { identifier: params.identifier, name: params.name, platform: \"IOS\" },\n },\n }),\n });\n const resource = extractSingle(body, toAscBundleId);\n if (resource === null) {\n return yield* Effect.fail(malformed(\"bundleId\"));\n }\n return resource;\n }),\n );\n\nexport const listDevices = (credentials: AscCredentials) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n const body = yield* fetchRaw(jwt, \"/v1/devices?limit=200\");\n return extractList(body, toAscDevice);\n }),\n );\n\nexport const createProvisioningProfile = (\n credentials: AscCredentials,\n params: {\n readonly profileName: string;\n readonly profileType: AscProfileType;\n readonly bundleIdAscId: string;\n readonly certificateAscIds: readonly string[];\n readonly deviceAscIds: readonly string[];\n },\n) =>\n withJwt(credentials, (jwt) =>\n Effect.gen(function* () {\n const relationships = {\n bundleId: { data: { type: \"bundleIds\", id: params.bundleIdAscId } },\n certificates: {\n data: params.certificateAscIds.map((id) => ({ type: \"certificates\", id })),\n },\n ...(params.deviceAscIds.length > 0\n ? { devices: { data: params.deviceAscIds.map((id) => ({ type: \"devices\", id })) } }\n : {}),\n };\n const body = yield* fetchRaw(jwt, \"/v1/profiles\", {\n method: \"POST\",\n body: JSON.stringify({\n data: {\n type: \"profiles\",\n attributes: { name: params.profileName, profileType: params.profileType },\n relationships,\n },\n }),\n });\n const resource = extractSingle(body, toAscProfile);\n if (resource === null) {\n return yield* Effect.fail(malformed(\"profile\"));\n }\n return resource;\n }),\n );\n\nexport const isCertificateLimitError = (error: AscError): boolean => {\n if (error._tag !== \"AscApiError\") {\n return false;\n }\n return /already have a current.*certificate|pending certificate request/iu.test(error.message);\n};\n","import { Data, Effect } from \"effect\";\nimport forge from \"node-forge\";\n\nexport class CertParseError extends Data.TaggedError(\"CertParseError\")<{\n readonly message: string;\n}> {}\n\nexport interface CertMetadata {\n readonly serialNumber: string;\n readonly validFrom: string;\n readonly validUntil: string;\n readonly appleTeamId: string;\n readonly appleTeamName: string | null;\n readonly developerIdIdentifier: string | null;\n readonly commonName: string | null;\n}\n\nexport interface P12Bundle {\n readonly p12Base64: string;\n readonly password: string;\n readonly metadata: CertMetadata;\n}\n\nconst APPLE_TEAM_ID_RE = /^[A-Z0-9]{10}$/u;\n\nconst stringField = (cert: forge.pki.Certificate, name: string): string | null => {\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- forge.pki.CertificateField has `value: any` from @types/node-forge; narrow to unknown before the typeof guard\n const field = cert.subject.getField(name) as { value?: unknown } | undefined;\n if (field === undefined || typeof field.value !== \"string\") {\n return null;\n }\n return field.value;\n};\n\nconst matchTeamFromCommonName = (cn: string): string | null => {\n const match = /\\(([A-Z0-9]{10})\\)/u.exec(cn);\n if (match === null) {\n return null;\n }\n const [, captured] = match;\n return captured === undefined ? null : captured;\n};\n\nconst extractTeamId = (cert: forge.pki.Certificate): string | null => {\n const ou = stringField(cert, \"OU\");\n if (ou !== null && APPLE_TEAM_ID_RE.test(ou)) {\n return ou;\n }\n const cn = stringField(cert, \"CN\");\n if (cn === null) {\n return null;\n }\n return matchTeamFromCommonName(cn);\n};\n\nconst parseCert = (certDerBytes: string): forge.pki.Certificate => {\n const asn1 = forge.asn1.fromDer(certDerBytes);\n return forge.pki.certificateFromAsn1(asn1);\n};\n\nconst generatePassword = (): string => forge.util.encode64(forge.random.getBytesSync(16));\n\nexport const buildDistributionCertP12 = (params: {\n readonly certificateContentBase64: string;\n readonly privateKey: forge.pki.rsa.PrivateKey;\n}): Effect.Effect<P12Bundle, CertParseError> =>\n Effect.gen(function* () {\n const result = yield* Effect.try({\n try: () => {\n const certDer = forge.util.decode64(params.certificateContentBase64);\n const cert = parseCert(certDer);\n const password = generatePassword();\n const p12Asn1 = forge.pkcs12.toPkcs12Asn1(params.privateKey, [cert], password, {\n friendlyName: \"key\",\n algorithm: \"3des\",\n });\n const p12Base64 = forge.util.encode64(forge.asn1.toDer(p12Asn1).getBytes());\n return { cert, p12Base64, password };\n },\n catch: (error) =>\n new CertParseError({\n message: `Failed to assemble .p12: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n const appleTeamId = extractTeamId(result.cert);\n if (appleTeamId === null) {\n return yield* Effect.fail(\n new CertParseError({\n message: \"Could not extract Apple team identifier from certificate subject\",\n }),\n );\n }\n return {\n p12Base64: result.p12Base64,\n password: result.password,\n metadata: {\n serialNumber: result.cert.serialNumber.toUpperCase(),\n validFrom: result.cert.validity.notBefore.toISOString(),\n validUntil: result.cert.validity.notAfter.toISOString(),\n appleTeamId,\n appleTeamName: stringField(result.cert, \"O\"),\n developerIdIdentifier: stringField(result.cert, \"UID\"),\n commonName: stringField(result.cert, \"CN\"),\n },\n };\n });\n","import forge from \"node-forge\";\n\nexport interface CsrResult {\n readonly csrPem: string;\n readonly privateKeyPem: string;\n readonly privateKey: forge.pki.rsa.PrivateKey;\n}\n\nconst generateRsaKeyPair = async (): Promise<forge.pki.rsa.KeyPair> =>\n new Promise((resolve) => {\n forge.pki.rsa.generateKeyPair({ bits: 2048, workers: 2 }, (_err, keyPair) => {\n resolve(keyPair);\n });\n });\n\nexport const generateCertificateSigningRequest = async (): Promise<CsrResult> => {\n const keyPair = await generateRsaKeyPair();\n const csr = forge.pki.createCertificationRequest();\n csr.publicKey = keyPair.publicKey;\n csr.setSubject([{ name: \"commonName\", shortName: \"CN\", value: \"PEM\" }]);\n csr.sign(keyPair.privateKey, forge.md.sha1.create());\n return {\n csrPem: forge.pki.certificationRequestToPem(csr),\n privateKeyPem: forge.pki.privateKeyToPem(keyPair.privateKey),\n privateKey: keyPair.privateKey,\n };\n};\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { fromBase64, toBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Data, Effect } from \"effect\";\n\nimport { generateAndroidKeystore } from \"./android-keystore\";\nimport {\n createBundleId,\n createCertificate,\n createProvisioningProfile,\n deleteCertificate,\n isCertificateLimitError,\n listBundleIds,\n listCertificates,\n listDevices,\n} from \"./apple-asc-client\";\nimport { buildDistributionCertP12 } from \"./apple-cert-to-p12\";\nimport { generateCertificateSigningRequest } from \"./apple-csr\";\nimport { acquireBuildTempDir } from \"./temp-dir\";\n\nimport type { ApiClient } from \"../services/api-client\";\nimport type {\n AscCertificateType,\n AscCredentials,\n AscError,\n AscProfileType,\n} from \"./apple-asc-client\";\n\ntype DistributionType = \"APP_STORE\" | \"AD_HOC\" | \"DEVELOPMENT\" | \"ENTERPRISE\";\n\nconst DISTRIBUTION_TO_PROFILE_TYPE: Record<DistributionType, AscProfileType> = {\n APP_STORE: \"IOS_APP_STORE\",\n AD_HOC: \"IOS_APP_ADHOC\",\n DEVELOPMENT: \"IOS_APP_DEVELOPMENT\",\n ENTERPRISE: \"IOS_APP_INHOUSE\",\n};\n\nexport const computeDeviceRosterHashHex = (ascDeviceIds: readonly string[]): string => {\n const sorted = [...ascDeviceIds].toSorted();\n return createHash(\"sha256\").update(sorted.join(\",\"), \"utf8\").digest(\"hex\");\n};\n\nexport class CertificateLimitError extends Data.TaggedError(\"CertificateLimitError\")<{\n readonly message: string;\n}> {}\n\nexport class GenerateFailedError extends Data.TaggedError(\"GenerateFailedError\")<{\n readonly step: string;\n readonly message: string;\n}> {}\n\nconst messageForAscCause = (cause: AscError): string => {\n if (cause._tag === \"AscApiError\") {\n return cause.message;\n }\n if (cause._tag === \"AppleAuthError\") {\n return \"Apple JWT signing failed\";\n }\n return \"Network error talking to Apple\";\n};\n\nconst wrapAscError = (step: string) => (cause: AscError) => {\n if (cause._tag === \"AscApiError\" && isCertificateLimitError(cause)) {\n return new CertificateLimitError({ message: cause.message });\n }\n return new GenerateFailedError({ step, message: messageForAscCause(cause) });\n};\n\n// ── Android keystore ───────────────────────────────────────────────\n\nexport interface GenerateAndUploadKeystoreInput {\n readonly keyAlias: string;\n readonly storePassword: string;\n readonly keyPassword: string;\n readonly commonName: string;\n readonly organization: string;\n readonly validityDays?: number;\n}\n\nexport const generateAndUploadKeystore = (api: ApiClient, input: GenerateAndUploadKeystoreInput) =>\n Effect.scoped(\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const tempDir = yield* acquireBuildTempDir;\n const keystorePath = path.join(tempDir, \"release.keystore\");\n\n yield* generateAndroidKeystore({\n outputPath: keystorePath,\n keyAlias: input.keyAlias,\n storePassword: input.storePassword,\n keyPassword: input.keyPassword,\n commonName: input.commonName,\n organization: input.organization,\n ...(input.validityDays === undefined ? {} : { validityDays: input.validityDays }),\n });\n\n const bytes = yield* fs.readFile(keystorePath);\n const created = yield* api.androidUploadKeystores.upload({\n payload: {\n keystoreBase64: toBase64(bytes),\n keyAlias: input.keyAlias,\n keystorePassword: input.storePassword,\n keyPassword: input.keyPassword,\n },\n });\n return { id: created.id, keyAlias: created.keyAlias };\n }),\n );\n\n// ── ASC credentials fetcher ────────────────────────────────────────\n\nexport const fetchAscCredentials = (api: ApiClient, ascApiKeyId: string) =>\n api.ascApiKeys.getCredentials({ path: { id: ascApiKeyId } });\n\n// ── iOS distribution certificate ───────────────────────────────────\n\nexport interface GenerateAndUploadDistributionCertificateInput {\n readonly ascApiKeyId: string;\n readonly certificateType?: \"IOS_DISTRIBUTION\" | \"IOS_DEVELOPMENT\";\n}\n\nexport const generateAndUploadDistributionCertificate = (\n api: ApiClient,\n input: GenerateAndUploadDistributionCertificateInput,\n) =>\n Effect.gen(function* () {\n const creds = yield* fetchAscCredentials(api, input.ascApiKeyId);\n const ascCreds = { keyId: creds.keyId, issuerId: creds.issuerId, p8Pem: creds.p8Pem };\n\n const csrResult = yield* Effect.tryPromise({\n try: generateCertificateSigningRequest,\n catch: (cause) =>\n new GenerateFailedError({\n step: \"csr\",\n message: `CSR generation failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n }),\n });\n\n const certificateType = input.certificateType ?? \"IOS_DISTRIBUTION\";\n const apple = yield* createCertificate(ascCreds, {\n csrPem: csrResult.csrPem,\n certificateType,\n }).pipe(Effect.mapError(wrapAscError(\"apple-create-certificate\")));\n\n if (apple.certificateContent === null) {\n return yield* Effect.fail(\n new GenerateFailedError({\n step: \"apple-create-certificate\",\n message: \"Apple response missing certificateContent\",\n }),\n );\n }\n\n const bundle = yield* buildDistributionCertP12({\n certificateContentBase64: apple.certificateContent,\n privateKey: csrResult.privateKey,\n }).pipe(\n Effect.mapError(\n (cause) => new GenerateFailedError({ step: \"p12-build\", message: cause.message }),\n ),\n );\n\n const created = yield* api.appleDistributionCertificates.upload({\n payload: {\n p12Base64: bundle.p12Base64,\n p12Password: bundle.password,\n serialNumber: bundle.metadata.serialNumber,\n appleTeamIdentifier: bundle.metadata.appleTeamId,\n ...(bundle.metadata.appleTeamName === null\n ? {}\n : { appleTeamName: bundle.metadata.appleTeamName }),\n ...(bundle.metadata.developerIdIdentifier === null\n ? {}\n : { developerIdIdentifier: bundle.metadata.developerIdIdentifier }),\n validFrom: bundle.metadata.validFrom,\n validUntil: bundle.metadata.validUntil,\n },\n });\n\n return {\n id: created.id,\n serialNumber: bundle.metadata.serialNumber,\n appleTeamId: bundle.metadata.appleTeamId,\n developerPortalIdentifier: apple.id,\n };\n });\n\nexport const revokeAppleCertificate = (\n api: ApiClient,\n input: { readonly ascApiKeyId: string; readonly developerPortalIdentifier: string },\n) =>\n Effect.gen(function* () {\n const creds = yield* fetchAscCredentials(api, input.ascApiKeyId);\n yield* deleteCertificate(\n { keyId: creds.keyId, issuerId: creds.issuerId, p8Pem: creds.p8Pem },\n input.developerPortalIdentifier,\n ).pipe(Effect.mapError(wrapAscError(\"apple-revoke-certificate\")));\n });\n\nexport interface RevokeLocalDistributionCertificateInput {\n readonly ascApiKeyId: string;\n readonly distributionCertificateId: string;\n readonly keepLocal?: boolean;\n}\n\nexport interface RevokeLocalDistributionCertificateResult {\n readonly localId: string;\n readonly serialNumber: string;\n readonly revokedOnApple: boolean;\n readonly deletedLocally: boolean;\n}\n\nexport const revokeLocalDistributionCertificate = (\n api: ApiClient,\n input: RevokeLocalDistributionCertificateInput,\n) =>\n Effect.gen(function* () {\n const listing = yield* api.appleDistributionCertificates.list();\n const local = listing.items.find((entry) => entry.id === input.distributionCertificateId);\n if (local === undefined) {\n return yield* Effect.fail(\n new GenerateFailedError({\n step: \"load-distribution-certificate\",\n message: `Distribution certificate ${input.distributionCertificateId} not found on this account`,\n }),\n );\n }\n\n const creds = yield* fetchAscCredentials(api, input.ascApiKeyId);\n const ascCreds = { keyId: creds.keyId, issuerId: creds.issuerId, p8Pem: creds.p8Pem };\n const targetSerial = local.serialNumber.toUpperCase();\n\n const matching = yield* Effect.all(\n [\n listCertificates(ascCreds, { certificateType: \"IOS_DISTRIBUTION\" }),\n listCertificates(ascCreds, { certificateType: \"IOS_DEVELOPMENT\" }),\n ],\n { concurrency: 2 },\n ).pipe(Effect.mapError(wrapAscError(\"apple-list-certificates\")));\n\n const ascMatch = [...matching[0], ...matching[1]].find(\n (entry) => entry.serialNumber.toUpperCase() === targetSerial,\n );\n\n let revokedOnApple = false;\n if (ascMatch !== undefined) {\n yield* deleteCertificate(ascCreds, ascMatch.id).pipe(\n Effect.mapError(wrapAscError(\"apple-revoke-certificate\")),\n );\n revokedOnApple = true;\n }\n\n let deletedLocally = false;\n if (input.keepLocal !== true) {\n yield* api.appleDistributionCertificates.delete({\n path: { id: input.distributionCertificateId },\n });\n deletedLocally = true;\n }\n\n return {\n localId: input.distributionCertificateId,\n serialNumber: local.serialNumber,\n revokedOnApple,\n deletedLocally,\n } satisfies RevokeLocalDistributionCertificateResult;\n });\n\nexport const listAppleCertificates = (\n api: ApiClient,\n input: {\n readonly ascApiKeyId: string;\n readonly certificateType?: AscCertificateType;\n },\n) =>\n Effect.gen(function* () {\n const creds = yield* fetchAscCredentials(api, input.ascApiKeyId);\n return yield* listCertificates(\n { keyId: creds.keyId, issuerId: creds.issuerId, p8Pem: creds.p8Pem },\n input.certificateType === undefined ? {} : { certificateType: input.certificateType },\n ).pipe(Effect.mapError(wrapAscError(\"apple-list-certificates\")));\n });\n\n// ── iOS provisioning profile ───────────────────────────────────────\n\nexport interface GenerateAndUploadProvisioningProfileInput {\n readonly ascApiKeyId: string;\n readonly distributionCertificateId: string;\n readonly bundleIdentifier: string;\n readonly distributionType: DistributionType;\n readonly deviceIds?: readonly string[];\n}\n\nconst resolveCertAscId = (\n creds: AscCredentials,\n serialNumber: string,\n certificateType: AscCertificateType,\n) =>\n Effect.gen(function* () {\n const certs = yield* listCertificates(creds, { certificateType }).pipe(\n Effect.mapError(wrapAscError(\"apple-list-certificates\")),\n );\n const match = certs.find((entry) => entry.serialNumber.toUpperCase() === serialNumber);\n if (match === undefined) {\n return yield* Effect.fail(\n new GenerateFailedError({\n step: \"match-apple-certificate\",\n message: `Distribution certificate ${serialNumber} not present on Apple Developer Portal; upload or re-generate it`,\n }),\n );\n }\n return match.id;\n });\n\nconst ensureBundleId = (creds: AscCredentials, bundleIdentifier: string) =>\n Effect.gen(function* () {\n const bundles = yield* listBundleIds(creds).pipe(\n Effect.mapError(wrapAscError(\"apple-list-bundle-ids\")),\n );\n const existing = bundles.find((entry) => entry.identifier === bundleIdentifier);\n if (existing !== undefined) {\n return existing.id;\n }\n const created = yield* createBundleId(creds, {\n identifier: bundleIdentifier,\n name: bundleIdentifier,\n }).pipe(Effect.mapError(wrapAscError(\"apple-create-bundle-id\")));\n return created.id;\n });\n\nconst collectDeviceAscIds = (\n creds: AscCredentials,\n appleTeamId: string,\n deviceIds: readonly string[] | undefined,\n) =>\n Effect.gen(function* () {\n const devices = yield* listDevices(creds).pipe(\n Effect.mapError(wrapAscError(\"apple-list-devices\")),\n );\n const ids =\n deviceIds === undefined\n ? devices.map((device) => device.id)\n : devices.filter((device) => new Set(deviceIds).has(device.id)).map((device) => device.id);\n return { ids, appleTeamId };\n });\n\nexport const generateAndUploadProvisioningProfile = (\n api: ApiClient,\n input: GenerateAndUploadProvisioningProfileInput,\n) =>\n Effect.gen(function* () {\n const creds = yield* fetchAscCredentials(api, input.ascApiKeyId);\n const ascCreds: AscCredentials = {\n keyId: creds.keyId,\n issuerId: creds.issuerId,\n p8Pem: creds.p8Pem,\n };\n\n const cert = yield* api.appleDistributionCertificates.list().pipe(\n Effect.map(({ items }) => items.find((item) => item.id === input.distributionCertificateId)),\n Effect.flatMap((match) =>\n match === undefined\n ? Effect.fail(\n new GenerateFailedError({\n step: \"load-distribution-certificate\",\n message: `Distribution certificate ${input.distributionCertificateId} not found`,\n }),\n )\n : Effect.succeed(match),\n ),\n );\n\n const certificateType: AscCertificateType =\n input.distributionType === \"DEVELOPMENT\" ? \"IOS_DEVELOPMENT\" : \"IOS_DISTRIBUTION\";\n\n const [certAscId, bundleIdAscId] = yield* Effect.all(\n [\n resolveCertAscId(ascCreds, cert.serialNumber.toUpperCase(), certificateType),\n ensureBundleId(ascCreds, input.bundleIdentifier),\n ],\n { concurrency: 2 },\n );\n\n const useDevices =\n input.distributionType === \"AD_HOC\" || input.distributionType === \"DEVELOPMENT\";\n\n const { ids: deviceAscIds } = useDevices\n ? yield* collectDeviceAscIds(ascCreds, cert.appleTeamId, input.deviceIds)\n : { ids: [] as readonly string[] };\n\n if (useDevices && deviceAscIds.length === 0) {\n return yield* Effect.fail(\n new GenerateFailedError({\n step: \"collect-devices\",\n message: \"No registered devices to attach to the provisioning profile\",\n }),\n );\n }\n\n const profileName = `${input.bundleIdentifier} ${input.distributionType} ${Date.now()}`;\n const profile = yield* createProvisioningProfile(ascCreds, {\n profileName,\n profileType: DISTRIBUTION_TO_PROFILE_TYPE[input.distributionType],\n bundleIdAscId,\n certificateAscIds: [certAscId],\n deviceAscIds,\n }).pipe(Effect.mapError(wrapAscError(\"apple-create-profile\")));\n\n const profileBytes = fromBase64(profile.profileContent);\n const rosterHash = useDevices ? computeDeviceRosterHashHex(deviceAscIds) : undefined;\n\n const created = yield* api.appleProvisioningProfiles.upload({\n payload: {\n profileBase64: toBase64(profileBytes),\n appleDistributionCertificateId: input.distributionCertificateId,\n isManaged: true,\n ...(rosterHash === undefined ? {} : { deviceRosterHash: rosterHash }),\n },\n });\n\n return {\n id: created.id,\n bundleIdentifier: created.bundleIdentifier,\n distributionType: created.distributionType,\n profileName: created.profileName,\n validUntil: created.validUntil,\n developerPortalIdentifier: created.developerPortalIdentifier,\n };\n });\n","import { Console, Effect } from \"effect\";\n\nimport { IOS_DISTRIBUTION_TO_TYPE } from \"../lib/credentials-downloader\";\nimport {\n generateAndUploadDistributionCertificate,\n generateAndUploadKeystore,\n generateAndUploadProvisioningProfile,\n listAppleCertificates,\n revokeAppleCertificate,\n} from \"../lib/credentials-generator\";\nimport { MissingCredentialsError } from \"../lib/exit-codes\";\nimport { InteractiveMode } from \"../lib/interactive-mode\";\nimport {\n promptConfirm,\n promptMultiSelect,\n promptPassword,\n promptSelect,\n promptText,\n} from \"../lib/prompts\";\n\nimport type { IosDistribution } from \"../lib/build-profile\";\nimport type { ApiClient } from \"../services/api-client\";\n\ninterface TaggedCause {\n readonly _tag: string;\n readonly message?: string;\n}\n\nconst hasTag = (cause: unknown): cause is TaggedCause =>\n typeof cause === \"object\" && cause !== null && \"_tag\" in cause;\n\nconst isMissingResolveError = (cause: unknown) =>\n hasTag(cause) && (cause._tag === \"NotFound\" || cause._tag === \"BadRequest\");\n\n// ── Android ────────────────────────────────────────────────────────\n\nexport interface AndroidSetupInput {\n readonly projectId: string;\n readonly applicationIdentifier: string;\n}\n\nconst generateKeystoreInteractive = (api: ApiClient) =>\n Effect.gen(function* () {\n const alias = yield* promptText(\"Key alias\", { placeholder: \"upload-key\" });\n const storePassword = yield* promptPassword(\"Keystore password\");\n const keyPassword = yield* promptPassword(\"Key password\");\n const commonName = yield* promptText(\"Common name (CN)\", { placeholder: \"Your App\" });\n const organization = yield* promptText(\"Organization (O)\", { placeholder: \"Your Company\" });\n yield* Console.log(\"Generating keystore with keytool...\");\n const created = yield* generateAndUploadKeystore(api, {\n keyAlias: alias,\n storePassword,\n keyPassword,\n commonName,\n organization,\n });\n return created.id;\n });\n\nconst pickExistingKeystore = (api: ApiClient) =>\n Effect.gen(function* () {\n const keystores = yield* api.androidUploadKeystores.list();\n if (keystores.items.length === 0) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"No existing keystores in this organization.\",\n hint: \"Re-run and choose 'Generate new keystore'.\",\n }),\n );\n }\n return yield* promptSelect<string>(\n \"Select a keystore\",\n keystores.items.map((item) => ({ value: item.id, label: item.keyAlias })),\n );\n });\n\nconst resolveAndroidAppId = (api: ApiClient, input: AndroidSetupInput) =>\n Effect.gen(function* () {\n const apps = yield* api.androidApplicationIdentifiers.list({\n path: { projectId: input.projectId },\n });\n const existing = apps.items.find((item) => item.packageName === input.applicationIdentifier);\n if (existing !== undefined) {\n return existing.id;\n }\n const created = yield* api.androidApplicationIdentifiers.create({\n path: { projectId: input.projectId },\n payload: { packageName: input.applicationIdentifier },\n });\n return created.id;\n });\n\nexport const resolveAndroidKeystoreId = (api: ApiClient, choice: \"generate\" | \"existing\") =>\n choice === \"generate\" ? generateKeystoreInteractive(api) : pickExistingKeystore(api);\n\nconst setupAndroidInteractive = (api: ApiClient, input: AndroidSetupInput) =>\n Effect.gen(function* () {\n yield* Console.log(\"\");\n yield* Console.log(\n `No Android build credentials configured for ${input.applicationIdentifier}.`,\n );\n\n const appId = yield* resolveAndroidAppId(api, input);\n\n const choice = yield* promptSelect<\"generate\" | \"existing\" | \"abort\">(\n \"How would you like to provide a keystore?\",\n [\n { value: \"generate\", label: \"Generate new keystore\" },\n { value: \"existing\", label: \"Pick an existing keystore\" },\n { value: \"abort\", label: \"Abort — I'll configure it in the dashboard\" },\n ],\n );\n\n if (choice === \"abort\") {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: `Build aborted — no keystore bound to ${input.applicationIdentifier}.`,\n hint: \"Run `better-update credentials generate keystore` or upload via the dashboard.\",\n }),\n );\n }\n\n const keystoreId = yield* resolveAndroidKeystoreId(api, choice);\n\n yield* api.androidBuildCredentials.create({\n path: { applicationIdentifierId: appId },\n payload: { name: \"Default\", isDefault: true, androidUploadKeystoreId: keystoreId },\n });\n yield* Console.log(\"Android build credentials configured.\");\n return undefined;\n });\n\nconst ensureAndroidCredentialsAvailable = (api: ApiClient, input: AndroidSetupInput) =>\n api.buildCredentials\n .resolve({\n path: { projectId: input.projectId },\n payload: {\n platform: \"android\",\n applicationIdentifier: input.applicationIdentifier,\n },\n })\n .pipe(Effect.asVoid);\n\nexport interface EnsureCredentialsOptions {\n readonly freezeCredentials: boolean;\n}\n\nexport const ensureAndroidCredentials = (\n api: ApiClient,\n input: AndroidSetupInput,\n options: EnsureCredentialsOptions,\n) =>\n ensureAndroidCredentialsAvailable(api, input).pipe(\n Effect.catchIf(isMissingResolveError, () =>\n Effect.gen(function* () {\n const mode = yield* InteractiveMode;\n if (options.freezeCredentials || !mode.allow) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: `No Android build credentials for ${input.applicationIdentifier}.`,\n hint: options.freezeCredentials\n ? \"Run `better-update credentials generate` first, or remove --freeze-credentials.\"\n : \"Run `better-update credentials generate` first, or rerun with --interactive to configure now.\",\n }),\n );\n }\n yield* setupAndroidInteractive(api, input);\n return yield* ensureAndroidCredentialsAvailable(api, input);\n }),\n ),\n );\n\n// ── iOS ────────────────────────────────────────────────────────────\n\nexport interface IosSetupInput {\n readonly projectId: string;\n readonly bundleIdentifier: string;\n readonly distribution: IosDistribution;\n}\n\ntype DistributionTypeValue =\n (typeof IOS_DISTRIBUTION_TO_TYPE)[keyof typeof IOS_DISTRIBUTION_TO_TYPE];\n\nexport interface IosSetupContext {\n readonly certId: string;\n readonly cert: { readonly appleTeamId: string };\n readonly ascKeyId: string;\n readonly distributionType: DistributionTypeValue;\n}\n\nconst interactiveCertLimitRecover = (api: ApiClient, ascApiKeyId: string) =>\n Effect.gen(function* () {\n yield* Console.log(\"\");\n yield* Console.log(\n \"Apple reports the certificate limit was hit (max 3 distribution certs per team).\",\n );\n const certs = yield* listAppleCertificates(api, {\n ascApiKeyId,\n certificateType: \"IOS_DISTRIBUTION\",\n });\n if (certs.length === 0) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message:\n \"Apple says the certificate limit is hit but no existing certificates were returned.\",\n hint: \"Try again later or check the Apple Developer portal.\",\n }),\n );\n }\n const toRevoke = yield* promptMultiSelect<string>(\n \"Select one or more certificates to revoke before retrying\",\n certs.map((entry) => ({\n value: entry.id,\n label: `${entry.serialNumber.slice(0, 12)}… (${entry.displayName ?? entry.certificateType}, exp ${entry.expirationDate.slice(0, 10)})`,\n })),\n { required: true },\n );\n yield* Effect.forEach(\n toRevoke,\n (id) => revokeAppleCertificate(api, { ascApiKeyId, developerPortalIdentifier: id }),\n { concurrency: \"inherit\" },\n );\n yield* Console.log(`Revoked ${toRevoke.length} certificate(s); retrying generation...`);\n return undefined;\n });\n\nconst generateDistributionCertInteractive = (api: ApiClient) =>\n Effect.gen(function* () {\n const ascKeys = yield* api.ascApiKeys.list();\n const teamAscKeys = ascKeys.items.filter((key) => key.appleTeamId !== null);\n if (teamAscKeys.length === 0) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"No ASC API key linked to an Apple team in this organization.\",\n hint: \"Upload an ASC API key with a team assignment via the dashboard, then retry.\",\n }),\n );\n }\n const ascKeyId = yield* promptSelect<string>(\n \"Select an ASC API key to issue the certificate against\",\n teamAscKeys.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n );\n yield* Console.log(\"Generating CSR and requesting certificate from Apple...\");\n const generate = generateAndUploadDistributionCertificate(api, { ascApiKeyId: ascKeyId });\n return yield* generate.pipe(\n Effect.catchTag(\"CertificateLimitError\", () =>\n interactiveCertLimitRecover(api, ascKeyId).pipe(Effect.flatMap(() => generate)),\n ),\n );\n });\n\nconst chooseIosCertificateId = (api: ApiClient) =>\n Effect.gen(function* () {\n const certs = yield* api.appleDistributionCertificates.list();\n if (certs.items.length === 0) {\n yield* Console.log(\"No distribution certificate found in this organization.\");\n const choice = yield* promptSelect<\"generate\" | \"abort\">(\"How would you like to proceed?\", [\n { value: \"generate\", label: \"Generate a new distribution certificate\" },\n { value: \"abort\", label: \"Abort — I'll upload one manually\" },\n ]);\n if (choice === \"abort\") {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"Build aborted — no distribution certificate available.\",\n hint: \"Run `better-update credentials generate distribution-certificate --asc-key-id <id>` or upload via the dashboard.\",\n }),\n );\n }\n const created = yield* generateDistributionCertInteractive(api);\n return created.id;\n }\n const choice = yield* promptSelect<string>(\n \"Select a distribution certificate (or 'generate' for a fresh one)\",\n [\n { value: \"__generate__\", label: \"Generate a new distribution certificate\" },\n ...certs.items.map((cert) => ({\n value: cert.id,\n label: `${cert.serialNumber.slice(0, 12)}… (team ${cert.appleTeamId})`,\n })),\n ],\n );\n if (choice === \"__generate__\") {\n const created = yield* generateDistributionCertInteractive(api);\n return created.id;\n }\n return choice;\n });\n\nexport const pickIosCertificate = (api: ApiClient) =>\n Effect.gen(function* () {\n const chosenId = yield* chooseIosCertificateId(api);\n const refreshed = yield* api.appleDistributionCertificates.list();\n const cert = refreshed.items.find((entry) => entry.id === chosenId);\n if (cert === undefined) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: \"Selected certificate not found after generation.\",\n hint: \"Retry.\",\n }),\n );\n }\n return { certId: chosenId, cert };\n });\n\nexport const pickIosAscKey = (api: ApiClient, appleTeamId: string) =>\n Effect.gen(function* () {\n const ascKeys = yield* api.ascApiKeys.list();\n const teamAscKeys = ascKeys.items.filter(\n (key) => key.appleTeamId !== null && key.appleTeamId === appleTeamId,\n );\n if (teamAscKeys.length === 0) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: `No ASC API key linked to Apple team ${appleTeamId}.`,\n hint: \"Upload an ASC API key for that team via the dashboard, then retry.\",\n }),\n );\n }\n return yield* promptSelect<string>(\n \"Select an ASC API key\",\n teamAscKeys.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n );\n });\n\nconst generateProvisioningProfileForBundle = (\n api: ApiClient,\n input: IosSetupInput,\n ctx: IosSetupContext,\n) =>\n Effect.gen(function* () {\n yield* Console.log(\"Generating provisioning profile via App Store Connect API...\");\n const generated = yield* generateAndUploadProvisioningProfile(api, {\n ascApiKeyId: ctx.ascKeyId,\n distributionCertificateId: ctx.certId,\n bundleIdentifier: input.bundleIdentifier,\n distributionType: ctx.distributionType,\n });\n return generated.id;\n });\n\nexport const resolveIosProfileId = (api: ApiClient, input: IosSetupInput, ctx: IosSetupContext) =>\n Effect.gen(function* () {\n const profiles = yield* api.appleProvisioningProfiles.list({ urlParams: {} });\n const matching = profiles.items.filter(\n (profile) =>\n profile.bundleIdentifier === input.bundleIdentifier &&\n profile.distributionType === ctx.distributionType &&\n profile.appleTeamId === ctx.cert.appleTeamId,\n );\n if (matching.length === 0) {\n return yield* generateProvisioningProfileForBundle(api, input, ctx);\n }\n const useExisting = yield* promptConfirm(\n `Reuse an existing ${input.distribution} profile for ${input.bundleIdentifier}?`,\n { initialValue: true },\n );\n if (!useExisting) {\n return yield* generateProvisioningProfileForBundle(api, input, ctx);\n }\n return yield* promptSelect<string>(\n \"Select a provisioning profile\",\n matching.map((profile) => ({\n value: profile.id,\n label: profile.profileName ?? profile.developerPortalIdentifier ?? profile.id,\n })),\n );\n });\n\nconst setupIosInteractive = (api: ApiClient, input: IosSetupInput) =>\n Effect.gen(function* () {\n yield* Console.log(\"\");\n yield* Console.log(\n `No iOS bundle configuration for ${input.bundleIdentifier} (${input.distribution}).`,\n );\n\n const { certId, cert } = yield* pickIosCertificate(api);\n const ascKeyId = yield* pickIosAscKey(api, cert.appleTeamId);\n const distributionType = IOS_DISTRIBUTION_TO_TYPE[input.distribution];\n const ctx: IosSetupContext = { certId, cert, ascKeyId, distributionType };\n const profileId = yield* resolveIosProfileId(api, input, ctx);\n\n yield* api.iosBundleConfigurations.create({\n path: { projectId: input.projectId },\n payload: {\n bundleIdentifier: input.bundleIdentifier,\n distributionType,\n appleTeamId: cert.appleTeamId,\n appleDistributionCertificateId: certId,\n appleProvisioningProfileId: profileId,\n ascApiKeyId: ascKeyId,\n },\n });\n yield* Console.log(\"iOS bundle configuration saved.\");\n return undefined;\n });\n\nconst resolveIosBuildCredentials = (api: ApiClient, input: IosSetupInput) =>\n api.buildCredentials.resolve({\n path: { projectId: input.projectId },\n payload: {\n platform: \"ios\",\n bundleIdentifier: input.bundleIdentifier,\n distributionType: IOS_DISTRIBUTION_TO_TYPE[input.distribution],\n },\n });\n\nconst findBoundIosConfig = (api: ApiClient, input: IosSetupInput) =>\n Effect.gen(function* () {\n const distributionType = IOS_DISTRIBUTION_TO_TYPE[input.distribution];\n const configs = yield* api.iosBundleConfigurations.list({\n path: { projectId: input.projectId },\n });\n const match = configs.items.find(\n (config) =>\n config.bundleIdentifier === input.bundleIdentifier &&\n config.distributionType === distributionType,\n );\n if (match === undefined) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: `iOS bundle configuration vanished while regenerating stale profile for ${input.bundleIdentifier}`,\n hint: \"Retry; the configuration must exist before regeneration\",\n }),\n );\n }\n return match;\n });\n\nexport const regenerateProvisioningProfile = (api: ApiClient, input: IosSetupInput) =>\n Effect.gen(function* () {\n const config = yield* findBoundIosConfig(api, input);\n if (config.ascApiKeyId === null || config.appleDistributionCertificateId === null) {\n return yield* new MissingCredentialsError({\n message:\n \"Profile cannot be regenerated: bundle configuration is missing ASC key or distribution certificate\",\n hint: \"Re-bind credentials via `better-update credentials generate` or the dashboard\",\n });\n }\n yield* Console.log(\"Regenerating provisioning profile via App Store Connect API...\");\n const created = yield* generateAndUploadProvisioningProfile(api, {\n ascApiKeyId: config.ascApiKeyId,\n distributionCertificateId: config.appleDistributionCertificateId,\n bundleIdentifier: input.bundleIdentifier,\n distributionType: IOS_DISTRIBUTION_TO_TYPE[input.distribution],\n });\n yield* api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: { appleProvisioningProfileId: created.id },\n });\n return created;\n });\n\nexport const ensureIosCredentials = (\n api: ApiClient,\n input: IosSetupInput,\n options: EnsureCredentialsOptions,\n) =>\n resolveIosBuildCredentials(api, input).pipe(\n Effect.catchIf(isMissingResolveError, () =>\n Effect.gen(function* () {\n const mode = yield* InteractiveMode;\n if (options.freezeCredentials || !mode.allow) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: `No iOS build credentials for ${input.bundleIdentifier} (${input.distribution}).`,\n hint: options.freezeCredentials\n ? \"Run `better-update credentials generate` first, or remove --freeze-credentials.\"\n : \"Run `better-update credentials generate` first, or rerun with --interactive to configure now.\",\n }),\n );\n }\n yield* setupIosInteractive(api, input);\n return yield* resolveIosBuildCredentials(api, input);\n }),\n ),\n Effect.flatMap((resolved) =>\n Effect.gen(function* () {\n if (resolved.platform !== \"ios\" || !resolved.profileStale) {\n return undefined;\n }\n const mode = yield* InteractiveMode;\n if (options.freezeCredentials || !mode.allow) {\n return yield* Effect.fail(\n new MissingCredentialsError({\n message: `Stale provisioning profile for ${input.bundleIdentifier}; cannot regenerate without an interactive session.`,\n hint: options.freezeCredentials\n ? \"Run a build without --freeze-credentials once to refresh the profile, or run `better-update credentials regenerate-profile`.\"\n : \"Run `better-update credentials regenerate-profile --bundle <id> --distribution <type>` from an interactive terminal.\",\n }),\n );\n }\n yield* Console.log(\n `Stale provisioning profile for ${input.bundleIdentifier} (device roster changed). Regenerating...`,\n );\n yield* regenerateProvisioningProfile(api, input);\n return undefined;\n }),\n ),\n );\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport { runAndroidBuild } from \"../commands/build/android\";\nimport { runIosBuild } from \"../commands/build/ios\";\nimport { reserveAndUpload } from \"../commands/build/reserve-and-upload\";\nimport { readBuildProfile } from \"../lib/build-profile\";\nimport { clearBuildCaches } from \"../lib/clear-cache\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { BuildProfileError } from \"../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../lib/expo-config\";\nimport { formatCause } from \"../lib/format-error\";\nimport { readGitContext } from \"../lib/git-context\";\nimport { readGradleConfig, warnOnGradleMismatch } from \"../lib/gradle-config\";\nimport { printHuman, printKeyValue } from \"../lib/output\";\nimport { detectPlatform } from \"../lib/platform-detect\";\nimport { ensureRepoClean } from \"../lib/repo-clean\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { acquireBuildTempDir } from \"../lib/temp-dir\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { ensureAndroidCredentials, ensureIosCredentials } from \"./credentials-interactive\";\n\nimport type { BuildTarget } from \"../commands/build/reserve-and-upload\";\nimport type { Platform } from \"../lib/build-profile\";\n\nexport interface RunBuildWorkflowOptions {\n readonly platform: Platform | undefined;\n readonly profileName: string;\n readonly message: string | undefined;\n readonly noUpload: boolean;\n readonly output?: string;\n readonly rawOutput?: boolean;\n readonly clearCache?: boolean;\n readonly freezeCredentials?: boolean;\n readonly allowDirty?: boolean;\n}\n\ntype AppMeta = Effect.Effect.Success<ReturnType<typeof readAppMeta>>;\ntype BuildProfile = Effect.Effect.Success<ReturnType<typeof readBuildProfile>>;\ntype ApiClient = Effect.Effect.Success<typeof apiClient>;\n\ninterface PlatformBuildInput {\n readonly api: ApiClient;\n readonly options: RunBuildWorkflowOptions;\n readonly platform: Platform;\n readonly profile: BuildProfile;\n readonly appMeta: AppMeta;\n readonly envVars: Record<string, string>;\n readonly projectId: string;\n readonly projectRoot: string;\n readonly tempDir: string;\n}\n\nconst runIosPlatformBuild = (input: PlatformBuildInput) =>\n Effect.gen(function* () {\n const { api, appMeta, envVars, options, profile, projectId, projectRoot, tempDir } = input;\n if (!profile.ios) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no ios section.`,\n });\n }\n const iosProfile = profile.ios;\n const iosBundleId = appMeta.bundleId;\n if (!iosBundleId) {\n return yield* new BuildProfileError({\n message: \"Missing ios.bundleIdentifier in your Expo config.\",\n });\n }\n const isSimulator = iosProfile.simulator === true;\n const credentialsSource = profile.credentialsSource ?? \"remote\";\n if (!isSimulator && credentialsSource === \"remote\") {\n yield* ensureIosCredentials(\n api,\n {\n projectId,\n bundleIdentifier: iosBundleId,\n distribution: iosProfile.distribution,\n },\n { freezeCredentials: options.freezeCredentials ?? false },\n );\n }\n const build = yield* runIosBuild({\n api,\n tempDir,\n projectRoot,\n iosProfile,\n bundleId: iosBundleId,\n envVars,\n projectId,\n credentialsSource,\n rawOutput: options.rawOutput,\n });\n const target: BuildTarget = isSimulator\n ? { platform: \"ios\", distribution: \"simulator\", artifactFormat: \"tar.gz\" }\n : { platform: \"ios\", distribution: iosProfile.distribution, artifactFormat: \"ipa\" };\n return { build, target, bundleId: iosBundleId };\n });\n\nconst runAndroidPlatformBuild = (input: PlatformBuildInput) =>\n Effect.gen(function* () {\n const { api, appMeta, envVars, options, profile, projectId, projectRoot, tempDir } = input;\n if (!profile.android) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no android section.`,\n });\n }\n const androidProfile = profile.android;\n const androidBundleId = appMeta.androidPackage;\n if (!androidBundleId) {\n return yield* new BuildProfileError({\n message: \"Missing android.package in your Expo config.\",\n });\n }\n // Cross-validate Gradle config against the Expo config (Groovy only). When\n // Gradle resolves a different applicationId, the built APK/AAB is signed\n // Under that id — so the Credential resolver must key off the Gradle value.\n const androidDir = `${projectRoot}/android`;\n const gradleConfig = yield* readGradleConfig(androidDir);\n yield* warnOnGradleMismatch(gradleConfig, androidBundleId);\n const applicationIdentifier = gradleConfig?.applicationId ?? androidBundleId;\n const credentialsSource = profile.credentialsSource ?? \"remote\";\n if (credentialsSource === \"remote\") {\n yield* ensureAndroidCredentials(\n api,\n { projectId, applicationIdentifier },\n { freezeCredentials: options.freezeCredentials ?? false },\n );\n }\n const build = yield* runAndroidBuild({\n api,\n tempDir,\n projectRoot,\n androidProfile,\n applicationIdentifier,\n envVars,\n projectId,\n credentialsSource,\n });\n const target: BuildTarget =\n androidProfile.format === \"aab\"\n ? { platform: \"android\", distribution: \"play-store\", artifactFormat: \"aab\" }\n : { platform: \"android\", distribution: \"direct\", artifactFormat: \"apk\" };\n return { build, target, bundleId: applicationIdentifier };\n });\n\nconst runPlatformBuild = (input: PlatformBuildInput) =>\n input.platform === \"ios\" ? runIosPlatformBuild(input) : runAndroidPlatformBuild(input);\n\nexport const runBuildWorkflow = (options: RunBuildWorkflowOptions) =>\n Effect.scoped(\n // eslint-disable-next-line eslint/max-statements -- build orchestration is inherently sequential (read config → detect platform → resolve profile → pull env → build → upload); splitting further fragments the pipeline\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n\n yield* ensureRepoClean({\n projectRoot,\n allowDirty: options.allowDirty ?? false,\n label: \"build\",\n });\n\n // Read the project's Expo config to extract projectId.\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n const platform = yield* detectPlatform(options.platform, baseConfig);\n\n // Resolve the build profile from eas.json — static, env-independent.\n const profile = yield* readBuildProfile(projectRoot, options.profileName);\n\n // Pull env vars for the profile's environment scope.\n const envVars = yield* pullEnvVars(api, {\n projectId,\n environment: profile.environment,\n });\n\n // Re-resolve the Expo config with the env overlay so dynamic configs\n // (app.config.js/ts) can read these env vars when computing AppMeta\n // (bundleId, version, runtimeVersion). envVars are scoped to the call\n // so they don't leak to child processes.\n const expoConfig = yield* readExpoConfig(projectRoot, envVars);\n const appMeta = yield* readAppMeta(expoConfig, platform);\n\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: appMeta.rawRuntimeVersion,\n appVersion: appMeta.appVersion,\n projectRoot,\n });\n\n if (options.clearCache) {\n yield* clearBuildCaches(projectRoot);\n }\n\n const tempDir = yield* acquireBuildTempDir;\n\n yield* Console.log(\n `Building ${platform} artifact for profile \"${profile.name}\" (runtimeVersion=${runtimeVersion})`,\n );\n\n const outcome = yield* runPlatformBuild({\n api,\n options,\n platform,\n profile,\n appMeta,\n envVars,\n projectId,\n projectRoot,\n tempDir,\n });\n const { build, target, bundleId } = outcome;\n\n yield* Console.log(`Artifact produced: ${build.artifactPath}`);\n\n let exportedArtifactPath: string | undefined = undefined;\n if (options.output !== undefined) {\n const fs = yield* FileSystem.FileSystem;\n const outputPath = path.resolve(projectRoot, options.output);\n const outputDir = path.dirname(outputPath);\n yield* fs.makeDirectory(outputDir, { recursive: true }).pipe(\n Effect.mapError(\n (cause) =>\n new BuildProfileError({\n message: `Failed to create output directory: ${formatCause(cause)}`,\n }),\n ),\n );\n yield* fs.copyFile(build.artifactPath, outputPath).pipe(\n Effect.mapError(\n (cause) =>\n new BuildProfileError({\n message: `Failed to copy artifact to ${outputPath}: ${formatCause(cause)}`,\n }),\n ),\n );\n exportedArtifactPath = outputPath;\n yield* printHuman(`Copied artifact to ${outputPath}`);\n }\n\n if (options.noUpload) {\n yield* printKeyValue([\n [\"Artifact\", build.artifactPath],\n ...(exportedArtifactPath === undefined\n ? []\n : [[\"Exported to\", exportedArtifactPath] as const]),\n [\"SHA-256\", build.sha256],\n [\"Bytes\", String(build.byteSize)],\n [\"Upload\", \"skipped (--no-upload)\"],\n ]);\n return;\n }\n\n const rawGitContext = yield* readGitContext(projectRoot);\n const gitContext: {\n readonly ref?: string;\n readonly commit?: string;\n readonly dirty: boolean;\n } = {\n ...(rawGitContext.ref === undefined ? {} : { ref: rawGitContext.ref }),\n ...(rawGitContext.commit === undefined ? {} : { commit: rawGitContext.commit }),\n dirty: rawGitContext.dirty,\n };\n\n const result = yield* reserveAndUpload(api, {\n target,\n projectId,\n profileName: profile.name,\n runtimeVersion,\n ...(appMeta.appVersion === undefined ? {} : { appVersion: appMeta.appVersion }),\n ...(appMeta.buildNumber === undefined ? {} : { buildNumber: appMeta.buildNumber }),\n bundleId,\n gitContext,\n ...(options.message === undefined ? {} : { message: options.message }),\n artifactPath: build.artifactPath,\n sha256: build.sha256,\n byteSize: build.byteSize,\n });\n\n yield* Console.log(\"\");\n yield* printKeyValue([\n [\"Build ID\", result.id],\n [\"Status\", result.status],\n [\"Platform\", platform],\n [\"Profile\", profile.name],\n [\"Runtime version\", runtimeVersion],\n [\"Artifact\", build.artifactPath],\n [\"SHA-256\", build.sha256],\n [\"Bytes\", String(build.byteSize)],\n ]);\n }),\n );\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseEasConfig } from \"../../lib/eas-config\";\nimport { BuildProfileError } from \"../../lib/exit-codes\";\nimport { printHuman, printKeyValue } from \"../../lib/output\";\nimport { promptConfirm } from \"../../lib/prompts\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nconst DEFAULT_EAS_JSON = {\n cli: {\n version: \">= 7.0.0\",\n },\n build: {\n development: {\n developmentClient: true,\n distribution: \"internal\",\n channel: \"development\",\n environment: \"development\",\n android: { format: \"apk\" },\n },\n preview: {\n distribution: \"internal\",\n channel: \"preview\",\n environment: \"preview\",\n android: { format: \"apk\" },\n },\n production: {\n channel: \"production\",\n environment: \"production\",\n android: { format: \"aab\" },\n },\n },\n};\n\nconst DEFAULT_PROFILES = [\"development\", \"preview\", \"production\"] as const;\n\nconst writeEasJson = (filePath: string, value: unknown) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .writeFileString(filePath, `${JSON.stringify(value, null, 2)}\\n`)\n .pipe(\n Effect.mapError(\n (cause) =>\n new BuildProfileError({ message: `Failed to write eas.json: ${cause.message}` }),\n ),\n );\n });\n\nexport const configureBuildCommand = defineCommand({\n meta: {\n name: \"configure\",\n description: \"Scaffold or top up eas.json with default development/preview/production profiles\",\n },\n args: {\n force: {\n type: \"boolean\",\n description: \"Overwrite an existing eas.json with the defaults\",\n },\n \"non-interactive\": {\n type: \"boolean\",\n description: \"Add missing default profiles without prompting (no overwrite)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n // eslint-disable-next-line eslint/max-statements -- linear orchestration: detect → branch on (missing|invalid|valid)\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const easJsonPath = path.join(projectRoot, \"eas.json\");\n\n const fs = yield* FileSystem.FileSystem;\n const exists = yield* fs.exists(easJsonPath);\n\n if (!exists) {\n yield* writeEasJson(easJsonPath, DEFAULT_EAS_JSON);\n yield* Console.log(`Wrote eas.json with default profiles to ${easJsonPath}.`);\n yield* printKeyValue([\n [\"Profiles\", DEFAULT_PROFILES.join(\", \")],\n [\"Path\", easJsonPath],\n ]);\n return undefined;\n }\n\n if (args.force === true) {\n const proceed =\n args[\"non-interactive\"] === true\n ? true\n : yield* promptConfirm(\n `Overwrite existing eas.json at ${easJsonPath} with defaults?`,\n );\n if (!proceed) {\n yield* printHuman(\"Aborted. eas.json was not modified.\");\n return undefined;\n }\n yield* writeEasJson(easJsonPath, DEFAULT_EAS_JSON);\n yield* Console.log(`Overwrote eas.json with default profiles.`);\n return undefined;\n }\n\n const existingRaw = yield* fs\n .readFileString(easJsonPath)\n .pipe(\n Effect.mapError(\n (cause) =>\n new BuildProfileError({ message: `Failed to read eas.json: ${cause.message}` }),\n ),\n );\n const config = yield* parseEasConfig(existingRaw);\n\n const existingProfiles = Object.keys(config.build ?? {});\n const missing = DEFAULT_PROFILES.filter((name) => !existingProfiles.includes(name));\n\n if (missing.length === 0) {\n yield* printHuman(\n `eas.json already defines all default profiles (${existingProfiles.join(\", \")}). Nothing to add.`,\n );\n yield* printHuman(\"Pass --force to overwrite with the default template.\");\n return undefined;\n }\n\n const proceed =\n args[\"non-interactive\"] === true\n ? true\n : yield* promptConfirm(\n `Add missing profile(s) [${missing.join(\", \")}] to existing eas.json?`,\n { initialValue: true },\n );\n if (!proceed) {\n yield* printHuman(\"Aborted. eas.json was not modified.\");\n return undefined;\n }\n\n const additions = Object.fromEntries(\n missing.map((name) => [name, DEFAULT_EAS_JSON.build[name]]),\n );\n const merged = {\n ...(config.cli === undefined ? {} : { cli: config.cli }),\n build: {\n ...config.build,\n ...additions,\n },\n };\n yield* writeEasJson(easJsonPath, merged);\n yield* Console.log(`Added profile(s) to eas.json: ${missing.join(\", \")}.`);\n yield* printKeyValue([\n [\"Existing\", existingProfiles.join(\", \") || \"(none)\"],\n [\"Added\", missing.join(\", \")],\n [\"Path\", easJsonPath],\n ]);\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { runBuildWorkflow } from \"../../application/build-workflow\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { configureBuildCommand } from \"./configure\";\n\nconst BUILD_EXIT_EXTRAS = {\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n MissingCredentialsError: 5,\n BuildFailedError: 6,\n KeychainError: 6,\n ProvisioningError: 6,\n ArtifactNotFoundError: 6,\n ReserveError: 7,\n UploadFailedError: 7,\n PresignedUrlExpiredError: 7,\n CompleteError: 7,\n EnvExportError: 7,\n DirtyRepoError: 3,\n} as const;\n\nexport const buildCommand = defineCommand({\n meta: { name: \"build\", description: \"Build the app locally and optionally upload\" },\n subCommands: {\n configure: configureBuildCommand,\n },\n args: {\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\"],\n description: \"Target platform (auto-detected from app.json when omitted)\",\n },\n profile: { type: \"string\", default: \"production\", description: \"Build profile name\" },\n message: { type: \"string\", description: \"Optional build message\" },\n upload: {\n type: \"boolean\",\n default: true,\n description: \"Upload the built artifact to better-update\",\n negativeDescription: \"Skip upload (use --no-upload)\",\n },\n output: {\n type: \"string\",\n description: \"Copy the built artifact to this path after completing the build\",\n },\n \"raw-output\": { type: \"boolean\", description: \"Stream raw Gradle/Xcode output\" },\n \"clear-cache\": {\n type: \"boolean\",\n description: \"Clear project-scoped build caches before building\",\n },\n \"freeze-credentials\": {\n type: \"boolean\",\n description: \"Fail fast if credentials missing instead of prompting (for CI)\",\n },\n \"allow-dirty\": {\n type: \"boolean\",\n description: \"Proceed even with uncommitted git changes\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n runBuildWorkflow({\n platform: args.platform,\n profileName: args.profile,\n message: args.message,\n noUpload: !args.upload,\n ...(args.output === undefined ? {} : { output: args.output }),\n rawOutput: args[\"raw-output\"] ?? false,\n clearCache: args[\"clear-cache\"] ?? false,\n freezeCredentials: args[\"freeze-credentials\"] ?? false,\n allowDirty: args[\"allow-dirty\"] ?? false,\n }),\n BUILD_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printHuman, printJson, printTable } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const compatibilityMatrixCommand = defineCommand({\n meta: {\n name: \"compatibility-matrix\",\n description: \"Show build-to-channel compatibility and missing runtime versions\",\n },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const result = yield* api.builds.compatibilityMatrix({ urlParams: { projectId } });\n\n const matrixKeys = Object.keys(result.channelStatusByKey);\n\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(result);\n return;\n }\n\n if (matrixKeys.length === 0 && result.missingRuntimeVersions.length === 0) {\n yield* printHuman(\"No compatibility data found.\");\n return;\n }\n\n const channelLookup: Record<string, string> = Object.fromEntries(\n result.channels.map((channel) => [channel.channelId, channel.channelName]),\n );\n\n if (matrixKeys.length > 0) {\n yield* printHuman(\"Channel Status by (Platform / Runtime Version):\");\n yield* printTable(\n [\"Platform / Runtime\", \"Channel\", \"Updates\"],\n matrixKeys.flatMap((key) =>\n (result.channelStatusByKey[key] ?? [])\n .filter((entry) => entry.updateCount > 0)\n .map((entry) => [\n key,\n channelLookup[entry.channelId] ?? entry.channelId,\n String(entry.updateCount),\n ]),\n ),\n );\n }\n\n if (result.missingRuntimeVersions.length > 0) {\n yield* printHuman(\"\\nMissing Runtime Versions:\");\n yield* printTable(\n [\"Channel\", \"Platform\", \"Runtime Version\", \"Updates\"],\n result.missingRuntimeVersions.map((missing) => [\n missing.channelName,\n missing.platform,\n missing.runtimeVersion,\n String(missing.updateCount),\n ]),\n );\n }\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a build\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.builds.delete({ path: { id: args.id } });\n yield* Console.log(`Build ${args.id} deleted.`);\n }),\n ),\n});\n","import { Buffer } from \"node:buffer\";\nimport path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { UploadFailedError } from \"../../lib/exit-codes\";\nimport { formatCause } from \"../../lib/format-error\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nconst EXIT_EXTRAS = { UploadFailedError: 7 } as const;\n\nconst fetchArtifact = (url: string): Effect.Effect<Buffer, UploadFailedError> =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: async () => fetch(url),\n catch: (cause) =>\n new UploadFailedError({\n message: `Failed to request artifact: ${formatCause(cause)}`,\n }),\n });\n if (!response.ok) {\n return yield* new UploadFailedError({\n message: `Failed to download artifact: HTTP ${String(response.status)} ${response.statusText}`,\n });\n }\n const buffer = yield* Effect.tryPromise({\n try: async () => response.arrayBuffer(),\n catch: (cause) =>\n new UploadFailedError({\n message: `Failed to read artifact body: ${formatCause(cause)}`,\n }),\n });\n return Buffer.from(buffer);\n });\n\nexport const downloadCommand = defineCommand({\n meta: {\n name: \"download\",\n description: \"Download the artifact for a build (.ipa/.apk/.aab) to a local path\",\n },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n output: {\n type: \"string\",\n description: \"Output path (default: ./<id>.<ext> inferred from artifact format)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const fs = yield* FileSystem.FileSystem;\n const runtime = yield* CliRuntime;\n const cwd = yield* runtime.cwd;\n\n const build = yield* api.builds.get({ path: { id: args.id } });\n const { artifact } = build;\n if (!artifact) {\n yield* Effect.fail(\n new UploadFailedError({ message: `Build ${args.id} has no artifact yet.` }),\n );\n return;\n }\n\n const link = yield* api.builds.getInstallLink({ path: { id: args.id } });\n const ext = artifact.format;\n const outputPath = args.output ?? path.join(cwd, `${args.id}.${ext}`);\n\n const bytes = yield* fetchArtifact(link.artifactUrl);\n yield* fs.writeFile(outputPath, bytes);\n\n yield* printKeyValue([\n [\"Path\", outputPath],\n [\"Format\", ext],\n [\"Size\", `${String(bytes.byteLength)} bytes`],\n ]);\n }),\n EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const getCommand = defineCommand({\n meta: { name: \"get\", description: \"Show a build\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const build = yield* api.builds.get({ path: { id: args.id } });\n yield* printKeyValue([\n [\"ID\", build.id],\n [\"Platform\", build.platform],\n [\"Profile\", build.profile],\n [\"Distribution\", build.distribution],\n [\"Version\", build.appVersion ?? \"-\"],\n [\"Build Number\", build.buildNumber ?? \"-\"],\n [\"Runtime Version\", build.runtimeVersion ?? \"-\"],\n [\"Bundle ID\", build.bundleId ?? \"-\"],\n [\"Git Ref\", build.gitRef ?? \"-\"],\n [\"Message\", build.message ?? \"-\"],\n [\n \"Artifact\",\n build.artifact\n ? `${build.artifact.format} (${String(build.artifact.byteSize)} bytes)`\n : \"none\",\n ],\n [\"Created\", build.createdAt],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const installLinkCommand = defineCommand({\n meta: { name: \"install-link\", description: \"Get install/artifact URLs for a build\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.builds.getInstallLink({ path: { id: args.id } });\n yield* printKeyValue([\n [\"Artifact URL\", result.artifactUrl],\n [\"Install URL\", result.installUrl ?? \"-\"],\n [\"Expires\", String(result.expires)],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseLimit } from \"../../lib/cli-schemas\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printTable } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nconst SORT_OPTIONS = [\n \"createdAt\",\n \"-createdAt\",\n \"platform\",\n \"-platform\",\n \"distribution\",\n \"-distribution\",\n \"runtimeVersion\",\n \"-runtimeVersion\",\n \"appVersion\",\n \"-appVersion\",\n] as const;\n\nconst DISTRIBUTION_OPTIONS = [\n \"app-store\",\n \"ad-hoc\",\n \"development\",\n \"enterprise\",\n \"simulator\",\n \"play-store\",\n \"direct\",\n] as const;\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List builds for the linked project\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], description: \"Filter by platform\" },\n profile: { type: \"string\", description: \"Filter by build profile name\" },\n \"runtime-version\": { type: \"string\", description: \"Filter by runtime version\" },\n distribution: {\n type: \"enum\",\n options: [...DISTRIBUTION_OPTIONS],\n description: \"Filter by distribution channel\",\n },\n sort: {\n type: \"enum\",\n options: [...SORT_OPTIONS],\n description: \"Sort column; prefix with `-` for descending (e.g. -createdAt)\",\n },\n limit: { type: \"string\", default: \"10\", description: \"Max rows (default 10)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const limit = yield* parseLimit(args.limit, 10);\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const { items } = yield* api.builds.list({\n urlParams: {\n projectId,\n limit,\n ...(args.platform === undefined ? {} : { platform: args.platform }),\n ...(args.profile === undefined ? {} : { profile: args.profile }),\n ...(args[\"runtime-version\"] === undefined\n ? {}\n : { runtimeVersion: args[\"runtime-version\"] }),\n ...(args.distribution === undefined ? {} : { distribution: args.distribution }),\n ...(args.sort === undefined ? {} : { sort: args.sort }),\n },\n });\n\n yield* printTable(\n [\"ID\", \"Platform\", \"Profile\", \"Distribution\", \"Version\", \"Created\"],\n items.map((build) => [\n build.id,\n build.platform,\n build.profile,\n build.distribution,\n build.appVersion ?? \"-\",\n build.createdAt,\n ]),\n );\n }),\n ),\n});\n","import process from \"node:process\";\n\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printHuman } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nconst resignWorkflowText = (buildId: string, installLink: string) =>\n `Resigning iOS build ${buildId}\n=================================================\n\niOS code-signing requires native macOS tooling (codesign, security, xcodebuild)\nand the matching distribution certificate in your Keychain. better-update does\nnot bundle that toolchain — instead it gives you the inputs and a re-upload\npath.\n\nStep 1 — Download the existing IPA\n ${installLink}\n\nStep 2 — Resign the IPA locally with your new provisioning profile.\n Pick one of:\n a) fastlane sigh resign:\n fastlane sigh resign /tmp/build.ipa \\\\\n --signing_identity \"iPhone Distribution: Your Team (ABCDE12345)\" \\\\\n --provisioning_profile /path/to/new.mobileprovision\n\n b) Apple's codesign + xcodebuild:\n unzip /tmp/build.ipa -d /tmp/payload\n cp /path/to/new.mobileprovision /tmp/payload/Payload/YourApp.app/embedded.mobileprovision\n codesign -f -s \"iPhone Distribution: Your Team (ABCDE12345)\" \\\\\n --entitlements <(security cms -D -i /path/to/new.mobileprovision) \\\\\n /tmp/payload/Payload/YourApp.app\n (cd /tmp/payload && zip -qr /tmp/resigned.ipa Payload)\n\nStep 3 — Upload the re-signed IPA as a fresh build:\n better-update builds upload --platform ios --profile <profile> \\\\\n --artifact /tmp/resigned.ipa --project <projectId>\n\nThe new build will get a fresh build ID. The original build remains for\nrollback. Disable or delete it when the re-signed build is verified.\n`;\n\nexport const resignCommand = defineCommand({\n meta: {\n name: \"resign\",\n description:\n \"Print step-by-step instructions for re-signing an iOS build with a new provisioning profile\",\n },\n args: {\n build: { type: \"string\", required: true, description: \"Source build ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const build = yield* api.builds.get({ path: { id: args.build } });\n if (build.platform !== \"ios\") {\n yield* printHuman(\n `Build ${args.build} is ${build.platform}. Re-signing this command currently covers iOS only.`,\n );\n process.exitCode = 2;\n return undefined;\n }\n const link = yield* api.builds.getInstallLink({ path: { id: args.build } });\n yield* printHuman(resignWorkflowText(args.build, link.artifactUrl));\n return undefined;\n }),\n ),\n});\n","import { Buffer } from \"node:buffer\";\nimport path from \"node:path\";\n\nimport { asRecord } from \"@better-update/type-guards\";\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Data, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { parsePlist } from \"./plist\";\n\nexport class NativeRunError extends Data.TaggedError(\"NativeRunError\")<{\n readonly message: string;\n}> {}\n\nexport const execCapture = (\n step: string,\n bin: string,\n ...args: readonly string[]\n): Effect.Effect<string, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const result = yield* Command.string(Command.make(bin, ...args)).pipe(\n Effect.mapError(\n (cause) => new NativeRunError({ message: `${step} failed: ${String(cause)}` }),\n ),\n );\n return result;\n });\n\nconst runInherit = (\n step: string,\n bin: string,\n ...args: readonly string[]\n): Effect.Effect<void, NativeRunError, CommandExecutor.CommandExecutor> =>\n Command.exitCode(\n Command.make(bin, ...args).pipe(Command.stdout(\"inherit\"), Command.stderr(\"inherit\")),\n ).pipe(\n Effect.mapError(\n (cause) => new NativeRunError({ message: `${step} failed to spawn: ${String(cause)}` }),\n ),\n Effect.flatMap((code) =>\n code === 0\n ? Effect.void\n : Effect.fail(new NativeRunError({ message: `${step} exited with code ${String(code)}` })),\n ),\n );\n\n/**\n * Locate a tool on PATH. Returns the absolute path or fails with NativeRunError.\n */\nexport const which = (\n bin: string,\n): Effect.Effect<string, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const output = yield* Command.string(Command.make(\"which\", bin)).pipe(\n Effect.catchAll(() =>\n Effect.fail(new NativeRunError({ message: `${bin} not found in PATH` })),\n ),\n );\n const trimmed = output.trim();\n if (trimmed === \"\") {\n return yield* new NativeRunError({ message: `${bin} not found in PATH` });\n }\n return trimmed;\n });\n\n/**\n * Extract a .tar.gz into destDir using the system `tar` binary.\n */\nexport const extractTarGz = (\n archive: string,\n destDir: string,\n): Effect.Effect<void, NativeRunError, CommandExecutor.CommandExecutor> =>\n runInherit(\"tar -xzf\", \"tar\", \"-xzf\", archive, \"-C\", destDir);\n\n/**\n * Extract a zip-like archive (e.g. .ipa) into destDir.\n */\nexport const extractZip = (\n archive: string,\n destDir: string,\n): Effect.Effect<void, NativeRunError, CommandExecutor.CommandExecutor> =>\n runInherit(\"unzip\", \"unzip\", \"-q\", \"-o\", archive, \"-d\", destDir);\n\n/**\n * Locate the first `.app` directory under root (recursive, depth ≤ 3).\n */\nexport const findAppBundle = (\n root: string,\n): Effect.Effect<string, NativeRunError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const candidates = [root, path.join(root, \"Payload\")];\n for (const candidate of candidates) {\n const entries = yield* fs\n .readDirectory(candidate)\n .pipe(Effect.catchAll(() => Effect.succeed<readonly string[]>([])));\n const app = entries.find((entry) => entry.endsWith(\".app\"));\n if (app) {\n return path.join(candidate, app);\n }\n }\n return yield* new NativeRunError({\n message: `No .app bundle found inside ${root} or ${path.join(root, \"Payload\")}.`,\n });\n });\n\n/**\n * Read CFBundleIdentifier from an .app bundle's Info.plist.\n */\nexport const readBundleIdFromApp = (\n appDir: string,\n): Effect.Effect<string, NativeRunError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const plistPath = path.join(appDir, \"Info.plist\");\n const data = yield* fs\n .readFile(plistPath)\n .pipe(\n Effect.mapError(\n (cause) => new NativeRunError({ message: `Failed to read Info.plist: ${String(cause)}` }),\n ),\n );\n const parsed = parsePlist(Buffer.from(data));\n const bundleId = parsed[\"CFBundleIdentifier\"];\n if (typeof bundleId !== \"string\" || bundleId === \"\") {\n return yield* new NativeRunError({\n message: `Info.plist at ${plistPath} is missing CFBundleIdentifier.`,\n });\n }\n return bundleId;\n });\n\nexport interface BootedSimulator {\n readonly udid: string;\n readonly name: string;\n}\n\ninterface SimctlDevice {\n readonly udid: string;\n readonly name: string;\n readonly state: string;\n readonly isAvailable: boolean;\n}\n\nconst isSimctlDevice = (value: unknown): value is SimctlDevice => {\n const record = asRecord(value);\n if (!record) {\n return false;\n }\n return (\n typeof record[\"udid\"] === \"string\" &&\n typeof record[\"name\"] === \"string\" &&\n typeof record[\"state\"] === \"string\" &&\n typeof record[\"isAvailable\"] === \"boolean\"\n );\n};\n\nconst parseSimctlList = (raw: string): Effect.Effect<readonly SimctlDevice[], NativeRunError> =>\n Effect.gen(function* () {\n const parsed = yield* Effect.try({\n try: (): unknown => JSON.parse(raw),\n catch: () =>\n new NativeRunError({ message: \"Failed to parse `simctl list devices --json` output.\" }),\n });\n const root = asRecord(parsed);\n const devicesField = root ? asRecord(root[\"devices\"]) : undefined;\n if (!devicesField) {\n return [];\n }\n return Object.values(devicesField)\n .filter((group): group is readonly unknown[] => Array.isArray(group))\n .flatMap((group) => group.filter(isSimctlDevice));\n });\n\n/**\n * Pick an iOS simulator: --simulator flag wins (matches name or udid), else the\n * first booted simulator, else fail with a list of bootable choices.\n */\nexport const pickSimulator = (\n selector: string | undefined,\n): Effect.Effect<BootedSimulator, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const raw = yield* execCapture(\n \"xcrun simctl list devices --json\",\n \"xcrun\",\n \"simctl\",\n \"list\",\n \"devices\",\n \"--json\",\n );\n const devices = yield* parseSimctlList(raw);\n const available = devices.filter((device) => device.isAvailable);\n\n if (selector !== undefined) {\n const match = available.find(\n (device) => device.udid === selector || device.name === selector,\n );\n if (!match) {\n return yield* new NativeRunError({\n message: `Simulator \"${selector}\" not found. Run \\`xcrun simctl list devices\\` to inspect available devices.`,\n });\n }\n return { udid: match.udid, name: match.name };\n }\n\n const booted = available.find((device) => device.state === \"Booted\");\n if (booted) {\n return { udid: booted.udid, name: booted.name };\n }\n\n return yield* new NativeRunError({\n message:\n \"No booted simulator found. Pass --simulator <name|udid>, or boot one with `xcrun simctl boot <udid>` and re-run.\",\n });\n });\n\nexport interface ConnectedAndroidDevice {\n readonly serial: string;\n}\n\n/**\n * Pick an Android device or emulator via adb devices.\n */\nexport const pickAndroidDevice = (\n selector: string | undefined,\n): Effect.Effect<ConnectedAndroidDevice, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const raw = yield* execCapture(\"adb devices\", \"adb\", \"devices\");\n const lines = raw\n .split(\"\\n\")\n .slice(1)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && line.endsWith(\"device\"));\n const serials = lines\n .map((line) => line.split(/\\s+/u)[0])\n .filter((serial): serial is string => serial !== undefined);\n\n if (selector !== undefined) {\n const match = serials.find((serial) => serial === selector);\n if (!match) {\n return yield* new NativeRunError({\n message: `Android device \"${selector}\" not connected. Run \\`adb devices\\` to inspect available devices.`,\n });\n }\n return { serial: match };\n }\n\n const [first] = serials;\n if (!first) {\n return yield* new NativeRunError({\n message:\n \"No Android device or emulator connected. Start an emulator or attach a device, then re-run.\",\n });\n }\n return { serial: first };\n });\n\nexport const installAndLaunchIosSimulator = (params: {\n readonly udid: string;\n readonly appDir: string;\n readonly bundleId: string;\n}): Effect.Effect<void, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n yield* runInherit(\n `xcrun simctl install ${params.udid}`,\n \"xcrun\",\n \"simctl\",\n \"install\",\n params.udid,\n params.appDir,\n );\n yield* runInherit(\n `xcrun simctl launch ${params.udid} ${params.bundleId}`,\n \"xcrun\",\n \"simctl\",\n \"launch\",\n params.udid,\n params.bundleId,\n );\n });\n\nexport const installAndLaunchIosDevice = (params: {\n readonly udid: string;\n readonly ipaPath: string;\n readonly bundleId: string;\n}): Effect.Effect<void, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n yield* runInherit(\n `xcrun devicectl device install app --device ${params.udid}`,\n \"xcrun\",\n \"devicectl\",\n \"device\",\n \"install\",\n \"app\",\n \"--device\",\n params.udid,\n params.ipaPath,\n );\n yield* runInherit(\n `xcrun devicectl device process launch --device ${params.udid} ${params.bundleId}`,\n \"xcrun\",\n \"devicectl\",\n \"device\",\n \"process\",\n \"launch\",\n \"--device\",\n params.udid,\n params.bundleId,\n );\n });\n\n/**\n * Read the Android package name from an APK via aapt or aapt2. Returns\n * undefined if neither tool is on PATH or extraction fails — callers should\n * fall back to a CLI flag.\n */\nconst tryReadApkPackageWith = (\n bin: string,\n apkPath: string,\n): Effect.Effect<string | undefined, never, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const located = yield* which(bin).pipe(\n Effect.catchAll(() => Effect.succeed<string | null>(null)),\n );\n if (!located) {\n return undefined;\n }\n const raw = yield* execCapture(`${bin} dump`, bin, \"dump\", \"badging\", apkPath).pipe(\n Effect.catchAll(() => Effect.succeed<string | null>(null)),\n );\n if (!raw) {\n return undefined;\n }\n const match = /package: name='([^']+)'/u.exec(raw);\n return match?.[1];\n });\n\nexport const readApkPackageName = (\n apkPath: string,\n): Effect.Effect<string | undefined, never, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const candidates = [\"aapt2\", \"aapt\"] as const;\n return yield* Effect.reduce(candidates, undefined as string | undefined, (acc, bin) =>\n acc === undefined ? tryReadApkPackageWith(bin, apkPath) : Effect.succeed(acc),\n );\n });\n\nexport const installAndLaunchAndroid = (params: {\n readonly serial: string;\n readonly apkPath: string;\n readonly packageName: string;\n}): Effect.Effect<void, NativeRunError, CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n yield* runInherit(\n `adb -s ${params.serial} install`,\n \"adb\",\n \"-s\",\n params.serial,\n \"install\",\n \"-r\",\n params.apkPath,\n );\n yield* runInherit(\n `adb -s ${params.serial} monkey ${params.packageName}`,\n \"adb\",\n \"-s\",\n params.serial,\n \"shell\",\n \"monkey\",\n \"-p\",\n params.packageName,\n \"-c\",\n \"android.intent.category.LAUNCHER\",\n \"1\",\n );\n });\n","import { Buffer } from \"node:buffer\";\nimport path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError, UploadFailedError } from \"../../lib/exit-codes\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { formatCause } from \"../../lib/format-error\";\nimport {\n extractTarGz,\n extractZip,\n findAppBundle,\n installAndLaunchAndroid,\n installAndLaunchIosDevice,\n installAndLaunchIosSimulator,\n NativeRunError,\n pickAndroidDevice,\n pickSimulator,\n readApkPackageName,\n readBundleIdFromApp,\n} from \"../../lib/native-runner\";\nimport { printHuman, printKeyValue } from \"../../lib/output\";\nimport { acquireBuildTempDir } from \"../../lib/temp-dir\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\ntype ArtifactFormat = \"ipa\" | \"apk\" | \"aab\" | \"tar.gz\";\n\nconst RUN_EXIT_EXTRAS = {\n UploadFailedError: 7,\n NativeRunError: 6,\n InvalidArgumentError: 2,\n} as const;\n\nconst fetchArtifact = (url: string): Effect.Effect<Buffer, UploadFailedError> =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: async () => fetch(url),\n catch: (cause) =>\n new UploadFailedError({ message: `Failed to request artifact: ${formatCause(cause)}` }),\n });\n if (!response.ok) {\n return yield* new UploadFailedError({\n message: `HTTP ${String(response.status)} ${response.statusText}`,\n });\n }\n const buffer = yield* Effect.tryPromise({\n try: async () => response.arrayBuffer(),\n catch: (cause) =>\n new UploadFailedError({ message: `Failed to read artifact body: ${formatCause(cause)}` }),\n });\n return Buffer.from(buffer);\n });\n\nconst resolveBuild = (params: {\n readonly api: ApiClient;\n readonly id: string | undefined;\n readonly latest: boolean;\n readonly platform: \"ios\" | \"android\" | undefined;\n readonly projectId: string;\n}) =>\n Effect.gen(function* () {\n if (params.id !== undefined) {\n return yield* params.api.builds.get({ path: { id: params.id } });\n }\n if (!params.latest) {\n return yield* new InvalidArgumentError({\n message: \"Pass a build id, or use --latest --platform <ios|android>.\",\n });\n }\n if (!params.platform) {\n return yield* new InvalidArgumentError({\n message: \"--latest requires --platform <ios|android>.\",\n });\n }\n const list = yield* params.api.builds.list({\n urlParams: { projectId: params.projectId, platform: params.platform, limit: 1 },\n });\n const [first] = list.items;\n if (!first) {\n return yield* new InvalidArgumentError({\n message: `No builds found for platform ${params.platform}.`,\n });\n }\n return yield* params.api.builds.get({ path: { id: first.id } });\n });\n\ninterface IosRunParams {\n readonly tempDir: string;\n readonly artifactPath: string;\n readonly format: ArtifactFormat;\n readonly simulatorSelector: string | undefined;\n readonly deviceSelector: string | undefined;\n readonly useDevice: boolean;\n}\n\nconst extractIosArtifact = (params: {\n readonly tempDir: string;\n readonly artifactPath: string;\n readonly format: ArtifactFormat;\n readonly subdir: string;\n}) =>\n Effect.gen(function* () {\n const extractDir = path.join(params.tempDir, params.subdir);\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(extractDir, { recursive: true });\n yield* params.format === \"tar.gz\"\n ? extractTarGz(params.artifactPath, extractDir)\n : extractZip(params.artifactPath, extractDir);\n return extractDir;\n });\n\nconst runIosSimulator = (params: IosRunParams) =>\n Effect.gen(function* () {\n const extractDir = yield* extractIosArtifact({\n tempDir: params.tempDir,\n artifactPath: params.artifactPath,\n format: params.format,\n subdir: \"ios-simulator\",\n });\n const appDir = yield* findAppBundle(extractDir);\n const bundleId = yield* readBundleIdFromApp(appDir);\n const simulator = yield* pickSimulator(params.simulatorSelector);\n yield* printHuman(`Installing on simulator \"${simulator.name}\" (${simulator.udid})...`);\n yield* installAndLaunchIosSimulator({ udid: simulator.udid, appDir, bundleId });\n yield* printKeyValue([\n [\"Simulator\", simulator.name],\n [\"Bundle ID\", bundleId],\n [\"App\", appDir],\n ]);\n });\n\nconst runIosDevice = (params: IosRunParams) =>\n Effect.gen(function* () {\n const { deviceSelector } = params;\n if (deviceSelector === undefined) {\n yield* Effect.fail(\n new InvalidArgumentError({\n message:\n \"Pass --device-id <udid>. Run `xcrun devicectl list devices` to list connected devices.\",\n }),\n );\n return;\n }\n const extractDir = yield* extractIosArtifact({\n tempDir: params.tempDir,\n artifactPath: params.artifactPath,\n format: params.format,\n subdir: \"ios-device\",\n });\n const appDir = yield* findAppBundle(extractDir);\n const bundleId = yield* readBundleIdFromApp(appDir);\n yield* printHuman(`Installing IPA on device ${deviceSelector}...`);\n yield* installAndLaunchIosDevice({\n udid: deviceSelector,\n ipaPath: params.artifactPath,\n bundleId,\n });\n yield* printKeyValue([\n [\"Device\", deviceSelector],\n [\"Bundle ID\", bundleId],\n [\"IPA\", params.artifactPath],\n ]);\n });\n\nconst runIos = (params: IosRunParams) => {\n if (params.format === \"tar.gz\") {\n return runIosSimulator(params);\n }\n if (params.format === \"ipa\") {\n return params.useDevice ? runIosDevice(params) : runIosSimulator(params);\n }\n return Effect.fail(\n new NativeRunError({\n message: `Cannot install ${params.format} on iOS; only tar.gz (simulator) or ipa are supported.`,\n }),\n );\n};\n\ninterface AndroidRunParams {\n readonly artifactPath: string;\n readonly format: ArtifactFormat;\n readonly emulatorSelector: string | undefined;\n readonly packageOverride: string | undefined;\n}\n\nconst runAndroid = (params: AndroidRunParams) =>\n Effect.gen(function* () {\n if (params.format === \"aab\") {\n yield* Effect.fail(\n new InvalidArgumentError({\n message:\n \".aab artifacts cannot be installed directly. Use bundletool to convert to apks, or download the play-store APK.\",\n }),\n );\n return;\n }\n if (params.format !== \"apk\") {\n yield* Effect.fail(\n new NativeRunError({\n message: `Cannot install ${params.format} on Android; only apk is supported.`,\n }),\n );\n return;\n }\n const device = yield* pickAndroidDevice(params.emulatorSelector);\n const detected = yield* readApkPackageName(params.artifactPath);\n const packageName = params.packageOverride ?? detected;\n if (!packageName) {\n yield* Effect.fail(\n new InvalidArgumentError({\n message:\n \"Could not detect APK package name (aapt/aapt2 not on PATH). Pass --package <name> explicitly.\",\n }),\n );\n return;\n }\n yield* printHuman(`Installing on Android device ${device.serial}...`);\n yield* installAndLaunchAndroid({\n serial: device.serial,\n apkPath: params.artifactPath,\n packageName,\n });\n yield* printKeyValue([\n [\"Device\", device.serial],\n [\"Package\", packageName],\n [\"APK\", params.artifactPath],\n ]);\n });\n\nexport const runCommand = defineCommand({\n meta: {\n name: \"run\",\n description: \"Install and launch a build on a simulator/emulator or device\",\n },\n args: {\n id: { type: \"positional\", required: false, description: \"Build ID (or use --latest)\" },\n latest: { type: \"boolean\", description: \"Pick the most recent build for --platform\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\"],\n description: \"Platform filter (required with --latest)\",\n },\n simulator: {\n type: \"string\",\n description: \"iOS simulator name or UDID (iOS simulator/tar.gz builds)\",\n },\n \"device-id\": {\n type: \"string\",\n description: \"Real-device UDID (iOS .ipa via xcrun devicectl)\",\n },\n device: {\n type: \"boolean\",\n description: \"Force real-device install for iOS .ipa (default: simulator if possible)\",\n },\n emulator: {\n type: \"string\",\n description: \"Android adb serial (emulator or device)\",\n },\n package: {\n type: \"string\",\n description: \"Android package name override (used when aapt/aapt2 is unavailable)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.scoped(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const projectId = yield* readProjectId;\n const build = yield* resolveBuild({\n api,\n id: args.id,\n latest: args.latest ?? false,\n platform: args.platform,\n projectId,\n });\n const { artifact } = build;\n if (!artifact) {\n yield* Effect.fail(\n new UploadFailedError({ message: `Build ${build.id} has no artifact yet.` }),\n );\n return;\n }\n const link = yield* api.builds.getInstallLink({ path: { id: build.id } });\n const tempDir = yield* acquireBuildTempDir;\n const artifactPath = path.join(tempDir, `artifact.${artifact.format}`);\n yield* Console.log(\n `Downloading ${artifact.format} artifact (${String(artifact.byteSize)} bytes)...`,\n );\n const bytes = yield* fetchArtifact(link.artifactUrl);\n const fs = yield* FileSystem.FileSystem;\n yield* fs.writeFile(artifactPath, bytes);\n\n if (build.platform === \"ios\") {\n yield* runIos({\n tempDir,\n artifactPath,\n format: artifact.format,\n simulatorSelector: args.simulator,\n deviceSelector: args[\"device-id\"],\n useDevice: args.device ?? false,\n });\n return;\n }\n yield* runAndroid({\n artifactPath,\n format: artifact.format,\n emulatorSelector: args.emulator,\n packageOverride: args.package,\n });\n }),\n ),\n RUN_EXIT_EXTRAS,\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport { reserveAndUpload } from \"../commands/build/reserve-and-upload\";\nimport { readBuildProfile } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { ArtifactNotFoundError, BuildProfileError } from \"../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../lib/expo-config\";\nimport { readGitContext } from \"../lib/git-context\";\nimport { readGradleConfig, warnOnGradleMismatch } from \"../lib/gradle-config\";\nimport { printKeyValue } from \"../lib/output\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { sha256File } from \"../lib/sha256\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nimport type { BuildTarget } from \"../commands/build/reserve-and-upload\";\nimport type { Platform } from \"../lib/build-profile\";\n\nexport interface RunUploadWorkflowOptions {\n readonly platform: Platform;\n readonly profileName: string;\n readonly artifactPath: string;\n readonly message: string | undefined;\n}\n\ninterface ResolvedTarget {\n readonly target: BuildTarget;\n readonly bundleId: string;\n}\n\nconst resolveIosTarget = (\n profile: Effect.Effect.Success<ReturnType<typeof readBuildProfile>>,\n appMeta: Effect.Effect.Success<ReturnType<typeof readAppMeta>>,\n): Effect.Effect<ResolvedTarget, BuildProfileError> =>\n Effect.gen(function* () {\n if (!profile.ios) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no ios section.`,\n });\n }\n if (!appMeta.bundleId) {\n return yield* new BuildProfileError({\n message: \"Missing ios.bundleIdentifier in your Expo config.\",\n });\n }\n return {\n target: {\n platform: \"ios\",\n distribution: profile.ios.distribution,\n artifactFormat: \"ipa\",\n },\n bundleId: appMeta.bundleId,\n };\n });\n\nconst resolveAndroidTarget = (\n profile: Effect.Effect.Success<ReturnType<typeof readBuildProfile>>,\n appMeta: Effect.Effect.Success<ReturnType<typeof readAppMeta>>,\n projectRoot: string,\n) =>\n Effect.gen(function* () {\n if (!profile.android) {\n return yield* new BuildProfileError({\n message: `Profile \"${profile.name}\" has no android section.`,\n });\n }\n if (!appMeta.androidPackage) {\n return yield* new BuildProfileError({\n message: \"Missing android.package in your Expo config.\",\n });\n }\n const gradleConfig = yield* readGradleConfig(`${projectRoot}/android`);\n yield* warnOnGradleMismatch(gradleConfig, appMeta.androidPackage);\n const bundleId = gradleConfig?.applicationId ?? appMeta.androidPackage;\n const target: BuildTarget =\n profile.android.format === \"aab\"\n ? { platform: \"android\", distribution: \"play-store\", artifactFormat: \"aab\" }\n : { platform: \"android\", distribution: \"direct\", artifactFormat: \"apk\" };\n return { target, bundleId };\n });\n\nexport const runUploadWorkflow = (options: RunUploadWorkflowOptions) =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n\n const fs = yield* FileSystem.FileSystem;\n const artifactExists = yield* fs\n .exists(options.artifactPath)\n .pipe(Effect.orElseSucceed(() => false));\n if (!artifactExists) {\n yield* new ArtifactNotFoundError({\n message: `Artifact not found at ${options.artifactPath}.`,\n });\n }\n\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n const profile = yield* readBuildProfile(projectRoot, options.profileName);\n\n const envVars = yield* pullEnvVars(api, {\n projectId,\n environment: profile.environment,\n });\n\n const expoConfig = yield* readExpoConfig(projectRoot, envVars);\n const appMeta = yield* readAppMeta(expoConfig, options.platform);\n\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: appMeta.rawRuntimeVersion,\n appVersion: appMeta.appVersion,\n projectRoot,\n });\n\n const { target, bundleId } =\n options.platform === \"ios\"\n ? yield* resolveIosTarget(profile, appMeta)\n : yield* resolveAndroidTarget(profile, appMeta, projectRoot);\n\n yield* Console.log(`Hashing ${options.artifactPath}...`);\n const { sha256, byteSize } = yield* sha256File(options.artifactPath);\n\n const rawGitContext = yield* readGitContext(projectRoot);\n const gitContext: {\n readonly ref?: string;\n readonly commit?: string;\n readonly dirty: boolean;\n } = {\n ...(rawGitContext.ref === undefined ? {} : { ref: rawGitContext.ref }),\n ...(rawGitContext.commit === undefined ? {} : { commit: rawGitContext.commit }),\n dirty: rawGitContext.dirty,\n };\n\n const result = yield* reserveAndUpload(api, {\n target,\n projectId,\n profileName: profile.name,\n runtimeVersion,\n ...(appMeta.appVersion === undefined ? {} : { appVersion: appMeta.appVersion }),\n ...(appMeta.buildNumber === undefined ? {} : { buildNumber: appMeta.buildNumber }),\n bundleId,\n gitContext,\n ...(options.message === undefined ? {} : { message: options.message }),\n artifactPath: options.artifactPath,\n sha256,\n byteSize,\n });\n\n yield* Console.log(\"\");\n yield* printKeyValue([\n [\"Build ID\", result.id],\n [\"Status\", result.status],\n [\"Platform\", options.platform],\n [\"Profile\", profile.name],\n [\"Runtime version\", runtimeVersion],\n [\"Artifact\", options.artifactPath],\n [\"SHA-256\", sha256],\n [\"Bytes\", String(byteSize)],\n ]);\n });\n","import { defineCommand } from \"citty\";\n\nimport { runUploadWorkflow } from \"../../application/upload-workflow\";\nimport { runEffect } from \"../../lib/citty-effect\";\n\nconst UPLOAD_EXIT_EXTRAS = {\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n ArtifactNotFoundError: 6,\n BuildFailedError: 6,\n ReserveError: 7,\n UploadFailedError: 7,\n PresignedUrlExpiredError: 7,\n CompleteError: 7,\n EnvExportError: 7,\n} as const;\n\nexport const uploadCommand = defineCommand({\n meta: { name: \"upload\", description: \"Upload an existing artifact to better-update\" },\n args: {\n \"artifact-path\": { type: \"positional\", required: true, description: \"Path to artifact\" },\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n profile: { type: \"string\", default: \"production\", description: \"Build profile name\" },\n message: { type: \"string\", description: \"Optional build message\" },\n },\n run: async ({ args }) =>\n runEffect(\n runUploadWorkflow({\n artifactPath: args[\"artifact-path\"],\n platform: args.platform,\n profileName: args.profile,\n message: args.message,\n }),\n UPLOAD_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { compatibilityMatrixCommand } from \"./compatibility-matrix\";\nimport { deleteCommand } from \"./delete\";\nimport { downloadCommand } from \"./download\";\nimport { getCommand } from \"./get\";\nimport { installLinkCommand } from \"./install-link\";\nimport { listCommand } from \"./list\";\nimport { resignCommand } from \"./resign\";\nimport { runCommand } from \"./run\";\nimport { uploadCommand } from \"./upload\";\n\nexport const buildsCommand = defineCommand({\n meta: { name: \"builds\", description: \"Manage builds\" },\n subCommands: {\n list: listCommand,\n get: getCommand,\n delete: deleteCommand,\n download: downloadCommand,\n run: runCommand,\n \"install-link\": installLinkCommand,\n \"compatibility-matrix\": compatibilityMatrixCommand,\n upload: uploadCommand,\n resign: resignCommand,\n },\n});\n","import { Effect } from \"effect\";\n\ninterface NamedResource {\n readonly id: string;\n readonly name: string;\n}\n\nexport const resolveNamedResourceId = <Err>(\n params: {\n readonly items: readonly NamedResource[];\n readonly kind: string;\n readonly name: string;\n },\n makeError: (message: string) => Err,\n): Effect.Effect<string, Err> =>\n Effect.gen(function* () {\n const match = params.items.find((item) => item.name === params.name);\n if (match === undefined) {\n return yield* Effect.fail(\n makeError(`${params.kind} \"${params.name}\" not found in the linked project.`),\n );\n }\n return match.id;\n });\n","import { Data } from \"effect\";\n\nimport { resolveNamedResourceId as resolveNamedResourceIdBase } from \"../../lib/resolve-named-resource\";\n\nexport class ChannelCommandError extends Data.TaggedError(\"ChannelCommandError\")<{\n readonly message: string;\n}> {}\n\nexport const channelErrorExtras = { ChannelCommandError: 2 } as const;\n\nexport const resolveNamedResourceId = (params: {\n readonly items: readonly { readonly id: string; readonly name: string }[];\n readonly kind: string;\n readonly name: string;\n}) => resolveNamedResourceIdBase(params, (message) => new ChannelCommandError({ message }));\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras, resolveNamedResourceId } from \"./helpers\";\n\nexport const createCommand = defineCommand({\n meta: { name: \"create\", description: \"Create a channel\" },\n args: {\n name: { type: \"string\", required: true, description: \"Channel name\" },\n branch: { type: \"string\", required: true, description: \"Initial branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const branchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n });\n\n const channel = yield* api.channels.create({\n payload: { projectId, name: args.name, branchId },\n });\n\n yield* printKeyValue([\n [\"ID\", channel.id],\n [\"Name\", channel.name],\n [\"Branch\", args.branch],\n [\"Created\", channel.createdAt],\n ]);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a channel\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.channels.delete({ path: { id: args.id } });\n yield* Console.log(`Channel ${args.id} deleted.`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const insightsCommand = defineCommand({\n meta: { name: \"insights\", description: \"Show adoption + traffic stats for a channel\" },\n args: {\n name: { type: \"positional\", required: true, description: \"Channel name\" },\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const periodFilter = args.period ? { period: args.period } : {};\n const result = yield* api.analytics.channels({\n urlParams: { projectId, channel: args.name, ...periodFilter },\n });\n\n yield* printKeyValue([\n [\"Channel\", result.channel],\n [\"Total Requests\", String(result.totalRequests)],\n [\"Unique Devices\", String(result.uniqueDevices)],\n [\"Manifest\", String(result.responseTypeDistribution.manifest)],\n [\"Directive\", String(result.responseTypeDistribution.directive)],\n [\"No Update\", String(result.responseTypeDistribution.no_update)],\n ]);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List channels for the linked project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const [items, branches] = yield* Effect.all([\n drainPages((page) =>\n api.channels.list({\n urlParams: { projectId, limit: 100, page },\n }),\n ),\n drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n ),\n ]);\n\n const branchNames = new Map(branches.map((branch) => [branch.id, branch.name]));\n\n yield* printList(\n [\"ID\", \"Name\", \"Branch\", \"Paused\", \"Rollout\", \"Created\"],\n items.map((channel) => [\n channel.id,\n channel.name,\n branchNames.get(channel.branchId) ?? channel.branchId,\n channel.isPaused ? \"yes\" : \"no\",\n channel.branchMappingJson === null ? \"-\" : \"active\",\n channel.createdAt,\n ]),\n \"No channels found.\",\n );\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const pauseCommand = defineCommand({\n meta: { name: \"pause\", description: \"Pause a channel\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.pause({ path: { id: args.id } });\n yield* Console.log(`Channel \"${channel.name}\" paused.`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras } from \"./helpers\";\n\nexport const resumeCommand = defineCommand({\n meta: { name: \"resume\", description: \"Resume a paused channel\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.resume({ path: { id: args.id } });\n yield* Console.log(`Channel \"${channel.name}\" resumed.`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras } from \"../helpers\";\n\nexport const completeCommand = defineCommand({\n meta: { name: \"complete\", description: \"Complete the active branch rollout\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.completeBranchRollout({\n path: { id: args.channelId },\n });\n yield* Console.log(`Completed rollout on channel \"${channel.name}\".`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../../lib/cli-schemas\";\nimport { drainPages } from \"../../../lib/drain-cursor\";\nimport { readProjectId } from \"../../../lib/expo-config\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras, resolveNamedResourceId } from \"../helpers\";\n\nexport const createCommand = defineCommand({\n meta: { name: \"create\", description: \"Start a branch rollout on a channel\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n branch: { type: \"string\", required: true, description: \"Target branch name\" },\n percentage: {\n type: \"string\",\n required: true,\n description: \"Initial rollout percentage (1-100)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const percentage = yield* parseRolloutPercentage(args.percentage, \"percentage\");\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const newBranchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n });\n\n const channel = yield* api.channels.createBranchRollout({\n path: { id: args.channelId },\n payload: { newBranchId, percentage },\n });\n\n yield* Console.log(\n `Started rollout on channel \"${channel.name}\" to branch \"${args.branch}\" at ${String(percentage)}%.`,\n );\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras } from \"../helpers\";\n\nexport const revertCommand = defineCommand({\n meta: { name: \"revert\", description: \"Revert the active branch rollout\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const channel = yield* api.channels.revertBranchRollout({\n path: { id: args.channelId },\n });\n yield* Console.log(`Reverted rollout on channel \"${channel.name}\".`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../../lib/cli-schemas\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { channelErrorExtras } from \"../helpers\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Update the rollout percentage on a channel\" },\n args: {\n channelId: { type: \"positional\", required: true, description: \"Channel ID\" },\n percentage: { type: \"string\", required: true, description: \"New rollout percentage (1-100)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const percentage = yield* parseRolloutPercentage(args.percentage, \"percentage\");\n const api = yield* apiClient;\n const channel = yield* api.channels.updateBranchRollout({\n path: { id: args.channelId },\n payload: { percentage },\n });\n\n yield* Console.log(\n `Updated rollout on channel \"${channel.name}\" to ${String(percentage)}%.`,\n );\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { completeCommand } from \"./complete\";\nimport { createCommand } from \"./create\";\nimport { revertCommand } from \"./revert\";\nimport { updateCommand } from \"./update\";\n\nexport const rolloutCommand = defineCommand({\n meta: { name: \"rollout\", description: \"Manage channel branch rollouts\" },\n subCommands: {\n create: createCommand,\n update: updateCommand,\n complete: completeCommand,\n revert: revertCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { channelErrorExtras, resolveNamedResourceId } from \"./helpers\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Relink a channel to a different branch\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Channel ID\" },\n branch: { type: \"string\", required: true, description: \"Target branch name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const branches = yield* drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n );\n const branchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n });\n\n const channel = yield* api.channels.update({\n path: { id: args.id },\n payload: { branchId },\n });\n\n yield* Console.log(`Channel \"${channel.name}\" relinked to branch \"${args.branch}\".`);\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\nimport { ChannelCommandError, channelErrorExtras } from \"./helpers\";\n\nexport const viewCommand = defineCommand({\n meta: { name: \"view\", description: \"Show a channel by ID or name\" },\n args: {\n target: {\n type: \"positional\",\n required: true,\n description: \"Channel ID or channel name\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const [channels, branches] = yield* Effect.all([\n drainPages((page) =>\n api.channels.list({\n urlParams: { projectId, limit: 100, page },\n }),\n ),\n drainPages((page) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page },\n }),\n ),\n ]);\n\n const channel =\n channels.find((entry) => entry.id === args.target) ??\n channels.find((entry) => entry.name === args.target);\n\n if (!channel) {\n return yield* Effect.fail(\n new ChannelCommandError({\n message: `Channel \"${args.target}\" not found by ID or name.`,\n }),\n );\n }\n\n const branchNames = new Map(branches.map((branch) => [branch.id, branch.name]));\n const branchName = branchNames.get(channel.branchId) ?? channel.branchId;\n\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson({\n id: channel.id,\n projectId: channel.projectId,\n name: channel.name,\n branchId: channel.branchId,\n branchName,\n branchMappingJson: channel.branchMappingJson,\n cacheVersion: channel.cacheVersion,\n isPaused: channel.isPaused,\n createdAt: channel.createdAt,\n });\n return undefined;\n }\n\n yield* printKeyValue([\n [\"ID\", channel.id],\n [\"Name\", channel.name],\n [\"Project ID\", channel.projectId],\n [\"Branch\", `${branchName} (${channel.branchId})`],\n [\"Paused\", channel.isPaused ? \"yes\" : \"no\"],\n [\"Rollout\", channel.branchMappingJson ?? \"-\"],\n [\"Cache version\", String(channel.cacheVersion)],\n [\"Created\", channel.createdAt],\n ]);\n return undefined;\n }),\n channelErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { insightsCommand } from \"./insights\";\nimport { listCommand } from \"./list\";\nimport { pauseCommand } from \"./pause\";\nimport { resumeCommand } from \"./resume\";\nimport { rolloutCommand } from \"./rollout\";\nimport { updateCommand } from \"./update\";\nimport { viewCommand } from \"./view\";\n\nexport const channelsCommand = defineCommand({\n meta: { name: \"channels\", description: \"Manage channels\" },\n subCommands: {\n list: listCommand,\n view: viewCommand,\n create: createCommand,\n update: updateCommand,\n pause: pauseCommand,\n resume: resumeCommand,\n delete: deleteCommand,\n rollout: rolloutCommand,\n insights: insightsCommand,\n },\n});\n","/* eslint-disable typescript/no-unsafe-assignment, typescript/no-unsafe-member-access, typescript/no-unsafe-type-assertion -- @expo/pkcs12 exports declare node-forge cert shapes as `any`; this file is the narrowing boundary that produces the typed P12Info for the rest of the CLI */\n\nimport { getFormattedSerialNumber, getX509Certificate, parsePKCS12 } from \"@expo/pkcs12\";\nimport { Effect } from \"effect\";\n\nimport { CredentialValidationError } from \"./exit-codes\";\n\nexport interface P12Info {\n readonly serialNumber: string;\n readonly validFrom: Date | undefined;\n readonly expiresAt: Date | undefined;\n readonly subject: string;\n readonly issuerCN: string | undefined;\n readonly signingIdentity: string;\n readonly teamId: string | undefined;\n}\n\nconst APPLE_TEAM_ID_RE = /^[A-Z0-9]{10}$/u;\n\nconst extractTeamId = (params: {\n readonly signingIdentity: string;\n readonly orgUnit: string | undefined;\n}): string | undefined => {\n if (params.orgUnit && APPLE_TEAM_ID_RE.test(params.orgUnit)) {\n return params.orgUnit;\n }\n const parenMatch = /\\(([A-Z0-9]{10})\\)\\s*$/u.exec(params.signingIdentity);\n return parenMatch?.[1];\n};\n\n/**\n * Parse a PKCS#12 (.p12) buffer and extract certificate metadata.\n */\nexport const inspectP12 = (params: {\n readonly data: Buffer;\n readonly password: string;\n}): Effect.Effect<P12Info, CredentialValidationError> =>\n Effect.try({\n try: () => {\n const p12 = parsePKCS12(params.data, params.password);\n const cert = getX509Certificate(p12);\n\n const serialNumber = getFormattedSerialNumber(cert) ?? \"unknown\";\n\n const validFrom =\n cert.validity.notBefore instanceof Date ? cert.validity.notBefore : undefined;\n const expiresAt = cert.validity.notAfter instanceof Date ? cert.validity.notAfter : undefined;\n\n const attrs = cert.subject.attributes as readonly {\n shortName?: string | undefined;\n name?: string | undefined;\n value: unknown;\n }[];\n const subjectParts: string[] = attrs.map((attr) => {\n const label = attr.shortName ?? attr.name;\n if (label === undefined) {\n return `(unknown)=${String(attr.value)}`;\n }\n return `${label}=${String(attr.value)}`;\n });\n const subject = subjectParts.join(\", \");\n\n const issuerCNValue = cert.issuer.getField(\"CN\")?.value;\n const issuerCN = typeof issuerCNValue === \"string\" ? issuerCNValue : undefined;\n\n // Signing identity = Common Name from subject, e.g. \"Apple Distribution: Name (TEAMID)\"\n const cnValue = cert.subject.getField(\"CN\")?.value;\n const cn = typeof cnValue === \"string\" ? cnValue : undefined;\n const signingIdentity = cn ?? subject;\n const orgUnitValue = cert.subject.getField(\"OU\")?.value;\n const orgUnit = typeof orgUnitValue === \"string\" ? orgUnitValue : undefined;\n\n const teamId = extractTeamId({ signingIdentity, orgUnit });\n\n return { serialNumber, validFrom, expiresAt, subject, issuerCN, signingIdentity, teamId };\n },\n catch: (error) =>\n new CredentialValidationError({\n message: `Failed to parse P12 certificate: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n","import { toBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Match } from \"effect\";\n\nimport { CredentialValidationError } from \"./exit-codes\";\nimport { inspectP12 } from \"./pkcs12\";\n\nimport type { ApiClient } from \"../services/api-client\";\n\nexport type CliCredentialType =\n | \"distribution-certificate\"\n | \"push-key\"\n | \"asc-api-key\"\n | \"provisioning-profile\"\n | \"keystore\"\n | \"google-service-account-key\";\n\nexport type CliCredentialPlatform = \"ios\" | \"android\";\n\nexport interface CliCredentialRow {\n readonly id: string;\n readonly name: string;\n readonly platform: CliCredentialPlatform;\n readonly type: CliCredentialType;\n readonly distribution: string | null;\n}\n\nconst formatDistribution = (value: string): string => value.toLowerCase().replaceAll(\"_\", \"-\");\n\nexport const listAllCredentials = (api: ApiClient) =>\n Effect.gen(function* () {\n const [certs, pushKeys, ascKeys, profiles, keystores, googleKeys] = yield* Effect.all(\n [\n api.appleDistributionCertificates.list(),\n api.applePushKeys.list(),\n api.ascApiKeys.list(),\n api.appleProvisioningProfiles.list({ urlParams: {} }),\n api.androidUploadKeystores.list(),\n api.googleServiceAccountKeys.list(),\n ],\n { concurrency: \"unbounded\" },\n );\n\n const rows: CliCredentialRow[] = [\n ...certs.items.map(\n (cert): CliCredentialRow => ({\n id: cert.id,\n name: cert.serialNumber,\n platform: \"ios\",\n type: \"distribution-certificate\",\n distribution: null,\n }),\n ),\n ...pushKeys.items.map(\n (key): CliCredentialRow => ({\n id: key.id,\n name: key.keyId,\n platform: \"ios\",\n type: \"push-key\",\n distribution: null,\n }),\n ),\n ...ascKeys.items.map(\n (key): CliCredentialRow => ({\n id: key.id,\n name: key.name,\n platform: \"ios\",\n type: \"asc-api-key\",\n distribution: null,\n }),\n ),\n ...profiles.items.map(\n (profile): CliCredentialRow => ({\n id: profile.id,\n name: profile.profileName ?? profile.bundleIdentifier,\n platform: \"ios\",\n type: \"provisioning-profile\",\n distribution: formatDistribution(profile.distributionType),\n }),\n ),\n ...keystores.items.map(\n (ks): CliCredentialRow => ({\n id: ks.id,\n name: ks.keyAlias,\n platform: \"android\",\n type: \"keystore\",\n distribution: null,\n }),\n ),\n ...googleKeys.items.map(\n (key): CliCredentialRow => ({\n id: key.id,\n name: key.clientEmail,\n platform: \"android\",\n type: \"google-service-account-key\",\n distribution: null,\n }),\n ),\n ];\n\n return rows;\n });\n\nexport const filterCredentials = (\n rows: readonly CliCredentialRow[],\n filter: {\n readonly platform?: CliCredentialPlatform;\n readonly type?: CliCredentialType;\n readonly distribution?: string;\n },\n): CliCredentialRow[] =>\n rows.filter((row) => {\n if (filter.platform && row.platform !== filter.platform) {\n return false;\n }\n if (filter.type && row.type !== filter.type) {\n return false;\n }\n if (filter.distribution && row.distribution !== filter.distribution) {\n return false;\n }\n return true;\n });\n\nexport interface UploadCredentialInput {\n readonly platform: CliCredentialPlatform;\n readonly type: CliCredentialType;\n readonly name: string;\n readonly filePath: string;\n readonly password?: string;\n readonly distribution?: string;\n readonly keyAlias?: string;\n readonly keyPassword?: string;\n readonly keyId?: string;\n readonly issuerId?: string;\n readonly appleTeamIdentifier?: string;\n}\n\nconst toUtf8 = (bytes: Uint8Array): string => new TextDecoder().decode(bytes);\n\nconst missing = (label: string) =>\n new CredentialValidationError({\n message: `Missing --${label} required for the selected credential type.`,\n });\n\nconst uploadIosDistributionCertificate = (\n api: ApiClient,\n input: UploadCredentialInput,\n bytes: Uint8Array,\n) =>\n Effect.gen(function* () {\n if (input.password === undefined) {\n return yield* missing(\"password\");\n }\n const info = yield* inspectP12({ data: Buffer.from(bytes), password: input.password });\n if (!info.teamId) {\n return yield* new CredentialValidationError({\n message:\n \"Could not derive Apple Team ID from certificate subject (expected OU=TEAMID or CN with (TEAMID)).\",\n });\n }\n if (!info.validFrom || !info.expiresAt) {\n return yield* new CredentialValidationError({\n message: \"Certificate is missing notBefore/notAfter dates.\",\n });\n }\n const created = yield* api.appleDistributionCertificates.upload({\n payload: {\n p12Base64: toBase64(bytes),\n p12Password: input.password,\n serialNumber: info.serialNumber,\n appleTeamIdentifier: info.teamId,\n validFrom: info.validFrom.toISOString(),\n validUntil: info.expiresAt.toISOString(),\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"distribution-certificate\" as const,\n };\n });\n\nconst uploadIosPushKey = (api: ApiClient, input: UploadCredentialInput, bytes: Uint8Array) =>\n Effect.gen(function* () {\n if (!input.keyId) {\n return yield* missing(\"key-id\");\n }\n if (!input.appleTeamIdentifier) {\n return yield* missing(\"apple-team-identifier\");\n }\n const created = yield* api.applePushKeys.upload({\n payload: {\n keyId: input.keyId,\n p8Pem: toUtf8(bytes),\n appleTeamIdentifier: input.appleTeamIdentifier,\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"push-key\" as const,\n };\n });\n\nconst uploadIosAscApiKey = (api: ApiClient, input: UploadCredentialInput, bytes: Uint8Array) =>\n Effect.gen(function* () {\n if (!input.keyId) {\n return yield* missing(\"key-id\");\n }\n if (!input.issuerId) {\n return yield* missing(\"issuer-id\");\n }\n const created = yield* api.ascApiKeys.upload({\n payload: {\n name: input.name,\n keyId: input.keyId,\n issuerId: input.issuerId,\n p8Pem: toUtf8(bytes),\n ...(input.appleTeamIdentifier === undefined\n ? {}\n : { appleTeamIdentifier: input.appleTeamIdentifier }),\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"asc-api-key\" as const,\n };\n });\n\nconst uploadIosProvisioningProfile = (\n api: ApiClient,\n input: UploadCredentialInput,\n bytes: Uint8Array,\n) =>\n Effect.gen(function* () {\n const created = yield* api.appleProvisioningProfiles.upload({\n payload: { profileBase64: toBase64(bytes) },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"ios\" as const,\n type: \"provisioning-profile\" as const,\n };\n });\n\nconst uploadAndroidKeystore = (api: ApiClient, input: UploadCredentialInput, bytes: Uint8Array) =>\n Effect.gen(function* () {\n if (input.password === undefined) {\n return yield* missing(\"password\");\n }\n if (!input.keyAlias) {\n return yield* missing(\"key-alias\");\n }\n if (!input.keyPassword) {\n return yield* missing(\"key-password\");\n }\n const created = yield* api.androidUploadKeystores.upload({\n payload: {\n keystoreBase64: toBase64(bytes),\n keyAlias: input.keyAlias,\n keystorePassword: input.password,\n keyPassword: input.keyPassword,\n },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"android\" as const,\n type: \"keystore\" as const,\n };\n });\n\nconst uploadAndroidGoogleServiceAccountKey = (\n api: ApiClient,\n input: UploadCredentialInput,\n bytes: Uint8Array,\n) =>\n Effect.gen(function* () {\n const created = yield* api.googleServiceAccountKeys.upload({\n payload: { json: toUtf8(bytes) },\n });\n return {\n id: created.id,\n name: input.name,\n platform: \"android\" as const,\n type: \"google-service-account-key\" as const,\n };\n });\n\nconst uploadHandlers = {\n \"ios:distribution-certificate\": uploadIosDistributionCertificate,\n \"ios:push-key\": uploadIosPushKey,\n \"ios:asc-api-key\": uploadIosAscApiKey,\n \"ios:provisioning-profile\": uploadIosProvisioningProfile,\n \"android:keystore\": uploadAndroidKeystore,\n \"android:google-service-account-key\": uploadAndroidGoogleServiceAccountKey,\n};\n\nexport const uploadCredential = (api: ApiClient, input: UploadCredentialInput) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const bytes = yield* fs.readFile(input.filePath);\n const key = `${input.platform}:${input.type}`;\n type HandlerKey = keyof typeof uploadHandlers;\n const hasKey = (candidate: string): candidate is HandlerKey =>\n Object.hasOwn(uploadHandlers, candidate);\n const handler = hasKey(key) ? uploadHandlers[key] : undefined;\n if (!handler) {\n return yield* new CredentialValidationError({\n message: `Unsupported credential combination: platform=${input.platform} type=${input.type}`,\n });\n }\n return yield* handler(api, input, bytes);\n });\n\nexport const deleteCredential = (\n api: ApiClient,\n input: {\n readonly id: string;\n readonly platform: CliCredentialPlatform;\n readonly type: CliCredentialType;\n },\n) => {\n const path = { id: input.id };\n return Match.value({ platform: input.platform, type: input.type }).pipe(\n Match.when({ platform: \"ios\", type: \"distribution-certificate\" }, () =>\n api.appleDistributionCertificates.delete({ path }),\n ),\n Match.when({ platform: \"ios\", type: \"push-key\" }, () => api.applePushKeys.delete({ path })),\n Match.when({ platform: \"ios\", type: \"asc-api-key\" }, () => api.ascApiKeys.delete({ path })),\n Match.when({ platform: \"ios\", type: \"provisioning-profile\" }, () =>\n api.appleProvisioningProfiles.delete({ path }),\n ),\n Match.when({ platform: \"android\", type: \"keystore\" }, () =>\n api.androidUploadKeystores.delete({ path }),\n ),\n Match.when({ platform: \"android\", type: \"google-service-account-key\" }, () =>\n api.googleServiceAccountKeys.delete({ path }),\n ),\n Match.orElse(() =>\n Effect.fail(\n new CredentialValidationError({\n message: `Unsupported credential combination: platform=${input.platform} type=${input.type}`,\n }),\n ),\n ),\n );\n};\n","import { Console, Effect } from \"effect\";\n\nimport type { CommandExecutor, FileSystem } from \"@effect/platform\";\n\nimport { IOS_DISTRIBUTION_TO_TYPE } from \"../lib/credentials-downloader\";\nimport {\n deleteCredential,\n filterCredentials,\n listAllCredentials,\n} from \"../lib/credentials-manager\";\nimport { MissingCredentialsError } from \"../lib/exit-codes\";\nimport { promptConfirm, promptSelect } from \"../lib/prompts\";\n\nimport type { IosDistribution } from \"../lib/build-profile\";\nimport type { CliCredentialRow } from \"../lib/credentials-manager\";\nimport type { InteractiveMode } from \"../lib/interactive-mode\";\nimport type { OutputMode } from \"../lib/output-mode\";\nimport type { ApiClient } from \"../services/api-client\";\n\nexport const APPLE_PUSH_KEY_PORTAL_URL =\n \"https://developer.apple.com/account/resources/authkeys/list\";\n\nexport const DISTRIBUTION_OPTIONS: readonly {\n readonly value: IosDistribution;\n readonly label: string;\n}[] = [\n { value: \"ad-hoc\", label: \"Ad Hoc (internal testers)\" },\n { value: \"app-store\", label: \"App Store\" },\n { value: \"development\", label: \"Development\" },\n { value: \"enterprise\", label: \"Enterprise\" },\n];\n\nexport interface WizardContext {\n readonly api: ApiClient;\n readonly projectId: string;\n readonly iosBundleId: string | undefined;\n readonly androidPackage: string | undefined;\n}\n\nexport const BACK = \"__back__\" as const;\nexport const EXIT = \"__exit__\" as const;\n\nexport type MenuEffect = Effect.Effect<\n void,\n never,\n InteractiveMode | OutputMode | FileSystem.FileSystem | CommandExecutor.CommandExecutor\n>;\n\nexport const announce = (heading: string) =>\n Effect.gen(function* () {\n yield* Console.log(\"\");\n yield* Console.log(`── ${heading} ──`);\n });\n\nexport const reportError = (label: string, cause: unknown) =>\n Console.log(`✗ ${label}: ${cause instanceof Error ? cause.message : String(cause)}`);\n\nexport const safely = <Value, Err, Req>(\n label: string,\n effect: Effect.Effect<Value, Err, Req>,\n): Effect.Effect<void, never, Req> =>\n effect.pipe(\n Effect.catchAll((cause) => reportError(label, cause)),\n Effect.asVoid,\n );\n\nexport const safePrompt = (effect: Effect.Effect<string, unknown, InteractiveMode>) =>\n effect.pipe(Effect.catchAll(() => Effect.succeed(BACK as string)));\n\nexport const promptForBundleConfig = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const list = yield* ctx.api.iosBundleConfigurations.list({\n path: { projectId: ctx.projectId },\n });\n if (list.items.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No iOS bundle configurations registered yet.\",\n hint: \"Run 'Set up project credentials' first to create one.\",\n });\n }\n if (list.items.length === 1) {\n const [only] = list.items;\n if (only !== undefined) {\n return only;\n }\n }\n const choice = yield* promptSelect<string>(\n \"Select an iOS bundle configuration\",\n list.items.map((item) => ({\n value: item.id,\n label: `${item.bundleIdentifier} (${item.distributionType})`,\n })),\n );\n const found = list.items.find((item) => item.id === choice);\n if (!found) {\n return yield* new MissingCredentialsError({\n message: \"Selected bundle configuration not found.\",\n hint: \"Retry.\",\n });\n }\n return found;\n });\n\nconst IOS_DISTRIBUTION_VALUES = [\"ad-hoc\", \"app-store\", \"development\", \"enterprise\"] as const;\n\nconst isIosDistribution = (value: string): value is IosDistribution =>\n (IOS_DISTRIBUTION_VALUES as readonly string[]).includes(value);\n\nexport const matchDistribution = (raw: string): IosDistribution => {\n for (const [key, value] of Object.entries(IOS_DISTRIBUTION_TO_TYPE)) {\n if (value === raw && isIosDistribution(key)) {\n return key;\n }\n }\n return \"app-store\";\n};\n\nconst TYPE_LABELS: Record<string, string> = {\n \"distribution-certificate\": \"iOS distribution certificate\",\n \"provisioning-profile\": \"iOS provisioning profile\",\n \"push-key\": \"APNs push key\",\n \"asc-api-key\": \"ASC API key\",\n keystore: \"Android keystore\",\n \"google-service-account-key\": \"Google service account key\",\n};\n\nconst formatRowLabel = (row: CliCredentialRow): string => `${row.name} (${row.id.slice(0, 8)}…)`;\n\nexport type DeletableType =\n | \"distribution-certificate\"\n | \"provisioning-profile\"\n | \"push-key\"\n | \"asc-api-key\"\n | \"keystore\"\n | \"google-service-account-key\";\n\nexport const pickAndDelete = (ctx: WizardContext, type: DeletableType, humanLabel: string) =>\n Effect.gen(function* () {\n const rows = yield* listAllCredentials(ctx.api);\n const matches = filterCredentials(rows, { type });\n if (matches.length === 0) {\n return yield* Console.log(`No ${humanLabel} entries found.`);\n }\n const id = yield* promptSelect<string>(\n `Select a ${humanLabel} to delete`,\n matches.map((row) => ({ value: row.id, label: formatRowLabel(row) })),\n );\n const chosen = matches.find((row) => row.id === id);\n if (!chosen) {\n return yield* Console.log(\"Selection lost — try again.\");\n }\n const confirmed = yield* promptConfirm(\n `Delete ${TYPE_LABELS[type] ?? type} ${id.slice(0, 8)}…? This cannot be undone.`,\n { initialValue: false },\n );\n if (!confirmed) {\n return yield* Console.log(\"Aborted.\");\n }\n yield* deleteCredential(ctx.api, { id, platform: chosen.platform, type });\n return yield* Console.log(`Deleted ${humanLabel} ${id}.`);\n });\n","import { Console, Effect } from \"effect\";\n\nimport { IOS_DISTRIBUTION_TO_TYPE } from \"../lib/credentials-downloader\";\nimport { MissingCredentialsError } from \"../lib/exit-codes\";\nimport { printKeyValue } from \"../lib/output\";\nimport { promptSelect } from \"../lib/prompts\";\nimport {\n pickIosAscKey,\n pickIosCertificate,\n resolveAndroidKeystoreId,\n resolveIosProfileId,\n} from \"./credentials-interactive\";\n\nimport type { ApiClient } from \"../services/api-client\";\nimport type { AndroidSetupInput, IosSetupContext, IosSetupInput } from \"./credentials-interactive\";\n\n// ── Android ────────────────────────────────────────────────────────\n\nconst findAndroidGroup = (api: ApiClient, input: AndroidSetupInput) =>\n Effect.gen(function* () {\n const apps = yield* api.androidApplicationIdentifiers.list({\n path: { projectId: input.projectId },\n });\n const app = apps.items.find((entry) => entry.packageName === input.applicationIdentifier);\n if (app === undefined) {\n return { app: undefined, group: undefined } as const;\n }\n const groups = yield* api.androidBuildCredentials.list({\n path: { applicationIdentifierId: app.id },\n });\n const group = groups.items.find((entry) => entry.isDefault) ?? groups.items.at(0);\n return { app, group } as const;\n });\n\nconst resolveKeystoreLabel = (api: ApiClient, keystoreId: string | null) =>\n Effect.gen(function* () {\n if (keystoreId === null) {\n return \"-\";\n }\n const keystores = yield* api.androidUploadKeystores.list();\n const match = keystores.items.find((entry) => entry.id === keystoreId);\n return match === undefined ? keystoreId : `${match.keyAlias} (${match.id.slice(0, 8)}…)`;\n });\n\nexport const showAndroidBinding = (api: ApiClient, input: AndroidSetupInput) =>\n Effect.gen(function* () {\n const { group } = yield* findAndroidGroup(api, input);\n if (group === undefined) {\n yield* Console.log(\n `No Android build credentials registered for ${input.applicationIdentifier}.`,\n );\n return;\n }\n const keystoreLabel = yield* resolveKeystoreLabel(api, group.androidUploadKeystoreId);\n yield* printKeyValue([\n [\"Application\", input.applicationIdentifier],\n [\"Group\", group.name],\n [\"Group ID\", group.id],\n [\"Default\", group.isDefault ? \"yes\" : \"no\"],\n [\"Keystore\", keystoreLabel],\n ]);\n });\n\nexport const rebindAndroidKeystore = (api: ApiClient, input: AndroidSetupInput) =>\n Effect.gen(function* () {\n const { group } = yield* findAndroidGroup(api, input);\n if (group === undefined) {\n return yield* new MissingCredentialsError({\n message: `No Android build credentials group to rebind for ${input.applicationIdentifier}.`,\n hint: \"Run `better-update credentials configure --platform android` (without --rebind) first.\",\n });\n }\n\n yield* Console.log(\n `Rebinding default Android build credentials for ${input.applicationIdentifier}.`,\n );\n\n const choice = yield* promptSelect<\"generate\" | \"existing\">(\"Pick a keystore to bind:\", [\n { value: \"existing\", label: \"Pick an existing keystore\" },\n { value: \"generate\", label: \"Generate a new keystore\" },\n ]);\n const keystoreId = yield* resolveAndroidKeystoreId(api, choice);\n\n yield* api.androidBuildCredentials.update({\n path: { id: group.id },\n payload: { androidUploadKeystoreId: keystoreId },\n });\n yield* Console.log(\"Default Android keystore rebind complete.\");\n return undefined;\n });\n\n// ── iOS ────────────────────────────────────────────────────────────\n\nconst fetchIosBinding = (api: ApiClient, input: IosSetupInput) =>\n Effect.gen(function* () {\n const distributionType = IOS_DISTRIBUTION_TO_TYPE[input.distribution];\n const configs = yield* api.iosBundleConfigurations.list({\n path: { projectId: input.projectId },\n });\n return configs.items.find(\n (entry) =>\n entry.bundleIdentifier === input.bundleIdentifier &&\n entry.distributionType === distributionType,\n );\n });\n\nconst labelDistributionCertificate = (api: ApiClient, id: string | null) =>\n Effect.gen(function* () {\n if (id === null) {\n return \"-\";\n }\n const certs = yield* api.appleDistributionCertificates.list();\n const match = certs.items.find((entry) => entry.id === id);\n return match === undefined\n ? id\n : `${match.serialNumber.slice(0, 12)}… (team ${match.appleTeamId})`;\n });\n\nconst labelProvisioningProfile = (api: ApiClient, id: string | null) =>\n Effect.gen(function* () {\n if (id === null) {\n return \"-\";\n }\n const profiles = yield* api.appleProvisioningProfiles.list({ urlParams: {} });\n const match = profiles.items.find((entry) => entry.id === id);\n if (match === undefined) {\n return id;\n }\n return match.profileName ?? match.developerPortalIdentifier ?? id;\n });\n\nconst labelAscApiKey = (api: ApiClient, id: string | null) =>\n Effect.gen(function* () {\n if (id === null) {\n return \"-\";\n }\n const keys = yield* api.ascApiKeys.list();\n const match = keys.items.find((entry) => entry.id === id);\n return match === undefined ? id : `${match.name} (${match.keyId})`;\n });\n\nconst labelPushKey = (api: ApiClient, id: string | null) =>\n Effect.gen(function* () {\n if (id === null) {\n return \"-\";\n }\n const keys = yield* api.applePushKeys.list();\n const match = keys.items.find((entry) => entry.id === id);\n return match === undefined ? id : match.keyId;\n });\n\nexport const showIosBinding = (api: ApiClient, input: IosSetupInput) =>\n Effect.gen(function* () {\n const config = yield* fetchIosBinding(api, input);\n if (config === undefined) {\n yield* Console.log(\n `No iOS bundle configuration for ${input.bundleIdentifier} (${input.distribution}).`,\n );\n return;\n }\n const [certLabel, profileLabel, ascLabel, pushLabel] = yield* Effect.all(\n [\n labelDistributionCertificate(api, config.appleDistributionCertificateId),\n labelProvisioningProfile(api, config.appleProvisioningProfileId),\n labelAscApiKey(api, config.ascApiKeyId),\n labelPushKey(api, config.applePushKeyId),\n ],\n { concurrency: \"unbounded\" },\n );\n yield* printKeyValue([\n [\"Bundle\", config.bundleIdentifier],\n [\"Distribution\", config.distributionType],\n [\"Apple team\", config.appleTeamId],\n [\"Bundle config ID\", config.id],\n [\"Distribution cert\", certLabel],\n [\"Provisioning profile\", profileLabel],\n [\"ASC API key\", ascLabel],\n [\"APNs push key\", pushLabel],\n ]);\n });\n\nexport const rebindIosBundle = (api: ApiClient, input: IosSetupInput) =>\n Effect.gen(function* () {\n const config = yield* fetchIosBinding(api, input);\n if (config === undefined) {\n return yield* new MissingCredentialsError({\n message: `No iOS bundle configuration to rebind for ${input.bundleIdentifier} (${input.distribution}).`,\n hint: \"Run `better-update credentials configure --platform ios` (without --rebind) first.\",\n });\n }\n\n yield* Console.log(`Rebinding iOS bundle ${input.bundleIdentifier} (${input.distribution}).`);\n\n const { certId, cert } = yield* pickIosCertificate(api);\n const ascKeyId = yield* pickIosAscKey(api, cert.appleTeamId);\n const distributionType = IOS_DISTRIBUTION_TO_TYPE[input.distribution];\n const ctx: IosSetupContext = { certId, cert, ascKeyId, distributionType };\n const profileId = yield* resolveIosProfileId(api, input, ctx);\n\n yield* api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: {\n appleDistributionCertificateId: certId,\n appleProvisioningProfileId: profileId,\n ascApiKeyId: ascKeyId,\n },\n });\n yield* Console.log(\"iOS bundle configuration rebind complete.\");\n return undefined;\n });\n","import path from \"node:path\";\nimport process from \"node:process\";\n\nimport { fromBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport { generateAndUploadKeystore } from \"../lib/credentials-generator\";\nimport { uploadCredential } from \"../lib/credentials-manager\";\nimport { MissingCredentialsError } from \"../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../lib/expo-config\";\nimport { printHuman, printKeyValue } from \"../lib/output\";\nimport { promptPassword, promptSelect, promptText } from \"../lib/prompts\";\nimport { ensureAndroidCredentials } from \"./credentials-interactive\";\nimport { announce, BACK, pickAndDelete, safely, safePrompt } from \"./credentials-manager-shared\";\nimport { rebindAndroidKeystore, showAndroidBinding } from \"./credentials-rebind\";\n\nimport type { MenuEffect, WizardContext } from \"./credentials-manager-shared\";\n\nconst setupAndroidProjectCredentials = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const applicationIdentifier =\n ctx.androidPackage ?? (yield* promptText(\"Android application identifier\"));\n yield* ensureAndroidCredentials(\n ctx.api,\n { projectId: ctx.projectId, applicationIdentifier },\n { freezeCredentials: false },\n );\n yield* Console.log(\"\");\n yield* showAndroidBinding(ctx.api, { projectId: ctx.projectId, applicationIdentifier });\n });\n\nconst generateAndroidKeystoreInteractive = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const alias = yield* promptText(\"Key alias\", { placeholder: \"upload-key\" });\n const storePassword = yield* promptPassword(\"Keystore password\");\n const keyPassword = yield* promptPassword(\"Key password\");\n const commonName = yield* promptText(\"Common name (CN)\", { placeholder: \"Your App\" });\n const organization = yield* promptText(\"Organization (O)\", { placeholder: \"Your Company\" });\n yield* Console.log(\"Generating keystore with keytool...\");\n const created = yield* generateAndUploadKeystore(ctx.api, {\n keyAlias: alias,\n storePassword,\n keyPassword,\n commonName,\n organization,\n });\n yield* Console.log(\"Keystore generated and uploaded.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Alias\", created.keyAlias],\n ]);\n });\n\nconst uploadAndroidKeystoreInteractive = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const filePath = yield* promptText(\"Path to the keystore (.jks/.keystore) file\");\n const keyAlias = yield* promptText(\"Key alias\");\n const storePassword = yield* promptPassword(\"Keystore password\");\n const keyPassword = yield* promptPassword(\"Key password\");\n const created = yield* uploadCredential(ctx.api, {\n platform: \"android\",\n type: \"keystore\",\n name: keyAlias,\n filePath,\n keyAlias,\n keyPassword,\n password: storePassword,\n });\n yield* Console.log(\"Keystore uploaded.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Alias\", keyAlias],\n ]);\n });\n\nconst changeDefaultKeystore = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const applicationIdentifier =\n ctx.androidPackage ?? (yield* promptText(\"Android application identifier\"));\n yield* rebindAndroidKeystore(ctx.api, {\n projectId: ctx.projectId,\n applicationIdentifier,\n });\n yield* showAndroidBinding(ctx.api, { projectId: ctx.projectId, applicationIdentifier });\n });\n\nconst downloadAndroidKeystoreInteractive = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const list = yield* ctx.api.androidUploadKeystores.list();\n if (list.items.length === 0) {\n return yield* Console.log(\"No keystores to download.\");\n }\n const id = yield* promptSelect<string>(\n \"Select a keystore to download\",\n list.items.map((item) => ({\n value: item.id,\n label: `${item.keyAlias} (${item.id.slice(0, 8)}…)`,\n })),\n );\n const data = yield* ctx.api.androidUploadKeystores.download({ path: { id } });\n const defaultPath = path.join(process.cwd(), `${data.id}.keystore`);\n const rawTarget = yield* promptText(\"Output path\", { defaultValue: defaultPath });\n const target = rawTarget.trim().length === 0 ? defaultPath : rawTarget;\n const fs = yield* FileSystem.FileSystem;\n yield* fs.writeFile(target, fromBase64(data.keystoreBase64));\n yield* Console.log(\"Keystore downloaded.\");\n yield* printKeyValue([\n [\"Path\", target],\n [\"Key alias\", data.keyAlias],\n [\"Keystore password\", data.keystorePassword],\n [\"Key password\", data.keyPassword],\n ]);\n return undefined;\n });\n\nconst uploadAndroidGsa = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const filePath = yield* promptText(\"Path to the Google service account JSON file\");\n const created = yield* uploadCredential(ctx.api, {\n platform: \"android\",\n type: \"google-service-account-key\",\n name: filePath,\n filePath,\n });\n yield* Console.log(\"Google service account key uploaded.\");\n yield* printKeyValue([[\"ID\", created.id]]);\n });\n\nconst resolveAndroidPackageForBinding = (ctx: WizardContext) =>\n Effect.gen(function* () {\n if (ctx.androidPackage !== undefined) {\n return ctx.androidPackage;\n }\n const expo = yield* readExpoConfig(process.cwd()).pipe(\n Effect.catchAll(() => Effect.succeed(undefined)),\n );\n if (expo === undefined) {\n return yield* promptText(\"Android application identifier (package name)\");\n }\n const meta = yield* readAppMeta(expo, \"android\").pipe(\n Effect.catchAll(() => Effect.succeed({ androidPackage: undefined })),\n );\n return (\n meta.androidPackage ?? (yield* promptText(\"Android application identifier (package name)\"))\n );\n });\n\nconst findDefaultAndroidGroup = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const projectId =\n ctx.projectId.length > 0\n ? ctx.projectId\n : yield* extractProjectId(yield* readExpoConfig(process.cwd()));\n const applicationIdentifier = yield* resolveAndroidPackageForBinding(ctx);\n const apps = yield* ctx.api.androidApplicationIdentifiers.list({\n path: { projectId },\n });\n const app = apps.items.find((entry) => entry.packageName === applicationIdentifier);\n if (app === undefined) {\n return yield* new MissingCredentialsError({\n message: `No Android build credentials registered for ${applicationIdentifier}.`,\n hint: \"Run 'Keystore > Set up keystore for this app' first.\",\n });\n }\n const groups = yield* ctx.api.androidBuildCredentials.list({\n path: { applicationIdentifierId: app.id },\n });\n const group = groups.items.find((entry) => entry.isDefault) ?? groups.items.at(0);\n if (group === undefined) {\n return yield* new MissingCredentialsError({\n message: `No default Android build credentials group for ${applicationIdentifier}.`,\n hint: \"Run 'Keystore > Set up keystore for this app' first.\",\n });\n }\n return { applicationIdentifier, group } as const;\n });\n\nconst bindFcmV1Gsa = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keys = yield* ctx.api.googleServiceAccountKeys.list();\n if (keys.items.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No Google service account keys uploaded yet.\",\n hint: \"Run 'Upload a Google service account JSON key' first.\",\n });\n }\n const { applicationIdentifier, group } = yield* findDefaultAndroidGroup(ctx);\n const gsaKeyId = yield* promptSelect<string>(\n \"Select a GSA key to bind for FCM V1 push notifications\",\n keys.items.map((key) => ({\n value: key.id,\n label: `${key.clientEmail} (${key.id.slice(0, 8)}…)`,\n })),\n );\n yield* ctx.api.androidBuildCredentials.update({\n path: { id: group.id },\n payload: { googleServiceAccountKeyForFcmV1Id: gsaKeyId },\n });\n yield* Console.log(\n `Bound GSA key ${gsaKeyId.slice(0, 8)}… to ${applicationIdentifier} for FCM V1 push.`,\n );\n yield* printKeyValue([\n [\"Application\", applicationIdentifier],\n [\"Group\", group.name],\n [\"FCM V1 GSA key\", gsaKeyId],\n ]);\n return undefined;\n });\n\nconst unbindFcmV1Gsa = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const { applicationIdentifier, group } = yield* findDefaultAndroidGroup(ctx);\n if (group.googleServiceAccountKeyForFcmV1Id === null) {\n return yield* Console.log(`No FCM V1 GSA key bound to ${applicationIdentifier}.`);\n }\n yield* ctx.api.androidBuildCredentials.update({\n path: { id: group.id },\n payload: { googleServiceAccountKeyForFcmV1Id: null },\n });\n yield* Console.log(`Unbound FCM V1 GSA key from ${applicationIdentifier}.`);\n return undefined;\n });\n\nconst androidKeystoreMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"Android > Keystore\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"setup\", label: \"Set up keystore for this app (auto-generate or pick)\" },\n { value: \"generate\", label: \"Generate a new keystore\" },\n { value: \"upload\", label: \"Upload an existing keystore\" },\n { value: \"rebind\", label: \"Change the default keystore\" },\n { value: \"download\", label: \"Download a keystore\" },\n { value: \"delete\", label: \"Delete a keystore\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"setup\") {\n yield* safely(\"setup\", setupAndroidProjectCredentials(ctx));\n } else if (choice === \"generate\") {\n yield* safely(\"generate keystore\", generateAndroidKeystoreInteractive(ctx));\n } else if (choice === \"upload\") {\n yield* safely(\"upload keystore\", uploadAndroidKeystoreInteractive(ctx));\n } else if (choice === \"rebind\") {\n yield* safely(\"rebind keystore\", changeDefaultKeystore(ctx));\n } else if (choice === \"download\") {\n yield* safely(\"download keystore\", downloadAndroidKeystoreInteractive(ctx));\n } else if (choice === \"delete\") {\n yield* safely(\"delete keystore\", pickAndDelete(ctx, \"keystore\", \"keystore\"));\n }\n yield* androidKeystoreMenu(ctx);\n });\n\nconst androidGsaMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"Android > Google Service Account\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"upload\", label: \"Upload a Google service account JSON key\" },\n { value: \"bind-fcm\", label: \"Set up GSA key for FCM V1 push notifications\" },\n { value: \"unbind-fcm\", label: \"Unbind GSA key from FCM V1 push notifications\" },\n { value: \"delete\", label: \"Delete a Google service account key\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"upload\") {\n yield* safely(\"upload GSA\", uploadAndroidGsa(ctx));\n } else if (choice === \"bind-fcm\") {\n yield* safely(\"bind FCM V1 GSA\", bindFcmV1Gsa(ctx));\n } else if (choice === \"unbind-fcm\") {\n yield* safely(\"unbind FCM V1 GSA\", unbindFcmV1Gsa(ctx));\n } else if (choice === \"delete\") {\n yield* safely(\n \"delete GSA\",\n pickAndDelete(ctx, \"google-service-account-key\", \"Google service account key\"),\n );\n }\n yield* androidGsaMenu(ctx);\n });\n\nconst credentialsJsonMenuAndroid = (): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"Android > credentials.json\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"pull\", label: \"Download credentials to local credentials.json\" },\n { value: \"push\", label: \"Upload credentials.json to the server\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n const cmd = choice === \"pull\" ? \"credentials sync pull\" : \"credentials sync push\";\n yield* printHuman(\n `Run: \\`better-update ${cmd}\\` from your project root for the full file-aware flow.`,\n );\n yield* credentialsJsonMenuAndroid();\n });\n\nexport const androidMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"Android\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to manage?\", [\n { value: \"keystore\", label: \"Keystore\" },\n { value: \"gsa\", label: \"Google Service Account (FCM V1)\" },\n { value: \"json\", label: \"credentials.json (sync push/pull)\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"keystore\") {\n yield* androidKeystoreMenu(ctx);\n } else if (choice === \"gsa\") {\n yield* androidGsaMenu(ctx);\n } else if (choice === \"json\") {\n yield* credentialsJsonMenuAndroid();\n }\n yield* androidMenu(ctx);\n });\n","import { Console, Effect } from \"effect\";\n\nimport { uploadCredential } from \"../lib/credentials-manager\";\nimport { MissingCredentialsError } from \"../lib/exit-codes\";\nimport { printKeyValue } from \"../lib/output\";\nimport { promptSelect, promptText } from \"../lib/prompts\";\nimport {\n announce,\n BACK,\n pickAndDelete,\n promptForBundleConfig,\n safely,\n safePrompt,\n} from \"./credentials-manager-shared\";\n\nimport type { MenuEffect, WizardContext } from \"./credentials-manager-shared\";\n\nconst uploadIosAscKey = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keyId = (yield* promptText(\"ASC key ID (10 uppercase alphanumeric)\"))\n .trim()\n .toUpperCase();\n const issuerId = yield* promptText(\"ASC issuer ID (UUID)\");\n const p8Path = yield* promptText(\"Path to the ASC AuthKey_XXXXXXXXXX.p8 file\");\n const rawName = yield* promptText(\"Display name\", { defaultValue: keyId });\n const name = rawName.length === 0 ? keyId : rawName;\n const created = yield* uploadCredential(ctx.api, {\n platform: \"ios\",\n type: \"asc-api-key\",\n name,\n filePath: p8Path,\n keyId,\n issuerId,\n });\n yield* Console.log(\"ASC API key uploaded.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Key ID\", keyId],\n ]);\n });\n\nconst bindIosAscKey = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keys = yield* ctx.api.ascApiKeys.list();\n if (keys.items.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No ASC API keys uploaded yet.\",\n hint: \"Run 'Upload a new ASC API key' first.\",\n });\n }\n const config = yield* promptForBundleConfig(ctx);\n const ascKeyId = yield* promptSelect<string>(\n \"Select an ASC API key to bind\",\n keys.items.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n );\n yield* ctx.api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: { ascApiKeyId: ascKeyId },\n });\n yield* Console.log(\n `Bound ASC API key ${ascKeyId} to ${config.bundleIdentifier} (${config.distributionType}).`,\n );\n return undefined;\n });\n\nconst uploadNewAscKey = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keyId = (yield* promptText(\"ASC key ID (10 uppercase alphanumeric)\"))\n .trim()\n .toUpperCase();\n const issuerId = yield* promptText(\"ASC issuer ID (UUID)\");\n const p8Path = yield* promptText(\"Path to the ASC AuthKey_XXXXXXXXXX.p8 file\");\n const rawName = yield* promptText(\"Display name\", { defaultValue: keyId });\n const name = rawName.length === 0 ? keyId : rawName;\n const created = yield* uploadCredential(ctx.api, {\n platform: \"ios\",\n type: \"asc-api-key\",\n name,\n filePath: p8Path,\n keyId,\n issuerId,\n });\n yield* Console.log(`ASC API key ${keyId} uploaded.`);\n return created.id;\n });\n\nconst setupProjectAscApiKey = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keys = yield* ctx.api.ascApiKeys.list();\n const choice =\n keys.items.length === 0\n ? \"upload\"\n : yield* promptSelect<\"upload\" | \"existing\">(\"How would you like to set up the ASC key?\", [\n {\n value: \"existing\",\n label: `Use an existing ASC API key (${String(keys.items.length)})`,\n },\n { value: \"upload\", label: \"Upload a new ASC API key\" },\n ]);\n const config = yield* promptForBundleConfig(ctx);\n const ascKeyId =\n choice === \"upload\"\n ? yield* uploadNewAscKey(ctx)\n : yield* promptSelect<string>(\n \"Select an ASC API key to bind\",\n keys.items.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n );\n yield* ctx.api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: { ascApiKeyId: ascKeyId },\n });\n yield* Console.log(\n `ASC API key set up: ${ascKeyId} bound to ${config.bundleIdentifier} (${config.distributionType}).`,\n );\n return undefined;\n });\n\nexport const iosAscKeysMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"iOS > App Store Connect API Key\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"setup\", label: \"Set up your project to use an ASC API Key\" },\n { value: \"upload\", label: \"Add a new ASC API key\" },\n { value: \"bind\", label: \"Use an existing ASC API key\" },\n { value: \"delete\", label: \"Delete an ASC API key\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"setup\") {\n yield* safely(\"set up ASC key\", setupProjectAscApiKey(ctx));\n } else if (choice === \"upload\") {\n yield* safely(\"upload ASC key\", uploadIosAscKey(ctx));\n } else if (choice === \"bind\") {\n yield* safely(\"bind ASC key\", bindIosAscKey(ctx));\n } else if (choice === \"delete\") {\n yield* safely(\"delete ASC key\", pickAndDelete(ctx, \"asc-api-key\", \"ASC API key\"));\n }\n yield* iosAscKeysMenu(ctx);\n });\n","import { Console, Effect } from \"effect\";\n\nimport { revokeLocalDistributionCertificate } from \"../lib/credentials-generator\";\nimport { MissingCredentialsError } from \"../lib/exit-codes\";\nimport { printKeyValue } from \"../lib/output\";\nimport { promptConfirm, promptSelect } from \"../lib/prompts\";\n\nimport type { WizardContext } from \"./credentials-manager-shared\";\n\nexport const revokeIosDistributionCert = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const certs = yield* ctx.api.appleDistributionCertificates.list();\n if (certs.items.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No distribution certificates in this account.\",\n hint: \"Run 'Add a new distribution certificate' to create one first.\",\n });\n }\n const ascKeys = yield* ctx.api.ascApiKeys.list();\n const teamKeys = ascKeys.items.filter((entry) => entry.appleTeamId !== null);\n if (teamKeys.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No ASC API key linked to an Apple team.\",\n hint: \"Upload an ASC API key first so the CLI can call Apple to revoke.\",\n });\n }\n const localId = yield* promptSelect<string>(\n \"Select a distribution certificate to revoke\",\n certs.items.map((cert) => ({\n value: cert.id,\n label: `${cert.serialNumber.slice(0, 12)}… (team ${cert.appleTeamId})`,\n })),\n );\n const target = certs.items.find((entry) => entry.id === localId);\n const matchingAscKey = teamKeys.find((key) => key.appleTeamId === target?.appleTeamId);\n const ascApiKeyId =\n matchingAscKey?.id ??\n (yield* promptSelect<string>(\n \"Select an ASC API key to call Apple with\",\n teamKeys.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n ));\n const keepLocal = yield* promptConfirm(\"Keep the certificate in this account after revoking?\", {\n initialValue: false,\n });\n yield* Console.log(\"Calling Apple to revoke the certificate...\");\n const result = yield* revokeLocalDistributionCertificate(ctx.api, {\n ascApiKeyId,\n distributionCertificateId: localId,\n keepLocal,\n });\n yield* Console.log(\"Revoke complete.\");\n yield* printKeyValue([\n [\"Local ID\", result.localId],\n [\"Serial\", result.serialNumber],\n [\"Revoked on Apple\", result.revokedOnApple ? \"yes\" : \"no (not present on portal)\"],\n [\"Deleted locally\", result.deletedLocally ? \"yes\" : \"no (kept)\"],\n ]);\n return undefined;\n });\n","import { Console, Effect } from \"effect\";\n\nimport { generateAndUploadDistributionCertificate } from \"../lib/credentials-generator\";\nimport { uploadCredential } from \"../lib/credentials-manager\";\nimport { CredentialValidationError, MissingCredentialsError } from \"../lib/exit-codes\";\nimport { printHuman, printKeyValue } from \"../lib/output\";\nimport { promptSelect, promptText } from \"../lib/prompts\";\nimport {\n ensureIosCredentials,\n pickIosAscKey,\n pickIosCertificate,\n regenerateProvisioningProfile,\n resolveIosProfileId,\n} from \"./credentials-interactive\";\nimport { iosAscKeysMenu } from \"./credentials-manager-ios-asc\";\nimport { revokeIosDistributionCert } from \"./credentials-manager-ios-revoke\";\nimport {\n announce,\n APPLE_PUSH_KEY_PORTAL_URL,\n BACK,\n DISTRIBUTION_OPTIONS,\n matchDistribution,\n pickAndDelete,\n promptForBundleConfig,\n safely,\n safePrompt,\n} from \"./credentials-manager-shared\";\nimport { showIosBinding } from \"./credentials-rebind\";\n\nimport type { IosDistribution } from \"../lib/build-profile\";\nimport type { IosSetupContext } from \"./credentials-interactive\";\nimport type { MenuEffect, WizardContext } from \"./credentials-manager-shared\";\n\nconst APPLE_TEN_CHARS = /^[A-Z0-9]{10}$/u;\n\n// ── Actions ──────────────────────────────────────────────────────\n\nconst setupIosProjectCredentials = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const bundleIdentifier = ctx.iosBundleId ?? (yield* promptText(\"iOS bundle identifier\"));\n const distribution = yield* promptSelect<IosDistribution>(\n \"Distribution type\",\n DISTRIBUTION_OPTIONS,\n );\n yield* ensureIosCredentials(\n ctx.api,\n { projectId: ctx.projectId, bundleIdentifier, distribution },\n { freezeCredentials: false },\n );\n yield* Console.log(\"\");\n yield* showIosBinding(ctx.api, {\n projectId: ctx.projectId,\n bundleIdentifier,\n distribution,\n });\n });\n\nconst useExistingIosDistributionCert = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const config = yield* promptForBundleConfig(ctx);\n yield* Console.log(\n `Re-binding distribution certificate + provisioning profile for ${config.bundleIdentifier} (${config.distributionType}).`,\n );\n const { certId, cert } = yield* pickIosCertificate(ctx.api);\n const ascKeyId = yield* pickIosAscKey(ctx.api, cert.appleTeamId);\n const setupCtx: IosSetupContext = {\n certId,\n cert,\n ascKeyId,\n distributionType: config.distributionType,\n };\n const profileId = yield* resolveIosProfileId(\n ctx.api,\n {\n projectId: ctx.projectId,\n bundleIdentifier: config.bundleIdentifier,\n distribution: matchDistribution(config.distributionType),\n },\n setupCtx,\n );\n yield* ctx.api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: {\n appleDistributionCertificateId: certId,\n appleProvisioningProfileId: profileId,\n ascApiKeyId: ascKeyId,\n },\n });\n yield* Console.log(\"Bundle configuration updated.\");\n });\n\nconst generateNewIosDistributionCert = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const ascKeys = yield* ctx.api.ascApiKeys.list();\n const teamKeys = ascKeys.items.filter((entry) => entry.appleTeamId !== null);\n if (teamKeys.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No ASC API key linked to an Apple team.\",\n hint: \"Upload an ASC API key first (App Store Connect API Key > Upload).\",\n });\n }\n const ascKeyId = yield* promptSelect<string>(\n \"ASC API key to issue against\",\n teamKeys.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n );\n yield* Console.log(\"Generating CSR and requesting certificate from Apple...\");\n const created = yield* generateAndUploadDistributionCertificate(ctx.api, {\n ascApiKeyId: ascKeyId,\n });\n yield* Console.log(\"Distribution certificate generated.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Serial\", created.serialNumber],\n [\"Apple team\", created.appleTeamId],\n ]);\n return undefined;\n });\n\nconst addIosPushKey = (ctx: WizardContext) =>\n Effect.gen(function* () {\n yield* printHuman(\"Apple does not expose APNs key creation via API.\");\n yield* printHuman(`Create one here, download .p8, then return: ${APPLE_PUSH_KEY_PORTAL_URL}`);\n const keyId = (yield* promptText(\"APNs key ID (10 uppercase alphanumeric)\"))\n .trim()\n .toUpperCase();\n if (!APPLE_TEN_CHARS.test(keyId)) {\n return yield* new CredentialValidationError({\n message: `Push key ID \"${keyId}\" must be 10 uppercase alphanumeric characters.`,\n });\n }\n const ascKeys = yield* ctx.api.ascApiKeys.list();\n const teamKeys = ascKeys.items.filter((entry) => entry.appleTeamId !== null);\n const [firstKey] = teamKeys;\n const teamFromAsc =\n teamKeys.length === 1 && firstKey !== undefined && firstKey.appleTeamId !== null\n ? firstKey.appleTeamId\n : undefined;\n const appleTeamIdentifier = teamFromAsc ?? (yield* promptText(\"Apple Team identifier\"));\n if (!APPLE_TEN_CHARS.test(appleTeamIdentifier)) {\n return yield* new CredentialValidationError({\n message: \"Apple Team ID must be 10 uppercase alphanumeric characters.\",\n });\n }\n const p8Path = yield* promptText(\"Path to the AuthKey_XXXXXXXXXX.p8 file\");\n const created = yield* uploadCredential(ctx.api, {\n platform: \"ios\",\n type: \"push-key\",\n name: keyId,\n filePath: p8Path,\n keyId,\n appleTeamIdentifier,\n });\n yield* Console.log(\"APNs push key registered.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Key ID\", keyId],\n [\"Apple team\", appleTeamIdentifier],\n ]);\n return undefined;\n });\n\nconst bindIosPushKey = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keys = yield* ctx.api.applePushKeys.list();\n if (keys.items.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No APNs auth keys uploaded yet.\",\n hint: \"Run 'Add a new push key' first.\",\n });\n }\n const config = yield* promptForBundleConfig(ctx);\n const pushKeyId = yield* promptSelect<string>(\n \"Select a push key to bind\",\n keys.items.map((key) => ({ value: key.id, label: `${key.keyId} (team ${key.appleTeamId})` })),\n );\n yield* ctx.api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: { applePushKeyId: pushKeyId },\n });\n yield* Console.log(\n `Bound push key ${pushKeyId} to ${config.bundleIdentifier} (${config.distributionType}).`,\n );\n return undefined;\n });\n\nconst setupProjectPushNotifications = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const keys = yield* ctx.api.applePushKeys.list();\n const choice =\n keys.items.length === 0\n ? \"add\"\n : yield* promptSelect<\"add\" | \"existing\">(\"How would you like to set up the push key?\", [\n { value: \"existing\", label: `Use an existing push key (${String(keys.items.length)})` },\n { value: \"add\", label: \"Add a new push key\" },\n ]);\n const config = yield* promptForBundleConfig(ctx);\n const pushKeyId =\n choice === \"add\"\n ? yield* createNewPushKeyForBundle(ctx, config.appleTeamId)\n : yield* promptSelect<string>(\n \"Select a push key to bind\",\n keys.items.map((key) => ({\n value: key.id,\n label: `${key.keyId} (team ${key.appleTeamId})`,\n })),\n );\n yield* ctx.api.iosBundleConfigurations.update({\n path: { id: config.id },\n payload: { applePushKeyId: pushKeyId },\n });\n yield* Console.log(\n `Push notifications set up: key ${pushKeyId} bound to ${config.bundleIdentifier} (${config.distributionType}).`,\n );\n return undefined;\n });\n\nconst createNewPushKeyForBundle = (ctx: WizardContext, fallbackTeamId: string) =>\n Effect.gen(function* () {\n yield* printHuman(\"Apple does not expose APNs key creation via API.\");\n yield* printHuman(`Create one here, download .p8, then return: ${APPLE_PUSH_KEY_PORTAL_URL}`);\n const rawKeyId = (yield* promptText(\"APNs key ID (10 uppercase alphanumeric)\"))\n .trim()\n .toUpperCase();\n if (!APPLE_TEN_CHARS.test(rawKeyId)) {\n return yield* new CredentialValidationError({\n message: `Push key ID \"${rawKeyId}\" must be 10 uppercase alphanumeric characters.`,\n });\n }\n const rawTeamId = (yield* promptText(\"Apple Team identifier\", {\n defaultValue: fallbackTeamId,\n }))\n .trim()\n .toUpperCase();\n if (!APPLE_TEN_CHARS.test(rawTeamId)) {\n return yield* new CredentialValidationError({\n message: \"Apple Team ID must be 10 uppercase alphanumeric characters.\",\n });\n }\n const p8Path = yield* promptText(\"Path to the AuthKey_XXXXXXXXXX.p8 file\");\n const created = yield* uploadCredential(ctx.api, {\n platform: \"ios\",\n type: \"push-key\",\n name: rawKeyId,\n filePath: p8Path,\n keyId: rawKeyId,\n appleTeamIdentifier: rawTeamId,\n });\n yield* Console.log(`APNs push key ${rawKeyId} uploaded.`);\n return created.id;\n });\n\n// ── Menus ────────────────────────────────────────────────────────\n\nconst refreshIosProvisioningProfile = (ctx: WizardContext) =>\n Effect.gen(function* () {\n const config = yield* promptForBundleConfig(ctx);\n yield* regenerateProvisioningProfile(ctx.api, {\n projectId: ctx.projectId,\n bundleIdentifier: config.bundleIdentifier,\n distribution: matchDistribution(config.distributionType),\n });\n });\n\nconst iosBuildCredentialsMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"iOS > Build Credentials\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"setup\", label: \"Set up project credentials (cert + profile + bind)\" },\n { value: \"use-existing-cert\", label: \"Use an existing distribution certificate\" },\n { value: \"generate-cert\", label: \"Add a new distribution certificate\" },\n { value: \"refresh-profile\", label: \"Refresh provisioning profile (re-issue from Apple)\" },\n {\n value: \"revoke-cert\",\n label: \"Revoke a distribution certificate (Apple Developer Portal)\",\n },\n { value: \"delete-cert\", label: \"Delete a distribution certificate (local only)\" },\n { value: \"delete-profile\", label: \"Delete a provisioning profile\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"setup\") {\n yield* safely(\"setup\", setupIosProjectCredentials(ctx));\n } else if (choice === \"use-existing-cert\") {\n yield* safely(\"use existing cert\", useExistingIosDistributionCert(ctx));\n } else if (choice === \"generate-cert\") {\n yield* safely(\"generate cert\", generateNewIosDistributionCert(ctx));\n } else if (choice === \"refresh-profile\") {\n yield* safely(\"refresh provisioning profile\", refreshIosProvisioningProfile(ctx));\n } else if (choice === \"revoke-cert\") {\n yield* safely(\"revoke cert\", revokeIosDistributionCert(ctx));\n } else if (choice === \"delete-cert\") {\n yield* safely(\n \"delete cert\",\n pickAndDelete(ctx, \"distribution-certificate\", \"iOS distribution certificate\"),\n );\n } else if (choice === \"delete-profile\") {\n yield* safely(\n \"delete profile\",\n pickAndDelete(ctx, \"provisioning-profile\", \"iOS provisioning profile\"),\n );\n }\n yield* iosBuildCredentialsMenu(ctx);\n });\n\nconst iosPushKeysMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"iOS > Push Notifications\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"setup\", label: \"Set up your project to use Push Notifications\" },\n { value: \"add\", label: \"Add a new push key\" },\n { value: \"bind\", label: \"Use an existing push key\" },\n { value: \"remove\", label: \"Remove a push key\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"setup\") {\n yield* safely(\"set up push notifications\", setupProjectPushNotifications(ctx));\n } else if (choice === \"add\") {\n yield* safely(\"add push key\", addIosPushKey(ctx));\n } else if (choice === \"bind\") {\n yield* safely(\"bind push key\", bindIosPushKey(ctx));\n } else if (choice === \"remove\") {\n yield* safely(\"remove push key\", pickAndDelete(ctx, \"push-key\", \"APNs push key\"));\n }\n yield* iosPushKeysMenu(ctx);\n });\n\nconst credentialsJsonMenuIos = (): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"iOS > credentials.json\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to do?\", [\n { value: \"pull\", label: \"Download credentials to local credentials.json\" },\n { value: \"push\", label: \"Upload credentials.json to the server\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n const cmd = choice === \"pull\" ? \"credentials sync pull\" : \"credentials sync push\";\n yield* printHuman(\n `Run: \\`better-update ${cmd}\\` from your project root for the full file-aware flow.`,\n );\n yield* credentialsJsonMenuIos();\n });\n\nexport const iosMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"iOS\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"What do you want to manage?\", [\n { value: \"build\", label: \"Build Credentials (cert + provisioning profile)\" },\n { value: \"push\", label: \"Push Notifications (APNs auth key)\" },\n { value: \"asc\", label: \"App Store Connect API Key\" },\n { value: \"json\", label: \"credentials.json (sync push/pull)\" },\n { value: BACK, label: \"Go back\" },\n ]),\n );\n if (choice === BACK) {\n return;\n }\n if (choice === \"build\") {\n yield* iosBuildCredentialsMenu(ctx);\n } else if (choice === \"push\") {\n yield* iosPushKeysMenu(ctx);\n } else if (choice === \"asc\") {\n yield* iosAscKeysMenu(ctx);\n } else if (choice === \"json\") {\n yield* credentialsJsonMenuIos();\n }\n yield* iosMenu(ctx);\n });\n","import { Console, Effect } from \"effect\";\n\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../lib/expo-config\";\nimport { promptSelect } from \"../lib/prompts\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { androidMenu } from \"./credentials-manager-android\";\nimport { iosMenu } from \"./credentials-manager-ios\";\nimport { announce, EXIT, safePrompt } from \"./credentials-manager-shared\";\n\nimport type { MenuEffect, WizardContext } from \"./credentials-manager-shared\";\n\nconst mainMenu = (ctx: WizardContext): MenuEffect =>\n Effect.gen(function* () {\n yield* announce(\"Main\");\n const choice = yield* safePrompt(\n promptSelect<string>(\"Pick a platform\", [\n { value: \"ios\", label: \"iOS\" },\n { value: \"android\", label: \"Android\" },\n { value: EXIT, label: \"Exit\" },\n ]),\n );\n if (choice === EXIT) {\n return;\n }\n if (choice === \"ios\") {\n yield* iosMenu(ctx);\n } else if (choice === \"android\") {\n yield* androidMenu(ctx);\n }\n yield* mainMenu(ctx);\n });\n\nexport const runCredentialsManager = Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const cwd = yield* runtime.cwd;\n\n const expoConfig = yield* readExpoConfig(cwd);\n const projectId = yield* extractProjectId(expoConfig);\n const emptyMeta = {\n bundleId: undefined,\n androidPackage: undefined,\n appVersion: undefined,\n buildNumber: undefined,\n rawRuntimeVersion: undefined,\n } as const;\n const iosMeta = yield* readAppMeta(expoConfig, \"ios\").pipe(Effect.orElseSucceed(() => emptyMeta));\n const androidMeta = yield* readAppMeta(expoConfig, \"android\").pipe(\n Effect.orElseSucceed(() => emptyMeta),\n );\n\n const ctx: WizardContext = {\n api,\n projectId,\n iosBundleId: iosMeta.bundleId,\n androidPackage: androidMeta.androidPackage,\n };\n\n yield* Console.log(\"better-update credentials manager\");\n yield* Console.log(`Project: ${projectId}`);\n\n yield* mainMenu(ctx);\n\n yield* Console.log(\"Bye.\");\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport {\n ensureAndroidCredentials,\n ensureIosCredentials,\n} from \"../../application/credentials-interactive\";\nimport {\n rebindAndroidKeystore,\n rebindIosBundle,\n showAndroidBinding,\n showIosBinding,\n} from \"../../application/credentials-rebind\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { IOS_DISTRIBUTION_TO_TYPE } from \"../../lib/credentials-downloader\";\nimport { MissingCredentialsError } from \"../../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../../lib/expo-config\";\nimport { printHuman } from \"../../lib/output\";\nimport { promptSelect, promptText } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nimport type { IosDistribution } from \"../../lib/build-profile\";\nimport type { ApiClient } from \"../../services/api-client\";\n\ninterface ConfigureAndroidArgs {\n readonly api: ApiClient;\n readonly projectId: string;\n readonly applicationIdentifier: string;\n readonly rebind: boolean;\n readonly bindFcmGsa: string | undefined;\n}\n\nconst bindAndroidFcmGsa = (\n api: ApiClient,\n input: {\n readonly projectId: string;\n readonly applicationIdentifier: string;\n readonly gsaKeyId: string;\n },\n) =>\n Effect.gen(function* () {\n const apps = yield* api.androidApplicationIdentifiers.list({\n path: { projectId: input.projectId },\n });\n const app = apps.items.find((entry) => entry.packageName === input.applicationIdentifier);\n if (app === undefined) {\n return yield* new MissingCredentialsError({\n message: `No Android build credentials for ${input.applicationIdentifier}.`,\n hint: \"Run `better-update credentials configure --platform android` (without --bind-fcm-gsa) first to create one.\",\n });\n }\n const groups = yield* api.androidBuildCredentials.list({\n path: { applicationIdentifierId: app.id },\n });\n const group = groups.items.find((entry) => entry.isDefault) ?? groups.items.at(0);\n if (group === undefined) {\n return yield* new MissingCredentialsError({\n message: `No default Android build credentials group for ${input.applicationIdentifier}.`,\n hint: \"Run `better-update credentials configure --platform android` (without --bind-fcm-gsa) first.\",\n });\n }\n yield* api.androidBuildCredentials.update({\n path: { id: group.id },\n payload: { googleServiceAccountKeyForFcmV1Id: input.gsaKeyId },\n });\n yield* Console.log(`Bound FCM V1 GSA key ${input.gsaKeyId} to ${input.applicationIdentifier}.`);\n return undefined;\n });\n\nconst bindBundleResource = (\n api: ApiClient,\n input: {\n readonly projectId: string;\n readonly bundleIdentifier: string;\n readonly distribution: IosDistribution;\n },\n payload: { readonly applePushKeyId?: string; readonly ascApiKeyId?: string },\n) =>\n Effect.gen(function* () {\n const distributionType = IOS_DISTRIBUTION_TO_TYPE[input.distribution];\n const list = yield* api.iosBundleConfigurations.list({\n path: { projectId: input.projectId },\n });\n const match = list.items.find(\n (item) =>\n item.bundleIdentifier === input.bundleIdentifier &&\n item.distributionType === distributionType,\n );\n if (match === undefined) {\n return yield* new MissingCredentialsError({\n message: `No iOS bundle configuration for ${input.bundleIdentifier} (${input.distribution}).`,\n hint: \"Run credentials configure --platform ios (without --bind-*) once to create it.\",\n });\n }\n yield* api.iosBundleConfigurations.update({\n path: { id: match.id },\n payload,\n });\n yield* Console.log(\n `Updated iOS bundle ${input.bundleIdentifier} (${input.distribution}) binding.`,\n );\n return undefined;\n });\n\nconst configureAndroid = (args: ConfigureAndroidArgs) =>\n Effect.gen(function* () {\n const input = {\n projectId: args.projectId,\n applicationIdentifier: args.applicationIdentifier,\n };\n if (args.bindFcmGsa !== undefined) {\n yield* bindAndroidFcmGsa(args.api, { ...input, gsaKeyId: args.bindFcmGsa });\n yield* Console.log(\"\");\n yield* Console.log(\"Updated binding:\");\n yield* showAndroidBinding(args.api, input);\n return;\n }\n if (args.rebind) {\n yield* rebindAndroidKeystore(args.api, input);\n yield* Console.log(\"\");\n yield* Console.log(\"Updated binding:\");\n yield* showAndroidBinding(args.api, input);\n return;\n }\n yield* Console.log(`Configuring Android credentials for ${args.applicationIdentifier}...`);\n yield* ensureAndroidCredentials(args.api, input, { freezeCredentials: false });\n yield* Console.log(\"\");\n yield* Console.log(\"Current Android binding:\");\n yield* showAndroidBinding(args.api, input);\n yield* printHuman(\"\");\n yield* printHuman(\"Run with --rebind to switch keystore on the default group.\");\n yield* printHuman(\n \"Run with --bind-fcm-gsa <gsaKeyId> to bind a GSA key for FCM V1 push notifications.\",\n );\n });\n\ninterface ConfigureIosArgs {\n readonly api: ApiClient;\n readonly projectId: string;\n readonly bundleIdentifier: string;\n readonly distribution: IosDistribution;\n readonly rebind: boolean;\n readonly bindPushKey: string | undefined;\n readonly bindAscKey: string | undefined;\n}\n\nconst configureIos = (args: ConfigureIosArgs) =>\n Effect.gen(function* () {\n const input = {\n projectId: args.projectId,\n bundleIdentifier: args.bundleIdentifier,\n distribution: args.distribution,\n };\n if (args.bindPushKey !== undefined || args.bindAscKey !== undefined) {\n yield* bindBundleResource(args.api, input, {\n ...(args.bindPushKey === undefined ? {} : { applePushKeyId: args.bindPushKey }),\n ...(args.bindAscKey === undefined ? {} : { ascApiKeyId: args.bindAscKey }),\n });\n yield* Console.log(\"\");\n yield* Console.log(\"Updated binding:\");\n yield* showIosBinding(args.api, input);\n return;\n }\n if (args.rebind) {\n yield* rebindIosBundle(args.api, input);\n yield* Console.log(\"\");\n yield* Console.log(\"Updated binding:\");\n yield* showIosBinding(args.api, input);\n return;\n }\n yield* Console.log(\n `Configuring iOS credentials for ${args.bundleIdentifier} (${args.distribution})...`,\n );\n yield* ensureIosCredentials(args.api, input, { freezeCredentials: false });\n yield* Console.log(\"\");\n yield* Console.log(\"Current iOS binding:\");\n yield* showIosBinding(args.api, input);\n yield* printHuman(\"\");\n yield* printHuman(\"Run with --rebind to switch certificate, profile, or ASC key.\");\n yield* printHuman(\n \"Run with --bind-push-key <id> / --bind-asc-key <id> to update a single binding.\",\n );\n });\n\nexport const configureCommand = defineCommand({\n meta: {\n name: \"configure\",\n description: \"Interactive wizard to configure signing credentials (outside a build run)\",\n },\n args: {\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\"],\n description: \"Skip the platform prompt\",\n },\n bundle: { type: \"string\", description: \"iOS bundle identifier (defaults to app.json)\" },\n \"android-package\": {\n type: \"string\",\n description: \"Android application identifier (defaults to app.json)\",\n },\n distribution: {\n type: \"enum\",\n options: [\"ad-hoc\", \"app-store\", \"development\", \"enterprise\"],\n default: \"ad-hoc\",\n description: \"iOS distribution type\",\n },\n rebind: {\n type: \"boolean\",\n description: \"Re-bind credentials on an already-configured app/bundle (swap keystore/cert)\",\n },\n \"bind-push-key\": {\n type: \"string\",\n description: \"iOS only: bind an existing push key by ID to the bundle config\",\n },\n \"bind-asc-key\": {\n type: \"string\",\n description: \"iOS only: bind an existing ASC API key by ID to the bundle config\",\n },\n \"bind-fcm-gsa\": {\n type: \"string\",\n description:\n \"Android only: bind an existing GSA key by ID to FCM V1 push notifications on the default credentials group\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const root = yield* runtime.cwd;\n const expo = yield* readExpoConfig(root);\n const projectId = yield* extractProjectId(expo);\n\n const platform =\n args.platform ??\n (yield* promptSelect<\"ios\" | \"android\">(\"Configure credentials for which platform?\", [\n { value: \"ios\", label: \"iOS\" },\n { value: \"android\", label: \"Android\" },\n ]));\n\n if (platform === \"ios\") {\n const iosMeta = yield* readAppMeta(expo, \"ios\");\n const bundleIdentifier =\n args.bundle ?? iosMeta.bundleId ?? (yield* promptText(\"iOS bundle identifier\"));\n yield* configureIos({\n api,\n projectId,\n bundleIdentifier,\n distribution: args.distribution as IosDistribution,\n rebind: args.rebind ?? false,\n bindPushKey: args[\"bind-push-key\"],\n bindAscKey: args[\"bind-asc-key\"],\n });\n return;\n }\n const androidMeta = yield* readAppMeta(expo, \"android\");\n const applicationIdentifier =\n args[\"android-package\"] ??\n androidMeta.androidPackage ??\n (yield* promptText(\"Android application identifier\"));\n yield* configureAndroid({\n api,\n projectId,\n applicationIdentifier,\n rebind: args.rebind ?? false,\n bindFcmGsa: args[\"bind-fcm-gsa\"],\n });\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { deleteCredential } from \"../../lib/credentials-manager\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { CliCredentialType } from \"../../lib/credentials-manager\";\n\nconst CREDENTIAL_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a credential\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Credential ID\" },\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n type: { type: \"enum\", options: [...CREDENTIAL_TYPES], required: true },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* deleteCredential(api, {\n id: args.id,\n platform: args.platform,\n type: args.type as CliCredentialType,\n });\n yield* Console.log(`Credential ${args.id} deleted.`);\n }),\n ),\n});\n","import path from \"node:path\";\n\nimport { fromBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { CredentialValidationError } from \"../../lib/exit-codes\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst DOWNLOAD_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\ntype DownloadType = (typeof DOWNLOAD_TYPES)[number];\n\ninterface DownloadResult {\n readonly path: string;\n readonly pairs: readonly (readonly [string, string])[];\n readonly metadata: Readonly<Record<string, string>>;\n}\n\nconst writeBinary = (filePath: string, bytes: Uint8Array) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.writeFile(filePath, bytes);\n });\n\nconst writeText = (filePath: string, contents: string) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.writeFileString(filePath, contents);\n });\n\nconst resolveOutputPath = (cwd: string, output: string | undefined, defaultName: string) =>\n output === undefined || output.length === 0 ? path.join(cwd, defaultName) : output;\n\nconst downloadDistributionCertificate = (\n api: ApiClient,\n id: string,\n cwd: string,\n output: string | undefined,\n) =>\n Effect.gen(function* () {\n const data = yield* api.appleDistributionCertificates.download({ path: { id } });\n const filePath = resolveOutputPath(cwd, output, `${data.id}.p12`);\n yield* writeBinary(filePath, fromBase64(data.p12Base64));\n return {\n path: filePath,\n pairs: [\n [\"Path\", filePath],\n [\"Type\", \"Apple distribution certificate (.p12)\"],\n [\"Serial\", data.serialNumber],\n [\"Apple team\", data.appleTeamIdentifier],\n [\"Valid from\", data.validFrom],\n [\"Valid until\", data.validUntil],\n [\"P12 password\", data.p12Password],\n ] as const,\n metadata: {\n serialNumber: data.serialNumber,\n appleTeamIdentifier: data.appleTeamIdentifier,\n validFrom: data.validFrom,\n validUntil: data.validUntil,\n p12Password: data.p12Password,\n },\n } satisfies DownloadResult;\n });\n\nconst downloadProvisioningProfile = (\n api: ApiClient,\n id: string,\n cwd: string,\n output: string | undefined,\n) =>\n Effect.gen(function* () {\n const data = yield* api.appleProvisioningProfiles.download({ path: { id } });\n const filePath = resolveOutputPath(cwd, output, `${data.id}.mobileprovision`);\n yield* writeBinary(filePath, fromBase64(data.profileBase64));\n return {\n path: filePath,\n pairs: [\n [\"Path\", filePath],\n [\"Type\", \"Apple provisioning profile (.mobileprovision)\"],\n [\"Bundle\", data.bundleIdentifier],\n [\"Distribution\", data.distributionType],\n [\"Profile name\", data.profileName ?? \"-\"],\n [\"Apple profile\", data.developerPortalIdentifier ?? \"-\"],\n ] as const,\n metadata: {\n bundleIdentifier: data.bundleIdentifier,\n distributionType: data.distributionType,\n ...(data.profileName === null ? {} : { profileName: data.profileName }),\n ...(data.developerPortalIdentifier === null\n ? {}\n : { developerPortalIdentifier: data.developerPortalIdentifier }),\n },\n } satisfies DownloadResult;\n });\n\nconst downloadPushKey = (api: ApiClient, id: string, cwd: string, output: string | undefined) =>\n Effect.gen(function* () {\n const data = yield* api.applePushKeys.download({ path: { id } });\n const filePath = resolveOutputPath(cwd, output, `AuthKey_${data.keyId}.p8`);\n yield* writeText(filePath, data.p8Pem);\n return {\n path: filePath,\n pairs: [\n [\"Path\", filePath],\n [\"Type\", \"Apple APNs auth key (.p8)\"],\n [\"Key ID\", data.keyId],\n [\"Apple team\", data.appleTeamIdentifier],\n ] as const,\n metadata: {\n keyId: data.keyId,\n appleTeamIdentifier: data.appleTeamIdentifier,\n },\n } satisfies DownloadResult;\n });\n\nconst downloadAscApiKey = (api: ApiClient, id: string, cwd: string, output: string | undefined) =>\n Effect.gen(function* () {\n const data = yield* api.ascApiKeys.getCredentials({ path: { id } });\n const filePath = resolveOutputPath(cwd, output, `AuthKey_${data.keyId}-asc.p8`);\n yield* writeText(filePath, data.p8Pem);\n return {\n path: filePath,\n pairs: [\n [\"Path\", filePath],\n [\"Type\", \"App Store Connect API key (.p8)\"],\n [\"Key ID\", data.keyId],\n [\"Issuer ID\", data.issuerId],\n [\"Apple team\", data.appleTeamIdentifier ?? \"-\"],\n ] as const,\n metadata: {\n keyId: data.keyId,\n issuerId: data.issuerId,\n ...(data.appleTeamIdentifier === null\n ? {}\n : { appleTeamIdentifier: data.appleTeamIdentifier }),\n },\n } satisfies DownloadResult;\n });\n\nconst downloadKeystore = (api: ApiClient, id: string, cwd: string, output: string | undefined) =>\n Effect.gen(function* () {\n const data = yield* api.androidUploadKeystores.download({ path: { id } });\n const filePath = resolveOutputPath(cwd, output, `${data.id}.keystore`);\n yield* writeBinary(filePath, fromBase64(data.keystoreBase64));\n return {\n path: filePath,\n pairs: [\n [\"Path\", filePath],\n [\"Type\", \"Android upload keystore\"],\n [\"Key alias\", data.keyAlias],\n [\"Keystore password\", data.keystorePassword],\n [\"Key password\", data.keyPassword],\n ] as const,\n metadata: {\n keyAlias: data.keyAlias,\n keystorePassword: data.keystorePassword,\n keyPassword: data.keyPassword,\n },\n } satisfies DownloadResult;\n });\n\nconst downloadGoogleServiceAccountKey = (\n api: ApiClient,\n id: string,\n cwd: string,\n output: string | undefined,\n) =>\n Effect.gen(function* () {\n const data = yield* api.googleServiceAccountKeys.download({ path: { id } });\n const filePath = resolveOutputPath(cwd, output, `${data.id}-gsa.json`);\n yield* writeText(filePath, data.json);\n return {\n path: filePath,\n pairs: [\n [\"Path\", filePath],\n [\"Type\", \"Google service account key (.json)\"],\n [\"Client email\", data.clientEmail],\n ] as const,\n metadata: {\n clientEmail: data.clientEmail,\n },\n } satisfies DownloadResult;\n });\n\nconst dispatchDownload = (\n api: ApiClient,\n type: DownloadType,\n id: string,\n cwd: string,\n output: string | undefined,\n) => {\n switch (type) {\n case \"distribution-certificate\": {\n return downloadDistributionCertificate(api, id, cwd, output);\n }\n case \"provisioning-profile\": {\n return downloadProvisioningProfile(api, id, cwd, output);\n }\n case \"push-key\": {\n return downloadPushKey(api, id, cwd, output);\n }\n case \"asc-api-key\": {\n return downloadAscApiKey(api, id, cwd, output);\n }\n case \"keystore\": {\n return downloadKeystore(api, id, cwd, output);\n }\n case \"google-service-account-key\": {\n return downloadGoogleServiceAccountKey(api, id, cwd, output);\n }\n default: {\n return Effect.fail(\n new CredentialValidationError({\n message: `Unsupported credential type: ${String(type)}`,\n }),\n );\n }\n }\n};\n\nexport const downloadCommand = defineCommand({\n meta: {\n name: \"download\",\n description:\n \"Download a single credential file (keystore/.p12/.mobileprovision/.p8/.json) for local use\",\n },\n args: {\n id: { type: \"positional\", required: true, description: \"Credential ID\" },\n type: {\n type: \"enum\",\n options: [...DOWNLOAD_TYPES],\n required: true,\n description: \"Credential type\",\n },\n output: {\n type: \"string\",\n description: \"Output path (default: ./<id>.<ext> derived from credential type)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const cwd = yield* runtime.cwd;\n const result = yield* dispatchDownload(api, args.type, args.id, cwd, args.output);\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson({ path: result.path, ...result.metadata });\n return undefined;\n }\n yield* printKeyValue(result.pairs.map((pair) => [pair[0], pair[1]] as const));\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport {\n CertificateLimitError,\n generateAndUploadDistributionCertificate,\n generateAndUploadKeystore,\n generateAndUploadProvisioningProfile,\n listAppleCertificates,\n revokeAppleCertificate,\n} from \"../../lib/credentials-generator\";\nimport { uploadCredential } from \"../../lib/credentials-manager\";\nimport { CredentialValidationError } from \"../../lib/exit-codes\";\nimport { printHuman, printKeyValue } from \"../../lib/output\";\nimport { promptMultiSelect, promptPassword, promptText } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst GENERATE_EXIT_EXTRAS = {\n CredentialValidationError: 2,\n BuildFailedError: 6,\n GenerateFailedError: 6,\n CertificateLimitError: 6,\n} as const;\n\nconst ensureNonEmpty = (value: string | undefined, label: string) =>\n value === undefined || value.trim().length === 0\n ? Effect.fail(new CredentialValidationError({ message: `Missing --${label}` }))\n : Effect.succeed(value);\n\ninterface KeystoreCliArgs {\n readonly alias?: string | undefined;\n readonly \"store-password\"?: string | undefined;\n readonly \"key-password\"?: string | undefined;\n readonly \"common-name\"?: string | undefined;\n readonly organization?: string | undefined;\n readonly \"validity-days\"?: string | undefined;\n}\n\nconst parseValidityDays = (raw: string | undefined) => {\n if (raw === undefined || raw.length === 0) {\n return Effect.succeed(undefined);\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n return Effect.fail(\n new CredentialValidationError({ message: \"--validity-days must be a positive integer\" }),\n );\n }\n return Effect.succeed(parsed);\n};\n\nconst resolveKeystoreInput = (args: KeystoreCliArgs) =>\n Effect.gen(function* () {\n const alias =\n args.alias !== undefined && args.alias.trim().length > 0\n ? args.alias\n : yield* promptText(\"Key alias\", { placeholder: \"upload-key\" });\n const storePassword =\n args[\"store-password\"] !== undefined && args[\"store-password\"].length > 0\n ? args[\"store-password\"]\n : yield* promptPassword(\"Keystore password\");\n const keyPassword =\n args[\"key-password\"] !== undefined && args[\"key-password\"].length > 0\n ? args[\"key-password\"]\n : yield* promptPassword(\"Key password\");\n const commonName =\n args[\"common-name\"] !== undefined && args[\"common-name\"].trim().length > 0\n ? args[\"common-name\"]\n : yield* promptText(\"Common name (CN)\", { placeholder: \"Your App\" });\n const organization =\n args.organization !== undefined && args.organization.trim().length > 0\n ? args.organization\n : yield* promptText(\"Organization (O)\", { placeholder: \"Your Company\" });\n const validityDays = yield* parseValidityDays(args[\"validity-days\"]);\n return {\n alias: yield* ensureNonEmpty(alias, \"alias\"),\n storePassword: yield* ensureNonEmpty(storePassword, \"store-password\"),\n keyPassword: yield* ensureNonEmpty(keyPassword, \"key-password\"),\n commonName: yield* ensureNonEmpty(commonName, \"common-name\"),\n organization: yield* ensureNonEmpty(organization, \"organization\"),\n ...(validityDays === undefined ? {} : { validityDays }),\n };\n });\n\nconst keystoreCommand = defineCommand({\n meta: {\n name: \"keystore\",\n description: \"Generate a new Android upload keystore via keytool and store it server-side\",\n },\n args: {\n alias: { type: \"string\", description: \"Key alias\" },\n \"store-password\": { type: \"string\", description: \"Keystore password\" },\n \"key-password\": { type: \"string\", description: \"Key password\" },\n \"common-name\": { type: \"string\", description: \"Certificate CN\" },\n organization: { type: \"string\", description: \"Certificate O\" },\n \"validity-days\": {\n type: \"string\",\n description: \"Certificate validity in days (default 10000)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const resolved = yield* resolveKeystoreInput(args);\n yield* Console.log(\"Generating keystore with keytool...\");\n const created = yield* generateAndUploadKeystore(api, {\n keyAlias: resolved.alias,\n storePassword: resolved.storePassword,\n keyPassword: resolved.keyPassword,\n commonName: resolved.commonName,\n organization: resolved.organization,\n ...(resolved.validityDays === undefined ? {} : { validityDays: resolved.validityDays }),\n });\n yield* Console.log(\"\");\n yield* Console.log(\"Keystore generated and uploaded.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Alias\", created.keyAlias],\n ]);\n }),\n GENERATE_EXIT_EXTRAS,\n ),\n});\n\nconst distributionCertificateCommand = defineCommand({\n meta: {\n name: \"distribution-certificate\",\n description:\n \"Generate an iOS distribution certificate via the App Store Connect API and store the resulting .p12\",\n },\n args: {\n \"asc-key-id\": {\n type: \"string\",\n required: true,\n description: \"ASC API key ID (from `credentials list`)\",\n },\n type: {\n type: \"enum\",\n options: [\"distribution\", \"development\"],\n default: \"distribution\",\n description: \"Certificate type to issue\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const certificateType =\n args.type === \"development\" ? \"IOS_DEVELOPMENT\" : \"IOS_DISTRIBUTION\";\n yield* Console.log(\"Generating CSR and requesting certificate from Apple...\");\n\n const attempt = generateAndUploadDistributionCertificate(api, {\n ascApiKeyId: args[\"asc-key-id\"],\n certificateType,\n });\n\n const created = yield* attempt.pipe(\n Effect.catchTag(\"CertificateLimitError\", () =>\n handleCertLimitInteractive(api, args[\"asc-key-id\"], certificateType).pipe(\n Effect.flatMap(() => attempt),\n ),\n ),\n );\n\n yield* Console.log(\"Distribution certificate generated and stored.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Serial\", created.serialNumber],\n [\"Apple team\", created.appleTeamId],\n [\"Apple cert\", created.developerPortalIdentifier],\n ]);\n }),\n GENERATE_EXIT_EXTRAS,\n ),\n});\n\nconst handleCertLimitInteractive = (\n api: ApiClient,\n ascApiKeyId: string,\n certificateType: \"IOS_DISTRIBUTION\" | \"IOS_DEVELOPMENT\",\n) =>\n Effect.gen(function* () {\n yield* Console.log(\"\");\n yield* Console.log(\"Apple reports the certificate limit was hit (max 3 distribution certs).\");\n const certs = yield* listAppleCertificates(api, { ascApiKeyId, certificateType });\n if (certs.length === 0) {\n return yield* Effect.fail(\n new CertificateLimitError({\n message:\n \"Apple says the certificate limit is hit but no existing certificates were returned — try again later.\",\n }),\n );\n }\n const toRevoke = yield* promptMultiSelect<string>(\n \"Select one or more certificates to revoke before retrying\",\n certs.map((entry) => ({\n value: entry.id,\n label: `${entry.serialNumber.slice(0, 12)}… (${entry.displayName ?? entry.certificateType}, exp ${entry.expirationDate.slice(0, 10)})`,\n })),\n { required: true },\n );\n yield* Effect.forEach(\n toRevoke,\n (id) => revokeAppleCertificate(api, { ascApiKeyId, developerPortalIdentifier: id }),\n { concurrency: \"inherit\" },\n );\n yield* Console.log(`Revoked ${toRevoke.length} certificate(s); retrying generation...`);\n return undefined;\n });\n\nconst provisioningProfileCommand = defineCommand({\n meta: {\n name: \"provisioning-profile\",\n description:\n \"Generate an iOS provisioning profile via the App Store Connect API and store the resulting .mobileprovision\",\n },\n args: {\n \"asc-key-id\": {\n type: \"string\",\n required: true,\n description: \"ASC API key ID (from `credentials list`)\",\n },\n \"cert-id\": {\n type: \"string\",\n required: true,\n description: \"Distribution certificate ID (from `credentials list`)\",\n },\n bundle: { type: \"string\", required: true, description: \"Bundle identifier\" },\n distribution: {\n type: \"enum\",\n options: [\"APP_STORE\", \"AD_HOC\", \"DEVELOPMENT\", \"ENTERPRISE\"],\n required: true,\n description: \"Distribution type\",\n },\n \"device-ids\": {\n type: \"string\",\n description: \"Comma-separated better-update device IDs (required for AD_HOC/DEVELOPMENT)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const deviceIds = parseDeviceIds(args[\"device-ids\"]);\n const created = yield* generateAndUploadProvisioningProfile(api, {\n ascApiKeyId: args[\"asc-key-id\"],\n distributionCertificateId: args[\"cert-id\"],\n bundleIdentifier: args.bundle,\n distributionType: args.distribution,\n ...(deviceIds === undefined ? {} : { deviceIds }),\n });\n yield* Console.log(\"Provisioning profile generated and stored.\");\n yield* printKeyValue([\n [\"ID\", created.id],\n [\"Bundle\", created.bundleIdentifier],\n [\"Distribution\", created.distributionType],\n [\"Profile name\", created.profileName ?? \"-\"],\n [\"Valid until\", created.validUntil ?? \"-\"],\n [\"Apple profile\", created.developerPortalIdentifier ?? \"-\"],\n ]);\n }),\n GENERATE_EXIT_EXTRAS,\n ),\n});\n\nconst parseDeviceIds = (raw: string | undefined): readonly string[] | undefined => {\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const ids = raw\n .split(\",\")\n .map((id) => id.trim())\n .filter((id) => id.length > 0);\n return ids.length === 0 ? undefined : ids;\n};\n\nconst APPLE_PUSH_KEY_PORTAL_URL = \"https://developer.apple.com/account/resources/authkeys/list\";\nconst KEY_ID_PATTERN = /^[A-Z0-9]{10}$/u;\nconst APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u;\n\nconst resolveAppleTeamFromAscKey = (api: ApiClient, ascApiKeyId: string | undefined) =>\n Effect.gen(function* () {\n if (ascApiKeyId === undefined) {\n return undefined;\n }\n const ascKeys = yield* api.ascApiKeys.list();\n const match = ascKeys.items.find((entry) => entry.id === ascApiKeyId);\n const teamId = match?.appleTeamId;\n return typeof teamId === \"string\" ? teamId : undefined;\n });\n\ninterface PushKeyArgs {\n readonly \"key-id\"?: string | undefined;\n readonly \"apple-team-id\"?: string | undefined;\n readonly p8?: string | undefined;\n readonly \"asc-key-id\"?: string | undefined;\n readonly name?: string | undefined;\n readonly \"skip-portal-hint\"?: boolean | undefined;\n}\n\nconst validateKeyId = (value: string) =>\n KEY_ID_PATTERN.test(value)\n ? Effect.succeed(value)\n : Effect.fail(\n new CredentialValidationError({\n message: `Push key ID \"${value}\" must be 10 uppercase alphanumeric characters.`,\n }),\n );\n\nconst validateAppleTeamId = (value: string) =>\n APPLE_TEAM_ID_PATTERN.test(value)\n ? Effect.succeed(value)\n : Effect.fail(\n new CredentialValidationError({\n message: `Apple Team ID \"${value}\" must be 10 uppercase alphanumeric characters.`,\n }),\n );\n\nconst pushKeyCommand = defineCommand({\n meta: {\n name: \"push-key\",\n description:\n \"Register an APNs auth key (.p8) — guides you through creating one in the Apple Developer portal, then uploads it\",\n },\n args: {\n \"key-id\": { type: \"string\", description: \"APNs key ID (10 uppercase alphanumeric)\" },\n \"apple-team-id\": { type: \"string\", description: \"Apple Team identifier\" },\n p8: { type: \"string\", description: \"Path to the AuthKey_XXXXXXXXXX.p8 file\" },\n \"asc-key-id\": {\n type: \"string\",\n description: \"ASC API key ID to derive --apple-team-id automatically\",\n },\n name: { type: \"string\", description: \"Display name (defaults to the key ID)\" },\n \"skip-portal-hint\": {\n type: \"boolean\",\n description: \"Skip the Apple Developer portal URL hint (already created the key)\",\n },\n },\n run: async ({ args }: { readonly args: PushKeyArgs }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n\n if (args[\"skip-portal-hint\"] !== true) {\n yield* printHuman(\"Apple does not expose APNs key creation via the public ASC API.\");\n yield* printHuman(\"Create the key here, download the .p8, then come back:\");\n yield* printHuman(` ${APPLE_PUSH_KEY_PORTAL_URL}`);\n yield* printHuman(\"\");\n }\n\n const resolved = yield* resolvePushKeyInput(api, args);\n yield* Console.log(\"Uploading APNs auth key...\");\n const credential = yield* uploadCredential(api, {\n platform: \"ios\",\n type: \"push-key\",\n name: resolved.name,\n filePath: resolved.p8Path,\n keyId: resolved.keyId,\n appleTeamIdentifier: resolved.appleTeamIdentifier,\n });\n yield* Console.log(\"APNs push key registered.\");\n yield* printKeyValue([\n [\"ID\", credential.id],\n [\"Key ID\", resolved.keyId],\n [\"Apple team\", resolved.appleTeamIdentifier],\n ]);\n return undefined;\n }),\n GENERATE_EXIT_EXTRAS,\n ),\n});\n\nconst resolvePushKeyInput = (api: ApiClient, args: PushKeyArgs) =>\n Effect.gen(function* () {\n const derivedTeamId = yield* resolveAppleTeamFromAscKey(api, args[\"asc-key-id\"]);\n\n const rawKeyId =\n args[\"key-id\"] ?? (yield* promptText(\"APNs key ID (10 uppercase alphanumeric)\"));\n const keyId = yield* validateKeyId(rawKeyId.trim().toUpperCase());\n\n const rawTeamId =\n args[\"apple-team-id\"] ??\n derivedTeamId ??\n (yield* promptText(\"Apple Team identifier (10 uppercase alphanumeric)\"));\n const appleTeamIdentifier = yield* validateAppleTeamId(rawTeamId.trim().toUpperCase());\n\n const p8Path =\n args.p8 ?? (yield* promptText(\"Path to the AuthKey_XXXXXXXXXX.p8 file you downloaded\"));\n if (p8Path.trim().length === 0) {\n return yield* new CredentialValidationError({ message: \"Missing --p8 path\" });\n }\n\n const name = args.name ?? keyId;\n return { keyId, appleTeamIdentifier, p8Path, name };\n });\n\nconst GSA_FIREBASE_URL =\n \"https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk\";\nconst GSA_GCP_URL = \"https://console.cloud.google.com/iam-admin/serviceaccounts\";\n\ninterface GsaKeyArgs {\n readonly file?: string | undefined;\n readonly name?: string | undefined;\n readonly purpose?: \"fcm\" | \"play\" | undefined;\n readonly \"skip-portal-hint\"?: boolean | undefined;\n}\n\nconst gsaKeyCommand = defineCommand({\n meta: {\n name: \"gsa-key\",\n description:\n \"Register a Google Service Account JSON key — guides you through creating one in the Firebase/GCP console, then uploads it\",\n },\n args: {\n file: { type: \"string\", description: \"Path to the Google service account JSON file\" },\n name: { type: \"string\", description: \"Display name (defaults to the file name)\" },\n purpose: {\n type: \"enum\",\n options: [\"fcm\", \"play\"],\n description:\n \"Where this key will be used: fcm (Firebase Cloud Messaging V1) or play (Play Store submissions)\",\n },\n \"skip-portal-hint\": {\n type: \"boolean\",\n description: \"Skip the Firebase/GCP portal URL hint (already downloaded the key)\",\n },\n },\n run: async ({ args }: { readonly args: GsaKeyArgs }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n\n if (args[\"skip-portal-hint\"] !== true) {\n yield* printHuman(\n \"Google does not expose service-account key creation via a public API.\",\n );\n yield* printHuman(\n \"Create one in the appropriate console, download the JSON, then come back:\",\n );\n if (args.purpose === \"play\") {\n yield* printHuman(` Play submissions (GCP IAM): ${GSA_GCP_URL}`);\n } else if (args.purpose === \"fcm\") {\n yield* printHuman(` FCM V1 push (Firebase console): ${GSA_FIREBASE_URL}`);\n } else {\n yield* printHuman(` FCM V1 push (Firebase): ${GSA_FIREBASE_URL}`);\n yield* printHuman(` Play submissions (GCP IAM): ${GSA_GCP_URL}`);\n }\n yield* printHuman(\"\");\n }\n\n const filePath =\n args.file !== undefined && args.file.trim().length > 0\n ? args.file\n : yield* promptText(\"Path to the Google service account JSON file\");\n if (filePath.trim().length === 0) {\n return yield* new CredentialValidationError({ message: \"Missing --file path\" });\n }\n const name = args.name ?? filePath;\n\n yield* Console.log(\"Uploading Google service account key...\");\n const credential = yield* uploadCredential(api, {\n platform: \"android\",\n type: \"google-service-account-key\",\n name,\n filePath,\n });\n yield* Console.log(\"Google service account key registered.\");\n yield* printKeyValue([\n [\"ID\", credential.id],\n [\"Name\", credential.name],\n ]);\n return undefined;\n }),\n GENERATE_EXIT_EXTRAS,\n ),\n});\n\nexport const generateCommand = defineCommand({\n meta: { name: \"generate\", description: \"Generate signing credentials\" },\n subCommands: {\n keystore: keystoreCommand,\n \"distribution-certificate\": distributionCertificateCommand,\n \"provisioning-profile\": provisioningProfileCommand,\n \"push-key\": pushKeyCommand,\n \"gsa-key\": gsaKeyCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { filterCredentials, listAllCredentials } from \"../../lib/credentials-manager\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List credentials across platforms\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], description: \"Filter by platform\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const rows = yield* listAllCredentials(api);\n\n const filtered = filterCredentials(rows, args.platform ? { platform: args.platform } : {});\n\n yield* printList(\n [\"ID\", \"Name\", \"Platform\", \"Type\", \"Distribution\"],\n filtered.map((row) => [\n row.id,\n row.name,\n row.platform,\n row.type,\n row.distribution ?? \"-\",\n ]),\n \"No credentials found.\",\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { regenerateProvisioningProfile } from \"../../application/credentials-interactive\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { CredentialValidationError, MissingCredentialsError } from \"../../lib/exit-codes\";\nimport { extractProjectId, readAppMeta, readExpoConfig } from \"../../lib/expo-config\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nimport type { IosDistribution } from \"../../lib/build-profile\";\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst REGENERATE_EXIT_EXTRAS = {\n CredentialValidationError: 2,\n MissingCredentialsError: 5,\n} as const;\n\nconst distributionTypeToDistribution = (value: string): IosDistribution => {\n switch (value) {\n case \"AD_HOC\": {\n return \"ad-hoc\";\n }\n case \"DEVELOPMENT\": {\n return \"development\";\n }\n case \"ENTERPRISE\": {\n return \"enterprise\";\n }\n default: {\n return \"app-store\";\n }\n }\n};\n\nconst regenerateOne = (\n api: ApiClient,\n projectId: string,\n bundleIdentifier: string,\n distribution: IosDistribution,\n) =>\n Effect.gen(function* () {\n const created = yield* regenerateProvisioningProfile(api, {\n projectId,\n bundleIdentifier,\n distribution,\n });\n yield* printKeyValue([\n [\"Bundle\", bundleIdentifier],\n [\"Distribution\", distribution],\n [\"Profile ID\", created.id],\n [\"Profile name\", created.profileName ?? \"-\"],\n [\"Valid until\", created.validUntil ?? \"-\"],\n ]);\n });\n\nconst regenerateAllForProject = (api: ApiClient, projectId: string) =>\n Effect.gen(function* () {\n const configs = yield* api.iosBundleConfigurations.list({ path: { projectId } });\n if (configs.items.length === 0) {\n return yield* new MissingCredentialsError({\n message: \"No iOS bundle configurations found for this project.\",\n hint: \"Run `better-update credentials configure --platform ios` to create one first.\",\n });\n }\n yield* Console.log(\n `Regenerating ${String(configs.items.length)} provisioning profile(s) for this project...`,\n );\n for (const config of configs.items) {\n const distribution = distributionTypeToDistribution(config.distributionType);\n yield* Console.log(\"\");\n yield* regenerateOne(api, projectId, config.bundleIdentifier, distribution);\n }\n return undefined;\n });\n\nexport const regenerateProfileCommand = defineCommand({\n meta: {\n name: \"regenerate-profile\",\n description:\n \"Re-issue an iOS provisioning profile via the App Store Connect API (after device roster changes or expiry)\",\n },\n args: {\n bundle: { type: \"string\", description: \"iOS bundle identifier (defaults to app.json)\" },\n distribution: {\n type: \"enum\",\n options: [\"ad-hoc\", \"app-store\", \"development\", \"enterprise\"],\n default: \"ad-hoc\",\n description: \"Distribution type of the bundle configuration\",\n },\n all: {\n type: \"boolean\",\n description: \"Regenerate profiles for every iOS bundle configuration on this project\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const expo = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(expo);\n\n if (args.all === true) {\n yield* regenerateAllForProject(api, projectId);\n return undefined;\n }\n\n const iosMeta = yield* readAppMeta(expo, \"ios\");\n const bundleIdentifier = args.bundle ?? iosMeta.bundleId;\n if (bundleIdentifier === undefined || bundleIdentifier.length === 0) {\n return yield* new CredentialValidationError({\n message: \"Missing --bundle and could not read ios.bundleIdentifier from app.json.\",\n });\n }\n\n yield* regenerateOne(api, projectId, bundleIdentifier, args.distribution);\n return undefined;\n }),\n REGENERATE_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport {\n deleteCredential,\n filterCredentials,\n listAllCredentials,\n} from \"../../lib/credentials-manager\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { promptConfirm, promptSelect } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type {\n CliCredentialPlatform,\n CliCredentialRow,\n CliCredentialType,\n} from \"../../lib/credentials-manager\";\n\nconst CREDENTIAL_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\nconst isPlatform = (value: string): value is CliCredentialPlatform =>\n value === \"ios\" || value === \"android\";\n\nconst isType = (value: string): value is CliCredentialType =>\n (CREDENTIAL_TYPES as readonly string[]).includes(value);\n\nconst formatRowLabel = (row: CliCredentialRow): string => {\n const distro = row.distribution ? ` (${row.distribution})` : \"\";\n return `${row.type}: ${row.name}${distro} — ${row.id.slice(0, 8)}…`;\n};\n\nexport const removeCommand = defineCommand({\n meta: {\n name: \"remove\",\n description: \"Interactively pick a credential to delete (uses prompts to narrow the choice)\",\n },\n args: {\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\"],\n description: \"Pre-filter by platform\",\n },\n type: {\n type: \"enum\",\n options: [...CREDENTIAL_TYPES],\n description: \"Pre-filter by credential type\",\n },\n yes: {\n type: \"boolean\",\n description: \"Skip the final confirmation prompt\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const rows = yield* listAllCredentials(api);\n\n const platform = yield* resolvePlatform(args.platform);\n const platformRows = filterCredentials(rows, { platform });\n if (platformRows.length === 0) {\n yield* Console.log(`No ${platform} credentials to remove.`);\n return undefined;\n }\n\n const availableTypes = [...new Set(platformRows.map((row) => row.type))];\n const type = yield* resolveType(args.type, availableTypes);\n const filtered = filterCredentials(platformRows, { type });\n if (filtered.length === 0) {\n yield* Console.log(`No ${platform} ${type} credentials to remove.`);\n return undefined;\n }\n\n const id = yield* promptSelect<string>(\n `Select a ${type} to remove`,\n filtered.map((row) => ({ value: row.id, label: formatRowLabel(row) })),\n );\n\n if (!args.yes) {\n const confirmed = yield* promptConfirm(\n `Delete ${type} ${id.slice(0, 8)}…? This cannot be undone.`,\n { initialValue: false },\n );\n if (!confirmed) {\n yield* Console.log(\"Aborted.\");\n return undefined;\n }\n }\n\n yield* deleteCredential(api, { id, platform, type });\n yield* Console.log(`Credential ${id} deleted.`);\n return undefined;\n }),\n ),\n});\n\nconst resolvePlatform = (raw: string | undefined) =>\n Effect.gen(function* () {\n if (raw === undefined) {\n return yield* promptSelect<CliCredentialPlatform>(\"Filter by platform\", [\n { value: \"ios\", label: \"iOS\" },\n { value: \"android\", label: \"Android\" },\n ]);\n }\n if (!isPlatform(raw)) {\n return yield* new InvalidArgumentError({ message: `Invalid platform \"${raw}\"` });\n }\n return raw;\n });\n\nconst resolveType = (raw: string | undefined, available: readonly CliCredentialType[]) =>\n Effect.gen(function* () {\n if (raw === undefined) {\n return yield* promptSelect<CliCredentialType>(\n \"Filter by type\",\n available.map((entry) => ({ value: entry, label: entry })),\n );\n }\n if (!isType(raw)) {\n return yield* new InvalidArgumentError({ message: `Invalid type \"${raw}\"` });\n }\n return raw;\n });\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { revokeLocalDistributionCertificate } from \"../../lib/credentials-generator\";\nimport { CredentialValidationError } from \"../../lib/exit-codes\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { promptSelect } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst REVOKE_EXIT_EXTRAS = {\n CredentialValidationError: 2,\n GenerateFailedError: 6,\n} as const;\n\nconst resolveAscKeyId = (api: ApiClient, raw: string | undefined) =>\n Effect.gen(function* () {\n if (raw !== undefined && raw.length > 0) {\n return raw;\n }\n const keys = yield* api.ascApiKeys.list();\n if (keys.items.length === 0) {\n return yield* new CredentialValidationError({\n message: \"No ASC API keys available. Upload one with `credentials upload-asc-key` first.\",\n });\n }\n if (keys.items.length === 1) {\n const [only] = keys.items;\n if (only !== undefined) {\n return only.id;\n }\n }\n return yield* promptSelect<string>(\n \"Select an ASC API key to revoke with\",\n keys.items.map((key) => ({ value: key.id, label: `${key.name} (${key.keyId})` })),\n );\n });\n\nconst distributionCertificateCommand = defineCommand({\n meta: {\n name: \"distribution-certificate\",\n description:\n \"Revoke an iOS distribution certificate on the Apple Developer Portal and delete it from this account\",\n },\n args: {\n id: { type: \"string\", required: true, description: \"Local distribution certificate ID\" },\n \"asc-key-id\": {\n type: \"string\",\n description: \"ASC API key ID (prompts if omitted and multiple keys exist)\",\n },\n \"keep-local\": {\n type: \"boolean\",\n description: \"Revoke on Apple but keep the credential in this account\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const ascApiKeyId = yield* resolveAscKeyId(api, args[\"asc-key-id\"]);\n const result = yield* revokeLocalDistributionCertificate(api, {\n ascApiKeyId,\n distributionCertificateId: args.id,\n keepLocal: args[\"keep-local\"] ?? false,\n });\n yield* Console.log(\"Distribution certificate revoke complete.\");\n yield* printKeyValue([\n [\"Local ID\", result.localId],\n [\"Serial\", result.serialNumber],\n [\"Revoked on Apple\", result.revokedOnApple ? \"yes\" : \"no (not present on portal)\"],\n [\"Deleted locally\", result.deletedLocally ? \"yes\" : \"no (--keep-local)\"],\n ]);\n }),\n REVOKE_EXIT_EXTRAS,\n ),\n});\n\nexport const revokeCommand = defineCommand({\n meta: { name: \"revoke\", description: \"Revoke credentials on the upstream provider\" },\n subCommands: {\n \"distribution-certificate\": distributionCertificateCommand,\n },\n});\n","import path from \"node:path\";\n\nimport { Effect } from \"effect\";\n\nimport type { FileSystem } from \"@effect/platform\";\n\nimport { CredentialsJsonError } from \"../../../lib/exit-codes\";\n\nimport type { CredentialsJson } from \"../../../lib/credentials-json\";\n\nexport const SYNC_EXIT_EXTRAS = {\n CredentialsJsonError: 5,\n CredentialValidationError: 5,\n} as const;\n\nexport interface SyncRow {\n readonly type: string;\n readonly path: string;\n readonly status: string;\n readonly id: string;\n}\n\nexport interface PullRow {\n readonly type: string;\n readonly path: string;\n readonly id: string;\n}\n\nexport const writeArtifact = (\n fs: FileSystem.FileSystem,\n projectRoot: string,\n relPath: string,\n bytes: Uint8Array,\n): Effect.Effect<string, CredentialsJsonError> =>\n Effect.gen(function* () {\n const abs = path.join(projectRoot, relPath);\n const dir = path.dirname(abs);\n yield* fs\n .makeDirectory(dir, { recursive: true })\n .pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({ message: `Failed to create ${dir}: ${String(cause)}` }),\n ),\n );\n yield* fs\n .writeFile(abs, bytes)\n .pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({ message: `Failed to write ${abs}: ${String(cause)}` }),\n ),\n );\n return relPath;\n });\n\nexport const writeText = (\n fs: FileSystem.FileSystem,\n projectRoot: string,\n relPath: string,\n text: string,\n) => writeArtifact(fs, projectRoot, relPath, new TextEncoder().encode(text));\n\nexport const ensureGitignoreEntries = (\n fs: FileSystem.FileSystem,\n projectRoot: string,\n paths: readonly string[],\n): Effect.Effect<readonly string[], CredentialsJsonError> =>\n Effect.gen(function* () {\n const filePath = path.join(projectRoot, \".gitignore\");\n const exists = yield* fs.exists(filePath).pipe(Effect.catchAll(() => Effect.succeed(false)));\n const previous = exists\n ? yield* fs.readFileString(filePath).pipe(Effect.catchAll(() => Effect.succeed(\"\")))\n : \"\";\n const lines = previous.split(\"\\n\");\n const added: string[] = [];\n const next = [...lines];\n for (const entry of paths) {\n if (!lines.includes(entry)) {\n next.push(entry);\n added.push(entry);\n }\n }\n if (added.length === 0) {\n return [];\n }\n const body = next.join(\"\\n\").trimEnd();\n yield* fs.writeFileString(filePath, `${body}\\n`).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to update .gitignore: ${String(cause)}`,\n }),\n ),\n );\n return added;\n });\n\ninterface CredentialMeta {\n readonly id: string;\n readonly label: string;\n}\n\ninterface IosBuildInput {\n readonly first: CredentialMeta | undefined;\n readonly profileFirst: CredentialMeta | undefined;\n readonly pushFirst: CredentialMeta | undefined;\n readonly ascFirst: CredentialMeta | undefined;\n readonly storage: Map<\n string,\n { readonly relPath: string; readonly extras?: Record<string, string> }\n >;\n}\n\nexport const buildIosFromMeta = (\n params: IosBuildInput,\n): NonNullable<CredentialsJson[\"ios\"]> | undefined => {\n if (!params.first || !params.profileFirst) {\n return undefined;\n }\n const cert = params.storage.get(params.first.id);\n const profile = params.storage.get(params.profileFirst.id);\n if (!cert || !profile || !cert.extras?.[\"password\"]) {\n return undefined;\n }\n const result: NonNullable<CredentialsJson[\"ios\"]> = {\n provisioningProfilePath: profile.relPath,\n distributionCertificate: {\n path: cert.relPath,\n password: cert.extras[\"password\"],\n },\n };\n if (params.pushFirst) {\n const push = params.storage.get(params.pushFirst.id);\n if (push?.extras?.[\"keyId\"] && push.extras[\"teamId\"]) {\n return {\n ...result,\n pushKey: {\n path: push.relPath,\n keyId: push.extras[\"keyId\"],\n teamId: push.extras[\"teamId\"],\n },\n };\n }\n }\n if (params.ascFirst) {\n const asc = params.storage.get(params.ascFirst.id);\n if (asc?.extras?.[\"keyId\"] && asc.extras[\"issuerId\"]) {\n return {\n ...result,\n ascApiKey: {\n path: asc.relPath,\n keyId: asc.extras[\"keyId\"],\n issuerId: asc.extras[\"issuerId\"],\n },\n };\n }\n }\n return result;\n};\n","import path from \"node:path\";\n\nimport { fromBase64 } from \"@better-update/encoding\";\nimport { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { writeCredentialsJson } from \"../../../lib/credentials-json\";\nimport { CredentialsJsonError } from \"../../../lib/exit-codes\";\nimport { formatCause } from \"../../../lib/format-error\";\nimport { printHuman, printTable } from \"../../../lib/output\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { CliRuntime } from \"../../../services/cli-runtime\";\nimport {\n buildIosFromMeta,\n ensureGitignoreEntries,\n SYNC_EXIT_EXTRAS,\n writeArtifact,\n writeText,\n} from \"./helpers\";\n\nimport type { CredentialsJson } from \"../../../lib/credentials-json\";\nimport type { ApiClient } from \"../../../services/api-client\";\nimport type { PullRow } from \"./helpers\";\n\ninterface IosListItems {\n readonly certFirst: { readonly id: string; readonly serialNumber: string } | undefined;\n readonly profileFirst: { readonly id: string; readonly bundleIdentifier: string } | undefined;\n readonly pushFirst: { readonly id: string; readonly keyId: string } | undefined;\n readonly ascFirst: { readonly id: string; readonly name: string } | undefined;\n}\n\nconst fetchIosListing = (api: ApiClient): Effect.Effect<IosListItems, CredentialsJsonError> =>\n Effect.gen(function* () {\n const [certs, profiles, pushKeys, ascKeys] = yield* Effect.all(\n [\n api.appleDistributionCertificates.list(),\n api.appleProvisioningProfiles.list({ urlParams: {} }),\n api.applePushKeys.list(),\n api.ascApiKeys.list(),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to list iOS credentials: ${formatCause(cause)}`,\n }),\n ),\n );\n return {\n certFirst: certs.items.at(0),\n profileFirst: profiles.items.at(0),\n pushFirst: pushKeys.items.at(0),\n ascFirst: ascKeys.items.at(0),\n };\n });\n\nconst downloadIosDistCert = (\n api: ApiClient,\n fs: FileSystem.FileSystem,\n projectRoot: string,\n keysDir: string,\n id: string,\n) =>\n Effect.gen(function* () {\n const data = yield* api.appleDistributionCertificates.download({ path: { id } }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to download distribution certificate: ${formatCause(cause)}`,\n }),\n ),\n );\n const rel = path.join(keysDir, `${data.id}.p12`);\n yield* writeArtifact(fs, projectRoot, rel, fromBase64(data.p12Base64));\n return { rel, password: data.p12Password, id: data.id };\n });\n\nconst downloadProvisioningProfile = (\n api: ApiClient,\n fs: FileSystem.FileSystem,\n projectRoot: string,\n keysDir: string,\n id: string,\n) =>\n Effect.gen(function* () {\n const data = yield* api.appleProvisioningProfiles.download({ path: { id } }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to download provisioning profile: ${formatCause(cause)}`,\n }),\n ),\n );\n const rel = path.join(keysDir, `${data.id}.mobileprovision`);\n yield* writeArtifact(fs, projectRoot, rel, fromBase64(data.profileBase64));\n return { rel, id: data.id };\n });\n\nconst downloadIosPushKey = (\n api: ApiClient,\n fs: FileSystem.FileSystem,\n projectRoot: string,\n keysDir: string,\n id: string,\n) =>\n Effect.gen(function* () {\n const data = yield* api.applePushKeys.download({ path: { id } }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to download push key: ${formatCause(cause)}`,\n }),\n ),\n );\n const rel = path.join(keysDir, `${data.id}.p8`);\n yield* writeText(fs, projectRoot, rel, data.p8Pem);\n return { rel, keyId: data.keyId, teamId: data.appleTeamIdentifier, id: data.id };\n });\n\nconst downloadAscApiKey = (\n api: ApiClient,\n fs: FileSystem.FileSystem,\n projectRoot: string,\n keysDir: string,\n id: string,\n) =>\n Effect.gen(function* () {\n const data = yield* api.ascApiKeys.getCredentials({ path: { id } }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to download ASC API key: ${formatCause(cause)}`,\n }),\n ),\n );\n const rel = path.join(keysDir, `${data.ascApiKeyId}-asc.p8`);\n yield* writeText(fs, projectRoot, rel, data.p8Pem);\n return { rel, keyId: data.keyId, issuerId: data.issuerId, id: data.ascApiKeyId };\n });\n\nconst pullIos = (\n api: ApiClient,\n fs: FileSystem.FileSystem,\n projectRoot: string,\n keysDir: string,\n): Effect.Effect<\n { readonly entry: CredentialsJson[\"ios\"]; readonly rows: readonly PullRow[] },\n CredentialsJsonError\n> =>\n Effect.gen(function* () {\n const listing = yield* fetchIosListing(api);\n const rows: PullRow[] = [];\n const storage = new Map<\n string,\n { readonly relPath: string; readonly extras?: Record<string, string> }\n >();\n\n if (listing.certFirst) {\n const result = yield* downloadIosDistCert(\n api,\n fs,\n projectRoot,\n keysDir,\n listing.certFirst.id,\n );\n storage.set(listing.certFirst.id, {\n relPath: result.rel,\n extras: { password: result.password },\n });\n rows.push({ type: \"ios:distribution-certificate\", path: result.rel, id: result.id });\n }\n if (listing.profileFirst) {\n const result = yield* downloadProvisioningProfile(\n api,\n fs,\n projectRoot,\n keysDir,\n listing.profileFirst.id,\n );\n storage.set(listing.profileFirst.id, { relPath: result.rel });\n rows.push({ type: \"ios:provisioning-profile\", path: result.rel, id: result.id });\n }\n if (listing.pushFirst) {\n const result = yield* downloadIosPushKey(api, fs, projectRoot, keysDir, listing.pushFirst.id);\n storage.set(listing.pushFirst.id, {\n relPath: result.rel,\n extras: { keyId: result.keyId, teamId: result.teamId },\n });\n rows.push({ type: \"ios:push-key\", path: result.rel, id: result.id });\n }\n if (listing.ascFirst) {\n const result = yield* downloadAscApiKey(api, fs, projectRoot, keysDir, listing.ascFirst.id);\n storage.set(listing.ascFirst.id, {\n relPath: result.rel,\n extras: { keyId: result.keyId, issuerId: result.issuerId },\n });\n rows.push({ type: \"ios:asc-api-key\", path: result.rel, id: result.id });\n }\n\n const entry = buildIosFromMeta({\n first: listing.certFirst\n ? { id: listing.certFirst.id, label: listing.certFirst.serialNumber }\n : undefined,\n profileFirst: listing.profileFirst\n ? { id: listing.profileFirst.id, label: listing.profileFirst.bundleIdentifier }\n : undefined,\n pushFirst: listing.pushFirst\n ? { id: listing.pushFirst.id, label: listing.pushFirst.keyId }\n : undefined,\n ascFirst: listing.ascFirst\n ? { id: listing.ascFirst.id, label: listing.ascFirst.name }\n : undefined,\n storage,\n });\n return { entry, rows };\n });\n\nconst pullAndroid = (\n api: ApiClient,\n fs: FileSystem.FileSystem,\n projectRoot: string,\n keysDir: string,\n): Effect.Effect<\n { readonly entry: CredentialsJson[\"android\"]; readonly rows: readonly PullRow[] },\n CredentialsJsonError\n> =>\n Effect.gen(function* () {\n const [keystores, gsaKeys] = yield* Effect.all(\n [api.androidUploadKeystores.list(), api.googleServiceAccountKeys.list()],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to list Android credentials: ${formatCause(cause)}`,\n }),\n ),\n );\n\n const rows: PullRow[] = [];\n const keystoreFirst = keystores.items.at(0);\n if (!keystoreFirst) {\n return { entry: undefined, rows: [] } as const;\n }\n const keystoreData = yield* api.androidUploadKeystores\n .download({ path: { id: keystoreFirst.id } })\n .pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to download keystore: ${formatCause(cause)}`,\n }),\n ),\n );\n const keystoreRel = path.join(keysDir, `${keystoreData.id}.keystore`);\n yield* writeArtifact(fs, projectRoot, keystoreRel, fromBase64(keystoreData.keystoreBase64));\n rows.push({ type: \"android:keystore\", path: keystoreRel, id: keystoreData.id });\n\n const entry: NonNullable<CredentialsJson[\"android\"]> = {\n keystore: {\n keystorePath: keystoreRel,\n keystorePassword: keystoreData.keystorePassword,\n keyAlias: keystoreData.keyAlias,\n keyPassword: keystoreData.keyPassword,\n },\n };\n\n const gsaFirst = gsaKeys.items.at(0);\n if (gsaFirst) {\n const gsaData = yield* api.googleServiceAccountKeys\n .download({ path: { id: gsaFirst.id } })\n .pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to download Google service account key: ${formatCause(cause)}`,\n }),\n ),\n );\n const rel = path.join(keysDir, `${gsaData.id}-gsa.json`);\n yield* writeText(fs, projectRoot, rel, gsaData.json);\n rows.push({ type: \"android:google-service-account-key\", path: rel, id: gsaData.id });\n return {\n entry: { ...entry, googleServiceAccountKey: { path: rel } },\n rows,\n } as const;\n }\n return { entry, rows } as const;\n });\n\nexport const pullCommand = defineCommand({\n meta: {\n name: \"pull\",\n description: \"Download account credentials into a local credentials.json\",\n },\n args: {\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Limit to a single platform\",\n },\n \"keys-dir\": {\n type: \"string\",\n default: \"credentials\",\n description: \"Directory (relative to project root) for downloaded key files\",\n },\n \"skip-gitignore\": {\n type: \"boolean\",\n description: \"Skip auto-appending credentials.json/keys-dir to .gitignore\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const fs = yield* FileSystem.FileSystem;\n\n const includeIos = args.platform === \"all\" || args.platform === \"ios\";\n const includeAndroid = args.platform === \"all\" || args.platform === \"android\";\n\n const iosResult = includeIos\n ? yield* pullIos(api, fs, projectRoot, args[\"keys-dir\"])\n : { entry: undefined, rows: [] as readonly PullRow[] };\n const androidResult = includeAndroid\n ? yield* pullAndroid(api, fs, projectRoot, args[\"keys-dir\"])\n : { entry: undefined, rows: [] as readonly PullRow[] };\n\n const allRows = [...iosResult.rows, ...androidResult.rows];\n if (allRows.length === 0) {\n yield* Console.log(`No ${args.platform} credentials available to pull.`);\n return;\n }\n\n const next: CredentialsJson = {\n ...(iosResult.entry === undefined ? {} : { ios: iosResult.entry }),\n ...(androidResult.entry === undefined ? {} : { android: androidResult.entry }),\n };\n const outPath = yield* writeCredentialsJson(projectRoot, next);\n\n if (!args[\"skip-gitignore\"]) {\n const added = yield* ensureGitignoreEntries(fs, projectRoot, [\n \"credentials.json\",\n `${args[\"keys-dir\"]}/`,\n ]);\n if (added.length > 0) {\n yield* printHuman(`Added to .gitignore: ${added.join(\", \")}`);\n }\n }\n\n yield* printTable(\n [\"Type\", \"Path\", \"ID\"],\n allRows.map((row) => [row.type, row.path, row.id]),\n );\n yield* Console.log(\"\");\n yield* Console.log(`credentials.json written to ${outPath}`);\n }),\n SYNC_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport type { FileSystem } from \"@effect/platform\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { readCredentialsJson, resolveCredentialPath } from \"../../../lib/credentials-json\";\nimport { uploadCredential } from \"../../../lib/credentials-manager\";\nimport { CredentialsJsonError } from \"../../../lib/exit-codes\";\nimport { formatCause } from \"../../../lib/format-error\";\nimport { printTable } from \"../../../lib/output\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { CliRuntime } from \"../../../services/cli-runtime\";\nimport { SYNC_EXIT_EXTRAS } from \"./helpers\";\n\nimport type { CredentialsJson } from \"../../../lib/credentials-json\";\nimport type { ApiClient } from \"../../../services/api-client\";\nimport type { SyncRow } from \"./helpers\";\n\nconst pushIos = (\n api: ApiClient,\n projectRoot: string,\n ios: NonNullable<CredentialsJson[\"ios\"]>,\n): Effect.Effect<readonly SyncRow[], CredentialsJsonError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const rows: SyncRow[] = [];\n\n const distResult = yield* uploadCredential(api, {\n platform: \"ios\",\n type: \"distribution-certificate\",\n name: \"credentials.json: distribution certificate\",\n filePath: resolveCredentialPath(projectRoot, ios.distributionCertificate.path),\n password: ios.distributionCertificate.password,\n }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to upload iOS distribution certificate: ${formatCause(cause)}`,\n }),\n ),\n );\n rows.push({\n type: \"ios:distribution-certificate\",\n path: ios.distributionCertificate.path,\n status: \"uploaded\",\n id: distResult.id,\n });\n\n const profileResult = yield* uploadCredential(api, {\n platform: \"ios\",\n type: \"provisioning-profile\",\n name: \"credentials.json: provisioning profile\",\n filePath: resolveCredentialPath(projectRoot, ios.provisioningProfilePath),\n }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to upload iOS provisioning profile: ${formatCause(cause)}`,\n }),\n ),\n );\n rows.push({\n type: \"ios:provisioning-profile\",\n path: ios.provisioningProfilePath,\n status: \"uploaded\",\n id: profileResult.id,\n });\n\n if (ios.pushKey) {\n const pushResult = yield* uploadCredential(api, {\n platform: \"ios\",\n type: \"push-key\",\n name: \"credentials.json: push key\",\n filePath: resolveCredentialPath(projectRoot, ios.pushKey.path),\n keyId: ios.pushKey.keyId,\n appleTeamIdentifier: ios.pushKey.teamId,\n }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to upload iOS push key: ${formatCause(cause)}`,\n }),\n ),\n );\n rows.push({\n type: \"ios:push-key\",\n path: ios.pushKey.path,\n status: \"uploaded\",\n id: pushResult.id,\n });\n }\n\n if (ios.ascApiKey) {\n const ascResult = yield* uploadCredential(api, {\n platform: \"ios\",\n type: \"asc-api-key\",\n name: \"credentials.json: asc api key\",\n filePath: resolveCredentialPath(projectRoot, ios.ascApiKey.path),\n keyId: ios.ascApiKey.keyId,\n issuerId: ios.ascApiKey.issuerId,\n }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to upload iOS ASC API key: ${formatCause(cause)}`,\n }),\n ),\n );\n rows.push({\n type: \"ios:asc-api-key\",\n path: ios.ascApiKey.path,\n status: \"uploaded\",\n id: ascResult.id,\n });\n }\n\n return rows;\n });\n\nconst pushAndroid = (\n api: ApiClient,\n projectRoot: string,\n android: NonNullable<CredentialsJson[\"android\"]>,\n): Effect.Effect<readonly SyncRow[], CredentialsJsonError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const rows: SyncRow[] = [];\n\n const keystoreResult = yield* uploadCredential(api, {\n platform: \"android\",\n type: \"keystore\",\n name: \"credentials.json: keystore\",\n filePath: resolveCredentialPath(projectRoot, android.keystore.keystorePath),\n password: android.keystore.keystorePassword,\n keyAlias: android.keystore.keyAlias,\n keyPassword: android.keystore.keyPassword,\n }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to upload Android keystore: ${formatCause(cause)}`,\n }),\n ),\n );\n rows.push({\n type: \"android:keystore\",\n path: android.keystore.keystorePath,\n status: \"uploaded\",\n id: keystoreResult.id,\n });\n\n if (android.googleServiceAccountKey) {\n const gsaResult = yield* uploadCredential(api, {\n platform: \"android\",\n type: \"google-service-account-key\",\n name: \"credentials.json: google service account\",\n filePath: resolveCredentialPath(projectRoot, android.googleServiceAccountKey.path),\n }).pipe(\n Effect.mapError(\n (cause) =>\n new CredentialsJsonError({\n message: `Failed to upload Google Service Account key: ${formatCause(cause)}`,\n }),\n ),\n );\n rows.push({\n type: \"android:google-service-account-key\",\n path: android.googleServiceAccountKey.path,\n status: \"uploaded\",\n id: gsaResult.id,\n });\n }\n\n return rows;\n });\n\nexport const pushCommand = defineCommand({\n meta: {\n name: \"push\",\n description: \"Upload credentials.json contents to the better-update server\",\n },\n args: {\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Limit to a single platform\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const data = yield* readCredentialsJson(projectRoot);\n\n const rows: SyncRow[] = [];\n if ((args.platform === \"all\" || args.platform === \"ios\") && data.ios) {\n rows.push(...(yield* pushIos(api, projectRoot, data.ios)));\n }\n if ((args.platform === \"all\" || args.platform === \"android\") && data.android) {\n rows.push(...(yield* pushAndroid(api, projectRoot, data.android)));\n }\n\n if (rows.length === 0) {\n yield* Console.log(`No ${args.platform} entries found in credentials.json.`);\n return;\n }\n yield* printTable(\n [\"Type\", \"Path\", \"Status\", \"ID\"],\n rows.map((row) => [row.type, row.path, row.status, row.id]),\n );\n }),\n SYNC_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { pullCommand } from \"./pull\";\nimport { pushCommand } from \"./push\";\n\nexport const syncCommand = defineCommand({\n meta: {\n name: \"sync\",\n description: \"Sync credentials between local credentials.json and the server\",\n },\n subCommands: {\n push: pushCommand,\n pull: pullCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { uploadCredential } from \"../../lib/credentials-manager\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { CliCredentialType } from \"../../lib/credentials-manager\";\n\nconst CREDENTIAL_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\nexport const uploadCommand = defineCommand({\n meta: { name: \"upload\", description: \"Upload a credential\" },\n args: {\n platform: { type: \"enum\", options: [\"ios\", \"android\"], required: true },\n type: { type: \"enum\", options: [...CREDENTIAL_TYPES], required: true },\n name: { type: \"string\", required: true, description: \"Display name\" },\n file: { type: \"string\", required: true, description: \"Path to credential file\" },\n password: { type: \"string\", description: \"File password (keystore/p12)\" },\n \"key-alias\": { type: \"string\", description: \"Keystore alias\" },\n \"key-password\": { type: \"string\", description: \"Keystore key password\" },\n \"key-id\": { type: \"string\", description: \"ASC API key ID\" },\n \"issuer-id\": { type: \"string\", description: \"ASC API issuer ID\" },\n \"apple-team-identifier\": { type: \"string\", description: \"Apple Team ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n\n const input: {\n readonly platform: \"ios\" | \"android\";\n readonly type: CliCredentialType;\n readonly name: string;\n readonly filePath: string;\n readonly password?: string;\n readonly keyAlias?: string;\n readonly keyPassword?: string;\n readonly keyId?: string;\n readonly issuerId?: string;\n readonly appleTeamIdentifier?: string;\n } = {\n platform: args.platform,\n type: args.type as CliCredentialType,\n name: args.name,\n filePath: args.file,\n ...(args.password === undefined ? {} : { password: args.password }),\n ...(args[\"key-alias\"] === undefined ? {} : { keyAlias: args[\"key-alias\"] }),\n ...(args[\"key-password\"] === undefined ? {} : { keyPassword: args[\"key-password\"] }),\n ...(args[\"key-id\"] === undefined ? {} : { keyId: args[\"key-id\"] }),\n ...(args[\"issuer-id\"] === undefined ? {} : { issuerId: args[\"issuer-id\"] }),\n ...(args[\"apple-team-identifier\"] === undefined\n ? {}\n : { appleTeamIdentifier: args[\"apple-team-identifier\"] }),\n };\n\n const credential = yield* uploadCredential(api, input);\n\n yield* Console.log(\"Credential uploaded successfully.\");\n yield* Console.log(\"\");\n yield* printKeyValue([\n [\"ID\", credential.id],\n [\"Name\", credential.name],\n [\"Platform\", credential.platform],\n [\"Type\", credential.type],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { uploadCredential } from \"../../lib/credentials-manager\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { promptText } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const uploadAscKeyCommand = defineCommand({\n meta: {\n name: \"upload-asc-key\",\n description:\n \"Upload an App Store Connect API key (.p8) so the CLI can issue certificates + sync devices\",\n },\n args: {\n p8: { type: \"string\", required: true, description: \"Path to the AuthKey_XXXXXXXXXX.p8 file\" },\n \"key-id\": { type: \"string\", description: \"ASC key ID (10 uppercase alphanumeric)\" },\n \"issuer-id\": { type: \"string\", description: \"ASC issuer ID (UUID)\" },\n \"apple-team-identifier\": {\n type: \"string\",\n description: \"Apple Team identifier (optional, derived from token at first use)\",\n },\n name: { type: \"string\", description: \"Display name (defaults to the key ID)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const keyId =\n args[\"key-id\"] ?? (yield* promptText(\"ASC key ID (10 uppercase alphanumeric)\"));\n const issuerId = args[\"issuer-id\"] ?? (yield* promptText(\"ASC issuer ID (UUID)\"));\n const name = args.name ?? keyId;\n const credential = yield* uploadCredential(api, {\n platform: \"ios\",\n type: \"asc-api-key\",\n name,\n filePath: args.p8,\n keyId,\n issuerId,\n ...(args[\"apple-team-identifier\"] === undefined\n ? {}\n : { appleTeamIdentifier: args[\"apple-team-identifier\"] }),\n });\n yield* Console.log(\"ASC API key uploaded.\");\n yield* printKeyValue([\n [\"ID\", credential.id],\n [\"Name\", credential.name],\n [\"Type\", credential.type],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { CredentialValidationError } from \"../../lib/exit-codes\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst CREDENTIAL_TYPES = [\n \"distribution-certificate\",\n \"provisioning-profile\",\n \"push-key\",\n \"asc-api-key\",\n \"keystore\",\n \"google-service-account-key\",\n] as const;\n\ntype CredentialType = (typeof CREDENTIAL_TYPES)[number];\n\nconst notFound = (id: string, type: CredentialType) =>\n new CredentialValidationError({ message: `${type} with ID \"${id}\" not found.` });\n\nconst viewDistributionCertificate = (api: ApiClient, id: string) =>\n Effect.gen(function* () {\n const { items } = yield* api.appleDistributionCertificates.list();\n const item = items.find((entry) => entry.id === id);\n if (!item) {\n return yield* notFound(id, \"distribution-certificate\");\n }\n return {\n kind: \"distribution-certificate\" as const,\n pairs: [\n [\"ID\", item.id],\n [\"Type\", \"Apple distribution certificate\"],\n [\"Apple team ID\", item.appleTeamId],\n [\"Serial number\", item.serialNumber],\n [\"Developer ID\", item.developerIdIdentifier ?? \"-\"],\n [\"Valid from\", item.validFrom],\n [\"Valid until\", item.validUntil],\n [\"Created\", item.createdAt],\n [\"Updated\", item.updatedAt],\n ] as const,\n raw: item,\n };\n });\n\nconst viewProvisioningProfile = (api: ApiClient, id: string) =>\n Effect.gen(function* () {\n const { items } = yield* api.appleProvisioningProfiles.list({ urlParams: {} });\n const item = items.find((entry) => entry.id === id);\n if (!item) {\n return yield* notFound(id, \"provisioning-profile\");\n }\n return {\n kind: \"provisioning-profile\" as const,\n pairs: [\n [\"ID\", item.id],\n [\"Type\", \"Apple provisioning profile\"],\n [\"Bundle identifier\", item.bundleIdentifier],\n [\"Distribution\", item.distributionType],\n [\"Profile name\", item.profileName ?? \"-\"],\n [\"Apple team ID\", item.appleTeamId],\n [\"Distribution cert ID\", item.appleDistributionCertificateId ?? \"-\"],\n [\"Apple profile\", item.developerPortalIdentifier ?? \"-\"],\n [\"Valid until\", item.validUntil ?? \"-\"],\n [\"Created\", item.createdAt],\n [\"Updated\", item.updatedAt],\n ] as const,\n raw: item,\n };\n });\n\nconst viewPushKey = (api: ApiClient, id: string) =>\n Effect.gen(function* () {\n const { items } = yield* api.applePushKeys.list();\n const item = items.find((entry) => entry.id === id);\n if (!item) {\n return yield* notFound(id, \"push-key\");\n }\n return {\n kind: \"push-key\" as const,\n pairs: [\n [\"ID\", item.id],\n [\"Type\", \"Apple APNs auth key\"],\n [\"Key ID\", item.keyId],\n [\"Apple team ID\", item.appleTeamId],\n [\"Created\", item.createdAt],\n [\"Updated\", item.updatedAt],\n ] as const,\n raw: item,\n };\n });\n\nconst viewAscApiKey = (api: ApiClient, id: string) =>\n Effect.gen(function* () {\n const { items } = yield* api.ascApiKeys.list();\n const item = items.find((entry) => entry.id === id);\n if (!item) {\n return yield* notFound(id, \"asc-api-key\");\n }\n return {\n kind: \"asc-api-key\" as const,\n pairs: [\n [\"ID\", item.id],\n [\"Type\", \"App Store Connect API key\"],\n [\"Name\", item.name],\n [\"Key ID\", item.keyId],\n [\"Apple team ID\", item.appleTeamId ?? \"-\"],\n [\"Roles\", item.roles.length === 0 ? \"-\" : item.roles.join(\", \")],\n [\"Created\", item.createdAt],\n [\"Updated\", item.updatedAt],\n ] as const,\n raw: item,\n };\n });\n\nconst viewKeystore = (api: ApiClient, id: string) =>\n Effect.gen(function* () {\n const { items } = yield* api.androidUploadKeystores.list();\n const item = items.find((entry) => entry.id === id);\n if (!item) {\n return yield* notFound(id, \"keystore\");\n }\n return {\n kind: \"keystore\" as const,\n pairs: [\n [\"ID\", item.id],\n [\"Type\", \"Android upload keystore\"],\n [\"Key alias\", item.keyAlias],\n [\"Created\", item.createdAt],\n [\"Updated\", item.updatedAt],\n ] as const,\n raw: item,\n };\n });\n\nconst viewGoogleServiceAccountKey = (api: ApiClient, id: string) =>\n Effect.gen(function* () {\n const { items } = yield* api.googleServiceAccountKeys.list();\n const item = items.find((entry) => entry.id === id);\n if (!item) {\n return yield* notFound(id, \"google-service-account-key\");\n }\n return {\n kind: \"google-service-account-key\" as const,\n pairs: [\n [\"ID\", item.id],\n [\"Type\", \"Google service account key\"],\n [\"Client email\", item.clientEmail],\n [\"Google project ID\", item.googleProjectId],\n [\"Private key ID\", item.privateKeyId],\n [\"Created\", item.createdAt],\n [\"Updated\", item.updatedAt],\n ] as const,\n raw: item,\n };\n });\n\nconst lookupByType = (api: ApiClient, id: string, type: CredentialType) => {\n switch (type) {\n case \"distribution-certificate\": {\n return viewDistributionCertificate(api, id);\n }\n case \"provisioning-profile\": {\n return viewProvisioningProfile(api, id);\n }\n case \"push-key\": {\n return viewPushKey(api, id);\n }\n case \"asc-api-key\": {\n return viewAscApiKey(api, id);\n }\n case \"keystore\": {\n return viewKeystore(api, id);\n }\n case \"google-service-account-key\": {\n return viewGoogleServiceAccountKey(api, id);\n }\n default: {\n return Effect.fail(\n new CredentialValidationError({\n message: `Unsupported credential type: ${String(type)}`,\n }),\n );\n }\n }\n};\n\nexport const viewCommand = defineCommand({\n meta: { name: \"view\", description: \"Show details for a single credential (without secrets)\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Credential ID\" },\n type: {\n type: \"enum\",\n options: [...CREDENTIAL_TYPES],\n required: true,\n description: \"Credential type\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* lookupByType(api, args.id, args.type);\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(result.raw);\n return undefined;\n }\n yield* printKeyValue(result.pairs.map((pair) => [pair[0], pair[1]] as const));\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { runCredentialsManager } from \"../../application/credentials-manager\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { configureCommand } from \"./configure\";\nimport { deleteCommand } from \"./delete\";\nimport { downloadCommand } from \"./download\";\nimport { generateCommand } from \"./generate\";\nimport { listCommand } from \"./list\";\nimport { regenerateProfileCommand } from \"./regenerate-profile\";\nimport { removeCommand } from \"./remove\";\nimport { revokeCommand } from \"./revoke\";\nimport { syncCommand } from \"./sync\";\nimport { uploadCommand } from \"./upload\";\nimport { uploadAscKeyCommand } from \"./upload-asc-key\";\nimport { viewCommand } from \"./view\";\n\nconst managerCommand = defineCommand({\n meta: {\n name: \"manager\",\n description: \"Interactive credentials manager (top-level wizard: platform → category → action)\",\n },\n run: async () => runEffect(runCredentialsManager),\n});\n\nexport const credentialsCommand = defineCommand({\n meta: { name: \"credentials\", description: \"Manage credentials\" },\n subCommands: {\n manager: managerCommand,\n list: listCommand,\n view: viewCommand,\n download: downloadCommand,\n upload: uploadCommand,\n \"upload-asc-key\": uploadAscKeyCommand,\n generate: generateCommand,\n \"regenerate-profile\": regenerateProfileCommand,\n delete: deleteCommand,\n remove: removeCommand,\n revoke: revokeCommand,\n configure: configureCommand,\n sync: syncCommand,\n },\n run: async () => runEffect(runCredentialsManager),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\nimport qrcode from \"qrcode-terminal\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { printHuman, printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst DEVICE_CLASS_VALUES = [\"IPHONE\", \"IPAD\", \"MAC\", \"UNKNOWN\"] as const;\ntype DeviceClassArg = (typeof DEVICE_CLASS_VALUES)[number];\n\nconst isDeviceClass = (value: string): value is DeviceClassArg =>\n (DEVICE_CLASS_VALUES as readonly string[]).includes(value);\n\nconst ttlHours = (value: string | undefined): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n const match = /^([0-9]+)([hd])?$/u.exec(value);\n if (!match?.[1]) {\n return undefined;\n }\n const num = Number.parseInt(match[1], 10);\n return match[2] === \"d\" ? num * 24 : num;\n};\n\nconst renderQrcode = (url: string): Effect.Effect<string> =>\n Effect.async<string>((resume) => {\n qrcode.generate(url, { small: true }, (qr) => {\n resume(Effect.succeed(qr));\n });\n });\n\ninterface InviteArgs {\n readonly name?: string;\n readonly deviceClass?: DeviceClassArg;\n readonly appleTeamId?: string;\n readonly ttl?: number;\n readonly renderQr: boolean;\n}\n\nconst handleInvite = (api: ApiClient, args: InviteArgs) =>\n Effect.gen(function* () {\n const mode = yield* OutputMode;\n const result = yield* api.devices.createRegistrationRequest({\n payload: {\n ...(args.name === undefined ? {} : { deviceNameHint: args.name }),\n ...(args.deviceClass === undefined ? {} : { deviceClassHint: args.deviceClass }),\n ...(args.appleTeamId === undefined ? {} : { appleTeamId: args.appleTeamId }),\n ...(args.ttl === undefined ? {} : { ttlHours: args.ttl }),\n },\n });\n if (mode.json) {\n yield* printJson(result);\n return;\n }\n yield* printHuman(\"Share this URL with the device owner (open it in Safari on iOS):\");\n yield* printKeyValue([\n [\"URL\", result.url],\n [\"Expires at\", result.expiresAt],\n [\"Request ID\", result.id],\n ]);\n if (args.renderQr) {\n const rendered = yield* renderQrcode(result.url);\n yield* printHuman(\"\");\n yield* printHuman(rendered);\n }\n });\n\nexport const addDeviceCommand = defineCommand({\n meta: {\n name: \"add\",\n description:\n \"Register an Apple device (direct via --udid, or generate an invitation URL via --invite)\",\n },\n args: {\n udid: { type: \"string\", description: \"Apple UDID (40 hex, or UUID format)\" },\n name: { type: \"string\", description: \"Friendly name for the device\" },\n \"device-class\": {\n type: \"string\",\n default: \"IPHONE\",\n description: \"Device class (IPHONE, IPAD, MAC, UNKNOWN)\",\n },\n \"apple-team-id\": { type: \"string\", description: \"Apple team to assign\" },\n invite: {\n type: \"boolean\",\n description:\n \"Generate a self-service registration URL the user opens on their iOS device in Safari\",\n },\n \"expires-in\": {\n type: \"string\",\n default: \"24h\",\n description: \"Invitation TTL (e.g. 24h, 7d, max 168h)\",\n },\n qr: {\n type: \"boolean\",\n default: true,\n description: \"Render a scannable QR code alongside the invitation URL\",\n negativeDescription: \"Skip QR rendering (use --no-qr)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const mode = yield* OutputMode;\n\n if (args.invite) {\n const deviceClass = isDeviceClass(args[\"device-class\"])\n ? args[\"device-class\"]\n : undefined;\n const ttl = ttlHours(args[\"expires-in\"]);\n yield* handleInvite(api, {\n ...(args.name === undefined ? {} : { name: args.name }),\n ...(deviceClass === undefined ? {} : { deviceClass }),\n ...(args[\"apple-team-id\"] === undefined ? {} : { appleTeamId: args[\"apple-team-id\"] }),\n ...(ttl === undefined ? {} : { ttl }),\n renderQr: args.qr,\n });\n return;\n }\n\n if (args.udid === undefined) {\n yield* new InvalidArgumentError({\n message:\n \"Pass --udid <udid> --name <name>, or use --invite to generate an enrollment URL.\",\n });\n return;\n }\n const name = args.name ?? args.udid;\n const deviceClass = isDeviceClass(args[\"device-class\"]) ? args[\"device-class\"] : \"IPHONE\";\n const device = yield* api.devices.register({\n payload: {\n identifier: args.udid,\n name,\n deviceClass,\n ...(args[\"apple-team-id\"] === undefined ? {} : { appleTeamId: args[\"apple-team-id\"] }),\n },\n });\n if (mode.json) {\n yield* printJson(device);\n return;\n }\n yield* printKeyValue([\n [\"ID\", device.id],\n [\"Name\", device.name],\n [\"UDID\", device.identifier],\n [\"Class\", device.deviceClass],\n [\"Enabled\", device.enabled ? \"yes\" : \"no\"],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printHuman } from \"../../lib/output\";\nimport { promptConfirm } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const deleteDeviceCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a device permanently\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Device ID\" },\n yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n if (!args.yes) {\n const confirmed = yield* promptConfirm(`Delete device ${args.id}?`, {\n initialValue: false,\n });\n if (!confirmed) {\n yield* printHuman(\"Cancelled.\");\n return;\n }\n }\n const api = yield* apiClient;\n yield* api.devices.delete({ path: { id: args.id } });\n yield* printHuman(`Deleted device ${args.id}.`);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const disableDeviceCommand = defineCommand({\n meta: {\n name: \"disable\",\n description: \"Disable a device (exclude it from new provisioning profiles)\",\n },\n args: {\n id: { type: \"positional\", required: true, description: \"Device ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const device = yield* api.devices.update({\n path: { id: args.id },\n payload: { enabled: false },\n });\n yield* printKeyValue([\n [\"ID\", device.id],\n [\"Name\", device.name],\n [\"Enabled\", \"no\"],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const enableDeviceCommand = defineCommand({\n meta: { name: \"enable\", description: \"Re-enable a device (include it in new provisioning)\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Device ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const device = yield* api.devices.update({\n path: { id: args.id },\n payload: { enabled: true },\n });\n yield* printKeyValue([\n [\"ID\", device.id],\n [\"Name\", device.name],\n [\"Enabled\", \"yes\"],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printJson, printTable } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nconst parseEnabled = (value: string | undefined): boolean | undefined => {\n if (value === undefined) {\n return undefined;\n }\n if (value === \"true\") {\n return true;\n }\n if (value === \"false\") {\n return false;\n }\n return undefined;\n};\n\nexport const listDevicesCommand = defineCommand({\n meta: { name: \"list\", description: \"List registered Apple devices\" },\n args: {\n \"device-class\": {\n type: \"enum\",\n options: [\"IPHONE\", \"IPAD\", \"MAC\", \"UNKNOWN\"],\n description: \"Filter by device class\",\n },\n \"apple-team-id\": { type: \"string\", description: \"Filter by Apple team ID\" },\n query: { type: \"string\", description: \"Search devices by name or identifier\" },\n enabled: { type: \"string\", description: \"Filter by enabled status (true/false)\" },\n page: { type: \"string\", default: \"1\", description: \"Page number\" },\n limit: { type: \"string\", default: \"20\", description: \"Items per page\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.devices.list({\n urlParams: {\n ...(args[\"device-class\"] === undefined ? {} : { deviceClass: args[\"device-class\"] }),\n ...(args[\"apple-team-id\"] === undefined ? {} : { appleTeamId: args[\"apple-team-id\"] }),\n ...(args.query === undefined ? {} : { query: args.query }),\n page: Number(args.page),\n limit: Number(args.limit),\n },\n });\n const enabledFilter = parseEnabled(args.enabled);\n const items =\n enabledFilter === undefined\n ? result.items\n : result.items.filter((device) => device.enabled === enabledFilter);\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson({ items, total: result.total, page: result.page, limit: result.limit });\n return;\n }\n yield* printTable(\n [\"ID\", \"Name\", \"Class\", \"UDID\", \"Team\", \"Enabled\"],\n items.map((device) => [\n device.id,\n device.name,\n device.deviceClass,\n device.identifier,\n device.appleTeamId ?? \"—\",\n device.enabled ? \"yes\" : \"no\",\n ]),\n );\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { promptText } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const renameDeviceCommand = defineCommand({\n meta: { name: \"rename\", description: \"Rename a device\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Device ID\" },\n name: { type: \"string\", description: \"New name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const name = args.name ?? (yield* promptText(\"New name\"));\n const device = yield* api.devices.update({\n path: { id: args.id },\n payload: { name },\n });\n yield* printKeyValue([\n [\"ID\", device.id],\n [\"Name\", device.name],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { printHuman, printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { promptSelect } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const syncDevicesCommand = defineCommand({\n meta: {\n name: \"sync\",\n description:\n \"Pull devices from Apple Developer Portal via an ASC API key, push local devices that aren't registered yet\",\n },\n args: {\n \"asc-key-id\": {\n type: \"string\",\n description:\n \"ASC API key ID (from `credentials list`). If omitted, the CLI lists keys and prompts.\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n let ascKeyId = args[\"asc-key-id\"];\n\n if (ascKeyId === undefined) {\n const keys = yield* api.ascApiKeys.list();\n if (keys.items.length === 0) {\n return yield* new InvalidArgumentError({\n message:\n \"No ASC API keys uploaded. Run `better-update credentials upload asc-key --p8 <path> ...` first.\",\n });\n }\n ascKeyId =\n keys.items.length === 1\n ? keys.items[0]?.id\n : yield* promptSelect<string>(\n \"Select an ASC API key\",\n keys.items.map((key) => ({\n value: key.id,\n label: `${key.name} (${key.keyId})`,\n })),\n );\n }\n if (ascKeyId === undefined) {\n return yield* new InvalidArgumentError({ message: \"ASC API key ID required.\" });\n }\n const result = yield* api.ascApiKeys.syncDevices({ path: { id: ascKeyId } });\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(result);\n return undefined;\n }\n yield* printHuman(`Sync complete via ASC key ${ascKeyId}.`);\n yield* printKeyValue([\n [\"Pulled\", String(result.pulled)],\n [\"Pushed\", String(result.pushed)],\n [\"Skipped\", String(result.skipped)],\n [\"Devices\", String(result.devices.length)],\n ]);\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const viewDeviceCommand = defineCommand({\n meta: { name: \"view\", description: \"Show details for a single device\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Device ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const device = yield* api.devices.get({ path: { id: args.id } });\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(device);\n return;\n }\n yield* printKeyValue([\n [\"ID\", device.id],\n [\"Name\", device.name],\n [\"Class\", device.deviceClass],\n [\"UDID\", device.identifier],\n [\"Model\", device.model ?? \"—\"],\n [\"Apple team\", device.appleTeamId ?? \"—\"],\n [\"Apple portal\", device.appleDevicePortalId ?? \"—\"],\n [\"Enabled\", device.enabled ? \"yes\" : \"no\"],\n [\"Created\", device.createdAt],\n ]);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { addDeviceCommand } from \"./add\";\nimport { deleteDeviceCommand } from \"./delete\";\nimport { disableDeviceCommand } from \"./disable\";\nimport { enableDeviceCommand } from \"./enable\";\nimport { listDevicesCommand } from \"./list\";\nimport { renameDeviceCommand } from \"./rename\";\nimport { syncDevicesCommand } from \"./sync\";\nimport { viewDeviceCommand } from \"./view\";\n\nexport const devicesCommand = defineCommand({\n meta: { name: \"devices\", description: \"Manage Apple devices for ad-hoc distribution\" },\n subCommands: {\n add: addDeviceCommand,\n list: listDevicesCommand,\n view: viewDeviceCommand,\n rename: renameDeviceCommand,\n enable: enableDeviceCommand,\n disable: disableDeviceCommand,\n delete: deleteDeviceCommand,\n sync: syncDevicesCommand,\n },\n});\n","import { spawnSync } from \"node:child_process\";\nimport process from \"node:process\";\n\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { readEasJson } from \"../lib/eas-config\";\nimport { extractProjectId, readExpoConfig } from \"../lib/expo-config\";\nimport { printJson, printTable } from \"../lib/output\";\nimport { OutputMode } from \"../lib/output-mode\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { ConfigStore } from \"../services/config-store\";\n\ntype CheckStatus = \"pass\" | \"warn\" | \"fail\";\n\ninterface CheckResult {\n readonly id: string;\n readonly name: string;\n readonly status: CheckStatus;\n readonly message: string;\n}\n\nconst pass = (id: string, name: string, message: string): CheckResult => ({\n id,\n name,\n status: \"pass\",\n message,\n});\n\nconst warn = (id: string, name: string, message: string): CheckResult => ({\n id,\n name,\n status: \"warn\",\n message,\n});\n\nconst fail = (id: string, name: string, message: string): CheckResult => ({\n id,\n name,\n status: \"fail\",\n message,\n});\n\nconst checkNode = (): CheckResult => {\n const version = process.versions.node;\n const major = Number.parseInt(version.split(\".\")[0] ?? \"0\", 10);\n if (major >= 22) {\n return pass(\"node\", \"Node.js version\", `${version} (>= 22 required)`);\n }\n return fail(\"node\", \"Node.js version\", `${version} is below the minimum required version 22`);\n};\n\nconst checkCommand = (id: string, name: string, command: string, args: readonly string[]) =>\n Effect.sync((): CheckResult => {\n const result = spawnSync(command, [...args], { stdio: \"pipe\", timeout: 5000 });\n if (result.status === 0) {\n const stdout = result.stdout.toString().trim();\n return pass(id, name, stdout.length > 0 ? stdout : \"available\");\n }\n return warn(id, name, `${command} not found or returned status ${result.status}`);\n });\n\nconst checkServerHealth = Effect.gen(function* () {\n const config = yield* ConfigStore;\n const base = yield* config.getBaseUrl;\n const url = `${base}/api/health`;\n const response = yield* Effect.tryPromise({\n try: async () => fetch(url, { signal: AbortSignal.timeout(3000) }),\n catch: (cause) => new Error(String(cause)),\n }).pipe(Effect.either);\n if (response._tag === \"Left\") {\n return fail(\"health\", \"Server reachable\", `${url} unreachable: ${response.left.message}`);\n }\n const res = response.right;\n if (res.ok) {\n return pass(\"health\", \"Server reachable\", `${url} returned 200`);\n }\n return warn(\"health\", \"Server reachable\", `${url} returned ${res.status}`);\n}).pipe(Effect.scoped);\n\nconst checkAuth = Effect.gen(function* () {\n const api = yield* apiClient.pipe(Effect.option);\n if (api._tag === \"None\") {\n return fail(\"auth\", \"Auth token\", \"Not logged in (run `better-update login`)\");\n }\n const result = yield* api.value.me.get().pipe(Effect.either);\n if (result._tag === \"Left\") {\n return fail(\"auth\", \"Auth token\", `Token rejected by server: ${String(result.left)}`);\n }\n const me = result.right;\n const who = me.user?.email ?? me.actorEmail;\n return pass(\"auth\", \"Auth token\", `Valid (${who})`);\n});\n\nconst checkExpoConfig = Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const root = yield* runtime.cwd;\n const expo = yield* readExpoConfig(root).pipe(Effect.either);\n if (expo._tag === \"Left\") {\n return warn(\n \"expo-config\",\n \"Expo config\",\n \"No app.json / app.config.{js,ts} in the current directory\",\n );\n }\n const projectId = yield* extractProjectId(expo.right).pipe(Effect.either);\n if (projectId._tag === \"Left\") {\n return warn(\n \"project-linked\",\n \"Project linked\",\n \"extra.betterUpdate.projectId not set — run `better-update init`\",\n );\n }\n return pass(\"project-linked\", \"Project linked\", `projectId=${projectId.right}`);\n});\n\nconst checkEasJson = Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const root = yield* runtime.cwd;\n const result = yield* readEasJson(root).pipe(Effect.either);\n if (result._tag === \"Left\") {\n return warn(\"eas-json\", \"eas.json\", result.left.message);\n }\n const count = Object.keys(result.right.build ?? {}).length;\n return pass(\"eas-json\", \"eas.json\", `${count} profile(s) defined`);\n});\n\nconst runChecks = Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const xcode =\n runtime.platform === \"darwin\"\n ? [yield* checkCommand(\"xcode\", \"Xcode CLI tools\", \"xcode-select\", [\"-p\"])]\n : [];\n return [\n checkNode(),\n ...xcode,\n yield* checkCommand(\"keytool\", \"keytool (Android signing)\", \"keytool\", [\"-help\"]),\n yield* checkServerHealth,\n yield* checkAuth,\n yield* checkExpoConfig,\n yield* checkEasJson,\n ];\n});\n\nconst statusIcon = (status: CheckStatus): string => {\n if (status === \"pass\") {\n return \"[OK] \";\n }\n if (status === \"warn\") {\n return \"[WARN]\";\n }\n return \"[FAIL]\";\n};\n\nconst renderHuman = (checks: readonly CheckResult[]) => {\n const rows: (readonly string[])[] = checks.map((check) => [\n statusIcon(check.status),\n check.name,\n check.message,\n ]);\n return printTable([\"\", \"Check\", \"Detail\"], rows);\n};\n\nconst computeExitCode = (checks: readonly CheckResult[]): number =>\n checks.some((check) => check.status === \"fail\") ? 6 : 0;\n\nexport const doctorCommand = defineCommand({\n meta: {\n name: \"doctor\",\n description: \"Run diagnostic checks (Node, signing tools, server reachability, auth, config)\",\n },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const checks = yield* runChecks;\n const mode = yield* OutputMode;\n yield* mode.json ? printJson({ checks }) : renderHuman(checks);\n const exitCode = computeExitCode(checks);\n if (exitCode !== 0) {\n yield* runtime.setExitCode(exitCode);\n }\n }),\n ),\n});\n","import { Data } from \"effect\";\n\nexport class EnvResourceNotFoundError extends Data.TaggedError(\"EnvResourceNotFoundError\")<{\n readonly message: string;\n}> {}\n\nexport const envErrorExtras = {\n EnvResourceNotFoundError: 1,\n SystemError: 6,\n BadArgument: 6,\n} as const;\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { EnvResourceNotFoundError, envErrorExtras } from \"./helpers\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete an environment variable by key\" },\n args: {\n key: { type: \"positional\", required: true, description: \"Env var key\" },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const existing = yield* api[\"env-vars\"].list({\n urlParams: { projectId, environment: args.environment },\n });\n\n const match = existing.items.find((item) => item.key === args.key);\n\n if (!match) {\n return yield* new EnvResourceNotFoundError({\n message: `Environment variable ${args.key} not found in ${args.environment}`,\n });\n }\n\n yield* api[\"env-vars\"].delete({ path: { id: match.id } });\n yield* Console.log(`Deleted ${args.key} from ${args.environment}`);\n return undefined;\n }),\n envErrorExtras,\n ),\n});\n","/**\n * Argv after the first `--` separator. Captured at entry point so commands like\n * `env exec` can read raw command + args without citty interpreting them as flags.\n * `null` means no separator was present.\n */\nlet trailing: readonly string[] | null = null;\n\nexport const splitTrailingArgv = (\n argv: readonly string[],\n): { readonly mainArgs: readonly string[]; readonly trailing: readonly string[] | null } => {\n const idx = argv.indexOf(\"--\");\n if (idx === -1) {\n return { mainArgs: argv, trailing: null };\n }\n return { mainArgs: argv.slice(0, idx), trailing: argv.slice(idx + 1) };\n};\n\nexport const setExecTrailingArgv = (args: readonly string[] | null): void => {\n trailing = args;\n};\n\nexport const getExecTrailingArgv = (): readonly string[] | null => trailing;\n","import { Command } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { getExecTrailingArgv } from \"../../lib/exec-trailing-argv\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\nimport { envErrorExtras } from \"./helpers\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst pullForExec = (\n api: ApiClient,\n projectId: string,\n environment: string,\n): Effect.Effect<Record<string, string>> =>\n api[\"env-vars\"].export({ urlParams: { projectId, environment } }).pipe(\n Effect.map((result) => Object.fromEntries(result.items.map((item) => [item.key, item.value]))),\n Effect.catchAll(() => Effect.succeed<Record<string, string>>({})),\n );\n\nconst splitTrailing = (\n trailing: readonly string[] | null,\n): Effect.Effect<readonly [string, readonly string[]], InvalidArgumentError> => {\n if (!trailing || trailing.length === 0) {\n return Effect.fail(\n new InvalidArgumentError({\n message:\n \"Pass the command after `--`. Example: `better-update env exec production -- bun run dev`.\",\n }),\n );\n }\n const [bin, ...rest] = trailing;\n if (bin === undefined) {\n return Effect.fail(new InvalidArgumentError({ message: \"Missing command name after `--`.\" }));\n }\n return Effect.succeed([bin, rest] as const);\n};\n\nexport const execCommand = defineCommand({\n meta: {\n name: \"exec\",\n description:\n \"Run a command with project env vars injected. Usage: env exec <environment> -- <command...>\",\n },\n args: {\n environment: {\n type: \"positional\",\n required: true,\n description: \"Target environment (e.g. production)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const [bin, rest] = yield* splitTrailing(getExecTrailingArgv());\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const runtime = yield* CliRuntime;\n const baseEnv = yield* runtime.commandEnvironment();\n const pulled = yield* pullForExec(api, projectId, args.environment);\n\n const cmd = Command.make(bin, ...rest).pipe(\n Command.env({ ...baseEnv, ...pulled }),\n Command.stdin(\"inherit\"),\n Command.stdout(\"inherit\"),\n Command.stderr(\"inherit\"),\n );\n const code = yield* Command.exitCode(cmd).pipe(Effect.orDie);\n yield* runtime.setExitCode(code);\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const exportCommand = defineCommand({\n meta: { name: \"export\", description: \"Print env vars in KEY='value' format\" },\n args: {\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const result = yield* api[\"env-vars\"].export({\n urlParams: { projectId, environment: args.environment },\n });\n\n for (const item of result.items) {\n const escaped = item.value.replaceAll(\"'\", String.raw`'\\''`);\n yield* Console.log(`${item.key}='${escaped}'`);\n }\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const getCommand = defineCommand({\n meta: { name: \"get\", description: \"Show an environment variable\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Env var ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const envVar = yield* api[\"env-vars\"].get({ path: { id: args.id } });\n yield* printKeyValue([\n [\"ID\", envVar.id],\n [\"Key\", envVar.key],\n [\"Environment\", envVar.environment],\n [\"Visibility\", envVar.visibility],\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- EnvVar.value nullable at storage; display empty when absent\n [\"Value\", envVar.visibility === \"plaintext\" ? (envVar.value ?? \"\") : \"******\"],\n [\"Created\", envVar.createdAt],\n [\"Updated\", envVar.updatedAt],\n ]);\n }),\n envErrorExtras,\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const importCommand = defineCommand({\n meta: { name: \"import\", description: \"Bulk-import env vars from a dotenv file\" },\n args: {\n file: { type: \"positional\", required: true, description: \"Path to .env file\" },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n visibility: {\n type: \"enum\",\n options: [\"plaintext\", \"sensitive\", \"secret\"],\n default: \"plaintext\",\n description: \"Visibility applied to all imported values\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const content = yield* fs.readFileString(args.file);\n\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const result = yield* api[\"env-vars\"].bulkImport({\n payload: {\n projectId,\n environment: args.environment,\n content,\n visibility: args.visibility,\n },\n });\n\n yield* Console.log(\n `Imported: ${String(result.created)} created, ${String(result.updated)} updated, ${String(result.skipped)} skipped`,\n );\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List environment variables\" },\n args: {\n environment: { type: \"string\", description: \"Filter by environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const envFilter = args.environment ? { environment: args.environment } : {};\n\n const result = yield* api[\"env-vars\"].list({\n urlParams: { projectId, ...envFilter },\n });\n\n yield* printList(\n [\"Key\", \"Environment\", \"Visibility\", \"Value\"],\n result.items.map((item) => [\n item.key,\n item.environment,\n item.visibility,\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- EnvVar.value nullable at storage; display empty when absent\n item.visibility === \"plaintext\" ? (item.value ?? \"\") : \"••••••\",\n ]),\n \"No environment variables found.\",\n );\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const pullCommand = defineCommand({\n meta: { name: \"pull\", description: \"Print env vars in `export KEY='value'` format\" },\n args: {\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const result = yield* api[\"env-vars\"].export({\n urlParams: { projectId, environment: args.environment },\n });\n\n for (const item of result.items) {\n const escaped = item.value.replaceAll(\"'\", String.raw`'\\''`);\n yield* Console.log(`export ${item.key}='${escaped}'`);\n }\n }),\n envErrorExtras,\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { InteractiveMode } from \"../../lib/interactive-mode\";\nimport { printHuman } from \"../../lib/output\";\nimport { promptMultiSelect } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\ntype Visibility = \"plaintext\" | \"sensitive\" | \"secret\";\n\ninterface ParsedVar {\n readonly key: string;\n readonly value: string;\n readonly visibility: Visibility;\n}\n\nconst LINE_PATTERN = /^\\s*(?:export\\s+)?([A-Z][A-Z0-9_]*)\\s*=\\s*(.*?)\\s*$/u;\n\nconst stripQuotes = (raw: string): string => {\n if (raw.length < 2) {\n return raw;\n }\n const [first] = raw;\n const last = raw.at(-1);\n const quoted = (first === '\"' && last === '\"') || (first === \"'\" && last === \"'\");\n return quoted ? raw.slice(1, -1) : raw;\n};\n\nconst classifyVisibility = (key: string): Visibility =>\n key.startsWith(\"EXPO_PUBLIC_\") ? \"plaintext\" : \"sensitive\";\n\nconst parseLine = (rawLine: string): ParsedVar | undefined => {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n return undefined;\n }\n const match = LINE_PATTERN.exec(line);\n if (!match) {\n return undefined;\n }\n const [, key, rawValue] = match;\n if (key === undefined || rawValue === undefined) {\n return undefined;\n }\n return { key, value: stripQuotes(rawValue), visibility: classifyVisibility(key) };\n};\n\nconst parseDotenv = (content: string): readonly ParsedVar[] =>\n content\n .split(/\\r?\\n/u)\n .map(parseLine)\n .filter((entry): entry is ParsedVar => entry !== undefined);\n\nexport const pushCommand = defineCommand({\n meta: {\n name: \"push\",\n description:\n \"Push env vars from a dotenv file. Auto-classifies EXPO_PUBLIC_* as plaintext, others as sensitive.\",\n },\n args: {\n file: {\n type: \"positional\",\n required: false,\n default: \".env.local\",\n description: \"Path to dotenv file (default: .env.local)\",\n },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n force: {\n type: \"boolean\",\n description: \"Overwrite existing vars without prompting\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const content = yield* fs.readFileString(args.file);\n const parsed = parseDotenv(content);\n\n if (parsed.length === 0) {\n yield* printHuman(`No valid KEY=VALUE entries found in ${args.file}.`);\n return;\n }\n\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const existingResp = yield* api[\"env-vars\"].list({\n urlParams: { projectId, environment: args.environment },\n });\n const existingByKey = new Map(existingResp.items.map((item) => [item.key, item]));\n\n const conflicts = parsed.filter((entry) => existingByKey.has(entry.key));\n const newEntries = parsed.filter((entry) => !existingByKey.has(entry.key));\n\n const resolveOverwriteSet = Effect.gen(function* () {\n if (conflicts.length === 0 || args.force) {\n return conflicts;\n }\n const mode = yield* InteractiveMode;\n if (!mode.allow) {\n const conflictKeys = conflicts.map((conflict) => conflict.key).join(\", \");\n return yield* new InvalidArgumentError({\n message: `${String(conflicts.length)} conflict(s): ${conflictKeys}. Pass --force to overwrite or run interactively.`,\n });\n }\n const picked = yield* promptMultiSelect<string>(\n \"Overwrite which existing vars?\",\n conflicts.map((entry) => ({\n value: entry.key,\n label: `${entry.key} (${existingByKey.get(entry.key)?.visibility ?? \"?\"} → ${entry.visibility})`,\n })),\n );\n const pickedSet = new Set(picked);\n return conflicts.filter((entry) => pickedSet.has(entry.key));\n });\n\n const entriesToOverwrite = yield* resolveOverwriteSet;\n\n const skipped = conflicts.length - entriesToOverwrite.length;\n\n yield* Effect.forEach(\n newEntries,\n (entry) =>\n api[\"env-vars\"].create({\n payload: {\n projectId,\n environment: args.environment,\n key: entry.key,\n value: entry.value,\n visibility: entry.visibility,\n },\n }),\n { concurrency: 4 },\n );\n\n yield* Effect.forEach(\n entriesToOverwrite,\n (entry) => {\n const existing = existingByKey.get(entry.key);\n if (!existing) {\n return Effect.succeed(undefined);\n }\n return api[\"env-vars\"].update({\n path: { id: existing.id },\n payload: { value: entry.value, visibility: entry.visibility },\n });\n },\n { concurrency: 4 },\n );\n\n yield* printHuman(\n `Pushed to ${args.environment}: ${String(newEntries.length)} created, ${String(\n entriesToOverwrite.length,\n )} updated${skipped > 0 ? `, ${String(skipped)} skipped` : \"\"}.`,\n );\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseKeyValue } from \"../../lib/cli-schemas\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { apiClient } from \"../../services/api-client\";\nimport { envErrorExtras } from \"./helpers\";\n\nexport const setCommand = defineCommand({\n meta: { name: \"set\", description: \"Create or update an environment variable\" },\n args: {\n keyValue: {\n type: \"positional\",\n required: true,\n description: \"KEY=VALUE pair (e.g. API_KEY=abc123)\",\n },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n visibility: {\n type: \"enum\",\n options: [\"plaintext\", \"sensitive\", \"secret\"],\n default: \"plaintext\",\n description: \"Value visibility\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const { key, value } = yield* parseKeyValue(args.keyValue);\n const { environment } = args;\n const { visibility } = args;\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const existing = yield* api[\"env-vars\"].list({\n urlParams: { projectId, environment },\n });\n\n const match = existing.items.find((item) => item.key === key);\n\n if (match) {\n yield* api[\"env-vars\"].update({\n path: { id: match.id },\n payload: { value, visibility },\n });\n yield* Console.log(`Updated ${key} in ${environment}`);\n } else {\n yield* api[\"env-vars\"].create({\n payload: { projectId, environment, key, value, visibility },\n });\n yield* Console.log(`Created ${key} in ${environment}`);\n }\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printHuman } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { EnvResourceNotFoundError, envErrorExtras } from \"./helpers\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Update an env var's value or visibility\" },\n args: {\n key: { type: \"positional\", required: true, description: \"Env var key (e.g. API_KEY)\" },\n value: { type: \"string\", description: \"New value (leave unset to keep current)\" },\n visibility: {\n type: \"enum\",\n options: [\"plaintext\", \"sensitive\", \"secret\"],\n description: \"New visibility (leave unset to keep current)\",\n },\n environment: { type: \"string\", default: \"production\", description: \"Target environment\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const { key, value, visibility, environment } = args;\n\n if (value === undefined && visibility === undefined) {\n return yield* new InvalidArgumentError({\n message: \"Pass --value, --visibility, or both. Nothing to update otherwise.\",\n });\n }\n\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const existing = yield* api[\"env-vars\"].list({\n urlParams: { projectId, environment },\n });\n const match = existing.items.find((item) => item.key === key);\n if (!match) {\n return yield* new EnvResourceNotFoundError({\n message: `Env var \"${key}\" not found in environment \"${environment}\".`,\n });\n }\n\n const payload = {\n ...(value === undefined ? {} : { value }),\n ...(visibility === undefined ? {} : { visibility }),\n };\n yield* api[\"env-vars\"].update({ path: { id: match.id }, payload });\n\n const changed: string[] = [];\n if (value !== undefined) {\n changed.push(\"value\");\n }\n if (visibility !== undefined) {\n changed.push(\"visibility\");\n }\n yield* printHuman(`Updated ${changed.join(\" + \")} for ${key} in ${environment}.`);\n return undefined;\n }),\n envErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { deleteCommand } from \"./delete\";\nimport { execCommand } from \"./exec\";\nimport { exportCommand } from \"./export\";\nimport { getCommand } from \"./get\";\nimport { importCommand } from \"./import\";\nimport { listCommand } from \"./list\";\nimport { pullCommand } from \"./pull\";\nimport { pushCommand } from \"./push\";\nimport { setCommand } from \"./set\";\nimport { updateCommand } from \"./update\";\n\nexport const envCommand = defineCommand({\n meta: { name: \"env\", description: \"Manage environment variables\" },\n subCommands: {\n list: listCommand,\n get: getCommand,\n set: setCommand,\n update: updateCommand,\n delete: deleteCommand,\n import: importCommand,\n push: pushCommand,\n export: exportCommand,\n pull: pullCommand,\n exec: execCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { exitWith } from \"../../application/command-exit\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { runFingerprintFull } from \"../../lib/fingerprint\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nexport const compareCommand = defineCommand({\n meta: { name: \"compare\", description: \"Compare a fingerprint hash against the current project\" },\n args: {\n hash: { type: \"positional\", required: true, description: \"Fingerprint hash to compare\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const result = yield* runFingerprintFull(projectRoot);\n\n if (result.hash === args.hash) {\n yield* Console.log(\"Fingerprints match.\");\n return undefined;\n }\n yield* Console.log(\"Fingerprints differ.\");\n yield* Console.log(` Local: ${result.hash}`);\n yield* Console.log(` Provided: ${args.hash}`);\n return yield* exitWith(1, \"Fingerprint mismatch\");\n }),\n { FingerprintError: 2 },\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { runFingerprintFull } from \"../../lib/fingerprint\";\nimport { CliRuntime } from \"../../services/cli-runtime\";\n\nexport const generateCommand = defineCommand({\n meta: { name: \"generate\", description: \"Compute a fingerprint for the current project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const result = yield* runFingerprintFull(projectRoot);\n yield* Console.log(result.hash);\n if (result.sources.length > 0) {\n yield* Console.log(`${result.sources.length} sources`);\n }\n }),\n { FingerprintError: 2 },\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { compareCommand } from \"./compare\";\nimport { generateCommand } from \"./generate\";\n\nexport const fingerprintCommand = defineCommand({\n meta: { name: \"fingerprint\", description: \"Fingerprint utilities\" },\n subCommands: {\n generate: generateCommand,\n compare: compareCommand,\n },\n});\n","import path from \"node:path\";\n\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { extractSlug, readExpoConfig, writeProjectId } from \"../lib/expo-config\";\nimport { InteractiveMode } from \"../lib/interactive-mode\";\nimport { promptConfirm } from \"../lib/prompts\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nimport type { ApiClient } from \"../services/api-client\";\n\nconst checkExistingLink = (\n api: ApiClient,\n config: { readonly extra?: { readonly betterUpdate?: { readonly projectId?: unknown } } },\n localSlug: string,\n) =>\n Effect.gen(function* () {\n const existingId = config.extra?.betterUpdate?.projectId;\n if (typeof existingId !== \"string\" || existingId.length === 0) {\n return \"no-link\" as const;\n }\n\n const project = yield* api.projects\n .get({ path: { id: existingId } })\n .pipe(Effect.catchAll(() => Effect.succeed(undefined)));\n if (project === undefined) {\n yield* Console.error(\n `Existing projectId \"${existingId}\" not found on server. Re-linking by local slug \"${localSlug}\".`,\n );\n return \"stale\" as const;\n }\n if (project.slug === localSlug) {\n yield* Console.log(`Already linked to \"${project.name}\" (${project.id}). Nothing to do.`);\n return \"matched\" as const;\n }\n yield* Console.error(\n `Linked projectId \"${existingId}\" points to slug \"${project.slug}\" but local slug is \"${localSlug}\".`,\n );\n const mode = yield* InteractiveMode;\n if (!mode.allow) {\n yield* Console.error(\"Re-running in interactive mode would prompt to overwrite. Aborting.\");\n return \"mismatch-abort\" as const;\n }\n const overwrite = yield* promptConfirm(\"Overwrite local projectId with a fresh link by slug?\", {\n initialValue: false,\n });\n return overwrite ? (\"mismatch-overwrite\" as const) : (\"mismatch-abort\" as const);\n });\n\nexport const initCommand = defineCommand({\n meta: { name: \"init\", description: \"Link the local Expo project to a better-update project\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const config = yield* readExpoConfig(projectRoot);\n const name = config.name ?? config.slug ?? \"untitled\";\n const slug = yield* extractSlug(config);\n\n yield* Console.log(`Linking project: ${name} (${slug})`);\n\n const api = yield* apiClient;\n\n const linkState = yield* checkExistingLink(api, config, slug);\n if (linkState === \"matched\" || linkState === \"mismatch-abort\") {\n return;\n }\n\n const { items } = yield* api.projects.list({ urlParams: { page: 1, limit: 100 } });\n const existing = items.find((project) => project.slug === slug);\n const linkedProjectId = yield* Effect.gen(function* () {\n if (existing) {\n yield* Console.log(`Found existing project: ${existing.name} (${existing.id})`);\n return existing.id;\n }\n yield* Console.log(\"No existing project found. Creating new project...\");\n const created = yield* api.projects.create({ payload: { name, slug } });\n yield* Console.log(`Created project: ${created.name} (${created.id})`);\n return created.id;\n });\n\n const writeResult = yield* writeProjectId(projectRoot, linkedProjectId);\n const target = writeResult.configPath\n ? path.relative(projectRoot, writeResult.configPath)\n : \"your Expo config\";\n yield* Console.log(`Project linked successfully. ID saved to ${target}.`);\n if (writeResult.type === \"warn\" && writeResult.message) {\n yield* Console.log(`Note: ${writeResult.message}`);\n }\n }),\n ),\n});\n","import { once } from \"node:events\";\nimport { createServer } from \"node:http\";\nimport type { IncomingMessage, Server, ServerResponse } from \"node:http\";\n\nimport { isRecord } from \"@better-update/type-guards\";\nimport { Data, Deferred, Duration, Effect } from \"effect\";\n\nexport class BrowserLoginTimeoutError extends Data.TaggedError(\"BrowserLoginTimeoutError\")<{\n readonly message: string;\n}> {}\n\nexport class BrowserLoginSessionClosedError extends Data.TaggedError(\n \"BrowserLoginSessionClosedError\",\n)<{\n readonly message: string;\n}> {}\n\nexport type BrowserLoginError = BrowserLoginSessionClosedError | BrowserLoginTimeoutError;\n\nexport const CALLBACK_PAGE = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>better-update CLI Login</title>\n <style>\n :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }\n body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; }\n main { max-width: 32rem; line-height: 1.5; }\n code { font-family: ui-monospace, SFMono-Regular, monospace; }\n </style>\n </head>\n <body>\n <main>\n <h1>Completing CLI login...</h1>\n <p id=\"message\">Finalizing the local session. You can keep this tab open.</p>\n </main>\n <script>\n const message = document.getElementById(\"message\");\n const render = (text) => {\n if (message) message.textContent = text;\n };\n\n const params = new URLSearchParams(window.location.hash.slice(1));\n const token = params.get(\"token\");\n\n if (!token) {\n render(\"Missing token. Return to the CLI and run login again.\");\n } else {\n fetch(\"/callback/token\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ token }),\n })\n .then(async (response) => {\n if (!response.ok) {\n const body = await response.text();\n throw new Error(body || \"Callback failed\");\n }\n window.history.replaceState({}, document.title, window.location.pathname);\n render(\"CLI login complete. You can close this tab.\");\n setTimeout(() => window.close(), 300);\n })\n .catch((error) => {\n render(error instanceof Error ? error.message : \"Callback failed.\");\n });\n }\n </script>\n </body>\n</html>`;\n\nexport interface BrowserLoginServer {\n readonly callbackUrl: string;\n readonly waitForToken: Effect.Effect<string, BrowserLoginError>;\n readonly stop: () => void;\n}\n\nexport interface BrowserLoginSession {\n readonly callbackPath: string;\n readonly waitForToken: Effect.Effect<string, BrowserLoginError>;\n readonly handleRequest: (request: Request) => Promise<Response>;\n readonly dispose: () => void;\n}\n\nexport interface CreateBrowserLoginServerOptions {\n readonly timeoutMs?: number;\n}\n\nexport const createBrowserLoginSession = (\n options: CreateBrowserLoginServerOptions = {},\n): BrowserLoginSession => {\n const tokenDeferred = Effect.runSync(Deferred.make<string, BrowserLoginSessionClosedError>());\n const waitForToken = Deferred.await(tokenDeferred).pipe(\n Effect.timeoutFail({\n duration:\n options.timeoutMs === undefined ? Duration.minutes(5) : Duration.millis(options.timeoutMs),\n onTimeout: () =>\n new BrowserLoginTimeoutError({\n message: \"Timed out waiting for browser login to complete.\",\n }),\n }),\n );\n\n const dispose = () => {\n Effect.runSync(\n Deferred.fail(\n tokenDeferred,\n new BrowserLoginSessionClosedError({\n message: \"Browser login session closed.\",\n }),\n ),\n );\n };\n\n return {\n callbackPath: \"/callback\",\n waitForToken,\n handleRequest: async (request) => {\n const url = new URL(request.url);\n\n if (request.method === \"GET\" && url.pathname === \"/callback\") {\n return new Response(CALLBACK_PAGE, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n }\n\n if (request.method === \"POST\" && url.pathname === \"/callback/token\") {\n try {\n const body: unknown = await request.json();\n if (!isRecord(body)) {\n return new Response(\"Invalid callback payload\", { status: 400 });\n }\n const token = typeof body[\"token\"] === \"string\" ? body[\"token\"].trim() : \"\";\n if (token.length === 0) {\n return new Response(\"Missing token\", { status: 400 });\n }\n\n Effect.runSync(Deferred.succeed(tokenDeferred, token));\n return Response.json({ ok: true });\n } catch {\n return new Response(\"Invalid callback payload\", { status: 400 });\n }\n }\n\n return new Response(\"Not found\", { status: 404 });\n },\n dispose,\n };\n};\n\nconst readBody = async (req: IncomingMessage): Promise<Buffer> => {\n const chunks: Buffer[] = [];\n for await (const chunk of req as AsyncIterable<Buffer>) {\n chunks.push(chunk);\n }\n return Buffer.concat(chunks);\n};\n\nconst toFetchRequest = async (req: IncomingMessage, origin: string): Promise<Request> => {\n const url = new URL(req.url ?? \"/\", origin);\n const method = req.method ?? \"GET\";\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) {\n // eslint-disable-next-line no-continue -- forEach would require push-style state mutation; continue keeps the filter inline\n continue;\n }\n if (Array.isArray(value)) {\n for (const entry of value) {\n headers.append(key, entry);\n }\n } else {\n headers.append(key, value);\n }\n }\n const init: RequestInit = { method, headers };\n if (method !== \"GET\" && method !== \"HEAD\") {\n const body = await readBody(req);\n init.body = new Uint8Array(body);\n }\n return new Request(url, init);\n};\n\nconst writeFetchResponse = async (res: ServerResponse, response: Response): Promise<void> => {\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n const body = await response.arrayBuffer();\n res.end(Buffer.from(body));\n};\n\nconst handleIncoming = async (\n req: IncomingMessage,\n res: ServerResponse,\n session: BrowserLoginSession,\n): Promise<void> => {\n try {\n const request = await toFetchRequest(req, \"http://127.0.0.1\");\n const response = await session.handleRequest(request);\n await writeFetchResponse(res, response);\n } catch {\n res.statusCode = 500;\n res.end(\"Local callback failed\");\n }\n};\n\nexport const createBrowserLoginServer = async (\n options: CreateBrowserLoginServerOptions = {},\n): Promise<BrowserLoginServer> => {\n const session = createBrowserLoginSession(options);\n const server: Server = createServer((req, res) => {\n // eslint-disable-next-line promise/prefer-await-to-then -- node createServer callback is sync; rejections already swallowed inside handleIncoming, so .catch here is a safety net, not a control-flow then()\n handleIncoming(req, res, session).catch(() => undefined);\n });\n\n server.listen(0, \"127.0.0.1\");\n await once(server, \"listening\");\n const address = server.address();\n const port = address !== null && typeof address === \"object\" ? address.port : 0;\n\n return {\n callbackUrl: `http://127.0.0.1:${port}${session.callbackPath}`,\n waitForToken: session.waitForToken,\n stop: () => {\n session.dispose();\n server.close();\n },\n };\n};\n","import { Command } from \"@effect/platform\";\nimport { Console, Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { createBrowserLoginServer } from \"../lib/browser-login\";\nimport { promptPassword } from \"../lib/prompts\";\nimport { AuthStore } from \"../services/auth-store\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { ConfigStore } from \"../services/config-store\";\n\nconst buildOpenBrowserCommand = (platform: NodeJS.Platform, url: string) => {\n if (platform === \"darwin\") {\n return Command.make(\"open\", url);\n }\n if (platform === \"win32\") {\n return Command.make(\"cmd\", \"/c\", \"start\", \"\", url);\n }\n return Command.make(\"xdg-open\", url);\n};\n\nconst openBrowser = (\n url: string,\n): Effect.Effect<void, never, CliRuntime | CommandExecutor.CommandExecutor> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const command = buildOpenBrowserCommand(runtime.platform, url);\n\n const opened = yield* Command.exitCode(command).pipe(\n Effect.map((code) => code === 0),\n Effect.catchAll(() => Effect.succeed(false)),\n );\n\n if (!opened) {\n yield* Console.log(`Open this URL manually:\\n${url}`);\n }\n });\n\nconst browserLogin = Effect.scoped(\n Effect.gen(function* () {\n const configStore = yield* ConfigStore;\n const authStore = yield* AuthStore;\n const webUrl = yield* configStore.getWebUrl;\n\n const loginServer = yield* Effect.acquireRelease(\n Effect.promise(async () => createBrowserLoginServer()),\n (server) => Effect.sync(server.stop),\n );\n\n const loginUrl = `${webUrl}/auth/cli-login?callbackUrl=${encodeURIComponent(loginServer.callbackUrl)}`;\n\n yield* Console.log(\"Opening browser for better-update login...\");\n yield* Console.log(\"\");\n yield* openBrowser(loginUrl);\n\n const token = yield* loginServer.waitForToken;\n yield* authStore.saveToken(token);\n yield* Console.log(\"\");\n yield* Console.log(\"Logged in successfully. Token saved to ~/.better-update/auth.json\");\n }),\n);\n\nconst manualLogin = Effect.gen(function* () {\n yield* Console.log(\"Log in to better-update with an existing API key\");\n yield* Console.log(\"Get your API key from the dashboard > API Keys page\");\n yield* Console.log(\"\");\n\n const token = yield* promptPassword(\"Paste your API key (from dashboard > API Keys):\");\n const authStore = yield* AuthStore;\n yield* authStore.saveToken(token);\n yield* Console.log(\"\");\n yield* Console.log(\"Logged in successfully. Token saved to ~/.better-update/auth.json\");\n});\n\nexport const runLogin = (options: { readonly manualApiKey: boolean }) =>\n Effect.gen(function* () {\n if (options.manualApiKey) {\n yield* manualLogin;\n return;\n }\n\n yield* browserLogin;\n });\n","import { defineCommand } from \"citty\";\n\nimport { runLogin } from \"../application/login\";\nimport { runEffect } from \"../lib/citty-effect\";\n\nexport const loginCommand = defineCommand({\n meta: { name: \"login\", description: \"Log in to better-update\" },\n args: {\n \"api-key\": {\n type: \"boolean\",\n description: \"Paste an API key manually instead of opening the browser\",\n },\n },\n run: async ({ args }) => runEffect(runLogin({ manualApiKey: args[\"api-key\"] ?? false })),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { AuthStore } from \"../services/auth-store\";\n\nexport const logoutCommand = defineCommand({\n meta: { name: \"logout\", description: \"Remove the stored auth token\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const authStore = yield* AuthStore;\n yield* authStore.clearToken;\n yield* Console.log(\"Logged out. Auth token removed.\");\n }),\n ),\n});\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../lib/exit-codes\";\nimport { printHuman } from \"../lib/output\";\nimport { promptConfirm } from \"../lib/prompts\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\ninterface LegacyTemplate {\n readonly expo?: {\n readonly extra?: {\n readonly betterUpdate?: {\n readonly profiles?: unknown;\n readonly [key: string]: unknown;\n };\n readonly [key: string]: unknown;\n };\n readonly [key: string]: unknown;\n };\n}\n\nconst readAppJson = (projectRoot: string): LegacyTemplate | null => {\n const path = join(projectRoot, \"app.json\");\n if (!existsSync(path)) {\n return null;\n }\n const raw = readFileSync(path, \"utf8\");\n // eslint-disable-next-line typescript/no-unsafe-type-assertion -- narrowing JSON.parse result; downstream code only reads known optional shape\n return JSON.parse(raw) as LegacyTemplate;\n};\n\nconst writeAppJson = (projectRoot: string, content: unknown): void => {\n writeFileSync(join(projectRoot, \"app.json\"), `${JSON.stringify(content, null, 2)}\\n`);\n};\n\nconst writeEasJson = (projectRoot: string, profiles: unknown): void => {\n writeFileSync(join(projectRoot, \"eas.json\"), `${JSON.stringify({ build: profiles }, null, 2)}\\n`);\n};\n\nexport const migrateConfigCommand = defineCommand({\n meta: {\n name: \"migrate-config\",\n description:\n \"Migrate legacy `extra.betterUpdate.profiles` (in app.json) to a sibling `eas.json` file\",\n },\n args: {\n yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const root = yield* runtime.cwd;\n const appJson = readAppJson(root);\n if (!appJson) {\n return yield* new InvalidArgumentError({\n message: `No app.json found at ${root}.`,\n });\n }\n const profiles = appJson.expo?.extra?.betterUpdate?.profiles;\n if (profiles === undefined) {\n yield* printHuman(\n \"No legacy `extra.betterUpdate.profiles` found in app.json — nothing to migrate.\",\n );\n return undefined;\n }\n if (existsSync(join(root, \"eas.json\"))) {\n return yield* new InvalidArgumentError({\n message:\n \"eas.json already exists. Manual review required — refusing to overwrite. Remove eas.json first if you want to regenerate.\",\n });\n }\n if (!args.yes) {\n const confirmed = yield* promptConfirm(\n `Move profiles to eas.json and strip from app.json?`,\n { initialValue: true },\n );\n if (!confirmed) {\n yield* printHuman(\"Cancelled.\");\n return undefined;\n }\n }\n writeEasJson(root, profiles);\n // Strip profiles, keeping any other betterUpdate fields (e.g. projectId).\n const clone = structuredClone(appJson);\n const extra = clone.expo?.extra;\n const betterUpdate = extra?.betterUpdate as Record<string, unknown> | undefined;\n if (betterUpdate) {\n delete betterUpdate[\"profiles\"];\n }\n writeAppJson(root, clone);\n yield* printHuman(\"Migrated profiles into eas.json. Legacy field removed from app.json.\");\n return undefined;\n }),\n ),\n});\n","import { spawn } from \"node:child_process\";\n\nimport { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { extractSlug, readExpoConfig } from \"../lib/expo-config\";\nimport { printHuman } from \"../lib/output\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { ConfigStore } from \"../services/config-store\";\n\nconst RESOURCE_PATHS: Record<string, string> = {\n builds: \"builds\",\n updates: \"updates\",\n channels: \"channels\",\n branches: \"branches\",\n credentials: \"credentials\",\n devices: \"apple-devices\",\n \"env-vars\": \"environment-variables\",\n webhooks: \"webhooks\",\n settings: \"settings\",\n};\n\nconst resolveOpenCommand = (platform: NodeJS.Platform): string => {\n if (platform === \"darwin\") {\n return \"open\";\n }\n if (platform === \"win32\") {\n return \"start\";\n }\n return \"xdg-open\";\n};\n\nconst openInBrowser = (url: string, platform: NodeJS.Platform): Effect.Effect<void> =>\n Effect.sync(() => {\n const child = spawn(resolveOpenCommand(platform), [url], {\n detached: true,\n stdio: \"ignore\",\n shell: true,\n });\n child.unref();\n });\n\nconst resolveTargetUrl = (resource: string | undefined) =>\n Effect.gen(function* () {\n const config = yield* ConfigStore;\n const webUrl = yield* config.getWebUrl;\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const expo = yield* readExpoConfig(projectRoot).pipe(Effect.option);\n const slug =\n expo._tag === \"Some\" ? yield* extractSlug(expo.value).pipe(Effect.option) : undefined;\n const projectPath = slug?._tag === \"Some\" ? `/projects/${slug.value}` : \"\";\n if (!resource || resource === \"project\") {\n return projectPath ? `${webUrl}${projectPath}` : webUrl;\n }\n const subPath = RESOURCE_PATHS[resource] ?? resource;\n return projectPath ? `${webUrl}${projectPath}/${subPath}` : `${webUrl}/${subPath}`;\n });\n\nexport const openCommand = defineCommand({\n meta: {\n name: \"open\",\n description: \"Open the dashboard URL (project or sub-resource) in the default browser\",\n },\n args: {\n resource: {\n type: \"positional\",\n required: false,\n description:\n \"Sub-resource: builds, updates, channels, branches, credentials, devices, env-vars, webhooks, settings\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const url = yield* resolveTargetUrl(args.resource);\n yield* printHuman(`Opening ${url}`);\n yield* openInBrowser(url, runtime.platform);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { printHuman, printKeyValue, printList } from \"../lib/output\";\nimport { apiClient } from \"../services/api-client\";\n\nconst listCommand = defineCommand({\n meta: { name: \"list\", description: \"List projects (most recently active first)\" },\n args: {\n query: { type: \"string\", description: \"Substring search on name or slug\" },\n sort: {\n type: \"string\",\n description: \"Sort key: lastActivityAt (default) or name\",\n default: \"lastActivityAt\",\n },\n limit: { type: \"string\", description: \"Page size (default 50, max 100)\", default: \"50\" },\n page: { type: \"string\", description: \"1-based page number\", default: \"1\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const sort = args.sort === \"name\" ? \"name\" : \"lastActivityAt\";\n const { items, total, page } = yield* api.projects.list({\n urlParams: {\n page: Number(args.page),\n limit: Number(args.limit),\n sort,\n ...(args.query ? { query: args.query } : {}),\n },\n });\n\n yield* printList(\n [\"ID\", \"Name\", \"Slug\", \"Last activity\"],\n items.map((project) => [project.id, project.name, project.slug, project.lastActivityAt]),\n \"No projects found.\",\n );\n yield* printHuman(`Page ${page} · ${items.length} of ${total} project(s)`);\n }),\n ),\n});\n\nconst createCommand = defineCommand({\n meta: { name: \"create\", description: \"Create a new project\" },\n args: {\n name: { type: \"string\", required: true, description: \"Display name\" },\n slug: { type: \"string\", required: true, description: \"URL-safe slug\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const project = yield* api.projects.create({\n payload: { name: args.name, slug: args.slug },\n });\n yield* printKeyValue([\n [\"ID\", project.id],\n [\"Name\", project.name],\n [\"Slug\", project.slug],\n [\"Created\", project.createdAt],\n ]);\n }),\n ),\n});\n\nconst getCommand = defineCommand({\n meta: { name: \"get\", description: \"Show a project\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Project ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const project = yield* api.projects.get({ path: { id: args.id } });\n yield* printKeyValue([\n [\"ID\", project.id],\n [\"Name\", project.name],\n [\"Slug\", project.slug],\n [\"Created\", project.createdAt],\n ]);\n }),\n ),\n});\n\nconst renameCommand = defineCommand({\n meta: { name: \"rename\", description: \"Rename a project\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Project ID\" },\n name: { type: \"string\", required: true, description: \"New display name\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const project = yield* api.projects.rename({\n path: { id: args.id },\n payload: { name: args.name },\n });\n yield* Console.log(`Project renamed to \"${project.name}\".`);\n }),\n ),\n});\n\nconst deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a project\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Project ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n yield* api.projects.delete({ path: { id: args.id } });\n yield* Console.log(`Project ${args.id} deleted.`);\n }),\n ),\n});\n\nexport const projectsCommand = defineCommand({\n meta: { name: \"projects\", description: \"Manage projects\" },\n subCommands: {\n list: listCommand,\n create: createCommand,\n get: getCommand,\n rename: renameCommand,\n delete: deleteCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { listAllCredentials } from \"../lib/credentials-manager\";\nimport { readProjectId } from \"../lib/expo-config\";\nimport { printKeyValue } from \"../lib/output\";\nimport { apiClient } from \"../services/api-client\";\n\nexport const statusCommand = defineCommand({\n meta: { name: \"status\", description: \"Show project status (credentials, builds)\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const { project, credentials, builds } = yield* Effect.all(\n {\n project: api.projects.get({ path: { id: projectId } }),\n credentials: listAllCredentials(api),\n builds: api.builds.list({ urlParams: { projectId } }),\n },\n { concurrency: \"unbounded\" },\n );\n\n yield* Console.log(\"Project\");\n yield* Console.log(\"-------\");\n yield* printKeyValue([\n [\"Name\", project.name],\n [\"ID\", project.id],\n [\"Slug\", project.slug],\n [\"Created\", project.createdAt],\n ]);\n\n yield* Console.log(\"\");\n yield* Console.log(\"Credentials\");\n yield* Console.log(\"-----------\");\n const iosCreds = credentials.filter((cred) => cred.platform === \"ios\").length;\n const androidCreds = credentials.filter((cred) => cred.platform === \"android\").length;\n yield* printKeyValue([\n [\"iOS\", String(iosCreds)],\n [\"Android\", String(androidCreds)],\n [\"Total\", String(credentials.length)],\n ]);\n\n yield* Console.log(\"\");\n yield* Console.log(\"Builds\");\n yield* Console.log(\"------\");\n const moreSuffix = builds.items.length < builds.total ? \"+\" : \"\";\n yield* printKeyValue([\n [\"Recent\", `${String(builds.items.length)}${moreSuffix}`],\n [\"Total\", String(builds.total)],\n ]);\n }),\n ),\n});\n","import path from \"node:path\";\n\nimport { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport {\n extractProjectId,\n getConfigFilePaths,\n readExpoConfig,\n writeExpoConfigPatch,\n} from \"../../lib/expo-config\";\nimport { printHuman, printKeyValue } from \"../../lib/output\";\nimport { ConfigStore } from \"../../services/config-store\";\n\ntype RuntimePolicy = \"appVersion\" | \"fingerprint\";\n\nconst RUNTIME_POLICIES: readonly RuntimePolicy[] = [\"appVersion\", \"fingerprint\"];\n\nconst isRuntimePolicy = (value: string): value is RuntimePolicy =>\n (RUNTIME_POLICIES as readonly string[]).includes(value);\n\nconst renderManualHint = (manifestUrl: string, policy: RuntimePolicy): string =>\n [\n \"Cannot write to a dynamic Expo config. Add these fields manually:\",\n \"\",\n ` runtimeVersion: { policy: \"${policy}\" },`,\n ` updates: { url: \"${manifestUrl}\" }`,\n ].join(\"\\n\");\n\nconst readExistingUpdateUrl = (config: Record<string, unknown>): string | undefined => {\n const { updates } = config;\n if (typeof updates !== \"object\" || updates === null || !(\"url\" in updates)) {\n return undefined;\n }\n const { url } = updates as { readonly url?: unknown };\n return typeof url === \"string\" ? url : undefined;\n};\n\nexport const configureCommand = defineCommand({\n meta: {\n name: \"configure\",\n description:\n \"Wire expo-updates plugin into your Expo config (runtimeVersion + updates.url for this project)\",\n },\n args: {\n \"runtime-policy\": {\n type: \"string\",\n default: \"appVersion\",\n description: \"Runtime version policy: appVersion or fingerprint\",\n },\n force: {\n type: \"boolean\",\n description: \"Overwrite existing runtimeVersion / updates.url fields\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n // eslint-disable-next-line eslint/max-statements -- linear orchestration: validate policy → read config/baseUrl → check existing → write or hint\n Effect.gen(function* () {\n if (!isRuntimePolicy(args[\"runtime-policy\"])) {\n return yield* new InvalidArgumentError({\n message: `Invalid --runtime-policy \"${args[\"runtime-policy\"]}\". Use \"appVersion\" or \"fingerprint\".`,\n });\n }\n const policy = args[\"runtime-policy\"];\n\n const configStore = yield* ConfigStore;\n const baseUrl = yield* configStore.getBaseUrl;\n\n const projectRoot = process.cwd();\n const expoConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(expoConfig);\n\n const manifestUrl = `${baseUrl}/manifest/${projectId}`;\n\n const existingRuntime = expoConfig.runtimeVersion;\n const existingUrl = readExistingUpdateUrl(expoConfig);\n\n if (!args.force && (existingRuntime !== undefined || existingUrl !== undefined)) {\n yield* Console.log(\"Expo config already has runtimeVersion or updates.url set:\");\n if (existingRuntime !== undefined) {\n yield* Console.log(` runtimeVersion: ${JSON.stringify(existingRuntime)}`);\n }\n if (existingUrl !== undefined) {\n yield* Console.log(` updates.url: ${existingUrl}`);\n }\n yield* Console.log(\"\");\n yield* Console.log(\"Pass --force to overwrite.\");\n return undefined;\n }\n\n const result = yield* writeExpoConfigPatch(projectRoot, {\n runtimeVersion: { policy },\n updates: { url: manifestUrl },\n });\n\n if (result.configPath === null) {\n yield* printHuman(renderManualHint(manifestUrl, policy));\n return undefined;\n }\n\n const paths = yield* getConfigFilePaths(projectRoot);\n const targetPath = paths.staticConfigPath\n ? path.relative(projectRoot, paths.staticConfigPath)\n : \"your Expo config\";\n\n yield* Console.log(`Wired expo-updates plugin into ${targetPath}.`);\n yield* printKeyValue([\n [\"runtimeVersion.policy\", policy],\n [\"updates.url\", manifestUrl],\n ]);\n return undefined;\n }),\n ),\n});\n","import { Data } from \"effect\";\n\nimport { resolveNamedResourceId as resolveNamedResourceIdBase } from \"../../lib/resolve-named-resource\";\n\nexport class UpdateCommandError extends Data.TaggedError(\"UpdateCommandError\")<{\n readonly message: string;\n}> {}\n\nexport const updateErrorExtras = {\n UpdateCommandError: 2,\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n EnvExportError: 7,\n UpdateRollbackError: 2,\n UpdatePromoteError: 2,\n} as const;\n\nexport const resolveNamedResourceId = (params: {\n readonly items: readonly { readonly id: string; readonly name: string }[];\n readonly kind: string;\n readonly name: string;\n}) => resolveNamedResourceIdBase(params, (message) => new UpdateCommandError({ message }));\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { apiClient } from \"../../services/api-client\";\nimport { updateErrorExtras } from \"./helpers\";\n\nexport const deleteCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete an update group\" },\n args: {\n groupId: { type: \"positional\", required: true, description: \"Update group ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.updates.deleteGroup({ path: { groupId: args.groupId } });\n yield* Console.log(\n `Deleted ${String(result.deleted)} update(s) from group ${args.groupId}.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../lib/cli-schemas\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printHuman } from \"../../lib/output\";\nimport { promptSelect, promptText } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\nimport { resolveNamedResourceId, UpdateCommandError, updateErrorExtras } from \"./helpers\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\nconst promptGroupId = (api: ApiClient, projectId: string, branchName: string | undefined) =>\n Effect.gen(function* () {\n const branches = yield* drainPages((page) =>\n api.branches.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const branchId = branchName\n ? yield* resolveNamedResourceId({ items: branches, kind: \"Branch\", name: branchName })\n : undefined;\n const { items } = yield* api.updates.list({\n urlParams: {\n projectId,\n ...(branchId === undefined ? {} : { branchId }),\n limit: 50,\n },\n });\n const groups = new Map<string, { readonly groupId: string; readonly message: string | null }>();\n for (const update of items) {\n if (!groups.has(update.groupId)) {\n groups.set(update.groupId, { groupId: update.groupId, message: update.message });\n }\n }\n if (groups.size === 0) {\n return yield* new UpdateCommandError({\n message: \"No update groups found to edit.\",\n });\n }\n return yield* promptSelect<string>(\n \"Select an update group\",\n [...groups.values()].map((group) => ({\n value: group.groupId,\n label: `${group.groupId} — ${group.message ?? \"(no message)\"}`,\n })),\n );\n });\n\nexport const editCommand = defineCommand({\n meta: {\n name: \"edit\",\n description: \"Edit rollout percentage for every update in a group\",\n },\n args: {\n groupId: { type: \"positional\", required: false, description: \"Update group ID\" },\n branch: {\n type: \"string\",\n description: \"Filter interactive group selection to a single branch\",\n },\n \"rollout-percentage\": {\n type: \"string\",\n description: \"New rollout percentage (1-100)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const groupId = args.groupId ?? (yield* promptGroupId(api, projectId, args.branch));\n\n const rolloutRaw =\n args[\"rollout-percentage\"] ?? (yield* promptText(\"New rollout percentage (1-100)\"));\n const percentage = yield* parseRolloutPercentage(rolloutRaw, \"rollout-percentage\");\n\n const allUpdates = yield* drainPages((page) =>\n api.updates.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const inGroup = allUpdates.filter((update) => update.groupId === groupId);\n if (inGroup.length === 0) {\n return yield* new UpdateCommandError({\n message: `No updates found for group ${groupId}.`,\n });\n }\n\n yield* Effect.forEach(\n inGroup,\n (update) =>\n api.updates.editRollout({\n path: { id: update.id },\n payload: { percentage },\n }),\n { concurrency: 2 },\n );\n\n yield* printHuman(\n `Set rollout to ${String(percentage)}% for ${String(inGroup.length)} update(s) in group ${groupId}.`,\n );\n return undefined;\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printJson, printKeyValue, printTable } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\nimport { UpdateCommandError, updateErrorExtras } from \"./helpers\";\n\nexport const insightsCommand = defineCommand({\n meta: {\n name: \"insights\",\n description: \"Show traffic and adoption stats for every update in a group\",\n },\n args: {\n groupId: { type: \"positional\", required: true, description: \"Update group ID\" },\n period: { type: \"enum\", options: [\"1d\", \"7d\", \"30d\", \"90d\"], description: \"Time window\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const allUpdates = yield* drainPages((page) =>\n api.updates.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const inGroup = allUpdates.filter((update) => update.groupId === args.groupId);\n if (inGroup.length === 0) {\n return yield* new UpdateCommandError({\n message: `No updates found for group ${args.groupId}.`,\n });\n }\n\n const periodFilter = args.period ? { period: args.period } : {};\n const stats = yield* Effect.forEach(\n inGroup,\n (update) =>\n api.analytics\n .updates({\n urlParams: { projectId, updateId: update.id, ...periodFilter },\n })\n .pipe(Effect.map((result) => ({ update, result }))),\n { concurrency: 4 },\n );\n\n const totalRequests = stats.reduce((sum, stat) => sum + stat.result.totalRequests, 0);\n const totalDevices = stats.reduce((sum, stat) => sum + stat.result.uniqueDevices, 0);\n const totalManifest = stats.reduce(\n (sum, stat) => sum + stat.result.byResponseType.manifest,\n 0,\n );\n const totalDirective = stats.reduce(\n (sum, stat) => sum + stat.result.byResponseType.directive,\n 0,\n );\n const totalNoUpdate = stats.reduce(\n (sum, stat) => sum + stat.result.byResponseType.no_update,\n 0,\n );\n\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson({\n groupId: args.groupId,\n updates: inGroup.length,\n totalRequests,\n totalDevices,\n byResponseType: {\n manifest: totalManifest,\n directive: totalDirective,\n no_update: totalNoUpdate,\n },\n items: stats.map(({ update, result }) => ({\n updateId: update.id,\n platform: update.platform,\n totalRequests: result.totalRequests,\n uniqueDevices: result.uniqueDevices,\n byResponseType: result.byResponseType,\n })),\n });\n return undefined;\n }\n\n yield* printKeyValue([\n [\"Group ID\", args.groupId],\n [\"Updates\", String(inGroup.length)],\n [\"Total Requests\", String(totalRequests)],\n [\"Unique Devices (sum)\", String(totalDevices)],\n [\"Manifest\", String(totalManifest)],\n [\"Directive\", String(totalDirective)],\n [\"No Update\", String(totalNoUpdate)],\n ]);\n yield* printTable(\n [\"Update ID\", \"Platform\", \"Requests\", \"Devices\", \"Manifest\", \"Directive\", \"No Update\"],\n stats.map(({ update, result }) => [\n update.id,\n update.platform,\n String(result.totalRequests),\n String(result.uniqueDevices),\n String(result.byResponseType.manifest),\n String(result.byResponseType.directive),\n String(result.byResponseType.no_update),\n ]),\n );\n return undefined;\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseLimit } from \"../../lib/cli-schemas\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printList } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { resolveNamedResourceId, updateErrorExtras } from \"./helpers\";\n\nexport const listCommand = defineCommand({\n meta: { name: \"list\", description: \"List recent updates\" },\n args: {\n branch: { type: \"string\", description: \"Filter by branch name\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\"],\n description: \"Filter by platform\",\n },\n limit: { type: \"string\", default: \"20\", description: \"Max rows (default 20)\" },\n offset: { type: \"string\", description: \"Pagination offset (page number, 1-based)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const limit = yield* parseLimit(args.limit, 20);\n const page = args.offset === undefined ? undefined : yield* parseLimit(args.offset, 1);\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n const branches = yield* drainPages((cursor) =>\n api.branches.list({\n urlParams: { projectId, limit: 100, page: cursor },\n }),\n );\n\n const branchId = args.branch\n ? yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: args.branch,\n })\n : undefined;\n\n const { items } = yield* api.updates.list({\n urlParams: {\n projectId,\n ...(branchId === undefined ? {} : { branchId }),\n ...(args.platform === undefined ? {} : { platform: args.platform }),\n ...(page === undefined ? {} : { page }),\n limit,\n },\n });\n\n const branchNames = new Map(branches.map((item) => [item.id, item.name]));\n\n yield* printList(\n [\"Update ID\", \"Group\", \"Branch\", \"Platform\", \"Runtime\", \"Rollout\", \"Rollback\", \"Created\"],\n items.map((item) => [\n item.id,\n item.groupId,\n branchNames.get(item.branchId) ?? item.branchId,\n item.platform,\n item.runtimeVersion,\n `${String(item.rolloutPercentage)}%`,\n item.isRollback ? \"yes\" : \"no\",\n item.createdAt,\n ]),\n \"No updates found.\",\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport { formatCause } from \"./format-error\";\n\nimport type { Platform } from \"./build-profile\";\n\nexport interface SignedPayload {\n readonly manifestBody: string;\n readonly signature: string;\n readonly certificateChain: string;\n}\n\nexport interface SignedPayloadFileSet {\n readonly manifestBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n}\n\nconst emptySignedPayloadFileSet = {\n manifestBodyFile: undefined,\n signatureFile: undefined,\n certificateChainFile: undefined,\n} as const satisfies SignedPayloadFileSet;\n\nconst hasAnySignedPayloadFile = (files: SignedPayloadFileSet) =>\n files.manifestBodyFile !== undefined ||\n files.signatureFile !== undefined ||\n files.certificateChainFile !== undefined;\n\nconst loadSignedPayloadFromFiles = <Err>(params: {\n readonly files: SignedPayloadFileSet;\n readonly label: string;\n readonly makeError: (message: string) => Err;\n}): Effect.Effect<SignedPayload | null, Err, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n if (!hasAnySignedPayloadFile(params.files)) {\n return null;\n }\n\n if (\n !params.files.manifestBodyFile ||\n !params.files.signatureFile ||\n !params.files.certificateChainFile\n ) {\n return yield* Effect.fail(\n params.makeError(\n `${params.label} requires ${[\n params.files.manifestBodyFile ? null : \"manifest body\",\n params.files.signatureFile ? null : \"signature\",\n params.files.certificateChainFile ? null : \"certificate chain\",\n ]\n .filter(Boolean)\n .join(\", \")} file inputs to be provided as a complete triplet.`,\n ),\n );\n }\n\n const [manifestBody, signature, certificateChain] = yield* Effect.all(\n [\n fileSystem.readFileString(params.files.manifestBodyFile),\n fileSystem.readFileString(params.files.signatureFile),\n fileSystem.readFileString(params.files.certificateChainFile),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.mapError((cause) =>\n params.makeError(`${params.label} failed to read signed inputs: ${formatCause(cause)}`),\n ),\n );\n\n return {\n manifestBody,\n signature: signature.trim(),\n certificateChain: certificateChain.trimEnd(),\n } as const satisfies SignedPayload;\n });\n\nexport const loadOptionalSignedPayload = loadSignedPayloadFromFiles;\n\nexport const loadSignedPublishPayloads = <Err>(params: {\n readonly platforms: readonly Platform[];\n readonly globalFiles: SignedPayloadFileSet;\n readonly platformFiles: Partial<Record<Platform, SignedPayloadFileSet>>;\n readonly makeError: (message: string) => Err;\n}): Effect.Effect<Partial<Record<Platform, SignedPayload>>, Err, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const targetedPlatforms = new Set(params.platforms);\n const nonTargetedPlatforms = ([\"ios\", \"android\"] as const).filter(\n (platform) =>\n !targetedPlatforms.has(platform) &&\n hasAnySignedPayloadFile(params.platformFiles[platform] ?? emptySignedPayloadFileSet),\n );\n if (nonTargetedPlatforms.length > 0) {\n return yield* Effect.fail(\n params.makeError(\n `Signed publish inputs were provided for non-targeted platform(s): ${nonTargetedPlatforms.join(\", \")}.`,\n ),\n );\n }\n\n const hasGlobalFiles = hasAnySignedPayloadFile(params.globalFiles);\n if (\n !hasGlobalFiles &&\n Object.values(params.platformFiles).every((files) => !hasAnySignedPayloadFile(files))\n ) {\n return {};\n }\n\n if (params.platforms.length > 1 && hasGlobalFiles) {\n return yield* Effect.fail(\n params.makeError(\n \"Signed multi-platform publish requires per-platform file sets. Use the --*-ios and --*-android options.\",\n ),\n );\n }\n\n if (params.platforms.length === 1 && hasGlobalFiles) {\n const [platform] = params.platforms;\n if (!platform) {\n return {};\n }\n if (hasAnySignedPayloadFile(params.platformFiles[platform] ?? emptySignedPayloadFileSet)) {\n return yield* Effect.fail(\n params.makeError(\n `Signed publish for ${platform} is ambiguous. Use either the generic file options or the ${platform}-specific file options, not both.`,\n ),\n );\n }\n\n const globalPayload = yield* loadSignedPayloadFromFiles({\n files: params.globalFiles,\n label: \"Signed publish\",\n makeError: params.makeError,\n });\n return globalPayload === null ? {} : { [platform]: globalPayload };\n }\n\n const platformPayloadEntries = yield* Effect.forEach(\n params.platforms,\n (platform) =>\n Effect.gen(function* () {\n const payload = yield* loadSignedPayloadFromFiles({\n files: params.platformFiles[platform] ?? emptySignedPayloadFileSet,\n label: `Signed publish for ${platform}`,\n makeError: params.makeError,\n });\n\n if (payload === null) {\n return yield* Effect.fail(\n params.makeError(\n `Signed multi-platform publish requires a signed payload for ${platform}.`,\n ),\n );\n }\n\n return [platform, payload] as const;\n }),\n { concurrency: 1 },\n );\n\n return Object.fromEntries(platformPayloadEntries) as Partial<Record<Platform, SignedPayload>>;\n });\n","import { Effect } from \"effect\";\n\nimport type { FileSystem } from \"@effect/platform\";\n\nimport { UpdatePromoteError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\nimport { loadOptionalSignedPayload } from \"../lib/signed-payloads\";\nimport { apiClient } from \"../services/api-client\";\n\nimport type { AuthRequiredError } from \"../lib/exit-codes\";\nimport type { ApiClientService } from \"../services/api-client\";\n\nexport interface RunUpdatePromoteOptions {\n readonly updateId: string;\n readonly channel: string;\n readonly manifestBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n}\n\nexport interface UpdatePromoteResult {\n readonly sourceUpdateId: string;\n readonly channel: string;\n readonly updateId: string;\n}\n\nexport const runUpdatePromote = (\n options: RunUpdatePromoteOptions,\n): Effect.Effect<\n UpdatePromoteResult,\n AuthRequiredError | UpdatePromoteError,\n ApiClientService | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const signedPayload = yield* loadOptionalSignedPayload({\n files: {\n manifestBodyFile: options.manifestBodyFile,\n signatureFile: options.signatureFile,\n certificateChainFile: options.certificateChainFile,\n },\n label: \"Signed promote\",\n makeError: (message) => new UpdatePromoteError({ message }),\n });\n\n const result = yield* api.updates\n .republish({\n payload: {\n sourceUpdateId: options.updateId,\n destinationChannel: options.channel,\n ...(signedPayload\n ? {\n signedUpdates: [\n {\n sourceUpdateId: options.updateId,\n manifestBody: signedPayload.manifestBody,\n signature: signedPayload.signature,\n certificateChain: signedPayload.certificateChain,\n },\n ],\n }\n : {}),\n },\n })\n .pipe(\n Effect.catchIf(\n (cause): cause is Exclude<typeof cause, AuthRequiredError> =>\n (cause as { readonly _tag?: string })._tag !== \"AuthRequiredError\",\n (cause) =>\n new UpdatePromoteError({\n message: `Failed to promote update: ${formatCause(cause)}`,\n }),\n ),\n );\n\n const [promotedUpdate] = result.updates;\n if (!promotedUpdate) {\n return yield* new UpdatePromoteError({\n message: \"Promote completed without returning a promoted update.\",\n });\n }\n\n return {\n sourceUpdateId: options.updateId,\n channel: options.channel,\n updateId: promotedUpdate.id,\n } as const satisfies UpdatePromoteResult;\n });\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdatePromote } from \"../../application/update-promote\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { updateErrorExtras } from \"./helpers\";\n\nexport const promoteCommand = defineCommand({\n meta: { name: \"promote\", description: \"Promote an existing update to a channel\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Source update ID\" },\n channel: { type: \"string\", required: true, description: \"Target channel name\" },\n \"manifest-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const result = yield* runUpdatePromote({\n updateId: args.updateId,\n channel: args.channel,\n manifestBodyFile: args[\"manifest-body-file\"],\n signatureFile: args[\"signature-file\"],\n certificateChainFile: args[\"certificate-chain-file\"],\n });\n\n yield* Console.log(\n `Promoted update ${result.sourceUpdateId} to channel \"${result.channel}\" as update ${result.updateId}.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import path from \"node:path\";\n\nimport { asRecord } from \"@better-update/type-guards\";\nimport { Command, FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { BuildFailedError, UpdatePublishError } from \"./exit-codes\";\n\nimport type { Platform } from \"./build-profile\";\n\nexport interface ExportedUpdateAssetFile {\n readonly path: string;\n readonly key: string;\n readonly fileExt: string;\n readonly contentType: string;\n readonly isLaunch: boolean;\n}\n\ninterface ReadExpoPublicConfigOptions {\n readonly projectRoot: string;\n readonly envVars: Record<string, string>;\n}\n\ninterface RunExpoExportOptions extends ReadExpoPublicConfigOptions {\n readonly exportDir: string;\n readonly platform: Platform;\n readonly clear: boolean;\n readonly noBytecode?: boolean;\n readonly sourceMaps?: boolean;\n}\n\ninterface ReadExpoExportAssetsOptions {\n readonly exportDir: string;\n readonly platform: Platform;\n}\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined;\n\nconst normalizeExtension = (value: string | undefined): string | undefined => {\n if (!value) {\n return undefined;\n }\n return value.startsWith(\".\") ? value.slice(1) : value;\n};\n\nconst inferContentType = (fileExt: string, isLaunch: boolean): string => {\n const normalized = fileExt.toLowerCase();\n if (isLaunch || normalized === \"js\" || normalized === \"hbc\" || normalized === \"bundle\") {\n return \"application/javascript\";\n }\n\n switch (normalized) {\n case \"png\": {\n return \"image/png\";\n }\n case \"jpg\":\n case \"jpeg\": {\n return \"image/jpeg\";\n }\n case \"webp\": {\n return \"image/webp\";\n }\n case \"gif\": {\n return \"image/gif\";\n }\n case \"svg\": {\n return \"image/svg+xml\";\n }\n case \"json\": {\n return \"application/json\";\n }\n case \"mp4\": {\n return \"video/mp4\";\n }\n case \"mp3\": {\n return \"audio/mpeg\";\n }\n case \"wav\": {\n return \"audio/wav\";\n }\n case \"ttf\": {\n return \"font/ttf\";\n }\n case \"otf\": {\n return \"font/otf\";\n }\n case \"woff\": {\n return \"font/woff\";\n }\n case \"woff2\": {\n return \"font/woff2\";\n }\n default: {\n return \"application/octet-stream\";\n }\n }\n};\n\nconst makeBunxCommand = (...args: readonly string[]): Command.Command =>\n Command.make(\"bunx\", ...args);\n\nconst runCommand = (\n cmd: Command.Command,\n step: string,\n): Effect.Effect<void, BuildFailedError, CommandExecutor.CommandExecutor> =>\n Command.exitCode(cmd.pipe(Command.stdout(\"inherit\"), Command.stderr(\"inherit\"))).pipe(\n Effect.mapError(\n (cause) =>\n new BuildFailedError({\n step,\n exitCode: 1,\n message: `${step} failed to spawn: ${String(cause)}`,\n }),\n ),\n Effect.flatMap((code) =>\n code === 0\n ? Effect.void\n : Effect.fail(\n new BuildFailedError({\n step,\n exitCode: code,\n message: `${step} exited with code ${code}`,\n }),\n ),\n ),\n );\n\nexport const readExpoPublicConfig = ({\n projectRoot,\n envVars,\n}: ReadExpoPublicConfigOptions): Effect.Effect<\n Record<string, unknown>,\n UpdatePublishError,\n CliRuntime | CommandExecutor.CommandExecutor\n> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n const stdout = yield* Command.string(\n makeBunxCommand(\"expo\", \"config\", \"--type\", \"public\", \"--json\").pipe(\n Command.workingDirectory(projectRoot),\n Command.env(commandEnv),\n ),\n ).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to read Expo public config: ${String(cause)}`,\n }),\n ),\n );\n\n const parsed = yield* Effect.try({\n try: () => JSON.parse(stdout) as unknown,\n catch: () =>\n new UpdatePublishError({\n message: \"Expo public config output was not valid JSON.\",\n }),\n });\n\n const config = asRecord(parsed);\n if (!config) {\n return yield* new UpdatePublishError({\n message: \"Expo public config did not decode to a JSON object.\",\n });\n }\n\n return config;\n });\n\nexport const runExpoExport = ({\n projectRoot,\n exportDir,\n platform,\n envVars,\n clear,\n noBytecode,\n sourceMaps,\n}: RunExpoExportOptions): Effect.Effect<\n void,\n BuildFailedError,\n CliRuntime | CommandExecutor.CommandExecutor\n> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const commandEnv = yield* runtime.commandEnvironment(envVars);\n const args = [\n \"expo\",\n \"export\",\n \"--platform\",\n platform,\n \"--output-dir\",\n exportDir,\n \"--dump-assetmap\",\n ];\n if (clear) {\n args.push(\"--clear\");\n }\n if (noBytecode === true) {\n args.push(\"--no-bytecode\");\n }\n if (sourceMaps === true) {\n args.push(\"--source-maps\");\n }\n\n return yield* runCommand(\n makeBunxCommand(...args).pipe(Command.workingDirectory(projectRoot), Command.env(commandEnv)),\n `expo export ${platform}`,\n );\n });\n\nexport const readExpoExportAssets = ({\n exportDir,\n platform,\n}: ReadExpoExportAssetsOptions): Effect.Effect<\n readonly ExportedUpdateAssetFile[],\n UpdatePublishError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const metadataPath = path.join(exportDir, \"metadata.json\");\n const metadataText = yield* fs.readFileString(metadataPath).pipe(\n Effect.mapError(\n () =>\n new UpdatePublishError({\n message: `Expected Expo export metadata at ${metadataPath}.`,\n }),\n ),\n );\n\n const metadata = yield* Effect.try({\n try: () => JSON.parse(metadataText) as unknown,\n catch: () =>\n new UpdatePublishError({\n message: `Failed to parse ${metadataPath} as JSON.`,\n }),\n });\n\n const platformMetadata = asRecord(asRecord(asRecord(metadata)?.[\"fileMetadata\"])?.[platform]);\n const bundlePath = asString(platformMetadata?.[\"bundle\"]);\n if (!bundlePath) {\n return yield* new UpdatePublishError({\n message: `Expo export did not contain a bundle path for platform \"${platform}\".`,\n });\n }\n\n const bundleExt = normalizeExtension(path.extname(bundlePath)) ?? \"js\";\n const rawAssets = Array.isArray(platformMetadata?.[\"assets\"]) ? platformMetadata[\"assets\"] : [];\n\n // eslint-disable-next-line unicorn/no-array-method-this-argument -- Effect.forEach, not Array.prototype.forEach; the second arg is a mapping effect, not a thisArg\n const assets = yield* Effect.forEach(rawAssets, (rawAsset, index) =>\n Effect.gen(function* () {\n const asset = asRecord(rawAsset);\n const assetPath = asString(asset?.[\"path\"]);\n if (!assetPath) {\n return yield* new UpdatePublishError({\n message: `Expo export asset #${String(index + 1)} is missing its \"path\" field.`,\n });\n }\n\n const fileExt =\n normalizeExtension(asString(asset?.[\"ext\"])) ??\n normalizeExtension(path.extname(assetPath)) ??\n \"bin\";\n\n return {\n path: path.join(exportDir, assetPath),\n key: path.posix.basename(assetPath),\n fileExt,\n contentType: inferContentType(fileExt, false),\n isLaunch: false,\n } as const satisfies ExportedUpdateAssetFile;\n }),\n );\n\n return [\n {\n path: path.join(exportDir, bundlePath),\n key: path.posix.basename(bundlePath),\n fileExt: bundleExt,\n contentType: inferContentType(bundleExt, true),\n isLaunch: true,\n } as const satisfies ExportedUpdateAssetFile,\n ...assets,\n ] as const;\n });\n","import type { Platform } from \"./build-profile\";\nimport type { ExpoConfig } from \"./expo-config\";\n\nexport type UpdatePlatformOption = Platform | \"all\";\n\nexport const resolveUpdatePlatforms = (\n config: ExpoConfig,\n requestedPlatform: UpdatePlatformOption,\n): readonly Platform[] => {\n if (requestedPlatform !== \"all\") {\n return [requestedPlatform] as const;\n }\n\n // Typeof null === \"object\" in JS, so an explicit null check is required to\n // Reject configs that opt a platform out via `ios: null` / `android: null`.\n return ([\"ios\", \"android\"] as const).filter(\n (platform) =>\n // eslint-disable-next-line typescript/no-unnecessary-condition -- runtime guards against `ios: null` / `android: null` even though the static type excludes null\n typeof config[platform] === \"object\" && config[platform] !== null,\n );\n};\n","import path from \"node:path\";\n\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport { UpdatePublishError } from \"../lib/exit-codes\";\nimport { formatCause } from \"../lib/format-error\";\n\nimport type { Platform } from \"../lib/build-profile\";\nimport type { apiClient } from \"../services/api-client\";\n\nexport interface PublishedPlatformMetadata {\n readonly platform: Platform;\n readonly updateId: string;\n readonly runtimeVersion: string;\n}\n\nexport const resolveChannelToBranch = (\n client: Effect.Effect.Success<typeof apiClient>,\n projectId: string,\n channelName: string,\n) =>\n Effect.gen(function* () {\n const channels = yield* client.channels.list({ urlParams: { projectId, limit: 100 } }).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to list channels: ${formatCause(cause)}`,\n }),\n ),\n );\n const match = channels.items.find((channel) => channel.name === channelName);\n if (!match) {\n return yield* new UpdatePublishError({\n message: `Channel \"${channelName}\" not found.`,\n });\n }\n const branches = yield* client.branches.list({ urlParams: { projectId, limit: 100 } }).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to list branches: ${formatCause(cause)}`,\n }),\n ),\n );\n const branch = branches.items.find((entry) => entry.id === match.branchId);\n if (!branch) {\n return yield* new UpdatePublishError({\n message: `Channel \"${channelName}\" maps to a branch (${match.branchId}) not in the project's branch list.`,\n });\n }\n return branch.name;\n });\n\nexport const emitMetadataFile = (input: {\n readonly dir: string;\n readonly groupId: string;\n readonly branch: string;\n readonly channel: string | undefined;\n readonly message: string;\n readonly results: readonly PublishedPlatformMetadata[];\n}) =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(input.dir, { recursive: true }).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to prepare metadata directory: ${formatCause(cause)}`,\n }),\n ),\n );\n const metadata = {\n groupId: input.groupId,\n branch: input.branch,\n ...(input.channel === undefined ? {} : { channel: input.channel }),\n message: input.message,\n updates: input.results.map((entry) => ({\n platform: entry.platform,\n updateId: entry.updateId,\n runtimeVersion: entry.runtimeVersion,\n })),\n };\n const filePath = path.join(input.dir, \"eas-update-metadata.json\");\n yield* fs.writeFileString(filePath, `${JSON.stringify(metadata, null, 2)}\\n`).pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to write ${filePath}: ${formatCause(cause)}`,\n }),\n ),\n );\n });\n","import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport { fromHex, toBase64Url } from \"@better-update/encoding\";\nimport { Effect } from \"effect\";\nimport { uniqBy } from \"es-toolkit\";\n\nimport type { CommandExecutor, FileSystem } from \"@effect/platform\";\n\nimport { readRuntimeVersionMeta } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { UpdatePublishError } from \"../lib/exit-codes\";\nimport { extractProjectId, extractSlug, readExpoConfig } from \"../lib/expo-config\";\nimport { readExpoExportAssets, readExpoPublicConfig, runExpoExport } from \"../lib/expo-export\";\nimport { formatCause } from \"../lib/format-error\";\nimport { readGitContext } from \"../lib/git-context\";\nimport { ensureRepoClean } from \"../lib/repo-clean\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { sha256File, sha256Namespaced } from \"../lib/sha256\";\nimport { loadSignedPublishPayloads } from \"../lib/signed-payloads\";\nimport { acquireBuildTempDir } from \"../lib/temp-dir\";\nimport { resolveUpdatePlatforms } from \"../lib/update-platforms\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { UpdateAssetUploader } from \"../services/update-asset-uploader\";\nimport { emitMetadataFile, resolveChannelToBranch } from \"./update-publish-helpers\";\n\nimport type { Platform } from \"../lib/build-profile\";\nimport type {\n AuthRequiredError,\n BuildProfileError,\n BuildFailedError,\n DirtyRepoError,\n InteractiveProhibitedError,\n ProjectNotLinkedError,\n EnvExportError,\n RuntimeVersionError,\n} from \"../lib/exit-codes\";\nimport type { ExpoConfig } from \"../lib/expo-config\";\nimport type { InteractiveMode } from \"../lib/interactive-mode\";\nimport type { SignedPayload } from \"../lib/signed-payloads\";\nimport type { ApiClientService } from \"../services/api-client\";\n\nexport interface RunUpdatePublishOptions {\n readonly branch: string | undefined;\n readonly channel: string | undefined;\n readonly platform: Platform | \"all\";\n readonly message: string | undefined;\n readonly auto: boolean;\n readonly environment: string;\n readonly clear: boolean;\n readonly allowDirty: boolean;\n readonly rolloutPercentage: number | undefined;\n readonly inputDir: string | undefined;\n readonly skipBundler: boolean;\n readonly emitMetadata: boolean;\n readonly noBytecode: boolean;\n readonly sourceMaps: boolean;\n readonly manifestBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n readonly manifestBodyFileIos: string | undefined;\n readonly signatureFileIos: string | undefined;\n readonly certificateChainFileIos: string | undefined;\n readonly manifestBodyFileAndroid: string | undefined;\n readonly signatureFileAndroid: string | undefined;\n readonly certificateChainFileAndroid: string | undefined;\n}\n\nexport interface PublishedPlatformResult {\n readonly platform: Platform;\n readonly updateId: string;\n readonly runtimeVersion: string;\n readonly uploadedAssets: number;\n readonly deduplicatedAssets: number;\n}\n\nexport interface PublishUpdatesResult {\n readonly groupId: string;\n readonly branch: string;\n readonly results: readonly PublishedPlatformResult[];\n}\n\ninterface PreparedAsset {\n readonly path: string;\n readonly key: string;\n readonly hash: string;\n readonly contentChecksum: string;\n readonly byteSize: number;\n readonly contentType: string;\n readonly fileExt: string;\n readonly isLaunch: boolean;\n}\n\nconst buildUpdateExtra = (\n expoClient: Record<string, unknown>,\n projectId: string,\n environment: string,\n) => ({\n expoClient,\n eas: { projectId },\n environment,\n});\n\nconst dedupeAssetsByHash = (assets: readonly PreparedAsset[]): readonly PreparedAsset[] =>\n uniqBy(assets, (asset) => asset.hash);\n\nconst preparePlatformAssets = ({\n exportDir,\n platform,\n}: {\n readonly exportDir: string;\n readonly platform: Platform;\n}): Effect.Effect<\n readonly PreparedAsset[],\n UpdatePublishError | BuildFailedError,\n FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const exportedAssets = yield* readExpoExportAssets({ exportDir, platform });\n return yield* Effect.forEach(\n exportedAssets,\n (asset) =>\n sha256File(asset.path).pipe(\n Effect.map(({ sha256: contentSha256Hex, byteSize }) => ({\n ...asset,\n hash: sha256Namespaced(asset.contentType, contentSha256Hex),\n contentChecksum: toBase64Url(fromHex(contentSha256Hex)),\n byteSize,\n })),\n ),\n { concurrency: 4 },\n );\n });\n\nconst publishPlatform = (params: {\n readonly projectRoot: string;\n readonly exportDir: string;\n readonly projectId: string;\n readonly slug: string;\n readonly branch: string;\n readonly groupId: string;\n readonly message: string;\n readonly environment: string;\n readonly environmentVars: Record<string, string>;\n readonly expoClientConfig: Record<string, unknown>;\n readonly clear: boolean;\n readonly expoConfig: ExpoConfig;\n readonly platform: Platform;\n readonly signedPayload: SignedPayload | null;\n readonly rolloutPercentage: number | undefined;\n readonly skipBundler: boolean;\n readonly noBytecode: boolean;\n readonly sourceMaps: boolean;\n}): Effect.Effect<\n PublishedPlatformResult,\n | AuthRequiredError\n | UpdatePublishError\n | BuildProfileError\n | BuildFailedError\n | RuntimeVersionError,\n | ApiClientService\n | CliRuntime\n | UpdateAssetUploader\n | CommandExecutor.CommandExecutor\n | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const assetUploader = yield* UpdateAssetUploader;\n\n const runtimeVersionMeta = readRuntimeVersionMeta(params.expoConfig);\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: runtimeVersionMeta.rawRuntimeVersion,\n appVersion: runtimeVersionMeta.appVersion,\n projectRoot: params.projectRoot,\n });\n\n if (!params.skipBundler) {\n yield* runExpoExport({\n projectRoot: params.projectRoot,\n exportDir: params.exportDir,\n platform: params.platform,\n envVars: params.environmentVars,\n clear: params.clear,\n noBytecode: params.noBytecode,\n sourceMaps: params.sourceMaps,\n });\n }\n\n const preparedAssets = yield* preparePlatformAssets({\n exportDir: params.exportDir,\n platform: params.platform,\n });\n const uniqueAssets = dedupeAssetsByHash(preparedAssets);\n\n const assetRegistration = yield* api.assets\n .upload({\n payload: {\n projectId: params.projectId,\n assets: uniqueAssets.map((asset) => ({\n hash: asset.hash,\n contentType: asset.contentType,\n fileExt: asset.fileExt,\n contentChecksum: asset.contentChecksum,\n })),\n },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to register ${params.platform} assets: ${formatCause(cause)}`,\n }),\n ),\n );\n\n const uploadDetailsByHash = new Map(\n assetRegistration.uploaded.map((asset) => [asset.hash, asset] as const),\n );\n yield* Effect.forEach(\n uniqueAssets.filter((asset) => uploadDetailsByHash.has(asset.hash)),\n (asset) =>\n Effect.gen(function* () {\n const detail = uploadDetailsByHash.get(asset.hash);\n if (!detail) {\n return yield* Effect.fail(\n new UpdatePublishError({\n message: `Missing upload details for asset ${asset.hash}`,\n }),\n );\n }\n return yield* assetUploader.uploadAssetBinary({\n path: asset.path,\n hash: asset.hash,\n byteSize: asset.byteSize,\n uploadUrl: detail.uploadUrl,\n uploadExpiresAt: detail.uploadExpiresAt,\n uploadHeaders: detail.uploadHeaders,\n });\n }),\n { concurrency: 4 },\n );\n\n const update = yield* api.updates\n .create({\n payload: {\n branch: params.branch,\n slug: params.slug,\n runtimeVersion,\n platform: params.platform,\n message: params.message,\n groupId: params.groupId,\n metadata: {},\n extra: buildUpdateExtra(params.expoClientConfig, params.projectId, params.environment),\n assets: preparedAssets.map((asset) => ({\n hash: asset.hash,\n key: asset.key,\n isLaunch: asset.isLaunch,\n contentChecksum: asset.contentChecksum,\n })),\n ...(params.signedPayload\n ? {\n manifestBody: params.signedPayload.manifestBody,\n signature: params.signedPayload.signature,\n certificateChain: params.signedPayload.certificateChain,\n }\n : {}),\n ...(params.rolloutPercentage === undefined\n ? {}\n : { rolloutPercentage: params.rolloutPercentage }),\n },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to publish ${params.platform} update: ${formatCause(cause)}`,\n }),\n ),\n );\n\n return {\n platform: params.platform,\n updateId: update.id,\n runtimeVersion,\n uploadedAssets: assetRegistration.uploaded.length,\n deduplicatedAssets: assetRegistration.deduplicated.length,\n } as const satisfies PublishedPlatformResult;\n });\n\nexport const runUpdatePublish = (\n options: RunUpdatePublishOptions,\n): Effect.Effect<\n PublishUpdatesResult,\n | AuthRequiredError\n | UpdatePublishError\n | ProjectNotLinkedError\n | BuildProfileError\n | RuntimeVersionError\n | EnvExportError\n | BuildFailedError\n | DirtyRepoError\n | InteractiveProhibitedError,\n | ApiClientService\n | CliRuntime\n | UpdateAssetUploader\n | CommandExecutor.CommandExecutor\n | FileSystem.FileSystem\n | InteractiveMode\n> =>\n Effect.scoped(\n // eslint-disable-next-line eslint/max-statements -- update publish orchestration is inherently sequential (read config → resolve runtime version → expo export → register assets → publish per platform); splitting further fragments the pipeline without improving readability\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const api = yield* apiClient;\n\n yield* ensureRepoClean({\n projectRoot,\n allowDirty: options.allowDirty,\n label: \"update publish\",\n });\n\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n\n const environmentVars = yield* pullEnvVars(api, {\n projectId,\n environment: options.environment,\n });\n\n // Read slug from the env-resolved config so dynamic configs that derive\n // slug from env vars publish under the same identity as `expo export`.\n const expoConfig = yield* readExpoConfig(projectRoot, environmentVars);\n const slug = yield* extractSlug(expoConfig);\n const platforms = resolveUpdatePlatforms(expoConfig, options.platform);\n if (platforms.length === 0) {\n return yield* new UpdatePublishError({\n message:\n 'No publishable platforms found in your Expo config. Add an \"ios\" or \"android\" section, or pass --platform explicitly.',\n });\n }\n const expoClientConfig = yield* readExpoPublicConfig({\n projectRoot,\n envVars: environmentVars,\n });\n const tempDir = yield* acquireBuildTempDir.pipe(\n Effect.mapError(\n (cause) =>\n new UpdatePublishError({\n message: `Failed to create a temporary export directory: ${formatCause(cause)}`,\n }),\n ),\n );\n let resolvedBranch = options.branch;\n let resolvedMessage = options.message;\n\n if (options.auto) {\n const gitContext = yield* readGitContext(projectRoot);\n if (!resolvedBranch) {\n if (!gitContext.ref) {\n return yield* new UpdatePublishError({\n message:\n \"Cannot infer branch from git. Ensure you are in a git repo with a checked-out branch, or provide --branch explicitly.\",\n });\n }\n resolvedBranch = gitContext.ref;\n }\n if (!resolvedMessage && gitContext.commitMessage) {\n resolvedMessage = gitContext.commitMessage;\n }\n }\n\n if (!resolvedBranch && options.channel !== undefined) {\n resolvedBranch = yield* resolveChannelToBranch(api, projectId, options.channel);\n }\n\n if (!resolvedBranch) {\n return yield* new UpdatePublishError({\n message:\n \"Missing --branch or --channel. Provide one explicitly or use --auto to infer from git.\",\n });\n }\n\n if (options.skipBundler && options.inputDir === undefined) {\n return yield* new UpdatePublishError({\n message: \"--skip-bundler requires --input-dir <path> pointing to a pre-bundled export.\",\n });\n }\n\n const sharedExportDir =\n options.inputDir === undefined ? undefined : path.resolve(projectRoot, options.inputDir);\n\n const branch = resolvedBranch;\n const groupId = randomUUID();\n const message = resolvedMessage ?? \"Publish via better-update CLI\";\n const signedPayloads = yield* loadSignedPublishPayloads({\n platforms,\n globalFiles: {\n manifestBodyFile: options.manifestBodyFile,\n signatureFile: options.signatureFile,\n certificateChainFile: options.certificateChainFile,\n },\n platformFiles: {\n ios: {\n manifestBodyFile: options.manifestBodyFileIos,\n signatureFile: options.signatureFileIos,\n certificateChainFile: options.certificateChainFileIos,\n },\n android: {\n manifestBodyFile: options.manifestBodyFileAndroid,\n signatureFile: options.signatureFileAndroid,\n certificateChainFile: options.certificateChainFileAndroid,\n },\n },\n makeError: (errorMessage) => new UpdatePublishError({ message: errorMessage }),\n });\n const results = yield* Effect.forEach(\n platforms,\n (platform) =>\n publishPlatform({\n projectRoot,\n exportDir: sharedExportDir ?? path.join(tempDir, `export-${platform}`),\n projectId,\n slug,\n branch,\n groupId,\n message,\n environment: options.environment,\n environmentVars,\n expoClientConfig,\n clear: options.clear,\n expoConfig,\n platform,\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- signedPayload absence means unsigned; null is correct downstream\n signedPayload: signedPayloads[platform] ?? null,\n rolloutPercentage: options.rolloutPercentage,\n skipBundler: options.skipBundler,\n noBytecode: options.noBytecode,\n sourceMaps: options.sourceMaps,\n }),\n { concurrency: 1 },\n );\n\n if (options.emitMetadata) {\n const dir = sharedExportDir ?? tempDir;\n yield* emitMetadataFile({\n dir,\n groupId,\n branch,\n channel: options.channel,\n message,\n results,\n });\n }\n\n return {\n groupId,\n branch,\n results,\n } as const satisfies PublishUpdatesResult;\n }),\n );\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdatePublish } from \"../../application/update-publish\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../lib/cli-schemas\";\nimport { printTable } from \"../../lib/output\";\n\nconst PUBLISH_EXIT_EXTRAS = {\n BuildProfileError: 2,\n RuntimeVersionError: 2,\n EnvExportError: 7,\n BuildFailedError: 6,\n UpdatePublishError: 7,\n DirtyRepoError: 3,\n} as const;\n\nexport const publishCommand = defineCommand({\n meta: { name: \"publish\", description: \"Publish a new OTA update group\" },\n args: {\n branch: { type: \"string\", description: \"Target branch name\" },\n channel: {\n type: \"string\",\n description: \"Channel name to route the update through (resolves to branch)\",\n },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Platform(s) to publish\",\n },\n message: { type: \"string\", description: \"Optional update message\" },\n environment: { type: \"string\", default: \"production\", description: \"Env vars scope\" },\n auto: { type: \"boolean\", description: \"Skip prompts (for CI)\" },\n clear: { type: \"boolean\", description: \"Drop existing assets before upload\" },\n \"rollout-percentage\": { type: \"string\", description: \"Initial rollout percentage (1-100)\" },\n \"input-dir\": {\n type: \"string\",\n description: \"Path to a pre-bundled Expo export directory (skips re-running expo export)\",\n },\n \"skip-bundler\": {\n type: \"boolean\",\n description: \"Skip running expo export — requires --input-dir to point at the bundle\",\n },\n \"emit-metadata\": {\n type: \"boolean\",\n description: \"Write eas-update-metadata.json into the export directory after publish\",\n },\n \"no-bytecode\": {\n type: \"boolean\",\n description: \"Disable Hermes bytecode compilation (emit raw JS)\",\n },\n \"source-maps\": {\n type: \"boolean\",\n description: \"Emit JavaScript source maps alongside bundles\",\n },\n \"manifest-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n \"manifest-body-file-ios\": { type: \"string\" },\n \"signature-file-ios\": { type: \"string\" },\n \"certificate-chain-file-ios\": { type: \"string\" },\n \"manifest-body-file-android\": { type: \"string\" },\n \"signature-file-android\": { type: \"string\" },\n \"certificate-chain-file-android\": { type: \"string\" },\n \"allow-dirty\": {\n type: \"boolean\",\n description: \"Proceed even with uncommitted git changes\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const rolloutPercentage = args[\"rollout-percentage\"]\n ? yield* parseRolloutPercentage(args[\"rollout-percentage\"], \"rollout-percentage\")\n : undefined;\n\n const result = yield* runUpdatePublish({\n branch: args.branch,\n channel: args.channel,\n platform: args.platform,\n message: args.message,\n auto: args.auto ?? false,\n environment: args.environment,\n clear: args.clear ?? false,\n allowDirty: args[\"allow-dirty\"] ?? false,\n rolloutPercentage,\n inputDir: args[\"input-dir\"],\n skipBundler: args[\"skip-bundler\"] ?? false,\n emitMetadata: args[\"emit-metadata\"] ?? false,\n noBytecode: args[\"no-bytecode\"] ?? false,\n sourceMaps: args[\"source-maps\"] ?? false,\n manifestBodyFile: args[\"manifest-body-file\"],\n signatureFile: args[\"signature-file\"],\n certificateChainFile: args[\"certificate-chain-file\"],\n manifestBodyFileIos: args[\"manifest-body-file-ios\"],\n signatureFileIos: args[\"signature-file-ios\"],\n certificateChainFileIos: args[\"certificate-chain-file-ios\"],\n manifestBodyFileAndroid: args[\"manifest-body-file-android\"],\n signatureFileAndroid: args[\"signature-file-android\"],\n certificateChainFileAndroid: args[\"certificate-chain-file-android\"],\n });\n\n yield* Console.log(\n `Published update group ${result.groupId} to branch \"${result.branch}\".`,\n );\n yield* Console.log(\"\");\n yield* printTable(\n [\"Platform\", \"Update ID\", \"Runtime Version\", \"Uploaded\", \"Reused\"],\n result.results.map((entry) => [\n entry.platform,\n entry.updateId,\n entry.runtimeVersion,\n String(entry.uploadedAssets),\n String(entry.deduplicatedAssets),\n ]),\n );\n }),\n PUBLISH_EXIT_EXTRAS,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../lib/cli-schemas\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printHuman, printJson, printTable } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\ninterface SourceArgs {\n readonly group?: string | undefined;\n readonly update?: string | undefined;\n readonly branch?: string | undefined;\n readonly channel?: string | undefined;\n readonly platform?: string | undefined;\n}\n\ninterface ResolvedSource {\n readonly sourceGroupId?: string | undefined;\n readonly sourceUpdateId?: string | undefined;\n}\n\nconst ensureSingleSource = (args: SourceArgs) => {\n const provided = [args.group, args.update, args.branch, args.channel].filter(\n (value) => value !== undefined && value.length > 0,\n );\n if (provided.length === 0) {\n return Effect.fail(\n new InvalidArgumentError({\n message: \"Pass one of --group, --update, --branch, or --channel to pick a source.\",\n }),\n );\n }\n if (provided.length > 1) {\n return Effect.fail(\n new InvalidArgumentError({\n message: \"Pass only one of --group, --update, --branch, or --channel.\",\n }),\n );\n }\n return Effect.void;\n};\n\nconst resolveChannelToBranchName = (api: ApiClient, projectId: string, channelName: string) =>\n Effect.gen(function* () {\n const channels = yield* drainPages((page) =>\n api.channels.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const channel = channels.find((entry) => entry.name === channelName);\n if (!channel) {\n return yield* new InvalidArgumentError({\n message: `Channel \"${channelName}\" not found.`,\n });\n }\n const branches = yield* drainPages((page) =>\n api.branches.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const branch = branches.find((entry) => entry.id === channel.branchId);\n if (!branch) {\n return yield* new InvalidArgumentError({\n message: `Channel \"${channelName}\" maps to branch ${channel.branchId} which is not in the project.`,\n });\n }\n return branch.name;\n });\n\nconst resolveSource = (api: ApiClient, args: SourceArgs) => {\n if (args.group !== undefined && args.group.length > 0) {\n return Effect.succeed<ResolvedSource>({ sourceGroupId: args.group });\n }\n if (args.update !== undefined && args.update.length > 0) {\n return Effect.succeed<ResolvedSource>({ sourceUpdateId: args.update });\n }\n if (args.channel !== undefined && args.channel.length > 0) {\n const { channel } = args;\n return Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const branchName = yield* resolveChannelToBranchName(api, projectId, channel);\n return yield* resolveLatestGroupOnBranch(api, { ...args, branch: branchName });\n });\n }\n return resolveLatestGroupOnBranch(api, args);\n};\n\nconst resolveLatestGroupOnBranch = (api: ApiClient, args: SourceArgs) =>\n Effect.gen(function* () {\n if (args.branch === undefined || args.branch.length === 0) {\n return yield* new InvalidArgumentError({ message: \"Missing --branch <branchName>\" });\n }\n const branchName = args.branch;\n const projectId = yield* readProjectId;\n const branches = yield* drainPages((page) =>\n api.branches.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const branch = branches.find((entry) => entry.name === branchName);\n if (!branch) {\n return yield* new InvalidArgumentError({\n message: `Branch \"${branchName}\" not found in project.`,\n });\n }\n const { items } = yield* api.updates.list({\n urlParams: { projectId, branchId: branch.id, limit: 20 },\n });\n const candidates =\n args.platform === undefined ? items : items.filter((item) => item.platform === args.platform);\n if (candidates.length === 0) {\n return yield* new InvalidArgumentError({\n message: `No updates found on branch \"${branchName}\"${\n args.platform === undefined ? \"\" : ` for platform ${args.platform}`\n }.`,\n });\n }\n const [latest] = candidates;\n if (!latest) {\n return yield* new InvalidArgumentError({\n message: `No updates found on branch \"${branchName}\".`,\n });\n }\n return { sourceGroupId: latest.groupId };\n });\n\ninterface DestinationArgs {\n readonly \"to-branch\"?: string | undefined;\n readonly \"to-channel\"?: string | undefined;\n}\n\ninterface ResolvedDestination {\n readonly destinationBranchId?: string | undefined;\n readonly destinationChannel?: string | undefined;\n}\n\nconst ensureSingleDestination = (args: DestinationArgs) => {\n const provided = [args[\"to-branch\"], args[\"to-channel\"]].filter(\n (value) => value !== undefined && value.length > 0,\n );\n if (provided.length === 0) {\n return Effect.fail(\n new InvalidArgumentError({\n message: \"Pass --to-branch <id> or --to-channel <name> to choose a destination.\",\n }),\n );\n }\n if (provided.length > 1) {\n return Effect.fail(\n new InvalidArgumentError({\n message: \"Pass only one of --to-branch or --to-channel.\",\n }),\n );\n }\n return Effect.void;\n};\n\nconst resolveDestination = (args: DestinationArgs): ResolvedDestination => {\n if (args[\"to-branch\"] !== undefined && args[\"to-branch\"].length > 0) {\n return { destinationBranchId: args[\"to-branch\"] };\n }\n return { destinationChannel: args[\"to-channel\"] };\n};\n\nexport const republishCommand = defineCommand({\n meta: {\n name: \"republish\",\n description:\n \"Copy an existing update (group, single update, or latest on a branch) to another branch or channel, preserving the runtime version\",\n },\n args: {\n group: { type: \"string\", description: \"Source group ID (republish both platforms together)\" },\n update: {\n type: \"string\",\n description: \"Source update ID (republish a single platform)\",\n },\n branch: {\n type: \"string\",\n description: \"Source branch name — republish the latest update group on this branch\",\n },\n channel: {\n type: \"string\",\n description: \"Source channel — republish the latest update group on the channel's branch\",\n },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\"],\n description:\n \"When using --branch/--channel/--group, restrict to a single platform's update id\",\n },\n \"to-branch\": {\n type: \"string\",\n description: \"Destination branch ID\",\n },\n \"to-channel\": {\n type: \"string\",\n description: \"Destination channel name (resolves to the channel's mapped branch)\",\n },\n message: { type: \"string\", description: \"Override the update message\" },\n \"rollout-percentage\": {\n type: \"string\",\n description: \"Set rollout percentage (1-100) on the republished group after publish\",\n },\n \"project-id\": {\n type: \"string\",\n description: \"Project ID (only required when destination is a name and no linked project)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n yield* ensureSingleSource(args);\n yield* ensureSingleDestination(args);\n\n const api = yield* apiClient;\n const rawSource = yield* resolveSource(api, args);\n const source = yield* applyPlatformFilter(api, rawSource, args);\n const destination = resolveDestination(args);\n\n const result = yield* api.updates.republish({\n payload: {\n ...source,\n ...destination,\n ...(args[\"project-id\"] === undefined ? {} : { projectId: args[\"project-id\"] }),\n ...(args.message === undefined ? {} : { message: args.message }),\n },\n });\n\n if (args[\"rollout-percentage\"] !== undefined) {\n const percentage = yield* parseRolloutPercentage(\n args[\"rollout-percentage\"],\n \"rollout-percentage\",\n );\n yield* Effect.forEach(\n result.updates,\n (update) =>\n api.updates.editRollout({\n path: { id: update.id },\n payload: { percentage },\n }),\n { concurrency: 2 },\n );\n }\n\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(result);\n return undefined;\n }\n yield* printHuman(`Republished ${String(result.updates.length)} update(s).`);\n yield* printTable(\n [\"ID\", \"Platform\", \"Runtime version\", \"Group ID\"],\n result.updates.map((update) => [\n update.id,\n update.platform,\n update.runtimeVersion,\n update.groupId,\n ]),\n );\n return undefined;\n }),\n ),\n});\n\nconst applyPlatformFilter = (api: ApiClient, source: ResolvedSource, args: SourceArgs) => {\n if (args.platform === undefined || source.sourceGroupId === undefined) {\n return Effect.succeed<ResolvedSource>(source);\n }\n return Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const all = yield* drainPages((page) =>\n api.updates.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const target = all.find(\n (entry) => entry.groupId === source.sourceGroupId && entry.platform === args.platform,\n );\n if (!target) {\n return yield* new InvalidArgumentError({\n message: `Group ${source.sourceGroupId} has no ${args.platform} update.`,\n });\n }\n return { sourceUpdateId: target.id };\n });\n};\n","export const buildRollbackDirectiveBody = (commitTime: string): string =>\n JSON.stringify({\n type: \"rollBackToEmbedded\",\n parameters: {\n commitTime,\n },\n });\n","import { randomUUID } from \"node:crypto\";\n\nimport { buildRollbackDirectiveBody } from \"@better-update/expo-protocol\";\nimport { isRecord } from \"@better-update/type-guards\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\n\nimport type { CommandExecutor } from \"@effect/platform\";\n\nimport { readRuntimeVersionMeta } from \"../lib/build-profile\";\nimport { pullEnvVars } from \"../lib/env-exporter\";\nimport { UpdateRollbackError } from \"../lib/exit-codes\";\nimport { extractProjectId, extractSlug, readExpoConfig } from \"../lib/expo-config\";\nimport { formatCause } from \"../lib/format-error\";\nimport { resolveRuntimeVersion } from \"../lib/runtime-version\";\nimport { resolveUpdatePlatforms } from \"../lib/update-platforms\";\nimport { apiClient } from \"../services/api-client\";\nimport { CliRuntime } from \"../services/cli-runtime\";\n\nimport type { Platform } from \"../lib/build-profile\";\nimport type {\n AuthRequiredError,\n BuildProfileError,\n EnvExportError,\n ProjectNotLinkedError,\n RuntimeVersionError,\n} from \"../lib/exit-codes\";\nimport type { UpdatePlatformOption } from \"../lib/update-platforms\";\nimport type { ApiClientService } from \"../services/api-client\";\n\ninterface CreateRollbackParams {\n readonly branch: string;\n readonly projectSlug: string;\n readonly runtimeVersion: string;\n readonly platform: Platform;\n readonly message: string;\n readonly groupId: string;\n readonly directiveBody: string;\n readonly signature: string | undefined;\n readonly certificateChain: string | undefined;\n}\n\nexport interface RollbackResultItem {\n readonly platform: Platform;\n readonly updateId: string;\n readonly runtimeVersion: string;\n}\n\nexport interface RunUpdateRollbackOptions {\n readonly branch: string;\n readonly platform: UpdatePlatformOption;\n readonly environment: string;\n readonly message: string | undefined;\n readonly commitTime: string | undefined;\n readonly directiveBodyFile: string | undefined;\n readonly signatureFile: string | undefined;\n readonly certificateChainFile: string | undefined;\n}\n\nexport interface UpdateRollbackResult {\n readonly groupId: string;\n readonly branch: string;\n readonly commitTime: string;\n readonly results: readonly RollbackResultItem[];\n}\n\ninterface SignedRollbackPayload {\n readonly directiveBody: string;\n readonly signature: string;\n readonly certificateChain: string;\n}\n\nconst resolveCommitTime = (input: string | undefined): Effect.Effect<string, UpdateRollbackError> =>\n Effect.gen(function* () {\n const commitTime = input ?? new Date().toISOString();\n if (Number.isNaN(Date.parse(commitTime))) {\n return yield* new UpdateRollbackError({\n message: \"commitTime must be a valid ISO 8601 timestamp.\",\n });\n }\n return commitTime;\n });\n\nconst extractDirectiveCommitTime = (\n directiveBody: string,\n): Effect.Effect<string, UpdateRollbackError> =>\n Effect.gen(function* () {\n const directive = yield* Effect.try({\n try: (): unknown => JSON.parse(directiveBody),\n catch: () =>\n new UpdateRollbackError({\n message: \"directiveBody must be valid JSON.\",\n }),\n });\n\n if (!isRecord(directive)) {\n return yield* new UpdateRollbackError({\n message: \"directiveBody must decode to a JSON object.\",\n });\n }\n\n if (directive[\"type\"] !== \"rollBackToEmbedded\") {\n return yield* new UpdateRollbackError({\n message: 'directiveBody.type must be \"rollBackToEmbedded\".',\n });\n }\n\n const { parameters } = directive;\n if (!isRecord(parameters)) {\n return yield* new UpdateRollbackError({\n message: \"directiveBody.parameters must be an object.\",\n });\n }\n\n const { commitTime } = parameters;\n if (typeof commitTime !== \"string\" || Number.isNaN(Date.parse(commitTime))) {\n return yield* new UpdateRollbackError({\n message: \"directiveBody.parameters.commitTime must be a valid ISO 8601 timestamp.\",\n });\n }\n\n return commitTime;\n });\n\nconst loadOptionalSignedRollbackPayload = (\n options: RunUpdateRollbackOptions,\n): Effect.Effect<SignedRollbackPayload | null, UpdateRollbackError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const hasAnySigningInput =\n options.directiveBodyFile !== undefined ||\n options.signatureFile !== undefined ||\n options.certificateChainFile !== undefined;\n\n if (!hasAnySigningInput) {\n return null;\n }\n\n if (!options.directiveBodyFile || !options.signatureFile || !options.certificateChainFile) {\n return yield* new UpdateRollbackError({\n message:\n \"Signed rollback requires --directive-body-file, --signature-file, and --certificate-chain-file together.\",\n });\n }\n\n const [directiveBody, signature, certificateChain] = yield* Effect.all(\n [\n fileSystem.readFileString(options.directiveBodyFile),\n fileSystem.readFileString(options.signatureFile),\n fileSystem.readFileString(options.certificateChainFile),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.mapError(\n (cause) =>\n new UpdateRollbackError({\n message: `Failed to read signed rollback inputs: ${formatCause(cause)}`,\n }),\n ),\n );\n\n return {\n directiveBody,\n signature: signature.trim(),\n certificateChain: certificateChain.trimEnd(),\n } satisfies SignedRollbackPayload;\n });\n\nconst createRollbackForPlatform = (\n params: CreateRollbackParams,\n): Effect.Effect<RollbackResultItem, AuthRequiredError | UpdateRollbackError, ApiClientService> =>\n Effect.gen(function* () {\n const api = yield* apiClient;\n const update = yield* api.updates\n .create({\n payload: {\n branch: params.branch,\n slug: params.projectSlug,\n runtimeVersion: params.runtimeVersion,\n platform: params.platform,\n message: params.message,\n groupId: params.groupId,\n metadata: {},\n assets: [],\n isRollback: true,\n directiveBody: params.directiveBody,\n ...(params.signature ? { signature: params.signature } : {}),\n ...(params.certificateChain ? { certificateChain: params.certificateChain } : {}),\n },\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new UpdateRollbackError({\n message: `Failed to create ${params.platform} rollback: ${formatCause(cause)}`,\n }),\n ),\n );\n\n return {\n platform: params.platform,\n updateId: update.id,\n runtimeVersion: params.runtimeVersion,\n } as const satisfies RollbackResultItem;\n });\n\nexport const runUpdateRollback = (\n options: RunUpdateRollbackOptions,\n): Effect.Effect<\n UpdateRollbackResult,\n | AuthRequiredError\n | ProjectNotLinkedError\n | BuildProfileError\n | EnvExportError\n | RuntimeVersionError\n | UpdateRollbackError,\n ApiClientService | CliRuntime | CommandExecutor.CommandExecutor | FileSystem.FileSystem\n> =>\n Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const projectRoot = yield* runtime.cwd;\n const api = yield* apiClient;\n\n const baseConfig = yield* readExpoConfig(projectRoot);\n const projectId = yield* extractProjectId(baseConfig);\n\n const environmentVars = yield* pullEnvVars(api, {\n projectId,\n environment: options.environment,\n });\n\n // Re-resolve with the env-var overlay so runtimeVersion / ios / android\n // sections (and slug) derived from process.env match what the corresponding\n // publish would have computed — otherwise rollback can target the wrong\n // runtime or publish under a stale slug.\n const config = yield* readExpoConfig(projectRoot, environmentVars);\n const projectSlug = yield* extractSlug(config);\n const platforms = resolveUpdatePlatforms(config, options.platform);\n if (platforms.length === 0) {\n return yield* new UpdateRollbackError({\n message:\n 'No publishable platforms found in your Expo config. Add an \"ios\" or \"android\" section, or pass --platform explicitly.',\n });\n }\n\n const { appVersion, rawRuntimeVersion } = readRuntimeVersionMeta(config);\n const runtimeVersion = yield* resolveRuntimeVersion({\n raw: rawRuntimeVersion,\n appVersion,\n projectRoot,\n });\n const signedPayload = yield* loadOptionalSignedRollbackPayload(options);\n const commitTime = signedPayload\n ? yield* Effect.gen(function* () {\n const directiveCommitTime = yield* extractDirectiveCommitTime(\n signedPayload.directiveBody,\n );\n if (options.commitTime && options.commitTime !== directiveCommitTime) {\n return yield* new UpdateRollbackError({\n message: \"commitTime must match directiveBody.parameters.commitTime in signed mode.\",\n });\n }\n return directiveCommitTime;\n })\n : yield* resolveCommitTime(options.commitTime);\n const groupId = randomUUID();\n const message = options.message ?? \"Rollback to embedded via better-update CLI\";\n\n const results = yield* Effect.forEach(\n platforms,\n (platform) =>\n createRollbackForPlatform({\n branch: options.branch,\n projectSlug,\n runtimeVersion,\n platform,\n message,\n groupId,\n directiveBody: signedPayload?.directiveBody ?? buildRollbackDirectiveBody(commitTime),\n signature: signedPayload?.signature,\n certificateChain: signedPayload?.certificateChain,\n }),\n { concurrency: 1 },\n );\n\n return {\n groupId,\n branch: options.branch,\n commitTime,\n results,\n } as const satisfies UpdateRollbackResult;\n });\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdateRollback } from \"../../application/update-rollback\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printHuman, printTable } from \"../../lib/output\";\nimport { promptSelect, promptText } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\nimport { resolveNamedResourceId, UpdateCommandError, updateErrorExtras } from \"./helpers\";\n\nimport type { ApiClient } from \"../../services/api-client\";\n\ntype RevertChoice = \"published\" | \"embedded\";\n\nconst promptBranchName = (api: ApiClient, projectId: string) =>\n Effect.gen(function* () {\n const branches = yield* drainPages((page) =>\n api.branches.list({ urlParams: { projectId, limit: 100, page } }),\n );\n if (branches.length === 0) {\n return yield* new UpdateCommandError({\n message: \"No branches found in this project.\",\n });\n }\n return yield* promptSelect<string>(\n \"Which branch to revert?\",\n branches.map((branch) => ({ value: branch.name, label: branch.name })),\n );\n });\n\nconst findPreviousGroupOnBranch = (\n api: ApiClient,\n projectId: string,\n branchId: string,\n platform: \"ios\" | \"android\" | \"all\",\n) =>\n Effect.gen(function* () {\n const updates = yield* drainPages((page) =>\n api.updates.list({ urlParams: { projectId, branchId, limit: 100, page } }),\n );\n const filtered =\n platform === \"all\" ? updates : updates.filter((entry) => entry.platform === platform);\n const seen = new Set<string>();\n const orderedGroups: string[] = [];\n for (const update of filtered) {\n if (!seen.has(update.groupId)) {\n seen.add(update.groupId);\n orderedGroups.push(update.groupId);\n }\n }\n if (orderedGroups.length < 2) {\n return undefined;\n }\n return orderedGroups[1];\n });\n\nconst revertToPublished = (\n api: ApiClient,\n projectId: string,\n branchName: string,\n platform: \"ios\" | \"android\" | \"all\",\n message: string | undefined,\n) =>\n Effect.gen(function* () {\n const branches = yield* drainPages((page) =>\n api.branches.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const branchId = yield* resolveNamedResourceId({\n items: branches,\n kind: \"Branch\",\n name: branchName,\n });\n const previousGroup = yield* findPreviousGroupOnBranch(api, projectId, branchId, platform);\n if (previousGroup === undefined) {\n return yield* new UpdateCommandError({\n message: `Branch \"${branchName}\" does not have a previous update group to revert to. Use --type embedded to publish a rollback-to-embedded directive instead.`,\n });\n }\n yield* Console.log(`Republishing previous group ${previousGroup} onto branch \"${branchName}\".`);\n const result = yield* api.updates.republish({\n payload: {\n sourceGroupId: previousGroup,\n destinationBranchId: branchId,\n ...(message === undefined ? {} : { message }),\n },\n });\n yield* printHuman(`Republished ${String(result.updates.length)} update(s).`);\n yield* printTable(\n [\"ID\", \"Platform\", \"Runtime version\", \"Group ID\"],\n result.updates.map((update) => [\n update.id,\n update.platform,\n update.runtimeVersion,\n update.groupId,\n ]),\n );\n return undefined;\n });\n\nconst revertToEmbedded = (\n branchName: string,\n platform: \"ios\" | \"android\" | \"all\",\n environment: string,\n message: string | undefined,\n) =>\n Effect.gen(function* () {\n const result = yield* runUpdateRollback({\n branch: branchName,\n platform,\n environment,\n message,\n commitTime: undefined,\n directiveBodyFile: undefined,\n signatureFile: undefined,\n certificateChainFile: undefined,\n });\n yield* Console.log(\n `Created rollback group ${result.groupId} on branch \"${result.branch}\" at ${result.commitTime}.`,\n );\n yield* Console.log(\"\");\n yield* printTable(\n [\"Platform\", \"Update ID\", \"Runtime Version\"],\n result.results.map((entry) => [entry.platform, entry.updateId, entry.runtimeVersion]),\n );\n });\n\nconst isRevertChoice = (value: string): value is RevertChoice =>\n value === \"published\" || value === \"embedded\";\n\nexport const revertCommand = defineCommand({\n meta: {\n name: \"revert\",\n description:\n \"Revert the most recent update on a branch — either by republishing the previous group or by publishing a rollback-to-embedded directive\",\n },\n args: {\n branch: { type: \"string\", description: \"Branch to revert\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Platform(s) to revert\",\n },\n type: {\n type: \"enum\",\n options: [\"published\", \"embedded\"],\n description: \"Pick revert target (skips the interactive router)\",\n },\n message: { type: \"string\", description: \"Optional update message\" },\n environment: {\n type: \"string\",\n default: \"production\",\n description: \"Env vars scope (only used for embedded rollback)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const projectId = yield* readProjectId;\n const branchName =\n args.branch !== undefined && args.branch.length > 0\n ? args.branch\n : yield* promptBranchName(api, projectId);\n const rawChoice =\n args.type ??\n (yield* promptSelect<string>(\"Which type of update would you like to revert to?\", [\n { value: \"published\", label: \"Published Update (republish the previous group)\" },\n {\n value: \"embedded\",\n label: \"Embedded Update (publish rollback-to-embedded directive)\",\n },\n ]));\n if (!isRevertChoice(rawChoice)) {\n return yield* new UpdateCommandError({\n message: `Invalid --type \"${rawChoice}\".`,\n });\n }\n const message =\n args.message ??\n (yield* promptText(\"Update message (optional, press enter to skip)\", {\n defaultValue: \"\",\n }).pipe(Effect.orElseSucceed(() => \"\")));\n const messageOrUndefined = message.length === 0 ? undefined : message;\n if (rawChoice === \"embedded\") {\n yield* revertToEmbedded(branchName, args.platform, args.environment, messageOrUndefined);\n return undefined;\n }\n yield* revertToPublished(api, projectId, branchName, args.platform, messageOrUndefined);\n return undefined;\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { drainPages } from \"../../lib/drain-cursor\";\nimport { readProjectId } from \"../../lib/expo-config\";\nimport { printHuman } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\nimport { UpdateCommandError, updateErrorExtras } from \"./helpers\";\n\nexport const revertRolloutCommand = defineCommand({\n meta: {\n name: \"revert-rollout\",\n description: \"Revert in-progress rollout for every update in a group\",\n },\n args: {\n groupId: { type: \"positional\", required: true, description: \"Update group ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const projectId = yield* readProjectId;\n const api = yield* apiClient;\n\n const allUpdates = yield* drainPages((page) =>\n api.updates.list({ urlParams: { projectId, limit: 100, page } }),\n );\n const inGroup = allUpdates.filter((update) => update.groupId === args.groupId);\n if (inGroup.length === 0) {\n return yield* new UpdateCommandError({\n message: `No updates found for group ${args.groupId}.`,\n });\n }\n\n yield* Effect.forEach(\n inGroup,\n (update) => api.updates.revertRollout({ path: { id: update.id } }),\n { concurrency: 2 },\n );\n\n yield* printHuman(\n `Reverted rollout for ${String(inGroup.length)} update(s) in group ${args.groupId}.`,\n );\n return undefined;\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runUpdateRollback } from \"../../application/update-rollback\";\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printTable } from \"../../lib/output\";\nimport { updateErrorExtras } from \"./helpers\";\n\ninterface RollbackParsedArgs {\n readonly branch: string;\n readonly platform: \"ios\" | \"android\" | \"all\";\n readonly environment: string;\n readonly message: string | undefined;\n readonly [\"commit-time\"]: string | undefined;\n readonly [\"directive-body-file\"]: string | undefined;\n readonly [\"signature-file\"]: string | undefined;\n readonly [\"certificate-chain-file\"]: string | undefined;\n}\n\nconst buildRollbackRun = (args: RollbackParsedArgs) =>\n Effect.gen(function* () {\n const result = yield* runUpdateRollback({\n branch: args.branch,\n platform: args.platform,\n environment: args.environment,\n message: args.message,\n commitTime: args[\"commit-time\"],\n directiveBodyFile: args[\"directive-body-file\"],\n signatureFile: args[\"signature-file\"],\n certificateChainFile: args[\"certificate-chain-file\"],\n });\n\n yield* Console.log(\n `Created rollback group ${result.groupId} on branch \"${result.branch}\" at ${result.commitTime}.`,\n );\n yield* Console.log(\"\");\n yield* printTable(\n [\"Platform\", \"Update ID\", \"Runtime Version\"],\n result.results.map((entry) => [entry.platform, entry.updateId, entry.runtimeVersion]),\n );\n });\n\nexport const rollBackToEmbeddedCommand = defineCommand({\n meta: {\n name: \"roll-back-to-embedded\",\n description:\n \"Roll back updates on a branch to the embedded JS (alias of `update rollback` for EAS parity)\",\n },\n args: {\n branch: { type: \"string\", required: true, description: \"Branch to roll back\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Platform(s) to roll back\",\n },\n message: { type: \"string\" },\n environment: { type: \"string\", default: \"production\", description: \"Env vars scope\" },\n \"commit-time\": { type: \"string\" },\n \"directive-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n },\n run: async ({ args }) => runEffect(buildRollbackRun(args), updateErrorExtras),\n});\n\nexport const rollbackCommand = defineCommand({\n meta: { name: \"rollback\", description: \"Roll back updates on a branch\" },\n args: {\n branch: { type: \"string\", required: true, description: \"Branch to roll back\" },\n platform: {\n type: \"enum\",\n options: [\"ios\", \"android\", \"all\"],\n default: \"all\",\n description: \"Platform(s) to roll back\",\n },\n message: { type: \"string\" },\n environment: { type: \"string\", default: \"production\", description: \"Env vars scope\" },\n \"commit-time\": { type: \"string\" },\n \"directive-body-file\": { type: \"string\" },\n \"signature-file\": { type: \"string\" },\n \"certificate-chain-file\": { type: \"string\" },\n },\n run: async ({ args }) => runEffect(buildRollbackRun(args), updateErrorExtras),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { updateErrorExtras } from \"../helpers\";\n\nexport const completeCommand = defineCommand({\n meta: { name: \"complete\", description: \"Complete the rollout for an update\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Update ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.updates.completeRollout({ path: { id: args.updateId } });\n yield* Console.log(\n `Completed rollout for ${args.updateId}. Current rollout is ${String(result.rolloutPercentage)}%.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { updateErrorExtras } from \"../helpers\";\n\nexport const revertCommand = defineCommand({\n meta: { name: \"revert\", description: \"Revert the rollout for an update\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Update ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.updates.revertRollout({ path: { id: args.updateId } });\n yield* Console.log(\n `Reverted rollout for ${args.updateId}. Current rollout is ${String(result.rolloutPercentage)}%.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Console, Effect } from \"effect\";\n\nimport { runEffect } from \"../../../lib/citty-effect\";\nimport { parseRolloutPercentage } from \"../../../lib/cli-schemas\";\nimport { apiClient } from \"../../../services/api-client\";\nimport { updateErrorExtras } from \"../helpers\";\n\nexport const setCommand = defineCommand({\n meta: { name: \"set\", description: \"Set the rollout percentage for an update\" },\n args: {\n updateId: { type: \"positional\", required: true, description: \"Update ID\" },\n percentage: { type: \"string\", required: true, description: \"Rollout percentage (1-100)\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const percentage = yield* parseRolloutPercentage(args.percentage, \"percentage\");\n const api = yield* apiClient;\n const result = yield* api.updates.editRollout({\n path: { id: args.updateId },\n payload: { percentage },\n });\n\n yield* Console.log(\n `Updated rollout for ${args.updateId} to ${String(result.rolloutPercentage)}%.`,\n );\n }),\n updateErrorExtras,\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { completeCommand } from \"./complete\";\nimport { revertCommand } from \"./revert\";\nimport { setCommand } from \"./set\";\n\nexport const rolloutCommand = defineCommand({\n meta: { name: \"rollout\", description: \"Manage per-update rollouts\" },\n subCommands: {\n set: setCommand,\n complete: completeCommand,\n revert: revertCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const viewCommand = defineCommand({\n meta: { name: \"view\", description: \"Show details for a single update\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Update ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const update = yield* api.updates.get({ path: { id: args.id } });\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(update);\n return undefined;\n }\n yield* printKeyValue([\n [\"ID\", update.id],\n [\"Group ID\", update.groupId],\n [\"Branch ID\", update.branchId],\n [\"Platform\", update.platform],\n [\"Runtime version\", update.runtimeVersion],\n [\"Rollout %\", String(update.rolloutPercentage)],\n [\"Is rollback\", update.isRollback ? \"yes\" : \"no\"],\n [\"Created\", update.createdAt],\n [\"Message\", update.message],\n ]);\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { configureCommand } from \"./configure\";\nimport { deleteCommand } from \"./delete\";\nimport { editCommand } from \"./edit\";\nimport { insightsCommand } from \"./insights\";\nimport { listCommand } from \"./list\";\nimport { promoteCommand } from \"./promote\";\nimport { publishCommand } from \"./publish\";\nimport { republishCommand } from \"./republish\";\nimport { revertCommand } from \"./revert\";\nimport { revertRolloutCommand } from \"./revert-rollout\";\nimport { rollbackCommand, rollBackToEmbeddedCommand } from \"./rollback\";\nimport { rolloutCommand } from \"./rollout\";\nimport { viewCommand } from \"./view\";\n\nexport const updateCommand = defineCommand({\n meta: { name: \"update\", description: \"Manage OTA updates\" },\n subCommands: {\n publish: publishCommand,\n configure: configureCommand,\n list: listCommand,\n view: viewCommand,\n delete: deleteCommand,\n edit: editCommand,\n promote: promoteCommand,\n republish: republishCommand,\n rollback: rollbackCommand,\n \"roll-back-to-embedded\": rollBackToEmbeddedCommand,\n revert: revertCommand,\n rollout: rolloutCommand,\n \"revert-rollout\": revertRolloutCommand,\n insights: insightsCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nconst ALLOWED_EVENTS = [\"update.published\", \"build.completed\"] as const;\ntype WebhookEvent = (typeof ALLOWED_EVENTS)[number];\n\nconst isWebhookEvent = (value: string): value is WebhookEvent =>\n (ALLOWED_EVENTS as readonly string[]).includes(value);\n\nconst parseEvents = (raw: string): readonly WebhookEvent[] | { readonly error: string } => {\n const list = raw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n const invalid = list.filter((value) => !isWebhookEvent(value));\n if (invalid.length > 0) {\n return {\n error: `Unknown event(s): ${invalid.join(\", \")}. Allowed: ${ALLOWED_EVENTS.join(\", \")}`,\n };\n }\n return list.filter(isWebhookEvent);\n};\n\nexport const createWebhookCommand = defineCommand({\n meta: {\n name: \"create\",\n description:\n \"Create a webhook subscription. The signing secret is returned ONCE — store it now.\",\n },\n args: {\n name: { type: \"string\", required: true, description: \"Display name\" },\n url: { type: \"string\", required: true, description: \"HTTPS URL to POST events to\" },\n events: {\n type: \"string\",\n required: true,\n description: \"Comma-separated event names. Allowed: update.published, build.completed\",\n },\n \"project-id\": {\n type: \"string\",\n description: \"Restrict the webhook to a single project (optional)\",\n },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const parsed = parseEvents(args.events);\n if (\"error\" in parsed) {\n return yield* new InvalidArgumentError({ message: parsed.error });\n }\n if (parsed.length === 0) {\n return yield* new InvalidArgumentError({\n message: \"Pass at least one event via --events\",\n });\n }\n const api = yield* apiClient;\n const webhook = yield* api.webhooks.create({\n payload: {\n name: args.name,\n url: args.url,\n events: parsed,\n ...(args[\"project-id\"] === undefined ? {} : { projectId: args[\"project-id\"] }),\n },\n });\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(webhook);\n return undefined;\n }\n yield* printKeyValue([\n [\"ID\", webhook.id],\n [\"Name\", webhook.name],\n [\"URL\", webhook.url],\n [\"Events\", webhook.events.join(\",\")],\n [\"Secret (save now!)\", webhook.secret],\n ]);\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printHuman } from \"../../lib/output\";\nimport { promptConfirm } from \"../../lib/prompts\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const deleteWebhookCommand = defineCommand({\n meta: { name: \"delete\", description: \"Delete a webhook subscription\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Webhook ID\" },\n yes: { type: \"boolean\", description: \"Skip confirmation prompt\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n if (!args.yes) {\n const confirmed = yield* promptConfirm(`Delete webhook ${args.id}?`, {\n initialValue: false,\n });\n if (!confirmed) {\n yield* printHuman(\"Cancelled.\");\n return;\n }\n }\n const api = yield* apiClient;\n yield* api.webhooks.delete({ path: { id: args.id } });\n yield* printHuman(`Deleted webhook ${args.id}.`);\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printJson, printTable } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const listWebhooksCommand = defineCommand({\n meta: { name: \"list\", description: \"List webhook subscriptions\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const result = yield* api.webhooks.list();\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(result);\n return undefined;\n }\n yield* printTable(\n [\"ID\", \"Name\", \"URL\", \"Events\", \"Enabled\"],\n result.items.map((webhook) => [\n webhook.id,\n webhook.name,\n webhook.url,\n webhook.events.join(\",\"),\n webhook.enabled ? \"yes\" : \"no\",\n ]),\n );\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { InvalidArgumentError } from \"../../lib/exit-codes\";\nimport { printKeyValue } from \"../../lib/output\";\nimport { apiClient } from \"../../services/api-client\";\n\nconst ALLOWED_EVENTS = [\"update.published\", \"build.completed\"] as const;\ntype WebhookEvent = (typeof ALLOWED_EVENTS)[number];\n\nconst isWebhookEvent = (value: string): value is WebhookEvent =>\n (ALLOWED_EVENTS as readonly string[]).includes(value);\n\nconst parseEvents = (\n raw: string | undefined,\n): readonly WebhookEvent[] | undefined | { readonly error: string } => {\n if (raw === undefined) {\n return undefined;\n }\n const list = raw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n const invalid = list.filter((value) => !isWebhookEvent(value));\n if (invalid.length > 0) {\n return {\n error: `Unknown event(s): ${invalid.join(\", \")}. Allowed: ${ALLOWED_EVENTS.join(\", \")}`,\n };\n }\n return list.filter(isWebhookEvent);\n};\n\nconst resolveEnabled = (enable: boolean | undefined, disable: boolean | undefined) => {\n if (enable) {\n return true;\n }\n if (disable) {\n return false;\n }\n return undefined;\n};\n\nexport const updateWebhookCommand = defineCommand({\n meta: { name: \"update\", description: \"Update webhook fields (name, url, events, enabled)\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Webhook ID\" },\n name: { type: \"string\", description: \"New display name\" },\n url: { type: \"string\", description: \"New URL\" },\n events: { type: \"string\", description: \"Replace event list (comma-separated)\" },\n enable: { type: \"boolean\", description: \"Mark webhook as enabled\" },\n disable: { type: \"boolean\", description: \"Mark webhook as disabled\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const events = parseEvents(args.events);\n if (events && \"error\" in events) {\n return yield* new InvalidArgumentError({ message: events.error });\n }\n const enabled = resolveEnabled(args.enable, args.disable);\n const api = yield* apiClient;\n const webhook = yield* api.webhooks.update({\n path: { id: args.id },\n payload: {\n ...(args.name === undefined ? {} : { name: args.name }),\n ...(args.url === undefined ? {} : { url: args.url }),\n ...(events === undefined ? {} : { events }),\n ...(enabled === undefined ? {} : { enabled }),\n },\n });\n yield* printKeyValue([\n [\"ID\", webhook.id],\n [\"Name\", webhook.name],\n [\"URL\", webhook.url],\n [\"Events\", webhook.events.join(\",\")],\n [\"Enabled\", webhook.enabled ? \"yes\" : \"no\"],\n ]);\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../../lib/citty-effect\";\nimport { printJson, printKeyValue } from \"../../lib/output\";\nimport { OutputMode } from \"../../lib/output-mode\";\nimport { apiClient } from \"../../services/api-client\";\n\nexport const viewWebhookCommand = defineCommand({\n meta: { name: \"view\", description: \"Show details for a webhook (without the secret)\" },\n args: {\n id: { type: \"positional\", required: true, description: \"Webhook ID\" },\n },\n run: async ({ args }) =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const webhook = yield* api.webhooks.get({ path: { id: args.id } });\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(webhook);\n return undefined;\n }\n yield* printKeyValue([\n [\"ID\", webhook.id],\n [\"Name\", webhook.name],\n [\"URL\", webhook.url],\n [\"Events\", webhook.events.join(\",\")],\n [\"Enabled\", webhook.enabled ? \"yes\" : \"no\"],\n [\"Project ID\", webhook.projectId ?? \"(all)\"],\n [\"Created\", webhook.createdAt],\n ]);\n return undefined;\n }),\n ),\n});\n","import { defineCommand } from \"citty\";\n\nimport { createWebhookCommand } from \"./create\";\nimport { deleteWebhookCommand } from \"./delete\";\nimport { listWebhooksCommand } from \"./list\";\nimport { updateWebhookCommand } from \"./update\";\nimport { viewWebhookCommand } from \"./view\";\n\nexport const webhooksCommand = defineCommand({\n meta: {\n name: \"webhooks\",\n description: \"Manage HTTPS event subscriptions (update.published, build.completed)\",\n },\n subCommands: {\n list: listWebhooksCommand,\n create: createWebhookCommand,\n view: viewWebhookCommand,\n update: updateWebhookCommand,\n delete: deleteWebhookCommand,\n },\n});\n","import { defineCommand } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport { runEffect } from \"../lib/citty-effect\";\nimport { printJson, printKeyValue } from \"../lib/output\";\nimport { OutputMode } from \"../lib/output-mode\";\nimport { apiClient } from \"../services/api-client\";\n\nexport const whoamiCommand = defineCommand({\n meta: { name: \"whoami\", description: \"Show the currently authenticated user + organization\" },\n run: async () =>\n runEffect(\n Effect.gen(function* () {\n const api = yield* apiClient;\n const me = yield* api.me.get();\n const mode = yield* OutputMode;\n if (mode.json) {\n yield* printJson(me);\n return;\n }\n const rows: (readonly [string, string])[] = [];\n if (me.user) {\n rows.push([\"User ID\", me.user.id]);\n rows.push([\"Name\", me.user.name]);\n rows.push([\"Email\", me.user.email]);\n } else {\n rows.push([\"Actor\", me.actorEmail]);\n }\n rows.push([\"Source\", me.source]);\n if (me.activeOrganization) {\n rows.push([\"Organization\", me.activeOrganization.name]);\n rows.push([\"Org slug\", me.activeOrganization.slug]);\n rows.push([\"Org ID\", me.activeOrganization.id]);\n rows.push([\"Role\", me.activeOrganization.role ?? \"—\"]);\n } else {\n rows.push([\"Organization\", \"(none)\"]);\n }\n yield* printKeyValue(rows);\n }),\n ),\n});\n","export interface GlobalFlags {\n /** Emit machine-readable JSON instead of human-readable output. */\n readonly json: boolean;\n /** Disallow interactive prompts. Errors out if a prompt is needed but no flag value was provided. */\n readonly nonInteractive: boolean;\n}\n\nconst FLAG_JSON = \"--json\";\nconst FLAG_NON_INTERACTIVE = \"--non-interactive\";\nconst FLAG_INTERACTIVE = \"--interactive\";\n\nconst isCi = (env: NodeJS.ProcessEnv): boolean => env[\"CI\"] === \"true\" || env[\"CI\"] === \"1\";\n\nexport const parseGlobalFlags = (\n argv: readonly string[],\n env: NodeJS.ProcessEnv = process.env,\n): GlobalFlags => {\n const json = argv.includes(FLAG_JSON);\n const explicitNonInteractive = argv.includes(FLAG_NON_INTERACTIVE);\n const explicitInteractive = argv.includes(FLAG_INTERACTIVE);\n const nonInteractive =\n explicitNonInteractive || (!explicitInteractive && json) || (!explicitInteractive && isCi(env));\n return { json, nonInteractive };\n};\n\n/**\n * Remove global flags from argv before citty parses subcommand args. citty would\n * otherwise treat them as unknown args and fail or noise the help output.\n */\nexport const stripGlobalFlags = (argv: readonly string[]): readonly string[] =>\n argv.filter(\n (arg) => arg !== FLAG_JSON && arg !== FLAG_NON_INTERACTIVE && arg !== FLAG_INTERACTIVE,\n );\n","import { fileURLToPath } from \"node:url\";\n\nexport type Installer = \"bun\" | \"pnpm\" | \"yarn\" | \"npm\";\n\nexport const detectInstaller = (modulePath: string): Installer => {\n const normalized = modulePath.replaceAll(\"\\\\\", \"/\").toLowerCase();\n if (normalized.includes(\"/.bun/\")) {\n return \"bun\";\n }\n if (normalized.includes(\"/pnpm/\")) {\n return \"pnpm\";\n }\n if (normalized.includes(\"/.yarn/\") || normalized.includes(\"/yarn/\")) {\n return \"yarn\";\n }\n return \"npm\";\n};\n\nconst INSTALL_COMMANDS: Readonly<Record<Installer, string>> = {\n bun: \"bun add -g @better-update/cli@latest\",\n pnpm: \"pnpm add -g @better-update/cli@latest\",\n yarn: \"yarn global add @better-update/cli@latest\",\n npm: \"npm install -g @better-update/cli@latest\",\n};\n\nexport const installCommand = (installer: Installer): string => INSTALL_COMMANDS[installer];\n\nexport const detectInstallerFromImportMetaUrl = (importMetaUrl: string): Installer =>\n detectInstaller(fileURLToPath(importMetaUrl));\n","const stripPrerelease = (version: string): readonly number[] => {\n const main = version.replace(/-.*$/u, \"\");\n return main.split(\".\").map((part) => Number.parseInt(part, 10) || 0);\n};\n\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const [la = 0, lb = 0, lc = 0] = stripPrerelease(latest);\n const [ca = 0, cb = 0, cc = 0] = stripPrerelease(current);\n if (la !== ca) {\n return la > ca;\n }\n if (lb !== cb) {\n return lb > cb;\n }\n return lc > cc;\n};\n","import { Console, Effect } from \"effect\";\n\nimport { CliRuntime } from \"../services/cli-runtime\";\nimport { VersionCheck } from \"../services/version-check\";\nimport { detectInstallerFromImportMetaUrl, installCommand } from \"./detect-installer\";\nimport { isNewerVersion } from \"./semver-compare\";\n\nconst formatNotice = (current: string, latest: string, command: string): string =>\n [\n \"\",\n `╭─ Update available: @better-update/cli ${current} → ${latest}`,\n `│ Run: ${command}`,\n \"╰─\",\n \"\",\n ].join(\"\\n\");\n\nconst isOptedOut = Effect.gen(function* () {\n const runtime = yield* CliRuntime;\n const value = yield* runtime.getEnv(\"BETTER_UPDATE_DISABLE_UPDATE_NOTIFIER\");\n return value === \"1\" || value === \"true\";\n});\n\nexport const bootstrapVersionCheck = (\n currentVersion: string,\n installerHint: string,\n spawnRefresh: () => void,\n): Effect.Effect<void, never, VersionCheck | CliRuntime> =>\n Effect.gen(function* () {\n if (yield* isOptedOut) {\n return;\n }\n const versionCheck = yield* VersionCheck;\n const cached = yield* versionCheck.cachedLatest;\n if (cached && isNewerVersion(cached, currentVersion)) {\n const installer = detectInstallerFromImportMetaUrl(installerHint);\n yield* Console.error(formatNotice(currentVersion, cached, installCommand(installer)));\n }\n if (yield* versionCheck.cacheStale) {\n spawnRefresh();\n }\n });\n\nexport const refreshVersionCacheIfStale: Effect.Effect<void, never, VersionCheck | CliRuntime> =\n Effect.gen(function* () {\n if (yield* isOptedOut) {\n return;\n }\n const versionCheck = yield* VersionCheck;\n const stale = yield* versionCheck.cacheStale;\n if (stale) {\n yield* versionCheck.refreshCache;\n }\n });\n","#!/usr/bin/env node\n\nimport { spawn } from \"node:child_process\";\n\nimport { defineCommand, runMain } from \"citty\";\nimport { Effect } from \"effect\";\n\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport { makeCliLive } from \"./app-layer\";\nimport { analyticsCommand } from \"./commands/analytics\";\nimport { auditLogsCommand } from \"./commands/audit-logs\";\nimport { autocompleteCommand } from \"./commands/autocomplete\";\nimport { branchesCommand } from \"./commands/branches\";\nimport { buildCommand } from \"./commands/build\";\nimport { buildsCommand } from \"./commands/builds\";\nimport { channelsCommand } from \"./commands/channels\";\nimport { credentialsCommand } from \"./commands/credentials\";\nimport { devicesCommand } from \"./commands/devices\";\nimport { doctorCommand } from \"./commands/doctor\";\nimport { envCommand } from \"./commands/env\";\nimport { fingerprintCommand } from \"./commands/fingerprint\";\nimport { initCommand } from \"./commands/init\";\nimport { loginCommand } from \"./commands/login\";\nimport { logoutCommand } from \"./commands/logout\";\nimport { migrateConfigCommand } from \"./commands/migrate-config\";\nimport { openCommand } from \"./commands/open\";\nimport { projectsCommand } from \"./commands/projects\";\nimport { statusCommand } from \"./commands/status\";\nimport { updateCommand } from \"./commands/update\";\nimport { webhooksCommand } from \"./commands/webhooks\";\nimport { whoamiCommand } from \"./commands/whoami\";\nimport { setActiveCliLayer } from \"./lib/citty-effect\";\nimport { setExecTrailingArgv, splitTrailingArgv } from \"./lib/exec-trailing-argv\";\nimport { parseGlobalFlags, stripGlobalFlags } from \"./lib/global-flags\";\nimport { bootstrapVersionCheck, refreshVersionCacheIfStale } from \"./lib/version-notifier\";\n\nconst REFRESH_VERSION_CACHE_FLAG = \"__refresh-version-cache\";\n\n// Parse + strip global flags before citty sees them. argv[0]=node, argv[1]=script, args start at [2].\nconst rawArgs = process.argv.slice(2);\nconst globalFlags = parseGlobalFlags(rawArgs);\nconst withoutGlobals = stripGlobalFlags(rawArgs);\n// Split at `--` so subcommands like `env exec` can read raw trailing argv.\nconst { mainArgs, trailing } = splitTrailingArgv(withoutGlobals);\nsetExecTrailingArgv(trailing);\nprocess.argv = [...process.argv.slice(0, 2), ...mainArgs];\n\nconst cliLayer = makeCliLive({\n json: globalFlags.json,\n interactive: !globalFlags.nonInteractive,\n});\nsetActiveCliLayer(cliLayer);\n\nif (process.argv[2] === REFRESH_VERSION_CACHE_FLAG) {\n await Effect.runPromise(refreshVersionCacheIfStale.pipe(Effect.provide(cliLayer)));\n process.exit(0);\n}\n\nconst spawnDetachedRefresh = (): void => {\n const child = spawn(process.execPath, [import.meta.filename, REFRESH_VERSION_CACHE_FLAG], {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n};\n\nconst main = defineCommand({\n meta: {\n name: \"better-update\",\n version: pkg.version,\n description: \"Publish OTA updates and builds for Expo apps\",\n },\n setup: async () => {\n await Effect.runPromise(\n bootstrapVersionCheck(pkg.version, import.meta.url, spawnDetachedRefresh).pipe(\n Effect.provide(cliLayer),\n ),\n );\n },\n subCommands: {\n login: loginCommand,\n logout: logoutCommand,\n init: initCommand,\n status: statusCommand,\n projects: projectsCommand,\n branches: branchesCommand,\n channels: channelsCommand,\n build: buildCommand,\n builds: buildsCommand,\n credentials: credentialsCommand,\n env: envCommand,\n fingerprint: fingerprintCommand,\n update: updateCommand,\n analytics: analyticsCommand,\n \"audit-logs\": auditLogsCommand,\n whoami: whoamiCommand,\n open: openCommand,\n doctor: doctorCommand,\n devices: devicesCommand,\n webhooks: webhooksCommand,\n autocomplete: autocompleteCommand,\n \"migrate-config\": migrateConfigCommand,\n },\n});\n\nawait runMain(main);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACEA,IAAa,kBAAb,cAAqC,QAAQ,IAAI,sBAAsB,EAMpE,CAAC;AAEJ,MAAa,4BAA4B,UACvC,MAAM,QAAQ,iBAAiB,EAAE,OAAO,CAAC;;AAG3C,MAAa,sBAAsB,yBAAyB,KAAK;;;;ACZjE,IAAa,aAAb,cAAgC,QAAQ,IAAI,iBAAiB,EAM1D,CAAC;AAEJ,MAAa,uBAAuB,SAClC,MAAM,QAAQ,YAAY,EAAE,MAAM,CAAC;;AAGrC,MAAa,iBAAiB,oBAAoB,MAAM;;;;ACuBxD,IAAa,cAAb,cAAiC,QAAQ,IAAI,kBAAkB,EAAiC,CAAC;;;;AClCjG,IAAa,eAAb,cAAkC,OAAO,aAA2B,CAClE,gBACA,EAAE,SAAS,OAAO,QAAQ,EAC1B,cAAc,YAAY,EAAE,QAAQ,KAAK,CAAC,CAC3C,CAAC;AAEF,IAAa,YAAb,cAA+B,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