mayura 1.2.1 → 1.3.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.
- package/README.md +4 -4
- package/docs/README.md +22 -5
- package/docs/cli/init.md +15 -3
- package/docs/guides/authentication.md +3 -1
- package/docs/guides/browsers.md +1 -0
- package/docs/guides/choosing-a-starter.md +83 -0
- package/docs/guides/copy-in-ui.md +36 -4
- package/docs/guides/framework-starters.md +7 -2
- package/docs/guides/hono.md +94 -0
- package/docs/guides/nextjs.md +94 -0
- package/docs/guides/nuxt.md +94 -0
- package/docs/guides/rag-deployment.md +49 -0
- package/docs/guides/rag-modal-pinecone-starter.md +65 -0
- package/docs/guides/rag-production.md +34 -15
- package/docs/guides/rag-quickstart.md +119 -0
- package/docs/guides/rag.md +11 -1
- package/docs/guides/react-router.md +94 -0
- package/docs/guides/release-readiness.md +98 -39
- package/docs/guides/sandboxes.md +1 -1
- package/docs/guides/server-and-client.md +8 -3
- package/docs/guides/sveltekit.md +94 -0
- package/docs/guides/tanstack-start.md +94 -0
- package/docs/integrations/browser-stagehand.md +5 -1
- package/docs/integrations/reranker-cohere.md +1 -0
- package/docs/integrations/reranker-jina.md +1 -0
- package/docs/integrations/reranker-voyage.md +1 -0
- package/docs/integrations/sandbox-codesandbox.md +4 -0
- package/docs/integrations/ui.md +82 -0
- package/docs/integrations/vector-chroma.md +1 -0
- package/docs/integrations/vector-libsql.md +1 -0
- package/docs/integrations/vector-pgvector.md +1 -0
- package/docs/integrations/vector-pinecone.md +4 -1
- package/docs/integrations/vector-qdrant.md +1 -0
- package/docs/integrations/vector-weaviate.md +1 -0
- package/docs/introduction.md +5 -0
- package/docs/project/changelog.md +48 -0
- package/docs/project/whats-new.md +79 -2
- package/docs/quickstart.md +5 -3
- package/docs/reference/integrations.md +11 -3
- package/lib/adapter-code-docker/image/Dockerfile +1 -1
- package/lib/adapter-code-docker/package.json +1 -1
- package/lib/adapter-code-quickjs/package.json +1 -1
- package/lib/adapter-mcp/package.json +1 -1
- package/lib/ag-ui/package.json +1 -1
- package/lib/artifacts/package.json +1 -1
- package/lib/auth/dist/identity.d.ts +2 -5
- package/lib/auth/dist/identity.d.ts.map +1 -1
- package/lib/auth/dist/identity.js.map +1 -1
- package/lib/auth/package.json +1 -1
- package/lib/auth/src/identity.ts +3 -3
- package/lib/authz/package.json +1 -1
- package/lib/browser/package.json +1 -1
- package/lib/cli/dist/deploy-targets.js +1 -1
- package/lib/cli/dist/deploy-targets.js.map +1 -1
- package/lib/cli/dist/index.d.ts +1 -1
- package/lib/cli/dist/index.d.ts.map +1 -1
- package/lib/cli/dist/index.js +63 -20
- package/lib/cli/dist/index.js.map +1 -1
- package/lib/cli/dist/interactive.js +2 -2
- package/lib/cli/dist/interactive.js.map +1 -1
- package/lib/cli/package.json +1 -1
- package/lib/cli/src/deploy-targets.ts +1 -1
- package/lib/cli/src/index.ts +51 -12
- package/lib/cli/src/interactive.ts +2 -2
- package/lib/cli/starter-assets/manifest.json +1 -0
- package/lib/cli/starters/hono/package.json +2 -2
- package/lib/cli/starters/rag-modal-pinecone/README.md +60 -0
- package/lib/cli/starters/rag-modal-pinecone/dot-env.example +23 -0
- package/lib/cli/starters/{event-automation → rag-modal-pinecone}/dot-gitignore +2 -4
- package/lib/cli/starters/rag-modal-pinecone/fixtures/on-call.md +4 -0
- package/lib/cli/starters/rag-modal-pinecone/mayura.project.json +13 -0
- package/lib/cli/starters/rag-modal-pinecone/modal-app.py +110 -0
- package/lib/cli/starters/rag-modal-pinecone/package.json +28 -0
- package/lib/cli/starters/rag-modal-pinecone/src/application.ts +148 -0
- package/lib/cli/starters/rag-modal-pinecone/src/cli.ts +78 -0
- package/lib/cli/starters/rag-modal-pinecone/src/hosted.ts +137 -0
- package/lib/cli/starters/rag-modal-pinecone/test/modal_worker_test.py +53 -0
- package/lib/cli/starters/rag-modal-pinecone/test/pipeline.test.ts +137 -0
- package/lib/cli/starters/{cli-agent → rag-modal-pinecone}/tsconfig.json +0 -1
- package/lib/cli/starters/support-agent/src/dev-request.ts +18 -0
- package/lib/cli/starters/support-agent/src/dev.ts +7 -4
- package/lib/cli/starters/support-agent/test/dev-request.test.ts +19 -0
- package/lib/client/dist/index.js +2 -2
- package/lib/client/dist/index.js.map +1 -1
- package/lib/client/package.json +1 -1
- package/lib/client/src/index.ts +2 -2
- package/lib/client-react/package.json +1 -1
- package/lib/code-mode/package.json +1 -1
- package/lib/code-mode-workflows/package.json +1 -1
- package/lib/context/package.json +1 -1
- package/lib/core/package.json +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
- package/lib/exporter-otlp/dist/signals.js +2 -2
- package/lib/exporter-otlp/dist/signals.js.map +1 -1
- package/lib/exporter-otlp/package.json +1 -1
- package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
- package/lib/exporter-otlp/src/signals.ts +2 -2
- package/lib/files/dist/store.d.ts.map +1 -1
- package/lib/files/dist/store.js +15 -2
- package/lib/files/dist/store.js.map +1 -1
- package/lib/files/package.json +1 -1
- package/lib/files/src/store.ts +15 -2
- package/lib/guardrails/package.json +1 -1
- package/lib/helpers/package.json +1 -1
- package/lib/keys/dist/manager.d.ts +1 -4
- package/lib/keys/dist/manager.d.ts.map +1 -1
- package/lib/keys/dist/manager.js +6 -4
- package/lib/keys/dist/manager.js.map +1 -1
- package/lib/keys/dist/verifier.d.ts +2 -1
- package/lib/keys/dist/verifier.d.ts.map +1 -1
- package/lib/keys/dist/verifier.js +2 -2
- package/lib/keys/dist/verifier.js.map +1 -1
- package/lib/keys/package.json +1 -1
- package/lib/keys/src/manager.ts +8 -6
- package/lib/keys/src/verifier.ts +4 -4
- package/lib/memory/package.json +1 -1
- package/lib/memory-remote/package.json +1 -1
- package/lib/observability/package.json +1 -1
- package/lib/provider-anthropic/package.json +1 -1
- package/lib/provider-openai/package.json +1 -1
- package/lib/rag/package.json +1 -1
- package/lib/runtime/package.json +1 -1
- package/lib/sandbox/package.json +1 -1
- package/lib/sdk/package.json +1 -1
- package/lib/server/dist/index.d.ts +2 -1
- package/lib/server/dist/index.d.ts.map +1 -1
- package/lib/server/dist/index.js +29 -24
- package/lib/server/dist/index.js.map +1 -1
- package/lib/server/dist/inspector-bundle.d.ts +1 -1
- package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
- package/lib/server/dist/inspector-bundle.js +4 -4
- package/lib/server/dist/inspector-bundle.js.map +1 -1
- package/lib/server/package.json +1 -1
- package/lib/server/src/index.ts +26 -20
- package/lib/server/src/inspector-bundle.ts +4 -4
- package/lib/server-node/package.json +1 -1
- package/lib/skills/package.json +1 -1
- package/lib/storage/package.json +1 -1
- package/lib/storage-contracts/package.json +1 -1
- package/lib/storage-postgres/package.json +1 -1
- package/lib/storage-sql/package.json +1 -1
- package/lib/storage-sqlite/package.json +1 -1
- package/lib/terminal/package.json +1 -1
- package/lib/testing/package.json +1 -1
- package/lib/threads/package.json +1 -1
- package/lib/tools/package.json +1 -1
- package/lib/voice/package.json +1 -1
- package/lib/workflows/package.json +1 -1
- package/lib/workstream/package.json +1 -1
- package/llms-full.txt +1595 -292
- package/llms.txt +23 -5
- package/package.json +4 -4
- package/lib/cli/starters/cli-agent/dot-github/workflows/ci.yml +0 -13
- package/lib/cli/starters/cli-agent/dot-gitignore +0 -10
- package/lib/cli/starters/event-automation/dot-dockerignore +0 -7
- package/lib/cli/starters/event-automation/dot-github/workflows/ci.yml +0 -13
- package/lib/cli/starters/event-automation/src/model.ts +0 -40
- package/lib/cli/starters/event-automation/tsconfig.json +0 -20
- package/lib/cli/starters/nextjs/Dockerfile +0 -12
- package/lib/cli/starters/nextjs/compose.yaml +0 -19
- package/lib/cli/starters/nextjs/dot-dockerignore +0 -11
- package/lib/cli/starters/nextjs/dot-env.example +0 -7
- package/lib/cli/starters/nextjs/scripts/setup.mjs +0 -9
- package/lib/cli/starters/nextjs/server/application.mjs +0 -74
- package/lib/cli/starters/nextjs/server/auth.mjs +0 -24
- package/lib/cli/starters/nextjs/server/worker.mjs +0 -11
- package/lib/cli/starters/nextjs/server/workflows.mjs +0 -23
- package/lib/cli/starters/nextjs/src/ChatApp.jsx +0 -57
- package/lib/cli/starters/nextjs/src/Notebook.jsx +0 -25
- package/lib/cli/starters/nextjs/src/components/mayura/approval.tsx +0 -142
- package/lib/cli/starters/nextjs/src/components/mayura/thread-history.tsx +0 -142
- package/lib/cli/starters/nextjs/src/components/mayura/thread-list.tsx +0 -9
- package/lib/cli/starters/nextjs/src/components/mayura/ui.css +0 -14
- package/lib/cli/starters/nextjs/src/connect.js +0 -21
- package/lib/cli/starters/nextjs/src/session.js +0 -138
- package/lib/cli/starters/nextjs/src/style.css +0 -11
- package/lib/cli/starters/nextjs/test/server.test.mjs +0 -95
- package/lib/cli/starters/nextjs/test/session.test.mjs +0 -16
- package/lib/cli/starters/nuxt/compose.yaml +0 -19
- package/lib/cli/starters/nuxt/dot-dockerignore +0 -11
- package/lib/cli/starters/nuxt/dot-env.example +0 -7
- package/lib/cli/starters/nuxt/dot-gitignore +0 -14
- package/lib/cli/starters/nuxt/scripts/setup.mjs +0 -9
- package/lib/cli/starters/nuxt/server/application.mjs +0 -74
- package/lib/cli/starters/nuxt/server/auth.mjs +0 -24
- package/lib/cli/starters/nuxt/server/worker.mjs +0 -11
- package/lib/cli/starters/nuxt/server/workflows.mjs +0 -23
- package/lib/cli/starters/nuxt/src/connect.js +0 -21
- package/lib/cli/starters/nuxt/src/session.js +0 -138
- package/lib/cli/starters/nuxt/src/style.css +0 -11
- package/lib/cli/starters/nuxt/test/server.test.mjs +0 -95
- package/lib/cli/starters/nuxt/test/session.test.mjs +0 -16
- package/lib/cli/starters/react-router/Dockerfile +0 -12
- package/lib/cli/starters/react-router/compose.yaml +0 -19
- package/lib/cli/starters/react-router/dot-dockerignore +0 -11
- package/lib/cli/starters/react-router/dot-env.example +0 -7
- package/lib/cli/starters/react-router/dot-gitignore +0 -14
- package/lib/cli/starters/react-router/scripts/setup.mjs +0 -9
- package/lib/cli/starters/react-router/server/application.mjs +0 -74
- package/lib/cli/starters/react-router/server/auth.mjs +0 -24
- package/lib/cli/starters/react-router/server/worker.mjs +0 -11
- package/lib/cli/starters/react-router/server/workflows.mjs +0 -23
- package/lib/cli/starters/react-router/src/ChatApp.jsx +0 -57
- package/lib/cli/starters/react-router/src/Notebook.jsx +0 -25
- package/lib/cli/starters/react-router/src/components/mayura/approval.tsx +0 -142
- package/lib/cli/starters/react-router/src/components/mayura/thread-history.tsx +0 -142
- package/lib/cli/starters/react-router/src/components/mayura/thread-list.tsx +0 -9
- package/lib/cli/starters/react-router/src/components/mayura/ui.css +0 -14
- package/lib/cli/starters/react-router/src/connect.js +0 -21
- package/lib/cli/starters/react-router/src/session.js +0 -138
- package/lib/cli/starters/react-router/src/style.css +0 -11
- package/lib/cli/starters/react-router/src/vite-env.d.ts +0 -1
- package/lib/cli/starters/react-router/test/server.test.mjs +0 -95
- package/lib/cli/starters/react-router/test/session.test.mjs +0 -16
- package/lib/cli/starters/research-team/dot-dockerignore +0 -7
- package/lib/cli/starters/research-team/dot-github/workflows/ci.yml +0 -13
- package/lib/cli/starters/research-team/dot-gitignore +0 -10
- package/lib/cli/starters/research-team/src/model.ts +0 -40
- package/lib/cli/starters/research-team/tsconfig.json +0 -20
- package/lib/cli/starters/support-agent/dot-dockerignore +0 -7
- package/lib/cli/starters/support-agent/dot-github/workflows/ci.yml +0 -13
- package/lib/cli/starters/support-agent/dot-gitignore +0 -10
- package/lib/cli/starters/support-agent/src/model.ts +0 -40
- package/lib/cli/starters/support-agent/tsconfig.json +0 -20
- package/lib/cli/starters/sveltekit/Dockerfile +0 -12
- package/lib/cli/starters/sveltekit/compose.yaml +0 -19
- package/lib/cli/starters/sveltekit/dot-dockerignore +0 -11
- package/lib/cli/starters/sveltekit/dot-env.example +0 -7
- package/lib/cli/starters/sveltekit/dot-gitignore +0 -14
- package/lib/cli/starters/sveltekit/scripts/setup.mjs +0 -9
- package/lib/cli/starters/sveltekit/server/application.mjs +0 -74
- package/lib/cli/starters/sveltekit/server/auth.mjs +0 -24
- package/lib/cli/starters/sveltekit/server/worker.mjs +0 -11
- package/lib/cli/starters/sveltekit/server/workflows.mjs +0 -23
- package/lib/cli/starters/sveltekit/src/connect.js +0 -21
- package/lib/cli/starters/sveltekit/src/session.js +0 -138
- package/lib/cli/starters/sveltekit/src/style.css +0 -11
- package/lib/cli/starters/sveltekit/src/view.js +0 -49
- package/lib/cli/starters/sveltekit/test/server.test.mjs +0 -95
- package/lib/cli/starters/sveltekit/test/session.test.mjs +0 -16
- package/lib/cli/starters/tanstack-start/Dockerfile +0 -12
- package/lib/cli/starters/tanstack-start/compose.yaml +0 -19
- package/lib/cli/starters/tanstack-start/dot-dockerignore +0 -11
- package/lib/cli/starters/tanstack-start/dot-env.example +0 -7
- package/lib/cli/starters/tanstack-start/dot-gitignore +0 -14
- package/lib/cli/starters/tanstack-start/scripts/setup.mjs +0 -9
- package/lib/cli/starters/tanstack-start/server/application.mjs +0 -74
- package/lib/cli/starters/tanstack-start/server/auth.mjs +0 -24
- package/lib/cli/starters/tanstack-start/server/worker.mjs +0 -11
- package/lib/cli/starters/tanstack-start/server/workflows.mjs +0 -23
- package/lib/cli/starters/tanstack-start/src/ChatApp.jsx +0 -57
- package/lib/cli/starters/tanstack-start/src/Notebook.jsx +0 -25
- package/lib/cli/starters/tanstack-start/src/components/mayura/approval.tsx +0 -142
- package/lib/cli/starters/tanstack-start/src/components/mayura/thread-history.tsx +0 -142
- package/lib/cli/starters/tanstack-start/src/components/mayura/thread-list.tsx +0 -9
- package/lib/cli/starters/tanstack-start/src/components/mayura/ui.css +0 -14
- package/lib/cli/starters/tanstack-start/src/connect.js +0 -21
- package/lib/cli/starters/tanstack-start/src/session.js +0 -138
- package/lib/cli/starters/tanstack-start/src/style.css +0 -11
- package/lib/cli/starters/tanstack-start/test/server.test.mjs +0 -95
- package/lib/cli/starters/tanstack-start/test/session.test.mjs +0 -16
- /package/lib/cli/{starters/hono/src/components/mayura/ui.css → starter-assets/011cacc77ada0de5b447674e9fc4374a247b9a46eb169722b12649753f24188f} +0 -0
- /package/lib/cli/{starters/hono/test/server.test.mjs → starter-assets/0c825d6a776673ec6274cfc29cd45b1a8c56dcb880c291a91075c77e1ef1e4f3} +0 -0
- /package/lib/cli/{starters/hono/server/auth.mjs → starter-assets/0dd570bfacc357d23be3340250090b9a4c6193a49cdd02e9b6789e7bee8433dd} +0 -0
- /package/lib/cli/{starters/hono/src/components/mayura/approval.tsx → starter-assets/11292bd14cdaf27a8f8317ba4ab768d706a726b2e26474b599f3db116674b4b3} +0 -0
- /package/lib/cli/{starters/nextjs/dot-gitignore → starter-assets/1873b02e070347f9a449e07084242982fa6af412c45aa764985d553975b64589} +0 -0
- /package/lib/cli/{starters/hono/src/style.css → starter-assets/2f3869e6d69134e43be713c4590bfe48896a5c54ece6ffc1a4f204cfcfe54218} +0 -0
- /package/lib/cli/{starters/hono/server/worker.mjs → starter-assets/350d77757f548369beff29d658cf1620752d4e23b4b732d99a1b403ca043137f} +0 -0
- /package/lib/cli/{starters/approval-workflow/src/model.ts → starter-assets/37294d24c04b71eaf6d6f0bd52fd4c1cc7a5d3cb63da9c7920ed1d44276da9cb} +0 -0
- /package/lib/cli/{starters/approval-workflow/tsconfig.json → starter-assets/4387d6537dd5924ae62326aa3d7d8cbad1e5abd930aecc9daa6fab1ac2f6ef24} +0 -0
- /package/lib/cli/{starters/hono/dot-dockerignore → starter-assets/4434be031b58cc6ee680b2860b2ad1fe4089af7ee866c13223dfb621dd042ff1} +0 -0
- /package/lib/cli/{starters/hono/src/ChatApp.jsx → starter-assets/46e199317648a076243d6c8e7ffedc48785a6ffc0f203b88c7c4a9479b34c5b9} +0 -0
- /package/lib/cli/{starters/hono/src/components/mayura/thread-history.tsx → starter-assets/4741fccbca2e0d2fc6f61d11af3cf7bcc5f0238b67bb46282287207abdc6c536} +0 -0
- /package/lib/cli/{starters/approval-workflow/dot-dockerignore → starter-assets/4be664708b0120da5d2b73c5a27968093da06b8728f88f2bda2a1ccbf40f6891} +0 -0
- /package/lib/cli/{starters/hono/server/workflows.mjs → starter-assets/4d11f729672df54969a851494877a3c5aee24bb8f8c68eacaaa22e715bf5ed69} +0 -0
- /package/lib/cli/{starters/hono/dot-env.example → starter-assets/4f141323062660c4dc5b563300d57bb4cdbdc7fe9bfba96e43d9c64bb274474e} +0 -0
- /package/lib/cli/{starters/hono/Dockerfile → starter-assets/5471b74c46258d1edb00eb8f60f4219c389a252f7e224f2692f8f3e71ae43e3e} +0 -0
- /package/lib/cli/{starters/hono/scripts/setup.mjs → starter-assets/56e2d6db9fe4b0449c979acd06947a5b776bcc645184b54b8d3654a48bd12c38} +0 -0
- /package/lib/cli/{starters/hono/src/Notebook.jsx → starter-assets/6138d1e2ca4469daf4f5545d140943f6e23b0c37f865051b266ec99695cf181a} +0 -0
- /package/lib/cli/{starters/hono/src/vite-env.d.ts → starter-assets/65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5} +0 -0
- /package/lib/cli/{starters/hono/server/application.mjs → starter-assets/757f43c27415654049ecf01b67d560c83d788108d1aebcf1f16a86d956bd7fb6} +0 -0
- /package/lib/cli/{starters/hono/src/components/mayura/thread-list.tsx → starter-assets/97601d0bf331df7bbde88f7ee269610bc8a1239f8eeb58fded6416e588a5b7dd} +0 -0
- /package/lib/cli/{starters/approval-workflow/dot-github/workflows/ci.yml → starter-assets/aa4182c76778ba2194ecbfde9a960c20181534fd1ab484df126278dbc6eb0186} +0 -0
- /package/lib/cli/{starters/hono/src/session.js → starter-assets/abcc6ebd29ba47a079befb6568054dec8f43d4c729187e4a3610af39789e77be} +0 -0
- /package/lib/cli/{starters/hono/compose.yaml → starter-assets/cc1df6f5ce0eebffc567ecea1d599eba97cd1b94ab01551085c0eb87a28e3a6c} +0 -0
- /package/lib/cli/{starters/hono/src/connect.js → starter-assets/cd3ddb959b277e7d495cc020a6f8146acfbcc9d05ececa3809e8aafcf84504d9} +0 -0
- /package/lib/cli/{starters/hono/test/session.test.mjs → starter-assets/dfe75fd07538427d80ba76767e037e929664c80ff5a41b7544496a789181bb73} +0 -0
- /package/lib/cli/{starters/approval-workflow/dot-gitignore → starter-assets/f3ef7285253ec9668732f535306beee602e91cb6e20f83d4799b3323399ce569} +0 -0
- /package/lib/cli/{starters/nuxt/src/view.js → starter-assets/ff840fe960683d377e78f731b5d4318adf6050384791fa20e4948d34192aa35d} +0 -0
package/lib/ag-ui/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServerIdentity } from '../../server/dist/index.js';
|
|
1
|
+
import type { AgentServerOptions, ServerIdentity } from '../../server/dist/index.js';
|
|
2
2
|
import { type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';
|
|
3
3
|
/** A permission Mayura's server knows. */
|
|
4
4
|
export type ServerCapability = ServerIdentity['capabilities'][number];
|
|
@@ -14,10 +14,7 @@ export interface IdentityGrant {
|
|
|
14
14
|
}
|
|
15
15
|
/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */
|
|
16
16
|
export interface Authenticator {
|
|
17
|
-
(request:
|
|
18
|
-
readonly token: string;
|
|
19
|
-
readonly signal: AbortSignal;
|
|
20
|
-
}): Promise<ServerIdentity | null>;
|
|
17
|
+
(request: Parameters<AgentServerOptions['authenticate']>[0]): Promise<ServerIdentity | null>;
|
|
21
18
|
/** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */
|
|
22
19
|
readonly accepts: (token: string) => boolean;
|
|
23
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,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E,CAAC;QACjI,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,yDAAyD,CAAC,CAAC;IACrG,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,GAAG,cAAc,CAAC,CAAC;IACjC,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1E,MAAM,YAAY,GAAG,KAAK,EAAE,OAAiE,EAAkC,EAAE;QAC/H,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC9D,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { MayuraError } from '@mayura/core';\nimport { sha256, toBase64Url } from '@mayura/core/host';\nimport type { ServerIdentity } from '@mayura/server';\nimport { peekIssuer, type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';\n\n/** A permission Mayura's server knows. */\nexport type ServerCapability = ServerIdentity['capabilities'][number];\n/** Every permission Mayura's server knows, for mapping tables and checks. */\nexport const serverCapabilities: readonly ServerCapability[] = Object.freeze(['runs:read', 'runs:submit', 'runs:cancel', 'runs:approve', 'runs:resume', 'threads:read', 'threads:write', 'threads:delete', 'threads:compact', 'threads:import', 'operations:read',\n 'humans:read', 'humans:respond', 'workflows:read', 'workflows:control', 'workflows:fleet', 'workflows:migrate']);\n\n/** What a verified caller may do, as an identity mapping returns it; `expiresAtMs` defaults to the credential's expiry. */\nexport interface IdentityGrant {\n readonly principalId: string;\n readonly projectId: string;\n readonly agentIds: readonly string[];\n readonly capabilities: readonly ServerCapability[];\n readonly expiresAtMs?: number;\n}\n\n/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */\nexport interface Authenticator {\n (request: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null>;\n /** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */\n readonly accepts: (token: string) => boolean;\n}\n\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/u;\nconst namespacePattern = /^[a-z0-9][a-z0-9.-]{0,31}$/u;\n\n/**\n * A principal id for a subject of an identity provider, as Mayura's server accepts one: `<namespace>/<subject>`. A\n * subject with characters the server does not accept (such as Auth0's `auth0|123`), or too long, becomes `_` and the\n * base64url of its SHA-256: stable, and never equal to a subject kept as it is.\n */\nexport function principalId(namespace: string, subject: string): string {\n if (typeof namespace !== 'string' || !namespacePattern.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'principalId(): namespace is 1-32 lowercase letters, digits, \".\" or \"-\".');\n if (typeof subject !== 'string' || subject === '') throw new MayuraError('INVALID_INPUT', 'principalId(): subject is a non-empty string.');\n const id = `${namespace}/${subject}`;\n if (!subject.startsWith('_') && identifier.test(id)) return id;\n return `${namespace}/_${toBase64Url(sha256(subject))}`;\n}\n\n/**\n * Mayura capabilities for an identity provider's permissions or roles, through an explicit table: each listed value\n * grants its capabilities, and anything not in the table grants nothing.\n */\nexport function mapCapabilities(values: unknown, table: Readonly<Record<string, readonly ServerCapability[]>>): ServerCapability[] {\n if (!table || typeof table !== 'object') throw new MayuraError('INVALID_CONFIG', 'mapCapabilities(): table maps permission names to capabilities.');\n for (const [name, granted] of Object.entries(table)) {\n if (!Array.isArray(granted) || granted.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', `mapCapabilities(): ${name} maps to capabilities Mayura's server knows.`);\n }\n const list = typeof values === 'string' ? values.split(' ') : Array.isArray(values) ? values : [];\n const found = new Set<ServerCapability>();\n for (const value of list) if (typeof value === 'string' && Object.hasOwn(table, value)) for (const capability of table[value]!) found.add(capability);\n return serverCapabilities.filter(capability => found.has(capability));\n}\n\n/** @internal An identity the server accepts, from a grant; null when the grant is unusable or already expired. */\nexport function identityFrom(grant: IdentityGrant | null | undefined, credentialExpiresAtMs: number, maxIdentityMs: number): ServerIdentity | null {\n if (!grant) return null;\n const { principalId: principal, projectId, agentIds, capabilities } = grant;\n if (typeof principal !== 'string' || !identifier.test(principal) || typeof projectId !== 'string' || !identifier.test(projectId)) {\n throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned a principalId or projectId Mayura cannot use: 1-128 letters, digits, \".\", \"_\", \"/\" or \"-\", starting with a letter or digit.');\n }\n if (!Array.isArray(agentIds) || agentIds.length > 256 || agentIds.some(id => typeof id !== 'string' || !identifier.test(id))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned agentIds Mayura cannot use.');\n if (!Array.isArray(capabilities) || capabilities.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned capabilities Mayura\\'s server does not know.');\n const now = Date.now();\n const requested = grant.expiresAtMs ?? credentialExpiresAtMs;\n if (!Number.isSafeInteger(requested)) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned an expiresAtMs that is not a whole number of milliseconds.');\n // Never past the credential, and never longer than maxIdentityMs: the caller presents the credential again.\n const expiresAtMs = Math.min(requested, credentialExpiresAtMs, now + maxIdentityMs);\n if (expiresAtMs <= now) return null;\n return Object.freeze({\n scope: Object.freeze({ principalId: principal, projectId }), agentIds: Object.freeze([...new Set(agentIds)]),\n capabilities: Object.freeze(serverCapabilities.filter(capability => capabilities.includes(capability))), expiresAtMs,\n });\n}\n\n/**\n * The identity Mayura's server takes, from what a verified credential may do: checked against what the server accepts,\n * and lasting no longer than the credential nor `maxIdentityMs` (60 s by default). Null for no grant, or one already\n * over. For authenticators of your own; the ones here use it.\n */\nexport function serverIdentity(grant: IdentityGrant | null | undefined, options: { readonly credentialExpiresAtMs: number; readonly maxIdentityMs?: number }): ServerIdentity | null {\n if (!options || typeof options.credentialExpiresAtMs !== 'number' || Number.isNaN(options.credentialExpiresAtMs)) throw new MayuraError('INVALID_CONFIG', 'serverIdentity(): credentialExpiresAtMs is when the credential expires.');\n return identityFrom(grant, options.credentialExpiresAtMs, checkMaxIdentityMs(options.maxIdentityMs, 'serverIdentity()'));\n}\n\nexport interface JwtAuthenticatorOptions {\n readonly verifier: JwtVerifier;\n /**\n * What a verified token's holder may do, or null to refuse. Grant only what your application decides: a valid token\n * proves who someone is, not what they may do here.\n */\n readonly identity: (claims: JwtClaims, header: JwtHeader) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** The longest an identity lasts before the token is checked again; 60 s by default (1 s to 1 hour). */\n readonly maxIdentityMs?: number;\n}\n\n/** @internal */\nexport function checkMaxIdentityMs(value: number | undefined, owner: string): number {\n const result = value ?? 60_000;\n if (!Number.isSafeInteger(result) || result < 1_000 || result > 3_600_000) throw new MayuraError('INVALID_CONFIG', `${owner}: maxIdentityMs is 1,000 to 3,600,000.`);\n return result;\n}\n\n/**\n * A server `authenticate` for JWTs from one issuer: the verifier checks the token, then `identity` decides what its\n * holder may do. It accepts only tokens naming the verifier's issuer, so several can be chained.\n */\nexport function jwtAuthenticator(options: JwtAuthenticatorOptions): Authenticator {\n if (!options?.verifier || typeof options.verifier.verify !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): verifier is jwtVerifier(...).');\n if (typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): identity decides what a verified caller may do.');\n const maxIdentityMs = checkMaxIdentityMs(options.maxIdentityMs, 'jwtAuthenticator()');\n const issuers = options.verifier.issuers;\n const accepts = (token: string) => { const iss = peekIssuer(token); return iss !== undefined && issuers.includes(iss); };\n const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null> => {\n if (!accepts(token)) return null;\n const result = await options.verifier.verify(token, { signal });\n if (!result.ok) return null;\n return identityFrom(await options.identity(result.claims, result.header), result.claims.exp * 1_000, maxIdentityMs);\n };\n return Object.assign(authenticate, { accepts });\n}\n\n/**\n * One server `authenticate` from several: a token goes to the first authenticator that accepts it (by issuer or key\n * prefix), and nothing else sees it. A token none accepts is refused.\n */\nexport function chainAuthenticators(...authenticators: readonly Authenticator[]): Authenticator {\n if (authenticators.length === 0 || authenticators.some(item => typeof item !== 'function' || typeof item.accepts !== 'function')) {\n throw new MayuraError('INVALID_CONFIG', 'chainAuthenticators() takes one or more authenticators.');\n }\n const list = [...authenticators];\n const accepts = (token: string) => list.some(item => item.accepts(token));\n const authenticate = async (request: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null> => {\n const chosen = list.find(item => item.accepts(request.token));\n return chosen ? chosen(request) : null;\n };\n return Object.assign(authenticate, { accepts });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,EAAE,UAAU,EAAoD,MAAM,UAAU,CAAC;AAIxF,6EAA6E;AAC7E,MAAM,CAAC,MAAM,kBAAkB,GAAgC,MAAM,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,iBAAiB;IAC/P,aAAa,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,mBAAmB,CAAC,CAAC,CAAC;AAkBnH,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAC1D,MAAM,gBAAgB,GAAG,6BAA6B,CAAC;AAEvD;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,SAAi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,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC9D,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { MayuraError } from '@mayura/core';\nimport { sha256, toBase64Url } from '@mayura/core/host';\nimport type { AgentServerOptions, ServerIdentity } from '@mayura/server';\nimport { peekIssuer, type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';\n\n/** A permission Mayura's server knows. */\nexport type ServerCapability = ServerIdentity['capabilities'][number];\n/** Every permission Mayura's server knows, for mapping tables and checks. */\nexport const serverCapabilities: readonly ServerCapability[] = Object.freeze(['runs:read', 'runs:submit', 'runs:cancel', 'runs:approve', 'runs:resume', 'threads:read', 'threads:write', 'threads:delete', 'threads:compact', 'threads:import', 'operations:read',\n 'humans:read', 'humans:respond', 'workflows:read', 'workflows:control', 'workflows:fleet', 'workflows:migrate']);\n\n/** What a verified caller may do, as an identity mapping returns it; `expiresAtMs` defaults to the credential's expiry. */\nexport interface IdentityGrant {\n readonly principalId: string;\n readonly projectId: string;\n readonly agentIds: readonly string[];\n readonly capabilities: readonly ServerCapability[];\n readonly expiresAtMs?: number;\n}\n\n/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */\nexport interface Authenticator {\n (request: Parameters<AgentServerOptions['authenticate']>[0]): Promise<ServerIdentity | null>;\n /** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */\n readonly accepts: (token: string) => boolean;\n}\n\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/u;\nconst namespacePattern = /^[a-z0-9][a-z0-9.-]{0,31}$/u;\n\n/**\n * A principal id for a subject of an identity provider, as Mayura's server accepts one: `<namespace>/<subject>`. A\n * subject with characters the server does not accept (such as Auth0's `auth0|123`), or too long, becomes `_` and the\n * base64url of its SHA-256: stable, and never equal to a subject kept as it is.\n */\nexport function principalId(namespace: string, subject: string): string {\n if (typeof namespace !== 'string' || !namespacePattern.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'principalId(): namespace is 1-32 lowercase letters, digits, \".\" or \"-\".');\n if (typeof subject !== 'string' || subject === '') throw new MayuraError('INVALID_INPUT', 'principalId(): subject is a non-empty string.');\n const id = `${namespace}/${subject}`;\n if (!subject.startsWith('_') && identifier.test(id)) return id;\n return `${namespace}/_${toBase64Url(sha256(subject))}`;\n}\n\n/**\n * Mayura capabilities for an identity provider's permissions or roles, through an explicit table: each listed value\n * grants its capabilities, and anything not in the table grants nothing.\n */\nexport function mapCapabilities(values: unknown, table: Readonly<Record<string, readonly ServerCapability[]>>): ServerCapability[] {\n if (!table || typeof table !== 'object') throw new MayuraError('INVALID_CONFIG', 'mapCapabilities(): table maps permission names to capabilities.');\n for (const [name, granted] of Object.entries(table)) {\n if (!Array.isArray(granted) || granted.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', `mapCapabilities(): ${name} maps to capabilities Mayura's server knows.`);\n }\n const list = typeof values === 'string' ? values.split(' ') : Array.isArray(values) ? values : [];\n const found = new Set<ServerCapability>();\n for (const value of list) if (typeof value === 'string' && Object.hasOwn(table, value)) for (const capability of table[value]!) found.add(capability);\n return serverCapabilities.filter(capability => found.has(capability));\n}\n\n/** @internal An identity the server accepts, from a grant; null when the grant is unusable or already expired. */\nexport function identityFrom(grant: IdentityGrant | null | undefined, credentialExpiresAtMs: number, maxIdentityMs: number): ServerIdentity | null {\n if (!grant) return null;\n const { principalId: principal, projectId, agentIds, capabilities } = grant;\n if (typeof principal !== 'string' || !identifier.test(principal) || typeof projectId !== 'string' || !identifier.test(projectId)) {\n throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned a principalId or projectId Mayura cannot use: 1-128 letters, digits, \".\", \"_\", \"/\" or \"-\", starting with a letter or digit.');\n }\n if (!Array.isArray(agentIds) || agentIds.length > 256 || agentIds.some(id => typeof id !== 'string' || !identifier.test(id))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned agentIds Mayura cannot use.');\n if (!Array.isArray(capabilities) || capabilities.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned capabilities Mayura\\'s server does not know.');\n const now = Date.now();\n const requested = grant.expiresAtMs ?? credentialExpiresAtMs;\n if (!Number.isSafeInteger(requested)) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned an expiresAtMs that is not a whole number of milliseconds.');\n // Never past the credential, and never longer than maxIdentityMs: the caller presents the credential again.\n const expiresAtMs = Math.min(requested, credentialExpiresAtMs, now + maxIdentityMs);\n if (expiresAtMs <= now) return null;\n return Object.freeze({\n scope: Object.freeze({ principalId: principal, projectId }), agentIds: Object.freeze([...new Set(agentIds)]),\n capabilities: Object.freeze(serverCapabilities.filter(capability => capabilities.includes(capability))), expiresAtMs,\n });\n}\n\n/**\n * The identity Mayura's server takes, from what a verified credential may do: checked against what the server accepts,\n * and lasting no longer than the credential nor `maxIdentityMs` (60 s by default). Null for no grant, or one already\n * over. For authenticators of your own; the ones here use it.\n */\nexport function serverIdentity(grant: IdentityGrant | null | undefined, options: { readonly credentialExpiresAtMs: number; readonly maxIdentityMs?: number }): ServerIdentity | null {\n if (!options || typeof options.credentialExpiresAtMs !== 'number' || Number.isNaN(options.credentialExpiresAtMs)) throw new MayuraError('INVALID_CONFIG', 'serverIdentity(): credentialExpiresAtMs is when the credential expires.');\n return identityFrom(grant, options.credentialExpiresAtMs, checkMaxIdentityMs(options.maxIdentityMs, 'serverIdentity()'));\n}\n\nexport interface JwtAuthenticatorOptions {\n readonly verifier: JwtVerifier;\n /**\n * What a verified token's holder may do, or null to refuse. Grant only what your application decides: a valid token\n * proves who someone is, not what they may do here.\n */\n readonly identity: (claims: JwtClaims, header: JwtHeader) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** The longest an identity lasts before the token is checked again; 60 s by default (1 s to 1 hour). */\n readonly maxIdentityMs?: number;\n}\n\n/** @internal */\nexport function checkMaxIdentityMs(value: number | undefined, owner: string): number {\n const result = value ?? 60_000;\n if (!Number.isSafeInteger(result) || result < 1_000 || result > 3_600_000) throw new MayuraError('INVALID_CONFIG', `${owner}: maxIdentityMs is 1,000 to 3,600,000.`);\n return result;\n}\n\n/**\n * A server `authenticate` for JWTs from one issuer: the verifier checks the token, then `identity` decides what its\n * holder may do. It accepts only tokens naming the verifier's issuer, so several can be chained.\n */\nexport function jwtAuthenticator(options: JwtAuthenticatorOptions): Authenticator {\n if (!options?.verifier || typeof options.verifier.verify !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): verifier is jwtVerifier(...).');\n if (typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): identity decides what a verified caller may do.');\n const maxIdentityMs = checkMaxIdentityMs(options.maxIdentityMs, 'jwtAuthenticator()');\n const issuers = options.verifier.issuers;\n const accepts = (token: string) => { const iss = peekIssuer(token); return iss !== undefined && issuers.includes(iss); };\n const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null> => {\n if (!accepts(token)) return null;\n const result = await options.verifier.verify(token, { signal });\n if (!result.ok) return null;\n return identityFrom(await options.identity(result.claims, result.header), result.claims.exp * 1_000, maxIdentityMs);\n };\n return Object.assign(authenticate, { accepts });\n}\n\n/**\n * One server `authenticate` from several: a token goes to the first authenticator that accepts it (by issuer or key\n * prefix), and nothing else sees it. A token none accepts is refused.\n */\nexport function chainAuthenticators(...authenticators: readonly Authenticator[]): Authenticator {\n if (authenticators.length === 0 || authenticators.some(item => typeof item !== 'function' || typeof item.accepts !== 'function')) {\n throw new MayuraError('INVALID_CONFIG', 'chainAuthenticators() takes one or more authenticators.');\n }\n const list = [...authenticators];\n const accepts = (token: string) => list.some(item => item.accepts(token));\n const authenticate = async (request: Parameters<Authenticator>[0]): Promise<ServerIdentity | null> => {\n const chosen = list.find(item => item.accepts(request.token));\n return chosen ? chosen(request) : null;\n };\n return Object.assign(authenticate, { accepts });\n}\n"]}
|
package/lib/auth/package.json
CHANGED
package/lib/auth/src/identity.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MayuraError } from '@mayura/core';
|
|
2
2
|
import { sha256, toBase64Url } from '@mayura/core/host';
|
|
3
|
-
import type { ServerIdentity } from '@mayura/server';
|
|
3
|
+
import type { AgentServerOptions, ServerIdentity } from '@mayura/server';
|
|
4
4
|
import { peekIssuer, type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';
|
|
5
5
|
|
|
6
6
|
/** A permission Mayura's server knows. */
|
|
@@ -20,7 +20,7 @@ export interface IdentityGrant {
|
|
|
20
20
|
|
|
21
21
|
/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */
|
|
22
22
|
export interface Authenticator {
|
|
23
|
-
(request:
|
|
23
|
+
(request: Parameters<AgentServerOptions['authenticate']>[0]): Promise<ServerIdentity | null>;
|
|
24
24
|
/** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */
|
|
25
25
|
readonly accepts: (token: string) => boolean;
|
|
26
26
|
}
|
|
@@ -134,7 +134,7 @@ export function chainAuthenticators(...authenticators: readonly Authenticator[])
|
|
|
134
134
|
}
|
|
135
135
|
const list = [...authenticators];
|
|
136
136
|
const accepts = (token: string) => list.some(item => item.accepts(token));
|
|
137
|
-
const authenticate = async (request:
|
|
137
|
+
const authenticate = async (request: Parameters<Authenticator>[0]): Promise<ServerIdentity | null> => {
|
|
138
138
|
const chosen = list.find(item => item.accepts(request.token));
|
|
139
139
|
return chosen ? chosen(request) : null;
|
|
140
140
|
};
|
package/lib/authz/package.json
CHANGED
package/lib/browser/package.json
CHANGED
|
@@ -217,7 +217,7 @@ const manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/k
|
|
|
217
217
|
* `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).
|
|
218
218
|
*/
|
|
219
219
|
export function releaseSlug(tag) {
|
|
220
|
-
const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(
|
|
220
|
+
const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+/u, '').slice(0, 13).replace(/-+$/u, '');
|
|
221
221
|
return slug || 'release';
|
|
222
222
|
}
|
|
223
223
|
function render(manifest, path, image, slug) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deploy-targets.js","sourceRoot":"","sources":["../src/deploy-targets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmC,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAA8E,MAAM,aAAa,CAAC;AAE7H,sHAAsH;AAEtH,MAAM,SAAS,GAAG,6FAA6F,CAAC;AAChH,MAAM,aAAa,GAAG,kFAAkF,CAAC;AACzG,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AAEpD,SAAS,cAAc,CAAC,KAA4B,EAAE,MAAc,EAAE,OAA0B;IAC9F,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IACnC,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;QAC1H,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,WAAW,MAAM,gBAAgB,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,I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AE,cAAc,EAAE,WAAW,EAAE,iCAAiC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,OAAO,OAAO,EAAE,CAAC,EAAE;YACrI,EAAE,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,oCAAoC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,0BAA0B,EAAE,eAAe,EAAE,OAAO,OAAO,EAAE,CAAC,EAAE;YACrL,EAAE,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,8CAA8C,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE;YAC1J,EAAE,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,6BAA6B,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,OAAO,CAAC,IAAI,SAAS,EAAE,OAAO,CAAC,EAAE;YAC1K,EAAE,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,6BAA6B,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,OAAO,CAAC,IAAI,SAAS,EAAE,OAAO,CAAC,EAAE;SAC3K,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEH,qFAAqF;AACrF,MAAM,CAAC,MAAM,oBAAoB,GAA2C,MAAM,CAAC,MAAM,CAAC;IACxF,MAAM,EAAE,YAAuC,EAAE,OAAO,EAAE,aAAwC,EAAE,UAAU,EAAE,gBAA2C;CAC5J,CAAC,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type JsonValue } from '@mayura/core';\nimport { defineDeployTarget, type DeployProject, type DeployRelease, type DeployStep, type DeployTarget } from './deploy.js';\n\n// The container targets every Mayura app can use without a platform package: an image, Docker Compose and Kubernetes.\n\nconst nodeImage = 'node:24.14.1-alpine@sha256:8510330d3eb72c804231a834b1a8ebb55cb3796c3e4431297a24d246b8add4d5';\nconst postgresImage = 'postgres@sha256:f02121de6f74d30d8a94cd1d9584125e2178d7e6c377d8130112d4e52d867995';\n/** In the Kubernetes manifests: the image and the release, replaced when a release is planned. */\nexport const IMAGE_PLACEHOLDER = 'mayura-app-image';\nexport const RELEASE_PLACEHOLDER = 'mayura-release';\n\nfunction settingsObject(value: JsonValue | undefined, target: string, allowed: readonly string[]): JsonObject {\n if (value === undefined) return {};\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !allowed.includes(key))) {\n throw new MayuraError('INVALID_CONFIG', `targets.${target} allows only ${allowed.length ? allowed.join(', ') : 'no settings'}.`);\n }\n return value;\n}\nfunction needImage(release: DeployRelease, target: string): string {\n if (release.image === undefined) throw new MayuraError('INVALID_CONFIG', `The ${target} target pushes an image: set \"image\" in mayura.deploy.json.`);\n return release.image;\n}\n\n/**\n * The application image: built once, it runs any role. With `entrypoint: false` it has no entry point, and its default\n * command is the full `node …/bin.js serve` line, for platforms whose start commands replace the entry point.\n */\nexport function dockerfile(project: DeployProject, options: { readonly entrypoint?: boolean } = {}): string {\n const cli = 'node_modules/mayura/lib/cli/dist/bin.js';\n const start = options.entrypoint === false\n ? `CMD [\"node\", \"${cli}\", \"serve\", \"--app\", \"${project.app}\"]`\n : `ENTRYPOINT [\"node\", \"${cli}\"]\nCMD [\"serve\", \"--app\", \"${project.app}\"]`;\n return `# One image for every role; the command chooses serve, worker or migrate.\nFROM ${nodeImage} AS build\nWORKDIR /app\nCOPY package.json package-lock.json* ./\nRUN npm install --no-audit --no-fund\nCOPY . .\nRUN npx tsc -p tsconfig.json && npm prune --omit=dev\n\nFROM ${nodeImage}\nWORKDIR /app\nCOPY --from=build --chown=65532:65532 /app/package.json ./\nCOPY --from=build --chown=65532:65532 /app/node_modules ./node_modules\nCOPY --from=build --chown=65532:65532 /app/dist ./dist\nUSER 65532:65532\nENV NODE_ENV=production MAYURA_ENV=production\nEXPOSE ${project.port} ${project.probePort}\n${start}\n`;\n}\nexport const dockerignore = 'node_modules\\ndist\\n.data\\n.env\\n.env.*\\n*.sqlite*\\n.git\\n';\n\n/** Build and push the release's image: the first steps of every target that runs it somewhere else. */\nexport function imageSteps(release: DeployRelease, target: string): DeployStep[] {\n const image = needImage(release, target);\n return [\n { id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--tag', image, '.'] },\n { id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },\n ];\n}\n\nexport const dockerTarget = defineDeployTarget<Record<string, never>>({\n id: 'docker', description: 'Build the application image and push it to its registry.', tools: ['docker'],\n settings: value => { settingsObject(value, 'docker', []); return {}; },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore }),\n plan: ({ release }) => imageSteps(release, 'docker'),\n});\n\nfunction composeFile(project: DeployProject): string {\n const database = `postgres://app:\\${POSTGRES_PASSWORD}@postgres:5432/app`;\n // BusyBox wget is in the Alpine Node image; it exits non-zero unless /readyz answers 2xx.\n const probe = (portNumber: number) => `[\"CMD\", \"wget\", \"-q\", \"-O\", \"/dev/null\", \"http://127.0.0.1:${portNumber}/readyz\"]`;\n return `# Production-shaped stack: PostgreSQL, a one-shot migration, the server and a worker, from one image.\n# Put a TLS proxy in front of \\`server\\`; it must forward to port ${project.port} with the public origin's Host.\n# cp .env.example .env # set POSTGRES_PASSWORD and the app's variables\nservices:\n postgres:\n image: ${postgresImage}\n environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: \"\\${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}\", POSTGRES_DB: app }\n volumes: [postgres-data:/var/lib/postgresql/data]\n healthcheck: { test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"], interval: 2s, timeout: 5s, retries: 30 }\n migrate:\n build: .\n command: [\"migrate\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { postgres: { condition: service_healthy } }\n server:\n build: .\n command: [\"serve\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n ports: [\"${project.port}:${project.port}\"]\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.port)}, interval: 5s, timeout: 5s, retries: 30 }\n worker:\n build: .\n command: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.probePort)}, interval: 5s, timeout: 5s, retries: 30 }\nvolumes:\n postgres-data:\n`;\n}\n\nexport const composeTarget = defineDeployTarget<{ readonly projectName?: string }>({\n id: 'compose', description: 'Run PostgreSQL, the migration, the server and a worker with Docker Compose.', tools: ['docker'],\n settings: value => {\n const settings = settingsObject(value, 'compose', ['projectName']); const projectName = settings['projectName'];\n if (projectName !== undefined && (typeof projectName !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(projectName))) throw new MayuraError('INVALID_CONFIG', 'targets.compose.projectName must be a Compose project name.');\n return projectName === undefined ? {} : { projectName };\n },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore, 'compose.yaml': composeFile(project) }),\n plan: ({ project, settings }) => {\n const compose = ['compose', '--project-name', settings.projectName ?? project.name];\n return [\n { id: 'build', description: 'Build the image', tool: 'docker', args: [...compose, 'build'] },\n { id: 'migrate', description: 'Migrate storage, once, before the new release serves', tool: 'docker', args: [...compose, 'run', '--rm', 'migrate'] },\n { id: 'start', description: 'Start or update the server and the worker, and wait until they are healthy', tool: 'docker', args: [...compose, 'up', '--detach', '--wait', 'server', 'worker'] },\n ];\n },\n});\n\ninterface KubernetesSettings { readonly namespace: string; readonly context?: string; readonly secret: string; readonly serverReplicas: number; readonly workerReplicas: number; readonly timeoutSeconds: number }\n\nconst dns = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\nfunction count(value: JsonValue | undefined, fallback: number, max: number, what: string): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > max) throw new MayuraError('INVALID_CONFIG', `targets.kubernetes.${what} must be a whole number from 1 to ${max}.`);\n return value;\n}\n\nfunction migrationJob(project: DeployProject, settings: KubernetesSettings): string {\n return `# One Job per release, run to completion before the rollout. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} and\n# ${RELEASE_PLACEHOLDER} with the release's image and tag; keep both when you edit this file.\napiVersion: batch/v1\nkind: Job\nmetadata:\n name: ${project.name}-migrate-${RELEASE_PLACEHOLDER}\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: migrate }\nspec:\n backoffLimit: 0\n ttlSecondsAfterFinished: 86400\n template:\n spec:\n restartPolicy: Never\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: migrate\n image: ${IMAGE_PLACEHOLDER}\n args: [\"migrate\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n`;\n}\nfunction serverManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# The HTTP server and its Service. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n replicas: ${settings.serverReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: server\n image: ${IMAGE_PLACEHOLDER}\n args: [\"serve\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n ports: [{ containerPort: ${project.port} }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.port} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.port} }, periodSeconds: 10 }\n---\napiVersion: v1\nkind: Service\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n selector: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n ports: [{ port: 80, targetPort: ${project.port} }]\n`;\n}\nfunction workerManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# Workflow workers: one leads, the rest stand by. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-worker\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\nspec:\n replicas: ${settings.workerReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: worker\n image: ${IMAGE_PLACEHOLDER}\n args: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n env: [{ name: MAYURA_WORKER_ID, valueFrom: { fieldRef: { fieldPath: metadata.name } } }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.probePort} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.probePort} }, periodSeconds: 10 }\n`;\n}\n\nconst manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/kubernetes/server.yaml', worker: 'deploy/kubernetes/worker.yaml' } as const;\n\n/**\n * A release tag as it may appear in a Kubernetes name: lowercase, `.` and `_` as `-`, at most 13 characters, so that\n * `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).\n */\nexport function releaseSlug(tag: string): string {\n const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+|-+$/gu, '').slice(0, 13).replace(/-+$/u, '');\n return slug || 'release';\n}\nfunction render(manifest: string, path: string, image: string, slug: string): string {\n if (!manifest.includes(IMAGE_PLACEHOLDER)) throw new MayuraError('INVALID_CONFIG', `${path} must keep the image placeholder ${IMAGE_PLACEHOLDER}.`);\n return manifest.replaceAll(IMAGE_PLACEHOLDER, image).replaceAll(RELEASE_PLACEHOLDER, slug);\n}\n\nexport const kubernetesTarget = defineDeployTarget<KubernetesSettings>({\n id: 'kubernetes', description: 'Build and push the image, run the migration Job, then roll out the server and worker with kubectl.', tools: ['docker', 'kubectl'],\n settings: value => {\n const settings = settingsObject(value, 'kubernetes', ['namespace', 'context', 'secret', 'serverReplicas', 'workerReplicas', 'timeoutSeconds']);\n const namespace = settings['namespace'] ?? 'default'; const context = settings['context']; const secret = settings['secret'];\n if (typeof namespace !== 'string' || !dns.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.namespace must be a Kubernetes namespace name.');\n if (context !== undefined && (typeof context !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,252}$/u.test(context))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.context must be a kubeconfig context name.');\n if (secret !== undefined && (typeof secret !== 'string' || !dns.test(secret))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.secret must be a Secret name.');\n return { namespace, ...(context === undefined ? {} : { context: context as string }), secret: (secret as string | undefined) ?? '',\n serverReplicas: count(settings['serverReplicas'], 2, 100, 'serverReplicas'), workerReplicas: count(settings['workerReplicas'], 2, 100, 'workerReplicas'),\n timeoutSeconds: count(settings['timeoutSeconds'], 600, 3_600, 'timeoutSeconds') };\n },\n files: ({ project, settings }) => {\n const resolved = { ...settings, secret: settings.secret || `${project.name}-env` };\n return { Dockerfile: dockerfile(project), '.dockerignore': dockerignore,\n [manifests.job]: migrationJob(project, resolved), [manifests.server]: serverManifest(project, resolved), [manifests.worker]: workerManifest(project, resolved) };\n },\n plan: async ({ project, settings, release, readFile }) => {\n const image = needImage(release, 'kubernetes'); const slug = releaseSlug(release.tag);\n const kubectl = [...(settings.context === undefined ? [] : ['--context', settings.context]), '--namespace', settings.namespace];\n const job = render(await readFile(manifests.job), manifests.job, image, slug);\n const workloads = `${render(await readFile(manifests.server), manifests.server, image, slug)}---\\n${render(await readFile(manifests.worker), manifests.worker, image, slug)}`;\n const jobName = `${project.name}-migrate-${slug}`; const timeout = `--timeout=${settings.timeoutSeconds}s`;\n return [\n ...imageSteps(release, 'kubernetes'),\n { id: 'migrate', description: `Start the migration Job ${jobName}`, tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: job },\n // A Job's first condition appears only once it has an outcome (SuccessCriteriaMet or Complete, FailureTarget or\n // Failed), so this returns as soon as the migration succeeds or fails, instead of waiting out the timeout.\n { id: 'migrate-finish', description: 'Wait for the migration to finish', tool: 'kubectl', args: [...kubectl, 'wait', '--for=jsonpath={.status.conditions[0].type}', timeout, `job/${jobName}`] },\n { id: 'migrate-logs', description: 'Show what the migration printed', tool: 'kubectl', args: [...kubectl, 'logs', `job/${jobName}`] },\n { id: 'migrate-wait', description: 'Check that the migration succeeded', tool: 'kubectl', args: [...kubectl, 'wait', '--for=condition=complete', '--timeout=30s', `job/${jobName}`] },\n { id: 'roll-out', description: 'Apply the server and worker at the new image', tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: workloads },\n { id: 'server-ready', description: 'Wait for the server rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-server`, timeout] },\n { id: 'worker-ready', description: 'Wait for the worker rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-worker`, timeout] },\n ];\n },\n});\n\n/** The targets every project has. Others come from `@mayurajs/deploy-*` packages. */\nexport const builtInDeployTargets: Readonly<Record<string, DeployTarget>> = Object.freeze({\n docker: dockerTarget as unknown as DeployTarget, compose: composeTarget as unknown as DeployTarget, kubernetes: kubernetesTarget as unknown as DeployTarget,\n});\n"]}
|
|
1
|
+
{"version":3,"file":"deploy-targets.js","sourceRoot":"","sources":["../src/deploy-targets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmC,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAA8E,MAAM,aAAa,CAAC;AAE7H,sHAAsH;AAEtH,MAAM,SAAS,GAAG,6FAA6F,CAAC;AAChH,MAAM,aAAa,GAAG,kFAAkF,CAAC;AACzG,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AAEpD,SAAS,cAAc,CAAC,KAA4B,EAAE,MAAc,EAAE,OAA0B;IAC9F,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IACnC,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;QAC1H,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,WAAW,MAAM,gBAAgB,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,aAAa,GAAG,CAAC,CAAC;IACnI,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AACD,SAAS,SAAS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EAAE,CAAC,EAAE;YACrI,EAAE,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,oCAAoC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,0BAA0B,EAAE,eAAe,EAAE,OAAO,OAAO,EAAE,CAAC,EAAE;YACrL,EAAE,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,8CAA8C,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE;YAC1J,EAAE,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,6BAA6B,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,OAAO,CAAC,IAAI,SAAS,EAAE,OAAO,CAAC,EAAE;YAC1K,EAAE,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,6BAA6B,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,OAAO,CAAC,IAAI,SAAS,EAAE,OAAO,CAAC,EAAE;SAC3K,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEH,qFAAqF;AACrF,MAAM,CAAC,MAAM,oBAAoB,GAA2C,MAAM,CAAC,MAAM,CAAC;IACxF,MAAM,EAAE,YAAuC,EAAE,OAAO,EAAE,aAAwC,EAAE,UAAU,EAAE,gBAA2C;CAC5J,CAAC,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type JsonValue } from '@mayura/core';\nimport { defineDeployTarget, type DeployProject, type DeployRelease, type DeployStep, type DeployTarget } from './deploy.js';\n\n// The container targets every Mayura app can use without a platform package: an image, Docker Compose and Kubernetes.\n\nconst nodeImage = 'node:24.14.1-alpine@sha256:8510330d3eb72c804231a834b1a8ebb55cb3796c3e4431297a24d246b8add4d5';\nconst postgresImage = 'postgres@sha256:f02121de6f74d30d8a94cd1d9584125e2178d7e6c377d8130112d4e52d867995';\n/** In the Kubernetes manifests: the image and the release, replaced when a release is planned. */\nexport const IMAGE_PLACEHOLDER = 'mayura-app-image';\nexport const RELEASE_PLACEHOLDER = 'mayura-release';\n\nfunction settingsObject(value: JsonValue | undefined, target: string, allowed: readonly string[]): JsonObject {\n if (value === undefined) return {};\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !allowed.includes(key))) {\n throw new MayuraError('INVALID_CONFIG', `targets.${target} allows only ${allowed.length ? allowed.join(', ') : 'no settings'}.`);\n }\n return value;\n}\nfunction needImage(release: DeployRelease, target: string): string {\n if (release.image === undefined) throw new MayuraError('INVALID_CONFIG', `The ${target} target pushes an image: set \"image\" in mayura.deploy.json.`);\n return release.image;\n}\n\n/**\n * The application image: built once, it runs any role. With `entrypoint: false` it has no entry point, and its default\n * command is the full `node …/bin.js serve` line, for platforms whose start commands replace the entry point.\n */\nexport function dockerfile(project: DeployProject, options: { readonly entrypoint?: boolean } = {}): string {\n const cli = 'node_modules/mayura/lib/cli/dist/bin.js';\n const start = options.entrypoint === false\n ? `CMD [\"node\", \"${cli}\", \"serve\", \"--app\", \"${project.app}\"]`\n : `ENTRYPOINT [\"node\", \"${cli}\"]\nCMD [\"serve\", \"--app\", \"${project.app}\"]`;\n return `# One image for every role; the command chooses serve, worker or migrate.\nFROM ${nodeImage} AS build\nWORKDIR /app\nCOPY package.json package-lock.json* ./\nRUN npm install --no-audit --no-fund\nCOPY . .\nRUN npx tsc -p tsconfig.json && npm prune --omit=dev\n\nFROM ${nodeImage}\nWORKDIR /app\nCOPY --from=build --chown=65532:65532 /app/package.json ./\nCOPY --from=build --chown=65532:65532 /app/node_modules ./node_modules\nCOPY --from=build --chown=65532:65532 /app/dist ./dist\nUSER 65532:65532\nENV NODE_ENV=production MAYURA_ENV=production\nEXPOSE ${project.port} ${project.probePort}\n${start}\n`;\n}\nexport const dockerignore = 'node_modules\\ndist\\n.data\\n.env\\n.env.*\\n*.sqlite*\\n.git\\n';\n\n/** Build and push the release's image: the first steps of every target that runs it somewhere else. */\nexport function imageSteps(release: DeployRelease, target: string): DeployStep[] {\n const image = needImage(release, target);\n return [\n { id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--tag', image, '.'] },\n { id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },\n ];\n}\n\nexport const dockerTarget = defineDeployTarget<Record<string, never>>({\n id: 'docker', description: 'Build the application image and push it to its registry.', tools: ['docker'],\n settings: value => { settingsObject(value, 'docker', []); return {}; },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore }),\n plan: ({ release }) => imageSteps(release, 'docker'),\n});\n\nfunction composeFile(project: DeployProject): string {\n const database = `postgres://app:\\${POSTGRES_PASSWORD}@postgres:5432/app`;\n // BusyBox wget is in the Alpine Node image; it exits non-zero unless /readyz answers 2xx.\n const probe = (portNumber: number) => `[\"CMD\", \"wget\", \"-q\", \"-O\", \"/dev/null\", \"http://127.0.0.1:${portNumber}/readyz\"]`;\n return `# Production-shaped stack: PostgreSQL, a one-shot migration, the server and a worker, from one image.\n# Put a TLS proxy in front of \\`server\\`; it must forward to port ${project.port} with the public origin's Host.\n# cp .env.example .env # set POSTGRES_PASSWORD and the app's variables\nservices:\n postgres:\n image: ${postgresImage}\n environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: \"\\${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}\", POSTGRES_DB: app }\n volumes: [postgres-data:/var/lib/postgresql/data]\n healthcheck: { test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"], interval: 2s, timeout: 5s, retries: 30 }\n migrate:\n build: .\n command: [\"migrate\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { postgres: { condition: service_healthy } }\n server:\n build: .\n command: [\"serve\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n ports: [\"${project.port}:${project.port}\"]\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.port)}, interval: 5s, timeout: 5s, retries: 30 }\n worker:\n build: .\n command: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.probePort)}, interval: 5s, timeout: 5s, retries: 30 }\nvolumes:\n postgres-data:\n`;\n}\n\nexport const composeTarget = defineDeployTarget<{ readonly projectName?: string }>({\n id: 'compose', description: 'Run PostgreSQL, the migration, the server and a worker with Docker Compose.', tools: ['docker'],\n settings: value => {\n const settings = settingsObject(value, 'compose', ['projectName']); const projectName = settings['projectName'];\n if (projectName !== undefined && (typeof projectName !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(projectName))) throw new MayuraError('INVALID_CONFIG', 'targets.compose.projectName must be a Compose project name.');\n return projectName === undefined ? {} : { projectName };\n },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore, 'compose.yaml': composeFile(project) }),\n plan: ({ project, settings }) => {\n const compose = ['compose', '--project-name', settings.projectName ?? project.name];\n return [\n { id: 'build', description: 'Build the image', tool: 'docker', args: [...compose, 'build'] },\n { id: 'migrate', description: 'Migrate storage, once, before the new release serves', tool: 'docker', args: [...compose, 'run', '--rm', 'migrate'] },\n { id: 'start', description: 'Start or update the server and the worker, and wait until they are healthy', tool: 'docker', args: [...compose, 'up', '--detach', '--wait', 'server', 'worker'] },\n ];\n },\n});\n\ninterface KubernetesSettings { readonly namespace: string; readonly context?: string; readonly secret: string; readonly serverReplicas: number; readonly workerReplicas: number; readonly timeoutSeconds: number }\n\nconst dns = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\nfunction count(value: JsonValue | undefined, fallback: number, max: number, what: string): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > max) throw new MayuraError('INVALID_CONFIG', `targets.kubernetes.${what} must be a whole number from 1 to ${max}.`);\n return value;\n}\n\nfunction migrationJob(project: DeployProject, settings: KubernetesSettings): string {\n return `# One Job per release, run to completion before the rollout. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} and\n# ${RELEASE_PLACEHOLDER} with the release's image and tag; keep both when you edit this file.\napiVersion: batch/v1\nkind: Job\nmetadata:\n name: ${project.name}-migrate-${RELEASE_PLACEHOLDER}\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: migrate }\nspec:\n backoffLimit: 0\n ttlSecondsAfterFinished: 86400\n template:\n spec:\n restartPolicy: Never\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: migrate\n image: ${IMAGE_PLACEHOLDER}\n args: [\"migrate\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n`;\n}\nfunction serverManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# The HTTP server and its Service. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n replicas: ${settings.serverReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: server\n image: ${IMAGE_PLACEHOLDER}\n args: [\"serve\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n ports: [{ containerPort: ${project.port} }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.port} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.port} }, periodSeconds: 10 }\n---\napiVersion: v1\nkind: Service\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n selector: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n ports: [{ port: 80, targetPort: ${project.port} }]\n`;\n}\nfunction workerManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# Workflow workers: one leads, the rest stand by. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-worker\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\nspec:\n replicas: ${settings.workerReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: worker\n image: ${IMAGE_PLACEHOLDER}\n args: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n env: [{ name: MAYURA_WORKER_ID, valueFrom: { fieldRef: { fieldPath: metadata.name } } }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.probePort} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.probePort} }, periodSeconds: 10 }\n`;\n}\n\nconst manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/kubernetes/server.yaml', worker: 'deploy/kubernetes/worker.yaml' } as const;\n\n/**\n * A release tag as it may appear in a Kubernetes name: lowercase, `.` and `_` as `-`, at most 13 characters, so that\n * `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).\n */\nexport function releaseSlug(tag: string): string {\n const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+/u, '').slice(0, 13).replace(/-+$/u, '');\n return slug || 'release';\n}\nfunction render(manifest: string, path: string, image: string, slug: string): string {\n if (!manifest.includes(IMAGE_PLACEHOLDER)) throw new MayuraError('INVALID_CONFIG', `${path} must keep the image placeholder ${IMAGE_PLACEHOLDER}.`);\n return manifest.replaceAll(IMAGE_PLACEHOLDER, image).replaceAll(RELEASE_PLACEHOLDER, slug);\n}\n\nexport const kubernetesTarget = defineDeployTarget<KubernetesSettings>({\n id: 'kubernetes', description: 'Build and push the image, run the migration Job, then roll out the server and worker with kubectl.', tools: ['docker', 'kubectl'],\n settings: value => {\n const settings = settingsObject(value, 'kubernetes', ['namespace', 'context', 'secret', 'serverReplicas', 'workerReplicas', 'timeoutSeconds']);\n const namespace = settings['namespace'] ?? 'default'; const context = settings['context']; const secret = settings['secret'];\n if (typeof namespace !== 'string' || !dns.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.namespace must be a Kubernetes namespace name.');\n if (context !== undefined && (typeof context !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,252}$/u.test(context))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.context must be a kubeconfig context name.');\n if (secret !== undefined && (typeof secret !== 'string' || !dns.test(secret))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.secret must be a Secret name.');\n return { namespace, ...(context === undefined ? {} : { context: context as string }), secret: (secret as string | undefined) ?? '',\n serverReplicas: count(settings['serverReplicas'], 2, 100, 'serverReplicas'), workerReplicas: count(settings['workerReplicas'], 2, 100, 'workerReplicas'),\n timeoutSeconds: count(settings['timeoutSeconds'], 600, 3_600, 'timeoutSeconds') };\n },\n files: ({ project, settings }) => {\n const resolved = { ...settings, secret: settings.secret || `${project.name}-env` };\n return { Dockerfile: dockerfile(project), '.dockerignore': dockerignore,\n [manifests.job]: migrationJob(project, resolved), [manifests.server]: serverManifest(project, resolved), [manifests.worker]: workerManifest(project, resolved) };\n },\n plan: async ({ project, settings, release, readFile }) => {\n const image = needImage(release, 'kubernetes'); const slug = releaseSlug(release.tag);\n const kubectl = [...(settings.context === undefined ? [] : ['--context', settings.context]), '--namespace', settings.namespace];\n const job = render(await readFile(manifests.job), manifests.job, image, slug);\n const workloads = `${render(await readFile(manifests.server), manifests.server, image, slug)}---\\n${render(await readFile(manifests.worker), manifests.worker, image, slug)}`;\n const jobName = `${project.name}-migrate-${slug}`; const timeout = `--timeout=${settings.timeoutSeconds}s`;\n return [\n ...imageSteps(release, 'kubernetes'),\n { id: 'migrate', description: `Start the migration Job ${jobName}`, tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: job },\n // A Job's first condition appears only once it has an outcome (SuccessCriteriaMet or Complete, FailureTarget or\n // Failed), so this returns as soon as the migration succeeds or fails, instead of waiting out the timeout.\n { id: 'migrate-finish', description: 'Wait for the migration to finish', tool: 'kubectl', args: [...kubectl, 'wait', '--for=jsonpath={.status.conditions[0].type}', timeout, `job/${jobName}`] },\n { id: 'migrate-logs', description: 'Show what the migration printed', tool: 'kubectl', args: [...kubectl, 'logs', `job/${jobName}`] },\n { id: 'migrate-wait', description: 'Check that the migration succeeded', tool: 'kubectl', args: [...kubectl, 'wait', '--for=condition=complete', '--timeout=30s', `job/${jobName}`] },\n { id: 'roll-out', description: 'Apply the server and worker at the new image', tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: workloads },\n { id: 'server-ready', description: 'Wait for the server rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-server`, timeout] },\n { id: 'worker-ready', description: 'Wait for the worker rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-worker`, timeout] },\n ];\n },\n});\n\n/** The targets every project has. Others come from `@mayurajs/deploy-*` packages. */\nexport const builtInDeployTargets: Readonly<Record<string, DeployTarget>> = Object.freeze({\n docker: dockerTarget as unknown as DeployTarget, compose: composeTarget as unknown as DeployTarget, kubernetes: kubernetesTarget as unknown as DeployTarget,\n});\n"]}
|
package/lib/cli/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export type TemplateName = typeof TEMPLATE_NAMES[number];
|
|
|
4
4
|
/** Versions of the third-party packages generated projects install; kept equal to the workspace's (tested). */
|
|
5
5
|
export declare const PEER_VERSIONS: Readonly<Record<string, string>>;
|
|
6
6
|
/** Complete multi-file projects: offline by default, one environment switch to a real provider or PostgreSQL. */
|
|
7
|
-
export declare const STARTER_NAMES: readonly ["approval-workflow", "support-agent", "research-team", "event-automation", "cli-agent", "nextjs", "hono", "react-router", "tanstack-start", "sveltekit", "nuxt"];
|
|
7
|
+
export declare const STARTER_NAMES: readonly ["approval-workflow", "support-agent", "research-team", "event-automation", "cli-agent", "nextjs", "hono", "react-router", "tanstack-start", "sveltekit", "nuxt", "rag-modal-pinecone"];
|
|
8
8
|
export type StarterName = typeof STARTER_NAMES[number];
|
|
9
9
|
export interface ProjectToolRecord {
|
|
10
10
|
readonly id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,SAAS,EAAE,cAAc,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,UAAU,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,eAAe,EAAE,gBAAgB,EAC7M,iBAAiB,EAAE,oBAAoB,EAAE,aAAa,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,cAAc,EAAE,cAAc,EAAE,kBAAkB,EAAE,UAAU,EACjK,KAAK,oBAAoB,EAAE,KAAK,qBAAqB,EAAE,KAAK,4BAA4B,EACxF,KAAK,wBAAwB,EAAE,KAAK,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LToPath } from 'node:url';
|
|
5
5
|
import { MayuraError, freezeJson, jsonValue } from '../../core/dist/index.js';
|
|
6
|
+
import { sha256Hex } from '../../core/dist/host.js';
|
|
6
7
|
import { agentGuide } from './agent-guide.js';
|
|
7
8
|
import { assertSafeDirectory, canonicalTarget, digest, planChanges, writePlannedFiles } from './files.js';
|
|
8
9
|
export { OperationalRequestError, approveWorkflow, cancelRun, cancelWorkflow, inspectHumanRequest, inspectHumanRequests, inspectRun, inspectServerHealth, inspectServerTools, inspectWorkflow, inspectWorkflows, holdWorkflowFleet, inspectWorkflowFleet, pauseWorkflow, releaseWorkflowFleet, respondHumanRequest, resumeWorkflow, signalWorkflow, sweepWorkflowFleet, waitForRun } from './operations.js';
|
|
@@ -36,7 +37,7 @@ export const PEER_VERSIONS = Object.freeze({
|
|
|
36
37
|
'better-sqlite3': '13.0.3', pg: '8.23.0', '@jitl/quickjs-wasmfile-release-sync': '0.32.0', 'quickjs-emscripten-core': '0.32.0',
|
|
37
38
|
});
|
|
38
39
|
/** Complete multi-file projects: offline by default, one environment switch to a real provider or PostgreSQL. */
|
|
39
|
-
export const STARTER_NAMES = Object.freeze(['approval-workflow', 'support-agent', 'research-team', 'event-automation', 'cli-agent', 'nextjs', 'hono', 'react-router', 'tanstack-start', 'sveltekit', 'nuxt']);
|
|
40
|
+
export const STARTER_NAMES = Object.freeze(['approval-workflow', 'support-agent', 'research-team', 'event-automation', 'cli-agent', 'nextjs', 'hono', 'react-router', 'tanstack-start', 'sveltekit', 'nuxt', 'rag-modal-pinecone']);
|
|
40
41
|
const starterDescriptions = Object.freeze({
|
|
41
42
|
'approval-workflow': 'Durable refund approvals: triage agent, human approval, separate server and worker, operator console and a reviewed v1 to v2 migration.',
|
|
42
43
|
'support-agent': 'Customer support chat: a streaming agent with order tools scoped to the signed-in customer, per-customer native memory, PII redaction, a React chat UI and the operator console.',
|
|
@@ -49,6 +50,7 @@ const starterDescriptions = Object.freeze({
|
|
|
49
50
|
'tanstack-start': 'TanStack Start notebook: scoped persistent threads, exact in-run approvals, local deterministic models and background workflow processing.',
|
|
50
51
|
'sveltekit': 'SvelteKit notebook: scoped persistent threads, exact in-run approvals, local deterministic models and background workflow processing.',
|
|
51
52
|
'nuxt': 'Nuxt notebook: scoped persistent threads, exact in-run approvals, local deterministic models and background workflow processing.',
|
|
53
|
+
'rag-modal-pinecone': 'Retrieval agent with durable Markdown ingestion, exact citations, an offline demo and an opt-in Modal + Pinecone deployment.',
|
|
52
54
|
});
|
|
53
55
|
const id = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;
|
|
54
56
|
const templateRoot = fileURLToPath(new URL('../templates/', import.meta.url));
|
|
@@ -57,6 +59,7 @@ const starterRoot = fileURLToPath(new URL('../starters/', import.meta.url));
|
|
|
57
59
|
const starterLimits = Object.freeze({ files: 256, fileBytes: 262_144, totalBytes: 4_194_304 });
|
|
58
60
|
// Build output, installs and local state never leave the repository copy of a starter.
|
|
59
61
|
const starterSkipped = new Set(['node_modules', 'dist', 'build', '.data', 'coverage']);
|
|
62
|
+
const starterWorkspaceDependencies = new Set(['mayura', '@mayurajs/storage-d1', '@mayurajs/vector-pinecone']);
|
|
60
63
|
const plans = new WeakMap();
|
|
61
64
|
function projectName(directory) {
|
|
62
65
|
const name = directory.replaceAll('\\', '/').split('/').filter(Boolean).at(-1)?.toLowerCase().replace(/[^a-z0-9-]+/g, '-') ?? '';
|
|
@@ -108,41 +111,81 @@ export async function planProject(template, directory) {
|
|
|
108
111
|
}
|
|
109
112
|
// Starter files that npm would drop or rename when packing (.gitignore, .github) are stored with a `dot-` prefix.
|
|
110
113
|
const starterPath = (segments) => segments.map(segment => segment.startsWith('dot-') ? `.${segment.slice(4)}` : segment).join('/');
|
|
114
|
+
const starterSegment = /^[A-Za-z0-9_+$\[\]][A-Za-z0-9._+$\[\]-]{0,99}$/u;
|
|
115
|
+
/** Published copies can share identical source assets. A workspace starter uses its own full tree. */
|
|
116
|
+
async function sharedStarterFiles(name) {
|
|
117
|
+
const path = fileURLToPath(new URL('../starter-assets/manifest.json', import.meta.url));
|
|
118
|
+
try {
|
|
119
|
+
const details = await lstat(path);
|
|
120
|
+
if (!details.isFile() || details.size > 262_144)
|
|
121
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Shared starter manifest is invalid.');
|
|
122
|
+
const manifest = await readFile(path, 'utf8');
|
|
123
|
+
const entries = JSON.parse(manifest)[name];
|
|
124
|
+
if (entries === undefined)
|
|
125
|
+
return {};
|
|
126
|
+
if (entries === null || typeof entries !== 'object' || Array.isArray(entries))
|
|
127
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Shared starter entries are invalid.');
|
|
128
|
+
return entries;
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error.code === 'ENOENT')
|
|
132
|
+
return {};
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
111
136
|
async function collectStarter(name) {
|
|
112
137
|
const root = resolve(starterRoot, name);
|
|
113
138
|
const files = new Map();
|
|
114
139
|
let total = 0;
|
|
140
|
+
const collect = async (path, segments, expected) => {
|
|
141
|
+
const details = await lstat(path);
|
|
142
|
+
if (!details.isFile() || details.isSymbolicLink() || details.size > starterLimits.fileBytes)
|
|
143
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter contains an unsupported file type or size.');
|
|
144
|
+
total += details.size;
|
|
145
|
+
if (files.size >= starterLimits.files || total > starterLimits.totalBytes)
|
|
146
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter exceeds its file bounds.');
|
|
147
|
+
const bytes = await readFile(path);
|
|
148
|
+
let content;
|
|
149
|
+
try {
|
|
150
|
+
content = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter files must be UTF-8 text.');
|
|
154
|
+
}
|
|
155
|
+
if (expected !== undefined && sha256Hex(bytes) !== expected)
|
|
156
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Shared starter file differs from its manifest.');
|
|
157
|
+
const target = starterPath(segments);
|
|
158
|
+
if (files.has(target))
|
|
159
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter file paths overlap.');
|
|
160
|
+
files.set(target, content);
|
|
161
|
+
};
|
|
115
162
|
const walk = async (segments) => {
|
|
116
163
|
const entries = await readdir(resolve(root, ...segments), { withFileTypes: true });
|
|
117
164
|
for (const entry of entries.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)) {
|
|
118
165
|
if (starterSkipped.has(entry.name) || entry.name.startsWith('.') || entry.name.endsWith('.tsbuildinfo'))
|
|
119
166
|
continue;
|
|
120
|
-
if (
|
|
167
|
+
if (!starterSegment.test(entry.name))
|
|
121
168
|
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter contains an unsupported file name.');
|
|
122
169
|
const next = [...segments, entry.name];
|
|
123
170
|
if (entry.isDirectory()) {
|
|
124
171
|
await walk(next);
|
|
125
172
|
continue;
|
|
126
173
|
}
|
|
127
|
-
|
|
128
|
-
const details = await lstat(path);
|
|
129
|
-
if (!details.isFile() || details.isSymbolicLink() || details.size > starterLimits.fileBytes)
|
|
130
|
-
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter contains an unsupported file type or size.');
|
|
131
|
-
total += details.size;
|
|
132
|
-
if (files.size >= starterLimits.files || total > starterLimits.totalBytes)
|
|
133
|
-
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter exceeds its file bounds.');
|
|
134
|
-
let content;
|
|
135
|
-
try {
|
|
136
|
-
content = new TextDecoder('utf-8', { fatal: true }).decode(await readFile(path));
|
|
137
|
-
}
|
|
138
|
-
catch {
|
|
139
|
-
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter files must be UTF-8 text.');
|
|
140
|
-
}
|
|
141
|
-
files.set(starterPath(next), content);
|
|
174
|
+
await collect(resolve(root, ...next), next);
|
|
142
175
|
}
|
|
143
176
|
};
|
|
144
177
|
await walk([]);
|
|
145
|
-
|
|
178
|
+
const sharedRoot = fileURLToPath(new URL('../starter-assets/', import.meta.url));
|
|
179
|
+
for (const [path, expected] of Object.entries(await sharedStarterFiles(name))) {
|
|
180
|
+
const segments = path.split('/');
|
|
181
|
+
if (!segments.every(segment => starterSegment.test(segment) && !starterSkipped.has(segment) && !segment.endsWith('.tsbuildinfo')) ||
|
|
182
|
+
typeof expected !== 'string' || !/^[a-f0-9]{64}$/u.test(expected)) {
|
|
183
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Shared starter file has an invalid path or digest.');
|
|
184
|
+
}
|
|
185
|
+
await collect(resolve(sharedRoot, expected), segments, expected);
|
|
186
|
+
}
|
|
187
|
+
// Planning hashes the ordered changes. Keep the workspace and packaged file order identical.
|
|
188
|
+
return new Map([...files].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0));
|
|
146
189
|
}
|
|
147
190
|
/** The repository copy links Mayura packages with `workspace:*`; a generated project pins this CLI's exact release. */
|
|
148
191
|
async function starterManifest(content, name) {
|
|
@@ -152,10 +195,10 @@ async function starterManifest(content, name) {
|
|
|
152
195
|
for (const field of ['dependencies', 'devDependencies']) {
|
|
153
196
|
const entries = manifest[field];
|
|
154
197
|
for (const [dependency, range] of Object.entries(entries ?? {})) {
|
|
155
|
-
if (range === 'workspace:*' && (dependency
|
|
198
|
+
if (range === 'workspace:*' && starterWorkspaceDependencies.has(dependency))
|
|
156
199
|
entries[dependency] = version;
|
|
157
200
|
else if (range.startsWith('workspace:'))
|
|
158
|
-
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter manifests may
|
|
201
|
+
throw new MayuraError('INTEGRITY_VIOLATION', 'Starter manifests may only link to reviewed Mayura packages.');
|
|
159
202
|
}
|
|
160
203
|
}
|
|
161
204
|
return `${JSON.stringify(manifest, null, 2)}\n`;
|