beadscope 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/build-manifest.json +3 -3
  3. package/.next/fallback-build-manifest.json +3 -3
  4. package/.next/next-server.js.nft.json +1 -1
  5. package/.next/prerender-manifest.json +4 -4
  6. package/.next/required-server-files.js +8 -8
  7. package/.next/required-server-files.json +8 -8
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  14. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/server/app/_not-found.html +2 -2
  16. package/.next/server/app/_not-found.rsc +4 -4
  17. package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  18. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
  19. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  20. package/.next/server/app/api/config/route.js.nft.json +1 -1
  21. package/.next/server/app/api/fs/route.js.nft.json +1 -1
  22. package/.next/server/app/api/p/[projectId]/activity/route.js.nft.json +1 -1
  23. package/.next/server/app/api/p/[projectId]/attachments/[...path]/route.js.nft.json +1 -1
  24. package/.next/server/app/api/p/[projectId]/attachments/route.js.nft.json +1 -1
  25. package/.next/server/app/api/p/[projectId]/beads/[id]/archive/route.js.nft.json +1 -1
  26. package/.next/server/app/api/p/[projectId]/beads/[id]/assist/route.js.nft.json +1 -1
  27. package/.next/server/app/api/p/[projectId]/beads/[id]/comments/route.js.nft.json +1 -1
  28. package/.next/server/app/api/p/[projectId]/beads/[id]/deps/route.js.nft.json +1 -1
  29. package/.next/server/app/api/p/[projectId]/beads/[id]/gate/route.js.nft.json +1 -1
  30. package/.next/server/app/api/p/[projectId]/beads/[id]/human/route.js.nft.json +1 -1
  31. package/.next/server/app/api/p/[projectId]/beads/[id]/route.js.nft.json +1 -1
  32. package/.next/server/app/api/p/[projectId]/beads/[id]/status/route.js.nft.json +1 -1
  33. package/.next/server/app/api/p/[projectId]/beads/route.js.nft.json +1 -1
  34. package/.next/server/app/api/p/[projectId]/beads/stream/route.js.nft.json +1 -1
  35. package/.next/server/app/api/p/[projectId]/doctor/route.js.nft.json +1 -1
  36. package/.next/server/app/api/p/[projectId]/gamification/route.js.nft.json +1 -1
  37. package/.next/server/app/api/p/[projectId]/insights/route.js.nft.json +1 -1
  38. package/.next/server/app/api/p/[projectId]/order/route.js.nft.json +1 -1
  39. package/.next/server/app/api/p/[projectId]/publish/route.js.nft.json +1 -1
  40. package/.next/server/app/api/projects/[id]/route.js.nft.json +1 -1
  41. package/.next/server/app/api/projects/route.js.nft.json +1 -1
  42. package/.next/server/app/api/telemetry/route.js.nft.json +1 -1
  43. package/.next/server/app/api/update/check/route.js +3 -3
  44. package/.next/server/app/api/update/check/route.js.nft.json +1 -1
  45. package/.next/server/app/api/update/run/route.js +3 -3
  46. package/.next/server/app/api/update/run/route.js.nft.json +1 -1
  47. package/.next/server/app/api/viewer-mode/route.js.nft.json +1 -1
  48. package/.next/server/app/index.html +2 -2
  49. package/.next/server/app/index.rsc +7 -7
  50. package/.next/server/app/index.segments/__PAGE__.segment.rsc +7 -7
  51. package/.next/server/app/index.segments/_full.segment.rsc +7 -7
  52. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  53. package/.next/server/app/p/[projectId]/page.js.nft.json +1 -1
  54. package/.next/server/app/p/[projectId]/page_client-reference-manifest.js +1 -1
  55. package/.next/server/app/page.js.nft.json +1 -1
  56. package/.next/server/app/page_client-reference-manifest.js +1 -1
  57. package/.next/server/chunks/[root-of-the-server]__0190u3x31o2kc._.js +1 -1
  58. package/.next/server/chunks/[root-of-the-server]__0190u3x31o2kc._.js.map +1 -1
  59. package/.next/server/chunks/[root-of-the-server]__1-f7qk3-8a266._.js +1 -1
  60. package/.next/server/chunks/[root-of-the-server]__1zrubp2jc8bi0._.js +1 -1
  61. package/.next/server/chunks/_004qegokrf7fy._.js +1 -1
  62. package/.next/server/chunks/_004qegokrf7fy._.js.map +1 -1
  63. package/.next/server/chunks/_0vx1iev9xu_vx._.js +1 -1
  64. package/.next/server/chunks/_0vx1iev9xu_vx._.js.map +1 -1
  65. package/.next/server/chunks/_10s9tyeasgb0i._.js +1 -1
  66. package/.next/server/chunks/_10s9tyeasgb0i._.js.map +1 -1
  67. package/.next/server/chunks/_146xyuw6iu78n._.js +1 -1
  68. package/.next/server/chunks/_146xyuw6iu78n._.js.map +1 -1
  69. package/.next/server/chunks/_1n-6yntr59hz-._.js +1 -1
  70. package/.next/server/chunks/_1n-6yntr59hz-._.js.map +1 -1
  71. package/.next/server/chunks/_1tji4d-rsralm._.js +1 -1
  72. package/.next/server/chunks/lib_beads-view_ts_1fvxcrevh9zu_._.js +1 -1
  73. package/.next/server/chunks/lib_beads-view_ts_1fvxcrevh9zu_._.js.map +1 -1
  74. package/.next/server/chunks/lib_config_ts_0zrjxh_mm8sv8._.js +1 -1
  75. package/.next/server/chunks/lib_config_ts_0zrjxh_mm8sv8._.js.map +1 -1
  76. package/.next/server/chunks/lib_self-update_ts_1s_0im4leryko._.js +1 -1
  77. package/.next/server/chunks/lib_self-update_ts_1s_0im4leryko._.js.map +1 -1
  78. package/.next/server/chunks/ssr/[root-of-the-server]__10sjsc4ko7y98._.js +1 -1
  79. package/.next/server/chunks/ssr/[root-of-the-server]__10sjsc4ko7y98._.js.map +1 -1
  80. package/.next/server/chunks/ssr/[root-of-the-server]__1xizcyi5hek65._.js +7 -7
  81. package/.next/server/chunks/ssr/[root-of-the-server]__1xizcyi5hek65._.js.map +1 -1
  82. package/.next/server/chunks/ssr/_0_ky_k50rh6-9._.js +1 -1
  83. package/.next/server/chunks/ssr/_0_ky_k50rh6-9._.js.map +1 -1
  84. package/.next/server/chunks/ssr/_16j7dxy5pqj44._.js +291 -0
  85. package/.next/server/chunks/ssr/_16j7dxy5pqj44._.js.map +1 -0
  86. package/.next/server/chunks/ssr/_1bulx6_unf6c7._.js +3 -0
  87. package/.next/server/chunks/ssr/_1bulx6_unf6c7._.js.map +1 -0
  88. package/.next/server/chunks/ssr/_1mzldxegsozij._.js +1 -1
  89. package/.next/server/chunks/ssr/_1mzldxegsozij._.js.map +1 -1
  90. package/.next/server/chunks/ssr/_1obdc2e416ry-._.js +3 -0
  91. package/.next/server/chunks/ssr/_1obdc2e416ry-._.js.map +1 -0
  92. package/.next/server/chunks/ssr/components_launcher_tsx_1i40oht1v6miz._.js +1 -1
  93. package/.next/server/chunks/ssr/components_launcher_tsx_1i40oht1v6miz._.js.map +1 -1
  94. package/.next/server/chunks/ssr/components_providers_tsx_0thx-xfvr_dtx._.js.map +1 -1
  95. package/.next/server/middleware-build-manifest.js +3 -3
  96. package/.next/server/middleware.js.nft.json +1 -1
  97. package/.next/server/pages/404.html +2 -2
  98. package/.next/server/pages/500.html +1 -1
  99. package/.next/server/preview-props.json +3 -3
  100. package/.next/server/server-reference-manifest.js +1 -1
  101. package/.next/server/server-reference-manifest.json +1 -1
  102. package/.next/static/chunks/0gexf4-utluu4.js +1 -0
  103. package/.next/static/chunks/23nopl40nheqr.js +1 -0
  104. package/.next/static/chunks/2c10hhzk7mgkf.js +58 -0
  105. package/.next/static/chunks/2n4lv4u0xo5oz.css +3 -0
  106. package/.next/static/chunks/3m8u_309a1_fw.js +1 -0
  107. package/.next/static/chunks/3tepw2noo82tm.js +1 -0
  108. package/README.md +91 -25
  109. package/bin/beadscope.mjs +75 -32
  110. package/package.json +2 -1
  111. package/.next/server/chunks/ssr/_02mwe4ucwaopu._.js +0 -291
  112. package/.next/server/chunks/ssr/_02mwe4ucwaopu._.js.map +0 -1
  113. package/.next/server/chunks/ssr/_1020o02v8ucmf._.js +0 -3
  114. package/.next/server/chunks/ssr/_1020o02v8ucmf._.js.map +0 -1
  115. package/.next/server/chunks/ssr/_1i_x4qkev3tax._.js +0 -3
  116. package/.next/server/chunks/ssr/_1i_x4qkev3tax._.js.map +0 -1
  117. package/.next/static/chunks/07balm4l-kilq.js +0 -1
  118. package/.next/static/chunks/0lf_v5uyq3i9q.js +0 -1
  119. package/.next/static/chunks/21v6r4y8vgqng.css +0 -3
  120. package/.next/static/chunks/2xh00k9l33qnb.js +0 -1
  121. package/.next/static/chunks/3yk880zca6oid.js +0 -58
  122. package/.next/static/chunks/3yqhmu1hny1_2.js +0 -1
  123. /package/.next/static/{CNwJGIAhEiVMAkf3ebvok → BoR0CvHf7BXhmN1hRjwWk}/_buildManifest.js +0 -0
  124. /package/.next/static/{CNwJGIAhEiVMAkf3ebvok → BoR0CvHf7BXhmN1hRjwWk}/_clientMiddlewareManifest.js +0 -0
  125. /package/.next/static/{CNwJGIAhEiVMAkf3ebvok → BoR0CvHf7BXhmN1hRjwWk}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../app/api/p/%5BprojectId%5D/beads/route.ts","../../../node_modules/next/src/build/templates/app-route.ts"],"sourcesContent":["import { getStore } from \"@/lib/store\";\nimport { getConfig, isReadOnly, lanePrefix } from \"@/lib/config\";\nimport { createInputSchema } from \"@/lib/schema\";\nimport { ok, fail } from \"@/lib/api\";\n\nexport const dynamic = \"force-dynamic\";\n\ntype Ctx = { params: Promise<{ projectId: string }> };\n\nexport async function GET(_req: Request, { params }: Ctx) {\n try {\n const { projectId } = await params;\n const store = await getStore(projectId);\n const cfg = getConfig();\n const beads = await store.list();\n return ok({\n beads,\n meta: {\n kind: store.kind,\n humanActor: cfg.humanActor,\n humanAllowlist: cfg.humanAllowlist,\n pollIntervalMs: cfg.pollIntervalMs,\n gamification: cfg.gamification,\n readOnly: isReadOnly(_req),\n lanePrefix: lanePrefix(),\n },\n });\n } catch (e) {\n return fail(e);\n }\n}\n\nexport async function POST(req: Request, { params }: Ctx) {\n try {\n const { projectId } = await params;\n const store = await getStore(projectId);\n const cfg = getConfig();\n const input = createInputSchema.parse(await req.json());\n const bead = await store.create(input, cfg.humanActor);\n return ok(bead, 201);\n } catch (e) {\n return fail(e);\n }\n}\n","import {\n AppRouteRouteModule,\n type AppRouteRouteHandlerContext,\n type AppRouteRouteModuleOptions,\n} from '../../server/route-modules/app-route/module.compiled'\nimport { RouteKind } from '../../server/route-kind'\nimport { patchFetch as _patchFetch } from '../../server/lib/patch-fetch'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n addRequestMeta,\n getRequestMeta,\n setRequestMeta,\n type RequestMeta,\n} from '../../server/request-meta'\nimport {\n getTracer,\n type Span,\n SpanKind,\n SpanStatusCode,\n} from '../../server/lib/trace/tracer'\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'\nimport {\n NextRequestAdapter,\n signalFromNodeResponse,\n} from '../../server/web/spec-extension/adapters/next-request'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport { getRevalidateReason } from '../../server/instrumentation/utils'\nimport { sendResponse } from '../../server/send-response'\nimport {\n fromNodeOutgoingHttpHeaders,\n toNodeOutgoingHttpHeaders,\n} from '../../server/web/utils'\nimport { getCacheControlHeader } from '../../server/lib/cache-control'\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport { isRouteCacheOwner } from '../../server/lib/route-cache-key'\nimport {\n CachedRouteKind,\n type ResponseCacheEntry,\n type ResponseGenerator,\n} from '../../server/response-cache'\n\n// These are injected by the loader afterwards. This is injected as a variable\n// instead of a replacement because this could also be `undefined` instead of\n// an empty string.\ndeclare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput']\n\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\n// INJECT:nextConfigOutput\n\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: 'VAR_DEFINITION_PAGE',\n pathname: 'VAR_DEFINITION_PATHNAME',\n filename: 'VAR_DEFINITION_FILENAME',\n bundlePath: 'VAR_DEFINITION_BUNDLE_PATH',\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH',\n nextConfigOutput,\n // The lazy require factory ensures that:\n // - In dev: devRequestTimingInternalsEnd is set before userland executes,\n // correctly attributing module load time to application-code rather than\n // framework internals.\n // - In all modes: async modules (route files with top-level await) are\n // handled correctly — require() returns a Promise for such modules, which\n // ensureUserland() awaits before the first request is handled.\n userland: () => require('VAR_USERLAND') as typeof import('VAR_USERLAND'),\n // In Turbopack dev mode, also provide a synchronous per-request getter so\n // server HMR updates are picked up without re-executing the entry chunk.\n // Using require() (synchronous) avoids adding async overhead that would be\n // incorrectly attributed to application-code time in devRequestTiming.\n ...(process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER\n ? {\n getUserland: () =>\n require('VAR_USERLAND') as typeof import('VAR_USERLAND'),\n }\n : {}),\n})\n\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule\n\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\nexport {\n routeModule,\n workAsyncStorage,\n workUnitAsyncStorage,\n serverHooks,\n patchFetch,\n}\n\nexport async function handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n requestMeta?: RequestMeta\n }\n) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta)\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())\n }\n let srcPage = 'VAR_DEFINITION_PAGE'\n\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/'\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/'\n }\n const multiZoneDraftMode = process.env\n .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean\n\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode,\n })\n\n if (!prepareResult) {\n res.statusCode = 400\n res.end('Bad Request')\n ctx.waitUntil?.(Promise.resolve())\n return null\n }\n\n const {\n buildId,\n deploymentId,\n params,\n nextConfig,\n parsedUrl,\n isDraftMode,\n prerenderManifest,\n routerServerContext,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n resolvedPathname,\n clientReferenceManifest,\n serverActionsManifest,\n previewProps,\n } = prepareResult\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n\n // Only this route's prerenders can establish ISR or admit generated params.\n const isPrerendered =\n Boolean(prerenderManifest.routes[resolvedPathname]) &&\n (routeModule.isDev ||\n isRouteCacheOwner(\n resolvedPathname,\n routeModule.cacheOwner,\n prerenderManifest.routes[resolvedPathname]\n ))\n\n let isIsr = Boolean(\n prerenderManifest.dynamicRoutes[normalizedSrcPage] || isPrerendered\n )\n\n const render404 = async () => {\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext?.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false)\n } else {\n res.end('This page could not be found')\n }\n return null\n }\n\n if (isIsr && !isDraftMode) {\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]\n\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404()\n }\n throw new NoFallbackError()\n }\n }\n }\n\n let cacheKey: string | null = null\n\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey\n }\n\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const method = req.method || 'GET'\n const tracer = getTracer()\n const activeSpan = tracer.getActiveScopeSpan()\n const isWrappedByNextServer = Boolean(\n routerServerContext?.isWrappedByNextServer\n )\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'))\n\n const incrementalCache =\n getRequestMeta(req, 'incrementalCache') ||\n (await routeModule.getIncrementalCache(\n req,\n nextConfig,\n previewProps,\n prerenderManifest,\n isMinimalMode\n ))\n\n incrementalCache?.resetRequestCache()\n ;(globalThis as any).__incrementalCache = incrementalCache\n\n const context: AppRouteRouteHandlerContext = {\n params,\n previewProps,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n durableUseCacheEntries: Boolean(\n nextConfig.experimental.durableUseCacheEntries\n ),\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n validationLevel: nextConfig.experimental.instantInsights.validationLevel,\n isDraftMode,\n incrementalCache,\n hmrRefreshHash: getRequestMeta(req, 'hmrRefreshHash'),\n cacheLifeProfiles: nextConfig.cacheLife,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n waitUntil: ctx.waitUntil,\n onClose: (cb) => {\n res.on('close', cb)\n },\n onAfterTaskError: undefined,\n },\n sharedContext: {\n buildId,\n deploymentId,\n },\n }\n const nodeNextReq = new NodeNextRequest(req)\n const nodeNextRes = new NodeNextResponse(res)\n\n const nextReq = NextRequestAdapter.fromNodeNextRequest(\n nodeNextReq,\n signalFromNodeResponse(res)\n )\n\n const responseGenerator: ResponseGenerator = async ({\n previousCacheEntry,\n }) => {\n try {\n if (\n !isMinimalMode &&\n isOnDemandRevalidate &&\n revalidateOnlyGenerated &&\n !previousCacheEntry\n ) {\n res.statusCode = 404\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED')\n res.end('This page could not be found')\n return null\n }\n\n const response =\n cacheKey === null\n ? await routeModule.handle(nextReq, context)\n : await routeModule.prerender(nextReq, context)\n\n ;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil\n\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil)\n pendingWaitUntil = undefined\n }\n }\n const cacheTags = context.renderOpts.collectedTags\n\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob()\n\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers)\n\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags\n }\n\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type\n }\n\n const revalidate =\n typeof context.renderOpts.collectedRevalidate === 'undefined' ||\n context.renderOpts.collectedRevalidate >= INFINITE_CACHE\n ? false\n : context.renderOpts.collectedRevalidate\n\n const expire =\n typeof context.renderOpts.collectedExpire === 'undefined' ||\n context.renderOpts.collectedExpire >= INFINITE_CACHE\n ? // Fall back to the global `expireTime` config when the\n // route has a numeric `revalidate` but didn't declare an\n // explicit `expire` (e.g. via `cacheLife`). This mirrors the\n // build-time fallback in `build/index.ts` so cache entries\n // and the response Cache-Control header agree on the route's\n // effective expire. Routes that opt out of revalidation\n // (`revalidate: false`) or that are dynamic (`revalidate: 0`)\n // keep `expire: undefined`.\n revalidate !== false && revalidate > 0\n ? nextConfig.expireTime\n : undefined\n : context.renderOpts.collectedExpire\n\n // Create the cache entry for the response.\n const cacheEntry: ResponseCacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers,\n },\n cacheControl: { revalidate, expire },\n }\n\n return cacheEntry\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, pendingWaitUntil)\n return null\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry?.isStale) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration: cacheKey !== null,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n throw err\n }\n }\n\n const handleResponse = async (\n currentSpan: Span | undefined,\n parentSpan: Span | undefined\n ) => {\n try {\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n previewProps,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode,\n })\n\n if (cacheEntry !== null && 'error' in cacheEntry) {\n throw cacheEntry.error\n }\n\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return\n }\n\n if (cacheEntry?.value?.kind !== CachedRouteKind.APP_ROUTE) {\n throw new Error(\n `Invariant: app-route received invalid cache entry ${cacheEntry?.value?.kind}`\n )\n }\n\n if (!isMinimalMode) {\n res.setHeader(\n 'x-nextjs-cache',\n isOnDemandRevalidate\n ? 'REVALIDATED'\n : cacheEntry.isMiss\n ? 'MISS'\n : cacheEntry.isStale\n ? 'STALE'\n : 'HIT'\n )\n }\n\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n }\n\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers)\n\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER)\n }\n\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (\n cacheEntry.cacheControl &&\n !res.getHeader('Cache-Control') &&\n !headers.get('Cache-Control')\n ) {\n headers.set(\n 'Cache-Control',\n getCacheControlHeader(cacheEntry.cacheControl)\n )\n }\n\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200,\n })\n )\n return\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration: cacheKey !== null,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n\n // rethrow so that we can handle serving error page\n\n // If this is during static generation, throw the error again.\n if (isIsr) throw err\n\n // Otherwise, send a 500 response unless the original response has\n // already committed. In that case, preserve its status code for\n // telemetry while still recording the failure and terminating a response\n // that the failed pipeline left open.\n if (res.headersSent) {\n if (currentSpan) {\n const error =\n err instanceof Error ? err : new Error('Unknown app route error')\n currentSpan.recordException(error)\n currentSpan.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n })\n currentSpan.setAttribute('error.type', error.name)\n }\n if (!res.writableEnded && !res.destroyed) {\n res.end()\n }\n } else {\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n new Response(null, { status: 500 })\n )\n }\n return\n } finally {\n ;(() => {\n if (!currentSpan) {\n return\n }\n\n let statusCode = res.statusCode\n\n currentSpan.setAttributes({\n 'http.status_code': statusCode,\n 'next.rsc': false,\n })\n\n if (statusCode && statusCode >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n currentSpan.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n currentSpan.setAttribute('error.type', statusCode.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = rootSpanAttributes.get('next.route') || normalizedSrcPage\n const name = `${method} ${route}`\n\n currentSpan.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n currentSpan.updateName(name)\n\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== currentSpan) {\n parentSpan.setAttribute('http.route', route)\n parentSpan.updateName(name)\n }\n })()\n }\n }\n\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan, undefined)\n } else {\n let parentSpan = tracer.getActiveScopeSpan()\n await tracer.withPropagatedContext(\n req.headers,\n () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url,\n },\n },\n (span) => handleResponse(span, parentSpan)\n ),\n undefined,\n !isWrappedByNextServer\n )\n }\n}\n"],"names":["dynamic","GET","_req","params","projectId","store","cfg","beads","list","meta","kind","humanActor","humanAllowlist","pollIntervalMs","gamification","readOnly","lanePrefix","e","POST","req","input","parse","json","bead","create","AppRouteRouteModule","RouteKind","patchFetch","_patchFetch","addRequestMeta","getRequestMeta","setRequestMeta","getTracer","SpanKind","SpanStatusCode","setManifestsSingleton","normalizeAppPath","NodeNextRequest","NodeNextResponse","NextRequestAdapter","signalFromNodeResponse","BaseServerSpan","getRevalidateReason","sendResponse","fromNodeOutgoingHttpHeaders","toNodeOutgoingHttpHeaders","getCacheControlHeader","INFINITE_CACHE","NEXT_CACHE_TAGS_HEADER","NoFallbackError","isRouteCacheOwner","CachedRouteKind","routeModule","definition","APP_ROUTE","page","pathname","filename","bundlePath","distDir","process","env","__NEXT_RELATIVE_DIST_DIR","relativeProjectDir","__NEXT_RELATIVE_PROJECT_DIR","resolvedPagePath","nextConfigOutput","userland","require","TURBOPACK","__NEXT_DEV_SERVER","getUserland","workAsyncStorage","workUnitAsyncStorage","serverHooks","handler","res","ctx","requestMeta","isDev","hrtime","bigint","srcPage","replace","multiZoneDraftMode","__NEXT_MULTI_ZONE_DRAFT_MODE","prepareResult","prepare","statusCode","end","waitUntil","Promise","resolve","buildId","deploymentId","nextConfig","parsedUrl","isDraftMode","prerenderManifest","routerServerContext","isOnDemandRevalidate","revalidateOnlyGenerated","resolvedPathname","clientReferenceManifest","serverActionsManifest","previewProps","normalizedSrcPage","isPrerendered","Boolean","routes","cacheOwner","isIsr","dynamicRoutes","render404","prerenderInfo","fallback","adapterPath","cacheKey","method","tracer","activeSpan","getActiveScopeSpan","isWrappedByNextServer","isMinimalMode","incrementalCache","getIncrementalCache","resetRequestCache","globalThis","__incrementalCache","context","renderOpts","experimental","authInterrupts","useCacheTimeout","durableUseCacheEntries","cacheComponents","validationLevel","instantInsights","hmrRefreshHash","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","onClose","cb","on","onAfterTaskError","undefined","sharedContext","nodeNextReq","nodeNextRes","nextReq","fromNodeNextRequest","responseGenerator","previousCacheEntry","setHeader","response","handle","prerender","fetchMetrics","pendingWaitUntil","cacheTags","collectedTags","blob","headers","type","revalidate","collectedRevalidate","expire","collectedExpire","expireTime","cacheEntry","value","status","body","Buffer","from","arrayBuffer","cacheControl","err","isStale","silenceLog","onRequestError","routerKind","routePath","routeType","revalidateReason","isStaticGeneration","handleResponse","currentSpan","parentSpan","routeKind","isFallback","isRoutePPREnabled","error","Error","isMiss","delete","getHeader","get","set","Response","headersSent","recordException","setStatus","code","ERROR","message","setAttribute","name","writableEnded","destroyed","setAttributes","toString","rootSpanAttributes","getRootSpanAttributes","handleRequest","console","warn","route","updateName","withPropagatedContext","trace","spanName","SERVER","attributes","url","span"],"mappings":"6CAAA,IAAA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,MACA,EAAA,EAAA,CAAA,CAAA,OAMO,eAAeC,EAAIC,CAAa,CAAE,QAAEC,CAAM,CAAO,EACtD,GAAI,CACF,GAAM,WAAEC,CAAS,CAAE,CAAG,MAAMD,EACtBE,EAAQ,MAAM,CAAA,EAAA,EAAA,CAAA,AAAQ,EAACD,GACvBE,EAAM,CAAA,EAAA,EAAA,CAAA,AAAS,IACfC,EAAQ,MAAMF,EAAMG,IAAI,GAC9B,MAAO,CAAA,EAAA,EAAA,CAAA,AAAE,EAAC,OACRD,EACAE,KAAM,CACJC,KAAML,EAAMK,IAAI,CAChBC,WAAYL,EAAIK,UAAU,CAC1BC,eAAgBN,EAAIM,cAAc,CAClCC,eAAgBP,EAAIO,cAAc,CAClCC,aAAcR,EAAIQ,YAAY,CAC9BC,SAAU,CAAA,EAAA,EAAA,CAAA,AAAU,EAACb,GACrBc,WAAY,CAAA,EAAA,EAAA,CAAA,AAAU,GACxB,CACF,EACF,CAAE,MAAOC,EAAG,CACV,MAAO,CAAA,EAAA,EAAA,CAAI,AAAJ,EAAKA,EACd,CACF,CAEO,eAAeC,EAAKC,CAAY,CAAE,QAAEhB,CAAM,CAAO,EACtD,GAAI,CACF,GAAM,WAAEC,CAAS,CAAE,CAAG,MAAMD,EACtBE,EAAQ,MAAM,CAAA,EAAA,EAAA,CAAA,AAAQ,EAACD,GACvBE,E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E,IAAMoB,EAAQL,EAAmBf,GAAG,CAAC,eAAiB5F,EAChDsG,EAAO,CAAA,EAAG1F,EAAO,CAAC,EAAEoG,EAAAA,CAAO,CAEjC9B,EAAYuB,aAAa,CAAC,CACxB,aAAcO,EACd,aAAcA,EACd,iBAAkBV,CACpB,GACApB,EAAY+B,UAAU,CAACX,GAInBnB,GAAcA,IAAeD,IAC/BC,EAAWkB,OADiC,KACrB,CAAC,aAAcW,GACtC7B,EAAW8B,UAAU,CAACX,IAE1B,CAAA,EACF,CACF,EAIA,GAAItF,GAAyBF,EAC3B,MAAMmE,EAAenE,EADkB,KACN0B,OAC5B,CACL,IAAI2C,EAAatE,EAAOE,kBAAkB,EAC1C,OAAMF,EAAOqG,qBAAqB,CAChCzM,EAAIgJ,OAAO,CACX,IACE5C,EAAOsG,KAAK,CACVpL,EAAAA,CAAAA,CAAe8K,aAAa,CAC5B,CACEO,SAAU,CAAA,EAAGxG,EAAO,CAAC,EAAEpC,EAAAA,CAAS,CAChCxE,KAAMuB,EAAAA,CAAAA,CAAS8L,MAAM,CACrBC,WAAY,CACV,cAAe1G,EACf,cAAenG,EAAI8M,GAAG,AACxB,CACF,EACA,AAACC,GAASvC,EAAeuC,EAAMrC,SAEnC3C,EACA,CAACxB,EAEL,CACF,mCA9gBA,SAAS/F,EACP,MAAA,CAAA,EAAOC,EAAAA,CAAAA,EAAY,kBACjB4C,uBACAC,CACF,EACF","ignoreList":[1]}
1
+ {"version":3,"sources":["../../../app/api/p/%5BprojectId%5D/beads/route.ts","../../../node_modules/next/src/build/templates/app-route.ts"],"sourcesContent":["import { getStore } from \"@/lib/store\";\nimport { getConfig, isReadOnly, lanePrefix } from \"@/lib/config\";\nimport { createInputSchema } from \"@/lib/schema\";\nimport { ok, fail } from \"@/lib/api\";\n\nexport const dynamic = \"force-dynamic\";\n\ntype Ctx = { params: Promise<{ projectId: string }> };\n\nexport async function GET(_req: Request, { params }: Ctx) {\n try {\n const { projectId } = await params;\n const store = await getStore(projectId);\n const cfg = getConfig();\n const beads = await store.list();\n return ok({\n beads,\n meta: {\n kind: store.kind,\n humanActor: cfg.humanActor,\n humanAllowlist: cfg.humanAllowlist,\n agents: cfg.agents,\n pollIntervalMs: cfg.pollIntervalMs,\n gamification: cfg.gamification,\n readOnly: isReadOnly(_req),\n lanePrefix: lanePrefix(),\n },\n });\n } catch (e) {\n return fail(e);\n }\n}\n\nexport async function POST(req: Request, { params }: Ctx) {\n try {\n const { projectId } = await params;\n const store = await getStore(projectId);\n const cfg = getConfig();\n const input = createInputSchema.parse(await req.json());\n const bead = await store.create(input, cfg.humanActor);\n return ok(bead, 201);\n } catch (e) {\n return fail(e);\n }\n}\n","import {\n AppRouteRouteModule,\n type AppRouteRouteHandlerContext,\n type AppRouteRouteModuleOptions,\n} from '../../server/route-modules/app-route/module.compiled'\nimport { RouteKind } from '../../server/route-kind'\nimport { patchFetch as _patchFetch } from '../../server/lib/patch-fetch'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n addRequestMeta,\n getRequestMeta,\n setRequestMeta,\n type RequestMeta,\n} from '../../server/request-meta'\nimport {\n getTracer,\n type Span,\n SpanKind,\n SpanStatusCode,\n} from '../../server/lib/trace/tracer'\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'\nimport {\n NextRequestAdapter,\n signalFromNodeResponse,\n} from '../../server/web/spec-extension/adapters/next-request'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport { getRevalidateReason } from '../../server/instrumentation/utils'\nimport { sendResponse } from '../../server/send-response'\nimport {\n fromNodeOutgoingHttpHeaders,\n toNodeOutgoingHttpHeaders,\n} from '../../server/web/utils'\nimport { getCacheControlHeader } from '../../server/lib/cache-control'\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport { isRouteCacheOwner } from '../../server/lib/route-cache-key'\nimport {\n CachedRouteKind,\n type ResponseCacheEntry,\n type ResponseGenerator,\n} from '../../server/response-cache'\n\n// These are injected by the loader afterwards. This is injected as a variable\n// instead of a replacement because this could also be `undefined` instead of\n// an empty string.\ndeclare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput']\n\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\n// INJECT:nextConfigOutput\n\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: 'VAR_DEFINITION_PAGE',\n pathname: 'VAR_DEFINITION_PATHNAME',\n filename: 'VAR_DEFINITION_FILENAME',\n bundlePath: 'VAR_DEFINITION_BUNDLE_PATH',\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH',\n nextConfigOutput,\n // The lazy require factory ensures that:\n // - In dev: devRequestTimingInternalsEnd is set before userland executes,\n // correctly attributing module load time to application-code rather than\n // framework internals.\n // - In all modes: async modules (route files with top-level await) are\n // handled correctly — require() returns a Promise for such modules, which\n // ensureUserland() awaits before the first request is handled.\n userland: () => require('VAR_USERLAND') as typeof import('VAR_USERLAND'),\n // In Turbopack dev mode, also provide a synchronous per-request getter so\n // server HMR updates are picked up without re-executing the entry chunk.\n // Using require() (synchronous) avoids adding async overhead that would be\n // incorrectly attributed to application-code time in devRequestTiming.\n ...(process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER\n ? {\n getUserland: () =>\n require('VAR_USERLAND') as typeof import('VAR_USERLAND'),\n }\n : {}),\n})\n\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule\n\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\nexport {\n routeModule,\n workAsyncStorage,\n workUnitAsyncStorage,\n serverHooks,\n patchFetch,\n}\n\nexport async function handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n requestMeta?: RequestMeta\n }\n) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta)\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())\n }\n let srcPage = 'VAR_DEFINITION_PAGE'\n\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/'\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/'\n }\n const multiZoneDraftMode = process.env\n .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean\n\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode,\n })\n\n if (!prepareResult) {\n res.statusCode = 400\n res.end('Bad Request')\n ctx.waitUntil?.(Promise.resolve())\n return null\n }\n\n const {\n buildId,\n deploymentId,\n params,\n nextConfig,\n parsedUrl,\n isDraftMode,\n prerenderManifest,\n routerServerContext,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n resolvedPathname,\n clientReferenceManifest,\n serverActionsManifest,\n previewProps,\n } = prepareResult\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n\n // Only this route's prerenders can establish ISR or admit generated params.\n const isPrerendered =\n Boolean(prerenderManifest.routes[resolvedPathname]) &&\n (routeModule.isDev ||\n isRouteCacheOwner(\n resolvedPathname,\n routeModule.cacheOwner,\n prerenderManifest.routes[resolvedPathname]\n ))\n\n let isIsr = Boolean(\n prerenderManifest.dynamicRoutes[normalizedSrcPage] || isPrerendered\n )\n\n const render404 = async () => {\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext?.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false)\n } else {\n res.end('This page could not be found')\n }\n return null\n }\n\n if (isIsr && !isDraftMode) {\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]\n\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404()\n }\n throw new NoFallbackError()\n }\n }\n }\n\n let cacheKey: string | null = null\n\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey\n }\n\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const method = req.method || 'GET'\n const tracer = getTracer()\n const activeSpan = tracer.getActiveScopeSpan()\n const isWrappedByNextServer = Boolean(\n routerServerContext?.isWrappedByNextServer\n )\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'))\n\n const incrementalCache =\n getRequestMeta(req, 'incrementalCache') ||\n (await routeModule.getIncrementalCache(\n req,\n nextConfig,\n previewProps,\n prerenderManifest,\n isMinimalMode\n ))\n\n incrementalCache?.resetRequestCache()\n ;(globalThis as any).__incrementalCache = incrementalCache\n\n const context: AppRouteRouteHandlerContext = {\n params,\n previewProps,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n durableUseCacheEntries: Boolean(\n nextConfig.experimental.durableUseCacheEntries\n ),\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n validationLevel: nextConfig.experimental.instantInsights.validationLevel,\n isDraftMode,\n incrementalCache,\n hmrRefreshHash: getRequestMeta(req, 'hmrRefreshHash'),\n cacheLifeProfiles: nextConfig.cacheLife,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n waitUntil: ctx.waitUntil,\n onClose: (cb) => {\n res.on('close', cb)\n },\n onAfterTaskError: undefined,\n },\n sharedContext: {\n buildId,\n deploymentId,\n },\n }\n const nodeNextReq = new NodeNextRequest(req)\n const nodeNextRes = new NodeNextResponse(res)\n\n const nextReq = NextRequestAdapter.fromNodeNextRequest(\n nodeNextReq,\n signalFromNodeResponse(res)\n )\n\n const responseGenerator: ResponseGenerator = async ({\n previousCacheEntry,\n }) => {\n try {\n if (\n !isMinimalMode &&\n isOnDemandRevalidate &&\n revalidateOnlyGenerated &&\n !previousCacheEntry\n ) {\n res.statusCode = 404\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED')\n res.end('This page could not be found')\n return null\n }\n\n const response =\n cacheKey === null\n ? await routeModule.handle(nextReq, context)\n : await routeModule.prerender(nextReq, context)\n\n ;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil\n\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil)\n pendingWaitUntil = undefined\n }\n }\n const cacheTags = context.renderOpts.collectedTags\n\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob()\n\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers)\n\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags\n }\n\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type\n }\n\n const revalidate =\n typeof context.renderOpts.collectedRevalidate === 'undefined' ||\n context.renderOpts.collectedRevalidate >= INFINITE_CACHE\n ? false\n : context.renderOpts.collectedRevalidate\n\n const expire =\n typeof context.renderOpts.collectedExpire === 'undefined' ||\n context.renderOpts.collectedExpire >= INFINITE_CACHE\n ? // Fall back to the global `expireTime` config when the\n // route has a numeric `revalidate` but didn't declare an\n // explicit `expire` (e.g. via `cacheLife`). This mirrors the\n // build-time fallback in `build/index.ts` so cache entries\n // and the response Cache-Control header agree on the route's\n // effective expire. Routes that opt out of revalidation\n // (`revalidate: false`) or that are dynamic (`revalidate: 0`)\n // keep `expire: undefined`.\n revalidate !== false && revalidate > 0\n ? nextConfig.expireTime\n : undefined\n : context.renderOpts.collectedExpire\n\n // Create the cache entry for the response.\n const cacheEntry: ResponseCacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers,\n },\n cacheControl: { revalidate, expire },\n }\n\n return cacheEntry\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, pendingWaitUntil)\n return null\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry?.isStale) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration: cacheKey !== null,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n throw err\n }\n }\n\n const handleResponse = async (\n currentSpan: Span | undefined,\n parentSpan: Span | undefined\n ) => {\n try {\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n previewProps,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode,\n })\n\n if (cacheEntry !== null && 'error' in cacheEntry) {\n throw cacheEntry.error\n }\n\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return\n }\n\n if (cacheEntry?.value?.kind !== CachedRouteKind.APP_ROUTE) {\n throw new Error(\n `Invariant: app-route received invalid cache entry ${cacheEntry?.value?.kind}`\n )\n }\n\n if (!isMinimalMode) {\n res.setHeader(\n 'x-nextjs-cache',\n isOnDemandRevalidate\n ? 'REVALIDATED'\n : cacheEntry.isMiss\n ? 'MISS'\n : cacheEntry.isStale\n ? 'STALE'\n : 'HIT'\n )\n }\n\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n }\n\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers)\n\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER)\n }\n\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (\n cacheEntry.cacheControl &&\n !res.getHeader('Cache-Control') &&\n !headers.get('Cache-Control')\n ) {\n headers.set(\n 'Cache-Control',\n getCacheControlHeader(cacheEntry.cacheControl)\n )\n }\n\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200,\n })\n )\n return\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration: cacheKey !== null,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n\n // rethrow so that we can handle serving error page\n\n // If this is during static generation, throw the error again.\n if (isIsr) throw err\n\n // Otherwise, send a 500 response unless the original response has\n // already committed. In that case, preserve its status code for\n // telemetry while still recording the failure and terminating a response\n // that the failed pipeline left open.\n if (res.headersSent) {\n if (currentSpan) {\n const error =\n err instanceof Error ? err : new Error('Unknown app route error')\n currentSpan.recordException(error)\n currentSpan.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n })\n currentSpan.setAttribute('error.type', error.name)\n }\n if (!res.writableEnded && !res.destroyed) {\n res.end()\n }\n } else {\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n new Response(null, { status: 500 })\n )\n }\n return\n } finally {\n ;(() => {\n if (!currentSpan) {\n return\n }\n\n let statusCode = res.statusCode\n\n currentSpan.setAttributes({\n 'http.status_code': statusCode,\n 'next.rsc': false,\n })\n\n if (statusCode && statusCode >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n currentSpan.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n currentSpan.setAttribute('error.type', statusCode.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = rootSpanAttributes.get('next.route') || normalizedSrcPage\n const name = `${method} ${route}`\n\n currentSpan.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n currentSpan.updateName(name)\n\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== currentSpan) {\n parentSpan.setAttribute('http.route', route)\n parentSpan.updateName(name)\n }\n })()\n }\n }\n\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan, undefined)\n } else {\n let parentSpan = tracer.getActiveScopeSpan()\n await tracer.withPropagatedContext(\n req.headers,\n () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url,\n },\n },\n (span) => handleResponse(span, parentSpan)\n ),\n undefined,\n !isWrappedByNextServer\n )\n }\n}\n"],"names":["dynamic","GET","_req","params","projectId","store","cfg","beads","list","meta","kind","humanActor","humanAllowlist","agents","pollIntervalMs","gamification","readOnly","lanePrefix","e","POST","req","input","parse","json","bead","create","AppRouteRouteModule","RouteKind","patchFetch","_patchFetch","addRequestMeta","getRequestMeta","setRequestMeta","getTracer","SpanKind","SpanStatusCode","setManifestsSingleton","normalizeAppPath","NodeNextRequest","NodeNextResponse","NextRequestAdapter","signalFromNodeResponse","BaseServerSpan","getRevalidateReason","sendResponse","fromNodeOutgoingHttpHeaders","toNodeOutgoingHttpHeaders","getCacheControlHeader","INFINITE_CACHE","NEXT_CACHE_TAGS_HEADER","NoFallbackError","isRouteCacheOwner","CachedRouteKind","routeModule","definition","APP_ROUTE","page","pathname","filename","bundlePath","distDir","process","env","__NEXT_RELATIVE_DIST_DIR","relativeProjectDir","__NEXT_RELATIVE_PROJECT_DIR","resolvedPagePath","nextConfigOutput","userland","require","TURBOPACK","__NEXT_DEV_SERVER","getUserland","workAsyncStorage","workUnitAsyncStorage","serverHooks","handler","res","ctx","requestMeta","isDev","hrtime","bigint","srcPage","replace","multiZoneDraftMode","__NEXT_MULTI_ZONE_DRAFT_MODE","prepareResult","prepare","statusCode","end","waitUntil","Promise","resolve","buildId","deploymentId","nextConfig","parsedUrl","isDraftMode","prerenderManifest","routerServerContext","isOnDemandRevalidate","revalidateOnlyGenerated","resolvedPathname","clientReferenceManifest","serverActionsManifest","previewProps","normalizedSrcPage","isPrerendered","Boolean","routes","cacheOwner","isIsr","dynamicRoutes","render404","prerenderInfo","fallback","adapterPath","cacheKey","method","tracer","activeSpan","getActiveScopeSpan","isWrappedByNextServer","isMinimalMode","incrementalCache","getIncrementalCache","resetRequestCache","globalThis","__incrementalCache","context","renderOpts","experimental","authInterrupts","useCacheTimeout","durableUseCacheEntries","cacheComponents","validationLevel","instantInsights","hmrRefreshHash","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","onClose","cb","on","onAfterTaskError","undefined","sharedContext","nodeNextReq","nodeNextRes","nextReq","fromNodeNextRequest","responseGenerator","previousCacheEntry","setHeader","response","handle","prerender","fetchMetrics","pendingWaitUntil","cacheTags","collectedTags","blob","headers","type","revalidate","collectedRevalidate","expire","collectedExpire","expireTime","cacheEntry","value","status","body","Buffer","from","arrayBuffer","cacheControl","err","isStale","silenceLog","onRequestError","routerKind","routePath","routeType","revalidateReason","isStaticGeneration","handleResponse","currentSpan","parentSpan","routeKind","isFallback","isRoutePPREnabled","error","Error","isMiss","delete","getHeader","get","set","Response","headersSent","recordException","setStatus","code","ERROR","message","setAttribute","name","writableEnded","destroyed","setAttributes","toString","rootSpanAttributes","getRootSpanAttributes","handleRequest","console","warn","route","updateName","withPropagatedContext","trace","spanName","SERVER","attributes","url","span"],"mappings":"6CAAA,IAAA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,MACA,EAAA,EAAA,CAAA,CAAA,OAMO,eAAeC,EAAIC,CAAa,CAAE,QAAEC,CAAM,CAAO,EACtD,GAAI,CACF,GAAM,WAAEC,CAAS,CAAE,CAAG,MAAMD,EACtBE,EAAQ,MAAM,CAAA,EAAA,EAAA,CAAA,AAAQ,EAACD,GACvBE,EAAM,CAAA,EAAA,EAAA,CAAA,AAAS,IACfC,EAAQ,MAAMF,EAAMG,IAAI,GAC9B,MAAO,CAAA,EAAA,EAAA,CAAA,AAAE,EAAC,OACRD,EACAE,KAAM,CACJC,KAAML,EAAMK,IAAI,CAChBC,WAAYL,EAAIK,UAAU,CAC1BC,eAAgBN,EAAIM,cAAc,CAClCC,OAAQP,EAAIO,MAAM,CAClBC,eAAgBR,EAAIQ,cAAc,CAClCC,aAAcT,EAAIS,YAAY,CAC9BC,SAAU,CAAA,EAAA,EAAA,CAAA,AAAU,EAACd,GACrBe,WAAY,CAAA,EAAA,EAAA,CAAA,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i(5954),a=e.i(55744),n=e.i(72507),i=e.i(73744);let o=t.z.object({columnId:r.z.string().min(1),ids:a.z.array(r.z.string())});async function s(e,{params:t}){try{let{projectId:e}=await t;return(0,i.N)({orders:(0,n.d)(e)})}catch(e){return(0,i.O)(e)}}async function l(e,{params:t}){try{let{projectId:r}=await t,{columnId:a,ids:s}=o.parse(await e.json());return(0,i.N)({orders:(0,n.v)(r,a,s)})}catch(e){return(0,i.O)(e)}}e.s(["GET",0,s,"PUT",0,l,"dynamic",0,"force-dynamic"])},4953,e=>{var t=e.i(47909),r=e.i(74017),a=e.i(96250),n=e.i(59756),i=e.i(61916),o=e.i(74677),s=e.i(69741),l=e.i(16795),u=e.i(87718),d=e.i(95169),c=e.i(47587),p=e.i(66012),h=e.i(70101),f=e.i(74838),v=e.i(10372),w=e.i(93695),m=e.i(9580);e.i(52474);var R=e.i(220);let x=new t.AppRouteRouteModule({definition:{kind:r.f.APP_ROUTE,page:"/api/p/[projectId]/order/route",pathname:"/api/p/[projectId]/order",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/p/[projectId]/order/route.ts",nextConfigOutput:"",userland:()=>e.r(85824),...{}}),{workAsyncStorage:y,workUnitAsyncStorage:g,serverHooks:E}=x;async function C(e,t,a){a.requestMeta&&(0,n.R)(e,a.requestMeta),x.isDev&&(0,n.i)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let y="/api/p/[projectId]/order/route";y=y.replace(/\/index$/,"")||"/";let g=await x.prepare(e,t,{srcPage:y,multiZoneDraftMode:!1});if(!g)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:E,deploymentId:C,params:b,nextConfig:P,parsedUrl:T,isDraftMode:A,prerenderManifest:S,routerServerContext:O,isOnDemandRevalidate:U,revalidateOnlyGenerated:k,resolvedPathname:I,clientReferenceManifest:j,serverActionsManifest:q,previewProps:M}=g,N=(0,s.f)(y),D=!!S.routes[I]&&(x.isDev||(0,m.f)(I,x.cacheOwner,S.routes[I])),_=!!(S.dynamicRoutes[N]||D),H=async()=>((null==O?void 0:O.render404)?await O.render404(e,t,T,!1):t.end("This page could not be found"),null);if(_&&!A){let e=S.dynamicRoutes[N];if(e&&!1===e.fallback&&!D){if(P.adapterPath)return await H();throw new w.NoFallbackError}}let G=null;!_||x.isDev||A||(G="/index"===(G=I)?"/":G),q&&j&&(0,o.f)({page:y,clientReferenceManifest:j,serverActionsManifest:q});let L=e.method||"GET",$=(0,i.v)(),z=$.getActiveScopeSpan(),B=!!(null==O?void 0:O.isWrappedByNextServer),F=!!(0,n.w)(e,"minimalMode"),K=(0,n.w)(e,"incrementalCache")||await x.getIncrementalCache(e,P,M,S,F);null==K||K.resetRequestCache(),globalThis.__incrementalCache=K;let V={params:b,previewProps:M,renderOpts:{experimental:{authInterrupts:!!P.experimental.authInterrupts,useCacheTimeout:P.experimental.useCacheTimeout,durableUseCacheEntries:!!P.experimental.durableUseCacheEntries},cacheComponents:!!P.cacheComponents,validationLevel:P.experimental.instantInsights.validationLevel,isDraftMode:A,incrementalCache:K,hmrRefreshHash:(0,n.w)(e,"hmrRefreshHash"),cacheLifeProfiles:P.cacheLife,staticPageGenerationTimeout:P.staticPageGenerationTimeout,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0},sharedContext:{buildId:E,deploymentId:C}},J=new l.x(e),Q=new l.e(t),W=u.k.fromNodeNextRequest(J,(0,u.t)(t)),Z=async({previousCacheEntry:r})=>{try{if(!F&&U&&k&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=null===G?await x.handle(W,V):await x.prerender(W,V);e.fetchMetrics=V.renderOpts.fetchMetrics;let i=V.renderOpts.pendingWaitUntil;i&&a.waitUntil&&(a.waitUntil(i),i=void 0);let o=V.renderOpts.collectedTags;if(!_)return await (0,p.f)(J,Q,n,i),null;{let e=await n.blob(),t=(0,h.S)(n.headers);o&&(t[v.M]=o),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==V.renderOpts.collectedRevalidate&&!(V.renderOpts.collectedRevalidate>=v.Q)&&V.renderOpts.collectedRevalidate,a=void 0===V.renderOpts.collectedExpire||V.renderOpts.collectedExpire>=v.Q?!1!==r&&r>0?P.expireTime:void 0:V.renderOpts.collectedExpire;return{value:{kind:R.x.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await x.onRequestError(e,t,{routerKind:"App Router",routePath:y,routeType:"route",revalidateReason:(0,c.f)({isStaticGeneration:null!==G,isOnDemandRevalidate:U})},!1,O),t}},X=async(n,o)=>{try{var s,l;let n=await x.handleResponse({req:e,nextConfig:P,cacheKey:G,routeKind:r.f.APP_ROUTE,isFallback:!1,previewProps:M,prerenderManifest:S,isRoutePPREnabled:!1,isOnDemandRevalidate:U,revalidateOnlyGenerated:k,responseGenerator:Z,waitUntil:a.waitUntil,isMinimalMode:F});if(null!==n&&"error"in n)throw n.error;if(!_)return;if((null==n||null==(s=n.value)?void 0:s.kind)!==R.x.APP_ROUTE)throw Error(`Invariant: app-route received invalid cache entry ${null==n||null==(l=n.value)?void 0:l.kind}`);F||t.setHeader("x-nextjs-cache",U?"REVALIDATED":n.isMiss?"MISS":n.isStale?"STALE":"HIT"),A&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let i=(0,h.G)(n.value.headers);F&&_||i.delete(v.M),!n.cacheControl||t.getHeader("Cache-Control")||i.get("Cache-Control")||i.set("Cache-Control",(0,f.f)(n.cacheControl)),await (0,p.f)(J,Q,new Response(n.value.body,{headers:i,status:n.value.status||200}));return}catch(r){if(r instanceof w.NoFallbackError||await x.onRequestError(e,r,{routerKind:"App Router",routePath:N,routeType:"route",revalidateReason:(0,c.f)({isStaticGeneration:null!==G,isOnDemandRevalidate:U})},!1,O),_)throw r;if(t.headersSent){if(n){let e=r instanceof Error?r:Error("Unknown app route error");n.recordException(e),n.setStatus({code:i.J.ERROR,message:e.message}),n.setAttribute("error.type",e.name)}t.writableEnded||t.destroyed||t.end()}else await (0,p.f)(J,Q,new Response(null,{status:500}));return}finally{(()=>{if(!n)return;let e=t.statusCode;n.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(n.setStatus({code:i.J.ERROR}),n.setAttribute("error.type",e.toString()));let r=$.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.q.handleRequest)return console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route")||N,s=`${L} ${a}`;n.setAttributes({"next.route":a,"http.route":a,"next.span_name":s}),n.updateName(s),o&&o!==n&&(o.setAttribute("http.route",a),o.updateName(s))})()}};if(B&&z)await X(z,void 0);else{let t=$.getActiveScopeSpan();await $.withPropagatedContext(e.headers,()=>$.trace(d.q.handleRequest,{spanName:`${L} ${y}`,kind:i.C.SERVER,attributes:{"http.method":L,"http.target":e.url}},e=>X(e,t)),void 0,!B)}}e.s(["handler",0,C,"patchFetch",0,function(){return(0,a.f)({workAsyncStorage:y,workUnitAsyncStorage:g})},"routeModule",0,x,"serverHooks",0,E,"workAsyncStorage",0,y,"workUnitAsyncStorage",0,g])}]})();
1
+ (()=>{"use strict";module.exports=[85824,e=>{var t=e.i(71724),r=e.i(5954),a=e.i(55744),n=e.i(72507),i=e.i(73744);let o=t.z.object({columnId:r.z.string().min(1),ids:a.z.array(r.z.string())});async function s(e,{params:t}){try{let{projectId:e}=await t;return(0,i.N)({orders:(0,n.d)(e)})}catch(e){return(0,i.O)(e)}}async function l(e,{params:t}){try{let{projectId:r}=await t,{columnId:a,ids:s}=o.parse(await e.json());return(0,i.N)({orders:(0,n.w)(r,a,s)})}catch(e){return(0,i.O)(e)}}e.s(["GET",0,s,"PUT",0,l,"dynamic",0,"force-dynamic"])},4953,e=>{var t=e.i(47909),r=e.i(74017),a=e.i(96250),n=e.i(59756),i=e.i(61916),o=e.i(74677),s=e.i(69741),l=e.i(16795),u=e.i(87718),d=e.i(95169),c=e.i(47587),p=e.i(66012),h=e.i(70101),f=e.i(74838),v=e.i(10372),w=e.i(93695),m=e.i(9580);e.i(52474);var R=e.i(220);let x=new t.AppRouteRouteModule({definition:{kind:r.f.APP_ROUTE,page:"/api/p/[projectId]/order/route",pathname:"/api/p/[projectId]/order",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/p/[projectId]/order/route.ts",nextConfigOutput:"",userland:()=>e.r(85824),...{}}),{workAsyncStorage:y,workUnitAsyncStorage:g,serverHooks:E}=x;async function C(e,t,a){a.requestMeta&&(0,n.R)(e,a.requestMeta),x.isDev&&(0,n.i)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let y="/api/p/[projectId]/order/route";y=y.replace(/\/index$/,"")||"/";let g=await x.prepare(e,t,{srcPage:y,multiZoneDraftMode:!1});if(!g)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:E,deploymentId:C,params:b,nextConfig:P,parsedUrl:T,isDraftMode:A,prerenderManifest:S,routerServerContext:O,isOnDemandRevalidate:U,revalidateOnlyGenerated:k,resolvedPathname:I,clientReferenceManifest:j,serverActionsManifest:q,previewProps:M}=g,N=(0,s.f)(y),D=!!S.routes[I]&&(x.isDev||(0,m.f)(I,x.cacheOwner,S.routes[I])),_=!!(S.dynamicRoutes[N]||D),H=async()=>((null==O?void 0:O.render404)?await O.render404(e,t,T,!1):t.end("This page could not be found"),null);if(_&&!A){let e=S.dynamicRoutes[N];if(e&&!1===e.fallback&&!D){if(P.adapterPath)return await H();throw new w.NoFallbackError}}let G=null;!_||x.isDev||A||(G="/index"===(G=I)?"/":G),q&&j&&(0,o.f)({page:y,clientReferenceManifest:j,serverActionsManifest:q});let L=e.method||"GET",$=(0,i.v)(),z=$.getActiveScopeSpan(),B=!!(null==O?void 0:O.isWrappedByNextServer),F=!!(0,n.w)(e,"minimalMode"),K=(0,n.w)(e,"incrementalCache")||await x.getIncrementalCache(e,P,M,S,F);null==K||K.resetRequestCache(),globalThis.__incrementalCache=K;let V={params:b,previewProps:M,renderOpts:{experimental:{authInterrupts:!!P.experimental.authInterrupts,useCacheTimeout:P.experimental.useCacheTimeout,durableUseCacheEntries:!!P.experimental.durableUseCacheEntries},cacheComponents:!!P.cacheComponents,validationLevel:P.experimental.instantInsights.validationLevel,isDraftMode:A,incrementalCache:K,hmrRefreshHash:(0,n.w)(e,"hmrRefreshHash"),cacheLifeProfiles:P.cacheLife,staticPageGenerationTimeout:P.staticPageGenerationTimeout,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0},sharedContext:{buildId:E,deploymentId:C}},J=new l.x(e),Q=new l.e(t),W=u.k.fromNodeNextRequest(J,(0,u.t)(t)),Z=async({previousCacheEntry:r})=>{try{if(!F&&U&&k&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=null===G?await x.handle(W,V):await x.prerender(W,V);e.fetchMetrics=V.renderOpts.fetchMetrics;let i=V.renderOpts.pendingWaitUntil;i&&a.waitUntil&&(a.waitUntil(i),i=void 0);let o=V.renderOpts.collectedTags;if(!_)return await (0,p.f)(J,Q,n,i),null;{let e=await n.blob(),t=(0,h.S)(n.headers);o&&(t[v.M]=o),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==V.renderOpts.collectedRevalidate&&!(V.renderOpts.collectedRevalidate>=v.Q)&&V.renderOpts.collectedRevalidate,a=void 0===V.renderOpts.collectedExpire||V.renderOpts.collectedExpire>=v.Q?!1!==r&&r>0?P.expireTime:void 0:V.renderOpts.collectedExpire;return{value:{kind:R.x.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await x.onRequestError(e,t,{routerKind:"App Router",routePath:y,routeType:"route",revalidateReason:(0,c.f)({isStaticGeneration:null!==G,isOnDemandRevalidate:U})},!1,O),t}},X=async(n,o)=>{try{var s,l;let n=await x.handleResponse({req:e,nextConfig:P,cacheKey:G,routeKind:r.f.APP_ROUTE,isFallback:!1,previewProps:M,prerenderManifest:S,isRoutePPREnabled:!1,isOnDemandRevalidate:U,revalidateOnlyGenerated:k,responseGenerator:Z,waitUntil:a.waitUntil,isMinimalMode:F});if(null!==n&&"error"in n)throw n.error;if(!_)return;if((null==n||null==(s=n.value)?void 0:s.kind)!==R.x.APP_ROUTE)throw Error(`Invariant: app-route received invalid cache entry ${null==n||null==(l=n.value)?void 0:l.kind}`);F||t.setHeader("x-nextjs-cache",U?"REVALIDATED":n.isMiss?"MISS":n.isStale?"STALE":"HIT"),A&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let i=(0,h.G)(n.value.headers);F&&_||i.delete(v.M),!n.cacheControl||t.getHeader("Cache-Control")||i.get("Cache-Control")||i.set("Cache-Control",(0,f.f)(n.cacheControl)),await (0,p.f)(J,Q,new Response(n.value.body,{headers:i,status:n.value.status||200}));return}catch(r){if(r instanceof w.NoFallbackError||await x.onRequestError(e,r,{routerKind:"App Router",routePath:N,routeType:"route",revalidateReason:(0,c.f)({isStaticGeneration:null!==G,isOnDemandRevalidate:U})},!1,O),_)throw r;if(t.headersSent){if(n){let e=r instanceof Error?r:Error("Unknown app route error");n.recordException(e),n.setStatus({code:i.J.ERROR,message:e.message}),n.setAttribute("error.type",e.name)}t.writableEnded||t.destroyed||t.end()}else await (0,p.f)(J,Q,new Response(null,{status:500}));return}finally{(()=>{if(!n)return;let e=t.statusCode;n.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(n.setStatus({code:i.J.ERROR}),n.setAttribute("error.type",e.toString()));let r=$.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.q.handleRequest)return console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route")||N,s=`${L} ${a}`;n.setAttributes({"next.route":a,"http.route":a,"next.span_name":s}),n.updateName(s),o&&o!==n&&(o.setAttribute("http.route",a),o.updateName(s))})()}};if(B&&z)await X(z,void 0);else{let t=$.getActiveScopeSpan();await $.withPropagatedContext(e.headers,()=>$.trace(d.q.handleRequest,{spanName:`${L} ${y}`,kind:i.C.SERVER,attributes:{"http.method":L,"http.target":e.url}},e=>X(e,t)),void 0,!B)}}e.s(["handler",0,C,"patchFetch",0,function(){return(0,a.f)({workAsyncStorage:y,workUnitAsyncStorage:g})},"routeModule",0,x,"serverHooks",0,E,"workAsyncStorage",0,y,"workUnitAsyncStorage",0,g])}]})();
2
2
 
3
3
  //# sourceMappingURL=_1tji4d-rsralm._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[95100,e=>{"use strict";var t=e.i(5622);let n={open:"Open",in_progress:"In progress",blocked:"Blocked",deferred:"Deferred",closed:"Closed",pinned:"Pinned",hooked:"Hooked"},o=["Critical","High","Medium","Low","Backlog"],r=["#6d5ef0","#0ea5e9","#16a34a","#d97706","#db2777","#0891b2","#7c3aed"];e.s(["q",0,function(e){if(!e)return"#9aa0aa";let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)>>>0;return r[t%r.length]},"P",0,function(e,t){return t.filter(t=>(t.dependencies??[]).some(t=>"parent-child"===t.type&&t.depends_on_id===e))},"s",0,function(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric"}):""},"u",0,function(e){if(!e)return"?";let t=e.split(/[-_ .]/).filter(Boolean);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()},"V",0,function(e,n){var o,r;return"blocked"===e.status||"open"===e.status&&(o=e,r=n,(o.dependencies??[]).filter(e=>"parent-child"!==e.type&&t.K.includes(e.type)&&(r.get(e.depends_on_id)?.status??"open")!=="closed").map(e=>e.depends_on_id)).length>0},"Y",0,function(e){let t=new Map;for(let n of e)t.set(n.id,n);return t},"v",0,function(e){return o[e]??String(e)},"L",0,function(e,t=new Date){if(!e)return"";let n=(t.getTime()-new Date(e).getTime())/1e3;return n<60?"just now":n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:n<2592e3?`${Math.floor(n/86400)}d ago`:`${Math.floor(n/2592e3)}mo ago`},"g",0,function(e){return n[e]??e},"H",0,function(e){return e.charAt(0).toUpperCase()+e.slice(1)}])}];
1
+ module.exports=[95100,e=>{"use strict";var t=e.i(5622);let n={open:"Open",in_progress:"In progress",blocked:"Blocked",deferred:"Deferred",closed:"Closed",pinned:"Pinned",hooked:"Hooked"},o=["Critical","High","Medium","Low","Backlog"],r=["#5f50e6","#0369a1","#15803d","#b45309","#be185d","#0e7490","#6d28d9"];e.s(["q",0,function(e){if(!e)return"#6b7280";let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)>>>0;return r[t%r.length]},"P",0,function(e,t){return t.filter(t=>(t.dependencies??[]).some(t=>"parent-child"===t.type&&t.depends_on_id===e))},"s",0,function(e){return e?new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric"}):""},"u",0,function(e){if(!e)return"?";let t=e.split(/[-_ .]/).filter(Boolean);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()},"V",0,function(e,n){var o,r;return"blocked"===e.status||"open"===e.status&&(o=e,r=n,(o.dependencies??[]).filter(e=>"parent-child"!==e.type&&t.K.includes(e.type)&&(r.get(e.depends_on_id)?.status??"open")!=="closed").map(e=>e.depends_on_id)).length>0},"Y",0,function(e){let t=new Map;for(let n of e)t.set(n.id,n);return t},"v",0,function(e){return o[e]??String(e)},"L",0,function(e,t=new Date){if(!e)return"";let n=(t.getTime()-new Date(e).getTime())/1e3;return n<60?"just now":n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:n<2592e3?`${Math.floor(n/86400)}d ago`:`${Math.floor(n/2592e3)}mo ago`},"g",0,function(e){return n[e]??e},"H",0,function(e){return e.charAt(0).toUpperCase()+e.slice(1)}])}];
2
2
 
3
3
  //# sourceMappingURL=lib_beads-view_ts_1fvxcrevh9zu_._.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../lib/beads-view.ts"],"sourcesContent":["import type { Bead } from \"./schema\";\nimport { BLOCKING_DEP_TYPES } from \"./schema\";\n\n/**\n * Pure view-model helpers, ported from the Claude Design export prototype.\n * Framework-agnostic so they can run on the server and the client.\n */\n\n/**\n * A bead needs a human decision when it carries the `human` label (set by\n * `bd human`) and is still actionable (not closed or deferred). Drives the\n * \"Needs You\" inbox and its sidebar count badge.\n */\nexport function needsHuman(b: Bead): boolean {\n return (b.labels ?? []).includes(\"human\") && b.status !== \"closed\" && b.status !== \"deferred\";\n}\n\n/**\n * A human-approval gate: an `issue_type === \"gate\"` bead created by\n * `bd gate create --type human`. Unlike `bd human` (a label on a normal bead),\n * a gate is its own bead whose sub-type lives in `await_type`, so it never\n * carries the `human` label and `needsHuman()` misses it.\n */\nexport function isHumanGate(b: Bead): boolean {\n return b.issue_type === \"gate\" && b.await_type === \"human\";\n}\n\n/**\n * A human-approval gate that is unresolved and not itself blocked — its own\n * blockers (if any) are all closed, so a person can approve/resolve it now.\n * These belong on the \"Needs You\" inbox alongside `needsHuman()` beads\n * (bead 8qc / gh-6). Resolving = closing the gate, which unblocks its dependents.\n */\nexport function readyHumanGate(b: Bead, index: Map<string, Bead>): boolean {\n return isHumanGate(b) && b.status !== \"closed\" && !isBlocked(b, index);\n}\n\n/** Beads that this gate blocks (they depend on it via a blocking dep). */\nexport function gateBlocks(gateId: string, beads: Bead[]): Bead[] {\n return beads.filter((b) =>\n (b.dependencies ?? []).some((d) => d.depends_on_id === gateId && BLOCKING_DEP_TYPES.includes(d.type as never)),\n );\n}\n\n/**\n * GFM task-list (\"- [ ]\" / \"- [x]\") helpers. Checklists live in the bead\n * description text itself (zero new schema), so toggling rewrites the markdown.\n */\nconst TASK_RE = /^(\\s*(?:[-*+]|\\d+\\.)\\s+)\\[([ xX])\\]/gm;\n\nexport function checklistProgress(text?: string | null): { done: number; total: number } {\n if (!text) return { done: 0, total: 0 };\n const re = new RegExp(TASK_RE);\n let done = 0;\n let total = 0;\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n total++;\n if (m[2].toLowerCase() === \"x\") done++;\n }\n return { done, total };\n}\n\n/** Flip the Nth task checkbox (0-based, document order) and return the new text. */\nexport function toggleTask(text: string, index: number): string {\n let i = 0;\n return text.replace(TASK_RE, (full, prefix: string, mark: string) => {\n if (i++ !== index) return full;\n return `${prefix}[${mark.toLowerCase() === \"x\" ? \" \" : \"x\"}]`;\n });\n}\n\n/**\n * `bd close` with no `--reason` still records a reason: the literal \"Closed\".\n * That placeholder carries no information, so treat it as absent rather than\n * rendering a \"Close reason\" section that just says \"Closed\".\n */\nexport function closeReasonOf(b: Bead): string {\n const reason = b.close_reason?.trim() ?? \"\";\n return reason.toLowerCase() === \"closed\" ? \"\" : reason;\n}\n\nexport type StatusCategory = \"done\" | \"wip\" | \"blocked\" | \"frozen\" | \"active\";\n\nexport function category(status: string): StatusCategory {\n if (status === \"closed\") return \"done\";\n if (status === \"in_progress\" || status === \"hooked\") return \"wip\";\n if (status === \"blocked\") return \"blocked\";\n if (status === \"deferred\" || status === \"pinned\") return \"frozen\";\n return \"active\";\n}\n\nconst CAT_COLORS: Record<StatusCategory, string> = {\n done: \"#16a34a\",\n wip: \"#d97706\",\n blocked: \"#ef4444\",\n frozen: \"#64748b\",\n active: \"#3b82f6\",\n};\nexport function catColor(status: string): string {\n return CAT_COLORS[category(status)];\n}\n\nconst STATUS_LABELS: Record<string, string> = {\n open: \"Open\",\n in_progress: \"In progress\",\n blocked: \"Blocked\",\n deferred: \"Deferred\",\n closed: \"Closed\",\n pinned: \"Pinned\",\n hooked: \"Hooked\",\n};\nexport function statusLabel(status: string): string {\n return STATUS_LABELS[status] ?? status;\n}\n\nconst PRIO_COLORS = [\"#ef4444\", \"#f97316\", \"#eab308\", \"#0ea5e9\", \"#64748b\"];\nconst PRIO_LABELS = [\"Critical\", \"High\", \"Medium\", \"Low\", \"Backlog\"];\nexport function prioColor(p: number): string {\n return PRIO_COLORS[p] ?? \"#64748b\";\n}\nexport function prioLabel(p: number): string {\n return PRIO_LABELS[p] ?? String(p);\n}\n\nexport function typeColor(t: string): string {\n if (t === \"epic\") return \"var(--brand)\";\n if (t === \"bug\") return \"#ef4444\";\n return \"var(--text-3)\";\n}\nexport function typeLabel(t: string): string {\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\nconst AVATARS = [\n \"#6d5ef0\",\n \"#0ea5e9\",\n \"#16a34a\",\n \"#d97706\",\n \"#db2777\",\n \"#0891b2\",\n \"#7c3aed\",\n];\nexport function avatarColor(name: string): string {\n if (!name) return \"#9aa0aa\";\n let h = 0;\n for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;\n return AVATARS[h % AVATARS.length];\n}\nexport function initials(name: string): string {\n if (!name) return \"?\";\n const parts = name.split(/[-_ .]/).filter(Boolean);\n if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();\n return name.slice(0, 2).toUpperCase();\n}\n\n// ---- relationship helpers (need the full bead set for lookups) ----\n\nexport function makeIndex(beads: Bead[]): Map<string, Bead> {\n const m = new Map<string, Bead>();\n for (const b of beads) m.set(b.id, b);\n return m;\n}\n\nexport function isBlocked(b: Bead, index: Map<string, Bead>): boolean {\n if (b.status === \"blocked\") return true;\n if (b.status !== \"open\") return false;\n return blockingDeps(b, index).length > 0;\n}\n\n/**\n * The unresolved things actually holding this bead up — for naming blockers on a\n * card, so it must not name something the user doesn't experience as a blocker.\n *\n * `parent-child` is excluded even though bd counts it in BLOCKING_DEP_TYPES for\n * ready-queue purposes: the edge points from a child to its epic, so including\n * it makes every blocked child report its own parent epic alongside the real\n * blocker (\"blocked by <the epic it lives in>\"), which is noise at best and\n * misdirection at worst. Hierarchy is shown as hierarchy elsewhere.\n *\n * Shared by isBlocked so the badge, Focus column, and blocker names agree.\n */\nexport function blockingDeps(b: Bead, index: Map<string, Bead>): string[] {\n return (b.dependencies ?? [])\n .filter(\n (d) =>\n d.type !== \"parent-child\" &&\n BLOCKING_DEP_TYPES.includes(d.type as never) &&\n (index.get(d.depends_on_id)?.status ?? \"open\") !== \"closed\",\n )\n .map((d) => d.depends_on_id);\n}\n\n/**\n * The bead's parent, whatever its type. Resolved from the parent-child\n * dependency EDGE — never `bead.parent`, which `bd export --json` omits, so an\n * edge lookup is the only one correct on board/list data as well as in the\n * drawer.\n *\n * Replaces the former `epicOf`, which returned the same thing but was named as\n * though the parent were always an epic — so a task-parented bead rendered a\n * chip labelled \"epic\" and clicked through to the Epics screen, which renders\n * epics only. Callers now branch on `parent.issue_type` themselves.\n */\nexport function parentOf(b: Bead, index: Map<string, Bead>): Bead | null {\n const d = (b.dependencies ?? []).find((x) => x.type === \"parent-child\");\n return d ? index.get(d.depends_on_id) ?? null : null;\n}\n\n/**\n * Children per parent id, built in ONE pass over all beads. Callers render\n * per-card counts from this rather than calling childrenOf() per card, which\n * would be an O(n²) scan on a large board.\n */\nexport function childrenCountMap(beads: Bead[]): Map<string, number> {\n const m = new Map<string, number>();\n for (const b of beads) {\n for (const d of b.dependencies ?? []) {\n if (d.type === \"parent-child\") m.set(d.depends_on_id, (m.get(d.depends_on_id) ?? 0) + 1);\n }\n }\n return m;\n}\n\nexport function childrenOf(epicId: string, beads: Bead[]): Bead[] {\n return beads.filter((b) =>\n (b.dependencies ?? []).some(\n (d) => d.type === \"parent-child\" && d.depends_on_id === epicId,\n ),\n );\n}\n\nexport function epicProgress(\n epicId: string,\n beads: Bead[],\n): { closed: number; total: number; pct: number } {\n const kids = childrenOf(epicId, beads);\n const total = kids.length;\n const closed = kids.filter((k) => k.status === \"closed\").length;\n return { closed, total, pct: total ? Math.round((closed / total) * 100) : 0 };\n}\n\n// ---- relative time ----\n\nexport function relTime(iso?: string | null, now: Date = new Date()): string {\n if (!iso) return \"\";\n const d = (now.getTime() - new Date(iso).getTime()) / 1000;\n if (d < 60) return \"just now\";\n if (d < 3600) return `${Math.floor(d / 60)}m ago`;\n if (d < 86400) return `${Math.floor(d / 3600)}h ago`;\n if (d < 2592000) return `${Math.floor(d / 86400)}d ago`;\n return `${Math.floor(d / 2592000)}mo ago`;\n}\n\nexport function fmtDate(iso?: string | null): string {\n if (!iso) return \"\";\n return new Date(iso).toLocaleDateString(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n });\n}\n\n/** Full absolute timestamp, e.g. \"Jun 24, 2026, 2:15 PM\" — used as the hover\n * title behind relative times like \"3d ago\" (bead hl2). */\nexport function fmtDateTime(iso?: string | null): string {\n if (!iso) return \"\";\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return \"\";\n return d.toLocaleString(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n}\n"],"names":["needsHuman","b","labels","includes","status","isHumanGate","issue_type","await_type","readyHumanGate","index","isBlocked","gateBlocks","gateId","beads","filter","dependencies","some","d","depends_on_id","type","TASK_RE","checklistProgress","text","done","total","re","RegExp","m","exec","toLowerCase","toggleTask","i","replace","full","prefix","mark","closeReasonOf","reason","close_reason","trim","category","CAT_COLORS","wip","blocked","frozen","active","catColor","STATUS_LABELS","open","in_progress","deferred","closed","pinned","hooked","statusLabel","PRIO_COLORS","PRIO_LABELS","prioColor","p","prioLabel","String","typeColor","t","typeLabel","charAt","toUpperCase","slice","AVATARS","avatarColor","name","h","length","charCodeAt","initials","parts","split","Boolean","makeIndex","Map","set","id","blockingDeps","get","map","parentOf","find","x","childrenCountMap","childrenOf","epicId","epicProgress","kids","k","pct","Math","round","relTime","iso","now","Date","getTime","floor","fmtDate","toLocaleDateString","month","day","fmtDateTime","Number","isNaN","toLocaleString","year","hour","minute"],"m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c,EACxC,OAAO2C,CAAa,CAAC3C,EAAO,EAAIA,CAClC,QAgBO,SAAS2D,AAAUD,CAAS,EACjC,OAAOA,EAAEE,MAAM,CAAC,GAAGC,WAAW,GAAKH,EAAEI,KAAK,CAAC,EAC7C"}
1
+ {"version":3,"sources":["../../../lib/beads-view.ts"],"sourcesContent":["import type { Bead } from \"./schema\";\nimport { BLOCKING_DEP_TYPES } from \"./schema\";\n\n/**\n * Pure view-model helpers, ported from the Claude Design export prototype.\n * Framework-agnostic so they can run on the server and the client.\n */\n\n/**\n * A bead needs a human decision when it carries the `human` label (set by\n * `bd human`) and is still actionable (not closed or deferred). Drives the\n * \"Needs You\" inbox and its sidebar count badge.\n */\nexport function needsHuman(b: Bead): boolean {\n return (b.labels ?? []).includes(\"human\") && b.status !== \"closed\" && b.status !== \"deferred\";\n}\n\n/**\n * A human-approval gate: an `issue_type === \"gate\"` bead created by\n * `bd gate create --type human`. Unlike `bd human` (a label on a normal bead),\n * a gate is its own bead whose sub-type lives in `await_type`, so it never\n * carries the `human` label and `needsHuman()` misses it.\n */\nexport function isHumanGate(b: Bead): boolean {\n return b.issue_type === \"gate\" && b.await_type === \"human\";\n}\n\n/**\n * A human-approval gate that is unresolved and not itself blocked — its own\n * blockers (if any) are all closed, so a person can approve/resolve it now.\n * These belong on the \"Needs You\" inbox alongside `needsHuman()` beads\n * (bead 8qc / gh-6). Resolving = closing the gate, which unblocks its dependents.\n */\nexport function readyHumanGate(b: Bead, index: Map<string, Bead>): boolean {\n return isHumanGate(b) && b.status !== \"closed\" && !isBlocked(b, index);\n}\n\n/** Beads that this gate blocks (they depend on it via a blocking dep). */\nexport function gateBlocks(gateId: string, beads: Bead[]): Bead[] {\n return beads.filter((b) =>\n (b.dependencies ?? []).some((d) => d.depends_on_id === gateId && BLOCKING_DEP_TYPES.includes(d.type as never)),\n );\n}\n\n/**\n * GFM task-list (\"- [ ]\" / \"- [x]\") helpers. Checklists live in the bead\n * description text itself (zero new schema), so toggling rewrites the markdown.\n */\nconst TASK_RE = /^(\\s*(?:[-*+]|\\d+\\.)\\s+)\\[([ xX])\\]/gm;\n\nexport function checklistProgress(text?: string | null): { done: number; total: number } {\n if (!text) return { done: 0, total: 0 };\n const re = new RegExp(TASK_RE);\n let done = 0;\n let total = 0;\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n total++;\n if (m[2].toLowerCase() === \"x\") done++;\n }\n return { done, total };\n}\n\n/** Flip the Nth task checkbox (0-based, document order) and return the new text. */\nexport function toggleTask(text: string, index: number): string {\n let i = 0;\n return text.replace(TASK_RE, (full, prefix: string, mark: string) => {\n if (i++ !== index) return full;\n return `${prefix}[${mark.toLowerCase() === \"x\" ? \" \" : \"x\"}]`;\n });\n}\n\n/**\n * `bd close` with no `--reason` still records a reason: the literal \"Closed\".\n * That placeholder carries no information, so treat it as absent rather than\n * rendering a \"Close reason\" section that just says \"Closed\".\n */\nexport function closeReasonOf(b: Bead): string {\n const reason = b.close_reason?.trim() ?? \"\";\n return reason.toLowerCase() === \"closed\" ? \"\" : reason;\n}\n\nexport type StatusCategory = \"done\" | \"wip\" | \"blocked\" | \"frozen\" | \"active\";\n\nexport function category(status: string): StatusCategory {\n if (status === \"closed\") return \"done\";\n if (status === \"in_progress\" || status === \"hooked\") return \"wip\";\n if (status === \"blocked\") return \"blocked\";\n if (status === \"deferred\" || status === \"pinned\") return \"frozen\";\n return \"active\";\n}\n\nconst CAT_COLORS: Record<StatusCategory, string> = {\n done: \"#16a34a\",\n wip: \"#d97706\",\n blocked: \"#ef4444\",\n frozen: \"#64748b\",\n active: \"#3b82f6\",\n};\nexport function catColor(status: string): string {\n return CAT_COLORS[category(status)];\n}\n\nconst STATUS_LABELS: Record<string, string> = {\n open: \"Open\",\n in_progress: \"In progress\",\n blocked: \"Blocked\",\n deferred: \"Deferred\",\n closed: \"Closed\",\n pinned: \"Pinned\",\n hooked: \"Hooked\",\n};\nexport function statusLabel(status: string): string {\n return STATUS_LABELS[status] ?? status;\n}\n\nconst PRIO_COLORS = [\"#ef4444\", \"#f97316\", \"#eab308\", \"#0ea5e9\", \"#64748b\"];\nconst PRIO_LABELS = [\"Critical\", \"High\", \"Medium\", \"Low\", \"Backlog\"];\nexport function prioColor(p: number): string {\n return PRIO_COLORS[p] ?? \"#64748b\";\n}\nexport function prioLabel(p: number): string {\n return PRIO_LABELS[p] ?? String(p);\n}\n\nexport function typeColor(t: string): string {\n if (t === \"epic\") return \"var(--brand)\";\n if (t === \"bug\") return \"#ef4444\";\n return \"var(--text-3)\";\n}\nexport function typeLabel(t: string): string {\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\n// Each is at least 4.5:1 against the white initials drawn on it (checked by the quality gate).\nconst AVATARS = [\n \"#5f50e6\",\n \"#0369a1\",\n \"#15803d\",\n \"#b45309\",\n \"#be185d\",\n \"#0e7490\",\n \"#6d28d9\",\n];\nexport function avatarColor(name: string): string {\n if (!name) return \"#6b7280\";\n let h = 0;\n for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;\n return AVATARS[h % AVATARS.length];\n}\nexport function initials(name: string): string {\n if (!name) return \"?\";\n const parts = name.split(/[-_ .]/).filter(Boolean);\n if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();\n return name.slice(0, 2).toUpperCase();\n}\n\n// ---- relationship helpers (need the full bead set for lookups) ----\n\nexport function makeIndex(beads: Bead[]): Map<string, Bead> {\n const m = new Map<string, Bead>();\n for (const b of beads) m.set(b.id, b);\n return m;\n}\n\nexport function isBlocked(b: Bead, index: Map<string, Bead>): boolean {\n if (b.status === \"blocked\") return true;\n if (b.status !== \"open\") return false;\n return blockingDeps(b, index).length > 0;\n}\n\n/**\n * The unresolved things actually holding this bead up — for naming blockers on a\n * card, so it must not name something the user doesn't experience as a blocker.\n *\n * `parent-child` is excluded even though bd counts it in BLOCKING_DEP_TYPES for\n * ready-queue purposes: the edge points from a child to its epic, so including\n * it makes every blocked child report its own parent epic alongside the real\n * blocker (\"blocked by <the epic it lives in>\"), which is noise at best and\n * misdirection at worst. Hierarchy is shown as hierarchy elsewhere.\n *\n * Shared by isBlocked so the badge, Focus column, and blocker names agree.\n */\nexport function blockingDeps(b: Bead, index: Map<string, Bead>): string[] {\n return (b.dependencies ?? [])\n .filter(\n (d) =>\n d.type !== \"parent-child\" &&\n BLOCKING_DEP_TYPES.includes(d.type as never) &&\n (index.get(d.depends_on_id)?.status ?? \"open\") !== \"closed\",\n )\n .map((d) => d.depends_on_id);\n}\n\n/**\n * The bead's parent, whatever its type. Resolved from the parent-child\n * dependency EDGE — never `bead.parent`, which `bd export --json` omits, so an\n * edge lookup is the only one correct on board/list data as well as in the\n * drawer.\n *\n * Replaces the former `epicOf`, which returned the same thing but was named as\n * though the parent were always an epic — so a task-parented bead rendered a\n * chip labelled \"epic\" and clicked through to the Epics screen, which renders\n * epics only. Callers now branch on `parent.issue_type` themselves.\n */\nexport function parentOf(b: Bead, index: Map<string, Bead>): Bead | null {\n const d = (b.dependencies ?? []).find((x) => x.type === \"parent-child\");\n return d ? index.get(d.depends_on_id) ?? null : null;\n}\n\n/**\n * Children per parent id, built in ONE pass over all beads. Callers render\n * per-card counts from this rather than calling childrenOf() per card, which\n * would be an O(n²) scan on a large board.\n */\nexport function childrenCountMap(beads: Bead[]): Map<string, number> {\n const m = new Map<string, number>();\n for (const b of beads) {\n for (const d of b.dependencies ?? []) {\n if (d.type === \"parent-child\") m.set(d.depends_on_id, (m.get(d.depends_on_id) ?? 0) + 1);\n }\n }\n return m;\n}\n\nexport function childrenOf(epicId: string, beads: Bead[]): Bead[] {\n return beads.filter((b) =>\n (b.dependencies ?? []).some(\n (d) => d.type === \"parent-child\" && d.depends_on_id === epicId,\n ),\n );\n}\n\nexport function epicProgress(\n epicId: string,\n beads: Bead[],\n): { closed: number; total: number; pct: number } {\n const kids = childrenOf(epicId, beads);\n const total = kids.length;\n const closed = kids.filter((k) => k.status === \"closed\").length;\n return { closed, total, pct: total ? Math.round((closed / total) * 100) : 0 };\n}\n\n// ---- relative time ----\n\nexport function relTime(iso?: string | null, now: Date = new Date()): string {\n if (!iso) return \"\";\n const d = (now.getTime() - new Date(iso).getTime()) / 1000;\n if (d < 60) return \"just now\";\n if (d < 3600) return `${Math.floor(d / 60)}m ago`;\n if (d < 86400) return `${Math.floor(d / 3600)}h ago`;\n if (d < 2592000) return `${Math.floor(d / 86400)}d ago`;\n return `${Math.floor(d / 2592000)}mo ago`;\n}\n\nexport function fmtDate(iso?: string | null): string {\n if (!iso) return \"\";\n return new Date(iso).toLocaleDateString(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n });\n}\n\n/** Full absolute timestamp, e.g. \"Jun 24, 2026, 2:15 PM\" — used as the hover\n * title behind relative times like \"3d ago\" (bead hl2). */\nexport function fmtDateTime(iso?: string | null): string {\n if (!iso) return \"\";\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return \"\";\n return d.toLocaleString(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n}\n"],"names":["needsHuman","b","labels","includes","status","isHumanGate","issue_type","await_type","readyHumanGate","index","isBlocked","gateBlocks","gateId","beads","filter","dependencies","some","d","depends_on_id","type","TASK_RE","checklistProgress","text","done","total","re","RegExp","m","exec","toLowerCase","toggleTask","i","replace","full","prefix","mark","closeReasonOf","reason","close_reason","trim","category","CAT_COLORS","wip","blocked","frozen","active","catColor","STATUS_LABELS","open","in_progress","deferred","closed","pinned","hooked","statusLabel","PRIO_COLORS","PRIO_LABELS","prioColor","p","prioLabel","String","typeColor","t","typeLabel","charAt","toUpperCase","slice","AVATARS","avatarColor","name","h","length","charCodeAt","initials","parts","split","Boolean","makeIndex","Map","set","id","blockingDeps","get","map","parentOf","find","x","childrenCountMap","childrenOf","epicId","epicProgress","kids","k","pct","Math","round","relTime","iso","now","Date","getTime","floor","fmtDate","toLocaleDateString","month","day","fmtDateTime","Number","isNaN","toLocaleString","year","hour","minute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,CAAc,EACxC,OAAO2C,CAAa,CAAC3C,EAAO,EAAIA,CAClC,QAgBO,SAAS2D,AAAUD,CAAS,EACjC,OAAOA,EAAEE,MAAM,CAAC,GAAGC,WAAW,GAAKH,EAAEI,KAAK,CAAC,EAC7C"}
@@ -1,3 +1,3 @@
1
- module.exports=[72507,e=>{"use strict";var t=e.i(2157),r=e.i(50227),n=e.i(60526),o=e.i(74533);let a={id:"demo",name:"Demo",path:null};class i extends Error{code;constructor(e,t){super(e),this.name="ConfigError",this.code=t}}let u="beadscope-viewer-mode";function l(){let e=process.env.XDG_CONFIG_HOME||r.default.join(n.default.homedir(),".config");return r.default.join(e,"beadscope")}function s(){return r.default.join(l(),"config.json")}function c(){try{return n.default.userInfo().username||"you"}catch{return"you"}}function d(e){try{return t.default.existsSync(r.default.join(e,".beads"))}catch{return!1}}function f(e){try{return t.default.realpathSync(e)}catch{return r.default.resolve(e)}}function p(e,t){let n=r.default.resolve(e),o=new Date().toISOString();return{id:function(e,t){let n=r.default.basename(e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project",o=n;for(;t.has(o)||o===a.id;)o=`${n}-${Math.random().toString(36).slice(2,6)}`;return o}(n,t),name:r.default.basename(n)||n,path:n,addedAt:o,lastOpened:o}}let h=null;function m(e){h=e;try{t.default.mkdirSync(l(),{recursive:!0});let r={};try{r=JSON.parse(t.default.readFileSync(s(),"utf8"))}catch{r={}}let n={...r,...e};t.default.writeFileSync(s(),JSON.stringify(n,null,2),"utf8")}catch{}}function A(){let e;if(h)return h;let n={humanActor:e=process.env.BEADS_ACTOR||function(){try{return(0,o.execFileSync)("git",["config","--get","user.name"],{cwd:process.cwd(),encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}()||c(),humanAllowlist:[e],pollIntervalMs:3e4,projects:[],orders:{},gamification:!1},i=null;try{i=JSON.parse(t.default.readFileSync(s(),"utf8"))}catch{i=null}let u=!i?.humanActorChosen&&i?.humanActor===c()&&n.humanActor!==i.humanActor,l=i?.humanAllowlist&&i.humanAllowlist.length?i.humanAllowlist:null,A={humanActor:u?n.humanActor:i?.humanActor||n.humanActor,humanAllowlist:l?u&&!l.includes(n.humanActor)?[...l,n.humanActor]:l:n.humanAllowlist,pollIntervalMs:"number"==typeof i?.pollIntervalMs?i.pollIntervalMs:n.pollIntervalMs,projects:function(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(o&&"object"==typeof o)"string"==typeof o.id&&"string"==typeof o.path&&(o.id===a.id||n.has(o.id)||(n.add(o.id),t.push({id:o.id,path:o.path,name:"string"==typeof o.name&&o.name?o.name:r.default.basename(o.path)||o.path,addedAt:"string"==typeof o.addedAt?o.addedAt:new Date().toISOString(),lastOpened:"string"==typeof o.lastOpened?o.lastOpened:new Date().toISOString()})))}return t}(i?.projects),orders:i?.orders&&"object"==typeof i.orders&&!Array.isArray(i.orders)?i.orders:{},gamification:"boolean"==typeof i?.gamification?i.gamification:n.gamification,humanActorChosen:i?.humanActorChosen===!0},g=!1;if(!i||void 0===i.projects){let e=i?.repoPath||process.env.BEADS_REPO||process.cwd();e&&d(e)&&!A.projects.some(t=>{var r;return r=t.path,f(r)===f(e)})&&(A.projects.push(p(e,new Set(A.projects.map(e=>e.id)))),g=!0)}return h=A,g&&m(A),h}e.s(["b",0,i,"U",0,a,"a",0,u,"X",0,function(e){let t=A(),n=r.default.resolve(e);if(!d(n))throw new i(`No .beads directory found in ${n}`,"no_beads");let o=t.projects.find(e=>{var t;return t=e.path,f(t)===f(n)});if(o)return o.lastOpened=new Date().toISOString(),m(t),o;let a=p(n,new Set(t.projects.map(e=>e.id)));return t.projects.push(a),m(t),a},"T",0,function(e){let{humanActor:t}=A();return e&&e!==t&&e===c()?e:t},"M",0,l,"d",0,function(e){return A().orders[e]??{}},"L",0,A,"e",0,function(e){return e===a.id?a:A().projects.find(t=>t.id===e)},"g",0,function(e){let t=e?.headers.get("cookie")?.split(";").map(e=>e.trim()).find(e=>e.startsWith(`${u}=`))?.slice(u.length+1);if("read-only"===t)return!0;if("editing"===t)return!1;let r=process.env.BEADSCOPE_READ_ONLY;return"1"===r||"true"===r},"A",0,function(){return process.env.BEADSCOPE_LANE_PREFIX||null},"W",0,function(){return A().projects},"s",0,function(e){let t=A();if(t.projects=t.projects.filter(t=>t.id!==e),t.orders[e]){let r={...t.orders};delete r[e],t.orders=r}m(t)},"Z",0,function(e,t){let r=A(),n=r.projects.find(t=>t.id===e);if(n)return n.name=t,m(r),n},"F",0,function(e){let t={...A(),...e};return void 0!==e.humanActor&&(t.humanActorChosen=!0),m(t),t},"v",0,function(e,t,r){let n=A(),o={...n.orders[e]??{}};return o[t]=r,n.orders={...n.orders,[e]:o},m(n),o},"$",0,function(e){let t=A(),r=t.projects.find(t=>t.id===e);r&&(r.lastOpened=new Date().toISOString(),m(t))}])}];
1
+ module.exports=[72507,e=>{"use strict";var t=e.i(2157),n=e.i(50227),r=e.i(60526),o=e.i(74533);let a=[{id:"claude-code",name:"claude-code",label:"Claude Code",color:"#d97757",enabled:!0},{id:"codex",name:"codex",label:"Codex",color:"#10a37f",enabled:!1},{id:"cursor",name:"cursor-agent",label:"Cursor",color:"#4b5563",enabled:!1},{id:"gemini",name:"gemini",label:"Gemini CLI",color:"#4285f4",enabled:!1},{id:"copilot",name:"copilot",label:"GitHub Copilot",color:"#8957e5",enabled:!1}],i=["🤖","🧠","⚡","🛠️","🚀","🦾","🔮","🛰️","🦉","🐙","🦊","🐱","🧪","🎯","🌟","🧩"],l=["#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#3b82f6","#8b5cf6","#ec4899"];function s(e){let t=new Map,n=[];if(Array.isArray(e))for(let n of e)n&&"object"==typeof n&&("string"!=typeof n.id||!n.id||t.has(n.id)||t.set(n.id,n));let r=(e,t)=>("string"==typeof e?.name?e.name.trim().slice(0,64):"")||t,o=a.map(e=>{let n=t.get(e.id);return{id:e.id,name:r(n,e.name),enabled:"boolean"==typeof n?.enabled?n.enabled:e.enabled}});for(let[e,o]of t){if(function(e){return a.find(t=>t.id===e)}(e)||!e.startsWith("custom-"))continue;let t=r(o,"");if(!t)continue;let s={id:e,name:t,enabled:!1!==o.enabled};"string"==typeof o.emoji&&i.includes(o.emoji)&&(s.emoji=o.emoji),"string"==typeof o.color&&l.includes(o.color)&&(s.color=o.color),n.push(s)}return[...o,...n]}l[5];let u={id:"demo",name:"Demo",path:null};class c extends Error{code;constructor(e,t){super(e),this.name="ConfigError",this.code=t}}let d="beadscope-viewer-mode";function f(){let e=process.env.XDG_CONFIG_HOME||n.default.join(r.default.homedir(),".config");return n.default.join(e,"beadscope")}function m(){return n.default.join(f(),"config.json")}function p(){try{return r.default.userInfo().username||"you"}catch{return"you"}}function h(e){try{let r=n.default.join(e,".beads");if(!t.default.existsSync(r))return!1;return!(t.default.existsSync(n.default.join(r,"machine-id"))&&!t.default.existsSync(n.default.join(r,"config.yaml"))&&!t.default.existsSync(n.default.join(r,"metadata.json")))}catch{return!1}}function g(e){try{return t.default.realpathSync(e)}catch{return n.default.resolve(e)}}function y(e,t){let r=n.default.resolve(e),o=new Date().toISOString();return{id:function(e,t){let r=n.default.basename(e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"project",o=r;for(;t.has(o)||o===u.id;)o=`${r}-${Math.random().toString(36).slice(2,6)}`;return o}(r,t),name:n.default.basename(r)||r,path:r,addedAt:o,lastOpened:o}}let A=Symbol.for("beadscope.config.cache");function b(e){globalThis[A]=e}function w(e){b(e);try{t.default.mkdirSync(f(),{recursive:!0});let n={};try{n=JSON.parse(t.default.readFileSync(m(),"utf8"))}catch{n={}}let r={...n,...e};t.default.writeFileSync(m(),JSON.stringify(r,null,2),"utf8")}catch{}}function S(){let e,r=globalThis[A]??null;if(r)return r;let i={humanActor:e=process.env.BEADS_ACTOR||function(){try{return(0,o.execFileSync)("git",["config","--get","user.name"],{cwd:process.cwd(),encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}()||p(),humanAllowlist:[e],agents:a.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),pollIntervalMs:3e4,projects:[],orders:{},gamification:!1},l=null;try{l=JSON.parse(t.default.readFileSync(m(),"utf8"))}catch{l=null}let c=!l?.humanActorChosen&&l?.humanActor===p()&&i.humanActor!==l.humanActor,d=l?.humanAllowlist&&l.humanAllowlist.length?l.humanAllowlist:null,f={humanActor:c?i.humanActor:l?.humanActor||i.humanActor,humanAllowlist:d?c&&!d.includes(i.humanActor)?[...d,i.humanActor]:d:i.humanAllowlist,agents:s(l?.agents),pollIntervalMs:"number"==typeof l?.pollIntervalMs?l.pollIntervalMs:i.pollIntervalMs,projects:function(e){if(!Array.isArray(e))return[];let t=[],r=new Set;for(let o of e){if(o&&"object"==typeof o)"string"==typeof o.id&&"string"==typeof o.path&&(o.id===u.id||r.has(o.id)||(r.add(o.id),t.push({id:o.id,path:o.path,name:"string"==typeof o.name&&o.name?o.name:n.default.basename(o.path)||o.path,addedAt:"string"==typeof o.addedAt?o.addedAt:new Date().toISOString(),lastOpened:"string"==typeof o.lastOpened?o.lastOpened:new Date().toISOString()})))}return t}(l?.projects),orders:l?.orders&&"object"==typeof l.orders&&!Array.isArray(l.orders)?l.orders:{},gamification:"boolean"==typeof l?.gamification?l.gamification:i.gamification,humanActorChosen:l?.humanActorChosen===!0},S=!1;if(!l||void 0===l.projects){let e=l?.repoPath||process.env.BEADS_REPO||process.cwd();e&&h(e)&&!f.projects.some(t=>{var n;return n=t.path,g(n)===g(e)})&&(f.projects.push(y(e,new Set(f.projects.map(e=>e.id)))),S=!0)}return b(f),S&&w(f),f}e.s(["b",0,c,"U",0,u,"a",0,d,"X",0,function(e){let t=S(),r=n.default.resolve(e);if(!h(r))throw new c(`No .beads directory found in ${r}`,"no_beads");let o=t.projects.find(e=>{var t;return t=e.path,g(t)===g(r)});if(o)return o.lastOpened=new Date().toISOString(),w(t),o;let a=y(r,new Set(t.projects.map(e=>e.id)));return t.projects.push(a),w(t),a},"T",0,function(e){let{humanActor:t}=S();return e&&e!==t&&e===p()?e:t},"M",0,f,"d",0,function(e){return S().orders[e]??{}},"L",0,S,"e",0,function(e){return e===u.id?u:S().projects.find(t=>t.id===e)},"v",0,h,"g",0,function(e){let t=e?.headers.get("cookie")?.split(";").map(e=>e.trim()).find(e=>e.startsWith(`${d}=`))?.slice(d.length+1);if("read-only"===t)return!0;if("editing"===t)return!1;let n=process.env.BEADSCOPE_READ_ONLY;return"1"===n||"true"===n},"A",0,function(){return process.env.BEADSCOPE_LANE_PREFIX||null},"W",0,function(){return S().projects},"s",0,function(e){let t=S();if(t.projects=t.projects.filter(t=>t.id!==e),t.orders[e]){let n={...t.orders};delete n[e],t.orders=n}w(t)},"Z",0,function(e,t){let n=S(),r=n.projects.find(t=>t.id===e);if(r)return r.name=t,w(n),r},"F",0,function(e){let t={...S(),...e};if(void 0!==e.humanActor&&(t.humanActorChosen=!0),void 0!==e.agents||void 0!==e.humanActor||void 0!==e.humanAllowlist){let n=function(e,t){let n=new Set,r=new Set(t.map(e=>e.trim().toLowerCase()).filter(Boolean));for(let t of e){let e=t.name.trim();if(!e)return"Every agent needs a name.";if(e.length>64)return"Agent names are at most 64 characters.";if(/[\u0000-\u001f\u007f]/.test(e))return"Agent names cannot contain control characters.";let o=e.toLowerCase();if(r.has(o))return`"${e}" is a human name (the human actor or allowlist); agents need their own.`;if(n.has(o))return`"${e}" is used twice. Agent names must be unique.`;n.add(o)}return null}(e.agents??t.agents,[t.humanActor,...t.humanAllowlist]);if(n)throw new c(n,"invalid_agents")}return void 0!==e.agents&&(t.agents=s(e.agents)),w(t),t},"w",0,function(e,t,n){let r=S(),o={...r.orders[e]??{}};return o[t]=n,r.orders={...r.orders,[e]:o},w(r),o},"$",0,function(e){let t=S(),n=t.projects.find(t=>t.id===e);n&&(n.lastOpened=new Date().toISOString(),w(t))}],72507)}];
2
2
 
3
3
  //# sourceMappingURL=lib_config_ts_0zrjxh_mm8sv8._.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../lib/config.ts"],"sourcesContent":["import \"server-only\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFileSync } from \"node:child_process\";\n\n/**\n * Local app config (NOT stored in beads). Lives as a small JSON file under the\n * OS config dir. Holds the human actor used to stamp writes, the human allowlist\n * for origin detection, the poll interval, and the registry of beads projects\n * the app knows about.\n *\n * Project identity is per-request (driven by the /p/<projectId> URL), so the\n * \"active\" project is NOT stored here — only the durable list of discovered ones.\n */\nexport interface ProjectEntry {\n id: string;\n name: string;\n path: string;\n /** ISO timestamps. */\n addedAt: string;\n lastOpened: string;\n}\n\nexport interface AppConfig {\n humanActor: string;\n humanAllowlist: string[];\n pollIntervalMs: number;\n projects: ProjectEntry[];\n /**\n * Manual board ordering, kept app-local (NOT in beads): projectId → columnId →\n * ordered bead ids. Lets users drag beads within a column to set work order.\n */\n orders: Record<string, Record<string, string[]>>;\n /** Opt-in: show the gamification XP/level layer (off by default). */\n gamification: boolean;\n /**\n * True once the human actor was saved from Settings. Until then the actor\n * follows the computed default, even if an older version wrote it to disk.\n */\n humanActorChosen?: boolean;\n}\n\n/**\n * The built-in demo dataset, surfaced as an always-available pseudo-project.\n * It has no filesystem path; the store resolver maps it to the in-memory store.\n */\nexport const DEMO_PROJECT = {\n id: \"demo\",\n name: \"Demo\",\n path: null,\n} as const;\nexport type DemoProject = typeof DEMO_PROJECT;\n\nexport class ConfigError extends Error {\n code: string;\n constructor(message: string, code: string) {\n super(message);\n this.name = \"ConfigError\";\n this.code = code;\n }\n}\n\n/**\n * BEADSCOPE_READ_ONLY=1 (or \"true\") supplies the default for new browser sessions.\n * The session cookie overrides that default when the user changes the mode.\n * In the effective read-only mode, project writes are refused server-side and\n * editing controls are disabled. App settings remain available.\n */\nexport const VIEWER_MODE_COOKIE = \"beadscope-viewer-mode\";\n\nexport function isReadOnly(request?: Request): boolean {\n // This is a browser preference, not an authorization boundary. A session\n // cookie lets one browser override the launch default without affecting others.\n const cookie = request?.headers.get(\"cookie\")?.split(\";\").map((v) => v.trim())\n .find((v) => v.startsWith(`${VIEWER_MODE_COOKIE}=`))?.slice(VIEWER_MODE_COOKIE.length + 1);\n if (cookie === \"read-only\") return true;\n if (cookie === \"editing\") return false;\n const v = process.env.BEADSCOPE_READ_ONLY;\n return v === \"1\" || v === \"true\";\n}\n\n/**\n * Focus-view lane chips: BEADSCOPE_LANE_PREFIX names a label prefix (e.g. \"ctx:\")\n * whose values partition work into lanes/teams/areas. When set, the Focus view\n * offers one filter chip per lane label found on the visible beads. Unset →\n * no chips (the feature is invisible).\n */\nexport function lanePrefix(): string | null {\n return process.env.BEADSCOPE_LANE_PREFIX || null;\n}\n\nexport function configDir(): string {\n const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), \".config\");\n return path.join(base, \"beadscope\");\n}\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nfunction osUserName(): string {\n try {\n return os.userInfo().username || \"you\";\n } catch {\n return \"you\";\n }\n}\n\n/** git's user.name as seen from the launch directory, or null without git or a name. */\nfunction gitUserName(): string | null {\n try {\n const name = execFileSync(\"git\", [\"config\", \"--get\", \"user.name\"], {\n cwd: process.cwd(),\n encoding: \"utf8\",\n timeout: 2000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return name || null;\n } catch {\n return null;\n }\n}\n\nfunction defaults(): AppConfig {\n // Same order as bd's own actor (`bd --help`, --actor): BEADS_ACTOR, then git\n // user.name, then the OS user. If Beadscope stamped writes with the OS name\n // while `bd update --claim` used the git name, bd would refuse to let the UI\n // close beads the user claimed from the CLI.\n const humanActor = process.env.BEADS_ACTOR || gitUserName() || osUserName();\n return {\n humanActor,\n humanAllowlist: [humanActor],\n // Fallback refresh interval. The SSE change stream (see lib/beads-watch)\n // drives fast updates; this interval only backstops a dropped stream.\n pollIntervalMs: 30000,\n projects: [],\n orders: {},\n gamification: false,\n };\n}\n\n// ---- helpers -------------------------------------------------------------\n\nfunction hasBeads(p: string): boolean {\n try {\n return fs.existsSync(path.join(p, \".beads\"));\n } catch {\n return false;\n }\n}\nfunction realpathOrSelf(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return path.resolve(p);\n }\n}\nfunction sameDir(a: string, b: string): boolean {\n return realpathOrSelf(a) === realpathOrSelf(b);\n}\nfunction slug(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"project\"\n );\n}\nfunction makeId(absPath: string, taken: Set<string>): string {\n const base = slug(path.basename(absPath));\n let id = base;\n while (taken.has(id) || id === DEMO_PROJECT.id) {\n id = `${base}-${Math.random().toString(36).slice(2, 6)}`;\n }\n return id;\n}\nfunction makeEntry(inputPath: string, taken: Set<string>): ProjectEntry {\n const abs = path.resolve(inputPath);\n const now = new Date().toISOString();\n return {\n id: makeId(abs, taken),\n name: path.basename(abs) || abs,\n path: abs,\n addedAt: now,\n lastOpened: now,\n };\n}\n\n/** Drop malformed registry entries so a bad config file never crashes startup. */\nfunction sanitizeProjects(input: unknown): ProjectEntry[] {\n if (!Array.isArray(input)) return [];\n const out: ProjectEntry[] = [];\n const seen = new Set<string>();\n for (const it of input) {\n if (!it || typeof it !== \"object\") continue;\n const e = it as Record<string, unknown>;\n if (typeof e.id !== \"string\" || typeof e.path !== \"string\") continue;\n if (e.id === DEMO_PROJECT.id || seen.has(e.id)) continue;\n seen.add(e.id);\n out.push({\n id: e.id,\n path: e.path,\n name: typeof e.name === \"string\" && e.name ? e.name : path.basename(e.path) || e.path,\n addedAt: typeof e.addedAt === \"string\" ? e.addedAt : new Date().toISOString(),\n lastOpened: typeof e.lastOpened === \"string\" ? e.lastOpened : new Date().toISOString(),\n });\n }\n return out;\n}\n\n// ---- load / persist ------------------------------------------------------\n\nlet cached: AppConfig | null = null;\n\n/**\n * Persist the config, preserving any unknown keys already on disk (e.g. the\n * legacy `repoPath`/`demo` fields) so older app versions can still read them.\n */\nfunction persist(cfg: AppConfig): void {\n cached = cfg;\n try {\n fs.mkdirSync(configDir(), { recursive: true });\n let base: Record<string, unknown> = {};\n try {\n base = JSON.parse(fs.readFileSync(configFile(), \"utf8\")) as Record<string, unknown>;\n } catch {\n base = {};\n }\n const next = { ...base, ...cfg };\n fs.writeFileSync(configFile(), JSON.stringify(next, null, 2), \"utf8\");\n } catch {\n /* best-effort; config still applies for the session */\n }\n}\n\nexport function getConfig(): AppConfig {\n if (cached) return cached;\n const d = defaults();\n\n let onDisk:\n | (Partial<AppConfig> & { repoPath?: string; demo?: boolean })\n | null = null;\n try {\n onDisk = JSON.parse(fs.readFileSync(configFile(), \"utf8\"));\n } catch {\n onDisk = null;\n }\n\n // Before 0.3.1 the computed default (the OS user) was written to disk along\n // with the first project, so an unchosen OS username on disk is a stale\n // default rather than a preference. Replace it, and keep the new actor in the\n // allowlist so the user's own writes still render as human.\n const staleActor =\n !onDisk?.humanActorChosen && onDisk?.humanActor === osUserName() && d.humanActor !== onDisk.humanActor;\n const storedAllowlist = onDisk?.humanAllowlist && onDisk.humanAllowlist.length ? onDisk.humanAllowlist : null;\n const merged: AppConfig = {\n humanActor: staleActor ? d.humanActor : onDisk?.humanActor || d.humanActor,\n humanAllowlist: !storedAllowlist\n ? d.humanAllowlist\n : staleActor && !storedAllowlist.includes(d.humanActor)\n ? [...storedAllowlist, d.humanActor]\n : storedAllowlist,\n pollIntervalMs:\n typeof onDisk?.pollIntervalMs === \"number\" ? onDisk.pollIntervalMs : d.pollIntervalMs,\n projects: sanitizeProjects(onDisk?.projects),\n orders:\n onDisk?.orders && typeof onDisk.orders === \"object\" && !Array.isArray(onDisk.orders)\n ? (onDisk.orders as Record<string, Record<string, string[]>>)\n : {},\n gamification: typeof onDisk?.gamification === \"boolean\" ? onDisk.gamification : d.gamification,\n humanActorChosen: onDisk?.humanActorChosen === true,\n };\n\n // One-time migration: back-fill the registry from the legacy single repoPath\n // (or BEADS_REPO / cwd) when no projects array exists yet.\n let migrated = false;\n if (!onDisk || onDisk.projects === undefined) {\n const legacyPath = onDisk?.repoPath || process.env.BEADS_REPO || process.cwd();\n if (\n legacyPath &&\n hasBeads(legacyPath) &&\n !merged.projects.some((p) => sameDir(p.path, legacyPath))\n ) {\n merged.projects.push(makeEntry(legacyPath, new Set(merged.projects.map((p) => p.id))));\n migrated = true;\n }\n }\n\n cached = merged;\n // Persist the migrated entry so its id is stable across restarts.\n if (migrated) persist(merged);\n return cached;\n}\n\n/**\n * The actor to close a bead as. bd refuses to close a claimed bead as anyone\n * but its assignee. Before 0.3.1 Beadscope wrote as the OS user, so beads people\n * assigned to themselves then still carry that name. It is the same person on\n * this machine, so close those as it rather than failing — #61 in reverse.\n * Every other assignee (a teammate, an agent) keeps bd's protection.\n */\nexport function closeActor(assignee: string | null | undefined): string {\n const { humanActor } = getConfig();\n return assignee && assignee !== humanActor && assignee === osUserName() ? assignee : humanActor;\n}\n\n/** Update global settings (actor / allowlist / poll). Project registry has its own mutators. */\nexport function saveConfig(\n patch: Partial<Pick<AppConfig, \"humanActor\" | \"humanAllowlist\" | \"pollIntervalMs\" | \"gamification\">>,\n): AppConfig {\n const next = { ...getConfig(), ...patch };\n if (patch.humanActor !== undefined) next.humanActorChosen = true;\n persist(next);\n return next;\n}\n\n// ---- project registry ----------------------------------------------------\n\nexport function listProjects(): ProjectEntry[] {\n return getConfig().projects;\n}\n\nexport function getProject(id: string): ProjectEntry | DemoProject | undefined {\n if (id === DEMO_PROJECT.id) return DEMO_PROJECT;\n return getConfig().projects.find((p) => p.id === id);\n}\n\n/** Add (or re-touch) a project by folder path. Validates a `.beads` dir exists. */\nexport function addProject(inputPath: string): ProjectEntry {\n const cfg = getConfig();\n const abs = path.resolve(inputPath);\n if (!hasBeads(abs)) {\n throw new ConfigError(`No .beads directory found in ${abs}`, \"no_beads\");\n }\n const existing = cfg.projects.find((p) => sameDir(p.path, abs));\n if (existing) {\n existing.lastOpened = new Date().toISOString();\n persist(cfg);\n return existing;\n }\n const entry = makeEntry(abs, new Set(cfg.projects.map((p) => p.id)));\n cfg.projects.push(entry);\n persist(cfg);\n return entry;\n}\n\nexport function removeProject(id: string): void {\n const cfg = getConfig();\n cfg.projects = cfg.projects.filter((p) => p.id !== id);\n // Drop any saved board ordering for the removed project so it can't orphan.\n if (cfg.orders[id]) {\n const rest = { ...cfg.orders };\n delete rest[id];\n cfg.orders = rest;\n }\n persist(cfg);\n}\n\nexport function touchProject(id: string): void {\n const cfg = getConfig();\n const p = cfg.projects.find((x) => x.id === id);\n if (p) {\n p.lastOpened = new Date().toISOString();\n persist(cfg);\n }\n}\n\nexport function renameProject(id: string, name: string): ProjectEntry | undefined {\n const cfg = getConfig();\n const p = cfg.projects.find((x) => x.id === id);\n if (!p) return undefined;\n p.name = name;\n persist(cfg);\n return p;\n}\n\n// ---- manual board ordering ------------------------------------------------\n\n/** All saved column orders for a project: columnId → ordered bead ids. */\nexport function getColumnOrders(projectId: string): Record<string, string[]> {\n return getConfig().orders[projectId] ?? {};\n}\n\n/** Replace the saved order for one column of one project. */\nexport function setColumnOrder(\n projectId: string,\n columnId: string,\n ids: string[],\n): Record<string, string[]> {\n const cfg = getConfig();\n const proj = { ...(cfg.orders[projectId] ?? {}) };\n proj[columnId] = ids;\n cfg.orders = { ...cfg.orders, [projectId]: proj };\n persist(cfg);\n return proj;\n}\n"],"names":["DEMO_PROJECT","id","name","path","ConfigError","Error","code","message","VIEWER_MODE_COOKIE","isReadOnly","request","cookie","headers","get","split","map","v","trim","find","startsWith","slice","length","process","env","BEADSCOPE_READ_ONLY","lanePrefix","BEADSCOPE_LANE_PREFIX","configDir","base","XDG_CONFIG_HOME","join","homedir","configFile","osUserName","userInfo","username","gitUserName","cwd","encoding","timeout","stdio","defaults","humanActor","BEADS_ACTOR","humanAllowlist","pollIntervalMs","projects","orders","gamification","hasBeads","p","existsSync","realpathOrSelf","realpathSync","resolve","sameDir","a","b","slug","s","toLowerCase","replace","makeId","absPath","taken","basename","has","Math","random","toString","makeEntry","inputPath","abs","now","Date","toISOString","addedAt","lastOpened","sanitizeProjects","input","Array","isArray","out","seen","Set","it","e","add","push","cached","persist","cfg","mkdirSync","recursive","JSON","parse","readFileSync","next","writeFileSync","stringify","getConfig","d","onDisk","staleActor","humanActorChosen","storedAllowlist","merged","includes","migrated","undefined","legacyPath","repoPath","BEADS_REPO","some","closeActor","assignee","saveConfig","patch","listProjects","getProject","addProject","existing","entry","removeProject","filter","rest","touchProject","x","renameProject","getColumnOrders","projectId","setColumnOrder","columnId","ids","proj"],"mappings":"uCACA,IAAA,EAAA,EAAA,CAAA,CAAA,MACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OA2CO,IAAMA,EAAe,CAC1BC,GAAI,OACJC,KAAM,OACNC,KAAM,IACR,CAGO,OAAMC,UAAoBC,MAC/BC,IAAa,AACbF,aAAYG,CAAe,CAAED,CAAY,CAAE,CACzC,KAAK,CAACC,GACN,IAAI,CAACL,IAAI,CAAG,cACZ,IAAI,CAACI,IAAI,CAAGA,CACd,CACF,CAQO,IAAME,EAAqB,wBAuB3B,SAASmB,IACd,IAAMC,EAAON,QAAQC,GAAG,CAACM,eAAe,EAAI,EAAA,OAAI,CAACC,IAAI,CAAC,EAAA,OAAE,CAACC,OAAO,GAAI,WACpE,OAAO,EAAA,OAAI,CAACD,IAAI,CAACF,EAAM,YACzB,CACA,SAASI,IACP,OAAO,EAAA,OAAI,CAACF,IAAI,CAACH,IAAa,cAChC,CAEA,SAASM,IACP,GAAI,CACF,OAAO,EAAA,OAAE,CAACC,QAAQ,GAAGC,QAAQ,EAAI,KACnC,CAAE,KAAM,CACN,MAAO,KACT,CACF,CAqCA,SAASc,EAASC,CAAS,EACzB,GAAI,CACF,OAAO,EAAA,OAAE,CAACC,UAAU,CAAC,EAAA,OAAI,CAACrB,IAAI,CAACoB,EAAG,UACpC,CAAE,KAAM,CACN,OAAO,CACT,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AAMS,IACNlD,EAAIyC,EAAI7C,QAAQ,CAAC5B,IAAI,CAAC,AAAC6G,GAAMA,EAAE9H,EAAE,GAAKA,GAC5C,GAAKiD,CAAD,CAGJ,CAHQ,MACRA,CADe2D,CACb3G,IAAI,CAAGA,EACTwF,EAAQC,GACDzC,CACT,QAnEO,SAASkE,AACdC,CAAoG,EAEpG,IAAMpB,EAAO,CAAE,GAAGG,GAAW,CAAE,GAAGiB,CAAK,AAAC,EAGxC,YAFyBR,IAArBQ,EAAM3E,UAAU,EAAgBuD,GAAKO,gBAAgB,EAAG,CAAA,EAC5Dd,EAAQO,GACDA,CACT,QAsEO,SAASkC,AACdD,CAAiB,CACjBE,CAAgB,CAChBC,CAAa,EAEb,IAAM1C,EAAMS,IACNkC,EAAO,CAAE,GAAI3C,EAAI5C,MAAM,CAACmF,EAAU,EAAI,CAAC,CAAC,AAAE,EAIhD,OAHAI,CAAI,CAACF,EAAS,CAAGC,EACjB1C,EAAI5C,MAAM,CAAG,CAAE,GAAG4C,EAAI5C,MAAM,CAAE,CAACmF,EAAU,CAAEI,CAAK,EAChD5C,EAAQC,GACD2C,CACT,QArCO,SAASR,AAAa7H,CAAU,EACrC,IAAM0F,EAAMS,IACNlD,EAAIyC,EAAI7C,QAAQ,CAAC5B,IAAI,CAAC,AAAC6G,GAAMA,EAAE9H,EAAE,GAAKA,GACxCiD,GAAG,CACLA,EAAE2B,UAAU,CAAG,IAAIH,OAAOC,WAAW,GACrCe,EAAQC,GAEZ"}
1
+ {"version":3,"sources":["../../../lib/config.ts","../../../lib/agents.ts"],"sourcesContent":["import \"server-only\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFileSync } from \"node:child_process\";\nimport { defaultAgents, normalizeAgents, validateAgents, type AgentIdentity } from \"./agents.ts\";\n\n/**\n * Local app config (NOT stored in beads). Lives as a small JSON file under the\n * OS config dir. Holds the human actor used to stamp writes, the human allowlist\n * for origin detection, the poll interval, and the registry of beads projects\n * the app knows about.\n *\n * Project identity is per-request (driven by the /p/<projectId> URL), so the\n * \"active\" project is NOT stored here — only the durable list of discovered ones.\n */\nexport interface ProjectEntry {\n id: string;\n name: string;\n path: string;\n /** ISO timestamps. */\n addedAt: string;\n lastOpened: string;\n}\n\nexport interface AppConfig {\n humanActor: string;\n humanAllowlist: string[];\n /** Agent identities (the assignee picker choices); see lib/agents.ts. */\n agents: AgentIdentity[];\n pollIntervalMs: number;\n projects: ProjectEntry[];\n /**\n * Manual board ordering, kept app-local (NOT in beads): projectId → columnId →\n * ordered bead ids. Lets users drag beads within a column to set work order.\n */\n orders: Record<string, Record<string, string[]>>;\n /** Opt-in: show the gamification XP/level layer (off by default). */\n gamification: boolean;\n /**\n * True once the human actor was saved from Settings. Until then the actor\n * follows the computed default, even if an older version wrote it to disk.\n */\n humanActorChosen?: boolean;\n}\n\n/**\n * The built-in demo dataset, surfaced as an always-available pseudo-project.\n * It has no filesystem path; the store resolver maps it to the in-memory store.\n */\nexport const DEMO_PROJECT = {\n id: \"demo\",\n name: \"Demo\",\n path: null,\n} as const;\nexport type DemoProject = typeof DEMO_PROJECT;\n\nexport class ConfigError extends Error {\n code: string;\n constructor(message: string, code: string) {\n super(message);\n this.name = \"ConfigError\";\n this.code = code;\n }\n}\n\n/**\n * BEADSCOPE_READ_ONLY=1 (or \"true\") supplies the default for new browser sessions.\n * The session cookie overrides that default when the user changes the mode.\n * In the effective read-only mode, project writes are refused server-side and\n * editing controls are disabled. App settings remain available.\n */\nexport const VIEWER_MODE_COOKIE = \"beadscope-viewer-mode\";\n\nexport function isReadOnly(request?: Request): boolean {\n // This is a browser preference, not an authorization boundary. A session\n // cookie lets one browser override the launch default without affecting others.\n const cookie = request?.headers.get(\"cookie\")?.split(\";\").map((v) => v.trim())\n .find((v) => v.startsWith(`${VIEWER_MODE_COOKIE}=`))?.slice(VIEWER_MODE_COOKIE.length + 1);\n if (cookie === \"read-only\") return true;\n if (cookie === \"editing\") return false;\n const v = process.env.BEADSCOPE_READ_ONLY;\n return v === \"1\" || v === \"true\";\n}\n\n/**\n * Focus-view lane chips: BEADSCOPE_LANE_PREFIX names a label prefix (e.g. \"ctx:\")\n * whose values partition work into lanes/teams/areas. When set, the Focus view\n * offers one filter chip per lane label found on the visible beads. Unset →\n * no chips (the feature is invisible).\n */\nexport function lanePrefix(): string | null {\n return process.env.BEADSCOPE_LANE_PREFIX || null;\n}\n\nexport function configDir(): string {\n const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), \".config\");\n return path.join(base, \"beadscope\");\n}\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nfunction osUserName(): string {\n try {\n return os.userInfo().username || \"you\";\n } catch {\n return \"you\";\n }\n}\n\n/** git's user.name as seen from the launch directory, or null without git or a name. */\nfunction gitUserName(): string | null {\n try {\n const name = execFileSync(\"git\", [\"config\", \"--get\", \"user.name\"], {\n cwd: process.cwd(),\n encoding: \"utf8\",\n timeout: 2000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return name || null;\n } catch {\n return null;\n }\n}\n\nfunction defaults(): AppConfig {\n // Same order as bd's own actor (`bd --help`, --actor): BEADS_ACTOR, then git\n // user.name, then the OS user. If Beadscope stamped writes with the OS name\n // while `bd update --claim` used the git name, bd would refuse to let the UI\n // close beads the user claimed from the CLI.\n const humanActor = process.env.BEADS_ACTOR || gitUserName() || osUserName();\n return {\n humanActor,\n humanAllowlist: [humanActor],\n agents: defaultAgents(),\n // Fallback refresh interval. The SSE change stream (see lib/beads-watch)\n // drives fast updates; this interval only backstops a dropped stream.\n pollIntervalMs: 30000,\n projects: [],\n orders: {},\n gamification: false,\n };\n}\n\n// ---- helpers -------------------------------------------------------------\n\n/**\n * Whether `p` holds a beads workspace. bd also keeps per-user state (a machine-id\n * and an event queue) in `~/.beads`; that folder is not a workspace, so it must not\n * make the home directory look like a project. A workspace has a config.yaml or\n * metadata.json next to its database.\n */\nexport function hasBeads(p: string): boolean {\n try {\n const dir = path.join(p, \".beads\");\n if (!fs.existsSync(dir)) return false;\n const isUserStateDir =\n fs.existsSync(path.join(dir, \"machine-id\")) &&\n !fs.existsSync(path.join(dir, \"config.yaml\")) &&\n !fs.existsSync(path.join(dir, \"metadata.json\"));\n return !isUserStateDir;\n } catch {\n return false;\n }\n}\nfunction realpathOrSelf(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return path.resolve(p);\n }\n}\nfunction sameDir(a: string, b: string): boolean {\n return realpathOrSelf(a) === realpathOrSelf(b);\n}\nfunction slug(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"project\"\n );\n}\nfunction makeId(absPath: string, taken: Set<string>): string {\n const base = slug(path.basename(absPath));\n let id = base;\n while (taken.has(id) || id === DEMO_PROJECT.id) {\n id = `${base}-${Math.random().toString(36).slice(2, 6)}`;\n }\n return id;\n}\nfunction makeEntry(inputPath: string, taken: Set<string>): ProjectEntry {\n const abs = path.resolve(inputPath);\n const now = new Date().toISOString();\n return {\n id: makeId(abs, taken),\n name: path.basename(abs) || abs,\n path: abs,\n addedAt: now,\n lastOpened: now,\n };\n}\n\n/** Drop malformed registry entries so a bad config file never crashes startup. */\nfunction sanitizeProjects(input: unknown): ProjectEntry[] {\n if (!Array.isArray(input)) return [];\n const out: ProjectEntry[] = [];\n const seen = new Set<string>();\n for (const it of input) {\n if (!it || typeof it !== \"object\") continue;\n const e = it as Record<string, unknown>;\n if (typeof e.id !== \"string\" || typeof e.path !== \"string\") continue;\n if (e.id === DEMO_PROJECT.id || seen.has(e.id)) continue;\n seen.add(e.id);\n out.push({\n id: e.id,\n path: e.path,\n name: typeof e.name === \"string\" && e.name ? e.name : path.basename(e.path) || e.path,\n addedAt: typeof e.addedAt === \"string\" ? e.addedAt : new Date().toISOString(),\n lastOpened: typeof e.lastOpened === \"string\" ? e.lastOpened : new Date().toISOString(),\n });\n }\n return out;\n}\n\n// ---- load / persist ------------------------------------------------------\n\n// Keyed off globalThis, not module scope: the page renderer (generateMetadata) and the API route\n// handlers are separate bundles with their own copy of this module, so a module-level cache would\n// leave the page showing the old project name after a rename.\nconst CACHE_KEY = Symbol.for(\"beadscope.config.cache\");\ntype CacheHolder = Record<symbol, AppConfig | null | undefined>;\nfunction readCache(): AppConfig | null {\n return (globalThis as unknown as CacheHolder)[CACHE_KEY] ?? null;\n}\nfunction writeCache(cfg: AppConfig | null): void {\n (globalThis as unknown as CacheHolder)[CACHE_KEY] = cfg;\n}\n\n/**\n * Persist the config, preserving any unknown keys already on disk (e.g. the\n * legacy `repoPath`/`demo` fields) so older app versions can still read them.\n */\nfunction persist(cfg: AppConfig): void {\n writeCache(cfg);\n try {\n fs.mkdirSync(configDir(), { recursive: true });\n let base: Record<string, unknown> = {};\n try {\n base = JSON.parse(fs.readFileSync(configFile(), \"utf8\")) as Record<string, unknown>;\n } catch {\n base = {};\n }\n const next = { ...base, ...cfg };\n fs.writeFileSync(configFile(), JSON.stringify(next, null, 2), \"utf8\");\n } catch {\n /* best-effort; config still applies for the session */\n }\n}\n\nexport function getConfig(): AppConfig {\n const hit = readCache();\n if (hit) return hit;\n const d = defaults();\n\n let onDisk:\n | (Partial<AppConfig> & { repoPath?: string; demo?: boolean })\n | null = null;\n try {\n onDisk = JSON.parse(fs.readFileSync(configFile(), \"utf8\"));\n } catch {\n onDisk = null;\n }\n\n // Before 0.3.1 the computed default (the OS user) was written to disk along\n // with the first project, so an unchosen OS username on disk is a stale\n // default rather than a preference. Replace it, and keep the new actor in the\n // allowlist so the user's own writes still render as human.\n const staleActor =\n !onDisk?.humanActorChosen && onDisk?.humanActor === osUserName() && d.humanActor !== onDisk.humanActor;\n const storedAllowlist = onDisk?.humanAllowlist && onDisk.humanAllowlist.length ? onDisk.humanAllowlist : null;\n const merged: AppConfig = {\n humanActor: staleActor ? d.humanActor : onDisk?.humanActor || d.humanActor,\n humanAllowlist: !storedAllowlist\n ? d.humanAllowlist\n : staleActor && !storedAllowlist.includes(d.humanActor)\n ? [...storedAllowlist, d.humanActor]\n : storedAllowlist,\n agents: normalizeAgents(onDisk?.agents),\n pollIntervalMs:\n typeof onDisk?.pollIntervalMs === \"number\" ? onDisk.pollIntervalMs : d.pollIntervalMs,\n projects: sanitizeProjects(onDisk?.projects),\n orders:\n onDisk?.orders && typeof onDisk.orders === \"object\" && !Array.isArray(onDisk.orders)\n ? (onDisk.orders as Record<string, Record<string, string[]>>)\n : {},\n gamification: typeof onDisk?.gamification === \"boolean\" ? onDisk.gamification : d.gamification,\n humanActorChosen: onDisk?.humanActorChosen === true,\n };\n\n // One-time migration: back-fill the registry from the legacy single repoPath\n // (or BEADS_REPO / cwd) when no projects array exists yet.\n let migrated = false;\n if (!onDisk || onDisk.projects === undefined) {\n const legacyPath = onDisk?.repoPath || process.env.BEADS_REPO || process.cwd();\n if (\n legacyPath &&\n hasBeads(legacyPath) &&\n !merged.projects.some((p) => sameDir(p.path, legacyPath))\n ) {\n merged.projects.push(makeEntry(legacyPath, new Set(merged.projects.map((p) => p.id))));\n migrated = true;\n }\n }\n\n writeCache(merged);\n // Persist the migrated entry so its id is stable across restarts.\n if (migrated) persist(merged);\n return merged;\n}\n\n/**\n * The actor to close a bead as. bd refuses to close a claimed bead as anyone\n * but its assignee. Before 0.3.1 Beadscope wrote as the OS user, so beads people\n * assigned to themselves then still carry that name. It is the same person on\n * this machine, so close those as it rather than failing — #61 in reverse.\n * Every other assignee (a teammate, an agent) keeps bd's protection.\n */\nexport function closeActor(assignee: string | null | undefined): string {\n const { humanActor } = getConfig();\n return assignee && assignee !== humanActor && assignee === osUserName() ? assignee : humanActor;\n}\n\n/** Update global settings (actor / allowlist / poll). Project registry has its own mutators. */\nexport function saveConfig(\n patch: Partial<Pick<AppConfig, \"humanActor\" | \"humanAllowlist\" | \"agents\" | \"pollIntervalMs\" | \"gamification\">>,\n): AppConfig {\n const current = getConfig();\n const next = { ...current, ...patch };\n if (patch.humanActor !== undefined) next.humanActorChosen = true;\n // Check the names as sent (before normalizing quietly repairs an empty one), against\n // the humans being saved, so an agent cannot take a human name.\n if (patch.agents !== undefined || patch.humanActor !== undefined || patch.humanAllowlist !== undefined) {\n const problem = validateAgents(patch.agents ?? next.agents, [next.humanActor, ...next.humanAllowlist]);\n if (problem) throw new ConfigError(problem, \"invalid_agents\");\n }\n if (patch.agents !== undefined) next.agents = normalizeAgents(patch.agents);\n persist(next);\n return next;\n}\n\n// ---- project registry ----------------------------------------------------\n\nexport function listProjects(): ProjectEntry[] {\n return getConfig().projects;\n}\n\nexport function getProject(id: string): ProjectEntry | DemoProject | undefined {\n if (id === DEMO_PROJECT.id) return DEMO_PROJECT;\n return getConfig().projects.find((p) => p.id === id);\n}\n\n/** Add (or re-touch) a project by folder path. Validates a `.beads` dir exists. */\nexport function addProject(inputPath: string): ProjectEntry {\n const cfg = getConfig();\n const abs = path.resolve(inputPath);\n if (!hasBeads(abs)) {\n throw new ConfigError(`No .beads directory found in ${abs}`, \"no_beads\");\n }\n const existing = cfg.projects.find((p) => sameDir(p.path, abs));\n if (existing) {\n existing.lastOpened = new Date().toISOString();\n persist(cfg);\n return existing;\n }\n const entry = makeEntry(abs, new Set(cfg.projects.map((p) => p.id)));\n cfg.projects.push(entry);\n persist(cfg);\n return entry;\n}\n\nexport function removeProject(id: string): void {\n const cfg = getConfig();\n cfg.projects = cfg.projects.filter((p) => p.id !== id);\n // Drop any saved board ordering for the removed project so it can't orphan.\n if (cfg.orders[id]) {\n const rest = { ...cfg.orders };\n delete rest[id];\n cfg.orders = rest;\n }\n persist(cfg);\n}\n\nexport function touchProject(id: string): void {\n const cfg = getConfig();\n const p = cfg.projects.find((x) => x.id === id);\n if (p) {\n p.lastOpened = new Date().toISOString();\n persist(cfg);\n }\n}\n\nexport function renameProject(id: string, name: string): ProjectEntry | undefined {\n const cfg = getConfig();\n const p = cfg.projects.find((x) => x.id === id);\n if (!p) return undefined;\n p.name = name;\n persist(cfg);\n return p;\n}\n\n// ---- manual board ordering ------------------------------------------------\n\n/** All saved column orders for a project: columnId → ordered bead ids. */\nexport function getColumnOrders(projectId: string): Record<string, string[]> {\n return getConfig().orders[projectId] ?? {};\n}\n\n/** Replace the saved order for one column of one project. */\nexport function setColumnOrder(\n projectId: string,\n columnId: string,\n ids: string[],\n): Record<string, string[]> {\n const cfg = getConfig();\n const proj = { ...(cfg.orders[projectId] ?? {}) };\n proj[columnId] = ids;\n cfg.orders = { ...cfg.orders, [projectId]: proj };\n persist(cfg);\n return proj;\n}\n","/**\n * Agent identities: the names an AI agent works under (the `bd` actor string),\n * managed in Settings. Shared by the server (config) and the UI, so this file\n * must not import anything server-only.\n *\n * An identity only labels and offers a name. `bd` stores the plain string in\n * `assignee` / `created_by`; Beadscope already treats any name that is not on the\n * human allowlist as an agent (lib/attribution.ts), so identities do not change\n * that rule. They give the assignee picker its choices and give those names an icon.\n */\n\n/** What is stored in config.json. */\nexport interface AgentIdentity {\n /**\n * Stable key. Renaming an identity changes `name`, never `id`. Pre-defined\n * identities use their preset key (\"claude-code\"); user-added ones \"custom-…\".\n */\n id: string;\n /** The actor name: what `bd` records as the assignee. Editable. */\n name: string;\n /** Only enabled identities are offered in the assignee picker. */\n enabled: boolean;\n /** User-added identities only: a stock emoji from AGENT_EMOJIS. Wins over `color`. */\n emoji?: string;\n /** User-added identities only: a colour from AGENT_COLORS. */\n color?: string;\n}\n\nexport interface AgentPreset {\n id: string;\n /** The default actor name. */\n name: string;\n /** Product name shown beside the name in Settings. */\n label: string;\n /** Brand colour behind the icon. */\n color: string;\n /** Enabled the first time Beadscope sees it. */\n enabled: boolean;\n}\n\n/** Pre-defined identities, in display order. They can be disabled and renamed, not deleted. */\nexport const AGENT_PRESETS: AgentPreset[] = [\n { id: \"claude-code\", name: \"claude-code\", label: \"Claude Code\", color: \"#d97757\", enabled: true },\n { id: \"codex\", name: \"codex\", label: \"Codex\", color: \"#10a37f\", enabled: false },\n { id: \"cursor\", name: \"cursor-agent\", label: \"Cursor\", color: \"#4b5563\", enabled: false },\n { id: \"gemini\", name: \"gemini\", label: \"Gemini CLI\", color: \"#4285f4\", enabled: false },\n { id: \"copilot\", name: \"copilot\", label: \"GitHub Copilot\", color: \"#8957e5\", enabled: false },\n];\n\n/** Stock emoji for identities the user adds. */\nexport const AGENT_EMOJIS = [\n \"🤖\", \"🧠\", \"⚡\", \"🛠️\", \"🚀\", \"🦾\", \"🔮\", \"🛰️\",\n \"🦉\", \"🐙\", \"🦊\", \"🐱\", \"🧪\", \"🎯\", \"🌟\", \"🧩\",\n];\n\n/** Colours for identities the user adds (shown behind the initials). */\nexport const AGENT_COLORS = [\n \"#ef4444\", \"#f97316\", \"#eab308\", \"#22c55e\",\n \"#14b8a6\", \"#3b82f6\", \"#8b5cf6\", \"#ec4899\",\n];\n\nexport const DEFAULT_AGENT_COLOR = AGENT_COLORS[5];\nexport const MAX_AGENT_NAME = 64;\n\nexport function presetOf(id: string): AgentPreset | undefined {\n return AGENT_PRESETS.find((p) => p.id === id);\n}\n\nexport function defaultAgents(): AgentIdentity[] {\n return AGENT_PRESETS.map((p) => ({ id: p.id, name: p.name, enabled: p.enabled }));\n}\n\n/**\n * Turn whatever is on disk (or in a request) into a clean list: every preset\n * present and in order, then the user's own, with unknown fields dropped.\n * Never throws, so a bad config file cannot break startup.\n */\nexport function normalizeAgents(input: unknown): AgentIdentity[] {\n const stored = new Map<string, Record<string, unknown>>();\n const custom: AgentIdentity[] = [];\n if (Array.isArray(input)) {\n for (const item of input) {\n if (!item || typeof item !== \"object\") continue;\n const e = item as Record<string, unknown>;\n if (typeof e.id !== \"string\" || !e.id || stored.has(e.id)) continue;\n stored.set(e.id, e);\n }\n }\n const nameOf = (e: Record<string, unknown> | undefined, fallback: string) => {\n const n = typeof e?.name === \"string\" ? e.name.trim().slice(0, MAX_AGENT_NAME) : \"\";\n return n || fallback;\n };\n const out: AgentIdentity[] = AGENT_PRESETS.map((p) => {\n const e = stored.get(p.id);\n return {\n id: p.id,\n name: nameOf(e, p.name),\n enabled: typeof e?.enabled === \"boolean\" ? e.enabled : p.enabled,\n };\n });\n for (const [id, e] of stored) {\n if (presetOf(id) || !id.startsWith(\"custom-\")) continue;\n const name = nameOf(e, \"\");\n if (!name) continue;\n const agent: AgentIdentity = { id, name, enabled: e.enabled !== false };\n if (typeof e.emoji === \"string\" && AGENT_EMOJIS.includes(e.emoji)) agent.emoji = e.emoji;\n if (typeof e.color === \"string\" && AGENT_COLORS.includes(e.color)) agent.color = e.color;\n custom.push(agent);\n }\n return [...out, ...custom];\n}\n\n/**\n * Check a list a user is saving. Returns a message for the first problem, or\n * null. Names must be unique (ignoring case) and must not collide with a human\n * name, which would make the agent's work render as human's.\n */\nexport function validateAgents(agents: AgentIdentity[], humanNames: string[]): string | null {\n const seen = new Set<string>();\n const humans = new Set(humanNames.map((n) => n.trim().toLowerCase()).filter(Boolean));\n for (const a of agents) {\n const name = a.name.trim();\n if (!name) return \"Every agent needs a name.\";\n if (name.length > MAX_AGENT_NAME) return `Agent names are at most ${MAX_AGENT_NAME} characters.`;\n if (/[\\u0000-\\u001f\\u007f]/.test(name)) return \"Agent names cannot contain control characters.\";\n const key = name.toLowerCase();\n if (humans.has(key)) return `\"${name}\" is a human name (the human actor or allowlist); agents need their own.`;\n if (seen.has(key)) return `\"${name}\" is used twice. Agent names must be unique.`;\n seen.add(key);\n }\n return null;\n}\n\n/** Enabled identities' names, in list order: what the assignee picker offers. */\nexport function enabledAgentNames(agents: AgentIdentity[] | undefined): string[] {\n return (agents ?? []).filter((a) => a.enabled).map((a) => a.name);\n}\n\n/** The identity an assignee name belongs to, enabled or not (so old beads keep their icon). */\nexport function agentByName(agents: AgentIdentity[] | undefined, name: string | null | undefined): AgentIdentity | undefined {\n const key = name?.trim().toLowerCase();\n if (!key) return undefined;\n return (agents ?? []).find((a) => a.name.trim().toLowerCase() === key);\n}\n\nexport function newCustomAgentId(): string {\n return `custom-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;\n}\n"],"names":["AGENT_PRESETS","id","name","label","color","enabled","AGENT_EMOJIS","AGENT_COLORS","DEFAULT_AGENT_COLOR","MAX_AGENT_NAME","presetOf","find","p","defaultAgents","map","normalizeAgents","input","stored","Map","custom","Array","isArray","item","e","has","set","nameOf","fallback","n","trim","slice","out","get","startsWith","agent","emoji","includes","push","validateAgents","agents","humanNames","seen","Set","humans","toLowerCase","filter","Boolean","a","length","test","key","add","enabledAgentNames","agentByName","undefined","newCustomAgentId","Date","now","toString","Math","random"],"mappings":"uCACA,IAAA,EAAA,EAAA,CAAA,CAAA,MACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OCqCO,IAAMA,EAA+B,CAC1C,CAAEC,GAAI,cAAeC,KAAM,cAAeC,MAAO,cAAeC,MAAO,UAAWC,SAAS,CAAK,EAChG,CAAEJ,GAAI,QAASC,KAAM,QAASC,MAAO,QAASC,MAAO,UAAWC,QAAS,EAAM,EAC/E,CAAEJ,GAAI,SAAUC,KAAM,eAAgBC,MAAO,SAAUC,MAAO,UAAWC,SAAS,CAAM,EACxF,CAAEJ,GAAI,SAAUC,KAAM,SAAUC,MAAO,aAAcC,MAAO,UAAWC,SAAS,CAAM,EACtF,CAAEJ,GAAI,UAAWC,KAAM,UAAWC,MAAO,iBAAkBC,MAAO,UAAWC,SAAS,CAAM,EAC7F,CAGYC,EAAe,CAC1B,KAAM,KAAM,IAAK,MAAO,KAAM,KAAM,KAAM,MAC1C,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAC3C,CAGYC,EAAe,CAC1B,UAAW,UAAW,UAAW,UACjC,UAAW,UAAW,UAAW,UAClC,CAkBM,SAASQ,EAAgBC,CAAc,EAC5C,IAAMC,EAAS,IAAIC,IACbC,EAA0B,EAAE,CAClC,GAAIC,MAAMC,OAAO,CAACL,GAChB,IAAK,CADmB,GACbM,KAAQN,EACZM,GAAwB,CADL,SACX,AAA0B,OAAnBA,IAEA,UAAhB,OAAO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IAAM,EAAM,IACN,EAAI,EAAI,QAAQ,CAAC,IAAI,CAAC,AAAC,GAAM,EAAE,EAAE,GAAK,GACxC,GAAG,CACL,EAAE,UAAU,CAAG,IAAI,OAAO,WAAW,GACrC,EAAQ,GAEZ"}
@@ -1,3 +1,3 @@
1
- module.exports=[60759,e=>{"use strict";var a=e.i(74533),t=e.i(12057),r=e.i(2157),i=e.i(50227);let n=(0,t.promisify)(a.execFile),s=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function o(e){let a=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(e);if(!a)throw Error("Invalid version metadata. Check the release instructions.");return{numbers:a.slice(1,4).map(Number),prerelease:!!a[4]}}function l(e,a){let t=o(e),r=o(a);for(let e=0;e<3;e++)if(t.numbers[e]!==r.numbers[e])return t.numbers[e]>r.numbers[e];return r.prerelease}var u=e.i(9069);let c=function(e){let a,t,{cwd:o,version:u,repository:c}=e,h=e.remote??`https://github.com/${c}.git`,d=e.fetch??fetch,p=e.run??((e,a,t)=>n(e,a,t)),f=!1,m=!1,w=()=>r.default.existsSync(i.default.join(o,".git")),g=async(...e)=>(await p("git",e,{cwd:o,timeout:2e4,maxBuffer:4194304})).stdout.trim();async function b(e){let a=await d(`https://api.github.com/repos/${c}/releases/${e?`tags/${encodeURIComponent(e)}`:"latest"}`,{headers:{Accept:"application/vnd.github+json"},signal:AbortSignal.timeout(1e4),cache:"no-store"});if(404===a.status&&!e)return null;if(!a.ok)throw Error(`Release check unavailable (${a.status}). Try again later.`);let t=await a.json();if(t.draft||t.prerelease||"string"!=typeof t.tag_name||!s.test(t.tag_name)||e&&t.tag_name!==e)throw Error("Invalid stable release metadata.");return t.tag_name}async function v(){return a&&a.until>Date.now()?a.value:(t||(t=b().then(e=>(a={value:e,until:Date.now()+3e5},e)).finally(()=>{t=void 0})),t)}async function y(e,a){let t="stable"===e?`refs/tags/${a}`:"refs/heads/main",r=[...new Map((await g("ls-remote",h,t,`${t}^{}`)).split("\n").map(e=>e.split(/\s+/)))],i=r.find(([,e])=>e===`${t}^{}`)?.[0]??r.find(([,e])=>e===t)?.[0];if(!i||!/^[a-f0-9]{40}$/.test(i))throw Error("The update target is unavailable.");return i}async function E(){if(!w())return"This installation needs a manual update. Follow the instructions in the release notes for a global copy, source download, or Docker installation.";let e=await g("branch","--show-current");return e&&"main"!==e?"Switch to the main branch before updating; your working branch will not be changed.":await g("status","--porcelain")?"Your checkout has uncommitted changes. Commit or stash them before updating.":void 0}return{check:async function(a="stable"){let t={channel:a,currentVersion:u,isGitRepo:w(),supervised:!!e.supervised,updateAvailable:!1,canUpdate:!1,behind:0,localSha:"",remoteSha:""};try{if("stable"===a){let e=await v();if(!e||(t.latestVersion=e.replace(/^v/,""),t.releaseUrl=`https://github.com/${c}/releases/tag/${encodeURIComponent(e)}`,t.updateAvailable=l(e,u),!t.updateAvailable)||(t.manualReason=await E(),!t.isGitRepo))return t;t.localSha=await g("rev-parse","HEAD"),t.remoteSha=await y(a,e),t.target={channel:a,tag:e,sha:t.remoteSha}}else{if(!t.isGitRepo)return{...t,manualReason:"Development updates require a Git checkout."};t.localSha=await g("rev-parse","HEAD"),t.remoteSha=await y(a),await g("fetch","--quiet","--no-tags","--no-write-fetch-head",h,t.remoteSha),t.behind=Number(await g("rev-list","--count",`HEAD..${t.remoteSha}`));let r=!!e.buildSha&&!t.localSha.startsWith(e.buildSha);t.updateAvailable=t.behind>0||r&&t.localSha===t.remoteSha,t.target={channel:a,sha:t.remoteSha},t.manualReason=await E()}return t.canUpdate=t.updateAvailable&&!t.manualReason,t}catch(e){return{...t,canUpdate:!1,error:e.message}}},update:async function(a){if(f)throw Error("An update is already running.");f=!0;try{if(!a||!["stable","development"].includes(a.channel)||!/^[a-f0-9]{40}$/.test(a.sha)||"stable"===a.channel&&(!a.tag||!s.test(a.tag)))throw Error("Invalid update target. Check for updates again.");if(!w())throw Error("A Git checkout is required for in-app updates. See the release instructions.");let t=await E();if(t)throw Error(t);if("stable"===a.channel&&(await b(a.tag),!l(a.tag,u)))throw Error("This release is not newer than the running version.");if(await y(a.channel,a.tag)!==a.sha)throw Error("The advertised update target changed. Check for updates again.");if(await g("fetch","--quiet","--no-tags","--no-write-fetch-head",h,a.sha),"stable"===a.channel){let e=JSON.parse(await g("show",`${a.sha}:package.json`));if("beadscope"!==e.name||e.version!==a.tag.replace(/^v/,""))throw Error("Release tag and package version do not match.")}let r=await g("rev-parse","HEAD");try{await g("merge-base","--is-ancestor",r,a.sha)}catch{throw Error("Your checkout has diverged from this update. A fast-forward is required; no local work was overwritten.")}let i=await E();if(i)throw Error(i);if(await g("rev-parse","HEAD")!==r)throw Error("The checkout changed while preparing the update. Try again.");let n=[],c=async(e,a,t)=>{try{let r=await p(a,t,{cwd:o,timeout:3e5,maxBuffer:0x4000000});n.push({name:e,ok:!0,output:`${r.stdout}${r.stderr}`.slice(-4e3)})}catch{throw Error(`${e} failed. Source files may already be updated; fix the problem and retry, or rebuild manually.`)}};await c("Install selected source version","git",["merge","--ff-only",a.sha]);let d=await g("rev-parse","HEAD");if(d!==a.sha)throw Error("The checkout does not match the selected update.");return await c("Install dependencies","npm",["ci","--include=dev","--no-audit","--no-fund"]),await c("Build app","npm",["run","build"]),m=!!e.supervised,{ok:!0,steps:n,restarting:m,fromSha:r,toSha:d}}finally{m||(f=!1)}}}}({cwd:process.cwd(),version:u.K,buildSha:u.p,repository:u.B,supervised:"1"===process.env.BEADSCOPE_SUPERVISED}),h=c.check,d=c.update;e.s(["D",0,75,"Y",0,h,"O",0,d],60759)}];
1
+ module.exports=[60759,e=>{"use strict";var a=e.i(74533),t=e.i(12057),r=e.i(2157),i=e.i(50227);let n=(0,t.promisify)(a.execFile),s=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function o(e){let a=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(e);if(!a)throw Error("Invalid version metadata. Check the release instructions.");return{numbers:a.slice(1,4).map(Number),prerelease:!!a[4]}}function l(e,a){let t=o(e),r=o(a);for(let e=0;e<3;e++)if(t.numbers[e]!==r.numbers[e])return t.numbers[e]>r.numbers[e];return r.prerelease}var u=e.i(9069);let c=function(e){let a,t,{cwd:o,version:u,repository:c}=e,h=e.remote??`https://github.com/${c}.git`,d=e.fetch??fetch,p=e.run??((e,a,t)=>n(e,a,t)),f=!1,m=!1,w=()=>r.default.existsSync(i.default.join(o,".git")),g=async(...e)=>(await p("git",e,{cwd:o,timeout:2e4,maxBuffer:4194304})).stdout.trim();async function b(e){let a=await d(`https://api.github.com/repos/${c}/releases/${e?`tags/${encodeURIComponent(e)}`:"latest"}`,{headers:{Accept:"application/vnd.github+json"},signal:AbortSignal.timeout(1e4),cache:"no-store"});if(404===a.status&&!e)return null;if(!a.ok)throw Error(`Release check unavailable (${a.status}). Try again later.`);let t=await a.json();if(t.draft||t.prerelease||"string"!=typeof t.tag_name||!s.test(t.tag_name)||e&&t.tag_name!==e)throw Error("Invalid stable release metadata.");return t.tag_name}async function v(){return a&&a.until>Date.now()?a.value:(t||(t=b().then(e=>(a={value:e,until:Date.now()+3e5},e)).finally(()=>{t=void 0})),t)}async function y(e,a){let t="stable"===e?`refs/tags/${a}`:"refs/heads/main",r=[...new Map((await g("ls-remote",h,t,`${t}^{}`)).split("\n").map(e=>e.split(/\s+/)))],i=r.find(([,e])=>e===`${t}^{}`)?.[0]??r.find(([,e])=>e===t)?.[0];if(!i||!/^[a-f0-9]{40}$/.test(i))throw Error("The update target is unavailable.");return i}async function E(){if(!w())return"This installation needs a manual update. Run `npm install -g beadscope` or `brew upgrade beadscope`, then `beadscope stop` and `beadscope start`; for a source download or Docker, follow the release notes.";let e=await g("branch","--show-current");return e&&"main"!==e?"Switch to the main branch before updating; your working branch will not be changed.":await g("status","--porcelain")?"Your checkout has uncommitted changes. Commit or stash them before updating.":void 0}return{check:async function(a="stable"){let t={channel:a,currentVersion:u,isGitRepo:w(),supervised:!!e.supervised,updateAvailable:!1,canUpdate:!1,behind:0,localSha:"",remoteSha:""};try{if("stable"===a){let e=await v();if(!e||(t.latestVersion=e.replace(/^v/,""),t.releaseUrl=`https://github.com/${c}/releases/tag/${encodeURIComponent(e)}`,t.updateAvailable=l(e,u),!t.updateAvailable)||(t.manualReason=await E(),!t.isGitRepo))return t;t.localSha=await g("rev-parse","HEAD"),t.remoteSha=await y(a,e),t.target={channel:a,tag:e,sha:t.remoteSha}}else{if(!t.isGitRepo)return{...t,manualReason:"Development updates require a Git checkout."};t.localSha=await g("rev-parse","HEAD"),t.remoteSha=await y(a),await g("fetch","--quiet","--no-tags","--no-write-fetch-head",h,t.remoteSha),t.behind=Number(await g("rev-list","--count",`HEAD..${t.remoteSha}`));let r=!!e.buildSha&&!t.localSha.startsWith(e.buildSha);t.updateAvailable=t.behind>0||r&&t.localSha===t.remoteSha,t.target={channel:a,sha:t.remoteSha},t.manualReason=await E()}return t.canUpdate=t.updateAvailable&&!t.manualReason,t}catch(e){return{...t,canUpdate:!1,error:e.message}}},update:async function(a){if(f)throw Error("An update is already running.");f=!0;try{if(!a||!["stable","development"].includes(a.channel)||!/^[a-f0-9]{40}$/.test(a.sha)||"stable"===a.channel&&(!a.tag||!s.test(a.tag)))throw Error("Invalid update target. Check for updates again.");if(!w())throw Error("A Git checkout is required for in-app updates. See the release instructions.");let t=await E();if(t)throw Error(t);if("stable"===a.channel&&(await b(a.tag),!l(a.tag,u)))throw Error("This release is not newer than the running version.");if(await y(a.channel,a.tag)!==a.sha)throw Error("The advertised update target changed. Check for updates again.");if(await g("fetch","--quiet","--no-tags","--no-write-fetch-head",h,a.sha),"stable"===a.channel){let e=JSON.parse(await g("show",`${a.sha}:package.json`));if("beadscope"!==e.name||e.version!==a.tag.replace(/^v/,""))throw Error("Release tag and package version do not match.")}let r=await g("rev-parse","HEAD");try{await g("merge-base","--is-ancestor",r,a.sha)}catch{throw Error("Your checkout has diverged from this update. A fast-forward is required; no local work was overwritten.")}let i=await E();if(i)throw Error(i);if(await g("rev-parse","HEAD")!==r)throw Error("The checkout changed while preparing the update. Try again.");let n=[],c=async(e,a,t)=>{try{let r=await p(a,t,{cwd:o,timeout:3e5,maxBuffer:0x4000000});n.push({name:e,ok:!0,output:`${r.stdout}${r.stderr}`.slice(-4e3)})}catch{throw Error(`${e} failed. Source files may already be updated; fix the problem and retry, or rebuild manually.`)}};await c("Install selected source version","git",["merge","--ff-only",a.sha]);let d=await g("rev-parse","HEAD");if(d!==a.sha)throw Error("The checkout does not match the selected update.");return await c("Install dependencies","npm",["ci","--include=dev","--no-audit","--no-fund"]),await c("Build app","npm",["run","build"]),m=!!e.supervised,{ok:!0,steps:n,restarting:m,fromSha:r,toSha:d}}finally{m||(f=!1)}}}}({cwd:process.cwd(),version:u.K,buildSha:u.p,repository:u.B,supervised:"1"===process.env.BEADSCOPE_SUPERVISED}),h=c.check,d=c.update;e.s(["D",0,75,"Y",0,h,"O",0,d],60759)}];
2
2
 
3
3
  //# sourceMappingURL=lib_self-update_ts_1s_0im4leryko._.js.map