gigadrive 2.7.1 → 2.7.3

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,"sources":["../src/index.ts","../package.json","../src/commands/ai/index.ts","../src/errors.ts","../src/services/api-client.ts","../src/services/auth.ts","../src/domain.ts","../src/lib/clipboard.ts","../src/services/auth-storage.ts","../src/services/oauth-config.ts","../src/services/project-link.ts","../src/commands/apps/index.ts","../src/commands/build/index.ts","../src/services/package-manager.ts","../src/commands/debug/index.ts","../src/commands/debug/config/index.ts","../src/services/project-config.ts","../src/commands/deployments/index.ts","../src/commands/domains/index.ts","../src/lib/domain-output.ts","../src/commands/env/index.ts","../src/services/env-file.ts","../src/lib/dotenv.ts","../src/services/local-credentials.ts","../src/services/dev-credentials-store.ts","../src/commands/link/index.ts","../src/commands/login/index.ts","../src/commands/logout/index.ts","../src/commands/platform/index.ts","../src/commands/platform/deploy/index.ts","../src/services/archive.ts","../src/services/deployment-api.ts","../src/commands/setup/index.ts","../src/commands/whoami/index.ts"],"sourcesContent":["import { Command } from '@effect/cli';\nimport { NodeContext, NodeRuntime } from '@effect/platform-node';\nimport { NetworkConfigLive } from '@gigadrive/network-config';\nimport { Effect, Layer, LogLevel, Logger } from 'effect';\nimport pkg from '../package.json';\nimport { aiCommand } from './commands/ai';\nimport { appsCommand } from './commands/apps';\nimport { buildCommand } from './commands/build';\nimport { debugCommand } from './commands/debug';\nimport { deploymentsCommand } from './commands/deployments';\nimport { domainsCommand } from './commands/domains';\nimport { envCommand } from './commands/env';\nimport { linkCommand, unlinkCommand } from './commands/link';\nimport { loginCommand } from './commands/login';\nimport { logoutCommand } from './commands/logout';\nimport { platformCommand } from './commands/platform';\nimport { deployCommand } from './commands/platform/deploy';\nimport { setupCommand } from './commands/setup';\nimport { whoamiCommand } from './commands/whoami';\nimport { ApiClientService } from './services/api-client';\nimport { ArchiveService } from './services/archive';\nimport { AuthService } from './services/auth';\nimport { AuthStorageService } from './services/auth-storage';\nimport { DeploymentApiService } from './services/deployment-api';\nimport { DevCredentialsStore } from './services/dev-credentials-store';\nimport { EnvFileService } from './services/env-file';\nimport { LocalCredentialsService } from './services/local-credentials';\nimport { OAuthConfigService } from './services/oauth-config';\nimport { PackageManagerService } from './services/package-manager';\nimport { ProjectConfigService } from './services/project-config';\nimport { ProjectLinkService } from './services/project-link';\n\n// ---------------------------------------------------------------------------\n// Root command with subcommands\n// ---------------------------------------------------------------------------\n\nconst gigadrive = Command.make('gigadrive', {}, () => Effect.void).pipe(\n Command.withSubcommands([\n loginCommand,\n logoutCommand,\n whoamiCommand,\n linkCommand,\n unlinkCommand,\n appsCommand,\n envCommand,\n deploymentsCommand,\n domainsCommand,\n aiCommand,\n buildCommand,\n debugCommand,\n deployCommand,\n platformCommand,\n setupCommand,\n ])\n);\n\n// ---------------------------------------------------------------------------\n// CLI application\n// ---------------------------------------------------------------------------\n\nconst cli = Command.run(gigadrive, {\n name: 'Gigadrive CLI',\n version: pkg.version,\n});\n\n// ---------------------------------------------------------------------------\n// Service layers — flat composition via mergeAll + provideMerge\n// ---------------------------------------------------------------------------\n\nconst BaseServices = Layer.mergeAll(\n OAuthConfigService.Default,\n AuthStorageService.Default,\n PackageManagerService.Default,\n ArchiveService.Default,\n NetworkConfigLive,\n ProjectConfigService.Default,\n ProjectLinkService.Default,\n EnvFileService.Default,\n DevCredentialsStore.Default\n).pipe(Layer.provideMerge(AuthService.Default));\n\nconst ApiClientLive = Layer.provide(ApiClientService.Default, BaseServices);\nconst DeploymentApiLive = Layer.provide(DeploymentApiService.Default, BaseServices);\n// LocalCredentialsService bakes in ApiClientService + DevCredentialsStore via its\n// `dependencies`, so it only needs BaseServices (for the transitive AuthService).\nconst LocalCredentialsLive = Layer.provide(LocalCredentialsService.Default, BaseServices);\n\nconst ServicesLive = Layer.mergeAll(BaseServices, ApiClientLive, DeploymentApiLive, LocalCredentialsLive);\n\nconst AppLive = Layer.mergeAll(ServicesLive, Logger.minimumLogLevel(LogLevel.Info)).pipe(\n Layer.provideMerge(NodeContext.layer)\n);\n\n// ---------------------------------------------------------------------------\n// Run\n// ---------------------------------------------------------------------------\n\nNodeRuntime.runMain(Effect.provide(cli(process.argv), AppLive));\n","{\n \"name\": \"gigadrive\",\n \"version\": \"2.7.1\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Gigadrive/sdk.git\",\n \"directory\": \"packages/cli\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Gigadrive <business@gigadrivegroup.com> (https://gigadrive.de)\",\n \"type\": \"module\",\n \"module\": \"src/index.ts\",\n \"bin\": {\n \"gigadrive\": \"dist/index.mjs\",\n \"gn\": \"dist/index.mjs\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"clean\": \"rm -rf dist\",\n \"dev\": \"pnpm build && node dist/index.mjs\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@effect/cli\": \"^0.77.0\",\n \"@effect/platform\": \"^0.97.0\",\n \"@effect/platform-node\": \"^0.108.0\",\n \"@gigadrive/build-utils\": \"workspace:*\",\n \"@gigadrive/commons\": \"workspace:*\",\n \"@gigadrive/network-config\": \"workspace:*\",\n \"@gigadrive/sdk\": \"workspace:*\",\n \"archiver\": \"^7.0.1\",\n \"effect\": \"^3.19.17\",\n \"ignore\": \"^7.0.5\",\n \"open\": \"^10.2.0\"\n },\n \"devDependencies\": {\n \"@effect/language-service\": \"^0.87.0\",\n \"@types/archiver\": \"^6.0.4\",\n \"esbuild\": \"^0.28.0\",\n \"typescript\": \"catalog:\"\n },\n \"engines\": {\n \"node\": \">=20.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import { Args, Command, Options } from '@effect/cli';\nimport { FileSystem } from '@effect/platform';\nimport type { AiGatewayBudgetInput, AiGatewayPolicyInput } from '@gigadrive/sdk';\nimport { Console, Effect, Option } from 'effect';\nimport { ApiRequestError, NotAuthenticatedError, ProjectLinkReadError, ProjectNotLinkedError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\n// ---------------------------------------------------------------------------\n// Shared options / helpers\n// ---------------------------------------------------------------------------\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Organization ID (defaults to the linked organization)'),\n Options.optional\n);\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Restrict to this application ID'),\n Options.optional\n);\n\nconst fromOption = Options.text('from').pipe(\n Options.withDescription('Include usage at or after this ISO 8601 timestamp'),\n Options.optional\n);\n\nconst toOption = Options.text('to').pipe(\n Options.withDescription('Include usage before or at this ISO 8601 timestamp'),\n Options.optional\n);\n\nconst fileOption = Options.text('file').pipe(\n Options.withAlias('f'),\n Options.withDescription('Path to a JSON file, or \"-\" for stdin (default: stdin)'),\n Options.optional\n);\n\n/** Resolve the organization ID from `--org` or the linked project. */\nconst resolveOrgId = (org: Option.Option<string>) =>\n Effect.gen(function* () {\n if (Option.isSome(org)) return org.value;\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.resolve(process.cwd());\n if (link.organizationId === undefined) {\n return yield* Effect.fail(\n new ProjectNotLinkedError({\n message: 'No organization is linked. Pass --org <id> or re-run \"gigadrive link\".',\n directory: process.cwd(),\n })\n );\n }\n return link.organizationId;\n });\n\n/** Read all of stdin as a UTF-8 string. */\nconst readStdin = Effect.async<string, ApiRequestError>((resume) => {\n let data = '';\n const stdin = process.stdin;\n stdin.setEncoding('utf8');\n const onData = (chunk: string) => {\n data += chunk;\n };\n const cleanup = () => {\n stdin.off('data', onData);\n stdin.off('end', onEnd);\n stdin.off('error', onError);\n };\n const onEnd = () => {\n cleanup();\n resume(Effect.succeed(data));\n };\n const onError = (err: Error) => {\n cleanup();\n resume(Effect.fail(new ApiRequestError({ message: `Failed to read stdin: ${err.message}` })));\n };\n stdin.on('data', onData);\n stdin.on('end', onEnd);\n stdin.on('error', onError);\n stdin.resume();\n});\n\n/** Read JSON from a file (or stdin when the path is omitted or `-`). */\nconst readJsonInput = (file: Option.Option<string>) =>\n Effect.gen(function* () {\n const path = Option.getOrUndefined(file);\n let raw: string;\n if (path === undefined || path === '-') {\n raw = yield* readStdin;\n } else {\n const fs = yield* FileSystem.FileSystem;\n raw = yield* fs\n .readFileString(path, 'utf8')\n .pipe(Effect.mapError((e) => new ApiRequestError({ message: `Failed to read ${path}: ${String(e)}` })));\n }\n return yield* Effect.try({\n try: () => JSON.parse(raw) as unknown,\n catch: () => new ApiRequestError({ message: 'Input is not valid JSON.' }),\n });\n });\n\n/** Shared error handlers for the governance commands — log, then re-fail so the process exits non-zero. */\nconst governanceErrorHandlers = {\n NotAuthenticatedError: (err: NotAuthenticatedError) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err: ApiRequestError) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err: ProjectNotLinkedError) =>\n Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err: ProjectLinkReadError) =>\n Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n};\n\n// ---------------------------------------------------------------------------\n// ai usage\n// ---------------------------------------------------------------------------\n\nconst usageSummaryCommand = Command.make(\n 'summary',\n { org: orgOption, app: appOption, from: fromOption, to: toOption },\n ({ org, app, from, to }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const summary = yield* apiClient.request((client) =>\n client.organizations.aiGateway.usage.summary(orgId, {\n applicationId: Option.getOrUndefined(app),\n from: Option.getOrUndefined(from),\n to: Option.getOrUndefined(to),\n })\n );\n yield* Console.log(JSON.stringify(summary, null, 2));\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst usageRequestsCommand = Command.make(\n 'requests',\n { org: orgOption, app: appOption, from: fromOption, to: toOption },\n ({ org, app, from, to }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const { items, total } = yield* apiClient.request((client) =>\n client.organizations.aiGateway.usage.requests(orgId, {\n applicationId: Option.getOrUndefined(app),\n from: Option.getOrUndefined(from),\n to: Option.getOrUndefined(to),\n })\n );\n if (items.length === 0) {\n yield* Console.log('No AI Gateway requests found.');\n return;\n }\n for (const e of items) {\n yield* Console.log(\n `${e.createdAt} ${e.modelRequested} ${e.status} ${e.totalTokens} tok ${e.billableCostMicros}µ$`\n );\n }\n yield* Console.log(`\\n${total} request(s).`);\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst outOption = Options.text('out').pipe(\n Options.withDescription('Write the CSV to this file instead of stdout'),\n Options.optional\n);\n\nconst usageExportCommand = Command.make(\n 'export',\n { org: orgOption, app: appOption, from: fromOption, to: toOption, out: outOption },\n ({ org, app, from, to, out }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const csv = yield* apiClient.request((client) =>\n client.organizations.aiGateway.usage.export(orgId, {\n applicationId: Option.getOrUndefined(app),\n from: Option.getOrUndefined(from),\n to: Option.getOrUndefined(to),\n })\n );\n const outPath = Option.getOrUndefined(out);\n if (outPath === undefined) {\n yield* Console.log(csv);\n } else {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .writeFileString(outPath, csv)\n .pipe(Effect.mapError((e) => new ApiRequestError({ message: `Failed to write ${outPath}: ${String(e)}` })));\n yield* Console.log(`Wrote ${outPath}.`);\n }\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst usageCommand = Command.make('usage', {}, () => Effect.void).pipe(\n Command.withSubcommands([usageSummaryCommand, usageRequestsCommand, usageExportCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai budgets\n// ---------------------------------------------------------------------------\n\nconst budgetsGetCommand = Command.make('get', { org: orgOption }, ({ org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const { items } = yield* apiClient.request((client) => client.organizations.aiGateway.budgets.list(orgId));\n yield* Console.log(JSON.stringify(items, null, 2));\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst budgetsSetCommand = Command.make('set', { org: orgOption, file: fileOption }, ({ org, file }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const parsed = yield* readJsonInput(file);\n const budgets = Array.isArray(parsed) ? parsed : (parsed as { budgets?: unknown }).budgets;\n if (!Array.isArray(budgets)) {\n return yield* Effect.fail(\n new ApiRequestError({\n message: 'Expected a JSON array of budgets, or an object of the form { \"budgets\": [...] }.',\n })\n );\n }\n const { items } = yield* apiClient.request((client) =>\n client.organizations.aiGateway.budgets.replace(orgId, budgets as AiGatewayBudgetInput[])\n );\n yield* Console.log(`Saved ${items.length} budget(s).`);\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst budgetsCommand = Command.make('budgets', {}, () => Effect.void).pipe(\n Command.withSubcommands([budgetsGetCommand, budgetsSetCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai policies\n// ---------------------------------------------------------------------------\n\nconst policiesGetCommand = Command.make('get', { org: orgOption, app: appOption }, ({ org, app }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const policy = yield* apiClient.request((client) =>\n client.organizations.aiGateway.policies.get(orgId, { applicationId: Option.getOrUndefined(app) })\n );\n yield* Console.log(policy === null ? 'No policy set.' : JSON.stringify(policy, null, 2));\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst policiesSetCommand = Command.make('set', { org: orgOption, file: fileOption }, ({ org, file }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const parsed = yield* readJsonInput(file);\n const policy = yield* apiClient.request((client) =>\n client.organizations.aiGateway.policies.put(orgId, parsed as AiGatewayPolicyInput)\n );\n yield* Console.log(`Policy saved${policy.applicationId ? ` for application ${policy.applicationId}` : ''}.`);\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst policiesCommand = Command.make('policies', {}, () => Effect.void).pipe(\n Command.withSubcommands([policiesGetCommand, policiesSetCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai models\n// ---------------------------------------------------------------------------\n\nconst inferenceErrorHandlers = {\n NotAuthenticatedError: (err: NotAuthenticatedError) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err: ApiRequestError) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n};\n\nconst modelsListCommand = Command.make('list', {}, () =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const { items } = yield* apiClient.request((client) => client.aiGateway.listModels());\n for (const m of items) {\n yield* Console.log(`${m.id} ${m.name} (ctx ${m.contextWindow})`);\n }\n }).pipe(Effect.catchTags(inferenceErrorHandlers))\n);\n\nconst modelIdArg = Args.text({ name: 'model-id' }).pipe(Args.withDescription('The model ID, e.g. openai/gpt-4o'));\n\nconst modelsGetCommand = Command.make('get', { modelId: modelIdArg }, ({ modelId }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const model = yield* apiClient.request((client) => client.aiGateway.getModel(modelId));\n yield* Console.log(JSON.stringify(model, null, 2));\n }).pipe(Effect.catchTags(inferenceErrorHandlers))\n);\n\nconst modelsCommand = Command.make('models', {}, () => Effect.void).pipe(\n Command.withSubcommands([modelsListCommand, modelsGetCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai chat\n// ---------------------------------------------------------------------------\n\nconst modelOption = Options.text('model').pipe(\n Options.withAlias('m'),\n Options.withDescription('The model ID to use, e.g. openai/gpt-4o')\n);\n\nconst streamOption = Options.boolean('stream').pipe(Options.withDescription('Stream the response token by token'));\n\nconst promptArg = Args.text({ name: 'prompt' }).pipe(\n Args.withDescription('The prompt text, or \"-\" to read from stdin')\n);\n\nconst chatCommand = Command.make(\n 'chat',\n { prompt: promptArg, model: modelOption, stream: streamOption },\n ({ prompt, model, stream }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const text = prompt === '-' ? yield* readStdin : prompt;\n const messages = [{ role: 'user', content: text }];\n\n if (stream) {\n const client = yield* apiClient.getClient;\n yield* Effect.tryPromise({\n try: async () => {\n for await (const chunk of client.aiGateway.chatCompletionsStream({ model, messages })) {\n process.stdout.write(chunk.choices[0]?.delta?.content ?? '');\n }\n process.stdout.write('\\n');\n },\n catch: (error) => new ApiRequestError({ message: error instanceof Error ? error.message : String(error) }),\n });\n return;\n }\n\n const response = yield* apiClient.request((client) => client.aiGateway.chatCompletions({ model, messages }));\n const content = response.choices[0]?.message.content;\n yield* Console.log(typeof content === 'string' ? content : JSON.stringify(content));\n }).pipe(Effect.catchTags(inferenceErrorHandlers))\n);\n\n// ---------------------------------------------------------------------------\n// ai (parent)\n// ---------------------------------------------------------------------------\n\nconst aiBase = Command.make('ai', {}, () => Effect.void);\n\n/** `gigadrive ai` — AI Gateway governance (usage, budgets, policies) and inference (models, chat). */\nexport const aiCommand = aiBase.pipe(\n Command.withSubcommands([usageCommand, budgetsCommand, policiesCommand, modelsCommand, chatCommand])\n);\n","import { Schema } from 'effect';\n\n// ---------------------------------------------------------------------------\n// Auth errors\n// ---------------------------------------------------------------------------\n\nexport class OAuthDiscoveryError extends Schema.TaggedError<OAuthDiscoveryError>()('OAuthDiscoveryError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class AuthStorageReadError extends Schema.TaggedError<AuthStorageReadError>()('AuthStorageReadError', {\n message: Schema.String,\n}) {}\n\nexport class AuthStorageWriteError extends Schema.TaggedError<AuthStorageWriteError>()('AuthStorageWriteError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class LoginFlowError extends Schema.TaggedError<LoginFlowError>()('LoginFlowError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class TokenExchangeError extends Schema.TaggedError<TokenExchangeError>()('TokenExchangeError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\n/** The device authorization request (RFC 8628 §3.1) failed. */\nexport class DeviceAuthorizationError extends Schema.TaggedError<DeviceAuthorizationError>()(\n 'DeviceAuthorizationError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n }\n) {}\n\n/** The user denied the device login on the verification page (`access_denied`). */\nexport class AuthorizationDeniedError extends Schema.TaggedError<AuthorizationDeniedError>()(\n 'AuthorizationDeniedError',\n {\n message: Schema.String,\n }\n) {}\n\n/** The device/user code expired before the user approved it (`expired_token`). */\nexport class DeviceCodeExpiredError extends Schema.TaggedError<DeviceCodeExpiredError>()('DeviceCodeExpiredError', {\n message: Schema.String,\n}) {}\n\nexport class TokenRefreshError extends Schema.TaggedError<TokenRefreshError>()('TokenRefreshError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\nexport class NotAuthenticatedError extends Schema.TaggedError<NotAuthenticatedError>()('NotAuthenticatedError', {\n message: Schema.String,\n}) {}\n\nexport class UserInfoFetchError extends Schema.TaggedError<UserInfoFetchError>()('UserInfoFetchError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\n// ---------------------------------------------------------------------------\n// API errors\n// ---------------------------------------------------------------------------\n\n/** A request to the Gigadrive Network API failed. Wraps the SDK's `ApiError`. */\nexport class ApiRequestError extends Schema.TaggedError<ApiRequestError>()('ApiRequestError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n code: Schema.optional(Schema.String),\n /** Finer-grained reason next to `code`, for example `daily_add_limit`. */\n reason: Schema.optional(Schema.String),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Command input errors\n// ---------------------------------------------------------------------------\n\n/** An environment-variable assignment was not in `KEY=VALUE` form. */\nexport class InvalidEnvVarFormatError extends Schema.TaggedError<InvalidEnvVarFormatError>()(\n 'InvalidEnvVarFormatError',\n {\n message: Schema.String,\n }\n) {}\n\n/** No environment variable matched the requested key or ID. */\nexport class EnvVarNotFoundError extends Schema.TaggedError<EnvVarNotFoundError>()('EnvVarNotFoundError', {\n message: Schema.String,\n}) {}\n\n/** No custom domain of the application matched the requested hostname or ID. */\nexport class DomainNotFoundError extends Schema.TaggedError<DomainNotFoundError>()('DomainNotFoundError', {\n message: Schema.String,\n}) {}\n\n/** `--wait` gave up: the domain did not start serving in time, or stopped in a state that needs action. */\nexport class DomainWaitError extends Schema.TaggedError<DomainWaitError>()('DomainWaitError', {\n message: Schema.String,\n state: Schema.String,\n}) {}\n\n/** The domain command's flags contradict each other or are out of range. */\nexport class InvalidDomainOptionsError extends Schema.TaggedError<InvalidDomainOptionsError>()(\n 'InvalidDomainOptionsError',\n { message: Schema.String }\n) {}\n\n/** A destructive command needs confirmation, but there is no terminal to ask on and `--yes` was not passed. */\nexport class ConfirmationRequiredError extends Schema.TaggedError<ConfirmationRequiredError>()(\n 'ConfirmationRequiredError',\n { message: Schema.String }\n) {}\n\n/** No organization was given and the linked project does not name one. */\nexport class OrganizationRequiredError extends Schema.TaggedError<OrganizationRequiredError>()(\n 'OrganizationRequiredError',\n { message: Schema.String }\n) {}\n\n/** The actor has no applications to link. */\nexport class NoApplicationsFoundError extends Schema.TaggedError<NoApplicationsFoundError>()(\n 'NoApplicationsFoundError',\n {\n message: Schema.String,\n }\n) {}\n\n/** The requested application ID was not among the actor's applications. */\nexport class ApplicationNotFoundError extends Schema.TaggedError<ApplicationNotFoundError>()(\n 'ApplicationNotFoundError',\n {\n message: Schema.String,\n }\n) {}\n\n/** The actor has no organization available for automatic application creation. */\nexport class NoOrganizationsFoundError extends Schema.TaggedError<NoOrganizationsFoundError>()(\n 'NoOrganizationsFoundError',\n {\n message: Schema.String,\n }\n) {}\n\n// ---------------------------------------------------------------------------\n// Env file / local credentials errors\n// ---------------------------------------------------------------------------\n\n/** Failed to read a local `.env` (or `.gitignore`) file. */\nexport class EnvFileReadError extends Schema.TaggedError<EnvFileReadError>()('EnvFileReadError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n/** Failed to write a local `.env` (or `.gitignore`) file. */\nexport class EnvFileWriteError extends Schema.TaggedError<EnvFileWriteError>()('EnvFileWriteError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n/** Failed to read `~/.gigadrive/dev-keys.json`. */\nexport class DevCredentialsStoreReadError extends Schema.TaggedError<DevCredentialsStoreReadError>()(\n 'DevCredentialsStoreReadError',\n {\n message: Schema.String,\n }\n) {}\n\n/** Failed to write `~/.gigadrive/dev-keys.json`. */\nexport class DevCredentialsStoreWriteError extends Schema.TaggedError<DevCredentialsStoreWriteError>()(\n 'DevCredentialsStoreWriteError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n }\n) {}\n\n// ---------------------------------------------------------------------------\n// Project errors\n// ---------------------------------------------------------------------------\n\nexport class ConfigNotFoundError extends Schema.TaggedError<ConfigNotFoundError>()('ConfigNotFoundError', {\n message: Schema.String,\n directory: Schema.String,\n}) {}\n\n/** The project directory has no `.gigadrive/project.json` link. */\nexport class ProjectNotLinkedError extends Schema.TaggedError<ProjectNotLinkedError>()('ProjectNotLinkedError', {\n message: Schema.String,\n directory: Schema.String,\n}) {}\n\n/** Failed to read or parse `.gigadrive/project.json`. */\nexport class ProjectLinkReadError extends Schema.TaggedError<ProjectLinkReadError>()('ProjectLinkReadError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n/** Failed to write `.gigadrive/project.json`. */\nexport class ProjectLinkWriteError extends Schema.TaggedError<ProjectLinkWriteError>()('ProjectLinkWriteError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class ConfigParseError extends Schema.TaggedError<ConfigParseError>()('ConfigParseError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class ConfigValidationError extends Schema.TaggedError<ConfigValidationError>()('ConfigValidationError', {\n message: Schema.String,\n errors: Schema.Array(Schema.String),\n}) {}\n\nexport class PackageJsonNotFoundError extends Schema.TaggedError<PackageJsonNotFoundError>()(\n 'PackageJsonNotFoundError',\n {\n message: Schema.String,\n directory: Schema.String,\n }\n) {}\n\nexport class PackageJsonParseError extends Schema.TaggedError<PackageJsonParseError>()('PackageJsonParseError', {\n message: Schema.String,\n directory: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class BuildScriptNotFoundError extends Schema.TaggedError<BuildScriptNotFoundError>()(\n 'BuildScriptNotFoundError',\n {\n message: Schema.String,\n }\n) {}\n\nexport class PackageManagerNotFoundError extends Schema.TaggedError<PackageManagerNotFoundError>()(\n 'PackageManagerNotFoundError',\n {\n message: Schema.String,\n directory: Schema.String,\n }\n) {}\n\n// ---------------------------------------------------------------------------\n// Build errors\n// ---------------------------------------------------------------------------\n\nexport class ExecError extends Schema.TaggedError<ExecError>()('ExecError', {\n message: Schema.String,\n command: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Deployment errors\n// ---------------------------------------------------------------------------\n\nexport class DeploymentCreateError extends Schema.TaggedError<DeploymentCreateError>()('DeploymentCreateError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\nexport class UploadStartError extends Schema.TaggedError<UploadStartError>()('UploadStartError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\nexport class PresignedUrlError extends Schema.TaggedError<PresignedUrlError>()('PresignedUrlError', {\n message: Schema.String,\n partNumber: Schema.Number,\n}) {}\n\nexport class UploadPartError extends Schema.TaggedError<UploadPartError>()('UploadPartError', {\n message: Schema.String,\n partNumber: Schema.Number,\n}) {}\n\nexport class UploadCompleteError extends Schema.TaggedError<UploadCompleteError>()('UploadCompleteError', {\n message: Schema.String,\n}) {}\n\nexport class DeploymentStatusError extends Schema.TaggedError<DeploymentStatusError>()('DeploymentStatusError', {\n message: Schema.String,\n}) {}\n\nexport class DeploymentLogsFetchError extends Schema.TaggedError<DeploymentLogsFetchError>()(\n 'DeploymentLogsFetchError',\n {\n message: Schema.String,\n }\n) {}\n\nexport class DeploymentHostnamesFetchError extends Schema.TaggedError<DeploymentHostnamesFetchError>()(\n 'DeploymentHostnamesFetchError',\n {\n message: Schema.String,\n }\n) {}\n\nexport class ArchiveCreateError extends Schema.TaggedError<ArchiveCreateError>()('ArchiveCreateError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class DeploymentAuthError extends Schema.TaggedError<DeploymentAuthError>()('DeploymentAuthError', {\n message: Schema.String,\n}) {}\n\nexport class DeploymentFailedError extends Schema.TaggedError<DeploymentFailedError>()('DeploymentFailedError', {\n message: Schema.String,\n}) {}\n","import { ApiError, GigadriveClient } from '@gigadrive/sdk';\nimport { Config, Effect, Option, Redacted } from 'effect';\nimport { ApiRequestError } from '../errors';\nimport { AuthService } from './auth';\n\n// ---------------------------------------------------------------------------\n// ApiClientService\n//\n// A single, shared factory for the `@gigadrive/sdk` client. Every command that\n// talks to the Gigadrive Network API obtains its client here so authentication\n// (a fresh access token from AuthService) and the base URL are configured in\n// exactly one place.\n// ---------------------------------------------------------------------------\n\nconst ApiBaseUrl = Config.string('GIGADRIVE_API_BASE_URL').pipe(Config.withDefault('https://api.gigadrive.network'));\nconst ServiceCredentials = Config.all({\n bearerToken: Config.redacted('GIGADRIVE_BEARER_TOKEN').pipe(Config.option),\n clientId: Config.string('GIGADRIVE_CLIENT_ID').pipe(Config.option),\n clientSecret: Config.redacted('GIGADRIVE_CLIENT_SECRET').pipe(Config.option),\n refreshToken: Config.redacted('GIGADRIVE_REFRESH_TOKEN').pipe(Config.option),\n});\n\n/** Map any error thrown by an SDK call into a tagged {@link ApiRequestError}. */\nconst toApiRequestError = (error: unknown): ApiRequestError => {\n if (error instanceof ApiError) {\n return new ApiRequestError({\n message: error.message,\n statusCode: error.status,\n code: error.code,\n reason: error.reason,\n });\n }\n return new ApiRequestError({ message: error instanceof Error ? error.message : String(error) });\n};\n\nexport class ApiClientService extends Effect.Service<ApiClientService>()('ApiClientService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const baseUrl = yield* ApiBaseUrl;\n const serviceCredentials = yield* ServiceCredentials;\n const authService = yield* AuthService;\n const hasServiceCredentials =\n Option.isSome(serviceCredentials.bearerToken) ||\n Option.isSome(serviceCredentials.clientId) ||\n Option.isSome(serviceCredentials.clientSecret) ||\n Option.isSome(serviceCredentials.refreshToken);\n\n /**\n * Build a `GigadriveClient` authenticated with a fresh access token.\n * Fails with `NotAuthenticatedError` when the user is not logged in.\n */\n const getClient = hasServiceCredentials\n ? Effect.succeed(\n new GigadriveClient({\n baseUrl,\n bearerToken: Option.map(serviceCredentials.bearerToken, Redacted.value).pipe(Option.getOrUndefined),\n clientId: Option.getOrUndefined(serviceCredentials.clientId),\n clientSecret: Option.map(serviceCredentials.clientSecret, Redacted.value).pipe(Option.getOrUndefined),\n refreshToken: Option.map(serviceCredentials.refreshToken, Redacted.value).pipe(Option.getOrUndefined),\n })\n )\n : Effect.gen(function* () {\n const token = yield* authService.getAccessToken;\n return new GigadriveClient({ bearerToken: token, baseUrl });\n });\n\n /**\n * Run an SDK call against an authenticated client, translating rejected\n * promises into a tagged {@link ApiRequestError}. This is the ergonomic\n * entry point for command handlers.\n *\n * @example\n * ```ts\n * const { items } = yield* apiClient.request((client) => client.applications.list());\n * ```\n */\n const request = <A>(f: (client: GigadriveClient) => Promise<A>) =>\n Effect.gen(function* () {\n const client = yield* getClient;\n return yield* Effect.tryPromise({\n try: () => f(client),\n catch: toApiRequestError,\n });\n });\n\n return { getClient, request };\n }),\n}) {}\n","import { Console, Duration, Effect, Option, Schema } from 'effect';\nimport process from 'node:process';\nimport open from 'open';\nimport { DeviceAuthorizationResponse, type OAuthClientConfig, type StoredAuthData } from '../domain';\nimport {\n AuthorizationDeniedError,\n DeviceAuthorizationError,\n DeviceCodeExpiredError,\n LoginFlowError,\n NotAuthenticatedError,\n TokenExchangeError,\n TokenRefreshError,\n UserInfoFetchError,\n} from '../errors';\nimport { writeClipboard } from '../lib/clipboard';\nimport { AuthStorageService } from './auth-storage';\nimport { OAuthConfigService } from './oauth-config';\n\n/** Grant type identifier for the OAuth 2.0 Device Authorization Grant (RFC 8628). */\nconst DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';\n\n/** Fallback poll interval (seconds) when the provider omits `interval`. */\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\n\n/**\n * Per-request timeout (seconds) for the device-authorization request and each\n * token poll. `fetch` has no default timeout, so without this a hung connection\n * would stall the poll loop and the RFC 8628 `expires_in` deadline (which is only\n * checked between requests) would never be enforced.\n */\nconst REQUEST_TIMEOUT_SECONDS = 30;\n\n// ---------------------------------------------------------------------------\n// AuthService\n// ---------------------------------------------------------------------------\n\nexport class AuthService extends Effect.Service<AuthService>()('AuthService', {\n accessors: true,\n dependencies: [OAuthConfigService.Default, AuthStorageService.Default],\n\n effect: Effect.gen(function* () {\n const oauthConfig = yield* OAuthConfigService;\n const storage = yield* AuthStorageService;\n\n // In-memory token cache\n let accessToken: string | null = null;\n let tokenExpirationTime = 0;\n\n const logout = Effect.gen(function* () {\n accessToken = null;\n tokenExpirationTime = 0;\n yield* storage.remove;\n yield* Effect.log('Logged out');\n });\n\n // Step 1 (RFC 8628 §3.1): request a device_code / user_code pair.\n const requestDeviceAuthorization = (config: OAuthClientConfig) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: (signal) =>\n fetch(config.deviceAuthorizeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: config.clientId, scope: config.scope }).toString(),\n signal,\n }),\n catch: (error) =>\n new DeviceAuthorizationError({\n message: `Device authorization request failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n if (!response.ok) {\n const body = yield* Effect.tryPromise({\n try: () => response.text(),\n catch: () =>\n new DeviceAuthorizationError({ message: 'Failed to read device authorization error response' }),\n });\n return yield* Effect.fail(\n new DeviceAuthorizationError({\n message: `Device authorization failed: ${response.status} ${response.statusText} - ${body}`,\n })\n );\n }\n\n const json = yield* Effect.tryPromise({\n try: () => response.json(),\n catch: () => new DeviceAuthorizationError({ message: 'Failed to parse device authorization response' }),\n });\n\n return yield* Schema.decodeUnknown(DeviceAuthorizationResponse)(json).pipe(\n Effect.mapError(\n () => new DeviceAuthorizationError({ message: 'Invalid device authorization response schema' })\n )\n );\n }).pipe(\n Effect.timeoutFail({\n duration: Duration.seconds(REQUEST_TIMEOUT_SECONDS),\n onTimeout: () => new DeviceAuthorizationError({ message: 'Device authorization request timed out' }),\n })\n );\n\n // A single poll of the token endpoint (RFC 8628 §3.4). Translates the RFC 8628\n // §3.5 poll errors into control-flow values; any other failure is fatal.\n const pollTokenOnce = (config: OAuthClientConfig, deviceCode: string) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: (signal) =>\n fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: DEVICE_CODE_GRANT_TYPE,\n client_id: config.clientId,\n device_code: deviceCode,\n }).toString(),\n signal,\n }),\n catch: (error) =>\n new TokenExchangeError({\n message: `Token poll request failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n if (response.ok) {\n const tokens = yield* Effect.tryPromise({\n try: () =>\n response.json() as Promise<{ access_token: string; refresh_token?: string; expires_in?: number }>,\n catch: () => new TokenExchangeError({ message: 'Failed to parse token response' }),\n });\n return { kind: 'tokens', tokens } as const;\n }\n\n const errorBody = yield* Effect.tryPromise({\n try: () => response.json() as Promise<{ error?: string }>,\n catch: () => new TokenExchangeError({ message: 'Failed to parse token poll error response' }),\n });\n\n switch (errorBody.error) {\n case 'authorization_pending':\n return { kind: 'pending' } as const;\n case 'slow_down':\n return { kind: 'slow_down' } as const;\n case 'access_denied':\n return { kind: 'denied' } as const;\n case 'expired_token':\n return { kind: 'expired' } as const;\n default:\n return yield* Effect.fail(\n new TokenExchangeError({\n message: `Token poll failed: ${response.status} ${response.statusText} - ${errorBody.error ?? 'unknown_error'}`,\n statusCode: response.status,\n })\n );\n }\n });\n\n // Step 2 (RFC 8628 §3.4–3.5): poll until approval, denial, or expiry.\n const pollForToken = (config: OAuthClientConfig, device: DeviceAuthorizationResponse) =>\n Effect.gen(function* () {\n const deadline = Date.now() + device.expires_in * 1000;\n let interval = device.interval ?? DEFAULT_POLL_INTERVAL_SECONDS;\n\n while (true) {\n yield* Effect.sleep(Duration.seconds(interval));\n\n if (Date.now() >= deadline) {\n return yield* Effect.fail(\n new DeviceCodeExpiredError({\n message: 'The login code expired before it was approved. Please run `gigadrive login` again.',\n })\n );\n }\n\n const result = yield* pollTokenOnce(config, device.device_code).pipe(\n // A hung poll must not stall the loop: on timeout treat it as pending so\n // the next iteration re-checks the expiry deadline.\n Effect.timeoutTo({\n duration: Duration.seconds(REQUEST_TIMEOUT_SECONDS),\n onSuccess: (value) => value,\n onTimeout: () => ({ kind: 'pending' }) as const,\n })\n );\n switch (result.kind) {\n case 'tokens':\n return result.tokens;\n case 'pending':\n continue;\n case 'slow_down':\n // RFC 8628 §3.5: back off by 5 seconds on slow_down.\n interval += 5;\n continue;\n case 'denied':\n return yield* Effect.fail(new AuthorizationDeniedError({ message: 'The login request was denied.' }));\n case 'expired':\n return yield* Effect.fail(\n new DeviceCodeExpiredError({\n message: 'The login code expired before it was approved. Please run `gigadrive login` again.',\n })\n );\n }\n }\n });\n\n // Runs alongside polling in a TTY: lets the user press \"c\" to copy the URL\n // (Claude-Code style) and Ctrl+C to cancel. Never completes on its own — the\n // poll loop wins the race and interrupts this, restoring the terminal.\n const watchCopyKey = (url: string) =>\n Effect.async<never, LoginFlowError>((resume) => {\n const stdin = process.stdin;\n if (!stdin.isTTY) {\n // Not interactive: nothing to listen for; wait to be interrupted.\n return;\n }\n\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n const onData = (key: string) => {\n if (key === 'c' || key === 'C') {\n writeClipboard(url);\n // runSync inside a raw Node callback — a deliberate, localized exception.\n Console.log('Copied the login URL to your clipboard.').pipe(Effect.runSync);\n } else if (key === '\\u0003') {\n // Ctrl+C: raw mode suppresses SIGINT, so handle cancellation explicitly.\n resume(Effect.fail(new LoginFlowError({ message: 'Login canceled.' })));\n }\n };\n\n stdin.on('data', onData);\n\n return Effect.sync(() => {\n stdin.off('data', onData);\n if (stdin.isTTY) stdin.setRawMode(false);\n stdin.pause();\n });\n });\n\n const login = Effect.gen(function* () {\n yield* logout;\n\n const config = yield* oauthConfig.getConfig;\n const device = yield* requestDeviceAuthorization(config);\n\n const verificationUri = device.verification_uri;\n const verificationUriComplete = device.verification_uri_complete ?? verificationUri;\n const interactive = process.stdin.isTTY === true;\n\n yield* Console.log(\n `\\nTo sign in, visit:\\n\\n ${verificationUri}\\n\\nand enter the code:\\n\\n ${device.user_code}\\n`\n );\n\n if (interactive) {\n // Best-effort: the URL is printed above regardless. Route through the Effect\n // runtime so a spawn/DISPLAY failure can't become an unhandled rejection.\n yield* Effect.tryPromise(() => open(verificationUriComplete)).pipe(Effect.catchAll(() => Effect.void));\n yield* Console.log('We tried to open your browser automatically. If it did not open, use the URL above.');\n yield* Console.log('Press \"c\" to copy the URL to your clipboard, or Ctrl+C to cancel.');\n }\n\n yield* Console.log('\\nWaiting for you to approve the login…');\n\n const poll = pollForToken(config, device);\n // `watchCopyKey` never completes on its own, so use `raceFirst` (settles on the\n // first effect to finish, success or failure) — plain `race` waits for a success\n // and would hang here when the poll fails (e.g. denied/expired).\n const tokens = yield* interactive ? poll.pipe(Effect.raceFirst(watchCopyKey(verificationUriComplete))) : poll;\n\n if (!tokens.refresh_token) {\n return yield* Effect.fail(\n new TokenExchangeError({ message: 'No refresh token received from identity provider' })\n );\n }\n\n accessToken = tokens.access_token;\n tokenExpirationTime = Date.now() + (tokens.expires_in || 3600) * 1000;\n\n yield* storage.save({\n refreshToken: tokens.refresh_token,\n accessToken,\n tokenExpirationTime,\n });\n\n yield* Effect.log('Login successful');\n return true as const;\n });\n\n const refreshAccessToken: Effect.Effect<true, TokenRefreshError> = Effect.gen(function* () {\n const stored: Option.Option<StoredAuthData> = yield* storage.load.pipe(\n Effect.catchTag('AuthStorageReadError', (err) => Effect.fail(new TokenRefreshError({ message: err.message })))\n );\n const config = yield* oauthConfig.getConfig.pipe(\n Effect.catchTag('OAuthDiscoveryError', (err) => Effect.fail(new TokenRefreshError({ message: err.message })))\n );\n\n const authData: StoredAuthData = yield* Option.match(stored, {\n onNone: () => Effect.fail(new TokenRefreshError({ message: 'No refresh token available. Please log in.' })),\n onSome: (data: StoredAuthData) =>\n data.refreshToken\n ? Effect.succeed(data)\n : Effect.fail(new TokenRefreshError({ message: 'No refresh token available. Please log in.' })),\n });\n\n const response = yield* Effect.tryPromise({\n try: () =>\n fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: authData.refreshToken,\n }).toString(),\n }),\n catch: (error) =>\n new TokenRefreshError({\n message: `Token refresh request failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n if (!response.ok) {\n if (response.status === 400) {\n yield* logout.pipe(Effect.catchAll(() => Effect.void));\n return yield* Effect.fail(\n new TokenRefreshError({\n message: 'Refresh token is invalid or expired. Please log in again.',\n statusCode: response.status,\n })\n );\n }\n const body = yield* Effect.tryPromise({\n try: () => response.text(),\n catch: () => new TokenRefreshError({ message: 'Failed to read refresh error response' }),\n });\n return yield* Effect.fail(\n new TokenRefreshError({\n message: `Token refresh failed: ${response.status} ${response.statusText} - ${body}`,\n statusCode: response.status,\n })\n );\n }\n\n const tokens = yield* Effect.tryPromise({\n try: () => response.json() as Promise<{ access_token: string; refresh_token?: string; expires_in?: number }>,\n catch: () => new TokenRefreshError({ message: 'Failed to parse token refresh response' }),\n });\n\n accessToken = tokens.access_token;\n tokenExpirationTime = Date.now() + (tokens.expires_in || 3600) * 1000;\n const newRefreshToken = tokens.refresh_token || authData.refreshToken;\n\n yield* storage\n .save({\n refreshToken: newRefreshToken,\n accessToken,\n tokenExpirationTime,\n })\n .pipe(Effect.catchAll(() => Effect.void));\n\n yield* Effect.log('Access token refreshed successfully');\n return true as const;\n });\n\n const getAccessToken = Effect.gen(function* () {\n // Check in-memory cache\n if (accessToken && Date.now() < tokenExpirationTime) {\n return accessToken;\n }\n\n // Try to load from storage\n const stored: Option.Option<StoredAuthData> = yield* storage.load.pipe(\n Effect.catchAll(() => Effect.succeed(Option.none<StoredAuthData>()))\n );\n Option.match(stored, {\n onNone: () => {},\n onSome: (data: StoredAuthData) => {\n if (data.accessToken && data.tokenExpirationTime && Date.now() < data.tokenExpirationTime) {\n accessToken = data.accessToken;\n tokenExpirationTime = data.tokenExpirationTime;\n }\n },\n });\n\n if (accessToken && Date.now() < tokenExpirationTime) {\n return accessToken;\n }\n\n // Try refresh\n yield* Effect.log('Access token expired or not available. Attempting to refresh...');\n yield* refreshAccessToken.pipe(\n Effect.catchTag('TokenRefreshError', (err) => Effect.fail(new NotAuthenticatedError({ message: err.message })))\n );\n\n if (!accessToken) {\n return yield* Effect.fail(\n new NotAuthenticatedError({ message: 'No valid access token available. Please log in first.' })\n );\n }\n\n return accessToken;\n });\n\n const getUserInfo = Effect.gen(function* () {\n const config = yield* oauthConfig.getConfig;\n const token = yield* getAccessToken;\n\n const fetchUserInfo = (t: string) =>\n Effect.tryPromise({\n try: () =>\n fetch(config.userinfoUrl, {\n headers: {\n Authorization: `Bearer ${t}`,\n Accept: 'application/json',\n },\n }),\n catch: (error) =>\n new UserInfoFetchError({\n message: `Failed to fetch user info: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n let response = yield* fetchUserInfo(token);\n\n // Retry once on 401/403\n if (response.status === 401 || response.status === 403) {\n yield* refreshAccessToken.pipe(\n Effect.catchTag('TokenRefreshError', (err) => Effect.fail(new UserInfoFetchError({ message: err.message })))\n );\n if (!accessToken) {\n return yield* Effect.fail(new UserInfoFetchError({ message: 'Token refresh failed' }));\n }\n response = yield* fetchUserInfo(accessToken);\n }\n\n if (!response.ok) {\n const body = yield* Effect.tryPromise({\n try: () => response.text(),\n catch: () => new UserInfoFetchError({ message: 'Failed to read user info error response' }),\n });\n return yield* Effect.fail(\n new UserInfoFetchError({\n message: `Failed to fetch user info: ${response.status} ${response.statusText}${body ? ` - ${body}` : ''}`,\n statusCode: response.status,\n })\n );\n }\n\n const data = yield* Effect.tryPromise({\n try: () => response.json() as Promise<Record<string, unknown>>,\n catch: () => new UserInfoFetchError({ message: 'Failed to parse user info response' }),\n });\n\n return data;\n });\n\n const inferUserName = (info: Record<string, unknown>): string => {\n const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.trim() !== '';\n\n const name = info.name;\n const givenName = info.given_name;\n const familyName = info.family_name;\n const preferredUsername = info.preferred_username;\n const email = info.email;\n\n return (\n (isNonEmptyString(name) && name) ||\n (isNonEmptyString(givenName) && isNonEmptyString(familyName) ? `${givenName} ${familyName}` : undefined) ||\n (isNonEmptyString(preferredUsername) && preferredUsername) ||\n (isNonEmptyString(email) && email) ||\n 'your account'\n );\n };\n\n return { login, logout, getAccessToken, getUserInfo, refreshAccessToken, inferUserName };\n }),\n}) {}\n","import { Schema } from 'effect';\n\n// ---------------------------------------------------------------------------\n// Re-export shared types from SDK\n// ---------------------------------------------------------------------------\n\nexport type { DeploymentLog, DeploymentLogPage, DeploymentLogType, DeploymentStatus } from '@gigadrive/sdk';\n\n// ---------------------------------------------------------------------------\n// Branded IDs (CLI-specific, for type safety within Effect pipelines)\n// ---------------------------------------------------------------------------\n\nexport const DeploymentId = Schema.String.pipe(Schema.brand('@Gigadrive/DeploymentId'));\nexport type DeploymentId = Schema.Schema.Type<typeof DeploymentId>;\n\nexport const ApplicationId = Schema.String.pipe(Schema.brand('@Gigadrive/ApplicationId'));\nexport type ApplicationId = Schema.Schema.Type<typeof ApplicationId>;\n\nexport const UploadId = Schema.String.pipe(Schema.brand('@Gigadrive/UploadId'));\nexport type UploadId = Schema.Schema.Type<typeof UploadId>;\n\n// ---------------------------------------------------------------------------\n// CLI-specific domain schemas\n// ---------------------------------------------------------------------------\n\nexport const PackageManager = Schema.Literal('npm', 'yarn', 'pnpm', 'bun');\nexport type PackageManager = Schema.Schema.Type<typeof PackageManager>;\n\n// ---------------------------------------------------------------------------\n// OAuth schemas (CLI-specific, for interactive login flow)\n// ---------------------------------------------------------------------------\n\nexport const OAuthTokens = Schema.Struct({\n access_token: Schema.String,\n refresh_token: Schema.optional(Schema.String),\n expires_in: Schema.optional(Schema.Number),\n token_type: Schema.optional(Schema.String),\n});\nexport type OAuthTokens = Schema.Schema.Type<typeof OAuthTokens>;\n\nexport const OAuthClientConfig = Schema.Struct({\n clientId: Schema.String,\n issuer: Schema.String,\n authorizeUrl: Schema.String,\n tokenUrl: Schema.String,\n deviceAuthorizeUrl: Schema.String,\n scope: Schema.String,\n userinfoUrl: Schema.String,\n});\nexport type OAuthClientConfig = Schema.Schema.Type<typeof OAuthClientConfig>;\n\n/**\n * Response from the OAuth 2.0 Device Authorization Endpoint (RFC 8628 §3.2).\n * `verification_uri_complete` and `interval` are RECOMMENDED/OPTIONAL per the spec.\n */\nexport const DeviceAuthorizationResponse = Schema.Struct({\n device_code: Schema.String,\n user_code: Schema.String,\n verification_uri: Schema.String,\n verification_uri_complete: Schema.optional(Schema.String),\n expires_in: Schema.Number,\n interval: Schema.optional(Schema.Number),\n});\nexport type DeviceAuthorizationResponse = Schema.Schema.Type<typeof DeviceAuthorizationResponse>;\n\nexport const StoredAuthData = Schema.Struct({\n refreshToken: Schema.String,\n accessToken: Schema.optional(Schema.String),\n tokenExpirationTime: Schema.optional(Schema.Number),\n});\nexport type StoredAuthData = Schema.Schema.Type<typeof StoredAuthData>;\n\n// ---------------------------------------------------------------------------\n// Project link (.gigadrive/project.json) — links a working directory to an app\n// ---------------------------------------------------------------------------\n\nexport const ProjectLink = Schema.Struct({\n applicationId: Schema.String,\n organizationId: Schema.optional(Schema.String),\n});\nexport type ProjectLink = Schema.Schema.Type<typeof ProjectLink>;\n\n// ---------------------------------------------------------------------------\n// Local dev API-key store (~/.gigadrive/dev-keys.json)\n// Maps an application ID to the ID of the API key the CLI provisioned for local\n// development, so re-runs can rotate/revoke the previous key instead of piling\n// up. Only the key ID is stored — never the secret (which is unrecoverable).\n// ---------------------------------------------------------------------------\n\nexport const DevKeyEntry = Schema.Struct({\n apiKeyId: Schema.String,\n});\nexport type DevKeyEntry = Schema.Schema.Type<typeof DevKeyEntry>;\n\nexport const DevKeyStore = Schema.Record({ key: Schema.String, value: DevKeyEntry });\nexport type DevKeyStore = Schema.Schema.Type<typeof DevKeyStore>;\n","import { spawn } from 'node:child_process';\nimport process from 'node:process';\n\ninterface ClipboardCommand {\n cmd: string;\n args: string[];\n}\n\n/**\n * Ordered list of clipboard commands to try for the current platform. On Linux\n * we try Wayland first, then the common X11 tools; the first one that spawns\n * successfully wins.\n */\nconst clipboardCandidates = (): ClipboardCommand[] => {\n switch (process.platform) {\n case 'darwin':\n return [{ cmd: 'pbcopy', args: [] }];\n case 'win32':\n return [{ cmd: 'clip', args: [] }];\n default:\n return [\n { cmd: 'wl-copy', args: [] },\n { cmd: 'xclip', args: ['-selection', 'clipboard'] },\n { cmd: 'xsel', args: ['--clipboard', '--input'] },\n ];\n }\n};\n\n/**\n * Best-effort copy of `text` to the OS clipboard by spawning the platform's\n * clipboard utility (`pbcopy` / `clip` / `wl-copy` / `xclip` / `xsel`). Never\n * throws: if no utility is available the call is silently a no-op, so callers\n * can offer \"press c to copy\" without a hard dependency.\n */\nexport function writeClipboard(text: string): void {\n const candidates = clipboardCandidates();\n\n const tryNext = (index: number): void => {\n if (index >= candidates.length) return;\n const { cmd, args } = candidates[index];\n\n let proc;\n try {\n proc = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] });\n } catch {\n tryNext(index + 1);\n return;\n }\n\n // ENOENT (utility not installed) surfaces as an async 'error' event.\n proc.on('error', () => tryNext(index + 1));\n proc.stdin?.on('error', () => {\n /* ignore broken pipe */\n });\n proc.stdin?.end(text);\n };\n\n tryNext(0);\n}\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option, Schema } from 'effect';\nimport * as os from 'node:os';\nimport type { StoredAuthData } from '../domain';\nimport { StoredAuthData as StoredAuthDataSchema } from '../domain';\nimport { AuthStorageReadError, AuthStorageWriteError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// AuthStorageService\n// ---------------------------------------------------------------------------\n\nexport class AuthStorageService extends Effect.Service<AuthStorageService>()('AuthStorageService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const homeDir = os.homedir();\n const authDir = pathService.join(homeDir, '.gigadrive');\n const authFile = pathService.join(authDir, 'auth.json');\n\n const ensureDirectory = Effect.gen(function* () {\n yield* fs.makeDirectory(authDir, { recursive: true }).pipe(\n Effect.mapError(\n (error) =>\n new AuthStorageWriteError({\n message: 'Failed to create auth directory',\n cause: String(error),\n })\n )\n );\n yield* fs.chmod(authDir, 0o700).pipe(\n Effect.mapError(\n (error) =>\n new AuthStorageWriteError({\n message: 'Failed to set auth directory permissions',\n cause: String(error),\n })\n )\n );\n });\n\n const load = Effect.gen(function* () {\n const exists = yield* fs\n .exists(authFile)\n .pipe(Effect.mapError(() => new AuthStorageReadError({ message: 'Failed to check auth file existence' })));\n if (!exists) return Option.none<StoredAuthData>();\n\n const data = yield* fs\n .readFileString(authFile, 'utf8')\n .pipe(Effect.mapError(() => new AuthStorageReadError({ message: 'Failed to read auth file' })));\n\n const json = yield* Effect.try({\n try: () => JSON.parse(data) as unknown,\n catch: () => new AuthStorageReadError({ message: 'Auth file contains invalid JSON' }),\n });\n\n const authData = yield* Schema.decodeUnknown(StoredAuthDataSchema)(json).pipe(\n Effect.mapError(() => new AuthStorageReadError({ message: 'Auth file has invalid schema' }))\n );\n\n return Option.some(authData);\n });\n\n const save = Effect.fn('AuthStorageService.save')(function* (authData: StoredAuthData) {\n yield* ensureDirectory;\n yield* fs.writeFileString(authFile, JSON.stringify(authData, null, 2), { mode: 0o600 }).pipe(\n Effect.mapError(\n (error) =>\n new AuthStorageWriteError({\n message: 'Failed to write auth file',\n cause: String(error),\n })\n )\n );\n yield* Effect.log('Auth data saved to local storage');\n });\n\n const remove = Effect.gen(function* () {\n yield* fs.remove(authFile).pipe(\n Effect.mapError((error) => {\n const cause = error instanceof Error ? error : (error as { error?: Error }).error;\n const code = cause && typeof cause === 'object' && 'code' in cause ? (cause as { code: string }).code : '';\n return { isNotFound: code === 'ENOENT' || String(error).includes('ENOENT'), original: error };\n }),\n Effect.catchAll((mapped) =>\n mapped.isNotFound\n ? Effect.void\n : Effect.fail(\n new AuthStorageWriteError({\n message: 'Failed to remove auth file',\n cause: String(mapped.original),\n })\n )\n )\n );\n yield* Effect.log('Auth data removed from local storage');\n });\n\n return { load, save, remove };\n }),\n}) {}\n","import { Config, Effect, Schema } from 'effect';\nimport type { OAuthClientConfig } from '../domain';\nimport { OAuthDiscoveryError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// Environment config (replaces env.ts + @t3-oss/env-core + zod + dotenv)\n// ---------------------------------------------------------------------------\n\nconst OAuthEnvConfig = Config.all({\n issuerUrl: Config.string('GIGADRIVE_NETWORK_OAUTH_ISSUER_URL').pipe(Config.withDefault('https://idp.gigadrive.de')),\n // Default is the first-party CLI's public OAuth client (seeded in the Network\n // repo). Override with GIGADRIVE_NETWORK_OAUTH_CLIENT_ID per environment.\n clientId: Config.string('GIGADRIVE_NETWORK_OAUTH_CLIENT_ID').pipe(\n Config.withDefault('0195c11c-0000-7000-8000-000000000001')\n ),\n});\n\n// ---------------------------------------------------------------------------\n// OIDC discovery document schema\n// ---------------------------------------------------------------------------\n\nconst OpenIdDiscoveryDocument = Schema.Struct({\n issuer: Schema.optional(Schema.String),\n authorization_endpoint: Schema.optional(Schema.String),\n token_endpoint: Schema.optional(Schema.String),\n userinfo_endpoint: Schema.optional(Schema.String),\n device_authorization_endpoint: Schema.optional(Schema.String),\n});\n\n/**\n * Scopes requested at login. Identity scopes plus the Network API capability\n * scopes available to the standalone first-party CLI and the platform scopes\n * needed to provision local-dev API credentials. AI Gateway governance scopes\n * are intentionally excluded because the IDP only grants them to OAuth clients\n * bound to a Network application; requesting one would reject the entire login.\n */\nconst CLI_SCOPES = [\n // Identity / OIDC\n 'offline_access',\n 'openid',\n 'profile',\n 'email',\n // Platform discovery used for zero-config application onboarding\n 'platform:organizations:read',\n // Network API capabilities\n 'network:applications:read',\n 'network:applications:write',\n 'network:env_vars:read',\n 'network:env_vars:write',\n 'network:env_vars:delete',\n 'network:deployments:read',\n 'network:deployments:write',\n 'network:deployments:trigger',\n 'network:ai_gateway:chat',\n 'network:ai_gateway:models',\n // Provisioning local-dev API credentials\n 'platform:api_keys:read',\n 'platform:api_keys:write',\n 'platform:api_keys:delete',\n] as const;\n\nconst DEFAULT_SCOPE = CLI_SCOPES.join(' ');\n\n// ---------------------------------------------------------------------------\n// OAuthConfigService\n// ---------------------------------------------------------------------------\n\nexport class OAuthConfigService extends Effect.Service<OAuthConfigService>()('OAuthConfigService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const envConfig = yield* OAuthEnvConfig;\n let cached: OAuthClientConfig | null = null;\n\n const getConfig: Effect.Effect<OAuthClientConfig, OAuthDiscoveryError> = Effect.gen(function* () {\n if (cached) return cached;\n\n const issuerBase = envConfig.issuerUrl.replace(/\\/$/, '');\n const discoveryUrl = `${issuerBase}/.well-known/openid-configuration`;\n\n yield* Effect.log('Fetching OIDC discovery document', { discoveryUrl });\n\n const response = yield* Effect.tryPromise({\n try: (signal) => fetch(discoveryUrl, { signal }),\n catch: (error) =>\n new OAuthDiscoveryError({\n message: 'Failed to fetch OIDC discovery document',\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n if (!response.ok) {\n return yield* Effect.fail(\n new OAuthDiscoveryError({\n message: `OIDC discovery returned ${response.status} ${response.statusText}`,\n })\n );\n }\n\n const json = yield* Effect.tryPromise({\n try: () => response.json(),\n catch: () =>\n new OAuthDiscoveryError({\n message: 'Failed to parse OIDC discovery JSON',\n }),\n });\n\n const decoded = yield* Schema.decodeUnknown(OpenIdDiscoveryDocument)(json).pipe(\n Effect.mapError(\n () =>\n new OAuthDiscoveryError({\n message: 'Invalid OIDC discovery document schema',\n })\n )\n );\n\n if (\n !decoded.authorization_endpoint ||\n !decoded.token_endpoint ||\n !decoded.userinfo_endpoint ||\n !decoded.device_authorization_endpoint\n ) {\n return yield* Effect.fail(\n new OAuthDiscoveryError({\n message: 'OIDC discovery returned incomplete endpoints',\n })\n );\n }\n\n const config: OAuthClientConfig = {\n clientId: envConfig.clientId,\n issuer: decoded.issuer ?? issuerBase,\n authorizeUrl: decoded.authorization_endpoint,\n tokenUrl: decoded.token_endpoint,\n deviceAuthorizeUrl: decoded.device_authorization_endpoint,\n scope: DEFAULT_SCOPE,\n userinfoUrl: decoded.userinfo_endpoint,\n };\n\n cached = config;\n yield* Effect.log('OIDC discovery completed', { issuer: config.issuer });\n return config;\n });\n\n return { getConfig };\n }),\n}) {}\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option, Schema } from 'effect';\nimport type { ProjectLink } from '../domain';\nimport { ProjectLink as ProjectLinkSchema } from '../domain';\nimport { ProjectLinkReadError, ProjectLinkWriteError, ProjectNotLinkedError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// ProjectLinkService\n//\n// Links a working directory to a Gigadrive application by persisting the choice\n// in `<projectFolder>/.gigadrive/project.json`. Commands read the linked\n// application so they don't require an explicit `--app` on every invocation.\n// ---------------------------------------------------------------------------\n\nconst LINK_DIR = '.gigadrive';\nconst LINK_FILE = 'project.json';\n\nexport class ProjectLinkService extends Effect.Service<ProjectLinkService>()('ProjectLinkService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const linkDir = (projectFolder: string) => pathService.join(projectFolder, LINK_DIR);\n const linkFile = (projectFolder: string) => pathService.join(projectFolder, LINK_DIR, LINK_FILE);\n\n /** Load the project link, returning `Option.none` when the directory is not linked. */\n const load = Effect.fn('ProjectLinkService.load')(function* (projectFolder: string) {\n const file = linkFile(projectFolder);\n\n const exists = yield* fs\n .exists(file)\n .pipe(Effect.mapError(() => new ProjectLinkReadError({ message: 'Failed to check project link existence' })));\n if (!exists) return Option.none<ProjectLink>();\n\n const data = yield* fs\n .readFileString(file, 'utf8')\n .pipe(Effect.mapError(() => new ProjectLinkReadError({ message: 'Failed to read project link file' })));\n\n const json = yield* Effect.try({\n try: () => JSON.parse(data) as unknown,\n catch: () => new ProjectLinkReadError({ message: `${LINK_DIR}/${LINK_FILE} contains invalid JSON` }),\n });\n\n const link = yield* Schema.decodeUnknown(ProjectLinkSchema)(json).pipe(\n Effect.mapError(() => new ProjectLinkReadError({ message: `${LINK_DIR}/${LINK_FILE} has an invalid schema` }))\n );\n\n return Option.some(link);\n });\n\n /** Load the project link, failing with `ProjectNotLinkedError` when absent. */\n const resolve = Effect.fn('ProjectLinkService.resolve')(function* (projectFolder: string) {\n const link = yield* load(projectFolder);\n return yield* Option.match(link, {\n onNone: () =>\n Effect.fail(\n new ProjectNotLinkedError({\n message: 'This directory is not linked to an application. Run \"gigadrive link\" first.',\n directory: projectFolder,\n })\n ),\n onSome: (value) => Effect.succeed(value),\n });\n });\n\n /** Persist the project link, creating `.gigadrive/` if needed. */\n const save = Effect.fn('ProjectLinkService.save')(function* (projectFolder: string, link: ProjectLink) {\n yield* fs\n .makeDirectory(linkDir(projectFolder), { recursive: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new ProjectLinkWriteError({ message: 'Failed to create .gigadrive directory', cause: String(error) })\n )\n );\n yield* fs\n .writeFileString(linkFile(projectFolder), `${JSON.stringify(link, null, 2)}\\n`)\n .pipe(\n Effect.mapError(\n (error) => new ProjectLinkWriteError({ message: 'Failed to write project link file', cause: String(error) })\n )\n );\n yield* Effect.log('Project link saved', { applicationId: link.applicationId });\n });\n\n /** Remove the project link file, treating a missing file as success. */\n const remove = Effect.fn('ProjectLinkService.remove')(function* (projectFolder: string) {\n // `force: true` makes removing a missing file a no-op (@effect/platform swallows the\n // NotFound SystemError); genuine failures (e.g. permissions) still surface below.\n yield* fs\n .remove(linkFile(projectFolder), { force: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new ProjectLinkWriteError({ message: 'Failed to remove project link file', cause: String(error) })\n )\n );\n });\n\n return { load, resolve, save, remove };\n }),\n}) {}\n","import { Command, Options } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApiClientService } from '../../services/api-client';\n\nconst listOrgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Only list applications belonging to this organization ID'),\n Options.optional\n);\n\nconst createOrgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Organization ID that will own the application')\n);\n\nconst nameOption = Options.text('name').pipe(\n Options.withAlias('n'),\n Options.withDescription('Application display name')\n);\n\nconst slugOption = Options.text('slug').pipe(\n Options.withDescription('Optional lowercase application slug'),\n Options.optional\n);\n\nconst rootDirectoryOption = Options.text('root-directory').pipe(\n Options.withDescription('Optional project directory relative to the repository root'),\n Options.optional\n);\n\nconst appsListCommand = Command.make('list', { org: listOrgOption }, ({ org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = Option.getOrUndefined(org);\n const { items, total } = yield* apiClient.request((client) => client.applications.list({ organizationId }));\n\n if (items.length === 0) {\n yield* Console.log('No applications found.');\n return;\n }\n\n for (const app of items) {\n yield* Console.log(`${app.id} ${app.name} (${app.organization.name})`);\n }\n yield* Console.log(`\\n${total} application(s).`);\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list applications: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst appsCreateCommand = Command.make(\n 'create',\n { org: createOrgOption, name: nameOption, slug: slugOption, rootDirectory: rootDirectoryOption },\n ({ org, name, slug, rootDirectory }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const application = yield* apiClient.request((client) =>\n client.applications.create({\n organizationId: org,\n name,\n ...Option.match(slug, { onNone: () => ({}), onSome: (value) => ({ slug: value }) }),\n ...Option.match(rootDirectory, {\n onNone: () => ({}),\n onSome: (value) => ({ rootDirectory: value }),\n }),\n })\n );\n\n yield* Console.log(`Created application ${application.name} (${application.id}).`);\n yield* Console.log(`Run \"gigadrive link --app ${application.id}\" to link the current directory.`);\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to create application: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst appsBase = Command.make('apps', {}, () => Effect.void);\n\n/** `gigadrive apps` — create and inspect applications the authenticated actor can access. */\nexport const appsCommand = appsBase.pipe(Command.withSubcommands([appsListCommand, appsCreateCommand]));\n","import { Command } from '@effect/cli';\nimport { FileSystem, Path } from '@effect/platform';\nimport { exec } from '@gigadrive/build-utils';\nimport { Console, Effect } from 'effect';\nimport { BuildScriptNotFoundError, ExecError, PackageJsonNotFoundError, PackageJsonParseError } from '../../errors';\nimport { PackageManagerService } from '../../services/package-manager';\n\nexport const buildCommand = Command.make('build', {}, () =>\n Effect.gen(function* () {\n const pmService = yield* PackageManagerService;\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n const cwd = process.cwd();\n\n yield* Effect.log('Starting build', { cwd });\n\n // Validate package.json exists\n const packageJsonPath = pathService.join(cwd, 'package.json');\n const packageJsonExists = yield* fs\n .exists(packageJsonPath)\n .pipe(\n Effect.mapError(\n () => new PackageJsonNotFoundError({ message: 'Failed to check for package.json', directory: cwd })\n )\n );\n if (!packageJsonExists) {\n return yield* Effect.fail(new PackageJsonNotFoundError({ message: 'No package.json found', directory: cwd }));\n }\n\n // Read and validate build script\n const packageJsonContent = yield* fs\n .readFileString(packageJsonPath, 'utf-8')\n .pipe(\n Effect.mapError(() => new PackageJsonNotFoundError({ message: 'Failed to read package.json', directory: cwd }))\n );\n\n const packageJson = yield* Effect.try({\n try: () => JSON.parse(packageJsonContent) as { scripts?: { build?: string } },\n catch: (error) =>\n new PackageJsonParseError({\n message: 'Failed to parse package.json',\n directory: cwd,\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n if (!packageJson.scripts?.build) {\n return yield* Effect.fail(new BuildScriptNotFoundError({ message: 'No build script found in package.json' }));\n }\n\n // Detect package manager\n const pm = yield* pmService.detect(cwd);\n\n const buildEnv = {\n ...process.env,\n NODE_ENV: 'production',\n NEBULA: '1',\n VERCEL: '1',\n NOW_BUILDER: '1',\n };\n\n // Install dependencies\n const installCmd = pmService.installCommand(pm);\n yield* Console.log(`Running: ${installCmd}`);\n yield* Effect.tryPromise({\n try: () =>\n exec({\n command: installCmd,\n cwd,\n env: buildEnv,\n onOutput: (chunk) => {\n Console.log(chunk).pipe(Effect.runSync);\n },\n }),\n catch: (error) =>\n new ExecError({\n message: 'Install failed',\n command: installCmd,\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n // Run build\n const buildCmd = pmService.buildCommand(pm);\n yield* Console.log(`Running: ${buildCmd}`);\n yield* Effect.tryPromise({\n try: () =>\n exec({\n command: buildCmd,\n cwd,\n env: buildEnv,\n onOutput: (chunk) => {\n Console.log(chunk).pipe(Effect.runSync);\n },\n }),\n catch: (error) =>\n new ExecError({\n message: 'Build failed',\n command: buildCmd,\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n yield* Console.log('Build completed successfully.');\n }).pipe(\n Effect.catchTags({\n PackageJsonNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n PackageJsonParseError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n BuildScriptNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n PackageManagerNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ExecError: (err) =>\n Console.error(`${err.message}: ${err.cause ?? err.command}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { FileSystem, Path } from '@effect/platform';\nimport { exec } from '@gigadrive/build-utils';\nimport { Effect } from 'effect';\nimport type { PackageManager } from '../domain';\nimport { ExecError, PackageManagerNotFoundError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// PackageManagerService\n// ---------------------------------------------------------------------------\n\nexport class PackageManagerService extends Effect.Service<PackageManagerService>()('PackageManagerService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const detect = Effect.fn('PackageManagerService.detect')(function* (cwd: string) {\n yield* Effect.annotateCurrentSpan('cwd', cwd);\n\n const packageJsonPath = pathService.join(cwd, 'package.json');\n const exists = yield* fs\n .exists(packageJsonPath)\n .pipe(\n Effect.mapError(\n () => new PackageManagerNotFoundError({ message: 'Failed to check for package.json', directory: cwd })\n )\n );\n if (!exists) {\n return yield* Effect.fail(\n new PackageManagerNotFoundError({\n message: 'No package.json found',\n directory: cwd,\n })\n );\n }\n\n // Check lock files in priority order\n const lockChecks: Array<{ file: string; pm: PackageManager }> = [\n { file: 'yarn.lock', pm: 'yarn' },\n { file: 'pnpm-lock.yaml', pm: 'pnpm' },\n { file: 'bun.lockb', pm: 'bun' },\n { file: 'package-lock.json', pm: 'npm' },\n ];\n\n for (const { file, pm } of lockChecks) {\n const lockExists = yield* fs\n .exists(pathService.join(cwd, file))\n .pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (lockExists) {\n yield* Effect.log('Package manager detected from lock file', { packageManager: pm, lockFile: file });\n return pm;\n }\n }\n\n // Fallback: check if bun is installed\n const bunAvailable = yield* Effect.tryPromise({\n try: () => exec({ command: 'bun --version', cwd }),\n catch: () => new ExecError({ message: 'bun not found', command: 'bun --version' }),\n }).pipe(\n Effect.as(true),\n Effect.catchTag('ExecError', () => Effect.succeed(false))\n );\n\n const pm: PackageManager = bunAvailable ? 'bun' : 'npm';\n yield* Effect.log('Package manager detected via fallback', { packageManager: pm });\n return pm;\n });\n\n const installCommand = (pm: PackageManager): string =>\n ({\n bun: 'bun install',\n npm: 'npm install',\n pnpm: 'pnpm install',\n yarn: 'yarn install',\n })[pm];\n\n const buildCommand = (pm: PackageManager): string =>\n ({\n bun: 'bun run build',\n npm: 'npm run build',\n pnpm: 'pnpm build',\n yarn: 'yarn build',\n })[pm];\n\n return { detect, installCommand, buildCommand };\n }),\n}) {}\n","import { Command } from '@effect/cli';\nimport { Effect } from 'effect';\nimport { debugConfigCommand } from './config';\n\nconst debugBase = Command.make('debug', {}, () => Effect.void);\n\nexport const debugCommand = debugBase.pipe(Command.withSubcommands([debugConfigCommand]));\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { ProjectConfigService } from '../../../services/project-config';\n\nexport const debugConfigCommand = Command.make('config', {}, () =>\n Effect.gen(function* () {\n const projectConfig = yield* ProjectConfigService;\n const cwd = process.cwd();\n const { config, configPath } = yield* projectConfig.resolve(cwd);\n\n yield* Console.log(`Config file found at: ${configPath}`);\n yield* Console.log(JSON.stringify(config, null, 2));\n }).pipe(\n Effect.catchTags({\n ConfigNotFoundError: (err) => Console.error(err.message),\n ConfigParseError: (err) => Console.error(`Config parse error: ${err.message}`),\n ConfigValidationError: (err) =>\n Effect.gen(function* () {\n for (const e of err.errors) {\n yield* Console.error(e);\n }\n yield* Console.error(err.message);\n }),\n })\n )\n);\n","import type {\n ConfigFileEmptyError,\n ConfigFileNotFoundError,\n ConfigFileParseError,\n ConfigModuleLoadError,\n ConfigSchemaValidationError,\n ConfigVersionError,\n ContainerConfigError,\n FunctionConfigError,\n NormalizedConfig,\n} from '@gigadrive/network-config';\nimport {\n detectContainerProject,\n detectFramework,\n mergeWithFrameworkDefaults,\n NetworkConfigLive,\n parseConfig,\n parseConfigRaw,\n postProcessConfig,\n RawConfigReader,\n} from '@gigadrive/network-config';\nimport { Effect } from 'effect';\nimport { ConfigNotFoundError, ConfigParseError, ConfigValidationError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps parseConfig errors into the CLI's ConfigParseError type.\n */\ntype ParseConfigErrors =\n | ConfigFileNotFoundError\n | ConfigFileEmptyError\n | ConfigFileParseError\n | ConfigModuleLoadError\n | ConfigVersionError\n | ConfigSchemaValidationError\n | ContainerConfigError\n | FunctionConfigError;\n\nconst wrapParseErrors = <A, R>(effect: Effect.Effect<A, ParseConfigErrors, R>) =>\n effect.pipe(\n Effect.catchTags({\n ConfigFileNotFoundError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath })),\n ConfigFileEmptyError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath })),\n ConfigFileParseError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.cause })),\n ConfigModuleLoadError: (e) =>\n Effect.fail(new ConfigParseError({ message: e.message, cause: e.cause ?? e.filePath })),\n ConfigVersionError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath })),\n ConfigSchemaValidationError: (e) =>\n Effect.fail(new ConfigParseError({ message: e.message, cause: e.validationErrors.join(', ') })),\n FunctionConfigError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.functionPath })),\n ContainerConfigError: (e) =>\n Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath ?? e.containerName })),\n })\n );\n\n// ---------------------------------------------------------------------------\n// ProjectConfigService\n// ---------------------------------------------------------------------------\n\nexport class ProjectConfigService extends Effect.Service<ProjectConfigService>()('ProjectConfigService', {\n accessors: true,\n dependencies: [NetworkConfigLive],\n\n effect: Effect.gen(function* () {\n const rawReader = yield* RawConfigReader;\n\n const resolve = Effect.fn('ProjectConfigService.resolve')(function* (cwd: string) {\n yield* Effect.annotateCurrentSpan('cwd', cwd);\n yield* Effect.log('Resolving project config', { cwd });\n\n const configPath = yield* rawReader.findConfig(cwd);\n\n // Attempt framework auto-detection.\n // ManifestReadError / ManifestParseError indicate genuine problems (the\n // manifest file exists but is unreadable or malformed), so we surface them\n // as ConfigParseError instead of silently swallowing them.\n const detection = yield* detectFramework(cwd).pipe(\n Effect.catchTag('FrameworkNotDetectedError', () => Effect.succeed(null)),\n Effect.catchTag('ManifestReadError', (e) =>\n Effect.fail(new ConfigParseError({ message: `Framework detection failed: ${e.message}`, cause: e.filePath }))\n ),\n Effect.catchTag('ManifestParseError', (e) =>\n Effect.fail(new ConfigParseError({ message: `Framework detection failed: ${e.message}`, cause: e.filePath }))\n )\n );\n\n if (detection) {\n yield* Effect.log('Framework auto-detected', {\n framework: detection.framework.name,\n slug: detection.framework.slug,\n });\n }\n\n let config: NormalizedConfig;\n let resolvedConfigPath: string | null = null;\n let framework: { name: string; slug: string } | undefined;\n\n if (configPath && detection) {\n // Case A: config file + framework detected → parse raw (no post-processing), merge\n // with framework defaults, then post-process the merged result. Running postProcessConfig\n // after the merge ensures validations (empty-deployment check, Vercel BOv3 merge,\n // function/asset dedup) see the full picture instead of producing stale pre-merge errors.\n yield* Effect.log('Config file found, merging with framework defaults', { configPath });\n resolvedConfigPath = configPath;\n\n const userConfig: NormalizedConfig = yield* wrapParseErrors(parseConfigRaw(configPath, cwd));\n const merged: NormalizedConfig = yield* mergeWithFrameworkDefaults(userConfig, detection.config);\n\n config = yield* wrapParseErrors(postProcessConfig(merged, cwd));\n framework = { name: detection.framework.name, slug: detection.framework.slug };\n } else if (configPath) {\n // Case B: config file only → existing behavior\n yield* Effect.log('Config file found', { configPath });\n resolvedConfigPath = configPath;\n\n config = yield* wrapParseErrors(parseConfig(configPath, cwd));\n } else if (detection) {\n // Case C: no config file, framework detected → use detection + post-process\n config = yield* wrapParseErrors(postProcessConfig(detection.config, cwd));\n\n framework = { name: detection.framework.name, slug: detection.framework.slug };\n } else {\n // Case D: neither config file nor framework → a Compose file or a root\n // Dockerfile deploys as container images. Tried last so a framework\n // project's local-development Compose file never replaces the framework.\n const containerProject = yield* wrapParseErrors(\n detectContainerProject(cwd).pipe(Effect.map((result) => result?.config ?? null))\n );\n if (containerProject === null) {\n return yield* Effect.fail(\n new ConfigNotFoundError({\n message: 'No config file, framework, Compose file or Dockerfile found.',\n directory: cwd,\n })\n );\n }\n\n config = yield* wrapParseErrors(postProcessConfig(containerProject, cwd));\n }\n\n // Report warnings via structured logging\n for (const warning of config.warnings) {\n yield* Effect.logWarning(warning);\n }\n\n // Fail on config errors\n if (config.errors.length > 0) {\n return yield* Effect.fail(\n new ConfigValidationError({\n message: 'Config file has validation errors',\n errors: config.errors,\n })\n );\n }\n\n return { config, configPath: resolvedConfigPath, framework };\n });\n\n return { resolve };\n }),\n}) {}\n","import { Args, Command, Options } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst DEPLOYMENT_STATUSES = ['PENDING', 'QUEUED', 'STARTING', 'BUILDING', 'PROVISIONING', 'ACTIVE', 'FAILED'] as const;\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Filter by application ID (defaults to the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Filter by organization ID'),\n Options.optional\n);\n\nconst statusOption = Options.choice('status', DEPLOYMENT_STATUSES).pipe(\n Options.withAlias('s'),\n Options.withDescription('Filter by deployment status'),\n Options.optional\n);\n\n/**\n * Resolve the application filter: an explicit `--app` wins, otherwise fall back\n * to the linked application. An unlinked directory yields no filter (`load`\n * returns `Option.none`); a broken/unreadable `.gigadrive/project.json` surfaces\n * as `ProjectLinkReadError` rather than being silently treated as unlinked.\n */\nconst resolveApplicationFilter = (app: Option.Option<string>) =>\n Option.match(app, {\n onSome: (id) => Effect.succeed<string | undefined>(id),\n onNone: () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.load(process.cwd());\n return Option.match(link, { onNone: () => undefined, onSome: (l) => l.applicationId });\n }),\n });\n\nconst deploymentsListCommand = Command.make(\n 'list',\n { app: appOption, org: orgOption, status: statusOption },\n ({ app, org, status }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const applicationId = yield* resolveApplicationFilter(app);\n\n const { items, total } = yield* apiClient.request((client) =>\n client.deployments.list({\n applicationId,\n organizationId: Option.getOrUndefined(org),\n status: Option.getOrUndefined(status),\n })\n );\n\n if (items.length === 0) {\n yield* Console.log('No deployments found.');\n return;\n }\n\n for (const d of items) {\n yield* Console.log(`${d.id} ${d.status.padEnd(12)} ${d.createdAt}`);\n }\n yield* Console.log(`\\n${total} deployment(s).`);\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list deployments: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst deploymentIdArg = Args.text({ name: 'deployment-id' }).pipe(Args.withDescription('The deployment ID to inspect'));\n\nconst deploymentsInspectCommand = Command.make('inspect', { deploymentId: deploymentIdArg }, ({ deploymentId }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n\n const deployment = yield* apiClient.request((client) => client.deployments.get(deploymentId));\n yield* Console.log(`ID: ${deployment.id}`);\n yield* Console.log(`Application: ${deployment.applicationId}`);\n yield* Console.log(`Status: ${deployment.status}`);\n yield* Console.log(`Created: ${deployment.createdAt}`);\n yield* Console.log(`Updated: ${deployment.updatedAt}`);\n\n const hostnames = yield* apiClient\n .request((client) => client.deployments.getHostnames(deploymentId))\n .pipe(Effect.catchAll(() => Effect.succeed({ items: [], total: 0 })));\n if (hostnames.items.length > 0) {\n yield* Console.log('Hostnames:');\n for (const h of hostnames.items) {\n yield* Console.log(` https://${h.hostname}${h.active ? '' : ' (inactive)'}`);\n }\n }\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to inspect deployment: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst deploymentsBase = Command.make('deployments', {}, () => Effect.void);\n\n/** `gigadrive deployments` — list and inspect deployments. */\nexport const deploymentsCommand = deploymentsBase.pipe(\n Command.withSubcommands([deploymentsListCommand, deploymentsInspectCommand])\n);\n","import { Args, Command, Options, Prompt } from '@effect/cli';\nimport type { CustomDomain, CustomDomainTargetInput } from '@gigadrive/sdk';\nimport { Clock, Console, Duration, Effect, Either, Option } from 'effect';\nimport {\n ConfirmationRequiredError,\n DomainNotFoundError,\n DomainWaitError,\n InvalidDomainOptionsError,\n OrganizationRequiredError,\n} from '../../errors';\nimport { describeDomain, DOMAIN_STATE_LABELS, formatDnsRecords, IN_PROGRESS_STATES } from '../../lib/domain-output';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst REDIRECT_STATUS_CODES = ['301', '302', '307', '308'] as const;\nconst CONSOLE_URL = 'https://console.gigadrive.de';\nconst POLL_INTERVAL = Duration.seconds(5);\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Operate on this application (overrides the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Operate on this organization (defaults to the linked project’s organization)'),\n Options.optional\n);\n\nconst jsonOption = Options.boolean('json').pipe(\n Options.withDescription('Print only the result as JSON on stdout; progress goes to stderr')\n);\n\nconst waitOption = Options.boolean('wait').pipe(\n Options.withAlias('w'),\n Options.withDescription('Wait until the domain serves traffic, printing each state change')\n);\n\nconst timeoutOption = Options.integer('timeout').pipe(\n Options.withDescription('Minutes to wait with --wait, at least 1 (default: 10)'),\n Options.withDefault(10)\n);\n\nconst branchOption = Options.text('branch').pipe(\n Options.withDescription('Serve the latest deployment of this branch ID instead of production'),\n Options.optional\n);\n\nconst productionOption = Options.boolean('production').pipe(\n Options.withDescription('Serve the production deployment (the default for new domains)')\n);\n\nconst redirectToOption = Options.text('redirect-to').pipe(\n Options.withDescription('Redirect every request to this hostname instead of serving the application'),\n Options.optional\n);\n\nconst statusOption = Options.choice('status', REDIRECT_STATUS_CODES).pipe(\n Options.withDescription('Redirect status code with --redirect-to (default: 308)'),\n Options.optional\n);\n\nconst dropPathOption = Options.boolean('drop-path').pipe(\n Options.withDescription('With --redirect-to, redirect to the root instead of keeping the path and query')\n);\n\nconst primaryOption = Options.boolean('primary').pipe(\n Options.withDescription('Make this domain the application’s primary URL')\n);\n\nconst yesOption = Options.boolean('yes').pipe(\n Options.withAlias('y'),\n Options.withDescription('Skip the confirmation prompt (required when not running in a terminal)')\n);\n\nconst hostnameArg = Args.text({ name: 'hostname' }).pipe(\n Args.withDescription('Hostname to attach, e.g. shop.example.com or example.com')\n);\n\nconst domainArg = Args.text({ name: 'hostname-or-id' }).pipe(Args.withDescription('Domain hostname or ID'));\n\n/** Target flags shared by `add` and `update`. */\nexport interface TargetFlags {\n readonly production: boolean;\n readonly branch: Option.Option<string>;\n readonly redirectTo: Option.Option<string>;\n readonly status: Option.Option<(typeof REDIRECT_STATUS_CODES)[number]>;\n readonly dropPath: boolean;\n}\n\n/**\n * Turns the target flags into the API's target, refusing combinations that contradict each other\n * instead of silently picking one.\n *\n * @returns The target, or `undefined` when no target flag was given.\n */\nexport const targetFromFlags = (flags: TargetFlags) =>\n Effect.gen(function* () {\n const chosen = [flags.production, Option.isSome(flags.branch), Option.isSome(flags.redirectTo)].filter(Boolean);\n if (chosen.length > 1) {\n return yield* new InvalidDomainOptionsError({\n message: 'Choose one target: --production, --branch or --redirect-to.',\n });\n }\n if (Option.isNone(flags.redirectTo) && (Option.isSome(flags.status) || flags.dropPath)) {\n return yield* new InvalidDomainOptionsError({\n message: '--status and --drop-path only apply together with --redirect-to.',\n });\n }\n if (Option.isSome(flags.redirectTo)) {\n const target: CustomDomainTargetInput = {\n type: 'redirect',\n to: flags.redirectTo.value,\n statusCode: Option.match(flags.status, {\n onNone: () => undefined,\n onSome: (code) => (code === '301' ? 301 : code === '302' ? 302 : code === '307' ? 307 : 308),\n }),\n preservePath: !flags.dropPath,\n };\n return target;\n }\n if (Option.isSome(flags.branch)) {\n const target: CustomDomainTargetInput = { type: 'branch', branchId: flags.branch.value };\n return target;\n }\n if (flags.production) {\n const target: CustomDomainTargetInput = { type: 'production' };\n return target;\n }\n return undefined;\n });\n\nconst requirePositiveTimeout = (minutes: number) =>\n minutes >= 1\n ? Effect.succeed(minutes)\n : new InvalidDomainOptionsError({ message: '--timeout must be at least 1 minute.' });\n\n/** Asks before a destructive action. Without a terminal there is nobody to ask, so `--yes` is required. */\nconst confirm = (message: string, yes: boolean) =>\n Effect.gen(function* () {\n if (yes) return true;\n if (process.stdin.isTTY !== true) {\n return yield* new ConfirmationRequiredError({\n message: 'Not running in a terminal, so there is no way to confirm. Pass --yes to proceed.',\n });\n }\n return yield* Prompt.run(Prompt.confirm({ message, initial: false }));\n });\n\nconst resolveApplication = (app: Option.Option<string>) =>\n Option.match(app, {\n onSome: (value) => Effect.succeed(value),\n onNone: () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.resolve(process.cwd());\n return link.applicationId;\n }),\n });\n\nconst resolveOrganization = (org: Option.Option<string>) =>\n Option.match(org, {\n onSome: (value) => Effect.succeed(value),\n onNone: () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.load(process.cwd());\n const organizationId = Option.flatMap(link, (value) => Option.fromNullable(value.organizationId));\n if (Option.isNone(organizationId)) {\n return yield* new OrganizationRequiredError({\n message: 'Pass --org, or run the command in a linked project.',\n });\n }\n return organizationId.value;\n }),\n });\n\nconst normalizeHostname = (value: string) => value.trim().toLowerCase().replace(/\\.$/, '');\n\n/** Finds a domain of the application by hostname (any case, trailing dot allowed) or ID. */\nexport const findDomain = (applicationId: string, hostnameOrId: string) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const { items } = yield* apiClient.request((client) => client.applications.domains.list(applicationId));\n const wanted = normalizeHostname(hostnameOrId);\n const domain = items.find(\n (item) => item.id === hostnameOrId || item.hostname === wanted || item.unicodeHostname === wanted\n );\n if (!domain) {\n return yield* new DomainNotFoundError({ message: `No custom domain ${hostnameOrId} on this application.` });\n }\n return domain;\n });\n\nconst printDomain = (domain: CustomDomain) =>\n Effect.gen(function* () {\n for (const line of describeDomain(domain)) yield* Console.log(line);\n const pending = domain.requiredRecords.filter((record) => record.status !== 'ok');\n const records = formatDnsRecords(pending);\n if (records.length > 0 && domain.state !== 'removing') {\n yield* Console.log('\\nAdd these records at your DNS provider:');\n for (const line of records) yield* Console.log(` ${line}`);\n if (pending.some((record) => record.type === 'ALIAS')) {\n yield* Console.log(\n '\\nApex domains need an ALIAS, ANAME or flattened CNAME record. Without one, attach www instead and redirect the apex to it.'\n );\n }\n }\n });\n\n/** Rate limits, server errors and network failures are worth another poll. */\nconst isTransient = (error: { readonly _tag: string; readonly statusCode?: number }) =>\n error._tag === 'ApiRequestError' &&\n (error.statusCode === undefined || error.statusCode === 429 || error.statusCode >= 500);\n\n/**\n * Polls until the domain serves traffic, reporting each state change.\n *\n * In JSON mode the progress goes to stderr and the last known domain is printed to stdout even when\n * the wait fails, so stdout always holds exactly one JSON document.\n */\nexport const waitUntilServing = (applicationId: string, initial: CustomDomain, timeoutMinutes: number, json: boolean) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const progress = (line: string) => (json ? Console.error(line) : Console.log(line));\n const fail = (domain: CustomDomain, message: string) =>\n Effect.gen(function* () {\n if (json) yield* Console.log(JSON.stringify(domain, null, 2));\n return yield* new DomainWaitError({ message, state: domain.state });\n });\n\n const deadline = (yield* Clock.currentTimeMillis) + Duration.toMillis(Duration.minutes(timeoutMinutes));\n let domain = initial;\n yield* progress(`Waiting for ${domain.unicodeHostname} (${DOMAIN_STATE_LABELS[domain.state]})...`);\n\n while (IN_PROGRESS_STATES.has(domain.state)) {\n const remaining = deadline - (yield* Clock.currentTimeMillis);\n if (remaining <= 0) {\n return yield* fail(\n domain,\n `${domain.unicodeHostname} is not serving yet (${DOMAIN_STATE_LABELS[domain.state]}). Check again later with \"gigadrive domains inspect ${domain.hostname}\".`\n );\n }\n yield* Effect.sleep(Duration.min(POLL_INTERVAL, Duration.millis(remaining)));\n const polled = yield* Effect.either(\n apiClient.request((client) => client.applications.domains.get(applicationId, domain.id))\n );\n if (Either.isLeft(polled)) {\n // A blip (rate limit, 5xx, network) should not end a ten-minute wait; the loop retries until the deadline.\n if (isTransient(polled.left)) continue;\n return yield* polled.left;\n }\n if (polled.right.state !== domain.state) {\n yield* progress(` ${DOMAIN_STATE_LABELS[polled.right.state]}`);\n }\n domain = polled.right;\n }\n\n if (domain.state !== 'active' && domain.state !== 'degraded') {\n return yield* fail(\n domain,\n `${domain.unicodeHostname} is ${DOMAIN_STATE_LABELS[domain.state]}${domain.error ? `: ${domain.error.message}` : ''}`\n );\n }\n yield* progress(`\\n${domain.unicodeHostname} is live: https://${domain.hostname}`);\n if (json) yield* Console.log(JSON.stringify(domain, null, 2));\n return domain;\n });\n\n/** What to tell the user for a failed command, keeping the typed error as the exit status. */\nexport const errorMessage = (\n action: string,\n error: { readonly _tag: string; readonly message: string; readonly code?: string; readonly reason?: string }\n) => {\n switch (error._tag) {\n case 'NotAuthenticatedError':\n return 'You are not logged in. Run \"gigadrive login\" to authenticate.';\n case 'ApiRequestError':\n if (error.code === 'quota_exceeded' && error.reason === 'daily_add_limit') {\n return `${error.message}\\nThe daily limit resets within 24 hours; upgrading your plan raises it.`;\n }\n if (error.code === 'quota_exceeded') {\n return `${error.message}\\nSee your plan's limits and upgrade at ${CONSOLE_URL} (organization settings > Limits).`;\n }\n if (error.code === 'invalid_target' && error.reason === 'redirects_not_available') {\n return `${error.message}\\nRedirect domains are available on paid plans. Upgrade at ${CONSOLE_URL}.`;\n }\n if (error.code === 'domain_in_use' && error.reason === 'other_organization') {\n return `${error.message}\\nIf you control the domain, verify it with \"gigadrive domains owners add <domain>\", then move it with \"gigadrive domains claim <hostname>\".`;\n }\n if (error.reason === 'ownership_not_live') {\n return `${error.message}\\nPublish the TXT record shown by \"gigadrive domains owners list\" again, wait for DNS to update, then retry the claim.`;\n }\n return `Failed to ${action}: ${error.message}`;\n default:\n return error.message;\n }\n};\n\n/** Prints what went wrong while keeping the typed error, so the command still exits non-zero. */\nconst reportErrors =\n (action: string) =>\n <A, E extends { readonly _tag: string; readonly message: string }, R>(self: Effect.Effect<A, E, R>) =>\n Effect.tapError(self, (error) => Console.error(errorMessage(action, error)));\n\nconst listCommand = Command.make('list', { app: appOption, json: jsonOption }, ({ app, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const applicationId = yield* resolveApplication(app);\n const { items } = yield* apiClient.request((client) => client.applications.domains.list(applicationId));\n if (json) return yield* Console.log(JSON.stringify(items, null, 2));\n if (items.length === 0) {\n return yield* Console.log('No custom domains. Add one with \"gigadrive domains add <hostname>\".');\n }\n const width = Math.max(...items.map((item) => item.unicodeHostname.length));\n for (const item of items) {\n const problem = item.error ? ` ${item.error.code}` : '';\n yield* Console.log(\n `${item.unicodeHostname.padEnd(width)} ${DOMAIN_STATE_LABELS[item.state]}${item.primary ? ' (primary)' : ''}${problem}`\n );\n }\n }).pipe(reportErrors('list custom domains'))\n);\n\n/** Input of {@link addDomain}. */\nexport interface AddDomainInput extends TargetFlags {\n readonly hostname: string;\n readonly applicationId: string;\n readonly wait: boolean;\n readonly timeout: number;\n readonly json: boolean;\n}\n\n/** Attaches a hostname and optionally waits until it serves. */\nexport const addDomain = (input: AddDomainInput) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const target = yield* targetFromFlags(input);\n const timeout = yield* requirePositiveTimeout(input.timeout);\n const domain = yield* apiClient.request((client) =>\n client.applications.domains.add(input.applicationId, { hostname: input.hostname, target })\n );\n if (input.wait) return yield* waitUntilServing(input.applicationId, domain, timeout, input.json);\n if (input.json) {\n yield* Console.log(JSON.stringify(domain, null, 2));\n return domain;\n }\n yield* printDomain(domain);\n if (IN_PROGRESS_STATES.has(domain.state)) {\n yield* Console.log(\n `\\nGigadrive checks the records automatically. Follow progress with \"gigadrive domains inspect ${domain.hostname}\".`\n );\n }\n return domain;\n });\n\nconst addCommand = Command.make(\n 'add',\n {\n hostname: hostnameArg,\n app: appOption,\n production: productionOption,\n branch: branchOption,\n redirectTo: redirectToOption,\n status: statusOption,\n dropPath: dropPathOption,\n wait: waitOption,\n timeout: timeoutOption,\n json: jsonOption,\n },\n ({ app, ...options }) =>\n Effect.gen(function* () {\n const applicationId = yield* resolveApplication(app);\n yield* addDomain({ ...options, applicationId });\n }).pipe(reportErrors('add the domain'))\n);\n\nconst updateCommand = Command.make(\n 'update',\n {\n domain: domainArg,\n app: appOption,\n production: productionOption,\n branch: branchOption,\n redirectTo: redirectToOption,\n status: statusOption,\n dropPath: dropPathOption,\n primary: primaryOption,\n json: jsonOption,\n },\n ({ domain: hostnameOrId, app, primary, json, ...flags }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const target = yield* targetFromFlags(flags);\n if (target === undefined && !primary) {\n return yield* new InvalidDomainOptionsError({\n message: 'Nothing to change. Pass --production, --branch, --redirect-to or --primary.',\n });\n }\n const applicationId = yield* resolveApplication(app);\n const found = yield* findDomain(applicationId, hostnameOrId);\n const domain = yield* apiClient.request((client) =>\n client.applications.domains.update(applicationId, found.id, {\n ...(target === undefined ? {} : { target }),\n ...(primary ? { primary: true } : {}),\n })\n );\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* printDomain(domain);\n }).pipe(reportErrors('update the domain'))\n);\n\nconst claimCommand = Command.make(\n 'claim',\n {\n hostname: hostnameArg.pipe(Args.withDescription('Hostname another organization attached')),\n app: appOption,\n json: jsonOption,\n },\n ({ hostname, app, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const applicationId = yield* resolveApplication(app);\n const domain = yield* apiClient.request((client) => client.applications.domains.claim(applicationId, hostname));\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* Console.log(`Moved ${domain.unicodeHostname} to this application.`);\n yield* printDomain(domain);\n }).pipe(reportErrors('claim the domain'))\n);\n\nconst inspectCommand = Command.make(\n 'inspect',\n { domain: domainArg, app: appOption, json: jsonOption },\n ({ domain: hostnameOrId, app, json }) =>\n Effect.gen(function* () {\n const applicationId = yield* resolveApplication(app);\n const domain = yield* findDomain(applicationId, hostnameOrId);\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* printDomain(domain);\n if (domain.nextCheckAt !== null) yield* Console.log(`\\nNext automatic check: ${domain.nextCheckAt}`);\n }).pipe(reportErrors('inspect the domain'))\n);\n\nconst checkCommand = Command.make(\n 'check',\n { domain: domainArg, app: appOption, wait: waitOption, timeout: timeoutOption, json: jsonOption },\n ({ domain: hostnameOrId, app, wait, timeout, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const minutes = yield* requirePositiveTimeout(timeout);\n const applicationId = yield* resolveApplication(app);\n const found = yield* findDomain(applicationId, hostnameOrId);\n const domain = yield* apiClient.request((client) => client.applications.domains.refresh(applicationId, found.id));\n if (wait) return yield* waitUntilServing(applicationId, domain, minutes, json);\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* Console.log(`Checking ${domain.unicodeHostname}.`);\n yield* printDomain(domain);\n }).pipe(reportErrors('check the domain'))\n);\n\n/** Removes a domain after confirmation. */\nexport const removeDomain = (applicationId: string, hostnameOrId: string, yes: boolean) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const domain = yield* findDomain(applicationId, hostnameOrId);\n const confirmed = yield* confirm(\n `Remove ${domain.unicodeHostname}? It stops serving this application immediately.`,\n yes\n );\n if (!confirmed) return yield* Console.log('Cancelled.');\n yield* apiClient.request((client) => client.applications.domains.remove(applicationId, domain.id));\n yield* Console.log(`Removed ${domain.unicodeHostname}.`);\n });\n\nconst removeCommand = Command.make(\n 'rm',\n { domain: domainArg, app: appOption, yes: yesOption },\n ({ domain: hostnameOrId, app, yes }) =>\n Effect.gen(function* () {\n const applicationId = yield* resolveApplication(app);\n yield* removeDomain(applicationId, hostnameOrId, yes);\n }).pipe(\n // Ctrl+C at the confirmation is a deliberate cancel, not a failure.\n Effect.catchTag('QuitException', () => Console.log('Cancelled.')),\n reportErrors('remove the domain')\n )\n);\n\nconst findOwnership = (organizationId: string, name: string) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const { items } = yield* apiClient.request((client) => client.organizations.domains.list(organizationId));\n const wanted = normalizeHostname(name);\n const claim = items.find((item) => item.id === name || item.name === wanted || item.unicodeName === wanted);\n if (!claim) {\n return yield* new DomainNotFoundError({\n message: `${name} is not claimed. Add it with \"gigadrive domains owners add\".`,\n });\n }\n return claim;\n });\n\nconst ownersListCommand = Command.make('list', { org: orgOption, json: jsonOption }, ({ org, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const { items } = yield* apiClient.request((client) => client.organizations.domains.list(organizationId));\n if (json) return yield* Console.log(JSON.stringify(items, null, 2));\n if (items.length === 0) return yield* Console.log('No verified domains.');\n const width = Math.max(...items.map((item) => item.unicodeName.length));\n for (const item of items) {\n yield* Console.log(`${item.unicodeName.padEnd(width)} ${item.status}`);\n }\n }).pipe(reportErrors('list verified domains'))\n);\n\nconst ownersAddCommand = Command.make(\n 'add',\n {\n name: Args.text({ name: 'domain' }).pipe(Args.withDescription('Domain to verify, e.g. example.com')),\n org: orgOption,\n json: jsonOption,\n },\n ({ name, org, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const claim = yield* apiClient.request((client) => client.organizations.domains.add(organizationId, name));\n if (json) return yield* Console.log(JSON.stringify(claim, null, 2));\n if (claim.status === 'verified') {\n return yield* Console.log(`${claim.unicodeName} is verified.`);\n }\n yield* Console.log(`Publish this TXT record for ${claim.unicodeName}:`);\n yield* Console.log(` Name: ${claim.record.host}`);\n yield* Console.log(` Value: ${claim.record.value}`);\n yield* Console.log(`\\nThen run \"gigadrive domains owners verify ${claim.name}\".`);\n }).pipe(reportErrors('add the domain'))\n);\n\nconst ownersVerifyCommand = Command.make(\n 'verify',\n { name: Args.text({ name: 'domain' }).pipe(Args.withDescription('Domain to verify')), org: orgOption },\n ({ name, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const claim = yield* findOwnership(organizationId, name);\n const checked = yield* apiClient.request((client) =>\n client.organizations.domains.verify(organizationId, claim.id)\n );\n if (checked.status === 'verified') {\n return yield* Console.log(`${checked.unicodeName} is verified.`);\n }\n yield* Console.log(\n `${checked.unicodeName} is not verified yet${checked.error ? `: ${checked.error.message}` : '.'} Gigadrive keeps checking automatically.`\n );\n }).pipe(reportErrors('verify the domain'))\n);\n\nconst ownersRemoveCommand = Command.make(\n 'rm',\n {\n name: Args.text({ name: 'domain' }).pipe(Args.withDescription('Domain to remove')),\n org: orgOption,\n yes: yesOption,\n },\n ({ name, org, yes }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const claim = yield* findOwnership(organizationId, name);\n const confirmed = yield* confirm(\n `Remove ${claim.unicodeName} from your organization's domains? Custom domains that rely on it must be removed first.`,\n yes\n );\n if (!confirmed) return yield* Console.log('Cancelled.');\n yield* apiClient.request((client) => client.organizations.domains.remove(organizationId, claim.id));\n yield* Console.log(`Removed ${claim.unicodeName}.`);\n }).pipe(\n Effect.catchTag('QuitException', () => Console.log('Cancelled.')),\n reportErrors('remove the domain')\n )\n);\n\nconst ownersCommand = Command.make('owners', {}, () => Effect.void).pipe(\n Command.withDescription('Domains your organization verified with a TXT record'),\n Command.withSubcommands([ownersListCommand, ownersAddCommand, ownersVerifyCommand, ownersRemoveCommand])\n);\n\nconst domainsBase = Command.make('domains', {}, () => Effect.void).pipe(\n Command.withDescription('Custom domains of the linked application')\n);\n\n/** `gigadrive domains` — attach, change, inspect and remove custom domains, and verify domain ownership. */\nexport const domainsCommand = domainsBase.pipe(\n Command.withSubcommands([\n listCommand,\n addCommand,\n updateCommand,\n claimCommand,\n inspectCommand,\n checkCommand,\n removeCommand,\n ownersCommand,\n ])\n);\n","import type { CustomDomain, CustomDomainState, RequiredDnsRecord } from '@gigadrive/sdk';\n\n/** Human-readable label per lifecycle state, matching the console. */\nexport const DOMAIN_STATE_LABELS: Record<CustomDomainState, string> = {\n pending_ownership: 'verifying ownership',\n pending_dns: 'waiting for DNS',\n issuing_certificate: 'issuing certificate',\n active: 'active',\n degraded: 'needs attention',\n failed: 'failed',\n suspended: 'suspended',\n removing: 'removing',\n};\n\nconst RECORD_STATUS_LABELS: Record<RequiredDnsRecord['status'], string> = {\n ok: 'found',\n pending: 'waiting',\n mismatch: 'different value',\n};\n\n/** States the lifecycle leaves on its own; waiting makes sense only while in one of these. */\nexport const IN_PROGRESS_STATES: ReadonlySet<CustomDomainState> = new Set([\n 'pending_ownership',\n 'pending_dns',\n 'issuing_certificate',\n]);\n\n/**\n * Formats the DNS records a domain still needs as an aligned table, one line per record.\n *\n * @param records - The domain's required records.\n * @returns The table lines, header first. Empty when there are no records.\n *\n * @example\n * ```ts\n * formatDnsRecords(domain.requiredRecords).forEach((line) => console.log(line));\n * ```\n */\nexport const formatDnsRecords = (records: readonly RequiredDnsRecord[]): string[] => {\n if (records.length === 0) return [];\n const rows = [\n ['Type', 'Name', 'Value', 'Status'],\n ...records.map((record) => [record.type, record.host, record.value, RECORD_STATUS_LABELS[record.status]]),\n ];\n const widths = [0, 1, 2].map((column) => Math.max(...rows.map((row) => row[column].length)));\n return rows.map((row) =>\n row\n .map((cell, column) => (column < widths.length ? cell.padEnd(widths[column]) : cell))\n .join(' ')\n .trimEnd()\n );\n};\n\n/**\n * Summarizes a domain in a few lines: hostname, state, target, problem and certificate.\n *\n * @param domain - The domain to describe.\n * @returns The lines to print.\n */\nexport const describeDomain = (domain: CustomDomain): string[] => {\n const lines = [\n `${domain.unicodeHostname} ${DOMAIN_STATE_LABELS[domain.state]}${domain.primary ? ' (primary)' : ''}`,\n ];\n if (domain.target.type === 'redirect' && domain.target.redirectTo !== null) {\n lines.push(`Redirects to ${domain.target.redirectTo} (${domain.target.redirectStatusCode ?? 308})`);\n } else if (domain.target.type === 'branch') {\n lines.push(`Serves branch ${domain.target.branchId ?? 'unknown'}`);\n }\n if (domain.error !== null) lines.push(`Problem (${domain.error.code}): ${domain.error.message}`);\n if (domain.certificate.expiresAt !== null) lines.push(`Certificate expires ${domain.certificate.expiresAt}`);\n return lines;\n};\n","import { Args, Command, Options, Prompt } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { EnvVarNotFoundError, InvalidEnvVarFormatError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { EnvFileService } from '../../services/env-file';\nimport { LocalCredentialsService } from '../../services/local-credentials';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Operate on this application (overrides the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Operate on this organization instead of an application'),\n Options.optional\n);\n\nconst sensitiveOption = Options.boolean('sensitive').pipe(\n Options.withDescription('Store the value as sensitive (hidden in API responses)')\n);\n\nconst envIdOption = Options.text('env').pipe(\n Options.withAlias('e'),\n Options.withDescription('Environment ID for an environment-scoped variable (application scope only)'),\n Options.optional\n);\n\nconst keyValueArg = Args.text({ name: 'key=value' }).pipe(\n Args.withDescription('Variable assignment, e.g. DATABASE_URL=postgres://user:pass@host/db')\n);\n\nconst keyOrIdArg = Args.text({ name: 'key-or-id' }).pipe(Args.withDescription('Variable key or ID to remove'));\n\nconst fileArg = Args.text({ name: 'file' }).pipe(\n Args.withDescription('Output file to write (default: .env.local)'),\n Args.optional\n);\n\nconst environmentOption = Options.text('environment').pipe(\n Options.withAlias('e'),\n Options.withDescription('Environment slug to resolve overrides for (e.g. preview). Omit for the local baseline'),\n Options.optional\n);\n\nconst yesOption = Options.boolean('yes').pipe(\n Options.withAlias('y'),\n Options.withDescription('Overwrite an existing file without confirmation')\n);\n\nconst withCredentialsOption = Options.boolean('with-credentials').pipe(\n Options.withDescription('Also provision API-key credentials so the local app can call the API as this application')\n);\n\nconst rotateOption = Options.boolean('rotate').pipe(\n Options.withDescription('Force a fresh API key when provisioning credentials, revoking the previous one')\n);\n\n/**\n * Resolve which resource the command operates on: an explicit `--org` selects\n * organization scope; otherwise application scope using `--app` or the linked\n * application. Fails with `ProjectNotLinkedError` when neither is available.\n */\nconst resolveScope = (app: Option.Option<string>, org: Option.Option<string>) =>\n Effect.gen(function* () {\n if (Option.isSome(org)) {\n return { kind: 'organization' as const, id: org.value };\n }\n const projectLink = yield* ProjectLinkService;\n const id = yield* Option.match(app, {\n onSome: (value) => Effect.succeed(value),\n onNone: () => projectLink.resolve(process.cwd()).pipe(Effect.map((link) => link.applicationId)),\n });\n return { kind: 'application' as const, id };\n });\n\nconst envListCommand = Command.make('list', { app: appOption, org: orgOption }, ({ app, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const scope = yield* resolveScope(app, org);\n\n const { items } = yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.list(scope.id)\n : client.applications.envVars.list(scope.id)\n );\n\n if (items.length === 0) {\n yield* Console.log('No environment variables set.');\n return;\n }\n for (const v of items) {\n yield* Console.log(`${v.key}=${v.sensitive ? '***' : (v.value ?? '')}`);\n }\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list environment variables: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envSetCommand = Command.make(\n 'set',\n { keyValue: keyValueArg, app: appOption, org: orgOption, sensitive: sensitiveOption, env: envIdOption },\n ({ keyValue, app, org, sensitive, env }) =>\n Effect.gen(function* () {\n const separator = keyValue.indexOf('=');\n if (separator <= 0) {\n return yield* Effect.fail(\n new InvalidEnvVarFormatError({\n message: 'Invalid format. Use KEY=VALUE, e.g. \"gigadrive env set DATABASE_URL=postgres://...\".',\n })\n );\n }\n const key = keyValue.slice(0, separator);\n const value = keyValue.slice(separator + 1);\n\n const apiClient = yield* ApiClientService;\n const scope = yield* resolveScope(app, org);\n const environmentId = Option.getOrUndefined(env);\n\n const created = yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.create(scope.id, { key, value, sensitive })\n : client.applications.envVars.create(scope.id, { key, value, sensitive, environmentId })\n );\n yield* Console.log(`Set ${created.key}.`);\n }).pipe(\n Effect.catchTags({\n InvalidEnvVarFormatError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to set environment variable: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envRmCommand = Command.make(\n 'rm',\n { keyOrId: keyOrIdArg, app: appOption, org: orgOption },\n ({ keyOrId, app, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const scope = yield* resolveScope(app, org);\n\n const { items } = yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.list(scope.id)\n : client.applications.envVars.list(scope.id)\n );\n\n const target = items.find((v) => v.id === keyOrId || v.key === keyOrId);\n if (target === undefined) {\n return yield* Effect.fail(\n new EnvVarNotFoundError({ message: `No environment variable matching \"${keyOrId}\".` })\n );\n }\n\n yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.delete(scope.id, target.id)\n : client.applications.envVars.delete(scope.id, target.id)\n );\n yield* Console.log(`Removed ${target.key}.`);\n }).pipe(\n Effect.catchTags({\n EnvVarNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to remove environment variable: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envPullCommand = Command.make(\n 'pull',\n {\n file: fileArg,\n app: appOption,\n environment: environmentOption,\n yes: yesOption,\n withCredentials: withCredentialsOption,\n rotate: rotateOption,\n },\n ({ file, app, environment, yes, withCredentials, rotate }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const projectLink = yield* ProjectLinkService;\n const envFile = yield* EnvFileService;\n\n // `env pull` always targets an application (via --app or the linked project).\n const applicationId = yield* Option.match(app, {\n onSome: (value) => Effect.succeed(value),\n onNone: () => projectLink.resolve(process.cwd()).pipe(Effect.map((link) => link.applicationId)),\n });\n const target = Option.getOrElse(file, () => '.env.local');\n const environmentSlug = Option.getOrUndefined(environment);\n\n const { items, omittedSensitive } = yield* apiClient.request((client) =>\n client.applications.envVars.pull(applicationId, environmentSlug ? { environment: environmentSlug } : undefined)\n );\n\n const existing = yield* envFile.read(target);\n if (Option.isSome(existing) && !yes) {\n const overwrite = yield* Prompt.run(\n Prompt.confirm({ message: `${target} already exists. Overwrite?`, initial: false })\n );\n if (!overwrite) {\n return yield* Console.log('Cancelled.');\n }\n }\n\n let credentialEntries: { key: string; value: string }[] = [];\n if (withCredentials) {\n const localCredentials = yield* LocalCredentialsService;\n credentialEntries = yield* localCredentials.provision({\n applicationId,\n rotate,\n existingContent: Option.getOrUndefined(existing),\n });\n }\n\n const entries = [...items.map((v) => ({ key: v.key, value: v.value })), ...credentialEntries];\n yield* envFile.write(target, entries);\n const gitignored = yield* envFile.ensureGitignored(process.cwd(), target);\n\n yield* Console.log(\n `Pulled ${items.length} environment variable(s)${withCredentials ? ' and API credentials' : ''} to ${target}.`\n );\n if (omittedSensitive > 0) {\n yield* Console.log(\n `Skipped ${omittedSensitive} sensitive variable(s); secrets live only in production/preview environments.`\n );\n }\n if (gitignored) {\n yield* Console.log(`Added ${target} to .gitignore.`);\n }\n }).pipe(\n Effect.catchTags({\n // Ctrl+C during the overwrite prompt is a deliberate cancel — exit 0.\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to pull environment variables: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envBase = Command.make('env', {}, () => Effect.void);\n\n/** `gigadrive env` — manage environment variables for the linked app or an organization. */\nexport const envCommand = envBase.pipe(\n Command.withSubcommands([envListCommand, envSetCommand, envRmCommand, envPullCommand])\n);\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option } from 'effect';\nimport { EnvFileReadError, EnvFileWriteError } from '../errors';\nimport { serializeEnv, type EnvEntry } from '../lib/dotenv';\n\n// ---------------------------------------------------------------------------\n// EnvFileService\n//\n// Reads and writes local `.env` files (and maintains `.gitignore`). Files may\n// contain secrets (e.g. provisioned API credentials), so they are written with\n// mode 0o600, mirroring AuthStorageService.\n// ---------------------------------------------------------------------------\n\nexport class EnvFileService extends Effect.Service<EnvFileService>()('EnvFileService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n /** Whether a file exists at `filePath`. */\n const exists = Effect.fn('EnvFileService.exists')(function* (filePath: string) {\n return yield* fs\n .exists(filePath)\n .pipe(Effect.mapError(() => new EnvFileReadError({ message: `Failed to check whether ${filePath} exists` })));\n });\n\n /** Read a file's contents, returning `Option.none` when it does not exist. */\n const read = Effect.fn('EnvFileService.read')(function* (filePath: string) {\n const present = yield* exists(filePath);\n if (!present) return Option.none<string>();\n const contents = yield* fs\n .readFileString(filePath, 'utf8')\n .pipe(Effect.mapError(() => new EnvFileReadError({ message: `Failed to read ${filePath}` })));\n return Option.some(contents);\n });\n\n /** Serialize `entries` and write them to `filePath` with mode 0o600. */\n const write = Effect.fn('EnvFileService.write')(function* (\n filePath: string,\n entries: ReadonlyArray<EnvEntry>,\n opts?: { header?: string }\n ) {\n const dir = pathService.dirname(filePath);\n yield* fs\n .makeDirectory(dir, { recursive: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new EnvFileWriteError({ message: `Failed to create directory for ${filePath}`, cause: String(error) })\n )\n );\n yield* fs\n .writeFileString(filePath, serializeEnv(entries, opts), { mode: 0o600 })\n .pipe(\n Effect.mapError(\n (error) => new EnvFileWriteError({ message: `Failed to write ${filePath}`, cause: String(error) })\n )\n );\n // `mode` on writeFileString only applies when the file is created. Explicitly\n // tighten permissions so an overwritten file (which may hold a provisioned\n // API secret) is never left world/group-readable.\n yield* fs\n .chmod(filePath, 0o600)\n .pipe(\n Effect.mapError(\n (error) => new EnvFileWriteError({ message: `Failed to secure ${filePath}`, cause: String(error) })\n )\n );\n });\n\n /**\n * Ensure `entry` is present in `<dir>/.gitignore`, creating the file when\n * needed. Returns `true` when the entry was added, `false` when it was\n * already ignored.\n */\n const ensureGitignored = Effect.fn('EnvFileService.ensureGitignored')(function* (dir: string, entry: string) {\n const gitignorePath = pathService.join(dir, '.gitignore');\n const existing = yield* read(gitignorePath);\n const current = Option.getOrElse(existing, () => '');\n const alreadyIgnored = current.split('\\n').some((line) => line.trim() === entry);\n if (alreadyIgnored) {\n return false;\n }\n const separator = current.length > 0 && !current.endsWith('\\n') ? '\\n' : '';\n yield* fs\n .writeFileString(gitignorePath, `${current}${separator}${entry}\\n`)\n .pipe(\n Effect.mapError(\n (error) => new EnvFileWriteError({ message: 'Failed to update .gitignore', cause: String(error) })\n )\n );\n return true;\n });\n\n return { exists, read, write, ensureGitignored };\n }),\n}) {}\n","// ---------------------------------------------------------------------------\n// dotenv serialization helpers\n//\n// Pure functions (no I/O) for turning key/value pairs into `.env` file contents\n// and reading a few values back. Kept dependency-free so they are trivially unit\n// testable and can be reused by both `env pull` and `setup`.\n// ---------------------------------------------------------------------------\n\n/** A single environment entry to serialize. */\nexport interface EnvEntry {\n key: string;\n value: string;\n}\n\n/** Default header written at the top of a generated `.env` file. */\nexport const DEFAULT_ENV_HEADER = '# Generated by `gigadrive env pull` — do not edit by hand.';\n\n// Values matching this are safe to emit unquoted; anything else is double-quoted.\nconst UNQUOTED_SAFE = /^[A-Za-z0-9_.\\-/@:+]*$/;\n\n/**\n * Format a single value for a `.env` file. Identifier-like values (and the empty\n * string) are emitted verbatim; anything containing whitespace, quotes, `#`,\n * `=`, or control characters is double-quoted with escapes that standard dotenv\n * parsers reverse — so values round-trip.\n */\nexport const formatEnvValue = (value: string): string => {\n if (UNQUOTED_SAFE.test(value)) {\n return value;\n }\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t');\n return `\"${escaped}\"`;\n};\n\n/**\n * Serialize env entries into `.env` file contents with a leading header comment.\n * Entry order is preserved.\n */\nexport const serializeEnv = (entries: ReadonlyArray<EnvEntry>, opts?: { header?: string }): string => {\n const header = opts?.header ?? DEFAULT_ENV_HEADER;\n if (entries.length === 0) {\n return `${header}\\n`;\n }\n const body = entries.map((e) => `${e.key}=${formatEnvValue(e.value)}`).join('\\n');\n return `${header}\\n${body}\\n`;\n};\n\n/**\n * Parse `.env` file contents into a key→value map. Handles unquoted values and\n * double-quoted values with standard escapes; comment (`#`) and blank lines are\n * ignored. Intended for recovering a few known keys (e.g. `GIGADRIVE_CLIENT_ID`),\n * not as a full-fidelity dotenv parser.\n */\nexport const parseEnv = (content: string): Record<string, string> => {\n const result: Record<string, string> = {};\n for (const rawLine of content.split('\\n')) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) {\n continue;\n }\n const eq = line.indexOf('=');\n if (eq <= 0) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n let value = line.slice(eq + 1).trim();\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n // Single-pass decode: consume each backslash together with the character it\n // escapes, left to right. A sequential chain of `.replace()` calls would\n // mis-handle a literal backslash followed by n/r/t/\" (e.g. `C:\\\\new` after\n // escaping would decode `\\n` before collapsing `\\\\`).\n value = value.slice(1, -1).replace(/\\\\(\\\\|\"|n|r|t)/g, (_, ch: string) => {\n switch (ch) {\n case 'n':\n return '\\n';\n case 'r':\n return '\\r';\n case 't':\n return '\\t';\n case '\"':\n return '\"';\n default:\n return '\\\\';\n }\n });\n }\n result[key] = value;\n }\n return result;\n};\n","import { Config, Effect, Option } from 'effect';\nimport * as os from 'node:os';\nimport { parseEnv, type EnvEntry } from '../lib/dotenv';\nimport { ApiClientService } from './api-client';\nimport { DevCredentialsStore } from './dev-credentials-store';\n\n// ---------------------------------------------------------------------------\n// LocalCredentialsService\n//\n// Provisions least-privilege, application-scoped API credentials for local\n// development and returns them as `.env` entries (GIGADRIVE_CLIENT_ID /\n// GIGADRIVE_CLIENT_SECRET / GIGADRIVE_API_BASE_URL). The local app uses these\n// with the SDK's client-credentials provider to call the API as the application.\n//\n// Because a key secret is only returned once at creation, we cannot re-read it.\n// To avoid key sprawl we store the provisioned key's ID (in DevCredentialsStore)\n// and, on subsequent runs, either reuse the credentials already present in the\n// target file or rotate (revoke the old key, mint a new one).\n// ---------------------------------------------------------------------------\n\n/** Least-privilege default scopes for a local-dev key. */\nconst DEV_KEY_SCOPES = ['network:env_vars:read'];\n\nconst ApiBaseUrl = Config.string('GIGADRIVE_API_BASE_URL').pipe(Config.withDefault('https://api.gigadrive.network'));\n\nconst credentialEntries = (clientId: string, clientSecret: string, baseUrl: string): EnvEntry[] => [\n { key: 'GIGADRIVE_CLIENT_ID', value: clientId },\n { key: 'GIGADRIVE_CLIENT_SECRET', value: clientSecret },\n { key: 'GIGADRIVE_API_BASE_URL', value: baseUrl },\n];\n\nexport interface ProvisionInput {\n applicationId: string;\n /** Force a fresh key even when reusable credentials already exist. */\n rotate: boolean;\n /** Current contents of the target `.env` file, if any (used to reuse credentials). */\n existingContent?: string;\n}\n\nexport class LocalCredentialsService extends Effect.Service<LocalCredentialsService>()('LocalCredentialsService', {\n accessors: true,\n dependencies: [ApiClientService.Default, DevCredentialsStore.Default],\n\n effect: Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const store = yield* DevCredentialsStore;\n const baseUrl = yield* ApiBaseUrl;\n\n const keyName = (applicationId: string) => `cli-dev:${os.hostname()}:${applicationId}`;\n\n /**\n * Provision (or reuse) application-scoped credentials and return them as\n * `.env` entries. Reuses the credentials already in `existingContent` when\n * they match the stored key and `rotate` is not set; otherwise revokes any\n * previously provisioned key and mints a fresh one.\n */\n const provision = Effect.fn('LocalCredentialsService.provision')(function* (input: ProvisionInput) {\n const stored = yield* store.get(input.applicationId);\n const existing = input.existingContent ? parseEnv(input.existingContent) : {};\n const existingClientId = existing['GIGADRIVE_CLIENT_ID'];\n const existingClientSecret = existing['GIGADRIVE_CLIENT_SECRET'];\n\n const canReuse =\n !input.rotate &&\n existingClientId !== undefined &&\n existingClientSecret !== undefined &&\n Option.isSome(stored) &&\n stored.value.apiKeyId === existingClientId;\n\n if (canReuse) {\n return credentialEntries(existingClientId, existingClientSecret, baseUrl);\n }\n\n // Revoke the previously provisioned key (if any) to avoid sprawl. Best\n // effort: a key that was already deleted server-side must not block us.\n if (Option.isSome(stored)) {\n yield* apiClient\n .request((client) => client.apiKeys.delete(stored.value.apiKeyId))\n .pipe(Effect.catchTag('ApiRequestError', () => Effect.void));\n }\n\n const created = yield* apiClient.request((client) =>\n client.apiKeys.create({\n name: keyName(input.applicationId),\n applicationId: input.applicationId,\n scopes: DEV_KEY_SCOPES,\n })\n );\n\n yield* store.set(input.applicationId, { apiKeyId: created.id });\n\n return credentialEntries(created.id, created.secret, baseUrl);\n });\n\n return { provision };\n }),\n}) {}\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option, Schema } from 'effect';\nimport * as os from 'node:os';\nimport type { DevKeyEntry, DevKeyStore } from '../domain';\nimport { DevKeyStore as DevKeyStoreSchema } from '../domain';\nimport { DevCredentialsStoreReadError, DevCredentialsStoreWriteError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// DevCredentialsStore\n//\n// Persists, per user/machine, the ID of the API key the CLI provisioned for\n// local development, keyed by application ID. Lives at\n// `~/.gigadrive/dev-keys.json` (mode 0o600, in the 0o700 dir). Only the key ID\n// is stored — never the secret.\n// ---------------------------------------------------------------------------\n\nexport class DevCredentialsStore extends Effect.Service<DevCredentialsStore>()('DevCredentialsStore', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const homeDir = os.homedir();\n const storeDir = pathService.join(homeDir, '.gigadrive');\n const storeFile = pathService.join(storeDir, 'dev-keys.json');\n\n const ensureDirectory = Effect.gen(function* () {\n yield* fs\n .makeDirectory(storeDir, { recursive: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new DevCredentialsStoreWriteError({ message: 'Failed to create ~/.gigadrive', cause: String(error) })\n )\n );\n yield* fs.chmod(storeDir, 0o700).pipe(\n Effect.mapError(\n (error) =>\n new DevCredentialsStoreWriteError({\n message: 'Failed to set ~/.gigadrive permissions',\n cause: String(error),\n })\n )\n );\n });\n\n const load = Effect.gen(function* () {\n const present = yield* fs\n .exists(storeFile)\n .pipe(Effect.mapError(() => new DevCredentialsStoreReadError({ message: 'Failed to check dev-keys.json' })));\n if (!present) return {};\n\n const data = yield* fs\n .readFileString(storeFile, 'utf8')\n .pipe(Effect.mapError(() => new DevCredentialsStoreReadError({ message: 'Failed to read dev-keys.json' })));\n\n const json = yield* Effect.try({\n try: () => JSON.parse(data) as unknown,\n catch: () => new DevCredentialsStoreReadError({ message: 'dev-keys.json contains invalid JSON' }),\n });\n\n return yield* Schema.decodeUnknown(DevKeyStoreSchema)(json).pipe(\n Effect.mapError(() => new DevCredentialsStoreReadError({ message: 'dev-keys.json has an invalid schema' }))\n );\n });\n\n /** Look up the stored dev-key entry for an application. */\n const get = Effect.fn('DevCredentialsStore.get')(function* (applicationId: string) {\n const store = yield* load;\n const entry = store[applicationId];\n return entry ? Option.some(entry) : Option.none<DevKeyEntry>();\n });\n\n /** Record the provisioned key ID for an application. */\n const set = Effect.fn('DevCredentialsStore.set')(function* (applicationId: string, entry: DevKeyEntry) {\n const store = yield* load;\n const next: DevKeyStore = { ...store, [applicationId]: entry };\n yield* ensureDirectory;\n yield* fs\n .writeFileString(storeFile, `${JSON.stringify(next, null, 2)}\\n`, { mode: 0o600 })\n .pipe(\n Effect.mapError(\n (error) =>\n new DevCredentialsStoreWriteError({ message: 'Failed to write dev-keys.json', cause: String(error) })\n )\n );\n });\n\n return { get, set };\n }),\n}) {}\n","import { Command, Options, Prompt } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApplicationNotFoundError, NoApplicationsFoundError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Application ID to link (skips the interactive picker)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Only list applications belonging to this organization ID'),\n Options.optional\n);\n\n/**\n * `gigadrive link` — associate the current directory with an application by\n * writing `.gigadrive/project.json`. Deploy and the resource commands read it.\n */\nexport const linkCommand = Command.make('link', { app: appOption, org: orgOption }, ({ app, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const projectLink = yield* ProjectLinkService;\n const cwd = process.cwd();\n\n const organizationId = Option.getOrUndefined(org);\n const { items: apps } = yield* apiClient.request((client) => client.applications.list({ organizationId }));\n\n if (apps.length === 0) {\n return yield* Effect.fail(\n new NoApplicationsFoundError({\n message: 'No applications found. Create one in the Gigadrive console, then run \"gigadrive link\" again.',\n })\n );\n }\n\n const explicitAppId = Option.getOrUndefined(app);\n\n let applicationId: string;\n let linkedOrganizationId: string | undefined;\n\n if (explicitAppId !== undefined) {\n const match = apps.find((a) => a.id === explicitAppId);\n if (match === undefined) {\n return yield* Effect.fail(\n new ApplicationNotFoundError({\n message: `Application \"${explicitAppId}\" was not found among your applications.`,\n })\n );\n }\n applicationId = match.id;\n linkedOrganizationId = match.organization.id;\n } else if (apps.length === 1) {\n applicationId = apps[0].id;\n linkedOrganizationId = apps[0].organization.id;\n } else {\n const chosen = yield* Prompt.run(\n Prompt.select({\n message: 'Select an application to link',\n choices: apps.map((a) => ({ title: `${a.name} (${a.organization.name})`, value: a })),\n })\n );\n applicationId = chosen.id;\n linkedOrganizationId = chosen.organization.id;\n }\n\n yield* projectLink.save(cwd, { applicationId, organizationId: linkedOrganizationId });\n\n yield* Console.log(`Linked this directory to application ${applicationId}.`);\n yield* Console.log('Tip: add \".gigadrive/\" to your .gitignore.');\n }).pipe(\n Effect.catchTags({\n // Ctrl+C during the picker is a deliberate cancel — exit 0.\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list applications: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n NoApplicationsFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ApplicationNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\n/** `gigadrive unlink` — remove the current directory's `.gigadrive/project.json`. */\nexport const unlinkCommand = Command.make('unlink', {}, () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n yield* projectLink.remove(process.cwd());\n yield* Console.log('Unlinked this directory.');\n }).pipe(\n Effect.catchTags({\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { AuthService } from '../../services/auth';\n\nexport const loginCommand = Command.make('login', {}, () =>\n Effect.gen(function* () {\n yield* Console.log('Initiating login...');\n\n const auth = yield* AuthService;\n yield* auth.login;\n\n const info = yield* auth.getUserInfo.pipe(Effect.catchAll(() => Effect.succeed({})));\n\n const name = auth.inferUserName(info);\n yield* Console.log(`You are now logged in as ${name}.`);\n }).pipe(\n Effect.catchTags({\n LoginFlowError: (err: { message: string }) => Console.error(err.message),\n DeviceAuthorizationError: (err: { message: string }) => Console.error(`Login failed: ${err.message}`),\n AuthorizationDeniedError: (err: { message: string }) => Console.error(err.message),\n DeviceCodeExpiredError: (err: { message: string }) => Console.error(err.message),\n TokenExchangeError: (err: { message: string }) => Console.error(`Login failed: ${err.message}`),\n OAuthDiscoveryError: (err: { message: string }) => Console.error(`Login failed: ${err.message}`),\n AuthStorageWriteError: (err: { message: string }) => Console.error(`Failed to save credentials: ${err.message}`),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { AuthService } from '../../services/auth';\n\n/** `gigadrive logout` — clear stored credentials (`~/.gigadrive/auth.json`). */\nexport const logoutCommand = Command.make('logout', {}, () =>\n Effect.gen(function* () {\n const auth = yield* AuthService;\n yield* auth.logout;\n yield* Console.log('Logged out.');\n }).pipe(\n Effect.catchTags({\n AuthStorageWriteError: (err) =>\n Console.error(`Failed to log out: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Effect } from 'effect';\nimport { deployCommand } from './deploy';\n\nconst platformBase = Command.make('platform', {}, () => Effect.void);\n\nexport const platformCommand = platformBase.pipe(Command.withSubcommands([deployCommand]));\n","import { Command, Options, Prompt } from '@effect/cli';\nimport { FileSystem, Path } from '@effect/platform';\nimport { formatFileSize } from '@gigadrive/commons';\nimport { Console, Duration, Effect, Option, Schedule, Stream } from 'effect';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { DeploymentId, DeploymentLog, DeploymentStatus } from '../../../domain';\nimport { DeploymentFailedError, NoOrganizationsFoundError, UploadPartError } from '../../../errors';\nimport { ApiClientService } from '../../../services/api-client';\nimport { ArchiveService } from '../../../services/archive';\nimport { DeploymentApiService } from '../../../services/deployment-api';\nimport { ProjectConfigService } from '../../../services/project-config';\nimport { ProjectLinkService } from '../../../services/project-link';\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Application ID to deploy to (overrides the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Organization ID to use when automatically creating an application'),\n Options.optional\n);\n\nconst nameOption = Options.text('name').pipe(\n Options.withAlias('n'),\n Options.withDescription('Application name to use when automatically creating an application'),\n Options.optional\n);\n\ninterface DeploymentApplicationInput {\n app: Option.Option<string>;\n org: Option.Option<string>;\n name: Option.Option<string>;\n cwd: string;\n}\n\nconst createAndLinkDeploymentApplication = (input: DeploymentApplicationInput) =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const apiClient = yield* ApiClientService;\n const { items: organizations } = yield* apiClient.request((client) => client.organizations.list());\n const availableOrganizations = Option.match(input.org, {\n onNone: () => organizations,\n onSome: (organizationId) => organizations.filter((organization) => organization.id === organizationId),\n });\n\n if (availableOrganizations.length === 0) {\n return yield* new NoOrganizationsFoundError({\n message: Option.match(input.org, {\n onNone: () =>\n 'No organization is available for this deployment. Create an organization, then run \"gigadrive deploy\" again.',\n onSome: (organizationId) => `Organization \"${organizationId}\" was not found among your organizations.`,\n }),\n });\n }\n\n const organization =\n availableOrganizations.length === 1\n ? availableOrganizations[0]\n : yield* Prompt.run(\n Prompt.select({\n message: 'Select an organization for this application',\n choices: availableOrganizations.map((candidate) => ({\n title: candidate.name,\n value: candidate,\n })),\n })\n );\n\n const inferredName = path.basename(input.cwd) || 'Application';\n const applicationName = Option.match(input.name, {\n onNone: () => inferredName,\n onSome: (name) => name,\n }).trim();\n const application = yield* apiClient.request((client) =>\n client.applications.create({\n organizationId: organization.id,\n name: applicationName || inferredName,\n })\n );\n\n yield* projectLink.save(input.cwd, {\n applicationId: application.id,\n organizationId: organization.id,\n });\n yield* Console.log(`Created and linked application ${application.name} (${application.id}).`);\n return application.id;\n });\n\nconst resolveLinkedDeploymentApplication = (input: DeploymentApplicationInput) =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const existingLink = yield* projectLink.load(input.cwd);\n return yield* Option.match(existingLink, {\n onNone: () => createAndLinkDeploymentApplication(input),\n onSome: (link) => Effect.succeed(link.applicationId),\n });\n });\n\n/**\n * Resolves the application for a deployment, automatically creating and\n * linking one when the current directory has no project link.\n *\n * An explicit application ID always wins. Otherwise an existing local link is\n * reused. For a new project, the authenticated actor's sole organization is\n * selected automatically; multiple organizations trigger an interactive\n * picker unless `--org` identifies one. The created link makes subsequent\n * deploys non-interactive.\n *\n * @param input - Command options and the current project directory.\n * @returns The application UUID that should own the deployment.\n */\nexport const resolveDeploymentApplication = (input: DeploymentApplicationInput) =>\n Option.match(input.app, {\n onNone: () => resolveLinkedDeploymentApplication(input),\n onSome: Effect.succeed,\n });\n\nexport const deployCommand = Command.make(\n 'deploy',\n { app: appOption, org: orgOption, name: nameOption },\n ({ app, org, name }) =>\n Effect.gen(function* () {\n const projectConfig = yield* ProjectConfigService;\n const deploymentApi = yield* DeploymentApiService;\n const archiveService = yield* ArchiveService;\n const pathService = yield* Path.Path;\n\n const cwd = process.cwd();\n\n // Resolve and validate config\n yield* Effect.log('Starting deploy command');\n const { config } = yield* projectConfig.resolve(cwd);\n\n const applicationId = yield* resolveDeploymentApplication({ app, org, name, cwd });\n\n // Create deployment\n yield* Console.log('Creating deployment...');\n const deploymentId = yield* deploymentApi.createDeployment(applicationId);\n yield* Console.log(`Deployment ID: ${deploymentId}`);\n\n // Create and upload archive\n yield* Console.log('Creating archive...');\n const archivePath = pathService.join(os.tmpdir(), `project-${Date.now()}.zip`);\n const archive = yield* archiveService.createZipArchive(config.userArchive?.rootOverwrite || cwd, archivePath, {\n whitelist: config.userArchive?.fileWhitelist,\n excludeFiles: config.excludeFiles,\n buildsContainerImages: [\n ...config.entrypoints.flatMap((entrypoint) => (entrypoint.container ? [entrypoint.container] : [])),\n ...(config.sidecars ?? []),\n ].some((container) => container.source.type === 'dockerfile'),\n });\n yield* Console.log(`Archive created (${formatFileSize(archive.size)})`);\n\n // Upload archive\n yield* Console.log('Uploading archive...');\n yield* uploadArchive(deploymentId, archivePath, archive.size);\n yield* Console.log('Upload complete.');\n yield* Console.log('The deployment pipeline is now being provisioned. This may take a few seconds.');\n\n // Poll for status and logs\n yield* pollDeployment(deploymentId);\n }).pipe(\n Effect.catchTags({\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Application setup failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n NoOrganizationsFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ConfigNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ConfigParseError: (err) =>\n Console.error(`Config parse error: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ConfigValidationError: (err) =>\n Effect.gen(function* () {\n for (const e of err.errors) {\n yield* Console.error(e);\n }\n yield* Console.error(err.message);\n }).pipe(Effect.andThen(Effect.fail(err))),\n DeploymentCreateError: (err) =>\n Console.error(`Deployment creation failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ArchiveCreateError: (err) =>\n Console.error(`Archive creation failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n UploadStartError: (err) =>\n Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n UploadPartError: (err) => Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n UploadCompleteError: (err) =>\n Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n PresignedUrlError: (err) =>\n Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n DeploymentAuthError: (err) =>\n Console.error(`Authentication failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n DeploymentFailedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\n// ---------------------------------------------------------------------------\n// Upload archive helper\n// ---------------------------------------------------------------------------\n\nconst uploadArchive = (deploymentId: DeploymentId, archivePath: string, fileSize: number) =>\n Effect.gen(function* () {\n const deploymentApi = yield* DeploymentApiService;\n const fs = yield* FileSystem.FileSystem;\n\n const uploadId = yield* deploymentApi.startMultipartUpload(deploymentId);\n\n const FILE_CHUNK_SIZE = 10 * 1024 * 1024; // 10 MB\n const numChunks = Math.ceil(fileSize / FILE_CHUNK_SIZE);\n\n yield* Effect.log('Starting multipart upload', { uploadId, numChunks, fileSize });\n\n // Upload all chunks — each chunk is streamed from disk independently\n const parts = yield* Effect.all(\n Array.from({ length: numChunks }, (_, i) => {\n const partNumber = i + 1;\n const start = i * FILE_CHUNK_SIZE;\n const bytesToRead = partNumber < numChunks ? FILE_CHUNK_SIZE : fileSize - start;\n\n return Effect.gen(function* () {\n const presignedUrl = yield* deploymentApi.getPresignedUrl(deploymentId, uploadId, partNumber);\n\n // Stream only this chunk from disk to keep memory bounded\n const chunkData = yield* Stream.runCollect(fs.stream(archivePath, { offset: start, bytesToRead })).pipe(\n Effect.map((chunks) => {\n const arrays = Array.from(chunks);\n return Buffer.concat(arrays);\n }),\n Effect.mapError(\n (error) =>\n new UploadPartError({\n message: `Failed to read chunk ${partNumber}: ${String(error)}`,\n partNumber,\n })\n )\n );\n\n yield* Effect.log(`Uploading part ${partNumber}/${numChunks}`, { size: chunkData.length });\n return yield* deploymentApi.uploadPart(presignedUrl, chunkData, partNumber);\n });\n }),\n { concurrency: 3 }\n );\n\n yield* deploymentApi.completeUpload(deploymentId, uploadId, parts);\n });\n\n// ---------------------------------------------------------------------------\n// Poll deployment status + logs\n// ---------------------------------------------------------------------------\n\nconst pollDeployment = (deploymentId: DeploymentId) =>\n Effect.gen(function* () {\n const deploymentApi = yield* DeploymentApiService;\n let lastStatus: DeploymentStatus = 'PENDING';\n let logOffset = 0;\n\n yield* Console.log('Status: Pending');\n\n // Poll in a loop until terminal status\n yield* Effect.repeat(\n Effect.gen(function* () {\n // Check status\n const newStatus = yield* deploymentApi\n .getDeploymentStatus(deploymentId)\n .pipe(Effect.catchTag('DeploymentStatusError', () => Effect.succeed(lastStatus)));\n\n if (newStatus !== lastStatus) {\n lastStatus = newStatus;\n const label = newStatus.charAt(0) + newStatus.slice(1).toLowerCase();\n yield* Console.log(`Status: ${label}`);\n }\n\n // Fetch logs\n const logsPage = yield* deploymentApi\n .getLogs(deploymentId, { offset: logOffset, limit: 100 })\n .pipe(Effect.catchTag('DeploymentLogsFetchError', () => Effect.succeed(null)));\n\n if (logsPage) {\n for (const logEntry of logsPage.items) {\n logOffset++;\n yield* printLog(logEntry);\n }\n }\n\n // Check terminal states\n if (newStatus === 'ACTIVE') {\n // Print the real per-deployment `*.gigadrive.app` hostname. Hostname\n // lookup is best-effort — a failure here must not fail a successful deploy.\n const hostnames = yield* deploymentApi\n .getHostnames(deploymentId)\n .pipe(Effect.catchTag('DeploymentHostnamesFetchError', () => Effect.succeed([])));\n const active = hostnames.find((h) => h.active) ?? hostnames.at(0);\n if (active) {\n yield* Console.log(`Deployed to https://${active.hostname}`);\n } else {\n yield* Console.log('Deployment is live.');\n }\n return yield* Effect.fail('done' as const);\n }\n\n if (newStatus === 'FAILED') {\n return yield* Effect.fail(\n new DeploymentFailedError({\n message: 'The deployment failed. Please check the logs for more information.',\n })\n );\n }\n }),\n Schedule.addDelay(Schedule.forever, () => Duration.seconds(1))\n ).pipe(\n Effect.catchAll((err) => {\n if (err === 'done') return Effect.void;\n return Effect.fail(err);\n })\n );\n });\n\nconst printLog = (logEntry: DeploymentLog) => {\n switch (logEntry.type) {\n case 'ERROR':\n return Console.error(logEntry.message);\n case 'WARN':\n return Console.warn(logEntry.message);\n default:\n return Console.log(logEntry.message);\n }\n};\n","import { FileSystem, Path } from '@effect/platform';\nimport { getFilesForPattern } from '@gigadrive/build-utils';\nimport archiver from 'archiver';\nimport { Effect } from 'effect';\nimport ignore, { type Ignore } from 'ignore';\nimport * as nodeFs from 'node:fs';\nimport * as nodeFsPromises from 'node:fs/promises';\nimport { ArchiveCreateError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// Ignore file handling\n// ---------------------------------------------------------------------------\n\nconst IGNORE_FILE_NAMES = ['.gitignore', '.dockerignore', '.nowignore', '.vercelignore', '.gigadriveignore'];\n\nconst MANAGED_IGNORE_PATTERNS = [\n '.git/',\n '**/.git/',\n 'node_modules/',\n '**/node_modules/',\n '**/.DS_Store',\n '**/Thumbs.db',\n];\n\n/**\n * Container build inputs that stay in the archive whatever the ignore files\n * say. Docker sends a Dockerfile even when `.dockerignore` lists it, and that\n * file, like a Compose file, is commonly listed there.\n */\nconst CONTAINER_BUILD_FILE_PATTERNS = [\n '!Dockerfile',\n '!**/Dockerfile',\n '!**/*.Dockerfile',\n '!**/Dockerfile.*',\n '!compose.yaml',\n '!compose.yml',\n '!docker-compose.yaml',\n '!docker-compose.yml',\n];\n\n/**\n * `.dockerignore` filters a Docker build context, which BuildKit reads on the\n * server. Applied here with gitignore semantics it would also drop files a\n * Dockerfile copies: Docker anchors its patterns at the context root and\n * allow-lists such as `*` then `!src` exclude more here than there.\n */\nconst DOCKER_BUILD_IGNORE_FILE = '.dockerignore';\n\nconst readIgnoreFile = (fs: FileSystem.FileSystem, ignorePath: string): Effect.Effect<string[]> =>\n fs.readFileString(ignorePath, 'utf8').pipe(\n Effect.map((content) => content.split('\\n').filter((line: string) => line.trim() !== '')),\n Effect.catchAll(() => Effect.succeed([] as string[]))\n );\n\nconst collectIgnorePatterns = (\n fs: FileSystem.FileSystem,\n pathService: Path.Path,\n dir: string,\n baseDir: string,\n ignoreRules: Ignore,\n ignoreFileNames: readonly string[]\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const items = yield* fs\n .readDirectory(dir)\n .pipe(Effect.mapError(() => new ArchiveCreateError({ message: `Failed to read directory: ${dir}` })));\n\n for (const item of items) {\n const fullPath = pathService.join(dir, item);\n const relativePath = pathService.relative(baseDir, fullPath);\n // Use lstat to avoid following symlinks (matches original behavior)\n const stat = yield* Effect.tryPromise({\n try: () => nodeFsPromises.lstat(fullPath),\n catch: () => new ArchiveCreateError({ message: `Failed to stat: ${fullPath}` }),\n });\n\n if (stat.isDirectory()) {\n if (ignoreRules.ignores(`${relativePath}/`)) continue;\n\n for (const ignoreFileName of ignoreFileNames) {\n const ignoreFilePath = pathService.join(fullPath, ignoreFileName);\n const patterns = yield* readIgnoreFile(fs, ignoreFilePath);\n if (patterns.length > 0) {\n ignoreRules.add(\n patterns.map((pattern: string) =>\n pattern.startsWith('!')\n ? `!${pathService.join(relativePath, pattern.slice(1))}`\n : pathService.join(relativePath, pattern)\n )\n );\n }\n }\n\n yield* collectIgnorePatterns(fs, pathService, fullPath, baseDir, ignoreRules, ignoreFileNames);\n }\n }\n }).pipe(Effect.catchAll(() => Effect.void));\n\nconst initializeIgnoreRules = (\n fs: FileSystem.FileSystem,\n pathService: Path.Path,\n baseDir: string,\n useIgnoreFiles: boolean,\n useManagedIgnore: boolean,\n buildsContainerImages: boolean\n): Effect.Effect<Ignore> =>\n Effect.gen(function* () {\n const ignoreRules = ignore();\n const ignoreFileNames = buildsContainerImages\n ? IGNORE_FILE_NAMES.filter((name) => name !== DOCKER_BUILD_IGNORE_FILE)\n : IGNORE_FILE_NAMES;\n if (useManagedIgnore) {\n ignoreRules.add(MANAGED_IGNORE_PATTERNS);\n }\n\n if (useIgnoreFiles) {\n for (const ignoreFileName of ignoreFileNames) {\n const ignoreFilePath = pathService.join(baseDir, ignoreFileName);\n const patterns = yield* readIgnoreFile(fs, ignoreFilePath);\n if (patterns.length > 0) {\n ignoreRules.add(\n patterns.map((pattern: string) => (pattern.startsWith('!') ? `!${pattern.slice(1)}` : pattern))\n );\n }\n }\n\n yield* collectIgnorePatterns(fs, pathService, baseDir, baseDir, ignoreRules, ignoreFileNames);\n ignoreRules.add(CONTAINER_BUILD_FILE_PATTERNS);\n }\n return ignoreRules;\n });\n\nconst getFilesToInclude = (\n fs: FileSystem.FileSystem,\n pathService: Path.Path,\n dir: string,\n ignoreRules: Ignore\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const filesToInclude: string[] = [];\n\n const walkDir = (currentDir: string): Effect.Effect<void> =>\n Effect.gen(function* () {\n const items = yield* fs\n .readDirectory(currentDir)\n .pipe(Effect.mapError(() => new ArchiveCreateError({ message: `Failed to read directory: ${currentDir}` })));\n\n for (const item of items) {\n const fullPath = pathService.join(currentDir, item);\n const relativePath = pathService.relative(dir, fullPath);\n // Use lstat to avoid following symlinks (matches original behavior)\n const stat = yield* Effect.tryPromise({\n try: () => nodeFsPromises.lstat(fullPath),\n catch: () => new ArchiveCreateError({ message: `Failed to stat: ${fullPath}` }),\n });\n\n if (stat.isDirectory()) {\n if (!ignoreRules.ignores(`${relativePath}/`)) {\n yield* walkDir(fullPath);\n }\n } else {\n if (!ignoreRules.ignores(relativePath)) {\n filesToInclude.push(fullPath);\n }\n }\n }\n }).pipe(Effect.catchAll(() => Effect.void));\n\n yield* walkDir(dir);\n return filesToInclude;\n });\n\n// ---------------------------------------------------------------------------\n// ArchiveService\n// ---------------------------------------------------------------------------\n\nexport class ArchiveService extends Effect.Service<ArchiveService>()('ArchiveService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const createZipArchive = Effect.fn('ArchiveService.createZipArchive')(function* (\n inputDir: string,\n outputFile: string,\n options: {\n whitelist?: string[];\n excludeFiles?: string[];\n useIgnoreFiles?: boolean;\n useManagedIgnore?: boolean;\n /** The deployment builds Dockerfiles, so `.dockerignore` is left to BuildKit. */\n buildsContainerImages?: boolean;\n } = {}\n ) {\n yield* Effect.annotateCurrentSpan('inputDir', inputDir);\n yield* Effect.annotateCurrentSpan('outputFile', outputFile);\n yield* Effect.log('Creating zip archive', { inputDir, outputFile });\n\n const ignoreRules = yield* initializeIgnoreRules(\n fs,\n pathService,\n inputDir,\n options.useIgnoreFiles !== false,\n options.useManagedIgnore !== false,\n options.buildsContainerImages === true\n );\n\n const filesToInclude = options.whitelist\n ? yield* Effect.tryPromise({\n try: () =>\n Promise.all(\n options.whitelist!.map((file) => getFilesForPattern(file, inputDir, options.excludeFiles ?? []))\n ),\n catch: (error) =>\n new ArchiveCreateError({\n message: 'Failed to resolve whitelist patterns',\n cause: error instanceof Error ? error.message : String(error),\n }),\n })\n : yield* Effect.gen(function* () {\n // Add excludeFiles patterns (from framework detection or user config) to ignore rules\n if (options.excludeFiles && options.excludeFiles.length > 0) {\n ignoreRules.add(options.excludeFiles);\n }\n return yield* getFilesToInclude(fs, pathService, inputDir, ignoreRules).pipe(\n Effect.map((files) => [files])\n );\n });\n\n // Remove existing archive if present\n const archiveExists = yield* fs.exists(outputFile).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (archiveExists) {\n yield* fs.remove(outputFile).pipe(\n Effect.mapError(\n (error) =>\n new ArchiveCreateError({\n message: `Failed to remove existing archive: ${String(error)}`,\n })\n )\n );\n }\n\n yield* Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n // archiver requires a Node.js writable stream\n const output = nodeFs.createWriteStream(outputFile);\n const archive = archiver('zip', { zlib: { level: 9 } });\n\n output.on('close', () => resolve());\n output.on('error', reject);\n archive.on('error', reject);\n archive.pipe(output);\n\n for (const file of filesToInclude.flat()) {\n archive.file(file, { name: pathService.relative(inputDir, file) });\n }\n\n void archive.finalize();\n }),\n catch: (error) =>\n new ArchiveCreateError({\n message: 'Failed to create zip archive',\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n const fileInfo = yield* fs.stat(outputFile).pipe(\n Effect.mapError(\n (error) =>\n new ArchiveCreateError({\n message: `Failed to stat archive: ${String(error)}`,\n })\n )\n );\n const size = Number(fileInfo.size);\n yield* Effect.log('Archive created', { size });\n\n return { path: outputFile, size };\n });\n\n return { createZipArchive };\n }),\n}) {}\n","import { Effect } from 'effect';\nimport type { DeploymentId, UploadId } from '../domain';\nimport {\n DeploymentAuthError,\n DeploymentCreateError,\n DeploymentHostnamesFetchError,\n DeploymentLogsFetchError,\n DeploymentStatusError,\n PresignedUrlError,\n UploadCompleteError,\n UploadPartError,\n UploadStartError,\n} from '../errors';\nimport { ApiClientService } from './api-client';\n\n// ---------------------------------------------------------------------------\n// DeploymentApiService\n//\n// A thin, deployment-focused wrapper over the shared ApiClientService. It keeps\n// its own tagged errors (DeploymentAuthError, UploadPartError, …) so the deploy\n// command's error handling and spans are unchanged.\n// ---------------------------------------------------------------------------\n\nexport class DeploymentApiService extends Effect.Service<DeploymentApiService>()('DeploymentApiService', {\n accessors: true,\n dependencies: [ApiClientService.Default],\n\n effect: Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n\n const getClient = apiClient.getClient.pipe(\n Effect.mapError((err) => new DeploymentAuthError({ message: `Authentication failed: ${err.message}` }))\n );\n\n const createDeployment = Effect.fn('DeploymentApiService.createDeployment')(function* (applicationId: string) {\n yield* Effect.annotateCurrentSpan('applicationId', applicationId);\n yield* Effect.log('Creating deployment', { applicationId });\n\n const client = yield* getClient;\n const deployment = yield* Effect.tryPromise({\n try: () => client.deployments.create({ applicationId }),\n catch: (error) =>\n new DeploymentCreateError({\n message: `Failed to create deployment: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n yield* Effect.log('Deployment created', { deploymentId: deployment.id });\n return deployment.id as DeploymentId;\n });\n\n const startMultipartUpload = Effect.fn('DeploymentApiService.startMultipartUpload')(function* (\n deploymentId: DeploymentId\n ) {\n yield* Effect.annotateCurrentSpan('deploymentId', deploymentId);\n\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.startUpload(deploymentId),\n catch: (error) =>\n new UploadStartError({\n message: `Failed to start multipart upload: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return result.uploadId as UploadId;\n });\n\n const getPresignedUrl = Effect.fn('DeploymentApiService.getPresignedUrl')(function* (\n deploymentId: DeploymentId,\n uploadId: UploadId,\n partNumber: number\n ) {\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.getPresignedUrl(deploymentId, uploadId, partNumber),\n catch: (error) =>\n new PresignedUrlError({\n message: `Failed to get presigned URL: ${error instanceof Error ? error.message : String(error)}`,\n partNumber,\n }),\n });\n\n return result.url;\n });\n\n const uploadPart = Effect.fn('DeploymentApiService.uploadPart')(function* (\n presignedUrl: string,\n data: Buffer,\n partNumber: number\n ) {\n yield* Effect.annotateCurrentSpan('partNumber', partNumber);\n yield* Effect.annotateCurrentSpan('size', data.length);\n\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.uploadPart(presignedUrl, data, partNumber),\n catch: (error) =>\n new UploadPartError({\n message: `Failed to upload part ${partNumber}: ${error instanceof Error ? error.message : String(error)}`,\n partNumber,\n }),\n });\n\n return result;\n });\n\n const completeUpload = Effect.fn('DeploymentApiService.completeUpload')(function* (\n deploymentId: DeploymentId,\n uploadId: UploadId,\n parts: Array<{ partNumber: number; etag: string }>\n ) {\n yield* Effect.annotateCurrentSpan('deploymentId', deploymentId);\n yield* Effect.annotateCurrentSpan('partsCount', parts.length);\n\n const client = yield* getClient;\n yield* Effect.tryPromise({\n try: () => client.deployments.completeUpload(deploymentId, uploadId, parts),\n catch: (error) =>\n new UploadCompleteError({\n message: `Failed to complete upload: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n yield* Effect.log('Upload completed successfully');\n });\n\n const getDeploymentStatus = Effect.fn('DeploymentApiService.getDeploymentStatus')(function* (\n deploymentId: DeploymentId\n ) {\n const client = yield* getClient;\n const deployment = yield* Effect.tryPromise({\n try: () => client.deployments.get(deploymentId),\n catch: (error) =>\n new DeploymentStatusError({\n message: `Failed to get deployment status: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return deployment.status;\n });\n\n const getLogs = Effect.fn('DeploymentApiService.getLogs')(function* (\n deploymentId: DeploymentId,\n options?: { offset: number; limit: number; 'createdAt[gt]'?: string }\n ) {\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.getLogs(deploymentId, options),\n catch: (error) =>\n new DeploymentLogsFetchError({\n message: `Failed to get logs: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return result;\n });\n\n const getHostnames = Effect.fn('DeploymentApiService.getHostnames')(function* (deploymentId: DeploymentId) {\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.getHostnames(deploymentId),\n catch: (error) =>\n new DeploymentHostnamesFetchError({\n message: `Failed to get hostnames: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return result.items;\n });\n\n return {\n createDeployment,\n startMultipartUpload,\n getPresignedUrl,\n uploadPart,\n completeUpload,\n getDeploymentStatus,\n getLogs,\n getHostnames,\n };\n }),\n}) {}\n","import { Args, Command, Options, Prompt } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApplicationNotFoundError, NoApplicationsFoundError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { EnvFileService } from '../../services/env-file';\nimport { LocalCredentialsService } from '../../services/local-credentials';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst fileArg = Args.text({ name: 'file' }).pipe(\n Args.withDescription('Output file to write (default: .env.local)'),\n Args.optional\n);\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Application ID to set up (skips the interactive picker)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Only list applications belonging to this organization ID when picking'),\n Options.optional\n);\n\nconst environmentOption = Options.text('environment').pipe(\n Options.withAlias('e'),\n Options.withDescription('Environment slug to resolve overrides for (e.g. preview)'),\n Options.optional\n);\n\nconst yesOption = Options.boolean('yes').pipe(\n Options.withAlias('y'),\n Options.withDescription('Overwrite an existing file without confirmation')\n);\n\nconst rotateOption = Options.boolean('rotate').pipe(\n Options.withDescription('Force a fresh API key, revoking the previous one')\n);\n\n/**\n * `gigadrive setup` — one command to wire up a local dev environment: ensures the\n * directory is linked to an application (prompting if needed), pulls the\n * application's non-sensitive environment variables, provisions least-privilege\n * API credentials, and writes everything to `.env.local`.\n */\nexport const setupCommand = Command.make(\n 'setup',\n {\n file: fileArg,\n app: appOption,\n org: orgOption,\n environment: environmentOption,\n yes: yesOption,\n rotate: rotateOption,\n },\n ({ file, app, org, environment, yes, rotate }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const projectLink = yield* ProjectLinkService;\n const envFile = yield* EnvFileService;\n const localCredentials = yield* LocalCredentialsService;\n const cwd = process.cwd();\n\n // 1. Ensure the directory is linked to an application.\n const existingLink = yield* projectLink.load(cwd);\n let applicationId: string;\n if (Option.isSome(existingLink)) {\n applicationId = existingLink.value.applicationId;\n // The picker (and thus --app/--org) is only consulted when unlinked.\n if (Option.isSome(app) || Option.isSome(org)) {\n yield* Console.log(\n `Note: this directory is already linked to ${applicationId}; ignoring --app/--org. Run \"gigadrive unlink\" first to target a different application.`\n );\n }\n } else {\n const organizationId = Option.getOrUndefined(org);\n const { items: apps } = yield* apiClient.request((client) => client.applications.list({ organizationId }));\n if (apps.length === 0) {\n return yield* Effect.fail(\n new NoApplicationsFoundError({\n message: 'No applications found. Create one in the Gigadrive console, then run \"gigadrive setup\" again.',\n })\n );\n }\n\n const explicitAppId = Option.getOrUndefined(app);\n let chosen: (typeof apps)[number];\n if (explicitAppId !== undefined) {\n const match = apps.find((a) => a.id === explicitAppId);\n if (match === undefined) {\n return yield* Effect.fail(\n new ApplicationNotFoundError({\n message: `Application \"${explicitAppId}\" was not found among your applications.`,\n })\n );\n }\n chosen = match;\n } else if (apps.length === 1) {\n chosen = apps[0];\n } else {\n chosen = yield* Prompt.run(\n Prompt.select({\n message: 'Select an application to set up',\n choices: apps.map((a) => ({ title: `${a.name} (${a.organization.name})`, value: a })),\n })\n );\n }\n\n applicationId = chosen.id;\n yield* projectLink.save(cwd, { applicationId, organizationId: chosen.organization.id });\n yield* Console.log(`Linked this directory to application ${applicationId}.`);\n }\n\n const target = Option.getOrElse(file, () => '.env.local');\n const environmentSlug = Option.getOrUndefined(environment);\n\n // 2. Pull the application's non-sensitive environment variables.\n const { items, omittedSensitive } = yield* apiClient.request((client) =>\n client.applications.envVars.pull(applicationId, environmentSlug ? { environment: environmentSlug } : undefined)\n );\n\n // 3. Confirm overwrite (reading first so credentials can be reused).\n const existing = yield* envFile.read(target);\n if (Option.isSome(existing) && !yes) {\n const overwrite = yield* Prompt.run(\n Prompt.confirm({ message: `${target} already exists. Overwrite?`, initial: false })\n );\n if (!overwrite) {\n return yield* Console.log('Cancelled.');\n }\n }\n\n // 4. Provision least-privilege API credentials.\n const credentialEntries = yield* localCredentials.provision({\n applicationId,\n rotate,\n existingContent: Option.getOrUndefined(existing),\n });\n\n // 5. Write the combined file and keep it out of git.\n const entries = [...items.map((v) => ({ key: v.key, value: v.value })), ...credentialEntries];\n yield* envFile.write(target, entries);\n const gitignored = yield* envFile.ensureGitignored(cwd, target);\n\n // 6. Print next steps.\n yield* Console.log('\\nLocal dev environment ready.');\n yield* Console.log(` • Wrote ${items.length} variable(s) and API credentials to ${target}.`);\n if (omittedSensitive > 0) {\n yield* Console.log(\n ` • Skipped ${omittedSensitive} sensitive variable(s) (only production/preview hold secrets).`\n );\n }\n if (gitignored) {\n yield* Console.log(` • Added ${target} to .gitignore.`);\n }\n yield* Console.log(' • Your app can now call the Gigadrive API via the SDK (GIGADRIVE_CLIENT_ID/SECRET).');\n }).pipe(\n Effect.catchTags({\n // Ctrl+C during a prompt is a deliberate cancel — exit 0.\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) => Console.error(`Setup failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n NoApplicationsFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ApplicationNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { AuthService } from '../../services/auth';\n\nexport const whoamiCommand = Command.make('whoami', {}, () =>\n Effect.gen(function* () {\n const auth = yield* AuthService;\n const info = yield* auth.getUserInfo;\n yield* Console.log(JSON.stringify(info, null, 2));\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: () => Console.log('You are not logged in. Run \"gigadrive login\" to authenticate.'),\n UserInfoFetchError: (err) => Console.error(`Failed to retrieve user info: ${err.message}`),\n OAuthDiscoveryError: (err) => Console.error(`Failed to retrieve user info: ${err.message}`),\n })\n )\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,eAAwB;AACxB,2BAAyC;AACzC,IAAAC,yBAAkC;AAClC,IAAAC,kBAAgD;;;ACHhD;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,SAAW;AAAA,EACX,QAAU;AAAA,EACV,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,KAAO;AAAA,IACL,WAAa;AAAA,IACb,IAAM;AAAA,EACR;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,OAAS;AAAA,IACT,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,cAAgB;AAAA,IACd,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,yBAAyB;AAAA,IACzB,0BAA0B;AAAA,IAC1B,sBAAsB;AAAA,IACtB,6BAA6B;AAAA,IAC7B,kBAAkB;AAAA,IAClB,UAAY;AAAA,IACZ,QAAU;AAAA,IACV,QAAU;AAAA,IACV,MAAQ;AAAA,EACV;AAAA,EACA,iBAAmB;AAAA,IACjB,4BAA4B;AAAA,IAC5B,mBAAmB;AAAA,IACnB,SAAW;AAAA,IACX,YAAc;AAAA,EAChB;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,eAAiB;AAAA,IACf,QAAU;AAAA,EACZ;AACF;;;AClDA,iBAAuC;AACvC,IAAAC,mBAA2B;AAE3B,IAAAC,iBAAwC;;;ACHxC,oBAAuB;AAMhB,IAAM,sBAAN,cAAkC,qBAAO,Y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AiC,IAAI,OAAO,EAAE;AAAA,IAC5F,CAAC;AAAA,EACH;AACF;;;AjCoBA,IAAM,YAAY,qBAAQ,KAAK,aAAa,CAAC,GAAG,MAAM,uBAAO,IAAI,EAAE;AAAA,EACjE,qBAAQ,gBAAgB;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAMA,IAAM,MAAM,qBAAQ,IAAI,WAAW;AAAA,EACjC,MAAM;AAAA,EACN,SAAS,gBAAI;AACf,CAAC;AAMD,IAAM,eAAe,sBAAM;AAAA,EACzB,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,sBAAsB;AAAA,EACtB,eAAe;AAAA,EACf;AAAA,EACA,qBAAqB;AAAA,EACrB,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,oBAAoB;AACtB,EAAE,KAAK,sBAAM,aAAa,YAAY,OAAO,CAAC;AAE9C,IAAM,gBAAgB,sBAAM,QAAQ,iBAAiB,SAAS,YAAY;AAC1E,IAAM,oBAAoB,sBAAM,QAAQ,qBAAqB,SAAS,YAAY;AAGlF,IAAM,uBAAuB,sBAAM,QAAQ,wBAAwB,SAAS,YAAY;AAExF,IAAM,eAAe,sBAAM,SAAS,cAAc,eAAe,mBAAmB,oBAAoB;AAExG,IAAM,UAAU,sBAAM,SAAS,cAAc,uBAAO,gBAAgB,yBAAS,IAAI,CAAC,EAAE;AAAA,EAClF,sBAAM,aAAa,iCAAY,KAAK;AACtC;AAMA,iCAAY,QAAQ,uBAAO,QAAQ,IAAI,QAAQ,IAAI,GAAG,OAAO,CAAC;","names":["import_cli","import_network_config","import_effect","import_platform","import_effect","import_effect","import_effect","import_node_process","import_effect","process","import_effect","import_effect","process","open","import_platform","import_effect","path","import_cli","import_effect","import_cli","import_platform","import_build_utils","import_effect","import_platform","import_effect","pm","buildCommand","import_cli","import_effect","import_cli","import_effect","import_effect","import_cli","import_effect","appOption","orgOption","import_cli","import_effect","appOption","orgOption","statusOption","domain","hostname","import_cli","import_effect","import_platform","import_effect","import_effect","os","import_platform","import_effect","os","ApiBaseUrl","appOption","orgOption","yesOption","credentialEntries","import_cli","import_effect","appOption","orgOption","import_cli","import_effect","import_cli","import_effect","import_cli","import_effect","import_cli","import_platform","import_effect","os","import_platform","import_build_utils","import_effect","ignore","archiver","import_effect","appOption","orgOption","nameOption","organization","import_cli","import_effect","fileArg","appOption","orgOption","environmentOption","yesOption","rotateOption","credentialEntries","import_cli","import_effect"]}
1
+ {"version":3,"sources":["../src/index.ts","../package.json","../src/commands/ai/index.ts","../src/errors.ts","../src/services/api-client.ts","../src/services/auth.ts","../src/domain.ts","../src/lib/clipboard.ts","../src/services/auth-storage.ts","../src/services/oauth-config.ts","../src/services/project-link.ts","../src/commands/apps/index.ts","../src/commands/build/index.ts","../src/services/package-manager.ts","../src/commands/debug/index.ts","../src/commands/debug/config/index.ts","../src/services/project-config.ts","../src/commands/deployments/index.ts","../src/commands/domains/index.ts","../src/lib/domain-output.ts","../src/commands/env/index.ts","../src/services/env-file.ts","../src/lib/dotenv.ts","../src/services/local-credentials.ts","../src/services/dev-credentials-store.ts","../src/commands/link/index.ts","../src/commands/login/index.ts","../src/commands/logout/index.ts","../src/commands/platform/index.ts","../src/commands/platform/deploy/index.ts","../src/services/archive.ts","../src/services/deployment-api.ts","../src/commands/setup/index.ts","../src/commands/whoami/index.ts"],"sourcesContent":["import { Command } from '@effect/cli';\nimport { NodeContext, NodeRuntime } from '@effect/platform-node';\nimport { NetworkConfigLive } from '@gigadrive/network-config';\nimport { Effect, Layer, LogLevel, Logger } from 'effect';\nimport pkg from '../package.json';\nimport { aiCommand } from './commands/ai';\nimport { appsCommand } from './commands/apps';\nimport { buildCommand } from './commands/build';\nimport { debugCommand } from './commands/debug';\nimport { deploymentsCommand } from './commands/deployments';\nimport { domainsCommand } from './commands/domains';\nimport { envCommand } from './commands/env';\nimport { linkCommand, unlinkCommand } from './commands/link';\nimport { loginCommand } from './commands/login';\nimport { logoutCommand } from './commands/logout';\nimport { platformCommand } from './commands/platform';\nimport { deployCommand } from './commands/platform/deploy';\nimport { setupCommand } from './commands/setup';\nimport { whoamiCommand } from './commands/whoami';\nimport { ApiClientService } from './services/api-client';\nimport { ArchiveService } from './services/archive';\nimport { AuthService } from './services/auth';\nimport { AuthStorageService } from './services/auth-storage';\nimport { DeploymentApiService } from './services/deployment-api';\nimport { DevCredentialsStore } from './services/dev-credentials-store';\nimport { EnvFileService } from './services/env-file';\nimport { LocalCredentialsService } from './services/local-credentials';\nimport { OAuthConfigService } from './services/oauth-config';\nimport { PackageManagerService } from './services/package-manager';\nimport { ProjectConfigService } from './services/project-config';\nimport { ProjectLinkService } from './services/project-link';\n\n// ---------------------------------------------------------------------------\n// Root command with subcommands\n// ---------------------------------------------------------------------------\n\nconst gigadrive = Command.make('gigadrive', {}, () => Effect.void).pipe(\n Command.withSubcommands([\n loginCommand,\n logoutCommand,\n whoamiCommand,\n linkCommand,\n unlinkCommand,\n appsCommand,\n envCommand,\n deploymentsCommand,\n domainsCommand,\n aiCommand,\n buildCommand,\n debugCommand,\n deployCommand,\n platformCommand,\n setupCommand,\n ])\n);\n\n// ---------------------------------------------------------------------------\n// CLI application\n// ---------------------------------------------------------------------------\n\nconst cli = Command.run(gigadrive, {\n name: 'Gigadrive CLI',\n version: pkg.version,\n});\n\n// ---------------------------------------------------------------------------\n// Service layers — flat composition via mergeAll + provideMerge\n// ---------------------------------------------------------------------------\n\nconst BaseServices = Layer.mergeAll(\n OAuthConfigService.Default,\n AuthStorageService.Default,\n PackageManagerService.Default,\n ArchiveService.Default,\n NetworkConfigLive,\n ProjectConfigService.Default,\n ProjectLinkService.Default,\n EnvFileService.Default,\n DevCredentialsStore.Default\n).pipe(Layer.provideMerge(AuthService.Default));\n\nconst ApiClientLive = Layer.provide(ApiClientService.Default, BaseServices);\nconst DeploymentApiLive = Layer.provide(DeploymentApiService.Default, BaseServices);\n// LocalCredentialsService bakes in ApiClientService + DevCredentialsStore via its\n// `dependencies`, so it only needs BaseServices (for the transitive AuthService).\nconst LocalCredentialsLive = Layer.provide(LocalCredentialsService.Default, BaseServices);\n\nconst ServicesLive = Layer.mergeAll(BaseServices, ApiClientLive, DeploymentApiLive, LocalCredentialsLive);\n\nconst AppLive = Layer.mergeAll(ServicesLive, Logger.minimumLogLevel(LogLevel.Info)).pipe(\n Layer.provideMerge(NodeContext.layer)\n);\n\n// ---------------------------------------------------------------------------\n// Run\n// ---------------------------------------------------------------------------\n\nNodeRuntime.runMain(Effect.provide(cli(process.argv), AppLive));\n","{\n \"name\": \"gigadrive\",\n \"version\": \"2.7.3\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Gigadrive/sdk.git\",\n \"directory\": \"packages/cli\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Gigadrive <business@gigadrivegroup.com> (https://gigadrive.de)\",\n \"type\": \"module\",\n \"module\": \"src/index.ts\",\n \"bin\": {\n \"gigadrive\": \"dist/index.mjs\",\n \"gn\": \"dist/index.mjs\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"clean\": \"rm -rf dist\",\n \"dev\": \"pnpm build && node dist/index.mjs\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@effect/cli\": \"^0.77.0\",\n \"@effect/platform\": \"^0.97.0\",\n \"@effect/platform-node\": \"^0.108.0\",\n \"@gigadrive/build-utils\": \"workspace:*\",\n \"@gigadrive/commons\": \"workspace:*\",\n \"@gigadrive/network-config\": \"workspace:*\",\n \"@gigadrive/sdk\": \"workspace:*\",\n \"archiver\": \"^7.0.1\",\n \"effect\": \"^3.19.17\",\n \"ignore\": \"^7.0.5\",\n \"open\": \"^10.2.0\"\n },\n \"devDependencies\": {\n \"@effect/language-service\": \"^0.87.0\",\n \"@types/archiver\": \"^6.0.4\",\n \"esbuild\": \"^0.28.0\",\n \"typescript\": \"catalog:\"\n },\n \"engines\": {\n \"node\": \">=20.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import { Args, Command, Options } from '@effect/cli';\nimport { FileSystem } from '@effect/platform';\nimport type { AiGatewayBudgetInput, AiGatewayPolicyInput } from '@gigadrive/sdk';\nimport { Console, Effect, Option } from 'effect';\nimport { ApiRequestError, NotAuthenticatedError, ProjectLinkReadError, ProjectNotLinkedError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\n// ---------------------------------------------------------------------------\n// Shared options / helpers\n// ---------------------------------------------------------------------------\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Organization ID (defaults to the linked organization)'),\n Options.optional\n);\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Restrict to this application ID'),\n Options.optional\n);\n\nconst fromOption = Options.text('from').pipe(\n Options.withDescription('Include usage at or after this ISO 8601 timestamp'),\n Options.optional\n);\n\nconst toOption = Options.text('to').pipe(\n Options.withDescription('Include usage before or at this ISO 8601 timestamp'),\n Options.optional\n);\n\nconst fileOption = Options.text('file').pipe(\n Options.withAlias('f'),\n Options.withDescription('Path to a JSON file, or \"-\" for stdin (default: stdin)'),\n Options.optional\n);\n\n/** Resolve the organization ID from `--org` or the linked project. */\nconst resolveOrgId = (org: Option.Option<string>) =>\n Effect.gen(function* () {\n if (Option.isSome(org)) return org.value;\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.resolve(process.cwd());\n if (link.organizationId === undefined) {\n return yield* Effect.fail(\n new ProjectNotLinkedError({\n message: 'No organization is linked. Pass --org <id> or re-run \"gigadrive link\".',\n directory: process.cwd(),\n })\n );\n }\n return link.organizationId;\n });\n\n/** Read all of stdin as a UTF-8 string. */\nconst readStdin = Effect.async<string, ApiRequestError>((resume) => {\n let data = '';\n const stdin = process.stdin;\n stdin.setEncoding('utf8');\n const onData = (chunk: string) => {\n data += chunk;\n };\n const cleanup = () => {\n stdin.off('data', onData);\n stdin.off('end', onEnd);\n stdin.off('error', onError);\n };\n const onEnd = () => {\n cleanup();\n resume(Effect.succeed(data));\n };\n const onError = (err: Error) => {\n cleanup();\n resume(Effect.fail(new ApiRequestError({ message: `Failed to read stdin: ${err.message}` })));\n };\n stdin.on('data', onData);\n stdin.on('end', onEnd);\n stdin.on('error', onError);\n stdin.resume();\n});\n\n/** Read JSON from a file (or stdin when the path is omitted or `-`). */\nconst readJsonInput = (file: Option.Option<string>) =>\n Effect.gen(function* () {\n const path = Option.getOrUndefined(file);\n let raw: string;\n if (path === undefined || path === '-') {\n raw = yield* readStdin;\n } else {\n const fs = yield* FileSystem.FileSystem;\n raw = yield* fs\n .readFileString(path, 'utf8')\n .pipe(Effect.mapError((e) => new ApiRequestError({ message: `Failed to read ${path}: ${String(e)}` })));\n }\n return yield* Effect.try({\n try: () => JSON.parse(raw) as unknown,\n catch: () => new ApiRequestError({ message: 'Input is not valid JSON.' }),\n });\n });\n\n/** Shared error handlers for the governance commands — log, then re-fail so the process exits non-zero. */\nconst governanceErrorHandlers = {\n NotAuthenticatedError: (err: NotAuthenticatedError) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err: ApiRequestError) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err: ProjectNotLinkedError) =>\n Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err: ProjectLinkReadError) =>\n Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n};\n\n// ---------------------------------------------------------------------------\n// ai usage\n// ---------------------------------------------------------------------------\n\nconst usageSummaryCommand = Command.make(\n 'summary',\n { org: orgOption, app: appOption, from: fromOption, to: toOption },\n ({ org, app, from, to }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const summary = yield* apiClient.request((client) =>\n client.organizations.aiGateway.usage.summary(orgId, {\n applicationId: Option.getOrUndefined(app),\n from: Option.getOrUndefined(from),\n to: Option.getOrUndefined(to),\n })\n );\n yield* Console.log(JSON.stringify(summary, null, 2));\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst usageRequestsCommand = Command.make(\n 'requests',\n { org: orgOption, app: appOption, from: fromOption, to: toOption },\n ({ org, app, from, to }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const { items, total } = yield* apiClient.request((client) =>\n client.organizations.aiGateway.usage.requests(orgId, {\n applicationId: Option.getOrUndefined(app),\n from: Option.getOrUndefined(from),\n to: Option.getOrUndefined(to),\n })\n );\n if (items.length === 0) {\n yield* Console.log('No AI Gateway requests found.');\n return;\n }\n for (const e of items) {\n yield* Console.log(\n `${e.createdAt} ${e.modelRequested} ${e.status} ${e.totalTokens} tok ${e.billableCostMicros}µ$`\n );\n }\n yield* Console.log(`\\n${total} request(s).`);\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst outOption = Options.text('out').pipe(\n Options.withDescription('Write the CSV to this file instead of stdout'),\n Options.optional\n);\n\nconst usageExportCommand = Command.make(\n 'export',\n { org: orgOption, app: appOption, from: fromOption, to: toOption, out: outOption },\n ({ org, app, from, to, out }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const csv = yield* apiClient.request((client) =>\n client.organizations.aiGateway.usage.export(orgId, {\n applicationId: Option.getOrUndefined(app),\n from: Option.getOrUndefined(from),\n to: Option.getOrUndefined(to),\n })\n );\n const outPath = Option.getOrUndefined(out);\n if (outPath === undefined) {\n yield* Console.log(csv);\n } else {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .writeFileString(outPath, csv)\n .pipe(Effect.mapError((e) => new ApiRequestError({ message: `Failed to write ${outPath}: ${String(e)}` })));\n yield* Console.log(`Wrote ${outPath}.`);\n }\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst usageCommand = Command.make('usage', {}, () => Effect.void).pipe(\n Command.withSubcommands([usageSummaryCommand, usageRequestsCommand, usageExportCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai budgets\n// ---------------------------------------------------------------------------\n\nconst budgetsGetCommand = Command.make('get', { org: orgOption }, ({ org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const { items } = yield* apiClient.request((client) => client.organizations.aiGateway.budgets.list(orgId));\n yield* Console.log(JSON.stringify(items, null, 2));\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst budgetsSetCommand = Command.make('set', { org: orgOption, file: fileOption }, ({ org, file }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const parsed = yield* readJsonInput(file);\n const budgets = Array.isArray(parsed) ? parsed : (parsed as { budgets?: unknown }).budgets;\n if (!Array.isArray(budgets)) {\n return yield* Effect.fail(\n new ApiRequestError({\n message: 'Expected a JSON array of budgets, or an object of the form { \"budgets\": [...] }.',\n })\n );\n }\n const { items } = yield* apiClient.request((client) =>\n client.organizations.aiGateway.budgets.replace(orgId, budgets as AiGatewayBudgetInput[])\n );\n yield* Console.log(`Saved ${items.length} budget(s).`);\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst budgetsCommand = Command.make('budgets', {}, () => Effect.void).pipe(\n Command.withSubcommands([budgetsGetCommand, budgetsSetCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai policies\n// ---------------------------------------------------------------------------\n\nconst policiesGetCommand = Command.make('get', { org: orgOption, app: appOption }, ({ org, app }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const policy = yield* apiClient.request((client) =>\n client.organizations.aiGateway.policies.get(orgId, { applicationId: Option.getOrUndefined(app) })\n );\n yield* Console.log(policy === null ? 'No policy set.' : JSON.stringify(policy, null, 2));\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst policiesSetCommand = Command.make('set', { org: orgOption, file: fileOption }, ({ org, file }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const orgId = yield* resolveOrgId(org);\n const parsed = yield* readJsonInput(file);\n const policy = yield* apiClient.request((client) =>\n client.organizations.aiGateway.policies.put(orgId, parsed as AiGatewayPolicyInput)\n );\n yield* Console.log(`Policy saved${policy.applicationId ? ` for application ${policy.applicationId}` : ''}.`);\n }).pipe(Effect.catchTags(governanceErrorHandlers))\n);\n\nconst policiesCommand = Command.make('policies', {}, () => Effect.void).pipe(\n Command.withSubcommands([policiesGetCommand, policiesSetCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai models\n// ---------------------------------------------------------------------------\n\nconst inferenceErrorHandlers = {\n NotAuthenticatedError: (err: NotAuthenticatedError) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err: ApiRequestError) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n};\n\nconst modelsListCommand = Command.make('list', {}, () =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const { items } = yield* apiClient.request((client) => client.aiGateway.listModels());\n for (const m of items) {\n yield* Console.log(`${m.id} ${m.name} (ctx ${m.contextWindow})`);\n }\n }).pipe(Effect.catchTags(inferenceErrorHandlers))\n);\n\nconst modelIdArg = Args.text({ name: 'model-id' }).pipe(Args.withDescription('The model ID, e.g. openai/gpt-4o'));\n\nconst modelsGetCommand = Command.make('get', { modelId: modelIdArg }, ({ modelId }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const model = yield* apiClient.request((client) => client.aiGateway.getModel(modelId));\n yield* Console.log(JSON.stringify(model, null, 2));\n }).pipe(Effect.catchTags(inferenceErrorHandlers))\n);\n\nconst modelsCommand = Command.make('models', {}, () => Effect.void).pipe(\n Command.withSubcommands([modelsListCommand, modelsGetCommand])\n);\n\n// ---------------------------------------------------------------------------\n// ai chat\n// ---------------------------------------------------------------------------\n\nconst modelOption = Options.text('model').pipe(\n Options.withAlias('m'),\n Options.withDescription('The model ID to use, e.g. openai/gpt-4o')\n);\n\nconst streamOption = Options.boolean('stream').pipe(Options.withDescription('Stream the response token by token'));\n\nconst promptArg = Args.text({ name: 'prompt' }).pipe(\n Args.withDescription('The prompt text, or \"-\" to read from stdin')\n);\n\nconst chatCommand = Command.make(\n 'chat',\n { prompt: promptArg, model: modelOption, stream: streamOption },\n ({ prompt, model, stream }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const text = prompt === '-' ? yield* readStdin : prompt;\n const messages = [{ role: 'user', content: text }];\n\n if (stream) {\n const client = yield* apiClient.getClient;\n yield* Effect.tryPromise({\n try: async () => {\n for await (const chunk of client.aiGateway.chatCompletionsStream({ model, messages })) {\n process.stdout.write(chunk.choices[0]?.delta?.content ?? '');\n }\n process.stdout.write('\\n');\n },\n catch: (error) => new ApiRequestError({ message: error instanceof Error ? error.message : String(error) }),\n });\n return;\n }\n\n const response = yield* apiClient.request((client) => client.aiGateway.chatCompletions({ model, messages }));\n const content = response.choices[0]?.message.content;\n yield* Console.log(typeof content === 'string' ? content : JSON.stringify(content));\n }).pipe(Effect.catchTags(inferenceErrorHandlers))\n);\n\n// ---------------------------------------------------------------------------\n// ai (parent)\n// ---------------------------------------------------------------------------\n\nconst aiBase = Command.make('ai', {}, () => Effect.void);\n\n/** `gigadrive ai` — AI Gateway governance (usage, budgets, policies) and inference (models, chat). */\nexport const aiCommand = aiBase.pipe(\n Command.withSubcommands([usageCommand, budgetsCommand, policiesCommand, modelsCommand, chatCommand])\n);\n","import { Schema } from 'effect';\n\n// ---------------------------------------------------------------------------\n// Auth errors\n// ---------------------------------------------------------------------------\n\nexport class OAuthDiscoveryError extends Schema.TaggedError<OAuthDiscoveryError>()('OAuthDiscoveryError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class AuthStorageReadError extends Schema.TaggedError<AuthStorageReadError>()('AuthStorageReadError', {\n message: Schema.String,\n}) {}\n\nexport class AuthStorageWriteError extends Schema.TaggedError<AuthStorageWriteError>()('AuthStorageWriteError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class LoginFlowError extends Schema.TaggedError<LoginFlowError>()('LoginFlowError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class TokenExchangeError extends Schema.TaggedError<TokenExchangeError>()('TokenExchangeError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\n/** The device authorization request (RFC 8628 §3.1) failed. */\nexport class DeviceAuthorizationError extends Schema.TaggedError<DeviceAuthorizationError>()(\n 'DeviceAuthorizationError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n }\n) {}\n\n/** The user denied the device login on the verification page (`access_denied`). */\nexport class AuthorizationDeniedError extends Schema.TaggedError<AuthorizationDeniedError>()(\n 'AuthorizationDeniedError',\n {\n message: Schema.String,\n }\n) {}\n\n/** The device/user code expired before the user approved it (`expired_token`). */\nexport class DeviceCodeExpiredError extends Schema.TaggedError<DeviceCodeExpiredError>()('DeviceCodeExpiredError', {\n message: Schema.String,\n}) {}\n\nexport class TokenRefreshError extends Schema.TaggedError<TokenRefreshError>()('TokenRefreshError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\nexport class NotAuthenticatedError extends Schema.TaggedError<NotAuthenticatedError>()('NotAuthenticatedError', {\n message: Schema.String,\n}) {}\n\nexport class UserInfoFetchError extends Schema.TaggedError<UserInfoFetchError>()('UserInfoFetchError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\n// ---------------------------------------------------------------------------\n// API errors\n// ---------------------------------------------------------------------------\n\n/** A request to the Gigadrive Network API failed. Wraps the SDK's `ApiError`. */\nexport class ApiRequestError extends Schema.TaggedError<ApiRequestError>()('ApiRequestError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n code: Schema.optional(Schema.String),\n /** Finer-grained reason next to `code`, for example `daily_add_limit`. */\n reason: Schema.optional(Schema.String),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Command input errors\n// ---------------------------------------------------------------------------\n\n/** An environment-variable assignment was not in `KEY=VALUE` form. */\nexport class InvalidEnvVarFormatError extends Schema.TaggedError<InvalidEnvVarFormatError>()(\n 'InvalidEnvVarFormatError',\n {\n message: Schema.String,\n }\n) {}\n\n/** No environment variable matched the requested key or ID. */\nexport class EnvVarNotFoundError extends Schema.TaggedError<EnvVarNotFoundError>()('EnvVarNotFoundError', {\n message: Schema.String,\n}) {}\n\n/** No custom domain of the application matched the requested hostname or ID. */\nexport class DomainNotFoundError extends Schema.TaggedError<DomainNotFoundError>()('DomainNotFoundError', {\n message: Schema.String,\n}) {}\n\n/** `--wait` gave up: the domain did not start serving in time, or stopped in a state that needs action. */\nexport class DomainWaitError extends Schema.TaggedError<DomainWaitError>()('DomainWaitError', {\n message: Schema.String,\n state: Schema.String,\n}) {}\n\n/** The domain command's flags contradict each other or are out of range. */\nexport class InvalidDomainOptionsError extends Schema.TaggedError<InvalidDomainOptionsError>()(\n 'InvalidDomainOptionsError',\n { message: Schema.String }\n) {}\n\n/** A destructive command needs confirmation, but there is no terminal to ask on and `--yes` was not passed. */\nexport class ConfirmationRequiredError extends Schema.TaggedError<ConfirmationRequiredError>()(\n 'ConfirmationRequiredError',\n { message: Schema.String }\n) {}\n\n/** No organization was given and the linked project does not name one. */\nexport class OrganizationRequiredError extends Schema.TaggedError<OrganizationRequiredError>()(\n 'OrganizationRequiredError',\n { message: Schema.String }\n) {}\n\n/** The actor has no applications to link. */\nexport class NoApplicationsFoundError extends Schema.TaggedError<NoApplicationsFoundError>()(\n 'NoApplicationsFoundError',\n {\n message: Schema.String,\n }\n) {}\n\n/** The requested application ID was not among the actor's applications. */\nexport class ApplicationNotFoundError extends Schema.TaggedError<ApplicationNotFoundError>()(\n 'ApplicationNotFoundError',\n {\n message: Schema.String,\n }\n) {}\n\n/** The actor has no organization available for automatic application creation. */\nexport class NoOrganizationsFoundError extends Schema.TaggedError<NoOrganizationsFoundError>()(\n 'NoOrganizationsFoundError',\n {\n message: Schema.String,\n }\n) {}\n\n// ---------------------------------------------------------------------------\n// Env file / local credentials errors\n// ---------------------------------------------------------------------------\n\n/** Failed to read a local `.env` (or `.gitignore`) file. */\nexport class EnvFileReadError extends Schema.TaggedError<EnvFileReadError>()('EnvFileReadError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n/** Failed to write a local `.env` (or `.gitignore`) file. */\nexport class EnvFileWriteError extends Schema.TaggedError<EnvFileWriteError>()('EnvFileWriteError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n/** Failed to read `~/.gigadrive/dev-keys.json`. */\nexport class DevCredentialsStoreReadError extends Schema.TaggedError<DevCredentialsStoreReadError>()(\n 'DevCredentialsStoreReadError',\n {\n message: Schema.String,\n }\n) {}\n\n/** Failed to write `~/.gigadrive/dev-keys.json`. */\nexport class DevCredentialsStoreWriteError extends Schema.TaggedError<DevCredentialsStoreWriteError>()(\n 'DevCredentialsStoreWriteError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n }\n) {}\n\n// ---------------------------------------------------------------------------\n// Project errors\n// ---------------------------------------------------------------------------\n\nexport class ConfigNotFoundError extends Schema.TaggedError<ConfigNotFoundError>()('ConfigNotFoundError', {\n message: Schema.String,\n directory: Schema.String,\n}) {}\n\n/** The project directory has no `.gigadrive/project.json` link. */\nexport class ProjectNotLinkedError extends Schema.TaggedError<ProjectNotLinkedError>()('ProjectNotLinkedError', {\n message: Schema.String,\n directory: Schema.String,\n}) {}\n\n/** Failed to read or parse `.gigadrive/project.json`. */\nexport class ProjectLinkReadError extends Schema.TaggedError<ProjectLinkReadError>()('ProjectLinkReadError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n/** Failed to write `.gigadrive/project.json`. */\nexport class ProjectLinkWriteError extends Schema.TaggedError<ProjectLinkWriteError>()('ProjectLinkWriteError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class ConfigParseError extends Schema.TaggedError<ConfigParseError>()('ConfigParseError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class ConfigValidationError extends Schema.TaggedError<ConfigValidationError>()('ConfigValidationError', {\n message: Schema.String,\n errors: Schema.Array(Schema.String),\n}) {}\n\nexport class PackageJsonNotFoundError extends Schema.TaggedError<PackageJsonNotFoundError>()(\n 'PackageJsonNotFoundError',\n {\n message: Schema.String,\n directory: Schema.String,\n }\n) {}\n\nexport class PackageJsonParseError extends Schema.TaggedError<PackageJsonParseError>()('PackageJsonParseError', {\n message: Schema.String,\n directory: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class BuildScriptNotFoundError extends Schema.TaggedError<BuildScriptNotFoundError>()(\n 'BuildScriptNotFoundError',\n {\n message: Schema.String,\n }\n) {}\n\nexport class PackageManagerNotFoundError extends Schema.TaggedError<PackageManagerNotFoundError>()(\n 'PackageManagerNotFoundError',\n {\n message: Schema.String,\n directory: Schema.String,\n }\n) {}\n\n// ---------------------------------------------------------------------------\n// Build errors\n// ---------------------------------------------------------------------------\n\nexport class ExecError extends Schema.TaggedError<ExecError>()('ExecError', {\n message: Schema.String,\n command: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Deployment errors\n// ---------------------------------------------------------------------------\n\nexport class DeploymentCreateError extends Schema.TaggedError<DeploymentCreateError>()('DeploymentCreateError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\nexport class UploadStartError extends Schema.TaggedError<UploadStartError>()('UploadStartError', {\n message: Schema.String,\n statusCode: Schema.optional(Schema.Number),\n}) {}\n\nexport class PresignedUrlError extends Schema.TaggedError<PresignedUrlError>()('PresignedUrlError', {\n message: Schema.String,\n partNumber: Schema.Number,\n}) {}\n\nexport class UploadPartError extends Schema.TaggedError<UploadPartError>()('UploadPartError', {\n message: Schema.String,\n partNumber: Schema.Number,\n}) {}\n\nexport class UploadCompleteError extends Schema.TaggedError<UploadCompleteError>()('UploadCompleteError', {\n message: Schema.String,\n}) {}\n\nexport class DeploymentStatusError extends Schema.TaggedError<DeploymentStatusError>()('DeploymentStatusError', {\n message: Schema.String,\n}) {}\n\nexport class DeploymentLogsFetchError extends Schema.TaggedError<DeploymentLogsFetchError>()(\n 'DeploymentLogsFetchError',\n {\n message: Schema.String,\n }\n) {}\n\nexport class DeploymentHostnamesFetchError extends Schema.TaggedError<DeploymentHostnamesFetchError>()(\n 'DeploymentHostnamesFetchError',\n {\n message: Schema.String,\n }\n) {}\n\nexport class ArchiveCreateError extends Schema.TaggedError<ArchiveCreateError>()('ArchiveCreateError', {\n message: Schema.String,\n cause: Schema.optional(Schema.String),\n}) {}\n\nexport class DeploymentAuthError extends Schema.TaggedError<DeploymentAuthError>()('DeploymentAuthError', {\n message: Schema.String,\n}) {}\n\nexport class DeploymentFailedError extends Schema.TaggedError<DeploymentFailedError>()('DeploymentFailedError', {\n message: Schema.String,\n}) {}\n","import { ApiError, GigadriveClient } from '@gigadrive/sdk';\nimport { Config, Effect, Option, Redacted } from 'effect';\nimport { ApiRequestError } from '../errors';\nimport { AuthService } from './auth';\n\n// ---------------------------------------------------------------------------\n// ApiClientService\n//\n// A single, shared factory for the `@gigadrive/sdk` client. Every command that\n// talks to the Gigadrive Network API obtains its client here so authentication\n// (a fresh access token from AuthService) and the base URL are configured in\n// exactly one place.\n// ---------------------------------------------------------------------------\n\nconst ApiBaseUrl = Config.string('GIGADRIVE_API_BASE_URL').pipe(Config.withDefault('https://api.gigadrive.network'));\nconst ServiceCredentials = Config.all({\n bearerToken: Config.redacted('GIGADRIVE_BEARER_TOKEN').pipe(Config.option),\n clientId: Config.string('GIGADRIVE_CLIENT_ID').pipe(Config.option),\n clientSecret: Config.redacted('GIGADRIVE_CLIENT_SECRET').pipe(Config.option),\n refreshToken: Config.redacted('GIGADRIVE_REFRESH_TOKEN').pipe(Config.option),\n});\n\n/** Map any error thrown by an SDK call into a tagged {@link ApiRequestError}. */\nconst toApiRequestError = (error: unknown): ApiRequestError => {\n if (error instanceof ApiError) {\n return new ApiRequestError({\n message: error.message,\n statusCode: error.status,\n code: error.code,\n reason: error.reason,\n });\n }\n return new ApiRequestError({ message: error instanceof Error ? error.message : String(error) });\n};\n\nexport class ApiClientService extends Effect.Service<ApiClientService>()('ApiClientService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const baseUrl = yield* ApiBaseUrl;\n const serviceCredentials = yield* ServiceCredentials;\n const authService = yield* AuthService;\n const hasServiceCredentials =\n Option.isSome(serviceCredentials.bearerToken) ||\n Option.isSome(serviceCredentials.clientId) ||\n Option.isSome(serviceCredentials.clientSecret) ||\n Option.isSome(serviceCredentials.refreshToken);\n\n /**\n * Build a `GigadriveClient` authenticated with a fresh access token.\n * Fails with `NotAuthenticatedError` when the user is not logged in.\n */\n const getClient = hasServiceCredentials\n ? Effect.succeed(\n new GigadriveClient({\n baseUrl,\n bearerToken: Option.map(serviceCredentials.bearerToken, Redacted.value).pipe(Option.getOrUndefined),\n clientId: Option.getOrUndefined(serviceCredentials.clientId),\n clientSecret: Option.map(serviceCredentials.clientSecret, Redacted.value).pipe(Option.getOrUndefined),\n refreshToken: Option.map(serviceCredentials.refreshToken, Redacted.value).pipe(Option.getOrUndefined),\n })\n )\n : Effect.gen(function* () {\n const token = yield* authService.getAccessToken;\n return new GigadriveClient({ bearerToken: token, baseUrl });\n });\n\n /**\n * Run an SDK call against an authenticated client, translating rejected\n * promises into a tagged {@link ApiRequestError}. This is the ergonomic\n * entry point for command handlers.\n *\n * @example\n * ```ts\n * const { items } = yield* apiClient.request((client) => client.applications.list());\n * ```\n */\n const request = <A>(f: (client: GigadriveClient) => Promise<A>) =>\n Effect.gen(function* () {\n const client = yield* getClient;\n return yield* Effect.tryPromise({\n try: () => f(client),\n catch: toApiRequestError,\n });\n });\n\n return { getClient, request };\n }),\n}) {}\n","import { Console, Duration, Effect, Option, Schema } from 'effect';\nimport process from 'node:process';\nimport open from 'open';\nimport { DeviceAuthorizationResponse, type OAuthClientConfig, type StoredAuthData } from '../domain';\nimport {\n AuthorizationDeniedError,\n DeviceAuthorizationError,\n DeviceCodeExpiredError,\n LoginFlowError,\n NotAuthenticatedError,\n TokenExchangeError,\n TokenRefreshError,\n UserInfoFetchError,\n} from '../errors';\nimport { writeClipboard } from '../lib/clipboard';\nimport { AuthStorageService } from './auth-storage';\nimport { OAuthConfigService } from './oauth-config';\n\n/** Grant type identifier for the OAuth 2.0 Device Authorization Grant (RFC 8628). */\nconst DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';\n\n/** Fallback poll interval (seconds) when the provider omits `interval`. */\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\n\n/**\n * Per-request timeout (seconds) for the device-authorization request and each\n * token poll. `fetch` has no default timeout, so without this a hung connection\n * would stall the poll loop and the RFC 8628 `expires_in` deadline (which is only\n * checked between requests) would never be enforced.\n */\nconst REQUEST_TIMEOUT_SECONDS = 30;\n\n// ---------------------------------------------------------------------------\n// AuthService\n// ---------------------------------------------------------------------------\n\nexport class AuthService extends Effect.Service<AuthService>()('AuthService', {\n accessors: true,\n dependencies: [OAuthConfigService.Default, AuthStorageService.Default],\n\n effect: Effect.gen(function* () {\n const oauthConfig = yield* OAuthConfigService;\n const storage = yield* AuthStorageService;\n\n // In-memory token cache\n let accessToken: string | null = null;\n let tokenExpirationTime = 0;\n\n const logout = Effect.gen(function* () {\n accessToken = null;\n tokenExpirationTime = 0;\n yield* storage.remove;\n yield* Effect.log('Logged out');\n });\n\n // Step 1 (RFC 8628 §3.1): request a device_code / user_code pair.\n const requestDeviceAuthorization = (config: OAuthClientConfig) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: (signal) =>\n fetch(config.deviceAuthorizeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: config.clientId, scope: config.scope }).toString(),\n signal,\n }),\n catch: (error) =>\n new DeviceAuthorizationError({\n message: `Device authorization request failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n if (!response.ok) {\n const body = yield* Effect.tryPromise({\n try: () => response.text(),\n catch: () =>\n new DeviceAuthorizationError({ message: 'Failed to read device authorization error response' }),\n });\n return yield* Effect.fail(\n new DeviceAuthorizationError({\n message: `Device authorization failed: ${response.status} ${response.statusText} - ${body}`,\n })\n );\n }\n\n const json = yield* Effect.tryPromise({\n try: () => response.json(),\n catch: () => new DeviceAuthorizationError({ message: 'Failed to parse device authorization response' }),\n });\n\n return yield* Schema.decodeUnknown(DeviceAuthorizationResponse)(json).pipe(\n Effect.mapError(\n () => new DeviceAuthorizationError({ message: 'Invalid device authorization response schema' })\n )\n );\n }).pipe(\n Effect.timeoutFail({\n duration: Duration.seconds(REQUEST_TIMEOUT_SECONDS),\n onTimeout: () => new DeviceAuthorizationError({ message: 'Device authorization request timed out' }),\n })\n );\n\n // A single poll of the token endpoint (RFC 8628 §3.4). Translates the RFC 8628\n // §3.5 poll errors into control-flow values; any other failure is fatal.\n const pollTokenOnce = (config: OAuthClientConfig, deviceCode: string) =>\n Effect.gen(function* () {\n const response = yield* Effect.tryPromise({\n try: (signal) =>\n fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: DEVICE_CODE_GRANT_TYPE,\n client_id: config.clientId,\n device_code: deviceCode,\n }).toString(),\n signal,\n }),\n catch: (error) =>\n new TokenExchangeError({\n message: `Token poll request failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n if (response.ok) {\n const tokens = yield* Effect.tryPromise({\n try: () =>\n response.json() as Promise<{ access_token: string; refresh_token?: string; expires_in?: number }>,\n catch: () => new TokenExchangeError({ message: 'Failed to parse token response' }),\n });\n return { kind: 'tokens', tokens } as const;\n }\n\n const errorBody = yield* Effect.tryPromise({\n try: () => response.json() as Promise<{ error?: string }>,\n catch: () => new TokenExchangeError({ message: 'Failed to parse token poll error response' }),\n });\n\n switch (errorBody.error) {\n case 'authorization_pending':\n return { kind: 'pending' } as const;\n case 'slow_down':\n return { kind: 'slow_down' } as const;\n case 'access_denied':\n return { kind: 'denied' } as const;\n case 'expired_token':\n return { kind: 'expired' } as const;\n default:\n return yield* Effect.fail(\n new TokenExchangeError({\n message: `Token poll failed: ${response.status} ${response.statusText} - ${errorBody.error ?? 'unknown_error'}`,\n statusCode: response.status,\n })\n );\n }\n });\n\n // Step 2 (RFC 8628 §3.4–3.5): poll until approval, denial, or expiry.\n const pollForToken = (config: OAuthClientConfig, device: DeviceAuthorizationResponse) =>\n Effect.gen(function* () {\n const deadline = Date.now() + device.expires_in * 1000;\n let interval = device.interval ?? DEFAULT_POLL_INTERVAL_SECONDS;\n\n while (true) {\n yield* Effect.sleep(Duration.seconds(interval));\n\n if (Date.now() >= deadline) {\n return yield* Effect.fail(\n new DeviceCodeExpiredError({\n message: 'The login code expired before it was approved. Please run `gigadrive login` again.',\n })\n );\n }\n\n const result = yield* pollTokenOnce(config, device.device_code).pipe(\n // A hung poll must not stall the loop: on timeout treat it as pending so\n // the next iteration re-checks the expiry deadline.\n Effect.timeoutTo({\n duration: Duration.seconds(REQUEST_TIMEOUT_SECONDS),\n onSuccess: (value) => value,\n onTimeout: () => ({ kind: 'pending' }) as const,\n })\n );\n switch (result.kind) {\n case 'tokens':\n return result.tokens;\n case 'pending':\n continue;\n case 'slow_down':\n // RFC 8628 §3.5: back off by 5 seconds on slow_down.\n interval += 5;\n continue;\n case 'denied':\n return yield* Effect.fail(new AuthorizationDeniedError({ message: 'The login request was denied.' }));\n case 'expired':\n return yield* Effect.fail(\n new DeviceCodeExpiredError({\n message: 'The login code expired before it was approved. Please run `gigadrive login` again.',\n })\n );\n }\n }\n });\n\n // Runs alongside polling in a TTY: lets the user press \"c\" to copy the URL\n // (Claude-Code style) and Ctrl+C to cancel. Never completes on its own — the\n // poll loop wins the race and interrupts this, restoring the terminal.\n const watchCopyKey = (url: string) =>\n Effect.async<never, LoginFlowError>((resume) => {\n const stdin = process.stdin;\n if (!stdin.isTTY) {\n // Not interactive: nothing to listen for; wait to be interrupted.\n return;\n }\n\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n const onData = (key: string) => {\n if (key === 'c' || key === 'C') {\n writeClipboard(url);\n // runSync inside a raw Node callback — a deliberate, localized exception.\n Console.log('Copied the login URL to your clipboard.').pipe(Effect.runSync);\n } else if (key === '\\u0003') {\n // Ctrl+C: raw mode suppresses SIGINT, so handle cancellation explicitly.\n resume(Effect.fail(new LoginFlowError({ message: 'Login canceled.' })));\n }\n };\n\n stdin.on('data', onData);\n\n return Effect.sync(() => {\n stdin.off('data', onData);\n if (stdin.isTTY) stdin.setRawMode(false);\n stdin.pause();\n });\n });\n\n const login = Effect.gen(function* () {\n yield* logout;\n\n const config = yield* oauthConfig.getConfig;\n const device = yield* requestDeviceAuthorization(config);\n\n const verificationUri = device.verification_uri;\n const verificationUriComplete = device.verification_uri_complete ?? verificationUri;\n const interactive = process.stdin.isTTY === true;\n\n yield* Console.log(\n `\\nTo sign in, visit:\\n\\n ${verificationUri}\\n\\nand enter the code:\\n\\n ${device.user_code}\\n`\n );\n\n if (interactive) {\n // Best-effort: the URL is printed above regardless. Route through the Effect\n // runtime so a spawn/DISPLAY failure can't become an unhandled rejection.\n yield* Effect.tryPromise(() => open(verificationUriComplete)).pipe(Effect.catchAll(() => Effect.void));\n yield* Console.log('We tried to open your browser automatically. If it did not open, use the URL above.');\n yield* Console.log('Press \"c\" to copy the URL to your clipboard, or Ctrl+C to cancel.');\n }\n\n yield* Console.log('\\nWaiting for you to approve the login…');\n\n const poll = pollForToken(config, device);\n // `watchCopyKey` never completes on its own, so use `raceFirst` (settles on the\n // first effect to finish, success or failure) — plain `race` waits for a success\n // and would hang here when the poll fails (e.g. denied/expired).\n const tokens = yield* interactive ? poll.pipe(Effect.raceFirst(watchCopyKey(verificationUriComplete))) : poll;\n\n if (!tokens.refresh_token) {\n return yield* Effect.fail(\n new TokenExchangeError({ message: 'No refresh token received from identity provider' })\n );\n }\n\n accessToken = tokens.access_token;\n tokenExpirationTime = Date.now() + (tokens.expires_in || 3600) * 1000;\n\n yield* storage.save({\n refreshToken: tokens.refresh_token,\n accessToken,\n tokenExpirationTime,\n });\n\n yield* Effect.log('Login successful');\n return true as const;\n });\n\n const refreshAccessToken: Effect.Effect<true, TokenRefreshError> = Effect.gen(function* () {\n const stored: Option.Option<StoredAuthData> = yield* storage.load.pipe(\n Effect.catchTag('AuthStorageReadError', (err) => Effect.fail(new TokenRefreshError({ message: err.message })))\n );\n const config = yield* oauthConfig.getConfig.pipe(\n Effect.catchTag('OAuthDiscoveryError', (err) => Effect.fail(new TokenRefreshError({ message: err.message })))\n );\n\n const authData: StoredAuthData = yield* Option.match(stored, {\n onNone: () => Effect.fail(new TokenRefreshError({ message: 'No refresh token available. Please log in.' })),\n onSome: (data: StoredAuthData) =>\n data.refreshToken\n ? Effect.succeed(data)\n : Effect.fail(new TokenRefreshError({ message: 'No refresh token available. Please log in.' })),\n });\n\n const response = yield* Effect.tryPromise({\n try: () =>\n fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: authData.refreshToken,\n }).toString(),\n }),\n catch: (error) =>\n new TokenRefreshError({\n message: `Token refresh request failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n if (!response.ok) {\n if (response.status === 400) {\n yield* logout.pipe(Effect.catchAll(() => Effect.void));\n return yield* Effect.fail(\n new TokenRefreshError({\n message: 'Refresh token is invalid or expired. Please log in again.',\n statusCode: response.status,\n })\n );\n }\n const body = yield* Effect.tryPromise({\n try: () => response.text(),\n catch: () => new TokenRefreshError({ message: 'Failed to read refresh error response' }),\n });\n return yield* Effect.fail(\n new TokenRefreshError({\n message: `Token refresh failed: ${response.status} ${response.statusText} - ${body}`,\n statusCode: response.status,\n })\n );\n }\n\n const tokens = yield* Effect.tryPromise({\n try: () => response.json() as Promise<{ access_token: string; refresh_token?: string; expires_in?: number }>,\n catch: () => new TokenRefreshError({ message: 'Failed to parse token refresh response' }),\n });\n\n accessToken = tokens.access_token;\n tokenExpirationTime = Date.now() + (tokens.expires_in || 3600) * 1000;\n const newRefreshToken = tokens.refresh_token || authData.refreshToken;\n\n yield* storage\n .save({\n refreshToken: newRefreshToken,\n accessToken,\n tokenExpirationTime,\n })\n .pipe(Effect.catchAll(() => Effect.void));\n\n yield* Effect.log('Access token refreshed successfully');\n return true as const;\n });\n\n const getAccessToken = Effect.gen(function* () {\n // Check in-memory cache\n if (accessToken && Date.now() < tokenExpirationTime) {\n return accessToken;\n }\n\n // Try to load from storage\n const stored: Option.Option<StoredAuthData> = yield* storage.load.pipe(\n Effect.catchAll(() => Effect.succeed(Option.none<StoredAuthData>()))\n );\n Option.match(stored, {\n onNone: () => {},\n onSome: (data: StoredAuthData) => {\n if (data.accessToken && data.tokenExpirationTime && Date.now() < data.tokenExpirationTime) {\n accessToken = data.accessToken;\n tokenExpirationTime = data.tokenExpirationTime;\n }\n },\n });\n\n if (accessToken && Date.now() < tokenExpirationTime) {\n return accessToken;\n }\n\n // Try refresh\n yield* Effect.log('Access token expired or not available. Attempting to refresh...');\n yield* refreshAccessToken.pipe(\n Effect.catchTag('TokenRefreshError', (err) => Effect.fail(new NotAuthenticatedError({ message: err.message })))\n );\n\n if (!accessToken) {\n return yield* Effect.fail(\n new NotAuthenticatedError({ message: 'No valid access token available. Please log in first.' })\n );\n }\n\n return accessToken;\n });\n\n const getUserInfo = Effect.gen(function* () {\n const config = yield* oauthConfig.getConfig;\n const token = yield* getAccessToken;\n\n const fetchUserInfo = (t: string) =>\n Effect.tryPromise({\n try: () =>\n fetch(config.userinfoUrl, {\n headers: {\n Authorization: `Bearer ${t}`,\n Accept: 'application/json',\n },\n }),\n catch: (error) =>\n new UserInfoFetchError({\n message: `Failed to fetch user info: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n let response = yield* fetchUserInfo(token);\n\n // Retry once on 401/403\n if (response.status === 401 || response.status === 403) {\n yield* refreshAccessToken.pipe(\n Effect.catchTag('TokenRefreshError', (err) => Effect.fail(new UserInfoFetchError({ message: err.message })))\n );\n if (!accessToken) {\n return yield* Effect.fail(new UserInfoFetchError({ message: 'Token refresh failed' }));\n }\n response = yield* fetchUserInfo(accessToken);\n }\n\n if (!response.ok) {\n const body = yield* Effect.tryPromise({\n try: () => response.text(),\n catch: () => new UserInfoFetchError({ message: 'Failed to read user info error response' }),\n });\n return yield* Effect.fail(\n new UserInfoFetchError({\n message: `Failed to fetch user info: ${response.status} ${response.statusText}${body ? ` - ${body}` : ''}`,\n statusCode: response.status,\n })\n );\n }\n\n const data = yield* Effect.tryPromise({\n try: () => response.json() as Promise<Record<string, unknown>>,\n catch: () => new UserInfoFetchError({ message: 'Failed to parse user info response' }),\n });\n\n return data;\n });\n\n const inferUserName = (info: Record<string, unknown>): string => {\n const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.trim() !== '';\n\n const name = info.name;\n const givenName = info.given_name;\n const familyName = info.family_name;\n const preferredUsername = info.preferred_username;\n const email = info.email;\n\n return (\n (isNonEmptyString(name) && name) ||\n (isNonEmptyString(givenName) && isNonEmptyString(familyName) ? `${givenName} ${familyName}` : undefined) ||\n (isNonEmptyString(preferredUsername) && preferredUsername) ||\n (isNonEmptyString(email) && email) ||\n 'your account'\n );\n };\n\n return { login, logout, getAccessToken, getUserInfo, refreshAccessToken, inferUserName };\n }),\n}) {}\n","import { Schema } from 'effect';\n\n// ---------------------------------------------------------------------------\n// Re-export shared types from SDK\n// ---------------------------------------------------------------------------\n\nexport type { DeploymentLog, DeploymentLogPage, DeploymentLogType, DeploymentStatus } from '@gigadrive/sdk';\n\n// ---------------------------------------------------------------------------\n// Branded IDs (CLI-specific, for type safety within Effect pipelines)\n// ---------------------------------------------------------------------------\n\nexport const DeploymentId = Schema.String.pipe(Schema.brand('@Gigadrive/DeploymentId'));\nexport type DeploymentId = Schema.Schema.Type<typeof DeploymentId>;\n\nexport const ApplicationId = Schema.String.pipe(Schema.brand('@Gigadrive/ApplicationId'));\nexport type ApplicationId = Schema.Schema.Type<typeof ApplicationId>;\n\nexport const UploadId = Schema.String.pipe(Schema.brand('@Gigadrive/UploadId'));\nexport type UploadId = Schema.Schema.Type<typeof UploadId>;\n\n// ---------------------------------------------------------------------------\n// CLI-specific domain schemas\n// ---------------------------------------------------------------------------\n\nexport const PackageManager = Schema.Literal('npm', 'yarn', 'pnpm', 'bun');\nexport type PackageManager = Schema.Schema.Type<typeof PackageManager>;\n\n// ---------------------------------------------------------------------------\n// OAuth schemas (CLI-specific, for interactive login flow)\n// ---------------------------------------------------------------------------\n\nexport const OAuthTokens = Schema.Struct({\n access_token: Schema.String,\n refresh_token: Schema.optional(Schema.String),\n expires_in: Schema.optional(Schema.Number),\n token_type: Schema.optional(Schema.String),\n});\nexport type OAuthTokens = Schema.Schema.Type<typeof OAuthTokens>;\n\nexport const OAuthClientConfig = Schema.Struct({\n clientId: Schema.String,\n issuer: Schema.String,\n authorizeUrl: Schema.String,\n tokenUrl: Schema.String,\n deviceAuthorizeUrl: Schema.String,\n scope: Schema.String,\n userinfoUrl: Schema.String,\n});\nexport type OAuthClientConfig = Schema.Schema.Type<typeof OAuthClientConfig>;\n\n/**\n * Response from the OAuth 2.0 Device Authorization Endpoint (RFC 8628 §3.2).\n * `verification_uri_complete` and `interval` are RECOMMENDED/OPTIONAL per the spec.\n */\nexport const DeviceAuthorizationResponse = Schema.Struct({\n device_code: Schema.String,\n user_code: Schema.String,\n verification_uri: Schema.String,\n verification_uri_complete: Schema.optional(Schema.String),\n expires_in: Schema.Number,\n interval: Schema.optional(Schema.Number),\n});\nexport type DeviceAuthorizationResponse = Schema.Schema.Type<typeof DeviceAuthorizationResponse>;\n\nexport const StoredAuthData = Schema.Struct({\n refreshToken: Schema.String,\n accessToken: Schema.optional(Schema.String),\n tokenExpirationTime: Schema.optional(Schema.Number),\n});\nexport type StoredAuthData = Schema.Schema.Type<typeof StoredAuthData>;\n\n// ---------------------------------------------------------------------------\n// Project link (.gigadrive/project.json) — links a working directory to an app\n// ---------------------------------------------------------------------------\n\nexport const ProjectLink = Schema.Struct({\n applicationId: Schema.String,\n organizationId: Schema.optional(Schema.String),\n});\nexport type ProjectLink = Schema.Schema.Type<typeof ProjectLink>;\n\n// ---------------------------------------------------------------------------\n// Local dev API-key store (~/.gigadrive/dev-keys.json)\n// Maps an application ID to the ID of the API key the CLI provisioned for local\n// development, so re-runs can rotate/revoke the previous key instead of piling\n// up. Only the key ID is stored — never the secret (which is unrecoverable).\n// ---------------------------------------------------------------------------\n\nexport const DevKeyEntry = Schema.Struct({\n apiKeyId: Schema.String,\n});\nexport type DevKeyEntry = Schema.Schema.Type<typeof DevKeyEntry>;\n\nexport const DevKeyStore = Schema.Record({ key: Schema.String, value: DevKeyEntry });\nexport type DevKeyStore = Schema.Schema.Type<typeof DevKeyStore>;\n","import { spawn } from 'node:child_process';\nimport process from 'node:process';\n\ninterface ClipboardCommand {\n cmd: string;\n args: string[];\n}\n\n/**\n * Ordered list of clipboard commands to try for the current platform. On Linux\n * we try Wayland first, then the common X11 tools; the first one that spawns\n * successfully wins.\n */\nconst clipboardCandidates = (): ClipboardCommand[] => {\n switch (process.platform) {\n case 'darwin':\n return [{ cmd: 'pbcopy', args: [] }];\n case 'win32':\n return [{ cmd: 'clip', args: [] }];\n default:\n return [\n { cmd: 'wl-copy', args: [] },\n { cmd: 'xclip', args: ['-selection', 'clipboard'] },\n { cmd: 'xsel', args: ['--clipboard', '--input'] },\n ];\n }\n};\n\n/**\n * Best-effort copy of `text` to the OS clipboard by spawning the platform's\n * clipboard utility (`pbcopy` / `clip` / `wl-copy` / `xclip` / `xsel`). Never\n * throws: if no utility is available the call is silently a no-op, so callers\n * can offer \"press c to copy\" without a hard dependency.\n */\nexport function writeClipboard(text: string): void {\n const candidates = clipboardCandidates();\n\n const tryNext = (index: number): void => {\n if (index >= candidates.length) return;\n const { cmd, args } = candidates[index];\n\n let proc;\n try {\n proc = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] });\n } catch {\n tryNext(index + 1);\n return;\n }\n\n // ENOENT (utility not installed) surfaces as an async 'error' event.\n proc.on('error', () => tryNext(index + 1));\n proc.stdin?.on('error', () => {\n /* ignore broken pipe */\n });\n proc.stdin?.end(text);\n };\n\n tryNext(0);\n}\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option, Schema } from 'effect';\nimport * as os from 'node:os';\nimport type { StoredAuthData } from '../domain';\nimport { StoredAuthData as StoredAuthDataSchema } from '../domain';\nimport { AuthStorageReadError, AuthStorageWriteError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// AuthStorageService\n// ---------------------------------------------------------------------------\n\nexport class AuthStorageService extends Effect.Service<AuthStorageService>()('AuthStorageService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const homeDir = os.homedir();\n const authDir = pathService.join(homeDir, '.gigadrive');\n const authFile = pathService.join(authDir, 'auth.json');\n\n const ensureDirectory = Effect.gen(function* () {\n yield* fs.makeDirectory(authDir, { recursive: true }).pipe(\n Effect.mapError(\n (error) =>\n new AuthStorageWriteError({\n message: 'Failed to create auth directory',\n cause: String(error),\n })\n )\n );\n yield* fs.chmod(authDir, 0o700).pipe(\n Effect.mapError(\n (error) =>\n new AuthStorageWriteError({\n message: 'Failed to set auth directory permissions',\n cause: String(error),\n })\n )\n );\n });\n\n const load = Effect.gen(function* () {\n const exists = yield* fs\n .exists(authFile)\n .pipe(Effect.mapError(() => new AuthStorageReadError({ message: 'Failed to check auth file existence' })));\n if (!exists) return Option.none<StoredAuthData>();\n\n const data = yield* fs\n .readFileString(authFile, 'utf8')\n .pipe(Effect.mapError(() => new AuthStorageReadError({ message: 'Failed to read auth file' })));\n\n const json = yield* Effect.try({\n try: () => JSON.parse(data) as unknown,\n catch: () => new AuthStorageReadError({ message: 'Auth file contains invalid JSON' }),\n });\n\n const authData = yield* Schema.decodeUnknown(StoredAuthDataSchema)(json).pipe(\n Effect.mapError(() => new AuthStorageReadError({ message: 'Auth file has invalid schema' }))\n );\n\n return Option.some(authData);\n });\n\n const save = Effect.fn('AuthStorageService.save')(function* (authData: StoredAuthData) {\n yield* ensureDirectory;\n yield* fs.writeFileString(authFile, JSON.stringify(authData, null, 2), { mode: 0o600 }).pipe(\n Effect.mapError(\n (error) =>\n new AuthStorageWriteError({\n message: 'Failed to write auth file',\n cause: String(error),\n })\n )\n );\n yield* Effect.log('Auth data saved to local storage');\n });\n\n const remove = Effect.gen(function* () {\n yield* fs.remove(authFile).pipe(\n Effect.mapError((error) => {\n const cause = error instanceof Error ? error : (error as { error?: Error }).error;\n const code = cause && typeof cause === 'object' && 'code' in cause ? (cause as { code: string }).code : '';\n return { isNotFound: code === 'ENOENT' || String(error).includes('ENOENT'), original: error };\n }),\n Effect.catchAll((mapped) =>\n mapped.isNotFound\n ? Effect.void\n : Effect.fail(\n new AuthStorageWriteError({\n message: 'Failed to remove auth file',\n cause: String(mapped.original),\n })\n )\n )\n );\n yield* Effect.log('Auth data removed from local storage');\n });\n\n return { load, save, remove };\n }),\n}) {}\n","import { Config, Effect, Schema } from 'effect';\nimport type { OAuthClientConfig } from '../domain';\nimport { OAuthDiscoveryError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// Environment config (replaces env.ts + @t3-oss/env-core + zod + dotenv)\n// ---------------------------------------------------------------------------\n\nconst OAuthEnvConfig = Config.all({\n issuerUrl: Config.string('GIGADRIVE_NETWORK_OAUTH_ISSUER_URL').pipe(Config.withDefault('https://idp.gigadrive.de')),\n // Default is the first-party CLI's public OAuth client (seeded in the Network\n // repo). Override with GIGADRIVE_NETWORK_OAUTH_CLIENT_ID per environment.\n clientId: Config.string('GIGADRIVE_NETWORK_OAUTH_CLIENT_ID').pipe(\n Config.withDefault('0195c11c-0000-7000-8000-000000000001')\n ),\n});\n\n// ---------------------------------------------------------------------------\n// OIDC discovery document schema\n// ---------------------------------------------------------------------------\n\nconst OpenIdDiscoveryDocument = Schema.Struct({\n issuer: Schema.optional(Schema.String),\n authorization_endpoint: Schema.optional(Schema.String),\n token_endpoint: Schema.optional(Schema.String),\n userinfo_endpoint: Schema.optional(Schema.String),\n device_authorization_endpoint: Schema.optional(Schema.String),\n});\n\n/**\n * Scopes requested at login. Identity scopes plus the Network API capability\n * scopes available to the standalone first-party CLI and the platform scopes\n * needed to provision local-dev API credentials. AI Gateway governance scopes\n * are intentionally excluded because the IDP only grants them to OAuth clients\n * bound to a Network application; requesting one would reject the entire login.\n */\nconst CLI_SCOPES = [\n // Identity / OIDC\n 'offline_access',\n 'openid',\n 'profile',\n 'email',\n // Platform discovery used for zero-config application onboarding\n 'platform:organizations:read',\n // Network API capabilities\n 'network:applications:read',\n 'network:applications:write',\n 'network:env_vars:read',\n 'network:env_vars:write',\n 'network:env_vars:delete',\n 'network:deployments:read',\n 'network:deployments:write',\n 'network:deployments:trigger',\n 'network:ai_gateway:chat',\n 'network:ai_gateway:models',\n // Provisioning local-dev API credentials\n 'platform:api_keys:read',\n 'platform:api_keys:write',\n 'platform:api_keys:delete',\n] as const;\n\nconst DEFAULT_SCOPE = CLI_SCOPES.join(' ');\n\n// ---------------------------------------------------------------------------\n// OAuthConfigService\n// ---------------------------------------------------------------------------\n\nexport class OAuthConfigService extends Effect.Service<OAuthConfigService>()('OAuthConfigService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const envConfig = yield* OAuthEnvConfig;\n let cached: OAuthClientConfig | null = null;\n\n const getConfig: Effect.Effect<OAuthClientConfig, OAuthDiscoveryError> = Effect.gen(function* () {\n if (cached) return cached;\n\n const issuerBase = envConfig.issuerUrl.replace(/\\/$/, '');\n const discoveryUrl = `${issuerBase}/.well-known/openid-configuration`;\n\n yield* Effect.log('Fetching OIDC discovery document', { discoveryUrl });\n\n const response = yield* Effect.tryPromise({\n try: (signal) => fetch(discoveryUrl, { signal }),\n catch: (error) =>\n new OAuthDiscoveryError({\n message: 'Failed to fetch OIDC discovery document',\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n if (!response.ok) {\n return yield* Effect.fail(\n new OAuthDiscoveryError({\n message: `OIDC discovery returned ${response.status} ${response.statusText}`,\n })\n );\n }\n\n const json = yield* Effect.tryPromise({\n try: () => response.json(),\n catch: () =>\n new OAuthDiscoveryError({\n message: 'Failed to parse OIDC discovery JSON',\n }),\n });\n\n const decoded = yield* Schema.decodeUnknown(OpenIdDiscoveryDocument)(json).pipe(\n Effect.mapError(\n () =>\n new OAuthDiscoveryError({\n message: 'Invalid OIDC discovery document schema',\n })\n )\n );\n\n if (\n !decoded.authorization_endpoint ||\n !decoded.token_endpoint ||\n !decoded.userinfo_endpoint ||\n !decoded.device_authorization_endpoint\n ) {\n return yield* Effect.fail(\n new OAuthDiscoveryError({\n message: 'OIDC discovery returned incomplete endpoints',\n })\n );\n }\n\n const config: OAuthClientConfig = {\n clientId: envConfig.clientId,\n issuer: decoded.issuer ?? issuerBase,\n authorizeUrl: decoded.authorization_endpoint,\n tokenUrl: decoded.token_endpoint,\n deviceAuthorizeUrl: decoded.device_authorization_endpoint,\n scope: DEFAULT_SCOPE,\n userinfoUrl: decoded.userinfo_endpoint,\n };\n\n cached = config;\n yield* Effect.log('OIDC discovery completed', { issuer: config.issuer });\n return config;\n });\n\n return { getConfig };\n }),\n}) {}\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option, Schema } from 'effect';\nimport type { ProjectLink } from '../domain';\nimport { ProjectLink as ProjectLinkSchema } from '../domain';\nimport { ProjectLinkReadError, ProjectLinkWriteError, ProjectNotLinkedError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// ProjectLinkService\n//\n// Links a working directory to a Gigadrive application by persisting the choice\n// in `<projectFolder>/.gigadrive/project.json`. Commands read the linked\n// application so they don't require an explicit `--app` on every invocation.\n// ---------------------------------------------------------------------------\n\nconst LINK_DIR = '.gigadrive';\nconst LINK_FILE = 'project.json';\n\nexport class ProjectLinkService extends Effect.Service<ProjectLinkService>()('ProjectLinkService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const linkDir = (projectFolder: string) => pathService.join(projectFolder, LINK_DIR);\n const linkFile = (projectFolder: string) => pathService.join(projectFolder, LINK_DIR, LINK_FILE);\n\n /** Load the project link, returning `Option.none` when the directory is not linked. */\n const load = Effect.fn('ProjectLinkService.load')(function* (projectFolder: string) {\n const file = linkFile(projectFolder);\n\n const exists = yield* fs\n .exists(file)\n .pipe(Effect.mapError(() => new ProjectLinkReadError({ message: 'Failed to check project link existence' })));\n if (!exists) return Option.none<ProjectLink>();\n\n const data = yield* fs\n .readFileString(file, 'utf8')\n .pipe(Effect.mapError(() => new ProjectLinkReadError({ message: 'Failed to read project link file' })));\n\n const json = yield* Effect.try({\n try: () => JSON.parse(data) as unknown,\n catch: () => new ProjectLinkReadError({ message: `${LINK_DIR}/${LINK_FILE} contains invalid JSON` }),\n });\n\n const link = yield* Schema.decodeUnknown(ProjectLinkSchema)(json).pipe(\n Effect.mapError(() => new ProjectLinkReadError({ message: `${LINK_DIR}/${LINK_FILE} has an invalid schema` }))\n );\n\n return Option.some(link);\n });\n\n /** Load the project link, failing with `ProjectNotLinkedError` when absent. */\n const resolve = Effect.fn('ProjectLinkService.resolve')(function* (projectFolder: string) {\n const link = yield* load(projectFolder);\n return yield* Option.match(link, {\n onNone: () =>\n Effect.fail(\n new ProjectNotLinkedError({\n message: 'This directory is not linked to an application. Run \"gigadrive link\" first.',\n directory: projectFolder,\n })\n ),\n onSome: (value) => Effect.succeed(value),\n });\n });\n\n /** Persist the project link, creating `.gigadrive/` if needed. */\n const save = Effect.fn('ProjectLinkService.save')(function* (projectFolder: string, link: ProjectLink) {\n yield* fs\n .makeDirectory(linkDir(projectFolder), { recursive: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new ProjectLinkWriteError({ message: 'Failed to create .gigadrive directory', cause: String(error) })\n )\n );\n yield* fs\n .writeFileString(linkFile(projectFolder), `${JSON.stringify(link, null, 2)}\\n`)\n .pipe(\n Effect.mapError(\n (error) => new ProjectLinkWriteError({ message: 'Failed to write project link file', cause: String(error) })\n )\n );\n yield* Effect.log('Project link saved', { applicationId: link.applicationId });\n });\n\n /** Remove the project link file, treating a missing file as success. */\n const remove = Effect.fn('ProjectLinkService.remove')(function* (projectFolder: string) {\n // `force: true` makes removing a missing file a no-op (@effect/platform swallows the\n // NotFound SystemError); genuine failures (e.g. permissions) still surface below.\n yield* fs\n .remove(linkFile(projectFolder), { force: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new ProjectLinkWriteError({ message: 'Failed to remove project link file', cause: String(error) })\n )\n );\n });\n\n return { load, resolve, save, remove };\n }),\n}) {}\n","import { Command, Options } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApiClientService } from '../../services/api-client';\n\nconst listOrgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Only list applications belonging to this organization ID'),\n Options.optional\n);\n\nconst createOrgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Organization ID that will own the application')\n);\n\nconst nameOption = Options.text('name').pipe(\n Options.withAlias('n'),\n Options.withDescription('Application display name')\n);\n\nconst slugOption = Options.text('slug').pipe(\n Options.withDescription('Optional lowercase application slug'),\n Options.optional\n);\n\nconst rootDirectoryOption = Options.text('root-directory').pipe(\n Options.withDescription('Optional project directory relative to the repository root'),\n Options.optional\n);\n\nconst appsListCommand = Command.make('list', { org: listOrgOption }, ({ org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = Option.getOrUndefined(org);\n const { items, total } = yield* apiClient.request((client) => client.applications.list({ organizationId }));\n\n if (items.length === 0) {\n yield* Console.log('No applications found.');\n return;\n }\n\n for (const app of items) {\n yield* Console.log(`${app.id} ${app.name} (${app.organization.name})`);\n }\n yield* Console.log(`\\n${total} application(s).`);\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list applications: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst appsCreateCommand = Command.make(\n 'create',\n { org: createOrgOption, name: nameOption, slug: slugOption, rootDirectory: rootDirectoryOption },\n ({ org, name, slug, rootDirectory }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const application = yield* apiClient.request((client) =>\n client.applications.create({\n organizationId: org,\n name,\n ...Option.match(slug, { onNone: () => ({}), onSome: (value) => ({ slug: value }) }),\n ...Option.match(rootDirectory, {\n onNone: () => ({}),\n onSome: (value) => ({ rootDirectory: value }),\n }),\n })\n );\n\n yield* Console.log(`Created application ${application.name} (${application.id}).`);\n yield* Console.log(`Run \"gigadrive link --app ${application.id}\" to link the current directory.`);\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to create application: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst appsBase = Command.make('apps', {}, () => Effect.void);\n\n/** `gigadrive apps` — create and inspect applications the authenticated actor can access. */\nexport const appsCommand = appsBase.pipe(Command.withSubcommands([appsListCommand, appsCreateCommand]));\n","import { Command } from '@effect/cli';\nimport { FileSystem, Path } from '@effect/platform';\nimport { exec } from '@gigadrive/build-utils';\nimport { Console, Effect } from 'effect';\nimport { BuildScriptNotFoundError, ExecError, PackageJsonNotFoundError, PackageJsonParseError } from '../../errors';\nimport { PackageManagerService } from '../../services/package-manager';\n\nexport const buildCommand = Command.make('build', {}, () =>\n Effect.gen(function* () {\n const pmService = yield* PackageManagerService;\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n const cwd = process.cwd();\n\n yield* Effect.log('Starting build', { cwd });\n\n // Validate package.json exists\n const packageJsonPath = pathService.join(cwd, 'package.json');\n const packageJsonExists = yield* fs\n .exists(packageJsonPath)\n .pipe(\n Effect.mapError(\n () => new PackageJsonNotFoundError({ message: 'Failed to check for package.json', directory: cwd })\n )\n );\n if (!packageJsonExists) {\n return yield* Effect.fail(new PackageJsonNotFoundError({ message: 'No package.json found', directory: cwd }));\n }\n\n // Read and validate build script\n const packageJsonContent = yield* fs\n .readFileString(packageJsonPath, 'utf-8')\n .pipe(\n Effect.mapError(() => new PackageJsonNotFoundError({ message: 'Failed to read package.json', directory: cwd }))\n );\n\n const packageJson = yield* Effect.try({\n try: () => JSON.parse(packageJsonContent) as { scripts?: { build?: string } },\n catch: (error) =>\n new PackageJsonParseError({\n message: 'Failed to parse package.json',\n directory: cwd,\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n if (!packageJson.scripts?.build) {\n return yield* Effect.fail(new BuildScriptNotFoundError({ message: 'No build script found in package.json' }));\n }\n\n // Detect package manager\n const pm = yield* pmService.detect(cwd);\n\n const buildEnv = {\n ...process.env,\n NODE_ENV: 'production',\n NEBULA: '1',\n VERCEL: '1',\n NOW_BUILDER: '1',\n };\n\n // Install dependencies\n const installCmd = pmService.installCommand(pm);\n yield* Console.log(`Running: ${installCmd}`);\n yield* Effect.tryPromise({\n try: () =>\n exec({\n command: installCmd,\n cwd,\n env: buildEnv,\n onOutput: (chunk) => {\n Console.log(chunk).pipe(Effect.runSync);\n },\n }),\n catch: (error) =>\n new ExecError({\n message: 'Install failed',\n command: installCmd,\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n // Run build\n const buildCmd = pmService.buildCommand(pm);\n yield* Console.log(`Running: ${buildCmd}`);\n yield* Effect.tryPromise({\n try: () =>\n exec({\n command: buildCmd,\n cwd,\n env: buildEnv,\n onOutput: (chunk) => {\n Console.log(chunk).pipe(Effect.runSync);\n },\n }),\n catch: (error) =>\n new ExecError({\n message: 'Build failed',\n command: buildCmd,\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n yield* Console.log('Build completed successfully.');\n }).pipe(\n Effect.catchTags({\n PackageJsonNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n PackageJsonParseError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n BuildScriptNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n PackageManagerNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ExecError: (err) =>\n Console.error(`${err.message}: ${err.cause ?? err.command}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { FileSystem, Path } from '@effect/platform';\nimport { exec } from '@gigadrive/build-utils';\nimport { Effect } from 'effect';\nimport type { PackageManager } from '../domain';\nimport { ExecError, PackageManagerNotFoundError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// PackageManagerService\n// ---------------------------------------------------------------------------\n\nexport class PackageManagerService extends Effect.Service<PackageManagerService>()('PackageManagerService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const detect = Effect.fn('PackageManagerService.detect')(function* (cwd: string) {\n yield* Effect.annotateCurrentSpan('cwd', cwd);\n\n const packageJsonPath = pathService.join(cwd, 'package.json');\n const exists = yield* fs\n .exists(packageJsonPath)\n .pipe(\n Effect.mapError(\n () => new PackageManagerNotFoundError({ message: 'Failed to check for package.json', directory: cwd })\n )\n );\n if (!exists) {\n return yield* Effect.fail(\n new PackageManagerNotFoundError({\n message: 'No package.json found',\n directory: cwd,\n })\n );\n }\n\n // Check lock files in priority order\n const lockChecks: Array<{ file: string; pm: PackageManager }> = [\n { file: 'yarn.lock', pm: 'yarn' },\n { file: 'pnpm-lock.yaml', pm: 'pnpm' },\n { file: 'bun.lockb', pm: 'bun' },\n { file: 'package-lock.json', pm: 'npm' },\n ];\n\n for (const { file, pm } of lockChecks) {\n const lockExists = yield* fs\n .exists(pathService.join(cwd, file))\n .pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (lockExists) {\n yield* Effect.log('Package manager detected from lock file', { packageManager: pm, lockFile: file });\n return pm;\n }\n }\n\n // Fallback: check if bun is installed\n const bunAvailable = yield* Effect.tryPromise({\n try: () => exec({ command: 'bun --version', cwd }),\n catch: () => new ExecError({ message: 'bun not found', command: 'bun --version' }),\n }).pipe(\n Effect.as(true),\n Effect.catchTag('ExecError', () => Effect.succeed(false))\n );\n\n const pm: PackageManager = bunAvailable ? 'bun' : 'npm';\n yield* Effect.log('Package manager detected via fallback', { packageManager: pm });\n return pm;\n });\n\n const installCommand = (pm: PackageManager): string =>\n ({\n bun: 'bun install',\n npm: 'npm install',\n pnpm: 'pnpm install',\n yarn: 'yarn install',\n })[pm];\n\n const buildCommand = (pm: PackageManager): string =>\n ({\n bun: 'bun run build',\n npm: 'npm run build',\n pnpm: 'pnpm build',\n yarn: 'yarn build',\n })[pm];\n\n return { detect, installCommand, buildCommand };\n }),\n}) {}\n","import { Command } from '@effect/cli';\nimport { Effect } from 'effect';\nimport { debugConfigCommand } from './config';\n\nconst debugBase = Command.make('debug', {}, () => Effect.void);\n\nexport const debugCommand = debugBase.pipe(Command.withSubcommands([debugConfigCommand]));\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { ProjectConfigService } from '../../../services/project-config';\n\nexport const debugConfigCommand = Command.make('config', {}, () =>\n Effect.gen(function* () {\n const projectConfig = yield* ProjectConfigService;\n const cwd = process.cwd();\n const { config, configPath } = yield* projectConfig.resolve(cwd);\n\n yield* Console.log(`Config file found at: ${configPath}`);\n yield* Console.log(JSON.stringify(config, null, 2));\n }).pipe(\n Effect.catchTags({\n ConfigNotFoundError: (err) => Console.error(err.message),\n ConfigParseError: (err) => Console.error(`Config parse error: ${err.message}`),\n ConfigValidationError: (err) =>\n Effect.gen(function* () {\n for (const e of err.errors) {\n yield* Console.error(e);\n }\n yield* Console.error(err.message);\n }),\n })\n )\n);\n","import type {\n ConfigFileEmptyError,\n ConfigFileNotFoundError,\n ConfigFileParseError,\n ConfigModuleLoadError,\n ConfigSchemaValidationError,\n ConfigVersionError,\n ContainerConfigError,\n FunctionConfigError,\n NormalizedConfig,\n} from '@gigadrive/network-config';\nimport {\n detectContainerProject,\n detectFramework,\n mergeWithFrameworkDefaults,\n NetworkConfigLive,\n parseConfig,\n parseConfigRaw,\n postProcessConfig,\n RawConfigReader,\n} from '@gigadrive/network-config';\nimport { Effect } from 'effect';\nimport { ConfigNotFoundError, ConfigParseError, ConfigValidationError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps parseConfig errors into the CLI's ConfigParseError type.\n */\ntype ParseConfigErrors =\n | ConfigFileNotFoundError\n | ConfigFileEmptyError\n | ConfigFileParseError\n | ConfigModuleLoadError\n | ConfigVersionError\n | ConfigSchemaValidationError\n | ContainerConfigError\n | FunctionConfigError;\n\nconst wrapParseErrors = <A, R>(effect: Effect.Effect<A, ParseConfigErrors, R>) =>\n effect.pipe(\n Effect.catchTags({\n ConfigFileNotFoundError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath })),\n ConfigFileEmptyError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath })),\n ConfigFileParseError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.cause })),\n ConfigModuleLoadError: (e) =>\n Effect.fail(new ConfigParseError({ message: e.message, cause: e.cause ?? e.filePath })),\n ConfigVersionError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath })),\n ConfigSchemaValidationError: (e) =>\n Effect.fail(new ConfigParseError({ message: e.message, cause: e.validationErrors.join(', ') })),\n FunctionConfigError: (e) => Effect.fail(new ConfigParseError({ message: e.message, cause: e.functionPath })),\n ContainerConfigError: (e) =>\n Effect.fail(new ConfigParseError({ message: e.message, cause: e.filePath ?? e.containerName })),\n })\n );\n\n// ---------------------------------------------------------------------------\n// ProjectConfigService\n// ---------------------------------------------------------------------------\n\nexport class ProjectConfigService extends Effect.Service<ProjectConfigService>()('ProjectConfigService', {\n accessors: true,\n dependencies: [NetworkConfigLive],\n\n effect: Effect.gen(function* () {\n const rawReader = yield* RawConfigReader;\n\n const resolve = Effect.fn('ProjectConfigService.resolve')(function* (cwd: string) {\n yield* Effect.annotateCurrentSpan('cwd', cwd);\n yield* Effect.log('Resolving project config', { cwd });\n\n const configPath = yield* rawReader.findConfig(cwd);\n\n // Attempt framework auto-detection.\n // ManifestReadError / ManifestParseError indicate genuine problems (the\n // manifest file exists but is unreadable or malformed), so we surface them\n // as ConfigParseError instead of silently swallowing them.\n const detection = yield* detectFramework(cwd).pipe(\n Effect.catchTag('FrameworkNotDetectedError', () => Effect.succeed(null)),\n Effect.catchTag('ManifestReadError', (e) =>\n Effect.fail(new ConfigParseError({ message: `Framework detection failed: ${e.message}`, cause: e.filePath }))\n ),\n Effect.catchTag('ManifestParseError', (e) =>\n Effect.fail(new ConfigParseError({ message: `Framework detection failed: ${e.message}`, cause: e.filePath }))\n )\n );\n\n if (detection) {\n yield* Effect.log('Framework auto-detected', {\n framework: detection.framework.name,\n slug: detection.framework.slug,\n });\n }\n\n let config: NormalizedConfig;\n let resolvedConfigPath: string | null = null;\n let framework: { name: string; slug: string } | undefined;\n\n if (configPath && detection) {\n // Case A: config file + framework detected → parse raw (no post-processing), merge\n // with framework defaults, then post-process the merged result. Running postProcessConfig\n // after the merge ensures validations (empty-deployment check, Vercel BOv3 merge,\n // function/asset dedup) see the full picture instead of producing stale pre-merge errors.\n yield* Effect.log('Config file found, merging with framework defaults', { configPath });\n resolvedConfigPath = configPath;\n\n const userConfig: NormalizedConfig = yield* wrapParseErrors(parseConfigRaw(configPath, cwd));\n const merged: NormalizedConfig = yield* mergeWithFrameworkDefaults(userConfig, detection.config);\n\n config = yield* wrapParseErrors(postProcessConfig(merged, cwd));\n framework = { name: detection.framework.name, slug: detection.framework.slug };\n } else if (configPath) {\n // Case B: config file only → existing behavior\n yield* Effect.log('Config file found', { configPath });\n resolvedConfigPath = configPath;\n\n config = yield* wrapParseErrors(parseConfig(configPath, cwd));\n } else if (detection) {\n // Case C: no config file, framework detected → use detection + post-process\n config = yield* wrapParseErrors(postProcessConfig(detection.config, cwd));\n\n framework = { name: detection.framework.name, slug: detection.framework.slug };\n } else {\n // Case D: neither config file nor framework → a Compose file or a root\n // Dockerfile deploys as container images. Tried last so a framework\n // project's local-development Compose file never replaces the framework.\n const containerProject = yield* wrapParseErrors(\n detectContainerProject(cwd).pipe(Effect.map((result) => result?.config ?? null))\n );\n if (containerProject === null) {\n return yield* Effect.fail(\n new ConfigNotFoundError({\n message: 'No config file, framework, Compose file or Dockerfile found.',\n directory: cwd,\n })\n );\n }\n\n config = yield* wrapParseErrors(postProcessConfig(containerProject, cwd));\n }\n\n // Report warnings via structured logging\n for (const warning of config.warnings) {\n yield* Effect.logWarning(warning);\n }\n\n // Fail on config errors\n if (config.errors.length > 0) {\n return yield* Effect.fail(\n new ConfigValidationError({\n message: 'Config file has validation errors',\n errors: config.errors,\n })\n );\n }\n\n return { config, configPath: resolvedConfigPath, framework };\n });\n\n return { resolve };\n }),\n}) {}\n","import { Args, Command, Options } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst DEPLOYMENT_STATUSES = ['PENDING', 'QUEUED', 'STARTING', 'BUILDING', 'PROVISIONING', 'ACTIVE', 'FAILED'] as const;\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Filter by application ID (defaults to the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Filter by organization ID'),\n Options.optional\n);\n\nconst statusOption = Options.choice('status', DEPLOYMENT_STATUSES).pipe(\n Options.withAlias('s'),\n Options.withDescription('Filter by deployment status'),\n Options.optional\n);\n\n/**\n * Resolve the application filter: an explicit `--app` wins, otherwise fall back\n * to the linked application. An unlinked directory yields no filter (`load`\n * returns `Option.none`); a broken/unreadable `.gigadrive/project.json` surfaces\n * as `ProjectLinkReadError` rather than being silently treated as unlinked.\n */\nconst resolveApplicationFilter = (app: Option.Option<string>) =>\n Option.match(app, {\n onSome: (id) => Effect.succeed<string | undefined>(id),\n onNone: () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.load(process.cwd());\n return Option.match(link, { onNone: () => undefined, onSome: (l) => l.applicationId });\n }),\n });\n\nconst deploymentsListCommand = Command.make(\n 'list',\n { app: appOption, org: orgOption, status: statusOption },\n ({ app, org, status }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const applicationId = yield* resolveApplicationFilter(app);\n\n const { items, total } = yield* apiClient.request((client) =>\n client.deployments.list({\n applicationId,\n organizationId: Option.getOrUndefined(org),\n status: Option.getOrUndefined(status),\n })\n );\n\n if (items.length === 0) {\n yield* Console.log('No deployments found.');\n return;\n }\n\n for (const d of items) {\n yield* Console.log(`${d.id} ${d.status.padEnd(12)} ${d.createdAt}`);\n }\n yield* Console.log(`\\n${total} deployment(s).`);\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list deployments: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst deploymentIdArg = Args.text({ name: 'deployment-id' }).pipe(Args.withDescription('The deployment ID to inspect'));\n\nconst deploymentsInspectCommand = Command.make('inspect', { deploymentId: deploymentIdArg }, ({ deploymentId }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n\n const deployment = yield* apiClient.request((client) => client.deployments.get(deploymentId));\n yield* Console.log(`ID: ${deployment.id}`);\n yield* Console.log(`Application: ${deployment.applicationId}`);\n yield* Console.log(`Status: ${deployment.status}`);\n yield* Console.log(`Created: ${deployment.createdAt}`);\n yield* Console.log(`Updated: ${deployment.updatedAt}`);\n\n const hostnames = yield* apiClient\n .request((client) => client.deployments.getHostnames(deploymentId))\n .pipe(Effect.catchAll(() => Effect.succeed({ items: [], total: 0 })));\n if (hostnames.items.length > 0) {\n yield* Console.log('Hostnames:');\n for (const h of hostnames.items) {\n yield* Console.log(` https://${h.hostname}${h.active ? '' : ' (inactive)'}`);\n }\n }\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to inspect deployment: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst deploymentsBase = Command.make('deployments', {}, () => Effect.void);\n\n/** `gigadrive deployments` — list and inspect deployments. */\nexport const deploymentsCommand = deploymentsBase.pipe(\n Command.withSubcommands([deploymentsListCommand, deploymentsInspectCommand])\n);\n","import { Args, Command, Options, Prompt } from '@effect/cli';\nimport type { CustomDomain, CustomDomainTargetInput } from '@gigadrive/sdk';\nimport { Clock, Console, Duration, Effect, Either, Option } from 'effect';\nimport {\n ConfirmationRequiredError,\n DomainNotFoundError,\n DomainWaitError,\n InvalidDomainOptionsError,\n OrganizationRequiredError,\n} from '../../errors';\nimport { describeDomain, DOMAIN_STATE_LABELS, formatDnsRecords, IN_PROGRESS_STATES } from '../../lib/domain-output';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst REDIRECT_STATUS_CODES = ['301', '302', '307', '308'] as const;\nconst CONSOLE_URL = 'https://console.gigadrive.de';\nconst POLL_INTERVAL = Duration.seconds(5);\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Operate on this application (overrides the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Operate on this organization (defaults to the linked project’s organization)'),\n Options.optional\n);\n\nconst jsonOption = Options.boolean('json').pipe(\n Options.withDescription('Print only the result as JSON on stdout; progress goes to stderr')\n);\n\nconst waitOption = Options.boolean('wait').pipe(\n Options.withAlias('w'),\n Options.withDescription('Wait until the domain serves traffic, printing each state change')\n);\n\nconst timeoutOption = Options.integer('timeout').pipe(\n Options.withDescription('Minutes to wait with --wait, at least 1 (default: 10)'),\n Options.withDefault(10)\n);\n\nconst branchOption = Options.text('branch').pipe(\n Options.withDescription('Serve the latest deployment of this branch ID instead of production'),\n Options.optional\n);\n\nconst productionOption = Options.boolean('production').pipe(\n Options.withDescription('Serve the production deployment (the default for new domains)')\n);\n\nconst redirectToOption = Options.text('redirect-to').pipe(\n Options.withDescription('Redirect every request to this hostname instead of serving the application'),\n Options.optional\n);\n\nconst statusOption = Options.choice('status', REDIRECT_STATUS_CODES).pipe(\n Options.withDescription('Redirect status code with --redirect-to (default: 308)'),\n Options.optional\n);\n\nconst dropPathOption = Options.boolean('drop-path').pipe(\n Options.withDescription('With --redirect-to, redirect to the root instead of keeping the path and query')\n);\n\nconst primaryOption = Options.boolean('primary').pipe(\n Options.withDescription('Make this domain the application’s primary URL')\n);\n\nconst yesOption = Options.boolean('yes').pipe(\n Options.withAlias('y'),\n Options.withDescription('Skip the confirmation prompt (required when not running in a terminal)')\n);\n\nconst hostnameArg = Args.text({ name: 'hostname' }).pipe(\n Args.withDescription('Hostname to attach, e.g. shop.example.com or example.com')\n);\n\nconst domainArg = Args.text({ name: 'hostname-or-id' }).pipe(Args.withDescription('Domain hostname or ID'));\n\n/** Target flags shared by `add` and `update`. */\nexport interface TargetFlags {\n readonly production: boolean;\n readonly branch: Option.Option<string>;\n readonly redirectTo: Option.Option<string>;\n readonly status: Option.Option<(typeof REDIRECT_STATUS_CODES)[number]>;\n readonly dropPath: boolean;\n}\n\n/**\n * Turns the target flags into the API's target, refusing combinations that contradict each other\n * instead of silently picking one.\n *\n * @returns The target, or `undefined` when no target flag was given.\n */\nexport const targetFromFlags = (flags: TargetFlags) =>\n Effect.gen(function* () {\n const chosen = [flags.production, Option.isSome(flags.branch), Option.isSome(flags.redirectTo)].filter(Boolean);\n if (chosen.length > 1) {\n return yield* new InvalidDomainOptionsError({\n message: 'Choose one target: --production, --branch or --redirect-to.',\n });\n }\n if (Option.isNone(flags.redirectTo) && (Option.isSome(flags.status) || flags.dropPath)) {\n return yield* new InvalidDomainOptionsError({\n message: '--status and --drop-path only apply together with --redirect-to.',\n });\n }\n if (Option.isSome(flags.redirectTo)) {\n const target: CustomDomainTargetInput = {\n type: 'redirect',\n to: flags.redirectTo.value,\n statusCode: Option.match(flags.status, {\n onNone: () => undefined,\n onSome: (code) => (code === '301' ? 301 : code === '302' ? 302 : code === '307' ? 307 : 308),\n }),\n preservePath: !flags.dropPath,\n };\n return target;\n }\n if (Option.isSome(flags.branch)) {\n const target: CustomDomainTargetInput = { type: 'branch', branchId: flags.branch.value };\n return target;\n }\n if (flags.production) {\n const target: CustomDomainTargetInput = { type: 'production' };\n return target;\n }\n return undefined;\n });\n\nconst requirePositiveTimeout = (minutes: number) =>\n minutes >= 1\n ? Effect.succeed(minutes)\n : new InvalidDomainOptionsError({ message: '--timeout must be at least 1 minute.' });\n\n/** Asks before a destructive action. Without a terminal there is nobody to ask, so `--yes` is required. */\nconst confirm = (message: string, yes: boolean) =>\n Effect.gen(function* () {\n if (yes) return true;\n if (process.stdin.isTTY !== true) {\n return yield* new ConfirmationRequiredError({\n message: 'Not running in a terminal, so there is no way to confirm. Pass --yes to proceed.',\n });\n }\n return yield* Prompt.run(Prompt.confirm({ message, initial: false }));\n });\n\nconst resolveApplication = (app: Option.Option<string>) =>\n Option.match(app, {\n onSome: (value) => Effect.succeed(value),\n onNone: () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.resolve(process.cwd());\n return link.applicationId;\n }),\n });\n\nconst resolveOrganization = (org: Option.Option<string>) =>\n Option.match(org, {\n onSome: (value) => Effect.succeed(value),\n onNone: () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const link = yield* projectLink.load(process.cwd());\n const organizationId = Option.flatMap(link, (value) => Option.fromNullable(value.organizationId));\n if (Option.isNone(organizationId)) {\n return yield* new OrganizationRequiredError({\n message: 'Pass --org, or run the command in a linked project.',\n });\n }\n return organizationId.value;\n }),\n });\n\nconst normalizeHostname = (value: string) => value.trim().toLowerCase().replace(/\\.$/, '');\n\n/** Finds a domain of the application by hostname (any case, trailing dot allowed) or ID. */\nexport const findDomain = (applicationId: string, hostnameOrId: string) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const { items } = yield* apiClient.request((client) => client.applications.domains.list(applicationId));\n const wanted = normalizeHostname(hostnameOrId);\n const domain = items.find(\n (item) => item.id === hostnameOrId || item.hostname === wanted || item.unicodeHostname === wanted\n );\n if (!domain) {\n return yield* new DomainNotFoundError({ message: `No custom domain ${hostnameOrId} on this application.` });\n }\n return domain;\n });\n\nconst printDomain = (domain: CustomDomain) =>\n Effect.gen(function* () {\n for (const line of describeDomain(domain)) yield* Console.log(line);\n const pending = domain.requiredRecords.filter((record) => record.status !== 'ok');\n const records = formatDnsRecords(pending);\n if (records.length > 0 && domain.state !== 'removing') {\n yield* Console.log('\\nAdd these records at your DNS provider:');\n for (const line of records) yield* Console.log(` ${line}`);\n if (pending.some((record) => record.type === 'ALIAS')) {\n yield* Console.log(\n '\\nApex domains need an ALIAS, ANAME or flattened CNAME record. Without one, attach www instead and redirect the apex to it.'\n );\n }\n }\n });\n\n/** Rate limits, server errors and network failures are worth another poll. */\nconst isTransient = (error: { readonly _tag: string; readonly statusCode?: number }) =>\n error._tag === 'ApiRequestError' &&\n (error.statusCode === undefined || error.statusCode === 429 || error.statusCode >= 500);\n\n/**\n * Polls until the domain serves traffic, reporting each state change.\n *\n * In JSON mode the progress goes to stderr and the last known domain is printed to stdout even when\n * the wait fails, so stdout always holds exactly one JSON document.\n */\nexport const waitUntilServing = (applicationId: string, initial: CustomDomain, timeoutMinutes: number, json: boolean) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const progress = (line: string) => (json ? Console.error(line) : Console.log(line));\n const fail = (domain: CustomDomain, message: string) =>\n Effect.gen(function* () {\n if (json) yield* Console.log(JSON.stringify(domain, null, 2));\n return yield* new DomainWaitError({ message, state: domain.state });\n });\n\n const deadline = (yield* Clock.currentTimeMillis) + Duration.toMillis(Duration.minutes(timeoutMinutes));\n let domain = initial;\n yield* progress(`Waiting for ${domain.unicodeHostname} (${DOMAIN_STATE_LABELS[domain.state]})...`);\n\n while (IN_PROGRESS_STATES.has(domain.state)) {\n const remaining = deadline - (yield* Clock.currentTimeMillis);\n if (remaining <= 0) {\n return yield* fail(\n domain,\n `${domain.unicodeHostname} is not serving yet (${DOMAIN_STATE_LABELS[domain.state]}). Check again later with \"gigadrive domains inspect ${domain.hostname}\".`\n );\n }\n yield* Effect.sleep(Duration.min(POLL_INTERVAL, Duration.millis(remaining)));\n const polled = yield* Effect.either(\n apiClient.request((client) => client.applications.domains.get(applicationId, domain.id))\n );\n if (Either.isLeft(polled)) {\n // A blip (rate limit, 5xx, network) should not end a ten-minute wait; the loop retries until the deadline.\n if (isTransient(polled.left)) continue;\n return yield* polled.left;\n }\n if (polled.right.state !== domain.state) {\n yield* progress(` ${DOMAIN_STATE_LABELS[polled.right.state]}`);\n }\n domain = polled.right;\n }\n\n if (domain.state !== 'active' && domain.state !== 'degraded') {\n return yield* fail(\n domain,\n `${domain.unicodeHostname} is ${DOMAIN_STATE_LABELS[domain.state]}${domain.error ? `: ${domain.error.message}` : ''}`\n );\n }\n yield* progress(`\\n${domain.unicodeHostname} is live: https://${domain.hostname}`);\n if (json) yield* Console.log(JSON.stringify(domain, null, 2));\n return domain;\n });\n\n/** What to tell the user for a failed command, keeping the typed error as the exit status. */\nexport const errorMessage = (\n action: string,\n error: { readonly _tag: string; readonly message: string; readonly code?: string; readonly reason?: string }\n) => {\n switch (error._tag) {\n case 'NotAuthenticatedError':\n return 'You are not logged in. Run \"gigadrive login\" to authenticate.';\n case 'ApiRequestError':\n if (error.code === 'quota_exceeded' && error.reason === 'daily_add_limit') {\n return `${error.message}\\nThe daily limit resets within 24 hours; upgrading your plan raises it.`;\n }\n if (error.code === 'quota_exceeded') {\n return `${error.message}\\nSee your plan's limits and upgrade at ${CONSOLE_URL} (organization settings > Limits).`;\n }\n if (error.code === 'invalid_target' && error.reason === 'redirects_not_available') {\n return `${error.message}\\nRedirect domains are available on paid plans. Upgrade at ${CONSOLE_URL}.`;\n }\n if (error.code === 'domain_in_use' && error.reason === 'other_organization') {\n return `${error.message}\\nIf you control the domain, verify it with \"gigadrive domains owners add <domain>\", then move it with \"gigadrive domains claim <hostname>\".`;\n }\n if (error.reason === 'ownership_not_live') {\n return `${error.message}\\nPublish the TXT record shown by \"gigadrive domains owners list\" again, wait for DNS to update, then retry the claim.`;\n }\n return `Failed to ${action}: ${error.message}`;\n default:\n return error.message;\n }\n};\n\n/** Prints what went wrong while keeping the typed error, so the command still exits non-zero. */\nconst reportErrors =\n (action: string) =>\n <A, E extends { readonly _tag: string; readonly message: string }, R>(self: Effect.Effect<A, E, R>) =>\n Effect.tapError(self, (error) => Console.error(errorMessage(action, error)));\n\nconst listCommand = Command.make('list', { app: appOption, json: jsonOption }, ({ app, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const applicationId = yield* resolveApplication(app);\n const { items } = yield* apiClient.request((client) => client.applications.domains.list(applicationId));\n if (json) return yield* Console.log(JSON.stringify(items, null, 2));\n if (items.length === 0) {\n return yield* Console.log('No custom domains. Add one with \"gigadrive domains add <hostname>\".');\n }\n const width = Math.max(...items.map((item) => item.unicodeHostname.length));\n for (const item of items) {\n const problem = item.error ? ` ${item.error.code}` : '';\n yield* Console.log(\n `${item.unicodeHostname.padEnd(width)} ${DOMAIN_STATE_LABELS[item.state]}${item.primary ? ' (primary)' : ''}${problem}`\n );\n }\n }).pipe(reportErrors('list custom domains'))\n);\n\n/** Input of {@link addDomain}. */\nexport interface AddDomainInput extends TargetFlags {\n readonly hostname: string;\n readonly applicationId: string;\n readonly wait: boolean;\n readonly timeout: number;\n readonly json: boolean;\n}\n\n/** Attaches a hostname and optionally waits until it serves. */\nexport const addDomain = (input: AddDomainInput) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const target = yield* targetFromFlags(input);\n const timeout = yield* requirePositiveTimeout(input.timeout);\n const domain = yield* apiClient.request((client) =>\n client.applications.domains.add(input.applicationId, { hostname: input.hostname, target })\n );\n if (input.wait) return yield* waitUntilServing(input.applicationId, domain, timeout, input.json);\n if (input.json) {\n yield* Console.log(JSON.stringify(domain, null, 2));\n return domain;\n }\n yield* printDomain(domain);\n if (IN_PROGRESS_STATES.has(domain.state)) {\n yield* Console.log(\n `\\nGigadrive checks the records automatically. Follow progress with \"gigadrive domains inspect ${domain.hostname}\".`\n );\n }\n return domain;\n });\n\nconst addCommand = Command.make(\n 'add',\n {\n hostname: hostnameArg,\n app: appOption,\n production: productionOption,\n branch: branchOption,\n redirectTo: redirectToOption,\n status: statusOption,\n dropPath: dropPathOption,\n wait: waitOption,\n timeout: timeoutOption,\n json: jsonOption,\n },\n ({ app, ...options }) =>\n Effect.gen(function* () {\n const applicationId = yield* resolveApplication(app);\n yield* addDomain({ ...options, applicationId });\n }).pipe(reportErrors('add the domain'))\n);\n\nconst updateCommand = Command.make(\n 'update',\n {\n domain: domainArg,\n app: appOption,\n production: productionOption,\n branch: branchOption,\n redirectTo: redirectToOption,\n status: statusOption,\n dropPath: dropPathOption,\n primary: primaryOption,\n json: jsonOption,\n },\n ({ domain: hostnameOrId, app, primary, json, ...flags }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const target = yield* targetFromFlags(flags);\n if (target === undefined && !primary) {\n return yield* new InvalidDomainOptionsError({\n message: 'Nothing to change. Pass --production, --branch, --redirect-to or --primary.',\n });\n }\n const applicationId = yield* resolveApplication(app);\n const found = yield* findDomain(applicationId, hostnameOrId);\n const domain = yield* apiClient.request((client) =>\n client.applications.domains.update(applicationId, found.id, {\n ...(target === undefined ? {} : { target }),\n ...(primary ? { primary: true } : {}),\n })\n );\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* printDomain(domain);\n }).pipe(reportErrors('update the domain'))\n);\n\nconst claimCommand = Command.make(\n 'claim',\n {\n hostname: hostnameArg.pipe(Args.withDescription('Hostname another organization attached')),\n app: appOption,\n json: jsonOption,\n },\n ({ hostname, app, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const applicationId = yield* resolveApplication(app);\n const domain = yield* apiClient.request((client) => client.applications.domains.claim(applicationId, hostname));\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* Console.log(`Moved ${domain.unicodeHostname} to this application.`);\n yield* printDomain(domain);\n }).pipe(reportErrors('claim the domain'))\n);\n\nconst inspectCommand = Command.make(\n 'inspect',\n { domain: domainArg, app: appOption, json: jsonOption },\n ({ domain: hostnameOrId, app, json }) =>\n Effect.gen(function* () {\n const applicationId = yield* resolveApplication(app);\n const domain = yield* findDomain(applicationId, hostnameOrId);\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* printDomain(domain);\n if (domain.nextCheckAt !== null) yield* Console.log(`\\nNext automatic check: ${domain.nextCheckAt}`);\n }).pipe(reportErrors('inspect the domain'))\n);\n\nconst checkCommand = Command.make(\n 'check',\n { domain: domainArg, app: appOption, wait: waitOption, timeout: timeoutOption, json: jsonOption },\n ({ domain: hostnameOrId, app, wait, timeout, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const minutes = yield* requirePositiveTimeout(timeout);\n const applicationId = yield* resolveApplication(app);\n const found = yield* findDomain(applicationId, hostnameOrId);\n const domain = yield* apiClient.request((client) => client.applications.domains.refresh(applicationId, found.id));\n if (wait) return yield* waitUntilServing(applicationId, domain, minutes, json);\n if (json) return yield* Console.log(JSON.stringify(domain, null, 2));\n yield* Console.log(`Checking ${domain.unicodeHostname}.`);\n yield* printDomain(domain);\n }).pipe(reportErrors('check the domain'))\n);\n\n/** Removes a domain after confirmation. */\nexport const removeDomain = (applicationId: string, hostnameOrId: string, yes: boolean) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const domain = yield* findDomain(applicationId, hostnameOrId);\n const confirmed = yield* confirm(\n `Remove ${domain.unicodeHostname}? It stops serving this application immediately.`,\n yes\n );\n if (!confirmed) return yield* Console.log('Cancelled.');\n yield* apiClient.request((client) => client.applications.domains.remove(applicationId, domain.id));\n yield* Console.log(`Removed ${domain.unicodeHostname}.`);\n });\n\nconst removeCommand = Command.make(\n 'rm',\n { domain: domainArg, app: appOption, yes: yesOption },\n ({ domain: hostnameOrId, app, yes }) =>\n Effect.gen(function* () {\n const applicationId = yield* resolveApplication(app);\n yield* removeDomain(applicationId, hostnameOrId, yes);\n }).pipe(\n // Ctrl+C at the confirmation is a deliberate cancel, not a failure.\n Effect.catchTag('QuitException', () => Console.log('Cancelled.')),\n reportErrors('remove the domain')\n )\n);\n\nconst findOwnership = (organizationId: string, name: string) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const { items } = yield* apiClient.request((client) => client.organizations.domains.list(organizationId));\n const wanted = normalizeHostname(name);\n const claim = items.find((item) => item.id === name || item.name === wanted || item.unicodeName === wanted);\n if (!claim) {\n return yield* new DomainNotFoundError({\n message: `${name} is not claimed. Add it with \"gigadrive domains owners add\".`,\n });\n }\n return claim;\n });\n\nconst ownersListCommand = Command.make('list', { org: orgOption, json: jsonOption }, ({ org, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const { items } = yield* apiClient.request((client) => client.organizations.domains.list(organizationId));\n if (json) return yield* Console.log(JSON.stringify(items, null, 2));\n if (items.length === 0) return yield* Console.log('No verified domains.');\n const width = Math.max(...items.map((item) => item.unicodeName.length));\n for (const item of items) {\n yield* Console.log(`${item.unicodeName.padEnd(width)} ${item.status}`);\n }\n }).pipe(reportErrors('list verified domains'))\n);\n\nconst ownersAddCommand = Command.make(\n 'add',\n {\n name: Args.text({ name: 'domain' }).pipe(Args.withDescription('Domain to verify, e.g. example.com')),\n org: orgOption,\n json: jsonOption,\n },\n ({ name, org, json }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const claim = yield* apiClient.request((client) => client.organizations.domains.add(organizationId, name));\n if (json) return yield* Console.log(JSON.stringify(claim, null, 2));\n if (claim.status === 'verified') {\n return yield* Console.log(`${claim.unicodeName} is verified.`);\n }\n yield* Console.log(`Publish this TXT record for ${claim.unicodeName}:`);\n yield* Console.log(` Name: ${claim.record.host}`);\n yield* Console.log(` Value: ${claim.record.value}`);\n yield* Console.log(`\\nThen run \"gigadrive domains owners verify ${claim.name}\".`);\n }).pipe(reportErrors('add the domain'))\n);\n\nconst ownersVerifyCommand = Command.make(\n 'verify',\n { name: Args.text({ name: 'domain' }).pipe(Args.withDescription('Domain to verify')), org: orgOption },\n ({ name, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const claim = yield* findOwnership(organizationId, name);\n const checked = yield* apiClient.request((client) =>\n client.organizations.domains.verify(organizationId, claim.id)\n );\n if (checked.status === 'verified') {\n return yield* Console.log(`${checked.unicodeName} is verified.`);\n }\n yield* Console.log(\n `${checked.unicodeName} is not verified yet${checked.error ? `: ${checked.error.message}` : '.'} Gigadrive keeps checking automatically.`\n );\n }).pipe(reportErrors('verify the domain'))\n);\n\nconst ownersRemoveCommand = Command.make(\n 'rm',\n {\n name: Args.text({ name: 'domain' }).pipe(Args.withDescription('Domain to remove')),\n org: orgOption,\n yes: yesOption,\n },\n ({ name, org, yes }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const organizationId = yield* resolveOrganization(org);\n const claim = yield* findOwnership(organizationId, name);\n const confirmed = yield* confirm(\n `Remove ${claim.unicodeName} from your organization's domains? Custom domains that rely on it must be removed first.`,\n yes\n );\n if (!confirmed) return yield* Console.log('Cancelled.');\n yield* apiClient.request((client) => client.organizations.domains.remove(organizationId, claim.id));\n yield* Console.log(`Removed ${claim.unicodeName}.`);\n }).pipe(\n Effect.catchTag('QuitException', () => Console.log('Cancelled.')),\n reportErrors('remove the domain')\n )\n);\n\nconst ownersCommand = Command.make('owners', {}, () => Effect.void).pipe(\n Command.withDescription('Domains your organization verified with a TXT record'),\n Command.withSubcommands([ownersListCommand, ownersAddCommand, ownersVerifyCommand, ownersRemoveCommand])\n);\n\nconst domainsBase = Command.make('domains', {}, () => Effect.void).pipe(\n Command.withDescription('Custom domains of the linked application')\n);\n\n/** `gigadrive domains` — attach, change, inspect and remove custom domains, and verify domain ownership. */\nexport const domainsCommand = domainsBase.pipe(\n Command.withSubcommands([\n listCommand,\n addCommand,\n updateCommand,\n claimCommand,\n inspectCommand,\n checkCommand,\n removeCommand,\n ownersCommand,\n ])\n);\n","import type { CustomDomain, CustomDomainState, RequiredDnsRecord } from '@gigadrive/sdk';\n\n/** Human-readable label per lifecycle state, matching the console. */\nexport const DOMAIN_STATE_LABELS: Record<CustomDomainState, string> = {\n pending_ownership: 'verifying ownership',\n pending_dns: 'waiting for DNS',\n issuing_certificate: 'issuing certificate',\n active: 'active',\n degraded: 'needs attention',\n failed: 'failed',\n suspended: 'suspended',\n removing: 'removing',\n};\n\nconst RECORD_STATUS_LABELS: Record<RequiredDnsRecord['status'], string> = {\n ok: 'found',\n pending: 'waiting',\n mismatch: 'different value',\n};\n\n/** States the lifecycle leaves on its own; waiting makes sense only while in one of these. */\nexport const IN_PROGRESS_STATES: ReadonlySet<CustomDomainState> = new Set([\n 'pending_ownership',\n 'pending_dns',\n 'issuing_certificate',\n]);\n\n/**\n * Formats the DNS records a domain still needs as an aligned table, one line per record.\n *\n * @param records - The domain's required records.\n * @returns The table lines, header first. Empty when there are no records.\n *\n * @example\n * ```ts\n * formatDnsRecords(domain.requiredRecords).forEach((line) => console.log(line));\n * ```\n */\nexport const formatDnsRecords = (records: readonly RequiredDnsRecord[]): string[] => {\n if (records.length === 0) return [];\n const rows = [\n ['Type', 'Name', 'Value', 'Status'],\n ...records.map((record) => [record.type, record.host, record.value, RECORD_STATUS_LABELS[record.status]]),\n ];\n const widths = [0, 1, 2].map((column) => Math.max(...rows.map((row) => row[column].length)));\n return rows.map((row) =>\n row\n .map((cell, column) => (column < widths.length ? cell.padEnd(widths[column]) : cell))\n .join(' ')\n .trimEnd()\n );\n};\n\n/**\n * Summarizes a domain in a few lines: hostname, state, target, problem and certificate.\n *\n * @param domain - The domain to describe.\n * @returns The lines to print.\n */\nexport const describeDomain = (domain: CustomDomain): string[] => {\n const lines = [\n `${domain.unicodeHostname} ${DOMAIN_STATE_LABELS[domain.state]}${domain.primary ? ' (primary)' : ''}`,\n ];\n if (domain.target.type === 'redirect' && domain.target.redirectTo !== null) {\n lines.push(`Redirects to ${domain.target.redirectTo} (${domain.target.redirectStatusCode ?? 308})`);\n } else if (domain.target.type === 'branch') {\n lines.push(`Serves branch ${domain.target.branchId ?? 'unknown'}`);\n }\n if (domain.error !== null) lines.push(`Problem (${domain.error.code}): ${domain.error.message}`);\n if (domain.certificate.expiresAt !== null) lines.push(`Certificate expires ${domain.certificate.expiresAt}`);\n return lines;\n};\n","import { Args, Command, Options, Prompt } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { EnvVarNotFoundError, InvalidEnvVarFormatError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { EnvFileService } from '../../services/env-file';\nimport { LocalCredentialsService } from '../../services/local-credentials';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Operate on this application (overrides the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Operate on this organization instead of an application'),\n Options.optional\n);\n\nconst sensitiveOption = Options.boolean('sensitive').pipe(\n Options.withDescription('Store the value as sensitive (hidden in API responses)')\n);\n\nconst envIdOption = Options.text('env').pipe(\n Options.withAlias('e'),\n Options.withDescription('Environment ID for an environment-scoped variable (application scope only)'),\n Options.optional\n);\n\nconst keyValueArg = Args.text({ name: 'key=value' }).pipe(\n Args.withDescription('Variable assignment, e.g. DATABASE_URL=postgres://user:pass@host/db')\n);\n\nconst keyOrIdArg = Args.text({ name: 'key-or-id' }).pipe(Args.withDescription('Variable key or ID to remove'));\n\nconst fileArg = Args.text({ name: 'file' }).pipe(\n Args.withDescription('Output file to write (default: .env.local)'),\n Args.optional\n);\n\nconst environmentOption = Options.text('environment').pipe(\n Options.withAlias('e'),\n Options.withDescription('Environment slug to resolve overrides for (e.g. preview). Omit for the local baseline'),\n Options.optional\n);\n\nconst yesOption = Options.boolean('yes').pipe(\n Options.withAlias('y'),\n Options.withDescription('Overwrite an existing file without confirmation')\n);\n\nconst withCredentialsOption = Options.boolean('with-credentials').pipe(\n Options.withDescription('Also provision API-key credentials so the local app can call the API as this application')\n);\n\nconst rotateOption = Options.boolean('rotate').pipe(\n Options.withDescription('Force a fresh API key when provisioning credentials, revoking the previous one')\n);\n\n/**\n * Resolve which resource the command operates on: an explicit `--org` selects\n * organization scope; otherwise application scope using `--app` or the linked\n * application. Fails with `ProjectNotLinkedError` when neither is available.\n */\nconst resolveScope = (app: Option.Option<string>, org: Option.Option<string>) =>\n Effect.gen(function* () {\n if (Option.isSome(org)) {\n return { kind: 'organization' as const, id: org.value };\n }\n const projectLink = yield* ProjectLinkService;\n const id = yield* Option.match(app, {\n onSome: (value) => Effect.succeed(value),\n onNone: () => projectLink.resolve(process.cwd()).pipe(Effect.map((link) => link.applicationId)),\n });\n return { kind: 'application' as const, id };\n });\n\nconst envListCommand = Command.make('list', { app: appOption, org: orgOption }, ({ app, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const scope = yield* resolveScope(app, org);\n\n const { items } = yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.list(scope.id)\n : client.applications.envVars.list(scope.id)\n );\n\n if (items.length === 0) {\n yield* Console.log('No environment variables set.');\n return;\n }\n for (const v of items) {\n yield* Console.log(`${v.key}=${v.sensitive ? '***' : (v.value ?? '')}`);\n }\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list environment variables: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envSetCommand = Command.make(\n 'set',\n { keyValue: keyValueArg, app: appOption, org: orgOption, sensitive: sensitiveOption, env: envIdOption },\n ({ keyValue, app, org, sensitive, env }) =>\n Effect.gen(function* () {\n const separator = keyValue.indexOf('=');\n if (separator <= 0) {\n return yield* Effect.fail(\n new InvalidEnvVarFormatError({\n message: 'Invalid format. Use KEY=VALUE, e.g. \"gigadrive env set DATABASE_URL=postgres://...\".',\n })\n );\n }\n const key = keyValue.slice(0, separator);\n const value = keyValue.slice(separator + 1);\n\n const apiClient = yield* ApiClientService;\n const scope = yield* resolveScope(app, org);\n const environmentId = Option.getOrUndefined(env);\n\n const created = yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.create(scope.id, { key, value, sensitive })\n : client.applications.envVars.create(scope.id, { key, value, sensitive, environmentId })\n );\n yield* Console.log(`Set ${created.key}.`);\n }).pipe(\n Effect.catchTags({\n InvalidEnvVarFormatError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to set environment variable: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envRmCommand = Command.make(\n 'rm',\n { keyOrId: keyOrIdArg, app: appOption, org: orgOption },\n ({ keyOrId, app, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const scope = yield* resolveScope(app, org);\n\n const { items } = yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.list(scope.id)\n : client.applications.envVars.list(scope.id)\n );\n\n const target = items.find((v) => v.id === keyOrId || v.key === keyOrId);\n if (target === undefined) {\n return yield* Effect.fail(\n new EnvVarNotFoundError({ message: `No environment variable matching \"${keyOrId}\".` })\n );\n }\n\n yield* apiClient.request((client) =>\n scope.kind === 'organization'\n ? client.organizations.envVars.delete(scope.id, target.id)\n : client.applications.envVars.delete(scope.id, target.id)\n );\n yield* Console.log(`Removed ${target.key}.`);\n }).pipe(\n Effect.catchTags({\n EnvVarNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to remove environment variable: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envPullCommand = Command.make(\n 'pull',\n {\n file: fileArg,\n app: appOption,\n environment: environmentOption,\n yes: yesOption,\n withCredentials: withCredentialsOption,\n rotate: rotateOption,\n },\n ({ file, app, environment, yes, withCredentials, rotate }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const projectLink = yield* ProjectLinkService;\n const envFile = yield* EnvFileService;\n\n // `env pull` always targets an application (via --app or the linked project).\n const applicationId = yield* Option.match(app, {\n onSome: (value) => Effect.succeed(value),\n onNone: () => projectLink.resolve(process.cwd()).pipe(Effect.map((link) => link.applicationId)),\n });\n const target = Option.getOrElse(file, () => '.env.local');\n const environmentSlug = Option.getOrUndefined(environment);\n\n const { items, omittedSensitive } = yield* apiClient.request((client) =>\n client.applications.envVars.pull(applicationId, environmentSlug ? { environment: environmentSlug } : undefined)\n );\n\n const existing = yield* envFile.read(target);\n if (Option.isSome(existing) && !yes) {\n const overwrite = yield* Prompt.run(\n Prompt.confirm({ message: `${target} already exists. Overwrite?`, initial: false })\n );\n if (!overwrite) {\n return yield* Console.log('Cancelled.');\n }\n }\n\n let credentialEntries: { key: string; value: string }[] = [];\n if (withCredentials) {\n const localCredentials = yield* LocalCredentialsService;\n credentialEntries = yield* localCredentials.provision({\n applicationId,\n rotate,\n existingContent: Option.getOrUndefined(existing),\n });\n }\n\n const entries = [...items.map((v) => ({ key: v.key, value: v.value })), ...credentialEntries];\n yield* envFile.write(target, entries);\n const gitignored = yield* envFile.ensureGitignored(process.cwd(), target);\n\n yield* Console.log(\n `Pulled ${items.length} environment variable(s)${withCredentials ? ' and API credentials' : ''} to ${target}.`\n );\n if (omittedSensitive > 0) {\n yield* Console.log(\n `Skipped ${omittedSensitive} sensitive variable(s); secrets live only in production/preview environments.`\n );\n }\n if (gitignored) {\n yield* Console.log(`Added ${target} to .gitignore.`);\n }\n }).pipe(\n Effect.catchTags({\n // Ctrl+C during the overwrite prompt is a deliberate cancel — exit 0.\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to pull environment variables: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ProjectNotLinkedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\nconst envBase = Command.make('env', {}, () => Effect.void);\n\n/** `gigadrive env` — manage environment variables for the linked app or an organization. */\nexport const envCommand = envBase.pipe(\n Command.withSubcommands([envListCommand, envSetCommand, envRmCommand, envPullCommand])\n);\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option } from 'effect';\nimport { EnvFileReadError, EnvFileWriteError } from '../errors';\nimport { serializeEnv, type EnvEntry } from '../lib/dotenv';\n\n// ---------------------------------------------------------------------------\n// EnvFileService\n//\n// Reads and writes local `.env` files (and maintains `.gitignore`). Files may\n// contain secrets (e.g. provisioned API credentials), so they are written with\n// mode 0o600, mirroring AuthStorageService.\n// ---------------------------------------------------------------------------\n\nexport class EnvFileService extends Effect.Service<EnvFileService>()('EnvFileService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n /** Whether a file exists at `filePath`. */\n const exists = Effect.fn('EnvFileService.exists')(function* (filePath: string) {\n return yield* fs\n .exists(filePath)\n .pipe(Effect.mapError(() => new EnvFileReadError({ message: `Failed to check whether ${filePath} exists` })));\n });\n\n /** Read a file's contents, returning `Option.none` when it does not exist. */\n const read = Effect.fn('EnvFileService.read')(function* (filePath: string) {\n const present = yield* exists(filePath);\n if (!present) return Option.none<string>();\n const contents = yield* fs\n .readFileString(filePath, 'utf8')\n .pipe(Effect.mapError(() => new EnvFileReadError({ message: `Failed to read ${filePath}` })));\n return Option.some(contents);\n });\n\n /** Serialize `entries` and write them to `filePath` with mode 0o600. */\n const write = Effect.fn('EnvFileService.write')(function* (\n filePath: string,\n entries: ReadonlyArray<EnvEntry>,\n opts?: { header?: string }\n ) {\n const dir = pathService.dirname(filePath);\n yield* fs\n .makeDirectory(dir, { recursive: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new EnvFileWriteError({ message: `Failed to create directory for ${filePath}`, cause: String(error) })\n )\n );\n yield* fs\n .writeFileString(filePath, serializeEnv(entries, opts), { mode: 0o600 })\n .pipe(\n Effect.mapError(\n (error) => new EnvFileWriteError({ message: `Failed to write ${filePath}`, cause: String(error) })\n )\n );\n // `mode` on writeFileString only applies when the file is created. Explicitly\n // tighten permissions so an overwritten file (which may hold a provisioned\n // API secret) is never left world/group-readable.\n yield* fs\n .chmod(filePath, 0o600)\n .pipe(\n Effect.mapError(\n (error) => new EnvFileWriteError({ message: `Failed to secure ${filePath}`, cause: String(error) })\n )\n );\n });\n\n /**\n * Ensure `entry` is present in `<dir>/.gitignore`, creating the file when\n * needed. Returns `true` when the entry was added, `false` when it was\n * already ignored.\n */\n const ensureGitignored = Effect.fn('EnvFileService.ensureGitignored')(function* (dir: string, entry: string) {\n const gitignorePath = pathService.join(dir, '.gitignore');\n const existing = yield* read(gitignorePath);\n const current = Option.getOrElse(existing, () => '');\n const alreadyIgnored = current.split('\\n').some((line) => line.trim() === entry);\n if (alreadyIgnored) {\n return false;\n }\n const separator = current.length > 0 && !current.endsWith('\\n') ? '\\n' : '';\n yield* fs\n .writeFileString(gitignorePath, `${current}${separator}${entry}\\n`)\n .pipe(\n Effect.mapError(\n (error) => new EnvFileWriteError({ message: 'Failed to update .gitignore', cause: String(error) })\n )\n );\n return true;\n });\n\n return { exists, read, write, ensureGitignored };\n }),\n}) {}\n","// ---------------------------------------------------------------------------\n// dotenv serialization helpers\n//\n// Pure functions (no I/O) for turning key/value pairs into `.env` file contents\n// and reading a few values back. Kept dependency-free so they are trivially unit\n// testable and can be reused by both `env pull` and `setup`.\n// ---------------------------------------------------------------------------\n\n/** A single environment entry to serialize. */\nexport interface EnvEntry {\n key: string;\n value: string;\n}\n\n/** Default header written at the top of a generated `.env` file. */\nexport const DEFAULT_ENV_HEADER = '# Generated by `gigadrive env pull` — do not edit by hand.';\n\n// Values matching this are safe to emit unquoted; anything else is double-quoted.\nconst UNQUOTED_SAFE = /^[A-Za-z0-9_.\\-/@:+]*$/;\n\n/**\n * Format a single value for a `.env` file. Identifier-like values (and the empty\n * string) are emitted verbatim; anything containing whitespace, quotes, `#`,\n * `=`, or control characters is double-quoted with escapes that standard dotenv\n * parsers reverse — so values round-trip.\n */\nexport const formatEnvValue = (value: string): string => {\n if (UNQUOTED_SAFE.test(value)) {\n return value;\n }\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t');\n return `\"${escaped}\"`;\n};\n\n/**\n * Serialize env entries into `.env` file contents with a leading header comment.\n * Entry order is preserved.\n */\nexport const serializeEnv = (entries: ReadonlyArray<EnvEntry>, opts?: { header?: string }): string => {\n const header = opts?.header ?? DEFAULT_ENV_HEADER;\n if (entries.length === 0) {\n return `${header}\\n`;\n }\n const body = entries.map((e) => `${e.key}=${formatEnvValue(e.value)}`).join('\\n');\n return `${header}\\n${body}\\n`;\n};\n\n/**\n * Parse `.env` file contents into a key→value map. Handles unquoted values and\n * double-quoted values with standard escapes; comment (`#`) and blank lines are\n * ignored. Intended for recovering a few known keys (e.g. `GIGADRIVE_CLIENT_ID`),\n * not as a full-fidelity dotenv parser.\n */\nexport const parseEnv = (content: string): Record<string, string> => {\n const result: Record<string, string> = {};\n for (const rawLine of content.split('\\n')) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) {\n continue;\n }\n const eq = line.indexOf('=');\n if (eq <= 0) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n let value = line.slice(eq + 1).trim();\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n // Single-pass decode: consume each backslash together with the character it\n // escapes, left to right. A sequential chain of `.replace()` calls would\n // mis-handle a literal backslash followed by n/r/t/\" (e.g. `C:\\\\new` after\n // escaping would decode `\\n` before collapsing `\\\\`).\n value = value.slice(1, -1).replace(/\\\\(\\\\|\"|n|r|t)/g, (_, ch: string) => {\n switch (ch) {\n case 'n':\n return '\\n';\n case 'r':\n return '\\r';\n case 't':\n return '\\t';\n case '\"':\n return '\"';\n default:\n return '\\\\';\n }\n });\n }\n result[key] = value;\n }\n return result;\n};\n","import { Config, Effect, Option } from 'effect';\nimport * as os from 'node:os';\nimport { parseEnv, type EnvEntry } from '../lib/dotenv';\nimport { ApiClientService } from './api-client';\nimport { DevCredentialsStore } from './dev-credentials-store';\n\n// ---------------------------------------------------------------------------\n// LocalCredentialsService\n//\n// Provisions least-privilege, application-scoped API credentials for local\n// development and returns them as `.env` entries (GIGADRIVE_CLIENT_ID /\n// GIGADRIVE_CLIENT_SECRET / GIGADRIVE_API_BASE_URL). The local app uses these\n// with the SDK's client-credentials provider to call the API as the application.\n//\n// Because a key secret is only returned once at creation, we cannot re-read it.\n// To avoid key sprawl we store the provisioned key's ID (in DevCredentialsStore)\n// and, on subsequent runs, either reuse the credentials already present in the\n// target file or rotate (revoke the old key, mint a new one).\n// ---------------------------------------------------------------------------\n\n/** Least-privilege default scopes for a local-dev key. */\nconst DEV_KEY_SCOPES = ['network:env_vars:read'];\n\nconst ApiBaseUrl = Config.string('GIGADRIVE_API_BASE_URL').pipe(Config.withDefault('https://api.gigadrive.network'));\n\nconst credentialEntries = (clientId: string, clientSecret: string, baseUrl: string): EnvEntry[] => [\n { key: 'GIGADRIVE_CLIENT_ID', value: clientId },\n { key: 'GIGADRIVE_CLIENT_SECRET', value: clientSecret },\n { key: 'GIGADRIVE_API_BASE_URL', value: baseUrl },\n];\n\nexport interface ProvisionInput {\n applicationId: string;\n /** Force a fresh key even when reusable credentials already exist. */\n rotate: boolean;\n /** Current contents of the target `.env` file, if any (used to reuse credentials). */\n existingContent?: string;\n}\n\nexport class LocalCredentialsService extends Effect.Service<LocalCredentialsService>()('LocalCredentialsService', {\n accessors: true,\n dependencies: [ApiClientService.Default, DevCredentialsStore.Default],\n\n effect: Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const store = yield* DevCredentialsStore;\n const baseUrl = yield* ApiBaseUrl;\n\n const keyName = (applicationId: string) => `cli-dev:${os.hostname()}:${applicationId}`;\n\n /**\n * Provision (or reuse) application-scoped credentials and return them as\n * `.env` entries. Reuses the credentials already in `existingContent` when\n * they match the stored key and `rotate` is not set; otherwise revokes any\n * previously provisioned key and mints a fresh one.\n */\n const provision = Effect.fn('LocalCredentialsService.provision')(function* (input: ProvisionInput) {\n const stored = yield* store.get(input.applicationId);\n const existing = input.existingContent ? parseEnv(input.existingContent) : {};\n const existingClientId = existing['GIGADRIVE_CLIENT_ID'];\n const existingClientSecret = existing['GIGADRIVE_CLIENT_SECRET'];\n\n const canReuse =\n !input.rotate &&\n existingClientId !== undefined &&\n existingClientSecret !== undefined &&\n Option.isSome(stored) &&\n stored.value.apiKeyId === existingClientId;\n\n if (canReuse) {\n return credentialEntries(existingClientId, existingClientSecret, baseUrl);\n }\n\n // Revoke the previously provisioned key (if any) to avoid sprawl. Best\n // effort: a key that was already deleted server-side must not block us.\n if (Option.isSome(stored)) {\n yield* apiClient\n .request((client) => client.apiKeys.delete(stored.value.apiKeyId))\n .pipe(Effect.catchTag('ApiRequestError', () => Effect.void));\n }\n\n const created = yield* apiClient.request((client) =>\n client.apiKeys.create({\n name: keyName(input.applicationId),\n applicationId: input.applicationId,\n scopes: DEV_KEY_SCOPES,\n })\n );\n\n yield* store.set(input.applicationId, { apiKeyId: created.id });\n\n return credentialEntries(created.id, created.secret, baseUrl);\n });\n\n return { provision };\n }),\n}) {}\n","import { FileSystem, Path } from '@effect/platform';\nimport { Effect, Option, Schema } from 'effect';\nimport * as os from 'node:os';\nimport type { DevKeyEntry, DevKeyStore } from '../domain';\nimport { DevKeyStore as DevKeyStoreSchema } from '../domain';\nimport { DevCredentialsStoreReadError, DevCredentialsStoreWriteError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// DevCredentialsStore\n//\n// Persists, per user/machine, the ID of the API key the CLI provisioned for\n// local development, keyed by application ID. Lives at\n// `~/.gigadrive/dev-keys.json` (mode 0o600, in the 0o700 dir). Only the key ID\n// is stored — never the secret.\n// ---------------------------------------------------------------------------\n\nexport class DevCredentialsStore extends Effect.Service<DevCredentialsStore>()('DevCredentialsStore', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const homeDir = os.homedir();\n const storeDir = pathService.join(homeDir, '.gigadrive');\n const storeFile = pathService.join(storeDir, 'dev-keys.json');\n\n const ensureDirectory = Effect.gen(function* () {\n yield* fs\n .makeDirectory(storeDir, { recursive: true })\n .pipe(\n Effect.mapError(\n (error) =>\n new DevCredentialsStoreWriteError({ message: 'Failed to create ~/.gigadrive', cause: String(error) })\n )\n );\n yield* fs.chmod(storeDir, 0o700).pipe(\n Effect.mapError(\n (error) =>\n new DevCredentialsStoreWriteError({\n message: 'Failed to set ~/.gigadrive permissions',\n cause: String(error),\n })\n )\n );\n });\n\n const load = Effect.gen(function* () {\n const present = yield* fs\n .exists(storeFile)\n .pipe(Effect.mapError(() => new DevCredentialsStoreReadError({ message: 'Failed to check dev-keys.json' })));\n if (!present) return {};\n\n const data = yield* fs\n .readFileString(storeFile, 'utf8')\n .pipe(Effect.mapError(() => new DevCredentialsStoreReadError({ message: 'Failed to read dev-keys.json' })));\n\n const json = yield* Effect.try({\n try: () => JSON.parse(data) as unknown,\n catch: () => new DevCredentialsStoreReadError({ message: 'dev-keys.json contains invalid JSON' }),\n });\n\n return yield* Schema.decodeUnknown(DevKeyStoreSchema)(json).pipe(\n Effect.mapError(() => new DevCredentialsStoreReadError({ message: 'dev-keys.json has an invalid schema' }))\n );\n });\n\n /** Look up the stored dev-key entry for an application. */\n const get = Effect.fn('DevCredentialsStore.get')(function* (applicationId: string) {\n const store = yield* load;\n const entry = store[applicationId];\n return entry ? Option.some(entry) : Option.none<DevKeyEntry>();\n });\n\n /** Record the provisioned key ID for an application. */\n const set = Effect.fn('DevCredentialsStore.set')(function* (applicationId: string, entry: DevKeyEntry) {\n const store = yield* load;\n const next: DevKeyStore = { ...store, [applicationId]: entry };\n yield* ensureDirectory;\n yield* fs\n .writeFileString(storeFile, `${JSON.stringify(next, null, 2)}\\n`, { mode: 0o600 })\n .pipe(\n Effect.mapError(\n (error) =>\n new DevCredentialsStoreWriteError({ message: 'Failed to write dev-keys.json', cause: String(error) })\n )\n );\n });\n\n return { get, set };\n }),\n}) {}\n","import { Command, Options, Prompt } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApplicationNotFoundError, NoApplicationsFoundError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Application ID to link (skips the interactive picker)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Only list applications belonging to this organization ID'),\n Options.optional\n);\n\n/**\n * `gigadrive link` — associate the current directory with an application by\n * writing `.gigadrive/project.json`. Deploy and the resource commands read it.\n */\nexport const linkCommand = Command.make('link', { app: appOption, org: orgOption }, ({ app, org }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const projectLink = yield* ProjectLinkService;\n const cwd = process.cwd();\n\n const organizationId = Option.getOrUndefined(org);\n const { items: apps } = yield* apiClient.request((client) => client.applications.list({ organizationId }));\n\n if (apps.length === 0) {\n return yield* Effect.fail(\n new NoApplicationsFoundError({\n message: 'No applications found. Create one in the Gigadrive console, then run \"gigadrive link\" again.',\n })\n );\n }\n\n const explicitAppId = Option.getOrUndefined(app);\n\n let applicationId: string;\n let linkedOrganizationId: string | undefined;\n\n if (explicitAppId !== undefined) {\n const match = apps.find((a) => a.id === explicitAppId);\n if (match === undefined) {\n return yield* Effect.fail(\n new ApplicationNotFoundError({\n message: `Application \"${explicitAppId}\" was not found among your applications.`,\n })\n );\n }\n applicationId = match.id;\n linkedOrganizationId = match.organization.id;\n } else if (apps.length === 1) {\n applicationId = apps[0].id;\n linkedOrganizationId = apps[0].organization.id;\n } else {\n const chosen = yield* Prompt.run(\n Prompt.select({\n message: 'Select an application to link',\n choices: apps.map((a) => ({ title: `${a.name} (${a.organization.name})`, value: a })),\n })\n );\n applicationId = chosen.id;\n linkedOrganizationId = chosen.organization.id;\n }\n\n yield* projectLink.save(cwd, { applicationId, organizationId: linkedOrganizationId });\n\n yield* Console.log(`Linked this directory to application ${applicationId}.`);\n yield* Console.log('Tip: add \".gigadrive/\" to your .gitignore.');\n }).pipe(\n Effect.catchTags({\n // Ctrl+C during the picker is a deliberate cancel — exit 0.\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Failed to list applications: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n NoApplicationsFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ApplicationNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\n/** `gigadrive unlink` — remove the current directory's `.gigadrive/project.json`. */\nexport const unlinkCommand = Command.make('unlink', {}, () =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n yield* projectLink.remove(process.cwd());\n yield* Console.log('Unlinked this directory.');\n }).pipe(\n Effect.catchTags({\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { AuthService } from '../../services/auth';\n\nexport const loginCommand = Command.make('login', {}, () =>\n Effect.gen(function* () {\n yield* Console.log('Initiating login...');\n\n const auth = yield* AuthService;\n yield* auth.login;\n\n const info = yield* auth.getUserInfo.pipe(Effect.catchAll(() => Effect.succeed({})));\n\n const name = auth.inferUserName(info);\n yield* Console.log(`You are now logged in as ${name}.`);\n }).pipe(\n Effect.catchTags({\n LoginFlowError: (err: { message: string }) => Console.error(err.message),\n DeviceAuthorizationError: (err: { message: string }) => Console.error(`Login failed: ${err.message}`),\n AuthorizationDeniedError: (err: { message: string }) => Console.error(err.message),\n DeviceCodeExpiredError: (err: { message: string }) => Console.error(err.message),\n TokenExchangeError: (err: { message: string }) => Console.error(`Login failed: ${err.message}`),\n OAuthDiscoveryError: (err: { message: string }) => Console.error(`Login failed: ${err.message}`),\n AuthStorageWriteError: (err: { message: string }) => Console.error(`Failed to save credentials: ${err.message}`),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { AuthService } from '../../services/auth';\n\n/** `gigadrive logout` — clear stored credentials (`~/.gigadrive/auth.json`). */\nexport const logoutCommand = Command.make('logout', {}, () =>\n Effect.gen(function* () {\n const auth = yield* AuthService;\n yield* auth.logout;\n yield* Console.log('Logged out.');\n }).pipe(\n Effect.catchTags({\n AuthStorageWriteError: (err) =>\n Console.error(`Failed to log out: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Effect } from 'effect';\nimport { deployCommand } from './deploy';\n\nconst platformBase = Command.make('platform', {}, () => Effect.void);\n\nexport const platformCommand = platformBase.pipe(Command.withSubcommands([deployCommand]));\n","import { Command, Options, Prompt } from '@effect/cli';\nimport { FileSystem, Path } from '@effect/platform';\nimport { formatFileSize } from '@gigadrive/commons';\nimport { Console, Duration, Effect, Option, Schedule, Stream } from 'effect';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { DeploymentId, DeploymentLog, DeploymentStatus } from '../../../domain';\nimport { DeploymentFailedError, NoOrganizationsFoundError, UploadPartError } from '../../../errors';\nimport { ApiClientService } from '../../../services/api-client';\nimport { ArchiveService } from '../../../services/archive';\nimport { DeploymentApiService } from '../../../services/deployment-api';\nimport { ProjectConfigService } from '../../../services/project-config';\nimport { ProjectLinkService } from '../../../services/project-link';\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Application ID to deploy to (overrides the linked application)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Organization ID to use when automatically creating an application'),\n Options.optional\n);\n\nconst nameOption = Options.text('name').pipe(\n Options.withAlias('n'),\n Options.withDescription('Application name to use when automatically creating an application'),\n Options.optional\n);\n\ninterface DeploymentApplicationInput {\n app: Option.Option<string>;\n org: Option.Option<string>;\n name: Option.Option<string>;\n cwd: string;\n}\n\nconst createAndLinkDeploymentApplication = (input: DeploymentApplicationInput) =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const apiClient = yield* ApiClientService;\n const { items: organizations } = yield* apiClient.request((client) => client.organizations.list());\n const availableOrganizations = Option.match(input.org, {\n onNone: () => organizations,\n onSome: (organizationId) => organizations.filter((organization) => organization.id === organizationId),\n });\n\n if (availableOrganizations.length === 0) {\n return yield* new NoOrganizationsFoundError({\n message: Option.match(input.org, {\n onNone: () =>\n 'No organization is available for this deployment. Create an organization, then run \"gigadrive deploy\" again.',\n onSome: (organizationId) => `Organization \"${organizationId}\" was not found among your organizations.`,\n }),\n });\n }\n\n const organization =\n availableOrganizations.length === 1\n ? availableOrganizations[0]\n : yield* Prompt.run(\n Prompt.select({\n message: 'Select an organization for this application',\n choices: availableOrganizations.map((candidate) => ({\n title: candidate.name,\n value: candidate,\n })),\n })\n );\n\n const inferredName = path.basename(input.cwd) || 'Application';\n const applicationName = Option.match(input.name, {\n onNone: () => inferredName,\n onSome: (name) => name,\n }).trim();\n const application = yield* apiClient.request((client) =>\n client.applications.create({\n organizationId: organization.id,\n name: applicationName || inferredName,\n })\n );\n\n yield* projectLink.save(input.cwd, {\n applicationId: application.id,\n organizationId: organization.id,\n });\n yield* Console.log(`Created and linked application ${application.name} (${application.id}).`);\n return application.id;\n });\n\nconst resolveLinkedDeploymentApplication = (input: DeploymentApplicationInput) =>\n Effect.gen(function* () {\n const projectLink = yield* ProjectLinkService;\n const existingLink = yield* projectLink.load(input.cwd);\n return yield* Option.match(existingLink, {\n onNone: () => createAndLinkDeploymentApplication(input),\n onSome: (link) => Effect.succeed(link.applicationId),\n });\n });\n\n/**\n * Resolves the application for a deployment, automatically creating and\n * linking one when the current directory has no project link.\n *\n * An explicit application ID always wins. Otherwise an existing local link is\n * reused. For a new project, the authenticated actor's sole organization is\n * selected automatically; multiple organizations trigger an interactive\n * picker unless `--org` identifies one. The created link makes subsequent\n * deploys non-interactive.\n *\n * @param input - Command options and the current project directory.\n * @returns The application UUID that should own the deployment.\n */\nexport const resolveDeploymentApplication = (input: DeploymentApplicationInput) =>\n Option.match(input.app, {\n onNone: () => resolveLinkedDeploymentApplication(input),\n onSome: Effect.succeed,\n });\n\nexport const deployCommand = Command.make(\n 'deploy',\n { app: appOption, org: orgOption, name: nameOption },\n ({ app, org, name }) =>\n Effect.gen(function* () {\n const projectConfig = yield* ProjectConfigService;\n const deploymentApi = yield* DeploymentApiService;\n const archiveService = yield* ArchiveService;\n const pathService = yield* Path.Path;\n\n const cwd = process.cwd();\n\n // Resolve and validate config\n yield* Effect.log('Starting deploy command');\n const { config } = yield* projectConfig.resolve(cwd);\n\n const applicationId = yield* resolveDeploymentApplication({ app, org, name, cwd });\n\n // Create deployment\n yield* Console.log('Creating deployment...');\n const deploymentId = yield* deploymentApi.createDeployment(applicationId);\n yield* Console.log(`Deployment ID: ${deploymentId}`);\n\n // Create and upload archive\n yield* Console.log('Creating archive...');\n const archivePath = pathService.join(os.tmpdir(), `project-${Date.now()}.zip`);\n const archive = yield* archiveService.createZipArchive(config.userArchive?.rootOverwrite || cwd, archivePath, {\n whitelist: config.userArchive?.fileWhitelist,\n excludeFiles: config.excludeFiles,\n buildsContainerImages: [\n ...config.entrypoints.flatMap((entrypoint) => (entrypoint.container ? [entrypoint.container] : [])),\n ...(config.sidecars ?? []),\n ].some((container) => container.source.type === 'dockerfile'),\n });\n yield* Console.log(`Archive created (${formatFileSize(archive.size)})`);\n\n // Upload archive\n yield* Console.log('Uploading archive...');\n yield* uploadArchive(deploymentId, archivePath, archive.size);\n yield* Console.log('Upload complete.');\n yield* Console.log('The deployment pipeline is now being provisioned. This may take a few seconds.');\n\n // Poll for status and logs\n yield* pollDeployment(deploymentId);\n }).pipe(\n Effect.catchTags({\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) =>\n Console.error(`Application setup failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n NoOrganizationsFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ConfigNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ConfigParseError: (err) =>\n Console.error(`Config parse error: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ConfigValidationError: (err) =>\n Effect.gen(function* () {\n for (const e of err.errors) {\n yield* Console.error(e);\n }\n yield* Console.error(err.message);\n }).pipe(Effect.andThen(Effect.fail(err))),\n DeploymentCreateError: (err) =>\n Console.error(`Deployment creation failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n ArchiveCreateError: (err) =>\n Console.error(`Archive creation failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n UploadStartError: (err) =>\n Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n UploadPartError: (err) => Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n UploadCompleteError: (err) =>\n Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n PresignedUrlError: (err) =>\n Console.error(`Upload failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n DeploymentAuthError: (err) =>\n Console.error(`Authentication failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n DeploymentFailedError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n\n// ---------------------------------------------------------------------------\n// Upload archive helper\n// ---------------------------------------------------------------------------\n\nconst uploadArchive = (deploymentId: DeploymentId, archivePath: string, fileSize: number) =>\n Effect.gen(function* () {\n const deploymentApi = yield* DeploymentApiService;\n const fs = yield* FileSystem.FileSystem;\n\n const uploadId = yield* deploymentApi.startMultipartUpload(deploymentId);\n\n const FILE_CHUNK_SIZE = 10 * 1024 * 1024; // 10 MB\n const numChunks = Math.ceil(fileSize / FILE_CHUNK_SIZE);\n\n yield* Effect.log('Starting multipart upload', { uploadId, numChunks, fileSize });\n\n // Upload all chunks — each chunk is streamed from disk independently\n const parts = yield* Effect.all(\n Array.from({ length: numChunks }, (_, i) => {\n const partNumber = i + 1;\n const start = i * FILE_CHUNK_SIZE;\n const bytesToRead = partNumber < numChunks ? FILE_CHUNK_SIZE : fileSize - start;\n\n return Effect.gen(function* () {\n const presignedUrl = yield* deploymentApi.getPresignedUrl(deploymentId, uploadId, partNumber);\n\n // Stream only this chunk from disk to keep memory bounded\n const chunkData = yield* Stream.runCollect(fs.stream(archivePath, { offset: start, bytesToRead })).pipe(\n Effect.map((chunks) => {\n const arrays = Array.from(chunks);\n return Buffer.concat(arrays);\n }),\n Effect.mapError(\n (error) =>\n new UploadPartError({\n message: `Failed to read chunk ${partNumber}: ${String(error)}`,\n partNumber,\n })\n )\n );\n\n yield* Effect.log(`Uploading part ${partNumber}/${numChunks}`, { size: chunkData.length });\n return yield* deploymentApi.uploadPart(presignedUrl, chunkData, partNumber);\n });\n }),\n { concurrency: 3 }\n );\n\n yield* deploymentApi.completeUpload(deploymentId, uploadId, parts);\n });\n\n// ---------------------------------------------------------------------------\n// Poll deployment status + logs\n// ---------------------------------------------------------------------------\n\nconst pollDeployment = (deploymentId: DeploymentId) =>\n Effect.gen(function* () {\n const deploymentApi = yield* DeploymentApiService;\n let lastStatus: DeploymentStatus = 'PENDING';\n let logOffset = 0;\n\n yield* Console.log('Status: Pending');\n\n // Poll in a loop until terminal status\n yield* Effect.repeat(\n Effect.gen(function* () {\n // Check status\n const newStatus = yield* deploymentApi\n .getDeploymentStatus(deploymentId)\n .pipe(Effect.catchTag('DeploymentStatusError', () => Effect.succeed(lastStatus)));\n\n if (newStatus !== lastStatus) {\n lastStatus = newStatus;\n const label = newStatus.charAt(0) + newStatus.slice(1).toLowerCase();\n yield* Console.log(`Status: ${label}`);\n }\n\n // Fetch logs\n const logsPage = yield* deploymentApi\n .getLogs(deploymentId, { offset: logOffset, limit: 100 })\n .pipe(Effect.catchTag('DeploymentLogsFetchError', () => Effect.succeed(null)));\n\n if (logsPage) {\n for (const logEntry of logsPage.items) {\n logOffset++;\n yield* printLog(logEntry);\n }\n }\n\n // Check terminal states\n if (newStatus === 'ACTIVE') {\n // Print the real per-deployment `*.gigadrive.app` hostname. Hostname\n // lookup is best-effort — a failure here must not fail a successful deploy.\n const hostnames = yield* deploymentApi\n .getHostnames(deploymentId)\n .pipe(Effect.catchTag('DeploymentHostnamesFetchError', () => Effect.succeed([])));\n const active = hostnames.find((h) => h.active) ?? hostnames.at(0);\n if (active) {\n yield* Console.log(`Deployed to https://${active.hostname}`);\n } else {\n yield* Console.log('Deployment is live.');\n }\n return yield* Effect.fail('done' as const);\n }\n\n if (newStatus === 'FAILED') {\n return yield* Effect.fail(\n new DeploymentFailedError({\n message: 'The deployment failed. Please check the logs for more information.',\n })\n );\n }\n }),\n Schedule.addDelay(Schedule.forever, () => Duration.seconds(1))\n ).pipe(\n Effect.catchAll((err) => {\n if (err === 'done') return Effect.void;\n return Effect.fail(err);\n })\n );\n });\n\nconst printLog = (logEntry: DeploymentLog) => {\n switch (logEntry.type) {\n case 'ERROR':\n return Console.error(logEntry.message);\n case 'WARN':\n return Console.warn(logEntry.message);\n default:\n return Console.log(logEntry.message);\n }\n};\n","import { FileSystem, Path } from '@effect/platform';\nimport { getFilesForPattern } from '@gigadrive/build-utils';\nimport archiver from 'archiver';\nimport { Effect } from 'effect';\nimport ignore, { type Ignore } from 'ignore';\nimport * as nodeFs from 'node:fs';\nimport * as nodeFsPromises from 'node:fs/promises';\nimport { ArchiveCreateError } from '../errors';\n\n// ---------------------------------------------------------------------------\n// Ignore file handling\n// ---------------------------------------------------------------------------\n\nconst IGNORE_FILE_NAMES = ['.gitignore', '.dockerignore', '.nowignore', '.vercelignore', '.gigadriveignore'];\n\nconst MANAGED_IGNORE_PATTERNS = [\n '.git/',\n '**/.git/',\n 'node_modules/',\n '**/node_modules/',\n '**/.DS_Store',\n '**/Thumbs.db',\n];\n\n/**\n * Container build inputs that stay in the archive whatever the ignore files\n * say. Docker sends a Dockerfile even when `.dockerignore` lists it, and that\n * file, like a Compose file, is commonly listed there.\n */\nconst CONTAINER_BUILD_FILE_PATTERNS = [\n '!Dockerfile',\n '!**/Dockerfile',\n '!**/*.Dockerfile',\n '!**/Dockerfile.*',\n '!compose.yaml',\n '!compose.yml',\n '!docker-compose.yaml',\n '!docker-compose.yml',\n];\n\n/**\n * `.dockerignore` filters a Docker build context, which BuildKit reads on the\n * server. Applied here with gitignore semantics it would also drop files a\n * Dockerfile copies: Docker anchors its patterns at the context root and\n * allow-lists such as `*` then `!src` exclude more here than there.\n */\nconst DOCKER_BUILD_IGNORE_FILE = '.dockerignore';\n\nconst readIgnoreFile = (fs: FileSystem.FileSystem, ignorePath: string): Effect.Effect<string[]> =>\n fs.readFileString(ignorePath, 'utf8').pipe(\n Effect.map((content) => content.split('\\n').filter((line: string) => line.trim() !== '')),\n Effect.catchAll(() => Effect.succeed([] as string[]))\n );\n\nconst collectIgnorePatterns = (\n fs: FileSystem.FileSystem,\n pathService: Path.Path,\n dir: string,\n baseDir: string,\n ignoreRules: Ignore,\n ignoreFileNames: readonly string[]\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const items = yield* fs\n .readDirectory(dir)\n .pipe(Effect.mapError(() => new ArchiveCreateError({ message: `Failed to read directory: ${dir}` })));\n\n for (const item of items) {\n const fullPath = pathService.join(dir, item);\n const relativePath = pathService.relative(baseDir, fullPath);\n // Use lstat to avoid following symlinks (matches original behavior)\n const stat = yield* Effect.tryPromise({\n try: () => nodeFsPromises.lstat(fullPath),\n catch: () => new ArchiveCreateError({ message: `Failed to stat: ${fullPath}` }),\n });\n\n if (stat.isDirectory()) {\n if (ignoreRules.ignores(`${relativePath}/`)) continue;\n\n for (const ignoreFileName of ignoreFileNames) {\n const ignoreFilePath = pathService.join(fullPath, ignoreFileName);\n const patterns = yield* readIgnoreFile(fs, ignoreFilePath);\n if (patterns.length > 0) {\n ignoreRules.add(\n patterns.map((pattern: string) =>\n pattern.startsWith('!')\n ? `!${pathService.join(relativePath, pattern.slice(1))}`\n : pathService.join(relativePath, pattern)\n )\n );\n }\n }\n\n yield* collectIgnorePatterns(fs, pathService, fullPath, baseDir, ignoreRules, ignoreFileNames);\n }\n }\n }).pipe(Effect.catchAll(() => Effect.void));\n\nconst initializeIgnoreRules = (\n fs: FileSystem.FileSystem,\n pathService: Path.Path,\n baseDir: string,\n useIgnoreFiles: boolean,\n useManagedIgnore: boolean,\n buildsContainerImages: boolean\n): Effect.Effect<Ignore> =>\n Effect.gen(function* () {\n const ignoreRules = ignore();\n const ignoreFileNames = buildsContainerImages\n ? IGNORE_FILE_NAMES.filter((name) => name !== DOCKER_BUILD_IGNORE_FILE)\n : IGNORE_FILE_NAMES;\n if (useManagedIgnore) {\n ignoreRules.add(MANAGED_IGNORE_PATTERNS);\n }\n\n if (useIgnoreFiles) {\n for (const ignoreFileName of ignoreFileNames) {\n const ignoreFilePath = pathService.join(baseDir, ignoreFileName);\n const patterns = yield* readIgnoreFile(fs, ignoreFilePath);\n if (patterns.length > 0) {\n ignoreRules.add(\n patterns.map((pattern: string) => (pattern.startsWith('!') ? `!${pattern.slice(1)}` : pattern))\n );\n }\n }\n\n yield* collectIgnorePatterns(fs, pathService, baseDir, baseDir, ignoreRules, ignoreFileNames);\n ignoreRules.add(CONTAINER_BUILD_FILE_PATTERNS);\n }\n return ignoreRules;\n });\n\nconst getFilesToInclude = (\n fs: FileSystem.FileSystem,\n pathService: Path.Path,\n dir: string,\n ignoreRules: Ignore\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const filesToInclude: string[] = [];\n\n const walkDir = (currentDir: string): Effect.Effect<void> =>\n Effect.gen(function* () {\n const items = yield* fs\n .readDirectory(currentDir)\n .pipe(Effect.mapError(() => new ArchiveCreateError({ message: `Failed to read directory: ${currentDir}` })));\n\n for (const item of items) {\n const fullPath = pathService.join(currentDir, item);\n const relativePath = pathService.relative(dir, fullPath);\n // Use lstat to avoid following symlinks (matches original behavior)\n const stat = yield* Effect.tryPromise({\n try: () => nodeFsPromises.lstat(fullPath),\n catch: () => new ArchiveCreateError({ message: `Failed to stat: ${fullPath}` }),\n });\n\n if (stat.isDirectory()) {\n if (!ignoreRules.ignores(`${relativePath}/`)) {\n yield* walkDir(fullPath);\n }\n } else {\n if (!ignoreRules.ignores(relativePath)) {\n filesToInclude.push(fullPath);\n }\n }\n }\n }).pipe(Effect.catchAll(() => Effect.void));\n\n yield* walkDir(dir);\n return filesToInclude;\n });\n\n// ---------------------------------------------------------------------------\n// ArchiveService\n// ---------------------------------------------------------------------------\n\nexport class ArchiveService extends Effect.Service<ArchiveService>()('ArchiveService', {\n accessors: true,\n\n effect: Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const pathService = yield* Path.Path;\n\n const createZipArchive = Effect.fn('ArchiveService.createZipArchive')(function* (\n inputDir: string,\n outputFile: string,\n options: {\n whitelist?: string[];\n excludeFiles?: string[];\n useIgnoreFiles?: boolean;\n useManagedIgnore?: boolean;\n /** The deployment builds Dockerfiles, so `.dockerignore` is left to BuildKit. */\n buildsContainerImages?: boolean;\n } = {}\n ) {\n yield* Effect.annotateCurrentSpan('inputDir', inputDir);\n yield* Effect.annotateCurrentSpan('outputFile', outputFile);\n yield* Effect.log('Creating zip archive', { inputDir, outputFile });\n\n const ignoreRules = yield* initializeIgnoreRules(\n fs,\n pathService,\n inputDir,\n options.useIgnoreFiles !== false,\n options.useManagedIgnore !== false,\n options.buildsContainerImages === true\n );\n\n const filesToInclude = options.whitelist\n ? yield* Effect.tryPromise({\n try: () =>\n Promise.all(\n options.whitelist!.map((file) => getFilesForPattern(file, inputDir, options.excludeFiles ?? []))\n ),\n catch: (error) =>\n new ArchiveCreateError({\n message: 'Failed to resolve whitelist patterns',\n cause: error instanceof Error ? error.message : String(error),\n }),\n })\n : yield* Effect.gen(function* () {\n // Add excludeFiles patterns (from framework detection or user config) to ignore rules\n if (options.excludeFiles && options.excludeFiles.length > 0) {\n ignoreRules.add(options.excludeFiles);\n }\n return yield* getFilesToInclude(fs, pathService, inputDir, ignoreRules).pipe(\n Effect.map((files) => [files])\n );\n });\n\n // Remove existing archive if present\n const archiveExists = yield* fs.exists(outputFile).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (archiveExists) {\n yield* fs.remove(outputFile).pipe(\n Effect.mapError(\n (error) =>\n new ArchiveCreateError({\n message: `Failed to remove existing archive: ${String(error)}`,\n })\n )\n );\n }\n\n yield* Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n // archiver requires a Node.js writable stream\n const output = nodeFs.createWriteStream(outputFile);\n const archive = archiver('zip', { zlib: { level: 9 } });\n\n output.on('close', () => resolve());\n output.on('error', reject);\n archive.on('error', reject);\n archive.pipe(output);\n\n for (const file of filesToInclude.flat()) {\n archive.file(file, { name: pathService.relative(inputDir, file) });\n }\n\n void archive.finalize();\n }),\n catch: (error) =>\n new ArchiveCreateError({\n message: 'Failed to create zip archive',\n cause: error instanceof Error ? error.message : String(error),\n }),\n });\n\n const fileInfo = yield* fs.stat(outputFile).pipe(\n Effect.mapError(\n (error) =>\n new ArchiveCreateError({\n message: `Failed to stat archive: ${String(error)}`,\n })\n )\n );\n const size = Number(fileInfo.size);\n yield* Effect.log('Archive created', { size });\n\n return { path: outputFile, size };\n });\n\n return { createZipArchive };\n }),\n}) {}\n","import { Effect } from 'effect';\nimport type { DeploymentId, UploadId } from '../domain';\nimport {\n DeploymentAuthError,\n DeploymentCreateError,\n DeploymentHostnamesFetchError,\n DeploymentLogsFetchError,\n DeploymentStatusError,\n PresignedUrlError,\n UploadCompleteError,\n UploadPartError,\n UploadStartError,\n} from '../errors';\nimport { ApiClientService } from './api-client';\n\n// ---------------------------------------------------------------------------\n// DeploymentApiService\n//\n// A thin, deployment-focused wrapper over the shared ApiClientService. It keeps\n// its own tagged errors (DeploymentAuthError, UploadPartError, …) so the deploy\n// command's error handling and spans are unchanged.\n// ---------------------------------------------------------------------------\n\nexport class DeploymentApiService extends Effect.Service<DeploymentApiService>()('DeploymentApiService', {\n accessors: true,\n dependencies: [ApiClientService.Default],\n\n effect: Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n\n const getClient = apiClient.getClient.pipe(\n Effect.mapError((err) => new DeploymentAuthError({ message: `Authentication failed: ${err.message}` }))\n );\n\n const createDeployment = Effect.fn('DeploymentApiService.createDeployment')(function* (applicationId: string) {\n yield* Effect.annotateCurrentSpan('applicationId', applicationId);\n yield* Effect.log('Creating deployment', { applicationId });\n\n const client = yield* getClient;\n const deployment = yield* Effect.tryPromise({\n try: () => client.deployments.create({ applicationId }),\n catch: (error) =>\n new DeploymentCreateError({\n message: `Failed to create deployment: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n yield* Effect.log('Deployment created', { deploymentId: deployment.id });\n return deployment.id as DeploymentId;\n });\n\n const startMultipartUpload = Effect.fn('DeploymentApiService.startMultipartUpload')(function* (\n deploymentId: DeploymentId\n ) {\n yield* Effect.annotateCurrentSpan('deploymentId', deploymentId);\n\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.startUpload(deploymentId),\n catch: (error) =>\n new UploadStartError({\n message: `Failed to start multipart upload: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return result.uploadId as UploadId;\n });\n\n const getPresignedUrl = Effect.fn('DeploymentApiService.getPresignedUrl')(function* (\n deploymentId: DeploymentId,\n uploadId: UploadId,\n partNumber: number\n ) {\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.getPresignedUrl(deploymentId, uploadId, partNumber),\n catch: (error) =>\n new PresignedUrlError({\n message: `Failed to get presigned URL: ${error instanceof Error ? error.message : String(error)}`,\n partNumber,\n }),\n });\n\n return result.url;\n });\n\n const uploadPart = Effect.fn('DeploymentApiService.uploadPart')(function* (\n presignedUrl: string,\n data: Buffer,\n partNumber: number\n ) {\n yield* Effect.annotateCurrentSpan('partNumber', partNumber);\n yield* Effect.annotateCurrentSpan('size', data.length);\n\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.uploadPart(presignedUrl, data, partNumber),\n catch: (error) =>\n new UploadPartError({\n message: `Failed to upload part ${partNumber}: ${error instanceof Error ? error.message : String(error)}`,\n partNumber,\n }),\n });\n\n return result;\n });\n\n const completeUpload = Effect.fn('DeploymentApiService.completeUpload')(function* (\n deploymentId: DeploymentId,\n uploadId: UploadId,\n parts: Array<{ partNumber: number; etag: string }>\n ) {\n yield* Effect.annotateCurrentSpan('deploymentId', deploymentId);\n yield* Effect.annotateCurrentSpan('partsCount', parts.length);\n\n const client = yield* getClient;\n yield* Effect.tryPromise({\n try: () => client.deployments.completeUpload(deploymentId, uploadId, parts),\n catch: (error) =>\n new UploadCompleteError({\n message: `Failed to complete upload: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n yield* Effect.log('Upload completed successfully');\n });\n\n const getDeploymentStatus = Effect.fn('DeploymentApiService.getDeploymentStatus')(function* (\n deploymentId: DeploymentId\n ) {\n const client = yield* getClient;\n const deployment = yield* Effect.tryPromise({\n try: () => client.deployments.get(deploymentId),\n catch: (error) =>\n new DeploymentStatusError({\n message: `Failed to get deployment status: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return deployment.status;\n });\n\n const getLogs = Effect.fn('DeploymentApiService.getLogs')(function* (\n deploymentId: DeploymentId,\n options?: { offset: number; limit: number; 'createdAt[gt]'?: string }\n ) {\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.getLogs(deploymentId, options),\n catch: (error) =>\n new DeploymentLogsFetchError({\n message: `Failed to get logs: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return result;\n });\n\n const getHostnames = Effect.fn('DeploymentApiService.getHostnames')(function* (deploymentId: DeploymentId) {\n const client = yield* getClient;\n const result = yield* Effect.tryPromise({\n try: () => client.deployments.getHostnames(deploymentId),\n catch: (error) =>\n new DeploymentHostnamesFetchError({\n message: `Failed to get hostnames: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\n\n return result.items;\n });\n\n return {\n createDeployment,\n startMultipartUpload,\n getPresignedUrl,\n uploadPart,\n completeUpload,\n getDeploymentStatus,\n getLogs,\n getHostnames,\n };\n }),\n}) {}\n","import { Args, Command, Options, Prompt } from '@effect/cli';\nimport { Console, Effect, Option } from 'effect';\nimport { ApplicationNotFoundError, NoApplicationsFoundError } from '../../errors';\nimport { ApiClientService } from '../../services/api-client';\nimport { EnvFileService } from '../../services/env-file';\nimport { LocalCredentialsService } from '../../services/local-credentials';\nimport { ProjectLinkService } from '../../services/project-link';\n\nconst fileArg = Args.text({ name: 'file' }).pipe(\n Args.withDescription('Output file to write (default: .env.local)'),\n Args.optional\n);\n\nconst appOption = Options.text('app').pipe(\n Options.withAlias('a'),\n Options.withDescription('Application ID to set up (skips the interactive picker)'),\n Options.optional\n);\n\nconst orgOption = Options.text('org').pipe(\n Options.withAlias('o'),\n Options.withDescription('Only list applications belonging to this organization ID when picking'),\n Options.optional\n);\n\nconst environmentOption = Options.text('environment').pipe(\n Options.withAlias('e'),\n Options.withDescription('Environment slug to resolve overrides for (e.g. preview)'),\n Options.optional\n);\n\nconst yesOption = Options.boolean('yes').pipe(\n Options.withAlias('y'),\n Options.withDescription('Overwrite an existing file without confirmation')\n);\n\nconst rotateOption = Options.boolean('rotate').pipe(\n Options.withDescription('Force a fresh API key, revoking the previous one')\n);\n\n/**\n * `gigadrive setup` — one command to wire up a local dev environment: ensures the\n * directory is linked to an application (prompting if needed), pulls the\n * application's non-sensitive environment variables, provisions least-privilege\n * API credentials, and writes everything to `.env.local`.\n */\nexport const setupCommand = Command.make(\n 'setup',\n {\n file: fileArg,\n app: appOption,\n org: orgOption,\n environment: environmentOption,\n yes: yesOption,\n rotate: rotateOption,\n },\n ({ file, app, org, environment, yes, rotate }) =>\n Effect.gen(function* () {\n const apiClient = yield* ApiClientService;\n const projectLink = yield* ProjectLinkService;\n const envFile = yield* EnvFileService;\n const localCredentials = yield* LocalCredentialsService;\n const cwd = process.cwd();\n\n // 1. Ensure the directory is linked to an application.\n const existingLink = yield* projectLink.load(cwd);\n let applicationId: string;\n if (Option.isSome(existingLink)) {\n applicationId = existingLink.value.applicationId;\n // The picker (and thus --app/--org) is only consulted when unlinked.\n if (Option.isSome(app) || Option.isSome(org)) {\n yield* Console.log(\n `Note: this directory is already linked to ${applicationId}; ignoring --app/--org. Run \"gigadrive unlink\" first to target a different application.`\n );\n }\n } else {\n const organizationId = Option.getOrUndefined(org);\n const { items: apps } = yield* apiClient.request((client) => client.applications.list({ organizationId }));\n if (apps.length === 0) {\n return yield* Effect.fail(\n new NoApplicationsFoundError({\n message: 'No applications found. Create one in the Gigadrive console, then run \"gigadrive setup\" again.',\n })\n );\n }\n\n const explicitAppId = Option.getOrUndefined(app);\n let chosen: (typeof apps)[number];\n if (explicitAppId !== undefined) {\n const match = apps.find((a) => a.id === explicitAppId);\n if (match === undefined) {\n return yield* Effect.fail(\n new ApplicationNotFoundError({\n message: `Application \"${explicitAppId}\" was not found among your applications.`,\n })\n );\n }\n chosen = match;\n } else if (apps.length === 1) {\n chosen = apps[0];\n } else {\n chosen = yield* Prompt.run(\n Prompt.select({\n message: 'Select an application to set up',\n choices: apps.map((a) => ({ title: `${a.name} (${a.organization.name})`, value: a })),\n })\n );\n }\n\n applicationId = chosen.id;\n yield* projectLink.save(cwd, { applicationId, organizationId: chosen.organization.id });\n yield* Console.log(`Linked this directory to application ${applicationId}.`);\n }\n\n const target = Option.getOrElse(file, () => '.env.local');\n const environmentSlug = Option.getOrUndefined(environment);\n\n // 2. Pull the application's non-sensitive environment variables.\n const { items, omittedSensitive } = yield* apiClient.request((client) =>\n client.applications.envVars.pull(applicationId, environmentSlug ? { environment: environmentSlug } : undefined)\n );\n\n // 3. Confirm overwrite (reading first so credentials can be reused).\n const existing = yield* envFile.read(target);\n if (Option.isSome(existing) && !yes) {\n const overwrite = yield* Prompt.run(\n Prompt.confirm({ message: `${target} already exists. Overwrite?`, initial: false })\n );\n if (!overwrite) {\n return yield* Console.log('Cancelled.');\n }\n }\n\n // 4. Provision least-privilege API credentials.\n const credentialEntries = yield* localCredentials.provision({\n applicationId,\n rotate,\n existingContent: Option.getOrUndefined(existing),\n });\n\n // 5. Write the combined file and keep it out of git.\n const entries = [...items.map((v) => ({ key: v.key, value: v.value })), ...credentialEntries];\n yield* envFile.write(target, entries);\n const gitignored = yield* envFile.ensureGitignored(cwd, target);\n\n // 6. Print next steps.\n yield* Console.log('\\nLocal dev environment ready.');\n yield* Console.log(` • Wrote ${items.length} variable(s) and API credentials to ${target}.`);\n if (omittedSensitive > 0) {\n yield* Console.log(\n ` • Skipped ${omittedSensitive} sensitive variable(s) (only production/preview hold secrets).`\n );\n }\n if (gitignored) {\n yield* Console.log(` • Added ${target} to .gitignore.`);\n }\n yield* Console.log(' • Your app can now call the Gigadrive API via the SDK (GIGADRIVE_CLIENT_ID/SECRET).');\n }).pipe(\n Effect.catchTags({\n // Ctrl+C during a prompt is a deliberate cancel — exit 0.\n QuitException: () => Console.log('Cancelled.'),\n NotAuthenticatedError: (err) =>\n Console.error('You are not logged in. Run \"gigadrive login\" to authenticate.').pipe(\n Effect.andThen(Effect.fail(err))\n ),\n ApiRequestError: (err) => Console.error(`Setup failed: ${err.message}`).pipe(Effect.andThen(Effect.fail(err))),\n NoApplicationsFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ApplicationNotFoundError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n ProjectLinkWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n EnvFileWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreReadError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n DevCredentialsStoreWriteError: (err) => Console.error(err.message).pipe(Effect.andThen(Effect.fail(err))),\n })\n )\n);\n","import { Command } from '@effect/cli';\nimport { Console, Effect } from 'effect';\nimport { AuthService } from '../../services/auth';\n\nexport const whoamiCommand = Command.make('whoami', {}, () =>\n Effect.gen(function* () {\n const auth = yield* AuthService;\n const info = yield* auth.getUserInfo;\n yield* Console.log(JSON.stringify(info, null, 2));\n }).pipe(\n Effect.catchTags({\n NotAuthenticatedError: () => Console.log('You are not logged in. Run \"gigadrive login\" to authenticate.'),\n UserInfoFetchError: (err) => Console.error(`Failed to retrieve user info: ${err.message}`),\n OAuthDiscoveryError: (err) => Console.error(`Failed to retrieve user info: ${err.message}`),\n })\n )\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,eAAwB;AACxB,2BAAyC;AACzC,IAAAC,yBAAkC;AAClC,IAAAC,kBAAgD;;;ACHhD;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,SAAW;AAAA,EACX,QAAU;AAAA,EACV,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,KAAO;AAAA,IACL,WAAa;AAAA,IACb,IAAM;AAAA,EACR;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,OAAS;AAAA,IACT,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,cAAgB;AAAA,IACd,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,yBAAyB;AAAA,IACzB,0BAA0B;AAAA,IAC1B,sBAAsB;AAAA,IACtB,6BAA6B;AAAA,IAC7B,kBAAkB;AAAA,IAClB,UAAY;AAAA,IACZ,QAAU;AAAA,IACV,QAAU;AAAA,IACV,MAAQ;AAAA,EACV;AAAA,EACA,iBAAmB;AAA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sBAAM,SAAS,cAAc,uBAAO,gBAAgB,yBAAS,IAAI,CAAC,EAAE;AAAA,EAClF,sBAAM,aAAa,iCAAY,KAAK;AACtC;AAMA,iCAAY,QAAQ,uBAAO,QAAQ,IAAI,QAAQ,IAAI,GAAG,OAAO,CAAC;","names":["import_cli","import_network_config","import_effect","import_platform","import_effect","import_effect","import_effect","import_node_process","import_effect","process","import_effect","import_effect","process","open","import_platform","import_effect","path","import_cli","import_effect","import_cli","import_platform","import_build_utils","import_effect","import_platform","import_effect","pm","buildCommand","import_cli","import_effect","import_cli","import_effect","import_effect","import_cli","import_effect","appOption","orgOption","import_cli","import_effect","appOption","orgOption","statusOption","domain","hostname","import_cli","import_effect","import_platform","import_effect","import_effect","os","import_platform","import_effect","os","ApiBaseUrl","appOption","orgOption","yesOption","credentialEntries","import_cli","import_effect","appOption","orgOption","import_cli","import_effect","import_cli","import_effect","import_cli","import_effect","import_cli","import_platform","import_effect","os","import_platform","import_build_utils","import_effect","ignore","archiver","import_effect","appOption","orgOption","nameOption","organization","import_cli","import_effect","fileArg","appOption","orgOption","environmentOption","yesOption","rotateOption","credentialEntries","import_cli","import_effect"]}