@tailor-platform/sdk 2.25.0 → 2.27.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/CHANGELOG.md +106 -0
- package/dist/application-DFeuELRo.mjs +200 -0
- package/dist/application-DFeuELRo.mjs.map +1 -0
- package/dist/application-nT_4a5HO.mjs +1 -0
- package/dist/cli/commands/deploy/deploy.d.mts +2 -0
- package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +2 -1
- package/dist/cli/commands/tailordb/migrate/bundler.d.mts +7 -6
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +12 -0
- package/dist/cli/commands/tailordb/migrate/remote-state.d.mts +1 -0
- package/dist/cli/lib.d.mts +2 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +43 -43
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/workspace-name.d.mts +2 -0
- package/dist/completion/zsh-worker.zsh +4 -2
- package/dist/configure/config/types.d.mts +11 -0
- package/dist/configure/index.d.mts +6 -6
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/auth/types.d.mts +6 -1
- package/dist/configure/services/executor/trigger/event.d.mts +1 -1
- package/dist/configure/services/executor/trigger/webhook.d.mts +1 -1
- package/dist/configure/services/idp/permission.d.mts +2 -2
- package/dist/configure/services/resolver/resolver.d.mts +1 -1
- package/dist/configure/services/tailordb/schema.d.mts +1 -1
- package/dist/configure/services/tailordb/types.d.mts +1 -1
- package/dist/configure/services/workflow/job.d.mts +1 -1
- package/dist/configure/types/field.types.d.mts +48 -11
- package/dist/configure/types/type.d.mts +1 -1
- package/dist/date-CgP7gMG_.mjs +2 -0
- package/dist/date-CgP7gMG_.mjs.map +1 -0
- package/dist/{secretmanager-5olfnI1b.mjs → date-representation-Cr7W7Pn2.mjs} +2 -2
- package/dist/date-representation-Cr7W7Pn2.mjs.map +1 -0
- package/dist/{field-parse-DhnFs9WG.mjs → field-parse-C41e3UAF.mjs} +2 -2
- package/dist/{field-parse-DhnFs9WG.mjs.map → field-parse-C41e3UAF.mjs.map} +1 -1
- package/dist/idp-G_ojPBB5.mjs.map +1 -1
- package/dist/kysely/index.d.mts +47 -15
- package/dist/kysely/index.mjs +1 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/kysely-type-RDX59E1j.mjs +48 -0
- package/dist/kysely-type-RDX59E1j.mjs.map +1 -0
- package/dist/{manager-8-JOvuLl.mjs → manager-Bk-7vkwd.mjs} +2 -2
- package/dist/{manager-8-JOvuLl.mjs.map → manager-Bk-7vkwd.mjs.map} +1 -1
- package/dist/migration-steps-C6F3zNdQ.mjs +3 -0
- package/dist/migration-steps-C6F3zNdQ.mjs.map +1 -0
- package/dist/plugin/builtin/kysely-type/index.d.mts +11 -0
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/register-ts-hook-D6KXrGrB.mjs +1009 -0
- package/dist/register-ts-hook-D6KXrGrB.mjs.map +1 -0
- package/dist/runtime/idp.d.mts +6 -0
- package/dist/runtime/index.d.mts +8 -0
- package/dist/runtime/index.mjs +1 -1
- package/dist/runtime/types.d.mts +5 -0
- package/dist/{schema-CRtAmDcl.mjs → schema-B6hJQWp6.mjs} +2 -2
- package/dist/{schema-CRtAmDcl.mjs.map → schema-B6hJQWp6.mjs.map} +1 -1
- package/dist/seed/index.d.mts +3 -1
- package/dist/seed/index.mjs +7 -9
- package/dist/seed/index.mjs.map +1 -1
- package/dist/service-Cc7OY0Oh.mjs +7 -0
- package/dist/service-Cc7OY0Oh.mjs.map +1 -0
- package/dist/service-sH2MZ4_W.mjs +1 -0
- package/dist/service_pb-Dw2ilc1O.mjs +2 -0
- package/dist/{service_pb-ZClWtj1X.mjs.map → service_pb-Dw2ilc1O.mjs.map} +1 -1
- package/dist/service_pb-GDOqfwb6.mjs +1 -0
- package/dist/types/field.generated.d.mts +2 -2
- package/dist/utils/test/index.mjs +1 -1
- package/dist/vitest/date-representation.d.mts +23 -0
- package/dist/vitest/index.d.mts +5 -2
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/migration-steps.d.mts +45 -0
- package/dist/vitest/mocks/file.d.mts +1 -1
- package/dist/vitest/mocks/idp.d.mts +1 -0
- package/dist/vitest/mocks/tailordb-pglite.d.mts +1 -0
- package/dist/vitest/pglite-kysely.d.mts +14 -1
- package/dist/vitest/pglite-temporal.d.mts +9 -0
- package/dist/vitest/setup.d.mts +3 -1
- package/dist/vitest/setup.mjs +1 -1
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/{workspace_resource_pb-CxR_6fyN.mjs → workspace_resource_pb-ChWejcj0.mjs} +2 -2
- package/dist/workspace_resource_pb-ChWejcj0.mjs.map +1 -0
- package/docs/cli/application.md +24 -16
- package/docs/cli/function.md +2 -0
- package/docs/cli/workspace.md +1 -1
- package/docs/configuration.md +19 -6
- package/docs/github-actions.md +124 -58
- package/docs/plugin/custom.md +2 -1
- package/docs/services/auth.md +20 -0
- package/docs/services/executor.md +2 -2
- package/docs/services/idp.md +6 -1
- package/docs/services/resolver.md +4 -2
- package/docs/services/staticwebsite.md +5 -5
- package/docs/services/tailordb-migration.md +159 -35
- package/docs/services/tailordb.md +2 -2
- package/docs/testing.md +5 -1
- package/package.json +12 -12
- package/dist/application-ChqHuhZW.mjs +0 -1
- package/dist/application-DS0XKBtK.mjs +0 -200
- package/dist/application-DS0XKBtK.mjs.map +0 -1
- package/dist/date-Dri6Yas-.mjs +0 -2
- package/dist/date-Dri6Yas-.mjs.map +0 -1
- package/dist/kysely-type-C-iyFFH7.mjs +0 -43
- package/dist/kysely-type-C-iyFFH7.mjs.map +0 -1
- package/dist/register-ts-hook-DPAW0Z4M.mjs +0 -924
- package/dist/register-ts-hook-DPAW0Z4M.mjs.map +0 -1
- package/dist/secretmanager-5olfnI1b.mjs.map +0 -1
- package/dist/service-Bx-7Lz06.mjs +0 -1
- package/dist/service-CL1Bp4It.mjs +0 -7
- package/dist/service-CL1Bp4It.mjs.map +0 -1
- package/dist/service_pb-ZClWtj1X.mjs +0 -2
- package/dist/service_pb-dB3RrGeh.mjs +0 -1
- package/dist/tailordb-ddl-DqInYupv.mjs +0 -7
- package/dist/tailordb-ddl-DqInYupv.mjs.map +0 -1
- package/dist/workspace_resource_pb-CxR_6fyN.mjs.map +0 -1
package/dist/cli/main.mjs
CHANGED
|
@@ -1,94 +1,94 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"../field-parse-
|
|
3
|
-
`)}const Ei=T({name:`inspect`,description:`Print the input message tree of an OperatorService endpoint.`,notes:"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.",examples:[{cmd:`GetApplication`,desc:`Show fields of GetApplicationRequest.`},{cmd:`CreateExecutorExecutor`,desc:"Inspect a deeply nested input with `(oneof config)` annotations."}],args:q.strictObject({endpoint:W(q.string(),{positional:!0,description:`API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodNames()}}})}),run:e=>{let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t);if(!n)throw U({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});C.jsonMode?C.out(renderInspectJson(n)):C.out(renderInspectText(n))}}),Di=T({name:`list`,description:`List all invocable OperatorService methods.`,notes:`Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.`,args:q.strictObject({}),run:()=>{let e=listMethodNames();if(C.jsonMode)C.out(e);else for(let t of e)C.out(t)}});function resolveNamespaceName(e,t){if(/Auth|Tenant|UserProfile/.test(e))return t.auth?.name;if(/IdP/.test(e))return t.idp?.length===1?o(t.idp[0],`idp config missing`).name:void 0;if(/TailorDB/.test(e)){let e=Object.keys(t.db??{});return e.length===1?e[0]:void 0}if(/Pipeline/.test(e)){let e=Object.keys(t.resolver??{});return e.length===1?e[0]:void 0}}function parseBodyAsObject(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return t}function setNestedPath(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=o(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[o(t[t.length-1],`path last segment missing`)]=n}function coerceFieldValue(e,t){if(e&&e.fieldKind===`scalar`&&e.scalar===J.BOOL){if(t===`true`)return!0;if(t===`false`)return!1;throw U({code:`API_FIELD_VALUE_INVALID`,message:`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`,command:`api`})}return t}function normalizeBodyFieldKeys(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.localName),n.set(e.jsonName,e.localName);let r=!1;for(let t of Object.keys(e)){let i=n.get(t);i&&i!==t&&(Object.hasOwn(e,i)||(e[i]=e[t]),delete e[t],r=!0)}return r}const Oi=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),ki=q.string().transform((e,t)=>{let n=e.indexOf(`=`);if(n<0)return t.addIssue({code:`custom`,message:`Invalid field format: '${e}'. Expected format: 'key=value' or 'a.b.c=value'`}),q.NEVER;let r=e.slice(0,n);if(r.length===0)return t.addIssue({code:`custom`,message:`Field key cannot be empty`}),q.NEVER;let i=r.split(`.`);if(i.some(e=>e.length===0))return t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Dotted segments cannot be empty`}),q.NEVER;let a=i.find(e=>Oi.has(e));return a?(t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),q.NEVER):{path:i,value:e.slice(n+1)}}),Ai=T({name:`api`,description:`Call Tailor Platform API endpoints directly.`,notes:"Use `tailor api list` to enumerate invocable methods and `tailor api inspect <endpoint>` to print an endpoint's input message tree (combine with `--json` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from `--body`:\n\n- `workspaceId` — resolved from `-w` / `TAILOR_PLATFORM_WORKSPACE_ID` / the selected profile.\n- `namespaceName` — resolved from `tailor.config.ts` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use `auth.name`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in `--body` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse `--field key=value` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. `application.name=foo`) build nested objects. `--field` overrides matching fields in `--body` and tab-completes from the endpoint's request schema.",examples:[{cmd:`GetApplication -b '{"applicationName":"app-1"}'`,desc:`Call an endpoint; workspaceId is auto-injected.`},{cmd:`GetApplication -f applicationName=app-1`,desc:`Same as above, using --field instead of --body.`},{cmd:`list`,desc:`List all invocable OperatorService methods.`},{cmd:`inspect GetApplication`,desc:`Show the input message tree for an endpoint.`}],subCommands:{list:Di,inspect:Ei},args:q.strictObject({...k,...lt,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(ki.array().optional(),{alias:`f`,description:"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.",completion:{custom:{expand:{dependsOn:[`endpoint`],enumerate:({endpoint:e})=>enumerateAllFieldCompletions(extractMethodName(e??``))}}}}),endpoint:W(q.string(),{positional:!0,description:`API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodChoices()}}})}),run:async e=>{await N({profile:e.profile});let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t),r=parseBodyAsObject(e.body),i=!1;if(e.field&&e.field.length>0){if(!r)throw U({code:`API_OPTIONS_INVALID`,message:`--field requires --body to be a JSON object (or omitted).`,command:`api`});for(let t of e.field){let e=n?resolveLeafField(n.input,t.path):void 0;setNestedPath(r,t.path,coerceFieldValue(e,t.value))}i=!0}if(r&&n){normalizeBodyFieldKeys(r,n.input.fields)&&(i=!0);let a=n.input.fields.map(e=>e.localName);if(a.includes(`workspaceId`)&&!Object.hasOwn(r,`workspaceId`))try{r.workspaceId=await br({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await I(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await nr({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});C.out(JSON.stringify(a.data,null,2))}}),ji=T({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:k.profile}),run:async({profile:e})=>{let t=await Cn({profile:e});if(C.out(t),!t.authenticated)throw U({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...Fe({profile:e})]}})}}),Mi=T({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:k.profile}),run:async({profile:e})=>{let t=await Ln({profile:e});C.out(t)}}),Ni=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:ji,token:Mi}}),Pi={name:W(q.string(),{alias:`n`,description:`Auth connection name`})};async function fetchOIDCDiscovery(e){let t=e.replace(/\/$/,``)+`/.well-known/openid-configuration`,n=await fetch(t).catch(e=>{throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${Ir(e).message}`,cause:e})});if(!n.ok)throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return ui.randomBytes(32).toString(`base64url`)}const Fi=T({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...k,...Pi,scopes:q.string().optional().default(`openid,profile,email`).describe(`OAuth2 scopes to request (comma-separated)`),port:q.coerce.number().optional().default(8080).describe(`Local callback server port`),"no-browser":q.boolean().optional().default(!1).describe(`Don't open browser automatically`)}),run:async e=>{await N({profile:e.profile});let t=H({command:`tailor`,args:[`authconnection`,`open`,...Fe({profile:e.profile,workspaceId:e[`workspace-id`]})]}),{client:n,workspaceId:r}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await fe(async(e,t)=>{let{connections:i,nextPageToken:a}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:t});return[i,a]})).find(t=>t.name===e.name);if(!i)throw U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw U({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),c;c=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let l=new URL(c);l.searchParams.set(`client_id`,a.clientId),l.searchParams.set(`redirect_uri`,o),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,s),l.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,l)=>{if(!t.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let a=new URL(t.url,`http://localhost:${e.port}`),u=a.searchParams.get(`code`),d=a.searchParams.get(`state`),f=a.searchParams.get(`error`);if(f)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${f}`});if(d!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!u)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});C.registerSecret(u),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),c.close(),i()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),c.close(),a(Ir(e))}},c=fi.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{c.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);c.on(`close`,()=>{clearTimeout(u)}),c.on(`error`,n=>{clearTimeout(u);let r=n.code,i=r===`EADDRINUSE`||r===`EACCES`?`Try a different port with --port, or authorize via the Console instead:`:`Authorize via the Console instead:`;C.warn(`Could not start the local callback server on port ${e.port}${r?` (${r})`:``}.\n${i}\n ${t}`),a(n)});let announceAuthorizeUrl=async()=>{let n=l.toString();if(C.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),C.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await pi(n)}catch{C.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(e.port,()=>void announceAuthorizeUrl())}),C.success(`Auth connection "${e.name}" authorized successfully.`),R({changed:!0,workspaceId:r,name:e.name})}}),Ii=T({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...k,...Pi,...D}),run:async e=>{await N({profile:e.profile});let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await P.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_DELETION_CANCELLED`,message:`Auth connection deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}C.success(`Auth connection "${e.name}" deleted.`)}});function connectionInfo(e){let t=e.config.case===`oauth2`?e.config.value:void 0;return{name:e.name,type:e.config.case??`unknown`,providerUrl:t?.providerUrl??``,issuerUrl:t?.issuerUrl??``,clientId:t?.clientId??``,authUrl:t?.authUrl??``,tokenUrl:t?.tokenUrl??``,createdAt:e.createdAt?X(e.createdAt):null}}const Li=T({name:`list`,description:`List all auth connections.`,args:q.strictObject({...k,...Ot()}),run:async e=>{let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=We(e.order),i=await L(e.limit,e=>b(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e}));C.out(i.items.map(connectionInfo)),await z(i,e.limit)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){C.out([]);return}throw e}}}),Ri=T({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...k}),run:async e=>{let t=await br({workspaceId:e[`workspace-id`],profile:e.profile}),n=`/workspaces/${t}/services/auth-connections`,r=await Jt({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=C.jsonMode;C.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await pi(i)}catch{o=!1}if(a){C.out({consoleUrl:i,workspaceId:t,opened:o});return}o?(C.out(`Console URL: ${i}`),C.out(`Workspace ID: ${t}`)):C.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),zi=T({name:`revoke`,description:`Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).`,notes:"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.",args:q.strictObject({...k,...Pi,...D}),run:async e=>{await N({profile:e.profile});let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await P.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_REVOCATION_CANCELLED`,message:`Auth connection revocation cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}C.success(`Auth connection "${e.name}" revoked.`)}}),Bi=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Fi,list:Li,open:Ri,revoke:zi,delete:Ii},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(Hr)).toSorted(),r=t.order===`asc`?n:n.toReversed();return t.limit&&t.limit>0?r.slice(0,t.limit):r}function formatCrashReportFiles(e,t){return e.map(e=>({file:e,path:K.join(t,e)}))}const Vi=T({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Ot()}),run:async e=>{let t=Ur(),n=C.jsonMode;if(!t.localDir){C.info(`Crash report directory not available.`),n&&C.out([]);return}let r;try{r=Y.readdirSync(t.localDir)}catch{C.info(`No crash reports found.`),n&&C.out([]);return}let i=await L(e.limit,async t=>orderAndLimitCrashReports(r,{order:e.order,limit:t})),a=i.items;if(a.length===0){C.info(`No crash reports found.`),n&&C.out([]);return}if(n){C.out(formatCrashReportFiles(a,t.localDir)),await z(i,e.limit);return}C.info(`${a.length} crash report(s) in ${t.localDir}:`);for(let e of a)C.log(` ${e}`);await z(i,e.limit)}}),Hi=T({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:q.strictObject({file:W(q.string(),{description:`Path to the crash report file`,required:!0,completion:{type:`file`,extensions:[`log`]}})}),run:async e=>{let t;try{t=Y.readFileSync(e.file,`utf-8`)}catch{C.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(C.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await zr();C.info(`Sending crash report...`),await Wr(n,r)?(C.success(`Crash report submitted successfully. Thank you!`),R({changed:!0,id:n.id,file:e.file})):(C.error(`Failed to submit crash report. The server may be unavailable.`),process.exit(1))}});function parseCrashLogFile(e){try{let t=e.replace(/\r\n/g,`
|
|
4
|
-
`),n=`\n${
|
|
5
|
-
`)[0];return i?JSON.parse(i):void 0}catch{return}}const
|
|
2
|
+
import{r as e}from"../field-parse-C41e3UAF.mjs";import{At as t,E as n,J as r,K as i,Lt as a,Wt as o}from"../workspace_resource_pb-ChWejcj0.mjs";import{t as s}from"../assert-WeXvmG4j.mjs";import{$ as c,B as l,C as u,F as d,H as f,I as p,J as m,K as h,P as g,Q as _,R as v,S as y,T as b,V as ee,Y as x,Z as S,_ as te,at as ne,c as re,g as ie,ht as ae,l as oe,nt as se,o as ce,ot as le,p as ue,q as de,rt as fe,s as pe,st as me,tt as he,vt as ge,w as _e,y as ve,z as ye}from"../application-DFeuELRo.mjs";import{i as C,o as w}from"../logger-Db-YRTwK.mjs";import{$i as be,$n as xe,$r as Se,$t as Ce,Ai as T,At as we,B as Te,Bi as Ee,Bn as De,Br as Oe,Bt as ke,Ci as Ae,Cn as je,Cr as Me,Ct as Ne,D as Pe,Di as Fe,Ei as Ie,Er as E,Et as Le,Fi as Re,Fr as ze,G as Be,Gi as Ve,Gn as He,Gt as Ue,Hi as D,Hn as We,I as Ge,Ii as O,In as Ke,It as qe,Ji as Je,Jn as Ye,Jr as Xe,K as Ze,Ki as Qe,Kn as $e,Kr as et,Li as k,Ln as tt,Lr as nt,M as rt,Mi as it,N as at,Ni as ot,Nt as st,Oi as ct,Ot as lt,P as ut,Pi as dt,Pn as ft,Pr as pt,Pt as mt,Q as ht,Qi as gt,Qn as _t,Qr as A,R as vt,Ri as yt,Rn as bt,Rr as xt,S as St,Si as Ct,Sn as wt,Sr as Tt,St as Et,T as Dt,Ti as Ot,Tr as kt,Tt as At,U as jt,Un as Mt,Ur as Nt,Ut as Pt,V as Ft,Vi as It,Vn as Lt,Vr as Rt,Wi as j,Wn as zt,Wr as Bt,X as Vt,Xi as Ht,Xn as Ut,Xt as Wt,Y as Gt,Yi as Kt,Yn as qt,Yr as Jt,Zi as Yt,Zn as Xt,Zr as Zt,_i as Qt,_n as $t,_r as en,a as tn,ai as nn,an as rn,ar as an,b as on,bi as sn,br as cn,bt as ln,c as un,ci as dn,cn as fn,cr as pn,ct as mn,di as M,dn as hn,dr as gn,ea as _n,ei as vn,en as yn,er as bn,et as xn,f as Sn,fi as N,fn as Cn,fr as wn,ft as Tn,g as En,gi as P,gn as Dn,gr as On,gt as kn,hi as F,hn as An,hr as jn,ht as Mn,ii as I,in as Nn,ir as Pn,it as Fn,ji as In,k as Ln,ki as Rn,li as L,ln as zn,lr as Bn,m as Vn,mi as Hn,mn as Un,mr as Wn,n as Gn,na as R,ni as Kn,nn as qn,nr as Jn,nt as Yn,o as Xn,oi as Zn,or as Qn,ot as $n,pi as z,pn as er,pr as tr,qn as nr,qr as rr,qt as ir,ri as ar,rr as or,si as sr,sn as cr,sr as lr,t as ur,ta as dr,ti as fr,tn as pr,tr as mr,u as hr,ui as B,un as gr,ur as _r,ut as vr,v as yr,vi as br,vn as xr,vr as Sr,vt as Cr,w as wr,wi as Tr,wr as Er,wt as Dr,xi as Or,xr as kr,xt as Ar,yi as jr,yn as Mr,yr as Nr,z as Pr,zn as Fr}from"../register-ts-hook-D6KXrGrB.mjs";import{g as Ir,i as Lr,r as Rr}from"../service-Cc7OY0Oh.mjs";import{t as V}from"../multiline-EyzjEwn9.mjs";import{a as zr,i as Br,n as Vr,o as Hr,r as H,s as Ur,t as U}from"../errors-CpvSChyL.mjs";import{t as Wr}from"../package-json-C690ceex.mjs";import{t as Gr}from"../user-agent-vdHYF3QL.mjs";import{t as Kr}from"../service_pb-Dw2ilc1O.mjs";import{a as qr,i as Jr,o as Yr,r as Xr,t as Zr}from"../crashreport-DFpRn-LS.mjs";import{t as Qr}from"../manager-Bk-7vkwd.mjs";import{a as $r,n as ei,o as ti}from"../kysely-type-RDX59E1j.mjs";import{arg as W,defineCommand as G,extractFields as ni,runMain as ri,toCamelCase as ii}from"@politty/zod";import{withCompletionCommand as ai}from"@politty/zod/completion";import{withSkillCommand as oi}from"@politty/zod/skill";import*as K from"pathe";import{dirname as si,resolve as ci}from"pathe";import{resolvePackageJSON as li}from"pkg-types";import{z as q}from"zod";import{ScalarType as J,create as ui}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as di,constants as fi,readdirSync as pi}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import{pathToFileURL as mi}from"node:url";import{generateCodeVerifier as hi}from"@badgateway/oauth2-client";import*as gi from"node:crypto";import{randomBytes as _i}from"node:crypto";import*as vi from"node:http";import yi from"open";import*as bi from"rolldown";import{parseSync as xi}from"oxc-parser";import*as Si from"node:os";import*as $ from"node:fs/promises";import{setTimeout as Ci}from"node:timers/promises";import{spawn as wi,spawnSync as Ti}from"node:child_process";import{TraceMap as Ei,generatedPositionFor as Di,originalPositionFor as Oi}from"@jridgewell/trace-mapping";const ki=Kr.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return ki.map(e=>e.name).toSorted()}function listMethodChoices(){return ki.flatMap(e=>[e.name,`${Kr.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return ki.find(t=>t.name===e)}function extractMethodName(e){return e.includes(`/`)?e.split(`/`).pop()??e:e}function nestedMessage(e){if(e.fieldKind===`message`||e.fieldKind===`list`&&e.listKind===`message`||e.fieldKind===`map`&&e.mapKind===`message`)return e.message}function isWellKnownType(e){return e.typeName.startsWith(`google.protobuf.`)}const Ai=/* @__PURE__ */ new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return Ai.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=/* @__PURE__ */ new Set;function walk(e,t){r.add(e);for(let i of e.fields){if(i.fieldKind===`list`||i.fieldKind===`map`)continue;let e=t+i.localName;if(i.fieldKind===`message`){if(isUnrepresentableWellKnownType(i.message))continue;if(!isWellKnownType(i.message)){let t=i.message;n.push({value:`${e}.`,description:`${e} (message)`}),r.has(t)||walk(t,`${e}.`);continue}}if(n.push({value:`${e}=`,description:`Set ${e}`}),i.fieldKind===`enum`)for(let t of i.enum.values)n.push({value:`${e}=${t.name}`,description:t.name});else i.fieldKind===`scalar`&&i.scalar===J.BOOL&&(n.push({value:`${e}=true`,description:`true`}),n.push({value:`${e}=false`,description:`false`}))}r.delete(e)}return walk(t.input,``),n}function resolveLeafField(e,t){let n=e;for(let e=0;e<t.length;e++){let r=n.fields.find(n=>n.localName===t[e]);if(!r)return;if(e===t.length-1)return r.fieldKind===`message`&&isUnrepresentableWellKnownType(r.message)?void 0:r;if(r.fieldKind!==`message`||isWellKnownType(r.message))return;n=r.message}}const ji={[J.DOUBLE]:`double`,[J.FLOAT]:`float`,[J.INT64]:`int64`,[J.UINT64]:`uint64`,[J.INT32]:`int32`,[J.FIXED64]:`fixed64`,[J.FIXED32]:`fixed32`,[J.BOOL]:`bool`,[J.STRING]:`string`,[J.BYTES]:`bytes`,[J.UINT32]:`uint32`,[J.SFIXED32]:`sfixed32`,[J.SFIXED64]:`sfixed64`,[J.SINT32]:`sint32`,[J.SINT64]:`sint64`};function shortName(e){let t=e.lastIndexOf(`.`);return t<0?e:e.slice(t+1)}function scalarLabel(e){return ji[e]??`scalar(${e})`}function enumLabel(e){return`enum ${shortName(e.typeName)}`}function enumOf(e){if(e.fieldKind===`enum`||e.fieldKind===`list`&&e.listKind===`enum`)return e.enum}function describeFieldType(e){switch(e.fieldKind){case`scalar`:return scalarLabel(e.scalar);case`enum`:return enumLabel(e.enum);case`message`:return shortName(e.message.typeName);case`list`:{let t;return t=e.listKind===`scalar`?scalarLabel(e.scalar):e.listKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`repeated ${t}`}case`map`:{let t=scalarLabel(e.mapKey),n;return n=e.mapKind===`scalar`?scalarLabel(e.scalar):e.mapKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`map<${t}, ${n}>`}default:return`<unknown>`}}function fieldToJson(e,t){let n={name:e.localName,protoName:e.name,type:describeFieldType(e),fieldKind:e.fieldKind,repeated:e.fieldKind===`list`};e.oneof&&(n.oneof=e.oneof.name);let r=enumOf(e);r&&(n.enumValues=r.values.map(e=>e.name));let i=nestedMessage(e);return i&&!t.has(i)?(t.add(i),n.message={typeName:i.typeName,fields:i.fields.map(e=>fieldToJson(e,t))},t.delete(i)):i&&(n.message={typeName:i.typeName,fields:[],recursive:!0}),n}function renderInspectJson(e){let t=/* @__PURE__ */ new Set([e.input]);return{method:e.name,input:{typeName:e.input.typeName,fields:e.input.fields.map(e=>fieldToJson(e,t))},output:{typeName:e.output.typeName}}}function renderFieldText(e,t,n){let r=[],i=e.oneof?` (oneof ${e.oneof.name})`:``;r.push(`${t}${e.localName}: ${describeFieldType(e)}${i}`);let a=enumOf(e);if(a){let e=a.values.map(e=>e.name).join(`, `);r.push(`${t} values: ${e}`)}let o=nestedMessage(e);if(o&&!n.has(o)){n.add(o);for(let e of o.fields)r.push(...renderFieldText(e,`${t} `,n));n.delete(o)}else o&&r.push(`${t} …(recursive ${o.typeName})`);return r}function renderInspectText(e){let t=[];t.push(`${e.name}`),t.push(` request: ${e.input.typeName}`);let n=/* @__PURE__ */ new Set([e.input]);for(let r of e.input.fields)t.push(...renderFieldText(r,` `,n));return t.push(` response: ${e.output.typeName}`),t.join(`
|
|
3
|
+
`)}const Mi=k({name:`inspect`,description:`Print the input message tree of an OperatorService endpoint.`,notes:"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.",examples:[{cmd:`GetApplication`,desc:`Show fields of GetApplicationRequest.`},{cmd:`CreateExecutorExecutor`,desc:"Inspect a deeply nested input with `(oneof config)` annotations."}],args:q.strictObject({endpoint:W(q.string(),{positional:!0,description:`API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodNames()}}})}),run:e=>{let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t);if(!n)throw U({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});C.jsonMode?C.out(renderInspectJson(n)):C.out(renderInspectText(n))}}),Ni=k({name:`list`,description:`List all invocable OperatorService methods.`,notes:`Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.`,args:q.strictObject({}),run:()=>{let e=listMethodNames();if(C.jsonMode)C.out(e);else for(let t of e)C.out(t)}});function resolveNamespaceName(e,t){if(/Auth|Tenant|UserProfile/.test(e))return t.auth?.name;if(/IdP/.test(e))return t.idp?.length===1?s(t.idp[0],`idp config missing`).name:void 0;if(/TailorDB/.test(e)){let e=Object.keys(t.db??{});return e.length===1?e[0]:void 0}if(/Pipeline/.test(e)){let e=Object.keys(t.resolver??{});return e.length===1?e[0]:void 0}}function parseBodyAsObject(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return t}function setNestedPath(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=s(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[s(t[t.length-1],`path last segment missing`)]=n}function coerceFieldValue(e,t){if(e&&e.fieldKind===`scalar`&&e.scalar===J.BOOL){if(t===`true`)return!0;if(t===`false`)return!1;throw U({code:`API_FIELD_VALUE_INVALID`,message:`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`,command:`api`})}return t}function normalizeBodyFieldKeys(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.localName),n.set(e.jsonName,e.localName);let r=!1;for(let t of Object.keys(e)){let i=n.get(t);i&&i!==t&&(Object.hasOwn(e,i)||(e[i]=e[t]),delete e[t],r=!0)}return r}const Pi=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),Fi=q.string().transform((e,t)=>{let n=e.indexOf(`=`);if(n<0)return t.addIssue({code:`custom`,message:`Invalid field format: '${e}'. Expected format: 'key=value' or 'a.b.c=value'`}),q.NEVER;let r=e.slice(0,n);if(r.length===0)return t.addIssue({code:`custom`,message:`Field key cannot be empty`}),q.NEVER;let i=r.split(`.`);if(i.some(e=>e.length===0))return t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Dotted segments cannot be empty`}),q.NEVER;let a=i.find(e=>Pi.has(e));return a?(t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),q.NEVER):{path:i,value:e.slice(n+1)}}),Ii=k({name:`api`,description:`Call Tailor Platform API endpoints directly.`,notes:"Use `tailor api list` to enumerate invocable methods and `tailor api inspect <endpoint>` to print an endpoint's input message tree (combine with `--json` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from `--body`:\n\n- `workspaceId` — resolved from `-w` / `TAILOR_PLATFORM_WORKSPACE_ID` / the selected profile.\n- `namespaceName` — resolved from `tailor.config.ts` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use `auth.name`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in `--body` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse `--field key=value` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. `application.name=foo`) build nested objects. `--field` overrides matching fields in `--body` and tab-completes from the endpoint's request schema.",examples:[{cmd:`GetApplication -b '{"applicationName":"app-1"}'`,desc:`Call an endpoint; workspaceId is auto-injected.`},{cmd:`GetApplication -f applicationName=app-1`,desc:`Same as above, using --field instead of --body.`},{cmd:`list`,desc:`List all invocable OperatorService methods.`},{cmd:`inspect GetApplication`,desc:`Show the input message tree for an endpoint.`}],subCommands:{list:Ni,inspect:Mi},args:q.strictObject({...R,...It,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(Fi.array().optional(),{alias:`f`,description:"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.",completion:{custom:{expand:{dependsOn:[`endpoint`],enumerate:({endpoint:e})=>enumerateAllFieldCompletions(extractMethodName(e??``))}}}}),endpoint:W(q.string(),{positional:!0,description:`API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodChoices()}}})}),run:async e=>{await F({profile:e.profile});let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t),r=parseBodyAsObject(e.body),i=!1;if(e.field&&e.field.length>0){if(!r)throw U({code:`API_OPTIONS_INVALID`,message:`--field requires --body to be a JSON object (or omitted).`,command:`api`});for(let t of e.field){let e=n?resolveLeafField(n.input,t.path):void 0;setNestedPath(r,t.path,coerceFieldValue(e,t.value))}i=!0}if(r&&n){normalizeBodyFieldKeys(r,n.input.fields)&&(i=!0);let a=n.input.fields.map(e=>e.localName);if(a.includes(`workspaceId`)&&!Object.hasOwn(r,`workspaceId`))try{r.workspaceId=await ct({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await P(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await Hn({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});C.out(JSON.stringify(a.data,null,2))}}),Li=k({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:R.profile}),run:async({profile:e})=>{let t=await Ct({profile:e});if(C.out(t),!t.authenticated)throw U({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...gt({profile:e})]}})}}),Ri=k({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:R.profile}),run:async({profile:e})=>{let t=await Or({profile:e});C.out(t)}}),zi=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:Li,token:Ri}}),Bi={name:W(q.string(),{alias:`n`,description:`Auth connection name`})};async function fetchOIDCDiscovery(e){let t=e.replace(/\/$/,``)+`/.well-known/openid-configuration`,n=await fetch(t).catch(e=>{throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${Hr(e).message}`,cause:e})});if(!n.ok)throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return gi.randomBytes(32).toString(`base64url`)}const Vi=k({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...R,...Bi,scopes:q.string().optional().default(`openid,profile,email`).describe(`OAuth2 scopes to request (comma-separated)`),port:q.coerce.number().optional().default(8080).describe(`Local callback server port`),"no-browser":q.boolean().optional().default(!1).describe(`Don't open browser automatically`)}),run:async e=>{await F({profile:e.profile});let t=H({command:`tailor`,args:[`authconnection`,`open`,...gt({profile:e.profile,workspaceId:e[`workspace-id`]})]}),{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await m(async(e,t)=>{let{connections:i,nextPageToken:a}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:t});return[i,a]})).find(t=>t.name===e.name);if(!i)throw U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw U({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),c;c=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let l=new URL(c);l.searchParams.set(`client_id`,a.clientId),l.searchParams.set(`redirect_uri`,o),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,s),l.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,l)=>{if(!t.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let a=new URL(t.url,`http://localhost:${e.port}`),u=a.searchParams.get(`code`),d=a.searchParams.get(`state`),f=a.searchParams.get(`error`);if(f)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${f}`});if(d!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!u)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});C.registerSecret(u),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),c.close(),i()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),c.close(),a(Hr(e))}},c=vi.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{c.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);c.on(`close`,()=>{clearTimeout(u)}),c.on(`error`,n=>{clearTimeout(u);let r=n.code,i=r===`EADDRINUSE`||r===`EACCES`?`Try a different port with --port, or authorize via the Console instead:`:`Authorize via the Console instead:`;C.warn(`Could not start the local callback server on port ${e.port}${r?` (${r})`:``}.\n${i}\n ${t}`),a(n)});let announceAuthorizeUrl=async()=>{let n=l.toString();if(C.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),C.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await yi(n)}catch{C.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(e.port,()=>void announceAuthorizeUrl())}),C.success(`Auth connection "${e.name}" authorized successfully.`),z({changed:!0,workspaceId:r,name:e.name})}}),Hi=k({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...R,...Bi,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await M.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_DELETION_CANCELLED`,message:`Auth connection deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}C.success(`Auth connection "${e.name}" deleted.`),z({changed:!0,workspaceId:n,name:e.name})}});function connectionInfo(e){let t=e.config.case===`oauth2`?e.config.value:void 0;return{name:e.name,type:e.config.case??`unknown`,providerUrl:t?.providerUrl??``,issuerUrl:t?.issuerUrl??``,clientId:t?.clientId??``,authUrl:t?.authUrl??``,tokenUrl:t?.tokenUrl??``,createdAt:e.createdAt?X(e.createdAt):null}}const Ui=k({name:`list`,description:`List all auth connections.`,args:q.strictObject({...R,...Ht()}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=dr(e.order),i=await L(e.limit,e=>S(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e}));C.out(i.items.map(connectionInfo)),await B(i,e.limit)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){C.out([]);return}throw e}}}),Wi=k({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...R}),run:async e=>{let t=await ct({workspaceId:e[`workspace-id`],profile:e.profile}),n=`/workspaces/${t}/services/auth-connections`,r=await Tr({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=C.jsonMode;C.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await yi(i)}catch{o=!1}if(a){C.out({consoleUrl:i,workspaceId:t,opened:o});return}o?(C.out(`Console URL: ${i}`),C.out(`Workspace ID: ${t}`)):C.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),Gi=k({name:`revoke`,description:`Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).`,notes:"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.",args:q.strictObject({...R,...Bi,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await M.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_REVOCATION_CANCELLED`,message:`Auth connection revocation cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}C.success(`Auth connection "${e.name}" revoked.`),z({changed:!0,workspaceId:n,name:e.name})}}),Ki=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Vi,list:Ui,open:Wi,revoke:Gi,delete:Hi},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(Jr)).toSorted(),r=t.order===`asc`?n:n.toReversed();return t.limit&&t.limit>0?r.slice(0,t.limit):r}function formatCrashReportFiles(e,t){return e.map(e=>({file:e,path:K.join(t,e)}))}const qi=k({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Ht()}),run:async e=>{let t=Yr(),n=C.jsonMode;if(!t.localDir){C.info(`Crash report directory not available.`),n&&C.out([]);return}let r;try{r=Y.readdirSync(t.localDir)}catch{C.info(`No crash reports found.`),n&&C.out([]);return}let i=await L(e.limit,async t=>orderAndLimitCrashReports(r,{order:e.order,limit:t})),a=i.items;if(a.length===0){C.info(`No crash reports found.`),n&&C.out([]);return}if(n){C.out(formatCrashReportFiles(a,t.localDir)),await B(i,e.limit);return}C.info(`${a.length} crash report(s) in ${t.localDir}:`);for(let e of a)C.log(` ${e}`);await B(i,e.limit)}}),Ji=k({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:q.strictObject({file:W(q.string(),{description:`Path to the crash report file`,required:!0,completion:{type:`file`,extensions:[`log`]}})}),run:async e=>{let t;try{t=Y.readFileSync(e.file,`utf-8`)}catch{C.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(C.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await Gr();C.info(`Sending crash report...`),await Xr(n,r)?(C.success(`Crash report submitted successfully. Thank you!`),z({changed:!0,id:n.id,file:e.file})):(C.error(`Failed to submit crash report. The server may be unavailable.`),process.exit(1))}});function parseCrashLogFile(e){try{let t=e.replace(/\r\n/g,`
|
|
4
|
+
`),n=`\n${qr}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
|
|
5
|
+
`)[0];return i?JSON.parse(i):void 0}catch{return}}const Yi=G({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:qi,send:Ji},defaultSubCommand:`list`}),Xi=k({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,args:q.strictObject({...R,...Je,...D,"create-workspace":W(q.boolean().optional(),{description:`Create a workspace when the account has none`}),"workspace-name":W(q.string().optional(),{description:`Name for a workspace created during deploy`}),"workspace-region":W(q.string().optional(),{description:`Region for a workspace created during deploy`}),"organization-id":W(q.string().optional(),{description:`Organization ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":W(q.string().optional(),{description:`Folder ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_FOLDER_ID`}),"dry-run":W(q.boolean().optional(),{alias:`d`,description:`Run the command without making any changes`}),"no-schema-check":W(q.boolean().optional(),{description:`Skip schema diff check against migration snapshots`}),"migration-skip-steps":W(q.string().optional(),{description:`Skip steps of a partially applied multi-step migration that already succeeded (comma-separated namespace/step entries)`}),"no-validate":W(q.boolean().optional(),{description:`Skip client-side validation against platform resource constraints`}),"no-cache":W(q.boolean().optional(),{description:`Disable bundle caching for this run`}),"clean-cache":W(q.boolean().optional(),{description:`Clean the bundle cache before building`})}),run:async e=>{await F({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await Ce({workspaceId:e[`workspace-id`],profile:e.profile,configPath:e.config,dryRun:e[`dry-run`],yes:e.yes,createWorkspace:e[`create-workspace`],workspaceName:e[`workspace-name`],workspaceRegion:e[`workspace-region`],organizationId:e[`organization-id`],folderId:e[`folder-id`],noSchemaCheck:e[`no-schema-check`],migrationSkipSteps:zt(e[`migration-skip-steps`]),noValidate:e[`no-validate`],noCache:e[`no-cache`],cleanCache:e[`clean-cache`]},{envFile:e[`env-file`],envFileIfExists:e[`env-file-if-exists`],verbose:e.verbose,json:e.json})}}),Zi=G({name:`executor`,description:`Manage executors`,subCommands:{trigger:mt,jobs:ke,list:qe,get:Wt,webhook:st},defaultSubCommand:`list`});function scriptNameToRegistryName(e,t){if(t===r.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let i=/^(.+)\.operation\.js$/.exec(e);if(i){let[,e]=i;return`executor--${e}`}let a=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(a){let[,e,t]=a;return`auth-hook--${e}--${t}`}return t===r.UNSPECIFIED&&!e.includes(`.`)?`workflow--${e}`:null}async function downloadFunctionScript(e){let{client:t,workspaceId:n,name:r,contentHash:i}=e;try{let e=[];for await(let a of t.downloadFunctionRegistryScript({workspaceId:n,name:r,contentHash:i}))a.payload.case===`chunk`&&e.push(a.payload.value);return e.length===0?null:{code:Buffer.concat(e).toString(`utf-8`)}}catch(t){return C.debug(`Failed to download function script "${e.name}": ${t}`),null}}const Qi=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
|
|
6
6
|
`),n=[],r=[];for(let e of t)/^\s+at\s+/.test(e)?r.push(e):r.length===0&&n.push(e);let i=n.join(`
|
|
7
|
-
`);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=
|
|
7
|
+
`);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=Qi.exec(e);t&&a.push({functionName:t[1]||`<anonymous>`,file:s(t[2],`stack frame file missing`),line:Number(s(t[3],`stack frame line missing`)),column:Number(s(t[4],`stack frame column missing`))})}return{errorMessage:i,frames:a}}const $i=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=$i.exec(e);if(!t)return null;try{let e=Buffer.from(s(t[1],`sourcemap base64 data missing`),`base64`).toString(`utf-8`),n=JSON.parse(e);return new Ei(n)}catch{return null}}function mapStackFrames(e,t){return e.map(e=>{if(!t)return{original:e,mapped:null};try{for(let n=t.sources.length-1;n>=0;n--){let r=t.sources[n];if(r==null)continue;let i=Di(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=Oi(t,{line:i.line,column:i.column});if(a.source===r&&a.line===e.line&&a.column===e.column-1)return{original:e,mapped:{source:r,line:e.line,column:e.column,name:null}}}return{original:e,mapped:null}}catch{return{original:e,mapped:null}}})}function detectEditorScheme(){let e=process.env.VISUAL||process.env.EDITOR||``;return/\bcode\b/.test(e)?`vscode`:null}function osc8Link(e,t){return`\x1b]8;;${e}\x07${t}\x1b]8;;\x07`}function buildSourceLink(e,t,n,r){let i=`${e}:${n}:${r}`;return detectEditorScheme()===`vscode`?osc8Link(`vscode://file${t}:${n}:${r}`,i):osc8Link(`file://${t}`,i)}function buildCodeSnippet(e,t){let n=e.split(`
|
|
8
8
|
`),r=Math.max(0,t-1-2),i=Math.min(n.length,t+2),a=String(i).length,o=[];for(let e=r;e<i;e++){let r=e+1,i=String(r).padStart(a),s=n[e];r===t?o.push(` ${w.error(`>`)} ${w.error(`${i} | ${s}`)}`):o.push(` ${w.dim(`${i} | ${s}`)}`)}return o.join(`
|
|
9
9
|
`)}function formatMappedError(e,t,n,r){let i=[` ${w.error(e)}`];for(let e of t)if(e.mapped){let{source:t,line:a,column:o,name:s}=e.mapped,c=r?K.resolve(r,t):K.resolve(t),l=K.relative(process.cwd(),c),u=l.startsWith(`..`)?l:`./${l}`,d=s??e.original.functionName,f=buildSourceLink(u,c,a,o);if(i.push(`\n at ${d} (${f})`),n){let e=n.sources.indexOf(t);if(e!==-1){let t=n.sourcesContent?.[e];t&&i.push(buildCodeSnippet(t,a))}}}else{let t=`${e.original.file.replace(/^file:\/\/\//,``)}:${e.original.line}:${e.original.column}`;i.push(`\n ${w.dim(`at ${e.original.functionName} (${t})`)}`)}return i.join(`
|
|
10
|
-
`)}function formatErrorWithSourcemap(e,t,n){try{let{errorMessage:r,frames:i}=parseStackTrace(e);if(i.length===0)return null;let a=extractInlineSourcemap(t);if(!a)return null;let o=mapStackFrames(i,a);return o.some(e=>e.mapped!==null)?formatMappedError(r,o,a,n):null}catch{return null}}function functionExecutionTypeToString(e){
|
|
11
|
-
`,1)[0]??``;return/^\s+at\s+/.test(
|
|
10
|
+
`)}function formatErrorWithSourcemap(e,t,n){try{let{errorMessage:r,frames:i}=parseStackTrace(e);if(i.length===0)return null;let a=extractInlineSourcemap(t);if(!a)return null;let o=mapStackFrames(i,a);return o.some(e=>e.mapped!==null)?formatMappedError(r,o,a,n):null}catch{return null}}function functionExecutionTypeToString(e){return or(r,e)??`UNSPECIFIED`}function functionErrorKindToString(e){return or(i,e)??`UNSPECIFIED`}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:_t(e.status),type:functionExecutionTypeToString(e.type),startedAt:e.startedAt?X(e.startedAt):null,finishedAt:e.finishedAt?X(e.finishedAt):null,errorKind:functionErrorKindToString(e.errorKind),errorName:e.error?.name||null,errorMessage:e.error?.message||null}}function toFunctionExecutionDetailInfo(e){return{...toFunctionExecutionListInfo(e),logs:bn(e.logEntries),logEntries:e.logEntries.map(mr),result:e.result,error:e.error?{name:e.error.name,message:e.error.message,stackTrace:e.error.stackTrace}:null}}function composeExecutionErrorString(e){let{name:t,message:n,stackTrace:r}=e,i=t&&n?`${t}: ${n}`:t||n;if(!r)return i;let a=r.split(`
|
|
11
|
+
`,1)[0]??``;return/^\s+at\s+/.test(a)?`${i}\n${r}`:r}function formatExecutionErrorFallback(e){let[t=``,...n]=composeExecutionErrorString(e).split(`
|
|
12
12
|
`);return[` ${w.error(t)}`,...n.map(e=>` ${w.dim(e)}`)].join(`
|
|
13
|
-
`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,process.cwd());if(n)return n}return formatExecutionErrorFallback(e)}const formatDate=e=>e?e.toISOString():`N/A`;function printFunctionExecutionSummary(e){let t=[[`id`,e.id],[`scriptName`,e.scriptName],[`status`,e.status],[`type`,e.type],[`startedAt`,formatDate(e.startedAt)],[`finishedAt`,formatDate(e.finishedAt)]];C.out(
|
|
13
|
+
`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,process.cwd());if(n)return n}return formatExecutionErrorFallback(e)}const formatDate=e=>e?e.toISOString():`N/A`;function printFunctionExecutionSummary(e){let t=[[`id`,e.id],[`scriptName`,e.scriptName],[`status`,e.status],[`type`,e.type],[`startedAt`,formatDate(e.startedAt)],[`finishedAt`,formatDate(e.finishedAt)],[`errorKind`,e.errorKind]];C.out(gr(t))}function printFunctionExecutionLogs(e){let t=Xt(e.logEntries);if(t.length!==0){C.log(w.bold(`
|
|
14
14
|
Logs:`));for(let e of t)C.log(` ${e}`)}}function printFunctionExecutionOutcome(e){let{detail:t,bundledCode:n}=e;if(t.result){C.log(w.bold(`
|
|
15
15
|
Result:`));try{let e=JSON.parse(t.result);C.log(` ${JSON.stringify(e,null,2).split(`
|
|
16
16
|
`).join(`
|
|
17
17
|
`)}`)}catch{C.log(` ${t.result}`)}}t.error&&(C.log(w.bold(`
|
|
18
|
-
Error:`)),C.log(formatExecutionError(t.error,n??null)))}async function fetchFunctionExecution(e){let{execution:t}=await e.client.getFunctionExecution({workspaceId:e.workspaceId,executionId:e.executionId},{signal:e.signal});if(!t)throw U({code:`FUNCTION_EXECUTION_NOT_FOUND`,message:`Function execution '${e.executionId}' not found.`});return t}async function followFunctionExecution(e){let{interval:t,timeout:n,showProgress:r}=e,i=Date.now(),a=0,o,remainingMs=()=>n===void 0?void 0:n-(Date.now()-i),timedOut=()=>{let e=remainingMs();return e!==void 0&&e<=0},timeoutError=()=>{let t=o===void 0?`unknown`:
|
|
19
|
-
Logs:`));for(let e of n.logEntries.slice(a))C.log(` ${
|
|
20
|
-
export { main } from "${
|
|
18
|
+
Error:`)),C.log(formatExecutionError(t.error,n??null)))}async function fetchFunctionExecution(e){let{execution:t}=await e.client.getFunctionExecution({workspaceId:e.workspaceId,executionId:e.executionId},{signal:e.signal});if(!t)throw U({code:`FUNCTION_EXECUTION_NOT_FOUND`,message:`Function execution '${e.executionId}' not found.`});return t}async function followFunctionExecution(e){let{interval:t,timeout:n,showProgress:r}=e,i=Date.now(),a=0,o,remainingMs=()=>n===void 0?void 0:n-(Date.now()-i),timedOut=()=>{let e=remainingMs();return e!==void 0&&e<=0},timeoutError=()=>{let t=o===void 0?`unknown`:_t(o);return U({code:`FUNCTION_EXECUTION_TIMEOUT`,message:`Timed out waiting for function execution '${e.executionId}' to complete. Last status: ${t}.`})},sleep=async()=>{let e=remainingMs();if(e===void 0){await Ci(t);return}if(e<=0)throw timeoutError();await Ci(Math.min(t,e))};for(;;){let t=remainingMs();if(t!==void 0&&t<=0)throw timeoutError();let n;try{n=await fetchFunctionExecution({...e,signal:t===void 0?void 0:AbortSignal.timeout(t)})}catch(e){if(timedOut())throw timeoutError();if(!Ye(e))throw e;C.warn(`Retrying function execution poll: ${nr(e)}`,{mode:`stream`}),await sleep();continue}if(r){if(o===void 0&&(printFunctionExecutionSummary(toFunctionExecutionListInfo(n)),xe(n.status)||C.info(`Following log entries until the execution completes (Ctrl+C to stop)`,{mode:`stream`})),n.logEntries.length>a){a===0&&C.log(w.bold(`
|
|
19
|
+
Logs:`));for(let e of n.logEntries.slice(a))C.log(` ${Ut(mr(e))}`);a=n.logEntries.length}if(o!==void 0&&n.status!==o){let e=qt(_t(n.status));C.info(`Status: ${e}`,{mode:`stream`})}}let i=o!==void 0;if(o=n.status,xe(n.status))return{execution:n,printedEntries:a,followed:i};await sleep()}}async function downloadScriptForMapping(e){let{client:t,workspaceId:n,scriptName:r,executionType:i,executionContentHash:a}=e,o=scriptNameToRegistryName(r,i);if(o==null)return C.debug(`Script "${r}" is not a deployed registry script (e.g. function run or seed); skipping sourcemap mapping.`),null;if(a===``)return C.debug(`Function execution "${r}" has no contentHash; skipping sourcemap mapping because the exact bundle cannot be identified.`),null;let s=await downloadFunctionScript({client:t,workspaceId:n,name:o,contentHash:a});return s==null?(C.debug(`Could not download pinned script "${r}" (registry: "${o}", contentHash: "${a}") for stack trace mapping; showing raw stack trace.`),null):s.code}const ea=k({name:`logs`,description:`List or get function execution logs.`,notes:"Each execution includes `errorKind`, which tells you where a failure came from: `USER_RUNTIME` (your code threw while running, or exceeded its time, memory, or CPU limit), `USER_NON_RUNTIME` (your script failed while loading, before your function was called, such as when its top-level code threw), `PLATFORM` (a failure on the Platform side, or the Platform aborting the run because of its own deadline or cancellation), `NONE` (no error), or `UNSPECIFIED` (not recorded, or a kind this CLI version does not recognize). A workflow job waiting on another job also reports `USER_NON_RUNTIME` when that job fails or is canceled. `errorName` and `errorMessage` hold the error's name and message, or `null` when none was recorded. The list table omits `errorMessage`; use `--json` or the execution details to read it.\n\nExecution details include `logEntries`, the structured log lines (message, severity, timestamp) recorded while the function ran. They are available while the execution is still running. The `logs` string joins their messages with newlines.\n\nUse `--follow` to keep polling a running execution and print new log entries as they arrive until it completes. Polling continues while the execution is suspended at a wait point, and indefinitely unless `--timeout` is set. With `--json`, `--follow` waits for completion and then emits the final execution details once.\n\nWhen viewing a specific execution that failed, the command displays error details with the stack trace mapped back to your original source files (clickable file links and code snippets, matching `function run` output).\n\nStack traces are mapped only when the execution includes a content hash for the exact build that ran. If the content hash is missing or the build is no longer available, the command falls back to a plain-text error display.",examples:[{cmd:``,desc:`List all function execution logs`},{cmd:`<execution-id>`,desc:`Get execution details with logs`},{cmd:`--json`,desc:`Output as JSON`},{cmd:`<execution-id> --json`,desc:`Get execution details as JSON`},{cmd:`<execution-id> --follow`,desc:`Stream log entries of a running execution until it completes`}],args:q.strictObject({...R,...Kt,"execution-id":W(q.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`}),follow:W(q.boolean().default(!1),{alias:`f`,description:`Keep polling a running execution and print new log entries as they arrive (detail mode only)`}),interval:W(Ve.default(`3s`),{alias:`i`,description:`Polling interval for --follow (e.g., '3s', '500ms', '1m')`}),timeout:W(Ve.optional(),{alias:`t`,description:`Maximum time to keep following (e.g., '30s', '10m'); unbounded by default`})}),run:async e=>{if(e.follow&&!e.executionId)throw U({code:`FUNCTION_LOGS_OPTIONS_INVALID`,message:`--follow requires an execution ID.`,command:`function logs`});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let r=C.jsonMode||e.json,i={client:t,workspaceId:n,executionId:e.executionId},{execution:a,printedEntries:o,followed:s}=e.follow?await followFunctionExecution({...i,interval:Yt(e.interval),timeout:e.timeout===void 0?void 0:Yt(e.timeout),showProgress:!r}):{execution:await fetchFunctionExecution(i),printedEntries:0,followed:!1},c=toFunctionExecutionDetailInfo(a);if(r){C.out(c);return}(!e.follow||s)&&printFunctionExecutionSummary(c),o===0&&printFunctionExecutionLogs(c),printFunctionExecutionOutcome({detail:c,bundledCode:c.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:c.scriptName,executionType:a.type,executionContentHash:a.contentHash}):null})}else{let r=dr(e.order),i=await L(e.limit,e=>S(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e})),a=i.items.map(toFunctionExecutionListInfo);if(a.length===0&&!e.json){C.info(`No function execution logs found.`);return}C.out(a,{display:{errorMessage:null}}),await B(i,e.limit)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o,dateDefault:s=`legacy`}=e,c=ce(e.inlineSourcemap),u=l(e.logLevel),m=K.resolve(pe(),`test-run`);Y.mkdirSync(m,{recursive:!0});let h=`test-run--${t.name}`,_=`${h}.js`,y=K.join(m,`${h}.entry.js`),b=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission,dateDefault:s});Y.writeFileSync(y,b);let x=await d(r),S=ee({tsconfig:x}),te=await bi.build({plugins:[g(y,r),f(),p(t.type===`resolver`?_e(t.fields,s):{date:!0,temporal:!0},s)],input:y,write:!1,output:{format:`esm`,sourcemap:!c||`inline`,minify:!c||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:x,treeshake:v([ye(u)]),...S.options});return S.assertAllResolved(),{bundledCode:te.output[0].code,scriptName:_}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:o,dateDefault:c}=e,l=K.resolve(n);switch(t.type){case`plain`:return t.namedMain?V`
|
|
20
|
+
export { main } from "${l}";
|
|
21
21
|
`:V`
|
|
22
|
-
import _fn from "${
|
|
22
|
+
import _fn from "${l}";
|
|
23
23
|
export { _fn as main };
|
|
24
|
-
`;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=
|
|
25
|
-
import _internalResolver from "${
|
|
24
|
+
`;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=u({permission:t.permission,defaultPermission:o}),{importStatement:s,resultExpr:d}=y(t.fields?.output,c);return V`
|
|
25
|
+
import _internalResolver from "${l}";
|
|
26
26
|
import { t } from "@tailor-platform/sdk";
|
|
27
|
-
${
|
|
27
|
+
${s}
|
|
28
28
|
|
|
29
29
|
const $tailor_resolver_body = async (rawInput) => {
|
|
30
30
|
const _caller = ${e};
|
|
31
|
-
const invoker = (${
|
|
31
|
+
const invoker = (${ve}) ?? _caller;
|
|
32
32
|
const context = { input: rawInput, env: ${JSON.stringify(r)}, caller: _caller, invoker };
|
|
33
33
|
const input = ${n};
|
|
34
34
|
const result = await _internalResolver.body({ ...context, input });
|
|
35
|
-
return ${
|
|
35
|
+
return ${d};
|
|
36
36
|
};
|
|
37
37
|
|
|
38
38
|
export { $tailor_resolver_body as main };
|
|
39
39
|
`}case`executor`:{let e=buildMachinePrincipalExpr(i,a);return V`
|
|
40
|
-
import _internalExecutor from "${
|
|
40
|
+
import _internalExecutor from "${l}";
|
|
41
41
|
|
|
42
42
|
const _env = ${JSON.stringify(r)};
|
|
43
43
|
const _actor = ${e};
|
|
44
44
|
|
|
45
45
|
const __executor_function = async (args) => {
|
|
46
|
-
const _invoker = ${
|
|
46
|
+
const _invoker = ${ve} ?? _actor;
|
|
47
47
|
return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });
|
|
48
48
|
};
|
|
49
49
|
|
|
50
50
|
export { __executor_function as main };
|
|
51
|
-
`}case`workflow-job`:{let e=
|
|
52
|
-
import { ${e} } from "${
|
|
51
|
+
`}case`workflow-job`:{let e=s(t.exportName,`workflow job export name missing`),n=buildMachinePrincipalExpr(i,a);return V`
|
|
52
|
+
import { ${e} } from "${l}";
|
|
53
53
|
|
|
54
54
|
const env = ${JSON.stringify(r)};
|
|
55
55
|
const fallbackInvoker = ${n};
|
|
56
56
|
|
|
57
57
|
export async function main(input) {
|
|
58
|
-
const invoker = ${
|
|
58
|
+
const invoker = ${ve} ?? fallbackInvoker;
|
|
59
59
|
return await ${e}.body(input, { env, invoker });
|
|
60
60
|
}
|
|
61
|
-
`}}}function buildMachinePrincipalExpr(e,t){return JSON.stringify({id:e.id,type:`machine_user`,workspaceId:t,attributes:e.attributes??{},attributeList:e.attributeList})}async function detectFunctionType(t){let{filePath:n,jobName:r}=t,i=await import(
|
|
61
|
+
`}}}function buildMachinePrincipalExpr(e,t){return JSON.stringify({id:e.id,type:`machine_user`,workspaceId:t,attributes:e.attributes??{},attributeList:e.attributeList})}async function detectFunctionType(t){let{filePath:n,jobName:r}=t,i=await import(mi(n).href),a=te.safeParse(i.default);if(a.success){let t=i.default.input,n;if(t){let r=t;n={parse:t=>e({...t,fields:r})}}return{type:`resolver`,name:a.data.name,hasInput:t!=null,inputSchema:n,permission:a.data.permission,fields:{input:a.data.input,output:a.data.output}}}let o=Lr.safeParse(Rr(i.default));if(o.success){let{operation:e}=o.data;if(e.kind===`function`||e.kind===`jobFunction`)return{type:`executor`,name:o.data.name}}let s=detectWorkflowJob(i,r);if(s)return s;if(typeof i.default==`function`)return{type:`plain`,name:deriveNameFromPath(n)};if(typeof i.main==`function`)return{type:`plain`,name:deriveNameFromPath(n),namedMain:!0};throw U({code:`FUNCTION_TYPE_UNDETECTED`,message:`Could not detect function type from ${n}.`,details:`The file must have one of:
|
|
62
62
|
- A default-exported resolver (createResolver)
|
|
63
63
|
- A default-exported executor (createExecutor) with function/jobFunction operation
|
|
64
64
|
- A named-exported workflow job (createWorkflowJob)
|
|
65
65
|
- A default-exported function
|
|
66
|
-
- A named-exported "main" function`})}function detectWorkflowJob(e,t){let n=[];for(let[t,r]of Object.entries(e)){if(t==="default")continue;let e=
|
|
67
|
-
`);throw U({code:`WORKFLOW_JOB_NOT_FOUND`,message:`Workflow job "${t}" not found.`,details:`Available jobs:\n${e}`})}return{type:`workflow-job`,name:e.name,exportName:e.exportName}}if(n.length===1){let[e]=n,t=
|
|
68
|
-
`);throw U({code:`WORKFLOW_JOB_AMBIGUOUS`,message:`Multiple workflow jobs found.`,details:`Available jobs:\n${r}`,suggestion:`Specify one with --name.`})}function deriveNameFromPath(e){return K.basename(e,K.extname(e))}const
|
|
69
|
-
`);function generateScriptDbTypes(e){let
|
|
70
|
-
`)}function loadScriptSchemaSnapshot(e){let t=K.join(K.dirname(e),
|
|
66
|
+
- A named-exported "main" function`})}function detectWorkflowJob(e,t){let n=[];for(let[t,r]of Object.entries(e)){if(t==="default")continue;let e=ue.safeParse(r);e.success&&n.push({name:e.data.name,exportName:t})}if(n.length===0)return null;if(t){let e=n.find(e=>e.name===t);if(!e){let e=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
|
|
67
|
+
`);throw U({code:`WORKFLOW_JOB_NOT_FOUND`,message:`Workflow job "${t}" not found.`,details:`Available jobs:\n${e}`})}return{type:`workflow-job`,name:e.name,exportName:e.exportName}}if(n.length===1){let[e]=n,t=s(e,`workflow job missing`);return{type:`workflow-job`,name:t.name,exportName:t.exportName}}let r=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
|
|
68
|
+
`);throw U({code:`WORKFLOW_JOB_AMBIGUOUS`,message:`Multiple workflow jobs found.`,details:`Available jobs:\n${r}`,suggestion:`Specify one with --name.`})}function deriveNameFromPath(e){return K.basename(e,K.extname(e))}const ta=`db.ts`,na=`db.snapshot.json`,ra=[`/**`,` * Auto-generated Kysely types for one-off scripts in this directory.`," * Generated by `tailor function script` from the selected TailorDB schema.",` *`," * DO NOT EDIT - Re-run `tailor function script` to refresh.",` */`].join(`
|
|
69
|
+
`);function generateScriptDbTypes(e,t=!1){let n=Object.values(e.tables).map(e=>ti(e.name,e.fields,t)),r=$r([{namespace:e.namespace,types:n}],t);return`${ra}\n\n${r}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=xi(K.basename(e),t);if(n.length>0)throw Br(`Generated ${e} does not parse as TypeScript: ${n.map(e=>e.message).join(`; `)}`)}function generateScriptSkeleton(e){let{getDBImportPath:t,namespace:n}=e;return[`/**`,` * One-off script. Run it on the platform without deploying:`,` *`,` * tailor function run <this file>`,` *`,` * For large tables, batch updates by primary-key range instead of one`,` * statement over the whole table; see the "Performance and Large Tables"`,` * section in @tailor-platform/sdk's docs/services/tailordb-migration.md.`,` */`,``,`import { getDB } from ${JSON.stringify(t)};`,``,`export default async function main() {`,` const db = getDB(${JSON.stringify(n)});`,``,` // A transaction rolls every change back when any statement fails.`,` await db.transaction().execute(async (trx) => {`,` // e.g. await trx.updateTable("MyTable").set({ ... }).where("id", "=", "...").execute();`,` });`,`}`,``].join(`
|
|
70
|
+
`)}function loadScriptSchemaSnapshot(e){let t=K.join(K.dirname(e),na);if(!Y.existsSync(t))return null;let n;try{n=JSON.parse(Y.readFileSync(t,`utf-8`))}catch(e){throw U({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}.`,suggestion:"Re-run `tailor function script` to regenerate it.",cause:e})}let r=n;if(typeof r!=`object`||!r||typeof r.namespace!=`string`||typeof r.tables!=`object`||r.tables===null)throw unexpectedSnapshotShapeError(t);let i=r.source??`remote`;if(i!==`local`&&i!==`remote`)throw unexpectedSnapshotShapeError(t);let a={...r};delete a.source;try{return{snapshotPath:t,source:i,snapshot:Zt(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return U({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Schema snapshot ${e} has an unexpected shape.`,suggestion:"Re-run `tailor function script` to regenerate it."})}async function verifyScriptSchemaSnapshot(e){let{client:t,workspaceId:n,config:r,configArgValue:i,sidecar:a}=e,{snapshot:o}=a,s=o.namespace;if(At(r).includes(s)){let{namespaces:t}=await Ne({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,Er(e)])),r=Jt(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(Kn(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await bt(t,n,s),l=Jt(a.source===`local`?generatedContractSnapshot(o):Zt(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):Zt(pickTableFields(c)));if(Kn(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return Zt(pickTableFields(kr(e)))}function generatedContractSnapshot(e){let t=fieldsOnlySnapshot(e),n=Object.fromEntries(Object.entries(t.tables).map(([t,n])=>{let r=e.tables[t],i=Object.fromEntries(Object.entries(n.fields).map(([e,t])=>[e,preserveGeneratedContract(t,r?.fields[e])]));return[t,{...n,fields:i}]}));return Zt({...t,tables:n})}function preserveGeneratedContract(e,t){let n=e.fields?Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,preserveGeneratedContract(n,t?.fields?.[e])])):void 0,r=t?.hooks?.create!==void 0||t?.default!==void 0||t?.optionalOnCreate===!0;return{...e,...n===void 0?{}:{fields:n},...r?{optionalOnCreate:!0}:{}}}function pickTableFields(e){let t=Object.fromEntries(Object.entries(e.tables).map(([e,t])=>[e,{name:t.name,pluralForm:t.pluralForm,fields:t.fields}]));return{...e,tables:t}}function schemaDriftError(e,t,n){let r=[...n.configArgValue===`tailor.config.ts`?[]:[`--config=${n.configArgValue}`],`--workspace-id=${n.workspaceId}`,...n.profileArgValue===void 0?[]:[`--profile=${n.profileArgValue}`]],i=H({command:`tailor`,args:[`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]}),a=H({command:`tailor`,args:[`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]});return U({code:`SCRIPT_SCHEMA_DRIFT`,message:`Schema drift detected: ${na} next to the script no longer matches ${e}.`,details:fr(t),suggestion:`Refresh the generated types with ${i}, or run anyway with ${a}.`})}const ia=k({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:q.object({...R,file:W(q.string(),{positional:!0,description:`Path to the function file`}),name:W(q.string().optional(),{alias:`n`,description:"Workflow job name to run (matches the `name` field of createWorkflowJob)"}),arg:W(q.string().optional(),{alias:`a`,description:`JSON argument to pass to the function`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Machine user name for authentication. Falls back to the active profile's default machine user.`,env:`TAILOR_PLATFORM_MACHINE_USER_NAME`}),config:W(q.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`}),"allow-schema-drift":W(q.boolean().default(!1),{description:`Run a scaffolded script even when its schema snapshot no longer matches`})}),notes:"You can pass either a source file (`.ts`) or a pre-bundled file (`.js`).\nWhen a `.js` file is provided, detection and bundling are skipped and the file is executed as-is.\n\nA script scaffolded by `function script` with a generated `db.ts` is checked against its `db.snapshot.json` before execution and refused on schema drift; pass `--allow-schema-drift` to run it anyway. The check compares table and field structure; hook and validator code changes are not detected.\n\n`test-run` is a deprecated alias of this command and will be removed in v3.\n\n> [!WARNING]\n> Workflow job `.start()` calls do not work in this mode.\n> Started jobs are not executed; only the target job's `body` function runs in isolation.",examples:[{cmd:`resolvers/add.ts --arg '{"a":1,"b":2}'`,desc:`Run a resolver with input arguments`},{cmd:`workflows/sample.ts --name validate-order`,desc:`Run a specific workflow job by name`},{cmd:`build/resolvers/add.js --arg '{"a":1,"b":2}'`,desc:`Run a pre-bundled .js file directly`}],run:async e=>{invokedViaTestRunAlias(process.argv)&&C.warn("`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.");let n=C.jsonMode,r=K.resolve(e.file);if(!Y.existsSync(r))throw U({code:`FILE_NOT_FOUND`,message:`File not found: ${r}`});let{config:i}=await P(e.config),a=resolveAuthNamespace(i.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:_n(e[`machine-user`]),profile:e.profile,authConfig:i.auth}),{client:s,workspaceId:c}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),l=await resolveMachineUser({client:s,workspaceId:c,authNamespace:a,machineUserName:o,authConfig:i.auth}),u=K.relative(process.cwd(),r),d=r.endsWith(`.js`);if(!d){if(e[`allow-schema-drift`])Y.existsSync(K.join(K.dirname(r),`db.snapshot.json`))&&C.warn(`Skipping the schema snapshot check (--allow-schema-drift).`);else{let t=loadScriptSchemaSnapshot(r);t&&(C.info(`Checking the script's schema snapshot for drift...`),await verifyScriptSchemaSnapshot({client:s,workspaceId:c,config:i,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let f,p,m,h;if(d)p=K.basename(r),f=Y.readFileSync(r,`utf-8`),C.info(`Using pre-bundled script ${w.bold(p)}`);else{C.info(`Detecting function type from ${w.path(u)}`);let t=await detectFunctionType({filePath:r,jobName:e.name});m=t.type,h=t.name,C.info(`Detected: ${w.bold(t.type)} ${w.info(`"${t.name}"`)}`),t.type===`resolver`&&e.arg&&!t.hasInput&&(C.warn(`--arg is ignored because this resolver has no input schema. Define "input" in your resolver to use --arg.`),e.arg=void 0),C.info(`Bundling...`);let n=oe(i),a=K.dirname(i.path);({bundledCode:f,scriptName:p}=await bundleForRun({detected:t,sourceFile:r,baseDir:a,defaultPermission:t.type===`resolver`?ie({config:i.resolver,filePath:r,baseDir:a}):void 0,env:i.env??{},inlineSourcemap:n.inlineSourcemap,logLevel:n.logLevel,dateDefault:re(i),machineUser:l,workspaceId:c})),C.info(`Bundled as ${w.bold(p)}`)}let g=ui(t,{namespace:a,machineUserName:l.name});C.info(`Executing on workspace ${w.dim(c)}...`);let _;if(e.arg!==void 0)try{_=JSON.parse(e.arg)}catch(e){throw U({code:`FUNCTION_ARG_INVALID`,message:`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,command:`function run`,cause:e})}let v=await Le({client:s,workspaceId:c,name:p,code:f,arg:_,invoker:g});if(n)C.out({success:v.success,scriptName:p,functionType:m,functionName:h,logs:v.logs,result:v.result,error:v.error});else{if(v.success?C.success(`Execution succeeded`):C.error(`Execution failed`),v.logs.trim()){C.log(w.bold(`
|
|
71
71
|
Logs:`));for(let e of v.logs.split(`
|
|
72
72
|
`))C.log(` ${e}`)}if(v.result&&v.success){C.log(w.bold(`
|
|
73
73
|
Result:`));try{let e=JSON.parse(v.result);C.log(` ${JSON.stringify(e,null,2).split(`
|
|
74
74
|
`).join(`
|
|
75
75
|
`)}`)}catch{C.log(` ${v.result}`)}}if(v.error&&!v.success){C.log(w.bold(`
|
|
76
|
-
Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?C.log(e):C.log(` ${w.error(v.error)}`)}}v.success||process.exit(1)}})
|
|
77
|
-
`),m.push(a),h=`./db`}else{if(r)throw U({code:`SCRIPT_EXISTS`,message:`Script already exists: ${K.relative(process.cwd(),t)}.`,suggestion:`It imports the project's generated Kysely types, so there is nothing to refresh.`});let e=resolveKyselyTypesPath(c);h=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||C.warn(`Generated Kysely types not found at ${w.path(K.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:h,namespace:p});assertGeneratedTypeScript(t,e),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(t,e),m.unshift(t)}let _=[`function`,`run`,K.relative(process.cwd(),t)];e.config!==`tailor.config.ts`&&_.push(`--config=${e.config}`);let v=g??e[`workspace-id`];if(v!==void 0&&_.push(`--workspace-id=${v}`),e.profile!==void 0&&_.push(`--profile=${e.profile}`),C.jsonMode){C.out({script:t,created:m,namespace:p,usesGeneratedDbTypes:d});return}r&&C.info(`Script already exists; refreshed generated types only.`);for(let e of m)C.success(`Created ${w.path(K.relative(process.cwd(),e))}`);C.info(`Next: edit the script, then run ${H({command:`tailor`,args:_})}`)}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=
|
|
78
|
-
`)}function retryInstruction(e){if(e.loginMode===`machine-user`)return`Then retry the original machine-user login command.`;let t=quoteCommandArg(e.profile);return t?`Then run:\n tailor login --profile ${t}`:`Then retry the browser login with the same profile value.`}function profileUserMismatchError(e){let t=profileUpdateCommand(e),n=retryInstruction(e);return U({code:`PROFILE_USER_MISMATCH`,message:`Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".`,details:`The authenticated user has been saved.`,suggestion:`To use it with this profile, run:\n ${t}\n${n}`,context:{profile:e.profile,configuredUser:e.oldUser,authenticatedUser:e.authenticatedUser}})}function shouldUpdateCurrentUser(e,t){return!e||de(t)}const startAuthServer=async(e={})=>{let t=se(e.platformConfig),n=randomState(),r=await li(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:aa,state:n,codeVerifier:r}).catch(e=>{throw U({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${Ir(e).message}`,cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,l)=>{try{if(!i.url?.startsWith(`/callback`))throw U({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let s=`http://${i.headers.host}${i.url}`,c=new URL(s).searchParams.get(`code`);c&&C.registerSecret(c);let u=await t.authorizationCode.getTokenFromCodeRedirect(s,{redirectUri:aa,state:n,codeVerifier:r});_r({accessToken:u.accessToken,refreshToken:u.refreshToken??void 0});let d=await _(u.accessToken,e.platformConfig),f=await E();await ot(f,d.sub,{accessToken:u.accessToken,refreshToken:u.refreshToken??void 0},new Date(o(u.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:d.email});let p=getProfileUserMismatch(e,d.email,d.sub);if(p)throw F(f),profileUserMismatchError(p);(e.updateCurrentUser??!0)&&(f.current_user=d.sub),await wt(f,d.email,d.sub,e.platformConfig),F(f),l.writeHead(200,{"Content-Type":`application/json`}),l.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a({user:d.sub,email:d.email})}catch(e){l.writeHead(401),l.end(`Authentication failed`),s(Ir(e))}finally{c.close()}},c=fi.createServer((e,t)=>void handleCallback(e,t)),l=setTimeout(()=>{c.close(),s(U({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);c.on(`close`,()=>{clearTimeout(l)}),c.on(`error`,e=>{s(e)});let openBrowser=async()=>{C.info(`Opening browser for login:\n\n${i}\n`);try{await pi(i)}catch{C.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(ia,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await P.password({message:`Client secret`}),n=await te(e.clientId,t,e.platformConfig),r=await E();await ot(r,e.clientId,{accessToken:n.accessToken},new Date(o(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw F(r),profileUserMismatchError(i);return(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),F(r),{user:e.clientId,email:null}}const oa=T({name:`login`,description:`Login to Tailor Platform.`,args:q.xor([q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`User Login`),q.strictObject({"machine-user":W(q.literal(!0),{description:`Login as a platform machine user.`,required:!0}),"client-id":W(q.string(),{description:`Client ID`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID`,required:!0}),"client-secret":W(q.string().optional(),{description:`Client secret`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET`}),profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`Machine User Login`)]),run:async e=>{try{let t,n;if(`profile`in e&&e.profile){let r=(await E()).profiles[e.profile];if(!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=bt(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t),i;i=`machine-user`in e?await loginAsMachineUser({clientId:e.clientId,clientSecret:e.clientSecret,profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`machine-user`}):await startAuthServer({profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`user`}),C.success(`Successfully logged in to Tailor Platform.`),R({changed:!0,...i})}finally{await u()}}}),sa=T({name:`logout`,description:`Logout from Tailor Platform.`,args:q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for logout.`,env:`TAILOR_PLATFORM_PROFILE`})}),run:async e=>{let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE,n=await E(),r=t?n.profiles[t]:void 0;if(t&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?bt(r):void 0,a=r?r.user:n.current_user,o=de(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){C.info(`You are not logged in.`),R({changed:!1,user:null,revoked:!1});return}let hasDefaultUserToken=()=>Gn(n,a,{platformUrl:p}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!hn(n,a))&&!hasDefaultUserToken(),c,l=!1;try{c=await nn(n,a,i,s)}catch(e){l=!0,C.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!c&&!l){C.info(`You are not logged in.`);let e=shouldClearCurrentUser();e&&(n.current_user=null),F(n),R({changed:e,user:a,revoked:!1});return}let u=!1;if(c)try{let e=se(i),t=c.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:c.accessToken,refreshToken:c.refreshToken??null,expiresAt:Date.parse(c.userEntry.token_expires_at)},t),u=!0}catch(e){C.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await ur(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),F(n),C.success(`Successfully logged out from Tailor Platform.`),R({changed:!0,user:a,revoked:u})}}),ca=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Xt,token:Sn},defaultSubCommand:`list`}),la=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:dn,get:Jn},defaultSubCommand:`list`}),ua=T({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...$e}),run:async e=>{let t=await br({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await I(e.config),r=n.name,i=`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`,a=await Jt({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),s=C.jsonMode;C.info(`Opening Tailor Platform Console...`);let c=!0;try{await pi(o)}catch{c=!1}if(s){C.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:c});return}c?(C.out(`Console URL: ${o}`),C.out(`Workspace ID: ${t}`),C.out(`Application Name: ${r}`)):C.warn(`Failed to open browser automatically. Please open this URL manually:\n${o}`)}}),da=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Fn,delete:ir,get:en,list:tr,update:cr}}),fa=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:da,get:ye,list:Gt,tree:Bt,update:Yn},defaultSubCommand:`list`}),pa=/* @__PURE__ */ `api.auth.authconnection.crashreport.deploy.executor.function.generate.init.login.logout.machineuser.oauth2client.open.organization.plugin.profile.query.remove.secret.show.skills.staticwebsite.tailordb.upgrade.user.workflow.workspace`.split(`.`),ma={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},ha=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=K.resolve(e),n=K.dirname(t);for(;n!==t;)yield t,t=n,n=K.dirname(t);yield t}function windowsExecutableExts(){return(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD;.PS1`).split(`;`).map(e=>e.trim().toLowerCase()).filter(Boolean)}function isExecutable(e){try{ai(e,process.platform===`win32`?oi.F_OK:oi.X_OK)}catch{return!1}if(process.platform===`win32`){let t=K.extname(e).toLowerCase();return t===``||windowsExecutableExts().includes(t)}return!0}function binaryCandidates(e){return process.platform===`win32`?[e,...windowsExecutableExts().map(t=>`${e}${t}`)]:[e]}function pathDirs(){return(process.env.PATH??``).split(ha).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(K.join(t,`node_modules`,`.bin`));return e}function findExecutableIn(e,t){let n=binaryCandidates(t);for(let t of e)for(let e of n){let n=K.join(t,e);if(isExecutable(n))return n}}function resolvePlugin(e,t){if(e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`))return null;let n=`${t}-${e}`,r=findExecutableIn(nodeModulesBinDirs(),n);if(r)return{name:e,path:r,source:`node_modules`};let i=findExecutableIn(pathDirs(),n);return i?{name:e,path:i,source:`path`}:null}function stripBinExt(e){if(process.platform!==`win32`)return e;let t=K.extname(e);return t?e.slice(0,-t.length):e}function listPlugins(e){let t=`${e}-`,n=/* @__PURE__ */ new Map,scan=(e,r)=>{for(let i of e){let e;try{e=si(i)}catch{continue}for(let a of e){let e=stripBinExt(a);if(!e.startsWith(t)||e.length===t.length)continue;let o=e.slice(t.length);if(n.has(o))continue;let s=K.join(i,a);isExecutable(s)&&n.set(o,{name:o,path:s,source:r})}}};return scan(nodeModulesBinDirs(),`node_modules`),scan(pathDirs(),`path`),[...n.values()]}async function resolveActiveUser(e){let t=await E(),n=e?t.profiles[e]?.user:t.current_user;if(n)return t.users[n]?.email??n}async function buildPluginEnv(e={}){let{profile:t}=e,n={},r=process.argv[1];r&&(n.TAILOR_BIN=r);try{let{version:e}=await Rr();e&&(n.TAILOR_VERSION=e)}catch{}let i=yn();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await Cr({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=le(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=re(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await br({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await Ln({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=gi.constants.signals[e];return typeof t==`number`?128+t:1}function buildSpawnTarget(e,t){if(process.platform!==`win32`)return{command:e,args:[...t],shell:!1};let n=K.extname(e).toLowerCase();return n===`.exe`||n===`.com`?{command:e,args:[...t],shell:!1}:n===`.cmd`||n===`.bat`?{command:e,args:[...t],shell:!0}:n===`.ps1`?{command:findExecutableIn(pathDirs(),`pwsh`)??findExecutableIn(pathDirs(),`powershell`)??`powershell`,args:[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,e,...t],shell:!1}:{command:findExecutableIn(pathDirs(),`sh`)??`sh`,args:[`-c`,`command "$@"`,`--`,e,...t],shell:!1}}function hasEnvFileFlag(e){for(let t of e){if(t===`--`)return!1;if(t===`--env-file`||t===`-e`||t===`--env-file-if-exists`||t.startsWith(`--env-file=`)||t.startsWith(`-e=`)||t.startsWith(`--env-file-if-exists=`))return!0}return!1}function explicitProfileFromArgs(e){let t;for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0||r===`--`)break;if(r===`--profile`||r===`-p`){let r=e[n+1];r!==void 0&&!r.startsWith(`-`)&&(t=r,n++);continue}r.startsWith(`--profile=`)?t=r.slice(10):r.startsWith(`-p=`)&&(t=r.slice(3))}return t||void 0}function pluginSlug(e,t){return[...e??[],t].join(`-`)}async function dispatchPlugin(e){let t=pluginSlug(e.commandPath,e.name),n=resolvePlugin(t,e.cliName);if(!n)return;let r=explicitProfileFromArgs(e.args)??e.profile,i={...process.env,...await buildPluginEnv({profile:r,skipPlatformContext:hasEnvFileFlag(e.args)})},{command:a,args:o,shell:s}=buildSpawnTarget(n.path,e.args);return await new Promise(n=>{let r=vi(a,o,{stdio:`inherit`,env:i,shell:s});r.on(`error`,r=>{C.error(`Failed to run plugin "${e.cliName}-${t}": ${r.message}`),n(1)}),r.on(`close`,(e,t)=>{n(t?signalToExitCode(t):e??0)})})}async function dispatchPluginWithInstallHint(e){let t=await dispatchPlugin(e);if(t!==void 0)return t;let n=ma[pluginSlug(e.commandPath,e.name)];if(!n)return;let r=[e.cliName,...e.commandPath??[],e.name].join(` `);return C.error(`"${r}" is provided by the ${n} CLI plugin, which is not installed.`),C.info(`Install it with: npm install -D ${n}`),1}const ga=T({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Rr(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(pa),r=listPlugins(t);if(r.length===0){C.info(V`
|
|
76
|
+
Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?C.log(e):C.log(` ${w.error(v.error)}`)}}v.success||process.exit(1)}}),aa=new Set(ni(q.strictObject(Ee)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${ii(e)}`]}function invokedViaTestRunAlias(e){let t=[];for(let n=2;n<e.length&&t.length<2;n++){let r=e[n];if(r===void 0||r===`--`)break;if(!r.startsWith(`-`)){t.push(r);continue}!r.includes(`=`)&&aa.has(r)&&n++}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth namespace is required.`,suggestion:`Ensure tailor.config.ts has an auth config.`})}async function resolveMachineUserName(e){let{cliMachineUser:t,cliMachineUserSource:n,profile:r,authConfig:i}=e,a=await Ot({machineUser:t,machineUserSource:n,profile:r});if(a)return a;if(i&&!(`external`in i&&i.external)){let e=i.machineUsers;if(e){let t=Object.keys(e);if(t.length>0)return s(t[0],`machine user key missing`)}}throw U({code:`MACHINE_USER_REQUIRED`,message:`Machine user is required.`,suggestion:`Provide --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, set a profile default with 'tailor profile update <profile> --machine-user <name>', or ensure tailor.config.ts has machine users configured.`})}async function resolveMachineUser(e){let{client:t,workspaceId:n,authNamespace:r,machineUserName:i,authConfig:a}=e,o=`00000000-0000-0000-0000-000000000000`;try{let{machineUser:e}=await t.getAuthMachineUser({workspaceId:n,authNamespace:r,name:i});e?.id&&(o=e.id)}catch{C.debug(`Could not fetch machine user "${i}" from server, using nil UUID`)}let s=a?.machineUsers?.[i],c=null,l=[];if(s&&typeof s==`object`){let e=s;c=e.attributes??null,l=e.attributeList??[]}return{name:i,id:o,attributes:c,attributeList:l}}const oa=k({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:q.object({...R,...It,file:W(q.string(),{positional:!0,description:`Path to create the script at (must end with .ts)`}),namespace:W(q.string().optional(),{description:`Target TailorDB namespace (required when the config does not pin one)`}),remote:W(q.boolean().default(!1),{description:`Generate script-scoped DB types from the deployed schema`})}),notes:"The scaffolded script is a plain default-exported function; execute it with `tailor function run <file>`.\n\nBy default, when the project configures `kyselyTypePlugin`, the skeleton imports `getDB()` from the plugin's generated types. Without the plugin, the command uses the namespace's local table definitions to write a script-scoped `db.ts` plus a `db.snapshot.json` next to the script; `function run` refuses to run the script when that snapshot no longer matches the deployed or locally defined table and field structure.\n\nPass `--remote` to generate the script-scoped files from the deployed schema instead, even when `kyselyTypePlugin` is configured. This is required for an external namespace. Re-running the command refreshes `db.ts` and `db.snapshot.json` from the selected source and leaves the script itself untouched.",examples:[{cmd:`scripts/fix-prices.ts`,desc:`Scaffold a one-off script (single-namespace project)`},{cmd:`scripts/fix-prices.ts --namespace tailordb`,desc:`Scaffold a script targeting a specific namespace`},{cmd:`scripts/fix-prices.ts --namespace shared --remote`,desc:`Scaffold from a deployed or external namespace`}],run:async e=>{let t=K.resolve(e.file);if(!t.endsWith(`.ts`))throw U({code:`SCRIPT_PATH_INVALID`,message:`Script path must end with .ts: ${e.file}`,command:`function script`});let n=K.dirname(t),r=Y.existsSync(t),i=K.join(n,ta),a=K.join(n,na);if(t===i)throw U({code:`SCRIPT_PATH_INVALID`,message:`${ta} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,command:`function script`});let{config:o,plugins:c}=await P(e.config),l=c.find(e=>e.id===ei),u=Y.existsSync(a);if(e.remote&&l!==void 0&&r&&!u)throw U({code:`SCRIPT_EXISTS`,message:`Script already exists: ${K.relative(process.cwd(),t)}.`,suggestion:`Scaffold --remote at a new path so the generated script imports its script-scoped db.ts.`});let d=e.remote||l===void 0||u,f;if(d)try{f=loadScriptSchemaSnapshot(t)?.snapshot.namespace}catch{}let p=resolveNamespace({config:o,explicit:e.namespace,sidecarNamespace:f,remote:e.remote});if(f!==void 0&&f!==p)throw U({code:`SCRIPT_NAMESPACE_MISMATCH`,message:`This directory's generated types target namespace "${f}" (${na}).`,suggestion:`Scaffold scripts for namespace "${p}" in a separate directory.`});let m=[],h,g;if(d){let t;if(e.remote){let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});g=r,C.info(`Fetching deployed schema of namespace ${w.bold(p)}...`),t=await bt(n,r,p)}else{C.info(`Loading local definitions of namespace ${w.bold(p)}...`);let{namespaces:n}=await Ne({configPath:e.config,namespaces:[p]}),r=s(n[0],`namespace ${p}`);t=Me(r.tables,p)}if(Object.keys(t.tables).length===0){let t=e.remote?`deployed tables in workspace ${s(g,`workspace ID`)}`:`locally defined tables`;throw U({code:`SCRIPT_SCHEMA_NOT_FOUND`,message:`Namespace "${p}" has no ${t}.`})}if(Y.existsSync(i)&&!isGeneratedScriptDbTypes(Y.readFileSync(i,`utf-8`)))throw U({code:`GENERATED_TYPES_NOT_OWNED`,message:`Refusing to overwrite ${K.relative(process.cwd(),i)}: it was not generated by \`tailor function script\`.`});let r=generateScriptDbTypes(t,Ar(c,`@tailor-platform/kysely-type`)?.temporal??!1);assertGeneratedTypeScript(i,r),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(i,r),m.push(i),Y.writeFileSync(a,JSON.stringify({...t,source:e.remote?`remote`:`local`},null,2)+`
|
|
77
|
+
`),m.push(a),h=`./db`}else{if(r)throw U({code:`SCRIPT_EXISTS`,message:`Script already exists: ${K.relative(process.cwd(),t)}.`,suggestion:`It imports the project's generated Kysely types, so there is nothing to refresh.`});let e=resolveKyselyTypesPath(c);h=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||C.warn(`Generated Kysely types not found at ${w.path(K.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:h,namespace:p});assertGeneratedTypeScript(t,e),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(t,e),m.unshift(t)}let _=[`function`,`run`,K.relative(process.cwd(),t)];e.config!==`tailor.config.ts`&&_.push(`--config=${e.config}`);let v=g??e[`workspace-id`];if(v!==void 0&&_.push(`--workspace-id=${v}`),e.profile!==void 0&&_.push(`--profile=${e.profile}`),C.jsonMode){C.out({script:t,created:m,namespace:p,usesGeneratedDbTypes:d});return}r&&C.info(`Script already exists; refreshed generated types only.`);for(let e of m)C.success(`Created ${w.path(K.relative(process.cwd(),e))}`);C.info(`Next: edit the script, then run ${H({command:`tailor`,args:_})}`)}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=Dr(t),o=At(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw U({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${n}" is not owned by the config and requires --remote.`,command:`function script`});return n}if(r!==void 0){if(!i&&!o.includes(r))throw U({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${r}" is not owned by the config and requires --remote.`,command:`function script`});return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?U({code:`TAILORDB_NAMESPACE_REQUIRED`,message:`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`,command:`function script`}):!i&&a.length>0?U({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`}):U({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No TailorDB namespace is defined in the config.`})}function resolveKyselyTypesPath(e){let t=Ar(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw U({code:`KYSELY_TYPE_PLUGIN_INVALID`,message:`kyselyTypePlugin is configured without a distPath; cannot locate getDB().`});return K.resolve(t)}function toImportSpecifier(e){let t=e.replace(/\.ts$/,``);return t.startsWith(`.`)?t:`./${t}`}const sa=G({name:`function`,description:`Manage functions`,subCommands:{get:we,list:lt,logs:ea,run:ia,script:oa},defaultSubCommand:`list`}),ca=k({name:`generate`,description:`Generate files using Tailor configuration.`,args:q.strictObject({config:W(q.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await Cr({configPath:e.config})}}),detectPackageManager=()=>{let e=[`npm`,`yarn`,`pnpm`,`bun`],t=process.env.npm_config_user_agent;if(!t)return;let[n]=t.split(`/`);if(e.includes(n))return n},la=k({name:`init`,description:`Initialize a new project using create-sdk.`,args:q.strictObject({name:W(q.string().optional(),{positional:!0,description:`Project name`}),template:W(q.string().optional(),{alias:`t`,description:`Template name`})}),run:async e=>{let t=await Wr(),n=t.version&&t.version!==`0.0.0`?t.version:`latest`,r=detectPackageManager();r||=(C.warn(`Could not detect package manager, defaulting to npm`),`npm`);let i=[`create`,`@tailor-platform/sdk@${n}`,...e.name?[e.name]:[],...r===`npm`?[`--`]:[],...e.template?[`--template`,e.template]:[]];C.log(`Running: ${r} ${i.join(` `)}`);let a=Ti(r,i,{stdio:`inherit`}),o={command:r,args:i};if(a.error)throw U({code:`INIT_SPAWN_FAILED`,message:`Failed to run ${r}: ${a.error.message}`,suggestion:`Check that ${r} is installed and executable.`,command:`init`,context:o,cause:a.error});if(a.status!==0)throw U({code:`INIT_FAILED`,message:a.signal===null?`${r} create exited with code ${a.status}.`:`${r} create was terminated by ${a.signal}.`,command:`init`,context:{...o,exitCode:a.status??void 0,signal:a.signal??void 0}})}}),ua=8085,da=`http://localhost:${ua}/callback`;function randomState(){return gi.randomBytes(32).toString(`base64url`)}function getProfileUserMismatch(e,t,n){if(e.profile&&e.profileUser&&t!==e.profileUser&&n!==e.profileUser)return{profile:e.profile,oldUser:e.profileUser,authenticatedUser:t,loginMode:e.loginMode??`user`}}function quoteCommandArg(e,t=process.platform){return t===`win32`?/^[A-Za-z0-9_./:@+=,-]+$/.test(e)?e:void 0:`'${e.replaceAll(`'`,`'\\''`)}'`}function profileUpdateCommand(e){let t=quoteCommandArg(e.profile),n=quoteCommandArg(e.authenticatedUser);return t&&n?`tailor profile update --user ${n} -- ${t}`:[`tailor profile update --user <authenticated-user> -- <profile>`,`profile = ${JSON.stringify(e.profile)}`,`authenticated user = ${JSON.stringify(e.authenticatedUser)}`].join(`
|
|
78
|
+
`)}function retryInstruction(e){if(e.loginMode===`machine-user`)return`Then retry the original machine-user login command.`;let t=quoteCommandArg(e.profile);return t?`Then run:\n tailor login --profile ${t}`:`Then retry the browser login with the same profile value.`}function profileUserMismatchError(e){let t=profileUpdateCommand(e),n=retryInstruction(e);return U({code:`PROFILE_USER_MISMATCH`,message:`Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".`,details:`The authenticated user has been saved.`,suggestion:`To use it with this profile, run:\n ${t}\n${n}`,context:{profile:e.profile,configuredUser:e.oldUser,authenticatedUser:e.authenticatedUser}})}function shouldUpdateCurrentUser(e,t){return!e||me(t)}const startAuthServer=async(e={})=>{let t=ne(e.platformConfig),n=randomState(),r=await hi(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:da,state:n,codeVerifier:r}).catch(e=>{throw U({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${Hr(e).message}`,cause:e})});return new Promise((a,o)=>{let handleCallback=async(i,u)=>{try{if(!i.url?.startsWith(`/callback`))throw U({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let o=`http://${i.headers.host}${i.url}`,l=new URL(o).searchParams.get(`code`);l&&C.registerSecret(l);let d=await t.authorizationCode.getTokenFromCodeRedirect(o,{redirectUri:da,state:n,codeVerifier:r});In({accessToken:d.accessToken,refreshToken:d.refreshToken??void 0});let f=await c(d.accessToken,e.platformConfig),p=await T();await Re(p,f.sub,{accessToken:d.accessToken,refreshToken:d.refreshToken??void 0},new Date(s(d.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:f.email});let m=getProfileUserMismatch(e,f.email,f.sub);if(m)throw O(p),profileUserMismatchError(m);(e.updateCurrentUser??!0)&&(p.current_user=f.sub),await it(p,f.email,f.sub,e.platformConfig),O(p),u.writeHead(200,{"Content-Type":`application/json`}),u.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a({user:f.sub,email:f.email})}catch(e){u.writeHead(401),u.end(`Authentication failed`),o(Hr(e))}finally{l.close()}},l=vi.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),o(U({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);l.on(`close`,()=>{clearTimeout(u)}),l.on(`error`,e=>{o(e)});let openBrowser=async()=>{C.info(`Opening browser for login:\n\n${i}\n`);try{await yi(i)}catch{C.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(ua,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await M.password({message:`Client secret`}),n=await _(e.clientId,t,e.platformConfig),r=await T();await Re(r,e.clientId,{accessToken:n.accessToken},new Date(s(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw O(r),profileUserMismatchError(i);return(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),O(r),{user:e.clientId,email:null}}const fa=k({name:`login`,description:`Login to Tailor Platform.`,args:q.xor([q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`User Login`),q.strictObject({"machine-user":W(q.literal(!0),{description:`Login as a platform machine user.`,required:!0}),"client-id":W(q.string(),{description:`Client ID`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID`,required:!0}),"client-secret":W(q.string().optional(),{description:`Client secret`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET`}),profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`Machine User Login`)]),run:async e=>{try{let t,n;if(`profile`in e&&e.profile){let r=(await T()).profiles[e.profile];if(!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=Rn(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t),i;i=`machine-user`in e?await loginAsMachineUser({clientId:e.clientId,clientSecret:e.clientSecret,profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`machine-user`}):await startAuthServer({profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`user`}),C.success(`Successfully logged in to Tailor Platform.`),z({changed:!0,...i})}finally{await h()}}}),pa=k({name:`logout`,description:`Logout from Tailor Platform.`,args:q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for logout.`,env:`TAILOR_PLATFORM_PROFILE`})}),run:async e=>{let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE,n=await T(),r=t?n.profiles[t]:void 0;if(t&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?Rn(r):void 0,a=r?r.user:n.current_user,o=me(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){C.info(`You are not logged in.`),z({changed:!1,user:null,revoked:!1});return}let hasDefaultUserToken=()=>sn(n,a,{platformUrl:de}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!jr(n,a))&&!hasDefaultUserToken(),c,l=!1;try{c=await Fe(n,a,i,s)}catch(e){l=!0,C.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!c&&!l){C.info(`You are not logged in.`);let e=shouldClearCurrentUser();e&&(n.current_user=null),O(n),z({changed:e,user:a,revoked:!1});return}let u=!1;if(c)try{let e=ne(i),t=c.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:c.accessToken,refreshToken:c.refreshToken??null,expiresAt:Date.parse(c.userEntry.token_expires_at)},t),u=!0}catch(e){C.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await Qt(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),O(n),C.success(`Successfully logged out from Tailor Platform.`),z({changed:!0,user:a,revoked:u})}}),ma=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:kn,token:Mn},defaultSubCommand:`list`}),ha=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:vr,get:Tn},defaultSubCommand:`list`}),ga=k({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...j}),run:async e=>{let t=await ct({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await P(e.config),r=n.name,i=`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`,a=await Tr({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),s=C.jsonMode;C.info(`Opening Tailor Platform Console...`);let c=!0;try{await yi(o)}catch{c=!1}if(s){C.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:c});return}c?(C.out(`Console URL: ${o}`),C.out(`Workspace ID: ${t}`),C.out(`Application Name: ${r}`)):C.warn(`Failed to open browser automatically. Please open this URL manually:\n${o}`)}}),_a=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:mn,delete:$n,get:Fn,list:Yn,update:xn}}),va=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:_a,get:ht,list:Vt,tree:Gt,update:Ze},defaultSubCommand:`list`}),ya=/* @__PURE__ */ `api.auth.authconnection.crashreport.deploy.executor.function.generate.init.login.logout.machineuser.oauth2client.open.organization.plugin.profile.query.remove.secret.show.skills.staticwebsite.tailordb.upgrade.user.workflow.workspace`.split(`.`),ba={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},xa=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=K.resolve(e),n=K.dirname(t);for(;n!==t;)yield t,t=n,n=K.dirname(t);yield t}function windowsExecutableExts(){return(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD;.PS1`).split(`;`).map(e=>e.trim().toLowerCase()).filter(Boolean)}function isExecutable(e){try{di(e,process.platform===`win32`?fi.F_OK:fi.X_OK)}catch{return!1}if(process.platform===`win32`){let t=K.extname(e).toLowerCase();return t===``||windowsExecutableExts().includes(t)}return!0}function binaryCandidates(e){return process.platform===`win32`?[e,...windowsExecutableExts().map(t=>`${e}${t}`)]:[e]}function pathDirs(){return(process.env.PATH??``).split(xa).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(K.join(t,`node_modules`,`.bin`));return e}function findExecutableIn(e,t){let n=binaryCandidates(t);for(let t of e)for(let e of n){let n=K.join(t,e);if(isExecutable(n))return n}}function resolvePlugin(e,t){if(e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`))return null;let n=`${t}-${e}`,r=findExecutableIn(nodeModulesBinDirs(),n);if(r)return{name:e,path:r,source:`node_modules`};let i=findExecutableIn(pathDirs(),n);return i?{name:e,path:i,source:`path`}:null}function stripBinExt(e){if(process.platform!==`win32`)return e;let t=K.extname(e);return t?e.slice(0,-t.length):e}function listPlugins(e){let t=`${e}-`,n=/* @__PURE__ */ new Map,scan=(e,r)=>{for(let i of e){let e;try{e=pi(i)}catch{continue}for(let a of e){let e=stripBinExt(a);if(!e.startsWith(t)||e.length===t.length)continue;let o=e.slice(t.length);if(n.has(o))continue;let s=K.join(i,a);isExecutable(s)&&n.set(o,{name:o,path:s,source:r})}}};return scan(nodeModulesBinDirs(),`node_modules`),scan(pathDirs(),`path`),[...n.values()]}async function resolveActiveUser(e){let t=await T(),n=e?t.profiles[e]?.user:t.current_user;if(n)return t.users[n]?.email??n}async function buildPluginEnv(e={}){let{profile:t}=e,n={},r=process.argv[1];r&&(n.TAILOR_BIN=r);try{let{version:e}=await Wr();e&&(n.TAILOR_VERSION=e)}catch{}let i=Ae();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await Ie({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=fe(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=he(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await ct({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await Or({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Si.constants.signals[e];return typeof t==`number`?128+t:1}function buildSpawnTarget(e,t){if(process.platform!==`win32`)return{command:e,args:[...t],shell:!1};let n=K.extname(e).toLowerCase();return n===`.exe`||n===`.com`?{command:e,args:[...t],shell:!1}:n===`.cmd`||n===`.bat`?{command:e,args:[...t],shell:!0}:n===`.ps1`?{command:findExecutableIn(pathDirs(),`pwsh`)??findExecutableIn(pathDirs(),`powershell`)??`powershell`,args:[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,e,...t],shell:!1}:{command:findExecutableIn(pathDirs(),`sh`)??`sh`,args:[`-c`,`command "$@"`,`--`,e,...t],shell:!1}}function hasEnvFileFlag(e){for(let t of e){if(t===`--`)return!1;if(t===`--env-file`||t===`-e`||t===`--env-file-if-exists`||t.startsWith(`--env-file=`)||t.startsWith(`-e=`)||t.startsWith(`--env-file-if-exists=`))return!0}return!1}function explicitProfileFromArgs(e){let t;for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0||r===`--`)break;if(r===`--profile`||r===`-p`){let r=e[n+1];r!==void 0&&!r.startsWith(`-`)&&(t=r,n++);continue}r.startsWith(`--profile=`)?t=r.slice(10):r.startsWith(`-p=`)&&(t=r.slice(3))}return t||void 0}function pluginSlug(e,t){return[...e??[],t].join(`-`)}async function dispatchPlugin(e){let t=pluginSlug(e.commandPath,e.name),n=resolvePlugin(t,e.cliName);if(!n)return;let r=explicitProfileFromArgs(e.args)??e.profile,i={...process.env,...await buildPluginEnv({profile:r,skipPlatformContext:hasEnvFileFlag(e.args)})},{command:a,args:o,shell:s}=buildSpawnTarget(n.path,e.args);return await new Promise(n=>{let r=wi(a,o,{stdio:`inherit`,env:i,shell:s});r.on(`error`,r=>{C.error(`Failed to run plugin "${e.cliName}-${t}": ${r.message}`),n(1)}),r.on(`close`,(e,t)=>{n(t?signalToExitCode(t):e??0)})})}async function dispatchPluginWithInstallHint(e){let t=await dispatchPlugin(e);if(t!==void 0)return t;let n=ba[pluginSlug(e.commandPath,e.name)];if(!n)return;let r=[e.cliName,...e.commandPath??[],e.name].join(` `);return C.error(`"${r}" is provided by the ${n} CLI plugin, which is not installed.`),C.info(`Install it with: npm install -D ${n}`),1}const Sa=k({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Wr(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(ya),r=listPlugins(t);if(r.length===0){C.info(V`
|
|
79
79
|
No plugins found.
|
|
80
80
|
Install an executable named "${t}-<name>" on your PATH or in node_modules/.bin,
|
|
81
81
|
then run it with "${t} <name>".
|
|
82
|
-
`),C.jsonMode&&C.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));C.out(i);for(let e of i)e.shadowed&&C.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),
|
|
82
|
+
`),C.jsonMode&&C.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));C.out(i);for(let e of i)e.shadowed&&C.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),Ca=G({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:Sa},defaultSubCommand:`list`}),wa=k({name:`create`,description:`Create a new profile.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string(),{alias:`u`,description:`User email address or machine user client ID`}),"workspace-id":W(q.string(),{alias:`w`,description:`Workspace ID`}),permission:W(q.enum([`write`,`read`]).default(`write`),{description:`Profile permission. 'read' blocks all write commands while the profile is active.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token).`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user.`}),"platform-url":W(q.url().optional(),{description:`Platform API base URL for this profile.`,env:`TAILOR_PLATFORM_URL`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform.`,env:`TAILOR_PLATFORM_OAUTH2_CLIENT_ID`}),"console-url":W(q.url().optional(),{description:`Console base URL for this profile.`,env:`TAILOR_PLATFORM_CONSOLE_URL`})}),run:async e=>{if(e[`machine-user-override`]===`deny`&&!e[`machine-user`])throw U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile create`});let t=await T();if(t.profiles[e.name])throw U({code:`PROFILE_EXISTS`,message:`Profile "${e.name}" already exists.`});let n={...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}},r=Object.keys(n).length>0?n:void 0,{accessToken:i,user:a}=await br(t,e.user,r),o=await le(i,r);if(!(await m(async(e,t)=>{let{workspaces:n,nextPageToken:r}=await o.listWorkspaces({pageToken:e,pageSize:t});return[n,r]})).find(t=>t.id===e[`workspace-id`]))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${e[`workspace-id`]}" not found.`});t.profiles[e.name]={user:a,workspace_id:e[`workspace-id`],...e.permission===`read`?{readonly:!0}:{},...e[`machine-user`]?{machine_user:e[`machine-user`]}:{},...e[`machine-user-override`]===`deny`?{machine_user_override:`deny`}:{},...e[`platform-url`]?{platform_url:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2_client_id:e[`oauth2-client-id`]}:{},...e[`console-url`]?{console_url:e[`console-url`]}:{}},O(t),e.json||C.success(`Profile "${e.name}" created successfully.`);let s={name:e.name,user:a,workspaceId:e[`workspace-id`],permission:e.permission,...e[`machine-user`]?{machineUser:e[`machine-user`],machineUserOverride:e[`machine-user-override`]??`allow`}:{},...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}};C.out(s)}}),Ta=k({name:`delete`,description:`Delete a profile.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await T();if(!t.profiles[e.name])throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});delete t.profiles[e.name],O(t),C.success(`Profile "${e.name}" deleted successfully.`),z({changed:!0,name:e.name})}}),Ea=k({name:`list`,description:`List all profiles.`,args:q.strictObject({}),run:async()=>{let e=await T(),t=C.jsonMode,n=Object.entries(e.profiles);if(n.length===0){C.info(V`
|
|
83
83
|
No profiles found.
|
|
84
84
|
Please create a profile first using 'tailor profile create' command.
|
|
85
|
-
`),t&&C.out([]);return}let r=n.map(([e,t])=>{let n=o(t,`profile entry "${e}" is undefined`);return{name:e,user:n.user,workspaceId:n.workspace_id,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}}});C.out(r)}}),xa=T({name:`update`,description:`Update profile properties.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":W(q.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:W(q.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token). Pass an empty string to clear.`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.`}),"platform-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Console base URL for this profile. Pass an empty string to clear.`})}),run:async e=>{let t=await E(),n=t.profiles[e.name];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});if(!e.user&&!e[`workspace-id`]&&e.permission===void 0&&e[`machine-user`]===void 0&&e[`machine-user-override`]===void 0&&e[`platform-url`]===void 0&&e[`oauth2-client-id`]===void 0&&e[`console-url`]===void 0)throw U({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,c=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,l=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,u=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,d=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,f=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,p={...u?{platformUrl:u}:{},...d?{oauth2ClientId:d}:{},...f?{consoleUrl:f}:{}},m=Object.keys(p).length>0?p:void 0,h=e[`platform-url`]===``?bt(n):m;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&l===`deny`&&!c)throw e[`machine-user-override`]===`deny`?U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):U({code:`PROFILE_OPTIONS_INVALID`,message:`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`,command:`profile update`});if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let n=await cn(t,i,h,e.name);s=n.user;let r=await S(n.accessToken,m);if(!(await fe(async(e,t)=>{let{workspaces:n,nextPageToken:i}=await r.listWorkspaces({pageToken:e,pageSize:t});return[n,i]})).find(e=>e.id===o))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${o}" not found.`})}n.user=s,n.workspace_id=o,e.permission===`read`?n.readonly=!0:e.permission===`write`&&delete n.readonly,e[`machine-user`]!==void 0&&(e[`machine-user`]===``?delete n.machine_user:n.machine_user=e[`machine-user`]),e[`machine-user-override`]===`deny`?n.machine_user_override=`deny`:e[`machine-user-override`]===`allow`&&delete n.machine_user_override,e[`platform-url`]!==void 0&&(e[`platform-url`]===``?delete n.platform_url:n.platform_url=e[`platform-url`]),e[`oauth2-client-id`]!==void 0&&(e[`oauth2-client-id`]===``?delete n.oauth2_client_id:n.oauth2_client_id=e[`oauth2-client-id`]),e[`console-url`]!==void 0&&(e[`console-url`]===``?delete n.console_url:n.console_url=e[`console-url`]),F(t),e.json||C.success(`Profile "${e.name}" updated successfully`);let g={name:e.name,user:s,workspaceId:o,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}};C.out(g)}}),Sa=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:va,delete:ya,list:ba,update:xa},defaultSubCommand:`list`});async function resolveSecretValue(e,t,n){if(e.value!==void 0)return e.value;let missing=e=>U({code:`SECRET_VALUE_REQUIRED`,message:`No secret value was given: --value is omitted and standard input ${e}.`,suggestion:`Pass --value, or pipe or redirect the value into the command.`,command:n});if(t.isTTY===!0)throw missing(`is a terminal`);let tooLarge=()=>U({code:`SECRET_VALUE_TOO_LARGE`,message:`The secret value read from standard input exceeds 128 KiB.`,command:n}),r=[],i=0;for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e;if(i+=t.length,i>131074)throw tooLarge();r.push(t)}let a;try{a=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(Buffer.concat(r))}catch(e){throw U({code:`SECRET_VALUE_INVALID_UTF8`,message:`The secret value read from standard input is not valid UTF-8.`,command:n,cause:e})}let o=a.replace(/\r?\n$/,``);if(Buffer.byteLength(o)>131072)throw tooLarge();if(o===``)throw missing(`is empty`);return o}const Ca={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},wa={...Ca,name:W(q.string(),{alias:`n`,description:`Secret name`})},Ta={...wa,value:W(q.string().optional(),{alias:`v`,description:`Secret value (read from standard input when omitted)`})};function secretValueNotes(e){return`Pass the value with \`--value\`, or omit \`--value\` and pipe the value in to keep it out of shell history and process listings, for example \`printf '%s' "$STRIPE_KEY" | tailor secret ${e} --vault-name api-keys --name stripe-secret-key\`. A piped value can be up to 128 KiB, and one trailing newline is removed from it. In a vault managed by \`defineSecretManager()\`, the command asks for confirmation before releasing the vault from the config, which needs an interactive terminal, so pass \`--yes\` when piping the value.`}async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=A(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[xe]}catch{return a}return o?(C.warn(`Vault "${r}" is managed by defineSecretManager() in tailor.config.ts (owner: "${o}"). Changes made via CLI may conflict with the config on the next apply.`),{isManaged:!0,trn:i,existingLabels:s}):a}async function releaseVaultOwnership(e){let{client:t,trn:n}=e;await or(t,{trn:n,remove:[xe,fn,pt]}),C.info(`Config ownership has been removed from this vault. Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.`)}const Ea=T({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...k,...Ta,...D}),notes:secretValueNotes(`create`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret create`);C.registerSecret(t),await N({profile:e.profile});let{client:n,workspaceId:r}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await P.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_CREATION_CANCELLED`,message:`Secret creation cancelled. The vault is still managed by the config.`});try{await n.createSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw U({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),C.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}),Da=T({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...k,...wa,...D}),run:async e=>{await N({profile:e.profile});let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await P.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`SECRET_DELETION_CANCELLED`,message:`Secret deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),C.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`)}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e.workspaceId}),r=We(e.order);return(await b(async(i,a)=>{let{secrets:o,nextPageToken:s}=await t.listSecretManagerSecrets({workspaceId:n,secretmanagerVaultName:e.vaultName,pageToken:i,pageSize:a,pageDirection:r});return[o,s]},{limit:e.limit})).map(secretInfo)}const Oa=T({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...k,...Ca,...Ot()}),run:async e=>{try{let t=await L(e.limit,t=>secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:t})),n=t.items;C.out(n),await z(t,e.limit)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),ka=T({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...k,...Ta,...D}),notes:secretValueNotes(`update`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret update`);C.registerSecret(t),await N({profile:e.profile});let{client:n,workspaceId:r}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await P.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_UPDATE_CANCELLED`,message:`Secret update cancelled. The vault is still managed by the config.`});try{await n.updateSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),C.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`)}}),Aa={name:W(q.string(),{positional:!0,description:`Vault name`})},ja=T({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...k,...Aa}),run:async e=>{await N({profile:e.profile});let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]});try{await t.createSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.AlreadyExists?U({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}C.success(`Vault: ${e.name} created`),R({changed:!0,workspaceId:n,name:e.name})}}),Ma=T({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...k,...Aa,...D}),run:async e=>{await N({profile:e.profile});let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await P.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`VAULT_DELETION_CANCELLED`,message:`Vault deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&C.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),C.success(`Vault: ${e.name} deleted`)}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await M({profile:e?.profile,workspaceId:e?.workspaceId}),r=We(e?.order);return(await b(async(e,i)=>{let{vaults:a,nextPageToken:o}=await t.listSecretManagerVaults({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const Na=T({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...k,...Ot()}),run:async e=>{let t=await L(e.limit,t=>vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),n=t.items;C.out(n),await z(t,e.limit)}}),Pa=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:ja,delete:Ma,list:Na},defaultSubCommand:`list`}),Fa=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Pa,create:Ea,update:ka,list:Oa,delete:Da},defaultSubCommand:`vault`}),Ia={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},La=T({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...k,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Custom domain "${e.domain}" not found.`;try{let{customDomain:i}=await t.getCustomDomain({workspaceId:n,domain:e.domain});if(!i)throw U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:Ia[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};C.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),Ra=T({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...k,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]});try{let{customDomains:r}=await t.listCustomDomains({workspaceId:n,staticWebsiteName:e.name});if(r.length===0){C.info(`No custom domains found.`),C.jsonMode&&C.out([]);return}let i=r.map(e=>({domain:e.domain,status:Ia[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));C.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),za=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:Ra,get:La}}),Ba=T({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...k,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await M({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Static website "${e.name}" not found.`;try{let{staticwebsite:i}=await t.getStaticWebsite({workspaceId:n,name:e.name});if(!i)throw U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r});let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
|
|
86
|
-
`)};C.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await M({profile:e?.profile,workspaceId:e?.workspaceId}),r=We(e?.order);return(await b(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const Va=T({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...k,...Ot()}),run:async e=>{let t=C.jsonMode,n=await L(e.limit,t=>listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),r=n.items,i=t?r:r.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});C.out(i),await z(n,e.limit)}}),Ha=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:He,domain:za,list:Va,get:Ba},defaultSubCommand:`list`}),Ua=new Set(Object.values(Et));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=K.dirname(i),o=K.basename(i),s=await $.mkdtemp(K.join(a,`.${o}-rebaseline-`)),c=`${s}-previous`,l=!1,u=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!je.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Ua.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:6,createdAt:(/* @__PURE__ */ new Date()).toISOString(),rebaseline:r},a=await At(e,s,0);Ne(a.filePath),await $.rename(i,c),l=!0;try{await $.rename(s,i),u=!0}catch(e){throw await $.rename(c,i),l=!1,e}try{await $.rm(c,{recursive:!0,force:!0})}catch(e){C.warn(`The previous migration directory remains at ${c}: ${e instanceof Error?e.message:String(e)}`)}l=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!u&&l&&Y.existsSync(c)&&await $.rename(c,i)}}async function rebaseline(e){Le(`tailordb migration`);let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=Pn(B(t,r),e.namespace),a=`First run ${H({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;xn(i.migrationsDir,i.namespace);let o=j(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=Mn(i.migrationsDir),c=j(i.migrationsDir,0)?.rebaseline?.historyId??null,l=un([i])[i.namespace],u=n.length>0?new Kr(n):void 0,{defineApplication:d}=await import(`../application-ChqHuhZW.mjs`),f=d({config:t,pluginManager:u});for(let e of f.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let p=f.tailorDBServices.find(e=>e.namespace===i.namespace);if(!p)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=zn(p.types,i.namespace),t=Nt(o,e.tables,i.namespace);if(Wt(t))throw C.error(`Migration history does not reproduce the current local schema for namespace ${w.bold(i.namespace)}:`),C.log(Ke(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...Ar(p.config,r)];assertLocalTypesReady();let m=fr(localSourceFiles()),{client:h,workspaceId:g}=await M({profile:e.profile,workspaceId:e.workspaceId}),_=[`--config`,t.path,...Fe({workspaceId:g,profile:e.profile})],v=`Run ${H({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,..._]})}`,y=`after resolving the connection error, deploy with schema checks enabled by running ${H({command:`tailor`,args:[`deploy`,..._]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await Wn(h,A(g,`tailordb`,i.namespace)),a=r.number;if(a!==s){let e=a===null?`<unset>`:O(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${O(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw U({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw U(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await Lt(h,g,[i],t,[kt(p)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(C.error(`Remote schema drift detected:`),C.log(we(o))),U({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(c,`initial`),C.newline(),C.warn(`This will replace the migration history for ${w.bold(i.namespace)}.`),C.log(` Latest migration: ${O(s)}`),C.log(` New history: 0000/schema.json only`),C.log(` migrate.ts and db.ts files will disappear from the working tree.`),C.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),C.log(` Every other environment must already be at the latest migration.`),C.log(` The connected workspace checkpoint will be reset to 0000.`),C.newline(),!e.yes&&!await P.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw U({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(xn(i.migrationsDir,i.namespace),un([i])[i.namespace]!==l)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(fr(localSourceFiles())!==m)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(c,`confirmation`);let ee={historyId:vt(),replacedHistoryId:c,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,ee);try{await Xe(h,g,i.namespace,0,ee.historyId)}catch(e){throw U({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${v}, or ${y}`,cause:e})}C.success(`Re-baselined ${w.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const Wa=T({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...$e,...D,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await N({profile:e.profile}),await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});async function set(e){Le(`tailordb migration`);let t=Ze(e.number),{config:n}=await I(e.configPath),r=K.dirname(n.path),i=B(n,r),a=Pn(i,e.namespace),o=a.namespace;xn(a.migrationsDir,o),st(a.migrationsDir,t);let s=j(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await M({profile:e.profile,workspaceId:e.workspaceId}),u=A(l,`tailordb`,o),d=await Wn(c,u),f=d.number,p=f??0,m=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,h=s??`<unset>`;if(C.newline(),C.warn(`This operation will change TailorDB migration state metadata.`),C.log(`Namespace: ${w.bold(o)}`),C.log(`Current migration: ${f===null?`<unset>`:w.bold(O(f))}`),C.log(`New migration: ${w.bold(O(t))}`),C.log(`Current migration history ID: ${w.bold(m)}`),C.log(`New migration history ID: ${w.bold(h)}`),C.newline(),t<p?(C.warn(`Setting migration number backwards (${O(p)} → ${O(t)}) will cause previous migrations to be re-executed on next apply.`),C.newline()):t>p&&(C.warn(`Setting migration number forwards (${O(p)} → ${O(t)}) will skip migrations ${O(p+1)} to ${O(t)}.`),C.newline()),!e.yes){if(!await P.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw U({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});C.newline()}await or(c,{trn:u,labels:{[et]:Te(t),...s?{[Ue]:s}:{}},remove:s?void 0:[Ue]}),C.success(`Migration checkpoint set to ${w.bold(O(t))} for namespace ${w.bold(o)}`)}const Ga=T({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...$e,...D,number:W(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await N({profile:e.profile}),await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await I(e.configPath),n=K.dirname(t.path),r=B(t,n);if(r.length===0)throw sn();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=rt(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n){if(e.type===`schema`){let t=Ne(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=ut(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Nr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Fr(t))}if(a.size===0)return i.map(({namespace:e})=>({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`}));let{client:s,workspaceId:c}=await M({profile:e.profile,workspaceId:e.workspaceId}),l=[];for(let{namespace:e}of i){if(o.has(e)){l.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){l.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,u=A(c,`tailordb`,e),d;try{d=await Wn(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:O(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:O(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(C.newline(),C.info(`Namespace: ${w.bold(t.namespace)}`),isStatusFailure(t)){C.error(` Migration status error: ${t.error}`);continue}if(C.log(` Current migration: ${w.bold(t.currentMigrationLabel)}`),t.pendingMigrations.length>0){C.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?C.log(` - ${e.label}: ${e.description}`):C.log(` - ${e.label}`)}else C.log(` Pending migrations: (none)`)}C.newline()}async function status(e){Le(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?C.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw U({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const Ka=T({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...$e,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:C.jsonMode})}});async function fetchRemoteGqlPermissions(e,t,n){return f(async(r,i)=>{let{permissions:a,nextPageToken:o}=await e.listTailorDBGQLPermissions({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e,t,n){return fe(async(r,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await e.listTailorDBTypes({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,suggestion:`Deploy the namespace before syncing its migration history.`,cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Kr(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-ChqHuhZW.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let l=o(i,s.tailorDBServices,n.path),u=s.executorService??(l.length>0?(await import(`../service-Bx-7Lz06.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await u?.loadExecutors(),l.length>0&&await u?.loadPluginExecutorFiles([...l]);let d=/* @__PURE__ */ new Set;for(let e of Object.values(u?.executors??{}))Ht(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let f={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},p=j(t.migrationsDir);if(!p)return f;let m=zn(c.types,t.namespace),h=Nt(p,m.tables,t.namespace);if(!Wt(h))return f;throw C.error(`Migration history does not reproduce the current local schema for namespace ${w.bold(t.namespace)}:`),C.log(Ke(h)),C.newline(),C.info(`This usually means one of the following:`),C.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),C.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),C.newline(),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){Le(`tailordb migration`);let t=Ze(e.number),n=await I(e.configPath),{config:r}=n,i=K.dirname(r.path),a=B(r,i),o=Pn(a,e.namespace);xn(o.migrationsDir,o.namespace);let s=st(o.migrationsDir,t),c=j(o.migrationsDir,t);if(!c)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let l=await assertMigrationsReproduceLocalTypes(n,o),{client:u,workspaceId:d}=await M({profile:e.profile,workspaceId:e.workspaceId}),f=A(d,`tailordb`,o.namespace),p=await $t(u,f),m=await fetchRemoteTypes(u,d,o.namespace),h=new Set(m.map(e=>e.name)),{creates:g,updates:_,deletes:v}=Hn(c,h),y=await fetchRemoteGqlPermissions(u,d,o.namespace),ee=new Set(y.map(e=>e.typeName)),b=Object.entries(c.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:Dn(t.permissions.gql)}]:[]),te=new Set(b.map(e=>e.typeName)),x=y.filter(e=>!te.has(e.typeName));if(C.newline(),C.info(`Namespace: ${w.bold(o.namespace)}`),C.log(` Current migration: ${p===null?`<unset>`:w.bold(O(p))}`),C.log(` Target migration: ${w.bold(O(t))}`),C.log(` Tables to create: ${w.bold(String(g.length))}`),C.log(` Tables to update: ${w.bold(String(_.length))}`),C.log(` Tables to delete: ${w.bold(String(v.length))}`),C.log(` GQL permissions to set: ${w.bold(String(b.length))}`),C.log(` GQL permissions to delete: ${w.bold(String(x.length))}`),C.newline(),g.length+_.length+v.length+b.length+x.length===0?C.info(`No tables to apply; only the migration label will be updated.`):(C.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),v.length>0&&C.warn(`Existing data in deleted tables will be lost.`),C.newline()),C.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),C.newline(),p!==null&&t<p?(C.warn(`Migrations ${O(t+1)}–${O(p)} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`),C.newline()):p!==null&&t>p&&(C.warn(`Moving the migration label forwards (${O(p)} → ${O(t)}): migrate.ts scripts for migrations ${O(p+1)}–${O(t)} will not run on the next deploy.`),C.newline()),!e.yes){if(!await P.confirm({message:`Continue and set migration label to ${O(t)}?`,default:!1}))throw U({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});C.newline()}let S=er(c,l),manifestFor=e=>{let t=S.get(e);if(!t)throw Pr(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ne=g.map(e=>manifestFor(e)),re=_.map(e=>manifestFor(e));try{await Promise.all([...ne.map(e=>u.createTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbType:e})),...re.map(e=>u.updateTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbType:e}))])}catch(e){kr(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}await Promise.all(b.map(({typeName:e,permission:t})=>{let n={workspaceId:d,namespaceName:o.namespace,typeName:e,permission:t};return ee.has(e)?u.updateTailorDBGQLPermission(n):u.createTailorDBGQLPermission(n)})),await Promise.all(x.map(e=>u.deleteTailorDBGQLPermission({workspaceId:d,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(v.map(e=>u.deleteTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbTypeName:e}))),await or(u,{trn:f,labels:{[et]:Te(t),...c.rebaseline?.historyId?{[Ue]:c.rebaseline.historyId}:{}},remove:c.rebaseline?.historyId?void 0:[Ue]}),C.success(`Synced namespace ${w.bold(o.namespace)} to migration ${w.bold(O(t))}.`),t<s&&(C.newline(),C.info(`Run 'tailor deploy' to apply migrations ${O(t+1)}–${O(s)} from the working tree.`))}const qa=T({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...$e,...D,number:W(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await N({profile:e.profile}),await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=Y.statSync(e)}catch(t){throw t.code===`ENOENT`?U({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw U({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=K.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?U({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw U({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw U({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw U({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw U({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>Or(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,o(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,i=t.timeout??3e5,a=Date.now()+i;for(;Date.now()<=a;){let i=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw U({code:`MIGRATION_TEST_CLONE_FAILED`,message:`Application data clone failed: ${i.errorMessage||`unknown platform error`}`});if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw Pr(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw U({code:`MIGRATION_TEST_CLONE_TIMEOUT`,message:`Application data clone timed out after ${Math.round(i/1e3)} seconds.`})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=K.join(e,`${i}.jsonl`),o;try{o=Y.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
|
|
87
|
-
`).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw U({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw U({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,/* @__PURE__ */ new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=/* @__PURE__ */ new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=/* @__PURE__ */ new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=/* @__PURE__ */ new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=/* @__PURE__ */ new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${di(3).toString(`hex`)}`}function stateOrThrow(e){return o(e,`migration test runtime was used before preparation`)}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=B(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(kt),o=(await Lt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let r of i){let i=t.baselines.get(r.namespace);if(!i)continue;let a=await $t(e.client,A(n,`tailordb`,r.namespace));if(a!==i.migrationNumber)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" moved from migration ${i.migrationNumber} to ${a??`none`} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await Or(e.client,n,r.namespace);if(Be(i,a).changes.length>0)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await me(()=>e.client.getUserProfileConfig({workspaceId:t,namespaceName:r}))&&await e.client.deleteUserProfileConfig({workspaceId:t,namespaceName:r})}function migrationConfig(e,t){return e.config.db?.[t]?.migration}function authExecutionContext(e,t,n){let r=e.loaded.application.authService;if(!r)throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??Ie(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw U({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await Ee({configPath:e.configPath}),n=K.dirname(t.config.path),r=B(t.config,n);if(r.length===0)throw sn();for(let e of r)xn(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await it({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(kt),s=await Ln({profile:e.profile}),c=await Cr({profile:e.profile}),l=await S(s,c),u=await br({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,f,p]=await Promise.all([l.getWorkspace({workspaceId:u}),l.getApplication({workspaceId:u,applicationName:t.config.name}),e.data===`clone`&&e.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=o(d.workspace,`source workspace "${u}" not found`);o(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?o(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,g=await Lt(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${_.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let v=g.find(e=>e.checkpointRepair);if(v)throw U({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${v.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let y=/* @__PURE__ */ new Map,ee=/* @__PURE__ */ new Map,b=[];for(let e of r){let t=await $t(l,A(u,`tailordb`,e.namespace));if(t===null)throw U({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${e.namespace}" has no sdk-migration checkpoint.`,suggestion:`Deploy or set the migration checkpoint before testing.`});let n=Mn(e.migrationsDir);if(t>n)throw U({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${t}, but the local history ends at ${n}.`});let r=j(e.migrationsDir,t);if(!r)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});y.set(e.namespace,{migrationNumber:t,snapshot:r,historyId:r.rebaseline?.historyId??null});let i=j(e.migrationsDir,n);if(!i)throw U({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});ee.set(e.namespace,i),t<n&&b.push(e.namespace)}if(b.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let te=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),x={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:y,baselineSnapshots:te,targetSnapshots:ee,pendingNamespaces:b,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:x}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await on(n.client,t.temporaryWorkspace);return C.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name}},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await $n({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.baselines,t.baselineSnapshots);for(let[e,i]of t.baselines)await Xe(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=o(r.seedContext,`seed context missing after migration test preparation`),a=K.join(i.distPath,`data`);assertSeedDataDirectory(a);let s=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=kt(e);return[e.namespace,n?.snapshot??Rt({version:1,namespace:e.namespace,createdAt:(/* @__PURE__ */ new Date()).toISOString(),tables:r.types})]}));for(let[e,t]of s){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await Ve(e,l,K.dirname(r.loaded.config.path)),d=ct({data:c,order:o,codeByteSize:new TextEncoder().encode(u.bundledCode).length}),f=authExecutionContext(r,e,r.options.machineUser??i.machineUserName);for(let t of d){let i=await ke({client:r.client,workspaceId:n,name:`migration-test-seed-${e}.ts`,code:u.bundledCode,arg:{data:t.data,order:t.order,selfRefTypes:s,upsert:!1},invoker:{namespace:f.authNamespace,machineUserName:f.machineUserName}});if(!i.success)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i})=>{let a=stateOrThrow(e);await assertSourceBaselineFresh(a,t,n),C.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let o;try{o=(await a.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?U({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!o)throw Pr(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(a.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:o})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await En({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.targetSnapshots)},runAssertion:async({prepared:t,targetWorkspaceId:n,assertionPath:r,assertionNamespace:i,machineUser:a})=>{let o=stateOrThrow(e),s=resolveAssertionNamespace(t.pendingNamespaces,i),c=authExecutionContext(o,s,a),l=await sr(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path)),u=await ke({client:o.client,workspaceId:n,name:`migration-test-assert-${s}.ts`,code:l.bundledCode,invoker:{namespace:c.authNamespace,machineUserName:c.machineUserName}});if(!u.success)throw U({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=o(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:o(e.targetWorkspaceId,`designated target workspace missing`),name:void 0},a,s=!1,c=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){a=e,s=!0}if(r&&e.keep)C.info(`Keeping temporary workspace ${i.name??i.id}.`);else if(r)try{await t.deleteWorkspace(i.id),c=!0}catch(t){if(!s)throw U({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});C.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(s)throw a;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:c,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){Le(`tailordb migration`);let t=await runMigrationTest(e);if(e.json){C.out(t);return}C.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const Ja=T({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs.`,args:q.strictObject({...$e,yes:W(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:W(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":W(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:W(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:W(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":W(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"machine-user":W(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await N({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],yes:e.yes,json:C.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[];for(let t of rt(e)){if(t.type!==`diff`)continue;let n=ut(t.path),s=kn(e,t.number,`migrate`),c=Y.existsSync(s);n.requiresMigrationScript&&!n.scriptSkipped&&!c&&r.push(t.number),n.scriptSkipped&&c&&i.push(t.number),c&&Y.readFileSync(s,`utf8`).includes(`TODO(tailor-migration-review)`)&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!c&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw U({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(O).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${pn({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
88
|
-
`);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(O).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw U({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(O).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts.`,suggestion:`Review each ${Ce} marker, then remove the marker and its associated \`never\` annotation.`});return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let s=o(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:s.hasDiff,...s.diff?{diff:s.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=o(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=B(t,r);if(i.length===0)throw sn();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new Kr(n):void 0,{defineApplication:s}=await import(`../application-ChqHuhZW.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();ge({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(kt),u=new Map(l.map(e=>[e.namespace,e.types])),d=/* @__PURE__ */ new Map,f=[],p=e.strict?/* @__PURE__ */ new Map:void 0;for(let t of a)try{xn(t.migrationsDir,t.namespace),j(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,Fr(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await _t(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await M({profile:e.profile,workspaceId:e.workspaceId});h=await Lt(n,r,f,t,l)}catch(e){return{reports:buildValidationReports(m),remoteError:e}}return{reports:buildValidationReports({...m,remoteResults:h})}}function printValidationReports(e){for(let t of e){if(C.newline(),C.info(`Namespace: ${w.bold(t.namespace)}`),!t.migrationFiles.valid){C.log(` Migration files: ${w.error(`invalid`)}`),C.log(` ${t.migrationFiles.error}`);continue}C.log(` Migration files: ${w.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(C.log(` Local schema: ${w.error(`changes not in migration files`)}`),C.log(` ${Qn(e.diff)}`),C.log(Ke(e.diff))):C.log(` Local schema: ${w.error(`no migration snapshot found`)}`):C.log(` Local schema: ${w.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?C.log(` Remote schema: ${w.error(`not checked`)}`):n?.checkpointRepair?C.log(` Remote schema: ${w.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${O(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(C.log(` Remote schema: ${w.error(`remote migration ${O(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&C.log(` Fell behind before 'migration rebaseline' ran; must reach ${O(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(C.log(` Remote schema: ${w.error(`drift detected`)} (remote migration: ${O(n.remoteMigrationNumber)})`),C.log(qn(n.drifts))):n?.skipped===`not_deployed`?C.log(` Remote schema: ${w.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?C.log(` Remote schema: ${w.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?C.log(` Remote schema: ${w.dim(`skipped (no local snapshot for remote migration ${O(n.remoteMigrationNumber)})`)}`):n&&C.log(` Remote schema: ${w.success(`OK`)} (remote migration: ${O(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)C.log(` Warning acknowledgments: ${w.success(`OK`)}`);else{C.log(` Warning acknowledgments: ${w.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=O(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;C.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}C.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&C.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&C.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&Mt(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&ze(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let r=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(r.length>0){C.info(`For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:`);for(let e of r)for(let n of e.warningAcknowledgments?.missing??[])C.info(` ${pn({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){Le(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?C.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?C.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw U({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const Ya=T({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...$e,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:C.jsonMode,strict:e.strict})}}),Xa=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:ht,rebaseline:Wa,script:Er,set:Ga,status:Ka,sync:qa,test:Ja,validate:Ya}}),Za=G({name:`tailordb`,description:`Manage TailorDB tables and data.`,notes:"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.",subCommands:{truncate:nt,migration:Xa}}),Qa=T({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:W(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":W(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:W(q.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t();let{upgrade:n}=await import(`../service-DFmt9UJP.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),$a=T({name:`current`,description:`Show current user.`,args:q.strictObject({profile:k.profile}),run:async e=>{let t=await E(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?bt(r):void 0,a=n?r?.user??null:t.current_user,o=C.jsonMode;if(!a)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...Fe({profile:n})]}});if(!Gn(t,a,i))throw U({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...Fe({profile:n})]}});if(o){C.out({user:a});return}C.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?Oe(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return Oe(e,n.user,bt(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const eo=T({name:`list`,description:`List all users.`,args:q.strictObject({profile:k.profile}),run:async e=>{let t=await E(),n=C.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){C.info(V`
|
|
85
|
+
`),t&&C.out([]);return}let r=n.map(([e,t])=>{let n=s(t,`profile entry "${e}" is undefined`);return{name:e,user:n.user,workspaceId:n.workspace_id,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}}});C.out(r)}}),Da=k({name:`update`,description:`Update profile properties.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":W(q.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:W(q.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token). Pass an empty string to clear.`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.`}),"platform-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Console base URL for this profile. Pass an empty string to clear.`})}),run:async e=>{let t=await T(),n=t.profiles[e.name];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});if(!e.user&&!e[`workspace-id`]&&e.permission===void 0&&e[`machine-user`]===void 0&&e[`machine-user-override`]===void 0&&e[`platform-url`]===void 0&&e[`oauth2-client-id`]===void 0&&e[`console-url`]===void 0)throw U({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,c=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,l=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,u=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,d=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,f=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,p={...u?{platformUrl:u}:{},...d?{oauth2ClientId:d}:{},...f?{consoleUrl:f}:{}},h=Object.keys(p).length>0?p:void 0,g=e[`platform-url`]===``?Rn(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&l===`deny`&&!c)throw e[`machine-user-override`]===`deny`?U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):U({code:`PROFILE_OPTIONS_INVALID`,message:`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`,command:`profile update`});if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let n=await br(t,i,g,e.name);s=n.user;let r=await le(n.accessToken,h);if(!(await m(async(e,t)=>{let{workspaces:n,nextPageToken:i}=await r.listWorkspaces({pageToken:e,pageSize:t});return[n,i]})).find(e=>e.id===o))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${o}" not found.`})}n.user=s,n.workspace_id=o,e.permission===`read`?n.readonly=!0:e.permission===`write`&&delete n.readonly,e[`machine-user`]!==void 0&&(e[`machine-user`]===``?delete n.machine_user:n.machine_user=e[`machine-user`]),e[`machine-user-override`]===`deny`?n.machine_user_override=`deny`:e[`machine-user-override`]===`allow`&&delete n.machine_user_override,e[`platform-url`]!==void 0&&(e[`platform-url`]===``?delete n.platform_url:n.platform_url=e[`platform-url`]),e[`oauth2-client-id`]!==void 0&&(e[`oauth2-client-id`]===``?delete n.oauth2_client_id:n.oauth2_client_id=e[`oauth2-client-id`]),e[`console-url`]!==void 0&&(e[`console-url`]===``?delete n.console_url:n.console_url=e[`console-url`]),O(t),e.json||C.success(`Profile "${e.name}" updated successfully`);let _={name:e.name,user:s,workspaceId:o,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}};C.out(_)}}),Oa=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:wa,delete:Ta,list:Ea,update:Da},defaultSubCommand:`list`});async function resolveSecretValue(e,t,n){if(e.value!==void 0)return e.value;let missing=e=>U({code:`SECRET_VALUE_REQUIRED`,message:`No secret value was given: --value is omitted and standard input ${e}.`,suggestion:`Pass --value, or pipe or redirect the value into the command.`,command:n});if(t.isTTY===!0)throw missing(`is a terminal`);let tooLarge=()=>U({code:`SECRET_VALUE_TOO_LARGE`,message:`The secret value read from standard input exceeds 128 KiB.`,command:n}),r=[],i=0;for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e;if(i+=t.length,i>131074)throw tooLarge();r.push(t)}let a;try{a=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(Buffer.concat(r))}catch(e){throw U({code:`SECRET_VALUE_INVALID_UTF8`,message:`The secret value read from standard input is not valid UTF-8.`,command:n,cause:e})}let o=a.replace(/\r?\n$/,``);if(Buffer.byteLength(o)>131072)throw tooLarge();if(o===``)throw missing(`is empty`);return o}const ka={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},Aa={...ka,name:W(q.string(),{alias:`n`,description:`Secret name`})},ja={...Aa,value:W(q.string().optional(),{alias:`v`,description:`Secret value (read from standard input when omitted)`})};function secretValueNotes(e){return`Pass the value with \`--value\`, or omit \`--value\` and pipe the value in to keep it out of shell history and process listings, for example \`printf '%s' "$STRIPE_KEY" | tailor secret ${e} --vault-name api-keys --name stripe-secret-key\`. A piped value can be up to 128 KiB, and one trailing newline is removed from it. In a vault managed by \`defineSecretManager()\`, the command asks for confirmation before releasing the vault from the config, which needs an interactive terminal, so pass \`--yes\` when piping the value.`}async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=I(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[Zn]}catch{return a}return o?(C.warn(`Vault "${r}" is managed by defineSecretManager() in tailor.config.ts (owner: "${o}"). Changes made via CLI may conflict with the config on the next apply.`),{isManaged:!0,trn:i,existingLabels:s}):a}async function releaseVaultOwnership(e){let{client:t,trn:n}=e;await dn(t,{trn:n,remove:[Zn,sr,nn]}),C.info(`Config ownership has been removed from this vault. Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.`)}const Ma=k({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...R,...ja,...D}),notes:secretValueNotes(`create`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret create`);C.registerSecret(t),await F({profile:e.profile});let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await M.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_CREATION_CANCELLED`,message:`Secret creation cancelled. The vault is still managed by the config.`});try{await n.createSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw U({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),C.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`),z({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),Na=k({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...R,...Aa,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await M.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`SECRET_DELETION_CANCELLED`,message:`Secret deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),C.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`),z({changed:!0,workspaceId:n,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:r.isManaged})}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e.workspaceId}),r=dr(e.order);return(await S(async(i,a)=>{let{secrets:o,nextPageToken:s}=await t.listSecretManagerSecrets({workspaceId:n,secretmanagerVaultName:e.vaultName,pageToken:i,pageSize:a,pageDirection:r});return[o,s]},{limit:e.limit})).map(secretInfo)}const Pa=k({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...R,...ka,...Ht()}),run:async e=>{try{let t=await L(e.limit,t=>secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:t})),n=t.items;C.out(n),await B(t,e.limit)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),Fa=k({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...R,...ja,...D}),notes:secretValueNotes(`update`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret update`);C.registerSecret(t),await F({profile:e.profile});let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await M.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_UPDATE_CANCELLED`,message:`Secret update cancelled. The vault is still managed by the config.`});try{await n.updateSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),C.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`),z({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),Ia={name:W(q.string(),{positional:!0,description:`Vault name`})},La=k({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...R,...Ia}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});try{await t.createSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.AlreadyExists?U({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}C.success(`Vault: ${e.name} created`),z({changed:!0,workspaceId:n,name:e.name})}}),Ra=k({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...R,...Ia,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await M.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`VAULT_DELETION_CANCELLED`,message:`Vault deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&C.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),C.success(`Vault: ${e.name} deleted`),z({changed:!0,workspaceId:n,name:e.name,managed:r.isManaged})}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await N({profile:e?.profile,workspaceId:e?.workspaceId}),r=dr(e?.order);return(await S(async(e,i)=>{let{vaults:a,nextPageToken:o}=await t.listSecretManagerVaults({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const za=k({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...R,...Ht()}),run:async e=>{let t=await L(e.limit,t=>vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),n=t.items;C.out(n),await B(t,e.limit)}}),Ba=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:La,delete:Ra,list:za},defaultSubCommand:`list`}),Va=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Ba,create:Ma,update:Fa,list:Pa,delete:Na},defaultSubCommand:`vault`}),Ha={[n.UNSPECIFIED]:`unspecified`,[n.PENDING]:`pending`,[n.VERIFYING]:`verifying`,[n.CERT_ISSUED]:`cert_issued`,[n.ACTIVE]:`active`,[n.FAILED]:`failed`},Ua=k({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...R,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Custom domain "${e.domain}" not found.`;try{let{customDomain:i}=await t.getCustomDomain({workspaceId:n,domain:e.domain});if(!i)throw U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:Ha[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};C.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),Wa=k({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...R,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});try{let{customDomains:r}=await t.listCustomDomains({workspaceId:n,staticWebsiteName:e.name});if(r.length===0){C.info(`No custom domains found.`),C.jsonMode&&C.out([]);return}let i=r.map(e=>({domain:e.domain,status:Ha[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));C.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),Ga=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:Wa,get:Ua}}),Ka=k({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...R,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Static website "${e.name}" not found.`;try{let{staticwebsite:i}=await t.getStaticWebsite({workspaceId:n,name:e.name});if(!i)throw U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r});let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
|
|
86
|
+
`)};C.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await N({profile:e?.profile,workspaceId:e?.workspaceId}),r=dr(e?.order);return(await S(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const qa=k({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...R,...Ht()}),run:async e=>{let t=C.jsonMode,n=await L(e.limit,t=>listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),r=n.items,i=t?r:r.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});C.out(i),await B(n,e.limit)}}),Ja=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:ft,domain:Ga,list:qa,get:Ka},defaultSubCommand:`list`}),Ya=new Set(Object.values(pt));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=K.dirname(i),o=K.basename(i),s=await $.mkdtemp(K.join(a,`.${o}-rebaseline-`)),c=`${s}-previous`,l=!1,u=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!ze.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Ya.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:8,createdAt:(/* @__PURE__ */ new Date()).toISOString(),rebaseline:r},a=await Te(e,s,0);Bt(a.filePath),await $.rename(i,c),l=!0;try{await $.rename(s,i),u=!0}catch(e){throw await $.rename(c,i),l=!1,e}try{await $.rm(c,{recursive:!0,force:!0})}catch(e){C.warn(`The previous migration directory remains at ${c}: ${e instanceof Error?e.message:String(e)}`)}l=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!u&&l&&Y.existsSync(c)&&await $.rename(c,i)}}async function rebaseline(e){Ft(`tailordb migration`);let{config:t,plugins:n}=await P(e.configPath),r=K.dirname(t.path),i=Sr(On(t,r),e.namespace),a=`First run ${H({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;kt(i.migrationsDir,i.namespace);let o=E(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=xt(i.migrationsDir),c=E(i.migrationsDir,0)?.rebaseline?.historyId??null,l=cn([i])[i.namespace],u=n.length>0?new Qr(n):void 0,{defineApplication:d}=await import(`../application-nT_4a5HO.mjs`),f=d({config:t,pluginManager:u});for(let e of f.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let p=f.tailorDBServices.find(e=>e.namespace===i.namespace);if(!p)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=Me(p.types,i.namespace),t=Xe(o,e.tables,i.namespace);if(Kn(t))throw C.error(`Migration history does not reproduce the current local schema for namespace ${w.bold(i.namespace)}:`),C.log(fr(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...Ir(p.config,r)];assertLocalTypesReady();let m=Nr(localSourceFiles()),{client:h,workspaceId:g}=await N({profile:e.profile,workspaceId:e.workspaceId}),_=[`--config`,t.path,...gt({workspaceId:g,profile:e.profile})],v=`Run ${H({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,..._]})}`,y=`after resolving the connection error, deploy with schema checks enabled by running ${H({command:`tailor`,args:[`deploy`,..._]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await Wn(h,I(g,`tailordb`,i.namespace));tr(r,i.namespace);let a=r.number;if(a!==s){let e=a===null?`<unset>`:A(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${A(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw U({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw U(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await Mt(h,g,[i],t,[We(p)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(C.error(`Remote schema drift detected:`),C.log(Fr(o))),U({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(c,`initial`),C.newline(),C.warn(`This will replace the migration history for ${w.bold(i.namespace)}.`),C.log(` Latest migration: ${A(s)}`),C.log(` New history: 0000/schema.json only`),C.log(` migrate.ts and db.ts files will disappear from the working tree.`),C.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),C.log(` Every other environment must already be at the latest migration.`),C.log(` The connected workspace checkpoint will be reset to 0000.`),C.newline(),!e.yes&&!await M.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw U({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(kt(i.migrationsDir,i.namespace),cn([i])[i.namespace]!==l)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(Nr(localSourceFiles())!==m)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(c,`confirmation`);let b={historyId:et(),replacedHistoryId:c,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,b);try{await $e(h,g,i.namespace,0,b.historyId)}catch(e){throw U({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${v}, or ${y}`,cause:e})}return C.success(`Re-baselined ${w.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`),{changed:!0,workspaceId:g,namespace:i.namespace,...b,schemaPath:Oe(i.migrationsDir,0,`schema`)}}const Xa=k({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...j,...D,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await F({profile:e.profile});let t=await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});z(t)}});async function set(e){Ft(`tailordb migration`);let t=Se(e.number),{config:n}=await P(e.configPath),r=K.dirname(n.path),i=On(n,r),a=Sr(i,e.namespace),o=a.namespace;kt(a.migrationsDir,o),nt(a.migrationsDir,t);let s=E(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await N({profile:e.profile,workspaceId:e.workspaceId}),u=I(l,`tailordb`,o),d=await Wn(c,u),f=d.inProgress?.number===t;f||tr(d,o);let p=d.number,m=p??0,h=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,g=s??`<unset>`;if(C.newline(),C.warn(`This operation will change TailorDB migration state metadata.`),C.log(`Namespace: ${w.bold(o)}`),C.log(`Current migration: ${p===null?`<unset>`:w.bold(A(p))}`),C.log(`New migration: ${w.bold(A(t))}`),C.log(`Current migration history ID: ${w.bold(h)}`),C.log(`New migration history ID: ${w.bold(g)}`),C.newline(),f&&(C.warn(`Migration ${A(t)} is in progress. Setting the checkpoint to it marks it as completed and clears its in-progress record; do this only when its schema changes are already applied.`),C.newline()),t<m?(C.warn(`Setting migration number backwards (${A(m)} → ${A(t)}) will cause previous migrations to be re-executed on next apply.`),C.newline()):t>m&&(C.warn(`Setting migration number forwards (${A(m)} → ${A(t)}) will skip migrations ${A(m+1)} to ${A(t)}.`),C.newline()),!e.yes){if(!await M.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw U({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});C.newline()}let _=await $e(c,l,o,t,s);return C.success(`Migration checkpoint set to ${w.bold(A(t))} for namespace ${w.bold(o)}`),{changed:_,workspaceId:l,namespace:o,previousMigrationNumber:p,migrationNumber:t,historyId:s??null}}const Za=k({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...j,...D,number:W(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await F({profile:e.profile});let t=await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});z(t)}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await P(e.configPath),n=K.dirname(t.path),r=On(t,n);if(r.length===0)throw en();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=Rt(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n){if(e.type===`schema`){let t=Bt(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Nt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(zr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Vr(t))}if(a.size===0)return i.map(({namespace:e})=>({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`}));let{client:s,workspaceId:c}=await N({profile:e.profile,workspaceId:e.workspaceId}),l=[];for(let{namespace:e}of i){if(o.has(e)){l.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){l.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,u=I(c,`tailordb`,e),d;try{d=await Wn(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if(d.inProgressInvalid){l.push({status:`error`,namespace:e,error:`Remote in-progress migration record is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:A(e),...r.has(e)?{description:r.get(e)}:{}})),m=jn(d)?null:d.inProgress;l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:A(f),pendingMigrations:p,...m?{inProgressMigration:m.number,inProgressMigrationLabel:A(m.number)}:{}})}return l}function printMigrationStatuses(e){for(let t of e){if(C.newline(),C.info(`Namespace: ${w.bold(t.namespace)}`),isStatusFailure(t)){C.error(` Migration status error: ${t.error}`);continue}if(C.log(` Current migration: ${w.bold(t.currentMigrationLabel)}`),t.inProgressMigrationLabel&&C.log(` In progress: ${w.bold(t.inProgressMigrationLabel)} (partially applied; the next deploy resumes it)`),t.pendingMigrations.length>0){C.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?C.log(` - ${e.label}: ${e.description}`):C.log(` - ${e.label}`)}else C.log(` Pending migrations: (none)`)}C.newline()}async function status(e){Ft(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?C.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw U({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const Qa=k({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...j,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:C.jsonMode})}});async function fetchRemoteGqlPermissions(e,t,n){return x(async(r,i)=>{let{permissions:a,nextPageToken:o}=await e.listTailorDBGQLPermissions({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e,t,n){return m(async(r,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await e.listTailorDBTypes({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,suggestion:`Deploy the namespace before syncing its migration history.`,cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Qr(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-nT_4a5HO.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let l=o(i,s.tailorDBServices,n.path),u=s.executorService??(l.length>0?(await import(`../service-sH2MZ4_W.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await u?.loadExecutors(),l.length>0&&await u?.loadPluginExecutorFiles([...l]);let d=/* @__PURE__ */ new Set;for(let e of Object.values(u?.executors??{}))ar(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let f={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},p=E(t.migrationsDir);if(!p)return f;let m=Me(c.types,t.namespace),h=Xe(p,m.tables,t.namespace);if(!Kn(h))return f;throw C.error(`Migration history does not reproduce the current local schema for namespace ${w.bold(t.namespace)}:`),C.log(fr(h)),C.newline(),C.info(`This usually means one of the following:`),C.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),C.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),C.newline(),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){Ft(`tailordb migration`);let t=Se(e.number),n=await P(e.configPath),{config:r}=n,i=K.dirname(r.path),a=On(r,i),o=Sr(a,e.namespace);kt(o.migrationsDir,o.namespace);let s=nt(o.migrationsDir,t),c=E(o.migrationsDir,t);if(!c)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let l=await assertMigrationsReproduceLocalTypes(n,o),{client:u,workspaceId:d}=await N({profile:e.profile,workspaceId:e.workspaceId}),f=I(d,`tailordb`,o.namespace),p=await Wn(u,f);tr(p,o.namespace);let m=p.number,h=await fetchRemoteTypes(u,d,o.namespace),g=new Set(h.map(e=>e.name)),{creates:_,updates:v,deletes:y}=Qn(c,g),b=await fetchRemoteGqlPermissions(u,d,o.namespace),ee=new Set(b.map(e=>e.typeName)),x=Object.entries(c.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:pn(t.permissions.gql)}]:[]),S=new Set(x.map(e=>e.typeName)),te=b.filter(e=>!S.has(e.typeName));C.newline(),C.info(`Namespace: ${w.bold(o.namespace)}`),C.log(` Current migration: ${m===null?`<unset>`:w.bold(A(m))}`),C.log(` Target migration: ${w.bold(A(t))}`),C.log(` Tables to create: ${w.bold(String(_.length))}`),C.log(` Tables to update: ${w.bold(String(v.length))}`),C.log(` Tables to delete: ${w.bold(String(y.length))}`),C.log(` GQL permissions to set: ${w.bold(String(x.length))}`),C.log(` GQL permissions to delete: ${w.bold(String(te.length))}`),C.newline();let ne=_.length+v.length+y.length+x.length+te.length;if(ne===0?C.info(`No tables to apply; only the migration label will be updated.`):(C.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),y.length>0&&C.warn(`Existing data in deleted tables will be lost.`),C.newline()),C.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),C.newline(),m!==null&&t<m?(C.warn(`Migrations ${A(t+1)}–${A(m)} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`),C.newline()):m!==null&&t>m&&(C.warn(`Moving the migration label forwards (${A(m)} → ${A(t)}): migrate.ts scripts for migrations ${A(m+1)}–${A(t)} will not run on the next deploy.`),C.newline()),!e.yes){if(!await M.confirm({message:`Continue and set migration label to ${A(t)}?`,default:!1}))throw U({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});C.newline()}let re=lr(c,l),manifestFor=e=>{let t=re.get(e);if(!t)throw Br(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ie=_.map(e=>manifestFor(e)),ae=v.map(e=>manifestFor(e));try{await Promise.all([...ie.map(e=>u.createTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbType:e})),...ae.map(e=>u.updateTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbType:e}))])}catch(e){rr(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}await Promise.all(x.map(({typeName:e,permission:t})=>{let n={workspaceId:d,namespaceName:o.namespace,typeName:e,permission:t};return ee.has(e)?u.updateTailorDBGQLPermission(n):u.createTailorDBGQLPermission(n)})),await Promise.all(te.map(e=>u.deleteTailorDBGQLPermission({workspaceId:d,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(y.map(e=>u.deleteTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbTypeName:e})));let oe=c.rebaseline?.historyId,se=await $e(u,d,o.namespace,t,oe);return C.success(`Synced namespace ${w.bold(o.namespace)} to migration ${w.bold(A(t))}.`),t<s&&(C.newline(),C.info(`Run 'tailor deploy' to apply migrations ${A(t+1)}–${A(s)} from the working tree.`)),{changed:ne>0||se,workspaceId:d,namespace:o.namespace,previousMigrationNumber:m,migrationNumber:t,historyId:oe??null,tables:{created:_,updated:v,deleted:y},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:te.map(({typeName:e})=>e)}}}const $a=k({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...j,...D,number:W(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await F({profile:e.profile});let t=await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});z(t)}});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=Y.statSync(e)}catch(t){throw t.code===`ENOENT`?U({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw U({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=K.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?U({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw U({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw U({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw U({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw U({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>bt(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,s(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,r=t.timeout??3e5,i=Date.now()+r;for(;Date.now()<=i;){let r=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(r.status===o.COMPLETED)return;if(r.status===o.FAILED)throw U({code:`MIGRATION_TEST_CLONE_FAILED`,message:`Application data clone failed: ${r.errorMessage||`unknown platform error`}`});if(r.status!==o.PENDING&&r.status!==o.PROCESSING)throw Br(`Application data clone returned unexpected status ${r.status}.`);await delay(n)}throw U({code:`MIGRATION_TEST_CLONE_TIMEOUT`,message:`Application data clone timed out after ${Math.round(r/1e3)} seconds.`})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=K.join(e,`${i}.jsonl`),o;try{o=Y.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
|
|
87
|
+
`).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw U({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw U({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,/* @__PURE__ */ new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=/* @__PURE__ */ new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=/* @__PURE__ */ new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=/* @__PURE__ */ new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=/* @__PURE__ */ new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${_i(3).toString(`hex`)}`}function stateOrThrow(e){return s(e,`migration test runtime was used before preparation`)}async function resolveSourceMigrationNumber(e,t,n,r,i,a){if(r.number!==null)return r.number;if(!r.metadataExists)throw U({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${n.namespace}" has not been deployed.`,suggestion:`Deploy to the source workspace before testing.`});let o=E(n.migrationsDir,0);if(!o)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${n.namespace}".`});let s=await tt(e,t,n.namespace,o,i,a);if(s.length>0)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${n.namespace}" has no migration label and its schema differs from the initial migration snapshot (0000).`,details:Tt(s),suggestion:`Bring the source schema in line with 0000 or set its migration label.`});return 0}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=On(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(We),o=(await Mt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let o of i){let i=t.baselines.get(o.namespace);if(!i)continue;let s=await Wn(e.client,I(n,`tailordb`,o.namespace));tr(s,o.namespace);let c=await resolveSourceMigrationNumber(e.client,n,o,s,r.config,a);if(c!==i.migrationNumber)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" moved from migration ${i.migrationNumber} to ${c} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await bt(e.client,n,r.namespace);if(Jt(i,a).changes.length>0)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await se(()=>e.client.getUserProfileConfig({workspaceId:t,namespaceName:r}))&&await e.client.deleteUserProfileConfig({workspaceId:t,namespaceName:r})}function migrationConfig(e,t){return e.config.db?.[t]?.migration}function authExecutionContext(e,t,n){let r=e.loaded.application.authService;if(!r)throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??He(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw U({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await Et({configPath:e.configPath}),n=K.dirname(t.config.path),r=On(t.config,n);if(r.length===0)throw en();for(let e of r)kt(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await at({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(We),o=await Or({profile:e.profile}),c=await Ie({profile:e.profile}),l=await le(o,c),u=await ct({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,f,p]=await Promise.all([l.getWorkspace({workspaceId:u}),l.getApplication({workspaceId:u,applicationName:t.config.name}),e.data===`clone`&&e.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=s(d.workspace,`source workspace "${u}" not found`);s(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?s(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,g=await Mt(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${_.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let v=g.find(e=>e.checkpointRepair);if(v)throw U({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${v.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let y=/* @__PURE__ */ new Map,b=/* @__PURE__ */ new Map,ee=[];for(let e of r){let n=await Wn(l,I(u,`tailordb`,e.namespace));tr(n,e.namespace);let r=await resolveSourceMigrationNumber(l,u,e,n,t.config,a),i=xt(e.migrationsDir);if(r>i)throw U({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${r}, but the local history ends at ${i}.`});let o=E(e.migrationsDir,r);if(!o)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});y.set(e.namespace,{migrationNumber:r,snapshot:o,historyId:o.rebaseline?.historyId??null});let s=E(e.migrationsDir,i);if(!s)throw U({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,s),r<i&&ee.push(e.namespace)}if(ee.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let x=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),S={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:y,baselineSnapshots:x,targetSnapshots:b,pendingNamespaces:ee,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:S}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await rn(n.client,t.temporaryWorkspace);return C.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name}},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await yn({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.baselines,t.baselineSnapshots);for(let[e,i]of t.baselines)await $e(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=s(r.seedContext,`seed context missing after migration test preparation`),a=K.join(i.distPath,`data`);assertSeedDataDirectory(a);let o=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=We(e);return[e.namespace,n?.snapshot??Zt({version:1,namespace:e.namespace,createdAt:(/* @__PURE__ */ new Date()).toISOString(),tables:r.types})]}));for(let[e,t]of o){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await Ge(e,l,K.dirname(r.loaded.config.path)),d=ut({data:c,order:o,codeByteSize:new TextEncoder().encode(u.bundledCode).length}),f=authExecutionContext(r,e,r.options.machineUser??i.machineUserName);for(let t of d){let i=await Le({client:r.client,workspaceId:n,name:`migration-test-seed-${e}.ts`,code:u.bundledCode,arg:{data:t.data,order:t.order,selfRefTypes:s,upsert:!1},invoker:{namespace:f.authNamespace,machineUserName:f.machineUserName}});if(!i.success)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i})=>{let a=stateOrThrow(e);await assertSourceBaselineFresh(a,t,n),C.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let o;try{o=(await a.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?U({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!o)throw Br(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(a.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:o})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await pr({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.targetSnapshots)},runAssertion:async({prepared:t,targetWorkspaceId:n,assertionPath:r,assertionNamespace:i,machineUser:a})=>{let o=stateOrThrow(e),s=resolveAssertionNamespace(t.pendingNamespaces,i),c=authExecutionContext(o,s,a),l=await an(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path),Ar(o.loaded.plugins,`@tailor-platform/kysely-type`)?.temporal??!1,re(o.loaded.config)),u=await Le({client:o.client,workspaceId:n,name:`migration-test-assert-${s}.ts`,code:l.bundledCode,invoker:{namespace:c.authNamespace,machineUserName:c.machineUserName}});if(!u.success)throw U({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=s(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:s(e.targetWorkspaceId,`designated target workspace missing`),name:void 0},a,o=!1,c=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){a=e,o=!0}if(r&&e.keep)C.info(`Keeping temporary workspace ${i.name??i.id}.`);else if(r)try{await t.deleteWorkspace(i.id),c=!0}catch(t){if(!o)throw U({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});C.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(o)throw a;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:c,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){Ft(`tailordb migration`);let t=await runMigrationTest(e);if(e.json){C.out(t);return}C.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const eo=k({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs.`,args:q.strictObject({...j,yes:W(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:W(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":W(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:W(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:W(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":W(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"machine-user":W(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await F({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],yes:e.yes,json:C.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[],s=[];for(let t of Rt(e)){if(t.type!==`diff`)continue;let n=Nt(t.path),c=Oe(e,t.number,`migrate`),l=Y.existsSync(c);l&&s.push([t.number,c]),n.requiresMigrationScript&&!n.scriptSkipped&&!l&&r.push(t.number),n.scriptSkipped&&l&&i.push(t.number),l&&gn(c)>0&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!l&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw U({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(A).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${Pn({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
88
|
+
`);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(A).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw U({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(A).join(`, `)} in namespace "${t}" still have a TODO() call or review marker in migrate.ts, where the generated script leaves a value or logic for you to decide.`,suggestion:Bn});for(let[e,n]of s){let r=_r(n);r.kind===`main`&&r.ignoredSteps&&C.warn(wn(`${t}/${A(e)}`))}return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let o=s(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:o.hasDiff,...o.diff?{diff:o.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=s(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await P(e.configPath),r=K.dirname(t.path),i=On(t,r);if(i.length===0)throw en();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new Qr(n):void 0,{defineApplication:s}=await import(`../application-nT_4a5HO.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();b({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(We),u=new Map(l.map(e=>[e.namespace,e.types])),d=/* @__PURE__ */ new Map,f=[],p=e.strict?/* @__PURE__ */ new Map:void 0;for(let t of a)try{kt(t.migrationsDir,t.namespace),E(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,Vr(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await Ke(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e.workspaceId});h=await Mt(n,r,f,t,l)}catch(e){return{reports:buildValidationReports(m),remoteError:e}}return{reports:buildValidationReports({...m,remoteResults:h})}}function printValidationReports(e){for(let t of e){if(C.newline(),C.info(`Namespace: ${w.bold(t.namespace)}`),!t.migrationFiles.valid){C.log(` Migration files: ${w.error(`invalid`)}`),C.log(` ${t.migrationFiles.error}`);continue}C.log(` Migration files: ${w.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(C.log(` Local schema: ${w.error(`changes not in migration files`)}`),C.log(` ${vn(e.diff)}`),C.log(fr(e.diff))):C.log(` Local schema: ${w.error(`no migration snapshot found`)}`):C.log(` Local schema: ${w.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?C.log(` Remote schema: ${w.error(`not checked`)}`):n?.checkpointRepair?C.log(` Remote schema: ${w.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${A(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(C.log(` Remote schema: ${w.error(`remote migration ${A(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&C.log(` Fell behind before 'migration rebaseline' ran; must reach ${A(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(C.log(` Remote schema: ${w.error(`drift detected`)} (remote migration: ${A(n.remoteMigrationNumber)})`),C.log(Tt(n.drifts))):n?.skipped===`not_deployed`?C.log(` Remote schema: ${w.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?C.log(` Remote schema: ${w.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?C.log(` Remote schema: ${w.dim(`skipped (no local snapshot for remote migration ${A(n.remoteMigrationNumber)})`)}`):n&&C.log(` Remote schema: ${w.success(`OK`)} (remote migration: ${A(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)C.log(` Warning acknowledgments: ${w.success(`OK`)}`);else{C.log(` Warning acknowledgments: ${w.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=A(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;C.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}C.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&C.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&C.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&De(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&Lt(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let r=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(r.length>0){C.info(`For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:`);for(let e of r)for(let n of e.warningAcknowledgments?.missing??[])C.info(` ${Pn({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){Ft(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?C.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?C.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw U({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const to=k({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...j,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:C.jsonMode,strict:e.strict})}}),no=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:vt,rebaseline:Xa,script:Pr,set:Za,status:Qa,sync:$a,test:eo,validate:to}}),ro=G({name:`tailordb`,description:`Manage TailorDB tables and data.`,notes:"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.",subCommands:{truncate:rt,migration:no}}),io=k({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:W(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":W(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:W(q.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t();let{upgrade:n}=await import(`../service-DFmt9UJP.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),ao=k({name:`current`,description:`Show current user.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await T(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Rn(r):void 0,a=n?r?.user??null:t.current_user,o=C.jsonMode;if(!a)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...gt({profile:n})]}});if(!sn(t,a,i))throw U({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...gt({profile:n})]}});if(o){C.out({user:a});return}C.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?dt(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return dt(e,n.user,Rn(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const oo=k({name:`list`,description:`List all users.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await T(),n=C.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){C.info(V`
|
|
89
89
|
No users found.
|
|
90
90
|
Please login first using 'tailor login' command to register a user.
|
|
91
|
-
`),n&&C.out([]);return}let a=i.map(e=>toUserListInfo(e,r));if(n){C.out([...new Set(a.map(e=>e.user))]);return}a.forEach(e=>{e.current?C.success(formatUserListInfo(e),{mode:`plain`}):C.log(formatUserListInfo(e))})}});function patScopeToString(e){
|
|
91
|
+
`),n&&C.out([]);return}let a=i.map(e=>toUserListInfo(e,r));if(n){C.out([...new Set(a.map(e=>e.user))]);return}a.forEach(e=>{e.current?C.success(formatUserListInfo(e),{mode:`plain`}):C.log(formatUserListInfo(e))})}}),so={[a.PAT_SCOPE_UNSPECIFIED]:`unknown`,[a.PAT_SCOPE_READ]:`read`,[a.PAT_SCOPE_WRITE]:`write`};function patScopeToString(e){return Jn(so,e,`unknown`)}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:hn(e.createdAt),lastUsedAt:hn(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[a.PAT_SCOPE_READ,a.PAT_SCOPE_WRITE]:[a.PAT_SCOPE_READ]}function getScopeStringsFromWriteFlag(e){return e?[`read`,`write`]:[`read`]}function printCreatedToken(e,t,n,r){let i=getScopeStringsFromWriteFlag(n);C.jsonMode?C.out({name:e,scopes:i,token:t}):C.out(V`
|
|
92
92
|
Personal access token ${r} successfully.
|
|
93
93
|
|
|
94
94
|
name: ${e}
|
|
@@ -96,10 +96,10 @@ Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?C.log(e):C.l
|
|
|
96
96
|
token: ${t}
|
|
97
97
|
|
|
98
98
|
Please save this token in a secure location. You won't be able to see it again.
|
|
99
|
-
`)}async function createPatOperatorClient(e){let t=await
|
|
99
|
+
`)}async function createPatOperatorClient(e){let t=await Or({profile:e});return await le(t)}const co=k({name:`create`,description:`Create a new personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),write:W(q.boolean().default(!1),{alias:`W`,description:`Grant write permission (default: read-only)`}),profile:R.profile}),run:async e=>{await F({profile:e.profile});let t=await createPatOperatorClient(e.profile),n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Br(`Failed to create personal access token`);C.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),lo=k({name:`delete`,description:`Delete a personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),profile:R.profile}),run:async e=>{await F({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),C.success(`Personal access token "${e.name}" deleted successfully.`),z({changed:!0,name:e.name})}}),uo=k({name:`list`,description:`List all personal access tokens.`,args:q.strictObject({...Ht(),profile:R.profile}),run:async e=>{let t=C.jsonMode,n=await createPatOperatorClient(e.profile),r=dr(e.order),i=await L(e.limit,e=>S(async(e,t)=>{let{personalAccessTokens:i,nextPageToken:a}=await n.listPersonalAccessTokens({pageToken:e,pageSize:t,pageDirection:r});return[i,a]},{limit:e})),a=i.items;if(a.length===0&&(C.info(V`
|
|
100
100
|
No personal access tokens found.
|
|
101
101
|
Please create a token using 'tailor user pat create' command.
|
|
102
|
-
`),!t))return;let o=a.map(transformPersonalAccessToken);C.out(o,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:
|
|
102
|
+
`),!t))return;let o=a.map(transformPersonalAccessToken);C.out(o,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:Cn(e)}}),await B(i,e.limit)}}),fo=k({name:`update`,description:`Update a personal access token (delete and recreate).`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),write:W(q.boolean().default(!1),{alias:`W`,description:`Grant write permission (if not specified, keeps read-only)`}),profile:R.profile}),run:async e=>{await F({profile:e.profile});let t=await createPatOperatorClient(e.profile);await t.deletePersonalAccessToken({name:e.name});let n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Br(`Failed to create personal access token`);C.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),po=G({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:uo,create:co,delete:lo,update:fo},defaultSubCommand:`list`}),mo=k({name:`switch`,description:`Set current user.`,args:q.strictObject({user:W(q.string(),{positional:!0,description:`User email address or machine user client ID`}),profile:R.profile}),run:async e=>{let t=await T(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Rn(r):void 0;if(e.user.includes(`|`))throw U({code:`USER_NAME_INVALID`,message:`User "${e.user}" looks like a platform-scoped token key. Pass the user name without the platform URL and select the platform with TAILOR_PLATFORM_URL or a profile.`,command:`user switch`});let a=ot(t,e.user,i);if(!a)throw U({code:`USER_NOT_FOUND`,message:`User "${e.user}" not found.`,suggestion:`Log in first to register this user.`,next:{command:`tailor`,args:[`login`,...gt({profile:n})]}});let o=r?r.user:t.current_user;r?r.user=a:t.current_user=a,O(t),C.success(`Current user set to "${a}" successfully.`),z({changed:o!==a,user:a,profile:n||null})}}),ho=G({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:ao,list:oo,switch:mo,pat:po},defaultSubCommand:`list`}),go=G({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:Ln,get:Ue,start:Pt,wait:Dt,executions:ir,resume:Pe},defaultSubCommand:`list`}),_o=G({name:`app`,description:`Manage workspace applications`,subCommands:{health:wr,list:St},defaultSubCommand:`list`}),locationIdsArg=()=>q.array(q.union([q.literal(``),q.uuid()])).optional(),vo=q.preprocess(e=>typeof e==`string`&&e.trim()===``?NaN:e,q.coerce.number().int().nonnegative());function matchesName(e,t){return t.nameRegexes.length===0||t.nameRegexes.some(t=>t.test(e.name))}function hasLocation(e){return e.organizationRoots.length>0||e.folderIds.length>0||e.personal}function matchesScope(e,t){return hasLocation(t)?e.folderId?t.folderIds.includes(e.folderId):e.organizationId?t.organizationRoots.includes(e.organizationId):t.personal:!0}function staleCandidateReason(e,t){if(e.deleteProtection)return`delete protection was turned on`;if(!matchesScope(e,t))return`it moved outside the requested scope`;if(!matchesName(e,t))return`it no longer matches the name filter`;if(t.exclude.has(e.name))return`it is now excluded by --exclude`}function selectPruneCandidates(e,t,n){let r={candidates:[],excluded:[],protectedSkipped:[],missingCreateTime:[],tooYoung:[]};for(let i of e)if(matchesScope(i,t)&&matchesName(i,t)){if(t.exclude.has(i.name)){r.excluded.push(i);continue}if(i.deleteProtection){r.protectedSkipped.push(i);continue}if(t.olderThanMs!==void 0){let e=hn(i.createTime);if(!e){r.missingCreateTime.push(i);continue}if(e.getTime()>n.getTime()-t.olderThanMs){r.tooYoung.push(i);continue}}r.candidates.push(i)}return r}async function partitionByExpiry(e,t,n){let r=ae(),i=await Promise.all(t.map(async t=>({workspace:t,result:await r(()=>Dn(e,t.id,n))}))),a={expired:[],pending:[],unset:[],unreadable:[]};for(let{workspace:e,result:t}of i){if(`error`in t){a.unreadable.push({workspace:e,reason:t.error.message});continue}recordExpiryState(a,e,t.expiry)}return a}function recordExpiryState(e,t,n){switch(n.state){case`expired`:e.expired.push(t);return;case`pending`:e.pending.push(t);return;case`unset`:e.unset.push(t);return;case`invalid`:e.unreadable.push({workspace:t,reason:`recorded expiry "${n.value}" is not a value this CLI wrote`})}}async function fetchAllWorkspaces(e){return S(async(t,n)=>{let{workspaces:r,nextPageToken:i}=await e.listWorkspaces({pageToken:t,pageSize:n});return[r,i]})}function compileNameRegex(e){try{return new RegExp(e),RegExp(`^(?:${e})$`)}catch(t){throw U({code:`INVALID_NAME_PATTERN`,message:`Invalid --name "${e}".`,details:t instanceof Error?t.message:String(t)})}}const yo=[{key:`excluded`,selection:`excluded`,reason:`excluded by --exclude`},{key:`deleteProtection`,selection:`protectedSkipped`,reason:`delete protection is on`},{key:`unknownAge`,selection:`missingCreateTime`,reason:`creation time is unknown`}],bo=k({name:`prune`,description:`Delete stale temporary workspaces, by name and age or by the expiry each recorded at creation.`,notes:V`
|
|
103
103
|
Use this to reclaim workspaces left behind by CI runs, preview deployments, or interrupted local test runs. A workspace is deleted only when its whole name matches a --name pattern, it was created at least --older-than ago, and it is not excluded, delete-protected, or outside the requested locations. Run with --dry-run first to see what would be deleted.
|
|
104
104
|
|
|
105
105
|
With --expired the workspaces select themselves instead: each one is deleted only once the --ttl expiry it recorded at creation has passed, so callers need no --name or --older-than. A workspace that records no expiry is never deleted this way, and neither is one whose recorded expiry cannot be read. Because that expiry is recorded on the workspace rather than derived from its name, anything able to write the workspace's metadata can bring its deletion forward -- and writing a workspace's metadata is a lesser permission than deleting it. --expired therefore requires at least one location, and --name still applies on top.
|
|
@@ -111,9 +111,9 @@ Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?C.log(e):C.l
|
|
|
111
111
|
Safety guards: the command aborts without deleting anything when more workspaces match than --limit allows (--dry-run still lists them all), both --expired and --older-than 0s (no age check) are only accepted together with at least one location option, and a location option that resolves to an empty value (an unset CI secret) is rejected instead of silently widening the sweep -- even when another location is given alongside it. Each workspace is re-read immediately before it is deleted and skipped when it no longer matches the name, location, exclusion, or delete-protection criteria that selected it. Unlike \`workspace delete\`, a single confirmation covers every listed candidate; pass --yes to skip it in CI. Deleted workspaces can be restored with \`workspace restore\` for a limited time.
|
|
112
112
|
|
|
113
113
|
Only workspaces visible to the current login (or the machine user in CI) are considered.
|
|
114
|
-
`,args:q.strictObject({name:W(q.array(q.string().min(1)).optional(),{description:`Select workspaces whose whole name matches this regular expression (repeatable)`}),"older-than":W(xr.optional(),{description:`Minimum age since creation, such as 30m, 24h, or 7d. 0s disables the age check and requires a location. Required unless --expired is given`}),expired:W(q.boolean().default(!1),{description:`Select workspaces whose own --ttl expiry has passed, instead of by name and age. Requires --organization-root, --folder-id, or --personal`}),"organization-root":W(locationIdsArg(),{placeholder:`ORGANIZATION_ID`,description:`Consider the workspaces directly under this organization, excluding those in its folders (repeatable)`}),"folder-id":W(locationIdsArg(),{description:`Consider the workspaces in this folder (repeatable)`}),personal:W(q.boolean().default(!1),{description:`Consider the workspaces belonging to no organization and no folder`}),exclude:W(q.array(q.string().min(1)).optional(),{description:`Keep a workspace with this exact name even when it matches (repeatable)`}),limit:W(
|
|
114
|
+
`,args:q.strictObject({name:W(q.array(q.string().min(1)).optional(),{description:`Select workspaces whose whole name matches this regular expression (repeatable)`}),"older-than":W(xr.optional(),{description:`Minimum age since creation, such as 30m, 24h, or 7d. 0s disables the age check and requires a location. Required unless --expired is given`}),expired:W(q.boolean().default(!1),{description:`Select workspaces whose own --ttl expiry has passed, instead of by name and age. Requires --organization-root, --folder-id, or --personal`}),"organization-root":W(locationIdsArg(),{placeholder:`ORGANIZATION_ID`,description:`Consider the workspaces directly under this organization, excluding those in its folders (repeatable)`}),"folder-id":W(locationIdsArg(),{description:`Consider the workspaces in this folder (repeatable)`}),personal:W(q.boolean().default(!1),{description:`Consider the workspaces belonging to no organization and no folder`}),exclude:W(q.array(q.string().min(1)).optional(),{description:`Keep a workspace with this exact name even when it matches (repeatable)`}),limit:W(vo.default(20),{description:`Abort when more workspaces match than this, without deleting anything. 0 removes the cap`}),"dry-run":W(q.boolean().default(!1),{description:`List the workspaces that would be deleted without deleting them`}),profile:W(wt.optional(),{description:`Workspace profile used for authentication and Platform selection`,env:`TAILOR_PLATFORM_PROFILE`}),...D}),run:async e=>{let t=e.name??[],n=e[`older-than`];if(e.expired&&n!==void 0)throw U({code:`CONFLICTING_AGE_FILTER`,message:`--expired and --older-than cannot be combined.`,details:`--expired defers to the expiry each workspace recorded at creation, which --older-than would override.`});if(!e.expired&&n===void 0)throw U({code:`MISSING_AGE_FILTER`,message:`Specify --older-than, or --expired to use each workspace's recorded expiry.`});if(!e.expired&&t.length===0)throw U({code:`MISSING_NAME_FILTER`,message:`Specify at least one --name.`,details:`Only workspaces whose name matches the filter are considered for deletion.`});let r=e[`organization-root`]??[],i=e[`folder-id`]??[],a=[[`--organization-root`,r],[`--folder-id`,i]].filter(([,e])=>e.includes(``)).map(([e])=>e);if(a.length>0)throw U({code:`EMPTY_SCOPE`,message:`${a.join(` and `)} resolved to an empty value.`,details:`An empty location is indistinguishable from an omitted one, so the sweep would not cover what the caller meant. This usually means an unset CI secret.`,suggestion:`Set the id, or drop the option on purpose.`});let o=n===void 0?void 0:Mr(n),s={nameRegexes:t.map(compileNameRegex),...o===void 0?{}:{olderThanMs:o},organizationRoots:r,folderIds:i,personal:e.personal,exclude:new Set(e.exclude??[])};if(e.expired&&!hasLocation(s))throw U({code:`UNSCOPED_EXPIRED`,message:`--expired requires --organization-root, --folder-id, or --personal.`,details:`The expiry lives on the workspace, and writing a workspace's metadata is a lesser permission than deleting it, so an unscoped sweep would delete on behalf of anyone able to write that metadata.`});if(o===0&&!hasLocation(s))throw U({code:`UNSCOPED_ZERO_AGE`,message:`--older-than 0s requires --organization-root, --folder-id, or --personal.`,details:`Without an age check the name filter is the only guard, so the sweep must name the organization roots, folders, or personal workspaces it covers.`});await F({profile:e.profile});let c=await Or({profile:e.profile}),l=await Ie({profile:e.profile}),u=await le(c,l),d=/* @__PURE__ */ new Date,f=selectPruneCandidates(await fetchAllWorkspaces(u),s,d),p={dryRun:e[`dry-run`],candidates:[],deleted:[],failed:[],skipped:{excluded:[],deleteProtection:[],unknownAge:[],notExpired:[],noExpiry:[],unreadableExpiry:[],expiryChanged:[],changed:[]}};if(e.expired){let e=await partitionByExpiry(u,f.candidates,d);f.candidates=e.expired;for(let t of e.pending)p.skipped.notExpired.push(t.name);for(let t of e.unset)p.skipped.noExpiry.push(t.name);for(let{workspace:t,reason:n}of e.unreadable)p.skipped.unreadableExpiry.push(t.name),C.warn(`Keeping ${t.name} (${t.id}): ${n}.`);C.info(`${e.pending.length} workspace(s) have not expired and ${e.unset.length} record no expiry; both were kept.`)}for(let{key:e,selection:t,reason:n}of yo)for(let r of f[t])p.skipped[e].push(r.name),C.warn(`Keeping ${r.name} (${r.id}): ${n}.`);if(f.tooYoung.length>0&&C.info(`${f.tooYoung.length} matching workspace(s) are younger than ${e[`older-than`]} and were kept.`),f.candidates.length===0){C.info(`No stale workspaces matched.`),C.jsonMode&&C.out(p);return}let m=e.limit>0&&f.candidates.length>e.limit;if(m&&!e[`dry-run`])throw U({code:`PRUNE_LIMIT_EXCEEDED`,message:`${f.candidates.length} workspaces matched, but --limit is ${e.limit}. Nothing was deleted.`,details:`A match count this high usually means the name filter is broader than intended.`,suggestion:`Check the filter with --dry-run, then raise --limit (or pass --limit 0) if every match should be deleted.`});if(p.candidates=await fn(u,f.candidates),C.jsonMode||C.out(p.candidates,{display:{name:zn,folderName:null,organizationId:null,folderId:null,updatedAt:null}}),e[`dry-run`]){m&&C.warn(`${p.candidates.length} workspaces matched, but --limit is ${e.limit}: a real run would abort without deleting anything.`),C.info(`Dry run: ${p.candidates.length} workspace(s) would be deleted.`),C.jsonMode&&C.out(p);return}if(!e.yes&&!await M.confirm({message:`Delete these ${p.candidates.length} workspace(s)? They can be restored with "tailor workspace restore" for a limited time.`,default:!1}))throw U({code:`PRUNE_CANCELLED`,message:`Prune cancelled. No workspaces were deleted.`});let h=/* @__PURE__ */ new Set;for(let t of p.candidates){let n=cr(t);try{let{workspace:r}=await u.getWorkspace({workspaceId:t.id}),i=r?staleCandidateReason(r,s):void 0;if(i){p.skipped.changed.push(t.name),C.warn(`Keeping ${n} (${t.id}): ${i}.`);continue}if(e.expired){let e=await Dn(u,t.id,/* @__PURE__ */ new Date);if(`error`in e&&e.error instanceof Q&&e.error.code===Z.NotFound)throw e.error;if((`error`in e?`unreadable`:e.expiry.state)!==`expired`){p.skipped.expiryChanged.push(n),C.info(`Skipped ${n} (${t.id}): its recorded expiry no longer selects it.`);continue}}h.add(t.id),await u.deleteWorkspace({workspaceId:t.id}),p.deleted.push(t),C.success(`Deleted ${n} (${t.id}).`)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){h.add(t.id),p.deleted.push(t),C.info(`${n} (${t.id}) was already deleted.`);continue}let r=e instanceof Error?e.message:String(e);p.failed.push({workspace:t,error:r}),C.error(`Failed to delete ${n} (${t.id}): ${r}`)}}let g=await on(h);if(g.length>0&&C.info(`Removed ${g.length} local profile(s) that pointed at deleted workspaces: ${g.join(`, `)}.`),C.jsonMode&&C.out(p),C.success(`Deleted ${p.deleted.length} workspace(s).`),p.failed.length>0)throw U({code:`PRUNE_INCOMPLETE`,message:`Failed to delete ${p.failed.length} workspace(s).`,suggestion:`Fix the reported errors and run the command again; deleted workspaces are not retried.`})}}),xo=q.object({workspaceId:q.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:q.string().optional()});async function clearWorkspaceTtl(e){let t=je(xo,e),{client:n,workspaceId:r}=await N({profile:t.profile,workspaceId:t.workspaceId});return{workspaceId:r,changed:await er(n,r)}}const So=k({name:`clear`,description:`Drop a workspace's recorded prune expiry.`,notes:`
|
|
115
115
|
A workspace recording no expiry is never deleted by \`workspace prune --expired\`. Clearing an expiry the workspace does not record succeeds without changing anything.
|
|
116
|
-
`,args:q.strictObject({...
|
|
117
|
-
Run \`${
|
|
118
|
-
The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:
|
|
116
|
+
`,args:q.strictObject({...R}),run:async e=>{await F({profile:e.profile});let{workspaceId:t,changed:n}=await clearWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile});C.success(`Workspace records no prune expiry.`),z({changed:n,workspaceId:t,expiresAt:null})}}),Co=q.object({workspaceId:q.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:q.string().optional(),ttl:xr});async function setWorkspaceTtl(e){let t=je(Co,e),{client:n,workspaceId:r}=await N({profile:t.profile,workspaceId:t.workspaceId}),i=new Date(Date.now()+Mr(t.ttl));return{workspaceId:r,expiresAt:i,changed:await $t(n,r,i)}}const wo=k({name:`set`,description:`Record when a workspace becomes prunable, replacing any expiry it already records.`,notes:"\n The expiry runs from now, not from when the workspace was created, so `--ttl 24h` always leaves a full day regardless of the workspace's age. Use this to give a restored workspace a new expiry, or to record one after `workspace create --ttl` failed to.\n\n This is not an auto-delete timer: it only makes the workspace eligible for `workspace prune --expired`, which still honors delete protection and its own filters.\n ",args:q.strictObject({...R,ttl:W(xr,{description:`Time from now until the workspace becomes prunable, such as 30m, 24h, or 7d`})}),run:async e=>{await F({profile:e.profile});let{workspaceId:t,expiresAt:n,changed:r}=await setWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile,ttl:e.ttl});C.success(`Workspace becomes prunable at ${n.toISOString()}.`);let i=s(Un(An(n)),`encoded workspace expiry must decode`);z({changed:r,workspaceId:t,expiresAt:i.toISOString()})}}),To=G({name:`ttl`,description:`Manage when a workspace becomes prunable.`,subCommands:{set:wo,clear:So},async run(){await yt(To,[`--help`])}}),Eo=G({name:`user`,description:`Manage workspace users`,subCommands:{invite:Sn,list:hr,remove:un,update:Xn},defaultSubCommand:`list`}),Do=G({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:_o,create:Nn,delete:yr,get:En,list:qn,prune:bo,restore:Vn,ttl:To,user:Eo},defaultSubCommand:`list`});await ur(new URL(`./ts-hook.mjs`,import.meta.url)),Zr();const Oo=await Wr(),ko=Object.keys(Oo.bin??{})[0]||`tailor`,Ao=Oo.name??`@tailor-platform/sdk`,jo=await li(import.meta.url),Mo=ci(si(jo),`agent-skills`);function defaultSkillsRunToAdd(e){let{run:t,...n}=e;return{...n,defaultSubCommand:`add`}}const No=oi(G({name:ko,description:Oo.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${ko}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
|
|
117
|
+
Run \`${ko} plugin list\` to see which plugins are installed and where they resolve from.
|
|
118
|
+
The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Ii,auth:zi,authconnection:Ki,crashreport:Yi,deploy:Xi,executor:Zi,function:sa,generate:ca,init:la,login:fa,logout:pa,machineuser:ma,oauth2client:ha,open:ga,organization:va,plugin:Ca,profile:Oa,query:tn,remove:Be,secret:Va,show:jt,staticwebsite:Ja,tailordb:ro,upgrade:io,user:ho,workflow:go,workspace:Do}}),{sourceDir:Mo,package:Ao,mode:`copy`,descriptionAppend:!1,globalArgs:q.object(Ee),commandMap:{add:[`add`],remove:[`remove`]},unknownKeys:`strict`,descriptions:{skills:`Manage Tailor SDK agent skills.`,add:`Install Tailor SDK agent skills.`,list:`List Tailor SDK agent skills.`,remove:`Remove installed Tailor SDK agent skills.`,sync:`Remove and reinstall Tailor SDK agent skills.`}}),Po=ai({...No,subCommands:{...No.subCommands,skills:defaultSkillsRunToAdd(No.subCommands.skills)}});ri(Po,{version:Oo.version,globalArgs:q.object(Ee),displayErrors:!1,onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:ko,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){Qe()||be(e,process.argv.slice(2));let t;if(C.jsonMode?C.log(ln(e,{includeStack:C.verbose})):zr(e)?(C.log(e.format()),C.verbose&&e.stack&&C.debug(`\nStack trace:\n${e.stack}`)):e instanceof Error?(C.error(e.message),t=ge(e).suggestion??Ur(e),t&&C.log(` ${w.info(`Suggestion:`)} ${t}`),C.verbose&&e.stack&&C.debug(`\nStack trace:\n${e.stack}`)):C.error(`Unknown error: ${e}`),Gn(e,{jsonMode:C.jsonMode,suggestion:t}),!zr(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-CBaRJl5h.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t()}});export{Po as mainCommand};
|
|
119
119
|
//# sourceMappingURL=main.mjs.map
|