@flisk-sh/flisk 1.4.2 → 1.4.5

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.
Files changed (83) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +119 -43
  3. package/cli/dist/backend-languages/bun.js +5 -0
  4. package/cli/dist/backend-languages/go.js +3 -1
  5. package/cli/dist/cli.js +9 -0
  6. package/cli/dist/commands/completion.js +8 -1
  7. package/cli/dist/commands/config.js +130 -55
  8. package/cli/dist/commands/doctor.js +16 -15
  9. package/cli/dist/commands/logs.js +1 -0
  10. package/cli/dist/commands/project.js +1 -0
  11. package/cli/dist/commands/resource.js +39 -11
  12. package/cli/dist/commands/status.js +18 -9
  13. package/cli/dist/commands/up.js +102 -17
  14. package/cli/dist/frontend-frameworks/next.js +197 -0
  15. package/cli/dist/frontend-frameworks/react.js +81 -12
  16. package/cli/dist/frontend-frameworks/registry.js +5 -4
  17. package/cli/dist/frontend-frameworks/vue.js +82 -12
  18. package/cli/dist/generator/resource-templates.js +2 -4
  19. package/cli/dist/generator/template-engine.js +5 -3
  20. package/cli/dist/utils/cold-preflight.js +3 -2
  21. package/cli/dist/utils/config-explain.js +197 -0
  22. package/cli/dist/utils/demo-reset.js +22 -0
  23. package/cli/dist/utils/discovery-paths.js +7 -1
  24. package/cli/dist/utils/host-port-plan.js +8 -3
  25. package/cli/dist/utils/port-conflict-fix.js +16 -14
  26. package/cli/dist/utils/port-occupant.js +35 -0
  27. package/cli/dist/utils/project-features.js +7 -16
  28. package/cli/dist/utils/project-templates.js +8 -8
  29. package/cli/dist/utils/resource-features.js +5 -5
  30. package/cli/dist/utils/service-manifest.js +1 -0
  31. package/cli/dist/utils/service-urls.js +11 -0
  32. package/cli/dist/utils/startup-report.js +4 -3
  33. package/cli/dist/utils/tar.js +33 -28
  34. package/cli/dist/utils/tilt-process.js +4 -3
  35. package/cli/dist/utils/windows-doctor.js +18 -15
  36. package/cli/dist-bundle/{chunk-IGN5UC3P.js → chunk-4J2FLFUA.js} +14 -7
  37. package/cli/dist-bundle/{chunk-ETKUVKJ2.js → chunk-BMHPPX2Q.js} +10 -10
  38. package/cli/dist-bundle/chunk-BP2M4OJ4.js +2 -0
  39. package/cli/dist-bundle/{chunk-53L2JN7G.js → chunk-CGTWXWBU.js} +1 -1
  40. package/cli/dist-bundle/chunk-GPUJ55MI.js +3 -0
  41. package/cli/dist-bundle/{chunk-5QBYM33Q.js → chunk-LUUJ4JB7.js} +1 -1
  42. package/cli/dist-bundle/chunk-PEZQEZVV.js +17 -0
  43. package/cli/dist-bundle/{chunk-MWOVYIBB.js → chunk-SFOFTVYM.js} +5 -5
  44. package/cli/dist-bundle/{chunk-3XODDLRJ.js → chunk-TIYTGN5R.js} +1 -1
  45. package/cli/dist-bundle/{chunk-YNCBBJ4V.js → chunk-U42XZWXB.js} +1 -1
  46. package/cli/dist-bundle/chunk-ULMQVD7J.js +122 -0
  47. package/cli/dist-bundle/chunk-V36PT2HF.js +24 -0
  48. package/cli/dist-bundle/{chunk-I7TGIK5N.js → chunk-VMVTECCK.js} +1 -1
  49. package/cli/dist-bundle/{chunk-DU2BN46C.js → chunk-Z5QEE4SW.js} +1 -1
  50. package/cli/dist-bundle/cli.js +607 -375
  51. package/cli/dist-bundle/cold-preflight-3BNDOLGS.js +2 -0
  52. package/cli/dist-bundle/{demo-stage-OHNTP2UJ.js → demo-stage-G4W23BXW.js} +1 -1
  53. package/cli/dist-bundle/{extension-fetch-VEFSCG4B.js → extension-fetch-KIPYDIRM.js} +1 -1
  54. package/cli/dist-bundle/{open-XROJ6YEY.js → open-HQFT6WDC.js} +1 -1
  55. package/cli/dist-bundle/project-JZO2CPZZ.js +2 -0
  56. package/cli/dist-bundle/{project-templates-EYSQG2EO.js → project-templates-IMJ3OX5I.js} +1 -1
  57. package/cli/dist-bundle/{services-BIMF6MVU.js → services-GLFKZBBZ.js} +1 -1
  58. package/cli/dist-bundle/{tilt-port-owner-ZY5M2JC4.js → tilt-port-owner-PJN4MPYE.js} +1 -1
  59. package/cli/package.json +1 -1
  60. package/package.json +1 -1
  61. package/runtime/engine/topologies/platform/docker/compose/compose.star +40 -4
  62. package/runtime/engine/topologies/platform/docker/dockerfile/language_dockerfile.star +6 -0
  63. package/runtime/engine/topologies/platform/docker/dockerfile/next_dockerfile.star +83 -0
  64. package/runtime/engine/topologies/platform/docker/index.star +4 -0
  65. package/runtime/engine/topologies/platform/docker/layers/prisma/filesystem_setup.star +7 -0
  66. package/runtime/engine/topologies/platform/docker/networking/traefik.star +85 -46
  67. package/runtime/engine/topologies/tilt/common/utils_output.star +1 -0
  68. package/runtime/engine/topologies/tilt/generators/validators.star +1 -1
  69. package/runtime/engine/topologies/tilt/generators/vite/frontend.star +2 -2
  70. package/runtime/engine/topologies/tilt/generators/vite/generators.star +3 -0
  71. package/runtime/engine/topologies/tilt/manifest/constants.star +3 -0
  72. package/runtime/engine/topologies/tilt/manifest/parser.star +9 -3
  73. package/runtime/engine/topologies/tilt/resources/orchestrator/apply_compose_resource_registration.star +8 -3
  74. package/runtime/engine/topologies/tilt/resources/orchestrator/generators/dependencies/resolver.star +50 -24
  75. package/runtime/engine/topologies/tilt/resources/orchestrator/generators/env.star +11 -2
  76. package/runtime/engine/topologies/tilt/resources/orchestrator/generators/manifest_resource.star +23 -9
  77. package/cli/dist-bundle/chunk-43XWL2PB.js +0 -61
  78. package/cli/dist-bundle/chunk-5F7YP5IR.js +0 -17
  79. package/cli/dist-bundle/chunk-K6SOCO6V.js +0 -3
  80. package/cli/dist-bundle/chunk-YHYRGWUH.js +0 -24
  81. package/cli/dist-bundle/chunk-YL56J2WX.js +0 -2
  82. package/cli/dist-bundle/cold-preflight-ZOPR7PWJ.js +0 -2
  83. package/cli/dist-bundle/project-7PTIOHGF.js +0 -2
@@ -20,6 +20,7 @@ load("./constants.star",
20
20
  "MANIFEST_FILENAME",
21
21
  "VALID_APP_TYPES",
22
22
  "DEFAULT_SYNCS",
23
+ "NEXT_FRONTEND_SYNCS",
23
24
  "AUTOGENERATED_CONFIG_PATHS",
24
25
  "TRAEFIK_DEFAULTS",
25
26
  )
@@ -90,6 +91,7 @@ _GENERATED_STRING_RULES = [
90
91
  (['databaseName'], _ALPHANUM + '_-', ''),
91
92
  (['stack'], _ALPHANUM + '_-', ''),
92
93
  (['image'], _ALPHANUM + '._/:@-', ''),
94
+ (['basePath'], _PATH_CHARS, '/'),
93
95
  ]
94
96
 
95
97
  def generated_string_error(manifest, resource_path=""):
@@ -200,7 +202,8 @@ def normalize(manifest, resource_path=""):
200
202
  if normalized.get('syncs') == None or normalized.get('syncs') == []:
201
203
  normalized['syncs'] = _compute_syncs(
202
204
  normalized['appType'],
203
- normalized.get('featuresEnabled', [])
205
+ normalized.get('featuresEnabled', []),
206
+ normalized.get('framework')
204
207
  )
205
208
 
206
209
  # Compute backendName for frontends if missing
@@ -339,13 +342,14 @@ def _determine_app_type(manifest, resource_path):
339
342
  # Default to backend
340
343
  return "backend"
341
344
 
342
- def _compute_syncs(app_type, features):
345
+ def _compute_syncs(app_type, features, framework=None):
343
346
  """
344
347
  Compute default sync paths based on app type and features.
345
348
 
346
349
  Args:
347
350
  app_type: App type string
348
351
  features: List of feature strings
352
+ framework: Frontend framework id (Next.js has no index.html, so it syncs less than a Vite SPA)
349
353
 
350
354
  Returns:
351
355
  List of sync paths
@@ -353,7 +357,9 @@ def _compute_syncs(app_type, features):
353
357
  syncs = []
354
358
 
355
359
  # Start with default syncs for app type
356
- if app_type in DEFAULT_SYNCS:
360
+ if app_type == 'frontend' and framework == 'next':
361
+ syncs.extend(NEXT_FRONTEND_SYNCS)
362
+ elif app_type in DEFAULT_SYNCS:
357
363
  syncs.extend(DEFAULT_SYNCS[app_type])
358
364
 
359
365
  # Add feature-specific syncs
@@ -321,7 +321,7 @@ def _live_update_sync_source(project_root, full_res_path, sync_path):
321
321
  return relative_path
322
322
 
323
323
 
324
- def _build_live_update_rules(res_path, full_res_path, syncs, project_root='', language='bun', go_live_reload=False):
324
+ def _build_live_update_rules(res_path, full_res_path, syncs, project_root='', language='bun', go_live_reload=False, node_frontend=False):
325
325
  """Build live update sync and run rules for a resource.
326
326
 
327
327
  Python backends reload their own process after a sync (uvicorn --reload), so they have
@@ -363,7 +363,7 @@ def _build_live_update_rules(res_path, full_res_path, syncs, project_root='', la
363
363
  dest = '/app/' + full_res_path + '/' + sync_path
364
364
  live_update_rules.append(sync(full_sync_path, dest))
365
365
 
366
- if language == 'python' or language == 'node':
366
+ if language == 'python' or language == 'node' or node_frontend:
367
367
  return live_update_rules
368
368
 
369
369
  package_json_path = '/app/' + full_res_path + '/package.json'
@@ -407,6 +407,9 @@ def _wake_compose_invocation(project_root, resource_path, res_name, resource_nam
407
407
 
408
408
  def _image_target(config):
409
409
  """The Dockerfile target Tilt builds and the deferStart prebuild must match: `development` for Go with `dev.liveReload`."""
410
+ # Next.js runs `next dev` in the development image, so a saved file hot-reloads through the synced sources.
411
+ if Docker.is_next_frontend(config.get('manifest', {})):
412
+ return 'development'
410
413
  return 'development' if Docker.go_live_reload(config.get('manifest', {})) else 'production'
411
414
 
412
415
 
@@ -548,6 +551,8 @@ def _register_single_resource(config, resource_path, compose_project_name, auto_
548
551
  config['syncs'],
549
552
  project_root=config.get('project_root', ''),
550
553
  language=config.get('manifest', {}).get('language', 'bun'),
554
+ # A Next.js image is Node with no Bun install step: syncing sources is enough, `next dev` reloads itself.
555
+ node_frontend=Docker.is_next_frontend(config.get('manifest', {})),
551
556
  go_live_reload=Docker.go_live_reload(config.get('manifest', {})),
552
557
  )
553
558
  _register_docker_build(config, live_update_rules)
@@ -610,7 +615,7 @@ def _register_frontend_typecheck(res, service_dir, typecheck_cmd):
610
615
  # Fixed script, variable parts passed as argv ($1 = service dir, $2 = typecheck command), never spliced into the shell text.
611
616
  cmd=[
612
617
  'sh', '-c',
613
- 'cd "$1" && { bunx tsc --version >/dev/null 2>&1 || { echo "typecheck needs host dependencies: run bun install in $1"; exit 1; }; } && eval "$2"',
618
+ 'cd "$1" && { bunx tsc --version >/dev/null 2>&1 && test -f "$1/node_modules/vite/package.json" || { echo "typecheck needs host dependencies: run bun install in $1"; exit 1; }; } && eval "$2"',
614
619
  'sh', service_dir, typecheck_cmd,
615
620
  ],
616
621
  deps=[service_dir + '/src', service_dir + '/tsconfig.json'],
@@ -7,37 +7,63 @@
7
7
  # Auto-inject configuration from internal dependencies
8
8
  # =============================================================================
9
9
 
10
- load("../../../../../../../discovery/registry.star", "get_resource_by_name")
10
+ load("../../../../../../../discovery/registry.star", "get_app_resources", "get_resource_by_name")
11
+ load("../../../../../platform/docker/networking/traefik_helpers.star", "cli_api_path")
12
+
13
+ def _find_backend_resource(resource_name):
14
+ """Find a discovered resource by its own name, e.g. "api".
15
+
16
+ Registry services are stacks (`app`) whose resources are the runnable pieces (`api`, `web`), so the lookup
17
+ must search resources rather than service names. Frontends are skipped.
18
+ """
19
+ for service in get_app_resources():
20
+ for resource in service.get("resources", []):
21
+ if resource.get("name") != resource_name:
22
+ continue
23
+ app_type = resource.get("_manifest", {}).get("appType") or resource.get("appType")
24
+ if app_type == "frontend":
25
+ continue
26
+ return resource
27
+ return None
28
+
29
+
30
+ def _find_frontend_backend(manifest):
31
+ """Find the backend a frontend talks to: `backendName` first, then the first API `dependsOn` entry.
32
+
33
+ Returns:
34
+ tuple: (backend resource name, backend manifest), or (None, None) when the frontend has no discovered backend
35
+ """
36
+ backend_name = manifest.get("backendName")
37
+ if backend_name:
38
+ backend = _find_backend_resource(backend_name)
39
+ if backend:
40
+ return backend_name, backend.get("_manifest", {})
41
+
42
+ for dep_name in manifest.get("dependsOn", []):
43
+ dep = _find_backend_resource(dep_name)
44
+ if dep and dep.get("_manifest", {}).get("appType") in ["backend", "mcp", "agent"]:
45
+ return dep_name, dep.get("_manifest", {})
46
+
47
+ return None, None
48
+
11
49
 
12
50
  def resolve_backend_api_path(manifest):
13
- """Resolve API path from backend manifest if backendName is specified.
14
-
15
- Frontend manifests often reference a backend via backendName.
16
- This function looks up the backend's apiPath for consistency.
17
-
51
+ """Resolve the URL path a frontend uses to reach its backend, e.g. "/api/api".
52
+
53
+ The path is the backend's route on api.{project}.localhost: its explicit `apiPath` when set, otherwise
54
+ `/api/{name}` with a trailing `-api` stripped, the same rule `flisk up` prints and Traefik serves.
55
+ Frontends that have no discovered backend get None, so callers keep their stack-management fallback.
56
+
18
57
  Args:
19
58
  manifest: Frontend service manifest
20
-
59
+
21
60
  Returns:
22
- str: API path from backend manifest, or None if not found
61
+ str: API path of the frontend's backend, or None if there is no backend
23
62
  """
24
- backend_name = manifest.get("backendName")
25
- if not backend_name:
26
- return None
27
-
28
- # Try to find the backend service
29
- backend_service = get_resource_by_name(backend_name)
30
- if not backend_service:
63
+ backend_name, backend_manifest = _find_frontend_backend(manifest)
64
+ if backend_name == None:
31
65
  return None
32
-
33
- # Get the backend manifest
34
- backend_resources = backend_service.get("resources", [])
35
- for resource in backend_resources:
36
- if resource.get("name") == backend_name:
37
- backend_manifest = resource.get("_manifest", {})
38
- return backend_manifest.get("apiPath")
39
-
40
- return None
66
+ return cli_api_path(backend_name, backend_manifest)
41
67
 
42
68
 
43
69
  def resolve_dependency_api_urls(manifest):
@@ -16,6 +16,7 @@ OUTPUT = struct(AUTOGENERATED_FOLDER = ".autogenerated")
16
16
 
17
17
  load("../../../../platform/docker/auth/auth.star", "AuthConfig")
18
18
  load("../../../../platform/docker/networking/traefik_helpers.star", "get_api_path")
19
+ load("./dependencies/resolver.star", "resolve_backend_api_path")
19
20
  load("../../../../platform/docker/networking/api_path_constants.star", "get_frontend_base_path")
20
21
  load("../../../../platform/docker/constants.star", "PlatformDockerConstants")
21
22
 
@@ -154,9 +155,11 @@ def _generate_params_env(manifest, backend_manifest=None, write_fn=None):
154
155
  backend_port = backend_manifest.get('port', BASE_PORT_BACKEND) if backend_manifest else BASE_PORT_BACKEND
155
156
  backend_name = manifest.get('backendName', stack + '-backend')
156
157
  target_filename = '/' + OUTPUT.AUTOGENERATED_FOLDER + '/.env.frontend.autogenerated'
158
+ # The browser calls the frontend's own backend; the stack-management route only serves flisk's own API.
159
+ frontend_api_url = 'http://' + PlatformDockerConstants.API_LOCAL_DOMAIN + (resolve_backend_api_path(manifest) or api_path)
157
160
 
158
161
  # Shared with the Traefik route and the Vite `base` -- see get_frontend_base_path.
159
- base_path = get_frontend_base_path(manifest)
162
+ base_path = get_frontend_base_path(manifest, manifest.get('appName'))
160
163
  public_url = 'http://' + PlatformDockerConstants.LOCAL_DOMAIN + base_path
161
164
 
162
165
  content = """# Generated by Tilt SDK - DO NOT EDIT
@@ -167,10 +170,16 @@ VITE_BACKEND_NAME={backend_name}
167
170
  PUBLIC_URL={public_url}
168
171
  """.format(
169
172
  backend_port=backend_port,
170
- api_url=api_url,
173
+ api_url=frontend_api_url,
171
174
  backend_name=backend_name,
172
175
  public_url=public_url,
173
176
  )
177
+ if manifest.get('framework') == 'next':
178
+ # Next.js reads NEXT_PUBLIC_* (inlined into the browser bundle) and next.config.mjs reads FLISK_BASE_PATH.
179
+ # The generated Dockerfile copies this file to .env, which `next dev` and `next build` both load.
180
+ content += """NEXT_PUBLIC_API_URL={api_url}
181
+ FLISK_BASE_PATH={base_path}
182
+ """.format(api_url=frontend_api_url, base_path=base_path)
174
183
  content += _build_dependency_env_lines(manifest)
175
184
  else:
176
185
  db_name = manifest.get('databaseName', PlatformDockerConstants.get_db_name(stack))
@@ -132,9 +132,12 @@ def _build_generated_file_list(resource_config, resource_path, manifest):
132
132
  if app_type == 'bring-your-own':
133
133
  return []
134
134
  is_frontend = resource_config.get('frontend', False) or app_type == 'frontend'
135
+ is_next = is_frontend and manifest.get('framework') == 'next'
135
136
 
136
137
  # Vite
137
- if is_frontend:
138
+ if is_next:
139
+ pass
140
+ elif is_frontend:
138
141
  files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['vite_frontend'])
139
142
  files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['vite_build'])
140
143
  elif app_type == 'backend':
@@ -143,7 +146,7 @@ def _build_generated_file_list(resource_config, resource_path, manifest):
143
146
  files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['vite_sdk'])
144
147
 
145
148
  # Nginx (frontends)
146
- if is_frontend:
149
+ if is_frontend and not is_next:
147
150
  files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['nginx'])
148
151
 
149
152
  # Env
@@ -159,9 +162,10 @@ def _build_generated_file_list(resource_config, resource_path, manifest):
159
162
  dockerfile_path = resource_path + "/" + dockerfile_rel_path
160
163
  files.append(dockerfile_path + '.dockerignore')
161
164
 
162
- # TS config(s)
163
- files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['tsconfig_docker'])
164
- files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['tsconfig_local'])
165
+ # TS config(s): Next.js uses the app's own tsconfig.json
166
+ if not is_next:
167
+ files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['tsconfig_docker'])
168
+ files.append(resource_path + '/' + OUTPUT.AUTOGENERATED_FOLDER + '/' + GENERATED_CONFIG_FILENAMES['tsconfig_local'])
165
169
 
166
170
  # Prisma config (non-frontends)
167
171
  if not is_frontend:
@@ -313,6 +317,8 @@ def _generate_all_configs_for_resource(
313
317
 
314
318
  app_type = manifest.get('appType', 'backend')
315
319
  is_frontend = resource_config.get('frontend', False) or app_type == 'frontend'
320
+ # Next.js is a server framework: it owns its build and dev server, so the SPA outputs (Vite, nginx, api-client, tsconfig) are skipped.
321
+ is_next = is_frontend and manifest.get('framework') == 'next'
316
322
  # Provider-owned backends (Python, Go) own their runtime files (package/pyproject, Dockerfile,
317
323
  # reload command). Bun-only configs below (Vite, tsconfig, Prisma, bunfig) are skipped.
318
324
  provider_owned = Docker.is_provider_owned_language(manifest)
@@ -342,7 +348,7 @@ def _generate_all_configs_for_resource(
342
348
  # ==========================================================================
343
349
  # 2. NGINX CONFIG (for frontends)
344
350
  # ==========================================================================
345
- if is_frontend:
351
+ if is_frontend and not is_next:
346
352
  # Generate referer map using ApiGateway and pass to Nginx
347
353
  referer_map_block = ApiGateway.build_referer_map_block(manifest)
348
354
  Nginx.frontend(manifest, write_file, referer_map_block)
@@ -355,7 +361,7 @@ def _generate_all_configs_for_resource(
355
361
  # ==========================================================================
356
362
  # 3.5 FRONTEND API CLIENT FILES (for frontends only)
357
363
  # ==========================================================================
358
- if is_frontend:
364
+ if is_frontend and not is_next:
359
365
  FrontendGenerators.generate_all(manifest, write_file)
360
366
 
361
367
  # ==========================================================================
@@ -368,7 +374,13 @@ def _generate_all_configs_for_resource(
368
374
  # ==========================================================================
369
375
  # 5. DOCKERFILE
370
376
  # ==========================================================================
371
- if is_frontend:
377
+ if is_next:
378
+ dockerfile_content = Docker.next_frontend(
379
+ res_path=resource_path,
380
+ port=resource_config.get('port', manifest.get('port', BASE_PORT_FRONTEND)),
381
+ use_golden=should_enable('golden-image'),
382
+ )
383
+ elif is_frontend:
372
384
  target_path = resource_config.get('target_path', '/usr/share/nginx/html')
373
385
  use_nginx = 'nginx' in target_path or target_path == '/usr/share/nginx/html'
374
386
  port = resource_config.get('port', manifest.get('port', BASE_PORT_FRONTEND))
@@ -425,7 +437,9 @@ def _generate_all_configs_for_resource(
425
437
  # ==========================================================================
426
438
  internal_deps_map = Libs.get_deps_mapping(ctx, resource_path)
427
439
 
428
- if is_frontend:
440
+ if is_next:
441
+ pass
442
+ elif is_frontend:
429
443
  # CRITICAL FIX (v2.0): For Docker builds, we MUST NOT pass internal_deps
430
444
  # This prevents "Module not found" errors when path aliases point to
431
445
  # source files outside the Docker context.
@@ -1,61 +0,0 @@
1
- import{createRequire as __fliskRequire}from'node:module';const require=__fliskRequire(import.meta.url);
2
- import{o as mt,u as ht}from"./chunk-MWOVYIBB.js";import{f as O,g as gt,h as kt,i as St,j as se,k as yt,l as wt,m as xt,n as Pt,o as bt,p as ne,q as vt,s as Dt,t as $t}from"./chunk-IGN5UC3P.js";import{c as ft}from"./chunk-K6SOCO6V.js";import{b as W,c as Ct,d as K}from"./chunk-3J6XI3NX.js";import{a as dt,f as pt,g as te,j as Nt,k as Tt,l as Et,m as Rt,o as Ot,p as be,q as ve,r as _t,s as De,t as $e,u as jt,v as Ce,w as At}from"./chunk-YHYRGWUH.js";import{A as rt,B as we,C as Q,D as ot,E as Z,I as xe,J as it,K as ee,L as at,M as ct,O as lt,P as ut,Q as Pe,a as C,ga as w,t as st,x as nt}from"./chunk-5F7YP5IR.js";import{C as b,D as et,L as tt,b as h,d as v,j as A,m as H,n as G,o as Se,q as ye,x as g,y as Ze}from"./chunk-YNCBBJ4V.js";import{execFileSync as _s}from"node:child_process";import{readFileSync as Jr}from"node:fs";import{join as zr}from"node:path";import{execFileSync as sr,execSync as gs}from"node:child_process";import{existsSync as $,readdirSync as xs,readFileSync as B}from"node:fs";import{join as x,normalize as pe,relative as fe}from"node:path";import{Command as nr}from"commander";import{existsSync as Ms}from"node:fs";var re="docs/agent-hosts.md",Ne=`WebContainers cannot run Flisk: there is no Docker daemon or Tilt. Run \`flisk up\` on a machine with Docker. See ${re}.`,Ft=`Docker is not reachable from this Dev Container. Mount the host Docker socket (-v /var/run/docker.sock:/var/run/docker.sock) or add the docker-outside-of-docker feature to devcontainer.json, then retry. Docker-in-docker is not supported. See ${re}.`;function Hs(){return{env:process.env,versions:process.versions,platform:process.platform,fileExists:Ms}}function It(e=Hs()){let{env:t,versions:s,platform:n,fileExists:r}=e;return s.webcontainer?{kind:"webcontainer",canUp:!1}:t.CODESPACES==="true"?{kind:"codespaces",canUp:!0}:t.REMOTE_CONTAINERS||r("/.dockerenv")&&t.DEVCONTAINER?{kind:"devcontainer",canUp:!0}:n==="win32"?{kind:"native-windows",canUp:t.FLISK_ALLOW_NATIVE_WINDOWS==="1"}:n==="linux"&&t.WSL_DISTRO_NAME?{kind:"wsl2",canUp:!0}:{kind:"local",canUp:!0}}function Lt(e){return e==="devcontainer"||e==="codespaces"}function oe(e){return e.some(t=>st(t.config?.appType)||t.config?.appType==="frontend"||t.config?.appType==="worker")}import{existsSync as Ws,readFileSync as Bs}from"node:fs";import{join as Vs,relative as Mt,resolve as Ht,sep as Us}from"node:path";var Gs=2,Wt=["services/*/*"];function Bt(e){return e.split(Us).filter(Boolean)}function Ks(e,t){let s=0,n=0,r=-1,o=0;for(;n<t.length;)if(s<e.length&&e[s]!=="*"&&(e[s]==="?"||e[s]===t[n]))s++,n++;else if(s<e.length&&e[s]==="*")r=s++,o=n;else if(r!==-1)s=r+1,n=++o;else return!1;for(;s<e.length&&e[s]==="*";)s++;return s===e.length}function qs(e,t){return e.length===t.length&&e.every((s,n)=>Ks(s,t[n]))}function Te(e){let t=Vs(e,".flisk",H);if(!Ws(t))return Wt;try{let s=JSON.parse(Bs(t,"utf-8"))?.discovery?.paths;if(Array.isArray(s)&&s.every(n=>typeof n=="string"))return s}catch{}return Wt}function ie(e,t,s){let n=Bt(Mt(e,Ht(e,t)));return s.some(r=>{let o=Bt(Mt(e,Ht(e,r)));for(let i=0;i<=Gs;i++){let a=n.length-i;if(a>0&&qs(o,n.slice(0,a)))return!0}return!1})}function lo(e,t,s,n){let r=Te(e);if(ie(e,t,r))return{path:t};let o=`services/${s}/${n}`;return ie(e,o,r)?{path:o,adjustedFrom:t}:{path:t}}import{execFile as Js}from"node:child_process";import{promisify as zs}from"node:util";var Xs=zs(Js),Ys=1e4,Qs=5,Vt=10*6e4,Zs=3,en=200,tn=async e=>{let{stdout:t,stderr:s}=await Xs("docker",e,{encoding:"utf-8",timeout:Ys,windowsHide:!0});return`${t}${s}`};function sn(e,t){let s=Nt(t).toLowerCase(),n=e.replace(/-/g,"_").toLowerCase();return n===s||n.startsWith(`${s}_`)}function nn(e,t=Date.now()){if(e.status==="restarting")return!0;if(e.restartCount<Qs)return!1;if(e.status==="running"){let n=Date.parse(e.startedAt);return Number.isNaN(n)||t-n<Vt}let s=Date.parse(e.finishedAt??"");return e.exitCode!==0&&!Number.isNaN(s)&&t-s<Vt}function rn(e,t){let s=/database "([^"]+)" does not exist/i.exec(e);return s?`database "${s[1]}" does not exist: re-run the project's database provisioning (flisk up) or create it`:/Cannot find module|MODULE_NOT_FOUND|module not found/i.test(e)?"a module is missing from the image: rebuild it (flisk up --force) after checking the resource's dependencies":/EADDRINUSE|address already in use/i.test(e)?"the port inside the container is already in use: check for two processes started by the same command":/ECONNREFUSED|connection refused|could not connect/i.test(e)?"a dependency is not reachable: check that the service it connects to is running and healthy":/\b(?:environment variable|env var)\b.*\b(?:missing|not set|required|undefined)\b/i.test(e)||/\b[A-Z][A-Z0-9_]{2,}\b (?:is )?(?:not set|required|missing)\b/.test(e)?"a required environment variable is missing: check the project's .env":t.exitCode===137?"killed (exit 137), usually out of memory: raise the container's memory limit":null}function on(e){let t=[];for(let s of e.split(/\r?\n/)){let[n,r,o,i,a,c]=s.split(" ");!n||r===void 0||t.push({name:n.replace(/^\//,""),restartCount:Number(r)||0,status:o??"",startedAt:i??"",exitCode:Number(a)||0,finishedAt:c??""})}return t}async function Ut(e,t=[],s=tn,n=Date.now()){let r="Crash-looping containers",o;try{o=(await s(["ps","-a","--format",'{{.ID}} {{.Label "com.docker.compose.project"}}'])).split(/\r?\n/).map(m=>m.split(" ")).filter(([m,d])=>m&&d&&sn(d,e)).map(([m])=>m)}catch{return{name:r,didPass:!0,isSkipped:!0,message:"Docker not available - skipped crash-loop check"}}if(o.length===0)return{name:r,didPass:!0,isSkipped:!0,message:"No project containers to check"};let i;try{i=on(await s(["inspect","--format","{{.Name}} {{.RestartCount}} {{.State.Status}} {{.State.StartedAt}} {{.State.ExitCode}} {{.State.FinishedAt}}",...o]))}catch{return{name:r,didPass:!0,isSkipped:!0,message:"Containers changed while checking - skipped crash-loop check"}}let a=i.filter(f=>nn(f,n));if(a.length===0)return{name:r,didPass:!0,message:"No project container is crash-looping"};let c=[],l=new Set;for(let f of a){let m="";try{m=await s(["logs","--tail",String(Zs),f.name])}catch{}let d=Q(m,t).split(/\r?\n/).map(k=>k.trim().slice(0,en)).filter(Boolean),S=rn(m,f);S&&l.add(S),c.push([`${f.name}: ${f.status}, restarted ${f.restartCount} times`,...d.map(k=>` | ${k}`)].join(`
3
- `))}return{name:r,didPass:!1,message:`${a.length} container${a.length===1?" is":"s are"} crash-looping:
4
- ${c.join(`
5
- `)}`,fix:[...l,"Read the full log: docker logs <container>"].join("; ")}}import{execFile as yn,execFileSync as wn}from"node:child_process";import{existsSync as xn,realpathSync as Xt,statfsSync as Pn}from"node:fs";import{homedir as bn}from"node:os";import{join as vn}from"node:path";import{promisify as Dn}from"node:util";import{statfsSync as an}from"node:fs";import{homedir as cn}from"node:os";var ae="Disk Space",ln=1024**3,un=2,Ee=10,Gt=["Free disk space, then retry: flisk doctor"," docker system prune -af # unused images and build cache (needs Docker running)"," npm cache clean --force"," bun pm cache rm"," brew cleanup -s"].join(`
6
- `);function Kt(e=an,t=cn()){let s;try{let r=e(t);s=Number(r.bavail)*Number(r.bsize)/ln}catch{return{name:ae,didPass:!0,isSkipped:!0,message:"Could not read free disk space"}}let n=`${s.toFixed(1)} GB free`;return s<un?{name:ae,didPass:!1,message:`${n}: Docker cannot build or start containers`,fix:Gt}:s<Ee?{name:ae,didPass:!1,isWarning:!0,message:`${n}: image builds may fail`,fix:Gt}:{name:ae,didPass:!0,message:n}}var dn="Quit Docker Desktop completely (whale icon > Quit Docker Desktop), reopen it, and wait until it shows Running. If it keeps getting stuck, check free disk space. Then retry: flisk doctor";function qt(e,t=process.platform){return t!=="darwin"||!e?null:{name:"Container Runtime",didPass:!1,message:"Docker Desktop is open, but its engine is not responding",fix:dn}}import{execFileSync as pn}from"node:child_process";var Re=(e,t)=>pn(e,t,{encoding:"utf-8",stdio:"pipe",windowsHide:!0}),Jt=["traefik-public","traefik-private","backend","database","infisical-network","verdaccio-network","proxy"];function Oe(e){let t=e.replace(/-/g,"_");return Jt.map(s=>`${t}_${s}`)}function zt(e){let t=new Set;for(let s of e)for(let n of["traefik-public","traefik-private"])s.endsWith(`_${n}`)&&t.add(s.slice(0,-(n.length+1)));return t}function _e(e,t){for(let s of Jt)if(e.endsWith(`_${s}`)){let n=e.slice(0,-(s.length+1));if(t.has(n))return n}return null}function xo(e,t=Re){let s=new Set(t("docker",["network","ls","--format","{{.Name}}"]).split(/\r?\n/).map(r=>r.trim()).filter(Boolean)),n={removed:[],kept:[]};for(let r of Oe(e))if(s.has(r))try{t("docker",["network","rm",r]),n.removed.push(r)}catch(o){let i=String(o.stderr??o).trim();n.kept.push({name:r,reason:i.split(/\r?\n/)[0]??""})}return n}function ce(e,t=process.platform,s=Re){if(t==="win32")return[];let n;try{n=s("ps",["-axo","pid=,command="])}catch{return[]}let r=[];for(let o of n.split(/\r?\n/)){let i=/^\s*(\d+)\s+(.*)$/.exec(o);if(!i)continue;let a=i[2]??"",c=(a.split(/\s+/)[0]??"").split("/").at(-1),l=` -f ${e}`,f=a.indexOf(l),m=a[f+l.length];c==="tilt"&&/^\S+\s+up\s/.test(a)&&f>0&&(m===void 0||m===" ")&&r.push(Number(i[1]))}return r}function Po(e,t=process.platform,s=Re){let n=ce(e,t,s);for(let r of n)try{s("kill",["-TERM",String(r)])}catch{}return n}async function bo(e,t=8e3,s=ce){let n=Date.now()+t;for(;s(e).length>0;){if(Date.now()>=n)return!1;await new Promise(r=>setTimeout(r,250))}return!0}import{execFile as fn}from"node:child_process";function je(e){return new Promise(t=>{fn(b("tilt")??"tilt",["get","uiresources","-o","json","--port",String(e)],{timeout:15e3,maxBuffer:16*1024*1024},(s,n)=>t(s?null:n))})}function mn(e){let s=(JSON.parse(e).items??[]).filter(n=>n.status?.disableStatus?.state!=="Disabled").map(n=>n.status?.updateStatus==="not_applicable"?{...n,status:{...n.status,updateStatus:"ok"}}:n);return JSON.stringify({items:s})}function hn(e){return(JSON.parse(e).items??[]).filter(t=>t.status?.disableStatus?.state!=="Disabled").flatMap(t=>t.metadata?.name?[t.metadata.name]:[])}function gn(e,t){let s=JSON.parse(e).items??[],n=new Map(s.map(r=>[r.metadata?.name,r]));return{missing:t.filter(r=>!n.has(r)),disabled:t.filter(r=>n.get(r)?.status?.disableStatus?.state==="Disabled")}}function kn(e){return e.endsWith("-typecheck")}function Sn(e,t,s){let n=Rt(mn(e),t),r=n.failures.filter(i=>!kn(i.name)),o={ready:r.length===0&&n.pendingCount===0&&n.okCount>0,failures:r.map(i=>({name:i.name,message:i.error||`${i.updateStatus}/${i.runtimeStatus}`})),pending:n.pendingCount,timedOut:!1,enabled:hn(e)};if(s&&s.length>0){let{missing:i,disabled:a}=gn(e,s);if(i.length>0&&(o={...o,ready:!1,pending:o.pending+i.length}),a.length>0)return{settled:!0,result:{...o,ready:!1,failures:[...o.failures,...a.map(c=>({name:c,message:"disabled in Tilt"}))]}}}return{result:o,settled:o.ready||o.failures.length>0&&o.pending===0}}async function No(e,t={}){let s=t.timeoutMs??Number(process.env.FLISK_UP_READY_TIMEOUT_MS??9e5),n=t.intervalMs??2e3,r=t.fetchJson??je,o=t.deferred??Et(),i=Date.now()+s,a={ready:!1,failures:[],pending:0,timedOut:!1,enabled:[]};for(;;){let c=await r(e);if(c)try{let l=Sn(c,o,t.expected);if(a=l.result,l.settled||a.failures.length>0&&t.isStalled?.(c))return a}catch{}if(Date.now()>=i)return{...a,ready:!1,timedOut:!0};await new Promise(l=>setTimeout(l,n))}}var I=Dn(yn),$n=15e3,Cn=/^flisk_doctor_probe_(\d+)$/,Nn=async e=>{let{stdout:t}=await I("docker",e,{encoding:"utf-8",timeout:$n,windowsHide:!0});return t};function Tn(){try{return wn("docker",["info","--format","{{.ServerVersion}}"],{encoding:"utf-8",timeout:15e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}}function le(e){return String(e.stderr??e).trim().split(/\r?\n/)[0]??""}var En=120;function Rn(e){let t=/^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s*$/.exec(e);if(!t)return null;let[,s="0",n="0",r="0",o="0"]=t;return((Number(s)*24+Number(n))*60+Number(r))*60+Number(o)}async function On(e,t=je,s=2,n=r=>new Promise(o=>setTimeout(o,r))){for(let r=0;r<s;r++){r>0&&await n(1e3);for(let o of e)if(await t(o)!==null)return!0}return!1}async function _n(e){if(process.platform==="win32")return"unknown";try{let{stdout:t}=await I("ps",["-p",String(e),"-o","etime="],{encoding:"utf-8",timeout:5e3}),s=Rn(t);if(s===null||s<En)return"unknown";let{stdout:n}=await I("lsof",["-nP","-a","-p",String(e),"-iTCP","-sTCP:LISTEN","-Fn"],{encoding:"utf-8",timeout:5e3}),r=[...n.matchAll(/^n.*:(\d+)$/gm)].map(o=>Number(o[1]));return await On(r)?"healthy":"stale"}catch{return"unknown"}}function jn(e=Nn){return{colima:An,colimaStatus:()=>W(),dockerAnswers:Tn,async listNetworks(){let t=(await e(["network","ls","--format","{{.Name}}"])).split(/\r?\n/).map(n=>n.trim()).filter(Boolean);return(await Promise.all(t.map(async n=>{try{let r=await e(["network","inspect","--format","{{len .Containers}}",n]);return{name:n,containers:Number(r.trim())||0}}catch(r){if(/no such network|not found/i.test(String(r)))return null;throw r}}))).filter(n=>n!==null)},async removeNetwork(t){try{await e(["network","rm",t])}catch(s){throw new Error(le(s))}},freeDiskGib(){try{let t=Pn(bn());return Number(t.bavail)*Number(t.bsize)/1024**3}catch{return null}},async reclaimable(){let t=null;try{let n=await e(["system","df","--format","{{.Type}} {{.Reclaimable}}"]);for(let r of n.split(/\r?\n/)){let[o,i]=r.split(" ");o==="Build Cache"&&i&&(t=i.replace(/\s*\(.*\)/,"").trim())}}catch{}let s=0;try{s=(await e(["images","-q","-f","dangling=true"])).split(/\r?\n/).filter(Boolean).length}catch{}return{buildCache:t,danglingImages:s}},async prune(t){try{await e(t==="builder"?["builder","prune","-f"]:["image","prune","-f"])}catch(s){throw new Error(le(s))}},async tiltStatus(t){return _n(t)},stopProcess(t){process.kill(t,"SIGTERM")},isProcessAlive(t){try{return process.kill(t,0),!0}catch(s){return s.code==="EPERM"}}}}var Yt=jn();async function An(e){if(e==="native-lima"){let n=K();if(!n){let o=xn("/opt/homebrew/bin/brew")?"/opt/homebrew/bin/brew":"brew";if(await I(o,["reinstall","lima"],{encoding:"utf-8",timeout:3e5}),n=K(),!n)throw new Error("brew reinstall lima did not provide a native limactl")}let r=n?{...process.env,PATH:`${n}:${process.env.PATH??""}`}:process.env;await I("colima",["start"],{encoding:"utf-8",timeout:3e5,env:r});return}let t=K(),s=t?{...process.env,PATH:`${t}:${process.env.PATH??""}`}:process.env;await I("colima",[e],{encoding:"utf-8",timeout:3e5,env:s})}async function Qt(e,t=Yt,s={}){let n=[],r=[];for(let d of s.tiltPids??[])await t.tiltStatus(d)==="stale"?n.push({id:`stop-tilt:${d}`,check:"Tilt processes",scope:"project",command:`kill -TERM ${d}`,status:"planned",reason:"this project's Tilt is running but its UI does not answer"}):r.push(d);let o=r.length>0?`Tilt is running for this project (pid ${r.join(", ")}); run flisk down first`:void 0,i=t.colimaStatus(),a=Ct(i,t.dockerAnswers());if(a==="start")n.push({id:"colima:start",check:"Colima",scope:"host",command:"colima start",status:"planned",reason:i.problem??"the Colima VM is not running"});else if(a==="restart")n.push({id:"colima:restart",check:"Colima",scope:"host",command:"colima restart",status:"planned",reason:"the Colima VM is running but its Docker daemon does not answer"});else if(a==="native-lima"){let d=K();n.push({id:"colima:native-lima",check:"Colima",scope:"host",command:d?`PATH="${d}:$PATH" colima start`:"brew reinstall lima",status:"planned",reason:d?`the colima CLI on this PATH cannot see the VM; a native limactl is installed in ${d}`:"the colima CLI on this PATH cannot see the VM; lima is installed as an x86_64 build (brew reinstall lima)"})}let c=await t.listNetworks(),l=t.freeDiskGib();if(l!==null&&l<Ee){let{buildCache:d,danglingImages:S}=await t.reclaimable(),k=`${l.toFixed(1)} GB free`;d&&!/^0(\.0+)?\s*B$/i.test(d)&&n.push({id:"prune:builder",check:"Disk Space",scope:"host",command:"docker builder prune -f",status:"planned",reason:`${k}; ${d} of build cache reclaimable`}),S>0&&n.push({id:"prune:images",check:"Disk Space",scope:"host",command:"docker image prune -f",status:"planned",reason:`${k}; ${S} untagged image${S===1?"":"s"}`})}let f=new Set(e?Oe(e):[]),m=zt(c.map(d=>d.name));for(let d of c){let S=Cn.exec(d.name),k,y,p="unused network";if(S)k="probe",y="Orphaned probe networks";else if(f.has(d.name))k="project",y="Docker networks";else if(s.machine&&_e(d.name,m))k="machine",y="Docker networks",p=`unused network of project "${_e(d.name,m)}"`;else continue;let D={id:`remove-network:${d.name}`,check:y,scope:k,command:`docker network rm ${d.name}`,status:"planned",reason:p};d.containers>0?(D.status="skipped",D.reason=`${d.containers} container(s) still attached`):k==="project"&&o?(D.status="skipped",D.reason=o):S&&t.isProcessAlive(Number(S[1]))&&(D.status="skipped",D.reason=`probe of a running process (pid ${S[1]})`),n.push(D)}return n}async function Zt(e,t,s=Yt){let n=[];for(let r of e){if(r.status!=="planned"||t.dryRun){n.push(r);continue}if(!t.confirm){n.push({...r,status:"skipped",reason:"confirmation required; run in a terminal or pass --yes"});continue}let o=!1;try{o=await t.confirm(r)}catch{}if(!o){n.push({...r,status:"skipped",reason:"not confirmed"});continue}try{if(r.id.startsWith("prune:")){await s.prune(r.id==="prune:builder"?"builder":"images"),n.push({...r,status:"applied",reason:"pruned"});continue}if(r.id.startsWith("colima:")){let i=r.id.slice(7);if(i==="start"||i==="restart"){await s.colima(i),n.push({...r,status:"applied",reason:`colima ${i} ran`});continue}try{await s.colima("native-lima"),n.push({...r,status:"applied",reason:"native lima repaired and colima started"})}catch(a){n.push({...r,status:"failed",reason:le(a)})}continue}if(r.id.startsWith("stop-tilt:")){s.stopProcess(Number(r.id.slice(10))),n.push({...r,status:"applied",reason:"stopped"});continue}await s.removeNetwork(r.id.slice(15)),n.push({...r,status:"applied",reason:"removed"})}catch(i){n.push({...r,status:"failed",reason:le(i)})}}return n}function es(e){return e.some(t=>t.status==="failed")}async function Fn(e){try{let{stdout:t}=await I(e,["--version"],{encoding:"utf-8",timeout:5e3,windowsHide:!0});return t.trim().split(/\r?\n/)[0]||null}catch{return null}}async function In(e=et("flisk"),t=Fn){let s=new Set,n=[];for(let r of e){let o=r;try{o=Xt(r)}catch{}s.has(o)||(s.add(o),n.push({path:r,version:await t(r)}))}return n}async function ts(e){let t=e??await In();if(t.length<=1)return{name:"Flisk installs",didPass:!0,message:"One flisk install on PATH"};let s=t.map(r=>`${r.path} (${r.version??"version unknown"})`).join(", "),n=new Set(t.map(r=>r.version));return{name:"Flisk installs",didPass:!1,isWarning:!0,message:`${t.length} flisk installs on PATH${n.size>1?" with different versions":""}: ${s}`,fix:"Keep one: remove the others, or run flisk upgrade. The first on PATH is the one your shell runs; tools that launch /usr/local/bin/flisk directly may use another"}}function ss(e,t=ce){let s=new Set([e]);try{s.add(Xt(e))}catch{}let n=new Set;for(let r of s)for(let o of t(vn(r,".flisk",".flisk-out","Tiltfile")))n.add(o);return[...n]}var Ae=1;function Ln(e,t=[]){return{schemaVersion:Ae,data:e,errors:t}}function Mn(e){return e instanceof tt?{error:{code:"COMMAND_FAILED",message:e.message,...e.suggestions.length>0?{suggestions:e.suggestions}:{}},exitCode:e.exitCode}:{error:{code:"INTERNAL",message:e instanceof Error?e.message:String(e)},exitCode:2}}function Bo(e){let t=Mn(e);console.log(JSON.stringify(Ln(null,[t.error]))),console.error(t.error.message),process.exit(t.exitCode)}async function rs(e,t){let s=[],n=[],r=o=>{o.status==="fulfilled"?s.push(o.value):n.push({code:"INTERNAL",message:o.reason instanceof Error?o.reason.message:String(o.reason)})};for(let o of await Promise.allSettled(e.map(i=>Promise.resolve().then(i))))r(o);for(let o of t)for(let i of await Promise.allSettled([Promise.resolve().then(o)]))r(i);return{checks:s,errors:n}}function ns(e){let t=e.find(s=>s.name===v);return t?t.didPass:null}function F(e,t,s=[],n,r){return{schemaVersion:Ae,data:{ready:s.length===0&&e.every(o=>o.didPass||o.isSkipped||o.isWarning),inProject:t,checks:e,...r?{host:{...r,containerRuntimeReachable:ns(e),canUp:r.canUp&&ns(e)!==!1}}:{},...n!==void 0?{ports:{http:{requested:n?.requested.ingressHttp??80,chosen:n?.ingressHttp??null,explicit:n?.explicit.ingressHttp??!!process.env.FLISK_HTTP_PORT,reason:n?.reason.ingressHttp??"port planning failed"},https:{requested:n?.requested.ingressHttps??443,chosen:n?.ingressHttps??null,explicit:n?.explicit.ingressHttps??!!process.env.FLISK_HTTPS_PORT,reason:n?.reason.ingressHttps??"port planning failed"},postgres:{requested:n?.requested.postgres??5432,chosen:n?.postgres??null,explicit:n?.explicit.postgres??!!process.env.FLISK_POSTGRES_PORT,reason:n?.reason.postgres??"port planning failed"}}}:{}},errors:s}}function os(e){return e.errors.length>0?2:e.data.ready?0:1}import{existsSync as Ie,readFileSync as is}from"node:fs";import{dirname as Hn,join as Fe,normalize as Wn}from"node:path";function Bn(e){let t=new Set,s=/^load\s*\(([\s\S]*?)\)/gm;for(let n of e.matchAll(s)){let r=n[1]??"",o=/["']([^"']+)["']/g,i=Array.from(r.matchAll(o),a=>a[1]);for(let a of i.slice(1))a.startsWith("_")&&t.add(a)}return Array.from(t).sort()}function as(e,t,s){return t==="ext://flisk-cli"?Fe(s,".flisk",".flisk-out","flisk-cli-ext","Tiltfile"):t.startsWith(".")||!t.includes("://")&&!t.startsWith("@")?Wn(Fe(Hn(e),t)):null}function Vn(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(!c)continue;let l=as(e,c,s);l&&(Ie(l)||n.push(`${e}: ${c} -> ${l}`))}return n}function Un(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(c){let l=as(e,c,s);l&&n.push(l)}}return n}function Gn(e,t){let s=new Set,n=[e];for(;n.length>0;){let r=n.pop();if(!r||s.has(r)||!Ie(r))continue;s.add(r);let o=is(r,"utf-8");for(let i of Un(r,o,t))s.has(i)||n.push(i)}return Array.from(s).sort()}function cs(){let e=g()??process.cwd(),t=Fe(e,".flisk",".flisk-out","Tiltfile");if(!Ie(t))return{name:"Starlark Load Exports",didPass:!0,isSkipped:!0,message:"No generated Tiltfile to check"};let s=[],n=[],r=Gn(t,e);for(let i of r){let a=is(i,"utf-8"),c=Bn(a);c.length>0&&s.push(`${i}: ${c.join(", ")}`);for(let l of Vn(i,a,e))n.push(l)}if(s.length===0&&n.length===0)return{name:"Starlark Load Exports",didPass:!0,message:`${C(r.length,"reachable Starlark file")} ${r.length===1?"has":"have"} valid load exports and paths`};let o=[];return s.length>0&&o.push(`Private exported symbols:
7
- ${s.join(`
8
- `)}`),n.length>0&&o.push(`Missing relative load targets:
9
- ${n.join(`
10
- `)}`),{name:"Starlark Load Exports",didPass:!1,message:`Starlark load() issues will stop Tilt before services start:
11
- ${o.join(`
12
-
13
- `)}`,fix:"Regenerate with a current Flisk (`flisk config regenerate`). If the issue remains, rename loaded symbols without leading underscores and update stale load paths."}}import{readFileSync as Kn}from"node:fs";import{join as qn}from"node:path";function ls(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Jn(e){try{return JSON.parse(Kn(qn(e,".flisk",H),"utf-8"))?.minFliskVersion}catch{return}}function us(e,t){let s=Jn(e);if(s===void 0)return{status:"none"};let n=typeof s=="string"?ls(s):null;if(!n||!/^\d+\.\d+\.\d+$/.test(String(s).trim()))return{status:"malformed",message:`.flisk/project.json minFliskVersion ${JSON.stringify(s)} is not a version like "1.3.80"`,fix:'Set minFliskVersion to a MAJOR.MINOR.PATCH string, for example "1.3.80".'};let r=ls(t),o=r!==null&&(()=>{for(let[a,c]of n.entries()){let l=r[a]??0;if(l!==c)return l>c}return!0})(),i=n.join(".");return o?{status:"ok",required:i}:{status:"too-old",required:i,message:`flisk ${t} is older than the ${i} this project requires (minFliskVersion)`,fix:"Run: flisk upgrade"}}import{relative as zn}from"node:path";function ue(e,t){return zn(e,t.configPath)||t.configPath}function ds(e){let t=e.config?.dependsOn;return t===void 0?[]:Array.isArray(t)&&t.every(s=>typeof s=="string")?t:null}function Xn(e){let t=new Set(e.map(a=>a.name)),s=new Map(e.map(a=>[a.name,(ds(a)??[]).filter(c=>t.has(c))])),n=new Map,r=new Map,o=[],i=a=>{r.set(a,"visiting"),o.push(a);for(let c of s.get(a)??[])if(r.get(c)==="visiting"){let l=o.slice(o.indexOf(c)),f=l.indexOf([...l].sort()[0]??c),m=[...l.slice(f),...l.slice(0,f)];n.set(m.join(">"),[...m,m[0]??c])}else r.has(c)||i(c);o.pop(),r.set(a,"done")};for(let a of[...s.keys()].sort())r.has(a)||i(a);return[...n.values()]}function Le(e=g()??process.cwd(),t=w(e)){let s=t.flatMap(n=>ds(n)===null?[`${ue(e,n)} dependsOn ${JSON.stringify(n.config?.dependsOn)}: expected an array of service names`]:[]);return s.length===0?{name:"dependsOn",didPass:!0,message:"Every dependsOn is a list of service names"}:{name:"dependsOn",didPass:!1,message:`${C(s.length,"invalid dependsOn","invalid dependsOn")}:
14
- ${s.join(`
15
- `)}`,fix:'Write "dependsOn" as an array of service names, for example ["postgres", "api"]'}}function Me(e=g()??process.cwd(),t=w(e)){let s=new Map(t.map(o=>[o.name,o])),n=Xn(t);if(n.length===0)return{name:"Circular dependencies",didPass:!0,message:"No service depends on itself through dependsOn"};let r=n.map(o=>{let i=s.get(o[0]??""),a=o[1]??"";return`${i?ue(e,i):o[0]} dependsOn "${a}": circular dependency ${o.join(" -> ")}`});return{name:"Circular dependencies",didPass:!1,message:`${n.length} ${n.length===1?"circular dependency":"circular dependencies"}:
16
- ${r.join(`
17
- `)}`,fix:'Remove one "dependsOn" entry in each cycle so the services no longer wait on each other, or move what they share into a third service'}}function He(e=g()??process.cwd(),t=w(e)){let s=t.flatMap(n=>{let r=n.config?.port;return r===void 0?[]:typeof r=="number"&&Number.isInteger(r)&&r>=1&&r<=65535?[]:[`${ue(e,n)} port ${JSON.stringify(r)}: not an integer from 1 to 65535`]});return s.length===0?{name:"Service ports",didPass:!0,message:"Every declared port is valid"}:{name:"Service ports",didPass:!1,message:`${C(s.length,"invalid port")}:
18
- ${s.join(`
19
- `)}`,fix:'Set "port" to the port the service listens on, an integer from 1 to 65535'}}function We(e=g()??process.cwd(),t=!1,s=w(e)){let n=[],r=[];for(let i of s){let a=i.config?.schemaVersion;if(a===Pe)continue;let c=ue(e,i);a===void 0?n.push(`${c} schemaVersion: missing`):r.push(`${c} schemaVersion ${JSON.stringify(a)}: this flisk supports ${Pe}`)}if(n.length===0&&r.length===0)return{name:"schemaVersion",didPass:!0,message:"Every service.json has a supported schemaVersion"};let o=[...n.length>0?["Run `flisk config migrate` to add the missing schemaVersion"]:[],...r.length>0?["A version this flisk does not support cannot be migrated: upgrade flisk"]:[]];return{name:"schemaVersion",didPass:!1,isWarning:!t,message:`${C(n.length+r.length,"service.json file")} without a supported schemaVersion:
20
- ${[...n,...r].join(`
21
- `)}`,fix:o.join(". ")}}function li(e,t){let s=We(e,!1,t);s.didPass||(console.warn(h.yellow(`\u26A0 ${s.message}`)),s.fix&&console.warn(h.gray(` ${s.fix}`)))}function ui(e,t={},s=process.exit){let n=t.resources??w(e),r=[se(e,n),Le(e,n),Me(e,n),He(e,n)].filter(i=>!i.didPass);if(r.length===0)return;let o=r.map(i=>`${i.message}${i.fix?`
22
- Fix: ${i.fix}`:""}`).join(`
23
- `);t.onInvalid?.(o);for(let i of r)console.error(h.red(`\u2717 ${i.message}`)),i.fix&&console.error(h.gray(` Fix: ${i.fix}`));s(1)}import{execFileSync as q}from"node:child_process";import{lookup as Yn}from"node:dns/promises";var ps="Windows did not resolve *.flisk.localhost to 127.0.0.1. Browser URLs with hostnames will fail until you fix hosts or use the 127.0.0.1 URLs printed by flisk networks.";function Qn(e){return e.length>0&&e.every(t=>t==="127.0.0.1"||t==="::1")}function Zn(e){return e.split(/\r?\n/).flatMap(t=>{let s=t.match(/^\s*(\d+)\s+(\d+)(?:\s|$)/);return s?[[Number(s[1]),Number(s[2])]]:[]})}function er(e,t,s){let n=s.replace(/-/g,"_").toLowerCase();return e.filter(r=>{let o=t.find(a=>a.publishedPorts.includes(r));if(!o||!n)return!0;let i=o.name.toLowerCase();return!i.startsWith(`${n}_`)&&!i.startsWith(`${n}-`)})}function tr(){return b("docker")}function fs(){let e=tr();if(!e)return{name:"Windows Runtime Tools",didPass:!1,message:"Docker is not running. Start Docker Desktop, wait until it is Running, then retry flisk doctor.",fix:"Install Docker Desktop and start it in Linux container mode."};if(!b("tilt"))return{name:"Windows Runtime Tools",didPass:!1,message:"tilt.exe not found on PATH. Install Tilt from https://docs.tilt.dev/install.html"};let t=b("bun");return((process.argv[1]??"").toLowerCase().includes("node_modules")?b("node"):!0)?{name:"Windows Runtime Tools",didPass:!0,message:t?`Docker (${e}), Tilt, and Bun found on PATH`:`Docker (${e}) and Tilt found on PATH; \u26A0\uFE0F Bun was not found (generated services need Bun)`}:{name:"Windows Runtime Tools",didPass:!1,message:"node.exe not found on PATH for this npm installation."}}function ms(){try{return q(b("docker")??"docker",["info","--format","{{.OSType}}"],{encoding:"utf-8",timeout:1e4,windowsHide:!0}).trim().toLowerCase()==="windows"?{name:"Docker container mode",didPass:!1,message:"Docker Desktop is using Windows containers. Switch to Linux containers. Flisk stacks are Linux images.",fix:"Switch Docker Desktop to Linux containers. Flisk does not run Windows containers."}:{name:"Docker container mode",didPass:!0,message:"Docker Desktop is using Linux containers"}}catch{return{name:"Docker container mode",didPass:!1,message:"Docker is not running. Start Docker Desktop, wait until it is Running, then retry flisk doctor."}}}async function hs(){let e=[],t=[];try{let l=q("netsh",["interface","ipv4","show","excludedportrange","protocol=tcp"],{encoding:"utf-8",timeout:1e4,windowsHide:!0});t=Zn(l)}catch{e.push("Could not inspect Windows Hyper-V excluded TCP port ranges.")}let s=[80,443,5432],n=s.filter(l=>t.some(([f,m])=>l>=f&&l<=m));n.length>0&&e.push(`\u26A0\uFE0F Windows reserved port${n.length>1?"s":""} ${n.join(", ")} for Hyper-V/WSL. Fix: disable the conflicting Windows feature or change Flisk ports in project config. Common fix: run \`net stop winnat\` then \`net start winnat\` in an Administrator terminal, then retry \`flisk doctor\`.`);let r=[];for(let l of s)await _t(l)==="in-use"&&r.push(l);let o=[];try{let l=q(b("docker")??"docker",["ps","--format","{{.Names}}\\t{{.Ports}}"],{encoding:"utf-8",timeout:1e4,windowsHide:!0});o=Tt(l,s)}catch{}let i=g()?Z():"",a=er(r,o,i);if(a.length>0)try{let l=q("powershell.exe",["-NoProfile","-Command",`$ports = '${a.join(",")}'.Split(','); foreach ($port in $ports) { Get-NetTCPConnection -LocalPort ([int]$port) -State Listen -ErrorAction SilentlyContinue | ForEach-Object { $connection = $_; $service = Get-CimInstance Win32_Service | Where-Object { $_.ProcessId -eq $connection.OwningProcess } | Select-Object -First 1; if ([int]$port -eq 80 -and ($service.Name -eq 'W3SVC' -or $connection.OwningProcess -eq 4)) { '80: IIS / World Wide Web Publishing (HTTP.sys)' } elseif ($service) { '{0}: {1}' -f $port, $service.DisplayName } else { '{0}: PID {1}' -f $port, $connection.OwningProcess } } }`],{encoding:"utf-8",timeout:1e4,windowsHide:!0}).trim();e.push(`\u26A0\uFE0F Ports ${a.join(", ")} are already listening${l?`:
24
- ${l}`:"."}`)}catch{e.push(`\u26A0\uFE0F Ports ${a.join(", ")} are already in use.`)}let c=!0;for(let l of["flisk.localhost","example.flisk.localhost"])try{let f=await Yn(l,{all:!0,verbatim:!0});Qn(f.map(m=>m.address))||(c=!1)}catch{c=!1}c||e.push(`${ps}
25
- Add these lines to C:\\Windows\\System32\\drivers\\etc\\hosts (Administrator Notepad):
26
- 127.0.0.1 flisk.localhost
27
- 127.0.0.1 example.flisk.localhost`);try{q("git",["config","core.autocrlf"],{encoding:"utf-8",timeout:5e3,windowsHide:!0}).trim().toLowerCase()==="true"&&e.push("git core.autocrlf is true; generated files may get CRLF while Docker Linux containers expect LF. Recommended: git config core.autocrlf input in Flisk repos.")}catch{}return e.push("Docker Desktop Settings \u2192 Resources \u2192 File sharing must include this project directory."),{name:"Windows ports and DNS",didPass:c&&a.length===0,message:e.length>0?e.join(`
28
- `):"Required ports are available and Flisk localhost DNS resolves to loopback",...c?{}:{fix:ps}}}var R=1e4,E={dockerMissing:"See https://docs.docker.com/get-docker/",dockerDaemonDown:"Start Docker Desktop, OrbStack, or Colima, then retry: flisk doctor",tiltMissing:"curl -fsSL https://raw.githubusercontent.com/tilt-dev/tilt/master/scripts/install.sh | bash",bunMissing:"curl -fsSL https://bun.sh/install | bash",port80:"Stop the process bound to port 80, or stop local nginx/caddy. Then: flisk doctor",port5432:"Stop local Postgres or change the host port. Then: flisk doctor",notProject:"flisk project --yes"},ks="WSL2 detected. Use Docker Desktop WSL integration. Guide: docs/wsl2.md",Ss="Native Windows landscape boot is unsupported. Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md",Be=[0,25,0],L=[1,2,0];function me(e,t){let s=Ge(e);return s?Ke(s,t):!1}function rr(e,t,s=process.platform==="linux"&&!!process.env.WSL_DISTRO_NAME){if(!s)return{name:"WSL project location",didPass:!0,isSkipped:!0,message:"Not running in WSL2 - skipped project filesystem check"};let n=e.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase();if(n!=="/mnt/c"&&!n.startsWith("/mnt/c/"))return{name:"WSL project location",didPass:!0,message:`${ks} Project is on the WSL filesystem.`};let r=`${ks} Project is under /mnt/c (${e}); hot reload may be broken. Move it into the WSL filesystem, such as ~/projects.`;return{name:"WSL project location",didPass:!t,isWarning:!t,message:r,fix:"Move the repository under your WSL home directory (for example, ~/projects) and retry flisk doctor."}}function or(e){let t=e.replace(/^\[(.*)\]$/,"$1");return t==="0.0.0.0"||/^[0:]*:0\.0\.0\.0$/.test(t)?!0:t.includes(":")&&/^[0:]+$/.test(t)}function ir(e=process.env,t=!1){let s=(e.FLISK_BIND_ADDRESS??"").trim();return or(s)?{name:"Dev Port Bind Address",didPass:!t,isWarning:!t,message:`FLISK_BIND_ADDRESS is ${s}: Traefik and Postgres are reachable from other machines on the network.`,fix:"Unset FLISK_BIND_ADDRESS to keep dev ports on 127.0.0.1. Keep it only when you test from another device on purpose."}:{name:"Dev Port Bind Address",didPass:!0,message:s?`Dev ports bind to ${s}`:"Dev ports bind to 127.0.0.1 (this machine only)"}}function Ps(e){let t=e.filter(n=>!n.didPass&&!n.isSkipped&&!n.isWarning),s=e.filter(n=>n.didPass||n.isSkipped||n.isWarning);return t.sort((n,r)=>{let o=i=>i.name==="Host Ports"&&/\b5432\b/.test(i.message)?0:i.name==="Host Ports"?1:i.name==="Ingress Ports"?2:3;return o(n)-o(r)}),[...t,...s]}function ar(e,t){return t?e?"Doctor passed. Next: flisk up":"Doctor passed. Next: flisk project example":"Doctor failed. Fix the items above, then run: flisk doctor"}var Ue={checkDockerOperatingSystem:"Docker OS",checkDockerCompose:"Docker Compose",checkDockerVersions:"Docker Versions",checkDockerNetworkCapacity:"Docker Network Pool",checkContainerResourceHealth:"Container Resource Health",checkCrashLoopingContainers:"Crash-looping containers",checkTiltResourceHealth:"Tilt Resources",checkServiceHealth:"Service Health",checkServiceSmoke:"Service Smoke",checkAdvertisedEndpoints:"Advertised Endpoints"},ys=new Set(["Docker OS","Docker Compose","Docker Versions","Docker Network Pool","Container Resource Health","Crash-looping containers","Tilt Resources","Service Health","Service Smoke","Advertised Endpoints",...Object.keys(Ue)]);function cr(e){return!!(e.requiresContainerRuntime||e.checkName&&ys.has(e.checkName)||e.name&&ys.has(e.name))}function T(e,t){let s=()=>t();return s.requiresContainerRuntime=!0,s.checkName=e,s}async function lr(e,t={}){let s=[],n=!!t.containerRuntimeFailed;for(let r of e){if(n&&cr(r)){let i=r.checkName??(r.name&&Ue[r.name]?Ue[r.name]:r.name&&r.name!=="check"&&r.name!=="fn"?r.name:"Container check");s.push({name:i,didPass:!0,isSkipped:!0,message:`Docker not running - skipped ${i} check`});continue}let o=await r();if(s.push(o),o.name===v&&!o.didPass&&(n=!0),!t.all&&!o.didPass&&!o.isSkipped&&!o.isWarning)break}return s}function ur(e){let t=0,s=0,n=0,r=0;for(let o of e)o.isSkipped?n++:o.isWarning?r++:o.didPass?t++:s++;return r>0?`${t} passed, ${r} warned, ${s} failed, ${n} skipped`:`${t} passed, ${s} failed, ${n} skipped`}function Je(e){return gt(e)}function dr(e,t,s,n,r){return async(o=O)=>{try{return await o(t,R),{name:e,didPass:!0,message:s}}catch(i){return Je(i)?{name:e,didPass:!1,message:`${e} did not respond within ${R/1e3}s`,fix:r}:{name:e,didPass:!1,message:n,fix:r}}}}async function Ve(e){try{return await O(e,R),!0}catch{return!1}}async function pr(){let e=W();return e.isColima?e.running&&!e.problem?{name:"Colima",didPass:!0,message:`Colima VM is running${e.arch?` (${e.arch})`:""}`}:{name:"Colima",didPass:!1,message:e.problem??"The Colima VM is not running",fix:e.fix}:{name:"Colima",didPass:!0,message:"Docker does not run on Colima"}}async function ze(){if(process.platform==="win32")try{return await O("docker ps",R),{name:v,didPass:!0,message:"Docker Desktop Linux container engine is running"}}catch{return{name:v,didPass:!1,message:"Docker is not running",fix:E.dockerDaemonDown}}let e=!!b("docker");try{return await O("docker ps",R),{name:v,didPass:!0,message:"Docker daemon is running"}}catch(s){if(Je(s))return{name:v,didPass:!1,message:"Docker daemon is not responding",fix:E.dockerDaemonDown}}let t=qt(await Ve("pgrep -f com.docker.backend"));return t||(await Ve("colima status")?{name:v,didPass:!0,message:"Colima (Docker runtime) is running"}:b("colima")?{name:v,didPass:!1,message:"Colima is installed but not running",fix:E.dockerDaemonDown}:await Ve("podman ps")?{name:v,didPass:!0,message:"Podman is running"}:e?{name:v,didPass:!1,message:"Docker daemon is not running",fix:E.dockerDaemonDown}:{name:v,didPass:!1,message:"Docker is not running",fix:E.dockerMissing})}var J=dr("Docker Compose","docker compose version","Docker Compose plugin available","Docker Compose plugin not found","Install Docker Compose: https://docs.docker.com/compose/install/");J.requiresContainerRuntime=!0;J.checkName="Docker Compose";var fr=[25,0,0],mr=[2,20,2];function Ge(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Ke(e,t){for(let[s,n]of t.entries()){let r=e[s]??0;if(r!==n)return r>n}return!0}async function z(e=O){let t=async a=>String(await e(a,R)).trim(),s,n;try{[s,n]=await Promise.all([t("docker version --format '{{.Server.Version}}'"),t("docker compose version --short")])}catch{return{name:"Docker Versions",didPass:!0,isSkipped:!0,message:"Could not read Docker Engine/Compose versions - skipped version check"}}let r=Ge(s),o=Ge(n);if(!r||!o)return{name:"Docker Versions",didPass:!0,isSkipped:!0,message:`Unrecognized Docker version output (engine "${s}", compose "${n}") - skipped version check`};let i=[];return Ke(r,fr)||i.push(`Docker Engine ${s} (need 25.0+)`),Ke(o,mr)||i.push(`Docker Compose ${n} (need 2.20.2+)`),i.length===0?{name:"Docker Versions",didPass:!0,message:`Docker Engine ${s} and Compose ${n} support generated healthchecks`}:{name:"Docker Versions",didPass:!1,message:`Docker is too old for generated healthchecks (they use start_interval):
29
- ${i.join(`
30
- `)}`,fix:"Update Docker Desktop, or on Linux update docker-ce and the docker-compose-plugin package"}}z.requiresContainerRuntime=!0;z.checkName="Docker Versions";async function Xe(e=O){let t;try{t=String(await e("tilt version",R)).trim()}catch{return{name:"Tilt CLI",didPass:!1,message:"Tilt CLI not found",fix:E.tiltMissing}}return me(t,Be)?{name:"Tilt CLI",didPass:!0,message:`Tilt ${t} is available`}:{name:"Tilt CLI",didPass:!1,message:`Tilt ${t||"version unknown"} is below the required v${Be.join(".")} floor`,fix:`Install Tilt v${Be.join(".")} or newer: https://docs.tilt.dev/install.html`}}async function Ye(e=O){let t;try{t=String(await e("docker info --format '{{.OSType}}'",R)).trim().toLowerCase()}catch{return{name:"Docker OS",didPass:!0,isSkipped:!0,message:"Docker OS unavailable - daemon failure reported separately"}}return t!=="linux"?{name:"Docker OS",didPass:!1,message:`Docker is using the ${t||"unknown"} engine; Flisk requires Linux containers`,fix:"Switch Docker Desktop to Linux containers, enable WSL2 integration, then retry flisk doctor."}:{name:"Docker OS",didPass:!0,message:"Docker is using Linux containers"}}Ye.requiresContainerRuntime=!0;Ye.checkName="Docker OS";async function hr(e=O){let t=g();if(!t)return{name:"Bun",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Bun check"};if(!oe(w(t)))return{name:"Bun",didPass:!0,isSkipped:!0,message:"No generated JS services - skipping Bun check"};try{let s=String(await e("bun --version",R)).trim();return me(s,L)?{name:"Bun",didPass:!0,message:`Bun ${s} is available`}:{name:"Bun",didPass:!1,message:`Bun ${s||"version unknown"} is below the required ${L.join(".")} floor`,fix:`Install Bun ${L.join(".")} or newer: https://bun.sh/install`}}catch{return{name:"Bun",didPass:!1,message:"Bun is not available",fix:E.bunMissing}}}function gr(){let e=g()??process.cwd(),t=nt(e);if(t.missing.length>0)return{name:"Environment Variables",didPass:!1,message:`Missing required env variables: ${t.missing.join(", ")}`,fix:$(x(e,".env"))?`Edit .env and set these values:
31
- ${t.missing.map(n=>`${n}=<value>`).join(`
32
- `)}`:"No .env file yet. Run `flisk project` to create one with working defaults."};if(t.invalid.length>0)return{name:"Environment Variables",didPass:!1,message:`Invalid env variables: ${t.invalid.join(", ")}`,fix:"Edit .env and provide values for empty variables"};let s=t.warnings.filter(n=>!n.startsWith(".env file not found"));return{name:"Environment Variables",didPass:!0,message:s.length>0?`All required environment variables are set (warning: ${s.join("; ")})`:"All required environment variables are set"}}function kr(){let e=g()??process.cwd(),t=x(e,".flisk",".flisk-out"),s=Se.filter(n=>!$(x(t,n)));return s.length===0?{name:"Master Configs",didPass:!0,message:`${Se.join(", ")} found`}:{name:"Master Configs",didPass:!1,message:`Master configs missing: ${s.join(", ")}`,fix:"Run: flisk project"}}function Sr(e=Ze()){let t=g();if(!t)return{name:"Flisk version",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Flisk version check"};let s=us(t,e);return s.status==="none"?{name:"Flisk version",didPass:!0,isSkipped:!0,message:`flisk ${e} (no minFliskVersion in .flisk/project.json)`}:s.status==="malformed"||s.status==="too-old"?{name:"Flisk version",didPass:!1,message:s.message,fix:s.fix}:{name:"Flisk version",didPass:!0,message:`flisk ${e} meets minFliskVersion ${s.required}`}}function yr(){let e=g()??process.cwd(),t=Te(e),s=w(e).filter(r=>!ie(e,r.path,t));if(s.length===0)return{name:"Resource Discovery",didPass:!0,message:`All resources are covered by discovery.paths ${JSON.stringify(t)}`};let n=s.map(r=>pe(fe(e,r.path))).join(", ");return{name:"Resource Discovery",didPass:!1,message:`${C(s.length,"resource")} outside discovery.paths ${JSON.stringify(t)}: ${n}. \`flisk up\` will not start them`,fix:"Move each under services/<stack>/<name>, or add a matching pattern to discovery.paths in .flisk/project.json and run: flisk config regenerate"}}function wr(e){let t=[],s=(n,r)=>{for(let o of xs(n,{withFileTypes:!0})){if(r===""&&o.name===".flisk-contract")continue;let i=r===""?o.name:`${r}/${o.name}`;o.isDirectory()?s(x(n,o.name),i):o.isFile()&&t.push(i)}};return s(e,""),t.sort()}function xr(e=!1){let t=g()??process.cwd(),s=w(t).filter(o=>(o.config?.appType??o.type)!=="library");if(s.length===0)return{name:"Generated Files",didPass:!0,isSkipped:!0,message:"No resources to check"};let n=[],r=[];for(let o of s){let i=pe(fe(t,o.path)),a=x(o.path,A),c=$(a)?wr(a):[];c.length===0?(r.push(i),n.push(`${i}: no ${A}/ files`)):n.push(`${i}: ${c.join(", ")}`)}return r.length===0?{name:"Generated Files",didPass:!0,message:`${C(s.length,"resource")} with generated files:
33
- ${n.join(`
34
- `)}`}:{name:"Generated Files",didPass:!1,isWarning:!e,message:`${r.length} of ${C(s.length,"resource")} not generated yet:
35
- ${n.join(`
36
- `)}`,fix:"Run `flisk up` to generate them (it needs Docker, Compose and Tilt). `flisk config verify` checks the project-level files only."}}var Pr=["install-deps.sh","bun-hoisted-symlink-fix.sh","prisma-bun-client-link-fix.sh","prisma-normalize-client.sh","infisical-entrypoint.sh"],br=/shared-platform-engineering\/docker-templates\/([\w.-]+)/g;function vr(e){let t=new Set;for(let s of w(e)){let n=x(s.path,A);if($(n)){for(let r of xs(n))if(!(!r.startsWith("Dockerfile")||r.endsWith(".dockerignore")))for(let o of B(x(n,r),"utf-8").matchAll(br))t.add(o[1])}}return[...t]}function Dr(){let e=g()??process.cwd(),t=[];$(x(e,G))||t.push(`${G} (workspace root manifest)`);let s=x(e,"shared-platform-engineering","docker-templates"),n=[];try{n=vr(e)}catch{}for(let r of new Set([...Pr,...n]))$(x(s,r))||t.push(`shared-platform-engineering/docker-templates/${r}`);return t.length===0?{name:"Generated Runtime Assets",didPass:!0,message:"Generated Docker runtime assets are present"}:{name:"Generated Runtime Assets",didPass:!1,message:`Generated Dockerfiles reference missing project runtime assets:
37
- ${t.join(`
38
- `)}`,fix:"Run `flisk project --yes` (or `flisk config regenerate`) with an updated Flisk. `flisk up` also refreshes these assets before starting Tilt."}}function $r(){let e=g()??process.cwd(),t=w(e),s=[];for(let n of t){let r=x(n.path,G);if(!$(r))continue;let o=n.config?.appType??"backend",i=ye[o]??ye.backend,a;try{a=JSON.parse(B(r,"utf-8")).scripts??{}}catch{s.push(`${n.name} (package.json is invalid JSON)`);continue}let c=i.filter(l=>!a[l]);c.length>0&&s.push(`${n.name}: missing "${c.join('", "')}"`)}return s.length===0?{name:"Startup Scripts",didPass:!0,message:"All services have required package.json scripts"}:{name:"Startup Scripts",didPass:!1,message:`Services missing required package.json scripts:
39
- ${s.join(`
40
- `)}`,fix:`Add the missing scripts to each service's package.json, e.g.:
41
- "dev": "bun run src/index.ts",
42
- "build": "tsc",
43
- "start": "bun run dist/index.js"`}}function bs(e){if(e.startsWith("@"))return[e.split("/").slice(0,2).join("/")];let t=e.split("/")[0]??e;return[`@types/${t}`,t]}function vs(e,t,s=0){let n=e[t];if(typeof n!="string"||s>3)return!1;if(/(^|[\s;&|(])tsc(\s|$)/.test(n))return!0;for(let r of n.matchAll(/\b(?:bun|npm|pnpm|yarn)\s+run\s+([\w:.-]+)/g))if(vs(e,r[1],s+1))return!0;return!1}function ws(e){let t=bs(e);return e.includes("/")||e.startsWith("@")?t[t.length-1]:t[0]}var Cr={"@types/bun":"^1.4.2","@types/node":"^20.0.0"};function Nr(e,t){return(t.includes("bun")||e.has("@types/bun"))&&!e.has("@types/node")}function Tr(){let e=g()??process.cwd(),t=w(e),s=[],n=new Set;for(let o of t){let i=x(o.path,G),a=x(o.path,A,"tsconfig.docker.autogenerated.json");if(!$(i)||!$(a))continue;let f=qe(a)?.compilerOptions?.types;if(!Array.isArray(f))continue;let m=qe(i),d=m?.scripts??{};if(!vs(d,"build"))continue;let S=new Set([...Object.keys(m?.devDependencies??{}),...Object.keys(m?.dependencies??{})]),k=f.filter(y=>typeof y=="string").filter(y=>!bs(y).some(p=>S.has(p)));for(let y of k)n.add(ws(y));if(k.length>0){let y=k.map(p=>`"${p}" (needs ${ws(p)})`).join(", ");s.push(`${o.name}: "types" lists ${y}`)}Nr(S,f)&&(n.add("@types/node"),s.push(`${o.name}: uses @types/bun, which references node types internally, but @types/node is not a direct dependency`))}if(s.length===0)return{name:"TypeScript Type Dependencies",didPass:!0,message:`Every service's Docker tsconfig "types" entry has its @types package installed`};let r=[...n].map(o=>{let i=Cr[o];return i?`"${o}": "${i}"`:`${o} (bun add -d ${o})`});return{name:"TypeScript Type Dependencies",didPass:!1,message:`\`bun run build\` will fail with TS2688 (Cannot find type definition file) because a @types package it needs is not a direct dependency:
44
- ${s.join(`
45
- `)}`,fix:`Add to each service's package.json devDependencies: ${r.join(", ")}`}}function qe(e){try{return JSON.parse(B(e,"utf-8"))}catch{return null}}function Er(e){let s=qe(e)?.compilerOptions;return s?.allowSyntheticDefaultImports===!0||s?.esModuleInterop===!0}function Rr(){let e=g()??process.cwd(),t=w(e).filter(n=>n.config?.appType==="frontend");if(t.length===0)return{name:"Frontend Docker Preflight",didPass:!0,isSkipped:!0,message:"No frontend services to check"};let s=[];for(let n of t){$(x(n.path,"public"))||s.push(`${n.name}: no public/ folder, but the Docker build copies it. Create it: mkdir -p ${pe(fe(e,x(n.path,"public")))} && touch ${pe(fe(e,x(n.path,"public",".gitkeep")))}`);let r=x(n.path,A,"Dockerfile.app.autogenerated"),o=x(n.path,A,"tsconfig.docker.autogenerated.json");if($(r)){let i=B(r,"utf-8"),a=/\bEXPOSE\s+80\b/.test(i),c=n.config?.stack,l=c?x(e,"services",c,A,"docker-compose.app.autogenerated.yml"):"";if(a&&l&&$(l)){let f=B(l,"utf-8"),m=n.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(`traefik\\.http\\.services\\.${m}\\.loadbalancer\\.server\\.port=(\\d+)`),k=f.match(d)?.[1];k&&k!=="80"&&s.push(`${n.name}: nginx runtime exposes 80, but generated Traefik routes to ${k}`)}}if($(o)&&!Er(o)){let i=x(n.path,"src","main.tsx");if($(i)){let a=B(i,"utf-8"),c=[/import\s+\w+\s+from\s+["']react["']/,/import\s+\w+\s+from\s+["']react-dom\/client["']/].filter(l=>l.test(a)).map(l=>l.source.includes("react-dom")?"react-dom/client":"react");c.length>0&&s.push(`${n.name}: Docker tsconfig does not allow synthetic default imports, but src/main.tsx default-imports ${c.join(" and ")}`)}}}return s.length===0?{name:"Frontend Docker Preflight",didPass:!0,message:`${C(t.length,"frontend")} ${t.length===1?"has":"have"} compatible Docker build/routing metadata`}:{name:"Frontend Docker Preflight",didPass:!1,message:`Frontend Docker metadata has issues that will make \`flisk up\` fail or route 404:
46
- ${s.join(`
47
- `)}`,fix:'Regenerate with a current Flisk (`flisk config regenerate`) and ensure frontend nginx runtimes route to port 80. For React entrypoints, prefer named imports: `import { StrictMode } from "react"` and `import { createRoot } from "react-dom/client"`.'}}var Or=90,_r=80;function jr(e){return e.split(`
48
- `).map(t=>t.trim()).filter(Boolean).map(t=>{let[s,n,r]=t.split(",");return{name:s??"unknown",memPct:Number.parseFloat((n??"").replace(/%/g,"")),cpuPct:Number.parseFloat((r??"").replace(/%/g,""))}}).filter(t=>Number.isFinite(t.memPct)&&Number.isFinite(t.cpuPct))}var Ar=Object.assign(function(){let t;try{t=sr(b("docker")??"docker",["stats","--no-stream","--format","{{.Name}},{{.MemPerc}},{{.CPUPerc}}"],{stdio:"pipe",encoding:"utf-8",timeout:R,windowsHide:process.platform==="win32"})}catch(o){return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:Je(o)?"Docker not responding - skipped container resource check":"Docker not running - skipped container resource check"}}let s=jr(t);if(s.length===0)return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:"No running containers to check"};let n=s.filter(o=>o.memPct>=Or&&o.cpuPct>=_r);if(n.length===0)return{name:"Container Resource Health",didPass:!0,message:`${C(s.length,"container")} within normal resource usage`};let r=n.map(o=>`${o.name} (mem ${o.memPct.toFixed(0)}%, cpu ${o.cpuPct.toFixed(0)}%)`).join(`
49
- `);return{name:"Container Resource Health",didPass:!1,message:`${C(n.length,"container")} pinned near its memory limit while burning CPU -- likely stuck in a boot-time retry/fetch loop, not a normal crash:
50
- ${r}`,fix:"Check the container's boot logs for a network fetch loop (e.g. `bunx <pkg>` re-downloading a CLI on every start instead of using one already installed): docker logs <container>. If a Prisma auto-migration is the cause, set AUTO_MIGRATE=false in the project's .env as a temporary unblock."}},{requiresContainerRuntime:!0,checkName:"Container Resource Health"}),Fr=5e3;async function Ir(e,t){let s=g()??process.cwd(),n=xe(w(s),t);return n.length===0?{name:"Service Health",didPass:!0,isSkipped:!0,message:"No routable services to ping"}:De(await ee(n,e))}async function Lr(e,t){let s=g()??process.cwd(),n=w(s),r=ct(at(n,t),{timeoutSeconds:Math.ceil(e/1e3)});return r.length===0?$e([]):(await ee(xe(n,t),e)).some(i=>i.status!==void 0)?$e(await ut(r,lt(s))):{name:"Service Smoke",didPass:!0,isSkipped:!0,message:"No services responded - skipped smoke checks"}}async function Mr(e,t){let s=g()??process.cwd(),n=w(s),r=it(n,t);return r.length===0?{name:"Advertised Endpoints",didPass:!0,isSkipped:!0,message:"No routable services to check"}:jt(await ee(r,e))}function Hr(e,t){if(e.length===0){console.log(`${h.green("\u2713")} Nothing to repair
51
- `);return}for(let s of e){let n=s.status==="planned"?`${h.cyan("would run")}`:s.status==="applied"?h.green("ran"):s.status==="failed"?h.red("failed"):h.gray("skipped"),r=s.status==="planned"?"":` (${s.reason})`;console.log(`${n}: ${s.command}${r}`)}t&&console.log(h.gray(`
52
- Dry run: nothing was changed.`)),console.log("")}function de(e){for(let t of Ps(e))!t.didPass&&!t.isSkipped&&!t.isWarning?(console.log(`${h.red("\u2717")} ${t.message}`),t.fix&&console.log(`${h.blue("\u2139")} Fix: ${t.fix}`)):t.isWarning?(console.log(`${h.yellow("\u26A0")} ${h.yellow(t.message)}`),t.fix&&console.log(`${h.blue("\u2139")} Fix: ${t.fix}`)):t.isSkipped?(console.log(`${h.gray("\u25CB")} ${h.gray(t.message)}`),t.fix&&console.log(`${h.blue("\u2139")} ${t.fix}`)):console.log(`${h.green("\u2713")} ${t.message}`)}function Wr(e,t,s,n={},r){let o=r??[...e,...t];n.all?(console.log(h.bold("Machine")),de(e),console.log(`
53
- ${h.bold("Project")}`),s?t.length>0&&de(t):console.log(`${h.gray("\u25CB")} ${h.gray("Not in a Flisk project, so project checks were skipped")}`),console.log(""),console.log(ur(o))):(de(o),console.log(""),o.every(a=>a.didPass||a.isSkipped||a.isWarning)&&!s&&(console.log(`${h.gray("\u25CB")} ${h.gray("Not in a Flisk project, so project checks were skipped")}`),console.log("")))}var Br=new nr("doctor").description("Check environment readiness for Flisk").option("--all","Run every check and show Machine and Project sections with a summary",!1).option("--json","Output a versioned JSON readiness report",!1).exitOverride(e=>{e.exitCode===0&&process.exit(0),Br.opts().json&&console.log(JSON.stringify(F([],!1,[{code:"USAGE",message:e.message}]))),process.exit(2)}).option("--no-ping","Skip pinging running services' /health endpoints").option("--strict","Fail warnings such as a WSL project under /mnt/c").option("--fix","Repair this project's unused Docker networks and leftover doctor probes",!1).option("--dry-run","With --fix: list the repairs without changing anything",!1).option("--scope <scope>","With --fix: project (default) or machine, which also removes unused networks of other Flisk projects","project").option("-y, --yes","With --fix: apply every repair without asking",!1).option("--ping-timeout <ms>","Per-service ping timeout in milliseconds",String(Fr)).action(async e=>{let t=Number(e.pingTimeout);if(!/^\d+$/.test(e.pingTimeout)||!Number.isSafeInteger(t)||t<=0){let u="--ping-timeout must be a positive integer number of milliseconds";e.json&&console.log(JSON.stringify(F([],!1,[{code:"USAGE",message:u}]))),console.error(u),process.exit(2);return}let s=!["project","machine"].includes(e.scope),n=e.scope!=="project"&&!e.fix;if(s||n||(e.dryRun||e.yes)&&!e.fix){let u=s?`--scope must be project or machine, got "${e.scope}"`:n?"--scope only applies with --fix":`${e.dryRun?"--dry-run":"--yes"} only applies with --fix`;e.json&&console.log(JSON.stringify(F([],!1,[{code:"USAGE",message:u}]))),console.error(u),process.exit(2);return}e.json||console.log("Flisk doctor checks your local Docker + Tilt development environment; it does not check cluster deployments.");let r=It();if(process.platform==="win32"){let P=[{name:"Native Windows support",didPass:!1,message:Ss,fix:"Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md"},fs(),ms(),await hs()],M=null;try{M=await dt()}catch{}e.json?console.log(JSON.stringify(F(P,!!g(),[],M,{...r,canUp:!1}))):(de(P),console.log("")),console.error(Ss),process.exit(1);return}if(r.kind==="webcontainer"){let u=F([{name:"Host",didPass:!1,message:Ne,fix:`Use a machine with Docker. Guide: ${re}`}],!!g(),[],void 0,r);e.json&&console.log(JSON.stringify(u)),console.error(Ne),process.exit(1);return}e.json||(console.log(`
54
- ${h.bold("\u{1F50D} Flisk Doctor")}
55
- `),console.log(`Checking environment...
56
- `));let o=g(),i;if(e.fix){try{let u;if(o)try{u=mt(o).project.name}catch{}let P=o?ss(o):[],M=await Qt(u,void 0,{tiltPids:P,machine:e.scope==="machine"});i=await Zt(M,{dryRun:e.dryRun,confirm:e.yes||!e.json&&process.stdin.isTTY?async N=>e.yes||await ht({message:`Run \`${N.command}\` (${N.check}, ${N.reason})?`}):void 0})}catch(u){i=[{id:"plan-fixes",check:"Docker networks",scope:"project",command:"docker network ls",status:"failed",reason:`could not list Docker networks: ${(u instanceof Error?u.message:String(u)).split(/\r?\n/)[0]}`}]}e.json||Hr(i,e.dryRun)}let a,c;try{a=await te(o??process.cwd())}catch(u){a=null,c=u instanceof Error?u.message:String(u)}let l=[()=>a?{name:"Host Ports",didPass:!0,message:`HTTP ${a.ingressHttp}, HTTPS ${a.ingressHttps}, Postgres ${a.postgres}`}:{name:"Host Ports",didPass:!1,message:c??"Could not select host ports",fix:"Set FLISK_HTTP_PORT, FLISK_HTTPS_PORT, or FLISK_POSTGRES_PORT to available host ports."},()=>a?ve(gs,void 0,[a.ingressHttp,a.ingressHttps]):{name:"Ingress Ports",didPass:!1,message:"Ingress port plan is unavailable"},pr,ze,()=>Kt(),T("Docker OS",Ye),Xe,T("Docker Compose",J),T("Docker Versions",z),hr,()=>rr(g()??process.cwd(),e.strict),()=>ir(process.env,e.strict),T("Docker Network Pool",()=>$t()),()=>ts()],f=[()=>Sr(),kr,Dr,()=>xr(e.strict),cs,$r,()=>At(),Tr,Rr,yr,()=>St(),()=>se(),()=>Le(),()=>Me(),()=>He(),()=>We(void 0,e.strict),()=>yt(),()=>wt(),()=>Pt(),()=>xt(),()=>ne(),()=>kt(),()=>vt(),()=>bt(),()=>Dt(),gr,async()=>{let u=g()??process.cwd(),P=Ot(u)?await ft(u):!0;return be(gs,u,void 0,P)},T("Container Resource Health",Ar),T("Crash-looping containers",()=>{let u=g()??process.cwd(),P=[];try{P=we(u)}catch{return{name:"Crash-looping containers",didPass:!0,isSkipped:!0,message:"Could not read .env - skipped crash-loop check"}}return Ut(Z(),P)}),T("Tilt Resources",Ce)];if(e.ping){let u=o?pt(o,a?.ingressHttp):a?.ingressHttp;f.push(T("Service Health",()=>Ir(t,u))),f.push(T("Service Smoke",()=>Lr(t,u))),f.push(T("Advertised Endpoints",()=>Mr(t,u)))}let m=!!o,d=[],S=[],k,y=[];if(e.json||!e.all){let u=await rs(l,m?f:[]);k=u.checks,y=u.errors}else{let u=async(N,Is=!1)=>{let Ls=N.map(Y=>{let ge=async()=>{try{return await Y()}catch(ke){return y.push({code:"INTERNAL",message:ke instanceof Error?ke.message:String(ke)}),{name:Y.checkName??"Doctor check",didPass:!1,isSkipped:!1,message:"Check failed with an internal error"}}};return ge.requiresContainerRuntime=Y.requiresContainerRuntime,ge.checkName=Y.checkName,ge});return lr(Ls,{all:!!e.all,containerRuntimeFailed:Is})};d=await u(l);let P=d.some(N=>!N.didPass&&!N.isSkipped&&!N.isWarning),M=d.some(N=>N.name===v&&!N.didPass);m&&(e.all||!P)&&(S=await u(f,M)),k=[...d,...S]}if(Lt(r.kind))for(let u of k)u.name===v&&!u.didPass&&(u.fix=Ft);let p=F(Ps(k),m,y,a,r);i&&(p.data.actions=i),i&&es(i)&&(p.data.ready=!1);let j=os(p),U=p.data.ready;if(e.json){let u;try{u=we(g()??process.cwd())}catch(P){if(!(P instanceof rt))throw P;console.log(JSON.stringify(F([],m,[...y,{code:"ENV_UNREADABLE",message:P.message}]))),console.error(P.message),process.exit(1)}console.log(JSON.stringify(ot(p,u)));for(let P of y)console.error(Q(P.message,u));j!==0&&process.exit(j);return}for(let u of y)console.error(`${h.red("\u2717")} Doctor check failed: ${u.message}`);Wr(d,S,m,e,k);let Qe=ar(m,U);console.log(`${U?h.green(h.bold("\u2713")):h.red(h.bold("\u2717"))} ${Qe}`),j!==0&&process.exit(j)});function Ds(e){return me(e,L)}var X=`${L[0]}.${L[1]}+`;import{execFileSync as $s}from"node:child_process";import{accessSync as Cs,constants as Ns,readdirSync as Vr}from"node:fs";import{delimiter as Ur,join as V}from"node:path";var _="flisk",Ts="@flisk-sh/flisk",Gr="https://github.com/flisk-sh/flisk",Es="@tdk-landscape/tdk-cli-core";function Rs(e=_,t=process.env){let s=t.PATH??t.Path??"";for(let n of s.split(Ur)){if(!n)continue;let r=[V(n,e),V(n,`${e}.cmd`),V(n,`${e}.exe`)];for(let o of r)try{return Cs(o,Ns.X_OK),!0}catch{}}return!1}function Kr(e=process.env){let t=e.HOME??e.USERPROFILE??"";if(!t)return"flisk-workspace";let s=V(t,"Documents");try{return Cs(s,Ns.F_OK),V(s,"flisk")}catch{return V(t,"flisk")}}function qr(e){try{return Vr(e).every(t=>t.startsWith("."))}catch{return!0}}function Os(e=process.env,t=process.cwd()){if(!Rs(_,e))return`The \`${_}\` command is not on PATH (this run is not a global install). Install it with \`npm install -g ${Ts}\`, then run \`${_} project --yes\`. If npm reports EEXIST for \`flisk\`, the old package still owns that command: run \`npm uninstall -g ${Es}\` first. The current release is published from ${Gr}.`;if(qr(t))return`Next: ${_} project --yes`;let s=Kr(e);return`Next: mkdir -p ${s} && cd ${s} && ${_} project --yes
57
- (${_} project writes .flisk/ and the master configs into the current folder, so it starts clean in a folder of its own. Or clone a starter: ${_} project example)`}function aa(e=process.env){if(Rs(_,e))return"present";let t=e.npm_execpath?.includes("bun")?"bun":"npm",s=t==="bun"?"bun remove -g":"npm uninstall -g";try{$s(s,[Es],{stdio:"ignore",timeout:12e4})}catch{}try{return $s(t,["install","-g",Ts],{stdio:"ignore",timeout:3e5}),"installed"}catch{return"failed"}}var Xr=["docker","compose","tilt"],As=["node","bun","ports"],Fs=["node",...Xr,"bun","ports"];function Yr(e,t){return{id:e,ok:t.didPass||!!t.isSkipped,message:t.message,fix:t.fix}}function js(e){let[t=0,s=0]=String(e).split(".").map(n=>Number.parseInt(n,10));return!Number.isFinite(t)||!Number.isFinite(s)||t<22||t===22&&s<12}async function he(e,t,s){try{return Yr(e,await t())}catch{return{id:e,ok:!1,message:s}}}function Qr(e){return e.isSkipped?{...e,didPass:!1,isSkipped:!1,message:`Could not verify Docker Engine/Compose minimum versions: ${e.message}`,fix:e.fix??"Start Docker and ensure Docker Engine 25+ and Compose 2.20.2+ are installed."}:e}function Zr(e){try{return w(e).some(t=>t.config?.featuresEnabled?.includes("prisma")??!1)}catch{return!1}}async function eo(e={}){let t=e.cwd??process.cwd(),s=e.scope??"runtime",n=g(t),r=!!n,o=[],i=process.versions.node;if(o.push({id:"node",ok:!js(i),message:i,fix:js(i)?`Install Node.js 22.12+ (current: ${i}). https://nodejs.org`:void 0}),s==="runtime"){let p=W();p.isColima&&o.push({id:"colima",ok:p.running,message:p.running?`Colima VM is running${p.arch?` (${p.arch})`:""}`:p.problem??"The Colima VM is not running",fix:p.running?void 0:p.fix}),o.push(await he("docker",ze,"Docker daemon is not running")),o.push(await he("compose",async()=>{let[D,j]=await Promise.all([J(),z()]);return D.didPass?Qr(j):D},"Docker Engine or Compose version check failed")),o.push(await he("tilt",Xe,"Tilt CLI not found"))}let a=n?oe(w(n)):!0,c=!1,l=a?b("bun"):void 0;if(l)try{let p=_s(l,["--version"],{encoding:"utf-8",timeout:3e3}).trim();c=Ds(p)}catch{}o.push(a?{id:"bun",ok:c,message:c?`Bun ${X} is available on PATH`:`Bun ${X} not found on PATH`,fix:c?void 0:"curl -fsSL https://bun.sh/install | bash"}:{id:"bun",ok:!0,message:"Bun not needed: no generated JS services"});try{let p=await te(n??t,s==="scaffold"?{inspectDocker:!1}:{});o.push({id:"ports",ok:!0,message:`HTTP ${p.ingressHttp}, HTTPS ${p.ingressHttps}, Postgres ${p.postgres}`})}catch(p){o.push({id:"ports",ok:!1,message:p instanceof Error?p.message:String(p),fix:"Set FLISK_HTTP_PORT, FLISK_HTTPS_PORT, or FLISK_POSTGRES_PORT to available host ports."})}if(n&&s==="runtime"){let p=await he("nats",()=>ne(n),"NATS broker check failed");if(p.ok||o.push(p),Zr(n)){let D=!1;try{let j=JSON.parse(Jr(zr(n,".flisk",H),"utf-8")),U=String(j?.project?.name??"").replace(/-/g,"_");U&&(D=_s(b("docker")??"docker",["ps","--filter",`label=com.docker.compose.project=${U}`,"--filter","label=com.docker.compose.service=postgres","--filter","health=healthy","--format","{{.Names}}"],{encoding:"utf-8",timeout:3e3}).trim().length>0)}catch{}D||o.push({id:"prisma",ok:!1,message:"A Prisma resource is configured, but the project Postgres service is not healthy",fix:"Run `flisk up` to start the bundled Postgres, then check `flisk doctor`."})}}let f=o.filter(p=>!p.ok).slice(0,8),m=s==="scaffold"?As:Fs,d=f.some(p=>m.includes(p.id)),S=f.some(p=>p.id==="bun"),k=f.length?d?s==="scaffold"?S?`Project setup blocked. Bun ${X} must be installed on PATH.
58
- Fix the machine checks below.`:"Project setup blocked. Fix the machine checks below.":S?`Cold start blocked. Bun ${X} must be installed on PATH.
59
- Prisma/NATS configuration is project-specific and generated after \`flisk project\`. Fix the machine checks below.`:"Cold start blocked. Bun/Prisma/NATS are not the first failure.\nThey are generated after `flisk project`. Fix the machine checks below.":"Machine is ready. Project wiring is not.":"",y=f.length?"":r?"Environment ready for Flisk":`This machine is ready for Flisk.
60
- ${Os()}`;return{ok:f.length===0,inProject:r,items:f,header:k,footer:y}}function to(e,t={}){let s=[e.header];for(let n of e.items)s.push(`FAIL ${n.id.padEnd(7)} ${n.message}`),n.fix&&s.push(` ${n.fix}`);return e.footer&&(t.includeSuccessFooter??!0)&&s.push(e.footer),s.filter(Boolean).join(`
61
- `)}async function ba(e={}){let t=e.scope??"runtime",s=await eo({scope:t}),n=t==="scaffold"?As:Fs;s.items.some(o=>n.includes(o.id))&&(console.error(to(s)),process.exit(1))}function va(e=b){return{hasDockerCli:!!e("docker"),hasTiltCli:!!e("tilt")}}function Da(e){let t=[];return e.hasDockerCli||t.push(`Docker is not installed. ${E.dockerMissing}`),e.hasTiltCli||t.push(`Tilt is not installed. ${E.tiltMissing}`),t.push("Docker and Tilt are only needed to start the stack: start them, then run `flisk doctor` (readiness) and `flisk up`."),t}export{Ln as a,Mn as b,Bo as c,Ne as d,Ft as e,It as f,Lt as g,Te as h,ie as i,lo as j,xo as k,Po as l,bo as m,je as n,mn as o,Sn as p,No as q,us as r,li as s,ui as t,Br as u,Es as v,aa as w,Xr as x,As as y,Fs as z,js as A,Qr as B,eo as C,to as D,ba as E,va as F,Da as G};