@dashai/cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/config.ts","../src/lib/api-client.ts","../src/lib/manifest-io.ts","../src/lib/output.ts","../src/lib/scaffold.ts","../src/lib/workspaces.ts","../src/commands/module/init.ts","../src/commands/module/destroy-dev-install.ts","../src/commands/module/reset-dev-install.ts","../src/lib/schema-command-context.ts","../src/lib/field-spec.ts","../src/commands/table/create.ts","../src/commands/table/delete.ts","../src/commands/field/add.ts","../src/commands/field/remove.ts","../src/commands/field/set-type.ts","../src/commands/dev.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/profile.ts","../src/commands/workspace.ts","../src/commands/module/clone.ts","../src/commands/module/connect-git.ts","../src/commands/module/generate.ts","../src/commands/module/dev.ts","../src/commands/module/diff.ts","../src/bin.ts","../src/commands/module/list.ts","../src/commands/module/publish.ts","../src/lib/tarball.ts","../src/commands/module/pull-data.ts","../src/commands/module/validate.ts","../src/commands/deps/add.ts","../src/commands/deps/check.ts","../src/commands/deps/list.ts","../src/commands/deps/remove.ts","../src/commands/query.ts","../src/commands/module/query-log.ts","../src/commands/module/action-log.ts"],"names":["c","out","code","join","existsSync","readFileSync","writeFileSync","select","isCancel","intro","resolve","readdirSync","mkdirSync","outro","workspace","resolvePath","manifestPath","exitCode","text","rmSync","fsWatch","statSync","formatBytes","pathResolve","sleep","POLL_INTERVAL_MS","runTail","runOnce","msg","destroyDevInstallCommand","resetDevInstallCommand","tableCreateCommand","tableDeleteCommand","fieldAddCommand","fieldRemoveCommand","fieldSetTypeCommand"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+FO,SAAS,SAAA,GAAoB;AAClC,EAAA,IAAI,OAAA,CAAQ,IAAI,eAAA,EAAiB;AAC/B,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI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D,YAAY;AACX,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,UAAA,CAAW,OAAA,CAAQ,IAAI,CAAA;AAAA,EACvC,SAAS,GAAA,EAAK;AACZ,IAAA,IAAA,CAAK,oBAAqB,GAAA,CAAc,OAAA,IAAW,MAAA,CAAO,GAAG,CAAC,CAAA,CAAE,CAAA;AAChE,IAAA,IAAI,OAAA,CAAQ,IAAI,cAAA,EAAgB;AAI9B,MAAA,OAAA,CAAQ,MAAM,GAAG,CAAA;AAAA,IACnB;AACA,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA,GAAG;AAQH,SAAS,UAAA,GAAqB;AAC5B,EAAA,OAAO,OAAA;AACT;AAGA,SAAS,eAAe,KAAA,EAAuB;AAC7C,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,QAAA,CAAS,KAAA,EAAO,EAAE,CAAA;AACnC,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,KAAK,CAAA,CAAA,CAAG,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,CAAA;AACT;AAUA,SAAS,eAAA,CAAgB,OAAe,QAAA,EAA8B;AACpE,EAAA,OAAO,CAAC,GAAG,QAAA,EAAU,KAAK,CAAA;AAC5B","file":"bin.js","sourcesContent":["/**\n * Local CLI configuration — persisted to\n * `$XDG_CONFIG_HOME/dashwise/auth.json` (defaults to\n * `~/.config/dashwise/auth.json` on Linux/macOS and the equivalent\n * `%APPDATA%\\dashwise\\auth.json` on Windows).\n *\n * Contents:\n * - `apiUrl` — backend root, e.g. `http://localhost:3000`\n * - `token` — raw `dwc_*` CLI token (the secret)\n * - `tokenId` — DB id of the `cli_tokens` row (so `dashwise\n * logout` can call DELETE precisely)\n * - `user` — cached profile for fast `dashwise profile`\n * (refreshed on `dashwise login` + on demand)\n * - `workspaceSlug` — default workspace selected via\n * `dashwise workspace use <slug>`\n *\n * Permissions: chmod 0600 on write — the file holds a long-lived\n * bearer credential. Best-effort on Windows (the API tolerates\n * `EPERM` on the chmod call there).\n */\n\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface CliConfig {\n /** Backend base URL — e.g. `http://localhost:3000`. */\n apiUrl: string;\n /** Raw CLI token (`dwc_<...>`). */\n token: string;\n /** DB id of the matching `cli_tokens` row. Used by `logout`. */\n tokenId: number;\n /** Cached user identity. */\n user: {\n id: number;\n email: string;\n username: string;\n firstName: string;\n lastName: string;\n };\n /** Optional default workspace slug. */\n workspaceSlug?: string;\n /**\n * HH-CC-LDI-6 — per-module local-dev install metadata, keyed by\n * the module's slug (matches `module.json#module.slug`).\n *\n * Written by `dashwise init` after `POST /api/installations/dev`\n * returns a runtime token. Read by `@dashai/sdk`'s\n * `createDevClient({ moduleSlug })` to authenticate against the\n * local-dev install. Each entry is independent — entries for\n * other modules survive any single module's destroy / re-init.\n *\n * Field semantics:\n * - `runtimeToken` — JWT bearer the SDK sends on every data\n * request. Long-lived (default 90d). Replaced on rotation\n * (LDI-9 `dashwise module rotate-token`).\n * - `installationId` — numeric install id the token binds to.\n * Useful for surfacing to the user in `dashwise module status`\n * output and for the future LDI-9 destroy command.\n * - `expiresAt` — ISO timestamp; informational only. The CLI\n * can warn when the token is nearing expiry, but expiry is\n * enforced server-side via the JWT's `exp` claim.\n */\n modules?: Record<string, CliConfigModuleEntry>;\n}\n\n/** Per-module entry within `CliConfig.modules`. See `modules` field above. */\nexport interface CliConfigModuleEntry {\n runtimeToken: string;\n installationId: number;\n expiresAt: string;\n}\n\nconst FILE_NAME = 'auth.json';\nconst DIR_NAME = 'dashwise';\n\n/**\n * Resolve the config directory using XDG conventions.\n *\n * 1. `$XDG_CONFIG_HOME/dashwise/` if set\n * 2. `~/.config/dashwise/` on Linux/macOS\n * 3. `%APPDATA%\\dashwise\\` on Windows (via env)\n *\n * Mirrors `dashwise` projects on common platforms; matches what\n * users would expect from other CLIs (gh, npm, etc.).\n */\nexport function configDir(): string {\n if (process.env.XDG_CONFIG_HOME) {\n return join(process.env.XDG_CONFIG_HOME, DIR_NAME);\n }\n if (platform() === 'win32' && process.env.APPDATA) {\n return join(process.env.APPDATA, DIR_NAME);\n }\n return join(homedir(), '.config', DIR_NAME);\n}\n\nexport function configPath(): string {\n return join(configDir(), FILE_NAME);\n}\n\n/**\n * Read the saved config, or `null` if no file exists. Throws if the\n * file exists but is malformed JSON — the caller decides whether to\n * surface as \"run `dashwise login` again\" or as a hard error.\n */\nexport function readConfig(): CliConfig | null {\n const path = configPath();\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n if (!isPlausibleConfig(parsed)) {\n throw new Error(\n `Config at ${path} is missing required fields. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n return parsed;\n}\n\n/**\n * Write the config atomically (via temp + rename) with 0600 perms.\n * Creates the parent dir if missing.\n */\nexport function writeConfig(config: CliConfig): void {\n const dir = configDir();\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const path = configPath();\n const tmp = `${path}.tmp.${process.pid}`;\n writeFileSync(tmp, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // Windows + some FUSE FS don't support chmod; best-effort.\n }\n // Atomic rename — readers see either the old config or the new\n // one, never a partial write.\n renameSync(tmp, path);\n}\n\n/**\n * Remove the config file (`dashwise logout`). Idempotent — no error\n * if the file already doesn't exist.\n */\nexport function deleteConfig(): void {\n const path = configPath();\n if (!existsSync(path)) return;\n rmSync(path);\n}\n\n/**\n * Resolve the API URL the CLI should talk to.\n * Priority: explicit `DASHWISE_API_URL` env → saved config → default.\n */\nexport function resolveApiUrl(): string {\n const fromEnv = process.env.DASHWISE_API_URL?.trim();\n if (fromEnv) return fromEnv.replace(/\\/+$/, '');\n const cfg = safeReadConfig();\n if (cfg?.apiUrl) return cfg.apiUrl.replace(/\\/+$/, '');\n return 'http://localhost:3000';\n}\n\n/**\n * Convenience: read the saved token if the file exists + is valid.\n * Returns `null` if the user isn't logged in.\n */\nexport function readSavedToken(): string | null {\n const cfg = safeReadConfig();\n return cfg?.token ?? null;\n}\n\nfunction safeReadConfig(): CliConfig | null {\n try {\n return readConfig();\n } catch {\n return null;\n }\n}\n\nfunction isPlausibleConfig(v: unknown): v is CliConfig {\n if (!v || typeof v !== 'object') return false;\n const c = v as Record<string, unknown>;\n if (typeof c.apiUrl !== 'string') return false;\n if (typeof c.token !== 'string') return false;\n if (typeof c.tokenId !== 'number') return false;\n if (!c.user || typeof c.user !== 'object') return false;\n const u = c.user as Record<string, unknown>;\n if (typeof u.id !== 'number') return false;\n if (typeof u.email !== 'string') return false;\n // HH-CC-LDI-6: `modules` is optional and forgiving — entries with\n // wrong shape are silently ignored at read time, mirroring the\n // SDK's reader. Strict per-entry validation would force CLI\n // crashes on partial writes (e.g. interrupt mid-init).\n if (c.modules !== undefined) {\n if (typeof c.modules !== 'object' || c.modules === null) return false;\n }\n return true;\n}\n\n/**\n * HH-CC-LDI-6 — record a module's local-dev install in `auth.json`.\n *\n * Atomic: reads, mutates, writes. If `dashwise init` is interrupted\n * after the API call but before this returns, the install row exists\n * server-side without local persistence — the user has to re-init or\n * use the future `dashwise module recover-dev-install` command (LDI-9).\n *\n * Throws if there's no saved config (the user isn't logged in).\n * Callers should check `isLoggedIn()` first and surface a clear\n * \"run `dashwise login` first\" error.\n */\nexport function upsertModuleEntry(\n slug: string,\n entry: CliConfigModuleEntry,\n): void {\n const cfg = readConfig();\n if (!cfg) {\n throw new Error(\n 'No CLI config file. Run `dashwise login` first to create one.',\n );\n }\n const next: CliConfig = {\n ...cfg,\n modules: {\n ...(cfg.modules ?? {}),\n [slug]: entry,\n },\n };\n writeConfig(next);\n}\n\n/**\n * HH-CC-LDI-6 — read a module's local-dev entry, or `null` if none\n * has been provisioned. Returns `null` when the user isn't logged in.\n */\nexport function readModuleEntry(slug: string): CliConfigModuleEntry | null {\n const cfg = safeReadConfig();\n if (!cfg?.modules) return null;\n return cfg.modules[slug] ?? null;\n}\n\n/**\n * HH-CC-LDI-6 — remove a module's entry (used by future LDI-9\n * `dashwise module destroy-dev-install`). Idempotent — no-op when\n * the entry doesn't exist or the user isn't logged in.\n */\nexport function removeModuleEntry(slug: string): void {\n const cfg = safeReadConfig();\n if (!cfg?.modules || !(slug in cfg.modules)) return;\n const { [slug]: _removed, ...rest } = cfg.modules;\n void _removed;\n const next: CliConfig = {\n ...cfg,\n modules: Object.keys(rest).length > 0 ? rest : undefined,\n };\n writeConfig(next);\n}\n\n/**\n * Return current file mode bits (for diagnostics). Returns `null`\n * on any failure (file missing, permission denied, etc.).\n */\nexport function configFileMode(): number | null {\n try {\n const s = statSync(configPath());\n return s.mode & 0o777;\n } catch {\n return null;\n }\n}\n\n/** Confirm a saved config exists (for `whoami` short-circuit). */\nexport function isLoggedIn(): boolean {\n return readSavedToken() !== null;\n}\n\n/** Convenience helper used by tests + diagnostic commands. */\nexport function configSummary(): {\n path: string;\n exists: boolean;\n mode: number | null;\n} {\n return {\n path: configPath(),\n exists: existsSync(configPath()),\n mode: configFileMode(),\n };\n}\n\n// Helpers above intentionally exported individually — no default\n// export so tree-shake at the `bin.ts` level remains effective.\n","/**\n * Thin HTTP client for the DashWise backend, tailored for the CLI's\n * call patterns.\n *\n * Three shapes of authenticated request emerge in the CLI:\n * 1. **Public** — `dashwise login` device-code start/poll (no token yet)\n * 2. **CLI token (`Bearer dwc_*`)** — every command after login\n * 3. **One-off Bearer** — internal use during the login flow\n * (we don't have a saved token while polling)\n *\n * The class is intentionally small + dependency-free (uses\n * `globalThis.fetch`). Error envelopes from the backend\n * (`{ code, message, retriable, context }`) are surfaced as typed\n * `ApiError`s so command code can branch on `err.code`.\n */\n\nimport { resolveApiUrl, readSavedToken } from './config.js';\n\nexport interface ApiErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly context: Record<string, unknown> | undefined;\n readonly retriable: boolean;\n\n constructor(status: number, envelope: ApiErrorEnvelope | null, fallbackMessage: string) {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? fallbackMessage;\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.context = envelope?.context;\n this.retriable = envelope?.retriable ?? status >= 500;\n }\n}\n\nexport interface RequestOptions {\n /**\n * Auth mode:\n * - `'auto'` (default) — `Bearer <saved-token>` if one exists,\n * else no header.\n * - `'public'` — no Authorization header (used by the device-code\n * endpoints which authenticate via the device_code itself).\n * - `{ token: 'dwc_...' }` — explicit token (used during login\n * polling before we save the file).\n */\n auth?: 'auto' | 'public' | { token: string };\n\n /** Override the base URL (testing / `--api-url` flag). */\n baseUrl?: string;\n\n /** Extra request headers (rare — diagnostic plumbing). */\n headers?: Record<string, string>;\n}\n\n/**\n * Make a JSON request. Returns the parsed body (`T`) or throws an\n * `ApiError`. 204 responses return `undefined`.\n */\nexport async function apiRequest<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n): Promise<T> {\n const baseUrl = (options.baseUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.headers ?? {}),\n };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n const authMode = options.auth ?? 'auto';\n if (authMode === 'auto') {\n const saved = readSavedToken();\n if (saved) headers['Authorization'] = `Bearer ${saved}`;\n } else if (typeof authMode === 'object' && authMode.token) {\n headers['Authorization'] = `Bearer ${authMode.token}`;\n }\n\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n // Network-level failure — DNS, ECONNREFUSED, TLS, etc. Surface\n // as an ApiError with a stable code so callers can branch.\n throw new ApiError(0, { code: 'NETWORK_ERROR', message: (err as Error).message }, 'Network error');\n }\n\n if (res.status === 204) {\n return undefined as T;\n }\n\n const contentType = res.headers.get('content-type') ?? '';\n let parsed: unknown = null;\n if (contentType.includes('application/json')) {\n try {\n parsed = await res.json();\n } catch {\n parsed = null;\n }\n } else if (res.status >= 400) {\n // Non-JSON error body — still want a stable error shape.\n try {\n parsed = { message: await res.text() };\n } catch {\n parsed = null;\n }\n }\n\n if (!res.ok) {\n throw new ApiError(res.status, asEnvelope(parsed), `HTTP ${res.status}`);\n }\n return parsed as T;\n}\n\nfunction asEnvelope(v: unknown): ApiErrorEnvelope | null {\n if (!v || typeof v !== 'object') return null;\n const env = v as Record<string, unknown>;\n const out: ApiErrorEnvelope = {};\n if (typeof env.code === 'string') out.code = env.code;\n if (typeof env.message === 'string') out.message = env.message;\n if (typeof env.retriable === 'boolean') out.retriable = env.retriable;\n if (env.context && typeof env.context === 'object') {\n out.context = env.context as Record<string, unknown>;\n }\n return out;\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return 'UNAUTHENTICATED';\n if (status === 403) return 'FORBIDDEN';\n if (status === 404) return 'NOT_FOUND';\n if (status === 0) return 'NETWORK_ERROR';\n if (status >= 500) return 'INTERNAL_ERROR';\n return 'HTTP_ERROR';\n}\n\n// ── HH-CC-LDI-6: typed wrapper for POST /api/installations/dev ────────\n\n/**\n * Shape returned by `POST /api/installations/dev` — matches the\n * backend's `DevInstallationController.createDevInstallation` envelope.\n * See `dashwise-backend/src/modules/modules/installation/dev-installation.controller.ts`.\n */\nexport interface DevInstallationResponse {\n installation: {\n id: number;\n kind: 'sandbox' | 'local' | 'production';\n workspace_id: number;\n module_id: number;\n module_version_id: number;\n application_id: number;\n installed_on: string;\n };\n module: {\n id: number;\n slug: string;\n name: string;\n };\n runtime_token: string;\n runtime_token_expires_at: string;\n}\n\n/**\n * Create a local-dev module installation + mint a runtime token.\n *\n * Called by `dashwise init` after the user picks a workspace + slug\n * + name. The returned `runtime_token` is persisted into\n * `auth.json#modules[<slug>]` via `upsertModuleEntry`; the SDK's\n * `createDevClient({ moduleSlug })` reads from there on every dev\n * server boot.\n *\n * Errors (surfaced as `ApiError` with the backend's `code` field):\n * - 403 — caller is not a member of the target workspace.\n * - 409 SLUG_ALREADY_EXISTS — a module with this slug exists. The\n * user should pick a different slug or run `dashwise module\n * destroy-dev-install` first (LDI-9).\n * - 503 RUNTIME_DATA_API_DISABLED — `BUILDER_SESSION_TOKEN_SECRET`\n * unset on the backend. Operator-side issue, not a user issue.\n */\nexport async function createDevInstallation(\n body: {\n slug: string;\n name: string;\n description?: string;\n workspaceId: number;\n /**\n * HH-CC-FUP-2 — `module_kind` from the scaffold's `module.json`.\n * Without forwarding it the backend's draft manifest gets no\n * `module_kind`, `SchemaProposeService.getManifest()` falls back\n * to `'ai_builder'`, and that wrong value rewrites the local\n * module.json on the first watcher tick.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n },\n options: RequestOptions = {},\n): Promise<DevInstallationResponse> {\n return apiRequest<DevInstallationResponse>(\n 'POST',\n '/api/installations/dev',\n body,\n options,\n );\n}\n\n/**\n * HH-CC-LDI-9 — destroy a local-dev installation.\n *\n * Maps to `DELETE /api/installations/dev/:installationId`. The\n * backend (`DevInstallationService.destroy`) tears down the install\n * row + its application tile, and conditionally drops the module\n * if it was a dev-only artifact (no other installs, never published).\n *\n * Returns `{ installation_id, module_id, module_also_dropped }`.\n *\n * Errors (`ApiError`):\n * - 404 `INSTALLATION_NOT_FOUND` — install id doesn't exist.\n * - 403 `INSTALLATION_KIND_NOT_LOCAL` — refuses non-local installs.\n * - 403 `NOT_WORKSPACE_MEMBER` — caller isn't in the install's workspace.\n */\nexport interface DestroyDevInstallationResponse {\n installation_id: number;\n module_id: number;\n module_also_dropped: boolean;\n}\n\nexport async function destroyDevInstallation(\n installationId: number,\n options: RequestOptions = {},\n): Promise<DestroyDevInstallationResponse> {\n return apiRequest<DestroyDevInstallationResponse>(\n 'DELETE',\n `/api/installations/dev/${installationId}`,\n undefined,\n options,\n );\n}\n\n// ── HH-CC-LDI-8: schema-mutation endpoints (mirrors LDI-4 controller) ──\n\n/** FieldDef body shape — open enough to carry `options`, `target`, etc. */\nexport interface FieldDefBody {\n slug: string;\n type: string;\n required?: boolean;\n options?: string[];\n target?: string;\n default?: unknown;\n}\n\n/**\n * Common response shape from `propose_*` endpoints — the LDI-4\n * controller strips the in-memory `sdk` blob, so the wire payload is\n * just the operation result + sdk_regen metadata.\n */\nexport interface SchemaOpResponse {\n table_slug: string;\n physical_table_id: number;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n /** Present on proposeField responses (add / update / remove). */\n operation_applied?: 'add' | 'update' | 'remove';\n}\n\nexport interface DropTableResponse {\n table_slug: string;\n dropped: boolean;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n}\n\n/** `POST /api/installations/:id/schema/tables` — create a table. */\nexport async function createTable(\n installationId: number,\n body: {\n slug: string;\n fields: FieldDefBody[];\n indexes?: Array<{ fields: string[]; unique?: boolean }>;\n },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/installations/${installationId}/schema/tables`,\n body,\n options,\n );\n}\n\n/** `DELETE /api/installations/:id/schema/tables/:tableSlug` — drop a table. */\nexport async function dropTable(\n installationId: number,\n tableSlug: string,\n options: RequestOptions = {},\n): Promise<DropTableResponse> {\n return apiRequest<DropTableResponse>(\n 'DELETE',\n `/api/installations/${installationId}/schema/tables/${tableSlug}`,\n undefined,\n options,\n );\n}\n\n/** `POST /api/installations/:id/schema/fields` — add a field. */\nexport async function addField(\n installationId: number,\n body: { table_slug: string; field: FieldDefBody },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/installations/${installationId}/schema/fields`,\n body,\n options,\n );\n}\n\n/** `PATCH /api/installations/:id/schema/fields/:tableSlug/:fieldSlug` — update. */\nexport async function updateField(\n installationId: number,\n tableSlug: string,\n fieldSlug: string,\n body: Omit<FieldDefBody, 'slug'>,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'PATCH',\n `/api/installations/${installationId}/schema/fields/${tableSlug}/${fieldSlug}`,\n body,\n options,\n );\n}\n\n/**\n * `GET /api/installations/:id/schema` — read the current draft\n * manifest. Used post-mutation to write the new state back to local\n * `module.json` (HH-CC-LDI-8 REST-first / write-back-from-GET model).\n */\nexport async function getInstallationSchema(\n installationId: number,\n options: RequestOptions = {},\n): Promise<{ manifest: Record<string, unknown> }> {\n return apiRequest<{ manifest: Record<string, unknown> }>(\n 'GET',\n `/api/installations/${installationId}/schema`,\n undefined,\n options,\n );\n}\n\n/** `DELETE /api/installations/:id/schema/fields/:tableSlug/:fieldSlug` — remove. */\nexport async function removeField(\n installationId: number,\n tableSlug: string,\n fieldSlug: string,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'DELETE',\n `/api/installations/${installationId}/schema/fields/${tableSlug}/${fieldSlug}`,\n undefined,\n options,\n );\n}\n","/**\n * Shared `module.json` I/O for CLI commands.\n *\n * Several commands need to read + mutate the local manifest\n * (`connect-git`, `deps add / remove`, future `module fields add`,\n * etc.). Inlining the read/write/JSON-parse dance in every command\n * leaks formatting choices (2-space indent, trailing newline) and\n * makes file-level invariants harder to enforce. This helper is the\n * single chokepoint.\n *\n * Properties:\n * - Tolerates an absent file with a typed null return.\n * - Throws a typed error (with file path) on parse failure.\n * - Writes are atomic-ish: same write pattern as the rest of the\n * CLI (one `writeFileSync`, no temp file — manifest is small +\n * local; partial writes only matter for ~256-byte regions and\n * fsync ordering on local disk).\n * - Preserves 2-space indent + trailing newline so `git diff` after\n * a CLI mutation shows only the actual change.\n * - Generic over the manifest shape — callers cast to their needed\n * shape since the manifest schema is owned by the backend.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Reasonably-permissive shape covering what CLI commands care about.\n * The backend validator owns the full schema; we only narrow what we\n * need to read/write here.\n */\nexport interface ManifestShape {\n schema_version?: number;\n module?: {\n slug?: string;\n name?: string;\n version?: string;\n [k: string]: unknown;\n };\n module_kind?: string;\n owns?: { tables?: Array<{ slug?: string; [k: string]: unknown }> };\n dependencies?: ManifestDependency[];\n exposes?: Array<Record<string, unknown>>;\n repository?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ManifestDependency {\n module: string;\n version: string;\n reads: Array<{ table: string; fields: string[] }>;\n writes?: Array<{ table: string; fields: string[]; operations: string[] }>;\n purpose: string;\n}\n\n/**\n * Resolve the manifest path inside `dir` (defaults to `process.cwd()`).\n * Pure path math — does not touch the filesystem.\n */\nexport function manifestPath(dir?: string): string {\n return join(resolve(dir ?? process.cwd()), 'module.json');\n}\n\n/**\n * Read + parse `module.json` from `dir`. Returns `null` when the file\n * doesn't exist (so callers can branch on \"not a module directory\" vs\n * \"broken manifest\"). Throws with a clear message on parse failure.\n */\nexport function readManifest<T extends ManifestShape = ManifestShape>(dir?: string): T | null {\n const path = manifestPath(dir);\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n try {\n return JSON.parse(raw) as T;\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Fix or delete the file and re-run.`,\n );\n }\n}\n\n/**\n * Write `manifest` back to `module.json` in `dir`. Uses the canonical\n * 2-space indent + trailing newline so subsequent commits show only\n * the intended diff. Caller is responsible for any structural\n * validation — this helper is a dumb serializer.\n */\nexport function writeManifest(manifest: ManifestShape, dir?: string): void {\n const path = manifestPath(dir);\n writeFileSync(path, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n}\n\n/**\n * Convenience: read the manifest or throw a CLI-friendly error if\n * either the file is missing or unparseable. Use from commands that\n * REQUIRE a manifest to function (most of them).\n */\nexport function readManifestOrThrow<T extends ManifestShape = ManifestShape>(dir?: string): T {\n const manifest = readManifest<T>(dir);\n if (!manifest) {\n throw new Error(\n `No module.json found in ${resolve(dir ?? process.cwd())}. Run \\`dashwise module init\\` first or pass \\`--dir <path>\\`.`,\n );\n }\n return manifest;\n}\n","/**\n * Output formatting helpers — colors via picocolors (zero deps,\n * tiny). All output goes through these so the CLI has a consistent\n * voice + we can later add `--no-color` / `--json` modes by editing\n * one file.\n */\n\nimport pc from 'picocolors';\n\nexport function success(msg: string): void {\n process.stderr.write(`${pc.green('✓')} ${msg}\\n`);\n}\n\nexport function info(msg: string): void {\n process.stderr.write(`${pc.cyan('ℹ')} ${msg}\\n`);\n}\n\nexport function warn(msg: string): void {\n process.stderr.write(`${pc.yellow('⚠')} ${msg}\\n`);\n}\n\nexport function fail(msg: string): void {\n process.stderr.write(`${pc.red('✗')} ${msg}\\n`);\n}\n\n/** Plain text to stdout — for command output that should be pipe-able. */\nexport function out(msg: string): void {\n process.stdout.write(`${msg}\\n`);\n}\n\n/** Print a `key: value` pair, key bold and right-padded. */\nexport function kv(key: string, value: string, padTo = 14): void {\n const padded = key.padEnd(padTo);\n process.stdout.write(`${pc.bold(padded)} ${value}\\n`);\n}\n\n/** Highlight CLI commands or paths in inline text. */\nexport function code(s: string): string {\n return pc.cyan(s);\n}\n\n/** Dim secondary info (timestamps, helper hints). */\nexport function dim(s: string): string {\n return pc.dim(s);\n}\n\nexport { pc };\n","/**\n * Inline scaffold for `dashwise module init`. Each function returns\n * the file content for a single file in the target project tree.\n *\n * Kept inline (no template-files dir) because the scaffold is small\n * + benefits from having the runtime values (slug, name) interpolated\n * in TS rather than via a separate templating engine. When the\n * scaffold grows beyond ~10 files OR starts to differ meaningfully\n * between AI-built / hand-authored / custom flavors, splitting to\n * `templates/<flavor>/` becomes worth it.\n */\n\nexport type ScaffoldKind = 'hand_authored' | 'custom';\n\nexport interface ScaffoldOptions {\n slug: string;\n name: string;\n /** Module flavor — `hand_authored` (simple isolate-runtime) or `custom` (full Next.js + machine runtime). */\n kind?: ScaffoldKind;\n /** Optional Git repository URL — populates `module.json#repository.url`. */\n repositoryUrl?: string;\n}\n\nexport function manifestJson(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n const manifest: Record<string, unknown> = {\n schema_version: 2,\n module: {\n slug: opts.slug,\n name: opts.name,\n version: '0.0.1',\n },\n module_kind: kind,\n owns: {\n tables: [\n {\n slug: 'items',\n fields: [{ slug: 'title', type: 'text', required: true }],\n },\n ],\n },\n };\n if (kind === 'custom') {\n manifest.runtime = {\n type: 'nextjs',\n kind: 'machine',\n machine_size: 'shared-cpu-1x',\n server_actions: true,\n };\n }\n if (opts.repositoryUrl) {\n manifest.repository = { type: 'git', url: opts.repositoryUrl };\n }\n return JSON.stringify(manifest, null, 2) + '\\n';\n}\n\nexport function packageJson(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^0.8.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function tsconfigJson(): string {\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n lib: ['dom', 'dom.iterable', 'ES2022'],\n module: 'ESNext',\n moduleResolution: 'Bundler',\n jsx: 'preserve',\n strict: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n esModuleInterop: true,\n isolatedModules: true,\n allowJs: false,\n noEmit: true,\n incremental: true,\n plugins: [{ name: 'next' }],\n paths: { '@/*': ['./*'] },\n },\n include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],\n exclude: ['node_modules'],\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function nextConfig(): string {\n return `/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {\n typescript: { ignoreBuildErrors: true },\n eslint: { ignoreDuringBuilds: true },\n};\nexport default nextConfig;\n`;\n}\n\nexport function nextEnvDts(): string {\n return `/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n`;\n}\n\nexport function gitignore(): string {\n return [\n '# Dependencies',\n '/node_modules',\n '',\n '# Generated by Next.js',\n '/.next',\n '/out',\n '',\n '# Production',\n '/build',\n '',\n '# Misc',\n '.DS_Store',\n '*.log',\n '',\n '# Env',\n '.env',\n '.env.local',\n '.env.*.local',\n '',\n '# Editor',\n '.vscode/',\n '.idea/',\n '',\n '# DashWise-generated SDK output is regenerable from module.json',\n '# (run `dashwise module generate`); keep it out of source control.',\n '/node_modules/@dashai/generated/',\n '',\n ].join('\\n');\n}\n\nexport function envLocalExample(): string {\n return [\n '# Copy to .env.local + fill in real values.',\n '# These vars are auto-injected by `dashwise dev` (the unified dev loop)',\n '# from ~/.config/dashwise/auth.json — you only need to edit this file if',\n '# you want to point at a non-default backend or run `next dev` standalone.',\n 'DASHWISE_API_URL=http://localhost:3000',\n '# Client-side mirror — Next.js inlines NEXT_PUBLIC_* into the browser',\n '# bundle so the SDK\\'s <AuthProvider> can hit `/api/auth/sessions/me`',\n '# on the right origin. Should match DASHWISE_API_URL above.',\n 'NEXT_PUBLIC_DASHWISE_API_URL=http://localhost:3000',\n 'DASHWISE_API_TOKEN=',\n 'DASHWISE_INSTALLATION_ID=local',\n '',\n ].join('\\n');\n}\n\nexport function envLocal(): string {\n return [\n '# Local dev config — auto-generated by `dashwise module init`.',\n '# Gitignored; safe to edit. `dashwise dev` (the unified loop) auto-',\n '# injects DASHWISE_API_TOKEN from ~/.config/dashwise/auth.json AND',\n '# DASHWISE_DEV_SESSION_ID from the dev session it registers — so',\n '# you typically don\\'t need to set either here. Change DASHWISE_API_URL',\n '# (and NEXT_PUBLIC_DASHWISE_API_URL to match) to point at a non-default',\n '# backend (e.g. https://api.dashwise.net).',\n '#',\n '# DASHWISE_INSTALLATION_ID is only needed AFTER you publish + install',\n '# the module in a workspace; until then dev mode (DASHWISE_DEV_SESSION_ID,',\n '# auto-set by `dashwise dev`) is the auth path.',\n 'DASHWISE_API_URL=http://localhost:3000',\n '# Client-side mirror (must match DASHWISE_API_URL). Next.js inlines',\n '# NEXT_PUBLIC_* into the browser bundle so the SDK\\'s AuthProvider can',\n '# call /api/auth/sessions/me on the right origin instead of bouncing',\n '# off the local module server with a 404.',\n 'NEXT_PUBLIC_DASHWISE_API_URL=http://localhost:3000',\n 'DASHWISE_API_TOKEN=',\n 'DASHWISE_INSTALLATION_ID=',\n '',\n ].join('\\n');\n}\n\nexport function appLayoutTsx(opts: ScaffoldOptions): string {\n return `export const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>{children}</body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageTsx(opts: ScaffoldOptions): string {\n return `export default function Page() {\n return (\n <main style={{ minHeight: '100dvh', display: 'grid', placeItems: 'center', padding: 32 }}>\n <div style={{ maxWidth: 560, textAlign: 'center' }}>\n <h1 style={{ fontSize: 28, marginBottom: 8 }}>${escapeHtml(opts.name)}</h1>\n <p style={{ color: '#475569' }}>\n Module slug: <code>${escapeHtml(opts.slug)}</code>\n </p>\n <p style={{ marginTop: 24, color: '#64748b', fontSize: 14 }}>\n Run <code>dashwise module dev</code> to start the watch loop.\n <br />\n Edit <code>module.json</code> to add tables; regenerated types\n land in <code>@dashai/generated</code>.\n </p>\n </div>\n </main>\n );\n}\n`;\n}\n\nexport function readme(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n if (kind === 'custom') {\n return readmeCustom(opts);\n }\n return readmeHandAuthored(opts);\n}\n\nfunction readmeHandAuthored(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA DashWise module (hand-authored). Slug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch module.json + auto-regenerate\nnpm run dev:next # plain Next.js dev server (in another terminal)\n\\`\\`\\`\n\n## Project layout\n\n| Path | What |\n| --- | --- |\n| \\`module.json\\` | Manifest. Declares tables, dependencies, runtime config. |\n| \\`app/\\` | Next.js App Router. Edit freely. |\n| \\`node_modules/@dashai/generated/\\` | Auto-generated typed wrappers. **Do not edit by hand** — regenerated by \\`dashwise module generate\\`. |\n\n## Imports\n\n\\`\\`\\`ts\nimport { db } from '@dashai/generated';\nimport type { ItemsRow } from '@dashai/generated';\n\n// runtime types + errors\nimport { createClient, type Where } from '@dashai/sdk';\n\\`\\`\\`\n`;\n}\n\nfunction readmeCustom(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA **custom DashWise module** — a full Next.js App Router app that\nruns in a per-installation Fly Machine (P7 substrate). Authenticated\nvia the DashWise NestJS backend through \\`@dashai/sdk/auth\\`.\n\nSlug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch + regen on module.json save (terminal 1)\nnpm run dev:next # next dev on :3000 (terminal 2)\n\\`\\`\\`\n\n## Architecture\n\n- **\\`module.json\\`** — manifest (\\`module_kind: 'custom'\\`, \\`runtime.kind: 'machine'\\`).\n- **\\`middleware.ts\\`** — \\`withAuth\\` from \\`@dashai/sdk/auth/middleware\\`. Redirects unauthenticated requests through the DashWise SSO flow.\n- **\\`app/layout.tsx\\`** — wraps the tree in \\`<AuthProvider>\\` from \\`@dashai/sdk/auth/client\\`.\n- **\\`app/page.tsx\\`** — public landing (allowlisted in \\`middleware.ts\\`).\n- **\\`app/dashboard/page.tsx\\`** — Server Component requiring a valid session via \\`getServerSession()\\`.\n- **\\`app/api/auth/callback/route.ts\\`** — exchanges the SSO one-time code for a session cookie (uses \\`exchangeCode()\\` from the SDK).\n- **\\`app/api/auth/sign-in/route.ts\\`** — entry point that redirects to the backend's \\`/sso/start\\` with the right \\`return_to\\` + \\`client_id\\`.\n- **\\`app/api/auth/sign-out/route.ts\\`** — clears the session cookie + tells the backend to revoke.\n\n## Imports\n\n\\`\\`\\`ts\n// Data:\nimport { db } from '@dashai/generated';\n\n// Auth (server, e.g. inside a Server Component or route handler):\nimport { getServerSession, exchangeCode, signOut } from '@dashai/sdk/auth/server';\n\n// Auth (client, inside a Client Component):\n'use client';\nimport { useSession, SignOutButton, AuthProvider } from '@dashai/sdk/auth/client';\n\n// Runtime types + errors:\nimport { type Where, RowNotFoundError } from '@dashai/sdk';\n\\`\\`\\`\n\n## Publish\n\n\\`\\`\\`bash\ndashwise module validate # local lint\ndashwise module publish --bump patch\n\\`\\`\\`\n\n## Adding UI blocks\n\nThe scaffold pre-installs two shadcn/ui primitives (\\`Button\\`, \\`Card\\`) plus the\ncanonical Tailwind 4 + theme-tokens setup. To add more components:\n\n\\`\\`\\`bash\n# shadcn/ui base (free):\nnpx shadcn@latest add input badge dialog dropdown-menu\n\n# shadcn-studio blocks (free at https://shadcnstudio.com):\nnpx shadcn@latest add @shadcn-studio/hero-section-01\n\n# shadcn-studio Pro blocks (requires \\$EMAIL + \\$LICENSE_KEY env vars):\nnpx shadcn@latest add @ss-components/dashboard-shell-01\n\\`\\`\\`\n\nIf you're using Claude Code or another IDE that supports the shadcn-studio MCP,\ntrigger \\`/cui\\` (create new UI) or \\`/rui\\` (refine existing UI) to walk through\nthe canonical block-discovery flow.\n\n## Deploying elsewhere (custom domain)\n\nThe scaffolded SSO flow is wired for DashWise's own infrastructure\n(\\`m-<id>.dashwise.net\\`). If you want to host this module on your own\ndomain (e.g. \\`mymodule.example.com\\`), there are two options:\n\n1. **Wait for custom-domain support (in design).** A future \\`--callback-origin\\`\n flag on \\`dashwise module init\\` plus a \\`module_oauth_clients\\` allowlist will\n let modules run at arbitrary domains while still using DashWise SSO. Tracked\n in [\\`modules-author-experience-v1.md\\`](https://github.com/sharmaintuize/dashwise-devops-docs/blob/main/plans/modules-author-experience-v1.md) §3.\n2. **Bypass SSO + use a Workspace API Token today.** Replace the SSO middleware\n with a token-check middleware that reads \\`Authorization: Token <key>\\` from\n each request. Tokens are created at \\`<dashwise-dashboard>/settings/tokens\\`\n and scoped to a workspace. The SDK accepts these via the standard\n \\`DASHWISE_API_TOKEN\\` env var. You'll lose the per-user session model\n (every request runs as the token's owner) but gain the freedom to deploy\n anywhere.\n\nThe CLI's \\`dashwise dev\\` command auto-injects the developer's CLI token (also\na bearer token) into local dev — so local development works regardless of\nwhich path you pick for production.\n`;\n}\n\n// ── Custom-flavor templates ──────────────────────────────────────────\n\nexport function middlewareTs(): string {\n return `// Next.js middleware — gates every route on the DashWise session cookie.\n// Public routes (and /api/auth/*) bypass the redirect; everything else\n// 302s through the SSO flow when no \\`dashwise.session\\` cookie is set.\nimport { withAuth } from '@dashai/sdk/auth/middleware';\n\nexport default withAuth({\n // \\`/sign-in-error\\` is public so unauthenticated visitors can actually\n // see the polished SSO error page — otherwise a sign-in failure would\n // redirect-loop trying to re-authenticate.\n publicPaths: ['/', '/about', '/sign-in-error'],\n loginPath: '/api/auth/sign-in',\n});\n\nexport const config = {\n matcher: ['/((?!_next/static|_next/image|favicon.ico|public/).*)'],\n};\n`;\n}\n\nexport function appLayoutCustomTsx(opts: ScaffoldOptions): string {\n return `import './globals.css';\nimport { AuthProvider } from '@dashai/sdk/auth/client';\nimport { ThemeProvider } from '@/components/theme-provider';\n\nexport const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise custom module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\" suppressHydrationWarning>\n <body className=\"antialiased\">\n <ThemeProvider\n attribute=\"class\"\n defaultTheme=\"system\"\n enableSystem\n disableTransitionOnChange\n >\n <AuthProvider>{children}</AuthProvider>\n </ThemeProvider>\n </body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageCustomTsx(opts: ScaffoldOptions): string {\n return `// Public landing page — listed in middleware.ts publicPaths.\n//\n// First-run experience for unauthenticated visitors: hero with the\n// module name + tagline, a \"Sign in with DashWise\" button that kicks\n// off the SSO flow (via /api/auth/sign-in), and a feature card\n// describing what the module does. After signing in, the user lands\n// on /dashboard (Server Component, session-validated).\n//\n// Styling: shadcn/ui primitives (\\`<Button>\\`, \\`<Card>\\`) on Tailwind 4\n// theme tokens. Add more blocks via \\`npx shadcn add @shadcn-studio/...\\`\n// (see README's \"Adding UI blocks\" section).\nimport Link from 'next/link';\nimport { LogIn, LayoutDashboard } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nexport default function Page() {\n return (\n <main className=\"flex min-h-dvh flex-col items-center justify-center gap-12 px-6 py-16\">\n <section className=\"flex max-w-2xl flex-col items-center gap-6 text-center\">\n <h1 className=\"text-balance text-4xl font-semibold tracking-tight sm:text-5xl\">\n ${escapeHtml(opts.name)}\n </h1>\n <p className=\"text-balance text-lg text-muted-foreground\">\n A DashWise module. Sign in with your DashWise account to access the\n dashboard and start using the workspace's data through the typed SDK.\n </p>\n <div className=\"flex flex-wrap items-center justify-center gap-3\">\n <Button asChild size=\"lg\">\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <LogIn aria-hidden=\"true\" />\n Sign in with DashWise\n </Link>\n </Button>\n <Button asChild variant=\"ghost\" size=\"lg\">\n <Link href=\"/dashboard\">\n <LayoutDashboard aria-hidden=\"true\" />\n Go to dashboard\n </Link>\n </Button>\n </div>\n </section>\n\n <Card className=\"w-full max-w-2xl\">\n <CardHeader>\n <CardTitle>What you can do here</CardTitle>\n <CardDescription>\n This is a custom DashWise module — a full Next.js app authenticated\n against the DashWise SSO. Edit \\`app/page.tsx\\` to replace this\n landing page; everything else is yours to customize.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"text-sm text-muted-foreground\">\n <ul className=\"space-y-2\">\n <li>\n Edit <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>\n {' '}to declare tables, dependencies, and runtime config.\n </li>\n <li>\n Run <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise dev</code>\n {' '}for a one-command local loop with auth env vars auto-injected.\n </li>\n <li>\n Import typed table clients from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>\n {' '}— the SDK regenerates on every manifest save.\n </li>\n </ul>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nexport function appDashboardPageTsx(): string {\n return `import { getServerSession } from '@dashai/sdk/auth/server';\nimport { redirect } from 'next/navigation';\nimport { LogOut, ShieldCheck } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\n/**\n * Auth-gated Server Component. The middleware ensures the user has\n * a session cookie before this page renders; \\`getServerSession()\\`\n * validates the cookie against the backend's \\`/api/auth/sessions/me\\`\n * endpoint, returning the decoded \\`Session\\` (or \\`null\\` if stale).\n *\n * On a successful render, this is the polished session card — replace\n * the contents with whatever your module actually needs to show.\n */\nexport default async function Dashboard() {\n const session = await getServerSession();\n if (!session) {\n redirect('/api/auth/sign-in?return_to=/dashboard');\n }\n return (\n <main className=\"mx-auto flex min-h-dvh max-w-3xl flex-col gap-6 px-6 py-12\">\n <header className=\"flex items-start justify-between gap-4\">\n <div>\n <h1 className=\"text-2xl font-semibold tracking-tight\">Dashboard</h1>\n <p className=\"text-sm text-muted-foreground\">\n You're signed in. This page is rendered as a Server Component and\n validates the session cookie on every request.\n </p>\n </div>\n <form action=\"/api/auth/sign-out\" method=\"POST\">\n <Button variant=\"outline\" size=\"sm\" type=\"submit\">\n <LogOut aria-hidden=\"true\" />\n Sign out\n </Button>\n </form>\n </header>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2\">\n <ShieldCheck className=\"size-5 text-primary\" aria-hidden=\"true\" />\n Session\n </CardTitle>\n <CardDescription>\n Decoded from the \\`dashwise.session\\` cookie via{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">getServerSession()</code>.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-3 text-sm\">\n <Row label=\"Email\" value={session.user.email} />\n <Row label=\"User ID\" value={String(session.user.id)} />\n <Row label=\"Workspace\" value={String(session.workspaceId)} />\n <Row label=\"Role\" value={session.role} />\n {session.installationId !== undefined && (\n <Row\n label=\"Installation\"\n value={\n session.moduleSlug\n ? \\`\\${session.installationId} (\\${session.moduleSlug})\\`\n : String(session.installationId)\n }\n />\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle>Next steps</CardTitle>\n <CardDescription>\n Replace this dashboard with your module's actual UI.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm text-muted-foreground\">\n <p>\n <strong className=\"text-foreground\">1.</strong> Edit{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>{' '}\n to add tables, dependencies, and exposed actions.\n </p>\n <p>\n <strong className=\"text-foreground\">2.</strong> Import typed clients\n from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>{' '}\n (regenerated on every manifest save).\n </p>\n <p>\n <strong className=\"text-foreground\">3.</strong> Run{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise module publish --bump patch</code>{' '}\n when you're ready to ship.\n </p>\n </CardContent>\n </Card>\n </main>\n );\n}\n\nfunction Row({ label, value }: { label: string; value: string }) {\n return (\n <div className=\"flex items-baseline justify-between gap-4 border-b border-border/50 pb-2 last:border-0 last:pb-0\">\n <span className=\"text-muted-foreground\">{label}</span>\n <span className=\"font-mono text-sm\">{value}</span>\n </div>\n );\n}\n`;\n}\n\nexport function appApiAuthSignInTs(): string {\n return `// /api/auth/sign-in — kick off the SSO flow.\n//\n// Reads \\`?return_to=\\` from the caller (defaults to '/'). Branches\n// on env:\n//\n// - DASHWISE_DEV_SESSION_ID set (set automatically by\n// \\`dashwise dev\\`): hits /api/auth/dev/sso/start with the dev\n// session id. No installation_id required — the module isn't\n// installed in a workspace yet.\n//\n// - DASHWISE_INSTALLATION_ID set (production / installed-module\n// path): hits /api/auth/sso/start with the installation id.\n//\n// In both cases the backend mints an exchange code + 302s back to\n// \\`/api/auth/callback?code=...\\` where we set the session cookie.\n//\n// Unauthenticated browser hits to either backend endpoint 302 to\n// the DashWise FE \\`/login?return_to=...\\` automatically — you don't\n// need to handle the \"user not logged in\" case here.\nimport { NextResponse } from 'next/server';\n\nexport function GET(request: Request) {\n const url = new URL(request.url);\n const returnTo = url.searchParams.get('return_to') ?? '/';\n const apiBaseUrl = process.env.DASHWISE_API_URL;\n const installationId = process.env.DASHWISE_INSTALLATION_ID;\n const devSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n if (!apiBaseUrl) {\n return new NextResponse(\n 'DASHWISE_API_URL must be set in .env.local',\n { status: 500 },\n );\n }\n if (!installationId && !devSessionId) {\n return new NextResponse(\n 'Either DASHWISE_INSTALLATION_ID (installed module) or DASHWISE_DEV_SESSION_ID ' +\n '(local dev via \\`dashwise dev\\`) must be set. Run \\`dashwise dev\\` to register ' +\n 'a dev session, or set DASHWISE_INSTALLATION_ID after publishing your module.',\n { status: 500 },\n );\n }\n\n // Absolute URL for return_to so the backend knows which host to\n // bounce back to (the callback path is fixed at /api/auth/callback\n // by SDK convention).\n const moduleOrigin = url.origin;\n const absoluteReturnTo = \\`\\${moduleOrigin}\\${returnTo}\\`;\n\n let ssoStart;\n if (devSessionId) {\n // Dev mode wins when both are set — \\`dashwise dev\\` injects\n // DASHWISE_DEV_SESSION_ID into the child env, which overrides\n // whatever was in .env.local. The dev session id keys back to\n // the dev's workspace + callback origin allowlist.\n ssoStart = new URL('/api/auth/dev/sso/start', apiBaseUrl);\n ssoStart.searchParams.set('return_to', absoluteReturnTo);\n ssoStart.searchParams.set('dev_session_id', devSessionId);\n } else {\n ssoStart = new URL('/api/auth/sso/start', apiBaseUrl);\n ssoStart.searchParams.set('return_to', absoluteReturnTo);\n ssoStart.searchParams.set('client_id', installationId);\n }\n return NextResponse.redirect(ssoStart);\n}\n`;\n}\n\nexport function appApiAuthCallbackTs(): string {\n return `// /api/auth/callback — receives \\`?code=&return_to=\\` from the\n// DashWise SSO start endpoint OR \\`?error=&error_description=\\` if the\n// SSO flow failed. Two paths:\n//\n// 1. Success path: exchange \\`?code\\` for a session cookie via\n// \\`exchangeCode()\\`, then redirect to \\`return_to\\`.\n// 2. Error path: SSO returned \\`?error=\\` — redirect to the polished\n// sign-in-error page so the user sees a real error UI instead of\n// a raw 4xx page. The error code maps to known SSO error codes\n// (e.g. \\`access_denied\\`, \\`server_error\\`, \\`invalid_request\\`).\nimport { NextResponse } from 'next/server';\nimport { exchangeCode } from '@dashai/sdk/auth/server';\n\nexport async function GET(request: Request) {\n const url = new URL(request.url);\n const error = url.searchParams.get('error');\n if (error) {\n const target = new URL('/sign-in-error', url.origin);\n target.searchParams.set('code', error);\n const description = url.searchParams.get('error_description');\n if (description) target.searchParams.set('description', description);\n return NextResponse.redirect(target);\n }\n const code = url.searchParams.get('code');\n const returnTo = url.searchParams.get('return_to') ?? '/';\n if (!code) {\n const target = new URL('/sign-in-error', url.origin);\n target.searchParams.set('code', 'missing_code');\n return NextResponse.redirect(target);\n }\n try {\n await exchangeCode(code); // sets the dashwise.session cookie\n } catch (err) {\n const target = new URL('/sign-in-error', url.origin);\n target.searchParams.set('code', 'exchange_failed');\n target.searchParams.set('description', (err as Error).message);\n return NextResponse.redirect(target);\n }\n return NextResponse.redirect(new URL(returnTo, url.origin));\n}\n`;\n}\n\nexport function appApiAuthSignOutTs(): string {\n return `// /api/auth/sign-out — best-effort backend revoke + cookie clear,\n// then redirect to / so the browser actually navigates somewhere\n// after the form POST. A 204 here would leave the user staring at\n// /dashboard with stale-rendered HTML — the cookie WAS cleared but\n// they'd think nothing happened. 303 See Other forces the browser\n// to follow with GET (not re-POST), landing on the public '/' page.\nimport { NextResponse } from 'next/server';\nimport { signOut } from '@dashai/sdk/auth/server';\n\nexport async function POST(request: Request) {\n await signOut();\n return NextResponse.redirect(new URL('/', request.url), 303);\n}\n`;\n}\n\nexport function packageJsonCustom(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^0.8.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n // Styling system — same shadcn + Tailwind 4 stack as the\n // main DashWise frontend, so look-and-feel stays consistent\n // and module authors can add more blocks via the\n // shadcn-studio MCP (`npx shadcn add @shadcn-studio/...`).\n tailwindcss: '^4',\n '@tailwindcss/postcss': '^4',\n 'tw-animate-css': '^1.4.0',\n shadcn: '^4.0.8',\n 'radix-ui': '^1.4.3',\n 'class-variance-authority': '^0.7.1',\n clsx: '^2.1.1',\n 'tailwind-merge': '^3.5.0',\n 'lucide-react': '^0.577.0',\n 'next-themes': '^0.4.6',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n// ── shadcn + Tailwind 4 stack (custom scaffold) ──────────────────────\n//\n// These templates mirror the configuration the main `dashwise-frontend`\n// uses, so visual + UX consistency is preserved across the dashboard\n// and scaffolded modules. The stack: Tailwind 4 (no config file —\n// config lives in `globals.css` via `@import \"tailwindcss\"`), shadcn\n// New York style, oklch theme tokens, lucide icons, next-themes for\n// the dark-mode toggle.\n//\n// Module authors who want more blocks add them via the shadcn-studio\n// MCP workflow: `/cui` for new blocks, `/rui` for refines (see the\n// scaffold's README for the canonical pointer).\n\n/**\n * `components.json` — shadcn config. Pins the style + base color so\n * `npx shadcn add` produces the same look as the rest of the DashWise\n * ecosystem. The two registries (`@shadcn-studio` free + `@ss-components`\n * Pro) are declared so module authors can pull blocks from either\n * without re-running init.\n */\nexport function componentsJson(): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://ui.shadcn.com/schema.json',\n style: 'new-york',\n rsc: true,\n tsx: true,\n tailwind: {\n config: '',\n css: 'app/globals.css',\n baseColor: 'neutral',\n cssVariables: true,\n prefix: '',\n },\n iconLibrary: 'lucide',\n rtl: false,\n aliases: {\n components: '@/components',\n utils: '@/lib/utils',\n ui: '@/components/ui',\n lib: '@/lib',\n hooks: '@/hooks',\n },\n registries: {\n '@shadcn-studio': 'https://shadcnstudio.com/r/{name}.json',\n '@ss-components': {\n url: 'https://shadcnstudio.com/r/components/{name}.json',\n params: {\n email: '${EMAIL}',\n license_key: '${LICENSE_KEY}',\n },\n },\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * `postcss.config.mjs` — Tailwind 4's PostCSS plugin entry. No other\n * plugins needed; the rest of the build is Next.js's defaults.\n */\nexport function postcssConfigMjs(): string {\n return `const config = {\n plugins: {\n \"@tailwindcss/postcss\": {},\n },\n};\n\nexport default config;\n`;\n}\n\n/**\n * `app/globals.css` — Tailwind 4 entry + oklch theme tokens.\n *\n * Tailwind 4 has no `tailwind.config.ts`; config lives here via the\n * `@import \"tailwindcss\"` directive + CSS custom properties. The\n * `:root` block defines the light theme; `.dark` overrides it. Tokens\n * are copied verbatim from the main dashwise-frontend so module authors\n * who later read the frontend code see the same names.\n */\nexport function globalsCss(): string {\n return `@import \"tailwindcss\";\n@import \"tw-animate-css\";\n@import \"shadcn/tailwind.css\";\n\n@custom-variant dark (&:is(.dark *));\n\n:root {\n --background: oklch(1 0 0);\n --foreground: oklch(0.14 0 0);\n --card: oklch(1 0 0);\n --card-foreground: oklch(0.14 0 0);\n --popover: oklch(1 0 0);\n --popover-foreground: oklch(0.14 0 0);\n --primary: oklch(0.2 0 0);\n --primary-foreground: oklch(0.99 0 0);\n --secondary: oklch(0.97 0 0);\n --secondary-foreground: oklch(0.2 0 0);\n --muted: oklch(0.97 0 0);\n --muted-foreground: oklch(0.56 0 0);\n --accent: oklch(0.97 0 0);\n --accent-foreground: oklch(0.2 0 0);\n --destructive: oklch(0.58 0.24 28.48);\n --border: oklch(0.92 0 0);\n --input: oklch(0.92 0 0);\n --ring: oklch(0.71 0 0);\n --radius: 0.625rem;\n\n --font-sans:\n ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,\n \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n --font-mono:\n ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace;\n}\n\n.dark {\n --background: oklch(0.14 0 0);\n --foreground: oklch(0.99 0 0);\n --card: oklch(0.2 0 0);\n --card-foreground: oklch(0.99 0 0);\n --popover: oklch(0.2 0 0);\n --popover-foreground: oklch(0.99 0 0);\n --primary: oklch(0.92 0 0);\n --primary-foreground: oklch(0.2 0 0);\n --secondary: oklch(0.27 0 0);\n --secondary-foreground: oklch(0.99 0 0);\n --muted: oklch(0.27 0 0);\n --muted-foreground: oklch(0.71 0 0);\n --accent: oklch(0.27 0 0);\n --accent-foreground: oklch(0.99 0 0);\n --destructive: oklch(0.7 0.19 22.23);\n --border: oklch(0.27 0 0);\n --input: oklch(0.27 0 0);\n --ring: oklch(0.56 0 0);\n}\n\n* {\n border-color: var(--border);\n}\n\nbody {\n background-color: var(--background);\n color: var(--foreground);\n font-family: var(--font-sans);\n}\n`;\n}\n\n/**\n * `lib/utils.ts` — the canonical \\`cn()\\` helper that shadcn components\n * import. Combines \\`clsx\\` (conditional class composition) with\n * \\`tailwind-merge\\` (resolves conflicting Tailwind utilities, e.g.\n * \\`px-2 px-4\\` → \\`px-4\\`).\n */\nexport function libUtilsTs(): string {\n return `import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n`;\n}\n\n/**\n * \\`components/ui/button.tsx\\` — vendored from the dashwise-frontend's\n * canonical button (which itself came from shadcn New York). Vendored\n * (vs running \\`npx shadcn add\\` in a post-install) so the scaffold\n * doesn't need network access at install time.\n */\nexport function componentsUiButtonTsx(): string {\n return `import * as React from \"react\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport { Slot } from \"radix-ui\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst buttonVariants = cva(\n \"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-white hover:bg-destructive/90\",\n outline:\n \"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost:\n \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-9 px-4 py-2 has-[>svg]:px-3\",\n sm: \"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5\",\n lg: \"h-10 rounded-md px-6 has-[>svg]:px-4\",\n icon: \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n },\n);\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n asChild = false,\n ...props\n}: React.ComponentProps<\"button\"> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean;\n }) {\n const Comp = asChild ? Slot.Root : \"button\";\n return (\n <Comp\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Button, buttonVariants };\n`;\n}\n\n/**\n * \\`components/ui/card.tsx\\` — vendored from the dashwise-frontend. Same\n * rationale as button.tsx.\n */\nexport function componentsUiCardTsx(): string {\n return `import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n );\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n );\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n );\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6\", className)}\n {...props}\n />\n );\n}\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };\n`;\n}\n\n/**\n * \\`components/theme-provider.tsx\\` — thin re-export of the next-themes\n * provider, marked \\`\"use client\"\\`. Layout wraps in this so the\n * \\`.dark\\` class can be applied to \\`<html>\\` based on system preference\n * or explicit user toggle.\n */\nexport function componentsThemeProviderTsx(): string {\n return `\"use client\";\n\nimport { ThemeProvider as NextThemesProvider } from \"next-themes\";\n\nexport function ThemeProvider({\n children,\n ...props\n}: React.ComponentProps<typeof NextThemesProvider>) {\n return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n`;\n}\n\n/**\n * \\`app/sign-in-error/page.tsx\\` — the SSO error landing.\n *\n * Reached via redirect from /api/auth/callback when the SSO flow\n * returns \\`?error=\\` or when code exchange fails. Renders a polished\n * error UI with the SSO error code (plain-English when known) + a\n * \"Try again\" button that retries the sign-in flow.\n *\n * Listed in middleware.ts publicPaths so unauthenticated visitors can\n * actually reach the error page (otherwise the redirect would loop).\n */\nexport function appSignInErrorPageTsx(): string {\n return `import Link from 'next/link';\nimport { AlertTriangle, RefreshCw } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nconst ERROR_MESSAGES: Record<string, string> = {\n access_denied:\n \"You declined the sign-in request. To use this module, you'll need to authorize it on the DashWise sign-in page.\",\n server_error:\n 'The DashWise sign-in server returned an internal error. This is usually transient — try again in a moment.',\n invalid_request:\n 'The sign-in request was malformed. This is almost always a configuration bug — check that DASHWISE_API_URL and DASHWISE_INSTALLATION_ID are set correctly.',\n missing_code:\n 'The callback URL was missing the expected exchange code. This usually means the SSO flow was interrupted.',\n exchange_failed:\n \"The exchange code couldn't be redeemed for a session. The code may have expired (they're single-use and short-lived) — try signing in again.\",\n};\n\ninterface SignInErrorPageProps {\n searchParams: Promise<{ code?: string; description?: string }>;\n}\n\nexport default async function SignInErrorPage({ searchParams }: SignInErrorPageProps) {\n const params = await searchParams;\n const errorCode = params.code ?? 'unknown';\n const friendlyMessage = ERROR_MESSAGES[errorCode];\n return (\n <main className=\"flex min-h-dvh items-center justify-center px-6 py-12\">\n <Card className=\"w-full max-w-lg\">\n <CardHeader>\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-full bg-destructive/10 p-2\">\n <AlertTriangle className=\"size-5 text-destructive\" aria-hidden=\"true\" />\n </div>\n <div className=\"flex-1\">\n <CardTitle>Sign-in failed</CardTitle>\n <CardDescription>\n The DashWise SSO flow couldn't complete.\n </CardDescription>\n </div>\n </div>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Error code\n </div>\n <code className=\"block rounded bg-muted px-2 py-1 text-sm\">\n {errorCode}\n </code>\n </div>\n {friendlyMessage && (\n <p className=\"text-sm text-muted-foreground\">{friendlyMessage}</p>\n )}\n {params.description && (\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Detail\n </div>\n <p className=\"text-sm text-muted-foreground\">{params.description}</p>\n </div>\n )}\n <div className=\"flex flex-wrap gap-2 pt-2\">\n <Button asChild>\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <RefreshCw aria-hidden=\"true\" />\n Try again\n </Link>\n </Button>\n <Button asChild variant=\"ghost\">\n <Link href=\"/\">Back to landing</Link>\n </Button>\n </div>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/** Slug validation matching the manifest schema's regex. */\nexport function isValidSlug(slug: string): boolean {\n return /^[a-z][a-z0-9_-]*$/.test(slug);\n}\n","/**\n * HH-CC-LDI-6 — workspace selection helpers used across commands\n * that need to scope an operation to one workspace (`dashwise init`,\n * `dashwise dev`, future `dashwise module status`, etc.).\n *\n * Two resolution paths emerge from the existing CLI:\n *\n * - **Non-interactive** (CI, scripted) — caller passes `--workspace\n * <slug-or-id>`. We validate against the user's accessible\n * workspaces; throw on miss. Auto-pick if the user has exactly\n * one workspace.\n *\n * - **Interactive** (TTY, no `--workspace` flag) — when the user\n * has multiple workspaces and `interactive: true` is passed, we\n * prompt with @clack's `select`. Otherwise we throw with the\n * same \"re-run with --workspace\" error as the non-interactive\n * path.\n *\n * The split exists because `dashwise dev` was designed for\n * scripting (errors loudly with a re-run hint) and `dashwise init`\n * is designed for interactive onboarding (asks the user to pick).\n * One function, two policies via the `interactive` flag.\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport { apiRequest } from './api-client.js';\n\nexport interface WorkspaceSummary {\n id: number;\n name: string;\n slug: string;\n}\n\n/**\n * Resolve which workspace an operation should target.\n *\n * Resolution order:\n * 1. If `flag` is set → match it against the user's workspaces by\n * slug (preferred) or numeric id; throw if no match.\n * 2. Else if the user has exactly one workspace → auto-pick it.\n * 3. Else if `interactive` and we're in a TTY → prompt with @clack.\n * 4. Else → throw with a \"re-run with --workspace\" hint.\n *\n * `apiToken` is taken explicitly (not from saved config) so callers\n * can pass an in-memory token during the login flow or a per-call\n * override token. Most callers pass `readSavedToken()`.\n */\nexport async function selectWorkspace(opts: {\n apiUrl: string;\n apiToken: string;\n flag?: string;\n interactive: boolean;\n}): Promise<WorkspaceSummary> {\n const workspaces = await apiRequest<WorkspaceSummary[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: opts.apiUrl, auth: { token: opts.apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n\n // Flag path — caller provided a slug or id.\n if (opts.flag !== undefined) {\n return matchWorkspaceOrThrow(workspaces, opts.flag);\n }\n\n // Single workspace — auto-pick. Same behavior in both modes.\n if (workspaces.length === 1) {\n return workspaces[0]!;\n }\n\n // Multiple workspaces — interactive prompt OR throw.\n if (opts.interactive && process.stdout.isTTY) {\n const choice = await select({\n message: 'Which workspace should this module live in?',\n options: workspaces.map((w) => ({\n value: w.slug,\n label: w.name,\n hint: `slug=${w.slug}, id=${w.id}`,\n })),\n });\n if (isCancel(choice)) {\n throw new Error('Aborted.');\n }\n const picked = workspaces.find((w) => w.slug === choice);\n if (!picked) {\n // Shouldn't happen — @clack returns one of the options we\n // gave it — but defensive guard so a TS narrowing failure\n // doesn't surface as a stack trace.\n throw new Error(`Internal error: selection \"${String(choice)}\" did not match any workspace.`);\n }\n return picked;\n }\n\n // Non-interactive multi-workspace case — throw with the re-run hint.\n const list = workspaces\n .map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`)\n .join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n}\n\n/**\n * Match a `--workspace` flag value against the workspace list.\n *\n * Accepts either a slug (preferred) or a numeric id as a string.\n * Throws if there's no match — surfacing the list helps users\n * notice typos.\n *\n * Exported for tests; not part of the typical command surface.\n */\nexport function matchWorkspaceOrThrow(\n workspaces: WorkspaceSummary[],\n flag: string,\n): WorkspaceSummary {\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(`No workspace matching --workspace=${flag}. Available:\\n${list}`);\n }\n return match;\n}\n","/**\n * `dashwise module init <slug>` — scaffold a new DashWise module\n * project in a fresh directory.\n *\n * As of 2026-05-18, the DEFAULT scaffold is the full Next.js custom-\n * module scaffold — a real Next.js 16 app with `middleware.ts`,\n * `/api/auth/*` routes, an `<AuthProvider>` wrap, and a protected\n * `app/dashboard/page.tsx` example. Authentication + workspace\n * context are wired against the DashWise NestJS backend out of the\n * box (per the v1 plan in\n * `dashwise-devops-docs/plans/module-authoring-platform.md`).\n *\n * Files emitted by the default (`custom` kind):\n *\n * module.json — manifest (schema_version 2)\n * package.json — deps on @dashai/sdk + next + react\n * tsconfig.json\n * next.config.mjs\n * next-env.d.ts\n * .gitignore — ignores node_modules + .next + .dashwise/\n * .env.local.example — DASHWISE_* var template\n * middleware.ts — uses withAuth() from @dashai/sdk/auth/middleware\n * app/layout.tsx — wraps {children} in <AuthProvider>\n * app/page.tsx — public landing\n * app/dashboard/page.tsx — protected route using getServerSession()\n * app/api/auth/sign-in/route.ts — kicks off DashWise SSO redirect\n * app/api/auth/callback/route.ts — exchanges one-time code for cookie\n * app/api/auth/sign-out/route.ts — clears cookie + tells backend\n * README.md — getting-started + auth flow explainer\n *\n * For the legacy minimal scaffold (no Next.js auth wiring — purely\n * hand-authored simple-module runtime), pass `--simple`:\n *\n * dashwise module init my-mod --simple\n *\n * This emits 9 files (no middleware, no /api/auth/*, no dashboard).\n * The `--simple` flag is permanent — some module use cases (public\n * data viewers, demo modules) genuinely don't need auth.\n *\n * `--custom` is kept as a back-compat alias for the default and is\n * silently deprecated. New code should not pass either flag for the\n * full scaffold — just `dashwise module init <slug>`.\n *\n * Refuses to overwrite an existing non-empty directory unless\n * `--force` is passed. Does NOT run `npm install` automatically —\n * surfaces the next-step commands at the end of the run.\n */\n\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, text } from '@clack/prompts';\nimport {\n appApiAuthCallbackTs,\n appApiAuthSignInTs,\n appApiAuthSignOutTs,\n appDashboardPageTsx,\n appLayoutCustomTsx,\n appLayoutTsx,\n appPageCustomTsx,\n appPageTsx,\n appSignInErrorPageTsx,\n componentsJson,\n componentsThemeProviderTsx,\n componentsUiButtonTsx,\n componentsUiCardTsx,\n envLocal,\n envLocalExample,\n gitignore,\n globalsCss,\n isValidSlug,\n libUtilsTs,\n manifestJson,\n middlewareTs,\n nextConfig,\n nextEnvDts,\n packageJson,\n packageJsonCustom,\n postcssConfigMjs,\n readme,\n type ScaffoldKind,\n tsconfigJson,\n} from '../../lib/scaffold.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\nimport {\n ApiError,\n createDevInstallation,\n type DevInstallationResponse,\n} from '../../lib/api-client.js';\nimport {\n isLoggedIn,\n readConfig,\n resolveApiUrl,\n upsertModuleEntry,\n} from '../../lib/config.js';\nimport { selectWorkspace } from '../../lib/workspaces.js';\n\nexport interface InitOptions {\n /** Override the target directory (defaults to `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Human-readable module name (default: derive from slug). */\n name?: string;\n /**\n * Use the legacy minimal scaffold (hand-authored simple module —\n * no Next.js auth wiring). Default before 2026-05-18; opt-in now.\n * Mutually exclusive with `custom`; if both are passed, an error\n * is raised before any files are written.\n */\n simple?: boolean;\n /**\n * @deprecated Back-compat alias for the default (full Next.js +\n * auth wiring). New code should call `init` without flags.\n *\n * Kept for back-compat across the v0.x.y series. Will be removed\n * in a future major version. When passed alongside `--simple`,\n * raises an error (mutually exclusive).\n */\n custom?: boolean;\n /** Optional Git repository URL to write into module.json#repository. */\n git?: string;\n /**\n * HH-CC-LDI-6 — skip the provisioning phase (no `POST /api/installations/dev`\n * call, no `auth.json#modules[slug]` write). The local scaffold is\n * created as before; the resulting module has no dev install backing it,\n * so `dashwise dev` / SDK data-plane calls will fail with\n * `UnauthenticatedError` until you run a future\n * `dashwise module provision-dev-install` (LDI-9) or re-run\n * `dashwise init --force`.\n *\n * Commander maps the CLI flag `--no-provision` to `provision: false`;\n * this option is therefore typed as `provision?: boolean` with\n * `undefined` (default) meaning \"provision if logged in\".\n */\n provision?: boolean;\n /**\n * HH-CC-LDI-6 — target workspace slug or numeric id. When omitted +\n * interactive (TTY), the CLI prompts; when omitted + non-interactive\n * (CI), throws if the user has more than one workspace.\n */\n workspace?: string;\n /**\n * HH-CC-LDI-6 — module description forwarded to the backend's\n * `POST /api/installations/dev` request. No effect when\n * `--no-provision`. Defaults to undefined.\n */\n description?: string;\n}\n\nexport async function moduleInitCommand(\n slugArg: string | undefined,\n options: InitOptions,\n): Promise<number> {\n intro('Scaffolding a new DashWise module');\n\n // Resolve slug — prompt if not provided.\n let slug = slugArg;\n if (!slug && process.stdout.isTTY) {\n const answer = await text({\n message: 'Module slug?',\n placeholder: 'tasks',\n validate: (v) =>\n isValidSlug(v) ? undefined : 'Slug must match /^[a-z][a-z0-9_-]*$/',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n slug = answer;\n }\n if (!slug) {\n fail('Usage: `dashwise module init <slug>`');\n return 1;\n }\n if (!isValidSlug(slug)) {\n fail(`Invalid slug ${code(slug)} — must match /^[a-z][a-z0-9_-]*$/`);\n return 1;\n }\n\n // Derive a default human name from the slug if --name wasn't given.\n const name = options.name ?? humanizeSlug(slug);\n const dir = resolve(options.dir ?? slug);\n\n if (existsSync(dir)) {\n const entries = readdirSync(dir);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(dir)} is not empty. Pass ${code('--force')} to scaffold anyway (existing files will be overwritten).`,\n );\n return 1;\n }\n }\n\n // Resolve scaffold kind. As of 2026-05-18 the default is `'custom'`\n // (the full Next.js + auth scaffold); `--simple` opts back to the\n // legacy minimal scaffold; `--custom` is a back-compat no-op alias.\n //\n // Mutually-exclusive flags are caught here before any files are\n // written so the user gets a clean failure instead of \"scaffolded\n // simple but you also passed --custom, which one wins?\".\n if (options.simple && options.custom) {\n fail(\n `Cannot pass both ${code('--simple')} and ${code('--custom')} — they're mutually exclusive. ${code('--simple')} selects the legacy minimal scaffold; the default (no flag) is the full Next.js scaffold (formerly ${code('--custom')}).`,\n );\n return 1;\n }\n const kind: ScaffoldKind = options.simple ? 'hand_authored' : 'custom';\n const scaffoldOpts = {\n slug,\n name,\n kind,\n ...(options.git !== undefined ? { repositoryUrl: options.git } : {}),\n };\n\n // Common files (both flavors).\n const files: Array<[string, string]> = [\n ['module.json', manifestJson(scaffoldOpts)],\n ['tsconfig.json', tsconfigJson()],\n ['next.config.mjs', nextConfig()],\n ['next-env.d.ts', nextEnvDts()],\n ['.gitignore', gitignore()],\n ['.env.local.example', envLocalExample()],\n ['.env.local', envLocal()],\n ['README.md', readme(scaffoldOpts)],\n ];\n\n // Flavor-specific files.\n if (kind === 'custom') {\n // Custom Next.js app with auth wiring + shadcn/Tailwind 4 stack.\n // The shadcn config + base primitives (button, card) are vendored\n // rather than installed via `npx shadcn add` so the scaffold has\n // no network dependency at first run.\n files.push(\n ['package.json', packageJsonCustom(scaffoldOpts)],\n ['middleware.ts', middlewareTs()],\n ['components.json', componentsJson()],\n ['postcss.config.mjs', postcssConfigMjs()],\n ['app/globals.css', globalsCss()],\n ['lib/utils.ts', libUtilsTs()],\n ['components/theme-provider.tsx', componentsThemeProviderTsx()],\n ['components/ui/button.tsx', componentsUiButtonTsx()],\n ['components/ui/card.tsx', componentsUiCardTsx()],\n ['app/layout.tsx', appLayoutCustomTsx(scaffoldOpts)],\n ['app/page.tsx', appPageCustomTsx(scaffoldOpts)],\n ['app/dashboard/page.tsx', appDashboardPageTsx()],\n ['app/sign-in-error/page.tsx', appSignInErrorPageTsx()],\n ['app/api/auth/sign-in/route.ts', appApiAuthSignInTs()],\n ['app/api/auth/callback/route.ts', appApiAuthCallbackTs()],\n ['app/api/auth/sign-out/route.ts', appApiAuthSignOutTs()],\n );\n } else {\n // Hand-authored simple module (isolate runtime).\n files.push(\n ['package.json', packageJson(scaffoldOpts)],\n ['app/layout.tsx', appLayoutTsx(scaffoldOpts)],\n ['app/page.tsx', appPageTsx(scaffoldOpts)],\n );\n }\n\n // We intentionally don't run `npm install` here — the user might\n // want to inspect what we wrote first OR run it in their own shell\n // with their preferred package manager.\n for (const [relPath, content] of files) {\n const absPath = join(dir, relPath);\n const parentDir = join(absPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Scaffolded ${code(slug)} (${kind === 'custom' ? 'custom Next.js' : 'simple module'}) in ${code(dir)}`,\n );\n\n // HH-CC-LDI-6: provisioning phase. After the scaffold lands, talk\n // to the backend to create a real local-dev install + mint a\n // runtime token. Cache the token in `auth.json#modules[slug]` so\n // `dashwise dev` + `@dashai/sdk`'s `createDevClient({ moduleSlug })`\n // can pick it up. Failures here DON'T roll back the scaffold —\n // the user can re-run `dashwise init --force` later (or, once\n // LDI-9 ships, `dashwise module provision-dev-install`).\n let devInstall: DevInstallationResponse | null = null;\n const wantsProvision = options.provision !== false; // default = true\n if (wantsProvision) {\n // FUP-2: forward the scaffold's module_kind so the backend stamps\n // it on the draft manifest at provision time. `kind` here is the\n // ScaffoldKind we just resolved above (custom | hand_authored).\n devInstall = await tryProvisionDevInstall({\n slug,\n name,\n description: options.description,\n workspaceFlag: options.workspace,\n moduleKind: kind,\n });\n } else {\n info(\n `Skipping provisioning (${code('--no-provision')}). ${dim(\"Run with provisioning later to enable `dashwise dev` data-plane.\")}`,\n );\n }\n\n info(`Next steps:`);\n process.stdout.write(`\n ${dim('1.')} ${code(`cd ${dir}`)}\n ${dim('2.')} ${code('npm install')}\n ${dim('3.')} ${code('dashwise dev')} ${dim('# one command: watcher + next dev, auth auto-injected')}\n\n ${dim(' (or, for the two-terminal flow:')}\n ${dim(' dashwise module generate')} ${dim('# materialize typed wrappers')}\n ${dim(' dashwise module dev')} ${dim('# watch + auto-regenerate')}\n ${dim(' npm run dev:next # next dev on :3000)')}\n${\n devInstall\n ? `\n ${dim(`Dev installation id=${devInstall.installation.id}; runtime token expires ${devInstall.runtime_token_expires_at}.`)}\n`\n : ''\n}`);\n outro('Happy authoring.');\n return 0;\n}\n\n/**\n * HH-CC-LDI-6 — provisioning sub-flow for `dashwise init`.\n *\n * Returns the API response on success, or `null` on a recoverable\n * failure (not logged in, network error, backend down). All failures\n * are surfaced to the user with `warn(...)` so they know what to fix;\n * the parent caller continues with a successful scaffold.\n *\n * Errors that should be unrecoverable (slug conflict, kind mismatch,\n * any 4xx from the backend) are surfaced as warnings too — the user\n * can re-init with a different slug or destroy the conflicting\n * install (LDI-9) without losing their local scaffold.\n *\n * Exported as an internal because the integration is hard to unit-\n * test through `moduleInitCommand` (intro/outro/text prompts +\n * filesystem). Tests that need to exercise this path can call this\n * function directly.\n */\nasync function tryProvisionDevInstall(args: {\n slug: string;\n name: string;\n description?: string;\n workspaceFlag?: string;\n /**\n * FUP-2: scaffold's `module_kind`. Stamped on the backend's draft\n * manifest at create time so the first getManifest() read returns\n * this value instead of falling back to `'ai_builder'`.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n}): Promise<DevInstallationResponse | null> {\n if (!isLoggedIn()) {\n warn(\n `Not logged in — skipping dev-install provisioning. Run ${code('dashwise login')} then ${code(`dashwise init ${args.slug} --force`)} to retry.`,\n );\n return null;\n }\n const cfg = readConfig();\n if (!cfg) {\n // Defense — isLoggedIn() returned true so cfg should exist; if\n // it doesn't, the file got removed between the two reads. Treat\n // as not-logged-in.\n warn('CLI config disappeared mid-init. Skipping provisioning.');\n return null;\n }\n\n let workspace;\n try {\n workspace = await selectWorkspace({\n apiUrl: resolveApiUrl(),\n apiToken: cfg.token,\n flag: args.workspaceFlag,\n interactive: true,\n });\n } catch (err) {\n warn(`Workspace selection failed: ${(err as Error).message}`);\n return null;\n }\n info(\n `Provisioning dev install in workspace ${code(workspace.slug)} (id=${workspace.id})…`,\n );\n\n let response: DevInstallationResponse;\n try {\n response = await createDevInstallation(\n {\n slug: args.slug,\n name: args.name,\n ...(args.description !== undefined ? { description: args.description } : {}),\n workspaceId: workspace.id,\n ...(args.moduleKind !== undefined ? { moduleKind: args.moduleKind } : {}),\n },\n { baseUrl: resolveApiUrl(), auth: { token: cfg.token } },\n );\n } catch (err) {\n if (err instanceof ApiError) {\n surfaceProvisionApiError(err, args.slug);\n return null;\n }\n warn(`Provisioning failed: ${(err as Error).message}`);\n return null;\n }\n\n // Persist the runtime token. If THIS step fails (disk full,\n // permissions, etc.) we MUST tell the user the token so they can\n // recover manually — the server-side install was created and\n // there's no point in re-creating it.\n try {\n upsertModuleEntry(args.slug, {\n runtimeToken: response.runtime_token,\n installationId: response.installation.id,\n expiresAt: response.runtime_token_expires_at,\n });\n } catch (err) {\n warn(\n `Provisioned successfully (installation id=${response.installation.id}) but failed to cache the runtime token: ${(err as Error).message}\\n` +\n ` Runtime token (save this manually): ${response.runtime_token}\\n` +\n ` Token expires: ${response.runtime_token_expires_at}`,\n );\n return response;\n }\n\n success(\n `Provisioned dev install id=${response.installation.id}. Runtime token cached in your CLI config.`,\n );\n return response;\n}\n\n/**\n * Map a known `ApiError.code` to a user-friendly recovery hint.\n * Anything unmapped falls back to printing the raw envelope.\n */\nfunction surfaceProvisionApiError(err: ApiError, slug: string): void {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n warn(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then ${code(`dashwise init ${slug} --force`)}.`,\n );\n return;\n case 'FORBIDDEN':\n warn(\n `Not authorized to create a module in that workspace. Confirm you're a member at the DashWise dashboard.`,\n );\n return;\n case 'SLUG_ALREADY_EXISTS':\n // The backend's POST /api/installations/dev maps the upstream\n // createDraft 409 ConflictException to this code; the user\n // either picks a different slug or, once LDI-9 ships,\n // destroys the existing install.\n warn(\n `A module with slug ${code(slug)} already exists. Pick a different slug, or destroy the existing dev install (LDI-9 coming soon) and re-run.`,\n );\n return;\n case 'RUNTIME_DATA_API_DISABLED':\n warn(\n `Backend has the local-dev API turned off (BUILDER_SESSION_TOKEN_SECRET unset). Contact the operator.`,\n );\n return;\n default:\n warn(\n `Provisioning failed (${err.code} ${err.status}): ${err.message}`,\n );\n }\n}\n\n/** Convert `tasks-app` → `Tasks app` for a friendly default name. */\nfunction humanizeSlug(slug: string): string {\n const words = slug.replace(/[-_]/g, ' ').split(/\\s+/).filter(Boolean);\n if (words.length === 0) return slug;\n const first = words[0];\n const cap = first.charAt(0).toUpperCase() + first.slice(1);\n return [cap, ...words.slice(1)].join(' ');\n}\n","/**\n * `dashwise module destroy-dev-install [--module <slug>]`\n *\n * HH-CC-LDI-9 — tear down the local-dev install for a module. Reads\n * the current module's slug from `module.json` by default; pass\n * `--module <slug>` to target a different one (useful when the\n * project directory's manifest is gone but the auth.json entry\n * still lingers).\n *\n * Sequence:\n * 1. Resolve slug + install id from auth.json#modules[slug].\n * 2. DELETE /api/installations/dev/:id (audited as\n * DESTROY_DEV_INSTALLATION on the backend).\n * 3. Remove the auth.json#modules[slug] entry.\n *\n * If the backend returns 404 INSTALLATION_NOT_FOUND, we still clean\n * up the local auth.json entry — the install is gone on the server\n * already, no point in leaving a dangling token client-side.\n */\n\nimport { isCancel, confirm } from '@clack/prompts';\nimport { resolve as resolvePath } from 'node:path';\nimport {\n ApiError,\n destroyDevInstallation,\n} from '../../lib/api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n removeModuleEntry,\n resolveApiUrl,\n} from '../../lib/config.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DestroyDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: read from local module.json). */\n module?: string;\n /** Skip the confirmation prompt — for CI. */\n yes?: boolean;\n}\n\nexport async function destroyDevInstallCommand(\n options: DestroyDevInstallOptions,\n): Promise<number> {\n // ── 1. Resolve slug ────────────────────────────────────────────────\n let slug = options.module;\n if (!slug) {\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n slug = manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n }\n\n // ── 2. Find the cached install id ──────────────────────────────────\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n warn(\n `No cached dev install for ${code(slug)} in auth.json. Nothing to do.`,\n );\n return 0;\n }\n\n // ── 3. Confirm (skipped with --yes) ────────────────────────────────\n if (!options.yes && process.stdout.isTTY) {\n const choice = await confirm({\n message: `Destroy dev install ${code(`${slug} (id=${entry.installationId})`)}? Tables and rows will be soft-deleted (recoverable for 30 days via dashboard trash).`,\n });\n if (isCancel(choice) || !choice) {\n info('Aborted.');\n return 130;\n }\n }\n\n // ── 4. DELETE on backend ───────────────────────────────────────────\n let backendCleaned = false;\n try {\n const response = await destroyDevInstallation(entry.installationId, {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n });\n backendCleaned = true;\n success(\n `Destroyed dev install ${code(`${slug} (id=${response.installation_id})`)}${\n response.module_also_dropped\n ? ' — module also dropped (no other installs, unpublished).'\n : ' (module kept — other installs reference it or it has a published version).'\n }`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.code === 'INSTALLATION_NOT_FOUND') {\n // Already gone server-side; clean up the local entry anyway.\n warn(\n `Install ${entry.installationId} not found on the backend — already destroyed elsewhere. Cleaning up local cache.`,\n );\n backendCleaned = true;\n } else {\n return surfaceDestroyError(err);\n }\n }\n\n // ── 5. Clean up auth.json ──────────────────────────────────────────\n if (backendCleaned) {\n try {\n removeModuleEntry(slug);\n info(`Removed ${code(slug)} entry from auth.json.`);\n } catch (err) {\n warn(\n `Backend cleanup succeeded but failed to update auth.json: ${(err as Error).message}. Edit ${code('~/.config/dashwise/auth.json')} manually to remove the ${code(`modules[\"${slug}\"]`)} entry.`,\n );\n }\n }\n\n return 0;\n}\n\nfunction surfaceDestroyError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'INSTALLATION_KIND_NOT_LOCAL':\n fail(\n `Refusing to destroy: the install isn't kind=local (it may have been promoted to production). Use the dashboard's uninstall flow instead.`,\n );\n break;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of the install's workspace. Contact a workspace admin.`,\n );\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend — your CLI bearer may be stale. Re-run ${code('dashwise login')} and try again.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise module reset-dev-install`\n *\n * HH-CC-LDI-9 — destroy + re-create the local-dev install for the\n * current module. Useful when:\n * - Test data has accumulated and you want a clean slate\n * - The cached runtime token has been compromised + you want a\n * fresh one without the LDI-9.x rotate-token endpoint\n * - Schema is in a wedged state and you want to start over from\n * the local module.json\n *\n * Implementation: composes `destroyDevInstallCommand` +\n * `moduleInitCommand({ provision: true, force: true })`. Both phases\n * are interactive in a TTY (with `--yes` to skip prompts).\n *\n * If destroy fails the reset bails — we don't want to provision a\n * second install while a stale one still exists (the backend would\n * 409 SLUG_ALREADY_EXISTS anyway).\n */\n\nimport { resolve as resolvePath } from 'node:path';\nimport { destroyDevInstallCommand } from './destroy-dev-install.js';\nimport { moduleInitCommand } from './init.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info } from '../../lib/output.js';\n\nexport interface ResetDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: from local module.json). */\n module?: string;\n /** Target workspace for re-provisioning (passed to init). */\n workspace?: string;\n /** Skip confirmation prompts in both destroy + init phases. */\n yes?: boolean;\n}\n\nexport async function resetDevInstallCommand(\n options: ResetDevInstallOptions,\n): Promise<number> {\n // We need both a slug AND the module's display name (init re-uses\n // these on re-create). Read once from module.json so destroy + init\n // both agree on the target.\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n\n const slug = options.module ?? manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n const name = manifest?.module?.name ?? slug;\n\n // ── Phase 1: destroy ──────────────────────────────────────────────\n info(`Resetting dev install for ${code(slug)} — phase 1/2: destroy…`);\n const destroyExit = await destroyDevInstallCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n module: slug,\n ...(options.yes !== undefined ? { yes: options.yes } : {}),\n });\n if (destroyExit !== 0) {\n fail(\n `Destroy phase failed (exit ${destroyExit}); aborting reset. Fix the underlying error and re-run.`,\n );\n return destroyExit;\n }\n\n // ── Phase 2: re-init / provision ──────────────────────────────────\n info(`Reset phase 2/2: re-provisioning…`);\n return moduleInitCommand(slug, {\n name,\n ...(options.dir !== undefined ? { dir: options.dir } : { dir: projectRoot }),\n // `--force` so init doesn't refuse to overwrite the existing\n // module.json (we're keeping the local scaffold; only the\n // backend install is being recreated).\n force: true,\n // Keep the current scaffold layout — don't try to detect or\n // change `simple` vs `custom`. The user can re-init manually\n // with `dashwise init` if they want to swap scaffolds.\n provision: true,\n ...(options.workspace !== undefined ? { workspace: options.workspace } : {}),\n });\n}\n","/**\n * HH-CC-LDI-8 — shared setup for `dashwise table` / `dashwise field`\n * commands.\n *\n * Each schema-mutation command needs the same six things:\n *\n * 1. The project root (containing `module.json`)\n * 2. The current manifest (parsed) + the raw bytes (for rollback)\n * 3. The module's slug\n * 4. The CLI's saved config (apiUrl + bearer + ...)\n * 5. The per-module dev install entry (`auth.json#modules[slug]`)\n * — runtime token + installation id\n * 6. A `RequestOptions` ready to pass to the api-client helpers\n *\n * `loadSchemaCommandContext()` centralises that — commands stay\n * focused on the operation itself instead of repeating the setup\n * boilerplate.\n *\n * Errors at any step throw a user-readable `Error` (no stack trace\n * surface area); commands catch + `fail(err.message)` + return 1.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join, resolve as resolvePath } from 'node:path';\nimport type { RequestOptions } from './api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n resolveApiUrl,\n type CliConfig,\n type CliConfigModuleEntry,\n} from './config.js';\nimport {\n readManifestOrThrow,\n type ManifestShape,\n} from './manifest-io.js';\n\nexport interface SchemaCommandContext {\n projectRoot: string;\n manifestPath: string;\n manifest: ManifestShape;\n /** Verbatim file bytes — preserved so commands that want to do\n * edit-first-with-rollback have something to restore from. */\n manifestRawBytes: string;\n slug: string;\n cfg: CliConfig;\n entry: CliConfigModuleEntry;\n /**\n * Pre-built RequestOptions targeting the per-module runtime token.\n * Pass directly to api-client helpers (createTable, addField, etc.).\n * Uses the bound install's runtime token, NOT the CLI bearer —\n * the REST endpoints require a kind=local runtime token.\n */\n requestOptions: RequestOptions;\n}\n\n/**\n * Load + validate the four prerequisites for any schema-mutation\n * command. Throws on any missing piece with a clear \"how to fix\"\n * error message.\n */\nexport function loadSchemaCommandContext(opts: {\n dir?: string;\n}): SchemaCommandContext {\n const projectRoot = resolvePath(opts.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n\n // Use readManifestOrThrow for a typed \"doesn't exist / unreadable\"\n // failure mode; capture the raw bytes for potential rollback paths.\n const manifest = readManifestOrThrow<ManifestShape>(projectRoot);\n const manifestRawBytes = readFileSync(manifestPath, 'utf-8');\n\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json at ${manifestPath} has no module.slug — the manifest is malformed.`,\n );\n }\n\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n\n return {\n projectRoot,\n manifestPath,\n manifest,\n manifestRawBytes,\n slug,\n cfg,\n entry,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: entry.runtimeToken },\n },\n };\n}\n","/**\n * HH-CC-LDI-8 — parse `--field <slug>:<type>[:flags]` syntax for\n * `dashwise table create` / `dashwise field add`.\n *\n * Grammar (regular):\n *\n * spec := <slug> ':' <type> [ ':' <flag> (',' <flag>)* ]\n * slug := snake_case, ^[a-z][a-z0-9_]*[a-z0-9]$\n * type := one of FIELD_TYPES (defined here to avoid a backend\n * import; kept in sync with manifest-schema.ts on the\n * server side)\n * flag := 'required' | 'unique' (v1 — extend as needed)\n *\n * Examples:\n * \"title:text\" → { slug:'title', type:'text' }\n * \"title:text:required\" → { slug:'title', type:'text', required:true }\n * \"tags:multi_select:required\" → { slug:'tags', type:'multi_select', required:true }\n *\n * For field types that need extra config (`single_select` / `multi_select`\n * with `options`, `link_row` with `target`, `formula` with `formula`,\n * `ai` with `prompt`), use `--field-json '{...}'` instead — the JSON\n * shape mirrors `FieldDefBody` from `api-client.ts`. This split keeps\n * the simple syntax actually simple while still supporting the rich\n * cases.\n *\n * Pure function — easy to unit-test. No I/O.\n */\n\nimport type { FieldDefBody } from './api-client.js';\n\n/**\n * Closed set of field types the backend accepts. Mirrors\n * `dashwise-backend/src/modules/modules/manifest/manifest-schema.ts:FIELD_TYPES`.\n * Kept here to avoid a backend dep; backend's manifest validator is\n * still the source of truth at apply-time.\n */\nexport const FIELD_TYPES = [\n 'text',\n 'long_text',\n 'number',\n 'boolean',\n 'date',\n 'datetime',\n 'single_select',\n 'multi_select',\n 'link_row',\n 'file',\n 'multi_file',\n 'email',\n 'url',\n 'phone',\n 'formula',\n 'ai',\n] as const;\nexport type FieldType = (typeof FIELD_TYPES)[number];\n\nconst SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\nconst KNOWN_FLAGS = new Set(['required', 'unique']);\n\n/**\n * Parse a single `--field <slug>:<type>[:flags]` spec into a FieldDef\n * body. Throws with a clear error message if any part is malformed —\n * callers surface to the user via `fail()`.\n */\nexport function parseFieldSpec(spec: string): FieldDefBody {\n const parts = spec.split(':');\n if (parts.length < 2) {\n throw new FieldSpecError(\n `Field spec ${quote(spec)} is malformed — expected ${quote('<slug>:<type>[:flags]')}.`,\n );\n }\n const [slug, type, ...flagParts] = parts;\n\n if (!SLUG_REGEX.test(slug!)) {\n throw new FieldSpecError(\n `Field slug ${quote(slug!)} must match ${quote(SLUG_REGEX.source)} (snake_case, 2+ chars).`,\n );\n }\n\n if (!(FIELD_TYPES as readonly string[]).includes(type!)) {\n throw new FieldSpecError(\n `Field type ${quote(type!)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n\n const result: FieldDefBody = { slug: slug!, type: type! };\n\n if (flagParts.length > 0) {\n // Flags are comma-separated within a single colon segment OR\n // each flag is its own colon segment. We accept both for\n // ergonomics: `name:text:required,unique` and\n // `name:text:required:unique` both parse the same.\n const flags = flagParts\n .flatMap((segment) => segment.split(','))\n .map((f) => f.trim())\n .filter((f) => f.length > 0);\n\n for (const flag of flags) {\n if (!KNOWN_FLAGS.has(flag)) {\n throw new FieldSpecError(\n `Unknown flag ${quote(flag)} in field spec ${quote(spec)}. Known flags: ${[...KNOWN_FLAGS].join(', ')}. For options/target/default, use ${quote('--field-json')} instead.`,\n );\n }\n if (flag === 'required') result.required = true;\n // `unique` is a table-level index concern, not a field-level\n // attribute on FieldDef — we accept the flag for forward\n // compat with `dashwise table create --field foo:text:unique`\n // but turning it into a table-level unique index belongs in\n // the calling command. Silently dropped here; the command\n // handler reads it from the raw spec if it cares.\n }\n }\n\n // Types that need options / target / formula / prompt can't be\n // expressed in the simple syntax — direct the user to --field-json.\n // We validate post-flag-parse so the type check fires before the\n // options check (better error ordering for the user).\n if (\n (type === 'single_select' || type === 'multi_select') &&\n result.options === undefined\n ) {\n throw new FieldSpecError(\n `Type ${quote(type)} requires an ${quote('options')} list. Use ${quote('--field-json')} for this field — e.g. ${quote(`'{\"slug\":\"${slug}\",\"type\":\"${type}\",\"options\":[\"a\",\"b\"]}'`)}.`,\n );\n }\n if (type === 'link_row' && result.target === undefined) {\n throw new FieldSpecError(\n `Type ${quote('link_row')} requires a ${quote('target')}. Use ${quote('--field-json')}.`,\n );\n }\n if (type === 'formula' || type === 'ai') {\n throw new FieldSpecError(\n `Type ${quote(type)} requires extra config (${quote('formula')} or ${quote('prompt')}). Use ${quote('--field-json')}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Parse a `--field-json '<json>'` value into a FieldDef body. Just a\n * thin wrapper around `JSON.parse` with shape validation against\n * `FieldDefBody`. Pure function.\n */\nexport function parseFieldJson(json: string): FieldDefBody {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err) {\n throw new FieldSpecError(\n `--field-json value is not valid JSON: ${(err as Error).message}`,\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new FieldSpecError('--field-json must be a JSON object.');\n }\n const o = parsed as Record<string, unknown>;\n if (typeof o.slug !== 'string' || !SLUG_REGEX.test(o.slug)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('slug')}. Must match ${quote(SLUG_REGEX.source)}.`,\n );\n }\n if (typeof o.type !== 'string' || !(FIELD_TYPES as readonly string[]).includes(o.type)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('type')}. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n // The rest of the fields are best-effort — the backend's manifest\n // validator is the final authority on what shapes are accepted.\n // Cast through unknown because Record<string, unknown> doesn't\n // structurally narrow to FieldDefBody (we've validated slug + type\n // above, which is enough for the runtime path).\n return o as unknown as FieldDefBody;\n}\n\nexport class FieldSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'FieldSpecError';\n }\n}\n\nfunction quote(s: string): string {\n return `\\`${s}\\``;\n}\n","/**\n * `dashwise table create <slug> --field <spec>... [--field-json <json>...]`\n *\n * HH-CC-LDI-8 — create a new table in the current module's manifest +\n * materialize it as a physical Postgres table in the dev installation.\n *\n * Flow (REST-first / write-back-from-GET):\n * 1. Load context (manifest slug, runtime token, install id).\n * 2. Parse `--field` + `--field-json` flags into a FieldDef array.\n * 3. POST /api/installations/:id/schema/tables (LDI-4 endpoint).\n * 4. GET /api/installations/:id/schema to fetch the new manifest.\n * 5. Write the response to local module.json.\n *\n * No local-mutation logic — the backend's `SchemaProposeService`\n * is the source of truth for the manifest shape after the operation.\n * If the POST succeeds but the GET fails, local module.json is left\n * stale; `dashwise dev` reconciles on next startup.\n */\n\nimport { writeManifest, type ManifestShape } from '../../lib/manifest-io.js';\nimport {\n ApiError,\n createTable,\n getInstallationSchema,\n type FieldDefBody,\n} from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface TableCreateOptions {\n dir?: string;\n field?: string[];\n fieldJson?: string[];\n}\n\nexport async function tableCreateCommand(\n slug: string | undefined,\n options: TableCreateOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table create <slug> --field <slug>:<type>[:required] [...]`');\n return 1;\n }\n\n // ── 1. Build the FieldDef array from --field + --field-json flags ──\n const fields: FieldDefBody[] = [];\n try {\n for (const spec of options.field ?? []) {\n fields.push(parseFieldSpec(spec));\n }\n for (const json of options.fieldJson ?? []) {\n fields.push(parseFieldJson(json));\n }\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n if (fields.length === 0) {\n fail(\n `At least one field is required. Use ${code('--field <slug>:<type>')} (repeatable) or ${code(\"--field-json '{...}'\")} for fields with options/target/default.`,\n );\n return 1;\n }\n\n // Detect duplicate slugs within the input (the backend also rejects\n // but a local check gives a clearer error than the round-trip).\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.slug)) {\n fail(`Duplicate field slug ${code(f.slug)} in --field flags.`);\n return 1;\n }\n seen.add(f.slug);\n }\n\n // ── 2. Load command context ────────────────────────────────────────\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 3. POST /api/installations/:id/schema/tables ───────────────────\n info(`Creating table ${code(slug)} in installation ${ctx.entry.installationId}…`);\n try {\n const result = await createTable(\n ctx.entry.installationId,\n { slug, fields },\n ctx.requestOptions,\n );\n success(\n `Created table ${code(slug)} (physical_table_id=${result.physical_table_id}, manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n // ── 4. GET /schema + write back to local module.json ───────────────\n return syncLocalManifest(ctx);\n}\n\n/**\n * After a successful schema mutation, fetch the new server-side\n * manifest and write it to local `module.json`. Shared by every\n * schema-mutation command.\n *\n * Failure here is non-fatal — the mutation already succeeded\n * server-side, the local file just gets stale. We surface a warning\n * + tell the user to retry via `dashwise module reconcile` (future\n * LDI-9 sub-command) OR they can re-run their next `dashwise dev`\n * which will pick up the latest manifest automatically.\n */\nexport async function syncLocalManifest(\n ctx: ReturnType<typeof loadSchemaCommandContext>,\n): Promise<number> {\n try {\n const { manifest } = await getInstallationSchema(\n ctx.entry.installationId,\n ctx.requestOptions,\n );\n writeManifest(manifest as ManifestShape, ctx.projectRoot);\n return 0;\n } catch (err) {\n if (err instanceof ApiError) {\n warn(\n `Schema sync to local module.json failed (${err.code} ${err.status}): ${err.message}. The mutation succeeded server-side; re-run your next command to retry the local sync.`,\n );\n } else {\n warn(\n `Schema sync to local module.json failed: ${(err as Error).message}. The mutation succeeded server-side.`,\n );\n }\n // Exit 0 — the operation succeeded, only the local sync didn't.\n return 0;\n }\n}\n\n/**\n * Translate an ApiError from a schema-mutation REST call into a\n * user-facing failure message. Reused by every table/field command\n * since they all surface the same set of codes from\n * `SchemaProposeService → InstallationSchemaController.mapServiceError`.\n */\nexport function surfaceFailure(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'TABLE_SLUG_EXISTS':\n fail(`A table with this slug already exists in the manifest.`);\n break;\n case 'FIELD_SLUG_EXISTS':\n fail(`A field with this slug already exists on the table.`);\n break;\n case 'TABLE_NOT_FOUND':\n fail(`Table not found in the manifest.`);\n break;\n case 'FIELD_NOT_FOUND':\n fail(`Field not found on the table.`);\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Runtime token rejected by backend. The cached token may be expired — re-run \\`dashwise init <slug> --force\\` to mint a fresh one.`,\n );\n break;\n case 'SANDBOX_TOKEN_NOT_ACCEPTED':\n fail(\n `Schema-mutation endpoints require a local-dev runtime token (kind=local). The cached token is the wrong kind — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALL_MISMATCH':\n fail(\n `Runtime token is bound to a different installation than the URL. The cached install id may be stale — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise table delete <slug>`\n *\n * HH-CC-LDI-8 — drop a table from the current module. Calls LDI-4's\n * `DELETE /api/installations/:id/schema/tables/:tableSlug`, which\n * (via the backend's `applyManifestDelta`) soft-deletes the physical\n * table — recoverable for 30 days through the dashboard's trash.\n *\n * Same REST-first / write-back-from-GET pattern as `table create`.\n */\n\nimport { dropTable } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from './create.js';\n\nexport interface TableDeleteOptions {\n dir?: string;\n}\n\nexport async function tableDeleteCommand(\n slug: string | undefined,\n options: TableDeleteOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table delete <slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(`Dropping table ${code(slug)} from installation ${ctx.entry.installationId}…`);\n try {\n const result = await dropTable(\n ctx.entry.installationId,\n slug,\n ctx.requestOptions,\n );\n success(\n `Dropped table ${code(slug)} (manifest_version=${result.manifest_version}). Physical table soft-deleted; recoverable for 30 days via the dashboard's trash.`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field add <table-slug> <field-spec>`\n *\n * HH-CC-LDI-8 — add a new field to an existing table. The field spec\n * uses the same `<slug>:<type>[:flags]` syntax as `dashwise table\n * create --field`, OR the `--field-json '{...}'` escape hatch for\n * options/target/default.\n *\n * Examples:\n * dashwise field add tasks title:text:required\n * dashwise field add tasks done:boolean\n * dashwise field add tasks priority --field-json '{\"slug\":\"priority\",\"type\":\"single_select\",\"options\":[\"low\",\"medium\",\"high\"]}'\n *\n * REST-first / write-back-from-GET pattern (same as `table create`).\n */\n\nimport { addField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldAddOptions {\n dir?: string;\n fieldJson?: string;\n}\n\nexport async function fieldAddCommand(\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n options: FieldAddOptions,\n): Promise<number> {\n if (!tableSlug) {\n fail(\n 'Usage: `dashwise field add <table-slug> <field-slug>:<type>[:required]` or `dashwise field add <table-slug> --field-json \\'{...}\\'`',\n );\n return 1;\n }\n\n // The field can come from either the positional `<spec>` arg OR\n // `--field-json`. Exactly one must be supplied; both would be\n // ambiguous (which wins?).\n const hasPositional = fieldSpec !== undefined;\n const hasJson = options.fieldJson !== undefined;\n if (!hasPositional && !hasJson) {\n fail(\n `Pass either a field spec (e.g. ${code('title:text:required')}) or ${code('--field-json')} with the field's JSON definition.`,\n );\n return 1;\n }\n if (hasPositional && hasJson) {\n fail(\n `Pass only ONE of the field spec or ${code('--field-json')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n let field;\n try {\n field = hasJson\n ? parseFieldJson(options.fieldJson!)\n : parseFieldSpec(fieldSpec!);\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Adding field ${code(`${tableSlug}.${field.slug}`)} (${field.type}) to installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await addField(\n ctx.entry.installationId,\n { table_slug: tableSlug, field },\n ctx.requestOptions,\n );\n success(\n `Added field ${code(`${tableSlug}.${field.slug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field remove <table-slug> <field-slug>`\n *\n * HH-CC-LDI-8 — remove a field from a table. The backend's\n * `proposeField(operation='remove')` includes the M2-C-FIX\n * cascading-index-cleanup: any index referencing the removed field\n * is trimmed, and if the index becomes empty it's dropped entirely.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { removeField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldRemoveOptions {\n dir?: string;\n}\n\nexport async function fieldRemoveCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n options: FieldRemoveOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug) {\n fail('Usage: `dashwise field remove <table-slug> <field-slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Removing field ${code(`${tableSlug}.${fieldSlug}`)} from installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await removeField(\n ctx.entry.installationId,\n tableSlug,\n fieldSlug,\n ctx.requestOptions,\n );\n success(\n `Removed field ${code(`${tableSlug}.${fieldSlug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field set-type <table-slug> <field-slug> <new-type>`\n *\n * HH-CC-LDI-8 — change an existing field's type. Maps to LDI-4's\n * `PATCH /api/installations/:id/schema/fields/:tableSlug/:fieldSlug`\n * with the new type passed in the body.\n *\n * Lossy type changes (text → number with non-numeric data; multi_select\n * → single_select with multi-value rows) are deferred to v1.1 per\n * `local-dev-installs-v1.md` §8.2 — the backend's manifest validator\n * rejects the unsafe cases today; v1.1 adds a structured\n * `RETYPE_UNSAFE` precheck.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { updateField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { FIELD_TYPES } from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldSetTypeOptions {\n dir?: string;\n}\n\nexport async function fieldSetTypeCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n options: FieldSetTypeOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug || !newType) {\n fail(\n 'Usage: `dashwise field set-type <table-slug> <field-slug> <new-type>`',\n );\n return 1;\n }\n if (!(FIELD_TYPES as readonly string[]).includes(newType)) {\n fail(\n `Type ${code(newType)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Setting type of ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} on installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await updateField(\n ctx.entry.installationId,\n tableSlug,\n fieldSlug,\n { type: newType },\n ctx.requestOptions,\n );\n success(\n `Updated ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise dev` — the one-command local dev loop.\n *\n * What it does:\n * 1. Verifies the developer has run `dashwise login` (i.e. the auth.json\n * config file exists). Bails with a clear pointer otherwise.\n * 2. Resolves `DASHWISE_API_URL`, `DASHWISE_API_TOKEN`,\n * `DASHWISE_INSTALLATION_ID` from (a) explicit flags, (b) existing\n * env vars, (c) the saved CLI config — and injects them into BOTH\n * child processes' env so the SDK can authenticate without the\n * developer ever touching `.env.local`.\n * 3. Spawns two children:\n * - `dashwise module dev` — manifest watcher + SDK regen loop\n * - `next dev` — Next.js dev server\n * Both stdout/stderr streams are line-prefixed with `[sdk]` and\n * `[next]` so a single terminal can show both subsystems' output\n * without confusion.\n * 4. Forwards SIGINT/SIGTERM to both children, waits for them to exit,\n * then exits itself with the worst child's exit code (so CI catches\n * a crash on either side).\n *\n * Why two child processes rather than running `module dev` in-process:\n * - Symmetric output prefixing — same code path handles both.\n * - Signal isolation — Ctrl-C is forwarded cleanly to both, neither\n * can interfere with the other's shutdown by throwing async.\n * - Failure isolation — a crash in `module dev`'s generator can't\n * take down `next dev` or vice versa; users see a clear \"[sdk]\n * exited with code 1, [next] still running\" line.\n *\n * The Next.js process gets spawned via `npx next dev` (or the project's\n * own `dev:next` script if present), which avoids hard-coding a path\n * to the user's local node_modules.\n */\n\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve as resolvePath } from 'node:path';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport { readConfig, readModuleEntry } from '../lib/config.js';\nimport { readManifest } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../lib/output.js';\n\nexport interface DevCommandOptions {\n /** Project directory containing `module.json`. Defaults to cwd. */\n dir?: string;\n /**\n * Override the `DASHWISE_INSTALLATION_ID` env var passed to children.\n *\n * When set to a real installation id (numeric), prod-mode SSO is used\n * — the SDK's middleware hits `/api/auth/sso/start?client_id=<id>`\n * and that installation must already exist in your workspace.\n *\n * When NOT set (the default), `dashwise dev` registers a dev session\n * with the backend and injects `DASHWISE_DEV_SESSION_ID` instead —\n * no installation required (see auth/spec.md § Dev-Mode SSO).\n */\n installationId?: string;\n /**\n * Override the `DASHWISE_API_URL` env var passed to children.\n * Defaults to the saved CLI config's `apiUrl`.\n */\n apiUrl?: string;\n /**\n * Port for `next dev`. Defaults to 3000 — used both for the child\n * spawn AND for computing the default dev-session callback origin\n * (`http://localhost:<port>`).\n */\n port?: number;\n /**\n * Workspace to scope the dev session to. Either a numeric id (`'42'`)\n * or a slug (`'my-workspace'`). When omitted, defaults to the user's\n * primary workspace if they have only one; errors out asking for an\n * explicit `--workspace` if they have multiple.\n *\n * Only relevant when using dev-mode SSO (the default — ignored if\n * `--installation-id` is passed).\n */\n workspace?: string;\n /**\n * Additional callback origins to allowlist on the dev session, beyond\n * the default `http://localhost:<port>`. Repeatable.\n *\n * Example: `--callback-origin https://myapp.local` for custom-domain\n * local dev. Each origin must be a fully-qualified http(s) URL.\n *\n * Only relevant when using dev-mode SSO.\n */\n callbackOrigin?: string[];\n /**\n * Skip the Next.js dev server — only run the manifest watcher.\n * Useful if the developer is running `next dev` separately for\n * some reason (e.g. they want a debugger attached to it).\n */\n sdkOnly?: boolean;\n /**\n * Skip the manifest watcher — only run `next dev`. Symmetric escape\n * hatch to `--sdk-only`.\n */\n nextOnly?: boolean;\n}\n\n/**\n * Default port for the scaffolded Next.js dev server. Used both for\n * the `--port` default AND for computing the default callback origin\n * passed to `POST /api/auth/dev/sessions`. Single source of truth —\n * if the user overrides one without the other, the dev session's\n * allowlist won't match the actual dev server origin and SSO fails\n * with `INVALID_RETURN_TO`.\n */\nconst DEFAULT_NEXT_PORT = 3000;\n\n/**\n * ANSI-styled prefix prepended to every line of a child's output.\n * Colors are kept faint so a long dev session doesn't strain the eye.\n *\n * `[sdk]` is cyan-ish, `[next]` is magenta-ish — they map cleanly to\n * the two subsystems and stay distinguishable on dark + light terminals.\n */\nconst PREFIX_SDK = `\\x1b[36m[sdk]\\x1b[0m `;\nconst PREFIX_NEXT = `\\x1b[35m[next]\\x1b[0m `;\n\nexport async function devCommand(\n options: DevCommandOptions,\n): Promise<number> {\n if (options.sdkOnly && options.nextOnly) {\n fail(\n `Cannot pass both ${code('--sdk-only')} and ${code('--next-only')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifestPath = `${projectRoot}/module.json`;\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info(`Run ${code('dashwise module init <slug>')} to scaffold a new module first.`);\n return 1;\n }\n\n // HH-CC-LDI-7: read the manifest to learn this module's slug, so we\n // can look up its per-module runtime token from auth.json#modules[slug].\n // Failing to parse the manifest isn't fatal — `module dev` will catch\n // it downstream with a clearer error message. We just lose the\n // runtime-token injection in that case.\n const manifestSlug = (() => {\n try {\n return readManifest(projectRoot)?.module?.slug;\n } catch {\n return undefined;\n }\n })();\n\n // ── 1. Auth resolution ───────────────────────────────────────────────\n // Saved config is the source of truth; --api-url / env can override\n // individual fields. Refuse to start if no auth at all — the dev\n // server would just 401 on every request.\n const savedConfig = (() => {\n try {\n return readConfig();\n } catch {\n // Corrupt config — treat as if not logged in. The login command\n // will surface the real error if re-run.\n return null;\n }\n })();\n\n const apiToken = process.env.DASHWISE_API_TOKEN ?? savedConfig?.token;\n if (!apiToken) {\n fail(`Not authenticated. Run ${code('dashwise login')} first.`);\n info(\n 'The unified dev loop reads your CLI token from ~/.config/dashwise/auth.json ' +\n 'and injects it into both child processes so the SDK can authenticate ' +\n 'without you editing .env.local.',\n );\n return 1;\n }\n const apiUrl =\n options.apiUrl ??\n process.env.DASHWISE_API_URL ??\n savedConfig?.apiUrl ??\n 'http://localhost:3000';\n const port = options.port ?? DEFAULT_NEXT_PORT;\n\n // ── 2. Resolve auth mode ─────────────────────────────────────────────\n // Three paths, in priority order:\n //\n // (a) `--installation-id <id>` (or `DASHWISE_INSTALLATION_ID` env)\n // — prod-like mode. SDK's sign-in route uses /sso/start with\n // client_id=<id>. The installation must already exist.\n //\n // (b) `DASHWISE_DEV_SESSION_ID` env set (e.g. for testing) — reuse\n // the existing dev session id without re-registering.\n //\n // (c) Default — register a fresh dev session with the backend,\n // inject DASHWISE_DEV_SESSION_ID into the child env, revoke\n // on graceful shutdown.\n const explicitInstallationId =\n options.installationId ?? process.env.DASHWISE_INSTALLATION_ID;\n const reuseDevSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n // HH-CC-LDI-7: per-module runtime-token lookup. We read it BEFORE\n // the auth-mode branching below so the path can branch on its\n // presence — but we don't make the runtime token gate dev-session\n // setup. The two are orthogonal: the dev session powers SSO sign-in\n // callbacks for end users hitting the running module; the runtime\n // token powers the SDK's data-plane calls. Both can be active\n // simultaneously.\n const moduleEntry =\n manifestSlug !== undefined ? readModuleEntry(manifestSlug) : null;\n const runtimeTokenEnv = process.env.DASHWISE_RUNTIME_TOKEN ?? moduleEntry?.runtimeToken;\n\n let installationIdEnv: string | undefined;\n let devSessionIdEnv: string | undefined;\n let revokeDevSession: (() => Promise<void>) | undefined;\n\n if (explicitInstallationId && explicitInstallationId !== 'local') {\n installationIdEnv = explicitInstallationId;\n } else if (reuseDevSessionId) {\n devSessionIdEnv = reuseDevSessionId;\n } else {\n // Default — register a dev session.\n let workspaceContext: { id: number; name: string; slug: string };\n try {\n workspaceContext = await resolveTargetWorkspace(apiUrl, apiToken, options.workspace);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n const callbackOrigins = computeCallbackOrigins(port, options.callbackOrigin ?? []);\n try {\n const session = await registerDevSession(apiUrl, apiToken, {\n target_workspace_id: workspaceContext.id,\n callback_origins: callbackOrigins,\n });\n devSessionIdEnv = session.id;\n revokeDevSession = () => revokeDevSessionBestEffort(apiUrl, apiToken, session.id);\n info(` ${dim('dev session')} ${session.id}`);\n info(` ${dim('workspace')} ${workspaceContext.name} (id=${workspaceContext.id}, slug=${workspaceContext.slug})`);\n info(` ${dim('callbacks')} ${callbackOrigins.join(', ')}`);\n info(` ${dim('expires')} ${session.expires_at}`);\n } catch (err) {\n if (err instanceof ApiError) {\n fail(`Failed to register dev session: ${err.code} — ${err.message}`);\n } else {\n fail(`Failed to register dev session: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // ── 3. Build child env ───────────────────────────────────────────────\n // Inherit the parent's env so user-set vars (e.g. NEXT_TELEMETRY_DISABLED,\n // NODE_OPTIONS) flow through unchanged. Overlay the DASHWISE_* vars\n // so the SDK can read them — these win over anything the user set\n // in .env.local because Next.js loads .env.local AFTER process.env.\n //\n // Set DASHWISE_INSTALLATION_ID to empty string when in dev mode so\n // the scaffolded sign-in route sees `process.env.DASHWISE_INSTALLATION_ID\n // === ''` (falsy) and correctly branches on DASHWISE_DEV_SESSION_ID\n // instead — without explicitly unsetting an inherited value.\n //\n // HH-CC-LDI-7: when a per-module runtime token is available (from\n // auth.json#modules[slug] written by `dashwise init`, or from a\n // DASHWISE_RUNTIME_TOKEN env override), inject it into the child env\n // so `@dashai/sdk`'s `createDevClient()` can pick it up for the\n // data plane. We also flip DASHWISE_INSTALLATION_ID to the literal\n // 'sandbox' (URL placeholder for runtime-token auth) WHEN no\n // explicit installation id is set — the backend's RuntimeTokenGuard\n // resolves the actual install from the JWT claims, not the URL.\n const childInstallationId =\n installationIdEnv ??\n (runtimeTokenEnv !== undefined ? 'sandbox' : '');\n const childEnv: Record<string, string | undefined> = {\n ...process.env,\n DASHWISE_API_URL: apiUrl,\n // HH-CC-FUP-3: client-side mirror. Next.js inlines NEXT_PUBLIC_*\n // env vars into the browser bundle at build time (or, in dev, at\n // process-start time). Without this, the SDK's <AuthProvider> hits\n // `/api/auth/sessions/me` on its own origin (localhost:<port>),\n // 404s, and stays unauthenticated. We mirror DASHWISE_API_URL so\n // the client + server agree on the backend origin without the\n // module author having to touch .env.local.\n NEXT_PUBLIC_DASHWISE_API_URL: apiUrl,\n DASHWISE_API_TOKEN: apiToken,\n DASHWISE_INSTALLATION_ID: childInstallationId,\n ...(devSessionIdEnv !== undefined ? { DASHWISE_DEV_SESSION_ID: devSessionIdEnv } : {}),\n ...(runtimeTokenEnv !== undefined\n ? { DASHWISE_RUNTIME_TOKEN: runtimeTokenEnv }\n : {}),\n };\n\n // ── 4. Pre-flight banner ─────────────────────────────────────────────\n info(`Dev loop starting — Ctrl-C to stop.`);\n info(` ${dim('api')} ${apiUrl}`);\n if (installationIdEnv !== undefined) {\n info(` ${dim('installation')} ${installationIdEnv} (prod-mode SSO)`);\n } else {\n info(` ${dim('mode')} dev (DASHWISE_DEV_SESSION_ID injected)`);\n }\n info(` ${dim('token')} ${maskedToken(apiToken)} ${dim(`(from ${apiToken === savedConfig?.token ? '~/.config/dashwise/auth.json' : '$DASHWISE_API_TOKEN'})`)}`);\n // HH-CC-LDI-7: surface the runtime-token source so developers know\n // which auth credentials the SDK will pick up. Three observable\n // states:\n // - cached: per-module entry in auth.json (the LDI-6 happy path)\n // - env: DASHWISE_RUNTIME_TOKEN explicit override\n // - missing: no runtime token; data-plane calls will fail with\n // UnauthenticatedError. Surface a hint to run `dashwise init`.\n if (runtimeTokenEnv !== undefined) {\n const source =\n process.env.DASHWISE_RUNTIME_TOKEN === runtimeTokenEnv\n ? '$DASHWISE_RUNTIME_TOKEN'\n : `~/.config/dashwise/auth.json#modules[${manifestSlug}]`;\n const installId = moduleEntry?.installationId;\n info(\n ` ${dim('runtime')} ${maskedToken(runtimeTokenEnv)} ${dim(`(from ${source}${installId ? `, install id=${installId}` : ''})`)}`,\n );\n } else if (manifestSlug !== undefined && installationIdEnv === undefined) {\n // No runtime token + no explicit install id → the SDK's data plane\n // will 401 on every call. Print a one-line hint so the dev knows\n // why; don't block the dev loop because SSO + scaffolding still\n // work without it.\n warn(\n `No runtime token cached for module ${code(manifestSlug)}. ` +\n `Data-plane calls (db, qb) will fail with UnauthenticatedError. ` +\n `Run ${code(`dashwise init ${manifestSlug} --force`)} to provision a dev install + cache the token.`,\n );\n }\n info('');\n\n // ── 4. Spawn children ────────────────────────────────────────────────\n const children: { name: string; child: ChildProcess; prefix: string }[] = [];\n\n if (!options.nextOnly) {\n const sdkChild = spawnSdkWatcher(projectRoot, childEnv);\n children.push({ name: 'sdk', child: sdkChild, prefix: PREFIX_SDK });\n }\n if (!options.sdkOnly) {\n // Always pass `port` (default DEFAULT_NEXT_PORT, overridden by\n // --port). This ensures the actual dev server port matches the\n // dev session's callback origin allowlist computed above.\n const nextChild = spawnNextDev(projectRoot, childEnv, port);\n children.push({ name: 'next', child: nextChild, prefix: PREFIX_NEXT });\n }\n\n // ── 5. Wire output multiplexing ──────────────────────────────────────\n for (const { child, prefix } of children) {\n pipeWithPrefix(child.stdout, process.stdout, prefix);\n pipeWithPrefix(child.stderr, process.stderr, prefix);\n }\n\n // ── 6. Signal forwarding + exit aggregation ─────────────────────────\n let shuttingDown = false;\n const forwardSignal = (sig: NodeJS.Signals) => {\n if (shuttingDown) return;\n shuttingDown = true;\n info(`\\nReceived ${sig}, stopping children…`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill(sig);\n }\n }\n // Best-effort revoke the dev session — fire-and-forget so we\n // don't delay shutdown if the API is slow. If the request fails\n // (offline, backend down, etc.) the dev session naturally expires\n // in 24h, so the leftover is harmless.\n if (revokeDevSession) {\n revokeDevSession().catch(() => {\n /* swallowed — best-effort */\n });\n }\n };\n process.on('SIGINT', () => forwardSignal('SIGINT'));\n process.on('SIGTERM', () => forwardSignal('SIGTERM'));\n\n // Wait for each child's exit. Aggregate exit codes — if either fails\n // non-zero (and we didn't kill it intentionally), surface the worst\n // code so CI catches a crash.\n const results = await Promise.all(\n children.map(\n ({ name, child }) =>\n new Promise<{ name: string; code: number; killed: boolean }>(\n (resolveExit) => {\n child.on('exit', (exitCode, signal) => {\n const killed = signal !== null;\n const finalCode =\n exitCode ?? (killed ? 0 : 1); // signal-only exit treated as clean\n resolveExit({ name, code: finalCode, killed });\n });\n },\n ),\n ),\n );\n\n // If ANY child exits non-zero AND wasn't killed by our signal forward,\n // kill the others so we don't leave orphans. Then aggregate.\n const crashed = results.find((r) => !r.killed && r.code !== 0);\n if (crashed && !shuttingDown) {\n warn(`[${crashed.name}] exited with code ${crashed.code} — stopping others.`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill('SIGTERM');\n }\n }\n }\n\n const exitCode = Math.max(0, ...results.map((r) => r.code));\n if (exitCode === 0) {\n success('Dev loop stopped cleanly.');\n }\n return exitCode;\n}\n\n// ── Internals ───────────────────────────────────────────────────────────\n\n/**\n * Spawn `dashwise module dev` as a child. We re-exec the same CLI binary\n * via `process.execPath` + `process.argv[1]` so we never depend on the\n * binary being on $PATH (npm-install-globally is common but not\n * universal; pnpm workspace setups can put the bin in a non-PATH\n * directory).\n *\n * The child inherits stdio for stdin (so a future interactive-prompt\n * inside `module dev` could still work), but stdout/stderr are piped so\n * we can prefix the lines.\n */\nfunction spawnSdkWatcher(\n projectRoot: string,\n env: Record<string, string | undefined>,\n): ChildProcess {\n const child = spawn(\n process.execPath,\n [process.argv[1]!, 'module', 'dev', '--dir', projectRoot],\n {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n );\n return child;\n}\n\n/**\n * Spawn `next dev`. We prefer the project's `dev:next` npm script (which\n * the scaffold writes out) so the dev experience stays consistent with\n * what a user gets when running `npm run dev:next` directly. Falls back\n * to `npx next dev` if no script is defined.\n *\n * Pass `--port` explicitly if the caller asked, otherwise let Next pick\n * its default (3000 by default; Next falls forward to 3001/3002/...\n * when the port is taken — our local backend usually owns 3000).\n */\nfunction spawnNextDev(\n projectRoot: string,\n env: Record<string, string | undefined>,\n port: number | undefined,\n): ChildProcess {\n const portArgs = port !== undefined ? ['--', '--port', String(port)] : [];\n const hasDevNextScript = hasNpmScript(projectRoot, 'dev:next');\n // npm/yarn/pnpm differ on how they locate `next` — the safest cross-tool\n // path is to delegate to the project's own package manager via `npm run\n // dev:next`. If the script is missing, fall back to `npx next dev`.\n const [cmd, args] = hasDevNextScript\n ? ['npm', ['run', 'dev:next', ...portArgs]]\n : ['npx', ['next', 'dev', ...(port !== undefined ? ['--port', String(port)] : [])]];\n\n const child = spawn(cmd, args, {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Windows requires `shell: true` for `npm` / `npx` because they're\n // `.cmd` shims, not real binaries.\n shell: process.platform === 'win32',\n });\n return child;\n}\n\n/**\n * Read the project's `package.json` and check whether the named script\n * exists. Returns false on any error (missing package.json, malformed\n * JSON, etc.) — the caller falls back to npx in that case.\n */\nfunction hasNpmScript(projectRoot: string, scriptName: string): boolean {\n try {\n const pkgPath = `${projectRoot}/package.json`;\n if (!existsSync(pkgPath)) return false;\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n return typeof pkg.scripts?.[scriptName] === 'string';\n } catch {\n return false;\n }\n}\n\n/**\n * Pipe a child's readable stream into our output stream, prefixing each\n * line with the given prefix. Uses line-buffered prefixing: partial\n * lines (no trailing newline) get prefixed too so e.g. spinner output\n * still surfaces — but if a child emits a stream of \\r-overwrites for a\n * fancy progress bar, the prefix collapses correctly because we re-emit\n * the partial line as-is.\n *\n * Edge case: if the stream is null (child was spawned without piping),\n * silently no-op. Real spawn calls above always pipe both, so this is\n * defence-in-depth.\n */\nfunction pipeWithPrefix(\n src: NodeJS.ReadableStream | null,\n dst: NodeJS.WritableStream,\n prefix: string,\n): void {\n if (!src) return;\n let leftover = '';\n src.on('data', (chunk: Buffer | string) => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');\n const combined = leftover + text;\n const lines = combined.split('\\n');\n leftover = lines.pop() ?? '';\n for (const line of lines) {\n dst.write(`${prefix}${line}\\n`);\n }\n });\n src.on('end', () => {\n if (leftover.length > 0) {\n dst.write(`${prefix}${leftover}\\n`);\n }\n });\n}\n\n/**\n * Mask a bearer token for log display. Shows the prefix (so users can\n * recognize WHICH token is being used — `dwc_*` vs JWT etc.) and a\n * 4-char tail (for distinguishing between two tokens at a glance) but\n * never the middle.\n */\nfunction maskedToken(token: string): string {\n if (token.length <= 12) return '****';\n const prefix = token.slice(0, 4);\n const tail = token.slice(-4);\n return `${prefix}…${tail}`;\n}\n\n// ── Dev-Mode SSO session lifecycle ──────────────────────────────────────\n\ninterface WorkspaceListItem {\n id: number;\n name: string;\n slug: string;\n}\n\ninterface DevSessionApiResponse {\n id: string;\n target_workspace_id: number;\n allowed_callback_origins: string[];\n expires_at: string;\n}\n\n/**\n * Compute the dev session's allowed callback origins. Defaults to the\n * dev server's bind URL (`http://localhost:<port>`); the user can add\n * more via `--callback-origin <url>` (repeatable).\n *\n * Backend validates each entry is a well-formed http(s) URL — we do\n * NOT pre-validate here; let the BE's error response (with code\n * `INVALID_CALLBACK_ORIGIN`) be the source of truth.\n */\nfunction computeCallbackOrigins(port: number, extra: string[]): string[] {\n const def = `http://localhost:${port}`;\n // De-dup: prevent the BE from rejecting a list with redundant\n // entries (the BE doesn't reject — it stores them as-is — but\n // sending unique values is the kinder client behavior).\n return Array.from(new Set([def, ...extra]));\n}\n\n/**\n * Resolve the target workspace for the dev session, given the\n * optional `--workspace` flag. Three paths:\n *\n * - Flag is numeric → treat as id, fetch by id.\n * - Flag is non-numeric → treat as slug, look up.\n * - Flag absent → list user's workspaces. If exactly 1, auto-pick.\n * If 0, error. If >1, error with a list so the user can pick.\n *\n * Returns `{ id, name, slug }` for the chosen workspace.\n */\nasync function resolveTargetWorkspace(\n apiUrl: string,\n apiToken: string,\n flag: string | undefined,\n): Promise<{ id: number; name: string; slug: string }> {\n const workspaces = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n if (flag === undefined) {\n if (workspaces.length === 1) {\n return workspaces[0];\n }\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`).join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n }\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(\n `No workspace matching --workspace=${flag}. Available:\\n${list}`,\n );\n }\n return match;\n}\n\n/**\n * `POST /api/auth/dev/sessions`. CLI-token authenticated. Returns the\n * dev session row the SDK keys off of.\n */\nasync function registerDevSession(\n apiUrl: string,\n apiToken: string,\n body: { target_workspace_id: number; callback_origins: string[] },\n): Promise<DevSessionApiResponse> {\n return apiRequest<DevSessionApiResponse>(\n 'POST',\n '/api/auth/dev/sessions',\n body,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n\n/**\n * `DELETE /api/auth/dev/sessions/:id`. Best-effort — errors are\n * swallowed by the caller. If the call fails (offline, BE down,\n * CLI token revoked since registration), the session naturally\n * expires within 24h so leaving it is harmless.\n */\nasync function revokeDevSessionBestEffort(\n apiUrl: string,\n apiToken: string,\n id: string,\n): Promise<void> {\n await apiRequest<void>(\n 'DELETE',\n `/api/auth/dev/sessions/${encodeURIComponent(id)}`,\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n","/**\n * `dashwise login` — OAuth 2.0 Device Authorization Grant.\n *\n * Flow:\n * 1. POST /api/auth/cli/device-code → get `userCode` + `verificationUri`\n * 2. Display the code + URL; offer to open the browser\n * 3. Poll /api/auth/cli/poll on the published interval until the\n * user approves (or denies / it expires)\n * 4. On `approved`, save the returned token to ~/.config/dashwise/auth.json\n * 5. Fetch /api/auth/me to confirm + cache user identity\n *\n * UX: clack spinner during the poll loop; explicit prompts when\n * something needs the user's attention (e.g. opening the browser).\n * Non-interactive mode (`--no-prompt`) skips browser-open + just\n * prints the URL.\n */\n\nimport { cancel, intro, isCancel, log, outro, select, spinner } from '@clack/prompts';\nimport open from 'open';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type {\n AuthMeResponse,\n CliDeviceCodeResponse,\n CliPollResponse,\n} from '../lib/backend-types.js';\nimport { resolveApiUrl, writeConfig, type CliConfig } from '../lib/config.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\nexport interface LoginOptions {\n /** Override the backend URL for this login (`--api-url`). */\n apiUrl?: string;\n /** Skip the \"open in browser\" prompt; just print the URL. */\n noPrompt?: boolean;\n /** Token name to suggest to the backend (shown in `me/cli-tokens`). */\n name?: string;\n}\n\nconst DEFAULT_TOKEN_NAME = 'dashwise-cli';\n\nexport async function loginCommand(options: LoginOptions): Promise<number> {\n const apiUrl = (options.apiUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n intro(`Logging into ${code(apiUrl)}`);\n\n // 1. Kick off the device-code grant.\n let dc: CliDeviceCodeResponse;\n try {\n dc = await apiRequest<CliDeviceCodeResponse>(\n 'POST',\n '/api/auth/cli/device-code',\n {\n name: options.name ?? DEFAULT_TOKEN_NAME,\n },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n fail(formatApiError('Could not start login flow', err));\n return 1;\n }\n\n log.message(\n [\n `Open the verification URL and confirm the code:`,\n ``,\n ` URL: ${code(dc.verificationUriComplete)}`,\n ` Code: ${code(dc.userCode)}`,\n ``,\n dim(\n `Code expires in ${formatSeconds(dc.expiresIn)}. The CLI will keep polling until you approve.`,\n ),\n ].join('\\n'),\n );\n\n // 2. Offer to open the browser (skipped in non-interactive mode).\n if (!options.noPrompt && process.stdout.isTTY) {\n const choice = await select({\n message: 'Open the verification URL in your browser?',\n options: [\n { value: 'open', label: 'Open now' },\n { value: 'skip', label: 'I’ll open it manually' },\n ],\n initialValue: 'open',\n });\n if (isCancel(choice)) {\n cancel('Login cancelled.');\n return 130; // SIGINT-equivalent exit code\n }\n if (choice === 'open') {\n try {\n await open(dc.verificationUriComplete);\n } catch (err) {\n info(`Could not open browser automatically (${(err as Error).message}). Open the URL above manually.`);\n }\n }\n }\n\n // 3. Poll until approved / denied / expired / overall deadline.\n const sp = spinner();\n sp.start('Waiting for approval');\n const overallDeadline = Date.now() + dc.expiresIn * 1000;\n let outcome: CliPollResponse | null = null;\n // Use 1s sleeps + let the backend's `slow_down` response push us\n // back if we exceed the published interval. Cheap; no need to be\n // clever with the polling cadence.\n const pollIntervalMs = Math.max(1000, dc.interval * 1000);\n\n pollLoop: while (Date.now() < overallDeadline) {\n let res: CliPollResponse;\n try {\n res = await apiRequest<CliPollResponse>(\n 'POST',\n '/api/auth/cli/poll',\n { deviceCode: dc.deviceCode },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n sp.stop(`Poll failed: ${(err as Error).message}`);\n fail('Poll failed mid-flight; you can re-run `dashwise login` to retry.');\n return 1;\n }\n switch (res.status) {\n case 'pending':\n case 'slow_down':\n await sleep(pollIntervalMs);\n continue pollLoop;\n case 'denied':\n sp.stop('Login denied by user.');\n cancel('Aborted.');\n return 1;\n case 'expired':\n sp.stop('Login code expired.');\n fail('The code expired before approval. Run `dashwise login` again.');\n return 1;\n case 'approved':\n outcome = res;\n break pollLoop;\n }\n }\n\n if (!outcome) {\n sp.stop('Timed out waiting for approval.');\n fail('Login took too long to be approved. Run `dashwise login` again.');\n return 1;\n }\n\n if (!outcome.token || !outcome.tokenId) {\n // Shouldn't happen on a fresh approval — but guard anyway.\n sp.stop('Approval received but token missing from response.');\n fail(\n 'Approval received but the backend did not return a token. Run `dashwise logout` then `dashwise login` to retry.',\n );\n return 1;\n }\n\n // 4. Confirm the token works + cache the profile.\n let me: AuthMeResponse;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me', undefined, {\n auth: { token: outcome.token },\n baseUrl: apiUrl,\n });\n } catch (err) {\n sp.stop('Approval accepted but profile fetch failed.');\n fail(formatApiError('Could not load user profile', err));\n return 1;\n }\n\n const cfg: CliConfig = {\n apiUrl,\n token: outcome.token,\n tokenId: outcome.tokenId,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(cfg);\n sp.stop('Approved.');\n success(`Logged in as ${code(me.email)}`);\n outro('You can now run `dashwise profile`, `dashwise workspace list`, etc.');\n return 0;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction formatSeconds(seconds: number): string {\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n return `${minutes}m`;\n}\n\nfunction formatApiError(prefix: string, err: unknown): string {\n if (err instanceof ApiError) {\n return `${prefix}: ${err.message} (code: ${err.code}, status: ${err.status})`;\n }\n if (err instanceof Error) return `${prefix}: ${err.message}`;\n return `${prefix}: ${String(err)}`;\n}\n","/**\n * `dashwise logout` — clear the local credentials and best-effort\n * revoke the server-side token row.\n *\n * Behavior:\n * 1. Read the saved config; if there's no token, exit 0 with an\n * info message (idempotent).\n * 2. Call `DELETE /api/auth/cli-tokens/:id` to revoke the row.\n * 404 / 403 / network errors are tolerated — the local file is\n * cleared regardless. We never want a server-side hiccup to\n * keep stale credentials on disk.\n * 3. Delete the local config file.\n */\n\nimport { apiRequest } from '../lib/api-client.js';\nimport { deleteConfig, readConfig } from '../lib/config.js';\nimport { code, info, success, warn } from '../lib/output.js';\n\nexport async function logoutCommand(): Promise<number> {\n let cfg;\n try {\n cfg = readConfig();\n } catch {\n // Corrupt file — clearing it is precisely what `logout` should do.\n deleteConfig();\n success('Cleared a corrupted local credential file.');\n return 0;\n }\n if (!cfg) {\n info('Already logged out (no saved credentials).');\n return 0;\n }\n\n // Best-effort server-side revocation.\n try {\n await apiRequest(\n 'DELETE',\n `/api/auth/cli-tokens/${cfg.tokenId}`,\n undefined,\n { auth: { token: cfg.token }, baseUrl: cfg.apiUrl },\n );\n } catch (err) {\n warn(\n `Could not revoke the server-side token (${(err as Error).message}). Local credentials cleared anyway.`,\n );\n }\n\n deleteConfig();\n success(`Logged out ${code(cfg.user.email)}`);\n return 0;\n}\n","/**\n * `dashwise profile` — show the current user + (briefly) workspaces.\n *\n * Reads the saved config first so the basic identity prints\n * instantly; then makes a live `/api/auth/me` call to refresh the\n * cached profile (network errors are tolerated — we fall back to\n * the cached values and warn).\n *\n * Output is plain key/value to stdout so the command is pipeable\n * (e.g. `dashwise profile | grep email`). For machine-readable\n * output a future `--json` flag is the right call.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { AuthMeResponse, WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, warn } from '../lib/output.js';\n\nexport interface ProfileOptions {\n /** Emit the profile + workspaces as a single JSON object instead of human-readable kv pairs. */\n json?: boolean;\n}\n\nexport async function profileCommand(options: ProfileOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Refresh identity. Tolerate transient network errors.\n let me: AuthMeResponse | null = null;\n let refreshError: string | null = null;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n refreshError = (err as Error).message;\n if (!options.json) {\n warn(\n `Could not refresh profile from the server (${refreshError}). Showing cached values.`,\n );\n }\n }\n\n if (me) {\n // Persist any drift between cached + server values.\n const refreshed = {\n ...cfg,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(refreshed);\n }\n const u = (me ?? toMe(cfg.user));\n\n // Workspace list — best-effort.\n let workspaces: WorkspaceListItem[] = [];\n let workspaceError: string | null = null;\n try {\n const fetched = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n );\n workspaces = Array.isArray(fetched) ? fetched : [];\n } catch (err) {\n workspaceError = (err as Error).message;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n user: {\n id: u.id,\n username: u.username,\n email: u.email,\n first_name: u.first_name,\n last_name: u.last_name,\n },\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces,\n api_url: cfg.apiUrl,\n ...(refreshError ? { profile_refresh_error: refreshError } : {}),\n ...(workspaceError ? { workspaces_error: workspaceError } : {}),\n }),\n );\n return 0;\n }\n\n out('');\n kv('User ID', `${u.id}`);\n kv('Username', u.username);\n kv('Email', u.email);\n kv('Name', `${u.first_name} ${u.last_name}`.trim() || dim('(not set)'));\n\n out('');\n if (workspaceError) {\n warn(\n `Could not list workspaces (${workspaceError}). Try \\`dashwise workspace list\\`.`,\n );\n } else if (workspaces.length === 0) {\n info('No workspaces yet.');\n } else {\n kv('Workspaces', `${workspaces.length}`);\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const star = cfg.workspaceSlug === slug ? code(' (default)') : '';\n out(` - ${slug}${role ? dim(` [${role}]`) : ''}${star} ${dim(w.name)}`);\n }\n }\n\n out('');\n kv('API URL', cfg.apiUrl);\n return 0;\n}\n\nfunction toMe(cached: { id: number; email: string; username: string; firstName: string; lastName: string }): AuthMeResponse {\n return {\n id: cached.id,\n email: cached.email,\n username: cached.username,\n first_name: cached.firstName,\n last_name: cached.lastName,\n is_staff: false,\n is_active: true,\n date_joined: '',\n };\n}\n","/**\n * `dashwise workspace list` — list workspaces the user belongs to.\n * `dashwise workspace use <slug>` — set the default workspace (saved\n * to ~/.config/dashwise/auth.json).\n *\n * The \"default workspace\" is consumed by subsequent commands\n * (`module init`, `module publish`, etc.) so the user doesn't have\n * to pass `--workspace <slug>` every time. Persists across\n * `dashwise` invocations until `workspace use` is called again.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, success } from '../lib/output.js';\n\nexport interface WorkspaceListOptions {\n json?: boolean;\n}\n\nexport async function workspaceListCommand(options: WorkspaceListOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n let workspaces: WorkspaceListItem[];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces: Array.isArray(workspaces) ? workspaces : [],\n }),\n );\n return 0;\n }\n if (!Array.isArray(workspaces) || workspaces.length === 0) {\n info('No workspaces yet.');\n return 0;\n }\n out('');\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const isDefault = cfg.workspaceSlug === slug;\n const marker = isDefault ? code(' *') : ' ';\n out(`${marker} ${slug.padEnd(28)} ${dim(w.name)}${role ? dim(` [${role}]`) : ''}`);\n }\n out('');\n if (cfg.workspaceSlug) {\n info(`Default workspace: ${code(cfg.workspaceSlug)}`);\n } else {\n info('No default workspace set. Use `dashwise workspace use <slug>` to set one.');\n }\n return 0;\n}\n\nexport async function workspaceUseCommand(slug: string): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (typeof slug !== 'string' || slug.length === 0) {\n fail('Usage: `dashwise workspace use <slug>`');\n return 1;\n }\n // Validate the slug exists + the user has access. Avoids the\n // footgun of setting a default to a workspace the user can't\n // actually use.\n let workspaces: WorkspaceListItem[] = [];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n fail(`Could not validate the workspace (${(err as Error).message}).`);\n return 1;\n }\n const match = workspaces.find(\n (w) => w.slug === slug || `id:${w.id}` === slug || String(w.id) === slug,\n );\n if (!match) {\n fail(`Workspace ${code(slug)} not found in your accessible workspaces.`);\n out('');\n info('Run `dashwise workspace list` to see what you can choose.');\n return 1;\n }\n const matchedSlug = match.slug ?? `id:${match.id}`;\n writeConfig({ ...cfg, workspaceSlug: matchedSlug });\n success(`Default workspace set to ${code(matchedSlug)}`);\n kv('Name', match.name);\n if (match.role ?? match.permissions) {\n kv('Role', String(match.role ?? match.permissions));\n }\n return 0;\n}\n","/**\n * `dashwise module clone <slug>` — bring a published module's\n * source into a local directory.\n *\n * Two flavors based on what's available on the backend:\n *\n * 1. **Git mode** — when the module's published manifest carries\n * `repository.url`, we shell out to `git clone` to fetch the\n * source. This is the recommended path: full file history,\n * branch awareness, future `git pull` for updates.\n *\n * 2. **Manifest-only mode** — when no `repository.url` is set,\n * we write the published manifest into a fresh directory plus\n * a minimal scaffold (.gitignore, package.json, README) so the\n * user has a workable starting point. They can then layer\n * their own app code on top + run `dashwise module dev`.\n *\n * Refuses to write into a non-empty directory unless `--force` is\n * passed.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { gitignore, packageJson, packageJsonCustom } from '../../lib/scaffold.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\ninterface SourceMetadataResponse {\n module_slug: string;\n module_name: string;\n current_version: string | null;\n repository_url: string | null;\n manifest: Record<string, unknown> | null;\n}\n\nexport interface CloneOptions {\n /** Target directory (default: `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Skip git clone even when repository.url is set (use manifest mode). */\n noGit?: boolean;\n}\n\nexport async function moduleCloneCommand(\n slug: string,\n options: CloneOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise module clone <slug>`');\n return 1;\n }\n\n let meta: SourceMetadataResponse;\n try {\n meta = await apiRequest<SourceMetadataResponse>(\n 'GET',\n `/api/modules/${encodeURIComponent(slug)}/source-tarball`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 403) {\n fail(`No access to module ${code(slug)}. You must be a member of its owner workspace.`);\n return 1;\n }\n fail(`Could not fetch module metadata: ${(err as Error).message}`);\n return 1;\n }\n\n const target = resolve(options.dir ?? slug);\n\n // Refuse to overwrite an existing non-empty directory unless --force.\n if (existsSync(target)) {\n const entries = readdirSync(target);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(target)} is not empty. Pass ${code('--force')} to clone anyway.`,\n );\n return 1;\n }\n }\n\n // Decide between git mode + manifest-only fallback.\n const wantGit = !options.noGit && meta.repository_url !== null;\n if (wantGit) {\n return cloneViaGit(meta, target);\n }\n\n if (meta.repository_url !== null && options.noGit) {\n info(`--no-git: skipping git clone for ${code(meta.repository_url)}; writing manifest-only scaffold.`);\n } else {\n info(`Module ${code(slug)} has no ${code('repository.url')}; writing manifest-only scaffold.`);\n }\n return cloneViaManifest(slug, meta, target);\n}\n\n/**\n * Shell out to `git clone <url> <target>`. Inherits stdio so the\n * user sees git's progress + error messages directly. Returns 0 on\n * success, propagating git's exit code on failure.\n */\nfunction cloneViaGit(meta: SourceMetadataResponse, target: string): number {\n const repoUrl = meta.repository_url!;\n info(`Cloning ${code(repoUrl)} into ${code(target)}...`);\n const result = spawnSync('git', ['clone', repoUrl, target], {\n stdio: 'inherit',\n });\n if (result.error) {\n fail(`Failed to invoke git: ${result.error.message}`);\n return 1;\n }\n if (result.status !== 0) {\n fail(`git clone exited with status ${result.status}.`);\n return result.status ?? 1;\n }\n success(`Cloned ${code(meta.module_slug)} from ${code(repoUrl)}.`);\n if (meta.current_version) {\n info(`Current published version: ${code(`v${meta.current_version}`)}`);\n }\n return 0;\n}\n\n/**\n * Fallback when no Git URL is available: lay down `module.json` +\n * `.gitignore` + `package.json` + `README.md` so the user has a\n * starting point. The user has to recreate `app/` themselves —\n * we don't have access to the original source (no Git URL).\n */\nfunction cloneViaManifest(\n slug: string,\n meta: SourceMetadataResponse,\n target: string,\n): number {\n if (!meta.manifest) {\n fail(\n `Module ${code(slug)} has no published manifest yet (publish at least one version first).`,\n );\n return 1;\n }\n\n mkdirSync(target, { recursive: true });\n\n // Inspect the manifest to pick the right scaffold flavor.\n const manifestObj = meta.manifest as Record<string, unknown>;\n const moduleKind = manifestObj.module_kind === 'custom' ? 'custom' : 'hand_authored';\n const pkgFn = moduleKind === 'custom' ? packageJsonCustom : packageJson;\n\n writeFileSync(\n join(target, 'module.json'),\n JSON.stringify(manifestObj, null, 2) + '\\n',\n 'utf-8',\n );\n writeFileSync(\n join(target, 'package.json'),\n pkgFn({ slug: meta.module_slug, name: meta.module_name, kind: moduleKind }),\n 'utf-8',\n );\n writeFileSync(join(target, '.gitignore'), gitignore(), 'utf-8');\n writeFileSync(\n join(target, 'README.md'),\n readmeForClone(meta, moduleKind),\n 'utf-8',\n );\n\n success(`Wrote ${moduleKind} scaffold for ${code(meta.module_slug)} into ${code(target)}`);\n info(`Next steps:`);\n out('');\n out(` ${dim('1.')} ${code(`cd ${target}`)}`);\n out(` ${dim('2.')} ${code('npm install')}`);\n out(` ${dim('3.')} ${code('dashwise module generate')}`);\n out(` ${dim('4.')} Recreate your ${code('app/')} (manifest-only clone — no source code available).`);\n out('');\n if (meta.repository_url) {\n warn(\n `Module's manifest declared ${code(meta.repository_url)} as its repo; consider running ${code(`dashwise module clone ${slug}`)} without ${code('--no-git')} to get the full source.`,\n );\n } else {\n info(\n `If you have access to the original source, ` +\n `consider running ${code(`dashwise module connect-git <repo-url>`)} ` +\n `so future clones use it.`,\n );\n }\n return 0;\n}\n\nfunction readmeForClone(\n meta: SourceMetadataResponse,\n kind: 'hand_authored' | 'custom',\n): string {\n return `# ${meta.module_name}\n\nManifest-only clone of \\`${meta.module_slug}\\` (${kind}) at version \\`${meta.current_version ?? 'unpublished'}\\`.\n\nThe original source code wasn't available — this directory contains\nonly the published \\`module.json\\` + a starter scaffold. Recreate\n\\`app/\\` based on the manifest.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise module generate\ndashwise module dev\n\\`\\`\\`\n`;\n}\n","/**\n * `dashwise module connect-git <repo-url>` — write the Git repository\n * URL into the local `module.json#repository.url`.\n *\n * v1 scope: local manifest mutation only. The backend reads\n * `repository` from the manifest on the next `module publish` and\n * captures the URL + the actual `commit` + `branch` from the local\n * git working tree at publish time (P5b for the commit-capture\n * follow-up). For now, this command just sets the URL so the\n * marketplace + `module clone` know where to look.\n *\n * The URL is light-validated: must be a real URL, https:// or git@\n * shorthand also accepted. Branch can be passed via `--branch\n * <name>` to default to a non-`main` branch (rare, but common\n * for monorepos).\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface ConnectGitOptions {\n dir?: string;\n branch?: string;\n}\n\nexport async function moduleConnectGitCommand(\n repoUrl: string,\n options: ConnectGitOptions,\n): Promise<number> {\n if (!repoUrl || typeof repoUrl !== 'string') {\n fail('Usage: `dashwise module connect-git <repo-url>`');\n return 1;\n }\n if (!isPlausibleRepoUrl(repoUrl)) {\n fail(`Repo URL ${code(repoUrl)} doesn't look like https:// or git@host:owner/repo.`);\n return 1;\n }\n\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init\\` first.`,\n );\n return 1;\n }\n let manifest: Record<string, unknown>;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n const existing = (manifest.repository as Record<string, unknown> | undefined) ?? {};\n const next: Record<string, unknown> = {\n ...existing,\n type: 'git',\n url: repoUrl,\n };\n if (options.branch) {\n next.branch = options.branch;\n } else if (typeof existing.branch === 'string') {\n // Preserve any branch already set.\n next.branch = existing.branch;\n }\n manifest.repository = next;\n\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n success(`Connected to ${code(repoUrl)}`);\n if (next.branch) info(`Branch: ${code(String(next.branch))}`);\n info(`Updated ${code('module.json')}.`);\n return 0;\n}\n\n/**\n * Accept three URL shapes commonly used for Git remotes:\n * - https://github.com/org/repo\n * - https://github.com/org/repo.git\n * - git@github.com:org/repo.git\n *\n * Rejects obvious garbage; the backend (or git itself, at clone\n * time) does the real validation.\n */\nfunction isPlausibleRepoUrl(url: string): boolean {\n if (url.startsWith('https://') || url.startsWith('http://')) {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n // git@host:owner/repo[.git] shorthand\n return /^git@[^:]+:[^/]+\\/.+/.test(url);\n}\n","/**\n * `dashwise module generate` — regenerate the typed wrappers from the\n * local `module.json`.\n *\n * Flow:\n * 1. Read + parse `<cwd>/module.json`.\n * 2. POST it to `/api/modules/draft/generate-sdk`.\n * 3. Write each returned file to `node_modules/@dashai/generated/<path>`.\n * 4. Print summary (file count + content hash).\n *\n * Idempotent: re-running produces bit-identical output for an\n * unchanged manifest (per the generator's content-hash guarantee).\n * Returning a fresh generation counter on each call is reserved for\n * `module dev` — the one-shot CLI path uses generation=0.\n *\n * Requires the user to be logged in (uses the saved CLI token).\n */\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success } from '../../lib/output.js';\n\nexport interface GenerateOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** Monotonic counter passed to the generator (default 0). */\n generation?: number;\n /** Skip writing to node_modules — print summary only. */\n dryRun?: boolean;\n}\n\ninterface GenerateResponse {\n files: Record<string, string>;\n contentHash: string;\n}\n\n/** Resolved output directory: `<project>/node_modules/@dashai/generated/`. */\nfunction outputDir(projectRoot: string): string {\n return join(projectRoot, 'node_modules', '@dashai', 'generated');\n}\n\nexport async function moduleGenerateCommand(\n options: GenerateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n let res: GenerateResponse;\n try {\n res = await apiRequest<GenerateResponse>(\n 'POST',\n '/api/modules/draft/generate-sdk',\n {\n manifest,\n generation: options.generation ?? 0,\n },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 400) {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n process.stderr.write(JSON.stringify(err.context, null, 2) + '\\n');\n }\n return 1;\n }\n fail(`Could not generate SDK: ${(err as Error).message}`);\n return 1;\n }\n\n if (options.dryRun) {\n info(`Dry run: ${Object.keys(res.files).length} files`);\n info(`Hash: ${code(res.contentHash)}`);\n return 0;\n }\n\n const out = outputDir(projectRoot);\n // Wipe any prior generated content so a renamed/removed table\n // doesn't leave a stale wrapper file behind. The directory itself\n // is gitignored, so a wipe-then-rewrite is safe.\n if (existsSync(out)) {\n rmSync(out, { recursive: true, force: true });\n }\n mkdirSync(out, { recursive: true });\n for (const [relPath, content] of Object.entries(res.files)) {\n const absPath = join(out, relPath);\n const parent = dirname(absPath);\n if (!existsSync(parent)) {\n mkdirSync(parent, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Generated ${Object.keys(res.files).length} files into ${code('node_modules/@dashai/generated/')}`,\n );\n info(`Hash: ${dim(res.contentHash)}`);\n return 0;\n}\n","/**\n * `dashwise module dev` — watch `module.json` + auto-regenerate the\n * SDK on every change.\n *\n * Behavior:\n * 1. Read `module.json`; run an initial `module generate` so the\n * caller starts in a coherent state.\n * 2. Watch the manifest file for changes (`fs.watch`).\n * 3. On each change event, debounce 250ms (editor saves often\n * fire two events in quick succession), then regenerate.\n * 4. Bumps the `generation` counter per regen so the emitted\n * `package.json#version` shifts (`0.0.1-gen.N`), invalidating\n * any naïve caches keyed off it.\n * 5. Runs until Ctrl-C (clean exit on SIGINT/SIGTERM).\n *\n * Does NOT spawn `next dev` itself — the user runs that in another\n * terminal. Justification: `next dev`'s own output is dense + we\n * don't want to swallow/buffer it. If users want both, an\n * orchestrator like `npm-run-all` works (`npm run dev:next` and\n * `dashwise module dev` in parallel).\n */\n\nimport { existsSync, watch as fsWatch } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { moduleGenerateCommand } from './generate.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DevOptions {\n dir?: string;\n /** Debounce window in ms for filesystem change coalescing. */\n debounceMs?: number;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 250;\n\nexport async function moduleDevCommand(options: DevOptions): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info('Run `dashwise module init <slug>` to scaffold a new module.');\n return 1;\n }\n\n info(`Watching ${code(manifestPath)} — Ctrl-C to stop.`);\n\n // 1. Initial regen.\n let generation = 0;\n const initial = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n if (initial !== 0) {\n warn('Initial regen failed; watcher will retry on the next change.');\n }\n generation += 1;\n\n // 2. Watch loop with debounce. We deliberately use `fs.watch` (vs\n // chokidar) to keep deps small — chokidar weighs ~1MB packed, fs.watch\n // is built-in. Editor saves on macOS sometimes fire 2 events\n // back-to-back; the debounce coalesces them into one regen call.\n const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n let timer: NodeJS.Timeout | null = null;\n let isRunning = false;\n let pendingRegen = false;\n\n async function doRegen() {\n if (isRunning) {\n // Another regen is in flight — flag for re-run when it finishes.\n pendingRegen = true;\n return;\n }\n isRunning = true;\n try {\n const start = Date.now();\n const exit = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n const elapsedMs = Date.now() - start;\n if (exit === 0) {\n success(`Regen complete (${elapsedMs}ms, gen=${generation})`);\n } else {\n warn(`Regen failed (exit ${exit}, gen=${generation}) — will retry on next change.`);\n }\n generation += 1;\n } finally {\n isRunning = false;\n if (pendingRegen) {\n pendingRegen = false;\n // Schedule a follow-up — keeps the loop responsive when\n // the user saves rapidly.\n setImmediate(doRegen);\n }\n }\n }\n\n const watcher = fsWatch(manifestPath, (eventType) => {\n if (eventType !== 'change') return;\n if (timer !== null) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n void doRegen();\n }, debounceMs);\n });\n\n // Clean shutdown.\n return new Promise<number>((resolveExit) => {\n const stop = (signal: NodeJS.Signals | 'shutdown') => {\n if (timer !== null) clearTimeout(timer);\n watcher.close();\n info(`Stopping watcher${signal === 'shutdown' ? '' : ` (${signal})`}.`);\n // Use process.stdout flush hint to ensure the message lands\n // before exit.\n process.stdout.write(dim('Goodbye.\\n'));\n resolveExit(0);\n };\n process.once('SIGINT', () => stop('SIGINT'));\n process.once('SIGTERM', () => stop('SIGTERM'));\n });\n}\n","/**\n * `dashwise module diff` — preview what will change at the next\n * publish vs the currently-published version.\n *\n * Flow:\n * 1. Read local `module.json` for the slug.\n * 2. Resolve `slug → module.id` via `/api/modules/by-slug/:slug`.\n * 3. POST the local manifest to `/api/modules/:id/draft/diff`.\n * 4. Render the structured diff as a readable summary:\n * - \"unchanged\" short-circuit\n * - tables added/removed/changed\n * - dependencies added/removed\n * - top-level meta changes (version, name, module_kind, ...)\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out, success } from '../../lib/output.js';\n\ninterface FieldChange {\n field: string;\n changes: Record<string, unknown>;\n}\n\ninterface TableChange {\n table: string;\n fields_added: Array<{ slug: string; type: string }>;\n fields_removed: Array<{ slug: string; type: string }>;\n fields_changed: FieldChange[];\n}\n\ninterface DiffResponse {\n current_version: string | null;\n unchanged: boolean;\n meta_changes: Array<{ field: string; before: unknown; after: unknown }>;\n tables_added: string[];\n tables_removed: string[];\n tables_changed: TableChange[];\n deps_added: Array<{ module: string; version: string }>;\n deps_removed: Array<{ module: string; version: string }>;\n}\n\nexport interface DiffOptions {\n dir?: string;\n /** Emit the structured diff as JSON instead of the human-readable summary. */\n json?: boolean;\n}\n\nexport async function moduleDiffCommand(\n options: DiffOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NO_MANIFEST', message: `No module.json found in ${projectRoot}.` } }));\n } else {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n }\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_PARSE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n }\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_MISSING_SLUG', message: 'module.json is missing module.slug.' } }));\n } else {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n }\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number; current_version: string | null };\n try {\n mod = await apiRequest<{ id: number; current_version: string | null }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MODULE_NOT_FOUND', message: `Module ${slug} not found on the backend.` } }));\n } else {\n fail(\n `Module ${code(slug)} not found on the backend. Create + publish it first; `\n + `diff has nothing to compare against until then.`,\n );\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'RESOLVE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not resolve module: ${(err as Error).message}`);\n }\n return 1;\n }\n\n let diff: DiffResponse;\n try {\n diff = await apiRequest<DiffResponse>(\n 'POST',\n `/api/modules/${mod.id}/draft/diff`,\n { manifest },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'VALIDATION_FAILED', message: err.message, context: err.context ?? null } }));\n } else {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n out(JSON.stringify(err.context, null, 2));\n }\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not compute diff: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(JSON.stringify({ ok: true, ...diff }));\n return 0;\n }\n\n if (diff.unchanged) {\n success(\n `No changes vs ${code(diff.current_version ? `v${diff.current_version}` : '(unpublished)')} — manifest is in sync.`,\n );\n return 0;\n }\n\n // Header.\n out('');\n info(\n diff.current_version\n ? `Diff vs ${code(`v${diff.current_version}`)}:`\n : 'Diff vs ' + code('(unpublished — first version)') + ':',\n );\n\n if (diff.meta_changes.length > 0) {\n out('');\n out(code('Meta:'));\n for (const m of diff.meta_changes) {\n out(` ${m.field}: ${dim(JSON.stringify(m.before))} → ${JSON.stringify(m.after)}`);\n }\n }\n\n if (diff.tables_added.length > 0) {\n out('');\n out(code(`Tables added (${diff.tables_added.length}):`));\n for (const t of diff.tables_added) out(` + ${t}`);\n }\n\n if (diff.tables_removed.length > 0) {\n out('');\n out(code(`Tables removed (${diff.tables_removed.length}):`));\n for (const t of diff.tables_removed) out(` - ${t}`);\n }\n\n if (diff.tables_changed.length > 0) {\n out('');\n out(code(`Tables changed (${diff.tables_changed.length}):`));\n for (const t of diff.tables_changed) {\n out(` ${dim('•')} ${code(t.table)}`);\n for (const f of t.fields_added) {\n out(` + field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_removed) {\n out(` - field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_changed) {\n const changeSummary = Object.entries(f.changes)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n out(` ~ field ${f.field}: ${dim(changeSummary)}`);\n }\n }\n }\n\n if (diff.deps_added.length > 0) {\n out('');\n out(code(`Dependencies added (${diff.deps_added.length}):`));\n for (const d of diff.deps_added) {\n out(` + ${d.module}@${d.version}`);\n }\n }\n\n if (diff.deps_removed.length > 0) {\n out('');\n out(code(`Dependencies removed (${diff.deps_removed.length}):`));\n for (const d of diff.deps_removed) {\n out(` - ${d.module}@${d.version}`);\n }\n }\n\n out('');\n info('Run `dashwise module publish --bump <patch|minor|major>` when ready.');\n return 0;\n}\n","/**\n * `dashwise` CLI entry point.\n *\n * commander-based command tree. Each command sits in `./commands/`\n * and returns a numeric exit code; the entry handler awaits the\n * result + sets `process.exitCode` accordingly. Unhandled errors\n * are caught + printed via the shared output helpers.\n */\n\nimport { Command } from 'commander';\nimport { devCommand } from './commands/dev.js';\nimport { loginCommand } from './commands/login.js';\nimport { logoutCommand } from './commands/logout.js';\nimport { profileCommand } from './commands/profile.js';\nimport { workspaceListCommand, workspaceUseCommand } from './commands/workspace.js';\nimport { moduleCloneCommand } from './commands/module/clone.js';\nimport { moduleConnectGitCommand } from './commands/module/connect-git.js';\nimport { moduleDevCommand } from './commands/module/dev.js';\nimport { moduleDiffCommand } from './commands/module/diff.js';\nimport { moduleGenerateCommand } from './commands/module/generate.js';\nimport { moduleInitCommand } from './commands/module/init.js';\nimport { moduleListCommand } from './commands/module/list.js';\nimport { modulePublishCommand } from './commands/module/publish.js';\nimport { modulePullDataCommand } from './commands/module/pull-data.js';\nimport { moduleValidateCommand } from './commands/module/validate.js';\nimport { depsAddCommand } from './commands/deps/add.js';\nimport { depsCheckCommand } from './commands/deps/check.js';\nimport { depsListCommand } from './commands/deps/list.js';\nimport { depsRemoveCommand } from './commands/deps/remove.js';\nimport { queryCommand } from './commands/query.js';\nimport { moduleQueryLogCommand } from './commands/module/query-log.js';\nimport { moduleActionLogCommand } from './commands/module/action-log.js';\nimport { fail } from './lib/output.js';\n\nconst program = new Command();\n\nprogram\n .name('dashwise')\n .description('DashWise CLI — log in, author modules, publish to the marketplace.')\n .version(getVersion(), '-v, --version', 'Show the CLI version + exit')\n .option(\n '--api-url <url>',\n 'Override DashWise backend URL (default: $DASHWISE_API_URL or saved config or http://localhost:3000)',\n );\n\nprogram\n .command('login')\n .description('Sign in via the device-code flow.')\n .option('--no-prompt', 'Skip the \"open browser\" prompt; just print the URL.')\n .option('--name <name>', 'Suggested name for the minted token (default: dashwise-cli).')\n .action(async (cmdOpts: { prompt?: boolean; name?: string }) => {\n const apiUrl = program.opts<{ apiUrl?: string }>().apiUrl;\n const exit = await loginCommand({\n ...(apiUrl !== undefined ? { apiUrl } : {}),\n noPrompt: cmdOpts.prompt === false,\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n });\n process.exitCode = exit;\n });\n\nprogram\n .command('logout')\n .description('Clear the local credentials and revoke the server-side token.')\n .action(async () => {\n process.exitCode = await logoutCommand();\n });\n\nprogram\n .command('profile')\n .description('Show the current user, default workspace, and accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable kv pairs.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await profileCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nconst workspace = program\n .command('workspace')\n .description('Workspace context commands.');\n\nworkspace\n .command('list')\n .description('List accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await workspaceListCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nworkspace\n .command('use <slug>')\n .description('Set the default workspace for subsequent commands.')\n .action(async (slug: string) => {\n process.exitCode = await workspaceUseCommand(slug);\n });\n\n// One-command local dev loop. Spawns `dashwise module dev` + `next dev`\n// together with auth env vars auto-injected from the saved CLI config —\n// collapses the historical \"two terminals + manually edit .env.local\"\n// workflow into a single command. Top-level (not under `module`) because\n// it's the daily-driver entry point most developers will spend the most\n// time with.\nprogram\n .command('dev')\n .description(\n 'One-command local dev loop: runs the manifest watcher + Next.js dev server ' +\n 'together. Registers a dev-mode SSO session with the backend so workspace ' +\n 'members can sign into your locally-running module via DashWise SSO (no ' +\n 'installation_id required). Auth + dev-session env auto-injected into ' +\n 'both child processes from your saved CLI config. Run `dashwise login` first.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option(\n '--installation-id <id>',\n 'Use prod-mode SSO with this installation id instead of registering a dev session. ' +\n 'The installation must already exist in the target workspace.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Workspace to scope the dev session to (slug or numeric id). Required if your ' +\n 'account belongs to more than one workspace; auto-picked if you have just one.',\n )\n .option(\n '--callback-origin <url>',\n 'Additional callback origin to allowlist on the dev session (repeatable). ' +\n 'The dev server URL (http://localhost:<port>) is always allowlisted; pass ' +\n 'this for custom-domain local dev (e.g. https://myapp.local).',\n collectRepeated,\n [] as string[],\n )\n .option(\n '--api-url <url>',\n 'Override the `DASHWISE_API_URL` env var passed to children (default: saved CLI config).',\n )\n .option('--port <number>', 'Port for `next dev` (default: 3000).', parseIntOption)\n .option('--sdk-only', 'Only run the manifest watcher; skip `next dev`.')\n .option('--next-only', 'Only run `next dev`; skip the manifest watcher.')\n .action(\n async (cmdOpts: {\n dir?: string;\n installationId?: string;\n workspace?: string;\n callbackOrigin?: string[];\n apiUrl?: string;\n port?: number;\n sdkOnly?: boolean;\n nextOnly?: boolean;\n }) => {\n process.exitCode = await devCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.installationId !== undefined ? { installationId: cmdOpts.installationId } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.callbackOrigin !== undefined && cmdOpts.callbackOrigin.length > 0\n ? { callbackOrigin: cmdOpts.callbackOrigin }\n : {}),\n ...(cmdOpts.apiUrl !== undefined ? { apiUrl: cmdOpts.apiUrl } : {}),\n ...(cmdOpts.port !== undefined ? { port: cmdOpts.port } : {}),\n ...(cmdOpts.sdkOnly !== undefined ? { sdkOnly: cmdOpts.sdkOnly } : {}),\n ...(cmdOpts.nextOnly !== undefined ? { nextOnly: cmdOpts.nextOnly } : {}),\n });\n },\n );\n\n// FUP-3: top-level alias for `dashwise module init`. The two-command\n// bootstrap (`dashwise login` + `dashwise init`) is the headline daily-\n// driver flow per `building-modules.md` + the LDI v1 plan — making the\n// second command three words (`dashwise module init`) was a paper-cut\n// during the dogfood. This alias preserves both spellings: muscle\n// memory continues to work, the README docs are honest.\nconst initOptions = (cmd: Command): Command =>\n cmd\n .option('--dir <path>', 'Override the target directory (default: ./<slug>).')\n .option('--name <name>', 'Human-readable module name (default: derived from slug).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option(\n '--simple',\n 'Use the legacy minimal scaffold (hand-authored, no Next.js auth wiring). Default before 2026-05-18; opt-in now.',\n )\n .option(\n '--custom',\n \"[Deprecated alias — kept for backward compatibility.] Equivalent to the default (full Next.js + auth). Will be removed in a future major version; just call `dashwise init` without flags.\",\n )\n .option('--git <url>', 'Initial Git repository URL — written to module.json#repository.url.')\n // HH-CC-LDI-6 flags.\n .option(\n '--description <text>',\n 'Module description — forwarded to the backend when provisioning the dev installation.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for the dev installation (slug or numeric id). When omitted in a TTY, the CLI prompts; in non-interactive mode it auto-picks when you have one workspace and errors out otherwise.',\n )\n .option(\n '--no-provision',\n 'Skip the `POST /api/installations/dev` step. Local scaffold is still written; you can provision later by re-running `dashwise init --force` (or, once it ships, `dashwise module provision-dev-install`).',\n );\n\ninterface InitCmdOpts {\n dir?: string;\n name?: string;\n force?: boolean;\n simple?: boolean;\n custom?: boolean;\n git?: string;\n description?: string;\n workspace?: string;\n // Commander maps `--no-provision` → `provision: false`.\n provision?: boolean;\n}\n\nconst initAction = async (slugArg: string | undefined, cmdOpts: InitCmdOpts): Promise<void> => {\n process.exitCode = await moduleInitCommand(slugArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.simple !== undefined ? { simple: cmdOpts.simple } : {}),\n ...(cmdOpts.custom !== undefined ? { custom: cmdOpts.custom } : {}),\n ...(cmdOpts.git !== undefined ? { git: cmdOpts.git } : {}),\n ...(cmdOpts.description !== undefined ? { description: cmdOpts.description } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.provision !== undefined ? { provision: cmdOpts.provision } : {}),\n });\n};\n\ninitOptions(\n program\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth). Top-level alias for `dashwise module init`.',\n ),\n).action(initAction);\n\nconst moduleCmd = program\n .command('module')\n .description('Module authoring commands.');\n\ninitOptions(\n moduleCmd\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth).',\n ),\n).action(initAction);\n\nmoduleCmd\n .command('connect-git <repo-url>')\n .description('Link the local module to a Git repository (writes module.json#repository).')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--branch <name>', 'Default branch to publish from (e.g. `main`).')\n .action(\n async (repoUrl: string, cmdOpts: { dir?: string; branch?: string }) => {\n process.exitCode = await moduleConnectGitCommand(repoUrl, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.branch !== undefined ? { branch: cmdOpts.branch } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('generate')\n .description(\"Regenerate typed wrappers from the local module.json into node_modules/@dashai/generated/.\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--dry-run', 'Print summary without writing files.')\n .action(async (cmdOpts: { dir?: string; dryRun?: boolean }) => {\n process.exitCode = await moduleGenerateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n });\n });\n\nmoduleCmd\n .command('dev')\n .description('Watch module.json + regenerate typed wrappers on every save. Ctrl-C to stop.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--debounce-ms <n>', 'Filesystem change debounce window (default: 250ms).', parseIntOption)\n .action(async (cmdOpts: { dir?: string; debounceMs?: number }) => {\n process.exitCode = await moduleDevCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.debounceMs !== undefined ? { debounceMs: cmdOpts.debounceMs } : {}),\n });\n });\n\nmoduleCmd\n .command('validate')\n .description('Validate the local module.json against the backend manifest validator.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (cmdOpts: { dir?: string }) => {\n process.exitCode = await moduleValidateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nmoduleCmd\n .command('list')\n .description('List modules you own (or `--all` for owned + public).')\n .option('--all', 'Include public modules you can install but do not own.')\n .option('--workspace <slug>', 'Filter by workspace slug (default: saved default workspace).')\n .option('--json', 'Emit JSON to stdout instead of column-aligned text.')\n .action(async (cmdOpts: { all?: boolean; workspace?: string; json?: boolean }) => {\n process.exitCode = await moduleListCommand({\n ...(cmdOpts.all !== undefined ? { all: cmdOpts.all } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('diff')\n .description('Show what would change at the next publish vs the currently-published version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit the structured diff as JSON instead of the human-readable summary.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await moduleDiffCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('pull-data')\n .description(\"Export the module's own-table rows to a local JSON file (for fixtures, local dev seeding).\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--limit <n>', 'Max rows per table (1-1000, default 100).', parseIntOption)\n .option('--out <path>', 'Output file path (default: ./dashwise-data.json).')\n .action(async (cmdOpts: { dir?: string; limit?: number; out?: string }) => {\n process.exitCode = await modulePullDataCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.out !== undefined ? { out: cmdOpts.out } : {}),\n });\n });\n\nmoduleCmd\n .command('clone <slug>')\n .description('Clone a published module locally. Uses git if repository.url is set, else writes a manifest-only scaffold.')\n .option('--dir <path>', 'Target directory (default: ./<slug>).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option('--no-git', 'Skip git clone even when repository.url is set; use the manifest-only scaffold.')\n .action(\n async (\n slug: string,\n cmdOpts: { dir?: string; force?: boolean; git?: boolean },\n ) => {\n // commander maps `--no-git` to `git: false`; convert to our internal shape.\n process.exitCode = await moduleCloneCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.git === false ? { noGit: true } : {}),\n });\n },\n );\n\nconst depsCmd = program\n .command('deps')\n .description('Cross-module dependency commands (manipulate module.json#dependencies).');\n\ndepsCmd\n .command('list')\n .description('List declared cross-module dependencies.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\ndepsCmd\n .command('add <provider-slug>')\n .description(\n 'Declare a cross-module dependency. Interactive in TTY (picks tables + fields from the provider\\'s exposes); non-interactive requires --table, --fields, --purpose.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--table <slug>', 'Provider table slug to read from (non-interactive mode).')\n .option('--fields <list>', 'Comma-separated field slugs for --table (non-interactive mode).')\n .option('--purpose <text>', 'Human-readable explanation (10-500 chars, shown at install consent).')\n .option('--version <range>', 'SemVer range to pin (default: ^<provider-current-version>).')\n .option('-y, --yes', 'Skip the replace-existing confirmation prompt.')\n .action(\n async (\n providerSlug: string,\n cmdOpts: {\n dir?: string;\n table?: string;\n fields?: string;\n purpose?: string;\n version?: string;\n yes?: boolean;\n },\n ) => {\n process.exitCode = await depsAddCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.table !== undefined ? { table: cmdOpts.table } : {}),\n ...(cmdOpts.fields !== undefined ? { fields: cmdOpts.fields } : {}),\n ...(cmdOpts.purpose !== undefined ? { purpose: cmdOpts.purpose } : {}),\n ...(cmdOpts.version !== undefined ? { version: cmdOpts.version } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\ndepsCmd\n .command('remove <provider-slug>')\n .description('Remove a declared cross-module dependency.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('-y, --yes', 'Skip the confirmation prompt.')\n .action(async (providerSlug: string, cmdOpts: { dir?: string; yes?: boolean }) => {\n process.exitCode = await depsRemoveCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n });\n\ndepsCmd\n .command('check')\n .description('Verify each declared dep still resolves to a published provider + that every field/op is still exposed. Exits 1 on drift.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit a JSON drift report to stdout.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsCheckCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nprogram\n .command('query')\n .description(\n 'Run a typed query against the local module installation via @dashai/sdk/query. ' +\n 'Pass one of `--inline \"<expr>\"`, `--file <path>`, or `--repl`. ' +\n '`qb`, `deps`, `db` are pre-bound to the local module\\'s generated SDK.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option('--inline <expression>', 'Evaluate a one-liner. e.g., `qb.tasks.where({done:false}).count()`.')\n .option('--file <path>', 'Dynamic-import a .mjs/.js file. Default export = Query | AggQuery | Promise | value.')\n .option('--repl', 'Open an interactive Node REPL with the generated SDK pre-bound. Top-level await supported.')\n .option('--json', 'Emit compact JSON (default: pretty-printed).')\n .option(\n '--explain',\n 'Call .explain() instead of .execute() — returns the Postgres plan + estimatedCost without executing the query. MVP supports joined queries; bare own/dep/view paths reject with EXPLAIN_NOT_SUPPORTED_YET.',\n )\n .option(\n '--stream',\n 'Call .stream() instead of .execute() — prints rows incrementally as JSON-lines (one row per line). Lets you see progress on big queries + Ctrl-C cleanly midway. Mutually exclusive with --explain and --repl.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n explain?: boolean;\n stream?: boolean;\n }) => {\n process.exitCode = await queryCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.inline !== undefined ? { inline: cmdOpts.inline } : {}),\n ...(cmdOpts.file !== undefined ? { file: cmdOpts.file } : {}),\n ...(cmdOpts.repl !== undefined ? { repl: cmdOpts.repl } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.explain !== undefined ? { explain: cmdOpts.explain } : {}),\n ...(cmdOpts.stream !== undefined ? { stream: cmdOpts.stream } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('publish')\n .description('Pack the current directory + upload it as a new module version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--bump <direction>', 'Semver bump: patch | minor | major.')\n .option('--dry-run', 'Validate + upload but do not persist the version row.')\n .option('-y, --yes', 'Skip the confirmation prompt (for CI / scripted use).')\n .option(\n '--exclude <pattern...>',\n 'Extra exclude patterns (segment-matched) appended to the defaults.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n bump?: 'patch' | 'minor' | 'major';\n dryRun?: boolean;\n yes?: boolean;\n exclude?: string[];\n }) => {\n process.exitCode = await modulePublishCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.bump !== undefined ? { bump: cmdOpts.bump } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n ...(cmdOpts.exclude !== undefined ? { exclude: cmdOpts.exclude } : {}),\n });\n },\n );\n\n// Phase 6 slice 6.4 (2026-05-19): per-module SDK query log reader.\n// Workspace-member-scoped on the backend.\nmoduleCmd\n .command('query-log')\n .description(\n 'Read the per-module SDK query log. Default: 50 most recent entries. ' +\n '`--slow` filters to duration_ms > 500ms; `--since 1h` narrows by time; ' +\n '`--tail` streams new entries every 5s.',\n )\n .option(\n '--module <id-or-slug>',\n 'Module to inspect (default: slug from current directory\\'s module.json).',\n )\n .option('--slow', 'Filter to slow queries only (duration_ms > 500).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .option('--dir <path>', 'Override project directory for module.json lookup.')\n .action(\n async (cmdOpts: {\n module?: string;\n slow?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n dir?: string;\n }) => {\n process.exitCode = await moduleQueryLogCommand({\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\n// P7 slice 7.5b (2026-05-20): per-installation server-action audit log.\n// Follow-up (2026-05-20): added `--module <slug>` resolver.\nmoduleCmd\n .command('action-log')\n .description(\n 'Read the per-installation server-action audit log. Shows both ' +\n 'cross-module and own-module dispatches. Filter by role (caller / ' +\n 'provider), slow, since, cross-module-only. `--tail` streams new ' +\n 'entries every 5s. Pass either `--installation <id>` or ' +\n '`--module <slug>` (slug resolves to your accessible installation).',\n )\n .option(\n '--installation <id>',\n 'Installation id to inspect. Mutually exclusive with `--module`.',\n parseIntOption,\n )\n .option(\n '--module <slug>',\n \"Module slug. Resolves to the caller's accessible installation of \" +\n 'that module (first match if multi-workspace). Mutually exclusive with `--installation`.',\n )\n .option(\n '--role <caller|provider>',\n \"Which side of cross-module dispatches to show. 'caller' (default) \" +\n \"shows outbound; 'provider' shows inbound calls on this installation.\",\n )\n .option('--slow', 'Filter to slow actions only (elapsed_ms > 500).')\n .option('--cross-module-only', 'Hide own-module dispatches (cross_module=false rows).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .action(\n async (cmdOpts: {\n installation?: number;\n module?: string;\n role?: string;\n slow?: boolean;\n crossModuleOnly?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n }) => {\n if (cmdOpts.role !== undefined && cmdOpts.role !== 'caller' && cmdOpts.role !== 'provider') {\n fail(`--role must be 'caller' or 'provider' (got \"${cmdOpts.role}\").`);\n process.exitCode = 1;\n return;\n }\n process.exitCode = await moduleActionLogCommand({\n ...(cmdOpts.installation !== undefined ? { installation: cmdOpts.installation } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.role !== undefined ? { role: cmdOpts.role as 'caller' | 'provider' } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.crossModuleOnly !== undefined ? { crossModuleOnly: cmdOpts.crossModuleOnly } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-9: dashwise module destroy-dev-install + reset-dev-install ──\n\nmoduleCmd\n .command('destroy-dev-install')\n .description(\n \"Destroy the local-dev install for the current module. Tears down the install row + dashboard tile; if the module had no other installs and was never published, drops the module too. Local module.json is preserved (only the cached runtime token + install id in auth.json get cleared).\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n \"Override the module slug (default: read from local module.json). Useful when the project dir is gone but auth.json still has the entry.\",\n )\n .option('-y, --yes', 'Skip the confirmation prompt — for CI.')\n .action(\n async (cmdOpts: { dir?: string; module?: string; yes?: boolean }) => {\n const { destroyDevInstallCommand } = await import(\n './commands/module/destroy-dev-install.js'\n );\n process.exitCode = await destroyDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('reset-dev-install')\n .description(\n 'Destroy + re-provision the local-dev install in one shot. Useful for nuking accumulated test data, refreshing a compromised runtime token, or recovering from a wedged schema state. Keeps local module.json intact.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n 'Override the module slug (default: from local module.json).',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for re-provisioning (passed through to `dashwise init`).',\n )\n .option('-y, --yes', 'Skip prompts in both destroy + re-init phases.')\n .action(\n async (cmdOpts: {\n dir?: string;\n module?: string;\n workspace?: string;\n yes?: boolean;\n }) => {\n const { resetDevInstallCommand } = await import(\n './commands/module/reset-dev-install.js'\n );\n process.exitCode = await resetDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.workspace !== undefined\n ? { workspace: cmdOpts.workspace }\n : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-8: dashwise table / dashwise field schema commands ──\n\nconst tableCmd = program\n .command('table')\n .description(\n 'Schema commands for the current module — create/delete tables in the dev installation. Requires a per-module dev install (run `dashwise init` first).',\n );\n\ntableCmd\n .command('create <slug>')\n .description(\n 'Create a new table. Pass --field flags to define columns. Calls POST /api/installations/:id/schema/tables and syncs the updated manifest back to local module.json.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '-f, --field <spec>',\n \"Field spec — `<slug>:<type>[:required]`. Repeat for multiple fields. For options/target/default, use --field-json instead. Example: `--field title:text:required --field done:boolean`.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .option(\n '--field-json <json>',\n \"Field as a JSON object — `{slug,type,required?,options?,target?,default?}`. Repeatable. Use for fields where the simple syntax can't express the shape.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .action(\n async (\n slug: string | undefined,\n cmdOpts: { dir?: string; field?: string[]; fieldJson?: string[] },\n ) => {\n const { tableCreateCommand } = await import('./commands/table/create.js');\n process.exitCode = await tableCreateCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.field !== undefined ? { field: cmdOpts.field } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\ntableCmd\n .command('delete <slug>')\n .description(\n \"Drop a table. Calls DELETE /api/installations/:id/schema/tables/:slug — the physical table is soft-deleted (recoverable for 30 days via the dashboard's trash). Updates local module.json.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (slug: string | undefined, cmdOpts: { dir?: string }) => {\n const { tableDeleteCommand } = await import('./commands/table/delete.js');\n process.exitCode = await tableDeleteCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nconst fieldCmd = program\n .command('field')\n .description(\n 'Schema commands for fields within the current module — add/remove/change-type. Field rename is deferred to v1.1 per the plan.',\n );\n\nfieldCmd\n .command('add <table-slug> [field-spec]')\n .description(\n \"Add a field to a table. Pass the spec as `<slug>:<type>[:required]` OR use --field-json for fields with options/target/default. Example: `dashwise field add tasks priority --field-json '{\\\"slug\\\":\\\"priority\\\",\\\"type\\\":\\\"single_select\\\",\\\"options\\\":[\\\"low\\\",\\\"medium\\\",\\\"high\\\"]}'`.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--field-json <json>',\n \"Field as a JSON object. Mutually exclusive with the positional field spec.\",\n )\n .action(\n async (\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n cmdOpts: { dir?: string; fieldJson?: string },\n ) => {\n const { fieldAddCommand } = await import('./commands/field/add.js');\n process.exitCode = await fieldAddCommand(tableSlug, fieldSpec, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\nfieldCmd\n .command('remove <table-slug> <field-slug>')\n .description(\n 'Remove a field from a table. The backend cascades index cleanup (M2-C-FIX): any index referencing the removed field is trimmed; empty indexes are dropped.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldRemoveCommand } = await import('./commands/field/remove.js');\n process.exitCode = await fieldRemoveCommand(tableSlug, fieldSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\nfieldCmd\n .command('set-type <table-slug> <field-slug> <new-type>')\n .description(\n \"Change a field's type (e.g. text → long_text). Lossy changes (text → number with non-numeric data) are rejected by the backend's manifest validator today; v1.1 will add a structured RETYPE_UNSAFE precheck.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldSetTypeCommand } = await import('./commands/field/set-type.js');\n process.exitCode = await fieldSetTypeCommand(\n tableSlug,\n fieldSlug,\n newType,\n {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n },\n );\n },\n );\n\n// Single async entry so unhandled errors hit the same formatter.\n(async () => {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n fail(`Unhandled error: ${(err as Error).message ?? String(err)}`);\n if (process.env.DASHWISE_DEBUG) {\n // Print full stack when debugging — opt-in to keep normal\n // output uncluttered.\n // eslint-disable-next-line no-console\n console.error(err);\n }\n process.exitCode = 1;\n }\n})();\n\n/**\n * CLI version, injected at build time by tsup's `define` from\n * `packages/cli/package.json#version`. See tsup.config.ts.\n */\ndeclare const __CLI_VERSION__: string;\n\nfunction getVersion(): string {\n return __CLI_VERSION__;\n}\n\n/** commander helper: parse a `<n>` argument as an integer. */\nfunction parseIntOption(value: string): number {\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n)) {\n throw new Error(`Expected an integer, got '${value}'`);\n }\n return n;\n}\n\n/**\n * commander helper: collect repeated `--option <value>` flags into\n * an array. Use as the third arg to `.option()` along with `[]` as\n * the default (fourth arg).\n *\n * Example: `--callback-origin http://localhost:3000 --callback-origin https://myapp.local`\n * yields `['http://localhost:3000', 'https://myapp.local']`.\n */\nfunction collectRepeated(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n","/**\n * `dashwise module list` — list modules the current user can author.\n *\n * Hits `GET /api/modules?owned_only=true` so the listing scope is\n * \"modules I own\" by default. Add `--all` to include public modules\n * the user could install but doesn't own. Workspace filter (`--workspace\n * <slug>`) narrows further when the user has multiple workspaces.\n *\n * Output is plain text — column-aligned slug + version + name — so\n * it pipes cleanly into grep / awk.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig } from '../../lib/config.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleListOptions {\n /** Include public modules (default: false — owned only). */\n all?: boolean;\n /**\n * Filter by workspace slug. Falls back to the saved default if\n * omitted, no filter if neither.\n */\n workspace?: string;\n /** Emit JSON to stdout instead of column-aligned text. */\n json?: boolean;\n}\n\ninterface ModuleSummary {\n id: number;\n slug: string;\n name: string;\n owner_workspace_id: number;\n current_version: string | null;\n verified: boolean;\n public: boolean;\n}\n\nexport async function moduleListCommand(\n options: ModuleListOptions,\n): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Resolve workspaceId from slug if requested.\n let workspaceId: number | undefined;\n const targetSlug = options.workspace ?? cfg.workspaceSlug;\n if (targetSlug) {\n try {\n const workspaces = await apiRequest<Array<{ id: number; slug?: string }>>(\n 'GET',\n '/api/workspaces',\n );\n const match = workspaces.find((w) => w.slug === targetSlug);\n if (!match) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'WORKSPACE_NOT_FOUND', message: `Workspace ${targetSlug} not found.` } }));\n } else {\n fail(\n `Workspace ${code(targetSlug)} not found in your accessible workspaces. Run \\`dashwise workspace list\\` to see the choices.`,\n );\n }\n return 1;\n }\n workspaceId = match.id;\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not load workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // Build query.\n const params = new URLSearchParams();\n if (!options.all) params.set('owned_only', 'true');\n if (workspaceId !== undefined) params.set('workspaceId', String(workspaceId));\n const path = `/api/modules${params.toString() ? `?${params.toString()}` : ''}`;\n\n let modules: ModuleSummary[];\n try {\n modules = await apiRequest<ModuleSummary[]>('GET', path);\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list modules: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n modules: Array.isArray(modules) ? modules : [],\n total: Array.isArray(modules) ? modules.length : 0,\n }),\n );\n return 0;\n }\n\n if (!Array.isArray(modules) || modules.length === 0) {\n info(\n options.all\n ? 'No modules found.'\n : 'No modules owned by you yet. Use `dashwise module init <slug>` to scaffold one.',\n );\n return 0;\n }\n\n // Column-aligned plain output. Two passes: compute widths, then format.\n const slugWidth = Math.max(...modules.map((m) => m.slug.length), 4);\n const versionWidth = Math.max(\n ...modules.map((m) => (m.current_version ?? '(draft)').length),\n 7,\n );\n out('');\n out(\n `${'SLUG'.padEnd(slugWidth)} ${'VERSION'.padEnd(versionWidth)} NAME`,\n );\n out(\n `${'-'.repeat(slugWidth)} ${'-'.repeat(versionWidth)} ${'-'.repeat(20)}`,\n );\n for (const m of modules) {\n const version = m.current_version ?? '(draft)';\n const flags = [\n m.verified ? code('✓') : '',\n m.public ? dim('public') : '',\n ]\n .filter(Boolean)\n .join(' ');\n const flagsCol = flags ? ` ${flags}` : '';\n out(`${m.slug.padEnd(slugWidth)} ${version.padEnd(versionWidth)} ${m.name}${flagsCol}`);\n }\n out('');\n info(`${modules.length} module${modules.length === 1 ? '' : 's'}.`);\n return 0;\n}\n","/**\n * `dashwise module publish` — package the local project + upload it\n * as a new module version.\n *\n * Steps:\n * 1. Read local `module.json` to get the slug + module_kind.\n * 2. Resolve `slug → module_id` via `GET /api/modules/by-slug/:slug`.\n * 3. Pack `cwd` into a gzipped tarball via `packTarball()`. The\n * tarball excludes node_modules / .next / .git / .dashwise +\n * caps per-file at 10MB and total at 100MB (matches backend).\n * 4. POST the tarball as multipart form-data to\n * `/api/modules/:id/publish/cli` with the user's bump + flags.\n * 5. Print the resulting version + bundle hash.\n *\n * Confirms before uploading (in TTY) unless `--yes` is passed —\n * publish is the one command where a typo costs a real version bump.\n *\n * Tarball bytes live in memory (≤100MB) — no temp file. We use\n * the native `FormData` + `Blob` available on Node 18+.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, select } from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig, resolveApiUrl } from '../../lib/config.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\nimport { MAX_TARBALL_BYTES, packTarball } from '../../lib/tarball.js';\n\nexport interface PublishOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** SemVer bump direction; required. */\n bump?: 'patch' | 'minor' | 'major';\n /** Dry run: send `dry_run=true`; backend validates without persisting. */\n dryRun?: boolean;\n /** Skip the confirmation prompt (CI / scripted runs). */\n yes?: boolean;\n /** Additional exclude patterns appended to the defaults. */\n exclude?: string[];\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface PublishResponse {\n module_version_id: number;\n module_slug: string;\n version: string;\n bundle_url: string;\n bundle_hash: string;\n bytes_uploaded: number;\n publisher_type: string;\n verified: boolean;\n warnings: string[];\n pipeline_version: string;\n}\n\nconst VALID_BUMP = new Set(['patch', 'minor', 'major']);\n\nexport async function modulePublishCommand(\n options: PublishOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string; name?: string; version?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}. Cannot publish.`);\n return 1;\n }\n\n if (!readConfig()) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n\n // Resolve / prompt for bump.\n let bump = options.bump;\n if (!bump && process.stdout.isTTY) {\n intro(`Publishing module ${code(slug)}`);\n const answer = await select({\n message: 'Bump direction?',\n options: [\n { value: 'patch', label: 'patch — bug fixes only (recommended for first publish)' },\n { value: 'minor', label: 'minor — additive changes (new fields, new tables)' },\n { value: 'major', label: 'major — breaking changes' },\n ],\n initialValue: 'patch',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n bump = answer as 'patch' | 'minor' | 'major';\n }\n if (!bump || !VALID_BUMP.has(bump)) {\n fail('Bump direction required: `--bump patch|minor|major`.');\n return 1;\n }\n\n // Resolve slug → module id.\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(\n `Module ${code(slug)} not found on the backend. Create it via the UI / API first, then re-run publish.`,\n );\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n info(\n `Module: ${code(mod.slug)} (id ${mod.id})${\n mod.current_version ? `, current ${code(`v${mod.current_version}`)}` : dim(', no published version yet')\n }`,\n );\n\n // Pack tarball.\n let tarball;\n try {\n tarball = await packTarball({\n cwd: projectRoot,\n ...(options.exclude !== undefined ? { extraExclude: options.exclude } : {}),\n });\n } catch (err) {\n fail(`Could not pack tarball: ${(err as Error).message}`);\n return 1;\n }\n info(\n `Packed ${tarball.filesIncluded.length} file${tarball.filesIncluded.length === 1 ? '' : 's'} into ${formatBytes(tarball.bytes.byteLength)} (cap ${formatBytes(MAX_TARBALL_BYTES)}).`,\n );\n for (const w of tarball.warnings) warn(w);\n\n // Confirm.\n if (!options.yes && process.stdout.isTTY && !options.dryRun) {\n const answer = await select({\n message: `Upload + publish ${code(`bump:${bump}`)}?`,\n options: [\n { value: 'go', label: 'Yes, upload now' },\n { value: 'cancel', label: 'No, abort' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n fail('Aborted.');\n return 130;\n }\n }\n\n // Multipart upload.\n const cfg = readConfig();\n if (!cfg) {\n fail('Session vanished mid-publish — re-run `dashwise login`.');\n return 1;\n }\n const url = `${resolveApiUrl()}/api/modules/${mod.id}/publish/cli`;\n const form = new FormData();\n // Native `Blob` works in Node 18+; `Buffer` is array-buffer-like\n // so we wrap it before passing to FormData.\n const blob = new Blob([new Uint8Array(tarball.bytes)], { type: 'application/gzip' });\n form.set('file', blob, 'module.tar.gz');\n form.set('bump', bump);\n if (options.dryRun) form.set('dry_run', 'true');\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${cfg.token}`,\n },\n body: form,\n });\n } catch (err) {\n fail(`Network error during upload: ${(err as Error).message}`);\n return 1;\n }\n\n const body = (await res.json().catch(() => null)) as unknown;\n if (!res.ok) {\n const env = body && typeof body === 'object' ? (body as Record<string, unknown>) : null;\n fail(\n `Publish failed (${res.status}${env?.code ? ` ${env.code}` : ''}): ${env?.message ?? '(no message)'}`,\n );\n if (env?.context) {\n out(JSON.stringify(env.context, null, 2));\n }\n return 1;\n }\n\n const result = body as PublishResponse | null;\n if (!result) {\n fail('Publish succeeded but the response body was empty or malformed.');\n return 1;\n }\n if (options.dryRun) {\n success(`Dry run OK — would publish ${code(`v${result.version}`)}`);\n } else {\n success(`Published ${code(mod.slug)} ${code(`v${result.version}`)}`);\n }\n info(`Bundle: ${code(result.bundle_url)}`);\n info(`Hash: ${dim(result.bundle_hash)}`);\n info(`Size: ${formatBytes(result.bytes_uploaded)}`);\n if (result.warnings.length > 0) {\n warn(`${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'}:`);\n for (const w of result.warnings) {\n out(` ${dim('•')} ${w}`);\n }\n }\n if (process.stdout.isTTY && !options.dryRun) outro('Done.');\n return 0;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n","/**\n * Tarball helper for `dashwise module publish`.\n *\n * Wraps the `tar` npm package with DashWise-specific defaults:\n * - gzip compression (server expects `.tar.gz`)\n * - sensible exclusion list (node_modules, .next, .git, ...)\n * - allowlist of files that should ALWAYS be included if present\n * (module.json, manifest.yaml, package.json, app/, server/, etc.)\n * - 100MB size cap (matches backend's `BUNDLE_TOO_LARGE` gate)\n *\n * Output is a `Uint8Array` buffer so callers can pipe it straight\n * into a `fetch` multipart upload without a temp file. The trade-off\n * is memory — but 100MB max is fine for any modern CLI host.\n */\n\nimport { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport * as tar from 'tar';\n\n/**\n * Patterns that should NEVER be included in the published bundle.\n * Path semantics: a candidate path matches if any segment equals\n * the pattern (e.g. `node_modules` matches `foo/node_modules/bar`).\n *\n * Kept conservative: the backend's per-file policy gate is the\n * security boundary; this list is the UX layer that keeps tarballs\n * tractable and the upload step fast.\n */\nexport const DEFAULT_EXCLUDE_PATTERNS = [\n 'node_modules',\n '.next',\n '.git',\n '.turbo',\n '.dashwise',\n '.DS_Store',\n '.env',\n '.env.local',\n '.env.development.local',\n '.env.test.local',\n '.env.production.local',\n 'coverage',\n '.nyc_output',\n '.vitest-cache',\n '.idea',\n '.vscode',\n 'dist',\n 'build',\n] as const;\n\n/** Per-file size cap. Files larger than this are excluded with a warning. */\nconst PER_FILE_BYTE_LIMIT = 10 * 1024 * 1024; // 10MB\n/** Tarball total cap — matches backend BUNDLE_TOO_LARGE gate. */\nexport const MAX_TARBALL_BYTES = 100 * 1024 * 1024; // 100MB\n\nexport interface TarballResult {\n /** Gzipped tarball bytes ready to upload. */\n bytes: Uint8Array;\n /** Files included (relative paths from `cwd`). Sorted. */\n filesIncluded: string[];\n /** Files skipped + the reason. */\n warnings: string[];\n}\n\n/**\n * Pack `cwd` into a gzipped tarball.\n *\n * The pack walks `cwd` once, applies exclusion rules + per-file size\n * limits, and emits a buffer. We don't stream-to-disk because the\n * 100MB ceiling makes the in-memory path fine + lets the caller\n * `fetch(...)` without a temp file dance.\n *\n * `extraExclude` is appended to the defaults so callers can suppress\n * additional patterns (e.g. local secrets) without forking the list.\n */\nexport async function packTarball(opts: {\n cwd: string;\n extraExclude?: readonly string[];\n}): Promise<TarballResult> {\n if (!existsSync(opts.cwd)) {\n throw new Error(`packTarball: cwd not found at ${opts.cwd}`);\n }\n const excludeSet = new Set<string>([\n ...DEFAULT_EXCLUDE_PATTERNS,\n ...(opts.extraExclude ?? []),\n ]);\n const filesIncluded: string[] = [];\n const warnings: string[] = [];\n const candidates = walk(opts.cwd, excludeSet);\n for (const abs of candidates) {\n const rel = relative(opts.cwd, abs);\n const size = statSync(abs).size;\n if (size > PER_FILE_BYTE_LIMIT) {\n warnings.push(\n `${rel} skipped — ${formatBytes(size)} exceeds ${formatBytes(PER_FILE_BYTE_LIMIT)} per-file cap`,\n );\n continue;\n }\n filesIncluded.push(rel);\n }\n if (filesIncluded.length === 0) {\n throw new Error(\n `packTarball: nothing to pack in ${opts.cwd} (after applying exclude list)`,\n );\n }\n filesIncluded.sort();\n\n // The `tar.c` API streams chunks; collect them into one buffer.\n // We use the lower-level callback form so the result is a single\n // contiguous Uint8Array — the multipart upload step expects that.\n const chunks: Buffer[] = [];\n await new Promise<void>((resolveDone, rejectDone) => {\n const stream = tar.c(\n {\n gzip: true,\n cwd: opts.cwd,\n // Don't follow symlinks — bundle-local content only.\n follow: false,\n // Preserve the exact case of paths; the backend's per-file\n // policy gate keys off these.\n portable: true,\n },\n filesIncluded,\n );\n stream.on('data', (chunk: Buffer) => chunks.push(chunk));\n stream.on('error', rejectDone);\n stream.on('end', resolveDone);\n });\n const bytes = Buffer.concat(chunks);\n if (bytes.byteLength > MAX_TARBALL_BYTES) {\n throw new Error(\n `packTarball: tarball is ${formatBytes(bytes.byteLength)}, exceeds ${formatBytes(MAX_TARBALL_BYTES)} max`,\n );\n }\n return { bytes, filesIncluded, warnings };\n}\n\n// ── helpers ────────────────────────────────────────────────────────────\n\nfunction walk(root: string, excludeSet: Set<string>): string[] {\n const out: string[] = [];\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (!dir) continue;\n let entries: import('node:fs').Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue; // unreadable directory — silently skip\n }\n for (const entry of entries) {\n if (excludeSet.has(entry.name)) continue;\n const abs = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(abs);\n } else if (entry.isFile()) {\n out.push(abs);\n }\n // Skip symlinks + sockets + everything else.\n }\n }\n return out;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n\n// Test seam: expose internals for unit tests without making them\n// part of the public package surface.\nexport const __forTests = {\n walk,\n formatBytes,\n PER_FILE_BYTE_LIMIT,\n};\n","/**\n * `dashwise module pull-data` — export own-table data from the\n * owner-workspace installation to a local JSON file (default\n * `dashwise-data.json` in the project root).\n *\n * Useful for: seeding local dev with production-shaped data,\n * fixture generation, manual inspection. The output shape matches\n * what `db.<table>.list()` would return through the SDK — manifest\n * slugs as keys, NOT physical `field_<id>` names — so the data\n * can be reused as fixtures for unit tests or local API mocks.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface PullDataOptions {\n dir?: string;\n /** Max rows per table (1-1000, default 100). */\n limit?: number;\n /** Output path (default: `dashwise-data.json` in dir). */\n out?: string;\n}\n\ninterface PullDataResponse {\n module_slug: string;\n module_version: string | null;\n tables: Array<{\n slug: string;\n total_rows: number;\n rows: Array<Record<string, unknown>>;\n }>;\n}\n\nexport async function modulePullDataCommand(\n options: PullDataOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number };\n try {\n mod = await apiRequest<{ id: number }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found on the backend.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n const limit = options.limit ?? 100;\n let res: PullDataResponse;\n try {\n res = await apiRequest<PullDataResponse>(\n 'GET',\n `/api/modules/${mod.id}/own-data?limit=${limit}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n fail(`Invalid request: ${err.message}`);\n return 1;\n }\n fail(`Could not pull data: ${(err as Error).message}`);\n return 1;\n }\n\n const outPath = options.out\n ? resolve(options.out)\n : join(projectRoot, 'dashwise-data.json');\n writeFileSync(outPath, JSON.stringify(res, null, 2) + '\\n', 'utf-8');\n\n let totalRows = 0;\n for (const t of res.tables) totalRows += t.rows.length;\n success(`Wrote ${totalRows} row${totalRows === 1 ? '' : 's'} across ${res.tables.length} table${res.tables.length === 1 ? '' : 's'} to ${code(outPath)}`);\n\n // Warn on truncation per table — useful when a table has many\n // more rows than the user grabbed.\n for (const t of res.tables) {\n if (t.total_rows > t.rows.length) {\n warn(\n `Table ${code(t.slug)} truncated: ${t.rows.length} of ${t.total_rows} rows (use ${code(`--limit ${Math.min(t.total_rows, 1000)}`)} to grab more).`,\n );\n }\n }\n if (res.tables.length === 0) {\n info(dim('No owned tables on this module. (Did you publish a manifest with `owns.tables`?)'));\n }\n return 0;\n}\n","/**\n * `dashwise module validate` — run the local `module.json` through\n * the backend's `POST /api/modules/manifest/validate` endpoint.\n *\n * Useful as a pre-publish sanity check: catches structural manifest\n * errors (bad field types, unknown table refs, etc.) before paying\n * the cost of a publish round-trip.\n *\n * Output is structured-by-default: bullet-listed issues on failure,\n * \"Manifest is valid\" on success. Exit code 0 / 1 mirrors the\n * underlying validation result.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, out, success } from '../../lib/output.js';\n\nexport interface ValidateOptions {\n dir?: string;\n}\n\ninterface ValidateOkResponse {\n ok: true;\n manifest: unknown;\n}\n\ninterface ManifestIssue {\n path?: string;\n message?: string;\n}\n\nexport async function moduleValidateCommand(\n options: ValidateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n try {\n const res = await apiRequest<ValidateOkResponse>(\n 'POST',\n '/api/modules/manifest/validate',\n manifest,\n );\n if (res.ok) {\n success('Manifest is valid.');\n return 0;\n }\n // Defensive — the endpoint only returns `ok:true` on success;\n // anything else throws on the API side.\n fail(`Unexpected response shape: ${JSON.stringify(res)}`);\n return 1;\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n const issues = readIssues(err.context);\n if (issues.length > 0) {\n fail(`Manifest is invalid (${issues.length} issue${issues.length === 1 ? '' : 's'}):`);\n for (const issue of issues) {\n const path = issue.path ?? '(root)';\n const message = issue.message ?? '(no message)';\n out(` ${dim('•')} ${code(path)}: ${message}`);\n }\n } else {\n fail(`Manifest is invalid: ${err.message}`);\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not validate manifest: ${(err as Error).message}`);\n return 1;\n }\n}\n\nfunction readIssues(context: Record<string, unknown> | undefined): ManifestIssue[] {\n if (!context) return [];\n const v = context['issues'];\n if (!Array.isArray(v)) return [];\n return v\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null;\n const e = entry as Record<string, unknown>;\n const issue: ManifestIssue = {};\n if (typeof e.path === 'string') issue.path = e.path;\n if (typeof e.message === 'string') issue.message = e.message;\n return issue;\n })\n .filter((x): x is ManifestIssue => x !== null);\n}\n","/**\n * `dashwise deps add <provider-slug>` — declare a cross-module dep in\n * `module.json#dependencies`.\n *\n * Two modes:\n * 1. Interactive (TTY default) — fetches the provider's published\n * `exposes` block from the backend, lets the user pick tables +\n * fields via `@clack/prompts.multiselect`, prompts for the\n * required `purpose` string.\n * 2. Non-interactive (`--table`, `--fields`, `--purpose` provided\n * OR not a TTY) — single-table add with no prompts. Multi-table\n * adds are done by re-running the command per table, OR by\n * hand-editing module.json (which `deps list` then displays\n * verbatim).\n *\n * Backend reachability is best-effort: if the provider can't be\n * found (network down, slug typo, provider deleted), interactive\n * mode falls back to a minimal \"manual\" path that asks the user to\n * type the table + field names verbatim.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport {\n intro,\n isCancel,\n multiselect,\n outro,\n select,\n text,\n} from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n type ManifestShape,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DepsAddOptions {\n dir?: string;\n /** Single-table add: required in non-interactive mode. */\n table?: string;\n /** Comma-separated field slugs for `--table`. */\n fields?: string;\n /** Human-readable purpose (10-500 chars, per manifest schema). */\n purpose?: string;\n /** SemVer range (default: `^<provider-current-version>` if backend reachable, else `^0.0.1`). */\n version?: string;\n /** Skip the confirmation step when replacing an existing dep declaration. */\n yes?: boolean;\n}\n\nconst MIN_PURPOSE_LEN = 10;\nconst MAX_PURPOSE_LEN = 500;\n\n/** Backend manifest_jsonb shape, only the parts the CLI needs. */\ninterface ProviderManifestSummary {\n module?: { slug?: string; name?: string; version?: string };\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: {\n list?: { allowed?: boolean };\n get?: { allowed?: boolean };\n search?: { allowed?: boolean };\n };\n visibility?: string;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n module_id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\nexport async function depsAddCommand(\n providerSlug: string,\n options: DepsAddOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps add <provider-slug>`');\n return 1;\n }\n // Module slugs are kebab-case (matches backend MODULE_SLUG_REGEX).\n if (!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(providerSlug)) {\n fail(\n `Provider slug ${code(providerSlug)} is invalid. Module slugs are kebab-case (e.g. ${code('crm-app')}).`,\n );\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Refuse to self-depend (would be a no-op but confusing).\n if (manifest.module?.slug === providerSlug) {\n fail('A module cannot depend on itself.');\n return 1;\n }\n\n const isInteractive = process.stdout.isTTY;\n const hasAllNonInteractive =\n options.table !== undefined &&\n options.fields !== undefined &&\n options.purpose !== undefined;\n\n if (!isInteractive && !hasAllNonInteractive) {\n fail(\n `Non-interactive mode requires ${code('--table')}, ${code('--fields')}, and ${code('--purpose')}.`,\n );\n return 1;\n }\n\n // Fetch provider summary (best-effort — non-fatal in interactive mode).\n let providerSummary: ProviderManifestSummary | null = null;\n let resolvedVersion: string | null = null;\n try {\n const mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(providerSlug)}`,\n );\n if (mod.current_version) {\n const versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n // Versions are returned newest-first per the controller spec; the\n // first one matching `current_version` is what's actually\n // installable. Fall back to versions[0] if no exact match.\n const current =\n versions.find((v) => v.version === mod.current_version) ??\n versions[0];\n if (current) {\n providerSummary = current.manifest_jsonb;\n resolvedVersion = current.version;\n }\n }\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (!isInteractive) {\n fail(\n `Provider ${code(providerSlug)} not found on the backend. Publish it first or check the slug.`,\n );\n return 1;\n }\n warn(\n `Provider ${code(providerSlug)} not found on the backend (404). You can still declare the dep manually.`,\n );\n } else if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n } else {\n warn(`Could not fetch provider summary: ${(err as Error).message}`);\n }\n }\n\n // Resolve the dep entry's fields.\n let entry: ManifestDependency;\n if (isInteractive) {\n intro(`Adding dependency on ${code(providerSlug)}`);\n const built = await collectInteractive(\n providerSlug,\n providerSummary,\n resolvedVersion,\n options,\n );\n if (built === null) {\n outro('Cancelled.');\n return 130;\n }\n entry = built;\n } else {\n // Non-interactive path: all required args are present per the\n // check above; we trust them + let the backend validate semantics\n // on the next publish.\n const fieldList = (options.fields ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (fieldList.length === 0) {\n fail(`${code('--fields')} must list at least one field slug.`);\n return 1;\n }\n const purposeErr = validatePurpose(options.purpose!);\n if (purposeErr) {\n fail(purposeErr);\n return 1;\n }\n entry = {\n module: providerSlug,\n version: options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1'),\n reads: [{ table: options.table!, fields: fieldList }],\n purpose: options.purpose!,\n };\n }\n\n // Merge with existing manifest.dependencies[].\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const existingIdx = deps.findIndex((d) => d.module === providerSlug);\n if (existingIdx >= 0) {\n if (!options.yes && isInteractive) {\n const answer = await select({\n message: `Dep on ${providerSlug} already exists. Replace it?`,\n options: [\n { value: 'replace', label: 'Replace (loses prior reads/writes)' },\n { value: 'cancel', label: 'Cancel' },\n ],\n initialValue: 'replace',\n });\n if (isCancel(answer) || answer === 'cancel') {\n outro('Cancelled.');\n return 130;\n }\n }\n deps[existingIdx] = entry;\n } else {\n deps.push(entry);\n }\n manifest.dependencies = deps;\n\n try {\n writeManifest(manifest as ManifestShape, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(\n `${existingIdx >= 0 ? 'Replaced' : 'Added'} dependency on ${code(providerSlug)}@${entry.version}.`,\n );\n info(`Reads: ${entry.reads.map((r) => `${code(r.table)} (${r.fields.join(', ')})`).join('; ')}`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n if (isInteractive) outro('Done.');\n return 0;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\ninterface NormalizedReadEntry {\n table: string;\n fields: string[];\n}\n\nasync function collectInteractive(\n providerSlug: string,\n summary: ProviderManifestSummary | null,\n resolvedVersion: string | null,\n options: DepsAddOptions,\n): Promise<ManifestDependency | null> {\n const reads: NormalizedReadEntry[] = [];\n\n if (summary && summary.exposes && summary.exposes.length > 0) {\n // Backend-assisted: present the actual exposes set.\n info(\n `Provider exposes ${summary.exposes.length} table${summary.exposes.length === 1 ? '' : 's'}.`,\n );\n // Filter to tables the provider actually allows `list` or `get` on\n // (others are visible-but-unreadable from a SDK perspective).\n const readableTables = summary.exposes.filter((e) => {\n const ops = e.operations;\n if (!ops) return true; // back-compat: no operations block = implicit allow\n return ops.list?.allowed === true || ops.get?.allowed === true;\n });\n if (readableTables.length === 0) {\n warn(\n `Provider ${code(providerSlug)} exposes tables but none are readable (operations.list / .get all denied).`,\n );\n return null;\n }\n\n const picked = await multiselect({\n message: 'Which tables do you want to read from?',\n options: readableTables.map((e) => ({\n value: e.table,\n label: `${e.table} ${dim(`(${e.fields.length} field${e.fields.length === 1 ? '' : 's'})`)}`,\n })),\n required: true,\n });\n if (isCancel(picked)) return null;\n\n for (const tableSlug of picked as string[]) {\n const exposeEntry = readableTables.find((e) => e.table === tableSlug)!;\n const fieldsPicked = await multiselect({\n message: `Fields to read from ${code(tableSlug)}:`,\n options: exposeEntry.fields.map((f) => ({ value: f, label: f })),\n required: true,\n initialValues: exposeEntry.fields, // pre-select all; user trims down\n });\n if (isCancel(fieldsPicked)) return null;\n reads.push({ table: tableSlug, fields: fieldsPicked as string[] });\n }\n } else {\n // Manual fallback when no backend summary is available.\n info('No provider summary available — enter table + fields manually.');\n const tableSlug = await text({\n message: 'Provider table slug to read from:',\n placeholder: 'contacts',\n validate: (v) =>\n /^[a-z][a-z0-9_]*[a-z0-9]$/.test(v) ? undefined : 'Table slugs are snake_case.',\n });\n if (isCancel(tableSlug)) return null;\n const fieldsStr = await text({\n message: 'Comma-separated field slugs:',\n placeholder: 'name, email, company',\n validate: (v) =>\n v.split(',').map((s) => s.trim()).filter(Boolean).length > 0\n ? undefined\n : 'At least one field required.',\n });\n if (isCancel(fieldsStr)) return null;\n reads.push({\n table: tableSlug as string,\n fields: (fieldsStr as string)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean),\n });\n }\n\n // Purpose — manifest validator requires 10-500 chars.\n const initialPurpose = options.purpose ?? '';\n const purpose = await text({\n message: `Why does your module need this dependency? ${dim(`(${MIN_PURPOSE_LEN}-${MAX_PURPOSE_LEN} chars; shown to workspace admins at install consent)`)}`,\n placeholder: 'Look up assignee contact info when rendering tasks.',\n initialValue: initialPurpose,\n validate: (v) => validatePurpose(v) ?? undefined,\n });\n if (isCancel(purpose)) return null;\n\n // Version range — default to `^<resolved>` for stability.\n const defaultVersion =\n options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1');\n const version = await text({\n message: `SemVer range to pin: ${dim('(npm-style; e.g. ^1.2.3, ~1.2.0, >=1.0.0)')}`,\n placeholder: defaultVersion,\n initialValue: defaultVersion,\n validate: (v) =>\n /^[\\^~]?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v) ||\n /^(>=|<=|>|<|=)?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v)\n ? undefined\n : 'Must be a npm-style semver range (e.g. ^1.2.3).',\n });\n if (isCancel(version)) return null;\n\n return {\n module: providerSlug,\n version: version as string,\n reads,\n purpose: purpose as string,\n };\n}\n\nfunction validatePurpose(purpose: string): string | null {\n if (typeof purpose !== 'string') return 'Purpose must be a string.';\n if (purpose.length < MIN_PURPOSE_LEN) {\n return `Purpose must be at least ${MIN_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n if (purpose.length > MAX_PURPOSE_LEN) {\n return `Purpose must be at most ${MAX_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n return null;\n}\n","/**\n * `dashwise deps check` — verify each declared dep still resolves\n * against a currently-published provider and that every field /\n * operation in the contract is still exposed.\n *\n * Exit code:\n * 0 — all deps healthy\n * 1 — at least one drift issue found\n *\n * Reports per-dep issues with a clear next step:\n * - PROVIDER_NOT_FOUND → the provider was deleted or renamed\n * - NO_MATCHING_VERSION → no published version satisfies the SemVer range\n * - FIELD_NOT_EXPOSED → consumer reads a field the provider no longer exposes\n * - OP_NOT_ALLOWED → consumer declares writes the provider blocks (writes opt-in)\n *\n * Backend reachability is required — `check` is an online command by\n * design. If the backend is unreachable, exit 1 with a clear message\n * (CI workflows can catch this + retry).\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\nexport interface DepsCheckOptions {\n dir?: string;\n json?: boolean;\n}\n\ninterface ProviderManifestSummary {\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: Partial<\n Record<\n 'list' | 'get' | 'search' | 'create' | 'update' | 'delete',\n { allowed?: boolean }\n >\n >;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\ninterface Issue {\n /** Stable code so JSON consumers can branch. */\n code:\n | 'PROVIDER_NOT_FOUND'\n | 'NO_MATCHING_VERSION'\n | 'FIELD_NOT_EXPOSED'\n | 'TABLE_NOT_EXPOSED'\n | 'OP_NOT_ALLOWED'\n | 'BACKEND_UNREACHABLE';\n module: string;\n message: string;\n context?: Record<string, unknown>;\n}\n\nexport async function depsCheckCommand(options: DepsCheckOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n if (deps.length === 0) {\n if (options.json) {\n out(JSON.stringify({ ok: true, deps: [], issues: [] }, null, 2));\n } else {\n info('No dependencies declared. Nothing to check.');\n }\n return 0;\n }\n\n const issues: Issue[] = [];\n const perDepStatus: Array<{ module: string; ok: boolean; resolved_version: string | null }> = [];\n\n for (const dep of deps) {\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(dep.module)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n issues.push({\n code: 'PROVIDER_NOT_FOUND',\n module: dep.module,\n message: `Provider ${dep.module} not found on the backend. It may have been deleted or renamed.`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n // Network / 500 / etc. — treat as fatal; we can't reason about\n // drift without an answer from the backend.\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not reach the backend: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Pick the highest-matching version (newest-first per the\n // listVersions controller spec).\n let versions: VersionResponse[];\n try {\n versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n } catch (err) {\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not list versions: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n const matching = pickMatching(versions, dep.version);\n if (!matching) {\n issues.push({\n code: 'NO_MATCHING_VERSION',\n module: dep.module,\n message: `No published version satisfies ${dep.version}. Available: ${versions.map((v) => v.version).join(', ') || '(none)'}.`,\n context: { range: dep.version, available: versions.map((v) => v.version) },\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Drift checks against the matching version's manifest.\n const exposes = matching.manifest_jsonb.exposes ?? [];\n let depHealthy = true;\n\n for (const readEntry of dep.reads) {\n const exposeEntry = exposes.find((e) => e.table === readEntry.table);\n if (!exposeEntry) {\n issues.push({\n code: 'TABLE_NOT_EXPOSED',\n module: dep.module,\n message: `Table ${code(readEntry.table)} is no longer exposed by ${dep.module}@${matching.version}.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n continue;\n }\n const exposedFields = new Set(exposeEntry.fields);\n const missing = readEntry.fields.filter((f) => !exposedFields.has(f));\n if (missing.length > 0) {\n issues.push({\n code: 'FIELD_NOT_EXPOSED',\n module: dep.module,\n message: `Fields ${missing.map((f) => code(f)).join(', ')} on ${code(readEntry.table)} are no longer exposed by ${dep.module}@${matching.version}.`,\n context: {\n table: readEntry.table,\n missing,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n // Operation gate for list/get — we don't include search here since\n // the SDK doesn't expose it and the v1 plan doesn't either.\n const listAllowed = exposeEntry.operations?.list?.allowed !== false;\n const getAllowed = exposeEntry.operations?.get?.allowed !== false;\n if (!listAllowed && !getAllowed) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Provider ${dep.module}@${matching.version} disallows both list AND get on ${code(readEntry.table)} — no reads possible.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n }\n }\n\n // Write-side drift (only flagged when consumer declared writes).\n for (const writeEntry of dep.writes ?? []) {\n const exposeEntry = exposes.find((e) => e.table === writeEntry.table);\n if (!exposeEntry) continue; // already flagged via reads loop\n for (const op of writeEntry.operations) {\n const gate = exposeEntry.operations?.[op as 'create' | 'update' | 'delete'];\n if (!gate || gate.allowed !== true) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Write operation ${code(op)} on ${code(writeEntry.table)} is not allowed by ${dep.module}@${matching.version}.`,\n context: {\n table: writeEntry.table,\n operation: op,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n }\n }\n\n perDepStatus.push({\n module: dep.module,\n ok: depHealthy,\n resolved_version: matching.version,\n });\n }\n\n const ok = issues.length === 0;\n\n if (options.json) {\n out(\n JSON.stringify(\n { ok, deps: perDepStatus, issues },\n null,\n 2,\n ),\n );\n return ok ? 0 : 1;\n }\n\n // Human-readable output.\n for (const dep of perDepStatus) {\n if (dep.ok) {\n success(\n `${code(dep.module)} → ${dep.resolved_version ? `v${dep.resolved_version}` : dim('(no version)')}`,\n );\n } else {\n fail(`${code(dep.module)} ${dim('(drift detected)')}`);\n }\n }\n if (issues.length > 0) {\n out('');\n warn(`${issues.length} issue${issues.length === 1 ? '' : 's'}:`);\n for (const issue of issues) {\n out(` ${dim(`[${issue.code}]`)} ${issue.message}`);\n }\n out('');\n info(\n `Fix by removing/updating the dep (${code('dashwise deps remove <slug>')} then ${code('dashwise deps add <slug>')}) or by updating the provider.`,\n );\n } else {\n out('');\n success(`All ${perDepStatus.length} dependenc${perDepStatus.length === 1 ? 'y is' : 'ies are'} healthy.`);\n }\n return ok ? 0 : 1;\n}\n\n/**\n * Pick the newest version satisfying `range`. Range parsing is\n * intentionally minimal — covers `^x.y.z`, `~x.y.z`, `>=x.y.z`,\n * `<=x.y.z`, `>x.y.z`, `<x.y.z`, `=x.y.z`, and bare `x.y.z`. Full\n * SemVer support lives in the backend; this is a fail-soft heuristic\n * so check can give useful feedback even when offline tooling is the\n * canonical resolver.\n *\n * Caller passes `versions` in newest-first order (matches the\n * backend's `GET /:id/versions` contract).\n */\nfunction pickMatching(\n versions: VersionResponse[],\n range: string,\n): VersionResponse | null {\n for (const v of versions) {\n if (rangeSatisfied(v.version, range)) return v;\n }\n return null;\n}\n\nfunction rangeSatisfied(version: string, range: string): boolean {\n const vParts = parseSemver(version);\n if (!vParts) return false;\n const trimmed = range.trim();\n const opMatch = trimmed.match(/^(>=|<=|>|<|=|\\^|~)?(.+)$/);\n if (!opMatch) return false;\n const op = opMatch[1] ?? '=';\n const target = parseSemver(opMatch[2]);\n if (!target) return false;\n const cmp = compareSemver(vParts, target);\n switch (op) {\n case '=':\n return cmp === 0;\n case '>':\n return cmp > 0;\n case '<':\n return cmp < 0;\n case '>=':\n return cmp >= 0;\n case '<=':\n return cmp <= 0;\n case '^':\n // ^1.2.3 → >=1.2.3 <2.0.0 ; ^0.2.3 → >=0.2.3 <0.3.0 ; ^0.0.3 → >=0.0.3 <0.0.4\n if (cmp < 0) return false;\n if (target[0] > 0) return vParts[0] === target[0];\n if (target[1] > 0) return vParts[0] === 0 && vParts[1] === target[1];\n return vParts[0] === 0 && vParts[1] === 0 && vParts[2] === target[2];\n case '~':\n // ~1.2.3 → >=1.2.3 <1.3.0\n if (cmp < 0) return false;\n return vParts[0] === target[0] && vParts[1] === target[1];\n default:\n return false;\n }\n}\n\nfunction parseSemver(s: string): [number, number, number] | null {\n const m = s.trim().match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[a-zA-Z0-9.-]+)?$/);\n if (!m) return null;\n return [Number(m[1]), Number(m[2]), Number(m[3])];\n}\n\nfunction compareSemver(a: [number, number, number], b: [number, number, number]): number {\n for (let i = 0; i < 3; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return 0;\n}\n\n/**\n * Test seam — expose internal helpers for unit tests without making\n * them part of the CLI's public surface. Same pattern as\n * `lib/tarball.ts#__forTests`.\n */\nexport const __forTests = {\n rangeSatisfied,\n pickMatching,\n parseSemver,\n compareSemver,\n};\n","/**\n * `dashwise deps list` — show declared cross-module dependencies.\n *\n * Pure-local read from `module.json#dependencies`. No backend call;\n * runs offline. For drift detection (does each declared dep still\n * resolve against an installed provider?) use `dashwise deps check`.\n *\n * Output shapes:\n * - Default: human-readable columns + per-dep `reads:` / `writes:`\n * summaries.\n * - `--json`: stable JSON array of `{ module, version, reads,\n * writes?, purpose }` — same shape as the manifest's\n * `dependencies[]` entries. Pipes cleanly into `jq`.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { readManifestOrThrow, type ManifestDependency } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface DepsListOptions {\n dir?: string;\n json?: boolean;\n}\n\nexport async function depsListCommand(options: DepsListOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n\n if (options.json) {\n // Stable, pipe-friendly. Empty deps list → empty array (not null);\n // jq consumers don't have to handle the absent-key case.\n out(JSON.stringify(deps, null, 2));\n return 0;\n }\n\n if (deps.length === 0) {\n info('No dependencies declared in module.json.');\n info(`Run ${code('dashwise deps add <provider-slug>')} to add one.`);\n return 0;\n }\n\n out(`${deps.length} dependenc${deps.length === 1 ? 'y' : 'ies'} declared:`);\n out('');\n for (const dep of deps) {\n out(` ${code(dep.module)}@${dep.version}`);\n out(` ${dim('purpose:')} ${dep.purpose}`);\n if (dep.reads.length > 0) {\n out(` ${dim('reads:')}`);\n for (const r of dep.reads) {\n out(` ${code(r.table)} → ${r.fields.join(', ')}`);\n }\n }\n if (dep.writes && dep.writes.length > 0) {\n out(` ${dim('writes:')}`);\n for (const w of dep.writes) {\n out(\n ` ${code(w.table)} → ${w.fields.join(', ')} (${w.operations.join('/')})`,\n );\n }\n }\n out('');\n }\n return 0;\n}\n","/**\n * `dashwise deps remove <provider-slug>` — delete the dep entry from\n * `module.json#dependencies`.\n *\n * Pure-local mutation. Idempotent: removing a slug that's not declared\n * is treated as a no-op + reported (exit 0). Confirmation prompt\n * unless `--yes` is passed.\n *\n * After successful removal, prints a reminder to re-run\n * `dashwise module generate` so the typed wrappers no longer reference\n * the removed dep. (Generated `deps.<member>` access becomes a\n * compile error in consumer code — that's the right surface to catch\n * stale references.)\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface DepsRemoveOptions {\n dir?: string;\n /** Skip the confirmation prompt (CI / scripts). */\n yes?: boolean;\n}\n\nexport async function depsRemoveCommand(\n providerSlug: string,\n options: DepsRemoveOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps remove <provider-slug>`');\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const target = deps.find((d) => d.module === providerSlug);\n if (!target) {\n // Idempotent — not an error. Mirrors `apt remove` / `npm uninstall`\n // semantics for \"wasn't installed anyway.\"\n info(`No dependency on ${code(providerSlug)} declared; nothing to remove.`);\n return 0;\n }\n\n if (!options.yes && process.stdout.isTTY) {\n const answer = await select({\n message: `Remove dependency on ${providerSlug}?`,\n options: [\n { value: 'go', label: 'Yes, remove it' },\n { value: 'cancel', label: 'No, keep it' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n info('Aborted.');\n return 130;\n }\n }\n\n manifest.dependencies = deps.filter((d) => d.module !== providerSlug);\n // Normalize: if the array became empty, drop the key entirely so the\n // manifest matches what `dashwise module init` emits for a fresh\n // module (no `dependencies` key at all).\n if ((manifest.dependencies as ManifestDependency[]).length === 0) {\n delete manifest.dependencies;\n }\n\n try {\n writeManifest(manifest, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(`Removed dependency on ${code(providerSlug)}.`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n return 0;\n}\n","/**\n * `dashwise query` — run typed queries against the local module's\n * installation via the @dashai/sdk query plane.\n *\n * Three modes:\n * --inline \"<expr>\" Evaluate a one-liner. `qb`, `deps`, `db` are\n * pre-bound to the local module's generated SDK.\n * Example:\n * dashwise query --inline \"qb.tasks.where({done:false}).count()\"\n * --file <path> Dynamic-import a .mjs/.js file. The file should\n * export a default that's either a Query, an\n * AggQuery, or a Promise.\n * Example file:\n * import { qb } from '@dashai/generated';\n * export default qb.tasks.where({done:false}).limit(20);\n * --repl Open a Node REPL with the generated SDK pre-bound.\n * Top-level await supported. Ctrl-D to exit.\n *\n * All three modes:\n * - Run in the current directory (must contain `module.json` +\n * `node_modules/@dashai/generated`).\n * - Load env from `.env.local` if present (matches the scaffold's\n * dev-loop convention); DASHWISE_API_URL / _INSTALLATION_ID /\n * _API_TOKEN must be set before the SDK can hit the backend.\n * - Print the result as pretty-printed JSON. `--json` flag emits\n * compact JSON for piping.\n *\n * v1 limits:\n * - --file accepts .mjs / .js only. .ts requires `tsx` which we\n * don't bundle yet. Workaround: `npx tsx <path>` directly.\n * - --inline expression must be valid JS (or `await`-friendly\n * pattern). TS syntax not supported in --inline either.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §6.3, §9.\n */\n\nimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, resolve as pathResolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { manifestPath, readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../lib/output.js';\n\nexport interface QueryCommandOptions {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n /**\n * Phase 5 `.explain()` flag (2026-05-19). When true, the runner\n * calls `.explain()` on the resulting Query/JoinedQuery/AggQuery\n * (returning the Postgres plan envelope) instead of `.execute()`.\n * No-op for `--repl` mode — REPL users call `.explain()` themselves.\n *\n * Backend MVP supports joined queries only; bare own/dep/view paths\n * reject server-side with EXPLAIN_NOT_SUPPORTED_YET. The CLI passes\n * the call through unchanged and surfaces the typed error to the\n * caller.\n */\n explain?: boolean;\n /**\n * Phase 6 streaming flag (2026-05-20). When true, the runner calls\n * `.stream()` instead of `.execute()` and prints rows incrementally\n * as JSON-lines (one row per line, terminated by `\\n`). Lets users\n * see progress on big queries + Ctrl-C cleanly midway. Mutually\n * exclusive with `--explain` (different ops) and `--repl` (REPL\n * users call `.stream()` themselves and use `for await`).\n *\n * `--json` is implied — streaming always emits JSON-lines, never\n * the pretty-printed result wrapper. Bare-array `--json` output is\n * what most users want anyway when piping into `jq`.\n */\n stream?: boolean;\n}\n\nexport async function queryCommand(options: QueryCommandOptions): Promise<number> {\n const projectRoot = pathResolve(options.dir ?? process.cwd());\n\n // Sanity: must be inside a module project.\n try {\n readManifestOrThrow(projectRoot);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Must have run `dashwise module generate` so @dashai/generated\n // exists. Surface the missing-package case with the right next step.\n const generatedPath = join(\n projectRoot,\n 'node_modules',\n '@dashai',\n 'generated',\n );\n if (!existsSync(generatedPath)) {\n fail(\n `No ${code('@dashai/generated')} in ${code('node_modules')}. Run ${code('dashwise module generate')} first.`,\n );\n return 1;\n }\n\n // Best-effort env loading from .env.local — matches what the\n // scaffold ships + what `dashwise module dev` would inject. The\n // generated SDK reads these via `process.env.DASHWISE_*` so we\n // hydrate `process.env` directly (vs. a richer dotenv parser —\n // the format is k=v lines, no quoting needed for the dev env).\n hydrateEnvFromDotenvLocal(projectRoot);\n\n // Exactly one mode flag must be set.\n const modes = [\n options.inline !== undefined ? 'inline' : null,\n options.file !== undefined ? 'file' : null,\n options.repl === true ? 'repl' : null,\n ].filter(Boolean);\n if (modes.length === 0) {\n fail('Pass one of: `--inline \"expr\"`, `--file <path>`, or `--repl`.');\n return 1;\n }\n if (modes.length > 1) {\n fail(`--inline / --file / --repl are mutually exclusive (got: ${modes.join(', ')}).`);\n return 1;\n }\n\n // Phase 5 (2026-05-19): --explain is meaningless with --repl (REPL\n // users call .explain() themselves). Reject the combo with a clear\n // message rather than silently ignoring.\n if (options.explain === true && options.repl === true) {\n fail('--explain has no effect with --repl. In the REPL, call `.explain()` directly on your builder.');\n return 1;\n }\n // Phase 6 streaming (2026-05-20): same logic for --stream + --repl.\n if (options.stream === true && options.repl === true) {\n fail('--stream has no effect with --repl. In the REPL, call `.stream()` directly + use `for await`.');\n return 1;\n }\n // --explain and --stream are different operations (return plan vs.\n // stream rows). Mutual exclusion prevents accidental misuse like\n // \"stream the explain plan\" which has no defined semantic.\n if (options.explain === true && options.stream === true) {\n fail('--explain and --stream are mutually exclusive — `.explain()` returns a single plan envelope; `.stream()` yields rows.');\n return 1;\n }\n const explain = options.explain === true;\n const stream = options.stream === true;\n\n if (options.repl) return runRepl(generatedPath);\n if (options.file !== undefined)\n return runFile(options.file, projectRoot, options.json === true, explain, stream);\n if (options.inline !== undefined)\n return runInline(\n options.inline,\n projectRoot,\n generatedPath,\n options.json === true,\n explain,\n stream,\n );\n // Unreachable per the modes check above.\n return 1;\n}\n\n// ── Mode: --inline ──────────────────────────────────────────────────────\n\n/**\n * Evaluate a one-liner expression with `qb`, `deps`, `db` in scope.\n *\n * Strategy: write a temp `.mjs` file that imports the generated SDK\n * + evaluates the expression as a default export, then dynamic-import\n * it. The temp file lives in tmpdir; cleaned up on the way out (or\n * left on disk if the process is killed — best-effort cleanup).\n *\n * Reason for temp-file vs. `new Function(...)`: dynamic import gives\n * us proper ESM semantics + module-resolution against `node_modules/@dashai/generated`,\n * which `new Function` doesn't. Cost is one syscall per invocation.\n */\nasync function runInline(\n expression: string,\n projectRoot: string,\n _generatedPath: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const tmpDir = mkdtempSync(join(tmpdir(), 'dashwise-query-'));\n const tmpFile = join(tmpDir, 'inline.mjs');\n // Strip a trailing semicolon if present so the embedded expression\n // is a valid value position.\n const cleanedExpr = expression.trim().replace(/;\\s*$/, '');\n const source = [\n \"import { qb, deps, db } from '@dashai/generated';\",\n `export default (async () => (${cleanedExpr}))();`,\n '',\n ].join('\\n');\n writeFileSync(tmpFile, source, 'utf-8');\n try {\n return await importAndPrint(tmpFile, projectRoot, jsonCompact, explain, stream);\n } finally {\n try {\n rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup. tmp dirs get reaped by the OS.\n }\n }\n}\n\n// ── Mode: --file ────────────────────────────────────────────────────────\n\n/**\n * Run a `.mjs` / `.js` file via dynamic import. The file should\n * export a default that's a Query / AggQuery / Promise / value.\n *\n * `.ts` files are NOT supported in v1 — would require bundling `tsx`\n * or running through `node --import tsx`. Users can shell out via\n * `npx tsx <file>` directly for TS today.\n */\nasync function runFile(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const abs = pathResolve(projectRoot, file);\n if (!existsSync(abs)) {\n fail(`File not found: ${code(abs)}`);\n return 1;\n }\n if (!/\\.(mjs|js)$/.test(abs)) {\n fail(\n `Only .mjs / .js files are supported in v1. For .ts files, run ${code('npx tsx <file>')} directly. (Tracked: bundle tsx for native .ts support.)`,\n );\n return 1;\n }\n return importAndPrint(abs, projectRoot, jsonCompact, explain, stream);\n}\n\n// ── Mode: --repl ────────────────────────────────────────────────────────\n\n/**\n * Open an interactive Node REPL with the generated SDK pre-bound.\n *\n * Implementation: Node's built-in `repl` module. The generated SDK is\n * imported once at startup + its exports (`qb`, `deps`, `db`) are\n * added to the REPL's context object. Top-level await works because\n * Node's REPL has supported it since v12.\n *\n * Exit with `.exit` or Ctrl-D. Stack traces from query errors stay\n * in the REPL so users can keep iterating.\n */\nasync function runRepl(generatedPath: string): Promise<number> {\n let generated: Record<string, unknown>;\n try {\n generated = await dynamicImportFromPath(generatedPath);\n } catch (err) {\n fail(\n `Could not import ${code('@dashai/generated')}: ${(err as Error).message}`,\n );\n info(\n `Try running ${code('dashwise module generate')} to refresh the typed wrappers.`,\n );\n return 1;\n }\n\n info(`${code('dashwise query --repl')} — Node REPL with qb / deps / db pre-bound.`);\n info(`Try: ${code('await qb.<table>.execute()')} Ctrl-D to exit.`);\n out('');\n\n // Dynamic require for Node's repl module — keep it lazy so the\n // command's startup cost stays low for the inline/file modes.\n const repl = await import('node:repl');\n const server = repl.start({\n prompt: `${code('dashwise')}${dim('>')} `,\n useColors: true,\n useGlobal: false,\n });\n // Inject the generated SDK's exports into the REPL context so\n // users type `qb.tasks.execute()` without imports.\n for (const [key, value] of Object.entries(generated)) {\n Object.defineProperty(server.context, key, {\n configurable: false,\n enumerable: true,\n writable: false,\n value,\n });\n }\n\n return new Promise<number>((resolveExit) => {\n server.on('exit', () => {\n out(dim('Goodbye.'));\n resolveExit(0);\n });\n });\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Dynamic-import `file` (resolving from `projectRoot`'s\n * `node_modules`), await the default export if it's a Promise / Query\n * / AggQuery, and pretty-print the result.\n */\nasync function importAndPrint(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n // Switch cwd so bare imports inside the file resolve against the\n // project's `node_modules` instead of the CLI's own. Saved + restored\n // around the import — defensive in case the consumer's code touches\n // process.cwd elsewhere.\n const originalCwd = process.cwd();\n try {\n process.chdir(projectRoot);\n const url = pathToFileURL(file).toString();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import(url);\n let result = mod.default;\n // Default-export shapes we handle:\n // - Promise<T> → await it\n // - Query / AggQuery → .execute() (or .explain() if --explain,\n // or .stream() if --stream)\n // - Anything else → print as-is\n if (result && typeof result.then === 'function') {\n result = await result;\n }\n if (result && typeof result.toAst === 'function') {\n // Phase 6 streaming (2026-05-20): --stream takes precedence over\n // --execute (they're mutually exclusive at the option-parse level,\n // but ordering matters at dispatch time). Iterate the async\n // iterable + print one JSON-line per row so consumers can pipe\n // into jq / line-oriented tools.\n if (stream && typeof result.stream === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const iterable = result.stream() as AsyncIterable<unknown>;\n let rowCount = 0;\n for await (const row of iterable) {\n out(JSON.stringify(row));\n rowCount++;\n }\n // Emit a final summary on stderr so it doesn't pollute the\n // JSON-lines stdout stream. Consumers piping into jq see ONLY\n // the data; humans see \"streamed N rows\" at the bottom.\n if (!jsonCompact) {\n info(`Streamed ${rowCount} row${rowCount === 1 ? '' : 's'}.`);\n }\n return 0;\n }\n // Phase 5 `.explain()` (2026-05-19): if --explain was passed,\n // call .explain() instead of .execute(). All three builder\n // shapes (Query, JoinedQuery, AggQuery) expose .explain() since\n // the SDK slice landed alongside this CLI flag.\n if (explain && typeof result.explain === 'function') {\n result = await result.explain();\n } else if (typeof result.execute === 'function') {\n result = await result.execute();\n }\n }\n if (jsonCompact) {\n out(JSON.stringify(result));\n } else {\n out(JSON.stringify(result, null, 2));\n }\n return 0;\n } catch (err) {\n fail(`Query failed: ${(err as Error).message}`);\n if (process.env.DASHWISE_DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n return 1;\n } finally {\n process.chdir(originalCwd);\n }\n}\n\n/**\n * Resolve `@dashai/generated` from the project's node_modules and\n * dynamic-import its entry. Returns the module's exports object.\n */\nasync function dynamicImportFromPath(\n generatedDir: string,\n): Promise<Record<string, unknown>> {\n // Project-local @dashai/generated has `index.js` per the codegen\n // emitter; resolve directly rather than going through Node's package\n // resolution to keep the path deterministic.\n const entry = join(generatedDir, 'index.js');\n if (!existsSync(entry)) {\n throw new Error(`Expected ${entry} to exist. Did 'dashwise module generate' run?`);\n }\n const url = pathToFileURL(entry).toString();\n return (await import(url)) as Record<string, unknown>;\n}\n\n/**\n * Read `.env.local` from `projectRoot` and merge into `process.env`\n * without overwriting existing values. Supports `KEY=value` lines\n * + `#`-prefixed comments + blank lines — same dialect the scaffold's\n * `.env.local.example` uses. Robust enough for the dev-loop env.\n */\nfunction hydrateEnvFromDotenvLocal(projectRoot: string): void {\n const envFile = join(projectRoot, '.env.local');\n if (!existsSync(envFile)) return;\n const raw = readFileSync(envFile, 'utf-8');\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq <= 0) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n // Strip a single surrounding quote pair if present.\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n}\n\n// Use manifestPath() from manifest-io so the import isn't tree-shaken\n// for unused-import lint without an actual call.\nvoid manifestPath;\n","/**\n * `dashwise module query-log` — read the per-module SDK query log.\n *\n * Hits `GET /api/modules/:moduleId/query-log?since=...&slow=...&limit=...`\n * (added in dashwise-backend Phase 6 slice 6.4). Workspace-member-\n * scoped on the server side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * Module resolution order:\n * 1. `--module <id-or-slug>` if provided\n * 2. `module.json#module.slug` in the current directory if present\n * 3. Otherwise fail with a \"which module?\" message\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (the last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll, so very busy\n * modules may see \"(more entries above)\" between polls if log\n * volume exceeds 500/5s.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readManifestOrThrow } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleQueryLogOptions {\n /**\n * Module to read the log for. Accepts a numeric id (`123`) or a\n * slug (`my-module`). If omitted, falls back to the slug in the\n * current directory's `module.json`.\n */\n module?: string;\n /**\n * Filter to slow queries only (duration_ms > 500 — matches the\n * SDK/backend slow-query threshold).\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n * Passed through to the backend's validator.\n */\n since?: string;\n /**\n * Max rows to fetch per call. Default 50; backend caps at 500.\n */\n limit?: number;\n /**\n * Poll for new entries every 5s. Stops on Ctrl-C. Mutually\n * exclusive with `--json` (tail mode prints the table format\n * incrementally).\n */\n tail?: boolean;\n /**\n * Emit compact JSON instead of the table. Useful for piping into\n * `jq` / scripting. Ignored when `--tail` is set.\n */\n json?: boolean;\n /**\n * Override project directory (for `module.json` slug lookup).\n * Defaults to `process.cwd()`. Only consulted when `--module` is\n * absent.\n */\n dir?: string;\n}\n\ninterface QueryLogRow {\n id: string;\n request_id: string;\n installation_id: number;\n module_id: number;\n endpoint: 'query' | 'explain';\n ast_hash: string | null;\n duration_ms: number;\n row_count: number | null;\n error_code: string | null;\n error_message: string | null;\n created_at: string;\n}\n\ninterface QueryLogResponse {\n entries: QueryLogRow[];\n count: number;\n}\n\ninterface ModuleByIdResponse {\n id: number;\n slug: string;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleQueryLogCommand(\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Resolve the moduleId. The user can pass `--module <id-or-slug>`\n // or we infer from the current directory's manifest.\n let moduleId: number;\n try {\n moduleId = await resolveModuleId(options.module, options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n if (options.tail) {\n return runTail(moduleId, options);\n }\n return runOnce(moduleId, options);\n}\n\n// ── One-shot mode (default) ──────────────────────────────────────\n\nasync function runOnce(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n const params: Record<string, string> = {};\n if (options.slow) params.slow = 'true';\n if (options.since) params.since = options.since;\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n const qs = new URLSearchParams(params).toString();\n const path = `/api/modules/${moduleId}/query-log${qs ? `?${qs}` : ''}`;\n\n let body: QueryLogResponse;\n try {\n body = await apiRequest<QueryLogResponse>('GET', path);\n } catch (err) {\n return handleApiError(err);\n }\n\n if (options.json) {\n out(JSON.stringify(body));\n return 0;\n }\n\n if (body.entries.length === 0) {\n info(\n options.slow\n ? 'No slow queries in the requested window.'\n : 'No query log entries in the requested window.',\n );\n return 0;\n }\n\n renderTable(body.entries);\n out('');\n info(`${body.count} ${body.count === 1 ? 'entry' : 'entries'}.`);\n return 0;\n}\n\n// ── --tail mode ──────────────────────────────────────────────────\n\nasync function runTail(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Initial fetch — use whatever filters the user passed plus a\n // reasonable starting window if `--since` wasn't set.\n const initialParams: Record<string, string> = {};\n if (options.slow) initialParams.slow = 'true';\n initialParams.since = options.since ?? '5m';\n if (typeof options.limit === 'number') initialParams.limit = String(options.limit);\n const initialQs = new URLSearchParams(initialParams).toString();\n\n info(`Tailing query log for module ${moduleId}. Ctrl-C to stop.`);\n out('');\n\n // Track the most-recent created_at across polls so we can fetch\n // strictly-new rows. The backend's `since` param does a NOW()-based\n // window, so we use a small overlap (2s) to ensure we don't miss\n // entries whose created_at lands between poll cycles. De-dup by\n // request_id locally to suppress overlap repeats.\n const seenIds = new Set<string>();\n let firstPoll = true;\n\n // Print headers once up front; subsequent polls append rows without\n // re-printing.\n printTableHeader();\n\n // Initial poll uses the user-specified since; subsequent polls use\n // a fixed 7s window (5s poll interval + 2s overlap).\n while (true) {\n try {\n const path = `/api/modules/${moduleId}/query-log?${firstPoll ? initialQs : buildTailParams(options)}`;\n const body = await apiRequest<QueryLogResponse>('GET', path);\n\n // Print rows in chronological order (response is DESC, reverse\n // for the tail's natural \"latest at bottom\" reading order).\n const newRows: QueryLogRow[] = [];\n for (const row of [...body.entries].reverse()) {\n if (seenIds.has(row.request_id)) continue;\n seenIds.add(row.request_id);\n newRows.push(row);\n }\n for (const row of newRows) {\n out(formatRow(row));\n }\n firstPoll = false;\n } catch (err) {\n // Don't crash the tail on transient errors — log + continue.\n info(dim(`(tail poll error: ${(err as Error).message})`));\n }\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nfunction buildTailParams(options: ModuleQueryLogOptions): string {\n const params: Record<string, string> = { since: '7s' };\n if (options.slow) params.slow = 'true';\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n return new URLSearchParams(params).toString();\n}\n\n// ── Module-id resolution ─────────────────────────────────────────\n\nasync function resolveModuleId(\n moduleArg: string | undefined,\n dir: string | undefined,\n): Promise<number> {\n // 1. Explicit --module: numeric → use as-is; slug → lookup.\n if (moduleArg && moduleArg.length > 0) {\n const asInt = Number.parseInt(moduleArg, 10);\n if (Number.isFinite(asInt) && String(asInt) === moduleArg) {\n return asInt;\n }\n return lookupModuleIdBySlug(moduleArg);\n }\n // 2. Fall back to module.json in the project directory.\n const projectRoot = dir ?? process.cwd();\n try {\n const manifest = readManifestOrThrow(projectRoot);\n if (manifest?.module?.slug) {\n return lookupModuleIdBySlug(manifest.module.slug);\n }\n } catch {\n // Manifest absent or malformed — fall through to the error below.\n }\n throw new Error(\n `No module specified. Pass --module <id-or-slug> or run inside a module project directory containing module.json.`,\n );\n}\n\nasync function lookupModuleIdBySlug(slug: string): Promise<number> {\n const found = await apiRequest<ModuleByIdResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n if (!found || typeof found.id !== 'number') {\n throw new Error(`Module ${code(slug)} not found.`);\n }\n return found.id;\n}\n\n// ── Error handling ───────────────────────────────────────────────\n\nfunction handleApiError(err: unknown): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err.status === 403) {\n fail(\n `Forbidden — you are not a member of this module's owner workspace. ` +\n `Use \\`dashwise workspace list\\` to see what you have access to.`,\n );\n return 1;\n }\n if (err.status === 404) {\n fail(`Module not found.`);\n return 1;\n }\n }\n fail(`Could not load query log: ${(err as Error).message}`);\n return 1;\n}\n\n// ── Table rendering ──────────────────────────────────────────────\n\n/**\n * Column widths chosen to fit a typical 80-col terminal plus a\n * little slack. ID is the bigint serialized as string (up to ~19\n * digits); we show only the last 8 for compactness — the request_id\n * is the real trace anchor anyway.\n */\nconst COL_WIDTHS = {\n time: 19, // \"YYYY-MM-DD HH:MM:SS\"\n endpoint: 7, // \"query\" | \"explain\"\n ms: 6, // \"12345\" with margin\n rows: 5,\n code: 18,\n request: 12, // first 12 chars of request_id (most are UUIDs)\n};\n\nfunction renderTable(entries: QueryLogRow[]): void {\n out('');\n printTableHeader();\n // Server returns DESC (newest first) — preserve that for one-shot\n // mode so the most-recent activity is at the top of the screen.\n for (const row of entries) {\n out(formatRow(row));\n }\n}\n\nfunction printTableHeader(): void {\n out(\n [\n 'TIME'.padEnd(COL_WIDTHS.time),\n 'ENDPT'.padEnd(COL_WIDTHS.endpoint),\n 'MS'.padStart(COL_WIDTHS.ms),\n 'ROWS'.padStart(COL_WIDTHS.rows),\n 'CODE'.padEnd(COL_WIDTHS.code),\n 'REQ',\n ].join(' '),\n );\n out(\n [\n '-'.repeat(COL_WIDTHS.time),\n '-'.repeat(COL_WIDTHS.endpoint),\n '-'.repeat(COL_WIDTHS.ms),\n '-'.repeat(COL_WIDTHS.rows),\n '-'.repeat(COL_WIDTHS.code),\n '-'.repeat(COL_WIDTHS.request),\n ].join(' '),\n );\n}\n\nfunction formatRow(row: QueryLogRow): string {\n const time = formatTimestamp(row.created_at);\n const endpoint = row.endpoint.padEnd(COL_WIDTHS.endpoint);\n const ms = String(row.duration_ms).padStart(COL_WIDTHS.ms);\n const rows =\n row.row_count === null ? '—'.padStart(COL_WIDTHS.rows) : String(row.row_count).padStart(COL_WIDTHS.rows);\n const errCode = row.error_code ?? '';\n const codeCol = errCode\n ? code(errCode).padEnd(COL_WIDTHS.code + (code(errCode).length - errCode.length))\n : 'OK'.padEnd(COL_WIDTHS.code);\n const req = row.request_id.slice(0, COL_WIDTHS.request);\n return [time, endpoint, ms, rows, codeCol, dim(req)].join(' ');\n}\n\nfunction formatTimestamp(iso: string): string {\n // YYYY-MM-DD HH:MM:SS for compact display; preserves UTC if the\n // input is Z-suffixed. We deliberately don't convert to local TZ\n // here so log entries are reproducible across consumers in\n // different timezones.\n return iso.slice(0, 19).replace('T', ' ');\n}\n\n// ── Misc ─────────────────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * `dashwise module action-log` — read the per-installation server-action\n * audit log (cross-module + own-module dispatches).\n *\n * Hits `GET /api/modules/runtime/installations/:installationId/action-log`\n * (added in dashwise-backend Phase 7 slice 7.5a). Workspace-member-scoped\n * server-side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * **Why per-installation, not per-module**: cross-module dispatches are\n * events between TWO installations. The audit row keys by\n * installation id (not module id). The CLI surfaces either side\n * (`--role caller` for outbound; `--role provider` for inbound) so\n * authors can debug both directions from the same command.\n *\n * The user provides `--installation <id>` directly. A `--module <slug>`\n * convenience that resolves to the user's default-workspace\n * installation is a planned follow-up; it needs a new backend\n * \"list-installations-by-module-in-workspace\" endpoint.\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleActionLogOptions {\n /**\n * Installation to read the log for (numeric id). Mutually exclusive\n * with `module` — exactly one must be set. (Validated by the CLI\n * binder; the action handler treats both as optional + checks.)\n */\n installation?: number;\n /**\n * Module slug — resolves to the caller's accessible installation\n * via `GET /api/modules/by-slug/:slug/my-installation`. Convenience\n * for the common case where the user has one workspace's\n * installation; multi-workspace authors should use `--installation`\n * with an explicit id (or `dashwise workspace use <slug>` to fix\n * the default).\n */\n module?: string;\n /**\n * Which side of cross-module dispatches to query.\n * - `caller` (default) → outbound actions THIS installation invoked\n * - `provider` → inbound actions OTHER modules invoked on THIS installation\n */\n role?: 'caller' | 'provider';\n /**\n * Filter to slow actions only (elapsed_ms > 500 — matches the\n * SDK/backend slow threshold). Uses the partial slow-action index.\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n */\n since?: string;\n /** Filter to cross-module dispatches only (cross_module=true rows). */\n crossModuleOnly?: boolean;\n /** Max rows per call. Default 50; backend caps at 500. */\n limit?: number;\n /**\n * Poll every 5s for new entries. Stops on Ctrl-C. Mutually exclusive\n * with `--json` (tail mode prints incrementally as rows arrive).\n */\n tail?: boolean;\n /** Compact JSON instead of the table. Ignored when `--tail` is set. */\n json?: boolean;\n}\n\ninterface ActionLogRow {\n id: string;\n request_id: string;\n caller_installation_id: number;\n caller_module_slug: string;\n caller_user_id: number | null;\n provider_installation_id: number;\n provider_module_slug: string;\n action_name: string;\n input_hash: string;\n output_hash: string | null;\n ok: boolean;\n error_code: string | null;\n elapsed_ms: number;\n cross_module: boolean;\n created_at: string;\n}\n\ninterface ActionLogResponse {\n entries: ActionLogRow[];\n count: number;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleActionLogCommand(\n options: ModuleActionLogOptions,\n): Promise<number> {\n // Validate mutually-exclusive scope flags.\n if (options.installation === undefined && options.module === undefined) {\n fail('Must pass either `--installation <id>` or `--module <slug>`.');\n return 1;\n }\n if (options.installation !== undefined && options.module !== undefined) {\n fail('`--installation` and `--module` are mutually exclusive — pass one or the other.');\n return 1;\n }\n\n // If --module was passed, resolve to an installation id.\n let installationId = options.installation;\n if (installationId === undefined && options.module !== undefined) {\n try {\n const resolved = await apiRequest<{ installation_id: number; module_slug: string }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(options.module)}/my-installation`,\n );\n installationId = resolved.installation_id;\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n }\n if (options.tail) {\n return runTail(installationId as number, options);\n }\n return runOnce(installationId as number, options);\n}\n\n// ── One-shot mode ────────────────────────────────────────────────\n\nasync function runOnce(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (options.since !== undefined) params.since = options.since;\n if (options.limit !== undefined) params.limit = String(options.limit);\n\n let response: ActionLogResponse;\n try {\n response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n\n if (options.json) {\n out(JSON.stringify(response));\n return 0;\n }\n\n printTable(response.entries);\n if (response.entries.length === 0) {\n info('No entries.');\n }\n return 0;\n}\n\n// ── Tail mode ────────────────────────────────────────────────────\n\nasync function runTail(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n if (options.json) {\n fail('`--tail` and `--json` are mutually exclusive.');\n return 1;\n }\n info(`Tailing action log for installation ${code(String(installationId))} every 5s. Ctrl-C to stop.`);\n\n let lastSeen: string | undefined;\n const printed = new Set<string>();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (lastSeen !== undefined) params.since = lastSeen;\n else if (options.since !== undefined) params.since = options.since;\n params.limit = String(options.limit ?? 100);\n\n try {\n const response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n // Backend returns rows newest-first; we want oldest-first when\n // tailing so the user reads down the page. Reverse + dedup by id.\n const fresh = response.entries.filter((e) => !printed.has(e.id)).reverse();\n if (fresh.length > 0) {\n for (const entry of fresh) {\n printed.add(entry.id);\n printRow(entry);\n }\n // Update since-anchor to the newest row we just printed.\n lastSeen = fresh[fresh.length - 1].created_at;\n }\n } catch (err) {\n // Tail mode swallows transient errors + keeps polling. Fatal\n // (401/403) drops out so the user knows to re-login.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n return mapAndPrintError(err, false);\n }\n dim(`(tail: transient error — ${(err as Error).message})`);\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n}\n\n// ── Output ───────────────────────────────────────────────────────\n\nfunction printTable(rows: ActionLogRow[]): void {\n if (rows.length === 0) {\n out('');\n out(' (no entries)');\n out('');\n return;\n }\n const widths = {\n time: 19,\n elapsed: 5,\n cross: 5,\n caller: 18,\n action: 22,\n code: 18,\n };\n out('');\n out(\n `${'TIME'.padEnd(widths.time)} ${'MS'.padStart(widths.elapsed)} ${'CROSS'.padEnd(widths.cross)} ${'CALLER'.padEnd(widths.caller)} ${'ACTION'.padEnd(widths.action)} ${'CODE'.padEnd(widths.code)}`,\n );\n out(\n `${'-'.repeat(widths.time)} ${'-'.repeat(widths.elapsed)} ${'-'.repeat(widths.cross)} ${'-'.repeat(widths.caller)} ${'-'.repeat(widths.action)} ${'-'.repeat(widths.code)}`,\n );\n for (const r of rows) {\n printRow(r);\n }\n out('');\n info(`${rows.length} entr${rows.length === 1 ? 'y' : 'ies'}.`);\n}\n\nfunction printRow(r: ActionLogRow): void {\n const time = r.created_at.slice(0, 19).replace('T', ' ');\n const cross = r.cross_module ? code('yes') : dim(' no');\n const codeCol = r.ok ? dim('-') : code(r.error_code ?? 'ERROR');\n out(\n `${time.padEnd(19)} ${String(r.elapsed_ms).padStart(5)} ${cross.padEnd(5)} ${r.caller_module_slug.padEnd(18)} ${r.action_name.padEnd(22)} ${codeCol}`,\n );\n}\n\nfunction mapAndPrintError(err: unknown, json: boolean | undefined): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n const msg = 'Not logged in. Run `dashwise login` first.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 403) {\n const msg = 'Workspace-member access required for this installation.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FORBIDDEN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 404) {\n const msg = 'Installation not found.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'INSTALLATION_NOT_FOUND', message: msg } }));\n else fail(msg);\n return 1;\n }\n }\n const msg = `Could not fetch action log: ${(err as Error).message}`;\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n else fail(msg);\n return 1;\n}\n"]}
1
+ {"version":3,"sources":["../src/lib/config.ts","../src/lib/api-client.ts","../src/lib/manifest-io.ts","../src/lib/output.ts","../src/lib/scaffold.ts","../src/lib/workspaces.ts","../src/commands/module/init.ts","../src/commands/module/destroy-dev-install.ts","../src/commands/module/reset-dev-install.ts","../src/lib/schema-command-context.ts","../src/lib/field-spec.ts","../src/commands/table/create.ts","../src/commands/table/delete.ts","../src/commands/field/add.ts","../src/commands/field/remove.ts","../src/commands/field/set-type.ts","../src/commands/dev.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/profile.ts","../src/commands/workspace.ts","../src/commands/module/clone.ts","../src/commands/module/connect-git.ts","../src/commands/module/generate.ts","../src/commands/module/dev.ts","../src/commands/module/diff.ts","../src/bin.ts","../src/commands/module/list.ts","../src/commands/module/publish.ts","../src/lib/tarball.ts","../src/commands/module/pull-data.ts","../src/commands/module/validate.ts","../src/commands/deps/add.ts","../src/commands/deps/check.ts","../src/commands/deps/list.ts","../src/commands/deps/remove.ts","../src/commands/query.ts","../src/commands/module/query-log.ts","../src/commands/module/action-log.ts"],"names":["c","out","code","join","existsSync","readFileSync","writeFileSync","select","isCancel","intro","resolve","readdirSync","mkdirSync","outro","workspace","resolvePath","manifestPath","exitCode","text","rmSync","fsWatch","statSync","formatBytes","pathResolve","sleep","POLL_INTERVAL_MS","runTail","runOnce","msg","destroyDevInstallCommand","resetDevInstallCommand","tableCreateCommand","tableDeleteCommand","fieldAddCommand","fieldRemoveCommand","fieldSetTypeCommand"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+FO,SAAS,SAAA,GAAoB;AAClC,EAAA,IAAI,OAAA,CAAQ,IAAI,eAAA,EAAiB;AAC/B,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,eAAA,EAAiB,QAAQ,CAAA;AAAA,EACnD;AACA,EAAA,IAAI,QAAA,EAAS,KAAM,OAAA,IAAW,OAAA,CAAQ,IAAI,OAAA,EAAS;AACjD,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,OAAA,EAAS,QAAQ,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,IAAA,CAAK,OAAA,EAAQ,EAAG,SAAA,EAAW,QAAQ,CAAA;AAC5C;AAEO,SAAS,UAAA,GAAqB;AACnC,EAAA,OAAO,IAAA,CAAK,SAAA,EAAU,EAAG,SAAS,CAAA;AACpC;AAOO,SAAS,UAAA,GAA+B;AAC7C,EAAA,MAAM,OAAO,UAAA,EAAW;AACxB,EAAA,IAAI,CAAC,UAAA,CAAW,IAAI,CAAA,EAAG,OAAO,IAAA;AAC9B,EAAA,MAAM,GAAA,GAAM,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACtC,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,GAAG,CAAA;AAAA,EACzB,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gBAAA,EAAmB,IAAI,CAAA,EAAA,EAAM,GAAA,CAAc,OAAO,CAAA,wCAAA;AAAA,KACpD;AAAA,EACF;AACA,EAAA,IAAI,CAAC,iBAAA,CAAkB,MAAM,CAAA,EAAG;AAC9B,IAAA,MAAM,I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,cAAA,EAAgB;AAI9B,MAAA,OAAA,CAAQ,MAAM,GAAG,CAAA;AAAA,IACnB;AACA,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA,GAAG;AAQH,SAAS,UAAA,GAAqB;AAC5B,EAAA,OAAO,OAAA;AACT;AAGA,SAAS,eAAe,KAAA,EAAuB;AAC7C,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,QAAA,CAAS,KAAA,EAAO,EAAE,CAAA;AACnC,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,KAAK,CAAA,CAAA,CAAG,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,CAAA;AACT;AAUA,SAAS,eAAA,CAAgB,OAAe,QAAA,EAA8B;AACpE,EAAA,OAAO,CAAC,GAAG,QAAA,EAAU,KAAK,CAAA;AAC5B","file":"bin.js","sourcesContent":["/**\n * Local CLI configuration — persisted to\n * `$XDG_CONFIG_HOME/dashwise/auth.json` (defaults to\n * `~/.config/dashwise/auth.json` on Linux/macOS and the equivalent\n * `%APPDATA%\\dashwise\\auth.json` on Windows).\n *\n * Contents:\n * - `apiUrl` — backend root, e.g. `http://localhost:3000`\n * - `token` — raw `dwc_*` CLI token (the secret)\n * - `tokenId` — DB id of the `cli_tokens` row (so `dashwise\n * logout` can call DELETE precisely)\n * - `user` — cached profile for fast `dashwise profile`\n * (refreshed on `dashwise login` + on demand)\n * - `workspaceSlug` — default workspace selected via\n * `dashwise workspace use <slug>`\n *\n * Permissions: chmod 0600 on write — the file holds a long-lived\n * bearer credential. Best-effort on Windows (the API tolerates\n * `EPERM` on the chmod call there).\n */\n\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface CliConfig {\n /** Backend base URL — e.g. `http://localhost:3000`. */\n apiUrl: string;\n /** Raw CLI token (`dwc_<...>`). */\n token: string;\n /** DB id of the matching `cli_tokens` row. Used by `logout`. */\n tokenId: number;\n /** Cached user identity. */\n user: {\n id: number;\n email: string;\n username: string;\n firstName: string;\n lastName: string;\n };\n /** Optional default workspace slug. */\n workspaceSlug?: string;\n /**\n * HH-CC-LDI-6 — per-module local-dev install metadata, keyed by\n * the module's slug (matches `module.json#module.slug`).\n *\n * Written by `dashwise init` after `POST /api/installations/dev`\n * returns a runtime token. Read by `@dashai/sdk`'s\n * `createDevClient({ moduleSlug })` to authenticate against the\n * local-dev install. Each entry is independent — entries for\n * other modules survive any single module's destroy / re-init.\n *\n * Field semantics:\n * - `runtimeToken` — JWT bearer the SDK sends on every data\n * request. Long-lived (default 90d). Replaced on rotation\n * (LDI-9 `dashwise module rotate-token`).\n * - `installationId` — numeric install id the token binds to.\n * Useful for surfacing to the user in `dashwise module status`\n * output and for the future LDI-9 destroy command.\n * - `expiresAt` — ISO timestamp; informational only. The CLI\n * can warn when the token is nearing expiry, but expiry is\n * enforced server-side via the JWT's `exp` claim.\n */\n modules?: Record<string, CliConfigModuleEntry>;\n}\n\n/** Per-module entry within `CliConfig.modules`. See `modules` field above. */\nexport interface CliConfigModuleEntry {\n runtimeToken: string;\n installationId: number;\n expiresAt: string;\n}\n\nconst FILE_NAME = 'auth.json';\nconst DIR_NAME = 'dashwise';\n\n/**\n * Resolve the config directory using XDG conventions.\n *\n * 1. `$XDG_CONFIG_HOME/dashwise/` if set\n * 2. `~/.config/dashwise/` on Linux/macOS\n * 3. `%APPDATA%\\dashwise\\` on Windows (via env)\n *\n * Mirrors `dashwise` projects on common platforms; matches what\n * users would expect from other CLIs (gh, npm, etc.).\n */\nexport function configDir(): string {\n if (process.env.XDG_CONFIG_HOME) {\n return join(process.env.XDG_CONFIG_HOME, DIR_NAME);\n }\n if (platform() === 'win32' && process.env.APPDATA) {\n return join(process.env.APPDATA, DIR_NAME);\n }\n return join(homedir(), '.config', DIR_NAME);\n}\n\nexport function configPath(): string {\n return join(configDir(), FILE_NAME);\n}\n\n/**\n * Read the saved config, or `null` if no file exists. Throws if the\n * file exists but is malformed JSON — the caller decides whether to\n * surface as \"run `dashwise login` again\" or as a hard error.\n */\nexport function readConfig(): CliConfig | null {\n const path = configPath();\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n if (!isPlausibleConfig(parsed)) {\n throw new Error(\n `Config at ${path} is missing required fields. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n return parsed;\n}\n\n/**\n * Write the config atomically (via temp + rename) with 0600 perms.\n * Creates the parent dir if missing.\n */\nexport function writeConfig(config: CliConfig): void {\n const dir = configDir();\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const path = configPath();\n const tmp = `${path}.tmp.${process.pid}`;\n writeFileSync(tmp, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // Windows + some FUSE FS don't support chmod; best-effort.\n }\n // Atomic rename — readers see either the old config or the new\n // one, never a partial write.\n renameSync(tmp, path);\n}\n\n/**\n * Remove the config file (`dashwise logout`). Idempotent — no error\n * if the file already doesn't exist.\n */\nexport function deleteConfig(): void {\n const path = configPath();\n if (!existsSync(path)) return;\n rmSync(path);\n}\n\n/**\n * Resolve the API URL the CLI should talk to.\n * Priority: explicit `DASHWISE_API_URL` env → saved config → default.\n */\nexport function resolveApiUrl(): string {\n const fromEnv = process.env.DASHWISE_API_URL?.trim();\n if (fromEnv) return fromEnv.replace(/\\/+$/, '');\n const cfg = safeReadConfig();\n if (cfg?.apiUrl) return cfg.apiUrl.replace(/\\/+$/, '');\n return 'http://localhost:3000';\n}\n\n/**\n * Convenience: read the saved token if the file exists + is valid.\n * Returns `null` if the user isn't logged in.\n */\nexport function readSavedToken(): string | null {\n const cfg = safeReadConfig();\n return cfg?.token ?? null;\n}\n\nfunction safeReadConfig(): CliConfig | null {\n try {\n return readConfig();\n } catch {\n return null;\n }\n}\n\nfunction isPlausibleConfig(v: unknown): v is CliConfig {\n if (!v || typeof v !== 'object') return false;\n const c = v as Record<string, unknown>;\n if (typeof c.apiUrl !== 'string') return false;\n if (typeof c.token !== 'string') return false;\n if (typeof c.tokenId !== 'number') return false;\n if (!c.user || typeof c.user !== 'object') return false;\n const u = c.user as Record<string, unknown>;\n if (typeof u.id !== 'number') return false;\n if (typeof u.email !== 'string') return false;\n // HH-CC-LDI-6: `modules` is optional and forgiving — entries with\n // wrong shape are silently ignored at read time, mirroring the\n // SDK's reader. Strict per-entry validation would force CLI\n // crashes on partial writes (e.g. interrupt mid-init).\n if (c.modules !== undefined) {\n if (typeof c.modules !== 'object' || c.modules === null) return false;\n }\n return true;\n}\n\n/**\n * HH-CC-LDI-6 — record a module's local-dev install in `auth.json`.\n *\n * Atomic: reads, mutates, writes. If `dashwise init` is interrupted\n * after the API call but before this returns, the install row exists\n * server-side without local persistence — the user has to re-init or\n * use the future `dashwise module recover-dev-install` command (LDI-9).\n *\n * Throws if there's no saved config (the user isn't logged in).\n * Callers should check `isLoggedIn()` first and surface a clear\n * \"run `dashwise login` first\" error.\n */\nexport function upsertModuleEntry(\n slug: string,\n entry: CliConfigModuleEntry,\n): void {\n const cfg = readConfig();\n if (!cfg) {\n throw new Error(\n 'No CLI config file. Run `dashwise login` first to create one.',\n );\n }\n const next: CliConfig = {\n ...cfg,\n modules: {\n ...(cfg.modules ?? {}),\n [slug]: entry,\n },\n };\n writeConfig(next);\n}\n\n/**\n * HH-CC-LDI-6 — read a module's local-dev entry, or `null` if none\n * has been provisioned. Returns `null` when the user isn't logged in.\n */\nexport function readModuleEntry(slug: string): CliConfigModuleEntry | null {\n const cfg = safeReadConfig();\n if (!cfg?.modules) return null;\n return cfg.modules[slug] ?? null;\n}\n\n/**\n * HH-CC-LDI-6 — remove a module's entry (used by future LDI-9\n * `dashwise module destroy-dev-install`). Idempotent — no-op when\n * the entry doesn't exist or the user isn't logged in.\n */\nexport function removeModuleEntry(slug: string): void {\n const cfg = safeReadConfig();\n if (!cfg?.modules || !(slug in cfg.modules)) return;\n const { [slug]: _removed, ...rest } = cfg.modules;\n void _removed;\n const next: CliConfig = {\n ...cfg,\n modules: Object.keys(rest).length > 0 ? rest : undefined,\n };\n writeConfig(next);\n}\n\n/**\n * Return current file mode bits (for diagnostics). Returns `null`\n * on any failure (file missing, permission denied, etc.).\n */\nexport function configFileMode(): number | null {\n try {\n const s = statSync(configPath());\n return s.mode & 0o777;\n } catch {\n return null;\n }\n}\n\n/** Confirm a saved config exists (for `whoami` short-circuit). */\nexport function isLoggedIn(): boolean {\n return readSavedToken() !== null;\n}\n\n/** Convenience helper used by tests + diagnostic commands. */\nexport function configSummary(): {\n path: string;\n exists: boolean;\n mode: number | null;\n} {\n return {\n path: configPath(),\n exists: existsSync(configPath()),\n mode: configFileMode(),\n };\n}\n\n// Helpers above intentionally exported individually — no default\n// export so tree-shake at the `bin.ts` level remains effective.\n","/**\n * Thin HTTP client for the DashWise backend, tailored for the CLI's\n * call patterns.\n *\n * Three shapes of authenticated request emerge in the CLI:\n * 1. **Public** — `dashwise login` device-code start/poll (no token yet)\n * 2. **CLI token (`Bearer dwc_*`)** — every command after login\n * 3. **One-off Bearer** — internal use during the login flow\n * (we don't have a saved token while polling)\n *\n * The class is intentionally small + dependency-free (uses\n * `globalThis.fetch`). Error envelopes from the backend\n * (`{ code, message, retriable, context }`) are surfaced as typed\n * `ApiError`s so command code can branch on `err.code`.\n */\n\nimport { resolveApiUrl, readSavedToken } from './config.js';\n\nexport interface ApiErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly context: Record<string, unknown> | undefined;\n readonly retriable: boolean;\n\n constructor(status: number, envelope: ApiErrorEnvelope | null, fallbackMessage: string) {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? fallbackMessage;\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.context = envelope?.context;\n this.retriable = envelope?.retriable ?? status >= 500;\n }\n}\n\nexport interface RequestOptions {\n /**\n * Auth mode:\n * - `'auto'` (default) — `Bearer <saved-token>` if one exists,\n * else no header.\n * - `'public'` — no Authorization header (used by the device-code\n * endpoints which authenticate via the device_code itself).\n * - `{ token: 'dwc_...' }` — explicit token (used during login\n * polling before we save the file).\n */\n auth?: 'auto' | 'public' | { token: string };\n\n /** Override the base URL (testing / `--api-url` flag). */\n baseUrl?: string;\n\n /** Extra request headers (rare — diagnostic plumbing). */\n headers?: Record<string, string>;\n}\n\n/**\n * Make a JSON request. Returns the parsed body (`T`) or throws an\n * `ApiError`. 204 responses return `undefined`.\n */\nexport async function apiRequest<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n): Promise<T> {\n const baseUrl = (options.baseUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.headers ?? {}),\n };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n const authMode = options.auth ?? 'auto';\n if (authMode === 'auto') {\n const saved = readSavedToken();\n if (saved) headers['Authorization'] = `Bearer ${saved}`;\n } else if (typeof authMode === 'object' && authMode.token) {\n headers['Authorization'] = `Bearer ${authMode.token}`;\n }\n\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n // Network-level failure — DNS, ECONNREFUSED, TLS, etc. Surface\n // as an ApiError with a stable code so callers can branch.\n throw new ApiError(0, { code: 'NETWORK_ERROR', message: (err as Error).message }, 'Network error');\n }\n\n if (res.status === 204) {\n return undefined as T;\n }\n\n const contentType = res.headers.get('content-type') ?? '';\n let parsed: unknown = null;\n if (contentType.includes('application/json')) {\n try {\n parsed = await res.json();\n } catch {\n parsed = null;\n }\n } else if (res.status >= 400) {\n // Non-JSON error body — still want a stable error shape.\n try {\n parsed = { message: await res.text() };\n } catch {\n parsed = null;\n }\n }\n\n if (!res.ok) {\n throw new ApiError(res.status, asEnvelope(parsed), `HTTP ${res.status}`);\n }\n return parsed as T;\n}\n\nfunction asEnvelope(v: unknown): ApiErrorEnvelope | null {\n if (!v || typeof v !== 'object') return null;\n const env = v as Record<string, unknown>;\n const out: ApiErrorEnvelope = {};\n if (typeof env.code === 'string') out.code = env.code;\n if (typeof env.message === 'string') out.message = env.message;\n if (typeof env.retriable === 'boolean') out.retriable = env.retriable;\n if (env.context && typeof env.context === 'object') {\n out.context = env.context as Record<string, unknown>;\n }\n return out;\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return 'UNAUTHENTICATED';\n if (status === 403) return 'FORBIDDEN';\n if (status === 404) return 'NOT_FOUND';\n if (status === 0) return 'NETWORK_ERROR';\n if (status >= 500) return 'INTERNAL_ERROR';\n return 'HTTP_ERROR';\n}\n\n// ── HH-CC-LDI-6: typed wrapper for POST /api/installations/dev ────────\n\n/**\n * Shape returned by `POST /api/installations/dev` — matches the\n * backend's `DevInstallationController.createDevInstallation` envelope.\n * See `dashwise-backend/src/modules/modules/installation/dev-installation.controller.ts`.\n */\nexport interface DevInstallationResponse {\n installation: {\n id: number;\n kind: 'sandbox' | 'local' | 'production';\n workspace_id: number;\n module_id: number;\n module_version_id: number;\n application_id: number;\n installed_on: string;\n };\n module: {\n id: number;\n slug: string;\n name: string;\n };\n runtime_token: string;\n runtime_token_expires_at: string;\n}\n\n/**\n * Create a local-dev module installation + mint a runtime token.\n *\n * Called by `dashwise init` after the user picks a workspace + slug\n * + name. The returned `runtime_token` is persisted into\n * `auth.json#modules[<slug>]` via `upsertModuleEntry`; the SDK's\n * `createDevClient({ moduleSlug })` reads from there on every dev\n * server boot.\n *\n * Errors (surfaced as `ApiError` with the backend's `code` field):\n * - 403 — caller is not a member of the target workspace.\n * - 409 SLUG_ALREADY_EXISTS — a module with this slug exists. The\n * user should pick a different slug or run `dashwise module\n * destroy-dev-install` first (LDI-9).\n * - 503 RUNTIME_DATA_API_DISABLED — `BUILDER_SESSION_TOKEN_SECRET`\n * unset on the backend. Operator-side issue, not a user issue.\n */\nexport async function createDevInstallation(\n body: {\n slug: string;\n name: string;\n description?: string;\n workspaceId: number;\n /**\n * HH-CC-FUP-2 — `module_kind` from the scaffold's `module.json`.\n * Without forwarding it the backend's draft manifest gets no\n * `module_kind`, `SchemaProposeService.getManifest()` falls back\n * to `'ai_builder'`, and that wrong value rewrites the local\n * module.json on the first watcher tick.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n },\n options: RequestOptions = {},\n): Promise<DevInstallationResponse> {\n return apiRequest<DevInstallationResponse>(\n 'POST',\n '/api/installations/dev',\n body,\n options,\n );\n}\n\n/**\n * HH-CC-LDI-9 — destroy a local-dev installation.\n *\n * Maps to `DELETE /api/installations/dev/:installationId`. The\n * backend (`DevInstallationService.destroy`) tears down the install\n * row + its application tile, and conditionally drops the module\n * if it was a dev-only artifact (no other installs, never published).\n *\n * Returns `{ installation_id, module_id, module_also_dropped }`.\n *\n * Errors (`ApiError`):\n * - 404 `INSTALLATION_NOT_FOUND` — install id doesn't exist.\n * - 403 `INSTALLATION_KIND_NOT_LOCAL` — refuses non-local installs.\n * - 403 `NOT_WORKSPACE_MEMBER` — caller isn't in the install's workspace.\n */\nexport interface DestroyDevInstallationResponse {\n installation_id: number;\n module_id: number;\n module_also_dropped: boolean;\n}\n\nexport async function destroyDevInstallation(\n installationId: number,\n options: RequestOptions = {},\n): Promise<DestroyDevInstallationResponse> {\n return apiRequest<DestroyDevInstallationResponse>(\n 'DELETE',\n `/api/installations/dev/${installationId}`,\n undefined,\n options,\n );\n}\n\n// ── HH-CC-LDI-8: schema-mutation endpoints (mirrors LDI-4 controller) ──\n\n/** FieldDef body shape — open enough to carry `options`, `target`, etc. */\nexport interface FieldDefBody {\n slug: string;\n type: string;\n required?: boolean;\n options?: string[];\n target?: string;\n default?: unknown;\n}\n\n/**\n * Common response shape from `propose_*` endpoints — the LDI-4\n * controller strips the in-memory `sdk` blob, so the wire payload is\n * just the operation result + sdk_regen metadata.\n */\nexport interface SchemaOpResponse {\n table_slug: string;\n physical_table_id: number;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n /** Present on proposeField responses (add / update / remove). */\n operation_applied?: 'add' | 'update' | 'remove';\n}\n\nexport interface DropTableResponse {\n table_slug: string;\n dropped: boolean;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n}\n\n/** `POST /api/installations/:id/schema/tables` — create a table. */\nexport async function createTable(\n installationId: number,\n body: {\n slug: string;\n fields: FieldDefBody[];\n indexes?: Array<{ fields: string[]; unique?: boolean }>;\n },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/installations/${installationId}/schema/tables`,\n body,\n options,\n );\n}\n\n/** `DELETE /api/installations/:id/schema/tables/:tableSlug` — drop a table. */\nexport async function dropTable(\n installationId: number,\n tableSlug: string,\n options: RequestOptions = {},\n): Promise<DropTableResponse> {\n return apiRequest<DropTableResponse>(\n 'DELETE',\n `/api/installations/${installationId}/schema/tables/${tableSlug}`,\n undefined,\n options,\n );\n}\n\n/** `POST /api/installations/:id/schema/fields` — add a field. */\nexport async function addField(\n installationId: number,\n body: { table_slug: string; field: FieldDefBody },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/installations/${installationId}/schema/fields`,\n body,\n options,\n );\n}\n\n/** `PATCH /api/installations/:id/schema/fields/:tableSlug/:fieldSlug` — update. */\nexport async function updateField(\n installationId: number,\n tableSlug: string,\n fieldSlug: string,\n body: Omit<FieldDefBody, 'slug'>,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'PATCH',\n `/api/installations/${installationId}/schema/fields/${tableSlug}/${fieldSlug}`,\n body,\n options,\n );\n}\n\n/**\n * `GET /api/installations/:id/schema` — read the current draft\n * manifest. Used post-mutation to write the new state back to local\n * `module.json` (HH-CC-LDI-8 REST-first / write-back-from-GET model).\n */\nexport async function getInstallationSchema(\n installationId: number,\n options: RequestOptions = {},\n): Promise<{ manifest: Record<string, unknown> }> {\n return apiRequest<{ manifest: Record<string, unknown> }>(\n 'GET',\n `/api/installations/${installationId}/schema`,\n undefined,\n options,\n );\n}\n\n/** `DELETE /api/installations/:id/schema/fields/:tableSlug/:fieldSlug` — remove. */\nexport async function removeField(\n installationId: number,\n tableSlug: string,\n fieldSlug: string,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'DELETE',\n `/api/installations/${installationId}/schema/fields/${tableSlug}/${fieldSlug}`,\n undefined,\n options,\n );\n}\n","/**\n * Shared `module.json` I/O for CLI commands.\n *\n * Several commands need to read + mutate the local manifest\n * (`connect-git`, `deps add / remove`, future `module fields add`,\n * etc.). Inlining the read/write/JSON-parse dance in every command\n * leaks formatting choices (2-space indent, trailing newline) and\n * makes file-level invariants harder to enforce. This helper is the\n * single chokepoint.\n *\n * Properties:\n * - Tolerates an absent file with a typed null return.\n * - Throws a typed error (with file path) on parse failure.\n * - Writes are atomic-ish: same write pattern as the rest of the\n * CLI (one `writeFileSync`, no temp file — manifest is small +\n * local; partial writes only matter for ~256-byte regions and\n * fsync ordering on local disk).\n * - Preserves 2-space indent + trailing newline so `git diff` after\n * a CLI mutation shows only the actual change.\n * - Generic over the manifest shape — callers cast to their needed\n * shape since the manifest schema is owned by the backend.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Reasonably-permissive shape covering what CLI commands care about.\n * The backend validator owns the full schema; we only narrow what we\n * need to read/write here.\n */\nexport interface ManifestShape {\n schema_version?: number;\n module?: {\n slug?: string;\n name?: string;\n version?: string;\n [k: string]: unknown;\n };\n module_kind?: string;\n owns?: { tables?: Array<{ slug?: string; [k: string]: unknown }> };\n dependencies?: ManifestDependency[];\n exposes?: Array<Record<string, unknown>>;\n repository?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ManifestDependency {\n module: string;\n version: string;\n reads: Array<{ table: string; fields: string[] }>;\n writes?: Array<{ table: string; fields: string[]; operations: string[] }>;\n purpose: string;\n}\n\n/**\n * Resolve the manifest path inside `dir` (defaults to `process.cwd()`).\n * Pure path math — does not touch the filesystem.\n */\nexport function manifestPath(dir?: string): string {\n return join(resolve(dir ?? process.cwd()), 'module.json');\n}\n\n/**\n * Read + parse `module.json` from `dir`. Returns `null` when the file\n * doesn't exist (so callers can branch on \"not a module directory\" vs\n * \"broken manifest\"). Throws with a clear message on parse failure.\n */\nexport function readManifest<T extends ManifestShape = ManifestShape>(dir?: string): T | null {\n const path = manifestPath(dir);\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n try {\n return JSON.parse(raw) as T;\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Fix or delete the file and re-run.`,\n );\n }\n}\n\n/**\n * Write `manifest` back to `module.json` in `dir`. Uses the canonical\n * 2-space indent + trailing newline so subsequent commits show only\n * the intended diff. Caller is responsible for any structural\n * validation — this helper is a dumb serializer.\n */\nexport function writeManifest(manifest: ManifestShape, dir?: string): void {\n const path = manifestPath(dir);\n writeFileSync(path, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n}\n\n/**\n * Convenience: read the manifest or throw a CLI-friendly error if\n * either the file is missing or unparseable. Use from commands that\n * REQUIRE a manifest to function (most of them).\n */\nexport function readManifestOrThrow<T extends ManifestShape = ManifestShape>(dir?: string): T {\n const manifest = readManifest<T>(dir);\n if (!manifest) {\n throw new Error(\n `No module.json found in ${resolve(dir ?? process.cwd())}. Run \\`dashwise module init\\` first or pass \\`--dir <path>\\`.`,\n );\n }\n return manifest;\n}\n","/**\n * Output formatting helpers — colors via picocolors (zero deps,\n * tiny). All output goes through these so the CLI has a consistent\n * voice + we can later add `--no-color` / `--json` modes by editing\n * one file.\n */\n\nimport pc from 'picocolors';\n\nexport function success(msg: string): void {\n process.stderr.write(`${pc.green('✓')} ${msg}\\n`);\n}\n\nexport function info(msg: string): void {\n process.stderr.write(`${pc.cyan('ℹ')} ${msg}\\n`);\n}\n\nexport function warn(msg: string): void {\n process.stderr.write(`${pc.yellow('⚠')} ${msg}\\n`);\n}\n\nexport function fail(msg: string): void {\n process.stderr.write(`${pc.red('✗')} ${msg}\\n`);\n}\n\n/** Plain text to stdout — for command output that should be pipe-able. */\nexport function out(msg: string): void {\n process.stdout.write(`${msg}\\n`);\n}\n\n/** Print a `key: value` pair, key bold and right-padded. */\nexport function kv(key: string, value: string, padTo = 14): void {\n const padded = key.padEnd(padTo);\n process.stdout.write(`${pc.bold(padded)} ${value}\\n`);\n}\n\n/** Highlight CLI commands or paths in inline text. */\nexport function code(s: string): string {\n return pc.cyan(s);\n}\n\n/** Dim secondary info (timestamps, helper hints). */\nexport function dim(s: string): string {\n return pc.dim(s);\n}\n\nexport { pc };\n","/**\n * Inline scaffold for `dashwise module init`. Each function returns\n * the file content for a single file in the target project tree.\n *\n * Kept inline (no template-files dir) because the scaffold is small\n * + benefits from having the runtime values (slug, name) interpolated\n * in TS rather than via a separate templating engine. When the\n * scaffold grows beyond ~10 files OR starts to differ meaningfully\n * between AI-built / hand-authored / custom flavors, splitting to\n * `templates/<flavor>/` becomes worth it.\n */\n\nexport type ScaffoldKind = 'hand_authored' | 'custom';\n\nexport interface ScaffoldOptions {\n slug: string;\n name: string;\n /** Module flavor — `hand_authored` (simple isolate-runtime) or `custom` (full Next.js + machine runtime). */\n kind?: ScaffoldKind;\n /** Optional Git repository URL — populates `module.json#repository.url`. */\n repositoryUrl?: string;\n}\n\nexport function manifestJson(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n // HH-CC-FUP-5: `owns.tables` starts empty. Earlier versions seeded\n // a default `items` table with one `title` field as a \"starter\n // example\" — but dogfood feedback was that this is confusing\n // (authors think \"I didn't create that, why is it there?\") and\n // worse, the seeded slug + field never make it into the actual DB\n // (provisioning creates an empty draft on the backend, and the local\n // module.json doesn't sync into the manifest until something like\n // `dashwise table create` runs). Empty tables array is honest. The\n // first `dashwise table create` populates it.\n const manifest: Record<string, unknown> = {\n schema_version: 2,\n module: {\n slug: opts.slug,\n name: opts.name,\n version: '0.0.1',\n },\n module_kind: kind,\n owns: {\n tables: [],\n },\n };\n if (kind === 'custom') {\n manifest.runtime = {\n type: 'nextjs',\n kind: 'machine',\n machine_size: 'shared-cpu-1x',\n server_actions: true,\n };\n }\n if (opts.repositoryUrl) {\n manifest.repository = { type: 'git', url: opts.repositoryUrl };\n }\n return JSON.stringify(manifest, null, 2) + '\\n';\n}\n\nexport function packageJson(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^0.8.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function tsconfigJson(): string {\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n lib: ['dom', 'dom.iterable', 'ES2022'],\n module: 'ESNext',\n moduleResolution: 'Bundler',\n jsx: 'preserve',\n strict: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n esModuleInterop: true,\n isolatedModules: true,\n allowJs: false,\n noEmit: true,\n incremental: true,\n plugins: [{ name: 'next' }],\n paths: { '@/*': ['./*'] },\n },\n include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],\n exclude: ['node_modules'],\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function nextConfig(): string {\n return `/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {\n typescript: { ignoreBuildErrors: true },\n eslint: { ignoreDuringBuilds: true },\n};\nexport default nextConfig;\n`;\n}\n\nexport function nextEnvDts(): string {\n return `/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n`;\n}\n\nexport function gitignore(): string {\n return [\n '# Dependencies',\n '/node_modules',\n '',\n '# Generated by Next.js',\n '/.next',\n '/out',\n '',\n '# Production',\n '/build',\n '',\n '# Misc',\n '.DS_Store',\n '*.log',\n '',\n '# Env',\n '.env',\n '.env.local',\n '.env.*.local',\n '',\n '# Editor',\n '.vscode/',\n '.idea/',\n '',\n '# DashWise-generated SDK output is regenerable from module.json',\n '# (run `dashwise module generate`); keep it out of source control.',\n '/node_modules/@dashai/generated/',\n '',\n ].join('\\n');\n}\n\n/**\n * HH-CC-FUP-5: `apiUrl` accepts the CLI's saved API URL so a scaffold\n * created after `dashwise login https://api.dashwise.net` doesn't lie\n * about where it expects the backend to be. Falls back to localhost:3000\n * for offline scaffolds (no login yet).\n */\nconst SCAFFOLD_DEFAULT_API_URL = 'http://localhost:3000';\n\nexport function envLocalExample(apiUrl: string = SCAFFOLD_DEFAULT_API_URL): string {\n return [\n '# Copy to .env.local + fill in real values.',\n '# These vars are auto-injected by `dashwise dev` (the unified dev loop)',\n '# from ~/.config/dashwise/auth.json — you only need to edit this file if',\n '# you want to point at a non-default backend or run `next dev` standalone.',\n `DASHWISE_API_URL=${apiUrl}`,\n '# Client-side mirror — Next.js inlines NEXT_PUBLIC_* into the browser',\n '# bundle so the SDK\\'s <AuthProvider> can hit `/api/auth/sessions/me`',\n '# on the right origin. Should match DASHWISE_API_URL above.',\n `NEXT_PUBLIC_DASHWISE_API_URL=${apiUrl}`,\n 'DASHWISE_API_TOKEN=',\n 'DASHWISE_INSTALLATION_ID=local',\n '',\n ].join('\\n');\n}\n\nexport function envLocal(apiUrl: string = SCAFFOLD_DEFAULT_API_URL): string {\n return [\n '# Local dev config — auto-generated by `dashwise module init`.',\n `# Backend URL pinned to your logged-in CLI config (${apiUrl}). Gitignored;`,\n '# safe to edit. `dashwise dev` (the unified loop) auto-injects',\n '# DASHWISE_API_TOKEN from ~/.config/dashwise/auth.json AND',\n '# DASHWISE_DEV_SESSION_ID from the dev session it registers — so',\n '# you typically don\\'t need to set either here. Change DASHWISE_API_URL',\n '# (and NEXT_PUBLIC_DASHWISE_API_URL to match) to point at a different',\n '# backend.',\n '#',\n '# DASHWISE_INSTALLATION_ID is only needed AFTER you publish + install',\n '# the module in a workspace; until then dev mode (DASHWISE_DEV_SESSION_ID,',\n '# auto-set by `dashwise dev`) is the auth path.',\n `DASHWISE_API_URL=${apiUrl}`,\n '# Client-side mirror (must match DASHWISE_API_URL). Next.js inlines',\n '# NEXT_PUBLIC_* into the browser bundle so the SDK\\'s AuthProvider can',\n '# call /api/auth/sessions/me on the right origin instead of bouncing',\n '# off the local module server with a 404.',\n `NEXT_PUBLIC_DASHWISE_API_URL=${apiUrl}`,\n 'DASHWISE_API_TOKEN=',\n 'DASHWISE_INSTALLATION_ID=',\n '',\n ].join('\\n');\n}\n\nexport function appLayoutTsx(opts: ScaffoldOptions): string {\n return `export const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>{children}</body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageTsx(opts: ScaffoldOptions): string {\n return `export default function Page() {\n return (\n <main style={{ minHeight: '100dvh', display: 'grid', placeItems: 'center', padding: 32 }}>\n <div style={{ maxWidth: 560, textAlign: 'center' }}>\n <h1 style={{ fontSize: 28, marginBottom: 8 }}>${escapeHtml(opts.name)}</h1>\n <p style={{ color: '#475569' }}>\n Module slug: <code>${escapeHtml(opts.slug)}</code>\n </p>\n <p style={{ marginTop: 24, color: '#64748b', fontSize: 14 }}>\n Run <code>dashwise module dev</code> to start the watch loop.\n <br />\n Edit <code>module.json</code> to add tables; regenerated types\n land in <code>@dashai/generated</code>.\n </p>\n </div>\n </main>\n );\n}\n`;\n}\n\nexport function readme(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n if (kind === 'custom') {\n return readmeCustom(opts);\n }\n return readmeHandAuthored(opts);\n}\n\nfunction readmeHandAuthored(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA DashWise module (hand-authored). Slug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch module.json + auto-regenerate\nnpm run dev:next # plain Next.js dev server (in another terminal)\n\\`\\`\\`\n\n## Project layout\n\n| Path | What |\n| --- | --- |\n| \\`module.json\\` | Manifest. Declares tables, dependencies, runtime config. |\n| \\`app/\\` | Next.js App Router. Edit freely. |\n| \\`node_modules/@dashai/generated/\\` | Auto-generated typed wrappers. **Do not edit by hand** — regenerated by \\`dashwise module generate\\`. |\n\n## Imports\n\n\\`\\`\\`ts\nimport { db } from '@dashai/generated';\nimport type { ItemsRow } from '@dashai/generated';\n\n// runtime types + errors\nimport { createClient, type Where } from '@dashai/sdk';\n\\`\\`\\`\n`;\n}\n\nfunction readmeCustom(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA **custom DashWise module** — a full Next.js App Router app that\nruns in a per-installation Fly Machine (P7 substrate). Authenticated\nvia the DashWise NestJS backend through \\`@dashai/sdk/auth\\`.\n\nSlug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch + regen on module.json save (terminal 1)\nnpm run dev:next # next dev on :3000 (terminal 2)\n\\`\\`\\`\n\n## Architecture\n\n- **\\`module.json\\`** — manifest (\\`module_kind: 'custom'\\`, \\`runtime.kind: 'machine'\\`).\n- **\\`middleware.ts\\`** — \\`withAuth\\` from \\`@dashai/sdk/auth/middleware\\`. Redirects unauthenticated requests through the DashWise SSO flow.\n- **\\`app/layout.tsx\\`** — wraps the tree in \\`<AuthProvider>\\` from \\`@dashai/sdk/auth/client\\`.\n- **\\`app/page.tsx\\`** — public landing (allowlisted in \\`middleware.ts\\`).\n- **\\`app/dashboard/page.tsx\\`** — Server Component requiring a valid session via \\`getServerSession()\\`.\n- **\\`app/api/auth/callback/route.ts\\`** — exchanges the SSO one-time code for a session cookie (uses \\`exchangeCode()\\` from the SDK).\n- **\\`app/api/auth/sign-in/route.ts\\`** — entry point that redirects to the backend's \\`/sso/start\\` with the right \\`return_to\\` + \\`client_id\\`.\n- **\\`app/api/auth/sign-out/route.ts\\`** — clears the session cookie + tells the backend to revoke.\n\n## Imports\n\n\\`\\`\\`ts\n// Data:\nimport { db } from '@dashai/generated';\n\n// Auth (server, e.g. inside a Server Component or route handler):\nimport { getServerSession, exchangeCode, signOut } from '@dashai/sdk/auth/server';\n\n// Auth (client, inside a Client Component):\n'use client';\nimport { useSession, SignOutButton, AuthProvider } from '@dashai/sdk/auth/client';\n\n// Runtime types + errors:\nimport { type Where, RowNotFoundError } from '@dashai/sdk';\n\\`\\`\\`\n\n## Publish\n\n\\`\\`\\`bash\ndashwise module validate # local lint\ndashwise module publish --bump patch\n\\`\\`\\`\n\n## Adding UI blocks\n\nThe scaffold pre-installs two shadcn/ui primitives (\\`Button\\`, \\`Card\\`) plus the\ncanonical Tailwind 4 + theme-tokens setup. To add more components:\n\n\\`\\`\\`bash\n# shadcn/ui base (free):\nnpx shadcn@latest add input badge dialog dropdown-menu\n\n# shadcn-studio blocks (free at https://shadcnstudio.com):\nnpx shadcn@latest add @shadcn-studio/hero-section-01\n\n# shadcn-studio Pro blocks (requires \\$EMAIL + \\$LICENSE_KEY env vars):\nnpx shadcn@latest add @ss-components/dashboard-shell-01\n\\`\\`\\`\n\nIf you're using Claude Code or another IDE that supports the shadcn-studio MCP,\ntrigger \\`/cui\\` (create new UI) or \\`/rui\\` (refine existing UI) to walk through\nthe canonical block-discovery flow.\n\n## Deploying elsewhere (custom domain)\n\nThe scaffolded SSO flow is wired for DashWise's own infrastructure\n(\\`m-<id>.dashwise.net\\`). If you want to host this module on your own\ndomain (e.g. \\`mymodule.example.com\\`), there are two options:\n\n1. **Wait for custom-domain support (in design).** A future \\`--callback-origin\\`\n flag on \\`dashwise module init\\` plus a \\`module_oauth_clients\\` allowlist will\n let modules run at arbitrary domains while still using DashWise SSO. Tracked\n in [\\`modules-author-experience-v1.md\\`](https://github.com/sharmaintuize/dashwise-devops-docs/blob/main/plans/modules-author-experience-v1.md) §3.\n2. **Bypass SSO + use a Workspace API Token today.** Replace the SSO middleware\n with a token-check middleware that reads \\`Authorization: Token <key>\\` from\n each request. Tokens are created at \\`<dashwise-dashboard>/settings/tokens\\`\n and scoped to a workspace. The SDK accepts these via the standard\n \\`DASHWISE_API_TOKEN\\` env var. You'll lose the per-user session model\n (every request runs as the token's owner) but gain the freedom to deploy\n anywhere.\n\nThe CLI's \\`dashwise dev\\` command auto-injects the developer's CLI token (also\na bearer token) into local dev — so local development works regardless of\nwhich path you pick for production.\n`;\n}\n\n// ── Custom-flavor templates ──────────────────────────────────────────\n\nexport function middlewareTs(): string {\n return `// Next.js middleware — gates every route on the DashWise session cookie.\n// Public routes (and /api/auth/*) bypass the redirect; everything else\n// 302s through the SSO flow when no \\`dashwise.session\\` cookie is set.\nimport { withAuth } from '@dashai/sdk/auth/middleware';\n\nexport default withAuth({\n // \\`/sign-in-error\\` is public so unauthenticated visitors can actually\n // see the polished SSO error page — otherwise a sign-in failure would\n // redirect-loop trying to re-authenticate.\n publicPaths: ['/', '/about', '/sign-in-error'],\n loginPath: '/api/auth/sign-in',\n});\n\nexport const config = {\n matcher: ['/((?!_next/static|_next/image|favicon.ico|public/).*)'],\n};\n`;\n}\n\nexport function appLayoutCustomTsx(opts: ScaffoldOptions): string {\n return `import './globals.css';\nimport { AuthProvider } from '@dashai/sdk/auth/client';\nimport { ThemeProvider } from '@/components/theme-provider';\n\nexport const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise custom module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\" suppressHydrationWarning>\n <body className=\"antialiased\">\n <ThemeProvider\n attribute=\"class\"\n defaultTheme=\"system\"\n enableSystem\n disableTransitionOnChange\n >\n <AuthProvider>{children}</AuthProvider>\n </ThemeProvider>\n </body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageCustomTsx(opts: ScaffoldOptions): string {\n return `// Public landing page — listed in middleware.ts publicPaths.\n//\n// First-run experience for unauthenticated visitors: hero with the\n// module name + tagline, a \"Sign in with DashWise\" button that kicks\n// off the SSO flow (via /api/auth/sign-in), and a feature card\n// describing what the module does. After signing in, the user lands\n// on /dashboard (Server Component, session-validated).\n//\n// Styling: shadcn/ui primitives (\\`<Button>\\`, \\`<Card>\\`) on Tailwind 4\n// theme tokens. Add more blocks via \\`npx shadcn add @shadcn-studio/...\\`\n// (see README's \"Adding UI blocks\" section).\nimport Link from 'next/link';\nimport { LogIn, LayoutDashboard } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nexport default function Page() {\n return (\n <main className=\"flex min-h-dvh flex-col items-center justify-center gap-12 px-6 py-16\">\n <section className=\"flex max-w-2xl flex-col items-center gap-6 text-center\">\n <h1 className=\"text-balance text-4xl font-semibold tracking-tight sm:text-5xl\">\n ${escapeHtml(opts.name)}\n </h1>\n <p className=\"text-balance text-lg text-muted-foreground\">\n A DashWise module. Sign in with your DashWise account to access the\n dashboard and start using the workspace's data through the typed SDK.\n </p>\n <div className=\"flex flex-wrap items-center justify-center gap-3\">\n <Button asChild size=\"lg\">\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <LogIn aria-hidden=\"true\" />\n Sign in with DashWise\n </Link>\n </Button>\n <Button asChild variant=\"ghost\" size=\"lg\">\n <Link href=\"/dashboard\">\n <LayoutDashboard aria-hidden=\"true\" />\n Go to dashboard\n </Link>\n </Button>\n </div>\n </section>\n\n <Card className=\"w-full max-w-2xl\">\n <CardHeader>\n <CardTitle>What you can do here</CardTitle>\n <CardDescription>\n This is a custom DashWise module — a full Next.js app authenticated\n against the DashWise SSO. Edit \\`app/page.tsx\\` to replace this\n landing page; everything else is yours to customize.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"text-sm text-muted-foreground\">\n <ul className=\"space-y-2\">\n <li>\n Edit <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>\n {' '}to declare tables, dependencies, and runtime config.\n </li>\n <li>\n Run <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise dev</code>\n {' '}for a one-command local loop with auth env vars auto-injected.\n </li>\n <li>\n Import typed table clients from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>\n {' '}— the SDK regenerates on every manifest save.\n </li>\n </ul>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nexport function appDashboardPageTsx(): string {\n return `import { getServerSession } from '@dashai/sdk/auth/server';\nimport { redirect } from 'next/navigation';\nimport { LogOut, ShieldCheck } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\n/**\n * Auth-gated Server Component. The middleware ensures the user has\n * a session cookie before this page renders; \\`getServerSession()\\`\n * validates the cookie against the backend's \\`/api/auth/sessions/me\\`\n * endpoint, returning the decoded \\`Session\\` (or \\`null\\` if stale).\n *\n * On a successful render, this is the polished session card — replace\n * the contents with whatever your module actually needs to show.\n */\nexport default async function Dashboard() {\n const session = await getServerSession();\n if (!session) {\n redirect('/api/auth/sign-in?return_to=/dashboard');\n }\n return (\n <main className=\"mx-auto flex min-h-dvh max-w-3xl flex-col gap-6 px-6 py-12\">\n <header className=\"flex items-start justify-between gap-4\">\n <div>\n <h1 className=\"text-2xl font-semibold tracking-tight\">Dashboard</h1>\n <p className=\"text-sm text-muted-foreground\">\n You're signed in. This page is rendered as a Server Component and\n validates the session cookie on every request.\n </p>\n </div>\n <form action=\"/api/auth/sign-out\" method=\"POST\">\n <Button variant=\"outline\" size=\"sm\" type=\"submit\">\n <LogOut aria-hidden=\"true\" />\n Sign out\n </Button>\n </form>\n </header>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2\">\n <ShieldCheck className=\"size-5 text-primary\" aria-hidden=\"true\" />\n Session\n </CardTitle>\n <CardDescription>\n Decoded from the \\`dashwise.session\\` cookie via{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">getServerSession()</code>.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-3 text-sm\">\n <Row label=\"Email\" value={session.user.email} />\n <Row label=\"User ID\" value={String(session.user.id)} />\n <Row label=\"Workspace\" value={String(session.workspaceId)} />\n <Row label=\"Role\" value={session.role} />\n {session.installationId !== undefined && (\n <Row\n label=\"Installation\"\n value={\n session.moduleSlug\n ? \\`\\${session.installationId} (\\${session.moduleSlug})\\`\n : String(session.installationId)\n }\n />\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle>Next steps</CardTitle>\n <CardDescription>\n Replace this dashboard with your module's actual UI.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm text-muted-foreground\">\n <p>\n <strong className=\"text-foreground\">1.</strong> Edit{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>{' '}\n to add tables, dependencies, and exposed actions.\n </p>\n <p>\n <strong className=\"text-foreground\">2.</strong> Import typed clients\n from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>{' '}\n (regenerated on every manifest save).\n </p>\n <p>\n <strong className=\"text-foreground\">3.</strong> Run{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise module publish --bump patch</code>{' '}\n when you're ready to ship.\n </p>\n </CardContent>\n </Card>\n </main>\n );\n}\n\nfunction Row({ label, value }: { label: string; value: string }) {\n return (\n <div className=\"flex items-baseline justify-between gap-4 border-b border-border/50 pb-2 last:border-0 last:pb-0\">\n <span className=\"text-muted-foreground\">{label}</span>\n <span className=\"font-mono text-sm\">{value}</span>\n </div>\n );\n}\n`;\n}\n\nexport function appApiAuthSignInTs(): string {\n return `// /api/auth/sign-in — kick off the SSO flow.\n//\n// Reads \\`?return_to=\\` from the caller (defaults to '/'). Branches\n// on env:\n//\n// - DASHWISE_DEV_SESSION_ID set (set automatically by\n// \\`dashwise dev\\`): hits /api/auth/dev/sso/start with the dev\n// session id. No installation_id required — the module isn't\n// installed in a workspace yet.\n//\n// - DASHWISE_INSTALLATION_ID set (production / installed-module\n// path): hits /api/auth/sso/start with the installation id.\n//\n// In both cases the backend mints an exchange code + 302s back to\n// \\`/api/auth/callback?code=...\\` where we set the session cookie.\n//\n// Unauthenticated browser hits to either backend endpoint 302 to\n// the DashWise FE \\`/login?return_to=...\\` automatically — you don't\n// need to handle the \"user not logged in\" case here.\nimport { NextResponse } from 'next/server';\n\nexport function GET(request: Request) {\n const url = new URL(request.url);\n const returnTo = url.searchParams.get('return_to') ?? '/';\n const apiBaseUrl = process.env.DASHWISE_API_URL;\n const installationId = process.env.DASHWISE_INSTALLATION_ID;\n const devSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n if (!apiBaseUrl) {\n return new NextResponse(\n 'DASHWISE_API_URL must be set in .env.local',\n { status: 500 },\n );\n }\n if (!installationId && !devSessionId) {\n return new NextResponse(\n 'Either DASHWISE_INSTALLATION_ID (installed module) or DASHWISE_DEV_SESSION_ID ' +\n '(local dev via \\`dashwise dev\\`) must be set. Run \\`dashwise dev\\` to register ' +\n 'a dev session, or set DASHWISE_INSTALLATION_ID after publishing your module.',\n { status: 500 },\n );\n }\n\n // Absolute URL for return_to so the backend knows which host to\n // bounce back to (the callback path is fixed at /api/auth/callback\n // by SDK convention).\n const moduleOrigin = url.origin;\n const absoluteReturnTo = \\`\\${moduleOrigin}\\${returnTo}\\`;\n\n let ssoStart;\n if (devSessionId) {\n // Dev mode wins when both are set — \\`dashwise dev\\` injects\n // DASHWISE_DEV_SESSION_ID into the child env, which overrides\n // whatever was in .env.local. The dev session id keys back to\n // the dev's workspace + callback origin allowlist.\n ssoStart = new URL('/api/auth/dev/sso/start', apiBaseUrl);\n ssoStart.searchParams.set('return_to', absoluteReturnTo);\n ssoStart.searchParams.set('dev_session_id', devSessionId);\n } else {\n ssoStart = new URL('/api/auth/sso/start', apiBaseUrl);\n ssoStart.searchParams.set('return_to', absoluteReturnTo);\n ssoStart.searchParams.set('client_id', installationId);\n }\n return NextResponse.redirect(ssoStart);\n}\n`;\n}\n\nexport function appApiAuthCallbackTs(): string {\n return `// /api/auth/callback — receives \\`?code=&return_to=\\` from the\n// DashWise SSO start endpoint OR \\`?error=&error_description=\\` if the\n// SSO flow failed. Two paths:\n//\n// 1. Success path: exchange \\`?code\\` for a session cookie via\n// \\`exchangeCode()\\`, then redirect to \\`return_to\\`.\n// 2. Error path: SSO returned \\`?error=\\` — redirect to the polished\n// sign-in-error page so the user sees a real error UI instead of\n// a raw 4xx page. The error code maps to known SSO error codes\n// (e.g. \\`access_denied\\`, \\`server_error\\`, \\`invalid_request\\`).\nimport { NextResponse } from 'next/server';\nimport { exchangeCode } from '@dashai/sdk/auth/server';\n\nexport async function GET(request: Request) {\n const url = new URL(request.url);\n const error = url.searchParams.get('error');\n if (error) {\n const target = new URL('/sign-in-error', url.origin);\n target.searchParams.set('code', error);\n const description = url.searchParams.get('error_description');\n if (description) target.searchParams.set('description', description);\n return NextResponse.redirect(target);\n }\n const code = url.searchParams.get('code');\n const returnTo = url.searchParams.get('return_to') ?? '/';\n if (!code) {\n const target = new URL('/sign-in-error', url.origin);\n target.searchParams.set('code', 'missing_code');\n return NextResponse.redirect(target);\n }\n try {\n await exchangeCode(code); // sets the dashwise.session cookie\n } catch (err) {\n const target = new URL('/sign-in-error', url.origin);\n target.searchParams.set('code', 'exchange_failed');\n target.searchParams.set('description', (err as Error).message);\n return NextResponse.redirect(target);\n }\n return NextResponse.redirect(new URL(returnTo, url.origin));\n}\n`;\n}\n\nexport function appApiAuthSignOutTs(): string {\n return `// /api/auth/sign-out — best-effort backend revoke + cookie clear,\n// then redirect to / so the browser actually navigates somewhere\n// after the form POST. A 204 here would leave the user staring at\n// /dashboard with stale-rendered HTML — the cookie WAS cleared but\n// they'd think nothing happened. 303 See Other forces the browser\n// to follow with GET (not re-POST), landing on the public '/' page.\nimport { NextResponse } from 'next/server';\nimport { signOut } from '@dashai/sdk/auth/server';\n\nexport async function POST(request: Request) {\n await signOut();\n return NextResponse.redirect(new URL('/', request.url), 303);\n}\n`;\n}\n\nexport function packageJsonCustom(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^0.8.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n // Styling system — same shadcn + Tailwind 4 stack as the\n // main DashWise frontend, so look-and-feel stays consistent\n // and module authors can add more blocks via the\n // shadcn-studio MCP (`npx shadcn add @shadcn-studio/...`).\n tailwindcss: '^4',\n '@tailwindcss/postcss': '^4',\n 'tw-animate-css': '^1.4.0',\n shadcn: '^4.0.8',\n 'radix-ui': '^1.4.3',\n 'class-variance-authority': '^0.7.1',\n clsx: '^2.1.1',\n 'tailwind-merge': '^3.5.0',\n 'lucide-react': '^0.577.0',\n 'next-themes': '^0.4.6',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n// ── shadcn + Tailwind 4 stack (custom scaffold) ──────────────────────\n//\n// These templates mirror the configuration the main `dashwise-frontend`\n// uses, so visual + UX consistency is preserved across the dashboard\n// and scaffolded modules. The stack: Tailwind 4 (no config file —\n// config lives in `globals.css` via `@import \"tailwindcss\"`), shadcn\n// New York style, oklch theme tokens, lucide icons, next-themes for\n// the dark-mode toggle.\n//\n// Module authors who want more blocks add them via the shadcn-studio\n// MCP workflow: `/cui` for new blocks, `/rui` for refines (see the\n// scaffold's README for the canonical pointer).\n\n/**\n * `components.json` — shadcn config. Pins the style + base color so\n * `npx shadcn add` produces the same look as the rest of the DashWise\n * ecosystem. The two registries (`@shadcn-studio` free + `@ss-components`\n * Pro) are declared so module authors can pull blocks from either\n * without re-running init.\n */\nexport function componentsJson(): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://ui.shadcn.com/schema.json',\n style: 'new-york',\n rsc: true,\n tsx: true,\n tailwind: {\n config: '',\n css: 'app/globals.css',\n baseColor: 'neutral',\n cssVariables: true,\n prefix: '',\n },\n iconLibrary: 'lucide',\n rtl: false,\n aliases: {\n components: '@/components',\n utils: '@/lib/utils',\n ui: '@/components/ui',\n lib: '@/lib',\n hooks: '@/hooks',\n },\n registries: {\n '@shadcn-studio': 'https://shadcnstudio.com/r/{name}.json',\n '@ss-components': {\n url: 'https://shadcnstudio.com/r/components/{name}.json',\n params: {\n email: '${EMAIL}',\n license_key: '${LICENSE_KEY}',\n },\n },\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * `postcss.config.mjs` — Tailwind 4's PostCSS plugin entry. No other\n * plugins needed; the rest of the build is Next.js's defaults.\n */\nexport function postcssConfigMjs(): string {\n return `const config = {\n plugins: {\n \"@tailwindcss/postcss\": {},\n },\n};\n\nexport default config;\n`;\n}\n\n/**\n * `app/globals.css` — Tailwind 4 entry + oklch theme tokens.\n *\n * Tailwind 4 has no `tailwind.config.ts`; config lives here via the\n * `@import \"tailwindcss\"` directive + CSS custom properties. The\n * `:root` block defines the light theme; `.dark` overrides it. Tokens\n * are copied verbatim from the main dashwise-frontend so module authors\n * who later read the frontend code see the same names.\n */\nexport function globalsCss(): string {\n return `@import \"tailwindcss\";\n@import \"tw-animate-css\";\n@import \"shadcn/tailwind.css\";\n\n@custom-variant dark (&:is(.dark *));\n\n:root {\n --background: oklch(1 0 0);\n --foreground: oklch(0.14 0 0);\n --card: oklch(1 0 0);\n --card-foreground: oklch(0.14 0 0);\n --popover: oklch(1 0 0);\n --popover-foreground: oklch(0.14 0 0);\n --primary: oklch(0.2 0 0);\n --primary-foreground: oklch(0.99 0 0);\n --secondary: oklch(0.97 0 0);\n --secondary-foreground: oklch(0.2 0 0);\n --muted: oklch(0.97 0 0);\n --muted-foreground: oklch(0.56 0 0);\n --accent: oklch(0.97 0 0);\n --accent-foreground: oklch(0.2 0 0);\n --destructive: oklch(0.58 0.24 28.48);\n --border: oklch(0.92 0 0);\n --input: oklch(0.92 0 0);\n --ring: oklch(0.71 0 0);\n --radius: 0.625rem;\n\n --font-sans:\n ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,\n \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n --font-mono:\n ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace;\n}\n\n.dark {\n --background: oklch(0.14 0 0);\n --foreground: oklch(0.99 0 0);\n --card: oklch(0.2 0 0);\n --card-foreground: oklch(0.99 0 0);\n --popover: oklch(0.2 0 0);\n --popover-foreground: oklch(0.99 0 0);\n --primary: oklch(0.92 0 0);\n --primary-foreground: oklch(0.2 0 0);\n --secondary: oklch(0.27 0 0);\n --secondary-foreground: oklch(0.99 0 0);\n --muted: oklch(0.27 0 0);\n --muted-foreground: oklch(0.71 0 0);\n --accent: oklch(0.27 0 0);\n --accent-foreground: oklch(0.99 0 0);\n --destructive: oklch(0.7 0.19 22.23);\n --border: oklch(0.27 0 0);\n --input: oklch(0.27 0 0);\n --ring: oklch(0.56 0 0);\n}\n\n* {\n border-color: var(--border);\n}\n\nbody {\n background-color: var(--background);\n color: var(--foreground);\n font-family: var(--font-sans);\n}\n`;\n}\n\n/**\n * `lib/utils.ts` — the canonical \\`cn()\\` helper that shadcn components\n * import. Combines \\`clsx\\` (conditional class composition) with\n * \\`tailwind-merge\\` (resolves conflicting Tailwind utilities, e.g.\n * \\`px-2 px-4\\` → \\`px-4\\`).\n */\nexport function libUtilsTs(): string {\n return `import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n`;\n}\n\n/**\n * \\`components/ui/button.tsx\\` — vendored from the dashwise-frontend's\n * canonical button (which itself came from shadcn New York). Vendored\n * (vs running \\`npx shadcn add\\` in a post-install) so the scaffold\n * doesn't need network access at install time.\n */\nexport function componentsUiButtonTsx(): string {\n return `import * as React from \"react\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport { Slot } from \"radix-ui\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst buttonVariants = cva(\n \"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-white hover:bg-destructive/90\",\n outline:\n \"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost:\n \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-9 px-4 py-2 has-[>svg]:px-3\",\n sm: \"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5\",\n lg: \"h-10 rounded-md px-6 has-[>svg]:px-4\",\n icon: \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n },\n);\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n asChild = false,\n ...props\n}: React.ComponentProps<\"button\"> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean;\n }) {\n const Comp = asChild ? Slot.Root : \"button\";\n return (\n <Comp\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Button, buttonVariants };\n`;\n}\n\n/**\n * \\`components/ui/card.tsx\\` — vendored from the dashwise-frontend. Same\n * rationale as button.tsx.\n */\nexport function componentsUiCardTsx(): string {\n return `import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n );\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n );\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n );\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6\", className)}\n {...props}\n />\n );\n}\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };\n`;\n}\n\n/**\n * \\`components/theme-provider.tsx\\` — thin re-export of the next-themes\n * provider, marked \\`\"use client\"\\`. Layout wraps in this so the\n * \\`.dark\\` class can be applied to \\`<html>\\` based on system preference\n * or explicit user toggle.\n */\nexport function componentsThemeProviderTsx(): string {\n return `\"use client\";\n\nimport { ThemeProvider as NextThemesProvider } from \"next-themes\";\n\nexport function ThemeProvider({\n children,\n ...props\n}: React.ComponentProps<typeof NextThemesProvider>) {\n return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n`;\n}\n\n/**\n * \\`app/sign-in-error/page.tsx\\` — the SSO error landing.\n *\n * Reached via redirect from /api/auth/callback when the SSO flow\n * returns \\`?error=\\` or when code exchange fails. Renders a polished\n * error UI with the SSO error code (plain-English when known) + a\n * \"Try again\" button that retries the sign-in flow.\n *\n * Listed in middleware.ts publicPaths so unauthenticated visitors can\n * actually reach the error page (otherwise the redirect would loop).\n */\nexport function appSignInErrorPageTsx(): string {\n return `import Link from 'next/link';\nimport { AlertTriangle, RefreshCw } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nconst ERROR_MESSAGES: Record<string, string> = {\n access_denied:\n \"You declined the sign-in request. To use this module, you'll need to authorize it on the DashWise sign-in page.\",\n server_error:\n 'The DashWise sign-in server returned an internal error. This is usually transient — try again in a moment.',\n invalid_request:\n 'The sign-in request was malformed. This is almost always a configuration bug — check that DASHWISE_API_URL and DASHWISE_INSTALLATION_ID are set correctly.',\n missing_code:\n 'The callback URL was missing the expected exchange code. This usually means the SSO flow was interrupted.',\n exchange_failed:\n \"The exchange code couldn't be redeemed for a session. The code may have expired (they're single-use and short-lived) — try signing in again.\",\n};\n\ninterface SignInErrorPageProps {\n searchParams: Promise<{ code?: string; description?: string }>;\n}\n\nexport default async function SignInErrorPage({ searchParams }: SignInErrorPageProps) {\n const params = await searchParams;\n const errorCode = params.code ?? 'unknown';\n const friendlyMessage = ERROR_MESSAGES[errorCode];\n return (\n <main className=\"flex min-h-dvh items-center justify-center px-6 py-12\">\n <Card className=\"w-full max-w-lg\">\n <CardHeader>\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-full bg-destructive/10 p-2\">\n <AlertTriangle className=\"size-5 text-destructive\" aria-hidden=\"true\" />\n </div>\n <div className=\"flex-1\">\n <CardTitle>Sign-in failed</CardTitle>\n <CardDescription>\n The DashWise SSO flow couldn't complete.\n </CardDescription>\n </div>\n </div>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Error code\n </div>\n <code className=\"block rounded bg-muted px-2 py-1 text-sm\">\n {errorCode}\n </code>\n </div>\n {friendlyMessage && (\n <p className=\"text-sm text-muted-foreground\">{friendlyMessage}</p>\n )}\n {params.description && (\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Detail\n </div>\n <p className=\"text-sm text-muted-foreground\">{params.description}</p>\n </div>\n )}\n <div className=\"flex flex-wrap gap-2 pt-2\">\n <Button asChild>\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <RefreshCw aria-hidden=\"true\" />\n Try again\n </Link>\n </Button>\n <Button asChild variant=\"ghost\">\n <Link href=\"/\">Back to landing</Link>\n </Button>\n </div>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/** Slug validation matching the manifest schema's regex. */\nexport function isValidSlug(slug: string): boolean {\n return /^[a-z][a-z0-9_-]*$/.test(slug);\n}\n\n// ── HH-CC-FUP-5: agent-facing scaffold docs ───────────────────────────\n//\n// CLAUDE.md + spec.md + agent-log.md ship with every scaffold so AI\n// coding agents (Claude Code, Cursor, etc.) inherit the spec-first +\n// log-every-change discipline used in the dashwise-backend codebase\n// without the author having to write any of it themselves. The bodies\n// are kept short on purpose — pointers to the canonical docs\n// (`building-modules.md`, manifest schema) instead of duplicating\n// content that drifts.\n\nexport function claudeMd(opts: ScaffoldOptions): string {\n const isCustom = (opts.kind ?? 'hand_authored') === 'custom';\n return `# CLAUDE.md — ${opts.name}\n\nInstructions for AI coding agents (Claude Code, Cursor, etc.) working\nin this DashWise module. Read this before making changes.\n\n## What this module is\n\nA DashWise ${isCustom ? '**custom Next.js** module (full app runtime, machine-class)' : '**hand-authored simple** module (isolate runtime)'} authored against \\`@dashai/sdk\\`.\nModule slug: \\`${opts.slug}\\`.\n\nDashWise calls apps \"modules\". A module is a Next.js app + a\nmanifest (\\`module.json\\`) declaring the tables it owns, modules it\ndepends on, and actions it exposes. The DashWise backend hosts the\ndata plane + auth; this module ships UI + business logic.\n\n## Spec-first, log-every-change\n\nThis scaffold mirrors the dashwise-backend convention:\n\n- **\\`spec.md\\`** is the source of truth for what this module does —\n tables, fields, API contracts, business rules, error cases. Update\n it BEFORE writing code that changes behavior. If a behavior isn't\n in \\`spec.md\\`, it isn't real yet.\n- **\\`agent-log.md\\`** is an append-only log of every meaningful\n change. Every commit that touches \\`module.json\\`, \\`spec.md\\`, a\n schema mutation, or a public surface MUST add an entry. Format:\n\n \\`\\`\\`\n ## YYYY-MM-DD HH:MM — <author or agent name>\n\n **Change:** one-line summary\n **Files:** comma-separated list of files\n **Reason:** why this change was necessary\n **Spec impact:** none | updated spec.md §<section>\n \\`\\`\\`\n\n Reverse chronological (newest first).\n\n## Schema changes go through the CLI, not by hand\n\n\\`module.json\\` is the manifest. The backend has its own copy that\nthe runtime data plane uses. To keep them in sync, mutate via the\nCLI — \\`dashwise table create\\`, \\`dashwise field add\\`, etc. —\nwhich calls the schema endpoints and rewrites the local\n\\`module.json\\` from the backend's response. Hand-edits to\n\\`module.json\\` won't sync until the next CLI mutation picks them up.\n\nCommon commands:\n\n\\`\\`\\`\ndashwise table create <slug> --field <slug:type[:required]>\ndashwise table delete <slug>\ndashwise field add <table> <slug:type[:required]>\ndashwise field remove <table> <slug>\ndashwise field set-type <table> <slug> <type>\n\\`\\`\\`\n\nAllowed field types: \\`text\\`, \\`long_text\\`, \\`number\\`, \\`boolean\\`,\n\\`date\\`, \\`datetime\\`, \\`single_select\\`, \\`multi_select\\`,\n\\`link_row\\`, \\`file\\`, \\`multi_file\\`, \\`email\\`, \\`url\\`,\n\\`phone\\`, \\`formula\\`, \\`ai\\`.\n\n## Read + write data via the generated SDK\n\nThe CLI's watcher regenerates typed clients into\n\\`node_modules/@dashai/generated/\\` every time \\`module.json\\` changes.\nImport from there:\n\n\\`\\`\\`ts\nimport { db, qb } from '@dashai/generated';\n\n// Simple CRUD\nconst rows = await db.<table>.list();\nawait db.<table>.create({ /* fields */ });\n\n// Query builder (joins, aggregates)\nconst stats = await qb.from('<table>').where({ /* ... */ }).execute();\n\\`\\`\\`\n\nThe data plane authenticates via the per-module runtime token cached\nin \\`~/.config/dashwise/auth.json#modules[${opts.slug}]\\` after\n\\`dashwise init\\` provisions the dev install. \\`dashwise dev\\` injects\nthis token into the Next.js child env automatically.\n\n## Auth in dev mode\n\n\\`dashwise dev\\` registers a dev-mode SSO session with the backend\nand injects \\`DASHWISE_DEV_SESSION_ID\\` so workspace members can sign\ninto the locally-running module via DashWise SSO — no installed\n\\`installation_id\\` required.\n\nIn Server Components: \\`await getServerSession()\\` (from\n\\`@dashai/sdk/auth/server\\`).\nIn Client Components: \\`useSession()\\` (from\n\\`@dashai/sdk/auth/client\\`), wrapped in \\`<AuthProvider>\\` (already\nin \\`app/layout.tsx\\`).\n\n## Local dev lifecycle\n\n\\`\\`\\`\ndashwise login # one-time, opens browser\ndashwise init [slug] # scaffold + provision dev install\ndashwise dev # watcher + next dev, auth env auto-injected\ndashwise module destroy-dev-install # tear down when done (cleans backend + auth.json)\n\\`\\`\\`\n\n## Engineering bar\n\n- **No hacks, shortcuts, or temporary \"quick fixes\" as final\n implementations.** If something needs work, leave it as a stub and\n open an issue / TODO with a clear name — don't bury a workaround.\n- **No silent error swallowing.** Catch what you can handle; surface\n what you can't. Tests should assert error codes, not just status.\n- **No untyped \\`any\\`.** The generated SDK gives you types — use\n them. If you need an escape hatch, add a \\`@ts-expect-error\\` with\n a comment explaining why.\n- **No secrets in code or env files.** Use \\`runtime.secrets[]\\` in\n \\`module.json\\`; values are encrypted at rest and resolved at\n runtime.\n\n## Pointers\n\n- Full walkthrough — \\`@dashai/cli\\`'s [building-modules.md](https://github.com/Intuize/dashwise-cli/blob/main/docs/building-modules.md).\n- Manifest schema — \\`@dashai/sdk/dist/manifest/schema.d.ts\\` (generated from the backend Zod source of truth).\n- Query plane reference — same docs, \\`Query AST v1 wire format\\` section.\n`;\n}\n\nexport function specMd(opts: ScaffoldOptions): string {\n return `# ${opts.name} — Spec\n\n> Living document. Source of truth for what this module does. Update\n> this BEFORE changing code that changes behavior — see CLAUDE.md.\n\n## Notion\n\n(link to ticket / design doc here, or remove this section)\n\n## Overview\n\nOne-sentence description of what this module does, who uses it, and\nwhat tables it owns.\n\n## Database schema\n\n| Table | Columns | Notes |\n|---|---|---|\n| (none yet) | run \\`dashwise table create <slug> --field <slug:type>\\` to add one | |\n\n## API / contract\n\n| Method | Path | Auth | Purpose |\n|---|---|---|---|\n| (none yet) | | | |\n\n## Business rules\n\n- (RBAC, validation, domain logic.)\n\n## Dependencies\n\nModules this module reads from + which tables/actions:\n\n- (none yet — declare in \\`module.json#dependencies[]\\`)\n\n## Exposed tables + actions\n\nTables or server-actions this module makes available to other\nmodules:\n\n- (none yet)\n\n## Error cases\n\n- (what can go wrong + how it's handled)\n\n## Decisions\n\n- (architectural choices + the trade-offs that drove them)\n\n## Open questions\n\n- (anything blocking implementation)\n`;\n}\n\nexport function agentLogMd(opts: ScaffoldOptions): string {\n return `# Agent Log — ${opts.name}\n\nAppend-only log of meaningful changes to this module. Every commit\nthat touches \\`module.json\\`, \\`spec.md\\`, a schema, or a public\nsurface MUST add an entry here in the same change.\n\nFormat (reverse chronological, newest first):\n\n\\`\\`\\`\n## YYYY-MM-DD HH:MM — <author or agent name>\n\n**Change:** one-line summary\n**Files:** comma-separated list of files\n**Reason:** why this change was necessary\n**Spec impact:** none | updated spec.md §<section>\n\n(optional: longer context, verification steps, decisions deferred)\n\\`\\`\\`\n\n---\n\n## ${new Date().toISOString().slice(0, 10)} — dashwise module init\n\n**Change:** Scaffolded module \\`${opts.slug}\\` via \\`dashwise module init\\`.\n**Files:** entire scaffold (\\`module.json\\`, \\`app/\\`, \\`components/\\`, ...).\n**Reason:** initial scaffold.\n**Spec impact:** seeded \\`spec.md\\` template — fill in before first\nschema mutation.\n`;\n}\n","/**\n * HH-CC-LDI-6 — workspace selection helpers used across commands\n * that need to scope an operation to one workspace (`dashwise init`,\n * `dashwise dev`, future `dashwise module status`, etc.).\n *\n * Two resolution paths emerge from the existing CLI:\n *\n * - **Non-interactive** (CI, scripted) — caller passes `--workspace\n * <slug-or-id>`. We validate against the user's accessible\n * workspaces; throw on miss. Auto-pick if the user has exactly\n * one workspace.\n *\n * - **Interactive** (TTY, no `--workspace` flag) — when the user\n * has multiple workspaces and `interactive: true` is passed, we\n * prompt with @clack's `select`. Otherwise we throw with the\n * same \"re-run with --workspace\" error as the non-interactive\n * path.\n *\n * The split exists because `dashwise dev` was designed for\n * scripting (errors loudly with a re-run hint) and `dashwise init`\n * is designed for interactive onboarding (asks the user to pick).\n * One function, two policies via the `interactive` flag.\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport { apiRequest } from './api-client.js';\n\nexport interface WorkspaceSummary {\n id: number;\n name: string;\n slug: string;\n}\n\n/**\n * Resolve which workspace an operation should target.\n *\n * Resolution order:\n * 1. If `flag` is set → match it against the user's workspaces by\n * slug (preferred) or numeric id; throw if no match.\n * 2. Else if the user has exactly one workspace → auto-pick it.\n * 3. Else if `interactive` and we're in a TTY → prompt with @clack.\n * 4. Else → throw with a \"re-run with --workspace\" hint.\n *\n * `apiToken` is taken explicitly (not from saved config) so callers\n * can pass an in-memory token during the login flow or a per-call\n * override token. Most callers pass `readSavedToken()`.\n */\nexport async function selectWorkspace(opts: {\n apiUrl: string;\n apiToken: string;\n flag?: string;\n interactive: boolean;\n}): Promise<WorkspaceSummary> {\n const workspaces = await apiRequest<WorkspaceSummary[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: opts.apiUrl, auth: { token: opts.apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n\n // Flag path — caller provided a slug or id.\n if (opts.flag !== undefined) {\n return matchWorkspaceOrThrow(workspaces, opts.flag);\n }\n\n // Single workspace — auto-pick. Same behavior in both modes.\n if (workspaces.length === 1) {\n return workspaces[0]!;\n }\n\n // Multiple workspaces — interactive prompt OR throw.\n if (opts.interactive && process.stdout.isTTY) {\n const choice = await select({\n message: 'Which workspace should this module live in?',\n options: workspaces.map((w) => ({\n value: w.slug,\n label: w.name,\n hint: `slug=${w.slug}, id=${w.id}`,\n })),\n });\n if (isCancel(choice)) {\n throw new Error('Aborted.');\n }\n const picked = workspaces.find((w) => w.slug === choice);\n if (!picked) {\n // Shouldn't happen — @clack returns one of the options we\n // gave it — but defensive guard so a TS narrowing failure\n // doesn't surface as a stack trace.\n throw new Error(`Internal error: selection \"${String(choice)}\" did not match any workspace.`);\n }\n return picked;\n }\n\n // Non-interactive multi-workspace case — throw with the re-run hint.\n const list = workspaces\n .map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`)\n .join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n}\n\n/**\n * Match a `--workspace` flag value against the workspace list.\n *\n * Accepts either a slug (preferred) or a numeric id as a string.\n * Throws if there's no match — surfacing the list helps users\n * notice typos.\n *\n * Exported for tests; not part of the typical command surface.\n */\nexport function matchWorkspaceOrThrow(\n workspaces: WorkspaceSummary[],\n flag: string,\n): WorkspaceSummary {\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(`No workspace matching --workspace=${flag}. Available:\\n${list}`);\n }\n return match;\n}\n","/**\n * `dashwise module init <slug>` — scaffold a new DashWise module\n * project in a fresh directory.\n *\n * As of 2026-05-18, the DEFAULT scaffold is the full Next.js custom-\n * module scaffold — a real Next.js 16 app with `middleware.ts`,\n * `/api/auth/*` routes, an `<AuthProvider>` wrap, and a protected\n * `app/dashboard/page.tsx` example. Authentication + workspace\n * context are wired against the DashWise NestJS backend out of the\n * box (per the v1 plan in\n * `dashwise-devops-docs/plans/module-authoring-platform.md`).\n *\n * Files emitted by the default (`custom` kind):\n *\n * module.json — manifest (schema_version 2)\n * package.json — deps on @dashai/sdk + next + react\n * tsconfig.json\n * next.config.mjs\n * next-env.d.ts\n * .gitignore — ignores node_modules + .next + .dashwise/\n * .env.local.example — DASHWISE_* var template\n * middleware.ts — uses withAuth() from @dashai/sdk/auth/middleware\n * app/layout.tsx — wraps {children} in <AuthProvider>\n * app/page.tsx — public landing\n * app/dashboard/page.tsx — protected route using getServerSession()\n * app/api/auth/sign-in/route.ts — kicks off DashWise SSO redirect\n * app/api/auth/callback/route.ts — exchanges one-time code for cookie\n * app/api/auth/sign-out/route.ts — clears cookie + tells backend\n * README.md — getting-started + auth flow explainer\n *\n * For the legacy minimal scaffold (no Next.js auth wiring — purely\n * hand-authored simple-module runtime), pass `--simple`:\n *\n * dashwise module init my-mod --simple\n *\n * This emits 9 files (no middleware, no /api/auth/*, no dashboard).\n * The `--simple` flag is permanent — some module use cases (public\n * data viewers, demo modules) genuinely don't need auth.\n *\n * `--custom` is kept as a back-compat alias for the default and is\n * silently deprecated. New code should not pass either flag for the\n * full scaffold — just `dashwise module init <slug>`.\n *\n * Refuses to overwrite an existing non-empty directory unless\n * `--force` is passed. Does NOT run `npm install` automatically —\n * surfaces the next-step commands at the end of the run.\n */\n\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, text } from '@clack/prompts';\nimport {\n appApiAuthCallbackTs,\n appApiAuthSignInTs,\n agentLogMd,\n appApiAuthSignOutTs,\n appDashboardPageTsx,\n appLayoutCustomTsx,\n appLayoutTsx,\n appPageCustomTsx,\n appPageTsx,\n appSignInErrorPageTsx,\n claudeMd,\n componentsJson,\n componentsThemeProviderTsx,\n componentsUiButtonTsx,\n componentsUiCardTsx,\n envLocal,\n envLocalExample,\n gitignore,\n globalsCss,\n isValidSlug,\n libUtilsTs,\n manifestJson,\n middlewareTs,\n nextConfig,\n nextEnvDts,\n packageJson,\n packageJsonCustom,\n postcssConfigMjs,\n readme,\n specMd,\n type ScaffoldKind,\n tsconfigJson,\n} from '../../lib/scaffold.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\nimport {\n ApiError,\n createDevInstallation,\n type DevInstallationResponse,\n} from '../../lib/api-client.js';\nimport {\n isLoggedIn,\n readConfig,\n resolveApiUrl,\n upsertModuleEntry,\n} from '../../lib/config.js';\nimport { selectWorkspace } from '../../lib/workspaces.js';\n\nexport interface InitOptions {\n /** Override the target directory (defaults to `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Human-readable module name (default: derive from slug). */\n name?: string;\n /**\n * Use the legacy minimal scaffold (hand-authored simple module —\n * no Next.js auth wiring). Default before 2026-05-18; opt-in now.\n * Mutually exclusive with `custom`; if both are passed, an error\n * is raised before any files are written.\n */\n simple?: boolean;\n /**\n * @deprecated Back-compat alias for the default (full Next.js +\n * auth wiring). New code should call `init` without flags.\n *\n * Kept for back-compat across the v0.x.y series. Will be removed\n * in a future major version. When passed alongside `--simple`,\n * raises an error (mutually exclusive).\n */\n custom?: boolean;\n /** Optional Git repository URL to write into module.json#repository. */\n git?: string;\n /**\n * HH-CC-LDI-6 — skip the provisioning phase (no `POST /api/installations/dev`\n * call, no `auth.json#modules[slug]` write). The local scaffold is\n * created as before; the resulting module has no dev install backing it,\n * so `dashwise dev` / SDK data-plane calls will fail with\n * `UnauthenticatedError` until you run a future\n * `dashwise module provision-dev-install` (LDI-9) or re-run\n * `dashwise init --force`.\n *\n * Commander maps the CLI flag `--no-provision` to `provision: false`;\n * this option is therefore typed as `provision?: boolean` with\n * `undefined` (default) meaning \"provision if logged in\".\n */\n provision?: boolean;\n /**\n * HH-CC-LDI-6 — target workspace slug or numeric id. When omitted +\n * interactive (TTY), the CLI prompts; when omitted + non-interactive\n * (CI), throws if the user has more than one workspace.\n */\n workspace?: string;\n /**\n * HH-CC-LDI-6 — module description forwarded to the backend's\n * `POST /api/installations/dev` request. No effect when\n * `--no-provision`. Defaults to undefined.\n */\n description?: string;\n}\n\nexport async function moduleInitCommand(\n slugArg: string | undefined,\n options: InitOptions,\n): Promise<number> {\n intro('Scaffolding a new DashWise module');\n\n // Resolve slug — prompt if not provided.\n let slug = slugArg;\n if (!slug && process.stdout.isTTY) {\n const answer = await text({\n message: 'Module slug?',\n placeholder: 'tasks',\n validate: (v) =>\n isValidSlug(v) ? undefined : 'Slug must match /^[a-z][a-z0-9_-]*$/',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n slug = answer;\n }\n if (!slug) {\n fail('Usage: `dashwise module init <slug>`');\n return 1;\n }\n if (!isValidSlug(slug)) {\n fail(`Invalid slug ${code(slug)} — must match /^[a-z][a-z0-9_-]*$/`);\n return 1;\n }\n\n // Derive a default human name from the slug if --name wasn't given.\n const name = options.name ?? humanizeSlug(slug);\n const dir = resolve(options.dir ?? slug);\n\n if (existsSync(dir)) {\n const entries = readdirSync(dir);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(dir)} is not empty. Pass ${code('--force')} to scaffold anyway (existing files will be overwritten).`,\n );\n return 1;\n }\n }\n\n // Resolve scaffold kind. As of 2026-05-18 the default is `'custom'`\n // (the full Next.js + auth scaffold); `--simple` opts back to the\n // legacy minimal scaffold; `--custom` is a back-compat no-op alias.\n //\n // Mutually-exclusive flags are caught here before any files are\n // written so the user gets a clean failure instead of \"scaffolded\n // simple but you also passed --custom, which one wins?\".\n if (options.simple && options.custom) {\n fail(\n `Cannot pass both ${code('--simple')} and ${code('--custom')} — they're mutually exclusive. ${code('--simple')} selects the legacy minimal scaffold; the default (no flag) is the full Next.js scaffold (formerly ${code('--custom')}).`,\n );\n return 1;\n }\n const kind: ScaffoldKind = options.simple ? 'hand_authored' : 'custom';\n const scaffoldOpts = {\n slug,\n name,\n kind,\n ...(options.git !== undefined ? { repositoryUrl: options.git } : {}),\n };\n\n // HH-CC-FUP-5: pin the scaffold's .env.local to whatever backend\n // the CLI is currently pointed at (from saved login config or\n // $DASHWISE_API_URL or --api-url). Pre-FUP-5 every scaffold got\n // a hard-coded `http://localhost:3000`, which was wrong for anyone\n // running against api.dashwise.net (the common case once login\n // shipped). `resolveApiUrl()` falls back to `http://localhost:3000`\n // if nothing is set, preserving the old behavior for offline\n // scaffolds.\n const scaffoldApiUrl = resolveApiUrl();\n\n // Common files (both flavors).\n const files: Array<[string, string]> = [\n ['module.json', manifestJson(scaffoldOpts)],\n ['tsconfig.json', tsconfigJson()],\n ['next.config.mjs', nextConfig()],\n ['next-env.d.ts', nextEnvDts()],\n ['.gitignore', gitignore()],\n ['.env.local.example', envLocalExample(scaffoldApiUrl)],\n ['.env.local', envLocal(scaffoldApiUrl)],\n ['README.md', readme(scaffoldOpts)],\n // HH-CC-FUP-5: agent-facing docs ship with every scaffold so AI\n // coding agents (Claude Code, Cursor, etc.) have the spec + log\n // discipline + SDK pointers loaded into context from byte one.\n ['CLAUDE.md', claudeMd(scaffoldOpts)],\n ['spec.md', specMd(scaffoldOpts)],\n ['agent-log.md', agentLogMd(scaffoldOpts)],\n ];\n\n // Flavor-specific files.\n if (kind === 'custom') {\n // Custom Next.js app with auth wiring + shadcn/Tailwind 4 stack.\n // The shadcn config + base primitives (button, card) are vendored\n // rather than installed via `npx shadcn add` so the scaffold has\n // no network dependency at first run.\n files.push(\n ['package.json', packageJsonCustom(scaffoldOpts)],\n ['middleware.ts', middlewareTs()],\n ['components.json', componentsJson()],\n ['postcss.config.mjs', postcssConfigMjs()],\n ['app/globals.css', globalsCss()],\n ['lib/utils.ts', libUtilsTs()],\n ['components/theme-provider.tsx', componentsThemeProviderTsx()],\n ['components/ui/button.tsx', componentsUiButtonTsx()],\n ['components/ui/card.tsx', componentsUiCardTsx()],\n ['app/layout.tsx', appLayoutCustomTsx(scaffoldOpts)],\n ['app/page.tsx', appPageCustomTsx(scaffoldOpts)],\n ['app/dashboard/page.tsx', appDashboardPageTsx()],\n ['app/sign-in-error/page.tsx', appSignInErrorPageTsx()],\n ['app/api/auth/sign-in/route.ts', appApiAuthSignInTs()],\n ['app/api/auth/callback/route.ts', appApiAuthCallbackTs()],\n ['app/api/auth/sign-out/route.ts', appApiAuthSignOutTs()],\n );\n } else {\n // Hand-authored simple module (isolate runtime).\n files.push(\n ['package.json', packageJson(scaffoldOpts)],\n ['app/layout.tsx', appLayoutTsx(scaffoldOpts)],\n ['app/page.tsx', appPageTsx(scaffoldOpts)],\n );\n }\n\n // We intentionally don't run `npm install` here — the user might\n // want to inspect what we wrote first OR run it in their own shell\n // with their preferred package manager.\n for (const [relPath, content] of files) {\n const absPath = join(dir, relPath);\n const parentDir = join(absPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Scaffolded ${code(slug)} (${kind === 'custom' ? 'custom Next.js' : 'simple module'}) in ${code(dir)}`,\n );\n\n // HH-CC-LDI-6: provisioning phase. After the scaffold lands, talk\n // to the backend to create a real local-dev install + mint a\n // runtime token. Cache the token in `auth.json#modules[slug]` so\n // `dashwise dev` + `@dashai/sdk`'s `createDevClient({ moduleSlug })`\n // can pick it up. Failures here DON'T roll back the scaffold —\n // the user can re-run `dashwise init --force` later (or, once\n // LDI-9 ships, `dashwise module provision-dev-install`).\n let devInstall: DevInstallationResponse | null = null;\n const wantsProvision = options.provision !== false; // default = true\n if (wantsProvision) {\n // FUP-2: forward the scaffold's module_kind so the backend stamps\n // it on the draft manifest at provision time. `kind` here is the\n // ScaffoldKind we just resolved above (custom | hand_authored).\n devInstall = await tryProvisionDevInstall({\n slug,\n name,\n description: options.description,\n workspaceFlag: options.workspace,\n moduleKind: kind,\n });\n } else {\n info(\n `Skipping provisioning (${code('--no-provision')}). ${dim(\"Run with provisioning later to enable `dashwise dev` data-plane.\")}`,\n );\n }\n\n info(`Next steps:`);\n process.stdout.write(`\n ${dim('1.')} ${code(`cd ${dir}`)}\n ${dim('2.')} ${code('npm install')}\n ${dim('3.')} ${code('dashwise dev')} ${dim('# one command: watcher + next dev, auth auto-injected')}\n\n ${dim(' (or, for the two-terminal flow:')}\n ${dim(' dashwise module generate')} ${dim('# materialize typed wrappers')}\n ${dim(' dashwise module dev')} ${dim('# watch + auto-regenerate')}\n ${dim(' npm run dev:next # next dev on :3000)')}\n${\n devInstall\n ? `\n ${dim(`Dev installation id=${devInstall.installation.id}; runtime token expires ${devInstall.runtime_token_expires_at}.`)}\n`\n : ''\n}`);\n outro('Happy authoring.');\n return 0;\n}\n\n/**\n * HH-CC-LDI-6 — provisioning sub-flow for `dashwise init`.\n *\n * Returns the API response on success, or `null` on a recoverable\n * failure (not logged in, network error, backend down). All failures\n * are surfaced to the user with `warn(...)` so they know what to fix;\n * the parent caller continues with a successful scaffold.\n *\n * Errors that should be unrecoverable (slug conflict, kind mismatch,\n * any 4xx from the backend) are surfaced as warnings too — the user\n * can re-init with a different slug or destroy the conflicting\n * install (LDI-9) without losing their local scaffold.\n *\n * Exported as an internal because the integration is hard to unit-\n * test through `moduleInitCommand` (intro/outro/text prompts +\n * filesystem). Tests that need to exercise this path can call this\n * function directly.\n */\nasync function tryProvisionDevInstall(args: {\n slug: string;\n name: string;\n description?: string;\n workspaceFlag?: string;\n /**\n * FUP-2: scaffold's `module_kind`. Stamped on the backend's draft\n * manifest at create time so the first getManifest() read returns\n * this value instead of falling back to `'ai_builder'`.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n}): Promise<DevInstallationResponse | null> {\n if (!isLoggedIn()) {\n warn(\n `Not logged in — skipping dev-install provisioning. Run ${code('dashwise login')} then ${code(`dashwise init ${args.slug} --force`)} to retry.`,\n );\n return null;\n }\n const cfg = readConfig();\n if (!cfg) {\n // Defense — isLoggedIn() returned true so cfg should exist; if\n // it doesn't, the file got removed between the two reads. Treat\n // as not-logged-in.\n warn('CLI config disappeared mid-init. Skipping provisioning.');\n return null;\n }\n\n let workspace;\n try {\n workspace = await selectWorkspace({\n apiUrl: resolveApiUrl(),\n apiToken: cfg.token,\n flag: args.workspaceFlag,\n interactive: true,\n });\n } catch (err) {\n warn(`Workspace selection failed: ${(err as Error).message}`);\n return null;\n }\n info(\n `Provisioning dev install in workspace ${code(workspace.slug)} (id=${workspace.id})…`,\n );\n\n let response: DevInstallationResponse;\n try {\n response = await createDevInstallation(\n {\n slug: args.slug,\n name: args.name,\n ...(args.description !== undefined ? { description: args.description } : {}),\n workspaceId: workspace.id,\n ...(args.moduleKind !== undefined ? { moduleKind: args.moduleKind } : {}),\n },\n { baseUrl: resolveApiUrl(), auth: { token: cfg.token } },\n );\n } catch (err) {\n if (err instanceof ApiError) {\n surfaceProvisionApiError(err, args.slug);\n return null;\n }\n warn(`Provisioning failed: ${(err as Error).message}`);\n return null;\n }\n\n // Persist the runtime token. If THIS step fails (disk full,\n // permissions, etc.) we MUST tell the user the token so they can\n // recover manually — the server-side install was created and\n // there's no point in re-creating it.\n try {\n upsertModuleEntry(args.slug, {\n runtimeToken: response.runtime_token,\n installationId: response.installation.id,\n expiresAt: response.runtime_token_expires_at,\n });\n } catch (err) {\n warn(\n `Provisioned successfully (installation id=${response.installation.id}) but failed to cache the runtime token: ${(err as Error).message}\\n` +\n ` Runtime token (save this manually): ${response.runtime_token}\\n` +\n ` Token expires: ${response.runtime_token_expires_at}`,\n );\n return response;\n }\n\n success(\n `Provisioned dev install id=${response.installation.id}. Runtime token cached in your CLI config.`,\n );\n return response;\n}\n\n/**\n * Map a known `ApiError.code` to a user-friendly recovery hint.\n * Anything unmapped falls back to printing the raw envelope.\n */\nfunction surfaceProvisionApiError(err: ApiError, slug: string): void {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n warn(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then ${code(`dashwise init ${slug} --force`)}.`,\n );\n return;\n case 'FORBIDDEN':\n warn(\n `Not authorized to create a module in that workspace. Confirm you're a member at the DashWise dashboard.`,\n );\n return;\n case 'SLUG_ALREADY_EXISTS':\n // The backend's POST /api/installations/dev maps the upstream\n // createDraft 409 ConflictException to this code; the user\n // either picks a different slug or, once LDI-9 ships,\n // destroys the existing install.\n warn(\n `A module with slug ${code(slug)} already exists. Pick a different slug, or destroy the existing dev install (LDI-9 coming soon) and re-run.`,\n );\n return;\n case 'RUNTIME_DATA_API_DISABLED':\n warn(\n `Backend has the local-dev API turned off (BUILDER_SESSION_TOKEN_SECRET unset). Contact the operator.`,\n );\n return;\n default:\n warn(\n `Provisioning failed (${err.code} ${err.status}): ${err.message}`,\n );\n }\n}\n\n/** Convert `tasks-app` → `Tasks app` for a friendly default name. */\nfunction humanizeSlug(slug: string): string {\n const words = slug.replace(/[-_]/g, ' ').split(/\\s+/).filter(Boolean);\n if (words.length === 0) return slug;\n const first = words[0];\n const cap = first.charAt(0).toUpperCase() + first.slice(1);\n return [cap, ...words.slice(1)].join(' ');\n}\n","/**\n * `dashwise module destroy-dev-install [--module <slug>]`\n *\n * HH-CC-LDI-9 — tear down the local-dev install for a module. Reads\n * the current module's slug from `module.json` by default; pass\n * `--module <slug>` to target a different one (useful when the\n * project directory's manifest is gone but the auth.json entry\n * still lingers).\n *\n * Sequence:\n * 1. Resolve slug + install id from auth.json#modules[slug].\n * 2. DELETE /api/installations/dev/:id (audited as\n * DESTROY_DEV_INSTALLATION on the backend).\n * 3. Remove the auth.json#modules[slug] entry.\n *\n * If the backend returns 404 INSTALLATION_NOT_FOUND, we still clean\n * up the local auth.json entry — the install is gone on the server\n * already, no point in leaving a dangling token client-side.\n */\n\nimport { isCancel, confirm } from '@clack/prompts';\nimport { resolve as resolvePath } from 'node:path';\nimport {\n ApiError,\n destroyDevInstallation,\n} from '../../lib/api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n removeModuleEntry,\n resolveApiUrl,\n} from '../../lib/config.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DestroyDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: read from local module.json). */\n module?: string;\n /** Skip the confirmation prompt — for CI. */\n yes?: boolean;\n}\n\nexport async function destroyDevInstallCommand(\n options: DestroyDevInstallOptions,\n): Promise<number> {\n // ── 1. Resolve slug ────────────────────────────────────────────────\n let slug = options.module;\n if (!slug) {\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n slug = manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n }\n\n // ── 2. Find the cached install id ──────────────────────────────────\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n warn(\n `No cached dev install for ${code(slug)} in auth.json. Nothing to do.`,\n );\n return 0;\n }\n\n // ── 3. Confirm (skipped with --yes) ────────────────────────────────\n if (!options.yes && process.stdout.isTTY) {\n const choice = await confirm({\n message: `Destroy dev install ${code(`${slug} (id=${entry.installationId})`)}? Tables and rows will be soft-deleted (recoverable for 30 days via dashboard trash).`,\n });\n if (isCancel(choice) || !choice) {\n info('Aborted.');\n return 130;\n }\n }\n\n // ── 4. DELETE on backend ───────────────────────────────────────────\n let backendCleaned = false;\n try {\n const response = await destroyDevInstallation(entry.installationId, {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n });\n backendCleaned = true;\n success(\n `Destroyed dev install ${code(`${slug} (id=${response.installation_id})`)}${\n response.module_also_dropped\n ? ' — module also dropped (no other installs, unpublished).'\n : ' (module kept — other installs reference it or it has a published version).'\n }`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.code === 'INSTALLATION_NOT_FOUND') {\n // Already gone server-side; clean up the local entry anyway.\n warn(\n `Install ${entry.installationId} not found on the backend — already destroyed elsewhere. Cleaning up local cache.`,\n );\n backendCleaned = true;\n } else {\n return surfaceDestroyError(err);\n }\n }\n\n // ── 5. Clean up auth.json ──────────────────────────────────────────\n if (backendCleaned) {\n try {\n removeModuleEntry(slug);\n info(`Removed ${code(slug)} entry from auth.json.`);\n } catch (err) {\n warn(\n `Backend cleanup succeeded but failed to update auth.json: ${(err as Error).message}. Edit ${code('~/.config/dashwise/auth.json')} manually to remove the ${code(`modules[\"${slug}\"]`)} entry.`,\n );\n }\n }\n\n return 0;\n}\n\nfunction surfaceDestroyError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'INSTALLATION_KIND_NOT_LOCAL':\n fail(\n `Refusing to destroy: the install isn't kind=local (it may have been promoted to production). Use the dashboard's uninstall flow instead.`,\n );\n break;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of the install's workspace. Contact a workspace admin.`,\n );\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend — your CLI bearer may be stale. Re-run ${code('dashwise login')} and try again.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise module reset-dev-install`\n *\n * HH-CC-LDI-9 — destroy + re-create the local-dev install for the\n * current module. Useful when:\n * - Test data has accumulated and you want a clean slate\n * - The cached runtime token has been compromised + you want a\n * fresh one without the LDI-9.x rotate-token endpoint\n * - Schema is in a wedged state and you want to start over from\n * the local module.json\n *\n * Implementation: composes `destroyDevInstallCommand` +\n * `moduleInitCommand({ provision: true, force: true })`. Both phases\n * are interactive in a TTY (with `--yes` to skip prompts).\n *\n * If destroy fails the reset bails — we don't want to provision a\n * second install while a stale one still exists (the backend would\n * 409 SLUG_ALREADY_EXISTS anyway).\n */\n\nimport { resolve as resolvePath } from 'node:path';\nimport { destroyDevInstallCommand } from './destroy-dev-install.js';\nimport { moduleInitCommand } from './init.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info } from '../../lib/output.js';\n\nexport interface ResetDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: from local module.json). */\n module?: string;\n /** Target workspace for re-provisioning (passed to init). */\n workspace?: string;\n /** Skip confirmation prompts in both destroy + init phases. */\n yes?: boolean;\n}\n\nexport async function resetDevInstallCommand(\n options: ResetDevInstallOptions,\n): Promise<number> {\n // We need both a slug AND the module's display name (init re-uses\n // these on re-create). Read once from module.json so destroy + init\n // both agree on the target.\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n\n const slug = options.module ?? manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n const name = manifest?.module?.name ?? slug;\n\n // ── Phase 1: destroy ──────────────────────────────────────────────\n info(`Resetting dev install for ${code(slug)} — phase 1/2: destroy…`);\n const destroyExit = await destroyDevInstallCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n module: slug,\n ...(options.yes !== undefined ? { yes: options.yes } : {}),\n });\n if (destroyExit !== 0) {\n fail(\n `Destroy phase failed (exit ${destroyExit}); aborting reset. Fix the underlying error and re-run.`,\n );\n return destroyExit;\n }\n\n // ── Phase 2: re-init / provision ──────────────────────────────────\n info(`Reset phase 2/2: re-provisioning…`);\n return moduleInitCommand(slug, {\n name,\n ...(options.dir !== undefined ? { dir: options.dir } : { dir: projectRoot }),\n // `--force` so init doesn't refuse to overwrite the existing\n // module.json (we're keeping the local scaffold; only the\n // backend install is being recreated).\n force: true,\n // Keep the current scaffold layout — don't try to detect or\n // change `simple` vs `custom`. The user can re-init manually\n // with `dashwise init` if they want to swap scaffolds.\n provision: true,\n ...(options.workspace !== undefined ? { workspace: options.workspace } : {}),\n });\n}\n","/**\n * HH-CC-LDI-8 — shared setup for `dashwise table` / `dashwise field`\n * commands.\n *\n * Each schema-mutation command needs the same six things:\n *\n * 1. The project root (containing `module.json`)\n * 2. The current manifest (parsed) + the raw bytes (for rollback)\n * 3. The module's slug\n * 4. The CLI's saved config (apiUrl + bearer + ...)\n * 5. The per-module dev install entry (`auth.json#modules[slug]`)\n * — runtime token + installation id\n * 6. A `RequestOptions` ready to pass to the api-client helpers\n *\n * `loadSchemaCommandContext()` centralises that — commands stay\n * focused on the operation itself instead of repeating the setup\n * boilerplate.\n *\n * Errors at any step throw a user-readable `Error` (no stack trace\n * surface area); commands catch + `fail(err.message)` + return 1.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join, resolve as resolvePath } from 'node:path';\nimport type { RequestOptions } from './api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n resolveApiUrl,\n type CliConfig,\n type CliConfigModuleEntry,\n} from './config.js';\nimport {\n readManifestOrThrow,\n type ManifestShape,\n} from './manifest-io.js';\n\nexport interface SchemaCommandContext {\n projectRoot: string;\n manifestPath: string;\n manifest: ManifestShape;\n /** Verbatim file bytes — preserved so commands that want to do\n * edit-first-with-rollback have something to restore from. */\n manifestRawBytes: string;\n slug: string;\n cfg: CliConfig;\n entry: CliConfigModuleEntry;\n /**\n * Pre-built RequestOptions targeting the per-module runtime token.\n * Pass directly to api-client helpers (createTable, addField, etc.).\n * Uses the bound install's runtime token, NOT the CLI bearer —\n * the REST endpoints require a kind=local runtime token.\n */\n requestOptions: RequestOptions;\n}\n\n/**\n * Load + validate the four prerequisites for any schema-mutation\n * command. Throws on any missing piece with a clear \"how to fix\"\n * error message.\n */\nexport function loadSchemaCommandContext(opts: {\n dir?: string;\n}): SchemaCommandContext {\n const projectRoot = resolvePath(opts.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n\n // Use readManifestOrThrow for a typed \"doesn't exist / unreadable\"\n // failure mode; capture the raw bytes for potential rollback paths.\n const manifest = readManifestOrThrow<ManifestShape>(projectRoot);\n const manifestRawBytes = readFileSync(manifestPath, 'utf-8');\n\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json at ${manifestPath} has no module.slug — the manifest is malformed.`,\n );\n }\n\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n\n return {\n projectRoot,\n manifestPath,\n manifest,\n manifestRawBytes,\n slug,\n cfg,\n entry,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: entry.runtimeToken },\n },\n };\n}\n","/**\n * HH-CC-LDI-8 — parse `--field <slug>:<type>[:flags]` syntax for\n * `dashwise table create` / `dashwise field add`.\n *\n * Grammar (regular):\n *\n * spec := <slug> ':' <type> [ ':' <flag> (',' <flag>)* ]\n * slug := snake_case, ^[a-z][a-z0-9_]*[a-z0-9]$\n * type := one of FIELD_TYPES (defined here to avoid a backend\n * import; kept in sync with manifest-schema.ts on the\n * server side)\n * flag := 'required' | 'unique' (v1 — extend as needed)\n *\n * Examples:\n * \"title:text\" → { slug:'title', type:'text' }\n * \"title:text:required\" → { slug:'title', type:'text', required:true }\n * \"tags:multi_select:required\" → { slug:'tags', type:'multi_select', required:true }\n *\n * For field types that need extra config (`single_select` / `multi_select`\n * with `options`, `link_row` with `target`, `formula` with `formula`,\n * `ai` with `prompt`), use `--field-json '{...}'` instead — the JSON\n * shape mirrors `FieldDefBody` from `api-client.ts`. This split keeps\n * the simple syntax actually simple while still supporting the rich\n * cases.\n *\n * Pure function — easy to unit-test. No I/O.\n */\n\nimport type { FieldDefBody } from './api-client.js';\n\n/**\n * Closed set of field types the backend accepts. Mirrors\n * `dashwise-backend/src/modules/modules/manifest/manifest-schema.ts:FIELD_TYPES`.\n * Kept here to avoid a backend dep; backend's manifest validator is\n * still the source of truth at apply-time.\n */\nexport const FIELD_TYPES = [\n 'text',\n 'long_text',\n 'number',\n 'boolean',\n 'date',\n 'datetime',\n 'single_select',\n 'multi_select',\n 'link_row',\n 'file',\n 'multi_file',\n 'email',\n 'url',\n 'phone',\n 'formula',\n 'ai',\n] as const;\nexport type FieldType = (typeof FIELD_TYPES)[number];\n\nconst SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\nconst KNOWN_FLAGS = new Set(['required', 'unique']);\n\n/**\n * Parse a single `--field <slug>:<type>[:flags]` spec into a FieldDef\n * body. Throws with a clear error message if any part is malformed —\n * callers surface to the user via `fail()`.\n */\nexport function parseFieldSpec(spec: string): FieldDefBody {\n const parts = spec.split(':');\n if (parts.length < 2) {\n throw new FieldSpecError(\n `Field spec ${quote(spec)} is malformed — expected ${quote('<slug>:<type>[:flags]')}.`,\n );\n }\n const [slug, type, ...flagParts] = parts;\n\n if (!SLUG_REGEX.test(slug!)) {\n throw new FieldSpecError(\n `Field slug ${quote(slug!)} must match ${quote(SLUG_REGEX.source)} (snake_case, 2+ chars).`,\n );\n }\n\n if (!(FIELD_TYPES as readonly string[]).includes(type!)) {\n throw new FieldSpecError(\n `Field type ${quote(type!)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n\n const result: FieldDefBody = { slug: slug!, type: type! };\n\n if (flagParts.length > 0) {\n // Flags are comma-separated within a single colon segment OR\n // each flag is its own colon segment. We accept both for\n // ergonomics: `name:text:required,unique` and\n // `name:text:required:unique` both parse the same.\n const flags = flagParts\n .flatMap((segment) => segment.split(','))\n .map((f) => f.trim())\n .filter((f) => f.length > 0);\n\n for (const flag of flags) {\n if (!KNOWN_FLAGS.has(flag)) {\n throw new FieldSpecError(\n `Unknown flag ${quote(flag)} in field spec ${quote(spec)}. Known flags: ${[...KNOWN_FLAGS].join(', ')}. For options/target/default, use ${quote('--field-json')} instead.`,\n );\n }\n if (flag === 'required') result.required = true;\n // `unique` is a table-level index concern, not a field-level\n // attribute on FieldDef — we accept the flag for forward\n // compat with `dashwise table create --field foo:text:unique`\n // but turning it into a table-level unique index belongs in\n // the calling command. Silently dropped here; the command\n // handler reads it from the raw spec if it cares.\n }\n }\n\n // Types that need options / target / formula / prompt can't be\n // expressed in the simple syntax — direct the user to --field-json.\n // We validate post-flag-parse so the type check fires before the\n // options check (better error ordering for the user).\n if (\n (type === 'single_select' || type === 'multi_select') &&\n result.options === undefined\n ) {\n throw new FieldSpecError(\n `Type ${quote(type)} requires an ${quote('options')} list. Use ${quote('--field-json')} for this field — e.g. ${quote(`'{\"slug\":\"${slug}\",\"type\":\"${type}\",\"options\":[\"a\",\"b\"]}'`)}.`,\n );\n }\n if (type === 'link_row' && result.target === undefined) {\n throw new FieldSpecError(\n `Type ${quote('link_row')} requires a ${quote('target')}. Use ${quote('--field-json')}.`,\n );\n }\n if (type === 'formula' || type === 'ai') {\n throw new FieldSpecError(\n `Type ${quote(type)} requires extra config (${quote('formula')} or ${quote('prompt')}). Use ${quote('--field-json')}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Parse a `--field-json '<json>'` value into a FieldDef body. Just a\n * thin wrapper around `JSON.parse` with shape validation against\n * `FieldDefBody`. Pure function.\n */\nexport function parseFieldJson(json: string): FieldDefBody {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err) {\n throw new FieldSpecError(\n `--field-json value is not valid JSON: ${(err as Error).message}`,\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new FieldSpecError('--field-json must be a JSON object.');\n }\n const o = parsed as Record<string, unknown>;\n if (typeof o.slug !== 'string' || !SLUG_REGEX.test(o.slug)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('slug')}. Must match ${quote(SLUG_REGEX.source)}.`,\n );\n }\n if (typeof o.type !== 'string' || !(FIELD_TYPES as readonly string[]).includes(o.type)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('type')}. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n // The rest of the fields are best-effort — the backend's manifest\n // validator is the final authority on what shapes are accepted.\n // Cast through unknown because Record<string, unknown> doesn't\n // structurally narrow to FieldDefBody (we've validated slug + type\n // above, which is enough for the runtime path).\n return o as unknown as FieldDefBody;\n}\n\nexport class FieldSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'FieldSpecError';\n }\n}\n\nfunction quote(s: string): string {\n return `\\`${s}\\``;\n}\n","/**\n * `dashwise table create <slug> --field <spec>... [--field-json <json>...]`\n *\n * HH-CC-LDI-8 — create a new table in the current module's manifest +\n * materialize it as a physical Postgres table in the dev installation.\n *\n * Flow (REST-first / write-back-from-GET):\n * 1. Load context (manifest slug, runtime token, install id).\n * 2. Parse `--field` + `--field-json` flags into a FieldDef array.\n * 3. POST /api/installations/:id/schema/tables (LDI-4 endpoint).\n * 4. GET /api/installations/:id/schema to fetch the new manifest.\n * 5. Write the response to local module.json.\n *\n * No local-mutation logic — the backend's `SchemaProposeService`\n * is the source of truth for the manifest shape after the operation.\n * If the POST succeeds but the GET fails, local module.json is left\n * stale; `dashwise dev` reconciles on next startup.\n */\n\nimport { writeManifest, type ManifestShape } from '../../lib/manifest-io.js';\nimport {\n ApiError,\n createTable,\n getInstallationSchema,\n type FieldDefBody,\n} from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface TableCreateOptions {\n dir?: string;\n field?: string[];\n fieldJson?: string[];\n}\n\nexport async function tableCreateCommand(\n slug: string | undefined,\n options: TableCreateOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table create <slug> --field <slug>:<type>[:required] [...]`');\n return 1;\n }\n\n // ── 1. Build the FieldDef array from --field + --field-json flags ──\n const fields: FieldDefBody[] = [];\n try {\n for (const spec of options.field ?? []) {\n fields.push(parseFieldSpec(spec));\n }\n for (const json of options.fieldJson ?? []) {\n fields.push(parseFieldJson(json));\n }\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n if (fields.length === 0) {\n fail(\n `At least one field is required. Use ${code('--field <slug>:<type>')} (repeatable) or ${code(\"--field-json '{...}'\")} for fields with options/target/default.`,\n );\n return 1;\n }\n\n // Detect duplicate slugs within the input (the backend also rejects\n // but a local check gives a clearer error than the round-trip).\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.slug)) {\n fail(`Duplicate field slug ${code(f.slug)} in --field flags.`);\n return 1;\n }\n seen.add(f.slug);\n }\n\n // ── 2. Load command context ────────────────────────────────────────\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 3. POST /api/installations/:id/schema/tables ───────────────────\n info(`Creating table ${code(slug)} in installation ${ctx.entry.installationId}…`);\n try {\n const result = await createTable(\n ctx.entry.installationId,\n { slug, fields },\n ctx.requestOptions,\n );\n success(\n `Created table ${code(slug)} (physical_table_id=${result.physical_table_id}, manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n // ── 4. GET /schema + write back to local module.json ───────────────\n return syncLocalManifest(ctx);\n}\n\n/**\n * After a successful schema mutation, fetch the new server-side\n * manifest and write it to local `module.json`. Shared by every\n * schema-mutation command.\n *\n * Failure here is non-fatal — the mutation already succeeded\n * server-side, the local file just gets stale. We surface a warning\n * + tell the user to retry via `dashwise module reconcile` (future\n * LDI-9 sub-command) OR they can re-run their next `dashwise dev`\n * which will pick up the latest manifest automatically.\n */\nexport async function syncLocalManifest(\n ctx: ReturnType<typeof loadSchemaCommandContext>,\n): Promise<number> {\n try {\n const { manifest } = await getInstallationSchema(\n ctx.entry.installationId,\n ctx.requestOptions,\n );\n writeManifest(manifest as ManifestShape, ctx.projectRoot);\n return 0;\n } catch (err) {\n if (err instanceof ApiError) {\n warn(\n `Schema sync to local module.json failed (${err.code} ${err.status}): ${err.message}. The mutation succeeded server-side; re-run your next command to retry the local sync.`,\n );\n } else {\n warn(\n `Schema sync to local module.json failed: ${(err as Error).message}. The mutation succeeded server-side.`,\n );\n }\n // Exit 0 — the operation succeeded, only the local sync didn't.\n return 0;\n }\n}\n\n/**\n * Translate an ApiError from a schema-mutation REST call into a\n * user-facing failure message. Reused by every table/field command\n * since they all surface the same set of codes from\n * `SchemaProposeService → InstallationSchemaController.mapServiceError`.\n */\nexport function surfaceFailure(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'TABLE_SLUG_EXISTS':\n fail(`A table with this slug already exists in the manifest.`);\n break;\n case 'FIELD_SLUG_EXISTS':\n fail(`A field with this slug already exists on the table.`);\n break;\n case 'TABLE_NOT_FOUND':\n fail(`Table not found in the manifest.`);\n break;\n case 'FIELD_NOT_FOUND':\n fail(`Field not found on the table.`);\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Runtime token rejected by backend. The cached token may be expired — re-run \\`dashwise init <slug> --force\\` to mint a fresh one.`,\n );\n break;\n case 'SANDBOX_TOKEN_NOT_ACCEPTED':\n fail(\n `Schema-mutation endpoints require a local-dev runtime token (kind=local). The cached token is the wrong kind — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALL_MISMATCH':\n fail(\n `Runtime token is bound to a different installation than the URL. The cached install id may be stale — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise table delete <slug>`\n *\n * HH-CC-LDI-8 — drop a table from the current module. Calls LDI-4's\n * `DELETE /api/installations/:id/schema/tables/:tableSlug`, which\n * (via the backend's `applyManifestDelta`) soft-deletes the physical\n * table — recoverable for 30 days through the dashboard's trash.\n *\n * Same REST-first / write-back-from-GET pattern as `table create`.\n */\n\nimport { dropTable } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from './create.js';\n\nexport interface TableDeleteOptions {\n dir?: string;\n}\n\nexport async function tableDeleteCommand(\n slug: string | undefined,\n options: TableDeleteOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table delete <slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(`Dropping table ${code(slug)} from installation ${ctx.entry.installationId}…`);\n try {\n const result = await dropTable(\n ctx.entry.installationId,\n slug,\n ctx.requestOptions,\n );\n success(\n `Dropped table ${code(slug)} (manifest_version=${result.manifest_version}). Physical table soft-deleted; recoverable for 30 days via the dashboard's trash.`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field add <table-slug> <field-spec>`\n *\n * HH-CC-LDI-8 — add a new field to an existing table. The field spec\n * uses the same `<slug>:<type>[:flags]` syntax as `dashwise table\n * create --field`, OR the `--field-json '{...}'` escape hatch for\n * options/target/default.\n *\n * Examples:\n * dashwise field add tasks title:text:required\n * dashwise field add tasks done:boolean\n * dashwise field add tasks priority --field-json '{\"slug\":\"priority\",\"type\":\"single_select\",\"options\":[\"low\",\"medium\",\"high\"]}'\n *\n * REST-first / write-back-from-GET pattern (same as `table create`).\n */\n\nimport { addField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldAddOptions {\n dir?: string;\n fieldJson?: string;\n}\n\nexport async function fieldAddCommand(\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n options: FieldAddOptions,\n): Promise<number> {\n if (!tableSlug) {\n fail(\n 'Usage: `dashwise field add <table-slug> <field-slug>:<type>[:required]` or `dashwise field add <table-slug> --field-json \\'{...}\\'`',\n );\n return 1;\n }\n\n // The field can come from either the positional `<spec>` arg OR\n // `--field-json`. Exactly one must be supplied; both would be\n // ambiguous (which wins?).\n const hasPositional = fieldSpec !== undefined;\n const hasJson = options.fieldJson !== undefined;\n if (!hasPositional && !hasJson) {\n fail(\n `Pass either a field spec (e.g. ${code('title:text:required')}) or ${code('--field-json')} with the field's JSON definition.`,\n );\n return 1;\n }\n if (hasPositional && hasJson) {\n fail(\n `Pass only ONE of the field spec or ${code('--field-json')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n let field;\n try {\n field = hasJson\n ? parseFieldJson(options.fieldJson!)\n : parseFieldSpec(fieldSpec!);\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Adding field ${code(`${tableSlug}.${field.slug}`)} (${field.type}) to installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await addField(\n ctx.entry.installationId,\n { table_slug: tableSlug, field },\n ctx.requestOptions,\n );\n success(\n `Added field ${code(`${tableSlug}.${field.slug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field remove <table-slug> <field-slug>`\n *\n * HH-CC-LDI-8 — remove a field from a table. The backend's\n * `proposeField(operation='remove')` includes the M2-C-FIX\n * cascading-index-cleanup: any index referencing the removed field\n * is trimmed, and if the index becomes empty it's dropped entirely.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { removeField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldRemoveOptions {\n dir?: string;\n}\n\nexport async function fieldRemoveCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n options: FieldRemoveOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug) {\n fail('Usage: `dashwise field remove <table-slug> <field-slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Removing field ${code(`${tableSlug}.${fieldSlug}`)} from installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await removeField(\n ctx.entry.installationId,\n tableSlug,\n fieldSlug,\n ctx.requestOptions,\n );\n success(\n `Removed field ${code(`${tableSlug}.${fieldSlug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field set-type <table-slug> <field-slug> <new-type>`\n *\n * HH-CC-LDI-8 — change an existing field's type. Maps to LDI-4's\n * `PATCH /api/installations/:id/schema/fields/:tableSlug/:fieldSlug`\n * with the new type passed in the body.\n *\n * Lossy type changes (text → number with non-numeric data; multi_select\n * → single_select with multi-value rows) are deferred to v1.1 per\n * `local-dev-installs-v1.md` §8.2 — the backend's manifest validator\n * rejects the unsafe cases today; v1.1 adds a structured\n * `RETYPE_UNSAFE` precheck.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { updateField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { FIELD_TYPES } from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldSetTypeOptions {\n dir?: string;\n}\n\nexport async function fieldSetTypeCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n options: FieldSetTypeOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug || !newType) {\n fail(\n 'Usage: `dashwise field set-type <table-slug> <field-slug> <new-type>`',\n );\n return 1;\n }\n if (!(FIELD_TYPES as readonly string[]).includes(newType)) {\n fail(\n `Type ${code(newType)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Setting type of ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} on installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await updateField(\n ctx.entry.installationId,\n tableSlug,\n fieldSlug,\n { type: newType },\n ctx.requestOptions,\n );\n success(\n `Updated ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise dev` — the one-command local dev loop.\n *\n * What it does:\n * 1. Verifies the developer has run `dashwise login` (i.e. the auth.json\n * config file exists). Bails with a clear pointer otherwise.\n * 2. Resolves `DASHWISE_API_URL`, `DASHWISE_API_TOKEN`,\n * `DASHWISE_INSTALLATION_ID` from (a) explicit flags, (b) existing\n * env vars, (c) the saved CLI config — and injects them into BOTH\n * child processes' env so the SDK can authenticate without the\n * developer ever touching `.env.local`.\n * 3. Spawns two children:\n * - `dashwise module dev` — manifest watcher + SDK regen loop\n * - `next dev` — Next.js dev server\n * Both stdout/stderr streams are line-prefixed with `[sdk]` and\n * `[next]` so a single terminal can show both subsystems' output\n * without confusion.\n * 4. Forwards SIGINT/SIGTERM to both children, waits for them to exit,\n * then exits itself with the worst child's exit code (so CI catches\n * a crash on either side).\n *\n * Why two child processes rather than running `module dev` in-process:\n * - Symmetric output prefixing — same code path handles both.\n * - Signal isolation — Ctrl-C is forwarded cleanly to both, neither\n * can interfere with the other's shutdown by throwing async.\n * - Failure isolation — a crash in `module dev`'s generator can't\n * take down `next dev` or vice versa; users see a clear \"[sdk]\n * exited with code 1, [next] still running\" line.\n *\n * The Next.js process gets spawned via `npx next dev` (or the project's\n * own `dev:next` script if present), which avoids hard-coding a path\n * to the user's local node_modules.\n */\n\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve as resolvePath } from 'node:path';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport { readConfig, readModuleEntry } from '../lib/config.js';\nimport { readManifest } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../lib/output.js';\n\nexport interface DevCommandOptions {\n /** Project directory containing `module.json`. Defaults to cwd. */\n dir?: string;\n /**\n * Override the `DASHWISE_INSTALLATION_ID` env var passed to children.\n *\n * When set to a real installation id (numeric), prod-mode SSO is used\n * — the SDK's middleware hits `/api/auth/sso/start?client_id=<id>`\n * and that installation must already exist in your workspace.\n *\n * When NOT set (the default), `dashwise dev` registers a dev session\n * with the backend and injects `DASHWISE_DEV_SESSION_ID` instead —\n * no installation required (see auth/spec.md § Dev-Mode SSO).\n */\n installationId?: string;\n /**\n * Override the `DASHWISE_API_URL` env var passed to children.\n * Defaults to the saved CLI config's `apiUrl`.\n */\n apiUrl?: string;\n /**\n * Port for `next dev`. Defaults to 3000 — used both for the child\n * spawn AND for computing the default dev-session callback origin\n * (`http://localhost:<port>`).\n */\n port?: number;\n /**\n * Workspace to scope the dev session to. Either a numeric id (`'42'`)\n * or a slug (`'my-workspace'`). When omitted, defaults to the user's\n * primary workspace if they have only one; errors out asking for an\n * explicit `--workspace` if they have multiple.\n *\n * Only relevant when using dev-mode SSO (the default — ignored if\n * `--installation-id` is passed).\n */\n workspace?: string;\n /**\n * Additional callback origins to allowlist on the dev session, beyond\n * the default `http://localhost:<port>`. Repeatable.\n *\n * Example: `--callback-origin https://myapp.local` for custom-domain\n * local dev. Each origin must be a fully-qualified http(s) URL.\n *\n * Only relevant when using dev-mode SSO.\n */\n callbackOrigin?: string[];\n /**\n * Skip the Next.js dev server — only run the manifest watcher.\n * Useful if the developer is running `next dev` separately for\n * some reason (e.g. they want a debugger attached to it).\n */\n sdkOnly?: boolean;\n /**\n * Skip the manifest watcher — only run `next dev`. Symmetric escape\n * hatch to `--sdk-only`.\n */\n nextOnly?: boolean;\n}\n\n/**\n * Default port for the scaffolded Next.js dev server. Used both for\n * the `--port` default AND for computing the default callback origin\n * passed to `POST /api/auth/dev/sessions`. Single source of truth —\n * if the user overrides one without the other, the dev session's\n * allowlist won't match the actual dev server origin and SSO fails\n * with `INVALID_RETURN_TO`.\n */\nconst DEFAULT_NEXT_PORT = 3000;\n\n/**\n * ANSI-styled prefix prepended to every line of a child's output.\n * Colors are kept faint so a long dev session doesn't strain the eye.\n *\n * `[sdk]` is cyan-ish, `[next]` is magenta-ish — they map cleanly to\n * the two subsystems and stay distinguishable on dark + light terminals.\n */\nconst PREFIX_SDK = `\\x1b[36m[sdk]\\x1b[0m `;\nconst PREFIX_NEXT = `\\x1b[35m[next]\\x1b[0m `;\n\nexport async function devCommand(\n options: DevCommandOptions,\n): Promise<number> {\n if (options.sdkOnly && options.nextOnly) {\n fail(\n `Cannot pass both ${code('--sdk-only')} and ${code('--next-only')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifestPath = `${projectRoot}/module.json`;\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info(`Run ${code('dashwise module init <slug>')} to scaffold a new module first.`);\n return 1;\n }\n\n // HH-CC-LDI-7: read the manifest to learn this module's slug, so we\n // can look up its per-module runtime token from auth.json#modules[slug].\n // Failing to parse the manifest isn't fatal — `module dev` will catch\n // it downstream with a clearer error message. We just lose the\n // runtime-token injection in that case.\n const manifestSlug = (() => {\n try {\n return readManifest(projectRoot)?.module?.slug;\n } catch {\n return undefined;\n }\n })();\n\n // ── 1. Auth resolution ───────────────────────────────────────────────\n // Saved config is the source of truth; --api-url / env can override\n // individual fields. Refuse to start if no auth at all — the dev\n // server would just 401 on every request.\n const savedConfig = (() => {\n try {\n return readConfig();\n } catch {\n // Corrupt config — treat as if not logged in. The login command\n // will surface the real error if re-run.\n return null;\n }\n })();\n\n const apiToken = process.env.DASHWISE_API_TOKEN ?? savedConfig?.token;\n if (!apiToken) {\n fail(`Not authenticated. Run ${code('dashwise login')} first.`);\n info(\n 'The unified dev loop reads your CLI token from ~/.config/dashwise/auth.json ' +\n 'and injects it into both child processes so the SDK can authenticate ' +\n 'without you editing .env.local.',\n );\n return 1;\n }\n const apiUrl =\n options.apiUrl ??\n process.env.DASHWISE_API_URL ??\n savedConfig?.apiUrl ??\n 'http://localhost:3000';\n const port = options.port ?? DEFAULT_NEXT_PORT;\n\n // ── 2. Resolve auth mode ─────────────────────────────────────────────\n // Three paths, in priority order:\n //\n // (a) `--installation-id <id>` (or `DASHWISE_INSTALLATION_ID` env)\n // — prod-like mode. SDK's sign-in route uses /sso/start with\n // client_id=<id>. The installation must already exist.\n //\n // (b) `DASHWISE_DEV_SESSION_ID` env set (e.g. for testing) — reuse\n // the existing dev session id without re-registering.\n //\n // (c) Default — register a fresh dev session with the backend,\n // inject DASHWISE_DEV_SESSION_ID into the child env, revoke\n // on graceful shutdown.\n const explicitInstallationId =\n options.installationId ?? process.env.DASHWISE_INSTALLATION_ID;\n const reuseDevSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n // HH-CC-LDI-7: per-module runtime-token lookup. We read it BEFORE\n // the auth-mode branching below so the path can branch on its\n // presence — but we don't make the runtime token gate dev-session\n // setup. The two are orthogonal: the dev session powers SSO sign-in\n // callbacks for end users hitting the running module; the runtime\n // token powers the SDK's data-plane calls. Both can be active\n // simultaneously.\n const moduleEntry =\n manifestSlug !== undefined ? readModuleEntry(manifestSlug) : null;\n const runtimeTokenEnv = process.env.DASHWISE_RUNTIME_TOKEN ?? moduleEntry?.runtimeToken;\n\n let installationIdEnv: string | undefined;\n let devSessionIdEnv: string | undefined;\n let revokeDevSession: (() => Promise<void>) | undefined;\n\n if (explicitInstallationId && explicitInstallationId !== 'local') {\n installationIdEnv = explicitInstallationId;\n } else if (reuseDevSessionId) {\n devSessionIdEnv = reuseDevSessionId;\n } else {\n // Default — register a dev session.\n let workspaceContext: { id: number; name: string; slug: string };\n try {\n workspaceContext = await resolveTargetWorkspace(apiUrl, apiToken, options.workspace);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n const callbackOrigins = computeCallbackOrigins(port, options.callbackOrigin ?? []);\n try {\n const session = await registerDevSession(apiUrl, apiToken, {\n target_workspace_id: workspaceContext.id,\n callback_origins: callbackOrigins,\n });\n devSessionIdEnv = session.id;\n revokeDevSession = () => revokeDevSessionBestEffort(apiUrl, apiToken, session.id);\n info(` ${dim('dev session')} ${session.id}`);\n info(` ${dim('workspace')} ${workspaceContext.name} (id=${workspaceContext.id}, slug=${workspaceContext.slug})`);\n info(` ${dim('callbacks')} ${callbackOrigins.join(', ')}`);\n info(` ${dim('expires')} ${session.expires_at}`);\n } catch (err) {\n if (err instanceof ApiError) {\n fail(`Failed to register dev session: ${err.code} — ${err.message}`);\n } else {\n fail(`Failed to register dev session: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // ── 3. Build child env ───────────────────────────────────────────────\n // Inherit the parent's env so user-set vars (e.g. NEXT_TELEMETRY_DISABLED,\n // NODE_OPTIONS) flow through unchanged. Overlay the DASHWISE_* vars\n // so the SDK can read them — these win over anything the user set\n // in .env.local because Next.js loads .env.local AFTER process.env.\n //\n // Set DASHWISE_INSTALLATION_ID to empty string when in dev mode so\n // the scaffolded sign-in route sees `process.env.DASHWISE_INSTALLATION_ID\n // === ''` (falsy) and correctly branches on DASHWISE_DEV_SESSION_ID\n // instead — without explicitly unsetting an inherited value.\n //\n // HH-CC-LDI-7: when a per-module runtime token is available (from\n // auth.json#modules[slug] written by `dashwise init`, or from a\n // DASHWISE_RUNTIME_TOKEN env override), inject it into the child env\n // so `@dashai/sdk`'s `createDevClient()` can pick it up for the\n // data plane. We also flip DASHWISE_INSTALLATION_ID to the literal\n // 'sandbox' (URL placeholder for runtime-token auth) WHEN no\n // explicit installation id is set — the backend's RuntimeTokenGuard\n // resolves the actual install from the JWT claims, not the URL.\n const childInstallationId =\n installationIdEnv ??\n (runtimeTokenEnv !== undefined ? 'sandbox' : '');\n const childEnv: Record<string, string | undefined> = {\n ...process.env,\n DASHWISE_API_URL: apiUrl,\n // HH-CC-FUP-3: client-side mirror. Next.js inlines NEXT_PUBLIC_*\n // env vars into the browser bundle at build time (or, in dev, at\n // process-start time). Without this, the SDK's <AuthProvider> hits\n // `/api/auth/sessions/me` on its own origin (localhost:<port>),\n // 404s, and stays unauthenticated. We mirror DASHWISE_API_URL so\n // the client + server agree on the backend origin without the\n // module author having to touch .env.local.\n NEXT_PUBLIC_DASHWISE_API_URL: apiUrl,\n DASHWISE_API_TOKEN: apiToken,\n DASHWISE_INSTALLATION_ID: childInstallationId,\n ...(devSessionIdEnv !== undefined ? { DASHWISE_DEV_SESSION_ID: devSessionIdEnv } : {}),\n ...(runtimeTokenEnv !== undefined\n ? { DASHWISE_RUNTIME_TOKEN: runtimeTokenEnv }\n : {}),\n };\n\n // ── 4. Pre-flight banner ─────────────────────────────────────────────\n info(`Dev loop starting — Ctrl-C to stop.`);\n info(` ${dim('api')} ${apiUrl}`);\n if (installationIdEnv !== undefined) {\n info(` ${dim('installation')} ${installationIdEnv} (prod-mode SSO)`);\n } else {\n info(` ${dim('mode')} dev (DASHWISE_DEV_SESSION_ID injected)`);\n }\n info(` ${dim('token')} ${maskedToken(apiToken)} ${dim(`(from ${apiToken === savedConfig?.token ? '~/.config/dashwise/auth.json' : '$DASHWISE_API_TOKEN'})`)}`);\n // HH-CC-LDI-7: surface the runtime-token source so developers know\n // which auth credentials the SDK will pick up. Three observable\n // states:\n // - cached: per-module entry in auth.json (the LDI-6 happy path)\n // - env: DASHWISE_RUNTIME_TOKEN explicit override\n // - missing: no runtime token; data-plane calls will fail with\n // UnauthenticatedError. Surface a hint to run `dashwise init`.\n if (runtimeTokenEnv !== undefined) {\n const source =\n process.env.DASHWISE_RUNTIME_TOKEN === runtimeTokenEnv\n ? '$DASHWISE_RUNTIME_TOKEN'\n : `~/.config/dashwise/auth.json#modules[${manifestSlug}]`;\n const installId = moduleEntry?.installationId;\n info(\n ` ${dim('runtime')} ${maskedToken(runtimeTokenEnv)} ${dim(`(from ${source}${installId ? `, install id=${installId}` : ''})`)}`,\n );\n } else if (manifestSlug !== undefined && installationIdEnv === undefined) {\n // No runtime token + no explicit install id → the SDK's data plane\n // will 401 on every call. Print a one-line hint so the dev knows\n // why; don't block the dev loop because SSO + scaffolding still\n // work without it.\n warn(\n `No runtime token cached for module ${code(manifestSlug)}. ` +\n `Data-plane calls (db, qb) will fail with UnauthenticatedError. ` +\n `Run ${code(`dashwise init ${manifestSlug} --force`)} to provision a dev install + cache the token.`,\n );\n }\n info('');\n\n // ── 4. Spawn children ────────────────────────────────────────────────\n const children: { name: string; child: ChildProcess; prefix: string }[] = [];\n\n if (!options.nextOnly) {\n const sdkChild = spawnSdkWatcher(projectRoot, childEnv);\n children.push({ name: 'sdk', child: sdkChild, prefix: PREFIX_SDK });\n }\n if (!options.sdkOnly) {\n // Always pass `port` (default DEFAULT_NEXT_PORT, overridden by\n // --port). This ensures the actual dev server port matches the\n // dev session's callback origin allowlist computed above.\n const nextChild = spawnNextDev(projectRoot, childEnv, port);\n children.push({ name: 'next', child: nextChild, prefix: PREFIX_NEXT });\n }\n\n // ── 5. Wire output multiplexing ──────────────────────────────────────\n for (const { child, prefix } of children) {\n pipeWithPrefix(child.stdout, process.stdout, prefix);\n pipeWithPrefix(child.stderr, process.stderr, prefix);\n }\n\n // ── 6. Signal forwarding + exit aggregation ─────────────────────────\n let shuttingDown = false;\n const forwardSignal = (sig: NodeJS.Signals) => {\n if (shuttingDown) return;\n shuttingDown = true;\n info(`\\nReceived ${sig}, stopping children…`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill(sig);\n }\n }\n // Best-effort revoke the dev session — fire-and-forget so we\n // don't delay shutdown if the API is slow. If the request fails\n // (offline, backend down, etc.) the dev session naturally expires\n // in 24h, so the leftover is harmless.\n if (revokeDevSession) {\n revokeDevSession().catch(() => {\n /* swallowed — best-effort */\n });\n }\n };\n process.on('SIGINT', () => forwardSignal('SIGINT'));\n process.on('SIGTERM', () => forwardSignal('SIGTERM'));\n\n // Wait for each child's exit. Aggregate exit codes — if either fails\n // non-zero (and we didn't kill it intentionally), surface the worst\n // code so CI catches a crash.\n const results = await Promise.all(\n children.map(\n ({ name, child }) =>\n new Promise<{ name: string; code: number; killed: boolean }>(\n (resolveExit) => {\n child.on('exit', (exitCode, signal) => {\n const killed = signal !== null;\n const finalCode =\n exitCode ?? (killed ? 0 : 1); // signal-only exit treated as clean\n resolveExit({ name, code: finalCode, killed });\n });\n },\n ),\n ),\n );\n\n // If ANY child exits non-zero AND wasn't killed by our signal forward,\n // kill the others so we don't leave orphans. Then aggregate.\n const crashed = results.find((r) => !r.killed && r.code !== 0);\n if (crashed && !shuttingDown) {\n warn(`[${crashed.name}] exited with code ${crashed.code} — stopping others.`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill('SIGTERM');\n }\n }\n }\n\n const exitCode = Math.max(0, ...results.map((r) => r.code));\n if (exitCode === 0) {\n success('Dev loop stopped cleanly.');\n }\n return exitCode;\n}\n\n// ── Internals ───────────────────────────────────────────────────────────\n\n/**\n * Spawn `dashwise module dev` as a child. We re-exec the same CLI binary\n * via `process.execPath` + `process.argv[1]` so we never depend on the\n * binary being on $PATH (npm-install-globally is common but not\n * universal; pnpm workspace setups can put the bin in a non-PATH\n * directory).\n *\n * The child inherits stdio for stdin (so a future interactive-prompt\n * inside `module dev` could still work), but stdout/stderr are piped so\n * we can prefix the lines.\n */\nfunction spawnSdkWatcher(\n projectRoot: string,\n env: Record<string, string | undefined>,\n): ChildProcess {\n const child = spawn(\n process.execPath,\n [process.argv[1]!, 'module', 'dev', '--dir', projectRoot],\n {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n );\n return child;\n}\n\n/**\n * Spawn `next dev`. We prefer the project's `dev:next` npm script (which\n * the scaffold writes out) so the dev experience stays consistent with\n * what a user gets when running `npm run dev:next` directly. Falls back\n * to `npx next dev` if no script is defined.\n *\n * Pass `--port` explicitly if the caller asked, otherwise let Next pick\n * its default (3000 by default; Next falls forward to 3001/3002/...\n * when the port is taken — our local backend usually owns 3000).\n */\nfunction spawnNextDev(\n projectRoot: string,\n env: Record<string, string | undefined>,\n port: number | undefined,\n): ChildProcess {\n const portArgs = port !== undefined ? ['--', '--port', String(port)] : [];\n const hasDevNextScript = hasNpmScript(projectRoot, 'dev:next');\n // npm/yarn/pnpm differ on how they locate `next` — the safest cross-tool\n // path is to delegate to the project's own package manager via `npm run\n // dev:next`. If the script is missing, fall back to `npx next dev`.\n const [cmd, args] = hasDevNextScript\n ? ['npm', ['run', 'dev:next', ...portArgs]]\n : ['npx', ['next', 'dev', ...(port !== undefined ? ['--port', String(port)] : [])]];\n\n const child = spawn(cmd, args, {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Windows requires `shell: true` for `npm` / `npx` because they're\n // `.cmd` shims, not real binaries.\n shell: process.platform === 'win32',\n });\n return child;\n}\n\n/**\n * Read the project's `package.json` and check whether the named script\n * exists. Returns false on any error (missing package.json, malformed\n * JSON, etc.) — the caller falls back to npx in that case.\n */\nfunction hasNpmScript(projectRoot: string, scriptName: string): boolean {\n try {\n const pkgPath = `${projectRoot}/package.json`;\n if (!existsSync(pkgPath)) return false;\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n return typeof pkg.scripts?.[scriptName] === 'string';\n } catch {\n return false;\n }\n}\n\n/**\n * Pipe a child's readable stream into our output stream, prefixing each\n * line with the given prefix. Uses line-buffered prefixing: partial\n * lines (no trailing newline) get prefixed too so e.g. spinner output\n * still surfaces — but if a child emits a stream of \\r-overwrites for a\n * fancy progress bar, the prefix collapses correctly because we re-emit\n * the partial line as-is.\n *\n * Edge case: if the stream is null (child was spawned without piping),\n * silently no-op. Real spawn calls above always pipe both, so this is\n * defence-in-depth.\n */\nfunction pipeWithPrefix(\n src: NodeJS.ReadableStream | null,\n dst: NodeJS.WritableStream,\n prefix: string,\n): void {\n if (!src) return;\n let leftover = '';\n src.on('data', (chunk: Buffer | string) => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');\n const combined = leftover + text;\n const lines = combined.split('\\n');\n leftover = lines.pop() ?? '';\n for (const line of lines) {\n dst.write(`${prefix}${line}\\n`);\n }\n });\n src.on('end', () => {\n if (leftover.length > 0) {\n dst.write(`${prefix}${leftover}\\n`);\n }\n });\n}\n\n/**\n * Mask a bearer token for log display. Shows the prefix (so users can\n * recognize WHICH token is being used — `dwc_*` vs JWT etc.) and a\n * 4-char tail (for distinguishing between two tokens at a glance) but\n * never the middle.\n */\nfunction maskedToken(token: string): string {\n if (token.length <= 12) return '****';\n const prefix = token.slice(0, 4);\n const tail = token.slice(-4);\n return `${prefix}…${tail}`;\n}\n\n// ── Dev-Mode SSO session lifecycle ──────────────────────────────────────\n\ninterface WorkspaceListItem {\n id: number;\n name: string;\n slug: string;\n}\n\ninterface DevSessionApiResponse {\n id: string;\n target_workspace_id: number;\n allowed_callback_origins: string[];\n expires_at: string;\n}\n\n/**\n * Compute the dev session's allowed callback origins. Defaults to the\n * dev server's bind URL (`http://localhost:<port>`); the user can add\n * more via `--callback-origin <url>` (repeatable).\n *\n * Backend validates each entry is a well-formed http(s) URL — we do\n * NOT pre-validate here; let the BE's error response (with code\n * `INVALID_CALLBACK_ORIGIN`) be the source of truth.\n */\nfunction computeCallbackOrigins(port: number, extra: string[]): string[] {\n const def = `http://localhost:${port}`;\n // De-dup: prevent the BE from rejecting a list with redundant\n // entries (the BE doesn't reject — it stores them as-is — but\n // sending unique values is the kinder client behavior).\n return Array.from(new Set([def, ...extra]));\n}\n\n/**\n * Resolve the target workspace for the dev session, given the\n * optional `--workspace` flag. Three paths:\n *\n * - Flag is numeric → treat as id, fetch by id.\n * - Flag is non-numeric → treat as slug, look up.\n * - Flag absent → list user's workspaces. If exactly 1, auto-pick.\n * If 0, error. If >1, error with a list so the user can pick.\n *\n * Returns `{ id, name, slug }` for the chosen workspace.\n */\nasync function resolveTargetWorkspace(\n apiUrl: string,\n apiToken: string,\n flag: string | undefined,\n): Promise<{ id: number; name: string; slug: string }> {\n const workspaces = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n if (flag === undefined) {\n if (workspaces.length === 1) {\n return workspaces[0];\n }\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`).join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n }\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(\n `No workspace matching --workspace=${flag}. Available:\\n${list}`,\n );\n }\n return match;\n}\n\n/**\n * `POST /api/auth/dev/sessions`. CLI-token authenticated. Returns the\n * dev session row the SDK keys off of.\n */\nasync function registerDevSession(\n apiUrl: string,\n apiToken: string,\n body: { target_workspace_id: number; callback_origins: string[] },\n): Promise<DevSessionApiResponse> {\n return apiRequest<DevSessionApiResponse>(\n 'POST',\n '/api/auth/dev/sessions',\n body,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n\n/**\n * `DELETE /api/auth/dev/sessions/:id`. Best-effort — errors are\n * swallowed by the caller. If the call fails (offline, BE down,\n * CLI token revoked since registration), the session naturally\n * expires within 24h so leaving it is harmless.\n */\nasync function revokeDevSessionBestEffort(\n apiUrl: string,\n apiToken: string,\n id: string,\n): Promise<void> {\n await apiRequest<void>(\n 'DELETE',\n `/api/auth/dev/sessions/${encodeURIComponent(id)}`,\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n","/**\n * `dashwise login` — OAuth 2.0 Device Authorization Grant.\n *\n * Flow:\n * 1. POST /api/auth/cli/device-code → get `userCode` + `verificationUri`\n * 2. Display the code + URL; offer to open the browser\n * 3. Poll /api/auth/cli/poll on the published interval until the\n * user approves (or denies / it expires)\n * 4. On `approved`, save the returned token to ~/.config/dashwise/auth.json\n * 5. Fetch /api/auth/me to confirm + cache user identity\n *\n * UX: clack spinner during the poll loop; explicit prompts when\n * something needs the user's attention (e.g. opening the browser).\n * Non-interactive mode (`--no-prompt`) skips browser-open + just\n * prints the URL.\n */\n\nimport { cancel, intro, isCancel, log, outro, select, spinner } from '@clack/prompts';\nimport open from 'open';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type {\n AuthMeResponse,\n CliDeviceCodeResponse,\n CliPollResponse,\n} from '../lib/backend-types.js';\nimport { resolveApiUrl, writeConfig, type CliConfig } from '../lib/config.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\nexport interface LoginOptions {\n /** Override the backend URL for this login (`--api-url`). */\n apiUrl?: string;\n /** Skip the \"open in browser\" prompt; just print the URL. */\n noPrompt?: boolean;\n /** Token name to suggest to the backend (shown in `me/cli-tokens`). */\n name?: string;\n}\n\nconst DEFAULT_TOKEN_NAME = 'dashwise-cli';\n\nexport async function loginCommand(options: LoginOptions): Promise<number> {\n const apiUrl = (options.apiUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n intro(`Logging into ${code(apiUrl)}`);\n\n // 1. Kick off the device-code grant.\n let dc: CliDeviceCodeResponse;\n try {\n dc = await apiRequest<CliDeviceCodeResponse>(\n 'POST',\n '/api/auth/cli/device-code',\n {\n name: options.name ?? DEFAULT_TOKEN_NAME,\n },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n fail(formatApiError('Could not start login flow', err));\n return 1;\n }\n\n log.message(\n [\n `Open the verification URL and confirm the code:`,\n ``,\n ` URL: ${code(dc.verificationUriComplete)}`,\n ` Code: ${code(dc.userCode)}`,\n ``,\n dim(\n `Code expires in ${formatSeconds(dc.expiresIn)}. The CLI will keep polling until you approve.`,\n ),\n ].join('\\n'),\n );\n\n // 2. Offer to open the browser (skipped in non-interactive mode).\n if (!options.noPrompt && process.stdout.isTTY) {\n const choice = await select({\n message: 'Open the verification URL in your browser?',\n options: [\n { value: 'open', label: 'Open now' },\n { value: 'skip', label: 'I’ll open it manually' },\n ],\n initialValue: 'open',\n });\n if (isCancel(choice)) {\n cancel('Login cancelled.');\n return 130; // SIGINT-equivalent exit code\n }\n if (choice === 'open') {\n try {\n await open(dc.verificationUriComplete);\n } catch (err) {\n info(`Could not open browser automatically (${(err as Error).message}). Open the URL above manually.`);\n }\n }\n }\n\n // 3. Poll until approved / denied / expired / overall deadline.\n const sp = spinner();\n sp.start('Waiting for approval');\n const overallDeadline = Date.now() + dc.expiresIn * 1000;\n let outcome: CliPollResponse | null = null;\n // Use 1s sleeps + let the backend's `slow_down` response push us\n // back if we exceed the published interval. Cheap; no need to be\n // clever with the polling cadence.\n const pollIntervalMs = Math.max(1000, dc.interval * 1000);\n\n pollLoop: while (Date.now() < overallDeadline) {\n let res: CliPollResponse;\n try {\n res = await apiRequest<CliPollResponse>(\n 'POST',\n '/api/auth/cli/poll',\n { deviceCode: dc.deviceCode },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n sp.stop(`Poll failed: ${(err as Error).message}`);\n fail('Poll failed mid-flight; you can re-run `dashwise login` to retry.');\n return 1;\n }\n switch (res.status) {\n case 'pending':\n case 'slow_down':\n await sleep(pollIntervalMs);\n continue pollLoop;\n case 'denied':\n sp.stop('Login denied by user.');\n cancel('Aborted.');\n return 1;\n case 'expired':\n sp.stop('Login code expired.');\n fail('The code expired before approval. Run `dashwise login` again.');\n return 1;\n case 'approved':\n outcome = res;\n break pollLoop;\n }\n }\n\n if (!outcome) {\n sp.stop('Timed out waiting for approval.');\n fail('Login took too long to be approved. Run `dashwise login` again.');\n return 1;\n }\n\n if (!outcome.token || !outcome.tokenId) {\n // Shouldn't happen on a fresh approval — but guard anyway.\n sp.stop('Approval received but token missing from response.');\n fail(\n 'Approval received but the backend did not return a token. Run `dashwise logout` then `dashwise login` to retry.',\n );\n return 1;\n }\n\n // 4. Confirm the token works + cache the profile.\n let me: AuthMeResponse;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me', undefined, {\n auth: { token: outcome.token },\n baseUrl: apiUrl,\n });\n } catch (err) {\n sp.stop('Approval accepted but profile fetch failed.');\n fail(formatApiError('Could not load user profile', err));\n return 1;\n }\n\n const cfg: CliConfig = {\n apiUrl,\n token: outcome.token,\n tokenId: outcome.tokenId,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(cfg);\n sp.stop('Approved.');\n success(`Logged in as ${code(me.email)}`);\n outro('You can now run `dashwise profile`, `dashwise workspace list`, etc.');\n return 0;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction formatSeconds(seconds: number): string {\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n return `${minutes}m`;\n}\n\nfunction formatApiError(prefix: string, err: unknown): string {\n if (err instanceof ApiError) {\n return `${prefix}: ${err.message} (code: ${err.code}, status: ${err.status})`;\n }\n if (err instanceof Error) return `${prefix}: ${err.message}`;\n return `${prefix}: ${String(err)}`;\n}\n","/**\n * `dashwise logout` — clear the local credentials and best-effort\n * revoke the server-side token row.\n *\n * Behavior:\n * 1. Read the saved config; if there's no token, exit 0 with an\n * info message (idempotent).\n * 2. Call `DELETE /api/auth/cli-tokens/:id` to revoke the row.\n * 404 / 403 / network errors are tolerated — the local file is\n * cleared regardless. We never want a server-side hiccup to\n * keep stale credentials on disk.\n * 3. Delete the local config file.\n */\n\nimport { apiRequest } from '../lib/api-client.js';\nimport { deleteConfig, readConfig } from '../lib/config.js';\nimport { code, info, success, warn } from '../lib/output.js';\n\nexport async function logoutCommand(): Promise<number> {\n let cfg;\n try {\n cfg = readConfig();\n } catch {\n // Corrupt file — clearing it is precisely what `logout` should do.\n deleteConfig();\n success('Cleared a corrupted local credential file.');\n return 0;\n }\n if (!cfg) {\n info('Already logged out (no saved credentials).');\n return 0;\n }\n\n // Best-effort server-side revocation.\n try {\n await apiRequest(\n 'DELETE',\n `/api/auth/cli-tokens/${cfg.tokenId}`,\n undefined,\n { auth: { token: cfg.token }, baseUrl: cfg.apiUrl },\n );\n } catch (err) {\n warn(\n `Could not revoke the server-side token (${(err as Error).message}). Local credentials cleared anyway.`,\n );\n }\n\n deleteConfig();\n success(`Logged out ${code(cfg.user.email)}`);\n return 0;\n}\n","/**\n * `dashwise profile` — show the current user + (briefly) workspaces.\n *\n * Reads the saved config first so the basic identity prints\n * instantly; then makes a live `/api/auth/me` call to refresh the\n * cached profile (network errors are tolerated — we fall back to\n * the cached values and warn).\n *\n * Output is plain key/value to stdout so the command is pipeable\n * (e.g. `dashwise profile | grep email`). For machine-readable\n * output a future `--json` flag is the right call.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { AuthMeResponse, WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, warn } from '../lib/output.js';\n\nexport interface ProfileOptions {\n /** Emit the profile + workspaces as a single JSON object instead of human-readable kv pairs. */\n json?: boolean;\n}\n\nexport async function profileCommand(options: ProfileOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Refresh identity. Tolerate transient network errors.\n let me: AuthMeResponse | null = null;\n let refreshError: string | null = null;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n refreshError = (err as Error).message;\n if (!options.json) {\n warn(\n `Could not refresh profile from the server (${refreshError}). Showing cached values.`,\n );\n }\n }\n\n if (me) {\n // Persist any drift between cached + server values.\n const refreshed = {\n ...cfg,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(refreshed);\n }\n const u = (me ?? toMe(cfg.user));\n\n // Workspace list — best-effort.\n let workspaces: WorkspaceListItem[] = [];\n let workspaceError: string | null = null;\n try {\n const fetched = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n );\n workspaces = Array.isArray(fetched) ? fetched : [];\n } catch (err) {\n workspaceError = (err as Error).message;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n user: {\n id: u.id,\n username: u.username,\n email: u.email,\n first_name: u.first_name,\n last_name: u.last_name,\n },\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces,\n api_url: cfg.apiUrl,\n ...(refreshError ? { profile_refresh_error: refreshError } : {}),\n ...(workspaceError ? { workspaces_error: workspaceError } : {}),\n }),\n );\n return 0;\n }\n\n out('');\n kv('User ID', `${u.id}`);\n kv('Username', u.username);\n kv('Email', u.email);\n kv('Name', `${u.first_name} ${u.last_name}`.trim() || dim('(not set)'));\n\n out('');\n if (workspaceError) {\n warn(\n `Could not list workspaces (${workspaceError}). Try \\`dashwise workspace list\\`.`,\n );\n } else if (workspaces.length === 0) {\n info('No workspaces yet.');\n } else {\n kv('Workspaces', `${workspaces.length}`);\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const star = cfg.workspaceSlug === slug ? code(' (default)') : '';\n out(` - ${slug}${role ? dim(` [${role}]`) : ''}${star} ${dim(w.name)}`);\n }\n }\n\n out('');\n kv('API URL', cfg.apiUrl);\n return 0;\n}\n\nfunction toMe(cached: { id: number; email: string; username: string; firstName: string; lastName: string }): AuthMeResponse {\n return {\n id: cached.id,\n email: cached.email,\n username: cached.username,\n first_name: cached.firstName,\n last_name: cached.lastName,\n is_staff: false,\n is_active: true,\n date_joined: '',\n };\n}\n","/**\n * `dashwise workspace list` — list workspaces the user belongs to.\n * `dashwise workspace use <slug>` — set the default workspace (saved\n * to ~/.config/dashwise/auth.json).\n *\n * The \"default workspace\" is consumed by subsequent commands\n * (`module init`, `module publish`, etc.) so the user doesn't have\n * to pass `--workspace <slug>` every time. Persists across\n * `dashwise` invocations until `workspace use` is called again.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, success } from '../lib/output.js';\n\nexport interface WorkspaceListOptions {\n json?: boolean;\n}\n\nexport async function workspaceListCommand(options: WorkspaceListOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n let workspaces: WorkspaceListItem[];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces: Array.isArray(workspaces) ? workspaces : [],\n }),\n );\n return 0;\n }\n if (!Array.isArray(workspaces) || workspaces.length === 0) {\n info('No workspaces yet.');\n return 0;\n }\n out('');\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const isDefault = cfg.workspaceSlug === slug;\n const marker = isDefault ? code(' *') : ' ';\n out(`${marker} ${slug.padEnd(28)} ${dim(w.name)}${role ? dim(` [${role}]`) : ''}`);\n }\n out('');\n if (cfg.workspaceSlug) {\n info(`Default workspace: ${code(cfg.workspaceSlug)}`);\n } else {\n info('No default workspace set. Use `dashwise workspace use <slug>` to set one.');\n }\n return 0;\n}\n\nexport async function workspaceUseCommand(slug: string): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (typeof slug !== 'string' || slug.length === 0) {\n fail('Usage: `dashwise workspace use <slug>`');\n return 1;\n }\n // Validate the slug exists + the user has access. Avoids the\n // footgun of setting a default to a workspace the user can't\n // actually use.\n let workspaces: WorkspaceListItem[] = [];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n fail(`Could not validate the workspace (${(err as Error).message}).`);\n return 1;\n }\n const match = workspaces.find(\n (w) => w.slug === slug || `id:${w.id}` === slug || String(w.id) === slug,\n );\n if (!match) {\n fail(`Workspace ${code(slug)} not found in your accessible workspaces.`);\n out('');\n info('Run `dashwise workspace list` to see what you can choose.');\n return 1;\n }\n const matchedSlug = match.slug ?? `id:${match.id}`;\n writeConfig({ ...cfg, workspaceSlug: matchedSlug });\n success(`Default workspace set to ${code(matchedSlug)}`);\n kv('Name', match.name);\n if (match.role ?? match.permissions) {\n kv('Role', String(match.role ?? match.permissions));\n }\n return 0;\n}\n","/**\n * `dashwise module clone <slug>` — bring a published module's\n * source into a local directory.\n *\n * Two flavors based on what's available on the backend:\n *\n * 1. **Git mode** — when the module's published manifest carries\n * `repository.url`, we shell out to `git clone` to fetch the\n * source. This is the recommended path: full file history,\n * branch awareness, future `git pull` for updates.\n *\n * 2. **Manifest-only mode** — when no `repository.url` is set,\n * we write the published manifest into a fresh directory plus\n * a minimal scaffold (.gitignore, package.json, README) so the\n * user has a workable starting point. They can then layer\n * their own app code on top + run `dashwise module dev`.\n *\n * Refuses to write into a non-empty directory unless `--force` is\n * passed.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { gitignore, packageJson, packageJsonCustom } from '../../lib/scaffold.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\ninterface SourceMetadataResponse {\n module_slug: string;\n module_name: string;\n current_version: string | null;\n repository_url: string | null;\n manifest: Record<string, unknown> | null;\n}\n\nexport interface CloneOptions {\n /** Target directory (default: `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Skip git clone even when repository.url is set (use manifest mode). */\n noGit?: boolean;\n}\n\nexport async function moduleCloneCommand(\n slug: string,\n options: CloneOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise module clone <slug>`');\n return 1;\n }\n\n let meta: SourceMetadataResponse;\n try {\n meta = await apiRequest<SourceMetadataResponse>(\n 'GET',\n `/api/modules/${encodeURIComponent(slug)}/source-tarball`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 403) {\n fail(`No access to module ${code(slug)}. You must be a member of its owner workspace.`);\n return 1;\n }\n fail(`Could not fetch module metadata: ${(err as Error).message}`);\n return 1;\n }\n\n const target = resolve(options.dir ?? slug);\n\n // Refuse to overwrite an existing non-empty directory unless --force.\n if (existsSync(target)) {\n const entries = readdirSync(target);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(target)} is not empty. Pass ${code('--force')} to clone anyway.`,\n );\n return 1;\n }\n }\n\n // Decide between git mode + manifest-only fallback.\n const wantGit = !options.noGit && meta.repository_url !== null;\n if (wantGit) {\n return cloneViaGit(meta, target);\n }\n\n if (meta.repository_url !== null && options.noGit) {\n info(`--no-git: skipping git clone for ${code(meta.repository_url)}; writing manifest-only scaffold.`);\n } else {\n info(`Module ${code(slug)} has no ${code('repository.url')}; writing manifest-only scaffold.`);\n }\n return cloneViaManifest(slug, meta, target);\n}\n\n/**\n * Shell out to `git clone <url> <target>`. Inherits stdio so the\n * user sees git's progress + error messages directly. Returns 0 on\n * success, propagating git's exit code on failure.\n */\nfunction cloneViaGit(meta: SourceMetadataResponse, target: string): number {\n const repoUrl = meta.repository_url!;\n info(`Cloning ${code(repoUrl)} into ${code(target)}...`);\n const result = spawnSync('git', ['clone', repoUrl, target], {\n stdio: 'inherit',\n });\n if (result.error) {\n fail(`Failed to invoke git: ${result.error.message}`);\n return 1;\n }\n if (result.status !== 0) {\n fail(`git clone exited with status ${result.status}.`);\n return result.status ?? 1;\n }\n success(`Cloned ${code(meta.module_slug)} from ${code(repoUrl)}.`);\n if (meta.current_version) {\n info(`Current published version: ${code(`v${meta.current_version}`)}`);\n }\n return 0;\n}\n\n/**\n * Fallback when no Git URL is available: lay down `module.json` +\n * `.gitignore` + `package.json` + `README.md` so the user has a\n * starting point. The user has to recreate `app/` themselves —\n * we don't have access to the original source (no Git URL).\n */\nfunction cloneViaManifest(\n slug: string,\n meta: SourceMetadataResponse,\n target: string,\n): number {\n if (!meta.manifest) {\n fail(\n `Module ${code(slug)} has no published manifest yet (publish at least one version first).`,\n );\n return 1;\n }\n\n mkdirSync(target, { recursive: true });\n\n // Inspect the manifest to pick the right scaffold flavor.\n const manifestObj = meta.manifest as Record<string, unknown>;\n const moduleKind = manifestObj.module_kind === 'custom' ? 'custom' : 'hand_authored';\n const pkgFn = moduleKind === 'custom' ? packageJsonCustom : packageJson;\n\n writeFileSync(\n join(target, 'module.json'),\n JSON.stringify(manifestObj, null, 2) + '\\n',\n 'utf-8',\n );\n writeFileSync(\n join(target, 'package.json'),\n pkgFn({ slug: meta.module_slug, name: meta.module_name, kind: moduleKind }),\n 'utf-8',\n );\n writeFileSync(join(target, '.gitignore'), gitignore(), 'utf-8');\n writeFileSync(\n join(target, 'README.md'),\n readmeForClone(meta, moduleKind),\n 'utf-8',\n );\n\n success(`Wrote ${moduleKind} scaffold for ${code(meta.module_slug)} into ${code(target)}`);\n info(`Next steps:`);\n out('');\n out(` ${dim('1.')} ${code(`cd ${target}`)}`);\n out(` ${dim('2.')} ${code('npm install')}`);\n out(` ${dim('3.')} ${code('dashwise module generate')}`);\n out(` ${dim('4.')} Recreate your ${code('app/')} (manifest-only clone — no source code available).`);\n out('');\n if (meta.repository_url) {\n warn(\n `Module's manifest declared ${code(meta.repository_url)} as its repo; consider running ${code(`dashwise module clone ${slug}`)} without ${code('--no-git')} to get the full source.`,\n );\n } else {\n info(\n `If you have access to the original source, ` +\n `consider running ${code(`dashwise module connect-git <repo-url>`)} ` +\n `so future clones use it.`,\n );\n }\n return 0;\n}\n\nfunction readmeForClone(\n meta: SourceMetadataResponse,\n kind: 'hand_authored' | 'custom',\n): string {\n return `# ${meta.module_name}\n\nManifest-only clone of \\`${meta.module_slug}\\` (${kind}) at version \\`${meta.current_version ?? 'unpublished'}\\`.\n\nThe original source code wasn't available — this directory contains\nonly the published \\`module.json\\` + a starter scaffold. Recreate\n\\`app/\\` based on the manifest.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise module generate\ndashwise module dev\n\\`\\`\\`\n`;\n}\n","/**\n * `dashwise module connect-git <repo-url>` — write the Git repository\n * URL into the local `module.json#repository.url`.\n *\n * v1 scope: local manifest mutation only. The backend reads\n * `repository` from the manifest on the next `module publish` and\n * captures the URL + the actual `commit` + `branch` from the local\n * git working tree at publish time (P5b for the commit-capture\n * follow-up). For now, this command just sets the URL so the\n * marketplace + `module clone` know where to look.\n *\n * The URL is light-validated: must be a real URL, https:// or git@\n * shorthand also accepted. Branch can be passed via `--branch\n * <name>` to default to a non-`main` branch (rare, but common\n * for monorepos).\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface ConnectGitOptions {\n dir?: string;\n branch?: string;\n}\n\nexport async function moduleConnectGitCommand(\n repoUrl: string,\n options: ConnectGitOptions,\n): Promise<number> {\n if (!repoUrl || typeof repoUrl !== 'string') {\n fail('Usage: `dashwise module connect-git <repo-url>`');\n return 1;\n }\n if (!isPlausibleRepoUrl(repoUrl)) {\n fail(`Repo URL ${code(repoUrl)} doesn't look like https:// or git@host:owner/repo.`);\n return 1;\n }\n\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init\\` first.`,\n );\n return 1;\n }\n let manifest: Record<string, unknown>;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n const existing = (manifest.repository as Record<string, unknown> | undefined) ?? {};\n const next: Record<string, unknown> = {\n ...existing,\n type: 'git',\n url: repoUrl,\n };\n if (options.branch) {\n next.branch = options.branch;\n } else if (typeof existing.branch === 'string') {\n // Preserve any branch already set.\n next.branch = existing.branch;\n }\n manifest.repository = next;\n\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n success(`Connected to ${code(repoUrl)}`);\n if (next.branch) info(`Branch: ${code(String(next.branch))}`);\n info(`Updated ${code('module.json')}.`);\n return 0;\n}\n\n/**\n * Accept three URL shapes commonly used for Git remotes:\n * - https://github.com/org/repo\n * - https://github.com/org/repo.git\n * - git@github.com:org/repo.git\n *\n * Rejects obvious garbage; the backend (or git itself, at clone\n * time) does the real validation.\n */\nfunction isPlausibleRepoUrl(url: string): boolean {\n if (url.startsWith('https://') || url.startsWith('http://')) {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n // git@host:owner/repo[.git] shorthand\n return /^git@[^:]+:[^/]+\\/.+/.test(url);\n}\n","/**\n * `dashwise module generate` — regenerate the typed wrappers from the\n * local `module.json`.\n *\n * Flow:\n * 1. Read + parse `<cwd>/module.json`.\n * 2. POST it to `/api/modules/draft/generate-sdk`.\n * 3. Write each returned file to `node_modules/@dashai/generated/<path>`.\n * 4. Print summary (file count + content hash).\n *\n * Idempotent: re-running produces bit-identical output for an\n * unchanged manifest (per the generator's content-hash guarantee).\n * Returning a fresh generation counter on each call is reserved for\n * `module dev` — the one-shot CLI path uses generation=0.\n *\n * Requires the user to be logged in (uses the saved CLI token).\n */\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success } from '../../lib/output.js';\n\nexport interface GenerateOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** Monotonic counter passed to the generator (default 0). */\n generation?: number;\n /** Skip writing to node_modules — print summary only. */\n dryRun?: boolean;\n}\n\ninterface GenerateResponse {\n files: Record<string, string>;\n contentHash: string;\n}\n\n/** Resolved output directory: `<project>/node_modules/@dashai/generated/`. */\nfunction outputDir(projectRoot: string): string {\n return join(projectRoot, 'node_modules', '@dashai', 'generated');\n}\n\nexport async function moduleGenerateCommand(\n options: GenerateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n let res: GenerateResponse;\n try {\n res = await apiRequest<GenerateResponse>(\n 'POST',\n '/api/modules/draft/generate-sdk',\n {\n manifest,\n generation: options.generation ?? 0,\n },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 400) {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n process.stderr.write(JSON.stringify(err.context, null, 2) + '\\n');\n }\n return 1;\n }\n fail(`Could not generate SDK: ${(err as Error).message}`);\n return 1;\n }\n\n if (options.dryRun) {\n info(`Dry run: ${Object.keys(res.files).length} files`);\n info(`Hash: ${code(res.contentHash)}`);\n return 0;\n }\n\n const out = outputDir(projectRoot);\n // Wipe any prior generated content so a renamed/removed table\n // doesn't leave a stale wrapper file behind. The directory itself\n // is gitignored, so a wipe-then-rewrite is safe.\n if (existsSync(out)) {\n rmSync(out, { recursive: true, force: true });\n }\n mkdirSync(out, { recursive: true });\n for (const [relPath, content] of Object.entries(res.files)) {\n const absPath = join(out, relPath);\n const parent = dirname(absPath);\n if (!existsSync(parent)) {\n mkdirSync(parent, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Generated ${Object.keys(res.files).length} files into ${code('node_modules/@dashai/generated/')}`,\n );\n info(`Hash: ${dim(res.contentHash)}`);\n return 0;\n}\n","/**\n * `dashwise module dev` — watch `module.json` + auto-regenerate the\n * SDK on every change.\n *\n * Behavior:\n * 1. Read `module.json`; run an initial `module generate` so the\n * caller starts in a coherent state.\n * 2. Watch the manifest file for changes (`fs.watch`).\n * 3. On each change event, debounce 250ms (editor saves often\n * fire two events in quick succession), then regenerate.\n * 4. Bumps the `generation` counter per regen so the emitted\n * `package.json#version` shifts (`0.0.1-gen.N`), invalidating\n * any naïve caches keyed off it.\n * 5. Runs until Ctrl-C (clean exit on SIGINT/SIGTERM).\n *\n * Does NOT spawn `next dev` itself — the user runs that in another\n * terminal. Justification: `next dev`'s own output is dense + we\n * don't want to swallow/buffer it. If users want both, an\n * orchestrator like `npm-run-all` works (`npm run dev:next` and\n * `dashwise module dev` in parallel).\n */\n\nimport { existsSync, watch as fsWatch } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { moduleGenerateCommand } from './generate.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DevOptions {\n dir?: string;\n /** Debounce window in ms for filesystem change coalescing. */\n debounceMs?: number;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 250;\n\nexport async function moduleDevCommand(options: DevOptions): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info('Run `dashwise module init <slug>` to scaffold a new module.');\n return 1;\n }\n\n info(`Watching ${code(manifestPath)} — Ctrl-C to stop.`);\n\n // 1. Initial regen.\n let generation = 0;\n const initial = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n if (initial !== 0) {\n warn('Initial regen failed; watcher will retry on the next change.');\n }\n generation += 1;\n\n // 2. Watch loop with debounce. We deliberately use `fs.watch` (vs\n // chokidar) to keep deps small — chokidar weighs ~1MB packed, fs.watch\n // is built-in. Editor saves on macOS sometimes fire 2 events\n // back-to-back; the debounce coalesces them into one regen call.\n const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n let timer: NodeJS.Timeout | null = null;\n let isRunning = false;\n let pendingRegen = false;\n\n async function doRegen() {\n if (isRunning) {\n // Another regen is in flight — flag for re-run when it finishes.\n pendingRegen = true;\n return;\n }\n isRunning = true;\n try {\n const start = Date.now();\n const exit = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n const elapsedMs = Date.now() - start;\n if (exit === 0) {\n success(`Regen complete (${elapsedMs}ms, gen=${generation})`);\n } else {\n warn(`Regen failed (exit ${exit}, gen=${generation}) — will retry on next change.`);\n }\n generation += 1;\n } finally {\n isRunning = false;\n if (pendingRegen) {\n pendingRegen = false;\n // Schedule a follow-up — keeps the loop responsive when\n // the user saves rapidly.\n setImmediate(doRegen);\n }\n }\n }\n\n const watcher = fsWatch(manifestPath, (eventType) => {\n if (eventType !== 'change') return;\n if (timer !== null) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n void doRegen();\n }, debounceMs);\n });\n\n // Clean shutdown.\n return new Promise<number>((resolveExit) => {\n const stop = (signal: NodeJS.Signals | 'shutdown') => {\n if (timer !== null) clearTimeout(timer);\n watcher.close();\n info(`Stopping watcher${signal === 'shutdown' ? '' : ` (${signal})`}.`);\n // Use process.stdout flush hint to ensure the message lands\n // before exit.\n process.stdout.write(dim('Goodbye.\\n'));\n resolveExit(0);\n };\n process.once('SIGINT', () => stop('SIGINT'));\n process.once('SIGTERM', () => stop('SIGTERM'));\n });\n}\n","/**\n * `dashwise module diff` — preview what will change at the next\n * publish vs the currently-published version.\n *\n * Flow:\n * 1. Read local `module.json` for the slug.\n * 2. Resolve `slug → module.id` via `/api/modules/by-slug/:slug`.\n * 3. POST the local manifest to `/api/modules/:id/draft/diff`.\n * 4. Render the structured diff as a readable summary:\n * - \"unchanged\" short-circuit\n * - tables added/removed/changed\n * - dependencies added/removed\n * - top-level meta changes (version, name, module_kind, ...)\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out, success } from '../../lib/output.js';\n\ninterface FieldChange {\n field: string;\n changes: Record<string, unknown>;\n}\n\ninterface TableChange {\n table: string;\n fields_added: Array<{ slug: string; type: string }>;\n fields_removed: Array<{ slug: string; type: string }>;\n fields_changed: FieldChange[];\n}\n\ninterface DiffResponse {\n current_version: string | null;\n unchanged: boolean;\n meta_changes: Array<{ field: string; before: unknown; after: unknown }>;\n tables_added: string[];\n tables_removed: string[];\n tables_changed: TableChange[];\n deps_added: Array<{ module: string; version: string }>;\n deps_removed: Array<{ module: string; version: string }>;\n}\n\nexport interface DiffOptions {\n dir?: string;\n /** Emit the structured diff as JSON instead of the human-readable summary. */\n json?: boolean;\n}\n\nexport async function moduleDiffCommand(\n options: DiffOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NO_MANIFEST', message: `No module.json found in ${projectRoot}.` } }));\n } else {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n }\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_PARSE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n }\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_MISSING_SLUG', message: 'module.json is missing module.slug.' } }));\n } else {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n }\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number; current_version: string | null };\n try {\n mod = await apiRequest<{ id: number; current_version: string | null }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MODULE_NOT_FOUND', message: `Module ${slug} not found on the backend.` } }));\n } else {\n fail(\n `Module ${code(slug)} not found on the backend. Create + publish it first; `\n + `diff has nothing to compare against until then.`,\n );\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'RESOLVE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not resolve module: ${(err as Error).message}`);\n }\n return 1;\n }\n\n let diff: DiffResponse;\n try {\n diff = await apiRequest<DiffResponse>(\n 'POST',\n `/api/modules/${mod.id}/draft/diff`,\n { manifest },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'VALIDATION_FAILED', message: err.message, context: err.context ?? null } }));\n } else {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n out(JSON.stringify(err.context, null, 2));\n }\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not compute diff: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(JSON.stringify({ ok: true, ...diff }));\n return 0;\n }\n\n if (diff.unchanged) {\n success(\n `No changes vs ${code(diff.current_version ? `v${diff.current_version}` : '(unpublished)')} — manifest is in sync.`,\n );\n return 0;\n }\n\n // Header.\n out('');\n info(\n diff.current_version\n ? `Diff vs ${code(`v${diff.current_version}`)}:`\n : 'Diff vs ' + code('(unpublished — first version)') + ':',\n );\n\n if (diff.meta_changes.length > 0) {\n out('');\n out(code('Meta:'));\n for (const m of diff.meta_changes) {\n out(` ${m.field}: ${dim(JSON.stringify(m.before))} → ${JSON.stringify(m.after)}`);\n }\n }\n\n if (diff.tables_added.length > 0) {\n out('');\n out(code(`Tables added (${diff.tables_added.length}):`));\n for (const t of diff.tables_added) out(` + ${t}`);\n }\n\n if (diff.tables_removed.length > 0) {\n out('');\n out(code(`Tables removed (${diff.tables_removed.length}):`));\n for (const t of diff.tables_removed) out(` - ${t}`);\n }\n\n if (diff.tables_changed.length > 0) {\n out('');\n out(code(`Tables changed (${diff.tables_changed.length}):`));\n for (const t of diff.tables_changed) {\n out(` ${dim('•')} ${code(t.table)}`);\n for (const f of t.fields_added) {\n out(` + field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_removed) {\n out(` - field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_changed) {\n const changeSummary = Object.entries(f.changes)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n out(` ~ field ${f.field}: ${dim(changeSummary)}`);\n }\n }\n }\n\n if (diff.deps_added.length > 0) {\n out('');\n out(code(`Dependencies added (${diff.deps_added.length}):`));\n for (const d of diff.deps_added) {\n out(` + ${d.module}@${d.version}`);\n }\n }\n\n if (diff.deps_removed.length > 0) {\n out('');\n out(code(`Dependencies removed (${diff.deps_removed.length}):`));\n for (const d of diff.deps_removed) {\n out(` - ${d.module}@${d.version}`);\n }\n }\n\n out('');\n info('Run `dashwise module publish --bump <patch|minor|major>` when ready.');\n return 0;\n}\n","/**\n * `dashwise` CLI entry point.\n *\n * commander-based command tree. Each command sits in `./commands/`\n * and returns a numeric exit code; the entry handler awaits the\n * result + sets `process.exitCode` accordingly. Unhandled errors\n * are caught + printed via the shared output helpers.\n */\n\nimport { Command } from 'commander';\nimport { devCommand } from './commands/dev.js';\nimport { loginCommand } from './commands/login.js';\nimport { logoutCommand } from './commands/logout.js';\nimport { profileCommand } from './commands/profile.js';\nimport { workspaceListCommand, workspaceUseCommand } from './commands/workspace.js';\nimport { moduleCloneCommand } from './commands/module/clone.js';\nimport { moduleConnectGitCommand } from './commands/module/connect-git.js';\nimport { moduleDevCommand } from './commands/module/dev.js';\nimport { moduleDiffCommand } from './commands/module/diff.js';\nimport { moduleGenerateCommand } from './commands/module/generate.js';\nimport { moduleInitCommand } from './commands/module/init.js';\nimport { moduleListCommand } from './commands/module/list.js';\nimport { modulePublishCommand } from './commands/module/publish.js';\nimport { modulePullDataCommand } from './commands/module/pull-data.js';\nimport { moduleValidateCommand } from './commands/module/validate.js';\nimport { depsAddCommand } from './commands/deps/add.js';\nimport { depsCheckCommand } from './commands/deps/check.js';\nimport { depsListCommand } from './commands/deps/list.js';\nimport { depsRemoveCommand } from './commands/deps/remove.js';\nimport { queryCommand } from './commands/query.js';\nimport { moduleQueryLogCommand } from './commands/module/query-log.js';\nimport { moduleActionLogCommand } from './commands/module/action-log.js';\nimport { fail } from './lib/output.js';\n\nconst program = new Command();\n\nprogram\n .name('dashwise')\n .description('DashWise CLI — log in, author modules, publish to the marketplace.')\n .version(getVersion(), '-v, --version', 'Show the CLI version + exit')\n .option(\n '--api-url <url>',\n 'Override DashWise backend URL (default: $DASHWISE_API_URL or saved config or http://localhost:3000)',\n );\n\nprogram\n .command('login')\n .description('Sign in via the device-code flow.')\n .option('--no-prompt', 'Skip the \"open browser\" prompt; just print the URL.')\n .option('--name <name>', 'Suggested name for the minted token (default: dashwise-cli).')\n .action(async (cmdOpts: { prompt?: boolean; name?: string }) => {\n const apiUrl = program.opts<{ apiUrl?: string }>().apiUrl;\n const exit = await loginCommand({\n ...(apiUrl !== undefined ? { apiUrl } : {}),\n noPrompt: cmdOpts.prompt === false,\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n });\n process.exitCode = exit;\n });\n\nprogram\n .command('logout')\n .description('Clear the local credentials and revoke the server-side token.')\n .action(async () => {\n process.exitCode = await logoutCommand();\n });\n\nprogram\n .command('profile')\n .description('Show the current user, default workspace, and accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable kv pairs.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await profileCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nconst workspace = program\n .command('workspace')\n .description('Workspace context commands.');\n\nworkspace\n .command('list')\n .description('List accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await workspaceListCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nworkspace\n .command('use <slug>')\n .description('Set the default workspace for subsequent commands.')\n .action(async (slug: string) => {\n process.exitCode = await workspaceUseCommand(slug);\n });\n\n// One-command local dev loop. Spawns `dashwise module dev` + `next dev`\n// together with auth env vars auto-injected from the saved CLI config —\n// collapses the historical \"two terminals + manually edit .env.local\"\n// workflow into a single command. Top-level (not under `module`) because\n// it's the daily-driver entry point most developers will spend the most\n// time with.\nprogram\n .command('dev')\n .description(\n 'One-command local dev loop: runs the manifest watcher + Next.js dev server ' +\n 'together. Registers a dev-mode SSO session with the backend so workspace ' +\n 'members can sign into your locally-running module via DashWise SSO (no ' +\n 'installation_id required). Auth + dev-session env auto-injected into ' +\n 'both child processes from your saved CLI config. Run `dashwise login` first.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option(\n '--installation-id <id>',\n 'Use prod-mode SSO with this installation id instead of registering a dev session. ' +\n 'The installation must already exist in the target workspace.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Workspace to scope the dev session to (slug or numeric id). Required if your ' +\n 'account belongs to more than one workspace; auto-picked if you have just one.',\n )\n .option(\n '--callback-origin <url>',\n 'Additional callback origin to allowlist on the dev session (repeatable). ' +\n 'The dev server URL (http://localhost:<port>) is always allowlisted; pass ' +\n 'this for custom-domain local dev (e.g. https://myapp.local).',\n collectRepeated,\n [] as string[],\n )\n .option(\n '--api-url <url>',\n 'Override the `DASHWISE_API_URL` env var passed to children (default: saved CLI config).',\n )\n .option('--port <number>', 'Port for `next dev` (default: 3000).', parseIntOption)\n .option('--sdk-only', 'Only run the manifest watcher; skip `next dev`.')\n .option('--next-only', 'Only run `next dev`; skip the manifest watcher.')\n .action(\n async (cmdOpts: {\n dir?: string;\n installationId?: string;\n workspace?: string;\n callbackOrigin?: string[];\n apiUrl?: string;\n port?: number;\n sdkOnly?: boolean;\n nextOnly?: boolean;\n }) => {\n process.exitCode = await devCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.installationId !== undefined ? { installationId: cmdOpts.installationId } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.callbackOrigin !== undefined && cmdOpts.callbackOrigin.length > 0\n ? { callbackOrigin: cmdOpts.callbackOrigin }\n : {}),\n ...(cmdOpts.apiUrl !== undefined ? { apiUrl: cmdOpts.apiUrl } : {}),\n ...(cmdOpts.port !== undefined ? { port: cmdOpts.port } : {}),\n ...(cmdOpts.sdkOnly !== undefined ? { sdkOnly: cmdOpts.sdkOnly } : {}),\n ...(cmdOpts.nextOnly !== undefined ? { nextOnly: cmdOpts.nextOnly } : {}),\n });\n },\n );\n\n// FUP-3: top-level alias for `dashwise module init`. The two-command\n// bootstrap (`dashwise login` + `dashwise init`) is the headline daily-\n// driver flow per `building-modules.md` + the LDI v1 plan — making the\n// second command three words (`dashwise module init`) was a paper-cut\n// during the dogfood. This alias preserves both spellings: muscle\n// memory continues to work, the README docs are honest.\nconst initOptions = (cmd: Command): Command =>\n cmd\n .option('--dir <path>', 'Override the target directory (default: ./<slug>).')\n .option('--name <name>', 'Human-readable module name (default: derived from slug).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option(\n '--simple',\n 'Use the legacy minimal scaffold (hand-authored, no Next.js auth wiring). Default before 2026-05-18; opt-in now.',\n )\n .option(\n '--custom',\n \"[Deprecated alias — kept for backward compatibility.] Equivalent to the default (full Next.js + auth). Will be removed in a future major version; just call `dashwise init` without flags.\",\n )\n .option('--git <url>', 'Initial Git repository URL — written to module.json#repository.url.')\n // HH-CC-LDI-6 flags.\n .option(\n '--description <text>',\n 'Module description — forwarded to the backend when provisioning the dev installation.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for the dev installation (slug or numeric id). When omitted in a TTY, the CLI prompts; in non-interactive mode it auto-picks when you have one workspace and errors out otherwise.',\n )\n .option(\n '--no-provision',\n 'Skip the `POST /api/installations/dev` step. Local scaffold is still written; you can provision later by re-running `dashwise init --force` (or, once it ships, `dashwise module provision-dev-install`).',\n );\n\ninterface InitCmdOpts {\n dir?: string;\n name?: string;\n force?: boolean;\n simple?: boolean;\n custom?: boolean;\n git?: string;\n description?: string;\n workspace?: string;\n // Commander maps `--no-provision` → `provision: false`.\n provision?: boolean;\n}\n\nconst initAction = async (slugArg: string | undefined, cmdOpts: InitCmdOpts): Promise<void> => {\n process.exitCode = await moduleInitCommand(slugArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.simple !== undefined ? { simple: cmdOpts.simple } : {}),\n ...(cmdOpts.custom !== undefined ? { custom: cmdOpts.custom } : {}),\n ...(cmdOpts.git !== undefined ? { git: cmdOpts.git } : {}),\n ...(cmdOpts.description !== undefined ? { description: cmdOpts.description } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.provision !== undefined ? { provision: cmdOpts.provision } : {}),\n });\n};\n\ninitOptions(\n program\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth). Top-level alias for `dashwise module init`.',\n ),\n).action(initAction);\n\nconst moduleCmd = program\n .command('module')\n .description('Module authoring commands.');\n\ninitOptions(\n moduleCmd\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth).',\n ),\n).action(initAction);\n\nmoduleCmd\n .command('connect-git <repo-url>')\n .description('Link the local module to a Git repository (writes module.json#repository).')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--branch <name>', 'Default branch to publish from (e.g. `main`).')\n .action(\n async (repoUrl: string, cmdOpts: { dir?: string; branch?: string }) => {\n process.exitCode = await moduleConnectGitCommand(repoUrl, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.branch !== undefined ? { branch: cmdOpts.branch } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('generate')\n .description(\"Regenerate typed wrappers from the local module.json into node_modules/@dashai/generated/.\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--dry-run', 'Print summary without writing files.')\n .action(async (cmdOpts: { dir?: string; dryRun?: boolean }) => {\n process.exitCode = await moduleGenerateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n });\n });\n\nmoduleCmd\n .command('dev')\n .description('Watch module.json + regenerate typed wrappers on every save. Ctrl-C to stop.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--debounce-ms <n>', 'Filesystem change debounce window (default: 250ms).', parseIntOption)\n .action(async (cmdOpts: { dir?: string; debounceMs?: number }) => {\n process.exitCode = await moduleDevCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.debounceMs !== undefined ? { debounceMs: cmdOpts.debounceMs } : {}),\n });\n });\n\nmoduleCmd\n .command('validate')\n .description('Validate the local module.json against the backend manifest validator.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (cmdOpts: { dir?: string }) => {\n process.exitCode = await moduleValidateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nmoduleCmd\n .command('list')\n .description('List modules you own (or `--all` for owned + public).')\n .option('--all', 'Include public modules you can install but do not own.')\n .option('--workspace <slug>', 'Filter by workspace slug (default: saved default workspace).')\n .option('--json', 'Emit JSON to stdout instead of column-aligned text.')\n .action(async (cmdOpts: { all?: boolean; workspace?: string; json?: boolean }) => {\n process.exitCode = await moduleListCommand({\n ...(cmdOpts.all !== undefined ? { all: cmdOpts.all } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('diff')\n .description('Show what would change at the next publish vs the currently-published version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit the structured diff as JSON instead of the human-readable summary.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await moduleDiffCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('pull-data')\n .description(\"Export the module's own-table rows to a local JSON file (for fixtures, local dev seeding).\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--limit <n>', 'Max rows per table (1-1000, default 100).', parseIntOption)\n .option('--out <path>', 'Output file path (default: ./dashwise-data.json).')\n .action(async (cmdOpts: { dir?: string; limit?: number; out?: string }) => {\n process.exitCode = await modulePullDataCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.out !== undefined ? { out: cmdOpts.out } : {}),\n });\n });\n\nmoduleCmd\n .command('clone <slug>')\n .description('Clone a published module locally. Uses git if repository.url is set, else writes a manifest-only scaffold.')\n .option('--dir <path>', 'Target directory (default: ./<slug>).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option('--no-git', 'Skip git clone even when repository.url is set; use the manifest-only scaffold.')\n .action(\n async (\n slug: string,\n cmdOpts: { dir?: string; force?: boolean; git?: boolean },\n ) => {\n // commander maps `--no-git` to `git: false`; convert to our internal shape.\n process.exitCode = await moduleCloneCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.git === false ? { noGit: true } : {}),\n });\n },\n );\n\nconst depsCmd = program\n .command('deps')\n .description('Cross-module dependency commands (manipulate module.json#dependencies).');\n\ndepsCmd\n .command('list')\n .description('List declared cross-module dependencies.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\ndepsCmd\n .command('add <provider-slug>')\n .description(\n 'Declare a cross-module dependency. Interactive in TTY (picks tables + fields from the provider\\'s exposes); non-interactive requires --table, --fields, --purpose.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--table <slug>', 'Provider table slug to read from (non-interactive mode).')\n .option('--fields <list>', 'Comma-separated field slugs for --table (non-interactive mode).')\n .option('--purpose <text>', 'Human-readable explanation (10-500 chars, shown at install consent).')\n .option('--version <range>', 'SemVer range to pin (default: ^<provider-current-version>).')\n .option('-y, --yes', 'Skip the replace-existing confirmation prompt.')\n .action(\n async (\n providerSlug: string,\n cmdOpts: {\n dir?: string;\n table?: string;\n fields?: string;\n purpose?: string;\n version?: string;\n yes?: boolean;\n },\n ) => {\n process.exitCode = await depsAddCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.table !== undefined ? { table: cmdOpts.table } : {}),\n ...(cmdOpts.fields !== undefined ? { fields: cmdOpts.fields } : {}),\n ...(cmdOpts.purpose !== undefined ? { purpose: cmdOpts.purpose } : {}),\n ...(cmdOpts.version !== undefined ? { version: cmdOpts.version } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\ndepsCmd\n .command('remove <provider-slug>')\n .description('Remove a declared cross-module dependency.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('-y, --yes', 'Skip the confirmation prompt.')\n .action(async (providerSlug: string, cmdOpts: { dir?: string; yes?: boolean }) => {\n process.exitCode = await depsRemoveCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n });\n\ndepsCmd\n .command('check')\n .description('Verify each declared dep still resolves to a published provider + that every field/op is still exposed. Exits 1 on drift.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit a JSON drift report to stdout.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsCheckCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nprogram\n .command('query')\n .description(\n 'Run a typed query against the local module installation via @dashai/sdk/query. ' +\n 'Pass one of `--inline \"<expr>\"`, `--file <path>`, or `--repl`. ' +\n '`qb`, `deps`, `db` are pre-bound to the local module\\'s generated SDK.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option('--inline <expression>', 'Evaluate a one-liner. e.g., `qb.tasks.where({done:false}).count()`.')\n .option('--file <path>', 'Dynamic-import a .mjs/.js file. Default export = Query | AggQuery | Promise | value.')\n .option('--repl', 'Open an interactive Node REPL with the generated SDK pre-bound. Top-level await supported.')\n .option('--json', 'Emit compact JSON (default: pretty-printed).')\n .option(\n '--explain',\n 'Call .explain() instead of .execute() — returns the Postgres plan + estimatedCost without executing the query. MVP supports joined queries; bare own/dep/view paths reject with EXPLAIN_NOT_SUPPORTED_YET.',\n )\n .option(\n '--stream',\n 'Call .stream() instead of .execute() — prints rows incrementally as JSON-lines (one row per line). Lets you see progress on big queries + Ctrl-C cleanly midway. Mutually exclusive with --explain and --repl.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n explain?: boolean;\n stream?: boolean;\n }) => {\n process.exitCode = await queryCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.inline !== undefined ? { inline: cmdOpts.inline } : {}),\n ...(cmdOpts.file !== undefined ? { file: cmdOpts.file } : {}),\n ...(cmdOpts.repl !== undefined ? { repl: cmdOpts.repl } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.explain !== undefined ? { explain: cmdOpts.explain } : {}),\n ...(cmdOpts.stream !== undefined ? { stream: cmdOpts.stream } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('publish')\n .description('Pack the current directory + upload it as a new module version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--bump <direction>', 'Semver bump: patch | minor | major.')\n .option('--dry-run', 'Validate + upload but do not persist the version row.')\n .option('-y, --yes', 'Skip the confirmation prompt (for CI / scripted use).')\n .option(\n '--exclude <pattern...>',\n 'Extra exclude patterns (segment-matched) appended to the defaults.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n bump?: 'patch' | 'minor' | 'major';\n dryRun?: boolean;\n yes?: boolean;\n exclude?: string[];\n }) => {\n process.exitCode = await modulePublishCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.bump !== undefined ? { bump: cmdOpts.bump } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n ...(cmdOpts.exclude !== undefined ? { exclude: cmdOpts.exclude } : {}),\n });\n },\n );\n\n// Phase 6 slice 6.4 (2026-05-19): per-module SDK query log reader.\n// Workspace-member-scoped on the backend.\nmoduleCmd\n .command('query-log')\n .description(\n 'Read the per-module SDK query log. Default: 50 most recent entries. ' +\n '`--slow` filters to duration_ms > 500ms; `--since 1h` narrows by time; ' +\n '`--tail` streams new entries every 5s.',\n )\n .option(\n '--module <id-or-slug>',\n 'Module to inspect (default: slug from current directory\\'s module.json).',\n )\n .option('--slow', 'Filter to slow queries only (duration_ms > 500).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .option('--dir <path>', 'Override project directory for module.json lookup.')\n .action(\n async (cmdOpts: {\n module?: string;\n slow?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n dir?: string;\n }) => {\n process.exitCode = await moduleQueryLogCommand({\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\n// P7 slice 7.5b (2026-05-20): per-installation server-action audit log.\n// Follow-up (2026-05-20): added `--module <slug>` resolver.\nmoduleCmd\n .command('action-log')\n .description(\n 'Read the per-installation server-action audit log. Shows both ' +\n 'cross-module and own-module dispatches. Filter by role (caller / ' +\n 'provider), slow, since, cross-module-only. `--tail` streams new ' +\n 'entries every 5s. Pass either `--installation <id>` or ' +\n '`--module <slug>` (slug resolves to your accessible installation).',\n )\n .option(\n '--installation <id>',\n 'Installation id to inspect. Mutually exclusive with `--module`.',\n parseIntOption,\n )\n .option(\n '--module <slug>',\n \"Module slug. Resolves to the caller's accessible installation of \" +\n 'that module (first match if multi-workspace). Mutually exclusive with `--installation`.',\n )\n .option(\n '--role <caller|provider>',\n \"Which side of cross-module dispatches to show. 'caller' (default) \" +\n \"shows outbound; 'provider' shows inbound calls on this installation.\",\n )\n .option('--slow', 'Filter to slow actions only (elapsed_ms > 500).')\n .option('--cross-module-only', 'Hide own-module dispatches (cross_module=false rows).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .action(\n async (cmdOpts: {\n installation?: number;\n module?: string;\n role?: string;\n slow?: boolean;\n crossModuleOnly?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n }) => {\n if (cmdOpts.role !== undefined && cmdOpts.role !== 'caller' && cmdOpts.role !== 'provider') {\n fail(`--role must be 'caller' or 'provider' (got \"${cmdOpts.role}\").`);\n process.exitCode = 1;\n return;\n }\n process.exitCode = await moduleActionLogCommand({\n ...(cmdOpts.installation !== undefined ? { installation: cmdOpts.installation } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.role !== undefined ? { role: cmdOpts.role as 'caller' | 'provider' } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.crossModuleOnly !== undefined ? { crossModuleOnly: cmdOpts.crossModuleOnly } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-9: dashwise module destroy-dev-install + reset-dev-install ──\n\nmoduleCmd\n .command('destroy-dev-install')\n .description(\n \"Destroy the local-dev install for the current module. Tears down the install row + dashboard tile; if the module had no other installs and was never published, drops the module too. Local module.json is preserved (only the cached runtime token + install id in auth.json get cleared).\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n \"Override the module slug (default: read from local module.json). Useful when the project dir is gone but auth.json still has the entry.\",\n )\n .option('-y, --yes', 'Skip the confirmation prompt — for CI.')\n .action(\n async (cmdOpts: { dir?: string; module?: string; yes?: boolean }) => {\n const { destroyDevInstallCommand } = await import(\n './commands/module/destroy-dev-install.js'\n );\n process.exitCode = await destroyDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('reset-dev-install')\n .description(\n 'Destroy + re-provision the local-dev install in one shot. Useful for nuking accumulated test data, refreshing a compromised runtime token, or recovering from a wedged schema state. Keeps local module.json intact.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n 'Override the module slug (default: from local module.json).',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for re-provisioning (passed through to `dashwise init`).',\n )\n .option('-y, --yes', 'Skip prompts in both destroy + re-init phases.')\n .action(\n async (cmdOpts: {\n dir?: string;\n module?: string;\n workspace?: string;\n yes?: boolean;\n }) => {\n const { resetDevInstallCommand } = await import(\n './commands/module/reset-dev-install.js'\n );\n process.exitCode = await resetDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.workspace !== undefined\n ? { workspace: cmdOpts.workspace }\n : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-8: dashwise table / dashwise field schema commands ──\n\nconst tableCmd = program\n .command('table')\n .description(\n 'Schema commands for the current module — create/delete tables in the dev installation. Requires a per-module dev install (run `dashwise init` first).',\n );\n\ntableCmd\n .command('create <slug>')\n .description(\n 'Create a new table. Pass --field flags to define columns. Calls POST /api/installations/:id/schema/tables and syncs the updated manifest back to local module.json.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '-f, --field <spec>',\n \"Field spec — `<slug>:<type>[:required]`. Repeat for multiple fields. For options/target/default, use --field-json instead. Example: `--field title:text:required --field done:boolean`.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .option(\n '--field-json <json>',\n \"Field as a JSON object — `{slug,type,required?,options?,target?,default?}`. Repeatable. Use for fields where the simple syntax can't express the shape.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .action(\n async (\n slug: string | undefined,\n cmdOpts: { dir?: string; field?: string[]; fieldJson?: string[] },\n ) => {\n const { tableCreateCommand } = await import('./commands/table/create.js');\n process.exitCode = await tableCreateCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.field !== undefined ? { field: cmdOpts.field } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\ntableCmd\n .command('delete <slug>')\n .description(\n \"Drop a table. Calls DELETE /api/installations/:id/schema/tables/:slug — the physical table is soft-deleted (recoverable for 30 days via the dashboard's trash). Updates local module.json.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (slug: string | undefined, cmdOpts: { dir?: string }) => {\n const { tableDeleteCommand } = await import('./commands/table/delete.js');\n process.exitCode = await tableDeleteCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nconst fieldCmd = program\n .command('field')\n .description(\n 'Schema commands for fields within the current module — add/remove/change-type. Field rename is deferred to v1.1 per the plan.',\n );\n\nfieldCmd\n .command('add <table-slug> [field-spec]')\n .description(\n \"Add a field to a table. Pass the spec as `<slug>:<type>[:required]` OR use --field-json for fields with options/target/default. Example: `dashwise field add tasks priority --field-json '{\\\"slug\\\":\\\"priority\\\",\\\"type\\\":\\\"single_select\\\",\\\"options\\\":[\\\"low\\\",\\\"medium\\\",\\\"high\\\"]}'`.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--field-json <json>',\n \"Field as a JSON object. Mutually exclusive with the positional field spec.\",\n )\n .action(\n async (\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n cmdOpts: { dir?: string; fieldJson?: string },\n ) => {\n const { fieldAddCommand } = await import('./commands/field/add.js');\n process.exitCode = await fieldAddCommand(tableSlug, fieldSpec, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\nfieldCmd\n .command('remove <table-slug> <field-slug>')\n .description(\n 'Remove a field from a table. The backend cascades index cleanup (M2-C-FIX): any index referencing the removed field is trimmed; empty indexes are dropped.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldRemoveCommand } = await import('./commands/field/remove.js');\n process.exitCode = await fieldRemoveCommand(tableSlug, fieldSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\nfieldCmd\n .command('set-type <table-slug> <field-slug> <new-type>')\n .description(\n \"Change a field's type (e.g. text → long_text). Lossy changes (text → number with non-numeric data) are rejected by the backend's manifest validator today; v1.1 will add a structured RETYPE_UNSAFE precheck.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldSetTypeCommand } = await import('./commands/field/set-type.js');\n process.exitCode = await fieldSetTypeCommand(\n tableSlug,\n fieldSlug,\n newType,\n {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n },\n );\n },\n );\n\n// Single async entry so unhandled errors hit the same formatter.\n(async () => {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n fail(`Unhandled error: ${(err as Error).message ?? String(err)}`);\n if (process.env.DASHWISE_DEBUG) {\n // Print full stack when debugging — opt-in to keep normal\n // output uncluttered.\n // eslint-disable-next-line no-console\n console.error(err);\n }\n process.exitCode = 1;\n }\n})();\n\n/**\n * CLI version, injected at build time by tsup's `define` from\n * `packages/cli/package.json#version`. See tsup.config.ts.\n */\ndeclare const __CLI_VERSION__: string;\n\nfunction getVersion(): string {\n return __CLI_VERSION__;\n}\n\n/** commander helper: parse a `<n>` argument as an integer. */\nfunction parseIntOption(value: string): number {\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n)) {\n throw new Error(`Expected an integer, got '${value}'`);\n }\n return n;\n}\n\n/**\n * commander helper: collect repeated `--option <value>` flags into\n * an array. Use as the third arg to `.option()` along with `[]` as\n * the default (fourth arg).\n *\n * Example: `--callback-origin http://localhost:3000 --callback-origin https://myapp.local`\n * yields `['http://localhost:3000', 'https://myapp.local']`.\n */\nfunction collectRepeated(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n","/**\n * `dashwise module list` — list modules the current user can author.\n *\n * Hits `GET /api/modules?owned_only=true` so the listing scope is\n * \"modules I own\" by default. Add `--all` to include public modules\n * the user could install but doesn't own. Workspace filter (`--workspace\n * <slug>`) narrows further when the user has multiple workspaces.\n *\n * Output is plain text — column-aligned slug + version + name — so\n * it pipes cleanly into grep / awk.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig } from '../../lib/config.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleListOptions {\n /** Include public modules (default: false — owned only). */\n all?: boolean;\n /**\n * Filter by workspace slug. Falls back to the saved default if\n * omitted, no filter if neither.\n */\n workspace?: string;\n /** Emit JSON to stdout instead of column-aligned text. */\n json?: boolean;\n}\n\ninterface ModuleSummary {\n id: number;\n slug: string;\n name: string;\n owner_workspace_id: number;\n current_version: string | null;\n verified: boolean;\n public: boolean;\n}\n\nexport async function moduleListCommand(\n options: ModuleListOptions,\n): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Resolve workspaceId from slug if requested.\n let workspaceId: number | undefined;\n const targetSlug = options.workspace ?? cfg.workspaceSlug;\n if (targetSlug) {\n try {\n const workspaces = await apiRequest<Array<{ id: number; slug?: string }>>(\n 'GET',\n '/api/workspaces',\n );\n const match = workspaces.find((w) => w.slug === targetSlug);\n if (!match) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'WORKSPACE_NOT_FOUND', message: `Workspace ${targetSlug} not found.` } }));\n } else {\n fail(\n `Workspace ${code(targetSlug)} not found in your accessible workspaces. Run \\`dashwise workspace list\\` to see the choices.`,\n );\n }\n return 1;\n }\n workspaceId = match.id;\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not load workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // Build query.\n const params = new URLSearchParams();\n if (!options.all) params.set('owned_only', 'true');\n if (workspaceId !== undefined) params.set('workspaceId', String(workspaceId));\n const path = `/api/modules${params.toString() ? `?${params.toString()}` : ''}`;\n\n let modules: ModuleSummary[];\n try {\n modules = await apiRequest<ModuleSummary[]>('GET', path);\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list modules: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n modules: Array.isArray(modules) ? modules : [],\n total: Array.isArray(modules) ? modules.length : 0,\n }),\n );\n return 0;\n }\n\n if (!Array.isArray(modules) || modules.length === 0) {\n info(\n options.all\n ? 'No modules found.'\n : 'No modules owned by you yet. Use `dashwise module init <slug>` to scaffold one.',\n );\n return 0;\n }\n\n // Column-aligned plain output. Two passes: compute widths, then format.\n const slugWidth = Math.max(...modules.map((m) => m.slug.length), 4);\n const versionWidth = Math.max(\n ...modules.map((m) => (m.current_version ?? '(draft)').length),\n 7,\n );\n out('');\n out(\n `${'SLUG'.padEnd(slugWidth)} ${'VERSION'.padEnd(versionWidth)} NAME`,\n );\n out(\n `${'-'.repeat(slugWidth)} ${'-'.repeat(versionWidth)} ${'-'.repeat(20)}`,\n );\n for (const m of modules) {\n const version = m.current_version ?? '(draft)';\n const flags = [\n m.verified ? code('✓') : '',\n m.public ? dim('public') : '',\n ]\n .filter(Boolean)\n .join(' ');\n const flagsCol = flags ? ` ${flags}` : '';\n out(`${m.slug.padEnd(slugWidth)} ${version.padEnd(versionWidth)} ${m.name}${flagsCol}`);\n }\n out('');\n info(`${modules.length} module${modules.length === 1 ? '' : 's'}.`);\n return 0;\n}\n","/**\n * `dashwise module publish` — package the local project + upload it\n * as a new module version.\n *\n * Steps:\n * 1. Read local `module.json` to get the slug + module_kind.\n * 2. Resolve `slug → module_id` via `GET /api/modules/by-slug/:slug`.\n * 3. Pack `cwd` into a gzipped tarball via `packTarball()`. The\n * tarball excludes node_modules / .next / .git / .dashwise +\n * caps per-file at 10MB and total at 100MB (matches backend).\n * 4. POST the tarball as multipart form-data to\n * `/api/modules/:id/publish/cli` with the user's bump + flags.\n * 5. Print the resulting version + bundle hash.\n *\n * Confirms before uploading (in TTY) unless `--yes` is passed —\n * publish is the one command where a typo costs a real version bump.\n *\n * Tarball bytes live in memory (≤100MB) — no temp file. We use\n * the native `FormData` + `Blob` available on Node 18+.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, select } from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig, resolveApiUrl } from '../../lib/config.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\nimport { MAX_TARBALL_BYTES, packTarball } from '../../lib/tarball.js';\n\nexport interface PublishOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** SemVer bump direction; required. */\n bump?: 'patch' | 'minor' | 'major';\n /** Dry run: send `dry_run=true`; backend validates without persisting. */\n dryRun?: boolean;\n /** Skip the confirmation prompt (CI / scripted runs). */\n yes?: boolean;\n /** Additional exclude patterns appended to the defaults. */\n exclude?: string[];\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface PublishResponse {\n module_version_id: number;\n module_slug: string;\n version: string;\n bundle_url: string;\n bundle_hash: string;\n bytes_uploaded: number;\n publisher_type: string;\n verified: boolean;\n warnings: string[];\n pipeline_version: string;\n}\n\nconst VALID_BUMP = new Set(['patch', 'minor', 'major']);\n\nexport async function modulePublishCommand(\n options: PublishOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string; name?: string; version?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}. Cannot publish.`);\n return 1;\n }\n\n if (!readConfig()) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n\n // Resolve / prompt for bump.\n let bump = options.bump;\n if (!bump && process.stdout.isTTY) {\n intro(`Publishing module ${code(slug)}`);\n const answer = await select({\n message: 'Bump direction?',\n options: [\n { value: 'patch', label: 'patch — bug fixes only (recommended for first publish)' },\n { value: 'minor', label: 'minor — additive changes (new fields, new tables)' },\n { value: 'major', label: 'major — breaking changes' },\n ],\n initialValue: 'patch',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n bump = answer as 'patch' | 'minor' | 'major';\n }\n if (!bump || !VALID_BUMP.has(bump)) {\n fail('Bump direction required: `--bump patch|minor|major`.');\n return 1;\n }\n\n // Resolve slug → module id.\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(\n `Module ${code(slug)} not found on the backend. Create it via the UI / API first, then re-run publish.`,\n );\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n info(\n `Module: ${code(mod.slug)} (id ${mod.id})${\n mod.current_version ? `, current ${code(`v${mod.current_version}`)}` : dim(', no published version yet')\n }`,\n );\n\n // Pack tarball.\n let tarball;\n try {\n tarball = await packTarball({\n cwd: projectRoot,\n ...(options.exclude !== undefined ? { extraExclude: options.exclude } : {}),\n });\n } catch (err) {\n fail(`Could not pack tarball: ${(err as Error).message}`);\n return 1;\n }\n info(\n `Packed ${tarball.filesIncluded.length} file${tarball.filesIncluded.length === 1 ? '' : 's'} into ${formatBytes(tarball.bytes.byteLength)} (cap ${formatBytes(MAX_TARBALL_BYTES)}).`,\n );\n for (const w of tarball.warnings) warn(w);\n\n // Confirm.\n if (!options.yes && process.stdout.isTTY && !options.dryRun) {\n const answer = await select({\n message: `Upload + publish ${code(`bump:${bump}`)}?`,\n options: [\n { value: 'go', label: 'Yes, upload now' },\n { value: 'cancel', label: 'No, abort' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n fail('Aborted.');\n return 130;\n }\n }\n\n // Multipart upload.\n const cfg = readConfig();\n if (!cfg) {\n fail('Session vanished mid-publish — re-run `dashwise login`.');\n return 1;\n }\n const url = `${resolveApiUrl()}/api/modules/${mod.id}/publish/cli`;\n const form = new FormData();\n // Native `Blob` works in Node 18+; `Buffer` is array-buffer-like\n // so we wrap it before passing to FormData.\n const blob = new Blob([new Uint8Array(tarball.bytes)], { type: 'application/gzip' });\n form.set('file', blob, 'module.tar.gz');\n form.set('bump', bump);\n if (options.dryRun) form.set('dry_run', 'true');\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${cfg.token}`,\n },\n body: form,\n });\n } catch (err) {\n fail(`Network error during upload: ${(err as Error).message}`);\n return 1;\n }\n\n const body = (await res.json().catch(() => null)) as unknown;\n if (!res.ok) {\n const env = body && typeof body === 'object' ? (body as Record<string, unknown>) : null;\n fail(\n `Publish failed (${res.status}${env?.code ? ` ${env.code}` : ''}): ${env?.message ?? '(no message)'}`,\n );\n if (env?.context) {\n out(JSON.stringify(env.context, null, 2));\n }\n return 1;\n }\n\n const result = body as PublishResponse | null;\n if (!result) {\n fail('Publish succeeded but the response body was empty or malformed.');\n return 1;\n }\n if (options.dryRun) {\n success(`Dry run OK — would publish ${code(`v${result.version}`)}`);\n } else {\n success(`Published ${code(mod.slug)} ${code(`v${result.version}`)}`);\n }\n info(`Bundle: ${code(result.bundle_url)}`);\n info(`Hash: ${dim(result.bundle_hash)}`);\n info(`Size: ${formatBytes(result.bytes_uploaded)}`);\n if (result.warnings.length > 0) {\n warn(`${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'}:`);\n for (const w of result.warnings) {\n out(` ${dim('•')} ${w}`);\n }\n }\n if (process.stdout.isTTY && !options.dryRun) outro('Done.');\n return 0;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n","/**\n * Tarball helper for `dashwise module publish`.\n *\n * Wraps the `tar` npm package with DashWise-specific defaults:\n * - gzip compression (server expects `.tar.gz`)\n * - sensible exclusion list (node_modules, .next, .git, ...)\n * - allowlist of files that should ALWAYS be included if present\n * (module.json, manifest.yaml, package.json, app/, server/, etc.)\n * - 100MB size cap (matches backend's `BUNDLE_TOO_LARGE` gate)\n *\n * Output is a `Uint8Array` buffer so callers can pipe it straight\n * into a `fetch` multipart upload without a temp file. The trade-off\n * is memory — but 100MB max is fine for any modern CLI host.\n */\n\nimport { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport * as tar from 'tar';\n\n/**\n * Patterns that should NEVER be included in the published bundle.\n * Path semantics: a candidate path matches if any segment equals\n * the pattern (e.g. `node_modules` matches `foo/node_modules/bar`).\n *\n * Kept conservative: the backend's per-file policy gate is the\n * security boundary; this list is the UX layer that keeps tarballs\n * tractable and the upload step fast.\n */\nexport const DEFAULT_EXCLUDE_PATTERNS = [\n 'node_modules',\n '.next',\n '.git',\n '.turbo',\n '.dashwise',\n '.DS_Store',\n '.env',\n '.env.local',\n '.env.development.local',\n '.env.test.local',\n '.env.production.local',\n 'coverage',\n '.nyc_output',\n '.vitest-cache',\n '.idea',\n '.vscode',\n 'dist',\n 'build',\n] as const;\n\n/** Per-file size cap. Files larger than this are excluded with a warning. */\nconst PER_FILE_BYTE_LIMIT = 10 * 1024 * 1024; // 10MB\n/** Tarball total cap — matches backend BUNDLE_TOO_LARGE gate. */\nexport const MAX_TARBALL_BYTES = 100 * 1024 * 1024; // 100MB\n\nexport interface TarballResult {\n /** Gzipped tarball bytes ready to upload. */\n bytes: Uint8Array;\n /** Files included (relative paths from `cwd`). Sorted. */\n filesIncluded: string[];\n /** Files skipped + the reason. */\n warnings: string[];\n}\n\n/**\n * Pack `cwd` into a gzipped tarball.\n *\n * The pack walks `cwd` once, applies exclusion rules + per-file size\n * limits, and emits a buffer. We don't stream-to-disk because the\n * 100MB ceiling makes the in-memory path fine + lets the caller\n * `fetch(...)` without a temp file dance.\n *\n * `extraExclude` is appended to the defaults so callers can suppress\n * additional patterns (e.g. local secrets) without forking the list.\n */\nexport async function packTarball(opts: {\n cwd: string;\n extraExclude?: readonly string[];\n}): Promise<TarballResult> {\n if (!existsSync(opts.cwd)) {\n throw new Error(`packTarball: cwd not found at ${opts.cwd}`);\n }\n const excludeSet = new Set<string>([\n ...DEFAULT_EXCLUDE_PATTERNS,\n ...(opts.extraExclude ?? []),\n ]);\n const filesIncluded: string[] = [];\n const warnings: string[] = [];\n const candidates = walk(opts.cwd, excludeSet);\n for (const abs of candidates) {\n const rel = relative(opts.cwd, abs);\n const size = statSync(abs).size;\n if (size > PER_FILE_BYTE_LIMIT) {\n warnings.push(\n `${rel} skipped — ${formatBytes(size)} exceeds ${formatBytes(PER_FILE_BYTE_LIMIT)} per-file cap`,\n );\n continue;\n }\n filesIncluded.push(rel);\n }\n if (filesIncluded.length === 0) {\n throw new Error(\n `packTarball: nothing to pack in ${opts.cwd} (after applying exclude list)`,\n );\n }\n filesIncluded.sort();\n\n // The `tar.c` API streams chunks; collect them into one buffer.\n // We use the lower-level callback form so the result is a single\n // contiguous Uint8Array — the multipart upload step expects that.\n const chunks: Buffer[] = [];\n await new Promise<void>((resolveDone, rejectDone) => {\n const stream = tar.c(\n {\n gzip: true,\n cwd: opts.cwd,\n // Don't follow symlinks — bundle-local content only.\n follow: false,\n // Preserve the exact case of paths; the backend's per-file\n // policy gate keys off these.\n portable: true,\n },\n filesIncluded,\n );\n stream.on('data', (chunk: Buffer) => chunks.push(chunk));\n stream.on('error', rejectDone);\n stream.on('end', resolveDone);\n });\n const bytes = Buffer.concat(chunks);\n if (bytes.byteLength > MAX_TARBALL_BYTES) {\n throw new Error(\n `packTarball: tarball is ${formatBytes(bytes.byteLength)}, exceeds ${formatBytes(MAX_TARBALL_BYTES)} max`,\n );\n }\n return { bytes, filesIncluded, warnings };\n}\n\n// ── helpers ────────────────────────────────────────────────────────────\n\nfunction walk(root: string, excludeSet: Set<string>): string[] {\n const out: string[] = [];\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (!dir) continue;\n let entries: import('node:fs').Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue; // unreadable directory — silently skip\n }\n for (const entry of entries) {\n if (excludeSet.has(entry.name)) continue;\n const abs = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(abs);\n } else if (entry.isFile()) {\n out.push(abs);\n }\n // Skip symlinks + sockets + everything else.\n }\n }\n return out;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n\n// Test seam: expose internals for unit tests without making them\n// part of the public package surface.\nexport const __forTests = {\n walk,\n formatBytes,\n PER_FILE_BYTE_LIMIT,\n};\n","/**\n * `dashwise module pull-data` — export own-table data from the\n * owner-workspace installation to a local JSON file (default\n * `dashwise-data.json` in the project root).\n *\n * Useful for: seeding local dev with production-shaped data,\n * fixture generation, manual inspection. The output shape matches\n * what `db.<table>.list()` would return through the SDK — manifest\n * slugs as keys, NOT physical `field_<id>` names — so the data\n * can be reused as fixtures for unit tests or local API mocks.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface PullDataOptions {\n dir?: string;\n /** Max rows per table (1-1000, default 100). */\n limit?: number;\n /** Output path (default: `dashwise-data.json` in dir). */\n out?: string;\n}\n\ninterface PullDataResponse {\n module_slug: string;\n module_version: string | null;\n tables: Array<{\n slug: string;\n total_rows: number;\n rows: Array<Record<string, unknown>>;\n }>;\n}\n\nexport async function modulePullDataCommand(\n options: PullDataOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number };\n try {\n mod = await apiRequest<{ id: number }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found on the backend.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n const limit = options.limit ?? 100;\n let res: PullDataResponse;\n try {\n res = await apiRequest<PullDataResponse>(\n 'GET',\n `/api/modules/${mod.id}/own-data?limit=${limit}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n fail(`Invalid request: ${err.message}`);\n return 1;\n }\n fail(`Could not pull data: ${(err as Error).message}`);\n return 1;\n }\n\n const outPath = options.out\n ? resolve(options.out)\n : join(projectRoot, 'dashwise-data.json');\n writeFileSync(outPath, JSON.stringify(res, null, 2) + '\\n', 'utf-8');\n\n let totalRows = 0;\n for (const t of res.tables) totalRows += t.rows.length;\n success(`Wrote ${totalRows} row${totalRows === 1 ? '' : 's'} across ${res.tables.length} table${res.tables.length === 1 ? '' : 's'} to ${code(outPath)}`);\n\n // Warn on truncation per table — useful when a table has many\n // more rows than the user grabbed.\n for (const t of res.tables) {\n if (t.total_rows > t.rows.length) {\n warn(\n `Table ${code(t.slug)} truncated: ${t.rows.length} of ${t.total_rows} rows (use ${code(`--limit ${Math.min(t.total_rows, 1000)}`)} to grab more).`,\n );\n }\n }\n if (res.tables.length === 0) {\n info(dim('No owned tables on this module. (Did you publish a manifest with `owns.tables`?)'));\n }\n return 0;\n}\n","/**\n * `dashwise module validate` — run the local `module.json` through\n * the backend's `POST /api/modules/manifest/validate` endpoint.\n *\n * Useful as a pre-publish sanity check: catches structural manifest\n * errors (bad field types, unknown table refs, etc.) before paying\n * the cost of a publish round-trip.\n *\n * Output is structured-by-default: bullet-listed issues on failure,\n * \"Manifest is valid\" on success. Exit code 0 / 1 mirrors the\n * underlying validation result.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, out, success } from '../../lib/output.js';\n\nexport interface ValidateOptions {\n dir?: string;\n}\n\ninterface ValidateOkResponse {\n ok: true;\n manifest: unknown;\n}\n\ninterface ManifestIssue {\n path?: string;\n message?: string;\n}\n\nexport async function moduleValidateCommand(\n options: ValidateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n try {\n const res = await apiRequest<ValidateOkResponse>(\n 'POST',\n '/api/modules/manifest/validate',\n manifest,\n );\n if (res.ok) {\n success('Manifest is valid.');\n return 0;\n }\n // Defensive — the endpoint only returns `ok:true` on success;\n // anything else throws on the API side.\n fail(`Unexpected response shape: ${JSON.stringify(res)}`);\n return 1;\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n const issues = readIssues(err.context);\n if (issues.length > 0) {\n fail(`Manifest is invalid (${issues.length} issue${issues.length === 1 ? '' : 's'}):`);\n for (const issue of issues) {\n const path = issue.path ?? '(root)';\n const message = issue.message ?? '(no message)';\n out(` ${dim('•')} ${code(path)}: ${message}`);\n }\n } else {\n fail(`Manifest is invalid: ${err.message}`);\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not validate manifest: ${(err as Error).message}`);\n return 1;\n }\n}\n\nfunction readIssues(context: Record<string, unknown> | undefined): ManifestIssue[] {\n if (!context) return [];\n const v = context['issues'];\n if (!Array.isArray(v)) return [];\n return v\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null;\n const e = entry as Record<string, unknown>;\n const issue: ManifestIssue = {};\n if (typeof e.path === 'string') issue.path = e.path;\n if (typeof e.message === 'string') issue.message = e.message;\n return issue;\n })\n .filter((x): x is ManifestIssue => x !== null);\n}\n","/**\n * `dashwise deps add <provider-slug>` — declare a cross-module dep in\n * `module.json#dependencies`.\n *\n * Two modes:\n * 1. Interactive (TTY default) — fetches the provider's published\n * `exposes` block from the backend, lets the user pick tables +\n * fields via `@clack/prompts.multiselect`, prompts for the\n * required `purpose` string.\n * 2. Non-interactive (`--table`, `--fields`, `--purpose` provided\n * OR not a TTY) — single-table add with no prompts. Multi-table\n * adds are done by re-running the command per table, OR by\n * hand-editing module.json (which `deps list` then displays\n * verbatim).\n *\n * Backend reachability is best-effort: if the provider can't be\n * found (network down, slug typo, provider deleted), interactive\n * mode falls back to a minimal \"manual\" path that asks the user to\n * type the table + field names verbatim.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport {\n intro,\n isCancel,\n multiselect,\n outro,\n select,\n text,\n} from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n type ManifestShape,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DepsAddOptions {\n dir?: string;\n /** Single-table add: required in non-interactive mode. */\n table?: string;\n /** Comma-separated field slugs for `--table`. */\n fields?: string;\n /** Human-readable purpose (10-500 chars, per manifest schema). */\n purpose?: string;\n /** SemVer range (default: `^<provider-current-version>` if backend reachable, else `^0.0.1`). */\n version?: string;\n /** Skip the confirmation step when replacing an existing dep declaration. */\n yes?: boolean;\n}\n\nconst MIN_PURPOSE_LEN = 10;\nconst MAX_PURPOSE_LEN = 500;\n\n/** Backend manifest_jsonb shape, only the parts the CLI needs. */\ninterface ProviderManifestSummary {\n module?: { slug?: string; name?: string; version?: string };\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: {\n list?: { allowed?: boolean };\n get?: { allowed?: boolean };\n search?: { allowed?: boolean };\n };\n visibility?: string;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n module_id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\nexport async function depsAddCommand(\n providerSlug: string,\n options: DepsAddOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps add <provider-slug>`');\n return 1;\n }\n // Module slugs are kebab-case (matches backend MODULE_SLUG_REGEX).\n if (!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(providerSlug)) {\n fail(\n `Provider slug ${code(providerSlug)} is invalid. Module slugs are kebab-case (e.g. ${code('crm-app')}).`,\n );\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Refuse to self-depend (would be a no-op but confusing).\n if (manifest.module?.slug === providerSlug) {\n fail('A module cannot depend on itself.');\n return 1;\n }\n\n const isInteractive = process.stdout.isTTY;\n const hasAllNonInteractive =\n options.table !== undefined &&\n options.fields !== undefined &&\n options.purpose !== undefined;\n\n if (!isInteractive && !hasAllNonInteractive) {\n fail(\n `Non-interactive mode requires ${code('--table')}, ${code('--fields')}, and ${code('--purpose')}.`,\n );\n return 1;\n }\n\n // Fetch provider summary (best-effort — non-fatal in interactive mode).\n let providerSummary: ProviderManifestSummary | null = null;\n let resolvedVersion: string | null = null;\n try {\n const mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(providerSlug)}`,\n );\n if (mod.current_version) {\n const versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n // Versions are returned newest-first per the controller spec; the\n // first one matching `current_version` is what's actually\n // installable. Fall back to versions[0] if no exact match.\n const current =\n versions.find((v) => v.version === mod.current_version) ??\n versions[0];\n if (current) {\n providerSummary = current.manifest_jsonb;\n resolvedVersion = current.version;\n }\n }\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (!isInteractive) {\n fail(\n `Provider ${code(providerSlug)} not found on the backend. Publish it first or check the slug.`,\n );\n return 1;\n }\n warn(\n `Provider ${code(providerSlug)} not found on the backend (404). You can still declare the dep manually.`,\n );\n } else if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n } else {\n warn(`Could not fetch provider summary: ${(err as Error).message}`);\n }\n }\n\n // Resolve the dep entry's fields.\n let entry: ManifestDependency;\n if (isInteractive) {\n intro(`Adding dependency on ${code(providerSlug)}`);\n const built = await collectInteractive(\n providerSlug,\n providerSummary,\n resolvedVersion,\n options,\n );\n if (built === null) {\n outro('Cancelled.');\n return 130;\n }\n entry = built;\n } else {\n // Non-interactive path: all required args are present per the\n // check above; we trust them + let the backend validate semantics\n // on the next publish.\n const fieldList = (options.fields ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (fieldList.length === 0) {\n fail(`${code('--fields')} must list at least one field slug.`);\n return 1;\n }\n const purposeErr = validatePurpose(options.purpose!);\n if (purposeErr) {\n fail(purposeErr);\n return 1;\n }\n entry = {\n module: providerSlug,\n version: options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1'),\n reads: [{ table: options.table!, fields: fieldList }],\n purpose: options.purpose!,\n };\n }\n\n // Merge with existing manifest.dependencies[].\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const existingIdx = deps.findIndex((d) => d.module === providerSlug);\n if (existingIdx >= 0) {\n if (!options.yes && isInteractive) {\n const answer = await select({\n message: `Dep on ${providerSlug} already exists. Replace it?`,\n options: [\n { value: 'replace', label: 'Replace (loses prior reads/writes)' },\n { value: 'cancel', label: 'Cancel' },\n ],\n initialValue: 'replace',\n });\n if (isCancel(answer) || answer === 'cancel') {\n outro('Cancelled.');\n return 130;\n }\n }\n deps[existingIdx] = entry;\n } else {\n deps.push(entry);\n }\n manifest.dependencies = deps;\n\n try {\n writeManifest(manifest as ManifestShape, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(\n `${existingIdx >= 0 ? 'Replaced' : 'Added'} dependency on ${code(providerSlug)}@${entry.version}.`,\n );\n info(`Reads: ${entry.reads.map((r) => `${code(r.table)} (${r.fields.join(', ')})`).join('; ')}`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n if (isInteractive) outro('Done.');\n return 0;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\ninterface NormalizedReadEntry {\n table: string;\n fields: string[];\n}\n\nasync function collectInteractive(\n providerSlug: string,\n summary: ProviderManifestSummary | null,\n resolvedVersion: string | null,\n options: DepsAddOptions,\n): Promise<ManifestDependency | null> {\n const reads: NormalizedReadEntry[] = [];\n\n if (summary && summary.exposes && summary.exposes.length > 0) {\n // Backend-assisted: present the actual exposes set.\n info(\n `Provider exposes ${summary.exposes.length} table${summary.exposes.length === 1 ? '' : 's'}.`,\n );\n // Filter to tables the provider actually allows `list` or `get` on\n // (others are visible-but-unreadable from a SDK perspective).\n const readableTables = summary.exposes.filter((e) => {\n const ops = e.operations;\n if (!ops) return true; // back-compat: no operations block = implicit allow\n return ops.list?.allowed === true || ops.get?.allowed === true;\n });\n if (readableTables.length === 0) {\n warn(\n `Provider ${code(providerSlug)} exposes tables but none are readable (operations.list / .get all denied).`,\n );\n return null;\n }\n\n const picked = await multiselect({\n message: 'Which tables do you want to read from?',\n options: readableTables.map((e) => ({\n value: e.table,\n label: `${e.table} ${dim(`(${e.fields.length} field${e.fields.length === 1 ? '' : 's'})`)}`,\n })),\n required: true,\n });\n if (isCancel(picked)) return null;\n\n for (const tableSlug of picked as string[]) {\n const exposeEntry = readableTables.find((e) => e.table === tableSlug)!;\n const fieldsPicked = await multiselect({\n message: `Fields to read from ${code(tableSlug)}:`,\n options: exposeEntry.fields.map((f) => ({ value: f, label: f })),\n required: true,\n initialValues: exposeEntry.fields, // pre-select all; user trims down\n });\n if (isCancel(fieldsPicked)) return null;\n reads.push({ table: tableSlug, fields: fieldsPicked as string[] });\n }\n } else {\n // Manual fallback when no backend summary is available.\n info('No provider summary available — enter table + fields manually.');\n const tableSlug = await text({\n message: 'Provider table slug to read from:',\n placeholder: 'contacts',\n validate: (v) =>\n /^[a-z][a-z0-9_]*[a-z0-9]$/.test(v) ? undefined : 'Table slugs are snake_case.',\n });\n if (isCancel(tableSlug)) return null;\n const fieldsStr = await text({\n message: 'Comma-separated field slugs:',\n placeholder: 'name, email, company',\n validate: (v) =>\n v.split(',').map((s) => s.trim()).filter(Boolean).length > 0\n ? undefined\n : 'At least one field required.',\n });\n if (isCancel(fieldsStr)) return null;\n reads.push({\n table: tableSlug as string,\n fields: (fieldsStr as string)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean),\n });\n }\n\n // Purpose — manifest validator requires 10-500 chars.\n const initialPurpose = options.purpose ?? '';\n const purpose = await text({\n message: `Why does your module need this dependency? ${dim(`(${MIN_PURPOSE_LEN}-${MAX_PURPOSE_LEN} chars; shown to workspace admins at install consent)`)}`,\n placeholder: 'Look up assignee contact info when rendering tasks.',\n initialValue: initialPurpose,\n validate: (v) => validatePurpose(v) ?? undefined,\n });\n if (isCancel(purpose)) return null;\n\n // Version range — default to `^<resolved>` for stability.\n const defaultVersion =\n options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1');\n const version = await text({\n message: `SemVer range to pin: ${dim('(npm-style; e.g. ^1.2.3, ~1.2.0, >=1.0.0)')}`,\n placeholder: defaultVersion,\n initialValue: defaultVersion,\n validate: (v) =>\n /^[\\^~]?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v) ||\n /^(>=|<=|>|<|=)?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v)\n ? undefined\n : 'Must be a npm-style semver range (e.g. ^1.2.3).',\n });\n if (isCancel(version)) return null;\n\n return {\n module: providerSlug,\n version: version as string,\n reads,\n purpose: purpose as string,\n };\n}\n\nfunction validatePurpose(purpose: string): string | null {\n if (typeof purpose !== 'string') return 'Purpose must be a string.';\n if (purpose.length < MIN_PURPOSE_LEN) {\n return `Purpose must be at least ${MIN_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n if (purpose.length > MAX_PURPOSE_LEN) {\n return `Purpose must be at most ${MAX_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n return null;\n}\n","/**\n * `dashwise deps check` — verify each declared dep still resolves\n * against a currently-published provider and that every field /\n * operation in the contract is still exposed.\n *\n * Exit code:\n * 0 — all deps healthy\n * 1 — at least one drift issue found\n *\n * Reports per-dep issues with a clear next step:\n * - PROVIDER_NOT_FOUND → the provider was deleted or renamed\n * - NO_MATCHING_VERSION → no published version satisfies the SemVer range\n * - FIELD_NOT_EXPOSED → consumer reads a field the provider no longer exposes\n * - OP_NOT_ALLOWED → consumer declares writes the provider blocks (writes opt-in)\n *\n * Backend reachability is required — `check` is an online command by\n * design. If the backend is unreachable, exit 1 with a clear message\n * (CI workflows can catch this + retry).\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\nexport interface DepsCheckOptions {\n dir?: string;\n json?: boolean;\n}\n\ninterface ProviderManifestSummary {\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: Partial<\n Record<\n 'list' | 'get' | 'search' | 'create' | 'update' | 'delete',\n { allowed?: boolean }\n >\n >;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\ninterface Issue {\n /** Stable code so JSON consumers can branch. */\n code:\n | 'PROVIDER_NOT_FOUND'\n | 'NO_MATCHING_VERSION'\n | 'FIELD_NOT_EXPOSED'\n | 'TABLE_NOT_EXPOSED'\n | 'OP_NOT_ALLOWED'\n | 'BACKEND_UNREACHABLE';\n module: string;\n message: string;\n context?: Record<string, unknown>;\n}\n\nexport async function depsCheckCommand(options: DepsCheckOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n if (deps.length === 0) {\n if (options.json) {\n out(JSON.stringify({ ok: true, deps: [], issues: [] }, null, 2));\n } else {\n info('No dependencies declared. Nothing to check.');\n }\n return 0;\n }\n\n const issues: Issue[] = [];\n const perDepStatus: Array<{ module: string; ok: boolean; resolved_version: string | null }> = [];\n\n for (const dep of deps) {\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(dep.module)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n issues.push({\n code: 'PROVIDER_NOT_FOUND',\n module: dep.module,\n message: `Provider ${dep.module} not found on the backend. It may have been deleted or renamed.`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n // Network / 500 / etc. — treat as fatal; we can't reason about\n // drift without an answer from the backend.\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not reach the backend: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Pick the highest-matching version (newest-first per the\n // listVersions controller spec).\n let versions: VersionResponse[];\n try {\n versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n } catch (err) {\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not list versions: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n const matching = pickMatching(versions, dep.version);\n if (!matching) {\n issues.push({\n code: 'NO_MATCHING_VERSION',\n module: dep.module,\n message: `No published version satisfies ${dep.version}. Available: ${versions.map((v) => v.version).join(', ') || '(none)'}.`,\n context: { range: dep.version, available: versions.map((v) => v.version) },\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Drift checks against the matching version's manifest.\n const exposes = matching.manifest_jsonb.exposes ?? [];\n let depHealthy = true;\n\n for (const readEntry of dep.reads) {\n const exposeEntry = exposes.find((e) => e.table === readEntry.table);\n if (!exposeEntry) {\n issues.push({\n code: 'TABLE_NOT_EXPOSED',\n module: dep.module,\n message: `Table ${code(readEntry.table)} is no longer exposed by ${dep.module}@${matching.version}.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n continue;\n }\n const exposedFields = new Set(exposeEntry.fields);\n const missing = readEntry.fields.filter((f) => !exposedFields.has(f));\n if (missing.length > 0) {\n issues.push({\n code: 'FIELD_NOT_EXPOSED',\n module: dep.module,\n message: `Fields ${missing.map((f) => code(f)).join(', ')} on ${code(readEntry.table)} are no longer exposed by ${dep.module}@${matching.version}.`,\n context: {\n table: readEntry.table,\n missing,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n // Operation gate for list/get — we don't include search here since\n // the SDK doesn't expose it and the v1 plan doesn't either.\n const listAllowed = exposeEntry.operations?.list?.allowed !== false;\n const getAllowed = exposeEntry.operations?.get?.allowed !== false;\n if (!listAllowed && !getAllowed) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Provider ${dep.module}@${matching.version} disallows both list AND get on ${code(readEntry.table)} — no reads possible.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n }\n }\n\n // Write-side drift (only flagged when consumer declared writes).\n for (const writeEntry of dep.writes ?? []) {\n const exposeEntry = exposes.find((e) => e.table === writeEntry.table);\n if (!exposeEntry) continue; // already flagged via reads loop\n for (const op of writeEntry.operations) {\n const gate = exposeEntry.operations?.[op as 'create' | 'update' | 'delete'];\n if (!gate || gate.allowed !== true) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Write operation ${code(op)} on ${code(writeEntry.table)} is not allowed by ${dep.module}@${matching.version}.`,\n context: {\n table: writeEntry.table,\n operation: op,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n }\n }\n\n perDepStatus.push({\n module: dep.module,\n ok: depHealthy,\n resolved_version: matching.version,\n });\n }\n\n const ok = issues.length === 0;\n\n if (options.json) {\n out(\n JSON.stringify(\n { ok, deps: perDepStatus, issues },\n null,\n 2,\n ),\n );\n return ok ? 0 : 1;\n }\n\n // Human-readable output.\n for (const dep of perDepStatus) {\n if (dep.ok) {\n success(\n `${code(dep.module)} → ${dep.resolved_version ? `v${dep.resolved_version}` : dim('(no version)')}`,\n );\n } else {\n fail(`${code(dep.module)} ${dim('(drift detected)')}`);\n }\n }\n if (issues.length > 0) {\n out('');\n warn(`${issues.length} issue${issues.length === 1 ? '' : 's'}:`);\n for (const issue of issues) {\n out(` ${dim(`[${issue.code}]`)} ${issue.message}`);\n }\n out('');\n info(\n `Fix by removing/updating the dep (${code('dashwise deps remove <slug>')} then ${code('dashwise deps add <slug>')}) or by updating the provider.`,\n );\n } else {\n out('');\n success(`All ${perDepStatus.length} dependenc${perDepStatus.length === 1 ? 'y is' : 'ies are'} healthy.`);\n }\n return ok ? 0 : 1;\n}\n\n/**\n * Pick the newest version satisfying `range`. Range parsing is\n * intentionally minimal — covers `^x.y.z`, `~x.y.z`, `>=x.y.z`,\n * `<=x.y.z`, `>x.y.z`, `<x.y.z`, `=x.y.z`, and bare `x.y.z`. Full\n * SemVer support lives in the backend; this is a fail-soft heuristic\n * so check can give useful feedback even when offline tooling is the\n * canonical resolver.\n *\n * Caller passes `versions` in newest-first order (matches the\n * backend's `GET /:id/versions` contract).\n */\nfunction pickMatching(\n versions: VersionResponse[],\n range: string,\n): VersionResponse | null {\n for (const v of versions) {\n if (rangeSatisfied(v.version, range)) return v;\n }\n return null;\n}\n\nfunction rangeSatisfied(version: string, range: string): boolean {\n const vParts = parseSemver(version);\n if (!vParts) return false;\n const trimmed = range.trim();\n const opMatch = trimmed.match(/^(>=|<=|>|<|=|\\^|~)?(.+)$/);\n if (!opMatch) return false;\n const op = opMatch[1] ?? '=';\n const target = parseSemver(opMatch[2]);\n if (!target) return false;\n const cmp = compareSemver(vParts, target);\n switch (op) {\n case '=':\n return cmp === 0;\n case '>':\n return cmp > 0;\n case '<':\n return cmp < 0;\n case '>=':\n return cmp >= 0;\n case '<=':\n return cmp <= 0;\n case '^':\n // ^1.2.3 → >=1.2.3 <2.0.0 ; ^0.2.3 → >=0.2.3 <0.3.0 ; ^0.0.3 → >=0.0.3 <0.0.4\n if (cmp < 0) return false;\n if (target[0] > 0) return vParts[0] === target[0];\n if (target[1] > 0) return vParts[0] === 0 && vParts[1] === target[1];\n return vParts[0] === 0 && vParts[1] === 0 && vParts[2] === target[2];\n case '~':\n // ~1.2.3 → >=1.2.3 <1.3.0\n if (cmp < 0) return false;\n return vParts[0] === target[0] && vParts[1] === target[1];\n default:\n return false;\n }\n}\n\nfunction parseSemver(s: string): [number, number, number] | null {\n const m = s.trim().match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[a-zA-Z0-9.-]+)?$/);\n if (!m) return null;\n return [Number(m[1]), Number(m[2]), Number(m[3])];\n}\n\nfunction compareSemver(a: [number, number, number], b: [number, number, number]): number {\n for (let i = 0; i < 3; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return 0;\n}\n\n/**\n * Test seam — expose internal helpers for unit tests without making\n * them part of the CLI's public surface. Same pattern as\n * `lib/tarball.ts#__forTests`.\n */\nexport const __forTests = {\n rangeSatisfied,\n pickMatching,\n parseSemver,\n compareSemver,\n};\n","/**\n * `dashwise deps list` — show declared cross-module dependencies.\n *\n * Pure-local read from `module.json#dependencies`. No backend call;\n * runs offline. For drift detection (does each declared dep still\n * resolve against an installed provider?) use `dashwise deps check`.\n *\n * Output shapes:\n * - Default: human-readable columns + per-dep `reads:` / `writes:`\n * summaries.\n * - `--json`: stable JSON array of `{ module, version, reads,\n * writes?, purpose }` — same shape as the manifest's\n * `dependencies[]` entries. Pipes cleanly into `jq`.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { readManifestOrThrow, type ManifestDependency } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface DepsListOptions {\n dir?: string;\n json?: boolean;\n}\n\nexport async function depsListCommand(options: DepsListOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n\n if (options.json) {\n // Stable, pipe-friendly. Empty deps list → empty array (not null);\n // jq consumers don't have to handle the absent-key case.\n out(JSON.stringify(deps, null, 2));\n return 0;\n }\n\n if (deps.length === 0) {\n info('No dependencies declared in module.json.');\n info(`Run ${code('dashwise deps add <provider-slug>')} to add one.`);\n return 0;\n }\n\n out(`${deps.length} dependenc${deps.length === 1 ? 'y' : 'ies'} declared:`);\n out('');\n for (const dep of deps) {\n out(` ${code(dep.module)}@${dep.version}`);\n out(` ${dim('purpose:')} ${dep.purpose}`);\n if (dep.reads.length > 0) {\n out(` ${dim('reads:')}`);\n for (const r of dep.reads) {\n out(` ${code(r.table)} → ${r.fields.join(', ')}`);\n }\n }\n if (dep.writes && dep.writes.length > 0) {\n out(` ${dim('writes:')}`);\n for (const w of dep.writes) {\n out(\n ` ${code(w.table)} → ${w.fields.join(', ')} (${w.operations.join('/')})`,\n );\n }\n }\n out('');\n }\n return 0;\n}\n","/**\n * `dashwise deps remove <provider-slug>` — delete the dep entry from\n * `module.json#dependencies`.\n *\n * Pure-local mutation. Idempotent: removing a slug that's not declared\n * is treated as a no-op + reported (exit 0). Confirmation prompt\n * unless `--yes` is passed.\n *\n * After successful removal, prints a reminder to re-run\n * `dashwise module generate` so the typed wrappers no longer reference\n * the removed dep. (Generated `deps.<member>` access becomes a\n * compile error in consumer code — that's the right surface to catch\n * stale references.)\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface DepsRemoveOptions {\n dir?: string;\n /** Skip the confirmation prompt (CI / scripts). */\n yes?: boolean;\n}\n\nexport async function depsRemoveCommand(\n providerSlug: string,\n options: DepsRemoveOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps remove <provider-slug>`');\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const target = deps.find((d) => d.module === providerSlug);\n if (!target) {\n // Idempotent — not an error. Mirrors `apt remove` / `npm uninstall`\n // semantics for \"wasn't installed anyway.\"\n info(`No dependency on ${code(providerSlug)} declared; nothing to remove.`);\n return 0;\n }\n\n if (!options.yes && process.stdout.isTTY) {\n const answer = await select({\n message: `Remove dependency on ${providerSlug}?`,\n options: [\n { value: 'go', label: 'Yes, remove it' },\n { value: 'cancel', label: 'No, keep it' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n info('Aborted.');\n return 130;\n }\n }\n\n manifest.dependencies = deps.filter((d) => d.module !== providerSlug);\n // Normalize: if the array became empty, drop the key entirely so the\n // manifest matches what `dashwise module init` emits for a fresh\n // module (no `dependencies` key at all).\n if ((manifest.dependencies as ManifestDependency[]).length === 0) {\n delete manifest.dependencies;\n }\n\n try {\n writeManifest(manifest, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(`Removed dependency on ${code(providerSlug)}.`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n return 0;\n}\n","/**\n * `dashwise query` — run typed queries against the local module's\n * installation via the @dashai/sdk query plane.\n *\n * Three modes:\n * --inline \"<expr>\" Evaluate a one-liner. `qb`, `deps`, `db` are\n * pre-bound to the local module's generated SDK.\n * Example:\n * dashwise query --inline \"qb.tasks.where({done:false}).count()\"\n * --file <path> Dynamic-import a .mjs/.js file. The file should\n * export a default that's either a Query, an\n * AggQuery, or a Promise.\n * Example file:\n * import { qb } from '@dashai/generated';\n * export default qb.tasks.where({done:false}).limit(20);\n * --repl Open a Node REPL with the generated SDK pre-bound.\n * Top-level await supported. Ctrl-D to exit.\n *\n * All three modes:\n * - Run in the current directory (must contain `module.json` +\n * `node_modules/@dashai/generated`).\n * - Load env from `.env.local` if present (matches the scaffold's\n * dev-loop convention); DASHWISE_API_URL / _INSTALLATION_ID /\n * _API_TOKEN must be set before the SDK can hit the backend.\n * - Print the result as pretty-printed JSON. `--json` flag emits\n * compact JSON for piping.\n *\n * v1 limits:\n * - --file accepts .mjs / .js only. .ts requires `tsx` which we\n * don't bundle yet. Workaround: `npx tsx <path>` directly.\n * - --inline expression must be valid JS (or `await`-friendly\n * pattern). TS syntax not supported in --inline either.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §6.3, §9.\n */\n\nimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, resolve as pathResolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { manifestPath, readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../lib/output.js';\n\nexport interface QueryCommandOptions {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n /**\n * Phase 5 `.explain()` flag (2026-05-19). When true, the runner\n * calls `.explain()` on the resulting Query/JoinedQuery/AggQuery\n * (returning the Postgres plan envelope) instead of `.execute()`.\n * No-op for `--repl` mode — REPL users call `.explain()` themselves.\n *\n * Backend MVP supports joined queries only; bare own/dep/view paths\n * reject server-side with EXPLAIN_NOT_SUPPORTED_YET. The CLI passes\n * the call through unchanged and surfaces the typed error to the\n * caller.\n */\n explain?: boolean;\n /**\n * Phase 6 streaming flag (2026-05-20). When true, the runner calls\n * `.stream()` instead of `.execute()` and prints rows incrementally\n * as JSON-lines (one row per line, terminated by `\\n`). Lets users\n * see progress on big queries + Ctrl-C cleanly midway. Mutually\n * exclusive with `--explain` (different ops) and `--repl` (REPL\n * users call `.stream()` themselves and use `for await`).\n *\n * `--json` is implied — streaming always emits JSON-lines, never\n * the pretty-printed result wrapper. Bare-array `--json` output is\n * what most users want anyway when piping into `jq`.\n */\n stream?: boolean;\n}\n\nexport async function queryCommand(options: QueryCommandOptions): Promise<number> {\n const projectRoot = pathResolve(options.dir ?? process.cwd());\n\n // Sanity: must be inside a module project.\n try {\n readManifestOrThrow(projectRoot);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Must have run `dashwise module generate` so @dashai/generated\n // exists. Surface the missing-package case with the right next step.\n const generatedPath = join(\n projectRoot,\n 'node_modules',\n '@dashai',\n 'generated',\n );\n if (!existsSync(generatedPath)) {\n fail(\n `No ${code('@dashai/generated')} in ${code('node_modules')}. Run ${code('dashwise module generate')} first.`,\n );\n return 1;\n }\n\n // Best-effort env loading from .env.local — matches what the\n // scaffold ships + what `dashwise module dev` would inject. The\n // generated SDK reads these via `process.env.DASHWISE_*` so we\n // hydrate `process.env` directly (vs. a richer dotenv parser —\n // the format is k=v lines, no quoting needed for the dev env).\n hydrateEnvFromDotenvLocal(projectRoot);\n\n // Exactly one mode flag must be set.\n const modes = [\n options.inline !== undefined ? 'inline' : null,\n options.file !== undefined ? 'file' : null,\n options.repl === true ? 'repl' : null,\n ].filter(Boolean);\n if (modes.length === 0) {\n fail('Pass one of: `--inline \"expr\"`, `--file <path>`, or `--repl`.');\n return 1;\n }\n if (modes.length > 1) {\n fail(`--inline / --file / --repl are mutually exclusive (got: ${modes.join(', ')}).`);\n return 1;\n }\n\n // Phase 5 (2026-05-19): --explain is meaningless with --repl (REPL\n // users call .explain() themselves). Reject the combo with a clear\n // message rather than silently ignoring.\n if (options.explain === true && options.repl === true) {\n fail('--explain has no effect with --repl. In the REPL, call `.explain()` directly on your builder.');\n return 1;\n }\n // Phase 6 streaming (2026-05-20): same logic for --stream + --repl.\n if (options.stream === true && options.repl === true) {\n fail('--stream has no effect with --repl. In the REPL, call `.stream()` directly + use `for await`.');\n return 1;\n }\n // --explain and --stream are different operations (return plan vs.\n // stream rows). Mutual exclusion prevents accidental misuse like\n // \"stream the explain plan\" which has no defined semantic.\n if (options.explain === true && options.stream === true) {\n fail('--explain and --stream are mutually exclusive — `.explain()` returns a single plan envelope; `.stream()` yields rows.');\n return 1;\n }\n const explain = options.explain === true;\n const stream = options.stream === true;\n\n if (options.repl) return runRepl(generatedPath);\n if (options.file !== undefined)\n return runFile(options.file, projectRoot, options.json === true, explain, stream);\n if (options.inline !== undefined)\n return runInline(\n options.inline,\n projectRoot,\n generatedPath,\n options.json === true,\n explain,\n stream,\n );\n // Unreachable per the modes check above.\n return 1;\n}\n\n// ── Mode: --inline ──────────────────────────────────────────────────────\n\n/**\n * Evaluate a one-liner expression with `qb`, `deps`, `db` in scope.\n *\n * Strategy: write a temp `.mjs` file that imports the generated SDK\n * + evaluates the expression as a default export, then dynamic-import\n * it. The temp file lives in tmpdir; cleaned up on the way out (or\n * left on disk if the process is killed — best-effort cleanup).\n *\n * Reason for temp-file vs. `new Function(...)`: dynamic import gives\n * us proper ESM semantics + module-resolution against `node_modules/@dashai/generated`,\n * which `new Function` doesn't. Cost is one syscall per invocation.\n */\nasync function runInline(\n expression: string,\n projectRoot: string,\n _generatedPath: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const tmpDir = mkdtempSync(join(tmpdir(), 'dashwise-query-'));\n const tmpFile = join(tmpDir, 'inline.mjs');\n // Strip a trailing semicolon if present so the embedded expression\n // is a valid value position.\n const cleanedExpr = expression.trim().replace(/;\\s*$/, '');\n const source = [\n \"import { qb, deps, db } from '@dashai/generated';\",\n `export default (async () => (${cleanedExpr}))();`,\n '',\n ].join('\\n');\n writeFileSync(tmpFile, source, 'utf-8');\n try {\n return await importAndPrint(tmpFile, projectRoot, jsonCompact, explain, stream);\n } finally {\n try {\n rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup. tmp dirs get reaped by the OS.\n }\n }\n}\n\n// ── Mode: --file ────────────────────────────────────────────────────────\n\n/**\n * Run a `.mjs` / `.js` file via dynamic import. The file should\n * export a default that's a Query / AggQuery / Promise / value.\n *\n * `.ts` files are NOT supported in v1 — would require bundling `tsx`\n * or running through `node --import tsx`. Users can shell out via\n * `npx tsx <file>` directly for TS today.\n */\nasync function runFile(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const abs = pathResolve(projectRoot, file);\n if (!existsSync(abs)) {\n fail(`File not found: ${code(abs)}`);\n return 1;\n }\n if (!/\\.(mjs|js)$/.test(abs)) {\n fail(\n `Only .mjs / .js files are supported in v1. For .ts files, run ${code('npx tsx <file>')} directly. (Tracked: bundle tsx for native .ts support.)`,\n );\n return 1;\n }\n return importAndPrint(abs, projectRoot, jsonCompact, explain, stream);\n}\n\n// ── Mode: --repl ────────────────────────────────────────────────────────\n\n/**\n * Open an interactive Node REPL with the generated SDK pre-bound.\n *\n * Implementation: Node's built-in `repl` module. The generated SDK is\n * imported once at startup + its exports (`qb`, `deps`, `db`) are\n * added to the REPL's context object. Top-level await works because\n * Node's REPL has supported it since v12.\n *\n * Exit with `.exit` or Ctrl-D. Stack traces from query errors stay\n * in the REPL so users can keep iterating.\n */\nasync function runRepl(generatedPath: string): Promise<number> {\n let generated: Record<string, unknown>;\n try {\n generated = await dynamicImportFromPath(generatedPath);\n } catch (err) {\n fail(\n `Could not import ${code('@dashai/generated')}: ${(err as Error).message}`,\n );\n info(\n `Try running ${code('dashwise module generate')} to refresh the typed wrappers.`,\n );\n return 1;\n }\n\n info(`${code('dashwise query --repl')} — Node REPL with qb / deps / db pre-bound.`);\n info(`Try: ${code('await qb.<table>.execute()')} Ctrl-D to exit.`);\n out('');\n\n // Dynamic require for Node's repl module — keep it lazy so the\n // command's startup cost stays low for the inline/file modes.\n const repl = await import('node:repl');\n const server = repl.start({\n prompt: `${code('dashwise')}${dim('>')} `,\n useColors: true,\n useGlobal: false,\n });\n // Inject the generated SDK's exports into the REPL context so\n // users type `qb.tasks.execute()` without imports.\n for (const [key, value] of Object.entries(generated)) {\n Object.defineProperty(server.context, key, {\n configurable: false,\n enumerable: true,\n writable: false,\n value,\n });\n }\n\n return new Promise<number>((resolveExit) => {\n server.on('exit', () => {\n out(dim('Goodbye.'));\n resolveExit(0);\n });\n });\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Dynamic-import `file` (resolving from `projectRoot`'s\n * `node_modules`), await the default export if it's a Promise / Query\n * / AggQuery, and pretty-print the result.\n */\nasync function importAndPrint(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n // Switch cwd so bare imports inside the file resolve against the\n // project's `node_modules` instead of the CLI's own. Saved + restored\n // around the import — defensive in case the consumer's code touches\n // process.cwd elsewhere.\n const originalCwd = process.cwd();\n try {\n process.chdir(projectRoot);\n const url = pathToFileURL(file).toString();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import(url);\n let result = mod.default;\n // Default-export shapes we handle:\n // - Promise<T> → await it\n // - Query / AggQuery → .execute() (or .explain() if --explain,\n // or .stream() if --stream)\n // - Anything else → print as-is\n if (result && typeof result.then === 'function') {\n result = await result;\n }\n if (result && typeof result.toAst === 'function') {\n // Phase 6 streaming (2026-05-20): --stream takes precedence over\n // --execute (they're mutually exclusive at the option-parse level,\n // but ordering matters at dispatch time). Iterate the async\n // iterable + print one JSON-line per row so consumers can pipe\n // into jq / line-oriented tools.\n if (stream && typeof result.stream === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const iterable = result.stream() as AsyncIterable<unknown>;\n let rowCount = 0;\n for await (const row of iterable) {\n out(JSON.stringify(row));\n rowCount++;\n }\n // Emit a final summary on stderr so it doesn't pollute the\n // JSON-lines stdout stream. Consumers piping into jq see ONLY\n // the data; humans see \"streamed N rows\" at the bottom.\n if (!jsonCompact) {\n info(`Streamed ${rowCount} row${rowCount === 1 ? '' : 's'}.`);\n }\n return 0;\n }\n // Phase 5 `.explain()` (2026-05-19): if --explain was passed,\n // call .explain() instead of .execute(). All three builder\n // shapes (Query, JoinedQuery, AggQuery) expose .explain() since\n // the SDK slice landed alongside this CLI flag.\n if (explain && typeof result.explain === 'function') {\n result = await result.explain();\n } else if (typeof result.execute === 'function') {\n result = await result.execute();\n }\n }\n if (jsonCompact) {\n out(JSON.stringify(result));\n } else {\n out(JSON.stringify(result, null, 2));\n }\n return 0;\n } catch (err) {\n fail(`Query failed: ${(err as Error).message}`);\n if (process.env.DASHWISE_DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n return 1;\n } finally {\n process.chdir(originalCwd);\n }\n}\n\n/**\n * Resolve `@dashai/generated` from the project's node_modules and\n * dynamic-import its entry. Returns the module's exports object.\n */\nasync function dynamicImportFromPath(\n generatedDir: string,\n): Promise<Record<string, unknown>> {\n // Project-local @dashai/generated has `index.js` per the codegen\n // emitter; resolve directly rather than going through Node's package\n // resolution to keep the path deterministic.\n const entry = join(generatedDir, 'index.js');\n if (!existsSync(entry)) {\n throw new Error(`Expected ${entry} to exist. Did 'dashwise module generate' run?`);\n }\n const url = pathToFileURL(entry).toString();\n return (await import(url)) as Record<string, unknown>;\n}\n\n/**\n * Read `.env.local` from `projectRoot` and merge into `process.env`\n * without overwriting existing values. Supports `KEY=value` lines\n * + `#`-prefixed comments + blank lines — same dialect the scaffold's\n * `.env.local.example` uses. Robust enough for the dev-loop env.\n */\nfunction hydrateEnvFromDotenvLocal(projectRoot: string): void {\n const envFile = join(projectRoot, '.env.local');\n if (!existsSync(envFile)) return;\n const raw = readFileSync(envFile, 'utf-8');\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq <= 0) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n // Strip a single surrounding quote pair if present.\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n}\n\n// Use manifestPath() from manifest-io so the import isn't tree-shaken\n// for unused-import lint without an actual call.\nvoid manifestPath;\n","/**\n * `dashwise module query-log` — read the per-module SDK query log.\n *\n * Hits `GET /api/modules/:moduleId/query-log?since=...&slow=...&limit=...`\n * (added in dashwise-backend Phase 6 slice 6.4). Workspace-member-\n * scoped on the server side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * Module resolution order:\n * 1. `--module <id-or-slug>` if provided\n * 2. `module.json#module.slug` in the current directory if present\n * 3. Otherwise fail with a \"which module?\" message\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (the last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll, so very busy\n * modules may see \"(more entries above)\" between polls if log\n * volume exceeds 500/5s.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readManifestOrThrow } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleQueryLogOptions {\n /**\n * Module to read the log for. Accepts a numeric id (`123`) or a\n * slug (`my-module`). If omitted, falls back to the slug in the\n * current directory's `module.json`.\n */\n module?: string;\n /**\n * Filter to slow queries only (duration_ms > 500 — matches the\n * SDK/backend slow-query threshold).\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n * Passed through to the backend's validator.\n */\n since?: string;\n /**\n * Max rows to fetch per call. Default 50; backend caps at 500.\n */\n limit?: number;\n /**\n * Poll for new entries every 5s. Stops on Ctrl-C. Mutually\n * exclusive with `--json` (tail mode prints the table format\n * incrementally).\n */\n tail?: boolean;\n /**\n * Emit compact JSON instead of the table. Useful for piping into\n * `jq` / scripting. Ignored when `--tail` is set.\n */\n json?: boolean;\n /**\n * Override project directory (for `module.json` slug lookup).\n * Defaults to `process.cwd()`. Only consulted when `--module` is\n * absent.\n */\n dir?: string;\n}\n\ninterface QueryLogRow {\n id: string;\n request_id: string;\n installation_id: number;\n module_id: number;\n endpoint: 'query' | 'explain';\n ast_hash: string | null;\n duration_ms: number;\n row_count: number | null;\n error_code: string | null;\n error_message: string | null;\n created_at: string;\n}\n\ninterface QueryLogResponse {\n entries: QueryLogRow[];\n count: number;\n}\n\ninterface ModuleByIdResponse {\n id: number;\n slug: string;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleQueryLogCommand(\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Resolve the moduleId. The user can pass `--module <id-or-slug>`\n // or we infer from the current directory's manifest.\n let moduleId: number;\n try {\n moduleId = await resolveModuleId(options.module, options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n if (options.tail) {\n return runTail(moduleId, options);\n }\n return runOnce(moduleId, options);\n}\n\n// ── One-shot mode (default) ──────────────────────────────────────\n\nasync function runOnce(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n const params: Record<string, string> = {};\n if (options.slow) params.slow = 'true';\n if (options.since) params.since = options.since;\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n const qs = new URLSearchParams(params).toString();\n const path = `/api/modules/${moduleId}/query-log${qs ? `?${qs}` : ''}`;\n\n let body: QueryLogResponse;\n try {\n body = await apiRequest<QueryLogResponse>('GET', path);\n } catch (err) {\n return handleApiError(err);\n }\n\n if (options.json) {\n out(JSON.stringify(body));\n return 0;\n }\n\n if (body.entries.length === 0) {\n info(\n options.slow\n ? 'No slow queries in the requested window.'\n : 'No query log entries in the requested window.',\n );\n return 0;\n }\n\n renderTable(body.entries);\n out('');\n info(`${body.count} ${body.count === 1 ? 'entry' : 'entries'}.`);\n return 0;\n}\n\n// ── --tail mode ──────────────────────────────────────────────────\n\nasync function runTail(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Initial fetch — use whatever filters the user passed plus a\n // reasonable starting window if `--since` wasn't set.\n const initialParams: Record<string, string> = {};\n if (options.slow) initialParams.slow = 'true';\n initialParams.since = options.since ?? '5m';\n if (typeof options.limit === 'number') initialParams.limit = String(options.limit);\n const initialQs = new URLSearchParams(initialParams).toString();\n\n info(`Tailing query log for module ${moduleId}. Ctrl-C to stop.`);\n out('');\n\n // Track the most-recent created_at across polls so we can fetch\n // strictly-new rows. The backend's `since` param does a NOW()-based\n // window, so we use a small overlap (2s) to ensure we don't miss\n // entries whose created_at lands between poll cycles. De-dup by\n // request_id locally to suppress overlap repeats.\n const seenIds = new Set<string>();\n let firstPoll = true;\n\n // Print headers once up front; subsequent polls append rows without\n // re-printing.\n printTableHeader();\n\n // Initial poll uses the user-specified since; subsequent polls use\n // a fixed 7s window (5s poll interval + 2s overlap).\n while (true) {\n try {\n const path = `/api/modules/${moduleId}/query-log?${firstPoll ? initialQs : buildTailParams(options)}`;\n const body = await apiRequest<QueryLogResponse>('GET', path);\n\n // Print rows in chronological order (response is DESC, reverse\n // for the tail's natural \"latest at bottom\" reading order).\n const newRows: QueryLogRow[] = [];\n for (const row of [...body.entries].reverse()) {\n if (seenIds.has(row.request_id)) continue;\n seenIds.add(row.request_id);\n newRows.push(row);\n }\n for (const row of newRows) {\n out(formatRow(row));\n }\n firstPoll = false;\n } catch (err) {\n // Don't crash the tail on transient errors — log + continue.\n info(dim(`(tail poll error: ${(err as Error).message})`));\n }\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nfunction buildTailParams(options: ModuleQueryLogOptions): string {\n const params: Record<string, string> = { since: '7s' };\n if (options.slow) params.slow = 'true';\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n return new URLSearchParams(params).toString();\n}\n\n// ── Module-id resolution ─────────────────────────────────────────\n\nasync function resolveModuleId(\n moduleArg: string | undefined,\n dir: string | undefined,\n): Promise<number> {\n // 1. Explicit --module: numeric → use as-is; slug → lookup.\n if (moduleArg && moduleArg.length > 0) {\n const asInt = Number.parseInt(moduleArg, 10);\n if (Number.isFinite(asInt) && String(asInt) === moduleArg) {\n return asInt;\n }\n return lookupModuleIdBySlug(moduleArg);\n }\n // 2. Fall back to module.json in the project directory.\n const projectRoot = dir ?? process.cwd();\n try {\n const manifest = readManifestOrThrow(projectRoot);\n if (manifest?.module?.slug) {\n return lookupModuleIdBySlug(manifest.module.slug);\n }\n } catch {\n // Manifest absent or malformed — fall through to the error below.\n }\n throw new Error(\n `No module specified. Pass --module <id-or-slug> or run inside a module project directory containing module.json.`,\n );\n}\n\nasync function lookupModuleIdBySlug(slug: string): Promise<number> {\n const found = await apiRequest<ModuleByIdResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n if (!found || typeof found.id !== 'number') {\n throw new Error(`Module ${code(slug)} not found.`);\n }\n return found.id;\n}\n\n// ── Error handling ───────────────────────────────────────────────\n\nfunction handleApiError(err: unknown): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err.status === 403) {\n fail(\n `Forbidden — you are not a member of this module's owner workspace. ` +\n `Use \\`dashwise workspace list\\` to see what you have access to.`,\n );\n return 1;\n }\n if (err.status === 404) {\n fail(`Module not found.`);\n return 1;\n }\n }\n fail(`Could not load query log: ${(err as Error).message}`);\n return 1;\n}\n\n// ── Table rendering ──────────────────────────────────────────────\n\n/**\n * Column widths chosen to fit a typical 80-col terminal plus a\n * little slack. ID is the bigint serialized as string (up to ~19\n * digits); we show only the last 8 for compactness — the request_id\n * is the real trace anchor anyway.\n */\nconst COL_WIDTHS = {\n time: 19, // \"YYYY-MM-DD HH:MM:SS\"\n endpoint: 7, // \"query\" | \"explain\"\n ms: 6, // \"12345\" with margin\n rows: 5,\n code: 18,\n request: 12, // first 12 chars of request_id (most are UUIDs)\n};\n\nfunction renderTable(entries: QueryLogRow[]): void {\n out('');\n printTableHeader();\n // Server returns DESC (newest first) — preserve that for one-shot\n // mode so the most-recent activity is at the top of the screen.\n for (const row of entries) {\n out(formatRow(row));\n }\n}\n\nfunction printTableHeader(): void {\n out(\n [\n 'TIME'.padEnd(COL_WIDTHS.time),\n 'ENDPT'.padEnd(COL_WIDTHS.endpoint),\n 'MS'.padStart(COL_WIDTHS.ms),\n 'ROWS'.padStart(COL_WIDTHS.rows),\n 'CODE'.padEnd(COL_WIDTHS.code),\n 'REQ',\n ].join(' '),\n );\n out(\n [\n '-'.repeat(COL_WIDTHS.time),\n '-'.repeat(COL_WIDTHS.endpoint),\n '-'.repeat(COL_WIDTHS.ms),\n '-'.repeat(COL_WIDTHS.rows),\n '-'.repeat(COL_WIDTHS.code),\n '-'.repeat(COL_WIDTHS.request),\n ].join(' '),\n );\n}\n\nfunction formatRow(row: QueryLogRow): string {\n const time = formatTimestamp(row.created_at);\n const endpoint = row.endpoint.padEnd(COL_WIDTHS.endpoint);\n const ms = String(row.duration_ms).padStart(COL_WIDTHS.ms);\n const rows =\n row.row_count === null ? '—'.padStart(COL_WIDTHS.rows) : String(row.row_count).padStart(COL_WIDTHS.rows);\n const errCode = row.error_code ?? '';\n const codeCol = errCode\n ? code(errCode).padEnd(COL_WIDTHS.code + (code(errCode).length - errCode.length))\n : 'OK'.padEnd(COL_WIDTHS.code);\n const req = row.request_id.slice(0, COL_WIDTHS.request);\n return [time, endpoint, ms, rows, codeCol, dim(req)].join(' ');\n}\n\nfunction formatTimestamp(iso: string): string {\n // YYYY-MM-DD HH:MM:SS for compact display; preserves UTC if the\n // input is Z-suffixed. We deliberately don't convert to local TZ\n // here so log entries are reproducible across consumers in\n // different timezones.\n return iso.slice(0, 19).replace('T', ' ');\n}\n\n// ── Misc ─────────────────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * `dashwise module action-log` — read the per-installation server-action\n * audit log (cross-module + own-module dispatches).\n *\n * Hits `GET /api/modules/runtime/installations/:installationId/action-log`\n * (added in dashwise-backend Phase 7 slice 7.5a). Workspace-member-scoped\n * server-side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * **Why per-installation, not per-module**: cross-module dispatches are\n * events between TWO installations. The audit row keys by\n * installation id (not module id). The CLI surfaces either side\n * (`--role caller` for outbound; `--role provider` for inbound) so\n * authors can debug both directions from the same command.\n *\n * The user provides `--installation <id>` directly. A `--module <slug>`\n * convenience that resolves to the user's default-workspace\n * installation is a planned follow-up; it needs a new backend\n * \"list-installations-by-module-in-workspace\" endpoint.\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleActionLogOptions {\n /**\n * Installation to read the log for (numeric id). Mutually exclusive\n * with `module` — exactly one must be set. (Validated by the CLI\n * binder; the action handler treats both as optional + checks.)\n */\n installation?: number;\n /**\n * Module slug — resolves to the caller's accessible installation\n * via `GET /api/modules/by-slug/:slug/my-installation`. Convenience\n * for the common case where the user has one workspace's\n * installation; multi-workspace authors should use `--installation`\n * with an explicit id (or `dashwise workspace use <slug>` to fix\n * the default).\n */\n module?: string;\n /**\n * Which side of cross-module dispatches to query.\n * - `caller` (default) → outbound actions THIS installation invoked\n * - `provider` → inbound actions OTHER modules invoked on THIS installation\n */\n role?: 'caller' | 'provider';\n /**\n * Filter to slow actions only (elapsed_ms > 500 — matches the\n * SDK/backend slow threshold). Uses the partial slow-action index.\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n */\n since?: string;\n /** Filter to cross-module dispatches only (cross_module=true rows). */\n crossModuleOnly?: boolean;\n /** Max rows per call. Default 50; backend caps at 500. */\n limit?: number;\n /**\n * Poll every 5s for new entries. Stops on Ctrl-C. Mutually exclusive\n * with `--json` (tail mode prints incrementally as rows arrive).\n */\n tail?: boolean;\n /** Compact JSON instead of the table. Ignored when `--tail` is set. */\n json?: boolean;\n}\n\ninterface ActionLogRow {\n id: string;\n request_id: string;\n caller_installation_id: number;\n caller_module_slug: string;\n caller_user_id: number | null;\n provider_installation_id: number;\n provider_module_slug: string;\n action_name: string;\n input_hash: string;\n output_hash: string | null;\n ok: boolean;\n error_code: string | null;\n elapsed_ms: number;\n cross_module: boolean;\n created_at: string;\n}\n\ninterface ActionLogResponse {\n entries: ActionLogRow[];\n count: number;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleActionLogCommand(\n options: ModuleActionLogOptions,\n): Promise<number> {\n // Validate mutually-exclusive scope flags.\n if (options.installation === undefined && options.module === undefined) {\n fail('Must pass either `--installation <id>` or `--module <slug>`.');\n return 1;\n }\n if (options.installation !== undefined && options.module !== undefined) {\n fail('`--installation` and `--module` are mutually exclusive — pass one or the other.');\n return 1;\n }\n\n // If --module was passed, resolve to an installation id.\n let installationId = options.installation;\n if (installationId === undefined && options.module !== undefined) {\n try {\n const resolved = await apiRequest<{ installation_id: number; module_slug: string }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(options.module)}/my-installation`,\n );\n installationId = resolved.installation_id;\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n }\n if (options.tail) {\n return runTail(installationId as number, options);\n }\n return runOnce(installationId as number, options);\n}\n\n// ── One-shot mode ────────────────────────────────────────────────\n\nasync function runOnce(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (options.since !== undefined) params.since = options.since;\n if (options.limit !== undefined) params.limit = String(options.limit);\n\n let response: ActionLogResponse;\n try {\n response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n\n if (options.json) {\n out(JSON.stringify(response));\n return 0;\n }\n\n printTable(response.entries);\n if (response.entries.length === 0) {\n info('No entries.');\n }\n return 0;\n}\n\n// ── Tail mode ────────────────────────────────────────────────────\n\nasync function runTail(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n if (options.json) {\n fail('`--tail` and `--json` are mutually exclusive.');\n return 1;\n }\n info(`Tailing action log for installation ${code(String(installationId))} every 5s. Ctrl-C to stop.`);\n\n let lastSeen: string | undefined;\n const printed = new Set<string>();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (lastSeen !== undefined) params.since = lastSeen;\n else if (options.since !== undefined) params.since = options.since;\n params.limit = String(options.limit ?? 100);\n\n try {\n const response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n // Backend returns rows newest-first; we want oldest-first when\n // tailing so the user reads down the page. Reverse + dedup by id.\n const fresh = response.entries.filter((e) => !printed.has(e.id)).reverse();\n if (fresh.length > 0) {\n for (const entry of fresh) {\n printed.add(entry.id);\n printRow(entry);\n }\n // Update since-anchor to the newest row we just printed.\n lastSeen = fresh[fresh.length - 1].created_at;\n }\n } catch (err) {\n // Tail mode swallows transient errors + keeps polling. Fatal\n // (401/403) drops out so the user knows to re-login.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n return mapAndPrintError(err, false);\n }\n dim(`(tail: transient error — ${(err as Error).message})`);\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n}\n\n// ── Output ───────────────────────────────────────────────────────\n\nfunction printTable(rows: ActionLogRow[]): void {\n if (rows.length === 0) {\n out('');\n out(' (no entries)');\n out('');\n return;\n }\n const widths = {\n time: 19,\n elapsed: 5,\n cross: 5,\n caller: 18,\n action: 22,\n code: 18,\n };\n out('');\n out(\n `${'TIME'.padEnd(widths.time)} ${'MS'.padStart(widths.elapsed)} ${'CROSS'.padEnd(widths.cross)} ${'CALLER'.padEnd(widths.caller)} ${'ACTION'.padEnd(widths.action)} ${'CODE'.padEnd(widths.code)}`,\n );\n out(\n `${'-'.repeat(widths.time)} ${'-'.repeat(widths.elapsed)} ${'-'.repeat(widths.cross)} ${'-'.repeat(widths.caller)} ${'-'.repeat(widths.action)} ${'-'.repeat(widths.code)}`,\n );\n for (const r of rows) {\n printRow(r);\n }\n out('');\n info(`${rows.length} entr${rows.length === 1 ? 'y' : 'ies'}.`);\n}\n\nfunction printRow(r: ActionLogRow): void {\n const time = r.created_at.slice(0, 19).replace('T', ' ');\n const cross = r.cross_module ? code('yes') : dim(' no');\n const codeCol = r.ok ? dim('-') : code(r.error_code ?? 'ERROR');\n out(\n `${time.padEnd(19)} ${String(r.elapsed_ms).padStart(5)} ${cross.padEnd(5)} ${r.caller_module_slug.padEnd(18)} ${r.action_name.padEnd(22)} ${codeCol}`,\n );\n}\n\nfunction mapAndPrintError(err: unknown, json: boolean | undefined): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n const msg = 'Not logged in. Run `dashwise login` first.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 403) {\n const msg = 'Workspace-member access required for this installation.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FORBIDDEN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 404) {\n const msg = 'Installation not found.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'INSTALLATION_NOT_FOUND', message: msg } }));\n else fail(msg);\n return 1;\n }\n }\n const msg = `Could not fetch action log: ${(err as Error).message}`;\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n else fail(msg);\n return 1;\n}\n"]}