@tailor-platform/sdk 2.19.0 → 2.21.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 +51 -0
- package/dist/application-D4913edS.mjs +199 -0
- package/dist/application-D4913edS.mjs.map +1 -0
- package/dist/application-DBHaxmJE.mjs +1 -0
- package/dist/cli/commands/deploy/application.d.mts +1 -0
- package/dist/cli/commands/deploy/apply-phases.d.mts +1 -1
- package/dist/cli/commands/deploy/deploy.d.mts +1 -1
- package/dist/cli/commands/deploy/deployment-target.d.mts +1 -0
- package/dist/cli/commands/deploy/executor.d.mts +1 -1
- package/dist/cli/commands/deploy/function-registry.d.mts +1 -1
- package/dist/cli/commands/deploy/resolver.d.mts +1 -0
- package/dist/cli/commands/deploy/secret-manager.d.mts +1 -1
- package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +1 -1
- package/dist/cli/commands/deploy/tailordb/plan.d.mts +1 -1
- package/dist/cli/commands/deploy/types.d.mts +1 -1
- package/dist/cli/commands/deploy/workflow.d.mts +1 -0
- package/dist/cli/commands/tailordb/migrate/schema-checks.d.mts +1 -1
- package/dist/cli/lib.d.mts +1 -1
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/main.d.mts +1 -0
- package/dist/cli/main.mjs +37 -37
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/services/application.d.mts +2 -0
- package/dist/completion/zsh-worker.zsh +654 -131
- package/dist/configure/index.d.mts +2 -1
- package/dist/configure/index.mjs +12 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/secrets/index.d.mts +14 -0
- package/dist/configure/services/tailordb/schema.d.mts +3 -2
- package/dist/configure/types/secret-vault-name.d.mts +32 -0
- package/dist/{crashreport-Cyuz1qiu.mjs → crashreport-BAz-ph5O.mjs} +3 -3
- package/dist/{crashreport-Cyuz1qiu.mjs.map → crashreport-BAz-ph5O.mjs.map} +1 -1
- package/dist/crashreport-BfOkOFgc.mjs +1 -0
- package/dist/{date-B7-oyTGE.mjs → date-Dri6Yas-.mjs} +2 -2
- package/dist/date-Dri6Yas-.mjs.map +1 -0
- package/dist/{errors-BjJnpXkK.mjs → errors-sNtg2Mv3.mjs} +2 -2
- package/dist/{errors-BjJnpXkK.mjs.map → errors-sNtg2Mv3.mjs.map} +1 -1
- package/dist/es-builtins-SfvXRVoG.mjs +2 -0
- package/dist/{es-builtins-BHCXINQp.mjs.map → es-builtins-SfvXRVoG.mjs.map} +1 -1
- package/dist/field-parse-DhnFs9WG.mjs +2 -0
- package/dist/field-parse-DhnFs9WG.mjs.map +1 -0
- package/dist/{globals-CMHSnj4w.mjs → globals-BCmGX05J.mjs} +2 -2
- package/dist/{globals-CMHSnj4w.mjs.map → globals-BCmGX05J.mjs.map} +1 -1
- package/dist/guards-DsX7dJCP.mjs +2 -0
- package/dist/{guards-ForsrxnH.mjs.map → guards-DsX7dJCP.mjs.map} +1 -1
- package/dist/{kysely-type-B_oA8D1k.mjs → kysely-type-C-iyFFH7.mjs} +2 -2
- package/dist/{kysely-type-B_oA8D1k.mjs.map → kysely-type-C-iyFFH7.mjs.map} +1 -1
- package/dist/{logger-72hM4JWZ.mjs → logger-Cp5U2IDI.mjs} +2 -2
- package/dist/{logger-72hM4JWZ.mjs.map → logger-Cp5U2IDI.mjs.map} +1 -1
- package/dist/manager-C0dE7pd0.mjs +2 -0
- package/dist/{manager-qfbUL7ru.mjs.map → manager-C0dE7pd0.mjs.map} +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/register-ts-hook-YtsAGTMD.mjs +921 -0
- package/dist/register-ts-hook-YtsAGTMD.mjs.map +1 -0
- package/dist/registry-BijIDRVA.mjs +2 -0
- package/dist/{registry-HlEaGvl5.mjs.map → registry-BijIDRVA.mjs.map} +1 -1
- package/dist/repl-editor-DGJBfIt1.mjs +2 -0
- package/dist/{repl-editor-BG1aDOfH.mjs.map → repl-editor-DGJBfIt1.mjs.map} +1 -1
- package/dist/runtime/field-parse.d.mts +17 -1
- package/dist/runtime/index.d.mts +2 -1
- package/dist/runtime/index.mjs +1 -1
- package/dist/runtime/secretmanager.d.mts +8 -20
- package/dist/schema-CRtAmDcl.mjs +2 -0
- package/dist/{schema-BKvcWdVf.mjs.map → schema-CRtAmDcl.mjs.map} +1 -1
- package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
- package/dist/seed/index.mjs +2 -2
- package/dist/seed/index.mjs.map +1 -1
- package/dist/{service-B4Gh_bbL.mjs → service-8xznUrPU.mjs} +2 -2
- package/dist/{service-B4Gh_bbL.mjs.map → service-8xznUrPU.mjs.map} +1 -1
- package/dist/{service-CuqkHP1r.mjs → service-BrGSi2IQ.mjs} +3 -3
- package/dist/{service-CuqkHP1r.mjs.map → service-BrGSi2IQ.mjs.map} +1 -1
- package/dist/service-DWMm-4Vm.mjs +1 -0
- package/dist/service_pb-DNskuJQC.mjs +1 -0
- package/dist/service_pb-y2GYIgfs.mjs +2 -0
- package/dist/{service_pb-DprmLNsq.mjs.map → service_pb-y2GYIgfs.mjs.map} +1 -1
- package/dist/tailordb-ddl-DqInYupv.mjs +7 -0
- package/dist/{tailordb-ddl-Fgm2cNvT.mjs.map → tailordb-ddl-DqInYupv.mjs.map} +1 -1
- package/dist/utils/test/index.mjs +1 -1
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -1
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/setup.mjs +1 -1
- package/dist/workspace_resource_pb-D2njwgsE.mjs +2 -0
- package/dist/{workspace_resource_pb-BOoRts_z.mjs.map → workspace_resource_pb-D2njwgsE.mjs.map} +1 -1
- package/docs/configuration.md +18 -1
- package/docs/migration/v3.md +64 -0
- package/docs/services/resolver.md +21 -0
- package/docs/services/secret.md +20 -15
- package/docs/services/staticwebsite.md +17 -0
- package/package.json +14 -14
- package/dist/application-BYlhYQyh.mjs +0 -199
- package/dist/application-BYlhYQyh.mjs.map +0 -1
- package/dist/application-KZRJHv2j.mjs +0 -1
- package/dist/crashreport-CgymxQDu.mjs +0 -1
- package/dist/date-B7-oyTGE.mjs.map +0 -1
- package/dist/es-builtins-BHCXINQp.mjs +0 -2
- package/dist/field-parse-BbNyotv5.mjs +0 -2
- package/dist/field-parse-BbNyotv5.mjs.map +0 -1
- package/dist/guards-ForsrxnH.mjs +0 -2
- package/dist/manager-qfbUL7ru.mjs +0 -2
- package/dist/register-ts-hook-Djjnj5R8.mjs +0 -917
- package/dist/register-ts-hook-Djjnj5R8.mjs.map +0 -1
- package/dist/registry-HlEaGvl5.mjs +0 -2
- package/dist/repl-editor-BG1aDOfH.mjs +0 -2
- package/dist/schema-BKvcWdVf.mjs +0 -2
- package/dist/service-BgrEteZ2.mjs +0 -1
- package/dist/service_pb-DKrsO1_u.mjs +0 -1
- package/dist/service_pb-DprmLNsq.mjs +0 -2
- package/dist/tailordb-ddl-Fgm2cNvT.mjs +0 -7
- package/dist/workspace_resource_pb-BOoRts_z.mjs +0 -2
package/dist/cli/main.mjs
CHANGED
|
@@ -1,94 +1,94 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)}const gi=O({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))}}),_i=O({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=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 vi=new Set([`__proto__`,`constructor`,`prototype`]),yi=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=>vi.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)}}),bi=O({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:_i,inspect:gi},args:q.strictObject({...R,...ie,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(yi.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 A({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 on({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 f({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),xi=O({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 hn({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`,...T({profile:e})]}})}}),Si=O({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 nn({profile:e});c.out(t)}}),Ci=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:xi,token:Si}}),wi={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}: ${kr(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 ei.randomBytes(32).toString(`base64url`)}const Ti=O({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...R,...wi,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 A({profile:e.profile});let t=Or([`tailor`,`authconnection`,`open`,...T({profile:e.profile,workspaceId:e[`workspace-id`]})]),{client:n,workspaceId:r}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await er(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(),l;l=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let u=new URL(l);u.searchParams.set(`client_id`,a.clientId),u.searchParams.set(`redirect_uri`,o),u.searchParams.set(`response_type`,`code`),u.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),u.searchParams.set(`state`,s),u.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,u)=>{if(!t.url?.startsWith(`/callback`)){u.writeHead(404),u.end(`Not found`);return}try{let a=new URL(t.url,`http://localhost:${e.port}`),d=a.searchParams.get(`code`),f=a.searchParams.get(`state`),p=a.searchParams.get(`error`);if(p)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${p}`});if(f!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!d)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});c.registerSecret(d),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:d,redirectUri:o}),u.writeHead(200,{"Content-Type":`text/html`}),u.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),l.close(),i()}catch(e){u.writeHead(400,{"Content-Type":`text/plain`}),u.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),l.close(),a(kr(e))}},l=ni.createServer((e,t)=>void handleCallback(e,t)),d=setTimeout(()=>{l.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);l.on(`close`,()=>{clearTimeout(d)}),l.on(`error`,n=>{clearTimeout(d);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=u.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 ri(n)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(e.port,()=>void announceAuthorizeUrl())}),c.success(`Auth connection "${e.name}" authorized successfully.`)}}),Ei=O({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...R,...wi,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await k.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Auth connection deletion cancelled.`);return}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 Di=O({name:`list`,description:`List all auth connections.`,args:q.strictObject({...R,...Re()}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=Ue(e.order),i=await 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.limit});c.out(i.map(connectionInfo))}catch(e){if(e instanceof Q&&e.code===Z.NotFound){c.out([]);return}throw e}}}),Oi=O({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...R}),run:async e=>{let t=await on({workspaceId:e[`workspace-id`],profile:e.profile}),n=l(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/auth-connections`:`/workspaces/${t}/settings/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 ri(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}`)}}),ki=O({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,...wi,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await k.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name){c.info(`Auth connection revocation cancelled.`);return}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.`)}}),Ai=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Ti,list:Di,open:Oi,revoke:ki,delete:Ei},async run(){await b(Di)}});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(Mr)).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 ji=O({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Re()}),run:async e=>{let t=Nr(),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=orderAndLimitCrashReports(r,{order:e.order,limit:e.limit});if(i.length===0){c.info(`No crash reports found.`),n&&c.out([]);return}if(n){c.out(formatCrashReportFiles(i,t.localDir));return}c.info(`${i.length} crash report(s) in ${t.localDir}:`);for(let e of i)c.log(` ${e}`)}}),Mi=O({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 Cr();c.info(`Sending crash report...`),await Pr(n,r)?c.success(`Crash report submitted successfully. Thank you!`):(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-DhnFs9WG.mjs";import{E as t,It as n,Ut as r,kt as i,q as a}from"../workspace_resource_pb-D2njwgsE.mjs";import{t as o}from"../assert-WeXvmG4j.mjs";import{i as s,n as c,o as l}from"../logger-Cp5U2IDI.mjs";import{$ as u,$n as d,$r as f,$t as p,Ai as m,An as h,Ar as g,B as _,Bn as v,Br as y,Ci as b,Cn as x,Cr as ee,Ct as S,D as te,Di as C,Dn as w,Dr as ne,Dt as re,Ei as ie,En as ae,Er as oe,Et as se,Fi as ce,Fr as le,Gn as ue,Gr as de,H as T,Hn as fe,Hr as pe,I as me,Ii as E,Ir as he,It as ge,J as _e,Jn as ve,Jr as ye,Jt as be,K as xe,Kn as Se,Kr as D,Kt as Ce,Li as we,Lr as Te,Lt as Ee,M as De,Mi as Oe,Mr as ke,N as Ae,Ni as je,Nr as Me,Nt as Ne,On as Pe,Ot as Fe,P as Ie,Pi as Le,Pr as Re,Q as ze,Qn as Be,Qr as O,R as Ve,Ri as He,S as Ue,Si as k,Sn as We,T as Ge,Ti as Ke,Tn as qe,Tt as Je,U as Ye,Un as Xe,Ur as Ze,Ut as Qe,V as $e,Vn as et,Vr as tt,Wn as nt,Wr as rt,Xn as it,Xr as at,Xt as ot,Y as st,Yn as ct,Yr as lt,Zn as ut,Zr as A,_i as dt,a as ft,ai as pt,an as mt,ar as ht,at as gt,b as _t,bi as vt,bn as yt,br as bt,c as xt,ci as St,cr as Ct,di as wt,dn as Tt,dr as j,dt as Et,ei as M,en as Dt,er as Ot,f as kt,fi as At,fn as jt,fr as N,g as Mt,gi as Nt,gn as Pt,hi as P,hn as Ft,ht as It,ii as Lt,in as Rt,ir as zt,jn as Bt,jr as Vt,jt as Ht,k as Ut,ki as F,kr as Wt,kt as Gt,li as Kt,lr as qt,lt as Jt,m as Yt,mi as I,n as Xt,ni as Zt,nn as Qt,nr as L,o as $t,oi as en,on as tn,or as nn,pi as rn,pn as an,pt as on,qn as sn,qr as cn,ri as ln,rn as un,rr as dn,rt as fn,si as pn,sn as mn,sr as hn,st as gn,t as _n,ti as R,tn as vn,tr as yn,tt as bn,u as xn,ui as Sn,un as Cn,ur as wn,v as Tn,vi as En,vn as Dn,vt as On,w as kn,wn as An,wr as jn,wt as Mn,xi as z,xn as Nn,xr as Pn,xt as Fn,yi as In,yn as Ln,yt as Rn,z as zn,zi as B,zr as Bn,zt as Vn}from"../register-ts-hook-YtsAGTMD.mjs";import{$ as Hn,B as Un,C as Wn,F as Gn,G as Kn,I as qn,K as Jn,L as Yn,M as Xn,N as Zn,P as Qn,R as $n,S as er,W as tr,X as nr,Y as V,Z as rr,_ as ir,at as ar,b as or,d as sr,et as cr,ft as lr,h as ur,ht as dr,it as fr,m as pr,o as mr,q as hr,rt as gr,s as _r,tt as vr,x as yr,z as br}from"../application-D4913edS.mjs";import{g as xr,i as Sr,r as Cr}from"../service-BrGSi2IQ.mjs";import{t as H}from"../multiline-EyzjEwn9.mjs";import{a as wr,c as Tr,i as Er,n as Dr,o as Or,r as kr,s as Ar,t as U}from"../errors-sNtg2Mv3.mjs";import{t as jr}from"../package-json-C690ceex.mjs";import{t as Mr}from"../user-agent-vdHYF3QL.mjs";import{t as Nr}from"../service_pb-y2GYIgfs.mjs";import{a as Pr,i as Fr,o as Ir,r as Lr,t as Rr}from"../crashreport-BAz-ph5O.mjs";import{t as zr}from"../manager-C0dE7pd0.mjs";import{a as Br,i as Vr,n as Hr}from"../kysely-type-C-iyFFH7.mjs";import{arg as W,defineCommand as G,extractFields as Ur,runMain as Wr,toCamelCase as Gr}from"@politty/zod";import{withCompletionCommand as Kr}from"@politty/zod/completion";import{withSkillCommand as qr}from"@politty/zod/skill";import*as K from"pathe";import{dirname as Jr,resolve as Yr}from"pathe";import{resolvePackageJSON as Xr}from"pkg-types";import{z as q}from"zod";import{ScalarType as J,create as Zr}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as Qr,constants as $r,readdirSync as ei}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{pathToFileURL as ti}from"node:url";import{generateCodeVerifier as ni}from"@badgateway/oauth2-client";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import*as ri from"node:crypto";import{randomBytes as ii}from"node:crypto";import*as ai from"node:http";import oi from"open";import*as si from"rolldown";import{parseSync as ci}from"oxc-parser";import*as li from"node:os";import*as $ from"node:fs/promises";import{setTimeout as ui}from"node:timers/promises";import{TraceMap as di,generatedPositionFor as fi,originalPositionFor as pi}from"@jridgewell/trace-mapping";import{spawn as mi,spawnSync as hi}from"node:child_process";const gi=Nr.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return gi.map(e=>e.name).toSorted()}function listMethodChoices(){return gi.flatMap(e=>[e.name,`${Nr.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return gi.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 _i=/* @__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 _i.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 vi={[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 vi[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 yi=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))}}),bi=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?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 xi=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),Si=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=>xi.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)}}),Ci=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:bi,inspect:yi},args:q.strictObject({...B,...ie,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(Si.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 M({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 rn({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await R(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await f({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),wi=k({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:B.profile}),run:async({profile:e})=>{let t=await pn({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`,...E({profile:e})]}})}}),Ti=k({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:B.profile}),run:async({profile:e})=>{let t=await en({profile:e});c.out(t)}}),Ei=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:wi,token:Ti}}),Di={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}: ${Ar(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 ri.randomBytes(32).toString(`base64url`)}const Oi=k({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...B,...Di,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 M({profile:e.profile});let t=kr([`tailor`,`authconnection`,`open`,...E({profile:e.profile,workspaceId:e[`workspace-id`]})]),{client:n,workspaceId:r}=await O({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await Jn(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(),l;l=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let u=new URL(l);u.searchParams.set(`client_id`,a.clientId),u.searchParams.set(`redirect_uri`,o),u.searchParams.set(`response_type`,`code`),u.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),u.searchParams.set(`state`,s),u.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,u)=>{if(!t.url?.startsWith(`/callback`)){u.writeHead(404),u.end(`Not found`);return}try{let a=new URL(t.url,`http://localhost:${e.port}`),d=a.searchParams.get(`code`),f=a.searchParams.get(`state`),p=a.searchParams.get(`error`);if(p)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${p}`});if(f!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!d)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});c.registerSecret(d),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:d,redirectUri:o}),u.writeHead(200,{"Content-Type":`text/html`}),u.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),l.close(),i()}catch(e){u.writeHead(400,{"Content-Type":`text/plain`}),u.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),l.close(),a(Ar(e))}},l=ai.createServer((e,t)=>void handleCallback(e,t)),d=setTimeout(()=>{l.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);l.on(`close`,()=>{clearTimeout(d)}),l.on(`error`,n=>{clearTimeout(d);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=u.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 oi(n)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(e.port,()=>void announceAuthorizeUrl())}),c.success(`Auth connection "${e.name}" authorized successfully.`)}}),ki=k({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...B,...Di,...C}),run:async e=>{await M({profile:e.profile});let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await A.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Auth connection deletion cancelled.`);return}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 Ai=k({name:`list`,description:`List all auth connections.`,args:q.strictObject({...B,...Le()}),run:async e=>{let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=He(e.order),i=await V(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e.limit});c.out(i.map(connectionInfo))}catch(e){if(e instanceof Q&&e.code===Z.NotFound){c.out([]);return}throw e}}}),ji=k({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...B}),run:async e=>{let t=await rn({workspaceId:e[`workspace-id`],profile:e.profile}),n=l(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/auth-connections`:`/workspaces/${t}/settings/connections`,r=await Kt({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 oi(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}`)}}),Mi=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({...B,...Di,...C}),run:async e=>{await M({profile:e.profile});let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await A.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name){c.info(`Auth connection revocation cancelled.`);return}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.`)}}),Ni=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Oi,list:Ai,open:ji,revoke:Mi,delete:ki},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(Fr)).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 Pi=k({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Le()}),run:async e=>{let t=Ir(),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=orderAndLimitCrashReports(r,{order:e.order,limit:e.limit});if(i.length===0){c.info(`No crash reports found.`),n&&c.out([]);return}if(n){c.out(formatCrashReportFiles(i,t.localDir));return}c.info(`${i.length} crash report(s) in ${t.localDir}:`);for(let e of i)c.log(` ${e}`)}}),Fi=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 Mr();c.info(`Sending crash report...`),await Lr(n,r)?c.success(`Crash report submitted successfully. Thank you!`):(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${Pr}\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 Ii=G({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:Pi,send:Fi},defaultSubCommand:`list`}),Li=k({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,args:q.strictObject({...B,...Oe,...C,"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`}),"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 M({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await Cn({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`],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})}}),Ri=G({name:`executor`,description:`Manage executors`,subCommands:{trigger:Ee,jobs:Qe,list:Vn,get:mn,webhook:ge},defaultSubCommand:`list`});function scriptNameToRegistryName(e,t){if(t===a.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let r=/^(.+)\.operation\.js$/.exec(e);if(r){let[,e]=r;return`executor--${e}`}let i=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(i){let[,e,t]=i;return`auth-hook--${e}--${t}`}return t===a.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 zi=/^\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=zi.exec(e);t&&a.push({functionName:t[1]||`<anonymous>`,file:o(t[2],`stack frame file missing`),line:Number(o(t[3],`stack frame line missing`)),column:Number(o(t[4],`stack frame column missing`))})}return{errorMessage:i,frames:a}}const Bi=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=Bi.exec(e);if(!t)return null;try{let e=Buffer.from(o(t[1],`sourcemap base64 data missing`),`base64`).toString(`utf-8`),n=JSON.parse(e);return new di(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=fi(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=pi(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),c=n[e];r===t?o.push(` ${s.error(`>`)} ${s.error(`${i} | ${c}`)}`):o.push(` ${s.dim(`${i} | ${c}`)}`)}return o.join(`
|
|
9
9
|
`)}function formatMappedError(e,t,n,r){let i=[` ${s.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 ${s.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){switch(e){case a.STANDARD:return`STANDARD`;case a.JOB:return`JOB`;default:return`UNSPECIFIED`}}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:
|
|
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){switch(e){case a.STANDARD:return`STANDARD`;case a.JOB:return`JOB`;default:return`UNSPECIFIED`}}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:Rt(e.status),type:functionExecutionTypeToString(e.type),startedAt:e.startedAt?X(e.startedAt):null,finishedAt:e.finishedAt?X(e.finishedAt):null}}function toFunctionExecutionDetailInfo(e){return{...toFunctionExecutionListInfo(e),logs:e.logs,logEntries:e.logEntries.map(tn),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;if(!r)return`${t}: ${n}`;let i=r.split(`
|
|
11
11
|
`,1)[0]??``;return/^\s+at\s+/.test(i)?`${t}: ${n}\n${r}`:r}function formatExecutionErrorFallback(e){let[t=``,...n]=composeExecutionErrorString(e).split(`
|
|
12
12
|
`);return[` ${s.error(t)}`,...n.map(e=>` ${s.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)]];c.out(Nn(t))}function printFunctionExecutionLogs(e){let t=un(e.logEntries,e.logs);if(t.length!==0){c.log(s.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(s.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(s.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(` ${
|
|
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`:Rt(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 ui(t);return}if(e<=0)throw timeoutError();await ui(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(!Dt(e))throw e;c.warn(`Retrying function execution poll: ${p(e)}`,{mode:`stream`}),await sleep();continue}if(r){if(o===void 0&&(printFunctionExecutionSummary(toFunctionExecutionListInfo(n)),mt(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(s.bold(`
|
|
19
|
+
Logs:`));for(let e of n.logEntries.slice(a))c.log(` ${Qt(tn(e))}`);a=n.logEntries.length}if(o!==void 0&&n.status!==o){let e=vn(Rt(n.status));c.info(`Status: ${e}`,{mode:`stream`})}}let i=o!==void 0;if(o=n.status,mt(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 Vi=k({name:`logs`,description:`List or get function execution logs.`,notes:"Execution details include `logEntries`, the structured log lines (message, severity, timestamp) recorded while the function ran. They are available while the execution is still running, whereas the flat `logs` string is filled in only after completion. The human-readable view shows the structured entries when present and falls back to `logs` otherwise.\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. On environments where no structured entries are returned, `--follow` shows the flat `logs` string once the execution completes. 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({...B,...je,"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(m.default(`3s`),{alias:`i`,description:`Polling interval for --follow (e.g., '3s', '500ms', '1m')`}),timeout:W(m.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 O({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:ce(e.interval),timeout:e.timeout===void 0?void 0:ce(e.timeout),showProgress:!r}):{execution:await fetchFunctionExecution(i),printedEntries:0,followed:!1},l=toFunctionExecutionDetailInfo(a);if(r){c.out(l);return}(!e.follow||s)&&printFunctionExecutionSummary(l),o===0&&printFunctionExecutionLogs(l),printFunctionExecutionOutcome({detail:l,bundledCode:l.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:l.scriptName,executionType:a.type,executionContentHash:a.contentHash}):null})}else{let r=He(e.order),i=(await V(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e.limit})).map(toFunctionExecutionListInfo);if(i.length===0&&!e.json){c.info(`No function execution logs found.`);return}c.out(i)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o}=e,s=mr(e.inlineSourcemap),c=br(e.logLevel),l=K.resolve(_r(),`test-run`);Y.mkdirSync(l,{recursive:!0});let u=`test-run--${t.name}`,d=`${u}.js`,f=K.join(l,`${u}.entry.js`),p=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission});Y.writeFileSync(f,p);let m=await Qn(r),h=Un({tsconfig:m}),g=await si.build({plugins:[Xn(f,r),Zn(),t.type===`resolver`?Gn(er(t.fields)):qn],input:f,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:m,treeshake:Yn([$n(c)]),...h.options});return h.assertAllResolved(),{bundledCode:g.output[0].code,scriptName:d}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:s}=e,c=K.resolve(n);switch(t.type){case`plain`:return t.namedMain?H`
|
|
20
20
|
export { main } from "${c}";
|
|
21
|
-
`:
|
|
21
|
+
`:H`
|
|
22
22
|
import _fn from "${c}";
|
|
23
23
|
export { _fn as main };
|
|
24
|
-
`;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=
|
|
24
|
+
`;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=yr({permission:t.permission,defaultPermission:s}),{importStatement:o,resultExpr:l}=or(t.fields?.output);return H`
|
|
25
25
|
import _internalResolver from "${c}";
|
|
26
26
|
import { t } from "@tailor-platform/sdk";
|
|
27
|
-
|
|
27
|
+
${o}
|
|
28
28
|
|
|
29
29
|
const $tailor_resolver_body = async (rawInput) => {
|
|
30
30
|
const _caller = ${e};
|
|
31
|
-
const invoker = (${
|
|
31
|
+
const invoker = (${ir}) ?? _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 ${l};
|
|
36
36
|
};
|
|
37
37
|
|
|
38
38
|
export { $tailor_resolver_body as main };
|
|
39
|
-
`}case`executor`:{let e=buildMachinePrincipalExpr(i,a);return
|
|
39
|
+
`}case`executor`:{let e=buildMachinePrincipalExpr(i,a);return H`
|
|
40
40
|
import _internalExecutor from "${c}";
|
|
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 = ${ir} ?? _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=o(t.exportName,`workflow job export name missing`),n=buildMachinePrincipalExpr(i,a);return
|
|
51
|
+
`}case`workflow-job`:{let e=o(t.exportName,`workflow job export name missing`),n=buildMachinePrincipalExpr(i,a);return H`
|
|
52
52
|
import { ${e} } from "${c}";
|
|
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 = ${ir} ?? 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(ti(n).href),a=ur.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=Sr.safeParse(Cr(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
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=sr.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
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=o(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
|
|
69
|
-
`);function generateScriptDbTypes(e){let t=Object.values(e.tables).map(e=>
|
|
70
|
-
`)}function loadScriptSchemaSnapshot(e){let t=K.join(K.dirname(e),
|
|
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 Hi=`db.ts`,Ui=`db.snapshot.json`,Wi=[`/**`,` * 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){let t=Object.values(e.tables).map(e=>Br(e.name,e.fields)),n=Vr([{namespace:e.namespace,types:t}]);return`${Wi}\n\n${n}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=ci(K.basename(e),t);if(n.length>0)throw wr(`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),Ui);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:Bn(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(Fe(r).includes(s)){let{namespaces:t}=await se({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,wn(e)])),r=Te(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(rt(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await et(t,n,s),l=Te(a.source===`local`?generatedContractSnapshot(o):Bn(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):Bn(pickTableFields(c)));if(rt(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return Bn(pickTableFields(hn(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 Bn({...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=kr([`tailor`,`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]),a=kr([`tailor`,`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]);return U({code:`SCRIPT_SCHEMA_DRIFT`,message:`Schema drift detected: ${Ui} next to the script no longer matches ${e}.`,details:Ze(t),suggestion:`Refresh the generated types with ${i}, or run anyway with ${a}.`})}const Gi=k({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:q.object({...B,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 t=c.jsonMode,n=K.resolve(e.file);if(!Y.existsSync(n))throw U({code:`FILE_NOT_FOUND`,message:`File not found: ${n}`});let{config:r}=await R(e.config),a=resolveAuthNamespace(r.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:we(e[`machine-user`]),profile:e.profile,authConfig:r.auth}),{client:l,workspaceId:u}=await O({profile:e.profile,workspaceId:e[`workspace-id`]}),d=await resolveMachineUser({client:l,workspaceId:u,authNamespace:a,machineUserName:o,authConfig:r.auth}),f=K.relative(process.cwd(),n),p=n.endsWith(`.js`);if(!p){if(e[`allow-schema-drift`])Y.existsSync(K.join(K.dirname(n),`db.snapshot.json`))&&c.warn(`Skipping the schema snapshot check (--allow-schema-drift).`);else{let t=loadScriptSchemaSnapshot(n);t&&(c.info(`Checking the script's schema snapshot for drift...`),await verifyScriptSchemaSnapshot({client:l,workspaceId:u,config:r,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let m,h,g,_;if(p)h=K.basename(n),m=Y.readFileSync(n,`utf-8`),c.info(`Using pre-bundled script ${s.bold(h)}`);else{c.info(`Detecting function type from ${s.path(f)}`);let t=await detectFunctionType({filePath:n,jobName:e.name});g=t.type,_=t.name,c.info(`Detected: ${s.bold(t.type)} ${s.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 i=K.dirname(r.path);({bundledCode:m,scriptName:h}=await bundleForRun({detected:t,sourceFile:n,baseDir:i,defaultPermission:t.type===`resolver`?pr({config:r.resolver,filePath:n,baseDir:i}):void 0,env:r.env??{},inlineSourcemap:r.inlineSourcemap,logLevel:r.logLevel,machineUser:d,workspaceId:u})),c.info(`Bundled as ${s.bold(h)}`)}let v=Zr(i,{namespace:a,machineUserName:d.name});c.info(`Executing on workspace ${s.dim(u)}...`);let y;if(e.arg!==void 0)try{y=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 b=await Gt({client:l,workspaceId:u,name:h,code:m,arg:y,invoker:v});if(t)c.out({success:b.success,scriptName:h,functionType:g,functionName:_,logs:b.logs,result:b.result,error:b.error});else{if(b.success?c.success(`Execution succeeded`):c.error(`Execution failed`),b.logs.trim()){c.log(s.bold(`
|
|
71
71
|
Logs:`));for(let e of b.logs.split(`
|
|
72
72
|
`))c.log(` ${e}`)}if(b.result&&b.success){c.log(s.bold(`
|
|
73
73
|
Result:`));try{let e=JSON.parse(b.result);c.log(` ${JSON.stringify(e,null,2).split(`
|
|
74
74
|
`).join(`
|
|
75
75
|
`)}`)}catch{c.log(` ${b.result}`)}}if(b.error&&!b.success){c.log(s.bold(`
|
|
76
|
-
Error:`));let e=formatErrorWithSourcemap(b.error,m,process.cwd());e?c.log(e):c.log(` ${s.error(b.error)}`)}}b.success||process.exit(1)}}),
|
|
77
|
-
`),g.push(a),_=`./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(u);_=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||c.warn(`Generated Kysely types not found at ${s.path(K.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:_,namespace:h});assertGeneratedTypeScript(t,e),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(t,e),g.unshift(t)}let y=[`tailor`,`function`,`run`,K.relative(process.cwd(),t)];e.config!==`tailor.config.ts`&&y.push(`--config=${e.config}`);let b=v??e[`workspace-id`];if(b!==void 0&&y.push(`--workspace-id=${b}`),e.profile!==void 0&&y.push(`--profile=${e.profile}`),c.jsonMode){c.out({script:t,created:g,namespace:h,usesGeneratedDbTypes:p});return}r&&c.info(`Script already exists; refreshed generated types only.`);for(let e of g)c.success(`Created ${s.path(K.relative(process.cwd(),e))}`);c.info(`Next: edit the script, then run ${
|
|
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||_r(t)}const startAuthServer=async(e={})=>{let t=Un(e.platformConfig),n=randomState(),r=await $r(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:Yi,state:n,codeVerifier:r}).catch(e=>{throw U({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${kr(e).message}`,cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,u)=>{try{if(!i.url?.startsWith(`/callback`))throw U({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let s=`http://${i.headers.host}${i.url}`,l=new URL(s).searchParams.get(`code`);l&&c.registerSecret(l);let d=await t.authorizationCode.getTokenFromCodeRedirect(s,{redirectUri:Yi,state:n,codeVerifier:r});Ft({accessToken:d.accessToken,refreshToken:d.refreshToken??void 0});let f=await Jn(d.accessToken,e.platformConfig),p=await M();await yt(p,f.sub,{accessToken:d.accessToken,refreshToken:d.refreshToken??void 0},new Date(o(d.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:f.email});let m=getProfileUserMismatch(e,f.email,f.sub);if(m)throw L(p),profileUserMismatchError(m);(e.updateCurrentUser??!0)&&(p.current_user=f.sub),await ft(p,f.email,f.sub,e.platformConfig),L(p),u.writeHead(200,{"Content-Type":`application/json`}),u.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a()}catch(e){u.writeHead(401),u.end(`Authentication failed`),s(kr(e))}finally{l.close()}},l=ni.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),s(U({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);l.on(`close`,()=>{clearTimeout(u)}),l.on(`error`,e=>{s(e)});let openBrowser=async()=>{c.info(`Opening browser for login:\n\n${i}\n`);try{await ri(i)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(Ji,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await k.password({message:`Client secret`}),n=await hr(e.clientId,t,e.platformConfig),r=await M();await yt(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 L(r),profileUserMismatchError(i);(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),L(r)}const Xi=O({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 M()).profiles[e.profile];if(!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=P(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t);`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.`)}finally{await tr()}}}),Zi=O({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 M(),r=t?n.profiles[t]:void 0;if(t&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?P(r):void 0,a=r?r.user:n.current_user,o=_r(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){c.info(`You are not logged in.`);return}let hasDefaultUserToken=()=>mt(n,a,{platformUrl:Kn}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!zt(n,a))&&!hasDefaultUserToken(),l,u=!1;try{l=await Mt(n,a,i,s)}catch(e){u=!0,c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!l&&!u){c.info(`You are not logged in.`),shouldClearCurrentUser()&&(n.current_user=null),L(n);return}if(l)try{let e=Un(i),t=l.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:l.accessToken,refreshToken:l.refreshToken??null,expiresAt:Date.parse(l.userEntry.token_expires_at)},t)}catch(e){c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await $t(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),L(n),c.success(`Successfully logged out from Tailor Platform.`)}}),Qi=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Bn,token:An},async run(){await b(Bn)}}),$i=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:cn,get:Rt},async run(){await b(cn)}}),ea=O({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...N}),run:async e=>{let t=await on({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await I(e.config),r=n.name,i=l(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`:`/workspaces/${t}/applications/${encodeURIComponent(r)}/overview`,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 u=!0;try{await ri(o)}catch{u=!1}if(s){c.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:u});return}u?(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}`)}}),ta=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Ot,delete:Xt,get:vn,list:_t,update:mn}}),na=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:ta,get:Sn,list:u,tree:Be,update:ct},async run(){await b(u)}}),ra=`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(`.`),ia={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},aa=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{Yr(e,process.platform===`win32`?Xr.F_OK:Xr.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(aa).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=new Map,scan=(e,r)=>{for(let i of e){let e;try{e=Zr(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 M(),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 Sr();e&&(n.TAILOR_VERSION=e)}catch{}let i=Ct();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await Tt({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=$n(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=rr(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await on({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await nn({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=oi.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=di(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=ia[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 oa=O({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Sr(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(ra),r=listPlugins(t);if(r.length===0){c.info(V`
|
|
76
|
+
Error:`));let e=formatErrorWithSourcemap(b.error,m,process.cwd());e?c.log(e):c.log(` ${s.error(b.error)}`)}}b.success||process.exit(1)}}),Ki=new Set(Ur(q.strictObject(Ke)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${Gr(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(`=`)&&Ki.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 Sn({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 o(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],l=null,u=[];if(s&&typeof s==`object`){let e=s;l=e.attributes??null,u=e.attributeList??[]}return{name:i,id:o,attributes:l,attributeList:u}}const qi=k({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:q.object({...B,...ie,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,Hi),a=K.join(n,Ui);if(t===i)throw U({code:`SCRIPT_PATH_INVALID`,message:`${Hi} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,command:`function script`});let{config:l,plugins:u}=await R(e.config),d=u.find(e=>e.id===Hr),f=Y.existsSync(a);if(e.remote&&d!==void 0&&r&&!f)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 p=e.remote||d===void 0||f,m;if(p)try{m=loadScriptSchemaSnapshot(t)?.snapshot.namespace}catch{}let h=resolveNamespace({config:l,explicit:e.namespace,sidecarNamespace:m,remote:e.remote});if(m!==void 0&&m!==h)throw U({code:`SCRIPT_NAMESPACE_MISMATCH`,message:`This directory's generated types target namespace "${m}" (${Ui}).`,suggestion:`Scaffold scripts for namespace "${h}" in a separate directory.`});let g=[],_,v;if(p){let t;if(e.remote){let{client:n,workspaceId:r}=await O({profile:e.profile,workspaceId:e[`workspace-id`]});v=r,c.info(`Fetching deployed schema of namespace ${s.bold(h)}...`),t=await et(n,r,h)}else{c.info(`Loading local definitions of namespace ${s.bold(h)}...`);let{namespaces:n}=await se({configPath:e.config,namespaces:[h]}),r=o(n[0],`namespace ${h}`);t=qt(r.tables,h)}if(Object.keys(t.tables).length===0){let t=e.remote?`deployed tables in workspace ${o(v,`workspace ID`)}`:`locally defined tables`;throw U({code:`SCRIPT_SCHEMA_NOT_FOUND`,message:`Namespace "${h}" 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);assertGeneratedTypeScript(i,r),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(i,r),g.push(i),Y.writeFileSync(a,JSON.stringify({...t,source:e.remote?`remote`:`local`},null,2)+`
|
|
77
|
+
`),g.push(a),_=`./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(u);_=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||c.warn(`Generated Kysely types not found at ${s.path(K.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:_,namespace:h});assertGeneratedTypeScript(t,e),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(t,e),g.unshift(t)}let y=[`tailor`,`function`,`run`,K.relative(process.cwd(),t)];e.config!==`tailor.config.ts`&&y.push(`--config=${e.config}`);let b=v??e[`workspace-id`];if(b!==void 0&&y.push(`--workspace-id=${b}`),e.profile!==void 0&&y.push(`--profile=${e.profile}`),c.jsonMode){c.out({script:t,created:g,namespace:h,usesGeneratedDbTypes:p});return}r&&c.info(`Script already exists; refreshed generated types only.`);for(let e of g)c.success(`Created ${s.path(K.relative(process.cwd(),e))}`);c.info(`Next: edit the script, then run ${kr(y)}`)}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=re(t),o=Fe(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=Mn(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 Ji=G({name:`function`,description:`Manage functions`,subCommands:{get:Ne,list:Ht,logs:Vi,run:Gi,script:qi},defaultSubCommand:`list`}),Yi=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 Fn({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},Xi=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 jr(),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(` `)}`),hi(r,i,{stdio:`inherit`})}}),Zi=8085,Qi=`http://localhost:${Zi}/callback`;function randomState(){return ri.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||ar(t)}const startAuthServer=async(e={})=>{let t=gr(e.platformConfig),n=randomState(),r=await ni(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:Qi,state:n,codeVerifier:r}).catch(e=>{throw U({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${Ar(e).message}`,cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,u)=>{try{if(!i.url?.startsWith(`/callback`))throw U({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let s=`http://${i.headers.host}${i.url}`,l=new URL(s).searchParams.get(`code`);l&&c.registerSecret(l);let d=await t.authorizationCode.getTokenFromCodeRedirect(s,{redirectUri:Qi,state:n,codeVerifier:r});Nt({accessToken:d.accessToken,refreshToken:d.refreshToken??void 0});let f=await rr(d.accessToken,e.platformConfig),p=await P();await vt(p,f.sub,{accessToken:d.accessToken,refreshToken:d.refreshToken??void 0},new Date(o(d.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:f.email});let m=getProfileUserMismatch(e,f.email,f.sub);if(m)throw z(p),profileUserMismatchError(m);(e.updateCurrentUser??!0)&&(p.current_user=f.sub),await dt(p,f.email,f.sub,e.platformConfig),z(p),u.writeHead(200,{"Content-Type":`application/json`}),u.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a()}catch(e){u.writeHead(401),u.end(`Authentication failed`),s(Ar(e))}finally{l.close()}},l=ai.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),s(U({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);l.on(`close`,()=>{clearTimeout(u)}),l.on(`error`,e=>{s(e)});let openBrowser=async()=>{c.info(`Opening browser for login:\n\n${i}\n`);try{await oi(i)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(Zi,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await A.password({message:`Client secret`}),n=await nr(e.clientId,t,e.platformConfig),r=await P();await vt(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 z(r),profileUserMismatchError(i);(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),z(r)}const $i=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 P()).profiles[e.profile];if(!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=I(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t);`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.`)}finally{await tr()}}}),ea=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 P(),r=t?n.profiles[t]:void 0;if(t&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?I(r):void 0,a=r?r.user:n.current_user,o=ar(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){c.info(`You are not logged in.`);return}let hasDefaultUserToken=()=>pt(n,a,{platformUrl:Kn}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!Lt(n,a))&&!hasDefaultUserToken(),l,u=!1;try{l=await At(n,a,i,s)}catch(e){u=!0,c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!l&&!u){c.info(`You are not logged in.`),shouldClearCurrentUser()&&(n.current_user=null),z(n);return}if(l)try{let e=gr(i),t=l.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:l.accessToken,refreshToken:l.refreshToken??null,expiresAt:Date.parse(l.userEntry.token_expires_at)},t)}catch(e){c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await Zt(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),z(n),c.success(`Successfully logged out from Tailor Platform.`)}}),ta=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Rn,token:On},defaultSubCommand:`list`}),na=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:on,get:It},defaultSubCommand:`list`}),ra=k({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...F}),run:async e=>{let t=await rn({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await R(e.config),r=n.name,i=l(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`:`/workspaces/${t}/applications/${encodeURIComponent(r)}/overview`,a=await Kt({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 u=!0;try{await oi(o)}catch{u=!1}if(s){c.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:u});return}u?(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}`)}}),ia=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Et,delete:Jt,get:gn,list:gt,update:fn}}),aa=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:ia,get:bn,list:u,tree:ze,update:st},defaultSubCommand:`list`}),oa=/* @__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(`.`),sa={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},ca=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{Qr(e,process.platform===`win32`?$r.F_OK:$r.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(ca).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=ei(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 P(),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 jr();e&&(n.TAILOR_VERSION=e)}catch{}let i=St();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await wt({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=vr(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Hn(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await rn({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await en({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=li.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=mi(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=sa[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 la=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 jr(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(oa),r=listPlugins(t);if(r.length===0){c.info(H`
|
|
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.`)}}),ua=G({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:la},defaultSubCommand:`list`}),da=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 P();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 ln(t,e.user,r),o=await fr(i,r);if(!(await Jn(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`]}:{}},z(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)}}),fa=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 P();if(!t.profiles[e.name])throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});delete t.profiles[e.name],z(t),c.success(`Profile "${e.name}" deleted successfully.`)}}),pa=k({name:`list`,description:`List all profiles.`,args:q.strictObject({}),run:async()=>{let e=await P(),t=c.jsonMode,n=Object.entries(e.profiles);if(n.length===0){c.info(H`
|
|
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)}}),da=O({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 M(),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,l=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,u=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,d=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,f=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,p=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,m={...d?{platformUrl:d}:{},...f?{oauth2ClientId:f}:{},...p?{consoleUrl:p}:{}},h=Object.keys(m).length>0?m:void 0,g=e[`platform-url`]===``?P(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)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 dn(t,i,g,e.name);s=n.user;let r=await cr(n.accessToken,h);if(!(await er(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`]),L(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(_)}}),fa=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:ca,delete:la,list:ua,update:da},async run(){await b(ua)}}),pa={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},ma={...pa,name:W(q.string(),{alias:`n`,description:`Secret name`})},ha={...ma,value:W(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=E(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[be]}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 ot(t,{trn:n,remove:[be,ut,un]}),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 ga=O({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...R,...ha,...C}),run:async e=>{c.registerSecret(e.value),await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await k.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.createSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}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}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}}),_a=O({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...R,...ma,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await k.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Secret deletion cancelled.`);return}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 D({profile:e.profile,workspaceId:e.workspaceId}),r=Ue(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 va=O({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...R,...pa,...Re()}),run:async e=>{try{let t=await secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:e.limit});c.out(t)}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}}}),ya=O({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...R,...ha,...C}),run:async e=>{c.registerSecret(e.value),await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await k.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.updateSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}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} updated in vault: ${e[`vault-name`]}`)}}}),ba={name:W(q.string(),{positional:!0,description:`Vault name`})},xa=O({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...R,...ba}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({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`)}}),Sa=O({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...R,...ba,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await k.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Vault deletion cancelled.`);return}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 D({profile:e?.profile,workspaceId:e?.workspaceId}),r=Ue(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 Ca=O({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...R,...Re()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),wa=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:xa,delete:Sa,list:Ca},async run(){await b(Ca)}}),Ta=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:wa,create:ga,update:ya,list:va,delete:_a},async run(){await b(wa)}}),Ea={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},Da=O({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 D({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:Ea[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}}}),Oa=O({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 D({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:Ea[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}}}),ka=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:Oa,get:Da}}),Aa=O({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 D({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 D({profile:e?.profile,workspaceId:e?.workspaceId}),r=Ue(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 ja=O({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...R,...Re()}),run:async e=>{let t=c.jsonMode,n=await listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit}),r=t?n:n.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(r)}}),Ma=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Xe,domain:ka,list:ja,get:Aa},async run(){await b(ja)}}),Na=new Set(Object.values(xt));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-`)),l=`${s}-previous`,u=!1,d=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!In.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Na.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:6,createdAt:new Date().toISOString(),rebaseline:r},a=await et(e,s,0);g(a.filePath),await $.rename(i,l),u=!0;try{await $.rename(s,i),d=!0}catch(e){throw await $.rename(l,i),u=!1,e}try{await $.rm(l,{recursive:!0,force:!0})}catch(e){c.warn(`The previous migration directory remains at ${l}: ${e instanceof Error?e.message:String(e)}`)}u=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!d&&u&&Y.existsSync(l)&&await $.rename(l,i)}}async function rebaseline(e){fe(`tailordb migration`);let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=Vt(F(t,r),e.namespace),a=Tr({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});Dt(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:`Run ${a} first.`});let l=Nn(i.migrationsDir),u=j(i.migrationsDir,0)?.rebaseline?.historyId??null,d=an([i])[i.namespace],f=n.length>0?new Ir(n):void 0,{defineApplication:p}=await import(`../application-KZRJHv2j.mjs`),m=p({config:t,pluginManager:f});for(let e of m.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let h=m.tailorDBServices.find(e=>e.namespace===i.namespace);if(!h)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=Yt(h.types,i.namespace),t=ge(o,e.tables,i.namespace);if(it(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(i.namespace)}:`),c.log(Qe(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:`Run ${a} first.`})},localSourceFiles=()=>[t.path,...yr(h.config,r)];assertLocalTypesReady();let g=gt(localSourceFiles()),{client:_,workspaceId:v}=await D({profile:e.profile,workspaceId:e.workspaceId}),b=[`--config`,t.path,...T({workspaceId:v,profile:e.profile})],x=Tr({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...b]}),ee=Tr({command:`tailor`,args:[`deploy`,...b]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await xn(_,E(v,`tailordb`,i.namespace)),a=r.number;if(a!==l){let e=a===null?`<unset>`:y(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${y(l)} 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 Ce(_,v,[i],t,[ue(h)]),s=o[0];if(!s||s.remoteMigrationNumber!==l||s.hasDrift||s.checkpointMissingLocal)throw s?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(pe(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(u,`initial`),c.newline(),c.warn(`This will replace the migration history for ${s.bold(i.namespace)}.`),c.log(` Latest migration: ${y(l)}`),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 k.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(Dt(i.migrationsDir,i.namespace),an([i])[i.namespace]!==d)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(gt(localSourceFiles())!==g)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let S={historyId:Ne(),replacedHistoryId:u,replacedLatestMigration:l};await activateBaseline(i.migrationsDir,o,i.namespace,S);try{await ye(_,v,i.namespace,0,S.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:`Run ${x}, or run ${ee} with schema checks enabled after resolving the connection error.`,cause:e})}c.success(`Re-baselined ${s.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const Pa=O({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({...N,...C,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({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){fe(`tailordb migration`);let t=nt(e.number),{config:n}=await I(e.configPath),r=K.dirname(n.path),i=F(n,r),a=Vt(i,e.namespace),o=a.namespace;Dt(a.migrationsDir,o),ee(a.migrationsDir,t);let l=j(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await D({profile:e.profile,workspaceId:e.workspaceId}),f=E(d,`tailordb`,o),p=await xn(u,f),m=p.number,h=m??0,g=p.historyIdInvalid?`<invalid>`:p.historyId??`<unset>`,_=l??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${s.bold(o)}`),c.log(`Current migration: ${m===null?`<unset>`:s.bold(y(m))}`),c.log(`New migration: ${s.bold(y(t))}`),c.log(`Current migration history ID: ${s.bold(g)}`),c.log(`New migration history ID: ${s.bold(_)}`),c.newline(),t<h?(c.warn(`Setting migration number backwards (${y(h)} → ${y(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>h&&(c.warn(`Setting migration number forwards (${y(h)} → ${y(t)}) will skip migrations ${y(h+1)} to ${y(t)}.`),c.newline()),!e.yes){if(!await k.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await ot(u,{trn:f,labels:{[Ae]:le(t),...l?{[Ut]:l}:{}},remove:l?void 0:[Ut]}),c.success(`Migration checkpoint set to ${s.bold(y(t))} for namespace ${s.bold(o)}`)}const Fa=O({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({...N,...C,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 A({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=F(t,n);if(r.length===0)throw pn();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=new Map,o=new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=ne(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=g(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Kt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Dr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Er(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 D({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=E(c,`tailordb`,e),d;try{d=await xn(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:y(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:y(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${s.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${s.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){fe(`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 Ia=O({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({...N,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 nr(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 er(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 Ir(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-KZRJHv2j.mjs`),l=a({config:n,pluginManager:i}),u=l.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of l.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,l.tailorDBServices,n.path),f=l.executorService??(d.length>0?(await import(`../service-BgrEteZ2.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await f?.loadExecutors(),d.length>0&&await f?.loadPluginExecutorFiles([...d]);let p=new Set;for(let e of Object.values(f?.executors??{}))de(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=j(t.migrationsDir);if(!h)return m;let g=Yt(u.types,t.namespace),_=ge(h,g.tables,t.namespace);if(!it(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(t.namespace)}:`),c.log(Qe(_)),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){fe(`tailordb migration`);let t=nt(e.number),n=await I(e.configPath),{config:r}=n,i=K.dirname(r.path),a=F(r,i),o=Vt(a,e.namespace);Dt(o.migrationsDir,o.namespace);let l=ee(o.migrationsDir,t),u=j(o.migrationsDir,t);if(!u)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 f=await assertMigrationsReproduceLocalTypes(n,o),{client:p,workspaceId:m}=await D({profile:e.profile,workspaceId:e.workspaceId}),h=E(m,`tailordb`,o.namespace),g=await At(p,h),_=await fetchRemoteTypes(p,m,o.namespace),v=new Set(_.map(e=>e.name)),{creates:b,updates:x,deletes:S}=dt(u,v),te=await fetchRemoteGqlPermissions(p,m,o.namespace),C=new Set(te.map(e=>e.typeName)),w=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:d(t.permissions.gql)}]:[]),ne=new Set(w.map(e=>e.typeName)),re=te.filter(e=>!ne.has(e.typeName));if(c.newline(),c.info(`Namespace: ${s.bold(o.namespace)}`),c.log(` Current migration: ${g===null?`<unset>`:s.bold(y(g))}`),c.log(` Target migration: ${s.bold(y(t))}`),c.log(` Tables to create: ${s.bold(String(b.length))}`),c.log(` Tables to update: ${s.bold(String(x.length))}`),c.log(` Tables to delete: ${s.bold(String(S.length))}`),c.log(` GQL permissions to set: ${s.bold(String(w.length))}`),c.log(` GQL permissions to delete: ${s.bold(String(re.length))}`),c.newline(),b.length+x.length+S.length+w.length+re.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.`),S.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(),g!==null&&t<g?(c.warn(`Migrations ${y(t+1)}–${y(g)} 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()):g!==null&&t>g&&(c.warn(`Moving the migration label forwards (${y(g)} → ${y(t)}): migrate.ts scripts for migrations ${y(g+1)}–${y(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await k.confirm({message:`Continue and set migration label to ${y(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ie=Ve(u,f),manifestFor=e=>{let t=ie.get(e);if(!t)throw H(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ae=b.map(e=>manifestFor(e)),oe=x.map(e=>manifestFor(e));try{await Promise.all([...ae.map(e=>p.createTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e})),...oe.map(e=>p.updateTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e}))])}catch(e){ze(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(w.map(({typeName:e,permission:t})=>{let n={workspaceId:m,namespaceName:o.namespace,typeName:e,permission:t};return C.has(e)?p.updateTailorDBGQLPermission(n):p.createTailorDBGQLPermission(n)})),await Promise.all(re.map(e=>p.deleteTailorDBGQLPermission({workspaceId:m,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(S.map(e=>p.deleteTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbTypeName:e}))),await ot(p,{trn:h,labels:{[Ae]:le(t),...u.rebaseline?.historyId?{[Ut]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[Ut]}),c.success(`Synced namespace ${s.bold(o.namespace)} to migration ${s.bold(y(t))}.`),t<l&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${y(t+1)}–${y(l)} from the working tree.`))}const La=O({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...N,...C,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 A({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=>tt(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 H(`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,new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=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=new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=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=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-${new Date().toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${ti(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=F(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(ue),o=(await Ce(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 At(e.client,E(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 tt(e.client,n,r.namespace);if(Ee(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 ir(()=>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??ln(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 Ye({configPath:e.configPath}),n=K.dirname(t.config.path),r=F(t.config,n);if(r.length===0)throw pn();for(let e of r)Dt(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await je({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(ue),s=await nn({profile:e.profile}),c=await Tt({profile:e.profile}),l=await cr(s,c),u=await on({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 Ce(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=new Map,b=new Map,x=[];for(let e of r){let t=await At(l,E(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=Nn(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}".`});b.set(e.namespace,i),t<n&&x.push(e.namespace)}if(x.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let ee=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:ee,targetSnapshots:b,pendingNamespaces:x,...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 It(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 Et({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 ye(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=ue(e);return[e.namespace,n?.snapshot??z({version:1,namespace:e.namespace,createdAt: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 he(e,l,K.dirname(r.loaded.config.path)),d=Le({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 qt({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 H(`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 Nt({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 at(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path)),u=await qt({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,l=!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),l=!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:l,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){fe(`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 Ra=O({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({...N,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 A({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 ne(e)){if(t.type!==`diff`)continue;let n=Kt(t.path),s=oe(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(y).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=>` ${lt({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
88
|
-
`);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(y).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(y).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts.`,suggestion:`Review each ${_} 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=F(t,r);if(i.length===0)throw pn();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 Ir(n):void 0,{defineApplication:s}=await import(`../application-KZRJHv2j.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();vr({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(ue),u=new Map(l.map(e=>[e.namespace,e.types])),d=new Map,f=[],p=e.strict?new Map:void 0;for(let t of a)try{Dt(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,Er(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await v(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await D({profile:e.profile,workspaceId:e.workspaceId});h=await Ce(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: ${s.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${s.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${s.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${s.error(`changes not in migration files`)}`),c.log(` ${me(e.diff)}`),c.log(Qe(e.diff))):c.log(` Local schema: ${s.error(`no migration snapshot found`)}`):c.log(` Local schema: ${s.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${s.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${s.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${y(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(c.log(` Remote schema: ${s.error(`remote migration ${y(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&c.log(` Fell behind before 'migration rebaseline' ran; must reach ${y(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(c.log(` Remote schema: ${s.error(`drift detected`)} (remote migration: ${y(n.remoteMigrationNumber)})`),c.log(wt(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${s.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${s.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${s.dim(`skipped (no local snapshot for remote migration ${y(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${s.success(`OK`)} (remote migration: ${y(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${s.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${s.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=y(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&&Ze(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&rt(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(` ${lt({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){fe(`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 za=O({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({...N,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})}}),Ba=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:He,rebaseline:Pa,script:Vn,set:Fa,status:Ia,sync:La,test:Ra,validate:za}}),Va=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:Oe,migration:Ba}}),Ha=O({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-B4Gh_bbL.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),Ua=O({name:`current`,description:`Show current user.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await M(),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?P(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`,...T({profile:n})]}});if(!mt(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`,...T({profile:n})]}});if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?Rn(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return Rn(e,n.user,P(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 Wa=O({name:`list`,description:`List all users.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await M(),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=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)}}),ma=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 P(),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,l=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,u=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,d=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,f=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,p=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,m={...d?{platformUrl:d}:{},...f?{oauth2ClientId:f}:{},...p?{consoleUrl:p}:{}},h=Object.keys(m).length>0?m:void 0,g=e[`platform-url`]===``?I(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)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 ln(t,i,g,e.name);s=n.user;let r=await fr(n.accessToken,h);if(!(await Jn(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`]),z(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(_)}}),ha=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:da,delete:fa,list:pa,update:ma},defaultSubCommand:`list`}),ga={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},_a={...ga,name:W(q.string(),{alias:`n`,description:`Secret name`})},va={..._a,value:W(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=D(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[ye]}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 at(t,{trn:n,remove:[ye,lt,cn]}),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 ya=k({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...B,...va,...C}),run:async e=>{c.registerSecret(e.value),await M({profile:e.profile});let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await A.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.createSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}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}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}}),ba=k({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...B,..._a,...C}),run:async e=>{await M({profile:e.profile});let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await A.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Secret deletion cancelled.`);return}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 O({profile:e.profile,workspaceId:e.workspaceId}),r=He(e.order);return(await V(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 xa=k({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...B,...ga,...Le()}),run:async e=>{try{let t=await secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:e.limit});c.out(t)}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}}}),Sa=k({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...B,...va,...C}),run:async e=>{c.registerSecret(e.value),await M({profile:e.profile});let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await A.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.updateSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}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} updated in vault: ${e[`vault-name`]}`)}}}),Ca={name:W(q.string(),{positional:!0,description:`Vault name`})},wa=k({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...B,...Ca}),run:async e=>{await M({profile:e.profile});let{client:t,workspaceId:n}=await O({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`)}}),Ta=k({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...B,...Ca,...C}),run:async e=>{await M({profile:e.profile});let{client:t,workspaceId:n}=await O({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await A.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Vault deletion cancelled.`);return}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 O({profile:e?.profile,workspaceId:e?.workspaceId}),r=He(e?.order);return(await V(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 Ea=k({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...B,...Le()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),Da=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:wa,delete:Ta,list:Ea},defaultSubCommand:`list`}),Oa=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Da,create:ya,update:Sa,list:xa,delete:ba},defaultSubCommand:`vault`}),ka={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},Aa=k({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...B,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await O({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:ka[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}}}),ja=k({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...B,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await O({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:ka[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}}}),Ma=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:ja,get:Aa}}),Na=k({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...B,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await O({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 O({profile:e?.profile,workspaceId:e?.workspaceId}),r=He(e?.order);return(await V(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 Pa=k({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...B,...Le()}),run:async e=>{let t=c.jsonMode,n=await listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit}),r=t?n:n.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(r)}}),Fa=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Ye,domain:Ma,list:Pa,get:Na},defaultSubCommand:`list`}),Ia=new Set(Object.values(bt));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-`)),l=`${s}-previous`,u=!1,d=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!Pn.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Ia.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 $e(e,s,0);g(a.filePath),await $.rename(i,l),u=!0;try{await $.rename(s,i),d=!0}catch(e){throw await $.rename(l,i),u=!1,e}try{await $.rm(l,{recursive:!0,force:!0})}catch(e){c.warn(`The previous migration directory remains at ${l}: ${e instanceof Error?e.message:String(e)}`)}u=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!d&&u&&Y.existsSync(l)&&await $.rename(l,i)}}async function rebaseline(e){T(`tailordb migration`);let{config:t,plugins:n}=await R(e.configPath),r=K.dirname(t.path),i=zt(L(t,r),e.namespace),a=Er({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});j(i.migrationsDir,i.namespace);let o=N(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:`Run ${a} first.`});let l=jn(i.migrationsDir),u=N(i.migrationsDir,0)?.rebaseline?.historyId??null,d=nn([i])[i.namespace],f=n.length>0?new zr(n):void 0,{defineApplication:p}=await import(`../application-DBHaxmJE.mjs`),m=p({config:t,pluginManager:f});for(let e of m.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let h=m.tailorDBServices.find(e=>e.namespace===i.namespace);if(!h)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=qt(h.types,i.namespace),t=he(o,e.tables,i.namespace);if(rt(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(i.namespace)}:`),c.log(Ze(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:`Run ${a} first.`})},localSourceFiles=()=>[t.path,...xr(h.config,r)];assertLocalTypesReady();let g=ht(localSourceFiles()),{client:_,workspaceId:v}=await O({profile:e.profile,workspaceId:e.workspaceId}),b=[`--config`,t.path,...E({workspaceId:v,profile:e.profile})],x=Er({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...b]}),ee=Er({command:`tailor`,args:[`deploy`,...b]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await yn(_,D(v,`tailordb`,i.namespace)),a=r.number;if(a!==l){let e=a===null?`<unset>`:y(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${y(l)} 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 Se(_,v,[i],t,[ue(h)]),s=o[0];if(!s||s.remoteMigrationNumber!==l||s.hasDrift||s.checkpointMissingLocal)throw s?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(fe(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(u,`initial`),c.newline(),c.warn(`This will replace the migration history for ${s.bold(i.namespace)}.`),c.log(` Latest migration: ${y(l)}`),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 A.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(j(i.migrationsDir,i.namespace),nn([i])[i.namespace]!==d)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(ht(localSourceFiles())!==g)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let S={historyId:Me(),replacedHistoryId:u,replacedLatestMigration:l};await activateBaseline(i.migrationsDir,o,i.namespace,S);try{await ve(_,v,i.namespace,0,S.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:`Run ${x}, or run ${ee} with schema checks enabled after resolving the connection error.`,cause:e})}c.success(`Re-baselined ${s.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const La=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({...F,...C,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await M({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){T(`tailordb migration`);let t=tt(e.number),{config:n}=await R(e.configPath),r=K.dirname(n.path),i=L(n,r),a=zt(i,e.namespace),o=a.namespace;j(a.migrationsDir,o),ee(a.migrationsDir,t);let l=N(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await O({profile:e.profile,workspaceId:e.workspaceId}),f=D(d,`tailordb`,o),p=await yn(u,f),m=p.number,h=m??0,g=p.historyIdInvalid?`<invalid>`:p.historyId??`<unset>`,_=l??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${s.bold(o)}`),c.log(`Current migration: ${m===null?`<unset>`:s.bold(y(m))}`),c.log(`New migration: ${s.bold(y(t))}`),c.log(`Current migration history ID: ${s.bold(g)}`),c.log(`New migration history ID: ${s.bold(_)}`),c.newline(),t<h?(c.warn(`Setting migration number backwards (${y(h)} → ${y(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>h&&(c.warn(`Setting migration number forwards (${y(h)} → ${y(t)}) will skip migrations ${y(h+1)} to ${y(t)}.`),c.newline()),!e.yes){if(!await A.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await at(u,{trn:f,labels:{[ke]:le(t),...l?{[Vt]:l}:{}},remove:l?void 0:[Vt]}),c.success(`Migration checkpoint set to ${s.bold(y(t))} for namespace ${s.bold(o)}`)}const Ra=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({...F,...C,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 M({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 R(e.configPath),n=K.dirname(t.path),r=L(t,n);if(r.length===0)throw dn();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=ne(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n){if(e.type===`schema`){let t=g(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Wt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Or(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Dr(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 O({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=D(c,`tailordb`,e),d;try{d=await yn(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:y(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:y(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${s.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${s.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){T(`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 za=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({...F,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 hr(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 Jn(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 zr(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-DBHaxmJE.mjs`),l=a({config:n,pluginManager:i}),u=l.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of l.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,l.tailorDBServices,n.path),f=l.executorService??(d.length>0?(await import(`../service-DWMm-4Vm.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await f?.loadExecutors(),d.length>0&&await f?.loadPluginExecutorFiles([...d]);let p=/* @__PURE__ */ new Set;for(let e of Object.values(f?.executors??{}))de(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=N(t.migrationsDir);if(!h)return m;let g=qt(u.types,t.namespace),_=he(h,g.tables,t.namespace);if(!rt(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(t.namespace)}:`),c.log(Ze(_)),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){T(`tailordb migration`);let t=tt(e.number),n=await R(e.configPath),{config:r}=n,i=K.dirname(r.path),a=L(r,i),o=zt(a,e.namespace);j(o.migrationsDir,o.namespace);let l=ee(o.migrationsDir,t),u=N(o.migrationsDir,t);if(!u)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 f=await assertMigrationsReproduceLocalTypes(n,o),{client:p,workspaceId:m}=await O({profile:e.profile,workspaceId:e.workspaceId}),h=D(m,`tailordb`,o.namespace),g=await Ot(p,h),_=await fetchRemoteTypes(p,m,o.namespace),v=new Set(_.map(e=>e.name)),{creates:b,updates:x,deletes:S}=ut(u,v),te=await fetchRemoteGqlPermissions(p,m,o.namespace),C=new Set(te.map(e=>e.typeName)),w=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:d(t.permissions.gql)}]:[]),ne=new Set(w.map(e=>e.typeName)),re=te.filter(e=>!ne.has(e.typeName));if(c.newline(),c.info(`Namespace: ${s.bold(o.namespace)}`),c.log(` Current migration: ${g===null?`<unset>`:s.bold(y(g))}`),c.log(` Target migration: ${s.bold(y(t))}`),c.log(` Tables to create: ${s.bold(String(b.length))}`),c.log(` Tables to update: ${s.bold(String(x.length))}`),c.log(` Tables to delete: ${s.bold(String(S.length))}`),c.log(` GQL permissions to set: ${s.bold(String(w.length))}`),c.log(` GQL permissions to delete: ${s.bold(String(re.length))}`),c.newline(),b.length+x.length+S.length+w.length+re.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.`),S.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(),g!==null&&t<g?(c.warn(`Migrations ${y(t+1)}–${y(g)} 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()):g!==null&&t>g&&(c.warn(`Moving the migration label forwards (${y(g)} → ${y(t)}): migrate.ts scripts for migrations ${y(g+1)}–${y(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await A.confirm({message:`Continue and set migration label to ${y(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ie=Be(u,f),manifestFor=e=>{let t=ie.get(e);if(!t)throw wr(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ae=b.map(e=>manifestFor(e)),oe=x.map(e=>manifestFor(e));try{await Promise.all([...ae.map(e=>p.createTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e})),...oe.map(e=>p.updateTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e}))])}catch(e){Re(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(w.map(({typeName:e,permission:t})=>{let n={workspaceId:m,namespaceName:o.namespace,typeName:e,permission:t};return C.has(e)?p.updateTailorDBGQLPermission(n):p.createTailorDBGQLPermission(n)})),await Promise.all(re.map(e=>p.deleteTailorDBGQLPermission({workspaceId:m,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(S.map(e=>p.deleteTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbTypeName:e}))),await at(p,{trn:h,labels:{[ke]:le(t),...u.rebaseline?.historyId?{[Vt]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[Vt]}),c.success(`Synced namespace ${s.bold(o.namespace)} to migration ${s.bold(y(t))}.`),t<l&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${y(t+1)}–${y(l)} from the working tree.`))}const Ba=k({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...F,...C,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 M({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=>et(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 wr(`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)}-${ii(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=L(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(ue),o=(await Se(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 Ot(e.client,D(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 et(e.client,n,r.namespace);if(Te(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 cr(()=>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??sn(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 Je({configPath:e.configPath}),n=K.dirname(t.config.path),r=L(t.config,n);if(r.length===0)throw dn();for(let e of r)j(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await Ae({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(ue),s=await en({profile:e.profile}),c=await wt({profile:e.profile}),l=await fr(s,c),u=await rn({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 Se(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,x=[];for(let e of r){let t=await Ot(l,D(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=jn(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=N(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=N(e.migrationsDir,n);if(!i)throw U({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,i),t<n&&x.push(e.namespace)}if(x.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let ee=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:ee,targetSnapshots:b,pendingNamespaces:x,...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 Pt(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 Tt({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 ve(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=ue(e);return[e.namespace,n?.snapshot??Bn({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 me(e,l,K.dirname(r.loaded.config.path)),d=Ie({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 Gt({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 wr(`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 jt({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 it(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path)),u=await Gt({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,l=!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),l=!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:l,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){T(`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 Va=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({...F,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 M({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 ne(e)){if(t.type!==`diff`)continue;let n=Wt(t.path),s=oe(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(y).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=>` ${ct({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
88
|
+
`);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(y).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(y).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts.`,suggestion:`Review each ${_} 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 R(e.configPath),r=K.dirname(t.path),i=L(t,r);if(i.length===0)throw dn();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 zr(n):void 0,{defineApplication:s}=await import(`../application-DBHaxmJE.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();Wn({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(ue),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{j(t.migrationsDir,t.namespace),N(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,Dr(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await v(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await O({profile:e.profile,workspaceId:e.workspaceId});h=await Se(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: ${s.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${s.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${s.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${s.error(`changes not in migration files`)}`),c.log(` ${pe(e.diff)}`),c.log(Ze(e.diff))):c.log(` Local schema: ${s.error(`no migration snapshot found`)}`):c.log(` Local schema: ${s.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${s.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${s.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${y(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(c.log(` Remote schema: ${s.error(`remote migration ${y(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&c.log(` Fell behind before 'migration rebaseline' ran; must reach ${y(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(c.log(` Remote schema: ${s.error(`drift detected`)} (remote migration: ${y(n.remoteMigrationNumber)})`),c.log(Ct(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${s.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${s.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${s.dim(`skipped (no local snapshot for remote migration ${y(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${s.success(`OK`)} (remote migration: ${y(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${s.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${s.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=y(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&&Xe(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&nt(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(` ${ct({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){T(`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 Ha=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({...F,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})}}),Ua=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:Ve,rebaseline:La,script:zn,set:Ra,status:za,sync:Ba,test:Va,validate:Ha}}),Wa=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:De,migration:Ua}}),Ga=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-8xznUrPU.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),Ka=k({name:`current`,description:`Show current user.`,args:q.strictObject({profile:B.profile}),run:async e=>{let t=await P(),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?I(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`,...E({profile:n})]}});if(!pt(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`,...E({profile:n})]}});if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?In(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return In(e,n.user,I(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 qa=k({name:`list`,description:`List all users.`,args:q.strictObject({profile:B.profile}),run:async e=>{let t=await P(),n=c.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){c.info(H`
|
|
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){switch(e){case n.PAT_SCOPE_READ:return`read`;case n.PAT_SCOPE_WRITE:return`write`;default:return`unknown`}}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:
|
|
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){switch(e){case n.PAT_SCOPE_READ:return`read`;case n.PAT_SCOPE_WRITE:return`write`;default:return`unknown`}}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:We(e.createdAt),lastUsedAt:We(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[n.PAT_SCOPE_READ,n.PAT_SCOPE_WRITE]:[n.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(H`
|
|
92
92
|
Personal access token ${r} successfully.
|
|
93
93
|
|
|
94
94
|
name: ${e}
|
|
@@ -96,10 +96,10 @@ Error:`));let e=formatErrorWithSourcemap(b.error,m,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 en({profile:e});return await fr(t)}const Ja=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:B.profile}),run:async e=>{await M({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 wr(`Failed to create personal access token`);c.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),Ya=k({name:`delete`,description:`Delete a personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),profile:B.profile}),run:async e=>{await M({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),c.success(`Personal access token "${e.name}" deleted successfully.`)}}),Xa=k({name:`list`,description:`List all personal access tokens.`,args:q.strictObject({...Le(),profile:B.profile}),run:async e=>{let t=c.jsonMode,n=await createPatOperatorClient(e.profile),r=He(e.order),i=await V(async(e,t)=>{let{personalAccessTokens:i,nextPageToken:a}=await n.listPersonalAccessTokens({pageToken:e,pageSize:t,pageDirection:r});return[i,a]},{limit:e.limit});if(i.length===0&&(c.info(H`
|
|
100
100
|
No personal access tokens found.
|
|
101
101
|
Please create a token using 'tailor user pat create' command.
|
|
102
|
-
`),!t))return;let a=i.map(transformPersonalAccessToken);c.out(a,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:x(e)}})}}),
|
|
102
|
+
`),!t))return;let a=i.map(transformPersonalAccessToken);c.out(a,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:x(e)}})}}),Za=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:B.profile}),run:async e=>{await M({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 wr(`Failed to create personal access token`);c.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),Qa=G({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:Xa,create:Ja,delete:Ya,update:Za},defaultSubCommand:`list`}),$a=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:B.profile}),run:async e=>{let t=await P(),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?I(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=En(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`,...E({profile:n})]}});r?r.user=a:t.current_user=a,z(t),c.success(`Current user set to "${a}" successfully.`)}}),eo=G({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:Ka,list:qa,switch:$a,pat:Qa},defaultSubCommand:`list`}),to=G({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:Ut,get:be,start:Ce,wait:Ge,executions:ot,resume:te},defaultSubCommand:`list`}),no=G({name:`app`,description:`Manage workspace applications`,subCommands:{health:kn,list:Ue},defaultSubCommand:`list`}),locationIdsArg=()=>q.array(q.union([q.literal(``),q.uuid()])).optional(),ro=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=We(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=dr(),i=await Promise.all(t.map(async t=>({workspace:t,result:await r(()=>qe(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 V(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 io=[{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`}],ao=k({name:`prune`,description:`Delete stale temporary workspaces, by name and age or by the expiry each recorded at creation.`,notes:H`
|
|
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(b.error,m,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(w.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(w.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(ro.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(h.optional(),{description:`Workspace profile used for authentication and Platform selection`,env:`TAILOR_PLATFORM_PROFILE`}),...C}),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:Pe(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 M({profile:e.profile});let l=await en({profile:e.profile}),u=await wt({profile:e.profile}),d=await fr(l,u),f=/* @__PURE__ */ new Date,p=selectPruneCandidates(await fetchAllWorkspaces(d),s,f),m={dryRun:e[`dry-run`],candidates:[],deleted:[],failed:[],skipped:{excluded:[],deleteProtection:[],unknownAge:[],notExpired:[],noExpiry:[],unreadableExpiry:[],expiryChanged:[],changed:[]}};if(e.expired){let e=await partitionByExpiry(d,p.candidates,f);p.candidates=e.expired;for(let t of e.pending)m.skipped.notExpired.push(t.name);for(let t of e.unset)m.skipped.noExpiry.push(t.name);for(let{workspace:t,reason:n}of e.unreadable)m.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 io)for(let r of p[t])m.skipped[e].push(r.name),c.warn(`Keeping ${r.name} (${r.id}): ${n}.`);if(p.tooYoung.length>0&&c.info(`${p.tooYoung.length} matching workspace(s) are younger than ${e[`older-than`]} and were kept.`),p.candidates.length===0){c.info(`No stale workspaces matched.`),c.jsonMode&&c.out(m);return}let h=e.limit>0&&p.candidates.length>e.limit;if(h&&!e[`dry-run`])throw U({code:`PRUNE_LIMIT_EXCEEDED`,message:`${p.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(m.candidates=await Ln(d,p.candidates),c.jsonMode||c.out(m.candidates,{display:{name:yt,folderName:null,organizationId:null,folderId:null,updatedAt:null}}),e[`dry-run`]){h&&c.warn(`${m.candidates.length} workspaces matched, but --limit is ${e.limit}: a real run would abort without deleting anything.`),c.info(`Dry run: ${m.candidates.length} workspace(s) would be deleted.`),c.jsonMode&&c.out(m);return}if(!e.yes&&!await A.confirm({message:`Delete these ${m.candidates.length} workspace(s)? They can be restored with "tailor workspace restore" for a limited time.`,default:!1})){c.info(`Prune cancelled. No workspaces were deleted.`),c.jsonMode&&c.out(m);return}let g=/* @__PURE__ */ new Set;for(let t of m.candidates){let n=Dn(t);try{let{workspace:r}=await d.getWorkspace({workspaceId:t.id}),i=r?staleCandidateReason(r,s):void 0;if(i){m.skipped.changed.push(t.name),c.warn(`Keeping ${n} (${t.id}): ${i}.`);continue}if(e.expired){let e=await qe(d,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`){m.skipped.expiryChanged.push(n),c.info(`Skipped ${n} (${t.id}): its recorded expiry no longer selects it.`);continue}}g.add(t.id),await d.deleteWorkspace({workspaceId:t.id}),m.deleted.push(t),c.success(`Deleted ${n} (${t.id}).`)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){g.add(t.id),m.deleted.push(t),c.info(`${n} (${t.id}) was already deleted.`);continue}let r=e instanceof Error?e.message:String(e);m.failed.push({workspace:t,error:r}),c.error(`Failed to delete ${n} (${t.id}): ${r}`)}}let _=await _t(g);if(_.length>0&&c.info(`Removed ${_.length} local profile(s) that pointed at deleted workspaces: ${_.join(`, `)}.`),c.jsonMode&&c.out(m),c.success(`Deleted ${m.deleted.length} workspace(s).`),m.failed.length>0)throw U({code:`PRUNE_INCOMPLETE`,message:`Failed to delete ${m.failed.length} workspace(s).`,suggestion:`Fix the reported errors and run the command again; deleted workspaces are not retried.`})}}),oo=q.object({workspaceId:q.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:q.string().optional()});async function clearWorkspaceTtl(e){let t=Bt(oo,e),{client:n,workspaceId:r}=await O({profile:t.profile,workspaceId:t.workspaceId});await An(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({...B}),run:async e=>{await M({profile:e.profile}),await clearWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile}),c.success(`Workspace records no prune expiry.`)}}),co=q.object({workspaceId:q.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:q.string().optional(),ttl:w});async function setWorkspaceTtl(e){let t=Bt(co,e),{client:n,workspaceId:r}=await O({profile:t.profile,workspaceId:t.workspaceId}),i=new Date(Date.now()+Pe(t.ttl));return await ae(n,r,i),i}const lo=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({...B,ttl:W(w,{description:`Time from now until the workspace becomes prunable, such as 30m, 24h, or 7d`})}),run:async e=>{await M({profile:e.profile});let t=await setWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile,ttl:e.ttl});c.success(`Workspace becomes prunable at ${t.toISOString()}.`)}}),uo=G({name:`ttl`,description:`Manage when a workspace becomes prunable.`,subCommands:{set:lo,clear:so},async run(){await b(uo,[`--help`])}}),fo=G({name:`user`,description:`Manage workspace users`,subCommands:{invite:kt,list:xn,remove:xt,update:$t},defaultSubCommand:`list`}),po=G({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:no,create:Ft,delete:Tn,get:Mt,list:an,prune:ao,restore:Yt,ttl:uo,user:fo},defaultSubCommand:`list`});await _n(new URL(`./ts-hook.mjs`,import.meta.url)),Rr();const mo=await jr(),ho=Object.keys(mo.bin??{})[0]||`tailor`,go=mo.name??`@tailor-platform/sdk`,_o=await Xr(import.meta.url),vo=Yr(Jr(_o),`agent-skills`);function defaultSkillsRunToAdd(e){let{run:t,...n}=e;return{...n,defaultSubCommand:`add`}}const yo=qr(G({name:ho,description:mo.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${ho}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
|
|
117
|
+
Run \`${ho} 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:Ci,auth:Ei,authconnection:Ni,crashreport:Ii,deploy:Li,executor:Ri,function:Ji,generate:Yi,init:Xi,login:$i,logout:ea,machineuser:ta,oauth2client:na,open:ra,organization:aa,plugin:ua,profile:ha,query:ft,remove:_e,secret:Oa,show:xe,staticwebsite:Fa,tailordb:Wa,upgrade:Ga,user:eo,workflow:to,workspace:po}}),{sourceDir:vo,package:go,mode:`copy`,descriptionAppend:!1,globalArgs:q.object(Ke),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.`}}),bo=Kr({...yo,subCommands:{...yo.subCommands,skills:defaultSkillsRunToAdd(yo.subCommands.skills)}});Wr(bo,{version:mo.version,globalArgs:q.object(Ke),displayErrors:!1,onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:ho,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){let t;if(c.jsonMode?c.log(S(e,{includeStack:c.verbose})):Or(e)?(c.log(e.format()),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`)):e instanceof Error?(c.error(e.message),t=lr(e).suggestion??Tr(e),t&&c.log(` ${s.info(`Suggestion:`)} ${t}`),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`)):c.error(`Unknown error: ${e}`),Xt(e,{jsonMode:c.jsonMode,suggestion:t}),!Or(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-BfOkOFgc.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t()}});export{bo as mainCommand};
|
|
119
119
|
//# sourceMappingURL=main.mjs.map
|